node method

Json node(
  1. Json json,
  2. WidgetSpec? spec, {
  3. WidgetSpec? specOf(
    1. String id
    )?,
})

A node's JSON (or a patch of it: a media rule's, an interaction state's) with the names it uses resolved; json itself when it names nothing. spec declares its props; specOf gives the declaration of another node an interaction state patches.

Implementation

Json node(Json json, WidgetSpec? spec, {WidgetSpec? Function(String id)? specOf}) {
  Json? out;
  void put(String key, Object? v) {
    if (!identical(v, json[key])) (out ??= {...json})[key] = v;
  }

  final props = readMap(json['props']);
  if (props != null && spec != null) put('props', _fields(spec.props, props));
  final decoration = readMap(json['decoration']);
  if (decoration != null) put('decoration', _fields(DecorationFields.all, decoration));
  for (final d in BehaviorFields.all) {
    if (!json.containsKey(d.key) || d.key == BehaviorFields.states.key) continue;
    put(d.key, value(d.type, json[d.key]));
  }
  // Interaction states: state → {node id → patch of that node}.
  final states = readMap(json[BehaviorFields.states.key]);
  if (states != null) {
    Json? s;
    for (final e in states.entries) {
      final targets = readMap(e.value);
      if (targets == null) continue;
      Json? t;
      for (final p in targets.entries) {
        final patch = readMap(p.value);
        if (patch == null) continue;
        final r = node(patch, specOf?.call(p.key) ?? spec, specOf: specOf);
        if (!identical(r, patch)) (t ??= {...targets})[p.key] = r;
      }
      if (t != null) (s ??= {...states})[e.key] = t;
    }
    if (s != null) put(BehaviorFields.states.key, s);
  }
  final media = readList(json['media']);
  if (media != null) {
    List<Object?>? m;
    for (var i = 0; i < media.length; i++) {
      final rule = readMap(media[i]);
      final patch = readMap(rule?['patch']);
      if (rule == null || patch == null) continue;
      final r = node(patch, spec, specOf: specOf);
      if (!identical(r, patch)) (m ??= [...media])[i] = {...rule, 'patch': r};
    }
    if (m != null) put('media', m);
  }
  return out ?? json;
}