Form.vue 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  1. <!-- Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/ -->
  2. <script setup lang="ts">
  3. import { getNode, createMessage } from '@formkit/core'
  4. import { FormKit, FormKitMessages, FormKitSchema } from '@formkit/vue'
  5. import { refDebounced, watchOnce } from '@vueuse/shared'
  6. import { isEqual, cloneDeep, merge, isEmpty, isObject } from 'lodash-es'
  7. import {
  8. useTemplateRef,
  9. computed,
  10. ref,
  11. nextTick,
  12. shallowRef,
  13. reactive,
  14. toRef,
  15. watch,
  16. markRaw,
  17. useSlots,
  18. onBeforeUnmount,
  19. effectScope,
  20. } from 'vue'
  21. import { NotificationTypes } from '#shared/components/CommonNotifications/types.ts'
  22. import { useNotifications } from '#shared/components/CommonNotifications/useNotifications.ts'
  23. import { useObjectAttributeFormFields } from '#shared/entities/object-attributes/composables/useObjectAttributeFormFields.ts'
  24. import { useObjectAttributeLoadFormFields } from '#shared/entities/object-attributes/composables/useObjectAttributeLoadFormFields.ts'
  25. import UserError from '#shared/errors/UserError.ts'
  26. import type {
  27. EnumObjectManagerObjects,
  28. EnumFormUpdaterId,
  29. FormUpdaterRelationField,
  30. FormUpdaterQuery,
  31. FormUpdaterQueryVariables,
  32. ObjectAttributeValue,
  33. FormUpdaterMetaInput,
  34. FormUpdaterChangedFieldInput,
  35. } from '#shared/graphql/types.ts'
  36. import { parseGraphqlId } from '#shared/graphql/utils.ts'
  37. import { I18N, i18n } from '#shared/i18n.ts'
  38. import { QueryHandler } from '#shared/server/apollo/handler/index.ts'
  39. import type { EntityObject } from '#shared/types/entity.ts'
  40. import type {
  41. FormUpdaterAdditionalParams,
  42. FormUpdaterOptions,
  43. FormUpdaterTrigger,
  44. } from '#shared/types/form.ts'
  45. import { camelize } from '#shared/utils/formatter.ts'
  46. import { getFirstFocusableElement } from '#shared/utils/getFocusableElements.ts'
  47. import getUuid from '#shared/utils/getUuid.ts'
  48. import { edgesToArray } from '#shared/utils/helpers.ts'
  49. import log from '#shared/utils/log.ts'
  50. import { markup } from '#shared/utils/markup.ts'
  51. import testFlags from '#shared/utils/testFlags.ts'
  52. import FormGroup from './FormGroup.vue'
  53. import FormLayout from './FormLayout.vue'
  54. import { useFormUpdaterQuery } from './graphql/queries/formUpdater.api.ts'
  55. import { getFormClasses } from './initializeFormClasses.ts'
  56. import { FormHandlerExecution, FormValidationVisibility } from './types.ts'
  57. import {
  58. getNodeByName as getFormkitFieldNode,
  59. getNodeId,
  60. setErrors,
  61. } from './utils.ts'
  62. import type {
  63. ChangedField,
  64. FormSubmitData,
  65. FormFieldAdditionalProps,
  66. FormFieldValue,
  67. FormHandler,
  68. FormHandlerFunction,
  69. FormOnSubmitFunctionCallbacks,
  70. FormSchemaField,
  71. FormSchemaLayout,
  72. FormSchemaNode,
  73. FormValues,
  74. ReactiveFormSchemData,
  75. FormResetData,
  76. FormResetOptions,
  77. } from './types.ts'
  78. import type {
  79. FormKitPlugin,
  80. FormKitSchemaNode,
  81. FormKitSchemaCondition,
  82. FormKitNode,
  83. FormKitClasses,
  84. FormKitSchemaDOMNode,
  85. FormKitSchemaComponent,
  86. FormKitMessageProps,
  87. } from '@formkit/core'
  88. import type { Except, SetRequired } from 'type-fest'
  89. import type { Component, Ref } from 'vue'
  90. export interface Props {
  91. id?: string
  92. schema?: FormSchemaNode[]
  93. schemaData?: Except<ReactiveFormSchemData, 'fields' | 'flags'>
  94. schemaComponentLibrary?: Record<string, Component>
  95. handlers?: FormHandler[]
  96. changeFields?: Record<string, Partial<FormSchemaField>>
  97. formId?: string
  98. formUpdaterId?: EnumFormUpdaterId
  99. formUpdaterInitialOnly?: boolean
  100. formUpdaterAdditionalParams?: FormUpdaterAdditionalParams
  101. // Maybe in the future this is no longer needed, when FormKit supports group
  102. // without value grouping below group name (https://github.com/formkit/formkit/issues/461).
  103. flattenFormGroups?: string[]
  104. formKitPlugins?: FormKitPlugin[]
  105. formKitSectionsSchema?: Record<
  106. string,
  107. Partial<FormKitSchemaNode> | FormKitSchemaCondition
  108. >
  109. class?: FormKitClasses | string | Record<string, boolean>
  110. formClass?: string | Record<string, string>
  111. // Can be used to define initial values on frontend side and fetched schema from the server.
  112. initialValues?: Partial<FormValues>
  113. initialEntityObject?: EntityObject
  114. validationVisibility?: FormValidationVisibility
  115. disabled?: boolean
  116. shouldAutofocus?: boolean
  117. // Some special properties for working with object attribute fields inside of a form schema.
  118. useObjectAttributes?: boolean
  119. objectAttributeSkippedFields?: string[]
  120. clearValuesAfterSubmit?: boolean
  121. // Implement the submit in this way, because we need to react on async usage of the submit function.
  122. // Don't forget that to submit a form with "Enter" key, you need to add a button with type="submit" inside of the form.
  123. // Or to have a button outside of form with "form" attribite with the same value as the form id.
  124. // After this method is called, form resets its values and state. If you need to call something afterwards,
  125. // like make route navigation, you can return a function from the submit handler, which will be called after the form reset.
  126. // When you return "false" inside the submit function the handling will be stopped.
  127. onSubmit?: (
  128. values: FormSubmitData,
  129. flags?: Record<string, boolean>,
  130. ) =>
  131. | Promise<void | (() => void) | FormOnSubmitFunctionCallbacks | false>
  132. | void
  133. | (() => void)
  134. | FormOnSubmitFunctionCallbacks
  135. | false
  136. }
  137. const props = withDefaults(defineProps<Props>(), {
  138. schema: () => {
  139. return []
  140. },
  141. changeFields: () => {
  142. return reactive({})
  143. },
  144. validationVisibility: FormValidationVisibility.Submit,
  145. useObjectAttributes: false,
  146. })
  147. const formId = props.formId ? props.formId : getUuid()
  148. const slots = useSlots()
  149. const hasSchema = computed(
  150. () => Boolean(slots.default) || Boolean(props.schema),
  151. )
  152. const formSchemaInitialized = ref(false)
  153. if (!hasSchema.value) {
  154. log.error(
  155. 'No schema defined. Please use the schema prop or the default slot for the schema.',
  156. )
  157. }
  158. // Rename prop 'class' for usage in the template, because of reserved word
  159. const localClass = toRef(props, 'class')
  160. const emit = defineEmits<{
  161. changed: [
  162. fieldName: string,
  163. newValue: FormFieldValue,
  164. oldValue: FormFieldValue,
  165. ]
  166. node: [node: FormKitNode]
  167. settled: []
  168. focused: []
  169. }>()
  170. const showInitialLoadingAnimation = ref(false)
  171. const debouncedShowInitialLoadingAnimation = refDebounced(
  172. showInitialLoadingAnimation,
  173. 300,
  174. )
  175. const formKitInitialNodesSettled = ref(false)
  176. const formInitialSettled = ref(false)
  177. const formResetRunning = ref(false)
  178. const formNode: Ref<FormKitNode | undefined> = ref()
  179. const formElement = useTemplateRef('form')
  180. const changeFields = toRef(props, 'changeFields')
  181. const updaterChangedFields = new Set<string>()
  182. const changeInitialValue = new Map<string, FormFieldValue>()
  183. const getNodeByName = (id: string) => {
  184. return getFormkitFieldNode(formId, id)
  185. }
  186. const findNodeByName = (name: string) => {
  187. return formNode.value?.find(name, 'name')
  188. }
  189. const autofocusFirstInput = (node: FormKitNode) => {
  190. nextTick(() => {
  191. const firstInput = getFirstFocusableElement(formElement.value)
  192. firstInput?.focus()
  193. firstInput?.scrollIntoView({ block: 'nearest' })
  194. const formName = node.context?.id || node.name
  195. testFlags.set(`${formName}.focused`)
  196. emit('focused')
  197. })
  198. }
  199. const setInitialEntityObjectToContext = (
  200. node: FormKitNode,
  201. object = props.initialEntityObject,
  202. ) => {
  203. if (node.context && object) {
  204. node.context.initialEntityObject = object
  205. }
  206. }
  207. const setFormNode = (node: FormKitNode) => {
  208. formNode.value = node
  209. setInitialEntityObjectToContext(node)
  210. node.settled.then(() => {
  211. showInitialLoadingAnimation.value = false
  212. nextTick(() => {
  213. changeInitialValue.forEach((value, fieldName) => {
  214. findNodeByName(fieldName)?.input(value, false)
  215. })
  216. changeInitialValue.clear()
  217. formKitInitialNodesSettled.value = true
  218. // Reset directly after the initial request.
  219. updaterChangedFields.clear()
  220. const formName = node.context?.id || node.name
  221. testFlags.set(`${formName}.settled`)
  222. emit('settled')
  223. formInitialSettled.value = true
  224. executeFormHandler(FormHandlerExecution.InitialSettled, values.value)
  225. if (props.shouldAutofocus) autofocusFirstInput(node)
  226. })
  227. })
  228. node.on('autofocus', () => autofocusFirstInput(node))
  229. emit('node', node)
  230. }
  231. const formNodeContext = computed(() => formNode.value?.context)
  232. // Build the flat value when its requested for specific form groups.
  233. const getFlatValues = (values: FormValues, formGroups: string[]) => {
  234. const flatValues = {
  235. ...values,
  236. }
  237. formGroups.forEach((formGroup) => {
  238. Object.assign(flatValues, flatValues[formGroup])
  239. delete flatValues[formGroup]
  240. })
  241. return flatValues
  242. }
  243. // Use the node context value, instead of the v-model, because of performance reason.
  244. const values = computed<FormValues>(() => {
  245. if (!formNodeContext.value) {
  246. return {}
  247. }
  248. if (!props.flattenFormGroups) return formNodeContext.value.value
  249. return getFlatValues(formNodeContext.value.value, props.flattenFormGroups)
  250. })
  251. const relationFields: FormUpdaterRelationField[] = []
  252. const relationFieldBelongsToObjectField: Record<string, string> = {}
  253. const formUpdaterProcessing = computed(
  254. () => !!formNode.value?.context?.state.formUpdaterProcessing,
  255. )
  256. const uploadProcessing = computed(
  257. () => !!formNode.value?.context?.state.uploadProcessing,
  258. )
  259. let delayedSubmit = false
  260. const onSubmitRaw = () => {
  261. if (formUpdaterProcessing.value || uploadProcessing.value) {
  262. delayedSubmit = true
  263. }
  264. }
  265. const afterSubmitReset = (values: FormSubmitData) => {
  266. if (!formNode.value) return
  267. if (props.clearValuesAfterSubmit) {
  268. formNode.value.reset()
  269. } else {
  270. formNode.value.reset(values)
  271. }
  272. }
  273. const afterSubmitHandling = (
  274. submitReturn: void | (() => void) | FormOnSubmitFunctionCallbacks,
  275. values: FormSubmitData,
  276. ) => {
  277. if (!formNode.value) return
  278. schemaData.flags = {}
  279. if (
  280. isObject(submitReturn) &&
  281. ('reset' in submitReturn || 'finally' in submitReturn)
  282. ) {
  283. if (submitReturn.reset) {
  284. submitReturn.reset(values, formNode.value.value as FormValues)
  285. } else {
  286. afterSubmitReset(values)
  287. }
  288. submitReturn.finally?.()
  289. return
  290. }
  291. afterSubmitReset(values)
  292. if (typeof submitReturn === 'function') submitReturn()
  293. }
  294. const onSubmit = (values: FormSubmitData) => {
  295. // Needs to be checked, because the 'onSubmit' function is not required.
  296. if (!props.onSubmit) return undefined
  297. const flatValues = props.flattenFormGroups
  298. ? getFlatValues(values, props.flattenFormGroups)
  299. : values
  300. formNode.value?.clearErrors()
  301. const submitResult = props.onSubmit(flatValues, schemaData.flags)
  302. if (submitResult !== undefined && submitResult === false) return
  303. if (submitResult instanceof Promise) {
  304. return submitResult
  305. .then((result) => {
  306. // When false was returned the submit was skipped.
  307. if (result !== undefined && result === false) return
  308. // it's possible to destroy Form before this is called and the reset should not run when errors exists.
  309. if (!formNode.value || formNode.value.context?.state.errors) return
  310. afterSubmitHandling(result, values)
  311. })
  312. .catch((errors: UserError) => {
  313. if (formNode.value) setErrors(formNode.value, errors)
  314. })
  315. }
  316. afterSubmitHandling(submitResult, values)
  317. }
  318. let formUpdaterQueryHandler: QueryHandler<
  319. FormUpdaterQuery,
  320. FormUpdaterQueryVariables
  321. >
  322. const triggerFormUpdater = (options?: FormUpdaterOptions) => {
  323. handlesFormUpdater('manual', undefined, undefined, options)
  324. }
  325. const delayedSubmitPlugin = (node: FormKitNode) => {
  326. node.on('message-removed', async ({ payload }) => {
  327. if (
  328. (payload.key === 'formUpdaterProcessing' ||
  329. payload.key === 'uploadProcessing') &&
  330. delayedSubmit
  331. ) {
  332. // We need to wait on the "next tick", so that the validation for updated fields is ready.
  333. setTimeout(() => {
  334. delayedSubmit = false
  335. node.submit()
  336. }, 0)
  337. }
  338. })
  339. return false
  340. }
  341. const localFormKitPlugins = computed(() => {
  342. return [delayedSubmitPlugin, ...(props.formKitPlugins || [])]
  343. })
  344. const formConfig = computed(() => {
  345. return {
  346. validationVisibility: props.validationVisibility,
  347. }
  348. })
  349. // Define the additional component library for the used components which are not form fields.
  350. const additionalComponentLibrary = {
  351. FormLayout: markRaw(FormLayout),
  352. FormGroup: markRaw(FormGroup),
  353. ...props.schemaComponentLibrary,
  354. }
  355. // Define the static schema, which will be filled with the real fields from the `schemaData`.
  356. const staticSchema = ref<FormKitSchemaNode[]>([])
  357. const fixedAndSkippedFields: string[] = []
  358. const schemaData = reactive<ReactiveFormSchemData>({
  359. fields: {},
  360. flags: {},
  361. values,
  362. // Helper function to translate directly with the formkit syntax.
  363. // Wrapper is neded, because of unexpected side effects.
  364. t: (
  365. source: Parameters<I18N['t']>[0],
  366. ...args: Array<Parameters<I18N['t']>[1]>
  367. ) => {
  368. return i18n.t(source, ...args)
  369. },
  370. markup,
  371. ...props.schemaData,
  372. })
  373. const internalFieldCamelizeName: Record<string, string> = {}
  374. const getInternalId = (item?: { id?: string; internalId?: number }) => {
  375. if (!item) return undefined
  376. if (item.internalId) return item.internalId
  377. if (!item.id) return undefined
  378. return parseGraphqlId(item.id).id
  379. }
  380. let initialEntityObjectAttributeMap: Record<string, FormFieldValue> = {}
  381. const setInitialEntityObjectAttributeMap = (
  382. initialEntityObject = props.initialEntityObject,
  383. ) => {
  384. if (isEmpty(initialEntityObject)) return
  385. const { objectAttributeValues } = initialEntityObject
  386. if (!objectAttributeValues) return
  387. // Reduce object attribute values to flat structure
  388. initialEntityObjectAttributeMap =
  389. objectAttributeValues.reduce((acc: Record<string, FormFieldValue>, cur) => {
  390. const { attribute } = cur
  391. if (!attribute || !attribute.name) return acc
  392. acc[attribute.name] = cur.value
  393. return acc
  394. }, {}) || {}
  395. }
  396. // Initialize the initial entity object attribute map during the setup in a static way.
  397. // It will maybe be updated later, when the resetForm is used with a different entity object.
  398. setInitialEntityObjectAttributeMap()
  399. const getInitialEntityObjectValue = (
  400. fieldName: string,
  401. initialEntityObject = props.initialEntityObject,
  402. ): FormFieldValue => {
  403. if (isEmpty(initialEntityObject)) return undefined
  404. let value: FormFieldValue
  405. if (relationFieldBelongsToObjectField[fieldName]) {
  406. const belongsToObject =
  407. initialEntityObject[relationFieldBelongsToObjectField[fieldName]]
  408. if (!belongsToObject) return undefined
  409. if ('edges' in belongsToObject) {
  410. value = edgesToArray(
  411. belongsToObject as { edges?: { node: { internalId: number } }[] },
  412. ).map((item) => getInternalId(item))
  413. } else {
  414. value = getInternalId(belongsToObject)
  415. }
  416. }
  417. if (!value) {
  418. const targetFieldName = internalFieldCamelizeName[fieldName] || fieldName
  419. value =
  420. targetFieldName in initialEntityObjectAttributeMap
  421. ? initialEntityObjectAttributeMap[targetFieldName]
  422. : initialEntityObject[targetFieldName]
  423. }
  424. return value
  425. }
  426. const getResetFormValues = (
  427. rootNode: FormKitNode,
  428. values?: FormValues,
  429. object?: EntityObject,
  430. groupNode?: FormKitNode,
  431. resetDirty = true,
  432. ) => {
  433. const resetValues: FormValues = {}
  434. const dirtyNodes: FormKitNode[] = []
  435. const dirtyValues: FormValues = {}
  436. const setResetFormValue = (
  437. name: string,
  438. value: FormFieldValue,
  439. parentName?: string,
  440. ) => {
  441. if (parentName) {
  442. resetValues[parentName] ||= {}
  443. ;(resetValues[parentName] as Record<string, FormFieldValue>)[name] = value
  444. return
  445. }
  446. resetValues[name] = value
  447. }
  448. const checkValue = (
  449. name: string,
  450. values: FormValues,
  451. parentName?: string,
  452. ) => {
  453. if (name in values) {
  454. setResetFormValue(name, values[name], parentName)
  455. return true
  456. }
  457. if (parentName && parentName in values && values[parentName]) {
  458. const value = (values[parentName] as Record<string, FormFieldValue>)[name]
  459. setResetFormValue(name, value, parentName)
  460. return true
  461. }
  462. return false
  463. }
  464. const checkObjectValue = (
  465. name: string,
  466. object: EntityObject,
  467. parentName?: string,
  468. ) => {
  469. const objectValue = getInitialEntityObjectValue(name, object)
  470. if (objectValue !== undefined) {
  471. setResetFormValue(name, objectValue, parentName)
  472. return true
  473. }
  474. return false
  475. }
  476. Object.entries(schemaData.fields).forEach(([field, { props }]) => {
  477. const formElement = props.id ? getNode(props.id) : getNodeByName(props.name)
  478. if (!formElement) return
  479. let parentName = ''
  480. if (formElement.parent && formElement.parent.name !== rootNode.name) {
  481. parentName = formElement.parent.name
  482. }
  483. // Do not use the parentName, when we are in group node reset context.
  484. const groupName = groupNode?.name
  485. if (groupName) {
  486. if (parentName !== groupName) return
  487. parentName = ''
  488. }
  489. if (!resetDirty && formElement.context?.state.dirty) {
  490. dirtyNodes.push(formElement)
  491. dirtyValues[field] = formElement._value as FormFieldValue
  492. }
  493. // We should only do something related to the given values, when something was given.
  494. if (values && checkValue(field, values, parentName)) return
  495. if (object) {
  496. checkObjectValue(field, object, parentName)
  497. }
  498. })
  499. return {
  500. dirtyNodes,
  501. dirtyValues,
  502. resetValues,
  503. }
  504. }
  505. const resetForm = (
  506. data: FormResetData = {},
  507. options: FormResetOptions = {},
  508. ) => {
  509. if (!formNode.value) return
  510. const { object, values } = data
  511. const { resetDirty = true, resetFlags = true, groupNode } = options
  512. formResetRunning.value = true
  513. if (resetFlags) {
  514. schemaData.flags = {}
  515. }
  516. const rootNode = formNode.value
  517. if (object) {
  518. setInitialEntityObjectAttributeMap(object)
  519. setInitialEntityObjectToContext(rootNode, object)
  520. }
  521. const { dirtyNodes, dirtyValues, resetValues } = getResetFormValues(
  522. rootNode,
  523. values,
  524. object,
  525. groupNode,
  526. resetDirty,
  527. )
  528. ;(groupNode || rootNode)?.reset(
  529. Object.keys(resetValues).length ? resetValues : undefined,
  530. )
  531. // keep dirty nodes as dirty
  532. dirtyNodes.forEach((node) => {
  533. node.input(dirtyValues[node.name], false)
  534. })
  535. formResetRunning.value = false
  536. // Trigger the formUpdater, when the reset is done.
  537. handlesFormUpdater(resetDirty ? 'form-reset' : 'form-refresh')
  538. }
  539. const localInitialValues: FormValues = { ...props.initialValues }
  540. const initializeFieldRelation = (
  541. fieldName: string,
  542. relation: FormSchemaField['relation'],
  543. belongsToObjectField?: string,
  544. ) => {
  545. if (relation) {
  546. relationFields.push({
  547. name: fieldName,
  548. relation: relation.type,
  549. filterIds: relation.filterIds,
  550. })
  551. }
  552. if (belongsToObjectField) {
  553. relationFieldBelongsToObjectField[fieldName] = belongsToObjectField
  554. }
  555. }
  556. const setInternalField = (fieldName: string, internal: boolean) => {
  557. if (!internal) return
  558. internalFieldCamelizeName[fieldName] = camelize(fieldName)
  559. }
  560. const updateSchemaLink = (
  561. specificProps: FormFieldAdditionalProps,
  562. fieldName: string,
  563. ) => {
  564. // native fields don't have link attribute, and we don't have a way to get rendered link from graphql
  565. const values = (props.initialEntityObject?.objectAttributeValues ||
  566. []) as ObjectAttributeValue[]
  567. const attribute = values.find(({ attribute }) => attribute.name === fieldName)
  568. if (attribute?.renderedLink) {
  569. specificProps.link = attribute.renderedLink
  570. }
  571. }
  572. const updateSchemaDataField = (
  573. field: FormSchemaField | SetRequired<Partial<FormSchemaField>, 'name'>,
  574. ) => {
  575. const {
  576. show,
  577. updateFields,
  578. relation,
  579. if: staticCondition,
  580. props: specificProps = {},
  581. ...fieldProps
  582. } = field
  583. const showWithStaticCondition = Boolean(
  584. staticCondition || schemaData.fields[field.name]?.staticCondition,
  585. )
  586. const showField =
  587. show ??
  588. schemaData.fields[field.name]?.show ??
  589. (showWithStaticCondition ? undefined : true)
  590. // Special handling for the disabled prop, so that the form can handle also
  591. // the disable state from outside.
  592. if ('disabled' in fieldProps && !fieldProps.disabled) {
  593. fieldProps.disabled = undefined
  594. }
  595. updateSchemaLink(fieldProps, field.name)
  596. if (schemaData.fields[field.name]) {
  597. schemaData.fields[field.name] = {
  598. show: showField,
  599. updateFields: !!updateFields,
  600. staticCondition: showWithStaticCondition,
  601. props: Object.assign(
  602. schemaData.fields[field.name].props,
  603. fieldProps,
  604. specificProps,
  605. ),
  606. }
  607. } else {
  608. initializeFieldRelation(
  609. field.name,
  610. relation,
  611. specificProps?.belongsToObjectField,
  612. )
  613. setInternalField(field.name, Boolean(fieldProps.internal))
  614. const combinedFieldProps = Object.assign(fieldProps, specificProps)
  615. // Select the correct initial value (at this time localInitialValues has not already the information
  616. // from the initial entity object, so we need to check it manually).
  617. if (field.name in localInitialValues) {
  618. combinedFieldProps.value = localInitialValues[field.name]
  619. } else {
  620. const initialEntityOjectValue = getInitialEntityObjectValue(field.name)
  621. combinedFieldProps.value =
  622. initialEntityOjectValue !== undefined
  623. ? initialEntityOjectValue
  624. : combinedFieldProps.value
  625. }
  626. // Save current initial value for later usage.
  627. localInitialValues[field.name] = combinedFieldProps.value
  628. schemaData.fields[field.name] = {
  629. show: showField,
  630. updateFields: !!updateFields,
  631. staticCondition: showWithStaticCondition,
  632. props: combinedFieldProps,
  633. }
  634. }
  635. }
  636. const updateChangedFields = (
  637. changedFields: Record<string, Partial<FormSchemaField>>,
  638. ) => {
  639. const handleUpdatedInitialFieldValue = (
  640. fieldName: string,
  641. value: FormFieldValue,
  642. directly: boolean,
  643. field: Partial<FormSchemaField>,
  644. ) => {
  645. if (value === undefined) return
  646. if (directly) {
  647. field.value = value
  648. } else if (!formKitInitialNodesSettled.value) {
  649. changeInitialValue.set(fieldName, value)
  650. }
  651. }
  652. Object.keys(changedFields).forEach(async (fieldName) => {
  653. if (!schemaData.fields[fieldName]) return
  654. const { initialValue, value, ...changedFieldProps } =
  655. changedFields[fieldName]
  656. const field: SetRequired<Partial<FormSchemaField>, 'name'> = {
  657. ...changedFieldProps,
  658. name: fieldName,
  659. }
  660. const showField = !schemaData.fields[fieldName].show && field.show
  661. const staticShowCondition = schemaData.fields[fieldName].staticCondition
  662. const pendingValueUpdate =
  663. !showField &&
  664. value !== undefined &&
  665. !isEqual(value, values.value[fieldName])
  666. if (pendingValueUpdate) {
  667. field.pendingValueUpdate = true
  668. }
  669. // This happens for the initial updater, when the form is not settled yet or the field was not rendered yet.
  670. // In this case we need to remember the changes and do it afterwards after the form is settled the first time.
  671. // Sometimes the value from the server is the "real" initial value, for this the `initialValue` can be used.
  672. handleUpdatedInitialFieldValue(
  673. fieldName,
  674. value ?? initialValue,
  675. showField ||
  676. initialValue !== undefined ||
  677. (staticShowCondition && !getNodeByName(fieldName)),
  678. field,
  679. )
  680. // When a field will be visible with the update call, we need to wait before on a settled form, before we
  681. // continue (so that we have all values present inside the form).
  682. // This situtation can happen, when the form is used very fast.
  683. if (
  684. formKitInitialNodesSettled.value &&
  685. !schemaData.fields[fieldName].show &&
  686. field.show &&
  687. !formNode.value?.isSettled
  688. ) {
  689. await formNode.value?.settled
  690. }
  691. updaterChangedFields.add(fieldName)
  692. updateSchemaDataField(field)
  693. if (!formKitInitialNodesSettled.value) return
  694. if (pendingValueUpdate) {
  695. const node = field.id ? getNode(field.id) : getNodeByName(fieldName)
  696. // Update the value in the next tick, so that all other props are already updated.
  697. nextTick(() => {
  698. node?.input(value, false)
  699. })
  700. }
  701. })
  702. nextTick(() => {
  703. updaterChangedFields.clear()
  704. formNode.value?.store.remove('formUpdaterProcessing')
  705. })
  706. }
  707. const formHandlerExecution: Record<
  708. FormHandlerExecution,
  709. FormHandlerFunction[]
  710. > = {
  711. [FormHandlerExecution.Initial]: [],
  712. [FormHandlerExecution.InitialSettled]: [],
  713. [FormHandlerExecution.FieldChange]: [],
  714. }
  715. if (props.handlers) {
  716. props.handlers.forEach((handler) => {
  717. Object.values(FormHandlerExecution).forEach((execution) => {
  718. if (handler.execution.includes(execution)) {
  719. formHandlerExecution[execution].push(handler.callback)
  720. }
  721. })
  722. })
  723. }
  724. const executeFormHandler = (
  725. execution: FormHandlerExecution,
  726. currentValues: FormValues,
  727. changedField?: ChangedField,
  728. formUpdaterData?: FormUpdaterQuery['formUpdater'],
  729. ) => {
  730. if (formHandlerExecution[execution].length === 0) return
  731. formHandlerExecution[execution].forEach((handler) => {
  732. handler(
  733. execution,
  734. {
  735. changeFields,
  736. updateSchemaDataField,
  737. schemaData,
  738. },
  739. {
  740. formNode: formNode.value,
  741. getNodeByName,
  742. findNodeByName,
  743. values: currentValues,
  744. changedField,
  745. initialEntityObject: props.initialEntityObject,
  746. formUpdaterData,
  747. },
  748. )
  749. })
  750. }
  751. const formUpdaterVariables = shallowRef<FormUpdaterQueryVariables>()
  752. let nextFormUpdaterVariables: Maybe<FormUpdaterQueryVariables>
  753. const executeFormUpdaterRefetch = () => {
  754. if (!nextFormUpdaterVariables) return
  755. formNode.value?.store.set(
  756. createMessage({
  757. blocking: true,
  758. key: 'formUpdaterProcessing',
  759. value: true,
  760. visible: false,
  761. }),
  762. )
  763. formUpdaterVariables.value = nextFormUpdaterVariables
  764. // Reset the next variables so that it's not triggered a second time.
  765. nextFormUpdaterVariables = null
  766. }
  767. const handlesFormUpdater = (
  768. trigger: FormUpdaterTrigger,
  769. changedField?: FormUpdaterChangedFieldInput,
  770. changedFieldNode?: FormKitNode,
  771. options?: FormUpdaterOptions,
  772. ) => {
  773. if (!props.formUpdaterId || !formUpdaterQueryHandler) return
  774. // When formUpdaterInitial is set, trigger only on initial rendering and when the form was reseted.
  775. if (
  776. trigger !== 'manual' &&
  777. trigger !== 'form-reset' &&
  778. trigger !== 'form-refresh' &&
  779. (!changedField || props.formUpdaterInitialOnly)
  780. )
  781. return
  782. const meta: FormUpdaterMetaInput = {
  783. // We need a unique requestId, so that the query will always be executed on changes, also when the variables
  784. // are the same until the last request, because it could be that core workflow is setting a value back.
  785. requestId: getUuid(),
  786. formId,
  787. additionalData: {
  788. ...props.formUpdaterAdditionalParams,
  789. ...options?.additionalParams,
  790. },
  791. }
  792. if (options?.includeDirtyFields) {
  793. const dirtyFields: string[] = []
  794. Object.entries(schemaData.fields).forEach(([field, { props }]) => {
  795. const formElement = props.id
  796. ? getNode(props.id)
  797. : getNodeByName(props.name)
  798. if (!formElement) return
  799. if (formElement.context?.state.dirty) {
  800. dirtyFields.push(field)
  801. }
  802. })
  803. meta.dirtyFields = dirtyFields
  804. }
  805. const data: FormValues = {
  806. ...values.value,
  807. }
  808. if (trigger === 'form-reset') {
  809. meta.reset = true
  810. } else if (changedField) {
  811. meta.changedField = changedField
  812. const parentName = changedFieldNode?.parent?.name
  813. // Currently we are only supporting one level.
  814. if (
  815. formNode.value &&
  816. parentName &&
  817. parentName !== formNode.value.name &&
  818. (!props.flattenFormGroups ||
  819. !props.flattenFormGroups.includes(parentName))
  820. ) {
  821. data[parentName] ||= {}
  822. ;(data[parentName] as Record<string, FormFieldValue>)[changedField.name] =
  823. changedField.newValue
  824. } else {
  825. data[changedField.name] = changedField.newValue
  826. }
  827. }
  828. // We mark this as raw, because we want no deep reactivity on the form updater query variables.
  829. nextFormUpdaterVariables = markRaw({
  830. id: props.initialEntityObject?.id,
  831. formUpdaterId: props.formUpdaterId,
  832. data,
  833. meta,
  834. relationFields,
  835. })
  836. if (trigger !== 'blur') executeFormUpdaterRefetch()
  837. }
  838. const previousValues = new WeakMap<FormKitNode, FormFieldValue>()
  839. const changedInputValueHandling = (inputNode: FormKitNode) => {
  840. inputNode.on('commit', ({ payload: newValue, origin: node }) => {
  841. const oldValue = previousValues.get(node)
  842. if (isEqual(newValue, oldValue)) return
  843. if (!formKitInitialNodesSettled.value || formResetRunning.value) {
  844. previousValues.set(node, cloneDeep(newValue))
  845. return
  846. }
  847. if (
  848. inputNode.props.triggerFormUpdater &&
  849. !updaterChangedFields.has(node.name)
  850. ) {
  851. handlesFormUpdater(
  852. inputNode.props.formUpdaterTrigger,
  853. {
  854. name: node.name,
  855. newValue,
  856. oldValue,
  857. },
  858. node,
  859. )
  860. }
  861. emit('changed', node.name, newValue, oldValue)
  862. formNode.value?.emit(`changed:${node.name}`, {
  863. newValue,
  864. oldValue,
  865. fieldNode: node,
  866. })
  867. executeFormHandler(FormHandlerExecution.FieldChange, values.value, {
  868. name: node.name,
  869. newValue,
  870. oldValue,
  871. })
  872. previousValues.set(node, cloneDeep(newValue))
  873. updaterChangedFields.delete(node.name)
  874. })
  875. inputNode.on('blur', async () => {
  876. if (inputNode.props.formUpdaterTrigger !== 'blur') return
  877. if (!formNode.value?.isSettled) await formNode.value?.settled
  878. if (nextFormUpdaterVariables) executeFormUpdaterRefetch()
  879. })
  880. inputNode.hook.message((payload: FormKitMessageProps, next) => {
  881. if (payload.key === 'submitted' && formUpdaterProcessing.value) {
  882. payload.value = false
  883. }
  884. return next(payload)
  885. })
  886. return false
  887. }
  888. const buildStaticSchema = () => {
  889. const { getFormFieldSchema, getFormFieldsFromScreen } =
  890. useObjectAttributeFormFields(fixedAndSkippedFields)
  891. const buildFormKitField = (
  892. field: FormSchemaField,
  893. ): FormKitSchemaComponent => {
  894. const fieldId = field.id || getNodeId(formId, field.name)
  895. const plugins = [changedInputValueHandling]
  896. if (field.plugins) {
  897. plugins.push(...field.plugins)
  898. }
  899. return {
  900. $cmp: 'FormKit',
  901. if: field.if ? field.if : `$fields.${field.name}.show`,
  902. bind: `$fields.${field.name}.props`,
  903. props: {
  904. type: field.type,
  905. key: fieldId,
  906. name: field.name,
  907. id: fieldId,
  908. formId,
  909. plugins,
  910. triggerFormUpdater: field.triggerFormUpdater ?? !!props.formUpdaterId,
  911. },
  912. }
  913. }
  914. const getLayoutType = (
  915. layoutNode: FormSchemaLayout,
  916. ): FormKitSchemaDOMNode | FormKitSchemaComponent => {
  917. let layoutField: FormKitSchemaDOMNode | FormKitSchemaComponent
  918. if ('component' in layoutNode) {
  919. layoutField = {
  920. $cmp: layoutNode.component,
  921. ...(layoutNode.if && { if: layoutNode.if }),
  922. props: layoutNode.props,
  923. }
  924. } else {
  925. layoutField = {
  926. $el: layoutNode.element,
  927. ...(layoutNode.if && { if: layoutNode.if }),
  928. attrs: layoutNode.attrs,
  929. }
  930. }
  931. if (layoutNode.if) {
  932. layoutField.if = layoutNode.if
  933. }
  934. return layoutField
  935. }
  936. type ResolveFormSchemaNode = Exclude<FormSchemaNode, string>
  937. type ResolveFormKitSchemaNode = Exclude<FormKitSchemaNode, string>
  938. const resolveSchemaNode = (
  939. node: ResolveFormSchemaNode,
  940. ): Maybe<ResolveFormKitSchemaNode | ResolveFormKitSchemaNode[]> => {
  941. if ('isLayout' in node && node.isLayout) {
  942. return getLayoutType(node)
  943. }
  944. if ('isGroupOrList' in node && node.isGroupOrList) {
  945. const nodeId = `${node.name}-${formId}`
  946. return {
  947. $cmp: 'FormKit',
  948. ...(node.if && { if: node.if }),
  949. props: {
  950. type: node.type,
  951. name: node.name,
  952. id: nodeId,
  953. key: node.name,
  954. plugins: node.plugins,
  955. },
  956. }
  957. }
  958. if ('object' in node && getFormFieldSchema && getFormFieldsFromScreen) {
  959. if ('name' in node && node.name && !node.type) {
  960. const { screen, object, ...fieldNode } = node
  961. const resolvedField = getFormFieldSchema(fieldNode.name, object, screen)
  962. if (!resolvedField) return null
  963. node = {
  964. ...resolvedField,
  965. ...fieldNode,
  966. } as FormSchemaField
  967. } else if ('screen' in node && !('name' in node)) {
  968. const resolvedFields = getFormFieldsFromScreen(node.screen, node.object)
  969. const formKitFields: ResolveFormKitSchemaNode[] = []
  970. resolvedFields.forEach((screenField) => {
  971. updateSchemaDataField(screenField)
  972. formKitFields.push(buildFormKitField(screenField))
  973. })
  974. return formKitFields
  975. }
  976. }
  977. updateSchemaDataField(node as FormSchemaField)
  978. return buildFormKitField(node as FormSchemaField)
  979. }
  980. const resolveSchema = (schema: FormSchemaNode[] = props.schema) => {
  981. return schema.reduce((resolvedSchema: FormKitSchemaNode[], node) => {
  982. if (typeof node === 'string') {
  983. resolvedSchema.push(node)
  984. return resolvedSchema
  985. }
  986. const resolvedNode = resolveSchemaNode(node)
  987. if (!resolvedNode) return resolvedSchema
  988. if ('children' in node) {
  989. const childrens = Array.isArray(node.children)
  990. ? [...resolveSchema(node.children)]
  991. : node.children
  992. resolvedSchema.push({
  993. ...(resolvedNode as Exclude<FormKitSchemaNode, string>),
  994. children: childrens,
  995. })
  996. return resolvedSchema
  997. }
  998. if (Array.isArray(resolvedNode)) {
  999. resolvedSchema.push(...resolvedNode)
  1000. } else {
  1001. resolvedSchema.push(resolvedNode)
  1002. }
  1003. return resolvedSchema
  1004. }, [])
  1005. }
  1006. staticSchema.value = resolveSchema()
  1007. }
  1008. watchOnce(formKitInitialNodesSettled, () => {
  1009. watch(
  1010. changeFields,
  1011. (newValue) => {
  1012. updateChangedFields(newValue)
  1013. },
  1014. {
  1015. deep: true,
  1016. },
  1017. )
  1018. })
  1019. watch(
  1020. () => props.schemaData,
  1021. () => Object.assign(schemaData, props.schemaData),
  1022. {
  1023. deep: true,
  1024. },
  1025. )
  1026. const setFormSchemaInitialized = () => {
  1027. if (!formSchemaInitialized.value) {
  1028. formSchemaInitialized.value = true
  1029. }
  1030. }
  1031. const { notify, removeNotification } = useNotifications()
  1032. let formUpdaterQueryLoadingTimeoutId: NodeJS.Timeout | null
  1033. const clearFormUpdaterQueryLoadingTimeout = () => {
  1034. if (!formUpdaterQueryLoadingTimeoutId) return
  1035. clearTimeout(formUpdaterQueryLoadingTimeoutId)
  1036. formUpdaterQueryLoadingTimeoutId = null
  1037. }
  1038. const cleanupFormUpdaterAutosaveNotification = () => {
  1039. removeNotification('form-updater-autosave')
  1040. clearFormUpdaterQueryLoadingTimeout()
  1041. }
  1042. const handleFormUpdaterAutosaveNotification = () => {
  1043. if (
  1044. !formUpdaterVariables.value?.meta.additionalData?.taskbarId &&
  1045. !formUpdaterVariables.value?.meta.additionalData?.applyTaskbarState
  1046. )
  1047. return
  1048. // Clean up previous notification and timeout.
  1049. cleanupFormUpdaterAutosaveNotification()
  1050. const formUpdaterQueryLoading = formUpdaterQueryHandler.loading()
  1051. watch(formUpdaterQueryLoading, (isLoading) => {
  1052. if (!isLoading) {
  1053. cleanupFormUpdaterAutosaveNotification()
  1054. return
  1055. }
  1056. // Clear previous timeout.
  1057. clearFormUpdaterQueryLoadingTimeout()
  1058. formUpdaterQueryLoadingTimeoutId = setTimeout(() => {
  1059. // Show info notification if the request takes longer than a second.
  1060. notify({
  1061. id: 'form-updater-autosave',
  1062. message: __('Autosave in progress…'),
  1063. type: NotificationTypes.Info,
  1064. persistent: true,
  1065. })
  1066. // Show warning notification if the request takes longer than five seconds.
  1067. formUpdaterQueryLoadingTimeoutId = setTimeout(() => {
  1068. notify({
  1069. id: 'form-updater-autosave',
  1070. message: __('Autosaving is taking longer than expected…'),
  1071. type: NotificationTypes.Warn,
  1072. persistent: true,
  1073. })
  1074. }, 4000)
  1075. }, 1000)
  1076. })
  1077. }
  1078. const formUpdaterScope = effectScope()
  1079. onBeforeUnmount(() => {
  1080. if (formUpdaterScope.active) formUpdaterScope.stop()
  1081. cleanupFormUpdaterAutosaveNotification()
  1082. })
  1083. const initializeFormSchema = () => {
  1084. buildStaticSchema()
  1085. if (props.formUpdaterId) {
  1086. formUpdaterVariables.value = markRaw({
  1087. id: props.initialEntityObject?.id,
  1088. formUpdaterId: props.formUpdaterId,
  1089. data: localInitialValues,
  1090. meta: {
  1091. initial: true,
  1092. additionalData: props.formUpdaterAdditionalParams,
  1093. formId,
  1094. },
  1095. relationFields,
  1096. })
  1097. formUpdaterScope.run(() => {
  1098. formUpdaterQueryHandler = new QueryHandler(
  1099. useFormUpdaterQuery(
  1100. formUpdaterVariables as Ref<FormUpdaterQueryVariables>,
  1101. {
  1102. // TODO: we can try it like that to improve a little bit the loading situation, but could
  1103. // lead to an flickering when something changes from server perspective...
  1104. // fetchPolicy: 'cache-and-network',
  1105. // nextFetchPolicy: 'no-cache',
  1106. fetchPolicy: 'no-cache',
  1107. },
  1108. ),
  1109. )
  1110. })
  1111. handleFormUpdaterAutosaveNotification()
  1112. formUpdaterQueryHandler.onResult((queryResult) => {
  1113. // Execute the form handler function so that they can manipulate the form updater result.
  1114. if (!formSchemaInitialized.value) {
  1115. executeFormHandler(
  1116. FormHandlerExecution.Initial,
  1117. localInitialValues,
  1118. undefined,
  1119. queryResult?.data?.formUpdater,
  1120. )
  1121. }
  1122. if (queryResult?.data?.formUpdater) {
  1123. Object.assign(schemaData.flags, queryResult.data.formUpdater.flags)
  1124. updateChangedFields(
  1125. changeFields.value
  1126. ? merge(queryResult.data.formUpdater.fields, changeFields.value)
  1127. : queryResult.data.formUpdater.fields,
  1128. )
  1129. }
  1130. setFormSchemaInitialized()
  1131. })
  1132. } else {
  1133. executeFormHandler(FormHandlerExecution.Initial, localInitialValues)
  1134. if (changeFields.value) updateChangedFields(changeFields.value)
  1135. setFormSchemaInitialized()
  1136. }
  1137. }
  1138. // TODO: maybe we should react on schema changes and rebuild the static schema with a new form-id and re-rendering of
  1139. // the complete form (= use the formId as the key for the whole form to trigger the re-rendering of the component...)
  1140. if (props.schema) {
  1141. showInitialLoadingAnimation.value = true
  1142. if (props.useObjectAttributes) {
  1143. // TODO: rebuild schema, when object attributes
  1144. // was changed from outside(not such important,
  1145. // because we have currently the reload solution like in the desktop view).
  1146. if (props.objectAttributeSkippedFields) {
  1147. fixedAndSkippedFields.push(...props.objectAttributeSkippedFields)
  1148. }
  1149. const objectAttributeObjects: EnumObjectManagerObjects[] = []
  1150. const addObjectAttributeToObjects = (object: EnumObjectManagerObjects) => {
  1151. if (objectAttributeObjects.includes(object)) return
  1152. objectAttributeObjects.push(object)
  1153. }
  1154. const detectObjectAttributeObjects = (
  1155. schema: FormSchemaNode[] = props.schema,
  1156. ) => {
  1157. schema.forEach((item) => {
  1158. if (typeof item === 'string') return
  1159. if ('object' in item) {
  1160. if ('name' in item && item.name && !item.type) {
  1161. fixedAndSkippedFields.push(item.name)
  1162. }
  1163. addObjectAttributeToObjects(item.object)
  1164. }
  1165. if ('children' in item && Array.isArray(item.children)) {
  1166. detectObjectAttributeObjects(item.children)
  1167. }
  1168. })
  1169. }
  1170. detectObjectAttributeObjects()
  1171. // We need only to fetch object attributes, when there are used in the given schema.
  1172. if (objectAttributeObjects.length > 0) {
  1173. const { objectAttributesLoading } = useObjectAttributeLoadFormFields(
  1174. objectAttributeObjects,
  1175. )
  1176. const unwatchTriggerFormInitialize = watch(
  1177. objectAttributesLoading,
  1178. (loading) => {
  1179. if (!loading) {
  1180. nextTick(() => unwatchTriggerFormInitialize())
  1181. initializeFormSchema()
  1182. }
  1183. },
  1184. { immediate: true },
  1185. )
  1186. } else {
  1187. initializeFormSchema()
  1188. }
  1189. } else {
  1190. initializeFormSchema()
  1191. }
  1192. }
  1193. const classMap = getFormClasses()
  1194. defineExpose({
  1195. formNode,
  1196. formInitialSettled,
  1197. formId,
  1198. values,
  1199. flags: schemaData.flags,
  1200. updateChangedFields,
  1201. updateSchemaDataField,
  1202. getNodeByName,
  1203. findNodeByName,
  1204. resetForm,
  1205. triggerFormUpdater,
  1206. })
  1207. </script>
  1208. <script lang="ts">
  1209. export default {
  1210. inheritAttrs: false,
  1211. }
  1212. </script>
  1213. <template>
  1214. <div
  1215. v-if="debouncedShowInitialLoadingAnimation"
  1216. class="flex items-center justify-center"
  1217. >
  1218. <CommonIcon :class="classMap.loading" name="loading" animation="spin" />
  1219. </div>
  1220. <FormKit
  1221. v-if="
  1222. hasSchema &&
  1223. ((formSchemaInitialized && Object.keys(schemaData.fields).length > 0) ||
  1224. $slots.default)
  1225. "
  1226. v-bind="$attrs"
  1227. :id="id"
  1228. type="form"
  1229. novalidate
  1230. :config="formConfig"
  1231. :form-class="localClass"
  1232. :actions="false"
  1233. :incomplete-message="false"
  1234. :plugins="localFormKitPlugins"
  1235. :sections-schema="formKitSectionsSchema"
  1236. :disabled="disabled"
  1237. @node="setFormNode"
  1238. @submit="onSubmit"
  1239. @submit-raw="onSubmitRaw"
  1240. >
  1241. <FormKitMessages
  1242. :sections-schema="{
  1243. messages: {
  1244. $el: 'div',
  1245. },
  1246. message: {
  1247. $el: undefined,
  1248. $cmp: 'CommonAlert',
  1249. props: {
  1250. id: `$id + '-' + $message.key`,
  1251. key: '$message.key',
  1252. variant: {
  1253. if: '$message.type == error || $message.type == validation',
  1254. then: 'danger',
  1255. else: '$message.type',
  1256. },
  1257. },
  1258. slots: {
  1259. default: '$message.value',
  1260. },
  1261. },
  1262. }"
  1263. />
  1264. <slot name="before-fields" />
  1265. <slot
  1266. name="default"
  1267. :schema="staticSchema"
  1268. :data="schemaData"
  1269. :library="additionalComponentLibrary"
  1270. >
  1271. <div
  1272. v-show="
  1273. formKitInitialNodesSettled && !debouncedShowInitialLoadingAnimation
  1274. "
  1275. ref="form"
  1276. :class="formClass"
  1277. >
  1278. <FormKitSchema
  1279. :schema="staticSchema"
  1280. :data="schemaData"
  1281. :library="additionalComponentLibrary"
  1282. />
  1283. </div>
  1284. </slot>
  1285. <slot name="after-fields" />
  1286. </FormKit>
  1287. </template>