From 5e069c22d83da5548252ae6c8934ec4f0c291873 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:39:54 +0000 Subject: [PATCH 01/12] Write Excel dates in local time (#66, 8.1) Co-Authored-By: Claude Opus 5.5 --- .changeset/excel-local-dates.md | 5 +++++ docs/listing-pages/export-rows.md | 2 +- packages/onu/src/export/excel.ts | 23 +++++++++++++++++++++-- packages/onu/src/export/export.test.tsx | 14 +++++++++++++- 4 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 .changeset/excel-local-dates.md diff --git a/.changeset/excel-local-dates.md b/.changeset/excel-local-dates.md new file mode 100644 index 000000000..0508eb5f2 --- /dev/null +++ b/.changeset/excel-local-dates.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +Excel exports now write `date` and `datetime` cells in local time, like CSV and PDF. Before, a user east of UTC saw dates a day early and times shifted by their UTC offset. diff --git a/docs/listing-pages/export-rows.md b/docs/listing-pages/export-rows.md index daf3d144b..3807b8c6d 100644 --- a/docs/listing-pages/export-rows.md +++ b/docs/listing-pages/export-rows.md @@ -95,6 +95,6 @@ The export runs from the [`ExportMenu`](export-menu), which announces "Exporting ## RTL and Dhivehi - With `dir: "rtl"` (automatic for Dhivehi through `useExportRows`), Excel sheets are right to left and the PDF document is `dir="rtl" lang="dv"`. -- Dates use the locale's date-fns locale in the PDF ("12 މާޗު 2026"); CSV and Excel use ISO dates and real date cells. +- Dates use the locale's date-fns locale in the PDF ("12 މާޗު 2026"); CSV and Excel use ISO dates and real date cells. All three show the same local date and time: a `date` of `"2026-03-12"` is 12 March in every format, whatever the user's time zone. - Currency follows `common.currency` ("MVR 1,250.00" / "ރ. 1,250.00"); booleans use `common.yes` / `common.no`. - Text cells are wrapped in `` in the PDF, so Latin and Thaana values each read in their own direction while the column keeps the page alignment. diff --git a/packages/onu/src/export/excel.ts b/packages/onu/src/export/excel.ts index 7cae11c97..e4fb2df8d 100644 --- a/packages/onu/src/export/excel.ts +++ b/packages/onu/src/export/excel.ts @@ -57,6 +57,25 @@ function currencyFormat(ctx: ExportContext, decimals: number) { return `${quote(template.slice(0, at))}${number}${quote(template.slice(at + "{amount}".length))}` } +/** + * `write-excel-file` turns a Date into Excel's serial number from its UTC time, but Excel has no + * time zones: a cell shows the wall-clock time it holds. Moving the local date and time into UTC + * keeps the cell on the same day and hour that CSV and PDF show. + */ +function toExcelDate(date: Date) { + return new Date( + Date.UTC( + date.getFullYear(), + date.getMonth(), + date.getDate(), + date.getHours(), + date.getMinutes(), + date.getSeconds(), + date.getMilliseconds(), + ), + ) +} + function toExcelCell(cell: ExportCell, formatted: string | undefined, ctx: ExportContext): ExcelCell | null { switch (cell.type) { case "number": @@ -70,9 +89,9 @@ function toExcelCell(cell: ExportCell, formatted: string | undefined, ctx: Expor case "currency": return { value: cell.value, type: Number, format: currencyFormat(ctx, cell.decimals ?? 2) } case "date": - return { value: cell.value, type: Date, format: "yyyy-mm-dd" } + return { value: toExcelDate(cell.value), type: Date, format: "yyyy-mm-dd" } case "datetime": - return { value: cell.value, type: Date, format: "yyyy-mm-dd hh:mm" } + return { value: toExcelDate(cell.value), type: Date, format: "yyyy-mm-dd hh:mm" } case "empty": return formatted ? { value: formatted, type: String } : null default: diff --git a/packages/onu/src/export/export.test.tsx b/packages/onu/src/export/export.test.tsx index 87aa55926..a28dec281 100644 --- a/packages/onu/src/export/export.test.tsx +++ b/packages/onu/src/export/export.test.tsx @@ -214,7 +214,7 @@ describe("Excel", () => { expect(amount).toEqual({ value: 1250.5, type: Number, format: '"MVR "#,##0.00' }) expect(paid).toEqual({ value: "Yes", type: String }) expect(date).toMatchObject({ type: Date, format: "yyyy-mm-dd" }) - expect((date as { value: Date }).value.getDate()).toBe(12) + expect((date as { value: Date }).value.getUTCDate()).toBe(12) expect(note).toEqual({ value: 'Said "hi", then left', type: String }) // Text stays text: no formula is created from a "=" value. expect(sheet.data[2]![0]).toEqual({ value: '=HYPERLINK("http://evil")', type: String }) @@ -251,6 +251,18 @@ describe("Excel", () => { ]) }) + it("writes dates with the local calendar date and clock time, like CSV and PDF", () => { + // write-excel-file turns a Date into a serial number from its UTC time, so the cell holds + // the local wall-clock time as UTC. Run with TZ=Indian/Maldives (UTC+5) to see the shift. + const sheet = buildExcelSheet(rows, [ + { header: "Date", accessor: "date", type: "date" }, + { header: "At", accessor: "date", type: "datetime" }, + ]) + const value = (cell: unknown) => (cell as { value: Date }).value.toISOString() + expect(value(sheet.data[1]![0])).toBe("2026-03-12T00:00:00.000Z") + expect(value(sheet.data[2]![1])).toBe("2026-10-07T09:30:00.000Z") + }) + it("cleans sheet names", () => { expect(excelSheetName("a/b [c]: d?")).toBe("a b c d") expect(excelSheetName("x".repeat(40))).toHaveLength(31) From dd0b29cac15df1e02f62b0cdec9e3016f0f52ef6 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:40:35 +0000 Subject: [PATCH 02/12] Leave invalid timestamp dates empty in exports (#66, 8.2) Co-Authored-By: Claude Opus 5.5 --- .changeset/export-nan-dates.md | 5 +++++ docs/listing-pages/export-rows.md | 2 +- packages/onu/src/export/columns.ts | 8 +++++++- packages/onu/src/export/export.test.tsx | 10 ++++++++++ 4 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 .changeset/export-nan-dates.md diff --git a/.changeset/export-nan-dates.md b/.changeset/export-nan-dates.md new file mode 100644 index 000000000..b4579d93a --- /dev/null +++ b/.changeset/export-nan-dates.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +A `NaN` or out-of-range timestamp in a `date` or `datetime` export column now leaves the cell empty. It used to stop the PDF export with an error and write `NaN-NaN-NaN` to CSV. diff --git a/docs/listing-pages/export-rows.md b/docs/listing-pages/export-rows.md index 3807b8c6d..cc1127fe3 100644 --- a/docs/listing-pages/export-rows.md +++ b/docs/listing-pages/export-rows.md @@ -95,6 +95,6 @@ The export runs from the [`ExportMenu`](export-menu), which announces "Exporting ## RTL and Dhivehi - With `dir: "rtl"` (automatic for Dhivehi through `useExportRows`), Excel sheets are right to left and the PDF document is `dir="rtl" lang="dv"`. -- Dates use the locale's date-fns locale in the PDF ("12 މާޗު 2026"); CSV and Excel use ISO dates and real date cells. All three show the same local date and time: a `date` of `"2026-03-12"` is 12 March in every format, whatever the user's time zone. +- Dates use the locale's date-fns locale in the PDF ("12 މާޗު 2026"); CSV and Excel use ISO dates and real date cells. All three show the same local date and time: a `date` of `"2026-03-12"` is 12 March in every format, whatever the user's time zone. An invalid date (an Invalid `Date`, or a timestamp such as `NaN`) is left empty. - Currency follows `common.currency` ("MVR 1,250.00" / "ރ. 1,250.00"); booleans use `common.yes` / `common.no`. - Text cells are wrapped in `` in the PDF, so Latin and Thaana values each read in their own direction while the column keeps the page alignment. diff --git a/packages/onu/src/export/columns.ts b/packages/onu/src/export/columns.ts index ac8c50bc4..5e27028c8 100644 --- a/packages/onu/src/export/columns.ts +++ b/packages/onu/src/export/columns.ts @@ -72,7 +72,11 @@ export function getExportValue(row: T, column: ExportColumn, index: number function toDate(value: unknown): Date | null { if (value instanceof Date) return isValid(value) ? value : null - if (typeof value === "number") return new Date(value) + if (typeof value === "number") { + // NaN, Infinity and timestamps past the Date range make an Invalid Date. + const date = new Date(value) + return isValid(date) ? date : null + } if (typeof value === "string" && value) { const parsed = parseISO(value) return isValid(parsed) ? parsed : null @@ -121,6 +125,8 @@ export function toExportCell(value: unknown, type?: ExportColumnType, decimals?: case "datetime": { const date = toDate(value) if (date) return { type: kind, value: date } + // A timestamp that is not a real date is as empty as an Invalid Date. + if (typeof value === "number") return { type: "empty" } break } case "boolean": diff --git a/packages/onu/src/export/export.test.tsx b/packages/onu/src/export/export.test.tsx index a28dec281..7e9b8f81a 100644 --- a/packages/onu/src/export/export.test.tsx +++ b/packages/onu/src/export/export.test.tsx @@ -127,6 +127,16 @@ describe("columns", () => { expect(toExportCell(3)).toMatchObject({ type: "number" }) }) + it("leaves a timestamp that is not a real date empty instead of breaking the export", () => { + expect(toExportCell(Number.NaN, "date")).toEqual({ type: "empty" }) + expect(toExportCell(Number.POSITIVE_INFINITY, "datetime")).toEqual({ type: "empty" }) + expect(toExportCell(1e20, "date")).toEqual({ type: "empty" }) + const bad = [{ at: Number.NaN }] + const cols: ExportColumn<{ at: number }>[] = [{ header: "At", accessor: "at", type: "date" }] + expect(toCsv(bad, cols, { bom: false })).toBe("At\r\n\r\n") + expect(() => buildPrintDocument(bad, cols)).not.toThrow() + }) + it("formats display text in the locale", () => { const en = resolveExportContext() const dv = resolveExportContext({ locale: "dv" }) From 9b1be319a48f8b98796bc9c3fd109a984d19cbb0 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:42:26 +0000 Subject: [PATCH 03/12] Group TimeSeriesChart rows by interval instead of dropping them (#66, 8.3) Co-Authored-By: Claude Opus 5.5 --- .changeset/time-series-interval-buckets.md | 5 + docs/charts/time-series-chart.md | 7 +- .../onu/src/charts/time-series-chart.test.tsx | 79 +++++++++++++++ packages/onu/src/charts/time-series-chart.tsx | 95 +++++++++++++++---- 4 files changed, 168 insertions(+), 18 deletions(-) create mode 100644 .changeset/time-series-interval-buckets.md diff --git a/.changeset/time-series-interval-buckets.md b/.changeset/time-series-interval-buckets.md new file mode 100644 index 000000000..a814125c1 --- /dev/null +++ b/.changeset/time-series-interval-buckets.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`TimeSeriesChart` with `interval` no longer drops rows: rows in the same hour, day, week or month are added up (or averaged with the new `aggregate="mean"`), weekly data no longer needs to fall a whole number of weeks after the first date, and a range too long to fill keeps its newest rows. diff --git a/docs/charts/time-series-chart.md b/docs/charts/time-series-chart.md index 441a845a0..1a8822cef 100644 --- a/docs/charts/time-series-chart.md +++ b/docs/charts/time-series-chart.md @@ -31,6 +31,8 @@ Rows may come in any order; they are sorted oldest first. Dates can be `Date` ob `null` values break the line. With `interval` (`"hour" | "day" | "week" | "month"`), missing steps are inserted too (3 September above), so a missing day is a visible gap rather than a straight line across it. `connectNulls` bridges gaps instead. +`interval` also groups the data: each point sits at the start of its hour, day, week (counted from the first date) or month, and rows that fall in the same step are added up, so no row is dropped. Set `aggregate="mean"` to average them instead (for rates or temperatures). A range longer than 10,000 steps is drawn without the gap rows rather than cut short. + ## Stacked areas and bars `stacked` adds the series up, so the top edge is the total: use `variant="area"` for stacked areas or `variant="bar"` for stacked bars (a stacked `"line"` chart is drawn as stacked areas). Bars are centred on their date, and the axis is padded by half a step so the first and last bars are whole. The data table and summary still list each series on its own, and the time axis is mirrored in RTL as usual. @@ -93,7 +95,8 @@ Also takes the common chart props (`title` (required), `description`, `hideTitle | ------------------- | -------------------------------------- | ----------- | --------------------------------------- | | `data` | `Record[]` | required | One object per point in time | | `dateKey` | `string` | `"date"` | Key of the date | -| `interval` | `"hour" \| "day" \| "week" \| "month"` | | Fill missing steps with gaps | +| `interval` | `"hour" \| "day" \| "week" \| "month"` | | Group by step and fill missing steps with gaps | +| `aggregate` | `"sum" \| "mean"` | `"sum"` | With `interval`, how rows in one step combine | | `dateFormat` | `string` (date-fns) | by interval | Tick format (`d MMM`, `MMM yyyy`, time) | | `tooltipDateFormat` | `string` (date-fns) | by interval | Tooltip and table format | | `variant` | `"line" \| "area" \| "bar"` | `"line"` | How series are drawn | @@ -104,7 +107,7 @@ Also takes the common chart props (`title` (required), `description`, `hideTitle | `gradient` | `boolean` | `true` | Gradient area and bar fills | | `comparison` | `ChartComparison` | | This period against the previous one; see [Comparison](#comparison) | -Hourly data uses the locale's `hourCycle`. `normalizeTimeSeries(data, dateKey, interval)` and `toTimestamp(value)` are exported. +Hourly data uses the locale's `hourCycle`. `normalizeTimeSeries(data, dateKey, interval, aggregate)` and `toTimestamp(value)` are exported. ## RTL diff --git a/packages/onu/src/charts/time-series-chart.test.tsx b/packages/onu/src/charts/time-series-chart.test.tsx index a4ff469ad..49153bbbf 100644 --- a/packages/onu/src/charts/time-series-chart.test.tsx +++ b/packages/onu/src/charts/time-series-chart.test.tsx @@ -76,6 +76,73 @@ describe("normalizeTimeSeries", () => { expect(months).toHaveLength(6) }) + it("adds up rows that fall in the same step instead of dropping them", () => { + const days = normalizeTimeSeries( + [ + { t: new Date(2026, 0, 1, 9), v: 1, w: null }, + { t: new Date(2026, 0, 1, 15), v: 2, w: null }, + { t: new Date(2026, 0, 2, 9), v: 4, w: 3 }, + ], + "t", + "day", + ) + expect(days.map((r) => [r[TIME_KEY], r.v, r.w])).toEqual([ + [new Date(2026, 0, 1).getTime(), 3, null], + [new Date(2026, 0, 2).getTime(), 4, 3], + ]) + const months = normalizeTimeSeries( + [ + { t: "2026-01-05", v: 1 }, + { t: "2026-01-20", v: 2 }, + { t: "2026-03-02", v: 5 }, + ], + "t", + "month", + ) + expect(months.map((r) => r.v)).toEqual([3, undefined, 5]) + }) + + it("can average the rows in a step", () => { + const days = normalizeTimeSeries( + [ + { t: new Date(2026, 0, 1, 9), v: 1 }, + { t: new Date(2026, 0, 1, 15), v: 2 }, + ], + "t", + "day", + "mean", + ) + expect(days.map((r) => r.v)).toEqual([1.5]) + }) + + it("keeps weekly rows that are not a whole number of weeks after the first", () => { + const weeks = normalizeTimeSeries( + [ + { t: new Date(2026, 0, 1), v: 1 }, + { t: new Date(2026, 0, 4), v: 2 }, + { t: new Date(2026, 0, 10), v: 4 }, + ], + "t", + "week", + ) + expect(weeks.map((r) => [r[TIME_KEY], r.v])).toEqual([ + [new Date(2026, 0, 1).getTime(), 3], + [new Date(2026, 0, 8).getTime(), 4], + ]) + }) + + it("keeps the newest rows when the range has too many steps to fill", () => { + const hours = normalizeTimeSeries( + [ + { t: new Date(2020, 0, 1), v: 1 }, + { t: new Date(2026, 0, 1), v: 2 }, + ], + "t", + "hour", + ) + expect(hours.map((r) => r.v)).toEqual([1, 2]) + }) + it("leaves single rows alone", () => { expect(normalizeTimeSeries([{ date: "2026-01-01" }], "date", "day")).toHaveLength(1) }) @@ -147,6 +214,18 @@ describe("TimeSeriesChart", () => { expect(screen.getAllByRole("rowheader")[0]).toHaveTextContent("1 Jan 2026, 9:00 AM") }) + it("combines rows in the same step with `aggregate`", () => { + const tax = [ + { date: new Date(2026, 0, 5), tax: 10 }, + { date: new Date(2026, 0, 20), tax: 30 }, + ] + const props = { title: "Tax", config: { tax: { label: "Tax" } }, interval: "month", defaultView: "table" } as const + const { rerender } = renderWithOnu() + expect(screen.getAllByRole("row")[1]).toHaveTextContent("January 2026" + "40") + rerender() + expect(screen.getAllByRole("row")[1]).toHaveTextContent("January 2026" + "20") + }) + it.each(directions)("places the newest date on the correct side in %s", (dir) => { const { container } = renderWithOnu( , diff --git a/packages/onu/src/charts/time-series-chart.tsx b/packages/onu/src/charts/time-series-chart.tsx index 71cd77375..9f1d8a6dc 100644 --- a/packages/onu/src/charts/time-series-chart.tsx +++ b/packages/onu/src/charts/time-series-chart.tsx @@ -6,6 +6,7 @@ import { addHours, addMonths, addWeeks, + differenceInCalendarDays, format as formatDate, startOfDay, startOfHour, @@ -74,8 +75,14 @@ export interface TimeSeriesChartProps extends ChartBaseProps { config?: ChartConfig series?: string[] valueFormat?: ValueFormat - /** Insert empty points for missing hours/days/weeks/months so gaps show as breaks in the line. */ + /** + * Group the data by hour, day, week (counted from the first date) or month: each point sits at + * the start of its step, rows in the same step are combined (see `aggregate`), and empty points + * are inserted for missing steps so gaps show as breaks in the line. + */ interval?: TimeInterval + /** With `interval`, how values in the same step are combined: added up or averaged. Default `"sum"`. */ + aggregate?: TimeAggregate /** date-fns pattern for axis ticks. Defaults by `interval` (`d MMM`). */ dateFormat?: string /** date-fns pattern for tooltips and the data table. Defaults by `interval` (`d MMM yyyy`). */ @@ -126,32 +133,84 @@ const STEP: Record Date> = { month: addMonths, } -const START: Record Date> = { - hour: startOfHour, - day: startOfDay, - week: startOfDay, - month: startOfMonth, +/** The start of the step `time` falls in. Weeks count from the first row's day. */ +function stepStart(interval: TimeInterval, time: number, origin: Date): Date { + const date = new Date(time) + switch (interval) { + case "hour": + return startOfHour(date) + case "day": + return startOfDay(date) + case "week": + return addWeeks(origin, Math.floor(differenceInCalendarDays(date, origin) / 7)) + case "month": + return startOfMonth(date) + } +} + +/** How rows that fall in the same step are combined. */ +export type TimeAggregate = "sum" | "mean" + +/** Combines the rows of one step: numbers are added up (or averaged), anything else comes from the first row. */ +function combineStep(rows: ChartDatum[], dateKey: string, aggregate: TimeAggregate): ChartDatum { + if (rows.length === 1) return { ...rows[0] } + const combined: ChartDatum = { [dateKey]: rows[0]![dateKey] } + const totals = new Map() + for (const row of rows) { + for (const [key, value] of Object.entries(row)) { + if (key === dateKey || key === TIME_KEY) continue + if (typeof value === "number" && Number.isFinite(value)) { + const total = totals.get(key) ?? { sum: 0, count: 0 } + totals.set(key, { sum: total.sum + value, count: total.count + 1 }) + } else if (!(key in combined)) { + combined[key] = value + } + } + } + for (const [key, { sum, count }] of totals) combined[key] = aggregate === "mean" ? sum / count : sum + return combined } +/** Steps filled in at most; a longer range is shown without gap rows rather than cut short. */ +const MAX_STEPS = 10000 + export const TIME_KEY = "__time" /** - * Normalises time-series rows: adds a numeric `__time` key, drops rows without a valid date, - * sorts oldest first and, with `interval`, inserts empty rows for missing steps (gaps). + * Normalises time-series rows: adds a numeric `__time` key, drops rows without a valid date and + * sorts oldest first. With `interval`, each row is placed at the start of its hour/day/week/month, + * rows in the same step are combined (`aggregate`: added up by default, or averaged), and empty + * rows are inserted for missing steps (gaps). */ -export function normalizeTimeSeries(data: ChartDatum[], dateKey: string, interval?: TimeInterval): ChartDatum[] { +export function normalizeTimeSeries( + data: ChartDatum[], + dateKey: string, + interval?: TimeInterval, + aggregate: TimeAggregate = "sum", +): ChartDatum[] { const rows = data .map((d) => ({ ...d, [TIME_KEY]: toTimestamp(d[dateKey]) })) .filter((d): d is ChartDatum & { [TIME_KEY]: number } => d[TIME_KEY] !== null) .sort((a, b) => a[TIME_KEY] - b[TIME_KEY]) - if (!interval || rows.length < 2) return rows + if (!interval || rows.length === 0) return rows - const start = START[interval] - const byStep = new Map(rows.map((r) => [start(new Date(r[TIME_KEY])).getTime(), r])) + const origin = startOfDay(new Date(rows[0]![TIME_KEY])) + const steps = new Map() + for (const row of rows) { + const time = stepStart(interval, row[TIME_KEY], origin).getTime() + steps.set(time, [...(steps.get(time) ?? []), row]) + } + const byStep = new Map( + [...steps].map(([time, group]) => [time, { ...combineStep(group, dateKey, aggregate), [TIME_KEY]: time }]), + ) + + const times = [...byStep.keys()] + const last = times[times.length - 1]! const filled: ChartDatum[] = [] - const last = start(new Date(rows[rows.length - 1]![TIME_KEY])).getTime() - // Guard against runaway loops on huge ranges. - for (let i = 0, cursor = start(new Date(rows[0]![TIME_KEY])); cursor.getTime() <= last && i < 10000; i++) { + let cursor = new Date(times[0]!) + while (cursor.getTime() <= last) { + // Too many steps to fill: keep every row and skip the gap rows. + if (filled.length === MAX_STEPS) return [...byStep.values()] const time = cursor.getTime() filled.push(byStep.get(time) ?? { [dateKey]: new Date(time), [TIME_KEY]: time }) cursor = STEP[interval](cursor, 1) @@ -192,6 +251,7 @@ export function TimeSeriesChart({ series: seriesKeys, valueFormat = "number", interval, + aggregate = "sum", dateFormat, tooltipDateFormat, variant: variantProp, @@ -224,7 +284,10 @@ export function TimeSeriesChart({ const tickPattern = dateFormat ?? formats.tick const fullPattern = tooltipDateFormat ?? formats.full - const rows = React.useMemo(() => normalizeTimeSeries(data, dateKey, interval), [data, dateKey, interval]) + const rows = React.useMemo( + () => normalizeTimeSeries(data, dateKey, interval, aggregate), + [data, dateKey, interval, aggregate], + ) // In RTL the newest point is drawn on the left; reversing the rows keeps the brush in the same order. const displayRows = React.useMemo(() => (rtl ? [...rows].reverse() : rows), [rows, rtl]) From 8803edd940e34770a020e1ae6db727b2908df479 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 18 Nov 2026 05:43:04 +0000 Subject: [PATCH 04/12] Load the new media when MediaPlayer's src changes (#66, 8.4) Co-Authored-By: Claude Opus 5.5 --- .changeset/media-player-src-change.md | 5 +++++ packages/onu/src/media/media-player.test.tsx | 12 ++++++++++++ packages/onu/src/media/media-player.tsx | 9 +++++++-- 3 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 .changeset/media-player-src-change.md diff --git a/.changeset/media-player-src-change.md b/.changeset/media-player-src-change.md new file mode 100644 index 000000000..24575c6a5 --- /dev/null +++ b/.changeset/media-player-src-change.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`MediaPlayer` now plays the new media when `src` changes. Before, it kept playing the first source. diff --git a/packages/onu/src/media/media-player.test.tsx b/packages/onu/src/media/media-player.test.tsx index 8c46f5790..8c01ffad5 100644 --- a/packages/onu/src/media/media-player.test.tsx +++ b/packages/onu/src/media/media-player.test.tsx @@ -89,6 +89,18 @@ describe("MediaPlayer", () => { await expectNoA11yViolations() }) + it("loads the new media when `src` changes", () => { + // A media element ignores changed children until .load(); a new element loads them. + const { container, rerender } = renderWithOnu() + const first = container.querySelector("video") + rerender() + expect(container.querySelector("video")).toBe(first) + rerender() + const second = container.querySelector("video") + expect(second).not.toBe(first) + expect(second?.querySelector("source")).toHaveAttribute("src", "/v/two.webm") + }) + it("renders audio without fullscreen or captions buttons", () => { const { container } = renderWithOnu( , diff --git a/packages/onu/src/media/media-player.tsx b/packages/onu/src/media/media-player.tsx index c91f28043..01e9532d5 100644 --- a/packages/onu/src/media/media-player.tsx +++ b/packages/onu/src/media/media-player.tsx @@ -138,6 +138,9 @@ export function MediaPlayer({ }, [locale.code, t]) const sources = typeof src === "string" ? [{ src }] : src + // A media element ignores changed children until .load(); a new element per + // source list loads the new media. + const mediaKey = sources.map((s) => s.src).join("\n") const mediaProps = { slot: "media", title, @@ -184,10 +187,12 @@ export function MediaPlayer({ {/* Caption tracks come from the `tracks` prop, rendered in `children` (R14.10). */} {audio ? ( // eslint-disable-next-line jsx-a11y/media-has-caption - + ) : ( // eslint-disable-next-line jsx-a11y/media-has-caption -