feat(places): colour tags, tabs for the texts and opening hours on the phone

Tags on the place form are pills in their own colour, with a palette under
the dot that recolours a tag for the whole trip (PUT /trips/:id/tags/:id was
there already, the client now reaches it through repo and store) and a
custom colour field of its own instead of the system picker. A new tag is
made in a colour picked the same way.

Description, notes and the note for one day's visit sit in one card under a
switch, each with a line on where the text shows up; the day tab is named
after its day and is only there with one visit in context. Nothing about the
three fields changes underneath.

Opening hours get a switch for open around the clock next to closed. Google
writes a place open all week as one period on Sunday that never closes; it
read as Sunday open and every other day closed, and now opens every day.

The phone form follows the desktop: category as one field with a list, tags
in one field, the texts switch, and phone, e-mail and opening hours, which it
did not have. The hours and the text tabs are shared hooks (usePlaceHours,
usePlaceTextTabs). Files and costs on the phone sheets are drawn as fields
like the rest, and the paste hint, a keyboard shortcut a phone has no use
for, is gone with its key.
This commit is contained in:
Maurice
2026-11-17 08:44:05 +01:00
parent 33d074c786
commit a3f6635633
100 changed files with 2538 additions and 510 deletions
+4 -1
View File
@@ -1,4 +1,4 @@
import type { TripTagCreateRequest, TripTagListResponse, TripTagResponse } from '@trek/shared';
import type { TripTagCreateRequest, TripTagListResponse, TripTagResponse, TripTagUpdateRequest } from '@trek/shared';
import apiClient from './client';
/** The tags a trip owns: every member reads them, and whoever may edit its places adds one. */
@@ -8,4 +8,7 @@ export const tripTagsApi = {
/** Answers the trip's existing tag when it already has one of that name. */
create: (tripId: number | string, body: TripTagCreateRequest): Promise<TripTagResponse> =>
apiClient.post(`/trips/${tripId}/tags`, body).then((r) => r.data),
/** A new name or colour for one of the trip's tags; every place carrying it shows the change. */
update: (tripId: number | string, tagId: number, body: TripTagUpdateRequest): Promise<TripTagResponse> =>
apiClient.put(`/trips/${tripId}/tags/${tagId}`, body).then((r) => r.data),
};
@@ -1,4 +1,4 @@
// FE-PLANNER-CONTACT-001 to FE-PLANNER-CONTACT-002
// FE-PLANNER-CONTACT-001 to FE-PLANNER-CONTACT-004
import { describe, expect, it, vi } from 'vitest'
import { useState } from 'react'
import userEvent from '@testing-library/user-event'
@@ -87,5 +87,33 @@ describe('PlaceContactFields (#2472)', () => {
// Still an e-mail field, so the keyboard and the browser's check stay.
expect(screen.getByLabelText('E-mail')).toHaveAttribute('type', 'email')
})
})
it('FE-PLANNER-CONTACT-003: a day opens around the clock with one switch, and an all-day lookup shows it on', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(<Harness onChange={onChange} />)
await user.click(screen.getByRole('button', { name: 'Add opening hours' }))
const allDay = screen.getByRole('switch', { name: 'Monday: Open 24 hours' })
expect(allDay).toHaveAttribute('aria-checked', 'false')
await user.click(allDay)
expect(JSON.parse(onChange.mock.lastCall![1])[0]).toEqual({ closed: false, open: '00:00', close: '23:59' })
expect(allDay).toHaveAttribute('aria-checked', 'true')
// The two time fields give way to the word.
expect(screen.queryByRole('textbox', { name: /Monday opens/ })).not.toBeInTheDocument()
expect(screen.getByText('Open 24 hours', { selector: 'span' })).toBeInTheDocument()
// Closing the day turns the all-day switch off.
await user.click(screen.getByRole('switch', { name: 'Monday: Closed' }))
expect(JSON.parse(onChange.mock.lastCall![1])[0]).toEqual({ closed: true })
expect(allDay).toHaveAttribute('aria-checked', 'false')
})
it('FE-PLANNER-CONTACT-004: looked-up hours open around the clock arrive with the all-day switch on', () => {
const suggested = Array.from({ length: 7 }, () => ({ closed: false, open: '00:00', close: '23:59' }))
render(<Harness onChange={vi.fn()} suggested={suggested} />)
for (const day of ['Monday', 'Sunday']) {
expect(screen.getByRole('switch', { name: `${day}: Open 24 hours` })).toHaveAttribute('aria-checked', 'true')
}
})
})
@@ -1,14 +1,22 @@
import { useEffect, useId, useRef, useState } from 'react'
import { Copy, Mail, Phone, RotateCcw, X } from 'lucide-react'
import { useId } from 'react'
import { Copy, DoorClosed, Mail, Phone, RotateCcw, X } from 'lucide-react'
import type { PlaceClientOrigin, PlaceOpeningHours } from '@trek/shared'
import CustomTimePicker from '../shared/CustomTimePicker'
import { Tooltip } from '../shared/Tooltip'
import { DialogSection, fs } from '../shared/DialogShell'
import { AddRowButton, EditorField, GRID_2, INPUT } from '../shared/dialogParts'
import { cleanWeek, readWeek, weekdayNames, writeWeek } from './placeHours'
import { isAllDay, weekdayNames } from './placeHours'
import { usePlaceHours } from './usePlaceHours'
import { useTranslation } from '../../i18n'
import { NO_AUTOFILL } from '../../utils/noAutofill'
/** A closed or all-day row says so in place of the two times, in a box of their height. */
const DAY_STATE = 'flex h-[38px] min-w-0 items-center rounded-[10px] border border-edge-faint bg-surface-tertiary px-3.5 font-medium text-content-muted'
/** The two switches after the times: square, as tall as a time field. */
const DAY_BUTTON = 'grid h-[38px] w-[38px] flex-none place-items-center rounded-[10px] border font-semibold transition-colors'
const DAY_BUTTON_OFF = 'border-edge bg-surface-input text-content-faint hover:border-content-faint hover:text-content'
const DAY_BUTTON_ON = 'border-transparent bg-accent text-accent-text shadow-sm'
interface Props {
/** Anchor for the "add by hand" jump from an empty search. */
id?: string
@@ -36,45 +44,11 @@ interface Props {
export function PlaceContactFields({ id: anchorId, phone, email, openingHours, onChange, suggestedHours }: Props) {
const { t, locale } = useTranslation()
const id = useId()
// The editor's own draft, so a half-typed time ("09:3") stays on screen while
// only finished times reach the place.
const [week, setDraft] = useState(() => readWeek(openingHours))
const written = useRef(openingHours)
const [editing, setEditing] = useState(() => openingHours !== '')
const hours = usePlaceHours({ openingHours, suggestedHours, onChange: (value, origin) => onChange('opening_hours', value, origin) })
const { week, editing } = hours
const names = weekdayNames(locale, 'short')
const longNames = weekdayNames(locale, 'long')
// A value from outside (a picked search result, a reopened place) replaces the draft.
useEffect(() => {
if (openingHours === written.current) return
written.current = openingHours
setDraft(readWeek(openingHours))
if (openingHours) setEditing(true)
}, [openingHours])
const setWeek = (next: PlaceOpeningHours, origin?: PlaceClientOrigin) => {
setDraft(next)
const text = writeWeek(cleanWeek(next))
written.current = text
onChange('opening_hours', text, origin)
}
const setDay = (i: number, patch: Partial<PlaceOpeningHours[number]>) =>
setWeek(week.map((day, d) => (d === i ? { ...day, ...patch } : day)))
const copyFirstToAll = () => setWeek(week.map(() => ({ ...week[0] })))
const clearHours = () => { setWeek(readWeek('')); setEditing(false) }
// Looked-up hours are taken over by a place that has none yet, once per lookup.
const adopted = useRef<PlaceOpeningHours | null>(null)
useEffect(() => {
if (!suggestedHours || adopted.current === suggestedHours) return
adopted.current = suggestedHours
if (written.current) return
setWeek(suggestedHours, 'enrichment')
setEditing(true)
// setWeek only reads refs and setters; the lookup is the trigger.
}, [suggestedHours])
const canTakeOver = !!suggestedHours && writeWeek(suggestedHours) !== writeWeek(cleanWeek(week))
return (
<div id={anchorId} className="flex flex-col gap-4">
<div className={GRID_2}>
@@ -98,22 +72,22 @@ export function PlaceContactFields({ id: anchorId, phone, email, openingHours, o
label={t('inspector.openingHours')}
action={editing ? (
<div className="flex items-center gap-1">
{canTakeOver && (
{hours.canTakeOver && (
<Tooltip label={t('places.hoursFromDetails')}>
<button type="button" onClick={() => setWeek(suggestedHours!, 'enrichment')} aria-label={t('places.hoursFromDetails')}
<button type="button" onClick={hours.takeOver} aria-label={t('places.hoursFromDetails')}
className="grid h-7 w-7 place-items-center rounded-full text-content-faint hover:bg-surface-hover hover:text-content">
<RotateCcw size={13} strokeWidth={2} />
</button>
</Tooltip>
)}
<Tooltip label={t('places.hoursCopyFirst', { day: longNames[0] })}>
<button type="button" onClick={copyFirstToAll} aria-label={t('places.hoursCopyFirst', { day: longNames[0] })}
<button type="button" onClick={hours.copyFirstToAll} aria-label={t('places.hoursCopyFirst', { day: longNames[0] })}
className="grid h-7 w-7 place-items-center rounded-full text-content-faint hover:bg-surface-hover hover:text-content">
<Copy size={13} strokeWidth={2} />
</button>
</Tooltip>
<Tooltip label={t('places.hoursRemove')}>
<button type="button" onClick={clearHours} aria-label={t('places.hoursRemove')}
<button type="button" onClick={hours.clearHours} aria-label={t('places.hoursRemove')}
className="grid h-7 w-7 place-items-center rounded-full text-content-faint hover:bg-surface-hover hover:text-danger">
<X size={14} strokeWidth={2.2} />
</button>
@@ -126,32 +100,45 @@ export function PlaceContactFields({ id: anchorId, phone, email, openingHours, o
{week.map((day, i) => (
<div key={i} className="grid min-h-[46px] grid-cols-[44px_minmax(0,1fr)_auto] items-center gap-2.5 px-3 py-1.5">
<span className="font-semibold text-content-secondary" style={fs(12.5, 'body')} title={longNames[i]}>{names[i]}</span>
{day.closed ? (
<span className="text-content-faint" style={fs(12.5, 'body')}>{t('places.hoursClosed')}</span>
{day.closed || isAllDay(day) ? (
<span className={DAY_STATE} style={fs(12.5, 'body')}>
{day.closed ? t('places.hoursClosed') : t('places.hoursAllDay')}
</span>
) : (
<div className="flex min-w-0 items-center gap-1.5">
<div className="min-w-0 flex-1">
<CustomTimePicker value={day.open ?? ''} onChange={v => setDay(i, { open: v || undefined })}
<div className='flex min-w-0 items-center gap-1.5'>
<div className='min-w-0 flex-1'>
<CustomTimePicker value={day.open ?? ''} onChange={v => hours.setDay(i, { open: v || undefined })}
aria-label={`${longNames[i]} ${t('places.hoursOpens')}`} />
</div>
<span className="flex-none text-content-faint">–</span>
<div className="min-w-0 flex-1">
<CustomTimePicker value={day.close ?? ''} onChange={v => setDay(i, { close: v || undefined })}
<span className='flex-none text-content-faint'>–</span>
<div className='min-w-0 flex-1'>
<CustomTimePicker value={day.close ?? ''} onChange={v => hours.setDay(i, { close: v || undefined })}
aria-label={`${longNames[i]} ${t('places.hoursCloses')}`} />
</div>
</div>
)}
<button type="button" role="switch" aria-checked={day.closed} aria-label={`${longNames[i]}: ${t('places.hoursClosed')}`}
onClick={() => setDay(i, day.closed ? { closed: false } : { closed: true, open: undefined, close: undefined })}
className={`rounded-full border px-2.5 py-[3px] font-semibold transition-colors ${day.closed ? 'border-[color:var(--text-primary)] bg-surface-tertiary text-content' : 'border-edge text-content-faint hover:text-content'}`}
style={fs(11)}>
{t('places.hoursClosed')}
</button>
<div className='flex items-center gap-1.5'>
<Tooltip label={t('places.hoursAllDay')}>
<button type='button' role='switch' aria-checked={isAllDay(day)} aria-label={`${longNames[i]}: ${t('places.hoursAllDay')}`}
onClick={() => hours.toggleAllDay(i)}
className={`${DAY_BUTTON} ${isAllDay(day) ? DAY_BUTTON_ON : DAY_BUTTON_OFF}`}
style={fs(11.5, 'body')}>
24h
</button>
</Tooltip>
<Tooltip label={t('places.hoursClosed')}>
<button type='button' role='switch' aria-checked={day.closed} aria-label={`${longNames[i]}: ${t('places.hoursClosed')}`}
onClick={() => hours.toggleClosed(i)}
className={`${DAY_BUTTON} ${day.closed ? DAY_BUTTON_ON : DAY_BUTTON_OFF}`}>
<DoorClosed size={15} strokeWidth={2} />
</button>
</Tooltip>
</div>
</div>
))}
</div>
) : (
<AddRowButton onClick={() => setEditing(true)}>{t('places.hoursAdd')}</AddRowButton>
<AddRowButton raised onClick={() => hours.setEditing(true)}>{t('places.hoursAdd')}</AddRowButton>
)}
</DialogSection>
</div>
@@ -238,7 +238,7 @@ export default function PlaceDetailsColumn({
// tiles, which is too small to tell a facade from a foyer. The column is
// stretched to the form's height by the row it sits in, so the extra room
// costs nothing that was being used.
<aside className={dialog ? `${SIDE_COLUMN} ${fluid ? '' : 'sm:w-80'}` : `w-full ${fluid ? '' : 'sm:w-80'} shrink-0 flex flex-col rounded-[18px] border border-[color:var(--m-cbr)] bg-[color:var(--m-card)] overflow-hidden self-stretch`}>
<aside className={dialog ? `${SIDE_COLUMN} ${fluid ? '' : 'sm:w-80'}` : `w-full ${fluid ? '' : 'sm:w-80'} shrink-0 flex flex-col self-stretch`}>
{dialog ? (
<ColumnHead icon={<Landmark size={13} strokeWidth={2.2} />}>{t('places.details.title')}</ColumnHead>
) : (
@@ -247,16 +247,15 @@ export default function PlaceDetailsColumn({
aria-expanded={open}
aria-controls={bodyId}
onClick={() => setOpen(o => !o)}
className={`flex w-full shrink-0 items-center gap-2.5 px-3 py-2.5 text-start ${open ? 'border-b border-[color:var(--m-rowbr)]' : ''}`}
// A badge over the column's blocks: what they are, and the fold.
className="flex h-[36px] w-full shrink-0 items-center gap-2 rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] pe-3 ps-3.5 text-start"
>
<span className="flex h-8 w-8 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-ink">
<Landmark size={15} strokeWidth={2} />
</span>
<span className="min-w-0 flex-1 text-body font-semibold text-m-ink">{t('places.details.title')}</span>
<Landmark size={13} strokeWidth={2.2} className="flex-none text-m-muted" />
<span className="min-w-0 flex-1 truncate font-geist text-[0.75rem] font-semibold text-m-ink">{t('places.details.title')}</span>
<ChevronDown
size={16}
size={13}
strokeWidth={2.2}
className={`flex-none text-m-muted transition-transform duration-200 ${open ? 'rotate-180' : ''}`}
className={`flex-none text-m-faint transition-transform duration-200 ${open ? 'rotate-180' : ''}`}
/>
</button>
)}
@@ -267,7 +266,7 @@ export default function PlaceDetailsColumn({
className={dialog ? 'contents' : `grid transition-[grid-template-rows] duration-300 ease-out ${open ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]'}`}
>
<div className={dialog ? 'flex min-h-0 flex-1 flex-col gap-3.5 overflow-y-auto px-3 pb-3' : `min-h-0 overflow-hidden ${open ? '' : 'invisible'}`}>
<div className={dialog ? 'contents' : 'p-3 space-y-3'}>
<div className={dialog ? 'contents' : 'space-y-3 pt-3'}>
{/* The place's picture first: its own ones are there whatever the sources answer. */}
<PictureBlock
photos={state === 'ready' && !data?.disabled ? (data?.photos ?? []) : []}
@@ -66,7 +66,7 @@ describe('PlaceFormModal', () => {
it('FE-COMP-PLACEFORM-005: shows Description field', () => {
render(<PlaceFormModal {...defaultProps} />);
expect(screen.getByPlaceholderText(/Short description/i)).toBeInTheDocument();
expect(screen.getByLabelText('Description')).toBeInTheDocument();
});
it('FE-COMP-PLACEFORM-006: shows Address field', () => {
@@ -1486,8 +1486,10 @@ describe('PlaceFormModal', () => {
render(<PlaceFormModal {...defaultProps} onSave={onSave} categories={[cat]} />);
await user.type(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), 'Louvre');
await user.type(screen.getByPlaceholderText(/Short description/i), 'Glass pyramid');
await user.type(screen.getByPlaceholderText(/Personal notes/i), 'Book ahead');
await user.type(screen.getByLabelText('Description'), 'Glass pyramid');
// The notes sit behind their own tab in the texts card.
await user.click(within(screen.getByRole('group', { name: 'Text to edit' })).getByRole('button', { name: 'Notes' }));
await user.type(screen.getByLabelText('Notes'), 'Book ahead');
await user.type(screen.getByPlaceholderText(/Street, City, Country/i), 'Rue de Rivoli');
await user.type(screen.getByPlaceholderText(/Longitude/i), '2.3376');
await user.type(screen.getByPlaceholderText('https://...'), 'https://louvre.fr');
@@ -2438,8 +2440,8 @@ describe('PlaceFormModal on the dialog frame', () => {
// The icon button beside it carries the same name.
expect(within(screen.getByPlaceholderText('Search places...').closest('.flex') as HTMLElement).getByRole('button', { name: 'Search' })).toBeInTheDocument();
expect(screen.getByLabelText('Name *')).toHaveValue('Louvre');
expect(screen.getByLabelText('Description')).toBe(screen.getByPlaceholderText(/Short description/i));
expect(screen.getByLabelText('Notes')).toBe(screen.getByPlaceholderText(/Personal notes/i));
expect(screen.getByLabelText('Description').tagName).toBe('TEXTAREA');
expect(screen.getByLabelText('Notes').tagName).toBe('TEXTAREA');
expect(screen.getByLabelText('Address')).toBe(screen.getByPlaceholderText(/Street, City, Country/i));
expect(screen.getByLabelText('Notes for this day')).toBeInTheDocument();
expect(screen.getByLabelText('Website')).toBe(screen.getByPlaceholderText('https://...'));
@@ -1,6 +1,5 @@
import { useState, useEffect, useRef, useMemo, useCallback, useId, type ReactNode } from 'react'
import type { PlaceClientOrigin, RoadtripStopType, TourListItem } from '@trek/shared'
import NoteFormatToolbar from '../shared/NoteFormatToolbar'
import { useAuthStore } from '../../store/authStore'
import { useAddonStore } from '../../store/addonStore'
import { useCanDo } from '../../store/permissionsStore'
@@ -25,6 +24,7 @@ import {
import { useNewCategory, usePlaceForm } from './usePlaceForm'
import { usePlaceTags } from './usePlaceTags'
import { PlaceFormTags } from './PlaceFormTags'
import { PlaceFormTexts } from './PlaceFormTexts'
import { usePlaceSearch } from './usePlaceSearch'
import { guessCategoryId } from '@trek/shared'
import { offersGoogleRetry } from '../../utils/placeSource'
@@ -39,9 +39,9 @@ import { DEFAULT_SERVICE_KIND, serviceStopChoice, type ServiceStopMode } from '.
import { STOP_KIND_BY_KEY } from '../Roadtrip/stopKinds'
import { getCategoryIcon } from '../shared/categoryIcons'
import {
DialogShell, DialogHeader, DialogTile, DialogSection, DialogFooter, FooterSpacer, DialogButton, NEUTRAL_TINT, fs,
DialogShell, DialogHeader, DialogTile, DialogFooter, FooterSpacer, DialogButton, NEUTRAL_TINT, fs,
} from '../shared/DialogShell'
import { EditorField, GRID_2, INPUT, LABEL, PANEL, TEXTAREA } from '../shared/dialogParts'
import { EditorField, GRID_2, INPUT, LABEL, PANEL } from '../shared/dialogParts'
import { SoftPill, tintOf } from './planParts'
import { TimeSection } from './PlaceFormTimeSection'
import { HeaderPills } from './PlaceFormHeaderPills'
@@ -223,6 +223,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
}, [place, prefillCoords, isOpen, assignmentId])
const places = useTripStore((s) => s.places)
const tripDays = useTripStore((s) => s.days)
// Where the trip is happening — the hint that tells the search which of a
// thousand identically named places is meant. Autocomplete wants a box, the
// search wants a point; both are derived from the same places.
@@ -406,6 +407,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
categories,
assignmentId,
dayAssignments,
dayNumber: dayNumberOf(assignmentId, dayAssignments, tripDays),
isMobile,
collectionsEnabled,
form,
@@ -800,12 +802,11 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
stop on a drive, which is not an activity anyone looks up by its tags. */}
{!serviceStop && <PlaceFormTags tags={S.tagField} t={t} />}
{/* The day in context: its times and its own note. Both live on the
day-assignment, not on the pool place (#2163), so they are only shown
when a single assignment is in context (itinerary edit, or a
single-assignment pool edit). Hidden when creating, and for unassigned
or multi-day pool edits where a single time is ambiguous and would not
persist. */}
{/* The day in context: its times. They live on the day-assignment, not on
the pool place (#2163), so they are only shown when a single assignment
is in context (itinerary edit, or a single-assignment pool edit). Hidden
when creating, and for unassigned or multi-day pool edits where a single
time is ambiguous and would not persist. */}
{!!(place && S.assignmentId) && (
<div className={PANEL}>
<TimeSection
@@ -818,39 +819,25 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
tour={props.tour}
t={t}
/>
<EditorField label={t('places.assignmentNotes')} htmlFor={`${fieldId}-day-notes`}>
<textarea
id={`${fieldId}-day-notes`}
value={form.assignment_notes ?? ''}
onChange={e => handleChange('assignment_notes', e.target.value)}
rows={2}
placeholder={t('places.assignmentNotesPlaceholder')}
className={`${TEXTAREA} resize-y`}
/>
</EditorField>
</div>
)}
<MarkdownField
id={`${fieldId}-description`}
label={t('places.formDescription')}
value={form.description}
onChange={v => handleChange('description', v)}
placeholder={t('places.formDescriptionPlaceholder')}
{/* Description, notes and the note for this day, one at a time. The day
note follows the times: only with a single assignment in context. */}
<PlaceFormTexts
fieldId={fieldId}
description={form.description}
notes={form.notes}
dayNotes={place && S.assignmentId ? (form.assignment_notes ?? "") : null}
dayNumber={S.dayNumber}
onChange={(field, value) => handleChange(field, value)}
t={t}
/>
{/* Notes — Markdown, same as the description, and rendered as such in the
inspector. The bar is how anyone finds that out. */}
<MarkdownField
id={`${fieldId}-notes`}
label={t('places.formNotes')}
value={form.notes}
onChange={v => handleChange('notes', v)}
placeholder={t('places.formNotesPlaceholder')}
maxLength={2000}
/>
{!showDetails && <div className={PANEL}><PlaceImageSection image={S.image} onPickUrl={S.pickImage} t={t} /></div>}
{!showDetails && <PlaceImageSection image={S.image} onPickUrl={S.pickImage} t={t} />}
{/* Link, files and how to reach the place, in one card. */}
<div className={PANEL}>
{/* The link and the files side by side, as on a booking. */}
<div className={canUploadFiles ? GRID_2 : ''}>
<EditorField label={t('places.formWebsite')} htmlFor={`${fieldId}-website`}>
@@ -884,6 +871,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
suggestedHours={S.detailsHours}
onChange={(field, value, origin) => handleChange(field, value, origin)}
/>
</div>
{/* Costs — create / view the expense linked to this place (#1298).
Same block, same flow as a booking: save first, then the editor.
@@ -891,6 +879,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
Never for a stop on a drive: a petrol stop is not an activity with a budget
line, and the fuel it buys is an expense of the trip rather than of a place. */}
{S.isBudgetEnabled && !serviceStop && (
<div className={PANEL}>
<BookingCostsSection
placeId={place?.id ?? null}
reservationId={null}
@@ -902,6 +891,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
customTooltips
whiteButtons
/>
</div>
)}
</form>
{twoColumn && (
@@ -912,32 +902,9 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
)
}
/** A Markdown field: its label, the formatting bar on the same line, the text under both. */
function MarkdownField({ id, label, value, onChange, placeholder, maxLength }: {
id: string
label: string
value: string
onChange: (value: string) => void
placeholder: string
maxLength?: number
}) {
const ref = useRef<HTMLTextAreaElement | null>(null)
return (
<DialogSection
className="min-w-0"
label={<label htmlFor={id}>{label}</label>}
action={<NoteFormatToolbar textareaRef={ref} onChange={onChange} compact customTooltips />}
>
<textarea
id={id}
ref={ref}
value={value}
onChange={e => onChange(e.target.value)}
rows={3}
maxLength={maxLength}
placeholder={placeholder}
className={`${TEXTAREA} resize-y`}
/>
</DialogSection>
)
/** The number of the day the edited visit is on, for the day note's tab; null when it is not known. */
function dayNumberOf(assignmentId: number | null, visits: Assignment[], days: { id: number; day_number?: number | null }[]): number | null {
if (!assignmentId) return null
const dayId = visits.find(visit => visit.id === assignmentId)?.day_id
return days.find(day => day.id === dayId)?.day_number ?? null
}
@@ -1,4 +1,4 @@
// FE-PLANNER-PLFORMTAGS-001 to FE-PLANNER-PLFORMTAGS-004: the markup of the place form's tags
// FE-PLANNER-PLFORMTAGS-001 to FE-PLANNER-PLFORMTAGS-007: the markup of the place form's tags
// on the desktop. The state behind it is usePlaceTags', tested on its own.
import { describe, expect, it, vi } from 'vitest';
@@ -17,6 +17,9 @@ function field(overrides: Partial<PlaceTagsField> = {}): PlaceTagsField {
toggle: vi.fn(),
name: '',
setName: vi.fn(),
newColor: '#ec4899',
setNewColor: vi.fn(),
recolor: vi.fn(() => Promise.resolve()),
saving: false,
canAdd: false,
addNew: vi.fn(() => Promise.resolve()),
@@ -57,7 +60,7 @@ describe('PlaceFormTags', () => {
const idle = field({ options: [] });
const { unmount } = render(<PlaceFormTags tags={idle} t={t} />);
expect(screen.getByRole('button', { name: 'places.addTag' })).toBeDisabled();
expect(within(screen.getByRole('group', { name: 'places.tags' })).getAllByRole('button')).toHaveLength(1);
expect(within(screen.getByRole('group', { name: 'places.tags' })).getAllByRole('button')).toHaveLength(2);
unmount();
const ready = field({ name: 'Viewpoint', canAdd: true });
@@ -65,4 +68,48 @@ describe('PlaceFormTags', () => {
fireEvent.click(screen.getByRole('button', { name: 'places.addTag' }));
expect(ready.addNew).toHaveBeenCalledTimes(1);
});
it("FE-PLANNER-PLFORMTAGS-005: a tag's dot opens the palette, and a swatch recolours the tag and closes it", () => {
const tags = field();
render(<PlaceFormTags tags={tags} t={t} />);
// The mock t ignores the name, so the first dot is Monument's.
const dot = screen.getAllByRole('button', { name: 'places.tagColor' })[0];
expect(screen.queryByRole('button', { name: '#10b981' })).not.toBeInTheDocument();
fireEvent.click(dot);
expect(dot).toHaveAttribute('aria-expanded', 'true');
// The tag's own colour is the one marked.
expect(screen.getByRole('button', { name: '#6366f1' })).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(screen.getByRole('button', { name: '#10b981' }));
expect(tags.recolor).toHaveBeenCalledWith(7, '#10b981');
expect(screen.queryByRole('button', { name: '#10b981' })).not.toBeInTheDocument();
});
it("FE-PLANNER-PLFORMTAGS-006: the new tag's colour is picked the same way and tints the field once a name is typed", () => {
const tags = field({ name: 'Food' });
render(<PlaceFormTags tags={tags} t={t} />);
fireEvent.click(screen.getByRole('button', { name: 'places.newTagColor' }));
fireEvent.click(screen.getByRole('button', { name: '#f97316' }));
expect(tags.setNewColor).toHaveBeenCalledWith('#f97316');
expect(tags.recolor).not.toHaveBeenCalled();
const pill = screen.getByRole('textbox', { name: 'places.newTag' }).parentElement as HTMLElement;
expect(pill.style.background).toContain('#ec4899');
});
it('FE-PLANNER-PLFORMTAGS-007: Escape and a click outside close the palette without a pick', () => {
const tags = field();
render(<PlaceFormTags tags={tags} t={t} />);
const onDialogKey = vi.fn();
document.addEventListener('keydown', onDialogKey);
fireEvent.click(screen.getByRole('button', { name: 'places.newTagColor' }));
fireEvent.keyDown(screen.getByRole('button', { name: '#f97316' }), { key: 'Escape' });
expect(screen.queryByRole('button', { name: '#f97316' })).not.toBeInTheDocument();
// Escape stays in the palette and does not reach the dialog around it.
expect(onDialogKey).not.toHaveBeenCalled();
document.removeEventListener('keydown', onDialogKey);
fireEvent.click(screen.getByRole('button', { name: 'places.newTagColor' }));
fireEvent.pointerDown(document.body);
expect(screen.queryByRole('button', { name: '#f97316' })).not.toBeInTheDocument();
expect(tags.setNewColor).not.toHaveBeenCalled();
});
});
+134 -54
View File
@@ -1,71 +1,151 @@
import { TRIP_TAG_NAME_MAX } from '@trek/shared';
import { Plus, Tag as TagIcon } from 'lucide-react';
import { Check, Plus } from 'lucide-react';
import { useState } from 'react';
import { DialogSection, fs } from '../shared/DialogShell';
import { PANEL } from '../shared/dialogParts';
import { TagColorPopover } from './TagColorPopover';
import type { PlaceTagsField } from './usePlaceTags';
type Translate = (key: string, params?: Record<string, string | number>) => string;
const ROW = 'flex flex-wrap items-center gap-1.5';
const CHIP =
'inline-flex min-w-0 max-w-full items-center gap-1.5 rounded-full border px-2.5 py-1 font-medium transition-colors';
const CHIP_ON = 'border-transparent bg-accent text-accent-text';
const CHIP_OFF = 'border-edge bg-surface-input text-content-secondary hover:text-content';
const NEW_TAG = 'inline-flex min-w-0 items-center gap-1';
const NEW_TAG_INPUT =
'w-36 min-w-0 rounded-full border border-dashed border-edge bg-transparent px-2.5 py-1 text-content outline-none placeholder:text-content-faint focus:border-solid focus:border-content-faint';
const ROW = 'flex flex-wrap items-center gap-2';
/** One tag: the colour dot and the name, two buttons in one pill. */
const PILL =
'relative inline-flex h-8 min-w-0 max-w-full items-center rounded-full border shadow-sm transition-[background-color,border-color,box-shadow] duration-150';
const PILL_OFF = 'border-edge bg-surface-input hover:border-content-faint';
const DOT_BUTTON =
'ms-1 grid h-6 w-6 flex-none place-items-center rounded-full transition-transform duration-150 hover:scale-110 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)]';
const DOT = 'h-3.5 w-3.5 rounded-full ring-1 ring-inset ring-edge';
const NAME_BUTTON = 'inline-flex h-full min-w-0 items-center gap-1.5 rounded-e-full ps-1.5 font-medium';
/** The tick of a picked tag, in a round white badge. */
const TICK = 'me-1 grid h-5 w-5 flex-none place-items-center rounded-full bg-surface-card shadow-sm';
const NEW_TAG =
'relative inline-flex h-8 min-w-0 items-center rounded-full border pe-1 transition-[background-color,border-color,box-shadow] duration-150 focus-within:shadow-sm';
const NEW_TAG_INPUT = 'w-32 min-w-0 bg-transparent ps-1.5 text-content outline-none placeholder:text-content-faint';
const ADD_BUTTON =
'grid h-[26px] w-[26px] flex-none place-items-center rounded-full bg-surface-card text-content-muted shadow-sm ring-1 ring-edge-faint transition-colors hover:text-content disabled:cursor-default disabled:opacity-50';
'grid h-6 w-6 flex-none place-items-center rounded-full shadow-sm transition-[background-color,color,transform] duration-150 enabled:hover:scale-110 disabled:cursor-default disabled:bg-surface-tertiary disabled:text-content-faint disabled:shadow-none';
const FALLBACK_COLOR = 'var(--text-muted)';
const tint = (color: string, percent: number) => `color-mix(in srgb, ${color} ${percent}%, var(--bg-input))`;
/**
* The tags of the place form on the desktop: every tag on offer as a switch, and a
* field that adds a new one to the trip. The state is usePlaceTags'; this is its markup.
* The tags of the place form on the desktop, as a card like the search and the
* address. Every tag on offer is a pill in its own colour: the name ticks it for
* the place, the dot opens a palette that recolours it for the whole trip. The
* field after them adds a new tag, in a colour picked the same way and shown on
* the field as it is typed. The state is usePlaceTags'; this is its markup.
*/
export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate }) {
// Which palette is open: a tag's id, 'new' for the new tag's colour, or none.
const [palette, setPalette] = useState<number | 'new' | null>(null);
// The colour a tag shows while its custom colour is being dragged, before it is kept.
const [preview, setPreview] = useState<{ id: number; color: string } | null>(null);
const typing = !!tags.name.trim();
const closePalette = () => {
setPalette(null);
setPreview(null);
};
return (
<DialogSection label={t('places.tags')}>
<div role="group" aria-label={t('places.tags')} className={ROW}>
{tags.options.map((tag) => (
<button
key={tag.id}
type="button"
aria-pressed={tag.on}
onClick={() => tags.toggle(tag.id)}
className={`${CHIP} ${tag.on ? CHIP_ON : CHIP_OFF}`}
style={fs(12, 'body')}
<div className={PANEL}>
<DialogSection label={t('places.tags')}>
<div role="group" aria-label={t('places.tags')} className={ROW}>
{tags.options.map((tag) => {
const color = (preview?.id === tag.id ? preview.color : tag.color) ?? FALLBACK_COLOR;
return (
<span
key={tag.id}
className={`${PILL} ${tag.on ? '' : PILL_OFF}`}
style={tag.on ? { background: tint(color, 18), borderColor: tint(color, 55) } : undefined}
>
<button
type="button"
aria-label={t('places.tagColor', { name: tag.name })}
aria-expanded={palette === tag.id}
onClick={() => (palette === tag.id ? closePalette() : setPalette(tag.id))}
className={DOT_BUTTON}
>
<span aria-hidden="true" className={DOT} style={{ background: color }} />
</button>
<button
type="button"
aria-pressed={tag.on}
onClick={() => tags.toggle(tag.id)}
className={`${NAME_BUTTON} ${tag.on ? 'pe-0 text-content' : 'pe-3 text-content-secondary hover:text-content'}`}
style={fs(12, 'body')}
>
<span className="truncate">{tag.name}</span>
{tag.on && (
<span aria-hidden="true" className={TICK}>
<Check size={11} strokeWidth={3.2} style={{ color }} />
</span>
)}
</button>
{palette === tag.id && (
<TagColorPopover
label={t('places.tagColor', { name: tag.name })}
value={tag.color ?? null}
onPick={(next) => void tags.recolor(tag.id, next)}
onPreview={(next) => setPreview({ id: tag.id, color: next })}
onClose={closePalette}
t={t}
/>
)}
</span>
);
})}
<span
className={NEW_TAG}
style={{
background: tint(tags.newColor, typing ? 14 : 6),
borderColor: tint(tags.newColor, typing ? 60 : 35),
borderStyle: typing ? 'solid' : 'dashed',
}}
>
<TagIcon
size={12}
strokeWidth={2.2}
className="flex-none"
style={{ color: tag.on ? undefined : tag.color }}
<button
type="button"
aria-label={t('places.newTagColor')}
aria-expanded={palette === 'new'}
onClick={() => (palette === 'new' ? closePalette() : setPalette('new'))}
className={DOT_BUTTON}
>
<span aria-hidden="true" className={DOT} style={{ background: tags.newColor }} />
</button>
<input
type="text"
value={tags.name}
onChange={(e) => tags.setName(e.target.value)}
onKeyDown={tags.handleNameKey}
maxLength={TRIP_TAG_NAME_MAX}
aria-label={t('places.newTag')}
placeholder={t('places.newTag')}
className={NEW_TAG_INPUT}
style={fs(12, 'body')}
/>
<span className="truncate">{tag.name}</span>
</button>
))}
<span className={NEW_TAG}>
<input
type="text"
value={tags.name}
onChange={(e) => tags.setName(e.target.value)}
onKeyDown={tags.handleNameKey}
maxLength={TRIP_TAG_NAME_MAX}
aria-label={t('places.newTag')}
placeholder={t('places.newTag')}
className={NEW_TAG_INPUT}
style={fs(12, 'body')}
/>
<button
type="button"
onClick={() => void tags.addNew()}
disabled={!tags.canAdd}
aria-label={t('places.addTag')}
className={ADD_BUTTON}
>
<Plus size={13} strokeWidth={2.4} />
</button>
</span>
</div>
</DialogSection>
<button
type="button"
onClick={() => void tags.addNew()}
disabled={!tags.canAdd}
aria-label={t('places.addTag')}
className={ADD_BUTTON}
style={tags.canAdd ? { background: tags.newColor, color: 'var(--bg-card)' } : undefined}
>
<Plus size={13} strokeWidth={2.8} />
</button>
{palette === 'new' && (
<TagColorPopover
label={t('places.newTagColor')}
value={tags.newColor}
onPick={tags.setNewColor}
onPreview={tags.setNewColor}
onClose={closePalette}
t={t}
/>
)}
</span>
</div>
</DialogSection>
</div>
);
}
@@ -0,0 +1,66 @@
// FE-PLANNER-PLFORMTEXTS-001 to FE-PLANNER-PLFORMTEXTS-004: the place form's three texts in one card.
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, within } from '../../../tests/helpers/render';
import { PlaceFormTexts } from './PlaceFormTexts';
const t = (key: string, params?: Record<string, string | number>) =>
params ? `${key}:${Object.values(params).join(',')}` : key;
function renderTexts(overrides: Partial<Parameters<typeof PlaceFormTexts>[0]> = {}) {
const onChange = vi.fn();
render(
<PlaceFormTexts
fieldId="f"
description="A tower"
notes=""
dayNotes={null}
onChange={onChange}
t={t}
{...overrides}
/>
);
return onChange;
}
const tabs = () => within(screen.getByRole('group', { name: 'places.notesKind' }));
describe('PlaceFormTexts', () => {
it('FE-PLANNER-PLFORMTEXTS-001: shows one text at a time, with the line on where it appears', () => {
renderTexts();
expect(tabs().getByRole('button', { name: 'places.notesTabAbout' })).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByLabelText('places.formDescription')).toBeVisible();
expect(screen.getByLabelText('places.formNotes')).not.toBeVisible();
expect(screen.getByLabelText('places.formDescription')).toHaveAccessibleDescription('places.notesHintDescription');
fireEvent.click(tabs().getByRole('button', { name: 'places.formNotes' }));
expect(screen.getByLabelText('places.formNotes')).toBeVisible();
expect(screen.getByLabelText('places.formDescription')).not.toBeVisible();
});
it('FE-PLANNER-PLFORMTEXTS-002: each text writes its own field, and both keep their text while hidden', () => {
const onChange = renderTexts({ notes: 'Book ahead' });
fireEvent.change(screen.getByLabelText('places.formDescription'), { target: { value: 'A tall tower' } });
expect(onChange).toHaveBeenLastCalledWith('description', 'A tall tower');
expect(screen.getByLabelText('places.formNotes')).toHaveValue('Book ahead');
fireEvent.change(screen.getByLabelText('places.formNotes'), { target: { value: 'Book early' } });
expect(onChange).toHaveBeenLastCalledWith('notes', 'Book early');
});
it('FE-PLANNER-PLFORMTEXTS-003: the day tab is there only with a visit in context, named after its day', () => {
renderTexts();
expect(tabs().getAllByRole('button')).toHaveLength(2);
expect(screen.queryByLabelText('places.assignmentNotes')).not.toBeInTheDocument();
});
it('FE-PLANNER-PLFORMTEXTS-004: the day note is plain text under the tab of its day', () => {
const onChange = renderTexts({ dayNotes: 'Meet at 9', dayNumber: 3 });
const day = tabs().getByRole('button', { name: 'places.notesTabDayN:3' });
fireEvent.click(day);
const field = screen.getByLabelText('places.assignmentNotes');
expect(field).toBeVisible();
expect(field).toHaveValue('Meet at 9');
fireEvent.change(field, { target: { value: 'Meet at 10' } });
expect(onChange).toHaveBeenLastCalledWith('assignment_notes', 'Meet at 10');
});
});
@@ -0,0 +1,122 @@
import { CalendarDays, Info, StickyNote } from 'lucide-react';
import { useRef, type ReactNode } from 'react';
import { fs } from '../shared/DialogShell';
import NoteFormatToolbar from '../shared/NoteFormatToolbar';
import { PANEL, Segmented } from '../shared/dialogParts';
import { usePlaceTextTabs, type PlaceTextField } from './usePlaceTextTabs';
type Translate = (key: string, params?: Record<string, string | number>) => string;
/** The desktop draws each tab with an icon; the phone keeps to the words. */
const ICONS: Record<PlaceTextField, ReactNode> = {
description: <Info size={13} strokeWidth={2} />,
notes: <StickyNote size={13} strokeWidth={2} />,
assignment_notes: <CalendarDays size={13} strokeWidth={2} />,
};
const DOT = 'h-1.5 w-1.5 flex-none rounded-full bg-current opacity-60';
/** The field's frame, holding the text and, under it, the formatting bar, like a message composer. */
const FIELD_BOX =
'overflow-hidden rounded-[10px] border border-edge bg-surface-input focus-within:ring-2 focus-within:ring-[color:var(--text-primary)]';
const BARE_TEXTAREA =
'block w-full min-w-0 resize-y border-0 bg-transparent px-3 py-2 text-[length:calc(13px*var(--fs-scale-body,1))] leading-normal text-content outline-none placeholder:text-content-faint';
const FIELD_BAR = 'flex items-center justify-end border-t border-edge-faint px-1.5 py-0.5';
/**
* The place's three texts in one card: what the place is, notes on it, and the
* note for this day's visit. A switch on top picks the one to write; the others
* stay mounted and only hidden, so each keeps its caret and undo history, and a
* dot marks a tab that already holds text. The day tab is there only when the
* form edits one day-assignment.
*/
export function PlaceFormTexts({
fieldId,
description,
notes,
dayNotes,
dayNumber = null,
onChange,
t,
}: {
fieldId: string;
description: string;
notes: string;
/** null when no single day-assignment is in context. */
dayNotes: string | null;
/** The day that visit is on, to name the tab after it ("Only day 3"). */
dayNumber?: number | null;
onChange: (field: PlaceTextField, value: string) => void;
t: Translate;
}) {
const { tabs, shown, setActive } = usePlaceTextTabs({ description, notes, dayNotes, dayNumber, t });
const refs = {
description: useRef<HTMLTextAreaElement | null>(null),
notes: useRef<HTMLTextAreaElement | null>(null),
assignment_notes: useRef<HTMLTextAreaElement | null>(null),
};
return (
<div className={PANEL}>
<Segmented
fill
value={shown.field}
onChange={setActive}
label={t('places.notesKind')}
options={tabs.map((tab) => ({
value: tab.field,
label: tab.value.trim() ? (
<>
{tab.label}
<span aria-hidden="true" className={DOT} />
</>
) : (
tab.label
),
icon: (
<span aria-hidden="true" className="flex">
{ICONS[tab.field]}
</span>
),
}))}
/>
{tabs.map((tab) => (
<p
key={tab.field}
id={`${fieldId}-${tab.field}-hint`}
hidden={tab.field !== shown.field}
className="m-0 -mb-1 leading-snug text-content-muted"
style={fs(11)}
>
{tab.hint}
</p>
))}
{/* The box hides, not the field: the field's own `block` class would win over `hidden`. */}
{tabs.map((tab) => (
<div key={tab.field} hidden={tab.field !== shown.field} className={FIELD_BOX}>
<textarea
id={`${fieldId}-${tab.field}`}
ref={refs[tab.field]}
aria-label={tab.aria}
aria-describedby={`${fieldId}-${tab.field}-hint`}
value={tab.value}
onChange={(e) => onChange(tab.field, e.target.value)}
rows={3}
maxLength={tab.maxLength}
className={BARE_TEXTAREA}
/>
{tab.markdown && (
<div className={FIELD_BAR}>
<NoteFormatToolbar
textareaRef={refs[tab.field]}
onChange={(v) => onChange(tab.field, v)}
compact
customTooltips
/>
</div>
)}
</div>
))}
</div>
);
}
@@ -169,7 +169,7 @@ function UploadTile({
disabled={reading}
aria-pressed={selected}
aria-label={t('places.uploadImage')}
className={`${TILE} ${ring(selected, dialog)} ${preview ? '' : 'border border-dashed border-edge bg-surface-card'}`}
className={`${TILE} ${ring(selected, dialog)} ${preview ? '' : dialog ? 'border border-edge-faint bg-surface-secondary hover:bg-surface-tertiary' : 'border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)]'}`}
onMouseEnter={() => onHover(!!preview)}
onMouseLeave={() => onHover(false)}
>
@@ -179,13 +179,15 @@ function UploadTile({
{selected && <Picked />}
</>
) : (
<span className="flex h-full w-full flex-col items-center justify-center gap-1 px-1 text-center text-caption leading-tight text-content-muted group-hover:text-content">
{reading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<ImagePlus className="h-4 w-4" strokeWidth={2} />
)}
{t('places.uploadImage')}
// Icon only: the tooltip and the button's name say what it does.
<span className="flex h-full w-full items-center justify-center">
<span className="grid h-11 w-11 place-items-center rounded-full bg-surface-card text-content-muted shadow-sm transition-transform duration-150 group-hover:scale-105 group-hover:text-content">
{reading ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<ImagePlus className="h-5 w-5" strokeWidth={1.9} />
)}
</span>
</span>
)}
</button>
@@ -330,7 +330,7 @@ export default function PlaceInspector({
// periods next to them, in the place's own timezone. open_now stays the fallback.
// Hours the traveller typed in win over looked-up ones (#2472): they are what
// somebody actually checked, and a place nobody listed has no other source.
const ownHours = hoursLines(place.opening_hours, locale, t('places.hoursClosed'))
const ownHours = hoursLines(place.opening_hours, locale, t('places.hoursClosed'), t('places.hoursAllDay'))
const openingHours = ownHours ?? googleDetails?.opening_hours ?? null
const detailLat = place.lat ?? googleDetails?.lat
const detailLng = place.lng ?? googleDetails?.lng
@@ -20,7 +20,8 @@ const LABEL: Record<RefreshField, string> = {
/** A value as the list shows it: hours as one line per day, the rest as stored. */
function shown(field: RefreshField, value: string, locale: string | undefined, t: Translate): string[] {
if (!value) return [t('places.refresh.empty')];
if (field === 'opening_hours') return hoursLines(value, locale, t('places.hoursClosed')) ?? [value];
if (field === 'opening_hours')
return hoursLines(value, locale, t('places.hoursClosed'), t('places.hoursAllDay')) ?? [value];
return [value];
}
@@ -0,0 +1,73 @@
// FE-PLANNER-TAGCOLORFIELD-001 to FE-PLANNER-TAGCOLORFIELD-003: the custom colour of the tag palette.
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import { TagColorField } from './TagColorField';
const t = (key: string) => key;
function renderField(value = '#ff0000') {
const onPreview = vi.fn();
const onPick = vi.fn();
render(<TagColorField value={value} onPreview={onPreview} onPick={onPick} t={t} />);
return { onPreview, onPick };
}
describe('TagColorField', () => {
it('FE-PLANNER-TAGCOLORFIELD-001: a complete typed code is shown at once and kept on Enter; a broken one goes back', () => {
const { onPreview, onPick } = renderField();
const code = screen.getByRole('textbox', { name: 'places.tagColorHex' });
expect(code).toHaveValue('#ff0000');
fireEvent.change(code, { target: { value: '#10b9' } });
expect(onPreview).not.toHaveBeenCalled();
fireEvent.change(code, { target: { value: '10b981' } });
expect(onPreview).toHaveBeenLastCalledWith('#10b981');
fireEvent.keyDown(code, { key: 'Enter' });
expect(onPick).toHaveBeenLastCalledWith('#10b981');
fireEvent.change(code, { target: { value: 'nope' } });
fireEvent.blur(code);
expect(code).toHaveValue('#10b981');
expect(onPick).toHaveBeenCalledTimes(1);
});
it('FE-PLANNER-TAGCOLORFIELD-002: the arrow keys move the field and the hue, and keep each step', () => {
const { onPick } = renderField('#ff0000');
const field = screen.getByRole('slider', { name: 'places.tagColorCustom' });
fireEvent.keyDown(field, { key: 'ArrowDown' });
// Full red, a little darker.
expect(onPick).toHaveBeenLastCalledWith('#f50000');
const hue = screen.getByRole('slider', { name: 'places.tagColorHue' });
expect(hue).toHaveAttribute('aria-valuenow', '0');
fireEvent.keyDown(hue, { key: 'ArrowRight' });
expect(hue).toHaveAttribute('aria-valuenow', '6');
fireEvent.keyDown(hue, { key: 'Tab' });
expect(onPick).toHaveBeenCalledTimes(2);
});
it('FE-PLANNER-TAGCOLORFIELD-003: a drag shows the colour as it goes and keeps the one it ends on', () => {
const { onPreview, onPick } = renderField('#ff0000');
const field = screen.getByRole('slider', { name: 'places.tagColorCustom' });
field.getBoundingClientRect = () => ({
left: 0,
top: 0,
width: 100,
height: 100,
right: 100,
bottom: 100,
x: 0,
y: 0,
toJSON: () => ({}),
});
field.setPointerCapture = vi.fn();
field.releasePointerCapture = vi.fn();
field.hasPointerCapture = () => true;
fireEvent.pointerDown(field, { pointerId: 1, clientX: 100, clientY: 0 });
fireEvent.pointerMove(field, { pointerId: 1, clientX: 0, clientY: 0 });
expect(onPreview).toHaveBeenLastCalledWith('#ffffff');
expect(onPick).not.toHaveBeenCalled();
fireEvent.pointerUp(field, { pointerId: 1, clientX: 0, clientY: 100 });
expect(onPick).toHaveBeenCalledTimes(1);
expect(onPick).toHaveBeenLastCalledWith('#000000');
});
});
@@ -0,0 +1,162 @@
import { useState, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
import { hexToHsv, hsvToHex, hueHex, normalizeHex, type Hsv } from '../../utils/colorSpace';
import { fs } from '../shared/DialogShell';
type Translate = (key: string, params?: Record<string, string | number>) => string;
// The hue circle as a track, and the field over the picked hue: white to the right
// into the hue, black from the bottom up. Built as strings so no colour literal sits in a style.
const HUE_TRACK = `linear-gradient(to right, ${[0, 60, 120, 180, 240, 300, 360].map(hueHex).join(', ')})`;
const fieldBackground = (h: number) =>
`linear-gradient(to top, ${hsvToHex({ h: 0, s: 0, v: 0 })}, transparent), linear-gradient(to right, ${hsvToHex({ h: 0, s: 0, v: 1 })}, ${hueHex(h)})`;
const THUMB =
'pointer-events-none absolute h-4 w-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-surface-card shadow-md';
const KEY_STEP = 0.04;
const clamp = (n: number) => Math.min(1, Math.max(0, n));
/** Where a pointer is inside an element, as 0 to 1 across and down. */
function at(e: ReactPointerEvent<HTMLElement>): { x: number; y: number } {
const box = e.currentTarget.getBoundingClientRect();
return { x: clamp((e.clientX - box.left) / box.width), y: clamp((e.clientY - box.top) / box.height) };
}
/**
* The custom colour of the tag palette: a field for saturation and brightness,
* a slider for the hue and the hex code to type. Dragging shows the colour as it
* goes (onPreview); it is kept when the pointer lets go, or when a typed code is
* complete (onPick), so a drag sends one change and not one per pixel.
*/
export function TagColorField({
value,
onPreview,
onPick,
t,
}: {
value: string;
onPreview: (hex: string) => void;
onPick: (hex: string) => void;
t: Translate;
}) {
const [hsv, setHsv] = useState<Hsv>(() => hexToHsv(value));
const [typed, setTyped] = useState(value);
const hex = hsvToHex(hsv);
const show = (next: Hsv) => {
setHsv(next);
const nextHex = hsvToHex(next);
setTyped(nextHex);
onPreview(nextHex);
};
const drag = (read: (e: ReactPointerEvent<HTMLElement>) => Hsv) => ({
onPointerDown: (e: ReactPointerEvent<HTMLElement>) => {
e.currentTarget.setPointerCapture(e.pointerId);
show(read(e));
},
onPointerMove: (e: ReactPointerEvent<HTMLElement>) => {
if (e.currentTarget.hasPointerCapture(e.pointerId)) show(read(e));
},
onPointerUp: (e: ReactPointerEvent<HTMLElement>) => {
e.currentTarget.releasePointerCapture(e.pointerId);
onPick(hsvToHex(read(e)));
},
});
// The arrow keys move the field's point and the slider, and keep the colour at once.
const nudge = (patch: (cur: Hsv) => Hsv) => (e: KeyboardEvent<HTMLElement>) => {
const step = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: 1, ArrowDown: -1 }[e.key];
if (step === undefined) return;
e.preventDefault();
const next = patch({
...hsv,
...(e.key === 'ArrowUp' || e.key === 'ArrowDown'
? { v: clamp(hsv.v + step * KEY_STEP) }
: { s: clamp(hsv.s + step * KEY_STEP) }),
});
show(next);
onPick(hsvToHex(next));
};
const typeHex = (raw: string) => {
setTyped(raw);
const norm = normalizeHex(raw);
if (!norm) return;
setHsv(hexToHsv(norm));
onPreview(norm);
};
const keepTyped = () => {
const norm = normalizeHex(typed);
if (norm) onPick(norm);
else setTyped(hex);
};
return (
<div className="flex w-full flex-col gap-2.5">
<div
role="slider"
tabIndex={0}
aria-label={t('places.tagColorCustom')}
aria-valuetext={hex}
aria-valuenow={Math.round(hsv.s * 100)}
aria-valuemin={0}
aria-valuemax={100}
className="relative h-28 cursor-crosshair touch-none rounded-[10px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)]"
style={{ background: fieldBackground(hsv.h) }}
onKeyDown={nudge((next) => next)}
{...drag((e) => {
const p = at(e);
return { h: hsv.h, s: p.x, v: 1 - p.y };
})}
>
<span className={THUMB} style={{ left: `${hsv.s * 100}%`, top: `${(1 - hsv.v) * 100}%`, background: hex }} />
</div>
<div
role="slider"
tabIndex={0}
aria-label={t('places.tagColorHue')}
aria-valuenow={Math.round(hsv.h)}
aria-valuemin={0}
aria-valuemax={360}
className="relative h-3 cursor-pointer touch-none rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)]"
style={{ background: HUE_TRACK }}
onKeyDown={(e) => {
const step = { ArrowLeft: -6, ArrowRight: 6 }[e.key];
if (step === undefined) return;
e.preventDefault();
const next = { ...hsv, h: (hsv.h + step + 360) % 360 };
show(next);
onPick(hsvToHex(next));
}}
{...drag((e) => ({ ...hsv, h: at(e).x * 359.9 }))}
>
<span className={`${THUMB} top-1/2`} style={{ left: `${(hsv.h / 360) * 100}%`, background: hueHex(hsv.h) }} />
</div>
<div className="flex items-center gap-2">
<span
aria-hidden="true"
className="h-7 w-7 flex-none rounded-full ring-1 ring-inset ring-edge"
style={{ background: hex }}
/>
<input
type="text"
value={typed}
onChange={(e) => typeHex(e.target.value)}
onBlur={keepTyped}
onKeyDown={(e) => {
if (e.key !== 'Enter') return;
e.preventDefault();
keepTyped();
}}
maxLength={7}
spellCheck={false}
aria-label={t('places.tagColorHex')}
className="h-7 min-w-0 flex-1 rounded-[8px] border border-edge bg-surface-input px-2 font-mono uppercase text-content outline-none focus:border-content-faint"
style={fs(12, 'body')}
/>
</div>
</div>
);
}
@@ -0,0 +1,131 @@
import { Check, ChevronDown } from 'lucide-react';
import { useEffect, useRef, useState, type KeyboardEvent } from 'react';
import { TAG_COLORS } from '../../utils/placeTags';
import { fs } from '../shared/DialogShell';
import { TagColorField } from './TagColorField';
type Translate = (key: string, params?: Record<string, string | number>) => string;
const PANEL =
'absolute start-0 top-full z-20 mt-2 flex w-[240px] flex-col gap-2.5 rounded-[16px] border border-edge-faint bg-surface-card p-3 shadow-lg';
const SWATCH =
'grid h-8 w-8 place-items-center rounded-full ring-1 ring-inset ring-edge transition-transform duration-150 hover:scale-110 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)]';
/** The tick on the picked swatch, in a white badge like the tick on a picked tag. */
const TICK = 'grid h-4 w-4 place-items-center rounded-full bg-surface-card shadow-sm';
const CUSTOM_TOGGLE =
'flex items-center gap-2 rounded-[10px] px-1.5 py-1 font-semibold text-content-secondary transition-colors hover:bg-surface-hover hover:text-content';
/** The custom colour's mark: every colour of the palette round the wheel. */
const RAINBOW = `conic-gradient(${[...TAG_COLORS, TAG_COLORS[0]].join(', ')})`;
/**
* The palette under a tag's colour dot: the trip's colours as swatches, and
* under them a colour of one's own in TREK's own colour field. A swatch is kept
* at once and closes the palette; the field keeps its colour when a drag ends
* and stays open. Closes on a click outside or Escape, which stays here and does
* not close the dialog around it.
*/
export function TagColorPopover({
label,
value,
onPick,
onPreview,
onClose,
className = PANEL,
t,
}: {
/** What the palette colours, for its accessible name. */
label: string;
value: string | null;
onPick: (color: string) => void;
/** The colour while it is being dragged, for whoever can show it before it is kept. */
onPreview?: (color: string) => void;
onClose: () => void;
/** The frame: a floating card by default; the phone lays it into the sheet instead. */
className?: string;
t: Translate;
}) {
const ref = useRef<HTMLDivElement | null>(null);
const current = value?.toLowerCase() ?? null;
const isPreset = current !== null && TAG_COLORS.includes(current);
// A colour of its own opens with the field showing it.
const [custom, setCustom] = useState(current !== null && !isPreset);
// The latest close handler, so the listener below is set up once.
const close = useRef(onClose);
useEffect(() => {
close.current = onClose;
});
useEffect(() => {
const outside = (e: PointerEvent) => {
// The dot that opened it toggles it itself; a click there is not "outside".
const host = ref.current?.parentElement;
if (host && !host.contains(e.target as Node)) close.current();
};
document.addEventListener('pointerdown', outside);
return () => document.removeEventListener('pointerdown', outside);
}, []);
const pick = (color: string) => {
onPick(color);
onClose();
};
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if (e.key !== 'Escape') return;
e.stopPropagation();
onClose();
};
return (
<div ref={ref} role="group" aria-label={label} className={className} onKeyDown={onKeyDown}>
<div className="grid grid-cols-5 justify-items-center gap-y-2">
{TAG_COLORS.map((color) => {
const on = current === color;
return (
<button
key={color}
type="button"
aria-label={color}
aria-pressed={on}
onClick={() => pick(color)}
className={SWATCH}
style={{ background: color }}
>
{on && (
<span className={TICK}>
<Check size={10} strokeWidth={3.4} aria-hidden="true" style={{ color }} />
</span>
)}
</button>
);
})}
</div>
<div className="h-px bg-[var(--border-faint)]" />
<button
type="button"
aria-expanded={custom}
onClick={() => setCustom(!custom)}
className={CUSTOM_TOGGLE}
style={fs(12, 'body')}
>
<span
aria-hidden="true"
className="grid h-5 w-5 place-items-center rounded-full"
style={{ background: RAINBOW }}
>
{current !== null && !isPreset && <span className="h-2 w-2 rounded-full bg-surface-card" />}
</span>
{t('places.tagColorCustom')}
<ChevronDown
size={14}
strokeWidth={2.2}
aria-hidden="true"
className={`ms-auto transition-transform ${custom ? 'rotate-180' : ''}`}
/>
</button>
{custom && (
<TagColorField value={value ?? TAG_COLORS[0]} onPreview={(hex) => onPreview?.(hex)} onPick={onPick} t={t} />
)}
</div>
);
}
@@ -1,6 +1,6 @@
// FE-PLANNER-HOURS-001 to FE-PLANNER-HOURS-003
// FE-PLANNER-HOURS-001 to FE-PLANNER-HOURS-007
import { describe, expect, it } from 'vitest'
import { cleanWeek, emptyWeek, hoursLines, periodsFromWeek, readWeek, weekdayNames, weekFromPeriods, writeWeek } from './placeHours'
import { ALL_DAY, cleanWeek, emptyWeek, hoursLines, isAllDay, periodsFromWeek, readWeek, weekdayNames, weekFromPeriods, writeWeek } from './placeHours'
const week = JSON.stringify([
{ closed: false, open: '09:00', close: '17:00' },
@@ -61,5 +61,27 @@ describe('typing and taking over (#2472)', () => {
expect(weekFromPeriods(null)).toBeNull()
expect(weekFromPeriods([])).toBeNull()
})
})
it('FE-PLANNER-HOURS-006: a place open around the clock reads as all day, from the lookup and by hand', () => {
const p = (day: number, h: number, m = 0) => ({ day, hour: h, minute: m })
// Google writes a place open all week as one period on Sunday that never closes.
expect(weekFromPeriods([{ open: p(0, 0), close: null }])).toEqual(Array.from({ length: 7 }, () => ({ closed: false, ...ALL_DAY })))
// A day from midnight to the next midnight is the same.
expect(weekFromPeriods([{ open: p(1, 0), close: p(2, 0) }])![0]).toEqual({ closed: false, ...ALL_DAY })
expect(isAllDay({ closed: false, open: '00:00', close: '23:59' })).toBe(true)
expect(isAllDay({ closed: false, open: '00:00', close: '00:00' })).toBe(true)
expect(isAllDay({ closed: false, open: '00:00', close: '22:00' })).toBe(false)
expect(isAllDay({ closed: true })).toBe(false)
})
it('FE-PLANNER-HOURS-007: the inspector names an all-day day instead of 00:00 to 23:59', () => {
const week = emptyWeek()
week[0] = { closed: false, ...ALL_DAY }
week[1] = { closed: false, open: '09:00', close: '17:00' }
const lines = hoursLines(writeWeek(week), 'en', 'Closed', 'Open 24 hours')!
expect(lines[0]).toBe('Monday: Open 24 hours')
expect(lines[1]).toBe('Tuesday: 09:00 – 17:00')
// Without the label the times stay, as before.
expect(hoursLines(writeWeek(week), 'en', 'Closed')![0]).toBe('Monday: 00:00 – 23:59')
})
})
+20 -4
View File
@@ -26,12 +26,21 @@ export function weekdayNames(locale: string | undefined, width: 'long' | 'short'
* looked-up hours (#2472): "Monday: 09:00 – 17:00", or the closed word. Null
* when the place has no hours of its own, so the looked-up ones take over.
*/
export function hoursLines(raw: string | null | undefined, locale: string | undefined, closedLabel: string): string[] | null {
/** Open around the clock, written the way the editor and the lookup both store it. */
export const ALL_DAY = { open: '00:00', close: '23:59' } as const
/** A day open around the clock: 00:00 to 23:59, or to 00:00 as some sources write it. */
export function isAllDay(day: PlaceOpeningHours[number]): boolean {
return !day.closed && day.open === ALL_DAY.open && (day.close === ALL_DAY.close || day.close === ALL_DAY.open)
}
export function hoursLines(raw: string | null | undefined, locale: string | undefined, closedLabel: string, allDayLabel?: string): string[] | null {
const week = parsePlaceHours(raw)
if (!hasPlaceHours(week)) return null
const names = weekdayNames(locale)
return week!.map((day, i) => {
if (day.closed) return `${names[i]}: ${closedLabel}`
if (allDayLabel && isAllDay(day)) return `${names[i]}: ${allDayLabel}`
if (!day.open && !day.close) return `${names[i]}: –`
return `${names[i]}: ${day.open ?? '…'} – ${day.close ?? '…'}`
})
@@ -80,11 +89,14 @@ interface Point { day: number; hour: number; minute: number }
* column shows, so a place edited later starts from them instead of from
* nothing. One range per day, the earliest opening to the latest closing, which
* is what the editor can hold; a day the provider names no period for is
* closed. A period that never closes is open around the clock. Null when the
* provider gave no periods at all.
* closed. A period that never closes is open around the clock: Google writes a
* place open all week as one such period on Sunday, so that alone opens every
* day. A span of a whole day or more is open around the clock too. Null when
* the provider gave no periods at all.
*/
export function weekFromPeriods(periods: { open: Point; close?: Point | null }[] | null | undefined): PlaceOpeningHours | null {
if (!periods?.length) return null
if (periods.length === 1 && !periods[0].close) return Array.from({ length: PLACE_HOURS_DAYS }, () => ({ closed: false, ...ALL_DAY }))
// Minutes after the day's own midnight; a close past midnight counts on top of 24h.
const span: ({ open: number; close: number } | null)[] = Array.from({ length: PLACE_HOURS_DAYS }, () => null)
for (const period of periods) {
@@ -96,6 +108,10 @@ export function weekFromPeriods(periods: { open: Point; close?: Point | null }[]
span[i] = cur ? { open: Math.min(cur.open, open), close: Math.max(cur.close, close) } : { open, close }
}
const clock = (m: number) => `${String(Math.floor(m / 60) % 24).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`
const week: PlaceOpeningHours = span.map(s => (s ? { closed: false, open: clock(s.open), close: clock(s.close) } : { closed: true }))
const week: PlaceOpeningHours = span.map(s => {
if (!s) return { closed: true }
if (s.open === 0 && s.close >= 24 * 60 - 1) return { closed: false, ...ALL_DAY }
return { closed: false, open: clock(s.open), close: clock(s.close) }
})
return week
}
@@ -0,0 +1,86 @@
import type { PlaceClientOrigin, PlaceOpeningHours } from '@trek/shared';
import { useEffect, useRef, useState } from 'react';
import { ALL_DAY, cleanWeek, isAllDay, readWeek, writeWeek } from './placeHours';
interface PlaceHoursOptions {
/** The stored hours text (JSON), empty when the place has none of its own. */
openingHours: string;
/** `origin` is set when the hours were taken over from the details lookup rather than typed. */
onChange: (value: string, origin?: PlaceClientOrigin) => void;
/**
* The hours the place details looked up, as a week. A place without hours of
* its own takes them over on its own; one that has some can take them over
* on request (takeOver).
*/
suggestedHours?: PlaceOpeningHours | null;
}
/**
* The opening hours of the place form (#2472): the one logic path behind the
* desktop dialog and the phone sheet, which draw their own rows over it. It
* keeps the editor's own draft, so a half-typed time ("09:3") stays on screen
* while only finished times reach the place, folds the week away until someone
* wants it, and switches a day closed or open around the clock.
*/
export function usePlaceHours({ openingHours, onChange, suggestedHours }: PlaceHoursOptions) {
const [week, setDraft] = useState(() => readWeek(openingHours));
const written = useRef(openingHours);
const [editing, setEditing] = useState(() => openingHours !== '');
// A value from outside (a picked search result, a reopened place) replaces the draft.
useEffect(() => {
if (openingHours === written.current) return;
written.current = openingHours;
setDraft(readWeek(openingHours));
if (openingHours) setEditing(true);
}, [openingHours]);
const setWeek = (next: PlaceOpeningHours, origin?: PlaceClientOrigin) => {
setDraft(next);
const text = writeWeek(cleanWeek(next));
written.current = text;
onChange(text, origin);
};
const setDay = (i: number, patch: Partial<PlaceOpeningHours[number]>) =>
setWeek(week.map((day, d) => (d === i ? { ...day, ...patch } : day)));
const toggleClosed = (i: number) =>
setDay(i, week[i].closed ? { closed: false } : { closed: true, open: undefined, close: undefined });
const toggleAllDay = (i: number) =>
setDay(i, isAllDay(week[i]) ? { open: undefined, close: undefined } : { closed: false, ...ALL_DAY });
const copyFirstToAll = () => setWeek(week.map(() => ({ ...week[0] })));
const clearHours = () => {
setWeek(readWeek(''));
setEditing(false);
};
// Looked-up hours are taken over by a place that has none yet, once per lookup.
const adopted = useRef<PlaceOpeningHours | null>(null);
useEffect(() => {
if (!suggestedHours || adopted.current === suggestedHours) return;
adopted.current = suggestedHours;
if (written.current) return;
setWeek(suggestedHours, 'enrichment');
setEditing(true);
// setWeek only reads refs and setters; the lookup is the trigger.
}, [suggestedHours]);
const canTakeOver = !!suggestedHours && writeWeek(suggestedHours) !== writeWeek(cleanWeek(week));
const takeOver = () => {
if (suggestedHours) setWeek(suggestedHours, 'enrichment');
};
return {
week,
editing,
setEditing,
setDay,
toggleClosed,
toggleAllDay,
copyFirstToAll,
clearHours,
canTakeOver,
takeOver,
};
}
export type PlaceHoursField = ReturnType<typeof usePlaceHours>;
+28 -2
View File
@@ -31,6 +31,7 @@ interface PlaceTagsOptions {
export function usePlaceTags({ tripId, place, tags, setForm, t, toast }: PlaceTagsOptions) {
const tripTags = useTripStore((s) => s.tripTags);
const addTripTag = useTripStore((s) => s.addTripTag);
const updateTripTag = useTripStore((s) => s.updateTripTag);
const carried = place?.tags;
const saved = useMemo(() => placeTagIds(carried), [carried]);
const selected = tags ?? saved;
@@ -40,6 +41,9 @@ export function usePlaceTags({ tripId, place, tags, setForm, t, toast }: PlaceTa
);
const [name, setName] = useState('');
const [saving, setSaving] = useState(false);
// The colour picked for the next new tag; until one is picked, the trip's next one in turn.
const [pickedColor, setNewColor] = useState<string | null>(null);
const newColor = pickedColor ?? nextTagColor(tripTags);
/** Changes the ticked set from what it is when the change lands, not from what it was when it was asked for. */
const change = (next: (ids: number[]) => number[]) =>
@@ -54,9 +58,10 @@ export function usePlaceTags({ tripId, place, tags, setForm, t, toast }: PlaceTa
if (!wanted || saving) return;
setSaving(true);
try {
const tag = await addTripTag(tripId, { name: wanted, color: nextTagColor(tripTags) });
const tag = await addTripTag(tripId, { name: wanted, color: newColor });
change((ids) => (ids.includes(tag.id) ? ids : [...ids, tag.id]));
setName('');
setNewColor(null);
} catch {
toast.error(offlineOr(t, t('places.tagCreateError')));
} finally {
@@ -64,6 +69,15 @@ export function usePlaceTags({ tripId, place, tags, setForm, t, toast }: PlaceTa
}
};
/** A new colour for one of the trip's tags, for every place that carries it. */
const recolor = async (id: number, color: string) => {
try {
await updateTripTag(tripId, id, { color });
} catch {
toast.error(offlineOr(t, t('places.tagColorError')));
}
};
/** Enter in the name field adds the tag; with a name typed it never reaches the place's own save. */
const handleNameKey = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key !== 'Enter' || !name.trim()) return;
@@ -71,7 +85,19 @@ export function usePlaceTags({ tripId, place, tags, setForm, t, toast }: PlaceTa
void addNew();
};
return { options, toggle, name, setName, saving, canAdd: !!name.trim() && !saving, addNew, handleNameKey };
return {
options,
toggle,
name,
setName,
newColor,
setNewColor,
recolor,
saving,
canAdd: !!name.trim() && !saving,
addNew,
handleNameKey,
};
}
export type PlaceTagsField = ReturnType<typeof usePlaceTags>;
@@ -0,0 +1,71 @@
import { useState } from 'react';
type Translate = (key: string, params?: Record<string, string | number>) => string;
export type PlaceTextField = 'description' | 'notes' | 'assignment_notes';
export interface PlaceTextTab {
field: PlaceTextField;
/** The tab's own short name. */
label: string;
/** The field's name for a screen reader, the one it always had. */
aria: string;
/** Where the text shows up, under the tabs. */
hint: string;
value: string;
/** Rendered as Markdown where it is shown, so the desktop offers the formatting bar. */
markdown: boolean;
maxLength?: number;
}
interface PlaceTextTabsOptions {
description: string;
notes: string;
/** null when no single day-assignment is in context. */
dayNotes: string | null;
/** The day that visit is on, to name the tab after it ("Only day 3"). */
dayNumber?: number | null;
t: Translate;
}
/**
* The place form's three texts as tabs: what the place is, notes on it, and the
* note for one day's visit, which is only there when the form edits one visit.
* The one logic path behind the desktop card and the phone sheet; each draws its
* own tabs and field over it.
*/
export function usePlaceTextTabs({ description, notes, dayNotes, dayNumber = null, t }: PlaceTextTabsOptions) {
const [active, setActive] = useState<PlaceTextField>('description');
const tabs: PlaceTextTab[] = [
{
field: 'description',
label: t('places.notesTabAbout'),
aria: t('places.formDescription'),
hint: t('places.notesHintDescription'),
value: description,
markdown: true,
},
{
field: 'notes',
label: t('places.formNotes'),
aria: t('places.formNotes'),
hint: t('places.notesHintNotes'),
value: notes,
markdown: true,
maxLength: 2000,
},
];
if (dayNotes !== null) {
tabs.push({
field: 'assignment_notes',
label: dayNumber ? t('places.notesTabDayN', { day: dayNumber }) : t('places.notesTabDay'),
aria: t('places.assignmentNotes'),
hint: t('places.notesHintDay'),
value: dayNotes,
markdown: false,
});
}
// The day tab can go away under an open form (the visit is removed elsewhere).
const shown = tabs.find((tab) => tab.field === active) ?? tabs[0];
return { tabs, shown, setActive };
}
+16 -4
View File
@@ -174,12 +174,24 @@ export function PopoverListPanel({ list, label, className = '', children }: {
}
/** The dashed full-width button that adds a row: a stop, a leg. */
export function AddRowButton({ onClick, disabled, children }: { onClick: () => void; disabled?: boolean; children: ReactNode }) {
export function AddRowButton({ onClick, disabled, raised = false, children }: {
onClick: () => void
disabled?: boolean
/**
* On a PANEL: the white raised button of the cards (the costs' "Create expense"),
* at its size, instead of a dashed outline on grey.
*/
raised?: boolean
children: ReactNode
}) {
const look = raised
? 'gap-2 border-transparent bg-surface-card px-[13px] text-content shadow-sm ring-1 ring-edge-faint hover:bg-surface-hover'
: 'gap-1.5 border-dashed border-edge px-3 text-content-muted hover:border-content-faint hover:text-content'
return (
<button type="button" onClick={onClick} disabled={disabled}
className="flex w-full items-center justify-center gap-1.5 rounded-[10px] border border-dashed border-edge px-3 py-2 font-semibold text-content-muted hover:border-content-faint hover:text-content disabled:cursor-default disabled:opacity-50"
style={fs(12, 'body')}>
<Plus size={13} strokeWidth={2.2} />{children}
className={`flex w-full items-center justify-center rounded-[10px] border py-2 font-semibold transition-colors disabled:cursor-default disabled:opacity-50 ${look}`}
style={fs(raised ? 13 : 12, 'body')}>
<Plus size={raised ? 14 : 13} strokeWidth={2.2} />{children}
</button>
)
}
@@ -40,7 +40,6 @@ export default function MBookingFilesCosts({
files={pendingFiles}
onAdd={files => setPendingFiles(prev => [...prev, ...files])}
onRemove={idx => setPendingFiles(prev => prev.filter((_, i) => i !== idx))}
hideHint
canAttach={canUploadFiles}
attached={bookingFiles.attached}
linkable={bookingFiles.linkable}
@@ -1,5 +1,5 @@
import { useState } from 'react'
import { ChevronRight, Link2, Link2Off, Plus, Search, Trash2 } from 'lucide-react'
import { ChevronRight, Link2, Link2Off, Receipt, Search, Trash2 } from 'lucide-react'
import { useTranslation } from '../../../../i18n'
import { useTripStore } from '../../../../store/tripStore'
import { useSettingsStore } from '../../../../store/settingsStore'
@@ -8,10 +8,8 @@ import { formatMoney } from '../../../../utils/formatters'
import { catMeta } from '../../../../components/Budget/costsCategories'
import { useExpenseLinks } from '../../../../components/Planner/useRecordLinks'
import type { BudgetItem } from '../../../../types'
import { Eyebrow } from './PlSheetChrome'
import { AddFieldButton, Eyebrow } from './PlSheetChrome'
const PILL_CLS =
'flex w-full items-center justify-center gap-[6px] rounded-[13px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] py-[11px] text-[0.78125rem] font-semibold text-m-ink disabled:opacity-40'
const ROW_ICON_BTN_CLS = 'flex h-8 w-8 flex-none items-center justify-center rounded-full text-m-faint active:bg-[color:var(--m-ic)]'
// Past this many the list gets a search field, a trip can collect a lot of expenses.
const SEARCH_FROM = 6
@@ -88,16 +86,10 @@ export default function MLinkedCosts({ reservationId = null, placeId = null, hin
)}
<div className={`grid gap-2 ${targetId ? 'grid-cols-2' : 'grid-cols-1'}`}>
<button type="button" onClick={onCreate} disabled={createDisabled} className={PILL_CLS}>
<Plus size={13} strokeWidth={2.2} />
{t('reservations.createExpense')}
</button>
<AddFieldButton icon={Receipt} label={t('reservations.createExpense')} onClick={onCreate} disabled={createDisabled} />
{/* Linking needs the record to exist, so it waits for the first save. */}
{targetId !== null && (
<button type="button" onClick={() => setPicking(v => !v)} aria-expanded={picking} className={`${PILL_CLS} ${picking ? '!bg-m-act !text-m-actfg' : ''}`}>
<Link2 size={13} strokeWidth={2.2} />
{t('files.link')}
</button>
<AddFieldButton icon={Link2} label={t('files.link')} onClick={() => setPicking(v => !v)} pressed={picking} ariaExpanded={picking} />
)}
</div>
@@ -133,7 +125,7 @@ export default function MLinkedCosts({ reservationId = null, placeId = null, hin
</div>
)}
{linked.length === 0 && <div className="mt-[5px] font-geist text-[0.625rem] text-m-faint">{t(hintKey)}</div>}
{linked.length === 0 && <p className="m-0 mt-[5px] px-[6px] font-geist text-[0.65625rem] leading-snug text-m-faint">{t(hintKey)}</p>}
</>
)
}
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState, type ClipboardEvent } from 'react'
import { MapPin, MapPinOff } from 'lucide-react'
import { Globe, MapPin, MapPinOff } from 'lucide-react'
import MSheet from '../../../components/MSheet'
import {
DEFAULT_FORM,
@@ -14,12 +14,16 @@ import {
import { usePlaceForm } from '../../../../components/Planner/usePlaceForm'
import { usePlaceTags } from '../../../../components/Planner/usePlaceTags'
import { addressWithoutCoordinates } from '../../../../components/Planner/placeCoordinates'
import { Eyebrow, FIELD_AREA_CLS, FIELD_CLS, FormSheetBody, FormSheetFooter, FormSheetHeader } from './PlSheetChrome'
import { AMOUNT_FIELD_CLS, Eyebrow, FIELD_CLS, FormSheetBody, FormSheetFooter, FormSheetHeader } from './PlSheetChrome'
import { useAddonStore } from '../../../../store/addonStore'
import type { BookingExpenseRequest } from '../../../../components/Planner/BookingCostsSection.types'
import PlPlaceSearch, { type PlSearchPick } from './PlPlaceSearch'
import PlCategoryPicker from './PlCategoryPicker'
import { PlTagPicker } from './PlTags'
import { PlPlaceTexts } from './PlPlaceTexts'
import { PlContactFields } from './PlContactFields'
import { weekFromPeriods } from '../../../../components/Planner/placeHours'
import type { PlaceOpeningHours } from '@trek/shared'
import PlTimeFields from './PlTimeFields'
import PlFileAttach from './PlFileAttach'
import MLinkedCosts from './MLinkedCosts'
@@ -83,6 +87,8 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
place: editingPlace, imageUrl: form.image_url, pendingImage, canUploadFiles, stageUpload, stageAttached, removeImage,
})
const [resolvingPick, setResolvingPick] = useState(false)
// The hours the details looked up, offered to the hours editor as on the desktop.
const [detailsHours, setDetailsHours] = useState<PlaceOpeningHours | null>(null)
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
// Set right before submit: the place has to exist before an expense can point
// at it, exactly like MReservationSheet does it.
@@ -129,6 +135,7 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
else if (prefillCoords) next = prefillForm(prefillCoords)
else next = DEFAULT_FORM
openForm(next, editingPlace, prefillCoords)
setDetailsHours(null)
setDeleteArmed(false)
// storedAssignments is a fresh map each load, so it is read at open time only.
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -181,6 +188,9 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
}
}
// The day the visit under edit is on, to name its note's tab after it.
const dayNumber = ctxAssignment ? planner.days.find(d => d.id === ctxAssignment.day_id)?.day_number ?? null : null
// End before start blocks the save — tied to the values, not to which entry
// point opened the sheet.
const hasTimeError = endsBeforeStart(form.place_time, form.end_time)
@@ -265,6 +275,7 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
onPickImage={pickImage}
image={image}
onAdoptDescription={adoptDescription}
onHours={hours => setDetailsHours(weekFromPeriods(hours.periods))}
hasDescription={!!form.description.trim()}
language={language}
timeFormat={timeFormat}
@@ -289,25 +300,6 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
className={`${FIELD_CLS} ${resolvingPick ? 'opacity-60' : ''}`}
/>
<Eyebrow className="mb-[5px] mt-3 uppercase">{t('places.formDescription')}</Eyebrow>
<textarea
value={form.description}
onChange={e => handleChange('description', e.target.value)}
rows={2}
placeholder={t('places.formDescriptionPlaceholder')}
className={FIELD_AREA_CLS}
/>
<Eyebrow className="mb-[5px] mt-3 uppercase">{t('places.formNotes')}</Eyebrow>
<textarea
value={form.notes}
onChange={e => handleChange('notes', e.target.value)}
rows={2}
maxLength={2000}
placeholder={t('places.formNotesPlaceholder')}
className={FIELD_AREA_CLS}
/>
<Eyebrow className="mb-[5px] mt-3 uppercase">{t('places.formAddress')}</Eyebrow>
<input
type="text"
@@ -323,7 +315,7 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
value={form.lat}
onChange={e => handleChange('lat', e.target.value.replace(/[^0-9.-]/g, ''))}
onPaste={handleCoordPaste}
placeholder={t('places.formLat')}
placeholder={t('places.formLatLabel')}
className={`${FIELD_CLS} flex-1 text-[0.8125rem] [font-variant-numeric:tabular-nums]`}
/>
<input
@@ -331,7 +323,7 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
inputMode="decimal"
value={form.lng}
onChange={e => handleChange('lng', e.target.value.replace(/[^0-9.-]/g, ''))}
placeholder={t('places.formLng')}
placeholder={t('places.formLngLabel')}
className={`${FIELD_CLS} flex-1 text-[0.8125rem] [font-variant-numeric:tabular-nums]`}
/>
</div>
@@ -343,42 +335,56 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
</p>
)}
<Eyebrow className="mb-[6px] mt-3 uppercase">{t('places.formCategory')}</Eyebrow>
<Eyebrow className="mb-[5px] mt-3 uppercase">{t('places.formCategory')}</Eyebrow>
<PlCategoryPicker planner={planner} value={form.category_id} onChange={id => handleChange('category_id', id)} />
<PlTagPicker tags={tagField} t={t} />
{/* Times live per day-assignment — only editable when one is in context.
Same for the day-specific note (#2163). */}
{/* Times live per day-assignment, only editable when one is in context (#2163). */}
{sheetPlace && sheetAssignmentId && (
<>
<PlTimeFields
planner={planner}
startTime={form.place_time}
endTime={form.end_time}
onChange={handleChange}
assignmentId={sheetAssignmentId}
dayAssignments={dayAssignments}
hasTimeError={hasTimeError}
/>
<Eyebrow className="mb-[5px] mt-3 uppercase">{t('places.assignmentNotes')}</Eyebrow>
<textarea
value={form.assignment_notes ?? ''}
onChange={e => handleChange('assignment_notes', e.target.value)}
rows={2}
placeholder={t('places.assignmentNotesPlaceholder')}
className={FIELD_AREA_CLS}
/>
</>
<PlTimeFields
planner={planner}
startTime={form.place_time}
endTime={form.end_time}
onChange={handleChange}
assignmentId={sheetAssignmentId}
dayAssignments={dayAssignments}
hasTimeError={hasTimeError}
/>
)}
{/* Description, notes and the note for this visit, one at a time; the day's
tab follows the times and is only there with a visit in context. */}
<PlPlaceTexts
description={form.description}
notes={form.notes}
dayNotes={sheetPlace && sheetAssignmentId ? (form.assignment_notes ?? '') : null}
dayNumber={dayNumber}
onChange={(field, value) => handleChange(field, value)}
t={t}
/>
<Eyebrow className="mb-[5px] mt-3 uppercase">{t('places.formWebsite')}</Eyebrow>
<input
type="url"
dir="ltr"
value={form.website}
onChange={e => handleChange('website', e.target.value)}
placeholder="https://"
className={FIELD_CLS}
<label className={AMOUNT_FIELD_CLS}>
<Globe size={14} strokeWidth={2} aria-hidden="true" className="flex-none text-m-faint" />
<input
type="url"
dir="ltr"
value={form.website}
onChange={e => handleChange('website', e.target.value)}
placeholder="https://"
aria-label={t('places.formWebsite')}
className="min-w-0 flex-1 bg-transparent font-[inherit] text-[0.84375rem] font-medium text-m-ink outline-none placeholder:text-m-faint"
/>
</label>
<PlContactFields
phone={form.phone ?? ''}
email={form.email ?? ''}
openingHours={form.opening_hours ?? ''}
suggestedHours={detailsHours}
onChange={(field, value, origin) => handleChange(field, value, origin)}
locale={locale}
t={t}
/>
{canUploadFiles && (
@@ -1,7 +1,8 @@
import { Ban, Check, Plus } from 'lucide-react'
import { useState } from 'react'
import { Ban, Check, ChevronDown, Plus, X } from 'lucide-react'
import { getCategoryIcon } from '../../../../components/shared/categoryIcons'
import { useNewCategory } from '../../../../components/Planner/usePlaceForm'
import { FIELD_CLS } from './PlSheetChrome'
import { FIELD_CLS, SELECT_FIELD_CLS } from './PlSheetChrome'
import type { TripPlanner } from '../MTripShell'
interface PlCategoryPickerProps {
@@ -11,89 +12,107 @@ interface PlCategoryPickerProps {
onChange: (categoryId: string) => void
}
const PILL_BASE =
'flex flex-none items-center gap-[5px] rounded-full px-[11px] py-[6px] text-[0.71875rem] font-semibold'
const LIST = 'mt-[6px] max-h-[264px] overflow-y-auto overscroll-contain rounded-2xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-glass)]'
const ROW = 'flex w-full items-center gap-[10px] border-b border-[color:var(--m-rowbr)] px-[13px] py-[11px] text-start last:border-b-0'
const ROW_TEXT = 'min-w-0 flex-1 truncate text-[0.84375rem]'
/**
* Category pills of the place form: "no category" + every trip category, plus
* an inline create flow (dashed pill → name input) the demo leaves out but the
* desktop form has — new categories are selected right away.
* The category of the place form on the phone: one field that opens the list,
* the way the cost sheet picks its category, instead of a pill for every
* category, which took half the sheet on a trip with many. "No category" leads
* the list and a new category is made at its foot, picked straight away like on
* the desktop.
*/
export default function PlCategoryPicker({ planner, value, onChange }: PlCategoryPickerProps) {
const { t, toast, categories, tripActions } = planner
const [open, setOpen] = useState(false)
const pick = (id: string) => {
onChange(id)
setOpen(false)
}
const {
open: creating, setOpen: setCreating, name: newName, setName: setNewName, saving, submit: handleCreate,
} = useNewCategory({ variant: 'sheet', create: tripActions.addCategory, onCreated: onChange, t, toast })
} = useNewCategory({ variant: 'sheet', create: tripActions.addCategory, onCreated: pick, t, toast })
const current = (categories || []).find(cat => String(cat.id) === value)
const CurrentIcon = current ? getCategoryIcon(current.icon) : Ban
return (
<div className="flex flex-wrap gap-[6px]">
<div>
<button
type="button"
onClick={() => onChange('')}
className={`${PILL_BASE} ${value === '' ? 'bg-m-act text-m-actfg' : 'bg-[color:var(--m-ic)] text-m-muted'}`}
aria-expanded={open}
aria-label={`${t('places.formCategory')}: ${current ? current.name : t('places.noCategory')}`}
onClick={() => setOpen(v => !v)}
className={`${SELECT_FIELD_CLS} gap-[10px] text-start`}
>
<Ban size={13} strokeWidth={2} />
{t('places.noCategory')}
<CurrentIcon size={15} strokeWidth={2} className="flex-none" style={current?.color ? { color: current.color } : undefined} />
<span className={`${ROW_TEXT} font-medium ${current ? 'text-m-ink' : 'text-m-faint'}`}>
{current ? current.name : t('places.noCategory')}
</span>
<ChevronDown size={14} strokeWidth={2} className={`flex-none text-m-faint transition-transform duration-200 ${open ? 'rotate-180' : ''}`} />
</button>
{(categories || []).map(cat => {
const active = value === String(cat.id)
const Icon = getCategoryIcon(cat.icon)
return (
<button
key={cat.id}
type="button"
onClick={() => onChange(String(cat.id))}
className={`${PILL_BASE} ${active ? 'bg-m-act text-m-actfg' : 'bg-[color:var(--m-ic)] text-m-muted'}`}
>
<Icon size={13} strokeWidth={2} />
{cat.name}
</button>
)
})}
{!creating ? (
<button
type="button"
onClick={() => setCreating(true)}
className={`${PILL_BASE} border-[1.5px] border-dashed border-[color:var(--m-trackoff)] text-m-muted`}
>
<Plus size={13} strokeWidth={2.2} />
{t('mobileTrip.newCategory')}
</button>
) : (
<div className="mt-1 flex w-full items-center gap-2">
<input
type="text"
value={newName}
onChange={e => setNewName(e.target.value)}
onKeyDown={e => {
if (e.key === 'Enter') {
e.preventDefault()
void handleCreate()
}
}}
placeholder={t('places.categoryNamePlaceholder')}
autoFocus
className={`${FIELD_CLS} flex-1`}
/>
<button
type="button"
onClick={handleCreate}
disabled={!newName.trim() || saving}
aria-label={t('common.add')}
className="flex h-10 w-10 flex-none items-center justify-center rounded-[12px] bg-m-act text-m-actfg disabled:opacity-40"
>
<Check size={15} strokeWidth={2.4} />
</button>
<button
type="button"
onClick={() => {
setCreating(false)
setNewName('')
}}
className="flex-none text-[0.78125rem] font-semibold text-m-muted"
>
{t('common.cancel')}
{open && (
<div className={LIST}>
<button type="button" aria-pressed={value === ''} onClick={() => pick('')} className={ROW}>
<Ban size={14} strokeWidth={2} className="flex-none text-m-muted" />
<span className={`${ROW_TEXT} ${value === '' ? 'font-semibold text-m-ink' : 'text-m-muted'}`}>{t('places.noCategory')}</span>
{value === '' && <Check size={14} strokeWidth={2.4} className="flex-none text-m-ink" />}
</button>
{(categories || []).map(cat => {
const on = value === String(cat.id)
const Icon = getCategoryIcon(cat.icon)
return (
<button key={cat.id} type="button" aria-pressed={on} onClick={() => pick(String(cat.id))} className={ROW}>
<Icon size={14} strokeWidth={2} className="flex-none" style={cat.color ? { color: cat.color } : undefined} />
<span className={`${ROW_TEXT} ${on ? 'font-semibold text-m-ink' : 'text-m-ink'}`}>{cat.name}</span>
{on && <Check size={14} strokeWidth={2.4} className="flex-none text-m-ink" />}
</button>
)
})}
{!creating ? (
<button type="button" onClick={() => setCreating(true)} className={ROW}>
<Plus size={14} strokeWidth={2.2} className="flex-none text-m-muted" />
<span className={`${ROW_TEXT} font-semibold text-m-muted`}>{t('mobileTrip.newCategory')}</span>
</button>
) : (
<div className="flex items-center gap-2 px-[10px] py-[8px]">
<input
type="text"
value={newName}
onChange={e => setNewName(e.target.value)}
onKeyDown={e => {
if (e.key === 'Enter') {
e.preventDefault()
void handleCreate()
}
}}
placeholder={t('places.categoryNamePlaceholder')}
autoFocus
className={`${FIELD_CLS} flex-1`}
/>
<button
type="button"
onClick={handleCreate}
disabled={!newName.trim() || saving}
aria-label={t('common.add')}
className="flex h-10 w-10 flex-none items-center justify-center rounded-full bg-m-act text-m-actfg disabled:opacity-40"
>
<Check size={15} strokeWidth={2.4} />
</button>
<button
type="button"
onClick={() => {
setCreating(false)
setNewName('')
}}
aria-label={t('common.cancel')}
className="flex h-10 w-10 flex-none items-center justify-center rounded-full text-m-muted"
>
<X size={15} strokeWidth={2.2} />
</button>
</div>
)}
</div>
)}
</div>
@@ -0,0 +1,65 @@
// FE-MOB-PLCONTACT-001 to FE-MOB-PLCONTACT-003: phone, e-mail and opening hours on the phone.
import { useState } from 'react';
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../../../tests/helpers/render';
import { PlContactFields } from './PlContactFields';
const t = (key: string, params?: Record<string, string | number>) =>
params ? `${key}:${Object.values(params).join(',')}` : key;
function Harness({ onChange, start = '' }: { onChange: (field: string, value: string) => void; start?: string }) {
const [state, setState] = useState({ phone: '', email: '', opening_hours: start });
return (
<PlContactFields
phone={state.phone}
email={state.email}
openingHours={state.opening_hours}
locale="en"
t={t}
onChange={(field, value) => {
onChange(field, value);
setState((s) => ({ ...s, [field]: value }));
}}
/>
);
}
describe('PlContactFields', () => {
it('FE-MOB-PLCONTACT-001: phone and e-mail are fields of their own', () => {
const onChange = vi.fn();
render(<Harness onChange={onChange} />);
fireEvent.change(screen.getByLabelText('places.formPhone'), { target: { value: '+1 555' } });
expect(onChange).toHaveBeenLastCalledWith('phone', '+1 555');
fireEvent.change(screen.getByLabelText('places.formEmail'), { target: { value: 'a@b.co' } });
expect(onChange).toHaveBeenLastCalledWith('email', 'a@b.co');
expect(screen.getByLabelText('places.formEmail')).toHaveAttribute('type', 'email');
});
it('FE-MOB-PLCONTACT-002: the week unfolds from one field, and a day opens around the clock or closes', () => {
const onChange = vi.fn();
render(<Harness onChange={onChange} />);
expect(screen.queryByRole('switch', { name: 'Monday: places.hoursAllDay' })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'places.hoursAdd' }));
fireEvent.click(screen.getByRole('switch', { name: 'Monday: places.hoursAllDay' }));
expect(JSON.parse(onChange.mock.lastCall![1])[0]).toEqual({ closed: false, open: '00:00', close: '23:59' });
expect(screen.getByRole('switch', { name: 'Monday: places.hoursAllDay' })).toHaveAttribute('aria-checked', 'true');
fireEvent.click(screen.getByRole('switch', { name: 'Tuesday: places.hoursClosed' }));
expect(JSON.parse(onChange.mock.lastCall![1])[1]).toEqual({ closed: true });
expect(screen.getByText('places.hoursClosed')).toBeInTheDocument();
});
it('FE-MOB-PLCONTACT-003: Monday goes to every day, and the week folds away again', () => {
const onChange = vi.fn();
render(<Harness onChange={onChange} />);
fireEvent.click(screen.getByRole('button', { name: 'places.hoursAdd' }));
fireEvent.click(screen.getByRole('switch', { name: 'Monday: places.hoursClosed' }));
fireEvent.click(screen.getByRole('button', { name: 'places.hoursCopyFirst:Monday' }));
expect(JSON.parse(onChange.mock.lastCall![1]).every((d: { closed: boolean }) => d.closed)).toBe(true);
fireEvent.click(screen.getByRole('button', { name: 'places.hoursRemove' }));
expect(onChange).toHaveBeenLastCalledWith('opening_hours', '');
expect(screen.getByRole('button', { name: 'places.hoursAdd' })).toBeInTheDocument();
});
});
@@ -0,0 +1,186 @@
import type { PlaceClientOrigin, PlaceOpeningHours } from '@trek/shared';
import { Clock, Copy, DoorClosed, Mail, Phone, RotateCcw, X } from 'lucide-react';
import { isAllDay, weekdayNames } from '../../../../components/Planner/placeHours';
import { usePlaceHours } from '../../../../components/Planner/usePlaceHours';
import CustomTimePicker from '../../../../components/shared/CustomTimePicker';
import { NO_AUTOFILL } from '../../../../utils/noAutofill';
import { AddFieldButton, AMOUNT_FIELD_CLS, Eyebrow, FORM_PAIR_CLS } from './PlSheetChrome';
type Translate = (key: string, params?: Record<string, string | number>) => string;
const LABEL = 'mb-[5px] mt-3 uppercase';
const BARE_INPUT =
'min-w-0 flex-1 bg-transparent font-[inherit] text-[0.84375rem] font-medium text-m-ink outline-none placeholder:text-m-faint';
const HEAD_BUTTON = 'grid h-[28px] w-[28px] place-items-center rounded-full text-m-muted active:bg-[color:var(--m-ic)]';
const WEEK = 'overflow-hidden rounded-[18px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)]';
const DAY_ROW =
'grid grid-cols-[22px_minmax(0,1fr)_auto] items-center gap-[6px] border-b border-[color:var(--m-rowbr)] px-[8px] py-[6px] last:border-b-0';
/** A closed or all-day day says so where its two times would be. */
const DAY_STATE = 'flex h-[38px] items-center px-[4px] text-[0.78125rem] font-medium text-m-muted';
/** The two switches after the times: round, as tall as a time field. */
const DAY_BUTTON = 'grid h-[30px] w-[30px] flex-none place-items-center rounded-full text-[0.6875rem] font-bold';
const DAY_BUTTON_OFF = 'bg-[color:var(--m-card)] text-m-muted';
const DAY_BUTTON_ON = 'bg-m-act text-m-actfg';
/**
* Phone, e-mail and opening hours on the phone (#2472), as on the desktop. The
* week stays folded behind one row until someone wants it; each day then has
* its two times, a switch for open around the clock and one for closed. The
* hours are usePlaceHours', shared with the desktop dialog.
*/
export function PlContactFields({
phone,
email,
openingHours,
suggestedHours,
onChange,
locale,
t,
}: {
phone: string;
email: string;
openingHours: string;
suggestedHours?: PlaceOpeningHours | null;
onChange: (field: 'phone' | 'email' | 'opening_hours', value: string, origin?: PlaceClientOrigin) => void;
locale: string | undefined;
t: Translate;
}) {
const hours = usePlaceHours({
openingHours,
suggestedHours,
onChange: (value, origin) => onChange('opening_hours', value, origin),
});
const names = weekdayNames(locale, 'short');
const longNames = weekdayNames(locale, 'long');
return (
<>
<div className={`${FORM_PAIR_CLS} mt-3`}>
<div>
<Eyebrow className="mb-[5px] uppercase">{t('places.formPhone')}</Eyebrow>
<label className={AMOUNT_FIELD_CLS}>
<Phone size={14} strokeWidth={2} aria-hidden="true" className="flex-none text-m-faint" />
<input
type="tel"
value={phone}
onChange={(e) => onChange('phone', e.target.value)}
maxLength={50}
placeholder="+49 …"
aria-label={t('places.formPhone')}
className={BARE_INPUT}
{...NO_AUTOFILL}
/>
</label>
</div>
<div>
<Eyebrow className="mb-[5px] uppercase">{t('places.formEmail')}</Eyebrow>
<label className={AMOUNT_FIELD_CLS}>
<Mail size={14} strokeWidth={2} aria-hidden="true" className="flex-none text-m-faint" />
<input
type="email"
dir="ltr"
value={email}
onChange={(e) => onChange('email', e.target.value)}
maxLength={254}
placeholder="info@…"
aria-label={t('places.formEmail')}
className={BARE_INPUT}
{...NO_AUTOFILL}
/>
</label>
</div>
</div>
<div className={`${LABEL} flex items-center`}>
<Eyebrow className="uppercase">{t('inspector.openingHours')}</Eyebrow>
{hours.editing && (
<span className="-my-[6px] ms-auto flex items-center">
{hours.canTakeOver && (
<button
type="button"
onClick={hours.takeOver}
aria-label={t('places.hoursFromDetails')}
className={HEAD_BUTTON}
>
<RotateCcw size={13} strokeWidth={2} />
</button>
)}
<button
type="button"
onClick={hours.copyFirstToAll}
aria-label={t('places.hoursCopyFirst', { day: longNames[0] })}
className={HEAD_BUTTON}
>
<Copy size={13} strokeWidth={2} />
</button>
<button
type="button"
onClick={hours.clearHours}
aria-label={t('places.hoursRemove')}
className={HEAD_BUTTON}
>
<X size={14} strokeWidth={2.2} />
</button>
</span>
)}
</div>
{hours.editing ? (
<div className={WEEK}>
{hours.week.map((day, i) => {
const allDay = isAllDay(day);
return (
<div key={i} className={DAY_ROW}>
<span className="text-[0.71875rem] font-semibold text-m-ink">{names[i]}</span>
{day.closed || allDay ? (
<span className={DAY_STATE}>{day.closed ? t('places.hoursClosed') : t('places.hoursAllDay')}</span>
) : (
<div className="flex min-w-0 items-center gap-[3px]">
<div className="min-w-0 flex-1">
<CustomTimePicker
value={day.open ?? ''}
onChange={(v) => hours.setDay(i, { open: v || undefined })}
aria-label={`${longNames[i]} ${t('places.hoursOpens')}`}
/>
</div>
<div className="min-w-0 flex-1">
<CustomTimePicker
value={day.close ?? ''}
onChange={(v) => hours.setDay(i, { close: v || undefined })}
aria-label={`${longNames[i]} ${t('places.hoursCloses')}`}
/>
</div>
</div>
)}
<div className="flex items-center gap-[3px]">
<button
type="button"
role="switch"
aria-checked={allDay}
aria-label={`${longNames[i]}: ${t('places.hoursAllDay')}`}
onClick={() => hours.toggleAllDay(i)}
className={`${DAY_BUTTON} ${allDay ? DAY_BUTTON_ON : DAY_BUTTON_OFF}`}
>
24h
</button>
<button
type="button"
role="switch"
aria-checked={day.closed}
aria-label={`${longNames[i]}: ${t('places.hoursClosed')}`}
onClick={() => hours.toggleClosed(i)}
className={`${DAY_BUTTON} ${day.closed ? DAY_BUTTON_ON : DAY_BUTTON_OFF}`}
>
<DoorClosed size={14} strokeWidth={2} />
</button>
</div>
</div>
);
})}
</div>
) : (
<AddFieldButton icon={Clock} label={t('places.hoursAdd')} onClick={() => hours.setEditing(true)} />
)}
</>
);
}
@@ -4,14 +4,13 @@ import { openFile } from '../../../../utils/fileDownload'
import { isWalletPass } from '../../../../components/Files/FileManager.helpers'
import type { TripFile } from '../../../../types'
import type { TripPlanner } from '../MTripShell'
import { AddFieldButton, Eyebrow } from './PlSheetChrome'
interface PlFileAttachProps {
planner: TripPlanner
files: File[]
onAdd: (files: File[]) => void
onRemove: (index: number) => void
/** Hide the "you can also paste…" subline (booking/transport sheets keep it terse). */
hideHint?: boolean
/** False hides the picker pill (no upload permission); the row still lists and links files. */
canAttach?: boolean
/** Files already on the record, listed above the pending ones and opened on tap. */
@@ -31,41 +30,23 @@ const ITEM_CLS = 'flex w-full items-center gap-2 rounded-[10px] bg-[color:var(--
* Clipboard paste is handled by the sheet's onPaste so it works from any
* focused field.
*/
export default function PlFileAttach({ planner, files, onAdd, onRemove, hideHint = false, canAttach = true, attached = [], linkable = [], onLink }: PlFileAttachProps) {
export default function PlFileAttach({ planner, files, onAdd, onRemove, canAttach = true, attached = [], linkable = [], onLink }: PlFileAttachProps) {
const { t } = planner
const inputRef = useRef<HTMLInputElement>(null)
const [picking, setPicking] = useState(false)
const canLink = !!onLink && linkable.length > 0
return (
<div className="mt-3 rounded-[13px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 py-[10px]">
<div className="flex items-center gap-[10px]">
<div className="min-w-0 flex-1">
<div className="text-[0.78125rem] font-semibold text-m-ink">{t('files.title')}</div>
{!hideHint && <div className="truncate font-geist text-[0.65625rem] text-m-faint">{t('files.pasteHint')}</div>}
<div>
<Eyebrow className="mb-[5px] mt-3 uppercase">{t('files.title')}</Eyebrow>
{(canAttach || canLink) && (
<div className={`grid gap-2 ${canAttach && canLink ? 'grid-cols-2' : 'grid-cols-1'}`}>
{canAttach && <AddFieldButton icon={Paperclip} label={t('files.attach')} onClick={() => inputRef.current?.click()} />}
{canLink && (
<AddFieldButton icon={Link2} label={t('files.link')} onClick={() => setPicking(v => !v)} pressed={picking} ariaExpanded={picking} />
)}
</div>
{canLink && (
<button
type="button"
onClick={() => setPicking(v => !v)}
aria-expanded={picking}
className={`flex flex-none items-center gap-[5px] rounded-full border px-3 py-[5px] text-[0.6875rem] font-semibold ${picking ? 'border-transparent bg-m-act text-m-actfg' : 'border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] text-m-ink'}`}
>
<Link2 size={12} strokeWidth={2.2} />
{t('files.link')}
</button>
)}
{canAttach && (
<button
type="button"
onClick={() => inputRef.current?.click()}
className="flex flex-none items-center gap-[5px] rounded-full bg-m-act px-3 py-[6px] text-[0.6875rem] font-semibold text-m-actfg"
>
<Paperclip size={12} strokeWidth={2.2} />
{t('files.attach')}
</button>
)}
</div>
)}
<input
ref={inputRef}
type="file"
@@ -0,0 +1,48 @@
// FE-MOB-PLTEXTS-001 to FE-MOB-PLTEXTS-003: the place's three texts on the phone, one at a time.
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../../../tests/helpers/render';
import { PlPlaceTexts } from './PlPlaceTexts';
const t = (key: string, params?: Record<string, string | number>) =>
params ? `${key}:${Object.values(params).join(',')}` : key;
function setup(overrides: Partial<Parameters<typeof PlPlaceTexts>[0]> = {}) {
const onChange = vi.fn();
render(<PlPlaceTexts description="A tower" notes="" dayNotes={null} onChange={onChange} t={t} {...overrides} />);
return onChange;
}
describe('PlPlaceTexts', () => {
it('FE-MOB-PLTEXTS-001: heads the texts and shows the description first, with where it appears', () => {
setup();
expect(screen.getByText('places.textsLabel')).toBeInTheDocument();
expect(screen.getByRole('tab', { name: 'places.notesTabAbout' })).toHaveAttribute('aria-selected', 'true');
expect(screen.getByLabelText('places.formDescription')).toBeVisible();
expect(screen.getByLabelText('places.formNotes')).not.toBeVisible();
expect(screen.getByText('places.notesHintDescription')).toBeVisible();
});
it('FE-MOB-PLTEXTS-002: a tab switches the field, and each text writes its own', () => {
const onChange = setup({ notes: 'Cash only' });
fireEvent.click(screen.getByRole('tab', { name: 'places.formNotes' }));
expect(screen.getByLabelText('places.formNotes')).toBeVisible();
expect(screen.getByLabelText('places.formNotes')).toHaveValue('Cash only');
fireEvent.change(screen.getByLabelText('places.formNotes'), { target: { value: 'Cards too' } });
expect(onChange).toHaveBeenLastCalledWith('notes', 'Cards too');
fireEvent.change(screen.getByLabelText('places.formDescription'), { target: { value: 'A tall tower' } });
expect(onChange).toHaveBeenLastCalledWith('description', 'A tall tower');
});
it('FE-MOB-PLTEXTS-003: the day note has a tab of its own only with a visit, named after its day', () => {
const { unmount } = render(<PlPlaceTexts description="" notes="" dayNotes={null} onChange={vi.fn()} t={t} />);
expect(screen.getAllByRole('tab')).toHaveLength(2);
unmount();
const onChange = setup({ dayNotes: 'Meet at 9', dayNumber: 2 });
fireEvent.click(screen.getByRole('tab', { name: 'places.notesTabDayN:2' }));
expect(screen.getByLabelText('places.assignmentNotes')).toHaveValue('Meet at 9');
fireEvent.change(screen.getByLabelText('places.assignmentNotes'), { target: { value: 'Meet at 10' } });
expect(onChange).toHaveBeenLastCalledWith('assignment_notes', 'Meet at 10');
});
});
@@ -0,0 +1,65 @@
import { usePlaceTextTabs, type PlaceTextField } from '../../../../components/Planner/usePlaceTextTabs';
import MSegmented from '../../../components/MSegmented';
import { Eyebrow, FIELD_AREA_CLS } from './PlSheetChrome';
type Translate = (key: string, params?: Record<string, string | number>) => string;
const DOT = 'ms-[5px] inline-block h-[5px] w-[5px] rounded-full bg-current align-middle opacity-60';
/**
* The place's three texts on the phone, as on the desktop: what the place is,
* notes on it, and the note for this day's visit, one at a time under a switch,
* with a line on where the text shows up. The others stay mounted and only
* hidden, so each keeps what was typed; a dot marks a tab that holds text. The
* tabs are usePlaceTextTabs', shared with the desktop card.
*/
export function PlPlaceTexts({
description,
notes,
dayNotes,
dayNumber = null,
onChange,
t,
}: {
description: string;
notes: string;
/** null when no single day-assignment is in context. */
dayNotes: string | null;
dayNumber?: number | null;
onChange: (field: PlaceTextField, value: string) => void;
t: Translate;
}) {
const { tabs, shown, setActive } = usePlaceTextTabs({ description, notes, dayNotes, dayNumber, t });
return (
<div className="flex flex-col gap-2">
<Eyebrow className="-mb-[3px] mt-3 uppercase">{t('places.textsLabel')}</Eyebrow>
<MSegmented
value={shown.field}
onChange={setActive}
options={tabs.map((tab) => ({
value: tab.field,
label: (
<>
{tab.label}
{tab.value.trim() && <span aria-hidden="true" className={DOT} />}
</>
),
}))}
/>
{tabs.map((tab) => (
<div key={tab.field} hidden={tab.field !== shown.field}>
<textarea
value={tab.value}
onChange={(e) => onChange(tab.field, e.target.value)}
rows={3}
maxLength={tab.maxLength}
aria-label={tab.aria}
className={FIELD_AREA_CLS}
/>
<p className="m-0 mt-[5px] px-[6px] font-geist text-[0.65625rem] leading-snug text-m-faint">{tab.hint}</p>
</div>
))}
</div>
);
}
@@ -1,5 +1,5 @@
import { ComponentProps, HTMLAttributes, ReactNode, useState } from 'react'
import { Trash2, X } from 'lucide-react'
import { Plus, Trash2, X } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import MIconBtn from '../../../components/MIconBtn'
import { edgeFadeClass, useEdgeFade } from '../../../components/useEdgeFade'
@@ -35,6 +35,35 @@ export const FORM_PAIR_CLS = 'grid grid-cols-1 gap-2 [@container(min-width:400px
export const SELECT_FIELD_CLS =
'flex h-[42px] w-full min-w-0 items-center overflow-hidden rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-[14px]'
/**
* A button that adds something (opening hours, a file, an expense), drawn as an
* empty field of the form: its icon, the action in the placeholder's grey and a
* plus at the end, so it reads as one more field and not as a card of its own.
*/
export function AddFieldButton({ icon: Icon, label, onClick, disabled, pressed, ariaExpanded }: {
icon: LucideIcon
label: string
onClick: () => void
disabled?: boolean
/** Drawn as switched on, for a button that opens a list under it. */
pressed?: boolean
ariaExpanded?: boolean
}) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
aria-expanded={ariaExpanded}
className={`${SELECT_FIELD_CLS} gap-[10px] text-start disabled:opacity-40 ${pressed ? '!border-transparent !bg-m-act text-m-actfg' : 'text-m-faint'}`}
>
<Icon size={14} strokeWidth={2} aria-hidden="true" className="flex-none" />
<span className="min-w-0 flex-1 truncate text-[0.84375rem] font-medium">{label}</span>
<Plus size={14} strokeWidth={2.2} aria-hidden="true" className="flex-none" />
</button>
)
}
export const FIELD_AREA_CLS =
'w-full box-border resize-none rounded-[18px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-[14px] py-[10px] font-geist text-[0.78125rem] leading-[1.5] text-m-ink outline-none placeholder:text-m-faint'
@@ -1,4 +1,4 @@
// FE-MOB-PLTAGS-001 to FE-MOB-PLTAGS-005: the phone's tag markup, which is the picker of the
// FE-MOB-PLTAGS-001 to FE-MOB-PLTAGS-007: the phone's tag markup, which is the picker of the
// place form (its state is usePlaceTags', tested on its own) and the chips of the place sheet.
import { describe, expect, it, vi } from 'vitest';
@@ -17,6 +17,9 @@ function field(overrides: Partial<PlaceTagsField> = {}): PlaceTagsField {
toggle: vi.fn(),
name: '',
setName: vi.fn(),
newColor: '#ec4899',
setNewColor: vi.fn(),
recolor: vi.fn(() => Promise.resolve()),
saving: false,
canAdd: false,
addNew: vi.fn(() => Promise.resolve()),
@@ -61,6 +64,29 @@ describe('PlTagPicker', () => {
});
});
describe('PlTagPicker colours', () => {
it("FE-MOB-PLTAGS-006: a chip's dot opens the palette in the sheet, and a swatch recolours that tag", () => {
const tags = field();
render(<PlTagPicker tags={tags} t={t} />);
const dot = screen.getAllByRole('button', { name: 'places.tagColor' })[1];
fireEvent.click(dot);
expect(dot).toHaveAttribute('aria-expanded', 'true');
fireEvent.click(screen.getByRole('button', { name: '#10b981' }));
expect(tags.recolor).toHaveBeenCalledWith(8, '#10b981');
expect(screen.queryByRole('button', { name: '#10b981' })).not.toBeInTheDocument();
});
it('FE-MOB-PLTAGS-007: the dot in front of the new tag picks its colour, and the add button takes it on', () => {
const tags = field({ name: 'Food', canAdd: true });
render(<PlTagPicker tags={tags} t={t} />);
fireEvent.click(screen.getByRole('button', { name: 'places.newTagColor' }));
fireEvent.click(screen.getByRole('button', { name: '#f97316' }));
expect(tags.setNewColor).toHaveBeenCalledWith('#f97316');
expect(tags.recolor).not.toHaveBeenCalled();
expect(screen.getByRole('button', { name: 'places.addTag' }).style.background).toContain('236, 72, 153');
});
});
describe('PlTagChips', () => {
it('FE-MOB-PLTAGS-004: shows the tags a place carries, each once and by name', () => {
const { container } = render(
+141 -44
View File
@@ -1,65 +1,162 @@
import { TRIP_TAG_NAME_MAX } from '@trek/shared';
import { Check, Tag as TagIcon } from 'lucide-react';
import { Check, Plus, Tag as TagIcon } from 'lucide-react';
import { useState } from 'react';
import { TagColorPopover } from '../../../../components/Planner/TagColorPopover';
import type { PlaceTagsField } from '../../../../components/Planner/usePlaceTags';
import type { Place } from '../../../../types';
import { tagChoices } from '../../../../utils/placeTags';
import MChip from '../../../components/MChip';
import { Eyebrow, FIELD_CLS } from './PlSheetChrome';
import { Eyebrow } from './PlSheetChrome';
type Translate = (key: string, params?: Record<string, string | number>) => string;
const LABEL = 'mb-[6px] mt-3 uppercase';
const PICKER = 'flex flex-wrap gap-[6px]';
const NEW_TAG = 'mt-2 flex items-center gap-2';
const CONFIRM =
'flex h-10 w-10 flex-none items-center justify-center rounded-[12px] bg-m-act text-m-actfg disabled:opacity-40';
const CHIPS = 'mt-[6px] flex flex-wrap gap-1';
const LABEL = 'mb-[5px] mt-3 uppercase';
/** The one field the tags live in: their chips, then where a new one is typed. */
const FIELD =
'flex min-h-[42px] w-full flex-wrap items-center gap-[5px] rounded-[21px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] p-[5px]';
/** One tag: its colour dot and its name, two buttons in one chip. */
const CHIP =
'inline-flex h-[30px] min-w-0 max-w-full items-center rounded-full border transition-[background-color,border-color] duration-150';
const CHIP_OFF = 'border-[color:var(--m-rowbr)] bg-[color:var(--m-card)]';
const DOT_BUTTON = 'grid h-[30px] w-[26px] flex-none place-items-center ps-[3px]';
const DOT = 'h-[12px] w-[12px] rounded-full ring-1 ring-inset ring-[color:var(--m-rowbr)]';
const NAME_BUTTON = 'inline-flex h-full min-w-0 items-center gap-[5px] text-[0.75rem] font-semibold';
/** The tick of a picked tag, in a round white badge. */
const TICK =
'me-[3px] grid h-[22px] w-[22px] flex-none place-items-center rounded-full bg-[color:var(--m-card)] shadow-sm';
/** Where a new tag is typed: the rest of the field's line, at least wide enough for a short name. */
const NEW_TAG = 'flex h-[30px] min-w-[9rem] flex-1 items-center gap-[6px]';
const NEW_INPUT =
'min-w-0 flex-1 bg-transparent font-[inherit] text-[0.75rem] font-semibold text-m-ink outline-none placeholder:font-medium placeholder:text-m-faint';
const ADD_BUTTON = 'grid h-[30px] w-[30px] flex-none place-items-center rounded-full';
/** The palette laid into the sheet under the field, in the sheet's own surface. */
const PALETTE =
'mt-2 flex w-full flex-col gap-2.5 rounded-[18px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] p-3';
const CHIPS = 'mt-[6px] flex flex-wrap gap-1';
const SHEET_CHIP =
'inline-flex max-w-full items-center gap-1 rounded-full border border-[color:var(--m-faint)] px-2 py-[2px] font-geist text-caption font-semibold text-m-muted';
const FALLBACK_COLOR = 'var(--m-faint)';
const tint = (color: string, percent: number) => `color-mix(in srgb, ${color} ${percent}%, var(--m-card))`;
/**
* The tags of the place form on the phone: its label, every tag on offer as a chip to
* switch on or off, and a field that adds a new one to the trip. The state is
* The tags of the place form on the phone, in one field like the sheet's others:
* every tag on offer is a chip in its own colour inside it (the name ticks it,
* the dot opens the palette that recolours it for the whole trip), and the rest
* of the field takes a new tag, in a colour picked by the dot in front of it. The
* palette opens into the sheet under the field rather than floating. The state is
* usePlaceTags', run by the sheet; this is its markup.
*/
export function PlTagPicker({ tags, t }: { tags: PlaceTagsField; t: Translate }) {
const [palette, setPalette] = useState<number | 'new' | null>(null);
const [preview, setPreview] = useState<{ id: number; color: string } | null>(null);
const closePalette = () => {
setPalette(null);
setPreview(null);
};
const toggle = (which: number | 'new') => (palette === which ? closePalette() : setPalette(which));
const open = typeof palette === 'number' ? tags.options.find((tag) => tag.id === palette) : undefined;
return (
<>
<Eyebrow className={LABEL}>{t('places.tags')}</Eyebrow>
<div role="group" aria-label={t('places.tags')} className={PICKER}>
{tags.options.map((tag) => (
<MChip key={tag.id} pressable active={tag.on} onClick={() => tags.toggle(tag.id)}>
<TagIcon
size={12}
strokeWidth={2.2}
className="flex-none"
style={{ color: tag.on ? undefined : tag.color }}
<div>
<div role="group" aria-label={t('places.tags')} className={FIELD}>
{tags.options.map((tag) => {
const color = (preview?.id === tag.id ? preview.color : tag.color) ?? FALLBACK_COLOR;
return (
<span
key={tag.id}
className={`${CHIP} ${tag.on ? '' : CHIP_OFF}`}
style={tag.on ? { background: tint(color, 22), borderColor: tint(color, 55) } : undefined}
>
<button
type="button"
aria-label={t('places.tagColor', { name: tag.name })}
aria-expanded={palette === tag.id}
onClick={() => toggle(tag.id)}
className={DOT_BUTTON}
>
<span aria-hidden="true" className={DOT} style={{ background: color }} />
</button>
<button
type="button"
aria-pressed={tag.on}
onClick={() => tags.toggle(tag.id)}
className={`${NAME_BUTTON} ${tag.on ? 'ps-[2px] text-m-ink' : 'pe-[11px] ps-[2px] text-m-muted'}`}
>
<span dir="auto" className="truncate">
{tag.name}
</span>
{tag.on && (
<span aria-hidden="true" className={TICK}>
<Check size={12} strokeWidth={3.2} style={{ color }} />
</span>
)}
</button>
</span>
);
})}
<span className={`${NEW_TAG} ${tags.options.length ? 'ps-[4px]' : 'ps-[8px]'}`}>
<button
type="button"
aria-label={t('places.newTagColor')}
aria-expanded={palette === 'new'}
onClick={() => toggle('new')}
className="grid h-[30px] w-[18px] flex-none place-items-center"
>
<span
aria-hidden="true"
className="h-[14px] w-[14px] rounded-full ring-1 ring-inset ring-[color:var(--m-rowbr)]"
style={{ background: tags.newColor }}
/>
</button>
<input
type="text"
value={tags.name}
onChange={(e) => tags.setName(e.target.value)}
onKeyDown={tags.handleNameKey}
maxLength={TRIP_TAG_NAME_MAX}
aria-label={t('places.newTag')}
placeholder={t('places.newTag')}
enterKeyHint="done"
className={NEW_INPUT}
/>
{tag.name}
</MChip>
))}
</div>
<div className={NEW_TAG}>
<input
type="text"
value={tags.name}
onChange={(e) => tags.setName(e.target.value)}
onKeyDown={tags.handleNameKey}
maxLength={TRIP_TAG_NAME_MAX}
aria-label={t('places.newTag')}
placeholder={t('places.newTag')}
className={FIELD_CLS}
/>
<button
type="button"
onClick={() => void tags.addNew()}
disabled={!tags.canAdd}
aria-label={t('places.addTag')}
className={CONFIRM}
>
<Check size={15} strokeWidth={2.4} />
</button>
<button
type="button"
onClick={() => void tags.addNew()}
disabled={!tags.canAdd}
aria-label={t('places.addTag')}
className={`${ADD_BUTTON} ${tags.canAdd ? '' : 'text-m-faint'}`}
style={tags.canAdd ? { background: tags.newColor, color: 'var(--m-card)' } : undefined}
>
<Plus size={15} strokeWidth={2.6} />
</button>
</span>
</div>
{open && (
<TagColorPopover
key={open.id}
label={t('places.tagColor', { name: open.name })}
value={open.color ?? null}
onPick={(next) => void tags.recolor(open.id, next)}
onPreview={(next) => setPreview({ id: open.id, color: next })}
onClose={closePalette}
className={PALETTE}
t={t}
/>
)}
{palette === 'new' && (
<TagColorPopover
label={t('places.newTagColor')}
value={tags.newColor}
onPick={tags.setNewColor}
onPreview={tags.setNewColor}
onClose={closePalette}
className={PALETTE}
t={t}
/>
)}
</div>
</>
);
@@ -72,7 +169,7 @@ export function PlTagChips({ tags }: { tags: Place['tags'] }) {
return (
<div className={CHIPS}>
{shown.map((tag) => (
<span key={tag.id} className={CHIP}>
<span key={tag.id} className={SHEET_CHIP}>
<TagIcon size={10} strokeWidth={2} className="flex-none" style={{ color: tag.color }} />
<span dir="auto" className="truncate">
{tag.name}
+10 -1
View File
@@ -1,4 +1,4 @@
import type { Tag, TripTagCreateRequest, TripTagListResponse } from '@trek/shared';
import type { Tag, TripTagCreateRequest, TripTagListResponse, TripTagUpdateRequest } from '@trek/shared';
import { tripTagsApi } from '../api/tripTags';
import { cachedTripTags, cacheTripTags } from '../db/cacheTripTags';
@@ -34,4 +34,13 @@ export const tripTagRepo = {
await cacheTripTags(id, withTripTag(await cachedTripTags(id), tag));
return tag;
},
/** Renames or recolours a tag of the trip. Online only, like adding one: the tag is the trip's, not a place's own write. */
async update(tripId: number | string, tagId: number, body: TripTagUpdateRequest): Promise<Tag> {
requireOnline();
const id = Number(tripId);
const { tag } = await tripTagsApi.update(id, tagId, body);
await cacheTripTags(id, withTripTag(await cachedTripTags(id), tag));
return tag;
},
};
+9 -1
View File
@@ -1,4 +1,4 @@
import type { Tag, TripTagCreateRequest } from '@trek/shared';
import type { Tag, TripTagCreateRequest, TripTagUpdateRequest } from '@trek/shared';
import type { StoreApi } from 'zustand';
import { tripTagRepo } from '../../repo/tripTagRepo';
@@ -16,6 +16,8 @@ export interface TripTagsSlice {
loadTripTags: (tripId: number | string) => Promise<void>;
/** Adds a tag to the trip, or hands back the one it already has under that name. Needs a connection. */
addTripTag: (tripId: number | string, data: TripTagCreateRequest) => Promise<Tag>;
/** Renames or recolours one of the trip's tags, and takes the change into the places carrying it. Needs a connection. */
updateTripTag: (tripId: number | string, tagId: number, data: TripTagUpdateRequest) => Promise<Tag>;
}
/**
@@ -61,4 +63,10 @@ export const createTripTagsSlice = (set: SetState, get: GetState): TripTagsSlice
set((state) => ({ tripTags: withTripTag(state.tripTags, tag) }));
return tag;
},
updateTripTag: async (tripId, tagId, data) => {
const tag = await tripTagRepo.update(tripId, tagId, data);
set((state) => withTripTags(state, withTripTag(state.tripTags, tag)));
return tag;
},
});
+32
View File
@@ -0,0 +1,32 @@
// FE-UTIL-COLORSPACE-001 to FE-UTIL-COLORSPACE-003
import { describe, expect, it } from 'vitest';
import { hexToHsv, hsvToHex, hueHex, normalizeHex } from './colorSpace';
describe('colorSpace', () => {
it('FE-UTIL-COLORSPACE-001: reads a typed colour in the forms people type it, and nothing else', () => {
expect(normalizeHex('#ABCDEF')).toBe('#abcdef');
expect(normalizeHex('abcdef')).toBe('#abcdef');
expect(normalizeHex(' #f0a ')).toBe('#ff00aa');
expect(normalizeHex('#abcd')).toBeNull();
expect(normalizeHex('red')).toBeNull();
expect(normalizeHex('')).toBeNull();
});
it('FE-UTIL-COLORSPACE-002: hue, saturation and value of the primaries, grey and black', () => {
expect(hexToHsv('#ff0000')).toEqual({ h: 0, s: 1, v: 1 });
expect(hexToHsv('#00ff00')).toEqual({ h: 120, s: 1, v: 1 });
expect(hexToHsv('#0000ff')).toEqual({ h: 240, s: 1, v: 1 });
expect(hexToHsv('#808080')).toEqual({ h: 0, s: 0, v: 128 / 255 });
expect(hexToHsv('#000000')).toEqual({ h: 0, s: 0, v: 0 });
});
it('FE-UTIL-COLORSPACE-003: a colour survives the way there and back, and the hue alone is the pure one', () => {
for (const hex of ['#6366f1', '#ec4899', '#f97316', '#10b981', '#64748b', '#ffffff', '#000000']) {
expect(hsvToHex(hexToHsv(hex))).toBe(hex);
}
expect(hueHex(0)).toBe('#ff0000');
expect(hueHex(120)).toBe('#00ff00');
expect(hueHex(240)).toBe('#0000ff');
});
});
+52
View File
@@ -0,0 +1,52 @@
/**
* Hex colours to hue, saturation and value and back, for the colour field of
* the tag palette: the field picks saturation and value, the slider the hue.
*/
export interface Hsv {
/** 0 to 360. */
h: number;
/** 0 to 1. */
s: number;
/** 0 to 1. */
v: number;
}
const HEX = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i;
/** A typed colour as lowercase #rrggbb, or null when it is not one. Accepts the short #rgb form and a missing #. */
export function normalizeHex(raw: string): string | null {
const m = HEX.exec(raw.trim());
if (!m) return null;
const digits = m[1].length === 3 ? [...m[1]].map((c) => c + c).join('') : m[1];
return `#${digits.toLowerCase()}`;
}
export function hexToHsv(hex: string): Hsv {
const norm = normalizeHex(hex) ?? '#000000';
const [r, g, b] = [1, 3, 5].map((i) => parseInt(norm.slice(i, i + 2), 16) / 255);
const max = Math.max(r, g, b);
const d = max - Math.min(r, g, b);
let h = 0;
if (d) {
if (max === r) h = ((g - b) / d) % 6;
else if (max === g) h = (b - r) / d + 2;
else h = (r - g) / d + 4;
}
return { h: (h * 60 + 360) % 360, s: max ? d / max : 0, v: max };
}
export function hsvToHex({ h, s, v }: Hsv): string {
const f = (n: number) => {
const k = (n + h / 60) % 6;
const c = v - v * s * Math.max(0, Math.min(k, 4 - k, 1));
return Math.round(c * 255)
.toString(16)
.padStart(2, '0');
};
return `#${f(5)}${f(3)}${f(1)}`;
}
/** The pure hue at full saturation and value, the colour the field fades from. */
export function hueHex(h: number): string {
return hsvToHex({ h, s: 1, v: 1 });
}
+10 -2
View File
@@ -1,7 +1,15 @@
import { describe, expect, it } from 'vitest';
import { buildPlace, buildTag } from '../../tests/helpers/factories';
import { nextTagColor, placeTagIds, tagChanges, tagChoices, withTagChanges, withTripTag } from './placeTags';
import {
TAG_COLORS,
nextTagColor,
placeTagIds,
tagChanges,
tagChoices,
withTagChanges,
withTripTag,
} from './placeTags';
describe('placeTags', () => {
it('FE-UTIL-PLTAGS-001: offers each tag once and by name, as the first list that has it says', () => {
@@ -46,7 +54,7 @@ describe('placeTags', () => {
expect(second).toMatch(/^#[0-9a-f]{6}$/);
expect(second).not.toBe(first);
// Past the last colour it starts over.
expect(nextTagColor(Array.from({ length: 8 }, () => buildTag()))).toBe(first);
expect(nextTagColor(Array.from({ length: TAG_COLORS.length }, () => buildTag()))).toBe(first);
});
it('FE-UTIL-PLTAGS-005: adds a tag to the list by name, and replaces the one of the same id', () => {
+13 -2
View File
@@ -33,11 +33,22 @@ export function placeTagIds(carried: readonly PlaceTag[] | undefined): number[]
}
// What a new tag is coloured with, one after the other, so the tags of a trip tell apart at a glance.
const NEW_TAG_COLORS = ['#6366f1', '#ec4899', '#f97316', '#10b981', '#06b6d4', '#8b5cf6', '#ef4444', '#f59e0b'];
export const TAG_COLORS = [
'#6366f1',
'#ec4899',
'#f97316',
'#10b981',
'#06b6d4',
'#8b5cf6',
'#ef4444',
'#f59e0b',
'#84cc16',
'#64748b',
];
/** The colour the next new tag of a trip gets. */
export function nextTagColor(tripTags: readonly unknown[]): string {
return NEW_TAG_COLORS[tripTags.length % NEW_TAG_COLORS.length];
return TAG_COLORS[tripTags.length % TAG_COLORS.length];
}
/** The trip's tags with one more, or with the one of that id as it is now, by name as the server lists them. */