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
@@ -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 };
}