nandi/frqpublic Fork 0
abb8e366325685adc993796ccc13a0ac72d009dd
Commits
Clone
git clone https://git.rickub.com/nandi/frq.git
git clone ssh://git@rickub.com/nandi/frq.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

nim_renderer.dart · 730 lines · 27.9 KBDart Blame HistoryRaw
The data model, in Nim d333b6f nandi yesterday1/// The renderer: a Nim widget tree, walked into Flutter widgets.
2///
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday3/// This knows the tag vocabulary and nothing else — no screens, no state, no
4/// idea what "connect" means. Nim decides what the screen is; this decides
5/// what a `vbox` looks like.
The data model, in Nim d333b6f nandi yesterday6///
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday7/// The measure of whether the split is honest is how boring this file is. If a
8/// feature ever needs a change here AND in Nim, the boundary is in the wrong
9/// place. The treatments are `flutter/src/frq/hiccup.cljd`'s, so a tree from
10/// Nim paints the way the same tree painted under ClojureDart.
11library;
12
The data model, in Nim d333b6f nandi yesterday13import 'dart:async';
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday14import 'dart:io';
The data model, in Nim d333b6f nandi yesterday15
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday16import 'package:flutter/gestures.dart';
17
The data model, in Nim d333b6f nandi yesterday18import 'package:flutter/material.dart';
19import 'package:frq_core/frq_core.dart' as core;
20
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday21import 'nim_theme.dart' as t;
22
The data model, in Nim d333b6f nandi yesterday23class NimApp extends StatefulWidget {
24 const NimApp({super.key});
25 @override
26 State<NimApp> createState() => _NimAppState();
27}
28
29class _NimAppState extends State<NimApp> {
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday30 late core.UiFrame _frame = core.renderFrame();
31 core.UiNode get _tree => _frame.tree;
The data model, in Nim d333b6f nandi yesterday32 Timer? _poll;
33
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday34 // One controller and one focus node per keyed entry, kept across rebuilds.
35 //
36 // This is why `:key` is on every entry in both the Clojure and the Nim: a
37 // controller identified by position instead of name meant the host field and
38 // the port field shared one and both showed the port. The focus node is the
39 // same bug one layer up — the field is rebuilt from a fresh tree on every
40 // keystroke, so without a node held per key the caret goes nowhere after the
41 // first line.
42 final _controllers = <String, TextEditingController>{};
43 final _focus = <String, FocusNode>{};
44
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday45 // One tap recogniser per link URL, kept across rebuilds and disposed with
46 // the state. A recogniser made during build and dropped on the next frame
47 // leaks, and this tree is rebuilt on every keystroke.
48 final _linkTaps = <String, TapGestureRecognizer>{};
49
Both ends of a scroll, on the same controller 5594a62 nandi 22h ago50 // One ScrollController per `scrollKey`, for the same reason the entries
51 // have one per key — and for a second reason of its own. A `Scrollbar` with
52 // no controller of its own asks the PrimaryScrollController, and a
53 // SingleChildScrollView is only primary on mobile: on a desktop the two
54 // ends looked at different controllers, so the first wheel event over any
55 // scroll threw "The Scrollbar's ScrollController has no ScrollPosition
56 // attached" and went on throwing it. Naming the controller joins them.
57 //
58 // Two positions must never share one, which is what makes `scrollKey` a
59 // requirement rather than a nicety — the chat screen's is per room, since
60 // switching rooms is a different backlog at a different offset.
61 final _scrollers = <String, ScrollController>{};
62
The data model, in Nim d333b6f nandi yesterday63 @override
64 void initState() {
65 super.initState();
66 // Polling, because the socket lives on a Nim thread and there is no
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday67 // callback into Dart. At ~70µs a render a 100ms timer costs nothing.
The data model, in Nim d333b6f nandi yesterday68 _poll = Timer.periodic(const Duration(milliseconds: 100), (_) {
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday69 // Compared as the JSON Nim already produced, and decoded only when it
70 // differs. Stringifying both trees to answer "did anything change" was
71 // ~1MB of string churn per poll in a busy room, ten times a second, for
72 // an answer that is almost always no.
73 final next = core.pollIfChanged(_frame.json);
74 if (next != null) setState(() => _frame = next);
The data model, in Nim d333b6f nandi yesterday75 });
76 }
77
78 void _send(String id, [String value = '']) {
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday79 if (id.isEmpty) return;
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday80 setState(() => _frame = core.dispatchFrame(id, value));
The data model, in Nim d333b6f nandi yesterday81 if (id == 'send') _focus['draft']?.requestFocus();
82 }
83
84 @override
85 void dispose() {
86 _poll?.cancel();
87 for (final c in _controllers.values) {
88 c.dispose();
89 }
90 for (final f in _focus.values) {
91 f.dispose();
92 }
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday93 for (final r in _linkTaps.values) {
94 r.dispose();
95 }
Both ends of a scroll, on the same controller 5594a62 nandi 22h ago96 for (final c in _scrollers.values) {
97 c.dispose();
98 }
The data model, in Nim d333b6f nandi yesterday99 super.dispose();
100 }
101
102 @override
103 Widget build(BuildContext context) => MaterialApp(
104 title: 'frq',
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday105 debugShowCheckedModeBanner: false,
106 theme: ThemeData(
107 useMaterial3: true,
108 brightness: Brightness.dark,
109 scaffoldBackgroundColor: t.bg,
110 colorScheme: const ColorScheme.dark(
111 primary: t.accent,
112 onPrimary: t.onAccent,
113 surface: t.bg,
114 onSurface: t.onBg,
115 error: t.destructive,
116 ),
The data model, in Nim d333b6f nandi yesterday117 ),
Text can be selected ec74784 nandi 21h ago118 // Everything inside one SelectionArea, so a message can be selected
119 // and copied — and so can a nick, a timestamp, or a line of an error.
120 // Per-widget `SelectableText` was the alternative and is worse: it
121 // selects within one widget only, so a two-line answer and the name
122 // above it cannot be dragged across, which is most of what anyone
123 // wants to copy out of a chat.
124 //
125 // Taps still arrive: a selection starts on a drag, and the buttons,
126 // faces and reaction pills under here keep their gestures.
127 home: Scaffold(
128 backgroundColor: t.bg,
129 body: SafeArea(child: SelectionArea(child: _build(_tree))),
130 ),
The data model, in Nim d333b6f nandi yesterday131 );
132
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday133 // ---------------------------------------------------------------- helpers
134
135 TextStyle _style(double size, Color color) =>
136 TextStyle(fontSize: size, color: color, height: 1.35);
137
The pencil was drawn by a text font 1cb40af nandi 23h ago138 /// The style for a widget whose whole content is an emoji glyph.
139 ///
140 /// Naming the colour emoji font is not belt and braces: a glyph like ✏️ is
141 /// U+270F plus U+FE0F, and the variation selector is a *request* for emoji
142 /// presentation, not a guarantee. DejaVu Sans claims U+270F, so ordinary
143 /// fallback stops there and draws the monochrome pencil the text era had —
144 /// while 🙂, which no text font covers, falls all the way through to the
145 /// emoji font and looks right. That is why only some of the chips were
146 /// wrong.
147 ///
148 /// A family list rather than one name, because the font that has them
149 /// differs by platform, and a name nothing matches costs nothing.
150 static const List<String> _emojiFonts = <String>[
151 'Noto Color Emoji', // Linux, Android
152 'Apple Color Emoji', // macOS, iOS
153 'Segoe UI Emoji', // Windows
154 ];
155
156 TextStyle _emojiStyle(double size) => TextStyle(
157 fontSize: size,
158 fontFamily: _emojiFonts.first,
159 fontFamilyFallback: _emojiFonts,
160 );
161
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday162 double _d(dynamic v, double fallback) =>
163 v is num ? v.toDouble() : fallback;
164
165 /// Gaps between children, as real widgets rather than a `spacing:` — the
166 /// same layout on every Flutter version this might be built against.
167 List<Widget> _spaced(List<Widget> kids, double gap, {required bool vertical}) {
168 if (gap <= 0 || kids.length < 2) return kids;
169 final out = <Widget>[];
170 for (var i = 0; i < kids.length; i++) {
171 if (i > 0) {
172 out.add(vertical ? SizedBox(height: gap) : SizedBox(width: gap));
173 }
174 out.add(kids[i]);
175 }
176 return out;
177 }
178
179 /// A source that may be a bundled asset, a file on disk, or a URL — the
180 /// three the screens hand over, named apart by an `asset:` prefix so they
181 /// stay one property.
182 ImageProvider? _imageProvider(String src) {
183 if (src.isEmpty) return null;
184 if (src.startsWith('asset:')) return AssetImage(src.substring(6));
185 if (src.startsWith('http://') || src.startsWith('https://')) {
186 return NetworkImage(src);
187 }
188 return FileImage(File(src));
189 }
190
191 Widget _wrapTap(String onClick, Widget child, {BorderRadius? radius}) {
192 if (onClick.isEmpty) return child;
193 return InkWell(
194 onTap: () => _send(onClick),
195 borderRadius: radius,
196 child: child,
197 );
198 }
199
200 // ------------------------------------------------------------------ build
201
Expanded only where a Flex can hold it f1e99b4 nandi yesterday202 /// The axis of the widget a node is being built *into*, because `Expanded`
203 /// is only legal inside a Flex and there is no way to ask Flutter after the
204 /// fact.
205 ///
206 /// Getting this wrong is what "Cannot hit test a render box that has never
207 /// been laid out" means, in a pile: an `Expanded` inside a `Wrap` fails the
208 /// layout, and every box under it is then asked to hit-test without ever
209 /// having been laid out. The chats screen did exactly that — two unsized
210 /// entries in an `hbox`, which is a Wrap.
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday211 /// What an unsized entry or a stranded scroll falls back to.
212 ///
213 /// Both are only reachable when the tree has put one outside a Flex, which
214 /// is a tree bug rather than a rendering choice. The numbers exist so that
215 /// bug renders as something a person can see and a test can catch, not so
216 /// that it renders correctly.
217 static const _unsizedEntry = 320.0;
218 static const _strandedScroll = 400.0;
219
Expanded only where a Flex can hold it f1e99b4 nandi yesterday220 static const _noAxis = '';
221 static const _row = 'row';
222 static const _column = 'column';
223
224 Widget _build(core.UiNode n, [String axis = _noAxis]) {
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday225 final spacing = _d(n.props['spacing'], 0);
Expanded only where a Flex can hold it f1e99b4 nandi yesterday226 final flex = axis == _row || axis == _column;
227
228 // What this node's own children are being built into.
229 final childAxis = switch (n.tag) {
230 'page' || 'vbox' || 'card' || 'scroll' || 'dialog' => _column,
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday231 // Wrapping unless the row says otherwise. Flipping this default was
232 // tried and reverted: only 4 of 15 `hbox` call sites state `wrap` at
233 // all, so the other 11 became Rows and overflowed — the tree's habit is
234 // to wrap, and the default has to match it.
Expanded only where a Flex can hold it f1e99b4 nandi yesterday235 'hbox' => n.prop('wrap', true) ? _noAxis : _row,
236 _ => _noAxis,
237 };
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday238 // A paragraph's children are spans, not widgets — building them as
239 // widgets and throwing them away is what the `inline` special case did.
240 final kids = n.tag == 'paragraph'
241 ? const <Widget>[]
242 : n.children.map((c) => _build(c, childAxis)).toList();
243
244 // One rule for "take the remaining main-axis extent", stated by the node
245 // that expands. It used to be three: a vbox prop, a scroll with no
246 // height, and a row peering at its children's props to infer it.
247 Widget expanded(Widget w) =>
248 (n.prop('expand', false) && flex) ? Expanded(child: w) : w;
The data model, in Nim d333b6f nandi yesterday249
250 switch (n.tag) {
251 case 'page':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday252 return SingleChildScrollView(
253 child: Center(
254 child: ConstrainedBox(
255 constraints:
256 BoxConstraints(maxWidth: _d(n.props['maxWidth'], 520)),
257 child: Padding(
258 padding: const EdgeInsets.all(t.spaceM),
259 child: Column(
260 crossAxisAlignment: CrossAxisAlignment.start,
261 children: _spaced(kids, spacing, vertical: true)),
262 ),
The data model, in Nim d333b6f nandi yesterday263 ),
264 ),
265 );
266
267 case 'vbox':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday268 {
269 Widget col = Column(
270 crossAxisAlignment: CrossAxisAlignment.start,
271 mainAxisSize: MainAxisSize.min,
272 children: _spaced(kids, spacing, vertical: true),
273 );
274 col = _margins(n, col);
275 final w = _d(n.props['widthRequest'], 0);
276 if (w > 0) col = SizedBox(width: w, child: col);
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday277 return expanded(col);
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday278 }
The data model, in Nim d333b6f nandi yesterday279
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday280 // Prose with links in it. NOT a Wrap: children of a Wrap are given
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday281 // unbounded width, so a long URL or a long word can never wrap — it
282 // overflows, the layout fails, and every box under it is then hit-tested
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday283 // having never been laid out. Spans in one RichText wrap properly.
284 case 'paragraph':
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday285 return Text.rich(
286 TextSpan(children: n.children.map(_span).toList()),
287 softWrap: true,
288 );
289
The data model, in Nim d333b6f nandi yesterday290 case 'hbox':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday291 {
292 // Wrap and not Row: `:hbox` in the screens means "these go together
293 // across", not "these fit". The head row of the chat screen asks for
294 // more than 360 points has, and a Row answers that with an overflow
295 // rather than a second line.
296 final wrapping = n.prop('wrap', true);
297 final align = n.prop('align', 'center');
298 if (!wrapping) {
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday299 // An expanding row stretches on its cross axis, which is where a
300 // child's height comes from — Expanded in a Row is about width.
301 // Stretch needs a bounded height, and `expanded()` below is what
302 // gives the row one; without it the stretch resolves to infinity.
303 final fills = n.prop('expand', false);
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday304 final row = Row(
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday305 crossAxisAlignment: fills
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday306 ? CrossAxisAlignment.stretch
307 : (align == 'end'
308 ? CrossAxisAlignment.end
309 : CrossAxisAlignment.center),
310 children: _spaced(kids, spacing, vertical: false),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday311 );
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday312 return expanded(_margins(n, row));
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday313 }
314 return _margins(
315 n,
316 Wrap(
317 spacing: spacing,
318 runSpacing: spacing,
319 crossAxisAlignment: align == 'end'
320 ? WrapCrossAlignment.end
321 : WrapCrossAlignment.center,
322 children: kids,
The data model, in Nim d333b6f nandi yesterday323 ),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday324 );
325 }
The data model, in Nim d333b6f nandi yesterday326
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday327 // Container::Card in the Clojure: padding 12, fills its width.
The data model, in Nim d333b6f nandi yesterday328 case 'card':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday329 return Container(
330 width: double.infinity,
331 margin: const EdgeInsets.symmetric(vertical: t.spaceXxxs),
332 padding: const EdgeInsets.all(t.spaceXs),
333 decoration: BoxDecoration(
334 color: t.card,
335 borderRadius: BorderRadius.circular(t.radiusS),
The data model, in Nim d333b6f nandi yesterday336 ),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday337 child: Column(
338 crossAxisAlignment: CrossAxisAlignment.start,
339 children: _spaced(kids, spacing > 0 ? spacing : t.spaceXxs,
340 vertical: true)),
The data model, in Nim d333b6f nandi yesterday341 );
342
343 case 'title':
344 return Text(n.prop('label', ''),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday345 style: _style(t.textTitle3, t.onBg)
346 .copyWith(fontWeight: FontWeight.bold));
The data model, in Nim d333b6f nandi yesterday347
348 case 'title-2':
349 return Padding(
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday350 padding: const EdgeInsets.only(top: t.spaceXxs, bottom: t.spaceXxxs),
The data model, in Nim d333b6f nandi yesterday351 child: Text(n.prop('label', ''),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday352 style: _style(t.textTitle4, t.onBg)
353 .copyWith(fontWeight: FontWeight.w600)),
The data model, in Nim d333b6f nandi yesterday354 );
355
356 case 'label':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday357 return Text(n.prop('label', ''), style: _style(t.textBody, t.onBg));
The data model, in Nim d333b6f nandi yesterday358
359 case 'dim-label':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday360 return Text(n.prop('label', ''), style: _style(t.textCaption, t.dim));
361
362 /// Prose, as opposed to a label: this is what a message is, and it
363 /// wraps. Kept apart from `label` because a wrapping label in a row
364 /// lays out against the row's width rather than the column's.
365 case 'text':
366 return Text(n.prop('text', ''), style: _style(t.textBody, t.onBg));
367
368 case 'link':
369 return _wrapTap(
370 n.prop('onClick', ''),
371 Text(
372 n.prop('label', ''),
373 style: _style(t.textBody, t.accent)
374 .copyWith(decoration: TextDecoration.underline,
375 decorationColor: t.accent),
376 ),
377 );
378
379 case 'separator':
380 return const Divider(height: 1, thickness: 1, color: t.divider);
381
382 case 'spacer':
383 {
384 final s = _d(n.props['size'], t.spaceXxs);
385 return SizedBox(width: s, height: s);
386 }
The data model, in Nim d333b6f nandi yesterday387
388 case 'spinner':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday389 return Row(
390 mainAxisSize: MainAxisSize.min,
391 children: [
392 const SizedBox(
393 width: 16,
394 height: 16,
395 child: CircularProgressIndicator(
396 strokeWidth: 2, color: t.accent)),
397 if (n.prop('label', '').isNotEmpty) ...[
398 const SizedBox(width: t.spaceXxs),
399 Text(n.prop('label', ''), style: _style(t.textCaption, t.dim)),
400 ],
401 ],
402 );
403
404 /// A dot that says whether the thing is live, and the words beside it.
405 case 'status':
406 return Row(
407 mainAxisSize: MainAxisSize.min,
408 children: [
409 Container(
410 width: 8,
411 height: 8,
412 decoration: BoxDecoration(
413 color: n.prop('live', false) ? t.success : t.dim,
414 borderRadius: BorderRadius.circular(t.radiusXs),
415 ),
416 ),
417 const SizedBox(width: 6),
418 Text(n.prop('label', ''), style: _style(t.textCaption, t.dim)),
419 ],
420 );
The data model, in Nim d333b6f nandi yesterday421
422 case 'button':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday423 {
424 final onClick = n.prop('onClick', '');
425 final kind = n.prop('kind', 'default');
426 final label = Text(n.prop('label', ''));
427 if (kind == 'primary') {
428 return FilledButton(
429 onPressed: () => _send(onClick), child: label);
430 }
A face that opens someone 9bb81a1 nandi yesterday431 // A sender's name: a way in to who someone is, but it sits in the
432 // middle of a line and must not look like a control. Text that
433 // takes a press, with no chrome at all.
434 if (kind == 'plain') {
435 return InkWell(
436 onTap: () => _send(onClick),
437 child: Text(n.prop('label', ''),
438 style: _style(t.textBody, t.onBg)),
439 );
440 }
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday441 if (kind == 'destructive') {
442 return FilledButton(
443 style: FilledButton.styleFrom(
444 backgroundColor: t.destructive,
445 foregroundColor: t.onDestructive),
446 onPressed: () => _send(onClick),
447 child: label,
448 );
449 }
450 return OutlinedButton(onPressed: () => _send(onClick), child: label);
451 }
The data model, in Nim d333b6f nandi yesterday452
453 case 'checkbutton':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday454 {
455 // The label is part of the target. 20 logical pixels is a fine tick
456 // on a desktop pointer and a miss on a thumb, so the whole row taps.
457 final onToggled = n.prop('onToggled', '');
458 return InkWell(
459 onTap: () => _send(onToggled),
460 child: Row(
461 mainAxisSize: MainAxisSize.min,
462 children: [
463 Checkbox(
464 value: n.prop('active', false),
465 onChanged: (_) => _send(onToggled),
466 ),
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday467 // Flexible, because the label is prose and the row is as wide
468 // as the window: "Hide join/part messages" beside a checkbox
469 // overflows a phone otherwise.
470 Flexible(
471 child: Text(n.prop('label', ''),
472 style: _style(t.textBody, t.onBg)),
473 ),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday474 ],
475 ),
476 );
477 }
478
479 case 'emoji':
480 return _wrapTap(
481 n.prop('onClick', ''),
482 Text(n.prop('glyph', n.prop('emoji', '')),
The pencil was drawn by a text font 1cb40af nandi 23h ago483 style: _emojiStyle(_d(n.props['size'], 16))),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday484 );
485
486 /// A reaction pill: the glyph, and the tally beside it where there is
487 /// one to show. The same shape whether it is a reaction under a message,
488 /// a swatch in the picker, or a chip on the sender's row — which is the
489 /// point: what you press to react and what appears once you have should
490 /// look like one family.
491 ///
492 /// A count of zero is no count. The picker passes 0 for every swatch,
493 /// and a grid of little grey zeroes is noise where a reader is scanning
494 /// for a face. `mine` is the accent, because the only thing a pill has
495 /// to say at a glance is whether pressing it again takes yours off.
496 case 'reaction':
497 {
498 final size = _d(n.props['size'], 14);
499 final count = n.prop('count', 0);
500 final mine = n.prop('mine', false);
501 final pad = (0.25 * size).clamp(2.0, 8.0);
502 return _wrapTap(
503 n.prop('onClick', ''),
504 Container(
505 padding: EdgeInsets.symmetric(horizontal: pad, vertical: pad / 2),
506 decoration: BoxDecoration(
507 color: mine ? t.accent : t.component,
508 borderRadius: BorderRadius.circular(t.radiusS),
509 ),
510 child: Row(
511 mainAxisSize: MainAxisSize.min,
512 children: [
The pencil was drawn by a text font 1cb40af nandi 23h ago513 Text(n.prop('emoji', ''), style: _emojiStyle(size)),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday514 if (count > 0) ...[
515 const SizedBox(width: 4),
516 Text('$count',
517 style: _style(t.textCaption,
518 mine ? t.onAccent : t.dim)),
519 ],
520 ],
521 ),
522 ),
523 );
524 }
525
526 /// A face is a way in to who someone is, so it takes the press that
527 /// opens their profile. A picture that will not load is a face that
528 /// stays its initial and nothing else.
529 case 'avatar':
530 {
531 final size = _d(n.props['size'], 32);
532 final provider = _imageProvider(n.prop('url', ''));
533 final fallback = n.prop('fallback', '');
534 final face = CircleAvatar(
535 radius: size / 2,
536 backgroundColor: t.component,
537 backgroundImage: provider,
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday538 onBackgroundImageError: provider == null ? null : (_, _) {},
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday539 child: provider == null
540 ? Text(
541 fallback.isNotEmpty
542 ? fallback.substring(0, 1).toUpperCase()
543 : '?',
544 style: _style(t.textBody, t.onBg))
545 : null,
546 );
547 final onClick = n.prop('onClick', '');
548 if (onClick.isEmpty) return face;
549 return InkWell(
550 onTap: () => _send(onClick),
551 customBorder: const CircleBorder(),
552 child: face,
553 );
554 }
555
556 case 'image':
557 {
558 final provider = _imageProvider(n.prop('src', ''));
559 if (provider == null) return const SizedBox.shrink();
560 final maxW = _d(n.props['maxWidth'], 0);
561 final maxH = _d(n.props['maxHeight'], 0);
562 Widget img = Image(
563 image: provider,
564 fit: BoxFit.contain,
565 // A half-written cache file, or one deleted under us: the decoder
566 // throws during the build, and an exception in a build is a red
567 // screen for the whole conversation rather than a gap where one
568 // picture was.
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday569 errorBuilder: (_, _, _) => const SizedBox.shrink(),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday570 );
571 if (maxW > 0 || maxH > 0) {
572 img = ConstrainedBox(
573 constraints: BoxConstraints(
574 maxWidth: maxW > 0 ? maxW : double.infinity,
575 maxHeight: maxH > 0 ? maxH : double.infinity,
576 ),
577 child: img,
578 );
579 }
580 return _wrapTap(n.prop('onClick', ''), img);
581 }
The data model, in Nim d333b6f nandi yesterday582
583 case 'entry':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday584 {
585 final key = n.prop('key', '');
586 final value = n.prop('text', '');
587 final c = _controllers.putIfAbsent(
588 key, () => TextEditingController(text: value));
589 // Only when it actually differs: assigning unconditionally moves the
590 // caret to the end on every keystroke.
591 if (c.text != value) {
592 c.value = c.value.copyWith(
593 text: value,
594 selection: TextSelection.collapsed(offset: value.length),
595 );
596 }
597 final field = TextField(
598 controller: c,
599 focusNode: _focus.putIfAbsent(key, FocusNode.new),
600 style: _style(t.textBody, t.onBg),
601 decoration: InputDecoration(
602 hintText: n.prop('placeholder', ''),
603 hintStyle: _style(t.textBody, t.dim),
604 isDense: true,
605 filled: true,
606 fillColor: t.component,
607 border: OutlineInputBorder(
608 borderRadius: BorderRadius.circular(t.radiusS),
609 borderSide: BorderSide.none,
610 ),
611 ),
612 onChanged: (v) => _send(n.prop('onChange', ''), v),
613 onSubmitted: (_) => _send(n.prop('onSubmit', '')),
614 );
615 final w = _d(n.props['widthRequest'], 0);
Expanded only where a Flex can hold it f1e99b4 nandi yesterday616 if (w > 0) return SizedBox(width: w, child: field);
617 // No width asked for: take the rest of the row where there is a row
618 // to take it from, and otherwise a definite width. NOT Expanded
619 // unconditionally — a TextField has no intrinsic width, so in a Wrap
620 // it is both illegal and unmeasurable, and that combination is what
621 // took the whole screen down rather than one field.
622 return axis == _row
623 ? Expanded(child: field)
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday624 : SizedBox(width: _unsizedEntry, child: field);
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday625 }
626
627 case 'scroll':
628 {
Both ends of a scroll, on the same controller 5594a62 nandi 22h ago629 // Both ends of the same scroll, named so they are the same one.
630 final c = _scrollers.putIfAbsent(
631 n.prop('scrollKey', 'scroll'), ScrollController.new);
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday632 Widget body = SingleChildScrollView(
Both ends of a scroll, on the same controller 5594a62 nandi 22h ago633 controller: c,
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday634 // The backlog reads from the bottom; a settings list from the top.
635 reverse: n.prop('stickToBottom', false),
636 child: Column(
637 crossAxisAlignment: CrossAxisAlignment.start,
638 children: _spaced(kids, spacing, vertical: true)),
The data model, in Nim d333b6f nandi yesterday639 );
Both ends of a scroll, on the same controller 5594a62 nandi 22h ago640 body = Scrollbar(controller: c, child: body);
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday641 // A scroll takes what the column has left. Outside a Flex there is
642 // nothing to take, and the tree is malformed — `_strandedScroll` is
643 // a visible size rather than a correct one, so the layout tests see
644 // a screen instead of an exception.
645 return flex
646 ? Expanded(child: body)
647 : const SizedBox(height: _strandedScroll);
The data model, in Nim d333b6f nandi yesterday648 }
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday649
650 /// A panel over the screen rather than a screen of its own.
651 case 'dialog':
652 return Card(
653 color: t.cardComponent,
654 child: Padding(
655 padding: const EdgeInsets.all(t.spaceS),
656 child: Column(
657 mainAxisSize: MainAxisSize.min,
658 crossAxisAlignment: CrossAxisAlignment.start,
659 children: [
660 if (n.prop('title', '').isNotEmpty)
661 Padding(
662 padding: const EdgeInsets.only(bottom: t.spaceXxs),
663 child: Text(n.prop('title', ''),
664 style: _style(t.textTitle4, t.onCard)
665 .copyWith(fontWeight: FontWeight.w600)),
666 ),
667 ..._spaced(kids, spacing, vertical: true),
668 ],
669 ),
The data model, in Nim d333b6f nandi yesterday670 ),
671 );
672
673 default:
674 // An unknown tag paints as itself rather than crashing or vanishing.
675 // Nim can add one and see it before this file has heard of it, which
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday676 // is what makes the boundary pleasant to work across.
The data model, in Nim d333b6f nandi yesterday677 return Container(
678 padding: const EdgeInsets.all(4),
679 color: Colors.orange.withValues(alpha: 0.3),
680 child: Text('?${n.tag}'),
681 );
682 }
683 }
684
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday685 /// One node of an inline paragraph, as a span.
686 ///
687 /// Only `text` and `link` appear here — they are the only things `runNodes`
688 /// emits — and anything else falls back to its plain text so an unexpected
689 /// tag degrades to something readable rather than vanishing.
690 InlineSpan _span(core.UiNode n) {
691 switch (n.tag) {
692 case 'link':
693 final url = n.prop('url', n.prop('label', ''));
694 final onClick = n.prop('onClick', '');
695 return TextSpan(
696 text: n.prop('label', ''),
697 style: _style(t.textBody, t.accent)
698 .copyWith(decoration: TextDecoration.underline,
699 decorationColor: t.accent),
700 recognizer: onClick.isEmpty
701 ? null
702 : (_linkTaps[url] ??= TapGestureRecognizer()
703 ..onTap = () => _send(onClick)),
704 );
705 case 'text':
706 return TextSpan(
707 text: n.prop('text', ''), style: _style(t.textBody, t.onBg));
708 default:
709 return TextSpan(
710 text: n.prop('label', n.prop('text', '')),
711 style: _style(t.textBody, t.onBg));
712 }
713 }
714
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday715 /// `margin` and its four sides — the props the
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday716 /// screens use to buy air without a wrapper each time.
717 Widget _margins(core.UiNode n, Widget child) {
718 final all = _d(n.props['margin'], 0);
719 final top = _d(n.props['marginTop'], all);
720 final bottom = _d(n.props['marginBottom'], all);
721 final right = _d(n.props['marginRight'], all);
722 final left = _d(n.props['marginLeft'], all);
723 if (top == 0 && bottom == 0 && right == 0 && left == 0) return child;
724 return Padding(
725 padding: EdgeInsets.only(
726 top: top, bottom: bottom, right: right, left: left),
727 child: child,
728 );
The data model, in Nim d333b6f nandi yesterday729 }
730}