useFieldSecurity.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { computed, type Ref, type WritableComputedRef } from 'vue'
  3. import {
  4. EnumSecurityStateType,
  5. type FieldSecurityContext,
  6. type SecurityOption,
  7. type SecurityValue,
  8. } from './types.ts'
  9. import type { FormFieldContext } from '../../types/field.ts'
  10. export const useFieldSecurity = (
  11. context: Ref<FormFieldContext<FieldSecurityContext>>,
  12. localValue: WritableComputedRef<SecurityValue>,
  13. ) => {
  14. const securityMethods = computed(() => {
  15. return Object.keys(context.value.securityAllowed || {}).sort((a) => {
  16. if (a === EnumSecurityStateType.Pgp) return -1
  17. if (a === EnumSecurityStateType.Smime) return 1
  18. return 0
  19. }) as EnumSecurityStateType[]
  20. })
  21. const previewMethod = computed(
  22. () =>
  23. localValue.value?.method ??
  24. // smime should have priority
  25. (securityMethods.value.find(
  26. (value) => value === EnumSecurityStateType.Smime,
  27. ) ||
  28. securityMethods.value[0]),
  29. )
  30. const isCurrentSecurityOption = (option: SecurityOption) =>
  31. !!localValue.value?.options.includes(option)
  32. const isSecurityOptionDisabled = (option: SecurityOption) =>
  33. context.value.disabled ||
  34. !context.value.securityAllowed?.[previewMethod.value]?.includes(option)
  35. const defaultOptions = (method: EnumSecurityStateType) =>
  36. context.value.securityDefaultOptions?.[method] || []
  37. const filterOptions = (
  38. method: EnumSecurityStateType,
  39. options: SecurityOption[],
  40. ) => {
  41. return options
  42. .filter((option) =>
  43. context.value.securityAllowed?.[method]?.includes(option),
  44. )
  45. .sort()
  46. }
  47. const changeSecurityState = (method: EnumSecurityStateType) => {
  48. // Reset the default behavior of the chosen method and remove unsupported options.
  49. const newOptions = filterOptions(method, defaultOptions(method))
  50. localValue.value = {
  51. method,
  52. options: newOptions,
  53. }
  54. }
  55. return {
  56. securityMethods,
  57. previewMethod,
  58. isCurrentSecurityOption,
  59. isSecurityOptionDisabled,
  60. changeSecurityState,
  61. }
  62. }