scopeOverlays function

OverlayScoping scopeOverlays(
  1. List<ScopedPage> pages,
  2. List<ScopedComponent> components, {
  3. Map<String, ({Json document, String path})> otherComponents = const {},
})

Makes the overlays of pages that two or more pages write with one id and draw differently each page's own, and what names them follow (see the head of this file). components are the site's notation components (changed too); otherComponents the types of the site's components that are not (JSON ones): an open of a per-page overlay in one of those is said. pages and components hold documents changed in place.

Implementation

OverlayScoping scopeOverlays(List<ScopedPage> pages, List<ScopedComponent> components,
    {Map<String, ({String path, Json document})> otherComponents = const {}}) {
  final out = OverlayScoping();
  final pageNames = {for (final p in pages) p.name};
  // The pages that write each overlay id.
  final written = <String, List<ScopedPage>>{};
  for (final p in pages) {
    final roots = readStrings(p.document['roots']);
    final nodes = readMap(p.document['nodes']) ?? const {};
    for (final id in roots.skip(1)) {
      if (readMap(nodes[id])?['type'] != 'canvas') continue;
      if (pageNames.contains(id) && id != p.name) {
        out.issues.add((
          path: p.path,
          message: 'the overlay "$id" has the id of the page $id: a page and its overlays are screens of the whole site, so the two are one '
              'and only one of them is shown. Give this one an id of its own.',
        ));
        continue;
      }
      written.putIfAbsent(id, () => []).add(p);
    }
  }
  // The overlay ids each component names, its own and those of the
  // components it calls.
  final opens = <String, Set<String>>{
    for (final c in components) c.type: _named(c.document),
    for (final e in otherComponents.entries) e.key: _named(e.value.document),
  };
  final called = {
    for (final c in components) c.type: _callTypes(c.document, opens.keys.toSet()),
    for (final e in otherComponents.entries) e.key: _callTypes(e.value.document, opens.keys.toSet()),
  };
  for (var grew = true; grew;) {
    grew = false;
    for (final t in opens.keys) {
      for (final callee in called[t]!) {
        for (final id in opens[callee]!) {
          grew = opens[t]!.add(id) || grew;
        }
      }
    }
  }
  // Which overlays draw otherwise on two pages: what an overlay names that
  // is a page's own (an `open` of it, a call of a component that opens it)
  // is that page's, so one that names such an overlay draws otherwise too.
  final differ = <String>{};
  for (var grew = true; grew;) {
    grew = false;
    for (final e in written.entries) {
      if (e.value.length < 2 || differ.contains(e.key)) continue;
      final drawn = {
        for (final p in e.value)
          _drawn(readMap(p.document['nodes']) ?? const {}, e.key, mark: (v) {
            if (v is String && differ.contains(v)) return '$v@${p.name}';
            if (v is Map && (opens[v['type']]?.any(differ.contains) ?? false)) return {...v, '@page': p.name};
            return null;
          }),
      };
      if (drawn.length > 1) grew = differ.add(e.key);
    }
  }
  final allIds = {...pageNames, ...written.keys};
  for (final id in differ) {
    final perPage = <String, String>{};
    final e = MapEntry(id, {for (final p in written[id]!) p.name: p});
    for (final page in e.value.keys) {
      final to = pageScopedId(e.key, page);
      if (allIds.contains(to)) {
        out.issues.add((
          path: pages.firstWhere((p) => p.name == page).path,
          message: 'the overlay "${e.key}" draws otherwise on ${_list(e.value.keys.where((x) => x != page))}, so each page is given its own, '
              'but this page\'s would be "$to", which is the id of a page: it is left "${e.key}", one screen with theirs. '
              'Rename the page $to, or give this overlay an id of its own.',
        ));
        continue;
      }
      perPage[page] = to;
    }
    if (perPage.isNotEmpty) out.renamed[e.key] = perPage;
  }
  if (out.renamed.isEmpty) return out;

  // The pages: each overlay made its own, and what names it.
  for (final p in pages) {
    final map = {
      for (final e in out.renamed.entries)
        if (e.value[p.name] case final String to) e.key: to,
    };
    if (map.isEmpty) continue;
    _renameCanvases(p.document, map);
    _renameReferences(p.document, map, (field, value) {
      out.issues.add((
        path: p.path,
        message: 'an action\'s $field is worked out ($value) and may name the overlay ${_list(map.keys.where((id) => value.contains("'$id'") || value.contains('"$id"')))}, '
            'which this page has as its own (${_list(map.entries.where((e) => value.contains("'${e.key}'") || value.contains('"${e.key}"')).map((e) => e.value))}): '
            'the expression is left as written. Name the overlay by its id (open ${map.keys.first}), or write the new id in it.',
      ));
    });
  }

  // The components: an action that names a per-page overlay is an event of
  // the component, and its calls answer it.
  final types = {for (final c in components) c.type};
  final own = <String, Set<String>>{}; // type → events it fires itself
  final opener = <String, Set<String>>{}; // event → the components that fire it
  final templates = <String, String>{}; // id|action → event
  final values = <String, Json>{}; // event → the action it stands for
  for (final c in components) {
    final fired = own[c.type] = <String>{};
    _eventize(c.document, out.renamed.keys.toSet(), (action) {
      final id = readString(action['to']) ?? '';
      final verb = action['type'] == OpenModalAction.typeName ? 'open' : 'go';
      final key = '$id|${jsonEncode(_sorted(action))}';
      final event = templates[key] ??= () {
        var name = '$verb--$id';
        for (var i = 2; out.events.containsKey(name); i++) {
          name = '$verb--$id--$i';
        }
        out.events[name] = id;
        values[name] = action;
        return name;
      }();
      fired.add(event);
      opener.putIfAbsent(event, () => {}).add(c.type);
      return event;
    }, (what, id) {
      out.issues.add((
        path: c.path,
        message: switch (what) {
          'confirm' || 'base' => 'the component ${c.type} ${what == 'confirm' ? 'confirms with the dialog' : 'goes to a page over'} "$id", which pages '
              '${_list(out.renamed[id]!.keys)} each have as their own (they draw it differently): a component is one for the whole site, so it cannot name '
              'one page\'s, and this is left as written. Have it emit an event and do this on each page (onEvent={…}).',
          _ => 'the component ${c.type} reads the result of the overlay "$id" (an action after its open reads result), which pages '
              '${_list(out.renamed[id]!.keys)} each have as their own: the page opens it for the component, so the result does not come back. '
              'Have the component emit an event, and open "$id" and act on its result on each page.',
        },
      ));
    });
  }
  for (final e in otherComponents.entries) {
    final named = <String>{};
    _renameReferences(e.value.document, {for (final id in out.renamed.keys) id: id}, (_, _) {}, found: named);
    for (final id in named) {
      out.issues.add((
        path: e.value.path,
        message: 'the component ${e.key} names the overlay "$id", which pages ${_list(out.renamed[id]!.keys)} each have as their own '
            '(they draw it differently: ${_list(out.renamed[id]!.values)}); it is not a notation component, so it is not made to open the calling page\'s. '
            'Write it in the notation (components/${e.key}.txt), or have it emit an event and open "$id" on each page.',
      ));
    }
  }
  // What each component fires, its own and its calls' (a call passes on
  // what the component it calls fires).
  final calls = {for (final c in components) c.type: _callTypes(c.document, types)};
  final needs = {for (final t in types) t: {...?own[t]}};
  for (var grew = true; grew;) {
    grew = false;
    for (final t in types) {
      for (final callee in calls[t]!) {
        for (final ev in needs[callee]!) {
          grew = needs[t]!.add(ev) || grew;
        }
      }
    }
  }
  for (final c in components) {
    _answer(c.document, needs, (event, node) => {'type': ComponentEventAction.typeName, 'event': event, 'value': r'${result}'});
  }
  for (final p in pages) {
    final said = <String>{};
    _answer(p.document, needs, (event, node) {
      final id = out.events[event]!;
      final to = out.renamed[id]?[p.name];
      if (to == null) {
        final callee = readString(node['type'])!;
        final from = opener[event]!.toList()..sort();
        if (said.add('$callee|$id')) {
          final through = from.contains(callee) ? '' : ' (through ${from.join(', ')})';
          out.issues.add((
            path: p.path,
            message: 'the page calls ${from.length == 1 && from.single == callee ? 'the component $callee' : '$callee$through'}, which opens the overlay "$id"; '
                'pages ${_list(out.renamed[id]!.keys)} each have their own "$id" (they draw it differently), and this page has none, so it opens nothing here. '
                'Write an overlay #$id on the page ${p.name} too, or have ${from.first} emit an event and open what each page has.',
          ));
        }
        return null;
      }
      return _handler(values[event]!, to);
    });
  }
  return out;
}