printNotation function
document in the notation. Parse it back with notationOptionsFor.
Implementation
String printNotation(Json document, {required Catalog catalog}) {
final nodes = readMap(document['nodes']) ?? const {};
final roots = readStrings(document['roots']);
final screen = roots.isEmpty ? 'screen' : roots.first;
final options = notationOptionsFor(document);
final canvas = readMap(nodes[screen]);
final rootId = readString(readMap(canvas?['slots'])?['body']);
final state = <String>[
for (final v in readList(readMap(document['variables'])?[screen]) ?? const [])
if (v is Map && v['name'] is String) 'state ${v['name']}=${jsonEncode(v['value'])}',
];
final ids = <String>[], sugar = <String, String>{}, depth = <String, int>{};
final printable = RegExp(r'^[A-Za-z_][A-Za-z0-9_]*$');
var whole = rootId == null;
void walk(String id, int d, Set<String> seen) {
final n = readMap(nodes[id]);
if (n == null || !seen.add(id) || !printable.hasMatch(id)) {
whole = true;
return;
}
ids.add(id);
depth[id] = d;
sugar[id] = _line(id, n);
for (final c in readStrings(n['children'])) {
walk(c, d + 1, seen);
}
for (final c in (readMap(n['slots']) ?? const {}).values) {
if (c is String) walk(c, d + 1, seen);
}
}
if (rootId != null) walk(rootId, 0, {screen});
String text(Map<String, String> tails, String? last) => [
...state,
for (final id in ids) '${' ' * depth[id]!}${sugar[id]}${tails[id] ?? ''}',
?last,
].join('\n');
if (!whole) {
// What the words did not say, per node.
final first = parseNotation(text(const {}, null), catalog: catalog, options: options).document;
final parsed = readMap(first['nodes']) ?? const {};
final tails = <String, String>{};
for (final id in ids) {
final got = readMap(parsed[id]);
if (got == null) {
whole = true;
break;
}
final patch = diffPatch(got, readMap(nodes[id])!);
if (patch != null) tails[id] = ' ${jsonEncode(patch)}';
}
if (!whole) {
final second = parseNotation(text(tails, null), catalog: catalog, options: options).document;
final rest = diffPatch(second, document);
final out = text(tails, rest == null ? null : 'document ${jsonEncode(rest)}');
if (jsonEncode(_sorted(parseNotation(out, catalog: catalog, options: options).document)) == jsonEncode(_sorted(document))) return out;
}
}
// A document the tree's words cannot carry (a node id with other
// characters, a node outside the body): the whole of it as data.
final empty = parseNotation('', catalog: catalog, options: options).document;
return 'document ${jsonEncode(diffPatch(empty, document) ?? const {})}';
}