From c7dc66382a61a9e058c667c7aa24ed0f2fe83e44 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 07:44:14 +0000 Subject: [PATCH 1/7] Read a numberLocale's own digits in NumberInput (#66, 2.1) Co-Authored-By: Claude Opus 5.5 --- .changeset/number-input-locale-digits.md | 5 ++++ docs/text-inputs/number-input.md | 2 +- .../components/inputs/number-input.test.tsx | 26 ++++++++++++++++++- .../src/components/inputs/number-input.tsx | 17 +++++++++--- 4 files changed, 45 insertions(+), 5 deletions(-) create mode 100644 .changeset/number-input-locale-digits.md diff --git a/.changeset/number-input-locale-digits.md b/.changeset/number-input-locale-digits.md new file mode 100644 index 00000000..0da9e22a --- /dev/null +++ b/.changeset/number-input-locale-digits.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`NumberInput` reads and edits numbers in a `numberLocale` with its own digits (for example Arabic-Indic `١٢٣` in `ar-EG`). It used to reject them, so it couldn't parse its own draft. `numberSymbols()` also returns the locale's `digits`. diff --git a/docs/text-inputs/number-input.md b/docs/text-inputs/number-input.md index 0e14be90..09802b1d 100644 --- a/docs/text-inputs/number-input.md +++ b/docs/text-inputs/number-input.md @@ -87,7 +87,7 @@ With a `name` (or inside a `FormField` with `name`), the raw number is submitted | `startAddon` / `endAddon` | `ReactNode` | | Your own addons; the unit sits between them and the number | | `classNames` | `{ root, input, startAddon, endAddon, unit, unitTrigger, decrement, increment }` | | Classes for each part | -Also exported: `parseLocaleNumber(text, numberLocale)`, `numberSymbols(numberLocale)`, `numberInputVariants` and the `NumberInputUnitOption`, `NumberInputFieldProps` and `NumberInputStepperProps` types. +Also exported: `parseLocaleNumber(text, numberLocale)`, `numberSymbols(numberLocale)` (group and decimal separators, and the locale's digits), `numberInputVariants` and the `NumberInputUnitOption`, `NumberInputFieldProps` and `NumberInputStepperProps` types. ## RTL and Thaana diff --git a/packages/onu/src/components/inputs/number-input.test.tsx b/packages/onu/src/components/inputs/number-input.test.tsx index 9051fd95..6aca2cf5 100644 --- a/packages/onu/src/components/inputs/number-input.test.tsx +++ b/packages/onu/src/components/inputs/number-input.test.tsx @@ -4,6 +4,7 @@ import userEvent from "@testing-library/user-event" import { afterEach, describe, expect, it, vi } from "vitest" import { directions, expectNoA11yViolations, renderWithOnu } from "../../../test/utils" +import { en } from "../../locales/en" import { FormField } from "../form/form-field" import { NumberInput, numberSymbols, parseLocaleNumber } from "./number-input" @@ -13,6 +14,11 @@ vi.setConfig({ testTimeout: 30_000 }) afterEach(() => vi.useRealTimers()) describe("parseLocaleNumber", () => { + it("reads a locale's own digits, such as Arabic-Indic", () => { + expect(parseLocaleNumber("١٬٢٣٤٫٥", "ar-EG")).toBe(1234.5) + expect(parseLocaleNumber("١٢3", "ar-EG")).toBe(123) + }) + it("parses locale-formatted numbers", () => { expect(parseLocaleNumber("1,234.5", "en")).toBe(1234.5) expect(parseLocaleNumber(" -12 ", "en")).toBe(-12) @@ -20,11 +26,29 @@ describe("parseLocaleNumber", () => { expect(parseLocaleNumber("", "en")).toBeNull() expect(parseLocaleNumber("-", "en")).toBeUndefined() expect(parseLocaleNumber("1.234,5", "de")).toBe(1234.5) - expect(numberSymbols("de")).toEqual({ group: ".", decimal: "," }) + expect(numberSymbols("de")).toEqual({ + group: ".", + decimal: ",", + digits: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], + }) }) }) describe("NumberInput", () => { + it("edits its own draft with a numberLocale that uses other digits", async () => { + const onValueChange = vi.fn() + renderWithOnu(, { + locale: { ...en, numberLocale: "ar-EG" }, + }) + const input = screen.getByRole("spinbutton", { name: "Amount" }) + await userEvent.click(input) + expect(input).toHaveValue("١٢") + await userEvent.type(input, "3") + expect(onValueChange).toHaveBeenLastCalledWith(123) + await userEvent.type(input, "{Backspace}٤") + expect(onValueChange).toHaveBeenLastCalledWith(124) + }) + it("formats when not editing and shows the raw number while editing", async () => { const onValueChange = vi.fn() renderWithOnu() diff --git a/packages/onu/src/components/inputs/number-input.tsx b/packages/onu/src/components/inputs/number-input.tsx index 4eff3069..7af3b9f8 100644 --- a/packages/onu/src/components/inputs/number-input.tsx +++ b/packages/onu/src/components/inputs/number-input.tsx @@ -123,25 +123,35 @@ function decimalsOf(n: number | undefined) { /** Locale number symbols, e.g. `{ group: ",", decimal: "." }`. */ export function numberSymbols(numberLocale: string) { const parts = new Intl.NumberFormat(numberLocale).formatToParts(-12345.6) + const plain = new Intl.NumberFormat(numberLocale, { useGrouping: false }) return { group: parts.find((p) => p.type === "group")?.value ?? ",", decimal: parts.find((p) => p.type === "decimal")?.value ?? ".", + /** The locale's own digits 0–9 (e.g. Arabic-Indic `٠`–`٩`), which may differ from ASCII. */ + digits: Array.from({ length: 10 }, (_, i) => plain.format(i)), } } +/** Bidi marks some locales put around numbers (ALM, LRM, RLM). */ +const BIDI_MARKS = /[\u061c\u200e\u200f]/g + /** * Parses user input in the given locale. Returns `null` for an empty string, * and `undefined` when the text is not (yet) a number, e.g. `"-"`. */ export function parseLocaleNumber(text: string, numberLocale: string): number | null | undefined { - const { group, decimal } = numberSymbols(numberLocale) - const cleaned = text + const { group, decimal, digits } = numberSymbols(numberLocale) + let cleaned = text .trim() + .replace(BIDI_MARKS, "") .replace(/[\s\u00a0\u202f]/g, "") .split(group) .join("") .replace(decimal, ".") .replace(/^[\u2212]/, "-") + digits.forEach((digit, i) => { + if (digit !== String(i)) cleaned = cleaned.split(digit).join(String(i)) + }) if (cleaned === "") return null if (!/^[-+]?(\d+\.?\d*|\.\d+)$/.test(cleaned)) return undefined const n = Number(cleaned) @@ -423,7 +433,8 @@ export function NumberInput(allProps: NumberInputProps) { }} onChange={(e) => { const text = e.target.value - if (!/^[\d\s\u00a0\u202f.,'\u2019\u066b\u066c+\-\u2212]*$/.test(text)) return + // Any script's digits (\p{Nd}), so a numberLocale with its own digits can edit its draft. + if (!/^[\p{Nd}\s\u00a0\u202f.,'\u2019\u066b\u066c\u061c\u200e\u200f+\-\u2212]*$/u.test(text)) return const parsed = fromText(text) // An emptied stepper keeps its value until blur, so the field can be cleared and retyped. const settled = parsed !== undefined && !(stepper && parsed === null) From bac2b044c3e0b672b8d75086030251ac210dfcd7 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 07:51:37 +0000 Subject: [PATCH 2/7] Build apps without MapChart's optional peers (#66, 8.12) MapChart's Google renderer now imports @vis.gl/react-google-maps and deck.gl inside try, so webpack treats them as optional, and falls back to the table when they are missing. A fixture outside the workspace builds an app without the optional peers with webpack and Turbopack in CI. Co-Authored-By: Claude Opus 5.5 --- .changeset/optional-map-peers.md | 5 ++ .github/workflows/ssr.yml | 6 +++ AGENTS.md | 1 + docs/charts/map-chart.md | 2 +- e2e/optional-peers/README.md | 10 ++++ e2e/optional-peers/app/layout.tsx | 7 +++ e2e/optional-peers/app/page.tsx | 21 ++++++++ e2e/optional-peers/package.json | 20 +++++++ e2e/optional-peers/tsconfig.json | 19 +++++++ .../onu/src/charts/_map-chart-google.test.tsx | 12 ++++- packages/onu/src/charts/_map-chart-google.tsx | 52 +++++++++++++++---- .../onu/src/charts/map-chart-peers.test.tsx | 48 +++++++++++++++++ packages/onu/src/charts/map-chart.test.tsx | 1 + packages/onu/src/charts/map-chart.tsx | 29 +++++++++-- packages/onu/src/locales/dv/chart.ts | 2 + packages/onu/src/locales/en/chart.ts | 2 + scripts/check-optional-peers.mjs | 34 ++++++++++++ 17 files changed, 254 insertions(+), 17 deletions(-) create mode 100644 .changeset/optional-map-peers.md create mode 100644 e2e/optional-peers/README.md create mode 100644 e2e/optional-peers/app/layout.tsx create mode 100644 e2e/optional-peers/app/page.tsx create mode 100644 e2e/optional-peers/package.json create mode 100644 e2e/optional-peers/tsconfig.json create mode 100644 packages/onu/src/charts/map-chart-peers.test.tsx create mode 100644 scripts/check-optional-peers.mjs diff --git a/.changeset/optional-map-peers.md b/.changeset/optional-map-peers.md new file mode 100644 index 00000000..cc7226ac --- /dev/null +++ b/.changeset/optional-map-peers.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +An app that uses `@javaabu/onu/charts` without the optional map peers (`@vis.gl/react-google-maps`, deck.gl) now builds with webpack too; it used to fail with "Module not found". `MapChart` loads them on demand and, when they are missing, shows a note and the data table instead of the map. diff --git a/.github/workflows/ssr.yml b/.github/workflows/ssr.yml index dde21728..926b8e72 100644 --- a/.github/workflows/ssr.yml +++ b/.github/workflows/ssr.yml @@ -9,6 +9,8 @@ on: paths: - packages/onu/** - e2e/nextjs/** + - e2e/optional-peers/** + - scripts/check-optional-peers.mjs - pnpm-lock.yaml - pnpm-workspace.yaml - .github/workflows/ssr.yml @@ -16,6 +18,8 @@ on: paths: - packages/onu/** - e2e/nextjs/** + - e2e/optional-peers/** + - scripts/check-optional-peers.mjs - pnpm-lock.yaml - pnpm-workspace.yaml - .github/workflows/ssr.yml @@ -50,3 +54,5 @@ jobs: run: pnpm --filter onu-nextjs-fixture build - name: Check the server HTML and hydration run: pnpm --filter onu-nextjs-fixture test:ssr + - name: Build an app without the optional peers (webpack and Turbopack) + run: node scripts/check-optional-peers.mjs diff --git a/AGENTS.md b/AGENTS.md index 13969a95..259d7ffb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,6 +30,7 @@ pnpm build && pnpm --filter @javaabu/onu size # build + bundle budgets pnpm build:web # docs site node scripts/check-docs.mjs # every component has a docs page with Props + Accessibility node scripts/check-pack.mjs # no test files in the npm tarballs +node scripts/check-optional-peers.mjs # an app without the optional peers still builds (after pnpm build) pnpm e2e:chromium # Playwright (a11y with axe, visual) ``` diff --git a/docs/charts/map-chart.md b/docs/charts/map-chart.md index d8595353..ffadc164 100644 --- a/docs/charts/map-chart.md +++ b/docs/charts/map-chart.md @@ -6,7 +6,7 @@ sidebar_position: 9 A choropleth map: regions shaded by value on Google Maps, drawn with a deck.gl `GeoJsonLayer` (`GoogleMapsOverlay`). It has a stepped legend, a tap/hover read-out and a data table. Without a Google Maps API key it shows an accessible notice and the table instead. :::info -Needs the optional peers `@vis.gl/react-google-maps`, `@deck.gl/core`, `@deck.gl/layers` and `@deck.gl/google-maps`. The map code is loaded lazily, only when an API key is configured. +Needs the optional peers `@vis.gl/react-google-maps`, `@deck.gl/core`, `@deck.gl/layers` and `@deck.gl/google-maps`. The map code is loaded lazily, only when an API key is configured. If those peers are not installed, the app still builds (with webpack or Turbopack) and the chart shows a note and the data table instead of the map. ::: ```tsx diff --git a/e2e/optional-peers/README.md b/e2e/optional-peers/README.md new file mode 100644 index 00000000..f46530c5 --- /dev/null +++ b/e2e/optional-peers/README.md @@ -0,0 +1,10 @@ +# Optional peers fixture + +A Next.js app that uses `@javaabu/onu`, `@javaabu/onu/charts` (Recharts only) and +`@javaabu/onu/export` with **none** of the optional peers that Onu loads on demand +(deck.gl, `@vis.gl/react-google-maps`, `write-excel-file`, …) installed. + +It is not part of the pnpm workspace on purpose: inside the workspace every peer +resolves from the monorepo, which hides a missing one. `scripts/check-optional-peers.mjs` +packs the library, installs this app from the tarball in a temporary folder and builds +it with webpack and with Turbopack. diff --git a/e2e/optional-peers/app/layout.tsx b/e2e/optional-peers/app/layout.tsx new file mode 100644 index 00000000..0b1163df --- /dev/null +++ b/e2e/optional-peers/app/layout.tsx @@ -0,0 +1,7 @@ +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + {children} + + ) +} diff --git a/e2e/optional-peers/app/page.tsx b/e2e/optional-peers/app/page.tsx new file mode 100644 index 00000000..4d83ad72 --- /dev/null +++ b/e2e/optional-peers/app/page.tsx @@ -0,0 +1,21 @@ +"use client" + +import { Button } from "@javaabu/onu" +import { CategoryChart, MapChart } from "@javaabu/onu/charts" +import { exportCsv, exportExcel } from "@javaabu/onu/export" + +const rows = [{ name: "Malé", value: 1 }] +const columns = [{ header: "Name", accessor: "name" as const }] + +// MapChart lazy-loads deck.gl and @vis.gl/react-google-maps, and exportExcel loads +// write-excel-file: none are installed here, and the app must still build. +export default function Page() { + return ( +
+ + + + +
+ ) +} diff --git a/e2e/optional-peers/package.json b/e2e/optional-peers/package.json new file mode 100644 index 00000000..5cd23e0c --- /dev/null +++ b/e2e/optional-peers/package.json @@ -0,0 +1,20 @@ +{ + "name": "onu-optional-peers-fixture", + "private": true, + "type": "module", + "dependencies": { + "@javaabu/onu": "file:ONU_TARBALL", + "@tanstack/react-query": "^5.104.1", + "next": "^16.4.3", + "react": "^19.3.0", + "react-dom": "^19.3.0", + "react-hook-form": "^7.89.0", + "recharts": "^3.2.1", + "tailwindcss": "^4.3.3" + }, + "devDependencies": { + "@types/node": "^26.6.4", + "@types/react": "^19.3.0", + "typescript": "~6.0.3" + } +} diff --git a/e2e/optional-peers/tsconfig.json b/e2e/optional-peers/tsconfig.json new file mode 100644 index 00000000..37ab9748 --- /dev/null +++ b/e2e/optional-peers/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["dom", "esnext"], + "jsx": "react-jsx", + "module": "esnext", + "moduleResolution": "bundler", + "strict": true, + "skipLibCheck": true, + "noEmit": true, + "esModuleInterop": true, + "isolatedModules": true, + "resolveJsonModule": true, + "allowJs": true, + "plugins": [{ "name": "next" }] + }, + "include": ["**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/packages/onu/src/charts/_map-chart-google.test.tsx b/packages/onu/src/charts/_map-chart-google.test.tsx index 5be2a9c6..55ea6e2a 100644 --- a/packages/onu/src/charts/_map-chart-google.test.tsx +++ b/packages/onu/src/charts/_map-chart-google.test.tsx @@ -2,7 +2,7 @@ import { render } from "@testing-library/react" import * as React from "react" import { afterEach, describe, expect, it, vi } from "vitest" -import GoogleChoropleth, { resolveCssColor } from "./_map-chart-google" +import GoogleChoropleth, { loadMapPeers, resolveCssColor, type MapPeers } from "./_map-chart-google" import { choroplethRegions, type GeoJsonFeatureCollection } from "./choropleth" const overlays: { setMap: ReturnType; setProps: ReturnType }[] = [] @@ -82,7 +82,14 @@ describe("resolveCssColor", () => { }) describe("GoogleChoropleth", () => { - it("adds a deck.gl GeoJsonLayer to the map and reports hover and tap", () => { + it("loads the map peers when they are installed", async () => { + const peers = await loadMapPeers() + expect(peers?.deckLayers.GeoJsonLayer).toBeDefined() + expect(peers?.vis.APIProvider).toBeDefined() + }) + + it("adds a deck.gl GeoJsonLayer to the map and reports hover and tap", async () => { + const peers = (await loadMapPeers()) as MapPeers vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null) const { regions } = choroplethRegions(geojson, [{ id: "K", value: 10 }]) const onSelect = vi.fn() @@ -96,6 +103,7 @@ describe("GoogleChoropleth", () => { center={{ lat: 3, lng: 73 }} zoom={6} onSelect={onSelect} + peers={peers} />, ) expect(getByTestId("api")).toHaveAttribute("data-key", "key") diff --git a/packages/onu/src/charts/_map-chart-google.tsx b/packages/onu/src/charts/_map-chart-google.tsx index b9648f90..0e0d1b94 100644 --- a/packages/onu/src/charts/_map-chart-google.tsx +++ b/packages/onu/src/charts/_map-chart-google.tsx @@ -2,11 +2,13 @@ // Loaded lazily by MapChart only when a Google Maps API key is configured, so the // map peers (@vis.gl/react-google-maps, deck.gl) stay out of the main chart bundle. +// They are optional peers: only type imports here, and `loadMapPeers` imports them +// inside `try`, so an app without them still builds (bundlers treat them as optional). import * as React from "react" -import { GoogleMapsOverlay } from "@deck.gl/google-maps" -import { GeoJsonLayer } from "@deck.gl/layers" -import { APIProvider, Map, useMap } from "@vis.gl/react-google-maps" +import type * as DeckGoogleMaps from "@deck.gl/google-maps" +import type * as DeckLayers from "@deck.gl/layers" +import type * as VisGoogleMaps from "@vis.gl/react-google-maps" import { useOnu } from "../providers/onu-provider" import { useTheme } from "../providers/theme-provider" @@ -14,6 +16,27 @@ import { stepOpacity, type ChoroplethRegion } from "./choropleth" type Rgba = [number, number, number, number] +/** The optional peers the map needs. */ +export interface MapPeers { + vis: typeof VisGoogleMaps + deckGoogleMaps: typeof DeckGoogleMaps + deckLayers: typeof DeckLayers +} + +/** Loads the map peers, or returns `null` when one is not installed. */ +export async function loadMapPeers(): Promise { + try { + const [vis, deckGoogleMaps, deckLayers] = await Promise.all([ + import("@vis.gl/react-google-maps"), + import("@deck.gl/google-maps"), + import("@deck.gl/layers"), + ]) + return { vis, deckGoogleMaps, deckLayers } + } catch { + return null + } +} + const FALLBACK: Rgba = [100, 116, 139, 255] /** @@ -46,6 +69,7 @@ export interface GoogleChoroplethProps { center: { lat: number; lng: number } zoom: number onSelect: (region: ChoroplethRegion | null) => void + peers: MapPeers } function ChoroplethOverlay({ @@ -54,12 +78,13 @@ function ChoroplethOverlay({ color, onSelect, hostRef, -}: Pick & { + peers, +}: Pick & { hostRef: React.RefObject }) { - const map = useMap() + const map = peers.vis.useMap() const { resolvedTheme } = useTheme() - const overlay = React.useMemo(() => new GoogleMapsOverlay({ interleaved: true }), []) + const overlay = React.useMemo(() => new peers.deckGoogleMaps.GoogleMapsOverlay({ interleaved: true }), [peers]) React.useEffect(() => { if (!map) return @@ -78,7 +103,7 @@ function ChoroplethOverlay({ const byFeature = new globalThis.Map(regions.map((r) => [r.feature, r])) overlay.setProps({ layers: [ - new GeoJsonLayer({ + new peers.deckLayers.GeoJsonLayer({ id: "onu-choropleth", data: regions.map((r) => r.feature) as never, pickable: true, @@ -101,7 +126,7 @@ function ChoroplethOverlay({ }), ], }) - }, [overlay, regions, steps, color, hostRef, resolvedTheme, onSelect]) + }, [overlay, regions, steps, color, hostRef, resolvedTheme, onSelect, peers]) return null } @@ -117,7 +142,9 @@ export default function GoogleChoropleth({ center, zoom, onSelect, + peers, }: GoogleChoroplethProps) { + const { APIProvider, Map } = peers.vis const { locale } = useOnu() const { resolvedTheme } = useTheme() const hostRef = React.useRef(null) @@ -136,7 +163,14 @@ export default function GoogleChoropleth({ zoomControl className="size-full" > - + diff --git a/packages/onu/src/charts/map-chart-peers.test.tsx b/packages/onu/src/charts/map-chart-peers.test.tsx new file mode 100644 index 00000000..7574abe3 --- /dev/null +++ b/packages/onu/src/charts/map-chart-peers.test.tsx @@ -0,0 +1,48 @@ +import { screen } from "@testing-library/react" +import { describe, expect, it, vi } from "vitest" + +import { expectNoA11yViolations, renderWithOnu } from "../../test/utils" +import type { GeoJsonFeatureCollection } from "./choropleth" +import { MapChart } from "./map-chart" + +// An app that has not installed deck.gl: importing it fails. +vi.mock("@deck.gl/layers", () => { + throw new Error("Cannot find module '@deck.gl/layers'") +}) + +const geojson: GeoJsonFeatureCollection = { + type: "FeatureCollection", + features: [ + { + type: "Feature", + properties: { id: "K", name: "Kaafu" }, + geometry: { + type: "Polygon", + coordinates: [ + [ + [0, 0], + [1, 0], + [1, 1], + [0, 0], + ], + ], + }, + }, + ], +} + +describe("MapChart without its optional map peers", () => { + it("loadMapPeers returns null when a peer is not installed", async () => { + const { loadMapPeers } = await import("./_map-chart-google") + await expect(loadMapPeers()).resolves.toBeNull() + }) + + it("falls back to a note and the data table instead of crashing", async () => { + renderWithOnu(, { + provider: { maps: { googleMapsApiKey: "test-key" } }, + }) + expect(await screen.findByText(/map packages are not installed/)).toBeInTheDocument() + expect(screen.getByRole("table")).toHaveTextContent("Kaafu") + await expectNoA11yViolations() + }) +}) diff --git a/packages/onu/src/charts/map-chart.test.tsx b/packages/onu/src/charts/map-chart.test.tsx index 87245fa7..24c87a95 100644 --- a/packages/onu/src/charts/map-chart.test.tsx +++ b/packages/onu/src/charts/map-chart.test.tsx @@ -9,6 +9,7 @@ import { MapChart } from "./map-chart" const selectRef: { current: ((r: unknown) => void) | null } = { current: null } vi.mock("./_map-chart-google", () => ({ + loadMapPeers: async () => ({}), default: (props: { regions: unknown[]; onSelect: (r: unknown) => void; apiKey: string }) => { selectRef.current = props.onSelect return
diff --git a/packages/onu/src/charts/map-chart.tsx b/packages/onu/src/charts/map-chart.tsx index 9edf857d..8ce91003 100644 --- a/packages/onu/src/charts/map-chart.tsx +++ b/packages/onu/src/charts/map-chart.tsx @@ -7,6 +7,7 @@ import { cn } from "../lib/utils" import { useOnu } from "../providers/onu-provider" import { Skeleton } from "../ui/skeleton" import { chartColor, ChartFrame, type ChartBaseProps, type ChartDatum } from "./_shared" +import type { GoogleChoroplethProps } from "./_map-chart-google" import { choroplethRegions, stepOpacity, type ChoroplethRegion, type GeoJsonFeatureCollection } from "./choropleth" import { useChartFormat, type ValueFormat } from "./format" import { registerEnglish } from "../i18n/english" @@ -42,7 +43,20 @@ export interface MapChartProps extends Omit { showTableToggle?: boolean } -const GoogleChoropleth = React.lazy(() => import("./_map-chart-google")) +type GoogleChoroplethLoaderProps = Omit & { onUnavailable: () => void } + +// The map peers are optional: when one is missing, MapChart falls back to the table. +const GoogleChoropleth = React.lazy(async () => { + const { default: GoogleMap, loadMapPeers } = await import("./_map-chart-google") + const peers = await loadMapPeers() + function GoogleChoroplethLoader({ onUnavailable, ...props }: GoogleChoroplethLoaderProps) { + React.useEffect(() => { + if (!peers) onUnavailable() + }, [onUnavailable]) + return peers ? : null + } + return { default: GoogleChoroplethLoader } +}) /** * Choropleth map on Google Maps with a deck.gl `GeoJsonLayer`. Regions are shaded by value, @@ -69,6 +83,10 @@ export function MapChart({ const { t, maps } = useOnu() const fmt = useChartFormat(valueFormat) const apiKey = maps.googleMapsApiKey + // Set when @vis.gl/react-google-maps or deck.gl is not installed. + const [peersMissing, setPeersMissing] = React.useState(false) + const onUnavailable = React.useCallback(() => setPeersMissing(true), []) + const showMap = !!apiKey && !peersMissing // Keep the id, not the region: the read-out shows the region as it is in the current data. const [selectedId, setSelectedId] = React.useState(null) @@ -124,7 +142,7 @@ export function MapChart({
) - const readout = apiKey ? ( + const readout = showMap ? (

{selected ? t("chart.selectedRegion", { @@ -144,9 +162,9 @@ export function MapChart({ autoSummary={summary} table={table} isEmpty={!regions.length} - forceTable={!apiKey} + forceTable={!showMap} lead={ - apiKey ? ( + showMap ? ( legend ) : (

-

{t("chart.mapUnavailable")}

+

{t(apiKey ? "chart.mapPeersMissing" : "chart.mapUnavailable")}

) } @@ -187,6 +205,7 @@ export function MapChart({ center={center} zoom={zoom} onSelect={(region: ChoroplethRegion | null) => setSelectedId(region?.id ?? null)} + onUnavailable={onUnavailable} /> diff --git a/packages/onu/src/locales/dv/chart.ts b/packages/onu/src/locales/dv/chart.ts index dbdaf46a..873c5157 100644 --- a/packages/onu/src/locales/dv/chart.ts +++ b/packages/onu/src/locales/dv/chart.ts @@ -40,6 +40,8 @@ export const chart = { region: "ސަރަހައްދު", legend: "ކުލަތަކުގެ މާނަ", mapUnavailable: "ގޫގުލް މެޕްސް API ކީއެއް ނެތުމުން ފަށްޓަރު ދެއްކޭކަށް ނެތް. ޑޭޓާ ތިރީގައިވާ ޖަދުވަލުގައި އެބައޮތް.", + mapPeersMissing: + "ފަށްޓަރުގެ ޕެކޭޖުތައް އިންސްޓޯލް ނުކުރެވިފައިވާތީ ފަށްޓަރު ދެއްކޭކަށް ނެތް. ޑޭޓާ ތިރީގައިވާ ޖަދުވަލުގައި އެބައޮތް.", mapLoading: "ފަށްޓަރު ލޯޑުވަނީ…", selectedRegion: "{name}: {value}", mapHint: "ސަރަހައްދެއްގެ އަދަދު ބެއްލެވުމަށް އޭގައި ފިތާލައްވާ.", diff --git a/packages/onu/src/locales/en/chart.ts b/packages/onu/src/locales/en/chart.ts index bdac41e3..316e6164 100644 --- a/packages/onu/src/locales/en/chart.ts +++ b/packages/onu/src/locales/en/chart.ts @@ -40,6 +40,8 @@ export const chart = { region: "Region", legend: "Legend", mapUnavailable: "The map cannot be shown because no Google Maps API key is set. The data is in the table below.", + mapPeersMissing: + "The map cannot be shown because its map packages are not installed. The data is in the table below.", mapLoading: "Loading map…", selectedRegion: "{name}: {value}", mapHint: "Tap or hover over a region to see its value.", diff --git a/scripts/check-optional-peers.mjs b/scripts/check-optional-peers.mjs new file mode 100644 index 00000000..faba97fc --- /dev/null +++ b/scripts/check-optional-peers.mjs @@ -0,0 +1,34 @@ +#!/usr/bin/env node +// Builds e2e/optional-peers (a Next.js app without Onu's optional peers) against a packed +// copy of @javaabu/onu, with webpack and with Turbopack. Run `pnpm build` first. +// Outside the workspace on purpose: there, every peer resolves from the monorepo. +import { execFileSync } from "node:child_process" +import { cpSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join, resolve } from "node:path" + +const root = resolve(import.meta.dirname, "..") +const work = mkdtempSync(join(tmpdir(), "onu-optional-peers-")) +const run = (cmd, args, cwd) => + execFileSync(cmd, args, { cwd, stdio: "inherit", env: { ...process.env, NEXT_TELEMETRY_DISABLED: "1" } }) + +try { + run("pnpm", ["pack", "--pack-destination", work], join(root, "packages/onu")) + const tarball = join( + work, + readdirSync(work).find((f) => f.endsWith(".tgz")), + ) + const app = join(work, "app") + cpSync(join(root, "e2e/optional-peers"), app, { recursive: true }) + const pkgPath = join(app, "package.json") + writeFileSync(pkgPath, readFileSync(pkgPath, "utf8").replace("ONU_TARBALL", tarball)) + // npm, not pnpm: a plain app install, outside the workspace. Optional peers are not installed. + run("npm", ["install", "--no-audit", "--no-fund", "--legacy-peer-deps"], app) + for (const bundler of ["--webpack", "--turbopack"]) { + console.log(`\n▶ next build ${bundler}`) + run("npx", ["next", "build", bundler], app) + } + console.log("\n✓ The app builds with webpack and Turbopack without Onu's optional peers") +} finally { + rmSync(work, { recursive: true, force: true }) +} From 7243381bb13e47fa964aeec4de120d401b34d386 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 07:59:03 +0000 Subject: [PATCH 3/7] Add real-browser checks for behaviour jsdom can't show (#66) Scenarios live in web/src/e2e/*.harness.tsx (served at #/e2e/, not listed) and run from e2e/browser.spec.ts in the E2E smoke workflow. These first checks cover the [P] items that did not reproduce: SortableList focus (6.6), LoadMore auto (4.4), QrCode downloads (8.7) and InlineEdit Cancel in WebKit (2.5). They pass in Chromium and WebKit and stay as regression checks. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/e2e-smoke.yml | 2 +- CONTRIBUTING.md | 6 ++- e2e/browser.spec.ts | 54 ++++++++++++++++++++++++++ web/src/App.tsx | 2 + web/src/components/harness.tsx | 24 ++++++++++++ web/src/e2e/inline-edit.harness.tsx | 13 +++++++ web/src/e2e/load-more-auto.harness.tsx | 35 +++++++++++++++++ web/src/e2e/qr-download.harness.tsx | 6 +++ web/src/e2e/sortable-list.harness.tsx | 23 +++++++++++ 9 files changed, 162 insertions(+), 3 deletions(-) create mode 100644 e2e/browser.spec.ts create mode 100644 web/src/components/harness.tsx create mode 100644 web/src/e2e/inline-edit.harness.tsx create mode 100644 web/src/e2e/load-more-auto.harness.tsx create mode 100644 web/src/e2e/qr-download.harness.tsx create mode 100644 web/src/e2e/sortable-list.harness.tsx diff --git a/.github/workflows/e2e-smoke.yml b/.github/workflows/e2e-smoke.yml index 3bd75ea3..7775e4fb 100644 --- a/.github/workflows/e2e-smoke.yml +++ b/.github/workflows/e2e-smoke.yml @@ -31,7 +31,7 @@ jobs: - run: pnpm install --frozen-lockfile - run: pnpm exec playwright install --with-deps chromium - run: pnpm build:web - - run: pnpm e2e:chromium e2e/a11y.spec.ts e2e/thaana.spec.ts + - run: pnpm e2e:chromium e2e/a11y.spec.ts e2e/thaana.spec.ts e2e/browser.spec.ts - uses: actions/upload-artifact@v4 if: failure() with: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 033e7a90..18291093 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -58,10 +58,12 @@ The files in `packages/onu/src/ui` started as shadcn/ui's components (Radix base E2E (Playwright) runs in two tiers: -- **Smoke, on pull requests.** The **E2E smoke** workflow runs `e2e/a11y.spec.ts` and `e2e/thaana.spec.ts` in Chromium, with no screenshots, when a pull request touches `packages/onu/**`, `web/**` or `e2e/**`. +- **Smoke, on pull requests.** The **E2E smoke** workflow runs `e2e/a11y.spec.ts`, `e2e/thaana.spec.ts` and `e2e/browser.spec.ts` in Chromium, with no screenshots, when a pull request touches `packages/onu/**`, `web/**` or `e2e/**`. - **Full, on demand.** The **E2E** workflow (accessibility in five browsers, and Chromium screenshots) is slow, so CI runs it only when the last commit pushed to `main` starts with `e2e` (for example `e2e: new date picker`), or when you run it by hand from the Actions tab. -Run either locally with `pnpm e2e:chromium`, adding the two spec files for the smoke tier. +Run either locally with `pnpm e2e:chromium`, adding the three spec files for the smoke tier. + +`e2e/browser.spec.ts` covers behaviour jsdom can't show (focus after re-renders, inert modal backgrounds, `IntersectionObserver`, downloads, chart layout). Each scenario is a small page in `web/src/e2e/.harness.tsx`, served at `#/e2e/` and left out of the navigation and the a11y and visual runs. Server rendering has its own check. The **Server rendering** workflow builds the Next.js app in `e2e/nextjs` against the workspace copy of Onu, then checks its server HTML and hydration in English and Dhivehi, when a pull request touches `packages/onu/**` or `e2e/nextjs/**`. Run it locally with `pnpm build && pnpm --filter onu-nextjs-fixture build && pnpm --filter onu-nextjs-fixture test:ssr`. diff --git a/e2e/browser.spec.ts b/e2e/browser.spec.ts new file mode 100644 index 00000000..2c98c897 --- /dev/null +++ b/e2e/browser.spec.ts @@ -0,0 +1,54 @@ +import { expect, test, waitForPage } from "./fixtures" + +// Real-browser checks for behaviour jsdom can't show: focus after re-renders, inert +// modal backgrounds, IntersectionObserver, downloads and chart layout (#66). Each +// scenario lives in web/src/e2e/.harness.tsx, served at #/e2e/. +async function open(page: import("@playwright/test").Page, name: string) { + await page.goto(`/#/e2e/${name}`) + await waitForPage(page, `/#/e2e/${name}`) +} + +test.describe("focus", () => { + test("SortableList keeps focus on the moved item (Move down and Alt+ArrowDown)", async ({ page }) => { + await open(page, "sortable-list") + const items = page.getByRole("list", { name: "Islands" }).getByRole("listitem") + + await page.getByRole("button", { name: "Move Malé down" }).click() + await expect(items.nth(1)).toContainText("Malé") + await expect(page.getByRole("button", { name: "Move Malé down" })).toBeFocused() + + await page.getByRole("button", { name: "Drag to reorder Malé" }).focus() + await page.keyboard.press("Alt+ArrowDown") + await expect(items.nth(2)).toContainText("Malé") + await expect(page.getByRole("button", { name: "Drag to reorder Malé" })).toBeFocused() + }) +}) + +test("LoadMore auto doesn't load again while a load is starting", async ({ page }) => { + await open(page, "load-more-auto") + // Each load adds 5 items after 600 ms; a second call before `loading` is set would be a duplicate request. + await page.waitForTimeout(2500) + const items = await page.getByRole("listitem").count() + const calls = Number(await page.getByTestId("calls").textContent()) + expect(calls).toBeLessThanOrEqual((items - 5) / 5 + 1) +}) + +test("QrCode downloads PNG and SVG files", async ({ page }) => { + await open(page, "qr-download") + for (const name of [/PNG/, /SVG/]) { + const [download] = await Promise.all([page.waitForEvent("download"), page.getByRole("button", { name }).click()]) + expect(await download.failure()).toBeNull() + const chunks: Buffer[] = [] + for await (const chunk of await download.createReadStream()) chunks.push(chunk as Buffer) + expect(Buffer.concat(chunks).length).toBeGreaterThan(100) + } +}) + +test("InlineEdit: clicking Cancel doesn't save", async ({ page }) => { + await open(page, "inline-edit") + await page.getByRole("button", { name: /Edit Name/ }).click() + await page.getByRole("textbox", { name: "Name" }).fill("Changed") + await page.getByRole("button", { name: "Cancel" }).click() + await expect(page.getByTestId("saves")).toHaveText("") + await expect(page.getByRole("button", { name: /Edit Name/ })).toContainText("Aishath Shifa") +}) diff --git a/web/src/App.tsx b/web/src/App.tsx index f58e0276..45a036b3 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -6,6 +6,7 @@ import { DEMO_MAP_ID, googleMapsAdapter, MapProvider } from "@javaabu/onu/maps" import { SearchProvider } from "./components/search" import { BlocksPage } from "./components/blocks" +import { HarnessRoute } from "./components/harness" import { EntryView, PageReady, SectionIndex, componentsSection, pagesSection } from "./components/views" import { demos, pages } from "./registry" import { SettingsProvider, useSettings } from "./settings" @@ -88,6 +89,7 @@ export default function App() { } /> } /> } /> + } /> } /> diff --git a/web/src/components/harness.tsx b/web/src/components/harness.tsx new file mode 100644 index 00000000..770618e2 --- /dev/null +++ b/web/src/components/harness.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import { useParams } from "react-router" + +import { PageReady } from "./views" + +// Scenarios for the real-browser tests in e2e/browser.spec.ts. Unlisted: not in the +// navigation, search, or the a11y and visual loops (those walk showcase/ and pages/). +const harnesses = import.meta.glob<{ default: React.ComponentType }>("../e2e/*.harness.tsx") + +/** `#/e2e/` renders `web/src/e2e/.harness.tsx`. */ +export function HarnessRoute() { + const { name } = useParams() + const load = harnesses[`../e2e/${name}.harness.tsx`] + const Harness = React.useMemo(() => (load ? React.lazy(load) : null), [load]) + if (!Harness) return

No harness named {name}

+ return ( +
+ + + + +
+ ) +} diff --git a/web/src/e2e/inline-edit.harness.tsx b/web/src/e2e/inline-edit.harness.tsx new file mode 100644 index 00000000..0e6e180e --- /dev/null +++ b/web/src/e2e/inline-edit.harness.tsx @@ -0,0 +1,13 @@ +import * as React from "react" +import { InlineEdit } from "@javaabu/onu" + +// 2.5: clicking Cancel must not save first (Safari doesn't focus buttons on click). +export default function InlineEditHarness() { + const [saved, setSaved] = React.useState([]) + return ( +
+ setSaved((s) => [...s, v])} /> + {saved.join("|")} +
+ ) +} diff --git a/web/src/e2e/load-more-auto.harness.tsx b/web/src/e2e/load-more-auto.harness.tsx new file mode 100644 index 00000000..fb40f2e8 --- /dev/null +++ b/web/src/e2e/load-more-auto.harness.tsx @@ -0,0 +1,35 @@ +import * as React from "react" +import { LoadMore } from "@javaabu/onu" + +// 4.4: `auto` with an inline onLoadMore. The parent re-renders when a load starts and only +// sets `loading` a moment later, as an app that fetches in an effect would. +export default function LoadMoreAutoHarness() { + const [count, setCount] = React.useState(5) + const [calls, setCalls] = React.useState(0) + const [loading, setLoading] = React.useState(false) + return ( +
+ {calls} +
    + {Array.from({ length: count }, (_, i) => ( +
  • Item {i + 1}
  • + ))} +
+ { + setCalls((c) => c + 1) + setTimeout(() => setLoading(true), 50) + setTimeout(() => { + setCount((c) => c + 5) + setLoading(false) + }, 600) + }} + /> +
+
+ ) +} diff --git a/web/src/e2e/qr-download.harness.tsx b/web/src/e2e/qr-download.harness.tsx new file mode 100644 index 00000000..60042702 --- /dev/null +++ b/web/src/e2e/qr-download.harness.tsx @@ -0,0 +1,6 @@ +import { QrCode } from "@javaabu/onu/media" + +// 8.7: the PNG and SVG downloads complete in a real browser. +export default function QrDownloadHarness() { + return +} diff --git a/web/src/e2e/sortable-list.harness.tsx b/web/src/e2e/sortable-list.harness.tsx new file mode 100644 index 00000000..1f99daf6 --- /dev/null +++ b/web/src/e2e/sortable-list.harness.tsx @@ -0,0 +1,23 @@ +import * as React from "react" +import { SortableList } from "@javaabu/onu" + +// 6.6: focus after "Move down" and Alt+ArrowDown. +export default function SortableListHarness() { + const [items, setItems] = React.useState(["Malé", "Hulhumalé", "Villimalé"].map((name) => ({ id: name, name }))) + return ( + i.name} + moveButtons + onReorder={setItems} + renderItem={(item, { handle, moveButtons }) => ( +
+ {handle} + {item.name} + {moveButtons} +
+ )} + /> + ) +} From 51847f43875db3579f2b70a39d452f3ef52c3725 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 07:59:03 +0000 Subject: [PATCH 4/7] Keep focus in Form and the comment composer while they process (#66, 6.6) Disabling the fields blurs the focused one; focus now goes back to it when processing ends. Checked in Chromium and WebKit (e2e/browser.spec.ts). Co-Authored-By: Claude Opus 5.5 --- .changeset/focus-after-processing.md | 5 +++++ e2e/browser.spec.ts | 19 ++++++++++++++++++ .../onu/src/components/display/_composer.tsx | 10 ++++++++++ packages/onu/src/components/form/form.tsx | 20 +++++++++++++++++++ web/src/e2e/composer.harness.tsx | 20 +++++++++++++++++++ web/src/e2e/form-enter.harness.tsx | 13 ++++++++++++ 6 files changed, 87 insertions(+) create mode 100644 .changeset/focus-after-processing.md create mode 100644 web/src/e2e/composer.harness.tsx create mode 100644 web/src/e2e/form-enter.harness.tsx diff --git a/.changeset/focus-after-processing.md b/.changeset/focus-after-processing.md new file mode 100644 index 00000000..e0491602 --- /dev/null +++ b/.changeset/focus-after-processing.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +Focus no longer drops to the page while a form is busy. `Form` gives focus back to the field you were in after an Enter submit (its fields are disabled while it processes), and `CommentThread`'s composer puts focus back in the text box after posting. diff --git a/e2e/browser.spec.ts b/e2e/browser.spec.ts index 2c98c897..54327ccf 100644 --- a/e2e/browser.spec.ts +++ b/e2e/browser.spec.ts @@ -22,6 +22,25 @@ test.describe("focus", () => { await expect(items.nth(2)).toContainText("Malé") await expect(page.getByRole("button", { name: "Drag to reorder Malé" })).toBeFocused() }) + + test("Form keeps focus in the field after an Enter submit", async ({ page }) => { + await open(page, "form-enter") + const name = page.getByLabel("Name") + await name.click() + await page.keyboard.press("Enter") + await expect(page.locator("form")).toHaveAttribute("data-status", "success") + await expect(name).toBeFocused() + }) + + test("the top-level comment composer keeps focus after posting", async ({ page }) => { + await open(page, "composer") + const box = page.getByRole("textbox", { name: "Write a comment…" }) + await box.fill("First!") + await page.getByRole("button", { name: "Comment", exact: true }).click() + await expect(page.getByText("First!")).toBeVisible() + await expect(box).toHaveValue("") + await expect(box).toBeFocused() + }) }) test("LoadMore auto doesn't load again while a load is starting", async ({ page }) => { diff --git a/packages/onu/src/components/display/_composer.tsx b/packages/onu/src/components/display/_composer.tsx index a48477dc..e5a6704f 100644 --- a/packages/onu/src/components/display/_composer.tsx +++ b/packages/onu/src/components/display/_composer.tsx @@ -51,9 +51,19 @@ export function Composer({ if (focusOnMount) textarea.current?.focus() }, [focusOnMount]) const canSubmit = body.trim().length > 0 && !pending && !disabled + // The textarea and button are disabled while posting, which drops focus to . + // Once the post settles, put focus back in the textarea, ready for the next one. + const refocus = React.useRef(false) + React.useEffect(() => { + if (pending || !refocus.current) return + refocus.current = false + const active = document.activeElement + if (!active || active === document.body) textarea.current?.focus() + }, [pending]) const submit = async () => { if (!canSubmit) return + refocus.current = true setPending(true) setFailed(false) try { diff --git a/packages/onu/src/components/form/form.tsx b/packages/onu/src/components/form/form.tsx index f8897cc3..baf51d88 100644 --- a/packages/onu/src/components/form/form.tsx +++ b/packages/onu/src/components/form/form.tsx @@ -123,6 +123,7 @@ export function Form({ children, ref, onChange, + onFocus, noValidate, ...props }: FormProps) { @@ -171,6 +172,21 @@ export function Form({ if (errorEntries(errorsProp).length) pendingFocus.current = true }, [errorsProp]) + // Disabling fields while processing blurs the focused one, so an Enter submit drops focus + // to . Remember the last focused control and give focus back when processing ends. + const lastFocused = React.useRef(null) + const fieldsDisabled = disableWhileProcessing && processing + const wasDisabled = React.useRef(fieldsDisabled) + React.useEffect(() => { + const ended = wasDisabled.current && !fieldsDisabled + wasDisabled.current = fieldsDisabled + const target = lastFocused.current + if (!ended || !target?.isConnected) return + const active = document.activeElement + if (active && active !== document.body) return + target.focus({ preventScroll: true }) + }, [fieldsDisabled]) + React.useEffect(() => { if (!pendingFocus.current) return pendingFocus.current = false @@ -260,6 +276,10 @@ export function Form({ className={cn("gap-6 grid", className)} onSubmit={handleSubmit} onChange={handleChange} + onFocus={(event) => { + lastFocused.current = event.target as HTMLElement + onFocus?.(event) + }} {...props} > {summary ? ( diff --git a/web/src/e2e/composer.harness.tsx b/web/src/e2e/composer.harness.tsx new file mode 100644 index 00000000..20ca4762 --- /dev/null +++ b/web/src/e2e/composer.harness.tsx @@ -0,0 +1,20 @@ +import * as React from "react" +import { CommentThread, type CommentData } from "@javaabu/onu" + +// 6.6: focus after posting from the top-level composer. +export default function ComposerHarness() { + const [comments, setComments] = React.useState([]) + return ( + { + await new Promise((resolve) => setTimeout(resolve, 200)) + setComments((c) => [ + ...c, + { id: String(c.length + 1), author: { id: "me", name: "Aishath" }, body, createdAt: new Date() }, + ]) + }} + /> + ) +} diff --git a/web/src/e2e/form-enter.harness.tsx b/web/src/e2e/form-enter.harness.tsx new file mode 100644 index 00000000..bd705e8b --- /dev/null +++ b/web/src/e2e/form-enter.harness.tsx @@ -0,0 +1,13 @@ +import { Form, FormField, SubmitButton, TextInput } from "@javaabu/onu" + +// 6.6: Enter-submit while fields are disabled during processing. +export default function FormEnterHarness() { + return ( +
new Promise((resolve) => setTimeout(resolve, 400))}> + + + + Save +
+ ) +} From 892d43e40dedf21451aff5c0e08944df0fa5a347 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 07:59:04 +0000 Subject: [PATCH 5/7] Portal the slash menu into its dialog (#66, 6.7) A modal dialog makes the rest of the page inert, so a menu on could not be clicked. Checked in Chromium and WebKit (e2e/browser.spec.ts). Co-Authored-By: Claude Opus 5.5 --- .changeset/slash-menu-in-dialog.md | 5 +++++ e2e/browser.spec.ts | 17 +++++++++++++++++ packages/onu/src/editor/_slash-menu.tsx | 6 +++++- web/src/e2e/slash-menu-modal.harness.tsx | 13 +++++++++++++ 4 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 .changeset/slash-menu-in-dialog.md create mode 100644 web/src/e2e/slash-menu-modal.harness.tsx diff --git a/.changeset/slash-menu-in-dialog.md b/.changeset/slash-menu-in-dialog.md new file mode 100644 index 00000000..d3a26135 --- /dev/null +++ b/.changeset/slash-menu-in-dialog.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +The `BlockEditor` slash menu works inside a modal: it now opens inside the dialog, so it can be clicked and screen readers can reach it. diff --git a/e2e/browser.spec.ts b/e2e/browser.spec.ts index 54327ccf..1e395a16 100644 --- a/e2e/browser.spec.ts +++ b/e2e/browser.spec.ts @@ -41,6 +41,23 @@ test.describe("focus", () => { await expect(box).toHaveValue("") await expect(box).toBeFocused() }) + + test("the slash menu works inside a modal dialog", async ({ page }) => { + await open(page, "slash-menu-modal") + const editor = page.getByRole("dialog").getByRole("textbox", { name: "Page content" }) + await editor.click() + await page.keyboard.type("/head") + const option = page.getByRole("option", { name: /Heading 1/ }) + await expect(option).toBeVisible() + // Inside the dialog, and next to the editor rather than thrown off by the dialog's transform. + await expect(page.getByRole("dialog").locator("[data-slot=slash-menu]")).toBeVisible() + const menu = (await page.locator("[data-slot=slash-menu]").boundingBox())! + const field = (await editor.boundingBox())! + expect(menu.y).toBeGreaterThan(field.y) + expect(menu.y).toBeLessThan(field.y + 120) + await option.click() + await expect(editor.locator("h1")).toHaveCount(1) + }) }) test("LoadMore auto doesn't load again while a load is starting", async ({ page }) => { diff --git a/packages/onu/src/editor/_slash-menu.tsx b/packages/onu/src/editor/_slash-menu.tsx index 01982c48..490941af 100644 --- a/packages/onu/src/editor/_slash-menu.tsx +++ b/packages/onu/src/editor/_slash-menu.tsx @@ -162,6 +162,10 @@ export function SlashMenuPopup({ store, editor }: { store: SlashMenuStore; edito if (!open) return null + // Inside a modal dialog the rest of the page is inert, so a menu portalled to + // could not be clicked and would be hidden from assistive technology: portal into the dialog. + const container = editor.view.dom.closest("[role=dialog], [role=alertdialog]") ?? document.body + return createPortal(
, - document.body, + container, ) } diff --git a/web/src/e2e/slash-menu-modal.harness.tsx b/web/src/e2e/slash-menu-modal.harness.tsx new file mode 100644 index 00000000..ea3eff85 --- /dev/null +++ b/web/src/e2e/slash-menu-modal.harness.tsx @@ -0,0 +1,13 @@ +import * as React from "react" +import { Modal } from "@javaabu/onu" +import { BlockEditor } from "@javaabu/onu/editor" + +// 6.7: the block editor's slash menu inside a modal dialog. +export default function SlashMenuModalHarness() { + const [open, setOpen] = React.useState(true) + return ( + + + + ) +} From 0fe47134ecc792002f3ee3bca114dd6075595061 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 07:59:04 +0000 Subject: [PATCH 6/7] Reset TimeSeriesChart's zoom when the data covers other dates (#66, 8.10) Checked in Chromium and WebKit (e2e/browser.spec.ts). Co-Authored-By: Claude Opus 5.5 --- .changeset/time-series-zoom-reset.md | 5 ++++ e2e/browser.spec.ts | 17 +++++++++++ packages/onu/src/charts/time-series-chart.tsx | 8 ++++++ web/src/e2e/time-series-zoom.harness.tsx | 28 +++++++++++++++++++ 4 files changed, 58 insertions(+) create mode 100644 .changeset/time-series-zoom-reset.md create mode 100644 web/src/e2e/time-series-zoom.harness.tsx diff --git a/.changeset/time-series-zoom-reset.md b/.changeset/time-series-zoom-reset.md new file mode 100644 index 00000000..ac715ef9 --- /dev/null +++ b/.changeset/time-series-zoom-reset.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`TimeSeriesChart` with `brush` resets its zoom when `data` changes to cover other dates, instead of keeping a range (and "Showing …" read-out) from the old data. Inline `data` with the same dates keeps the zoom. diff --git a/e2e/browser.spec.ts b/e2e/browser.spec.ts index 1e395a16..2adebbe0 100644 --- a/e2e/browser.spec.ts +++ b/e2e/browser.spec.ts @@ -80,6 +80,23 @@ test("QrCode downloads PNG and SVG files", async ({ page }) => { } }) +test("TimeSeriesChart drops its zoom range when the data changes", async ({ page }) => { + await open(page, "time-series-zoom") + const status = page.locator("[data-slot=chart-zoom-status]") + const traveller = page.locator(".recharts-brush-traveller").first() + const box = (await traveller.boundingBox())! + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2) + await page.mouse.down() + await page.mouse.move(box.x + 250, box.y + box.height / 2, { steps: 10 }) + await page.mouse.up() + await expect(page.getByRole("button", { name: "Reset zoom" })).toBeVisible() + + await page.getByRole("button", { name: "Switch data" }).click() + // The new data is 1–10 May: nothing from the old January–March range may remain. + await expect(status).not.toContainText(/Jan|Feb|Mar/) + await expect(page.getByRole("button", { name: "Reset zoom" })).toHaveCount(0) +}) + test("InlineEdit: clicking Cancel doesn't save", async ({ page }) => { await open(page, "inline-edit") await page.getByRole("button", { name: /Edit Name/ }).click() diff --git a/packages/onu/src/charts/time-series-chart.tsx b/packages/onu/src/charts/time-series-chart.tsx index 9f1d8a6d..8709e105 100644 --- a/packages/onu/src/charts/time-series-chart.tsx +++ b/packages/onu/src/charts/time-series-chart.tsx @@ -306,6 +306,14 @@ export function TimeSeriesChart({ setRange(null) setBrushKey((k) => k + 1) } + // The range is row indices: when the rows cover other dates, it no longer means anything. + // Compared by extent, not identity, so inline `data` (new each render) keeps the zoom. + const extent = `${rtl}:${displayRows.length}:${String(displayRows[0]?.[TIME_KEY])}:${String(displayRows.at(-1)?.[TIME_KEY])}` + const [rangeExtent, setRangeExtent] = React.useState(extent) + if (rangeExtent !== extent) { + setRangeExtent(extent) + if (range !== null) resetZoom() + } const first = rows[0]?.[TIME_KEY] const last = rows[rows.length - 1]?.[TIME_KEY] diff --git a/web/src/e2e/time-series-zoom.harness.tsx b/web/src/e2e/time-series-zoom.harness.tsx new file mode 100644 index 00000000..368bf199 --- /dev/null +++ b/web/src/e2e/time-series-zoom.harness.tsx @@ -0,0 +1,28 @@ +import * as React from "react" +import { Button } from "@javaabu/onu" +import { TimeSeriesChart } from "@javaabu/onu/charts" + +const days = (n: number, start: string) => + Array.from({ length: n }, (_, i) => { + const d = new Date(`${start}T00:00:00`) + d.setDate(d.getDate() + i) + return { date: d.toISOString().slice(0, 10), value: 100 + ((i * 37) % 50) } + }) + +// 8.10: the zoom range after `data` changes. +export default function TimeSeriesZoomHarness() { + const [short, setShort] = React.useState(false) + return ( +
+ + +
+ ) +} From 2dc8d6fdf91468334b7647a32d921a4ba9d53316 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 08:07:02 +0000 Subject: [PATCH 7/7] Create the e2e harness pages once, outside render Co-Authored-By: Claude Opus 5.5 --- web/src/components/harness.tsx | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/web/src/components/harness.tsx b/web/src/components/harness.tsx index 770618e2..a1da3f8e 100644 --- a/web/src/components/harness.tsx +++ b/web/src/components/harness.tsx @@ -5,16 +5,20 @@ import { PageReady } from "./views" // Scenarios for the real-browser tests in e2e/browser.spec.ts. Unlisted: not in the // navigation, search, or the a11y and visual loops (those walk showcase/ and pages/). -const harnesses = import.meta.glob<{ default: React.ComponentType }>("../e2e/*.harness.tsx") +const harnesses = Object.fromEntries( + Object.entries(import.meta.glob<{ default: React.ComponentType }>("../e2e/*.harness.tsx")).map(([path, load]) => [ + path, + React.lazy(load), + ]), +) /** `#/e2e/` renders `web/src/e2e/.harness.tsx`. */ export function HarnessRoute() { const { name } = useParams() - const load = harnesses[`../e2e/${name}.harness.tsx`] - const Harness = React.useMemo(() => (load ? React.lazy(load) : null), [load]) + const Harness = harnesses[`../e2e/${name}.harness.tsx`] if (!Harness) return

No harness named {name}

return ( -
+