Skip to content

An open source design system that's fully customizable and agent ready

TypeScript
2.4 KB
Raw Blame
// Generated by @astryxdesign/native. Do not edit.
import Foundation

/// A JSON value: a portable callback argument on its way to the core.
public enum AstryxValue: Codable, Equatable, Sendable {
  case null
  case bool(Bool)
  case number(Double)
  case string(String)
  case array([AstryxValue])
  case object([String: AstryxValue])

  /// Any portable value (a contract's strings, numbers, enums, and records) as JSON.
  public init<T: Encodable>(_ value: T) {
    guard let data = try? JSONEncoder().encode(value),
          let decoded = try? JSONDecoder().decode(AstryxValue.self, from: data) else {
      self = .null
      return
    }
    self = decoded
  }

  public init(from decoder: any Decoder) throws {
    let container = try decoder.singleValueContainer()
    if container.decodeNil() { self = .null }
    else if let value = try? container.decode(Bool.self) { self = .bool(value) }
    else if let value = try? container.decode(Double.self) { self = .number(value) }
    else if let value = try? container.decode(String.self) { self = .string(value) }
    else if let value = try? container.decode([AstryxValue].self) { self = .array(value) }
    else { self = .object(try container.decode([String: AstryxValue].self)) }
  }

  public func encode(to encoder: any Encoder) throws {
    var container = encoder.singleValueContainer()
    switch self {
    case .null: try container.encodeNil()
    case .bool(let value): try container.encode(value)
    case .number(let value): try container.encode(value)
    case .string(let value): try container.encode(value)
    case .array(let value): try container.encode(value)
    case .object(let value): try container.encode(value)
    }
  }
}

/// A callback a view called: which node, which prop, and its arguments.
public struct AstryxAction: Codable, Equatable, Sendable {
  public let key: String
  public let component: String
  public let event: String
  public let args: [AstryxValue]

  public init(key: String, component: String, event: String, args: [AstryxValue]) {
    self.key = key
    self.component = component
    self.event = event
    self.args = args
  }

  /// The JSON the core receives.
  public var json: String {
    let encoder = JSONEncoder()
    encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
    guard let data = try? encoder.encode(self) else { return "{}" }
    return String(decoding: data, as: UTF8.self)
  }
}