SPB Git

Repository Public License

CustomComponent.swift 2.7 KB 47 lines swift

1import Foundation2import PrismCore3import PrismObjectModel4import PrismScriptRuntime56/// On-demand components (ADR 0009): a `prism.component` object defines one for this app; objects of type `custom.<id>` use it.7///8/// Definition props: `summary`, `props` (the same contract as catalog props: `{name, kind, summary, required?, default?, values?}`),9/// `events` (names the component can emit), `source` (JavaScript with a `render(props)` function), `tick` (seconds between10/// `tick(props)` calls, optional), `keys` (true to receive `key(props, event)`).11public enum CustomComponent {12    public static let maxDefinitions = 401314    public static func id(ofType type: String) -> String? {15        type.hasPrefix(ObjectType.customPrefix) ? String(type.dropFirst(ObjectType.customPrefix.count)) : nil16    }1718    public static func definition(forType type: String, in bp: AppBlueprint) -> PrismObject? {19        guard let id = id(ofType: type), let o = bp.object(id), o.isComponentDefinition else { return nil }20        return o21    }2223    /// The contract of a definition, in the same shape as a catalog manifest, so one validator serves both.24    public static func manifest(_ definition: PrismObject) throws -> ComponentManifest {25        let props = try (definition.props["props"]?.arrayValue ?? []).map(PropSpec.init(json:))26        guard Set(props.map(\.name)).count == props.count else { throw ManifestError("Component `\(definition.id)` declares a prop twice.") }27        if let clash = props.first(where: { p in CommonProps.all.contains { $0.name == p.name } }) {28            throw ManifestError("Component `\(definition.id)`: `\(clash.name)` is a prop every component already has; choose another name.")29        }30        let events = (definition.props["events"]?.arrayValue ?? []).compactMap(\.stringValue)31        if let bad = events.first(where: { !PrismID.isValid($0) }) { throw ManifestError("Component `\(definition.id)`: `\(bad)` is not a valid event name.") }32        return ComponentManifest(33            type: ObjectType.customPrefix + definition.id, name: definition.name.isEmpty ? definition.id : definition.name, category: "custom",34            summary: definition.props["summary"]?.stringValue ?? "", props: props, events: events,35            permissions: [Permission.scripts], accessibilityRole: "group", fixture: .null36        )37    }38}3940extension ComponentRegistry {41    /// A catalog component, or an on-demand component defined by this app.42    public func manifest(_ type: String, in bp: AppBlueprint) -> ComponentManifest? {43        if let m = manifest(type) { return m }44        return CustomComponent.definition(forType: type, in: bp).flatMap { try? CustomComponent.manifest($0) }45    }46}47
Files main
Menu

Theme