From 5b74eb183ff135bc130147f13a62c4aa81f4d95e Mon Sep 17 00:00:00 2001 From: Joely Date: Tue, 3 Nov 2026 11:27:55 -0500 Subject: [PATCH 01/16] components 0.5.4 (unpublished): a document requirement's card, its versions and its capture, fed by the checklist item (contract request #117) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The partner's documents screens paint getMyStatus's checklist item (partner 0.2.53, K-32), so the library gets the pieces, with no document type of their own: - Partner/DocumentRequirementCard (portable): a Paper Card composed as Paper composes one. The title is the rule's name for the market, else the catalogue's (viewModel requirementTitle); the host's subtitle; a photo taken and not sent as the cover; what to do now and the rule's explanation; actions as Paper Buttons straight inside Card.Actions, which gives them their modes. Without actions it only reads (the console). - Partner/DocumentVersionList (portable): the item's versions as ListRows from viewModel documentVersionRows (the verification's label or «Superseded»; when sent, in the app's locale; «Scanning»; the reason; «Expires»). They open nothing, so no chevron. - Partner/DocumentCaptureCard (barrel only, the picker is native): the card with the way to send it, as item.capture says: one photo, or the front then the back (the front waits as the cover); «Subir un PDF» only with capture.pdf and an onUploadPdf. - ImagePicker.Avatar variant="sheet": no control of its own; the caller opens the sheet with the ref's show(), so its own Paper Button sits in Card.Actions (owner, 2026-11-03: the card's own button). avatar and button are as before. - documentAddFront, documentAddBack, documentAddBackPrompt, documentUploadPdf and documentSuperseded move here from the app's catalogue, same words (owner, 2026-11-03). Stories: Partner/DocumentRequirement.stories.js, the local circuit's real items (US, US-MA). Tests: the view model, the three components and the picker's sheet variant (14). The R1 and portable-entry guards pass. Co-Authored-By: Claude Opus 5.5 --- PROJECT.md | 18 ++ packages/components/package-lock.json | 4 +- packages/components/package.json | 2 +- .../src/ImagePicker/ImagePickerAvatar.js | 86 +++--- .../__tests__/ImagePickerAvatar.test.js | 79 ++++++ .../src/Localization/Translations/en.json | 5 + .../src/Localization/Translations/es.json | 5 + .../src/Partner/DocumentCaptureCard.js | 69 +++++ .../Partner/DocumentRequirement.stories.js | 216 +++++++++++++++ .../src/Partner/DocumentRequirementCard.js | 66 +++++ .../src/Partner/DocumentVersionList.js | 36 +++ .../__tests__/documentRequirement.test.js | 259 ++++++++++++++++++ packages/components/src/Partner/viewModel.js | 31 ++- packages/components/src/index.js | 4 + packages/components/src/portable.js | 3 + 15 files changed, 845 insertions(+), 38 deletions(-) create mode 100644 packages/components/src/ImagePicker/__tests__/ImagePickerAvatar.test.js create mode 100644 packages/components/src/Partner/DocumentCaptureCard.js create mode 100644 packages/components/src/Partner/DocumentRequirement.stories.js create mode 100644 packages/components/src/Partner/DocumentRequirementCard.js create mode 100644 packages/components/src/Partner/DocumentVersionList.js create mode 100644 packages/components/src/Partner/__tests__/documentRequirement.test.js diff --git a/PROJECT.md b/PROJECT.md index 599a0df7..f7982c71 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -213,6 +213,24 @@ themed through `useTheme()` so a host's theme applies: `onError({source, error})` reports an image the default renderer could not load (a lapsed signed URL). - `DecisionDialog` — Paper `Dialog` in a `Portal` (the host needs Paper's `Provider`). - `Timeline` — `history` and `steps`. +- Document requirements (contract request #117, 0.5.4), fed by a `getMyStatus` checklist item, so no host keeps a + document type of its own: + - `Partner/DocumentRequirementCard` (portable) — a Paper `Card` composed as Paper composes one: the title is + `requirementTitle(item)` (the rule's name for the market, else the catalogue's), `subtitle` is the host's, + then `cover` (a photo taken and not sent), `note` and the rule's explanation, and `actions` + (`{ label, onPress, isDisabled?, testID? }`) as Paper `Button`s straight inside `Card.Actions`, which gives + them their modes. Without `actions` it only reads (the console). + - `Partner/DocumentVersionList` (portable) — `item.versions` as `ListRow`s from `documentVersionRows`; they open + nothing, so no chevron. + - `Partner/DocumentCaptureCard` (barrel only: the picker is native) — the card with the way to send it, as + `item.capture` says (`pages` 1, or 2 = the front then the back; `pdf`): the front waits as the cover until the + back is taken, `onCapture(photos)` gets the pages in order, and «Subir un PDF» shows only with `capture.pdf` + and an `onUploadPdf` (none while the console acts as the partner). + - `ImagePicker.Avatar` `variant="sheet"` renders no control of its own; the caller opens the sheet with the + ref's `show()`, so its own Paper `Button` can sit inside a `Card.Actions`. `avatar` and `button` are as before. + - Their fixed words (`documentAddFront`, `documentAddBack`, `documentAddBackPrompt`, `documentUploadPdf`, + `documentSuperseded`) live in `Translations/*.json`; the stories (`Partner/DocumentRequirement.stories.js`) + use the local circuit's real items. - `Partner/viewModel.js` (barrel/portable: `PartnerViewModel`, because `statusLabel` is the Order one): the key is the package's `statusLabelKey(group, value)` resolved with `localized`; a value outside the vocabulary, or a key the registered catalogue lacks, renders the raw value. Each kind's group is read diff --git a/packages/components/package-lock.json b/packages/components/package-lock.json index 0321dfff..27385312 100644 --- a/packages/components/package-lock.json +++ b/packages/components/package-lock.json @@ -1,12 +1,12 @@ { "name": "@jmstechnologiesinc/react-native-components", - "version": "0.5.3", + "version": "0.5.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@jmstechnologiesinc/react-native-components", - "version": "0.5.3", + "version": "0.5.4", "license": "ISC", "devDependencies": { "@jmstechnologiesinc/partner": "0.2.48", diff --git a/packages/components/package.json b/packages/components/package.json index 788d5a7b..83659bb0 100644 --- a/packages/components/package.json +++ b/packages/components/package.json @@ -1,6 +1,6 @@ { "name": "@jmstechnologiesinc/react-native-components", - "version": "0.5.3", + "version": "0.5.4", "description": "Biblioteca de componentes de interfaz compartida por las aplicaciones de Daxir.", "author": "yerloveraaa ", "homepage": "https://github.com/jmstechnologiesinc/react-native-components#readme", diff --git a/packages/components/src/ImagePicker/ImagePickerAvatar.js b/packages/components/src/ImagePicker/ImagePickerAvatar.js index d262e22d..ef5c0df4 100644 --- a/packages/components/src/ImagePicker/ImagePickerAvatar.js +++ b/packages/components/src/ImagePicker/ImagePickerAvatar.js @@ -1,4 +1,4 @@ -import React, { useEffect, useRef } from 'react'; +import React, { forwardRef, useEffect, useImperativeHandle, useRef } from 'react'; import { moderateScale } from '@jmstechnologiesinc/react-native-size-matters'; import { Avatar as PaperAvatar, MD3LightTheme, TouchableRipple, List } from '@jmstechnologiesinc/react-native-paper'; @@ -19,17 +19,25 @@ export const IMAGE_PICKER_ACTIONS = { cancel: 'cancel', }; -const Avatar = ({ - photo, - onChange, - onRemove, - title, - variant = 'avatar', - icon = 'account', - size = moderateScale(150), - options = [], - isDisabled, -}) => { +/** + * The photo picker: a camera / library / cancel sheet, opened by an avatar (`variant="avatar"`), by a text button + * (`variant="button"`), or, with `variant="sheet"`, by the caller's own control through the ref's `show()` — so a + * caller can put a Paper `Button` straight inside its own container (a `Card.Actions` styles only its direct children). + */ +const Avatar = forwardRef(function Avatar( + { + photo, + onChange, + onRemove, + title, + variant = 'avatar', + icon = 'account', + size = moderateScale(150), + options = [], + isDisabled, + }, + ref +) { const imagePickerRef = useRef(); const actionSheetRef = useRef(); @@ -50,6 +58,8 @@ const Avatar = ({ actionSheetRef.current.show(); }; + useImperativeHandle(ref, () => ({ show: showActionSheet }), []); + const onActionDone = async (value) => { if (value === IMAGE_PICKER_ACTIONS.launchCamera) { imagePickerRef.current.takePhoto().then((rep) => { @@ -88,29 +98,37 @@ const Avatar = ({ { title: localized('cancel'), value: IMAGE_PICKER_ACTIONS.cancel, icon: 'cancel' }, ]; + // What opens the sheet: the avatar, the text button, or nothing of its own (`sheet`: the caller's control, `show()`). + let trigger = null; + if (variant === 'avatar') { + trigger = ( + + + {photo ? ( + + ) : ( + + )} + + + ); + } else if (variant !== 'sheet') { + trigger = ( + + ); + } + return ( <> - {variant === 'avatar' ? ( - - - {photo ? ( - - ) : ( - - )} - - - ) : ( - - )} + {trigger} ); -}; +}); export default Avatar; diff --git a/packages/components/src/ImagePicker/__tests__/ImagePickerAvatar.test.js b/packages/components/src/ImagePicker/__tests__/ImagePickerAvatar.test.js new file mode 100644 index 00000000..522ca852 --- /dev/null +++ b/packages/components/src/ImagePicker/__tests__/ImagePickerAvatar.test.js @@ -0,0 +1,79 @@ +import React, { createRef } from 'react'; +import renderer, { act } from 'react-test-renderer'; + +import { MD3LightTheme, Provider } from '@jmstechnologiesinc/react-native-paper'; + +import ButtonWrapper from '../../ButtonWrapper/ButtonWrapper'; +import ImagePickerAvatar from '../ImagePickerAvatar'; + +// The sheet is native; a stand-in records being opened through the same ref the picker uses. +const mockSheet = { shown: 0 }; +jest.mock('react-native-actions-sheet', () => { + const React = require('react'); + const ActionSheet = React.forwardRef(({ children }, ref) => { + React.useImperativeHandle(ref, () => ({ + show: () => { + mockSheet.shown += 1; + }, + hide: () => {}, + })); + return children; + }); + return { __esModule: true, default: ActionSheet }; +}); +// Insets of zero, and the context Paper's Provider reads them from (the library's own jest mock ships as TypeScript +// in the root install, which this config does not transform). +jest.mock('react-native-safe-area-context', () => { + const React = require('react'); + const insets = { top: 0, bottom: 0, left: 0, right: 0 }; + const frame = { x: 0, y: 0, width: 390, height: 844 }; + return { + SafeAreaProvider: ({ children }) => children, + SafeAreaInsetsContext: React.createContext(insets), + SafeAreaFrameContext: React.createContext(frame), + useSafeAreaInsets: () => insets, + useSafeAreaFrame: () => frame, + initialWindowMetrics: { insets, frame }, + }; +}); +jest.mock('../ImagePickerAPI', () => jest.fn()); + +jest.useFakeTimers(); + +const mounted = []; +const render = (element) => { + let tree; + act(() => { + tree = renderer.create({element}); + }); + mounted.push(tree); + return tree; +}; + +beforeEach(() => { + mockSheet.shown = 0; +}); + +afterEach(() => { + act(() => { + mounted.splice(0).forEach((tree) => tree.unmount()); + jest.runOnlyPendingTimers(); + }); +}); + +describe('ImagePicker.Avatar', () => { + it('opens its sheet from its own text button, as before', () => { + const tree = render(); + const [button] = tree.root.findAllByType(ButtonWrapper); + act(() => button.props.onPress()); + expect(mockSheet.shown).toBe(1); + }); + + it('with variant="sheet", renders no control of its own and opens through the ref', () => { + const ref = createRef(); + const tree = render(); + expect(tree.root.findAllByType(ButtonWrapper)).toHaveLength(0); + act(() => ref.current.show()); + expect(mockSheet.shown).toBe(1); + }); +}); diff --git a/packages/components/src/Localization/Translations/en.json b/packages/components/src/Localization/Translations/en.json index a5862c47..7584fb54 100644 --- a/packages/components/src/Localization/Translations/en.json +++ b/packages/components/src/Localization/Translations/en.json @@ -804,6 +804,11 @@ "contactSupportForHelp": "Contact support for help.", "documentExpires": "Expires", "documentExpired": "Expired", + "documentAddFront": "Add the front", + "documentAddBack": "Add the back", + "documentAddBackPrompt": "Now take a photo of the back of your licence.", + "documentUploadPdf": "Upload a PDF", + "documentSuperseded": "Superseded", "documentExpiryDate": "Expiry date", "documentExpiryInvalid": "Enter a valid future date (MM/DD/YYYY).", "reactivate": "Reactivate", diff --git a/packages/components/src/Localization/Translations/es.json b/packages/components/src/Localization/Translations/es.json index 41a583ce..9e53ef64 100644 --- a/packages/components/src/Localization/Translations/es.json +++ b/packages/components/src/Localization/Translations/es.json @@ -804,6 +804,11 @@ "contactSupportForHelp": "Contacta a soporte para más información.", "documentExpires": "Vence", "documentExpired": "Vencido", + "documentAddFront": "Añadir el anverso", + "documentAddBack": "Añadir el reverso", + "documentAddBackPrompt": "Ahora haz una foto del reverso de tu licencia.", + "documentUploadPdf": "Subir un PDF", + "documentSuperseded": "Sustituido", "documentExpiryDate": "Fecha de vencimiento", "documentExpiryInvalid": "Ingresa una fecha válida y futura (MM/DD/YYYY).", "reactivate": "Reactivar", diff --git a/packages/components/src/Partner/DocumentCaptureCard.js b/packages/components/src/Partner/DocumentCaptureCard.js new file mode 100644 index 00000000..437bbce9 --- /dev/null +++ b/packages/components/src/Partner/DocumentCaptureCard.js @@ -0,0 +1,69 @@ +import React, { useRef, useState } from 'react'; + +import ImagePickerAvatar from '../ImagePicker/ImagePickerAvatar'; +import { localized } from '../Localization/Localization'; +import DocumentRequirementCard from './DocumentRequirementCard'; + +/** + * Contract request #117: a document requirement's card with the way to send it, as the server says one version of it + * is taken (`item.capture`, K-32): one photo, or the front and then the back (§9.8.1 step 1), and one PDF from the + * phone's browser when `capture.pdf` and the host can open the link (#66; never while the console acts as the + * partner). The front waits here, shown as the card's cover with what to do next, until the back is taken; then + * `onCapture(photos)` gets the pages in order (the picker's assets) and the host sends them. The photo sheet is the + * library's picker, opened by the card's own button (`variant="sheet"`). Not portable: the picker is native. + * + * @param {{item: object, subtitle?: ?string, onCapture: (photos: Array) => void, + * onUploadPdf?: ?(() => void), isDisabled?: boolean, testID?: string}} props + */ +const DocumentCaptureCard = ({ + item, + subtitle, + onCapture, + onUploadPdf, + isDisabled = false, + testID = 'document-requirement', +}) => { + const pickerRef = useRef(); + const [front, setFront] = useState(null); + const twoSided = item.capture?.pages === 2; + + const take = (photo) => { + if (twoSided && !front) { + setFront(photo); + return; + } + setFront(null); + onCapture(front ? [front, photo] : [photo]); + }; + + let addLabel = localized('add'); + if (twoSided) addLabel = localized(front ? 'documentAddBack' : 'documentAddFront'); + const add = { label: addLabel, onPress: () => pickerRef.current?.show(), isDisabled, testID: `${testID}-add` }; + + // Card.Actions makes the first button outlined and the next contained: the way to send is the last. + let actions = [add]; + if (front) { + actions = [{ label: localized('cancel'), onPress: () => setFront(null), testID: `${testID}-cancel` }, add]; + } else if (item.capture?.pdf && onUploadPdf) { + actions = [ + { label: localized('documentUploadPdf'), onPress: onUploadPdf, isDisabled, testID: `${testID}-pdf` }, + add, + ]; + } + + return ( + <> + + + + ); +}; + +export default DocumentCaptureCard; diff --git a/packages/components/src/Partner/DocumentRequirement.stories.js b/packages/components/src/Partner/DocumentRequirement.stories.js new file mode 100644 index 00000000..4981101f --- /dev/null +++ b/packages/components/src/Partner/DocumentRequirement.stories.js @@ -0,0 +1,216 @@ +import React from 'react'; +import { ScrollView, View } from 'react-native'; + +import { interpunct } from '@jmstechnologiesinc/commons'; +import { EN, ES, REQUIREMENT_CAUSE, formatVehicleValue, vehicleValueParts } from '@jmstechnologiesinc/partner'; +import { MD3LightTheme } from '@jmstechnologiesinc/react-native-paper'; + +import { localized, registerFlatCatalog, setI18nConfig } from '../Localization/Localization'; +import DocumentCaptureCard from './DocumentCaptureCard'; +import DocumentRequirementCard from './DocumentRequirementCard'; +import DocumentVersionList from './DocumentVersionList'; +import { requirementTitle, statusLabel } from './viewModel'; + +// The library's own words, then the `partner.*` catalogue, which belongs to `@jmstechnologiesinc/partner` (R2): a +// host sets both up once, as here. +setI18nConfig(); +registerFlatCatalog({ en: EN, es: ES }); + +export default { + title: 'packages/Partner/DocumentRequirement', +}; + +// Real items, nothing made up: the two drivers of the local circuit (US → US-MA, Boxford), as getMyStatus answers +// their checklist (read from the emulators on 2026-11-03), with the five fields of contract request #117 filled from +// what the server holds for them — the composed rules persisted beside their state (`label`, `explanation`), the +// server's capture table, and their versions in `…/partner_documents`. +const HONDA = { vehicleType: 'car', color: 'BLK', make: 'Honda', model: 'Accord', licensePlate: '123456' }; +const CIVIC = { vehicleType: 'car', color: 'BGE', make: 'cifid', model: 'civic', licensePlate: '123445' }; +const ONE_PAGE = { pages: 1, pdf: true }; + +const US_LICENCE = { + en: "The valid driver's license of whoever drives a motor vehicle. Not asked for a store's own deliveries: the store's declaration stands in for it there.", + es: 'La licencia de conducir vigente de quien conduce un vehículo de motor. No se pide para las entregas de una tienda: ahí la sustituye la declaración de la tienda.', +}; +const US_INSURANCE = { + en: "The valid insurance policy of each motor vehicle they work with. Not asked for a store's own deliveries: the store's declaration stands in for it there.", + es: 'La póliza de seguro vigente de cada vehículo de motor con el que trabaja. No se pide para las entregas de una tienda: ahí la sustituye la declaración de la tienda.', +}; + +const LICENCE_NOTHING_SENT = { + id: 'driver_license', + requirementKey: 'driver_license', + bucket: 'currently_due', + cause: 'missing', + evidence: 'document', + explanation: US_LICENCE, + documentType: 'driver_licence', + capture: { pages: 2, pdf: true }, + versions: [], +}; + +const INSPECTION_DUE_SOON = { + id: 'lhmawbh2rCiMmzcoY5Om.vehicle_inspection', + requirementKey: 'vehicle_inspection', + vehicleId: 'lhmawbh2rCiMmzcoY5Om', + vehicle: HONDA, + bucket: 'eventually_due', + cause: 'expiring_within_notice', + evidence: 'document', + expiresAt: 1795478400000, + label: { en: 'Annual vehicle safety inspection', es: 'Inspección anual de seguridad del vehículo' }, + explanation: { + en: 'The current Massachusetts safety inspection of each vehicle they drive passengers in, done every year at an RMV-licensed station.', + es: 'La inspección de seguridad vigente de Massachusetts de cada vehículo con el que lleva pasajeros, hecha cada año en una estación autorizada por el RMV.', + }, + documentType: 'state_safety_inspection_report', + capture: ONE_PAGE, + versions: [ + { + versionId: '6WoqFfmibiFIgv6Ko6nh', + verification: { status: 'verified' }, + expires_at: '2026-11-23', + scan: { status: 'clean' }, + submittedTime: 1793249082020, + }, + ], +}; + +const INSURANCE_WITH_HISTORY = { + id: 'lhmawbh2rCiMmzcoY5Om.vehicle_insurance', + requirementKey: 'vehicle_insurance', + vehicleId: 'lhmawbh2rCiMmzcoY5Om', + vehicle: HONDA, + bucket: null, + cause: 'satisfied', + evidence: 'document', + expiresAt: 1893456000000, + explanation: US_INSURANCE, + documentType: 'insurance', + capture: ONE_PAGE, + versions: [ + { + versionId: '3p9wgxM49qaibuOFC9KT', + verification: { status: 'verified' }, + expires_at: '2029-12-31', + scan: { status: 'clean' }, + submittedTime: 1793249519602, + }, + { + versionId: 'VjNKwrsZCIt1uEiYJS1F', + verification: { status: 'unverified', details_code: 'document_not_readable' }, + scan: { status: 'clean' }, + supersededBy: '3p9wgxM49qaibuOFC9KT', + submittedTime: 1793249040678, + }, + ], +}; + +const INSURANCE_JUST_SENT = { + id: 'krb6NkPk2R9LLukYD1bj.vehicle_insurance', + requirementKey: 'vehicle_insurance', + vehicleId: 'krb6NkPk2R9LLukYD1bj', + vehicle: CIVIC, + bucket: 'currently_due', + cause: 'missing', + evidence: 'document', + explanation: US_INSURANCE, + documentType: 'insurance', + capture: ONE_PAGE, + versions: [ + { + versionId: 'kOFizggUFsNliTITk3fW', + verification: { status: 'pending' }, + scan: { status: 'pending' }, + submittedTime: 1793675729952, + }, + ], +}; + +const DPU_CERTIFICATE = { + id: 'ma_dpu_clearance_certificate', + requirementKey: 'ma_dpu_clearance_certificate', + bucket: null, + cause: 'satisfied', + evidence: 'document', + expiresAt: 1893456000000, + label: { en: 'DPU background check clearance certificate', es: 'Certificado de antecedentes del DPU' }, + explanation: { + en: 'The certificate the Massachusetts Department of Public Utilities issues once it has checked their criminal, sex offender and driving records.', + es: 'El certificado que emite el Departamento de Servicios Públicos de Massachusetts tras revisar sus antecedentes penales, de delitos sexuales y de manejo.', + }, + documentType: 'ma_dpu_clearance_certificate', + capture: ONE_PAGE, + versions: [ + { + versionId: 'yzu7Y8MIxmmwb7jHFseI', + verification: { status: 'verified' }, + expires_at: '2029-12-31', + scan: { status: 'clean' }, + submittedTime: 1793249092768, + }, + ], +}; + +// The subtitle is the host's: the app names the vehicle and where the requirement stands, but not `missing` (its add +// control says it; owner, 2026-11-03). The stories say it the same way. +const subtitleOf = (item) => + interpunct([ + item.vehicle ? formatVehicleValue(vehicleValueParts(item.vehicle), localized) : null, + item.cause === REQUIREMENT_CAUSE.MISSING ? null : statusLabel('requirement_cause', item.cause), + ]); + +const pane = { padding: MD3LightTheme.spacing.x4, gap: MD3LightTheme.spacing.x2 }; + +// The app's document screen: the card with its capture, then the versions. +const Screen = ({ item, canUploadPdf = true }) => ( + + {}} + onUploadPdf={canUploadPdf ? () => {} : null} + /> + + +); + +export const LicenceNothingSent = () => ; + +export const InspectionDueSoonMassachusetts = () => ; + +export const InsuranceWithHistory = () => ; + +export const InsuranceJustSent = () => ; + +export const MassachusettsOnlyCertificate = () => ; + +// While the console acts as the partner: no PDF link (the hook gives none). +export const ActingAsNoPdf = () => ; + +// What the console shows of it («Así lo ve el socio»): the card reads, nothing is sent. +export const ReadOnlyInTheConsole = () => ( + + + + +); + +// The front of a licence taken and waiting for the back. The cover is the partner's own photo, which a story does +// not have: an empty one shows where it goes. +export const LicenceFrontTaken = () => ( + + {} }, + { label: localized('documentAddBack'), onPress: () => {} }, + ]} + /> + +); diff --git a/packages/components/src/Partner/DocumentRequirementCard.js b/packages/components/src/Partner/DocumentRequirementCard.js new file mode 100644 index 00000000..683231a8 --- /dev/null +++ b/packages/components/src/Partner/DocumentRequirementCard.js @@ -0,0 +1,66 @@ +import React from 'react'; + +import { MATERIAL_ICONS } from '@jmstechnologiesinc/commons'; +import { Avatar, Button, Card, Text, useTheme } from '@jmstechnologiesinc/react-native-paper'; + +import { requirementTitle, ruleText } from './viewModel'; + +/** + * Contract request #117: one requirement of the partner as the server states it (a `getMyStatus` checklist item), in + * a Paper `Card` composed the way Paper composes one, with no style of its own: + * - the title is the composed rule's name for the partner's market, else the catalogue's (`requirementTitle`); + * - `subtitle` is what the host says of it (its vehicle and where it stands, in the host's words); + * - `cover` is the URI of a photo the partner has just taken and not sent yet (the front of a two-sided document); + * - the content is `note` (what to do now) and the rule's plain explanation for the market; + * - `actions` are `{ label, onPress, isDisabled?, testID? }`, Paper `Button`s straight inside `Card.Actions`, which + * gives them their modes (the first outlined, the next contained). + * Without `actions` (the console showing what the partner sees) the card only reads. + * + * @param {{item: object, subtitle?: ?string, cover?: ?string, note?: ?string, + * actions?: Array<{label: string, onPress: () => void, isDisabled?: boolean, testID?: string}>, testID?: string}} props + */ +const DocumentRequirementCard = ({ item, subtitle, cover, note, actions = [], testID = 'document-requirement' }) => { + const { spacing } = useTheme(); + const explanation = ruleText(item.explanation); + return ( + + } + /> + {cover ? : null} + {note || explanation ? ( + + {note ? ( + + {note} + + ) : null} + {explanation ? ( + + {explanation} + + ) : null} + + ) : null} + {actions.length > 0 ? ( + + {actions.map(({ label, onPress, isDisabled, testID: actionTestID }) => ( + + ))} + + ) : null} + + ); +}; + +export default DocumentRequirementCard; diff --git a/packages/components/src/Partner/DocumentVersionList.js b/packages/components/src/Partner/DocumentVersionList.js new file mode 100644 index 00000000..74d633c9 --- /dev/null +++ b/packages/components/src/Partner/DocumentVersionList.js @@ -0,0 +1,36 @@ +import React from 'react'; +import { View } from 'react-native'; + +import { MATERIAL_ICONS } from '@jmstechnologiesinc/commons'; + +import ListRow from '../ListRow/ListRow'; +import { documentVersionRows } from './viewModel'; + +/** + * Contract request #117: a document requirement's versions as the server sent them (`checklistItem.versions`, newest + * first), one `ListRow` (a Paper `List.Item`) each: the version's state is the title, when it was sent and what the + * server says of it the description. The rows are the view model's (`documentVersionRows`) and open nothing, so they + * carry no chevron. No versions, no list. + * + * @param {{versions: ?Array, accessibilityLabel: string, testID?: string}} props + * `accessibilityLabel` names the list (the requirement it belongs to); each row's testID is `-` + */ +const DocumentVersionList = ({ versions, accessibilityLabel, testID = 'document-versions' }) => { + const rows = documentVersionRows(versions); + if (rows.length === 0) return null; + return ( + + {rows.map(({ key, title, description }) => ( + + ))} + + ); +}; + +export default DocumentVersionList; diff --git a/packages/components/src/Partner/__tests__/documentRequirement.test.js b/packages/components/src/Partner/__tests__/documentRequirement.test.js new file mode 100644 index 00000000..a35dd388 --- /dev/null +++ b/packages/components/src/Partner/__tests__/documentRequirement.test.js @@ -0,0 +1,259 @@ +import React from 'react'; +import renderer, { act } from 'react-test-renderer'; + +import { EN, ES } from '@jmstechnologiesinc/partner'; +import { MD3LightTheme, Provider } from '@jmstechnologiesinc/react-native-paper'; + +import { formatDateTime } from '../../Localization/format'; +import { registerFlatCatalog, setI18nConfig } from '../../Localization/Localization'; +import DocumentCaptureCard from '../DocumentCaptureCard'; +import DocumentRequirementCard from '../DocumentRequirementCard'; +import DocumentVersionList from '../DocumentVersionList'; +import { documentVersionRows, requirementTitle } from '../viewModel'; + +// The photo sheet is the native picker; here it is a stand-in that records being opened and hands back the photo a +// test gives it, through the same ref and `onChange` the card uses. +const mockPicker = { shown: 0, take: null }; +jest.mock('../../ImagePicker/ImagePickerAvatar', () => { + const React = require('react'); + const Sheet = React.forwardRef(({ onChange }, ref) => { + React.useImperativeHandle(ref, () => ({ + show: () => { + mockPicker.shown += 1; + }, + })); + mockPicker.take = onChange; + return null; + }); + return { __esModule: true, default: Sheet }; +}); + +// Paper animates on timers; fake ones, and unmounting after each test, keep those animations from firing after the +// environment is torn down. +jest.useFakeTimers(); + +const mounted = []; +const render = (element) => { + let tree; + act(() => { + tree = renderer.create({element}); + }); + mounted.push(tree); + return tree; +}; + +beforeAll(() => { + setI18nConfig(); + registerFlatCatalog({ en: EN, es: ES }); +}); + +beforeEach(() => { + mockPicker.shown = 0; + mockPicker.take = null; +}); + +afterEach(() => { + act(() => { + mounted.splice(0).forEach((tree) => tree.unmount()); + jest.runOnlyPendingTimers(); + }); +}); + +// Every string a host Text renders, in order. +const textsOf = (tree) => + tree.root + .findAll((node) => node.type === 'Text' && typeof node.props.children === 'string') + .map((node) => node.props.children); +const buttonOf = (tree, testID) => + tree.root.findAll((node) => node.props.testID === testID && typeof node.props.onPress === 'function')[0]; +const hasTestID = (tree, testID) => tree.root.findAll((node) => node.props.testID === testID).length > 0; +const press = (tree, testID) => act(() => buttonOf(tree, testID).props.onPress()); +const take = (photo) => act(() => mockPicker.take(photo)); + +const INSPECTION = { + id: 'car1.vehicle_inspection', + requirementKey: 'vehicle_inspection', + vehicleId: 'car1', + bucket: 'eventually_due', + cause: 'expiring_within_notice', + evidence: 'document', + label: { en: 'Annual vehicle safety inspection', es: 'Inspección anual de seguridad del vehículo' }, + explanation: { en: 'The current Massachusetts safety inspection.', es: 'La inspección de seguridad vigente.' }, + documentType: 'state_safety_inspection_report', + capture: { pages: 1, pdf: true }, + versions: [], +}; +const LICENCE = { + id: 'driver_license', + requirementKey: 'driver_license', + bucket: 'currently_due', + cause: 'missing', + evidence: 'document', + documentType: 'driver_licence', + capture: { pages: 2, pdf: true }, + versions: [], +}; +const AT = 1793249082020; + +describe('requirementTitle', () => { + it("is the rule's own name for the market, in the reader's language", () => { + expect(requirementTitle(INSPECTION)).toBe('Annual vehicle safety inspection'); + }); + + it("is the catalogue's name when the rule has none", () => { + expect(requirementTitle(LICENCE)).toBe(EN['partner.requirement.driver_license']); + expect(requirementTitle({ requirementKey: 'car1.vehicle_insurance' })).toBe( + EN['partner.requirement.vehicle_insurance'] + ); + }); +}); + +describe('documentVersionRows', () => { + it('titles a version by its verification, or as superseded, and says only what the version says', () => { + const rows = documentVersionRows([ + { versionId: 'v3', verification: { status: 'pending' }, scan: { status: 'pending' }, submittedTime: AT }, + { + versionId: 'v2', + verification: { status: 'verified' }, + expires_at: '2026-11-23', + scan: { status: 'clean' }, + submittedTime: AT, + }, + { + versionId: 'v1', + verification: { status: 'unverified', details_code: 'document_not_readable' }, + scan: { status: 'clean' }, + supersededBy: 'v2', + submittedTime: AT, + }, + ]); + const sent = formatDateTime(AT); + expect(rows).toEqual([ + { + key: 'v3', + title: EN['partner.verification_status.pending'], + description: `${sent} · ${EN['partner.scan_status.pending']}`, + }, + { + key: 'v2', + title: EN['partner.verification_status.verified'], + description: `${sent} · Expires 2026-11-23`, + }, + { + key: 'v1', + title: 'Superseded', + description: `${sent} · ${EN['partner.details_code.document_not_readable']}`, + }, + ]); + }); + + it('has no rows without versions', () => { + expect(documentVersionRows(undefined)).toEqual([]); + expect(documentVersionRows([])).toEqual([]); + }); +}); + +describe('DocumentRequirementCard', () => { + it("reads the rule's name, the host's subtitle and the rule's explanation, and offers nothing by itself", () => { + const tree = render(); + expect(textsOf(tree)).toEqual([ + 'Annual vehicle safety inspection', + 'Black Honda Accord · 123456', + 'The current Massachusetts safety inspection.', + ]); + expect(hasTestID(tree, 'document-requirement-cover')).toBe(false); + expect(tree.root.findAll((node) => typeof node.props.onPress === 'function')).toHaveLength(0); + }); + + it('shows a photo taken, what to do next, and the actions the host gives it', () => { + const onPress = jest.fn(); + const tree = render( + + ); + expect(hasTestID(tree, 'document-requirement-cover')).toBe(true); + expect(textsOf(tree)).toContain('Now take a photo of the back of your licence.'); + press(tree, 'cancel'); + expect(onPress).toHaveBeenCalledTimes(1); + }); +}); + +describe('DocumentVersionList', () => { + it('lists one row per version, and nothing without versions', () => { + const versions = [{ versionId: 'v1', verification: { status: 'verified' }, submittedTime: AT }]; + const tree = render(); + expect(hasTestID(tree, 'document-versions-v1')).toBe(true); + expect( + hasTestID(render(), 'document-versions') + ).toBe(false); + }); +}); + +describe('DocumentCaptureCard', () => { + it('takes one photo of a one-page document and hands it over at once', () => { + const onCapture = jest.fn(); + const tree = render(); + expect(textsOf(tree)).toEqual(expect.arrayContaining(['Upload a PDF', 'Add'])); + press(tree, 'document-requirement-add'); + expect(mockPicker.shown).toBe(1); + take({ uri: 'file:///page.jpg' }); + expect(onCapture).toHaveBeenCalledWith([{ uri: 'file:///page.jpg' }]); + }); + + it('keeps the front of a two-sided document, shows it, then hands over the front and the back', () => { + const onCapture = jest.fn(); + const tree = render(); + expect(textsOf(tree)).toContain('Add the front'); + + take({ uri: 'file:///front.jpg' }); + expect(onCapture).not.toHaveBeenCalled(); + expect(hasTestID(tree, 'document-requirement-cover')).toBe(true); + expect(textsOf(tree)).toEqual( + expect.arrayContaining(['Now take a photo of the back of your licence.', 'Cancel', 'Add the back']) + ); + expect(textsOf(tree)).not.toContain('Upload a PDF'); + + take({ uri: 'file:///back.jpg' }); + expect(onCapture).toHaveBeenCalledWith([{ uri: 'file:///front.jpg' }, { uri: 'file:///back.jpg' }]); + expect(hasTestID(tree, 'document-requirement-cover')).toBe(false); + expect(textsOf(tree)).toContain('Add the front'); + }); + + it('drops the front on «Cancel»', () => { + const onCapture = jest.fn(); + const tree = render(); + take({ uri: 'file:///front.jpg' }); + press(tree, 'document-requirement-cancel'); + expect(hasTestID(tree, 'document-requirement-cover')).toBe(false); + expect(textsOf(tree)).toContain('Add the front'); + expect(onCapture).not.toHaveBeenCalled(); + }); + + it('offers the PDF only where the server takes one and the host can open the link', () => { + const withPdf = render(); + expect(hasTestID(withPdf, 'document-requirement-pdf')).toBe(true); + // Acting as the partner, the host gives no link. + const actingAs = render(); + expect(hasTestID(actingAs, 'document-requirement-pdf')).toBe(false); + const noPdf = render( + + ); + expect(hasTestID(noPdf, 'document-requirement-pdf')).toBe(false); + }); + + it('disables sending while the host sends', () => { + const tree = render( + + ); + expect(buttonOf(tree, 'document-requirement-add').props.disabled).toBe(true); + expect(buttonOf(tree, 'document-requirement-pdf').props.disabled).toBe(true); + }); +}); diff --git a/packages/components/src/Partner/viewModel.js b/packages/components/src/Partner/viewModel.js index 7de70171..327d53db 100644 --- a/packages/components/src/Partner/viewModel.js +++ b/packages/components/src/Partner/viewModel.js @@ -1,4 +1,4 @@ -import { MATERIAL_ICONS } from '@jmstechnologiesinc/commons'; +import { interpunct, MATERIAL_ICONS } from '@jmstechnologiesinc/commons'; import { CHECKR_REPORT_ADJUDICATION, CHECKR_REPORT_RESULT, @@ -24,12 +24,14 @@ import { RULE_CLAUSE, RULE_ERROR_CODE, RULE_REFERENCE_SUBJECT, + SCAN_STATUS, SCREENING_PACKAGE, STAFF_INTENT, VERIFICATION_STATUS, statusLabelKey, } from '@jmstechnologiesinc/partner'; +import { formatDateTime } from '../Localization/format'; import { currentLocale, localized } from '../Localization/Localization'; import { STATUS_TONES } from '../tones'; @@ -92,6 +94,7 @@ const GROUP = Object.freeze({ disabledReason: groupOf(DISABLED_REASON), intent: groupOf(STAFF_INTENT), refusal: groupOf(REFUSAL_REASON), + scan: groupOf(SCAN_STATUS), }); const { success, warning, danger, neutral, info } = STATUS_TONES; @@ -384,6 +387,32 @@ const COUNT_WORD = Object.freeze({ /** A rule's own text (`{en, es}`, written in the rules editor) in the reader's language, else the package's first. */ export const ruleText = (text) => (text ? text[currentLocale().split('-')[0]] ?? text[LOCALES[0]] : null); +/** + * Contract request #117: a requirement's name — the composed rule's own for the partner's market (`label`, #97) when + * it has one, else the catalogue's — so the hub, the lists and the document screen name one requirement one way. + */ +export const requirementTitle = (item) => ruleText(item?.label) ?? requirementLabel(item?.requirementKey); + +/** + * Contract request #117: a document requirement's versions (`checklistItem.versions`, newest first, as the server + * sends them) as list rows `{ key, title, description }`. The title is the version's state: «Superseded» once a newer + * one replaced it, else its verification's label. The description is when it was sent (in the app's locale), that it + * is still being scanned, why it was not accepted and until when it counts — each only when the version says it. + */ +export const documentVersionRows = (versions) => + (Array.isArray(versions) ? versions : []).map((version) => ({ + key: version.versionId, + title: version.supersededBy + ? localized('documentSuperseded') + : statusLabel('verification', version.verification?.status), + description: interpunct([ + formatDateTime(version.submittedTime), + version.scan?.status === SCAN_STATUS.PENDING ? labelOf(GROUP.scan, version.scan.status) : null, + detailsCodeLabel(version.verification?.details_code), + version.expires_at ? `${localized('documentExpires')} ${version.expires_at}` : null, + ]), + })); + /** «24 h», «30 días»: the catalogue's word for the count, or the bare count while no catalogue carries it. */ const countText = (kind, count) => { const key = statusLabelKey(CLAUSE_WORD, COUNT_WORD[kind]); diff --git a/packages/components/src/index.js b/packages/components/src/index.js index 882bd035..578027ed 100644 --- a/packages/components/src/index.js +++ b/packages/components/src/index.js @@ -80,6 +80,10 @@ export { localizedAuthError } from './Localization/authErrors'; // K-22 — also served by `portable.js`, the entry a web host imports. export { default as StatusChip, SlaChip, LabelChip } from './Partner/StatusChip'; export { default as RuleClauseList } from './Partner/RuleClauseList'; +export { default as DocumentRequirementCard } from './Partner/DocumentRequirementCard'; +export { default as DocumentVersionList } from './Partner/DocumentVersionList'; +// Contract request #117: the card with its capture; native (the photo picker), so not in portable.js. +export { default as DocumentCaptureCard } from './Partner/DocumentCaptureCard'; export { default as DocumentViewer } from './DocumentViewer/DocumentViewer'; export { default as DecisionDialog } from './DecisionDialog/DecisionDialog'; export { default as Timeline } from './Timeline/Timeline'; diff --git a/packages/components/src/portable.js b/packages/components/src/portable.js index 50a6823a..28033742 100644 --- a/packages/components/src/portable.js +++ b/packages/components/src/portable.js @@ -73,6 +73,9 @@ export { orderViewModel, fromDescriptor, statusLabel } from './Order/viewModel'; // K-22 export { default as StatusChip, SlaChip, LabelChip } from './Partner/StatusChip'; export { default as RuleClauseList } from './Partner/RuleClauseList'; +// Contract request #117: a document requirement and its versions, read-only (the capture card is native). +export { default as DocumentRequirementCard } from './Partner/DocumentRequirementCard'; +export { default as DocumentVersionList } from './Partner/DocumentVersionList'; export { default as DocumentViewer, ZOOM } from './DocumentViewer/DocumentViewer'; export { default as DecisionDialog } from './DecisionDialog/DecisionDialog'; // The web keyboard contract of a modal surface (focus in, Tab trap, Esc, From 403c1b0fad69944969bdcece81efc658d87692d4 Mon Sep 17 00:00:00 2001 From: Joely Date: Tue, 3 Nov 2026 15:42:22 -0500 Subject: [PATCH 02/16] =?UTF-8?q?components=200.5.4=20(unpublished):=20tak?= =?UTF-8?q?ing=20a=20document's=20photo=20sends=20nothing;=20=C2=ABSend=20?= =?UTF-8?q?to=20review=C2=BB=20does=20(owner,=202026-11-03)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DocumentCaptureCard keeps the pages taken (one, or the front then the back) and shows them as the card's covers. The card's actions follow MD3 (the main action last, Card.Actions makes it contained): «Cancel» drops what was taken, «Send to review» (the catalogue's existing `sendToReview`) hands the pages to onCapture in order. With nothing taken, the PDF link and the add button as before. DocumentRequirementCard takes `covers` (the photos in order) instead of one `cover`. Stories: the front waiting for the back, and both sides ready to send. Tests: one page, two sides, cancel at each step, the PDF, sending disabled. Co-Authored-By: Claude Opus 5.5 --- PROJECT.md | 9 ++-- .../src/Partner/DocumentCaptureCard.js | 41 +++++++++++-------- .../Partner/DocumentRequirement.stories.js | 20 +++++++-- .../src/Partner/DocumentRequirementCard.js | 17 ++++++-- .../__tests__/documentRequirement.test.js | 40 +++++++++++++----- 5 files changed, 89 insertions(+), 38 deletions(-) diff --git a/PROJECT.md b/PROJECT.md index f7982c71..095a2c43 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -217,15 +217,16 @@ themed through `useTheme()` so a host's theme applies: document type of its own: - `Partner/DocumentRequirementCard` (portable) — a Paper `Card` composed as Paper composes one: the title is `requirementTitle(item)` (the rule's name for the market, else the catalogue's), `subtitle` is the host's, - then `cover` (a photo taken and not sent), `note` and the rule's explanation, and `actions` + then `covers` (the photos taken and not sent, in order), `note` and the rule's explanation, and `actions` (`{ label, onPress, isDisabled?, testID? }`) as Paper `Button`s straight inside `Card.Actions`, which gives them their modes. Without `actions` it only reads (the console). - `Partner/DocumentVersionList` (portable) — `item.versions` as `ListRow`s from `documentVersionRows`; they open nothing, so no chevron. - `Partner/DocumentCaptureCard` (barrel only: the picker is native) — the card with the way to send it, as - `item.capture` says (`pages` 1, or 2 = the front then the back; `pdf`): the front waits as the cover until the - back is taken, `onCapture(photos)` gets the pages in order, and «Subir un PDF» shows only with `capture.pdf` - and an `onUploadPdf` (none while the console acts as the partner). + `item.capture` says (`pages` 1, or 2 = the front then the back; `pdf`). Taking a photo sends nothing: the pages + show as covers, and «Send to review» (the card's last, contained action) hands them to `onCapture(photos)` in + order, «Cancel» drops them. «Subir un PDF» shows only with `capture.pdf` and an `onUploadPdf` (none while the + console acts as the partner). - `ImagePicker.Avatar` `variant="sheet"` renders no control of its own; the caller opens the sheet with the ref's `show()`, so its own Paper `Button` can sit inside a `Card.Actions`. `avatar` and `button` are as before. - Their fixed words (`documentAddFront`, `documentAddBack`, `documentAddBackPrompt`, `documentUploadPdf`, diff --git a/packages/components/src/Partner/DocumentCaptureCard.js b/packages/components/src/Partner/DocumentCaptureCard.js index 437bbce9..5dddd7e7 100644 --- a/packages/components/src/Partner/DocumentCaptureCard.js +++ b/packages/components/src/Partner/DocumentCaptureCard.js @@ -8,7 +8,8 @@ import DocumentRequirementCard from './DocumentRequirementCard'; * Contract request #117: a document requirement's card with the way to send it, as the server says one version of it * is taken (`item.capture`, K-32): one photo, or the front and then the back (§9.8.1 step 1), and one PDF from the * phone's browser when `capture.pdf` and the host can open the link (#66; never while the console acts as the - * partner). The front waits here, shown as the card's cover with what to do next, until the back is taken; then + * partner). Taking a photo sends nothing (owner, 2026-11-03): the pages taken show as the card's covers, and the + * partner sends them with the card's last action, «Send to review», or drops them with «Cancel»; then * `onCapture(photos)` gets the pages in order (the picker's assets) and the host sends them. The photo sheet is the * library's picker, opened by the card's own button (`variant="sheet"`). Not portable: the picker is native. * @@ -24,26 +25,34 @@ const DocumentCaptureCard = ({ testID = 'document-requirement', }) => { const pickerRef = useRef(); - const [front, setFront] = useState(null); - const twoSided = item.capture?.pages === 2; + const [pages, setPages] = useState([]); + const pageCount = item.capture?.pages === 2 ? 2 : 1; + const twoSided = pageCount === 2; + const complete = pages.length === pageCount; - const take = (photo) => { - if (twoSided && !front) { - setFront(photo); - return; - } - setFront(null); - onCapture(front ? [front, photo] : [photo]); + const take = (photo) => setPages((taken) => (taken.length < pageCount ? [...taken, photo] : taken)); + const cancel = () => setPages([]); + const send = () => { + const photos = pages; + setPages([]); + onCapture(photos); }; let addLabel = localized('add'); - if (twoSided) addLabel = localized(front ? 'documentAddBack' : 'documentAddFront'); + if (twoSided) addLabel = localized(pages.length === 0 ? 'documentAddFront' : 'documentAddBack'); const add = { label: addLabel, onPress: () => pickerRef.current?.show(), isDisabled, testID: `${testID}-add` }; + const cancelAction = { label: localized('cancel'), onPress: cancel, testID: `${testID}-cancel` }; - // Card.Actions makes the first button outlined and the next contained: the way to send is the last. + // MD3: a card's actions close it, the main one last. Card.Actions makes the first button outlined and the next + // contained, so what moves the partner forward (add the next side, or send) is the last. let actions = [add]; - if (front) { - actions = [{ label: localized('cancel'), onPress: () => setFront(null), testID: `${testID}-cancel` }, add]; + if (complete) { + actions = [ + cancelAction, + { label: localized('sendToReview'), onPress: send, isDisabled, testID: `${testID}-send` }, + ]; + } else if (pages.length > 0) { + actions = [cancelAction, add]; } else if (item.capture?.pdf && onUploadPdf) { actions = [ { label: localized('documentUploadPdf'), onPress: onUploadPdf, isDisabled, testID: `${testID}-pdf` }, @@ -56,8 +65,8 @@ const DocumentCaptureCard = ({ page.uri)} + note={twoSided && pages.length === 1 ? localized('documentAddBackPrompt') : null} actions={actions} testID={testID} /> diff --git a/packages/components/src/Partner/DocumentRequirement.stories.js b/packages/components/src/Partner/DocumentRequirement.stories.js index 4981101f..11bfa281 100644 --- a/packages/components/src/Partner/DocumentRequirement.stories.js +++ b/packages/components/src/Partner/DocumentRequirement.stories.js @@ -199,13 +199,14 @@ export const ReadOnlyInTheConsole = () => ( ); -// The front of a licence taken and waiting for the back. The cover is the partner's own photo, which a story does -// not have: an empty one shows where it goes. +// What the partner has taken shows on the card before anything is sent (owner, 2026-11-03): the front waiting for the +// back, then both sides with «Send to review». The covers are the partner's own photos, which a story does not have: +// empty ones show where they go. export const LicenceFrontTaken = () => ( {} }, @@ -214,3 +215,16 @@ export const LicenceFrontTaken = () => ( /> ); + +export const LicenceReadyToSend = () => ( + + {} }, + { label: localized('sendToReview'), onPress: () => {} }, + ]} + /> + +); diff --git a/packages/components/src/Partner/DocumentRequirementCard.js b/packages/components/src/Partner/DocumentRequirementCard.js index 683231a8..7bb0b3fe 100644 --- a/packages/components/src/Partner/DocumentRequirementCard.js +++ b/packages/components/src/Partner/DocumentRequirementCard.js @@ -10,16 +10,23 @@ import { requirementTitle, ruleText } from './viewModel'; * a Paper `Card` composed the way Paper composes one, with no style of its own: * - the title is the composed rule's name for the partner's market, else the catalogue's (`requirementTitle`); * - `subtitle` is what the host says of it (its vehicle and where it stands, in the host's words); - * - `cover` is the URI of a photo the partner has just taken and not sent yet (the front of a two-sided document); + * - `covers` are the URIs of the photos the partner has taken and not sent yet, in order (the front, then the back); * - the content is `note` (what to do now) and the rule's plain explanation for the market; * - `actions` are `{ label, onPress, isDisabled?, testID? }`, Paper `Button`s straight inside `Card.Actions`, which * gives them their modes (the first outlined, the next contained). * Without `actions` (the console showing what the partner sees) the card only reads. * - * @param {{item: object, subtitle?: ?string, cover?: ?string, note?: ?string, + * @param {{item: object, subtitle?: ?string, covers?: Array, note?: ?string, * actions?: Array<{label: string, onPress: () => void, isDisabled?: boolean, testID?: string}>, testID?: string}} props */ -const DocumentRequirementCard = ({ item, subtitle, cover, note, actions = [], testID = 'document-requirement' }) => { +const DocumentRequirementCard = ({ + item, + subtitle, + covers = [], + note, + actions = [], + testID = 'document-requirement', +}) => { const { spacing } = useTheme(); const explanation = ruleText(item.explanation); return ( @@ -31,7 +38,9 @@ const DocumentRequirementCard = ({ item, subtitle, cover, note, actions = [], te subtitleNumberOfLines={2} left={(props) => } /> - {cover ? : null} + {covers.map((uri, index) => ( + + ))} {note || explanation ? ( {note ? ( diff --git a/packages/components/src/Partner/__tests__/documentRequirement.test.js b/packages/components/src/Partner/__tests__/documentRequirement.test.js index a35dd388..e63f2249 100644 --- a/packages/components/src/Partner/__tests__/documentRequirement.test.js +++ b/packages/components/src/Partner/__tests__/documentRequirement.test.js @@ -161,7 +161,7 @@ describe('DocumentRequirementCard', () => { 'Black Honda Accord · 123456', 'The current Massachusetts safety inspection.', ]); - expect(hasTestID(tree, 'document-requirement-cover')).toBe(false); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(false); expect(tree.root.findAll((node) => typeof node.props.onPress === 'function')).toHaveLength(0); }); @@ -170,12 +170,12 @@ describe('DocumentRequirementCard', () => { const tree = render( ); - expect(hasTestID(tree, 'document-requirement-cover')).toBe(true); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); expect(textsOf(tree)).toContain('Now take a photo of the back of your licence.'); press(tree, 'cancel'); expect(onPress).toHaveBeenCalledTimes(1); @@ -194,41 +194,57 @@ describe('DocumentVersionList', () => { }); describe('DocumentCaptureCard', () => { - it('takes one photo of a one-page document and hands it over at once', () => { + it('takes one photo of a one-page document, shows it, and sends it only on «Send to review»', () => { const onCapture = jest.fn(); const tree = render(); expect(textsOf(tree)).toEqual(expect.arrayContaining(['Upload a PDF', 'Add'])); press(tree, 'document-requirement-add'); expect(mockPicker.shown).toBe(1); + take({ uri: 'file:///page.jpg' }); + expect(onCapture).not.toHaveBeenCalled(); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); + expect(textsOf(tree)).toEqual(expect.arrayContaining(['Cancel', 'Send to review'])); + expect(textsOf(tree)).not.toContain('Upload a PDF'); + + press(tree, 'document-requirement-send'); expect(onCapture).toHaveBeenCalledWith([{ uri: 'file:///page.jpg' }]); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(false); }); - it('keeps the front of a two-sided document, shows it, then hands over the front and the back', () => { + it('keeps the front of a two-sided document, then the back, and sends both only on «Send to review»', () => { const onCapture = jest.fn(); const tree = render(); expect(textsOf(tree)).toContain('Add the front'); take({ uri: 'file:///front.jpg' }); - expect(onCapture).not.toHaveBeenCalled(); - expect(hasTestID(tree, 'document-requirement-cover')).toBe(true); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); expect(textsOf(tree)).toEqual( expect.arrayContaining(['Now take a photo of the back of your licence.', 'Cancel', 'Add the back']) ); expect(textsOf(tree)).not.toContain('Upload a PDF'); take({ uri: 'file:///back.jpg' }); + expect(onCapture).not.toHaveBeenCalled(); + expect(hasTestID(tree, 'document-requirement-cover-1')).toBe(true); + expect(textsOf(tree)).toEqual(expect.arrayContaining(['Cancel', 'Send to review'])); + expect(textsOf(tree)).not.toContain('Now take a photo of the back of your licence.'); + + press(tree, 'document-requirement-send'); expect(onCapture).toHaveBeenCalledWith([{ uri: 'file:///front.jpg' }, { uri: 'file:///back.jpg' }]); - expect(hasTestID(tree, 'document-requirement-cover')).toBe(false); expect(textsOf(tree)).toContain('Add the front'); }); - it('drops the front on «Cancel»', () => { + it('drops what was taken on «Cancel», before the back or with both sides', () => { const onCapture = jest.fn(); const tree = render(); take({ uri: 'file:///front.jpg' }); press(tree, 'document-requirement-cancel'); - expect(hasTestID(tree, 'document-requirement-cover')).toBe(false); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(false); + take({ uri: 'file:///front.jpg' }); + take({ uri: 'file:///back.jpg' }); + press(tree, 'document-requirement-cancel'); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(false); expect(textsOf(tree)).toContain('Add the front'); expect(onCapture).not.toHaveBeenCalled(); }); @@ -249,11 +265,13 @@ describe('DocumentCaptureCard', () => { expect(hasTestID(noPdf, 'document-requirement-pdf')).toBe(false); }); - it('disables sending while the host sends', () => { + it('disables adding, the PDF and sending while the host sends', () => { const tree = render( ); expect(buttonOf(tree, 'document-requirement-add').props.disabled).toBe(true); expect(buttonOf(tree, 'document-requirement-pdf').props.disabled).toBe(true); + take({ uri: 'file:///page.jpg' }); + expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(true); }); }); From 24d41ebc21b685c98738e6e4d57aa6fd71e379b8 Mon Sep 17 00:00:00 2001 From: Joely Date: Wed, 4 Nov 2026 01:02:21 -0500 Subject: [PATCH 03/16] =?UTF-8?q?Revert=20=C2=ABcomponents=200.5.4=20(unpu?= =?UTF-8?q?blished):=20taking=20a=20document's=20photo=20sends=20nothing;?= =?UTF-8?q?=20=C2=ABSend=20to=20review=C2=BB=20does=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Owner, 2026-11-04: picking the photo from the device sends it, as before (the licence sends after its back). This reverts commit 403c1b0. Co-Authored-By: Claude Opus 5.5 --- PROJECT.md | 9 ++-- .../src/Partner/DocumentCaptureCard.js | 41 ++++++++----------- .../Partner/DocumentRequirement.stories.js | 20 ++------- .../src/Partner/DocumentRequirementCard.js | 17 ++------ .../__tests__/documentRequirement.test.js | 40 +++++------------- 5 files changed, 38 insertions(+), 89 deletions(-) diff --git a/PROJECT.md b/PROJECT.md index 095a2c43..f7982c71 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -217,16 +217,15 @@ themed through `useTheme()` so a host's theme applies: document type of its own: - `Partner/DocumentRequirementCard` (portable) — a Paper `Card` composed as Paper composes one: the title is `requirementTitle(item)` (the rule's name for the market, else the catalogue's), `subtitle` is the host's, - then `covers` (the photos taken and not sent, in order), `note` and the rule's explanation, and `actions` + then `cover` (a photo taken and not sent), `note` and the rule's explanation, and `actions` (`{ label, onPress, isDisabled?, testID? }`) as Paper `Button`s straight inside `Card.Actions`, which gives them their modes. Without `actions` it only reads (the console). - `Partner/DocumentVersionList` (portable) — `item.versions` as `ListRow`s from `documentVersionRows`; they open nothing, so no chevron. - `Partner/DocumentCaptureCard` (barrel only: the picker is native) — the card with the way to send it, as - `item.capture` says (`pages` 1, or 2 = the front then the back; `pdf`). Taking a photo sends nothing: the pages - show as covers, and «Send to review» (the card's last, contained action) hands them to `onCapture(photos)` in - order, «Cancel» drops them. «Subir un PDF» shows only with `capture.pdf` and an `onUploadPdf` (none while the - console acts as the partner). + `item.capture` says (`pages` 1, or 2 = the front then the back; `pdf`): the front waits as the cover until the + back is taken, `onCapture(photos)` gets the pages in order, and «Subir un PDF» shows only with `capture.pdf` + and an `onUploadPdf` (none while the console acts as the partner). - `ImagePicker.Avatar` `variant="sheet"` renders no control of its own; the caller opens the sheet with the ref's `show()`, so its own Paper `Button` can sit inside a `Card.Actions`. `avatar` and `button` are as before. - Their fixed words (`documentAddFront`, `documentAddBack`, `documentAddBackPrompt`, `documentUploadPdf`, diff --git a/packages/components/src/Partner/DocumentCaptureCard.js b/packages/components/src/Partner/DocumentCaptureCard.js index 5dddd7e7..437bbce9 100644 --- a/packages/components/src/Partner/DocumentCaptureCard.js +++ b/packages/components/src/Partner/DocumentCaptureCard.js @@ -8,8 +8,7 @@ import DocumentRequirementCard from './DocumentRequirementCard'; * Contract request #117: a document requirement's card with the way to send it, as the server says one version of it * is taken (`item.capture`, K-32): one photo, or the front and then the back (§9.8.1 step 1), and one PDF from the * phone's browser when `capture.pdf` and the host can open the link (#66; never while the console acts as the - * partner). Taking a photo sends nothing (owner, 2026-11-03): the pages taken show as the card's covers, and the - * partner sends them with the card's last action, «Send to review», or drops them with «Cancel»; then + * partner). The front waits here, shown as the card's cover with what to do next, until the back is taken; then * `onCapture(photos)` gets the pages in order (the picker's assets) and the host sends them. The photo sheet is the * library's picker, opened by the card's own button (`variant="sheet"`). Not portable: the picker is native. * @@ -25,34 +24,26 @@ const DocumentCaptureCard = ({ testID = 'document-requirement', }) => { const pickerRef = useRef(); - const [pages, setPages] = useState([]); - const pageCount = item.capture?.pages === 2 ? 2 : 1; - const twoSided = pageCount === 2; - const complete = pages.length === pageCount; + const [front, setFront] = useState(null); + const twoSided = item.capture?.pages === 2; - const take = (photo) => setPages((taken) => (taken.length < pageCount ? [...taken, photo] : taken)); - const cancel = () => setPages([]); - const send = () => { - const photos = pages; - setPages([]); - onCapture(photos); + const take = (photo) => { + if (twoSided && !front) { + setFront(photo); + return; + } + setFront(null); + onCapture(front ? [front, photo] : [photo]); }; let addLabel = localized('add'); - if (twoSided) addLabel = localized(pages.length === 0 ? 'documentAddFront' : 'documentAddBack'); + if (twoSided) addLabel = localized(front ? 'documentAddBack' : 'documentAddFront'); const add = { label: addLabel, onPress: () => pickerRef.current?.show(), isDisabled, testID: `${testID}-add` }; - const cancelAction = { label: localized('cancel'), onPress: cancel, testID: `${testID}-cancel` }; - // MD3: a card's actions close it, the main one last. Card.Actions makes the first button outlined and the next - // contained, so what moves the partner forward (add the next side, or send) is the last. + // Card.Actions makes the first button outlined and the next contained: the way to send is the last. let actions = [add]; - if (complete) { - actions = [ - cancelAction, - { label: localized('sendToReview'), onPress: send, isDisabled, testID: `${testID}-send` }, - ]; - } else if (pages.length > 0) { - actions = [cancelAction, add]; + if (front) { + actions = [{ label: localized('cancel'), onPress: () => setFront(null), testID: `${testID}-cancel` }, add]; } else if (item.capture?.pdf && onUploadPdf) { actions = [ { label: localized('documentUploadPdf'), onPress: onUploadPdf, isDisabled, testID: `${testID}-pdf` }, @@ -65,8 +56,8 @@ const DocumentCaptureCard = ({ page.uri)} - note={twoSided && pages.length === 1 ? localized('documentAddBackPrompt') : null} + cover={front?.uri ?? null} + note={front ? localized('documentAddBackPrompt') : null} actions={actions} testID={testID} /> diff --git a/packages/components/src/Partner/DocumentRequirement.stories.js b/packages/components/src/Partner/DocumentRequirement.stories.js index 11bfa281..4981101f 100644 --- a/packages/components/src/Partner/DocumentRequirement.stories.js +++ b/packages/components/src/Partner/DocumentRequirement.stories.js @@ -199,14 +199,13 @@ export const ReadOnlyInTheConsole = () => ( ); -// What the partner has taken shows on the card before anything is sent (owner, 2026-11-03): the front waiting for the -// back, then both sides with «Send to review». The covers are the partner's own photos, which a story does not have: -// empty ones show where they go. +// The front of a licence taken and waiting for the back. The cover is the partner's own photo, which a story does +// not have: an empty one shows where it goes. export const LicenceFrontTaken = () => ( {} }, @@ -215,16 +214,3 @@ export const LicenceFrontTaken = () => ( /> ); - -export const LicenceReadyToSend = () => ( - - {} }, - { label: localized('sendToReview'), onPress: () => {} }, - ]} - /> - -); diff --git a/packages/components/src/Partner/DocumentRequirementCard.js b/packages/components/src/Partner/DocumentRequirementCard.js index 7bb0b3fe..683231a8 100644 --- a/packages/components/src/Partner/DocumentRequirementCard.js +++ b/packages/components/src/Partner/DocumentRequirementCard.js @@ -10,23 +10,16 @@ import { requirementTitle, ruleText } from './viewModel'; * a Paper `Card` composed the way Paper composes one, with no style of its own: * - the title is the composed rule's name for the partner's market, else the catalogue's (`requirementTitle`); * - `subtitle` is what the host says of it (its vehicle and where it stands, in the host's words); - * - `covers` are the URIs of the photos the partner has taken and not sent yet, in order (the front, then the back); + * - `cover` is the URI of a photo the partner has just taken and not sent yet (the front of a two-sided document); * - the content is `note` (what to do now) and the rule's plain explanation for the market; * - `actions` are `{ label, onPress, isDisabled?, testID? }`, Paper `Button`s straight inside `Card.Actions`, which * gives them their modes (the first outlined, the next contained). * Without `actions` (the console showing what the partner sees) the card only reads. * - * @param {{item: object, subtitle?: ?string, covers?: Array, note?: ?string, + * @param {{item: object, subtitle?: ?string, cover?: ?string, note?: ?string, * actions?: Array<{label: string, onPress: () => void, isDisabled?: boolean, testID?: string}>, testID?: string}} props */ -const DocumentRequirementCard = ({ - item, - subtitle, - covers = [], - note, - actions = [], - testID = 'document-requirement', -}) => { +const DocumentRequirementCard = ({ item, subtitle, cover, note, actions = [], testID = 'document-requirement' }) => { const { spacing } = useTheme(); const explanation = ruleText(item.explanation); return ( @@ -38,9 +31,7 @@ const DocumentRequirementCard = ({ subtitleNumberOfLines={2} left={(props) => } /> - {covers.map((uri, index) => ( - - ))} + {cover ? : null} {note || explanation ? ( {note ? ( diff --git a/packages/components/src/Partner/__tests__/documentRequirement.test.js b/packages/components/src/Partner/__tests__/documentRequirement.test.js index e63f2249..a35dd388 100644 --- a/packages/components/src/Partner/__tests__/documentRequirement.test.js +++ b/packages/components/src/Partner/__tests__/documentRequirement.test.js @@ -161,7 +161,7 @@ describe('DocumentRequirementCard', () => { 'Black Honda Accord · 123456', 'The current Massachusetts safety inspection.', ]); - expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(false); + expect(hasTestID(tree, 'document-requirement-cover')).toBe(false); expect(tree.root.findAll((node) => typeof node.props.onPress === 'function')).toHaveLength(0); }); @@ -170,12 +170,12 @@ describe('DocumentRequirementCard', () => { const tree = render( ); - expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); + expect(hasTestID(tree, 'document-requirement-cover')).toBe(true); expect(textsOf(tree)).toContain('Now take a photo of the back of your licence.'); press(tree, 'cancel'); expect(onPress).toHaveBeenCalledTimes(1); @@ -194,57 +194,41 @@ describe('DocumentVersionList', () => { }); describe('DocumentCaptureCard', () => { - it('takes one photo of a one-page document, shows it, and sends it only on «Send to review»', () => { + it('takes one photo of a one-page document and hands it over at once', () => { const onCapture = jest.fn(); const tree = render(); expect(textsOf(tree)).toEqual(expect.arrayContaining(['Upload a PDF', 'Add'])); press(tree, 'document-requirement-add'); expect(mockPicker.shown).toBe(1); - take({ uri: 'file:///page.jpg' }); - expect(onCapture).not.toHaveBeenCalled(); - expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); - expect(textsOf(tree)).toEqual(expect.arrayContaining(['Cancel', 'Send to review'])); - expect(textsOf(tree)).not.toContain('Upload a PDF'); - - press(tree, 'document-requirement-send'); expect(onCapture).toHaveBeenCalledWith([{ uri: 'file:///page.jpg' }]); - expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(false); }); - it('keeps the front of a two-sided document, then the back, and sends both only on «Send to review»', () => { + it('keeps the front of a two-sided document, shows it, then hands over the front and the back', () => { const onCapture = jest.fn(); const tree = render(); expect(textsOf(tree)).toContain('Add the front'); take({ uri: 'file:///front.jpg' }); - expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); + expect(onCapture).not.toHaveBeenCalled(); + expect(hasTestID(tree, 'document-requirement-cover')).toBe(true); expect(textsOf(tree)).toEqual( expect.arrayContaining(['Now take a photo of the back of your licence.', 'Cancel', 'Add the back']) ); expect(textsOf(tree)).not.toContain('Upload a PDF'); take({ uri: 'file:///back.jpg' }); - expect(onCapture).not.toHaveBeenCalled(); - expect(hasTestID(tree, 'document-requirement-cover-1')).toBe(true); - expect(textsOf(tree)).toEqual(expect.arrayContaining(['Cancel', 'Send to review'])); - expect(textsOf(tree)).not.toContain('Now take a photo of the back of your licence.'); - - press(tree, 'document-requirement-send'); expect(onCapture).toHaveBeenCalledWith([{ uri: 'file:///front.jpg' }, { uri: 'file:///back.jpg' }]); + expect(hasTestID(tree, 'document-requirement-cover')).toBe(false); expect(textsOf(tree)).toContain('Add the front'); }); - it('drops what was taken on «Cancel», before the back or with both sides', () => { + it('drops the front on «Cancel»', () => { const onCapture = jest.fn(); const tree = render(); take({ uri: 'file:///front.jpg' }); press(tree, 'document-requirement-cancel'); - expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(false); - take({ uri: 'file:///front.jpg' }); - take({ uri: 'file:///back.jpg' }); - press(tree, 'document-requirement-cancel'); - expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(false); + expect(hasTestID(tree, 'document-requirement-cover')).toBe(false); expect(textsOf(tree)).toContain('Add the front'); expect(onCapture).not.toHaveBeenCalled(); }); @@ -265,13 +249,11 @@ describe('DocumentCaptureCard', () => { expect(hasTestID(noPdf, 'document-requirement-pdf')).toBe(false); }); - it('disables adding, the PDF and sending while the host sends', () => { + it('disables sending while the host sends', () => { const tree = render( ); expect(buttonOf(tree, 'document-requirement-add').props.disabled).toBe(true); expect(buttonOf(tree, 'document-requirement-pdf').props.disabled).toBe(true); - take({ uri: 'file:///page.jpg' }); - expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(true); }); }); From 2df534d29486a37bd257e90647c985e9b65e6659 Mon Sep 17 00:00:00 2001 From: Joely Date: Wed, 4 Nov 2026 01:04:44 -0500 Subject: [PATCH 04/16] components 0.5.4 (unpublished): the document card takes photos only, no PDF (owner, 2026-11-04) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DocumentCaptureCard drops onUploadPdf and its «Upload a PDF» action, the ActingAsNoPdf story goes, and documentUploadPdf leaves the catalogues (the card was its only reader here). Co-Authored-By: Claude Opus 5.5 --- PROJECT.md | 12 ++++---- .../src/Localization/Translations/en.json | 1 - .../src/Localization/Translations/es.json | 1 - .../src/Partner/DocumentCaptureCard.js | 28 +++++------------ .../Partner/DocumentRequirement.stories.js | 12 ++------ .../__tests__/documentRequirement.test.js | 30 ++++--------------- 6 files changed, 22 insertions(+), 62 deletions(-) diff --git a/PROJECT.md b/PROJECT.md index f7982c71..1659efce 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -223,14 +223,14 @@ themed through `useTheme()` so a host's theme applies: - `Partner/DocumentVersionList` (portable) — `item.versions` as `ListRow`s from `documentVersionRows`; they open nothing, so no chevron. - `Partner/DocumentCaptureCard` (barrel only: the picker is native) — the card with the way to send it, as - `item.capture` says (`pages` 1, or 2 = the front then the back; `pdf`): the front waits as the cover until the - back is taken, `onCapture(photos)` gets the pages in order, and «Subir un PDF» shows only with `capture.pdf` - and an `onUploadPdf` (none while the console acts as the partner). + `item.capture` says (`pages` 1, or 2 = the front then the back): picking the photo sends it; the front waits + as the cover until the back is taken, then `onCapture(photos)` gets the pages in order. Photos only: it offers + no PDF (owner, 2026-11-04). - `ImagePicker.Avatar` `variant="sheet"` renders no control of its own; the caller opens the sheet with the ref's `show()`, so its own Paper `Button` can sit inside a `Card.Actions`. `avatar` and `button` are as before. - - Their fixed words (`documentAddFront`, `documentAddBack`, `documentAddBackPrompt`, `documentUploadPdf`, - `documentSuperseded`) live in `Translations/*.json`; the stories (`Partner/DocumentRequirement.stories.js`) - use the local circuit's real items. + - Their fixed words (`documentAddFront`, `documentAddBack`, `documentAddBackPrompt`, `documentSuperseded`) + live in `Translations/*.json`; the stories (`Partner/DocumentRequirement.stories.js`) use the local + circuit's real items. - `Partner/viewModel.js` (barrel/portable: `PartnerViewModel`, because `statusLabel` is the Order one): the key is the package's `statusLabelKey(group, value)` resolved with `localized`; a value outside the vocabulary, or a key the registered catalogue lacks, renders the raw value. Each kind's group is read diff --git a/packages/components/src/Localization/Translations/en.json b/packages/components/src/Localization/Translations/en.json index 7584fb54..747b0a21 100644 --- a/packages/components/src/Localization/Translations/en.json +++ b/packages/components/src/Localization/Translations/en.json @@ -807,7 +807,6 @@ "documentAddFront": "Add the front", "documentAddBack": "Add the back", "documentAddBackPrompt": "Now take a photo of the back of your licence.", - "documentUploadPdf": "Upload a PDF", "documentSuperseded": "Superseded", "documentExpiryDate": "Expiry date", "documentExpiryInvalid": "Enter a valid future date (MM/DD/YYYY).", diff --git a/packages/components/src/Localization/Translations/es.json b/packages/components/src/Localization/Translations/es.json index 9e53ef64..911b7553 100644 --- a/packages/components/src/Localization/Translations/es.json +++ b/packages/components/src/Localization/Translations/es.json @@ -807,7 +807,6 @@ "documentAddFront": "Añadir el anverso", "documentAddBack": "Añadir el reverso", "documentAddBackPrompt": "Ahora haz una foto del reverso de tu licencia.", - "documentUploadPdf": "Subir un PDF", "documentSuperseded": "Sustituido", "documentExpiryDate": "Fecha de vencimiento", "documentExpiryInvalid": "Ingresa una fecha válida y futura (MM/DD/YYYY).", diff --git a/packages/components/src/Partner/DocumentCaptureCard.js b/packages/components/src/Partner/DocumentCaptureCard.js index 437bbce9..a5c6620a 100644 --- a/packages/components/src/Partner/DocumentCaptureCard.js +++ b/packages/components/src/Partner/DocumentCaptureCard.js @@ -6,23 +6,16 @@ import DocumentRequirementCard from './DocumentRequirementCard'; /** * Contract request #117: a document requirement's card with the way to send it, as the server says one version of it - * is taken (`item.capture`, K-32): one photo, or the front and then the back (§9.8.1 step 1), and one PDF from the - * phone's browser when `capture.pdf` and the host can open the link (#66; never while the console acts as the - * partner). The front waits here, shown as the card's cover with what to do next, until the back is taken; then - * `onCapture(photos)` gets the pages in order (the picker's assets) and the host sends them. The photo sheet is the - * library's picker, opened by the card's own button (`variant="sheet"`). Not portable: the picker is native. + * is taken (`item.capture`, K-32): one photo, or the front and then the back (§9.8.1 step 1). Photos only (owner, + * 2026-11-04): the card offers no PDF. The front waits here, shown as the card's cover with what to do next, until + * the back is taken; then `onCapture(photos)` gets the pages in order (the picker's assets) and the host sends them. + * The photo sheet is the library's picker, opened by the card's own button (`variant="sheet"`). Not portable: the + * picker is native. * - * @param {{item: object, subtitle?: ?string, onCapture: (photos: Array) => void, - * onUploadPdf?: ?(() => void), isDisabled?: boolean, testID?: string}} props + * @param {{item: object, subtitle?: ?string, onCapture: (photos: Array) => void, isDisabled?: boolean, + * testID?: string}} props */ -const DocumentCaptureCard = ({ - item, - subtitle, - onCapture, - onUploadPdf, - isDisabled = false, - testID = 'document-requirement', -}) => { +const DocumentCaptureCard = ({ item, subtitle, onCapture, isDisabled = false, testID = 'document-requirement' }) => { const pickerRef = useRef(); const [front, setFront] = useState(null); const twoSided = item.capture?.pages === 2; @@ -44,11 +37,6 @@ const DocumentCaptureCard = ({ let actions = [add]; if (front) { actions = [{ label: localized('cancel'), onPress: () => setFront(null), testID: `${testID}-cancel` }, add]; - } else if (item.capture?.pdf && onUploadPdf) { - actions = [ - { label: localized('documentUploadPdf'), onPress: onUploadPdf, isDisabled, testID: `${testID}-pdf` }, - add, - ]; } return ( diff --git a/packages/components/src/Partner/DocumentRequirement.stories.js b/packages/components/src/Partner/DocumentRequirement.stories.js index 4981101f..258b0022 100644 --- a/packages/components/src/Partner/DocumentRequirement.stories.js +++ b/packages/components/src/Partner/DocumentRequirement.stories.js @@ -163,14 +163,9 @@ const subtitleOf = (item) => const pane = { padding: MD3LightTheme.spacing.x4, gap: MD3LightTheme.spacing.x2 }; // The app's document screen: the card with its capture, then the versions. -const Screen = ({ item, canUploadPdf = true }) => ( +const Screen = ({ item }) => ( - {}} - onUploadPdf={canUploadPdf ? () => {} : null} - /> + {}} /> ); @@ -185,9 +180,6 @@ export const InsuranceJustSent = () => ; export const MassachusettsOnlyCertificate = () => ; -// While the console acts as the partner: no PDF link (the hook gives none). -export const ActingAsNoPdf = () => ; - // What the console shows of it («Así lo ve el socio»): the card reads, nothing is sent. export const ReadOnlyInTheConsole = () => ( diff --git a/packages/components/src/Partner/__tests__/documentRequirement.test.js b/packages/components/src/Partner/__tests__/documentRequirement.test.js index a35dd388..20ed8fc6 100644 --- a/packages/components/src/Partner/__tests__/documentRequirement.test.js +++ b/packages/components/src/Partner/__tests__/documentRequirement.test.js @@ -196,8 +196,10 @@ describe('DocumentVersionList', () => { describe('DocumentCaptureCard', () => { it('takes one photo of a one-page document and hands it over at once', () => { const onCapture = jest.fn(); - const tree = render(); - expect(textsOf(tree)).toEqual(expect.arrayContaining(['Upload a PDF', 'Add'])); + const tree = render(); + expect(textsOf(tree)).toContain('Add'); + // Photos only (owner, 2026-11-04): no PDF, even where the server takes one. + expect(textsOf(tree)).not.toContain('Upload a PDF'); press(tree, 'document-requirement-add'); expect(mockPicker.shown).toBe(1); take({ uri: 'file:///page.jpg' }); @@ -206,7 +208,7 @@ describe('DocumentCaptureCard', () => { it('keeps the front of a two-sided document, shows it, then hands over the front and the back', () => { const onCapture = jest.fn(); - const tree = render(); + const tree = render(); expect(textsOf(tree)).toContain('Add the front'); take({ uri: 'file:///front.jpg' }); @@ -215,7 +217,6 @@ describe('DocumentCaptureCard', () => { expect(textsOf(tree)).toEqual( expect.arrayContaining(['Now take a photo of the back of your licence.', 'Cancel', 'Add the back']) ); - expect(textsOf(tree)).not.toContain('Upload a PDF'); take({ uri: 'file:///back.jpg' }); expect(onCapture).toHaveBeenCalledWith([{ uri: 'file:///front.jpg' }, { uri: 'file:///back.jpg' }]); @@ -233,27 +234,8 @@ describe('DocumentCaptureCard', () => { expect(onCapture).not.toHaveBeenCalled(); }); - it('offers the PDF only where the server takes one and the host can open the link', () => { - const withPdf = render(); - expect(hasTestID(withPdf, 'document-requirement-pdf')).toBe(true); - // Acting as the partner, the host gives no link. - const actingAs = render(); - expect(hasTestID(actingAs, 'document-requirement-pdf')).toBe(false); - const noPdf = render( - - ); - expect(hasTestID(noPdf, 'document-requirement-pdf')).toBe(false); - }); - it('disables sending while the host sends', () => { - const tree = render( - - ); + const tree = render(); expect(buttonOf(tree, 'document-requirement-add').props.disabled).toBe(true); - expect(buttonOf(tree, 'document-requirement-pdf').props.disabled).toBe(true); }); }); From 7707357d9266218cf6187c1f7dba7455ffd95e44 Mon Sep 17 00:00:00 2001 From: Joely Date: Wed, 4 Nov 2026 01:36:19 -0500 Subject: [PATCH 05/16] =?UTF-8?q?components=200.5.4=20(unpublished):=20?= =?UTF-8?q?=C2=ABSend=20to=20review=C2=BB=20sends=20a=20document;=20the=20?= =?UTF-8?q?photo=20button=20stays=20(owner,=202026-11-04)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DocumentCaptureCard: taking a photo sends nothing; the pages show as the card's covers (DocumentRequirementCard `covers`, back from 403c1b0). Its actions are always the photo button (outlined) and «Send to review» (contained, last per MD3, disabled until every page is taken). A photo taken once every page is there starts the document again, which is how a wrong one is replaced. No «Cancel», no PDF. Co-Authored-By: Claude Opus 5.5 --- PROJECT.md | 9 +-- .../src/Partner/DocumentCaptureCard.js | 50 ++++++++------- .../Partner/DocumentRequirement.stories.js | 22 +++++-- .../src/Partner/DocumentRequirementCard.js | 17 ++++-- .../__tests__/documentRequirement.test.js | 61 +++++++++++++------ 5 files changed, 108 insertions(+), 51 deletions(-) diff --git a/PROJECT.md b/PROJECT.md index 1659efce..1b9472e8 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -217,15 +217,16 @@ themed through `useTheme()` so a host's theme applies: document type of its own: - `Partner/DocumentRequirementCard` (portable) — a Paper `Card` composed as Paper composes one: the title is `requirementTitle(item)` (the rule's name for the market, else the catalogue's), `subtitle` is the host's, - then `cover` (a photo taken and not sent), `note` and the rule's explanation, and `actions` + then `covers` (the photos taken and not sent, in order), `note` and the rule's explanation, and `actions` (`{ label, onPress, isDisabled?, testID? }`) as Paper `Button`s straight inside `Card.Actions`, which gives them their modes. Without `actions` it only reads (the console). - `Partner/DocumentVersionList` (portable) — `item.versions` as `ListRow`s from `documentVersionRows`; they open nothing, so no chevron. - `Partner/DocumentCaptureCard` (barrel only: the picker is native) — the card with the way to send it, as - `item.capture` says (`pages` 1, or 2 = the front then the back): picking the photo sends it; the front waits - as the cover until the back is taken, then `onCapture(photos)` gets the pages in order. Photos only: it offers - no PDF (owner, 2026-11-04). + `item.capture` says (`pages` 1, or 2 = the front then the back). Taking a photo sends nothing: the pages show + as covers; its first action takes a photo (one taken once every page is there starts again), and the last, + «Send to review», contained and disabled until every page is taken, hands them to `onCapture(photos)` in + order. Photos only: it offers no PDF (owner, 2026-11-04). - `ImagePicker.Avatar` `variant="sheet"` renders no control of its own; the caller opens the sheet with the ref's `show()`, so its own Paper `Button` can sit inside a `Card.Actions`. `avatar` and `button` are as before. - Their fixed words (`documentAddFront`, `documentAddBack`, `documentAddBackPrompt`, `documentSuperseded`) diff --git a/packages/components/src/Partner/DocumentCaptureCard.js b/packages/components/src/Partner/DocumentCaptureCard.js index a5c6620a..0abc3d46 100644 --- a/packages/components/src/Partner/DocumentCaptureCard.js +++ b/packages/components/src/Partner/DocumentCaptureCard.js @@ -7,45 +7,51 @@ import DocumentRequirementCard from './DocumentRequirementCard'; /** * Contract request #117: a document requirement's card with the way to send it, as the server says one version of it * is taken (`item.capture`, K-32): one photo, or the front and then the back (§9.8.1 step 1). Photos only (owner, - * 2026-11-04): the card offers no PDF. The front waits here, shown as the card's cover with what to do next, until - * the back is taken; then `onCapture(photos)` gets the pages in order (the picker's assets) and the host sends them. - * The photo sheet is the library's picker, opened by the card's own button (`variant="sheet"`). Not portable: the - * picker is native. + * 2026-11-04): the card offers no PDF. Taking a photo sends nothing (owner, 2026-11-04): the pages taken show as the + * card's covers, and «Send to review» sends them once every page is there; then `onCapture(photos)` gets them in + * order (the picker's assets) and the host sends them. The photo sheet is the library's picker, opened by the card's + * own button (`variant="sheet"`). Not portable: the picker is native. * * @param {{item: object, subtitle?: ?string, onCapture: (photos: Array) => void, isDisabled?: boolean, * testID?: string}} props */ const DocumentCaptureCard = ({ item, subtitle, onCapture, isDisabled = false, testID = 'document-requirement' }) => { const pickerRef = useRef(); - const [front, setFront] = useState(null); - const twoSided = item.capture?.pages === 2; + const [pages, setPages] = useState([]); + const pageCount = item.capture?.pages === 2 ? 2 : 1; + const twoSided = pageCount === 2; + const complete = pages.length === pageCount; - const take = (photo) => { - if (twoSided && !front) { - setFront(photo); - return; - } - setFront(null); - onCapture(front ? [front, photo] : [photo]); + // A photo taken once every page is there starts the document again: that is how a wrong one is replaced. + const take = (photo) => setPages((taken) => (taken.length < pageCount ? [...taken, photo] : [photo])); + const send = () => { + const photos = pages; + setPages([]); + onCapture(photos); }; let addLabel = localized('add'); - if (twoSided) addLabel = localized(front ? 'documentAddBack' : 'documentAddFront'); - const add = { label: addLabel, onPress: () => pickerRef.current?.show(), isDisabled, testID: `${testID}-add` }; + if (twoSided) addLabel = localized(pages.length === 1 ? 'documentAddBack' : 'documentAddFront'); - // Card.Actions makes the first button outlined and the next contained: the way to send is the last. - let actions = [add]; - if (front) { - actions = [{ label: localized('cancel'), onPress: () => setFront(null), testID: `${testID}-cancel` }, add]; - } + // MD3: the way to take a photo stays, and the main action, sending, is last (Card.Actions makes the first button + // outlined and the next contained); it waits, disabled, until every page is taken. + const actions = [ + { label: addLabel, onPress: () => pickerRef.current?.show(), isDisabled, testID: `${testID}-add` }, + { + label: localized('sendToReview'), + onPress: send, + isDisabled: isDisabled || !complete, + testID: `${testID}-send`, + }, + ]; return ( <> page.uri)} + note={twoSided && pages.length === 1 ? localized('documentAddBackPrompt') : null} actions={actions} testID={testID} /> diff --git a/packages/components/src/Partner/DocumentRequirement.stories.js b/packages/components/src/Partner/DocumentRequirement.stories.js index 258b0022..7d8879cd 100644 --- a/packages/components/src/Partner/DocumentRequirement.stories.js +++ b/packages/components/src/Partner/DocumentRequirement.stories.js @@ -191,17 +191,31 @@ export const ReadOnlyInTheConsole = () => ( ); -// The front of a licence taken and waiting for the back. The cover is the partner's own photo, which a story does -// not have: an empty one shows where it goes. +// What the partner has taken shows on the card before anything is sent (owner, 2026-11-04): the front waiting for the +// back, «Send to review» still disabled, then both sides ready to send. The covers are the partner's own photos, which a story does not have: +// empty ones show where they go. export const LicenceFrontTaken = () => ( {} }, { label: localized('documentAddBack'), onPress: () => {} }, + { label: localized('sendToReview'), onPress: () => {}, isDisabled: true }, + ]} + /> + +); + +export const LicenceReadyToSend = () => ( + + {} }, + { label: localized('sendToReview'), onPress: () => {} }, ]} /> diff --git a/packages/components/src/Partner/DocumentRequirementCard.js b/packages/components/src/Partner/DocumentRequirementCard.js index 683231a8..7bb0b3fe 100644 --- a/packages/components/src/Partner/DocumentRequirementCard.js +++ b/packages/components/src/Partner/DocumentRequirementCard.js @@ -10,16 +10,23 @@ import { requirementTitle, ruleText } from './viewModel'; * a Paper `Card` composed the way Paper composes one, with no style of its own: * - the title is the composed rule's name for the partner's market, else the catalogue's (`requirementTitle`); * - `subtitle` is what the host says of it (its vehicle and where it stands, in the host's words); - * - `cover` is the URI of a photo the partner has just taken and not sent yet (the front of a two-sided document); + * - `covers` are the URIs of the photos the partner has taken and not sent yet, in order (the front, then the back); * - the content is `note` (what to do now) and the rule's plain explanation for the market; * - `actions` are `{ label, onPress, isDisabled?, testID? }`, Paper `Button`s straight inside `Card.Actions`, which * gives them their modes (the first outlined, the next contained). * Without `actions` (the console showing what the partner sees) the card only reads. * - * @param {{item: object, subtitle?: ?string, cover?: ?string, note?: ?string, + * @param {{item: object, subtitle?: ?string, covers?: Array, note?: ?string, * actions?: Array<{label: string, onPress: () => void, isDisabled?: boolean, testID?: string}>, testID?: string}} props */ -const DocumentRequirementCard = ({ item, subtitle, cover, note, actions = [], testID = 'document-requirement' }) => { +const DocumentRequirementCard = ({ + item, + subtitle, + covers = [], + note, + actions = [], + testID = 'document-requirement', +}) => { const { spacing } = useTheme(); const explanation = ruleText(item.explanation); return ( @@ -31,7 +38,9 @@ const DocumentRequirementCard = ({ item, subtitle, cover, note, actions = [], te subtitleNumberOfLines={2} left={(props) => } /> - {cover ? : null} + {covers.map((uri, index) => ( + + ))} {note || explanation ? ( {note ? ( diff --git a/packages/components/src/Partner/__tests__/documentRequirement.test.js b/packages/components/src/Partner/__tests__/documentRequirement.test.js index 20ed8fc6..d01e698a 100644 --- a/packages/components/src/Partner/__tests__/documentRequirement.test.js +++ b/packages/components/src/Partner/__tests__/documentRequirement.test.js @@ -161,7 +161,7 @@ describe('DocumentRequirementCard', () => { 'Black Honda Accord · 123456', 'The current Massachusetts safety inspection.', ]); - expect(hasTestID(tree, 'document-requirement-cover')).toBe(false); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(false); expect(tree.root.findAll((node) => typeof node.props.onPress === 'function')).toHaveLength(0); }); @@ -170,12 +170,12 @@ describe('DocumentRequirementCard', () => { const tree = render( ); - expect(hasTestID(tree, 'document-requirement-cover')).toBe(true); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); expect(textsOf(tree)).toContain('Now take a photo of the back of your licence.'); press(tree, 'cancel'); expect(onPress).toHaveBeenCalledTimes(1); @@ -194,48 +194,75 @@ describe('DocumentVersionList', () => { }); describe('DocumentCaptureCard', () => { - it('takes one photo of a one-page document and hands it over at once', () => { + it('takes one photo of a one-page document, shows it, and sends it only on «Send to review»', () => { const onCapture = jest.fn(); const tree = render(); - expect(textsOf(tree)).toContain('Add'); + expect(textsOf(tree)).toEqual(expect.arrayContaining(['Add', 'Send to review'])); // Photos only (owner, 2026-11-04): no PDF, even where the server takes one. expect(textsOf(tree)).not.toContain('Upload a PDF'); + expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(true); press(tree, 'document-requirement-add'); expect(mockPicker.shown).toBe(1); + take({ uri: 'file:///page.jpg' }); + expect(onCapture).not.toHaveBeenCalled(); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); + // The way to take a photo stays. + expect(textsOf(tree)).toEqual(expect.arrayContaining(['Add', 'Send to review'])); + expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(false); + + press(tree, 'document-requirement-send'); expect(onCapture).toHaveBeenCalledWith([{ uri: 'file:///page.jpg' }]); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(false); + expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(true); }); - it('keeps the front of a two-sided document, shows it, then hands over the front and the back', () => { + it('keeps the front of a two-sided document, then the back, and sends both only on «Send to review»', () => { const onCapture = jest.fn(); const tree = render(); expect(textsOf(tree)).toContain('Add the front'); take({ uri: 'file:///front.jpg' }); - expect(onCapture).not.toHaveBeenCalled(); - expect(hasTestID(tree, 'document-requirement-cover')).toBe(true); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); expect(textsOf(tree)).toEqual( - expect.arrayContaining(['Now take a photo of the back of your licence.', 'Cancel', 'Add the back']) + expect.arrayContaining(['Now take a photo of the back of your licence.', 'Add the back']) ); + expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(true); take({ uri: 'file:///back.jpg' }); + expect(onCapture).not.toHaveBeenCalled(); + expect(hasTestID(tree, 'document-requirement-cover-1')).toBe(true); + expect(textsOf(tree)).not.toContain('Now take a photo of the back of your licence.'); + expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(false); + + press(tree, 'document-requirement-send'); expect(onCapture).toHaveBeenCalledWith([{ uri: 'file:///front.jpg' }, { uri: 'file:///back.jpg' }]); - expect(hasTestID(tree, 'document-requirement-cover')).toBe(false); expect(textsOf(tree)).toContain('Add the front'); }); - it('drops the front on «Cancel»', () => { + it('replaces what was taken with a photo taken once every page is there', () => { const onCapture = jest.fn(); - const tree = render(); + const single = render(); + take({ uri: 'file:///wrong.jpg' }); + take({ uri: 'file:///right.jpg' }); + press(single, 'document-requirement-send'); + expect(onCapture).toHaveBeenCalledWith([{ uri: 'file:///right.jpg' }]); + + // The sheet stand-in now hands photos to this card, the last one rendered. + const licence = render(); take({ uri: 'file:///front.jpg' }); - press(tree, 'document-requirement-cancel'); - expect(hasTestID(tree, 'document-requirement-cover')).toBe(false); - expect(textsOf(tree)).toContain('Add the front'); - expect(onCapture).not.toHaveBeenCalled(); + take({ uri: 'file:///back.jpg' }); + expect(textsOf(licence)).toContain('Add the front'); + take({ uri: 'file:///front-again.jpg' }); + expect(hasTestID(licence, 'document-requirement-cover-1')).toBe(false); + expect(textsOf(licence)).toContain('Add the back'); + expect(buttonOf(licence, 'document-requirement-send').props.disabled).toBe(true); }); - it('disables sending while the host sends', () => { + it('disables adding and sending while the host sends', () => { const tree = render(); expect(buttonOf(tree, 'document-requirement-add').props.disabled).toBe(true); + take({ uri: 'file:///page.jpg' }); + expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(true); }); }); From dfe3ee9fafbf75defbd0f5a24a32aacdca7bec5b Mon Sep 17 00:00:00 2001 From: Joely Date: Wed, 4 Nov 2026 02:02:39 -0500 Subject: [PATCH 06/16] components 0.5.4 (unpublished): a document's two sides in a Material 3 carousel (owner, 2026-11-04) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DocumentCovers (new, portable, not exported): one photo is the card's cover; more are a hero carousel, a horizontal ScrollView that snaps item by item (snapToInterval on iOS/Android, pagingEnabled's CSS scroll snap on the web, the one snapping prop react-native-web implements), items spacing.x2 apart and the next peeking spacing.x14: Material's 8 dp and 56 dp (material-components-android carousel). Its width is measured (onLayout), not assumed. DocumentRequirementCard: the photos move into its Card.Content, above the note and the explanation, with the space a cover gets: Card.Content takes its top padding from a Card.Cover or Card.Title just above it, so a carousel beside it would leave the text against the photos. `covers` are now `{ uri, label }`; each photo is an image a screen reader names. DocumentCaptureCard names them «Front»/«Back» (documentFront/documentBack, the console's words) on a two-sided document, else «Document». Co-Authored-By: Claude Opus 5.5 --- PROJECT.md | 12 ++-- .../src/Localization/Translations/en.json | 2 + .../src/Localization/Translations/es.json | 2 + .../src/Partner/DocumentCaptureCard.js | 15 +++-- .../components/src/Partner/DocumentCovers.js | 59 +++++++++++++++++++ .../Partner/DocumentRequirement.stories.js | 9 ++- .../src/Partner/DocumentRequirementCard.js | 33 +++++++---- .../__tests__/documentRequirement.test.js | 42 +++++++++++-- 8 files changed, 145 insertions(+), 29 deletions(-) create mode 100644 packages/components/src/Partner/DocumentCovers.js diff --git a/PROJECT.md b/PROJECT.md index 1b9472e8..990c6020 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -217,9 +217,13 @@ themed through `useTheme()` so a host's theme applies: document type of its own: - `Partner/DocumentRequirementCard` (portable) — a Paper `Card` composed as Paper composes one: the title is `requirementTitle(item)` (the rule's name for the market, else the catalogue's), `subtitle` is the host's, - then `covers` (the photos taken and not sent, in order), `note` and the rule's explanation, and `actions` + then, in its `Card.Content`, `covers` (the photos taken and not sent, in order, each `{ uri, label }` with the + name a screen reader says), `note` and the rule's explanation, and `actions` (`{ label, onPress, isDisabled?, testID? }`) as Paper `Button`s straight inside `Card.Actions`, which gives them their modes. Without `actions` it only reads (the console). + - `Partner/DocumentCovers` (portable, not exported) — the card's photos: one is a `Card.Cover`; more are a + Material 3 hero carousel (a horizontal `ScrollView`: `snapToInterval` on the phone, `pagingEnabled`'s CSS scroll + snap on the web; items `spacing.x2` apart, the next peeking `spacing.x14`, Material's 8 dp and 56 dp). - `Partner/DocumentVersionList` (portable) — `item.versions` as `ListRow`s from `documentVersionRows`; they open nothing, so no chevron. - `Partner/DocumentCaptureCard` (barrel only: the picker is native) — the card with the way to send it, as @@ -229,9 +233,9 @@ themed through `useTheme()` so a host's theme applies: order. Photos only: it offers no PDF (owner, 2026-11-04). - `ImagePicker.Avatar` `variant="sheet"` renders no control of its own; the caller opens the sheet with the ref's `show()`, so its own Paper `Button` can sit inside a `Card.Actions`. `avatar` and `button` are as before. - - Their fixed words (`documentAddFront`, `documentAddBack`, `documentAddBackPrompt`, `documentSuperseded`) - live in `Translations/*.json`; the stories (`Partner/DocumentRequirement.stories.js`) use the local - circuit's real items. + - Their fixed words (`documentAddFront`, `documentAddBack`, `documentAddBackPrompt`, `documentFront`, + `documentBack`, `documentSuperseded`) live in `Translations/*.json`; the stories + (`Partner/DocumentRequirement.stories.js`) use the local circuit's real items. - `Partner/viewModel.js` (barrel/portable: `PartnerViewModel`, because `statusLabel` is the Order one): the key is the package's `statusLabelKey(group, value)` resolved with `localized`; a value outside the vocabulary, or a key the registered catalogue lacks, renders the raw value. Each kind's group is read diff --git a/packages/components/src/Localization/Translations/en.json b/packages/components/src/Localization/Translations/en.json index 747b0a21..04c7dc9a 100644 --- a/packages/components/src/Localization/Translations/en.json +++ b/packages/components/src/Localization/Translations/en.json @@ -807,6 +807,8 @@ "documentAddFront": "Add the front", "documentAddBack": "Add the back", "documentAddBackPrompt": "Now take a photo of the back of your licence.", + "documentFront": "Front", + "documentBack": "Back", "documentSuperseded": "Superseded", "documentExpiryDate": "Expiry date", "documentExpiryInvalid": "Enter a valid future date (MM/DD/YYYY).", diff --git a/packages/components/src/Localization/Translations/es.json b/packages/components/src/Localization/Translations/es.json index 911b7553..481cb6fc 100644 --- a/packages/components/src/Localization/Translations/es.json +++ b/packages/components/src/Localization/Translations/es.json @@ -807,6 +807,8 @@ "documentAddFront": "Añadir el anverso", "documentAddBack": "Añadir el reverso", "documentAddBackPrompt": "Ahora haz una foto del reverso de tu licencia.", + "documentFront": "Anverso", + "documentBack": "Reverso", "documentSuperseded": "Sustituido", "documentExpiryDate": "Fecha de vencimiento", "documentExpiryInvalid": "Ingresa una fecha válida y futura (MM/DD/YYYY).", diff --git a/packages/components/src/Partner/DocumentCaptureCard.js b/packages/components/src/Partner/DocumentCaptureCard.js index 0abc3d46..e96cc860 100644 --- a/packages/components/src/Partner/DocumentCaptureCard.js +++ b/packages/components/src/Partner/DocumentCaptureCard.js @@ -8,9 +8,9 @@ import DocumentRequirementCard from './DocumentRequirementCard'; * Contract request #117: a document requirement's card with the way to send it, as the server says one version of it * is taken (`item.capture`, K-32): one photo, or the front and then the back (§9.8.1 step 1). Photos only (owner, * 2026-11-04): the card offers no PDF. Taking a photo sends nothing (owner, 2026-11-04): the pages taken show as the - * card's covers, and «Send to review» sends them once every page is there; then `onCapture(photos)` gets them in - * order (the picker's assets) and the host sends them. The photo sheet is the library's picker, opened by the card's - * own button (`variant="sheet"`). Not portable: the picker is native. + * card's covers (both sides in a carousel, owner 2026-11-04), and «Send to review» sends them once every page is + * there; then `onCapture(photos)` gets them in order (the picker's assets) and the host sends them. The photo sheet is + * the library's picker, opened by the card's own button (`variant="sheet"`). Not portable: the picker is native. * * @param {{item: object, subtitle?: ?string, onCapture: (photos: Array) => void, isDisabled?: boolean, * testID?: string}} props @@ -30,6 +30,13 @@ const DocumentCaptureCard = ({ item, subtitle, onCapture, isDisabled = false, te onCapture(photos); }; + // What a screen reader names each photo: the front and the back of a two-sided document, else the document. + const covers = pages.map((page, index) => { + let label = localized('global.document'); + if (twoSided) label = localized(index === 0 ? 'documentFront' : 'documentBack'); + return { uri: page.uri, label }; + }); + let addLabel = localized('add'); if (twoSided) addLabel = localized(pages.length === 1 ? 'documentAddBack' : 'documentAddFront'); @@ -50,7 +57,7 @@ const DocumentCaptureCard = ({ item, subtitle, onCapture, isDisabled = false, te page.uri)} + covers={covers} note={twoSided && pages.length === 1 ? localized('documentAddBackPrompt') : null} actions={actions} testID={testID} diff --git a/packages/components/src/Partner/DocumentCovers.js b/packages/components/src/Partner/DocumentCovers.js new file mode 100644 index 00000000..07f147a9 --- /dev/null +++ b/packages/components/src/Partner/DocumentCovers.js @@ -0,0 +1,59 @@ +import React, { useState } from 'react'; +import { ScrollView, View } from 'react-native'; + +import { Card, useTheme } from '@jmstechnologiesinc/react-native-paper'; + +/** + * The photos of a document the partner has taken and not sent yet (DocumentRequirementCard `covers`), in order: one is + * the card's cover; more are a Material 3 hero carousel, one large item with the next one peeking. Its measures are + * Material's (material-components-android carousel): it snaps to an item, items stand 8 dp apart, and the item that + * peeks is a small item of at most 56 dp (`m3_carousel_small_item_size_max`), here the theme's `spacing.x2` and + * `spacing.x14`. The large item is what the measured width leaves. + * + * Paper has no carousel, so a horizontal ScrollView snaps item by item: on iOS and Android by `snapToInterval`, which + * overrides `pagingEnabled` there, and on the web by `pagingEnabled`, the one snapping prop react-native-web + * implements (CSS scroll snap). Each photo is an image a screen reader names by its `label`. + * + * @param {{covers: Array<{uri: string, label: string}>, testID: string}} props + */ +const DocumentCovers = ({ covers, testID }) => { + const { spacing } = useTheme(); + const [width, setWidth] = useState(0); + + const coverOf = ({ uri, label }, index, style) => ( + + + + ); + + if (covers.length < 2) return covers.map((cover, index) => coverOf(cover, index)); + + const gap = spacing.x2; + // Until the carousel is measured its items are 0 wide; their height is the cover's, so nothing below moves. + const itemWidth = Math.max(0, width - spacing.x14 - gap); + return ( + setWidth(event.nativeEvent.layout.width)} + pagingEnabled + snapToInterval={itemWidth + gap} + snapToAlignment="start" + decelerationRate="fast" + disableIntervalMomentum + showsHorizontalScrollIndicator={false} + contentContainerStyle={{ gap }} + testID={`${testID}-covers`} + > + {covers.map((cover, index) => coverOf(cover, index, { width: itemWidth }))} + + ); +}; + +export default DocumentCovers; diff --git a/packages/components/src/Partner/DocumentRequirement.stories.js b/packages/components/src/Partner/DocumentRequirement.stories.js index 7d8879cd..af231775 100644 --- a/packages/components/src/Partner/DocumentRequirement.stories.js +++ b/packages/components/src/Partner/DocumentRequirement.stories.js @@ -192,13 +192,13 @@ export const ReadOnlyInTheConsole = () => ( ); // What the partner has taken shows on the card before anything is sent (owner, 2026-11-04): the front waiting for the -// back, «Send to review» still disabled, then both sides ready to send. The covers are the partner's own photos, which a story does not have: +// back, «Send to review» still disabled, then both sides ready to send, in a carousel. The covers are the partner's own photos, which a story does not have: // empty ones show where they go. export const LicenceFrontTaken = () => ( {} }, @@ -212,7 +212,10 @@ export const LicenceReadyToSend = () => ( {} }, { label: localized('sendToReview'), onPress: () => {} }, diff --git a/packages/components/src/Partner/DocumentRequirementCard.js b/packages/components/src/Partner/DocumentRequirementCard.js index 7bb0b3fe..58fa8110 100644 --- a/packages/components/src/Partner/DocumentRequirementCard.js +++ b/packages/components/src/Partner/DocumentRequirementCard.js @@ -3,6 +3,7 @@ import React from 'react'; import { MATERIAL_ICONS } from '@jmstechnologiesinc/commons'; import { Avatar, Button, Card, Text, useTheme } from '@jmstechnologiesinc/react-native-paper'; +import DocumentCovers from './DocumentCovers'; import { requirementTitle, ruleText } from './viewModel'; /** @@ -10,13 +11,16 @@ import { requirementTitle, ruleText } from './viewModel'; * a Paper `Card` composed the way Paper composes one, with no style of its own: * - the title is the composed rule's name for the partner's market, else the catalogue's (`requirementTitle`); * - `subtitle` is what the host says of it (its vehicle and where it stands, in the host's words); - * - `covers` are the URIs of the photos the partner has taken and not sent yet, in order (the front, then the back); - * - the content is `note` (what to do now) and the rule's plain explanation for the market; + * - the content is `covers`, the photos the partner has taken and not sent yet, in order (the front, then the back), + * each with the `label` a screen reader names it by (one is the cover, more a carousel: DocumentCovers), then + * `note` (what to do now) and the rule's plain explanation for the market. The photos sit in the Card.Content, not + * beside it: Card.Content takes its top padding from a Card.Cover or Card.Title just above it, so one carousel + * between them would leave the text against the photos; * - `actions` are `{ label, onPress, isDisabled?, testID? }`, Paper `Button`s straight inside `Card.Actions`, which * gives them their modes (the first outlined, the next contained). * Without `actions` (the console showing what the partner sees) the card only reads. * - * @param {{item: object, subtitle?: ?string, covers?: Array, note?: ?string, + * @param {{item: object, subtitle?: ?string, covers?: Array<{uri: string, label: string}>, note?: ?string, * actions?: Array<{label: string, onPress: () => void, isDisabled?: boolean, testID?: string}>, testID?: string}} props */ const DocumentRequirementCard = ({ @@ -29,6 +33,10 @@ const DocumentRequirementCard = ({ }) => { const { spacing } = useTheme(); const explanation = ruleText(item.explanation); + const hasCovers = covers.length > 0; + let explanationSpacing; + if (note) explanationSpacing = { marginTop: spacing.x2 }; + else if (hasCovers) explanationSpacing = { marginTop: spacing.x4 }; return ( } /> - {covers.map((uri, index) => ( - - ))} - {note || explanation ? ( + {hasCovers || note || explanation ? ( + {hasCovers ? : null} + {/* After the photos, the space Card.Content puts after a cover; between texts, the note's. */} {note ? ( - + {note} ) : null} {explanation ? ( - + {explanation} ) : null} diff --git a/packages/components/src/Partner/__tests__/documentRequirement.test.js b/packages/components/src/Partner/__tests__/documentRequirement.test.js index d01e698a..6c6a9ef8 100644 --- a/packages/components/src/Partner/__tests__/documentRequirement.test.js +++ b/packages/components/src/Partner/__tests__/documentRequirement.test.js @@ -67,6 +67,7 @@ const textsOf = (tree) => const buttonOf = (tree, testID) => tree.root.findAll((node) => node.props.testID === testID && typeof node.props.onPress === 'function')[0]; const hasTestID = (tree, testID) => tree.root.findAll((node) => node.props.testID === testID).length > 0; +const propsOf = (tree, testID) => tree.root.findAll((node) => node.props.testID === testID)[0].props; const press = (tree, testID) => act(() => buttonOf(tree, testID).props.onPress()); const take = (photo) => act(() => mockPicker.take(photo)); @@ -165,21 +166,51 @@ describe('DocumentRequirementCard', () => { expect(tree.root.findAll((node) => typeof node.props.onPress === 'function')).toHaveLength(0); }); - it('shows a photo taken, what to do next, and the actions the host gives it', () => { + it('shows a photo taken, named for a screen reader, what to do next, and the actions the host gives it', () => { const onPress = jest.fn(); const tree = render( ); - expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); + expect(propsOf(tree, 'document-requirement-cover-0')).toEqual( + expect.objectContaining({ accessible: true, accessibilityRole: 'image', accessibilityLabel: 'Front' }) + ); + // One photo is the cover, not a carousel. + expect(hasTestID(tree, 'document-requirement-covers')).toBe(false); expect(textsOf(tree)).toContain('Now take a photo of the back of your licence.'); press(tree, 'cancel'); expect(onPress).toHaveBeenCalledTimes(1); }); + + it('shows both sides as a carousel that snaps item by item, the next one peeking (Material 3 hero)', () => { + const { spacing } = MD3LightTheme; + const tree = render( + + ); + const carousel = propsOf(tree, 'document-requirement-covers'); + expect(carousel).toEqual( + expect.objectContaining({ horizontal: true, pagingEnabled: true, decelerationRate: 'fast' }) + ); + expect(propsOf(tree, 'document-requirement-cover-0').accessibilityLabel).toBe('Front'); + expect(propsOf(tree, 'document-requirement-cover-1').accessibilityLabel).toBe('Back'); + + act(() => carousel.onLayout({ nativeEvent: { layout: { width: 400 } } })); + // The large item is what the width leaves after the small item that peeks (56 dp) and the gap (8 dp). + const itemWidth = 400 - spacing.x14 - spacing.x2; + expect(propsOf(tree, 'document-requirement-cover-0').style).toEqual({ width: itemWidth }); + expect(propsOf(tree, 'document-requirement-covers').snapToInterval).toBe(itemWidth + spacing.x2); + expect(propsOf(tree, 'document-requirement-covers').contentContainerStyle).toEqual({ gap: spacing.x2 }); + }); }); describe('DocumentVersionList', () => { @@ -206,7 +237,7 @@ describe('DocumentCaptureCard', () => { take({ uri: 'file:///page.jpg' }); expect(onCapture).not.toHaveBeenCalled(); - expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); + expect(propsOf(tree, 'document-requirement-cover-0').accessibilityLabel).toBe('Document'); // The way to take a photo stays. expect(textsOf(tree)).toEqual(expect.arrayContaining(['Add', 'Send to review'])); expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(false); @@ -231,7 +262,8 @@ describe('DocumentCaptureCard', () => { take({ uri: 'file:///back.jpg' }); expect(onCapture).not.toHaveBeenCalled(); - expect(hasTestID(tree, 'document-requirement-cover-1')).toBe(true); + expect(propsOf(tree, 'document-requirement-cover-0').accessibilityLabel).toBe('Front'); + expect(propsOf(tree, 'document-requirement-cover-1').accessibilityLabel).toBe('Back'); expect(textsOf(tree)).not.toContain('Now take a photo of the back of your licence.'); expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(false); From 0b8b81e40e5a8c80f1598fa23cfc5a2cf70a67a8 Mon Sep 17 00:00:00 2001 From: Joely Date: Wed, 4 Nov 2026 02:13:22 -0500 Subject: [PATCH 07/16] =?UTF-8?q?components=200.5.4=20(unpublished):=20the?= =?UTF-8?q?=20document=20card's=20photo=20button=20is=20a=20text=20button;?= =?UTF-8?q?=20only=20=C2=ABSend=20to=20review=C2=BB=20has=20a=20border=20(?= =?UTF-8?q?owner,=202026-11-04)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DocumentRequirementCard actions take an optional Paper Button `mode`, which Card.Actions keeps (it gives a mode only to a child without one). DocumentCaptureCard: the photo button `text`, «Send to review» `outlined`. Co-Authored-By: Claude Opus 5.5 --- PROJECT.md | 10 +++++----- .../components/src/Partner/DocumentCaptureCard.js | 13 ++++++++++--- .../src/Partner/DocumentRequirement.stories.js | 8 ++++---- .../src/Partner/DocumentRequirementCard.js | 12 +++++++----- .../Partner/__tests__/documentRequirement.test.js | 3 +++ 5 files changed, 29 insertions(+), 17 deletions(-) diff --git a/PROJECT.md b/PROJECT.md index 990c6020..b5847fc6 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -219,8 +219,8 @@ themed through `useTheme()` so a host's theme applies: `requirementTitle(item)` (the rule's name for the market, else the catalogue's), `subtitle` is the host's, then, in its `Card.Content`, `covers` (the photos taken and not sent, in order, each `{ uri, label }` with the name a screen reader says), `note` and the rule's explanation, and `actions` - (`{ label, onPress, isDisabled?, testID? }`) as Paper `Button`s straight inside `Card.Actions`, which gives - them their modes. Without `actions` it only reads (the console). + (`{ label, onPress, isDisabled?, mode?, testID? }`) as Paper `Button`s straight inside `Card.Actions`, which + keeps a `mode` given and gives the rest theirs. Without `actions` it only reads (the console). - `Partner/DocumentCovers` (portable, not exported) — the card's photos: one is a `Card.Cover`; more are a Material 3 hero carousel (a horizontal `ScrollView`: `snapToInterval` on the phone, `pagingEnabled`'s CSS scroll snap on the web; items `spacing.x2` apart, the next peeking `spacing.x14`, Material's 8 dp and 56 dp). @@ -228,9 +228,9 @@ themed through `useTheme()` so a host's theme applies: nothing, so no chevron. - `Partner/DocumentCaptureCard` (barrel only: the picker is native) — the card with the way to send it, as `item.capture` says (`pages` 1, or 2 = the front then the back). Taking a photo sends nothing: the pages show - as covers; its first action takes a photo (one taken once every page is there starts again), and the last, - «Send to review», contained and disabled until every page is taken, hands them to `onCapture(photos)` in - order. Photos only: it offers no PDF (owner, 2026-11-04). + as covers; its first action, a text button, takes a photo (one taken once every page is there starts again), + and the last, «Send to review», the only one with a border (outlined) and disabled until every page is taken, + hands them to `onCapture(photos)` in order. Photos only: it offers no PDF (owner, 2026-11-04). - `ImagePicker.Avatar` `variant="sheet"` renders no control of its own; the caller opens the sheet with the ref's `show()`, so its own Paper `Button` can sit inside a `Card.Actions`. `avatar` and `button` are as before. - Their fixed words (`documentAddFront`, `documentAddBack`, `documentAddBackPrompt`, `documentFront`, diff --git a/packages/components/src/Partner/DocumentCaptureCard.js b/packages/components/src/Partner/DocumentCaptureCard.js index e96cc860..b8f54041 100644 --- a/packages/components/src/Partner/DocumentCaptureCard.js +++ b/packages/components/src/Partner/DocumentCaptureCard.js @@ -40,13 +40,20 @@ const DocumentCaptureCard = ({ item, subtitle, onCapture, isDisabled = false, te let addLabel = localized('add'); if (twoSided) addLabel = localized(pages.length === 1 ? 'documentAddBack' : 'documentAddFront'); - // MD3: the way to take a photo stays, and the main action, sending, is last (Card.Actions makes the first button - // outlined and the next contained); it waits, disabled, until every page is taken. + // The way to take a photo stays, a text button; the main action, sending, is last and the only one with a border + // (owner, 2026-11-04); it waits, disabled, until every page is taken. const actions = [ - { label: addLabel, onPress: () => pickerRef.current?.show(), isDisabled, testID: `${testID}-add` }, + { + label: addLabel, + onPress: () => pickerRef.current?.show(), + isDisabled, + mode: 'text', + testID: `${testID}-add`, + }, { label: localized('sendToReview'), onPress: send, + mode: 'outlined', isDisabled: isDisabled || !complete, testID: `${testID}-send`, }, diff --git a/packages/components/src/Partner/DocumentRequirement.stories.js b/packages/components/src/Partner/DocumentRequirement.stories.js index af231775..833e177c 100644 --- a/packages/components/src/Partner/DocumentRequirement.stories.js +++ b/packages/components/src/Partner/DocumentRequirement.stories.js @@ -201,8 +201,8 @@ export const LicenceFrontTaken = () => ( covers={[{ uri: 'data:,', label: localized('documentFront') }]} note={localized('documentAddBackPrompt')} actions={[ - { label: localized('documentAddBack'), onPress: () => {} }, - { label: localized('sendToReview'), onPress: () => {}, isDisabled: true }, + { label: localized('documentAddBack'), onPress: () => {}, mode: 'text' }, + { label: localized('sendToReview'), onPress: () => {}, isDisabled: true, mode: 'outlined' }, ]} /> @@ -217,8 +217,8 @@ export const LicenceReadyToSend = () => ( { uri: 'data:,', label: localized('documentBack') }, ]} actions={[ - { label: localized('documentAddFront'), onPress: () => {} }, - { label: localized('sendToReview'), onPress: () => {} }, + { label: localized('documentAddFront'), onPress: () => {}, mode: 'text' }, + { label: localized('sendToReview'), onPress: () => {}, mode: 'outlined' }, ]} /> diff --git a/packages/components/src/Partner/DocumentRequirementCard.js b/packages/components/src/Partner/DocumentRequirementCard.js index 58fa8110..246c5a79 100644 --- a/packages/components/src/Partner/DocumentRequirementCard.js +++ b/packages/components/src/Partner/DocumentRequirementCard.js @@ -16,12 +16,14 @@ import { requirementTitle, ruleText } from './viewModel'; * `note` (what to do now) and the rule's plain explanation for the market. The photos sit in the Card.Content, not * beside it: Card.Content takes its top padding from a Card.Cover or Card.Title just above it, so one carousel * between them would leave the text against the photos; - * - `actions` are `{ label, onPress, isDisabled?, testID? }`, Paper `Button`s straight inside `Card.Actions`, which - * gives them their modes (the first outlined, the next contained). + * - `actions` are `{ label, onPress, isDisabled?, mode?, testID? }`, Paper `Button`s straight inside `Card.Actions`, + * which keeps a `mode` given (a Paper Button mode) and gives the rest its own (the first outlined, the next + * contained). * Without `actions` (the console showing what the partner sees) the card only reads. * * @param {{item: object, subtitle?: ?string, covers?: Array<{uri: string, label: string}>, note?: ?string, - * actions?: Array<{label: string, onPress: () => void, isDisabled?: boolean, testID?: string}>, testID?: string}} props + * actions?: Array<{label: string, onPress: () => void, isDisabled?: boolean, mode?: string, testID?: string}>, + * testID?: string}} props */ const DocumentRequirementCard = ({ item, @@ -68,8 +70,8 @@ const DocumentRequirementCard = ({ ) : null} {actions.length > 0 ? ( - {actions.map(({ label, onPress, isDisabled, testID: actionTestID }) => ( - ))} diff --git a/packages/components/src/Partner/__tests__/documentRequirement.test.js b/packages/components/src/Partner/__tests__/documentRequirement.test.js index 6c6a9ef8..6bd89b63 100644 --- a/packages/components/src/Partner/__tests__/documentRequirement.test.js +++ b/packages/components/src/Partner/__tests__/documentRequirement.test.js @@ -232,6 +232,9 @@ describe('DocumentCaptureCard', () => { // Photos only (owner, 2026-11-04): no PDF, even where the server takes one. expect(textsOf(tree)).not.toContain('Upload a PDF'); expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(true); + // A text button takes the photo; sending is the only one with a border (owner, 2026-11-04). + expect(buttonOf(tree, 'document-requirement-add').props.mode).toBe('text'); + expect(buttonOf(tree, 'document-requirement-send').props.mode).toBe('outlined'); press(tree, 'document-requirement-add'); expect(mockPicker.shown).toBe(1); From 38fab4bc11b862ab158c135c62883371a6915182 Mon Sep 17 00:00:00 2001 From: Joely Date: Wed, 4 Nov 2026 02:18:38 -0500 Subject: [PATCH 08/16] components 0.5.4 (unpublished): PartnerViewModel.documentVersionRow, one version's row for every page that lists versions documentVersionRows maps it; the documents list renders its program versions with it too, so one version reads the same in a requirement's history and in the list (the server's values, the catalogue's labels; owner, 2026-11-04). Co-Authored-By: Claude Opus 5.5 --- .../__tests__/documentRequirement.test.js | 7 +++- packages/components/src/Partner/viewModel.js | 37 ++++++++++--------- 2 files changed, 26 insertions(+), 18 deletions(-) diff --git a/packages/components/src/Partner/__tests__/documentRequirement.test.js b/packages/components/src/Partner/__tests__/documentRequirement.test.js index 6bd89b63..659d78bb 100644 --- a/packages/components/src/Partner/__tests__/documentRequirement.test.js +++ b/packages/components/src/Partner/__tests__/documentRequirement.test.js @@ -9,7 +9,7 @@ import { registerFlatCatalog, setI18nConfig } from '../../Localization/Localizat import DocumentCaptureCard from '../DocumentCaptureCard'; import DocumentRequirementCard from '../DocumentRequirementCard'; import DocumentVersionList from '../DocumentVersionList'; -import { documentVersionRows, requirementTitle } from '../viewModel'; +import { documentVersionRow, documentVersionRows, requirementTitle } from '../viewModel'; // The photo sheet is the native picker; here it is a stand-in that records being opened and hands back the photo a // test gives it, through the same ref and `onChange` the card uses. @@ -152,6 +152,11 @@ describe('documentVersionRows', () => { expect(documentVersionRows(undefined)).toEqual([]); expect(documentVersionRows([])).toEqual([]); }); + + it('is one version row for every page that lists versions', () => { + const version = { versionId: 'v2', verification: { status: 'verified' }, expires_at: '2026-11-23' }; + expect(documentVersionRow(version)).toEqual(documentVersionRows([version])[0]); + }); }); describe('DocumentRequirementCard', () => { diff --git a/packages/components/src/Partner/viewModel.js b/packages/components/src/Partner/viewModel.js index 327d53db..e09bc895 100644 --- a/packages/components/src/Partner/viewModel.js +++ b/packages/components/src/Partner/viewModel.js @@ -394,24 +394,27 @@ export const ruleText = (text) => (text ? text[currentLocale().split('-')[0]] ?? export const requirementTitle = (item) => ruleText(item?.label) ?? requirementLabel(item?.requirementKey); /** - * Contract request #117: a document requirement's versions (`checklistItem.versions`, newest first, as the server - * sends them) as list rows `{ key, title, description }`. The title is the version's state: «Superseded» once a newer - * one replaced it, else its verification's label. The description is when it was sent (in the app's locale), that it - * is still being scanned, why it was not accepted and until when it counts — each only when the version says it. + * One document version as the server sends it, as a list row `{ key, title, description }`, the same on every page that + * lists versions (a requirement's history, the documents list). The title is the version's state: «Superseded» once a + * newer one replaced it, else its verification's label. The description is when it was sent (in the app's locale), + * that it is still being scanned, why it was not accepted and until when it counts — each only when the version says + * it. */ -export const documentVersionRows = (versions) => - (Array.isArray(versions) ? versions : []).map((version) => ({ - key: version.versionId, - title: version.supersededBy - ? localized('documentSuperseded') - : statusLabel('verification', version.verification?.status), - description: interpunct([ - formatDateTime(version.submittedTime), - version.scan?.status === SCAN_STATUS.PENDING ? labelOf(GROUP.scan, version.scan.status) : null, - detailsCodeLabel(version.verification?.details_code), - version.expires_at ? `${localized('documentExpires')} ${version.expires_at}` : null, - ]), - })); +export const documentVersionRow = (version) => ({ + key: version.versionId, + title: version.supersededBy + ? localized('documentSuperseded') + : statusLabel('verification', version.verification?.status), + description: interpunct([ + formatDateTime(version.submittedTime), + version.scan?.status === SCAN_STATUS.PENDING ? labelOf(GROUP.scan, version.scan.status) : null, + detailsCodeLabel(version.verification?.details_code), + version.expires_at ? `${localized('documentExpires')} ${version.expires_at}` : null, + ]), +}); + +/** Contract request #117: a document requirement's versions (`checklistItem.versions`, newest first) as those rows. */ +export const documentVersionRows = (versions) => (Array.isArray(versions) ? versions : []).map(documentVersionRow); /** «24 h», «30 días»: the catalogue's word for the count, or the bare count while no catalogue carries it. */ const countText = (kind, count) => { From a3db471c6ac19305f698bee6c2c7db1b0d79fc36 Mon Sep 17 00:00:00 2001 From: Joely Date: Wed, 4 Nov 2026 11:43:37 -0500 Subject: [PATCH 09/16] components 0.5.4 (unpublished): the photo picker opens the library without a permission, reports its errors, launches once, goes straight to the library on the web and takes the caller's capture options - chooseFromLibrary asks for no permission: image-picker 8 opens Android's Photo Picker and iOS's PHPicker, which need none; asking blocked Android 13+ (READ_EXTERNAL_STORAGE is not declared) and iOS limited access. - The picker's errorCode is read (8.x never sets `error`): the permission alert only for a permission error, the generic failure (global.somethingWentWrong / global.tryAgainLater) for any other; no `Alert(...)` call, no debug logs, no `allowsMultipleSelection`. takePhoto / chooseFromLibrary always resolve: the asset or null. - The sheet ignores taps while a pick is in progress. - Where the sheet would offer a single choice (the web), show() takes it. - ImagePicker.Avatar `captureOptions` are laid over the defaults; callers that pass none behave as before. - ImagePickerAPI tests with image-picker and permissions mocked. Co-Authored-By: Claude Opus 5.5 --- PROJECT.md | 8 ++ .../src/ImagePicker/ImagePickerAPI.js | 135 ++++++++++-------- .../src/ImagePicker/ImagePickerAvatar.js | 48 +++++-- .../__tests__/ImagePickerAPI.test.js | 126 ++++++++++++++++ .../__tests__/ImagePickerAvatar.test.js | 73 +++++++++- 5 files changed, 311 insertions(+), 79 deletions(-) create mode 100644 packages/components/src/ImagePicker/__tests__/ImagePickerAPI.test.js diff --git a/PROJECT.md b/PROJECT.md index b5847fc6..b695d70e 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -233,6 +233,14 @@ themed through `useTheme()` so a host's theme applies: hands them to `onCapture(photos)` in order. Photos only: it offers no PDF (owner, 2026-11-04). - `ImagePicker.Avatar` `variant="sheet"` renders no control of its own; the caller opens the sheet with the ref's `show()`, so its own Paper `Button` can sit inside a `Card.Actions`. `avatar` and `button` are as before. + Every variant: `captureOptions` (react-native-image-picker's options) are laid over the defaults (a photo, quality + 1, base64), so callers that pass none behave as before; `onChange(asset)` is called only with a photo; the sheet + ignores taps while a pick is in progress; where it would offer a single choice (the web, which has no camera + option) `show()` takes that choice. `ImagePickerAPI`'s `takePhoto(options)` / `chooseFromLibrary(options)` always + resolve, never reject: the asset, or `null` — cancelled (silently), a permission refused (the permission alert, + with Settings) or any other picker error, read from its `errorCode` (`global.somethingWentWrong` / + `global.tryAgainLater`). The library asks for no permission: image-picker 8 opens Android's Photo Picker and iOS's + PHPicker, which need none (asking blocked Android 13+ and iOS limited access); the camera keeps its permission. - Their fixed words (`documentAddFront`, `documentAddBack`, `documentAddBackPrompt`, `documentFront`, `documentBack`, `documentSuperseded`) live in `Translations/*.json`; the stories (`Partner/DocumentRequirement.stories.js`) use the local circuit's real items. diff --git a/packages/components/src/ImagePicker/ImagePickerAPI.js b/packages/components/src/ImagePicker/ImagePickerAPI.js index c490e71f..25e13f84 100644 --- a/packages/components/src/ImagePicker/ImagePickerAPI.js +++ b/packages/components/src/ImagePicker/ImagePickerAPI.js @@ -1,7 +1,28 @@ import { Linking, Alert } from 'react-native'; import { launchCamera, launchImageLibrary } from 'react-native-image-picker'; -import { checkAndAskForPermissionCamara, checkAndAskForPermissionMediaLibrary } from './utils'; +import { RESULTS } from 'react-native-permissions'; +import { checkAndAskForPermissionCamara } from './utils'; +// What every pick asked for before a caller could pass options of its own (`takePhoto(options)`): a photo at full +// quality, with its base64. A caller's options are laid over these. +const DEFAULT_OPTIONS = Object.freeze({ mediaType: 'photo', quality: 1, includeBase64: true }); + +// react-native-image-picker's `errorCode` for a pick its platform refused for want of a permission; its other codes +// (`camera_unavailable`, `others`) are failures a setting cannot fix. +const PERMISSION_ERROR = 'permission'; + +// The answers of a camera permission request that Settings can change; anything else (`unavailable`, a request that +// threw) is a failure, not a refusal. +const PERMISSION_REFUSED = Object.freeze([RESULTS.DENIED, RESULTS.BLOCKED]); + +/** + * Takes one photo with the camera or picks one from the library. + * + * `takePhoto(options)` and `chooseFromLibrary(options)` always resolve, and never reject, so a caller never waits on + * a pick that ended: with the picked asset, or with `null` when nothing was picked — cancelled (silently), refused a + * permission (the permission alert, with a way to Settings) or failed (the generic failure alert). `options` are + * react-native-image-picker's, laid over `DEFAULT_OPTIONS`. + */ class ImagePickerAPI { constructor({ titlePermissionCamera, @@ -10,6 +31,9 @@ class ImagePickerAPI { descriptionPermissionPhotos, cancelPermission, settingPermission, + titleFailure, + descriptionFailure, + closeFailure, }) { this.titlePermissionCamera = titlePermissionCamera; this.titlePermissionPhotos = titlePermissionPhotos; @@ -17,6 +41,9 @@ class ImagePickerAPI { this.descriptionPermissionPhotos = descriptionPermissionPhotos; this.cancelPermission = cancelPermission; this.settingPermission = settingPermission; + this.titleFailure = titleFailure; + this.descriptionFailure = descriptionFailure; + this.closeFailure = closeFailure; } catchPermissionStatusCamara() { @@ -24,15 +51,8 @@ class ImagePickerAPI { this.titlePermissionCamera, this.descriptionPermissionCamera, [ - { - text: this.cancelPermission, - onPress: () => console.log('Cancel Pressed'), - style: 'cancel', - }, - { - text: this.settingPermission, - onPress: () => Linking.openSettings(), - }, + { text: this.cancelPermission, style: 'cancel' }, + { text: this.settingPermission, onPress: () => Linking.openSettings() }, ], { cancelable: false } ); @@ -43,65 +63,56 @@ class ImagePickerAPI { this.titlePermissionPhotos, this.descriptionPermissionPhotos, [ - { - text: this.cancelPermission, - onPress: () => console.log('Cancel Pressed'), - style: 'cancel', - }, - { - text: this.settingPermission, - onPress: () => Linking.openSettings(), - }, + { text: this.cancelPermission, style: 'cancel' }, + { text: this.settingPermission, onPress: () => Linking.openSettings() }, ], { cancelable: false } ); } - takePhoto() { - return new Promise((resolve) => { - checkAndAskForPermissionCamara() - .then(() => launchCamera({ mediaType: 'photo', quality: 1, includeBase64: true })) - .then((response) => { - if (response.didCancel) { - console.log('User cancelled image picker'); - } else if (response.error) { - Alert(response.error); - console.log('ImagePicker Error: ', response.error); - } else if (response.customButton) { - console.log('User tapped custom button: ', response.customButton); - } else { - resolve(response?.assets[0]); - } - }) - .catch(() => this.catchPermissionStatusCamara()); - }); + // The button is named here: without one Android's alert falls back to an English «OK». + alertFailure() { + Alert.alert(this.titleFailure, this.descriptionFailure, [{ text: this.closeFailure }]); + } + + /** The asset `launcher` picked, or null once the user has been told why there is none. */ + launch(launcher, options, alertPermission) { + return launcher({ ...DEFAULT_OPTIONS, ...options }) + .then((response) => { + if (response.didCancel) return null; + if (response.errorCode === PERMISSION_ERROR) { + alertPermission(); + return null; + } + if (response.errorCode) { + this.alertFailure(); + return null; + } + return response.assets?.[0] ?? null; + }) + .catch(() => { + this.alertFailure(); + return null; + }); + } + + takePhoto(options) { + return checkAndAskForPermissionCamara().then( + () => this.launch(launchCamera, options, () => this.catchPermissionStatusCamara()), + (status) => { + if (PERMISSION_REFUSED.includes(status)) this.catchPermissionStatusCamara(); + else this.alertFailure(); + return null; + } + ); } - chooseFromLibrary() { - return new Promise((resolve) => { - checkAndAskForPermissionMediaLibrary() - .then(() => - launchImageLibrary({ - mediaType: 'photo', - quality: 1, - includeBase64: true, - allowsMultipleSelection: true, - }) - ) - .then((response) => { - if (response.didCancel) { - console.log('User cancelled image picker'); - } else if (response.error) { - Alert(response.error); - console.log('ImagePicker Error: ', response.error); - } else if (response.customButton) { - console.log('User tapped custom button: ', response.customButton); - } else { - resolve(response?.assets[0]); - } - }) - .catch(() => this.catchPermissionStatusPhotos()); - }); + // No permission is asked: react-native-image-picker 8 opens Android's Photo Picker and iOS's PHPicker, which run + // outside the app and hand back only what the user picks. Asking for the library permission blocked the pick where + // it cannot be granted: Android 13+ (the app declares no READ_EXTERNAL_STORAGE) and iOS limited access. The picker + // still reports `permission` where its platform checks one (iOS with `includeExtra`). + chooseFromLibrary(options) { + return this.launch(launchImageLibrary, options, () => this.catchPermissionStatusPhotos()); } } diff --git a/packages/components/src/ImagePicker/ImagePickerAvatar.js b/packages/components/src/ImagePicker/ImagePickerAvatar.js index ef5c0df4..5ce7a8e9 100644 --- a/packages/components/src/ImagePicker/ImagePickerAvatar.js +++ b/packages/components/src/ImagePicker/ImagePickerAvatar.js @@ -23,6 +23,9 @@ export const IMAGE_PICKER_ACTIONS = { * The photo picker: a camera / library / cancel sheet, opened by an avatar (`variant="avatar"`), by a text button * (`variant="button"`), or, with `variant="sheet"`, by the caller's own control through the ref's `show()` — so a * caller can put a Paper `Button` straight inside its own container (a `Card.Actions` styles only its direct children). + * Where the sheet would offer a single choice (the web, which has no camera option, without extra `options`), opening + * it takes that choice instead. `onChange(asset)` gets each photo picked; a pick cancelled or refused calls nothing. + * `captureOptions` (react-native-image-picker's options, e.g. a maximum size) are laid over the picker's defaults. */ const Avatar = forwardRef(function Avatar( { @@ -35,11 +38,13 @@ const Avatar = forwardRef(function Avatar( size = moderateScale(150), options = [], isDisabled, + captureOptions, }, ref ) { const imagePickerRef = useRef(); const actionSheetRef = useRef(); + const launching = useRef(false); const insets = useSafeAreaInsets(); @@ -51,26 +56,33 @@ const Avatar = forwardRef(function Avatar( descriptionPermissionPhotos: localized('enablePhotosPermission'), cancelPermission: localized('global.cancel'), settingPermission: localized('goToSettings'), + titleFailure: localized('global.somethingWentWrong'), + descriptionFailure: localized('global.tryAgainLater'), + closeFailure: localized('global.close'), }); }, []); - const showActionSheet = () => { - actionSheetRef.current.show(); + // The sheet stays open after a pick cancelled or refused, so another source can be chosen. + const launch = async (pick) => { + launching.current = true; + try { + const asset = await pick(); + if (asset) { + onChange(asset); + actionSheetRef.current.hide(); + } + } finally { + launching.current = false; + } }; - useImperativeHandle(ref, () => ({ show: showActionSheet }), []); - - const onActionDone = async (value) => { + const onActionDone = (value) => { + // A tap while the picker is still opening would launch it a second time. + if (launching.current) return; if (value === IMAGE_PICKER_ACTIONS.launchCamera) { - imagePickerRef.current.takePhoto().then((rep) => { - onChange(rep); - actionSheetRef.current.hide(); - }); + launch(() => imagePickerRef.current.takePhoto(captureOptions)); } else if (value === IMAGE_PICKER_ACTIONS.launchImageLibrary) { - imagePickerRef.current.chooseFromLibrary().then((rep) => { - onChange(rep); - actionSheetRef.current.hide(); - }); + launch(() => imagePickerRef.current.chooseFromLibrary(captureOptions)); } else if (value === IMAGE_PICKER_ACTIONS.removeImage) { onRemove(); actionSheetRef.current.hide(); @@ -97,6 +109,16 @@ const Avatar = forwardRef(function Avatar( ...options, { title: localized('cancel'), value: IMAGE_PICKER_ACTIONS.cancel, icon: 'cancel' }, ]; + const choices = OPTIONS.filter(({ value }) => value !== IMAGE_PICKER_ACTIONS.cancel); + + const showActionSheet = () => { + if (choices.length === 1) onActionDone(choices[0].value); + else actionSheetRef.current.show(); + }; + + // Recreated on every render: `show()` may launch the picker itself, and must hand the photo to the current + // `onChange`, not the first render's. + useImperativeHandle(ref, () => ({ show: showActionSheet })); // What opens the sheet: the avatar, the text button, or nothing of its own (`sheet`: the caller's control, `show()`). let trigger = null; diff --git a/packages/components/src/ImagePicker/__tests__/ImagePickerAPI.test.js b/packages/components/src/ImagePicker/__tests__/ImagePickerAPI.test.js new file mode 100644 index 00000000..aee5e099 --- /dev/null +++ b/packages/components/src/ImagePicker/__tests__/ImagePickerAPI.test.js @@ -0,0 +1,126 @@ +import { Alert, Linking } from 'react-native'; +import { launchCamera, launchImageLibrary } from 'react-native-image-picker'; +import { PERMISSIONS, RESULTS, request } from 'react-native-permissions'; + +import ImagePickerAPI from '../ImagePickerAPI'; + +// Both are native modules. The permissions library publishes its own jest mock (every request granted unless a test +// says otherwise); the picker publishes none, so its two launchers are stand-ins that answer what a test gives them. +jest.mock('react-native-permissions', () => require('react-native-permissions/mock')); +jest.mock('react-native-image-picker', () => ({ launchCamera: jest.fn(), launchImageLibrary: jest.fn() })); + +const LABELS = { + titlePermissionCamera: 'Camera permission denied', + titlePermissionPhotos: 'Allow access to photos', + descriptionPermissionCamera: 'Enable the camera permission', + descriptionPermissionPhotos: 'Enable the photos permission', + cancelPermission: 'Cancel', + settingPermission: 'Go to settings', + titleFailure: 'Something went wrong', + descriptionFailure: 'Please try again later.', + closeFailure: 'Close', +}; +const ASSET = { uri: 'file:///photo.jpg', base64: 'photo' }; +const DEFAULTS = { mediaType: 'photo', quality: 1, includeBase64: true }; + +const picker = () => new ImagePickerAPI(LABELS); + +let alert; +beforeEach(() => { + jest.clearAllMocks(); + alert = jest.spyOn(Alert, 'alert').mockImplementation(() => {}); + launchCamera.mockResolvedValue({ assets: [ASSET] }); + launchImageLibrary.mockResolvedValue({ assets: [ASSET] }); +}); + +afterEach(() => alert.mockRestore()); + +describe('ImagePickerAPI.chooseFromLibrary', () => { + it('opens the library without asking for any permission, and resolves the photo picked', async () => { + await expect(picker().chooseFromLibrary()).resolves.toBe(ASSET); + expect(request).not.toHaveBeenCalled(); + expect(launchImageLibrary).toHaveBeenCalledWith(DEFAULTS); + expect(Alert.alert).not.toHaveBeenCalled(); + }); + + it("lays the caller's capture options over the defaults", async () => { + const options = { maxWidth: 5120, maxHeight: 5120, assetRepresentationMode: 'compatible' }; + await picker().chooseFromLibrary(options); + expect(launchImageLibrary).toHaveBeenCalledWith({ ...DEFAULTS, ...options }); + }); + + it('resolves nothing, and says nothing, when the pick is cancelled', async () => { + launchImageLibrary.mockResolvedValue({ didCancel: true }); + await expect(picker().chooseFromLibrary()).resolves.toBeNull(); + expect(Alert.alert).not.toHaveBeenCalled(); + }); + + it("shows the photos permission alert only for the picker's permission error", async () => { + launchImageLibrary.mockResolvedValue({ errorCode: 'permission' }); + await expect(picker().chooseFromLibrary()).resolves.toBeNull(); + expect(Alert.alert).toHaveBeenCalledWith( + LABELS.titlePermissionPhotos, + LABELS.descriptionPermissionPhotos, + expect.any(Array), + { cancelable: false } + ); + }); + + it('shows the generic failure when the library cannot open', async () => { + launchImageLibrary.mockResolvedValue({ errorCode: 'others', errorMessage: 'Activity error' }); + await expect(picker().chooseFromLibrary()).resolves.toBeNull(); + expect(Alert.alert).toHaveBeenCalledWith(LABELS.titleFailure, LABELS.descriptionFailure, [ + { text: LABELS.closeFailure }, + ]); + }); + + it('resolves nothing, after the generic failure, when the launcher itself throws', async () => { + launchImageLibrary.mockRejectedValue(new Error('no native module')); + await expect(picker().chooseFromLibrary()).resolves.toBeNull(); + expect(Alert.alert).toHaveBeenCalledWith(LABELS.titleFailure, LABELS.descriptionFailure, expect.any(Array)); + }); +}); + +describe('ImagePickerAPI.takePhoto', () => { + it('asks for the camera permission, then takes the photo with the capture options', async () => { + const options = { maxWidth: 5120, maxHeight: 5120, conversionQuality: 1 }; + await expect(picker().takePhoto(options)).resolves.toBe(ASSET); + expect(request).toHaveBeenCalledWith(PERMISSIONS.IOS.CAMERA); + expect(launchCamera).toHaveBeenCalledWith({ ...DEFAULTS, ...options }); + }); + + it.each([RESULTS.DENIED, RESULTS.BLOCKED])( + 'shows the camera permission alert, with a way to Settings, when the permission is %s', + async (status) => { + request.mockResolvedValueOnce(status); + const openSettings = jest.spyOn(Linking, 'openSettings').mockImplementation(() => Promise.resolve()); + await expect(picker().takePhoto()).resolves.toBeNull(); + expect(launchCamera).not.toHaveBeenCalled(); + const [title, description, buttons] = Alert.alert.mock.calls[0]; + expect([title, description]).toEqual([LABELS.titlePermissionCamera, LABELS.descriptionPermissionCamera]); + expect(buttons.map(({ text }) => text)).toEqual([LABELS.cancelPermission, LABELS.settingPermission]); + buttons[1].onPress(); + expect(openSettings).toHaveBeenCalled(); + openSettings.mockRestore(); + } + ); + + it('shows the generic failure, not the permission alert, when the device has no camera', async () => { + request.mockResolvedValueOnce(RESULTS.UNAVAILABLE); + await expect(picker().takePhoto()).resolves.toBeNull(); + expect(Alert.alert).toHaveBeenCalledWith(LABELS.titleFailure, LABELS.descriptionFailure, expect.any(Array)); + }); + + it('shows the generic failure for the camera_unavailable error code', async () => { + launchCamera.mockResolvedValue({ errorCode: 'camera_unavailable' }); + await expect(picker().takePhoto()).resolves.toBeNull(); + expect(Alert.alert).toHaveBeenCalledTimes(1); + expect(Alert.alert).toHaveBeenCalledWith(LABELS.titleFailure, LABELS.descriptionFailure, expect.any(Array)); + }); + + it('resolves nothing, and says nothing, when the photo is cancelled', async () => { + launchCamera.mockResolvedValue({ didCancel: true }); + await expect(picker().takePhoto()).resolves.toBeNull(); + expect(Alert.alert).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/components/src/ImagePicker/__tests__/ImagePickerAvatar.test.js b/packages/components/src/ImagePicker/__tests__/ImagePickerAvatar.test.js index 522ca852..6c324c9d 100644 --- a/packages/components/src/ImagePicker/__tests__/ImagePickerAvatar.test.js +++ b/packages/components/src/ImagePicker/__tests__/ImagePickerAvatar.test.js @@ -1,13 +1,15 @@ import React, { createRef } from 'react'; +import { Platform } from 'react-native'; import renderer, { act } from 'react-test-renderer'; import { MD3LightTheme, Provider } from '@jmstechnologiesinc/react-native-paper'; import ButtonWrapper from '../../ButtonWrapper/ButtonWrapper'; +import { localized } from '../../Localization/Localization'; import ImagePickerAvatar from '../ImagePickerAvatar'; -// The sheet is native; a stand-in records being opened through the same ref the picker uses. -const mockSheet = { shown: 0 }; +// The sheet is native; a stand-in records being opened and closed through the same ref the picker uses. +const mockSheet = { shown: 0, hidden: 0 }; jest.mock('react-native-actions-sheet', () => { const React = require('react'); const ActionSheet = React.forwardRef(({ children }, ref) => { @@ -15,7 +17,9 @@ jest.mock('react-native-actions-sheet', () => { show: () => { mockSheet.shown += 1; }, - hide: () => {}, + hide: () => { + mockSheet.hidden += 1; + }, })); return children; }); @@ -36,7 +40,9 @@ jest.mock('react-native-safe-area-context', () => { initialWindowMetrics: { insets, frame }, }; }); -jest.mock('../ImagePickerAPI', () => jest.fn()); +// The camera and the library are ImagePickerAPI's (its own suite); here each pick answers what a test gives it. +const mockPicks = { takePhoto: jest.fn(), chooseFromLibrary: jest.fn() }; +jest.mock('../ImagePickerAPI', () => jest.fn().mockImplementation(() => mockPicks)); jest.useFakeTimers(); @@ -52,6 +58,9 @@ const render = (element) => { beforeEach(() => { mockSheet.shown = 0; + mockSheet.hidden = 0; + mockPicks.takePhoto.mockReset(); + mockPicks.chooseFromLibrary.mockReset(); }); afterEach(() => { @@ -59,8 +68,13 @@ afterEach(() => { mounted.splice(0).forEach((tree) => tree.unmount()); jest.runOnlyPendingTimers(); }); + jest.restoreAllMocks(); }); +const optionOf = (tree, title) => + tree.root.findAll((node) => node.props.title === title && typeof node.props.onPress === 'function')[0]; +const ASSET = { uri: 'file:///photo.jpg' }; + describe('ImagePicker.Avatar', () => { it('opens its sheet from its own text button, as before', () => { const tree = render(); @@ -76,4 +90,55 @@ describe('ImagePicker.Avatar', () => { act(() => ref.current.show()); expect(mockSheet.shown).toBe(1); }); + + it("hands each photo picked to onChange with the caller's capture options, and closes the sheet", async () => { + const onChange = jest.fn(); + const captureOptions = { maxWidth: 5120, maxHeight: 5120 }; + mockPicks.chooseFromLibrary.mockResolvedValue(ASSET); + const tree = render(); + await act(async () => optionOf(tree, localized('chooseFromLibrary')).props.onPress()); + expect(mockPicks.chooseFromLibrary).toHaveBeenCalledWith(captureOptions); + expect(onChange).toHaveBeenCalledWith(ASSET); + expect(mockSheet.hidden).toBe(1); + }); + + it('calls nothing and keeps the sheet open when a pick ends without a photo', async () => { + const onChange = jest.fn(); + mockPicks.takePhoto.mockResolvedValue(null); + const tree = render(); + await act(async () => optionOf(tree, localized('takePhoto')).props.onPress()); + expect(onChange).not.toHaveBeenCalled(); + expect(mockSheet.hidden).toBe(0); + }); + + it('ignores the sheet while a pick is in progress, and listens again once it ends', async () => { + let finish; + mockPicks.takePhoto.mockReturnValue( + new Promise((resolve) => { + finish = resolve; + }) + ); + mockPicks.chooseFromLibrary.mockResolvedValue(ASSET); + const tree = render(); + act(() => optionOf(tree, localized('takePhoto')).props.onPress()); + act(() => optionOf(tree, localized('takePhoto')).props.onPress()); + act(() => optionOf(tree, localized('chooseFromLibrary')).props.onPress()); + expect(mockPicks.takePhoto).toHaveBeenCalledTimes(1); + expect(mockPicks.chooseFromLibrary).not.toHaveBeenCalled(); + + await act(async () => finish(null)); + await act(async () => optionOf(tree, localized('chooseFromLibrary')).props.onPress()); + expect(mockPicks.chooseFromLibrary).toHaveBeenCalledTimes(1); + }); + + it('on the web, where the library is the only choice, opens it straight from show()', async () => { + jest.replaceProperty(Platform, 'OS', 'web'); + const onChange = jest.fn(); + mockPicks.chooseFromLibrary.mockResolvedValue(ASSET); + const ref = createRef(); + render(); + await act(async () => ref.current.show()); + expect(mockSheet.shown).toBe(0); + expect(onChange).toHaveBeenCalledWith(ASSET); + }); }); From 82163f44f6fb85da7b8c7488d5db693fcd5e5761 Mon Sep 17 00:00:00 2001 From: Joely Date: Wed, 4 Nov 2026 11:44:28 -0500 Subject: [PATCH 10/16] components 0.5.4 (unpublished): a version's expiry reads as a date, and its scan shows while it is not clean MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - documentVersionRow formats `expires_at`, a calendar day, with the existing formatDateTime in UTC (no reader's zone moves it) inside the new key documentExpiresOn: «Expires %{date}» / «Vence el %{date}», the text of the app's partnerRequirements.expiresOn. documentExpires stays for the app's older list. - The scan's catalogue label shows whenever the scan is not SCAN_STATUS.CLEAN (pending, and partner 0.2.54's infected), with no status spelled here. Co-Authored-By: Claude Opus 5.5 --- PROJECT.md | 5 ++- .../src/Localization/Translations/en.json | 1 + .../src/Localization/Translations/es.json | 1 + .../__tests__/documentRequirement.test.js | 15 +++++++- packages/components/src/Partner/viewModel.js | 37 ++++++++++++------- 5 files changed, 43 insertions(+), 16 deletions(-) diff --git a/PROJECT.md b/PROJECT.md index b695d70e..347af33e 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -225,7 +225,10 @@ themed through `useTheme()` so a host's theme applies: Material 3 hero carousel (a horizontal `ScrollView`: `snapToInterval` on the phone, `pagingEnabled`'s CSS scroll snap on the web; items `spacing.x2` apart, the next peeking `spacing.x14`, Material's 8 dp and 56 dp). - `Partner/DocumentVersionList` (portable) — `item.versions` as `ListRow`s from `documentVersionRows`; they open - nothing, so no chevron. + nothing, so no chevron. A row's description: when it was sent, the scan's catalogue label while the scan is not + `SCAN_STATUS.CLEAN` (pending, and partner 0.2.54's infected, never spelled here), the details code's label, and + `documentExpiresOn` («Expires Nov 23, 2026»): `expires_at` is a calendar day, formatted by `formatDateTime` in UTC + so no reader's zone moves it. `documentExpires` stays for the app's older list. - `Partner/DocumentCaptureCard` (barrel only: the picker is native) — the card with the way to send it, as `item.capture` says (`pages` 1, or 2 = the front then the back). Taking a photo sends nothing: the pages show as covers; its first action, a text button, takes a photo (one taken once every page is there starts again), diff --git a/packages/components/src/Localization/Translations/en.json b/packages/components/src/Localization/Translations/en.json index 04c7dc9a..330ffbfc 100644 --- a/packages/components/src/Localization/Translations/en.json +++ b/packages/components/src/Localization/Translations/en.json @@ -803,6 +803,7 @@ "accountDeactivatedWithDate": "Your account will be deleted on", "contactSupportForHelp": "Contact support for help.", "documentExpires": "Expires", + "documentExpiresOn": "Expires %{date}", "documentExpired": "Expired", "documentAddFront": "Add the front", "documentAddBack": "Add the back", diff --git a/packages/components/src/Localization/Translations/es.json b/packages/components/src/Localization/Translations/es.json index 481cb6fc..9d309a6f 100644 --- a/packages/components/src/Localization/Translations/es.json +++ b/packages/components/src/Localization/Translations/es.json @@ -803,6 +803,7 @@ "accountDeactivatedWithDate": "Tu cuenta se eliminará el", "contactSupportForHelp": "Contacta a soporte para más información.", "documentExpires": "Vence", + "documentExpiresOn": "Vence el %{date}", "documentExpired": "Vencido", "documentAddFront": "Añadir el anverso", "documentAddBack": "Añadir el reverso", diff --git a/packages/components/src/Partner/__tests__/documentRequirement.test.js b/packages/components/src/Partner/__tests__/documentRequirement.test.js index 659d78bb..b392ae31 100644 --- a/packages/components/src/Partner/__tests__/documentRequirement.test.js +++ b/packages/components/src/Partner/__tests__/documentRequirement.test.js @@ -138,7 +138,8 @@ describe('documentVersionRows', () => { { key: 'v2', title: EN['partner.verification_status.verified'], - description: `${sent} · Expires 2026-11-23`, + // The calendar day the server sent, in the app's locale, in no reader's zone. + description: `${sent} · Expires Nov 23, 2026`, }, { key: 'v1', @@ -148,6 +149,18 @@ describe('documentVersionRows', () => { ]); }); + it('says the scan of a version while it is not clean, by its catalogue label', () => { + // `infected` is partner 0.2.54's (O-10); before it, the view model shows the raw value it does not know. + const infected = EN['partner.scan_status.infected'] ?? 'infected'; + const row = documentVersionRow({ + versionId: 'v4', + verification: { status: 'unverified' }, + scan: { status: 'infected' }, + submittedTime: AT, + }); + expect(row.description).toBe(`${formatDateTime(AT)} · ${infected}`); + }); + it('has no rows without versions', () => { expect(documentVersionRows(undefined)).toEqual([]); expect(documentVersionRows([])).toEqual([]); diff --git a/packages/components/src/Partner/viewModel.js b/packages/components/src/Partner/viewModel.js index e09bc895..a4cde10c 100644 --- a/packages/components/src/Partner/viewModel.js +++ b/packages/components/src/Partner/viewModel.js @@ -393,25 +393,34 @@ export const ruleText = (text) => (text ? text[currentLocale().split('-')[0]] ?? */ export const requirementTitle = (item) => ruleText(item?.label) ?? requirementLabel(item?.requirementKey); +// `expires_at` is a calendar day (`YYYY-MM-DD`), which `Date` reads as that day at 00:00 UTC: formatted in UTC it is +// the same day for every reader, where the reader's zone would move it to the day before west of Greenwich. +const CALENDAR_DAY = Object.freeze({ dateStyle: 'medium', timeZone: 'UTC' }); + /** * One document version as the server sends it, as a list row `{ key, title, description }`, the same on every page that * lists versions (a requirement's history, the documents list). The title is the version's state: «Superseded» once a * newer one replaced it, else its verification's label. The description is when it was sent (in the app's locale), - * that it is still being scanned, why it was not accepted and until when it counts — each only when the version says - * it. + * its scan while it is not clean (being scanned, or quarantined), why it was not accepted and until when it counts + * (that day, in the app's locale) — each only when the version says it. */ -export const documentVersionRow = (version) => ({ - key: version.versionId, - title: version.supersededBy - ? localized('documentSuperseded') - : statusLabel('verification', version.verification?.status), - description: interpunct([ - formatDateTime(version.submittedTime), - version.scan?.status === SCAN_STATUS.PENDING ? labelOf(GROUP.scan, version.scan.status) : null, - detailsCodeLabel(version.verification?.details_code), - version.expires_at ? `${localized('documentExpires')} ${version.expires_at}` : null, - ]), -}); +export const documentVersionRow = (version) => { + const scan = version.scan?.status; + return { + key: version.versionId, + title: version.supersededBy + ? localized('documentSuperseded') + : statusLabel('verification', version.verification?.status), + description: interpunct([ + formatDateTime(version.submittedTime), + scan && scan !== SCAN_STATUS.CLEAN ? labelOf(GROUP.scan, scan) : null, + detailsCodeLabel(version.verification?.details_code), + version.expires_at + ? localized('documentExpiresOn', { date: formatDateTime(version.expires_at, CALENDAR_DAY) }) + : null, + ]), + }; +}; /** Contract request #117: a document requirement's versions (`checklistItem.versions`, newest first) as those rows. */ export const documentVersionRows = (versions) => (Array.isArray(versions) ? versions : []).map(documentVersionRow); From e3f042211026c2503636d0bc741751b30b9dd7cd Mon Sep 17 00:00:00 2001 From: Joely Date: Wed, 4 Nov 2026 11:47:00 -0500 Subject: [PATCH 11/16] components 0.5.4 (unpublished): the document card is controlled, keeps its photos until the host's send succeeds, shows its progress and says what is left MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DocumentCaptureCard is controlled: `pages`, `onPagesChange(pages)`, `onSend()`, `isSending` replace `onCapture` and `isDisabled`. It never clears the pages; the host clears them once its send succeeded. While `isSending` every action is disabled and «Send to review» shows Paper Button's `loading`. - Every document photo is taken at 5,120 px on its long side at most, quality 1, as JPEG (DOCUMENT_CAPTURE_OPTIONS, with the standards they come from). - Once every page is taken the photo button reads «Retake» (`documentRetake`, moved from the app with its values), and the note says the photos are not sent yet (`documentNotSent`). - DocumentRequirementCard: actions take `loading`; Card.Actions wraps through its `style` (flexWrap, a spacing.x2 row gap); buttons are keyed by position, not by their label; the note sits in a polite live region that stays mounted. - Wording: es «Agregar el anverso/reverso»; the back prompt names the document, not «tu licencia». - Stories render DocumentCaptureCard itself with `pages` (front taken, ready to send, sending). Co-Authored-By: Claude Opus 5.5 --- PROJECT.md | 33 ++-- .../src/Localization/Translations/en.json | 4 +- .../src/Localization/Translations/es.json | 8 +- .../src/Partner/DocumentCaptureCard.js | 81 +++++++--- .../Partner/DocumentRequirement.stories.js | 67 ++++---- .../src/Partner/DocumentRequirementCard.js | 59 ++++--- .../__tests__/documentRequirement.test.js | 144 ++++++++++++++---- 7 files changed, 277 insertions(+), 119 deletions(-) diff --git a/PROJECT.md b/PROJECT.md index 347af33e..1095460e 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -219,8 +219,12 @@ themed through `useTheme()` so a host's theme applies: `requirementTitle(item)` (the rule's name for the market, else the catalogue's), `subtitle` is the host's, then, in its `Card.Content`, `covers` (the photos taken and not sent, in order, each `{ uri, label }` with the name a screen reader says), `note` and the rule's explanation, and `actions` - (`{ label, onPress, isDisabled?, mode?, testID? }`) as Paper `Button`s straight inside `Card.Actions`, which - keeps a `mode` given and gives the rest theirs. Without `actions` it only reads (the console). + (`{ label, onPress, isDisabled?, mode?, loading?, testID? }`) as Paper `Button`s straight inside `Card.Actions`, + which keeps a `mode` given and gives the rest theirs; `loading` is the Button's own. Without `actions` it only + reads (the console). The note sits in a polite live region (`aria-live`: Android's live region, the web's + `aria-live`) that stays mounted, so a screen reader announces each next step. `Card.Actions` gets, through its + `style`, `flexWrap` and a `spacing.x2` row gap (it does not wrap by itself; its alignment and padding stay), and + its buttons are keyed by position, as `Card.Actions` itself tells them apart (a label changes as photos are taken). - `Partner/DocumentCovers` (portable, not exported) — the card's photos: one is a `Card.Cover`; more are a Material 3 hero carousel (a horizontal `ScrollView`: `snapToInterval` on the phone, `pagingEnabled`'s CSS scroll snap on the web; items `spacing.x2` apart, the next peeking `spacing.x14`, Material's 8 dp and 56 dp). @@ -230,10 +234,19 @@ themed through `useTheme()` so a host's theme applies: `documentExpiresOn` («Expires Nov 23, 2026»): `expires_at` is a calendar day, formatted by `formatDateTime` in UTC so no reader's zone moves it. `documentExpires` stays for the app's older list. - `Partner/DocumentCaptureCard` (barrel only: the picker is native) — the card with the way to send it, as - `item.capture` says (`pages` 1, or 2 = the front then the back). Taking a photo sends nothing: the pages show - as covers; its first action, a text button, takes a photo (one taken once every page is there starts again), - and the last, «Send to review», the only one with a border (outlined) and disabled until every page is taken, - hands them to `onCapture(photos)` in order. Photos only: it offers no PDF (owner, 2026-11-04). + `item.capture` says (`pages` 1, or 2 = the front then the back). Controlled: `{ item, subtitle?, pages = [], + onPagesChange(pages), onSend(), isSending = false, testID = 'document-requirement' }` — the host owns the pages + (the picker's assets, in order) and clears them only once its send succeeded, so a failed send keeps them; the + card never clears them. Taking a photo sends nothing: the pages show as covers; its first action, a text button, + takes a photo («Add», or «Add the front»/«Add the back»; «Retake» once every page is there, when a photo starts + the document again), and the last, «Send to review», the only one with a border (outlined) and disabled until + every page is taken, calls `onSend()`. While `isSending` every action is disabled and «Send to review» shows the + Button's `loading`. The note asks for the back (`documentAddBackPrompt`) or, every page there and nothing sending, + says the photos are not sent yet (`documentNotSent`). Every photo is taken with `DOCUMENT_CAPTURE_OPTIONS`: + `maxWidth`/`maxHeight` 5,120 (an ID-1 card's PDF417 at ISO/IEC 15415's 5 px per module over AAMVA's 0.170 mm X + needs 3,597 px at 70% of the frame; an A4/Letter page at 300 ppi, 5,011 px; both bounds or the picker does not + resize), `quality` 1, `assetRepresentationMode: 'compatible'` (iOS JPEG, not HEIC) and `conversionQuality` 1 + (Android's HEIC → JPEG). Photos only: it offers no PDF (owner, 2026-11-04). - `ImagePicker.Avatar` `variant="sheet"` renders no control of its own; the caller opens the sheet with the ref's `show()`, so its own Paper `Button` can sit inside a `Card.Actions`. `avatar` and `button` are as before. Every variant: `captureOptions` (react-native-image-picker's options) are laid over the defaults (a photo, quality @@ -244,9 +257,11 @@ themed through `useTheme()` so a host's theme applies: with Settings) or any other picker error, read from its `errorCode` (`global.somethingWentWrong` / `global.tryAgainLater`). The library asks for no permission: image-picker 8 opens Android's Photo Picker and iOS's PHPicker, which need none (asking blocked Android 13+ and iOS limited access); the camera keeps its permission. - - Their fixed words (`documentAddFront`, `documentAddBack`, `documentAddBackPrompt`, `documentFront`, - `documentBack`, `documentSuperseded`) live in `Translations/*.json`; the stories - (`Partner/DocumentRequirement.stories.js`) use the local circuit's real items. + - Their fixed words (`documentAddFront`, `documentAddBack`, `documentAddBackPrompt`, `documentRetake` — moved here + from the app with its values —, `documentNotSent`, `documentFront`, `documentBack`, `documentSuperseded`, + `documentExpiresOn`) live in `Translations/*.json`, in the catalogue's «Agregar»; the stories + (`Partner/DocumentRequirement.stories.js`) use the local circuit's real items, and render the capture card itself + with `pages` for the photo states. - `Partner/viewModel.js` (barrel/portable: `PartnerViewModel`, because `statusLabel` is the Order one): the key is the package's `statusLabelKey(group, value)` resolved with `localized`; a value outside the vocabulary, or a key the registered catalogue lacks, renders the raw value. Each kind's group is read diff --git a/packages/components/src/Localization/Translations/en.json b/packages/components/src/Localization/Translations/en.json index 330ffbfc..d0982667 100644 --- a/packages/components/src/Localization/Translations/en.json +++ b/packages/components/src/Localization/Translations/en.json @@ -807,7 +807,9 @@ "documentExpired": "Expired", "documentAddFront": "Add the front", "documentAddBack": "Add the back", - "documentAddBackPrompt": "Now take a photo of the back of your licence.", + "documentAddBackPrompt": "Now take a photo of the back of the document.", + "documentRetake": "Retake", + "documentNotSent": "These photos are not sent yet. Tap «Send to review».", "documentFront": "Front", "documentBack": "Back", "documentSuperseded": "Superseded", diff --git a/packages/components/src/Localization/Translations/es.json b/packages/components/src/Localization/Translations/es.json index 9d309a6f..548b69d5 100644 --- a/packages/components/src/Localization/Translations/es.json +++ b/packages/components/src/Localization/Translations/es.json @@ -805,9 +805,11 @@ "documentExpires": "Vence", "documentExpiresOn": "Vence el %{date}", "documentExpired": "Vencido", - "documentAddFront": "Añadir el anverso", - "documentAddBack": "Añadir el reverso", - "documentAddBackPrompt": "Ahora haz una foto del reverso de tu licencia.", + "documentAddFront": "Agregar el anverso", + "documentAddBack": "Agregar el reverso", + "documentAddBackPrompt": "Ahora toma una foto del reverso del documento.", + "documentRetake": "Repetir", + "documentNotSent": "Estas fotos aún no se han enviado. Toca «Enviar a revisión».", "documentFront": "Anverso", "documentBack": "Reverso", "documentSuperseded": "Sustituido", diff --git a/packages/components/src/Partner/DocumentCaptureCard.js b/packages/components/src/Partner/DocumentCaptureCard.js index b8f54041..006953e4 100644 --- a/packages/components/src/Partner/DocumentCaptureCard.js +++ b/packages/components/src/Partner/DocumentCaptureCard.js @@ -1,34 +1,60 @@ -import React, { useRef, useState } from 'react'; +import React, { useRef } from 'react'; import ImagePickerAvatar from '../ImagePicker/ImagePickerAvatar'; import { localized } from '../Localization/Localization'; import DocumentRequirementCard from './DocumentRequirementCard'; +/** + * How every document photo is taken (react-native-image-picker options), whatever the document: the highest + * resolution any of them needs, at full quality, as JPEG. + * - 5,120 px on the long side at most. A barcode on an ID-1 card (the AAMVA driver's licence PDF417) reads at + * ISO/IEC 15415's 5 px per module over AAMVA's minimum module of 0.170 mm: 3,597 px for a card filling 70% of the + * frame; an A4 or Letter page at 300 ppi needs 5,011 px. The highest applies. The picker resizes only when both + * bounds are set, and never enlarges. + * - quality 1: no standard backs a lower one, and ICAO asks for no visible compression artefacts. + * - `compatible`: iOS hands a JPEG instead of a HEIC, which the server does not take (JPEG and PNG only); + * `conversionQuality` 1: Android converts a HEIC to JPEG at full quality. + */ +const DOCUMENT_CAPTURE_OPTIONS = Object.freeze({ + maxWidth: 5120, + maxHeight: 5120, + quality: 1, + assetRepresentationMode: 'compatible', + conversionQuality: 1, +}); + /** * Contract request #117: a document requirement's card with the way to send it, as the server says one version of it * is taken (`item.capture`, K-32): one photo, or the front and then the back (§9.8.1 step 1). Photos only (owner, * 2026-11-04): the card offers no PDF. Taking a photo sends nothing (owner, 2026-11-04): the pages taken show as the * card's covers (both sides in a carousel, owner 2026-11-04), and «Send to review» sends them once every page is - * there; then `onCapture(photos)` gets them in order (the picker's assets) and the host sends them. The photo sheet is - * the library's picker, opened by the card's own button (`variant="sheet"`). Not portable: the picker is native. + * there. The photo sheet is the library's picker, opened by the card's own button (`variant="sheet"`). Not portable: + * the picker is native. * - * @param {{item: object, subtitle?: ?string, onCapture: (photos: Array) => void, isDisabled?: boolean, - * testID?: string}} props + * Controlled: the host owns `pages` (the picker's assets, in order) and gets each change through + * `onPagesChange(pages)`. «Send to review» calls `onSend()`; the card never clears the pages itself, so a send that + * fails keeps them, and the host clears them once its send succeeds. While `isSending`, every action is disabled and + * «Send to review» shows its progress. + * + * @param {{item: object, subtitle?: ?string, pages?: Array, onPagesChange: (pages: Array) => void, + * onSend: () => void, isSending?: boolean, testID?: string}} props */ -const DocumentCaptureCard = ({ item, subtitle, onCapture, isDisabled = false, testID = 'document-requirement' }) => { +const DocumentCaptureCard = ({ + item, + subtitle, + pages = [], + onPagesChange, + onSend, + isSending = false, + testID = 'document-requirement', +}) => { const pickerRef = useRef(); - const [pages, setPages] = useState([]); const pageCount = item.capture?.pages === 2 ? 2 : 1; const twoSided = pageCount === 2; const complete = pages.length === pageCount; // A photo taken once every page is there starts the document again: that is how a wrong one is replaced. - const take = (photo) => setPages((taken) => (taken.length < pageCount ? [...taken, photo] : [photo])); - const send = () => { - const photos = pages; - setPages([]); - onCapture(photos); - }; + const take = (photo) => onPagesChange(pages.length < pageCount ? [...pages, photo] : [photo]); // What a screen reader names each photo: the front and the back of a two-sided document, else the document. const covers = pages.map((page, index) => { @@ -37,24 +63,32 @@ const DocumentCaptureCard = ({ item, subtitle, onCapture, isDisabled = false, te return { uri: page.uri, label }; }); - let addLabel = localized('add'); - if (twoSided) addLabel = localized(pages.length === 1 ? 'documentAddBack' : 'documentAddFront'); + // Once every page is there the photo button starts the document again, so it says so. + let takeLabel = localized('add'); + if (complete) takeLabel = localized('documentRetake'); + else if (twoSided) takeLabel = localized(pages.length === 1 ? 'documentAddBack' : 'documentAddFront'); + + // What to do now: the back, or — every page there and nothing sending — that the photos are not sent yet. + let note = null; + if (complete && !isSending) note = localized('documentNotSent'); + else if (twoSided && pages.length === 1) note = localized('documentAddBackPrompt'); // The way to take a photo stays, a text button; the main action, sending, is last and the only one with a border // (owner, 2026-11-04); it waits, disabled, until every page is taken. const actions = [ { - label: addLabel, + label: takeLabel, onPress: () => pickerRef.current?.show(), - isDisabled, + isDisabled: isSending, mode: 'text', testID: `${testID}-add`, }, { label: localized('sendToReview'), - onPress: send, + onPress: onSend, mode: 'outlined', - isDisabled: isDisabled || !complete, + isDisabled: isSending || !complete, + loading: isSending, testID: `${testID}-send`, }, ]; @@ -65,11 +99,16 @@ const DocumentCaptureCard = ({ item, subtitle, onCapture, isDisabled = false, te item={item} subtitle={subtitle} covers={covers} - note={twoSided && pages.length === 1 ? localized('documentAddBackPrompt') : null} + note={note} actions={actions} testID={testID} /> - + ); }; diff --git a/packages/components/src/Partner/DocumentRequirement.stories.js b/packages/components/src/Partner/DocumentRequirement.stories.js index 833e177c..320ab23d 100644 --- a/packages/components/src/Partner/DocumentRequirement.stories.js +++ b/packages/components/src/Partner/DocumentRequirement.stories.js @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useState } from 'react'; import { ScrollView, View } from 'react-native'; import { interpunct } from '@jmstechnologiesinc/commons'; @@ -162,13 +162,23 @@ const subtitleOf = (item) => const pane = { padding: MD3LightTheme.spacing.x4, gap: MD3LightTheme.spacing.x2 }; -// The app's document screen: the card with its capture, then the versions. -const Screen = ({ item }) => ( - - {}} /> - - -); +// The app's document screen: the card with its capture, then the versions. The screen owns the pages taken; a story +// sends nothing, so «Send to review» clears them as the app does once its send succeeds. +const Screen = ({ item }) => { + const [pages, setPages] = useState([]); + return ( + + setPages([])} + /> + + + ); +}; export const LicenceNothingSent = () => ; @@ -192,34 +202,25 @@ export const ReadOnlyInTheConsole = () => ( ); // What the partner has taken shows on the card before anything is sent (owner, 2026-11-04): the front waiting for the -// back, «Send to review» still disabled, then both sides ready to send, in a carousel. The covers are the partner's own photos, which a story does not have: -// empty ones show where they go. -export const LicenceFrontTaken = () => ( - - {}, mode: 'text' }, - { label: localized('sendToReview'), onPress: () => {}, isDisabled: true, mode: 'outlined' }, - ]} - /> - -); +// back, «Send to review» still disabled; both sides ready to send, in a carousel, with the note that they are not sent +// yet; and both sides on their way. The pages are the partner's own photos, which a story does not have: empty ones +// show where they go. +const PHOTO = { uri: 'data:,' }; -export const LicenceReadyToSend = () => ( +const Taken = ({ pages, isSending = false }) => ( - {}, mode: 'text' }, - { label: localized('sendToReview'), onPress: () => {}, mode: 'outlined' }, - ]} + pages={pages} + onPagesChange={() => {}} + onSend={() => {}} + isSending={isSending} /> ); + +export const LicenceFrontTaken = () => ; + +export const LicenceReadyToSend = () => ; + +export const LicenceSending = () => ; diff --git a/packages/components/src/Partner/DocumentRequirementCard.js b/packages/components/src/Partner/DocumentRequirementCard.js index 246c5a79..25e7bf2b 100644 --- a/packages/components/src/Partner/DocumentRequirementCard.js +++ b/packages/components/src/Partner/DocumentRequirementCard.js @@ -1,4 +1,5 @@ import React from 'react'; +import { View } from 'react-native'; import { MATERIAL_ICONS } from '@jmstechnologiesinc/commons'; import { Avatar, Button, Card, Text, useTheme } from '@jmstechnologiesinc/react-native-paper'; @@ -13,17 +14,17 @@ import { requirementTitle, ruleText } from './viewModel'; * - `subtitle` is what the host says of it (its vehicle and where it stands, in the host's words); * - the content is `covers`, the photos the partner has taken and not sent yet, in order (the front, then the back), * each with the `label` a screen reader names it by (one is the cover, more a carousel: DocumentCovers), then - * `note` (what to do now) and the rule's plain explanation for the market. The photos sit in the Card.Content, not - * beside it: Card.Content takes its top padding from a Card.Cover or Card.Title just above it, so one carousel - * between them would leave the text against the photos; - * - `actions` are `{ label, onPress, isDisabled?, mode?, testID? }`, Paper `Button`s straight inside `Card.Actions`, - * which keeps a `mode` given (a Paper Button mode) and gives the rest its own (the first outlined, the next - * contained). + * `note` (what to do now, announced by a screen reader when it changes) and the rule's plain explanation for the + * market. The photos sit in the Card.Content, not beside it: Card.Content takes its top padding from a Card.Cover or + * Card.Title just above it, so one carousel between them would leave the text against the photos; + * - `actions` are `{ label, onPress, isDisabled?, mode?, loading?, testID? }`, Paper `Button`s straight inside + * `Card.Actions`, which keeps a `mode` given (a Paper Button mode) and gives the rest its own (the first outlined, + * the next contained); `loading` is the Button's progress indicator. Actions that do not fit on one line wrap. * Without `actions` (the console showing what the partner sees) the card only reads. * * @param {{item: object, subtitle?: ?string, covers?: Array<{uri: string, label: string}>, note?: ?string, - * actions?: Array<{label: string, onPress: () => void, isDisabled?: boolean, mode?: string, testID?: string}>, - * testID?: string}} props + * actions?: Array<{label: string, onPress: () => void, isDisabled?: boolean, mode?: string, loading?: boolean, + * testID?: string}>, testID?: string}} props */ const DocumentRequirementCard = ({ item, @@ -51,16 +52,21 @@ const DocumentRequirementCard = ({ {hasCovers || note || explanation ? ( {hasCovers ? : null} - {/* After the photos, the space Card.Content puts after a cover; between texts, the note's. */} - {note ? ( - - {note} - - ) : null} + {/* A polite live region (Android's, and `aria-live` on the web) announces the next step. It stays + mounted, empty without a note: a region that appears together with its text is not announced + on the web. */} + + {/* After the photos, the space Card.Content puts after a cover; between texts, the note's. */} + {note ? ( + + {note} + + ) : null} + {explanation ? ( {explanation} @@ -69,9 +75,20 @@ const DocumentRequirementCard = ({ ) : null} {actions.length > 0 ? ( - - {actions.map(({ label, onPress, isDisabled, mode, testID: actionTestID }) => ( - ))} diff --git a/packages/components/src/Partner/__tests__/documentRequirement.test.js b/packages/components/src/Partner/__tests__/documentRequirement.test.js index b392ae31..a1a51caa 100644 --- a/packages/components/src/Partner/__tests__/documentRequirement.test.js +++ b/packages/components/src/Partner/__tests__/documentRequirement.test.js @@ -1,8 +1,8 @@ -import React from 'react'; +import React, { useState } from 'react'; import renderer, { act } from 'react-test-renderer'; import { EN, ES } from '@jmstechnologiesinc/partner'; -import { MD3LightTheme, Provider } from '@jmstechnologiesinc/react-native-paper'; +import { Card, MD3LightTheme, Provider } from '@jmstechnologiesinc/react-native-paper'; import { formatDateTime } from '../../Localization/format'; import { registerFlatCatalog, setI18nConfig } from '../../Localization/Localization'; @@ -11,18 +11,19 @@ import DocumentRequirementCard from '../DocumentRequirementCard'; import DocumentVersionList from '../DocumentVersionList'; import { documentVersionRow, documentVersionRows, requirementTitle } from '../viewModel'; -// The photo sheet is the native picker; here it is a stand-in that records being opened and hands back the photo a -// test gives it, through the same ref and `onChange` the card uses. -const mockPicker = { shown: 0, take: null }; +// The photo sheet is the native picker; here it is a stand-in that records being opened and the capture options it was +// given, and hands back the photo a test gives it, through the same ref and `onChange` the card uses. +const mockPicker = { shown: 0, take: null, captureOptions: null }; jest.mock('../../ImagePicker/ImagePickerAvatar', () => { const React = require('react'); - const Sheet = React.forwardRef(({ onChange }, ref) => { + const Sheet = React.forwardRef(({ onChange, captureOptions }, ref) => { React.useImperativeHandle(ref, () => ({ show: () => { mockPicker.shown += 1; }, })); mockPicker.take = onChange; + mockPicker.captureOptions = captureOptions; return null; }); return { __esModule: true, default: Sheet }; @@ -50,6 +51,7 @@ beforeAll(() => { beforeEach(() => { mockPicker.shown = 0; mockPicker.take = null; + mockPicker.captureOptions = null; }); afterEach(() => { @@ -204,6 +206,35 @@ describe('DocumentRequirementCard', () => { expect(onPress).toHaveBeenCalledTimes(1); }); + it('keeps a polite live region for the note, so a screen reader announces each next step', () => { + const liveRegionOf = (tree) => tree.root.findAll((node) => node.props['aria-live'] === 'polite')[0]; + // Mounted before there is anything to say: a region that appears together with its text is not announced. + const empty = render(); + expect(liveRegionOf(empty)).toBeDefined(); + expect(hasTestID(empty, 'document-requirement-note')).toBe(false); + + const tree = render(); + const note = liveRegionOf(tree).findAll((node) => node.props.testID === 'document-requirement-note'); + expect(note.length).toBeGreaterThan(0); + }); + + it("lets its actions wrap, keeping Card.Actions' own alignment, and shows an action in progress", () => { + const tree = render( + + ); + expect(tree.root.findByType(Card.Actions).props.style).toEqual({ + flexWrap: 'wrap', + rowGap: MD3LightTheme.spacing.x2, + }); + expect(buttonOf(tree, 'send').props).toEqual(expect.objectContaining({ loading: true, disabled: true })); + }); + it('shows both sides as a carousel that snaps item by item, the next one peeking (Material 3 hero)', () => { const { spacing } = MD3LightTheme; const tree = render( @@ -242,10 +273,29 @@ describe('DocumentVersionList', () => { }); }); +// A host as the app is one: it owns the pages, hands them to its send, and clears them only once the send succeeded. +const host = { clear: null }; +const Host = ({ item, onSend = jest.fn(), isSending = false }) => { + const [pages, setPages] = useState([]); + host.clear = () => setPages([]); + return ( + onSend(pages)} + isSending={isSending} + /> + ); +}; +const NOT_SENT = 'These photos are not sent yet. Tap «Send to review».'; +const BACK_PROMPT = 'Now take a photo of the back of the document.'; +const actionKeysOf = (tree) => tree.root.findByType(Card.Actions).props.children.map((button) => button.key); + describe('DocumentCaptureCard', () => { - it('takes one photo of a one-page document, shows it, and sends it only on «Send to review»', () => { - const onCapture = jest.fn(); - const tree = render(); + it('takes one photo of a one-page document, shows it, and hands it to the host only on «Send to review»', () => { + const onSend = jest.fn(); + const tree = render(); expect(textsOf(tree)).toEqual(expect.arrayContaining(['Add', 'Send to review'])); // Photos only (owner, 2026-11-04): no PDF, even where the server takes one. expect(textsOf(tree)).not.toContain('Upload a PDF'); @@ -257,65 +307,97 @@ describe('DocumentCaptureCard', () => { expect(mockPicker.shown).toBe(1); take({ uri: 'file:///page.jpg' }); - expect(onCapture).not.toHaveBeenCalled(); + expect(onSend).not.toHaveBeenCalled(); expect(propsOf(tree, 'document-requirement-cover-0').accessibilityLabel).toBe('Document'); - // The way to take a photo stays. - expect(textsOf(tree)).toEqual(expect.arrayContaining(['Add', 'Send to review'])); + // The way to take a photo stays, and now says it starts again; the note says nothing is sent yet. + expect(textsOf(tree)).toEqual(expect.arrayContaining(['Retake', 'Send to review', NOT_SENT])); expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(false); press(tree, 'document-requirement-send'); - expect(onCapture).toHaveBeenCalledWith([{ uri: 'file:///page.jpg' }]); + expect(onSend).toHaveBeenCalledWith([{ uri: 'file:///page.jpg' }]); + // The card never clears the pages itself: a send that fails keeps them. + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); + act(() => host.clear()); expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(false); expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(true); }); - it('keeps the front of a two-sided document, then the back, and sends both only on «Send to review»', () => { - const onCapture = jest.fn(); - const tree = render(); + it('keeps the front of a two-sided document, then the back, and hands over both on «Send to review»', () => { + const onSend = jest.fn(); + const tree = render(); expect(textsOf(tree)).toContain('Add the front'); take({ uri: 'file:///front.jpg' }); expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); - expect(textsOf(tree)).toEqual( - expect.arrayContaining(['Now take a photo of the back of your licence.', 'Add the back']) - ); + expect(textsOf(tree)).toEqual(expect.arrayContaining([BACK_PROMPT, 'Add the back'])); expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(true); take({ uri: 'file:///back.jpg' }); - expect(onCapture).not.toHaveBeenCalled(); + expect(onSend).not.toHaveBeenCalled(); expect(propsOf(tree, 'document-requirement-cover-0').accessibilityLabel).toBe('Front'); expect(propsOf(tree, 'document-requirement-cover-1').accessibilityLabel).toBe('Back'); - expect(textsOf(tree)).not.toContain('Now take a photo of the back of your licence.'); + expect(textsOf(tree)).not.toContain(BACK_PROMPT); + expect(textsOf(tree)).toEqual(expect.arrayContaining([NOT_SENT, 'Retake'])); expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(false); press(tree, 'document-requirement-send'); - expect(onCapture).toHaveBeenCalledWith([{ uri: 'file:///front.jpg' }, { uri: 'file:///back.jpg' }]); + expect(onSend).toHaveBeenCalledWith([{ uri: 'file:///front.jpg' }, { uri: 'file:///back.jpg' }]); + act(() => host.clear()); expect(textsOf(tree)).toContain('Add the front'); }); it('replaces what was taken with a photo taken once every page is there', () => { - const onCapture = jest.fn(); - const single = render(); + const onSend = jest.fn(); + const single = render(); take({ uri: 'file:///wrong.jpg' }); take({ uri: 'file:///right.jpg' }); press(single, 'document-requirement-send'); - expect(onCapture).toHaveBeenCalledWith([{ uri: 'file:///right.jpg' }]); + expect(onSend).toHaveBeenCalledWith([{ uri: 'file:///right.jpg' }]); // The sheet stand-in now hands photos to this card, the last one rendered. - const licence = render(); + const licence = render(); take({ uri: 'file:///front.jpg' }); take({ uri: 'file:///back.jpg' }); - expect(textsOf(licence)).toContain('Add the front'); + expect(textsOf(licence)).toContain('Retake'); take({ uri: 'file:///front-again.jpg' }); expect(hasTestID(licence, 'document-requirement-cover-1')).toBe(false); expect(textsOf(licence)).toContain('Add the back'); expect(buttonOf(licence, 'document-requirement-send').props.disabled).toBe(true); }); - it('disables adding and sending while the host sends', () => { - const tree = render(); + it('while the host sends, shows the progress on «Send to review», disables every action and keeps the photos', () => { + const tree = render( + + ); expect(buttonOf(tree, 'document-requirement-add').props.disabled).toBe(true); - take({ uri: 'file:///page.jpg' }); - expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(true); + expect(buttonOf(tree, 'document-requirement-send').props).toEqual( + expect.objectContaining({ disabled: true, loading: true }) + ); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); + expect(textsOf(tree)).not.toContain(NOT_SENT); + }); + + it('keys its buttons by position, so a label that changes does not remount the button', () => { + const tree = render(); + const keys = actionKeysOf(tree); + take({ uri: 'file:///front.jpg' }); + expect(actionKeysOf(tree)).toEqual(keys); + }); + + it('takes every document at the resolution its standards need, at full quality, as JPEG', () => { + render(); + expect(mockPicker.captureOptions).toEqual({ + maxWidth: 5120, + maxHeight: 5120, + quality: 1, + assetRepresentationMode: 'compatible', + conversionQuality: 1, + }); }); }); From f4112e3fc4d6478e55b0931a078eaf05879f5bed Mon Sep 17 00:00:00 2001 From: Joely Date: Wed, 4 Nov 2026 11:49:51 -0500 Subject: [PATCH 12/16] components 0.5.4 (unpublished): a document's photos open full screen, and the carousel keeps its place, shows its scrollbar on the web and gives way where both fit - Tapping a photo opens the library's DocumentViewer full screen (Paper Portal + Modal, a close action with global.close) on that page, with the sides (the covers' labels, documentFront / documentBack) for two pages. The cover keeps its label and is an image button (a button with aria-label on the web). - On the web the carousel shows its scrollbar: a mouse has no swipe. - The item the carousel rests on is followed from the scroll position; a new width (rotation, resize) scrolls back to it. - Where the measured width fits every cover at Material's largest large item (twice the cover's height) plus the gap, they show whole, side by side, without a carousel. Co-Authored-By: Claude Opus 5.5 --- PROJECT.md | 10 +- .../components/src/Partner/DocumentCovers.js | 183 ++++++++++++++---- .../__tests__/documentRequirement.test.js | 106 ++++++++-- 3 files changed, 243 insertions(+), 56 deletions(-) diff --git a/PROJECT.md b/PROJECT.md index 1095460e..7a9c274f 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -227,7 +227,15 @@ themed through `useTheme()` so a host's theme applies: its buttons are keyed by position, as `Card.Actions` itself tells them apart (a label changes as photos are taken). - `Partner/DocumentCovers` (portable, not exported) — the card's photos: one is a `Card.Cover`; more are a Material 3 hero carousel (a horizontal `ScrollView`: `snapToInterval` on the phone, `pagingEnabled`'s CSS scroll - snap on the web; items `spacing.x2` apart, the next peeking `spacing.x14`, Material's 8 dp and 56 dp). + snap on the web; items `spacing.x2` apart, the next peeking `spacing.x14`, Material's 8 dp and 56 dp), or all whole + side by side where the measured width fits them at Material's largest large item (twice the cover's height, which + the first cover reports, plus the gap). On the web the carousel's scrollbar shows (a mouse has no swipe). The item + it rests on is followed from `onScroll`, and a new width (rotation, resize) scrolls back to it. Each photo is an + image button (`imagebutton`; `button` + `aria-label` on the web, where react-native-web maps no role for it) named + by its `label`; it opens `DocumentViewer` full screen (Paper `Portal` + `Modal`, its height the window's between + the safe-area insets; the internal `SheetHeader` with its `global.close`) on that page, with the document's sides + (the covers' labels) when there are two. testIDs: `-covers`, `-carousel`, `-cover-`, `-viewer`, + `-viewer-header-close`, `-viewer-document`. - `Partner/DocumentVersionList` (portable) — `item.versions` as `ListRow`s from `documentVersionRows`; they open nothing, so no chevron. A row's description: when it was sent, the scan's catalogue label while the scan is not `SCAN_STATUS.CLEAN` (pending, and partner 0.2.54's infected, never spelled here), the details code's label, and diff --git a/packages/components/src/Partner/DocumentCovers.js b/packages/components/src/Partner/DocumentCovers.js index 07f147a9..f198081b 100644 --- a/packages/components/src/Partner/DocumentCovers.js +++ b/packages/components/src/Partner/DocumentCovers.js @@ -1,58 +1,163 @@ -import React, { useState } from 'react'; -import { ScrollView, View } from 'react-native'; +import React, { useEffect, useRef, useState } from 'react'; +import { ScrollView, View, useWindowDimensions } from 'react-native'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; -import { Card, useTheme } from '@jmstechnologiesinc/react-native-paper'; +import { Card, Modal, Portal, TouchableRipple, useTheme } from '@jmstechnologiesinc/react-native-paper'; + +import { accessibilityProps, isWeb } from '../accessibility'; +import DocumentViewer from '../DocumentViewer/DocumentViewer'; +import SheetHeader from '../Layout/SheetHeader'; +import { localized } from '../Localization/Localization'; /** - * The photos of a document the partner has taken and not sent yet (DocumentRequirementCard `covers`), in order: one is - * the card's cover; more are a Material 3 hero carousel, one large item with the next one peeking. Its measures are - * Material's (material-components-android carousel): it snaps to an item, items stand 8 dp apart, and the item that - * peeks is a small item of at most 56 dp (`m3_carousel_small_item_size_max`), here the theme's `spacing.x2` and - * `spacing.x14`. The large item is what the measured width leaves. + * Two covers or more: a Material 3 hero carousel, one large item with the next one peeking, or all of them whole, side + * by side, where the width fits them at Material's largest large item (twice as wide as the cover is tall, the + * cover's height measured from the first one). * - * Paper has no carousel, so a horizontal ScrollView snaps item by item: on iOS and Android by `snapToInterval`, which - * overrides `pagingEnabled` there, and on the web by `pagingEnabled`, the one snapping prop react-native-web - * implements (CSS scroll snap). Each photo is an image a screen reader names by its `label`. + * The carousel's measures are Material's (material-components-android carousel): it snaps to an item, items stand + * 8 dp apart, and the item that peeks is a small item of at most 56 dp (`m3_carousel_small_item_size_max`), here the + * theme's `spacing.x2` and `spacing.x14`. The large item is what the measured width leaves. Paper has no carousel, so + * a horizontal ScrollView snaps item by item: on iOS and Android by `snapToInterval`, which overrides `pagingEnabled` + * there, and on the web by `pagingEnabled`, the one snapping prop react-native-web implements (CSS scroll snap). On + * the web its scrollbar shows: a mouse has no swipe, and the scrollbar is its way to the next item. The item it rests + * on is followed from the scroll position, so a new width (a rotation, a resized window) scrolls back to it. + */ +const CoverCarousel = ({ covers, renderCover, testID }) => { + const { spacing } = useTheme(); + const [width, setWidth] = useState(0); + const [coverHeight, setCoverHeight] = useState(0); + const carouselRef = useRef(null); + const restingItem = useRef(0); + + const gap = spacing.x2; + // Until the carousel is measured its items are 0 wide; their height is the cover's, so nothing below moves. + const itemWidth = Math.max(0, width - spacing.x14 - gap); + const interval = itemWidth + gap; + // An item rests where it starts, but the scroll view stops at its end, where the last item shows whole and the + // one before it peeks. + const lastOffset = Math.max(0, covers.length * interval - gap - width); + const restOf = (index) => Math.min(index * interval, lastOffset); + const itemAt = (offset) => + covers.reduce( + (nearest, _cover, index) => + Math.abs(restOf(index) - offset) < Math.abs(restOf(nearest) - offset) ? index : nearest, + 0 + ); + + const largeItemMax = 2 * coverHeight; + const fitWhole = coverHeight > 0 && width >= covers.length * largeItemMax + (covers.length - 1) * gap; + + // `restOf` changes only with these two. + useEffect(() => { + carouselRef.current?.scrollTo({ x: restOf(restingItem.current), animated: false }); + }, [interval, lastOffset]); + + const measureCover = (event) => setCoverHeight(event.nativeEvent.layout.height); + const coversAt = (coverWidth) => + covers.map((cover, index) => + renderCover(cover, index, { + style: { width: coverWidth }, + onLayout: index === 0 ? measureCover : undefined, + }) + ); + + return ( + setWidth(event.nativeEvent.layout.width)} testID={`${testID}-covers`}> + {fitWhole ? ( + {coversAt(largeItemMax)} + ) : ( + { + restingItem.current = itemAt(event.nativeEvent.contentOffset.x); + }} + // Every event (16 ms or less turns throttling off on the phone): the handler only notes an index. + // react-native-web, without it, reports only the first one. + scrollEventThrottle={16} + contentContainerStyle={{ gap }} + testID={`${testID}-carousel`} + > + {coversAt(itemWidth)} + + )} + + ); +}; + +/** + * The photos of a document the partner has taken and not sent yet (DocumentRequirementCard `covers`), in order: one is + * the card's cover; more are a carousel, or side by side where they fit (CoverCarousel). Each photo is an image button + * a screen reader names by its `label`: it opens the library's DocumentViewer full screen, on that page, to check it + * before sending (zoom, rotation, and the sides of a two-page document, named by their labels). * * @param {{covers: Array<{uri: string, label: string}>, testID: string}} props */ const DocumentCovers = ({ covers, testID }) => { - const { spacing } = useTheme(); - const [width, setWidth] = useState(0); + const { colors } = useTheme(); + const window = useWindowDimensions(); + const insets = useSafeAreaInsets(); + const [viewing, setViewing] = useState(false); + const [page, setPage] = useState(0); - const coverOf = ({ uri, label }, index, style) => ( - { + setPage(index); + setViewing(true); + }; + const close = () => setViewing(false); + const shown = covers[page] ?? covers[0]; + const sides = covers.length > 1 ? covers.map(({ label }, index) => ({ value: String(index), label })) : undefined; + + // react-native-web gives `imagebutton` no web role; there an image that opens is a button named by its label. + const renderCover = ({ uri, label }, index, props) => ( + open(index)} + {...accessibilityProps({ role: isWeb() ? 'button' : 'imagebutton', label })} + {...props} testID={`${testID}-cover-${index}`} > - + ); - if (covers.length < 2) return covers.map((cover, index) => coverOf(cover, index)); - - const gap = spacing.x2; - // Until the carousel is measured its items are 0 wide; their height is the cover's, so nothing below moves. - const itemWidth = Math.max(0, width - spacing.x14 - gap); return ( - setWidth(event.nativeEvent.layout.width)} - pagingEnabled - snapToInterval={itemWidth + gap} - snapToAlignment="start" - decelerationRate="fast" - disableIntervalMomentum - showsHorizontalScrollIndicator={false} - contentContainerStyle={{ gap }} - testID={`${testID}-covers`} - > - {covers.map((cover, index) => coverOf(cover, index, { width: itemWidth }))} - + <> + {covers.length < 2 ? ( + covers.map((cover, index) => renderCover(cover, index)) + ) : ( + + )} + + + + setPage(Number(value))} + testID={`${testID}-viewer-document`} + /> + + + ); }; diff --git a/packages/components/src/Partner/__tests__/documentRequirement.test.js b/packages/components/src/Partner/__tests__/documentRequirement.test.js index a1a51caa..59ecc141 100644 --- a/packages/components/src/Partner/__tests__/documentRequirement.test.js +++ b/packages/components/src/Partner/__tests__/documentRequirement.test.js @@ -1,4 +1,5 @@ import React, { useState } from 'react'; +import { Platform, ScrollView } from 'react-native'; import renderer, { act } from 'react-test-renderer'; import { EN, ES } from '@jmstechnologiesinc/partner'; @@ -59,6 +60,7 @@ afterEach(() => { mounted.splice(0).forEach((tree) => tree.unmount()); jest.runOnlyPendingTimers(); }); + jest.restoreAllMocks(); }); // Every string a host Text renders, in order. @@ -97,6 +99,17 @@ const LICENCE = { versions: [], }; const AT = 1793249082020; +const BOTH_SIDES = [ + { uri: 'file:///front.jpg', label: 'Front' }, + { uri: 'file:///back.jpg', label: 'Back' }, +]; +// The cover's height, as the first cover reports it (Card.Cover's own), and the width the covers are laid out in. +const COVER_HEIGHT = 195; +const layOut = (tree, width) => + act(() => { + propsOf(tree, 'document-requirement-cover-0').onLayout({ nativeEvent: { layout: { height: COVER_HEIGHT } } }); + propsOf(tree, 'document-requirement-covers').onLayout({ nativeEvent: { layout: { width } } }); + }); describe('requirementTitle', () => { it("is the rule's own name for the market, in the reader's language", () => { @@ -197,7 +210,7 @@ describe('DocumentRequirementCard', () => { /> ); expect(propsOf(tree, 'document-requirement-cover-0')).toEqual( - expect.objectContaining({ accessible: true, accessibilityRole: 'image', accessibilityLabel: 'Front' }) + expect.objectContaining({ accessibilityRole: 'imagebutton', accessibilityLabel: 'Front' }) ); // One photo is the cover, not a carousel. expect(hasTestID(tree, 'document-requirement-covers')).toBe(false); @@ -237,28 +250,89 @@ describe('DocumentRequirementCard', () => { it('shows both sides as a carousel that snaps item by item, the next one peeking (Material 3 hero)', () => { const { spacing } = MD3LightTheme; - const tree = render( - - ); - const carousel = propsOf(tree, 'document-requirement-covers'); - expect(carousel).toEqual( - expect.objectContaining({ horizontal: true, pagingEnabled: true, decelerationRate: 'fast' }) + const tree = render(); + expect(propsOf(tree, 'document-requirement-carousel')).toEqual( + expect.objectContaining({ + horizontal: true, + pagingEnabled: true, + decelerationRate: 'fast', + showsHorizontalScrollIndicator: false, + }) ); expect(propsOf(tree, 'document-requirement-cover-0').accessibilityLabel).toBe('Front'); expect(propsOf(tree, 'document-requirement-cover-1').accessibilityLabel).toBe('Back'); - act(() => carousel.onLayout({ nativeEvent: { layout: { width: 400 } } })); + layOut(tree, 400); // The large item is what the width leaves after the small item that peeks (56 dp) and the gap (8 dp). const itemWidth = 400 - spacing.x14 - spacing.x2; expect(propsOf(tree, 'document-requirement-cover-0').style).toEqual({ width: itemWidth }); - expect(propsOf(tree, 'document-requirement-covers').snapToInterval).toBe(itemWidth + spacing.x2); - expect(propsOf(tree, 'document-requirement-covers').contentContainerStyle).toEqual({ gap: spacing.x2 }); + expect(propsOf(tree, 'document-requirement-carousel').snapToInterval).toBe(itemWidth + spacing.x2); + expect(propsOf(tree, 'document-requirement-carousel').contentContainerStyle).toEqual({ gap: spacing.x2 }); + }); + + it('scrolls back to the item it rested on when its width changes', () => { + const { spacing } = MD3LightTheme; + const tree = render(); + layOut(tree, 400); + // At its end the carousel rests with the back whole and the front peeking. + const interval = 400 - spacing.x14; + act(() => + propsOf(tree, 'document-requirement-carousel').onScroll({ + nativeEvent: { contentOffset: { x: 2 * interval - spacing.x2 - 400 } }, + }) + ); + const { scrollTo } = tree.root.findAllByType(ScrollView)[0].instance; + scrollTo.mockClear(); + + layOut(tree, 600); + const wider = 600 - spacing.x14; + expect(scrollTo).toHaveBeenCalledWith({ x: 2 * wider - spacing.x2 - 600, animated: false }); + }); + + it('shows both sides whole, without a carousel, where they fit at the largest large item', () => { + const { spacing } = MD3LightTheme; + const tree = render(); + // Twice as wide as the cover is tall, each, and the gap between them. + layOut(tree, 2 * (2 * COVER_HEIGHT) + spacing.x2); + expect(hasTestID(tree, 'document-requirement-carousel')).toBe(false); + expect(propsOf(tree, 'document-requirement-cover-0').style).toEqual({ width: 2 * COVER_HEIGHT }); + expect(propsOf(tree, 'document-requirement-cover-1').style).toEqual({ width: 2 * COVER_HEIGHT }); + }); + + it('on the web, shows the scrollbar and makes each photo a button named by its label', () => { + jest.replaceProperty(Platform, 'OS', 'web'); + const tree = render(); + expect(propsOf(tree, 'document-requirement-carousel').showsHorizontalScrollIndicator).toBe(true); + expect(propsOf(tree, 'document-requirement-cover-1')).toEqual( + expect.objectContaining({ role: 'button', 'aria-label': 'Back' }) + ); + }); + + it('opens a photo full screen in the document viewer, on its side, before anything is sent', () => { + const tree = render(); + expect(propsOf(tree, 'document-requirement-viewer').visible).toBe(false); + + press(tree, 'document-requirement-cover-1'); + expect(propsOf(tree, 'document-requirement-viewer').visible).toBe(true); + const viewer = propsOf(tree, 'document-requirement-viewer-document'); + expect(viewer.source).toEqual({ uri: 'file:///back.jpg' }); + expect(viewer.sides.map(({ label }) => label)).toEqual(['Front', 'Back']); + + act(() => viewer.onSideChange(viewer.sides[0].value)); + expect(propsOf(tree, 'document-requirement-viewer-document').source).toEqual({ uri: 'file:///front.jpg' }); + + press(tree, 'document-requirement-viewer-header-close'); + expect(propsOf(tree, 'document-requirement-viewer').visible).toBe(false); + }); + + it('opens a one-page document with no sides to choose', () => { + const tree = render( + + ); + press(tree, 'document-requirement-cover-0'); + const viewer = propsOf(tree, 'document-requirement-viewer-document'); + expect(viewer.source).toEqual({ uri: 'file:///page.jpg' }); + expect(viewer.sides).toBeUndefined(); }); }); From 545acd5bf6b5d0a39186c6e84a315ff0eb6c6239 Mon Sep 17 00:00:00 2001 From: Joely Date: Wed, 4 Nov 2026 11:50:31 -0500 Subject: [PATCH 13/16] components 0.5.4 (unpublished): a pick that ends after its sheet is gone does not throw The picker resolves after its own screen closes; by then the caller may have unmounted the sheet, so closing it is guarded. Co-Authored-By: Claude Opus 5.5 --- packages/components/src/ImagePicker/ImagePickerAvatar.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/components/src/ImagePicker/ImagePickerAvatar.js b/packages/components/src/ImagePicker/ImagePickerAvatar.js index 5ce7a8e9..9254faf4 100644 --- a/packages/components/src/ImagePicker/ImagePickerAvatar.js +++ b/packages/components/src/ImagePicker/ImagePickerAvatar.js @@ -62,14 +62,15 @@ const Avatar = forwardRef(function Avatar( }); }, []); - // The sheet stays open after a pick cancelled or refused, so another source can be chosen. + // The sheet stays open after a pick cancelled or refused, so another source can be chosen. The pick ends after the + // picker's own screen closes, by when the caller may have taken this sheet away. const launch = async (pick) => { launching.current = true; try { const asset = await pick(); if (asset) { onChange(asset); - actionSheetRef.current.hide(); + actionSheetRef.current?.hide(); } } finally { launching.current = false; From 686894f728b08c32220726cf054870bf03705641 Mon Sep 17 00:00:00 2001 From: Joely Date: Wed, 4 Nov 2026 17:08:57 -0500 Subject: [PATCH 14/16] components 0.5.4 (unpublished): a version's row names it by its date and opens with its state, and a reviewer reads the staff's labels (contract request #118) - documentVersionRow: the title is when it was sent; the description opens with its state, in the cause's words, as a requirement's row does. - staffDetailsCodeLabel and staffScanLabel; the rule's clause for what the partner reads. - The pure row tests move to their own suite, which needs no native module. Co-Authored-By: Claude Opus 5.5 --- .../Partner/DocumentRequirement.stories.js | 4 + .../src/Partner/DocumentVersionList.js | 6 +- .../__tests__/documentRequirement.test.js | 66 +---------- .../__tests__/documentVersionRow.test.js | 105 ++++++++++++++++++ packages/components/src/Partner/viewModel.js | 35 ++++-- 5 files changed, 138 insertions(+), 78 deletions(-) create mode 100644 packages/components/src/Partner/__tests__/documentVersionRow.test.js diff --git a/packages/components/src/Partner/DocumentRequirement.stories.js b/packages/components/src/Partner/DocumentRequirement.stories.js index 320ab23d..baaa4c3e 100644 --- a/packages/components/src/Partner/DocumentRequirement.stories.js +++ b/packages/components/src/Partner/DocumentRequirement.stories.js @@ -68,6 +68,7 @@ const INSPECTION_DUE_SOON = { versions: [ { versionId: '6WoqFfmibiFIgv6Ko6nh', + cause: 'satisfied', verification: { status: 'verified' }, expires_at: '2026-11-23', scan: { status: 'clean' }, @@ -91,6 +92,7 @@ const INSURANCE_WITH_HISTORY = { versions: [ { versionId: '3p9wgxM49qaibuOFC9KT', + cause: 'satisfied', verification: { status: 'verified' }, expires_at: '2029-12-31', scan: { status: 'clean' }, @@ -120,6 +122,7 @@ const INSURANCE_JUST_SENT = { versions: [ { versionId: 'kOFizggUFsNliTITk3fW', + cause: 'pending_review', verification: { status: 'pending' }, scan: { status: 'pending' }, submittedTime: 1793675729952, @@ -144,6 +147,7 @@ const DPU_CERTIFICATE = { versions: [ { versionId: 'yzu7Y8MIxmmwb7jHFseI', + cause: 'satisfied', verification: { status: 'verified' }, expires_at: '2029-12-31', scan: { status: 'clean' }, diff --git a/packages/components/src/Partner/DocumentVersionList.js b/packages/components/src/Partner/DocumentVersionList.js index 74d633c9..e002cf3c 100644 --- a/packages/components/src/Partner/DocumentVersionList.js +++ b/packages/components/src/Partner/DocumentVersionList.js @@ -8,9 +8,9 @@ import { documentVersionRows } from './viewModel'; /** * Contract request #117: a document requirement's versions as the server sent them (`checklistItem.versions`, newest - * first), one `ListRow` (a Paper `List.Item`) each: the version's state is the title, when it was sent and what the - * server says of it the description. The rows are the view model's (`documentVersionRows`) and open nothing, so they - * carry no chevron. No versions, no list. + * first), one `ListRow` (a Paper `List.Item`) each: when it was sent is the title, its state and what the server says + * of it the description. The rows are the view model's (`documentVersionRows`) and open nothing, so they carry no + * chevron. No versions, no list. * * @param {{versions: ?Array, accessibilityLabel: string, testID?: string}} props * `accessibilityLabel` names the list (the requirement it belongs to); each row's testID is `-` diff --git a/packages/components/src/Partner/__tests__/documentRequirement.test.js b/packages/components/src/Partner/__tests__/documentRequirement.test.js index 59ecc141..78a4f8bf 100644 --- a/packages/components/src/Partner/__tests__/documentRequirement.test.js +++ b/packages/components/src/Partner/__tests__/documentRequirement.test.js @@ -5,12 +5,11 @@ import renderer, { act } from 'react-test-renderer'; import { EN, ES } from '@jmstechnologiesinc/partner'; import { Card, MD3LightTheme, Provider } from '@jmstechnologiesinc/react-native-paper'; -import { formatDateTime } from '../../Localization/format'; import { registerFlatCatalog, setI18nConfig } from '../../Localization/Localization'; import DocumentCaptureCard from '../DocumentCaptureCard'; import DocumentRequirementCard from '../DocumentRequirementCard'; import DocumentVersionList from '../DocumentVersionList'; -import { documentVersionRow, documentVersionRows, requirementTitle } from '../viewModel'; +import { requirementTitle } from '../viewModel'; // The photo sheet is the native picker; here it is a stand-in that records being opened and the capture options it was // given, and hands back the photo a test gives it, through the same ref and `onChange` the card uses. @@ -124,69 +123,6 @@ describe('requirementTitle', () => { }); }); -describe('documentVersionRows', () => { - it('titles a version by its verification, or as superseded, and says only what the version says', () => { - const rows = documentVersionRows([ - { versionId: 'v3', verification: { status: 'pending' }, scan: { status: 'pending' }, submittedTime: AT }, - { - versionId: 'v2', - verification: { status: 'verified' }, - expires_at: '2026-11-23', - scan: { status: 'clean' }, - submittedTime: AT, - }, - { - versionId: 'v1', - verification: { status: 'unverified', details_code: 'document_not_readable' }, - scan: { status: 'clean' }, - supersededBy: 'v2', - submittedTime: AT, - }, - ]); - const sent = formatDateTime(AT); - expect(rows).toEqual([ - { - key: 'v3', - title: EN['partner.verification_status.pending'], - description: `${sent} · ${EN['partner.scan_status.pending']}`, - }, - { - key: 'v2', - title: EN['partner.verification_status.verified'], - // The calendar day the server sent, in the app's locale, in no reader's zone. - description: `${sent} · Expires Nov 23, 2026`, - }, - { - key: 'v1', - title: 'Superseded', - description: `${sent} · ${EN['partner.details_code.document_not_readable']}`, - }, - ]); - }); - - it('says the scan of a version while it is not clean, by its catalogue label', () => { - // `infected` is partner 0.2.54's (O-10); before it, the view model shows the raw value it does not know. - const infected = EN['partner.scan_status.infected'] ?? 'infected'; - const row = documentVersionRow({ - versionId: 'v4', - verification: { status: 'unverified' }, - scan: { status: 'infected' }, - submittedTime: AT, - }); - expect(row.description).toBe(`${formatDateTime(AT)} · ${infected}`); - }); - - it('has no rows without versions', () => { - expect(documentVersionRows(undefined)).toEqual([]); - expect(documentVersionRows([])).toEqual([]); - }); - - it('is one version row for every page that lists versions', () => { - const version = { versionId: 'v2', verification: { status: 'verified' }, expires_at: '2026-11-23' }; - expect(documentVersionRow(version)).toEqual(documentVersionRows([version])[0]); - }); -}); - describe('DocumentRequirementCard', () => { it("reads the rule's name, the host's subtitle and the rule's explanation, and offers nothing by itself", () => { const tree = render(); diff --git a/packages/components/src/Partner/__tests__/documentVersionRow.test.js b/packages/components/src/Partner/__tests__/documentVersionRow.test.js new file mode 100644 index 00000000..b53a17d4 --- /dev/null +++ b/packages/components/src/Partner/__tests__/documentVersionRow.test.js @@ -0,0 +1,105 @@ +// A document version's list row and the labels a reviewer reads: pure, with the package's catalogue registered as a +// host does (no native module, so this suite runs on its own). +jest.mock('react-native-localize', () => ({ + findBestLanguageTag: jest.fn(() => ({ languageTag: 'en', isRTL: false })), +})); + +import { EN, ES } from '@jmstechnologiesinc/partner'; + +import { formatDateTime } from '../../Localization/format'; +import { registerFlatCatalog, setI18nConfig } from '../../Localization/Localization'; +import { + detailsCodeLabel, + documentVersionRow, + documentVersionRows, + staffDetailsCodeLabel, + staffScanLabel, +} from '../viewModel'; + +const AT = 1793249082020; + +beforeAll(() => { + setI18nConfig(); + registerFlatCatalog({ en: EN, es: ES }); +}); + +describe('documentVersionRows', () => { + it('titles a version by when it was sent, and opens its description with its state, in the cause\'s words', () => { + const rows = documentVersionRows([ + { + versionId: 'v3', + cause: 'pending_review', + verification: { status: 'pending' }, + scan: { status: 'pending' }, + submittedTime: AT, + }, + { + versionId: 'v2', + cause: 'expiring_within_notice', + verification: { status: 'verified' }, + expires_at: '2026-11-23', + scan: { status: 'clean' }, + submittedTime: AT, + }, + { + versionId: 'v1', + verification: { status: 'unverified', details_code: 'document_not_readable' }, + scan: { status: 'clean' }, + supersededBy: 'v2', + submittedTime: AT, + }, + ]); + const sent = formatDateTime(AT); + expect(rows).toEqual([ + { + key: 'v3', + title: sent, + description: `${EN['partner.requirement_cause.pending_review']} · ${EN['partner.scan_status.pending']}`, + }, + { + key: 'v2', + title: sent, + // The calendar day the server sent, in the app's locale, in no reader's zone. + description: `${EN['partner.requirement_cause.expiring_within_notice']} · Expires Nov 23, 2026`, + }, + { + key: 'v1', + title: sent, + description: `Superseded · ${EN['partner.details_code.document_not_readable']}`, + }, + ]); + }); + + it('never names a version by its verification: that is the reviewer\'s word', () => { + const row = documentVersionRow({ versionId: 'v2', verification: { status: 'verified' }, submittedTime: AT }); + expect(row).toEqual({ key: 'v2', title: formatDateTime(AT), description: '' }); + }); + + it('says the scan of a version while it is not clean, by its catalogue label', () => { + const row = documentVersionRow({ + versionId: 'v4', + verification: { status: 'pending' }, + scan: { status: 'infected' }, + submittedTime: AT, + }); + expect(row.description).toBe(EN['partner.scan_status.infected']); + }); + + it('has no rows without versions', () => { + expect(documentVersionRows(undefined)).toEqual([]); + expect(documentVersionRows([])).toEqual([]); + }); + + it('is one version row for every page that lists versions', () => { + const version = { versionId: 'v2', cause: 'satisfied', expires_at: '2026-11-23' }; + expect(documentVersionRow(version)).toEqual(documentVersionRows([version])[0]); + }); +}); + +describe('staff labels (owner, 2026-11-04)', () => { + it('a reviewer reads a code and a scan in the staff\'s words, the partner keeps hers', () => { + expect(staffDetailsCodeLabel('document_failed_copy')).toBe(EN['partner.details_code_staff.document_failed_copy']); + expect(detailsCodeLabel('document_failed_copy')).toBe(EN['partner.details_code.document_failed_copy']); + expect(staffScanLabel('infected')).toBe(EN['partner.scan_status_staff.infected']); + }); +}); diff --git a/packages/components/src/Partner/viewModel.js b/packages/components/src/Partner/viewModel.js index a4cde10c..ff702370 100644 --- a/packages/components/src/Partner/viewModel.js +++ b/packages/components/src/Partner/viewModel.js @@ -97,6 +97,12 @@ const GROUP = Object.freeze({ scan: groupOf(SCAN_STATUS), }); +// A vocabulary labelled twice, once per audience: the partner's group is the one `groupOf` finds, these the staff's. +const STAFF_GROUP = Object.freeze({ + detailsCode: 'details_code_staff', + scan: 'scan_status_staff', +}); + const { success, warning, danger, neutral, info } = STATUS_TONES; /** @@ -231,9 +237,15 @@ export const requirementLabel = (key) => { return labelOf(GROUP.requirement, key, member); }; -/** The label of a Stripe `details_code` (canon §7.4). */ +/** The label of a Stripe `details_code` (canon §7.4), in the words the partner reads. */ export const detailsCodeLabel = (code) => labelOf(GROUP.detailsCode, code); +/** The same code in the words a reviewer reads (owner, 2026-11-04: each audience its own text). */ +export const staffDetailsCodeLabel = (code) => labelOf(STAFF_GROUP.detailsCode, code); + +/** A version's scan in the words a reviewer reads. */ +export const staffScanLabel = (scan) => labelOf(STAFF_GROUP.scan, scan); + /** The label of a `disabled_reason` (canon §7.2); the values are dotted, and * the flat catalogue resolves them by exact match. */ export const reasonLabel = (reason) => labelOf(GROUP.disabledReason, reason); @@ -299,6 +311,11 @@ export const CLAUSE_VALUE_KIND = Object.freeze({ export const RULE_CLAUSE_PRESENTATION = Object.freeze([ { clause: RULE_CLAUSE.LABEL, kind: CLAUSE_VALUE_KIND.RULE_TEXT, valueOf: (rule) => rule.label }, { clause: RULE_CLAUSE.EXPLANATION, kind: CLAUSE_VALUE_KIND.RULE_TEXT, valueOf: (rule) => rule.explanation }, + { + clause: RULE_CLAUSE.PARTNER_EXPLANATION, + kind: CLAUSE_VALUE_KIND.RULE_TEXT, + valueOf: (rule) => rule.partnerExplanation, + }, { clause: RULE_CLAUSE.EVIDENCE, kind: CLAUSE_VALUE_KIND.LABEL, @@ -398,21 +415,19 @@ export const requirementTitle = (item) => ruleText(item?.label) ?? requirementLa const CALENDAR_DAY = Object.freeze({ dateStyle: 'medium', timeZone: 'UTC' }); /** - * One document version as the server sends it, as a list row `{ key, title, description }`, the same on every page that - * lists versions (a requirement's history, the documents list). The title is the version's state: «Superseded» once a - * newer one replaced it, else its verification's label. The description is when it was sent (in the app's locale), - * its scan while it is not clean (being scanned, or quarantined), why it was not accepted and until when it counts - * (that day, in the app's locale) — each only when the version says it. + * One document version as the server sends it, as a list row `{ key, title, description }`, in the shape of a + * requirement's row (owner, 2026-11-04): the title names it, by when it was sent (in the app's locale), and the + * description opens with its state, in the words of a requirement's cause — «Superseded» once a newer one replaced it, + * else the `cause` the server sends with it. Then its scan while it is not clean (being scanned, or quarantined), why it + * was not accepted and until when it counts (that day, in the app's locale) — each only when the version says it. */ export const documentVersionRow = (version) => { const scan = version.scan?.status; return { key: version.versionId, - title: version.supersededBy - ? localized('documentSuperseded') - : statusLabel('verification', version.verification?.status), + title: formatDateTime(version.submittedTime), description: interpunct([ - formatDateTime(version.submittedTime), + version.supersededBy ? localized('documentSuperseded') : statusLabel('requirement_cause', version.cause), scan && scan !== SCAN_STATUS.CLEAN ? labelOf(GROUP.scan, scan) : null, detailsCodeLabel(version.verification?.details_code), version.expires_at From 8a04c09726fb2cbe025253a323a9da289ae51d7a Mon Sep 17 00:00:00 2001 From: Joely Date: Wed, 4 Nov 2026 17:44:39 -0500 Subject: [PATCH 15/16] components 0.5.4 (unpublished): the document card only sends, and says nothing of where the requirement stands Its subtitle names the vehicle; a version's row and the requirement's list row say the state. Co-Authored-By: Claude Opus 5.5 --- .../components/src/Partner/DocumentCaptureCard.js | 5 +++-- .../src/Partner/DocumentRequirement.stories.js | 15 +++++---------- .../src/Partner/DocumentRequirementCard.js | 2 +- 3 files changed, 9 insertions(+), 13 deletions(-) diff --git a/packages/components/src/Partner/DocumentCaptureCard.js b/packages/components/src/Partner/DocumentCaptureCard.js index 006953e4..d13610a8 100644 --- a/packages/components/src/Partner/DocumentCaptureCard.js +++ b/packages/components/src/Partner/DocumentCaptureCard.js @@ -28,8 +28,9 @@ const DOCUMENT_CAPTURE_OPTIONS = Object.freeze({ * is taken (`item.capture`, K-32): one photo, or the front and then the back (§9.8.1 step 1). Photos only (owner, * 2026-11-04): the card offers no PDF. Taking a photo sends nothing (owner, 2026-11-04): the pages taken show as the * card's covers (both sides in a carousel, owner 2026-11-04), and «Send to review» sends them once every page is - * there. The photo sheet is the library's picker, opened by the card's own button (`variant="sheet"`). Not portable: - * the picker is native. + * there. The card only sends (owner, 2026-11-04): it says nothing of where the requirement stands, which its versions + * and its row in the lists say. The photo sheet is the library's picker, opened by the card's own button + * (`variant="sheet"`). Not portable: the picker is native. * * Controlled: the host owns `pages` (the picker's assets, in order) and gets each change through * `onPagesChange(pages)`. «Send to review» calls `onSend()`; the card never clears the pages itself, so a send that diff --git a/packages/components/src/Partner/DocumentRequirement.stories.js b/packages/components/src/Partner/DocumentRequirement.stories.js index baaa4c3e..d32b7a76 100644 --- a/packages/components/src/Partner/DocumentRequirement.stories.js +++ b/packages/components/src/Partner/DocumentRequirement.stories.js @@ -1,15 +1,14 @@ import React, { useState } from 'react'; import { ScrollView, View } from 'react-native'; -import { interpunct } from '@jmstechnologiesinc/commons'; -import { EN, ES, REQUIREMENT_CAUSE, formatVehicleValue, vehicleValueParts } from '@jmstechnologiesinc/partner'; +import { EN, ES, formatVehicleValue, vehicleValueParts } from '@jmstechnologiesinc/partner'; import { MD3LightTheme } from '@jmstechnologiesinc/react-native-paper'; import { localized, registerFlatCatalog, setI18nConfig } from '../Localization/Localization'; import DocumentCaptureCard from './DocumentCaptureCard'; import DocumentRequirementCard from './DocumentRequirementCard'; import DocumentVersionList from './DocumentVersionList'; -import { requirementTitle, statusLabel } from './viewModel'; +import { requirementTitle } from './viewModel'; // The library's own words, then the `partner.*` catalogue, which belongs to `@jmstechnologiesinc/partner` (R2): a // host sets both up once, as here. @@ -156,13 +155,9 @@ const DPU_CERTIFICATE = { ], }; -// The subtitle is the host's: the app names the vehicle and where the requirement stands, but not `missing` (its add -// control says it; owner, 2026-11-03). The stories say it the same way. -const subtitleOf = (item) => - interpunct([ - item.vehicle ? formatVehicleValue(vehicleValueParts(item.vehicle), localized) : null, - item.cause === REQUIREMENT_CAUSE.MISSING ? null : statusLabel('requirement_cause', item.cause), - ]); +// The subtitle is the host's: the app names the vehicle, and not where the requirement stands (the card only sends; +// owner, 2026-11-04). The stories say it the same way. +const subtitleOf = (item) => (item.vehicle ? formatVehicleValue(vehicleValueParts(item.vehicle), localized) : null); const pane = { padding: MD3LightTheme.spacing.x4, gap: MD3LightTheme.spacing.x2 }; diff --git a/packages/components/src/Partner/DocumentRequirementCard.js b/packages/components/src/Partner/DocumentRequirementCard.js index 25e7bf2b..bdf1a005 100644 --- a/packages/components/src/Partner/DocumentRequirementCard.js +++ b/packages/components/src/Partner/DocumentRequirementCard.js @@ -11,7 +11,7 @@ import { requirementTitle, ruleText } from './viewModel'; * Contract request #117: one requirement of the partner as the server states it (a `getMyStatus` checklist item), in * a Paper `Card` composed the way Paper composes one, with no style of its own: * - the title is the composed rule's name for the partner's market, else the catalogue's (`requirementTitle`); - * - `subtitle` is what the host says of it (its vehicle and where it stands, in the host's words); + * - `subtitle` is what the host names it by besides its title (its vehicle, in the host's words); * - the content is `covers`, the photos the partner has taken and not sent yet, in order (the front, then the back), * each with the `label` a screen reader names it by (one is the cover, more a carousel: DocumentCovers), then * `note` (what to do now, announced by a screen reader when it changes) and the rule's plain explanation for the From 3e50c2617768b90792627a217169d2a7d15c93c5 Mon Sep 17 00:00:00 2001 From: Joely Date: Wed, 4 Nov 2026 17:48:25 -0500 Subject: [PATCH 16/16] components 0.5.4: needs partner 0.2.54, as a peer and for its own tests The rule clause for what the partner reads and the staff label groups are that version's. Co-Authored-By: Claude Opus 5.5 --- packages/components/package-lock.json | 10 +++++----- packages/components/package.json | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/components/package-lock.json b/packages/components/package-lock.json index 27385312..093f6fb4 100644 --- a/packages/components/package-lock.json +++ b/packages/components/package-lock.json @@ -9,7 +9,7 @@ "version": "0.5.4", "license": "ISC", "devDependencies": { - "@jmstechnologiesinc/partner": "0.2.48", + "@jmstechnologiesinc/partner": "0.2.54", "prettier": "^2.5.1", "rimraf": "^3.0.2" }, @@ -19,7 +19,7 @@ "@jmstechnologiesinc/commons": "^0.1.5", "@jmstechnologiesinc/order": "^0.6.0", "@jmstechnologiesinc/order-narration": "^0.0.9", - "@jmstechnologiesinc/partner": "^0.2.47", + "@jmstechnologiesinc/partner": "^0.2.54", "@jmstechnologiesinc/react-native-google-places-autocomplete": "^2.4.14", "@jmstechnologiesinc/react-native-image-blur-loading": "^1.2.5", "@jmstechnologiesinc/react-native-paper": "^5.12.12", @@ -1267,9 +1267,9 @@ } }, "node_modules/@jmstechnologiesinc/partner": { - "version": "0.2.48", - "resolved": "https://npm.pkg.github.com/download/@jmstechnologiesinc/partner/0.2.48/1e770b470a95642089fd06190f732f39b4faabdc", - "integrity": "sha512-VI5+m3Vlxt2D7Z/A0OWhGji+0XjG7rxKQtQ1008vYhwFCchdTdU6P/D0JcpfYQMLhCZSnmatHAvoUZcPf8n0zQ==", + "version": "0.2.54", + "resolved": "https://npm.pkg.github.com/download/@jmstechnologiesinc/partner/0.2.54/9932111297bbe3c3efa290abaa4894ca001b9917", + "integrity": "sha512-pejgHzr0q34Ssq1c5cgDeF4Ge+/Z8Mqcini0vR4mjb3eGJApE8j60yXXx6L/bIS+MApyhAeoilOIAAOCUH/zmw==", "license": "ISC" }, "node_modules/@jmstechnologiesinc/react-native-components": { diff --git a/packages/components/package.json b/packages/components/package.json index 83659bb0..6e6afe64 100644 --- a/packages/components/package.json +++ b/packages/components/package.json @@ -26,7 +26,7 @@ "url": "https://github.com/jmstechnologiesinc/react-native-components/issues" }, "devDependencies": { - "@jmstechnologiesinc/partner": "0.2.48", + "@jmstechnologiesinc/partner": "0.2.54", "prettier": "^2.5.1", "rimraf": "^3.0.2" }, @@ -36,7 +36,7 @@ "@jmstechnologiesinc/commons": "^0.1.5", "@jmstechnologiesinc/order": "^0.6.0", "@jmstechnologiesinc/order-narration": "^0.0.9", - "@jmstechnologiesinc/partner": "^0.2.47", + "@jmstechnologiesinc/partner": "^0.2.54", "@jmstechnologiesinc/react-native-google-places-autocomplete": "^2.4.14", "@jmstechnologiesinc/react-native-image-blur-loading": "^1.2.5", "@jmstechnologiesinc/react-native-paper": "^5.12.12",