Form.vue 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  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. validationMessages: field.validationMessages,
  911. validationRules: field.validationRules,
  912. triggerFormUpdater: field.triggerFormUpdater ?? !!props.formUpdaterId,
  913. },
  914. }
  915. }
  916. const getLayoutType = (
  917. layoutNode: FormSchemaLayout,
  918. ): FormKitSchemaDOMNode | FormKitSchemaComponent => {
  919. let layoutField: FormKitSchemaDOMNode | FormKitSchemaComponent
  920. if ('component' in layoutNode) {
  921. layoutField = {
  922. $cmp: layoutNode.component,
  923. ...(layoutNode.if && { if: layoutNode.if }),
  924. props: layoutNode.props,
  925. }
  926. } else {
  927. layoutField = {
  928. $el: layoutNode.element,
  929. ...(layoutNode.if && { if: layoutNode.if }),
  930. attrs: layoutNode.attrs,
  931. }
  932. }
  933. if (layoutNode.if) {
  934. layoutField.if = layoutNode.if
  935. }
  936. return layoutField
  937. }
  938. type ResolveFormSchemaNode = Exclude<FormSchemaNode, string>
  939. type ResolveFormKitSchemaNode = Exclude<FormKitSchemaNode, string>
  940. const resolveSchemaNode = (
  941. node: ResolveFormSchemaNode,
  942. ): Maybe<ResolveFormKitSchemaNode | ResolveFormKitSchemaNode[]> => {
  943. if ('isLayout' in node && node.isLayout) {
  944. return getLayoutType(node)
  945. }
  946. if ('isGroupOrList' in node && node.isGroupOrList) {
  947. const nodeId = `${node.name}-${formId}`
  948. return {
  949. $cmp: 'FormKit',
  950. ...(node.if && { if: node.if }),
  951. props: {
  952. type: node.type,
  953. name: node.name,
  954. id: nodeId,
  955. key: node.name,
  956. plugins: node.plugins,
  957. },
  958. }
  959. }
  960. if ('object' in node && getFormFieldSchema && getFormFieldsFromScreen) {
  961. if ('name' in node && node.name && !node.type) {
  962. const { screen, object, ...fieldNode } = node
  963. const resolvedField = getFormFieldSchema(fieldNode.name, object, screen)
  964. if (!resolvedField) return null
  965. node = {
  966. ...resolvedField,
  967. ...fieldNode,
  968. } as FormSchemaField
  969. } else if ('screen' in node && !('name' in node)) {
  970. const resolvedFields = getFormFieldsFromScreen(node.screen, node.object)
  971. const formKitFields: ResolveFormKitSchemaNode[] = []
  972. resolvedFields.forEach((screenField) => {
  973. updateSchemaDataField(screenField)
  974. formKitFields.push(buildFormKitField(screenField))
  975. })
  976. return formKitFields
  977. }
  978. }
  979. updateSchemaDataField(node as FormSchemaField)
  980. return buildFormKitField(node as FormSchemaField)
  981. }
  982. const resolveSchema = (schema: FormSchemaNode[] = props.schema) => {
  983. return schema.reduce((resolvedSchema: FormKitSchemaNode[], node) => {
  984. if (typeof node === 'string') {
  985. resolvedSchema.push(node)
  986. return resolvedSchema
  987. }
  988. const resolvedNode = resolveSchemaNode(node)
  989. if (!resolvedNode) return resolvedSchema
  990. if ('children' in node) {
  991. const childrens = Array.isArray(node.children)
  992. ? [...resolveSchema(node.children)]
  993. : node.children
  994. resolvedSchema.push({
  995. ...(resolvedNode as Exclude<FormKitSchemaNode, string>),
  996. children: childrens,
  997. })
  998. return resolvedSchema
  999. }
  1000. if (Array.isArray(resolvedNode)) {
  1001. resolvedSchema.push(...resolvedNode)
  1002. } else {
  1003. resolvedSchema.push(resolvedNode)
  1004. }
  1005. return resolvedSchema
  1006. }, [])
  1007. }
  1008. staticSchema.value = resolveSchema()
  1009. }
  1010. watchOnce(formKitInitialNodesSettled, () => {
  1011. watch(
  1012. changeFields,
  1013. (newValue) => {
  1014. updateChangedFields(newValue)
  1015. },
  1016. {
  1017. deep: true,
  1018. },
  1019. )
  1020. })
  1021. watch(
  1022. () => props.schemaData,
  1023. () => Object.assign(schemaData, props.schemaData),
  1024. {
  1025. deep: true,
  1026. },
  1027. )
  1028. const setFormSchemaInitialized = () => {
  1029. if (!formSchemaInitialized.value) {
  1030. formSchemaInitialized.value = true
  1031. }
  1032. }
  1033. const { notify, removeNotification } = useNotifications()
  1034. let formUpdaterQueryLoadingTimeoutId: NodeJS.Timeout | null
  1035. const clearFormUpdaterQueryLoadingTimeout = () => {
  1036. if (!formUpdaterQueryLoadingTimeoutId) return
  1037. clearTimeout(formUpdaterQueryLoadingTimeoutId)
  1038. formUpdaterQueryLoadingTimeoutId = null
  1039. }
  1040. const cleanupFormUpdaterAutosaveNotification = () => {
  1041. removeNotification('form-updater-autosave')
  1042. clearFormUpdaterQueryLoadingTimeout()
  1043. }
  1044. const handleFormUpdaterAutosaveNotification = () => {
  1045. if (
  1046. !formUpdaterVariables.value?.meta.additionalData?.taskbarId &&
  1047. !formUpdaterVariables.value?.meta.additionalData?.applyTaskbarState
  1048. )
  1049. return
  1050. // Clean up previous notification and timeout.
  1051. cleanupFormUpdaterAutosaveNotification()
  1052. const formUpdaterQueryLoading = formUpdaterQueryHandler.loading()
  1053. watch(formUpdaterQueryLoading, (isLoading) => {
  1054. if (!isLoading) {
  1055. cleanupFormUpdaterAutosaveNotification()
  1056. return
  1057. }
  1058. // Clear previous timeout.
  1059. clearFormUpdaterQueryLoadingTimeout()
  1060. formUpdaterQueryLoadingTimeoutId = setTimeout(() => {
  1061. // Show info notification if the request takes longer than a second.
  1062. notify({
  1063. id: 'form-updater-autosave',
  1064. message: __('Autosave in progress…'),
  1065. type: NotificationTypes.Info,
  1066. persistent: true,
  1067. })
  1068. // Show warning notification if the request takes longer than five seconds.
  1069. formUpdaterQueryLoadingTimeoutId = setTimeout(() => {
  1070. notify({
  1071. id: 'form-updater-autosave',
  1072. message: __('Autosaving is taking longer than expected…'),
  1073. type: NotificationTypes.Warn,
  1074. persistent: true,
  1075. })
  1076. }, 4000)
  1077. }, 1000)
  1078. })
  1079. }
  1080. const formUpdaterScope = effectScope()
  1081. onBeforeUnmount(() => {
  1082. if (formUpdaterScope.active) formUpdaterScope.stop()
  1083. cleanupFormUpdaterAutosaveNotification()
  1084. })
  1085. const initializeFormSchema = () => {
  1086. buildStaticSchema()
  1087. if (props.formUpdaterId) {
  1088. formUpdaterVariables.value = markRaw({
  1089. id: props.initialEntityObject?.id,
  1090. formUpdaterId: props.formUpdaterId,
  1091. data: localInitialValues,
  1092. meta: {
  1093. initial: true,
  1094. additionalData: props.formUpdaterAdditionalParams,
  1095. formId,
  1096. },
  1097. relationFields,
  1098. })
  1099. formUpdaterScope.run(() => {
  1100. formUpdaterQueryHandler = new QueryHandler(
  1101. useFormUpdaterQuery(
  1102. formUpdaterVariables as Ref<FormUpdaterQueryVariables>,
  1103. {
  1104. fetchPolicy: 'no-cache',
  1105. },
  1106. ),
  1107. )
  1108. })
  1109. handleFormUpdaterAutosaveNotification()
  1110. formUpdaterQueryHandler.onResult((queryResult) => {
  1111. // Execute the form handler function so that they can manipulate the form updater result.
  1112. if (!formSchemaInitialized.value) {
  1113. executeFormHandler(
  1114. FormHandlerExecution.Initial,
  1115. localInitialValues,
  1116. undefined,
  1117. queryResult?.data?.formUpdater,
  1118. )
  1119. }
  1120. if (queryResult?.data?.formUpdater) {
  1121. Object.assign(schemaData.flags, queryResult.data.formUpdater.flags)
  1122. updateChangedFields(
  1123. changeFields.value
  1124. ? merge(queryResult.data.formUpdater.fields, changeFields.value)
  1125. : queryResult.data.formUpdater.fields,
  1126. )
  1127. }
  1128. setFormSchemaInitialized()
  1129. })
  1130. } else {
  1131. executeFormHandler(FormHandlerExecution.Initial, localInitialValues)
  1132. if (changeFields.value) updateChangedFields(changeFields.value)
  1133. setFormSchemaInitialized()
  1134. }
  1135. }
  1136. // TODO: maybe we should react on schema changes and rebuild the static schema with a new form-id and re-rendering of
  1137. // the complete form (= use the formId as the key for the whole form to trigger the re-rendering of the component...)
  1138. if (props.schema) {
  1139. showInitialLoadingAnimation.value = true
  1140. if (props.useObjectAttributes) {
  1141. // TODO: rebuild schema, when object attributes
  1142. // was changed from outside(not such important,
  1143. // because we have currently the reload solution like in the desktop view).
  1144. if (props.objectAttributeSkippedFields) {
  1145. fixedAndSkippedFields.push(...props.objectAttributeSkippedFields)
  1146. }
  1147. const objectAttributeObjects: EnumObjectManagerObjects[] = []
  1148. const addObjectAttributeToObjects = (object: EnumObjectManagerObjects) => {
  1149. if (objectAttributeObjects.includes(object)) return
  1150. objectAttributeObjects.push(object)
  1151. }
  1152. const detectObjectAttributeObjects = (
  1153. schema: FormSchemaNode[] = props.schema,
  1154. ) => {
  1155. schema.forEach((item) => {
  1156. if (typeof item === 'string') return
  1157. if ('object' in item) {
  1158. if ('name' in item && item.name && !item.type) {
  1159. fixedAndSkippedFields.push(item.name)
  1160. }
  1161. addObjectAttributeToObjects(item.object)
  1162. }
  1163. if ('children' in item && Array.isArray(item.children)) {
  1164. detectObjectAttributeObjects(item.children)
  1165. }
  1166. })
  1167. }
  1168. detectObjectAttributeObjects()
  1169. // We need only to fetch object attributes, when there are used in the given schema.
  1170. if (objectAttributeObjects.length > 0) {
  1171. const { objectAttributesLoading } = useObjectAttributeLoadFormFields(
  1172. objectAttributeObjects,
  1173. )
  1174. const unwatchTriggerFormInitialize = watch(
  1175. objectAttributesLoading,
  1176. (loading) => {
  1177. if (!loading) {
  1178. nextTick(() => unwatchTriggerFormInitialize())
  1179. initializeFormSchema()
  1180. }
  1181. },
  1182. { immediate: true },
  1183. )
  1184. } else {
  1185. initializeFormSchema()
  1186. }
  1187. } else {
  1188. initializeFormSchema()
  1189. }
  1190. }
  1191. const classMap = getFormClasses()
  1192. defineExpose({
  1193. formNode,
  1194. formInitialSettled,
  1195. formId,
  1196. values,
  1197. flags: schemaData.flags,
  1198. updateChangedFields,
  1199. updateSchemaDataField,
  1200. getNodeByName,
  1201. findNodeByName,
  1202. resetForm,
  1203. triggerFormUpdater,
  1204. })
  1205. </script>
  1206. <script lang="ts">
  1207. export default {
  1208. inheritAttrs: false,
  1209. }
  1210. </script>
  1211. <template>
  1212. <div
  1213. v-if="debouncedShowInitialLoadingAnimation"
  1214. class="flex items-center justify-center"
  1215. >
  1216. <CommonIcon :class="classMap.loading" name="loading" animation="spin" />
  1217. </div>
  1218. <FormKit
  1219. v-if="
  1220. hasSchema &&
  1221. ((formSchemaInitialized && Object.keys(schemaData.fields).length > 0) ||
  1222. $slots.default)
  1223. "
  1224. v-bind="$attrs"
  1225. :id="id"
  1226. type="form"
  1227. novalidate
  1228. :config="formConfig"
  1229. :form-class="localClass"
  1230. :actions="false"
  1231. :incomplete-message="false"
  1232. :plugins="localFormKitPlugins"
  1233. :sections-schema="formKitSectionsSchema"
  1234. :disabled="disabled"
  1235. @node="setFormNode"
  1236. @submit="onSubmit"
  1237. @submit-raw="onSubmitRaw"
  1238. >
  1239. <FormKitMessages
  1240. :sections-schema="{
  1241. messages: {
  1242. $el: 'div',
  1243. },
  1244. message: {
  1245. $el: undefined,
  1246. $cmp: 'CommonAlert',
  1247. props: {
  1248. id: `$id + '-' + $message.key`,
  1249. key: '$message.key',
  1250. variant: {
  1251. if: '$message.type == error || $message.type == validation',
  1252. then: 'danger',
  1253. else: '$message.type',
  1254. },
  1255. },
  1256. slots: {
  1257. default: '$message.value',
  1258. },
  1259. },
  1260. }"
  1261. />
  1262. <slot name="before-fields" />
  1263. <slot
  1264. name="default"
  1265. :schema="staticSchema"
  1266. :data="schemaData"
  1267. :library="additionalComponentLibrary"
  1268. >
  1269. <div
  1270. v-show="
  1271. formKitInitialNodesSettled && !debouncedShowInitialLoadingAnimation
  1272. "
  1273. ref="form"
  1274. :class="formClass"
  1275. >
  1276. <FormKitSchema
  1277. :schema="staticSchema"
  1278. :data="schemaData"
  1279. :library="additionalComponentLibrary"
  1280. />
  1281. </div>
  1282. </slot>
  1283. <slot name="after-fields" />
  1284. </FormKit>
  1285. </template>