applyNotation method

Future<EditResult> applyNotation(
  1. Stream<String> text, {
  2. NotationOptions? options,
  3. String prelude = '',
  4. String author = 'agent',
  5. bool replace = false,
  6. void onOp(
    1. StreamProgress progress
    )?,
})

Applies a UI written in the compact notation (package:codelessly_api/notation.dart: one node per line, nested by indentation) as it arrives: each completed line becomes its edit operations and is applied at once, so the UI paints line by line. The rest is applyStream: one revision, one undo step, the same checks and result. What the notation could not read is in notationIssues.

With a designSystem, its blocks and components are called by name and its looks are the defaults (options replaces them): the looks it adds are written as the theme's names, so the UI follows dark mode and a change of design system, and a color the answer writes stays as written. prelude is notation the host puts before the model's answer: the state of an app's data contract, a screen's clock, anything that must be right and is not the model's to write (see notationInstructions). With replace, the UI the session holds is removed first, so the answer takes its place (a card written again once a block it wanted exists); without it, a session that has a UI takes changes to it, not a second one.

Implementation

Future<EditResult> applyNotation(
  Stream<String> text, {
  NotationOptions? options,
  String prelude = '',
  String author = 'agent',
  bool replace = false,
  void Function(StreamProgress progress)? onOp,
}) {
  final ds = designSystem;
  final old = replace ? [..._document.roots] : const <String>[];
  final used = options ?? (ds == null ? const NotationOptions() : NotationOptions.fromDesignSystem(ds, named: true));
  final notation = Catalog.run(catalog, () => NotationStream(catalog: catalog, options: used));
  Stream<String> ops() async* {
    yield '{"ops":[';
    var first = true;
    String encode(List<Json> ops) {
      final b = StringBuffer();
      for (final op in ops) {
        if (!first) b.write(',');
        first = false;
        b.write(jsonEncode(op));
      }
      return b.toString();
    }

    // The UI written before goes, in the same revision the new one arrives in.
    if (old.isNotEmpty) yield encode([RemoveOp(old).toJson()]);

    if (prelude.trim().isNotEmpty) {
      final out = encode(Catalog.run(catalog, () => notation.add('${prelude.trimRight()}\n')));
      if (out.isNotEmpty) yield out;
    }
    await for (final chunk in text) {
      final out = encode(Catalog.run(catalog, () => notation.add(chunk)));
      if (out.isNotEmpty) yield out;
    }
    final out = encode(Catalog.run(catalog, notation.close));
    if (out.isNotEmpty) yield out;
    yield ']}';
  }

  return applyStream(ops(), author: author, onOp: onOp, protect: old.isEmpty ? null : false).whenComplete(() {
    _notationIssues = notation.issues;
    _wantedBlocks = notation.wanted;
  });
}