effect-atom-svelte-devtools 0.2.2 → 0.3.0

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.
@@ -1,4 +1,6 @@
1
- import type { GraphEdge, GraphNode } from "./frame-graph.svelte";
1
+ import type { GraphEdge, GraphNode } from "./graph-types.ts";
2
+ /** Still held but read by nothing in view, or just removed. */
3
+ type AtomStatus = "live" | "held" | "removed";
2
4
  /** An atom to draw. */
3
5
  export interface GraphAtom {
4
6
  /** Stable for the atom, and in the order it was first seen: the layout keeps that order. */
@@ -7,7 +9,7 @@ export interface GraphAtom {
7
9
  /** The line under its name: its result, or why it's still held. */
8
10
  readonly note?: string | undefined;
9
11
  /** Still held but read by nothing in view (`held`), or just removed (`removed`, drawn crossed). */
10
- readonly status?: "live" | "held" | "removed" | undefined;
12
+ readonly status?: AtomStatus | undefined;
11
13
  /** Read by something, when there are no component readers to say so (the devtools panel). */
12
14
  readonly read?: boolean | undefined;
13
15
  }
@@ -63,3 +65,4 @@ export declare const toneOf: (state: string | undefined, waiting?: boolean) => "
63
65
  * depend on it: x is a fraction of the width, y is in pixels). Undefined when there's nothing to draw.
64
66
  */
65
67
  export declare const layoutGraph: (input: GraphInput, width: number) => GraphLayout | undefined;
68
+ export {};
@@ -22,7 +22,7 @@ const componentColumn = 0.72;
22
22
  const keyOf = (args) => {
23
23
  try {
24
24
  const value = JSON.parse(args);
25
- if (value && typeof value === "object") {
25
+ if (typeof value === "object" && value !== null) {
26
26
  return Object.values(value).map(String).join(" · ");
27
27
  }
28
28
  return String(value);
@@ -83,7 +83,7 @@ const parentsOf = (links, atoms, canonical) => {
83
83
  if (from !== to &&
84
84
  atoms.has(from) &&
85
85
  atoms.has(to) &&
86
- !parents.get(to)?.includes(from)) {
86
+ parents.get(to)?.includes(from) !== true) {
87
87
  append(parents, to, from);
88
88
  }
89
89
  }
@@ -272,11 +272,12 @@ const positions = (shape, tracks, dotted) => {
272
272
  const groupNode = (id, group, x, y) => {
273
273
  const repeats = group.dots.filter((dot) => dot.repeat).length;
274
274
  const keys = `${group.keys} ${group.keys === 1 ? "key" : "keys"}`;
275
+ const repeated = repeats > 0 ? ` · ${repeats} repeat a key` : "";
275
276
  return {
276
277
  id: `g${id}`,
277
278
  kind: "junction",
278
279
  label: `${group.name}(…)`,
279
- note: `${group.dots.length} atoms for ${keys}${repeats > 0 ? ` · ${repeats} repeat a key` : ""}`,
280
+ note: `${group.dots.length} atoms for ${keys}${repeated}`,
280
281
  side: "ne",
281
282
  x,
282
283
  y,
@@ -285,7 +286,7 @@ const groupNode = (id, group, x, y) => {
285
286
  const componentNote = (component) => {
286
287
  const kinds = new Set([...component.uses.values()].flatMap((uses) => [...uses]));
287
288
  if (!kinds.has("write")) {
288
- return undefined;
289
+ return;
289
290
  }
290
291
  return kinds.size === 1 ? "writes" : "reads, writes";
291
292
  };
@@ -11,7 +11,10 @@ export const stateText = (state) => {
11
11
  }
12
12
  return state.waiting ? `${state._tag}, waiting` : state._tag;
13
13
  };
14
- const hasToJSON = (value) => typeof value.toJSON === "function";
14
+ const hasToJSON = (value) => typeof value === "object" &&
15
+ value !== null &&
16
+ "toJSON" in value &&
17
+ typeof value.toJSON === "function";
15
18
  // How much of a value is written out: deeper or longer parts are cut short.
16
19
  const maxDepth = 5;
17
20
  const maxItems = 50;
@@ -80,7 +83,7 @@ const plainResult = (result, inner) => {
80
83
  waiting: result.waiting,
81
84
  };
82
85
  }
83
- default: {
86
+ case "Failure": {
84
87
  // What it failed with, fields and all, as the graph's note promises; then the whole cause.
85
88
  // oxlint-disable-next-line eslint/sort-keys -- what it failed with reads before the whole cause
86
89
  return {
@@ -102,7 +105,9 @@ const listed = (items, inner) => {
102
105
  /** An object cut to `maxItems` entries, saying how many more there are. */
103
106
  const withMore = (object, count) => count > maxItems ? { ...object, "…": `${count - maxItems} more` } : object;
104
107
  const isPrimitive = (value) => value === null || (typeof value !== "object" && typeof value !== "function");
105
- const plainObject = (value, inner) => {
108
+ const plainObject = (
109
+ // oxlint-disable-next-line anti-slop/no-object-parameters -- any value an atom holds that isn't a primitive: there is no narrower type
110
+ value, inner) => {
106
111
  if (AsyncResult.isAsyncResult(value)) {
107
112
  return plainResult(value, inner);
108
113
  }
@@ -114,7 +119,8 @@ const plainObject = (value, inner) => {
114
119
  return errorText(value, (field) => json(inner(field)));
115
120
  }
116
121
  if (value instanceof Map) {
117
- const entries = [...value];
122
+ const map = value;
123
+ const entries = [...map];
118
124
  // Primitive keys that stay distinct as strings make an object; any other keys would collide
119
125
  // or lose themselves as strings, so those maps are written as `[key, value]` pairs.
120
126
  const keys = entries.map(([key]) => key);
@@ -163,12 +169,13 @@ export const plain = (value, depth = 0, seen = new Set()) => {
163
169
  case "undefined": {
164
170
  return depth === 0 ? value : bare("undefined");
165
171
  }
172
+ case "boolean":
173
+ case "string": {
174
+ return value;
175
+ }
166
176
  case "object": {
167
177
  break;
168
178
  }
169
- default: {
170
- return value;
171
- }
172
179
  }
173
180
  if (value === null) {
174
181
  return value;
@@ -4,10 +4,10 @@
4
4
  effect is interrupted or an atom removed. Clicking an atom opens its sheet.
5
5
  -->
6
6
  <script lang="ts">
7
- import { AtomGraph, toneOf } from "../graph/index.js";
8
- import type { GraphAtom, GraphInput } from "../graph/index.js";
9
7
  import { AsyncResult } from "effect/reactivity";
10
8
 
9
+ import { AtomGraph, toneOf } from "../graph/index.js";
10
+ import type { GraphAtom, GraphInput } from "../graph/index.js";
11
11
  import { failureText, preview, stateText } from "./format.js";
12
12
  import type { AtomView } from "./model.svelte.js";
13
13
  import { lingerFor } from "./model.svelte.js";
@@ -23,10 +23,11 @@
23
23
 
24
24
  let graph = $state<AtomGraph>();
25
25
 
26
+ const lingering = (view: AtomView) =>
27
+ view.removedAt !== undefined &&
28
+ performance.now() - view.removedAt < lingerFor;
26
29
  const shown = (view: AtomView) =>
27
- (showPlumbing || !view.plumbing) &&
28
- (view.live ||
29
- (view.removedAt !== undefined && performance.now() - view.removedAt < lingerFor));
30
+ (showPlumbing || !view.plumbing) && (view.live || lingering(view));
30
31
 
31
32
  /** Why the registry holds an atom nothing reads. */
32
33
  const heldBecause = (view: AtomView) => {
@@ -52,10 +53,16 @@
52
53
  const state = stateText(view.state);
53
54
  let value = view.hasValue ? preview(view.value, 26) : "";
54
55
  // A failure shows what it failed with, by name: its fields are on its sheet.
55
- if (AsyncResult.isAsyncResult(view.value) && AsyncResult.isFailure(view.value)) {
56
+ if (
57
+ AsyncResult.isAsyncResult(view.value) &&
58
+ AsyncResult.isFailure(view.value)
59
+ ) {
56
60
  value = failureText(view.value.cause);
57
61
  }
58
- const withValue = state === "" || view.state._tag === "Success" || view.state._tag === "Failure";
62
+ const withValue =
63
+ state === "" ||
64
+ view.state._tag === "Success" ||
65
+ view.state._tag === "Failure";
59
66
  const parts = [state, withValue ? value : ""];
60
67
  if (view.readers === 0 && view.children.length === 0) {
61
68
  parts.push(heldBecause(view));
@@ -83,16 +90,16 @@
83
90
  return found;
84
91
  };
85
92
  return {
86
- atoms: visible.map(
87
- (view): GraphAtom => ({
88
- id: view.id,
89
- label: view.name,
90
- note: note(view),
91
- read: view.readers > 0,
92
- status: statusOf(view),
93
- })
93
+ atoms: visible.map((view): GraphAtom => ({
94
+ id: view.id,
95
+ label: view.name,
96
+ note: note(view),
97
+ read: view.readers > 0,
98
+ status: statusOf(view),
99
+ })),
100
+ links: visible.flatMap((view) =>
101
+ [...parentsOf(view)].map((from) => ({ from, to: view.id }))
94
102
  ),
95
- links: visible.flatMap((view) => [...parentsOf(view)].map((from) => ({ from, to: view.id }))),
96
103
  };
97
104
  });
98
105
 
@@ -41,14 +41,11 @@ const setLabel = (atom, text, at, kind) => {
41
41
  if (!free && !(previous !== undefined && replaces[kind].includes(previous))) {
42
42
  return;
43
43
  }
44
- try {
45
- // The second element is a stack frame, as Effect's own labels hold.
46
- atom.label = [text, `at ${text} (${at})`];
44
+ // The second element is a stack frame, as Effect's own labels hold. A frozen atom keeps the
45
+ // label it has.
46
+ if (Reflect.set(atom, "label", [text, `at ${text} (${at})`])) {
47
47
  kinds.set(atom, kind);
48
48
  }
49
- catch {
50
- // A frozen atom keeps the label it has.
51
- }
52
49
  };
53
50
  /** A family member's argument, short enough for a label. */
54
51
  const formatArg = (arg) => {
@@ -91,9 +88,26 @@ export const keepAcrossReloads = (atom, key, source, inRegistries = registries)
91
88
  }
92
89
  const release = registry.mount(atom);
93
90
  registry.set(atom, node.value());
91
+ // oxlint-disable-next-line effecttsgo/global-timers -- runs in the app's page, outside any Effect program
94
92
  setTimeout(release, holdFor);
95
93
  }
96
94
  };
95
+ // A function the plugin wrapped can take anything and return anything: `label` and `call` only
96
+ // pass its arguments through and look at what it returns.
97
+ const isFunction = (value) => typeof value === "function";
98
+ const isObjectLike = (value) => typeof value === "object" && value !== null;
99
+ // The key a form definition from `Form.make` carries (effect-atom-svelte's `Form.TypeId`).
100
+ const formTypeId = "~effect-atom-svelte/Form";
101
+ /** A form definition that `Form.make` was given no name for. */
102
+ const isUnnamedForm = (value) => {
103
+ if (!isObjectLike(value) || !(formTypeId in value && "definition" in value)) {
104
+ return false;
105
+ }
106
+ const { definition } = value;
107
+ return (isObjectLike(definition) &&
108
+ "name" in definition &&
109
+ definition.name === undefined);
110
+ };
97
111
  /**
98
112
  * Labels `value` with `text` and the place it was declared, `at` (`/src/lib/todos.ts:12:14`), if
99
113
  * it is an atom, and returns it. For an `Atom.family`, returns a family that labels each member
@@ -101,20 +115,27 @@ export const keepAcrossReloads = (atom, key, source, inRegistries = registries)
101
115
  */
102
116
  export const label = (value, text, at, options = {}) => {
103
117
  if (Atom.isAtom(value)) {
104
- setLabel(value, text, at, options.local ? "local" : "declaration");
118
+ setLabel(value, text, at, options.local === true ? "local" : "declaration");
105
119
  if (options.keep !== undefined) {
106
120
  keepAcrossReloads(value, `${at.replace(/:\d+:\d+$/u, "")}#${text}`, options.keep);
107
121
  }
108
122
  }
109
- else if (options.family && typeof value === "function") {
110
- const members = value;
111
- return ((arg) => {
112
- const member = members(arg);
123
+ else if (isUnnamedForm(value)) {
124
+ // A form from effect-atom-svelte's Form.make: its instances label their atoms with its name.
125
+ value.definition.name = text;
126
+ }
127
+ else if (options.family === true && isFunction(value)) {
128
+ const labelled = (arg) => {
129
+ const member = value(arg);
113
130
  if (Atom.isAtom(member)) {
114
131
  setLabel(member, `${text}(${formatArg(arg)})`, at, "family");
115
132
  }
116
133
  return member;
117
- });
134
+ };
135
+ // SAFETY: `value` is an `Atom.family`, a function of one argument; `labelled` takes the same
136
+ // argument and returns the same member, so it stands in for it.
137
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a wrapper can't be typed as the generic it wraps
138
+ return labelled;
118
139
  }
119
140
  return value;
120
141
  };
@@ -124,16 +145,18 @@ export const label = (value, text, at, options = {}) => {
124
145
  * two atoms made for equal keys get the same name; an atom returned again keeps the name it has.
125
146
  */
126
147
  export const call = (f, name, at) => {
127
- if (typeof f !== "function") {
148
+ if (!isFunction(f)) {
128
149
  // Calling it fails as the code would have without the plugin.
129
150
  return f;
130
151
  }
131
- const factory = f;
132
- return ((...args) => {
133
- const result = factory(...args);
152
+ const labelled = (...args) => {
153
+ const result = f(...args);
134
154
  if (Atom.isAtom(result)) {
135
155
  setLabel(result, `${name}(${args.map(formatArg).join(", ")})`, at, "call");
136
156
  }
137
157
  return result;
138
- });
158
+ };
159
+ // SAFETY: `f` is a function; `labelled` takes the same arguments and returns what `f` does.
160
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a wrapper can't be typed as the generic it wraps
161
+ return labelled;
139
162
  };
@@ -25,7 +25,7 @@ const causeText = (cause, nameOf) => {
25
25
  case "ParentChanged": {
26
26
  return `${cause.parents.map(nameOf).join(", ")} changed`;
27
27
  }
28
- default: {
28
+ case "Invalidated": {
29
29
  return "invalidated";
30
30
  }
31
31
  }
@@ -70,7 +70,9 @@ export class Model {
70
70
  entry.hasValue = true;
71
71
  }
72
72
  }
73
- const unsubscribe = this.#inspector.subscribe((event) => this.#receive(event));
73
+ const unsubscribe = this.#inspector.subscribe((event) => {
74
+ this.#receive(event);
75
+ });
74
76
  this.#schedule();
75
77
  return () => {
76
78
  unsubscribe();
@@ -170,13 +172,17 @@ export class Model {
170
172
  detail = `${event.finalizers} ${event.finalizers === 1 ? "finalizer" : "finalizers"} ran`;
171
173
  break;
172
174
  }
173
- default: {
175
+ case "NodeRemoved": {
174
176
  entry.node = undefined;
175
177
  entry.removedAt = event.time;
176
178
  detail = "removed";
177
179
  // Again once it has lingered, to take it off the graph.
178
- setTimeout(() => this.#schedule(), lingerFor + 50);
180
+ // oxlint-disable-next-line effecttsgo/global-timers -- the panel's UI scheduling, outside any Effect program
181
+ setTimeout(() => {
182
+ this.#schedule();
183
+ }, lingerFor + 50);
179
184
  this.#prune();
185
+ break;
180
186
  }
181
187
  }
182
188
  this.#seq += 1;
@@ -212,6 +218,34 @@ export class Model {
212
218
  this.#publish();
213
219
  });
214
220
  }
221
+ #view(entry, plumbing, state) {
222
+ const { node } = entry;
223
+ return {
224
+ atom: entry.atom,
225
+ builds: entry.builds,
226
+ children: node === undefined
227
+ ? []
228
+ : [...node.children].map((child) => this.#entry(child.atom).id),
229
+ hasValue: entry.hasValue,
230
+ id: entry.id,
231
+ identity: entry.identity,
232
+ idleTTL: this.#inspector.idleTTL(entry.atom),
233
+ interruptedAt: entry.interruptedAt,
234
+ interruptions: entry.interruptions,
235
+ keepAlive: entry.atom.keepAlive,
236
+ live: node !== undefined,
237
+ name: this.#name(entry),
238
+ parents: node === undefined
239
+ ? []
240
+ : [...node.parents].map((parent) => this.#entry(parent.atom).id),
241
+ plumbing,
242
+ readers: node?.listeners.size ?? 0,
243
+ removedAt: entry.removedAt,
244
+ state,
245
+ updates: entry.updates,
246
+ value: entry.value,
247
+ };
248
+ }
215
249
  #publish() {
216
250
  const now = performance.now();
217
251
  const views = [];
@@ -242,31 +276,7 @@ export class Model {
242
276
  const stateKey = state._tag === "Value" ? "Value" : state._tag;
243
277
  states[stateKey] = (states[stateKey] ?? 0) + 1;
244
278
  }
245
- views.push({
246
- atom: entry.atom,
247
- builds: entry.builds,
248
- children: node === undefined
249
- ? []
250
- : [...node.children].map((child) => this.#entry(child.atom).id),
251
- hasValue: entry.hasValue,
252
- id: entry.id,
253
- identity: entry.identity,
254
- idleTTL: this.#inspector.idleTTL(entry.atom),
255
- interruptedAt: entry.interruptedAt,
256
- interruptions: entry.interruptions,
257
- keepAlive: entry.atom.keepAlive,
258
- live: node !== undefined,
259
- name: this.#name(entry),
260
- parents: node === undefined
261
- ? []
262
- : [...node.parents].map((parent) => this.#entry(parent.atom).id),
263
- plumbing: isPlumbing,
264
- readers: node?.listeners.size ?? 0,
265
- removedAt: entry.removedAt,
266
- state,
267
- updates: entry.updates,
268
- value: entry.value,
269
- });
279
+ views.push(this.#view(entry, isPlumbing, state));
270
280
  }
271
281
  this.atoms = views;
272
282
  this.totals = {
@@ -55,6 +55,7 @@ export const shortPlace = (place) => `${place.file.split("/").at(-1) ?? place.fi
55
55
  * relative to the project's root or a full one: `/src/a.ts` becomes `src/a.ts`, and
56
56
  * `/@fs/home/me/a.ts` or `/@fs/C:/a.ts` the full path after `/@fs`.
57
57
  */
58
+ // oxlint-disable-next-line effecttsgo/async-function -- a click handler in the panel, outside any Effect program
58
59
  export const openInEditor = async (place) => {
59
60
  const full = place.file.startsWith("/@fs/")
60
61
  ? place.file.slice("/@fs".length)
@@ -63,8 +64,10 @@ export const openInEditor = async (place) => {
63
64
  if (full !== undefined) {
64
65
  file = /^\/[a-z]:\//iu.test(full) ? full.slice(1) : full;
65
66
  }
67
+ const target = encodeURIComponent(`${file}:${place.line}:${place.column}`);
66
68
  try {
67
- await fetch(`/__open-in-editor?file=${encodeURIComponent(`${file}:${place.line}:${place.column}`)}`);
69
+ // oxlint-disable-next-line effecttsgo/global-fetch -- one request to the Vite dev server, from the panel, outside any Effect program
70
+ await fetch(`/__open-in-editor?file=${target}`);
68
71
  }
69
72
  catch {
70
73
  // Not a Vite dev server, or it isn't running: there is no editor to open.
@@ -4,7 +4,11 @@
4
4
  -->
5
5
  <script module lang="ts">
6
6
  /** Where the launcher sits. */
7
- export type Corner = "bottom-right" | "bottom-left" | "top-right" | "top-left";
7
+ export type Corner =
8
+ | "bottom-right"
9
+ | "bottom-left"
10
+ | "top-right"
11
+ | "top-left";
8
12
  </script>
9
13
 
10
14
  <script lang="ts">
@@ -35,7 +39,9 @@
35
39
  shortcut = $bindable(),
36
40
  }: Props = $props();
37
41
 
38
- const mac = typeof navigator !== "undefined" && /Mac|iPhone|iPad/u.test(navigator.platform);
42
+ const mac =
43
+ typeof navigator !== "undefined" &&
44
+ /Mac|iPhone|iPad/u.test(navigator.platform);
39
45
  const shown = $derived.by(() => {
40
46
  const parsed = parseShortcut(shortcut);
41
47
  return parsed === undefined ? "none" : formatShortcut(parsed, mac);
@@ -74,15 +80,29 @@
74
80
  <div class="row">
75
81
  <span class="key" id="devtools-shortcut">Shortcut</span>
76
82
  <div class="value">
77
- <kbd aria-labelledby="devtools-shortcut">{recording ? "Press a shortcut…" : shown}</kbd>
78
- <button aria-pressed={recording} class="tool" onclick={() => (recording = !recording)} type="button">
83
+ <kbd aria-labelledby="devtools-shortcut"
84
+ >{recording ? "Press a shortcut…" : shown}</kbd
85
+ >
86
+ <button
87
+ aria-pressed={recording}
88
+ class="tool"
89
+ onclick={() => (recording = !recording)}
90
+ type="button"
91
+ >
79
92
  {recording ? "Cancel" : "Change"}
80
93
  </button>
81
- <button class="tool" disabled={shortcut === defaultShortcut} onclick={() => (shortcut = defaultShortcut)} type="button">
94
+ <button
95
+ class="tool"
96
+ disabled={shortcut === defaultShortcut}
97
+ onclick={() => (shortcut = defaultShortcut)}
98
+ type="button"
99
+ >
82
100
  Reset
83
101
  </button>
84
102
  <p class="note">
85
- Opens and closes the panel anywhere on the page. It needs Ctrl, Alt or {mac ? "⌘" : "Meta"} (or a function key), so it can't catch typing.
103
+ Opens and closes the panel anywhere on the page. It needs Ctrl, Alt or {mac
104
+ ? "⌘"
105
+ : "Meta"} (or a function key), so it can't catch typing.
86
106
  </p>
87
107
  </div>
88
108
  </div>
@@ -91,7 +111,12 @@
91
111
  <div class="value">
92
112
  <div aria-labelledby="devtools-corner" class="corners" role="group">
93
113
  {#each corners as item (item.id)}
94
- <button aria-pressed={corner === item.id} class="tool" onclick={() => (corner = item.id)} type="button">
114
+ <button
115
+ aria-pressed={corner === item.id}
116
+ class="tool"
117
+ onclick={() => (corner = item.id)}
118
+ type="button"
119
+ >
95
120
  {item.label}
96
121
  </button>
97
122
  {/each}
@@ -104,7 +129,9 @@
104
129
  <span class="value">
105
130
  <input bind:value={opacity} max="1" min="0.2" step="0.05" type="range" />
106
131
  <output>{Math.round(opacity * 100)}%</output>
107
- <span class="note">The button is opaque again while you point at it or focus it.</span>
132
+ <span class="note"
133
+ >The button is opaque again while you point at it or focus it.</span
134
+ >
108
135
  </span>
109
136
  </label>
110
137
  <label class="row">