diff --git a/AGENTS.md b/AGENTS.md index 2c0d3df..6261959 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -425,3 +425,13 @@ Vaul Vue 官方已说明停止维护并推荐 Reka Drawer;新项目不采用 V - 逻辑数据全集与挂载 registry 分开。虚拟导航先滚动再等 DOM 聚焦,异步焦点请求可被新请求或卸载取消;用户滚动卸载焦点行时不跳回首行。全选/范围/搜索不能只看可见窗口。 - 连续 typeahead 在当前项仍匹配时保留它;重复首字母才循环下一项。空 key / 数字 0 不得被真值判断排除;none 模式不显示遗留的选中状态。 - Root 与公开 Props 共用 ListBoxOptions 明确 schema,泛型 SFC 的 Parameters 提取曾让反例失效。后续泛型组件也必须做产物类型正反例,不能用 any 修复。 + +## SELECT-01 迁移经验(2026-10-23) + +- Select 六部件与十九例已实现,自动化验证和浏览器待验范围见 [SELECT-01](docs/migrations/SELECT-01-select.md)。不能把此前“Select 未实现”的历史描述当作当前状态,也不能把代码已落地等同完整验收。 +- 复用 Popover 时核对真正节点的 role、data-slot、aria-haspopup 与 controls:通用 dialog 默认值会覆盖字段 listbox 语义。显式部件透传放到实际 asChild 原生节点,通用默认行为保留回归。 +- 非模态不代表 Tab 不循环;Reka Popover FocusScope 默认 loop。字段复合组件要明确原生 Tab 起点与 Portal 顺序,复用现有栈,不能新增全局导航监听队列。 +- 表单可见值、原生提交、自动填充和 reset 同时验;受控值未变化时 Vue 不一定重写被浏览器 reset 的 option。原生层显式恢复接受值,数字/字符串 key 通过 option 索引恢复,内部编码不得进入提交。 +- SSR 的关闭态元数据必须先于 Value/原生选项渲染;未知包装要求显式完整 items。动态移除不得保留成功提交,布尔属性的空字符串按 true 处理,不执行用户任意 setup/render 来取文字。 +- 清空控件使用非 button、计数注册、实际 Trigger 禁用及原生取消协议;十九例同页检查 ID,异步例不能以静态假数据替代,分页失败重试和卸载 AbortSignal 都要测。 +- 本轮浏览器工具 URL 安全策略阻断,不绕过、不写成已验证;代码/SSR/水合/独立产物与真实几何/动效的结论分开,补验前留在任务分支。 diff --git a/apps/docs/.vitepress/theme/Layout.vue b/apps/docs/.vitepress/theme/Layout.vue index 56509fa..83541dc 100644 --- a/apps/docs/.vitepress/theme/Layout.vue +++ b/apps/docs/.vitepress/theme/Layout.vue @@ -101,6 +101,7 @@ const groups = [ { title: "NumberField 数字输入框", url: "/components/number-field" }, { title: "Slider 滑块", url: "/components/slider" }, { title: "ListBox 列表框", url: "/components/list-box" }, + { title: "Select 选择器", url: "/components/select" }, { title: "Tooltip 工具提示", url: "/components/tooltip" }, { title: "ToggleButton 切换按钮", diff --git a/apps/docs/components/select.md b/apps/docs/components/select.md new file mode 100644 index 0000000..206d803 --- /dev/null +++ b/apps/docs/components/select.md @@ -0,0 +1,348 @@ +--- +title: Select 选择器 +description: Select 展示可折叠的选项列表,并允许用户从中选择一项。 +component: select +group: 组件 +--- + +## 用法 + +```vue + +``` + + + +## 组件结构 + +```vue + + +``` + +## 示例 + +### 变体 + +Select 组件支持两种视觉变体: + +- **`primary`**(默认)— 带阴影的标准样式,适用于大多数场景 +- **`secondary`** — 低强调、无阴影,适合在 Surface 等表面背景上使用 + + + +### 宽度充满 + + + +### 带描述 + + + +### 必填 + + + +### 禁用 + + + +### 含禁用选项 + + + +### 多选 + + + +### 分组选项 + + + +### 受控组件 + + + +### 受控多选 + + + +### 受控展开状态 + + + +### 异步加载 + +Vue 使用响应式数组、Fetch 与 VueUse 可见性观察加载 PokeAPI 分页;保留取消、加载中、错误重试和手动加载入口,不导出 React Collection / ListBoxLoadMoreItem。 + + + +### 自定义指示器 + + + +### 带清除按钮 + +`SelectTrigger` 本身是 button,因此不能再嵌套 ``, + ); + await trigger(w).trigger("click"); + await flushPromises(); + const event = new KeyboardEvent("keydown", { + key: "Tab", + bubbles: true, + cancelable: true, + }); + option(0).dispatchEvent(event); + await flushPromises(); + expect(event.defaultPrevented).toBe(false); + expect(document.activeElement).toBe(trigger(w).element); + expect(trigger(w).attributes("aria-expanded")).toBe("false"); + }); + it("keeps controlled native selected options on reset even when Vue props did not change", async () => { + const value = ref("last"); + const w = fixture( + `
`, + () => ({ value }), + ); + value.value = 0; + await flushPromises(); + (w.get("form").element as HTMLFormElement).reset(); + await flushPromises(); + expect(w.get('[data-slot="select-value"]').text()).toBe("Zero number"); + expect(data()).toEqual([["choice", "0"]]); + }); +}); + +describe("Select hydration and baseline demos", () => { + it("hydrates default closed metadata, IDs and native selection without mismatches", async () => { + const Component = defineComponent({ + components, + template: ``, + }); + const host = document.createElement("div"); + host.innerHTML = await renderToString(createSSRApp(Component)); + document.body.append(host); + const before = host.querySelector('[data-slot="select-trigger"]'); + const warnings: string[] = []; + const app = createSSRApp(Component); + app.config.warnHandler = (message) => warnings.push(message); + app.mount(host); + await flushPromises(); + try { + expect(warnings).toEqual([]); + expect(host.querySelector('[data-slot="select-trigger"]')).toBe(before); + expect( + host.querySelector("select")?.selectedOptions[0].dataset.index, + ).toBe("0"); + } finally { + app.unmount(); + } + }); + it("mounts all nineteen source demos with unique IDs and real async data", async () => { + const original = globalThis.fetch; + globalThis.fetch = async () => + new Response( + JSON.stringify({ next: null, results: [{ name: "bulbasaur" }] }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + try { + const demos = import.meta.glob("../apps/docs/demos/select-*.vue", { + eager: true, + import: "default", + }); + expect(Object.keys(demos)).toHaveLength(19); + const warnings: string[] = []; + const w = mount( + defineComponent({ + render: () => + h( + "main", + Object.values(demos).map((component) => + h(component as ReturnType), + ), + ), + }), + { + attachTo: document.body, + global: { + config: { warnHandler: (message) => warnings.push(message) }, + }, + }, + ); + wrappers.push(w); + await flushPromises(); + expect(warnings).toEqual([]); + const ids = w.findAll("[id]").map((node) => node.attributes("id")); + expect(new Set(ids).size).toBe(ids.length); + expect(w.findAll('[data-slot="select-trigger"]')).toHaveLength(23); + const asyncDemo = w + .findAllComponents(Select) + .find( + (component) => component.props("placeholder") === "请选择宝可梦", + )!; + expect(asyncDemo.get("select").text()).toContain("bulbasaur"); + } finally { + globalThis.fetch = original; + } + }); +}); + +describe("Select names, cancellation and closed keyboard", () => { + it("moves focus on field Label click without opening the menu", async () => { + const w = fixture(``); + await w.get('[data-slot="label"]').trigger("click"); + expect(document.activeElement).toBe(trigger(w).element); + expect(trigger(w).attributes("aria-expanded")).toBe("false"); + }); + it("supports closed typeahead and skips disabled options without editing during IME", async () => { + const w = fixture( + ``, + ); + for (const key of ["l", "i", "a", "m"]) + await trigger(w).trigger("keydown", { key }); + expect(w.get('[data-slot="select-value"]').text()).toBe("Liam Smith"); + expect(w.getComponent(Select).emitted("change")).toEqual([["a"]]); + await trigger(w).trigger("keydown", { key: "m", isComposing: true }); + expect(w.getComponent(Select).emitted("change")).toHaveLength(1); + expect(trigger(w).attributes("aria-expanded")).toBe("false"); + }); + it("respects ListBox activation cancellation before selection or closing", async () => { + const w = fixture( + ``, + ); + await trigger(w).trigger("click"); + await flushPromises(); + option(0).dispatchEvent( + new KeyboardEvent("keydown", { + key: "Enter", + bubbles: true, + cancelable: true, + }), + ); + await flushPromises(); + expect(w.getComponent(Select).emitted("change")).toBeUndefined(); + expect(trigger(w).attributes("aria-expanded")).toBe("true"); + }); + it("keeps aria validation nonblocking and refreshes Form server errors", async () => { + const errors = ref>({ choice: "Server error" }); + const w = fixture( + `
`, + () => ({ errors }), + ); + expect(trigger(w).attributes("aria-invalid")).toBe("true"); + expect(w.text()).toContain("Server error"); + expect( + w.get('input[type="checkbox"]').element.checkValidity(), + ).toBe(true); + await trigger(w).trigger("click"); + await flushPromises(); + await clickOption(0); + expect(w.text()).not.toContain("Server error"); + errors.value = { choice: "Refreshed" }; + await flushPromises(); + expect(w.text()).toContain("Refreshed"); + }); +}); + +describe("Select metadata and identity", () => { + it("retains empty-string identities through native form submission", async () => { + const w = fixture( + `
`, + ); + expect(data()).toEqual([["choice", ""]]); + expect(w.get('[data-slot="select-value"]').text()).toBe("Empty key"); + await trigger(w).trigger("click"); + await flushPromises(); + expect(option(0).getAttribute("aria-selected")).toBe("true"); + }); + it("associates an external form dynamically and restores reset values", async () => { + const owner = ref("one"); + const w = fixture( + `
`, + () => ({ owner }), + ); + owner.value = "two"; + await flushPromises(); + await trigger(w).trigger("keydown", { key: "Delete" }); + (w.get("#one").element as HTMLFormElement).reset(); + await flushPromises(); + expect( + w.get('[data-slot="select-value"]').attributes("data-placeholder"), + ).toBe("true"); + (w.get("#two").element as HTMLFormElement).reset(); + await flushPromises(); + expect( + new FormData(w.get("#two").element as HTMLFormElement).get("choice"), + ).toBe("last"); + }); + it("refreshes explicit asynchronous selected metadata before opening", async () => { + const items = ref<{ id: number; textValue: string }[]>([]); + const w = fixture( + `
`, + () => ({ items }), + ); + expect(data()).toEqual([]); + items.value = [{ id: 0, textValue: "Loaded label" }]; + await flushPromises(); + expect(w.get('[data-slot="select-value"]').text()).toBe("Loaded label"); + expect(data()).toEqual([["choice", "0"]]); + items.value = []; + await flushPromises(); + expect(data()).toEqual([]); + }); + it("gives root accessible names to the popup list and keeps cancellation intact", async () => { + const w = fixture(``); + await trigger(w).trigger("click"); + await flushPromises(); + expect( + document.querySelector('[role="listbox"]')?.getAttribute("aria-label"), + ).toBe("Root name"); + }); +}); + +describe("Select integration boundaries", () => { + it("keeps a nested Modal open when its Select handles Escape", async () => { + const w = fixture( + `Open modalParent dialog`, + ); + await w.get('[data-slot="modal-trigger"]').trigger("click"); + await flushPromises(); + const selectTrigger = document.querySelector( + '[data-slot="select-trigger"]', + )!; + selectTrigger.click(); + await flushPromises(); + expect(option(0)).toBeTruthy(); + option(0).dispatchEvent( + new KeyboardEvent("keydown", { + key: "Escape", + bubbles: true, + cancelable: true, + }), + ); + await flushPromises(); + expect(document.querySelector('[role="dialog"]')).not.toBeNull(); + expect(selectTrigger.getAttribute("aria-expanded")).toBe("false"); + }); + it("honors open autofocus cancellation and native handler array stop semantics", async () => { + const calls: string[] = []; + const stop = (event: Event) => { + calls.push("first"); + event.stopImmediatePropagation(); + }; + const second = () => calls.push("second"); + const w = fixture( + ``, + () => ({ stop, second }), + ); + await trigger(w).trigger("keydown", { key: "ArrowDown" }); + expect(calls).toEqual(["first"]); + expect(trigger(w).attributes("aria-expanded")).toBe("false"); + (trigger(w).element as HTMLElement).focus(); + await trigger(w).trigger("click"); + await flushPromises(); + expect(document.activeElement).toBe(trigger(w).element); + }); + it("honors per-item cancellation before changing or closing", async () => { + const w = fixture( + ``, + ); + await trigger(w).trigger("click"); + await flushPromises(); + await clickOption(0); + expect(w.getComponent(Select).emitted("change")).toBeUndefined(); + expect(trigger(w).attributes("aria-expanded")).toBe("true"); + }); +}); + +describe("Select async demo lifecycle", () => { + it("loads a second page, retains existing options on failure, and retries", async () => { + const original = globalThis.fetch; + const cursors: string[] = []; + let call = 0; + globalThis.fetch = async (input) => { + cursors.push(String(input)); + call++; + if (call === 2) return new Response("", { status: 503 }); + return new Response( + JSON.stringify( + call === 1 + ? { + next: "https://pokeapi.co/api/v2/pokemon?offset=20", + results: [{ name: "bulbasaur" }], + } + : { next: null, results: [{ name: "ivysaur" }] }, + ), + { status: 200 }, + ); + }; + try { + const { default: Demo } = + await import("../apps/docs/demos/select-asynchronous-loading.vue"); + const w = mount(Demo, { attachTo: document.body }); + wrappers.push(w); + await flushPromises(); + await trigger(w).trigger("click"); + await flushPromises(); + const more = [ + ...document.querySelectorAll( + '[data-slot="select-popover"] button', + ), + ].find((button) => button.textContent?.includes("加载更多"))!; + more.click(); + await flushPromises(); + expect(w.get("select").text()).toContain("bulbasaur"); + const retry = [ + ...document.querySelectorAll( + '[data-slot="select-popover"] button', + ), + ].find((button) => button.textContent?.includes("重试"))!; + expect(retry).toBeTruthy(); + retry.click(); + await flushPromises(); + await vi.waitFor(() => + expect(w.get("select").text()).toContain("ivysaur"), + ); + expect(cursors).toEqual([ + "https://pokeapi.co/api/v2/pokemon", + "https://pokeapi.co/api/v2/pokemon?offset=20", + "https://pokeapi.co/api/v2/pokemon?offset=20", + ]); + } finally { + globalThis.fetch = original; + } + }); + it("aborts the pending request on unmount", async () => { + const original = globalThis.fetch; + let signal: AbortSignal | undefined; + globalThis.fetch = async (_input, init) => { + signal = init?.signal ?? undefined; + return new Promise(() => {}); + }; + try { + const { default: Demo } = + await import("../apps/docs/demos/select-asynchronous-loading.vue"); + const w = mount(Demo, { attachTo: document.body }); + expect(signal?.aborted).toBe(false); + w.unmount(); + expect(signal?.aborted).toBe(true); + } finally { + globalThis.fetch = original; + } + }); +}); + +describe("Select dynamic mode", () => { + it("adapts uncontrolled single/multiple shapes and reset without synthetic edits", async () => { + const mode = ref<"single" | "multiple">("single"); + const w = fixture( + `
`, + () => ({ mode }), + ); + mode.value = "multiple"; + await flushPromises(); + expect(data()).toEqual([["choice", "last"]]); + await trigger(w).trigger("click"); + await flushPromises(); + await clickOption(0); + expect(w.getComponent(Select).emitted("change")).toEqual([[["last", 0]]]); + mode.value = "single"; + await flushPromises(); + expect(data()).toEqual([["choice", "last"]]); + (w.get("form").element as HTMLFormElement).reset(); + await flushPromises(); + expect(data()).toEqual([["choice", "last"]]); + expect(w.getComponent(Select).emitted("change")).toHaveLength(1); + }); +}); + +it("keeps locally disabled options out of the native submission even with explicit text metadata", () => { + const w = fixture( + `
`, + ); + expect(data()).toEqual([]); + expect(w.get('[data-slot="select-value"]').text()).toBe("Alpha"); +});