import type { DynamicCustomTypeModel, StaticCustomTypeModel, StaticCustomTypeModelTab, } from "../model/customType" import type { SharedSliceModel, StaticSliceModel } from "../model/slice" export function toStatic( customType: DynamicCustomTypeModel, sharedSlices: Map | Record, ): StaticCustomTypeModel { const json: StaticCustomTypeModel["json"] = {} const sharedSlicesMap = sharedSlices instanceof Map ? sharedSlices : new Map(Object.entries(sharedSlices)) for (const [tabKey, tab] of Object.entries(customType.json)) { const tabJSON: StaticCustomTypeModel["json"][string] = {} for (const [key, widget] of Object.entries(tab)) { switch (widget.type) { case "Slices": case "Choice": const choices: Record = {} for (const [id, model] of Object.entries(widget.config?.choices || {})) { if (model.type === "SharedSlice") { const sharedSlice = sharedSlicesMap.get(id) if (sharedSlice) { choices[id] = sharedSlice } } else { choices[id] = model } } tabJSON[key] = { ...widget, config: { ...widget.config, choices }, } break default: tabJSON[key] = widget } } json[tabKey] = tabJSON } return { ...customType, json } } export function flatten(customType: StaticCustomTypeModel): StaticCustomTypeModelTab { return Object.values(customType.json).reduce((acc, fields) => ({ ...acc, ...fields }), {}) } export function collectSharedSlices( customType: StaticCustomTypeModel, ): Record { const sharedSlices: Record = {} const flattened = flatten(customType) for (const widget of Object.values(flattened)) { if (widget.type === "Slices" || widget.type === "Choice") { for (const [id, model] of Object.entries(widget.config?.choices || {})) { if (model.type === "SharedSlice") { sharedSlices[id] = model } } } } return sharedSlices } export function filterMissingSharedSlices< TCustomType extends StaticCustomTypeModel | DynamicCustomTypeModel, >( customType: TCustomType, sharedSlices: Map | Record, ): TCustomType { const json: TCustomType["json"] = {} const sharedSlicesMap = sharedSlices instanceof Map ? sharedSlices : new Map(Object.entries(sharedSlices)) for (const [tabKey, tab] of Object.entries(customType.json)) { const tabJSON: typeof tab = {} for (const [key, widget] of Object.entries(tab)) { switch (widget.type) { case "Slices": case "Choice": const choices: Required["config"]["choices"] = {} for (const [id, model] of Object.entries(widget.config?.choices || {})) { if (model.type === "SharedSlice") { if (sharedSlicesMap.get(id)) { choices[id] = model } } else { choices[id] = model } } tabJSON[key] = { ...widget, config: { ...widget.config, choices }, } break default: tabJSON[key] = widget } } json[tabKey] = tabJSON } return { ...customType, json } }