| 15 | }; |
| 16 | |
| 17 | export class Block< |
| 18 | Component extends ComponentType<any> = any, |
| 19 | Props = ComponentProps<Component>, |
| 20 | Key extends keyof Props = keyof Props, |
| 21 | > { |
| 22 | public static readonly UNCATEGORIZED = 'Uncategorized'; |
| 23 | public static readonly UNGROUPED = 'Default'; |
| 24 | |
| 25 | public readonly name: string; |
| 26 | public readonly category: string; |
| 27 | public readonly component: Component; |
| 28 | public readonly props: { |
| 29 | [key in Key]: PropertySpec<Props[key]>; |
| 30 | }; |
| 31 | |
| 32 | constructor(name: string, config: BlockConfig) { |
| 33 | this.name = name; |
| 34 | this.category = config.category ?? Block.UNCATEGORIZED; |
| 35 | this.component = config.component; |
| 36 | this.props = config.props as { |
| 37 | [key in Key]: PropertySpec<Props[key]>; |
| 38 | }; |
| 39 | |
| 40 | this.populateDefaults(); |
| 41 | } |
| 42 | |
| 43 | public getGroupedProps() { |
| 44 | const propsByGroup: Record<string, Record<string, PropertySpec<any>>> = {}; |
| 45 | |
| 46 | for (const key in this.props) { |
| 47 | const spec = this.props[key]; |
| 48 | const group = spec.group ?? Block.UNGROUPED; |
| 49 | |
| 50 | propsByGroup[group] ||= {}; |
| 51 | propsByGroup[group][key] = spec; |
| 52 | } |
| 53 | |
| 54 | return propsByGroup; |
| 55 | } |
| 56 | |
| 57 | private populateDefaults() { |
| 58 | for (const spec of Object.values(this.props)) { |
| 59 | const typedSpec = spec as PropertySpec<any>; |
| 60 | |
| 61 | this.setSpecDefault(typedSpec); |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | private setSpecDefault(spec: PropertySpec<any>) { |
| 66 | spec.hasDefault = typeof spec.default !== 'undefined'; |
| 67 | |
| 68 | switch (spec.type) { |
| 69 | case 'array': |
| 70 | spec.default ??= []; |
| 71 | this.setSpecDefault(spec.item); |
| 72 | break; |
| 73 | case 'boolean': |
| 74 | spec.default ??= false; |
nothing calls this directly
no outgoing calls
no test coverage detected