Compare commits

...

25 Commits

Author SHA1 Message Date
Maurice e5e0447fd0 style(server): format the assistant proposal guard
The Server lint formatting check rejected the assistant agent and its regression test. Apply the repository Prettier configuration to those two files.
2026-12-02 01:39:56 +01:00
Maurice 4c05f6f051 Hold identical assistant changes only once per step 2026-12-02 01:32:39 +01:00
Maurice a4cb6c69d8 chore(lint): lower the client ref-warning baseline
The plugin frame permission check now reads the store when needed. GitHub CI reports 384 react-hooks/refs warnings instead of 385.
2026-12-01 22:07:41 +01:00
Maurice 6e224cb7a4 fix(plugins): bind bridge replies to the active document
Keep pending replies tied to their original frame and verify the current permission before returning location data. Release watches when their frame detaches and preserve live replies across host context updates.
2026-12-01 22:00:45 +01:00
Maurice 56b4568a16 test(platform): cover static asset cache boundaries
Exercise the filename and path boundaries used to decide which static assets can be cached permanently, including unhashed Brotli copies.
2026-12-01 21:22:35 +01:00
Maurice 756ef14b97 fix(client): preserve explicit dialog focus and verify accessible controls
Keep the focused search for new places and title fields in explicitly opened dialogs. Assert the native ride badge button and the pointer grip tooltip in the existing tests.
2026-12-01 21:13:35 +01:00
Maurice e539860530 fix(quality): resolve reliability findings on dev
The Sonar quality gate rated new code D. Preserve focus and keyboard interaction through native controls and shared dialog behavior. Replace ambiguous regex scans with bounded parsing and make numeric coercion and initialization explicit.
2026-12-01 21:06:05 +01:00
Maurice 0d6a432967 test(server): type the hosted assistant regression on ES2022
Use the lookup overload for all addresses and drain the stream with the existing TypeScript target. Server types rejected the default lookup overload and Array.fromAsync.
2026-12-01 19:37:29 +01:00
Maurice 89035059ec fix(cloud): route the hosted assistant through its private gateway 2026-12-01 19:28:28 +01:00
Maurice 4ad926aafc fix(ci): give typed server lint more heap and patch audited dependencies
Keep the typed lint rules and ratchet intact after the 8 GiB heap was exhausted on the runner. Resolve the patched Hono adapter and cross-spawn within their existing major versions.
2026-12-01 15:21:50 +01:00
Maurice 60a30afb81 fix(deps): narrow Lucide icon types and lower the lint baseline
Keep the typed icon lookup aligned with the runtime namespace and record the three removed test assertions.
2026-12-01 13:51:32 +01:00
Maurice b77c246df4 fix(deps): keep Lucide SVG markup and Undici tests compatible
Build standalone SVG icons without a React context. Use accessible actions in tests and give the mocked dispatchers the interface the adapter expects.
2026-12-01 13:44:02 +01:00
Maurice 7f4ece2e6f chore(deps): update npm packages and adapt major upgrades
Resolve the MikroORM packages together and use the dispatcher adapter with older built-in fetch implementations. Preserve existing Lucide names and regenerate the Studio and SDK catalogs.
2026-12-01 13:32:28 +01:00
Maurice a14b6a61e6 chore(server): remove resolved plugin type errors from the baseline 2026-12-01 12:29:34 +01:00
Maurice 871135edeb refactor(plugins): generate SDK egress policy from the server 2026-12-01 12:24:32 +01:00
Maurice c22c464e68 fix: keep security checks in sync with their contracts
Mirror the egress policy in the standalone SDK and check its entire shared section. Keep entrypoint assertions aligned with the debug flag and document the mutually exclusive OIDC transactions.
2026-12-01 12:04:55 +01:00
Maurice 3c2dc51439 fix(plugins): validate stable egress options
Keep egress comparisons independent of mutable runtime methods and pass the same normalized options to validation and the socket. Restrict process signaling from plugin workers and disable signal-initiated debugging on standard server starts.
2026-12-01 11:56:24 +01:00
Maurice 28eea68559 fix(media): bound image work before public rendition
Check avatar uploads and raster fallbacks before decoding. Limit compressed bytes, decoded dimensions, GIF frames and the combined TIFF page budget.
2026-12-01 11:56:24 +01:00
Maurice 1ff8a814ae fix(oidc): verify mailbox identity before linking accounts
Preserve the provider mailbox on new accounts. For existing accounts, use the stored issuer and subject or check mailbox identity before linking. Keep the candidate lookup and identity update inside the same transaction.
2026-12-01 11:56:24 +01:00
Maurice 0d521f0930 test(transit): cover long labels in both journey details
Exercise a line with a provider colour and no foreground override on desktop and phone. Confirm that the badge can wrap and leaves room for the rest of the itinerary.
2026-12-01 11:42:31 +01:00
Maurice 7fc011408a test(transit): find mode icons on the line badge
The search test must look for the icon beside the label inside the shared badge.
2026-12-01 11:28:14 +01:00
Maurice 8f20f9f7ea test(transit): check the rendered line badge colours
The booking test checked the nested label after the badge layout changed. Assert the provider colours on the outer badge that sets them.
2026-12-01 11:21:52 +01:00
Maurice 67b65a7647 fix(transit): keep stop names readable beside long route names
Line badges could take the width of a transit row and squeeze its stops. Bound badge width across the itinerary views, wrap full labels in details, and keep compact summaries within their container.

Closes #3287
2026-12-01 11:11:53 +01:00
Luffy 82b2a530f3 fix(places): add titles to Unsplash list cover thumbnails 2026-12-01 15:31:01 +08:00
Maurice 76a3983972 Merge pull request #3284 from liketrek/fix/cloud-store-catalog
fix(native): offer Start and Plus in the TREK Cloud catalog
2026-12-01 01:04:29 +01:00
214 changed files with 4420 additions and 1951 deletions
+4 -4
View File
@@ -438,10 +438,10 @@ jobs:
- name: Lint - name: Lint
# Errors fail, and the warnings per rule may not pass # Errors fail, and the warnings per rule may not pass
# scripts/eslint-baseline.json (src, tests and eslint-disable'd # scripts/eslint-baseline.json (src, tests and eslint-disable'd
# messages counted apart). Type-aware rules build the src + tests # messages counted apart). The typed src and test programs can exhaust
# program, which outgrows Node's default ~4 GB heap on the runner. # an 8 GiB heap. Leave headroom within the runner's 16 GB of RAM.
env: env:
NODE_OPTIONS: --max-old-space-size=8192 NODE_OPTIONS: --max-old-space-size=10240
TREK_LINT_BASE: refs/remotes/lint-base TREK_LINT_BASE: refs/remotes/lint-base
run: cd server && npm run lint:warnings run: cd server && npm run lint:warnings
@@ -990,7 +990,7 @@ jobs:
# Fails on any ESLint error, like lint:check did, and on any rule # Fails on any ESLint error, like lint:check did, and on any rule
# whose warning count rises above scripts/eslint-baseline.json. # whose warning count rises above scripts/eslint-baseline.json.
# Typed linting (no-floating-promises, no-misused-promises) loads the # Typed linting (no-floating-promises, no-misused-promises) loads the
# whole TypeScript program, so it gets the heap the server lint gets. # whole TypeScript program, which exceeds Node's default heap.
env: env:
NODE_OPTIONS: --max-old-space-size=8192 NODE_OPTIONS: --max-old-space-size=8192
TREK_LINT_BASE: refs/remotes/lint-base TREK_LINT_BASE: refs/remotes/lint-base
+15 -14
View File
@@ -55,13 +55,13 @@
"dependencies": { "dependencies": {
"@assistant-ui/react": "0.15.38", "@assistant-ui/react": "0.15.38",
"@capacitor/action-sheet": "^8.1.1", "@capacitor/action-sheet": "^8.1.1",
"@capacitor/android": "^8.6.2", "@capacitor/android": "^8.6.3",
"@capacitor/app": "^8.1.1", "@capacitor/app": "^8.1.1",
"@capacitor/core": "^8.6.2", "@capacitor/core": "^8.6.3",
"@capacitor/dialog": "^8.0.1", "@capacitor/dialog": "^8.0.1",
"@capacitor/filesystem": "^8.1.3", "@capacitor/filesystem": "^8.1.6",
"@capacitor/haptics": "^8.0.2", "@capacitor/haptics": "^8.0.2",
"@capacitor/ios": "^8.6.2", "@capacitor/ios": "^8.6.3",
"@capacitor/keyboard": "^8.0.5", "@capacitor/keyboard": "^8.0.5",
"@capacitor/share": "^8.0.1", "@capacitor/share": "^8.0.1",
"@capacitor/splash-screen": "^8.0.2", "@capacitor/splash-screen": "^8.0.2",
@@ -101,6 +101,7 @@
"@fontsource/satisfy": "^5.3.0", "@fontsource/satisfy": "^5.3.0",
"@fontsource/shrikhand": "^5.3.0", "@fontsource/shrikhand": "^5.3.0",
"@fontsource/yellowtail": "^5.3.0", "@fontsource/yellowtail": "^5.3.0",
"@lucide/icons": "1.82.0",
"@maplibre/maplibre-gl-leaflet": "0.1.4", "@maplibre/maplibre-gl-leaflet": "0.1.4",
"@noble/hashes": "^2.4.0", "@noble/hashes": "^2.4.0",
"@simplewebauthn/browser": "^14.0.0", "@simplewebauthn/browser": "^14.0.0",
@@ -112,9 +113,9 @@
"heic-to": "^1.6.7", "heic-to": "^1.6.7",
"iso-3166-2": "^1.0.0", "iso-3166-2": "^1.0.0",
"leaflet": "^1.9.4", "leaflet": "^1.9.4",
"lucide-react": "^0.577.0", "lucide-react": "^1.82.0",
"mapbox-gl": "3.32.0", "mapbox-gl": "3.32.0",
"maplibre-gl": "6.19.0", "maplibre-gl": "6.20.0",
"modern-screenshot": "4.7.0", "modern-screenshot": "4.7.0",
"plyr": "^3.8.5", "plyr": "^3.8.5",
"react": "^19.3.1", "react": "^19.3.1",
@@ -123,7 +124,7 @@
"react-leaflet": "^5.0.0", "react-leaflet": "^5.0.0",
"react-leaflet-cluster": "^4.1.3", "react-leaflet-cluster": "^4.1.3",
"react-markdown": "^10.1.0", "react-markdown": "^10.1.0",
"react-router": "^7.18.4", "react-router": "^8.5.3",
"rehype-sanitize": "^6.0.0", "rehype-sanitize": "^6.0.0",
"remark-breaks": "^4.0.0", "remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1", "remark-gfm": "^4.0.1",
@@ -133,12 +134,12 @@
"zustand": "^5.0.15" "zustand": "^5.0.15"
}, },
"devDependencies": { "devDependencies": {
"@capacitor/cli": "^8.6.2", "@capacitor/cli": "^8.6.3",
"@eslint/js": "^10.0.1", "@eslint/js": "^10.0.1",
"@jscpd/core": "^4.2.5", "@jscpd/core": "^4.2.5",
"@jscpd/tokenizer": "^4.2.6", "@jscpd/tokenizer": "^4.2.6",
"@playwright/test": "^1.65.1", "@playwright/test": "^1.65.1",
"@testing-library/dom": "^10.4.1", "@testing-library/dom": "^10.4.2",
"@testing-library/jest-dom": "^8.0.0", "@testing-library/jest-dom": "^8.0.0",
"@testing-library/react": "^16.3.3", "@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.13", "@testing-library/user-event": "^14.6.13",
@@ -146,22 +147,22 @@
"@types/geojson": "^7946.0.16", "@types/geojson": "^7946.0.16",
"@types/leaflet": "^1.9.23", "@types/leaflet": "^1.9.23",
"@types/node": "^26.6.11", "@types/node": "^26.6.11",
"@types/react": "^19.3.2", "@types/react": "^19.3.3",
"@types/react-dom": "^19.3.0", "@types/react-dom": "^19.3.0",
"@types/topojson-client": "^3.1.5", "@types/topojson-client": "^3.1.5",
"@types/topojson-specification": "^1.0.5", "@types/topojson-specification": "^1.0.5",
"@vitejs/plugin-react": "^6.2.1", "@vitejs/plugin-react": "^6.2.1",
"@vitest/coverage-v8": "^5.1.2", "@vitest/coverage-v8": "^5.1.2",
"autoprefixer": "^10.7.0", "autoprefixer": "^10.7.1",
"eslint": "^10.11.0", "eslint": "^10.11.0",
"eslint-config-flat-gitignore": "^2.4.0", "eslint-config-flat-gitignore": "^2.4.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.9",
"eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.8", "eslint-plugin-react-refresh": "^0.5.8",
"fake-indexeddb": "^6.2.7", "fake-indexeddb": "^6.2.7",
"jsdom": "^29.1.1", "jsdom": "^29.1.1",
"msw": "^3.0.8", "msw": "^3.0.8",
"postcss": "^8.5.33", "postcss": "^8.5.34",
"prettier": "^3.10.1", "prettier": "^3.10.1",
"prettier-plugin-organize-imports": "^4.3.0", "prettier-plugin-organize-imports": "^4.3.0",
"prettier-plugin-tailwindcss": "^0.8.1", "prettier-plugin-tailwindcss": "^0.8.1",
@@ -170,7 +171,7 @@
"tailwindcss": "^3.4.19", "tailwindcss": "^3.4.19",
"typescript": "^6.0.3", "typescript": "^6.0.3",
"typescript-eslint": "^8.74.0", "typescript-eslint": "^8.74.0",
"vite": "8.3.8", "vite": "8.4.0",
"vite-plugin-pwa": "^2.0.0", "vite-plugin-pwa": "^2.0.0",
"vitest": "^5.1.2" "vitest": "^5.1.2"
} }
+2 -2
View File
@@ -8,7 +8,7 @@
"trek/no-swallowed-catch": 124, "trek/no-swallowed-catch": 124,
"max-params": 31, "max-params": 31,
"trek/store-without-selector": 65, "trek/store-without-selector": 65,
"react-hooks/refs": 385, "react-hooks/refs": 384,
"react-hooks/set-state-in-effect": 188, "react-hooks/set-state-in-effect": 188,
"@typescript-eslint/no-floating-promises": 162, "@typescript-eslint/no-floating-promises": 162,
"react-hooks/exhaustive-deps": 112, "react-hooks/exhaustive-deps": 112,
@@ -35,7 +35,7 @@
}, },
"tests": { "tests": {
"@typescript-eslint/no-explicit-any": 484, "@typescript-eslint/no-explicit-any": 484,
"@typescript-eslint/no-non-null-assertion": 1848, "@typescript-eslint/no-non-null-assertion": 1845,
"@typescript-eslint/no-misused-promises": 22, "@typescript-eslint/no-misused-promises": 22,
"@typescript-eslint/no-unused-vars": 48, "@typescript-eslint/no-unused-vars": 48,
"@typescript-eslint/no-floating-promises": 33, "@typescript-eslint/no-floating-promises": 33,
@@ -1,7 +1,7 @@
import { useState, type ReactNode } from 'react' import { useState, type ReactNode } from 'react'
import { import {
Blocks, AlertTriangle, RefreshCw, Trash2, Download, Bug, ShieldCheck, UploadCloud, Blocks, AlertTriangle, RefreshCw, Trash2, Download, Bug, ShieldCheck, UploadCloud,
ArrowUpCircle, Github, ExternalLink, Check, Search, Link2, KeyRound, ShieldAlert, ArrowUpCircle, ExternalLink, Check, Search, Link2, KeyRound, ShieldAlert,
SlidersHorizontal, CircleDot, Database, SlidersHorizontal, CircleDot, Database,
Globe, History, Puzzle, Bot, Loader2, Globe, History, Puzzle, Bot, Loader2,
} from 'lucide-react' } from 'lucide-react'
@@ -789,7 +789,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
footer={( footer={(
<DialogFooter> <DialogFooter>
<Tooltip label={t('admin.plugins.sourceRepo')}> <Tooltip label={t('admin.plugins.sourceRepo')}>
<a href={repoUrl} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.sourceRepo')} className={linkClass}><Github size={15} /></a> <a href={repoUrl} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.sourceRepo')} className={linkClass}><PluginIcon name="Github" size={15} /></a>
</Tooltip> </Tooltip>
<Tooltip label={t('admin.plugins.reportIssue')}> <Tooltip label={t('admin.plugins.reportIssue')}>
<a href={`${repoUrl}/issues`} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.reportIssue')} className={linkClass}><CircleDot size={15} /></a> <a href={`${repoUrl}/issues`} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.reportIssue')} className={linkClass}><CircleDot size={15} /></a>
@@ -210,11 +210,8 @@ describe('BackupPanel', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('backup-2025-01-15.zip')).toBeInTheDocument() expect(screen.getByText('backup-2025-01-15.zip')).toBeInTheDocument()
}) })
const trashBtn = Array.from(document.querySelectorAll('button')).find( const trashBtn = screen.getByRole('button', { name: 'Delete' })
b => b.querySelector('svg.lucide-trash2'), await user.click(trashBtn)
) as HTMLElement
expect(trashBtn).toBeTruthy()
await user.click(trashBtn!)
// The question is the shared confirm dialog now, not window.confirm // The question is the shared confirm dialog now, not window.confirm
expect(await screen.findByText('Delete backup "backup-2025-01-15.zip"?')).toBeInTheDocument() expect(await screen.findByText('Delete backup "backup-2025-01-15.zip"?')).toBeInTheDocument()
const deleteButtons = screen.getAllByRole('button', { name: 'Delete' }) const deleteButtons = screen.getAllByRole('button', { name: 'Delete' })
@@ -428,9 +425,7 @@ describe('BackupPanel', () => {
render(<><ToastContainer /><BackupPanel /></>) render(<><ToastContainer /><BackupPanel /></>)
await screen.findByText('backup-2025-01-15.zip') await screen.findByText('backup-2025-01-15.zip')
const trashBtn = Array.from(document.querySelectorAll('button')).find( const trashBtn = screen.getByRole('button', { name: 'Delete' })
b => b.querySelector('svg.lucide-trash2'),
) as HTMLElement
await user.click(trashBtn) await user.click(trashBtn)
await user.click(await screen.findByRole('button', { name: 'Cancel' })) await user.click(await screen.findByRole('button', { name: 'Cancel' }))
expect(deleteCalls).toBe(0) expect(deleteCalls).toBe(0)
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
import { Plus, Trash2, Pencil, Package, X, Check, ChevronRight, FolderPlus, Loader2 } from 'lucide-react' import { Plus, Trash2, Pencil, Package, X, Check, ChevronRight, FolderPlus, Loader2 } from 'lucide-react'
import { fs } from '../shared/DialogShell' import { fs } from '../shared/DialogShell'
@@ -57,7 +58,7 @@ export default function PackingTemplateManager() {
{showCreate && ( {showCreate && (
<div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}> <div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}>
<Package size={15} className="flex-none text-content-faint" /> <Package size={15} className="flex-none text-content-faint" />
<input autoFocus value={createName} onChange={e => setCreateName(e.target.value)} <input ref={focusRevealedEditor} value={createName} onChange={e => setCreateName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void handleCreateTemplate(); if (e.key === 'Escape') setShowCreate(false) }} onKeyDown={e => { if (e.key === 'Enter') void handleCreateTemplate(); if (e.key === 'Escape') setShowCreate(false) }}
placeholder={t('admin.packingTemplates.namePlaceholder')} className={COMPOSER_INPUT} style={fs(13, 'body')} /> placeholder={t('admin.packingTemplates.namePlaceholder')} className={COMPOSER_INPUT} style={fs(13, 'body')} />
<Tooltip label={t('common.save')}> <Tooltip label={t('common.save')}>
@@ -101,7 +102,7 @@ export default function PackingTemplateManager() {
<Package size={15} strokeWidth={1.9} /> <Package size={15} strokeWidth={1.9} />
</span> </span>
{editingTemplate === tmpl.id ? ( {editingTemplate === tmpl.id ? (
<input autoFocus value={editTemplateName} onChange={e => setEditTemplateName(e.target.value)} <input ref={focusRevealedEditor} value={editTemplateName} onChange={e => setEditTemplateName(e.target.value)}
onBlur={() => handleRenameTemplate(tmpl.id)} onBlur={() => handleRenameTemplate(tmpl.id)}
onKeyDown={e => { if (e.key === 'Enter') void handleRenameTemplate(tmpl.id); if (e.key === 'Escape') setEditingTemplate(null) }} onKeyDown={e => { if (e.key === 'Enter') void handleRenameTemplate(tmpl.id); if (e.key === 'Escape') setEditingTemplate(null) }}
aria-label={t('common.rename')} aria-label={t('common.rename')}
@@ -132,7 +133,7 @@ export default function PackingTemplateManager() {
{/* Category header */} {/* Category header */}
<div data-row="category" className="flex items-center gap-1.5 border-b border-edge-faint bg-surface-tertiary py-1.5 ps-3 pe-1.5"> <div data-row="category" className="flex items-center gap-1.5 border-b border-edge-faint bg-surface-tertiary py-1.5 ps-3 pe-1.5">
{editingCatId === cat.id ? ( {editingCatId === cat.id ? (
<input autoFocus value={editCatName} onChange={e => setEditCatName(e.target.value)} <input ref={focusRevealedEditor} value={editCatName} onChange={e => setEditCatName(e.target.value)}
onBlur={() => handleRenameCategory(cat.id)} onBlur={() => handleRenameCategory(cat.id)}
onKeyDown={e => { if (e.key === 'Enter') void handleRenameCategory(cat.id); if (e.key === 'Escape') setEditingCatId(null) }} onKeyDown={e => { if (e.key === 'Enter') void handleRenameCategory(cat.id); if (e.key === 'Escape') setEditingCatId(null) }}
aria-label={t('common.rename')} aria-label={t('common.rename')}
@@ -162,7 +163,7 @@ export default function PackingTemplateManager() {
<div key={item.id} data-row="item" className="group flex min-h-[40px] items-center gap-2 py-1.5 ps-3 pe-1.5"> <div key={item.id} data-row="item" className="group flex min-h-[40px] items-center gap-2 py-1.5 ps-3 pe-1.5">
{editingItemId === item.id ? ( {editingItemId === item.id ? (
<> <>
<input autoFocus value={editItemName} onChange={e => setEditItemName(e.target.value)} <input ref={focusRevealedEditor} value={editItemName} onChange={e => setEditItemName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void handleRenameItem(item.id); if (e.key === 'Escape') setEditingItemId(null) }} onKeyDown={e => { if (e.key === 'Enter') void handleRenameItem(item.id); if (e.key === 'Escape') setEditingItemId(null) }}
aria-label={t('common.rename')} aria-label={t('common.rename')}
className={`${ROW_INPUT} flex-1`} style={fs(12.5, 'body')} /> className={`${ROW_INPUT} flex-1`} style={fs(12.5, 'body')} />
@@ -219,7 +220,7 @@ export default function PackingTemplateManager() {
{/* Add category */} {/* Add category */}
{addingCategory ? ( {addingCategory ? (
<div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}> <div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}>
<input autoFocus value={newCatName} onChange={e => setNewCatName(e.target.value)} <input ref={focusRevealedEditor} value={newCatName} onChange={e => setNewCatName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void handleAddCategory(); if (e.key === 'Escape') { setAddingCategory(false); setNewCatName('') } }} onKeyDown={e => { if (e.key === 'Enter') void handleAddCategory(); if (e.key === 'Escape') { setAddingCategory(false); setNewCatName('') } }}
placeholder={t('admin.packingTemplates.categoryName')} placeholder={t('admin.packingTemplates.categoryName')}
className={COMPOSER_INPUT} style={fs(13, 'body')} /> className={COMPOSER_INPUT} style={fs(13, 'body')} />
@@ -67,7 +67,7 @@ function Catalog() {
}}> }}>
<div className={GRID_2}> <div className={GRID_2}>
<EditorField label={t('schoolCatalog.country')} htmlFor={`${fieldId}-name`}> <EditorField label={t('schoolCatalog.country')} htmlFor={`${fieldId}-name`}>
<input id={`${fieldId}-name`} autoFocus required maxLength={100} className={INPUT} value={name} onChange={event => setName(event.target.value)} /> <input id={`${fieldId}-name`} data-initial-focus required maxLength={100} className={INPUT} value={name} onChange={event => setName(event.target.value)} />
</EditorField> </EditorField>
<EditorField label={t('schoolCatalog.code')} htmlFor={`${fieldId}-code`}> <EditorField label={t('schoolCatalog.code')} htmlFor={`${fieldId}-code`}>
<input id={`${fieldId}-code`} required pattern="[A-Z]{2}" maxLength={2} className={`${INPUT} font-geist uppercase tracking-[.08em]`} value={code} onChange={event => setCode(event.target.value.toUpperCase())} placeholder="US" /> <input id={`${fieldId}-code`} required pattern="[A-Z]{2}" maxLength={2} className={`${INPUT} font-geist uppercase tracking-[.08em]`} value={code} onChange={event => setCode(event.target.value.toUpperCase())} placeholder="US" />
@@ -62,7 +62,7 @@ export default function SchoolHolidayRegionEditor({ region, busy, offline = fals
<div className={BODY}> <div className={BODY}>
<fieldset disabled={busy || offline} className={`m-0 flex min-w-0 flex-col gap-5 border-0 p-0 ${busy ? 'opacity-60' : ''}`}> <fieldset disabled={busy || offline} className={`m-0 flex min-w-0 flex-col gap-5 border-0 p-0 ${busy ? 'opacity-60' : ''}`}>
<EditorField label={t('schoolCatalog.region')} htmlFor={`${fieldId}-region`}> <EditorField label={t('schoolCatalog.region')} htmlFor={`${fieldId}-region`}>
<input id={`${fieldId}-region`} autoFocus required maxLength={150} className={INPUT} value={name} onChange={event => setName(event.target.value)} /> <input id={`${fieldId}-region`} data-initial-focus required maxLength={150} className={INPUT} value={name} onChange={event => setName(event.target.value)} />
</EditorField> </EditorField>
<SettingsHint>{t('schoolCatalog.periodHint')}</SettingsHint> <SettingsHint>{t('schoolCatalog.periodHint')}</SettingsHint>
{holidays.map((holiday, index) => { {holidays.map((holiday, index) => {
@@ -3,7 +3,6 @@ import {
ArrowUpCircle, ArrowUpCircle,
Bug, Bug,
CircleDot, CircleDot,
Github,
Globe, Globe,
History, History,
Info, Info,
@@ -23,6 +22,7 @@ import { createPortal } from 'react-dom';
import { POPOVER } from '../../Packing/packingPopoverStyles'; import { POPOVER } from '../../Packing/packingPopoverStyles';
import ToggleSwitch from '../../Settings/ToggleSwitch'; import ToggleSwitch from '../../Settings/ToggleSwitch';
import { fs } from '../../shared/DialogShell'; import { fs } from '../../shared/DialogShell';
import { Github } from '../../shared/legacyLucideIcons';
import PluginIcon from '../../shared/PluginIcon'; import PluginIcon from '../../shared/PluginIcon';
import { Tooltip } from '../../shared/Tooltip'; import { Tooltip } from '../../shared/Tooltip';
import { deriveCaps } from '../pluginCaps'; import { deriveCaps } from '../pluginCaps';
@@ -17,6 +17,10 @@ const h = vi.hoisted(() => {
insets: number[] = []; insets: number[] = [];
kicks = 0; kicks = 0;
disposed = false; disposed = false;
static create(opts: GlobeEngineOptions): FakeEngine {
return new FakeEngine(opts);
}
constructor(opts: GlobeEngineOptions) { constructor(opts: GlobeEngineOptions) {
if (state.failNext !== null) { if (state.failNext !== null) {
const err = state.failNext; const err = state.failNext;
@@ -54,7 +54,7 @@ const AtlasGlobe = forwardRef<AtlasGlobeHandle, AtlasGlobeProps>(function AtlasG
if (!canvas) return; if (!canvas) return;
let engine: GlobeEngine; let engine: GlobeEngine;
try { try {
engine = new GlobeEngine({ engine = GlobeEngine.create({
canvas, canvas,
fetchJson: (p) => propsRef.current.fetchJson(p), fetchJson: (p) => propsRef.current.fetchJson(p),
theme: globeTheme(propsRef.current.dark), theme: globeTheme(propsRef.current.dark),
@@ -210,7 +210,7 @@ async function start(o: StartOptions = {}) {
onSelect: vi.fn(), onSelect: vi.fn(),
onFrame: vi.fn(), onFrame: vi.fn(),
}; };
const engine = new mod.GlobeEngine({ canvas, fetchJson, theme: o.theme ?? LIGHT, initial: o.initial, ...cb }); const engine = mod.GlobeEngine.create({ canvas, fetchJson, theme: o.theme ?? LIGHT, initial: o.initial, ...cb });
engines.push(engine); engines.push(engine);
return { return {
mod, mod,
@@ -310,7 +310,7 @@ describe('GlobeEngine boot', () => {
const otherFetch = vi.fn(async (): Promise<unknown> => null); const otherFetch = vi.fn(async (): Promise<unknown> => null);
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
const onReady = vi.fn(); const onReady = vi.fn();
const second = new first.mod.GlobeEngine({ canvas, fetchJson: otherFetch, theme: LIGHT, onReady }); const second = first.mod.GlobeEngine.create({ canvas, fetchJson: otherFetch, theme: LIGHT, onReady });
engines.push(second); engines.push(second);
await flush(); await flush();
expect(otherFetch).not.toHaveBeenCalled(); expect(otherFetch).not.toHaveBeenCalled();
@@ -345,7 +345,7 @@ describe('GlobeEngine boot retries', () => {
}); });
const onError = vi.fn(); const onError = vi.fn();
engines.push( engines.push(
new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson: fail, theme: LIGHT, onError }) mod.GlobeEngine.create({ canvas: document.createElement('canvas'), fetchJson: fail, theme: LIGHT, onError })
); );
const delays: number[] = []; const delays: number[] = [];
for (let i = 0; i < 4; i++) { for (let i = 0; i < 4; i++) {
@@ -364,7 +364,7 @@ describe('GlobeEngine boot retries', () => {
const ok = vi.fn(async (p: string): Promise<unknown> => files[p]); const ok = vi.fn(async (p: string): Promise<unknown> => files[p]);
const onReady = vi.fn(); const onReady = vi.fn();
engines.push( engines.push(
new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson: ok, theme: LIGHT, onReady }) mod.GlobeEngine.create({ canvas: document.createElement('canvas'), fetchJson: ok, theme: LIGHT, onReady })
); );
await flush(); await flush();
expect(ok).toHaveBeenCalledWith('manifest'); expect(ok).toHaveBeenCalledWith('manifest');
@@ -381,7 +381,9 @@ describe('GlobeEngine boot retries', () => {
return files[p]; return files[p];
}); });
const onReady = vi.fn(); const onReady = vi.fn();
engines.push(new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson, theme: LIGHT, onReady })); engines.push(
mod.GlobeEngine.create({ canvas: document.createElement('canvas'), fetchJson, theme: LIGHT, onReady })
);
await flush(); await flush();
expect(pending.map((t) => t.ms)).toEqual([1000]); expect(pending.map((t) => t.ms)).toEqual([1000]);
pending[0].cb(); pending[0].cb();
@@ -164,7 +164,13 @@ export class GlobeEngine {
private sun: [number, number, number] = sunVector(new Date()); private sun: [number, number, number] = sunVector(new Date());
private sunAt = 0; private sunAt = 0;
constructor(opts: GlobeEngineOptions) { static create(opts: GlobeEngineOptions): GlobeEngine {
const engine = new GlobeEngine(opts);
void engine.boot();
return engine;
}
private constructor(opts: GlobeEngineOptions) {
this.opts = opts; this.opts = opts;
this.theme = opts.theme; this.theme = opts.theme;
Object.assign(this.cam, opts.initial ?? {}); Object.assign(this.cam, opts.initial ?? {});
@@ -187,7 +193,6 @@ export class GlobeEngine {
this.resizeObs.observe(opts.canvas); this.resizeObs.observe(opts.canvas);
opts.canvas.addEventListener('webglcontextlost', this.onContextLost); opts.canvas.addEventListener('webglcontextlost', this.onContextLost);
this.resize(); this.resize();
void this.boot();
} }
// ---------------------------------------------------------------- loading // ---------------------------------------------------------------- loading
@@ -14,7 +14,7 @@ export function hexToRgb(hex: string): Rgb {
.map((c) => c + c) .map((c) => c + c)
.join('') .join('')
: h.slice(0, 6); : h.slice(0, 6);
const n = parseInt(full, 16); const n = Number.parseInt(full, 16);
if (Number.isNaN(n)) return [0.5, 0.5, 0.5]; if (Number.isNaN(n)) return [0.5, 0.5, 0.5];
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]; return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
} }
+2 -1
View File
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react' import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'
import { ChevronDown, Lock, Pencil, Plus, Trash2 } from 'lucide-react' import { ChevronDown, Lock, Pencil, Plus, Trash2 } from 'lucide-react'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
@@ -307,7 +308,7 @@ function TextInput({ value, onSave, onCancel, label, numeric = false }: {
if (ev.key === 'Escape') { ev.preventDefault(); ev.stopPropagation(); finish(onCancel) } if (ev.key === 'Escape') { ev.preventDefault(); ev.stopPropagation(); finish(onCancel) }
} }
return ( return (
<input autoFocus type="text" value={draft} aria-label={label} inputMode={numeric ? 'decimal' : undefined} <input ref={focusRevealedEditor} type="text" value={draft} aria-label={label} inputMode={numeric ? 'decimal' : undefined}
onChange={ev => setDraft(ev.target.value)} onKeyDown={onKey} onBlur={() => finish(() => onSave(draft))} onChange={ev => setDraft(ev.target.value)} onKeyDown={onKey} onBlur={() => finish(() => onSave(draft))}
className={`${INPUT} ${numeric ? 'text-center tabular-nums' : ''}`} /> className={`${INPUT} ${numeric ? 'text-center tabular-nums' : ''}`} />
) )
@@ -197,7 +197,7 @@ function FilterMenu(f: CostsFilterProps & { splitting: boolean }) {
</button> </button>
</Tooltip> </Tooltip>
{open && ( {open && (
<div role="menu" onKeyDown={e => { if (e.key === 'Escape') close() }} className="absolute end-0 top-11 z-30" style={{ ...POPOVER, width: 310 }}> <div role="menu" tabIndex={-1} onKeyDown={e => { if (e.key === 'Escape') close() }} className="absolute end-0 top-11 z-30" style={{ ...POPOVER, width: 310 }}>
{f.splitting && <> {f.splitting && <>
<div className="mx-1.5 mb-1 mt-1.5 flex rounded-[10px] bg-surface-tertiary p-[3px]"> <div className="mx-1.5 mb-1 mt-1.5 flex rounded-[10px] bg-surface-tertiary p-[3px]">
{owners.map(([o, label]) => ( {owners.map(([o, label]) => (
+2 -1
View File
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { cloneElement, CSSProperties, FormEvent, ReactElement, useEffect, useId, useRef, useState } from 'react' import { cloneElement, CSSProperties, FormEvent, ReactElement, useEffect, useId, useRef, useState } from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
import { ExternalLink, Link2, Pencil, Pin, Plus, Trash2, X } from 'lucide-react' import { ExternalLink, Link2, Pencil, Pin, Plus, Trash2, X } from 'lucide-react'
@@ -147,7 +148,7 @@ function LinkModal({ link, onClose, onSave }: { link?: CollabLink; onClose: () =
<div style={{ padding: '14px 16px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}> <div style={{ padding: '14px 16px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
<div> <div>
<label htmlFor="collab-link-title" style={{ ...label, display: 'block' }}>{t('collab.links.titlePlaceholder')}</label> <label htmlFor="collab-link-title" style={{ ...label, display: 'block' }}>{t('collab.links.titlePlaceholder')}</label>
<input id="collab-link-title" value={title} onChange={e => setTitle(e.target.value)} placeholder={t('collab.links.titlePlaceholder')} autoFocus style={field} /> <input id="collab-link-title" value={title} onChange={e => setTitle(e.target.value)} placeholder={t('collab.links.titlePlaceholder')} ref={focusRevealedEditor} style={field} />
</div> </div>
<div> <div>
<label htmlFor="collab-link-url" style={{ ...label, display: 'block' }}>{t('collab.links.urlPlaceholder')}</label> <label htmlFor="collab-link-url" style={{ ...label, display: 'block' }}>{t('collab.links.urlPlaceholder')}</label>
+1 -1
View File
@@ -118,7 +118,7 @@ function CreatePollModal({ onClose, onCreate, t }: CreatePollModalProps) {
)} )}
> >
<EditorField label={t('collab.polls.question')} hint={t('collab.polls.markdownHint')}> <EditorField label={t('collab.polls.question')} hint={t('collab.polls.markdownHint')}>
<textarea autoFocus rows={4} value={question} onChange={e => setQuestion(e.target.value)} placeholder={t('collab.polls.questionPlaceholder')} className={`${TEXTAREA} resize-y`} /> <textarea data-initial-focus rows={4} value={question} onChange={e => setQuestion(e.target.value)} placeholder={t('collab.polls.questionPlaceholder')} className={`${TEXTAREA} resize-y`} />
</EditorField> </EditorField>
<EditorField label={t('collab.polls.options')}> <EditorField label={t('collab.polls.options')}>
@@ -102,7 +102,6 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
<div className="relative"> <div className="relative">
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" /> <Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
<input <input
autoFocus
data-initial-focus data-initial-focus
ref={searchRef} ref={searchRef}
type="text" type="text"
@@ -136,6 +136,7 @@ export default function CollectionExportMenu({ onExport, exporting, t }: Collect
ref={menuRef} ref={menuRef}
id={menuId} id={menuId}
role="menu" role="menu"
tabIndex={-1}
aria-label={t('collections.file.exportTitle')} aria-label={t('collections.file.exportTitle')}
onKeyDown={onMenuKeyDown} onKeyDown={onMenuKeyDown}
className="trek-popover-enter fixed z-[var(--z-toast)] p-1.5 rounded-xl border border-edge bg-surface-card shadow-dropdown" className="trek-popover-enter fixed z-[var(--z-toast)] p-1.5 rounded-xl border border-edge bg-surface-card shadow-dropdown"
@@ -25,6 +25,7 @@ import { placesPath } from '../../utils/placesRoutes';
import MarkdownToolbar from '../Journey/MarkdownToolbar'; import MarkdownToolbar from '../Journey/MarkdownToolbar';
import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation'; import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation';
import { getCategoryIcon } from '../shared/categoryIcons'; import { getCategoryIcon } from '../shared/categoryIcons';
import { focusRevealedEditor } from '../shared/dialogFocus';
import { DialogShell } from '../shared/DialogShell'; import { DialogShell } from '../shared/DialogShell';
import { markdownLinkComponents } from '../shared/markdownLink'; import { markdownLinkComponents } from '../shared/markdownLink';
import { NavigationMenu } from '../shared/NavigationMenu'; import { NavigationMenu } from '../shared/NavigationMenu';
@@ -202,7 +203,7 @@ function Cover({
value={form.name} value={form.name}
onChange={(e) => form.setName(e.target.value)} onChange={(e) => form.setName(e.target.value)}
className="col-detail-name-input min-w-0 flex-1" className="col-detail-name-input min-w-0 flex-1"
autoFocus ref={focusRevealedEditor}
aria-label={t('common.name')} aria-label={t('common.name')}
/> />
</div> </div>
@@ -55,7 +55,7 @@ export default function CopyToTripModal({ isOpen, onClose, placeIds, onCopy, car
<div className="relative"> <div className="relative">
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" /> <Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
<input <input
autoFocus data-initial-focus
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
placeholder={t('collections.copyToTripSearch')} placeholder={t('collections.copyToTripSearch')}
@@ -257,9 +257,14 @@ describe('ListEditorModal', () => {
fireEvent.click(screen.getByRole('button', { name: /Search Unsplash/ })) fireEvent.click(screen.getByRole('button', { name: /Search Unsplash/ }))
expect(await screen.findByRole('button', { name: 'Rin' })).toBeInTheDocument() expect(await screen.findByRole('button', { name: 'Rin' })).toBeInTheDocument()
expect(screen.getByAltText('A street')).toHaveAttribute('title', 'A street')
expect(tripsApi.searchCoverImages).toHaveBeenCalledWith('fjord') expect(tripsApi.searchCoverImages).toHaveBeenCalledWith('fjord')
// A photo without a photographer falls back to the generic label. // A photo without a photographer falls back to the generic label.
fireEvent.click(screen.getByRole('button', { name: 'Unsplash' })) const photo = screen.getByRole('button', { name: 'Unsplash' })
const thumb = photo.querySelector('img')
expect(thumb).toHaveAttribute('alt', '')
expect(thumb).not.toHaveAttribute('title')
fireEvent.click(photo)
expect(document.querySelector('img[src="https://img/full2.jpg"]')).toBeTruthy() expect(document.querySelector('img[src="https://img/full2.jpg"]')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Create' })) fireEvent.click(screen.getByRole('button', { name: 'Create' }))
@@ -126,7 +126,13 @@ export default function ListEditorModal({ target, onClose, onCreated, onRequestD
aria-pressed={on} aria-pressed={on}
className={`relative h-20 overflow-hidden rounded-[10px] transition-shadow ${on ? 'ring-2 ring-accent' : 'ring-1 ring-edge-faint hover:ring-content-faint'}`} className={`relative h-20 overflow-hidden rounded-[10px] transition-shadow ${on ? 'ring-2 ring-accent' : 'ring-1 ring-edge-faint hover:ring-content-faint'}`}
> >
<img src={photo.thumb} alt={photo.description || ''} loading="lazy" className="h-full w-full object-cover" /> <img
src={photo.thumb}
alt={photo.description || ''}
title={photo.description || undefined}
loading="lazy"
className="h-full w-full object-cover"
/>
{photo.photographer && <span className={PHOTO_CREDIT} style={fs(10)}>{photo.photographer}</span>} {photo.photographer && <span className={PHOTO_CREDIT} style={fs(10)}>{photo.photographer}</span>}
</button> </button>
) )
@@ -67,7 +67,7 @@ export default function MoveToListModal({ mode, lists, count, onPick, onClose, t
<div className="relative"> <div className="relative">
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" /> <Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
<input <input
autoFocus data-initial-focus
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
placeholder={t('collections.searchLists')} placeholder={t('collections.searchLists')}
@@ -1,11 +1,12 @@
import type { PlacesLibraryDetailResponse } from '@trek/shared'; import type { PlacesLibraryDetailResponse } from '@trek/shared';
import { Bookmark, Eye, Layers, Luggage, NotebookPen, Pencil, PenLine } from 'lucide-react'; import { Bookmark, Eye, Layers, Luggage, NotebookPen, Pencil, PenLine } from 'lucide-react';
import React, { useRef } from 'react'; import React, { useCallback, useRef } from 'react';
import Markdown from 'react-markdown'; import Markdown from 'react-markdown';
import remarkBreaks from 'remark-breaks'; import remarkBreaks from 'remark-breaks';
import remarkGfm from 'remark-gfm'; import remarkGfm from 'remark-gfm';
import type { TranslationFn } from '../../types'; import type { TranslationFn } from '../../types';
import MarkdownToolbar from '../Journey/MarkdownToolbar'; import MarkdownToolbar from '../Journey/MarkdownToolbar';
import { focusRevealedEditor } from '../shared/dialogFocus';
import { markdownLinkComponents } from '../shared/markdownLink'; import { markdownLinkComponents } from '../shared/markdownLink';
import { Tooltip } from '../shared/Tooltip'; import { Tooltip } from '../shared/Tooltip';
import PlaceCard from './PlaceCard'; import PlaceCard from './PlaceCard';
@@ -51,6 +52,10 @@ function NoteCard({ note, n, t }: { note: OriginNote; n: Notes; t: TranslationFn
*/ */
function NoteEditor({ n, t }: { n: Notes; t: TranslationFn }) { function NoteEditor({ n, t }: { n: Notes; t: TranslationFn }) {
const ref = useRef<HTMLTextAreaElement>(null); const ref = useRef<HTMLTextAreaElement>(null);
const attachEditor = useCallback((element: HTMLTextAreaElement | null) => {
ref.current = element;
focusRevealedEditor(element);
}, []);
const current = n.composeTargets.find((x) => x.key === n.editing) ?? n.notes.find((x) => x.key === n.editing); const current = n.composeTargets.find((x) => x.key === n.editing) ?? n.notes.find((x) => x.key === n.editing);
const multi = n.isNew && n.composeTargets.length > 1; const multi = n.isNew && n.composeTargets.length > 1;
return ( return (
@@ -111,8 +116,7 @@ function NoteEditor({ n, t }: { n: Notes; t: TranslationFn }) {
</div> </div>
) : ( ) : (
<textarea <textarea
ref={ref} ref={attachEditor}
autoFocus
rows={6} rows={6}
value={n.draft} value={n.draft}
onChange={(e) => n.setDraft(e.target.value)} onChange={(e) => n.setDraft(e.target.value)}
@@ -1,6 +1,7 @@
import { MapPin } from 'lucide-react'; import { MapPin } from 'lucide-react';
import React from 'react'; import React from 'react';
import type { Category, TranslationFn } from '../../types'; import type { Category, TranslationFn } from '../../types';
import { focusRevealedEditor } from '../shared/dialogFocus';
import { NumericInput } from '../shared/NumericInput'; import { NumericInput } from '../shared/NumericInput';
import CategoryTileMenu from './CategoryTileMenu'; import CategoryTileMenu from './CategoryTileMenu';
import type { PlaceEditState } from './usePlaceEdit'; import type { PlaceEditState } from './usePlaceEdit';
@@ -36,7 +37,7 @@ export default function PlaceEditForm({
/> />
)} )}
<input <input
autoFocus ref={focusRevealedEditor}
value={draft.name} value={draft.name}
onChange={(e) => edit.set('name', e.target.value)} onChange={(e) => edit.set('name', e.target.value)}
aria-label={t('common.name')} aria-label={t('common.name')}
@@ -1,6 +1,7 @@
import { Bookmark, Check, Luggage, Plus, Search, Tag, X } from 'lucide-react'; import { Bookmark, Check, Luggage, Plus, Search, Tag, X } from 'lucide-react';
import React, { useEffect, useRef } from 'react'; import React, { useEffect, useRef } from 'react';
import type { TranslationFn } from '../../types'; import type { TranslationFn } from '../../types';
import { focusRevealedEditor } from '../shared/dialogFocus';
import PlaceCard from './PlaceCard'; import PlaceCard from './PlaceCard';
import type { PlaceTagsState, TagGroup } from './usePlaceTags'; import type { PlaceTagsState, TagGroup } from './usePlaceTags';
@@ -38,7 +39,7 @@ function TagPicker({ tags, group, t }: { tags: PlaceTagsState; group: TagGroup;
> >
<Search size={14} aria-hidden="true" /> <Search size={14} aria-hidden="true" />
<input <input
autoFocus ref={focusRevealedEditor}
value={tags.query} value={tags.query}
onChange={(e) => tags.setQuery(e.target.value)} onChange={(e) => tags.setQuery(e.target.value)}
placeholder={t('placeTags.search')} placeholder={t('placeTags.search')}
@@ -55,7 +55,7 @@ export default function SaveTripPlacesToListModal({ isOpen, tripId, placeIds, on
<div className="relative"> <div className="relative">
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" /> <Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
<input <input
autoFocus data-initial-focus
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
placeholder={t('collections.searchLists')} placeholder={t('collections.searchLists')}
@@ -8,7 +8,9 @@ import { getApiErrorMessage } from '../../utils/apiError';
import { useToast } from '../shared/Toast'; import { useToast } from '../shared/Toast';
/** A pair's own name: its two keys in a fixed order, so either way round it is one pair. */ /** A pair's own name: its two keys in a fixed order, so either way round it is one pair. */
export const pairKey = (d: Pick<PlacesLibraryDuplicate, 'a' | 'b'>): string => [d.a.key, d.b.key].sort().join('|'); export function pairKey({ a, b }: Pick<PlacesLibraryDuplicate, 'a' | 'b'>): string {
return a.key <= b.key ? `${a.key}|${b.key}` : `${b.key}|${a.key}`;
}
/** /**
* Places that look like the same place (PLC-13), behind the desktop dialog and the * Places that look like the same place (PLC-13), behind the desktop dialog and the
+2 -1
View File
@@ -1,6 +1,7 @@
import { ArrowLeft, ArrowRight, Clock, ExternalLink, Images, RotateCcw } from 'lucide-react'; import { ArrowLeft, ArrowRight, Clock, ExternalLink, Images, RotateCcw } from 'lucide-react';
import { lazy, Suspense, useId } from 'react'; import { lazy, Suspense, useId } from 'react';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
import { focusRevealedEditor } from '../shared/dialogFocus';
import { import {
DialogButton, DialogButton,
DialogFooter, DialogFooter,
@@ -116,7 +117,7 @@ function FooterLinks({ t, onCredits, focusCredits }: { t: Translate; onCredits:
<button <button
type="button" type="button"
onClick={onCredits} onClick={onCredits}
autoFocus={focusCredits} ref={focusCredits ? focusRevealedEditor : undefined}
className={FOOTER_LINK} className={FOOTER_LINK}
style={fs(12.5, 'body')} style={fs(12.5, 'body')}
> >
@@ -106,17 +106,17 @@ export default function DocSyncConnectModal({
</Field> </Field>
))} ))}
<label className="flex items-start justify-between gap-4 rounded-lg border border-edge bg-surface-secondary px-3 py-2.5"> <div className="flex items-start justify-between gap-4 rounded-lg border border-edge bg-surface-secondary px-3 py-2.5">
<span className="min-w-0"> <span className="min-w-0">
<span className="block text-body text-content">{t('docsync.allowInsecureTls')}</span> <span className="block text-body text-content">{t('docsync.allowInsecureTls')}</span>
<span className="mt-0.5 block text-caption text-content-muted"> <span id={`${labelId}-tls-hint`} className="mt-0.5 block text-caption text-content-muted">
{t('docsync.connect.insecureHint')} {t('docsync.connect.insecureHint')}
</span> </span>
</span> </span>
<span className="shrink-0 pt-0.5"> <span className="shrink-0 pt-0.5">
<ToggleSwitch on={form.insecureTls} onToggle={() => form.setInsecureTls(!form.insecureTls)} /> <ToggleSwitch on={form.insecureTls} onToggle={() => form.setInsecureTls(!form.insecureTls)} label={t('docsync.allowInsecureTls')} describedBy={`${labelId}-tls-hint`} />
</span> </span>
</label> </div>
</div> </div>
<ConfirmDialog <ConfirmDialog
@@ -206,7 +206,7 @@ export default function ContributorInviteDialog({ journeyId, existingUserIds, on
<div className="relative"> <div className="relative">
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" /> <Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
<input <input
autoFocus data-initial-focus
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
placeholder={t('journey.contributors.searchPlaceholder')} placeholder={t('journey.contributors.searchPlaceholder')}
@@ -51,7 +51,7 @@ export function AddTripDialog({ journeyId, existingTripIds, onClose, onAdded }:
<div className="relative"> <div className="relative">
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" /> <Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
<input <input
autoFocus data-initial-focus
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
placeholder={t('journey.trips.searchPlaceholder')} placeholder={t('journey.trips.searchPlaceholder')}
@@ -113,9 +113,9 @@ describe('MobileEntryView', () => {
const order: string[] = [] const order: string[] = []
const onClose = vi.fn(() => { order.push('close') }) const onClose = vi.fn(() => { order.push('close') })
const onDelete = vi.fn(() => { order.push('delete') }) const onDelete = vi.fn(() => { order.push('delete') })
const { container } = renderView(buildEntry(), { onClose, onDelete }) renderView(buildEntry(), { onClose, onDelete })
fireEvent.click(container.querySelector('svg.lucide-trash2')!.closest('button')!) fireEvent.click(screen.getByRole('button', { name: /Delete/ }))
expect(order).toEqual(['close', 'delete']) expect(order).toEqual(['close', 'delete'])
}) })
@@ -123,7 +123,7 @@ describe('MobileEntryView', () => {
it('FE-COMP-JENTRYVIEW-006: read-only journeys hide the edit and delete actions', () => { it('FE-COMP-JENTRYVIEW-006: read-only journeys hide the edit and delete actions', () => {
const { container } = renderView(buildEntry(), { readOnly: true }) const { container } = renderView(buildEntry(), { readOnly: true })
expect(screen.queryByRole('button', { name: /Edit/ })).not.toBeInTheDocument() expect(screen.queryByRole('button', { name: /Edit/ })).not.toBeInTheDocument()
expect(container.querySelector('svg.lucide-trash2')).toBeNull() expect(screen.queryByRole('button', { name: /Delete/ })).not.toBeInTheDocument()
// the close button stays // the close button stays
expect(container.querySelector('svg.lucide-x')).not.toBeNull() expect(container.querySelector('svg.lucide-x')).not.toBeNull()
}) })
@@ -104,6 +104,7 @@ export default function MobileEntryView({ entry, readOnly, publicPhotoUrl, onClo
</button> </button>
<button type="button" <button type="button"
onClick={() => { onClose(); onDelete(); }} onClick={() => { onClose(); onDelete(); }}
aria-label={t('common.delete')}
className="w-8 h-8 rounded-lg flex items-center justify-center text-zinc-400 hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-900/20 dark:hover:text-red-400 transition-colors" className="w-8 h-8 rounded-lg flex items-center justify-center text-zinc-400 hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-900/20 dark:hover:text-red-400 transition-colors"
> >
<Trash2 size={15} /> <Trash2 size={15} />
+2 -1
View File
@@ -1,4 +1,5 @@
import { import {
stripTrailingSlashes,
resolveValhallaProvider, resolveValhallaProvider,
VALHALLA_COSTING, VALHALLA_COSTING,
VALHALLA_RELAY_MAX_LOCATIONS, VALHALLA_RELAY_MAX_LOCATIONS,
@@ -245,7 +246,7 @@ export function valhallaBase(): string | null {
*/ */
function currentProvider(ignoreRest = false): { provider: ValhallaProvider | null; own: string } { function currentProvider(ignoreRest = false): { provider: ValhallaProvider | null; own: string } {
const settings = useSettingsStore.getState().settings const settings = useSettingsStore.getState().settings
const own = settings.valhalla_base_url?.trim().replace(/\/+$/, '') ?? '' const own = stripTrailingSlashes(settings.valhalla_base_url?.trim() ?? '')
const provider = resolveValhallaProvider({ const provider = resolveValhallaProvider({
provider: settings.routing_valhalla_provider, provider: settings.routing_valhalla_provider,
valhallaUrl: own, valhallaUrl: own,
@@ -269,7 +269,7 @@ describe('PackingListPanel', () => {
const { container } = render(<PackingListPanel tripId={1} items={items} sort="name" />); const { container } = render(<PackingListPanel tripId={1} items={items} sort="name" />);
// Only the category grip stays: the order of the categories is not the A to Z of their items. // Only the category grip stays: the order of the categories is not the A to Z of their items.
const draggable = [...container.querySelectorAll('[draggable="true"]')]; const draggable = [...container.querySelectorAll('[draggable="true"]')];
expect(draggable.map((el) => el.getAttribute('aria-label'))).toEqual(['Drag to reorder the category']); expect(draggable.map((el) => el.getAttribute('title'))).toEqual(['Drag to reorder the category']);
}); });
it('FE-COMP-PACKING-023: inline edit item name via pencil icon calls PUT', async () => { it('FE-COMP-PACKING-023: inline edit item name via pencil icon calls PUT', async () => {
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { useState, useRef, useCallback } from 'react' import { useState, useRef, useCallback } from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
import { X, Plus } from 'lucide-react' import { X, Plus } from 'lucide-react'
@@ -37,7 +38,7 @@ export function BagCard({ bag, bagItems, totalWeight, pct, tripId, tripMembers,
<div style={{ display: 'flex', alignItems: 'center', gap: sz.gap }}> <div style={{ display: 'flex', alignItems: 'center', gap: sz.gap }}>
<span style={{ width: sz.dot, height: sz.dot, borderRadius: '50%', background: bag.color, flexShrink: 0 }} /> <span style={{ width: sz.dot, height: sz.dot, borderRadius: '50%', background: bag.color, flexShrink: 0 }} />
{editingName && canEdit ? ( {editingName && canEdit ? (
<input autoFocus value={nameVal} onChange={e => setNameVal(e.target.value)} <input ref={focusRevealedEditor} value={nameVal} onChange={e => setNameVal(e.target.value)}
onBlur={saveName} onKeyDown={e => { if (e.key === 'Enter') saveName(); if (e.key === 'Escape') cancelName() }} onBlur={saveName} onKeyDown={e => { if (e.key === 'Enter') saveName(); if (e.key === 'Escape') cancelName() }}
style={{ flex: 1, fontSize: sz.name, fontWeight: 600, padding: '1px 4px', borderRadius: 4, border: '1px solid var(--border-primary)', outline: 'none', fontFamily: 'inherit', color: 'var(--text-primary)', background: 'transparent' }} /> style={{ flex: 1, fontSize: sz.name, fontWeight: 600, padding: '1px 4px', borderRadius: 4, border: '1px solid var(--border-primary)', outline: 'none', fontFamily: 'inherit', color: 'var(--text-primary)', background: 'transparent' }} />
) : ( ) : (
@@ -101,7 +102,7 @@ export function BagCard({ bag, bagItems, totalWeight, pct, tripId, tripMembers,
{editingLimit && canEdit ? ( {editingLimit && canEdit ? (
<> <>
<span>/</span> <span>/</span>
<input autoFocus value={limitVal} onChange={e => setLimitVal(e.target.value)} <input ref={focusRevealedEditor} value={limitVal} onChange={e => setLimitVal(e.target.value)}
onBlur={saveLimit} onBlur={saveLimit}
onKeyDown={e => { if (e.key === 'Enter') saveLimit(); if (e.key === 'Escape') cancelLimit() }} onKeyDown={e => { if (e.key === 'Enter') saveLimit(); if (e.key === 'Escape') cancelLimit() }}
inputMode="decimal" aria-label={t('packing.bagLimit')} placeholder={t('packing.bagLimit')} inputMode="decimal" aria-label={t('packing.bagLimit')} placeholder={t('packing.bagLimit')}
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { X, Plus } from 'lucide-react' import { X, Plus } from 'lucide-react'
import type { PackingState } from './usePackingListPanel' import type { PackingState } from './usePackingListPanel'
import { bagFillPct, bagLoadSummary, packedWeight, perPersonLoads } from './packingListPanel.helpers' import { bagFillPct, bagLoadSummary, packedWeight, perPersonLoads } from './packingListPanel.helpers'
@@ -72,7 +73,7 @@ export function BagModal(S: PackingState) {
{/* Add bag */} {/* Add bag */}
{canEdit && (showAddBag ? ( {canEdit && (showAddBag ? (
<div style={{ display: 'flex', gap: 6, marginTop: 14 }}> <div style={{ display: 'flex', gap: 6, marginTop: 14 }}>
<input autoFocus value={newBagName} onChange={e => setNewBagName(e.target.value)} <input ref={focusRevealedEditor} value={newBagName} onChange={e => setNewBagName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void handleCreateBag(); if (e.key === 'Escape') { setShowAddBag(false); setNewBagName('') } }} onKeyDown={e => { if (e.key === 'Enter') void handleCreateBag(); if (e.key === 'Escape') { setShowAddBag(false); setNewBagName('') } }}
placeholder={t('packing.bagName')} placeholder={t('packing.bagName')}
style={{ flex: 1, padding: '8px 12px', borderRadius: 10, border: '1px solid var(--border-primary)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontFamily: 'inherit', outline: 'none' }} /> style={{ flex: 1, padding: '8px 12px', borderRadius: 10, border: '1px solid var(--border-primary)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontFamily: 'inherit', outline: 'none' }} />
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { useCallback, useRef } from 'react' import { useCallback, useRef } from 'react'
import { Briefcase, Plus, X } from 'lucide-react' import { Briefcase, Plus, X } from 'lucide-react'
import type { PackingState } from './usePackingListPanel' import type { PackingState } from './usePackingListPanel'
@@ -47,7 +48,7 @@ export function BagSidebar(S: PackingState) {
{canEdit && showAddBag && ( {canEdit && showAddBag && (
<div ref={composerRef} style={{ ...COMPOSER, margin: '10px 10px 0', paddingBlock: 4, paddingInlineEnd: 4, paddingInlineStart: 10 }}> <div ref={composerRef} style={{ ...COMPOSER, margin: '10px 10px 0', paddingBlock: 4, paddingInlineEnd: 4, paddingInlineStart: 10 }}>
<span aria-hidden style={{ width: 10, height: 10, borderRadius: '50%', border: '1.5px dashed var(--text-faint)', flexShrink: 0 }} /> <span aria-hidden style={{ width: 10, height: 10, borderRadius: '50%', border: '1.5px dashed var(--text-faint)', flexShrink: 0 }} />
<input autoFocus value={newBagName} onChange={e => setNewBagName(e.target.value)} <input ref={focusRevealedEditor} value={newBagName} onChange={e => setNewBagName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void handleCreateBag(); if (e.key === 'Escape') closeComposer() }} onKeyDown={e => { if (e.key === 'Enter') void handleCreateBag(); if (e.key === 'Escape') closeComposer() }}
placeholder={t('packing.bagName')} placeholder={t('packing.bagName')}
style={{ flex: 1, minWidth: 0, padding: '5px 0', border: 'none', fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 500, fontFamily: 'inherit', outline: 'none', color: 'var(--text-primary)', background: 'transparent' }} /> style={{ flex: 1, minWidth: 0, padding: '5px 0', border: 'none', fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 500, fontFamily: 'inherit', outline: 'none', color: 'var(--text-primary)', background: 'transparent' }} />
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import React, { useState, useRef, useEffect } from 'react' import React, { useState, useRef, useEffect } from 'react'
import { useTripStore } from '../../store/tripStore' import { useTripStore } from '../../store/tripStore'
import { useToast } from '../shared/Toast' import { useToast } from '../shared/Toast'
@@ -140,7 +141,7 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
{editingName && canEdit ? ( {editingName && canEdit ? (
<input <input
autoFocus value={editKatName} ref={focusRevealedEditor} value={editKatName}
onChange={e => setEditKatName(e.target.value)} onChange={e => setEditKatName(e.target.value)}
onBlur={handleSaveKatName} onBlur={handleSaveKatName}
onKeyDown={e => { if (e.key === 'Enter') void handleSaveKatName(); if (e.key === 'Escape') { setEditingName(false); setEditKatName(kategorie) } }} onKeyDown={e => { if (e.key === 'Enter') void handleSaveKatName(); if (e.key === 'Escape') { setEditingName(false); setEditKatName(kategorie) } }}
@@ -319,7 +320,6 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
<span aria-hidden style={{ width: 20, height: 20, borderRadius: 6, border: '1.5px solid var(--text-faint)', flexShrink: 0 }} /> <span aria-hidden style={{ width: 20, height: 20, borderRadius: 6, border: '1.5px solid var(--text-faint)', flexShrink: 0 }} />
<input <input
ref={addItemRef} ref={addItemRef}
autoFocus
value={newItemName} value={newItemName}
onChange={e => setNewItemName(e.target.value)} onChange={e => setNewItemName(e.target.value)}
onKeyDown={e => { onKeyDown={e => {
@@ -404,8 +404,7 @@ function CategoryGrip({ drag, kategorie, label }: { drag?: CategoryDrag; kategor
return ( return (
<span <span
draggable draggable
role="button" aria-hidden="true"
aria-label={label}
title={label} title={label}
onDragStart={e => { onDragStart={e => {
e.dataTransfer.effectAllowed = 'move' e.dataTransfer.effectAllowed = 'move'
@@ -1,3 +1,4 @@
import { replaceInlineMarkdownLinks } from '@trek/shared'
import type { PackingBag, PackingItem } from '../../types' import type { PackingBag, PackingItem } from '../../types'
import { KAT_COLORS, PACKING_PLACEHOLDER_NAME } from './packingListPanel.constants' import { KAT_COLORS, PACKING_PLACEHOLDER_NAME } from './packingListPanel.constants'
@@ -7,7 +8,7 @@ export function katColor(kat: string, allCategories?: string[]): string {
if (idx >= 0) return KAT_COLORS[idx % KAT_COLORS.length] if (idx >= 0) return KAT_COLORS[idx % KAT_COLORS.length]
// Fallback: hash-based // Fallback: hash-based
let h = 0 let h = 0
for (let i = 0; i < kat.length; i++) h = ((h << 5) - h + (kat.codePointAt(i) ?? 0)) | 0 for (let i = 0; i < kat.length; i++) h = Math.imul((h << 5) - h + (kat.codePointAt(i) ?? 0), 1)
return KAT_COLORS[Math.abs(h) % KAT_COLORS.length] return KAT_COLORS[Math.abs(h) % KAT_COLORS.length]
} }
@@ -148,7 +149,7 @@ const MD_WEIGHT = /\((\d+(?:[.,]\d+)?)\s?(g|kg)\)$/i
/** Links, emphasis and code marks as plain text: a list copied from a notes app is full of them. */ /** Links, emphasis and code marks as plain text: a list copied from a notes app is full of them. */
const plainMarkdown = (text: string): string => const plainMarkdown = (text: string): string =>
text.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/\*\*|__|~~|`/g, '').trim() replaceInlineMarkdownLinks(text, (label) => label, true).replace(/\*\*|__|~~|`/g, '').trim()
/** /**
* Whether pasted text is a Markdown list rather than CSV rows (#875): any heading or * Whether pasted text is a Markdown list rather than CSV rows (#875): any heading or
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { useState } from 'react' import { useState } from 'react'
import { Plus, X, MapPin } from 'lucide-react' import { Plus, X, MapPin } from 'lucide-react'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
@@ -40,7 +41,7 @@ export function MobileAddPlaceButton({ dayId, places, assignments, onAssign, onA
<div style={{ borderRadius: 14, border: '1px solid var(--border-primary)', background: 'var(--bg-card)', overflow: 'hidden' }}> <div style={{ borderRadius: 14, border: '1px solid var(--border-primary)', background: 'var(--bg-card)', overflow: 'hidden' }}>
<div style={{ padding: '8px 10px', borderBottom: '1px solid var(--border-faint)', display: 'flex', gap: 6 }}> <div style={{ padding: '8px 10px', borderBottom: '1px solid var(--border-faint)', display: 'flex', gap: 6 }}>
<input <input
autoFocus ref={focusRevealedEditor}
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
placeholder={t('dayplan.mobile.searchPlaces')} placeholder={t('dayplan.mobile.searchPlaces')}
@@ -4,6 +4,7 @@ import type { Category, Place } from '../../types';
import { safeHexColor } from '../../utils/safeColor'; import { safeHexColor } from '../../utils/safeColor';
import type { StopKind } from '../Roadtrip/stopKinds'; import type { StopKind } from '../Roadtrip/stopKinds';
import { getCategoryIcon } from '../shared/categoryIcons'; import { getCategoryIcon } from '../shared/categoryIcons';
import { focusRevealedEditor } from '../shared/dialogFocus';
import { PillSelect } from '../shared/dialogParts'; import { PillSelect } from '../shared/dialogParts';
import { PILL } from '../shared/DialogShell'; import { PILL } from '../shared/DialogShell';
import { NavigationMenu } from '../shared/NavigationMenu'; import { NavigationMenu } from '../shared/NavigationMenu';
@@ -185,7 +186,7 @@ function NewCategoryField({ inputId, name, setName, create, setOpen, t }: NewCat
<input <input
id={inputId} id={inputId}
type="text" type="text"
autoFocus ref={focusRevealedEditor}
value={name} value={name}
onChange={(e) => setName(e.target.value)} onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => { onKeyDown={(e) => {
@@ -12,6 +12,7 @@ import { PendingFiles, PlaceImageSection } from './PlaceFormMedia'
import { usePlaceImageField } from './usePlaceImageField' import { usePlaceImageField } from './usePlaceImageField'
import { useToast } from '../shared/Toast' import { useToast } from '../shared/Toast'
import { Tooltip } from '../shared/Tooltip' import { Tooltip } from '../shared/Tooltip'
import { focusRevealedEditor } from '../shared/dialogFocus'
import { Search, RotateCcw, LocateFixed, PencilLine } from 'lucide-react' import { Search, RotateCcw, LocateFixed, PencilLine } from 'lucide-react'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
import { PlaceContactFields } from './PlaceContactFields' import { PlaceContactFields } from './PlaceContactFields'
@@ -644,7 +645,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
type="text" type="text"
// A new place starts at the search; an edit or a place brought // A new place starts at the search; an edit or a place brought
// in from the map already has what the search would give. // in from the map already has what the search would give.
autoFocus={!place && !prefillCoords} ref={!place && !prefillCoords ? focusRevealedEditor : undefined}
value={mapsSearch} value={mapsSearch}
onChange={e => { setMapsSearch(e.target.value); S.setEmptySearch(null) }} onChange={e => { setMapsSearch(e.target.value); S.setEmptySearch(null) }}
onKeyDown={handleSearchKeyDown} onKeyDown={handleSearchKeyDown}
@@ -81,7 +81,7 @@ export function ListImportModal(S: SidebarState) {
onChange={e => setListImportUrl(e.target.value)} onChange={e => setListImportUrl(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter' && !listImportLoading) void handleListImport() }} onKeyDown={e => { if (e.key === 'Enter' && !listImportLoading) void handleListImport() }}
placeholder={google ? 'https://maps.app.goo.gl/...' : 'https://naver.me/...'} placeholder={google ? 'https://maps.app.goo.gl/...' : 'https://naver.me/...'}
autoFocus data-initial-focus
className={INPUT} className={INPUT}
/> />
</EditorField> </EditorField>
@@ -848,7 +848,7 @@ describe('ReservationsPanel', () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onEdit = vi.fn(); const onEdit = vi.fn();
render(<ReservationsPanel {...defaultProps} reservations={[transitJourney()]} onEdit={onEdit} />); render(<ReservationsPanel {...defaultProps} reservations={[transitJourney()]} onEdit={onEdit} />);
await user.click(screen.getByRole('article', { name: /Hamburg Hbf/ })); await user.click(screen.getByRole('button', { name: /Hamburg Hbf/ }));
const detail = await screen.findByRole('dialog'); const detail = await screen.findByRole('dialog');
expect(onEdit).not.toHaveBeenCalled(); expect(onEdit).not.toHaveBeenCalled();
await user.click(within(detail).getByRole('button', { name: 'Edit' })); await user.click(within(detail).getByRole('button', { name: 'Edit' }));
@@ -274,11 +274,11 @@ describe('ReservationsPanel views', () => {
it('FE-PLANNER-RESVIEW-016: a card opens the detail on click or Enter, and Close shuts it', async () => { it('FE-PLANNER-RESVIEW-016: a card opens the detail on click or Enter, and Close shuts it', async () => {
const user = userEvent.setup(); const user = userEvent.setup();
renderPanel(); renderPanel();
await user.click(screen.getByRole('article', { name: 'LH 716' })); await user.click(within(screen.getByRole('article', { name: 'LH 716' })).getByRole('button', { name: 'LH 716' }));
expect(screen.getByRole('dialog', { name: 'LH 716' })).toBeInTheDocument(); expect(screen.getByRole('dialog', { name: 'LH 716' })).toBeInTheDocument();
await user.click(within(screen.getByRole('dialog', { name: 'LH 716' })).getByRole('button', { name: 'Close' })); await user.click(within(screen.getByRole('dialog', { name: 'LH 716' })).getByRole('button', { name: 'Close' }));
expect(screen.queryByRole('dialog', { name: 'LH 716' })).toBeNull(); expect(screen.queryByRole('dialog', { name: 'LH 716' })).toBeNull();
screen.getByRole('article', { name: 'LH 716' }).focus(); within(screen.getByRole('article', { name: 'LH 716' })).getByRole('button', { name: 'LH 716' }).focus();
await user.keyboard('{Enter}'); await user.keyboard('{Enter}');
expect(screen.getByRole('dialog', { name: 'LH 716' })).toBeInTheDocument(); expect(screen.getByRole('dialog', { name: 'LH 716' })).toBeInTheDocument();
}); });
@@ -286,7 +286,7 @@ describe('ReservationsPanel views', () => {
it('FE-PLANNER-RESVIEW-017: deleting the booking the detail shows closes the detail first', async () => { it('FE-PLANNER-RESVIEW-017: deleting the booking the detail shows closes the detail first', async () => {
const user = userEvent.setup(); const user = userEvent.setup();
renderPanel(); renderPanel();
await user.click(screen.getByRole('article', { name: 'Kaiseki dinner' })); await user.click(within(screen.getByRole('article', { name: 'Kaiseki dinner' })).getByRole('button', { name: 'Kaiseki dinner' }));
expect(screen.getByRole('dialog', { name: 'Kaiseki dinner' })).toBeInTheDocument(); expect(screen.getByRole('dialog', { name: 'Kaiseki dinner' })).toBeInTheDocument();
await user.click(within(screen.getByRole('article', { name: 'Kaiseki dinner' })).getByRole('button', { name: 'Delete' })); await user.click(within(screen.getByRole('article', { name: 'Kaiseki dinner' })).getByRole('button', { name: 'Delete' }));
const deletes = screen.getAllByRole('button', { name: 'Delete' }); const deletes = screen.getAllByRole('button', { name: 'Delete' });
@@ -60,6 +60,19 @@ describe('TransitJourneyModal', () => {
expect(screen.getByText(/BVG/)).toBeInTheDocument() expect(screen.getByText(/BVG/)).toBeInTheDocument()
}) })
it('FE-PLANNER-TRANSITJOURNEY-019: keeps room for both desktop stops beside a long line name', () => {
const reservation = makeReservation()
const line = 'Melbourne Airport Express via Southern Cross'
reservation.metadata.transit.legs[1] = { ...reservation.metadata.transit.legs[1], line, line_text_color: undefined }
render(<TransitJourneyModal {...makeProps({ reservation })} />)
const label = screen.getByText(line)
expect(label.parentElement).toHaveStyle({ maxInlineSize: '40%', color: '#fff' })
expect(label).toHaveClass('[overflow-wrap:anywhere]')
expect(screen.getAllByText('Alexanderplatz').length).toBeGreaterThan(0)
expect(screen.getAllByText('Zoo').length).toBeGreaterThan(0)
})
it('FE-PLANNER-TRANSITJOURNEY-002: inline title rename + notes save as a minimal field payload', async () => { it('FE-PLANNER-TRANSITJOURNEY-002: inline title rename + notes save as a minimal field payload', async () => {
const user = userEvent.setup() const user = userEvent.setup()
const onSave = vi.fn().mockResolvedValue({}) const onSave = vi.fn().mockResolvedValue({})
@@ -263,6 +276,18 @@ describe('TransitJourneyModal (mobile viewport)', () => {
expect(screen.getByText('Kudamm')).toBeInTheDocument() expect(screen.getByText('Kudamm')).toBeInTheDocument()
}) })
it('FE-PLANNER-TRANSITJOURNEY-020: wraps a long phone badge while keeping its headsign visible', () => {
const reservation = makeMobileReservation()
const line = 'Melbourne Airport Express via Southern Cross'
reservation.metadata.transit.legs[1] = { ...reservation.metadata.transit.legs[1], line, line_text_color: undefined }
render(<TransitJourneyModal {...makeProps({ reservation })} />)
const label = screen.getByText(line)
expect(label.parentElement).toHaveStyle({ maxInlineSize: '40%', color: '#fff' })
expect(label).toHaveClass('[overflow-wrap:anywhere]')
expect(screen.getByText('Ruhleben')).toBeInTheDocument()
})
it('FE-PLANNER-TRANSITJOURNEY-016: mobile stat tiles stay iconless but keep value + caption', () => { it('FE-PLANNER-TRANSITJOURNEY-016: mobile stat tiles stay iconless but keep value + caption', () => {
render(<TransitJourneyModal {...makeProps({ reservation: makeMobileReservation() })} />) render(<TransitJourneyModal {...makeProps({ reservation: makeMobileReservation() })} />)
expect(screen.getByText('Transfers')).toBeInTheDocument() expect(screen.getByText('Transfers')).toBeInTheDocument()
@@ -15,7 +15,7 @@ import { useTranslation } from '../../i18n'
import { useSettingsStore } from '../../store/settingsStore' import { useSettingsStore } from '../../store/settingsStore'
import { useTripStore } from '../../store/tripStore' import { useTripStore } from '../../store/tripStore'
import { splitReservationDateTime, formatTime } from '../../utils/formatters' import { splitReservationDateTime, formatTime } from '../../utils/formatters'
import { TransitTitle, TransitMetaBadges, TransitWalkDivider, fmtTransitDuration } from './transitDisplay' import { TransitTitle, TransitLineBadge, TransitMetaBadges, TransitWalkDivider, fmtTransitDuration } from './transitDisplay'
import type { Reservation } from '../../types' import type { Reservation } from '../../types'
import { useIsPhone } from '../../mobile/useIsPhone' import { useIsPhone } from '../../mobile/useIsPhone'
@@ -423,9 +423,7 @@ export default function TransitJourneyModal({ reservation, onClose, onSave, onDe
</div> </div>
<div style={{ padding: '6px 0 8px', minWidth: 0 }}> <div style={{ padding: '6px 0 8px', minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
<span style={{ display: 'inline-flex', alignItems: 'center', background: leg.line_color || 'var(--bg-hover)', color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)', borderRadius: 6, padding: '1px 7px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 700, flexShrink: 0 }}> <TransitLineBadge label={leg.line || leg.mode} besideText={Boolean(leg.headsign)} wrap style={{ background: leg.line_color || 'var(--bg-hover)', color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)', borderRadius: 6, padding: '1px 7px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 700, flexShrink: 0 }} />
{leg.line || leg.mode}
</span>
{leg.headsign && ( {leg.headsign && (
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 'calc(11px * var(--fs-scale-caption, 1))', minWidth: 0 }}> <span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 'calc(11px * var(--fs-scale-caption, 1))', minWidth: 0 }}>
<MoveRight size={10} style={{ flexShrink: 0 }} /> <MoveRight size={10} style={{ flexShrink: 0 }} />
@@ -450,15 +448,13 @@ export default function TransitJourneyModal({ reservation, onClose, onSave, onDe
<div className="text-content-muted" style={{ width: 44, flexShrink: 0, textAlign: 'end', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, paddingTop: 1 }}> <div className="text-content-muted" style={{ width: 44, flexShrink: 0, textAlign: 'end', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, paddingTop: 1 }}>
{leg.from?.time || ''} {leg.from?.time || ''}
</div> </div>
<span style={{ display: 'inline-flex', alignItems: 'center', background: leg.line_color || 'var(--bg-hover)', color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)', borderRadius: 6, padding: '2px 8px', fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 700, flexShrink: 0 }}> <TransitLineBadge label={leg.line || leg.mode} besideText style={{ background: leg.line_color || 'var(--bg-hover)', color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)', borderRadius: 6, padding: '2px 8px', fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 700, flexShrink: 0 }} />
{leg.line || leg.mode}
</span>
<div style={{ flex: 1, minWidth: 0 }}> <div style={{ flex: 1, minWidth: 0 }}>
<div className="text-content" style={{ fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 5, flexWrap: 'wrap' }}> <div className="text-content" style={{ fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 5, flexWrap: 'wrap' }}>
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{leg.from?.name}</span> <span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.from?.name}</span>
{leg.from?.track && <span className="text-content-faint" style={{ fontWeight: 500 }}>({t('transit.platform', { track: leg.from.track })})</span>} {leg.from?.track && <span className="text-content-faint" style={{ fontWeight: 500 }}>({t('transit.platform', { track: leg.from.track })})</span>}
<ArrowRight size={12} className="text-content-faint" style={{ flexShrink: 0 }} /> <ArrowRight size={12} className="text-content-faint" style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{leg.to?.name}</span> <span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.to?.name}</span>
</div> </div>
<div style={{ marginTop: 3 }}> <div style={{ marginTop: 3 }}>
<TransitMetaBadges items={[ <TransitMetaBadges items={[
@@ -616,7 +616,7 @@ describe('TransitSearchPanel', () => {
await pickFromAndTo(user) await pickFromAndTo(user)
await user.click(screen.getByRole('button', { name: /^Search$/ })) await user.click(screen.getByRole('button', { name: /^Search$/ }))
await screen.findByText('B1') await screen.findByText('B1')
const icon = (text: string) => screen.getAllByText(text)[0].closest('span')?.querySelector('svg')?.getAttribute('class') const icon = (text: string) => screen.getAllByText(text)[0].parentElement?.querySelector('svg')?.getAttribute('class')
expect(icon('B1')).toContain('lucide-bus') expect(icon('B1')).toContain('lucide-bus')
expect(icon('M4')).toContain('lucide-tram-front') expect(icon('M4')).toContain('lucide-tram-front')
expect(icon('F10')).toContain('lucide-sailboat') expect(icon('F10')).toContain('lucide-sailboat')
@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom'
import tzlookup from 'tz-lookup' import tzlookup from 'tz-lookup'
import { ArrowLeftRight, ArrowRight, Bus, CableCar, ChevronDown, ChevronUp, Clock, Footprints, MapPin, Sailboat, Search, TramFront, TrainFront, TrainFrontTunnel } from 'lucide-react' import { ArrowLeftRight, ArrowRight, Bus, CableCar, ChevronDown, ChevronUp, Clock, Footprints, MapPin, Sailboat, Search, TramFront, TrainFront, TrainFrontTunnel } from 'lucide-react'
import CustomTimePicker from '../shared/CustomTimePicker' import CustomTimePicker from '../shared/CustomTimePicker'
import { TransitMetaBadges } from './transitDisplay' import { TransitLineBadge, TransitMetaBadges } from './transitDisplay'
import { transitApi } from '../../api/client' import { transitApi } from '../../api/client'
import { useSettingsStore } from '../../store/settingsStore' import { useSettingsStore } from '../../store/settingsStore'
import { useToast } from '../shared/Toast' import { useToast } from '../shared/Toast'
@@ -326,15 +326,17 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
// ── itinerary card ─────────────────────────────────────────────────────────── // ── itinerary card ───────────────────────────────────────────────────────────
function LineBadge({ leg }: { leg: TransitLeg }) { function LineBadge({ leg, wrap = false }: { leg: TransitLeg; wrap?: boolean }) {
const bg = leg.lineColor || 'var(--bg-tertiary)' const bg = leg.lineColor || 'var(--bg-tertiary)'
const fg = leg.lineColor ? (leg.lineTextColor || '#fff') : 'var(--text-primary)' const fg = leg.lineColor ? (leg.lineTextColor || '#fff') : 'var(--text-primary)'
const Icon = legIcon(leg.mode) const Icon = legIcon(leg.mode)
return ( return (
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: bg, color: fg, borderRadius: 6, padding: '2px 7px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 700, whiteSpace: 'nowrap' }}> <TransitLineBadge
<Icon size={11} strokeWidth={2.2} /> label={leg.line || leg.mode}
{leg.line || leg.mode} wrap={wrap}
</span> icon={<Icon size={11} strokeWidth={2.2} className="shrink-0" />}
style={{ gap: 4, background: bg, color: fg, borderRadius: 6, padding: '2px 7px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 700 }}
/>
) )
} }
@@ -425,7 +427,7 @@ function ItineraryCard({ it, tzFrom, tzTo, is12h, expanded, onToggle, onAdd, add
]} /> ]} />
) : ( ) : (
<> <>
<LineBadge leg={leg} /> <LineBadge leg={leg} wrap />
<TransitMetaBadges size="sm" items={[ <TransitMetaBadges size="sm" items={[
{ icon: ArrowRight, text: leg.headsign || '' }, { icon: ArrowRight, text: leg.headsign || '' },
{ text: fmtDuration(leg.duration, t) }, { text: fmtDuration(leg.duration, t) },
@@ -49,112 +49,112 @@ export default function BookingCard(p: BookingCardProps) {
const { t, locale } = useTranslation() const { t, locale } = useTranslation()
const tone = toneOf(r) const tone = toneOf(r)
const transit = r.type === 'transit' const transit = r.type === 'transit'
const title = displayTitle(r)
return ( return (
<article <article
tabIndex={0} aria-label={title}
onClick={p.onSelect} className={`group flex cursor-pointer flex-col overflow-hidden rounded-2xl border bg-surface-secondary transition-shadow hover:shadow-md ${p.selected ? 'border-[color:var(--text-primary)]' : 'border-edge-faint'}`}
onKeyDown={e => { if (e.target === e.currentTarget && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); p.onSelect() } }}
aria-label={displayTitle(r)}
className={`group flex cursor-pointer flex-col overflow-hidden rounded-2xl border bg-surface-secondary transition-shadow hover:shadow-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-[color:var(--text-primary)] ${p.selected ? 'border-[color:var(--text-primary)]' : 'border-edge-faint'}`}
> >
<div className="flex items-center gap-2 border-b border-edge-faint px-3 py-2.5" style={{ background: toneTint(tone) }}> <div role="presentation" onClick={p.onSelect} className="flex flex-1 flex-col">
<StatusDot r={r} canToggle={p.canEdit} onToggle={p.onToggleStatus} /> <div className="flex items-center gap-2 border-b border-edge-faint px-3 py-2.5" style={{ background: toneTint(tone) }}>
<TypeChip type={r.type} /> <StatusDot r={r} canToggle={p.canEdit} onToggle={p.onToggleStatus} />
<span className="flex min-w-0 flex-1 items-center gap-1.5"> <TypeChip type={r.type} />
<span className="min-w-0 truncate font-bold text-content" style={fs(13.5, 'body')}>{displayTitle(r)}</span> <button type="button" aria-label={title} className="flex min-w-0 flex-1 items-center gap-1.5 rounded text-start focus-visible:outline focus-visible:outline-2 focus-visible:outline-[color:var(--text-primary)]">
{!!r.needs_review && <ReviewPill />} <span className="min-w-0 truncate font-bold text-content" style={fs(13.5, 'body')}>{title}</span>
</span> {!!r.needs_review && <ReviewPill />}
<AirTrailPill r={r} /> </button>
{p.canEdit && <RoundAction label={t('common.edit')} onClick={p.onEdit}><Pencil size={12} strokeWidth={2} /></RoundAction>} <AirTrailPill r={r} />
{p.canEdit && <RoundAction label={t('common.delete')} onClick={p.onDelete} danger><Trash2 size={12} strokeWidth={2} /></RoundAction>} {p.canEdit && <RoundAction label={t('common.edit')} onClick={p.onEdit}><Pencil size={12} strokeWidth={2} /></RoundAction>}
</div> {p.canEdit && <RoundAction label={t('common.delete')} onClick={p.onDelete} danger><Trash2 size={12} strokeWidth={2} /></RoundAction>}
</div>
<div className="flex flex-1 flex-col gap-2 px-3 pb-3 pt-2.5"> <div className="flex flex-1 flex-col gap-2 px-3 pb-3 pt-2.5">
<WhenFields facts={facts} /> <WhenFields facts={facts} />
<FlightLiveStrip tripId={p.tripId} reservationId={r.id} type={r.type} /> <FlightLiveStrip tripId={p.tripId} reservationId={r.id} type={r.type} />
{transit ? <TransitBody r={r} /> : ( {transit ? <TransitBody r={r} /> : (
<> <>
{r.confirmation_number && ( {r.confirmation_number && (
<Field label={t('reservations.confirmationCode')} tabular> <Field label={t('reservations.confirmationCode')} tabular>
<BlurredCode className="font-geist">{r.confirmation_number}</BlurredCode> <BlurredCode className="font-geist">{r.confirmation_number}</BlurredCode>
</Field> </Field>
)} )}
<RouteBox type={r.type} facts={facts} /> <RouteBox type={r.type} facts={facts} />
{facts.legCodes.length > 0 && ( {facts.legCodes.length > 0 && (
<Block label={t('reservations.segmentCodes')}> <Block label={t('reservations.segmentCodes')}>
<div className={`${BOX} flex flex-col gap-1 px-[10px] py-2`}> <div className={`${BOX} flex flex-col gap-1 px-[10px] py-2`}>
{facts.legCodes.map((l, i) => ( {facts.legCodes.map((l, i) => (
<div key={i} className="flex items-center gap-2" style={fs(12, 'body')}> <div key={i} className="flex items-center gap-2" style={fs(12, 'body')}>
<span className="min-w-0 flex-1 truncate font-medium text-content-secondary">{l.route || t('reservations.confirmationCode')}</span> <span className="min-w-0 flex-1 truncate font-medium text-content-secondary">{l.route || t('reservations.confirmationCode')}</span>
<BlurredCode className="font-geist tabular-nums text-content-muted">{l.code}</BlurredCode> <BlurredCode className="font-geist tabular-nums text-content-muted">{l.code}</BlurredCode>
</div> </div>
))} ))}
</div>
</Block>
)}
{facts.cells.length > 0 && (
<div className="grid grid-cols-3 gap-2">
{facts.cells.map((c, i) => <Field key={i} label={c.label}>{c.value}</Field>)}
</div> </div>
</Block> )}
)} </>
{facts.cells.length > 0 && ( )}
<div className="grid grid-cols-3 gap-2">
{facts.cells.map((c, i) => <Field key={i} label={c.label}>{c.value}</Field>)} {facts.place && <Field label={t('reservations.locationAddress')}>{facts.place}</Field>}
{facts.accommodation && <Field label={t('reservations.meta.linkAccommodation')}>{facts.accommodation}</Field>}
{facts.linked && <Field label={t('reservations.linkedTo')}>{facts.linked}</Field>}
{facts.url && (
<Field label={t('reservations.urlLabel')}>
{facts.url.href
? <a href={facts.url.href} target="_blank" rel="noopener noreferrer" onClick={e => e.stopPropagation()} className="text-content hover:underline">{facts.url.href}</a>
: facts.url.text}
</Field>
)}
{r.notes && (
<Block label={t('reservations.notes')}>
<div className={`${BOX} collab-note-md line-clamp-4 px-[10px] py-2 text-content-muted`} style={fs(12, 'body')}>
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>{r.notes}</Markdown>
</div> </div>
)} </Block>
</> )}
)}
{facts.place && <Field label={t('reservations.locationAddress')}>{facts.place}</Field>} {(r.travelers || []).length > 0 && (
{facts.accommodation && <Field label={t('reservations.meta.linkAccommodation')}>{facts.accommodation}</Field>} <Block label={t('reservations.travelers.label')}>
{facts.linked && <Field label={t('reservations.linkedTo')}>{facts.linked}</Field>} <TravelerChips travelers={r.travelers || []} />
{facts.url && ( </Block>
<Field label={t('reservations.urlLabel')}> )}
{facts.url.href
? <a href={facts.url.href} target="_blank" rel="noopener noreferrer" onClick={e => e.stopPropagation()} className="text-content hover:underline">{facts.url.href}</a>
: facts.url.text}
</Field>
)}
{r.notes && ( {p.files.length > 0 && (
<Block label={t('reservations.notes')}> <Block label={t('files.title')}>
<div className={`${BOX} collab-note-md line-clamp-4 px-[10px] py-2 text-content-muted`} style={fs(12, 'body')}> <FileRows files={p.files} />
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>{r.notes}</Markdown> </Block>
)}
{p.costs.length > 0 && (
<div className="mt-auto flex flex-wrap justify-end gap-1.5 pt-0.5">
{p.costs.map(c => (
<span key={c.currency} className="inline-flex items-center gap-1 rounded-full bg-surface-tertiary px-2.5 py-[3px] font-geist font-semibold tabular-nums text-content-secondary" style={fs(11.5)}>
<Wallet size={11} strokeWidth={2} className="text-content-faint" />
{formatMoney(c.amount, c.currency, locale)}
</span>
))}
</div> </div>
</Block> )}
)} </div>
{(r.travelers || []).length > 0 && ( <PluginCardFooter items={p.contributions} tripId={p.tripId} />
<Block label={t('reservations.travelers.label')}> {p.showFrames && p.detailPlugins.length > 0 && (
<TravelerChips travelers={r.travelers || []} /> <div role="presentation" onClick={e => e.stopPropagation()} className="flex flex-col gap-2 px-3 pb-3">
</Block> {p.detailPlugins.map(pl => (
)} <div key={pl.id} className={`${BOX} overflow-hidden`}>
<PluginFrame pluginId={pl.id} tripId={String(p.tripId)} reservationId={String(r.id)} title={pl.name} surface="detail-slot" />
{p.files.length > 0 && ( </div>
<Block label={t('files.title')}>
<FileRows files={p.files} />
</Block>
)}
{p.costs.length > 0 && (
<div className="mt-auto flex flex-wrap justify-end gap-1.5 pt-0.5">
{p.costs.map(c => (
<span key={c.currency} className="inline-flex items-center gap-1 rounded-full bg-surface-tertiary px-2.5 py-[3px] font-geist font-semibold tabular-nums text-content-secondary" style={fs(11.5)}>
<Wallet size={11} strokeWidth={2} className="text-content-faint" />
{formatMoney(c.amount, c.currency, locale)}
</span>
))} ))}
</div> </div>
)} )}
</div> </div>
<PluginCardFooter items={p.contributions} tripId={p.tripId} />
{p.showFrames && p.detailPlugins.length > 0 && (
<div role="presentation" onClick={e => e.stopPropagation()} className="flex flex-col gap-2 px-3 pb-3">
{p.detailPlugins.map(pl => (
<div key={pl.id} className={`${BOX} overflow-hidden`}>
<PluginFrame pluginId={pl.id} tripId={String(p.tripId)} reservationId={String(r.id)} title={pl.name} surface="detail-slot" />
</div>
))}
</div>
)}
</article> </article>
) )
} }
@@ -163,7 +163,7 @@ function usePopover() {
function Menu({ children, onClose, width = 260 }: { children: ReactNode; onClose: () => void; width?: number }) { function Menu({ children, onClose, width = 260 }: { children: ReactNode; onClose: () => void; width?: number }) {
return ( return (
<div role="menu" onKeyDown={e => { if (e.key === 'Escape') onClose() }} className="absolute end-0 top-11 z-30" style={{ ...POPOVER, width }}> <div role="menu" tabIndex={-1} onKeyDown={e => { if (e.key === 'Escape') onClose() }} className="absolute end-0 top-11 z-30" style={{ ...POPOVER, width }}>
{children} {children}
</div> </div>
) )
@@ -35,7 +35,7 @@ export default function BookingsList(p: BookingsListProps) {
const rootRef = useRef<HTMLDivElement>(null) const rootRef = useRef<HTMLDivElement>(null)
const flat = p.groups.flatMap(g => (p.collapsed(g.id) ? [] : g.items)) const flat = p.groups.flatMap(g => (p.collapsed(g.id) ? [] : g.items))
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => { const onNavigate = (e: KeyboardEvent<HTMLElement>) => {
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return
e.preventDefault() e.preventDefault()
const focused = document.activeElement instanceof HTMLElement ? Number(document.activeElement.dataset.row) : Number.NaN const focused = document.activeElement instanceof HTMLElement ? Number(document.activeElement.dataset.row) : Number.NaN
@@ -45,13 +45,13 @@ export default function BookingsList(p: BookingsListProps) {
} }
return ( return (
<div ref={rootRef} onKeyDown={onKeyDown} className="flex flex-col gap-6"> <div ref={rootRef} className="flex flex-col gap-6">
{p.groups.map(g => { {p.groups.map(g => {
const open = !p.collapsed(g.id) const open = !p.collapsed(g.id)
return ( return (
<section key={g.id} className="overflow-hidden rounded-2xl border border-edge-faint bg-surface-card"> <section key={g.id} className="overflow-hidden rounded-2xl border border-edge-faint bg-surface-card">
{g.label && ( {g.label && (
<button type="button" onClick={() => p.onToggleGroup(g.id)} aria-expanded={open} <button type="button" onClick={() => p.onToggleGroup(g.id)} onKeyDown={onNavigate} aria-expanded={open}
className="flex w-full items-center gap-2 bg-surface-secondary px-3.5 py-2.5 text-start"> className="flex w-full items-center gap-2 bg-surface-secondary px-3.5 py-2.5 text-start">
<span className={EYEBROW} style={fs(10.5)}>{g.label}</span> <span className={EYEBROW} style={fs(10.5)}>{g.label}</span>
{g.sub && <span className="truncate font-geist font-medium text-content-muted" style={fs(11.5)}>{g.sub}</span>} {g.sub && <span className="truncate font-geist font-medium text-content-muted" style={fs(11.5)}>{g.sub}</span>}
@@ -59,7 +59,7 @@ export default function BookingsList(p: BookingsListProps) {
</button> </button>
)} )}
{open && g.items.map(r => ( {open && g.items.map(r => (
<Row key={r.id} r={r} p={p} facts={p.factsOf(r)} files={p.filesCount(r)} costs={p.costsOf(r)} t={t} locale={locale} /> <Row key={r.id} r={r} p={p} facts={p.factsOf(r)} files={p.filesCount(r)} costs={p.costsOf(r)} t={t} locale={locale} onNavigate={onNavigate} />
))} ))}
</section> </section>
) )
@@ -68,7 +68,7 @@ export default function BookingsList(p: BookingsListProps) {
) )
} }
function Row({ r, p, facts, files, costs, t, locale }: { function Row({ r, p, facts, files, costs, t, locale, onNavigate }: {
r: Reservation r: Reservation
p: BookingsListProps p: BookingsListProps
facts: BookingFacts facts: BookingFacts
@@ -76,6 +76,7 @@ function Row({ r, p, facts, files, costs, t, locale }: {
costs: CostTotal[] costs: CostTotal[]
t: (k: string, v?: Record<string, string | number>) => string t: (k: string, v?: Record<string, string | number>) => string
locale: string locale: string
onNavigate: (e: KeyboardEvent<HTMLElement>) => void
}) { }) {
const selected = p.selectedId === r.id const selected = p.selectedId === r.id
const transit = r.type === 'transit' const transit = r.type === 'transit'
@@ -93,7 +94,10 @@ function Row({ r, p, facts, files, costs, t, locale }: {
aria-pressed={selected} aria-pressed={selected}
aria-label={displayTitle(r)} aria-label={displayTitle(r)}
onClick={() => p.onSelect(r)} onClick={() => p.onSelect(r)}
onKeyDown={e => { if (e.target === e.currentTarget && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); p.onSelect(r) } }} onKeyDown={e => {
if (e.target === e.currentTarget && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); p.onSelect(r) }
else onNavigate(e)
}}
className={`group relative grid cursor-pointer grid-cols-[22px_32px_minmax(0,1fr)_minmax(118px,auto)_auto] items-center gap-3 border-t border-edge-faint px-3.5 py-2.5 first:border-t-0 hover:bg-surface-hover focus-visible:outline-none focus-visible:bg-surface-hover ${selected ? 'bg-surface-hover shadow-[inset_3px_0_0_0_var(--text-primary)]' : ''}`} className={`group relative grid cursor-pointer grid-cols-[22px_32px_minmax(0,1fr)_minmax(118px,auto)_auto] items-center gap-3 border-t border-edge-faint px-3.5 py-2.5 first:border-t-0 hover:bg-surface-hover focus-visible:outline-none focus-visible:bg-surface-hover ${selected ? 'bg-surface-hover shadow-[inset_3px_0_0_0_var(--text-primary)]' : ''}`}
> >
<StatusDot r={r} canToggle={p.canEdit} onToggle={() => p.onToggleStatus(r)} /> <StatusDot r={r} canToggle={p.canEdit} onToggle={() => p.onToggleStatus(r)} />
@@ -42,7 +42,7 @@ describe('transitSummary', () => {
describe('TransitLegs', () => { describe('TransitLegs', () => {
it('FE-PLANNER-BKTRANSIT-005: a ride shows its line, stops and facts', () => { it('FE-PLANNER-BKTRANSIT-005: a ride shows its line, stops and facts', () => {
render(<TransitLegs legs={[ride]} />); render(<TransitLegs legs={[ride]} />);
const line = screen.getByText('U2'); const line = screen.getByText('U2').parentElement;
expect(line).toHaveStyle({ background: '#dc2626', color: '#ffffff' }); expect(line).toHaveStyle({ background: '#dc2626', color: '#ffffff' });
expect(screen.getByText('Alexanderplatz')).toBeInTheDocument(); expect(screen.getByText('Alexanderplatz')).toBeInTheDocument();
expect(screen.getByText('Eberswalder Str.')).toBeInTheDocument(); expect(screen.getByText('Eberswalder Str.')).toBeInTheDocument();
@@ -71,14 +71,14 @@ describe('TransitLegs', () => {
it('FE-PLANNER-BKTRANSIT-007: a line without its own colour and a leg without times or name', () => { it('FE-PLANNER-BKTRANSIT-007: a line without its own colour and a leg without times or name', () => {
render(<TransitLegs legs={[{ mode: 'BUS', from: { name: 'A' }, to: { name: 'B' } }, { mode: 'WALK' }]} compact />); render(<TransitLegs legs={[{ mode: 'BUS', from: { name: 'A' }, to: { name: 'B' } }, { mode: 'WALK' }]} compact />);
expect(screen.getByText('BUS')).toHaveStyle({ background: 'var(--bg-tertiary)' }); expect(screen.getByText('BUS').parentElement).toHaveStyle({ background: 'var(--bg-tertiary)' });
expect(screen.getByText('Walk to')).toBeInTheDocument(); expect(screen.getByText('Walk to')).toBeInTheDocument();
expect(screen.queryByText(/min$/)).toBeNull(); expect(screen.queryByText(/min$/)).toBeNull();
}); });
it('FE-PLANNER-BKTRANSIT-008: a coloured line without a text colour is written in white', () => { it('FE-PLANNER-BKTRANSIT-008: a coloured line without a text colour is written in white', () => {
render(<TransitLegs legs={[{ mode: 'TRAM', line: 'M10', line_color: '#16a34a', from: { name: 'A', time: '09:00' }, to: { name: 'B' } }]} />); render(<TransitLegs legs={[{ mode: 'TRAM', line: 'M10', line_color: '#16a34a', from: { name: 'A', time: '09:00' }, to: { name: 'B' } }]} />);
expect(screen.getByText('M10')).toHaveStyle({ color: '#fff' }); expect(screen.getByText('M10').parentElement).toHaveStyle({ color: '#fff' });
expect(screen.getByText('09:00')).toBeInTheDocument(); expect(screen.getByText('09:00')).toBeInTheDocument();
}); });
}); });
@@ -1,6 +1,6 @@
import { ArrowRight, Clock, Footprints, MoveRight } from 'lucide-react' import { ArrowRight, Clock, Footprints, MoveRight } from 'lucide-react'
import { useTranslation } from '../../../i18n' import { useTranslation } from '../../../i18n'
import { TransitMetaBadges, type TransitLegDisplay } from '../transitDisplay' import { TransitLineBadge, TransitMetaBadges, type TransitLegDisplay } from '../transitDisplay'
import { BOX, fs } from './bookingParts' import { BOX, fs } from './bookingParts'
export interface TransitSummary { export interface TransitSummary {
@@ -41,11 +41,11 @@ export function TransitLegs({ legs, compact = false }: { legs: TransitLegDisplay
return ( return (
<div key={i} className="flex items-start gap-2.5"> <div key={i} className="flex items-start gap-2.5">
{walk ? <Footprints size={compact ? 13 : 14} strokeWidth={2} className="mt-0.5 w-[26px] flex-none text-content-faint" /> : ( {walk ? <Footprints size={compact ? 13 : 14} strokeWidth={2} className="mt-0.5 w-[26px] flex-none text-content-faint" /> : (
<span className="min-w-[26px] flex-none rounded-[5px] px-1.5 py-px text-center font-bold" style={{ <TransitLineBadge label={leg.line || leg.mode} besideText className="min-w-[26px] flex-none justify-center rounded-[5px] px-1.5 py-px text-center font-bold" style={{
...fs(compact ? 10.5 : 11), ...fs(compact ? 10.5 : 11),
background: leg.line_color || 'var(--bg-tertiary)', background: leg.line_color || 'var(--bg-tertiary)',
color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)', // theme-lint-disable: a transit line's own colours color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)', // theme-lint-disable: a transit line's own colours
}}>{leg.line || leg.mode}</span> }} />
)} )}
<div className={`flex min-w-0 flex-1 flex-col ${compact ? 'gap-1' : 'gap-1.5'}`}> <div className={`flex min-w-0 flex-1 flex-col ${compact ? 'gap-1' : 'gap-1.5'}`}>
{/* Detail views show a stop name whole: the names wrap and the {/* Detail views show a stop name whole: the names wrap and the
@@ -1,4 +1,4 @@
import { normalizePlaceWebsite, parsePlaceHours } from '@trek/shared'; import { normalizePlaceWebsite, parsePlaceHours, stripPreviewTags } from '@trek/shared';
import type { PlaceFormData } from './PlaceFormModal.helpers'; import type { PlaceFormData } from './PlaceFormModal.helpers';
import { cleanWeek, weekFromPeriods, writeWeek } from './placeHours'; import { cleanWeek, weekFromPeriods, writeWeek } from './placeHours';
@@ -23,8 +23,7 @@ const text = (value: unknown): string => (typeof value === 'string' ? value.trim
/** A description as plain words: the editor stores markup, the lookup sends text. */ /** A description as plain words: the editor stores markup, the lookup sends text. */
const plain = (value: string): string => const plain = (value: string): string =>
value stripPreviewTags(value)
.replace(/<[^>]*>/g, ' ')
.replace(/[*_`~#>]/g, '') .replace(/[*_`~#>]/g, '')
.replace(/\s+/g, ' ') .replace(/\s+/g, ' ')
.trim(); .trim();
@@ -1,8 +1,8 @@
// FE-PLANNER-TRANSITDISPLAY-001 to FE-PLANNER-TRANSITDISPLAY-003 // FE-PLANNER-TRANSITDISPLAY-001 to FE-PLANNER-TRANSITDISPLAY-005
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { render, screen } from '../../../tests/helpers/render'; import { render, screen } from '../../../tests/helpers/render';
import type { TransitLegDisplay } from './transitDisplay'; import type { TransitLegDisplay } from './transitDisplay';
import { TransitItineraryInline, TransitWalkDivider } from './transitDisplay'; import { TransitItineraryInline, TransitLegChips, TransitWalkDivider } from './transitDisplay';
const t = (key: string, params?: Record<string, string | number>) => const t = (key: string, params?: Record<string, string | number>) =>
params ? `${key}:${Object.values(params).join(',')}` : key; params ? `${key}:${Object.values(params).join(',')}` : key;
@@ -22,6 +22,21 @@ function clipsToOneLine(el: HTMLElement): boolean {
} }
describe('TransitItineraryInline (#3139)', () => { describe('TransitItineraryInline (#3139)', () => {
it('FE-PLANNER-TRANSITDISPLAY-004: a long line name leaves room for both stops', () => {
const line = 'Skybus - Melbourne Airport - Melbourne City';
const from = 'Skybus Coach Terminal/Spencer St';
const to = 'Melbourne (Tullamarine) Airport';
render(<TransitItineraryInline legs={[{ ...ride, line, from: { name: from }, to: { name: to } }]} t={t} />);
const label = screen.getByText(line);
expect(label.parentElement?.style.maxInlineSize).toBe('40%');
expect(label).toHaveClass('[overflow-wrap:anywhere]');
expect(label).not.toHaveClass('truncate');
expect(label).toHaveAttribute('title', line);
expect(screen.getByText(from)).toBeInTheDocument();
expect(screen.getByText(to)).toBeInTheDocument();
});
it('FE-PLANNER-TRANSITDISPLAY-001: a ride shows both stop names in full', () => { it('FE-PLANNER-TRANSITDISPLAY-001: a ride shows both stop names in full', () => {
render(<TransitItineraryInline legs={[ride]} t={t} />); render(<TransitItineraryInline legs={[ride]} t={t} />);
for (const name of ['Basingstoke', 'Reading']) { for (const name of ['Basingstoke', 'Reading']) {
@@ -45,3 +60,15 @@ describe('TransitWalkDivider (#3139)', () => {
expect(clipsToOneLine(text)).toBe(false); expect(clipsToOneLine(text)).toBe(false);
}); });
}); });
describe('TransitLegChips', () => {
it('FE-PLANNER-TRANSITDISPLAY-005: a long badge fits within the chip row', () => {
const line = 'Skybus Melbourne Airport Express';
const { container } = render(<TransitLegChips legs={[{ ...ride, line }]} t={t} />);
expect(container.firstElementChild).toHaveStyle({ minInlineSize: '0px', maxInlineSize: '100%' });
const label = screen.getByText(line);
expect(label).toHaveClass('truncate');
expect(label).toHaveAttribute('title', line);
});
});
@@ -22,6 +22,23 @@ export interface TransitLegDisplay {
to?: { name?: string; time?: string | null; track?: string | null } to?: { name?: string; time?: string | null; track?: string | null }
} }
/** Limit the line badge when it shares a row with stop or headsign text. */
export function TransitLineBadge({ label, besideText = false, wrap = besideText, icon, className = '', style }: {
label?: string
besideText?: boolean
wrap?: boolean
icon?: React.ReactNode
className?: string
style?: React.CSSProperties
}) {
return (
<span className={`inline-flex items-center overflow-hidden ${className}`} style={{ ...style, maxInlineSize: besideText ? '40%' : '100%' }}>
{icon}
<span className={wrap ? 'min-w-0 [overflow-wrap:anywhere]' : 'min-w-0 truncate'} dir="auto" title={label}>{label}</span>
</span>
)
}
/** /**
* A walk leg as a one-line centred divider — dashed rules left and right, * A walk leg as a one-line centred divider — dashed rules left and right,
@@ -77,14 +94,12 @@ export function TransitItineraryInline({ legs, t }: {
<span>{leg.from?.time || ''}</span> <span>{leg.from?.time || ''}</span>
{leg.to?.time && <span className="text-content-faint">{leg.to.time}</span>} {leg.to?.time && <span className="text-content-faint">{leg.to.time}</span>}
</span> </span>
<span style={{ <TransitLineBadge label={leg.line || leg.mode} besideText style={{
display: 'inline-flex', alignItems: 'center', borderRadius: 4, padding: '0 5px', borderRadius: 4, padding: '0 5px',
fontSize: 'calc(9.5px * var(--fs-scale-caption, 1))', fontWeight: 700, lineHeight: '15px', flexShrink: 0, fontSize: 'calc(9.5px * var(--fs-scale-caption, 1))', fontWeight: 700, lineHeight: '15px', flexShrink: 0,
background: leg.line_color || 'var(--bg-tertiary)', background: leg.line_color || 'var(--bg-tertiary)',
color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)', color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)',
}}> }} />
{leg.line || leg.mode}
</span>
<div style={{ flex: 1, minWidth: 0 }}> <div style={{ flex: 1, minWidth: 0 }}>
{/* The folded-out itinerary is where a journey is read in full: stop names wrap (#3139). */} {/* The folded-out itinerary is where a journey is read in full: stop names wrap (#3139). */}
<div className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, display: 'flex', flexWrap: 'wrap', alignItems: 'center', columnGap: 4, minWidth: 0 }}> <div className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, display: 'flex', flexWrap: 'wrap', alignItems: 'center', columnGap: 4, minWidth: 0 }}>
@@ -185,7 +200,7 @@ export function TransitLegChips({ legs, transfers, size = 'sm', t }: {
const walkIcon = size === 'sm' ? 10 : 12 const walkIcon = size === 'sm' ? 10 : 12
const shown = legs.filter(l => l.mode !== 'WALK' || (l.duration || 0) >= 60) const shown = legs.filter(l => l.mode !== 'WALK' || (l.duration || 0) >= 60)
return ( return (
<span style={{ display: 'inline-flex', alignItems: 'center', gap: size === 'sm' ? 4 : 5, flexWrap: 'wrap' }}> <span style={{ display: 'inline-flex', alignItems: 'center', gap: size === 'sm' ? 4 : 5, flexWrap: 'wrap', minInlineSize: 0, maxInlineSize: '100%' }}>
{shown.map((leg, i) => ( {shown.map((leg, i) => (
<React.Fragment key={i}> <React.Fragment key={i}>
{i > 0 && <span className="text-content-faint" style={{ fontSize: size === 'sm' ? 9 : 10 }}>›</span>} {i > 0 && <span className="text-content-faint" style={{ fontSize: size === 'sm' ? 9 : 10 }}>›</span>}
@@ -195,15 +210,13 @@ export function TransitLegChips({ legs, transfers, size = 'sm', t }: {
{Math.round((leg.duration || 0) / 60)} {Math.round((leg.duration || 0) / 60)}
</span> </span>
) : ( ) : (
<span style={{ <TransitLineBadge label={leg.line || leg.mode} style={{
display: 'inline-flex', alignItems: 'center', borderRadius: size === 'sm' ? 4 : 5, borderRadius: size === 'sm' ? 4 : 5,
padding: size === 'sm' ? '0 5px' : '1px 7px', lineHeight: size === 'sm' ? '15px' : undefined, padding: size === 'sm' ? '0 5px' : '1px 7px', lineHeight: size === 'sm' ? '15px' : undefined,
fontSize: badgeFont, fontWeight: 700, fontSize: badgeFont, fontWeight: 700,
background: leg.line_color || 'var(--bg-tertiary)', background: leg.line_color || 'var(--bg-tertiary)',
color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)', color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)',
}}> }} />
{leg.line || leg.mode}
</span>
)} )}
</React.Fragment> </React.Fragment>
))} ))}
@@ -1,4 +1,4 @@
// FE-PLUGINS-FRAME-001 to 061 // FE-PLUGINS-FRAME-001 to 062
import { render, cleanup, waitFor, fireEvent, screen, act } from '@testing-library/react'; import { render, cleanup, waitFor, fireEvent, screen, act } from '@testing-library/react';
import PluginFrame from './PluginFrame'; import PluginFrame from './PluginFrame';
import { usePluginStore } from '../../store/pluginStore'; import { usePluginStore } from '../../store/pluginStore';
@@ -366,6 +366,22 @@ describe('PluginFrame', () => {
}); });
}); });
it('FE-PLUGINS-FRAME-062: a pending get completes for the same document after a host settings update', () => {
const pending: { complete?: (position: unknown) => void } = {};
geo.getCurrentPosition.mockImplementation((complete: (position: unknown) => void) => { pending.complete = complete; });
const { iframe, posted, rerender } = mount(true);
fromFrame(iframe, { type: 'trek:geolocation', requestId: 'pending' });
host.settings = { ...DEFAULT_SETTINGS, distance_unit: 'imperial' };
rerender(<PluginFrame pluginId="demo" />);
pending.complete?.({
coords: { latitude: 0, longitude: 0, altitude: null, accuracy: 10, altitudeAccuracy: null, heading: null, speed: null },
timestamp: 1234,
});
expect(answerFor(posted, 'pending')).toMatchObject({ position: { lat: 0, lng: 0, accuracy: 10 } });
});
it('FE-PLUGINS-FRAME-017: watch streams updates and the GPS watch dies with the frame', () => { it('FE-PLUGINS-FRAME-017: watch streams updates and the GPS watch dies with the frame', () => {
let tick: ((p: unknown) => void) | null = null; let tick: ((p: unknown) => void) | null = null;
geo.watchPosition.mockImplementation((ok: (p: unknown) => void) => { tick = ok; return 7; }); geo.watchPosition.mockImplementation((ok: (p: unknown) => void) => { tick = ok; return 7; });
+49 -56
View File
@@ -223,7 +223,7 @@ function geoErrorCode(e: GeolocationPositionError): 'denied' | 'unavailable' | '
} }
interface ConfirmRequest { interface ConfirmRequest {
requestId: string respond: (confirmed: boolean) => void
title?: string title?: string
message?: string message?: string
confirmLabel?: string confirmLabel?: string
@@ -302,6 +302,17 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
// ids the plugin already had; never the httpOnly cookie); fully closing it // ids the plugin already had; never the httpOnly cookie); fully closing it
// would require not running plugin client JS at all. // would require not running plugin client JS at all.
const loadsRef = useRef(0) const loadsRef = useRef(0)
const geoWatchRef = useRef<number | null>(null)
const stopGeoWatch = useCallback(() => {
if (geoWatchRef.current == null) return
navigator.geolocation.clearWatch(geoWatchRef.current)
geoWatchRef.current = null
}, [])
const attachFrame = useCallback((frame: HTMLIFrameElement | null) => {
stopGeoWatch()
frameRef.current = frame
loadsRef.current = 0
}, [stopGeoWatch])
const { locale, t } = useTranslation() const { locale, t } = useTranslation()
const navigate = useNavigate() const navigate = useNavigate()
const toast = useToast() const toast = useToast()
@@ -342,19 +353,14 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
// height, which reads as a hung app rather than as a plugin that is gone. // height, which reads as a hung app rather than as a plugin that is gone.
const [loadFailed, setLoadFailed] = useState(false) const [loadFailed, setLoadFailed] = useState(false)
const confirmReqRef = useRef<ConfirmRequest | null>(null) const confirmReqRef = useRef<ConfirmRequest | null>(null)
// geolocation:read gate — the feed only flags plugins whose grant is recorded.
// Read via ref (like toastRef) so the bridge effect doesn't re-run on store churn.
const geoAllowed = usePluginStore((s) => s.getById(pluginId)?.geolocation === true)
const geoAllowedRef = useRef(geoAllowed)
geoAllowedRef.current = geoAllowed
// The single live watchPosition of this frame (id from navigator.geolocation).
const geoWatchRef = useRef<number | null>(null)
// opaque frame -> targetOrigin must be '*'. Hoisted so the iframe's onLoad can // opaque frame -> targetOrigin must be '*'. Hoisted so the iframe's onLoad can
// deliver the context too: the trek:ready handshake alone is racy — if the frame // deliver the context too: the trek:ready handshake alone is racy — if the frame
// boots before the effect's listener attaches, the plugin never learns the theme // boots before the effect's listener attaches, the plugin never learns the theme
// and falls back to the OS scheme (dark mode looking "off" until a toggle). // and falls back to the OS scheme (dark mode looking "off" until a toggle).
const postFrame = useCallback((msg: unknown) => frameRef.current?.contentWindow?.postMessage(msg, '*'), []) const postFrame = useCallback((msg: unknown, recipient = frameRef.current?.contentWindow) => {
recipient?.postMessage(msg, '*')
}, [])
const buildContext = useCallback(() => ({ const buildContext = useCallback(() => ({
type: 'trek:context', type: 'trek:context',
tripId, tripId,
@@ -398,17 +404,20 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
useEffect(() => { useEffect(() => {
const frame = frameRef.current const frame = frameRef.current
if (!frame) return const recipient = frame?.contentWindow
if (!frame || !recipient) return
const post = postFrame // Keep responses tied to the document that owns this bridge, including
// responses that arrive after a different iframe is already mounted.
const isCurrentFrame = () => frameRef.current === frame && frame.contentWindow === recipient && loadsRef.current <= 1
const post = (message: unknown) => {
if (isCurrentFrame()) postFrame(message, recipient)
}
const hasGeoGrant = () => usePluginStore.getState().getById(pluginId)?.geolocation === true
const context = buildContext const context = buildContext
const onMessage = async (ev: MessageEvent) => { const onMessage = async (ev: MessageEvent) => {
// The ONLY trusted identity: the message came from OUR iframe's window. if (ev.source !== recipient || !isCurrentFrame()) return
if (ev.source !== frame.contentWindow) return
// …AND that window still holds the original plugin document (loaded once).
// A 2nd load means the frame navigated elsewhere — stop bridging to it.
if (loadsRef.current > 1) return
const msg = ev.data as Inbound const msg = ev.data as Inbound
if (!msg || typeof msg !== 'object') return if (!msg || typeof msg !== 'object') return
@@ -442,8 +451,9 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
post({ type: 'trek:confirm:result', requestId: msg.requestId, confirmed: false }) post({ type: 'trek:confirm:result', requestId: msg.requestId, confirmed: false })
break break
} }
const requestId = msg.requestId
const req: ConfirmRequest = { const req: ConfirmRequest = {
requestId: msg.requestId, respond: confirmed => post({ type: 'trek:confirm:result', requestId, confirmed }),
title: typeof msg.title === 'string' ? msg.title.slice(0, 120) : undefined, title: typeof msg.title === 'string' ? msg.title.slice(0, 120) : undefined,
message: typeof msg.message === 'string' ? msg.message.slice(0, 500) : undefined, message: typeof msg.message === 'string' ? msg.message.slice(0, 500) : undefined,
confirmLabel: typeof msg.confirmLabel === 'string' ? msg.confirmLabel.slice(0, 40) : undefined, confirmLabel: typeof msg.confirmLabel === 'string' ? msg.confirmLabel.slice(0, 40) : undefined,
@@ -488,11 +498,11 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
if (typeof msg.requestId !== 'string' || !msg.requestId) break if (typeof msg.requestId !== 'string' || !msg.requestId) break
const requestId = msg.requestId const requestId = msg.requestId
const fail = (error: string) => post({ type: 'trek:geolocation:result', requestId, error }) const fail = (error: string) => post({ type: 'trek:geolocation:result', requestId, error })
if (!geoAllowedRef.current) { fail('forbidden'); break } if (!hasGeoGrant()) { fail('forbidden'); break }
if (!('geolocation' in navigator)) { fail('unsupported'); break } if (!('geolocation' in navigator)) { fail('unsupported'); break }
const action = msg.action ?? 'get' const action = msg.action ?? 'get'
if (action === 'clear') { if (action === 'clear') {
if (geoWatchRef.current != null) { navigator.geolocation.clearWatch(geoWatchRef.current); geoWatchRef.current = null } stopGeoWatch()
post({ type: 'trek:geolocation:result', requestId, cleared: true }) post({ type: 'trek:geolocation:result', requestId, cleared: true })
break break
} }
@@ -500,25 +510,28 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
if (action === 'watch') { if (action === 'watch') {
// One watch per frame — a new request replaces the old one. Confirmed // One watch per frame — a new request replaces the old one. Confirmed
// immediately; positions stream as trek:geolocation:update messages. // immediately; positions stream as trek:geolocation:update messages.
if (geoWatchRef.current != null) navigator.geolocation.clearWatch(geoWatchRef.current) stopGeoWatch()
post({ type: 'trek:geolocation:result', requestId, watching: true }) post({ type: 'trek:geolocation:result', requestId, watching: true })
// Re-check the grant on every fix, not just at start: if an admin revokes // Re-check the grant on every fix, not just at start: if an admin revokes
// geolocation:read while the frame stays open, the stream stops at once. // geolocation:read while the frame stays open, the stream stops at once.
const stillAllowed = () => { const stillAllowed = () => {
if (geoAllowedRef.current) return true if (hasGeoGrant()) return true
if (geoWatchRef.current != null) { navigator.geolocation.clearWatch(geoWatchRef.current); geoWatchRef.current = null } stopGeoWatch()
return false return false
} }
geoWatchRef.current = navigator.geolocation.watchPosition( geoWatchRef.current = navigator.geolocation.watchPosition(
(p) => { if (loadsRef.current <= 1 && stillAllowed()) post({ type: 'trek:geolocation:update', position: geoPosition(p) }) }, (p) => { if (isCurrentFrame() && stillAllowed()) post({ type: 'trek:geolocation:update', position: geoPosition(p) }) },
(e) => { if (loadsRef.current <= 1 && stillAllowed()) post({ type: 'trek:geolocation:update', error: geoErrorCode(e) }) }, (e) => { if (isCurrentFrame() && stillAllowed()) post({ type: 'trek:geolocation:update', error: geoErrorCode(e) }) },
geoOpts, geoOpts,
) )
break break
} }
navigator.geolocation.getCurrentPosition( navigator.geolocation.getCurrentPosition(
(p) => { if (loadsRef.current <= 1) post({ type: 'trek:geolocation:result', requestId, position: geoPosition(p) }) }, (p) => {
(e) => { if (loadsRef.current <= 1) fail(geoErrorCode(e)) }, if (!hasGeoGrant()) { fail('forbidden'); return }
post({ type: 'trek:geolocation:result', requestId, position: geoPosition(p) })
},
(e) => fail(hasGeoGrant() ? geoErrorCode(e) : 'forbidden'),
geoOpts, geoOpts,
) )
break break
@@ -662,23 +675,15 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
themeObserver.disconnect() themeObserver.disconnect()
if (wsForward) removeListener(wsForward) if (wsForward) removeListener(wsForward)
} }
}, [pluginId, tripId, fill, navigate, postFrame, buildContext, userId]) }, [pluginId, path, suspended, tripId, fill, navigate, postFrame, buildContext, userId, stopGeoWatch])
// Hosts swap pluginId in place (tab bar, /plugins/:id route) — the iframe below // The host can replace this document in place. Drop the previous document's
// is keyed so the document is a fresh first load, and the per-plugin bridge // UI while leaving ordinary context updates alone.
// state must start over with it or the new plugin would be refused as a
// "navigated" frame (loads > 1) and an open confirm would leak across plugins.
useEffect(() => { useEffect(() => {
loadsRef.current = 0
setHeight(null) setHeight(null)
confirmReqRef.current = null confirmReqRef.current = null
setConfirmReq(null) setConfirmReq(null)
// Only a real teardown may kill the watch: the bridge above re-runs on any }, [pluginId, path])
// settings, locale or breakpoint change, and nothing would re-arm it.
return () => {
if (geoWatchRef.current != null) { navigator.geolocation.clearWatch(geoWatchRef.current); geoWatchRef.current = null }
}
}, [pluginId])
// Watch whether the frame is on screen (and the tab/app in the foreground) and // Watch whether the frame is on screen (and the tab/app in the foreground) and
// forward it to the plugin as `trek:visibility`; on a phone, a dashboard widget // forward it to the plugin as `trek:visibility`; on a phone, a dashboard widget
@@ -712,27 +717,15 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
io.disconnect() io.disconnect()
document.removeEventListener('visibilitychange', onVis) document.removeEventListener('visibilitychange', onVis)
} }
}, [pluginId, postFrame, suspendable]) }, [pluginId, path, postFrame, suspendable])
// Coming back from a suspend remounts a fresh iframe (same pluginId key), so the
// load counter has to start over or the remount reads as a self-navigation and
// never gets the context; going into one stops the geolocation watch of the frame
// that is about to be unmounted.
useEffect(() => { useEffect(() => {
if (suspended) { if (!suspended) visibleRef.current = true
if (geoWatchRef.current != null) {
navigator.geolocation.clearWatch(geoWatchRef.current)
geoWatchRef.current = null
}
} else {
loadsRef.current = 0
visibleRef.current = true
}
}, [suspended]) }, [suspended])
const answerConfirm = (confirmed: boolean) => { const answerConfirm = (confirmed: boolean) => {
const req = confirmReqRef.current const req = confirmReqRef.current
if (req) postFrame({ type: 'trek:confirm:result', requestId: req.requestId, confirmed }) req?.respond(confirmed)
confirmReqRef.current = null confirmReqRef.current = null
setConfirmReq(null) setConfirmReq(null)
} }
@@ -744,8 +737,8 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
const pluginFrame = ( const pluginFrame = (
<iframe <iframe
key={pluginId} key={`${pluginId}/${path}`}
ref={frameRef} ref={attachFrame}
src={`/plugin-frame/${pluginId}/${path}`} src={`/plugin-frame/${pluginId}/${path}`}
// Deliver the context as soon as the document is parsed (the plugin sets up its // Deliver the context as soon as the document is parsed (the plugin sets up its
// message listener during parse), closing the trek:ready race so the theme is // message listener during parse), closing the trek:ready race so the theme is
@@ -761,7 +754,7 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
} }
// A self-navigated frame is no longer bridged, so its watch is only // A self-navigated frame is no longer bridged, so its watch is only
// burning battery for positions nobody receives. // burning battery for positions nobody receives.
else if (geoWatchRef.current != null) { navigator.geolocation.clearWatch(geoWatchRef.current); geoWatchRef.current = null } else stopGeoWatch()
}} }}
onError={() => setLoadFailed(true)} onError={() => setLoadFailed(true)}
sandbox="allow-scripts allow-forms" sandbox="allow-scripts allow-forms"
@@ -2,6 +2,6 @@ import { Tooltip } from '../shared/Tooltip'
export default function SettingsHint({ children, id }: { children: string; id?: string }) { export default function SettingsHint({ children, id }: { children: string; id?: string }) {
return <Tooltip label={children} placement="top"> return <Tooltip label={children} placement="top">
<p id={id} tabIndex={0} className="min-w-0 truncate text-caption leading-snug text-content-faint">{children}</p> <button type="button" id={id} className="block min-w-0 truncate text-start text-caption leading-snug text-content-faint">{children}</button>
</Tooltip> </Tooltip>
} }
+1 -1
View File
@@ -4,7 +4,6 @@ import {
Bug, Bug,
Coffee, Coffee,
ExternalLink, ExternalLink,
Github,
Heart, Heart,
Info, Info,
Lightbulb, Lightbulb,
@@ -17,6 +16,7 @@ import { useTranslation } from '../../i18n';
import { useAuthStore } from '../../store/authStore'; import { useAuthStore } from '../../store/authStore';
import { donationsShown } from '../../utils/donations'; import { donationsShown } from '../../utils/donations';
import { fs } from '../shared/DialogShell'; import { fs } from '../shared/DialogShell';
import { Github } from '../shared/legacyLucideIcons';
import PatreonIcon, { PATREON_COLOR, PATREON_URL } from '../shared/PatreonIcon'; import PatreonIcon, { PATREON_COLOR, PATREON_URL } from '../shared/PatreonIcon';
import Section from './Section'; import Section from './Section';
import { StatusPill } from './settingsKit'; import { StatusPill } from './settingsKit';
@@ -183,7 +183,7 @@ export default function ApiKeysSection(): React.ReactElement {
placeholder={t('settings.apiKeys.modal.namePlaceholder')} placeholder={t('settings.apiKeys.modal.namePlaceholder')}
maxLength={100} maxLength={100}
className={INPUT} className={INPUT}
autoFocus /> data-initial-focus />
</EditorField> </EditorField>
<section role="group" aria-labelledby="api-key-scopes-title"> <section role="group" aria-labelledby="api-key-scopes-title">
@@ -420,7 +420,7 @@ function CreateTokenDialog({ S }: { S: IntegrationsState }) {
onKeyDown={e => e.key === 'Enter' && handleCreateMcpToken()} onKeyDown={e => e.key === 'Enter' && handleCreateMcpToken()}
placeholder={t('settings.mcp.modal.tokenNamePlaceholder')} placeholder={t('settings.mcp.modal.tokenNamePlaceholder')}
className={INPUT} className={INPUT}
autoFocus /> data-initial-focus />
</EditorField> </EditorField>
)} )}
</DialogShell> </DialogShell>
@@ -453,17 +453,17 @@ function McpTokenModals({ S }: { S: IntegrationsState }) {
*/ */
function MachineClientSwitch({ checked, onChange, t }: { checked: boolean; onChange: (next: boolean) => void; t: IntegrationsState['t'] }) { function MachineClientSwitch({ checked, onChange, t }: { checked: boolean; onChange: (next: boolean) => void; t: IntegrationsState['t'] }) {
return ( return (
<label htmlFor="oauth-machine-client" className="flex cursor-pointer items-center gap-4 rounded-[12px] border border-edge-faint bg-surface-card px-3.5 py-3"> <div className="relative flex items-center gap-4 rounded-[12px] border border-edge-faint bg-surface-card px-3.5 py-3">
<span className="min-w-0 flex-1"> <span className="min-w-0 flex-1">
<span className="block font-medium text-content" style={fs(13, 'body')}>{t('settings.oauth.modal.machineClient')}</span> <label htmlFor="oauth-machine-client" className="block cursor-pointer font-medium text-content after:absolute after:inset-0" style={fs(13, 'body')}>{t('settings.oauth.modal.machineClient')}</label>
<span className="mt-0.5 block leading-snug text-content-faint" style={fs(11.5)}>{t('settings.oauth.modal.machineClientHint')}</span> <span id="oauth-machine-client-hint" className="mt-0.5 block leading-snug text-content-faint" style={fs(11.5)}>{t('settings.oauth.modal.machineClientHint')}</span>
</span> </span>
<input id="oauth-machine-client" type="checkbox" checked={checked} onChange={e => onChange(e.target.checked)} className="peer sr-only" /> <input id="oauth-machine-client" aria-describedby="oauth-machine-client-hint" type="checkbox" checked={checked} onChange={e => onChange(e.target.checked)} className="peer sr-only" />
<span aria-hidden="true" <span aria-hidden="true"
className="relative h-6 w-11 flex-none rounded-full bg-[var(--border-primary)] transition-colors peer-checked:bg-accent peer-focus-visible:ring-2 peer-focus-visible:ring-[color:var(--text-primary)] peer-checked:[&>span]:left-[22px] peer-checked:[&>span]:bg-[var(--accent-text)]"> className="relative h-6 w-11 flex-none rounded-full bg-[var(--border-primary)] transition-colors peer-checked:bg-accent peer-focus-visible:ring-2 peer-focus-visible:ring-[color:var(--text-primary)] peer-checked:[&>span]:left-[22px] peer-checked:[&>span]:bg-[var(--accent-text)]">
<span className="absolute left-0.5 top-0.5 h-5 w-5 rounded-full bg-surface-card shadow-sm transition-[left]" /> <span className="absolute left-0.5 top-0.5 h-5 w-5 rounded-full bg-surface-card shadow-sm transition-[left]" />
</span> </span>
</label> </div>
) )
} }
@@ -494,7 +494,7 @@ function ClientForm({ S, labelId }: { S: IntegrationsState; labelId: string }) {
<input id={`${labelId}-name`} type="text" value={oauthNewName} onChange={e => setOauthNewName(e.target.value)} <input id={`${labelId}-name`} type="text" value={oauthNewName} onChange={e => setOauthNewName(e.target.value)}
placeholder={t('settings.oauth.modal.clientNamePlaceholder')} placeholder={t('settings.oauth.modal.clientNamePlaceholder')}
className={INPUT} className={INPUT}
autoFocus /> data-initial-focus />
</EditorField> </EditorField>
<MachineClientSwitch checked={oauthIsMachine} onChange={setOauthIsMachine} t={t} /> <MachineClientSwitch checked={oauthIsMachine} onChange={setOauthIsMachine} t={t} />
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import React from 'react' import React from 'react'
import { Fingerprint, Plus, Trash2, Pencil, Check, X, AlertTriangle } from 'lucide-react' import { Fingerprint, Plus, Trash2, Pencil, Check, X, AlertTriangle } from 'lucide-react'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
@@ -56,7 +57,7 @@ export default function PasskeysSection({ demoMode }: { demoMode?: boolean }): R
{pk.renamingId === c.id ? ( {pk.renamingId === c.id ? (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<input <input
autoFocus ref={focusRevealedEditor}
type="text" type="text"
value={pk.renameVal} value={pk.renameVal}
onChange={e => pk.setRenameVal(e.target.value)} onChange={e => pk.setRenameVal(e.target.value)}
@@ -19,10 +19,7 @@ function WatchSwitch({ W }: { W: WandererWatchController }) {
// keeps its focus when the connection is known. // keeps its focus when the connection is known.
return ( return (
<Tooltip label={t('wanderer.watch.notConnected')} disabled={!off}> <Tooltip label={t('wanderer.watch.notConnected')} disabled={!off}>
<span <span className={`relative inline-flex rounded-full ${off ? 'opacity-50' : ''}`}>
tabIndex={off ? 0 : undefined}
className={`inline-flex rounded-full outline-none ${off ? 'cursor-not-allowed opacity-50 focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[color:var(--bg-card)]' : ''}`}
>
<span className={`inline-flex ${off ? 'pointer-events-none' : ''}`}> <span className={`inline-flex ${off ? 'pointer-events-none' : ''}`}>
<ToggleSwitch <ToggleSwitch
on={W.enabled} on={W.enabled}
@@ -31,6 +28,14 @@ function WatchSwitch({ W }: { W: WandererWatchController }) {
disabled={off} disabled={off}
/> />
</span> </span>
{off && (
<button
type="button"
aria-disabled="true"
aria-label={t('wanderer.watch.notConnected')}
className="absolute inset-0 cursor-not-allowed rounded-full outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)]"
/>
)}
</span> </span>
</Tooltip> </Tooltip>
); );
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { useState } from 'react' import { useState } from 'react'
import { ChevronsDown, ChevronsUp, Copy, Lock, RotateCcw, RotateCw, Trash2, Unlock } from 'lucide-react' import { ChevronsDown, ChevronsUp, Copy, Lock, RotateCcw, RotateCw, Trash2, Unlock } from 'lucide-react'
import type { BookElement, BookPageSetup, BookSpread } from '@trek/shared' import type { BookElement, BookPageSetup, BookSpread } from '@trek/shared'
@@ -304,7 +305,7 @@ export function StudioCanvas({
return ( return (
<textarea <textarea
className="st-inline-edit" className="st-inline-edit"
autoFocus ref={focusRevealedEditor}
defaultValue={el.text} defaultValue={el.text}
style={{ style={{
left: el.frame.x * scaled, left: el.frame.x * scaled,
@@ -123,13 +123,13 @@ export function StudioFontPicker({
close(); close();
}; };
const onKey = (e: KeyboardEvent) => { const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return; if (e.key !== 'Escape' || !open) return;
e.stopPropagation(); e.stopPropagation();
close(); close();
}; };
return ( return (
<div className={`st-fontpick ${open ? 'is-open' : ''}`} onKeyDown={onKey}> <div className={`st-fontpick ${open ? 'is-open' : ''}`}>
<button <button
ref={trigger} ref={trigger}
type="button" type="button"
@@ -138,6 +138,7 @@ export function StudioFontPicker({
aria-controls={listId} aria-controls={listId}
aria-label={`${t('journey.studio.fonts.change')}: ${current.name}`} aria-label={`${t('journey.studio.fonts.change')}: ${current.name}`}
onClick={() => (open ? close() : setOpen(true))} onClick={() => (open ? close() : setOpen(true))}
onKeyDown={onKey}
> >
<span <span
className="st-fontpick-face" className="st-fontpick-face"
@@ -156,18 +157,26 @@ export function StudioFontPicker({
ref={search} ref={search}
value={query} value={query}
onChange={(e) => setQuery(e.target.value)} onChange={(e) => setQuery(e.target.value)}
onKeyDown={onKey}
placeholder={t('journey.studio.fonts.search')} placeholder={t('journey.studio.fonts.search')}
aria-label={t('journey.studio.fonts.search')} aria-label={t('journey.studio.fonts.search')}
aria-controls={listId} aria-controls={listId}
spellCheck={false} spellCheck={false}
/> />
{query && ( {query && (
<button type="button" onClick={() => setQuery('')} aria-label={t('common.clear')}> <button type="button" onClick={() => setQuery('')} onKeyDown={onKey} aria-label={t('common.clear')}>
<X size={13} /> <X size={13} />
</button> </button>
)} )}
</div> </div>
<div id={listId} className="st-fontpick-list" role="listbox" aria-label={t('journey.studio.fonts.list')}> <div
id={listId}
className="st-fontpick-list"
role="listbox"
tabIndex={-1}
aria-label={t('journey.studio.fonts.list')}
onKeyDown={onKey}
>
{!query && ( {!query && (
<FontGroup <FontGroup
label={t('journey.studio.fonts.used')} label={t('journey.studio.fonts.used')}
@@ -22,6 +22,7 @@ import {
type LucideIcon, type LucideIcon,
} from 'lucide-react'; } from 'lucide-react';
import { useRef, useState } from 'react'; import { useRef, useState } from 'react';
import { focusRevealedEditor } from '../shared/dialogFocus';
import { useStudioStore } from '../../store/studioStore'; import { useStudioStore } from '../../store/studioStore';
import '../../styles/studio-layers.css'; import '../../styles/studio-layers.css';
@@ -261,6 +262,7 @@ export function StudioLayersPanel({ t }: { t: T }) {
ref={list} ref={list}
className={`st-layers ${drag?.active ? 'is-dragging' : ''}`} className={`st-layers ${drag?.active ? 'is-dragging' : ''}`}
role="tree" role="tree"
tabIndex={-1}
aria-label={t('journey.studio.layers')} aria-label={t('journey.studio.layers')}
onKeyDown={onTreeKey} onKeyDown={onTreeKey}
onPointerMove={onPointerMove} onPointerMove={onPointerMove}
@@ -448,7 +450,7 @@ function RowName(p: {
return ( return (
<input <input
className="st-input st-layer-input" className="st-input st-layer-input"
autoFocus ref={focusRevealedEditor}
defaultValue={p.named ? p.label : ''} defaultValue={p.named ? p.label : ''}
placeholder={p.label} placeholder={p.label}
maxLength={60} maxLength={60}
@@ -8,7 +8,7 @@ import {
type BookPatternPaint, type BookPatternPaint,
} from '@trek/shared'; } from '@trek/shared';
import { ArrowLeftRight, Ban, Trash2 } from 'lucide-react'; import { ArrowLeftRight, Ban, Trash2 } from 'lucide-react';
import { useRef, useState } from 'react'; import { useId, useRef, useState } from 'react';
import '../../styles/studio-paint.css'; import '../../styles/studio-paint.css';
import { NumField } from './StudioControls'; import { NumField } from './StudioControls';
import type { StudioT } from './StudioSidebar'; import type { StudioT } from './StudioSidebar';
@@ -350,13 +350,18 @@ function Slider({
const pos = Math.round((log ? Math.log(value / min) / Math.log(max / min) : (value - min) / (max - min)) * steps); const pos = Math.round((log ? Math.log(value / min) / Math.log(max / min) : (value - min) / (max - min)) * steps);
// What the slider was last moved to: a controlled input may still show the old value when it is let go. // What the slider was last moved to: a controlled input may still show the old value when it is let go.
const moved = useRef(value); const moved = useRef(value);
const fieldId = useId();
return ( return (
<label className="st-paint-slider"> <div className="st-paint-slider">
<span className="st-paint-slider-head"> <span className="st-paint-slider-head">
<span className="st-paint-caption">{label}</span> <label htmlFor={fieldId} className="st-paint-caption">
{label}
</label>
<span className="st-paint-value">{shown}</span> <span className="st-paint-value">{shown}</span>
</span> </span>
<input <input
id={fieldId}
aria-valuetext={shown}
type="range" type="range"
min={0} min={0}
max={steps} max={steps}
@@ -375,6 +380,6 @@ function Slider({
onPointerUp={() => onChange(moved.current, true)} onPointerUp={() => onChange(moved.current, true)}
onKeyUp={() => onChange(moved.current, true)} onKeyUp={() => onChange(moved.current, true)}
/> />
</label> </div>
); );
} }
+4 -2
View File
@@ -1,5 +1,6 @@
import * as LucideIcons from 'lucide-react' import * as LucideIcons from 'lucide-react'
import { resolvePluginIcon } from '../shared/PluginIcon' import { resolvePluginIcon } from '../shared/PluginIcon'
import { legacyLucideIcons } from '../shared/legacyLucideIcons'
import type { LucideIcon } from 'lucide-react' import type { LucideIcon } from 'lucide-react'
import { BOOK_DESIGN_ICONS } from '@trek/shared' import { BOOK_DESIGN_ICONS } from '@trek/shared'
@@ -30,10 +31,11 @@ const PASCAL_CASE = /^[A-Z][A-Za-z0-9]*$/
function buildNames(): string[] { function buildNames(): string[] {
const all = LucideIcons as unknown as Record<string, unknown> const all = LucideIcons as unknown as Record<string, unknown>
const names = Object.keys(all).filter(k => PASCAL_CASE.test(k)) const names = [...Object.keys(all), ...legacyLucideIcons.keys()]
.filter(k => PASCAL_CASE.test(k) && k !== 'Icon' && k !== 'LucideProvider')
const present = new Set(names) const present = new Set(names)
return names return [...present]
.filter(name => { .filter(name => {
// `LucidePlane` is always an alias of `Plane`. // `LucidePlane` is always an alias of `Plane`.
if (name.startsWith('Lucide') && present.has(name.slice(6))) return false if (name.startsWith('Lucide') && present.has(name.slice(6))) return false
@@ -1,4 +1,3 @@
import * as LucideIcons from 'lucide-react';
import { import {
BedDouble, BedDouble,
Check, Check,
@@ -16,6 +15,7 @@ import {
Zap, Zap,
} from 'lucide-react'; } from 'lucide-react';
import React from 'react'; import React from 'react';
import { lucideIconByName } from '../shared/lucideIconLookup';
import './releaseNoticeVisuals.css'; import './releaseNoticeVisuals.css';
/* /*
@@ -233,7 +233,7 @@ const VISUALS: Record<string, () => React.ReactElement> = {
export function ReleaseFeatureVisual({ visual, iconName }: { visual?: string; iconName: string }) { export function ReleaseFeatureVisual({ visual, iconName }: { visual?: string; iconName: string }) {
const Drawing = visual ? VISUALS[visual] : undefined; const Drawing = visual ? VISUALS[visual] : undefined;
if (Drawing) return <Drawing />; if (Drawing) return <Drawing />;
const Icon: React.ElementType = ((LucideIcons as Record<string, unknown>)[iconName] as React.ElementType) ?? Sparkles; const Icon = lucideIconByName[iconName] ?? Sparkles;
return ( return (
<div className="rn-vis rn-vis-icon"> <div className="rn-vis rn-vis-icon">
<Icon size={30} strokeWidth={1.6} aria-hidden="true" /> <Icon size={30} strokeWidth={1.6} aria-hidden="true" />
@@ -2,7 +2,6 @@ import React, { useState, useEffect, useRef } from 'react';
import { flushSync } from 'react-dom'; import { flushSync } from 'react-dom';
import { useNavigate } from 'react-router'; import { useNavigate } from 'react-router';
import { Info, AlertTriangle, AlertOctagon, X, ChevronLeft, ChevronRight, Coffee } from 'lucide-react'; import { Info, AlertTriangle, AlertOctagon, X, ChevronLeft, ChevronRight, Coffee } from 'lucide-react';
import * as LucideIcons from 'lucide-react';
import remarkGfm from 'remark-gfm'; import remarkGfm from 'remark-gfm';
import rehypeSanitize from 'rehype-sanitize'; import rehypeSanitize from 'rehype-sanitize';
import { useSystemNoticeStore } from '../../store/systemNoticeStore.js'; import { useSystemNoticeStore } from '../../store/systemNoticeStore.js';
@@ -11,6 +10,7 @@ import { useTranslation, isRtlLanguage } from '../../i18n/index.js';
import { runNoticeAction } from './noticeActions.js'; import { runNoticeAction } from './noticeActions.js';
import { ReleaseNoticeModal } from './ReleaseNoticeModal.js'; import { ReleaseNoticeModal } from './ReleaseNoticeModal.js';
import { PATREON_PATH } from '../shared/PatreonIcon'; import { PATREON_PATH } from '../shared/PatreonIcon';
import { lucideIconByName } from '../shared/lucideIconLookup';
import { lockBodyScroll } from '../../utils/bodyScrollLock.js'; import { lockBodyScroll } from '../../utils/bodyScrollLock.js';
const ReactMarkdown = React.lazy(() => const ReactMarkdown = React.lazy(() =>
@@ -101,9 +101,7 @@ function NoticeContent({ notice, title, body, ctaLabel, secondaryCtaLabel, terti
const isLastPage = total <= 1 || currentPage === total - 1; const isLastPage = total <= 1 || currentPage === total - 1;
const DefaultIcon = SEVERITY_ICONS[notice.severity] ?? Info; const DefaultIcon = SEVERITY_ICONS[notice.severity] ?? Info;
const LucideIcon: React.ElementType = notice.icon const LucideIcon: React.ElementType = lucideIconByName[notice.icon ?? ''] ?? DefaultIcon;
? ((LucideIcons as Record<string, unknown>)[notice.icon] as React.ElementType) ?? DefaultIcon
: DefaultIcon;
// Real brand logo for each support button, detected from the link target. // Real brand logo for each support button, detected from the link target.
const primaryBrand = notice.cta?.kind === 'link' ? brandForHref(notice.cta.href) : null; const primaryBrand = notice.cta?.kind === 'link' ? brandForHref(notice.cta.href) : null;
@@ -232,9 +230,7 @@ function NoticeContent({ notice, title, body, ctaLabel, secondaryCtaLabel, terti
{notice.highlights && notice.highlights.length > 0 && ( {notice.highlights && notice.highlights.length > 0 && (
<div className="flex flex-wrap justify-center gap-2 mb-4"> <div className="flex flex-wrap justify-center gap-2 mb-4">
{notice.highlights.map((h, i) => { {notice.highlights.map((h, i) => {
const HIcon: React.ElementType | null = h.iconName const HIcon = lucideIconByName[h.iconName ?? ''];
? ((LucideIcons as Record<string, unknown>)[h.iconName] as React.ElementType) ?? null
: null;
return ( return (
<span <span
key={i} key={i}
+2 -1
View File
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { Fragment, useId, useState, useEffect, useEffectEvent, type CSSProperties } from 'react' import { Fragment, useId, useState, useEffect, useEffectEvent, type CSSProperties } from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
import { useTripStore } from '../../store/tripStore' import { useTripStore } from '../../store/tripStore'
@@ -463,7 +464,7 @@ function NewTaskPane({ tripId, categories, members, defaultCategory, onCreated,
<PaneHead title={t('todo.newItem')} onClose={onClose} /> <PaneHead title={t('todo.newItem')} onClose={onClose} />
<div style={FORM_BODY}> <div style={FORM_BODY}>
<input autoFocus value={name} onChange={e => setName(e.target.value)} <input ref={focusRevealedEditor} value={name} onChange={e => setName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter' && name.trim()) void create() }} onKeyDown={e => { if (e.key === 'Enter' && name.trim()) void create() }}
style={{ ...taskInputStyle, fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 600 }} style={{ ...taskInputStyle, fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 600 }}
placeholder={t('todo.namePlaceholder')} /> placeholder={t('todo.namePlaceholder')} />
@@ -45,6 +45,7 @@ import { NavigationMenu } from '../shared/NavigationMenu';
import { useToast } from '../shared/Toast'; import { useToast } from '../shared/Toast';
import { Tooltip } from '../shared/Tooltip'; import { Tooltip } from '../shared/Tooltip';
import TrackColorPicker from '../shared/TrackColorPicker'; import TrackColorPicker from '../shared/TrackColorPicker';
import { focusRevealedEditor } from '../shared/dialogFocus';
import { markdownLinkComponents } from '../shared/markdownLink'; import { markdownLinkComponents } from '../shared/markdownLink';
import { TourDayRowAvatar } from './TourDayRowFacts'; import { TourDayRowAvatar } from './TourDayRowFacts';
import { TourGpxExportButton } from './TourGpxExportButton'; import { TourGpxExportButton } from './TourGpxExportButton';
@@ -442,7 +443,7 @@ function TourNameHeading({
return ( return (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<input <input
autoFocus ref={focusRevealedEditor}
value={nameDraft} value={nameDraft}
onChange={(event) => setNameDraft(event.target.value)} onChange={(event) => setNameDraft(event.target.value)}
onKeyDown={(event) => { onKeyDown={(event) => {
@@ -98,7 +98,7 @@ describe('a ride taken from a GPX file (HOR-02)', () => {
expect(facts).toHaveTextContent('No riding time'); expect(facts).toHaveTextContent('No riding time');
expect(facts).toHaveTextContent('Access not checked'); expect(facts).toHaveTextContent('Access not checked');
// Each reason is the badge's description, reachable without a pointer. // Each reason is the badge's description, reachable without a pointer.
const access = screen.getByText('Access not checked').closest('[tabindex="0"]') as HTMLElement; const access = screen.getByRole('button', { name: 'Access not checked' });
expect(access).toHaveAccessibleDescription( expect(access).toHaveAccessibleDescription(
'The import does not check whether the ways may be ridden. The signs on site count.' 'The import does not check whether the ways may be ridden. The signs on site count.'
); );
@@ -21,8 +21,9 @@ function FactPill({ icon, label, info }: { icon?: ReactNode; label: string; info
if (!info) return pill; if (!info) return pill;
return ( return (
<Tooltip label={info}> <Tooltip label={info}>
<span <button
tabIndex={0} type="button"
aria-label={label}
aria-describedby={id} aria-describedby={id}
className="inline-flex rounded-full focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent" className="inline-flex rounded-full focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
> >
@@ -30,7 +31,7 @@ function FactPill({ icon, label, info }: { icon?: ReactNode; label: string; info
<span id={id} className="sr-only"> <span id={id} className="sr-only">
{info} {info}
</span> </span>
</span> </button>
</Tooltip> </Tooltip>
); );
} }
@@ -117,7 +117,7 @@ function ListFilters({ library }: { library: TourLibrary }) {
</label> </label>
<input <input
id={searchId} id={searchId}
autoFocus data-initial-focus
value={library.filters.query} value={library.filters.query}
onChange={(event) => library.filter({ query: event.target.value })} onChange={(event) => library.filter({ query: event.target.value })}
placeholder={t('tours.library.search')} placeholder={t('tours.library.search')}
@@ -1,9 +1,10 @@
import { Check, MapPinned, Search, X } from 'lucide-react'; import { Check, MapPinned, Search, X } from 'lucide-react';
import { useId, useMemo, useState } from 'react'; import { useId, useMemo, useState, type KeyboardEvent } from 'react';
import { useTranslation } from '../../../i18n'; import { useTranslation } from '../../../i18n';
import { useSettingsStore } from '../../../store/settingsStore'; import { useSettingsStore } from '../../../store/settingsStore';
import { formatDistance } from '../../../utils/units'; import { formatDistance } from '../../../utils/units';
import { SoftPill } from '../../Planner/planParts'; import { SoftPill } from '../../Planner/planParts';
import { focusRevealedEditor } from '../../shared/dialogFocus';
import { fs } from '../../shared/DialogShell'; import { fs } from '../../shared/DialogShell';
import PlaceAvatar from '../../shared/PlaceAvatar'; import PlaceAvatar from '../../shared/PlaceAvatar';
import { NEAR_TOUR_M, type TripPlaceCandidate, type TripPlaceWaypoints } from './useTripPlaceWaypoints'; import { NEAR_TOUR_M, type TripPlaceCandidate, type TripPlaceWaypoints } from './useTripPlaceWaypoints';
@@ -16,10 +17,12 @@ function distanceLabel(metres: number, unit: 'metric' | 'imperial'): string {
function CandidateRow({ function CandidateRow({
candidate, candidate,
onPick, onPick,
onDismissKey,
unit, unit,
}: { }: {
candidate: TripPlaceCandidate; candidate: TripPlaceCandidate;
onPick: () => void; onPick: () => void;
onDismissKey: (event: KeyboardEvent<HTMLElement>) => void;
unit: 'metric' | 'imperial'; unit: 'metric' | 'imperial';
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -29,6 +32,7 @@ function CandidateRow({
<button <button
type="button" type="button"
onClick={onPick} onClick={onPick}
onKeyDown={onDismissKey}
disabled={used} disabled={used}
data-testid="trip-place-candidate" data-testid="trip-place-candidate"
className="flex w-full items-center gap-2.5 rounded-[10px] px-2 py-1.5 text-start transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent enabled:hover:bg-surface-hover disabled:cursor-default" className="flex w-full items-center gap-2.5 rounded-[10px] px-2 py-1.5 text-start transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent enabled:hover:bg-surface-hover disabled:cursor-default"
@@ -62,11 +66,13 @@ function CandidateRow({
function CandidateGroup({ function CandidateGroup({
title, title,
candidates, candidates,
onDismissKey,
picker, picker,
unit, unit,
}: { }: {
title: string; title: string;
candidates: TripPlaceCandidate[]; candidates: TripPlaceCandidate[];
onDismissKey: (event: KeyboardEvent<HTMLElement>) => void;
picker: TripPlaceWaypoints; picker: TripPlaceWaypoints;
unit: 'metric' | 'imperial'; unit: 'metric' | 'imperial';
}) { }) {
@@ -86,6 +92,7 @@ function CandidateGroup({
candidate={candidate} candidate={candidate}
unit={unit} unit={unit}
onPick={() => picker.add(candidate.place)} onPick={() => picker.add(candidate.place)}
onDismissKey={onDismissKey}
/> />
))} ))}
</ul> </ul>
@@ -114,17 +121,16 @@ export function TripPlacePicker({ picker, onClose }: { picker: TripPlaceWaypoint
}, [picker.candidates, query]); }, [picker.candidates, query]);
const near = matches.filter((candidate) => candidate.distanceM != null && candidate.distanceM <= NEAR_TOUR_M); const near = matches.filter((candidate) => candidate.distanceM != null && candidate.distanceM <= NEAR_TOUR_M);
const further = matches.filter((candidate) => !near.includes(candidate)); const further = matches.filter((candidate) => !near.includes(candidate));
const onDismissKey = (event: KeyboardEvent<HTMLElement>) => {
if (event.key !== 'Escape') return;
event.stopPropagation();
onClose();
};
return ( return (
<div <div
data-testid="trip-place-picker" data-testid="trip-place-picker"
className="mt-1.5 overflow-hidden rounded-[12px] bg-surface-card shadow-sm ring-1 ring-inset ring-edge-faint" className="mt-1.5 overflow-hidden rounded-[12px] bg-surface-card shadow-sm ring-1 ring-inset ring-edge-faint"
onKeyDown={(event) => {
if (event.key === 'Escape') {
event.stopPropagation();
onClose();
}
}}
> >
<div className="flex items-center gap-2 border-b border-edge-faint px-2.5 py-2"> <div className="flex items-center gap-2 border-b border-edge-faint px-2.5 py-2">
<Search size={13} strokeWidth={2.2} className="flex-none text-content-faint" /> <Search size={13} strokeWidth={2.2} className="flex-none text-content-faint" />
@@ -133,9 +139,10 @@ export function TripPlacePicker({ picker, onClose }: { picker: TripPlaceWaypoint
</label> </label>
<input <input
id={searchId} id={searchId}
autoFocus ref={focusRevealedEditor}
value={query} value={query}
onChange={(event) => setQuery(event.target.value)} onChange={(event) => setQuery(event.target.value)}
onKeyDown={onDismissKey}
placeholder={t('tours.placePicker.search')} placeholder={t('tours.placePicker.search')}
className="min-w-0 flex-1 border-0 bg-transparent text-content outline-none placeholder:text-content-faint" className="min-w-0 flex-1 border-0 bg-transparent text-content outline-none placeholder:text-content-faint"
style={fs(12.5, 'body')} style={fs(12.5, 'body')}
@@ -143,6 +150,7 @@ export function TripPlacePicker({ picker, onClose }: { picker: TripPlaceWaypoint
<button <button
type="button" type="button"
onClick={onClose} onClick={onClose}
onKeyDown={onDismissKey}
aria-label={t('common.close')} aria-label={t('common.close')}
className="grid h-6 w-6 flex-none place-items-center rounded-full text-content-faint transition-colors hover:bg-surface-hover hover:text-content" className="grid h-6 w-6 flex-none place-items-center rounded-full text-content-faint transition-colors hover:bg-surface-hover hover:text-content"
> >
@@ -161,10 +169,17 @@ export function TripPlacePicker({ picker, onClose }: { picker: TripPlaceWaypoint
</p> </p>
) : ( ) : (
<> <>
<CandidateGroup title={t('tours.placePicker.near')} candidates={near} picker={picker} unit={unit} /> <CandidateGroup
title={t('tours.placePicker.near')}
candidates={near}
picker={picker}
unit={unit}
onDismissKey={onDismissKey}
/>
<CandidateGroup <CandidateGroup
title={near.length > 0 ? t('tours.placePicker.further') : t('tours.placePicker.all')} title={near.length > 0 ? t('tours.placePicker.further') : t('tours.placePicker.all')}
candidates={further} candidates={further}
onDismissKey={onDismissKey}
picker={picker} picker={picker}
unit={unit} unit={unit}
/> />
@@ -119,7 +119,7 @@ describe('TripPlacePicker (PR1-10)', () => {
expect(screen.getAllByTestId('trip-place-candidate')).toHaveLength(1); expect(screen.getAllByTestId('trip-place-candidate')).toHaveLength(1);
fireEvent.change(screen.getByPlaceholderText('tours.placePicker.search'), { target: { value: 'zzz' } }); fireEvent.change(screen.getByPlaceholderText('tours.placePicker.search'), { target: { value: 'zzz' } });
expect(screen.getByText('tours.placePicker.noMatch')).toBeInTheDocument(); expect(screen.getByText('tours.placePicker.noMatch')).toBeInTheDocument();
fireEvent.keyDown(screen.getByTestId('trip-place-picker'), { key: 'Escape' }); fireEvent.keyDown(screen.getByPlaceholderText('tours.placePicker.search'), { key: 'Escape' });
expect(onClose).toHaveBeenCalled(); expect(onClose).toHaveBeenCalled();
}); });
@@ -75,7 +75,6 @@ function TrailSearch({ browser }: { browser: WandererBrowser }) {
<input <input
value={browser.query} value={browser.query}
onChange={(event) => browser.setQuery(event.target.value)} onChange={(event) => browser.setQuery(event.target.value)}
autoFocus
placeholder={t('wanderer.browser.searchPlaceholder')} placeholder={t('wanderer.browser.searchPlaceholder')}
aria-label={t('wanderer.browser.searchPlaceholder')} aria-label={t('wanderer.browser.searchPlaceholder')}
className="min-w-0 flex-1 border-0 bg-transparent text-content outline-none placeholder:text-content-faint" className="min-w-0 flex-1 border-0 bg-transparent text-content outline-none placeholder:text-content-faint"
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { useId, useState, type ComponentProps, type ReactNode } from 'react' import { useId, useState, type ComponentProps, type ReactNode } from 'react'
import { Check, Copy, Crown, Link2, LogOut, Pencil, Plus, Puzzle, Settings, Trash2, UserMinus, UserPlus, UserRound, Users } from 'lucide-react' import { Check, Copy, Crown, Link2, LogOut, Pencil, Plus, Puzzle, Settings, Trash2, UserMinus, UserPlus, UserRound, Users } from 'lucide-react'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
@@ -328,7 +329,7 @@ function GuestsList({ m, onAsk }: { m: TripMembersState; onAsk: (ask: Ask) => vo
<TripMemberAvatar username={g.username} avatarUrl={null} /> <TripMemberAvatar username={g.username} avatarUrl={null} />
{m.renamingGuestId === g.id ? ( {m.renamingGuestId === g.id ? (
<input <input
autoFocus ref={focusRevealedEditor}
value={m.renameValue} value={m.renameValue}
onChange={e => m.setRenameValue(e.target.value)} onChange={e => m.setRenameValue(e.target.value)}
onKeyDown={e => { onKeyDown={e => {
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from './dialogFocus';
import { Calendar, ChevronLeft, ChevronRight, Keyboard } from 'lucide-react'; import { Calendar, ChevronLeft, ChevronRight, Keyboard } from 'lucide-react';
import { localIsoDate } from '../../utils/localDate'; import { localIsoDate } from '../../utils/localDate';
import React, { useEffect, useRef, useState } from 'react'; import React, { useEffect, useRef, useState } from 'react';
@@ -269,7 +270,7 @@ export function CustomDatePicker({
<div ref={ref} style={{ position: 'relative', ...style }}> <div ref={ref} style={{ position: 'relative', ...style }}>
{isTyping ? ( {isTyping ? (
<input <input
autoFocus ref={focusRevealedEditor}
type="text" type="text"
value={textInput} value={textInput}
onChange={(e) => setTextInput(e.target.value)} onChange={(e) => setTextInput(e.target.value)}
+2 -2
View File
@@ -4,7 +4,7 @@ import { Trash2, X } from 'lucide-react'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
import { lockBodyScroll } from '../../utils/bodyScrollLock' import { lockBodyScroll } from '../../utils/bodyScrollLock'
import { Tooltip } from './Tooltip' import { Tooltip } from './Tooltip'
import { focusDialog, trapTab } from './dialogFocus' import { focusDialog, focusRevealedEditor, trapTab } from './dialogFocus'
import { useDiscardGuard } from './useDiscardGuard' import { useDiscardGuard } from './useDiscardGuard'
/** A font size that follows the user's text size setting for its tier. */ /** A font size that follows the user's text size setting for its tier. */
@@ -252,7 +252,7 @@ export function DialogHeader(p: DialogHeaderProps) {
onBlur={f.onBlur} onBlur={f.onBlur}
aria-label={f.label} aria-label={f.label}
placeholder={f.placeholder} placeholder={f.placeholder}
autoFocus={f.autoFocus} ref={f.autoFocus ? focusRevealedEditor : undefined}
required={f.required} required={f.required}
maxLength={f.maxLength} maxLength={f.maxLength}
className="-mx-2 block w-[calc(100%+16px)] rounded-[10px] border-0 bg-transparent px-2 py-0.5 font-bold tracking-[-0.01em] text-content outline-none placeholder:font-semibold placeholder:text-content-faint hover:bg-surface-card focus:bg-surface-card focus:shadow-sm dark:bg-transparent dark:hover:bg-surface-card dark:focus:bg-surface-card" className="-mx-2 block w-[calc(100%+16px)] rounded-[10px] border-0 bg-transparent px-2 py-0.5 font-bold tracking-[-0.01em] text-content outline-none placeholder:font-semibold placeholder:text-content-faint hover:bg-surface-card focus:bg-surface-card focus:shadow-sm dark:bg-transparent dark:hover:bg-surface-card dark:focus:bg-surface-card"
@@ -16,7 +16,7 @@ describe('resolvePluginIcon', () => {
}) })
// A manifest must not be able to reach lucide's non-icon exports. // A manifest must not be able to reach lucide's non-icon exports.
it.each(['icons', 'createLucideIcon', 'default', 'module.exports'])( it.each(['icons', 'createLucideIcon', 'default', 'module.exports', 'Icon', 'LucideProvider'])(
'falls back to Blocks for the non-icon export %s', 'falls back to Blocks for the non-icon export %s',
(name) => expect(resolvePluginIcon(name)).toBe(Blocks), (name) => expect(resolvePluginIcon(name)).toBe(Blocks),
) )
@@ -32,6 +32,13 @@ describe('PluginIcon', () => {
expect(container.querySelector('.lucide-stethoscope')).not.toBeNull() expect(container.querySelector('.lucide-stethoscope')).not.toBeNull()
}) })
it('renders removed icon names and aliases stored by earlier versions', () => {
const { container } = render(<PluginIcon name="GithubIcon" />)
expect(container.querySelector('.lucide-github')).not.toBeNull()
expect(resolvePluginIcon('LucideGithub')).toBe(resolvePluginIcon('Github'))
expect(resolvePluginIcon('RailSymbol')).not.toBe(Blocks)
})
it('renders Blocks when the plugin declares nothing', () => { it('renders Blocks when the plugin declares nothing', () => {
const { container } = render(<PluginIcon name={null} />) const { container } = render(<PluginIcon name={null} />)
expect(container.querySelector('.lucide-blocks')).not.toBeNull() expect(container.querySelector('.lucide-blocks')).not.toBeNull()
+2 -9
View File
@@ -1,11 +1,6 @@
import type { CSSProperties } from 'react' import type { CSSProperties } from 'react'
import * as LucideIcons from 'lucide-react'
import { Blocks, type LucideIcon } from 'lucide-react' import { Blocks, type LucideIcon } from 'lucide-react'
import { lucideIconByName } from './lucideIconLookup'
// Lucide names are PascalCase. Restricting the lookup to that shape keeps a manifest
// from reaching lucide's non-icon exports (`createLucideIcon`, `icons`, `default`,
// `module.exports`), which are all lowercase-initial.
const LUCIDE_ICON_NAME = /^[A-Z][A-Za-z0-9]*$/
/** /**
* Resolves a plugin manifest's `icon` (a lucide icon name, e.g. "Stethoscope") to the * Resolves a plugin manifest's `icon` (a lucide icon name, e.g. "Stethoscope") to the
@@ -17,9 +12,7 @@ const LUCIDE_ICON_NAME = /^[A-Z][A-Za-z0-9]*$/
* building nav/tab arrays. * building nav/tab arrays.
*/ */
export function resolvePluginIcon(name: string | null | undefined): LucideIcon { export function resolvePluginIcon(name: string | null | undefined): LucideIcon {
if (!name || !LUCIDE_ICON_NAME.test(name)) return Blocks return lucideIconByName[name ?? ''] ?? Blocks
const icon = (LucideIcons as unknown as Record<string, LucideIcon | undefined>)[name]
return icon ?? Blocks
} }
/** Renders the lucide icon a plugin declares in its manifest (Blocks if unknown). */ /** Renders the lucide icon a plugin declares in its manifest (Blocks if unknown). */
@@ -43,6 +43,11 @@ function typingDevice(): boolean {
return window.matchMedia('(pointer: fine)').matches && !isPhoneViewport() return window.matchMedia('(pointer: fine)').matches && !isPhoneViewport()
} }
/** Give focus to a field revealed by an explicit edit or search action. */
export function focusRevealedEditor(element: HTMLElement | null): void {
element?.focus({ preventScroll: true })
}
/** /**
* Puts the focus into a dialog that just opened, unless something inside already * Puts the focus into a dialog that just opened, unless something inside already
* took it (a field with autoFocus, a dialog's own choice). The panel itself is * took it (a field with autoFocus, a dialog's own choice). The panel itself is
@@ -0,0 +1,158 @@
{
"Chrome": {
"name": "chromium",
"node": [
["path",{"d":"M10.88 21.94 15.46 14","key":"xkve6t"}],
["path",{"d":"M21.17 8H12","key":"19dcdn"}],
["path",{"d":"M3.95 6.06 8.54 14","key":"g8jz9m"}],
["circle",{"cx":"12","cy":"12","r":"10","key":"1mglay"}],
["circle",{"cx":"12","cy":"12","r":"4","key":"4exip2"}]
]
},
"Chromium": {
"name": "chromium",
"node": [
["path",{"d":"M10.88 21.94 15.46 14","key":"xkve6t"}],
["path",{"d":"M21.17 8H12","key":"19dcdn"}],
["path",{"d":"M3.95 6.06 8.54 14","key":"g8jz9m"}],
["circle",{"cx":"12","cy":"12","r":"10","key":"1mglay"}],
["circle",{"cx":"12","cy":"12","r":"4","key":"4exip2"}]
]
},
"Codepen": {
"name": "codepen",
"node": [
["polygon",{"points":"12 2 22 8.5 22 15.5 12 22 2 15.5 2 8.5 12 2","key":"srzb37"}],
["line",{"x1":"12","x2":"12","y1":"22","y2":"15.5","key":"1t73f2"}],
["polyline",{"points":"22 8.5 12 15.5 2 8.5","key":"ajlxae"}],
["polyline",{"points":"2 15.5 12 8.5 22 15.5","key":"susrui"}],
["line",{"x1":"12","x2":"12","y1":"2","y2":"8.5","key":"2cldga"}]
]
},
"Codesandbox": {
"name": "codesandbox",
"node": [
["path",{"d":"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z","key":"yt0hxn"}],
["polyline",{"points":"7.5 4.21 12 6.81 16.5 4.21","key":"fabo96"}],
["polyline",{"points":"7.5 19.79 7.5 14.6 3 12","key":"z377f1"}],
["polyline",{"points":"21 12 16.5 14.6 16.5 19.79","key":"9nrev1"}],
["polyline",{"points":"3.27 6.96 12 12.01 20.73 6.96","key":"1180pa"}],
["line",{"x1":"12","x2":"12","y1":"22.08","y2":"12","key":"3z3uq6"}]
]
},
"Dribbble": {
"name": "dribbble",
"node": [
["circle",{"cx":"12","cy":"12","r":"10","key":"1mglay"}],
["path",{"d":"M19.13 5.09C15.22 9.14 10 10.44 2.25 10.94","key":"hpej1"}],
["path",{"d":"M21.75 12.84c-6.62-1.41-12.14 1-16.38 6.32","key":"1tr44o"}],
["path",{"d":"M8.56 2.75c4.37 6 6 9.42 8 17.72","key":"kbh691"}]
]
},
"Facebook": {
"name": "facebook",
"node": [
["path",{"d":"M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z","key":"1jg4f8"}]
]
},
"Figma": {
"name": "figma",
"node": [
["path",{"d":"M5 5.5A3.5 3.5 0 0 1 8.5 2H12v7H8.5A3.5 3.5 0 0 1 5 5.5z","key":"1340ok"}],
["path",{"d":"M12 2h3.5a3.5 3.5 0 1 1 0 7H12V2z","key":"1hz3m3"}],
["path",{"d":"M12 12.5a3.5 3.5 0 1 1 7 0 3.5 3.5 0 1 1-7 0z","key":"1oz8n2"}],
["path",{"d":"M5 19.5A3.5 3.5 0 0 1 8.5 16H12v3.5a3.5 3.5 0 1 1-7 0z","key":"1ff65i"}],
["path",{"d":"M5 12.5A3.5 3.5 0 0 1 8.5 9H12v7H8.5A3.5 3.5 0 0 1 5 12.5z","key":"pdip6e"}]
]
},
"Framer": {
"name": "framer",
"node": [
["path",{"d":"M5 16V9h14V2H5l14 14h-7m-7 0 7 7v-7m-7 0h7","key":"1a2nng"}]
]
},
"Github": {
"name": "github",
"node": [
["path",{"d":"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4","key":"tonef"}],
["path",{"d":"M9 18c-4.51 2-5-2-7-2","key":"9comsn"}]
]
},
"Gitlab": {
"name": "gitlab",
"node": [
["path",{"d":"m22 13.29-3.33-10a.42.42 0 0 0-.14-.18.38.38 0 0 0-.22-.11.39.39 0 0 0-.23.07.42.42 0 0 0-.14.18l-2.26 6.67H8.32L6.1 3.26a.42.42 0 0 0-.1-.18.38.38 0 0 0-.26-.08.39.39 0 0 0-.23.07.42.42 0 0 0-.14.18L2 13.29a.74.74 0 0 0 .27.83L12 21l9.69-6.88a.71.71 0 0 0 .31-.83Z","key":"148pdi"}]
]
},
"Instagram": {
"name": "instagram",
"node": [
["rect",{"width":"20","height":"20","x":"2","y":"2","rx":"5","ry":"5","key":"2e1cvw"}],
["path",{"d":"M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z","key":"9exkf1"}],
["line",{"x1":"17.5","x2":"17.51","y1":"6.5","y2":"6.5","key":"r4j83e"}]
]
},
"Linkedin": {
"name": "linkedin",
"node": [
["path",{"d":"M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z","key":"c2jq9f"}],
["rect",{"width":"4","height":"12","x":"2","y":"9","key":"mk3on5"}],
["circle",{"cx":"4","cy":"4","r":"2","key":"bt5ra8"}]
]
},
"Pocket": {
"name": "pocket",
"node": [
["path",{"d":"M20 3a2 2 0 0 1 2 2v6a1 1 0 0 1-20 0V5a2 2 0 0 1 2-2z","key":"1uodqw"}],
["path",{"d":"m8 10 4 4 4-4","key":"1mxd5q"}]
]
},
"RailSymbol": {
"name": "rail-symbol",
"node": [
["path",{"d":"M5 15h14","key":"m0yey3"}],
["path",{"d":"M5 9h14","key":"7tsvo6"}],
["path",{"d":"m14 20-5-5 6-6-5-5","key":"1jo42i"}]
]
},
"Slack": {
"name": "slack",
"node": [
["rect",{"width":"3","height":"8","x":"13","y":"2","rx":"1.5","key":"diqz80"}],
["path",{"d":"M19 8.5V10h1.5A1.5 1.5 0 1 0 19 8.5","key":"183iwg"}],
["rect",{"width":"3","height":"8","x":"8","y":"14","rx":"1.5","key":"hqg7r1"}],
["path",{"d":"M5 15.5V14H3.5A1.5 1.5 0 1 0 5 15.5","key":"76g71w"}],
["rect",{"width":"8","height":"3","x":"14","y":"13","rx":"1.5","key":"1kmz0a"}],
["path",{"d":"M15.5 19H14v1.5a1.5 1.5 0 1 0 1.5-1.5","key":"jc4sz0"}],
["rect",{"width":"8","height":"3","x":"2","y":"8","rx":"1.5","key":"1omvl4"}],
["path",{"d":"M8.5 5H10V3.5A1.5 1.5 0 1 0 8.5 5","key":"16f3cl"}]
]
},
"Trello": {
"name": "trello",
"node": [
["rect",{"width":"18","height":"18","x":"3","y":"3","rx":"2","ry":"2","key":"1m3agn"}],
["rect",{"width":"3","height":"9","x":"7","y":"7","key":"14n3xi"}],
["rect",{"width":"3","height":"5","x":"14","y":"7","key":"s4azjd"}]
]
},
"Twitch": {
"name": "twitch",
"node": [
["path",{"d":"M21 2H3v16h5v4l4-4h5l4-4V2zm-10 9V7m5 4V7","key":"c0yzno"}]
]
},
"Twitter": {
"name": "twitter",
"node": [
["path",{"d":"M22 4s-.7 2.1-2 3.4c1.6 10-9.4 17.3-18 11.6 2.2.1 4.4-.6 6-2C3 15.5.5 9.6 3 5c2.2 2.6 5.6 4.1 9 4-.9-4.2 4-6.6 7-3.8 1.1 0 3-1.2 3-1.2z","key":"pff0z6"}]
]
},
"Youtube": {
"name": "youtube",
"node": [
["path",{"d":"M2.5 17a24.12 24.12 0 0 1 0-10 2 2 0 0 1 1.4-1.4 49.56 49.56 0 0 1 16.2 0A2 2 0 0 1 21.5 7a24.12 24.12 0 0 1 0 10 2 2 0 0 1-1.4 1.4 49.55 49.55 0 0 1-16.2 0A2 2 0 0 1 2.5 17","key":"1q2vi4"}],
["path",{"d":"m10 15 5-3-5-3z","key":"1jp15x"}]
]
}
}
@@ -0,0 +1,53 @@
/*!
* Glyphs from lucide-react 0.577.0 for icons removed in Lucide 1.
*
* ISC License
*
* Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2026 as part of Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2026.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* ---
*
* The MIT License (MIT) (for portions derived from Feather)
*
* Copyright (c) 2013-2026 Cole Bemis
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { createLucideIcon, type LucideIcon, type LucideIconData } from 'lucide-react';
import legacyIcons from './legacy-lucide-icons.json';
const icons = Object.fromEntries(
Object.entries(legacyIcons).map(([name, data]) => [name, createLucideIcon(data as LucideIconData)])
) as Record<keyof typeof legacyIcons, LucideIcon>;
export const legacyLucideIcons = new Map<string, LucideIcon>(Object.entries(icons));
export const Github = icons.Github;
@@ -0,0 +1,28 @@
import type { LucideIcon } from 'lucide-react';
import * as LucideIcons from 'lucide-react';
import { legacyLucideIcons } from './legacyLucideIcons';
const icons = Object.create(null) as Record<string, LucideIcon | undefined>;
const forwardRef = Symbol.for('react.forward_ref');
for (const [name, component] of Object.entries<unknown>(LucideIcons)) {
if (
/^[A-Z][A-Za-z0-9]*$/.test(name) &&
name !== 'Icon' &&
typeof component === 'object' &&
component !== null &&
'$$typeof' in component &&
component.$$typeof === forwardRef
) {
icons[name] = component as LucideIcon;
}
}
for (const [name, component] of legacyLucideIcons) {
icons[name] ??= component;
icons[`Lucide${name}`] ??= component;
icons[`${name}Icon`] ??= component;
}
export const lucideIconByName: Readonly<typeof icons> = icons;
+1 -1
View File
@@ -159,7 +159,7 @@ export default function MDayPager({
// Still between pages: the snap has not finished, another event follows. // Still between pages: the snap has not finished, another event follows.
if (!resting || resting.hasAttribute('data-page-active')) return; if (!resting || resting.hasAttribute('data-page-active')) return;
const raw = resting.dataset.dayId; const raw = resting.dataset.dayId;
const dayId = raw ? Number(raw) : NaN; const dayId = raw ? Number(raw) : Number.NaN;
if (!Number.isFinite(dayId) || requested.current === dayId) return; if (!Number.isFinite(dayId) || requested.current === dayId) return;
requested.current = dayId; requested.current = dayId;
previewed = null; previewed = null;
+1 -1
View File
@@ -72,7 +72,7 @@ function useEvenLines(listRef: RefObject<HTMLDivElement | null>) {
const measure = () => { const measure = () => {
list.style.setProperty('--m-rail-lines', '1'); list.style.setProperty('--m-rail-lines', '1');
const two = names().some((el) => { const two = names().some((el) => {
const line = parseFloat(getComputedStyle(el).lineHeight) || 0; const line = Number.parseFloat(getComputedStyle(el).lineHeight) || 0;
return line > 0 && el.scrollHeight > line * 1.5; return line > 0 && el.scrollHeight > line * 1.5;
}); });
list.style.setProperty('--m-rail-lines', two ? '2' : '1'); list.style.setProperty('--m-rail-lines', two ? '2' : '1');
@@ -212,7 +212,7 @@ export default function MascotClip({
> >
<canvas <canvas
ref={canvasRef} ref={canvasRef}
aria-hidden inert
className="pointer-events-none absolute" className="pointer-events-none absolute"
style={{ style={{
left: `${x * 100}%` /* rtl-lint-disable: the crop sits where the frame was cut, video is never mirrored */, left: `${x * 100}%` /* rtl-lint-disable: the crop sits where the frame was cut, video is never mirrored */,
@@ -224,25 +224,25 @@ export default function MascotClip({
<video <video
key={loopUrl} key={loopUrl}
ref={loopRef} ref={loopRef}
inert
src={loopUrl} src={loopUrl}
autoPlay autoPlay
loop loop
muted muted
playsInline playsInline
disablePictureInPicture disablePictureInPicture
aria-hidden
style={HIDDEN_VIDEO} style={HIDDEN_VIDEO}
/> />
{pokeUrl && ( {pokeUrl && (
<video <video
key={pokeUrl} key={pokeUrl}
ref={pokeRef} ref={pokeRef}
inert
src={pokeUrl} src={pokeUrl}
muted muted
playsInline playsInline
preload="auto" preload="auto"
disablePictureInPicture disablePictureInPicture
aria-hidden
style={HIDDEN_VIDEO} style={HIDDEN_VIDEO}
/> />
)} )}
@@ -23,7 +23,6 @@ export default function MAdminCategoryManager() {
onChange={e => setForm(prev => ({ ...prev, name: e.target.value }))} onChange={e => setForm(prev => ({ ...prev, name: e.target.value }))}
placeholder={t('categories.namePlaceholder')} placeholder={t('categories.namePlaceholder')}
className="h-[42px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] px-3 text-[0.84375rem] text-m-ink outline-none placeholder:text-m-faint focus:border-[color:var(--m-faint)]" className="h-[42px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] px-3 text-[0.84375rem] text-m-ink outline-none placeholder:text-m-faint focus:border-[color:var(--m-faint)]"
autoFocus
/> />
<div> <div>
@@ -1,8 +1,9 @@
import { useState } from 'react' import { useState } from 'react'
import { useFormatDate } from '../../../hooks/useDateFormat' import { useFormatDate } from '../../../hooks/useDateFormat'
import MPluginVersionDate from './MPluginVersionDate' import MPluginVersionDate from './MPluginVersionDate'
import { Blocks, AlertTriangle, PackageOpen, RefreshCw, Trash2, Download, Bug, X, ShieldCheck, UploadCloud, ArrowUpCircle, Github, ExternalLink, ChevronDown, Check, Lock, Search, Link2, KeyRound, ShieldAlert, SlidersHorizontal, ArrowUpDown, CircleDot, MoreHorizontal, RotateCw, Database, Globe, Info, History, PauseCircle, Puzzle, Bot, ListChecks } from 'lucide-react' import { Blocks, AlertTriangle, PackageOpen, RefreshCw, Trash2, Download, Bug, X, ShieldCheck, UploadCloud, ArrowUpCircle, ExternalLink, ChevronDown, Check, Lock, Search, Link2, KeyRound, ShieldAlert, SlidersHorizontal, ArrowUpDown, CircleDot, MoreHorizontal, RotateCw, Database, Globe, Info, History, PauseCircle, Puzzle, Bot, ListChecks } from 'lucide-react'
import PluginIcon from '../../../components/shared/PluginIcon' import PluginIcon from '../../../components/shared/PluginIcon'
import { Github } from '../../../components/shared/legacyLucideIcons'
import { type RangeWarning } from '../../../components/Admin/useRangeBypass' import { type RangeWarning } from '../../../components/Admin/useRangeBypass'
import { deriveCaps } from '../../../components/Admin/pluginCaps' import { deriveCaps } from '../../../components/Admin/pluginCaps'
import PluginPoiCategoryList from '../../../components/Admin/PluginPoiCategoryList' import PluginPoiCategoryList from '../../../components/Admin/PluginPoiCategoryList'
@@ -100,7 +100,13 @@ export default function MCollEditSheet({ target, onClose, onCreated, onRequestDe
className="relative h-20 overflow-hidden rounded-[10px] border border-[color:var(--m-rowbr)]" className="relative h-20 overflow-hidden rounded-[10px] border border-[color:var(--m-rowbr)]"
style={coverPreview === photo.url ? { boxShadow: 'inset 0 0 0 2px var(--m-act)' } : undefined} style={coverPreview === photo.url ? { boxShadow: 'inset 0 0 0 2px var(--m-act)' } : undefined}
> >
<img src={photo.thumb} alt={photo.description || ''} loading="lazy" className="h-full w-full object-cover" /> <img
src={photo.thumb}
alt={photo.description || ''}
title={photo.description || undefined}
loading="lazy"
className="h-full w-full object-cover"
/>
{photo.photographer && ( {photo.photographer && (
<span className={PHOTO_CREDIT}> <span className={PHOTO_CREDIT}>
{photo.photographer} {photo.photographer}
@@ -4,6 +4,7 @@ import Markdown from 'react-markdown';
import remarkBreaks from 'remark-breaks'; import remarkBreaks from 'remark-breaks';
import remarkGfm from 'remark-gfm'; import remarkGfm from 'remark-gfm';
import { useOriginNotes } from '../../../components/Collections/useOriginNotes'; import { useOriginNotes } from '../../../components/Collections/useOriginNotes';
import { focusRevealedEditor } from '../../../components/shared/dialogFocus';
import { markdownLinkComponents } from '../../../components/shared/markdownLink'; import { markdownLinkComponents } from '../../../components/shared/markdownLink';
import type { TranslationFn } from '../../../types'; import type { TranslationFn } from '../../../types';
import { CancelPill, PrimaryPill } from './MCollSheetKit'; import { CancelPill, PrimaryPill } from './MCollSheetKit';
@@ -96,7 +97,7 @@ function MNoteEditor({ n, t }: { n: Notes; t: TranslationFn }) {
</div> </div>
) : ( ) : (
<textarea <textarea
autoFocus ref={focusRevealedEditor}
rows={6} rows={6}
value={n.draft} value={n.draft}
onChange={(e) => n.setDraft(e.target.value)} onChange={(e) => n.setDraft(e.target.value)}

Some files were not shown because too many files have changed in this diff Show More