keits 0.0.3 → 0.0.4
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/dist/dev/api.js +270 -0
- package/dist/dev/forms.js +328 -0
- package/dist/dev/index.js +8 -299
- package/dist/dev/router.js +3 -1
- package/dist/dev/shared/computed-3UO-KiH1.js +40 -0
- package/dist/dev/shared/{element-C4DfKtZW.js → element-CQPqagu1.js} +5 -38
- package/dist/dev/shared/owner-Dmge21OW.js +62 -0
- package/dist/dev/shared/render-effect-kOGnLNbL.js +26 -0
- package/dist/dev/shared/resource-CbXVATvq.js +154 -0
- package/dist/dev/shared/signal-BOXkY-Iv.js +24 -0
- package/dist/dev/shared/store-BzUN1qE5.js +148 -0
- package/dist/dev/svg.js +1 -1
- package/dist/prod/api.js +210 -0
- package/dist/prod/forms.js +237 -0
- package/dist/prod/index.js +107 -316
- package/dist/prod/router.js +24 -22
- package/dist/prod/shared/computed-CAPpOLCY.js +33 -0
- package/dist/prod/shared/element-DGyQ01Vs.js +164 -0
- package/dist/prod/shared/owner-6BFHIPR9.js +59 -0
- package/dist/prod/shared/render-effect-DjaUT3Cn.js +23 -0
- package/dist/prod/shared/resource-CNC2DBO3.js +109 -0
- package/dist/prod/shared/signal-DGrl3r9T.js +16 -0
- package/dist/prod/shared/store-Dcscpk_h.js +109 -0
- package/dist/prod/svg.js +1 -1
- package/dist/types/api/cache.d.ts +16 -0
- package/dist/types/api/client.d.ts +42 -0
- package/dist/types/api/error.d.ts +16 -0
- package/dist/types/api/index.d.ts +3 -0
- package/dist/types/api/url.d.ts +5 -0
- package/dist/types/forms/form.d.ts +55 -0
- package/dist/types/forms/index.d.ts +2 -0
- package/dist/types/forms/paths.d.ts +6 -0
- package/dist/types/forms/types.d.ts +38 -0
- package/package.json +16 -2
- package/dist/dev/shared/owner-DlUsXKXE.js +0 -122
- package/dist/prod/shared/element-DUtXb3px.js +0 -187
- package/dist/prod/shared/owner-DgJNPM0P.js +0 -104
package/dist/dev/api.js
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { t as resource } from "./shared/resource-CbXVATvq.js";
|
|
2
|
+
import { i as onCleanup } from "./shared/owner-Dmge21OW.js";
|
|
3
|
+
// src/api/url.ts
|
|
4
|
+
function buildPath(path, params, query) {
|
|
5
|
+
const filled = path.replace(/:([A-Za-z0-9_]+)/g, (_, name) => {
|
|
6
|
+
const value = params?.[name];
|
|
7
|
+
if (value === void 0) throw new Error(`[keits/api] Missing param "${name}" for "${path}".`);
|
|
8
|
+
return encodeURIComponent(String(value));
|
|
9
|
+
});
|
|
10
|
+
if (query === void 0) return filled;
|
|
11
|
+
const search = new URLSearchParams();
|
|
12
|
+
for (const [key, value] of Object.entries(query)) {
|
|
13
|
+
if (value === null || value === void 0) continue;
|
|
14
|
+
if (Array.isArray(value)) for (const item of value) search.append(key, String(item));
|
|
15
|
+
else search.append(key, String(value));
|
|
16
|
+
}
|
|
17
|
+
const text = search.toString();
|
|
18
|
+
return text === "" ? filled : `${filled}${filled.includes("?") ? "&" : "?"}${text}`;
|
|
19
|
+
}
|
|
20
|
+
function underPrefix(url, prefix) {
|
|
21
|
+
if (!url.startsWith(prefix)) return false;
|
|
22
|
+
const next = url.charAt(prefix.length);
|
|
23
|
+
return next === "" || next === "/" || next === "?" || prefix.endsWith("/");
|
|
24
|
+
}
|
|
25
|
+
// src/api/cache.ts
|
|
26
|
+
function createQueryCache(load, staleTime, maxEntries = 100) {
|
|
27
|
+
const entries = /* @__PURE__ */ new Map();
|
|
28
|
+
const watchers = /* @__PURE__ */ new Set();
|
|
29
|
+
const entryFor = (url) => {
|
|
30
|
+
let entry = entries.get(url);
|
|
31
|
+
if (entry === void 0) {
|
|
32
|
+
entry = {
|
|
33
|
+
data: void 0,
|
|
34
|
+
hasData: false,
|
|
35
|
+
fetchedAt: 0,
|
|
36
|
+
promise: null,
|
|
37
|
+
generation: 0
|
|
38
|
+
};
|
|
39
|
+
entries.set(url, entry);
|
|
40
|
+
evict();
|
|
41
|
+
}
|
|
42
|
+
return entry;
|
|
43
|
+
};
|
|
44
|
+
const evict = () => {
|
|
45
|
+
if (entries.size <= maxEntries) return;
|
|
46
|
+
const shown = new Set([...watchers].map((watcher) => watcher.url));
|
|
47
|
+
for (const [url, entry] of entries) {
|
|
48
|
+
if (entries.size <= maxEntries) return;
|
|
49
|
+
if (!shown.has(url) && entry.promise === null) entries.delete(url);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
return {
|
|
53
|
+
peek(url) {
|
|
54
|
+
const entry = entries.get(url);
|
|
55
|
+
if (entry === void 0 || !entry.hasData) return null;
|
|
56
|
+
return {
|
|
57
|
+
data: entry.data,
|
|
58
|
+
stale: Date.now() - entry.fetchedAt >= staleTime
|
|
59
|
+
};
|
|
60
|
+
},
|
|
61
|
+
fetch(url) {
|
|
62
|
+
const entry = entryFor(url);
|
|
63
|
+
if (entry.promise !== null) return entry.promise;
|
|
64
|
+
const generation = entry.generation;
|
|
65
|
+
const promise = load(url).then((data) => {
|
|
66
|
+
if (entry.promise === promise) entry.promise = null;
|
|
67
|
+
if (entry.generation !== generation) return data;
|
|
68
|
+
entry.data = data;
|
|
69
|
+
entry.hasData = true;
|
|
70
|
+
entry.fetchedAt = Date.now();
|
|
71
|
+
for (const watcher of watchers) if (watcher.url === url) watcher.push(data);
|
|
72
|
+
return data;
|
|
73
|
+
}, (error) => {
|
|
74
|
+
if (entry.promise === promise) entry.promise = null;
|
|
75
|
+
throw error;
|
|
76
|
+
});
|
|
77
|
+
entry.promise = promise;
|
|
78
|
+
return promise;
|
|
79
|
+
},
|
|
80
|
+
watch(watcher) {
|
|
81
|
+
watchers.add(watcher);
|
|
82
|
+
return () => watchers.delete(watcher);
|
|
83
|
+
},
|
|
84
|
+
async invalidate(prefix) {
|
|
85
|
+
for (const [url, entry] of entries) {
|
|
86
|
+
if (!underPrefix(url, prefix)) continue;
|
|
87
|
+
entry.fetchedAt = 0;
|
|
88
|
+
entry.generation++;
|
|
89
|
+
entry.promise = null;
|
|
90
|
+
}
|
|
91
|
+
const shown = [...watchers].filter((watcher) => watcher.url !== null && underPrefix(watcher.url, prefix));
|
|
92
|
+
await Promise.all(shown.map((watcher) => watcher.refetch()));
|
|
93
|
+
},
|
|
94
|
+
clear() {
|
|
95
|
+
entries.clear();
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
// src/api/error.ts
|
|
100
|
+
var ApiError = class extends Error {
|
|
101
|
+
name = "ApiError";
|
|
102
|
+
status;
|
|
103
|
+
body;
|
|
104
|
+
method;
|
|
105
|
+
url;
|
|
106
|
+
constructor(init) {
|
|
107
|
+
super(init.message, init.cause === void 0 ? void 0 : { cause: init.cause });
|
|
108
|
+
this.status = init.status;
|
|
109
|
+
this.body = init.body;
|
|
110
|
+
this.method = init.method;
|
|
111
|
+
this.url = init.url;
|
|
112
|
+
}
|
|
113
|
+
get timedOut() {
|
|
114
|
+
return this.status === 0 && this.cause?.name === "TimeoutError";
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
// src/api/client.ts
|
|
118
|
+
function createApi(config = {}) {
|
|
119
|
+
const base = (config.baseUrl ?? "").replace(/\/+$/, "");
|
|
120
|
+
let refreshing = null;
|
|
121
|
+
const refreshOnce = () => refreshing ??= Promise.resolve().then(() => config.refresh()).then(Boolean, () => false).finally(() => {
|
|
122
|
+
refreshing = null;
|
|
123
|
+
});
|
|
124
|
+
async function send(method, path, options, retried = false) {
|
|
125
|
+
const url = base + path;
|
|
126
|
+
const headers = new Headers({ Accept: "application/json" });
|
|
127
|
+
const shared = typeof config.headers === "function" ? await config.headers() : config.headers;
|
|
128
|
+
for (const extra of [shared, options.headers]) if (extra !== void 0) new Headers(extra).forEach((value, key) => headers.set(key, value));
|
|
129
|
+
let body = null;
|
|
130
|
+
if (options.body !== void 0) {
|
|
131
|
+
if (isRawBody(options.body)) body = options.body;
|
|
132
|
+
else {
|
|
133
|
+
body = JSON.stringify(options.body);
|
|
134
|
+
if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json");
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const timeout = options.timeout ?? config.timeout;
|
|
138
|
+
const { signal, done } = withTimeout(options.signal, timeout);
|
|
139
|
+
const init = {
|
|
140
|
+
method,
|
|
141
|
+
headers,
|
|
142
|
+
body,
|
|
143
|
+
signal
|
|
144
|
+
};
|
|
145
|
+
if (config.credentials !== void 0) init.credentials = config.credentials;
|
|
146
|
+
let response;
|
|
147
|
+
let data;
|
|
148
|
+
try {
|
|
149
|
+
response = await (config.fetch ?? fetch)(url, init);
|
|
150
|
+
if (response.status === 401 && config.refresh !== void 0 && !retried) {
|
|
151
|
+
done();
|
|
152
|
+
if (await refreshOnce()) return send(method, path, options, true);
|
|
153
|
+
}
|
|
154
|
+
data = await readBody(response, method);
|
|
155
|
+
} catch (error) {
|
|
156
|
+
done();
|
|
157
|
+
if (options.signal?.aborted) throw error;
|
|
158
|
+
const cause = signal?.aborted ? signal.reason : error;
|
|
159
|
+
throw new ApiError({
|
|
160
|
+
status: 0,
|
|
161
|
+
body: void 0,
|
|
162
|
+
method,
|
|
163
|
+
url,
|
|
164
|
+
message: `${method} ${url} ${cause?.name === "TimeoutError" ? `timed out after ${timeout} ms` : "got no response"}`,
|
|
165
|
+
cause
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
done();
|
|
169
|
+
if (!response.ok) throw new ApiError({
|
|
170
|
+
status: response.status,
|
|
171
|
+
body: data,
|
|
172
|
+
method,
|
|
173
|
+
url,
|
|
174
|
+
message: `${method} ${url} failed with ${response.status}`
|
|
175
|
+
});
|
|
176
|
+
return options.parse ? options.parse(data) : data;
|
|
177
|
+
}
|
|
178
|
+
const request = async (method, path, options = {}) => {
|
|
179
|
+
const data = await send(method.toUpperCase(), buildPath(path, options.params, options.query), options);
|
|
180
|
+
if (options.invalidate !== void 0) {
|
|
181
|
+
const prefixes = typeof options.invalidate === "string" ? [options.invalidate] : options.invalidate;
|
|
182
|
+
await Promise.all(prefixes.map((prefix) => cache.invalidate(prefix)));
|
|
183
|
+
}
|
|
184
|
+
return data;
|
|
185
|
+
};
|
|
186
|
+
const cache = createQueryCache((path) => send("GET", path, {}), config.staleTime ?? 0);
|
|
187
|
+
return {
|
|
188
|
+
get: (path, options) => request("GET", path, options),
|
|
189
|
+
post: (path, options) => request("POST", path, options),
|
|
190
|
+
put: (path, options) => request("PUT", path, options),
|
|
191
|
+
patch: (path, options) => request("PATCH", path, options),
|
|
192
|
+
delete: (path, options) => request("DELETE", path, options),
|
|
193
|
+
request,
|
|
194
|
+
query(path, options = {}) {
|
|
195
|
+
const parse = options.parse ?? ((data) => data);
|
|
196
|
+
let shownUrl = null;
|
|
197
|
+
const key = () => {
|
|
198
|
+
const params = typeof options.params === "function" ? options.params() : options.params;
|
|
199
|
+
const query = typeof options.query === "function" ? options.query() : options.query;
|
|
200
|
+
shownUrl = params === null || params === false || query === null || query === false ? null : buildPath(path, params, query);
|
|
201
|
+
return shownUrl;
|
|
202
|
+
};
|
|
203
|
+
const result = resource(key, (url, { refetching }) => {
|
|
204
|
+
const cached = refetching ? null : cache.peek(url);
|
|
205
|
+
if (cached === null) return cache.fetch(url).then(parse);
|
|
206
|
+
if (cached.stale) cache.fetch(url).catch(() => {});
|
|
207
|
+
return parse(cached.data);
|
|
208
|
+
});
|
|
209
|
+
const stop = cache.watch({
|
|
210
|
+
get url() {
|
|
211
|
+
return shownUrl;
|
|
212
|
+
},
|
|
213
|
+
push: (data) => result.mutate(parse(data)),
|
|
214
|
+
refetch: () => result.refetch()
|
|
215
|
+
});
|
|
216
|
+
onCleanup(stop);
|
|
217
|
+
return result;
|
|
218
|
+
},
|
|
219
|
+
async prefetch(path, options = {}) {
|
|
220
|
+
const url = buildPath(path, options.params, options.query);
|
|
221
|
+
const cached = cache.peek(url);
|
|
222
|
+
if (cached === null || cached.stale) await cache.fetch(url).catch(() => {});
|
|
223
|
+
},
|
|
224
|
+
invalidate: (prefix = "") => cache.invalidate(prefix),
|
|
225
|
+
clear: () => cache.clear()
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
function isRawBody(body) {
|
|
229
|
+
if (typeof body === "string" || body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return true;
|
|
230
|
+
for (const name of [
|
|
231
|
+
"Blob",
|
|
232
|
+
"FormData",
|
|
233
|
+
"URLSearchParams",
|
|
234
|
+
"ReadableStream"
|
|
235
|
+
]) {
|
|
236
|
+
const type = globalThis[name];
|
|
237
|
+
if (typeof type === "function" && body instanceof type) return true;
|
|
238
|
+
}
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
async function readBody(response, method) {
|
|
242
|
+
if (method === "HEAD" || response.status === 204 || response.status === 205 || response.status === 304) return void 0;
|
|
243
|
+
const text = await response.text();
|
|
244
|
+
if (text === "") return void 0;
|
|
245
|
+
if (!(response.headers.get("Content-Type") ?? "").includes("json")) return text;
|
|
246
|
+
try {
|
|
247
|
+
return JSON.parse(text);
|
|
248
|
+
} catch {
|
|
249
|
+
return text;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
function withTimeout(outer, timeout) {
|
|
253
|
+
if (timeout === void 0) return {
|
|
254
|
+
signal: outer ?? null,
|
|
255
|
+
done: () => {}
|
|
256
|
+
};
|
|
257
|
+
const controller = new AbortController();
|
|
258
|
+
const timer = setTimeout(() => controller.abort(new DOMException(`Timed out after ${timeout} ms`, "TimeoutError")), timeout);
|
|
259
|
+
const forward = () => controller.abort(outer.reason);
|
|
260
|
+
if (outer?.aborted) forward();
|
|
261
|
+
else outer?.addEventListener("abort", forward, { once: true });
|
|
262
|
+
return {
|
|
263
|
+
signal: controller.signal,
|
|
264
|
+
done: () => {
|
|
265
|
+
clearTimeout(timer);
|
|
266
|
+
outer?.removeEventListener("abort", forward);
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
export { ApiError, createApi };
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { t as computed } from "./shared/computed-3UO-KiH1.js";
|
|
2
|
+
import { h as untrack, i as batch } from "./shared/graph-D6-x_CWC.js";
|
|
3
|
+
import { t as signal } from "./shared/signal-BOXkY-Iv.js";
|
|
4
|
+
import { n as store, r as unwrap } from "./shared/store-BzUN1qE5.js";
|
|
5
|
+
// src/forms/paths.ts
|
|
6
|
+
function getAt(source, path) {
|
|
7
|
+
if (path === "") return source;
|
|
8
|
+
let current = source;
|
|
9
|
+
for (const key of path.split(".")) {
|
|
10
|
+
if (current === null || typeof current !== "object") return void 0;
|
|
11
|
+
current = current[key];
|
|
12
|
+
}
|
|
13
|
+
return current;
|
|
14
|
+
}
|
|
15
|
+
function setAt(target, path, value) {
|
|
16
|
+
const keys = path.split(".");
|
|
17
|
+
const last = keys.pop();
|
|
18
|
+
let current = target;
|
|
19
|
+
keys.forEach((key, i) => {
|
|
20
|
+
let next = current[key];
|
|
21
|
+
if (next === null || typeof next !== "object") {
|
|
22
|
+
next = /^\d+$/.test(keys[i + 1] ?? last) ? [] : {};
|
|
23
|
+
current[key] = next;
|
|
24
|
+
next = current[key];
|
|
25
|
+
}
|
|
26
|
+
current = next;
|
|
27
|
+
});
|
|
28
|
+
current[last] = value;
|
|
29
|
+
}
|
|
30
|
+
function deepEqual(a, b) {
|
|
31
|
+
if (Object.is(a, b)) return true;
|
|
32
|
+
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
|
|
33
|
+
if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
|
|
34
|
+
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
35
|
+
const keysA = Object.keys(a);
|
|
36
|
+
if (keysA.length !== Object.keys(b).length) return false;
|
|
37
|
+
return keysA.every((key) => deepEqual(a[key], b[key]));
|
|
38
|
+
}
|
|
39
|
+
function within(path, parent) {
|
|
40
|
+
return parent === "" || path === parent || path.startsWith(`${parent}.`);
|
|
41
|
+
}
|
|
42
|
+
function remapKeys(record, list, move) {
|
|
43
|
+
const result = {};
|
|
44
|
+
const prefix = `${list}.`;
|
|
45
|
+
for (const [key, value] of Object.entries(record)) {
|
|
46
|
+
if (!key.startsWith(prefix)) {
|
|
47
|
+
result[key] = value;
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
const rest = key.slice(prefix.length);
|
|
51
|
+
const dot = rest.indexOf(".");
|
|
52
|
+
const next = move(Number(dot < 0 ? rest : rest.slice(0, dot)));
|
|
53
|
+
if (next >= 0) result[`${prefix}${next}${dot < 0 ? "" : rest.slice(dot)}`] = value;
|
|
54
|
+
}
|
|
55
|
+
return result;
|
|
56
|
+
}
|
|
57
|
+
function serverErrors(body) {
|
|
58
|
+
const found = {};
|
|
59
|
+
const add = (path, message) => {
|
|
60
|
+
const text = Array.isArray(message) ? message.find((m) => typeof m === "string") : message;
|
|
61
|
+
if (typeof text === "string" && !(path in found)) found[path] = text;
|
|
62
|
+
};
|
|
63
|
+
const walk = (value, prefix) => {
|
|
64
|
+
for (const [key, inner] of Object.entries(value)) {
|
|
65
|
+
const path = prefix === "" ? key : `${prefix}.${key}`;
|
|
66
|
+
if (inner !== null && typeof inner === "object" && !Array.isArray(inner)) walk(inner, path);
|
|
67
|
+
else add(path, inner);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
if (body === null || typeof body !== "object") return found;
|
|
71
|
+
const { errors, detail, message } = body;
|
|
72
|
+
if (Array.isArray(errors)) for (const item of errors) {
|
|
73
|
+
const path = item.path ?? item.field ?? item.name;
|
|
74
|
+
add(Array.isArray(path) ? path.join(".") : String(path ?? ""), item.message);
|
|
75
|
+
}
|
|
76
|
+
else if (errors !== null && typeof errors === "object") walk(errors, "");
|
|
77
|
+
if (Array.isArray(detail)) for (const item of detail) {
|
|
78
|
+
const loc = Array.isArray(item.loc) ? item.loc : [];
|
|
79
|
+
const start = loc[0] === "body" || loc[0] === "query" ? 1 : 0;
|
|
80
|
+
add(loc.slice(start).join("."), item.msg);
|
|
81
|
+
}
|
|
82
|
+
if (Object.keys(found).length === 0) add("", message);
|
|
83
|
+
return found;
|
|
84
|
+
}
|
|
85
|
+
// src/forms/form.ts
|
|
86
|
+
function form(options) {
|
|
87
|
+
const [values, setValues] = store(structuredClone(options.initial));
|
|
88
|
+
const [errors, setErrorStore] = store({});
|
|
89
|
+
const [server, setServer] = store({});
|
|
90
|
+
const [touchedPaths, setTouched] = store({});
|
|
91
|
+
const baseline = signal(structuredClone(options.initial), { equals: false });
|
|
92
|
+
const submitCount = signal(0);
|
|
93
|
+
const submitting = signal(false);
|
|
94
|
+
const validating = signal(false);
|
|
95
|
+
let checkId = 0;
|
|
96
|
+
const read = (value) => typeof value === "function" ? value() : value;
|
|
97
|
+
const snapshot = () => structuredClone(unwrap(values));
|
|
98
|
+
const runChecks = () => {
|
|
99
|
+
const current = snapshot();
|
|
100
|
+
const bySource = [
|
|
101
|
+
{},
|
|
102
|
+
{},
|
|
103
|
+
{}
|
|
104
|
+
];
|
|
105
|
+
const result = {
|
|
106
|
+
errors: {},
|
|
107
|
+
output: void 0
|
|
108
|
+
};
|
|
109
|
+
const waiting = [];
|
|
110
|
+
const later = (value, use) => {
|
|
111
|
+
if (isPromiseLike(value)) waiting.push(value.then(use));
|
|
112
|
+
else use(value);
|
|
113
|
+
};
|
|
114
|
+
for (const [path, check] of Object.entries(options.fields ?? {})) later(check(getAt(current, path), current), (message) => {
|
|
115
|
+
if (message) bySource[0][path] = message;
|
|
116
|
+
});
|
|
117
|
+
if (options.validate) later(options.validate(current), (found) => {
|
|
118
|
+
for (const [path, message] of Object.entries(found ?? {})) if (typeof message === "string") bySource[1][path] = message;
|
|
119
|
+
});
|
|
120
|
+
if (options.schema) later(options.schema["~standard"].validate(current), (outcome) => {
|
|
121
|
+
if (outcome.issues === void 0) result.output = outcome.value;
|
|
122
|
+
else for (const issue of outcome.issues) {
|
|
123
|
+
const path = (issue.path ?? []).map((part) => String(typeof part === "object" ? part.key : part)).join(".");
|
|
124
|
+
bySource[2][path] ??= issue.message;
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
const finish = () => {
|
|
128
|
+
for (const source of bySource) for (const [path, message] of Object.entries(source)) result.errors[path] ??= message;
|
|
129
|
+
return result;
|
|
130
|
+
};
|
|
131
|
+
return waiting.length === 0 ? finish() : Promise.all(waiting).then(finish);
|
|
132
|
+
};
|
|
133
|
+
const check = () => {
|
|
134
|
+
const id = ++checkId;
|
|
135
|
+
const apply = (checked) => {
|
|
136
|
+
if (id !== checkId) return checked;
|
|
137
|
+
batch(() => {
|
|
138
|
+
replaceAll(setErrorStore, checked.errors);
|
|
139
|
+
validating.set(false);
|
|
140
|
+
});
|
|
141
|
+
return checked;
|
|
142
|
+
};
|
|
143
|
+
const outcome = runChecks();
|
|
144
|
+
if (!isPromiseLike(outcome)) return apply(outcome);
|
|
145
|
+
validating.set(true);
|
|
146
|
+
return outcome.then(apply);
|
|
147
|
+
};
|
|
148
|
+
const changed = (path) => {
|
|
149
|
+
setServer((draft) => {
|
|
150
|
+
for (const key of Object.keys(draft)) if (within(key, path) || within(path, key)) delete draft[key];
|
|
151
|
+
});
|
|
152
|
+
check();
|
|
153
|
+
};
|
|
154
|
+
const set = (path, value) => batch(() => {
|
|
155
|
+
setValues((draft) => setAt(draft, path, value));
|
|
156
|
+
changed(path);
|
|
157
|
+
});
|
|
158
|
+
const touch = (path) => setTouched((draft) => void (draft[path] = true));
|
|
159
|
+
const changeList = (path, change, move) => batch(() => {
|
|
160
|
+
setValues((draft) => {
|
|
161
|
+
if (!Array.isArray(getAt(draft, path))) setAt(draft, path, []);
|
|
162
|
+
change(getAt(draft, path));
|
|
163
|
+
});
|
|
164
|
+
setTouched((draft) => replaceKeys(draft, {
|
|
165
|
+
...remapKeys(unwrap(draft), path, move),
|
|
166
|
+
[path]: true
|
|
167
|
+
}));
|
|
168
|
+
setServer((draft) => replaceKeys(draft, remapKeys(unwrap(draft), path, move)));
|
|
169
|
+
check();
|
|
170
|
+
});
|
|
171
|
+
const submitted = () => submitCount() > 0;
|
|
172
|
+
const shown = (path) => path === "" ? submitted() : touchedPaths[path] === true || submitted();
|
|
173
|
+
const valid = computed(() => Object.keys(errors).length === 0);
|
|
174
|
+
const dirtyAll = computed(() => !deepEqual(values, baseline()));
|
|
175
|
+
const result = {
|
|
176
|
+
values,
|
|
177
|
+
value: (path) => getAt(values, read(path)),
|
|
178
|
+
set: (path, value) => set(path, value),
|
|
179
|
+
update: (fn) => batch(() => {
|
|
180
|
+
setValues(fn);
|
|
181
|
+
changed("");
|
|
182
|
+
}),
|
|
183
|
+
bind(pathOrAccessor, bindOptions = {}) {
|
|
184
|
+
const path = () => read(pathOrAccessor);
|
|
185
|
+
const current = () => getAt(values, path());
|
|
186
|
+
const common = {
|
|
187
|
+
name: path,
|
|
188
|
+
onblur: () => touch(path()),
|
|
189
|
+
"aria-invalid": () => result.error(path()) ? "true" : void 0
|
|
190
|
+
};
|
|
191
|
+
const initial = untrack(current);
|
|
192
|
+
const choice = bindOptions.value;
|
|
193
|
+
if (choice !== void 0 && Array.isArray(initial)) return {
|
|
194
|
+
...common,
|
|
195
|
+
type: "checkbox",
|
|
196
|
+
value: () => choice,
|
|
197
|
+
checked: () => current().includes(choice),
|
|
198
|
+
onchange: (event) => {
|
|
199
|
+
const list = untrack(current).filter((item) => item !== choice);
|
|
200
|
+
set(path(), event.currentTarget.checked ? [...list, choice] : list);
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
if (choice !== void 0) return {
|
|
204
|
+
...common,
|
|
205
|
+
type: "radio",
|
|
206
|
+
value: () => choice,
|
|
207
|
+
checked: () => current() === choice,
|
|
208
|
+
onchange: () => set(path(), choice)
|
|
209
|
+
};
|
|
210
|
+
if (typeof initial === "boolean") return {
|
|
211
|
+
...common,
|
|
212
|
+
type: "checkbox",
|
|
213
|
+
checked: () => current() === true,
|
|
214
|
+
onchange: (event) => set(path(), event.currentTarget.checked)
|
|
215
|
+
};
|
|
216
|
+
if (typeof initial === "number") return {
|
|
217
|
+
...common,
|
|
218
|
+
value: () => {
|
|
219
|
+
const number = current();
|
|
220
|
+
return Number.isNaN(number) ? "" : String(number);
|
|
221
|
+
},
|
|
222
|
+
oninput: (event) => {
|
|
223
|
+
const text = event.currentTarget.value;
|
|
224
|
+
set(path(), text.trim() === "" ? NaN : Number(text));
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
return {
|
|
228
|
+
...common,
|
|
229
|
+
value: () => String(current() ?? ""),
|
|
230
|
+
oninput: (event) => set(path(), event.currentTarget.value)
|
|
231
|
+
};
|
|
232
|
+
},
|
|
233
|
+
error(path = "") {
|
|
234
|
+
const key = read(path);
|
|
235
|
+
return (shown(key) ? errors[key] : void 0) ?? server[key];
|
|
236
|
+
},
|
|
237
|
+
touched: (path) => touchedPaths[read(path)] === true,
|
|
238
|
+
touch: (path) => touch(path),
|
|
239
|
+
dirty: (path) => path === void 0 ? dirtyAll() : !deepEqual(getAt(values, read(path)), getAt(baseline(), read(path))),
|
|
240
|
+
valid: () => valid(),
|
|
241
|
+
validating: () => validating(),
|
|
242
|
+
submitting: () => submitting(),
|
|
243
|
+
submitted,
|
|
244
|
+
array(path) {
|
|
245
|
+
return {
|
|
246
|
+
items: () => getAt(values, path) ?? [],
|
|
247
|
+
add: (item, at) => changeList(path, (list) => at === void 0 ? list.push(item) : list.splice(at, 0, item), (index) => at === void 0 || index < at ? index : index + 1),
|
|
248
|
+
remove: (index) => changeList(path, (list) => list.splice(index, 1), (i) => i === index ? -1 : i > index ? i - 1 : i),
|
|
249
|
+
move: (from, to) => changeList(path, (list) => list.splice(to, 0, ...list.splice(from, 1)), (i) => i === from ? to : from < to ? i > from && i <= to ? i - 1 : i : i >= to && i < from ? i + 1 : i)
|
|
250
|
+
};
|
|
251
|
+
},
|
|
252
|
+
setErrors(input) {
|
|
253
|
+
let found;
|
|
254
|
+
if (isHttpError(input)) {
|
|
255
|
+
if (input.status !== 400 && input.status !== 422) return false;
|
|
256
|
+
found = serverErrors(input.body);
|
|
257
|
+
} else {
|
|
258
|
+
found = {};
|
|
259
|
+
for (const [path, message] of Object.entries(input)) if (typeof message === "string") found[path] = message;
|
|
260
|
+
}
|
|
261
|
+
if (Object.keys(found).length === 0) return false;
|
|
262
|
+
setServer((draft) => replaceKeys(draft, found));
|
|
263
|
+
return true;
|
|
264
|
+
},
|
|
265
|
+
submit(handler) {
|
|
266
|
+
return async (event) => {
|
|
267
|
+
event?.preventDefault();
|
|
268
|
+
if (untrack(submitting)) return false;
|
|
269
|
+
const formElement = event?.currentTarget instanceof Element ? event.currentTarget : null;
|
|
270
|
+
const focusFirstError = () => formElement?.querySelector("[aria-invalid=\"true\"]")?.focus();
|
|
271
|
+
batch(() => {
|
|
272
|
+
submitCount.set(untrack(submitCount) + 1);
|
|
273
|
+
submitting.set(true);
|
|
274
|
+
setServer((draft) => replaceKeys(draft, {}));
|
|
275
|
+
});
|
|
276
|
+
try {
|
|
277
|
+
const sent = snapshot();
|
|
278
|
+
const checked = await check();
|
|
279
|
+
if (Object.keys(checked.errors).length > 0) {
|
|
280
|
+
focusFirstError();
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
await handler(options.schema ? checked.output : sent);
|
|
284
|
+
baseline.set(() => sent);
|
|
285
|
+
return true;
|
|
286
|
+
} catch (error) {
|
|
287
|
+
if (result.setErrors(error)) {
|
|
288
|
+
focusFirstError();
|
|
289
|
+
return false;
|
|
290
|
+
}
|
|
291
|
+
throw error;
|
|
292
|
+
} finally {
|
|
293
|
+
submitting.set(false);
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
},
|
|
297
|
+
reset(next) {
|
|
298
|
+
const start = structuredClone(next ?? untrack(baseline));
|
|
299
|
+
batch(() => {
|
|
300
|
+
setValues((draft) => replaceKeys(draft, structuredClone(start)));
|
|
301
|
+
baseline.set(() => start);
|
|
302
|
+
setTouched((draft) => replaceKeys(draft, {}));
|
|
303
|
+
setServer((draft) => replaceKeys(draft, {}));
|
|
304
|
+
submitCount.set(0);
|
|
305
|
+
check();
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
check();
|
|
310
|
+
return result;
|
|
311
|
+
}
|
|
312
|
+
function replaceKeys(draft, next) {
|
|
313
|
+
for (const key of Object.keys(draft)) if (!(key in next)) delete draft[key];
|
|
314
|
+
Object.assign(draft, next);
|
|
315
|
+
}
|
|
316
|
+
function replaceAll(setStore, next) {
|
|
317
|
+
setStore((draft) => {
|
|
318
|
+
for (const key of Object.keys(draft)) if (!(key in next)) delete draft[key];
|
|
319
|
+
for (const [key, message] of Object.entries(next)) if (draft[key] !== message) draft[key] = message;
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
function isHttpError(value) {
|
|
323
|
+
return value !== null && typeof value === "object" && typeof value.status === "number" && "body" in value;
|
|
324
|
+
}
|
|
325
|
+
function isPromiseLike(value) {
|
|
326
|
+
return typeof value?.then === "function";
|
|
327
|
+
}
|
|
328
|
+
export { form };
|