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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions backend/src/Http/ApiExceptionSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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();
}
Expand Down
29 changes: 29 additions & 0 deletions backend/tests/Contacts/ContactCardsWriteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
27 changes: 21 additions & 6 deletions frontend/src/ContactsApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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

Expand All @@ -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<ContactSummary, 'id' | 'etag' | 'photo'>) =>
c.photo ? urls.photo(c) : undefined
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -453,7 +468,7 @@ export function ContactsApp({
const showDetail = editing !== null || (mobileDetail && contactId !== null)

return (
<>
<PhoneHomeContext value={phoneHome}>
<SplitPanes
layout={layout}
list={list}
Expand Down Expand Up @@ -520,6 +535,6 @@ export function ContactsApp({
</Group>
</Stack>
</Modal>
</>
</PhoneHomeContext>
)
}
12 changes: 9 additions & 3 deletions frontend/src/api/client.ts
Original file line number Diff line number Diff line change
@@ -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
}
}

Expand Down Expand Up @@ -52,8 +55,11 @@ export async function api<T>(path: string, init?: RequestInit): Promise<T> {
}

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
Expand Down
72 changes: 72 additions & 0 deletions frontend/src/api/contactsHooks.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { describe, expect, it } from 'vitest'

import type { ContactInput } from '../types'
import { fromInput } from './contactsHooks'

const input = (patch: Partial<ContactInput> = {}): 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([[], [], [], []])
})
})
24 changes: 13 additions & 11 deletions frontend/src/api/contactsHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
}
Expand Down Expand Up @@ -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 ?? '',
Expand All @@ -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),
Expand All @@ -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())
Expand Down
20 changes: 10 additions & 10 deletions frontend/src/api/dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions frontend/src/components/contacts/ContactDetail.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Loading
Loading