From 368bedcbad3df6d81a486f982c7a9e06927e7793 Mon Sep 17 00:00:00 2001 From: chenshangshu Date: Mon, 23 Nov 2026 11:17:46 +0800 Subject: [PATCH 1/3] fix(select): preserve multiline option height --- packages/core/src/styles/components/select.css | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/core/src/styles/components/select.css b/packages/core/src/styles/components/select.css index 279ec3e..c098443 100644 --- a/packages/core/src/styles/components/select.css +++ b/packages/core/src/styles/components/select.css @@ -209,6 +209,7 @@ .mw-select__option { display: flex; + flex-shrink: 0; align-items: center; gap: var(--space-2); min-height: var(--size-sm-h); From ae94e7dc34b0dfa75675e7fda5f14c87269fb147 Mon Sep 17 00:00:00 2001 From: chenshangshu Date: Mon, 23 Nov 2026 11:36:49 +0800 Subject: [PATCH 2/3] =?UTF-8?q?feat(calendar):=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89=E6=97=A5=E5=8E=86=E5=92=8C=E5=B9=B4?= =?UTF-8?q?=E6=9C=88=E5=BF=AB=E9=80=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/core/src/defs/index.ts | 33 ++- packages/core/src/locale/index.ts | 6 + .../core/src/styles/components/calendar.css | 48 ++-- .../components/Calendar.component.test.tsx | 32 ++- packages/react/src/components/Calendar.tsx | 208 ++++++++---------- .../components/DatePicker.component.test.tsx | 15 ++ .../react/src/components/calendar-defs.ts | 19 +- packages/react/src/index.ts | 3 + packages/react/src/lib/useComboPanel.ts | 5 +- .../src/components/Calendar.component.test.ts | 36 ++- packages/vue/src/components/Calendar.vue | 195 ++++++++-------- .../components/DatePicker.component.test.ts | 20 ++ packages/vue/src/components/calendar-defs.ts | 47 +--- packages/vue/src/index.ts | 4 + packages/vue/src/lib/useComboPanel.ts | 4 +- playground/dev/api/entries/calendar.ts | 50 ++++- playground/dev/pages/components/calendar.vue | 15 +- 17 files changed, 433 insertions(+), 307 deletions(-) diff --git a/packages/core/src/defs/index.ts b/packages/core/src/defs/index.ts index f4a3153..8267c38 100644 --- a/packages/core/src/defs/index.ts +++ b/packages/core/src/defs/index.ts @@ -1,3 +1,5 @@ +import type { CalendarCell } from "../headless/calendar-grid.js"; + export type AccordionPanelValue = string | number; export type AccordionValue = | AccordionPanelValue @@ -75,7 +77,35 @@ export interface CalendarViewRange { month: number; } -export interface CalendarProps { +export interface CalendarTitleContext { + date: Date; + label: string; +} + +export interface CalendarNavigationContext extends CalendarTitleContext { + disabled: boolean; + showToday: boolean; + previous: () => void; + next: () => void; + today: () => void; +} + +export interface CalendarMonthContext { + year: number; + month: number; + label: string; + selected: boolean; +} + +export interface CalendarCustomizationProps { + viewDate?: Date | string | null; + hideOutsideDays?: boolean; + dayLabel?: (cell: CalendarCell) => string; + showTodayShortcut?: boolean | "always"; + pickerAppendTo?: "self" | "body"; +} + +export interface CalendarProps extends CalendarCustomizationProps { modelValue?: CalendarModelValue; selected?: string | null; selectionMode?: CalendarSelectionMode; @@ -84,7 +114,6 @@ export interface CalendarProps { firstDayOfWeek?: CalendarFirstDayOfWeek; days?: Record; onlySelectableWithDays?: boolean; - showTodayShortcut?: boolean; variant?: CalendarVariant; fluid?: boolean; disabled?: boolean; diff --git a/packages/core/src/locale/index.ts b/packages/core/src/locale/index.ts index 49c0941..7a0b827 100644 --- a/packages/core/src/locale/index.ts +++ b/packages/core/src/locale/index.ts @@ -31,6 +31,8 @@ export interface UiMessages { prevMonth: string; nextMonth: string; prevYear: string; + chooseMonth: string; + year: string; nextYear: string; today: string; backToToday: string; @@ -78,6 +80,8 @@ export const uiMessages: Record = { prevMonth: "上个月", nextMonth: "下个月", prevYear: "上一年", + chooseMonth: "切换月份", + year: "年份", nextYear: "下一年", today: "今天", backToToday: "回到今天", @@ -121,6 +125,8 @@ export const uiMessages: Record = { prevMonth: "Previous month", nextMonth: "Next month", prevYear: "Previous year", + chooseMonth: "Choose month", + year: "Year", nextYear: "Next year", today: "Today", backToToday: "Back to today", diff --git a/packages/core/src/styles/components/calendar.css b/packages/core/src/styles/components/calendar.css index e919339..5eafad6 100644 --- a/packages/core/src/styles/components/calendar.css +++ b/packages/core/src/styles/components/calendar.css @@ -59,6 +59,7 @@ display: inline-flex; align-items: center; gap: var(--space-1); + min-width: 0; padding: var(--space-0-5) var(--space-1-5); margin-inline-start: calc(var(--space-1-5) * -1); border: 0; @@ -75,12 +76,20 @@ color var(--duration-fast) var(--ease-standard); } +.mw-calendar__month-label { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + .mw-calendar__switcher-btn:hover:not(:disabled) { background-color: var(--fill-default); color: var(--text-accent); } .mw-calendar__switcher-chevron { + flex-shrink: 0; color: var(--text-tertiary); transition: transform var(--duration-fast) var(--ease-standard); } @@ -138,21 +147,12 @@ color: var(--text-primary); } -.mw-calendar__switcher { - position: absolute; - inset-inline: var(--space-2); - top: calc(var(--size-sm-h) + var(--space-3)); - z-index: 5; +.mw-calendar__switcher.mw-popover { display: flex; flex-direction: column; gap: var(--space-2); + width: calc(var(--size-xs-h) * 9); padding: var(--space-2-5); - border-radius: var(--radius-float); -} - -.mw-calendar--plain .mw-calendar__switcher { - inset-inline: var(--space-0); - top: calc(var(--size-sm-h) + var(--space-1)); } .mw-calendar__switcher-head { @@ -163,10 +163,12 @@ } .mw-calendar__switcher-year { - font-size: var(--type-body-sm-size); - line-height: var(--type-body-sm-line); - font-weight: var(--weight-semibold); - color: var(--text-primary); + width: calc(var(--size-xs-h) * 3); +} + +.mw-calendar__switcher-year input { + text-align: center; + font-variant-numeric: tabular-nums; } .mw-calendar__month-grid { @@ -191,17 +193,29 @@ color var(--duration-fast) var(--ease-standard); } -.mw-calendar__month-option:hover:not(.mw-calendar__month-option--active) { +.mw-calendar__month-option:hover:not([aria-pressed="true"]) { background-color: var(--fill-default); color: var(--text-primary); } -.mw-calendar__month-option--active { +.mw-calendar__month-option[aria-pressed="true"] { background-color: var(--accent); color: var(--text-on-accent); font-weight: var(--weight-semibold); } +@media (pointer: coarse) { + .mw-calendar__switcher-head .mw-calendar__nav-btn { + width: var(--hit-min); + height: var(--hit-min); + } + + .mw-calendar__switcher-year input, + .mw-calendar__month-option { + min-height: var(--hit-min); + } +} + .mw-calendar__weekdays { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); diff --git a/packages/react/src/components/Calendar.component.test.tsx b/packages/react/src/components/Calendar.component.test.tsx index 1738d84..dc7c58c 100644 --- a/packages/react/src/components/Calendar.component.test.tsx +++ b/packages/react/src/components/Calendar.component.test.tsx @@ -12,6 +12,34 @@ describe("Calendar", () => { expect(Calendar.displayName).toBe("MwCalendar"); }); + it("customizes the visible month and day content independently of selection", () => { + const onToday = vi.fn(); + const onSelect = vi.fn(); + const { container, getByRole, getByText } = render( + `Entry date ${cell.isoDate}`} + renderDay={({ cell }) => `Day ${cell.day}`} + renderFooter={({ date }) => `Month ${date.getMonth() + 1}`} + showTodayShortcut="always" + onToday={onToday} + onSelect={onSelect} + />, + ); + + expect(container.querySelector('[data-date="2026-05-01"]')).toBeNull(); + expect(container.querySelector(".mw-calendar__day--other-month")).toBeNull(); + expect(getByRole("button", { name: "Entry date 2026-06-01" }).textContent).toBe("Day 1"); + expect(getByText("Month 6")).toBeTruthy(); + + fireEvent.click(getByRole("button", { name: "回到今天" })); + expect(toIsoKey(onToday.mock.calls[0]![0])).toBe(toIsoKey(new Date())); + expect(onSelect).not.toHaveBeenCalled(); + expect(getByRole("button", { name: "回到今天" })).toBeTruthy(); + }); + it("renders month days and updates value / selected on day click, including plain variant", () => { const initial = new Date(2026, 4, 10); const onValueChange = vi.fn(); @@ -155,11 +183,13 @@ describe("Calendar", () => { ".mw-calendar__month-option", ); expect(monthOptions).toHaveLength(12); + const year = container.querySelector('input[aria-label="年份"]')!; + fireEvent.change(year, { target: { value: "2021" } }); fireEvent.click(monthOptions[2]!); expect(container.querySelector(".mw-calendar__switcher")).toBeNull(); const lastView = onView.mock.calls.at(-1)?.[0]; - expect(lastView?.month).toBe(3); + expect(lastView).toMatchObject({ year: 2021, month: 3 }); }); it("supports firstDayOfWeek and range / multiple selection modes", () => { diff --git a/packages/react/src/components/Calendar.tsx b/packages/react/src/components/Calendar.tsx index 4bd731b..3ccbbbb 100644 --- a/packages/react/src/components/Calendar.tsx +++ b/packages/react/src/components/Calendar.tsx @@ -17,13 +17,18 @@ import { type CalendarCell, } from "@mango-write/ui-core/headless/calendar-grid"; import { uiMessages, useUiLocale, type UiLocaleSource } from "../locale"; +import InputNumber from "./InputNumber"; +import Popover from "./Popover"; import type { CalendarFirstDayOfWeek, CalendarHandle, CalendarModelValue, + CalendarMonthContext, + CalendarNavigationContext, CalendarOutputValue, CalendarProps, CalendarSelectionMode, + CalendarTitleContext, CalendarVariant, CalendarViewRange, } from "./calendar-defs"; @@ -33,9 +38,12 @@ export type { CalendarFirstDayOfWeek, CalendarHandle, CalendarModelValue, + CalendarMonthContext, + CalendarNavigationContext, CalendarOutputValue, CalendarProps, CalendarSelectionMode, + CalendarTitleContext, CalendarVariant, CalendarViewRange, }; @@ -86,6 +94,17 @@ export const Calendar = forwardRef( onSelect, onDateSelect, onView, + onToday, + viewDate, + hideOutsideDays, + dayLabel, + pickerAppendTo = "self", + renderTitle, + renderNavigation, + renderWeekday, + renderDay, + renderMonth, + renderFooter, selectionMode = "single", minDate = null, maxDate = null, @@ -152,7 +171,7 @@ export const Calendar = forwardRef( const todayMonth = nowRef.current.getMonth(); const todayDate = nowRef.current.getDate(); - const initialPrimary = resolvePrimaryDate( + const initialPrimary = parseCoreDateValue(viewDate) ?? resolvePrimaryDate( currentModelValue, currentSelected, hours, @@ -165,13 +184,14 @@ export const Calendar = forwardRef( const [viewMonth, setViewMonth] = useState( () => initialPrimary?.getMonth() ?? todayMonth, ); - const [pickerYear, setPickerYear] = useState( + const [pickerYear, setPickerYear] = useState( () => initialPrimary?.getFullYear() ?? todayYear, ); const [switcherOpen, setSwitcherOpen] = useState(false); + const effectivePickerYear = Math.max(100, Math.min(9999, pickerYear ?? viewYear)); useEffect(() => { - const primary = resolvePrimaryDate( + const primary = parseCoreDateValue(viewDate) ?? resolvePrimaryDate( currentModelValue, currentSelected, hours, @@ -182,26 +202,21 @@ export const Calendar = forwardRef( setViewMonth(primary.getMonth()); setPickerYear(primary.getFullYear()); } - }, [currentModelValue, currentSelected, hours, minutes]); + }, [viewDate, currentModelValue, currentSelected, hours, minutes]); const effectiveAriaLabel = ariaLabel ?? restAttrs["aria-label"]; const isCurrentMonth = viewYear === todayYear && viewMonth === todayMonth; + const calendarDate = useMemo(() => new Date(viewYear, viewMonth, 1), [viewYear, viewMonth]); const monthLabel = useMemo(() => { - const date = new Date(viewYear, viewMonth, 1); return new Intl.DateTimeFormat(resolvedLocale, { year: "numeric", month: "long", - }).format(date); - }, [viewYear, viewMonth, resolvedLocale]); - - const yearLabel = useMemo(() => { - const date = new Date(pickerYear, 0, 1); - return new Intl.DateTimeFormat(resolvedLocale, { - year: "numeric", - }).format(date); - }, [pickerYear, resolvedLocale]); + }).format(calendarDate); + }, [calendarDate, resolvedLocale]); + const titleContext = { date: calendarDate, label: monthLabel }; + const showToday = showTodayShortcut === "always" || (showTodayShortcut && !isCurrentMonth); const monthNames = useMemo( () => @@ -299,7 +314,8 @@ export const Calendar = forwardRef( setPickerYear(todayYear); setSwitcherOpen(false); emitViewRange(todayYear, todayMonth); - }, [disabled, todayYear, todayMonth, emitViewRange]); + onToday?.(new Date()); + }, [disabled, todayYear, todayMonth, emitViewRange, onToday]); const setView = useCallback((year: number, monthZeroBased: number) => { setViewYear(year); @@ -316,18 +332,17 @@ export const Calendar = forwardRef( [setView, backToToday], ); - const toggleSwitcher = () => { - if (disabled) return; - setPickerYear(viewYear); - setSwitcherOpen((prev) => !prev); + const changeSwitcherOpen = (open: boolean) => { + if (open) setPickerYear(viewYear); + setSwitcherOpen(open); }; const pickMonth = (monthIndexZeroBased: number) => { if (disabled) return; - setViewYear(pickerYear); + setViewYear(effectivePickerYear); setViewMonth(monthIndexZeroBased); setSwitcherOpen(false); - emitViewRange(pickerYear, monthIndexZeroBased); + emitViewRange(effectivePickerYear, monthIndexZeroBased); }; const commitModelOutput = (nextVal: CalendarOutputValue) => { @@ -426,116 +441,62 @@ export const Calendar = forwardRef( >
- + } > - {monthLabel} -
-
- - + {renderNavigation ? renderNavigation({ ...titleContext, disabled, showToday, previous: prevMonth, next: nextMonth, today: backToToday }) : ( + <> + {showToday && } + + + + )}
- {switcherOpen && ( -
-
- - - {yearLabel} - - -
- -
- {monthNames.map((monthName, idx) => { - const active = idx === viewMonth && pickerYear === viewYear; - return ( - - ); - })} -
-
- )} -
- {weekdayLabels.map((weekday) => ( + {weekdayLabels.map((weekday, index) => ( - {weekday} + {renderWeekday ? renderWeekday({ label: weekday, index }) : weekday} ))}
@@ -548,7 +509,9 @@ export const Calendar = forwardRef( aria-label={monthLabel} > {calendarWeeks.flatMap((week) => - week.map((cell) => ( + week.map((cell) => hideOutsideDays && cell.otherMonth ? ( +
From 200e73e673e88519d4a9a8e652b08c6274b63de5 Mon Sep 17 00:00:00 2001 From: chenshangshu Date: Mon, 23 Nov 2026 14:07:21 +0800 Subject: [PATCH 3/3] =?UTF-8?q?feat(virtual-list):=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E5=8F=AF=E5=8F=98=E9=AB=98=E5=BA=A6=E7=9A=84=E8=99=9A=E6=8B=9F?= =?UTF-8?q?=E6=BB=9A=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/core/src/components.css | 1 + packages/core/src/defs/index.ts | 7 ++ packages/core/src/defs/virtual-list.ts | 19 ++++ .../src/styles/components/virtual-list.css | 21 +++++ packages/react/package.json | 27 ++++++ .../components/VirtualList.component.test.tsx | 57 ++++++++++++ packages/react/src/components/VirtualList.tsx | 90 ++++++++++++++++++ .../react/src/components/virtual-list-defs.ts | 6 ++ packages/react/src/index.ts | 2 + packages/react/vite.config.ts | 1 + packages/vue/package.json | 27 ++++++ .../components/VirtualList.component.test.ts | 59 ++++++++++++ packages/vue/src/components/VirtualList.vue | 92 +++++++++++++++++++ .../vue/src/components/virtual-list-defs.ts | 6 ++ packages/vue/src/index.ts | 2 + packages/vue/vite.config.ts | 1 + playground/dev/api/entries/virtual-list.ts | 21 +++++ .../dev/pages/components/virtual-list.vue | 55 +++++++++++ playground/dev/registry-data.ts | 8 ++ playground/dev/usage/entries/virtual-list.ts | 59 ++++++++++++ .../entries-display-overlays.tsx | 28 +++++- pnpm-lock.yaml | 18 ++++ 22 files changed, 606 insertions(+), 1 deletion(-) create mode 100644 packages/core/src/defs/virtual-list.ts create mode 100644 packages/core/src/styles/components/virtual-list.css create mode 100644 packages/react/src/components/VirtualList.component.test.tsx create mode 100644 packages/react/src/components/VirtualList.tsx create mode 100644 packages/react/src/components/virtual-list-defs.ts create mode 100644 packages/vue/src/components/VirtualList.component.test.ts create mode 100644 packages/vue/src/components/VirtualList.vue create mode 100644 packages/vue/src/components/virtual-list-defs.ts create mode 100644 playground/dev/api/entries/virtual-list.ts create mode 100644 playground/dev/pages/components/virtual-list.vue create mode 100644 playground/dev/usage/entries/virtual-list.ts diff --git a/packages/core/src/components.css b/packages/core/src/components.css index 43e61d6..37f9bfc 100644 --- a/packages/core/src/components.css +++ b/packages/core/src/components.css @@ -54,6 +54,7 @@ @import "./styles/components/user-card.css"; @import "./styles/components/user-chip.css"; @import "./styles/components/user-select.css"; +@import "./styles/components/virtual-list.css"; @import "./styles/components/admin-board-page.css"; @import "./styles/components/admin-board-section.css"; @import "./styles/components/admin-config-page.css"; diff --git a/packages/core/src/defs/index.ts b/packages/core/src/defs/index.ts index 8267c38..6f157f2 100644 --- a/packages/core/src/defs/index.ts +++ b/packages/core/src/defs/index.ts @@ -233,3 +233,10 @@ export interface UserSelectOption extends Record { avatar?: string | null; email?: string | null; } + +export type { + VirtualListAlignment, + VirtualListHandle, + VirtualListKey, + VirtualListProps, +} from "./virtual-list.js"; diff --git a/packages/core/src/defs/virtual-list.ts b/packages/core/src/defs/virtual-list.ts new file mode 100644 index 0000000..3efe356 --- /dev/null +++ b/packages/core/src/defs/virtual-list.ts @@ -0,0 +1,19 @@ +export type VirtualListKey = string | number; +export type VirtualListAlignment = "start" | "center" | "end" | "auto"; + +export interface VirtualListProps { + items: readonly T[]; + /** Stable, unique identity across reordering and pagination. */ + itemKey: (item: T) => VirtualListKey; + /** Positive height in pixels until the row is measured. */ + estimateSize: number | ((item: T, index: number) => number); + overscan?: number; + /** Keep these rows mounted outside the scroll window during an interaction. */ + pinnedKeys?: readonly VirtualListKey[]; +} + +export interface VirtualListHandle { + /** Jump immediately. Returns false if the key is absent or the list is unmounted. */ + scrollToKey: (key: VirtualListKey, align?: VirtualListAlignment) => boolean; + scrollToStart: () => void; +} diff --git a/packages/core/src/styles/components/virtual-list.css b/packages/core/src/styles/components/virtual-list.css new file mode 100644 index 0000000..fcf1957 --- /dev/null +++ b/packages/core/src/styles/components/virtual-list.css @@ -0,0 +1,21 @@ +.mw-virtual-list { + min-block-size: 0; + overflow-y: auto; + overflow-anchor: none; +} + +.mw-virtual-list__content { + max-inline-size: var(--mw-virtual-list-max-width, none); + margin-inline: auto; +} + +.mw-virtual-list__items { + position: relative; +} + +.mw-virtual-list__row { + position: absolute; + inset-block-start: 0; + inset-inline: 0; + display: flow-root; +} diff --git a/packages/react/package.json b/packages/react/package.json index 13ba0f8..ebcf81e 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -502,6 +502,14 @@ "types": "./dist/components/UserSelect.d.ts", "default": "./dist/components/UserSelect.js" }, + "./components/VirtualList": { + "mango-source": { + "types": "./src/components/VirtualList.tsx", + "default": "./src/components/VirtualList.tsx" + }, + "types": "./dist/components/VirtualList.d.ts", + "default": "./dist/components/VirtualList.js" + }, "./components/accordion": { "mango-source": { "types": "./src/components/accordion-defs.ts", @@ -790,6 +798,14 @@ "types": "./dist/components/user-select.d.ts", "default": "./dist/components/user-select.js" }, + "./components/virtual-list": { + "mango-source": { + "types": "./src/components/virtual-list-defs.ts", + "default": "./src/components/virtual-list-defs.ts" + }, + "types": "./dist/components/virtual-list-defs.d.ts", + "default": "./dist/components/virtual-list-defs.js" + }, "./lib/area-transition": { "mango-source": { "types": "./src/lib/area-transition.ts", @@ -1196,6 +1212,11 @@ "import": "./dist/components/UserSelect.js", "default": "./dist/components/UserSelect.js" }, + "./components/VirtualList": { + "types": "./dist/components/VirtualList.d.ts", + "import": "./dist/components/VirtualList.js", + "default": "./dist/components/VirtualList.js" + }, "./components/accordion": { "types": "./dist/components/accordion-defs.d.ts", "import": "./dist/components/accordion-defs.js", @@ -1376,6 +1397,11 @@ "import": "./dist/components/user-select.js", "default": "./dist/components/user-select.js" }, + "./components/virtual-list": { + "types": "./dist/components/virtual-list-defs.d.ts", + "import": "./dist/components/virtual-list-defs.js", + "default": "./dist/components/virtual-list-defs.js" + }, "./lib/area-transition": { "types": "./dist/lib/area-transition.d.ts", "import": "./dist/lib/area-transition.js", @@ -1460,6 +1486,7 @@ "@radix-ui/react-tooltip": "^1.4.1", "@radix-ui/react-visually-hidden": "^1.2.13", "@tanstack/react-table": "^8.21.3", + "@tanstack/react-virtual": "3.14.26", "radix-ui": "^1.8.1" }, "peerDependencies": { diff --git a/packages/react/src/components/VirtualList.component.test.tsx b/packages/react/src/components/VirtualList.component.test.tsx new file mode 100644 index 0000000..0edebc0 --- /dev/null +++ b/packages/react/src/components/VirtualList.component.test.tsx @@ -0,0 +1,57 @@ +import { act, fireEvent, render } from "@testing-library/react"; +import { createRef } from "react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import VirtualList from "./VirtualList"; +import type { VirtualListHandle } from "./virtual-list-defs"; + +const items = Array.from({ length: 1000 }, (_, i) => i); +const itemKey = (item: number) => item; + +describe("VirtualList", () => { + afterEach(() => vi.restoreAllMocks()); + + it("renders the visible range, supports pinned items, and jumps by key", () => { + vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(160); + vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(40); + vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue(40_000); + const scrollTo = vi.spyOn(HTMLElement.prototype, "scrollTo"); + const ref = createRef(); + const list = render( + + {(item) => } + , + ); + + const viewport = list.getByTestId("records"); + expect(viewport.getAttribute("tabindex")).toBe("0"); + expect(viewport.getAttribute("aria-label")).toBe("Records"); + expect(list.getAllByRole("listitem").length).toBeLessThan(18); + expect(list.getByText("999").parentElement?.getAttribute("aria-posinset")).toBe("1000"); + expect(list.queryByText("500")).toBeNull(); + act(() => list.getByText("0").focus()); + + expect(ref.current?.scrollToKey(500)).toBe(true); + expect(scrollTo).toHaveBeenLastCalledWith(expect.objectContaining({ behavior: "instant" })); + viewport.scrollTop = 20_000; + fireEvent.scroll(viewport); + + expect(list.getByText("500")).toBeTruthy(); + expect(list.getByText("0")).toBeTruthy(); + expect(list.queryByText("1")).toBeNull(); + expect(list.getByText("999")).toBeTruthy(); + expect(ref.current?.scrollToKey(-1)).toBe(false); + act(() => viewport.focus()); + expect(list.queryByText("0")).toBeNull(); + }); + + it("renders empty and persistent footer content", () => { + const list = render( + + {String} + , + ); + expect(list.getByText("No recordsLoad more")).toBeTruthy(); + expect(list.queryByRole("list")).toBeNull(); + }); +}); diff --git a/packages/react/src/components/VirtualList.tsx b/packages/react/src/components/VirtualList.tsx new file mode 100644 index 0000000..a28310b --- /dev/null +++ b/packages/react/src/components/VirtualList.tsx @@ -0,0 +1,90 @@ +import { + forwardRef, useCallback, useImperativeHandle, useMemo, useRef, useState, + type ForwardedRef, type HTMLAttributes, type ReactNode, type RefAttributes, +} from "react"; +import { defaultRangeExtractor, useVirtualizer } from "@tanstack/react-virtual"; +import type { VirtualListHandle, VirtualListKey, VirtualListProps } from "./virtual-list-defs"; + +export interface VirtualListReactProps extends VirtualListProps, Omit, "children"> { + children: (item: T, index: number) => ReactNode; + empty?: ReactNode; + footer?: ReactNode; +} + +function VirtualListInner({ + items, itemKey, estimateSize, overscan = 5, pinnedKeys, children, empty, footer, className, + onFocus, onBlur, ...attrs +}: VirtualListReactProps, ref: ForwardedRef) { + const viewport = useRef(null); + const [focusedKey, setFocusedKey] = useState(); + const keys = useMemo(() => items.map(itemKey), [items, itemKey]); + const indexes = useMemo(() => new Map(keys.map((key, index) => [key, index])), [keys]); + const getItemKey = useCallback((index: number) => keys[index]!, [keys]); + const estimateRowSize = useCallback( + (index: number) => typeof estimateSize === "number" ? estimateSize : estimateSize(items[index]!, index), + [items, estimateSize], + ); + const rangeExtractor = useMemo(() => { + const retained = [...(pinnedKeys ?? []), focusedKey] + .flatMap((key) => key === undefined ? [] : (indexes.get(key) ?? [])); + return (range: Parameters[0]) => + [...new Set([...defaultRangeExtractor(range), ...retained])].sort((a, b) => a - b); + }, [pinnedKeys, focusedKey, indexes]); + + const virtualizer = useVirtualizer({ + count: items.length, + getScrollElement: () => viewport.current, + getItemKey, + estimateSize: estimateRowSize, + overscan, + rangeExtractor, + }); + + useImperativeHandle(ref, () => ({ + scrollToKey(key, align = "start") { + const index = indexes.get(key); + if (!viewport.current || index === undefined) return false; + virtualizer.scrollToIndex(index, { align, behavior: "instant" }); + return true; + }, + scrollToStart() { + virtualizer.scrollToOffset(0, { behavior: "instant" }); + }, + }), [indexes, virtualizer]); + + function trackFocus(target: EventTarget | null) { + const row = target instanceof Element && target.closest(".mw-virtual-list__row"); + setFocusedKey(row && row.closest(".mw-virtual-list") === viewport.current + ? keys[Number(row.dataset.index)] + : undefined); + } + + return ( +
{ trackFocus(event.target); onFocus?.(event); }} + onBlur={(event) => { trackFocus(event.relatedTarget); onBlur?.(event); }} + > +
+ {items.length > 0 ? ( +
+ {virtualizer.getVirtualItems().map((row) => ( +
+ {children(items[row.index]!, row.index)} +
+ ))} +
+ ) : empty} + {footer} +
+
+ ); +} + +type VirtualListComponent = (props: VirtualListReactProps & RefAttributes) => ReactNode; +const VirtualList = forwardRef(VirtualListInner); +VirtualList.displayName = "MwVirtualList"; +export default VirtualList as VirtualListComponent; diff --git a/packages/react/src/components/virtual-list-defs.ts b/packages/react/src/components/virtual-list-defs.ts new file mode 100644 index 0000000..438d930 --- /dev/null +++ b/packages/react/src/components/virtual-list-defs.ts @@ -0,0 +1,6 @@ +export type { + VirtualListAlignment, + VirtualListHandle, + VirtualListKey, + VirtualListProps, +} from "@mango-write/ui-core/defs"; diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index e7aec85..1e73191 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -222,6 +222,8 @@ export { } from "./components/UserCard"; export { default as UserSelect } from "./components/UserSelect"; export { type UserSelectOption, type UserSelectProps } from "./components/user-select"; +export { default as VirtualList, type VirtualListReactProps } from "./components/VirtualList"; +export type { VirtualListAlignment, VirtualListHandle, VirtualListKey, VirtualListProps } from "./components/virtual-list-defs"; export { useComboPanel, diff --git a/packages/react/vite.config.ts b/packages/react/vite.config.ts index 19a0124..40bbe4c 100644 --- a/packages/react/vite.config.ts +++ b/packages/react/vite.config.ts @@ -8,6 +8,7 @@ const peers = [ "react-dom", "lucide-react", "@tanstack/react-table", + "@tanstack/react-virtual", "radix-ui", "@mango-write/ui-core", ]; diff --git a/packages/vue/package.json b/packages/vue/package.json index c791f5a..e00e8a2 100644 --- a/packages/vue/package.json +++ b/packages/vue/package.json @@ -502,6 +502,14 @@ "types": "./dist/components/UserSelect.d.ts", "default": "./dist/components/UserSelect.js" }, + "./components/VirtualList": { + "mango-source": { + "types": "./src/components/VirtualList.vue", + "default": "./src/components/VirtualList.vue" + }, + "types": "./dist/components/VirtualList.d.ts", + "default": "./dist/components/VirtualList.js" + }, "./components/accordion": { "mango-source": { "types": "./src/components/accordion-defs.ts", @@ -782,6 +790,14 @@ "types": "./dist/components/user-select.d.ts", "default": "./dist/components/user-select.js" }, + "./components/virtual-list": { + "mango-source": { + "types": "./src/components/virtual-list-defs.ts", + "default": "./src/components/virtual-list-defs.ts" + }, + "types": "./dist/components/virtual-list-defs.d.ts", + "default": "./dist/components/virtual-list-defs.js" + }, "./lib/area-transition": { "mango-source": { "types": "./src/lib/area-transition.ts", @@ -1167,6 +1183,11 @@ "import": "./dist/components/UserSelect.js", "default": "./dist/components/UserSelect.js" }, + "./components/VirtualList": { + "types": "./dist/components/VirtualList.d.ts", + "import": "./dist/components/VirtualList.js", + "default": "./dist/components/VirtualList.js" + }, "./components/accordion": { "types": "./dist/components/accordion-defs.d.ts", "import": "./dist/components/accordion-defs.js", @@ -1342,6 +1363,11 @@ "import": "./dist/components/user-select.js", "default": "./dist/components/user-select.js" }, + "./components/virtual-list": { + "types": "./dist/components/virtual-list-defs.d.ts", + "import": "./dist/components/virtual-list-defs.js", + "default": "./dist/components/virtual-list-defs.js" + }, "./lib/area-transition": { "types": "./dist/lib/area-transition.d.ts", "import": "./dist/lib/area-transition.js", @@ -1399,6 +1425,7 @@ }, "dependencies": { "@mango-write/ui-core": "workspace:*", + "@tanstack/vue-virtual": "3.13.52", "reka-ui": "^2.11.0" }, "peerDependencies": { diff --git a/packages/vue/src/components/VirtualList.component.test.ts b/packages/vue/src/components/VirtualList.component.test.ts new file mode 100644 index 0000000..855bac1 --- /dev/null +++ b/packages/vue/src/components/VirtualList.component.test.ts @@ -0,0 +1,59 @@ +import { mount } from "@vue/test-utils"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { h, nextTick } from "vue"; +import VirtualList from "./VirtualList.vue"; + +const items = Array.from({ length: 1000 }, (_, i) => i); +const itemKey = (item: number) => item; + +describe("VirtualList", () => { + afterEach(() => vi.restoreAllMocks()); + + it("renders the visible range, retains focused and pinned rows, and jumps by key", async () => { + vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(160); + vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(40); + vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue(40_000); + const scrollTo = vi.spyOn(HTMLElement.prototype, "scrollTo"); + const list = mount(VirtualList, { + attachTo: document.body, + props: { items, itemKey, estimateSize: 40, overscan: 2, pinnedKeys: [999] }, + attrs: { "aria-label": "Records", "data-testid": "records" }, + slots: { default: ({ item }: { item: number }) => h("button", { "data-row": item }, String(item)) }, + }); + await nextTick(); + + expect(list.attributes("tabindex")).toBe("0"); + expect(list.attributes("aria-label")).toBe("Records"); + expect(list.attributes("data-testid")).toBe("records"); + expect(list.findAll('[role="listitem"]').length).toBeLessThan(18); + expect(list.get('[data-row="999"]').element.parentElement?.getAttribute("aria-posinset")).toBe("1000"); + expect(list.find('[data-row="500"]').exists()).toBe(false); + list.get('[data-row="0"]').element.focus(); + + expect(list.vm.scrollToKey(500)).toBe(true); + expect(scrollTo).toHaveBeenLastCalledWith(expect.objectContaining({ behavior: "instant" })); + list.element.scrollTop = 20_000; + await list.trigger("scroll"); + await nextTick(); + + expect(list.find('[data-row="500"]').exists()).toBe(true); + expect(list.find('[data-row="0"]').exists()).toBe(true); + expect(list.find('[data-row="1"]').exists()).toBe(false); + expect(list.find('[data-row="999"]').exists()).toBe(true); + expect(list.vm.scrollToKey(-1)).toBe(false); + list.element.focus(); + await nextTick(); + expect(list.find('[data-row="0"]').exists()).toBe(false); + list.unmount(); + }); + + it("renders empty and persistent footer slots", () => { + const list = mount(VirtualList, { + props: { items: [], itemKey, estimateSize: 40 }, + slots: { default: () => "", empty: "No records", footer: "Load more" }, + }); + expect(list.text()).toBe("No recordsLoad more"); + expect(list.find('[role="list"]').exists()).toBe(false); + list.unmount(); + }); +}); diff --git a/packages/vue/src/components/VirtualList.vue b/packages/vue/src/components/VirtualList.vue new file mode 100644 index 0000000..0c6ffcf --- /dev/null +++ b/packages/vue/src/components/VirtualList.vue @@ -0,0 +1,92 @@ + + + diff --git a/packages/vue/src/components/virtual-list-defs.ts b/packages/vue/src/components/virtual-list-defs.ts new file mode 100644 index 0000000..438d930 --- /dev/null +++ b/packages/vue/src/components/virtual-list-defs.ts @@ -0,0 +1,6 @@ +export type { + VirtualListAlignment, + VirtualListHandle, + VirtualListKey, + VirtualListProps, +} from "@mango-write/ui-core/defs"; diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts index da0c70b..1472323 100644 --- a/packages/vue/src/index.ts +++ b/packages/vue/src/index.ts @@ -96,6 +96,8 @@ export { default as UserChip } from "./components/UserChip.vue"; export { default as UserCard } from "./components/UserCard.vue"; export { type UserProfile } from "./components/UserCard.vue"; export { default as UserSelect } from "./components/UserSelect.vue"; +export { default as VirtualList } from "./components/VirtualList.vue"; +export type { VirtualListAlignment, VirtualListHandle, VirtualListKey, VirtualListProps } from "./components/virtual-list-defs"; export { type UserSelectOption } from "./components/user-select"; export { useComboPanel, type ComboPanelAnchor, type ComboPanelOptions, type ComboPanelPlacement } from "./lib/useComboPanel"; export { vTooltip } from "./lib/tooltip"; diff --git a/packages/vue/vite.config.ts b/packages/vue/vite.config.ts index e2bcfdc..6b8e679 100644 --- a/packages/vue/vite.config.ts +++ b/packages/vue/vite.config.ts @@ -10,6 +10,7 @@ const peers = [ "lucide-vue-next", "reka-ui", "@tanstack/vue-table", + "@tanstack/vue-virtual", "@mango-write/ui-core", ]; diff --git a/playground/dev/api/entries/virtual-list.ts b/playground/dev/api/entries/virtual-list.ts new file mode 100644 index 0000000..e37b26c --- /dev/null +++ b/playground/dev/api/entries/virtual-list.ts @@ -0,0 +1,21 @@ +import type { ApiEntry } from "../types"; + +export const api: ApiEntry = { + slug: "virtual-list", + component: "VirtualList", + title: { zh: "虚拟列表", en: "VirtualList" }, + importPath: "@mango-write/ui-vue", + rows: [ + { name: "items", kind: "prop", type: "readonly T[]", desc: { zh: "已加载的条目", en: "Loaded items" } }, + { name: "itemKey", kind: "prop", type: "(item: T) => string | number", desc: { zh: "条目的稳定唯一键", en: "Stable, unique item key" } }, + { + name: "estimateSize", kind: "prop", type: "number | ((item: T, index: number) => number)", + desc: { zh: "实际测量前的预估行高(像素)", en: "Estimated row height in pixels before measurement" }, + }, + { name: "overscan", kind: "prop", type: "number", desc: { zh: "视口两侧额外渲染的条数,默认 5", en: "Extra rendered rows on each side of the viewport, defaults to 5" } }, + { name: "pinnedKeys", kind: "prop", type: "readonly VirtualListKey[]", desc: { zh: "滚出视口后仍保留的条目", en: "Rows to retain outside the viewport" } }, + { name: "default", kind: "slot", type: "{ item: T; index: number }", desc: { zh: "条目内容", en: "Item content" } }, + { name: "empty", kind: "slot", desc: { zh: "列表没有条目时的内容", en: "Content for an empty list" } }, + { name: "footer", kind: "slot", desc: { zh: "列表末尾的永久挂载区域", en: "Always-mounted area after the list" } }, + ], +}; diff --git a/playground/dev/pages/components/virtual-list.vue b/playground/dev/pages/components/virtual-list.vue new file mode 100644 index 0000000..c9730bf --- /dev/null +++ b/playground/dev/pages/components/virtual-list.vue @@ -0,0 +1,55 @@ + + + diff --git a/playground/dev/registry-data.ts b/playground/dev/registry-data.ts index 6df14b6..9e7f099 100644 --- a/playground/dev/registry-data.ts +++ b/playground/dev/registry-data.ts @@ -576,6 +576,14 @@ export const docGroups: DocGroup[] = [ en: "A table for homogeneous structured records: references, members, usage line items. The frame is a grouped card, rows split by hairlines, numeric columns align on tabular figures.", }, ), + component( + "virtual-list", + { zh: "虚拟列表", en: "VirtualList" }, + { + zh: "连续浏览长列表,按可见范围渲染可变高度的条目,支持按条目定位。", + en: "Browse long, continuous lists with variable-height rows and jump to a specific entry.", + }, + ), component( "paginator", { zh: "分页", en: "Paginator" }, diff --git a/playground/dev/usage/entries/virtual-list.ts b/playground/dev/usage/entries/virtual-list.ts new file mode 100644 index 0000000..e001d5e --- /dev/null +++ b/playground/dev/usage/entries/virtual-list.ts @@ -0,0 +1,59 @@ +import { defineComponent, h, ref, type Component } from "vue"; +import { Button, VirtualList, type VirtualListHandle } from "@mango-write/ui-vue"; +import { t } from "../../i18n"; +import { sfc } from "../codegen"; +import type { UsageEntry } from "../types"; + +const records = Array.from({ length: 1000 }, (_, i) => i + 1); +const key = (item: number) => item; +const text = { + jump: { zh: "跳到第 500 条", en: "Jump to record 500" }, + list: { zh: "记录列表", en: "Records" }, + details: { zh: "展开后仍会自动测量行高。", en: "The row is measured again after expansion." }, +}; +const rowStyle = "padding:var(--space-2);border-bottom:1px solid var(--border-subtle)"; +const viewportStyle = "height:16rem"; +const List = VirtualList as unknown as Component; + +const Demo = defineComponent({ + setup() { + const list = ref(null); + return () => h("div", { style: "width:100%" }, [ + h(Button, { label: t(text.jump), severity: "secondary", onClick: () => list.value?.scrollToKey(500) }), + h(List, { + ref: list, items: records, itemKey: key, estimateSize: 40, style: viewportStyle, "aria-label": t(text.list), + }, { + default: ({ item }: { item: number }) => h("div", { style: rowStyle }, item % 5 === 0 + ? [h("details", [h("summary", String(item)), h("p", t(text.details))])] + : String(item)), + }), + ]); + }, +}); + +export const usage: UsageEntry = { + slug: "virtual-list", + component: List, + tag: "VirtualList", + controls: [], + render: () => h(Demo), + code: () => sfc({ + ui: ["VirtualList"], + vue: [], + setup: ["const items = Array.from({ length: 1000 }, (_, i) => i + 1);"], + template: ` + +`, + }), + reactCode: () => `import { VirtualList } from "@mango-write/ui-react"; + +const items = Array.from({ length: 1000 }, (_, i) => i + 1); + +export default function Example() { + return ( + item} estimateSize={40} aria-label="Records" style={{ height: "16rem" }}> + {item =>
{item}
} +
+ ); +}`, +}; diff --git a/playground/react-preview/entries-display-overlays.tsx b/playground/react-preview/entries-display-overlays.tsx index d10f5ea..31947da 100644 --- a/playground/react-preview/entries-display-overlays.tsx +++ b/playground/react-preview/entries-display-overlays.tsx @@ -1,4 +1,4 @@ -import { useState } from "react"; +import { useRef, useState } from "react"; import { Bookmark, Check, @@ -63,6 +63,7 @@ import { Tooltip, UserCard, UserChip, + VirtualList, type AsyncSlotSkeleton, type AsyncSlotStatus, type AvatarShape, @@ -86,6 +87,7 @@ import { type UserChipSize, type UserChipVariant, type UserProfile, + type VirtualListHandle, } from "@mango-write/ui-react"; import type { ReactEntryRenderer, ReactPreviewContext } from "./types"; @@ -358,7 +360,31 @@ function AdminShellDemo({ ctx }: { ctx: ReactPreviewContext }) { ); } +const recordIds = Array.from({ length: 1000 }, (_, i) => i + 1); +const recordKey = (item: number) => item; + +function VirtualListDemo({ locale }: { locale: ReactPreviewContext["locale"] }) { + const list = useRef(null); + const zh = locale === "zh-CN"; + return ( +
+
+ ); +} + export const DISPLAY_OVERLAY_REACT_ENTRIES: Record = { + "virtual-list": ({ locale }) => , avatar: ({ values: v }) => ( =16.8' react-dom: '>=16.8' + '@tanstack/react-virtual@3.14.26': + resolution: {integrity: sha512-HUDlfsrYH6ko5xH56L62Mcl/uzT+AGVNMHFuDNqDJMdZWc1AQa2oeVKNUvZ/RWBZQ4TYtyQerFrNvLnp39h65A==} + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + '@tanstack/table-core@8.21.3': resolution: {integrity: sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==} engines: {node: '>=12'} @@ -3299,6 +3311,12 @@ snapshots: react: 19.3.1 react-dom: 19.3.1(react@19.3.1) + '@tanstack/react-virtual@3.14.26(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@tanstack/virtual-core': 3.19.11 + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + '@tanstack/table-core@8.21.3': {} '@tanstack/virtual-core@3.19.11': {}