@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.
- package/LICENSE-APACHE +201 -0
- package/LICENSE-MIT +21 -0
- package/README.md +15 -2
- package/install.mjs +86 -0
- package/package.json +35 -4
- package/safe-ts-migrate/SKILL.md +178 -0
- package/safe-ts-migrate/references/architecture.md +146 -0
- package/safe-ts-migrate/references/behaviour.md +86 -0
- package/safe-ts-migrate/references/census.md +136 -0
- package/safe-ts-migrate/references/escape-hatches.md +72 -0
- package/safe-ts-migrate/references/final-pass.md +46 -0
- package/safe-ts-migrate/references/fix-the-design.md +87 -0
- package/safe-ts-migrate/references/order-and-gates.md +101 -0
- package/safe-ts-migrate/references/patterns-core.md +2229 -0
- package/safe-ts-migrate/references/patterns-react.md +266 -0
- package/safe-ts-migrate/references/patterns-vue.md +713 -0
- package/safe-ts-migrate/references/review-checklist.md +70 -0
- package/safe-ts-migrate/references/templates.md +260 -0
- package/safe-ts-migrate/references/tool-gaps.md +394 -0
- package/safe-ts-migrate/scripts/census.mjs +870 -0
- package/safe-ts-migrate/scripts/safe-ts.mjs +79 -0
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
# Pattern catalogue: React
|
|
2
|
+
|
|
3
|
+
React components and hooks, before and after, in the convention of
|
|
4
|
+
[patterns-core.md](patterns-core.md): ` ```tsx bad <rules> ` is the code before with the rules
|
|
5
|
+
`safe-ts check` reports (none listed: the checker is silent), ` ```tsx good ` the target.
|
|
6
|
+
Examples import `fetchUser(id, signal)` from `./api`: a request function that returns
|
|
7
|
+
`Promise<Result<User, ApiError>>`, as in [patterns-core.md](patterns-core.md#requests-return-a-result).
|
|
8
|
+
|
|
9
|
+
SAFE-TS leaves the rules of hooks, effect dependencies and in-place state changes to
|
|
10
|
+
eslint-plugin-react-hooks, and JSX keys to your linter. React guide pages: Async state, State
|
|
11
|
+
and props, Errors in handlers, Cleanup, Security, Setup.
|
|
12
|
+
|
|
13
|
+
## Contents
|
|
14
|
+
|
|
15
|
+
- [A loading, error, data trio](#a-loading-error-data-trio)
|
|
16
|
+
- [An effect that loads without cleanup](#an-effect-that-loads-without-cleanup)
|
|
17
|
+
- [Module state](#module-state)
|
|
18
|
+
- [A prop changed by the child](#a-prop-changed-by-the-child)
|
|
19
|
+
- [A Result returned to React](#a-result-returned-to-react)
|
|
20
|
+
- [HTML from outside](#html-from-outside)
|
|
21
|
+
|
|
22
|
+
## A loading, error, data trio
|
|
23
|
+
|
|
24
|
+
`loading`, `error` and `data` states set from an effect can disagree, and an older response can
|
|
25
|
+
overwrite a newer one. `useTask` from `@evobug_com/safe-ts-react/task` keeps one `AsyncState`,
|
|
26
|
+
aborts the previous run (its `signal` fires) when a new one starts, and aborts the run in
|
|
27
|
+
progress on unmount. `run` is the same function on every render, so it goes in the effect's
|
|
28
|
+
dependencies.
|
|
29
|
+
|
|
30
|
+
```tsx bad react-async-race react-split-state
|
|
31
|
+
import { useEffect, useState } from "react";
|
|
32
|
+
import { isErr } from "@evobug_com/safe-ts-std/result";
|
|
33
|
+
import { fetchUser, type User } from "./api";
|
|
34
|
+
|
|
35
|
+
export function Profile({ id }: { id: string }) {
|
|
36
|
+
const [loading, setLoading] = useState(false);
|
|
37
|
+
const [failed, setFailed] = useState("");
|
|
38
|
+
const [user, setUser] = useState<User>();
|
|
39
|
+
|
|
40
|
+
useEffect(() => {
|
|
41
|
+
const load = async (): Promise<void> => {
|
|
42
|
+
setLoading(true);
|
|
43
|
+
const result = await fetchUser(id);
|
|
44
|
+
setLoading(false);
|
|
45
|
+
if (isErr(result)) setFailed(result.error.message);
|
|
46
|
+
else setUser(result);
|
|
47
|
+
};
|
|
48
|
+
void load();
|
|
49
|
+
}, [id]);
|
|
50
|
+
|
|
51
|
+
if (loading) return <p>Loading…</p>;
|
|
52
|
+
if (failed !== "") return <p>{failed}</p>;
|
|
53
|
+
return <p>{user?.name}</p>;
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
```tsx good
|
|
58
|
+
import { useEffect } from "react";
|
|
59
|
+
import { Match } from "@evobug_com/safe-ts-react/match";
|
|
60
|
+
import { useTask } from "@evobug_com/safe-ts-react/task";
|
|
61
|
+
import { fetchUser } from "./api";
|
|
62
|
+
|
|
63
|
+
export function Profile({ id }: { id: string }) {
|
|
64
|
+
const { state, run } = useTask((signal, id: string) => fetchUser(id, signal));
|
|
65
|
+
|
|
66
|
+
useEffect(() => {
|
|
67
|
+
run(id).catch((reason: unknown) => console.error(reason));
|
|
68
|
+
}, [id, run]);
|
|
69
|
+
|
|
70
|
+
return (
|
|
71
|
+
<Match
|
|
72
|
+
on={state}
|
|
73
|
+
Loading={() => <p>Loading…</p>}
|
|
74
|
+
Ready={({ value }) => <p>{value.name}</p>}
|
|
75
|
+
Failed={({ error }) => <p>Couldn't load the user: {error.message}</p>}
|
|
76
|
+
_={() => undefined}
|
|
77
|
+
/>
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
- `run(id)` rejects only when the work threw instead of returning an `Err`: a bug, which
|
|
83
|
+
`useTask` doesn't turn into `Failed`. Log it, as above.
|
|
84
|
+
- `<Match>` takes a function per variant; without `_`, a missing variant is a type error. When
|
|
85
|
+
every variant renders the same element, compute it with `match` from
|
|
86
|
+
`@evobug_com/safe-ts-std/enum` instead.
|
|
87
|
+
|
|
88
|
+
## An effect that loads without cleanup
|
|
89
|
+
|
|
90
|
+
Where `useTask` doesn't fit, an effect that loads must stop the run it no longer needs: return a
|
|
91
|
+
cleanup that aborts the request.
|
|
92
|
+
|
|
93
|
+
```tsx good
|
|
94
|
+
import { useEffect, useState } from "react";
|
|
95
|
+
import { isErr } from "@evobug_com/safe-ts-std/result";
|
|
96
|
+
import { fetchUser, type User } from "./api";
|
|
97
|
+
|
|
98
|
+
export function Name({ id }: { id: string }) {
|
|
99
|
+
const [user, setUser] = useState<User>();
|
|
100
|
+
|
|
101
|
+
useEffect(() => {
|
|
102
|
+
const controller = new AbortController();
|
|
103
|
+
const load = async (): Promise<void> => {
|
|
104
|
+
const result = await fetchUser(id, controller.signal);
|
|
105
|
+
if (!controller.signal.aborted && !isErr(result)) setUser(result);
|
|
106
|
+
};
|
|
107
|
+
void load();
|
|
108
|
+
return () => controller.abort();
|
|
109
|
+
}, [id]);
|
|
110
|
+
|
|
111
|
+
return <p>{user?.name ?? "…"}</p>;
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Module state
|
|
116
|
+
|
|
117
|
+
A `let` at the top of a file is one value for every instance, every test and (with server
|
|
118
|
+
rendering) every request (`no-mutable-global`). Keep it in the component, in a common parent, or
|
|
119
|
+
in a context whose provider creates it. A module-level object is the same once a function changes
|
|
120
|
+
it, however it reaches it: destructured, iterated, or handed back by a getter (`getConfig().x = 1`,
|
|
121
|
+
across files too).
|
|
122
|
+
|
|
123
|
+
```tsx bad no-mutable-global
|
|
124
|
+
let clicks = 0;
|
|
125
|
+
|
|
126
|
+
export function Counter() {
|
|
127
|
+
return <button onClick={() => { clicks += 1; }}>Clicked</button>;
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
```tsx good
|
|
132
|
+
import { useState } from "react";
|
|
133
|
+
|
|
134
|
+
export function Counter() {
|
|
135
|
+
const [clicks, setClicks] = useState(0);
|
|
136
|
+
return <button onClick={() => setClicks((n) => n + 1)}>Clicked {clicks} times</button>;
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## A prop changed by the child
|
|
141
|
+
|
|
142
|
+
Props are the parent's data; changing an object reached through them changes it without telling
|
|
143
|
+
React (`no-param-mutation`). Ask the parent with a callback.
|
|
144
|
+
|
|
145
|
+
```tsx bad no-param-mutation
|
|
146
|
+
type Todo = { title: string; done: boolean };
|
|
147
|
+
|
|
148
|
+
export function TodoItem({ todo }: { todo: Todo }) {
|
|
149
|
+
return (
|
|
150
|
+
<label>
|
|
151
|
+
<input type="checkbox" checked={todo.done} onChange={() => { todo.done = !todo.done; }} />
|
|
152
|
+
{todo.title}
|
|
153
|
+
</label>
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
```tsx good
|
|
159
|
+
type Todo = { readonly title: string; readonly done: boolean };
|
|
160
|
+
|
|
161
|
+
export function TodoItem({ todo, onToggle }: { todo: Todo; onToggle: () => void }) {
|
|
162
|
+
return (
|
|
163
|
+
<label>
|
|
164
|
+
<input type="checkbox" checked={todo.done} onChange={onToggle} />
|
|
165
|
+
{todo.title}
|
|
166
|
+
</label>
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## A Result returned to React
|
|
172
|
+
|
|
173
|
+
React drops what a handler returns, so `onClick={archive}` with a `Result` loses the error
|
|
174
|
+
(`must-use-result`). The component's state is one `Enum` that names every state, the first
|
|
175
|
+
included (`Ready`, `Refused` with a named error, `Archived`), and `<Match>` shows each: no `""`
|
|
176
|
+
for "no problem", no message built in the handler, and not an `Option` of the error, whose
|
|
177
|
+
`undefined` would mean both "not tried yet" and "archived".
|
|
178
|
+
|
|
179
|
+
```tsx bad must-use-result
|
|
180
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
181
|
+
import { err, type Result } from "@evobug_com/safe-ts-std/result";
|
|
182
|
+
|
|
183
|
+
type ArchiveError = Enum<{ NotDraft: {}; Locked: { by: string } }>;
|
|
184
|
+
const ArchiveError = constructors<ArchiveError>();
|
|
185
|
+
|
|
186
|
+
function archive(): Result<void, ArchiveError> {
|
|
187
|
+
return err(ArchiveError.Locked({ by: "Ada" }));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export function Toolbar() {
|
|
191
|
+
return <button onClick={archive}>Archive</button>;
|
|
192
|
+
}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
```tsx good
|
|
196
|
+
import { useState } from "react";
|
|
197
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
198
|
+
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
|
|
199
|
+
import { Match } from "@evobug_com/safe-ts-react/match";
|
|
200
|
+
|
|
201
|
+
type ArchiveError = Enum<{ NotDraft: {}; Locked: { by: string } }>;
|
|
202
|
+
const ArchiveError = constructors<ArchiveError>();
|
|
203
|
+
|
|
204
|
+
type Archiving = Enum<{ Ready: {}; Refused: { error: ArchiveError }; Archived: {} }>;
|
|
205
|
+
const Archiving = constructors<Archiving>();
|
|
206
|
+
|
|
207
|
+
function archive(): Result<void, ArchiveError> {
|
|
208
|
+
return err(ArchiveError.Locked({ by: "Ada" }));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function Toolbar() {
|
|
212
|
+
const [state, setState] = useState<Archiving>(Archiving.Ready());
|
|
213
|
+
const onArchive = (): void => {
|
|
214
|
+
const archived = archive();
|
|
215
|
+
setState(isErr(archived) ? Archiving.Refused({ error: archived.error }) : Archiving.Archived());
|
|
216
|
+
};
|
|
217
|
+
const button = <button onClick={onArchive}>Archive</button>;
|
|
218
|
+
return (
|
|
219
|
+
<Match
|
|
220
|
+
on={state}
|
|
221
|
+
Ready={() => button}
|
|
222
|
+
Refused={({ error }) => (
|
|
223
|
+
<>
|
|
224
|
+
{button}
|
|
225
|
+
<Match
|
|
226
|
+
on={error}
|
|
227
|
+
NotDraft={() => <p>Only drafts can be archived.</p>}
|
|
228
|
+
Locked={({ by }) => <p>{by} is editing it.</p>}
|
|
229
|
+
/>
|
|
230
|
+
</>
|
|
231
|
+
)}
|
|
232
|
+
Archived={() => <p>Archived.</p>}
|
|
233
|
+
/>
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
## HTML from outside
|
|
239
|
+
|
|
240
|
+
`dangerouslySetInnerHTML` with text from a user or the network can run script
|
|
241
|
+
(`react-dangerous-html`). Render text; when it must be HTML, go through the project's one
|
|
242
|
+
sanitizer, declared with `defineSanitizer` (`@evobug_com/safe-ts-std/html`): what it returns is
|
|
243
|
+
an `Html`, accepted by type. A known sanitizer called in the prop itself passes too.
|
|
244
|
+
React 19 neutralises `javascript:` URLs in `href`; on React 18, bind URLs from users through
|
|
245
|
+
`safeHref` from `@evobug_com/safe-ts-std/url`.
|
|
246
|
+
|
|
247
|
+
```tsx bad react-dangerous-html
|
|
248
|
+
type Comment = { readonly author: string; readonly body: string };
|
|
249
|
+
|
|
250
|
+
export function CommentView({ comment }: { comment: Comment }) {
|
|
251
|
+
return <div dangerouslySetInnerHTML={{ __html: comment.body }} />;
|
|
252
|
+
}
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
```tsx good
|
|
256
|
+
import { defineSanitizer } from "@evobug_com/safe-ts-std/html";
|
|
257
|
+
|
|
258
|
+
declare const DOMPurify: { sanitize(html: string): string };
|
|
259
|
+
|
|
260
|
+
const sanitizeHtml = defineSanitizer((raw) => DOMPurify.sanitize(raw));
|
|
261
|
+
|
|
262
|
+
export function Article({ html }: { html: string }) {
|
|
263
|
+
const clean = sanitizeHtml(html);
|
|
264
|
+
return <div dangerouslySetInnerHTML={{ __html: clean }} />;
|
|
265
|
+
}
|
|
266
|
+
```
|