Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/calendar-today-hydration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@javaabu/onu": patch
---

Server-rendered `DateCalendar` and `HijriCalendar` now mark the browser's today once hydrated. Before, a server in another time zone (UTC against the Maldives between 00:00 and 05:00) could leave yesterday marked.
5 changes: 5 additions & 0 deletions .changeset/full-calendar-mobile-hydration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@javaabu/onu": patch
---

A server-rendered `FullCalendar` without `view` or `defaultView` now opens on the agenda on phones once hydrated; before, it stayed on the month view.
4 changes: 4 additions & 0 deletions .changeset/nextjs-fixture-hydration-cases.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
---

The Next.js server-rendering check now covers a stored theme, `ShareButtons` without a `url` and a phone-width `FullCalendar` (test fixture only, no release).
5 changes: 5 additions & 0 deletions .changeset/share-buttons-hydration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@javaabu/onu": patch
---

Server-rendered `ShareButtons` without a `url` now get the current page's URL after hydration; before, their share links kept the server's empty URL.
5 changes: 5 additions & 0 deletions .changeset/theme-provider-hydration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@javaabu/onu": patch
---

`ThemeProvider` no longer causes a hydration mismatch when a theme is stored: it hydrates with `defaultTheme` and switches to the stored theme right after, so a server-rendered `ThemeToggle` shows the stored choice. It also follows a theme chosen in another tab.
5 changes: 5 additions & 0 deletions .changeset/theme-script-options.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@javaabu/onu": patch
---

`themeScript` now takes the provider's options as an object, `themeScript({ defaultTheme, forcedTheme, storageKey })`, applies `forcedTheme`, and falls back to `defaultTheme` for a stored value that isn't a theme, so the first paint matches `ThemeProvider`.
5 changes: 5 additions & 0 deletions .changeset/use-client-only-where-needed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@javaabu/onu": patch
---

The build now marks only modules that need the browser with `"use client"`, so Server Components can call pure helpers such as `cn`, `themeScript`, `createTranslator`, `mergeMessages`, the `/thaana` conversion functions and the `/export` builders. `themeScript` no longer needs a client-component wrapper in Next.js.
1 change: 1 addition & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ A component is done only when it meets REQUIREMENTS §21: light/dark, LTR/RTL, `
- Use `<Icon name="…">` (from `src/icons/icon`) with semantic names, so `OnuProvider icons` overrides apply. Never render a Lucide component directly. When a component always shows the same glyph (a spinner, a close button, a chevron), also pass that Lucide icon as `fallback`, e.g. `<Icon name="loading" fallback={Loader2Icon} />`: overrides still win, and the component keeps its glyph outside `OnuProvider`.
- Never import `src/icons/lucide-map` in a component. `OnuProvider` loads the default set on demand, so neither a single component nor the provider ships ~250 icons. ESLint and `src/icons/icon-imports.test.ts` enforce this, and `pnpm --filter @javaabu/onu size` checks the bundle budgets.
- Built-in strings: a module that uses `t("form.…")` registers the English namespaces it uses at the top level, e.g. `registerEnglish({ form: en_form })` with `import { form as en_form } from "../../locales/en/form"`. Never import the whole locale (`src/locales`, `locales/en/messages`) in a component, so a bundle carries only the English text of the components it uses. `src/i18n/english-registry.test.ts` checks this.
- Start a module with `"use client"` when it uses state, effects or context (its own hooks or Onu's, such as `useTranslation`). The build keeps the directive only on those modules, so pure helpers (`cn`, `themeScript`, `/thaana` conversion, `/export`) stay callable from React Server Components. `src/use-client.test.ts` checks this.
- Every `package.json` export has a `size-limit` budget (`pnpm --filter @javaabu/onu size`, run in CI). When a change grows an entry on purpose, raise its budget in the same PR and say why; keep budgets a little above the measured size.
- Prefer shadcn/ui or an approved library (REQUIREMENTS §4) before building from scratch. Record new dependencies in `DEPENDENCIES.md`.
- Add a changeset: `pnpm changeset`.
Expand Down
2 changes: 2 additions & 0 deletions docs/date-and-time/date-calendar.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ import { DateCalendar } from "@javaabu/onu"

`DEFAULT_WEEKEND_DAYS` (`[5, 6]`, Friday and Saturday) is exported.

Without `today`, "today" is the browser's date. When server-rendered, no day is marked as today until hydration (a server in another time zone can be on a different day); pass `today` to have it in the server's HTML.

## Accessibility

See the [DatePicker keyboard table](./date-picker#accessibility). The caption is a button ("March 2026: choose a month"); page changes are announced through a polite live region; the current month/year/range has `aria-current="date"`.
Expand Down
2 changes: 1 addition & 1 deletion docs/date-and-time/full-calendar.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const events: CalendarEvent[] = [
```

- `color` takes a theme colour (`primary`, `success`, `warning`, `destructive`, `info`, `secondary`, `chart-1`…`chart-8`), so events follow dark mode and `--onu-primary`. Any other FullCalendar event field (`backgroundColor`, `extendedProps`, `url`, …) passes through.
- The toolbar (‹ Today › · title · view switch) wraps on narrow containers; on phones the calendar opens on the agenda. No view scrolls the page sideways at 375px, in LTR or RTL: the agenda's screen-reader header is hidden in place (FullCalendar's `left: -10000px` would otherwise add 10,000px of overflow in RTL) and month events clip inside their day cell.
- The toolbar (‹ Today › · title · view switch) wraps on narrow containers; on phones the calendar opens on the agenda (also when server-rendered: it switches once hydrated), until a view is picked. No view scrolls the page sideways at 375px, in LTR or RTL: the agenda's screen-reader header is hidden in place (FullCalendar's `left: -10000px` would otherwise add 10,000px of overflow in RTL) and month events clip inside their day cell.
- Weekend days (Friday and Saturday by default) are shaded; today is marked.
- `apiRef` gives FullCalendar's `CalendarApi`; `options` passes any other FullCalendar option (Onu's props win); `hideToolbar` lets you build your own.

Expand Down
2 changes: 2 additions & 0 deletions docs/date-and-time/hijri-date-picker.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ Plus the shared picker field props.

`selected`, `onSelect`, `min`, `max`, `weekStartsOn`, `weekendDays`, `showGregorian` (default `true`), `today`, `initialFocus`, `className`, `ref`.

As with `DateCalendar`, without `today` the browser's date is marked once hydrated, not the server's.

## Accessibility

The days view is an in-house APG grid (react-day-picker has no Hijri support). Day buttons are named with both calendars ("Today, 23 Ramadan 1447 AH, Thursday, March 12th, 2026"); today has `aria-current="date"`; days outside `min`/`max` are `aria-disabled`.
Expand Down
2 changes: 2 additions & 0 deletions docs/display-and-feedback/share-buttons.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import { ShareButtons } from "@javaabu/onu"

`shareUrl(network, url, title?, text?)` builds the share links.

When server-rendered without `url`, the links start without a URL (the server doesn't know the page's address) and get the current page's URL straight after hydration. Pass `url` to have it in the server's HTML too.

:::info Brand icons
Onu's icon sets (Lucide, FontAwesome Free solid) don't include brand logos, so networks use generic icons with their names as text. Pass `icons` (e.g. from Simple Icons via the Iconify adapter) for logos.
:::
Expand Down
10 changes: 9 additions & 1 deletion docs/guides/dark-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,20 @@ function MyToggle() {
| `forcedTheme` | | Fix the theme, e.g. `"light"` for print pages |
| `storageKey` | `"onu-theme"` | `localStorage` key |

The provider sets `class="dark"`, `data-theme` and `color-scheme` on `<html>`, so dialogs and menus in portals follow it.
The provider sets `class="dark"`, `data-theme` and `color-scheme` on `<html>`, so dialogs and menus in portals follow it. A choice made in another tab applies here too.

When server-rendered, the provider hydrates with `defaultTheme` (the server can't read `localStorage`) and switches to the stored theme straight after hydration, so the markup matches and controls such as `ThemeToggle` show the stored choice.

In server-rendered apps, add `themeScript()` to `<head>` to apply the stored theme before the page paints:

```tsx
<script dangerouslySetInnerHTML={{ __html: themeScript() }} />
```

If you pass `defaultTheme`, `forcedTheme` or `storageKey` to the provider, pass the same options to the script, so the first paint matches what the provider applies (a stored value that isn't a theme falls back to `defaultTheme` in both):

```tsx
<script dangerouslySetInnerHTML={{ __html: themeScript({ defaultTheme: 'dark', storageKey: 'app-theme' }) }} />
```

In your own styles use Tailwind's `dark:` variant, which Onu configures for both the class and the attribute.
17 changes: 4 additions & 13 deletions docs/guides/inertia-and-nextjs.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Render `<html lang dir>` from the Blade root view so right-to-left pages are cor

# Next.js App Router

Every Onu component file is marked `"use client"`, so Server Components can render Onu components directly, as long as every prop is serialisable (strings, numbers, elements). Anything that takes a function (`onSubmit`, `onChange`, `linkComponent`) belongs in a `"use client"` file.
Every Onu module that needs the browser (state, effects, context) is marked `"use client"`, so Server Components can render Onu components directly, as long as every prop is serialisable (strings, numbers, elements). Anything that takes a function (`onSubmit`, `onChange`, `linkComponent`) belongs in a `"use client"` file. Pure helpers are not client modules, so Server Components can call them: `cn`, `themeScript`, `createTranslator`, `mergeMessages`, the `/thaana` conversion functions (`transliterate`, `containsThaana`) and the `/export` builders (`toCsv`).

Put `ThemeProvider`, `OnuProvider` and `TooltipProvider` in a client component, and render the layout's `<html lang dir>` on the server so right-to-left pages are correct in the first HTML:

Expand All @@ -60,27 +60,18 @@ export function Providers({ locale, children }) {
}
```

Because the package is a client module, `themeScript()` can't be called from a Server Component. Render it from a small client component instead, which puts the script in the server-rendered HTML:
Call `themeScript()` in the layout's `<head>` to apply the stored theme before the first paint:

```tsx
// components/theme-script.tsx
'use client';

// app/layout.tsx (a Server Component)
import { themeScript } from '@javaabu/onu';

export function ThemeScript() {
return <script dangerouslySetInnerHTML={{ __html: themeScript() }} suppressHydrationWarning />;
}
```

```tsx
// app/layout.tsx (a Server Component)
export default async function RootLayout({ children }) {
const locale = (await cookies()).get('locale')?.value === 'dv' ? 'dv' : 'en';
return (
<html lang={locale} dir={locale === 'dv' ? 'rtl' : 'ltr'} suppressHydrationWarning>
<head>
<ThemeScript />
<script dangerouslySetInnerHTML={{ __html: themeScript() }} />
</head>
<body>
<Providers locale={locale}>{children}</Providers>
Expand Down
15 changes: 15 additions & 0 deletions e2e/nextjs/app/hydration/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { ShareButtons, ThemeToggle } from "@javaabu/onu"
import { FullCalendar } from "@javaabu/onu/calendar"

// Components whose first client render depends on the browser (#66, Part 7): the stored theme, the page's URL and the
// screen width. `scripts/ssr-check.mjs` opens this page at phone width with a stored dark theme, and checks that each
// one follows the browser once hydrated, without a hydration error.
export default function HydrationPage() {
return (
<main>
<ThemeToggle variant="segmented" />
<ShareButtons native="never" networks={["facebook"]} />
<FullCalendar />
</main>
)
}
7 changes: 6 additions & 1 deletion e2e/nextjs/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { themeScript } from "@javaabu/onu"
import { cookies } from "next/headers"

import { Providers } from "@/components/providers"
Expand All @@ -6,11 +7,15 @@ import "./globals.css"

export const metadata = { title: "Onu server-rendering fixture" }

// A Server Component calling Onu's pure helpers (`themeScript` here, `cn` on the page): they have no "use client".
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const locale = (await cookies()).get("locale")?.value === "dv" ? "dv" : "en"

return (
<html lang={locale} dir={locale === "dv" ? "rtl" : "ltr"}>
<html lang={locale} dir={locale === "dv" ? "rtl" : "ltr"} suppressHydrationWarning>
<head>
<script dangerouslySetInnerHTML={{ __html: themeScript() }} />
</head>
<body>
<Providers locale={locale}>{children}</Providers>
</body>
Expand Down
12 changes: 9 additions & 3 deletions e2e/nextjs/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { Callout, Card, Countdown, PageTitle, PublishBox, RelativeDate, StatusBadge, Timeline } from "@javaabu/onu"
import { Callout, Card, cn, Countdown, PageTitle, PublishBox, RelativeDate, StatusBadge, Timeline } from "@javaabu/onu"
import { toCsv } from "@javaabu/onu/export"
import { transliterate } from "@javaabu/onu/thaana"

import { ContactForm } from "@/components/contact-form"

// A Server Component rendering Onu's client components with serialisable props. The clock-based ones catch hydration
// mismatches; ContactForm is the "use client" boundary for props that are functions.
// mismatches; ContactForm is the "use client" boundary for props that are functions. `cn`, `transliterate` and `toCsv`
// run here, on the server: pure helpers have no "use client".
export default function HomePage() {
return (
<main>
<main className={cn("p-4", "p-6", "server-cn")}>
<PageTitle title="Applications" />
<Callout tone="info" title="Welcome" />
<Card title="Recent">
Expand All @@ -17,6 +20,9 @@ export default function HomePage() {
<PublishBox status="draft" publishAt="2030-03-01T00:00:00Z" />
<Timeline groupByDay items={[{ id: "1", title: "Opened", time: "2026-01-01T00:00:00Z" }]} />
<ContactForm />
<pre data-testid="server-helpers">
{`${transliterate("divehi")}|${toCsv([{ name: "Ali" }], [{ header: "Name", accessor: "name" }]).trim()}`}
</pre>
</main>
)
}
60 changes: 58 additions & 2 deletions e2e/nextjs/scripts/ssr-check.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Server-rendering check (R16.1), in English (LTR) and Dhivehi (RTL), against the production build:
// the HTML has Onu's markup before any JavaScript runs, and the page hydrates in a browser without errors.
// `/hydration` checks that what only the browser knows (stored theme, page URL, screen width) applies once hydrated.
//
// pnpm build && pnpm --filter onu-nextjs-fixture build && pnpm --filter onu-nextjs-fixture test:ssr
//
Expand All @@ -13,6 +14,8 @@ import { fileURLToPath } from "node:url"

import { chromium } from "@playwright/test"

/* global document, location -- the page checks below run in the browser */

const root = join(dirname(fileURLToPath(import.meta.url)), "..")
const port = await freePort()
const base = `http://127.0.0.1:${port}`
Expand All @@ -25,6 +28,11 @@ const markup = [
'data-slot="status-badge"',
'data-slot="form"',
'data-slot="form-field"',
// Pure helpers called from Server Components: `cn` merged the padding, `themeScript` is in <head>,
// and `transliterate` and `toCsv` ran.
'<main class="p-6 server-cn"',
'localStorage.getItem("onu-theme")',
"ދިވެހި|Name",
]

const checks = [
Expand Down Expand Up @@ -53,12 +61,18 @@ try {
await waitForServer()
browser = await chromium.launch(process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {})
for (const check of checks) {
const problems = [...(await checkHtml(check)), ...(await checkHydration(check))]
const problems = [
...(await checkHtml(check)),
...(await checkHydration(check)),
...(await checkBrowserOnlyState(check)),
]
if (problems.length) {
failed++
console.error(`✗ ${check.name}:\n - ${problems.join("\n - ")}`)
} else {
console.log(`✓ ${check.name}: server HTML has ${check.expect.length} expected strings, and hydration is clean`)
console.log(
`✓ ${check.name}: server HTML has ${check.expect.length} expected strings, hydration is clean, and the stored theme, page URL and phone width apply after hydration`,
)
}
}
} catch (error) {
Expand Down Expand Up @@ -103,6 +117,48 @@ async function checkHydration({ locale }) {
return problems
}

/**
* `/hydration` at phone width, with a dark theme stored before the page loads. The server can't
* know any of these, so each component must catch up once hydrated (hydration doesn't patch
* attributes, so reading the browser during the hydrating render leaves stale markup).
*/
async function checkBrowserOnlyState({ locale }) {
const context = await browser.newContext({ baseURL: base, viewport: { width: 375, height: 812 } })
await context.addCookies([{ name: "locale", value: locale, url: base }])
await context.addInitScript(() => localStorage.setItem("onu-theme", "dark"))
const page = await context.newPage()
const problems = []
page.on("pageerror", (error) => problems.push(`Page error: ${error.message}`))
page.on("console", (message) => {
if (message.type() === "error") problems.push(`Console error: ${message.text()}`)
})
await page.goto("/hydration", { waitUntil: "networkidle" })

const expectations = [
["The stored dark theme isn't applied to <html>", () => document.documentElement.classList.contains("dark")],
[
"ThemeToggle doesn't select the stored theme (Dark)",
() => document.querySelectorAll('[data-slot="theme-toggle"] [role="radio"]')[1]?.ariaChecked === "true",
],
[
"ShareButtons' link doesn't carry the page's URL",
() =>
document.querySelector('[data-network="facebook"]')?.getAttribute("href") ===
`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(location.href)}`,
],
[
"FullCalendar didn't switch to the agenda at phone width",
() => document.querySelector('[data-slot="full-calendar"]')?.getAttribute("data-view") === "agenda",
],
]
for (const [problem, holds] of expectations) {
await page.waitForFunction(holds, null, { timeout: 5_000 }).catch(() => problems.push(problem))
}

await context.close()
return problems
}

async function waitForServer(timeoutMs = 30_000) {
const start = Date.now()
while (Date.now() - start < timeoutMs) {
Expand Down
22 changes: 22 additions & 0 deletions packages/onu/src/calendar/full-calendar.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ import userEvent from "@testing-library/user-event"
import { enUS } from "date-fns/locale/en-US"
import { describe, expect, it, vi } from "vitest"

import { hydrateAfterServer } from "../../test/hydrate"
import { controllableMatchMedia } from "../../test/match-media"
import { directions, expectNoA11yViolations, renderWithOnu } from "../../test/utils"
import { dv } from "../locales"
import { OnuProvider } from "../providers/onu-provider"
import type { CalendarApi } from "./index"
import { FullCalendar, rangeTitle, toEventInput, type CalendarEvent } from "./full-calendar"
import { dvFullCalendarLocale, fullCalendarLocale } from "./full-calendar-locale"
Expand Down Expand Up @@ -198,6 +201,25 @@ describe("FullCalendar", () => {
window.matchMedia = original
}
})

it("switches to the agenda on phones after server rendering", async () => {
let media: ReturnType<typeof controllableMatchMedia> | undefined
try {
const { container, errors } = await hydrateAfterServer(
<OnuProvider>
<FullCalendar events={EVENTS} initialDate={TODAY} today={TODAY} />
</OnuProvider>,
() => {
media = controllableMatchMedia((query) => query.includes("max-width"))
},
)
expect(errors).toEqual([])
expect(container.querySelector("[data-slot=full-calendar]")).toHaveAttribute("data-view", "agenda")
expect(within(container).getByRole("radio", { name: "Agenda" })).toHaveAttribute("aria-checked", "true")
} finally {
media?.restore()
}
})
})

describe("FullCalendar helpers", () => {
Expand Down
Loading
Loading