diff --git a/backend/src/Http/ApiExceptionSubscriber.php b/backend/src/Http/ApiExceptionSubscriber.php index ce44866..5e6bbf9 100644 --- a/backend/src/Http/ApiExceptionSubscriber.php +++ b/backend/src/Http/ApiExceptionSubscriber.php @@ -17,6 +17,7 @@ use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException; use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Component\Validator\Exception\ValidationFailedException; use Webklex\PHPIMAP\Exceptions\AuthFailedException; use Webklex\PHPIMAP\Exceptions\ConnectionFailedException; @@ -59,6 +60,15 @@ public function onException(ExceptionEvent $event): void }; $payload = ['error' => $error]; + // Which fields of the request were refused, so the client can point at them + $refused = $exception->getPrevious(); + if ($refused instanceof ValidationFailedException) { + $fields = []; + foreach ($refused->getViolations() as $violation) { + $fields[$violation->getPropertyPath()] = true; + } + $payload['fields'] = array_map(strval(...), array_keys($fields)); + } if ($this->debug) { $payload['detail'] = $exception->getMessage(); } diff --git a/backend/tests/Contacts/ContactCardsWriteTest.php b/backend/tests/Contacts/ContactCardsWriteTest.php index 3661fb6..6b185d2 100644 --- a/backend/tests/Contacts/ContactCardsWriteTest.php +++ b/backend/tests/Contacts/ContactCardsWriteTest.php @@ -166,6 +166,35 @@ public function testACardIsNotMergedWithItself(): void self::assertResponseStatusCodeSame(422); } + public function testARefusedSaveSaysWhichFields(): void + { + $card = $this->card(self::EMILE); + $this->dav->take(); + + $this->request('PUT', '/api/contacts/cards/'.$card['id'], [ + 'etag' => $card['etag'], + 'firstName' => 'Émile', + 'emails' => [['value' => 'emile@example.test', 'type' => 'work'], ['value' => 'not an address', 'type' => 'home']], + 'addresses' => [['type' => 'home', 'city' => 'Lyon', 'region' => null]], + ]); + + self::assertResponseStatusCodeSame(422); + $answer = $this->json(); + self::assertSame('invalid_request', $answer['error']); + self::assertSame(['addresses[0].region'], $answer['fields']); + self::assertSame([], $this->dav->take()); + + // A wrong type is found first; once the types are right, the values are checked + $this->request('PUT', '/api/contacts/cards/'.$card['id'], [ + 'etag' => $card['etag'], + 'firstName' => 'Émile', + 'emails' => [['value' => 'emile@example.test', 'type' => 'work'], ['value' => 'not an address', 'type' => 'home']], + ]); + + self::assertResponseStatusCodeSame(422); + self::assertSame(['emails[1].value'], $this->json()['fields']); + } + public function testWithoutAnEtagInTheAnswerTheCardIsReadBack(): void { $card = $this->card(self::EMILE); diff --git a/frontend/src/ContactsApp.tsx b/frontend/src/ContactsApp.tsx index 575968f..608d10d 100644 --- a/frontend/src/ContactsApp.tsx +++ b/frontend/src/ContactsApp.tsx @@ -7,6 +7,7 @@ import { ContactError, useMailHooks, type ContactUrls } from './hooks' import type { Addr, ContactCard, ContactInput, ContactSummary, Density, Undo } from './types' import { matchesFilter, secondLine } from './lib/addressBook' import { findDuplicates } from './lib/duplicates' +import { homeCallingCode, phoneLabel, PhoneHomeContext, readPhone } from './lib/phone' import { useI18n } from './lib/i18n' import { useMailShortcuts } from './lib/shortcuts' import type { Layout } from './components/AppShell' @@ -101,7 +102,20 @@ export function ContactsApp({ () => (data?.cards ?? []).filter((c) => bookId === 'all' || c.book === bookId), [data, bookId], ) - const cards = useMemo(() => inBook.filter((c) => matchesFilter(c, filter)), [inBook, filter]) + // Numbers written without a country are read as numbers of the book's own country + const phoneHome = useMemo( + () => + homeCallingCode( + (data?.cards ?? []).flatMap((c) => c.phones), + navigator.languages, + ), + [data], + ) + const phoneText = useCallback((raw: string) => phoneLabel(readPhone(raw, phoneHome)), [phoneHome]) + const cards = useMemo( + () => inBook.filter((c) => matchesFilter(c, filter, (raw) => readPhone(raw, phoneHome).dial)), + [inBook, filter, phoneHome], + ) // New cards and imports go to the picked book, else the first one const targetBook = bookId === 'all' ? (books[0]?.id ?? '') : bookId @@ -124,8 +138,8 @@ export function ContactsApp({ const ids = card ? (duplicateIds.get(card.id) ?? []) : [] return (data?.cards ?? []) .filter((c) => ids.includes(c.id)) - .map((c) => ({ id: c.id, name: c.name, detail: secondLine(c) })) - }, [card, duplicateIds, data]) + .map((c) => ({ id: c.id, name: c.name, detail: secondLine(c, phoneText) })) + }, [card, duplicateIds, data, phoneText]) const photoUrl = (c: Pick) => c.photo ? urls.photo(c) : undefined @@ -237,7 +251,8 @@ export function ContactsApp({ return { ok: false, problem, card: fresh.data } } // The fields may have gone through before the picture failed - return { ok: false, problem, card: saved } + const fields = error instanceof ContactError ? error.fields : [] + return { ok: false, problem, card: saved, fields } } setEditing(null) if (saved) { @@ -453,7 +468,7 @@ export function ContactsApp({ const showDetail = editing !== null || (mobileDetail && contactId !== null) return ( - <> + - + ) } diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 1761e56..0942fc7 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -1,11 +1,14 @@ export class ApiError extends Error { readonly status: number readonly code: string + /** The fields of the request the backend refused, as paths: `addresses[0].region`. */ + readonly fields: string[] - constructor(status: number, code: string) { + constructor(status: number, code: string, fields: string[] = []) { super(`${status} ${code}`) this.status = status this.code = code + this.fields = fields } } @@ -52,8 +55,11 @@ export async function api(path: string, init?: RequestInit): Promise { } if (!response.ok) { - const body = (await response.json().catch(() => ({}))) as { error?: string } - throw new ApiError(response.status, body.error ?? 'unknown') + const body = (await response.json().catch(() => ({}))) as { + error?: string + fields?: string[] + } + throw new ApiError(response.status, body.error ?? 'unknown', body.fields) } if (response.status === 204) return undefined as T diff --git a/frontend/src/api/contactsHooks.test.ts b/frontend/src/api/contactsHooks.test.ts new file mode 100644 index 0000000..5f047e0 --- /dev/null +++ b/frontend/src/api/contactsHooks.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vitest' + +import type { ContactInput } from '../types' +import { fromInput } from './contactsHooks' + +const input = (patch: Partial = {}): ContactInput => ({ + firstName: 'Émile', + lastName: 'Durand', + org: '', + title: '', + emails: [], + phones: [], + addresses: [], + urls: [], + birthday: '', + note: '', + ...patch, +}) + +describe('what a save sends', () => { + it('sends the empty parts of an address as empty text', () => { + // The server refuses null there, and the whole save with it + const sent = fromInput( + input({ + addresses: [ + { + key: 0, + type: 'home', + street: ' 12 rue des Lilas ', + city: 'Lyon', + region: '', + postalCode: '69001', + country: '', + }, + ], + }), + ) + + expect(sent.addresses).toEqual([ + { + key: 0, + type: 'home', + street: '12 rue des Lilas', + city: 'Lyon', + region: '', + postalCode: '69001', + country: '', + }, + ]) + }) + + it('leaves out the lines with nothing typed in', () => { + const empty = { + type: 'home' as const, + street: '', + city: ' ', + region: '', + postalCode: '', + country: '', + } + const sent = fromInput( + input({ + emails: [{ value: ' ', type: 'home' }], + phones: [{ value: '', type: 'cell' }], + addresses: [empty], + urls: [{ value: '' }], + }), + ) + + expect([sent.emails, sent.phones, sent.addresses, sent.urls]).toEqual([[], [], [], []]) + }) +}) diff --git a/frontend/src/api/contactsHooks.ts b/frontend/src/api/contactsHooks.ts index 879e4a6..1f5febe 100644 --- a/frontend/src/api/contactsHooks.ts +++ b/frontend/src/api/contactsHooks.ts @@ -49,6 +49,7 @@ function toContactError(error: unknown): ContactError { if (error.code === 'contact_changed' || error.status === 409) return new ContactError('changed') if (error.code === 'contacts_unavailable') return new ContactError('unavailable') if (error.code === 'contact_not_found') return new ContactError('notFound') + if (error.fields.length > 0) return new ContactError('refused', error.fields) } return new ContactError('failed') } @@ -128,11 +129,11 @@ function toCard(dto: Dto.Card): ContactCard { addresses: dto.addresses.map((a) => ({ key: a.key, type: toType(a.type), - street: a.street ?? '', - city: a.city ?? '', - region: a.region ?? '', - postalCode: a.postalCode ?? '', - country: a.country ?? '', + street: a.street, + city: a.city, + region: a.region, + postalCode: a.postalCode, + country: a.country, })), urls: dto.urls.map((u) => ({ key: u.key, value: u.value })), birthday: dto.birthday ?? '', @@ -159,7 +160,7 @@ const orNull = (value: string) => value.trim() || null const withKey = (key: number | undefined) => (key === undefined ? {} : { key }) /** Empty lines are dropped: the editor shows an empty row to type in, the card should not keep it. */ -function fromInput(input: ContactInput): Dto.CardInput { +export function fromInput(input: ContactInput): Dto.CardInput { return { firstName: orNull(input.firstName), lastName: orNull(input.lastName), @@ -173,14 +174,15 @@ function fromInput(input: ContactInput): Dto.CardInput { .map((p) => ({ ...withKey(p.key), value: p.value.trim(), type: p.type })), addresses: input.addresses .filter((a) => [a.street, a.city, a.region, a.postalCode, a.country].some((v) => v.trim())) + // The parts of an address are always text: an empty part is '', never null .map((a) => ({ ...withKey(a.key), type: a.type, - street: orNull(a.street), - city: orNull(a.city), - region: orNull(a.region), - postalCode: orNull(a.postalCode), - country: orNull(a.country), + street: a.street.trim(), + city: a.city.trim(), + region: a.region.trim(), + postalCode: a.postalCode.trim(), + country: a.country.trim(), })), urls: input.urls .filter((u) => u.value.trim()) diff --git a/frontend/src/api/dto.ts b/frontend/src/api/dto.ts index c4b03ef..a1e31cb 100644 --- a/frontend/src/api/dto.ts +++ b/frontend/src/api/dto.ts @@ -142,11 +142,11 @@ export type CardValue = { key: number; value: string; type: CardType | null; lab export type CardAddress = { key: number type: CardType | null - street: string | null - city: string | null - region: string | null - postalCode: string | null - country: string | null + street: string + city: string + region: string + postalCode: string + country: string } export type CardUrl = { key: number; value: string } @@ -186,11 +186,11 @@ export type CardInput = { addresses: { key?: number type: CardType - street: string | null - city: string | null - region: string | null - postalCode: string | null - country: string | null + street: string + city: string + region: string + postalCode: string + country: string }[] urls: { key?: number; value: string }[] birthday: string | null diff --git a/frontend/src/components/contacts/ContactDetail.module.css b/frontend/src/components/contacts/ContactDetail.module.css index a142b4b..848a990 100644 --- a/frontend/src/components/contacts/ContactDetail.module.css +++ b/frontend/src/components/contacts/ContactDetail.module.css @@ -196,3 +196,30 @@ color: var(--mantine-color-dimmed); user-select: none; } + +/* The picture opens larger */ +.picture { + flex: none; + border-radius: 50%; + cursor: zoom-in; + + &:focus-visible { + outline: 2px solid var(--mantine-primary-color-filled); + outline-offset: 2px; + } +} + +/* Pictures are saved at 512px: never shown larger than they are */ +.largePicture { + display: block; + width: min(512px, 80vw, 70vh); + aspect-ratio: 1; + object-fit: cover; + border-radius: var(--mantine-radius-md); +} + +.flag { + margin-inline-end: 6px; + font-size: var(--mantine-font-size-sm); + user-select: none; +} diff --git a/frontend/src/components/contacts/ContactDetail.tsx b/frontend/src/components/contacts/ContactDetail.tsx index b6e5d0b..5bc542e 100644 --- a/frontend/src/components/contacts/ContactDetail.tsx +++ b/frontend/src/components/contacts/ContactDetail.tsx @@ -1,4 +1,4 @@ -import { useState, type ReactNode } from 'react' +import { useMemo, useState, type ReactNode } from 'react' import { ActionIcon, Anchor, @@ -8,6 +8,7 @@ import { CopyButton, Group, Menu, + Modal, ScrollArea, Stack, Text, @@ -35,6 +36,7 @@ import type { ContactProblem } from '../../hooks' import { formatBirthday } from '../../lib/addressBook' import { initials } from '../../lib/format' import { useI18n } from '../../lib/i18n' +import { flagOf, usePhoneReader } from '../../lib/phone' import { KeyCombo, ShortcutTooltip } from '../ShortcutTooltip' import { ErrorState, ReaderSkeleton, StateMessage } from '../States' import classes from './ContactDetail.module.css' @@ -247,6 +249,10 @@ function Body({ }: ContactDetailProps & { card: ContactCard }) { const { t, locale } = useI18n() const typeLabel = (type: ContactType, label?: string) => label || t.contact.types[type] + const readPhone = usePhoneReader() + const countries = useMemo(() => new Intl.DisplayNames(locale, { type: 'region' }), [locale]) + const countryName = (country: string) => countries.of(country) ?? country + const [pictureOpen, setPictureOpen] = useState(false) const meta = [card.org !== card.name ? card.org : '', card.title].filter(Boolean).join(' · ') const avatar = isMobile ? 64 : 72 @@ -272,17 +278,26 @@ function Body({ ) if (card.phones.length) groups.push( - card.phones.map((p) => ( - - - {p.value} - - - )), + card.phones.map((p) => { + const phone = readPhone(p.value) + return ( + + {phone.country && ( + + {flagOf(phone.country)} + + )} + + {phone.text} + + + ) + }), ) if (card.addresses.length) groups.push( @@ -334,9 +349,28 @@ function Body({ return (
- - {initials({ name: card.name, email: card.emails[0]?.value ?? '' })} - + {photoUrl ? ( + setPictureOpen(true)} + > + + + ) : ( + + {initials({ name: card.name, email: card.emails[0]?.value ?? '' })} + + )} + setPictureOpen(false)} + title={card.name} + centered + size="auto" + > + + {card.name} diff --git a/frontend/src/components/contacts/ContactEditor.tsx b/frontend/src/components/contacts/ContactEditor.tsx index 10640d7..63a51f3 100644 --- a/frontend/src/components/contacts/ContactEditor.tsx +++ b/frontend/src/components/contacts/ContactEditor.tsx @@ -30,7 +30,7 @@ import type { ContactType, ContactValue, } from '../../types' -import { formatBirthday } from '../../lib/addressBook' +import { formatBirthday, refusedFields } from '../../lib/addressBook' import { initials } from '../../lib/format' import { useI18n } from '../../lib/i18n' import { rebaseInput } from '../../lib/rebase' @@ -54,7 +54,10 @@ export type ContactSave = { * A save that failed may still have moved the card: someone else changed it, or the * fields went through and the picture did not. `card` is then the card as it is now. */ -export type SaveOutcome = { ok: true } | { ok: false; problem: ContactProblem; card?: ContactCard } +export type SaveOutcome = + | { ok: true } + // `fields`: with the `refused` problem, the paths of the fields the backend refused + | { ok: false; problem: ContactProblem; card?: ContactCard; fields?: string[] } export type ContactEditorProps = { /** The card being edited; none for a new one. */ @@ -149,6 +152,7 @@ export function ContactEditor({ const [cropFile, setCropFile] = useState<File | null>(null) const [problem, setProblem] = useState<ContactProblem | 'badImage' | null>(null) const [saving, setSaving] = useState(false) + const [refused, setRefused] = useState<string[]>([]) const [errors, setErrors] = useState<{ name?: boolean; emails?: number[] }>({}) const [dropping, setDropping] = useState(false) const confirming = useRef(false) @@ -197,6 +201,7 @@ export function ContactEditor({ setSaving(false) if (outcome.ok) return setProblem(outcome.problem) + setRefused(refusedFields(outcome.fields ?? [])) if (outcome.card) { // The next attempt starts from the card as it is now: the edits are moved onto it, // so that each line still points at the right line of the card @@ -312,16 +317,44 @@ export function ContactEditor({ const updateAddress = (i: number, patch: Partial<ContactAddress>) => set({ addresses: draft.addresses.map((a, j) => (j === i ? { ...a, ...patch } : a)) }) + // The refused fields under the names they have in the form: "Email, Address (Region)" + const fieldNames: Record<string, string> = { + firstName: t.contact.firstName, + lastName: t.contact.lastName, + org: t.contact.org, + title: t.contact.jobTitle, + emails: t.contact.email, + phones: t.contact.phone, + addresses: t.contact.address, + urls: t.contact.url, + birthday: t.contact.birthdayLabel, + note: t.contact.noteLabel, + street: t.contact.street, + city: t.contact.city, + region: t.contact.region, + postalCode: t.contact.postalCode, + country: t.contact.country, + } + const refusedNames = refused.flatMap((field) => { + const [name = '', part] = field.split('.') + const label = fieldNames[name] + if (!label) return [] + const partLabel = part ? fieldNames[part] : undefined + return [partLabel ? `${label} (${partLabel})` : label] + }) + const problemText = - problem === 'changed' - ? t.contact.changed - : problem === 'unavailable' - ? t.contact.unreachable - : problem === 'badImage' - ? t.contact.badImage - : problem - ? t.contact.saveFailed - : null + problem === 'refused' && refusedNames.length > 0 + ? t.contact.saveRefused(refusedNames.join(', ')) + : problem === 'changed' + ? t.contact.changed + : problem === 'unavailable' + ? t.contact.unreachable + : problem === 'badImage' + ? t.contact.badImage + : problem + ? t.contact.saveFailed + : null const title = card ? t.contact.editTitle : t.contact.newContact const avatarName = diff --git a/frontend/src/components/contacts/ContactList.module.css b/frontend/src/components/contacts/ContactList.module.css index 930197c..71c2194 100644 --- a/frontend/src/components/contacts/ContactList.module.css +++ b/frontend/src/components/contacts/ContactList.module.css @@ -94,7 +94,8 @@ } } -/* A letter heading: lined up with the names, on the page colour so rows pass under it when pinned */ +/* A letter heading: lined up with the names. Pinned, it is a solid band from the top of the pane + down to the letter, so rows go out of sight under its lower edge */ .letter { left: 0; right: 0; diff --git a/frontend/src/components/contacts/ContactList.tsx b/frontend/src/components/contacts/ContactList.tsx index e316d72..563bc9b 100644 --- a/frontend/src/components/contacts/ContactList.tsx +++ b/frontend/src/components/contacts/ContactList.tsx @@ -407,7 +407,8 @@ export function ContactList(props: ContactListProps) { data-pinned={isPinned || undefined} style={ isPinned - ? { position: 'sticky', top: topInset + 6, height: vi.size } + ? // From the very top, behind the floating header too: no row shows above the letter + { position: 'sticky', top: 0, height: topInset + 6 + vi.size } : { position: 'absolute', top: 0, diff --git a/frontend/src/components/contacts/ContactRow.tsx b/frontend/src/components/contacts/ContactRow.tsx index e21e5a7..f7b8c56 100644 --- a/frontend/src/components/contacts/ContactRow.tsx +++ b/frontend/src/components/contacts/ContactRow.tsx @@ -3,6 +3,7 @@ import { Avatar, Text } from '@mantine/core' import type { ContactSummary, Density } from '../../types' import { secondLine } from '../../lib/addressBook' import { initials } from '../../lib/format' +import { phoneLabel, usePhoneReader } from '../../lib/phone' import classes from './ContactRow.module.css' // Slot per row, the highlight inset 2px top and bottom like the message rows @@ -28,7 +29,8 @@ function ContactRowImpl({ style, onActivate, }: ContactRowProps) { - const detail = secondLine(card) + const readPhone = usePhoneReader() + const detail = secondLine(card, (raw) => phoneLabel(readPhone(raw))) const size = AVATAR_SIZE[density] return ( <div style={style} className={classes.slot} data-density={density}> diff --git a/frontend/src/components/contacts/MergeDialog.tsx b/frontend/src/components/contacts/MergeDialog.tsx index 86d164c..8f9d8fe 100644 --- a/frontend/src/components/contacts/MergeDialog.tsx +++ b/frontend/src/components/contacts/MergeDialog.tsx @@ -4,6 +4,7 @@ import { CheckIcon, CircleAlertIcon, MergeIcon } from 'lucide-react' import type { ContactCard } from '../../types' import { initials } from '../../lib/format' import { useI18n } from '../../lib/i18n' +import { phoneLabel, usePhoneReader } from '../../lib/phone' import classes from './MergeDialog.module.css' export type MergeDialogProps = { @@ -20,11 +21,13 @@ export type MergeDialogProps = { } /** The few lines that tell one card from the other. */ -function lines(card: ContactCard): string[] { +function lines(card: ContactCard, phone: (raw: string) => string): string[] { const meta = [card.org !== card.name ? card.org : '', card.title].filter(Boolean).join(' · ') - return [meta, ...card.emails.map((e) => e.value), ...card.phones.map((p) => p.value)].filter( - Boolean, - ) + return [ + meta, + ...card.emails.map((e) => e.value), + ...card.phones.map((p) => phone(p.value)), + ].filter(Boolean) } /** @@ -42,6 +45,7 @@ export function MergeDialog({ problem, }: MergeDialogProps) { const { t } = useI18n() + const readPhone = usePhoneReader() const [keepSecond, setKeepSecond] = useState(false) const [busy, setBusy] = useState(false) const refs = useRef<(HTMLButtonElement | null)[]>([]) @@ -123,7 +127,7 @@ export function MergeDialog({ {initials({ name: card.name, email: card.emails[0]?.value ?? '' })} </Avatar> <span className={classes.name}>{card.name}</span> - {lines(card) + {lines(card, (raw) => phoneLabel(readPhone(raw))) .slice(0, 4) .map((line, n) => ( <span key={n} className={classes.line}> diff --git a/frontend/src/hooks.ts b/frontend/src/hooks.ts index 56a5981..698f41b 100644 --- a/frontend/src/hooks.ts +++ b/frontend/src/hooks.ts @@ -45,16 +45,20 @@ export interface MailActions { * - `changed`: someone changed the card since it was read (reload it, keep the user's input) * - `unavailable`: the address book's server cannot be reached * - `notFound`: the card is gone + * - `refused`: the backend does not accept what was typed; `fields` says where * - `failed`: anything else, the backend itself included */ -export type ContactProblem = 'changed' | 'unavailable' | 'notFound' | 'failed' +export type ContactProblem = 'changed' | 'unavailable' | 'notFound' | 'refused' | 'failed' export class ContactError extends Error { readonly problem: ContactProblem + /** With `refused`, the refused fields as paths: `addresses[0].region`. */ + readonly fields: string[] - constructor(problem: ContactProblem) { + constructor(problem: ContactProblem, fields: string[] = []) { super(problem) this.problem = problem + this.fields = fields } } diff --git a/frontend/src/lib/addressBook.test.ts b/frontend/src/lib/addressBook.test.ts index 4c0e892..bad9426 100644 --- a/frontend/src/lib/addressBook.test.ts +++ b/frontend/src/lib/addressBook.test.ts @@ -5,6 +5,7 @@ import { formatBirthday, letterOf, matchesFilter, + refusedFields, secondLine, sortCards, withLetters, @@ -50,7 +51,9 @@ describe('contact filter', () => { }) it('finds phones whatever the spacing', () => { - expect(matchesFilter(emile, '0612')).toBe(false) + // Typed the way it is dialled at home, stored with the country + expect(matchesFilter(emile, '0612')).toBe(true) + expect(matchesFilter(emile, '0712')).toBe(false) expect(matchesFilter(emile, '612 34')).toBe(true) expect(matchesFilter(emile, '+33612345678')).toBe(true) }) @@ -116,3 +119,15 @@ describe('birthday', () => { expect(formatBirthday('--0312', 'fr-FR')).toBe('12 mars') }) }) + +describe('the fields a save was refused for', () => { + it('names each field once, with the part of an address', () => { + expect( + refusedFields(['emails[1].value', 'emails[2].value', 'addresses[0].region', 'birthday']), + ).toEqual(['emails', 'addresses.region', 'birthday']) + }) + + it('names the address alone when no part is given', () => { + expect(refusedFields(['addresses', ''])).toEqual(['addresses']) + }) +}) diff --git a/frontend/src/lib/addressBook.ts b/frontend/src/lib/addressBook.ts index 7ba3777..458f60a 100644 --- a/frontend/src/lib/addressBook.ts +++ b/frontend/src/lib/addressBook.ts @@ -25,15 +25,24 @@ const digits = (value: string) => value.replace(/\D/g, '') * Every word of the query must appear somewhere: in the name, the organisation, an email, * or, for a word with digits, a phone number. */ -export function matchesFilter(card: ContactSummary, query: string): boolean { +export function matchesFilter( + card: ContactSummary, + query: string, + dial: (raw: string) => string = (raw) => raw, +): boolean { const words = fold(query).split(/\s+/).filter(Boolean) if (!words.length) return true const text = fold([card.name, card.org, ...card.emails].join('\n')) - const phones = card.phones.map(digits) + // As typed and as shown: "06 12" and "+33 6 12" both find the same number + const phones = card.phones.flatMap((phone) => [digits(phone), digits(dial(phone))]) return words.every((word) => { if (text.includes(word)) return true const number = digits(word) - return number.length > 0 && phones.some((phone) => phone.includes(number)) + if (!number) return false + const local = number.replace(/^0+/, '') + return phones.some( + (phone) => phone.includes(number) || (local.length > 1 && phone.includes(local)), + ) }) } @@ -62,10 +71,13 @@ export function withLetters(cards: ContactSummary[]): ListEntry[] { } /** The dimmed line under a name: the organisation, else the first email, else the first phone. */ -export function secondLine(card: ContactSummary): string { +export function secondLine( + card: ContactSummary, + phone: (raw: string) => string = (raw) => raw, +): string { if (card.org && card.org !== card.name) return card.org const email = card.emails.find((e) => e !== card.name) - return email ?? card.phones[0] ?? '' + return email ?? (card.phones[0] ? phone(card.phones[0]) : '') } /** A birthday through Intl, without the year when the card does not know it. */ @@ -86,3 +98,15 @@ export function formatBirthday(value: string, locale: string): string { } return value } + +/** + * The fields a save was refused for, from the backend's paths: `addresses[0].region` + * gives `addresses.region`, `emails[1].value` gives `emails`. Each one once. + */ +export function refusedFields(paths: string[]): string[] { + const fields = paths.map((path) => { + const [field = '', part] = path.replace(/\[\d+\]/g, '').split('.') + return field === 'addresses' && part ? `${field}.${part}` : field + }) + return [...new Set(fields.filter(Boolean))] +} diff --git a/frontend/src/lib/i18n.ts b/frontend/src/lib/i18n.ts index 5ffbcae..a0c4543 100644 --- a/frontend/src/lib/i18n.ts +++ b/frontend/src/lib/i18n.ts @@ -234,6 +234,7 @@ const en = { showMessages: 'Show messages', delete: 'Delete contact', deleted: (name: string) => `${name} deleted`, + showPicture: 'Show the picture larger', possibleDuplicate: (name: string) => `Possible duplicate: ${name}`, merge: 'Merge…', mergeTitle: 'Merge two contacts', @@ -289,6 +290,8 @@ const en = { 'This contact was changed somewhere else in the meantime. Those changes are now in the form, next to yours: check it and save again.', unreachable: 'Can’t reach the address book. Your edits are still here: try again in a moment.', saveFailed: 'Couldn’t save. Your edits are still here.', + saveRefused: (fields: string) => + `Couldn’t save: something is wrong in ${fields}. Check it and save again. Your edits are still here.`, unreachableNothing: 'Can’t reach the address book. Nothing was changed.', created: (name: string) => `${name} added to your contacts`, saved: 'Contact saved', @@ -585,6 +588,7 @@ const fr: Strings = { showMessages: 'Voir les messages', delete: 'Supprimer le contact', deleted: (name) => `${name} supprimé des contacts`, + showPicture: 'Agrandir la photo', possibleDuplicate: (name) => `Doublon possible : ${name}`, merge: 'Fusionner…', mergeTitle: 'Fusionner deux contacts', @@ -640,6 +644,8 @@ const fr: Strings = { unreachable: 'Carnet d’adresses injoignable. Vos modifications sont conservées : réessayez dans un instant.', saveFailed: 'Échec de l’enregistrement. Vos modifications sont conservées.', + saveRefused: (fields) => + `Échec de l’enregistrement : un problème dans ${fields}. Vérifiez et enregistrez de nouveau. Vos modifications sont conservées.`, unreachableNothing: 'Carnet d’adresses injoignable. Rien n’a été modifié.', created: (name) => `${name} ajouté aux contacts`, saved: 'Contact enregistré', diff --git a/frontend/src/lib/phone.test.ts b/frontend/src/lib/phone.test.ts new file mode 100644 index 0000000..f95dc83 --- /dev/null +++ b/frontend/src/lib/phone.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from 'vitest' + +import { flagOf, homeCallingCode, readPhone } from './phone' + +describe('reading phone numbers', () => { + it.each([ + ['+33612345678', '+33 6 12 34 56 78', 'FR'], + ['+33 6 12 34 56 78', '+33 6 12 34 56 78', 'FR'], + ['0033 6.12.34.56.78', '+33 6 12 34 56 78', 'FR'], + ['+33 (0)6 12 34 56 78', '+33 6 12 34 56 78', 'FR'], + ['+1 (415) 555-0142', '+1 415 555 0142', 'US'], + ['+1 514 555 0142', '+1 514 555 0142', 'CA'], + ['+1 876 555 0142', '+1 876 555 0142', 'JM'], + ['+44 7700 900142', '+44 7700 900142', 'GB'], + ['+41 79 555 01 42', '+41 79 555 01 42', 'CH'], + ['+351 912 555 018', '+351 912 555 018', 'PT'], + ['+49 151 555 0142', '+49 151 555 01 42', 'DE'], + ['+7 701 555 01 42', '+7 701 555 01 42', 'KZ'], + ['+262 692 12 34 56', '+262 692 123 456', 'RE'], + ])('%s', (typed, text, country) => { + expect(readPhone(typed)).toMatchObject({ text, country }) + }) + + it('gives the number to dial', () => { + expect(readPhone('+33 (0)6 12 34 56 78').dial).toBe('+33612345678') + expect(readPhone('06 12 34 56 78', '33').dial).toBe('+33612345678') + expect(readPhone('06 12 34 56 78').dial).toBe('0612345678') + }) + + it('takes a number without a country to be from home', () => { + expect(readPhone('06 12 34 56 78', '33')).toMatchObject({ + text: '+33 6 12 34 56 78', + country: 'FR', + }) + expect(readPhone('020 7946 0142', '44')).toMatchObject({ + text: '+44 207 946 01 42', + country: 'GB', + }) + // No leading 0 to drop in the United States or in Italy + expect(readPhone('0612345678', '1').country).toBeUndefined() + expect(readPhone('06 1234 5678', '39').country).toBeUndefined() + }) + + it('leaves alone what it cannot read', () => { + expect(readPhone(' 06 12 34 56 78 ')).toEqual({ text: '06 12 34 56 78', dial: '0612345678' }) + expect(readPhone('3615')).toEqual({ text: '3615', dial: '3615' }) + expect(readPhone('+33 6 12 34 56 78 ext. 12').country).toBeUndefined() + expect(readPhone('+999 123 456 789').country).toBeUndefined() + expect(readPhone('').text).toBe('') + }) + + it('draws the flag of a country', () => { + expect(flagOf('FR')).toBe('🇫🇷') + expect(flagOf('gb')).toBe('🇬🇧') + }) +}) + +describe('the home country of an address book', () => { + it('is the one most of its numbers are from', () => { + const phones = [ + '+33 6 00 00 00 01', + '+33600000002', + '0033 6 00 00 00 03', + '+44 7700 900142', + '06 00 00 00 04', + ] + expect(homeCallingCode(phones)).toBe('33') + }) + + it('falls back on the language of the browser when the book does not say', () => { + expect(homeCallingCode(['+33 6 00 00 00 01', '+44 7700 900142'], ['en', 'fr-FR'])).toBe('33') + expect(homeCallingCode([], ['en-CA'])).toBe('1') + expect(homeCallingCode(['06 00 00 00 04'], ['en'])).toBeUndefined() + }) +}) diff --git a/frontend/src/lib/phone.ts b/frontend/src/lib/phone.ts new file mode 100644 index 0000000..9762220 --- /dev/null +++ b/frontend/src/lib/phone.ts @@ -0,0 +1,176 @@ +import { createContext, use, useCallback } from 'react' + +/* + * Phone numbers are shown the same way wherever they come from: "+33 6 12 34 56 78", + * with the flag of the country. Cards keep the number as it was typed; only what is + * shown, and the tel: link, go through here. + */ + +/** Calling code -> country. Codes shared by several countries name the main one. */ +const CODES = + '1:US,7:RU,20:EG,27:ZA,30:GR,31:NL,32:BE,33:FR,34:ES,36:HU,39:IT,40:RO,41:CH,43:AT,44:GB,45:DK,46:SE,47:NO,48:PL,49:DE,' + + '51:PE,52:MX,53:CU,54:AR,55:BR,56:CL,57:CO,58:VE,60:MY,61:AU,62:ID,63:PH,64:NZ,65:SG,66:TH,81:JP,82:KR,84:VN,86:CN,' + + '90:TR,91:IN,92:PK,93:AF,94:LK,95:MM,98:IR,211:SS,212:MA,213:DZ,216:TN,218:LY,220:GM,221:SN,222:MR,223:ML,224:GN,' + + '225:CI,226:BF,227:NE,228:TG,229:BJ,230:MU,231:LR,232:SL,233:GH,234:NG,235:TD,236:CF,237:CM,238:CV,239:ST,240:GQ,' + + '241:GA,242:CG,243:CD,244:AO,245:GW,248:SC,249:SD,250:RW,251:ET,252:SO,253:DJ,254:KE,255:TZ,256:UG,257:BI,258:MZ,' + + '260:ZM,261:MG,262:RE,263:ZW,264:NA,265:MW,266:LS,267:BW,268:SZ,269:KM,291:ER,297:AW,298:FO,299:GL,350:GI,351:PT,' + + '352:LU,353:IE,354:IS,355:AL,356:MT,357:CY,358:FI,359:BG,370:LT,371:LV,372:EE,373:MD,374:AM,375:BY,376:AD,377:MC,' + + '378:SM,380:UA,381:RS,382:ME,383:XK,385:HR,386:SI,387:BA,389:MK,420:CZ,421:SK,423:LI,501:BZ,502:GT,503:SV,504:HN,' + + '505:NI,506:CR,507:PA,508:PM,509:HT,590:GP,591:BO,592:GY,593:EC,594:GF,595:PY,596:MQ,597:SR,598:UY,599:CW,670:TL,' + + '673:BN,674:NR,675:PG,676:TO,677:SB,678:VU,679:FJ,680:PW,682:CK,685:WS,686:KI,687:NC,689:PF,691:FM,692:MH,850:KP,' + + '852:HK,853:MO,855:KH,856:LA,880:BD,886:TW,960:MV,961:LB,962:JO,963:SY,964:IQ,965:KW,966:SA,967:YE,968:OM,970:PS,' + + '971:AE,972:IL,973:BH,974:QA,975:BT,976:MN,977:NP,992:TJ,993:TM,994:AZ,995:GE,996:KG,998:UZ,' + + // Kazakhstan shares +7 with Russia + '76:KZ,77:KZ,' + + // +1 is shared: these area codes are not the United States + '1242:BS,1246:BB,1264:AI,1268:AG,1284:VG,1340:VI,1345:KY,1441:BM,1473:GD,1649:TC,1664:MS,1670:MP,1671:GU,1684:AS,' + + '1721:SX,1758:LC,1767:DM,1784:VC,1787:PR,1939:PR,1809:DO,1829:DO,1849:DO,1868:TT,1869:KN,1876:JM,' + + [ + 204, 226, 236, 249, 250, 263, 289, 306, 343, 354, 365, 367, 368, 382, 403, 416, 418, 428, 431, + 437, 438, 450, 468, 474, 506, 514, 519, 548, 579, 581, 584, 587, 604, 613, 639, 647, 672, 683, + 705, 709, 742, 753, 778, 780, 782, 807, 819, 825, 867, 873, 879, 902, 905, + ] + .map((area) => `1${area}:CA`) + .join(',') + +const COUNTRY_BY_PREFIX = new Map( + CODES.split(',').map((pair) => pair.split(':') as [string, string]), +) + +/** How long the calling code is, when the prefix that names the country is longer (+1 204 is +1). */ +const callingCode = (prefix: string) => + prefix.startsWith('1') ? '1' : prefix.startsWith('7') ? '7' : prefix + +/** Countries where a number written for use inside the country starts with a 0 that the international form drops. */ +const TRUNK_ZERO = new Set( + '20,27,31,32,33,40,41,43,44,46,49,54,60,61,62,63,64,66,81,82,84,86,90,91,212,213,234,254,353,358,359,380,381,385,386,972'.split( + ',', + ), +) + +/** How the digits after the calling code are grouped, where there is a habit. Others go by threes. */ +const GROUPS: Record<string, number[]> = { + 1: [3, 3, 4], + 33: [1, 2, 2, 2, 2], + 34: [3, 3, 3], + 39: [3, 3, 4], + 41: [2, 3, 2, 2], + 44: [4, 6], + 351: [3, 3, 3], + 352: [3, 3, 3], +} + +function group(code: string, national: string): string { + // The British habit below is the one of mobile numbers + const habit = code === '44' && !national.startsWith('7') ? undefined : GROUPS[code] + if (habit && habit.reduce((a, b) => a + b, 0) === national.length) { + let at = 0 + return habit.map((size) => national.slice(at, (at += size))).join(' ') + } + // By threes, never leaving a digit alone at the end + const parts: string[] = [] + let rest = national + while (rest.length > 4) { + parts.push(rest.slice(0, 3)) + rest = rest.slice(3) + } + if (rest.length === 4) parts.push(rest.slice(0, 2), rest.slice(2)) + else if (rest) parts.push(rest) + return parts.join(' ') +} + +export type Phone = { + /** As shown: "+33 6 12 34 56 78", or the number as typed when it cannot be read. */ + text: string + /** Two-letter country, when known. */ + country?: string + /** "+33612345678", for a tel: link; the typed number's digits otherwise. */ + dial: string +} + +const asTyped = (raw: string): Phone => ({ + text: raw.trim().replace(/\s+/g, ' '), + dial: raw.replace(/[^\d+#*,;]/g, ''), +}) + +/** + * Reads a number however it was written. One that starts with "+" or "00" says its + * country; one that starts with a single 0 is taken to be from `home`, the calling code + * of the country most numbers around it are from. + */ +export function readPhone(raw: string, home?: string): Phone { + // "+33 (0)6 12…": the 0 in brackets is only for calls inside the country + const typed = raw.trim().replace(/\(0\)/g, '') + // Letters mean an extension or a note: left as typed + if (/[a-z]/i.test(typed)) return asTyped(raw) + const digits = typed.replace(/\D/g, '') + + let international = '' + if (typed.startsWith('+')) international = digits + else if (digits.startsWith('00')) international = digits.slice(2) + else if (home && TRUNK_ZERO.has(home) && /^0[1-9]/.test(digits)) + international = home + digits.slice(1) + if (international.length < 8 || international.length > 15) return asTyped(raw) + + for (let length = 4; length >= 1; length--) { + const prefix = international.slice(0, length) + const country = COUNTRY_BY_PREFIX.get(prefix) + if (!country) continue + const code = callingCode(prefix) + return { + text: `+${code} ${group(code, international.slice(code.length))}`, + country, + dial: `+${international}`, + } + } + return asTyped(raw) +} + +/** "FR" -> the flag emoji. */ +export function flagOf(country: string): string { + return String.fromCodePoint(...[...country.toUpperCase()].map((c) => 0x1f1a5 + c.charCodeAt(0))) +} + +/** + * The calling code that numbers written without one most likely belong to: the one most + * of the address book's own numbers carry, else the country of the browser's language. + */ +export function homeCallingCode( + phones: string[], + languages: readonly string[] = [], +): string | undefined { + const counts = new Map<string, number>() + let known = 0 + for (const phone of phones) { + const read = readPhone(phone) + if (!read.country) continue + const code = read.text.slice(1, read.text.indexOf(' ')) + counts.set(code, (counts.get(code) ?? 0) + 1) + known += 1 + } + const [code, count] = [...counts].sort((a, b) => b[1] - a[1])[0] ?? [] + // Only when the book is clear about it: a few numbers of one country, and most of them + if (code && count! >= 3 && count! * 2 > known) return code + + for (const language of languages) { + const region = /[-_]([A-Za-z]{2})\b/.exec(language)?.[1]?.toUpperCase() + if (!region) continue + for (const [prefix, country] of COUNTRY_BY_PREFIX) + if (country === region) return callingCode(prefix) + } + return undefined +} + +/** The flag, then the number: for places that show a phone as plain text. */ +export function phoneLabel(phone: Phone): string { + return phone.country ? `${flagOf(phone.country)} ${phone.text}` : phone.text +} + +/** The calling code of the address book on screen, see homeCallingCode. */ +export const PhoneHomeContext = createContext<string | undefined>(undefined) + +/** Reads numbers the way the address book on screen does. */ +export function usePhoneReader(): (raw: string) => Phone { + const home = use(PhoneHomeContext) + return useCallback((raw: string) => readPhone(raw, home), [home]) +} diff --git a/frontend/src/lib/shortcuts.ts b/frontend/src/lib/shortcuts.ts index ec8e8ac..440837c 100644 --- a/frontend/src/lib/shortcuts.ts +++ b/frontend/src/lib/shortcuts.ts @@ -92,6 +92,8 @@ export function useMailShortcuts(handlers: Handlers, enabled: boolean) { const onKeyDown = useEffectEvent((event: KeyboardEvent) => { if (event.defaultPrevented || isTypingTarget(event.target)) return + // A dialog on top has the keyboard: Esc closes it, and nothing happens underneath + if (document.querySelector('[aria-modal="true"]')) return const altGraph = event.getModifierState?.('AltGraph') ?? false if ((event.ctrlKey || event.metaKey || event.altKey) && !altGraph) return