bookmarks: user bookmarks in the navigation bar, stored in bookmarks.yaml

A "Bookmarks" tab between Calculators and Flasher opens on hover or click and
lists the user's bookmarks, with directories as flyout submenus (Menu.Sub).
The mobile hamburger shows directories as labelled groups instead.  The tab
always shows, with an "Edit bookmarks" item, so the feature can be found
before any bookmark exists.

Bookmarks live in a new config-only bookmarks.yaml: a nested tree where a
node with `children` is a directory and a node with `url` is a bookmark.
Every node carries an integer id so the API can rename, move and delete
without relying on names.  A URL may be a path on this WROLPi, a port on this
host (`:8096/` or `http://:8096/`, resolved against whatever hostname the
browser used, so it works over LAN IP, mDNS and the hotspot alike), or an
absolute URL.  Each bookmark chooses whether to open in a new tab.

The editor at /more/bookmarks follows the playlist items table: numbered rows,
up/down/edit/delete, and inline "Add a bookmark" / "Add a directory" forms
with a Location picker.  Deleting a directory asks first, since its contents
go with it.  The menu and the editor are in the component gallery.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-09-26 12:21:11 -06:00
parent 811793d767
commit b3c51c8b49
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
15 changed files with 1336 additions and 13 deletions

View file

@ -17,6 +17,7 @@ import {ArchiveRoute} from "./components/Archive";
import {FilesRoute} from "./components/Files";
import {QueryProvider, StatusProvider} from "./hooks/customHooks";
import {FileWorkerStatusProvider} from "./contexts/FileWorkerStatusContext";
import {BookmarksProvider} from "./contexts/BookmarksContext";
import {ChannelEditPage, ChannelNewPage, ChannelsPage} from "./components/Channels";
import {MapRoute} from "./components/Map";
import {MediaContextProvider, mediaStyles, StatusContext} from "./contexts/contexts";
@ -69,13 +70,15 @@ function Root() {
<TagsProvider>
<KeyboardShortcutsProvider>
<FilePreviewProvider>
<header>
<NavBar/>
</header>
<ErrorBoundary>
<Outlet/>
</ErrorBoundary>
<Footer/>
<BookmarksProvider>
<header>
<NavBar/>
</header>
<ErrorBoundary>
<Outlet/>
</ErrorBoundary>
<Footer/>
</BookmarksProvider>
</FilePreviewProvider>
</KeyboardShortcutsProvider>
</TagsProvider>

View file

@ -2438,3 +2438,46 @@ export async function setPlaylistTag(playlistId, tagName, directory) {
toast({type: 'error', title: 'Error', description: message, time: 5000});
throw Error(message);
}
// Bookmarks: a tree of nodes, a node with `children` being a directory.
export async function getBookmarks() {
const response = await apiGet(`${API_URI}/bookmarks`);
if (response.ok) {
return (await response.json())['bookmarks'];
}
throw new Error('Could not fetch bookmarks');
}
async function bookmarksModify(request, fallbackMessage) {
const response = await request;
if (response.ok) {
return response.status === 204 ? null : await response.json();
}
const message = await getErrorMessage(response, fallbackMessage);
toast({type: 'error', title: 'Bookmarks Error', description: message, time: 5000});
throw new Error(message);
}
export async function addBookmark({name, url, new_tab = false, parent_id = null, position = null}) {
const body = {name, url, new_tab, parent_id, position};
return await bookmarksModify(apiPost(`${API_URI}/bookmarks`, body), 'Could not add bookmark');
}
export async function addBookmarkDirectory({name, parent_id = null, position = null}) {
const body = {name, parent_id, position};
return await bookmarksModify(apiPost(`${API_URI}/bookmarks/directory`, body), 'Could not add directory');
}
export async function updateBookmark(nodeId, {name, url, new_tab}) {
const body = {name, url, new_tab};
return await bookmarksModify(apiPut(`${API_URI}/bookmarks/${nodeId}`, body), 'Could not update bookmark');
}
export async function moveBookmark(nodeId, parent_id, position = null) {
const body = {parent_id, position};
return await bookmarksModify(apiPost(`${API_URI}/bookmarks/${nodeId}/move`, body), 'Could not move bookmark');
}
export async function deleteBookmark(nodeId) {
return await bookmarksModify(apiDelete(`${API_URI}/bookmarks/${nodeId}`), 'Could not delete bookmark');
}

View file

@ -12,6 +12,7 @@ import {
import {Header, Loading, Panel, Statistic, StatisticGroup} from "./ui";
import {useStatistics} from "../hooks/customHooks";
import {CalculatorsPage} from "./Calculators";
import {BookmarksPage} from "./Bookmarks";
function StatisticsPage() {
useTitle('Statistics');
@ -104,6 +105,7 @@ export function MoreRoute(props) {
<Routes>
<Route path='calculators' element={<CalculatorsPage/>}/>
<Route path='statistics' exact element={<StatisticsPage/>}/>
<Route path='bookmarks' element={<BookmarksPage/>}/>
</Routes>
</PageContainer>
}

View file

@ -0,0 +1,430 @@
import React, {useState} from 'react';
import {Link} from 'react-router';
import {IconBookmark} from '@tabler/icons-react';
import {Button, Group, Header, Icon, Menu, Message, Modal, Panel, Select, Table, Text, TextInput, Toggle} from './ui';
import {APIButton, PageContainer, useTitle} from './Common';
import {isBookmarkDirectory, resolveBookmarkUrl, useBookmarks} from '../contexts/BookmarksContext';
import {addBookmark, addBookmarkDirectory, deleteBookmark, moveBookmark, updateBookmark} from '../api';
export const EDIT_BOOKMARKS_PATH = '/more/bookmarks';
/**
* The props that make a Menu.Item open a bookmark: an in-app Link for a path, a plain
* anchor for everything else, and a new tab when the bookmark asks for one.
*/
function bookmarkItemProps(node) {
const {internal, href} = resolveBookmarkUrl(node.url);
const target = node.new_tab ? {target: '_blank', rel: 'noopener noreferrer'} : {};
if (internal) {
return {component: Link, to: href, ...target};
}
return {component: 'a', href, ...target};
}
/**
* The items of a bookmarks menu.
*
* `nested` draws a directory as a flyout (Menu.Sub), which opens beside the menu on hover.
* Without it a directory is a labelled, indented run of items instead: the mobile
* hamburger is the one place bookmarks are shown where a flyout cannot be hovered.
*/
export function BookmarkMenuItems({nodes, nested = true, depth = 0}) {
if (!nodes || nodes.length === 0) {
return null;
}
return nodes.map(node => {
if (isBookmarkDirectory(node)) {
if (nested) {
return <Menu.Sub key={node.id}>
<Menu.Sub.Target>
<Menu.Sub.Item leftSection={<Icon name='folder' size='small'/>}>{node.name}</Menu.Sub.Item>
</Menu.Sub.Target>
<Menu.Sub.Dropdown>
{node.children.length > 0
? <BookmarkMenuItems nodes={node.children} nested={nested}/>
: <Menu.Item disabled>Empty</Menu.Item>}
</Menu.Sub.Dropdown>
</Menu.Sub>;
}
return <React.Fragment key={node.id}>
<Menu.Label style={{paddingLeft: `${0.75 + depth}em`}}>{node.name}</Menu.Label>
<BookmarkMenuItems nodes={node.children} nested={false} depth={depth + 1}/>
</React.Fragment>;
}
return <Menu.Item
key={node.id}
{...bookmarkItemProps(node)}
style={nested ? undefined : {paddingLeft: `${0.75 + depth}em`}}
rightSection={node.new_tab ? <Icon name='external' size='small'/> : undefined}
>
{node.name}
</Menu.Item>;
});
}
/**
* Everything inside a bookmarks dropdown: the bookmarks, then the link to edit them. The
* edit link is always there, so a user with no bookmarks yet can find where to add one.
*/
export function BookmarksMenuContents({nested = true}) {
const {bookmarks} = useBookmarks();
const nodes = bookmarks || [];
return <>
<BookmarkMenuItems nodes={nodes} nested={nested}/>
{nodes.length > 0 && <Menu.Divider/>}
<Menu.Item component={Link} to={EDIT_BOOKMARKS_PATH} leftSection={<Icon name='edit' size='small'/>}>
Edit bookmarks
</Menu.Item>
</>;
}
/** Every directory in the tree with its full path, for the "Location" picker. */
export function directoryOptions(nodes, prefix = '') {
const options = [];
for (const node of nodes || []) {
if (isBookmarkDirectory(node)) {
const label = `${prefix}${node.name}`;
options.push({value: String(node.id), label, id: node.id});
options.push(...directoryOptions(node.children, `${label} / `));
}
}
return options;
}
/** The ids of `node` and everything beneath it. */
const subtreeIds = (node) => {
const ids = [node.id];
if (isBookmarkDirectory(node)) {
node.children.forEach(child => ids.push(...subtreeIds(child)));
}
return ids;
};
const ROOT = 'root';
/** The places a node may live: the top level, and every directory not inside `node`. */
export function locationOptions(nodes, node = null) {
// A directory cannot be moved into itself or its own children.
const excluded = node ? new Set(subtreeIds(node)) : new Set();
return [
{value: ROOT, label: 'Top level'},
...directoryOptions(nodes).filter(i => !excluded.has(i.id)).map(({value, label}) => ({value, label})),
];
}
/**
* The form for one node. `node` is null when adding; `directory` says which kind.
* `parentId` is where a new node goes, or where an edited one currently lives.
*/
export function BookmarkNodeModal({open, node, directory, parentId, nodes, onSave, onClose}) {
const [name, setName] = useState(node?.name || '');
const [url, setUrl] = useState(node?.url || '');
const [newTab, setNewTab] = useState(Boolean(node?.new_tab));
const [location, setLocation] = useState(parentId === null || parentId === undefined ? ROOT : String(parentId));
const [saving, setSaving] = useState(false);
const locations = locationOptions(nodes, node);
const valid = name.trim() && (directory || url.trim());
const title = node ? (directory ? 'Edit directory' : 'Edit bookmark') : (directory ? 'New directory' : 'New bookmark');
const handleSave = async () => {
if (!valid) return;
setSaving(true);
try {
await onSave({
name: name.trim(),
url: url.trim(),
new_tab: newTab,
parent_id: location === ROOT ? null : Number(location),
});
} finally {
setSaving(false);
}
};
return <Modal open={open} onClose={onClose} size='tiny'>
<Modal.Header>{title}</Modal.Header>
<Modal.Content>
<form onSubmit={e => {
e.preventDefault();
handleSave();
}}>
<TextInput
autoFocus
label='Name'
value={name}
onChange={e => setName(e.currentTarget.value)}
/>
{!directory && <TextInput
label='URL'
style={{marginTop: '1em'}}
value={url}
onChange={e => setUrl(e.currentTarget.value)}
placeholder='/videos, :8096/, or https://example.com'
description='A path on this WROLPi (/videos), a port on this host (:8096/ or http://:8096/), or a full URL.'
/>}
<Select
label='Location'
style={{marginTop: '1em'}}
data={locations}
value={location}
onChange={value => setLocation(value || ROOT)}
allowDeselect={false}
/>
{!directory && <Toggle
style={{marginTop: '1em'}}
label='Open in a new tab'
checked={newTab}
onChange={e => setNewTab(e.currentTarget.checked)}
/>}
</form>
</Modal.Content>
<Modal.Actions>
<Button role='cancel' onClick={onClose}>Cancel</Button>
<Button role='save' disabled={!valid || saving} onClick={handleSave}>Save</Button>
</Modal.Actions>
</Modal>;
}
/** The rows of the editor, one per node, children beneath their directory and indented. */
function BookmarkTableRows({nodes, parentId, depth, editable, actions}) {
return nodes.map((node, index) => {
const directory = isBookmarkDirectory(node);
const {href} = directory ? {} : resolveBookmarkUrl(node.url);
return <React.Fragment key={node.id}>
<Table.Row>
<Table.Cell>{String(index + 1).padStart(2, '0')}</Table.Cell>
<Table.Cell style={{width: '90px', textAlign: 'center'}}>
{directory
? <Icon name='folder' size='large'/>
: <Icon name={node.new_tab ? 'external' : 'linkify'} size='large'/>}
</Table.Cell>
<Table.Cell style={{paddingLeft: depth ? `calc(0.75em + ${depth * 1.5}em)` : undefined}}>
{directory
? <b>{node.name}</b>
: <a href={href} target={node.new_tab ? '_blank' : undefined} rel='noopener noreferrer'>
{node.name}
</a>}
{!directory && <Text size='xs' c='dimmed' truncate='end'>{node.url}</Text>}
</Table.Cell>
{editable && <Table.Cell>
<div className='wrolpi-button-row' style={{justifyContent: 'flex-end'}}>
<Button icon='arrow up' size='xs' aria-label={`Move ${node.name} up`} disabled={index === 0}
onClick={() => actions.move(node, parentId, index - 1)}/>
<Button icon='arrow down' size='xs' aria-label={`Move ${node.name} down`}
disabled={index === nodes.length - 1}
onClick={() => actions.move(node, parentId, index + 1)}/>
<Button icon='edit' size='xs' aria-label={`Edit ${node.name}`}
onClick={() => actions.edit(node, parentId)}/>
{directory
? <APIButton
role='danger' icon='trash' size='xs' aria-label={`Delete ${node.name}`}
confirmContent={`Delete the directory "${node.name}" and everything in it?`}
confirmButton='Delete'
onClick={() => actions.remove(node)}/>
: <Button role='danger' icon='trash' size='xs' aria-label={`Delete ${node.name}`}
onClick={() => actions.remove(node)}/>}
</div>
</Table.Cell>}
</Table.Row>
{directory && <BookmarkTableRows nodes={node.children} parentId={node.id} depth={depth + 1}
editable={editable} actions={actions}/>}
</React.Fragment>;
});
}
/**
* The bookmarks table, in the shape of the playlist items table. `actions` carries
* edit/move/remove so the gallery can render it with none of them wired.
*/
export function BookmarkTable({nodes, editable = true, actions}) {
return <Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>#</Table.HeaderCell>
<Table.HeaderCell>Kind</Table.HeaderCell>
<Table.HeaderCell>Bookmark</Table.HeaderCell>
{editable && <Table.HeaderCell/>}
</Table.Row>
</Table.Header>
<Table.Body>
<BookmarkTableRows nodes={nodes} parentId={null} depth={0} editable={editable} actions={actions}/>
</Table.Body>
</Table>;
}
/** The "Add a bookmark" and "Add a directory" forms beneath the table. */
export function BookmarkAddForms({nodes, onAddBookmark, onAddDirectory}) {
const [url, setUrl] = useState('');
const [name, setName] = useState('');
const [newTab, setNewTab] = useState(false);
const [location, setLocation] = useState(ROOT);
const [directoryName, setDirectoryName] = useState('');
const [directoryLocation, setDirectoryLocation] = useState(ROOT);
const locations = locationOptions(nodes);
const parentOf = (value) => value === ROOT ? null : Number(value);
const handleAddBookmark = async () => {
if (!url.trim() || !name.trim()) return;
await onAddBookmark({name: name.trim(), url: url.trim(), new_tab: newTab, parent_id: parentOf(location)});
setUrl('');
setName('');
};
const handleAddDirectory = async () => {
if (!directoryName.trim()) return;
await onAddDirectory({name: directoryName.trim(), parent_id: parentOf(directoryLocation)});
setDirectoryName('');
};
return <>
<Header as='h4'>Add a bookmark</Header>
<form onSubmit={e => {
e.preventDefault();
handleAddBookmark();
}}>
<Group align='flex-end' wrap='wrap'>
<TextInput
style={{flex: '2 1 300px'}}
aria-label='Bookmark URL'
placeholder='URL (e.g. /videos, :8096/, or https://example.com)'
value={url}
onChange={e => setUrl(e.currentTarget.value)}/>
<TextInput
style={{flex: '1 1 200px'}}
aria-label='Bookmark name'
placeholder='Name'
value={name}
onChange={e => setName(e.currentTarget.value)}/>
<Select
style={{flex: '1 1 160px'}}
aria-label='Bookmark location'
data={locations}
value={location}
onChange={value => setLocation(value || ROOT)}
allowDeselect={false}/>
<Toggle
label='New tab'
checked={newTab}
onChange={e => setNewTab(e.currentTarget.checked)}/>
<Button role='primary' type='submit' disabled={!url.trim() || !name.trim()}>Add</Button>
</Group>
</form>
<p style={{marginTop: '0.5em'}}>
<Text size='xs' c='dimmed' component='span'>
A URL is a path on this WROLPi (/videos), a port on this host (:8096/ or http://:8096/) that
works whichever address you reach it by, or a full URL.
</Text>
</p>
<Header as='h4'>Add a directory</Header>
<form onSubmit={e => {
e.preventDefault();
handleAddDirectory();
}}>
<Group align='flex-end' wrap='wrap'>
<TextInput
style={{flex: '2 1 300px'}}
aria-label='Directory name'
placeholder='Directory name'
value={directoryName}
onChange={e => setDirectoryName(e.currentTarget.value)}/>
<Select
style={{flex: '1 1 160px'}}
aria-label='Directory location'
data={locations}
value={directoryLocation}
onChange={value => setDirectoryLocation(value || ROOT)}
allowDeselect={false}/>
<Button role='primary' type='submit' disabled={!directoryName.trim()}>Add</Button>
</Group>
</form>
</>;
}
export function BookmarksPage() {
useTitle('Bookmarks');
const {bookmarks, refresh} = useBookmarks();
// {node, directory, parentId} while the edit modal is open; a `key` remounts the form fresh.
const [modal, setModal] = useState(null);
const [modalKey, setModalKey] = useState(0);
const nodes = bookmarks || [];
const actions = {
edit: (node, parentId) => {
setModalKey(k => k + 1);
setModal({node, directory: isBookmarkDirectory(node), parentId});
},
move: async (node, parentId, position) => {
try {
await moveBookmark(node.id, parentId, position);
await refresh();
} catch (e) {
// Error toast already shown by the API client.
}
},
remove: async (node) => {
try {
await deleteBookmark(node.id);
await refresh();
} catch (e) {
}
},
};
const handleAddBookmark = async (bookmark) => {
try {
await addBookmark(bookmark);
await refresh();
} catch (e) {
}
};
const handleAddDirectory = async (directory) => {
try {
await addBookmarkDirectory(directory);
await refresh();
} catch (e) {
}
};
const handleEditSave = async ({name, url, new_tab, parent_id}) => {
const {node, directory, parentId} = modal;
try {
await updateBookmark(node.id, directory ? {name} : {name, url, new_tab});
if (parent_id !== parentId) {
await moveBookmark(node.id, parent_id);
}
await refresh();
setModal(null);
} catch (e) {
}
};
return <PageContainer>
<Panel>
<Header as='h1' icon={IconBookmark}>Bookmarks</Header>
<p>
Bookmarks appear in the Bookmarks menu of the navigation bar. They can point at pages on this
WROLPi, at other services running beside it, or anywhere on the web.
</p>
{nodes.length === 0
? <Message title='There are no bookmarks yet'>Add a bookmark below.</Message>
: <BookmarkTable nodes={nodes} actions={actions}/>}
<BookmarkAddForms nodes={nodes} onAddBookmark={handleAddBookmark} onAddDirectory={handleAddDirectory}/>
</Panel>
{modal && <BookmarkNodeModal
key={modalKey}
open
node={modal.node}
directory={modal.directory}
parentId={modal.parentId}
nodes={nodes}
onSave={handleEditSave}
onClose={() => setModal(null)}
/>}
</PageContainer>;
}

View file

@ -0,0 +1,160 @@
import React from 'react';
import {screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {render} from '../test-utils';
import {BookmarkAddForms, BookmarkNodeModal, BookmarkTable, directoryOptions, locationOptions} from './Bookmarks';
import {resolveBookmarkUrl} from '../contexts/BookmarksContext';
const tree = [
{id: 1, name: 'Channels', url: '/videos/channel', new_tab: false},
{
id: 2, name: 'Services', children: [
{id: 3, name: 'Jellyfin', url: ':8096/', new_tab: true},
{id: 4, name: 'Radio', children: []},
]
},
];
describe('resolveBookmarkUrl', () => {
const location = {protocol: 'https:', hostname: '10.0.0.2'};
it.each([
['/videos', {internal: true, href: '/videos'}],
[' /videos/channel/3 ', {internal: true, href: '/videos/channel/3'}],
// A port on this host takes the page's scheme, or its own when it names one.
[':8096/web', {internal: false, href: 'https://10.0.0.2:8096/web'}],
[':8096', {internal: false, href: 'https://10.0.0.2:8096'}],
['http://:8096/web', {internal: false, href: 'http://10.0.0.2:8096/web'}],
['HTTPS://:8085', {internal: false, href: 'https://10.0.0.2:8085'}],
['https://example.com/a?b=c', {internal: false, href: 'https://example.com/a?b=c'}],
])('resolves %s', (url, expected) => {
expect(resolveBookmarkUrl(url, location)).toEqual(expected);
});
});
describe('directoryOptions', () => {
it('lists every directory with its path, and no bookmarks', () => {
expect(directoryOptions(tree)).toEqual([
{value: '2', label: 'Services', id: 2},
{value: '4', label: 'Services / Radio', id: 4},
]);
});
});
describe('BookmarkTable', () => {
const actions = () => ({edit: jest.fn(), move: jest.fn(), remove: jest.fn()});
it('renders the tree with resolved links, numbered within each directory', () => {
render(<BookmarkTable nodes={tree} actions={actions()}/>);
const channels = screen.getByRole('link', {name: 'Channels'});
expect(channels).toHaveAttribute('href', '/videos/channel');
expect(channels).not.toHaveAttribute('target');
const jellyfin = screen.getByRole('link', {name: 'Jellyfin'});
expect(jellyfin).toHaveAttribute('href', `${window.location.protocol}//${window.location.hostname}:8096/`);
expect(jellyfin).toHaveAttribute('target', '_blank');
expect(screen.getByText('Radio')).toBeInTheDocument();
// Channels, Services, then Services' two children.
const numbers = screen.getAllByRole('row').slice(1).map(row => row.firstChild.textContent);
expect(numbers).toEqual(['01', '02', '01', '02']);
});
it('moves a node among its siblings and only within bounds', async () => {
const a = actions();
render(<BookmarkTable nodes={tree} actions={a}/>);
// The first top-level node cannot move up; the last cannot move down.
expect(screen.getByRole('button', {name: 'Move Channels up'})).toBeDisabled();
expect(screen.getByRole('button', {name: 'Move Services down'})).toBeDisabled();
await userEvent.click(screen.getByRole('button', {name: 'Move Channels down'}));
expect(a.move).toHaveBeenCalledWith(tree[0], null, 1);
// A child moves within its directory: parent 2, from index 1 to 0.
await userEvent.click(screen.getByRole('button', {name: 'Move Radio up'}));
expect(a.move).toHaveBeenCalledWith(tree[1].children[1], 2, 0);
});
it('edits with the parent the node lives in, and deletes a bookmark without asking', async () => {
const a = actions();
render(<BookmarkTable nodes={tree} actions={a}/>);
await userEvent.click(screen.getByRole('button', {name: 'Edit Jellyfin'}));
expect(a.edit).toHaveBeenCalledWith(tree[1].children[0], 2);
await userEvent.click(screen.getByRole('button', {name: 'Delete Channels'}));
expect(a.remove).toHaveBeenCalledWith(tree[0]);
});
it('asks before deleting a directory, since its contents go with it', async () => {
const a = actions();
render(<BookmarkTable nodes={tree} actions={a}/>);
await userEvent.click(screen.getByRole('button', {name: 'Delete Services'}));
expect(a.remove).not.toHaveBeenCalled();
await userEvent.click(await screen.findByRole('button', {name: 'Delete'}));
expect(a.remove).toHaveBeenCalledWith(tree[1]);
});
});
describe('BookmarkAddForms', () => {
it('adds a bookmark at the top level and clears the form', async () => {
const onAddBookmark = jest.fn();
render(<BookmarkAddForms nodes={tree} onAddBookmark={onAddBookmark} onAddDirectory={jest.fn()}/>);
const adds = screen.getAllByRole('button', {name: 'Add'});
expect(adds[0]).toBeDisabled();
await userEvent.type(screen.getByLabelText('Bookmark URL'), ':8123/');
expect(adds[0]).toBeDisabled();
await userEvent.type(screen.getByLabelText('Bookmark name'), 'Home Assistant');
await userEvent.click(screen.getByLabelText('New tab'));
await userEvent.click(adds[0]);
expect(onAddBookmark).toHaveBeenCalledWith({name: 'Home Assistant', url: ':8123/', new_tab: true, parent_id: null});
expect(screen.getByLabelText('Bookmark URL')).toHaveValue('');
});
it('adds a directory', async () => {
const onAddDirectory = jest.fn();
render(<BookmarkAddForms nodes={tree} onAddBookmark={jest.fn()} onAddDirectory={onAddDirectory}/>);
await userEvent.type(screen.getByLabelText('Directory name'), 'Tools');
await userEvent.click(screen.getAllByRole('button', {name: 'Add'})[1]);
expect(onAddDirectory).toHaveBeenCalledWith({name: 'Tools', parent_id: null});
});
});
describe('BookmarkNodeModal', () => {
// Mantine's Select scrolls the highlighted option into view; jsdom has no layout.
beforeAll(() => {
Element.prototype.scrollIntoView = jest.fn();
});
it('saves a new bookmark with its location and new-tab choice', async () => {
const onSave = jest.fn();
render(<BookmarkNodeModal open node={null} directory={false} parentId={2} nodes={tree}
onSave={onSave} onClose={jest.fn()}/>);
const save = screen.getByRole('button', {name: 'Save'});
expect(save).toBeDisabled();
await userEvent.type(screen.getByLabelText('Name'), 'Home Assistant');
expect(save).toBeDisabled();
await userEvent.type(screen.getByLabelText('URL'), ':8123/');
await userEvent.click(screen.getByLabelText('Open in a new tab'));
await userEvent.click(save);
expect(onSave).toHaveBeenCalledWith({name: 'Home Assistant', url: ':8123/', new_tab: true, parent_id: 2});
});
it('a directory has no URL or new-tab choice', () => {
render(<BookmarkNodeModal open node={tree[1]} directory parentId={null} nodes={tree}
onSave={jest.fn()} onClose={jest.fn()}/>);
expect(screen.getByLabelText('Name')).toHaveValue('Services');
expect(screen.queryByLabelText('URL')).not.toBeInTheDocument();
expect(screen.queryByLabelText('Open in a new tab')).not.toBeInTheDocument();
});
});
describe('locationOptions', () => {
it('offers the top level and every directory to a new node', () => {
expect(locationOptions(tree).map(o => o.label)).toEqual(['Top level', 'Services', 'Services / Radio']);
});
it('never offers a directory itself, or its children', () => {
expect(locationOptions(tree, tree[1]).map(o => o.label)).toEqual(['Top level']);
expect(locationOptions(tree, tree[1].children[1]).map(o => o.label)).toEqual(['Top level', 'Services']);
});
});

View file

@ -21,6 +21,7 @@ import {HELP_VIEWER_URI, NAME, navColorHexMap} from "./Vars";
import {useOverflowNav} from "../hooks/useOverflowNav";
import {defaultNavColor, navBarStyle, useNavColors} from "../themes/navColors";
import _ from "lodash";
import {BookmarksMenuContents, EDIT_BOOKMARKS_PATH} from "./Bookmarks";
function updateFavicon(colorName) {
// Fall back to violet if invalid color
@ -64,12 +65,18 @@ const allLinks = [
// No `end` on these two: a tab stays current for the pages beneath it, and `end` would
// drop the mark the moment either grows a sub-page.
{to: '/more/calculators', text: 'Calculators', key: 'calculators'},
// The user's bookmarks, read from BookmarksContext when rendered. No `to`: it is a
// menu, and its items are not sections of the app.
{text: 'Bookmarks', key: 'bookmarks', bookmarks: true},
{text: 'Flasher', to: '/flasher', key: 'flasher'},
{to: '/more/statistics', text: 'Statistics', key: 'statistics'},
];
function MenuLink({link}) {
// A top-level tab rendered directly in the bar (not inside a dropdown).
if (link.bookmarks) {
return <BookmarksDropdown link={link}/>
}
if (link.links) {
return <DropdownLinks link={link}/>
}
@ -85,13 +92,31 @@ function MenuLink({link}) {
</NavLink>
}
function DropdownMenuItem({link}) {
function DropdownMenuItem({link, nested = true}) {
// An item inside a Menu.Dropdown: the mobile hamburger menu, or the desktop
// "More" overflow menu.
// "More" overflow menu. `nested` allows flyout submenus, which the hamburger
// declines: a flyout opens on hover, and a phone has none.
if (link.bookmarks) {
if (nested) {
return <Menu.Sub>
<Menu.Sub.Target>
<Menu.Sub.Item>{link.text}</Menu.Sub.Item>
</Menu.Sub.Target>
<Menu.Sub.Dropdown>
<BookmarksMenuContents nested/>
</Menu.Sub.Dropdown>
</Menu.Sub>
}
return <React.Fragment>
<Menu.Divider/>
<Menu.Label>{link.text}</Menu.Label>
<BookmarksMenuContents nested={false}/>
<Menu.Divider/>
</React.Fragment>
}
if (link.links) {
// Mantine's Menu does not nest submenus without extra plumbing; a labelled,
// indented group stands in for one. No current data uses this path (no
// allLinks entry has its own `links`).
// A labelled, indented group stands in for a submenu here. No current data uses
// this path (no allLinks entry has its own `links`).
return <React.Fragment>
<Menu.Label>{link.text}</Menu.Label>
{link.links.map(l => <DropdownMenuItem key={l.key} link={l}/>)}
@ -175,6 +200,24 @@ function DropdownLinks({link}) {
</Menu>
}
/**
* The Bookmarks tab: a dropdown that opens on hover as well as on click, holding the
* user's bookmarks and the link to edit them. Marked current on the editor page only;
* a bookmark pointing at /videos does not make this tab own the Videos section.
*/
function BookmarksDropdown({link}) {
const {pathname} = useLocation();
const holdsCurrent = pathname === EDIT_BOOKMARKS_PATH || pathname.startsWith(`${EDIT_BOOKMARKS_PATH}/`);
return <Menu position='bottom-start' withinPortal trigger='click-hover' openDelay={100} closeDelay={200}>
<Menu.Target>
<NavDropdownTrigger text={link.text} className={holdsCurrent ? 'active' : undefined}/>
</Menu.Target>
<Menu.Dropdown>
<BookmarksMenuContents nested/>
</Menu.Dropdown>
</Menu>
}
function MobileMenu({links}) {
// The mobile hamburger menu: an icon-only trigger holding every link.
return <Menu position='bottom-end' withinPortal>
@ -182,7 +225,7 @@ function MobileMenu({links}) {
<IconButton icon={IconMenu2} label='Menu' variant='subtle'/>
</Menu.Target>
<Menu.Dropdown>
{links.map(link => <DropdownMenuItem key={link.key} link={link}/>)}
{links.map(link => <DropdownMenuItem key={link.key} link={link} nested={false}/>)}
</Menu.Dropdown>
</Menu>
}

View file

@ -231,3 +231,85 @@ describe('NavBar current tab', () => {
expect(ruleBody('\\.mantine-Menu-item\\.active')).toMatch(/background:|font-weight:/);
});
});
describe('NavBar bookmarks', () => {
const {BookmarksContext} = require('../contexts/BookmarksContext');
const bookmarks = [
{id: 1, name: 'Channels', url: '/videos/channel', new_tab: false},
{id: 2, name: 'Services', children: [{id: 3, name: 'Jellyfin', url: ':8096/', new_tab: true}]},
];
const renderWithBookmarks = (route, nodes) => render(<NavBar/>, {
route,
withMedia: true,
contexts: [
[FileWorkerStatusContext, fileWorkerStatus],
[BookmarksContext, {bookmarks: nodes, error: null, refresh: jest.fn()}],
],
});
it('sits between Calculators and Flasher', () => {
renderNav('/');
const texts = [...document.querySelectorAll('#global_navbar .wrolpi-navbar-link')]
.map(el => el.textContent.trim());
const at = texts.indexOf('Bookmarks');
expect(at).toBeGreaterThan(0);
expect(texts[at - 1]).toBe('Calculators');
expect(texts[at + 1]).toBe('Flasher');
});
it('opens on click with the bookmarks, a directory flyout, and the edit link', async () => {
useRealRects();
renderWithBookmarks('/', bookmarks);
await userEvent.click(screen.getByRole('button', {name: /Bookmarks/}));
const channels = await screen.findByRole('menuitem', {name: 'Channels'});
expect(channels).toHaveAttribute('href', '/videos/channel');
expect(channels).not.toHaveAttribute('target');
// A directory is a submenu; its bookmarks appear once it is hovered.
expect(screen.queryByRole('menuitem', {name: 'Jellyfin'})).not.toBeInTheDocument();
await userEvent.hover(screen.getByRole('menuitem', {name: 'Services'}));
// `hidden`: the flyout is placed by floating-ui, which jsdom cannot lay out, so it
// stays hidden to accessibility queries even though it has rendered.
const jellyfin = await screen.findByRole('menuitem', {name: 'Jellyfin', hidden: true});
expect(jellyfin).toHaveAttribute('href', `${window.location.protocol}//${window.location.hostname}:8096/`);
expect(jellyfin).toHaveAttribute('target', '_blank');
expect(screen.getByRole('menuitem', {name: 'Edit bookmarks', hidden: true})).toHaveAttribute('href', '/more/bookmarks');
});
it('offers the edit link even with no bookmarks, so the feature can be found', async () => {
useRealRects();
renderWithBookmarks('/', []);
await userEvent.click(screen.getByRole('button', {name: /Bookmarks/}));
expect(await screen.findByRole('menuitem', {name: 'Edit bookmarks'})).toBeInTheDocument();
expect(screen.getAllByRole('menuitem')).toHaveLength(1);
});
it('is marked current on the editor page, and never for a bookmark pointing at a section', () => {
renderWithBookmarks('/more/bookmarks', bookmarks);
expect(screen.getByRole('button', {name: /Bookmarks/})).toHaveClass('active');
expect(currentTab()).toEqual([]);
});
it('does not own the section a bookmark points at', () => {
renderWithBookmarks('/videos/channel', bookmarks);
expect(screen.getByRole('button', {name: /Bookmarks/})).not.toHaveClass('active');
expect(currentTab()).toEqual(['Videos']);
});
it('lists bookmarks as a labelled group in the mobile menu', async () => {
useViewport('mobile');
useRealRects();
renderWithBookmarks('/', bookmarks);
await userEvent.click(screen.getByRole('button', {name: 'Menu'}));
expect(await screen.findByRole('menuitem', {name: 'Channels'})).toBeInTheDocument();
// No flyout on a phone: the directory's bookmarks are listed directly.
expect(screen.getByRole('menuitem', {name: 'Jellyfin'})).toBeInTheDocument();
expect(screen.getByText('Services')).toBeInTheDocument();
expect(screen.getByRole('menuitem', {name: 'Edit bookmarks'})).toBeInTheDocument();
});
});

View file

@ -48,6 +48,7 @@ import {paletteColorNames} from '../themes/mantine';
import {contrastingColor} from './Common';
import {navBarStyle, navColorNames, useNavColors} from '../themes/navColors';
import {IconMenu2} from '@tabler/icons-react';
import {BookmarkAddForms, BookmarkMenuItems, BookmarkTable} from './Bookmarks';
/*
* A gallery of every component in the library, in the current theme.
@ -156,6 +157,19 @@ export const NavBarSample = ({color}) => {
// press adds a toast rather than replacing the first. Module scope, so it survives re-renders.
let toastCounter = 0;
// Sample data for the bookmarks section; the editor's actions do nothing here.
const sampleBookmarks = [
{id: 1, name: 'Channels', url: '/videos/channel', new_tab: false},
{id: 2, name: 'Services', children: [
{id: 3, name: 'Jellyfin', url: ':8096/', new_tab: true},
{id: 4, name: 'Radio', children: [
{id: 5, name: 'OpenWebRX', url: 'http://:8073/', new_tab: true},
]},
]},
{id: 6, name: 'WROLPi.org', url: 'https://wrolpi.org', new_tab: true},
];
const noBookmarkActions = {edit: () => null, move: () => null, remove: () => null};
export function ThemeSamplePage() {
const {theme, mediaFilterEnabled} = useContext(ThemeContext);
const [confirmOpen, setConfirmOpen] = useState(false);
@ -1078,6 +1092,41 @@ export function ThemeSamplePage() {
</Panel>
</Section>
<Section label='Bookmarks'>
<Panel>
<p style={{fontSize: '0.75rem', color: 'var(--muted)', marginTop: 0}}>
The Bookmarks menu in the navigation bar, and the editor under More. A
directory is a flyout that opens beside the menu. In the mobile menu it is a
labelled, indented run of items instead.
</p>
<Row>
<Menu position='bottom-start' withinPortal trigger='click-hover'>
<Menu.Target>
<Button iconAfter='dropdown'>Bookmarks</Button>
</Menu.Target>
<Menu.Dropdown>
<BookmarkMenuItems nodes={sampleBookmarks}/>
<Menu.Divider/>
<Menu.Item leftSection={<Icon name='edit' size='small'/>}>Edit bookmarks</Menu.Item>
</Menu.Dropdown>
</Menu>
<Menu position='bottom-start' withinPortal>
<Menu.Target>
<Button iconAfter='dropdown'>As the mobile menu shows it</Button>
</Menu.Target>
<Menu.Dropdown>
<Menu.Label>Bookmarks</Menu.Label>
<BookmarkMenuItems nodes={sampleBookmarks} nested={false}/>
</Menu.Dropdown>
</Menu>
</Row>
<div style={{marginTop: 12}}>
<BookmarkTable nodes={sampleBookmarks} actions={noBookmarkActions}/>
<BookmarkAddForms nodes={sampleBookmarks} onAddBookmark={() => null} onAddDirectory={() => null}/>
</div>
</Panel>
</Section>
<Section label='Danger zone'>
<Panel danger>
<h2 style={{color: 'var(--danger)', fontSize: '0.875rem', margin: '0 0 4px'}}>Danger zone</h2>

View file

@ -0,0 +1,65 @@
import React, {createContext, useCallback, useContext, useEffect, useState} from 'react';
import {getBookmarks} from '../api';
/*
* The user's bookmarks, shared by the navigation bar and the editor page.
*
* A context rather than a prop: the bar and the page are far apart in the tree, and an
* edit on the page must show in the bar at once. `bookmarks` is null until the first
* fetch answers, so the bar can tell "not loaded yet" from "the user has none".
*/
export const BookmarksContext = createContext({bookmarks: null, error: null, refresh: async () => null});
export function BookmarksProvider({children}) {
const [bookmarks, setBookmarks] = useState(null);
const [error, setError] = useState(null);
const refresh = useCallback(async () => {
try {
setBookmarks(await getBookmarks());
setError(null);
} catch (err) {
setError(err);
}
}, []);
useEffect(() => {
refresh();
}, [refresh]);
return <BookmarksContext.Provider value={{bookmarks, error, refresh}}>
{children}
</BookmarksContext.Provider>;
}
export function useBookmarks() {
return useContext(BookmarksContext);
}
export const isBookmarkDirectory = (node) => Array.isArray(node.children);
/**
* Where a bookmark URL really points, from the browser's point of view.
*
* Three forms are accepted, and only the first is an in-app link:
* `/videos/channel/3` a path on this WROLPi -> {internal: true, href: '/videos/channel/3'}
* `:8096/web` a port on this host, using the page's scheme
* `http://:8096/web` a port on this host, with its own scheme
* `https://example.com` anything else, verbatim
*
* The host-relative forms exist because a WROLPi is reached by LAN IP, by mDNS name, and
* by its hotspot address, and a service running beside it is reached the same way. A
* bookmark with the hostname written in would work from only one of them.
*/
export function resolveBookmarkUrl(url, location = window.location) {
const value = (url || '').trim();
if (value.startsWith('/')) {
return {internal: true, href: value};
}
const hostRelative = value.match(/^(?:(https?:)\/\/)?(:\d+.*)$/i);
if (hostRelative) {
const scheme = hostRelative[1] ? hostRelative[1].toLowerCase() : location.protocol;
return {internal: false, href: `${scheme}//${location.hostname}${hostRelative[2]}`};
}
return {internal: false, href: value};
}