|
| 1 | +import { useCallback, useMemo, useState } from 'react' |
| 2 | +import { |
| 3 | + OverrideOpHelperForItemContentsBatcher, |
| 4 | + WrappedOverridableItemNormal, |
| 5 | +} from '../../ui/Settings/util/OverrideOpHelper' |
| 6 | +import { SchemaFormCommonProps } from './schemaFormUtil' |
| 7 | +import { SchemaFormWithOverrides } from './SchemaFormWithOverrides' |
| 8 | +import { literal, objectPathSet } from '@sofie-automation/corelib/dist/lib' |
| 9 | +import { AnyARecord } from 'dns' |
| 10 | + |
| 11 | +interface SchemaFormWithStateProps extends Omit<SchemaFormCommonProps, 'isRequired'> { |
| 12 | + object: any |
| 13 | + |
| 14 | + onUpdate: (object: any) => void |
| 15 | +} |
| 16 | + |
| 17 | +export function SchemaFormWithState({ |
| 18 | + object, |
| 19 | + onUpdate, |
| 20 | + ...commonProps |
| 21 | +}: Readonly<SchemaFormWithStateProps>): JSX.Element { |
| 22 | + const helper = useCallback( |
| 23 | + () => |
| 24 | + new OverrideOpHelperWithState(object, (object) => { |
| 25 | + onUpdate(object) |
| 26 | + }), |
| 27 | + [object, onUpdate] |
| 28 | + ) |
| 29 | + |
| 30 | + const wrappedItem = useMemo( |
| 31 | + () => |
| 32 | + literal<WrappedOverridableItemNormal<any>>({ |
| 33 | + type: 'normal', |
| 34 | + id: 'not-used', |
| 35 | + computed: object, |
| 36 | + defaults: undefined, |
| 37 | + overrideOps: [], |
| 38 | + }), |
| 39 | + [object] |
| 40 | + ) |
| 41 | + |
| 42 | + return <SchemaFormWithOverrides {...commonProps} attr="" item={wrappedItem} overrideHelper={helper} isRequired /> |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * An alternate OverrideOpHelper designed to directly mutate an object, instead of using the `ObjectWithOverrides` system. |
| 47 | + * This allows us to have one SchemaForm implementation that can handle working with `ObjectWithOverrides`, and simpler options |
| 48 | + */ |
| 49 | +class OverrideOpHelperWithState implements OverrideOpHelperForItemContentsBatcher { |
| 50 | + readonly #object: any |
| 51 | + readonly #onUpdate: (object: any) => void |
| 52 | + |
| 53 | + constructor(object: AnyARecord, onUpdate: (object: any) => void) { |
| 54 | + this.#object = object |
| 55 | + this.#onUpdate = onUpdate |
| 56 | + } |
| 57 | + |
| 58 | + clearItemOverrides(_itemId: string, _subPath: string): this { |
| 59 | + // Not supported as this is faking an item with overrides |
| 60 | + |
| 61 | + return this |
| 62 | + } |
| 63 | + setItemValue(_itemId: string, subPath: string, value: any): this { |
| 64 | + objectPathSet(this.#object, subPath, value) |
| 65 | + |
| 66 | + return this |
| 67 | + } |
| 68 | + |
| 69 | + commit(): void { |
| 70 | + this.#onUpdate(this.#object) |
| 71 | + } |
| 72 | +} |
0 commit comments