@movk/nuxt 1.4.0 → 1.4.2

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.
Files changed (37) hide show
  1. package/README.en.md +308 -0
  2. package/README.md +2 -0
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +1 -1
  5. package/dist/runtime/components/StarRating.d.vue.ts +2 -2
  6. package/dist/runtime/components/StarRating.vue.d.ts +2 -2
  7. package/dist/runtime/components/Tree.vue +61 -17
  8. package/dist/runtime/composables/useApiFetch.d.ts +4 -1
  9. package/dist/runtime/composables/useApiFetch.js +14 -2
  10. package/dist/runtime/domains/api/deep-to-value.d.ts +9 -0
  11. package/dist/runtime/domains/api/deep-to-value.js +11 -0
  12. package/dist/runtime/domains/api/interceptors/compose.d.ts +24 -0
  13. package/dist/runtime/domains/api/interceptors/compose.js +18 -0
  14. package/dist/runtime/domains/auto-form/controls.d.ts +7 -6
  15. package/dist/runtime/domains/data-table/columns/resize.d.ts +4 -0
  16. package/dist/runtime/domains/data-table/columns/resize.js +134 -0
  17. package/dist/runtime/domains/data-table/columns/resolve-data-column.js +3 -46
  18. package/dist/runtime/domains/data-table/columns/resolve-special-columns.js +2 -1
  19. package/dist/runtime/domains/data-table/columns/style.d.ts +1 -0
  20. package/dist/runtime/domains/data-table/columns/style.js +22 -5
  21. package/dist/runtime/domains/tree/components/TreeToolbar.d.vue.ts +2 -0
  22. package/dist/runtime/domains/tree/components/TreeToolbar.vue +6 -1
  23. package/dist/runtime/domains/tree/components/TreeToolbar.vue.d.ts +2 -0
  24. package/dist/runtime/domains/tree/resolve-tree.d.ts +4 -5
  25. package/dist/runtime/domains/tree/resolve-tree.js +2 -1
  26. package/dist/runtime/domains/tree/tree-disabled.d.ts +3 -0
  27. package/dist/runtime/domains/tree/tree-disabled.js +12 -0
  28. package/dist/runtime/domains/tree/tree-icon.d.ts +3 -0
  29. package/dist/runtime/domains/tree/tree-icon.js +5 -0
  30. package/dist/runtime/domains/tree/tree-lazy.d.ts +3 -4
  31. package/dist/runtime/domains/tree/tree-search.d.ts +3 -0
  32. package/dist/runtime/domains/tree/tree-search.js +4 -0
  33. package/dist/runtime/plugins/api.factory.js +9 -3
  34. package/dist/runtime/types/auto-form/zod-factory.d.ts +20 -5
  35. package/dist/runtime/types/components/date-picker.d.ts +3 -0
  36. package/dist/runtime/types/components/tree.d.ts +14 -0
  37. package/package.json +5 -5
package/README.en.md ADDED
@@ -0,0 +1,308 @@
1
+ [![Movk Nuxt](https://nuxt.mhaibaraai.cn/og-image.png)](https://nuxt.mhaibaraai.cn/)
2
+
3
+ English | [简体中文](./README.md)
4
+
5
+ > A UI engineering toolkit built on top of Nuxt UI — Schema-driven AutoForm (Zod v4), a full-featured DataTable, standalone components and Composables. Get the complete capability set in Nuxt 4, including API integration with authentication and progress tracking; its UI, forms, tables, and theming also work directly in plain Vue + Vite projects through a Vite plugin (the API integration domain is Nuxt-only).
6
+
7
+ [![Install MCP in Cursor](https://nuxt.mhaibaraai.cn/mcp/badge.svg)](https://nuxt.mhaibaraai.cn/mcp/deeplink)
8
+ [![Install MCP in VS Code](https://nuxt.mhaibaraai.cn/mcp/badge.svg?ide=vscode)](https://nuxt.mhaibaraai.cn/mcp/deeplink?ide=vscode)
9
+
10
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
11
+ [![Nuxt](https://img.shields.io/badge/Nuxt-4-00DC82.svg)](https://nuxt.com/)
12
+ [![npm version][npm-version-src]][npm-version-href]
13
+ [![npm downloads][npm-downloads-src]][npm-downloads-href]
14
+ [![License][license-src]][license-href]
15
+ [![Nuxt UI][nuxt-ui-src]][nuxt-ui-href]
16
+
17
+ - 📖 [Online Documentation](https://nuxt.mhaibaraai.cn)
18
+
19
+ ## ✨ Features
20
+
21
+ Movk Nuxt is a UI engineering toolkit built on top of Nuxt UI, offering two ways to use it: the complete capability set with API integration in **Nuxt 4**, or its UI layer in plain **Vue + Vite** projects through a **Vite plugin**. The supported frameworks for each capability are:
22
+
23
+ - **AutoForm — Schema-driven forms** (✅ Nuxt | ✅ Vue + Vite) - Built on Zod v4 with a "define-is-render" model: a single Schema declares the data structure, validation rules, and UI configuration at once, automatically generating a complete form interface.
24
+ - **DataTable — Data table** (✅ Nuxt | ✅ Vue + Vite) - Wraps TanStack Table, covering data columns, special columns (selection / index / expand / actions), tree-structured data, row interactions, appearance customization, pagination, and load-more.
25
+ - **Standalone component library** (✅ Nuxt | ✅ Vue + Vite) - General-purpose UI components such as DatePicker, StarRating, PillGroup, SearchForm, Tree, WithCopy, and ThemePicker, usable on their own without AutoForm.
26
+ - **Theming and Composables** (✅ Nuxt | ✅ Vue + Vite) - Non-server composition functions such as useTheme (theme read/write and export), useMessageBox (imperative dialogs), and useDateFormatter (i18n dates).
27
+ - **API integration system** (✅ Nuxt | ❌ Vue + Vite) - The useApiFetch / useLazyApiFetch / useClientApiFetch trio plus useUploadWithProgress / useDownloadWithProgress, providing multi-endpoint support, automatic authentication, business status-code checks, data unwrapping, Toast notifications, and progress monitoring; **depends on the Nuxt server runtime and is available in Nuxt mode only**.
28
+ - **Type safety** - Full TypeScript type inference, from Schema to form data, with component prop callbacks and event handler types derivable via indexed access.
29
+ - **AI friendly** - Built-in MCP Server and llms.txt, so components, composables, and docs can be retrieved by AI agents.
30
+
31
+ ## 🚀 Getting Started
32
+
33
+ ### Installation
34
+
35
+ ```bash
36
+ # pnpm
37
+ pnpm add @movk/nuxt @nuxt/ui zod
38
+
39
+ # yarn
40
+ yarn add @movk/nuxt @nuxt/ui zod
41
+
42
+ # npm
43
+ npm install @movk/nuxt @nuxt/ui zod
44
+ ```
45
+
46
+ ### Nuxt
47
+
48
+ Register the module in `nuxt.config.ts`:
49
+
50
+ ```ts
51
+ export default defineNuxtConfig({
52
+ modules: ['@movk/nuxt'],
53
+ movk: {
54
+ prefix: 'M' // Component prefix, defaults to 'M'
55
+ }
56
+ })
57
+ ```
58
+
59
+ ### Vue / Vite
60
+
61
+ In a plain Vue + Vite project, use the UI layer (components, theming, AutoForm, DataTable, non-server Composables) through the Vite plugin + Vue plugin. **The API integration domain is not available in this mode.**
62
+
63
+ ```bash
64
+ pnpm add @movk/nuxt @nuxt/ui zod tailwindcss vue-router
65
+ ```
66
+
67
+ ```ts
68
+ // vite.config.ts
69
+ import { defineConfig } from 'vite'
70
+ import vue from '@vitejs/plugin-vue'
71
+ import movk from '@movk/nuxt/vite'
72
+
73
+ export default defineConfig({
74
+ plugins: [vue(), movk()]
75
+ })
76
+ ```
77
+
78
+ ```ts
79
+ // src/main.ts
80
+ import './assets/css/main.css'
81
+ import { createApp } from 'vue'
82
+ import { createRouter, createWebHistory } from 'vue-router'
83
+ import movk from '@movk/nuxt/vue-plugin'
84
+ import App from './App.vue'
85
+
86
+ const router = createRouter({ routes: [], history: createWebHistory() })
87
+ createApp(App).use(router).use(movk).mount('#app')
88
+ ```
89
+
90
+ ```css
91
+ /* src/assets/css/main.css — chains Tailwind CSS + Nuxt UI + Movk theme */
92
+ @import "@movk/nuxt";
93
+ ```
94
+
95
+ Wrap the root component in `<UApp>` (required for Toast / Tooltip / useMessageBox). See [Online Docs · Vue / Vite](https://nuxt.mhaibaraai.cn/docs/getting-started/vue).
96
+
97
+ ### Basic Example
98
+
99
+ Create a simple user registration form:
100
+
101
+ ```vue
102
+ <script setup lang="ts">
103
+ import type { FormSubmitEvent } from '@nuxt/ui'
104
+ import type { z } from 'zod'
105
+
106
+ const { afz } = useAutoForm()
107
+
108
+ // Define the Schema
109
+ const schema = afz.object({
110
+ username: afz.string().min(3).meta({ label: 'Username' }),
111
+ email: afz.email().meta({ label: 'Email' }),
112
+ age: afz.number().min(18).meta({ label: 'Age' })
113
+ })
114
+
115
+ // Type inference
116
+ type Schema = z.output<typeof schema>
117
+
118
+ // Form state
119
+ const form = ref<Partial<Schema>>({})
120
+
121
+ // Submit handler
122
+ async function onSubmit(event: FormSubmitEvent<Schema>) {
123
+ console.log('Submitted data:', event.data)
124
+ }
125
+ </script>
126
+
127
+ <template>
128
+ <MAutoForm :schema="schema" :state="form" @submit="onSubmit" />
129
+ </template>
130
+ ```
131
+
132
+ ## 📦 Core Features
133
+
134
+ ### Standalone Components
135
+
136
+ High-quality, ready-to-use UI components across four categories: input enhancements, forms, feedback, and advanced interactions.
137
+
138
+ ### DataTable - Full-featured Data Table
139
+
140
+ `MDataTable`, wrapping TanStack Table, driven by declarative column configuration:
141
+
142
+ ```ts
143
+ import type { DataTableColumn } from '@movk/nuxt'
144
+
145
+ const columns: DataTableColumn<Person>[] = [
146
+ { type: 'selection' }, // Special column: row selection
147
+ { accessorKey: 'name', header: 'Name', sortable: true, pinable: true },
148
+ { accessorKey: 'salary', header: 'Salary', sortable: true, truncate: true },
149
+ { type: 'actions', actions: row => [{ label: 'Edit', onClick: () => edit(row) }] }
150
+ ]
151
+ ```
152
+
153
+ Supports data columns (sorting / column pinning / column resize / truncate + Tooltip / visibility), special columns (selection / index / expand / actions / grouping), tree-structured data with cascading selection, row interactions (click / expand / context menu), appearance customization, client/server-side pagination, and load-more.
154
+
155
+ ### AutoForm - Schema-driven Form System
156
+
157
+ A "define-is-render" form solution based on Zod Schemas:
158
+
159
+ ```ts
160
+ const { afz } = useAutoForm()
161
+
162
+ const schema = afz.object({
163
+ // Basic types
164
+ username: afz.string().min(3),
165
+ age: afz.number().min(18),
166
+ isActive: afz.boolean(),
167
+
168
+ // Advanced types
169
+ email: afz.email(),
170
+ birthdate: afz.calendarDate(),
171
+ role: afz.enum(['admin', 'user']),
172
+ avatar: afz.file(),
173
+
174
+ // Nested objects
175
+ profile: afz.object({
176
+ bio: afz.string(),
177
+ website: afz.url()
178
+ }),
179
+
180
+ // Arrays
181
+ tags: afz.array(afz.string())
182
+ })
183
+ ```
184
+
185
+ ### Composables
186
+
187
+ #### useDateFormatter
188
+
189
+ A powerful tool for date formatting, parsing, and range handling:
190
+
191
+ ```ts
192
+ const { format, parse, isDateValue, formatRange } = useDateFormatter()
193
+
194
+ // Format a date
195
+ const formatted = format(new Date(), 'iso') // "2024-01-01"
196
+
197
+ // Parse a date string
198
+ const date = parse('2024-01-01', 'iso')
199
+
200
+ // Format a date range
201
+ const range = formatRange({ start: date1, end: date2 }, 'iso')
202
+ ```
203
+
204
+ #### useAutoForm
205
+
206
+ The core logic wrapper for AutoForm:
207
+
208
+ ```ts
209
+ const { afz, defineControl, getAutoFormMetadata } = useAutoForm()
210
+
211
+ // Create a Schema
212
+ const schema = afz.object({
213
+ username: afz.string()
214
+ })
215
+
216
+ // Define a custom control
217
+ const customControl = defineControl({
218
+ component: MyCustomInput,
219
+ controlProps: { class: 'w-full' }
220
+ })
221
+
222
+ // Get field metadata
223
+ const meta = getAutoFormMetadata(schema)
224
+ ```
225
+
226
+ #### useApiFetch
227
+
228
+ An API request wrapper built on Nuxt's useFetch:
229
+
230
+ ```ts
231
+ // Basic usage
232
+ const { data, pending, error } = await useApiFetch<User[]>('/users')
233
+
234
+ // POST request
235
+ const { data } = await useApiFetch<User>('/users', {
236
+ method: 'POST',
237
+ body: { name: 'test' },
238
+ toast: { successMessage: 'Created successfully' }
239
+ })
240
+
241
+ // Use another endpoint
242
+ const { data } = await useApiFetch('/users', { endpoint: 'v2' })
243
+ ```
244
+
245
+ #### useUploadWithProgress
246
+
247
+ File upload with progress monitoring:
248
+
249
+ ```ts
250
+ const { progress, uploading, upload, abort } = useUploadWithProgress()
251
+
252
+ // Upload a file
253
+ await upload('/api/upload', file, {
254
+ fieldName: 'avatar',
255
+ onSuccess: (response) => console.log('Upload succeeded:', response)
256
+ })
257
+ ```
258
+
259
+ #### useDownloadWithProgress
260
+
261
+ File download with progress monitoring:
262
+
263
+ ```ts
264
+ const { progress, downloading, download, abort } = useDownloadWithProgress()
265
+
266
+ // Download a file
267
+ await download('/api/export/report', {
268
+ filename: 'report.pdf',
269
+ onSuccess: (filename) => console.log('Download complete:', filename)
270
+ })
271
+ ```
272
+
273
+ ## 🏗️ Architecture Layers
274
+
275
+ Movk Nuxt adopts a clear layered architecture:
276
+
277
+ - **Core Systems** - AutoForm (Schema-driven forms), DataTable (data table)
278
+ - **API System** - useApiFetch / useLazyApiFetch / useClientApiFetch, useUploadWithProgress, useDownloadWithProgress, providing a complete API request solution
279
+ - **Standalone Components** - Standalone UI components such as DatePicker, StarRating, PillGroup, SearchForm, Tree, WithCopy, and ThemePicker
280
+ - **Composables** - General-purpose composition functions such as useDateFormatter, useTheme, useMessageBox, and useAutoForm
281
+ - **Foundation** - Built on [Nuxt UI](https://ui.nuxt.com), [Zod v4](https://zod.dev), [VueUse](https://vueuse.org), and [TanStack Table](https://tanstack.com/table)
282
+
283
+ ## ⚡ Tech Stack
284
+
285
+ - [Nuxt 4](https://nuxt.com/) - The Intuitive Vue Framework
286
+ - [Nuxt UI](https://ui.nuxt.com/) - A UI Library for Modern Web Apps
287
+ - [Zod v4](https://zod.dev/) - TypeScript-first schema validation
288
+ - [TypeScript](https://www.typescriptlang.org/) - JavaScript with syntax for types
289
+ - [VueUse](https://vueuse.org/) - Collection of Vue Composition Utilities
290
+ - [Vitest](https://vitest.dev/) - Next Generation Testing Framework
291
+
292
+ ## 📄 License
293
+
294
+ [MIT](./LICENSE) License © 2024-PRESENT [YiXuan](https://github.com/mhaibaraai)
295
+
296
+ <!-- Badges -->
297
+
298
+ [npm-version-src]: https://img.shields.io/npm/v/@movk/nuxt?style=flat&colorA=080f12&colorB=1fa669
299
+ [npm-version-href]: https://npmjs.com/package/@movk/nuxt
300
+
301
+ [npm-downloads-src]: https://img.shields.io/npm/dm/@movk/nuxt?style=flat&colorA=080f12&colorB=1fa669
302
+ [npm-downloads-href]: https://npmjs.com/package/@movk/nuxt
303
+
304
+ [license-src]: https://img.shields.io/github/license/mhaibaraai/movk-nuxt.svg?style=flat&colorA=080f12&colorB=1fa669
305
+ [license-href]: https://github.com/mhaibaraai/movk-nuxt/blob/main/LICENSE
306
+
307
+ [nuxt-ui-src]: https://img.shields.io/badge/Nuxt%20UI-4-00DC82?style=flat&colorA=080f12
308
+ [nuxt-ui-href]: https://ui.nuxt.com
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  [![Movk Nuxt](https://nuxt.mhaibaraai.cn/og-image.png)](https://nuxt.mhaibaraai.cn/)
2
2
 
3
+ 简体中文 | [English](./README.en.md)
4
+
3
5
  > 构建在 Nuxt UI 之上的 UI 工程套件 —— Schema 驱动的 AutoForm(Zod v4)、功能完备的 DataTable、独立组件与 Composables。在 Nuxt 4 中获得含认证与进度追踪的 API 集成在内的完整能力;其 UI、表单、表格与主题亦可经 Vite 插件直接用于纯 Vue + Vite 项目(API 集成域仅 Nuxt)。
4
6
 
5
7
  [![Install MCP in Cursor](https://nuxt.mhaibaraai.cn/mcp/badge.svg)](https://nuxt.mhaibaraai.cn/mcp/deeplink)
package/dist/module.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@movk/nuxt",
3
- "version": "1.4.0",
3
+ "version": "1.4.2",
4
4
  "configKey": "movk",
5
5
  "compatibility": {
6
6
  "nuxt": ">=4.4.2"
package/dist/module.mjs CHANGED
@@ -9,7 +9,7 @@ export * from '../dist/runtime/types/index.js';
9
9
  import 'node:url';
10
10
 
11
11
  const name = "@movk/nuxt";
12
- const version = "1.4.0";
12
+ const version = "1.4.2";
13
13
 
14
14
  function getDefaultApiConfig(apiConfig) {
15
15
  const publicEndpoints = {};
@@ -29,12 +29,12 @@ type __VLS_Slots = {} & {
29
29
  };
30
30
  declare const __VLS_base: import("vue").DefineComponent<__VLS_PublicProps, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
31
31
  change: (value: number) => any;
32
- "update:modelValue": (value: number) => any;
33
32
  hover: (value: number | null) => any;
33
+ "update:modelValue": (value: number) => any;
34
34
  }, string, import("vue").PublicProps, Readonly<__VLS_PublicProps> & Readonly<{
35
35
  onChange?: ((value: number) => any) | undefined;
36
- "onUpdate:modelValue"?: ((value: number) => any) | undefined;
37
36
  onHover?: ((value: number | null) => any) | undefined;
37
+ "onUpdate:modelValue"?: ((value: number) => any) | undefined;
38
38
  }>, {
39
39
  max: number;
40
40
  showBadge: boolean;
@@ -29,12 +29,12 @@ type __VLS_Slots = {} & {
29
29
  };
30
30
  declare const __VLS_base: import("vue").DefineComponent<__VLS_PublicProps, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
31
31
  change: (value: number) => any;
32
- "update:modelValue": (value: number) => any;
33
32
  hover: (value: number | null) => any;
33
+ "update:modelValue": (value: number) => any;
34
34
  }, string, import("vue").PublicProps, Readonly<__VLS_PublicProps> & Readonly<{
35
35
  onChange?: ((value: number) => any) | undefined;
36
- "onUpdate:modelValue"?: ((value: number) => any) | undefined;
37
36
  onHover?: ((value: number | null) => any) | undefined;
37
+ "onUpdate:modelValue"?: ((value: number) => any) | undefined;
38
38
  }>, {
39
39
  max: number;
40
40
  showBadge: boolean;
@@ -1,15 +1,17 @@
1
1
  <script setup>
2
2
  import { computed, ref, useSlots, watch } from "vue";
3
3
  import { reactiveOmit } from "@vueuse/core";
4
- import { Tree, omitUndefined, splitHighlight } from "@movk/core";
4
+ import { Tree, omitUndefined, splitHighlight, getPath } from "@movk/core";
5
5
  import { UCheckbox, UIcon, UTree } from "#components";
6
6
  import { useAppConfig } from "#imports";
7
7
  import { useExtendedTv } from "../utils/extend-theme";
8
8
  import treeTheme from "#build/ui/tree";
9
9
  import theme from "#build/movk-ui/tree";
10
10
  import { createGetKey, normalizeChildren } from "../domains/tree/resolve-tree";
11
- import { matchLabel } from "../domains/tree/tree-search";
11
+ import { resolveLeadingIcon } from "../domains/tree/tree-icon";
12
+ import { matchNode } from "../domains/tree/tree-search";
12
13
  import { isPlaceholder, LAZY_KEY_FIELD, markLazyPlaceholders } from "../domains/tree/tree-lazy";
14
+ import { collectDisabledKeys } from "../domains/tree/tree-disabled";
13
15
  import { computeTreeSelection, selectionSummary } from "../utils/tree-selection";
14
16
  import { resolveDefaultExpandedKeys } from "../utils/tree-expand";
15
17
  import TreeToolbar from "../domains/tree/components/TreeToolbar.vue";
@@ -26,6 +28,9 @@ const props = defineProps({
26
28
  bubbleSelect: { type: Boolean, required: false },
27
29
  size: { type: null, required: false },
28
30
  color: { type: null, required: false },
31
+ expandedIcon: { type: null, required: false },
32
+ collapsedIcon: { type: null, required: false },
33
+ disabled: { type: Boolean, required: false },
29
34
  searchable: { type: Boolean, required: false },
30
35
  filter: { type: Function, required: false },
31
36
  highlight: { type: Boolean, required: false, default: true },
@@ -33,7 +38,8 @@ const props = defineProps({
33
38
  loadChildren: { type: Function, required: false },
34
39
  toolbar: { type: Boolean, required: false },
35
40
  checkable: { type: Boolean, required: false },
36
- ui: { type: Object, required: false }
41
+ ui: { type: Object, required: false },
42
+ class: { type: null, required: false }
37
43
  });
38
44
  const emit = defineEmits(["update:modelValue", "update:expanded", "update:search", "change"]);
39
45
  defineSlots();
@@ -45,6 +51,12 @@ const expanded = defineModel("expanded", { type: Array, ...{ default: () => [] }
45
51
  const slots = useSlots();
46
52
  const appConfig = useAppConfig();
47
53
  const labelKey = computed(() => props.labelKey ?? "label");
54
+ function folderIcon(expanded2) {
55
+ return expanded2 ? props.expandedIcon ?? appConfig.ui?.icons?.folderOpen ?? "i-lucide-folder-open" : props.collapsedIcon ?? appConfig.ui?.icons?.folder ?? "i-lucide-folder";
56
+ }
57
+ function leadingIcon(node, expanded2) {
58
+ return resolveLeadingIcon(node, folderIcon(expanded2));
59
+ }
48
60
  const getKey = computed(() => createGetKey(props.getKey, labelKey.value));
49
61
  const { baseUi, extraUi } = useExtendedTv(
50
62
  treeTheme,
@@ -74,13 +86,26 @@ watch(() => props.items, (items) => {
74
86
  }
75
87
  }, { immediate: true });
76
88
  const searching = computed(() => !!(props.searchable && search.value.trim()));
89
+ const disabledKeys = computed(() => collectDisabledKeys(baseItems.value, getKey.value));
90
+ function applyDisabled(nodes) {
91
+ if (!disabledKeys.value.size) return nodes;
92
+ const inject = (list) => list.map((node) => {
93
+ const rawChildren = node.children;
94
+ const children = Array.isArray(rawChildren) ? inject(rawChildren) : rawChildren;
95
+ const disabled = disabledKeys.value.has(getKey.value(node));
96
+ if (!disabled && children === rawChildren) return node;
97
+ return {
98
+ ...node,
99
+ ...disabled ? { disabled: true } : null,
100
+ ...children !== rawChildren ? { children } : null
101
+ };
102
+ });
103
+ return inject(nodes);
104
+ }
77
105
  const displayItems = computed(() => {
78
- if (!searching.value) return baseItems.value;
79
106
  const term = search.value;
80
- return Tree.filter(
81
- baseItems.value,
82
- ({ node }) => props.filter ? props.filter(node, term) : matchLabel(node[labelKey.value], term)
83
- );
107
+ const filtered = !searching.value ? baseItems.value : Tree.filter(baseItems.value, ({ node }) => props.filter ? props.filter(node, term) : matchNode(node, labelKey.value, term));
108
+ return applyDisabled(filtered);
84
109
  });
85
110
  const isEmpty = computed(() => searching.value && displayItems.value.length === 0);
86
111
  watch([searching, displayItems], () => {
@@ -89,8 +114,10 @@ watch([searching, displayItems], () => {
89
114
  }
90
115
  });
91
116
  const loadingKeys = ref(/* @__PURE__ */ new Set());
92
- async function onExpandedUpdate(keys) {
117
+ async function onExpandedUpdate(incoming) {
118
+ if (props.disabled) return;
93
119
  const previous = expanded.value;
120
+ const keys = disabledKeys.value.size ? [...incoming.filter((k) => !disabledKeys.value.has(k)), ...previous.filter((k) => disabledKeys.value.has(k))] : incoming;
94
121
  expanded.value = keys;
95
122
  if (!props.lazy || !props.loadChildren) return;
96
123
  for (const key of keys.filter((k) => !previous.includes(k))) {
@@ -150,12 +177,12 @@ const utreeProps = computed(() => {
150
177
  const RESERVED_SLOTS = ["toolbar", "toolbar-leading", "toolbar-trailing", "empty", "loading"];
151
178
  const forwardSlots = computed(() => Object.keys(slots).filter((name) => !RESERVED_SLOTS.includes(name)));
152
179
  function nodeLabel(node) {
153
- const value = node[labelKey.value];
180
+ const value = getPath(node, labelKey.value);
154
181
  return value == null ? "" : String(value);
155
182
  }
156
183
  const isMultiple = computed(() => !!(props.checkable || props.multiple));
157
184
  const selectableNodes = computed(
158
- () => Tree.findAll(baseItems.value, ({ node }) => !isPlaceholder(node) && !node.disabled)
185
+ () => Tree.findAll(baseItems.value, ({ node }) => !isPlaceholder(node) && !disabledKeys.value.has(getKey.value(node)))
159
186
  );
160
187
  const nodesByKey = computed(() => {
161
188
  const map = /* @__PURE__ */ new Map();
@@ -184,7 +211,7 @@ const treeSelection = computed(
184
211
  })
185
212
  );
186
213
  const selectableLeafCount = computed(
187
- () => Tree.findAll(baseItems.value, ({ node }) => !isPlaceholder(node) && !node.disabled && !(Array.isArray(node.children) && node.children.length > 0)).length
214
+ () => Tree.findAll(baseItems.value, ({ node }) => !isPlaceholder(node) && !disabledKeys.value.has(getKey.value(node)) && !(Array.isArray(node.children) && node.children.length > 0)).length
188
215
  );
189
216
  const selectionSummaryValue = computed(
190
217
  () => selectionSummary(treeSelection.value.leaves.length, selectableLeafCount.value)
@@ -199,6 +226,15 @@ function setModel(value) {
199
226
  });
200
227
  emit("change", { value, keys, selection });
201
228
  }
229
+ function onModelUpdate(value) {
230
+ if (props.disabled) return;
231
+ if (Array.isArray(value)) {
232
+ setModel(value.filter((node) => !node.disabled));
233
+ return;
234
+ }
235
+ if (value && value.disabled) return;
236
+ setModel(value);
237
+ }
202
238
  const expandableKeys = computed(
203
239
  () => Tree.findAll(baseItems.value, ({ node }) => !!node.children?.length).map((n) => getKey.value(n))
204
240
  );
@@ -240,7 +276,7 @@ defineExpose({
240
276
  </script>
241
277
 
242
278
  <template>
243
- <div :class="extraUi.container">
279
+ <div :class="extraUi.container" data-slot="container">
244
280
  <slot
245
281
  v-if="props.toolbar || props.searchable || slots.toolbar"
246
282
  name="toolbar"
@@ -251,6 +287,7 @@ defineExpose({
251
287
  :select-all="selectAll"
252
288
  :clear="clearSelection"
253
289
  :search="search"
290
+ :disabled="props.disabled"
254
291
  :selection-summary="selectionSummaryValue"
255
292
  >
256
293
  <TreeToolbar
@@ -260,6 +297,7 @@ defineExpose({
260
297
  :search="search"
261
298
  :size="props.size"
262
299
  :color="props.color"
300
+ :disabled="props.disabled"
263
301
  :expanded="allExpanded"
264
302
  :selection-summary="selectionSummaryValue"
265
303
  :ui="{ toolbar: extraUi.toolbar, toolbarButton: extraUi.toolbarButton, search: extraUi.search }"
@@ -277,7 +315,7 @@ defineExpose({
277
315
  </TreeToolbar>
278
316
  </slot>
279
317
 
280
- <div v-if="isEmpty" :class="extraUi.empty">
318
+ <div v-if="isEmpty" :class="extraUi.empty" data-slot="empty">
281
319
  <slot name="empty">
282
320
  无匹配结果
283
321
  </slot>
@@ -290,27 +328,33 @@ defineExpose({
290
328
  :model-value="effectiveModel"
291
329
  :expanded="expanded"
292
330
  :ui="baseUi"
293
- @update:model-value="setModel($event)"
331
+ @update:model-value="onModelUpdate($event)"
294
332
  @update:expanded="onExpandedUpdate"
295
333
  >
296
334
  <template v-for="name in forwardSlots" #[name]="slotProps" :key="name">
297
335
  <slot :name="name" v-bind="slotProps ?? {}" />
298
336
  </template>
299
337
 
300
- <template v-if="props.checkable && !slots['item-leading']" #item-leading="{ item, selected, indeterminate, handleSelect }">
338
+ <template v-if="props.checkable && !slots['item-leading']" #item-leading="{ item, expanded: nodeExpanded, selected, indeterminate, handleSelect, ui: nodeUi }">
301
339
  <UCheckbox
302
340
  v-if="!isPlaceholder(item)"
303
341
  :model-value="indeterminate ? 'indeterminate' : selected"
304
342
  :size="props.size"
305
343
  :color="props.color"
344
+ :disabled="item.disabled || props.disabled"
306
345
  :class="extraUi.checkbox"
307
346
  tabindex="-1"
308
347
  @change="handleSelect"
309
348
  @click.stop
310
349
  />
350
+ <UIcon
351
+ v-if="leadingIcon(item, nodeExpanded)"
352
+ :name="leadingIcon(item, nodeExpanded)"
353
+ :class="nodeUi.linkLeadingIcon({ class: item.ui?.linkLeadingIcon })"
354
+ />
311
355
  </template>
312
356
 
313
- <template v-if="!slots['item-label']" #item-label="{ item }">
357
+ <template v-if="!slots['item-label'] && (props.lazy || searching && props.highlight)" #item-label="{ item }">
314
358
  <slot v-if="isPlaceholder(item)" name="loading" :node="item">
315
359
  <span :class="extraUi.loading">
316
360
  <UIcon name="i-lucide-loader-circle" :class="extraUi.loadingIcon" />加载中
@@ -38,13 +38,16 @@ import type { UseApiFetchOptions, UseApiFetchReturn } from '../types/api';
38
38
  * // 跳过解包,拿原始响应(与 skipBusinessCheck 正交)
39
39
  * const { data } = await useApiFetch<ApiResponse>('/external', { skipUnwrap: true })
40
40
  *
41
- * // 用户自定义 hooks(通过 useFetch 原生选项透传)
41
+ * // 用户自定义 hooks:与内置拦截器组合(内置先执行),不会覆盖认证/业务校验/解包/Toast
42
42
  * const { data } = await useApiFetch('/users', {
43
43
  * onResponse({ response }) {
44
44
  * // response._data 已是解包后的业务数据(除非传入 skipUnwrap: true)
45
+ * // 仅业务成功时触发;返回值被 ofetch 忽略,副作用专用
45
46
  * console.log('自定义处理:', response._data)
46
47
  * }
47
48
  * })
49
+ *
50
+ * // 变形输出请用 transform 或直接消费自动解包后的 data,而非在 onResponse 中 return
48
51
  * ```
49
52
  */
50
53
  export declare function useApiFetch<T = unknown, DataT = T>(url: NitroFetchRequest | (() => NitroFetchRequest), options?: UseApiFetchOptions<T, DataT>): UseApiFetchReturn<DataT>;
@@ -1,6 +1,8 @@
1
1
  import { computed, toValue } from "vue";
2
2
  import { useNuxtApp, useFetch } from "#app";
3
3
  import { buildApiFetchKey } from "../domains/api/fetch-key.js";
4
+ import { deepToValue } from "../domains/api/deep-to-value.js";
5
+ import { composeHook, getInterceptors } from "../domains/api/interceptors/compose.js";
4
6
  export function useApiFetch(url, options = {}) {
5
7
  const { $api } = useNuxtApp();
6
8
  const {
@@ -11,6 +13,15 @@ export function useApiFetch(url, options = {}) {
11
13
  ...fetchOptions
12
14
  } = options;
13
15
  const apiInstance = endpoint ? $api.use(endpoint) : $api;
16
+ const movk = getInterceptors(apiInstance);
17
+ const composedHooks = movk ? {
18
+ onRequest: composeHook(movk.onRequest, fetchOptions.onRequest),
19
+ onResponse: composeHook(movk.onResponse, fetchOptions.onResponse),
20
+ onResponseError: composeHook(movk.onResponseError, fetchOptions.onResponseError)
21
+ } : {};
22
+ const definedHooks = Object.fromEntries(
23
+ Object.entries(composedHooks).filter(([, value]) => value !== void 0)
24
+ );
14
25
  const fetchKey = computed(() => {
15
26
  const userKey = toValue(fetchOptions.key);
16
27
  if (userKey) return userKey;
@@ -21,12 +32,13 @@ export function useApiFetch(url, options = {}) {
21
32
  toast,
22
33
  method: toValue(fetchOptions.method),
23
34
  url: typeof url === "function" ? url() : url,
24
- query: toValue(fetchOptions.query),
25
- body: toValue(fetchOptions.body)
35
+ query: deepToValue(fetchOptions.query),
36
+ body: deepToValue(fetchOptions.body)
26
37
  });
27
38
  });
28
39
  return useFetch(url, {
29
40
  ...fetchOptions,
41
+ ...definedHooks,
30
42
  key: fetchKey,
31
43
  $fetch: apiInstance,
32
44
  context: { toast, skipBusinessCheck, skipUnwrap }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * 递归解包嵌套 ref,产出纯值结构
3
+ *
4
+ * @description Vue 的 toValue 仅解包顶层 ref,不会解包普通对象 / 数组内部的嵌套 ref。
5
+ * useApiFetch 的 query / body 常写成 `{ key: ref }`(Nuxt useFetch 允许字段为 ref),
6
+ * 若仅浅解包,buildApiFetchKey 序列化时会把 Ref 对象本身计入,导致不同值派生出相同 key 而缓存碰撞。
7
+ * 仅对纯对象 / 数组递归;Date / File / FormData 等非纯对象原样返回,避免破坏与栈溢出。
8
+ */
9
+ export declare function deepToValue(value: unknown): unknown;
@@ -0,0 +1,11 @@
1
+ import { toValue } from "vue";
2
+ export function deepToValue(value) {
3
+ const resolved = toValue(value);
4
+ if (Array.isArray(resolved)) return resolved.map(deepToValue);
5
+ if (resolved !== null && typeof resolved === "object" && Object.getPrototypeOf(resolved) === Object.prototype) {
6
+ return Object.fromEntries(
7
+ Object.entries(resolved).map(([k, v]) => [k, deepToValue(v)])
8
+ );
9
+ }
10
+ return resolved;
11
+ }