@rytass/bpm-core-react 0.17.5 → 0.17.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +1 -1
  3. package/dist/chunks/{FormBuilderView-aBcA-_tt.cjs → FormBuilderView-CUOyS07f.cjs} +2 -2
  4. package/dist/chunks/{FormBuilderView-aBcA-_tt.cjs.map → FormBuilderView-CUOyS07f.cjs.map} +1 -1
  5. package/dist/chunks/{FormBuilderView-BYL42M0d.js → FormBuilderView-ClLnQ1e_.js} +2 -2
  6. package/dist/chunks/{FormBuilderView-BYL42M0d.js.map → FormBuilderView-ClLnQ1e_.js.map} +1 -1
  7. package/dist/chunks/{FormRendererView-cZGOOjU5.js → FormRendererView-BsTwZkqU.js} +207 -198
  8. package/dist/chunks/FormRendererView-BsTwZkqU.js.map +1 -0
  9. package/dist/chunks/FormRendererView-GpsE03np.cjs +4 -0
  10. package/dist/chunks/FormRendererView-GpsE03np.cjs.map +1 -0
  11. package/dist/chunks/approver-filled-form-D1DmqDVP.cjs +2 -0
  12. package/dist/chunks/approver-filled-form-D1DmqDVP.cjs.map +1 -0
  13. package/dist/chunks/approver-filled-form-DuQGPtNB.js +95 -0
  14. package/dist/chunks/approver-filled-form-DuQGPtNB.js.map +1 -0
  15. package/dist/chunks/{compose-DOEaPfEC.cjs → compose-DjEJi5Dv.cjs} +2 -2
  16. package/dist/chunks/{compose-DOEaPfEC.cjs.map → compose-DjEJi5Dv.cjs.map} +1 -1
  17. package/dist/chunks/{compose-v1Vcw9hE.js → compose-WekGZj74.js} +4 -4
  18. package/dist/chunks/{compose-v1Vcw9hE.js.map → compose-WekGZj74.js.map} +1 -1
  19. package/dist/chunks/{designer-DBBrktom.js → designer-D87ILhjz.js} +1664 -1182
  20. package/dist/chunks/designer-D87ILhjz.js.map +1 -0
  21. package/dist/chunks/designer-DESS0CMl.cjs +65 -0
  22. package/dist/chunks/designer-DESS0CMl.cjs.map +1 -0
  23. package/dist/chunks/detail-D49NuNCn.cjs +2 -0
  24. package/dist/chunks/detail-D49NuNCn.cjs.map +1 -0
  25. package/dist/chunks/{detail-B_bSg31B.js → detail-URwxkcro.js} +1036 -847
  26. package/dist/chunks/detail-URwxkcro.js.map +1 -0
  27. package/dist/chunks/{providers-H_vPRsSN.js → providers-B_d5tbCL.js} +178 -167
  28. package/dist/chunks/providers-B_d5tbCL.js.map +1 -0
  29. package/dist/chunks/providers-chuJvMgv.cjs +2 -0
  30. package/dist/chunks/providers-chuJvMgv.cjs.map +1 -0
  31. package/dist/index.cjs +1 -1
  32. package/dist/index.js +1 -1
  33. package/dist/next/index.cjs +1 -1
  34. package/dist/next/index.js +1 -1
  35. package/dist/next/workflow-chat-route.cjs +1 -0
  36. package/dist/next/workflow-chat-route.cjs.map +1 -1
  37. package/dist/next/workflow-chat-route.d.cts +1 -1
  38. package/dist/next/workflow-chat-route.d.ts +1 -1
  39. package/dist/next/workflow-chat-route.js +1 -1
  40. package/dist/next/workflow-chat-route.js.map +1 -1
  41. package/dist/pages/instances/detail/index.cjs +1 -1
  42. package/dist/pages/instances/detail/index.js +1 -1
  43. package/dist/pages/templates/compose/index.cjs +1 -1
  44. package/dist/pages/templates/compose/index.js +1 -1
  45. package/dist/pages/templates/designer/index.cjs +1 -1
  46. package/dist/pages/templates/designer/index.js +1 -1
  47. package/dist/views/forms/builder/index.cjs +1 -1
  48. package/dist/views/forms/builder/index.js +1 -1
  49. package/dist/views/forms/renderer/FormRendererView.d.cts +16 -1
  50. package/dist/views/forms/renderer/FormRendererView.d.ts +16 -1
  51. package/dist/views/forms/renderer/index.cjs +1 -1
  52. package/dist/views/forms/renderer/index.js +1 -1
  53. package/dist/views/inbox/index.cjs +1 -1
  54. package/dist/views/inbox/index.cjs.map +1 -1
  55. package/dist/views/inbox/index.js +109 -99
  56. package/dist/views/inbox/index.js.map +1 -1
  57. package/dist/views/instances/approver-filled-form.d.cts +76 -0
  58. package/dist/views/instances/approver-filled-form.d.ts +76 -0
  59. package/dist/views/instances/detail/index.cjs +1 -1
  60. package/dist/views/instances/detail/index.js +1 -1
  61. package/dist/views/instances/detail/sections/InstanceFormSection.d.cts +30 -2
  62. package/dist/views/instances/detail/sections/InstanceFormSection.d.ts +30 -2
  63. package/dist/views/instances/detail/sections/InstanceHistorySection.d.cts +4 -1
  64. package/dist/views/instances/detail/sections/InstanceHistorySection.d.ts +4 -1
  65. package/dist/views/instances/detail/sections/InstanceTasksSection.d.cts +21 -0
  66. package/dist/views/instances/detail/sections/InstanceTasksSection.d.ts +21 -0
  67. package/dist/views/instances/detail/sections/container-helpers.d.cts +1 -1
  68. package/dist/views/instances/detail/sections/container-helpers.d.ts +1 -1
  69. package/dist/views/instances/detail/sections/shared.d.cts +11 -2
  70. package/dist/views/instances/detail/sections/shared.d.ts +11 -2
  71. package/dist/views/instances/new/index.cjs +1 -1
  72. package/dist/views/instances/new/index.cjs.map +1 -1
  73. package/dist/views/instances/new/index.js +88 -87
  74. package/dist/views/instances/new/index.js.map +1 -1
  75. package/dist/views/instances/viewer-field-access.d.cts +22 -0
  76. package/dist/views/instances/viewer-field-access.d.ts +22 -0
  77. package/dist/views/templates/compose/index.cjs +1 -1
  78. package/dist/views/templates/compose/index.js +1 -1
  79. package/dist/views/templates/designer/field-access-matrix/FieldAccessMatrixDrawer.d.cts +33 -0
  80. package/dist/views/templates/designer/field-access-matrix/FieldAccessMatrixDrawer.d.ts +33 -0
  81. package/dist/views/templates/designer/field-access-matrix/FieldAccessNodeSection.d.cts +20 -0
  82. package/dist/views/templates/designer/field-access-matrix/FieldAccessNodeSection.d.ts +20 -0
  83. package/dist/views/templates/designer/field-access-matrix/field-access-copy.d.cts +22 -0
  84. package/dist/views/templates/designer/field-access-matrix/field-access-copy.d.ts +22 -0
  85. package/dist/views/templates/designer/index.cjs +1 -1
  86. package/dist/views/templates/designer/index.js +1 -1
  87. package/package.json +3 -3
  88. package/dist/chunks/FormRendererView-DRFi_IH7.cjs +0 -4
  89. package/dist/chunks/FormRendererView-DRFi_IH7.cjs.map +0 -1
  90. package/dist/chunks/FormRendererView-cZGOOjU5.js.map +0 -1
  91. package/dist/chunks/designer-CTXMqCD2.cjs +0 -65
  92. package/dist/chunks/designer-CTXMqCD2.cjs.map +0 -1
  93. package/dist/chunks/designer-DBBrktom.js.map +0 -1
  94. package/dist/chunks/detail-BQSVgVlO.cjs +0 -2
  95. package/dist/chunks/detail-BQSVgVlO.cjs.map +0 -1
  96. package/dist/chunks/detail-B_bSg31B.js.map +0 -1
  97. package/dist/chunks/providers-DP7b0TMN.cjs +0 -2
  98. package/dist/chunks/providers-DP7b0TMN.cjs.map +0 -1
  99. package/dist/chunks/providers-H_vPRsSN.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"FormRendererView-cZGOOjU5.js","names":["BPMFormField","EMPTY_FIELD_STATE","NO_INVALID_VALUES","MIN_SCROLLABLE_OPTION_COUNT","RECOVERABLE_ERROR_CODES","useFormDataSourceField","dynamicField","isFormDataSourceFieldDefinition","input","queryFieldKey","snapshot","dynamicFieldSignature","snapshotSignature","snapshotOptions","useMemo","formDataSignature","initialFormDataSignature","schemaSignature","uiSchemaSignature","contextKind","contextInstanceId","contextTemplateId","rowValuesSignature","initialRowValuesSignature","currentValue","currentValueSignature","readFormDataSourceValueSignature","selectedValues","readFormDataSourceSelectedValues","hasValue","dataSourceRefreshSignature","binding","effectiveContext","valueChanged","bindingsChanged","isStale","needsResolve","quiescentStatus","readQuiescentFormDataSourceStatus","autoQueries","pendingQueryStatus","readPendingQueryStatus","readMissingFormDataSourceDependencies","remoteOptions","setRemoteOptions","useState","searchText","setSearchText","nextCursor","setNextCursor","resolution","setResolution","status","setStatus","error","setError","loadedOptionCount","useRef","requestSequence","resolveSequence","optionsAbort","resolveAbort","lastRequest","queryFormData","readDefinedValues","queryRowValues","mergedOptions","mergeFormDataSourceOptions","currentResolution","resolvePending","invalidValues","readInvalidFormDataSourceValues","loadOptions","useCallback","requestId","nextSearchTextToLoad","controller","previewFormFieldOptions","readFormFieldOptions","isSupersededRequest","selectedOptions","readSelectedFormDataSourceOptions","currentOptions","cursor","result","loadOptionsRef","message","readFormDataSourceErrorMessage","requestError","code","readFormDataSourceErrorCode","readFailedQueryStatus","runResolve","signature","previewResolveFormFieldOptions","resolveFormFieldOptions","runResolveRef","useEffect","currentCursor","currentSearchText","currentError","onSearch","onReachBottom","retry","readFormDataSourceExposedStatus","readFormDataSourceFieldStatusMessage","state","isFormDataSourceFieldSubmissionBlocked","readFormDataSourceSubmissionBlockMessage","blocked","states","readMissingFormDataSourceOptionValues","waiting","recoverable","sequence","values","key","value","defined","UNICODE_WHITESPACE_PATTERN","hasUnsafeCharacter","codePoint","character","ABSOLUTE_HTTP_PATTERN","resolveFormFieldLink","isSafeSiteRelativePath","isSafeAbsoluteHttpUrl","PLACEHOLDER_BASE","resolved","url","resolveMemberProfilesPerIdOnFailure","maxPerIdRequests","limits","concurrency","resolveMembers","memberIds","askedIds","settled","settleWithConcurrency","memberId","index","excludeFailedMemberIds","failedMemberIds","results","nextIndex","worker","items","run","UNKNOWN_MEMBER_NAME","readMemberFieldOption","member","formatMemberLabel","readUnresolvedMemberFieldOption","mergeMemberFieldOptions","resolvedById","nextOptions","option","currentIds","addedOptions","candidate","upgradedOptions","readUnresolvedMemberIds","knownIds","knownOptions","readFormMemberIds","readSelectedMemberFieldOptions","readMemberFieldValue","selected","multiple","MemberFieldControl","setKnownOptions","searchResults","setSearchResults","loading","setLoading","latestSearchRef","givenUpIdsRef","unresolvedKey","cancelled","profiles","placeholders","skippedIds","placeholder","current","handleSearch","options","searchMembers","commonProps","readonly","open","AutoComplete","onChange","nextOption","FORM_RENDERER_GRID_STYLE","FORM_RENDERER_EMPTY_STYLE","FORM_RENDERER_FIELD_STYLE","TEXTAREA_STYLE","applyFullWidthTextareaHost","element","FormRenderer","internalValues","setInternalValues","buildFormRendererValues","schema","valuesRef","visibleFields","readVisibleFormRendererFields","uiSchema","currentValues","updateValue","nextValues","fieldKey","nextValue","singleColumn","FormRendererField","errors","field","readFieldColumnSpan","isTableFieldDefinition","Typography","emptyText","required","isFormRendererFieldRequired","fields","fieldReadonly","isFormRendererFieldReadonly","dataSourceState","dataSourceContext","dataSourceInitialValues","dataSourceStatusMessage","dataSourceStateSignature","onDataSourceStateChange","FormTableField","renderControl","onUploadAttachment","DATA_SOURCE_FEEDBACK_STYLE","Button","EXTERNAL_LINK_CUE","EXTERNAL_LINK_TITLE","LINK_STYLE","TABLE_FIELD_STYLE","TABLE_FIELD_ACTIONS_STYLE","TABLE_SCROLLER_STYLE","TABLE_COLUMN_MIN_WIDTH","TABLE_ACTIONS_COLUMN_WIDTH","TABLE_CELL_STYLE","rows","readFormTableRows","bounds","readFormTableRowBounds","rowIdSequenceRef","rowIds","setRowIds","createRowId","commitRows","nextRows","handleAddRow","createFormTableRow","handleRemoveRow","rowIndex","handleCellChange","readNextTableRow","row","columnKey","cellValue","dataSource","columns","column","FormTableCell","readFormTableCellPath","readInitialTableRow","actions","TrashIcon","Table","PlusIcon","readTableCellValue","rowValues","initialRowValues","path","statusMessage","stateSignature","sequenceRef","isFormTableCellValue","renderDynamicOptionControl","size","renderStaticControl","link","Textarea","event","readStringValue","Toggle","isFormStaticOptionFieldDefinition","readFieldOptionAsSelectOption","Select","readStringArrayValue","readSelectOption","Upload","files","file","DatePicker","formatDatePickerValue","readInputPlaceholder","readDatePickerValue","DateTimePicker","formatDateTimePickerValue","Input","clampOptionalNumber","parseOptionalNumberInput","readNumberInputValue","waitingForDependencies","interactiveSearch","optionControlDisabled","autoCompleteDisabled","readFormFieldSelectionMode","RadioGroup","CheckboxGroup","item","type"],"sources":["../../src/views/forms/renderer/form-data-source-field.ts","../../src/views/forms/renderer/form-field-link.ts","../../src/lib/member-profile-resolution.ts","../../src/views/forms/renderer/member-field-options.ts","../../src/views/forms/renderer/member-field.tsx","../../src/views/forms/renderer/FormRendererView.tsx"],"sourcesContent":["'use client';\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport {\n FormDataSourceValueSnapshots,\n FormDefinitionSchema,\n FormFieldDefinition,\n FormFieldOption,\n FormFieldValue,\n FormUiSchema,\n isFormDataSourceFieldDefinition,\n} from '@rytass/bpm-core-shared/form';\nimport {\n FormDataSourceErrorCode,\n FormDataSourceFieldStatus,\n FormRendererValues,\n mergeFormDataSourceOptions,\n previewResolveFormFieldOptions,\n readFormDataSourceErrorCode,\n readFormDataSourceErrorMessage,\n readMissingFormDataSourceDependencies,\n readMissingFormDataSourceOptionValues,\n previewFormFieldOptions,\n readFormDataSourceSelectedValues,\n readFormDataSourceValueSignature,\n readSelectedFormDataSourceOptions,\n readFormFieldOptions,\n resolveFormFieldOptions,\n} from '@rytass/bpm-core-client/form';\n\nexport type FormRendererDataSourceContext =\n | { readonly kind: 'preview' }\n | {\n readonly instanceId?: string | null;\n readonly kind: 'runtime';\n readonly templateId?: string | null;\n };\n\nexport interface FormDataSourceFieldState {\n /**\n * False when nothing can be re-requested — a read-only or context-less field\n * has no query to retry, so the view must not offer a dead retry action.\n */\n readonly canRetry: boolean;\n readonly error: string | null;\n readonly hasValue: boolean;\n readonly hasNextPage: boolean;\n readonly invalidValues: readonly string[];\n readonly onReachBottom: () => void;\n readonly onSearch: (searchText: string) => void;\n readonly options: readonly FormFieldOption[];\n readonly retry: () => void;\n readonly status: FormDataSourceFieldStatus;\n}\n\n/**\n * What makes a table cell different from a top-level field: it is addressed by\n * a schema path, snapshotted under an instance path, and its `ROW_FIELD`\n * bindings read from its own row rather than the form (ADR 16 §3.3, §3.5).\n */\nexport interface UseFormDataSourceFieldRow {\n /** The row as it was loaded, so a returned case can tell what changed. */\n readonly initialValues?: FormRendererValues;\n readonly values: FormRendererValues;\n}\n\nexport interface UseFormDataSourceFieldInput {\n readonly context?: FormRendererDataSourceContext;\n readonly field: FormFieldDefinition;\n /** Schema path used to address the field; defaults to its own key. */\n readonly fieldPath?: string;\n readonly formData: FormRendererValues;\n readonly initialFormData?: FormRendererValues;\n readonly initialValue?: FormFieldValue | undefined;\n readonly optionSnapshots?: FormDataSourceValueSnapshots;\n readonly readonly: boolean;\n /** Set only for a table cell. */\n readonly row?: UseFormDataSourceFieldRow;\n readonly schema: FormDefinitionSchema;\n /** Snapshot map key; defaults to the field key. */\n readonly snapshotKey?: string;\n readonly uiSchema: FormUiSchema;\n}\n\ninterface FormDataSourceResolution {\n readonly signature: string;\n readonly unresolvedValues: readonly string[];\n}\n\nconst EMPTY_FIELD_STATE: FormDataSourceFieldState = {\n canRetry: false,\n error: null,\n hasValue: false,\n hasNextPage: false,\n invalidValues: [],\n onReachBottom: (): void => undefined,\n onSearch: (): void => undefined,\n options: [],\n retry: (): void => undefined,\n status: 'IDLE',\n};\n\nconst NO_INVALID_VALUES: readonly string[] = [];\n\n/**\n * A dropdown only fires `onReachBottom` once its content overflows. A source\n * whose first page is smaller than the menu is therefore unreachable past page\n * one — `demo.cost-centers` serves 3 at a time, which fits exactly, so nothing\n * ever scrolls and the remaining options cannot be selected at all. Keep\n * pulling pages until there are enough rows to scroll, or the source runs out.\n */\nconst MIN_SCROLLABLE_OPTION_COUNT = 10;\n\n/**\n * Failures the filler can clear on their own by typing differently. They are\n * reported as an inline hint and never turn the field unavailable, because a\n * short search string says nothing about the validity of an existing value.\n */\nconst RECOVERABLE_ERROR_CODES: readonly FormDataSourceErrorCode[] = [\n 'FORM_DATA_SOURCE_SEARCH_NOT_SUPPORTED',\n 'FORM_DATA_SOURCE_SEARCH_TOO_SHORT',\n];\n\nexport function useFormDataSourceField(\n input: UseFormDataSourceFieldInput,\n): FormDataSourceFieldState {\n const dynamicField = isFormDataSourceFieldDefinition(input.field)\n ? input.field\n : null;\n const queryFieldKey = input.fieldPath ?? dynamicField?.fieldKey ?? '';\n const snapshot = dynamicField\n ? input.optionSnapshots?.[input.snapshotKey ?? dynamicField.fieldKey]\n : undefined;\n // The field object is rebuilt on every parent render, so depending on its\n // identity re-ran the load effect three extra times per change — each request\n // aborting the last. Depend on what actually decides the query instead.\n const dynamicFieldSignature = dynamicField\n ? JSON.stringify({\n dataSource: dynamicField.dataSource,\n fieldKey: dynamicField.fieldKey,\n type: dynamicField.type,\n })\n : '';\n const snapshotSignature = JSON.stringify(snapshot ?? null);\n const snapshotOptions = useMemo(\n (): readonly FormFieldOption[] => snapshot?.options ?? [],\n [snapshotSignature],\n );\n const formDataSignature = JSON.stringify(input.formData);\n const initialFormDataSignature = JSON.stringify(input.initialFormData ?? {});\n const schemaSignature = JSON.stringify(input.schema);\n const uiSchemaSignature = JSON.stringify(input.uiSchema);\n const contextKind = input.context?.kind;\n const contextInstanceId =\n input.context?.kind === 'runtime' ? input.context.instanceId : undefined;\n const contextTemplateId =\n input.context?.kind === 'runtime' ? input.context.templateId : undefined;\n const rowValuesSignature = JSON.stringify(input.row?.values ?? null);\n const initialRowValuesSignature = JSON.stringify(\n input.row?.initialValues ?? null,\n );\n // A cell's value lives on its row, never on the form data — a top-level field\n // may even share the column's key.\n const currentValue = dynamicField\n ? input.row\n ? input.row.values[dynamicField.fieldKey]\n : input.formData[dynamicField.fieldKey]\n : undefined;\n const currentValueSignature = readFormDataSourceValueSignature(currentValue);\n const selectedValues = useMemo(\n (): readonly string[] => readFormDataSourceSelectedValues(currentValue),\n [currentValueSignature],\n );\n const hasValue = selectedValues.length > 0;\n const dataSourceRefreshSignature = dynamicField\n ? JSON.stringify({\n bindings: dynamicField.dataSource.bindings.map((binding) =>\n binding.from.kind === 'FIELD'\n ? {\n fieldKey: binding.from.fieldKey,\n value: input.formData[binding.from.fieldKey],\n }\n : binding.from.kind === 'CONSTANT'\n ? { value: binding.from.value }\n : {\n columnKey: binding.from.columnKey,\n value: input.row?.values[binding.from.columnKey],\n },\n ),\n value:\n typeof input.initialFormData !== 'undefined' ||\n typeof input.initialValue !== 'undefined'\n ? currentValue\n : undefined,\n })\n : '';\n const effectiveContext = useMemo(\n (): FormRendererDataSourceContext | undefined => {\n if (contextKind === 'preview') {\n return { kind: 'preview' };\n }\n\n if (contextKind === 'runtime' && !input.readonly) {\n return {\n instanceId: contextInstanceId,\n kind: 'runtime',\n templateId: contextTemplateId,\n };\n }\n\n return undefined;\n },\n [\n contextInstanceId,\n contextKind,\n contextTemplateId,\n input.readonly,\n ],\n );\n const valueChanged = dynamicField\n ? (typeof input.initialFormData !== 'undefined' ||\n typeof input.initialValue !== 'undefined') &&\n readFormDataSourceValueSignature(input.initialValue) !==\n currentValueSignature\n : false;\n const bindingsChanged = dynamicField\n ? typeof input.initialFormData !== 'undefined' &&\n dynamicField.dataSource.bindings.some((binding) => {\n if (binding.from.kind === 'FIELD') {\n return (\n readFormDataSourceValueSignature(\n input.initialFormData?.[binding.from.fieldKey],\n ) !==\n readFormDataSourceValueSignature(\n input.formData[binding.from.fieldKey],\n )\n );\n }\n\n if (binding.from.kind === 'ROW_FIELD' && input.row?.initialValues) {\n return (\n readFormDataSourceValueSignature(\n input.row.initialValues[binding.from.columnKey],\n ) !==\n readFormDataSourceValueSignature(\n input.row.values[binding.from.columnKey],\n )\n );\n }\n\n return false;\n })\n : false;\n const isStale = Boolean(\n (snapshot || hasValue) && (valueChanged || bindingsChanged),\n );\n // A stale field with a value is only trustworthy once the host has resolved\n // it: display options may still carry the value through the snapshot merge.\n const needsResolve = Boolean(dynamicField && effectiveContext && isStale && hasValue);\n const quiescentStatus = readQuiescentFormDataSourceStatus({\n hasSnapshot: Boolean(snapshot),\n hasValue,\n isStale,\n readonly: input.readonly,\n });\n // AutoComplete only queries on search, so every other control is the one that\n // loads by itself as soon as it has a context.\n const autoQueries = Boolean(\n dynamicField && effectiveContext && dynamicField.type !== 'autocomplete',\n );\n // Optimistic, and only until the first answer arrives: a binding pointing at\n // an empty field is usually blocking, and showing the control as usable for\n // one round trip would flash an enabled, empty list. AutoComplete is excluded\n // because nothing would ever correct the guess — it cannot be searched while\n // disabled, so an optional binding would lock it for good.\n const waitsForDependencies =\n autoQueries &&\n dynamicField !== null &&\n readMissingFormDataSourceDependencies(\n dynamicField,\n input.formData,\n input.row?.values,\n ).length > 0;\n const pendingQueryStatus = readPendingQueryStatus(isStale, waitsForDependencies);\n const [remoteOptions, setRemoteOptions] = useState<readonly FormFieldOption[]>(\n [],\n );\n const [searchText, setSearchText] = useState('');\n const [nextCursor, setNextCursor] = useState<string | null>(null);\n const [resolution, setResolution] = useState<FormDataSourceResolution | null>(\n null,\n );\n const [status, setStatus] = useState<FormDataSourceFieldStatus>(\n (): FormDataSourceFieldStatus => {\n if (!dynamicField) {\n return 'IDLE';\n }\n\n // The very first paint already reflects the query the effect is about to\n // fire, so the control never appears usable before its options exist.\n return autoQueries ? pendingQueryStatus : quiescentStatus;\n },\n );\n const [error, setError] = useState<string | null>(null);\n const loadedOptionCount = useRef(0);\n const requestSequence = useRef(0);\n const resolveSequence = useRef(0);\n const optionsAbort = useRef<AbortController | null>(null);\n const resolveAbort = useRef<AbortController | null>(null);\n const lastRequest = useRef<{ readonly cursor: string | null; readonly searchText: string }>({\n cursor: null,\n searchText: '',\n });\n\n const queryFormData = useMemo(\n (): Readonly<Record<string, FormFieldValue>> =>\n readDefinedValues(input.formData),\n [formDataSignature],\n );\n const queryRowValues = useMemo(\n (): Readonly<Record<string, FormFieldValue>> | undefined =>\n input.row ? readDefinedValues(input.row.values) : undefined,\n [rowValuesSignature],\n );\n const mergedOptions = useMemo(\n (): readonly FormFieldOption[] =>\n mergeFormDataSourceOptions(snapshotOptions, remoteOptions),\n [remoteOptions, snapshotOptions],\n );\n const currentResolution =\n resolution && resolution.signature === dataSourceRefreshSignature\n ? resolution\n : null;\n const resolvePending = needsResolve && !currentResolution;\n const invalidValues = readInvalidFormDataSourceValues({\n options: mergedOptions,\n resolution: currentResolution,\n resolvePending,\n value: currentValue,\n });\n\n const loadOptions = useCallback(\n (nextSearchTextToLoad: string, cursor: string | null): void => {\n if (!dynamicField || !effectiveContext) {\n return;\n }\n\n const requestId = requestSequence.current + 1;\n requestSequence.current = requestId;\n lastRequest.current = {\n cursor,\n searchText: nextSearchTextToLoad,\n };\n optionsAbort.current?.abort();\n const controller = new AbortController();\n optionsAbort.current = controller;\n setStatus(pendingQueryStatus);\n setError(null);\n\n const request =\n effectiveContext.kind === 'preview'\n ? previewFormFieldOptions({\n cursor,\n fieldKey: queryFieldKey,\n formData: queryFormData,\n rowValues: queryRowValues,\n schema: input.schema,\n searchText: nextSearchTextToLoad,\n signal: controller.signal,\n uiSchema: input.uiSchema,\n })\n : readFormFieldOptions({\n cursor,\n fieldKey: queryFieldKey,\n formData: queryFormData,\n instanceId: effectiveContext.instanceId ?? null,\n rowValues: queryRowValues,\n searchText: nextSearchTextToLoad,\n signal: controller.signal,\n templateId: effectiveContext.templateId ?? null,\n });\n\n void request\n .then((result): void => {\n if (isSupersededRequest(controller, requestSequence, requestId)) {\n return;\n }\n\n setRemoteOptions((currentOptions) => {\n const selectedOptions = readSelectedFormDataSourceOptions(\n currentValue,\n currentOptions,\n );\n\n return mergeFormDataSourceOptions(\n selectedOptions,\n cursor ? currentOptions : [],\n result.options,\n );\n });\n setNextCursor(result.nextCursor);\n setError(null);\n loadedOptionCount.current = cursor\n ? loadedOptionCount.current + result.options.length\n : result.options.length;\n\n // An empty page that still hands back a cursor would loop forever.\n if (\n result.nextCursor &&\n result.options.length > 0 &&\n loadedOptionCount.current < MIN_SCROLLABLE_OPTION_COUNT\n ) {\n loadOptionsRef.current(nextSearchTextToLoad, result.nextCursor);\n }\n\n // Only the host knows which bound parameters are required, so a\n // control is disabled on its answer instead of on a browser guess.\n setStatus(\n result.waitingForFieldKeys.length\n ? 'WAITING_FOR_DEPENDENCIES'\n : 'VALID',\n );\n })\n .catch((requestError: unknown): void => {\n if (isSupersededRequest(controller, requestSequence, requestId)) {\n return;\n }\n\n // Anything that is not a DataSource code — a transport failure, or a\n // server-side error the host deliberately reduced to a generic\n // message — must not be rendered verbatim; it is English technical\n // copy the filler cannot act on.\n const message =\n readFormDataSourceErrorMessage(requestError) ??\n '選項來源暫時無法使用。';\n const code = readFormDataSourceErrorCode(requestError);\n\n setError(message);\n setStatus(\n readFailedQueryStatus(\n Boolean(code && RECOVERABLE_ERROR_CODES.includes(code)),\n hasValue,\n ),\n );\n });\n },\n [\n currentValueSignature,\n dynamicFieldSignature,\n effectiveContext,\n hasValue,\n pendingQueryStatus,\n queryFieldKey,\n queryFormData,\n queryRowValues,\n schemaSignature,\n uiSchemaSignature,\n ],\n );\n const loadOptionsRef = useRef(loadOptions);\n loadOptionsRef.current = loadOptions;\n\n const runResolve = useCallback((): void => {\n if (!dynamicField || !effectiveContext || selectedValues.length === 0) {\n return;\n }\n\n const signature = dataSourceRefreshSignature;\n const requestId = resolveSequence.current + 1;\n resolveSequence.current = requestId;\n resolveAbort.current?.abort();\n const controller = new AbortController();\n resolveAbort.current = controller;\n setError(null);\n\n const request =\n effectiveContext.kind === 'preview'\n ? previewResolveFormFieldOptions({\n fieldKey: queryFieldKey,\n formData: queryFormData,\n rowValues: queryRowValues,\n schema: input.schema,\n signal: controller.signal,\n uiSchema: input.uiSchema,\n values: selectedValues,\n })\n : resolveFormFieldOptions({\n fieldKey: queryFieldKey,\n formData: queryFormData,\n instanceId: effectiveContext.instanceId ?? null,\n rowValues: queryRowValues,\n signal: controller.signal,\n templateId: effectiveContext.templateId ?? null,\n values: selectedValues,\n });\n\n void request\n .then((result): void => {\n if (isSupersededRequest(controller, resolveSequence, requestId)) {\n return;\n }\n\n if (result.waitingForFieldKeys.length) {\n // The host could not consult the provider, so this is no answer about\n // the value: leave the field waiting rather than call it resolved.\n setStatus('WAITING_FOR_DEPENDENCIES');\n\n return;\n }\n\n // Authoritative labels for the values that survived, merged so the old\n // snapshot label of an unresolved value stays visible for recognition.\n setRemoteOptions((currentOptions) =>\n mergeFormDataSourceOptions(currentOptions, result.options),\n );\n setResolution({\n signature,\n unresolvedValues: result.unresolvedValues,\n });\n // `invalidValues` turns this into `INVALID` when anything went missing.\n setStatus('VALID');\n })\n .catch((requestError: unknown): void => {\n if (isSupersededRequest(controller, resolveSequence, requestId)) {\n return;\n }\n\n setStatus('UNAVAILABLE');\n setError(\n readFormDataSourceErrorMessage(requestError) ??\n '選項來源暫時無法使用。',\n );\n });\n }, [\n dataSourceRefreshSignature,\n dynamicFieldSignature,\n effectiveContext,\n queryFieldKey,\n queryFormData,\n queryRowValues,\n schemaSignature,\n selectedValues,\n uiSchemaSignature,\n ]);\n const runResolveRef = useRef(runResolve);\n runResolveRef.current = runResolve;\n\n useEffect((): void => {\n requestSequence.current += 1;\n optionsAbort.current?.abort();\n setRemoteOptions((currentOptions) =>\n readSelectedFormDataSourceOptions(currentValue, currentOptions),\n );\n setNextCursor((currentCursor) =>\n currentCursor === null ? currentCursor : null,\n );\n setSearchText((currentSearchText) =>\n currentSearchText ? '' : currentSearchText,\n );\n setError((currentError) => (currentError ? null : currentError));\n\n if (!dynamicField) {\n setStatus('IDLE');\n\n return;\n }\n\n if (!autoQueries) {\n // AutoComplete queries on search only, so it stays quiescent until the\n // filler types; a context-less field has nothing to query at all.\n setStatus(quiescentStatus);\n\n return;\n }\n\n loadOptionsRef.current('', null);\n }, [\n autoQueries,\n dynamicFieldSignature,\n effectiveContext,\n dataSourceRefreshSignature,\n initialFormDataSignature,\n initialRowValuesSignature,\n input.readonly,\n pendingQueryStatus,\n quiescentStatus,\n snapshotSignature,\n ]);\n\n useEffect((): void => {\n if (!needsResolve) {\n return;\n }\n\n runResolveRef.current();\n }, [dataSourceRefreshSignature, effectiveContext, needsResolve]);\n\n useEffect((): (() => void) => {\n return (): void => {\n optionsAbort.current?.abort();\n resolveAbort.current?.abort();\n };\n }, []);\n\n const onSearch = useCallback(\n (nextSearchTextToLoad: string): void => {\n setSearchText(nextSearchTextToLoad);\n setRemoteOptions((currentOptions) =>\n readSelectedFormDataSourceOptions(currentValue, currentOptions),\n );\n setNextCursor(null);\n loadOptions(nextSearchTextToLoad, null);\n },\n [loadOptions],\n );\n const onReachBottom = useCallback((): void => {\n if (nextCursor) {\n loadOptions(searchText, nextCursor);\n }\n }, [loadOptions, nextCursor, searchText]);\n const retry = useCallback((): void => {\n if (!effectiveContext) {\n return;\n }\n\n loadOptions(lastRequest.current.searchText, lastRequest.current.cursor);\n\n if (needsResolve) {\n runResolveRef.current();\n }\n }, [effectiveContext, loadOptions, needsResolve]);\n\n if (!dynamicField) {\n return EMPTY_FIELD_STATE;\n }\n\n return {\n canRetry: Boolean(effectiveContext),\n error,\n hasValue,\n hasNextPage: Boolean(nextCursor),\n invalidValues,\n onReachBottom,\n onSearch,\n options: mergedOptions,\n retry,\n status: readFormDataSourceExposedStatus({\n invalidValues,\n resolvePending,\n status,\n }),\n };\n}\n\nexport function readFormDataSourceFieldStatusMessage(\n state: FormDataSourceFieldState,\n): string | null {\n switch (state.status) {\n case 'WAITING_FOR_DEPENDENCIES':\n return '請先填寫相依欄位。';\n case 'STALE':\n return '選項需要重新載入或驗證。';\n case 'INVALID':\n return state.invalidValues.length\n ? `無法辨識選項:${state.invalidValues.join('、')}`\n : '目前選項已失效,請重新選擇。';\n case 'UNAVAILABLE':\n return state.error ?? '選項來源暫時無法使用。';\n case 'VALID':\n // A recoverable search hint outranks the empty-result copy: it is what\n // tells the filler how to get results at all.\n return state.error ?? (state.options.length ? null : '目前沒有可用選項。');\n default:\n return state.error;\n }\n}\n\nexport function isFormDataSourceFieldSubmissionBlocked(\n state: Pick<FormDataSourceFieldState, 'hasValue' | 'status'>,\n): boolean {\n return state.hasValue && state.status !== 'VALID';\n}\n\n/**\n * The copy to show when a submission is refused because of dynamic options.\n * `LOADING` and `STALE` clear on their own once the pending query answers, so\n * saying \"finish validating\" reads as a dead end for what is really a \"wait a\n * moment\"; the caller would otherwise show the same permanent-sounding line for\n * both cases.\n *\n * Returns `null` when nothing blocks the submission.\n */\nexport function readFormDataSourceSubmissionBlockMessage(\n states: readonly Pick<FormDataSourceFieldState, 'hasValue' | 'status'>[],\n): string | null {\n const blocked = states.filter(isFormDataSourceFieldSubmissionBlocked);\n\n if (blocked.length === 0) {\n return null;\n }\n\n return blocked.every(\n (state) => state.status === 'LOADING' || state.status === 'STALE',\n )\n ? '選項驗證中,請稍候再送出。'\n : '請先完成動態選項驗證。';\n}\n\n/**\n * The values the field holds that no option accounts for.\n *\n * A completed resolve is the authority — the loaded pages are not, because the\n * option snapshot is merged into them for display and would vouch for a value\n * the source has already dropped.\n */\nfunction readInvalidFormDataSourceValues(input: {\n readonly options: readonly FormFieldOption[];\n readonly resolution: FormDataSourceResolution | null;\n readonly resolvePending: boolean;\n readonly value: FormFieldValue | undefined;\n}): readonly string[] {\n if (input.resolution) {\n return input.resolution.unresolvedValues;\n }\n\n // While the host is being asked, its answer is the only one worth showing.\n if (input.resolvePending) {\n return NO_INVALID_VALUES;\n }\n\n return readMissingFormDataSourceOptionValues(input.value, input.options);\n}\n\n/**\n * Status of a field nobody is querying — read-only history, a Designer preview\n * before the first search, or a control the host gave no context for.\n */\nfunction readQuiescentFormDataSourceStatus(input: {\n readonly hasSnapshot: boolean;\n readonly hasValue: boolean;\n readonly isStale: boolean;\n readonly readonly: boolean;\n}): FormDataSourceFieldStatus {\n if (input.isStale) {\n return 'STALE';\n }\n\n if (input.hasSnapshot) {\n return 'VALID';\n }\n\n // A read-only value with no snapshot cannot be labelled from anywhere, which\n // is worth saying. An empty read-only field is simply blank — warning about a\n // source nobody is going to query would be noise.\n return input.readonly && input.hasValue ? 'UNAVAILABLE' : 'IDLE';\n}\n\n/**\n * Status held while a query is in flight.\n *\n * `waiting` is the browser's optimistic guess and only survives until the host\n * answers: `waitingForFieldKeys` from the response replaces it either way, so an\n * optional binding left empty clears within one round trip instead of locking\n * the control.\n */\nfunction readPendingQueryStatus(\n isStale: boolean,\n waiting: boolean,\n): FormDataSourceFieldStatus {\n if (waiting) {\n return 'WAITING_FOR_DEPENDENCIES';\n }\n\n return isStale ? 'STALE' : 'LOADING';\n}\n\n/**\n * Status after a rejected query. A recoverable failure leaves the field as\n * usable as it was — only a broken source makes it unavailable.\n */\nfunction readFailedQueryStatus(\n recoverable: boolean,\n hasValue: boolean,\n): FormDataSourceFieldStatus {\n if (!recoverable) {\n return 'UNAVAILABLE';\n }\n\n return hasValue ? 'VALID' : 'IDLE';\n}\n\nfunction readFormDataSourceExposedStatus(input: {\n readonly invalidValues: readonly string[];\n readonly resolvePending: boolean;\n readonly status: FormDataSourceFieldStatus;\n}): FormDataSourceFieldStatus {\n if (\n input.status === 'LOADING' ||\n input.status === 'UNAVAILABLE' ||\n input.status === 'WAITING_FOR_DEPENDENCIES'\n ) {\n return input.status;\n }\n\n if (input.invalidValues.length) {\n return 'INVALID';\n }\n\n return input.resolvePending ? 'STALE' : input.status;\n}\n\n/**\n * True when a response no longer belongs to the field: its request was aborted\n * by a newer one, or a newer one started before it settled. Such a response\n * must not touch state — an aborted request is not a failure to report.\n */\nfunction isSupersededRequest(\n controller: AbortController,\n sequence: { readonly current: number },\n requestId: number,\n): boolean {\n return controller.signal.aborted || sequence.current !== requestId;\n}\n\nfunction readDefinedValues(\n values: FormRendererValues,\n): Readonly<Record<string, FormFieldValue>> {\n return Object.entries(values).reduce<\n Readonly<Record<string, FormFieldValue>>\n >((defined, [key, value]) => {\n if (typeof value === 'undefined') {\n return defined;\n }\n\n return { ...defined, [key]: value };\n }, {});\n}\n","export interface FormFieldLink {\n /** Absolute links open in a new tab; site-relative ones stay in this tab. */\n readonly external: boolean;\n readonly href: string;\n}\n\nconst UNICODE_WHITESPACE_PATTERN = /\\s/u;\n\n// Whitespace and control characters are refused anywhere in the value: URL\n// parsers silently drop tabs and newlines, so \"/\\t/evil.example\" would turn\n// into the protocol-relative \"//evil.example\" after our `//` check passed.\nfunction hasUnsafeCharacter(value: string): boolean {\n return [...value].some((character): boolean => {\n const codePoint = character.codePointAt(0) ?? 0;\n\n return (\n // C0 controls and the space, DEL, C1 controls and the no-break space.\n codePoint <= 0x20 ||\n (codePoint >= 0x7f && codePoint <= 0xa0) ||\n UNICODE_WHITESPACE_PATTERN.test(character)\n );\n });\n}\n\nconst ABSOLUTE_HTTP_PATTERN = /^https?:\\/\\//iu;\n\n/**\n * Decides whether a `displayAs: 'link'` text value may become an anchor.\n * Returns `null` for everything that must stay plain text.\n *\n * Allowed: a site-relative path (`/` first, never `//`) or an absolute\n * `http(s)://` URL with a host and no embedded credentials. Everything else —\n * `javascript:`, `data:`, protocol-relative `//host`, backslash tricks\n * (`/\\host` is `//host` to a browser), padded or multi-line values, non-strings\n * — is refused rather than repaired.\n */\nexport function resolveFormFieldLink(value: unknown): FormFieldLink | null {\n if (\n typeof value !== 'string' ||\n !value ||\n value.includes('\\\\') ||\n hasUnsafeCharacter(value)\n ) {\n return null;\n }\n\n if (value.startsWith('/')) {\n return !value.startsWith('//') && isSafeSiteRelativePath(value)\n ? { external: false, href: value }\n : null;\n }\n\n return ABSOLUTE_HTTP_PATTERN.test(value) && isSafeAbsoluteHttpUrl(value)\n ? { external: true, href: value }\n : null;\n}\n\nconst PLACEHOLDER_BASE = 'http://placeholder.invalid';\n\n/**\n * Dot segments collapse before navigation: `/.//evil.example` resolves to the\n * path `//evil.example`, which a naive `startsWith('//')` check misses. Resolve\n * the value against a throw-away origin and require that it stays on that\n * origin and does not come out as a protocol-relative path.\n */\nfunction isSafeSiteRelativePath(value: string): boolean {\n try {\n const resolved = new URL(value, PLACEHOLDER_BASE);\n\n return (\n resolved.origin === PLACEHOLDER_BASE && !resolved.pathname.startsWith('//')\n );\n } catch {\n return false;\n }\n}\n\nfunction isSafeAbsoluteHttpUrl(value: string): boolean {\n try {\n const url = new URL(value);\n\n return (\n (url.protocol === 'http:' || url.protocol === 'https:') &&\n Boolean(url.hostname) &&\n !url.username &&\n !url.password\n );\n } catch {\n return false;\n }\n}\n","import type { MemberProfileRecord } from '@rytass/bpm-core-client/template';\n\n/** Most ids asked for on their own after a failed batch, per round. */\nexport const MAX_PER_ID_REQUESTS = 20;\n\n/** Most per-id requests in flight at once. */\nexport const PER_ID_CONCURRENCY = 4;\n\nexport type MemberProfileResolution = Readonly<{\n /** Ids whose lookup failed even when asked for on their own. */\n failedIds: readonly string[];\n profiles: readonly MemberProfileRecord[];\n /**\n * Ids left unasked because a failed batch held more than the per-id budget.\n * They were not tried, so a later round may ask for them again.\n */\n skippedIds: readonly string[];\n}>;\n\nexport type MemberProfileResolutionLimits = Readonly<{\n concurrency?: number;\n maxPerIdRequests?: number;\n}>;\n\n/**\n * Looks up member profiles in one batch, and degrades per id when the batch\n * request fails.\n *\n * The host fails a whole lookup when it contains an id it cannot handle (a\n * foreign id stored in a template, say). Treating that as \"nobody resolved\"\n * labels every approver of the template 「未知會員」 for the sake of one bad\n * id, so a failed batch is retried one id at a time and only the ids that fail\n * on their own are reported back in `failedIds`.\n *\n * The retry is bounded: at most `maxPerIdRequests` ids are asked for on their\n * own (the rest come back in `skippedIds` without a request), and at most\n * `concurrency` of those requests run at once, so one bad id in a large\n * template cannot turn into a burst of requests.\n *\n * A single-id batch is not retried: it already is the per-id request.\n */\nexport async function resolveMemberProfilesPerIdOnFailure(\n memberIds: readonly string[],\n resolveMembers: (\n memberIds: readonly string[],\n ) => Promise<readonly MemberProfileRecord[]>,\n limits: MemberProfileResolutionLimits = {},\n): Promise<MemberProfileResolution> {\n const maxPerIdRequests = limits.maxPerIdRequests ?? MAX_PER_ID_REQUESTS;\n const concurrency = Math.max(1, limits.concurrency ?? PER_ID_CONCURRENCY);\n\n try {\n return {\n failedIds: [],\n profiles: await resolveMembers(memberIds),\n skippedIds: [],\n };\n } catch {\n if (memberIds.length <= 1) {\n return { failedIds: memberIds, profiles: [], skippedIds: [] };\n }\n }\n\n const askedIds = memberIds.slice(0, maxPerIdRequests);\n const settled = await settleWithConcurrency(\n askedIds,\n concurrency,\n (memberId) => resolveMembers([memberId]),\n );\n\n return {\n failedIds: askedIds.filter(\n (_, index) => settled[index].status === 'rejected',\n ),\n profiles: settled.flatMap((result) =>\n result.status === 'fulfilled' ? result.value : [],\n ),\n skippedIds: memberIds.slice(maxPerIdRequests),\n };\n}\n\n/**\n * The ids still worth asking the directory for: those that already failed on\n * their own in this session are left out, so they stay 「未知會員」 instead of\n * being re-requested every time the option list changes.\n *\n * A failed id stays 「未知會員」 for the rest of the session, even when the\n * failure was transient (a network blip, say), unless a later member search\n * returns it and replaces the placeholder. Ids skipped over the per-id cap\n * were never asked and must not be added to `failedMemberIds`.\n */\nexport function excludeFailedMemberIds(\n memberIds: readonly string[],\n failedMemberIds: ReadonlySet<string>,\n): readonly string[] {\n return memberIds.filter((memberId) => !failedMemberIds.has(memberId));\n}\n\nasync function settleWithConcurrency<TItem, TResult>(\n items: readonly TItem[],\n concurrency: number,\n run: (item: TItem) => Promise<TResult>,\n): Promise<readonly PromiseSettledResult<TResult>[]> {\n const results: PromiseSettledResult<TResult>[] = [];\n let nextIndex = 0;\n\n async function worker(): Promise<void> {\n while (nextIndex < items.length) {\n const index = nextIndex;\n\n nextIndex += 1;\n results[index] = await run(items[index]).then(\n (value): PromiseSettledResult<TResult> => ({\n status: 'fulfilled',\n value,\n }),\n (reason: unknown): PromiseSettledResult<TResult> => ({\n reason,\n status: 'rejected',\n }),\n );\n }\n }\n\n await Promise.all(\n Array.from({ length: Math.min(concurrency, items.length) }, worker),\n );\n\n return results;\n}\n","import type { FormFieldValue } from '@rytass/bpm-core-shared/form';\nimport { readFormMemberIds } from '@rytass/bpm-core-shared/form';\nimport { formatMemberLabel } from '../../../lib/format-member-label';\n\n/**\n * One pickable member, shaped for Mezzanine `AutoComplete` (`id` + `name`).\n * `unresolved` marks the placeholder written when a stored id has no profile,\n * so a real profile arriving later replaces it instead of the placeholder\n * sticking (the designer does the same for its approver list).\n */\nexport type MemberFieldOption = Readonly<{\n id: string;\n name: string;\n unresolved?: boolean;\n}>;\n\nexport const UNKNOWN_MEMBER_NAME = '未知會員';\n\nexport function readMemberFieldOption(member: {\n readonly email: string;\n readonly memberId: string;\n readonly name: string;\n}): MemberFieldOption {\n return {\n id: member.memberId,\n name: formatMemberLabel(member.name, member.email),\n };\n}\n\nexport function readUnresolvedMemberFieldOption(\n memberId: string,\n): MemberFieldOption {\n return { id: memberId, name: UNKNOWN_MEMBER_NAME, unresolved: true };\n}\n\n/**\n * Adds `nextOptions` to `currentOptions`. A resolved option replaces an\n * unresolved placeholder with the same id; otherwise the first one seen wins.\n * Returns `currentOptions` itself when nothing changed, so state setters can\n * bail out of a re-render.\n */\nexport function mergeMemberFieldOptions(\n currentOptions: readonly MemberFieldOption[],\n nextOptions: readonly MemberFieldOption[],\n): readonly MemberFieldOption[] {\n const resolvedById = new Map(\n nextOptions\n .filter((option) => !option.unresolved)\n .map((option) => [option.id, option] as const),\n );\n const currentIds = new Set(currentOptions.map((option) => option.id));\n const addedOptions = nextOptions.filter(\n (option, index) =>\n !currentIds.has(option.id) &&\n nextOptions.findIndex((candidate) => candidate.id === option.id) ===\n index,\n );\n const upgradedOptions = currentOptions.map(\n (option) =>\n (option.unresolved ? resolvedById.get(option.id) : undefined) ?? option,\n );\n const changed =\n addedOptions.length > 0 ||\n upgradedOptions.some((option, index) => option !== currentOptions[index]);\n\n return changed ? [...upgradedOptions, ...addedOptions] : currentOptions;\n}\n\n/** Ids in the stored value that no known option covers yet. */\nexport function readUnresolvedMemberIds(\n value: FormFieldValue | undefined,\n knownOptions: readonly MemberFieldOption[],\n): readonly string[] {\n const knownIds = new Set(\n knownOptions\n .filter((option) => !option.unresolved)\n .map((option) => option.id),\n );\n\n return readFormMemberIds(value).filter((memberId) => !knownIds.has(memberId));\n}\n\n/**\n * The stored value as options, in stored order. An id with no known profile\n * still shows up (as 「未知會員」) so the filler can see and remove it.\n */\nexport function readSelectedMemberFieldOptions(\n value: FormFieldValue | undefined,\n knownOptions: readonly MemberFieldOption[],\n): readonly MemberFieldOption[] {\n return readFormMemberIds(value).map(\n (memberId) =>\n knownOptions.find((option) => option.id === memberId) ??\n readUnresolvedMemberFieldOption(memberId),\n );\n}\n\n/**\n * What a picker change writes back. Nothing picked is `undefined`, the same as\n * every other optional field, so the renderer's own initial value (`[]` for a\n * multiple member field) is restored by `buildFormRendererValues`.\n */\nexport function readMemberFieldValue(\n selected: readonly MemberFieldOption[],\n multiple: boolean,\n): FormFieldValue | undefined {\n if (selected.length === 0) {\n return undefined;\n }\n\n return multiple ? selected.map((option) => option.id) : selected[0]?.id;\n}\n","'use client';\n\nimport { ReactElement, useEffect, useRef, useState } from 'react';\nimport { AutoComplete } from '@mezzanine-ui/react';\nimport { resolveMembers, searchMembers } from '@rytass/bpm-core-client';\nimport type { FormFieldValue } from '@rytass/bpm-core-shared/form';\nimport {\n excludeFailedMemberIds,\n resolveMemberProfilesPerIdOnFailure,\n} from '../../../lib/member-profile-resolution';\nimport {\n mergeMemberFieldOptions,\n readMemberFieldOption,\n readMemberFieldValue,\n readSelectedMemberFieldOptions,\n readUnresolvedMemberFieldOption,\n readUnresolvedMemberIds,\n type MemberFieldOption,\n} from './member-field-options';\n\nexport interface MemberFieldControlProps {\n readonly multiple: boolean;\n readonly name: string;\n readonly onChange: (value: FormFieldValue | undefined) => void;\n readonly placeholder?: string;\n readonly readonly: boolean;\n readonly size?: 'main' | 'sub';\n readonly value: FormFieldValue | undefined;\n}\n\n/**\n * 人員選擇 picker. Searching and name lookup reuse the directory queries the\n * admin member picker and the workflow designer already call\n * (`searchMembers` / `resolveMembers`); nothing new is added server side.\n *\n * Stored values are member ids. The names shown here are resolved on mount and\n * whenever a stored id has no profile yet, so a read-only view of a submitted\n * form (instance detail) shows names, not ids.\n */\nexport function MemberFieldControl({\n multiple,\n name,\n onChange,\n placeholder,\n readonly,\n size,\n value,\n}: MemberFieldControlProps): ReactElement {\n const [knownOptions, setKnownOptions] = useState<\n readonly MemberFieldOption[]\n >([]);\n const [searchResults, setSearchResults] = useState<\n readonly MemberFieldOption[]\n >([]);\n const [loading, setLoading] = useState(false);\n const latestSearchRef = useRef(0);\n // Ids the directory could not name; they stay 「未知會員」 and are not asked\n // for again when the other ids of the value resolve and the key changes.\n // That holds for the rest of the session, a transient failure included,\n // unless a later search returns the member (the merge then replaces the\n // placeholder). Ids skipped over the per-id cap were never asked, so they are\n // not given up on.\n const givenUpIdsRef = useRef<Set<string>>(new Set());\n const unresolvedKey = readUnresolvedMemberIds(value, knownOptions).join('\\n');\n\n useEffect((): (() => void) => {\n const memberIds = excludeFailedMemberIds(\n unresolvedKey ? unresolvedKey.split('\\n') : [],\n givenUpIdsRef.current,\n );\n let cancelled = false;\n\n if (memberIds.length === 0) {\n return (): void => undefined;\n }\n\n // One id the directory cannot handle fails the whole batch, so a failed\n // batch is retried per id: the other members keep their names.\n void resolveMemberProfilesPerIdOnFailure(memberIds, resolveMembers).then(\n ({ profiles, skippedIds }): void => {\n if (cancelled) {\n return;\n }\n\n const resolved = profiles.map(readMemberFieldOption);\n // Ids the directory did not return stay visible as placeholders.\n const placeholders = memberIds\n .filter(\n (memberId) => !resolved.some((option) => option.id === memberId),\n )\n .map(readUnresolvedMemberFieldOption);\n\n // Only the ids that were asked for and still came back without a\n // profile are given up on, so a failed lookup is not retried in a loop.\n // Ids skipped over the per-id cap were never asked: they keep a\n // placeholder but stay eligible for the next round, as the designer\n // does.\n placeholders\n .filter((placeholder) => !skippedIds.includes(placeholder.id))\n .forEach((placeholder) => givenUpIdsRef.current.add(placeholder.id));\n\n setKnownOptions((current) =>\n mergeMemberFieldOptions(current, [...resolved, ...placeholders]),\n );\n },\n );\n\n return (): void => {\n cancelled = true;\n };\n }, [unresolvedKey]);\n\n async function handleSearch(searchText: string): Promise<void> {\n const requestId = latestSearchRef.current + 1;\n\n latestSearchRef.current = requestId;\n setLoading(true);\n\n try {\n const options = (await searchMembers(searchText)).map(\n readMemberFieldOption,\n );\n\n if (latestSearchRef.current === requestId) {\n setSearchResults(options);\n setKnownOptions((current) => mergeMemberFieldOptions(current, options));\n }\n } catch {\n if (latestSearchRef.current === requestId) {\n setSearchResults([]);\n }\n } finally {\n if (latestSearchRef.current === requestId) {\n setLoading(false);\n }\n }\n }\n\n const selected = readSelectedMemberFieldOptions(value, knownOptions);\n // Selected members stay in the option list so a picked member can be\n // un-ticked from the dropdown, not only through its tag.\n const options = [...mergeMemberFieldOptions(selected, searchResults)];\n const commonProps = {\n asyncData: true,\n clearSearchText: true,\n disabled: readonly,\n disabledOptionsFilter: true,\n emptyText: '沒有符合的成員',\n globalPortal: true,\n inputProps: {\n autoCapitalize: 'none',\n autoCorrect: 'off',\n name,\n spellCheck: false,\n },\n loading,\n loadingText: '搜尋成員中...',\n onSearch: handleSearch,\n onVisibilityChange: (open: boolean): void => {\n if (open) {\n setSearchResults([]);\n void handleSearch('');\n }\n },\n options,\n placeholder: placeholder ?? '搜尋姓名或信箱',\n readOnly: readonly,\n searchDebounceTime: 300,\n size,\n } as const;\n\n return multiple ? (\n <AutoComplete\n {...commonProps}\n mode=\"multiple\"\n onChange={(nextOptions): void =>\n onChange(readMemberFieldValue(nextOptions, true))\n }\n value={[...selected]}\n />\n ) : (\n <AutoComplete\n {...commonProps}\n mode=\"single\"\n onChange={(nextOption): void =>\n onChange(readMemberFieldValue(nextOption ? [nextOption] : [], false))\n }\n value={selected[0] ?? null}\n />\n );\n}\n","'use client';\n\nimport {\n ChangeEvent,\n CSSProperties,\n ReactElement,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport {\n AutoComplete,\n Button,\n CheckboxGroup,\n DatePicker,\n DateTimePicker,\n Input,\n RadioGroup,\n Select,\n Table,\n Textarea,\n Toggle,\n Typography,\n Upload,\n} from '@mezzanine-ui/react';\nimport type { UploadFile } from '@mezzanine-ui/react/Upload';\nimport type { TableActions, TableColumn } from '@mezzanine-ui/core/table';\nimport { PlusIcon, TrashIcon } from '@mezzanine-ui/icons';\nimport {\n FormDataSourceOptionFieldDefinition,\n FormDataSourceValueSnapshots,\n FormDefinitionSchema,\n FormFieldDefinition,\n FormFieldValue,\n FormTableRowValue,\n FormUiSchema,\n TableColumnDefinition,\n TableFieldDefinition,\n isFormDataSourceFieldDefinition,\n isFormStaticOptionFieldDefinition,\n isFormTableCellValue,\n isTableFieldDefinition,\n readFormFieldSelectionMode,\n} from '@rytass/bpm-core-shared/form';\nimport {\n buildFormRendererValues,\n clampOptionalNumber,\n createFormTableRow,\n formatDatePickerValue,\n formatDateTimePickerValue,\n FormRendererValues,\n isFormRendererFieldReadonly,\n isFormRendererFieldRequired,\n parseOptionalNumberInput,\n readDatePickerValue,\n readFieldOptionAsSelectOption,\n readFormTableCellPath,\n readFormTableRowBounds,\n readFormTableRows,\n readSelectedFormDataSourceOptions,\n readSelectOption,\n readVisibleFormRendererFields,\n} from '@rytass/bpm-core-client/form';\nimport { BPMFormField } from '../../../components/bpm-form-field';\nimport {\n FormDataSourceFieldState,\n FormRendererDataSourceContext,\n readFormDataSourceFieldStatusMessage,\n useFormDataSourceField,\n} from './form-data-source-field';\nimport { resolveFormFieldLink } from './form-field-link';\nimport { MemberFieldControl } from './member-field';\n\nexport interface FormRendererProps {\n readonly dataSourceContext?: FormRendererDataSourceContext;\n readonly dataSourceInitialValues?: FormRendererValues;\n readonly emptyText?: string;\n readonly errors?: Readonly<Record<string, string>>;\n readonly maxWidth?: CSSProperties['maxWidth'];\n readonly onChange?: (values: FormRendererValues) => void;\n readonly onDataSourceStateChange?: (\n fieldKey: string,\n state: Pick<\n FormDataSourceFieldState,\n 'hasValue' | 'invalidValues' | 'status'\n >,\n ) => void;\n readonly onUploadAttachment?: (\n field: FormFieldDefinition,\n file: File,\n ) => Promise<{ readonly id: string }>;\n readonly optionSnapshots?: FormDataSourceValueSnapshots;\n readonly readonly?: boolean;\n readonly schema: FormDefinitionSchema;\n readonly singleColumn?: boolean;\n readonly uiSchema: FormUiSchema;\n readonly value?: FormRendererValues;\n}\n\n/**\n * Controls inside a table cell take the table's own `sub` size, so a row is\n * sized by its cells rather than by whichever control kept the default.\n * `DatePicker` and `DateTimePicker` accept no size, so a date column stays at\n * the default height — a Mezzanine limitation, not a choice.\n */\ntype ControlSize = 'main' | 'sub';\n\nconst FORM_RENDERER_GRID_STYLE: CSSProperties = {\n alignItems: 'start',\n display: 'grid',\n gap: 12,\n gridTemplateColumns: 'repeat(12, minmax(0, 1fr))',\n};\n\nconst FORM_RENDERER_EMPTY_STYLE: CSSProperties = {\n gridColumn: '1 / -1',\n};\n\nconst FORM_RENDERER_FIELD_STYLE: CSSProperties = {\n alignItems: 'start',\n display: 'grid',\n gap: 8,\n minWidth: 0,\n};\n\nconst TEXTAREA_STYLE: CSSProperties = {\n minWidth: '100%',\n width: '100%',\n};\n\nfunction applyFullWidthTextareaHost(element: HTMLDivElement | null): void {\n if (!element) {\n return;\n }\n\n element.style.width = '100%';\n}\n\nexport function FormRenderer({\n dataSourceContext,\n dataSourceInitialValues,\n emptyText = '尚未建立欄位。',\n errors = {},\n maxWidth,\n onChange,\n onDataSourceStateChange,\n onUploadAttachment,\n optionSnapshots,\n readonly = false,\n schema,\n singleColumn = false,\n uiSchema,\n value,\n}: FormRendererProps): ReactElement {\n const [internalValues, setInternalValues] = useState<FormRendererValues>(() =>\n buildFormRendererValues(schema.fields, value ?? {}),\n );\n const values = useMemo(\n (): FormRendererValues =>\n buildFormRendererValues(schema.fields, value ?? internalValues),\n [internalValues, schema.fields, value],\n );\n const valuesRef = useRef<FormRendererValues>(values);\n const visibleFields = useMemo(\n (): readonly FormFieldDefinition[] =>\n readVisibleFormRendererFields(schema, uiSchema, values),\n [schema, uiSchema, values],\n );\n\n useEffect((): void => {\n valuesRef.current = values;\n }, [values]);\n\n useEffect((): void => {\n setInternalValues((currentValues) =>\n buildFormRendererValues(schema.fields, value ?? currentValues),\n );\n }, [schema.fields, value]);\n\n function updateValue(\n fieldKey: string,\n nextValue: FormFieldValue | undefined,\n ): void {\n const nextValues = {\n ...valuesRef.current,\n [fieldKey]: nextValue,\n };\n valuesRef.current = nextValues;\n\n if (!value) {\n setInternalValues(nextValues);\n }\n\n onChange?.(nextValues);\n }\n\n if (!visibleFields.length) {\n return (\n <div style={FORM_RENDERER_GRID_STYLE}>\n <Typography\n color=\"text-neutral\"\n style={FORM_RENDERER_EMPTY_STYLE}\n variant=\"body\"\n >\n {schema.fields.length > 0 ? '目前條件下沒有可填寫欄位。' : emptyText}\n </Typography>\n </div>\n );\n }\n\n return (\n <div\n style={{\n ...FORM_RENDERER_GRID_STYLE,\n // `maxWidth` is applied per field rather than to the grid, so a table\n // field can use the full content width while every other field keeps\n // the single-column reading width (docs/17 P4).\n ...(singleColumn ? { width: '100%' } : {}),\n }}\n >\n {visibleFields.map((field) => (\n <FormRendererField\n dataSourceContext={dataSourceContext}\n dataSourceInitialValues={dataSourceInitialValues}\n field={field}\n error={errors[field.fieldKey] ?? null}\n errors={errors}\n fields={schema.fields}\n key={field.fieldKey}\n onChange={updateValue}\n onDataSourceStateChange={onDataSourceStateChange}\n onUploadAttachment={onUploadAttachment}\n optionSnapshots={optionSnapshots}\n readonly={readonly}\n schema={schema}\n style={{\n ...FORM_RENDERER_FIELD_STYLE,\n gridColumn: `span ${\n singleColumn ? 12 : readFieldColumnSpan(field, uiSchema)\n }`,\n ...(singleColumn && !isTableFieldDefinition(field)\n ? { maxWidth }\n : {}),\n }}\n value={values[field.fieldKey]}\n values={values}\n uiSchema={uiSchema}\n />\n ))}\n </div>\n );\n}\n\nfunction FormRendererField({\n dataSourceContext,\n dataSourceInitialValues,\n error,\n errors,\n field,\n fields,\n onChange,\n onDataSourceStateChange,\n onUploadAttachment,\n optionSnapshots,\n readonly,\n schema,\n style,\n value,\n values,\n uiSchema,\n}: {\n readonly dataSourceContext?: FormRendererDataSourceContext;\n readonly dataSourceInitialValues?: FormRendererValues;\n readonly error: string | null;\n /**\n * The whole error map, not just this field's line: a table addresses its\n * cells by instance path, so it needs the keys of its own rows too\n * (ADR 16 §3.3).\n */\n readonly errors: Readonly<Record<string, string>>;\n readonly field: FormFieldDefinition;\n readonly fields: readonly FormFieldDefinition[];\n readonly onChange: (\n fieldKey: string,\n value: FormFieldValue | undefined,\n ) => void;\n readonly onDataSourceStateChange?: (\n fieldKey: string,\n state: Pick<\n FormDataSourceFieldState,\n 'hasValue' | 'invalidValues' | 'status'\n >,\n ) => void;\n readonly onUploadAttachment?:\n | ((\n field: FormFieldDefinition,\n file: File,\n ) => Promise<{ readonly id: string }>)\n | undefined;\n readonly optionSnapshots?: FormDataSourceValueSnapshots;\n readonly readonly: boolean;\n readonly schema: FormDefinitionSchema;\n readonly style: CSSProperties;\n readonly uiSchema: FormUiSchema;\n readonly value: FormFieldValue | undefined;\n readonly values: FormRendererValues;\n}): ReactElement {\n const required = isFormRendererFieldRequired(field, fields, values);\n const fieldReadonly =\n readonly || isFormRendererFieldReadonly(field, fields, values);\n const dataSourceState = useFormDataSourceField({\n context: dataSourceContext,\n field,\n formData: values,\n initialFormData: dataSourceInitialValues,\n initialValue: dataSourceInitialValues?.[field.fieldKey],\n optionSnapshots,\n readonly: fieldReadonly,\n schema,\n uiSchema,\n });\n const dataSourceStatusMessage = readFormDataSourceFieldStatusMessage(\n dataSourceState,\n );\n const dataSourceStateSignature = JSON.stringify({\n hasValue: dataSourceState.hasValue,\n invalidValues: dataSourceState.invalidValues,\n status: dataSourceState.status,\n });\n\n useEffect((): void => {\n if (!isFormDataSourceFieldDefinition(field)) {\n return;\n }\n\n onDataSourceStateChange?.(field.fieldKey, {\n hasValue: dataSourceState.hasValue,\n invalidValues: dataSourceState.invalidValues,\n status: dataSourceState.status,\n });\n }, [\n dataSourceStateSignature,\n field.fieldKey,\n onDataSourceStateChange,\n ]);\n\n return (\n <div data-form-field-key={field.fieldKey} style={style}>\n <BPMFormField\n label={field.label}\n name={field.fieldKey}\n required={required}\n >\n {isTableFieldDefinition(field) ? (\n <FormTableField\n dataSourceContext={dataSourceContext}\n dataSourceInitialValues={dataSourceInitialValues}\n errors={errors}\n field={field}\n onChange={onChange}\n onDataSourceStateChange={onDataSourceStateChange}\n optionSnapshots={optionSnapshots}\n readonly={fieldReadonly}\n schema={schema}\n uiSchema={uiSchema}\n value={value}\n values={values}\n />\n ) : (\n renderControl(\n field,\n value,\n fieldReadonly,\n onChange,\n onUploadAttachment,\n dataSourceContext,\n dataSourceState,\n )\n )}\n </BPMFormField>\n {error ? (\n <Typography color=\"text-error\" variant=\"caption\">\n {error}\n </Typography>\n ) : null}\n {dataSourceStatusMessage ? (\n <div style={DATA_SOURCE_FEEDBACK_STYLE}>\n <Typography\n color={\n dataSourceState.status === 'INVALID' ||\n dataSourceState.status === 'UNAVAILABLE'\n ? 'text-error'\n : 'text-neutral'\n }\n variant=\"caption\"\n >\n {dataSourceStatusMessage}\n </Typography>\n {dataSourceState.status === 'UNAVAILABLE' && dataSourceState.canRetry ? (\n <Button\n onClick={dataSourceState.retry}\n size=\"sub\"\n type=\"button\"\n variant=\"base-ghost\"\n >\n 重試\n </Button>\n ) : null}\n </div>\n ) : null}\n </div>\n );\n}\n\nconst EXTERNAL_LINK_CUE = '(另開新分頁)';\nconst EXTERNAL_LINK_TITLE = '另開新分頁';\n\nconst LINK_STYLE: CSSProperties = {\n color: 'inherit',\n textDecoration: 'underline',\n wordBreak: 'break-all',\n};\n\nconst DATA_SOURCE_FEEDBACK_STYLE: CSSProperties = {\n alignItems: 'center',\n display: 'flex',\n gap: 8,\n};\n\nconst TABLE_FIELD_STYLE: CSSProperties = {\n display: 'grid',\n gap: 8,\n minWidth: 0,\n width: '100%',\n};\n\nconst TABLE_FIELD_ACTIONS_STYLE: CSSProperties = {\n display: 'flex',\n justifyContent: 'flex-start',\n};\n\nconst TABLE_SCROLLER_STYLE: CSSProperties = {\n maxWidth: '100%',\n overflowX: 'auto',\n};\n\n// Mezzanine `Table` fills whatever box it is given, so an `overflow-x: auto`\n// wrapper on its own never scrolls: the columns just keep shrinking. Keeping\n// the table out of the single-column reading width is what stops a control\n// from overflowing its own cell; this floor is the defence for tables wide\n// enough that even the full width would squeeze them, and it is what makes the\n// wrapper actually scroll when that happens.\nconst TABLE_COLUMN_MIN_WIDTH = 160;\nconst TABLE_ACTIONS_COLUMN_WIDTH = 56;\n\nconst TABLE_CELL_STYLE: CSSProperties = {\n display: 'grid',\n gap: 4,\n minWidth: 0,\n};\n\ntype FormTableRowRecord = Readonly<\n Record<string, unknown> & {\n index: number;\n key: string;\n }\n>;\n\n/**\n * Rows carry no identity in `formData` — array order is display order\n * (ADR 16 §3.2) — so the React key and, from P3, the per-cell DataSource state\n * key come from an ephemeral id minted here and never written to the value.\n */\nfunction FormTableField({\n dataSourceContext,\n dataSourceInitialValues,\n errors,\n field,\n onChange,\n onDataSourceStateChange,\n optionSnapshots,\n readonly,\n schema,\n uiSchema,\n value,\n values,\n}: {\n readonly dataSourceContext?: FormRendererDataSourceContext;\n readonly dataSourceInitialValues?: FormRendererValues;\n readonly errors: Readonly<Record<string, string>>;\n readonly field: TableFieldDefinition;\n readonly onChange: (\n fieldKey: string,\n value: FormFieldValue | undefined,\n ) => void;\n readonly onDataSourceStateChange?: (\n fieldKey: string,\n state: Pick<\n FormDataSourceFieldState,\n 'hasValue' | 'invalidValues' | 'status'\n >,\n ) => void;\n readonly optionSnapshots?: FormDataSourceValueSnapshots;\n readonly readonly: boolean;\n readonly schema: FormDefinitionSchema;\n readonly uiSchema: FormUiSchema;\n readonly value: FormFieldValue | undefined;\n readonly values: FormRendererValues;\n}): ReactElement {\n const rows = readFormTableRows(value);\n const bounds = readFormTableRowBounds(field);\n const rowIdSequenceRef = useRef(0);\n const [rowIds, setRowIds] = useState<readonly string[]>(() =>\n rows.map((): string => createRowId(rowIdSequenceRef)),\n );\n\n // The value can also change from outside (a parent reset, a returned case\n // loading its saved rows). Re-mint ids only then, so ordinary edits keep the\n // per-row identity stable.\n useEffect((): void => {\n if (rowIds.length === rows.length) {\n return;\n }\n\n setRowIds(rows.map((): string => createRowId(rowIdSequenceRef)));\n }, [rowIds.length, rows.length]);\n\n function commitRows(nextRows: readonly FormTableRowValue[]): void {\n onChange(field.fieldKey, nextRows);\n }\n\n function handleAddRow(): void {\n setRowIds([...rowIds, createRowId(rowIdSequenceRef)]);\n commitRows([...rows, createFormTableRow(field.columns)]);\n }\n\n function handleRemoveRow(rowIndex: number): void {\n setRowIds(rowIds.filter((_, index) => index !== rowIndex));\n commitRows(rows.filter((_, index) => index !== rowIndex));\n }\n\n function handleCellChange(\n rowIndex: number,\n columnKey: string,\n cellValue: FormFieldValue | undefined,\n ): void {\n commitRows(\n rows.map((row, index) =>\n index === rowIndex\n ? readNextTableRow(row, columnKey, cellValue)\n : row,\n ),\n );\n }\n\n const dataSource: readonly FormTableRowRecord[] = rows.map((row, index) => ({\n ...row,\n index,\n key: rowIds[index] ?? `row-${index}`,\n }));\n const columns: TableColumn<FormTableRowRecord>[] = field.columns.map(\n (column) => ({\n key: column.fieldKey,\n render: (row): ReactElement => (\n <FormTableCell\n column={column}\n dataSourceContext={dataSourceContext}\n error={\n errors[\n readFormTableCellPath(field.fieldKey, row.index, column.fieldKey)\n ] ?? null\n }\n fieldPath={`${field.fieldKey}.${column.fieldKey}`}\n formData={values}\n initialFormData={dataSourceInitialValues}\n initialRowValues={readInitialTableRow(\n dataSourceInitialValues?.[field.fieldKey],\n row.index,\n )}\n // Keyed by the ephemeral row id, so a cell's DataSource state follows\n // its row rather than its position (ADR 16 §3.9).\n key={`${rowIds[row.index] ?? row.index}-${column.fieldKey}`}\n onChange={(cellValue): void =>\n handleCellChange(row.index, column.fieldKey, cellValue)\n }\n onDataSourceStateChange={onDataSourceStateChange}\n optionSnapshots={optionSnapshots}\n path={readFormTableCellPath(\n field.fieldKey,\n row.index,\n column.fieldKey,\n )}\n readonly={readonly}\n rowValues={rows[row.index] ?? {}}\n schema={schema}\n uiSchema={uiSchema}\n />\n ),\n title: column.label || column.fieldKey,\n }),\n );\n const actions: TableActions<FormTableRowRecord> | undefined = readonly\n ? undefined\n : {\n render: (row): ReturnType<TableActions<FormTableRowRecord>['render']> => [\n {\n disabled: (): boolean => rows.length <= bounds.minRows,\n icon: TrashIcon,\n iconType: 'icon-only',\n name: '刪除此列',\n onClick: (): void => handleRemoveRow(row.index),\n variant: 'destructive-ghost',\n },\n ],\n width: 56,\n };\n\n return (\n <div style={TABLE_FIELD_STYLE}>\n {/*\n Mezzanine `Table`'s `scroll` is vertical only, so a wide table is kept\n inside its own horizontal scroller rather than pushing the page sideways.\n The wrapper adds no styling of its own to the table (ADR 16 §3.9 assumed\n `scroll` covered this; see docs/17).\n */}\n <div style={TABLE_SCROLLER_STYLE}>\n <div\n style={{\n minWidth:\n field.columns.length * TABLE_COLUMN_MIN_WIDTH +\n (actions ? TABLE_ACTIONS_COLUMN_WIDTH : 0),\n }}\n >\n <Table\n {...(actions ? { actions } : {})}\n columns={columns}\n dataSource={[...dataSource]}\n // Cells carry form controls rather than text, so the row height\n // comes from the roomy container token, not the compact default.\n rowHeightPreset=\"roomy\"\n showHeader\n size=\"sub\"\n />\n </div>\n </div>\n {readonly ? null : (\n <div style={TABLE_FIELD_ACTIONS_STYLE}>\n <Button\n disabled={rows.length >= bounds.maxRows}\n icon={PlusIcon}\n iconType=\"leading\"\n onClick={handleAddRow}\n size=\"sub\"\n type=\"button\"\n variant=\"base-secondary\"\n >\n {field.addRowLabel || '新增一列'}\n </Button>\n </div>\n )}\n </div>\n );\n}\n\nfunction FormTableCell({\n column,\n dataSourceContext,\n error,\n fieldPath,\n formData,\n initialFormData,\n initialRowValues,\n onChange,\n onDataSourceStateChange,\n optionSnapshots,\n path,\n readonly,\n rowValues,\n schema,\n uiSchema,\n}: {\n readonly column: TableColumnDefinition;\n readonly dataSourceContext?: FormRendererDataSourceContext;\n readonly error: string | null;\n readonly fieldPath: string;\n readonly formData: FormRendererValues;\n readonly initialFormData?: FormRendererValues;\n readonly initialRowValues?: FormTableRowValue;\n readonly onChange: (value: FormFieldValue | undefined) => void;\n readonly onDataSourceStateChange?: (\n fieldKey: string,\n state: Pick<\n FormDataSourceFieldState,\n 'hasValue' | 'invalidValues' | 'status'\n >,\n ) => void;\n readonly optionSnapshots?: FormDataSourceValueSnapshots;\n readonly path: string;\n readonly readonly: boolean;\n readonly rowValues: FormTableRowValue;\n readonly schema: FormDefinitionSchema;\n readonly uiSchema: FormUiSchema;\n}): ReactElement {\n const value = readTableCellValue(rowValues, column.fieldKey);\n const dataSourceState = useFormDataSourceField({\n context: dataSourceContext,\n field: column,\n fieldPath,\n formData,\n initialFormData,\n initialValue: initialRowValues\n ? readTableCellValue(initialRowValues, column.fieldKey)\n : undefined,\n optionSnapshots,\n readonly,\n row: {\n initialValues: initialRowValues,\n values: rowValues,\n },\n schema,\n snapshotKey: path,\n uiSchema,\n });\n const statusMessage = readFormDataSourceFieldStatusMessage(dataSourceState);\n const stateSignature = JSON.stringify({\n hasValue: dataSourceState.hasValue,\n invalidValues: dataSourceState.invalidValues,\n status: dataSourceState.status,\n });\n\n useEffect((): (() => void) | void => {\n if (!isFormDataSourceFieldDefinition(column)) {\n return;\n }\n\n onDataSourceStateChange?.(path, {\n hasValue: dataSourceState.hasValue,\n invalidValues: dataSourceState.invalidValues,\n status: dataSourceState.status,\n });\n\n // A deleted row must stop blocking the submit it can no longer be fixed in.\n return (): void => {\n onDataSourceStateChange?.(path, {\n hasValue: false,\n invalidValues: [],\n status: 'IDLE',\n });\n };\n }, [onDataSourceStateChange, path, stateSignature]);\n\n return (\n <div data-form-field-key={path} style={TABLE_CELL_STYLE}>\n {renderControl(\n column,\n value,\n readonly,\n (_columnKey, nextValue): void => onChange(nextValue),\n undefined,\n dataSourceContext,\n dataSourceState,\n 'sub',\n )}\n {error ? (\n <Typography color=\"text-error\" variant=\"caption\">\n {error}\n </Typography>\n ) : null}\n {statusMessage ? (\n <div style={DATA_SOURCE_FEEDBACK_STYLE}>\n <Typography\n color={\n dataSourceState.status === 'INVALID' ||\n dataSourceState.status === 'UNAVAILABLE'\n ? 'text-error'\n : 'text-neutral'\n }\n variant=\"caption\"\n >\n {statusMessage}\n </Typography>\n {dataSourceState.status === 'UNAVAILABLE' &&\n dataSourceState.canRetry ? (\n <Button\n onClick={dataSourceState.retry}\n size=\"sub\"\n type=\"button\"\n variant=\"base-ghost\"\n >\n 重試\n </Button>\n ) : null}\n </div>\n ) : null}\n </div>\n );\n}\n\n/**\n * The row as it was loaded, used to tell a returned case's stored values from\n * edits. Absent when the table itself is new.\n */\nfunction readInitialTableRow(\n value: FormFieldValue | undefined,\n rowIndex: number,\n): FormTableRowValue | undefined {\n return readFormTableRows(value)[rowIndex];\n}\n\nfunction createRowId(sequenceRef: { current: number }): string {\n sequenceRef.current += 1;\n\n return `table-row-${sequenceRef.current}`;\n}\n\n/**\n * Clearing a cell removes the key instead of storing `undefined`: the row is\n * serialised to JSON, where `undefined` would vanish anyway, and an absent key\n * is what an untouched cell looks like.\n */\nfunction readNextTableRow(\n row: FormTableRowValue,\n columnKey: string,\n value: FormFieldValue | undefined,\n): FormTableRowValue {\n if (typeof value === 'undefined' || !isFormTableCellValue(value)) {\n return Object.fromEntries(\n Object.entries(row).filter(([key]) => key !== columnKey),\n );\n }\n\n return { ...row, [columnKey]: value };\n}\n\nfunction readTableCellValue(\n row: FormTableRowValue | undefined,\n columnKey: string,\n): FormFieldValue | undefined {\n if (!row || !Object.prototype.hasOwnProperty.call(row, columnKey)) {\n return undefined;\n }\n\n return row[columnKey];\n}\n\nfunction renderControl(\n field: FormFieldDefinition,\n value: FormFieldValue | undefined,\n readonly: boolean,\n onChange: (fieldKey: string, value: FormFieldValue | undefined) => void,\n onUploadAttachment:\n | ((\n field: FormFieldDefinition,\n file: File,\n ) => Promise<{ readonly id: string }>)\n | undefined,\n dataSourceContext: FormRendererDataSourceContext | undefined,\n dataSourceState: FormDataSourceFieldState,\n size: ControlSize = 'main',\n): ReactElement {\n if (isFormDataSourceFieldDefinition(field)) {\n return renderDynamicOptionControl(\n field,\n value,\n readonly,\n onChange,\n dataSourceContext,\n dataSourceState,\n size,\n );\n }\n\n return renderStaticControl(\n field,\n value,\n readonly,\n onChange,\n onUploadAttachment,\n size,\n );\n}\n\n/**\n * Every control that does not depend on a DataSource. Split out of\n * {@link renderControl} so a table cell can reuse the same controls without\n * carrying a field-level DataSource state it has no use for (ADR 16 §3.9).\n */\nfunction renderStaticControl(\n field: FormFieldDefinition,\n value: FormFieldValue | undefined,\n readonly: boolean,\n onChange: (fieldKey: string, value: FormFieldValue | undefined) => void,\n onUploadAttachment:\n | ((\n field: FormFieldDefinition,\n file: File,\n ) => Promise<{ readonly id: string }>)\n | undefined,\n size: ControlSize = 'main',\n): ReactElement {\n const link =\n readonly &&\n (field.type === 'text' || field.type === 'textarea') &&\n field.displayAs === 'link'\n ? resolveFormFieldLink(value)\n : null;\n\n // Only a safe href becomes an anchor; anything else falls through to the\n // ordinary read-only control, i.e. plain text.\n if (link) {\n return (\n // Typography types its props as a paragraph's, so it cannot take `href`;\n // it supplies the brand colour and the anchor inherits it.\n <Typography color=\"text-brand\" component=\"span\" variant=\"body\">\n <a\n href={link.href}\n style={LINK_STYLE}\n {...(link.external\n ? {\n // The cue lives in attributes, not in a child node, so\n // selecting or copying the link yields just the URL.\n 'aria-label': `${link.href}${EXTERNAL_LINK_CUE}`,\n rel: 'noopener noreferrer',\n target: '_blank',\n title: EXTERNAL_LINK_TITLE,\n }\n : {})}\n >\n {link.href}\n </a>\n </Typography>\n );\n }\n\n if (field.type === 'textarea') {\n return (\n <Textarea\n onChange={(event: ChangeEvent<HTMLTextAreaElement>): void =>\n onChange(field.fieldKey, event.target.value)\n }\n placeholder={field.placeholder ?? '請輸入多行文字'}\n readOnly={readonly}\n ref={applyFullWidthTextareaHost}\n rows={3}\n style={TEXTAREA_STYLE}\n value={readStringValue(value)}\n />\n );\n }\n\n if (field.type === 'boolean') {\n return (\n <Toggle\n checked={value === true}\n disabled={readonly}\n label=\"啟用\"\n onChange={(event: ChangeEvent<HTMLInputElement>): void =>\n onChange(field.fieldKey, event.target.checked)\n }\n size={size}\n />\n );\n }\n\n if (isFormStaticOptionFieldDefinition(field) && field.type === 'checkbox') {\n const options = field.options.map(readFieldOptionAsSelectOption);\n\n return (\n <Select\n mode=\"multiple\"\n onChange={(options): void =>\n onChange(\n field.fieldKey,\n options?.length\n ? options.map((option) => option.id)\n : undefined,\n )\n }\n options={options}\n placeholder={field.placeholder ?? '請選擇一或多個選項'}\n readOnly={readonly}\n size={size}\n value={options.filter((option) =>\n readStringArrayValue(value).includes(option.id),\n )}\n />\n );\n }\n\n if (isFormStaticOptionFieldDefinition(field)) {\n const options = field.options.map(readFieldOptionAsSelectOption);\n\n return (\n <Select\n onChange={(option): void =>\n onChange(field.fieldKey, option?.id ?? undefined)\n }\n options={options}\n placeholder={field.placeholder ?? '請選擇'}\n readOnly={readonly}\n size={size}\n value={readSelectOption(options, readStringValue(value))}\n />\n );\n }\n\n if (field.type === 'member') {\n return (\n <MemberFieldControl\n multiple={field.multiple === true}\n name={field.fieldKey}\n onChange={(nextValue): void => onChange(field.fieldKey, nextValue)}\n placeholder={field.placeholder}\n readonly={readonly}\n size={size}\n value={value}\n />\n );\n }\n\n if (field.type === 'file_upload') {\n return (\n <Upload\n accept={field.acceptedMimeTypes?.join(',')}\n disabled={readonly}\n maxFiles={field.maxFiles}\n mode=\"button-list\"\n {...((field.maxFiles ?? 1) > 1 ? { multiple: true } : {})}\n onChange={(files): void =>\n onChange(\n field.fieldKey,\n files.length ? files.map((file) => file.id) : undefined,\n )\n }\n onUpload={async (files): Promise<UploadFile[]> =>\n Promise.all(\n files.map(async (file): Promise<UploadFile> => {\n const uploadedFile = onUploadAttachment\n ? await onUploadAttachment(field, file)\n : { id: `${file.name}-${file.lastModified}` };\n\n return {\n file,\n id: uploadedFile.id,\n progress: 100,\n status: 'done',\n };\n }),\n )\n }\n size=\"sub\"\n />\n );\n }\n\n if (field.type === 'date') {\n return (\n <DatePicker\n format=\"YYYY-MM-DD\"\n fullWidth\n onChange={(nextValue): void =>\n onChange(field.fieldKey, formatDatePickerValue(nextValue))\n }\n placeholder={field.placeholder ?? readInputPlaceholder(field.type)}\n readOnly={readonly}\n value={readDatePickerValue(value)}\n />\n );\n }\n\n if (field.type === 'datetime') {\n return (\n <DateTimePicker\n formatDate=\"YYYY-MM-DD\"\n formatTime=\"HH:mm\"\n fullWidth\n hideSecond\n onChange={(nextValue): void =>\n onChange(field.fieldKey, formatDateTimePickerValue(nextValue))\n }\n placeholderLeft=\"選擇日期\"\n placeholderRight=\"選擇時間\"\n readOnly={readonly}\n value={readDatePickerValue(value)}\n />\n );\n }\n\n if (field.type === 'number' || field.type === 'money') {\n return (\n <Input\n fullWidth\n max={field.maximum}\n min={field.minimum}\n size={size}\n onChange={(event: ChangeEvent<HTMLInputElement>): void =>\n onChange(\n field.fieldKey,\n clampOptionalNumber(parseOptionalNumberInput(event.target.value), {\n max: field.maximum,\n min: field.minimum,\n }),\n )\n }\n placeholder={field.placeholder ?? readInputPlaceholder(field.type)}\n {...(readonly ? { readonly: true as const } : {})}\n showSpinner\n value={readNumberInputValue(value)}\n variant=\"measure\"\n />\n );\n }\n\n return (\n <Input\n fullWidth\n onChange={(event: ChangeEvent<HTMLInputElement>): void =>\n onChange(field.fieldKey, event.target.value)\n }\n placeholder={field.placeholder ?? readInputPlaceholder(field.type)}\n {...(readonly ? { readonly: true as const } : {})}\n size={size}\n value={readStringValue(value)}\n variant=\"base\"\n />\n );\n}\n\nfunction renderDynamicOptionControl(\n field: FormDataSourceOptionFieldDefinition,\n value: FormFieldValue | undefined,\n readonly: boolean,\n onChange: (fieldKey: string, value: FormFieldValue | undefined) => void,\n dataSourceContext: FormRendererDataSourceContext | undefined,\n dataSourceState: FormDataSourceFieldState,\n size: ControlSize = 'main',\n): ReactElement {\n const options = dataSourceState.options.map(readFieldOptionAsSelectOption);\n const selectedOptions = readSelectedFormDataSourceOptions(\n value,\n dataSourceState.options,\n ).map(readFieldOptionAsSelectOption);\n const loading = dataSourceState.status === 'LOADING';\n const waitingForDependencies =\n dataSourceState.status === 'WAITING_FOR_DEPENDENCIES';\n const interactiveSearch = Boolean(dataSourceContext) && !readonly;\n const optionControlDisabled = readonly || waitingForDependencies;\n // AutoComplete alone has no pre-query gate — it only learns a dependency is\n // missing from the answer to a search the filler already typed. Disabling it\n // at that point strands that text in a locked input with no way to clear it,\n // so it stays editable and reports the wait through the status line instead.\n const autoCompleteDisabled = readonly;\n\n if (field.type === 'autocomplete') {\n if (readFormFieldSelectionMode(field) === 'multiple') {\n return (\n <AutoComplete\n asyncData={interactiveSearch}\n clearSearchText\n disabled={autoCompleteDisabled}\n disabledOptionsFilter={interactiveSearch}\n globalPortal\n loading={loading}\n mode=\"multiple\"\n onChange={(nextOptions): void =>\n onChange(\n field.fieldKey,\n nextOptions.length\n ? nextOptions.map((option) => option.id)\n : undefined,\n )\n }\n onReachBottom={\n dataSourceState.hasNextPage\n ? dataSourceState.onReachBottom\n : undefined\n }\n onSearch={interactiveSearch ? dataSourceState.onSearch : undefined}\n options={options}\n placeholder={field.placeholder ?? '請輸入或選擇'}\n readOnly={readonly}\n searchDebounceTime={300}\n size={size}\n value={selectedOptions}\n />\n );\n }\n\n return (\n <AutoComplete\n asyncData={interactiveSearch}\n clearSearchText\n disabled={autoCompleteDisabled}\n disabledOptionsFilter={interactiveSearch}\n globalPortal\n loading={loading}\n mode=\"single\"\n onChange={(nextOption): void =>\n onChange(field.fieldKey, nextOption?.id ?? undefined)\n }\n onReachBottom={\n dataSourceState.hasNextPage\n ? dataSourceState.onReachBottom\n : undefined\n }\n onSearch={interactiveSearch ? dataSourceState.onSearch : undefined}\n options={options}\n placeholder={field.placeholder ?? '請輸入或選擇'}\n readOnly={readonly}\n searchDebounceTime={300}\n size={size}\n value={selectedOptions[0] ?? null}\n />\n );\n }\n\n if (field.type === 'radio') {\n return (\n <RadioGroup\n disabled={optionControlDisabled}\n name={field.fieldKey}\n onChange={(event): void =>\n onChange(field.fieldKey, event.target.value || undefined)\n }\n options={options}\n value={readStringValue(value)}\n />\n );\n }\n\n if (field.type === 'checkbox') {\n return (\n <CheckboxGroup\n disabled={optionControlDisabled}\n name={field.fieldKey}\n onChange={(event): void =>\n onChange(\n field.fieldKey,\n event.target.values.length ? event.target.values : undefined,\n )\n }\n options={options.map((option) => ({\n label: option.name,\n value: option.id,\n }))}\n value={[...readStringArrayValue(value)]}\n />\n );\n }\n\n if (readFormFieldSelectionMode(field) === 'multiple') {\n return (\n <Select\n disabled={optionControlDisabled}\n loading={loading}\n mode=\"multiple\"\n onChange={(nextOptions): void =>\n onChange(\n field.fieldKey,\n nextOptions.length\n ? nextOptions.map((option) => option.id)\n : undefined,\n )\n }\n onReachBottom={\n dataSourceState.hasNextPage\n ? dataSourceState.onReachBottom\n : undefined\n }\n options={options}\n placeholder={field.placeholder ?? '請選擇一或多個選項'}\n readOnly={readonly}\n size={size}\n value={selectedOptions}\n />\n );\n }\n\n return (\n <Select\n disabled={optionControlDisabled}\n loading={loading}\n onChange={(nextOption): void =>\n onChange(field.fieldKey, nextOption?.id ?? undefined)\n }\n onReachBottom={\n dataSourceState.hasNextPage\n ? dataSourceState.onReachBottom\n : undefined\n }\n options={options}\n placeholder={field.placeholder ?? '請選擇'}\n readOnly={readonly}\n size={size}\n value={selectedOptions[0] ?? null}\n />\n );\n}\n\nfunction readFieldColumnSpan(\n field: FormFieldDefinition,\n uiSchema: FormUiSchema,\n): number {\n const width =\n uiSchema.layout.find((item) => item.fieldKey === field.fieldKey)?.width ??\n 'FULL';\n const spans: Readonly<Record<typeof width, number>> = {\n FULL: 12,\n HALF: 6,\n THIRD: 4,\n };\n\n return spans[width];\n}\n\nfunction readStringValue(value: FormFieldValue | undefined): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction readStringArrayValue(\n value: FormFieldValue | undefined,\n): readonly string[] {\n // A table value is also an array, so the element check is what separates a\n // multi-select value from table rows here.\n return Array.isArray(value) && value.every((item) => typeof item === 'string')\n ? value\n : [];\n}\n\nfunction readNumberInputValue(value: FormFieldValue | undefined): string {\n return typeof value === 'number' ? String(value) : '';\n}\n\nfunction readInputPlaceholder(type: FormFieldDefinition['type']): string {\n const placeholders: Readonly<Record<FormFieldDefinition['type'], string>> = {\n boolean: '',\n autocomplete: '請輸入或選擇',\n checkbox: '請選擇一或多個選項',\n date: '請選擇日期',\n datetime: '請選擇日期與時間',\n file_upload: '請上傳附件',\n member: '搜尋姓名或信箱',\n money: '請輸入金額',\n number: '請輸入數字',\n radio: '請選擇一個選項',\n select: '請選擇一個選項',\n table: '',\n text: '請輸入文字',\n textarea: '請輸入多行文字',\n };\n\n return placeholders[type];\n}\n\nexport { FormRenderer as FormRendererView };\n"],"mappings":";;;;;;;;;;;AAyFA,IAAMC,KAA8C;CAClD,UAAU;CACV,OAAO;CACP,UAAU;CACV,aAAa;CACb,eAAe,CAAC;CAChB,qBAA2B,KAAA;CAC3B,gBAAsB,KAAA;CACtB,SAAS,CAAC;CACV,aAAmB,KAAA;CACnB,QAAQ;AACV,GAEMC,IAAuC,CAAC,GASxCC,KAA8B,IAO9BC,KAA8D,CAClE,yCACA,mCACF;AAEA,SAAgBC,EACd,GAC0B;CAC1B,IAAMC,IAAeC,EAAgCC,EAAM,KAAK,IAC5DA,EAAM,QACN,MACEC,IAAgBD,EAAM,aAAaF,GAAc,YAAY,IAC7DI,IAAWJ,IACbE,EAAM,kBAAkBA,EAAM,eAAeF,EAAa,YAC1D,KAAA,GAIEK,IAAwBL,IAC1B,KAAK,UAAU;EACb,YAAYA,EAAa;EACzB,UAAUA,EAAa;EACvB,MAAMA,EAAa;CACrB,CAAC,IACD,IACEM,IAAoB,KAAK,UAAUF,KAAY,IAAI,GACnDG,IAAkBC,QACYJ,GAAU,WAAW,CAAC,GACxD,CAACE,CAAiB,CACpB,GACMG,IAAoB,KAAK,UAAUP,EAAM,QAAQ,GACjDQ,IAA2B,KAAK,UAAUR,EAAM,mBAAmB,CAAC,CAAC,GACrES,IAAkB,KAAK,UAAUT,EAAM,MAAM,GAC7CU,IAAoB,KAAK,UAAUV,EAAM,QAAQ,GACjDW,IAAcX,EAAM,SAAS,MAC7BY,IACJZ,EAAM,SAAS,SAAS,YAAYA,EAAM,QAAQ,aAAa,KAAA,GAC3Da,IACJb,EAAM,SAAS,SAAS,YAAYA,EAAM,QAAQ,aAAa,KAAA,GAC3Dc,IAAqB,KAAK,UAAUd,EAAM,KAAK,UAAU,IAAI,GAC7De,IAA4B,KAAK,UACrCf,EAAM,KAA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"use client";require('../style.css');const e=require("./rolldown-runtime-BocRIvOZ.cjs"),t=require("./router-adapter--gYs13E8.cjs"),n=require("./language-provider-Bdnx3Gxl.cjs"),r=require("./routes-config-C1j_vFKo.cjs"),i=require("./bpm-form-field-Bc6k4ZEO.cjs"),a=require("./format-member-label-t7ANTF62.cjs"),o=require("./admin-pickers-BRHk3qKq.cjs"),s=require("./FormRendererView-DRFi_IH7.cjs");;/* empty css */const c=require("./FormBuilderView-aBcA-_tt.cjs");let l=require("react"),u=require("@mezzanine-ui/react"),d=require("react/jsx-runtime"),f=require("@mezzanine-ui/react/Drawer");f=e.t(f,1);let p=require("@mezzanine-ui/react/ContentHeader");p=e.t(p,1);let m=require("@mezzanine-ui/icons"),h=require("ai"),g=require("@rytass/bpm-core-shared"),_=require("@rytass/bpm-core-client/form"),v=require("@rytass/bpm-core-shared/form"),ee=require("@rytass/bpm-core-client/organization"),y=require("@xyflow/react"),b=require("dagre");b=e.t(b,1);let x=require("@rytass/bpm-core-client/template"),te=require("@ai-sdk/react"),ne=require("@rytass/bpm-core-shared/workflow"),S=require("@rytass/bpm-core-shared/workflow-graph");var re=[{id:`SINGLE`,name:`單人簽核`},{id:`PARALLEL_ANY`,name:`任一人同意`},{id:`PARALLEL_ALL`,name:`全部同意`},{id:`SEQUENTIAL`,name:`依序簽核`},{id:`QUORUM`,name:`達到指定門檻`}];function ie(e){if(!e||e.type===`SINGLE`||e.type===`PARALLEL_ANY`)return`可指定多位;多位時所有人都會收到待辦,任一人同意即可通過。`;if(e.type===`PARALLEL_ALL`)return`可指定多位;多位時所有人都會收到待辦,全部同意後才會通過。`;if(e.type===`SEQUENTIAL`)return`依簽核人順序一次開放一位,前一位核准後才輪到下一位;任一位拒絕或退回即結束此關。`;let t=e.thresholdType===`PERCENTAGE`?`%`:` 位簽核者`;return`可指定多位;需達到 ${e.threshold}${t} 才會通過。`}function ae(e){return re.find(t=>t.id===e)||{id:e,name:`未知決策方式(${e})`}}function oe({directory:e,initialState:t,layout:n,onLayout:r}){let[i,a]=(0,l.useState)(t),o=(0,l.useRef)(t),s=(0,l.useRef)(e);s.current=e;let c=(0,l.useCallback)(e=>{if(!e.changed&&!e.error)return e;let t=e.effects.layout?n(e.state.definition):e.state.definition,i={...e.state,definition:t};return o.current=i,a(i),e.effects.layout&&r?.(t),{...e,state:i}},[n,r]),u=(0,l.useCallback)(e=>c((0,g.applyWorkflowCommand)(o.current,e)),[c]),d=(0,l.useCallback)(e=>c((0,g.applyWorkflowMacroCommand)(o.current,e)),[c]),f=(0,l.useCallback)(async(e,t)=>{let n=await(0,g.executeWorkflowTool)(o.current,e,t,{directory:s.current});if(n.ok&&(n.kind===`mutation`||n.kind===`macro`)){let e=c(n.result);return{...n,result:e,snapshot:(0,g.readWorkflowSnapshot)(e.state)}}return n},[c]),p=(0,l.useCallback)(e=>{let t=typeof e==`function`?e(o.current):e;o.current=t,a(t)},[]),m=(0,l.useCallback)(()=>o.current,[]),h=(0,l.useMemo)(()=>(0,g.readWorkflowSnapshot)(i),[i]);return(0,l.useMemo)(()=>({dispatch:u,dispatchMacro:d,executeTool:f,getState:m,replaceState:p,snapshot:h,state:i,tools:g.WORKFLOW_TOOLSET}),[u,d,f,m,p,h,i])}function se({controller:e,api:t=`/api/chat`}){let n=(0,l.useMemo)(()=>new h.DefaultChatTransport({api:t}),[t]),r=(0,te.useChat)({transport:n,sendAutomaticallyWhen:h.lastAssistantMessageIsCompleteWithToolCalls,async onToolCall({toolCall:t}){let n=await e.executeTool(t.toolName,t.input);n.ok?r.addToolOutput({output:n.kind===`query`?n.data:n.snapshot,tool:t.toolName,toolCallId:t.toolCallId}):r.addToolOutput({errorText:n.error,state:`output-error`,tool:t.toolName,toolCallId:t.toolCallId})}});return r}var ce=12;function C(){let e=globalThis.LanguageModel;return e&&typeof e==`object`?e:null}var le={additionalProperties:!1,properties:{action:{enum:[`tool`,`message`],type:`string`},input:{type:`object`},text:{type:`string`},tool:{type:`string`}},required:[`action`],type:`object`};function ue(){return`你是「簽核流程設計器」頁面的離線 AI 助理。只能透過下列工具操作這個流程畫布,其他請求一律婉拒並引導回流程設計。
2
-
3
- 每一步只輸出一個 JSON 決策物件:
4
- - 呼叫工具:{"action":"tool","tool":"<工具名>","input":{...}}
5
- - 回覆使用者(完成或詢問):{"action":"message","text":"<繁體中文訊息>"}
6
-
7
- 規則:先用 get_workflow_snapshot 了解現況再規劃;完成後用 validate_workflow 檢查並以 message 說明做了什麼。
8
-
9
- 可用工具:
10
- ${g.WORKFLOW_TOOLSET.map(e=>`- ${e.name}(${JSON.stringify(e.inputSchema.properties??{})}): ${e.description}`).join(`
11
- `)}`}function w({controller:e}){let[t,n]=(0,l.useState)(!1),[r,i]=(0,l.useState)([]),[a,o]=(0,l.useState)(`ready`),s=(0,l.useRef)(0);(0,l.useEffect)(()=>{let e=C();e&&e.availability().then(e=>{n(e!==`unavailable`)}).catch(()=>n(!1))},[]);let c=(0,l.useCallback)((e,t)=>{s.current+=1,i(n=>[...n,{id:`chrome-${s.current}`,parts:[{text:t,type:`text`}],role:e}])},[]);return{available:t,messages:r,send:(0,l.useCallback)(t=>{let n=C();n&&a===`ready`&&(c(`user`,t),o(`submitted`),T({appendMessage:c,controller:e,model:n,userText:t}).then(()=>o(`ready`)).catch(e=>{c(`assistant`,fe(e)),o(`error`)}))},[c,e,a]),status:a}}async function T({appendMessage:e,controller:t,model:n,userText:r}){let i=await n.create({initialPrompts:[{content:ue(),role:`system`}]});try{let n=`使用者需求:${r}\n目前流程:${JSON.stringify(t.snapshot)}`;for(let r=0;r<ce;r+=1){let r=de(await i.prompt(n,{responseConstraint:le}));if(!r||r.action===`message`){e(`assistant`,r?.text??`我已完成可處理的部分。`);return}if(!r.tool){e(`assistant`,`我已完成可處理的部分。`);return}let a=await t.executeTool(r.tool,r.input??{});if(a.ok){let t=a.kind===`query`?a.data:a.snapshot;e(`assistant`,`⚙ ${r.tool}`),n=`工具 ${r.tool} 已執行。最新流程:${JSON.stringify(t)}\n請決定下一步。`}else n=`工具 ${r.tool} 失敗:${a.error}\n請改用其他方式或回覆使用者。`}e(`assistant`,`已達到單次操作步數上限,請告訴我下一步。`)}finally{i.destroy()}}function de(e){try{let t=JSON.parse(e);return typeof t==`object`&&t&&t.action!==void 0?t:null}catch{return null}}function fe(e){return e instanceof Error?`離線模式發生錯誤:${e.message}`:`離線模式發生未知錯誤。`}var pe={display:`flex`,flexDirection:`column`,gap:12,height:`100%`},me={display:`flex`,flex:1,flexDirection:`column`,gap:12,minHeight:0,overflowY:`auto`},he={display:`flex`,gap:8,paddingBottom:4},ge={borderTop:`1px solid var(--mzn-color-border-neutral, #e5e7eb)`,display:`flex`,flexDirection:`column`,gap:8,paddingTop:12},_e={display:`flex`,justifyContent:`flex-end`},ve={width:`100%`},ye=`workflow-chat-input-field`,be=`
12
- .${ye}.mzn-text-field {
13
- width: 100%;
14
- }
15
- `,xe={color:`var(--mzn-color-text-secondary, #6b7280)`,fontSize:12,padding:`2px 0`},Se={"input-available":`執行中…`,"input-streaming":`準備中…`,"output-available":`完成`,"output-error":`失敗`};function Ce(e){let t=e===`user`;return{alignSelf:t?`flex-end`:`flex-start`,background:t?`var(--mzn-color-primary, #2563eb)`:`var(--mzn-color-surface, #f3f4f6)`,borderRadius:10,color:t?`#fff`:`var(--mzn-color-text-primary, #111827)`,maxWidth:`85%`,padding:`8px 12px`,whiteSpace:`pre-wrap`,wordBreak:`break-word`}}function we({api:e,controller:t,onClose:n,open:r}){let i=se({api:e,controller:t}),a=w({controller:t}),[o,s]=(0,l.useState)(`online`),[c,p]=(0,l.useState)(``),m=o===`offline`?{messages:a.messages,send:a.send,status:a.status}:{messages:i.messages,send:e=>{i.sendMessage({text:e})},status:i.status},{messages:h,send:g}=m,_=m.status===`submitted`||m.status===`streaming`,v=(0,l.useCallback)(()=>{let e=c.trim();e&&!_&&(p(``),g(e))},[_,c,g]),ee=(0,l.useCallback)(e=>{e.nativeEvent.isComposing||e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),v())},[v]);return(0,d.jsxs)(f.default,{headerTitle:`AI 流程助理`,isHeaderDisplay:!0,onClose:n,open:r,size:`medium`,children:[(0,d.jsx)(`style`,{children:be}),(0,d.jsxs)(`div`,{style:pe,children:[a.available?(0,d.jsxs)(`div`,{style:he,children:[(0,d.jsx)(u.Button,{onClick:()=>s(`online`),variant:o===`online`?`base-primary`:`base-tertiary`,children:`線上`}),(0,d.jsx)(u.Button,{onClick:()=>s(`offline`),variant:o===`offline`?`base-primary`:`base-tertiary`,children:`離線(裝置內,實驗)`})]}):null,(0,d.jsxs)(`div`,{role:`log`,style:me,children:[h.length===0?(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`body`,children:`用一句話描述你想要的流程,例如:「建立三關簽核:部門主管 → 經理 → 財務,金額大於十萬走財務複核」。我會直接在畫布上幫你繪製。`}):null,h.map(e=>(0,d.jsx)(l.Fragment,{children:Te(e)},e.id)),_?(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`body`,children:`思考中…`}):null]}),(0,d.jsxs)(`div`,{style:ge,children:[(0,d.jsx)(u.Textarea,{className:ye,disabled:_,maxLength:2e3,onChange:e=>p(e.target.value),onKeyDown:ee,placeholder:`描述你想要的流程…(Enter 送出,Shift + Enter 換行)`,rows:3,style:ve,value:c}),(0,d.jsx)(`div`,{style:_e,children:(0,d.jsx)(u.Button,{disabled:_||c.trim().length===0,loading:_,onClick:v,type:`button`,variant:`base-primary`,children:`送出`})})]})]})]})}function Te(e){return e.parts.map((t,n)=>{if(t.type===`text`)return(0,d.jsx)(`div`,{style:Ce(e.role),children:t.text},`${e.id}-${n}`);if(t.type===`dynamic-tool`||(0,h.isToolUIPart)(t)){let r=(0,h.getToolName)(t),i=Se[t.state]??t.state;return(0,d.jsx)(`div`,{style:xe,children:`⚙ ${r} · ${i}`},`${e.id}-${n}`)}return null})}var E={en:`An unknown error occurred`,"zh-TW":`發生未知錯誤`},D={en:`Webhook settings failed the publish check: `,"zh-TW":`Webhook 設定未通過發布檢查:`};function O(e,t,n){if(!(e instanceof Error))return E[t];let r=n?(0,x.readWorkflowLintMessage)(e.message,n,t):e.message;return r.includes(`WORKFLOW_WEBHOOK_`)?`${D[t]}${r}`:(0,_.readFormSchemaLintMessage)(r,t)}function Ee(e,t){let n=[...new Set(e.map(e=>e.level))];return[...n.includes(t)?n:[...n,t]].sort((e,t)=>t-e).map(t=>{let n=e.filter(e=>e.level===t).map(e=>e.name);return{id:String(t),name:n.length>0?`職等 ${t}(${n.join(`、`)})`:`職等 ${t}`,value:t}})}function k(e){return e.reduce((e,t)=>Math.max(e,t.level),1)}var A={"initiator.memberId":`發起人會員編號`,"instance.id":`案件編號`,"instance.templateId":`模板編號`,"instance.templateVersionId":`模板版本編號`,"instance.title":`案件主旨`,"node.id":`節點編號`,"node.label":`節點名稱`},De={boolean:`是/否`,json:`JSON`,number:`數字`,string:`文字`,stringArray:`文字清單`};function j(e){return`${e.key}@${e.version}`}function Oe(e,t){return e.find(e=>e.key===t.key&&e.version===t.version)??null}function ke(e){return[`FIELD`,...e===`stringArray`?[]:[`CONSTANT`],...e===`string`||e===`json`?[`CONTEXT`]:[]]}function Ae(e,t){return e.filter(e=>(0,S.isFormFieldCompatibleWithWebhookParameter)(e,t))}function je(e,t,n){return e===`FIELD`?{fieldKey:Ae(n,t.type)[0]?.fieldKey??``,kind:`FIELD`}:e===`CONTEXT`?{kind:`CONTEXT`,path:`instance.title`}:{kind:`CONSTANT`,value:t.type===`boolean`?!0:t.type===`number`?null:``}}var Me=/^-?\d+(\.\d+)?$/;function Ne(e,t){if(e!==`number`)return t;let n=t.trim();return n?Me.test(n)?Number(n):t:null}function Pe(e){return!(0,S.readNotifyWebhookStructureIssues)(e).some(e=>Fe.has(e.code))}var Fe=new Set([`BINDING_INVALID`,`BINDING_SOURCE_INVALID`,`BINDINGS_NOT_ARRAY`,`ENDPOINT_KEY_REQUIRED`,`ENDPOINT_VERSION_INVALID`,`TARGET_ID_REQUIRED`,`TARGET_INVALID`,`WEBHOOKS_NOT_ARRAY`]);function Ie(e,t,n){let r=e.bindings.filter(e=>e.parameter!==t),i=e.bindings.findIndex(e=>e.parameter===t);if(!n)return{...e,bindings:r};let a={from:n,parameter:t};return{...e,bindings:i===-1?[...e.bindings,a]:e.bindings.map((e,t)=>t===i?a:e)}}function M(e,t,n){return{bindings:e.bindings.filter(r=>{let i=t.parameters.find(e=>e.key===r.parameter);return i!==void 0&&!(0,S.readNotifyWebhookTargetCatalogIssues)({endpoint:{parameters:[{...i,required:!1}]},formFields:n,target:{...e,bindings:[r]}}).length}),endpoint:{key:t.key,version:t.version},id:e.id}}function Le({definition:e,endpoints:t,formFields:n}){return e.nodes.flatMap(e=>e.type!==`serviceTask`||e.data.action.type!==`NOTIFY`||(0,S.readNotifyWebhookStructureIssues)(e.data.action.webhooks).length?[]:(0,S.readNotifyWebhookTargets)(e.data.action).flatMap((r,i)=>{let a=Oe(t,r.endpoint);return(0,S.readNotifyWebhookTargetCatalogIssues)({endpoint:a,formFields:n,target:r}).map(t=>(0,S.readNotifyWebhookCatalogIssueMessage)({endpointLabel:a?.label??j(r.endpoint),issue:t,nodeLabel:e.data.label,targetIndex:i}))}))}var Re={display:`grid`,gap:`var(--mzn-spacing-gap-base)`},N={borderColor:`var(--mzn-color-border-neutral)`,borderRadius:`var(--mzn-radius-base)`,borderStyle:`solid`,borderWidth:1,display:`grid`,gap:`var(--mzn-spacing-gap-base)`,padding:`var(--mzn-spacing-padding-horizontal-base)`},ze={alignItems:`center`,display:`flex`,gap:`var(--mzn-spacing-gap-base)`,justifyContent:`space-between`},Be={display:`grid`,gap:`var(--mzn-spacing-gap-base)`,gridTemplateColumns:`minmax(0, 2fr) minmax(0, 3fr)`},Ve={id:`NONE`,name:`不傳送`},He={CONSTANT:{id:`CONSTANT`,name:`固定值`},CONTEXT:{id:`CONTEXT`,name:`案件資訊`},FIELD:{id:`FIELD`,name:`表單欄位`}},Ue=[{id:`true`,name:`是`},{id:`false`,name:`否`}],We=S.NOTIFY_WEBHOOK_CONTEXT_PATHS.map(e=>({id:e,name:A[e]}));function Ge({catalog:e,catalogState:t,formFields:n,onChange:r,targets:i}){let a=e.filter(e=>!e.deprecated);if(!i.length&&(t===`unavailable`||t===`ready`&&!a.length))return null;function o(e,t){r(i.map((n,r)=>r===e?t:n))}function s(){let[e]=a;e&&r([...i,(0,S.createNotifyWebhookTarget)({key:e.key,version:e.version})])}return(0,d.jsxs)(`div`,{style:Re,children:[(0,d.jsx)(u.Typography,{variant:`label-primary-highlight`,children:`Webhook`}),(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`caption`,children:`知會節點抵達時,將指定的表單欄位或案件資訊送到外部系統。`}),t===`loading`?(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`body`,children:`正在載入可用的 Webhook 端點…`}):null,t===`unavailable`?(0,d.jsx)(u.Typography,{color:`text-error`,variant:`body`,children:`目前無法載入 Webhook 端點,已設定的內容會保留,請稍後重試。`}):null,i.map((s,c)=>(0,d.jsx)(Ke,{activeEndpoints:a,catalog:e,catalogState:t,formFields:n,index:c,onChange:e=>o(c,e),onRemove:()=>r(i.filter((e,t)=>t!==c)),target:s},s.id)),(0,d.jsx)(`div`,{children:(0,d.jsx)(u.Button,{disabled:t!==`ready`||!a.length||i.length>=S.NOTIFY_WEBHOOK_TARGET_LIMIT,icon:m.PlusIcon,iconType:`leading`,onClick:s,variant:`base-dashed`,children:`新增 Webhook`})}),i.length>=S.NOTIFY_WEBHOOK_TARGET_LIMIT?(0,d.jsxs)(u.Typography,{color:`text-neutral`,variant:`caption`,children:[`每個知會節點最多 `,S.NOTIFY_WEBHOOK_TARGET_LIMIT,` 個 Webhook。`]}):null]})}function Ke({activeEndpoints:e,catalog:t,catalogState:n,formFields:r,index:a,onChange:o,onRemove:s,target:c}){let l=Oe(t,c.endpoint),f=j(c.endpoint),p=[...e.map(e=>({id:j(e),name:Xe(e)})),...l&&!l.deprecated?[]:[{id:f,name:l?Xe(l):`${f}(找不到端點)`}]],h=new Set((l?.parameters??[]).map(e=>e.key)),g=l?c.bindings.filter(e=>!h.has(e.parameter)):[];return(0,d.jsxs)(`div`,{style:N,children:[(0,d.jsxs)(`div`,{style:ze,children:[(0,d.jsxs)(u.Typography,{variant:`label-primary`,children:[`第 `,a+1,` 個 Webhook`]}),(0,d.jsx)(u.Button,{icon:m.TrashIcon,iconType:`leading`,onClick:s,variant:`destructive-text-link`,children:`移除`})]}),(0,d.jsx)(i.t,{label:`端點`,name:`webhookEndpoint-${c.id}`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,disabled:n!==`ready`,onChange:t=>{let n=e.find(e=>j(e)===t?.id);n&&o(M(c,n,r??[]))},options:[...p],placeholder:`選擇端點`,value:p.find(e=>e.id===f)??null})}),n===`ready`&&!l?(0,d.jsx)(u.Typography,{color:`text-warning`,variant:`body`,children:`找不到這個端點,設定會保留;請改選其他端點或移除,否則無法發布。`}):null,l?.disabled?(0,d.jsx)(u.Typography,{color:`text-warning`,variant:`body`,children:`這個端點已被管理者停用,不會再送出;設定會保留,請改選其他端點,否則無法發布。`}):l?.deprecated?(0,d.jsx)(u.Typography,{color:`text-warning`,variant:`body`,children:`這個端點不建議再使用,設定會保留;請改選其他端點,否則無法發布。`}):null,l?.description?(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`caption`,children:l.description}):null,l&&!l.parameters.length?(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`caption`,children:`這個端點不需要參數。`}):null,(l?.parameters??[]).map(e=>(0,d.jsx)(qe,{formFields:r,onChange:t=>o(Ie(c,e.key,t)),parameter:e,source:c.bindings.find(t=>t.parameter===e.key)?.from??null,targetId:c.id},e.key)),g.map(e=>(0,d.jsxs)(`div`,{style:ze,children:[(0,d.jsxs)(u.Typography,{color:`text-warning`,variant:`body`,children:[`參數「`,e.parameter,`」已不在端點定義中。`]}),(0,d.jsx)(u.Button,{onClick:()=>o(Ie(c,e.parameter,null)),variant:`base-text-link`,children:`移除設定`})]},e.parameter))]})}function qe({formFields:e,onChange:t,parameter:n,source:r,targetId:a}){let o=r?.kind===`FIELD`||Ae(e??[],n.type).length>0,s=[...n.required?[]:[Ve],...ke(n.type).filter(e=>e!==`FIELD`||o).map(e=>He[e])],c=De[n.type];return(0,d.jsx)(i.t,{hintText:[n.key,c,n.description].filter(Boolean).join(` · `),label:n.label,name:`webhookBinding-${a}-${n.key}`,required:n.required,children:(0,d.jsxs)(`div`,{style:Be,children:[(0,d.jsx)(u.Select,{clearable:!1,onChange:r=>{let i=Ze(r?.id??null);t(i?je(i,n,e??[]):null)},options:[...s],placeholder:`選擇來源`,value:r?He[r.kind]:n.required?null:Ve}),r?(0,d.jsx)(Je,{formFields:e,onChange:t,parameter:n,source:r}):null]})})}function Je({formFields:e,onChange:t,parameter:n,source:r}){if(r.kind===`FIELD`){if(!e)return(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`caption`,children:`請先綁定表單版本,才能選擇表單欄位。`});let i=Ae(e,n.type).map(e=>({id:e.fieldKey,name:`${e.label}(${e.fieldKey})`})),a=r.fieldKey&&!i.some(e=>e.id===r.fieldKey)?[...i,{id:r.fieldKey,name:`${r.fieldKey}(找不到相容欄位)`}]:i;return(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>t({fieldKey:e?.id??``,kind:`FIELD`}),options:[...a],placeholder:a.length?`選擇表單欄位`:`沒有型別相容的欄位`,value:a.find(e=>e.id===r.fieldKey)??null})}return r.kind===`CONTEXT`?(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>{(0,S.isNotifyWebhookContextPath)(e?.id)&&t({kind:`CONTEXT`,path:e.id})},options:[...We],value:We.find(e=>e.id===r.path)??null}):n.type===`boolean`?(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>t({kind:`CONSTANT`,value:e?.id===`true`}),options:[...Ue],value:typeof r.value==`boolean`?Ue.find(e=>e.id===String(r.value))??null:null}):(0,d.jsx)(Ye,{onChange:e=>t({kind:`CONSTANT`,value:e}),type:n.type,value:r.value})}function Ye({onChange:e,type:t,value:n}){let[r,i]=(0,l.useState)(n===null?``:String(n));return(0,l.useEffect)(()=>{i(e=>Ne(t,e)===n?e:n===null?``:String(n))},[t,n]),(0,d.jsx)(u.Input,{inputProps:{inputMode:t===`number`?`decimal`:void 0},onChange:n=>{i(n.target.value),e(Ne(t,n.target.value))},placeholder:t===`number`?`輸入數字`:`輸入固定值`,value:r,variant:`base`})}function Xe(e){let t=[`v${e.version}`,...e.source===`DATABASE`?[`後台維護`]:[],...e.disabled?[`已停用`]:e.deprecated?[`不建議使用`]:[]];return`${e.label}(${t.join(`,`)})`}function Ze(e){return e===`FIELD`||e===`CONSTANT`||e===`CONTEXT`?e:null}function Qe(e){return(e?.fields??[]).reduce((e,t)=>({...e,[t.fieldKey]:$e(t)}),{})}function P(e){return`formMember:${e}`}function $e(e){if(e.type===`number`||e.type===`money`)return 1e3;if(e.type===`boolean`)return!0;if(e.type===`member`){let t=P(e.fieldKey);return e.multiple?[t]:t}if((0,v.isFormOptionFieldDefinition)(e)){let t=(0,v.isFormStaticOptionFieldDefinition)(e)?e.options[0]?.value:void 0;if((0,v.readFormFieldSelectionMode)(e)===`multiple`)return t===void 0?[]:[t];if((0,v.isFormStaticOptionFieldDefinition)(e))return t??``}return e.type===`date`?`2026-05-08`:e.type===`datetime`?`2026-05-08T09:00:00+08:00`:e.placeholder??e.label}function et(e,t){let[n,...r]=e.split(`:`),i=e=>t.orgUnits.find(t=>t.id===e)?.name??e,a=e=>t.positions.find(t=>t.id===e)?.name??e;return n===`position`&&r.length===1&&r[0]?`職位:${a(r[0])}(送出時依當下人員決定)`:n===`orgUnitMember`&&r.length===1&&r[0]?`組織任一人:${i(r[0])}`:n===`orgUnitPosition`&&r.length===2&&r[0]&&r[1]?`組織職位:${i(r[0])}/${a(r[1])}`:n===`orgUnitManager`&&r.length===1&&r[0]?`組織主管:${i(r[0])}`:n===`formMember`&&r.length===1&&r[0]?`表單欄位「${(e=>t.formFields.find(t=>t.fieldKey===e)?.label||e)(r[0])}」選的人(送出時依填寫內容決定)`:n===`orgManagerChain`&&r.length===1&&r[0]?`主管鏈:簽到職等 ${r[0]}(送出時依組織決定實際主管)`:t.memberName(e)??e}var tt=`表單中沒有「人員選擇」欄位,請先到表單設計加入`,nt=`原本指定的欄位已不在表單中,或已不是「人員選擇」欄位,請重新選擇。`,rt=`此欄位非必填`,it=`此欄位可能被條件隱藏`,F=`此欄位為隱藏欄位,申請人無法填寫`,at=`,空白時此關會找不到人員,發佈時會被拒絕;請在表單設計將它設為必填且不隱藏`;function I(e){let t=[...e.required?[]:[rt],...e.visibleWhen?.trim()?[it]:[],...e.hidden?[F]:[]];return t.length>0?`${t.join(`、`)}${at}`:void 0}function ot(e){return`${e.required?``:`(非必填)`}${e.visibleWhen?.trim()?`(可能被條件隱藏)`:``}${e.hidden?`(隱藏欄位)`:``}`}function st(e){return(e?.fields??[]).filter(v.isMemberFieldDefinition).map(e=>{let t=I(e);return{id:e.fieldKey,name:`${e.label} (${e.fieldKey})${ot(e)}`,...t?{warning:t}:{}}})}function ct(e,t){let n=st(e),r=n.find(e=>e.id===t)??null;if(r)return{options:n,problem:r.warning??null,selected:r};if(t.trim()){let e={id:t,name:`${t}(無效欄位)`};return{options:[...n,e],problem:nt,selected:e}}return{options:n,problem:n.length===0?tt:null,selected:null}}function lt(e,t){if(!t.trim())return`依表單欄位:未設定`;let n=e?.fields.find(e=>e.fieldKey===t);return n&&!(0,v.isMemberFieldDefinition)(n)?`依表單欄位:${n.label||t}(非人員選擇欄位)`:`依表單欄位:${n?.label||t}`}function ut(e){return`${e.draftVersion===null?`尚未建立草稿`:`草稿 v${e.draftVersion}`} · ${e.publishedVersion===null?e.hasPublishedVersion?`已發布版本`:`尚未發布`:`已發布 v${e.publishedVersion}`}`}function dt(e,t){return`表單:${e} v${t}`}var ft={display:`grid`,gap:16},pt={alignItems:`start`,display:`grid`,gap:16,gridTemplateColumns:`minmax(0, 1fr) 420px`},mt={border:`1px solid var(--mzn-color-border-neutral)`,borderRadius:6,height:620,minWidth:0,overflow:`hidden`},ht={alignItems:`center`,boxSizing:`border-box`,color:`var(--mzn-color-text-error)`,display:`flex`,height:26,justifyContent:`center`,lineHeight:0,padding:0,width:26},gt={alignItems:`center`,display:`flex`,height:`100%`,justifyContent:`center`,width:`100%`},_t=`workflow-designer-side-panel`,vt=96,yt=`
16
- .${_t} .mzn-form-field--stretch .mzn-form-field__label-area,
17
- .${_t} .mzn-form-field--horizontal .mzn-form-field__label-area {
18
- flex: 0 0 ${vt}px;
19
- width: ${vt}px;
20
- }
21
-
22
- .${_t} .mzn-form-field--stretch .mzn-form-field__data-entry,
23
- .${_t} .mzn-form-field--horizontal .mzn-form-field__data-entry {
24
- min-width: 0;
25
- }
26
- `,bt=`#2563eb`,xt=`#64748b`,St=`var(--mzn-color-text-error, #dc2626)`,Ct=`drop-shadow(0 0 3px rgba(0, 87, 255, 0.85)) drop-shadow(0 0 9px rgba(0, 87, 255, 0.36))`,wt=`
27
- .workflow-selection-delete-control.react-flow__controls-button {
28
- align-items: center !important;
29
- display: flex !important;
30
- height: 26px !important;
31
- justify-content: center !important;
32
- padding: 0 !important;
33
- width: 26px !important;
34
- }
35
-
36
- .workflow-selection-delete-control .mzn-icon {
37
- align-items: center;
38
- display: flex;
39
- justify-content: center;
40
- }
41
-
42
- .workflow-selection-delete-control .mzn-icon svg {
43
- height: 16px !important;
44
- max-height: none !important;
45
- max-width: none !important;
46
- width: 16px !important;
47
- }
48
-
49
- .workflow-edge--selected .react-flow__edge-path,
50
- .react-flow__edge-path.workflow-edge--selected {
51
- filter: ${Ct};
52
- opacity: 1 !important;
53
- stroke: ${xt} !important;
54
- stroke-opacity: 1 !important;
55
- stroke-width: 1.5px !important;
56
- }
57
-
58
- .workflow-edge--selected {
59
- --xy-edge-stroke: ${xt};
60
- --xy-edge-stroke-selected: ${xt};
61
- --xy-edge-stroke-width: 1.5px;
62
- }
63
-
64
- `,Tt={display:`grid`,gap:12},Et={display:`grid`,gap:12},Dt={border:`1px solid var(--mzn-color-border-neutral)`,borderRadius:6,display:`grid`,gap:8,maxHeight:360,overflow:`auto`,padding:12},Ot={borderBottom:`1px solid var(--mzn-color-border-neutral)`,display:`grid`,gap:4,padding:`0 0 8px`},kt={display:`flex`,flexWrap:`wrap`,gap:8},At={alignItems:`center`,display:`flex`,gap:8},jt={flex:`1 1 auto`,minWidth:0},Mt={flex:`0 0 auto`},Nt={display:`grid`,gap:8},Pt={alignContent:`center`,background:`var(--mzn-color-bg-surface)`,border:`1px solid var(--mzn-color-border-neutral)`,borderRadius:6,boxShadow:`0 8px 20px rgba(15, 23, 42, 0.08)`,boxSizing:`border-box`,display:`grid`,gap:4,height:`100%`,minWidth:132,overflow:`visible`,padding:`10px 12px`,textAlign:`center`,width:`100%`},Ft=`0 8px 20px rgba(15, 23, 42, 0.08), 0 0 0 1px var(--mzn-color-primary, #0057ff), 0 0 10px rgba(0, 87, 255, 0.3)`,It=64,Lt=160,Rt=20,zt=64,Bt=180,Vt={...Pt,display:`grid`,gap:8,padding:`10px 12px`},Ht={...Vt,background:`#eff6ff`,border:`1px solid #2563eb`},Ut={...Vt,background:`#f0fdfa`,border:`1px solid #0f766e`},Wt={...Pt,background:`#ffffff`},Gt={...Pt,background:`#ecfdf3`,border:`1px solid #2f855a`},Kt={...Pt,background:`#fff4ed`,border:`1px solid #c2410c`},L={display:`block`,maxWidth:`100%`,minWidth:0},qt={display:`grid`,gap:2,minWidth:0},R=`input`,z=`output`,Jt={endEvent:`結束`,exclusiveGateway:`條件分流`,parallelGateway:`並行處理`,serviceTask:`系統`,startEvent:`開始`,userTask:`簽核`},Yt=[{icon:m.UserIcon,label:`簽核節點`,type:`userTask`},{icon:m.MailIcon,label:`知會節點`,type:`serviceTask`}],Xt=[{icon:m.FilterIcon,label:`條件分流`,type:`exclusiveGateway`}],Zt=[{id:`AND`,name:`全部前置完成`},{id:`OR`,name:`任一前置完成`}],Qt=[{id:`RESTART`,name:`重新送出後從開始重跑`},{id:`FROM_RETURN_POINT`,name:`重新送出後回到退回節點`}],$t=[{id:`NONE`,name:`不提醒`,value:null},{id:`0.5`,name:`過半時提醒`,value:.5},{id:`0.75`,name:`剩四分之一時提醒`,value:.75},{id:`0.9`,name:`剩十分之一時提醒`,value:.9}],en=[{id:`DIRECT`,name:`指定會員`},{id:`DYNAMIC_FORM`,name:`依表單欄位指定`},{id:`ORG_MANAGER`,name:`發起人主管`},{id:`ORG_MANAGER_CHAIN`,name:`主管鏈(簽到指定職等)`},{id:`ORG_UNIT_MANAGER`,name:`指定組織主管`},{id:`ORG_UNIT_MEMBER`,name:`組織任一人`},{id:`ORG_UNIT_POSITION`,name:`組織特定職位`},{id:`POSITION`,name:`指定職位`}],tn=[{id:`COUNT`,name:`人數`},{id:`PERCENTAGE`,name:`百分比`}],B=[{id:`1`,name:`直屬主管`,value:1},{id:`2`,name:`第二層主管`,value:2},{id:`3`,name:`第三層主管`,value:3}],nn=[{id:`NONE`,name:`停止流程並提示`},{id:`DIRECT`,name:`固定改派`},{id:`POSITION`,name:`指定職位`}],rn={id:`UNSUPPORTED`,name:`不支援的備援設定`},an=[{id:`INITIATOR_MANAGER`,name:`改由申請人的直屬主管簽核`},{id:`SKIP_NODE`,name:`跳過此關`},{id:`FAIL`,name:`停止流程並提示`}],on={whenEmpty:`INITIATOR_MANAGER`},sn=[`EQUALS`,`GREATER_THAN`,`GREATER_THAN_OR_EQUALS`,`LESS_THAN`,`LESS_THAN_OR_EQUALS`,`NOT_EQUALS`],cn=[{id:`NONE`,name:`未設定`},{id:`ALL`,name:`所有人`},{id:`ORG_UNIT`,name:`指定組織`},{id:`ORG_UNIT_POSITION`,name:`指定組織職位`}],ln={id:`CUSTOM`,name:`既有自訂規則`},un=`member-001`,dn={display:`flex`,flexDirection:`column`,height:`100%`},fn={flex:1,minHeight:0,overflowY:`auto`},pn={borderTop:`1px solid var(--mzn-color-border-neutral)`,display:`flex`,gap:8,paddingTop:12},mn={fields:[],schemaVersion:1},hn={layout:[],schemaVersion:1},gn={endEvent:V,exclusiveGateway:V,parallelGateway:V,serviceTask:V,startEvent:V,userTask:V};function _n(e,t){return typeof e==`function`?e(t):e}function vn({aiAssistantAvailable:e=!0,embedded:a=!1,formSchemaOverride:h,initialInitiatorPolicyCel:g,initialWorkflowDefinition:v,onInitiatorPolicyChange:b,onWorkflowChange:te,showAiAssistant:se=!1,showDryRun:ce=!0,templateId:C}){let le=t.r(),ue=r.r(),w=n.i(),[T,de]=(0,l.useState)(null),[fe,pe]=(0,l.useState)(null),[me,he]=(0,l.useState)(``),[ge,_e]=(0,l.useState)(null),[ve,ye]=(0,l.useState)(null),be=(0,l.useRef)(null),[xe,Se]=(0,l.useState)(void 0),Ce=(0,l.useRef)([]),Te=(0,l.useRef)([]),E=oe({directory:(0,l.useMemo)(()=>({listOrgUnits:async()=>Ce.current.map(e=>({id:e.id,name:e.name})),listPositions:async()=>Te.current.map(e=>({id:e.id,name:e.name})),searchMembers:async e=>br(await(0,x.searchMemberOptions)(e)).map(e=>({email:e.email,id:e.memberId,name:e.name}))}),[]),initialState:{definition:a&&v!=null?On(v):Mn(),editingEdgeId:null,formDefinitionVersionId:null,formSchema:null,initiatorPolicyCel:a&&g!==void 0?g:null,selectedEdgeIds:[],selectedNodeId:a&&v!=null?v.nodes[0]?.id??`start`:`start`},layout:Pn,onLayout:e=>{let t=Hr(e,be.current);t&&Se(t)}}),D=E.state.definition,k=E.state.formDefinitionVersionId,A=E.state.initiatorPolicyCel,De=E.state.selectedNodeId,j=E.state.selectedEdgeIds,Oe=E.state.editingEdgeId,ke=e=>E.replaceState(t=>({...t,definition:_n(e,t.definition)})),Ae=e=>E.replaceState(t=>({...t,formDefinitionVersionId:_n(e,t.formDefinitionVersionId)})),je=e=>E.replaceState(t=>({...t,initiatorPolicyCel:_n(e,t.initiatorPolicyCel)})),Me=e=>E.replaceState(t=>({...t,selectedNodeId:_n(e,t.selectedNodeId)})),Ne=e=>E.replaceState(t=>({...t,selectedEdgeIds:_n(e,t.selectedEdgeIds)})),Fe=e=>E.replaceState(t=>({...t,editingEdgeId:_n(e,t.editingEdgeId)})),[Ie,M]=(0,l.useState)(null),[Re,N]=(0,l.useState)(null);(0,l.useEffect)(()=>{N(null)},[De]);let[ze,Be]=(0,l.useState)(!0),[Ve,He]=(0,l.useState)(!1),[Ue,We]=(0,l.useState)(!1),[Ke,qe]=(0,l.useState)([]),Je=(0,l.useMemo)(()=>JSON.stringify({formDefinitionVersionId:k,initiatorPolicyCel:A,workflowDefinition:D}),[k,A,D]),Ye=!!me&&Je!==me,[Xe,Ze]=(0,l.useState)(!1),[P,$e]=(0,l.useState)([]),[tt,nt]=(0,l.useState)([]),rt=(0,l.useRef)(0),it=(0,l.useRef)(new Set),[F,at]=(0,l.useState)([]),[I,ot]=(0,l.useState)([]),[st,lt]=(0,l.useState)([]);Ce.current=F,Te.current=I;let[dt,vt]=(0,l.useState)(!1),[bt,xt]=(0,l.useState)(!1),[Ct,Pt]=(0,l.useState)(`{}`),[Ft,It]=(0,l.useState)(null),[Lt,Rt]=(0,l.useState)(null),[zt,Bt]=(0,l.useState)([]),[Vt,Ht]=(0,l.useState)(`loading`),[Ut,Wt]=(0,l.useState)(!1),[Gt,Kt]=(0,l.useState)(!1),[L,qt]=(0,l.useState)(null),[R,z]=(0,l.useState)(!1),[sn,vn]=(0,l.useState)(!1),V=Ye||R?`保存並發布`:fe?`發布草稿`:`已發布`;(0,l.useEffect)(()=>{a?fr():gr()},[a,C]),(0,l.useEffect)(()=>{function e(e){Ye&&(e.preventDefault(),e.returnValue=``)}return window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`beforeunload`,e)}},[Ye]),(0,l.useEffect)(()=>{Er(D)},[D,P]),(0,l.useEffect)(()=>{ke(e=>On(e))},[D.edges,D.nodes]);function bn(){(!Ye||window.confirm(`目前有尚未儲存的流程草稿,確定要離開嗎?`))&&le.push(ue.templates())}let H=(0,l.useMemo)(()=>D.nodes.find(e=>e.id===De)??null,[De,D.nodes]),xn=H?dr(H):!1,Sn=j.length>0||xn,U=(0,l.useCallback)(()=>{E.getState().selectedEdgeIds.forEach(e=>E.dispatch({edgeId:e,type:`deleteEdge`})),H&&dr(H)&&E.dispatch({nodeId:H.id,type:`deleteNode`})},[E,H]);(0,l.useEffect)(()=>{if(!Sn)return;function e(e){(e.key===`Delete`||e.key===`Backspace`)&&(pr(e.target)||(e.preventDefault(),U()))}return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e)}},[Sn,U]);let wn=(0,l.useMemo)(()=>D.edges.find(e=>e.id===Oe)??null,[Oe,D.edges]),Tn=(0,l.useMemo)(()=>j.length===1?D.edges.find(e=>e.id===j[0])??null:null,[j,D.edges]),En=(0,l.useMemo)(()=>j.map(e=>D.edges.find(t=>t.id===e)??null).filter(e=>!!e),[j,D.edges]),W=(0,l.useMemo)(()=>ve??rr(A,ge),[A,ve,ge]),kn=(0,l.useMemo)(()=>D.edges.map(e=>Dn(e,D.nodes,j.includes(e.id))),[j,D.edges,D.nodes]),G=(0,l.useMemo)(()=>K(Ke,k)??K(mr(T?.formVersions??[]),k),[k,Ke,T?.formVersions]),An=(0,l.useMemo)(()=>yr(Ke,G),[Ke,G]),jn=G?.schema??null,Yn=a?h??null:jn;(0,l.useEffect)(()=>{E.getState().formSchema!==Yn&&E.replaceState(e=>({...e,formSchema:Yn}))},[E,Yn]);let q=(0,l.useMemo)(()=>Ur(D),[D]);(0,l.useEffect)(()=>{let e=!0;return(0,x.listWorkflowWebhookEndpoints)({includeDeprecated:!0}).then(t=>{e&&(Bt(t),Ht(`ready`))}).catch(()=>{e&&Ht(`unavailable`)}),()=>{e=!1}},[]);let J=R&&L?L.schema:Yn,ar=(0,l.useMemo)(()=>Vt===`ready`?Le({definition:D,endpoints:zt,formFields:J?.fields??[]})[0]??null:null,[zt,Vt,J,D]),sr=(0,l.useMemo)(()=>D.nodes.map(e=>Cn(e,P,F,I,e.id===De,W,J)),[W,P,F,I,De,J,D.nodes]),Y=(0,l.useMemo)(()=>(0,S.hasConfiguredConditionEdges)(D),[D]),X=(0,l.useMemo)(()=>ir(W),[W]);(0,l.useEffect)(()=>{a&&te?.(D)},[a,D]),(0,l.useEffect)(()=>{a&&b?.(A)},[a,A]);async function fr(){Be(!0),M(null);try{let e=await(0,ee.readOrganizationDirectory)();at(e.orgUnits),ot(e.positions),lt(e.memberships)}catch(e){M(O(e,w))}finally{Be(!1)}}async function gr(){Be(!0),M(null),N(null);try{let[e,t]=await Promise.all([(0,x.readTemplateDesigner)(C),(0,ee.readOrganizationDirectory)()]),n=e.versions.find(e=>e.status===`DRAFT`)??null,r=n??e.versions[0]??null;de(e),pe(n),at(t.orgUnits),ot(t.positions),lt(t.memberships),qe(mr(e.formVersions));let i=On(r?.workflowDefinition??Mn()),a=r?.formDefinitionVersionId??e.formVersions[0]?.id??null,o=r?.initiatorPolicyCel??null;ke(i),Ae(a),je(o),he(JSON.stringify({formDefinitionVersionId:a,initiatorPolicyCel:o,workflowDefinition:i})),_e(r&&!e.template.currentVersionId&&!r.initiatorPolicyCel&&Nn(r.workflowDefinition)?`NONE`:null),ye(null),Me(r?.workflowDefinition.nodes[0]?.id??`start`),Ne([]),Fe(null),qt(null),z(!1)}catch(e){M(O(e,w))}finally{Be(!1)}}async function Z(e){We(!0),M(null);try{let t=await(0,x.searchPublishedFormVersionOptions)(e);qe(yr(mr(t),G))}catch(e){M(O(e,w))}finally{We(!1)}}async function Q(e){Ze(!0),M(null);let t=++rt.current;try{let n=br(await(0,x.searchMemberOptions)(e));$e(e=>Mr(e,n)),t===rt.current&&nt(n)}catch(e){t===rt.current&&M(O(e,w))}finally{t===rt.current&&Ze(!1)}}async function Er(e){let t=Pr(e),n=s.n(t.filter(e=>!P.some(t=>t.memberId===e&&!t.unresolved)),it.current);if(n.length===0)return;let{profiles:r,skippedIds:i}=await s.r(n,x.resolveMemberOptions),a=new Set(r.map(e=>e.memberId)),o=n.filter(e=>!a.has(e)&&!i.includes(e));o.forEach(e=>it.current.add(e)),$e(e=>Mr(e,[...br(r),...[...o,...i].map(xr)]))}async function Dr(e){He(!0),M(null);try{let t=Ur(D),n=ir(W),r=e?ar:null;if(t||n||r){let e=t??n??r??`流程設定未完成`;throw M(e),Error(e)}if(R&&L!==null)await(0,x.composeApprovalTemplateWithForm)({category:T?.template.category??null,categoryId:T?.template.categoryId??null,formDefinitionId:G?.formDefinitionId??null,formDescription:null,formName:G?.formName??T?.template.name??`表單`,initiatorPolicyCel:A,notificationConfig:null,publish:e,schema:L.schema,slaDefaults:null,templateDescription:null,templateId:C??null,templateName:T?.template.name??`模板`,uiSchema:L.uiSchema,workflowDefinition:D}),z(!1),qt(null),await gr();else{let t=fe??await(0,x.forkApprovalTemplate)(C),n=await(0,x.updateApprovalTemplateDraft)({formDefinitionVersionId:k,initiatorPolicyCel:A,versionId:t.id,workflowDefinition:D});pe(n),e&&await(0,x.publishApprovalTemplateVersion)(n.id),await gr()}}catch(e){throw M(O(e,w,D)),e}finally{He(!1)}}async function Or(){await Dr(!1)}async function kr(){await Dr(!0)}function jr(){Pt(JSON.stringify(Qe(J),null,2)),It(null),Rt(null),vt(!0)}function Nr(){bt||vt(!1)}async function Fr(){xt(!0),Rt(null),It(null);try{let e=hr(Ct),t=await(0,x.dryRunApprovalWorkflow)({formData:e,initiatorMemberId:un,initiatorMetadataSnapshot:Tr(un,st),workflowDefinition:D});It(t)}catch(e){Rt(O(e,w))}finally{xt(!1)}}async function Lr(){if(Kt(!0),L!==null)return;let e=G?.formDefinitionId??null;if(!e)qt({schema:mn,uiSchema:hn});else{vn(!0);try{let t=await(0,_.readFormBuilder)(e),n=t.versions.find(e=>e.status===`DRAFT`)??t.versions.find(e=>e.id===t.definition.currentVersionId)??t.versions[0]??null;qt({schema:n?.schema??mn,uiSchema:n?.uiSchema??hn})}catch(e){M(O(e,w))}finally{vn(!1)}}}function Rr(e){let t=(0,y.applyNodeChanges)(e,sr);ke(e=>({...e,nodes:e.nodes.map(e=>{let n=t.find(t=>t.id===e.id);return n?{...e,position:n.position}:e})}))}function Br(e){lr(e,D.nodes)&&e.source&&e.target&&E.dispatch({source:e.source,target:e.target,type:`connectEdge`})}function Vr(e,t){e.stopPropagation(),Ne(n=>e.shiftKey||e.metaKey||e.ctrlKey?ur(n,t.id):[t.id]),Me(null)}function Yr(){Fe(null)}function Zr(e){E.dispatch({nodeType:e,type:`addNode`})}function $r(e){H&&E.dispatch({label:e,nodeId:H.id,type:`renameNode`})}function $(e){if(!H||H.type!==`userTask`)return;let t=H.id,n=H.data.decisionPolicy;E.dispatch({approverResolver:e,nodeId:t,type:`setUserTaskApprover`}),N(null),(0,S.isOrgManagerChainDecisionPolicyInvalid)(e,n)?N({message:`主管鏈會依序加入多位主管,簽核方式已改為「依序簽核」。`,nodeId:t,policyType:`SEQUENTIAL`}):(0,S.isDecisionPolicyUnsatisfiable)(n,e)&&N({message:`簽核者已變更為 ${(0,S.readDesignTimeApproverCount)(e)} 位,不足原本設定的 ${n?.type===`QUORUM`?n.threshold:0} 位門檻,簽核政策已重設為單人簽核,請重新設定。`,nodeId:t,policyType:`SINGLE`})}function ei(e){H&&H.type===`userTask`&&E.dispatch({nodeId:H.id,resubmitStrategy:e,type:`setUserTaskReturnResubmitStrategy`})}function ti(e){H&&H.type===`userTask`&&E.dispatch({nodeId:H.id,requireComment:e,type:`setUserTaskReturnRequireComment`})}function ni(e){H&&H.type===`userTask`&&E.dispatch({nodeId:H.id,sla:e,type:`setUserTaskSla`})}function ri(e){H&&H.type===`userTask`&&E.dispatch({excludeInitiator:e,nodeId:H.id,type:`setUserTaskExcludeInitiator`})}function ii(e){if(!H||H.type!==`userTask`)return;N(null);let t=e.type===`QUORUM`?{...e,threshold:(0,S.composeQuorumThreshold)(e.threshold,e.thresholdType)}:e;E.dispatch({decisionPolicy:t,nodeId:H.id,type:`setUserTaskDecisionPolicy`})}function ai(e){H&&H.type===`userTask`&&E.dispatch({...e,nodeId:H.id,type:`setUserTaskOptions`})}function oi(e){H&&H.type===`serviceTask`&&E.dispatch({action:e,nodeId:H.id,type:`setServiceAction`})}function si(e){ye(e.mode===`ALL`||e.mode===`CUSTOM`?null:e),_e(e.mode===`ALL`||e.mode===`CUSTOM`?null:e.mode),je(or(e,F))}function ci(e){H&&H.type!==`startEvent`&&E.dispatch({nodeId:H.id,triggerMode:e,type:`setNodeTriggerMode`})}function li(e,t){E.dispatch({edgeId:e,isDefault:t,type:`setEdgeDefault`})}function ui({edgeId:e,fieldKey:t,operator:n,value:r}){E.dispatch({edgeId:e,fieldKey:t,operator:n,type:`setEdgeCondition`,value:r})}function di(){E.dispatch({type:`autoLayout`})}return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(`style`,{children:yt}),a?null:(0,d.jsx)(u.PageHeader,{children:(0,d.jsxs)(p.default,{description:ut({draftVersion:fe?.version??null,hasPublishedVersion:!!T?.template.currentVersionId,publishedVersion:T?.versions.find(e=>e.id===T.template.currentVersionId)?.version??null}),onBackClick:bn,title:T?.template.name??`流程設計器`,children:[se?(0,d.jsx)(u.Button,{disabled:!e,onClick:()=>Wt(e=>!e),variant:Ut?`base-primary`:`base-secondary`,children:e?`AI 助理`:`AI 助理(未設定)`}):null,(0,d.jsx)(u.Button,{"aria-label":`儲存草稿`,disabled:Ve||!!q||!!X,icon:m.SaveIcon,iconType:`icon-only`,onClick:()=>void Or(),variant:`base-secondary`,children:`儲存草稿`}),ce?(0,d.jsx)(u.Button,{disabled:ze||!!q||!!X,icon:m.EyeIcon,iconType:`leading`,onClick:jr,variant:`base-secondary`,children:`試跑流程`}):null,(0,d.jsx)(u.Button,{disabled:Ve||!fe&&!Ye&&!R||!!q||!!X||!!ar,icon:m.CheckedIcon,iconType:`leading`,onClick:()=>void kr(),variant:`base-primary`,children:V})]})}),(0,d.jsx)(u.SectionGroup,{children:(0,d.jsx)(u.Section,{children:(0,d.jsxs)(`div`,{style:ft,children:[Ie?(0,d.jsx)(u.Typography,{color:`text-error`,variant:`body`,children:Ie}):null,Re&&Re.nodeId===H?.id&&H.type===`userTask`&&(H.data.decisionPolicy?.type??`SINGLE`)===Re.policyType?(0,d.jsx)(u.Typography,{color:`text-warning`,variant:`body`,children:Re.message}):null,q?(0,d.jsx)(u.Typography,{color:`text-error`,variant:`body`,children:q}):null,X?(0,d.jsx)(u.Typography,{color:`text-error`,variant:`body`,children:X}):null,!q&&ar?(0,d.jsxs)(u.Typography,{color:`text-error`,variant:`body`,children:[`發布前需修正:`,ar]}):null,a?null:(0,d.jsx)(`div`,{style:Et,children:(0,d.jsx)(i.t,{hintText:Y?`已設定條件分流條件。請先移除所有條件,才能更換綁定表單版本。`:void 0,label:`綁定表單版本`,name:`formDefinitionVersionId`,required:!0,children:(0,d.jsxs)(`div`,{style:At,children:[(0,d.jsx)(`div`,{style:jt,children:(0,d.jsx)(u.AutoComplete,{asyncData:!0,disabled:ze||Y,disabledOptionsFilter:!0,emptyText:`沒有符合的已發布表單版本`,isForceClearable:!!k&&!Y,loading:Ue,loadingText:`搜尋表單版本中...`,mode:`single`,onChange:e=>{Y||Ae(e?.id??null)},onClear:()=>{Y||Ae(null)},onSearch:Z,onVisibilityChange:e=>{e&&!Y&&Z(``)},options:[...An],placeholder:`選擇已發布表單版本`,searchDebounceTime:300,value:G})}),(0,d.jsx)(u.Button,{disabled:ze,onClick:()=>{Lr()},style:Mt,variant:`base-secondary`,children:`編輯表單`})]})})}),(0,d.jsxs)(`div`,{style:pt,children:[(0,d.jsx)(`div`,{ref:be,style:mt,children:(0,d.jsxs)(y.ReactFlow,{connectionMode:y.ConnectionMode.Strict,edges:kn,fitView:!0,isValidConnection:e=>lr(e,D.nodes),nodeTypes:gn,nodes:sr,deleteKeyCode:null,multiSelectionKeyCode:[`Shift`,`Meta`,`Control`],onConnect:Br,onEdgeClick:Vr,onNodeClick:(e,t)=>{Me(t.id),Ne([])},onNodesChange:Rr,onPaneClick:()=>{Me(null),Ne([])},onViewportChange:Se,viewport:xe,children:[(0,d.jsx)(y.Background,{}),(0,d.jsx)(`style`,{children:wt}),(0,d.jsx)(y.Controls,{children:Sn?(0,d.jsx)(y.ControlButton,{"aria-label":`刪除選取項目`,className:`workflow-selection-delete-control`,onClick:U,style:ht,title:`刪除選取項目`,children:(0,d.jsx)(`span`,{style:gt,children:(0,d.jsx)(u.Icon,{color:`error`,icon:m.TrashIcon,size:16})})}):null}),(0,d.jsx)(yn,{onApplyAutoLayout:di}),(0,d.jsx)(y.MiniMap,{})]})}),(0,d.jsxs)(`div`,{className:_t,style:Tt,children:[(0,d.jsx)(u.Typography,{component:`h2`,variant:`h3`,children:`流程工具`}),a&&se?(0,d.jsxs)(`div`,{style:Nt,children:[(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`caption`,children:`AI 協助`}),(0,d.jsx)(`div`,{style:kt,children:(0,d.jsx)(u.Button,{disabled:!e,onClick:()=>Wt(e=>!e),size:`sub`,variant:Ut?`base-primary`:`base-secondary`,children:e?`AI 助理`:`AI 助理(未設定)`})})]}):null,(0,d.jsxs)(`div`,{style:Nt,children:[(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`caption`,children:`動作節點`}),(0,d.jsx)(`div`,{style:kt,children:Yt.map(e=>(0,d.jsx)(u.Button,{icon:e.icon,iconType:`leading`,onClick:()=>Zr(e.type),size:`sub`,variant:`base-secondary`,children:e.label},e.type))})]}),(0,d.jsxs)(`div`,{style:Nt,children:[(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`caption`,children:`流程控制`}),(0,d.jsx)(`div`,{style:kt,children:Xt.map(e=>(0,d.jsx)(u.Button,{icon:e.icon,iconType:`leading`,onClick:()=>Zr(e.type),size:`sub`,variant:`base-secondary`,children:e.label},e.type))})]}),En.length>1?vi(En):null,En.length===1&&Tn?yi(Tn):null,En.length===0&&H?pi(H):null]})]})]})})}),bi(wn),!a&&ce?fi():null,se&&e?(0,d.jsx)(we,{controller:E,onClose:()=>Wt(!1),open:Ut}):null,a?null:(0,d.jsx)(f.default,{headerTitle:`編輯表單`,isHeaderDisplay:!0,onClose:()=>Kt(!1),open:Gt,size:`wide`,children:(0,d.jsxs)(`div`,{style:dn,children:[(0,d.jsx)(`div`,{style:fn,children:sn?(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`body`,children:`載入中…`}):(0,d.jsx)(c.t,{onChange:e=>{qt(e)},value:L??{schema:mn,uiSchema:hn}})}),(0,d.jsxs)(`div`,{style:pn,children:[(0,d.jsx)(u.Button,{disabled:sn,onClick:()=>{L!==null&&(z(!0),E.replaceState(e=>({...e,formSchema:L.schema}))),Kt(!1)},variant:`base-primary`,children:`套用`}),(0,d.jsx)(u.Button,{onClick:()=>Kt(!1),variant:`base-secondary`,children:`取消`})]})]})})]});function fi(){let e={formFields:J?.fields??[],memberName:e=>P.find(t=>t.memberId===e&&!t.unresolved)?.displayName??null,orgUnits:F,positions:I};return(0,d.jsx)(u.Modal,{cancelText:`關閉`,confirmText:`執行試跑`,loading:bt,modalType:`standard`,onCancel:Nr,onClose:Nr,onConfirm:()=>void Fr(),open:dt,showModalFooter:!0,showModalHeader:!0,size:`wide`,supportingText:`使用 ${un} 與範例表單資料模擬目前畫布流程,不會建立案件。`,title:`試跑流程`,children:(0,d.jsxs)(`div`,{style:Et,children:[(0,d.jsx)(i.t,{label:`表單資料 JSON`,name:`dryRunFormDataJson`,required:!0,children:(0,d.jsx)(u.Textarea,{onChange:e=>Pt(e.target.value),resize:`vertical`,rows:8,value:Ct})}),Lt?(0,d.jsx)(u.Typography,{color:`text-error`,variant:`body`,children:Lt}):null,Ft?(0,d.jsxs)(`div`,{style:Dt,children:[(0,d.jsx)(u.Typography,{color:Ft.valid?`text-success`:`text-error`,variant:`label-primary-highlight`,children:Ft.valid?`試跑通過`:`試跑失敗`}),Ft.errors.map(e=>(0,d.jsx)(u.Typography,{color:`text-error`,variant:`body`,children:e},e)),Ft.steps.map(t=>(0,d.jsxs)(`div`,{style:Ot,children:[(0,d.jsxs)(u.Typography,{variant:`label-primary-highlight`,children:[t.nodeLabel,` · `,_r(t.status)]}),(0,d.jsxs)(u.Typography,{color:`text-neutral`,variant:`caption`,children:[vr(t.nodeType),t.assigneeMemberId?` · 處理者:${et(t.assigneeMemberId,e)}`:``,t.edgeLabel?` · 來源線段:${t.edgeLabel}`:``]}),t.edgeReason?(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`caption`,children:t.edgeReason}):null,t.entryCondition?(0,d.jsxs)(u.Typography,{color:`text-neutral`,variant:`caption`,children:[`進入條件:`,t.entryConditionMatched?`符合`:`不符合`,` ·`,` `,t.entryCondition]}):null,(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`body`,children:t.message}),(t.status===`SKIPPED`?[]:zr(D,t.nodeId,zt)).map(e=>(0,d.jsxs)(u.Typography,{color:`text-neutral`,variant:`caption`,children:[`將送出 Webhook:`,e.label]},e.key))]},t.id))]}):null]})})}function pi(e){return(0,d.jsxs)(`div`,{style:Et,children:[(0,d.jsx)(u.Typography,{component:`h2`,variant:`h3`,children:`節點屬性`}),(0,d.jsxs)(u.Typography,{color:`text-neutral`,variant:`body`,children:[Jt[e.type],` · `,e.id]}),(0,d.jsx)(i.t,{label:`顯示名稱`,name:`nodeLabel`,required:!0,children:(0,d.jsx)(u.Input,{onChange:e=>$r(e.target.value),value:e.data.label,variant:`base`})}),e.type===`startEvent`?mi():null,e.type===`startEvent`?null:hi(e),e.type===`userTask`?gi(e):null,e.type===`serviceTask`?_i(e):null]})}function mi(){let e=W.mode===`CUSTOM`?[...cn,ln]:[...cn],t=W.mode===`ORG_UNIT`||W.mode===`ORG_UNIT_POSITION`?Cr(F,W.orgUnitId??``):null,n=W.mode===`ORG_UNIT_POSITION`?wr(I,W.positionId??``):null,r=W.mode===`ORG_UNIT_POSITION`?Ar({includeDescendants:!!W.includeDescendants,memberships:st,orgUnitId:W.orgUnitId??``,orgUnits:F,positions:I}):[];return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(i.t,{hintText:W.mode===`CUSTOM`?`這是舊版表達式規則;切換成標準選項後會改由 UI 管理。`:void 0,label:`發起權限`,name:`initiatorPolicyMode`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>{if(e?.id===`CUSTOM`){_e(null),ye(null);return}let t=nr(e?.id??null),n=cr(t);_e(t===`ALL`?null:t),ye(t===`ALL`?null:n),je(or(n,F))},options:e,placeholder:`選擇誰可以發起`,value:K(e,W.mode)})}),W.mode===`ORG_UNIT`||W.mode===`ORG_UNIT_POSITION`?(0,d.jsx)(i.t,{label:`組織`,name:`initiatorOrgUnitId`,required:!0,children:(0,d.jsx)(o.n,{name:`initiatorOrgUnitId`,onChange:e=>si({...W,orgUnitId:e?.id??``,positionId:``,value:e?.id??``}),orgUnits:F,placeholder:`選擇組織`,value:t})}):null,W.mode===`ORG_UNIT`||W.mode===`ORG_UNIT_POSITION`?(0,d.jsx)(i.t,{label:`包含下層`,name:`initiatorIncludeDescendants`,children:(0,d.jsx)(u.Toggle,{checked:!!W.includeDescendants,onChange:e=>si({...W,includeDescendants:e.target.checked,...W.mode===`ORG_UNIT_POSITION`?{positionId:``}:{}})})}):null,W.mode===`ORG_UNIT_POSITION`?(0,d.jsx)(i.t,{label:`職位`,name:`initiatorPositionId`,required:!0,children:(0,d.jsx)(o.r,{disabled:!W.orgUnitId?.trim(),name:`initiatorPositionId`,onChange:e=>si({...W,positionId:e?.id??``}),placeholder:W.orgUnitId?.trim()?`選擇職位`:`請先選擇組織`,positions:r,value:n})}):null]})}function hi(e){let t=D.edges.filter(t=>t.target===e.id).length,n=t<2,r=n?`AND`:e.data.triggerMode??`AND`;return(0,d.jsx)(i.t,{hintText:n?`需要至少兩條前置連線,才可切換為任一前置完成。`:t>1?`${t} 條前置連線會依此規則觸發。`:`只有一條前置連線時,兩種設定效果相同。`,label:`前置條件`,name:`triggerMode`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>n?void 0:ci(Fn(e?.id??null)),options:[...Zt],readOnly:n,value:K(Zt,r)})})}function gi(e){let t=e.data.approverResolver,n=Xn(t.type),r=t.type===`DIRECT`?t.memberIds.map(e=>Sr(P,e)):[],a=t.type===`ORG_UNIT_MANAGER`||t.type===`ORG_UNIT_MEMBER`||t.type===`ORG_UNIT_POSITION`?Cr(F,t.orgUnitId):null,s=t.type===`POSITION`||t.type===`ORG_UNIT_POSITION`?wr(I,t.positionId):null,c=t.type===`ORG_UNIT_POSITION`?Ar({includeDescendants:!!t.includeDescendants,memberships:st,orgUnitId:t.orgUnitId,orgUnits:F,positions:I}):[],l=t.type===`DYNAMIC_FORM`?ct(J,t.formPath):null,f=t.type===`ORG_MANAGER`?er(t.levelsUp):B[0],p=t.type===`ORG_MANAGER`||t.type===`ORG_MANAGER_CHAIN`||t.type===`ORG_UNIT_MANAGER`?t.fallback??{type:`NONE`}:{type:`NONE`},m=(0,ne.readUnsupportedApproverFallbackType)(p),h=m===null?nn:[...nn,rn],g=t.type===`ORG_MANAGER_CHAIN`?Ee(I,t.minPositionLevel):[],_=p.type===`DIRECT`&&p.memberId?Sr(P,p.memberId):null,v=p.type===`POSITION`?wr(I,p.positionId):null,ee=e.data.returnBehavior.resubmitStrategy??`RESTART`,y=e.data.sla??null,b=e.data.excludeInitiator??null,x=y?(0,S.readSlaDurationParts)(y.duration):null,te=x?.unit??`DAY`,oe=Wn(y?.warningAt??null),se=er(y?.escalateLevelsUp??1),ce=Ln(e.data.decisionPolicy),C=zn(e.data.decisionPolicy);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(i.t,{label:`簽核來源`,name:`approverResolverType`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>$(Zn(e?.id??null,I)),options:[...en],value:K(en,n)})}),t.type===`DIRECT`?(0,d.jsx)(i.t,{hintText:ie(e.data.decisionPolicy),label:`簽核者`,name:`memberId`,required:!0,children:(0,d.jsx)(u.AutoComplete,{asyncData:!0,disabledOptionsFilter:!0,emptyText:`沒有符合的成員`,inputProps:{autoCapitalize:`none`,autoCorrect:`off`,name:`workflow-approver-search`,spellCheck:!1},loading:Xe,loadingText:`搜尋成員中...`,mode:`multiple`,onChange:e=>$({memberIds:e.map(e=>e.id),type:`DIRECT`}),onSearch:Q,onVisibilityChange:e=>{e&&(nt([]),Q(``))},options:[...Mr(r,tt)],placeholder:`搜尋姓名或信箱`,searchDebounceTime:300,value:r})}):null,t.type===`DYNAMIC_FORM`?(0,d.jsx)(i.t,{hintText:l?.problem??`簽核人取自申請人送出表單時在該欄位選的人員。`,label:`表單欄位`,name:`approverFormPath`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>$({formPath:e?.id??``,type:`DYNAMIC_FORM`}),options:[...l?.options??[]],placeholder:`選擇人員選擇欄位`,value:l?.selected??void 0})}):null,t.type===`ORG_MANAGER`?(0,d.jsx)(i.t,{hintText:`依發起人的有效會員歸屬與主管解析規則決定簽核人。`,label:`主管層級`,name:`managerLevelsUp`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>$({baseFromInitiator:!0,...t.fallback?{fallback:t.fallback}:{},levelsUp:tr(e?.id??null).value,type:`ORG_MANAGER`}),options:[...B],value:f})}):null,t.type===`ORG_MANAGER_CHAIN`?(0,d.jsx)(i.t,{hintText:`從發起人的直屬主管開始往上,職等比前一位高的主管依序加入,簽到職等達此值的主管為止。沒有職位的主管會略過。`,label:`簽到職等`,name:`minPositionLevel`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>$({...t,minPositionLevel:Number(e?.id??t.minPositionLevel)}),options:[...g],value:K(g,String(t.minPositionLevel))})}):null,t.type===`ORG_UNIT_MANAGER`||t.type===`ORG_UNIT_MEMBER`||t.type===`ORG_UNIT_POSITION`?(0,d.jsx)(i.t,{hintText:t.type===`ORG_UNIT_MANAGER`?`依指定組織或其上層的主管解析規則決定簽核人。`:`依指定組織目前有效會員歸屬建立候選簽核人。`,label:`組織`,name:`orgUnitId`,required:!0,children:(0,d.jsx)(o.n,{name:`orgUnitId`,onChange:e=>$(t.type===`ORG_UNIT_MEMBER`?{includeDescendants:t.includeDescendants,orgUnitId:e?.id??``,type:`ORG_UNIT_MEMBER`}:t.type===`ORG_UNIT_POSITION`?{includeDescendants:t.includeDescendants,orgUnitId:e?.id??``,positionId:``,type:`ORG_UNIT_POSITION`}:{fallback:t.fallback,orgUnitId:e?.id??``,type:`ORG_UNIT_MANAGER`}),orgUnits:F,placeholder:`選擇組織`,value:a})}):null,t.type===`ORG_MANAGER`||t.type===`ORG_MANAGER_CHAIN`||t.type===`ORG_UNIT_MANAGER`?(0,d.jsxs)(d.Fragment,{children:[t.type===`ORG_MANAGER_CHAIN`?null:(0,d.jsx)(i.t,{hintText:`開啟後只取離該員最近一層的主管規則;掛在上層單位、涵蓋範圍較大的規則不會再一併加入簽核人。`,label:`只取最近一層主管`,name:`preferClosestOrgUnit`,children:(0,d.jsx)(u.Toggle,{checked:!!t.preferClosestOrgUnit,inputProps:{id:`preferClosestOrgUnit`,name:`preferClosestOrgUnit`},onChange:e=>$({...t,preferClosestOrgUnit:e.target.checked})})}),(0,d.jsx)(i.t,{hintText:m===null?t.type===`ORG_MANAGER_CHAIN`?`預設會停止流程並提示;若設定固定人,主管鏈在達到簽核職等前就結束時,會再加上該會員作為最後一關。`:`預設會停止流程並提示;若設定固定人,找不到主管時會改派給該會員。`:`此改派設定來自較新版本的 BPMCore,本版本無法執行也無法編輯;請升級後再編輯。這裡選擇其他模式會覆寫原設定。`,label:`無主管時`,name:`approverFallbackMode`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>{e?.id!==`UNSUPPORTED`&&$($n(t,Qn(e?.id??null)))},options:[...h],value:m===null?K(nn,p.type):rn})}),p.type===`DIRECT`?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(i.t,{label:`改派人員`,name:`approverFallbackMemberId`,required:!0,children:(0,d.jsx)(u.AutoComplete,{asyncData:!0,disabledOptionsFilter:!0,emptyText:`沒有符合的成員`,inputProps:{autoCapitalize:`none`,autoCorrect:`off`,name:`workflow-approver-fallback-search`,spellCheck:!1},loading:Xe,loadingText:`搜尋成員中...`,mode:`single`,onChange:e=>$($n(t,{allowInitiatorSelfApproval:p.allowInitiatorSelfApproval,memberId:e?.id??``,type:`DIRECT`})),onSearch:Q,onVisibilityChange:e=>{e&&(nt([]),Q(``))},options:[...Mr(tt,_?[_]:[])],placeholder:`搜尋姓名或信箱`,searchDebounceTime:300,value:_})}),(0,d.jsx)(i.t,{hintText:`預設禁止申請人簽自己的案件;只有此流程允許自簽時才開啟。`,label:`允許自簽`,name:`allowInitiatorSelfApproval`,children:(0,d.jsx)(u.Toggle,{checked:!!p.allowInitiatorSelfApproval,inputProps:{id:`allowInitiatorSelfApproval`,name:`allowInitiatorSelfApproval`},onChange:e=>$($n(t,{allowInitiatorSelfApproval:e.target.checked,memberId:p.memberId,type:`DIRECT`}))})})]}):null,p.type===`POSITION`?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(i.t,{hintText:`指派給目前有效歸屬中擁有此職位的會員;主要歸屬優先。多人時全部成為簽核人,依上方的決策政策處理。`,label:`改派職位`,name:`approverFallbackPositionId`,required:!0,children:(0,d.jsx)(o.r,{name:`approverFallbackPositionId`,onChange:e=>$($n(t,{allowInitiatorSelfApproval:p.allowInitiatorSelfApproval,positionId:e?.id??``,type:`POSITION`})),placeholder:`選擇職位`,positions:I,value:v})}),(0,d.jsx)(i.t,{hintText:`預設禁止申請人簽自己的案件;只有此流程允許自簽時才開啟。`,label:`允許自簽`,name:`allowInitiatorSelfApproval`,children:(0,d.jsx)(u.Toggle,{checked:!!p.allowInitiatorSelfApproval,inputProps:{id:`allowInitiatorSelfApproval`,name:`allowInitiatorSelfApproval`},onChange:e=>$($n(t,{allowInitiatorSelfApproval:e.target.checked,positionId:p.positionId,type:`POSITION`}))})})]}):null]}):null,t.type===`ORG_UNIT_MEMBER`||t.type===`ORG_UNIT_POSITION`?(0,d.jsx)(i.t,{label:`包含下層`,name:`includeDescendants`,children:(0,d.jsx)(u.Toggle,{checked:!!t.includeDescendants,inputProps:{id:`includeDescendants`,name:`includeDescendants`},onChange:e=>$({...t,includeDescendants:e.target.checked,...t.type===`ORG_UNIT_POSITION`?{positionId:``}:{}})})}):null,t.type===`POSITION`?(0,d.jsx)(i.t,{hintText:`指派給目前有效歸屬中擁有此職位的會員;主要歸屬優先。`,label:`職位`,name:`positionId`,required:!0,children:(0,d.jsx)(o.r,{name:`positionId`,onChange:e=>$({positionId:e?.id??``,type:`POSITION`}),placeholder:`選擇職位`,positions:I,value:s})}):null,t.type===`ORG_UNIT_POSITION`?(0,d.jsx)(i.t,{hintText:`只納入指定組織範圍內擁有此職位的有效會員。`,label:`職位`,name:`orgUnitPositionId`,required:!0,children:(0,d.jsx)(o.r,{disabled:!t.orgUnitId.trim(),name:`orgUnitPositionId`,onChange:e=>$({includeDescendants:t.includeDescendants,orgUnitId:t.orgUnitId,positionId:e?.id??``,type:`ORG_UNIT_POSITION`}),placeholder:t.orgUnitId.trim()?`選擇職位`:`請先選擇組織`,positions:c,value:s})}):null,(0,d.jsx)(i.t,{hintText:`決定這一關要幾位簽核者同意才會通過;單人簽核與任一人同意的效果完全相同,皆為其中一人同意即通過。`,label:`決策方式`,name:`decisionPolicy`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:t=>ii(Rn(t?.id??null,e.data.decisionPolicy)),options:[...re.filter(e=>t.type!==`ORG_MANAGER_CHAIN`||e.id===`SEQUENTIAL`||e.id===`PARALLEL_ALL`)],value:ae(ce)})}),ce===`QUORUM`?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(i.t,{label:`門檻計算方式`,name:`quorumThresholdType`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>ii({threshold:C.threshold,thresholdType:Bn(e?.id??null),type:`QUORUM`}),options:[...tn],value:K(tn,C.thresholdType)})}),(0,d.jsx)(i.t,{hintText:C.thresholdType===`PERCENTAGE`?`達到簽核者總數的這個百分比即通過,換算人數時無條件進位;超過 100 的輸入會自動夾至 100。`:`達到這個同意人數即通過;門檻超過實際簽核者人數時,這一關將永遠無法通過,請勿設定超過實際簽核者人數。`,label:C.thresholdType===`PERCENTAGE`?`門檻百分比`:`門檻人數`,name:`quorumThreshold`,required:!0,children:(0,d.jsx)(u.Input,{id:`quorumThreshold`,inputProps:C.thresholdType===`PERCENTAGE`?{max:100,min:1}:{min:1},inputType:`number`,name:`quorumThreshold`,onChange:e=>ii({threshold:(0,S.composeQuorumThreshold)(Number(e.target.value),C.thresholdType),thresholdType:C.thresholdType,type:`QUORUM`}),value:String(C.threshold),variant:`base`})})]}):null,e.data.returnBehavior.allowReturn?(0,d.jsx)(i.t,{hintText:`退回發起人後,重新送出時要從流程開始重跑,或直接回到退回的簽核節點。`,label:`重送策略`,name:`returnResubmitStrategy`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>ei(In(e?.id??null)),options:[...Qt],value:K(Qt,ee)})}):null,e.data.returnBehavior.allowReturn?(0,d.jsx)(i.t,{hintText:`開啟後,簽核者按下退回時必須填寫意見,未填寫會被擋下。`,label:`退回時意見必填`,name:`returnRequireComment`,children:(0,d.jsx)(u.Toggle,{checked:e.data.returnBehavior.requireComment===!0,inputProps:{id:`returnRequireComment`,name:`returnRequireComment`},onChange:e=>ti(e.target.checked)})}):null,(0,d.jsx)(i.t,{hintText:`開啟後可設定簽核期限,逾時將依下方設定處理。`,label:`啟用時效`,name:`slaEnabled`,children:(0,d.jsx)(u.Toggle,{checked:!!y,inputProps:{id:`slaEnabled`,name:`slaEnabled`},onChange:e=>ni(e.target.checked?S.DEFAULT_SLA_CONFIG:null)})}),y&&!x?(0,d.jsx)(i.t,{hintText:`此期限混用了日與時,無法在表單中編輯。請改以單一單位設定,或透過 API 維護。`,label:`時效期限`,name:`slaDurationRaw`,children:(0,d.jsx)(u.Input,{disabled:!0,value:y.duration,variant:`base`})}):null,y&&x?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(i.t,{label:`時效期限`,name:`slaDurationValue`,required:!0,children:(0,d.jsx)(u.Input,{id:`slaDurationValue`,inputProps:{min:1},inputType:`number`,name:`slaDurationValue`,onChange:e=>ni(Kn(y,{unit:te,value:Number(e.target.value)})),value:String(x.value),variant:`base`})}),(0,d.jsx)(i.t,{label:`期限單位`,name:`slaDurationUnit`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>ni(Kn(y,{unit:Vn(e?.id??null),value:x.value})),options:[...S.SLA_DURATION_UNIT_OPTIONS],value:K(S.SLA_DURATION_UNIT_OPTIONS,te)})})]}):null,y&&te===`DAY`?(0,d.jsx)(i.t,{hintText:`工作日會跳過週末與行事曆上的假日,補班日仍計為工作日;行事曆由系統管理者設定。`,label:`計算方式`,name:`slaCalendar`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>ni({...y,calendar:Hn(e?.id??null)}),options:[...S.SLA_CALENDAR_MODE_OPTIONS],value:K(S.SLA_CALENDAR_MODE_OPTIONS,y.calendar??`CALENDAR`)})}):null,y?(0,d.jsx)(i.t,{label:`逾時處理`,name:`slaOnTimeout`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>ni(qn(y,Un(e?.id??null))),options:[...S.SLA_TIMEOUT_ACTION_OPTIONS],value:K(S.SLA_TIMEOUT_ACTION_OPTIONS,y.onTimeout)})}):null,y?.onTimeout===`ESCALATE`?(0,d.jsx)(i.t,{hintText:`逾時後改派給簽核者的上層主管,只會升級一次。`,label:`升級層級`,name:`slaEscalateLevelsUp`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>ni({...y,escalateLevelsUp:tr(e?.id??null).value}),options:[...B],value:se})}):null,y?(0,d.jsx)(i.t,{hintText:`在期限到達前先送出一次提醒。`,label:`預警提醒`,name:`slaWarningAt`,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>ni(Jn(y,Gn(e?.id??null).value)),options:[...$t],value:oe})}):null,(0,d.jsx)(i.t,{hintText:`關閉後,簽核者在此關卡看不到「拒絕」按鈕。`,label:`允許拒絕`,name:`allowReject`,children:(0,d.jsx)(u.Toggle,{checked:e.data.allowReject,inputProps:{id:`allowReject`,name:`allowReject`},onChange:e=>ai({allowReject:e.target.checked})})}),(0,d.jsx)(i.t,{hintText:`關閉後,簽核者無法把此關卡的任務轉派給其他人。`,label:`允許轉派`,name:`allowTransfer`,children:(0,d.jsx)(u.Toggle,{checked:e.data.allowTransfer,inputProps:{id:`allowTransfer`,name:`allowTransfer`},onChange:e=>ai({allowTransfer:e.target.checked})})}),(0,d.jsx)(i.t,{hintText:`開啟後,簽核者可在此關卡臨時加入其他簽核人;會簽為平行處理,加簽則需等加入者簽完才往下。`,label:`允許加簽`,name:`allowAddSigner`,children:(0,d.jsx)(u.Toggle,{checked:e.data.allowAddSigner,inputProps:{id:`allowAddSigner`,name:`allowAddSigner`},onChange:e=>ai({allowAddSigner:e.target.checked})})}),(0,d.jsx)(i.t,{hintText:`開啟後,申請人本人(含其代理人)不會成為此關的簽核人,也不能被轉簽或加簽到此關。`,label:`申請人不可簽核自己的單`,name:`excludeInitiator`,children:(0,d.jsx)(u.Toggle,{checked:!!b,inputProps:{id:`excludeInitiator`,name:`excludeInitiator`},onChange:e=>ri(e.target.checked?on:null)})}),b?(0,d.jsx)(i.t,{label:`排除後沒有簽核人時`,name:`excludeInitiatorWhenEmpty`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:e=>ri({whenEmpty:K(an,e?.id??null)?.id??on.whenEmpty}),options:[...an],value:K(an,b.whenEmpty)})}):null]})}function _i(e){let t=e.data.action,n=Qr(t).map(e=>Sr(P,e)),r=t.type===`NOTIFY`&&t.recipients.type!==`DIRECT`?Ir(t.recipients,P,F,I,J):null;function a(e){let n={memberIds:[...e],type:`DIRECT`};oi(t.type===`NOTIFY`?{...t,recipients:n}:{channels:[`IN_APP`],recipients:n,type:`NOTIFY`})}function o(e){t.type===`NOTIFY`&&oi({...t,webhooks:e})}return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(i.t,{hintText:r?`目前知會對象為「${r}」;在此選擇成員會改為指定成員。`:t.type===`NOTIFY`?`可只設定 Webhook,不指定知會對象。`:void 0,label:`知會對象`,name:`notifyMemberIds`,children:(0,d.jsx)(u.AutoComplete,{asyncData:!0,disabledOptionsFilter:!0,emptyText:`沒有符合的成員`,loading:Xe,loadingText:`搜尋成員中...`,mode:`multiple`,onChange:e=>a(e.map(e=>e.id)),onSearch:Q,onVisibilityChange:e=>{e&&(nt([]),Q(``))},options:[...Mr(n,tt)],overflowStrategy:`wrap`,placeholder:`搜尋姓名或信箱`,searchDebounceTime:300,value:[...n]})}),t.type===`NOTIFY`&&!Pe(t.webhooks)?(0,d.jsxs)(`div`,{style:Et,children:[(0,d.jsx)(u.Typography,{color:`text-warning`,variant:`body`,children:`這個節點的 Webhook 設定格式錯誤,無法在此編輯。清除後可重新新增。`}),(0,d.jsx)(`div`,{children:(0,d.jsx)(u.Button,{onClick:()=>o([]),variant:`destructive-secondary`,children:`清除 Webhook 設定`})})]}):null,t.type===`NOTIFY`&&Pe(t.webhooks)?(0,d.jsx)(Ge,{catalog:zt,catalogState:Vt,formFields:J?.fields??null,onChange:o,targets:(0,S.readNotifyWebhookTargets)(t)}):null]})}function vi(e){return(0,d.jsxs)(`div`,{style:Et,children:[(0,d.jsx)(u.Typography,{component:`h2`,variant:`h3`,children:`已選取線段`}),(0,d.jsxs)(u.Typography,{color:`text-neutral`,variant:`body`,children:[`已選取 `,e.length,` 條線段,可使用 Delete 或控制面板刪除。`]})]})}function yi(e){let t=Xr(e,D.nodes);return(0,d.jsxs)(`div`,{style:Et,children:[(0,d.jsx)(u.Typography,{component:`h2`,variant:`h3`,children:t?`條件設定`:`線段屬性`}),(0,d.jsxs)(u.Typography,{color:`text-neutral`,variant:`body`,children:[e.source,` → `,e.target]}),t?xi(e):(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`body`,children:`這條線會直接把流程送到下一個節點。`})]})}function bi(e){return!e||!Xr(e,D.nodes)?null:(0,d.jsx)(u.Modal,{cancelText:`取消`,confirmButtonProps:{disabled:!e.data.isDefault&&!e.data.condition},confirmText:`完成`,modalType:`standard`,onCancel:Yr,onClose:Yr,onConfirm:Yr,open:!!Oe,showModalFooter:!0,showModalHeader:!0,size:`regular`,supportingText:`條件分流的輸出連線需要指定條件,條件會直接顯示在線上。`,title:`條件設定`,children:xi(e)})}function xi(e){let t=Jr(e,D.nodes),n=Wr(G?.schema??null),r=Gr(G?.schema??null,e.data.conditionFieldKey??null),a=(0,S.readConditionOperatorOptionsForField)(r),o=Kr(r),s=K(a,e.data.conditionOperator??null),c=!e.data.isDefault&&!e.data.condition;return(0,d.jsxs)(`div`,{style:Et,children:[(0,d.jsxs)(u.Typography,{color:`text-neutral`,variant:`body`,children:[`畫布上的這條線目前會顯示「`,(0,d.jsx)(`span`,{style:{color:c?St:void 0},children:t??`請設定條件`}),`」。`]}),(0,d.jsx)(u.Toggle,{checked:!!e.data.isDefault,label:`其他情況走這條`,onChange:t=>li(e.id,t.target.checked)}),e.data.isDefault?(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`body`,children:`其他條件都不符合時,流程會走這條線。`}):(0,d.jsxs)(d.Fragment,{children:[G?null:(0,d.jsx)(u.Typography,{color:`text-neutral`,variant:`body`,children:`請先綁定表單版本,才能選擇條件欄位。`}),(0,d.jsx)(i.t,{label:`條件欄位`,name:`edgeConditionField`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:t=>ui({edgeId:e.id,fieldKey:t?.id??null,operator:null,value:null}),options:[...n],placeholder:`選擇條件欄位`,value:K(n,e.data.conditionFieldKey??null)})}),(0,d.jsx)(i.t,{label:`條件判斷`,name:`edgeConditionOperator`,required:!0,children:(0,d.jsx)(u.Select,{clearable:!1,onChange:t=>ui({edgeId:e.id,operator:(0,S.readConditionOperator)(t?.id??null),value:null}),options:[...a],placeholder:`選擇判斷方式`,value:s})}),s&&qr(s.id)?(0,d.jsx)(i.t,{label:`條件值`,name:`edgeConditionValue`,required:!0,children:o.length>0?(0,d.jsx)(u.Select,{clearable:!1,onChange:t=>ui({edgeId:e.id,value:t?.id??null}),options:[...o],placeholder:`選擇條件值`,value:K(o,e.data.conditionValue??null)}):(0,d.jsx)(u.Input,{onChange:t=>ui({edgeId:e.id,value:t.target.value}),placeholder:`輸入要比對的值`,value:e.data.conditionValue??``,variant:`base`})}):null]})]})}}function yn({onApplyAutoLayout:e}){function t(){e()}return(0,d.jsx)(y.Panel,{position:`top-right`,children:(0,d.jsx)(u.Button,{icon:m.DotGridIcon,iconType:`leading`,onClick:t,size:`sub`,variant:`base-secondary`,children:`自動排版`})})}function V({data:e,selected:t,type:n}){let r=e.approverLines??[e.approverSummary??e.label],i=bn(e),a=H(n,t);return(0,d.jsxs)(`div`,{style:a,children:[Sn(e),(0,d.jsx)(`div`,{style:qt,children:r.map((e,t)=>(0,d.jsx)(u.Typography,{component:`span`,ellipsis:!0,style:L,title:e,variant:`label-primary`,children:e},`${e}_${t}`))}),(0,d.jsx)(u.Typography,{color:`text-neutral`,component:`span`,ellipsis:!0,style:L,title:i,variant:`caption`,children:i})]})}function bn(e){return e.nodeKind===`startEvent`?e.initiatorPolicySummary??`所有人`:e.approverSummary||e.approverLines?e.label:e.nodeKind===`exclusiveGateway`?`條件在線上`:e.nodeKind===`parallelGateway`?`多條路徑同時進行`:Jt[e.nodeKind]}function H(e,t){let n=xn(e);return t?{...n,border:`1px solid var(--mzn-color-primary, #0057ff)`,boxShadow:Ft}:n}function xn(e){return e===`exclusiveGateway`?Ht:e===`parallelGateway`?Ut:e===`startEvent`?Gt:e===`endEvent`?Kt:e===`userTask`?Wt:Pt}function Sn(e){return!e.hasInput&&e.hasOutput?(0,d.jsx)(y.Handle,{id:z,position:y.Position.Right,type:`source`}):e.hasInput&&!e.hasOutput?(0,d.jsx)(y.Handle,{id:R,position:y.Position.Left,type:`target`}):!e.hasInput&&!e.hasOutput?null:[(0,d.jsx)(y.Handle,{id:R,position:y.Position.Left,type:`target`},`target`),(0,d.jsx)(y.Handle,{id:z,position:y.Position.Right,type:`source`},`source`)]}function Cn(e,t,n,r,i,a,o){let s=U(e);return{data:{approverLines:Lr(e,t,n,r,o),approverSummary:Fr(e,t,n,r,o),hasInput:Y(e),hasOutput:X(e),initiatorPolicySummary:e.type===`startEvent`?sr(a,n,r):null,label:e.data.label,nodeKind:e.type},height:s.height,handles:wn(e),id:e.id,initialHeight:s.height,initialWidth:s.width,position:e.position,selected:i,sourcePosition:y.Position.Right,targetPosition:y.Position.Left,type:e.type,width:s.width}}function U(e){return e.type===`exclusiveGateway`||e.type===`parallelGateway`?{height:zt,width:Bt}:e.type===`serviceTask`?{height:It+(Rr(e.data.action)-1)*Rt,width:Lt}:{height:It,width:Lt}}function wn(e){let t=U(e);return[...Y(e)?[Tn(t)]:[],...X(e)?[En(t)]:[]]}function Tn({height:e}){let t=e/2-9/2;return{height:9,id:R,position:y.Position.Left,type:`target`,width:9,x:-9/2,y:t}}function En({height:e,width:t}){let n=e/2-9/2;return{height:9,id:z,position:y.Position.Right,type:`source`,width:9,x:t-9/2,y:n}}function Dn(e,t,n){let r=Jr(e,t),i=Xr(e,t),a=i&&!e.data.isDefault&&!e.data.condition,o=a?St:i?bt:`#475569`,s=a?`#fef2f2`:i?`#eff6ff`:`#ffffff`,c=a?St:i?bt:xt;return{className:n?`workflow-edge--selected`:void 0,data:e.data,id:e.id,label:r,labelBgBorderRadius:6,labelBgPadding:[8,4],labelBgStyle:{fill:s,stroke:c,strokeWidth:1},labelShowBg:!!r,labelStyle:{fill:o,fontSize:12,fontWeight:600},selected:n,source:e.source,sourceHandle:e.sourceHandle,style:{filter:n?Ct:void 0,opacity:1,stroke:xt,strokeOpacity:1,strokeWidth:1.5},target:e.target,targetHandle:e.targetHandle,type:e.type??`smoothstep`}}function W(e,t){return e.type===`startEvent`?e:(e.type===`endEvent`||e.type===`userTask`||e.type===`serviceTask`||e.type,{...e,data:{...e.data,triggerMode:t}})}function On(e){return jn(G(An(kn(e))))}function kn(e){let t=e.edges.map(e=>{let t=e.data??{};return e.data===t?e:{...e,data:t}});return t.some((t,n)=>t!==e.edges[n])?{...e,edges:t}:e}function G(e){let t=e.nodes.map(e=>{if(e.type!==`userTask`)return e;let t=e.data.allowAddSigner??!1,n=e.data.allowReject??!0,r=e.data.allowTransfer??!0,i=!e.data.decisionPolicy;return e.data.allowAddSigner===t&&e.data.allowReject===n&&e.data.allowTransfer===r&&!i?e:{...e,data:{...e.data,allowAddSigner:t,allowReject:n,allowTransfer:r,decisionPolicy:e.data.decisionPolicy??{type:`SINGLE`}}}});return t.some((t,n)=>t!==e.nodes[n])?{...e,nodes:t}:e}function An(e){let t=new Set(e.nodes.filter(e=>fr(e)).map(e=>e.id)),n=e.edges.filter(e=>!t.has(e.source));return n.length===e.edges.length?e:{...e,edges:n}}function jn(e){let t=e.edges.reduce((e,t)=>({...e,[t.target]:(e[t.target]??0)+1}),{}),n=e.nodes.map(e=>e.type===`startEvent`?e:(t[e.id]??0)<2&&e.data.triggerMode!==`AND`?W(e,`AND`):e);return n.some((t,n)=>t!==e.nodes[n])?{...e,nodes:n}:e}function Mn(){return{edges:[],meta:{schemaVersion:1},nodes:[{data:{label:`開始`},id:`start`,position:{x:80,y:160},type:`startEvent`},{data:{endState:`APPROVED`,label:`完成`,triggerMode:`AND`},id:`end`,position:{x:560,y:160},type:`endEvent`}]}}function Nn(e){return e.edges.length===0&&e.nodes.length===2&&e.nodes.some(e=>e.type===`startEvent`)&&e.nodes.some(e=>e.type===`endEvent`)}function Pn(e){let t=new b.graphlib.Graph;return t.setDefaultEdgeLabel(()=>({})),t.setGraph({rankdir:`LR`,ranksep:120}),e.nodes.forEach(e=>{t.setNode(e.id,U(e))}),e.edges.forEach(e=>{t.setEdge(e.source,e.target)}),b.layout(t),{...e,nodes:e.nodes.map(e=>{let n=t.node(e.id);return n?{...e,position:{x:n.x-U(e).width/2,y:n.y-U(e).height/2}}:e})}}function K(e,t){return t?e.find(e=>e.id===t)??null:null}function Fn(e){return e===`OR`?`OR`:`AND`}function In(e){return e===`FROM_RETURN_POINT`?`FROM_RETURN_POINT`:`RESTART`}function Ln(e){return e?.type??`SINGLE`}function Rn(e,t){return e===`QUORUM`?t?.type===`QUORUM`?t:{threshold:S.DEFAULT_QUORUM_THRESHOLD,thresholdType:`COUNT`,type:`QUORUM`}:e===`PARALLEL_ALL`||e===`PARALLEL_ANY`||e===`SEQUENTIAL`?{type:e}:{type:`SINGLE`}}function zn(e){return e?.type===`QUORUM`?{threshold:Number.isFinite(e.threshold)?e.threshold:S.DEFAULT_QUORUM_THRESHOLD,thresholdType:Bn(e.thresholdType??null)}:{threshold:S.DEFAULT_QUORUM_THRESHOLD,thresholdType:`COUNT`}}function Bn(e){return e===`PERCENTAGE`?`PERCENTAGE`:`COUNT`}function Vn(e){return e===`HOUR`?`HOUR`:`DAY`}function Hn(e){return e===`BUSINESS_DAY`?`BUSINESS_DAY`:`CALENDAR`}function Un(e){return S.SLA_TIMEOUT_ACTION_OPTIONS.find(t=>t.id===e)?.id??`REMIND`}function Wn(e){return $t.find(t=>t.value===e)??$t[0]}function Gn(e){return $t.find(t=>t.id===e)??$t[0]}function Kn(e,t){let n=Number.isFinite(t.value)?Math.trunc(t.value):1,r=(0,S.composeSlaDuration)({unit:t.unit,value:n});return{...e,calendar:t.unit===`DAY`?e.calendar??`CALENDAR`:`CALENDAR`,duration:r}}function qn(e,t){return t===`ESCALATE`?{...e,escalateLevelsUp:e.escalateLevelsUp??1,onTimeout:t}:{...Yn(e,`escalateLevelsUp`),onTimeout:t}}function Jn(e,t){return t===null?Yn(e,`warningAt`):{...e,warningAt:t}}function Yn(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Xn(e){return e===`DYNAMIC_FORM`||e===`ORG_MANAGER`||e===`ORG_MANAGER_CHAIN`||e===`ORG_UNIT_MANAGER`||e===`ORG_UNIT_MEMBER`||e===`ORG_UNIT_POSITION`||e===`POSITION`?e:`DIRECT`}function Zn(e,t){let n=Xn(e??`DIRECT`);return n===`DYNAMIC_FORM`?{formPath:``,type:`DYNAMIC_FORM`}:n===`ORG_MANAGER`?{baseFromInitiator:!0,levelsUp:1,type:`ORG_MANAGER`}:n===`ORG_MANAGER_CHAIN`?{minPositionLevel:k(t),type:`ORG_MANAGER_CHAIN`}:n===`ORG_UNIT_MANAGER`?{orgUnitId:``,type:`ORG_UNIT_MANAGER`}:n===`ORG_UNIT_MEMBER`?{includeDescendants:!1,orgUnitId:``,type:`ORG_UNIT_MEMBER`}:n===`ORG_UNIT_POSITION`?{includeDescendants:!1,orgUnitId:``,positionId:``,type:`ORG_UNIT_POSITION`}:n===`POSITION`?{positionId:``,type:`POSITION`}:{memberIds:[],type:`DIRECT`}}function q(e){return e===`DIRECT`||e===`POSITION`?e:`NONE`}function Qn(e){let t=q(e);return t===`DIRECT`?{memberId:``,type:`DIRECT`}:t===`POSITION`?{positionId:``,type:`POSITION`}:{type:`NONE`}}function $n(e,t){return e.type===`ORG_MANAGER`||e.type===`ORG_MANAGER_CHAIN`||e.type===`ORG_UNIT_MANAGER`?{...e,fallback:t}:e}function er(e){return B.find(t=>t.value===e)??B[0]}function tr(e){return B.find(t=>t.id===e)??B[0]}function nr(e){return e===`ORG_UNIT`||e===`ORG_UNIT_POSITION`||e===`NONE`?e:`ALL`}function J(e){let t=e?.trim();if(!t)return{mode:`ALL`,value:``};let n=ar(t,/"([^"]+)" in subject\.orgUnitIds/gu),r=ar(t,/"([^"]+)" in subject\.positionIds/gu);return n.length>0&&r.length>0?{includeDescendants:n.length>1,mode:`ORG_UNIT_POSITION`,orgUnitId:n[0],positionId:r[0],value:n[0]??``}:n.length>0?{includeDescendants:n.length>1,mode:`ORG_UNIT`,orgUnitId:n[0],value:n[0]??``}:{mode:`CUSTOM`,value:t}}function rr(e,t){let n=J(e);return!t||t===`ALL`||t===`NONE`?t===`ALL`||t===`NONE`?{mode:t,value:``}:n:n.mode===t?n:cr(t)}function ir(e){return e.mode===`NONE`?`發起權限需要選擇誰可以發起。`:(e.mode===`ORG_UNIT`||e.mode===`ORG_UNIT_POSITION`)&&!e.orgUnitId?.trim()?`指定組織發起時,需要選擇組織。`:e.mode===`ORG_UNIT_POSITION`&&!e.positionId?.trim()?`指定組織職位發起時,需要選擇職位。`:null}function ar(e,t){return[...e.matchAll(t)].map(e=>e[1]).filter(e=>!!e)}function or(e,t){if(e.mode===`ALL`||e.mode===`NONE`)return null;let n=e.orgUnitId?.trim()??``;if(!n)return null;let r=jr(t,n,!!e.includeDescendants).map(e=>`${JSON.stringify(e)} in subject.orgUnitIds`).join(` || `);if(e.mode===`ORG_UNIT`)return r?`(${r})`:null;let i=e.positionId?.trim()??``;return i&&r?`(${r}) && ${JSON.stringify(i)} in subject.positionIds`:null}function sr(e,t,n){return e.mode===`NONE`?`未設定`:e.mode===`ORG_UNIT`?e.orgUnitId?`組織:${Z(t,e.orgUnitId)}`:`指定組織`:e.mode===`ORG_UNIT_POSITION`?e.orgUnitId&&e.positionId?`組織職位:${Z(t,e.orgUnitId)} / ${Q(n,e.positionId)}`:`指定組織職位`:e.mode===`CUSTOM`?`既有自訂規則`:`所有人`}function cr(e){return{includeDescendants:!0,mode:e,orgUnitId:``,positionId:``,value:``}}function lr(e,t){let n=e.source?t.find(t=>t.id===e.source)??null:null,r=e.target?t.find(t=>t.id===e.target)??null:null;return!!n&&!!r&&e.source!==e.target&&e.sourceHandle===z&&e.targetHandle===R&&!!(n&&X(n))&&!!(r&&Y(r))}function ur(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function dr(e){return e.type!==`startEvent`&&e.type!==`endEvent`}function Y(e){return e.type!==`startEvent`}function X(e){return e.type!==`endEvent`&&!fr(e)}function fr(e){return e.type===`serviceTask`&&e.data.action.type===`NOTIFY`}function pr(e){return e instanceof HTMLElement?e.isContentEditable||e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.tagName===`SELECT`||!!e.closest(`[contenteditable="true"]`):!1}function mr(e){return e.map(e=>({formDefinitionId:e.formDefinitionId,formName:e.formName,id:e.id,name:dt(e.formName,e.version),schema:e.schema}))}function hr(e){let t=JSON.parse(e);if(!gr(t))throw Error(`表單資料 JSON 必須是物件。`);return t}function gr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _r(e){return e===`COMPLETED`?`完成`:e===`PASSED`?`通過`:e===`SKIPPED`?`略過`:e===`STOPPED`?`已停止`:e===`WAITING`?`將等待簽核`:e}function vr(e){return e in Jt?Jt[e]:e}function yr(e,t){return t&&!e.some(e=>e.id===t.id)?[t,...e]:e}function br(e){return e.map(e=>({displayName:e.name,email:e.email,id:e.memberId,memberId:e.memberId,name:Vr(e.name,e.email)}))}function xr(e){return{displayName:`未知會員`,email:``,id:e,memberId:e,name:`未知會員`,unresolved:!0}}function Sr(e,t){return e.find(e=>e.memberId===t)??xr(t)}function Cr(e,t){let n=e.find(e=>e.id===t);return n?o.a(n):null}function wr(e,t){let n=e.find(e=>e.id===t);return n?o.o(n):null}function Z(e,t){return Cr(e,t)?.name??`未指定組織`}function Q(e,t){return wr(e,t)?.name??`未指定職位`}function Tr(e,t){let n=Er(),r=t.filter(t=>t.memberId===e&&Dr(t,n)),i=r.reduce((e,t)=>e&&Or(e,t)<=0?e:t,null);return{customFields:{},managerMemberId:`member-002`,memberId:e,orgCode:`HQ`,orgUnitIds:kr(r.map(e=>e.orgUnitId)),positionId:i?.positionId??null,positionIds:kr(r.map(e=>e.positionId)),primaryOrgUnitId:i?.orgUnitId??null,roles:[`manager`]}}function Er(){return new Date().toISOString().slice(0,10)}function Dr(e,t){return e.effectiveFrom<=t&&(!e.effectiveTo||e.effectiveTo>=t)}function Or(e,t){return e.isPrimary===t.isPrimary?t.effectiveFrom.localeCompare(e.effectiveFrom):e.isPrimary?-1:1}function kr(e){return e.reduce((e,t)=>t&&!e.includes(t)?[...e,t]:e,[])}function Ar({includeDescendants:e,memberships:t,orgUnitId:n,orgUnits:r,positions:i}){let a=new Set(jr(r,n,e)),o=new Set(t.filter(e=>a.has(e.orgUnitId)).map(e=>e.positionId).filter(e=>!!e));return i.filter(e=>o.has(e.id))}function jr(e,t,n){let r=e.find(e=>e.id===t);return r?n?e.filter(e=>e.id===r.id||e.path.startsWith(`${r.path}.`)).map(e=>e.id):[r.id]:t.trim()?[t]:[]}function Mr(e,t){let n=new Map(t.filter(e=>!e.unresolved).map(e=>[e.memberId,e])),r=new Set(e.map(e=>e.memberId)),i=t.filter(e=>!r.has(e.memberId)),a=e.map(e=>(e.unresolved?n.get(e.memberId):null)??e);return i.length>0||a.some((t,n)=>t!==e[n])?[...a,...i]:e}function Nr(e){return e.type===`DIRECT`?e.memberIds:(e.type===`ORG_MANAGER`||e.type===`ORG_MANAGER_CHAIN`||e.type===`ORG_UNIT_MANAGER`)&&e.fallback?.type===`DIRECT`&&e.fallback.memberId?[e.fallback.memberId]:[]}function Pr(e){return[...new Set(e.nodes.flatMap(e=>e.type===`userTask`?Nr(e.data.approverResolver):e.type===`serviceTask`?Qr(e.data.action):[]))]}function Fr(e,t,n,r,i){return e.type===`userTask`?Ir(e.data.approverResolver,t,n,r,i):null}function Ir(e,t,n,r,i){return e.type===`DIRECT`?Br(e.memberIds,t,`未指定簽核者`):e.type===`ORG_MANAGER`?er(e.levelsUp).name:e.type===`ORG_MANAGER_CHAIN`?`主管鏈:簽到職等 ${e.minPositionLevel}`:e.type===`ORG_UNIT_MANAGER`?`組織主管:${Z(n,e.orgUnitId)}`:e.type===`ORG_UNIT_MEMBER`?`組織任一人:${Z(n,e.orgUnitId)}`:e.type===`ORG_UNIT_POSITION`?`組織職位:${Z(n,e.orgUnitId)} / ${Q(r,e.positionId)}`:e.type===`POSITION`?`職位:${Q(r,e.positionId)}`:e.type===`DYNAMIC_FORM`?lt(i,e.formPath):`自訂表達式`}function Lr(e,t,n,r,i){if(e.type!==`serviceTask`)return null;let a=e.data.action,o=a.type===`NOTIFY`&&a.recipients.type!==`DIRECT`?[Ir(a.recipients,t,n,r,i)]:Qr(a).map(e=>Sr(t,e).name),s=(0,S.readNotifyWebhookTargets)(a).length,c=[...o,...s?[`Webhook ${s} 個`]:[]];return c.length?c:[`未指定知會對象`]}function Rr(e){let t=e.type===`NOTIFY`&&e.recipients.type!==`DIRECT`?1:Qr(e).length,n=+!!(0,S.readNotifyWebhookTargets)(e).length;return Math.max(1,t+n)}function zr(e,t,n){let r=e.nodes.find(e=>e.id===t);return r?.type===`serviceTask`&&r.data.action.type===`NOTIFY`&&Pe(r.data.action.webhooks)?(0,S.readNotifyWebhookTargets)(r.data.action).map(e=>({key:e.id,label:Oe(n,e.endpoint)?.label??j(e.endpoint)})):[]}function Br(e,t,n){let r=e.map(e=>Sr(t,e).name);return r.length===0?n:r.length<=2?r.join(`、`):`${r.slice(0,2).join(`、`)} 等 ${r.length} 人`}function Vr(e,t){return a.t(e,t)}function Hr(e,t){let n=t?.getBoundingClientRect();if(!n||e.nodes.length===0)return null;let r=e.nodes.reduce((e,t)=>{let n=U(t);return{maxX:Math.max(e.maxX,t.position.x+n.width),maxY:Math.max(e.maxY,t.position.y+n.height),minX:Math.min(e.minX,t.position.x),minY:Math.min(e.minY,t.position.y)}},{maxX:-1/0,maxY:-1/0,minX:1/0,minY:1/0});return(0,y.getViewportForBounds)({height:r.maxY-r.minY,width:r.maxX-r.minX,x:r.minX,y:r.minY},n.width,n.height,.1,1,.2)}function Ur(e){let t=e.nodes.find(e=>e.type===`userTask`&&!!(0,S.readApproverResolverIssue)(e.data.approverResolver)),n=e.nodes.find(e=>e.type===`userTask`&&!!(0,S.readExcludeInitiatorIssue)(e.data.excludeInitiator)),r=e.nodes.map(e=>(0,S.readNotifyServiceTaskIssue)(e)).find(e=>e!==null)??null,i=e.edges.find(t=>Xr(t,e.nodes)&&!t.data.isDefault&&!t.data.condition),a=e.nodes.find(e=>e.type===`userTask`&&(0,S.isOrgManagerChainDecisionPolicyInvalid)(e.data.approverResolver,e.data.decisionPolicy));return t&&t.type===`userTask`?(0,S.readApproverResolverIssue)(t.data.approverResolver):a&&a.type===`userTask`?`簽核節點「${a.data.label}」使用「沿主管鏈簽核」時,決策方式必須是「依序簽核或全部同意」,否則任一位主管簽完就會結案。`:n&&n.type===`userTask`?(0,S.readExcludeInitiatorIssue)(n.data.excludeInitiator):r||(i?`條件分流的每條輸出連線都需要先設定條件。`:null)}function Wr(e){return e?.fields.map(e=>({fieldType:e.type,id:e.fieldKey,name:`${e.label} (${e.fieldKey})`}))??[]}function Gr(e,t){return t?e?.fields.find(e=>e.fieldKey===t)??null:null}function Kr(e){return e?e.type===`boolean`?[{id:`true`,name:`是`},{id:`false`,name:`否`}]:(0,v.isFormStaticOptionFieldDefinition)(e)?e.options.map(e=>({id:e.value,name:e.label})):[]:[]}function qr(e){return sn.includes(e)}function Jr(e,t){if(e.data.label)return e.data.label;if(Xr(e,t))return Yr(e);if(Zr(e,t))return`同時進行`}function Yr(e){return e.data.isDefault?`其他情況`:`請設定條件`}function Xr(e,t){return t.some(t=>t.id===e.source&&t.type===`exclusiveGateway`)}function Zr(e,t){return t.some(t=>t.id===e.source&&t.type===`parallelGateway`)}function Qr(e){return e.type===`NOTIFY`&&e.recipients.type===`DIRECT`?e.recipients.memberIds:[]}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return vn}});
65
- //# sourceMappingURL=designer-CTXMqCD2.cjs.map