Form.vue 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545
  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. // TODO: we can try it like that to improve a little bit the loading situation, but could
  1105. // lead to an flickering when something changes from server perspective...
  1106. // fetchPolicy: 'cache-and-network',
  1107. // nextFetchPolicy: 'no-cache',
  1108. fetchPolicy: 'no-cache',
  1109. },
  1110. ),
  1111. )
  1112. })
  1113. handleFormUpdaterAutosaveNotification()
  1114. formUpdaterQueryHandler.onResult((queryResult) => {
  1115. // Execute the form handler function so that they can manipulate the form updater result.
  1116. if (!formSchemaInitialized.value) {
  1117. executeFormHandler(
  1118. FormHandlerExecution.Initial,
  1119. localInitialValues,
  1120. undefined,
  1121. queryResult?.data?.formUpdater,
  1122. )
  1123. }
  1124. if (queryResult?.data?.formUpdater) {
  1125. Object.assign(schemaData.flags, queryResult.data.formUpdater.flags)
  1126. updateChangedFields(
  1127. changeFields.value
  1128. ? merge(queryResult.data.formUpdater.fields, changeFields.value)
  1129. : queryResult.data.formUpdater.fields,
  1130. )
  1131. }
  1132. setFormSchemaInitialized()
  1133. })
  1134. } else {
  1135. executeFormHandler(FormHandlerExecution.Initial, localInitialValues)
  1136. if (changeFields.value) updateChangedFields(changeFields.value)
  1137. setFormSchemaInitialized()
  1138. }
  1139. }
  1140. // TODO: maybe we should react on schema changes and rebuild the static schema with a new form-id and re-rendering of
  1141. // the complete form (= use the formId as the key for the whole form to trigger the re-rendering of the component...)
  1142. if (props.schema) {
  1143. showInitialLoadingAnimation.value = true
  1144. if (props.useObjectAttributes) {
  1145. // TODO: rebuild schema, when object attributes
  1146. // was changed from outside(not such important,
  1147. // because we have currently the reload solution like in the desktop view).
  1148. if (props.objectAttributeSkippedFields) {
  1149. fixedAndSkippedFields.push(...props.objectAttributeSkippedFields)
  1150. }
  1151. const objectAttributeObjects: EnumObjectManagerObjects[] = []
  1152. const addObjectAttributeToObjects = (object: EnumObjectManagerObjects) => {
  1153. if (objectAttributeObjects.includes(object)) return
  1154. objectAttributeObjects.push(object)
  1155. }
  1156. const detectObjectAttributeObjects = (
  1157. schema: FormSchemaNode[] = props.schema,
  1158. ) => {
  1159. schema.forEach((item) => {
  1160. if (typeof item === 'string') return
  1161. if ('object' in item) {
  1162. if ('name' in item && item.name && !item.type) {
  1163. fixedAndSkippedFields.push(item.name)
  1164. }
  1165. addObjectAttributeToObjects(item.object)
  1166. }
  1167. if ('children' in item && Array.isArray(item.children)) {
  1168. detectObjectAttributeObjects(item.children)
  1169. }
  1170. })
  1171. }
  1172. detectObjectAttributeObjects()
  1173. // We need only to fetch object attributes, when there are used in the given schema.
  1174. if (objectAttributeObjects.length > 0) {
  1175. const { objectAttributesLoading } = useObjectAttributeLoadFormFields(
  1176. objectAttributeObjects,
  1177. )
  1178. const unwatchTriggerFormInitialize = watch(
  1179. objectAttributesLoading,
  1180. (loading) => {
  1181. if (!loading) {
  1182. nextTick(() => unwatchTriggerFormInitialize())
  1183. initializeFormSchema()
  1184. }
  1185. },
  1186. { immediate: true },
  1187. )
  1188. } else {
  1189. initializeFormSchema()
  1190. }
  1191. } else {
  1192. initializeFormSchema()
  1193. }
  1194. }
  1195. const classMap = getFormClasses()
  1196. defineExpose({
  1197. formNode,
  1198. formInitialSettled,
  1199. formId,
  1200. values,
  1201. flags: schemaData.flags,
  1202. updateChangedFields,
  1203. updateSchemaDataField,
  1204. getNodeByName,
  1205. findNodeByName,
  1206. resetForm,
  1207. triggerFormUpdater,
  1208. })
  1209. </script>
  1210. <script lang="ts">
  1211. export default {
  1212. inheritAttrs: false,
  1213. }
  1214. </script>
  1215. <template>
  1216. <div
  1217. v-if="debouncedShowInitialLoadingAnimation"
  1218. class="flex items-center justify-center"
  1219. >
  1220. <CommonIcon :class="classMap.loading" name="loading" animation="spin" />
  1221. </div>
  1222. <FormKit
  1223. v-if="
  1224. hasSchema &&
  1225. ((formSchemaInitialized && Object.keys(schemaData.fields).length > 0) ||
  1226. $slots.default)
  1227. "
  1228. v-bind="$attrs"
  1229. :id="id"
  1230. type="form"
  1231. novalidate
  1232. :config="formConfig"
  1233. :form-class="localClass"
  1234. :actions="false"
  1235. :incomplete-message="false"
  1236. :plugins="localFormKitPlugins"
  1237. :sections-schema="formKitSectionsSchema"
  1238. :disabled="disabled"
  1239. @node="setFormNode"
  1240. @submit="onSubmit"
  1241. @submit-raw="onSubmitRaw"
  1242. >
  1243. <FormKitMessages
  1244. :sections-schema="{
  1245. messages: {
  1246. $el: 'div',
  1247. },
  1248. message: {
  1249. $el: undefined,
  1250. $cmp: 'CommonAlert',
  1251. props: {
  1252. id: `$id + '-' + $message.key`,
  1253. key: '$message.key',
  1254. variant: {
  1255. if: '$message.type == error || $message.type == validation',
  1256. then: 'danger',
  1257. else: '$message.type',
  1258. },
  1259. },
  1260. slots: {
  1261. default: '$message.value',
  1262. },
  1263. },
  1264. }"
  1265. />
  1266. <slot name="before-fields" />
  1267. <slot
  1268. name="default"
  1269. :schema="staticSchema"
  1270. :data="schemaData"
  1271. :library="additionalComponentLibrary"
  1272. >
  1273. <div
  1274. v-show="
  1275. formKitInitialNodesSettled && !debouncedShowInitialLoadingAnimation
  1276. "
  1277. ref="form"
  1278. :class="formClass"
  1279. >
  1280. <FormKitSchema
  1281. :schema="staticSchema"
  1282. :data="schemaData"
  1283. :library="additionalComponentLibrary"
  1284. />
  1285. </div>
  1286. </slot>
  1287. <slot name="after-fields" />
  1288. </FormKit>
  1289. </template>