mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 07:30:04 +00:00
add Google Maps route import and plugin corridor search
This commit is contained in:
@@ -70,5 +70,7 @@ export interface Poi {
|
||||
capacity: number | null
|
||||
fee: boolean | null
|
||||
} | null
|
||||
source: 'openstreetmap'
|
||||
source: string
|
||||
pluginId?: string
|
||||
rating?: number | null
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import React from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { TranslationProvider } from '../../i18n'
|
||||
import GoogleRouteImport from './GoogleRouteImport'
|
||||
import { googleRouteRepo } from '../../repo/googleRouteRepo'
|
||||
|
||||
const { loadTrip, state } = vi.hoisted(() => ({ loadTrip: vi.fn(), state: { days: [{ id: 3, day_number: 1, title: 'First day' }] } }))
|
||||
vi.mock('../../store/tripStore', () => ({ useTripStore: Object.assign((select: (s: typeof state) => unknown) => select(state), { getState: () => ({ loadTrip }) }) }))
|
||||
vi.mock('../../repo/googleRouteRepo', () => ({ googleRouteRepo: { preview: vi.fn(), append: vi.fn() } }))
|
||||
|
||||
async function openPreview() {
|
||||
render(<TranslationProvider><GoogleRouteImport tripId={1} dayId={3} /></TranslationProvider>)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Import Google Maps route' }))
|
||||
fireEvent.click(screen.getByText('Import Google Maps route', { selector: 'span' }))
|
||||
fireEvent.change(screen.getByRole('textbox', { name: 'Google Maps URL' }), { target: { value: 'https://google.com/maps/dir/A/B' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Preview', exact: true }))
|
||||
await screen.findByText('Munich')
|
||||
}
|
||||
|
||||
describe('Google route preview', () => {
|
||||
beforeEach(() => { vi.clearAllMocks(); loadTrip.mockResolvedValue(undefined) })
|
||||
|
||||
it('previews in order and only saves resolved stops after confirmation', async () => {
|
||||
vi.mocked(googleRouteRepo.preview).mockResolvedValue({ stops: [{ name: 'Munich', lat: 48, lng: 11 }, { name: 'Unknown', lat: null, lng: null }, { name: 'Rome', lat: 41, lng: 12 }] })
|
||||
vi.mocked(googleRouteRepo.append).mockResolvedValue(undefined)
|
||||
await openPreview()
|
||||
expect(screen.getAllByRole('listitem').map(item => item.textContent)).toEqual([expect.stringContaining('Munich'), expect.stringContaining('Unknown'), expect.stringContaining('Rome')])
|
||||
expect(screen.getByText('Location unresolved; this stop will be skipped.')).toBeInTheDocument()
|
||||
expect(googleRouteRepo.append).not.toHaveBeenCalled()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Import', exact: true }))
|
||||
await waitFor(() => expect(loadTrip).toHaveBeenCalledWith(1))
|
||||
expect(googleRouteRepo.append).toHaveBeenCalledWith(1, { dayId: 3, stops: [{ name: 'Munich', lat: 48, lng: 11 }, { name: 'Rome', lat: 41, lng: 12 }] }, expect.any(String))
|
||||
})
|
||||
|
||||
it('blocks import when fewer than two locations resolve', async () => {
|
||||
vi.mocked(googleRouteRepo.preview).mockResolvedValue({ stops: [{ name: 'Munich', lat: 48, lng: 11 }, { name: 'Unknown', lat: null, lng: null }] })
|
||||
await openPreview()
|
||||
expect(screen.getByRole('button', { name: 'Import', exact: true })).toBeDisabled()
|
||||
expect(googleRouteRepo.append).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { MoreHorizontal, Link2 } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n/TranslationContext'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { googleRouteRepo } from '../../repo/googleRouteRepo'
|
||||
import { generateUUID } from '../../sync/mutationQueue'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import type { GoogleRoutePreview } from '@trek/shared'
|
||||
import Modal from '../shared/Modal'
|
||||
import CustomSelect from '../shared/CustomSelect'
|
||||
import { ContextMenu, useContextMenu } from '../shared/ContextMenu'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
|
||||
export default function GoogleRouteImport({ tripId, dayId }: { tripId: number; dayId?: number }) {
|
||||
const { t } = useTranslation()
|
||||
const days = useTripStore(s => s.days)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [url, setUrl] = useState('')
|
||||
const [preview, setPreview] = useState<GoogleRoutePreview | null>(null)
|
||||
const [target, setTarget] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [failure, setFailure] = useState('')
|
||||
const [saved, setSaved] = useState(false)
|
||||
const controller = useRef<AbortController | null>(null)
|
||||
const requestId = useRef('')
|
||||
const menu = useContextMenu()
|
||||
useEffect(() => () => controller.current?.abort(), [])
|
||||
const inspect = async () => {
|
||||
controller.current?.abort()
|
||||
const abort = new AbortController()
|
||||
controller.current = abort
|
||||
setBusy(true); setFailure(''); setPreview(null)
|
||||
try { const parsed = await googleRouteRepo.preview(url, abort.signal); if (!abort.signal.aborted) setPreview(parsed) }
|
||||
catch (error) { if (!abort.signal.aborted) setFailure(getApiErrorMessage(error, t('common.error'))) }
|
||||
finally { if (!abort.signal.aborted) setBusy(false) }
|
||||
}
|
||||
const save = async () => {
|
||||
if (!preview || !target) return
|
||||
setBusy(true); setFailure('')
|
||||
try {
|
||||
const stops = preview.stops.filter(s => s.lat != null && s.lng != null).map(s => ({ name: s.name, lat: s.lat!, lng: s.lng! }))
|
||||
await googleRouteRepo.append(tripId, { dayId: Number(target), stops }, requestId.current)
|
||||
setSaved(true)
|
||||
await useTripStore.getState().loadTrip(tripId)
|
||||
setOpen(false)
|
||||
} catch (error) { setFailure(getApiErrorMessage(error, t('common.error'))) }
|
||||
finally { setBusy(false) }
|
||||
}
|
||||
const show = () => {
|
||||
setUrl(''); setPreview(null); setFailure(''); setSaved(false)
|
||||
setTarget(String(dayId ?? days[0]?.id ?? ''))
|
||||
requestId.current = generateUUID(); setOpen(true)
|
||||
}
|
||||
const resolved = preview?.stops.filter(s => s.lat != null && s.lng != null) ?? []
|
||||
return <>
|
||||
<Tooltip label={t('roadtrip.import.title')}>
|
||||
<button type="button" aria-label={t('roadtrip.import.title')} className="shrink-0 rounded-lg p-2 text-content-muted hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-accent"
|
||||
onClick={e => menu.open(e, [{ label: t('roadtrip.import.title'), icon: Link2, onClick: show }], true)}>
|
||||
<MoreHorizontal size={18} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<ContextMenu menu={menu.menu} onClose={menu.close} />
|
||||
<Modal isOpen={open} onClose={() => { if (!busy) setOpen(false) }} title={t('roadtrip.import.title')} size="lg">
|
||||
<div className="space-y-4">
|
||||
<p className="text-caption text-content-muted">{t('roadtrip.import.note')}</p>
|
||||
{!preview ? <input type="url" value={url} disabled={busy} onChange={e => setUrl(e.target.value)} aria-label="Google Maps URL" placeholder="https://maps.app.goo.gl/…"
|
||||
className="w-full rounded-xl border border-edge bg-surface-input p-3 text-body text-content" /> : <>
|
||||
<CustomSelect value={target} onChange={value => { setTarget(String(value)); requestId.current = generateUUID() }}
|
||||
options={days.map(day => ({ value: String(day.id), label: day.title || `${t('roadtrip.import.day')} ${day.day_number}` }))} disabled={busy || saved} />
|
||||
<ol className="max-h-64 space-y-2 overflow-auto">
|
||||
{preview.stops.map((stop, index) => <li key={index} className="flex items-baseline gap-3 text-body text-content">
|
||||
<span className="text-caption tabular-nums text-content-muted">{index + 1}</span>
|
||||
<span className="min-w-0">{stop.name}{stop.name !== `${stop.lat}, ${stop.lng}` && <span className="block text-caption text-content-muted">{stop.lat == null || stop.lng == null ? t('roadtrip.import.unresolved') : `${stop.lat.toFixed(5)}, ${stop.lng.toFixed(5)}`}</span>}</span>
|
||||
</li>)}
|
||||
</ol>
|
||||
</>}
|
||||
{failure && <p role="alert" className="text-caption text-danger">{saved ? t('common.saved') + ': ' : ''}{failure}</p>}
|
||||
<div className="flex justify-end gap-2">
|
||||
<button type="button" disabled={busy} className="rounded-lg px-3 py-2 text-body text-content-secondary" onClick={() => setOpen(false)}>{t('common.cancel')}</button>
|
||||
<button type="button" disabled={busy || saved || (!preview ? !url.trim() : resolved.length < 2 || !target)} onClick={() => void (preview ? save() : inspect())}
|
||||
className="rounded-lg bg-accent px-4 py-2 text-body font-medium text-accent-text disabled:opacity-50">
|
||||
{busy ? t('common.loading') : t(preview ? 'common.import' : 'common.preview')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</>
|
||||
}
|
||||
@@ -279,6 +279,14 @@ describe('RoadtripCorridorPanel', () => {
|
||||
expect(screen.getByText('Aral')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the plugin source and failed providers beside remaining hits', () => {
|
||||
const c = corridor({}, { failedSources: ['plugin:unavailable'], results: [poi({ osm_id: 'plugin:stations:one', name: 'Plugin Station', pluginId: 'stations' })] })
|
||||
wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
|
||||
expect(screen.getByText('Plugin Station')).toBeInTheDocument()
|
||||
expect(screen.getByText('stations')).toBeInTheDocument()
|
||||
expect(screen.getByText('Error: plugin:unavailable')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-PANEL-015: a total outage reads as a failure, not as an empty road', () => {
|
||||
const c = corridor({}, { error: true, failedAreas: 4 })
|
||||
wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import GoogleRouteImport from './GoogleRouteImport'
|
||||
import React, { useMemo, useState } from 'react'
|
||||
import {
|
||||
Search, Plus, RotateCw, AlertTriangle, X, BedDouble, MapPin, ChevronDown,
|
||||
@@ -17,6 +18,8 @@ import type { CorridorPoi } from './useCorridorPois'
|
||||
import type { RoadtripRoutes } from './useRoadtripRoutes'
|
||||
|
||||
interface RoadtripCorridorPanelProps {
|
||||
tripId?: number
|
||||
canImport?: boolean
|
||||
corridor: RoadtripCorridor
|
||||
routes: RoadtripRoutes
|
||||
/** Opens the place form prefilled from a POI, on a day and at a position in it. */
|
||||
@@ -103,6 +106,7 @@ function ResultRow({ poi, onAdd }: { poi: CorridorPoi; onAdd?: () => void }): Re
|
||||
<div className="truncate font-semibold tracking-[-0.012em] text-content" style={{ fontSize: FS.name }}>
|
||||
{poi.name}
|
||||
</div>
|
||||
{poi.pluginId && <p className="truncate text-caption text-content-muted">{poi.pluginId}</p>}
|
||||
{/* Two facts, two chips. Where it is off the road and how far into the drive it
|
||||
comes are separate answers, and as two phrases sharing a line they read as one
|
||||
run-on sentence about the same thing. A chip each gives them an edge, and the
|
||||
@@ -249,7 +253,7 @@ function ResultGroup({ category, pois, dayId, insertIndexFor, onAddPoi }: {
|
||||
* header rather than among the filters — it is the question's subject, not one of its
|
||||
* conditions.
|
||||
*/
|
||||
export default function RoadtripCorridorPanel({ corridor, routes, onAddPoi }: RoadtripCorridorPanelProps): React.ReactElement {
|
||||
export default function RoadtripCorridorPanel({ corridor, routes, onAddPoi, tripId, canImport }: RoadtripCorridorPanelProps): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
|
||||
const { search } = corridor
|
||||
@@ -299,6 +303,7 @@ export default function RoadtripCorridorPanel({ corridor, routes, onAddPoi }: Ro
|
||||
: 0
|
||||
|
||||
const warnings: [string, string][] = []
|
||||
if (search.failedSources?.length) warnings.push(['sources', `${t('common.error')}: ${search.failedSources.join(', ')}`])
|
||||
if (search.capped) warnings.push(['capped', t('roadtrip.poi.capped')])
|
||||
if (search.error) warnings.push(['failed', t('roadtrip.poi.failed')])
|
||||
// Some boxes answered and some did not. Saying so is the difference between "there is
|
||||
@@ -327,6 +332,7 @@ export default function RoadtripCorridorPanel({ corridor, routes, onAddPoi }: Ro
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{tripId && canImport && <GoogleRouteImport tripId={tripId} dayId={corridor.day?.dayId} />}
|
||||
</div>
|
||||
|
||||
{/* What to look for. */}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { LatLng } from './corridor'
|
||||
|
||||
const { pois } = vi.hoisted(() => ({ pois: vi.fn() }))
|
||||
vi.mock('../../api/client', () => ({ mapsApi: { pois } }))
|
||||
vi.mock('../../repo/roadtripSearchRepo', () => ({ roadtripSearchRepo: { search: pois } }))
|
||||
vi.mock('../../i18n', () => ({ useTranslation: () => ({ locale: 'en-US' }) }))
|
||||
|
||||
import { useCorridorPois } from './useCorridorPois'
|
||||
@@ -30,7 +30,7 @@ const hit = (id: string, lat: number, lng: number, category = 'fuel') => ({
|
||||
source: 'openstreetmap',
|
||||
})
|
||||
|
||||
const answer = (...items: ReturnType<typeof hit>[]) => ({ pois: items, source: 'openstreetmap', truncated: false, clamped: false })
|
||||
const answer = (...items: ReturnType<typeof hit>[]) => ({ pois: items, sources: ['openstreetmap'], failedSources: [], truncated: false, clamped: false })
|
||||
|
||||
beforeEach(() => {
|
||||
pois.mockReset()
|
||||
@@ -38,6 +38,14 @@ beforeEach(() => {
|
||||
})
|
||||
|
||||
describe('useCorridorPois', () => {
|
||||
it('keeps plugin results and exposes failed sources', async () => {
|
||||
pois.mockResolvedValue({ ...answer(hit('plugin:stations:1', 53.5, 9.81)), failedSources: ['plugin:unavailable'] })
|
||||
const { result } = renderHook(() => useCorridorPois(LINE, ['fuel'], 10))
|
||||
act(() => { result.current.search() })
|
||||
await waitFor(() => expect(result.current.loading).toBe(false))
|
||||
expect(result.current.results[0].osm_id).toBe('plugin:stations:1')
|
||||
expect(result.current.failedSources).toEqual(['plugin:unavailable'])
|
||||
})
|
||||
it('FE-ROADTRIP-CORRIDOR-001: asks each box once for every category together', async () => {
|
||||
const { result } = renderHook(() => useCorridorPois(LINE, ['fuel', 'charging', 'rest_area'], 10))
|
||||
act(() => { result.current.search() })
|
||||
@@ -45,7 +53,7 @@ describe('useCorridorPois', () => {
|
||||
|
||||
expect(pois).toHaveBeenCalled()
|
||||
// The whole point of the batching: the kinds ride along in one query per box.
|
||||
for (const call of pois.mock.calls) expect(call[0]).toBe('fuel,charging,rest_area')
|
||||
for (const call of pois.mock.calls) expect(call[0]).toEqual(['fuel', 'charging', 'rest_area'])
|
||||
expect(result.current.progress.total).toBe(pois.mock.calls.length)
|
||||
})
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { mapsApi } from '../../api/client'
|
||||
import { roadtripSearchRepo } from '../../repo/roadtripSearchRepo'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { corridorTiles, projectOntoRoute, simplifyLine, type Bbox, type LatLng } from './corridor'
|
||||
import type { Poi } from '../Map/poiCategories'
|
||||
@@ -18,6 +18,7 @@ export interface CorridorSearch {
|
||||
/** True when the route was longer than the request budget and the tail was left out. */
|
||||
capped: boolean
|
||||
/** Boxes the place search could not answer — a partial result is still shown. */
|
||||
failedSources?: string[]
|
||||
failedAreas: number
|
||||
/**
|
||||
* Boxes where the server hit its own per-request ceiling and dropped the rest.
|
||||
@@ -71,6 +72,7 @@ export function useCorridorPois(line: LatLng[], categories: string[], widthKm: n
|
||||
const [capped, setCapped] = useState(false)
|
||||
const [failedAreas, setFailedAreas] = useState(0)
|
||||
const [truncatedAreas, setTruncatedAreas] = useState(0)
|
||||
const [failedSources, setFailedSources] = useState<string[]>([])
|
||||
const [error, setError] = useState(false)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
const runIdRef = useRef(0)
|
||||
@@ -91,6 +93,7 @@ export function useCorridorPois(line: LatLng[], categories: string[], widthKm: n
|
||||
setProgress({ done: 0, total: 0 })
|
||||
setLoading(false)
|
||||
setCapped(false)
|
||||
setFailedSources([])
|
||||
setFailedAreas(0)
|
||||
setTruncatedAreas(0)
|
||||
setError(false)
|
||||
@@ -112,6 +115,7 @@ export function useCorridorPois(line: LatLng[], categories: string[], widthKm: n
|
||||
const tiles = allTiles.slice(0, MAX_TILES)
|
||||
|
||||
setCapped(allTiles.length > tiles.length)
|
||||
setFailedSources([])
|
||||
setFailedAreas(0)
|
||||
setTruncatedAreas(0)
|
||||
setError(false)
|
||||
@@ -122,11 +126,12 @@ export function useCorridorPois(line: LatLng[], categories: string[], widthKm: n
|
||||
// All the wanted kinds in one query per box. Asking per kind was the same answer for
|
||||
// four times the requests, and every extra request is another chance for a shared
|
||||
// mirror to time out — which is what made a search both slow and patchy.
|
||||
const wanted = categories.join(',')
|
||||
|
||||
const jobs = [...tiles]
|
||||
|
||||
void (async () => {
|
||||
const seen = new Map<string, CorridorPoi>()
|
||||
const unavailable = new Set<string>()
|
||||
let failures = 0
|
||||
let shortened = 0
|
||||
let done = 0
|
||||
@@ -139,15 +144,26 @@ export function useCorridorPois(line: LatLng[], categories: string[], widthKm: n
|
||||
// cheaply; the small gap afterwards keeps one worker from queueing straight up.
|
||||
const collect = async (tile: Bbox): Promise<boolean> => {
|
||||
try {
|
||||
const data = await mapsApi.pois(wanted, tile, locale, controller.signal)
|
||||
const data = await roadtripSearchRepo.search(categories, tile, locale, controller.signal)
|
||||
if (controller.signal.aborted || runId !== runIdRef.current) return false
|
||||
data.failedSources.forEach(source => unavailable.add(source))
|
||||
setFailedSources([...unavailable])
|
||||
// The server answers with at most a few hundred per box and says so. A hit
|
||||
// dropped there is invisible here, so the count has to reach the surface.
|
||||
if (data.truncated) setTruncatedAreas(++shortened)
|
||||
if (data.truncated || data.clamped) setTruncatedAreas(++shortened)
|
||||
for (const poi of data.pois) {
|
||||
if (seen.has(poi.osm_id)) continue
|
||||
const hit = projectOntoRoute({ lat: poi.lat, lng: poi.lng }, spine)
|
||||
if (!hit || hit.offRouteKm > widthKm) continue
|
||||
seen.set(poi.osm_id, { ...poi, offRouteKm: hit.offRouteKm, alongKm: hit.alongKm })
|
||||
seen.set(poi.osm_id, {
|
||||
...poi, address: poi.address ?? null, website: poi.website ?? null, phone: poi.phone ?? null,
|
||||
opening_hours: poi.opening_hours ?? null, cuisine: poi.cuisine ?? null,
|
||||
charging: poi.charging ? {
|
||||
capacity: poi.charging.capacity ?? null, fee: poi.charging.fee ?? null,
|
||||
sockets: poi.charging.sockets.map(s => ({ type: s.type, count: s.count ?? null, kw: s.kw ?? null })),
|
||||
} : null,
|
||||
offRouteKm: hit.offRouteKm, alongKm: hit.alongKm,
|
||||
})
|
||||
}
|
||||
return true
|
||||
} catch {
|
||||
@@ -193,5 +209,5 @@ export function useCorridorPois(line: LatLng[], categories: string[], widthKm: n
|
||||
|
||||
useEffect(() => () => abortRef.current?.abort(), [])
|
||||
|
||||
return { results, progress, loading, capped, failedAreas, truncatedAreas, error, spine, search, clear }
|
||||
return { results, progress, loading, capped, failedAreas, failedSources, truncatedAreas, error, spine, search, clear }
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect, useRef } from 'react'
|
||||
import React, { useState, useEffect, useLayoutEffect, useRef } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { LucideIcon } from 'lucide-react'
|
||||
|
||||
@@ -14,15 +14,17 @@ interface MenuState {
|
||||
x: number
|
||||
y: number
|
||||
items: MenuItem[]
|
||||
alignEnd?: boolean
|
||||
}
|
||||
|
||||
export function useContextMenu() {
|
||||
const [menu, setMenu] = useState<MenuState | null>(null)
|
||||
|
||||
const open = (e: React.MouseEvent, items: MenuItem[]) => {
|
||||
const open = (e: React.MouseEvent, items: MenuItem[], alignEnd = false) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setMenu({ x: e.clientX, y: e.clientY, items })
|
||||
const anchor = e.currentTarget.getBoundingClientRect()
|
||||
setMenu({ x: alignEnd ? anchor.right : e.clientX, y: alignEnd ? anchor.bottom + 6 : e.clientY, items, alignEnd })
|
||||
}
|
||||
|
||||
const close = () => setMenu(null)
|
||||
@@ -49,11 +51,12 @@ export function ContextMenu({ menu, onClose }: ContextMenuProps) {
|
||||
}
|
||||
}, [menu, onClose])
|
||||
|
||||
useEffect(() => {
|
||||
useLayoutEffect(() => {
|
||||
if (!menu || !ref.current) return
|
||||
const el = ref.current
|
||||
const rect = el.getBoundingClientRect()
|
||||
let { x, y } = menu
|
||||
if (menu.alignEnd) x = Math.max(8, x - rect.width)
|
||||
if (x + rect.width > window.innerWidth - 8) x = window.innerWidth - rect.width - 8
|
||||
if (y + rect.height > window.innerHeight - 8) y = window.innerHeight - rect.height - 8
|
||||
if (x !== menu.x || y !== menu.y) {
|
||||
@@ -72,8 +75,10 @@ export function ContextMenu({ menu, onClose }: ContextMenuProps) {
|
||||
boxShadow: '0 8px 30px rgba(0,0,0,0.15)',
|
||||
backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
|
||||
minWidth: 160,
|
||||
width: menu.alignEnd ? 'max-content' : undefined,
|
||||
whiteSpace: menu.alignEnd ? 'nowrap' : undefined,
|
||||
fontFamily: "var(--font-system)",
|
||||
transformOrigin: 'top left',
|
||||
transformOrigin: menu.alignEnd ? 'top right' : 'top left',
|
||||
}}>
|
||||
{menu.items.filter(Boolean).map((item, i) => {
|
||||
if (item.divider) return <div key={i} style={{ height: 1, background: 'var(--border-faint)', margin: '3px 6px' }} />
|
||||
|
||||
Reference in New Issue
Block a user