feat: establish private collection selection foundation
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createSSRApp, defineComponent, h } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import Foundation from "../packages/vue/tests/fixtures/CollectionFoundation.vue";
|
||||
import SelectFoundation from "../packages/vue/tests/fixtures/SelectFoundation.vue";
|
||||
import { useCollectionRegistry } from "../packages/vue/src/components/collection/registry";
|
||||
import { useCollectionSelection } from "../packages/vue/src/components/collection/selection";
|
||||
|
||||
describe("collection foundation in real node SSR", () => {
|
||||
it("renders typed selection without browser globals", async () => {
|
||||
expect(typeof window).toBe("undefined");
|
||||
const html = await renderToString(
|
||||
createSSRApp(Foundation, { multiple: true, modelValue: [0] }),
|
||||
);
|
||||
expect(html).toContain('role="listbox"');
|
||||
expect(html.match(/aria-selected="true"/g)).toHaveLength(1);
|
||||
expect(html.match(/role="option"/g)).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("keeps instance registries isolated with no DOM access", async () => {
|
||||
const Component = defineComponent({
|
||||
setup() {
|
||||
const registry = useCollectionRegistry();
|
||||
registry.register({
|
||||
key: () => 0,
|
||||
element: () => undefined,
|
||||
textValue: () => "Zero",
|
||||
disabled: () => false,
|
||||
});
|
||||
const state = useCollectionSelection({
|
||||
mode: () => "single",
|
||||
controlled: () => false,
|
||||
value: () => undefined,
|
||||
defaultValue: [0],
|
||||
onChange: () => {},
|
||||
});
|
||||
return () =>
|
||||
h("output", `${registry.ordered().length}:${state.keys.value[0]}`);
|
||||
},
|
||||
});
|
||||
const html = await renderToString(
|
||||
createSSRApp({ render: () => h("main", [h(Component), h(Component)]) }),
|
||||
);
|
||||
expect(html).toBe("<main><output>1:0</output><output>1:0</output></main>");
|
||||
});
|
||||
|
||||
it("records that raw closed Select cannot SSR its selected item label", async () => {
|
||||
const html = await renderToString(
|
||||
createSSRApp(SelectFoundation, { defaultValue: 0, name: "choice" }),
|
||||
);
|
||||
expect(html).toContain('role="combobox"');
|
||||
expect(html).not.toContain("Numeric zero");
|
||||
// ItemText registers options on mount; SSR cannot discover closed descendants.
|
||||
expect(html).not.toContain('<option value="0"');
|
||||
});
|
||||
|
||||
it("records the raw Select empty-string key restriction", async () => {
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
await expect(
|
||||
renderToString(
|
||||
createSSRApp(SelectFoundation, { includeEmpty: true, open: true }),
|
||||
),
|
||||
).rejects.toThrow("empty string");
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,180 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { flushPromises, mount } from "@vue/test-utils";
|
||||
import { defineComponent, h } from "vue";
|
||||
import Foundation from "../packages/vue/tests/fixtures/CollectionFoundation.vue";
|
||||
import SelectFoundation from "../packages/vue/tests/fixtures/SelectFoundation.vue";
|
||||
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
const originalScroll = Object.getOwnPropertyDescriptor(
|
||||
HTMLElement.prototype,
|
||||
"scrollIntoView",
|
||||
);
|
||||
beforeEach(() => {
|
||||
// Only focus/selection, no geometry claims.
|
||||
Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
|
||||
configurable: true,
|
||||
value: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal(
|
||||
"ResizeObserver",
|
||||
class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
},
|
||||
);
|
||||
});
|
||||
afterEach(() => {
|
||||
wrappers.splice(0).forEach((wrapper) => wrapper.unmount());
|
||||
document.body.innerHTML = "";
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
if (originalScroll)
|
||||
Object.defineProperty(
|
||||
HTMLElement.prototype,
|
||||
"scrollIntoView",
|
||||
originalScroll,
|
||||
);
|
||||
else Reflect.deleteProperty(HTMLElement.prototype, "scrollIntoView");
|
||||
});
|
||||
|
||||
describe("installed Reka Select audit — not public component acceptance", () => {
|
||||
function form(props: Record<string, unknown>) {
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
render: () => h("form", {}, [h(SelectFoundation, props)]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(wrapper);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
it("records empty multiple FormData despite two selected trigger labels", async () => {
|
||||
const wrapper = form({
|
||||
multiple: true,
|
||||
defaultValue: [0, "0"],
|
||||
name: "choice",
|
||||
});
|
||||
await flushPromises();
|
||||
expect([...new FormData(wrapper.get("form").element)]).toEqual([]);
|
||||
const options = wrapper.get("select").findAll("option");
|
||||
expect(options).toHaveLength(3);
|
||||
expect(
|
||||
options.slice(0, 2).map((option) => option.attributes("value")),
|
||||
).toEqual(["0", "0"]);
|
||||
expect(wrapper.get("select").element.selectedOptions).toHaveLength(0);
|
||||
expect(wrapper.get('[role="combobox"]').text()).toBe(
|
||||
"Numeric zero, String zero",
|
||||
);
|
||||
expect(wrapper.get('[role="combobox"]').attributes("aria-expanded")).toBe(
|
||||
"false",
|
||||
);
|
||||
});
|
||||
|
||||
it("omits disabled whole-field values from the native submission layer", async () => {
|
||||
const wrapper = form({ defaultValue: 0, disabled: true, name: "choice" });
|
||||
await flushPromises();
|
||||
expect([...new FormData(wrapper.get("form").element)]).toEqual([]);
|
||||
expect(
|
||||
wrapper.get('[role="combobox"]').attributes("disabled"),
|
||||
).toBeDefined();
|
||||
});
|
||||
|
||||
it("keeps selected content in the closed trigger after mounting", async () => {
|
||||
const wrapper = form({ defaultValue: 0, name: "choice" });
|
||||
await flushPromises();
|
||||
expect(wrapper.get('[role="combobox"]').text()).toBe("Numeric zero");
|
||||
expect(new FormData(wrapper.get("form").element).get("choice")).toBe("0");
|
||||
});
|
||||
});
|
||||
function fixture(props: Record<string, unknown> = {}) {
|
||||
const wrapper = mount(Foundation, { props, attachTo: document.body });
|
||||
wrappers.push(wrapper);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
describe("installed Reka Listbox audit — not public component acceptance", () => {
|
||||
it("distinguishes numeric and string zero and toggles multiple values", async () => {
|
||||
const wrapper = fixture({ multiple: true, defaultValue: [0] });
|
||||
await flushPromises();
|
||||
await wrapper.findAll('[role="option"]')[1].trigger("click");
|
||||
expect(
|
||||
wrapper
|
||||
.findAll('[role="option"]')
|
||||
.map((item) => item.attributes("aria-selected")),
|
||||
).toEqual(["true", "true", "false"]);
|
||||
expect(wrapper.emitted("update:modelValue")).toEqual([[[0, "0"]]]);
|
||||
});
|
||||
|
||||
it("keeps controlled rejection visible and emits repeated proposals", async () => {
|
||||
const wrapper = fixture({ multiple: true, modelValue: [0] });
|
||||
await flushPromises();
|
||||
const item = wrapper.findAll('[role="option"]')[1];
|
||||
await item.trigger("click");
|
||||
await item.trigger("click");
|
||||
expect(item.attributes("aria-selected")).toBe("false");
|
||||
expect(wrapper.emitted("update:modelValue")).toEqual([
|
||||
[[0, "0"]],
|
||||
[[0, "0"]],
|
||||
]);
|
||||
});
|
||||
|
||||
it("skips disabled items for navigation and select-all", async () => {
|
||||
const wrapper = fixture({ multiple: true });
|
||||
await flushPromises();
|
||||
const listbox = wrapper.get('[role="listbox"]');
|
||||
await listbox.trigger("keydown", { key: "End" });
|
||||
expect(document.activeElement).toBe(
|
||||
wrapper.findAll('[role="option"]')[1].element,
|
||||
);
|
||||
await listbox.trigger("keydown", { key: "a", ctrlKey: true });
|
||||
expect(wrapper.emitted("update:modelValue")).toEqual([[[0, "0"]]]);
|
||||
expect(
|
||||
wrapper.findAll('[role="option"]')[2].attributes("aria-selected"),
|
||||
).toBe("false");
|
||||
});
|
||||
|
||||
it("serializes indexed names and does not restore selection on native reset", async () => {
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h("form", {}, [
|
||||
h(Foundation, {
|
||||
multiple: true,
|
||||
defaultValue: [0],
|
||||
name: "choices",
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(wrapper);
|
||||
await flushPromises();
|
||||
await wrapper.findAll('[role="option"]')[1].trigger("click");
|
||||
const form = wrapper.get("form").element;
|
||||
expect([...new FormData(form)]).toEqual([
|
||||
["choices[0]", "0"],
|
||||
["choices[1]", "0"],
|
||||
]);
|
||||
form.reset();
|
||||
await flushPromises();
|
||||
expect(
|
||||
wrapper.findAll('[role="option"]')[1].attributes("aria-selected"),
|
||||
).toBe("true");
|
||||
expect([...new FormData(form)]).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("allows cancelling item select before a value change", async () => {
|
||||
// Raw item event is tested in the fixture through the actual DOM CustomEvent.
|
||||
const wrapper = fixture({ multiple: true });
|
||||
await flushPromises();
|
||||
const option = wrapper.findAll('[role="option"]')[0];
|
||||
option.element.addEventListener("listbox.select", (event) =>
|
||||
event.preventDefault(),
|
||||
);
|
||||
await option.trigger("click");
|
||||
expect(option.attributes("aria-selected")).toBe("false");
|
||||
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,278 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { effectScope, reactive, ref } from "vue";
|
||||
import {
|
||||
copyKeys,
|
||||
decodeKey,
|
||||
encodeKey,
|
||||
type CollectionKey,
|
||||
} from "../packages/vue/src/components/collection/keys";
|
||||
import { useCollectionSelection } from "../packages/vue/src/components/collection/selection";
|
||||
import { useCollectionRegistry } from "../packages/vue/src/components/collection/registry";
|
||||
|
||||
function selection(overrides = {}) {
|
||||
const props = reactive({
|
||||
mode: "multiple" as "none" | "single" | "multiple",
|
||||
controlled: false,
|
||||
value: undefined as CollectionKey[] | undefined,
|
||||
disabled: false,
|
||||
readOnly: false,
|
||||
disabledKeys: [] as CollectionKey[],
|
||||
disallowEmptySelection: false,
|
||||
...overrides,
|
||||
});
|
||||
const onChange = vi.fn();
|
||||
const state = useCollectionSelection({
|
||||
mode: () => props.mode,
|
||||
controlled: () => props.controlled,
|
||||
value: () => props.value,
|
||||
disabled: () => props.disabled,
|
||||
readOnly: () => props.readOnly,
|
||||
disabledKeys: () => props.disabledKeys,
|
||||
disallowEmptySelection: () => props.disallowEmptySelection,
|
||||
defaultValue: ["initial"],
|
||||
onChange,
|
||||
});
|
||||
return { state, props, onChange };
|
||||
}
|
||||
|
||||
describe("private collection identity and accepted selection", () => {
|
||||
it("round trips typed keys including empty, zero and adapter-like strings", () => {
|
||||
const keys = ["", 0, "0", 1, "1", '["number",1]', "__proto__", "中文"];
|
||||
expect(new Set(keys.map(encodeKey)).size).toBe(keys.length);
|
||||
expect(keys.map(encodeKey).map(decodeKey)).toEqual(keys);
|
||||
expect(copyKeys([0, "0", 0, "0"])).toEqual([0, "0"]);
|
||||
});
|
||||
|
||||
it("rejects unsupported identities and malformed adapter values", () => {
|
||||
for (const key of [NaN, Infinity, null, undefined, {}, []]) {
|
||||
expect(() => encodeKey(key as CollectionKey)).toThrow(TypeError);
|
||||
}
|
||||
for (const encoded of ['["number","1"]', "{}", "null", '["object",{}]']) {
|
||||
expect(() => decodeKey(encoded)).toThrow(TypeError);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps caller arrays and emitted snapshots independent", () => {
|
||||
const initial: CollectionKey[] = [1];
|
||||
const onChange = vi.fn((value: CollectionKey[]) => value.push("injected"));
|
||||
const state = useCollectionSelection({
|
||||
mode: () => "multiple",
|
||||
controlled: () => false,
|
||||
value: () => undefined,
|
||||
defaultValue: initial,
|
||||
onChange,
|
||||
});
|
||||
initial.push(2);
|
||||
state.toggle("1");
|
||||
expect(state.keys.value).toEqual([1, "1"]);
|
||||
state.reset();
|
||||
expect(state.keys.value).toEqual([1]);
|
||||
});
|
||||
|
||||
it("retries equal rejected proposals from the last accepted value", () => {
|
||||
const { state, props, onChange } = selection({
|
||||
controlled: true,
|
||||
value: [1],
|
||||
});
|
||||
state.toggle("1");
|
||||
state.toggle("1");
|
||||
expect(onChange.mock.calls).toEqual([[[1, "1"]], [[1, "1"]]]);
|
||||
expect(state.keys.value).toEqual([1]);
|
||||
props.value = [1, "1"];
|
||||
state.toggle("1");
|
||||
expect(onChange).toHaveBeenLastCalledWith([1]);
|
||||
expect(state.keys.value).toEqual([1, "1"]);
|
||||
});
|
||||
|
||||
it("treats an explicitly controlled undefined as empty", () => {
|
||||
const { state, onChange } = selection({ controlled: true });
|
||||
expect(state.keys.value).toEqual([]);
|
||||
state.toggle(0);
|
||||
state.reset();
|
||||
expect(state.keys.value).toEqual([]);
|
||||
expect(onChange).toHaveBeenCalledExactlyOnceWith([0]);
|
||||
});
|
||||
|
||||
it("exposes immutable accepted snapshots and treats reordering as the same selection", () => {
|
||||
const { state, onChange } = selection({
|
||||
controlled: true,
|
||||
value: [0, "0"],
|
||||
});
|
||||
expect(Object.isFrozen(state.keys.value)).toBe(true);
|
||||
expect(state.request(["0", 0])).toBe(false);
|
||||
expect(state.keys.value).toEqual([0, "0"]);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("supports single replace, toggle and disallow-empty without duplicate changes", () => {
|
||||
const { state, props, onChange } = selection({ mode: "single" });
|
||||
expect(state.replace(0)).toBe(true);
|
||||
expect(state.replace(0)).toBe(false);
|
||||
props.disallowEmptySelection = true;
|
||||
expect(state.toggle(0)).toBe(false);
|
||||
expect(state.request([])).toBe(false);
|
||||
props.disallowEmptySelection = false;
|
||||
expect(state.toggle(0)).toBe(true);
|
||||
expect(state.keys.value).toEqual([]);
|
||||
expect(onChange.mock.calls).toEqual([[[0]], [[]]]);
|
||||
expect(() => state.request([1, 2])).toThrow(TypeError);
|
||||
});
|
||||
|
||||
it.each(["none", "disabled", "readOnly"])(
|
||||
"blocks selection for %s",
|
||||
(kind) => {
|
||||
const { state, onChange } = selection(
|
||||
kind === "none" ? { mode: "none" } : { [kind]: true },
|
||||
);
|
||||
expect(state.toggle("x")).toBe(false);
|
||||
expect(state.replace("x")).toBe(false);
|
||||
expect(state.selectAll(["x"])).toBe(false);
|
||||
expect(state.request([])).toBe(false);
|
||||
expect(state.keys.value).toEqual(["initial"]);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves disabled selections and excludes disabled additions in bulk paths", () => {
|
||||
const { state, props, onChange } = selection({
|
||||
disabledKeys: ["initial", 0],
|
||||
});
|
||||
expect(state.toggle("initial")).toBe(false);
|
||||
expect(state.request(["initial", 0])).toBe(false);
|
||||
state.selectAll([0, "0", "other"]);
|
||||
expect(state.keys.value).toEqual(["initial", "0", "other"]);
|
||||
props.disabledKeys = [];
|
||||
state.toggle("initial");
|
||||
expect(state.keys.value).toEqual(["0", "other"]);
|
||||
expect(onChange).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("can replace a disabled initial selection with an available single option", () => {
|
||||
const { state, onChange } = selection({
|
||||
mode: "single",
|
||||
disabledKeys: ["initial"],
|
||||
});
|
||||
expect(state.toggle("initial")).toBe(false);
|
||||
expect(state.replace(0)).toBe(true);
|
||||
expect(state.keys.value).toEqual([0]);
|
||||
expect(onChange).toHaveBeenCalledExactlyOnceWith([0]);
|
||||
});
|
||||
|
||||
it("leaves accepted missing keys intact until caller explicitly edits them", () => {
|
||||
const { state, props, onChange } = selection({
|
||||
controlled: true,
|
||||
value: ["missing"],
|
||||
});
|
||||
expect(state.keys.value).toEqual(["missing"]);
|
||||
props.value = ["replacement"];
|
||||
expect(state.keys.value).toEqual(["replacement"]);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reset restores the initial snapshot silently, including while disabled", () => {
|
||||
const { state, props, onChange } = selection();
|
||||
state.toggle("added");
|
||||
props.disabled = true;
|
||||
state.reset();
|
||||
expect(state.keys.value).toEqual(["initial"]);
|
||||
expect(onChange).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("collection membership, DOM order and navigation targets", () => {
|
||||
function member(key: CollectionKey, disabled = false) {
|
||||
const data = reactive({ key, disabled, text: `Item ${key}` });
|
||||
const element = document.createElement("div");
|
||||
return {
|
||||
data,
|
||||
node: element,
|
||||
member: {
|
||||
key: () => data.key,
|
||||
element: () => element,
|
||||
textValue: () => data.text,
|
||||
disabled: () => data.disabled,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it("tracks live DOM reordering, disabled updates and native member removal", () => {
|
||||
const registry = useCollectionRegistry();
|
||||
const a = member("a"),
|
||||
b = member("b"),
|
||||
c = member("c", true);
|
||||
const parent = document.createElement("div");
|
||||
parent.append(a.node, b.node, c.node);
|
||||
registry.register(c.member);
|
||||
registry.register(a.member);
|
||||
const removeB = registry.register(b.member);
|
||||
expect(registry.ordered().map((item) => item.key())).toEqual([
|
||||
"a",
|
||||
"b",
|
||||
"c",
|
||||
]);
|
||||
parent.prepend(c.node);
|
||||
expect(registry.available().map((item) => item.key())).toEqual(["a", "b"]);
|
||||
c.data.disabled = false;
|
||||
expect(registry.adjacent("b", "next", true)?.key()).toBe("c");
|
||||
expect(registry.adjacent("b", "next")).toBeUndefined();
|
||||
expect(registry.adjacent(undefined, "previous")?.key()).toBe("b");
|
||||
expect(registry.adjacent("a", "previous")?.key()).toBe("c");
|
||||
removeB();
|
||||
removeB();
|
||||
expect(registry.ordered().map((item) => item.key())).toEqual(["c", "a"]);
|
||||
});
|
||||
|
||||
it("distinguishes typed keys and rejects initial and dynamic duplicates", () => {
|
||||
const registry = useCollectionRegistry();
|
||||
const a = member(1),
|
||||
b = member("1");
|
||||
registry.register(a.member);
|
||||
registry.register(b.member);
|
||||
expect(() => registry.register(member(1).member)).toThrow("Duplicate");
|
||||
b.data.key = 1;
|
||||
expect(() => registry.ordered()).toThrow("Duplicate");
|
||||
b.data.key = "fixed";
|
||||
expect(registry.ordered()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("uses available DOM order for ranges and handles stale anchors", () => {
|
||||
const registry = useCollectionRegistry();
|
||||
const items = [member(0), member(1, true), member("1"), member(2)];
|
||||
const parent = document.createElement("div");
|
||||
items.forEach((item) => {
|
||||
parent.append(item.node);
|
||||
registry.register(item.member);
|
||||
});
|
||||
expect(registry.range(2, 0)).toEqual([0, "1", 2]);
|
||||
expect(registry.range(1, 2)).toEqual([]);
|
||||
expect(registry.range("missing", 2)).toEqual([]);
|
||||
expect(registry.adjacent(0, "first")?.key()).toBe(0);
|
||||
expect(registry.adjacent(0, "last")?.key()).toBe(2);
|
||||
expect(registry.adjacent(0, "previous", true)?.key()).toBe(2);
|
||||
});
|
||||
|
||||
it("isolates instances and disposes scope-owned registrations", () => {
|
||||
const outer = useCollectionRegistry(),
|
||||
inner = useCollectionRegistry();
|
||||
const scope = effectScope();
|
||||
scope.run(() => outer.register(member("same").member));
|
||||
inner.register(member("same").member);
|
||||
expect(outer.ordered()).toHaveLength(1);
|
||||
scope.stop();
|
||||
expect(outer.ordered()).toEqual([]);
|
||||
expect(inner.ordered()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("works without elements and retains registration order", () => {
|
||||
const registry = useCollectionRegistry();
|
||||
const element = ref<HTMLElement>();
|
||||
registry.register({
|
||||
key: () => 0,
|
||||
element: () => element.value,
|
||||
textValue: () => "Zero",
|
||||
disabled: () => false,
|
||||
});
|
||||
expect(registry.adjacent(undefined, "next")?.key()).toBe(0);
|
||||
expect(registry.range(0, 0)).toEqual([0]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user