SPB Git

Repository Public License

DynamicValue.swift 2.1 KB 56 lines swift

1import Foundation2import PrismCore34/// A prop value in a blueprint: a literal, a computed expression, or a two-way state binding (ADR 0002).5public enum DynamicValue: Sendable, Hashable {6    case literal(JSONValue)7    case expression(String)8    /// Path under `state`, e.g. `filter` or `form.amount`.9    case binding(String)1011    public init(_ json: JSONValue) {12        if let o = json.objectValue, o.count == 1 {13            if let e = o["$expr"]?.stringValue { self = .expression(e); return }14            if let b = o["$bind"]?.stringValue {15                self = .binding(b.hasPrefix("state.") ? String(b.dropFirst(6)) : b)16                return17            }18        }19        self = .literal(json)20    }2122    public var isDynamic: Bool { if case .literal = self { false } else { true } }2324    public func resolve(in scope: ExpressionScope) throws -> JSONValue {25        switch self {26        case .literal(let v): return v27        case .expression(let source): return try Evaluator.evaluate(source, scope: scope)28        case .binding(let path): return StatePath.get(path, in: scope.roots["state"] ?? .emptyObject)29        }30    }31}3233/// Dotted paths into the state object.34public enum StatePath {35    public static func get(_ path: String, in state: JSONValue) -> JSONValue {36        var current = state37        for part in path.split(separator: ".") { current = current[String(part)] ?? .null }38        return current39    }4041    public static func set(_ path: String, to value: JSONValue, in state: inout [String: JSONValue]) {42        let parts = path.split(separator: ".").map(String.init)43        guard let first = parts.first else { return }44        if parts.count == 1 { state[first] = value; return }45        var child = state[first]?.objectValue ?? [:]46        set(parts.dropFirst().joined(separator: "."), to: value, in: &child)47        state[first] = .object(child)48    }4950    public static func isValid(_ path: String) -> Bool {51        !path.isEmpty && path.split(separator: ".", omittingEmptySubsequences: false).allSatisfy {52            !$0.isEmpty && $0.allSatisfy { $0.isLetter || $0.isNumber || $0 == "_" } && !$0.first!.isNumber53        }54    }55}56
Files main
Menu

Theme