@yu-packages/hooks 0.0.0-stage → 1.0.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.
- package/LICENSE +21 -0
- package/README.md +61 -2
- package/dist/chunk-HX3TDMPN.js +312 -0
- package/dist/chunk-HX3TDMPN.js.map +1 -0
- package/dist/chunk-ZGUB7DGM.js +153 -0
- package/dist/chunk-ZGUB7DGM.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/useCrud.d.ts +84 -0
- package/dist/useCrud.js +7 -0
- package/dist/useCrud.js.map +1 -0
- package/dist/useForm.d.ts +46 -0
- package/dist/useForm.js +9 -0
- package/dist/useForm.js.map +1 -0
- package/package.json +41 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021-present Archer
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,62 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @yu-packages/hooks
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
## useCrud
|
|
4
|
+
|
|
5
|
+
`useCrud` 是与 UI、请求库和业务模型无关的 Vue 3 CRUD 控制器。页面只负责把后端接口适配为 `CrudService`,表格、弹窗、确认提示、权限和表单校验留在应用层。
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { useCrud, type CrudService } from '@yu-packages/hooks'
|
|
9
|
+
|
|
10
|
+
type User = { id: number; name: string }
|
|
11
|
+
type UserQuery = { keyword?: string }
|
|
12
|
+
type CreateUser = Pick<User, 'name'>
|
|
13
|
+
type UpdateUser = Partial<CreateUser>
|
|
14
|
+
|
|
15
|
+
const service: CrudService<User, User, UserQuery, CreateUser, UpdateUser, number> = {
|
|
16
|
+
list: async (params, { signal }) => {
|
|
17
|
+
const result = await request.get('/users', { params, signal })
|
|
18
|
+
return { list: result.data.items, total: result.data.total }
|
|
19
|
+
},
|
|
20
|
+
detail: (id, { signal }) => request.get(`/users/${id}`, { signal }),
|
|
21
|
+
create: (input, { signal }) => request.post('/users', input, { signal }),
|
|
22
|
+
update: (id, input, { signal }) => request.put(`/users/${id}`, input, { signal }),
|
|
23
|
+
remove: (ids, { signal }) => request.delete('/users', { data: ids, signal })
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const { state, actions } = useCrud({
|
|
27
|
+
service,
|
|
28
|
+
initialQuery: { keyword: '' },
|
|
29
|
+
initialPageSize: 20
|
|
30
|
+
})
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
状态按职责分开:
|
|
34
|
+
|
|
35
|
+
- 列表:`items`、`total`、`page`、`pageSize`、`query`
|
|
36
|
+
- 详情:`current`、`currentKey`
|
|
37
|
+
- 选择:`selectedKeys`
|
|
38
|
+
- 请求状态:`listLoading`、`detailLoading`、`mutationLoading` 及对应错误
|
|
39
|
+
|
|
40
|
+
动作覆盖列表与详情读取、查询重置、分页、增改删、选择、取消请求和整体重置。增改删默认在成功后刷新列表,可通过 `{ refresh: false }` 关闭;删除最后一页数据时会自动回退到有效页码。
|
|
41
|
+
|
|
42
|
+
控制器会取消同类旧请求,并阻止不支持 `AbortSignal` 的请求库用过期响应覆盖新数据。它不包含表格列、表单 schema、弹窗状态、消息提示、权限、缓存或乐观更新,这些能力应由应用层按需组合。
|
|
43
|
+
|
|
44
|
+
## useForm
|
|
45
|
+
|
|
46
|
+
`useForm` 管理表单值、字段校验、错误、脏值、提交和重置,不负责渲染具体表单组件。
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { required, useForm } from '@yu-packages/hooks'
|
|
50
|
+
|
|
51
|
+
const { state, actions } = useForm({
|
|
52
|
+
initialValues: { username: '', password: '' },
|
|
53
|
+
rules: {
|
|
54
|
+
username: required('请输入用户名'),
|
|
55
|
+
password: required('请输入密码')
|
|
56
|
+
}
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
await actions.submit((values) => loginApi(values))
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
服务端字段错误可通过 `setErrors` 写入;`validateField` 可用于失焦校验。表单模型采用浅层快照,嵌套对象应整体替换,以便正确计算 `dirtyFields`。
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
// src/useCrud.ts
|
|
2
|
+
import {
|
|
3
|
+
getCurrentInstance,
|
|
4
|
+
getCurrentScope,
|
|
5
|
+
nextTick,
|
|
6
|
+
onMounted,
|
|
7
|
+
onScopeDispose,
|
|
8
|
+
ref,
|
|
9
|
+
watch
|
|
10
|
+
} from "vue";
|
|
11
|
+
var abortError = () => Object.assign(new Error("The operation was aborted"), { name: "AbortError" });
|
|
12
|
+
var isAbortError = (error) => error instanceof Error && error.name === "AbortError";
|
|
13
|
+
var normalizePageValue = (value) => Number.isFinite(value) ? Math.max(1, Math.trunc(value)) : 1;
|
|
14
|
+
var useCrud = (options) => {
|
|
15
|
+
const createInitialQuery = () => ({ ...options.initialQuery ?? {} });
|
|
16
|
+
const initialPage = normalizePageValue(options.initialPage ?? 1);
|
|
17
|
+
const initialPageSize = normalizePageValue(options.initialPageSize ?? 10);
|
|
18
|
+
const page = ref(initialPage);
|
|
19
|
+
const pageSize = ref(initialPageSize);
|
|
20
|
+
const total = ref(0);
|
|
21
|
+
const items = ref([]);
|
|
22
|
+
const query = ref(createInitialQuery());
|
|
23
|
+
const current = ref(null);
|
|
24
|
+
const currentKey = ref(null);
|
|
25
|
+
const selectedKeys = ref([]);
|
|
26
|
+
const listLoading = ref(false);
|
|
27
|
+
const detailLoading = ref(false);
|
|
28
|
+
const mutationLoading = ref(false);
|
|
29
|
+
const mutationType = ref(null);
|
|
30
|
+
const listError = ref(null);
|
|
31
|
+
const detailError = ref(null);
|
|
32
|
+
const mutationError = ref(null);
|
|
33
|
+
let listRequest = 0;
|
|
34
|
+
let detailRequest = 0;
|
|
35
|
+
let listController;
|
|
36
|
+
let detailController;
|
|
37
|
+
let activeMutations = 0;
|
|
38
|
+
let skipNextPaginationFetch = false;
|
|
39
|
+
const mutationControllers = /* @__PURE__ */ new Set();
|
|
40
|
+
const fetchList = async () => {
|
|
41
|
+
const request = ++listRequest;
|
|
42
|
+
listController?.abort();
|
|
43
|
+
const controller = new AbortController();
|
|
44
|
+
listController = controller;
|
|
45
|
+
listLoading.value = true;
|
|
46
|
+
listError.value = null;
|
|
47
|
+
try {
|
|
48
|
+
const result = await options.service.list(
|
|
49
|
+
{
|
|
50
|
+
...query.value,
|
|
51
|
+
pageIndex: page.value,
|
|
52
|
+
pageSize: pageSize.value
|
|
53
|
+
},
|
|
54
|
+
{ signal: controller.signal }
|
|
55
|
+
);
|
|
56
|
+
if (controller.signal.aborted) throw abortError();
|
|
57
|
+
if (request === listRequest) {
|
|
58
|
+
items.value = result.list;
|
|
59
|
+
total.value = result.total ?? result.list.length;
|
|
60
|
+
}
|
|
61
|
+
return result;
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (request === listRequest && !isAbortError(error)) {
|
|
64
|
+
listError.value = error;
|
|
65
|
+
}
|
|
66
|
+
throw error;
|
|
67
|
+
} finally {
|
|
68
|
+
if (request === listRequest) {
|
|
69
|
+
listLoading.value = false;
|
|
70
|
+
listController = void 0;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
const refresh = async ({ resetPage = false } = {}) => {
|
|
75
|
+
if (resetPage && page.value !== 1) {
|
|
76
|
+
skipNextPaginationFetch = true;
|
|
77
|
+
page.value = 1;
|
|
78
|
+
await nextTick();
|
|
79
|
+
}
|
|
80
|
+
return fetchList();
|
|
81
|
+
};
|
|
82
|
+
const search = async (params) => {
|
|
83
|
+
query.value = { ...params };
|
|
84
|
+
return refresh({ resetPage: true });
|
|
85
|
+
};
|
|
86
|
+
const resetSearch = () => search(createInitialQuery());
|
|
87
|
+
const fetchDetail = async (key) => {
|
|
88
|
+
if (!options.service.detail) {
|
|
89
|
+
const error = new Error("detail is not configured");
|
|
90
|
+
detailError.value = error;
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
const request = ++detailRequest;
|
|
94
|
+
detailController?.abort();
|
|
95
|
+
const controller = new AbortController();
|
|
96
|
+
detailController = controller;
|
|
97
|
+
currentKey.value = key;
|
|
98
|
+
detailLoading.value = true;
|
|
99
|
+
detailError.value = null;
|
|
100
|
+
try {
|
|
101
|
+
const result = await options.service.detail(key, { signal: controller.signal });
|
|
102
|
+
if (controller.signal.aborted) throw abortError();
|
|
103
|
+
if (request === detailRequest) current.value = result;
|
|
104
|
+
return result;
|
|
105
|
+
} catch (error) {
|
|
106
|
+
if (request === detailRequest && !isAbortError(error)) {
|
|
107
|
+
detailError.value = error;
|
|
108
|
+
}
|
|
109
|
+
throw error;
|
|
110
|
+
} finally {
|
|
111
|
+
if (request === detailRequest) {
|
|
112
|
+
detailLoading.value = false;
|
|
113
|
+
detailController = void 0;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
const runMutation = async (type, action, mutationOptions, afterSuccess = () => refresh({ resetPage: mutationOptions.resetPage })) => {
|
|
118
|
+
if (!action) {
|
|
119
|
+
const error = new Error(`${type} is not configured`);
|
|
120
|
+
mutationError.value = error;
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
const controller = new AbortController();
|
|
124
|
+
mutationControllers.add(controller);
|
|
125
|
+
activeMutations += 1;
|
|
126
|
+
mutationLoading.value = true;
|
|
127
|
+
mutationType.value = type;
|
|
128
|
+
mutationError.value = null;
|
|
129
|
+
let result;
|
|
130
|
+
try {
|
|
131
|
+
result = await action({ signal: controller.signal });
|
|
132
|
+
if (controller.signal.aborted) throw abortError();
|
|
133
|
+
} catch (error) {
|
|
134
|
+
if (!isAbortError(error)) mutationError.value = error;
|
|
135
|
+
throw error;
|
|
136
|
+
} finally {
|
|
137
|
+
mutationControllers.delete(controller);
|
|
138
|
+
activeMutations -= 1;
|
|
139
|
+
mutationLoading.value = activeMutations > 0;
|
|
140
|
+
if (activeMutations === 0) mutationType.value = null;
|
|
141
|
+
}
|
|
142
|
+
if (mutationOptions.refresh !== false) await afterSuccess();
|
|
143
|
+
return result;
|
|
144
|
+
};
|
|
145
|
+
const create = (input, mutationOptions = {}) => runMutation(
|
|
146
|
+
"create",
|
|
147
|
+
options.service.create ? (context) => options.service.create(input, context) : void 0,
|
|
148
|
+
mutationOptions
|
|
149
|
+
);
|
|
150
|
+
const update = (key, input, mutationOptions = {}) => runMutation(
|
|
151
|
+
"update",
|
|
152
|
+
options.service.update ? (context) => options.service.update(key, input, context) : void 0,
|
|
153
|
+
mutationOptions
|
|
154
|
+
);
|
|
155
|
+
const remove = async (keys, mutationOptions = {}) => {
|
|
156
|
+
const uniqueKeys = [...new Set(keys)];
|
|
157
|
+
if (uniqueKeys.length === 0) return void 0;
|
|
158
|
+
const result = await runMutation(
|
|
159
|
+
"remove",
|
|
160
|
+
options.service.remove ? (context) => options.service.remove(uniqueKeys, context) : void 0,
|
|
161
|
+
{ ...mutationOptions, refresh: false }
|
|
162
|
+
);
|
|
163
|
+
const removed = new Set(uniqueKeys);
|
|
164
|
+
selectedKeys.value = selectedKeys.value.filter((key) => !removed.has(key));
|
|
165
|
+
if (mutationOptions.refresh !== false) {
|
|
166
|
+
const lastPage = Math.max(
|
|
167
|
+
1,
|
|
168
|
+
Math.ceil(Math.max(0, total.value - uniqueKeys.length) / pageSize.value)
|
|
169
|
+
);
|
|
170
|
+
const targetPage = mutationOptions.resetPage ? 1 : Math.min(page.value, lastPage);
|
|
171
|
+
if (page.value !== targetPage) {
|
|
172
|
+
skipNextPaginationFetch = true;
|
|
173
|
+
page.value = targetPage;
|
|
174
|
+
await nextTick();
|
|
175
|
+
}
|
|
176
|
+
await fetchList();
|
|
177
|
+
}
|
|
178
|
+
return result;
|
|
179
|
+
};
|
|
180
|
+
const setPage = (value) => {
|
|
181
|
+
page.value = normalizePageValue(value);
|
|
182
|
+
};
|
|
183
|
+
const setPageSize = (value) => {
|
|
184
|
+
pageSize.value = normalizePageValue(value);
|
|
185
|
+
};
|
|
186
|
+
const toKeys = (keys) => Array.isArray(keys) ? keys : [keys];
|
|
187
|
+
const setSelection = (keys) => {
|
|
188
|
+
selectedKeys.value = [...new Set(keys)];
|
|
189
|
+
};
|
|
190
|
+
const select = (keys) => {
|
|
191
|
+
setSelection([...selectedKeys.value, ...toKeys(keys)]);
|
|
192
|
+
};
|
|
193
|
+
const unselect = (keys) => {
|
|
194
|
+
const removing = new Set(toKeys(keys));
|
|
195
|
+
selectedKeys.value = selectedKeys.value.filter((key) => !removing.has(key));
|
|
196
|
+
};
|
|
197
|
+
const toggle = (key) => {
|
|
198
|
+
if (selectedKeys.value.includes(key)) unselect(key);
|
|
199
|
+
else select(key);
|
|
200
|
+
};
|
|
201
|
+
const isSelected = (key) => selectedKeys.value.includes(key);
|
|
202
|
+
const clearSelection = () => {
|
|
203
|
+
selectedKeys.value = [];
|
|
204
|
+
};
|
|
205
|
+
const clearDetail = () => {
|
|
206
|
+
detailRequest += 1;
|
|
207
|
+
detailController?.abort();
|
|
208
|
+
detailController = void 0;
|
|
209
|
+
detailLoading.value = false;
|
|
210
|
+
detailError.value = null;
|
|
211
|
+
current.value = null;
|
|
212
|
+
currentKey.value = null;
|
|
213
|
+
};
|
|
214
|
+
const cancel = (scope = "all") => {
|
|
215
|
+
if (scope === "list" || scope === "all") {
|
|
216
|
+
listRequest += 1;
|
|
217
|
+
listController?.abort();
|
|
218
|
+
listController = void 0;
|
|
219
|
+
listLoading.value = false;
|
|
220
|
+
}
|
|
221
|
+
if (scope === "detail" || scope === "all") {
|
|
222
|
+
detailRequest += 1;
|
|
223
|
+
detailController?.abort();
|
|
224
|
+
detailController = void 0;
|
|
225
|
+
detailLoading.value = false;
|
|
226
|
+
}
|
|
227
|
+
if (scope === "mutation" || scope === "all") {
|
|
228
|
+
mutationControllers.forEach((controller) => controller.abort());
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
const reset = async ({ fetch = false } = {}) => {
|
|
232
|
+
cancel();
|
|
233
|
+
const paginationChanged = page.value !== initialPage || pageSize.value !== initialPageSize;
|
|
234
|
+
if (paginationChanged) skipNextPaginationFetch = true;
|
|
235
|
+
page.value = initialPage;
|
|
236
|
+
pageSize.value = initialPageSize;
|
|
237
|
+
total.value = 0;
|
|
238
|
+
items.value = [];
|
|
239
|
+
query.value = createInitialQuery();
|
|
240
|
+
current.value = null;
|
|
241
|
+
currentKey.value = null;
|
|
242
|
+
selectedKeys.value = [];
|
|
243
|
+
listError.value = null;
|
|
244
|
+
detailError.value = null;
|
|
245
|
+
mutationError.value = null;
|
|
246
|
+
await nextTick();
|
|
247
|
+
if (fetch) return fetchList();
|
|
248
|
+
return void 0;
|
|
249
|
+
};
|
|
250
|
+
watch([page, pageSize], ([nextPage, nextSize], [, previousSize]) => {
|
|
251
|
+
if (skipNextPaginationFetch) {
|
|
252
|
+
skipNextPaginationFetch = false;
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
if (nextSize !== previousSize && nextPage !== 1) {
|
|
256
|
+
page.value = 1;
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
void fetchList().catch(() => void 0);
|
|
260
|
+
});
|
|
261
|
+
const start = () => void fetchList().catch(() => void 0);
|
|
262
|
+
if (options.immediate !== false) {
|
|
263
|
+
if (getCurrentInstance()) onMounted(start);
|
|
264
|
+
else start();
|
|
265
|
+
}
|
|
266
|
+
if (getCurrentScope()) onScopeDispose(() => cancel());
|
|
267
|
+
return {
|
|
268
|
+
state: {
|
|
269
|
+
page,
|
|
270
|
+
pageSize,
|
|
271
|
+
total,
|
|
272
|
+
items,
|
|
273
|
+
query,
|
|
274
|
+
current,
|
|
275
|
+
currentKey,
|
|
276
|
+
selectedKeys,
|
|
277
|
+
listLoading,
|
|
278
|
+
detailLoading,
|
|
279
|
+
mutationLoading,
|
|
280
|
+
mutationType,
|
|
281
|
+
listError,
|
|
282
|
+
detailError,
|
|
283
|
+
mutationError
|
|
284
|
+
},
|
|
285
|
+
actions: {
|
|
286
|
+
fetchList,
|
|
287
|
+
refresh,
|
|
288
|
+
search,
|
|
289
|
+
resetSearch,
|
|
290
|
+
fetchDetail,
|
|
291
|
+
clearDetail,
|
|
292
|
+
create,
|
|
293
|
+
update,
|
|
294
|
+
remove,
|
|
295
|
+
setPage,
|
|
296
|
+
setPageSize,
|
|
297
|
+
setSelection,
|
|
298
|
+
select,
|
|
299
|
+
unselect,
|
|
300
|
+
toggle,
|
|
301
|
+
isSelected,
|
|
302
|
+
clearSelection,
|
|
303
|
+
cancel,
|
|
304
|
+
reset
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
export {
|
|
310
|
+
useCrud
|
|
311
|
+
};
|
|
312
|
+
//# sourceMappingURL=chunk-HX3TDMPN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/useCrud.ts"],"sourcesContent":["import {\n getCurrentInstance,\n getCurrentScope,\n nextTick,\n onMounted,\n onScopeDispose,\n ref,\n watch,\n type Ref\n} from 'vue'\n\nexport type CrudKey = string | number\nexport type CrudQuery = Record<string, unknown>\nexport type CrudMutation = 'create' | 'update' | 'remove'\nexport type CrudRequestScope = 'list' | 'detail' | 'mutation' | 'all'\n\nexport interface CrudPagination {\n pageIndex: number\n pageSize: number\n}\n\nexport type CrudListParams<Query extends CrudQuery> = Query & CrudPagination\n\nexport interface CrudListResult<Row> {\n list: Row[]\n total?: number\n}\n\nexport interface CrudRequestContext {\n signal: AbortSignal\n}\n\nexport interface CrudService<\n Row,\n Detail = Row,\n Query extends CrudQuery = CrudQuery,\n CreateInput = Partial<Row>,\n UpdateInput = Partial<Row>,\n Key extends CrudKey = CrudKey\n> {\n list: (params: CrudListParams<Query>, context: CrudRequestContext) => Promise<CrudListResult<Row>>\n detail?: (key: Key, context: CrudRequestContext) => Promise<Detail>\n create?: (input: CreateInput, context: CrudRequestContext) => Promise<unknown>\n update?: (key: Key, input: UpdateInput, context: CrudRequestContext) => Promise<unknown>\n remove?: (keys: Key[], context: CrudRequestContext) => Promise<unknown>\n}\n\nexport interface UseCrudOptions<\n Row,\n Detail = Row,\n Query extends CrudQuery = CrudQuery,\n CreateInput = Partial<Row>,\n UpdateInput = Partial<Row>,\n Key extends CrudKey = CrudKey\n> {\n service: CrudService<Row, Detail, Query, CreateInput, UpdateInput, Key>\n immediate?: boolean\n initialQuery?: Query\n initialPage?: number\n initialPageSize?: number\n}\n\nexport interface CrudRefreshOptions {\n resetPage?: boolean\n}\n\nexport interface CrudMutationOptions extends CrudRefreshOptions {\n refresh?: boolean\n}\n\nexport interface CrudResetOptions {\n fetch?: boolean\n}\n\nconst abortError = () =>\n Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })\n\nconst isAbortError = (error: unknown) => error instanceof Error && error.name === 'AbortError'\n\nconst normalizePageValue = (value: number) =>\n Number.isFinite(value) ? Math.max(1, Math.trunc(value)) : 1\n\nexport const useCrud = <\n Row,\n Detail = Row,\n Query extends CrudQuery = CrudQuery,\n CreateInput = Partial<Row>,\n UpdateInput = Partial<Row>,\n Key extends CrudKey = CrudKey\n>(\n options: UseCrudOptions<Row, Detail, Query, CreateInput, UpdateInput, Key>\n) => {\n const createInitialQuery = () => ({ ...(options.initialQuery ?? ({} as Query)) }) as Query\n const initialPage = normalizePageValue(options.initialPage ?? 1)\n const initialPageSize = normalizePageValue(options.initialPageSize ?? 10)\n\n const page = ref(initialPage)\n const pageSize = ref(initialPageSize)\n const total = ref(0)\n const items = ref<Row[]>([]) as Ref<Row[]>\n const query = ref(createInitialQuery()) as Ref<Query>\n const current = ref<Detail | null>(null) as Ref<Detail | null>\n const currentKey = ref<Key | null>(null) as Ref<Key | null>\n const selectedKeys = ref<Key[]>([]) as Ref<Key[]>\n\n const listLoading = ref(false)\n const detailLoading = ref(false)\n const mutationLoading = ref(false)\n const mutationType = ref<CrudMutation | null>(null)\n\n const listError = ref<unknown>(null)\n const detailError = ref<unknown>(null)\n const mutationError = ref<unknown>(null)\n\n let listRequest = 0\n let detailRequest = 0\n let listController: AbortController | undefined\n let detailController: AbortController | undefined\n let activeMutations = 0\n let skipNextPaginationFetch = false\n const mutationControllers = new Set<AbortController>()\n\n const fetchList = async () => {\n const request = ++listRequest\n listController?.abort()\n const controller = new AbortController()\n listController = controller\n listLoading.value = true\n listError.value = null\n\n try {\n const result = await options.service.list(\n {\n ...query.value,\n pageIndex: page.value,\n pageSize: pageSize.value\n } as CrudListParams<Query>,\n { signal: controller.signal }\n )\n\n if (controller.signal.aborted) throw abortError()\n if (request === listRequest) {\n items.value = result.list\n total.value = result.total ?? result.list.length\n }\n return result\n } catch (error) {\n if (request === listRequest && !isAbortError(error)) {\n listError.value = error\n }\n throw error\n } finally {\n if (request === listRequest) {\n listLoading.value = false\n listController = undefined\n }\n }\n }\n\n const refresh = async ({ resetPage = false }: CrudRefreshOptions = {}) => {\n if (resetPage && page.value !== 1) {\n skipNextPaginationFetch = true\n page.value = 1\n await nextTick()\n }\n return fetchList()\n }\n\n const search = async (params: Query) => {\n query.value = { ...params }\n return refresh({ resetPage: true })\n }\n\n const resetSearch = () => search(createInitialQuery())\n\n const fetchDetail = async (key: Key) => {\n if (!options.service.detail) {\n const error = new Error('detail is not configured')\n detailError.value = error\n throw error\n }\n\n const request = ++detailRequest\n detailController?.abort()\n const controller = new AbortController()\n detailController = controller\n currentKey.value = key\n detailLoading.value = true\n detailError.value = null\n\n try {\n const result = await options.service.detail(key, { signal: controller.signal })\n if (controller.signal.aborted) throw abortError()\n if (request === detailRequest) current.value = result\n return result\n } catch (error) {\n if (request === detailRequest && !isAbortError(error)) {\n detailError.value = error\n }\n throw error\n } finally {\n if (request === detailRequest) {\n detailLoading.value = false\n detailController = undefined\n }\n }\n }\n\n const runMutation = async <Result>(\n type: CrudMutation,\n action: ((context: CrudRequestContext) => Promise<Result>) | undefined,\n mutationOptions: CrudMutationOptions,\n afterSuccess = () => refresh({ resetPage: mutationOptions.resetPage })\n ) => {\n if (!action) {\n const error = new Error(`${type} is not configured`)\n mutationError.value = error\n throw error\n }\n\n const controller = new AbortController()\n mutationControllers.add(controller)\n activeMutations += 1\n mutationLoading.value = true\n mutationType.value = type\n mutationError.value = null\n\n let result: Result\n try {\n result = await action({ signal: controller.signal })\n if (controller.signal.aborted) throw abortError()\n } catch (error) {\n if (!isAbortError(error)) mutationError.value = error\n throw error\n } finally {\n mutationControllers.delete(controller)\n activeMutations -= 1\n mutationLoading.value = activeMutations > 0\n if (activeMutations === 0) mutationType.value = null\n }\n\n if (mutationOptions.refresh !== false) await afterSuccess()\n return result\n }\n\n const create = (input: CreateInput, mutationOptions: CrudMutationOptions = {}) =>\n runMutation(\n 'create',\n options.service.create ? (context) => options.service.create!(input, context) : undefined,\n mutationOptions\n )\n\n const update = (key: Key, input: UpdateInput, mutationOptions: CrudMutationOptions = {}) =>\n runMutation(\n 'update',\n options.service.update\n ? (context) => options.service.update!(key, input, context)\n : undefined,\n mutationOptions\n )\n\n const remove = async (keys: Key[], mutationOptions: CrudMutationOptions = {}) => {\n const uniqueKeys = [...new Set(keys)]\n if (uniqueKeys.length === 0) return undefined\n\n const result = await runMutation(\n 'remove',\n options.service.remove\n ? (context) => options.service.remove!(uniqueKeys, context)\n : undefined,\n { ...mutationOptions, refresh: false }\n )\n\n const removed = new Set(uniqueKeys)\n selectedKeys.value = selectedKeys.value.filter((key) => !removed.has(key))\n\n if (mutationOptions.refresh !== false) {\n const lastPage = Math.max(\n 1,\n Math.ceil(Math.max(0, total.value - uniqueKeys.length) / pageSize.value)\n )\n const targetPage = mutationOptions.resetPage ? 1 : Math.min(page.value, lastPage)\n\n if (page.value !== targetPage) {\n skipNextPaginationFetch = true\n page.value = targetPage\n await nextTick()\n }\n await fetchList()\n }\n\n return result\n }\n\n const setPage = (value: number) => {\n page.value = normalizePageValue(value)\n }\n\n const setPageSize = (value: number) => {\n pageSize.value = normalizePageValue(value)\n }\n\n const toKeys = (keys: Key | readonly Key[]) =>\n (Array.isArray(keys) ? keys : [keys]) as readonly Key[]\n\n const setSelection = (keys: readonly Key[]) => {\n selectedKeys.value = [...new Set(keys)]\n }\n\n const select = (keys: Key | readonly Key[]) => {\n setSelection([...selectedKeys.value, ...toKeys(keys)])\n }\n\n const unselect = (keys: Key | readonly Key[]) => {\n const removing = new Set(toKeys(keys))\n selectedKeys.value = selectedKeys.value.filter((key) => !removing.has(key))\n }\n\n const toggle = (key: Key) => {\n if (selectedKeys.value.includes(key)) unselect(key)\n else select(key)\n }\n\n const isSelected = (key: Key) => selectedKeys.value.includes(key)\n\n const clearSelection = () => {\n selectedKeys.value = []\n }\n\n const clearDetail = () => {\n detailRequest += 1\n detailController?.abort()\n detailController = undefined\n detailLoading.value = false\n detailError.value = null\n current.value = null\n currentKey.value = null\n }\n\n const cancel = (scope: CrudRequestScope = 'all') => {\n if (scope === 'list' || scope === 'all') {\n listRequest += 1\n listController?.abort()\n listController = undefined\n listLoading.value = false\n }\n if (scope === 'detail' || scope === 'all') {\n detailRequest += 1\n detailController?.abort()\n detailController = undefined\n detailLoading.value = false\n }\n if (scope === 'mutation' || scope === 'all') {\n mutationControllers.forEach((controller) => controller.abort())\n }\n }\n\n const reset = async ({ fetch = false }: CrudResetOptions = {}) => {\n cancel()\n const paginationChanged = page.value !== initialPage || pageSize.value !== initialPageSize\n if (paginationChanged) skipNextPaginationFetch = true\n\n page.value = initialPage\n pageSize.value = initialPageSize\n total.value = 0\n items.value = []\n query.value = createInitialQuery()\n current.value = null\n currentKey.value = null\n selectedKeys.value = []\n listError.value = null\n detailError.value = null\n mutationError.value = null\n await nextTick()\n\n if (fetch) return fetchList()\n return undefined\n }\n\n watch([page, pageSize], ([nextPage, nextSize], [, previousSize]) => {\n if (skipNextPaginationFetch) {\n skipNextPaginationFetch = false\n return\n }\n if (nextSize !== previousSize && nextPage !== 1) {\n page.value = 1\n return\n }\n void fetchList().catch(() => undefined)\n })\n\n const start = () => void fetchList().catch(() => undefined)\n if (options.immediate !== false) {\n if (getCurrentInstance()) onMounted(start)\n else start()\n }\n\n if (getCurrentScope()) onScopeDispose(() => cancel())\n\n return {\n state: {\n page,\n pageSize,\n total,\n items,\n query,\n current,\n currentKey,\n selectedKeys,\n listLoading,\n detailLoading,\n mutationLoading,\n mutationType,\n listError,\n detailError,\n mutationError\n },\n actions: {\n fetchList,\n refresh,\n search,\n resetSearch,\n fetchDetail,\n clearDetail,\n create,\n update,\n remove,\n setPage,\n setPageSize,\n setSelection,\n select,\n unselect,\n toggle,\n isSelected,\n clearSelection,\n cancel,\n reset\n }\n }\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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AA,IACF;AAAA,IACA,SAAS;AAAA,MACP;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// src/useForm.ts
|
|
2
|
+
import { computed, ref, toRaw } from "vue";
|
|
3
|
+
var toArray = (value) => Array.isArray(value) ? value : [value];
|
|
4
|
+
var clone = (values) => ({ ...values });
|
|
5
|
+
var message = (value) => typeof value === "function" ? value() : value;
|
|
6
|
+
var required = (errorMessage = "This field is required") => {
|
|
7
|
+
return (value) => {
|
|
8
|
+
const empty = value == null || typeof value === "string" && value.trim() === "" || Array.isArray(value) && value.length === 0;
|
|
9
|
+
return empty ? message(errorMessage) : void 0;
|
|
10
|
+
};
|
|
11
|
+
};
|
|
12
|
+
var useForm = (options) => {
|
|
13
|
+
let initialValues = clone(options.initialValues);
|
|
14
|
+
const values = ref(clone(initialValues));
|
|
15
|
+
const errors = ref({});
|
|
16
|
+
const touchedFields = ref([]);
|
|
17
|
+
const validating = ref(false);
|
|
18
|
+
const submitting = ref(false);
|
|
19
|
+
const submitError = ref(null);
|
|
20
|
+
const submitCount = ref(0);
|
|
21
|
+
let activeValidations = 0;
|
|
22
|
+
const validationVersions = /* @__PURE__ */ new Map();
|
|
23
|
+
const dirtyFields = computed(() => {
|
|
24
|
+
const fields = /* @__PURE__ */ new Set([
|
|
25
|
+
...Object.keys(initialValues),
|
|
26
|
+
...Object.keys(values.value)
|
|
27
|
+
]);
|
|
28
|
+
return [...fields].filter(
|
|
29
|
+
(field) => !Object.is(toRaw(values.value[field]), initialValues[field])
|
|
30
|
+
);
|
|
31
|
+
});
|
|
32
|
+
const dirty = computed(() => dirtyFields.value.length > 0);
|
|
33
|
+
const hasErrors = computed(
|
|
34
|
+
() => Object.values(errors.value).some(
|
|
35
|
+
(messages) => messages && messages.length > 0
|
|
36
|
+
)
|
|
37
|
+
);
|
|
38
|
+
const setValue = (field, value) => {
|
|
39
|
+
values.value[field] = value;
|
|
40
|
+
};
|
|
41
|
+
const setValues = (nextValues) => {
|
|
42
|
+
Object.assign(values.value, nextValues);
|
|
43
|
+
};
|
|
44
|
+
const touch = (fields) => {
|
|
45
|
+
touchedFields.value = [
|
|
46
|
+
.../* @__PURE__ */ new Set([...touchedFields.value, ...toArray(fields)])
|
|
47
|
+
];
|
|
48
|
+
};
|
|
49
|
+
const clearErrors = (fields) => {
|
|
50
|
+
if (!fields) {
|
|
51
|
+
errors.value = {};
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const nextErrors = { ...errors.value };
|
|
55
|
+
toArray(fields).forEach((field) => delete nextErrors[field]);
|
|
56
|
+
errors.value = nextErrors;
|
|
57
|
+
};
|
|
58
|
+
const setErrors = (nextErrors) => {
|
|
59
|
+
const merged = { ...errors.value };
|
|
60
|
+
for (const field of Object.keys(nextErrors)) {
|
|
61
|
+
const fieldMessages = nextErrors[field];
|
|
62
|
+
if (fieldMessages == null || fieldMessages.length === 0) delete merged[field];
|
|
63
|
+
else merged[field] = typeof fieldMessages === "string" ? [fieldMessages] : fieldMessages;
|
|
64
|
+
}
|
|
65
|
+
errors.value = merged;
|
|
66
|
+
};
|
|
67
|
+
const validateField = async (field) => {
|
|
68
|
+
touch(field);
|
|
69
|
+
const configured = options.rules?.[field];
|
|
70
|
+
const validators = configured ? toArray(configured) : [];
|
|
71
|
+
const version = (validationVersions.get(field) ?? 0) + 1;
|
|
72
|
+
validationVersions.set(field, version);
|
|
73
|
+
activeValidations += 1;
|
|
74
|
+
validating.value = true;
|
|
75
|
+
const fieldErrors = [];
|
|
76
|
+
try {
|
|
77
|
+
for (const validator of validators) {
|
|
78
|
+
try {
|
|
79
|
+
const result = await validator(values.value[field], values.value);
|
|
80
|
+
if (result) fieldErrors.push(...toArray(result));
|
|
81
|
+
} catch (error) {
|
|
82
|
+
fieldErrors.push(error instanceof Error ? error.message : String(error));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (validationVersions.get(field) === version) {
|
|
86
|
+
setErrors({ [field]: fieldErrors });
|
|
87
|
+
}
|
|
88
|
+
return fieldErrors.length === 0;
|
|
89
|
+
} finally {
|
|
90
|
+
activeValidations -= 1;
|
|
91
|
+
validating.value = activeValidations > 0;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
const validate = async () => {
|
|
95
|
+
const fields = Object.keys(options.rules ?? {});
|
|
96
|
+
const results = await Promise.all(fields.map(validateField));
|
|
97
|
+
return results.every(Boolean);
|
|
98
|
+
};
|
|
99
|
+
const submit = async (handler) => {
|
|
100
|
+
if (submitting.value) return void 0;
|
|
101
|
+
submitting.value = true;
|
|
102
|
+
submitError.value = null;
|
|
103
|
+
submitCount.value += 1;
|
|
104
|
+
try {
|
|
105
|
+
if (!await validate()) return void 0;
|
|
106
|
+
return await handler(clone(values.value));
|
|
107
|
+
} catch (error) {
|
|
108
|
+
submitError.value = error;
|
|
109
|
+
throw error;
|
|
110
|
+
} finally {
|
|
111
|
+
submitting.value = false;
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
const reset = (nextValues) => {
|
|
115
|
+
if (nextValues) initialValues = clone(nextValues);
|
|
116
|
+
values.value = clone(initialValues);
|
|
117
|
+
errors.value = {};
|
|
118
|
+
touchedFields.value = [];
|
|
119
|
+
submitError.value = null;
|
|
120
|
+
validationVersions.clear();
|
|
121
|
+
};
|
|
122
|
+
return {
|
|
123
|
+
state: {
|
|
124
|
+
values,
|
|
125
|
+
errors,
|
|
126
|
+
touchedFields,
|
|
127
|
+
dirtyFields,
|
|
128
|
+
dirty,
|
|
129
|
+
hasErrors,
|
|
130
|
+
validating,
|
|
131
|
+
submitting,
|
|
132
|
+
submitError,
|
|
133
|
+
submitCount
|
|
134
|
+
},
|
|
135
|
+
actions: {
|
|
136
|
+
setValue,
|
|
137
|
+
setValues,
|
|
138
|
+
setErrors,
|
|
139
|
+
clearErrors,
|
|
140
|
+
touch,
|
|
141
|
+
validateField,
|
|
142
|
+
validate,
|
|
143
|
+
submit,
|
|
144
|
+
reset
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
export {
|
|
150
|
+
required,
|
|
151
|
+
useForm
|
|
152
|
+
};
|
|
153
|
+
//# sourceMappingURL=chunk-ZGUB7DGM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/useForm.ts"],"sourcesContent":["import { computed, ref, toRaw, type Ref } from 'vue'\n\nexport type FormModel = object\nexport type FormField<Model extends FormModel> = Extract<keyof Model, string>\nexport type FormValidatorResult = string | string[] | null | undefined\n\nexport type FormValidator<Value = unknown, Model extends FormModel = FormModel> = (\n value: Value,\n values: Readonly<Model>\n) => FormValidatorResult | Promise<FormValidatorResult>\n\nexport type FormRules<Model extends FormModel> = Partial<{\n [Field in FormField<Model>]:\n FormValidator<Model[Field], Model> | FormValidator<Model[Field], Model>[]\n}>\n\nexport type FormErrors<Model extends FormModel> = Partial<Record<FormField<Model>, string[]>>\n\nexport type FormErrorInput<Model extends FormModel> = Partial<\n Record<FormField<Model>, string | string[] | null | undefined>\n>\n\nexport interface UseFormOptions<Model extends FormModel> {\n initialValues: Model\n rules?: FormRules<Model>\n}\n\ntype FieldInput<Model extends FormModel> = FormField<Model> | readonly FormField<Model>[]\n\nconst toArray = <Value>(value: Value | readonly Value[]) =>\n (Array.isArray(value) ? value : [value]) as readonly Value[]\n\nconst clone = <Model extends FormModel>(values: Model) => ({ ...values }) as Model\n\nconst message = (value: string | (() => string)) => (typeof value === 'function' ? value() : value)\n\nexport const required = (\n errorMessage: string | (() => string) = 'This field is required'\n): FormValidator => {\n return (value) => {\n const empty =\n value == null ||\n (typeof value === 'string' && value.trim() === '') ||\n (Array.isArray(value) && value.length === 0)\n return empty ? message(errorMessage) : undefined\n }\n}\n\nexport const useForm = <Model extends FormModel>(options: UseFormOptions<Model>) => {\n let initialValues = clone(options.initialValues)\n const values = ref(clone(initialValues)) as Ref<Model>\n const errors = ref<FormErrors<Model>>({}) as Ref<FormErrors<Model>>\n const touchedFields = ref<FormField<Model>[]>([]) as Ref<FormField<Model>[]>\n const validating = ref(false)\n const submitting = ref(false)\n const submitError = ref<unknown>(null)\n const submitCount = ref(0)\n\n let activeValidations = 0\n const validationVersions = new Map<FormField<Model>, number>()\n\n const dirtyFields = computed(() => {\n const fields = new Set([\n ...Object.keys(initialValues),\n ...Object.keys(values.value)\n ] as FormField<Model>[])\n return [...fields].filter(\n (field) => !Object.is(toRaw(values.value[field]), initialValues[field])\n )\n })\n const dirty = computed(() => dirtyFields.value.length > 0)\n const hasErrors = computed(() =>\n (Object.values(errors.value) as Array<string[] | undefined>).some(\n (messages) => messages && messages.length > 0\n )\n )\n\n const setValue = <Field extends FormField<Model>>(field: Field, value: Model[Field]) => {\n values.value[field] = value\n }\n\n const setValues = (nextValues: Partial<Model>) => {\n Object.assign(values.value, nextValues)\n }\n\n const touch = (fields: FieldInput<Model>) => {\n touchedFields.value = [\n ...new Set([...touchedFields.value, ...toArray(fields)])\n ] as FormField<Model>[]\n }\n\n const clearErrors = (fields?: FieldInput<Model>) => {\n if (!fields) {\n errors.value = {}\n return\n }\n\n const nextErrors = { ...errors.value }\n toArray(fields).forEach((field) => delete nextErrors[field])\n errors.value = nextErrors\n }\n\n const setErrors = (nextErrors: FormErrorInput<Model>) => {\n const merged = { ...errors.value }\n for (const field of Object.keys(nextErrors) as FormField<Model>[]) {\n const fieldMessages = nextErrors[field] as string | string[] | null | undefined\n if (fieldMessages == null || fieldMessages.length === 0) delete merged[field]\n else merged[field] = typeof fieldMessages === 'string' ? [fieldMessages] : fieldMessages\n }\n errors.value = merged\n }\n\n const validateField = async (field: FormField<Model>) => {\n touch(field)\n const configured = options.rules?.[field]\n const validators = configured\n ? (toArray(configured) as readonly FormValidator<Model[typeof field], Model>[])\n : []\n const version = (validationVersions.get(field) ?? 0) + 1\n validationVersions.set(field, version)\n activeValidations += 1\n validating.value = true\n\n const fieldErrors: string[] = []\n try {\n for (const validator of validators) {\n try {\n const result = await validator(values.value[field], values.value)\n if (result) fieldErrors.push(...toArray(result))\n } catch (error) {\n fieldErrors.push(error instanceof Error ? error.message : String(error))\n }\n }\n\n if (validationVersions.get(field) === version) {\n setErrors({ [field]: fieldErrors } as FormErrorInput<Model>)\n }\n return fieldErrors.length === 0\n } finally {\n activeValidations -= 1\n validating.value = activeValidations > 0\n }\n }\n\n const validate = async () => {\n const fields = Object.keys(options.rules ?? {}) as FormField<Model>[]\n const results = await Promise.all(fields.map(validateField))\n return results.every(Boolean)\n }\n\n const submit = async <Result>(handler: (formValues: Model) => Promise<Result> | Result) => {\n if (submitting.value) return undefined\n\n submitting.value = true\n submitError.value = null\n submitCount.value += 1\n try {\n if (!(await validate())) return undefined\n return await handler(clone(values.value))\n } catch (error) {\n submitError.value = error\n throw error\n } finally {\n submitting.value = false\n }\n }\n\n const reset = (nextValues?: Model) => {\n if (nextValues) initialValues = clone(nextValues)\n values.value = clone(initialValues)\n errors.value = {}\n touchedFields.value = []\n submitError.value = null\n validationVersions.clear()\n }\n\n return {\n state: {\n values,\n errors,\n touchedFields,\n dirtyFields,\n dirty,\n hasErrors,\n validating,\n submitting,\n submitError,\n submitCount\n },\n actions: {\n setValue,\n setValues,\n setErrors,\n clearErrors,\n touch,\n validateField,\n validate,\n submit,\n reset\n }\n }\n}\n"],"mappings":";AAAA,SAAS,UAAU,KAAK,aAAuB;AA6B/C,IAAM,UAAU,CAAQ,UACrB,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;AAExC,IAAM,QAAQ,CAA0B,YAAmB,EAAE,GAAG,OAAO;AAEvE,IAAM,UAAU,CAAC,UAAoC,OAAO,UAAU,aAAa,MAAM,IAAI;AAEt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A;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { CrudKey, CrudListParams, CrudListResult, CrudMutation, CrudMutationOptions, CrudPagination, CrudQuery, CrudRefreshOptions, CrudRequestContext, CrudRequestScope, CrudResetOptions, CrudService, UseCrudOptions, useCrud } from './useCrud.js';
|
|
2
|
+
export { FormErrorInput, FormErrors, FormField, FormModel, FormRules, FormValidator, FormValidatorResult, UseFormOptions, required, useForm } from './useForm.js';
|
|
3
|
+
import 'vue';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { Ref } from 'vue';
|
|
2
|
+
|
|
3
|
+
type CrudKey = string | number;
|
|
4
|
+
type CrudQuery = Record<string, unknown>;
|
|
5
|
+
type CrudMutation = 'create' | 'update' | 'remove';
|
|
6
|
+
type CrudRequestScope = 'list' | 'detail' | 'mutation' | 'all';
|
|
7
|
+
interface CrudPagination {
|
|
8
|
+
pageIndex: number;
|
|
9
|
+
pageSize: number;
|
|
10
|
+
}
|
|
11
|
+
type CrudListParams<Query extends CrudQuery> = Query & CrudPagination;
|
|
12
|
+
interface CrudListResult<Row> {
|
|
13
|
+
list: Row[];
|
|
14
|
+
total?: number;
|
|
15
|
+
}
|
|
16
|
+
interface CrudRequestContext {
|
|
17
|
+
signal: AbortSignal;
|
|
18
|
+
}
|
|
19
|
+
interface CrudService<Row, Detail = Row, Query extends CrudQuery = CrudQuery, CreateInput = Partial<Row>, UpdateInput = Partial<Row>, Key extends CrudKey = CrudKey> {
|
|
20
|
+
list: (params: CrudListParams<Query>, context: CrudRequestContext) => Promise<CrudListResult<Row>>;
|
|
21
|
+
detail?: (key: Key, context: CrudRequestContext) => Promise<Detail>;
|
|
22
|
+
create?: (input: CreateInput, context: CrudRequestContext) => Promise<unknown>;
|
|
23
|
+
update?: (key: Key, input: UpdateInput, context: CrudRequestContext) => Promise<unknown>;
|
|
24
|
+
remove?: (keys: Key[], context: CrudRequestContext) => Promise<unknown>;
|
|
25
|
+
}
|
|
26
|
+
interface UseCrudOptions<Row, Detail = Row, Query extends CrudQuery = CrudQuery, CreateInput = Partial<Row>, UpdateInput = Partial<Row>, Key extends CrudKey = CrudKey> {
|
|
27
|
+
service: CrudService<Row, Detail, Query, CreateInput, UpdateInput, Key>;
|
|
28
|
+
immediate?: boolean;
|
|
29
|
+
initialQuery?: Query;
|
|
30
|
+
initialPage?: number;
|
|
31
|
+
initialPageSize?: number;
|
|
32
|
+
}
|
|
33
|
+
interface CrudRefreshOptions {
|
|
34
|
+
resetPage?: boolean;
|
|
35
|
+
}
|
|
36
|
+
interface CrudMutationOptions extends CrudRefreshOptions {
|
|
37
|
+
refresh?: boolean;
|
|
38
|
+
}
|
|
39
|
+
interface CrudResetOptions {
|
|
40
|
+
fetch?: boolean;
|
|
41
|
+
}
|
|
42
|
+
declare const useCrud: <Row, Detail = Row, Query extends CrudQuery = CrudQuery, CreateInput = Partial<Row>, UpdateInput = Partial<Row>, Key extends CrudKey = CrudKey>(options: UseCrudOptions<Row, Detail, Query, CreateInput, UpdateInput, Key>) => {
|
|
43
|
+
state: {
|
|
44
|
+
page: Ref<number, number>;
|
|
45
|
+
pageSize: Ref<number, number>;
|
|
46
|
+
total: Ref<number, number>;
|
|
47
|
+
items: Ref<Row[], Row[]>;
|
|
48
|
+
query: Ref<Query, Query>;
|
|
49
|
+
current: Ref<Detail | null, Detail | null>;
|
|
50
|
+
currentKey: Ref<Key | null, Key | null>;
|
|
51
|
+
selectedKeys: Ref<Key[], Key[]>;
|
|
52
|
+
listLoading: Ref<boolean, boolean>;
|
|
53
|
+
detailLoading: Ref<boolean, boolean>;
|
|
54
|
+
mutationLoading: Ref<boolean, boolean>;
|
|
55
|
+
mutationType: Ref<CrudMutation | null, CrudMutation | null>;
|
|
56
|
+
listError: Ref<unknown, unknown>;
|
|
57
|
+
detailError: Ref<unknown, unknown>;
|
|
58
|
+
mutationError: Ref<unknown, unknown>;
|
|
59
|
+
};
|
|
60
|
+
actions: {
|
|
61
|
+
fetchList: () => Promise<CrudListResult<Row>>;
|
|
62
|
+
refresh: ({ resetPage }?: CrudRefreshOptions) => Promise<CrudListResult<Row>>;
|
|
63
|
+
search: (params: Query) => Promise<CrudListResult<Row>>;
|
|
64
|
+
resetSearch: () => Promise<CrudListResult<Row>>;
|
|
65
|
+
fetchDetail: (key: Key) => Promise<Detail>;
|
|
66
|
+
clearDetail: () => void;
|
|
67
|
+
create: (input: CreateInput, mutationOptions?: CrudMutationOptions) => Promise<unknown>;
|
|
68
|
+
update: (key: Key, input: UpdateInput, mutationOptions?: CrudMutationOptions) => Promise<unknown>;
|
|
69
|
+
remove: (keys: Key[], mutationOptions?: CrudMutationOptions) => Promise<unknown>;
|
|
70
|
+
setPage: (value: number) => void;
|
|
71
|
+
setPageSize: (value: number) => void;
|
|
72
|
+
setSelection: (keys: readonly Key[]) => void;
|
|
73
|
+
select: (keys: Key | readonly Key[]) => void;
|
|
74
|
+
unselect: (keys: Key | readonly Key[]) => void;
|
|
75
|
+
toggle: (key: Key) => void;
|
|
76
|
+
isSelected: (key: Key) => boolean;
|
|
77
|
+
clearSelection: () => void;
|
|
78
|
+
cancel: (scope?: CrudRequestScope) => void;
|
|
79
|
+
reset: ({ fetch }?: CrudResetOptions) => Promise<CrudListResult<Row> | undefined>;
|
|
80
|
+
};
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
export { useCrud };
|
|
84
|
+
export type { CrudKey, CrudListParams, CrudListResult, CrudMutation, CrudMutationOptions, CrudPagination, CrudQuery, CrudRefreshOptions, CrudRequestContext, CrudRequestScope, CrudResetOptions, CrudService, UseCrudOptions };
|
package/dist/useCrud.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import * as vue from 'vue';
|
|
2
|
+
import { Ref } from 'vue';
|
|
3
|
+
|
|
4
|
+
type FormModel = object;
|
|
5
|
+
type FormField<Model extends FormModel> = Extract<keyof Model, string>;
|
|
6
|
+
type FormValidatorResult = string | string[] | null | undefined;
|
|
7
|
+
type FormValidator<Value = unknown, Model extends FormModel = FormModel> = (value: Value, values: Readonly<Model>) => FormValidatorResult | Promise<FormValidatorResult>;
|
|
8
|
+
type FormRules<Model extends FormModel> = Partial<{
|
|
9
|
+
[Field in FormField<Model>]: FormValidator<Model[Field], Model> | FormValidator<Model[Field], Model>[];
|
|
10
|
+
}>;
|
|
11
|
+
type FormErrors<Model extends FormModel> = Partial<Record<FormField<Model>, string[]>>;
|
|
12
|
+
type FormErrorInput<Model extends FormModel> = Partial<Record<FormField<Model>, string | string[] | null | undefined>>;
|
|
13
|
+
interface UseFormOptions<Model extends FormModel> {
|
|
14
|
+
initialValues: Model;
|
|
15
|
+
rules?: FormRules<Model>;
|
|
16
|
+
}
|
|
17
|
+
type FieldInput<Model extends FormModel> = FormField<Model> | readonly FormField<Model>[];
|
|
18
|
+
declare const required: (errorMessage?: string | (() => string)) => FormValidator;
|
|
19
|
+
declare const useForm: <Model extends FormModel>(options: UseFormOptions<Model>) => {
|
|
20
|
+
state: {
|
|
21
|
+
values: Ref<Model, Model>;
|
|
22
|
+
errors: Ref<Partial<Record<Extract<keyof Model, string>, string[]>>, Partial<Record<Extract<keyof Model, string>, string[]>>>;
|
|
23
|
+
touchedFields: Ref<Extract<keyof Model, string>[], Extract<keyof Model, string>[]>;
|
|
24
|
+
dirtyFields: vue.ComputedRef<Extract<keyof Model, string>[]>;
|
|
25
|
+
dirty: vue.ComputedRef<boolean>;
|
|
26
|
+
hasErrors: vue.ComputedRef<boolean>;
|
|
27
|
+
validating: Ref<boolean, boolean>;
|
|
28
|
+
submitting: Ref<boolean, boolean>;
|
|
29
|
+
submitError: Ref<unknown, unknown>;
|
|
30
|
+
submitCount: Ref<number, number>;
|
|
31
|
+
};
|
|
32
|
+
actions: {
|
|
33
|
+
setValue: <Field extends FormField<Model>>(field: Field, value: Model[Field]) => void;
|
|
34
|
+
setValues: (nextValues: Partial<Model>) => void;
|
|
35
|
+
setErrors: (nextErrors: FormErrorInput<Model>) => void;
|
|
36
|
+
clearErrors: (fields?: FieldInput<Model>) => void;
|
|
37
|
+
touch: (fields: FieldInput<Model>) => void;
|
|
38
|
+
validateField: (field: FormField<Model>) => Promise<boolean>;
|
|
39
|
+
validate: () => Promise<boolean>;
|
|
40
|
+
submit: <Result>(handler: (formValues: Model) => Promise<Result> | Result) => Promise<Result | undefined>;
|
|
41
|
+
reset: (nextValues?: Model) => void;
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export { required, useForm };
|
|
46
|
+
export type { FormErrorInput, FormErrors, FormField, FormModel, FormRules, FormValidator, FormValidatorResult, UseFormOptions };
|
package/dist/useForm.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yu-packages/hooks",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Vue Element Plus Admin 通用 Hooks",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts"
|
|
13
|
+
},
|
|
14
|
+
"./useCrud": {
|
|
15
|
+
"import": "./dist/useCrud.js",
|
|
16
|
+
"types": "./dist/useCrud.d.ts"
|
|
17
|
+
},
|
|
18
|
+
"./useForm": {
|
|
19
|
+
"import": "./dist/useForm.js",
|
|
20
|
+
"types": "./dist/useForm.d.ts"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist"
|
|
25
|
+
],
|
|
26
|
+
"sideEffects": false,
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"tsup": "^9.0.0",
|
|
29
|
+
"typescript": "npm:@typescript/typescript6@^6.0.2",
|
|
30
|
+
"vue": "3.5.41"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"vue": ">=3.4.0"
|
|
34
|
+
},
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"license": "MIT",
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsup src/index.ts src/useCrud.ts src/useForm.ts --format esm --dts --sourcemap --clean",
|
|
41
|
+
"typecheck": "tsc6 --noEmit -p tsconfig.json",
|
|
42
|
+
"test": "pnpm --workspace-root exec esno packages/hooks/test/index.ts"
|
|
43
|
+
}
|
|
6
44
|
}
|