diff --git a/.changeset/async-callback-rejections.md b/.changeset/async-callback-rejections.md new file mode 100644 index 00000000..f2319ab1 --- /dev/null +++ b/.changeset/async-callback-rejections.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +Rejected async callbacks no longer surface as unhandled rejections: `Wizard` marks the step as having errors when `validate`, `onValidateStep` or `onComplete` rejects, `LoadMore` shows "Couldn’t load more. Try again." and keeps its button, and the `CommentThread` composer keeps the text and shows an error. diff --git a/.changeset/avatar-upload-transparency.md b/.changeset/avatar-upload-transparency.md new file mode 100644 index 00000000..4482fa1e --- /dev/null +++ b/.changeset/avatar-upload-transparency.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`AvatarUpload` and `cropImage` no longer give transparent images a black background in JPEG output (transparent areas are white), and the cropped avatar file's extension now matches its type, e.g. `.png` with `cropOptions={{ type: "image/png" }}`. diff --git a/.changeset/excel-local-dates.md b/.changeset/excel-local-dates.md new file mode 100644 index 00000000..0508eb5f --- /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/.changeset/export-nan-dates.md b/.changeset/export-nan-dates.md new file mode 100644 index 00000000..b4579d93 --- /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/.changeset/image-cropper-aspect.md b/.changeset/image-cropper-aspect.md new file mode 100644 index 00000000..3330e071 --- /dev/null +++ b/.changeset/image-cropper-aspect.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`ImageCropper` follows a changed `aspect` prop instead of keeping the ratio it was mounted with. diff --git a/.changeset/map-chart-selected-readout.md b/.changeset/map-chart-selected-readout.md new file mode 100644 index 00000000..66175473 --- /dev/null +++ b/.changeset/map-chart-selected-readout.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`MapChart` updates the selected region's read-out when `data` or `geojson` changes, instead of showing the value from when it was selected. diff --git a/.changeset/maps-edits-live-region.md b/.changeset/maps-edits-live-region.md new file mode 100644 index 00000000..67ff709f --- /dev/null +++ b/.changeset/maps-edits-live-region.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +Maps: editing a shape on the map no longer deletes a `MapPolygon` or `MapRoute` shape that is still being entered with the keyboard; `LiveMap` lets a newer `markers` prop replace an earlier streamed update, drops markers that leave `markers`, and its `subscribe` gets a `remove(id)` callback; place search on Google Maps uses the `MapProvider` `region` instead of always the Maldives. diff --git a/.changeset/media-player-src-change.md b/.changeset/media-player-src-change.md new file mode 100644 index 00000000..24575c6a --- /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/.changeset/qr-code-downloads.md b/.changeset/qr-code-downloads.md new file mode 100644 index 00000000..678b285a --- /dev/null +++ b/.changeset/qr-code-downloads.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`QrCode` downloads: `tone="transparent"` in dark mode now saves dark modules on white instead of light modules that do not scan, the SVG download embeds the logo instead of linking to it, and a failed download shows an error under the buttons. diff --git a/.changeset/qr-scanner-repeats.md b/.changeset/qr-scanner-repeats.md new file mode 100644 index 00000000..2db7b219 --- /dev/null +++ b/.changeset/qr-scanner-repeats.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`QrCodeScanner` in `continuous` mode reports a code once while it stays in view instead of four times a second, and when the decoder fails to load it shows a new `decoder-error` status with the Start button to try again. diff --git a/.changeset/signature-pad-dark-ink.md b/.changeset/signature-pad-dark-ink.md new file mode 100644 index 00000000..6352d29b --- /dev/null +++ b/.changeset/signature-pad-dark-ink.md @@ -0,0 +1,5 @@ +--- +"@javaabu/onu": patch +--- + +`SignaturePad` now draws with black ink by default (`penColor`), so a signature made in dark mode no longer exports as near-white strokes; in dark mode the canvas is shown inverted so the ink stays visible. A saved signature from `defaultValue` is no longer erased when the pad resizes. diff --git a/.changeset/time-series-interval-buckets.md b/.changeset/time-series-interval-buckets.md new file mode 100644 index 00000000..a814125c --- /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 441a845a..1a8822ce 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/docs/display-and-feedback/comment-thread.md b/docs/display-and-feedback/comment-thread.md index df8931be..3da87116 100644 --- a/docs/display-and-feedback/comment-thread.md +++ b/docs/display-and-feedback/comment-thread.md @@ -37,6 +37,8 @@ import { CommentThread } from "@javaabu/onu" As in the thread, only the author may delete a note; pass `canDelete={() => true}` to let anyone delete. +If `onAdd` or `onEdit` returns a promise that rejects, the composer keeps the text and shows "Couldn’t save. Try again." as an alert. + ## Props | Prop | Type | Default | Description | diff --git a/docs/files-and-media/avatar-upload.md b/docs/files-and-media/avatar-upload.md index 04b18ddd..375f60b8 100644 --- a/docs/files-and-media/avatar-upload.md +++ b/docs/files-and-media/avatar-upload.md @@ -19,7 +19,7 @@ import { AvatarUpload } from "@javaabu/onu/media" ``` -The cropped image is a square JPEG, 512px by default (`cropOptions`), returned as a `File` through `onValueChange` and kept on the hidden file input for plain form submits. If cropping fails (for example a cross-origin image), the original file is used. +The cropped image is a square JPEG, 512px by default (`cropOptions`), with transparent areas filled white; pass `cropOptions={{ type: "image/png" }}` to keep transparency. The file is named after the picked one with the output type's extension (`me.png` → `me.jpg`). It is returned as a `File` through `onValueChange` and kept on the hidden file input for plain form submits. If cropping fails (for example a cross-origin image), the original file is used. ## Props diff --git a/docs/files-and-media/image-cropper.md b/docs/files-and-media/image-cropper.md index b2448273..d0bd26e3 100644 --- a/docs/files-and-media/image-cropper.md +++ b/docs/files-and-media/image-cropper.md @@ -38,7 +38,7 @@ The canvas helpers are exported for use without the component: `cropImage(src, p | --------------------- | -------------------------------------- | ---------- | -------------------------------------------------------------------- | | `src` | `string \| Blob` | | Image URL or picked file | | `alt` | `string` | (required) | Names the crop area | -| `aspect` | `number` | `1` | Initial aspect ratio | +| `aspect` | `number` | `1` | Aspect ratio; a new value replaces the one in use | | `aspectOptions` | `{ label, value }[]` | | Aspect presets (`undefined` = free, image ratio) | | `onAspectChange` | `(aspect) => void` | | A preset was chosen | | `cropShape` | `"rect" \| "round"` | `"rect"` | Crop shape | diff --git a/docs/files-and-media/qr-code.md b/docs/files-and-media/qr-code.md index 05246e17..e8d24a82 100644 --- a/docs/files-and-media/qr-code.md +++ b/docs/files-and-media/qr-code.md @@ -39,11 +39,11 @@ The code never mirrors and is rendered with tokens through the `tone` variant (` | `theme` | Follows the theme: light modules on a dark ground in dark mode. Most phone cameras scan this, some older readers do not | | `transparent` | No background; modules use the current text colour. Keep enough contrast with what is behind | -Recolour with `classNames.svg`, e.g. `classNames={{ svg: "text-primary" }}`. Downloads use the colours as rendered (read with `getComputedStyle`). +Recolour with `classNames.svg`, e.g. `classNames={{ svg: "text-primary" }}`. Downloads use the colours as rendered (read with `getComputedStyle`). Without a background of its own (`tone="transparent"`) the file gets a white one, and light modules (such as the text colour in dark mode) are saved black so the file still scans. ## Logo -`logo` takes a URL or `{ src, size?, excavate? }`. `size` is the logo width as a fraction of the code (0.1–0.3, default 0.22). The modules behind it are cleared unless `excavate={false}`. A logo always uses error-correction level H, so the code still scans with the centre covered. For the PNG download the image must allow CORS; otherwise the PNG has the cleared area without the logo. +`logo` takes a URL or `{ src, size?, excavate? }`. `size` is the logo width as a fraction of the code (0.1–0.3, default 0.22). The modules behind it are cleared unless `excavate={false}`. A logo always uses error-correction level H, so the code still scans with the centre covered. For downloads the image must allow CORS: the SVG download embeds it as a data URL so the saved file stands alone, and the PNG draws it. When it cannot be fetched, the file has the cleared area without the logo. ## Props @@ -74,7 +74,7 @@ Also exported for custom rendering: `encodeQrCode(value, level)`, `qrCodePath(mo - The code is an `img` named by `label` (default "QR code"); give it a label that says what it is for, e.g. "QR code to verify licence BL-2026-04417". - Put the information in text as well (`showValue`, `caption` or nearby text) for people who cannot scan. -- Download and copy buttons have visible, translated labels and are 44px tall on touch screens. Copying is announced in a polite live region. +- Download and copy buttons have visible, translated labels and are 44px tall on touch screens. Copying is announced in a polite live region. A failed download shows "Could not download the QR code" as an alert under the buttons. - Text that is too long is reported with `role="alert"`. | Key | Action | diff --git a/docs/layout-and-navigation/wizard.md b/docs/layout-and-navigation/wizard.md index e5796516..6bb6eb15 100644 --- a/docs/layout-and-navigation/wizard.md +++ b/docs/layout-and-navigation/wizard.md @@ -29,7 +29,7 @@ import { Wizard } from "@javaabu/onu" ## Navigation -- **Next** validates the current step (`validate`, then `onValidateStep`) and moves on; on the last step it calls `onComplete`. +- **Next** validates the current step (`validate`, then `onValidateStep`) and moves on; on the last step it calls `onComplete`. A `validate`, `onValidateStep` or `onComplete` that rejects marks the step as having errors, as a failed validation does. - **Back** never validates. - With `linear` (default), users can jump back to completed steps, and forward to the furthest unlocked step. `linear={false}` lets them jump anywhere. - `errorSteps={["address"]}` marks steps with server-side errors. diff --git a/docs/listing-pages/export-rows.md b/docs/listing-pages/export-rows.md index daf3d144..cc1127fe 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. 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/docs/listing-pages/load-more.md b/docs/listing-pages/load-more.md index b94e9fac..54655217 100644 --- a/docs/listing-pages/load-more.md +++ b/docs/listing-pages/load-more.md @@ -17,7 +17,7 @@ import { LoadMore } from "@javaabu/onu" /> ``` -If `onLoadMore` returns a promise, the button shows a spinner until it settles (no `loading` prop needed). +If `onLoadMore` returns a promise, the button shows a spinner until it settles (no `loading` prop needed). If the promise rejects, "Couldn’t load more. Try again." appears as an alert and the button stays for another try. ## Props diff --git a/docs/maps/live-map.md b/docs/maps/live-map.md index bbbb9419..76679186 100644 --- a/docs/maps/live-map.md +++ b/docs/maps/live-map.md @@ -10,15 +10,18 @@ import { LiveMap } from "@javaabu/onu/maps" { - const channel = echo.channel("fleet").listen("PositionUpdated", (e) => push(e.vessel)) - return () => channel.stopListening("PositionUpdated") + subscribe={(push, remove) => { + const channel = echo + .channel("fleet") + .listen("PositionUpdated", (e) => push(e.vessel)) + .listen("VesselDocked", (e) => remove(e.vessel.id)) + return () => channel.stopListening("PositionUpdated").stopListening("VesselDocked") }} overlay={} /> ``` -Each marker: `{ id, position, title, heading?, tone?, status?, updatedAt? }`. Updates from `subscribe` merge into `markers` by `id`. +Each marker: `{ id, position, title, heading?, tone?, status?, updatedAt? }`. Updates from `subscribe` merge into `markers` by `id`, and `remove(id)` takes a streamed marker off the map. When a marker changes in `markers` (a new position, heading or `updatedAt`, e.g. from polling) or leaves it, that is newer than its streamed update, so the prop wins. When the selection changes from the built-in list or from outside the map (a controlled `selectedId`, e.g. picking a vessel in your own table), the map pans to centre that marker. It does not turn on follow mode, and a tap on the marker itself does not move the map. Without `center` or `zoom`, the map fits all the markers once (also when they arrive after the first render, e.g. from a stream). @@ -33,7 +36,7 @@ Verified on the real Google Maps JavaScript API (see [MapProvider](./map-provide | Prop | Type | Default | Description | | ------------------------------------------------- | --------------------------- | ------- | --------------------------------------------------------- | | `markers` | `LiveMapMarker[]` | `[]` | Current markers | -| `subscribe` | `(push) => unsubscribe` | | Stream of updates | +| `subscribe` | `(push, remove) => unsubscribe` | | Stream of updates | | `selectedId` / `defaultSelectedId` / `onSelect` | `string \| null` | | Selected marker | | `followId` / `defaultFollowId` / `onFollowChange` | `string \| null` | | Marker the camera follows | | `animationDuration` | `number` | `1000` | Glide time in ms (`0` jumps; reduced motion always jumps) | diff --git a/docs/maps/map-polygon.md b/docs/maps/map-polygon.md index 2bbc67c1..f41848a7 100644 --- a/docs/maps/map-polygon.md +++ b/docs/maps/map-polygon.md @@ -41,7 +41,7 @@ Verified on the real Google Maps JavaScript API (see [MapProvider](./map-provide ## Accessibility -- Every area can be created, reviewed and edited from the list with the keyboard; changes are announced ("Point 3 added"). +- Every area can be created, reviewed and edited from the list with the keyboard; changes are announced ("Point 3 added"). An area still being entered (fewer than 3 points, so not yet on the map) is kept when another area is edited on the map. - Toolbar buttons are toggle buttons (`aria-pressed`). | Key | Action | diff --git a/docs/text-inputs/qr-code-scanner.md b/docs/text-inputs/qr-code-scanner.md index a4ac2dae..0162daee 100644 --- a/docs/text-inputs/qr-code-scanner.md +++ b/docs/text-inputs/qr-code-scanner.md @@ -22,6 +22,8 @@ import { QrCodeScanner } from "@javaabu/onu/media" The camera only starts after the user presses **Start camera** (or with `autoStart`), and browsers only allow it on HTTPS or `localhost`. +With `continuous`, a code that stays in front of the camera is reported once; the same code counts again after it has been out of view for a second. + ## States | Status | Shown | @@ -32,6 +34,7 @@ The camera only starts after the user presses **Start camera** (or with `autoSta | `denied` | How to allow the camera, plus manual entry | | `no-camera` | No camera found, plus manual entry | | `unsupported` | The browser cannot scan, plus manual entry | +| `decoder-error` | The code reader could not be loaded; Start tries again | | `error` | The camera could not be started | ## Props diff --git a/docs/text-inputs/signature-pad.md b/docs/text-inputs/signature-pad.md index 820748a3..bb3e89d4 100644 --- a/docs/text-inputs/signature-pad.md +++ b/docs/text-inputs/signature-pad.md @@ -25,7 +25,7 @@ import { SignaturePad } from "@javaabu/onu/media" | --------------------------------------- | ----------------------------------- | --------------- | ------------------------------------------------------------- | | `onValueChange` | `(dataUrl: string \| null) => void` | | Called after each stroke or typed change; `null` when cleared | | `defaultValue` | `string \| null` | | A saved data URL to start from | -| `penColor` | `string` | text colour | Ink colour | +| `penColor` | `string` | `"#000"` | Ink colour, on screen and in the image | | `backgroundColor` | `string` | transparent | Fill of the exported image | | `minWidth` / `maxWidth` | `number` | `0.75` / `2.75` | Stroke width range | | `disabled` | `boolean` | `false` | Stop drawing and disable the buttons | @@ -39,7 +39,7 @@ import { SignaturePad } from "@javaabu/onu/media" Also exported: `renderTypedSignature(text, options?)`. :::info -The ink follows the theme's text colour by default, so a signature drawn in dark mode exports with light ink. Pass `penColor` (and `backgroundColor`) when the image will be printed or shown on a fixed background. +The ink is black by default, so the exported image reads on a white document in either theme. In dark mode the canvas is shown inverted (with the hue turned back), so dark ink appears light on screen while the saved image keeps the real colours. A saved signature passed as `defaultValue` is drawn again when the canvas resizes. ::: ## RTL and Thaana diff --git a/packages/onu/src/charts/map-chart.test.tsx b/packages/onu/src/charts/map-chart.test.tsx index ea3c8ada..87245fa7 100644 --- a/packages/onu/src/charts/map-chart.test.tsx +++ b/packages/onu/src/charts/map-chart.test.tsx @@ -126,6 +126,34 @@ describe("MapChart", () => { expect(screen.getByRole("table")).toBeInTheDocument() }) + it("updates the selected region's read-out when the data changes", async () => { + const options = { provider: { maps: { googleMapsApiKey: "test-key" } } } + const { container, rerender } = renderWithOnu( + , + options, + ) + await screen.findByTestId("google-map") + const readout = container.querySelector('[data-slot="map-readout"]')! + act(() => selectRef.current!(choroplethRegions(geojson, data).regions[1])) + expect(readout).toHaveTextContent("Addu City: 500") + rerender( + , + ) + expect(readout).toHaveTextContent("Addu City: 650") + // A region that no longer exists clears the read-out. + rerender( + , + ) + expect(readout).toHaveTextContent("Tap or hover over a region") + }) + it("shows the empty state without features", () => { renderWithOnu() expect(screen.getByText("No data to show")).toBeInTheDocument() diff --git a/packages/onu/src/charts/map-chart.tsx b/packages/onu/src/charts/map-chart.tsx index 8cea6fe1..9edf857d 100644 --- a/packages/onu/src/charts/map-chart.tsx +++ b/packages/onu/src/charts/map-chart.tsx @@ -69,13 +69,15 @@ export function MapChart({ const { t, maps } = useOnu() const fmt = useChartFormat(valueFormat) const apiKey = maps.googleMapsApiKey - const [selected, setSelected] = React.useState(null) + // 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) const { regions, scale } = React.useMemo( () => choroplethRegions(geojson, data, { idKey, valueKey, featureIdKey, featureNameKey, steps }), [geojson, data, idKey, valueKey, featureIdKey, featureNameKey, steps], ) const withData = regions.filter((r) => r.value !== null) + const selected = regions.find((r) => r.id === selectedId) ?? null const summary = [ t("chart.summary", { type: t("chart.typeMap"), series: 1, count: withData.length }), @@ -184,7 +186,7 @@ export function MapChart({ color={color} center={center} zoom={zoom} - onSelect={setSelected} + onSelect={(region: ChoroplethRegion | null) => setSelectedId(region?.id ?? null)} /> diff --git a/packages/onu/src/charts/time-series-chart.test.tsx b/packages/onu/src/charts/time-series-chart.test.tsx index a4ff469a..49153bbb 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 71cd7737..9f1d8a6d 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]) diff --git a/packages/onu/src/components/display/_composer.tsx b/packages/onu/src/components/display/_composer.tsx index 15e7e2df..a48477dc 100644 --- a/packages/onu/src/components/display/_composer.tsx +++ b/packages/onu/src/components/display/_composer.tsx @@ -44,6 +44,7 @@ export function Composer({ const { t } = useTranslation() const [body, setBody] = React.useState(defaultValue) const [pending, setPending] = React.useState(false) + const [failed, setFailed] = React.useState(false) const hintId = React.useId() const textarea = React.useRef(null) React.useEffect(() => { @@ -54,9 +55,13 @@ export function Composer({ const submit = async () => { if (!canSubmit) return setPending(true) + setFailed(false) try { await onSubmit(body.trim()) setBody("") + } catch { + // Keep the text so nothing is lost; the user can try again. + setFailed(true) } finally { setPending(false) } @@ -93,6 +98,11 @@ export function Composer({ disabled={disabled || pending} className="min-h-20" /> + {failed ? ( +

+ {t("display.composerFailed")} +

+ ) : null}
{t("display.submitHint")} diff --git a/packages/onu/src/components/display/comment-thread.test.tsx b/packages/onu/src/components/display/comment-thread.test.tsx index bc14afd2..310f3029 100644 --- a/packages/onu/src/components/display/comment-thread.test.tsx +++ b/packages/onu/src/components/display/comment-thread.test.tsx @@ -63,6 +63,20 @@ describe("CommentThread", () => { await waitFor(() => expect(box).toHaveValue("")) }) + it("keeps the text and shows an error when posting fails", async () => { + const user = userEvent.setup() + const onAdd = vi.fn().mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce(undefined) + renderWithOnu() + const box = screen.getByRole("textbox", { name: "Write a comment…" }) + await user.type(box, "Looks good") + await user.click(screen.getByRole("button", { name: "Comment" })) + expect(await screen.findByRole("alert")).toHaveTextContent("Couldn’t save. Try again.") + expect(box).toHaveValue("Looks good") + await user.click(screen.getByRole("button", { name: "Comment" })) + await waitFor(() => expect(box).toHaveValue("")) + expect(screen.queryByRole("alert")).not.toBeInTheDocument() + }) + it("submits with Ctrl+Enter", async () => { const user = userEvent.setup() const onAdd = vi.fn() diff --git a/packages/onu/src/components/layout/wizard.test.tsx b/packages/onu/src/components/layout/wizard.test.tsx index 416748ca..0c6853ea 100644 --- a/packages/onu/src/components/layout/wizard.test.tsx +++ b/packages/onu/src/components/layout/wizard.test.tsx @@ -74,6 +74,28 @@ describe("Wizard", () => { expect(onComplete).toHaveBeenCalled() }) + it("marks the step when onComplete or validation rejects, without an unhandled rejection", async () => { + const onComplete = vi.fn(async () => { + throw new Error("server down") + }) + renderWithOnu() + await userEvent.click(screen.getByRole("button", { name: "Next" })) + await userEvent.click(screen.getByRole("button", { name: "Next" })) + await userEvent.click(screen.getByRole("button", { name: "Submit" })) + await waitFor(() => expect(within(stepList()).getAllByRole("listitem")[2]).toHaveTextContent("Has errors")) + expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled() + }) + + it("treats a rejected validate as a failed step", async () => { + const validate = vi.fn(async (): Promise => { + throw new Error("offline") + }) + renderWithOnu() + await userEvent.click(screen.getByRole("button", { name: "Next" })) + await waitFor(() => expect(within(stepList()).getAllByRole("listitem")[0]).toHaveTextContent("Has errors")) + expect(screen.getByRole("heading", { name: "Applicant" })).toBeInTheDocument() + }) + it("jumps back to completed steps only (linear)", async () => { renderWithOnu() expect(within(stepList()).queryByRole("button")).toBeNull() diff --git a/packages/onu/src/components/layout/wizard.tsx b/packages/onu/src/components/layout/wizard.tsx index 4c1da3c9..b006e549 100644 --- a/packages/onu/src/components/layout/wizard.tsx +++ b/packages/onu/src/components/layout/wizard.tsx @@ -166,20 +166,39 @@ export function Wizard({ if (busy.current) return false busy.current = true setValidating(true) - try { - let ok = true - if (current.validate) ok = await current.validate() - if (ok && onValidateStep) ok = await onValidateStep(index, current) + const markFailed = (hasFailed: boolean) => setFailed((prev) => { const nextSet = new Set(prev) - if (ok) nextSet.delete(index) - else nextSet.add(index) + if (hasFailed) nextSet.add(index) + else nextSet.delete(index) return nextSet }) + try { + let ok = true + try { + if (current.validate) ok = await current.validate() + if (ok && onValidateStep) ok = await onValidateStep(index, current) + } catch { + // A validator that rejects (e.g. a failed request) fails the step. + ok = false + } + markFailed(!ok) if (!ok) return false setCompleted((prev) => new Set(prev).add(index)) - if (index === total - 1) await onComplete?.() - else change(index + 1) + if (index === total - 1) { + try { + await onComplete?.() + } catch { + // A rejected onComplete (e.g. the submit request failed) marks the last step as failed. + setCompleted((prev) => { + const nextSet = new Set(prev) + nextSet.delete(index) + return nextSet + }) + markFailed(true) + return false + } + } else change(index + 1) return true } finally { busy.current = false diff --git a/packages/onu/src/components/listing/load-more.tsx b/packages/onu/src/components/listing/load-more.tsx index dc2beda8..748d9117 100644 --- a/packages/onu/src/components/listing/load-more.tsx +++ b/packages/onu/src/components/listing/load-more.tsx @@ -48,6 +48,7 @@ export function LoadMore({ const nounFor = useNoun(noun) const format = new Intl.NumberFormat(locale.numberLocale) const [pending, setPending] = React.useState(false) + const [failed, setFailed] = React.useState(false) const loading = loadingProp ?? pending const hasMore = hasMoreProp ?? (total !== undefined ? loaded < total : true) const buttonRef = React.useRef(null) @@ -63,12 +64,17 @@ export function LoadMore({ const load = React.useCallback(async () => { if (loading) return + setFailed(false) setBefore(loaded) const result = onLoadMore() if (result && typeof (result as Promise).then === "function") { setPending(true) try { await result + } catch { + // The button stays for another try; say what happened. + setBefore(null) + setFailed(true) } finally { setPending(false) } @@ -112,6 +118,11 @@ export function LoadMore({ {loading ? t("listing.loadingMore") : t("listing.loadMore")} ) : null} + {failed ? ( +

+ {t("listing.loadMoreFailed")} +

+ ) : null} {message} diff --git a/packages/onu/src/components/listing/toolbar.test.tsx b/packages/onu/src/components/listing/toolbar.test.tsx index 185509e2..b11b4683 100644 --- a/packages/onu/src/components/listing/toolbar.test.tsx +++ b/packages/onu/src/components/listing/toolbar.test.tsx @@ -132,6 +132,18 @@ describe("ExportMenu", () => { }) describe("LoadMore", () => { + it("says when loading fails and lets the user try again", async () => { + const onLoadMore = vi.fn(async () => { + throw new Error("network") + }) + renderWithOnu() + await userEvent.click(screen.getByRole("button", { name: "Load more" })) + expect(await screen.findByText("Couldn’t load more. Try again.")).toBeInTheDocument() + expect(screen.getByRole("button", { name: "Load more" })).toBeEnabled() + await userEvent.click(screen.getByRole("button", { name: "Load more" })) + expect(onLoadMore).toHaveBeenCalledTimes(2) + }) + it("loads more, shows progress and announces what arrived", async () => { function Harness() { const [loaded, setLoaded] = React.useState(20) diff --git a/packages/onu/src/export/columns.ts b/packages/onu/src/export/columns.ts index ac8c50bc..5e27028c 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/excel.ts b/packages/onu/src/export/excel.ts index 7cae11c9..e4fb2df8 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 87aa5592..7e9b8f81 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" }) @@ -214,7 +224,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 +261,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) diff --git a/packages/onu/src/locales/dv/display.ts b/packages/onu/src/locales/dv/display.ts index 56291bdd..c05c79e9 100644 --- a/packages/onu/src/locales/dv/display.ts +++ b/packages/onu/src/locales/dv/display.ts @@ -70,6 +70,7 @@ export const display = { deleteCannotUndo: "މިކަން އަނބުރާ ނުގެނެވޭނެ.", noComments: "އަދި އެއްވެސް ކޮމެންޓެއް ނެތް", submitHint: "ފޮނުވުމަށް Ctrl+Enter ފިއްތަވާ", + composerFailed: "ސޭވް ނުކުރެވުނު. އަލުން މަސައްކަތްކުރައްވާ.", // Comment thread, variant="list" notes: "ނޯޓުތައް", addNote: "ނޯޓު އިތުރުކުރޭ", diff --git a/packages/onu/src/locales/dv/file.ts b/packages/onu/src/locales/dv/file.ts index 66fc20fa..61a32839 100644 --- a/packages/onu/src/locales/dv/file.ts +++ b/packages/onu/src/locales/dv/file.ts @@ -114,6 +114,7 @@ export const file = { qrActions: "ކިއުއާރް ކޯޑާ ގުޅޭ ކަންކަން", qrDownloadPng: "PNG ޑައުންލޯޑްކުރޭ", qrDownloadSvg: "SVG ޑައުންލޯޑްކުރޭ", + qrDownloadFailed: "ކިއުއާރް ކޯޑު ޑައުންލޯޑް ނުކުރެވުނު", qrCopyValue: "ލިޔުން ކޮޕީކުރޭ", qrCopied: "ލިޔުން ކޮޕީކުރެވިއްޖެ", qrCopyFailed: "ކޮޕީ ނުކުރެވުނު", diff --git a/packages/onu/src/locales/dv/input.ts b/packages/onu/src/locales/dv/input.ts index 6d6cccb1..c0df9a49 100644 --- a/packages/onu/src/locales/dv/input.ts +++ b/packages/onu/src/locales/dv/input.ts @@ -91,6 +91,7 @@ export const input = { "ކެމެރާ ބޭނުންކުރުން ބްލޮކްކޮށްފައި. ބްރައުޒަރުގެ ސެޓިންގްސްއިން ހުއްދަ ދެއްވާ، ނުވަތަ ތިރީގައި ކޯޑު ލިޔުއްވާ.", scanNoCamera: "މި ޑިވައިސްގައި ކެމެރާއެއް ނުފެނުނު. ތިރީގައި ކޯޑު ލިޔުއްވާ.", scanUnsupported: "މި ބްރައުޒަރުން ކޯޑު ސްކޭން ނުކުރެވޭ. ތިރީގައި ކޯޑު ލިޔުއްވާ.", + scanDecoderError: "ކޯޑު ކިޔާ ގޮތް ތައްޔާރު ނުކުރެވުނު. އަލުން މަސައްކަތްކުރައްވާ، ނުވަތަ ތިރީގައި ކޯޑު ލިޔުއްވާ.", scanError: "ކެމެރާ ހުޅުވިއެއް ނުދިޔަ.", scanTorchOn: "ޓޯޗު ދިއްލާ", scanTorchOff: "ޓޯޗު ނިއްވާ", diff --git a/packages/onu/src/locales/dv/listing.ts b/packages/onu/src/locales/dv/listing.ts index 00862fb6..99db5b82 100644 --- a/packages/onu/src/locales/dv/listing.ts +++ b/packages/onu/src/locales/dv/listing.ts @@ -56,6 +56,7 @@ export const listing = { next: "ދެން އޮތް", loadMore: "އިތުރަށް ލޯޑުކުރޭ", + loadMoreFailed: "އިތުރަށް ލޯޑެއް ނުކުރެވުނު. އަލުން މަސައްކަތްކުރައްވާ.", loadingMore: "އިތުރަށް ލޯޑުވަނީ…", loadedMore: { one: "އިތުރު {count} {noun} ލޯޑުވެއްޖެ", other: "އިތުރު {count} {noun} ލޯޑުވެއްޖެ" }, allLoaded: "ހުރިހާ {total} {noun} ދައްކައިފި", diff --git a/packages/onu/src/locales/en/display.ts b/packages/onu/src/locales/en/display.ts index 77a37351..45197afe 100644 --- a/packages/onu/src/locales/en/display.ts +++ b/packages/onu/src/locales/en/display.ts @@ -69,6 +69,7 @@ export const display = { deleteCannotUndo: "This can't be undone.", noComments: "No comments yet", submitHint: "Press Ctrl+Enter to send", + composerFailed: "Couldn’t save. Try again.", // Comment thread, variant="list" notes: "Notes", addNote: "Add note", diff --git a/packages/onu/src/locales/en/file.ts b/packages/onu/src/locales/en/file.ts index 5125b1dc..32c1ed3a 100644 --- a/packages/onu/src/locales/en/file.ts +++ b/packages/onu/src/locales/en/file.ts @@ -113,6 +113,7 @@ export const file = { qrActions: "QR code actions", qrDownloadPng: "Download PNG", qrDownloadSvg: "Download SVG", + qrDownloadFailed: "Could not download the QR code", qrCopyValue: "Copy text", qrCopied: "Text copied", qrCopyFailed: "Could not copy", diff --git a/packages/onu/src/locales/en/input.ts b/packages/onu/src/locales/en/input.ts index 8fb00de8..0d0683f1 100644 --- a/packages/onu/src/locales/en/input.ts +++ b/packages/onu/src/locales/en/input.ts @@ -89,6 +89,7 @@ export const input = { scanDenied: "Camera access was blocked. Allow it in your browser settings, or enter the code below.", scanNoCamera: "No camera was found on this device. Enter the code below.", scanUnsupported: "This browser cannot scan codes. Enter the code below.", + scanDecoderError: "The code reader could not be loaded. Try again, or enter the code below.", scanError: "The camera could not be started.", scanTorchOn: "Turn on torch", scanTorchOff: "Turn off torch", diff --git a/packages/onu/src/locales/en/listing.ts b/packages/onu/src/locales/en/listing.ts index c0394ba6..ed67ec12 100644 --- a/packages/onu/src/locales/en/listing.ts +++ b/packages/onu/src/locales/en/listing.ts @@ -63,6 +63,7 @@ export const listing = { // Load more loadMore: "Load more", + loadMoreFailed: "Couldn’t load more. Try again.", loadingMore: "Loading more…", loadedMore: { one: "Loaded {count} more {noun}", other: "Loaded {count} more {noun}" }, allLoaded: "All {total} {noun} shown", diff --git a/packages/onu/src/maps/_context.ts b/packages/onu/src/maps/_context.ts index 3198dd88..8cbca736 100644 --- a/packages/onu/src/maps/_context.ts +++ b/packages/onu/src/maps/_context.ts @@ -13,6 +13,8 @@ export interface MapContextValue { colorScheme: "light" | "dark" /** Language for map tiles and the engine's controls. */ language: string + /** Region (CLDR code, e.g. `"MV"`) that biases geocoding and map borders. */ + region: string /** Theme colours as `#rrggbb`. */ colors: MapColors } diff --git a/packages/onu/src/maps/_google-adapter.tsx b/packages/onu/src/maps/_google-adapter.tsx index 2fd0b55e..bd768da0 100644 --- a/packages/onu/src/maps/_google-adapter.tsx +++ b/packages/onu/src/maps/_google-adapter.tsx @@ -299,9 +299,25 @@ function shapesFromSnapshot(features: DrawFeature[], kind: "polygon" | "linestri }) } +const minPoints = (kind: "polygon" | "linestring") => (kind === "polygon" ? 3 : 2) + +/** + * The value after an edit on the map. terra-draw only holds shapes with enough points to draw, + * so a shorter one (being entered with the keyboard) is kept from the current value. + */ +function mergeDrawn(current: DrawShape[], drawn: DrawShape[], kind: "polygon" | "linestring"): DrawShape[] { + const byId = new Map(drawn.map((s) => [s.id, s])) + const kept = current.flatMap((s) => { + const edited = byId.get(s.id) + if (edited) return [edited] + return s.path.length < minPoints(kind) ? [s] : [] + }) + return [...kept, ...drawn.filter((s) => !current.some((c) => c.id === s.id))] +} + function toFeatures(shapes: DrawShape[], kind: "polygon" | "linestring") { return shapes - .filter((s) => s.path.length >= (kind === "polygon" ? 3 : 2)) + .filter((s) => s.path.length >= minPoints(kind)) .map((s) => { const coords = s.path.map(toPosition) return { @@ -333,9 +349,9 @@ function GoogleDraw({ // Set while the value is pushed into terra-draw: its `clear()` reports a delete, // which must not be echoed back as the user removing every shape. const syncing = React.useRef(false) - const callbacks = React.useRef({ onValueChange, onSelect, onFinish }) + const callbacks = React.useRef({ onValueChange, onSelect, onFinish, shapes }) React.useEffect(() => { - callbacks.current = { onValueChange, onSelect, onFinish } + callbacks.current = { onValueChange, onSelect, onFinish, shapes } }) const color = colors[tone] @@ -395,7 +411,7 @@ function GoogleDraw({ }) const emit = () => { if (!instance) return - const next = shapesFromSnapshot(instance.getSnapshot(), kind) + const next = mergeDrawn(callbacks.current.shapes, shapesFromSnapshot(instance.getSnapshot(), kind), kind) lastEmitted.current = JSON.stringify(next) callbacks.current.onValueChange(next) } @@ -647,18 +663,19 @@ function abortable(promise: Promise, signal: AbortSignal) { function useGooglePlaceSearch(): PlaceSearch | null { const geocoding = useMapsLibrary("geocoding") + const { region } = useMapEngine() return React.useMemo(() => { if (!geocoding) return null const geocoder = new geocoding.Geocoder() return async (query, { signal }) => { - const { results } = await abortable(geocoder.geocode({ address: query, region: "mv" }), signal) + const { results } = await abortable(geocoder.geocode({ address: query, region }), signal) return results.map((r) => ({ id: r.place_id, label: r.formatted_address, position: r.geometry.location.toJSON(), })) } - }, [geocoding]) + }, [geocoding, region]) } function stripHtml(html: string) { diff --git a/packages/onu/src/maps/google-adapter.test.tsx b/packages/onu/src/maps/google-adapter.test.tsx index d8a57127..15942908 100644 --- a/packages/onu/src/maps/google-adapter.test.tsx +++ b/packages/onu/src/maps/google-adapter.test.tsx @@ -505,6 +505,65 @@ describe("Google Maps adapter", () => { expect(draw.stop).toHaveBeenCalled() }) + it("keeps a shape too short to draw (entered with the keyboard) when the map is edited", async () => { + const onChange = vi.fn() + const pending = { id: "typed", path: [{ lat: 2, lng: 2 }] } + const complete = { + id: "z1", + path: [ + { lat: 0, lng: 0 }, + { lat: 0, lng: 1 }, + { lat: 1, lng: 1 }, + ], + } + function Draw() { + const { adapter } = useMapEngine() + const D = adapter.Draw + return + } + renderGoogle( + + + , + ) + await waitFor(() => expect(h.draws[0]?.addFeatures).toHaveBeenCalled()) + const draw = h.draws[0]! + // terra-draw only holds the complete polygon. + expect(draw.addFeatures.mock.calls[0]![0]).toHaveLength(1) + draw.snapshot = [ + { + id: "z1", + geometry: { + type: "Polygon", + coordinates: [ + [ + [0, 0], + [5, 0], + [1, 1], + [0, 0], + ], + ], + }, + }, + ] + act(() => draw.handlers.finish!("z1", { action: "dragCoordinate", mode: "select" })) + expect(onChange).toHaveBeenLastCalledWith([ + { + id: "z1", + path: [ + { lat: 0, lng: 0 }, + { lat: 0, lng: 5 }, + { lat: 1, lng: 1 }, + ], + }, + pending, + ]) + // Deleting the polygon on the map still keeps the one being typed. + draw.snapshot = [] + act(() => draw.handlers.change!(["z1"], "delete")) + expect(onChange).toHaveBeenLastCalledWith([pending]) + }) + it("reloads the shapes into a new terra-draw instance when the tone changes", async () => { const shapes = [ { @@ -684,6 +743,28 @@ describe("Google Maps adapter", () => { await expect(pending).rejects.toThrow("Aborted") }) + it("geocodes in the MapProvider's region", async () => { + const geocode = vi.fn(async () => ({ results: [] })) + h.libraries.geocoding = { + Geocoder: class { + geocode = geocode + }, + } + let search: PlaceSearch | null = null + function Probe() { + search = useMapEngine().adapter.usePlaceSearch() + return null + } + renderGoogle( + + + , + ) + await search!("colombo", { signal: new AbortController().signal }) + expect(geocode).toHaveBeenCalledWith({ address: "colombo", region: "LK" }) + expect(last("APIProvider")).toMatchObject({ region: "LK" }) + }) + it("routes with the Directions service", async () => { const route = vi.fn(async (_request: Record) => ({ routes: [ diff --git a/packages/onu/src/maps/live-map.test.tsx b/packages/onu/src/maps/live-map.test.tsx index 63497704..81513fc3 100644 --- a/packages/onu/src/maps/live-map.test.tsx +++ b/packages/onu/src/maps/live-map.test.tsx @@ -106,6 +106,37 @@ describe("LiveMap", () => { expect(unsubscribe).toHaveBeenCalled() }) + it("lets a newer `markers` prop win over an earlier streamed update, and removes markers", () => { + let push!: (m: LiveMapMarker) => void + let remove!: (id: string) => void + const subscribe: LiveMapSubscribe = (p, r) => { + push = p + remove = r + return () => undefined + } + const list = () => screen.getByRole("region", { name: "Markers" }) + const { rerender } = renderWithOnu() + act(() => push({ ...boats[1]!, position: { lat: 4.195, lng: 73.531 } })) + act(() => push({ id: "c", title: "Kandu", position: { lat: 4.2, lng: 73.5 } })) + expect(list()).toHaveTextContent("4.1950") + // The same markers again (a new array from a re-render) keep the streamed position. + rerender( ({ ...m }))} subscribe={subscribe} animationDuration={0} />) + expect(list()).toHaveTextContent("4.1950") + // A newer position from the prop (e.g. polling) replaces the streamed one. + const polled = [boats[0]!, { ...boats[1]!, position: { lat: 4.21, lng: 73.53 } }] + rerender() + expect(list()).toHaveTextContent("4.2100") + expect(list()).not.toHaveTextContent("4.1950") + // Dropped from the prop: gone, even though it was streamed. + act(() => push({ ...boats[1]!, position: { lat: 4.22, lng: 73.53 } })) + rerender() + expect(list()).not.toHaveTextContent("Raajje") + // The stream can remove the markers it added. + expect(list()).toHaveTextContent("Kandu") + act(() => remove("c")) + expect(list()).not.toHaveTextContent("Kandu") + }) + it("shows an empty state and can hide the list", () => { const { rerender } = renderWithOnu() expect(screen.getByText("Nothing to show yet.")).toBeInTheDocument() diff --git a/packages/onu/src/maps/live-map.tsx b/packages/onu/src/maps/live-map.tsx index 08f2bda7..605816bc 100644 --- a/packages/onu/src/maps/live-map.tsx +++ b/packages/onu/src/maps/live-map.tsx @@ -33,13 +33,19 @@ export interface LiveMapMarker { updatedAt?: Date | number } -/** Call `push` with a marker update (new or changed position). Return an unsubscribe function. */ -export type LiveMapSubscribe = (push: (marker: LiveMapMarker) => void) => () => void +/** + * Call `push` with a marker update (new or changed position) and `remove` with the id of a marker + * that has gone. Return an unsubscribe function. + */ +export type LiveMapSubscribe = (push: (marker: LiveMapMarker) => void, remove: (id: string) => void) => () => void export interface LiveMapProps { /** Current markers (e.g. from polling or a parent's state). */ markers?: LiveMapMarker[] - /** Or subscribe to a stream (WebSocket, SSE, Echo). Updates merge into `markers` by id. */ + /** + * Or subscribe to a stream (WebSocket, SSE, Echo). Updates merge into `markers` by id until + * that marker changes in `markers` (a newer position, e.g. from polling) or leaves it. + */ subscribe?: LiveMapSubscribe selectedId?: string | null defaultSelectedId?: string | null @@ -86,8 +92,22 @@ function AnimatedMarker({ ) } +const NO_MARKERS: LiveMapMarker[] = [] + +const epoch = (value: Date | number | undefined) => (value === undefined ? undefined : new Date(value).getTime()) + +/** Whether a marker from `markers` reports something new: a position, heading or time. */ +function moved(before: LiveMapMarker, after: LiveMapMarker) { + return ( + before.position.lat !== after.position.lat || + before.position.lng !== after.position.lng || + before.heading !== after.heading || + epoch(before.updatedAt) !== epoch(after.updatedAt) + ) +} + function LiveMapInner({ - markers: markersProp = [], + markers: markersProp = NO_MARKERS, subscribe, selectedId: selectedProp, defaultSelectedId = null, @@ -114,9 +134,33 @@ function LiveMapInner({ React.useEffect(() => { if (!subscribe) return - return subscribe((marker) => setStreamed((prev) => ({ ...prev, [marker.id]: marker }))) + return subscribe( + (marker) => setStreamed((prev) => ({ ...prev, [marker.id]: marker })), + (id) => + setStreamed((prev) => { + if (!(id in prev)) return prev + const { [id]: _removed, ...rest } = prev + return rest + }), + ) }, [subscribe]) + // A marker that changes in (or leaves) `markers` is newer than its streamed update: drop that. + const [previousProp, setPreviousProp] = React.useState(markersProp) + if (previousProp !== markersProp) { + setPreviousProp(markersProp) + const next = new Map(markersProp.map((m) => [m.id, m])) + const stale = previousProp.filter((m) => { + const after = next.get(m.id) + return !after || moved(m, after) + }) + if (stale.some((m) => m.id in streamed)) { + const rest = { ...streamed } + for (const m of stale) delete rest[m.id] + setStreamed(rest) + } + } + const markers = React.useMemo(() => { const byId = new Map(markersProp.map((m) => [m.id, m])) for (const m of Object.values(streamed)) byId.set(m.id, { ...byId.get(m.id), ...m }) diff --git a/packages/onu/src/maps/map-provider.tsx b/packages/onu/src/maps/map-provider.tsx index f3a69767..e0814217 100644 --- a/packages/onu/src/maps/map-provider.tsx +++ b/packages/onu/src/maps/map-provider.tsx @@ -66,8 +66,8 @@ export function MapProvider({ const mapId = colorScheme === "dark" ? (darkMapId ?? lightMapId) : lightMapId const value = React.useMemo( - () => ({ adapter, apiKey, mapId, colorScheme, language, colors }), - [adapter, apiKey, mapId, colorScheme, language, colors], + () => ({ adapter, apiKey, mapId, colorScheme, language, region, colors }), + [adapter, apiKey, mapId, colorScheme, language, region, colors], ) const Provider = adapter.Provider diff --git a/packages/onu/src/media/avatar-upload.tsx b/packages/onu/src/media/avatar-upload.tsx index 5fe8f4c1..207efcf9 100644 --- a/packages/onu/src/media/avatar-upload.tsx +++ b/packages/onu/src/media/avatar-upload.tsx @@ -14,7 +14,7 @@ import { useTranslation } from "../providers/onu-provider" import { Avatar, AvatarFallback, AvatarImage } from "../ui/avatar" import { Button } from "../ui/button" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog" -import type { CropImageOptions } from "./crop-image" +import { imageExtension, type CropImageOptions } from "./crop-image" import { ImageCropper, type ImageCropperHandle } from "./image-cropper" import { registerEnglish } from "../i18n/english" import { common as en_common } from "../locales/en/common" @@ -120,8 +120,9 @@ export function AvatarUpload({ if (!pending) return setSaving(true) try { - const name = pending.name.replace(/\.[^.]+$/, "") + ".jpg" - const file = await cropper.current!.getFile(name, { type: "image/jpeg", maxSize: 512, ...cropOptions }) + const options = { type: "image/jpeg", maxSize: 512, ...cropOptions } + const name = `${pending.name.replace(/\.[^.]+$/, "")}.${imageExtension(options.type)}` + const file = await cropper.current!.getFile(name, options) setImage(file) setPending(null) } catch { diff --git a/packages/onu/src/media/crop-image.ts b/packages/onu/src/media/crop-image.ts index 944925f6..61a5c8a2 100644 --- a/packages/onu/src/media/crop-image.ts +++ b/packages/onu/src/media/crop-image.ts @@ -9,7 +9,7 @@ export interface PixelCrop { export interface CropImageOptions { /** Rotation in degrees, applied before cropping. */ rotation?: number - /** Output type. Default `image/jpeg` (`image/png` keeps transparency). */ + /** Output type. Default `image/jpeg`, where transparent areas become white (`image/png` keeps transparency). */ type?: string /** 0–1 quality for lossy types. Default `0.92`. */ quality?: number @@ -76,10 +76,21 @@ export async function cropImage( const ctx = out.getContext("2d") if (!ctx) throw new Error("Canvas is not supported") ctx.imageSmoothingQuality = "high" + // JPEG has no alpha: unpainted pixels would export black, so start from white. + if (type === "image/jpeg") { + ctx.fillStyle = "#fff" + ctx.fillRect(0, 0, out.width, out.height) + } ctx.drawImage(rotated, crop.x, crop.y, crop.width, crop.height, 0, 0, out.width, out.height) return canvasToBlob(out, type, quality) } +/** The usual file extension for an image type, e.g. `jpg` for `image/jpeg`. */ +export function imageExtension(type: string) { + const subtype = type.split("/")[1]?.split(/[+;]/)[0] ?? "" + return subtype === "jpeg" ? "jpg" : subtype || "img" +} + /** Like `cropImage`, but returns a `File` with the given name. */ export async function cropImageToFile(src: string, crop: PixelCrop, name: string, options: CropImageOptions = {}) { const blob = await cropImage(src, crop, options) diff --git a/packages/onu/src/media/image-cropper.test.tsx b/packages/onu/src/media/image-cropper.test.tsx index 15d28082..6fc6feb3 100644 --- a/packages/onu/src/media/image-cropper.test.tsx +++ b/packages/onu/src/media/image-cropper.test.tsx @@ -33,7 +33,14 @@ vi.mock("react-easy-crop", () => ({ /** Fake canvas + image so cropImage runs in jsdom. */ function mockCanvas() { - const ctx = { translate: vi.fn(), rotate: vi.fn(), drawImage: vi.fn(), imageSmoothingQuality: "" } + const ctx = { + translate: vi.fn(), + rotate: vi.fn(), + drawImage: vi.fn(), + fillRect: vi.fn(), + fillStyle: "", + imageSmoothingQuality: "", + } vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(ctx as never) vi.spyOn(HTMLCanvasElement.prototype, "toBlob").mockImplementation(function (cb, type) { cb(new Blob(["x"], { type: type ?? "image/png" })) @@ -81,6 +88,17 @@ describe("crop helpers", () => { expect(f.type).toBe("image/png") }) + it("puts transparent pixels on white for JPEG, which has no transparency", async () => { + const ctx = mockCanvas() + await cropImage("/a.png", { x: 0, y: 0, width: 20, height: 10 }) + expect(ctx.fillStyle).toBe("#fff") + expect(ctx.fillRect).toHaveBeenCalledWith(0, 0, 20, 10) + expect(ctx.fillRect.mock.invocationCallOrder[0]).toBeLessThan(ctx.drawImage.mock.invocationCallOrder.at(-1)!) + ctx.fillRect.mockClear() + await cropImage("/a.png", { x: 0, y: 0, width: 20, height: 10 }, { type: "image/png" }) + expect(ctx.fillRect).not.toHaveBeenCalled() + }) + it("rejects broken images, missing canvas support and failed exports", async () => { mockCanvas() await expect(loadImage("/broken.jpg")).rejects.toThrow(/Could not load/) @@ -127,6 +145,13 @@ describe("ImageCropper", () => { await expectNoA11yViolations() }) + it("follows a changed `aspect` prop", () => { + const { rerender } = renderWithOnu() + expect(screen.getByTestId("cropper")).toHaveAttribute("data-aspect", "1") + rerender() + expect(screen.getByTestId("cropper")).toHaveAttribute("data-aspect", String(4 / 3)) + }) + it("switches aspect ratios, including free cropping", async () => { const onAspectChange = vi.fn() renderWithOnu( @@ -206,6 +231,26 @@ describe("AvatarUpload", () => { await expectNoA11yViolations() }) + it("names the cropped file after its output type", async () => { + mockCanvas() + const onChange = vi.fn() + const { container } = renderWithOnu( + , + ) + await userEvent.upload(pick(container), new File(["x"], "me.photo.jpeg", { type: "image/jpeg" })) + await screen.findByRole("dialog", { name: "Crop photo" }) + act(() => + (cropperProps.current!.onCropComplete as (a: unknown, b: unknown) => void)( + {}, + { x: 0, y: 0, width: 10, height: 10 }, + ), + ) + await userEvent.click(screen.getByRole("button", { name: "Save photo" })) + await waitFor(() => + expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ name: "me.photo.png", type: "image/png" })), + ) + }) + it("falls back to the original file when cropping fails, and can cancel", async () => { const onChange = vi.fn() const { container } = renderWithOnu() diff --git a/packages/onu/src/media/image-cropper.tsx b/packages/onu/src/media/image-cropper.tsx index 129eb226..3cbbff4b 100644 --- a/packages/onu/src/media/image-cropper.tsx +++ b/packages/onu/src/media/image-cropper.tsx @@ -85,6 +85,12 @@ export function ImageCropper({ const [zoom, setZoom] = React.useState(1) const [rotation, setRotation] = React.useState(0) const [aspect, setAspect] = React.useState(aspectProp) + // A new `aspect` from the parent replaces the current one (also one picked from `aspectOptions`). + const [previousAspectProp, setPreviousAspectProp] = React.useState(aspectProp) + if (previousAspectProp !== aspectProp) { + setPreviousAspectProp(aspectProp) + setAspect(aspectProp) + } const [area, setArea] = React.useState(null) const [mediaAspect, setMediaAspect] = React.useState(1) const helpId = React.useId() diff --git a/packages/onu/src/media/media-player.test.tsx b/packages/onu/src/media/media-player.test.tsx index 8c46f579..8c01ffad 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 c91f2804..01e9532d 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 -
diff --git a/packages/onu/src/media/signature-pad.test.tsx b/packages/onu/src/media/signature-pad.test.tsx index b4116bfe..3a105e33 100644 --- a/packages/onu/src/media/signature-pad.test.tsx +++ b/packages/onu/src/media/signature-pad.test.tsx @@ -154,6 +154,46 @@ describe("SignaturePad", () => { expect(lastPad().toData()).toHaveLength(1) }) + it("redraws a saved signature after a resize", () => { + vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(300) + vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(160) + vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({ scale: vi.fn() } as never) + renderWithOnu() + expect(lastPad().fromDataURL).toHaveBeenCalledTimes(1) + vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(200) + act(() => { + window.dispatchEvent(new Event("resize")) + }) + expect(lastPad().fromDataURL).toHaveBeenCalledTimes(2) + expect(lastPad().fromDataURL).toHaveBeenLastCalledWith("data:image/png;base64,saved") + expect(document.querySelector("input[name=signature]")!.value).toBe("data:image/png;base64,saved") + }) + + it("draws and exports with dark ink, even when the theme text is light", async () => { + // Dark mode: the text colour is near-white, which would vanish on a white document. + const computed = window.getComputedStyle.bind(window) + vi.spyOn(window, "getComputedStyle").mockImplementation((element, pseudo) => { + const style = computed(element, pseudo) + return new Proxy(style, { + get: (target, key) => { + if (key === "color") return "rgb(250, 250, 250)" + const value = Reflect.get(target, key) as unknown + return typeof value === "function" ? (value as (...a: unknown[]) => unknown).bind(target) : value + }, + }) + }) + const ctx = { font: "", fillStyle: "", measureText: () => ({ width: 1 }), fillText: vi.fn() } + vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(ctx as never) + vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockReturnValue("data:image/png;base64,typed") + renderWithOnu() + expect(lastPad().penColor).toBe("#000") + // On screen the canvas is inverted in dark mode, so the ink still reads. + expect(screen.getByRole("img")).toHaveClass("dark:invert") + await userEvent.click(screen.getByRole("button", { name: "Type" })) + await userEvent.type(screen.getByRole("textbox"), "A") + expect(ctx.fillStyle).toBe("#000") + }) + it("loads a saved signature and follows pen settings and disabled", () => { const { rerender } = renderWithOnu( , diff --git a/packages/onu/src/media/signature-pad.tsx b/packages/onu/src/media/signature-pad.tsx index cba7bd36..71ead784 100644 --- a/packages/onu/src/media/signature-pad.tsx +++ b/packages/onu/src/media/signature-pad.tsx @@ -53,7 +53,10 @@ export interface SignaturePadProps extends Omit, "de onValueChange?: (dataUrl: string | null) => void /** A data URL to start from, e.g. a saved signature. */ defaultValue?: string | null - /** Ink colour. Defaults to the text colour (`currentColor`), so it follows the theme. */ + /** + * Ink colour, on screen and in the exported image. Default black, so the signature reads on a + * white document; in dark mode the canvas is shown inverted so the ink stays visible. + */ penColor?: string /** Fill colour of the exported image. Default transparent. */ backgroundColor?: string @@ -82,7 +85,7 @@ export interface SignaturePadProps extends Omit, "de export function SignaturePad({ onValueChange, defaultValue = null, - penColor, + penColor = "#000", backgroundColor = "rgba(0,0,0,0)", minWidth = 0.75, maxWidth = 2.75, @@ -115,22 +118,19 @@ export function SignaturePad({ const [dataUrl, setDataUrl] = React.useState(defaultValue) const [announce, setAnnounce] = React.useState(null) const initial = React.useRef(defaultValue) + // A loaded saved signature is an image, not strokes; a resize has to draw it again. + const image = React.useRef(null) const emit = React.useCallback((url: string | null) => { setDataUrl(url) onValueChangeRef.current?.(url) }, []) - const ink = React.useCallback( - () => penColor ?? (canvasRef.current ? getComputedStyle(canvasRef.current).color : "") ?? "#000", - [penColor], - ) - // Create the pad once the canvas is in the document (draw mode). React.useEffect(() => { const canvas = canvasRef.current if (mode !== "draw" || !canvas) return - const pad = new SignaturePadLib(canvas, { penColor: ink() || "#000", backgroundColor, minWidth, maxWidth }) + const pad = new SignaturePadLib(canvas, { penColor, backgroundColor, minWidth, maxWidth }) padRef.current = pad const onEnd = () => { setStrokes(pad.toData().length) @@ -150,13 +150,19 @@ export function SignaturePad({ canvas.height = Math.round(height * ratio) canvas.getContext("2d")?.scale(ratio, ratio) pad.clear() - if (data.length) pad.fromData(data) + if (image.current) { + // Strokes drawn over the saved signature go back on top once it has loaded. + void pad + .fromDataURL(image.current) + .then(() => data.length && pad.fromData(data, { clear: false })) + .catch(() => undefined) + } else if (data.length) pad.fromData(data) } resize() if (initial.current) { - const url = initial.current + image.current = initial.current initial.current = null - void pad.fromDataURL(url).catch(() => undefined) + void pad.fromDataURL(image.current).catch(() => undefined) } const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(resize) observer?.observe(canvas) @@ -174,13 +180,13 @@ export function SignaturePad({ React.useEffect(() => { const pad = padRef.current if (!pad) return - pad.penColor = ink() || "#000" + pad.penColor = penColor pad.minWidth = minWidth pad.maxWidth = maxWidth pad.backgroundColor = backgroundColor if (disabled) pad.off() else pad.on() - }, [ink, minWidth, maxWidth, backgroundColor, disabled, mode]) + }, [penColor, minWidth, maxWidth, backgroundColor, disabled, mode]) const undo = () => { const pad = padRef.current @@ -193,6 +199,7 @@ export function SignaturePad({ } const clear = () => { + image.current = null padRef.current?.clear() setStrokes(0) setTyped("") @@ -204,6 +211,7 @@ export function SignaturePad({ if (next === mode) return setInnerMode(next) onModeChange?.(next) + image.current = null setStrokes(0) setTyped("") emit(null) @@ -239,14 +247,16 @@ export function SignaturePad({ ) : null} {mode === "draw" ? ( -
+
{ setTyped(e.target.value) - emit(renderTypedSignature(e.target.value, { color: ink() || "#000" })) + emit(renderTypedSignature(e.target.value, { color: penColor })) }} />