tutuca 0.15.0 → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/CHANGELOG.md +132 -0
  2. package/LICENSE +1 -1
  3. package/README.md +64 -170
  4. package/{dist → deps}/immer.js +674 -249
  5. package/dist/tutuca.js +2342 -4057
  6. package/dist/tutuca.min.js +3 -3
  7. package/package.json +78 -96
  8. package/src/component.js +66 -0
  9. package/src/css/classes.js +77 -0
  10. package/src/dev/formatters.js +393 -0
  11. package/src/dev/jsonml.js +35 -0
  12. package/src/dev/panel.js +400 -0
  13. package/src/dev/summary.js +239 -0
  14. package/src/dev/vdom-formatters.js +102 -0
  15. package/src/drag.js +23 -0
  16. package/src/embed/element.js +111 -0
  17. package/src/env.js +30 -0
  18. package/src/events.js +85 -0
  19. package/src/history/bar.js +198 -0
  20. package/src/history/index.js +149 -0
  21. package/src/host.js +360 -0
  22. package/src/lint/index.js +470 -0
  23. package/src/meta.js +12 -0
  24. package/src/optimize.js +58 -0
  25. package/src/paths.js +205 -0
  26. package/src/playground/element.js +360 -0
  27. package/src/playground/index.js +5 -0
  28. package/src/playground/sources.js +107 -0
  29. package/src/playground/ui/playground.js +287 -0
  30. package/src/schema.js +460 -0
  31. package/src/scope.js +92 -0
  32. package/src/storybook/index.js +80 -0
  33. package/src/storybook/runner.js +452 -0
  34. package/src/storybook/stories.js +208 -0
  35. package/src/storybook/stress.js +76 -0
  36. package/src/storybook/ui/common.js +37 -0
  37. package/src/storybook/ui/link.js +80 -0
  38. package/src/storybook/ui/panels.js +32 -0
  39. package/src/storybook/ui/story-panel.js +432 -0
  40. package/src/storybook/ui/storybook.js +191 -0
  41. package/src/storybook/ui/stress-panel.js +231 -0
  42. package/src/sync/automerge.js +159 -0
  43. package/src/sync/codec.js +206 -0
  44. package/src/sync/diff.js +153 -0
  45. package/src/sync/index.js +97 -0
  46. package/src/sync/migrate.js +184 -0
  47. package/src/sync/ops.js +160 -0
  48. package/src/sync/remote.js +206 -0
  49. package/src/tag.js +24 -0
  50. package/src/tasks.js +244 -0
  51. package/src/test/driver.js +141 -0
  52. package/src/test/pbt.js +589 -0
  53. package/src/tutuca.js +66 -0
  54. package/src/vdom.js +349 -0
  55. package/src/view.js +354 -0
  56. package/src/walk.js +79 -0
  57. package/dist/chai.js +0 -4210
  58. package/dist/tutuca-cli.js +0 -16315
  59. package/dist/tutuca-components.js +0 -2232
  60. package/dist/tutuca-dev.ext.js +0 -8476
  61. package/dist/tutuca-dev.js +0 -13220
  62. package/dist/tutuca-dev.min.js +0 -5
  63. package/dist/tutuca-extra.ext.js +0 -4261
  64. package/dist/tutuca-extra.js +0 -4964
  65. package/dist/tutuca-extra.min.js +0 -3
  66. package/dist/tutuca-storybook.js +0 -970
  67. package/dist/tutuca.ext.js +0 -4183
  68. package/skill/margaui/SKILL.md +0 -105
  69. package/skill/margaui/components/accordion.md +0 -127
  70. package/skill/margaui/components/alert.md +0 -174
  71. package/skill/margaui/components/aura.md +0 -97
  72. package/skill/margaui/components/avatar.md +0 -220
  73. package/skill/margaui/components/badge.md +0 -193
  74. package/skill/margaui/components/breadcrumbs.md +0 -103
  75. package/skill/margaui/components/button.md +0 -322
  76. package/skill/margaui/components/calendar.md +0 -67
  77. package/skill/margaui/components/card.md +0 -373
  78. package/skill/margaui/components/carousel.md +0 -387
  79. package/skill/margaui/components/chat.md +0 -171
  80. package/skill/margaui/components/checkbox.md +0 -101
  81. package/skill/margaui/components/collapse.md +0 -172
  82. package/skill/margaui/components/countdown.md +0 -165
  83. package/skill/margaui/components/diff.md +0 -53
  84. package/skill/margaui/components/divider.md +0 -107
  85. package/skill/margaui/components/dock.md +0 -173
  86. package/skill/margaui/components/drawer.md +0 -184
  87. package/skill/margaui/components/dropdown.md +0 -388
  88. package/skill/margaui/components/fab.md +0 -346
  89. package/skill/margaui/components/fieldset.md +0 -88
  90. package/skill/margaui/components/file-input.md +0 -84
  91. package/skill/margaui/components/filter.md +0 -52
  92. package/skill/margaui/components/footer.md +0 -583
  93. package/skill/margaui/components/hero.md +0 -135
  94. package/skill/margaui/components/hover-3d.md +0 -129
  95. package/skill/margaui/components/hover-gallery.md +0 -49
  96. package/skill/margaui/components/indicator.md +0 -265
  97. package/skill/margaui/components/input.md +0 -389
  98. package/skill/margaui/components/join.md +0 -100
  99. package/skill/margaui/components/kbd.md +0 -127
  100. package/skill/margaui/components/label.md +0 -102
  101. package/skill/margaui/components/link.md +0 -96
  102. package/skill/margaui/components/list.md +0 -182
  103. package/skill/margaui/components/loading.md +0 -105
  104. package/skill/margaui/components/mask.md +0 -168
  105. package/skill/margaui/components/megamenu.md +0 -131
  106. package/skill/margaui/components/menu.md +0 -887
  107. package/skill/margaui/components/mockup-browser.md +0 -39
  108. package/skill/margaui/components/mockup-code.md +0 -81
  109. package/skill/margaui/components/mockup-phone.md +0 -39
  110. package/skill/margaui/components/mockup-window.md +0 -33
  111. package/skill/margaui/components/modal.md +0 -196
  112. package/skill/margaui/components/navbar.md +0 -282
  113. package/skill/margaui/components/otp.md +0 -171
  114. package/skill/margaui/components/pagination.md +0 -122
  115. package/skill/margaui/components/progress.md +0 -135
  116. package/skill/margaui/components/radial-progress.md +0 -67
  117. package/skill/margaui/components/radio.md +0 -133
  118. package/skill/margaui/components/range.md +0 -134
  119. package/skill/margaui/components/rating.md +0 -170
  120. package/skill/margaui/components/select.md +0 -225
  121. package/skill/margaui/components/skeleton.md +0 -64
  122. package/skill/margaui/components/stack.md +0 -142
  123. package/skill/margaui/components/stat.md +0 -254
  124. package/skill/margaui/components/status.md +0 -73
  125. package/skill/margaui/components/steps.md +0 -138
  126. package/skill/margaui/components/swap.md +0 -152
  127. package/skill/margaui/components/tab.md +0 -248
  128. package/skill/margaui/components/table.md +0 -1018
  129. package/skill/margaui/components/text-rotate.md +0 -91
  130. package/skill/margaui/components/textarea.md +0 -85
  131. package/skill/margaui/components/theme-controller.md +0 -266
  132. package/skill/margaui/components/timeline.md +0 -1356
  133. package/skill/margaui/components/toast.md +0 -165
  134. package/skill/margaui/components/toggle.md +0 -135
  135. package/skill/margaui/components/tooltip.md +0 -181
  136. package/skill/margaui/components/validator.md +0 -163
  137. package/skill/tutuca/SKILL.md +0 -56
  138. package/skill/tutuca/advanced.md +0 -292
  139. package/skill/tutuca/cli.md +0 -239
  140. package/skill/tutuca/component-design.md +0 -168
  141. package/skill/tutuca/core.md +0 -935
  142. package/skill/tutuca/iteration.md +0 -207
  143. package/skill/tutuca/macros.md +0 -86
  144. package/skill/tutuca/margaui.md +0 -175
  145. package/skill/tutuca/messages-and-intents.md +0 -414
  146. package/skill/tutuca/patterns/README.md +0 -48
  147. package/skill/tutuca/patterns/add-a-story.md +0 -26
  148. package/skill/tutuca/patterns/bind-text-and-attributes.md +0 -30
  149. package/skill/tutuca/patterns/conditional-attribute-value.md +0 -29
  150. package/skill/tutuca/patterns/coordinate-components.md +0 -54
  151. package/skill/tutuca/patterns/edit-through-a-dynamic-target.md +0 -32
  152. package/skill/tutuca/patterns/enrich-each-item.md +0 -25
  153. package/skill/tutuca/patterns/file-input.md +0 -39
  154. package/skill/tutuca/patterns/filter-a-list.md +0 -25
  155. package/skill/tutuca/patterns/filter-and-paginate.md +0 -60
  156. package/skill/tutuca/patterns/handle-events.md +0 -45
  157. package/skill/tutuca/patterns/iterate-a-list.md +0 -18
  158. package/skill/tutuca/patterns/paginate-a-list.md +0 -29
  159. package/skill/tutuca/patterns/render-a-child-component.md +0 -21
  160. package/skill/tutuca/patterns/reuse-markup-with-macros.md +0 -36
  161. package/skill/tutuca/patterns/share-state-across-the-tree.md +0 -53
  162. package/skill/tutuca/patterns/show-or-hide-content.md +0 -23
  163. package/skill/tutuca/patterns/switch-between-views.md +0 -30
  164. package/skill/tutuca/patterns/tabbed-interface.md +0 -43
  165. package/skill/tutuca/semantics.md +0 -219
  166. package/skill/tutuca/storybook.md +0 -270
  167. package/skill/tutuca/styles.md +0 -48
  168. package/skill/tutuca/testing.md +0 -345
  169. package/skill/tutuca-source/SKILL.md +0 -33
  170. package/skill/tutuca-source/tutuca.ext.js +0 -4183
@@ -0,0 +1,400 @@
1
+ // Tutuca components that show in a page what the DevTools formatters of src/dev/formatters.js show
2
+ // in the console: a component's fields and spec, field types, views, paths, tasks, scopes
3
+ // and render contexts, each node expanding into its rows. The main views say it in plain
4
+ // words (summary.js); the code views print it as formatters.js does.
5
+
6
+ import {
7
+ $if,
8
+ ComponentSpec,
9
+ component,
10
+ each,
11
+ field,
12
+ lookupBind,
13
+ pushView,
14
+ render,
15
+ renderEach,
16
+ send,
17
+ t,
18
+ tag,
19
+ } from "../tutuca.js";
20
+ import { describe, isObject, S } from "./formatters.js";
21
+ import { truncate } from "./jsonml.js";
22
+ import { summarize } from "./summary.js";
23
+
24
+ const { button, div, h3, li, p, section, span, ul } = tag;
25
+
26
+ // Live values stay out of the state: a node holds a ref to its value, so immer never walks
27
+ // or freezes a spec, scope or task, and the state stays plain data.
28
+ const refs = new Map();
29
+ const ids = new WeakMap();
30
+ let nextRef = 1;
31
+ const idOf = (v) => {
32
+ if (!isObject(v)) return 0;
33
+ let id = ids.get(v);
34
+ if (id === undefined) {
35
+ id = nextRef++;
36
+ ids.set(v, id);
37
+ refs.set(id, new WeakRef(v));
38
+ }
39
+ return id;
40
+ };
41
+ const deref = (id) => refs.get(id)?.deref();
42
+
43
+ // Classes for the styles of src/dev/formatters.js, by the name it gives them.
44
+ const TONES = {
45
+ plain: "",
46
+ name: "font-bold text-warning",
47
+ key: "text-secondary",
48
+ str: "text-success",
49
+ num: "text-info",
50
+ fn: "text-accent",
51
+ muted: "opacity-60",
52
+ };
53
+ const TONE_OF_STYLE = new Map(Object.entries(S).map(([tone, style]) => [style, tone]));
54
+ const MAX_TEXT = 60;
55
+
56
+ // JsonML parts as { text, tone } tokens; adjacent tokens of one tone merge.
57
+ const tokensOf = (parts) => {
58
+ const tokens = [];
59
+ const add = (text, tone) => {
60
+ const last = tokens.at(-1);
61
+ if (last?.tone === tone) last.text += text;
62
+ else tokens.push({ text, tone });
63
+ };
64
+ const visit = (part, tone) => {
65
+ if (typeof part === "string") return add(part, tone);
66
+ if (!Array.isArray(part)) return add(String(part), tone);
67
+ const [tag, attrs, ...kids] = part;
68
+ if (tag === "object") return add("{…}", "muted");
69
+ const own = TONE_OF_STYLE.get(attrs?.style) ?? tone;
70
+ for (const kid of kids) visit(kid, own);
71
+ };
72
+ for (const part of parts) visit(part, "plain");
73
+ return tokens;
74
+ };
75
+ const primTokens = (v) => {
76
+ if (typeof v === "string") return [{ text: truncate(JSON.stringify(v), MAX_TEXT), tone: "str" }];
77
+ if (typeof v === "function") return [{ text: `ƒ ${v.name}`, tone: "fn" }];
78
+ if (typeof v === "number" || typeof v === "boolean" || typeof v === "bigint") {
79
+ return [{ text: String(v), tone: "num" }];
80
+ }
81
+ return [{ text: String(v), tone: "muted" }];
82
+ };
83
+ const entriesOf = (v) => {
84
+ if (v instanceof Map) return [...v.entries()].map(([k, x]) => ({ label: String(k), value: x }));
85
+ if (v instanceof Set) return [...v].map((x, i) => ({ label: String(i), value: x }));
86
+ return Object.keys(v).map((k) => ({ label: k, value: v[k] }));
87
+ };
88
+ const safeDescribe = (v) => {
89
+ try {
90
+ return describe(v);
91
+ } catch {
92
+ return null; // e.g. a revoked immer draft
93
+ }
94
+ };
95
+ // What a node shows for v: header tokens, and rows as { label, value } to expand into nodes
96
+ // or { label, tokens } leaves.
97
+ export const inspect = (v) => {
98
+ if (!isObject(v) || typeof v === "function") return { tokens: primTokens(v), rows: [] };
99
+ const described = safeDescribe(v);
100
+ if (described !== null) {
101
+ // A spec's field types expand as types, so the readable view can name them.
102
+ const fields = v instanceof ComponentSpec ? v.fields : {};
103
+ const rows = described.rows.map(([label, value]) =>
104
+ Object.hasOwn(fields, label)
105
+ ? { label, value: fields[label] }
106
+ : value[0] === "object"
107
+ ? { label: label ?? "", value: value[1].object }
108
+ : { label: label ?? "", tokens: tokensOf([value]) },
109
+ );
110
+ return { tokens: tokensOf(described.header), rows };
111
+ }
112
+ const rows = entriesOf(v);
113
+ const name = Array.isArray(v) ? `Array(${v.length})` : (v.constructor?.name ?? "Object");
114
+ const size = v instanceof Map || v instanceof Set ? `(${v.size})` : "";
115
+ return { tokens: [{ text: `${name}${size}`, tone: "muted" }], rows };
116
+ };
117
+
118
+ const TONE_NAMES = Object.keys(TONES);
119
+ // A node for value, labelled; it computes its rows only when opened.
120
+ export const devNode = (C, label, value) => {
121
+ const { tokens, rows } = inspect(value);
122
+ const { title, detail } = summarize(value);
123
+ return C.DevNode({ label, tokens, title, detail, ref: idOf(value), canOpen: rows.length > 0 });
124
+ };
125
+ // A row with nothing to expand reads the same either way.
126
+ const leafNode = (C, label, tokens) =>
127
+ C.DevNode({ label, tokens, title: tokens.map((t) => t.text).join("") });
128
+
129
+ const expander = $if(
130
+ field("canOpen"),
131
+ button(
132
+ {
133
+ type: "button",
134
+ class: "w-3 shrink-0 cursor-pointer opacity-60 hover:opacity-100",
135
+ "aria-label": "Expand",
136
+ "on:click": send("toggle"),
137
+ },
138
+ $if(field("isOpen"), "▾", "▸"),
139
+ ),
140
+ span({ class: "w-3 shrink-0" }),
141
+ );
142
+ export const DevNode = component({
143
+ name: "DevNode",
144
+ fields: {
145
+ label: t.string(),
146
+ title: t.string(),
147
+ detail: t.string(),
148
+ tokens: t.array(t.record({ text: t.string(), tone: t.enum(...TONE_NAMES) })),
149
+ ref: t.number().int().min(0), // 0 for values with nothing to expand.
150
+ canOpen: t.boolean(),
151
+ isOpen: t.boolean(),
152
+ rows: t.array(t.component("DevNode")),
153
+ },
154
+ methods: {
155
+ get hasLabel() {
156
+ return this.label !== "";
157
+ },
158
+ get showRows() {
159
+ return this.isOpen && this.rows.length > 0;
160
+ },
161
+ get hasDetail() {
162
+ return this.detail !== "";
163
+ },
164
+ },
165
+ loops: {
166
+ tokens: {
167
+ enrich({ value }) {
168
+ return { tone: TONES[value.tone] };
169
+ },
170
+ },
171
+ },
172
+ views: {
173
+ main: div(
174
+ { class: "text-sm leading-6" },
175
+ div(
176
+ { class: "flex items-baseline gap-1.5" },
177
+ expander,
178
+ $if(field("hasLabel"), span({ class: "text-base-content/60" }, field("label")), ""),
179
+ span({ class: "min-w-0 font-medium break-words" }, field("title")),
180
+ $if(
181
+ field("hasDetail"),
182
+ span({ class: "min-w-0 text-xs text-base-content/60 break-words" }, field("detail")),
183
+ "",
184
+ ),
185
+ ),
186
+ $if(
187
+ field("showRows"),
188
+ div({ class: "ml-1.5 border-l border-base-300 pl-3" }, renderEach(field("rows"))),
189
+ "",
190
+ ),
191
+ ),
192
+ code: div(
193
+ { class: "font-mono text-xs leading-5" },
194
+ div(
195
+ { class: "flex items-baseline gap-1" },
196
+ expander,
197
+ $if(field("hasLabel"), span({ class: "text-secondary" }, field("label"), ":"), ""),
198
+ span(
199
+ { class: "min-w-0 break-all" },
200
+ each(field("tokens"), span({ class: lookupBind("tone") }, field("text")), "tokens"),
201
+ ),
202
+ ),
203
+ $if(
204
+ field("showRows"),
205
+ div({ class: "ml-1.5 border-l border-base-300 pl-3" }, renderEach(field("rows"))),
206
+ "",
207
+ ),
208
+ ),
209
+ },
210
+ on: {
211
+ toggle: {
212
+ args: [],
213
+ post: (prev, next) => next.isOpen !== prev.isOpen,
214
+ run(next, _args, ctx) {
215
+ next.isOpen = !this.isOpen;
216
+ if (!next.isOpen || this.rows.length > 0) return;
217
+ const value = deref(this.ref);
218
+ if (value === undefined) return;
219
+ const C = ctx.scope.components;
220
+ next.rows = inspect(value).rows.map((row) =>
221
+ row.tokens === undefined
222
+ ? devNode(C, row.label, row.value)
223
+ : leafNode(C, row.label, row.tokens),
224
+ );
225
+ },
226
+ },
227
+ },
228
+ });
229
+
230
+ const sectionTitle = "text-xs font-semibold uppercase tracking-wider text-base-content/60";
231
+
232
+ // A titled list of nodes.
233
+ export const DevSection = component({
234
+ name: "DevSection",
235
+ fields: {
236
+ title: t.string(),
237
+ emptyText: t.string("Nothing to show."),
238
+ nodes: t.array(t.component("DevNode")),
239
+ },
240
+ methods: {
241
+ get isEmpty() {
242
+ return this.nodes.length === 0;
243
+ },
244
+ },
245
+ view: section(
246
+ { class: "flex flex-col gap-1" },
247
+ h3({ class: sectionTitle }, field("title")),
248
+ $if(
249
+ field("isEmpty"),
250
+ p({ class: "text-xs text-base-content/50" }, field("emptyText")),
251
+ div({ class: "flex flex-col" }, renderEach(field("nodes"))),
252
+ ),
253
+ ),
254
+ });
255
+
256
+ const BADGE = "badge badge-sm shrink-0 whitespace-nowrap font-mono";
257
+ const LEVELS = { error: `${BADGE} badge-error`, warning: `${BADGE} badge-warning` };
258
+ // The issues of lint() from src/lint/index.js, as plain records.
259
+ export const DevLint = component({
260
+ name: "DevLint",
261
+ fields: {
262
+ issues: t.array(
263
+ t.record({
264
+ level: t.enum("error", "warning"),
265
+ code: t.string(),
266
+ path: t.string(),
267
+ message: t.string(),
268
+ }),
269
+ ),
270
+ },
271
+ methods: {
272
+ get isClean() {
273
+ return this.issues.length === 0;
274
+ },
275
+ },
276
+ loops: {
277
+ issues: {
278
+ enrich({ value }) {
279
+ return { badge: LEVELS[value.level] };
280
+ },
281
+ },
282
+ },
283
+ view: section(
284
+ { class: "flex flex-col gap-1" },
285
+ h3({ class: sectionTitle }, "Lint"),
286
+ $if(
287
+ field("isClean"),
288
+ p({ class: "text-xs text-success" }, "Clean"),
289
+ ul(
290
+ { class: "flex flex-col divide-y divide-base-300" },
291
+ each(
292
+ field("issues"),
293
+ li(
294
+ { class: "flex min-w-0 flex-col gap-1 py-2 text-xs first:pt-0 last:pb-0" },
295
+ div(
296
+ { class: "flex flex-wrap items-center gap-2" },
297
+ span({ class: lookupBind("badge") }, field("code")),
298
+ span({ class: "min-w-0" }, field("message")),
299
+ ),
300
+ span({ class: "min-w-0 break-all font-mono opacity-60" }, field("path")),
301
+ ),
302
+ "issues",
303
+ ),
304
+ ),
305
+ ),
306
+ ),
307
+ });
308
+ export const lintRecords = (issues) =>
309
+ issues.map(({ level, code, path, message }) => ({ level, code, path, message }));
310
+
311
+ // Dev information about a running app: its state, the tasks that made it, its components
312
+ // and their lint issues. update() keeps the nodes whose values didn't change, so what is
313
+ // open stays open.
314
+ const card = (name) =>
315
+ div({ class: "card border border-base-300 bg-base-100 p-4" }, render(field(name)));
316
+ const VIEW_BUTTON = "btn btn-xs join-item";
317
+ export const DevPanel = component({
318
+ name: "DevPanel",
319
+ fields: {
320
+ view: t.enum("main", "code"),
321
+ state: t.component("DevSection"),
322
+ tasks: t.component("DevSection"),
323
+ specs: t.component("DevSection"),
324
+ lint: t.component("DevLint"),
325
+ },
326
+ methods: {
327
+ get isCode() {
328
+ return this.view === "code";
329
+ },
330
+ },
331
+ view: div(
332
+ { class: "flex flex-col gap-3" },
333
+ div(
334
+ { class: "join self-start", role: "group", "aria-label": "Show as" },
335
+ button(
336
+ {
337
+ type: "button",
338
+ class: $if(field("isCode"), VIEW_BUTTON, `${VIEW_BUTTON} btn-primary`),
339
+ "on:click": send("setView", "main"),
340
+ },
341
+ "Readable",
342
+ ),
343
+ button(
344
+ {
345
+ type: "button",
346
+ class: $if(field("isCode"), `${VIEW_BUTTON} btn-primary`, VIEW_BUTTON),
347
+ "on:click": send("setView", "code"),
348
+ },
349
+ "Code",
350
+ ),
351
+ ),
352
+ // Every node below shows the view picked here.
353
+ pushView(
354
+ field("view"),
355
+ div(
356
+ { class: "grid gap-4 xl:grid-cols-2" },
357
+ div({ class: "flex min-w-0 flex-col gap-4" }, card("state"), card("tasks")),
358
+ div({ class: "flex min-w-0 flex-col gap-4" }, card("specs"), card("lint")),
359
+ ),
360
+ ),
361
+ ),
362
+ on: {
363
+ setView: {
364
+ args: [t.enum("main", "code")],
365
+ run(next, [view]) {
366
+ next.view = view;
367
+ },
368
+ },
369
+ },
370
+ });
371
+
372
+ export const makeDevPanel = (C) =>
373
+ C.DevPanel({
374
+ state: C.DevSection({ title: "State" }),
375
+ tasks: C.DevSection({ title: "Tasks", emptyText: "No tasks made this state." }),
376
+ specs: C.DevSection({ title: "Components" }),
377
+ lint: C.DevLint(),
378
+ });
379
+
380
+ const sameRefs = (nodes, values) =>
381
+ nodes.length === values.length && nodes.every((n, i) => n.ref === idOf(values[i].value));
382
+ // Sets section's nodes to { label, value } items, unless they show the same values already.
383
+ const updateSection = (C, section, items) => {
384
+ if (sameRefs(section.nodes, items)) return;
385
+ section.nodes = items.map(({ label, value }) => devNode(C, label, value));
386
+ };
387
+ // data: { state, tasks: [{ label, value }], specs: [spec], issues } for next, a DevPanel being updated.
388
+ export const updateDevPanel = (C, next, { state, tasks, specs, issues }) => {
389
+ updateSection(C, next.state, [{ label: "", value: state }]);
390
+ updateSection(C, next.tasks, tasks);
391
+ updateSection(
392
+ C,
393
+ next.specs,
394
+ specs.map((spec) => ({ label: "", value: spec })),
395
+ );
396
+ next.lint.issues = lintRecords(issues);
397
+ };
398
+
399
+ export const devComponents = { DevNode, DevSection, DevLint, DevPanel };
400
+ export const devClasses = [...Object.values(TONES), ...Object.values(LEVELS)];
@@ -0,0 +1,239 @@
1
+ // Plain language for tutuca values: what a node shows in its readable view, as
2
+ // { title, detail }. The code view shows them as src/dev/formatters.js prints them.
3
+ import {
4
+ AnyType,
5
+ ArrayType,
6
+ AskTask,
7
+ AstNode,
8
+ BooleanType,
9
+ ComponentSpec,
10
+ ComponentType,
11
+ DispatchPath,
12
+ EnumType,
13
+ EventTask,
14
+ Frame,
15
+ IndexType,
16
+ MapType,
17
+ MessageContext,
18
+ NotifyTask,
19
+ NumberType,
20
+ OptionType,
21
+ RecordType,
22
+ RenderContext,
23
+ Scope,
24
+ Selector,
25
+ StringType,
26
+ specOf,
27
+ Target,
28
+ Task,
29
+ UnionType,
30
+ UpdatePath,
31
+ } from "../tutuca.js";
32
+ import { truncate } from "./jsonml.js";
33
+
34
+ const MAX = 40;
35
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
36
+ const quote = (s) => `“${truncate(String(s), MAX)}”`;
37
+ // specOf alone isn't enough: a Proxy may answer any key.
38
+ export const isTutucaComponent = (v) => specOf(v) instanceof ComponentSpec;
39
+
40
+ // A value in a few words: "“hello”", "42", "3 items", "Tab".
41
+ const brief = (v) => {
42
+ if (typeof v === "string") return quote(v);
43
+ if (v === null || v === undefined) return "nothing";
44
+ if (typeof v === "function") return `function ${v.name || "(anonymous)"}`;
45
+ if (typeof v !== "object") return String(v);
46
+ if (isTutucaComponent(v)) return specOf(v).name;
47
+ if (Array.isArray(v)) return v.length === 0 ? "empty list" : `list of ${v.length}`;
48
+ if (v instanceof Map || v instanceof Set) return plural(v.size, "item");
49
+ return plural(Object.keys(v).length, "entry", "entries");
50
+ };
51
+
52
+ const frameWords = (frame) => [
53
+ ...(frame.provider === null ? [] : [`provided ${frame.provider.name}`]),
54
+ ...frame.accessKeys.map(String),
55
+ ];
56
+ const opWords = (op) =>
57
+ op.t === "field"
58
+ ? [op.name]
59
+ : op.t === "item"
60
+ ? [op.name, String(op.key)]
61
+ : [op.name, `item at ${op.keyName}`];
62
+ const pathWordList = (path) => {
63
+ if (path instanceof UpdatePath) return path.keys.map(String);
64
+ if (path instanceof Selector) return path.ops.flatMap(opWords);
65
+ if (path instanceof Target) return [...pathWordList(path.base), ...pathWordList(path.selector)];
66
+ return path.frames.flatMap(frameWords);
67
+ };
68
+ // "tabs → 1 → child", or "the root".
69
+ const pathWords = (path) => {
70
+ const words = pathWordList(path);
71
+ return words.length === 0 ? "the root" : words.join(" → ");
72
+ };
73
+
74
+ const CONSTRAINTS = {
75
+ int: () => "whole",
76
+ min: (n) => `at least ${n}`,
77
+ max: (n) => `at most ${n}`,
78
+ minLength: (n) => (n === 0 ? "" : `at least ${n} long`),
79
+ maxLength: (n) => (n === Number.POSITIVE_INFINITY ? "" : `at most ${n} long`),
80
+ pattern: (re) => `matching ${re}`,
81
+ where: (preds) => preds.map((p) => `where ${p.name || "a check"} holds`).join(", "),
82
+ };
83
+ // "list of whole number", "one of grey, red", "Tab component or nothing".
84
+ const typeWords = (type) => {
85
+ if (type instanceof OptionType) return `${typeWords(type.valueType)} or nothing`;
86
+ if (type instanceof StringType) return "text";
87
+ if (type instanceof BooleanType) return "true or false";
88
+ if (type instanceof NumberType) return type.constraints.int ? "whole number" : "number";
89
+ if (type instanceof EnumType) return `one of ${type.members.map(String).join(", ")}`;
90
+ if (type instanceof ArrayType) return `list of ${typeWords(type.valueType)}`;
91
+ if (type instanceof MapType) return `map of ${typeWords(type.valueType)}`;
92
+ if (type instanceof RecordType) return `record of ${Object.keys(type.shape).join(", ")}`;
93
+ if (type instanceof UnionType) return `either ${type.types.map(typeWords).join(" or ")}`;
94
+ if (type instanceof IndexType) return `a key of ${type.fieldName}`;
95
+ if (type instanceof ComponentType)
96
+ return type.names.length === 0 ? "any component" : `${type.names.join(" or ")} component`;
97
+ return "anything";
98
+ };
99
+ const typeDetail = (type) => {
100
+ const parts = Object.entries(type.constraints)
101
+ .filter(([key]) => key !== "int")
102
+ .map(([key, value]) => CONSTRAINTS[key]?.(value) ?? key)
103
+ .filter(Boolean);
104
+ const { defaultValue } = type;
105
+ if (defaultValue !== undefined && defaultValue !== null && typeof defaultValue !== "function") {
106
+ parts.push(`default ${brief(defaultValue)}`);
107
+ }
108
+ return parts.join(", ");
109
+ };
110
+
111
+ const sourceWords = (node) => (node instanceof AstNode ? astTitle(node) : brief(node));
112
+ const astTitle = (node) => {
113
+ switch (node.constructor.kind) {
114
+ case "element":
115
+ return `<${node.tagName}> element`;
116
+ case "field":
117
+ return `the field ${quote(node.name)}`;
118
+ case "seqItem":
119
+ return `the ${node.seqName} item at ${quote(node.keyName)}`;
120
+ case "provided":
121
+ return `the provided ${quote(node.name)}`;
122
+ case "constant":
123
+ return brief(node.value);
124
+ case "render":
125
+ return `renders ${sourceWords(node.source)}${node.viewName ? ` as ${quote(node.viewName)}` : ""}`;
126
+ case "renderIt":
127
+ return "renders the current item";
128
+ case "renderEach":
129
+ return `renders each of ${sourceWords(node.source)}`;
130
+ case "each":
131
+ return `repeats for each of ${sourceWords(node.source)}`;
132
+ case "cond":
133
+ return `if ${sourceWords(node.source)}`;
134
+ case "pushView":
135
+ return `uses the view ${sourceWords(node.viewNameVal)} inside`;
136
+ case "scope":
137
+ return `with the bindings of ${quote(node.scopeName)}`;
138
+ case "action":
139
+ return `sends ${quote(node.name)}`;
140
+ case "targetValue":
141
+ return "the value of the event's target";
142
+ case "sourceKey":
143
+ return "the key the event came from";
144
+ case "dragKey":
145
+ return "the key the dragged element came from";
146
+ case "lookupBind":
147
+ return `the binding ${quote(node.name)}`;
148
+ default:
149
+ return node.constructor.name;
150
+ }
151
+ };
152
+ const astDetail = (node) => {
153
+ switch (node.constructor.kind) {
154
+ case "element": {
155
+ const parts = [];
156
+ if (node.attrs.length > 0) parts.push(plural(node.attrs.length, "attribute"));
157
+ if (node.childs.length > 0) parts.push(plural(node.childs.length, "child", "children"));
158
+ if (node.handlers.length > 0)
159
+ parts.push(`handles ${node.handlers.map((h) => h.name).join(", ")}`);
160
+ return parts.join(" · ");
161
+ }
162
+ case "each":
163
+ case "renderEach":
164
+ return node.loopName ? `with the loop ${quote(node.loopName)}` : "";
165
+ case "action":
166
+ return node.args.length === 0 ? "" : `with ${plural(node.args.length, "argument")}`;
167
+ default:
168
+ return "";
169
+ }
170
+ };
171
+ // Each kind of task: the noun a summary titles it with and the verb a formatter shows.
172
+ const TASKS = [
173
+ [EventTask, "event", "event"],
174
+ [AskTask, "ask", "ask"],
175
+ [NotifyTask, "notification", "notify"],
176
+ [Task, "message", "send"],
177
+ ];
178
+ const taskWords = (task) => TASKS.find(([Kind]) => task instanceof Kind);
179
+ export const taskVerb = (task) => taskWords(task)[2];
180
+
181
+ export const summarize = (v) => {
182
+ try {
183
+ return summarizeUnsafe(v);
184
+ } catch {
185
+ return { title: brief(v), detail: "" }; // e.g. a revoked immer draft
186
+ }
187
+ };
188
+ const summarizeUnsafe = (v) => {
189
+ if (isTutucaComponent(v)) {
190
+ const fields = Object.keys(specOf(v).fields);
191
+ const shown = fields.slice(0, 3).map((k) => `${k} ${brief(v[k])}`);
192
+ return {
193
+ title: `${specOf(v).name}`,
194
+ detail: [...shown, ...(fields.length > 3 ? ["…"] : [])].join(" · "),
195
+ };
196
+ }
197
+ if (v instanceof ComponentSpec) {
198
+ const n = (o) => Object.keys(o).length;
199
+ const parts = [
200
+ plural(n(v.fields), "field"),
201
+ plural(n(v.views), "view"),
202
+ plural(n(v.on), "message"),
203
+ ];
204
+ if (n(v.invariants) > 0) parts.push(plural(n(v.invariants), "invariant"));
205
+ return { title: `${v.name} component`, detail: parts.join(" · ") };
206
+ }
207
+ if (v instanceof AnyType) return { title: typeWords(v), detail: typeDetail(v) };
208
+ if (v instanceof AstNode) return { title: astTitle(v), detail: astDetail(v) };
209
+ if (v instanceof DispatchPath || v instanceof UpdatePath)
210
+ return { title: "path", detail: pathWords(v) };
211
+ if (v instanceof Selector) return { title: "selector", detail: pathWords(v) };
212
+ if (v instanceof Target) return { title: "target", detail: pathWords(v) };
213
+ if (v instanceof Frame) return { title: "frame", detail: frameWords(v).join(" → ") || "nothing" };
214
+ if (v instanceof Task) {
215
+ const [, kind] = taskWords(v);
216
+ const where = v.to?.path ?? v.target;
217
+ const to = where === null ? "the ancestors" : pathWords(where);
218
+ const from = v.from.isHost ? "the host" : pathWords(v.from.path);
219
+ return {
220
+ title: `${kind} ${quote(v.name)}`,
221
+ detail: from === to ? `to ${to}` : `from ${from} to ${to}`,
222
+ };
223
+ }
224
+ if (v instanceof MessageContext)
225
+ return { title: "message context", detail: `at ${pathWords(v.path)}` };
226
+ if (v instanceof Scope) {
227
+ const names = Object.keys(v.byName);
228
+ return {
229
+ title: "scope",
230
+ detail: `${plural(names.length, "component")}${v.parent === null ? "" : " · inside another scope"}`,
231
+ };
232
+ }
233
+ if (v instanceof RenderContext)
234
+ return {
235
+ title: "render context",
236
+ detail: `${specOf(v.component)?.name ?? "?"} at depth ${v.depth}`,
237
+ };
238
+ return { title: brief(v), detail: "" };
239
+ };