|
| 1 | +// What tool/record.dart does with a recorded turn, offline: the ops of a |
| 2 | +// ui_apply tool input applied as a session applies a stream (strict |
| 3 | +// validation per op against the catalog, the design system's components |
| 4 | +// and its tokens; the end of the stream; the lints of a finished UI), and |
| 5 | +// the design system a recording is made with, found by id or folder. |
| 6 | +// Pure Dart with dart:io: the record command and the tests use it, the app |
| 7 | +// does not. |
| 8 | +import 'dart:convert'; |
| 9 | +import 'dart:io'; |
| 10 | + |
| 11 | +import 'package:codelessly_api/core.dart'; |
| 12 | +import 'package:codelessly_api/validate.dart'; |
| 13 | + |
| 14 | +/// The design system [idOrPath] names: a design system folder (with a |
| 15 | +/// `design_system.json`), a bundle (`.json`, `tool/design_system_bundle.dart`), |
| 16 | +/// or an id, looked up as a folder of [designSystems] (the SDK's |
| 17 | +/// `design_systems/`, `../../design_systems` from this example) and then as |
| 18 | +/// a bundled asset (`assets/design_systems/<id>.json`). Throws a |
| 19 | +/// [StateError] that says what was tried when none is found or it does not |
| 20 | +/// load cleanly. |
| 21 | +Future<DesignSystem> loadDesignSystem(String idOrPath, {String designSystems = '../../design_systems'}) async { |
| 22 | + final tried = <String>[]; |
| 23 | + for (final dir in [idOrPath, '$designSystems/$idOrPath']) { |
| 24 | + tried.add(dir); |
| 25 | + if (!File('$dir/${DesignSystemManifest.fileName}').existsSync()) continue; |
| 26 | + final problems = <String>[]; |
| 27 | + final ds = await DesignSystem.load((ref) async { |
| 28 | + final f = File('$dir/$ref'); |
| 29 | + return f.existsSync() ? f.readAsStringSync() : null; |
| 30 | + }, problems: problems); |
| 31 | + if (problems.isNotEmpty) throw StateError('The design system at $dir does not load cleanly: ${problems.join('; ')}'); |
| 32 | + return ds; |
| 33 | + } |
| 34 | + for (final file in [idOrPath, 'assets/design_systems/$idOrPath.json']) { |
| 35 | + tried.add(file); |
| 36 | + if (file.endsWith('.json') && File(file).existsSync()) return DesignSystem.fromJson(jsonDecode(File(file).readAsStringSync())); |
| 37 | + } |
| 38 | + throw StateError('No design system "$idOrPath" (tried ${tried.join(', ')}).'); |
| 39 | +} |
| 40 | + |
| 41 | +/// What the recording's meta says about [ds]: its id, name and version. |
| 42 | +Map<String, Object?> designSystemMeta(DesignSystem ds) => {'id': ds.id, 'name': ds.name, 'version': ds.manifest.version}; |
| 43 | + |
| 44 | +/// How much of [doc] is made of [ds]: nodes whose type is one of its |
| 45 | +/// components, and nodes of a base control type it `replaces` (a raw |
| 46 | +/// `filledButton` where its `Button` was meant). A measure of whether a |
| 47 | +/// model used the design system. |
| 48 | +({int components, int replaced}) designSystemUsage(LayoutDocument doc, DesignSystem ds) { |
| 49 | + final replaces = ds.manifest.replaces.toSet(); |
| 50 | + var components = 0, replaced = 0; |
| 51 | + for (final n in doc.nodes.values) { |
| 52 | + if (ds.components[n.type] != null) components++; |
| 53 | + if (replaces.contains(n.type)) replaced++; |
| 54 | + } |
| 55 | + return (components: components, replaced: replaced); |
| 56 | +} |
| 57 | + |
| 58 | +/// The catalog a UI made with [ds] decodes with: the core catalog with its |
| 59 | +/// components' declarations. |
| 60 | +Catalog catalogFor(DesignSystem? ds) => ds?.catalogOver(Catalog.core) ?? Catalog.core; |
| 61 | + |
| 62 | +/// The ops of [toolInput] applied to [doc] as a session applies a stream: |
| 63 | +/// one by one (incomplete), strictly validated (against [designSystem]'s |
| 64 | +/// components and tokens when there is one), then the end of the stream and |
| 65 | +/// the lints. |
| 66 | +CheckedTurn checkToolInput(LayoutDocument doc, String toolInput, |
| 67 | + {required TrustProfile profile, required bool protect, required int rev, GlyphCoverage? coverage, DesignSystem? designSystem}) { |
| 68 | + final before = doc; |
| 69 | + final catalog = catalogFor(designSystem); |
| 70 | + // As UiSession(designSystem:) does: its components are types the agent may call. |
| 71 | + final allowed = designSystem == null ? profile : profile.withComponents(designSystem.components); |
| 72 | + final decoder = OpStreamDecoder(); |
| 73 | + final streamed = decoder.add(toolInput); |
| 74 | + final end = decoder.close(); |
| 75 | + final diagnostics = <EditDiagnostic>[...end.diagnostics]; |
| 76 | + final applied = <int>{}, rejected = <int>{}; |
| 77 | + final appliedOps = <EditOp>[]; |
| 78 | + final check = strictEditCheck(ValidateOptions(components: designSystem?.components, theme: designSystem?.tokens)); |
| 79 | + for (final s in streamed) { |
| 80 | + final r = applyOps(doc, [s.op], |
| 81 | + catalog: catalog, profile: allowed, check: check, incomplete: true, protectRoots: protect && before.roots.isNotEmpty); |
| 82 | + for (final d in r.diagnostics) { |
| 83 | + diagnostics.add(d.atOp(s.index)); |
| 84 | + } |
| 85 | + if (r.applied.isNotEmpty) { |
| 86 | + applied.add(s.index); |
| 87 | + appliedOps.add(s.op); |
| 88 | + doc = r.document; |
| 89 | + } else { |
| 90 | + rejected.add(s.index); |
| 91 | + } |
| 92 | + } |
| 93 | + for (final d in end.diagnostics) { |
| 94 | + if (d.error && d.op >= 0) rejected.add(d.op); |
| 95 | + } |
| 96 | + diagnostics.addAll(endOfStream(doc)); |
| 97 | + final lints = uiLints(doc, hasGlyph: coverage); |
| 98 | + diagnostics.addAll(lints); |
| 99 | + final result = EditResult( |
| 100 | + document: doc, |
| 101 | + applied: applied.difference(rejected).toList()..sort(), |
| 102 | + rejected: rejected.toList()..sort(), |
| 103 | + appliedOps: appliedOps, |
| 104 | + inverse: const [], |
| 105 | + diagnostics: diagnostics, |
| 106 | + pending: pendingIds(doc), |
| 107 | + rev: rev, |
| 108 | + revisions: const EditRevisions(), |
| 109 | + changed: const {}, |
| 110 | + ); |
| 111 | + return CheckedTurn(result, streamed.length, end, lints.length, designSystem); |
| 112 | +} |
| 113 | + |
| 114 | +/// One turn's ops as checked by [checkToolInput]. |
| 115 | +class CheckedTurn { |
| 116 | + CheckedTurn(this.result, this.ops, this.end, this.lints, this.designSystem); |
| 117 | + final EditResult result; |
| 118 | + final int ops; |
| 119 | + final OpStreamEnd end; |
| 120 | + final int lints; |
| 121 | + final DesignSystem? designSystem; |
| 122 | + LayoutDocument get document => result.document; |
| 123 | + |
| 124 | + /// Rejected, pending or linted: worth a retry. |
| 125 | + bool get needsFix => result.errors.isNotEmpty || result.pending.isNotEmpty || lints > 0; |
| 126 | + |
| 127 | + /// What goes back to the model as the ui_apply tool result. |
| 128 | + Map<String, Object?> toolResult(int rev) { |
| 129 | + final j = result.toModelJson(); |
| 130 | + if (lints > 0 && !j.containsKey('next')) j['next'] = fixInstruction(rev: rev, pending: result.pending); |
| 131 | + return j; |
| 132 | + } |
| 133 | + |
| 134 | + Map<String, Object?> counts() { |
| 135 | + final ds = designSystem; |
| 136 | + final usage = ds == null ? null : designSystemUsage(document, ds); |
| 137 | + return { |
| 138 | + 'ops': ops, |
| 139 | + 'opsApplied': result.applied.length, |
| 140 | + 'opsRejected': result.rejected.length, |
| 141 | + 'opsRecoveredFromMalformed': end.recovered, |
| 142 | + 'jsonRepairs': end.repairs, |
| 143 | + 'pending': result.pending.length, |
| 144 | + 'errors': [for (final d in result.errors) '${d.code} ${d.path}'], |
| 145 | + 'lints': [for (final d in result.warnings) if (const {'empty_button', 'low_contrast', 'missing_glyph'}.contains(d.code)) '${d.code} ${d.nodeId}'], |
| 146 | + 'warnings': result.warnings.length, |
| 147 | + 'nodes': document.nodes.length, |
| 148 | + 'scripts': (document.extra['scripts'] as List?)?.length ?? 0, |
| 149 | + 'scriptChars': [for (final s in (document.extra['scripts'] as List?) ?? const []) '${(s as Map)['source'] ?? ''}'.length].fold<int>(0, (a, b) => a + b), |
| 150 | + if (usage != null) 'designSystemComponents': usage.components, |
| 151 | + if (usage != null) 'replacedControls': usage.replaced, |
| 152 | + }; |
| 153 | + } |
| 154 | +} |
0 commit comments