nandi/frqpublic Fork 0
4925e54c9cbf2c2fa55214ac147d458c00384a20
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 · 795 lines · 30.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 21h 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 arrow goes to the message 4925e54 nandi 13h ago63 // Where a "go to that message" is pointing, for the one frame it is
64 // pointing there. The core marks the row with `scrollHere`, this finds it
65 // after the frame is laid out — `ensureVisible` needs a built element, so
66 // it cannot happen during the build that asks for it — and then tells the
67 // core it has arrived, which takes the mark off. Leaving it on would pin
68 // the view to that row and take scrolling away from the reader.
69 final _jumpKey = GlobalKey();
70
71 // The last `scrollToBottom` tick acted on, per scroll. The core counts up
72 // when "Jump to present" is pressed; an unchanged count is a frame where
73 // nobody asked to be moved.
74 final _bottomTicks = <String, int>{};
75
The data model, in Nim d333b6f nandi yesterday76 @override
77 void initState() {
78 super.initState();
79 // 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 yesterday80 // callback into Dart. At ~70µs a render a 100ms timer costs nothing.
The data model, in Nim d333b6f nandi yesterday81 _poll = Timer.periodic(const Duration(milliseconds: 100), (_) {
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday82 // Compared as the JSON Nim already produced, and decoded only when it
83 // differs. Stringifying both trees to answer "did anything change" was
84 // ~1MB of string churn per poll in a busy room, ten times a second, for
85 // an answer that is almost always no.
86 final next = core.pollIfChanged(_frame.json);
87 if (next != null) setState(() => _frame = next);
The data model, in Nim d333b6f nandi yesterday88 });
89 }
90
91 void _send(String id, [String value = '']) {
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday92 if (id.isEmpty) return;
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday93 setState(() => _frame = core.dispatchFrame(id, value));
The data model, in Nim d333b6f nandi yesterday94 if (id == 'send') _focus['draft']?.requestFocus();
95 }
96
97 @override
98 void dispose() {
99 _poll?.cancel();
100 for (final c in _controllers.values) {
101 c.dispose();
102 }
103 for (final f in _focus.values) {
104 f.dispose();
105 }
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday106 for (final r in _linkTaps.values) {
107 r.dispose();
108 }
Both ends of a scroll, on the same controller 5594a62 nandi 21h ago109 for (final c in _scrollers.values) {
110 c.dispose();
111 }
The data model, in Nim d333b6f nandi yesterday112 super.dispose();
113 }
114
115 @override
116 Widget build(BuildContext context) => MaterialApp(
117 title: 'frq',
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday118 debugShowCheckedModeBanner: false,
119 theme: ThemeData(
120 useMaterial3: true,
121 brightness: Brightness.dark,
122 scaffoldBackgroundColor: t.bg,
123 colorScheme: const ColorScheme.dark(
124 primary: t.accent,
125 onPrimary: t.onAccent,
126 surface: t.bg,
127 onSurface: t.onBg,
128 error: t.destructive,
129 ),
The data model, in Nim d333b6f nandi yesterday130 ),
Text can be selected ec74784 nandi 21h ago131 // Everything inside one SelectionArea, so a message can be selected
132 // and copied — and so can a nick, a timestamp, or a line of an error.
133 // Per-widget `SelectableText` was the alternative and is worse: it
134 // selects within one widget only, so a two-line answer and the name
135 // above it cannot be dragged across, which is most of what anyone
136 // wants to copy out of a chat.
137 //
138 // Taps still arrive: a selection starts on a drag, and the buttons,
139 // faces and reaction pills under here keep their gestures.
140 home: Scaffold(
141 backgroundColor: t.bg,
142 body: SafeArea(child: SelectionArea(child: _build(_tree))),
143 ),
The data model, in Nim d333b6f nandi yesterday144 );
145
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday146 // ---------------------------------------------------------------- helpers
147
148 TextStyle _style(double size, Color color) =>
149 TextStyle(fontSize: size, color: color, height: 1.35);
150
The pencil was drawn by a text font 1cb40af nandi 22h ago151 /// The style for a widget whose whole content is an emoji glyph.
152 ///
153 /// Naming the colour emoji font is not belt and braces: a glyph like ✏️ is
154 /// U+270F plus U+FE0F, and the variation selector is a *request* for emoji
155 /// presentation, not a guarantee. DejaVu Sans claims U+270F, so ordinary
156 /// fallback stops there and draws the monochrome pencil the text era had —
157 /// while 🙂, which no text font covers, falls all the way through to the
158 /// emoji font and looks right. That is why only some of the chips were
159 /// wrong.
160 ///
161 /// A family list rather than one name, because the font that has them
162 /// differs by platform, and a name nothing matches costs nothing.
163 static const List<String> _emojiFonts = <String>[
164 'Noto Color Emoji', // Linux, Android
165 'Apple Color Emoji', // macOS, iOS
166 'Segoe UI Emoji', // Windows
167 ];
168
169 TextStyle _emojiStyle(double size) => TextStyle(
170 fontSize: size,
171 fontFamily: _emojiFonts.first,
172 fontFamilyFallback: _emojiFonts,
173 );
174
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday175 double _d(dynamic v, double fallback) =>
176 v is num ? v.toDouble() : fallback;
177
178 /// Gaps between children, as real widgets rather than a `spacing:` — the
179 /// same layout on every Flutter version this might be built against.
180 List<Widget> _spaced(List<Widget> kids, double gap, {required bool vertical}) {
181 if (gap <= 0 || kids.length < 2) return kids;
182 final out = <Widget>[];
183 for (var i = 0; i < kids.length; i++) {
184 if (i > 0) {
185 out.add(vertical ? SizedBox(height: gap) : SizedBox(width: gap));
186 }
187 out.add(kids[i]);
188 }
189 return out;
190 }
191
192 /// A source that may be a bundled asset, a file on disk, or a URL — the
193 /// three the screens hand over, named apart by an `asset:` prefix so they
194 /// stay one property.
195 ImageProvider? _imageProvider(String src) {
196 if (src.isEmpty) return null;
197 if (src.startsWith('asset:')) return AssetImage(src.substring(6));
198 if (src.startsWith('http://') || src.startsWith('https://')) {
199 return NetworkImage(src);
200 }
201 return FileImage(File(src));
202 }
203
204 Widget _wrapTap(String onClick, Widget child, {BorderRadius? radius}) {
205 if (onClick.isEmpty) return child;
206 return InkWell(
207 onTap: () => _send(onClick),
208 borderRadius: radius,
209 child: child,
210 );
211 }
212
213 // ------------------------------------------------------------------ build
214
Expanded only where a Flex can hold it f1e99b4 nandi yesterday215 /// The axis of the widget a node is being built *into*, because `Expanded`
216 /// is only legal inside a Flex and there is no way to ask Flutter after the
217 /// fact.
218 ///
219 /// Getting this wrong is what "Cannot hit test a render box that has never
220 /// been laid out" means, in a pile: an `Expanded` inside a `Wrap` fails the
221 /// layout, and every box under it is then asked to hit-test without ever
222 /// having been laid out. The chats screen did exactly that — two unsized
223 /// entries in an `hbox`, which is a Wrap.
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday224 /// What an unsized entry or a stranded scroll falls back to.
225 ///
226 /// Both are only reachable when the tree has put one outside a Flex, which
227 /// is a tree bug rather than a rendering choice. The numbers exist so that
228 /// bug renders as something a person can see and a test can catch, not so
229 /// that it renders correctly.
230 static const _unsizedEntry = 320.0;
231 static const _strandedScroll = 400.0;
232
Expanded only where a Flex can hold it f1e99b4 nandi yesterday233 static const _noAxis = '';
234 static const _row = 'row';
235 static const _column = 'column';
236
237 Widget _build(core.UiNode n, [String axis = _noAxis]) {
A row is named for its message, not its place 4083860 nandi 20h ago238 // A node that names itself keeps its element across rebuilds.
239 //
240 // The tree is rebuilt wholesale from the core, so Flutter matches
241 // children by position unless something says otherwise — and a position
242 // is not an identity when a line can arrive above. Everything Flutter
243 // holds per element is at stake: text controllers, scroll offsets, and
244 // the selectables a live text selection is made of.
245 final key = n.prop('key', '');
The arrow goes to the message 4925e54 nandi 13h ago246 var w = _buildNode(n, axis);
247
248 // The row a reply's arrow is aiming at. Two keys on one widget is not a
249 // thing, so they nest: the ValueKey keeps the element across rebuilds,
250 // and the GlobalKey is how this frame finds it afterwards.
251 if (n.prop('scrollHere', false)) {
252 w = KeyedSubtree(key: _jumpKey, child: w);
253 WidgetsBinding.instance.addPostFrameCallback((_) {
254 final ctx = _jumpKey.currentContext;
255 if (ctx == null || !mounted) return;
256 Scrollable.ensureVisible(
257 ctx,
258 duration: const Duration(milliseconds: 250),
259 curve: Curves.easeOut,
260 // A little down from the top, so the message that was replied to
261 // is read with what came after it rather than alone against the
262 // ceiling.
263 alignment: 0.2,
264 );
265 _send('jump.done');
266 });
267 }
A row is named for its message, not its place 4083860 nandi 20h ago268 return key.isEmpty ? w : KeyedSubtree(key: ValueKey(key), child: w);
269 }
270
271 Widget _buildNode(core.UiNode n, String axis) {
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday272 final spacing = _d(n.props['spacing'], 0);
Expanded only where a Flex can hold it f1e99b4 nandi yesterday273 final flex = axis == _row || axis == _column;
274
275 // What this node's own children are being built into.
276 final childAxis = switch (n.tag) {
277 'page' || 'vbox' || 'card' || 'scroll' || 'dialog' => _column,
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday278 // Wrapping unless the row says otherwise. Flipping this default was
279 // tried and reverted: only 4 of 15 `hbox` call sites state `wrap` at
280 // all, so the other 11 became Rows and overflowed — the tree's habit is
281 // to wrap, and the default has to match it.
Expanded only where a Flex can hold it f1e99b4 nandi yesterday282 'hbox' => n.prop('wrap', true) ? _noAxis : _row,
283 _ => _noAxis,
284 };
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday285 // A paragraph's children are spans, not widgets — building them as
286 // widgets and throwing them away is what the `inline` special case did.
287 final kids = n.tag == 'paragraph'
288 ? const <Widget>[]
289 : n.children.map((c) => _build(c, childAxis)).toList();
290
291 // One rule for "take the remaining main-axis extent", stated by the node
292 // that expands. It used to be three: a vbox prop, a scroll with no
293 // height, and a row peering at its children's props to infer it.
294 Widget expanded(Widget w) =>
295 (n.prop('expand', false) && flex) ? Expanded(child: w) : w;
The data model, in Nim d333b6f nandi yesterday296
297 switch (n.tag) {
298 case 'page':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday299 return SingleChildScrollView(
300 child: Center(
301 child: ConstrainedBox(
302 constraints:
303 BoxConstraints(maxWidth: _d(n.props['maxWidth'], 520)),
304 child: Padding(
305 padding: const EdgeInsets.all(t.spaceM),
306 child: Column(
307 crossAxisAlignment: CrossAxisAlignment.start,
308 children: _spaced(kids, spacing, vertical: true)),
309 ),
The data model, in Nim d333b6f nandi yesterday310 ),
311 ),
312 );
313
314 case 'vbox':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday315 {
316 Widget col = Column(
317 crossAxisAlignment: CrossAxisAlignment.start,
318 mainAxisSize: MainAxisSize.min,
319 children: _spaced(kids, spacing, vertical: true),
320 );
321 col = _margins(n, col);
322 final w = _d(n.props['widthRequest'], 0);
323 if (w > 0) col = SizedBox(width: w, child: col);
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday324 return expanded(col);
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday325 }
The data model, in Nim d333b6f nandi yesterday326
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday327 // 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 yesterday328 // unbounded width, so a long URL or a long word can never wrap — it
329 // overflows, the layout fails, and every box under it is then hit-tested
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday330 // having never been laid out. Spans in one RichText wrap properly.
331 case 'paragraph':
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday332 return Text.rich(
333 TextSpan(children: n.children.map(_span).toList()),
334 softWrap: true,
335 );
336
The data model, in Nim d333b6f nandi yesterday337 case 'hbox':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday338 {
339 // Wrap and not Row: `:hbox` in the screens means "these go together
340 // across", not "these fit". The head row of the chat screen asks for
341 // more than 360 points has, and a Row answers that with an overflow
342 // rather than a second line.
343 final wrapping = n.prop('wrap', true);
344 final align = n.prop('align', 'center');
345 if (!wrapping) {
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday346 // An expanding row stretches on its cross axis, which is where a
347 // child's height comes from — Expanded in a Row is about width.
348 // Stretch needs a bounded height, and `expanded()` below is what
349 // gives the row one; without it the stretch resolves to infinity.
350 final fills = n.prop('expand', false);
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday351 final row = Row(
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday352 crossAxisAlignment: fills
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday353 ? CrossAxisAlignment.stretch
354 : (align == 'end'
355 ? CrossAxisAlignment.end
356 : CrossAxisAlignment.center),
357 children: _spaced(kids, spacing, vertical: false),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday358 );
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday359 return expanded(_margins(n, row));
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday360 }
361 return _margins(
362 n,
363 Wrap(
364 spacing: spacing,
365 runSpacing: spacing,
366 crossAxisAlignment: align == 'end'
367 ? WrapCrossAlignment.end
368 : WrapCrossAlignment.center,
369 children: kids,
The data model, in Nim d333b6f nandi yesterday370 ),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday371 );
372 }
The data model, in Nim d333b6f nandi yesterday373
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday374 // Container::Card in the Clojure: padding 12, fills its width.
The data model, in Nim d333b6f nandi yesterday375 case 'card':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday376 return Container(
377 width: double.infinity,
378 margin: const EdgeInsets.symmetric(vertical: t.spaceXxxs),
379 padding: const EdgeInsets.all(t.spaceXs),
380 decoration: BoxDecoration(
381 color: t.card,
382 borderRadius: BorderRadius.circular(t.radiusS),
The data model, in Nim d333b6f nandi yesterday383 ),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday384 child: Column(
385 crossAxisAlignment: CrossAxisAlignment.start,
386 children: _spaced(kids, spacing > 0 ? spacing : t.spaceXxs,
387 vertical: true)),
The data model, in Nim d333b6f nandi yesterday388 );
389
390 case 'title':
391 return Text(n.prop('label', ''),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday392 style: _style(t.textTitle3, t.onBg)
393 .copyWith(fontWeight: FontWeight.bold));
The data model, in Nim d333b6f nandi yesterday394
395 case 'title-2':
396 return Padding(
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday397 padding: const EdgeInsets.only(top: t.spaceXxs, bottom: t.spaceXxxs),
The data model, in Nim d333b6f nandi yesterday398 child: Text(n.prop('label', ''),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday399 style: _style(t.textTitle4, t.onBg)
400 .copyWith(fontWeight: FontWeight.w600)),
The data model, in Nim d333b6f nandi yesterday401 );
402
403 case 'label':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday404 return Text(n.prop('label', ''), style: _style(t.textBody, t.onBg));
The data model, in Nim d333b6f nandi yesterday405
406 case 'dim-label':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday407 return Text(n.prop('label', ''), style: _style(t.textCaption, t.dim));
408
409 /// Prose, as opposed to a label: this is what a message is, and it
410 /// wraps. Kept apart from `label` because a wrapping label in a row
411 /// lays out against the row's width rather than the column's.
412 case 'text':
413 return Text(n.prop('text', ''), style: _style(t.textBody, t.onBg));
414
415 case 'link':
416 return _wrapTap(
417 n.prop('onClick', ''),
418 Text(
419 n.prop('label', ''),
420 style: _style(t.textBody, t.accent)
421 .copyWith(decoration: TextDecoration.underline,
422 decorationColor: t.accent),
423 ),
424 );
425
426 case 'separator':
427 return const Divider(height: 1, thickness: 1, color: t.divider);
428
429 case 'spacer':
430 {
431 final s = _d(n.props['size'], t.spaceXxs);
432 return SizedBox(width: s, height: s);
433 }
The data model, in Nim d333b6f nandi yesterday434
435 case 'spinner':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday436 return Row(
437 mainAxisSize: MainAxisSize.min,
438 children: [
439 const SizedBox(
440 width: 16,
441 height: 16,
442 child: CircularProgressIndicator(
443 strokeWidth: 2, color: t.accent)),
444 if (n.prop('label', '').isNotEmpty) ...[
445 const SizedBox(width: t.spaceXxs),
446 Text(n.prop('label', ''), style: _style(t.textCaption, t.dim)),
447 ],
448 ],
449 );
450
451 /// A dot that says whether the thing is live, and the words beside it.
452 case 'status':
453 return Row(
454 mainAxisSize: MainAxisSize.min,
455 children: [
456 Container(
457 width: 8,
458 height: 8,
459 decoration: BoxDecoration(
460 color: n.prop('live', false) ? t.success : t.dim,
461 borderRadius: BorderRadius.circular(t.radiusXs),
462 ),
463 ),
464 const SizedBox(width: 6),
465 Text(n.prop('label', ''), style: _style(t.textCaption, t.dim)),
466 ],
467 );
The data model, in Nim d333b6f nandi yesterday468
469 case 'button':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday470 {
471 final onClick = n.prop('onClick', '');
472 final kind = n.prop('kind', 'default');
473 final label = Text(n.prop('label', ''));
474 if (kind == 'primary') {
475 return FilledButton(
476 onPressed: () => _send(onClick), child: label);
477 }
A face that opens someone 9bb81a1 nandi yesterday478 // A sender's name: a way in to who someone is, but it sits in the
479 // middle of a line and must not look like a control. Text that
480 // takes a press, with no chrome at all.
481 if (kind == 'plain') {
482 return InkWell(
483 onTap: () => _send(onClick),
484 child: Text(n.prop('label', ''),
485 style: _style(t.textBody, t.onBg)),
486 );
487 }
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday488 if (kind == 'destructive') {
489 return FilledButton(
490 style: FilledButton.styleFrom(
491 backgroundColor: t.destructive,
492 foregroundColor: t.onDestructive),
493 onPressed: () => _send(onClick),
494 child: label,
495 );
496 }
497 return OutlinedButton(onPressed: () => _send(onClick), child: label);
498 }
The data model, in Nim d333b6f nandi yesterday499
500 case 'checkbutton':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday501 {
502 // The label is part of the target. 20 logical pixels is a fine tick
503 // on a desktop pointer and a miss on a thumb, so the whole row taps.
504 final onToggled = n.prop('onToggled', '');
505 return InkWell(
506 onTap: () => _send(onToggled),
507 child: Row(
508 mainAxisSize: MainAxisSize.min,
509 children: [
510 Checkbox(
511 value: n.prop('active', false),
512 onChanged: (_) => _send(onToggled),
513 ),
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday514 // Flexible, because the label is prose and the row is as wide
515 // as the window: "Hide join/part messages" beside a checkbox
516 // overflows a phone otherwise.
517 Flexible(
518 child: Text(n.prop('label', ''),
519 style: _style(t.textBody, t.onBg)),
520 ),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday521 ],
522 ),
523 );
524 }
525
526 case 'emoji':
527 return _wrapTap(
528 n.prop('onClick', ''),
529 Text(n.prop('glyph', n.prop('emoji', '')),
The pencil was drawn by a text font 1cb40af nandi 22h ago530 style: _emojiStyle(_d(n.props['size'], 16))),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday531 );
532
533 /// A reaction pill: the glyph, and the tally beside it where there is
534 /// one to show. The same shape whether it is a reaction under a message,
535 /// a swatch in the picker, or a chip on the sender's row — which is the
536 /// point: what you press to react and what appears once you have should
537 /// look like one family.
538 ///
539 /// A count of zero is no count. The picker passes 0 for every swatch,
540 /// and a grid of little grey zeroes is noise where a reader is scanning
541 /// for a face. `mine` is the accent, because the only thing a pill has
542 /// to say at a glance is whether pressing it again takes yours off.
543 case 'reaction':
544 {
545 final size = _d(n.props['size'], 14);
546 final count = n.prop('count', 0);
547 final mine = n.prop('mine', false);
548 final pad = (0.25 * size).clamp(2.0, 8.0);
549 return _wrapTap(
550 n.prop('onClick', ''),
551 Container(
552 padding: EdgeInsets.symmetric(horizontal: pad, vertical: pad / 2),
553 decoration: BoxDecoration(
554 color: mine ? t.accent : t.component,
555 borderRadius: BorderRadius.circular(t.radiusS),
556 ),
557 child: Row(
558 mainAxisSize: MainAxisSize.min,
559 children: [
The pencil was drawn by a text font 1cb40af nandi 22h ago560 Text(n.prop('emoji', ''), style: _emojiStyle(size)),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday561 if (count > 0) ...[
562 const SizedBox(width: 4),
563 Text('$count',
564 style: _style(t.textCaption,
565 mine ? t.onAccent : t.dim)),
566 ],
567 ],
568 ),
569 ),
570 );
571 }
572
573 /// A face is a way in to who someone is, so it takes the press that
574 /// opens their profile. A picture that will not load is a face that
575 /// stays its initial and nothing else.
576 case 'avatar':
577 {
578 final size = _d(n.props['size'], 32);
579 final provider = _imageProvider(n.prop('url', ''));
580 final fallback = n.prop('fallback', '');
581 final face = CircleAvatar(
582 radius: size / 2,
583 backgroundColor: t.component,
584 backgroundImage: provider,
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday585 onBackgroundImageError: provider == null ? null : (_, _) {},
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday586 child: provider == null
587 ? Text(
588 fallback.isNotEmpty
589 ? fallback.substring(0, 1).toUpperCase()
590 : '?',
591 style: _style(t.textBody, t.onBg))
592 : null,
593 );
594 final onClick = n.prop('onClick', '');
595 if (onClick.isEmpty) return face;
596 return InkWell(
597 onTap: () => _send(onClick),
598 customBorder: const CircleBorder(),
599 child: face,
600 );
601 }
602
603 case 'image':
604 {
605 final provider = _imageProvider(n.prop('src', ''));
606 if (provider == null) return const SizedBox.shrink();
607 final maxW = _d(n.props['maxWidth'], 0);
608 final maxH = _d(n.props['maxHeight'], 0);
609 Widget img = Image(
610 image: provider,
611 fit: BoxFit.contain,
612 // A half-written cache file, or one deleted under us: the decoder
613 // throws during the build, and an exception in a build is a red
614 // screen for the whole conversation rather than a gap where one
615 // picture was.
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday616 errorBuilder: (_, _, _) => const SizedBox.shrink(),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday617 );
618 if (maxW > 0 || maxH > 0) {
619 img = ConstrainedBox(
620 constraints: BoxConstraints(
621 maxWidth: maxW > 0 ? maxW : double.infinity,
622 maxHeight: maxH > 0 ? maxH : double.infinity,
623 ),
624 child: img,
625 );
626 }
627 return _wrapTap(n.prop('onClick', ''), img);
628 }
The data model, in Nim d333b6f nandi yesterday629
630 case 'entry':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday631 {
632 final key = n.prop('key', '');
633 final value = n.prop('text', '');
634 final c = _controllers.putIfAbsent(
635 key, () => TextEditingController(text: value));
636 // Only when it actually differs: assigning unconditionally moves the
637 // caret to the end on every keystroke.
638 if (c.text != value) {
639 c.value = c.value.copyWith(
640 text: value,
641 selection: TextSelection.collapsed(offset: value.length),
642 );
643 }
644 final field = TextField(
645 controller: c,
646 focusNode: _focus.putIfAbsent(key, FocusNode.new),
647 style: _style(t.textBody, t.onBg),
648 decoration: InputDecoration(
649 hintText: n.prop('placeholder', ''),
650 hintStyle: _style(t.textBody, t.dim),
651 isDense: true,
652 filled: true,
653 fillColor: t.component,
654 border: OutlineInputBorder(
655 borderRadius: BorderRadius.circular(t.radiusS),
656 borderSide: BorderSide.none,
657 ),
658 ),
659 onChanged: (v) => _send(n.prop('onChange', ''), v),
660 onSubmitted: (_) => _send(n.prop('onSubmit', '')),
661 );
662 final w = _d(n.props['widthRequest'], 0);
Expanded only where a Flex can hold it f1e99b4 nandi yesterday663 if (w > 0) return SizedBox(width: w, child: field);
664 // No width asked for: take the rest of the row where there is a row
665 // to take it from, and otherwise a definite width. NOT Expanded
666 // unconditionally — a TextField has no intrinsic width, so in a Wrap
667 // it is both illegal and unmeasurable, and that combination is what
668 // took the whole screen down rather than one field.
669 return axis == _row
670 ? Expanded(child: field)
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday671 : SizedBox(width: _unsizedEntry, child: field);
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday672 }
673
674 case 'scroll':
675 {
Both ends of a scroll, on the same controller 5594a62 nandi 21h ago676 // Both ends of the same scroll, named so they are the same one.
The arrow goes to the message 4925e54 nandi 13h ago677 final scrollKey = n.prop('scrollKey', 'scroll');
678 final c = _scrollers.putIfAbsent(scrollKey, ScrollController.new);
679 final stick = n.prop('stickToBottom', false);
680
681 // "Jump to present": a tick that goes up, rather than a flag that
682 // would have to be cleared. A reverse scroll holds the present at
683 // offset zero, which is why this is not maxScrollExtent.
684 final tick = n.prop('scrollToBottom', 0);
685 if (_bottomTicks[scrollKey] != tick) {
686 _bottomTicks[scrollKey] = tick;
687 WidgetsBinding.instance.addPostFrameCallback((_) {
688 if (!c.hasClients) return;
689 c.animateTo(
690 stick ? c.position.minScrollExtent
691 : c.position.maxScrollExtent,
692 duration: const Duration(milliseconds: 250),
693 curve: Curves.easeOut,
694 );
695 });
696 }
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday697 Widget body = SingleChildScrollView(
Both ends of a scroll, on the same controller 5594a62 nandi 21h ago698 controller: c,
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday699 // The backlog reads from the bottom; a settings list from the top.
The arrow goes to the message 4925e54 nandi 13h ago700 reverse: stick,
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday701 child: Column(
702 crossAxisAlignment: CrossAxisAlignment.start,
703 children: _spaced(kids, spacing, vertical: true)),
The data model, in Nim d333b6f nandi yesterday704 );
Both ends of a scroll, on the same controller 5594a62 nandi 21h ago705 body = Scrollbar(controller: c, child: body);
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday706 // A scroll takes what the column has left. Outside a Flex there is
707 // nothing to take, and the tree is malformed — `_strandedScroll` is
708 // a visible size rather than a correct one, so the layout tests see
709 // a screen instead of an exception.
710 return flex
711 ? Expanded(child: body)
712 : const SizedBox(height: _strandedScroll);
The data model, in Nim d333b6f nandi yesterday713 }
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday714
715 /// A panel over the screen rather than a screen of its own.
716 case 'dialog':
717 return Card(
718 color: t.cardComponent,
719 child: Padding(
720 padding: const EdgeInsets.all(t.spaceS),
721 child: Column(
722 mainAxisSize: MainAxisSize.min,
723 crossAxisAlignment: CrossAxisAlignment.start,
724 children: [
725 if (n.prop('title', '').isNotEmpty)
726 Padding(
727 padding: const EdgeInsets.only(bottom: t.spaceXxs),
728 child: Text(n.prop('title', ''),
729 style: _style(t.textTitle4, t.onCard)
730 .copyWith(fontWeight: FontWeight.w600)),
731 ),
732 ..._spaced(kids, spacing, vertical: true),
733 ],
734 ),
The data model, in Nim d333b6f nandi yesterday735 ),
736 );
737
738 default:
739 // An unknown tag paints as itself rather than crashing or vanishing.
740 // 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 yesterday741 // is what makes the boundary pleasant to work across.
The data model, in Nim d333b6f nandi yesterday742 return Container(
743 padding: const EdgeInsets.all(4),
744 color: Colors.orange.withValues(alpha: 0.3),
745 child: Text('?${n.tag}'),
746 );
747 }
748 }
749
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday750 /// One node of an inline paragraph, as a span.
751 ///
752 /// Only `text` and `link` appear here — they are the only things `runNodes`
753 /// emits — and anything else falls back to its plain text so an unexpected
754 /// tag degrades to something readable rather than vanishing.
755 InlineSpan _span(core.UiNode n) {
756 switch (n.tag) {
757 case 'link':
758 final url = n.prop('url', n.prop('label', ''));
759 final onClick = n.prop('onClick', '');
760 return TextSpan(
761 text: n.prop('label', ''),
762 style: _style(t.textBody, t.accent)
763 .copyWith(decoration: TextDecoration.underline,
764 decorationColor: t.accent),
765 recognizer: onClick.isEmpty
766 ? null
767 : (_linkTaps[url] ??= TapGestureRecognizer()
768 ..onTap = () => _send(onClick)),
769 );
770 case 'text':
771 return TextSpan(
772 text: n.prop('text', ''), style: _style(t.textBody, t.onBg));
773 default:
774 return TextSpan(
775 text: n.prop('label', n.prop('text', '')),
776 style: _style(t.textBody, t.onBg));
777 }
778 }
779
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday780 /// `margin` and its four sides — the props the
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday781 /// screens use to buy air without a wrapper each time.
782 Widget _margins(core.UiNode n, Widget child) {
783 final all = _d(n.props['margin'], 0);
784 final top = _d(n.props['marginTop'], all);
785 final bottom = _d(n.props['marginBottom'], all);
786 final right = _d(n.props['marginRight'], all);
787 final left = _d(n.props['marginLeft'], all);
788 if (top == 0 && bottom == 0 && right == 0 && left == 0) return child;
789 return Padding(
790 padding: EdgeInsets.only(
791 top: top, bottom: bottom, right: right, left: left),
792 child: child,
793 );
The data model, in Nim d333b6f nandi yesterday794 }
795}