Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(gallery): select several items, act on them by menu or bar (D3, 3.0.9)

purple1f57522b29ea
diff --git a/src/components/create/experimental/CreatePanel.tsx b/src/components/create/experimental/CreatePanel.tsx
index f42fc8c9..39e7962b 100644
--- a/src/components/create/experimental/CreatePanel.tsx
+++ b/src/components/create/experimental/CreatePanel.tsx
@@ -1,7 +1,7 @@
import { itemHasAlpha } from '../../../lib/transparent-image'
-import { useState } from 'react'
+import { useState, type MouseEvent as ReactMouseEvent } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
-import { Images, Play, PanelRightClose, Trash2, Download, MonitorOff, AudioLines, FolderInput } from 'lucide-react'
+import { Images, Play, PanelRightClose, Trash2, Download, MonitorOff, AudioLines, FolderInput, Check, X } from 'lucide-react'
import { useCreateStore, type GalleryItem } from '../../../stores/createStore'
import { galleryLabel } from '../../../lib/render/gallery-label'
import { GALLERY_DRAG_TYPE, playsAsVideo } from './galleryUrl'
@@ -12,6 +12,13 @@ import { useComfyMedia } from './useComfyMedia'
import { cn } from '../ui/cn'
import { itemsInFolder } from '../../../lib/gallery-folders'
import { FolderFilter, MoveToFolderModal, OnBody } from './GalleryFolders'
+import { ContextMenu } from '../../ui/ContextMenu'
+import { Modal } from '../../ui/Modal'
+import { ModalActions, ModalButton } from '../../ui/ModalActions'
+import {
+ EMPTY_SELECTION, buildGalleryMenu, clickSelection, deleteConfirmLine, keepShown, menuSelection, selectAll,
+ type GallerySelection,
+} from './gallerySelection'
interface Props {
open: boolean
@@ -34,6 +41,55 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {
const gallery = folderOpen === null ? all : itemsInFolder(all, folderOpen)
const [moving, setMoving] = useState<string[]>([])
const count = gallery.length
+ // Several at once (D3, 3.0.9): Cmd/Ctrl-click, Shift range, Cmd/Ctrl+A,
+ // Escape. The menu and the bar act on `sel.ids` with the tile's own code.
+ const [stored, setSel] = useState<GallerySelection>(EMPTY_SELECTION)
+ const [menu, setMenu] = useState<{ x: number; y: number; ids: readonly string[] } | null>(null)
+ const [confirming, setConfirming] = useState<readonly string[]>([])
+ const order = gallery.map((g) => g.id)
+ // Items no longer shown (another folder, deleted) are not selected.
+ const sel = keepShown(stored, order)
+ const picked = new Set(sel.ids)
+ const selecting = sel.ids.length > 0
+
+ const onTileClick = (e: ReactMouseEvent, id: string) => {
+ const mods = { toggle: e.metaKey || e.ctrlKey, range: e.shiftKey }
+ setSel(clickSelection(sel, order, id, mods))
+ if (!mods.toggle && !mods.range) onSelect(id)
+ }
+ const onTileMenu = (e: ReactMouseEvent, id: string) => {
+ e.preventDefault()
+ const next = menuSelection(sel, id)
+ setSel(next)
+ setMenu({ x: e.clientX, y: e.clientY, ids: next.ids })
+ }
+ const onGridKey = (e: React.KeyboardEvent) => {
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'a' && order.length > 0) {
+ e.preventDefault()
+ setSel(selectAll(order))
+ } else if (e.key === 'Escape' && selecting) {
+ e.stopPropagation()
+ setSel(EMPTY_SELECTION)
+ }
+ }
+ // The same ways a single tile goes: the move dialog, downloadGalleryItem
+ // (one Save dialog after the other), removeFromGallery after the question.
+ const downloadAll = async (ids: readonly string[]) => {
+ for (const id of ids) {
+ const g = useCreateStore.getState().gallery.find((x) => x.id === id)
+ if (g) await downloadGalleryItem(g)
+ }
+ }
+ const deleteAll = () => {
+ for (const id of confirming) removeFromGallery(id)
+ setConfirming([])
+ setSel(EMPTY_SELECTION)
+ }
+ const actionsFor = (ids: readonly string[]) => ({
+ move: () => setMoving([...ids]),
+ download: () => { void downloadAll(ids) },
+ remove: () => setConfirming(ids),
+ })
const bubble =
'my-2 mr-2 rounded-xl bg-gray-50 dark:bg-[#1e1e1e] ring-1 ring-black/[0.04] dark:ring-white/[0.05] flex flex-col overflow-hidden shrink-0'
@@ -110,16 +166,54 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {
<FolderFilter />
<OnBody><MoveToFolderModal ids={moving} onClose={() => setMoving([])} /></OnBody>
+ <OnBody>
+ <Modal open={confirming.length > 0} onClose={() => setConfirming([])} title="Delete from the gallery" maxWidth="max-w-md">
+ <div data-testid="gallery-delete-confirm">
+ <p className="t-body">{deleteConfirmLine(confirming.length, isMlxImageHost())}</p>
+ <ModalActions>
+ <ModalButton onClick={() => setConfirming([])}>Cancel</ModalButton>
+ <ModalButton variant="danger" onClick={deleteAll}>
+ {confirming.length > 1 ? `Delete ${confirming.length}` : 'Delete'}
+ </ModalButton>
+ </ModalActions>
+ </div>
+ </Modal>
+ </OnBody>
+ {menu && (
+ <ContextMenu
+ items={buildGalleryMenu(actionsFor(menu.ids), menu.ids.length)}
+ x={menu.x}
+ y={menu.y}
+ label={menu.ids.length > 1 ? `Actions for ${menu.ids.length} items` : 'Actions for this item'}
+ onClose={() => setMenu(null)}
+ />
+ )}
+ {selecting && (
+ <div
+ role="toolbar"
+ aria-label="Selected items"
+ className="flex items-center gap-1 px-3 py-1.5 border-b border-gray-200 dark:border-white/[0.05] shrink-0"
+ >
+ <span className="t-label text-gray-500 dark:text-gray-400 mr-auto" aria-live="polite">{sel.ids.length} selected</span>
+ <BarBtn title="Move to folder" onClick={actionsFor(sel.ids).move}><FolderInput size={13} /></BarBtn>
+ <BarBtn title="Download" onClick={actionsFor(sel.ids).download}><Download size={13} /></BarBtn>
+ <BarBtn title="Delete" danger onClick={actionsFor(sel.ids).remove}><Trash2 size={13} /></BarBtn>
+ <BarBtn title="Clear selection" onClick={() => setSel(EMPTY_SELECTION)}><X size={13} /></BarBtn>
+ </div>
+ )}
<div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin p-3">
{count === 0 ? (
<p className="t-body text-gray-500 py-2">{all.length > 0 ? 'Nothing in this folder yet.' : 'Nothing generated yet.'}</p>
) : (
- <div className="grid grid-cols-2 gap-2">
+ <div className="grid grid-cols-2 gap-2" role="group" aria-label="Gallery items" onKeyDown={onGridKey}>
{gallery.map((g) => (
<div key={g.id} className="relative group">
<button
- onClick={() => onSelect(g.id)}
+ onClick={(e) => onTileClick(e, g.id)}
+ onContextMenu={(e) => onTileMenu(e, g.id)}
+ data-gallery-id={g.id}
+ aria-pressed={selecting ? picked.has(g.id) : undefined}
title={g.sourceName ? `From ${g.sourceName}` : undefined}
draggable={g.type === 'image' && !g.unavailable}
onDragStart={(e) => {
@@ -128,7 +222,9 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {
}}
className={cn(
'w-full aspect-square rounded-lg overflow-hidden border-2 transition-colors relative',
- (activeId ?? gallery[0]?.id) === g.id ? 'border-gray-900/60 dark:border-white/60' : 'border-transparent hover:border-white/20',
+ picked.has(g.id)
+ ? 'border-blue-500 dark:border-blue-400'
+ : (activeId ?? gallery[0]?.id) === g.id ? 'border-gray-900/60 dark:border-white/60' : 'border-transparent hover:border-white/20',
itemHasAlpha(g) && 'lu-checker',
)}
>
@@ -141,6 +237,11 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {
<MonitorOff size={16} />
</span>
)}
+ {picked.has(g.id) && (
+ <span className="lu-on-dark absolute top-1 left-1 w-5 h-5 rounded-full bg-blue-500 text-white flex items-center justify-center shadow-sm" aria-hidden>
+ <Check size={12} />
+ </span>
+ )}
</button>
<button
onClick={() => removeFromGallery(g.id)}
@@ -174,6 +275,22 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {
)
}
+function BarBtn({ children, title, onClick, danger }: { children: React.ReactNode; title: string; onClick: () => void; danger?: boolean }) {
+ return (
+ <button
+ onClick={onClick}
+ title={title}
+ aria-label={title}
+ className={cn(
+ 'flex items-center justify-center w-6 h-6 rounded text-gray-500 hover:bg-gray-100 dark:hover:bg-white/5 transition-colors',
+ danger ? 'hover:text-red-600 dark:hover:text-red-400' : 'hover:text-gray-800 dark:hover:text-gray-200',
+ )}
+ >
+ {children}
+ </button>
+ )
+}
+
// One thumbnail. Its own component so it can use the useComfyMedia hook (which
// falls back to the Rust proxy when a user-managed ComfyUI 0.19+ 403s the
// direct /view load, #75) — hooks can't run inside the gallery .map().
diff --git a/src/components/create/experimental/__tests__/galerie-mehrfachauswahl.test.tsx b/src/components/create/experimental/__tests__/galerie-mehrfachauswahl.test.tsx
new file mode 100644
index 00000000..ff32d7f4
--- /dev/null
+++ b/src/components/create/experimental/__tests__/galerie-mehrfachauswahl.test.tsx
@@ -0,0 +1,169 @@
+// @vitest-environment jsdom
+/**
+ * D3 (3.0.9, Discord 01.11.2026): several images and videos at once in the
+ * Create gallery. Cmd/Ctrl-click, Shift range, Cmd/Ctrl+A, Escape; then the
+ * right-click menu or the bar above the grid: move to a folder, download,
+ * delete. Only what a single tile already does, through the same code
+ * (removeFromGallery, the move dialog, downloadGalleryItem). Delete asks
+ * first and names the count.
+ *
+ * Run: npx vitest run src/components/create/experimental/__tests__/galerie-mehrfachauswahl.test.tsx
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+
+vi.mock('../CreateContext', () => ({
+ useCreateExp: () => ({ quota: null, enhanceVideo: vi.fn() }),
+}))
+vi.mock('../useComfyMedia', () => ({
+ useComfyMedia: () => ({ src: 'blob:media', onError: vi.fn(), onLoad: vi.fn() }),
+}))
+vi.mock('../../../../api/mlx-image', () => ({ isMlxImageHost: () => false, MLX_MODEL_PREFIX: 'MLX ' }))
+const trash = vi.hoisted(() => vi.fn(async () => null))
+vi.mock('../../../../lib/gallery-trash', () => ({ trashGalleryFile: trash }))
+const download = vi.hoisted(() => vi.fn(async () => {}))
+vi.mock('../galleryDownload', () => ({ downloadGalleryItem: download }))
+
+import { useCreateStore, type GalleryItem } from '../../../../stores/createStore'
+import { CreatePanel } from '../CreatePanel'
+
+const ITEM = (id: string, extra: Partial<GalleryItem> = {}): GalleryItem => ({
+ id, type: 'image', filename: `${id}.png`, subfolder: '', prompt: `prompt ${id}`, negativePrompt: '',
+ model: 'm.safetensors', modelType: 'sdxl', seed: 1, steps: 20, cfgScale: 5, sampler: 'euler',
+ scheduler: 'normal', width: 512, height: 512, batchSize: 1, createdAt: 1, ...extra,
+})
+
+const st = () => useCreateStore.getState()
+const onSelect = vi.fn()
+
+beforeEach(() => {
+ trash.mockClear()
+ download.mockClear()
+ onSelect.mockClear()
+ useCreateStore.setState({
+ backend: 'local',
+ gallery: [ITEM('a'), ITEM('b'), ITEM('c', { type: 'video', filename: 'c.mp4' }), ITEM('d')],
+ galleryFolders: [{ id: 'f-1', name: 'Portraits' }],
+ galleryFolderOpen: null,
+ })
+})
+const ownRemove = useCreateStore.getState().removeFromGallery
+afterEach(() => { cleanup(); useCreateStore.setState({ removeFromGallery: ownRemove }) })
+
+const panel = () => render(<CreatePanel open onOpenChange={() => {}} activeId={null} onSelect={onSelect} />)
+const tile = (id: string) => document.querySelector(`[data-gallery-id="${id}"]`) as HTMLElement
+const selected = () => [...document.querySelectorAll('[data-gallery-id][aria-pressed="true"]')].map((e) => e.getAttribute('data-gallery-id'))
+const bar = () => screen.queryByRole('toolbar', { name: 'Selected items' })
+
+describe('selecting', () => {
+ it('Cmd/Ctrl-click picks several without opening any', () => {
+ panel()
+ fireEvent.click(tile('a'), { metaKey: true })
+ fireEvent.click(tile('c'), { ctrlKey: true })
+ expect(selected()).toEqual(['a', 'c'])
+ expect(onSelect).not.toHaveBeenCalled()
+ expect(bar()!.textContent).toContain('2 selected')
+ })
+
+ it('Shift-click takes the range from the last clicked item', () => {
+ panel()
+ fireEvent.click(tile('a'))
+ expect(onSelect).toHaveBeenCalledWith('a')
+ fireEvent.click(tile('c'), { shiftKey: true })
+ expect(selected()).toEqual(['a', 'b', 'c'])
+ })
+
+ it('Cmd/Ctrl+A selects all shown, Escape clears', () => {
+ panel()
+ fireEvent.keyDown(tile('b'), { key: 'a', metaKey: true })
+ expect(selected()).toEqual(['a', 'b', 'c', 'd'])
+ fireEvent.keyDown(tile('b'), { key: 'Escape' })
+ expect(selected()).toEqual([])
+ expect(bar()).toBeNull()
+ })
+
+ it('a plain click opens the item and drops the selection', () => {
+ panel()
+ fireEvent.click(tile('a'), { metaKey: true })
+ fireEvent.click(tile('d'))
+ expect(selected()).toEqual([])
+ expect(onSelect).toHaveBeenCalledWith('d')
+ })
+})
+
+describe('the right-click menu', () => {
+ it('on a selected tile acts on all selected, and names the count', () => {
+ panel()
+ fireEvent.click(tile('a'), { metaKey: true })
+ fireEvent.click(tile('b'), { metaKey: true })
+ fireEvent.contextMenu(tile('b'), { clientX: 40, clientY: 40 })
+ const menu = screen.getByRole('menu')
+ expect(within(menu).getAllByRole('menuitem').map((m) => m.textContent)).toEqual(['Move 2 to folder…', 'Download 2', 'Delete 2…'])
+ })
+
+ it('on an unselected tile acts on that tile alone', () => {
+ panel()
+ fireEvent.click(tile('a'), { metaKey: true })
+ fireEvent.contextMenu(tile('d'), { clientX: 40, clientY: 40 })
+ expect(selected()).toEqual(['d'])
+ expect(within(screen.getByRole('menu')).getAllByRole('menuitem').map((m) => m.textContent)).toEqual(['Move to folder…', 'Download', 'Delete…'])
+ })
+
+ it('Delete asks with the count first; Cancel keeps everything', () => {
+ panel()
+ fireEvent.click(tile('a'), { metaKey: true })
+ fireEvent.click(tile('c'), { metaKey: true })
+ fireEvent.contextMenu(tile('a'), { clientX: 40, clientY: 40 })
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Delete 2…' }))
+ const dialog = screen.getByTestId('gallery-delete-confirm')
+ expect(dialog.textContent).toContain('Delete 2 items? Their files move to the Recycle Bin.')
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))
+ expect(st().gallery.map((g) => g.id)).toEqual(['a', 'b', 'c', 'd'])
+ expect(trash).not.toHaveBeenCalled()
+ })
+
+ it('confirmed, each goes the single tile\'s way (removeFromGallery → trash)', async () => {
+ // The tile's own delete, wrapped to see each call. (The trash mock alone
+ // misses the second of two same-tick dynamic imports under vitest.)
+ const own = st().removeFromGallery
+ const removed: string[] = []
+ useCreateStore.setState({ removeFromGallery: (id: string) => { removed.push(id); own(id) } })
+ panel()
+ fireEvent.click(tile('a'), { metaKey: true })
+ fireEvent.click(tile('c'), { metaKey: true })
+ fireEvent.contextMenu(tile('a'), { clientX: 40, clientY: 40 })
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Delete 2…' }))
+ fireEvent.click(within(screen.getByTestId('gallery-delete-confirm')).getByRole('button', { name: 'Delete 2' }))
+ expect(st().gallery.map((g) => g.id)).toEqual(['b', 'd'])
+ expect(removed).toEqual(['a', 'c'])
+ await waitFor(() => expect(trash).toHaveBeenCalled())
+ expect(selected()).toEqual([])
+ })
+})
+
+describe('the bar', () => {
+ it('moves all selected into a folder with the existing dialog', () => {
+ panel()
+ fireEvent.click(tile('b'), { metaKey: true })
+ fireEvent.click(tile('d'), { metaKey: true })
+ fireEvent.click(within(bar()!).getByRole('button', { name: 'Move to folder' }))
+ fireEvent.click(within(screen.getByTestId('move-to-folder')).getByRole('button', { name: 'Move' }))
+ expect(st().gallery.filter((g) => g.folderId === 'f-1').map((g) => g.id)).toEqual(['b', 'd'])
+ })
+
+ it('downloads each selected through downloadGalleryItem, one after the other', async () => {
+ panel()
+ fireEvent.click(tile('a'), { metaKey: true })
+ fireEvent.click(tile('c'), { metaKey: true })
+ fireEvent.click(within(bar()!).getByRole('button', { name: 'Download' }))
+ await waitFor(() => expect(download).toHaveBeenCalledTimes(2))
+ expect(download.mock.calls.map((c) => (c as unknown as [GalleryItem])[0].id)).toEqual(['a', 'c'])
+ })
+
+ it('Clear selection empties it', () => {
+ panel()
+ fireEvent.click(tile('a'), { metaKey: true })
+ fireEvent.click(within(bar()!).getByRole('button', { name: 'Clear selection' }))
+ expect(selected()).toEqual([])
+ })
+})
diff --git a/src/components/create/experimental/__tests__/gallery-selection.test.ts b/src/components/create/experimental/__tests__/gallery-selection.test.ts
new file mode 100644
index 00000000..cacdf8f3
--- /dev/null
+++ b/src/components/create/experimental/__tests__/gallery-selection.test.ts
@@ -0,0 +1,86 @@
+/**
+ * D3 (3.0.9, Discord 01.11.2026): several gallery items at once. The rules
+ * of the selection (Cmd/Ctrl-click, Shift range, all, none) and the menu that
+ * acts on it, as pure functions.
+ *
+ * Run: npx vitest run src/components/create/experimental/__tests__/gallery-selection.test.ts
+ */
+import { describe, expect, it, vi } from 'vitest'
+import {
+ EMPTY_SELECTION,
+ buildGalleryMenu,
+ clickSelection,
+ deleteConfirmLine,
+ menuSelection,
+ selectAll,
+} from '../gallerySelection'
+
+const ORDER = ['a', 'b', 'c', 'd', 'e']
+
+describe('clicking tiles', () => {
+ it('a plain click selects nothing: it opens the item, as before, and sets the anchor', () => {
+ const s = clickSelection(EMPTY_SELECTION, ORDER, 'b', { toggle: false, range: false })
+ expect(s).toEqual({ ids: [], anchor: 'b' })
+ })
+
+ it('Cmd/Ctrl-click adds and removes one item', () => {
+ let s = clickSelection(EMPTY_SELECTION, ORDER, 'b', { toggle: true, range: false })
+ s = clickSelection(s, ORDER, 'd', { toggle: true, range: false })
+ expect(s.ids).toEqual(['b', 'd'])
+ s = clickSelection(s, ORDER, 'b', { toggle: true, range: false })
+ expect(s.ids).toEqual(['d'])
+ })
+
+ it('Shift-click selects the range from the anchor, in gallery order, both ways', () => {
+ const anchored = clickSelection(EMPTY_SELECTION, ORDER, 'b', { toggle: false, range: false })
+ expect(clickSelection(anchored, ORDER, 'd', { toggle: false, range: true }).ids).toEqual(['b', 'c', 'd'])
+ const fromD = clickSelection(EMPTY_SELECTION, ORDER, 'd', { toggle: true, range: false })
+ expect(clickSelection(fromD, ORDER, 'a', { toggle: false, range: true }).ids).toEqual(['a', 'b', 'c', 'd'])
+ })
+
+ it('Shift without an anchor selects just that item', () => {
+ expect(clickSelection(EMPTY_SELECTION, ORDER, 'c', { toggle: false, range: true }).ids).toEqual(['c'])
+ })
+
+ it('a plain click while a selection stands clears it', () => {
+ const s = clickSelection({ ids: ['a', 'b'], anchor: 'a' }, ORDER, 'e', { toggle: false, range: false })
+ expect(s.ids).toEqual([])
+ })
+
+ it('all selects every shown item; ids no longer shown fall out', () => {
+ expect(selectAll(ORDER).ids).toEqual(ORDER)
+ })
+})
+
+describe('the right-click', () => {
+ it('on a selected item acts on the whole selection', () => {
+ expect(menuSelection({ ids: ['a', 'c'], anchor: 'a' }, 'c').ids).toEqual(['a', 'c'])
+ })
+ it('on another item acts on that item alone', () => {
+ expect(menuSelection({ ids: ['a', 'c'], anchor: 'a' }, 'b')).toEqual({ ids: ['b'], anchor: 'b' })
+ })
+})
+
+describe('the menu', () => {
+ const h = { move: vi.fn(), download: vi.fn(), remove: vi.fn() }
+
+ it('offers exactly the single-item actions, run by the caller', () => {
+ const one = buildGalleryMenu(h, 1)
+ expect(one.map((m) => m.label)).toEqual(['Move to folder…', 'Download', 'Delete…'])
+ expect(one[0].run).toBe(h.move)
+ expect(one[1].run).toBe(h.download)
+ expect(one[2].run).toBe(h.remove)
+ expect(one[2].destructive).toBe(true)
+ })
+
+ it('names the count for several', () => {
+ expect(buildGalleryMenu(h, 3).map((m) => m.label)).toEqual(['Move 3 to folder…', 'Download 3', 'Delete 3…'])
+ })
+})
+
+describe('the delete question', () => {
+ it('names the count and where the files go, per host', () => {
+ expect(deleteConfirmLine(1, false)).toBe('Delete 1 item? Its file moves to the Recycle Bin.')
+ expect(deleteConfirmLine(4, true)).toBe('Delete 4 items? Their files move to the Trash.')
+ })
+})
diff --git a/src/components/create/experimental/gallerySelection.ts b/src/components/create/experimental/gallerySelection.ts
new file mode 100644
index 00000000..badb3763
--- /dev/null
+++ b/src/components/create/experimental/gallerySelection.ts
@@ -0,0 +1,91 @@
+// Several gallery items at once (D3, 3.0.9, Discord 01.11.2026): the rules of
+// the selection and the menu that acts on it, as pure functions. The menu
+// offers only what a single tile already does and runs the caller's
+// functions (components/ui/menu-actions.ts has the rule); CreatePanel hands in
+// the same code its tile buttons use.
+
+import type { MenuAction } from '../../ui/menu-actions'
+
+export interface GallerySelection {
+ /** Selected ids, in gallery order. */
+ readonly ids: readonly string[]
+ /** The last clicked item, where a Shift range starts. */
+ readonly anchor: string | null
+}
+
+export const EMPTY_SELECTION: GallerySelection = { ids: [], anchor: null }
+
+export interface ClickMods {
+ /** Cmd on a Mac, Ctrl elsewhere. */
+ readonly toggle: boolean
+ readonly range: boolean
+}
+
+const inOrder = (order: readonly string[], ids: ReadonlySet<string>) => order.filter((id) => ids.has(id))
+
+/**
+ * The selection after a click on `id`. A plain click selects nothing (it opens
+ * the item, as it always did) and only moves the anchor.
+ */
+export function clickSelection(
+ prev: GallerySelection,
+ order: readonly string[],
+ id: string,
+ mods: ClickMods,
+): GallerySelection {
+ if (mods.range) {
+ const from = prev.anchor ? order.indexOf(prev.anchor) : -1
+ const to = order.indexOf(id)
+ if (from < 0 || to < 0) return { ids: [id], anchor: id }
+ const [lo, hi] = from < to ? [from, to] : [to, from]
+ return { ids: order.slice(lo, hi + 1), anchor: prev.anchor }
+ }
+ if (mods.toggle) {
+ const next = new Set(prev.ids)
+ if (next.has(id)) next.delete(id)
+ else next.add(id)
+ return { ids: inOrder(order, next), anchor: id }
+ }
+ return { ids: [], anchor: id }
+}
+
+export function selectAll(order: readonly string[]): GallerySelection {
+ return { ids: [...order], anchor: order[0] ?? null }
+}
+
+/** A right-click on a selected item acts on the selection, on any other on that item alone. */
+export function menuSelection(prev: GallerySelection, id: string): GallerySelection {
+ return prev.ids.includes(id) ? prev : { ids: [id], anchor: id }
+}
+
+/** Ids that are no longer shown (another folder, deleted) drop out. */
+export function keepShown(prev: GallerySelection, order: readonly string[]): GallerySelection {
+ const shown = new Set(order)
+ const ids = prev.ids.filter((id) => shown.has(id))
+ const anchor = prev.anchor && shown.has(prev.anchor) ? prev.anchor : null
+ return ids.length === prev.ids.length && anchor === prev.anchor ? prev : { ids, anchor }
+}
+
+export interface GalleryMenuHandlers {
+ readonly move: () => void
+ readonly download: () => void
+ /** Opens the question; nothing is deleted before it is answered. */
+ readonly remove: () => void
+}
+
+export function buildGalleryMenu(h: GalleryMenuHandlers, count: number): MenuAction[] {
+ const n = count > 1 ? ` ${count}` : ''
+ return [
+ { id: 'move', label: count > 1 ? `Move${n} to folder…` : 'Move to folder…', run: h.move },
+ { id: 'download', label: `Download${n}`, run: h.download },
+ { id: 'delete', label: `Delete${n}…`, run: h.remove, destructive: true },
+ ]
+}
+
+/** The question before deleting. Where the files go, as deleteTitle says it per host. */
+export function deleteConfirmLine(count: number, mac: boolean): string {
+ const bin = mac ? 'the Trash' : 'the Recycle Bin'
+ return count === 1
+ ? `Delete 1 item? Its file moves to ${bin}.`
+ : `Delete ${count} items? Their files move to ${bin}.`
+}