nandi/frqpublic Fork 0
23846db48565a450ee8a6a689892db23663ad48e
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 · 862 lines · 33.8 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';
14
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday15import 'package:flutter/gestures.dart';
16
The data model, in Nim d333b6f nandi yesterday17import 'package:flutter/material.dart';
18import 'package:frq_core/frq_core.dart' as core;
A web version, from the same core 23846db nandi 9h ago19import 'src/host.dart' as host;
The data model, in Nim d333b6f nandi yesterday20
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
Jump to present, which was never on screen ecb440f nandi 11h ago76 // Whether each scroll is at the present, as last reported to the core.
77 // Only the changes are sent: a notification arrives per pixel of a drag,
78 // and the core has one question, not a thousand.
79 final _atPresent = <String, bool>{};
80
The data model, in Nim d333b6f nandi yesterday81 @override
82 void initState() {
83 super.initState();
84 // 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 yesterday85 // callback into Dart. At ~70µs a render a 100ms timer costs nothing.
The data model, in Nim d333b6f nandi yesterday86 _poll = Timer.periodic(const Duration(milliseconds: 100), (_) {
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday87 // Compared as the JSON Nim already produced, and decoded only when it
88 // differs. Stringifying both trees to answer "did anything change" was
89 // ~1MB of string churn per poll in a busy room, ten times a second, for
90 // an answer that is almost always no.
91 final next = core.pollIfChanged(_frame.json);
92 if (next != null) setState(() => _frame = next);
The data model, in Nim d333b6f nandi yesterday93 });
94 }
95
96 void _send(String id, [String value = '']) {
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday97 if (id.isEmpty) return;
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday98 setState(() => _frame = core.dispatchFrame(id, value));
The data model, in Nim d333b6f nandi yesterday99 if (id == 'send') _focus['draft']?.requestFocus();
100 }
101
102 @override
103 void dispose() {
104 _poll?.cancel();
105 for (final c in _controllers.values) {
106 c.dispose();
107 }
108 for (final f in _focus.values) {
109 f.dispose();
110 }
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday111 for (final r in _linkTaps.values) {
112 r.dispose();
113 }
Both ends of a scroll, on the same controller 5594a62 nandi 21h ago114 for (final c in _scrollers.values) {
115 c.dispose();
116 }
The data model, in Nim d333b6f nandi yesterday117 super.dispose();
118 }
119
120 @override
121 Widget build(BuildContext context) => MaterialApp(
122 title: 'frq',
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday123 debugShowCheckedModeBanner: false,
124 theme: ThemeData(
125 useMaterial3: true,
126 brightness: Brightness.dark,
127 scaffoldBackgroundColor: t.bg,
128 colorScheme: const ColorScheme.dark(
129 primary: t.accent,
130 onPrimary: t.onAccent,
131 surface: t.bg,
132 onSurface: t.onBg,
133 error: t.destructive,
134 ),
The data model, in Nim d333b6f nandi yesterday135 ),
Text can be selected ec74784 nandi 21h ago136 // Everything inside one SelectionArea, so a message can be selected
137 // and copied — and so can a nick, a timestamp, or a line of an error.
138 // Per-widget `SelectableText` was the alternative and is worse: it
139 // selects within one widget only, so a two-line answer and the name
140 // above it cannot be dragged across, which is most of what anyone
141 // wants to copy out of a chat.
142 //
143 // Taps still arrive: a selection starts on a drag, and the buttons,
144 // faces and reaction pills under here keep their gestures.
145 home: Scaffold(
146 backgroundColor: t.bg,
147 body: SafeArea(child: SelectionArea(child: _build(_tree))),
148 ),
The data model, in Nim d333b6f nandi yesterday149 );
150
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday151 // ---------------------------------------------------------------- helpers
152
153 TextStyle _style(double size, Color color) =>
154 TextStyle(fontSize: size, color: color, height: 1.35);
155
The pencil was drawn by a text font 1cb40af nandi 22h ago156 /// The style for a widget whose whole content is an emoji glyph.
157 ///
158 /// Naming the colour emoji font is not belt and braces: a glyph like ✏️ is
159 /// U+270F plus U+FE0F, and the variation selector is a *request* for emoji
160 /// presentation, not a guarantee. DejaVu Sans claims U+270F, so ordinary
161 /// fallback stops there and draws the monochrome pencil the text era had —
162 /// while 🙂, which no text font covers, falls all the way through to the
163 /// emoji font and looks right. That is why only some of the chips were
164 /// wrong.
165 ///
166 /// A family list rather than one name, because the font that has them
167 /// differs by platform, and a name nothing matches costs nothing.
168 TextStyle _emojiStyle(double size) => TextStyle(
169 fontSize: size,
A web version, from the same core 23846db nandi 9h ago170 fontFamily: host.emojiFonts.isEmpty ? null : host.emojiFonts.first,
171 fontFamilyFallback: host.emojiFonts.isEmpty ? null : host.emojiFonts,
The pencil was drawn by a text font 1cb40af nandi 22h ago172 );
173
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday174 double _d(dynamic v, double fallback) =>
175 v is num ? v.toDouble() : fallback;
176
177 /// Gaps between children, as real widgets rather than a `spacing:` — the
178 /// same layout on every Flutter version this might be built against.
179 List<Widget> _spaced(List<Widget> kids, double gap, {required bool vertical}) {
180 if (gap <= 0 || kids.length < 2) return kids;
181 final out = <Widget>[];
182 for (var i = 0; i < kids.length; i++) {
183 if (i > 0) {
184 out.add(vertical ? SizedBox(height: gap) : SizedBox(width: gap));
185 }
186 out.add(kids[i]);
187 }
188 return out;
189 }
190
191 /// A source that may be a bundled asset, a file on disk, or a URL — the
192 /// three the screens hand over, named apart by an `asset:` prefix so they
193 /// stay one property.
194 ImageProvider? _imageProvider(String src) {
195 if (src.isEmpty) return null;
196 if (src.startsWith('asset:')) return AssetImage(src.substring(6));
197 if (src.startsWith('http://') || src.startsWith('https://')) {
198 return NetworkImage(src);
199 }
A web version, from the same core 23846db nandi 9h ago200 return host.localImage(src);
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday201 }
202
203 Widget _wrapTap(String onClick, Widget child, {BorderRadius? radius}) {
204 if (onClick.isEmpty) return child;
205 return InkWell(
206 onTap: () => _send(onClick),
207 borderRadius: radius,
208 child: child,
209 );
210 }
211
212 // ------------------------------------------------------------------ build
213
Expanded only where a Flex can hold it f1e99b4 nandi yesterday214 /// The axis of the widget a node is being built *into*, because `Expanded`
215 /// is only legal inside a Flex and there is no way to ask Flutter after the
216 /// fact.
217 ///
218 /// Getting this wrong is what "Cannot hit test a render box that has never
219 /// been laid out" means, in a pile: an `Expanded` inside a `Wrap` fails the
220 /// layout, and every box under it is then asked to hit-test without ever
221 /// having been laid out. The chats screen did exactly that — two unsized
222 /// entries in an `hbox`, which is a Wrap.
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday223 /// What an unsized entry or a stranded scroll falls back to.
224 ///
225 /// Both are only reachable when the tree has put one outside a Flex, which
226 /// is a tree bug rather than a rendering choice. The numbers exist so that
227 /// bug renders as something a person can see and a test can catch, not so
228 /// that it renders correctly.
229 static const _unsizedEntry = 320.0;
230 static const _strandedScroll = 400.0;
231
Expanded only where a Flex can hold it f1e99b4 nandi yesterday232 static const _noAxis = '';
233 static const _row = 'row';
234 static const _column = 'column';
235
236 Widget _build(core.UiNode n, [String axis = _noAxis]) {
A row is named for its message, not its place 4083860 nandi 20h ago237 // A node that names itself keeps its element across rebuilds.
238 //
239 // The tree is rebuilt wholesale from the core, so Flutter matches
240 // children by position unless something says otherwise — and a position
241 // is not an identity when a line can arrive above. Everything Flutter
242 // holds per element is at stake: text controllers, scroll offsets, and
243 // the selectables a live text selection is made of.
244 final key = n.prop('key', '');
The arrow goes to the message 4925e54 nandi 13h ago245 var w = _buildNode(n, axis);
246
247 // The row a reply's arrow is aiming at. Two keys on one widget is not a
248 // thing, so they nest: the ValueKey keeps the element across rebuilds,
249 // and the GlobalKey is how this frame finds it afterwards.
250 if (n.prop('scrollHere', false)) {
251 w = KeyedSubtree(key: _jumpKey, child: w);
252 WidgetsBinding.instance.addPostFrameCallback((_) {
253 final ctx = _jumpKey.currentContext;
254 if (ctx == null || !mounted) return;
255 Scrollable.ensureVisible(
256 ctx,
257 duration: const Duration(milliseconds: 250),
258 curve: Curves.easeOut,
259 // A little down from the top, so the message that was replied to
260 // is read with what came after it rather than alone against the
261 // ceiling.
262 alignment: 0.2,
263 );
264 _send('jump.done');
265 });
266 }
A row is named for its message, not its place 4083860 nandi 20h ago267 return key.isEmpty ? w : KeyedSubtree(key: ValueKey(key), child: w);
268 }
269
270 Widget _buildNode(core.UiNode n, String axis) {
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday271 final spacing = _d(n.props['spacing'], 0);
Expanded only where a Flex can hold it f1e99b4 nandi yesterday272 final flex = axis == _row || axis == _column;
273
274 // What this node's own children are being built into.
275 final childAxis = switch (n.tag) {
276 'page' || 'vbox' || 'card' || 'scroll' || 'dialog' => _column,
Jump to present, which was never on screen ecb440f nandi 11h ago277 // A stack's children are laid out by the stack, not by a flex: an
278 // `Expanded` among them is illegal, so they must not think they are
279 // in one.
280 'overlay' => _noAxis,
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday281 // Wrapping unless the row says otherwise. Flipping this default was
282 // tried and reverted: only 4 of 15 `hbox` call sites state `wrap` at
283 // all, so the other 11 became Rows and overflowed — the tree's habit is
284 // to wrap, and the default has to match it.
Expanded only where a Flex can hold it f1e99b4 nandi yesterday285 'hbox' => n.prop('wrap', true) ? _noAxis : _row,
286 _ => _noAxis,
287 };
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday288 // A paragraph's children are spans, not widgets — building them as
289 // widgets and throwing them away is what the `inline` special case did.
290 final kids = n.tag == 'paragraph'
291 ? const <Widget>[]
292 : n.children.map((c) => _build(c, childAxis)).toList();
293
294 // One rule for "take the remaining main-axis extent", stated by the node
295 // that expands. It used to be three: a vbox prop, a scroll with no
296 // height, and a row peering at its children's props to infer it.
297 Widget expanded(Widget w) =>
298 (n.prop('expand', false) && flex) ? Expanded(child: w) : w;
The data model, in Nim d333b6f nandi yesterday299
300 switch (n.tag) {
301 case 'page':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday302 return SingleChildScrollView(
303 child: Center(
304 child: ConstrainedBox(
305 constraints:
306 BoxConstraints(maxWidth: _d(n.props['maxWidth'], 520)),
307 child: Padding(
308 padding: const EdgeInsets.all(t.spaceM),
309 child: Column(
310 crossAxisAlignment: CrossAxisAlignment.start,
311 children: _spaced(kids, spacing, vertical: true)),
312 ),
The data model, in Nim d333b6f nandi yesterday313 ),
314 ),
315 );
316
Jump to present, which was never on screen ecb440f nandi 11h ago317 /// A node with others floating over it — the backlog, with the button
318 /// that takes you back to the present sitting on top of it.
319 ///
320 /// The floating children are given no height of their own, which is
321 /// the whole point: a control that belongs to the backlog should not
322 /// take a row away from it, and on a short window that row is what
323 /// makes the screen overflow.
324 case 'overlay':
325 {
326 final base = kids.isNotEmpty ? kids.first : const SizedBox.shrink();
327 final over = kids.skip(1).toList();
328 return expanded(Stack(
329 children: [
330 Positioned.fill(child: base),
331 for (final o in over)
332 Positioned(
333 left: 0,
334 right: 0,
335 bottom: t.spaceS,
336 child: Align(alignment: Alignment.bottomCenter, child: o),
337 ),
338 ],
339 ));
340 }
341
The data model, in Nim d333b6f nandi yesterday342 case 'vbox':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday343 {
344 Widget col = Column(
345 crossAxisAlignment: CrossAxisAlignment.start,
346 mainAxisSize: MainAxisSize.min,
347 children: _spaced(kids, spacing, vertical: true),
348 );
349 col = _margins(n, col);
350 final w = _d(n.props['widthRequest'], 0);
351 if (w > 0) col = SizedBox(width: w, child: col);
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday352 return expanded(col);
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday353 }
The data model, in Nim d333b6f nandi yesterday354
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday355 // 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 yesterday356 // unbounded width, so a long URL or a long word can never wrap — it
357 // overflows, the layout fails, and every box under it is then hit-tested
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday358 // having never been laid out. Spans in one RichText wrap properly.
359 case 'paragraph':
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday360 return Text.rich(
361 TextSpan(children: n.children.map(_span).toList()),
362 softWrap: true,
363 );
364
The data model, in Nim d333b6f nandi yesterday365 case 'hbox':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday366 {
367 // Wrap and not Row: `:hbox` in the screens means "these go together
368 // across", not "these fit". The head row of the chat screen asks for
369 // more than 360 points has, and a Row answers that with an overflow
370 // rather than a second line.
371 final wrapping = n.prop('wrap', true);
372 final align = n.prop('align', 'center');
373 if (!wrapping) {
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday374 // An expanding row stretches on its cross axis, which is where a
375 // child's height comes from — Expanded in a Row is about width.
376 // Stretch needs a bounded height, and `expanded()` below is what
377 // gives the row one; without it the stretch resolves to infinity.
378 final fills = n.prop('expand', false);
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday379 final row = Row(
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday380 crossAxisAlignment: fills
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday381 ? CrossAxisAlignment.stretch
382 : (align == 'end'
383 ? CrossAxisAlignment.end
384 : CrossAxisAlignment.center),
385 children: _spaced(kids, spacing, vertical: false),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday386 );
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday387 return expanded(_margins(n, row));
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday388 }
389 return _margins(
390 n,
391 Wrap(
392 spacing: spacing,
393 runSpacing: spacing,
394 crossAxisAlignment: align == 'end'
395 ? WrapCrossAlignment.end
396 : WrapCrossAlignment.center,
397 children: kids,
The data model, in Nim d333b6f nandi yesterday398 ),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday399 );
400 }
The data model, in Nim d333b6f nandi yesterday401
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday402 // Container::Card in the Clojure: padding 12, fills its width.
The data model, in Nim d333b6f nandi yesterday403 case 'card':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday404 return Container(
405 width: double.infinity,
406 margin: const EdgeInsets.symmetric(vertical: t.spaceXxxs),
407 padding: const EdgeInsets.all(t.spaceXs),
408 decoration: BoxDecoration(
409 color: t.card,
410 borderRadius: BorderRadius.circular(t.radiusS),
The data model, in Nim d333b6f nandi yesterday411 ),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday412 child: Column(
413 crossAxisAlignment: CrossAxisAlignment.start,
414 children: _spaced(kids, spacing > 0 ? spacing : t.spaceXxs,
415 vertical: true)),
The data model, in Nim d333b6f nandi yesterday416 );
417
418 case 'title':
419 return Text(n.prop('label', ''),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday420 style: _style(t.textTitle3, t.onBg)
421 .copyWith(fontWeight: FontWeight.bold));
The data model, in Nim d333b6f nandi yesterday422
423 case 'title-2':
424 return Padding(
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday425 padding: const EdgeInsets.only(top: t.spaceXxs, bottom: t.spaceXxxs),
The data model, in Nim d333b6f nandi yesterday426 child: Text(n.prop('label', ''),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday427 style: _style(t.textTitle4, t.onBg)
428 .copyWith(fontWeight: FontWeight.w600)),
The data model, in Nim d333b6f nandi yesterday429 );
430
431 case 'label':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday432 return Text(n.prop('label', ''), style: _style(t.textBody, t.onBg));
The data model, in Nim d333b6f nandi yesterday433
434 case 'dim-label':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday435 return Text(n.prop('label', ''), style: _style(t.textCaption, t.dim));
436
437 /// Prose, as opposed to a label: this is what a message is, and it
438 /// wraps. Kept apart from `label` because a wrapping label in a row
439 /// lays out against the row's width rather than the column's.
440 case 'text':
441 return Text(n.prop('text', ''), style: _style(t.textBody, t.onBg));
442
443 case 'link':
444 return _wrapTap(
445 n.prop('onClick', ''),
446 Text(
447 n.prop('label', ''),
448 style: _style(t.textBody, t.accent)
449 .copyWith(decoration: TextDecoration.underline,
450 decorationColor: t.accent),
451 ),
452 );
453
454 case 'separator':
455 return const Divider(height: 1, thickness: 1, color: t.divider);
456
457 case 'spacer':
458 {
459 final s = _d(n.props['size'], t.spaceXxs);
460 return SizedBox(width: s, height: s);
461 }
The data model, in Nim d333b6f nandi yesterday462
463 case 'spinner':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday464 return Row(
465 mainAxisSize: MainAxisSize.min,
466 children: [
467 const SizedBox(
468 width: 16,
469 height: 16,
470 child: CircularProgressIndicator(
471 strokeWidth: 2, color: t.accent)),
472 if (n.prop('label', '').isNotEmpty) ...[
473 const SizedBox(width: t.spaceXxs),
474 Text(n.prop('label', ''), style: _style(t.textCaption, t.dim)),
475 ],
476 ],
477 );
478
479 /// A dot that says whether the thing is live, and the words beside it.
480 case 'status':
481 return Row(
482 mainAxisSize: MainAxisSize.min,
483 children: [
484 Container(
485 width: 8,
486 height: 8,
487 decoration: BoxDecoration(
488 color: n.prop('live', false) ? t.success : t.dim,
489 borderRadius: BorderRadius.circular(t.radiusXs),
490 ),
491 ),
492 const SizedBox(width: 6),
493 Text(n.prop('label', ''), style: _style(t.textCaption, t.dim)),
494 ],
495 );
The data model, in Nim d333b6f nandi yesterday496
497 case 'button':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday498 {
499 final onClick = n.prop('onClick', '');
500 final kind = n.prop('kind', 'default');
501 final label = Text(n.prop('label', ''));
502 if (kind == 'primary') {
503 return FilledButton(
504 onPressed: () => _send(onClick), child: label);
505 }
A face that opens someone 9bb81a1 nandi yesterday506 // A sender's name: a way in to who someone is, but it sits in the
507 // middle of a line and must not look like a control. Text that
508 // takes a press, with no chrome at all.
509 if (kind == 'plain') {
510 return InkWell(
511 onTap: () => _send(onClick),
512 child: Text(n.prop('label', ''),
513 style: _style(t.textBody, t.onBg)),
514 );
515 }
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday516 if (kind == 'destructive') {
517 return FilledButton(
518 style: FilledButton.styleFrom(
519 backgroundColor: t.destructive,
520 foregroundColor: t.onDestructive),
521 onPressed: () => _send(onClick),
522 child: label,
523 );
524 }
525 return OutlinedButton(onPressed: () => _send(onClick), child: label);
526 }
The data model, in Nim d333b6f nandi yesterday527
528 case 'checkbutton':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday529 {
530 // The label is part of the target. 20 logical pixels is a fine tick
531 // on a desktop pointer and a miss on a thumb, so the whole row taps.
532 final onToggled = n.prop('onToggled', '');
533 return InkWell(
534 onTap: () => _send(onToggled),
535 child: Row(
536 mainAxisSize: MainAxisSize.min,
537 children: [
538 Checkbox(
539 value: n.prop('active', false),
540 onChanged: (_) => _send(onToggled),
541 ),
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday542 // Flexible, because the label is prose and the row is as wide
543 // as the window: "Hide join/part messages" beside a checkbox
544 // overflows a phone otherwise.
545 Flexible(
546 child: Text(n.prop('label', ''),
547 style: _style(t.textBody, t.onBg)),
548 ),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday549 ],
550 ),
551 );
552 }
553
554 case 'emoji':
555 return _wrapTap(
556 n.prop('onClick', ''),
557 Text(n.prop('glyph', n.prop('emoji', '')),
The pencil was drawn by a text font 1cb40af nandi 22h ago558 style: _emojiStyle(_d(n.props['size'], 16))),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday559 );
560
561 /// A reaction pill: the glyph, and the tally beside it where there is
562 /// one to show. The same shape whether it is a reaction under a message,
563 /// a swatch in the picker, or a chip on the sender's row — which is the
564 /// point: what you press to react and what appears once you have should
565 /// look like one family.
566 ///
567 /// A count of zero is no count. The picker passes 0 for every swatch,
568 /// and a grid of little grey zeroes is noise where a reader is scanning
569 /// for a face. `mine` is the accent, because the only thing a pill has
570 /// to say at a glance is whether pressing it again takes yours off.
571 case 'reaction':
572 {
573 final size = _d(n.props['size'], 14);
574 final count = n.prop('count', 0);
575 final mine = n.prop('mine', false);
576 final pad = (0.25 * size).clamp(2.0, 8.0);
577 return _wrapTap(
578 n.prop('onClick', ''),
579 Container(
580 padding: EdgeInsets.symmetric(horizontal: pad, vertical: pad / 2),
581 decoration: BoxDecoration(
582 color: mine ? t.accent : t.component,
583 borderRadius: BorderRadius.circular(t.radiusS),
584 ),
585 child: Row(
586 mainAxisSize: MainAxisSize.min,
587 children: [
The pencil was drawn by a text font 1cb40af nandi 22h ago588 Text(n.prop('emoji', ''), style: _emojiStyle(size)),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday589 if (count > 0) ...[
590 const SizedBox(width: 4),
591 Text('$count',
592 style: _style(t.textCaption,
593 mine ? t.onAccent : t.dim)),
594 ],
595 ],
596 ),
597 ),
598 );
599 }
600
601 /// A face is a way in to who someone is, so it takes the press that
602 /// opens their profile. A picture that will not load is a face that
603 /// stays its initial and nothing else.
604 case 'avatar':
605 {
606 final size = _d(n.props['size'], 32);
A web version, from the same core 23846db nandi 9h ago607 final url = n.prop('url', '');
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday608 final fallback = n.prop('fallback', '');
A web version, from the same core 23846db nandi 9h ago609 final initial = Text(
610 fallback.isNotEmpty ? fallback.substring(0, 1).toUpperCase() : '?',
611 style: _style(t.textBody, t.onBg));
612 // Through the host rather than as a `backgroundImage`: on the web a
613 // face is an <img> the browser fetches, which is the only kind CORS
614 // lets through, and an element cannot be a decoration.
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday615 final face = CircleAvatar(
616 radius: size / 2,
617 backgroundColor: t.component,
A web version, from the same core 23846db nandi 9h ago618 child: url.isEmpty
619 ? initial
620 : ClipOval(
621 child: SizedBox(
622 width: size,
623 height: size,
624 child: host.networkImage(url,
625 fit: BoxFit.cover, onError: () => initial),
626 ),
627 ),
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday628 );
629 final onClick = n.prop('onClick', '');
630 if (onClick.isEmpty) return face;
631 return InkWell(
632 onTap: () => _send(onClick),
633 customBorder: const CircleBorder(),
634 child: face,
635 );
636 }
637
638 case 'image':
639 {
A web version, from the same core 23846db nandi 9h ago640 final src = n.prop('src', '');
641 if (src.isEmpty) return const SizedBox.shrink();
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday642 final maxW = _d(n.props['maxWidth'], 0);
643 final maxH = _d(n.props['maxHeight'], 0);
A web version, from the same core 23846db nandi 9h ago644 // A half-written cache file, or one deleted under us: the decoder
645 // throws during the build, and an exception in a build is a red
646 // screen for the whole conversation rather than a gap where one
647 // picture was.
648 Widget img;
649 if (src.startsWith('http://') || src.startsWith('https://')) {
650 img = host.networkImage(src);
651 } else {
652 final provider = _imageProvider(src);
653 if (provider == null) return const SizedBox.shrink();
654 img = Image(
655 image: provider,
656 fit: BoxFit.contain,
657 errorBuilder: (_, _, _) => const SizedBox.shrink(),
658 );
659 }
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday660 if (maxW > 0 || maxH > 0) {
661 img = ConstrainedBox(
662 constraints: BoxConstraints(
663 maxWidth: maxW > 0 ? maxW : double.infinity,
664 maxHeight: maxH > 0 ? maxH : double.infinity,
665 ),
666 child: img,
667 );
668 }
669 return _wrapTap(n.prop('onClick', ''), img);
670 }
The data model, in Nim d333b6f nandi yesterday671
672 case 'entry':
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday673 {
674 final key = n.prop('key', '');
675 final value = n.prop('text', '');
676 final c = _controllers.putIfAbsent(
677 key, () => TextEditingController(text: value));
678 // Only when it actually differs: assigning unconditionally moves the
679 // caret to the end on every keystroke.
680 if (c.text != value) {
681 c.value = c.value.copyWith(
682 text: value,
683 selection: TextSelection.collapsed(offset: value.length),
684 );
685 }
686 final field = TextField(
687 controller: c,
688 focusNode: _focus.putIfAbsent(key, FocusNode.new),
689 style: _style(t.textBody, t.onBg),
690 decoration: InputDecoration(
691 hintText: n.prop('placeholder', ''),
692 hintStyle: _style(t.textBody, t.dim),
693 isDense: true,
694 filled: true,
695 fillColor: t.component,
696 border: OutlineInputBorder(
697 borderRadius: BorderRadius.circular(t.radiusS),
698 borderSide: BorderSide.none,
699 ),
700 ),
701 onChanged: (v) => _send(n.prop('onChange', ''), v),
702 onSubmitted: (_) => _send(n.prop('onSubmit', '')),
703 );
704 final w = _d(n.props['widthRequest'], 0);
Expanded only where a Flex can hold it f1e99b4 nandi yesterday705 if (w > 0) return SizedBox(width: w, child: field);
706 // No width asked for: take the rest of the row where there is a row
707 // to take it from, and otherwise a definite width. NOT Expanded
708 // unconditionally — a TextField has no intrinsic width, so in a Wrap
709 // it is both illegal and unmeasurable, and that combination is what
710 // took the whole screen down rather than one field.
711 return axis == _row
712 ? Expanded(child: field)
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday713 : SizedBox(width: _unsizedEntry, child: field);
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday714 }
715
716 case 'scroll':
717 {
Both ends of a scroll, on the same controller 5594a62 nandi 21h ago718 // Both ends of the same scroll, named so they are the same one.
The arrow goes to the message 4925e54 nandi 13h ago719 final scrollKey = n.prop('scrollKey', 'scroll');
720 final c = _scrollers.putIfAbsent(scrollKey, ScrollController.new);
721 final stick = n.prop('stickToBottom', false);
722
723 // "Jump to present": a tick that goes up, rather than a flag that
724 // would have to be cleared. A reverse scroll holds the present at
725 // offset zero, which is why this is not maxScrollExtent.
726 final tick = n.prop('scrollToBottom', 0);
727 if (_bottomTicks[scrollKey] != tick) {
728 _bottomTicks[scrollKey] = tick;
729 WidgetsBinding.instance.addPostFrameCallback((_) {
730 if (!c.hasClients) return;
731 c.animateTo(
732 stick ? c.position.minScrollExtent
733 : c.position.maxScrollExtent,
734 duration: const Duration(milliseconds: 250),
735 curve: Curves.easeOut,
736 );
737 });
738 }
Jump to present, which was never on screen ecb440f nandi 11h ago739 // How far from the present counts as having left it. Enough that
740 // the last line being taller than the gap does not toggle this on
741 // its own, and little enough that a nudge upward and back does not
742 // leave the button on screen.
743 const away = 120.0;
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday744 Widget body = SingleChildScrollView(
Both ends of a scroll, on the same controller 5594a62 nandi 21h ago745 controller: c,
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday746 // The backlog reads from the bottom; a settings list from the top.
The arrow goes to the message 4925e54 nandi 13h ago747 reverse: stick,
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday748 child: Column(
749 crossAxisAlignment: CrossAxisAlignment.start,
750 children: _spaced(kids, spacing, vertical: true)),
The data model, in Nim d333b6f nandi yesterday751 );
Both ends of a scroll, on the same controller 5594a62 nandi 21h ago752 body = Scrollbar(controller: c, child: body);
Jump to present, which was never on screen ecb440f nandi 11h ago753
754 // Only the backlog reports this. A settings list has no present to
755 // be at, and telling the core about one would put the chat
756 // screen's button on the wrong screen's scrolling.
757 if (stick) {
758 body = NotificationListener<ScrollNotification>(
759 onNotification: (note) {
760 if (note.depth != 0) return false;
761 final m = note.metrics;
762 // Reversed, so the present is the zero end.
763 final here = m.pixels <= m.minScrollExtent + away;
764 if (_atPresent[scrollKey] != here) {
765 _atPresent[scrollKey] = here;
766 _send(here ? 'present.back' : 'present.left');
767 }
768 return false;
769 },
770 child: body,
771 );
772 }
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday773 // A scroll takes what the column has left. Outside a Flex there is
774 // nothing to take, and the tree is malformed — `_strandedScroll` is
775 // a visible size rather than a correct one, so the layout tests see
776 // a screen instead of an exception.
777 return flex
778 ? Expanded(child: body)
779 : const SizedBox(height: _strandedScroll);
The data model, in Nim d333b6f nandi yesterday780 }
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday781
782 /// A panel over the screen rather than a screen of its own.
783 case 'dialog':
784 return Card(
785 color: t.cardComponent,
786 child: Padding(
787 padding: const EdgeInsets.all(t.spaceS),
788 child: Column(
789 mainAxisSize: MainAxisSize.min,
790 crossAxisAlignment: CrossAxisAlignment.start,
791 children: [
792 if (n.prop('title', '').isNotEmpty)
793 Padding(
794 padding: const EdgeInsets.only(bottom: t.spaceXxs),
795 child: Text(n.prop('title', ''),
796 style: _style(t.textTitle4, t.onCard)
797 .copyWith(fontWeight: FontWeight.w600)),
798 ),
799 ..._spaced(kids, spacing, vertical: true),
800 ],
801 ),
The data model, in Nim d333b6f nandi yesterday802 ),
803 );
804
805 default:
806 // An unknown tag paints as itself rather than crashing or vanishing.
807 // 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 yesterday808 // is what makes the boundary pleasant to work across.
The data model, in Nim d333b6f nandi yesterday809 return Container(
810 padding: const EdgeInsets.all(4),
811 color: Colors.orange.withValues(alpha: 0.3),
812 child: Text('?${n.tag}'),
813 );
814 }
815 }
816
Lay every screen out in a test, and fix what that found 36bdfc5 nandi yesterday817 /// One node of an inline paragraph, as a span.
818 ///
819 /// Only `text` and `link` appear here — they are the only things `runNodes`
820 /// emits — and anything else falls back to its plain text so an unexpected
821 /// tag degrades to something readable rather than vanishing.
822 InlineSpan _span(core.UiNode n) {
823 switch (n.tag) {
824 case 'link':
825 final url = n.prop('url', n.prop('label', ''));
826 final onClick = n.prop('onClick', '');
827 return TextSpan(
828 text: n.prop('label', ''),
829 style: _style(t.textBody, t.accent)
830 .copyWith(decoration: TextDecoration.underline,
831 decorationColor: t.accent),
832 recognizer: onClick.isEmpty
833 ? null
834 : (_linkTaps[url] ??= TapGestureRecognizer()
835 ..onTap = () => _send(onClick)),
836 );
837 case 'text':
838 return TextSpan(
839 text: n.prop('text', ''), style: _style(t.textBody, t.onBg));
840 default:
841 return TextSpan(
842 text: n.prop('label', n.prop('text', '')),
843 style: _style(t.textBody, t.onBg));
844 }
845 }
846
Quality pass: reuse, dead weight, and two real costs 4dfc719 nandi yesterday847 /// `margin` and its four sides — the props the
The renderer, and a transport bug that took four tries 58e6c97 nandi yesterday848 /// screens use to buy air without a wrapper each time.
849 Widget _margins(core.UiNode n, Widget child) {
850 final all = _d(n.props['margin'], 0);
851 final top = _d(n.props['marginTop'], all);
852 final bottom = _d(n.props['marginBottom'], all);
853 final right = _d(n.props['marginRight'], all);
854 final left = _d(n.props['marginLeft'], all);
855 if (top == 0 && bottom == 0 && right == 0 && left == 0) return child;
856 return Padding(
857 padding: EdgeInsets.only(
858 top: top, bottom: bottom, right: right, left: left),
859 child: child,
860 );
The data model, in Nim d333b6f nandi yesterday861 }
862}