Form.vue 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. <!-- Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/ -->
  2. <script setup lang="ts">
  3. import { isEqual, cloneDeep, merge, isEmpty } from 'lodash-es'
  4. import type { ConcreteComponent, Ref } from 'vue'
  5. import {
  6. computed,
  7. ref,
  8. nextTick,
  9. shallowRef,
  10. reactive,
  11. toRef,
  12. watch,
  13. markRaw,
  14. useSlots,
  15. } from 'vue'
  16. import { FormKit, FormKitSchema } from '@formkit/vue'
  17. import type {
  18. FormKitPlugin,
  19. FormKitSchemaNode,
  20. FormKitSchemaCondition,
  21. FormKitNode,
  22. FormKitClasses,
  23. FormKitSchemaDOMNode,
  24. FormKitSchemaComponent,
  25. FormKitMessageProps,
  26. } from '@formkit/core'
  27. import { getNode, createMessage, reset } from '@formkit/core'
  28. import type { Except, SetRequired } from 'type-fest'
  29. import { refDebounced, watchOnce } from '@vueuse/shared'
  30. import getUuid from '@shared/utils/getUuid'
  31. import log from '@shared/utils/log'
  32. import { camelize } from '@shared/utils/formatter'
  33. import UserError from '@shared/errors/UserError'
  34. import type {
  35. EnumObjectManagerObjects,
  36. EnumFormUpdaterId,
  37. FormUpdaterRelationField,
  38. FormUpdaterQuery,
  39. FormUpdaterQueryVariables,
  40. ObjectAttributeValue,
  41. } from '@shared/graphql/types'
  42. import { QueryHandler } from '@shared/server/apollo/handler'
  43. import { useObjectAttributeLoadFormFields } from '@shared/entities/object-attributes/composables/useObjectAttributeLoadFormFields'
  44. import { useObjectAttributeFormFields } from '@shared/entities/object-attributes/composables/useObjectAttributeFormFields'
  45. import testFlags from '@shared/utils/testFlags'
  46. import { edgesToArray } from '@shared/utils/helpers'
  47. import type { FormUpdaterTrigger } from '@shared/types/form'
  48. import type { EntityObject } from '@shared/types/entity'
  49. import { getFirstFocusableElement } from '@shared/utils/getFocusableElements'
  50. import { parseGraphqlId } from '@shared/graphql/utils'
  51. import { useFormUpdaterQuery } from './graphql/queries/formUpdater.api'
  52. import { FormHandlerExecution, FormValidationVisibility } from './types'
  53. import { getNodeByName as getFormkitFieldNode } from './utils'
  54. import type {
  55. ChangedField,
  56. FormData,
  57. FormFieldAdditionalProps,
  58. FormFieldValue,
  59. FormHandler,
  60. FormHandlerFunction,
  61. FormSchemaField,
  62. FormSchemaLayout,
  63. FormSchemaNode,
  64. FormValues,
  65. ReactiveFormSchemData,
  66. } from './types'
  67. import FormLayout from './FormLayout.vue'
  68. import FormGroup from './FormGroup.vue'
  69. export interface Props {
  70. id?: string
  71. schema?: FormSchemaNode[]
  72. formUpdaterId?: EnumFormUpdaterId
  73. handlers?: FormHandler[]
  74. changeFields?: Record<string, Partial<FormSchemaField>>
  75. // Maybe in the future this is no longer needed, when FormKit supports group
  76. // without value grouping below group name (https://github.com/formkit/formkit/issues/461).
  77. flattenFormGroups?: string[]
  78. schemaData?: Except<ReactiveFormSchemData, 'fields'>
  79. formKitPlugins?: FormKitPlugin[]
  80. formKitSectionsSchema?: Record<
  81. string,
  82. Partial<FormKitSchemaNode> | FormKitSchemaCondition
  83. >
  84. class?: FormKitClasses | string | Record<string, boolean>
  85. // Can be used to define initial values on frontend side and fetched schema from the server.
  86. initialValues?: Partial<FormValues>
  87. initialEntityObject?: EntityObject
  88. queryParams?: Record<string, unknown>
  89. validationVisibility?: FormValidationVisibility
  90. disabled?: boolean
  91. autofocus?: boolean
  92. // Some special properties for working with object attribute fields inside of a form schema.
  93. useObjectAttributes?: boolean
  94. objectAttributeSkippedFields?: string[]
  95. // Implement the submit in this way, because we need to react on async usage of the submit function.
  96. // Don't forget that to submit a form with "Enter" key, you need to add a button with type="submit" inside of the form.
  97. // Or to have a button outside of form with "form" attribite with the same value as the form id.
  98. // After this method is called, form resets its values and state. If you need to call something afterwards,
  99. // like make route navigation, you can return a function from the submit handler, which will be called after the form reset.
  100. onSubmit?: (
  101. values: FormData,
  102. ) => Promise<void | (() => void)> | void | (() => void)
  103. }
  104. // Zammad currently expects formIds to be BigInts. Maybe convert to UUIDs later.
  105. // const formId = `form-${getUuid()}`
  106. // This is the formId generation logic from the legacy desktop app.
  107. let formId = new Date().getTime() + Math.floor(Math.random() * 99999).toString()
  108. formId = formId.substr(formId.length - 9, 9)
  109. const props = withDefaults(defineProps<Props>(), {
  110. schema: () => {
  111. return []
  112. },
  113. changeFields: () => {
  114. return reactive({})
  115. },
  116. validationVisibility: FormValidationVisibility.Submit,
  117. useObjectAttributes: false,
  118. })
  119. const slots = useSlots()
  120. const hasSchema = computed(
  121. () => Boolean(slots.default) || Boolean(props.schema),
  122. )
  123. const formSchemaInitialized = ref(false)
  124. if (!hasSchema.value) {
  125. log.error(
  126. 'No schema defined. Please use the schema prop or the default slot for the schema.',
  127. )
  128. }
  129. // Rename prop 'class' for usage in the template, because of reserved word
  130. const localClass = toRef(props, 'class')
  131. const emit = defineEmits<{
  132. (
  133. e: 'changed',
  134. fieldName: string,
  135. newValue: FormFieldValue,
  136. oldValue: FormFieldValue,
  137. ): void
  138. (e: 'node', node: FormKitNode): void
  139. (e: 'settled'): void
  140. }>()
  141. const showInitialLoadingAnimation = ref(false)
  142. const debouncedShowInitialLoadingAnimation = refDebounced(
  143. showInitialLoadingAnimation,
  144. 300,
  145. )
  146. const formKitInitialNodesSettled = ref(false)
  147. const formNode: Ref<FormKitNode | undefined> = ref()
  148. const formElement = ref<HTMLElement>()
  149. const changeFields = toRef(props, 'changeFields')
  150. const updaterChangedFields = new Set<string>()
  151. const changeInitialValue = new Map<string, FormFieldValue>()
  152. const getNodeByName = (id: string) => {
  153. return getFormkitFieldNode(formId, id)
  154. }
  155. const findNodeByName = (name: string) => {
  156. return formNode.value?.find(name, 'name')
  157. }
  158. const autofocusFirstInput = () => {
  159. nextTick(() => {
  160. const firstInput = getFirstFocusableElement(formElement.value)
  161. firstInput?.focus()
  162. firstInput?.scrollIntoView({ block: 'nearest' })
  163. })
  164. }
  165. const setFormNode = (node: FormKitNode) => {
  166. formNode.value = node
  167. // Save the initial entity object in the form node context, so that fields can use it.
  168. if (node.context && props.initialEntityObject) {
  169. node.context.initialEntityObject = props.initialEntityObject
  170. }
  171. node.settled.then(() => {
  172. showInitialLoadingAnimation.value = false
  173. nextTick(() => {
  174. changeInitialValue.forEach((value, fieldName) => {
  175. findNodeByName(fieldName)?.input(value, false)
  176. })
  177. changeInitialValue.clear()
  178. formKitInitialNodesSettled.value = true
  179. // Reset directly after the initial request.
  180. updaterChangedFields.clear()
  181. const formName = node.context?.id || node.name
  182. testFlags.set(`${formName}.settled`)
  183. emit('settled')
  184. if (props.autofocus) autofocusFirstInput()
  185. })
  186. })
  187. node.on('autofocus', autofocusFirstInput)
  188. emit('node', node)
  189. }
  190. const formNodeContext = computed(() => formNode.value?.context)
  191. // Build the flat value when its requested for specific form groups.
  192. const getFlatValues = (values: FormValues, formGroups: string[]) => {
  193. const flatValues = {
  194. ...values,
  195. }
  196. formGroups.forEach((formGroup) => {
  197. Object.assign(flatValues, flatValues[formGroup])
  198. delete flatValues[formGroup]
  199. })
  200. return flatValues
  201. }
  202. // Use the node context value, instead of the v-model, because of performance reason.
  203. const values = computed<FormValues>(() => {
  204. if (!formNodeContext.value) {
  205. return {}
  206. }
  207. if (!props.flattenFormGroups) return formNodeContext.value.value
  208. return getFlatValues(formNodeContext.value.value, props.flattenFormGroups)
  209. })
  210. const relationFields: FormUpdaterRelationField[] = []
  211. const relationFieldBelongsToObjectField: Record<string, string> = {}
  212. const formUpdaterProcessing = computed(
  213. () => formNode.value?.context?.state.formUpdaterProcessing || false,
  214. )
  215. let delayedSubmit = false
  216. const onSubmitRaw = () => {
  217. if (formUpdaterProcessing.value) {
  218. delayedSubmit = true
  219. }
  220. }
  221. const onSubmit = (values: FormData) => {
  222. // Needs to be checked, because the 'onSubmit' function is not required.
  223. if (!props.onSubmit) return undefined
  224. const flatValues = props.flattenFormGroups
  225. ? getFlatValues(values, props.flattenFormGroups)
  226. : values
  227. const emitValues = {
  228. ...flatValues,
  229. formId,
  230. }
  231. const submitResult = props.onSubmit(emitValues)
  232. if (submitResult instanceof Promise) {
  233. return submitResult
  234. .then((afterReset) => {
  235. // it's possible to destroy Form before this is called
  236. if (!formNode.value) return
  237. reset(formNode.value, values)
  238. if (typeof afterReset === 'function') afterReset()
  239. })
  240. .catch((errors: UserError) => {
  241. if (errors instanceof UserError) {
  242. formNode.value?.setErrors(
  243. // TODO: we need to check/style the general error output when we want to show it related to the form
  244. errors.generalErrors as string[],
  245. errors.getFieldErrorList(),
  246. )
  247. }
  248. })
  249. }
  250. if (formNode.value) {
  251. reset(formNode.value, values)
  252. }
  253. if (typeof submitResult === 'function') {
  254. submitResult()
  255. }
  256. return submitResult
  257. }
  258. let formUpdaterQueryHandler: QueryHandler<
  259. FormUpdaterQuery,
  260. FormUpdaterQueryVariables
  261. >
  262. const delayedSubmitPlugin = (node: FormKitNode) => {
  263. node.on('message-removed', async ({ payload }) => {
  264. if (payload.key === 'formUpdaterProcessing' && delayedSubmit) {
  265. // We need to wait on the "next tick", so that the validation for updated fields is ready.
  266. setTimeout(() => {
  267. delayedSubmit = false
  268. node.submit()
  269. }, 0)
  270. }
  271. })
  272. return false
  273. }
  274. const localFormKitPlugins = computed(() => {
  275. return [delayedSubmitPlugin, ...(props.formKitPlugins || [])]
  276. })
  277. const formConfig = computed(() => {
  278. return {
  279. validationVisibility: props.validationVisibility,
  280. }
  281. })
  282. // Define the additional component library for the used components which are not form fields.
  283. // Because of a typescript error, we need to cased the type: https://github.com/formkit/formkit/issues/274
  284. const additionalComponentLibrary = {
  285. FormLayout: markRaw(FormLayout) as unknown as ConcreteComponent,
  286. FormGroup: markRaw(FormGroup) as unknown as ConcreteComponent,
  287. }
  288. // Define the static schema, which will be filled with the real fields from the `schemaData`.
  289. const staticSchema = ref<FormKitSchemaNode[]>([])
  290. const fixedAndSkippedFields: string[] = []
  291. const schemaData = reactive<ReactiveFormSchemData>({
  292. fields: {},
  293. values,
  294. ...props.schemaData,
  295. })
  296. const internalFieldCamelizeName: Record<string, string> = {}
  297. const getInternalId = (item?: { id?: string; internalId?: number }) => {
  298. if (!item) return undefined
  299. if (item.internalId) return item.internalId
  300. if (!item.id) return undefined
  301. return parseGraphqlId(item.id).id
  302. }
  303. let initialEntityObjectAttributeMap: Record<string, FormFieldValue> = {}
  304. const setInitialEntityObjectAttributeMap = (
  305. initialEntityObject = props.initialEntityObject,
  306. ) => {
  307. if (isEmpty(initialEntityObject)) return
  308. const { objectAttributeValues } = initialEntityObject
  309. if (!objectAttributeValues) return
  310. // Reduce object attribute values to flat structure
  311. initialEntityObjectAttributeMap =
  312. objectAttributeValues.reduce((acc: Record<string, FormFieldValue>, cur) => {
  313. const { attribute } = cur
  314. if (!attribute || !attribute.name) return acc
  315. acc[attribute.name] = cur.value
  316. return acc
  317. }, {}) || {}
  318. }
  319. // Initialize the initial entity object attribute map during the setup in a static way.
  320. // It will maybe be updated later, when the resetForm is used with a different entity object.
  321. setInitialEntityObjectAttributeMap()
  322. const getInitialEntityObjectValue = (
  323. fieldName: string,
  324. initialEntityObject = props.initialEntityObject,
  325. ): FormFieldValue => {
  326. if (isEmpty(initialEntityObject)) return undefined
  327. let value: FormFieldValue
  328. if (relationFieldBelongsToObjectField[fieldName]) {
  329. const belongsToObject =
  330. initialEntityObject[relationFieldBelongsToObjectField[fieldName]]
  331. if (!belongsToObject) return undefined
  332. if ('edges' in belongsToObject) {
  333. value = edgesToArray(
  334. belongsToObject as { edges?: { node: { internalId: number } }[] },
  335. ).map((item) => getInternalId(item))
  336. } else {
  337. value = getInternalId(belongsToObject)
  338. }
  339. }
  340. if (!value) {
  341. const targetFieldName = internalFieldCamelizeName[fieldName] || fieldName
  342. value =
  343. targetFieldName in initialEntityObjectAttributeMap
  344. ? initialEntityObjectAttributeMap[targetFieldName]
  345. : initialEntityObject[targetFieldName]
  346. }
  347. return value
  348. }
  349. const getResetFormValues = (
  350. rootNode: FormKitNode,
  351. values: FormValues,
  352. object?: EntityObject,
  353. groupNode?: FormKitNode,
  354. resetDirty = true,
  355. ) => {
  356. const resetValues: FormValues = {}
  357. const dirtyNodes: FormKitNode[] = []
  358. const setResetFormValue = (
  359. name: string,
  360. value: FormFieldValue,
  361. parentName?: string,
  362. ) => {
  363. if (parentName) {
  364. resetValues[parentName] ||= {}
  365. ;(resetValues[parentName] as Record<string, FormFieldValue>)[name] = value
  366. return
  367. }
  368. resetValues[name] = value
  369. }
  370. Object.entries(schemaData.fields).forEach(([field, { props }]) => {
  371. const formElement = props.id ? getNode(props.id) : getNodeByName(props.name)
  372. let parentName = ''
  373. if (formElement?.parent && formElement?.parent.name !== rootNode.name) {
  374. parentName = formElement.parent.name
  375. }
  376. // Do not use the parentName, when we are in group node reset context.
  377. const groupName = groupNode?.name
  378. if (groupName) {
  379. if (parentName !== groupName) return
  380. parentName = ''
  381. }
  382. if (!resetDirty && formElement?.context?.state.dirty) {
  383. dirtyNodes.push(formElement)
  384. setResetFormValue(field, formElement._value as FormFieldValue, parentName)
  385. return
  386. }
  387. if (field in values) {
  388. setResetFormValue(field, values[field], parentName)
  389. return
  390. }
  391. if (parentName && parentName in values) {
  392. const value = (values[parentName] as Record<string, FormFieldValue>)[
  393. field
  394. ]
  395. setResetFormValue(field, value, parentName)
  396. return
  397. }
  398. const objectValue = getInitialEntityObjectValue(field, object)
  399. if (objectValue !== undefined) {
  400. setResetFormValue(field, objectValue, parentName)
  401. }
  402. })
  403. return {
  404. dirtyNodes,
  405. resetValues,
  406. }
  407. }
  408. const resetForm = (
  409. values: FormValues = {},
  410. object: EntityObject | undefined = undefined,
  411. { resetDirty = true }: { resetDirty?: boolean } = {},
  412. groupNode: FormKitNode | undefined = undefined,
  413. ) => {
  414. if (!formNode.value) return
  415. const rootNode = formNode.value
  416. if (object) setInitialEntityObjectAttributeMap(object)
  417. const { dirtyNodes, resetValues } = getResetFormValues(
  418. rootNode,
  419. values,
  420. object,
  421. groupNode,
  422. resetDirty,
  423. )
  424. reset(
  425. groupNode || rootNode,
  426. Object.keys(resetValues).length ? resetValues : undefined,
  427. )
  428. // keep dirty nodes as dirty
  429. // TODO: check if we need to skip the formUpdater???
  430. dirtyNodes.forEach((node) => {
  431. node.input(node._value, false)
  432. })
  433. }
  434. defineExpose({
  435. formNode,
  436. formId,
  437. getNodeByName,
  438. findNodeByName,
  439. resetForm,
  440. })
  441. const localInitialValues: FormValues = { ...props.initialValues }
  442. const initializeFieldRelation = (
  443. fieldName: string,
  444. relation: FormSchemaField['relation'],
  445. belongsToObjectField?: string,
  446. ) => {
  447. if (relation) {
  448. relationFields.push({
  449. name: fieldName,
  450. relation: relation.type,
  451. filterIds: relation.filterIds,
  452. })
  453. }
  454. if (belongsToObjectField) {
  455. relationFieldBelongsToObjectField[fieldName] = belongsToObjectField
  456. }
  457. }
  458. const setInternalField = (fieldName: string, internal: boolean) => {
  459. if (!internal) return
  460. internalFieldCamelizeName[fieldName] = camelize(fieldName)
  461. }
  462. const updateSchemaLink = (
  463. specificProps: FormFieldAdditionalProps,
  464. fieldName: string,
  465. ) => {
  466. // native fields don't have link attribute, and we don't have a way to get rendered link from graphql
  467. const values = (props.initialEntityObject?.objectAttributeValues ||
  468. []) as ObjectAttributeValue[]
  469. const attribute = values.find(({ attribute }) => attribute.name === fieldName)
  470. if (attribute?.renderedLink) {
  471. specificProps.link = attribute.renderedLink
  472. }
  473. }
  474. const updateSchemaDataField = (
  475. field: FormSchemaField | SetRequired<Partial<FormSchemaField>, 'name'>,
  476. ) => {
  477. const {
  478. show,
  479. updateFields,
  480. relation,
  481. props: specificProps = {},
  482. ...fieldProps
  483. } = field
  484. const showField = show ?? schemaData.fields[field.name]?.show ?? true
  485. // Not needed in this context.
  486. delete fieldProps.if
  487. // Special handling for the disabled prop, so that the form can handle also
  488. // the disable state from outside.
  489. if ('disabled' in fieldProps && !fieldProps.disabled) {
  490. fieldProps.disabled = undefined
  491. }
  492. updateSchemaLink(fieldProps, field.name)
  493. if (schemaData.fields[field.name]) {
  494. schemaData.fields[field.name] = {
  495. show: showField,
  496. updateFields: updateFields || false,
  497. props: Object.assign(
  498. schemaData.fields[field.name].props,
  499. fieldProps,
  500. specificProps,
  501. ),
  502. }
  503. } else {
  504. initializeFieldRelation(
  505. field.name,
  506. relation,
  507. specificProps?.belongsToObjectField,
  508. )
  509. setInternalField(field.name, Boolean(fieldProps.internal))
  510. const combinedFieldProps = Object.assign(fieldProps, specificProps)
  511. // Select the correct initial value (at this time localInitialValues has not already the information
  512. // from the initial entity object, so we need to check it manually).
  513. combinedFieldProps.value =
  514. field.name in localInitialValues
  515. ? localInitialValues[field.name]
  516. : getInitialEntityObjectValue(field.name) ?? combinedFieldProps.value
  517. // Save current initial value for later usage, when not already exists.
  518. if (!(field.name in localInitialValues))
  519. localInitialValues[field.name] = combinedFieldProps.value
  520. schemaData.fields[field.name] = {
  521. show: showField,
  522. updateFields: updateFields || false,
  523. props: combinedFieldProps,
  524. }
  525. }
  526. }
  527. const updateChangedFields = (
  528. changedFields: Record<string, Partial<FormSchemaField>>,
  529. ) => {
  530. const handleUpdatedInitialFieldValue = (
  531. fieldName: string,
  532. value: FormFieldValue,
  533. directly: boolean,
  534. field: Partial<FormSchemaField>,
  535. ) => {
  536. if (value === undefined) return
  537. if (directly) {
  538. field.value = value
  539. } else if (!formKitInitialNodesSettled.value) {
  540. changeInitialValue.set(fieldName, value)
  541. }
  542. }
  543. Object.keys(changedFields).forEach(async (fieldName) => {
  544. if (!schemaData.fields[fieldName]) return
  545. const { initialValue, value, ...changedFieldProps } =
  546. changedFields[fieldName]
  547. const field: SetRequired<Partial<FormSchemaField>, 'name'> = {
  548. ...changedFieldProps,
  549. name: fieldName,
  550. }
  551. const showField =
  552. !schemaData.fields[fieldName].show && changedFieldProps.show
  553. // This happens for the initial updater, when the form is not settled yet or the field was not rendered yet.
  554. // In this ase we need to remember the changes and do it afterwards after the form is settled the first time.
  555. // Sometimes the value from the server is the "real" initial value, for this the `initialValue` can be used.
  556. handleUpdatedInitialFieldValue(
  557. fieldName,
  558. value ?? initialValue,
  559. showField || initialValue !== undefined,
  560. field,
  561. )
  562. // When a field will be visible with the update call, we need to wait before on a settled form, before we
  563. // continue (so that we have all values present inside the form).
  564. // This situtation can happen, when the form is used very fast.
  565. if (
  566. formKitInitialNodesSettled.value &&
  567. !schemaData.fields[fieldName].show &&
  568. changedFieldProps.show &&
  569. !formNode.value?.isSettled
  570. ) {
  571. await formNode.value?.settled
  572. }
  573. updaterChangedFields.add(fieldName)
  574. updateSchemaDataField(field)
  575. if (!formKitInitialNodesSettled.value) return
  576. if (
  577. !showField &&
  578. value !== undefined &&
  579. !isEqual(value, values.value[fieldName])
  580. ) {
  581. updaterChangedFields.add(fieldName)
  582. const node = changedFieldProps.id
  583. ? getNode(changedFieldProps.id)
  584. : getNodeByName(fieldName)
  585. node?.input(value, false)
  586. }
  587. })
  588. nextTick(() => {
  589. updaterChangedFields.clear()
  590. formNode.value?.store.remove('formUpdaterProcessing')
  591. })
  592. }
  593. const formHandlerExecution: Record<
  594. FormHandlerExecution,
  595. FormHandlerFunction[]
  596. > = {
  597. [FormHandlerExecution.Initial]: [],
  598. [FormHandlerExecution.FieldChange]: [],
  599. }
  600. if (props.handlers) {
  601. props.handlers.forEach((handler) => {
  602. Object.values(FormHandlerExecution).forEach((execution) => {
  603. if (handler.execution.includes(execution)) {
  604. formHandlerExecution[execution].push(handler.callback)
  605. }
  606. })
  607. })
  608. }
  609. const executeFormHandler = (
  610. execution: FormHandlerExecution,
  611. currentValues: FormValues,
  612. changedField?: ChangedField,
  613. ) => {
  614. if (formHandlerExecution[execution].length === 0) return
  615. formHandlerExecution[execution].forEach((handler) => {
  616. handler(
  617. execution,
  618. formNode.value,
  619. currentValues,
  620. changeFields,
  621. updateSchemaDataField,
  622. schemaData,
  623. changedField,
  624. props.initialEntityObject,
  625. )
  626. })
  627. }
  628. const formUpdaterVariables = shallowRef<FormUpdaterQueryVariables>()
  629. let nextFormUpdaterVariables: Maybe<FormUpdaterQueryVariables>
  630. const executeFormUpdaterRefetch = () => {
  631. if (!nextFormUpdaterVariables) return
  632. formUpdaterVariables.value = nextFormUpdaterVariables
  633. // Reset the next variables so that it's not triggered a second time.
  634. nextFormUpdaterVariables = null
  635. }
  636. const handlesFormUpdater = (
  637. trigger: FormUpdaterTrigger,
  638. fieldName: string,
  639. newValue: FormFieldValue,
  640. oldValue: FormFieldValue,
  641. ) => {
  642. if (!props.formUpdaterId || !formUpdaterQueryHandler) return
  643. // We mark this as raw, because we want no deep reactivity on the form updater query variables.
  644. nextFormUpdaterVariables = markRaw({
  645. id: props.initialEntityObject?.id,
  646. formUpdaterId: props.formUpdaterId,
  647. data: {
  648. ...values.value,
  649. [fieldName]: newValue,
  650. },
  651. meta: {
  652. // We need a unique requestId, so that the query will always be executed on changes, also when the variables
  653. // are the same until the last request, because it could be that core workflow is setting a value back.
  654. requestId: getUuid(),
  655. formId,
  656. changedField: {
  657. name: fieldName,
  658. newValue,
  659. oldValue,
  660. },
  661. },
  662. relationFields,
  663. })
  664. formNode.value?.store.set(
  665. createMessage({
  666. blocking: true,
  667. key: 'formUpdaterProcessing',
  668. value: true,
  669. visible: false,
  670. }),
  671. )
  672. if (trigger !== 'blur') executeFormUpdaterRefetch()
  673. }
  674. const previousValues = new WeakMap<FormKitNode, FormFieldValue>()
  675. const changedInputValueHandling = (inputNode: FormKitNode) => {
  676. inputNode.on('commit', ({ payload: newValue, origin: node }) => {
  677. const oldValue = previousValues.get(node)
  678. if (isEqual(newValue, oldValue)) return
  679. if (!formKitInitialNodesSettled.value) {
  680. previousValues.set(node, cloneDeep(newValue))
  681. return
  682. }
  683. if (
  684. inputNode.props.triggerFormUpdater &&
  685. !updaterChangedFields.has(node.name)
  686. ) {
  687. handlesFormUpdater(
  688. inputNode.props.formUpdaterTrigger,
  689. node.name,
  690. newValue,
  691. oldValue,
  692. )
  693. }
  694. emit('changed', node.name, newValue, oldValue)
  695. executeFormHandler(FormHandlerExecution.FieldChange, values.value, {
  696. name: node.name,
  697. newValue,
  698. oldValue,
  699. })
  700. previousValues.set(node, cloneDeep(newValue))
  701. updaterChangedFields.delete(node.name)
  702. })
  703. inputNode.on('blur', async () => {
  704. if (inputNode.props.formUpdaterTrigger !== 'blur') return
  705. if (!formNode.value?.isSettled) await formNode.value?.settled
  706. if (nextFormUpdaterVariables) executeFormUpdaterRefetch()
  707. })
  708. inputNode.hook.message((payload: FormKitMessageProps, next) => {
  709. if (payload.key === 'submitted' && formUpdaterProcessing.value) {
  710. payload.value = false
  711. }
  712. return next(payload)
  713. })
  714. return false
  715. }
  716. const buildStaticSchema = () => {
  717. const { getFormFieldSchema, getFormFieldsFromScreen } =
  718. useObjectAttributeFormFields(fixedAndSkippedFields)
  719. const buildFormKitField = (
  720. field: FormSchemaField,
  721. ): FormKitSchemaComponent => {
  722. const fieldId = field.id || `${field.name}-${formId}`
  723. return {
  724. $cmp: 'FormKit',
  725. if: field.if ? field.if : `$fields.${field.name}.show`,
  726. bind: `$fields.${field.name}.props`,
  727. props: {
  728. type: field.type,
  729. key: fieldId,
  730. name: field.name,
  731. id: fieldId,
  732. formId,
  733. plugins: [changedInputValueHandling],
  734. triggerFormUpdater: field.triggerFormUpdater ?? !!props.formUpdaterId,
  735. },
  736. }
  737. }
  738. const getLayoutType = (
  739. layoutNode: FormSchemaLayout,
  740. ): FormKitSchemaDOMNode | FormKitSchemaComponent => {
  741. let layoutField: FormKitSchemaDOMNode | FormKitSchemaComponent
  742. if ('component' in layoutNode) {
  743. layoutField = {
  744. $cmp: layoutNode.component,
  745. props: layoutNode.props,
  746. }
  747. } else {
  748. layoutField = {
  749. $el: layoutNode.element,
  750. attrs: layoutNode.attrs,
  751. }
  752. }
  753. if (layoutNode.if) {
  754. layoutField.if = layoutNode.if
  755. }
  756. return layoutField
  757. }
  758. type ResolveFormSchemaNode = Exclude<FormSchemaNode, string>
  759. type ResolveFormKitSchemaNode = Exclude<FormKitSchemaNode, string>
  760. const resolveSchemaNode = (
  761. node: ResolveFormSchemaNode,
  762. ): Maybe<ResolveFormKitSchemaNode | ResolveFormKitSchemaNode[]> => {
  763. if ('isLayout' in node && node.isLayout) {
  764. return getLayoutType(node)
  765. }
  766. if ('isGroupOrList' in node && node.isGroupOrList) {
  767. return {
  768. $cmp: 'FormKit',
  769. ...(node.if && { if: node.if }),
  770. props: {
  771. type: node.type,
  772. name: node.name,
  773. id: node.name,
  774. key: node.name,
  775. plugins: node.plugins,
  776. },
  777. }
  778. }
  779. if ('object' in node && getFormFieldSchema && getFormFieldsFromScreen) {
  780. if ('name' in node && node.name && !node.type) {
  781. const { screen, object, ...fieldNode } = node
  782. const resolvedField = getFormFieldSchema(fieldNode.name, object, screen)
  783. if (!resolvedField) return null
  784. node = {
  785. ...resolvedField,
  786. ...fieldNode,
  787. } as FormSchemaField
  788. } else if ('screen' in node && !('name' in node)) {
  789. const resolvedFields = getFormFieldsFromScreen(node.screen, node.object)
  790. const formKitFields: ResolveFormKitSchemaNode[] = []
  791. resolvedFields.forEach((screenField) => {
  792. updateSchemaDataField(screenField)
  793. formKitFields.push(buildFormKitField(screenField))
  794. })
  795. return formKitFields
  796. }
  797. }
  798. updateSchemaDataField(node as FormSchemaField)
  799. return buildFormKitField(node as FormSchemaField)
  800. }
  801. const resolveSchema = (schema: FormSchemaNode[] = props.schema) => {
  802. return schema.reduce((resolvedSchema: FormKitSchemaNode[], node) => {
  803. if (typeof node === 'string') {
  804. resolvedSchema.push(node)
  805. return resolvedSchema
  806. }
  807. const resolvedNode = resolveSchemaNode(node)
  808. if (!resolvedNode) return resolvedSchema
  809. if ('children' in node) {
  810. const childrens = Array.isArray(node.children)
  811. ? [...resolveSchema(node.children)]
  812. : node.children
  813. resolvedSchema.push({
  814. ...(resolvedNode as Exclude<FormKitSchemaNode, string>),
  815. children: childrens,
  816. })
  817. return resolvedSchema
  818. }
  819. if (Array.isArray(resolvedNode)) {
  820. resolvedSchema.push(...resolvedNode)
  821. } else {
  822. resolvedSchema.push(resolvedNode)
  823. }
  824. return resolvedSchema
  825. }, [])
  826. }
  827. staticSchema.value = resolveSchema()
  828. }
  829. watchOnce(formKitInitialNodesSettled, () => {
  830. watch(
  831. changeFields,
  832. (newValue) => {
  833. updateChangedFields(newValue)
  834. },
  835. {
  836. deep: true,
  837. },
  838. )
  839. })
  840. watch(
  841. () => props.schemaData,
  842. () => Object.assign(schemaData, props.schemaData),
  843. {
  844. deep: true,
  845. },
  846. )
  847. const setFormSchemaInitialized = () => {
  848. if (!formSchemaInitialized.value) {
  849. formSchemaInitialized.value = true
  850. }
  851. }
  852. const initializeFormSchema = () => {
  853. buildStaticSchema()
  854. if (props.formUpdaterId) {
  855. formUpdaterVariables.value = markRaw({
  856. id: props.initialEntityObject?.id,
  857. formUpdaterId: props.formUpdaterId,
  858. data: localInitialValues,
  859. meta: {
  860. initial: true,
  861. formId,
  862. },
  863. relationFields,
  864. })
  865. formUpdaterQueryHandler = new QueryHandler(
  866. useFormUpdaterQuery(
  867. formUpdaterVariables as Ref<FormUpdaterQueryVariables>,
  868. {
  869. fetchPolicy: 'no-cache',
  870. },
  871. ),
  872. )
  873. formUpdaterQueryHandler.onResult((queryResult) => {
  874. // Execute the form handler function so that they can manipulate the form updater result.
  875. if (!formSchemaInitialized.value) {
  876. executeFormHandler(FormHandlerExecution.Initial, localInitialValues)
  877. }
  878. if (queryResult?.data.formUpdater) {
  879. updateChangedFields(
  880. changeFields.value
  881. ? merge(queryResult.data.formUpdater, changeFields.value)
  882. : queryResult.data.formUpdater,
  883. )
  884. }
  885. setFormSchemaInitialized()
  886. })
  887. } else {
  888. executeFormHandler(FormHandlerExecution.Initial, localInitialValues)
  889. if (changeFields.value) updateChangedFields(changeFields.value)
  890. setFormSchemaInitialized()
  891. }
  892. }
  893. // TODO: maybe we should react on schema changes and rebuild the static schema with a new form-id and re-rendering of
  894. // the complete form (= use the formId as the key for the whole form to trigger the re-rendering of the component...)
  895. if (props.schema) {
  896. showInitialLoadingAnimation.value = true
  897. if (props.useObjectAttributes) {
  898. // TODO: rebuild schema, when object attributes
  899. // was changed from outside(not such important,
  900. // because we have currently the reload solution like in the desktop view).
  901. if (props.objectAttributeSkippedFields) {
  902. fixedAndSkippedFields.push(...props.objectAttributeSkippedFields)
  903. }
  904. const objectAttributeObjects: EnumObjectManagerObjects[] = []
  905. const addObjectAttributeToObjects = (object: EnumObjectManagerObjects) => {
  906. if (objectAttributeObjects.includes(object)) return
  907. objectAttributeObjects.push(object)
  908. }
  909. const detectObjectAttributeObjects = (
  910. schema: FormSchemaNode[] = props.schema,
  911. ) => {
  912. schema.forEach((item) => {
  913. if (typeof item === 'string') return
  914. if ('object' in item) {
  915. if ('name' in item && item.name && !item.type) {
  916. fixedAndSkippedFields.push(item.name)
  917. }
  918. addObjectAttributeToObjects(item.object)
  919. }
  920. if ('children' in item && Array.isArray(item.children)) {
  921. detectObjectAttributeObjects(item.children)
  922. }
  923. })
  924. }
  925. detectObjectAttributeObjects()
  926. // We need only to fetch object attributes, when there are used in the given schema.
  927. if (objectAttributeObjects.length > 0) {
  928. const { objectAttributesLoading } = useObjectAttributeLoadFormFields(
  929. objectAttributeObjects,
  930. )
  931. const unwatchTriggerFormInitialize = watch(
  932. objectAttributesLoading,
  933. (loading) => {
  934. if (!loading) {
  935. nextTick(() => unwatchTriggerFormInitialize())
  936. initializeFormSchema()
  937. }
  938. },
  939. { immediate: true },
  940. )
  941. } else {
  942. initializeFormSchema()
  943. }
  944. } else {
  945. initializeFormSchema()
  946. }
  947. }
  948. </script>
  949. <script lang="ts">
  950. export default {
  951. inheritAttrs: false,
  952. }
  953. </script>
  954. <template>
  955. <div
  956. v-if="debouncedShowInitialLoadingAnimation"
  957. class="flex items-center justify-center"
  958. >
  959. <CommonIcon name="mobile-loading" animation="spin" />
  960. </div>
  961. <FormKit
  962. v-if="
  963. hasSchema &&
  964. ((formSchemaInitialized && Object.keys(schemaData.fields).length > 0) ||
  965. $slots.default)
  966. "
  967. v-bind="$attrs"
  968. :id="id"
  969. type="form"
  970. novalidate
  971. :config="formConfig"
  972. :form-class="localClass"
  973. :actions="false"
  974. :incomplete-message="false"
  975. :plugins="localFormKitPlugins"
  976. :sections-schema="formKitSectionsSchema"
  977. :disabled="disabled"
  978. @node="setFormNode"
  979. @submit="onSubmit"
  980. @submit-raw="onSubmitRaw"
  981. >
  982. <slot name="before-fields" />
  983. <slot
  984. name="default"
  985. :schema="staticSchema"
  986. :data="schemaData"
  987. :library="additionalComponentLibrary"
  988. >
  989. <div
  990. v-show="
  991. formKitInitialNodesSettled && !debouncedShowInitialLoadingAnimation
  992. "
  993. ref="formElement"
  994. >
  995. <FormKitSchema
  996. :schema="staticSchema"
  997. :data="schemaData"
  998. :library="additionalComponentLibrary"
  999. />
  1000. </div>
  1001. </slot>
  1002. <slot name="after-fields" />
  1003. </FormKit>
  1004. </template>