feat(studio): filter photos by entry, upload from Studio, and switch stops off

The content browser gets a filter over the journey's pictures: all of them,
the ones no entry holds, or one entry at a time, with the day and the place
under each name. An entry card in the Entries tab reaches its own pictures
the same way. Pictures can now come in without leaving Studio, into the
entry the filter names or into the gallery, from the panel or dropped
straight onto the page, and a photo element can fill its page or the whole
spread in one press.

Stops can be taken out of the arithmetic. A journal entry carries a
stats_excluded flag; an entry that has it is off the route, out of the
distance, out of the countries and not a step, while staying in the
journal. Studio lists every stop in the travel panel with a switch, the
entry editor carries the same switch on desktop and phone, and the entry
card says when a day is off the route.
This commit is contained in:
Maurice
2026-09-03 09:46:57 +02:00
committed by Maurice
parent 23401fcdb9
commit 6cbefd23e8
62 changed files with 2933 additions and 116 deletions
+39 -4
View File
@@ -65,6 +65,8 @@ export function StudioCanvas({
dropLabel,
cursors,
onCursor,
onDropFiles,
fileDropLabel,
}: {
spread: BookSpread | null
spreadIndex: number
@@ -73,6 +75,14 @@ export function StudioCanvas({
pxPerMm: number
bookView: boolean
dropLabel: string
/**
* Files from outside the browser, let go over the sheet. Absent for a
* viewer, and then a file drag is left to the browser, which opens it.
* `targetFrameId` is the photo frame under the pointer, when there is one.
*/
onDropFiles?: (files: File[], at: { x: number; y: number }, targetFrameId: string | null) => void
/** What the veil says while a file drag is over the sheet. */
fileDropLabel?: string
/** The other editors' pointers, on this spread and elsewhere. */
cursors?: PeerCursor[]
/** Where this one is, in the spread's millimetres. Null once it leaves. */
@@ -87,6 +97,8 @@ export function StudioCanvas({
const commit = useStudioStore(s => s.commit)
const addElement = useStudioStore(s => s.addElement)
const [dropTarget, setDropTarget] = useState<string | null>(null)
/** A file drag from outside the browser is over the sheet. */
const [fileOver, setFileOver] = useState(false)
const [editing, setEditing] = useState<string | null>(null)
/** Where on the spread, in millimetres, a drop landed. */
@@ -166,22 +178,34 @@ export function StudioCanvas({
onPointerUp={finish}
onPointerCancel={finish}
onDragOver={e => {
if (!e.dataTransfer.types.includes('application/x-trek-photo')) return
const fromPanel = e.dataTransfer.types.includes('application/x-trek-photo')
// A file drag is only claimed when somebody is there to take it; for a
// viewer the browser keeps its default and opens the picture itself.
const fromDisk = !!onDropFiles && e.dataTransfer.types.includes('Files')
if (!fromPanel && !fromDisk) return
e.preventDefault()
e.dataTransfer.dropEffect = 'copy'
const p = pointInMm(e)
setDropTarget(frameUnder(p.x, p.y)?.id ?? null)
setFileOver(fromDisk && !fromPanel)
}}
onDragLeave={() => setDropTarget(null)}
onDragLeave={() => { setDropTarget(null); setFileOver(false) }}
onDrop={e => {
const raw = e.dataTransfer.getData('application/x-trek-photo')
if (!raw) return
const files = Array.from(e.dataTransfer.files ?? [])
if (!raw && !(files.length && onDropFiles)) return
e.preventDefault()
setDropTarget(null)
setFileOver(false)
const p = pointInMm(e)
if (!raw) {
onDropFiles!(files, p, frameUnder(p.x, p.y)?.id ?? null)
return
}
const photoId = Number(raw)
if (!Number.isFinite(photoId)) return
const p = pointInMm(e)
const target = frameUnder(p.x, p.y)
if (target) {
// Dropped onto a frame: fill it. That is the whole point of an empty
@@ -211,6 +235,17 @@ export function StudioCanvas({
select([id])
}}
>
{/*
Over the stage rather than inside the sheet, which is scaled: at 40%
a label drawn on the page would be unreadable. It says what letting go
will do, because a page is not an obvious drop target for a file the
way an upload box is.
*/}
{fileOver && fileDropLabel && (
<div className="st-file-veil" aria-hidden>
<span>{fileDropLabel}</span>
</div>
)}
<div
className="st-sheet"
style={{
@@ -191,6 +191,34 @@ export function StudioInspector({
const live = (patch: Partial<BookElement>) => update(spreadIndex, el.id, patch)
/**
* Stretch the picture over the page it is on, or over both pages, bleed
* included.
*
* One commit rather than `set` followed by `raise`: the frame, the rotation
* put back to zero (a turned picture leaves bare corners), the cover crop and
* the move to the back are one press, and one press comes back with one
* undo. Which page is the one under the frame's centre; a cover has only
* the one.
*/
const fill = (scope: 'page' | 'spread') => commit(d => ({
...d,
spreads: d.spreads.map((sp, i) => {
if (i !== spreadIndex) return sp
const bleed = page.bleed
const onRight = sp.role === 'inner' && scope === 'page'
&& el.frame.x + el.frame.w / 2 >= page.pageWidth
const frame = {
x: onRight ? page.pageWidth - bleed : -bleed,
y: -bleed,
w: (scope === 'spread' ? 2 : 1) * page.pageWidth + 2 * bleed,
h: page.pageHeight + 2 * bleed,
}
const filled = { ...el, frame, rotation: 0, fit: 'cover' } as BookElement
return { ...sp, elements: [filled, ...sp.elements.filter(e => e.id !== el.id)] }
}),
}))
return (
<aside className="st-panel st-inspector">
{/*
@@ -696,6 +724,28 @@ export function StudioInspector({
<ChevronsDown size={14} />
</button>
</div>
{/*
The picture as the page.
A full-bleed photograph is the commonest layout in any photo book
and the hardest to make by hand: the frame has to reach exactly to
the bleed on every side, and a millimetre short leaves a white
hairline on the trimmed page. So it is one press. It goes to the
back as well, since a page-sized picture in front of everything is
a page with nothing else on it.
*/}
{one && el.kind === 'photo' && (
<div className="st-row" style={{ marginTop: 6 }}>
<button type="button" className="st-chip" onClick={() => fill('page')} title={t('journey.studio.fillHint')}>
{t('journey.studio.fillPage')}
</button>
{spread.role === 'inner' && (
<button type="button" className="st-chip" onClick={() => fill('spread')} title={t('journey.studio.fillHint')}>
{t('journey.studio.fillSpread')}
</button>
)}
</div>
)}
</Section>
</div>
</aside>
@@ -89,6 +89,9 @@ export default function StudioShell() {
path={s.path}
t={s.t}
locale={s.locale}
canEdit={s.canEdit}
onUpload={s.uploadPhotos}
onToggleStop={s.setStopExcluded}
/>
<Workbench s={s} bookView={bookView} />
<StudioInspector
@@ -431,7 +434,20 @@ function Workbench({ s, bookView }: { s: Studio; bookView: boolean }) {
dropLabel={s.t('journey.studio.dropPhotoHere')}
cursors={s.cursors}
onCursor={(x, y) => s.moveCursor(s.activeSpread, x, y)}
onDropFiles={s.canEdit ? s.dropFiles : undefined}
fileDropLabel={s.t('journey.studio.dropFilesHere')}
/>
{/*
Pictures dropped on the sheet are on their way. The page keeps
rendering underneath; the veil only says that something is happening
where the pointer let go, so the second or two before the frame
appears does not read as the drop having been ignored.
*/}
{s.canvasUpload && (
<div className="st-upload-veil" role="status" aria-live="polite">
{s.t('journey.studio.uploading', { done: s.canvasUpload.done, total: s.canvasUpload.total })}
</div>
)}
</div>
<div className="st-zoom">
+368 -32
View File
@@ -1,9 +1,13 @@
import { useMemo, useRef, useState } from 'react'
import { ChevronDown, ChevronUp, Compass, Copy, FileDown, Files, ImageIcon, LayoutTemplate, Plus, Search, Shapes, Trash2, X } from 'lucide-react'
import { useEffect, useMemo, useRef, useState } from 'react'
import {
Camera, Check, ChevronDown, ChevronUp, Compass, Copy, FileDown, Files, ImageIcon, LayoutTemplate,
Plus, Search, Shapes, Trash2, Upload, X,
} from 'lucide-react'
import type { BookElement, BookPageSetup, JourneyStats } from '@trek/shared'
import { useElementSize } from '../../hooks/useElementSize'
import { useStudioStore } from '../../store/studioStore'
import { formatDate } from '../../utils/formatters'
import { useToast } from '../shared/Toast'
import { SpreadFold, SpreadView } from './SpreadView'
import { photoSrc } from './bookRender'
import { formatBookCoords, formatBookDate, type CoordFormat } from './entryText'
@@ -14,6 +18,7 @@ import { PanelHead as Head } from './StudioPanelHead'
import { StudioElementsPanel } from './StudioElementsPanel'
import { StudioTravelPanel } from './StudioTravelPanel'
import { MAX_SPREAD_FILE_BYTES, importSpread } from './spreadFile'
import type { StudioUploader } from './studioUpload'
/**
* The left side of Studio: a narrow rail of sections and one wide panel showing
@@ -42,12 +47,18 @@ export interface JourneySource {
weather: string | null
pros: string[]
cons: string[]
/** The pictures attached to this entry, as trek_photos ids. */
photoIds: number[]
}[]
photos: { photoId: number; caption?: string | null }[]
/** `entryIds` is empty for a picture that sits only in the gallery. */
photos: { photoId: number; caption?: string | null; entryIds: number[] }[]
/** photoId to the words of the entry it belongs to, lower-cased. */
photoEntries: Record<number, string>
}
/** The translator, with the parameters some of the strings here take. */
export type StudioT = (k: string, params?: Record<string, string | number>) => string
const uid = (p: string) => `${p}-${Math.random().toString(36).slice(2, 9)}`
/**
@@ -72,6 +83,7 @@ const THUMB_CHROME = (2 + 3) * 2
export function StudioSidebar({
page, pxPerMm, bookView, source, stats, path, t, locale,
canEdit, onUpload, onToggleStop,
}: {
page: BookPageSetup
pxPerMm: number
@@ -81,8 +93,14 @@ export function StudioSidebar({
stats: JourneyStats | null
/** The roads the trip took, for a map that draws them. Empty when it has none. */
path: [number, number][][]
t: (k: string) => string
t: StudioT
locale: string
/** False for a viewer: no upload, no switching stops, nothing that writes. */
canEdit: boolean
/** Pictures into the gallery, or into one entry. See studioUpload.ts. */
onUpload: StudioUploader
/** Switch a stop on or off in the figures. Resolves false when it did not land. */
onToggleStop: (entryId: number, excluded: boolean) => Promise<boolean>
}) {
const [section, setSection] = useState<Section>('pages')
@@ -113,9 +131,21 @@ export function StudioSidebar({
<aside className="st-panel st-side">
{section === 'pages' && <PagesPanel page={page} pxPerMm={pxPerMm} bookView={bookView} t={t} />}
{section === 'content' && <ContentPanel source={source} page={page} t={t} locale={locale} />}
{section === 'content' && (
<ContentPanel source={source} page={page} t={t} locale={locale} canEdit={canEdit} onUpload={onUpload} />
)}
{section === 'elements' && <StudioElementsPanel page={page} t={t} />}
{section === 'travel' && <StudioTravelPanel page={page} stats={stats} path={path} t={t} locale={locale} />}
{section === 'travel' && (
<StudioTravelPanel
page={page}
stats={stats}
path={path}
t={t}
locale={locale}
canEdit={canEdit}
onToggleStop={onToggleStop}
/>
)}
{section === 'templates' && <TemplatesPanel page={page} pxPerMm={pxPerMm} t={t} onOpenContent={() => setSection('content')} />}
</aside>
</>
@@ -290,18 +320,46 @@ function PagesPanel({
)
}
/**
* Which of the journey's pictures the browser shows.
*
* `recent` holds ids rather than a flag on the photo: what just arrived is a
* fact about this sitting, not about the picture, and the journey store has no
* reason to remember it.
*/
type PhotoFilter =
| { kind: 'all' }
| { kind: 'entry'; id: number }
| { kind: 'loose' }
| { kind: 'recent'; photoIds: number[] }
/**
* The journey's own material.
*
* This is what separates a book maker from a drawing program: the pictures and
* the words are already written, and the job is putting them on pages. Clicking
* an item drops it on the current spread, centred, at a sensible size.
*
* Pictures can also come in here. A book is where you notice the one that
* never made it into the journal, and going back to the journey to add it, then
* finding the page again, was the one round trip Studio still asked for. What
* comes in goes through the journey store like any other upload, so the journal
* sees it the moment the panel does.
*/
function ContentPanel({
source, page, t, locale,
}: { source: JourneySource; page: BookPageSetup; t: (k: string) => string; locale: string }) {
source, page, t, locale, canEdit, onUpload,
}: {
source: JourneySource
page: BookPageSetup
t: StudioT
locale: string
canEdit: boolean
onUpload: StudioUploader
}) {
const [tab, setTab] = useState<'photos' | 'text'>('photos')
const [query, setQuery] = useState('')
const [filter, setFilter] = useState<PhotoFilter>({ kind: 'all' })
const toast = useToast()
/*
* Filtering, not a search index: a journey holds tens or hundreds of items, and
@@ -316,16 +374,144 @@ function ContentPanel({
[e.title, e.story, e.location, ...e.pros, ...e.cons]
.some(v => v && v.toLowerCase().includes(q)))
: source.entries
/*
* The filter narrows first and the words second, so an entry filter with a
* search typed into it means "these pictures, with these words". Which entry
* a picture belongs to is read off the journal's own junction rather than
* off its words, which is what lets "not in an entry" mean exactly that.
*/
const byFilter = (() => {
switch (filter.kind) {
case 'entry': return source.photos.filter(p => p.entryIds.includes(filter.id))
case 'loose': return source.photos.filter(p => !p.entryIds.length)
case 'recent': {
// In the order they were sent, which is the order they were chosen in,
// not wherever the gallery sorted them.
const byId = new Map(source.photos.map(p => [p.photoId, p] as const))
return filter.photoIds.flatMap(id => { const p = byId.get(id); return p ? [p] : [] })
}
default: return source.photos
}
})()
const photos = q
? source.photos.filter(p =>
? byFilter.filter(p =>
(p.caption && p.caption.toLowerCase().includes(q))
|| (source.photoEntries[p.photoId] || '').includes(q))
: source.photos
: byFilter
const looseCount = source.photos.filter(p => !p.entryIds.length).length
const withPhotos = source.entries.filter(e => e.photoIds.length > 0)
const nameOf = (e: { title: string | null; location: string | null } | undefined) =>
e?.title || e?.location || t('journey.studio.untitled')
const filterLabel = filter.kind === 'loose' ? t('journey.studio.filterLoose')
: filter.kind === 'recent' ? t('journey.studio.filterRecent')
: filter.kind === 'entry' ? nameOf(source.entries.find(e => e.id === filter.id))
: t('journey.studio.filterAll')
/*
* Why the grid is empty, which is four different answers. "No photos" on a
* journey with three hundred of them, because the filter is on a day with
* none, reads as the pictures having gone.
*/
const emptyKey = !source.photos.length ? 'journey.studio.noPhotos'
: byFilter.length ? 'journey.studio.noMatches'
: filter.kind === 'entry' ? 'journey.studio.noEntryPhotos'
: filter.kind === 'loose' ? 'journey.studio.noLoosePhotos'
: 'journey.studio.noMatches'
const [menuOpen, setMenuOpen] = useState(false)
const menuBox = useRef<HTMLDivElement>(null)
useEffect(() => {
if (!menuOpen) return
const onDown = (e: PointerEvent) => {
if (!menuBox.current?.contains(e.target as Node)) setMenuOpen(false)
}
const onKey = (e: KeyboardEvent) => {
// Swallowed, as the format picker does it: the shell's Escape closes Studio.
if (e.key === 'Escape') { e.stopPropagation(); setMenuOpen(false) }
}
document.addEventListener('pointerdown', onDown)
document.addEventListener('keydown', onKey, true)
return () => {
document.removeEventListener('pointerdown', onDown)
document.removeEventListener('keydown', onKey, true)
}
}, [menuOpen])
const pick = (f: PhotoFilter) => { setFilter(f); setMenuOpen(false) }
const addElement = useStudioStore(s => s.addElement)
const active = useStudioStore(s => s.activeSpread)
const doc = useStudioStore(s => s.doc)
const spread = doc?.spreads[active]
/*
* The page on the sheet belongs to a day, so its pictures are one press
* away. Offered only while the filter is not already there: a chip for the
* state you are in is a chip that does nothing.
*/
const pageEntry = spread?.entryId != null ? withPhotos.find(e => e.id === spread.entryId) : undefined
const offerThisPage = pageEntry && !(filter.kind === 'entry' && filter.id === pageEntry.id)
const fileInput = useRef<HTMLInputElement>(null)
const [upload, setUpload] = useState<{ done: number; total: number } | null>(null)
/* A ref as well as the state: two drops in one second would both read the
state before either had set it. */
const sending = useRef(false)
const [dropOver, setDropOver] = useState(false)
/**
* Into the entry the browser is filtered to, otherwise into the gallery. The
* filter is the one thing on screen that names an entry, so it is also the
* one thing that can say where a picture belongs; the line under it says so
* before the press. Afterwards the new pictures get a filter of their own,
* because the gallery sorts them to its end, and twelve pictures that arrive
* out of sight read as twelve that did not arrive.
*/
const send = async (files: File[]) => {
if (sending.current || !files.length) return
sending.current = true
setUpload({ done: 0, total: files.length })
try {
const entryId = filter.kind === 'entry' ? filter.id : null
const sent = await onUpload(files, entryId, p => setUpload({ done: p.done, total: p.total }))
if (sent.photoIds.length) {
setFilter({ kind: 'recent', photoIds: sent.photoIds })
setQuery('')
toast.success(t('journey.photosUploaded', { count: sent.photoIds.length }))
}
} finally {
sending.current = false
setUpload(null)
}
}
/*
* The whole scrolling area takes a drop, not just the dashed cell: a drag
* from the desktop arrives with the pointer wherever it arrives, and a target
* seventy pixels square is one you miss. Only a file drag is claimed; the
* panel's own photo drags carry another type and go to the sheet.
*/
const dropZone = canEdit && tab === 'photos' ? {
onDragOver: (e: React.DragEvent<HTMLDivElement>) => {
if (!e.dataTransfer.types.includes('Files')) return
e.preventDefault()
e.dataTransfer.dropEffect = 'copy'
setDropOver(true)
},
onDragLeave: (e: React.DragEvent<HTMLDivElement>) => {
// Moving onto a child of the box is not leaving the box.
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setDropOver(false)
},
onDrop: (e: React.DragEvent<HTMLDivElement>) => {
const files = Array.from(e.dataTransfer.files ?? [])
if (!files.length) return
e.preventDefault()
setDropOver(false)
void send(files)
},
} : {}
const centre = (w: number, h: number) => {
const W = spread && spread.role !== 'inner' ? page.pageWidth : page.pageWidth * 2
return { x: (W - w) / 2, y: (page.pageHeight - h) / 2, w, h }
@@ -444,33 +630,142 @@ function ContentPanel({
</button>
</div>
<div className="st-panel-scroll">
{tab === 'photos' ? (
<div className="st-photo-grid">
{photos.map(p => (
{/*
Which entry, as a row of its own under the tabs rather than a control
inside the search box: the search answers "which words" and this
answers "which day", and the two combine. The chip opens the same
popover the bar uses for formats, hung from its left edge because the
panel has no room to the right of it.
*/}
{tab === 'photos' && (
<div className="st-filter-row">
<div className="st-picker" ref={menuBox}>
<span className={`st-chip st-filter-chip ${filter.kind !== 'all' ? 'is-on' : ''}`}>
<button type="button"
key={p.photoId}
className="st-photo-cell"
onClick={() => dropPhoto(p.photoId)}
title={t('journey.studio.addToPage')}
draggable
onDragStart={e => {
// HTML5 drag is the right tool for exactly this shape of
// interaction — one item, from a list, onto a target — and it
// gives us the thumbnail as the drag image for free. The
// canvas uses pointer events instead, because free transform
// needs a live position that a drop event cannot provide.
e.dataTransfer.setData('application/x-trek-photo', String(p.photoId))
e.dataTransfer.effectAllowed = 'copy'
}}
onClick={() => setMenuOpen(o => !o)}
aria-haspopup="menu"
aria-expanded={menuOpen}
title={t('journey.studio.filterPhotos')}
>
<img src={photoSrc(p.photoId, false)} alt="" loading="lazy" draggable={false} />
<span className="st-filter-name">{filterLabel}</span>
<em>{byFilter.length}</em>
<ChevronDown size={12} style={{ opacity: .5 }} />
</button>
))}
{!photos.length && (
<p className="st-hint">{t(q ? 'journey.studio.noMatches' : 'journey.studio.noPhotos')}</p>
{filter.kind !== 'all' && (
<button type="button" onClick={() => setFilter({ kind: 'all' })} aria-label={t('common.clear')}>
<X size={12} />
</button>
)}
</span>
{menuOpen && (
<div className="st-menu" role="menu">
<FilterItem
on={filter.kind === 'all'}
label={t('journey.studio.filterAll')}
count={source.photos.length}
onPick={() => pick({ kind: 'all' })}
/>
<FilterItem
on={filter.kind === 'loose'}
label={t('journey.studio.filterLoose')}
count={looseCount}
onPick={() => pick({ kind: 'loose' })}
/>
{withPhotos.length > 0 && <div className="st-menu-sep" />}
{withPhotos.map(e => (
<FilterItem
key={e.id}
on={filter.kind === 'entry' && filter.id === e.id}
label={nameOf(e)}
// The day, and the place when the title took the top line.
dim={[e.date ? formatDate(e.date, locale) ?? e.date : null, e.title ? e.location : null]
.filter(Boolean).join(', ')}
count={e.photoIds.length}
onPick={() => pick({ kind: 'entry', id: e.id })}
/>
))}
</div>
)}
</div>
{offerThisPage && (
<button type="button" className="st-chip" onClick={() => setFilter({ kind: 'entry', id: pageEntry.id })}>
{t('journey.studio.filterThisPage')}
</button>
)}
</div>
)}
<div className={`st-panel-scroll ${dropOver ? 'is-drop-over' : ''}`} {...dropZone}>
{tab === 'photos' ? (
<>
{canEdit && (
<p className="st-hint st-upload-where">
{t(filter.kind === 'entry' ? 'journey.studio.uploadToEntry' : 'journey.studio.uploadToGallery')}
</p>
)}
<div className="st-photo-grid">
{/*
The first cell rather than a button above the grid: it is the
size and shape of what it produces, and it stays where the eye
already is. Disabled, not hidden, while a batch is on its way,
so the count has somewhere to be read.
*/}
{canEdit && (
<button type="button"
className="st-photo-cell is-upload"
onClick={() => fileInput.current?.click()}
disabled={!!upload}
title={t('journey.studio.uploadHint')}
>
<Upload size={18} strokeWidth={1.6} />
<span>
{upload
? t('journey.studio.uploading', { done: upload.done, total: upload.total })
: t('journey.studio.uploadPhotos')}
</span>
</button>
)}
{photos.map(p => (
<button type="button"
key={p.photoId}
className="st-photo-cell"
onClick={() => dropPhoto(p.photoId)}
title={t('journey.studio.addToPage')}
draggable
onDragStart={e => {
// HTML5 drag is the right tool for exactly this shape of
// interaction (one item, from a list, onto a target) and it
// gives us the thumbnail as the drag image for free. The
// canvas uses pointer events instead, because free transform
// needs a live position that a drop event cannot provide.
e.dataTransfer.setData('application/x-trek-photo', String(p.photoId))
e.dataTransfer.effectAllowed = 'copy'
}}
>
<img src={photoSrc(p.photoId, false)} alt="" loading="lazy" draggable={false} />
</button>
))}
{!photos.length && <p className="st-hint">{t(emptyKey)}</p>}
</div>
{canEdit && (
<input
ref={fileInput}
type="file"
multiple
accept="image/*,.heic,.heif"
hidden
onChange={e => {
const files = Array.from(e.target.files ?? [])
// Cleared straight away, as the spread import does, so the
// same pictures can be chosen twice in a row.
e.target.value = ''
void send(files)
}}
/>
)}
</>
) : (
<div className="st-entries">
{entries.map(e => (
@@ -556,6 +851,22 @@ function ContentPanel({
<em>{e.pros.length + e.cons.length}</em>
</button>
)}
{/*
Not a drop like the others: this one takes you to the
entry's pictures. The words of a day and its pictures were
two tabs apart with nothing joining them, and the day is
how anyone thinks of the pictures.
*/}
{e.photoIds.length > 0 && (
<button type="button"
className="st-chip"
onClick={() => { setFilter({ kind: 'entry', id: e.id }); setTab('photos') }}
>
<Camera size={12} />
{t('journey.studio.entryPhotos')}
<em>{e.photoIds.length}</em>
</button>
)}
</div>
</div>
))}
@@ -567,6 +878,31 @@ function ContentPanel({
)
}
/** One line of the photo filter: a name, a count, and a tick on the one in force. */
function FilterItem({ on, label, dim, count, onPick }: {
on: boolean
label: string
dim?: string
count: number
onPick: () => void
}) {
return (
<button type="button"
role="menuitemradio"
aria-checked={on}
className={`st-menu-item ${on ? 'is-active' : ''}`}
onClick={onPick}
>
<span className="st-menu-text">
<span className="st-menu-name">{label}</span>
{dim && <span className="st-menu-dim">{dim}</span>}
</span>
<span className="st-menu-dim st-filter-count">{count}</span>
{on && <Check size={14} />}
</button>
)
}
/**
* Layouts for the current spread.
*
@@ -1,7 +1,8 @@
import { useEffect, useRef } from 'react'
import { useEffect, useRef, useState } from 'react'
import type { BookElement, BookMetric, BookPageSetup, JourneyStats } from '@trek/shared'
import { BOOK_METRICS } from '@trek/shared'
import { useStudioStore } from '../../store/studioStore'
import { formatDate } from '../../utils/formatters'
import { PanelHead } from './StudioPanelHead'
import { TravelPreview } from './TravelPreview'
import { formatBookCoords } from './entryText'
@@ -38,6 +39,21 @@ import { fetchRoads } from './roadRoute'
const uid = (p: string) => `${p}-${Math.random().toString(36).slice(2, 9)}`
/**
* One row of the stops list: a point of the route or a stop switched off.
*
* `entryId` is null for a stop the server took straight from a trip's places,
* which is what a journey has before anyone wrote an entry. Such a stop has no
* switch, because there is no entry to put it on.
*/
type StopRow = {
entryId: number | null
label: string
date: string | null
country: string | null
excluded: boolean
}
/*
* How many cards share a row.
*
@@ -80,7 +96,7 @@ function Card({ label, onClick, children, recommended = false, title }: {
}
export function StudioTravelPanel({
page, stats, path, t, locale,
page, stats, path, t, locale, canEdit, onToggleStop,
}: {
page: BookPageSetup
stats: JourneyStats | null
@@ -88,6 +104,10 @@ export function StudioTravelPanel({
path: [number, number][][]
t: (k: string) => string
locale: string
/** False for a viewer: the stops are still listed, none of them can be switched. */
canEdit: boolean
/** Switch one stop on or off in the figures. Resolves false when it did not land. */
onToggleStop: (entryId: number, excluded: boolean) => Promise<boolean>
}) {
const addElement = useStudioStore(s => s.addElement)
const updateElement = useStudioStore(s => s.updateElement)
@@ -109,6 +129,17 @@ export function StudioTravelPanel({
roadJobs.current.clear()
}, [])
/*
* The stops whose switch is on its way to the server.
*
* No optimistic flip: which stop is furthest and which countries remain is
* the server's sum, so the row reads its state from the stats the hook
* fetches once the change has landed. Until then the chip is only held,
* so a second click cannot send the opposite of what the first one is
* still delivering.
*/
const [pending, setPending] = useState<Set<number>>(() => new Set())
const centre = (w: number, h: number) => {
const W = single ? page.pageWidth : page.pageWidth * 2
return { x: (W - w) / 2, y: (page.pageHeight - h) / 2, w, h }
@@ -183,6 +214,42 @@ export function StudioTravelPanel({
/** The linked trips that actually put stops on the route. */
const tripsWithRoute = (stats.trips ?? []).filter(t => t.points > 0)
/*
* The route as rows, counting and left-out stops together.
*
* Every point is listed, so the list reads as the route. The left-out
* stops sit among the counting ones in date order rather than in a list of
* their own, because the question the section answers is "which of these
* count?", and that is only answerable with all of them in one sequence.
* Undated stops go last, then by name.
*/
const stops: StopRow[] = [
...stats.points.map(p => ({
entryId: p.entryId, label: p.label, date: p.date, country: p.country, excluded: false,
})),
...(stats.excluded ?? []).map(x => ({
entryId: x.entryId, label: x.label, date: x.date, country: null, excluded: true,
})),
].sort((a, b) => {
if (a.date !== b.date) {
if (a.date == null) return 1
if (b.date == null) return -1
return a.date < b.date ? -1 : 1
}
return a.label.localeCompare(b.label)
})
const toggleStop = async (entryId: number, excluded: boolean) => {
setPending(prev => new Set(prev).add(entryId))
// A refusal is the hook's to report; here it only frees the chip again.
await onToggleStop(entryId, excluded)
setPending(prev => {
const next = new Set(prev)
next.delete(entryId)
return next
})
}
/* Satellite first: the recommendation should not be the second thing read. */
const imagery = sources
.filter(s => s.id === 'relief' || s.id === 'satellite')
@@ -383,6 +450,52 @@ export function StudioTravelPanel({
</div>
</div>
{/*
The switch is here, beside the maps and the figures it changes, and
not only in the entry editor: the moment somebody notices the home
airport on the printed route is the moment they are looking at this
panel. The rows carry no preview because they are not things to
place; they are the input every tile below reads.
*/}
{stops.length > 0 && (
<div className="st-section">
<div className="st-section-label">{t('journey.studio.stops')}</div>
<p className="st-hint">{t('journey.studio.stopsHint')}</p>
<ul className="st-stops">
{stops.map((stop, i) => {
const entryId = stop.entryId
const on = !stop.excluded
const state = t(on ? 'journey.studio.stopOn' : 'journey.studio.stopOff')
const chip = `st-chip is-pick ${on ? 'is-on' : ''}`
return (
<li key={entryId ?? `place-${i}`} className={`st-stop ${on ? '' : 'is-off'}`}>
<div className="st-stop-body">
<span className="st-stop-label">{stop.label || t('journey.studio.untitled')}</span>
<span className="st-stop-meta">
{stop.date && <span className="st-badge">{formatDate(stop.date, locale)}</span>}
{stop.country && <span className="st-badge is-quiet">{countryName(stop.country)}</span>}
</span>
</div>
{canEdit && entryId != null ? (
<button type="button"
className={chip}
aria-label={t('journey.studio.stopToggle')}
aria-pressed={on}
disabled={pending.has(entryId)}
onClick={() => void toggleStop(entryId, !stop.excluded)}
>
{state}
</button>
) : (
<span className={chip}>{state}</span>
)}
</li>
)
})}
</ul>
</div>
)}
<div className="st-section">
<div className="st-section-label">{t('journey.studio.routeMap')}</div>
{stats.points.length ? (
@@ -0,0 +1,54 @@
import { useJourneyStore } from '../../store/journeyStore'
import { normalizeImageFiles } from '../../utils/convertHeic'
import { isVideoFile } from '../../utils/videoPoster'
import type { UploadProgress } from '../../utils/uploadQueue'
export interface StudioUploadOutcome {
/** trek_photos ids of what arrived, in the order it was sent. */
photoIds: number[]
failed: number
/** Left out before anything was sent, see below. */
skippedVideos: number
}
export type StudioUploader = (
files: File[],
entryId: number | null,
onProgress?: (p: UploadProgress) => void,
) => Promise<StudioUploadOutcome>
/**
* Pictures into the journey without leaving Studio.
*
* Into an entry when one is named, into the gallery otherwise. The journey
* store is what changes either way, so the content browser sees the new
* pictures the way it sees any other; there is no second list to keep in
* step. HEIC is converted first, exactly as the journal's own upload does it.
*
* Videos are left out rather than refused. A drop that carries a clip usually
* carries pictures too, and failing the lot over one file would teach the
* wrong lesson; a book holds pictures, and the count of what was skipped goes
* back so the panel can say so.
*/
export async function uploadStudioPhotos(
journeyId: number,
files: File[],
entryId: number | null,
onProgress?: (p: UploadProgress) => void,
): Promise<StudioUploadOutcome> {
const images = files.filter(f => !isVideoFile(f))
const skippedVideos = files.length - images.length
if (!images.length) return { photoIds: [], failed: 0, skippedVideos }
const normalized = await normalizeImageFiles(images)
const store = useJourneyStore.getState()
const sent = entryId != null
? await store.uploadPhotos(entryId, normalized, { onProgress })
: await store.uploadGalleryPhotos(journeyId, normalized, { onProgress })
return {
photoIds: sent.succeeded.map(p => p.photo_id),
failed: sent.failed.length,
skippedVideos,
}
}