@evobug_com/safe-ts-skill 0.0.0-stage → 0.5.1

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.
@@ -0,0 +1,713 @@
1
+ # Pattern catalogue: Vue
2
+
3
+ Vue components and composables, before and after. The blocks follow the convention of
4
+ [patterns-core.md](patterns-core.md): ` ```vue bad <rules> ` is the code before with the rules
5
+ `safe-ts check` reports (none listed: the checker is silent), ` ```vue good ` / ` ```ts good `
6
+ the target. Examples import `fetchUser(id, signal)` and friends from `./api`: request functions
7
+ that return `Promise<Result<T, ApiError>>`, as in [patterns-core.md](patterns-core.md#requests-return-a-result).
8
+ Blocks marked `no-tsc` import `pinia`, which the SAFE-TS repository doesn't install: the checker
9
+ reads them, tsc doesn't.
10
+
11
+ Vue guide pages: Async state, State and props, Values that may be missing, Errors in handlers,
12
+ Cleanup, Security, Setup.
13
+
14
+ ## Contents
15
+
16
+ - [A loading, error, data trio](#a-loading-error-data-trio)
17
+ - [A ref filled after mount](#a-ref-filled-after-mount)
18
+ - [A refresh that blanks the list](#a-refresh-that-blanks-the-list)
19
+ - [A submit with a busy flag and an error message](#a-submit-with-a-busy-flag-and-an-error-message)
20
+ - [Showing an enum in a template](#showing-an-enum-in-a-template)
21
+ - [A template ref](#a-template-ref)
22
+ - [Module state](#module-state)
23
+ - [A store action that throws](#a-store-action-that-throws)
24
+ - [A prop changed by the child](#a-prop-changed-by-the-child)
25
+ - [v-html and bound URLs](#v-html-and-bound-urls)
26
+ - [A Result returned to Vue](#a-result-returned-to-vue)
27
+ - [A listener on window](#a-listener-on-window)
28
+ - [Typed props in defineComponent](#typed-props-in-definecomponent)
29
+
30
+ ## A loading, error, data trio
31
+
32
+ `loading`, `error` and `data` refs can disagree, and an older response can overwrite a newer one.
33
+ `useTask` keeps one `AsyncState` (`Idle`, `Loading`, `Ready` with `value`, `Failed` with
34
+ `error`), aborts the previous run when a new one starts, and aborts when the component
35
+ unmounts. In a component, `vue-split-state` reports the refs written around an `await` (a lone
36
+ `loading` flag too, and an `error = ref('')` set after one), and `vue-async-race` the missing
37
+ latest-wins check. The census counts the flags and error refs everywhere, stores and
38
+ composables included (`loading-flag`, `error-state`, `trio-files`).
39
+
40
+ ```vue bad vue-async-race vue-split-state
41
+ <script setup lang="ts">
42
+ import { ref, watch } from "vue";
43
+ import { isErr } from "@evobug_com/safe-ts-std/result";
44
+ import { fetchUser, type User } from "./api";
45
+
46
+ const props = defineProps<{ id: string }>();
47
+ const loading = ref(false);
48
+ const failed = ref("");
49
+ const user = ref<User>();
50
+
51
+ watch(() => props.id, async (id) => {
52
+ loading.value = true;
53
+ const result = await fetchUser(id);
54
+ loading.value = false;
55
+ if (isErr(result)) failed.value = result.error.message;
56
+ else user.value = result;
57
+ }, { immediate: true });
58
+ </script>
59
+
60
+ <template>
61
+ <p v-if="loading">Loading…</p>
62
+ <p v-else-if="failed !== ''">{{ failed }}</p>
63
+ <p v-else-if="user">{{ user.name }}</p>
64
+ </template>
65
+ ```
66
+
67
+ ```vue good
68
+ <script setup lang="ts">
69
+ import { watch } from "vue";
70
+ import { Match } from "@evobug_com/safe-ts-vue/match";
71
+ import { useTask } from "@evobug_com/safe-ts-vue/task";
72
+ import { fetchUser } from "./api";
73
+
74
+ const props = defineProps<{ id: string }>();
75
+ const { state, run } = useTask((signal, id: string) => fetchUser(id, signal));
76
+
77
+ watch(() => props.id, (id) => run(id), { immediate: true });
78
+ </script>
79
+
80
+ <template>
81
+ <Match :value="state">
82
+ <template #Loading>Loading…</template>
83
+ <template #Ready="{ value }">{{ value.name }}</template>
84
+ <template #Failed="{ error }">Couldn't load the user: {{ error.message }}</template>
85
+ <template #_></template>
86
+ </Match>
87
+ </template>
88
+ ```
89
+
90
+ - `run` resolves when the run is over; it rejects only when the work threw instead of returning
91
+ an `Err` (a bug). Returned from a `watch` callback, a hook or a template handler, Vue reports
92
+ that rejection to `app.config.errorHandler`.
93
+ - The work's `Err` becomes `Failed`. A throw does not: the state goes back to `Idle`, and the
94
+ task's `panic` holds what was thrown (a std `Panic`) until the next run or `reset()`. Give
95
+ `Idle` a slot (or `#_`) that reads `panic` and says something went wrong, so a bug doesn't
96
+ leave a blank area.
97
+ - `abort()` stops a run in progress; `reset()` goes back to `Idle` from `Ready`, `Failed` or a
98
+ run in progress, and clears `panic`. Use `reset()` to dismiss an answer or an error.
99
+ - The work takes the task's `signal` and passes it to the request; with the idiomatic layer on,
100
+ `unused-task-signal` reports a task that never reads it while calling something that could
101
+ take it (a navigation, which takes none, isn't reported).
102
+ - Write `<Match :value="...">`. The older `:on` still works at runtime but fails vue-tsc
103
+ (TS2345: Vue reads a prop named `on…` as an event listener).
104
+
105
+ ## A ref filled after mount
106
+
107
+ `ref<T>()` loaded in `onMounted` starts as `undefined`, so the template has to cope with it, and a
108
+ failure has nowhere to go (`vue-ref-without-value`).
109
+
110
+ ```vue bad vue-ref-without-value
111
+ <script setup lang="ts">
112
+ import { onMounted, shallowRef } from "vue";
113
+ import { isErr } from "@evobug_com/safe-ts-std/result";
114
+ import { fetchOrders, type Order } from "./api";
115
+
116
+ const orders = shallowRef<readonly Order[]>();
117
+
118
+ onMounted(async () => {
119
+ const result = await fetchOrders();
120
+ if (!isErr(result)) orders.value = result;
121
+ });
122
+ </script>
123
+
124
+ <template>
125
+ <p v-if="orders">{{ orders.length }} orders</p>
126
+ </template>
127
+ ```
128
+
129
+ ```vue good
130
+ <script setup lang="ts">
131
+ import { onMounted } from "vue";
132
+ import { Match } from "@evobug_com/safe-ts-vue/match";
133
+ import { useTask } from "@evobug_com/safe-ts-vue/task";
134
+ import { fetchOrders } from "./api";
135
+
136
+ const { state, run } = useTask((signal) => fetchOrders(signal));
137
+
138
+ onMounted(() => run());
139
+ </script>
140
+
141
+ <template>
142
+ <Match :value="state">
143
+ <template #Ready="{ value }">{{ value.length }} orders</template>
144
+ <template #Failed="{ error }">Couldn't load the orders: {{ error.message }}</template>
145
+ <template #_>Loading…</template>
146
+ </Match>
147
+ </template>
148
+ ```
149
+
150
+ Start a load in `onMounted` when the work reads template refs (`useElement`): setup runs before
151
+ the elements exist. That includes a `load` function passed to a child component that starts
152
+ it from its own setup. `vue-template-ref` reports a function that reads a `useElement` before
153
+ its first `await` and is called during setup, run by an immediate watcher (also through
154
+ `useTask`'s `run`), or passed as a prop.
155
+
156
+ ## A refresh that blanks the list
157
+
158
+ `run()` sets `Loading`, which carries no value: a list shown only in `#Ready` disappears while it
159
+ reloads, and a page that refreshes after each edit flickers or loses its scroll position. Where
160
+ the old list must stay on screen, keep the last answer next to the task.
161
+
162
+ ```vue good
163
+ <script setup lang="ts">
164
+ import { onMounted, shallowRef, watch } from "vue";
165
+ import { variant } from "@evobug_com/safe-ts-std/enum";
166
+ import { Match } from "@evobug_com/safe-ts-vue/match";
167
+ import { AsyncState } from "@evobug_com/safe-ts-vue/state";
168
+ import { useTask } from "@evobug_com/safe-ts-vue/task";
169
+ import { fetchOrders, type Order } from "./api";
170
+
171
+ const { state, run } = useTask((signal) => fetchOrders(signal));
172
+ // The last list loaded, kept on screen while a refresh runs.
173
+ const shown = shallowRef<readonly Order[]>([]);
174
+ watch(state, (now) => {
175
+ const ready = variant(now, AsyncState.Ready);
176
+ if (ready !== undefined) shown.value = ready.value;
177
+ });
178
+
179
+ onMounted(() => run());
180
+ </script>
181
+
182
+ <template>
183
+ <Match :value="state">
184
+ <template #Loading>Refreshing…</template>
185
+ <template #Failed>Couldn't refresh the orders.</template>
186
+ <template #_></template>
187
+ </Match>
188
+ <ul>
189
+ <li v-for="order in shown" :key="order.id">{{ order.total }}</li>
190
+ </ul>
191
+ </template>
192
+ ```
193
+
194
+ ## A submit with a busy flag and an error message
195
+
196
+ A `saving` flag and an `error = ref('')` around an `await` are the trio again, written for an
197
+ action, and `vue-split-state` reports them (a lone flag set around an `await` too). The task's
198
+ state says whether it is running and why it failed, and the typed input stays where it is when
199
+ the server refuses it.
200
+
201
+ ```vue bad vue-split-state
202
+ <script setup lang="ts">
203
+ import { ref } from "vue";
204
+ import { isErr } from "@evobug_com/safe-ts-std/result";
205
+ import { saveDraft } from "./api";
206
+
207
+ const text = ref("");
208
+ const saving = ref(false);
209
+ const error = ref("");
210
+
211
+ async function save(): Promise<void> {
212
+ saving.value = true;
213
+ const saved = await saveDraft(text.value);
214
+ saving.value = false;
215
+ error.value = isErr(saved) ? saved.error.message : "";
216
+ }
217
+ </script>
218
+
219
+ <template>
220
+ <textarea v-model="text" />
221
+ <button :disabled="saving" @click="save">Save</button>
222
+ <p v-if="error !== ''">{{ error }}</p>
223
+ </template>
224
+ ```
225
+
226
+ ```vue good
227
+ <script setup lang="ts">
228
+ import { ref } from "vue";
229
+ import { is } from "@evobug_com/safe-ts-std/enum";
230
+ import { Match } from "@evobug_com/safe-ts-vue/match";
231
+ import { AsyncState } from "@evobug_com/safe-ts-vue/state";
232
+ import { useTask } from "@evobug_com/safe-ts-vue/task";
233
+ import { saveDraft } from "./api";
234
+
235
+ const text = ref("");
236
+ const { state: saving, run: save } = useTask((signal, draft: string) => saveDraft(draft, signal));
237
+ </script>
238
+
239
+ <template>
240
+ <textarea v-model="text" />
241
+ <button :disabled="is(saving, AsyncState.Loading)" @click="save(text)">Save</button>
242
+ <Match :value="saving">
243
+ <template #Failed="{ error }">Couldn't save: {{ error.message }}</template>
244
+ <template #_></template>
245
+ </Match>
246
+ </template>
247
+ ```
248
+
249
+ A dialog that closed when its handler threw must stay open when the handler now returns an
250
+ `Err`: check what the caller does with the result before changing a handler's contract (see
251
+ [behaviour.md](behaviour.md)).
252
+
253
+ ## Showing an enum in a template
254
+
255
+ Three forms, all checked for exhaustiveness or explicitness:
256
+
257
+ - `<Match :value="value">` with one slot per variant (or `#_` last): checked by `vue-match`,
258
+ rewritten at build time into a `v-if` chain, and accepted by vue-tsc.
259
+ - `match(...)` in a `computed`, when every variant shows the same element with different text:
260
+ checked by TypeScript.
261
+ - A `v-if` / `v-else-if` chain of `is(state, AsyncState.Loading)` that names every variant,
262
+ without a final `v-else`: `vue-exhaustive-v-if` reports a chain that misses one, as it does
263
+ for a chain on `.tag` (which `prefer-is-over-tag` reports, with the idiomatic layer on).
264
+ One vue-tsc limit: inside an event handler of a `v-else-if` / `v-else` branch under `v-for`,
265
+ the row narrowed by `is` is `never`; give that branch its own `v-if` (Vue guide: Async state).
266
+
267
+ ```vue bad vue-exhaustive-v-if
268
+ <script setup lang="ts">
269
+ import { watch } from "vue";
270
+ import { is } from "@evobug_com/safe-ts-std/enum";
271
+ import { AsyncState } from "@evobug_com/safe-ts-vue/state";
272
+ import { useTask } from "@evobug_com/safe-ts-vue/task";
273
+ import { fetchUser } from "./api";
274
+
275
+ const props = defineProps<{ id: string }>();
276
+ const { state, run } = useTask((signal, id: string) => fetchUser(id, signal));
277
+
278
+ watch(() => props.id, (id) => run(id), { immediate: true });
279
+ </script>
280
+
281
+ <template>
282
+ <p v-if="is(state, AsyncState.Loading)">Loading…</p>
283
+ <p v-else-if="is(state, AsyncState.Ready)">{{ state.value.name }}</p>
284
+ </template>
285
+ ```
286
+
287
+ ```vue good
288
+ <script setup lang="ts">
289
+ import { watch } from "vue";
290
+ import { Match } from "@evobug_com/safe-ts-vue/match";
291
+ import { useTask } from "@evobug_com/safe-ts-vue/task";
292
+ import { fetchUser } from "./api";
293
+
294
+ const props = defineProps<{ id: string }>();
295
+ const { state, run } = useTask((signal, id: string) => fetchUser(id, signal));
296
+
297
+ watch(() => props.id, (id) => run(id), { immediate: true });
298
+ </script>
299
+
300
+ <template>
301
+ <Match :value="state">
302
+ <template #Idle></template>
303
+ <template #Loading>Loading…</template>
304
+ <template #Ready="{ value }">{{ value.name }}</template>
305
+ <template #Failed="{ error }">Couldn't load the user: {{ error.message }}</template>
306
+ </Match>
307
+ </template>
308
+ ```
309
+
310
+ When every variant shows the same element with different text, `match` in a `computed`:
311
+
312
+ ```vue good
313
+ <script setup lang="ts">
314
+ import { computed, watch } from "vue";
315
+ import { match } from "@evobug_com/safe-ts-std/enum";
316
+ import { useTask } from "@evobug_com/safe-ts-vue/task";
317
+ import { fetchUser } from "./api";
318
+
319
+ const props = defineProps<{ id: string }>();
320
+ const { state, run } = useTask((signal, id: string) => fetchUser(id, signal));
321
+
322
+ watch(() => props.id, (id) => run(id), { immediate: true });
323
+
324
+ const status = computed(() =>
325
+ match(state.value, {
326
+ Idle: () => "",
327
+ Loading: () => "Loading…",
328
+ Ready: ({ value }) => value.name,
329
+ Failed: ({ error }) => `Couldn't load the user: ${error.message}`,
330
+ }),
331
+ );
332
+ </script>
333
+
334
+ <template>
335
+ <p>{{ status }}</p>
336
+ </template>
337
+ ```
338
+
339
+ `<Match>` doesn't take an `Option` of an enum: put it under `v-if="value"` with a `v-else` for
340
+ the missing case.
341
+
342
+ ## A template ref
343
+
344
+ `ref<HTMLInputElement | null>(null)` (and `useTemplateRef`) is `null` until mount, and a `!`
345
+ hides the one case where that is real. `useElement` is typed without `null`, and the checker
346
+ proves the element is always rendered and read after mount (`vue-template-ref`). For an
347
+ element under `v-if`, `useOptionalElement` (`undefined` while missing); under `v-for`,
348
+ `useElements`.
349
+
350
+ ```vue bad no-null
351
+ <script setup lang="ts">
352
+ import { onMounted, ref } from "vue";
353
+
354
+ const input = ref<HTMLInputElement | null>(null);
355
+ onMounted(() => input.value?.focus());
356
+ </script>
357
+
358
+ <template>
359
+ <input ref="input" />
360
+ </template>
361
+ ```
362
+
363
+ ```vue good
364
+ <script setup lang="ts">
365
+ import { onMounted } from "vue";
366
+ import { useElement } from "@evobug_com/safe-ts-vue/element";
367
+
368
+ const input = useElement<HTMLInputElement>("input");
369
+ onMounted(() => input.value.focus());
370
+ </script>
371
+
372
+ <template>
373
+ <input ref="input" />
374
+ <button @click="input.select()">Select all</button>
375
+ </template>
376
+ ```
377
+
378
+ ## Module state
379
+
380
+ A `ref` or `let` at the top of a composable file (or a plain `<script>` block) is one value for
381
+ every component and every test (`no-mutable-global`). `<script setup>` is per instance, so state
382
+ there is fine. For state many components share, the target is a Pinia setup store, or a
383
+ `createX()` provided at startup and read with `injectRequired` (Vue guide: State and props). A
384
+ module-level object is the same once a function changes it, however it reaches it: destructured,
385
+ iterated, or handed back by a getter (`getConfig().x = 1`, across files too).
386
+
387
+ ```ts bad no-mutable-global
388
+ import { ref } from "vue";
389
+
390
+ const count = ref(0);
391
+
392
+ export function useCounter() {
393
+ const increment = (): void => {
394
+ count.value++;
395
+ };
396
+ return { count, increment };
397
+ }
398
+ ```
399
+
400
+ ```ts good no-tsc
401
+ import { defineStore } from "pinia";
402
+ import { ref } from "vue";
403
+
404
+ export const useCounterStore = defineStore("counter", () => {
405
+ const count = ref(0);
406
+ const increment = (): void => {
407
+ count.value++;
408
+ };
409
+ return { count, increment };
410
+ });
411
+ ```
412
+
413
+ - A store keeps the state; readers use `store.count` (or `storeToRefs(store)`), writers call its
414
+ functions. Destructuring the store copies the values (`vue-lost-reactivity`); a constant the
415
+ store returns (a `markRaw` router) is read as `store.router`.
416
+ - A counter used to keep only the newest answer (`let latest = 0`, compared after an `await`)
417
+ is what `useTask` does: called in a setup store, a task belongs to the store's effect scope
418
+ and is aborted when the store is disposed. With the idiomatic layer on, `latest-wins-counter`
419
+ reports the hand-written counter, at module level or in a store's setup function. Outside
420
+ Vue and React (a plain-DOM page, a worker), std's `latest(...)` (`@evobug_com/safe-ts-std/async`)
421
+ is the same without the state: each `run(...)` aborts the older run's `signal`, and an older
422
+ run resolves to `err(Superseded)`. Create it in the function that mounts the screen, with the
423
+ page's signal: a module-level one is one run in progress for every caller, and
424
+ `no-mutable-global` reports it.
425
+ - Readers outside components that imported the old module-level `ref` can read a module-level
426
+ `computed(() => useXStore().value)` bridge while they migrate (Vue guide: State and props).
427
+ - Two modules that must not import each other but need an event between them (a list that
428
+ refreshes when a thread is read elsewhere) share a small store: a counter the writer bumps
429
+ and the reader `watch`es. Don't rely on another store's `$onAction` hook: it stops firing
430
+ as soon as the call moves out of that store.
431
+
432
+ ```ts good no-tsc
433
+ import { defineStore } from "pinia";
434
+ import { useTask } from "@evobug_com/safe-ts-vue/task";
435
+ import { fetchOrders } from "./api";
436
+
437
+ export const useOrdersStore = defineStore("orders", () => {
438
+ const orders = useTask((signal) => fetchOrders(signal));
439
+ return { orders: orders.state, load: orders.run };
440
+ });
441
+ ```
442
+
443
+ ## A store action that throws
444
+
445
+ A store action that rejects (or throws "not hydrated") makes every caller wrap it. Return a
446
+ `Result` instead, and update every caller in the same change. The checker follows a `Result`
447
+ through Pinia setup stores and options stores' `actions`, so `must-use-result` reports a caller
448
+ that drops it (`await store.rename(x);`, `store.rename(x).catch(() => {})`), and
449
+ `catch-on-result` (idiomatic) a `try` left around it. It doesn't see a store reached through a
450
+ parameter or kept in a `ref`: search for each member's name too (`rg -n '\.rename\('`) and read
451
+ every site.
452
+
453
+ ```ts good no-tsc
454
+ import { defineStore } from "pinia";
455
+ import { ref } from "vue";
456
+ import type { Result } from "@evobug_com/safe-ts-std/result";
457
+ import { type ApiError, renameUser } from "./api";
458
+
459
+ export const useProfileStore = defineStore("profile", () => {
460
+ const name = ref("");
461
+ const rename = async (next: string): Promise<Result<void, ApiError>> => {
462
+ const renamed = await renameUser(next);
463
+ if (renamed === undefined) name.value = next;
464
+ return renamed;
465
+ };
466
+ return { name, rename };
467
+ });
468
+ ```
469
+
470
+ A caller that showed a server's message inline (a 422 refusal) must still show it: match on the
471
+ error kinds where the old code tested the HTTP library's error, not a generic toast. With the
472
+ idiomatic layer on, `misplaced-axios-check` reports an `isAxiosError(r.error)` left on a store
473
+ member that now has its own error type.
474
+
475
+ ## A prop changed by the child
476
+
477
+ Vue makes the props object read-only, not the objects inside it, so `props.user.email = ""`
478
+ changes the parent's data behind its back (`no-param-mutation`). Ask the parent with an event
479
+ or `defineModel()`. When the write was a deliberate sync of a store's own object, keep a local
480
+ `ref` for the control, send the change, and reload the store after the server answers. When the
481
+ child really owns one field of what it is given, say so in the prop's type,
482
+ `defineProps<{ draft: { text: Mut<Ref<string>> } }>()`: a `Mut<...>` field is the child's to
483
+ change, and the other fields stay borrowed.
484
+
485
+ ```vue bad no-param-mutation
486
+ <script setup lang="ts">
487
+ type User = { name: string; email: string };
488
+
489
+ const props = defineProps<{ user: User }>();
490
+
491
+ function clearEmail(): void {
492
+ props.user.email = "";
493
+ }
494
+ </script>
495
+
496
+ <template>
497
+ <input v-model="props.user.name" />
498
+ <button @click="clearEmail">Clear email</button>
499
+ </template>
500
+ ```
501
+
502
+ ```vue good
503
+ <script setup lang="ts">
504
+ const name = defineModel<string>("name", { required: true });
505
+ const emit = defineEmits<{ clearEmail: [] }>();
506
+ </script>
507
+
508
+ <template>
509
+ <input v-model="name" />
510
+ <button @click="emit('clearEmail')">Clear email</button>
511
+ </template>
512
+ ```
513
+
514
+ ## v-html and bound URLs
515
+
516
+ `v-html` inserts HTML as it is, and a bound `:href` takes `javascript:` URLs (`vue-v-html`,
517
+ `vue-unsafe-url`). Render text where you can; bind URLs through `safeHref`, which keeps
518
+ relative, `http:`, `https:`, `mailto:` and `tel:` URLs and gives `"#"` for anything else.
519
+ Another scheme the app needs goes in its options: `safeHref(url, { schemes: ["blob"] })`
520
+ (`javascript:`, `vbscript:` and `data:` stay refused even when listed). When it must be HTML,
521
+ sanitize it. Declare the project's sanitizer once with `defineSanitizer`
522
+ (`@evobug_com/safe-ts-vue/html`): what it returns is typed `Html`, so `v-html` accepts it in a
523
+ `computed`, a prop typed `Html` or either branch of a `?:`, and vue-tsc refuses a plain string
524
+ for that prop. `vue-v-html` also accepts DOMPurify, `sanitize-html` and `xss` called where it
525
+ can see them. The same goes for URLs: `safeHref` returns a `SafeUrl`, and a prop typed `SafeUrl`
526
+ needs no check in the child. `defineSanitizer` is where the project vouches for a function:
527
+ keep it in one module, and list it in the architecture document (guide: Proof types).
528
+
529
+ ```vue bad vue-v-html vue-unsafe-url
530
+ <script setup lang="ts">
531
+ type Comment = { readonly author: string; readonly website: string; readonly body: string };
532
+
533
+ const props = defineProps<{ comment: Comment }>();
534
+ </script>
535
+
536
+ <template>
537
+ <a :href="props.comment.website">{{ props.comment.author }}</a>
538
+ <div v-html="props.comment.body"></div>
539
+ </template>
540
+ ```
541
+
542
+ ```vue good
543
+ <script setup lang="ts">
544
+ import { safeHref } from "@evobug_com/safe-ts-vue/url";
545
+
546
+ type Comment = { readonly author: string; readonly website: string; readonly body: string };
547
+
548
+ const props = defineProps<{ comment: Comment }>();
549
+ </script>
550
+
551
+ <template>
552
+ <a :href="safeHref(props.comment.website)">{{ props.comment.author }}</a>
553
+ <p>{{ props.comment.body }}</p>
554
+ </template>
555
+ ```
556
+
557
+ A binding whose branches are each a checked URL or no URL is accepted too:
558
+ `ok ? safeHref(url) : undefined`, `safeHref(url) || undefined`, `ok && safeHref(url)`. A
559
+ written-out URL that `safeHref` would refuse (`safeHref('flow://watch')` without its scheme in
560
+ `schemes`) is reported: the link would always be `#`.
561
+
562
+ ## A Result returned to Vue
563
+
564
+ Vue drops what a handler returns, so `@click="publish"` with a `Result` loses the error
565
+ (`must-use-result`). The component's state is one `Enum` that names every state, the first
566
+ included (`Editing`, `Rejected` with a named error, `Published`), and `<Match>` shows each: no
567
+ `""` for "no problem", no message built in the handler, and not an `Option` of the error,
568
+ whose `undefined` would mean both "not tried yet" and "published".
569
+
570
+ ```vue bad must-use-result
571
+ <script setup lang="ts">
572
+ import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
573
+ import { err, type Result } from "@evobug_com/safe-ts-std/result";
574
+
575
+ type PublishError = Enum<{ Empty: {}; TooLong: { max: number } }>;
576
+ const PublishError = constructors<PublishError>();
577
+
578
+ const props = defineProps<{ draft: string }>();
579
+
580
+ function publish(): Result<void, PublishError> {
581
+ if (props.draft === "") return err(PublishError.Empty());
582
+ if (props.draft.length > 280) return err(PublishError.TooLong({ max: 280 }));
583
+ return undefined;
584
+ }
585
+ </script>
586
+
587
+ <template>
588
+ <button @click="publish">Publish</button>
589
+ </template>
590
+ ```
591
+
592
+ ```vue good
593
+ <script setup lang="ts">
594
+ import { shallowRef } from "vue";
595
+ import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
596
+ import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
597
+ import { Match } from "@evobug_com/safe-ts-vue/match";
598
+
599
+ type PublishError = Enum<{ Empty: {}; TooLong: { max: number } }>;
600
+ const PublishError = constructors<PublishError>();
601
+
602
+ type Publishing = Enum<{ Editing: {}; Rejected: { error: PublishError }; Published: {} }>;
603
+ const Publishing = constructors<Publishing>();
604
+
605
+ const props = defineProps<{ draft: string }>();
606
+ const emit = defineEmits<{ publish: [text: string] }>();
607
+ const state = shallowRef<Publishing>(Publishing.Editing());
608
+
609
+ function publish(): Result<void, PublishError> {
610
+ if (props.draft === "") return err(PublishError.Empty());
611
+ if (props.draft.length > 280) return err(PublishError.TooLong({ max: 280 }));
612
+ emit("publish", props.draft);
613
+ return undefined;
614
+ }
615
+
616
+ function onPublish(): void {
617
+ const published = publish();
618
+ state.value = isErr(published) ? Publishing.Rejected({ error: published.error }) : Publishing.Published();
619
+ }
620
+ </script>
621
+
622
+ <template>
623
+ <Match :value="state">
624
+ <template #Editing>
625
+ <button @click="onPublish">Publish</button>
626
+ </template>
627
+ <template #Rejected="{ error }">
628
+ <button @click="onPublish">Publish</button>
629
+ <Match :value="error">
630
+ <template #Empty>Write something first.</template>
631
+ <template #TooLong="{ max }">Keep it under {{ max }} characters.</template>
632
+ </Match>
633
+ </template>
634
+ <template #Published>Published.</template>
635
+ </Match>
636
+ </template>
637
+ ```
638
+
639
+ ## A listener on window
640
+
641
+ A listener or interval started by a component keeps running after it unmounts
642
+ (`listener-cleanup`). `useListener` and `useInterval` stop with the component.
643
+
644
+ ```vue bad listener-cleanup
645
+ <script setup lang="ts">
646
+ import { onMounted, ref } from "vue";
647
+
648
+ const width = ref(0);
649
+
650
+ function measure(): void {
651
+ width.value = window.innerWidth;
652
+ }
653
+
654
+ onMounted(() => {
655
+ window.addEventListener("resize", measure);
656
+ });
657
+ </script>
658
+
659
+ <template>
660
+ <p>{{ width }}px</p>
661
+ </template>
662
+ ```
663
+
664
+ ```vue good
665
+ <script setup lang="ts">
666
+ import { ref } from "vue";
667
+ import { useListener } from "@evobug_com/safe-ts-vue/listen";
668
+
669
+ const width = ref(window.innerWidth);
670
+
671
+ function measure(): void {
672
+ width.value = window.innerWidth;
673
+ }
674
+
675
+ useListener(window, "resize", measure);
676
+ </script>
677
+
678
+ <template>
679
+ <p>{{ width }}px</p>
680
+ </template>
681
+ ```
682
+
683
+ ## Typed props in defineComponent
684
+
685
+ Vue's documented way to type an options-object prop is a cast (`String as PropType<...>`,
686
+ `no-unchecked-cast`). `prop` and `oneOf` build the same declaration with the type attached.
687
+
688
+ ```ts bad no-unchecked-cast
689
+ import { defineComponent, h, type PropType } from "vue";
690
+
691
+ export const Panel = defineComponent({
692
+ props: {
693
+ side: { type: String as PropType<"left" | "right">, default: "left" },
694
+ },
695
+ setup(props) {
696
+ return () => h("aside", { class: props.side });
697
+ },
698
+ });
699
+ ```
700
+
701
+ ```ts good
702
+ import { defineComponent, h } from "vue";
703
+ import { oneOf } from "@evobug_com/safe-ts-vue/prop";
704
+
705
+ export const Panel = defineComponent({
706
+ props: {
707
+ side: oneOf(["left", "right"], { default: "left" }),
708
+ },
709
+ setup(props) {
710
+ return () => h("aside", { class: props.side });
711
+ },
712
+ });
713
+ ```