mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
feat(collections): a list as a file, so it can leave the instance (#2198)
Sharing a list works between people on the same TREK. This is the other case: giving one to somebody who runs their own, or keeping a copy. Export sits beside Edit and Share in the list header and downloads the open list; Import sits beside New list in the rail, reads a file, shows what is in it and makes a new list of it. Desktop only, which the route already decides. What travels is what somebody wrote down: the list's name, colour and description, its labels, and each place with its address, coordinates, notes, status, contact details, category name and labels. A file is dull JSON on purpose, so it can be read and edited by a person. What does not travel is everything that only means something on the instance it came from. Ids of every kind, since the receiver issues its own and a category crosses over by name. Star ratings and members, because a rating is an opinion somebody gave the people on that list. Provenance into trips, which points at rows the receiver cannot see. And an image path under /uploads, which resolves on the sender's server: only an absolute https URL survives. A file is a stranger's JSON and is read as one. It is parsed in the browser that chose it and never uploaded; the parsed list goes through the same contract on both sides; and a link that is not http(s) arrives as nothing rather than as an anchor. Strict where it must refuse, forgiving where it can drop: a file that does not say what it is never reaches the importer, while one unreadable place inside it is skipped and counted, and one bad field on a good place costs that field alone. An import is always a new list. Importing into an existing one would mean deciding what happens to a place that is already there, and every answer to that is a merge nobody asked for.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-COLHERO-001 to FE-COMP-COLHERO-011
|
||||
// FE-COMP-COLHERO-001 to FE-COMP-COLHERO-015
|
||||
import React from 'react';
|
||||
import { render, screen, within } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
@@ -160,4 +160,39 @@ describe('CollectionHero', () => {
|
||||
expect(within(share).queryByText('3')).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Share' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
// ── Export as a file (#2198) ───────────────────────────────────────────
|
||||
|
||||
it('FE-COMP-COLHERO-012: offers Export beside Edit and Share, in that order', async () => {
|
||||
const onExport = vi.fn();
|
||||
renderHero({ canEdit: true, canShare: true, isOwner: true, onExport });
|
||||
|
||||
const actions = ['Edit', 'Export', 'Share'].map(name => screen.getByRole('button', { name }));
|
||||
// Reading order in the DOM is the reading order on screen.
|
||||
const all = [...document.querySelectorAll('.col-hero-actions button')];
|
||||
expect(all).toEqual(actions);
|
||||
|
||||
await userEvent.click(actions[1]);
|
||||
expect(onExport).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-COLHERO-013: has no Export button where there is no list to export', () => {
|
||||
renderHero({ onExport: undefined });
|
||||
expect(screen.queryByRole('button', { name: 'Export' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLHERO-014: a viewer may export, since exporting reads and does not write', async () => {
|
||||
const onExport = vi.fn();
|
||||
renderHero({ canEdit: false, canShare: false, isOwner: false, onExport });
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Export' }));
|
||||
|
||||
expect(onExport).toHaveBeenCalledTimes(1);
|
||||
expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLHERO-015: refuses a second click while the first export is still running', () => {
|
||||
renderHero({ onExport: vi.fn(), exporting: true });
|
||||
expect(screen.getByRole('button', { name: 'Export' })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from 'react'
|
||||
import { avatarSrc } from '../../utils/avatarSrc'
|
||||
import { Share2, Users, Link2, Pencil } from 'lucide-react'
|
||||
import { Share2, Users, Link2, Pencil, Download, Loader2 } from 'lucide-react'
|
||||
import type { CollectionMember, CollectionLink } from '@trek/shared'
|
||||
import type { TranslationFn } from '../../types'
|
||||
|
||||
@@ -26,14 +26,18 @@ interface CollectionHeroProps {
|
||||
onEdit: () => void
|
||||
shareMemberCount: number
|
||||
onShare: () => void
|
||||
/** Absent on the "All saved" pseudo-list, which is a view rather than a list. */
|
||||
onExport?: () => void
|
||||
exporting?: boolean
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
/**
|
||||
* The page header — a colour-washed (or cover-image) glass hero that gives the
|
||||
* active list an identity: an eyebrow with the sharing state + member avatars,
|
||||
* the big list name, an optional description + link chips, and a Share action
|
||||
* top-right. Filtering lives in the toolbar above the places, not here.
|
||||
* the big list name, an optional description + link chips, and the Edit,
|
||||
* Export and Share actions top-right. Filtering lives in the toolbar above the
|
||||
* places, not here.
|
||||
* Modelled on the dashboard hero-trip.
|
||||
*/
|
||||
function linkHost(url: string): string {
|
||||
@@ -42,7 +46,7 @@ function linkHost(url: string): string {
|
||||
|
||||
export default function CollectionHero({
|
||||
eyebrow, title, color, coverImage, description, links,
|
||||
members, canShare, isOwner, canEdit, onEdit, shareMemberCount, onShare, t,
|
||||
members, canShare, isOwner, canEdit, onEdit, shareMemberCount, onShare, onExport, exporting, t,
|
||||
}: CollectionHeroProps): React.ReactElement {
|
||||
const accepted = members.filter(m => m.status === 'accepted' || m.is_owner)
|
||||
const showAvatars = accepted.length > 1
|
||||
@@ -94,6 +98,19 @@ export default function CollectionHero({
|
||||
<span className="txt">{t('common.edit')}</span>
|
||||
</button>
|
||||
)}
|
||||
{onExport && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onExport}
|
||||
disabled={exporting}
|
||||
aria-label={t('collections.file.export')}
|
||||
title={t('collections.file.exportTitle')}
|
||||
className="col-glass-btn"
|
||||
>
|
||||
{exporting ? <Loader2 size={15} className="animate-spin" /> : <Download size={15} />}
|
||||
<span className="txt">{t('collections.file.export')}</span>
|
||||
</button>
|
||||
)}
|
||||
{canShare && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
// FE-COMP-COLLIMPORT-001 to FE-COMP-COLLIMPORT-010
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import type { CollectionFile } from '@trek/shared';
|
||||
import { useTranslation } from '../../i18n/TranslationContext';
|
||||
import ImportCollectionModal from './ImportCollectionModal';
|
||||
|
||||
// The modal takes `t` as a prop, so this harness forwards the real English
|
||||
// translator and the assertions read as the strings a person sees.
|
||||
function Harness(props: Omit<React.ComponentProps<typeof ImportCollectionModal>, 't'>) {
|
||||
const { t } = useTranslation();
|
||||
return <ImportCollectionModal {...props} t={t} />;
|
||||
}
|
||||
|
||||
const listFile: CollectionFile = {
|
||||
format: 'trek.collection', version: 1, name: 'Lisbon',
|
||||
description: 'Worth it if you have three days',
|
||||
color: '#ef4444',
|
||||
labels: [{ name: 'Must see', color: '#ff0000' }, { name: 'Rainy day', color: '#00ff00' }],
|
||||
places: [{ name: 'Time Out Market' }, { name: 'Miradouro' }, { name: 'Pastéis de Belém' }],
|
||||
} as CollectionFile;
|
||||
|
||||
function renderModal(overrides: Partial<React.ComponentProps<typeof ImportCollectionModal>> = {}) {
|
||||
const props = {
|
||||
onImport: vi.fn().mockResolvedValue(undefined),
|
||||
onClose: vi.fn(),
|
||||
...overrides,
|
||||
};
|
||||
render(<Harness {...props} />);
|
||||
return props;
|
||||
}
|
||||
|
||||
/** Put a file into the hidden input the way a file picker would. */
|
||||
async function choose(content: string, name = 'list.trekcollection.json') {
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
const file = new File([content], name, { type: 'application/json' });
|
||||
// jsdom's File has no usable text(); the component awaits it.
|
||||
Object.defineProperty(file, 'text', { value: () => Promise.resolve(content) });
|
||||
await userEvent.upload(input, file);
|
||||
}
|
||||
|
||||
const importButton = () => screen.getByRole('button', { name: 'Import' });
|
||||
|
||||
describe('ImportCollectionModal (#2198)', () => {
|
||||
it('FE-COMP-COLLIMPORT-001: opens asking for a file, with Import not yet possible', () => {
|
||||
renderModal();
|
||||
expect(screen.getByText('Choose a list file')).toBeInTheDocument();
|
||||
expect(screen.getByText('.trekcollection.json')).toBeInTheDocument();
|
||||
expect(importButton()).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-002: shows what the file holds before anything is imported', async () => {
|
||||
const props = renderModal();
|
||||
await choose(JSON.stringify(listFile));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Worth it if you have three days')).toBeInTheDocument());
|
||||
expect(screen.getByText('3 places')).toBeInTheDocument();
|
||||
expect(screen.getByText('2 labels')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('Lisbon')).toBeInTheDocument();
|
||||
expect(importButton()).toBeEnabled();
|
||||
expect(props.onImport).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-003: leaves the label count out when the file has none', async () => {
|
||||
renderModal();
|
||||
await choose(JSON.stringify({ ...listFile, labels: [] }));
|
||||
await waitFor(() => expect(screen.getByText('3 places')).toBeInTheDocument());
|
||||
expect(screen.queryByText(/labels$/)).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-004: imports the file under its own name', async () => {
|
||||
const props = renderModal();
|
||||
await choose(JSON.stringify(listFile));
|
||||
await waitFor(() => expect(importButton()).toBeEnabled());
|
||||
|
||||
await userEvent.click(importButton());
|
||||
|
||||
await waitFor(() => expect(props.onImport).toHaveBeenCalledTimes(1));
|
||||
// No name argument: the file's own name was kept.
|
||||
expect(props.onImport).toHaveBeenCalledWith(expect.objectContaining({ name: 'Lisbon' }), undefined);
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-005: imports under a name the person typed instead', async () => {
|
||||
const props = renderModal();
|
||||
await choose(JSON.stringify(listFile));
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Lisbon')).toBeInTheDocument());
|
||||
|
||||
await userEvent.clear(screen.getByDisplayValue('Lisbon'));
|
||||
await userEvent.type(screen.getByRole('textbox'), 'Lisbon (from Ana)');
|
||||
await userEvent.click(importButton());
|
||||
|
||||
await waitFor(() => expect(props.onImport).toHaveBeenCalledWith(expect.anything(), 'Lisbon (from Ana)'));
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-006: will not import under an empty name', async () => {
|
||||
renderModal();
|
||||
await choose(JSON.stringify(listFile));
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Lisbon')).toBeInTheDocument());
|
||||
|
||||
await userEvent.clear(screen.getByRole('textbox'));
|
||||
|
||||
expect(importButton()).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-007: says what is wrong with a file it cannot use', async () => {
|
||||
renderModal();
|
||||
|
||||
await choose('not json');
|
||||
await waitFor(() => expect(screen.getByText('That file could not be read.')).toBeInTheDocument());
|
||||
|
||||
await choose(JSON.stringify({ format: 'something.else' }));
|
||||
await waitFor(() => expect(screen.getByText('That is not a TREK list file.')).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-008: takes a good file after a bad one, and forgets the complaint', async () => {
|
||||
renderModal();
|
||||
await choose('not json');
|
||||
await waitFor(() => expect(screen.getByText('That file could not be read.')).toBeInTheDocument());
|
||||
|
||||
await choose(JSON.stringify(listFile));
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('Lisbon')).toBeInTheDocument());
|
||||
expect(screen.queryByText('That file could not be read.')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-009: keeps the dialog open and says why when the import fails', async () => {
|
||||
const props = renderModal({ onImport: vi.fn().mockRejectedValue(new Error('the server said no')) });
|
||||
await choose(JSON.stringify(listFile));
|
||||
await waitFor(() => expect(importButton()).toBeEnabled());
|
||||
|
||||
await userEvent.click(importButton());
|
||||
|
||||
await waitFor(() => expect(screen.getByText('the server said no')).toBeInTheDocument());
|
||||
expect(screen.getByDisplayValue('Lisbon')).toBeInTheDocument();
|
||||
expect(props.onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLLIMPORT-010: closes without importing on Cancel', async () => {
|
||||
const props = renderModal();
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
expect(props.onClose).toHaveBeenCalledTimes(1);
|
||||
expect(props.onImport).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
import React, { useRef, useState } from 'react'
|
||||
import { Upload, FileJson, Loader2, MapPin, Tag, AlertCircle } from 'lucide-react'
|
||||
import Modal from '../shared/Modal'
|
||||
import type { CollectionFile } from '@trek/shared'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import { readCollectionFile, type CollectionFileError, COLLECTION_FILE_EXTENSION } from './collectionFile'
|
||||
|
||||
interface ImportCollectionModalProps {
|
||||
onImport: (file: CollectionFile, name?: string) => Promise<void>
|
||||
onClose: () => void
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a list file and make a list of it (#2198).
|
||||
*
|
||||
* Two steps on purpose. A file from somebody else is an unknown quantity, so
|
||||
* it is read and shown first — how many places, which labels, what the list is
|
||||
* called — and only then imported. The name is editable in the same breath,
|
||||
* because a file called "Lisbon" from a friend is usually worth calling
|
||||
* "Lisbon (from Ana)" on the way in, and renaming it afterwards means finding
|
||||
* the list editor.
|
||||
*
|
||||
* The file never leaves the browser as a file: it is parsed here, and what
|
||||
* goes to the server is the parsed list, through the same contract the server
|
||||
* validates against.
|
||||
*/
|
||||
export default function ImportCollectionModal({ onImport, onClose, t }: ImportCollectionModalProps): React.ReactElement {
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const [file, setFile] = useState<CollectionFile | null>(null)
|
||||
const [name, setName] = useState('')
|
||||
const [error, setError] = useState<CollectionFileError | 'failed' | null>(null)
|
||||
const [failedMessage, setFailedMessage] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [dragging, setDragging] = useState(false)
|
||||
|
||||
const take = async (chosen: File | undefined) => {
|
||||
if (!chosen) return
|
||||
setError(null)
|
||||
setFailedMessage(null)
|
||||
const result = await readCollectionFile(chosen)
|
||||
setFile(result.file)
|
||||
setError(result.error)
|
||||
if (result.file) setName(result.file.name)
|
||||
}
|
||||
|
||||
const onDrop = (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setDragging(false)
|
||||
void take(e.dataTransfer.files?.[0])
|
||||
}
|
||||
|
||||
const submit = async () => {
|
||||
if (!file || busy) return
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
setFailedMessage(null)
|
||||
try {
|
||||
const trimmed = name.trim()
|
||||
await onImport(file, trimmed && trimmed !== file.name ? trimmed : undefined)
|
||||
} catch (err) {
|
||||
setError('failed')
|
||||
setFailedMessage(getApiErrorMessage(err, t('common.error')))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const errorText = error === 'failed'
|
||||
? (failedMessage ?? t('common.error'))
|
||||
: error === 'too-large' ? t('collections.file.errorTooLarge')
|
||||
: error === 'unreadable' ? t('collections.file.errorUnreadable')
|
||||
: error === 'not-a-collection' ? t('collections.file.errorNotACollection')
|
||||
: null
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
title={t('collections.file.importTitle')}
|
||||
size="sm"
|
||||
footer={
|
||||
<div className="flex justify-end gap-2">
|
||||
<button type="button" onClick={onClose} className="px-4 py-2 rounded-lg text-[13px] font-medium text-content-muted hover:bg-surface-hover transition-colors">
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={submit}
|
||||
disabled={!file || busy || !name.trim()}
|
||||
className="px-4 py-2 rounded-lg text-[13px] font-semibold bg-accent text-accent-text disabled:opacity-50 transition-opacity inline-flex items-center gap-2"
|
||||
>
|
||||
{busy && <Loader2 size={14} className="animate-spin" />}
|
||||
{t('collections.file.confirm')}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-3">
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept=".json,application/json"
|
||||
className="hidden"
|
||||
onChange={e => { void take(e.target.files?.[0]); e.target.value = '' }}
|
||||
/>
|
||||
|
||||
{!file ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
onDragOver={e => { e.preventDefault(); setDragging(true) }}
|
||||
onDragLeave={() => setDragging(false)}
|
||||
onDrop={onDrop}
|
||||
className={`flex flex-col items-center justify-center gap-2 px-4 py-10 rounded-xl border border-dashed transition-colors ${
|
||||
dragging ? 'border-accent bg-surface-hover' : 'border-edge hover:bg-surface-hover'
|
||||
}`}
|
||||
>
|
||||
<Upload size={22} className="text-content-faint" />
|
||||
<span className="text-[13px] font-medium text-content">{t('collections.file.choose')}</span>
|
||||
<span className="text-[11.5px] text-content-faint">{COLLECTION_FILE_EXTENSION}</span>
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center gap-3 px-3 py-2.5 rounded-xl border border-edge bg-surface-card">
|
||||
<span className="w-9 h-9 min-w-[36px] rounded-lg flex items-center justify-center shrink-0 text-white" style={{ background: file.color || '#6366f1' }}>
|
||||
<FileJson size={15} />
|
||||
</span>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="block text-[13px] font-semibold text-content truncate">{file.name}</span>
|
||||
<span className="flex items-center gap-3 text-[11.5px] text-content-faint">
|
||||
<span className="inline-flex items-center gap-1"><MapPin size={11} />{t('collections.placeCount', { count: file.places.length })}</span>
|
||||
{file.labels && file.labels.length > 0 && (
|
||||
<span className="inline-flex items-center gap-1"><Tag size={11} />{t('collections.file.labelCount', { count: file.labels.length })}</span>
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
<button type="button" onClick={() => inputRef.current?.click()} className="text-[12px] font-medium text-accent shrink-0 hover:underline">
|
||||
{t('collections.file.change')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{file.description && (
|
||||
<p className="text-[12px] text-content-muted whitespace-pre-wrap">{file.description}</p>
|
||||
)}
|
||||
|
||||
<label className="flex flex-col gap-1.5">
|
||||
<span className="text-[12px] font-medium text-content-muted">{t('collections.listName')}</span>
|
||||
<input
|
||||
value={name}
|
||||
onChange={e => setName(e.target.value)}
|
||||
maxLength={120}
|
||||
className="w-full px-3 py-2 rounded-lg border border-edge bg-surface-input text-content text-[13px] outline-none focus:border-accent"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<p className="text-[11.5px] text-content-faint">{t('collections.file.hint')}</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{errorText && (
|
||||
<p className="flex items-start gap-2 text-[12px] text-danger">
|
||||
<AlertCircle size={13} className="shrink-0 mt-0.5" />
|
||||
<span>{errorText}</span>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -35,6 +35,7 @@ function renderRail(overrides: Partial<RailProps> = {}) {
|
||||
incomingInvites: [],
|
||||
onSelect: vi.fn(),
|
||||
onNewList: vi.fn(),
|
||||
onImportList: vi.fn(),
|
||||
onAcceptInvite: vi.fn(),
|
||||
onDeclineInvite: vi.fn(),
|
||||
...overrides,
|
||||
@@ -93,7 +94,7 @@ describe('ListsRail', () => {
|
||||
it('FE-COMP-LISTSRAIL-007: renders a Shared section with its lists only when there are shared lists', () => {
|
||||
const { unmount } = render(<Harness {...{
|
||||
ownedLists: [rome], sharedLists: [], activeId: null, incomingInvites: [],
|
||||
onSelect: vi.fn(), onNewList: vi.fn(), onAcceptInvite: vi.fn(), onDeclineInvite: vi.fn(),
|
||||
onSelect: vi.fn(), onNewList: vi.fn(), onImportList: vi.fn(), onAcceptInvite: vi.fn(), onDeclineInvite: vi.fn(),
|
||||
}} />);
|
||||
expect(screen.queryByText('Shared')).not.toBeInTheDocument();
|
||||
unmount();
|
||||
@@ -127,4 +128,18 @@ describe('ListsRail', () => {
|
||||
expect(screen.queryByText('Invites')).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'All saved' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-LISTSRAIL-011: offers Import beside New list, and it opens the file dialog (#2198)', async () => {
|
||||
const user = userEvent.setup();
|
||||
const props = renderRail();
|
||||
|
||||
const importBtn = screen.getByRole('button', { name: 'Import a list from a file' });
|
||||
await user.click(importBtn);
|
||||
|
||||
expect(props.onImportList).toHaveBeenCalledTimes(1);
|
||||
expect(props.onNewList).not.toHaveBeenCalled();
|
||||
// New list keeps its label; import is the icon beside it.
|
||||
expect(screen.getByRole('button', { name: 'New list' })).toHaveTextContent('New list');
|
||||
expect(importBtn).toHaveTextContent('');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react'
|
||||
import { Plus, Layers, Users } from 'lucide-react'
|
||||
import { Plus, Layers, Users, Upload } from 'lucide-react'
|
||||
import type { Collection } from '@trek/shared'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import { ALL_SAVED } from '../../store/collectionStore'
|
||||
@@ -12,6 +12,8 @@ interface ListsRailProps {
|
||||
incomingInvites: IncomingCollectionInvite[]
|
||||
onSelect: (id: ActiveCollectionId) => void
|
||||
onNewList: () => void
|
||||
/** Read a list file as a new list (#2198). */
|
||||
onImportList: () => void
|
||||
onAcceptInvite: (id: number) => void
|
||||
onDeclineInvite: (id: number) => void
|
||||
t: TranslationFn
|
||||
@@ -30,7 +32,7 @@ function ListRow({ list, active, onSelect }: { list: Collection; active: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Left rail of the user's lists: a "New list" action, the "All saved" union
|
||||
* Left rail of the user's lists: "New list" and "Import list" actions, the "All saved" union
|
||||
* pseudo-list, owned lists (colour dot + count), a shared section, and an
|
||||
* incoming-invites block. Selecting a list makes it active; editing / deleting
|
||||
* happens from the Edit button in the hero of the active list.
|
||||
@@ -38,14 +40,27 @@ function ListRow({ list, active, onSelect }: { list: Collection; active: boolean
|
||||
export default function ListsRail(props: ListsRailProps): React.ReactElement {
|
||||
const {
|
||||
ownedLists, sharedLists, activeId, incomingInvites,
|
||||
onSelect, onNewList, onAcceptInvite, onDeclineInvite, t,
|
||||
onSelect, onNewList, onImportList, onAcceptInvite, onDeclineInvite, t,
|
||||
} = props
|
||||
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={onNewList} className="col-rail-new">
|
||||
<Plus size={16} /> {t('collections.newList')}
|
||||
</button>
|
||||
<div className="col-rail-newrow">
|
||||
<button type="button" onClick={onNewList} className="col-rail-new">
|
||||
<Plus size={16} /> {t('collections.newList')}
|
||||
</button>
|
||||
{/* Import sits beside New rather than in the hero: a file becomes a NEW
|
||||
list, so it belongs where lists are made, not on the one open. */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onImportList}
|
||||
className="col-rail-new col-rail-import"
|
||||
aria-label={t('collections.file.importButton')}
|
||||
title={t('collections.file.importTitle')}
|
||||
>
|
||||
<Upload size={15} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="col-row">
|
||||
<button type="button" onClick={() => onSelect(ALL_SAVED)} className={`col-row-btn${activeId === ALL_SAVED ? ' on' : ''}`}>
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
// FE-COLL-FILE-001 to FE-COLL-FILE-012
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { collectionFileName, downloadCollectionFile, readCollectionFile, COLLECTION_FILE_EXTENSION } from './collectionFile'
|
||||
import type { CollectionFile } from '@trek/shared'
|
||||
|
||||
const file = (over: Partial<CollectionFile> = {}): CollectionFile => ({
|
||||
format: 'trek.collection', version: 1, name: 'Lisbon', places: [{ name: 'Time Out Market' }], ...over,
|
||||
} as CollectionFile)
|
||||
|
||||
/** A File whose text() the jsdom build does not provide on its own. */
|
||||
function asFile(content: string, size = content.length): File {
|
||||
return { size, text: () => Promise.resolve(content) } as unknown as File
|
||||
}
|
||||
|
||||
describe('collectionFileName', () => {
|
||||
it('FE-COLL-FILE-001: turns a list name into a short ascii file name', () => {
|
||||
expect(collectionFileName('Lisbon')).toBe('lisbon' + COLLECTION_FILE_EXTENSION)
|
||||
expect(collectionFileName('Wochenende in Rom!')).toBe('wochenende-in-rom' + COLLECTION_FILE_EXTENSION)
|
||||
expect(collectionFileName('東京')).toBe('collection' + COLLECTION_FILE_EXTENSION)
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-002: caps a very long name rather than producing an unusable file name', () => {
|
||||
const name = collectionFileName('a'.repeat(200))
|
||||
expect(name).toBe('a'.repeat(40) + COLLECTION_FILE_EXTENSION)
|
||||
})
|
||||
})
|
||||
|
||||
describe('downloadCollectionFile', () => {
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
it('FE-COLL-FILE-003: hands the browser a named JSON blob and releases it afterwards', () => {
|
||||
vi.useFakeTimers()
|
||||
const revoke = vi.fn()
|
||||
const created: Blob[] = []
|
||||
vi.stubGlobal('URL', {
|
||||
createObjectURL: (b: Blob) => { created.push(b); return 'blob:x' },
|
||||
revokeObjectURL: revoke,
|
||||
})
|
||||
const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {
|
||||
expect(this.download).toBe('lisbon' + COLLECTION_FILE_EXTENSION)
|
||||
expect(this.href).toContain('blob:')
|
||||
})
|
||||
|
||||
downloadCollectionFile(file())
|
||||
|
||||
expect(click).toHaveBeenCalledTimes(1)
|
||||
expect(created[0].type).toBe('application/json')
|
||||
expect(document.querySelector('a')).toBeNull()
|
||||
expect(revoke).not.toHaveBeenCalled()
|
||||
vi.runAllTimers()
|
||||
expect(revoke).toHaveBeenCalledWith('blob:x')
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
})
|
||||
|
||||
describe('readCollectionFile', () => {
|
||||
it('FE-COLL-FILE-004: reads one of ours', async () => {
|
||||
const result = await readCollectionFile(asFile(JSON.stringify(file())))
|
||||
expect(result.error).toBeNull()
|
||||
expect(result.file?.name).toBe('Lisbon')
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-005: refuses a file too large to be one, without reading it', async () => {
|
||||
const text = vi.fn()
|
||||
const huge = { size: 1024 * 1024 + 1, text } as unknown as File
|
||||
const result = await readCollectionFile(huge)
|
||||
expect(result).toEqual({ file: null, error: 'too-large' })
|
||||
expect(text).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-006: says a file is unreadable when it is not JSON', async () => {
|
||||
expect(await readCollectionFile(asFile('not json at all'))).toEqual({ file: null, error: 'unreadable' })
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-007: says a JSON that is not a list is not a list', async () => {
|
||||
for (const content of ['{}', '[]', 'null', '"a string"', JSON.stringify({ format: 'something.else', version: 1, name: 'x', places: [] })]) {
|
||||
expect(await readCollectionFile(asFile(content)), content).toEqual({ file: null, error: 'not-a-collection' })
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-008: refuses a list with no name, since the list would have none', async () => {
|
||||
const result = await readCollectionFile(asFile(JSON.stringify({ format: 'trek.collection', version: 1, name: '', places: [] })))
|
||||
expect(result.error).toBe('not-a-collection')
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-009: reads an empty list, which is a list somebody has not filled yet', async () => {
|
||||
const result = await readCollectionFile(asFile(JSON.stringify(file({ places: [] }))))
|
||||
expect(result.error).toBeNull()
|
||||
expect(result.file?.places).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-010: keeps a place the envelope does not check, for the server to judge', async () => {
|
||||
// The envelope counts places; each one is validated where it is written.
|
||||
const result = await readCollectionFile(asFile(JSON.stringify(file({
|
||||
places: [{ name: 'Fine' }, { nonsense: true }] as never,
|
||||
}))))
|
||||
expect(result.error).toBeNull()
|
||||
expect(result.file?.places).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-011: refuses a file carrying more places than the contract allows', async () => {
|
||||
const tooMany = Array.from({ length: 1001 }, (_, i) => ({ name: `Place ${i}` }))
|
||||
const result = await readCollectionFile(asFile(JSON.stringify(file({ places: tooMany as never }))))
|
||||
expect(result.error).toBe('not-a-collection')
|
||||
})
|
||||
|
||||
it('FE-COLL-FILE-012: reads a file from a later version, since its additions are optional', async () => {
|
||||
const result = await readCollectionFile(asFile(JSON.stringify({ ...file(), version: 99, somethingNew: 'x' })))
|
||||
expect(result.error).toBeNull()
|
||||
expect(result.file?.version).toBe(99)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
import { collectionFileSchema, MAX_COLLECTION_FILE_BYTES, type CollectionFile } from '@trek/shared'
|
||||
|
||||
/**
|
||||
* The browser half of list export and import (#2198).
|
||||
*
|
||||
* The file itself is built by the server, which is also where the decision
|
||||
* about what may leave the instance lives (`collection-file.schema.ts`). This
|
||||
* module only hands the JSON to the browser as a download, and reads a chosen
|
||||
* file back into something the import request will accept.
|
||||
*
|
||||
* A file that arrives here is a stranger's JSON and is treated as one: read
|
||||
* locally, never uploaded, parsed rather than evaluated, size-capped before
|
||||
* parsing, and put through the shared contract so a field this build does not
|
||||
* know is dropped instead of travelling on to the server.
|
||||
*/
|
||||
|
||||
export const COLLECTION_FILE_EXTENSION = '.trekcollection.json'
|
||||
|
||||
/** A file name from a list name: lowercase, ascii-ish, short. */
|
||||
export function collectionFileName(name: string): string {
|
||||
const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40)
|
||||
return `${slug || 'collection'}${COLLECTION_FILE_EXTENSION}`
|
||||
}
|
||||
|
||||
/** Hand the file to the browser as a download. */
|
||||
export function downloadCollectionFile(file: CollectionFile): void {
|
||||
const json = JSON.stringify(file, null, 2)
|
||||
const url = URL.createObjectURL(new Blob([json], { type: 'application/json' }))
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = collectionFileName(file.name)
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
// Revoked on the next tick: revoking synchronously can cancel the download
|
||||
// in some browsers before it has started reading the blob.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 0)
|
||||
}
|
||||
|
||||
export type CollectionFileError = 'too-large' | 'unreadable' | 'not-a-collection'
|
||||
|
||||
/**
|
||||
* Exactly one of the two is set.
|
||||
*
|
||||
* Two nullable fields rather than a discriminated union on an `ok` flag: the
|
||||
* client compiles with `strict: false`, and without `strictNullChecks` a
|
||||
* `{ok: true} | {ok: false}` union does not narrow, so every read of the
|
||||
* failure branch would need a cast.
|
||||
*/
|
||||
export interface ParsedCollectionFile {
|
||||
file: CollectionFile | null
|
||||
error: CollectionFileError | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a chosen file into a list file, or say why it is not one.
|
||||
*
|
||||
* The three failures are kept apart because they are three different things a
|
||||
* person can do something about: a file too big to be one of ours, a file that
|
||||
* is not JSON at all, and a JSON that is not a TREK list.
|
||||
*/
|
||||
export async function readCollectionFile(file: File): Promise<ParsedCollectionFile> {
|
||||
if (file.size > MAX_COLLECTION_FILE_BYTES) return { file: null, error: 'too-large' }
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(await file.text())
|
||||
} catch {
|
||||
return { file: null, error: 'unreadable' }
|
||||
}
|
||||
const parsed = collectionFileSchema.safeParse(raw)
|
||||
return parsed.success
|
||||
? { file: parsed.data, error: null }
|
||||
: { file: null, error: 'not-a-collection' }
|
||||
}
|
||||
Reference in New Issue
Block a user