nandi/frqpublic Fork 0
5594a62c4f5a20455b0742bc4521552c4f408a2e
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 · 718 lines · 27.3 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 20h 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 20h 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 ),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday118 home: Scaffold(backgroundColor: t.bg, body: SafeArea(child: _build(_tree))),
The data model, in Nim d333b6f nandi yesterday119 );
120
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday121 // ---------------------------------------------------------------- helpers
122
123 TextStyle _style(double size, Color color) =>
124 TextStyle(fontSize: size, color: color, height: 1.35);
125
The pencil was drawn by a text font 1cb40af nandi 20h ago126 /// The style for a widget whose whole content is an emoji glyph.
127 ///
128 /// Naming the colour emoji font is not belt and braces: a glyph like ✏️ is
129 /// U+270F plus U+FE0F, and the variation selector is a *request* for emoji
130 /// presentation, not a guarantee. DejaVu Sans claims U+270F, so ordinary
131 /// fallback stops there and draws the monochrome pencil the text era had —
132 /// while 🙂, which no text font covers, falls all the way through to the
133 /// emoji font and looks right. That is why only some of the chips were
134 /// wrong.
135 ///
136 /// A family list rather than one name, because the font that has them
137 /// differs by platform, and a name nothing matches costs nothing.
138 static const List<String> _emojiFonts = <String>[
139 'Noto Color Emoji', // Linux, Android
140 'Apple Color Emoji', // macOS, iOS
141 'Segoe UI Emoji', // Windows
142 ];
143
144 TextStyle _emojiStyle(double size) => TextStyle(
145 fontSize: size,
146 fontFamily: _emojiFonts.first,
147 fontFamilyFallback: _emojiFonts,
148 );
149
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday150 double _d(dynamic v, double fallback) =>
151 v is num ? v.toDouble() : fallback;
152
153 /// Gaps between children, as real widgets rather than a `spacing:` — the
154 /// same layout on every Flutter version this might be built against.
155 List<Widget> _spaced(List<Widget> kids, double gap, {required bool vertical}) {
156 if (gap <= 0 || kids.length < 2) return kids;
157 final out = <Widget>[];
158 for (var i = 0; i < kids.length; i++) {
159 if (i > 0) {
160 out.add(vertical ? SizedBox(height: gap) : SizedBox(width: gap));
161 }
162 out.add(kids[i]);
163 }
164 return out;
165 }
166
167 /// A source that may be a bundled asset, a file on disk, or a URL — the
168 /// three the screens hand over, named apart by an `asset:` prefix so they
169 /// stay one property.
170 ImageProvider? _imageProvider(String src) {
171 if (src.isEmpty) return null;
172 if (src.startsWith('asset:')) return AssetImage(src.substring(6));
173 if (src.startsWith('http://') || src.startsWith('https://')) {
174 return NetworkImage(src);
175 }
176 return FileImage(File(src));
177 }
178
179 Widget _wrapTap(String onClick, Widget child, {BorderRadius? radius}) {
180 if (onClick.isEmpty) return child;
181 return InkWell(
182 onTap: () => _send(onClick),
183 borderRadius: radius,
184 child: child,
185 );
186 }
187
188 // ------------------------------------------------------------------ build
189
Expanded only where a Flex can hold it f1e99b4 nandi yesterday190 /// The axis of the widget a node is being built *into*, because `Expanded`
191 /// is only legal inside a Flex and there is no way to ask Flutter after the
192 /// fact.
193 ///
194 /// Getting this wrong is what "Cannot hit test a render box that has never
195 /// been laid out" means, in a pile: an `Expanded` inside a `Wrap` fails the
196 /// layout, and every box under it is then asked to hit-test without ever
197 /// having been laid out. The chats screen did exactly that — two unsized
198 /// entries in an `hbox`, which is a Wrap.
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday199 /// What an unsized entry or a stranded scroll falls back to.
200 ///
201 /// Both are only reachable when the tree has put one outside a Flex, which
202 /// is a tree bug rather than a rendering choice. The numbers exist so that
203 /// bug renders as something a person can see and a test can catch, not so
204 /// that it renders correctly.
205 static const _unsizedEntry = 320.0;
206 static const _strandedScroll = 400.0;
207
Expanded only where a Flex can hold it f1e99b4 nandi yesterday208 static const _noAxis = '';
209 static const _row = 'row';
210 static const _column = 'column';
211
212 Widget _build(core.UiNode n, [String axis = _noAxis]) {
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday213 final spacing = _d(n.props['spacing'], 0);
Expanded only where a Flex can hold it f1e99b4 nandi yesterday214 final flex = axis == _row || axis == _column;
215
216 // What this node's own children are being built into.
217 final childAxis = switch (n.tag) {
218 'page' || 'vbox' || 'card' || 'scroll' || 'dialog' => _column,
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday219 // Wrapping unless the row says otherwise. Flipping this default was
220 // tried and reverted: only 4 of 15 `hbox` call sites state `wrap` at
221 // all, so the other 11 became Rows and overflowed — the tree's habit is
222 // to wrap, and the default has to match it.
Expanded only where a Flex can hold it f1e99b4 nandi yesterday223 'hbox' => n.prop('wrap', true) ? _noAxis : _row,
224 _ => _noAxis,
225 };
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday226 // A paragraph's children are spans, not widgets — building them as
227 // widgets and throwing them away is what the `inline` special case did.
228 final kids = n.tag == 'paragraph'
229 ? const <Widget>[]
230 : n.children.map((c) => _build(c, childAxis)).toList();
231
232 // One rule for "take the remaining main-axis extent", stated by the node
233 // that expands. It used to be three: a vbox prop, a scroll with no
234 // height, and a row peering at its children's props to infer it.
235 Widget expanded(Widget w) =>
236 (n.prop('expand', false) && flex) ? Expanded(child: w) : w;
The data model, in Nim d333b6f nandi yesterday237
238 switch (n.tag) {
239 case 'page':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday240 return SingleChildScrollView(
241 child: Center(
242 child: ConstrainedBox(
243 constraints:
244 BoxConstraints(maxWidth: _d(n.props['maxWidth'], 520)),
245 child: Padding(
246 padding: const EdgeInsets.all(t.spaceM),
247 child: Column(
248 crossAxisAlignment: CrossAxisAlignment.start,
249 children: _spaced(kids, spacing, vertical: true)),
250 ),
The data model, in Nim d333b6f nandi yesterday251 ),
252 ),
253 );
254
255 case 'vbox':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday256 {
257 Widget col = Column(
258 crossAxisAlignment: CrossAxisAlignment.start,
259 mainAxisSize: MainAxisSize.min,
260 children: _spaced(kids, spacing, vertical: true),
261 );
262 col = _margins(n, col);
263 final w = _d(n.props['widthRequest'], 0);
264 if (w > 0) col = SizedBox(width: w, child: col);
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday265 return expanded(col);
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday266 }
The data model, in Nim d333b6f nandi yesterday267
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday268 // 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 yesterday269 // unbounded width, so a long URL or a long word can never wrap — it
270 // overflows, the layout fails, and every box under it is then hit-tested
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday271 // having never been laid out. Spans in one RichText wrap properly.
272 case 'paragraph':
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday273 return Text.rich(
274 TextSpan(children: n.children.map(_span).toList()),
275 softWrap: true,
276 );
277
The data model, in Nim d333b6f nandi yesterday278 case 'hbox':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday279 {
280 // Wrap and not Row: `:hbox` in the screens means "these go together
281 // across", not "these fit". The head row of the chat screen asks for
282 // more than 360 points has, and a Row answers that with an overflow
283 // rather than a second line.
284 final wrapping = n.prop('wrap', true);
285 final align = n.prop('align', 'center');
286 if (!wrapping) {
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday287 // An expanding row stretches on its cross axis, which is where a
288 // child's height comes from — Expanded in a Row is about width.
289 // Stretch needs a bounded height, and `expanded()` below is what
290 // gives the row one; without it the stretch resolves to infinity.
291 final fills = n.prop('expand', false);
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday292 final row = Row(
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday293 crossAxisAlignment: fills
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday294 ? CrossAxisAlignment.stretch
295 : (align == 'end'
296 ? CrossAxisAlignment.end
297 : CrossAxisAlignment.center),
298 children: _spaced(kids, spacing, vertical: false),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday299 );
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday300 return expanded(_margins(n, row));
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday301 }
302 return _margins(
303 n,
304 Wrap(
305 spacing: spacing,
306 runSpacing: spacing,
307 crossAxisAlignment: align == 'end'
308 ? WrapCrossAlignment.end
309 : WrapCrossAlignment.center,
310 children: kids,
The data model, in Nim d333b6f nandi yesterday311 ),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday312 );
313 }
The data model, in Nim d333b6f nandi yesterday314
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday315 // Container::Card in the Clojure: padding 12, fills its width.
The data model, in Nim d333b6f nandi yesterday316 case 'card':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday317 return Container(
318 width: double.infinity,
319 margin: const EdgeInsets.symmetric(vertical: t.spaceXxxs),
320 padding: const EdgeInsets.all(t.spaceXs),
321 decoration: BoxDecoration(
322 color: t.card,
323 borderRadius: BorderRadius.circular(t.radiusS),
The data model, in Nim d333b6f nandi yesterday324 ),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday325 child: Column(
326 crossAxisAlignment: CrossAxisAlignment.start,
327 children: _spaced(kids, spacing > 0 ? spacing : t.spaceXxs,
328 vertical: true)),
The data model, in Nim d333b6f nandi yesterday329 );
330
331 case 'title':
332 return Text(n.prop('label', ''),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday333 style: _style(t.textTitle3, t.onBg)
334 .copyWith(fontWeight: FontWeight.bold));
The data model, in Nim d333b6f nandi yesterday335
336 case 'title-2':
337 return Padding(
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday338 padding: const EdgeInsets.only(top: t.spaceXxs, bottom: t.spaceXxxs),
The data model, in Nim d333b6f nandi yesterday339 child: Text(n.prop('label', ''),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday340 style: _style(t.textTitle4, t.onBg)
341 .copyWith(fontWeight: FontWeight.w600)),
The data model, in Nim d333b6f nandi yesterday342 );
343
344 case 'label':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday345 return Text(n.prop('label', ''), style: _style(t.textBody, t.onBg));
The data model, in Nim d333b6f nandi yesterday346
347 case 'dim-label':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday348 return Text(n.prop('label', ''), style: _style(t.textCaption, t.dim));
349
350 /// Prose, as opposed to a label: this is what a message is, and it
351 /// wraps. Kept apart from `label` because a wrapping label in a row
352 /// lays out against the row's width rather than the column's.
353 case 'text':
354 return Text(n.prop('text', ''), style: _style(t.textBody, t.onBg));
355
356 case 'link':
357 return _wrapTap(
358 n.prop('onClick', ''),
359 Text(
360 n.prop('label', ''),
361 style: _style(t.textBody, t.accent)
362 .copyWith(decoration: TextDecoration.underline,
363 decorationColor: t.accent),
364 ),
365 );
366
367 case 'separator':
368 return const Divider(height: 1, thickness: 1, color: t.divider);
369
370 case 'spacer':
371 {
372 final s = _d(n.props['size'], t.spaceXxs);
373 return SizedBox(width: s, height: s);
374 }
The data model, in Nim d333b6f nandi yesterday375
376 case 'spinner':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday377 return Row(
378 mainAxisSize: MainAxisSize.min,
379 children: [
380 const SizedBox(
381 width: 16,
382 height: 16,
383 child: CircularProgressIndicator(
384 strokeWidth: 2, color: t.accent)),
385 if (n.prop('label', '').isNotEmpty) ...[
386 const SizedBox(width: t.spaceXxs),
387 Text(n.prop('label', ''), style: _style(t.textCaption, t.dim)),
388 ],
389 ],
390 );
391
392 /// A dot that says whether the thing is live, and the words beside it.
393 case 'status':
394 return Row(
395 mainAxisSize: MainAxisSize.min,
396 children: [
397 Container(
398 width: 8,
399 height: 8,
400 decoration: BoxDecoration(
401 color: n.prop('live', false) ? t.success : t.dim,
402 borderRadius: BorderRadius.circular(t.radiusXs),
403 ),
404 ),
405 const SizedBox(width: 6),
406 Text(n.prop('label', ''), style: _style(t.textCaption, t.dim)),
407 ],
408 );
The data model, in Nim d333b6f nandi yesterday409
410 case 'button':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday411 {
412 final onClick = n.prop('onClick', '');
413 final kind = n.prop('kind', 'default');
414 final label = Text(n.prop('label', ''));
415 if (kind == 'primary') {
416 return FilledButton(
417 onPressed: () => _send(onClick), child: label);
418 }
A face that opens someone 9bb81a1 nandi 22h ago419 // A sender's name: a way in to who someone is, but it sits in the
420 // middle of a line and must not look like a control. Text that
421 // takes a press, with no chrome at all.
422 if (kind == 'plain') {
423 return InkWell(
424 onTap: () => _send(onClick),
425 child: Text(n.prop('label', ''),
426 style: _style(t.textBody, t.onBg)),
427 );
428 }
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday429 if (kind == 'destructive') {
430 return FilledButton(
431 style: FilledButton.styleFrom(
432 backgroundColor: t.destructive,
433 foregroundColor: t.onDestructive),
434 onPressed: () => _send(onClick),
435 child: label,
436 );
437 }
438 return OutlinedButton(onPressed: () => _send(onClick), child: label);
439 }
The data model, in Nim d333b6f nandi yesterday440
441 case 'checkbutton':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday442 {
443 // The label is part of the target. 20 logical pixels is a fine tick
444 // on a desktop pointer and a miss on a thumb, so the whole row taps.
445 final onToggled = n.prop('onToggled', '');
446 return InkWell(
447 onTap: () => _send(onToggled),
448 child: Row(
449 mainAxisSize: MainAxisSize.min,
450 children: [
451 Checkbox(
452 value: n.prop('active', false),
453 onChanged: (_) => _send(onToggled),
454 ),
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday455 // Flexible, because the label is prose and the row is as wide
456 // as the window: "Hide join/part messages" beside a checkbox
457 // overflows a phone otherwise.
458 Flexible(
459 child: Text(n.prop('label', ''),
460 style: _style(t.textBody, t.onBg)),
461 ),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday462 ],
463 ),
464 );
465 }
466
467 case 'emoji':
468 return _wrapTap(
469 n.prop('onClick', ''),
470 Text(n.prop('glyph', n.prop('emoji', '')),
The pencil was drawn by a text font 1cb40af nandi 20h ago471 style: _emojiStyle(_d(n.props['size'], 16))),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday472 );
473
474 /// A reaction pill: the glyph, and the tally beside it where there is
475 /// one to show. The same shape whether it is a reaction under a message,
476 /// a swatch in the picker, or a chip on the sender's row — which is the
477 /// point: what you press to react and what appears once you have should
478 /// look like one family.
479 ///
480 /// A count of zero is no count. The picker passes 0 for every swatch,
481 /// and a grid of little grey zeroes is noise where a reader is scanning
482 /// for a face. `mine` is the accent, because the only thing a pill has
483 /// to say at a glance is whether pressing it again takes yours off.
484 case 'reaction':
485 {
486 final size = _d(n.props['size'], 14);
487 final count = n.prop('count', 0);
488 final mine = n.prop('mine', false);
489 final pad = (0.25 * size).clamp(2.0, 8.0);
490 return _wrapTap(
491 n.prop('onClick', ''),
492 Container(
493 padding: EdgeInsets.symmetric(horizontal: pad, vertical: pad / 2),
494 decoration: BoxDecoration(
495 color: mine ? t.accent : t.component,
496 borderRadius: BorderRadius.circular(t.radiusS),
497 ),
498 child: Row(
499 mainAxisSize: MainAxisSize.min,
500 children: [
The pencil was drawn by a text font 1cb40af nandi 20h ago501 Text(n.prop('emoji', ''), style: _emojiStyle(size)),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday502 if (count > 0) ...[
503 const SizedBox(width: 4),
504 Text('$count',
505 style: _style(t.textCaption,
506 mine ? t.onAccent : t.dim)),
507 ],
508 ],
509 ),
510 ),
511 );
512 }
513
514 /// A face is a way in to who someone is, so it takes the press that
515 /// opens their profile. A picture that will not load is a face that
516 /// stays its initial and nothing else.
517 case 'avatar':
518 {
519 final size = _d(n.props['size'], 32);
520 final provider = _imageProvider(n.prop('url', ''));
521 final fallback = n.prop('fallback', '');
522 final face = CircleAvatar(
523 radius: size / 2,
524 backgroundColor: t.component,
525 backgroundImage: provider,
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday526 onBackgroundImageError: provider == null ? null : (_, _) {},
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday527 child: provider == null
528 ? Text(
529 fallback.isNotEmpty
530 ? fallback.substring(0, 1).toUpperCase()
531 : '?',
532 style: _style(t.textBody, t.onBg))
533 : null,
534 );
535 final onClick = n.prop('onClick', '');
536 if (onClick.isEmpty) return face;
537 return InkWell(
538 onTap: () => _send(onClick),
539 customBorder: const CircleBorder(),
540 child: face,
541 );
542 }
543
544 case 'image':
545 {
546 final provider = _imageProvider(n.prop('src', ''));
547 if (provider == null) return const SizedBox.shrink();
548 final maxW = _d(n.props['maxWidth'], 0);
549 final maxH = _d(n.props['maxHeight'], 0);
550 Widget img = Image(
551 image: provider,
552 fit: BoxFit.contain,
553 // A half-written cache file, or one deleted under us: the decoder
554 // throws during the build, and an exception in a build is a red
555 // screen for the whole conversation rather than a gap where one
556 // picture was.
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday557 errorBuilder: (_, _, _) => const SizedBox.shrink(),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday558 );
559 if (maxW > 0 || maxH > 0) {
560 img = ConstrainedBox(
561 constraints: BoxConstraints(
562 maxWidth: maxW > 0 ? maxW : double.infinity,
563 maxHeight: maxH > 0 ? maxH : double.infinity,
564 ),
565 child: img,
566 );
567 }
568 return _wrapTap(n.prop('onClick', ''), img);
569 }
The data model, in Nim d333b6f nandi yesterday570
571 case 'entry':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday572 {
573 final key = n.prop('key', '');
574 final value = n.prop('text', '');
575 final c = _controllers.putIfAbsent(
576 key, () => TextEditingController(text: value));
577 // Only when it actually differs: assigning unconditionally moves the
578 // caret to the end on every keystroke.
579 if (c.text != value) {
580 c.value = c.value.copyWith(
581 text: value,
582 selection: TextSelection.collapsed(offset: value.length),
583 );
584 }
585 final field = TextField(
586 controller: c,
587 focusNode: _focus.putIfAbsent(key, FocusNode.new),
588 style: _style(t.textBody, t.onBg),
589 decoration: InputDecoration(
590 hintText: n.prop('placeholder', ''),
591 hintStyle: _style(t.textBody, t.dim),
592 isDense: true,
593 filled: true,
594 fillColor: t.component,
595 border: OutlineInputBorder(
596 borderRadius: BorderRadius.circular(t.radiusS),
597 borderSide: BorderSide.none,
598 ),
599 ),
600 onChanged: (v) => _send(n.prop('onChange', ''), v),
601 onSubmitted: (_) => _send(n.prop('onSubmit', '')),
602 );
603 final w = _d(n.props['widthRequest'], 0);
Expanded only where a Flex can hold it f1e99b4 nandi yesterday604 if (w > 0) return SizedBox(width: w, child: field);
605 // No width asked for: take the rest of the row where there is a row
606 // to take it from, and otherwise a definite width. NOT Expanded
607 // unconditionally — a TextField has no intrinsic width, so in a Wrap
608 // it is both illegal and unmeasurable, and that combination is what
609 // took the whole screen down rather than one field.
610 return axis == _row
611 ? Expanded(child: field)
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday612 : SizedBox(width: _unsizedEntry, child: field);
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday613 }
614
615 case 'scroll':
616 {
Both ends of a scroll, on the same controller 5594a62 nandi 20h ago617 // Both ends of the same scroll, named so they are the same one.
618 final c = _scrollers.putIfAbsent(
619 n.prop('scrollKey', 'scroll'), ScrollController.new);
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday620 Widget body = SingleChildScrollView(
Both ends of a scroll, on the same controller 5594a62 nandi 20h ago621 controller: c,
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday622 // The backlog reads from the bottom; a settings list from the top.
623 reverse: n.prop('stickToBottom', false),
624 child: Column(
625 crossAxisAlignment: CrossAxisAlignment.start,
626 children: _spaced(kids, spacing, vertical: true)),
The data model, in Nim d333b6f nandi yesterday627 );
Both ends of a scroll, on the same controller 5594a62 nandi 20h ago628 body = Scrollbar(controller: c, child: body);
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday629 // A scroll takes what the column has left. Outside a Flex there is
630 // nothing to take, and the tree is malformed — `_strandedScroll` is
631 // a visible size rather than a correct one, so the layout tests see
632 // a screen instead of an exception.
633 return flex
634 ? Expanded(child: body)
635 : const SizedBox(height: _strandedScroll);
The data model, in Nim d333b6f nandi yesterday636 }
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday637
638 /// A panel over the screen rather than a screen of its own.
639 case 'dialog':
640 return Card(
641 color: t.cardComponent,
642 child: Padding(
643 padding: const EdgeInsets.all(t.spaceS),
644 child: Column(
645 mainAxisSize: MainAxisSize.min,
646 crossAxisAlignment: CrossAxisAlignment.start,
647 children: [
648 if (n.prop('title', '').isNotEmpty)
649 Padding(
650 padding: const EdgeInsets.only(bottom: t.spaceXxs),
651 child: Text(n.prop('title', ''),
652 style: _style(t.textTitle4, t.onCard)
653 .copyWith(fontWeight: FontWeight.w600)),
654 ),
655 ..._spaced(kids, spacing, vertical: true),
656 ],
657 ),
The data model, in Nim d333b6f nandi yesterday658 ),
659 );
660
661 default:
662 // An unknown tag paints as itself rather than crashing or vanishing.
663 // 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 yesterday664 // is what makes the boundary pleasant to work across.
The data model, in Nim d333b6f nandi yesterday665 return Container(
666 padding: const EdgeInsets.all(4),
667 color: Colors.orange.withValues(alpha: 0.3),
668 child: Text('?${n.tag}'),
669 );
670 }
671 }
672
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday673 /// One node of an inline paragraph, as a span.
674 ///
675 /// Only `text` and `link` appear here — they are the only things `runNodes`
676 /// emits — and anything else falls back to its plain text so an unexpected
677 /// tag degrades to something readable rather than vanishing.
678 InlineSpan _span(core.UiNode n) {
679 switch (n.tag) {
680 case 'link':
681 final url = n.prop('url', n.prop('label', ''));
682 final onClick = n.prop('onClick', '');
683 return TextSpan(
684 text: n.prop('label', ''),
685 style: _style(t.textBody, t.accent)
686 .copyWith(decoration: TextDecoration.underline,
687 decorationColor: t.accent),
688 recognizer: onClick.isEmpty
689 ? null
690 : (_linkTaps[url] ??= TapGestureRecognizer()
691 ..onTap = () => _send(onClick)),
692 );
693 case 'text':
694 return TextSpan(
695 text: n.prop('text', ''), style: _style(t.textBody, t.onBg));
696 default:
697 return TextSpan(
698 text: n.prop('label', n.prop('text', '')),
699 style: _style(t.textBody, t.onBg));
700 }
701 }
702
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday703 /// `margin` and its four sides — the props the
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday704 /// screens use to buy air without a wrapper each time.
705 Widget _margins(core.UiNode n, Widget child) {
706 final all = _d(n.props['margin'], 0);
707 final top = _d(n.props['marginTop'], all);
708 final bottom = _d(n.props['marginBottom'], all);
709 final right = _d(n.props['marginRight'], all);
710 final left = _d(n.props['marginLeft'], all);
711 if (top == 0 && bottom == 0 && right == 0 && left == 0) return child;
712 return Padding(
713 padding: EdgeInsets.only(
714 top: top, bottom: bottom, right: right, left: left),
715 child: child,
716 );
The data model, in Nim d333b6f nandi yesterday717 }
718}