buildManagedInstance function

ManagedBuild buildManagedInstance({
  1. required ManagedComponentVersion version,
  2. required String topId,
  3. ManagedComponentRef ref = const ManagedComponentRef(),
  4. Layout? layout,
  5. ThemeTokens? theme,
  6. Catalog? catalog,
})

Instance topId's nodes built from version with ref applied:

  • node ids derived from topId (managedNodeId; the top keeps topId), every reference to them renamed;
  • the setting values in ComponentLink.managed written to their targets by key;
  • theme bindings (${theme.primary}) replaced by the instance's token, else theme's, else the version's own value;
  • each slot node's children replaced by the instance's slot content (those nodes are the page's, not built here);
  • each event placeholder (kComponentEventAction) replaced by the instance's chain for it (or removed);
  • the top node linked to the version with ref, placed with layout (the instance's own place and size) when given.

Implementation

ManagedBuild buildManagedInstance({
  required ManagedComponentVersion version,
  required String topId,
  ManagedComponentRef ref = const ManagedComponentRef(),
  Layout? layout,
  ThemeTokens? theme,
  Catalog? catalog,
}) {
  final def = version.definition;
  final root = def.rootId!;
  final source = def.document.toJson();
  final raw = readMap(source['nodes']) ?? const {};
  final ids = {for (final id in raw.keys) id: id == root ? topId : managedNodeId(topId, id)};
  // Node references are renamed: string values (never keys) that are node
  // ids, anywhere but in a node's props (texts, hints, labels: words a node
  // id may equal), where only a variant's children are references.
  Object? rename(Object? v) => switch (v) {
    final String s when ids.containsKey(s) => ids[s],
    final List<Object?> l => [for (final x in l) rename(x)],
    final Map<Object?, Object?> m => {for (final e in m.entries) '${e.key}': rename(e.value)},
    _ => v,
  };
  Json renameNode(Json node) => {
    for (final e in node.entries) e.key: e.key == 'props' ? _renameProps(e.value, rename) : rename(e.value),
  };
  final eventJson = {
    for (final e in ref.events.entries) e.key: [for (final a in e.value) a.toJson()],
  };
  Object? splice(Object? v) {
    if (v is List) {
      return [
        for (final x in v)
          if (readMap(x) case final Json m when m['type'] == kComponentEventAction)
            ...?eventJson[readString(m['event'])]
          else
            splice(x),
      ];
    }
    if (v is Map) return {for (final e in v.entries) '${e.key}': splice(e.value)};
    return v;
  }

  final nodes = <String, Node>{};
  for (final id in [root, ...raw.keys.where((k) => k != root)]) {
    final source = readMap(raw[id]);
    if (source == null) continue;
    final json = renameNode(source);
    if (json['actions'] != null) json['actions'] = splice(json['actions']);
    final n = Node.fromJson(json, id: ids[id], catalog: catalog);
    if (n != null) nodes[n.id] = n;
  }

  // Settings, by key.
  for (final s in version.contract.flatSettings) {
    final key = s.effectiveKey;
    if (!ref.values.containsKey(key)) continue;
    final value = ref.values[key];
    for (final t in s.targets) {
      final id = ids[t.node] ?? t.node, path = t.path;
      final n = nodes[id];
      if (n == null || path == null) continue;
      nodes[id] = BindPaths.apply(n, path, value);
    }
  }

  // Theme tokens.
  final projectTokens = theme?.toJson() ?? const {};
  for (final id in [...nodes.keys]) {
    final n = nodes[id]!;
    if (n.bind.isEmpty) continue;
    var out = n;
    final bind = {...n.bind};
    for (final e in n.bind.entries) {
      final token = _themeBind.firstMatch(e.value)?[1];
      if (token == null) continue;
      bind.remove(e.key);
      final value = ref.tokens[token] ?? projectTokens[token];
      if (value != null) out = BindPaths.apply(out, e.key, value);
    }
    if (bind.length != n.bind.length) nodes[id] = out.copyWith(bind: bind);
  }

  // Slots.
  for (final slot in version.contract.slots) {
    final content = ref.slots[slot.key];
    final id = ids[slot.node];
    final n = id == null ? null : nodes[id];
    if (content == null || content.isEmpty || n == null) continue;
    // The version's default content of the slot goes.
    final drop = <String>{};
    void collect(String c) {
      if (!drop.add(c)) return;
      for (final cc in nodes[c]?.childIds ?? const <String>[]) {
        collect(cc);
      }
    }

    for (final c in n.children) {
      collect(c);
    }
    nodes.removeWhere((k, _) => drop.contains(k));
    nodes[n.id] = n.copyWith(children: content);
  }

  final top = nodes[topId]!;
  nodes[topId] = Node.fromJson({...top.toJson(), if (layout != null) 'layout': layout.toJson()}, id: topId, catalog: catalog)!
      .withComponent(
        ComponentLink(
          id: version.id,
          version: version.version,
          managedJson: ref.copyWith(semver: version.semver, digest: version.digest).toJson(),
        ),
      );
  return ManagedBuild(
    nodes: [nodes[topId]!, ...nodes.values.where((n) => n.id != topId)],
    variables: version.contract.variables,
  );
}