diff --git a/README.md b/README.md index fb2a911..4391a9e 100644 --- a/README.md +++ b/README.md @@ -178,14 +178,14 @@ a required BuildKit secret, never through build arguments or committed files. ## Catalog and release -The next app release is **0.1.16**, also recorded in `web/package.json`. +The next app release is **0.1.17**, also recorded in `web/package.json`. `catalog/entry.yaml` carries no committed version: the first tag (`v0.1.0`) created `versions[]` with `ghcr.io/appthrust/tracker@sha256:`, stream `0.1`; later tags append at publication time. Do not add a version with an unbuilt or placeholder image digest. OpenAPI's `info.version` describes the API schema, not the app release. This repository has no hand-maintained changelog. -After the release prerequisites are available, push the SemVer tag `v0.1.16`. +After the release prerequisites are available, push the SemVer tag `v0.1.17`. The tag workflow: 1. Performs one multi-platform build on `ubuntu-24.04` for Linux amd64 and arm64, @@ -205,8 +205,8 @@ The tag workflow: Publication commands used by the workflow: ```sh -bun hack/publish-entry.ts submit --version 0.1.16 --digest sha256: -bun hack/publish-entry.ts await --version 0.1.16 --digest sha256: +bun hack/publish-entry.ts submit --version 0.1.17 --digest sha256: +bun hack/publish-entry.ts await --version 0.1.17 --digest sha256: ``` Writers are serialized by `tracker-catalog-publish`; the workflow is guarded to @@ -227,7 +227,7 @@ After publication, each estate's `AppCatalogSource` syncs the signed catalog. Install Issues from the Project Marketplace (Directory is an automatic dependency). Existing `follow` installations on stream `0.1` roll to the new version; `pinned` installations show `UpdateAvailable` and require an explicit -version update. Confirm the installation is Ready, `/releasez` reports `0.1.16`, +version update. Confirm the installation is Ready, `/releasez` reports `0.1.17`, the Project lists the `tracker` Access Key space as Ready, and an exchanged key reads `/api/tracker/v1/me`. These are release steps, not actions performed by a source-only version bump. diff --git a/cmd/server/internal/api/openapi.json b/cmd/server/internal/api/openapi.json index f919198..273e09f 100644 --- a/cmd/server/internal/api/openapi.json +++ b/cmd/server/internal/api/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.1.0", "info": { "title": "Tracker API", - "version": "0.1.16", + "version": "0.1.17", "description": "Contract: design/API.md. One workspace per PLATFORM_PROJECT_ID. The bearer is the signed-in user's token or an Access Key assertion (audience tracker; scope tracker:read for GET, tracker:write otherwise). External-subject assertions resolve by immutable registered agent handle. GET scopes tracker:read; other methods tracker:write; missing scope is 403 insufficient_scope. Every key is refused on Admin routes. See /agent-guide for the collaboration protocol." }, "servers": [ diff --git a/design/README.md b/design/README.md index 7ce2f8c..b23f00d 100644 --- a/design/README.md +++ b/design/README.md @@ -212,6 +212,45 @@ not a prerequisite. - Freshness: TanStack Query with optimistic updates and 15 s refetch on focus/interval. No websockets in v1. +### Issue panel tabs (v0.1.17) + +The side panel showed one issue; opening another replaced it. It now keeps the +issues a person opened as tabs, so several can be compared and returned to. + +| Concept | Owner | Lifetime | Invariants | +| --- | --- | --- | --- | +| **Active issue** | the URL (`?issue=`, unchanged) | the history entry | the panel is open iff `issue` is set; links, reload and back/forward keep working as before | +| **Open tabs** | the browser tab (`sessionStorage`), not the URL and not the server | until closed or the browser tab ends | ordered, no duplicates (identifiers compared upper-cased), at most 20; the active issue is always one of them | + +Open tabs are a person's working set, not part of what a link means: a shared +link opens one issue, never someone else's tab strip. + +Rules (pure, `web/src/model/panel-tabs.ts`): + +- **Open** (click or `Enter` on a row/card, a URL with `issue`): the issue + becomes active; if it has no tab, one is appended to the right of the + previously active tab. A 21st tab evicts the least recently active one. + The command palette and links inside an issue (parent, children, blockers) + still go to the issue's full page, as before. +- **Browse** (`J`/`K`, arrows while the panel is open): the active tab's issue + is replaced in place, so walking a list does not leave a trail of tabs. When + the issue walked onto already has a tab, that tab becomes active instead and + nothing is replaced: browsing never closes a tab. +- **Close a tab** (its ×, middle click; `Esc` closes the active one): closing + the active tab activates the one to its right, else the one to its left; + closing the only tab closes the panel. Closing any other tab leaves the + active one alone. +- **Close the panel** (the panel's ×): every tab closes. +- A URL whose `issue` has no tab (deep link, back/forward to a closed issue) + opens it as a tab. Tabs survive moving between list pages, the board, a + sprint and the inbox; a page opened without `issue` shows no panel, and the + next open brings the strip back. +- A tab whose issue was deleted or is unknown shows the not-found state and + can be closed. + +Only the active tab's issue is fetched and rendered; a tab is its identifier +plus the title last seen, so twenty tabs cost nothing until selected. + ## Lifecycle 1. Tag `v0.1.0` in `appthrust/tracker` → `publish.yml` builds the image, diff --git a/web/package.json b/web/package.json index b5e3259..8219559 100644 --- a/web/package.json +++ b/web/package.json @@ -1,6 +1,6 @@ { "name": "@appthrust/tracker", - "version": "0.1.16", + "version": "0.1.17", "private": true, "type": "module", "scripts": { diff --git a/web/src/copy/issues.ts b/web/src/copy/issues.ts index cc3060d..bee7421 100644 --- a/web/src/copy/issues.ts +++ b/web/src/copy/issues.ts @@ -127,7 +127,9 @@ export const issueMessages = defineDashboardMessages({ 'tracker.issue.properties': { defaultMessage: 'Properties', translations: { ja: 'プロパティ' } }, 'tracker.issue.panel': { defaultMessage: 'Issue {identifier}', translations: { ja: '課題 {identifier}' } }, 'tracker.issue.openFull': { defaultMessage: 'Open full page', translations: { ja: '全画面で開く' } }, - 'tracker.issue.closePanel': { defaultMessage: 'Close panel', translations: { ja: 'パネルを閉じる' } }, + 'tracker.issue.tabs': { defaultMessage: 'Opened issues', translations: { ja: '開いている課題' } }, + 'tracker.issue.closeTab': { defaultMessage: 'Close {identifier}', translations: { ja: '{identifier} を閉じる' } }, + 'tracker.issue.closeAllTabs': { defaultMessage: 'Close all tabs', translations: { ja: 'すべてのタブを閉じる' } }, 'tracker.issue.notFoundTitle': { defaultMessage: '{identifier} not found', translations: { ja: '{identifier} が見つかりません' } }, 'tracker.issue.notFoundBody': { defaultMessage: 'It may have been deleted, or the identifier is wrong.', translations: { ja: '削除されたか、番号が間違っている可能性があります。' } }, 'tracker.issue.saveFailed': { defaultMessage: "Couldn't save the change", translations: { ja: '変更を保存できませんでした' } }, diff --git a/web/src/features/agents/inbox-page.tsx b/web/src/features/agents/inbox-page.tsx index 9aae5a4..37c0b6c 100644 --- a/web/src/features/agents/inbox-page.tsx +++ b/web/src/features/agents/inbox-page.tsx @@ -2,8 +2,9 @@ // first, each answerable in place), then updates — answers to the caller's // own questions and mentions — to acknowledge. Keyboard: J/K (or ↓/↑) move, // 1–6 choose an option and Enter sends it (Enter on an update or with nothing -// chosen opens the issue in the side panel), O opens the issue, E marks an -// update as read, Esc closes the panel. After an answer the next item takes +// chosen opens the issue as a side panel tab), O opens the issue, E marks an +// update as read, Esc closes the active panel tab; with the panel open J/K +// browse within the active tab. After an answer the next item takes // focus, so a run of decisions needs no mouse. import { useQuery } from '@tanstack/react-query' import { useNavigate } from '@tanstack/react-router' @@ -15,6 +16,7 @@ import { useText } from '../../i18n' import { paths } from '../../routes/paths' import { Button, cn, EmptyState, formatDateTime, formatRelative, HrefLink, Loading, LoadFailed, Markdown, useDocumentTitle } from '../../ui' import { IssuePanel } from '../issues/issue-detail' +import { usePanelTabs } from '../issues/use-panel-tabs' import { isPlainShortcut } from '../ui-state' import { ActorAvatar, ActorName } from './actor' import { optionText, RequestCard } from './request-card' @@ -39,8 +41,12 @@ export function InboxPage({ search }: { search: { issue?: string } }) { const [focusedKey, setFocusedKey] = useState(null) const lastIndex = useRef(0) - const open = useCallback((identifier: string) => void navigate({ to: paths.inbox, search: { issue: identifier } } as never), [navigate]) - const close = useCallback(() => void navigate({ to: paths.inbox, search: {} } as never), [navigate]) + const setIssue = useCallback( + (issue: string | undefined, replace: boolean) => void navigate({ to: paths.inbox, search: issue ? { issue } : {}, replace, resetScroll: false } as never), + [navigate] + ) + const panel = usePanelTabs(search.issue, setIssue) + const { open, browse, close } = panel const acknowledge = useCallback((item: InboxItem) => { if (item.kind === 'answer') ack.mutate({ answers: [item.request.id] }) else if (item.kind === 'mention') ack.mutate({ mentions: [item.comment.id] }) @@ -79,22 +85,22 @@ export function InboxPage({ search }: { search: { issue?: string } }) { const step = key === 'j' || key === 'ArrowDown' ? 1 : -1 const next = ordered[index === -1 ? (step > 0 ? 0 : ordered.length - 1) : Math.min(Math.max(index + step, 0), ordered.length - 1)]! focusKey(itemKey(next)) - if (search.issue) open(itemIssue(next).identifier) + if (search.issue) browse(itemIssue(next)) } else if ((key === 'o' || key === 'O') && index !== -1) { event.preventDefault() - open(itemIssue(ordered[index]!).identifier) + open(itemIssue(ordered[index]!)) } else if ((key === 'e' || key === 'E') && index !== -1) { event.preventDefault() acknowledge(ordered[index]!) } else if (key === 'Escape' && search.issue) { event.preventDefault() - close() + close(search.issue) if (focusedKey) focusKey(focusedKey) } } document.addEventListener('keydown', onKeyDown) return () => document.removeEventListener('keydown', onKeyDown) - }, [ordered, focusedKey, focusKey, open, close, acknowledge, search.issue]) + }, [ordered, focusedKey, focusKey, open, browse, close, acknowledge, search.issue]) const section = (title: string, list: InboxItem[], action?: ReactNode) => list.length === 0 ? null : ( @@ -111,9 +117,9 @@ export function InboxPage({ search }: { search: { issue?: string } }) { return (
  • setFocusedKey(key)}> {item.kind === 'request' ? ( - open(item.request.issue.identifier)} /> + open(item.request.issue)} /> ) : ( - open(itemIssue(item).identifier)} onAck={() => acknowledge(item)} /> + open(itemIssue(item))} onAck={() => acknowledge(item)} /> )}
  • ) @@ -166,7 +172,7 @@ export function InboxPage({ search }: { search: { issue?: string } }) { )} - {search.issue ? : null} + {panel.active ? : null} ) } diff --git a/web/src/features/issues/issue-detail.tsx b/web/src/features/issues/issue-detail.tsx index 81d2eb6..bb8b40c 100644 --- a/web/src/features/issues/issue-detail.tsx +++ b/web/src/features/issues/issue-detail.tsx @@ -7,11 +7,12 @@ // `updatedAt` they were made against: if someone else wrote in between, the // draft stays and a notice offers to load the latest version instead of // overwriting it. Rendered as the full page (`/issues/APT-12`) or as the side -// panel over a list. +// panel over a list, where the issues opened there are tabs (model/panel-tabs.ts, +// use-panel-tabs.ts): only the active one is loaded and rendered. import { useQuery, useQueryClient } from '@tanstack/react-query' import { useNavigate } from '@tanstack/react-router' import { Bug, Copy, Maximize2, Pencil, RotateCw, Trash2, X } from 'lucide-react' -import { useEffect, useRef, useState, type ClipboardEvent, type DragEvent, type ReactNode } from 'react' +import { useEffect, useId, useRef, useState, type ClipboardEvent, type DragEvent, type KeyboardEvent, type ReactNode } from 'react' import { issueQuery, timelineQuery, useDeleteIssue, useUpdateIssue } from '../../api/queries' import { isTrackerError, type Issue, type Report, type TrackerRequest, type UpdateIssueInput } from '../../api/tracker' import { useText } from '../../i18n' @@ -28,6 +29,7 @@ import { HierarchySection, IssueBreadcrumb, IssueParentPicker, parentLabel } fro import { AssigneePicker, EstimatePicker, IssueProjectPicker, LabelsPicker, PriorityPicker, SprintPicker, StatusPicker, TypePicker, useIssueEditor } from './properties' import { Relations } from './relations' import { CommentComposer, insertAtCaret, Timeline } from './timeline' +import type { PanelTabsController } from './use-panel-tabs' import { useReference } from './use-reference' type Variant = 'page' | 'panel' @@ -53,40 +55,157 @@ export function IssuePage({ identifier }: { identifier: string }) { ) } -export function IssuePanel({ identifier, onClose }: { identifier: string; onClose: () => void }) { +export function IssuePanel({ identifier, panel }: { identifier: string; panel: PanelTabsController }) { const { t } = useText() + const tabsId = useId() + const active = identifier.toUpperCase() + // Same query as the detail below (no second request): the tab learns the title once the issue loads, and again after a rename. + const loaded = useQuery(issueQuery(identifier)).data + const { retitle } = panel + useEffect(() => { + if (loaded) retitle(loaded.identifier, loaded.title) + }, [loaded, retitle]) return ( ) } +/** + * One tab per open issue, in a strip that scrolls sideways and keeps the + * active tab in view. Roving focus with manual activation (activating loads + * an issue and adds a history entry): ←/→ (wrapping), Home and End move + * focus, Enter or Space activates, Delete or Backspace closes the focused + * tab. A tab also closes with its × (out of the tab order; Delete covers the + * keyboard) or a middle click. + */ +function PanelTabStrip({ panel, active, idPrefix }: { panel: PanelTabsController; active: string; idPrefix: string }) { + const { t } = useText() + const listRef = useRef(null) + const { tabs } = panel + const tabStop = tabs.some((tab) => tab.identifier === active) ? active : tabs[0]?.identifier + const tabElement = (identifier: string) => listRef.current?.querySelector(`[data-panel-tab="${CSS.escape(identifier)}"]`) ?? null + + // Bring the active tab into view by scrolling the strip only: scrollIntoView could also move the page behind the panel. + useEffect(() => { + const list = listRef.current + const tab = tabElement(active) + if (!list || !tab) return + if (tab.offsetLeft < list.scrollLeft) list.scrollLeft = tab.offsetLeft + else if (tab.offsetLeft + tab.offsetWidth > list.scrollLeft + list.clientWidth) list.scrollLeft = tab.offsetLeft + tab.offsetWidth - list.clientWidth + }, [active, tabs.length]) + + const focusTab = (identifier: string | undefined) => { + if (identifier) tabElement(identifier)?.querySelector('[role="tab"]')?.focus() + } + + const onKeyDown = (event: KeyboardEvent, index: number) => { + if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return + const last = tabs.length - 1 + const moves: Partial> = { ArrowRight: index === last ? 0 : index + 1, ArrowLeft: index === 0 ? last : index - 1, Home: 0, End: last } + const move = moves[event.key] + if (move !== undefined) { + event.preventDefault() + focusTab(tabs[move]?.identifier) + } else if (event.key === 'Delete' || event.key === 'Backspace') { + event.preventDefault() + focusTab(panel.close(tabs[index]!.identifier)) + } + } + + return ( +
    + {tabs.map((tab, index) => { + const selected = tab.identifier === active + const closeLabel = t('tracker.issue.closeTab', { identifier: tab.identifier }) + return ( +
    { + // Middle click closes; without this the browser starts autoscroll. + if (event.button === 1) event.preventDefault() + }} + onAuxClick={(event) => { + if (event.button !== 1) return + event.preventDefault() + panel.close(tab.identifier) + }} + className={cn( + 'relative flex shrink-0 items-center border-r border-line', + selected ? 'bg-white text-stone-900 after:absolute after:inset-x-0 after:bottom-0 after:h-0.5 after:bg-accent' : 'bg-stone-50 text-stone-500 hover:bg-stone-100 hover:text-stone-800' + )} + > + + +
    + ) + })} +
    + ) +} + function IssueDetail({ identifier, variant }: { identifier: string; variant: Variant }) { const { t } = useText() const { issue, timeline } = useIssue(identifier) diff --git a/web/src/features/issues/issues-page.tsx b/web/src/features/issues/issues-page.tsx index dde3e5e..8dc7158 100644 --- a/web/src/features/issues/issues-page.tsx +++ b/web/src/features/issues/issues-page.tsx @@ -1,7 +1,8 @@ // `/`, `/board`, `/reported`, `/current-sprint`, `/sprints/` and // `/views/`: project scope switcher, filter bar, list or board, and the // side panel (`?issue=APT-12`). Keys: J/K (or ↓/↑) move, X selects, Enter -// opens the panel, Esc closes it (then clears the selection). The filter, +// opens the issue as a panel tab (J/K with the panel open browse within the +// active tab), Esc closes the active tab (then clears the selection). The filter, // sort, grouping, project scope and open issue live in the URL so a link // reproduces the screen. On `/`, `/board` and `/reported` a single project // in the filter travels as `?project=` (paths.ts) and is the scope new issues @@ -37,6 +38,7 @@ import { IssuePanel } from './issue-detail' import { GroupedIssueList, IssueList, type IssueGroup, type RowOptions } from './issue-list' import { NO_PROJECT, ProjectScopeSwitcher } from './projects' import { SaveViewDialog } from './save-view-dialog' +import { usePanelTabs } from './use-panel-tabs' import { useReference } from './use-reference' export type IssuesPageKind = @@ -191,8 +193,17 @@ export function IssuesPage({ page, path, search, top }: { page: IssuesPageKind; }, [ordered]) useEffect(() => () => setUi({ context: [], focusedId: null, selectedIds: [] }), []) - const open = useCallback((issue: { identifier: string }) => setSearch({ issue: issue.identifier }, false), [setSearch]) - const close = useCallback(() => setSearch({ issue: undefined }, false), [setSearch]) + const setIssue = useCallback( + (issue: string | undefined, replace: boolean) => { + const next: ListSearch = { ...search, issue } + if (!issue) delete next.issue + // The list or board behind the panel keeps its scroll while tabs open, change and close. + void navigate({ to: path, search: next, replace, resetScroll: false } as never) + }, + [navigate, path, search] + ) + const panel = usePanelTabs(search.issue, setIssue) + const { open, browse, close } = panel const focusedId = useUi((state) => state.focusedId) useEffect(() => { @@ -209,7 +220,7 @@ export function IssuesPage({ page, path, search, top }: { page: IssuesPageKind; const row = document.querySelector(`[data-issue-row="${CSS.escape(next.id)}"]`) row?.focus({ preventScroll: true }) row?.scrollIntoView({ block: 'nearest' }) - if (search.issue) setSearch({ issue: next.identifier }) + if (search.issue) browse(next) } else if ((key === 'x' || key === 'X') && !event.shiftKey && index !== -1) { event.preventDefault() const id = ordered[index]!.id @@ -222,14 +233,14 @@ export function IssuesPage({ page, path, search, top }: { page: IssuesPageKind; } else if (key === 'Escape') { if (search.issue) { event.preventDefault() - close() + close(search.issue) if (focusedId) document.querySelector(`[data-issue-row="${CSS.escape(focusedId)}"]`)?.focus({ preventScroll: true }) } else setUi({ selectedIds: [] }) } } document.addEventListener('keydown', onKeyDown) return () => document.removeEventListener('keydown', onKeyDown) - }, [ordered, focusedId, search.issue, setSearch, open, close]) + }, [ordered, focusedId, search.issue, open, browse, close]) const selectedCount = useUi((state) => state.selectedIds.length) const [saving, setSaving] = useState(false) @@ -434,7 +445,7 @@ export function IssuesPage({ page, path, search, top }: { page: IssuesPageKind; ) : null} {query.isError && query.data ? : null} - {search.issue ? : null} + {panel.active ? : null} diff --git a/web/src/features/issues/use-panel-tabs.ts b/web/src/features/issues/use-panel-tabs.ts new file mode 100644 index 0000000..c70b5d0 --- /dev/null +++ b/web/src/features/issues/use-panel-tabs.ts @@ -0,0 +1,81 @@ +// The issue panel's tabs for a page that hosts the panel (lists, board, +// sprints, views, inbox). The URL's `issue` is the active tab; the tab list +// is the store's (model/panel-tabs.ts, persisted per browser tab). Every +// action updates the list first and then the URL through the host's +// `setIssue`: opening, activating and closing push a history entry (back +// returns to the previously active issue), browsing replaces it. +import { useCallback, useLayoutEffect } from 'react' +import { browseTab, closeAllTabs, closeTab, normalizeIdentifier, openTab, reconcileTabs, retitleTab, type PanelTab } from '../../model/panel-tabs' +import { setPanelTabs, uiStore, useUi } from '../ui-state' + +/** Changes the URL's `issue` (undefined removes it and the panel closes). */ +export type SetIssue = (issue: string | undefined, replace: boolean) => void + +/** What a host page hands to IssuePanel. `active` is the URL's issue, upper-cased. */ +export type PanelTabsController = { + tabs: PanelTab[] + active: string | undefined + open: (issue: PanelTab) => void + browse: (issue: PanelTab) => void + close: (identifier: string) => string | undefined + closeAll: () => void + activate: (identifier: string) => void + retitle: (identifier: string, title: string) => void +} + +export function usePanelTabs(urlIssue: string | undefined, setIssue: SetIssue): PanelTabsController { + const tabs = useUi((state) => state.panelTabs.tabs) + const active = urlIssue ? normalizeIdentifier(urlIssue) : undefined + + // The URL's issue always has a tab: a deep link, a reload, back/forward to a closed one. Before paint, so the strip never shows without it. + useLayoutEffect(() => { + if (urlIssue) setPanelTabs((state) => reconcileTabs(state, urlIssue)) + }, [urlIssue]) + + /** Open (click or Enter on a row or card, a link): activates its tab, adding one right of the active tab when it has none. */ + const open = useCallback( + (issue: PanelTab) => { + setPanelTabs((state) => openTab(state, issue.identifier, issue.title)) + setIssue(issue.identifier, false) + }, + [setIssue] + ) + + /** + * Browse (J/K, arrows with the panel open): the active tab shows `issue` + * instead; without a panel it is an open. The tab browsed from is the + * store's most recent one, which a key repeat faster than the URL update + * has already moved on. + */ + const browse = useCallback( + (issue: PanelTab) => { + if (!active) return open(issue) + setPanelTabs((state) => browseTab(state, state.recent[0] ?? active, issue.identifier, issue.title)) + setIssue(issue.identifier, true) + }, + [active, open, setIssue] + ) + + /** Closes one tab. Closing the active one activates its right neighbour (else left) and the panel closes with the last tab; closing another leaves the URL alone. Returns the tab now active. */ + const close = useCallback( + (identifier: string) => { + const { state, next } = closeTab(uiStore.state.panelTabs, identifier) + setPanelTabs(() => state) + if (next !== active) setIssue(next, false) + return next + }, + [active, setIssue] + ) + + /** The panel's ×: every tab closes. */ + const closeAll = useCallback(() => { + setPanelTabs(closeAllTabs) + setIssue(undefined, false) + }, [setIssue]) + + const activate = useCallback((identifier: string) => open({ identifier }), [open]) + + const retitle = useCallback((identifier: string, title: string) => setPanelTabs((state) => retitleTab(state, identifier, title)), []) + + return { tabs, active, open, browse, close, closeAll, activate, retitle } +} diff --git a/web/src/features/ui-state.ts b/web/src/features/ui-state.ts index c3eef12..550703d 100644 --- a/web/src/features/ui-state.ts +++ b/web/src/features/ui-state.ts @@ -5,9 +5,12 @@ // `/board`, `/reported` and `/epics` publish their project scope // (`?project=`), which stays while the person moves elsewhere: new issues // default to it and the sidebar's list links keep it. Sprint charts share -// one unit (points or issues) while the person moves between them. +// one unit (points or issues) while the person moves between them. The issue +// panel's open tabs (model/panel-tabs.ts) belong to the browser tab: kept in +// `sessionStorage`, so they survive a reload; the active one is the URL's. import { Store, useSelector } from '@tanstack/react-store' import type { IssueSummary, IssueType, Unit } from '../api/tracker' +import { NO_PANEL_TABS, parsePanelTabs, serializePanelTabs, type PanelTabs } from '../model/panel-tabs' /** Defaults of the "new issue" dialog. `projectId` undefined = the project scope; null = no project. `parent` prefills the parent (an epic's "New story", a group's "+"); `sprintId` the sprint (a sprint section's "+", the sprint page). */ export type NewIssueDefaults = { statusId?: string; projectId?: string | null; type?: IssueType; parent?: IssueSummary; sprintId?: string } @@ -29,9 +32,22 @@ type UiState = { chartUnit: Unit /** The open sprint a sprint screen shows (its page, the current sprint): new issues (C) join it. */ sprintScope: string | null + /** The issue panel's tabs; persisted under PANEL_TABS_KEY by `setPanelTabs`. */ + panelTabs: PanelTabs } -export const uiStore = new Store({ palette: false, paletteStart: 'root', newIssue: null, context: [], focusedId: null, selectedIds: [], scope: null, chartUnit: 'points', sprintScope: null }) +const PANEL_TABS_KEY = 'tracker.panelTabs' + +/** Missing, corrupt or unavailable storage (private mode, blocked) starts with no tabs. */ +function loadPanelTabs(): PanelTabs { + try { + return parsePanelTabs(sessionStorage.getItem(PANEL_TABS_KEY)) + } catch { + return NO_PANEL_TABS + } +} + +export const uiStore = new Store({ palette: false, paletteStart: 'root', newIssue: null, context: [], focusedId: null, selectedIds: [], scope: null, chartUnit: 'points', sprintScope: null, panelTabs: loadPanelTabs() }) export function useUi(select: (state: UiState) => T): T { return useSelector(uiStore, select) @@ -41,6 +57,19 @@ export function setUi(patch: Partial | ((state: UiState) => Partial ({ ...state, ...(typeof patch === 'function' ? patch(state) : patch) })) } +/** Updates the panel's tabs and writes them to this browser tab's storage; a failed write keeps them in memory only. */ +export function setPanelTabs(update: (tabs: PanelTabs) => PanelTabs) { + const current = uiStore.state.panelTabs + const next = update(current) + if (next === current) return + setUi({ panelTabs: next }) + try { + sessionStorage.setItem(PANEL_TABS_KEY, serializePanelTabs(next)) + } catch { + // Storage full or blocked: the tabs still work until the page reloads. + } +} + /** The issues a command applies to: the X-selection when there is one, else the focused issue. */ export function commandTargets(state: UiState): IssueSummary[] { const ids = state.selectedIds.length > 0 ? state.selectedIds : state.focusedId ? [state.focusedId] : [] diff --git a/web/src/model/panel-tabs.test.ts b/web/src/model/panel-tabs.test.ts new file mode 100644 index 0000000..4f99b33 --- /dev/null +++ b/web/src/model/panel-tabs.test.ts @@ -0,0 +1,199 @@ +import { describe, expect, test } from 'bun:test' +import { browseTab, closeAllTabs, closeTab, MAX_PANEL_TABS, NO_PANEL_TABS, openTab, parsePanelTabs, reconcileTabs, retitleTab, serializePanelTabs, type PanelTabs } from './panel-tabs' + +/** Tabs in strip order; `recent` (most recently active first) defaults to the reverse, so the last tab is the active one. */ +const state = (ids: string[], recent: string[] = [...ids].reverse()): PanelTabs => ({ tabs: ids.map((identifier) => ({ identifier })), recent }) +const strip = (current: PanelTabs) => current.tabs.map((tab) => tab.identifier) +const active = (current: PanelTabs) => current.recent[0] +const openAll = (ids: string[]) => ids.reduce((current, id) => openTab(current, id), NO_PANEL_TABS) + +describe('openTab', () => { + test.each<[string, PanelTabs, string, string[], string[]]>([ + ['first tab', NO_PANEL_TABS, 'APT-1', ['APT-1'], ['APT-1']], + ['appends right of the active last tab', state(['APT-1', 'APT-2']), 'APT-3', ['APT-1', 'APT-2', 'APT-3'], ['APT-3', 'APT-2', 'APT-1']], + ['inserts right of an active middle tab', state(['APT-1', 'APT-2', 'APT-3'], ['APT-1', 'APT-3', 'APT-2']), 'APT-9', ['APT-1', 'APT-9', 'APT-2', 'APT-3'], ['APT-9', 'APT-1', 'APT-3', 'APT-2']], + ['an open issue only becomes active', state(['APT-1', 'APT-2', 'APT-3']), 'APT-1', ['APT-1', 'APT-2', 'APT-3'], ['APT-1', 'APT-3', 'APT-2']], + ['identifiers compare upper-cased', state(['APT-1', 'APT-2']), ' apt-1 ', ['APT-1', 'APT-2'], ['APT-1', 'APT-2']], + ['a lower-case new issue is stored upper-cased', state(['APT-1']), 'apt-7', ['APT-1', 'APT-7'], ['APT-7', 'APT-1']], + ])('%s', (_name, before, identifier, tabs, recent) => { + const after = openTab(before, identifier) + expect(strip(after)).toEqual(tabs) + expect(after.recent).toEqual(recent) + }) + + test('opening the active tab again changes nothing', () => { + const before = state(['APT-1', 'APT-2']) + expect(openTab(before, 'apt-2')).toBe(before) + }) + + test('the clicked row title is kept, a missing title does not erase one', () => { + const titled = openTab(NO_PANEL_TABS, 'APT-1', 'Login fails') + expect(titled.tabs).toEqual([{ identifier: 'APT-1', title: 'Login fails' }]) + expect(openTab(openTab(titled, 'APT-2'), 'APT-1').tabs[0]).toEqual({ identifier: 'APT-1', title: 'Login fails' }) + expect(openTab(titled, 'APT-1', 'Login fails on Safari').tabs[0]).toEqual({ identifier: 'APT-1', title: 'Login fails on Safari' }) + }) + + test(`a ${MAX_PANEL_TABS + 1}st tab evicts the least recently active one`, () => { + const ids = Array.from({ length: MAX_PANEL_TABS }, (_, index) => `APT-${index + 1}`) + // APT-1 was the first opened, but activating it again makes APT-2 the least recently active. + const full = openTab(openAll(ids), 'APT-1') + const after = openTab(full, 'APT-99') + expect(after.tabs).toHaveLength(MAX_PANEL_TABS) + expect(strip(after)).not.toContain('APT-2') + expect(strip(after)).toContain('APT-1') + expect(strip(after).indexOf('APT-99')).toBe(strip(after).indexOf('APT-1') + 1) + expect(active(after)).toBe('APT-99') + const next = openTab(after, 'APT-100') + expect(strip(next)).not.toContain('APT-3') + expect(strip(next)).toContain('APT-99') + }) + + test('the tab being opened is never the one evicted', () => { + const ids = Array.from({ length: MAX_PANEL_TABS }, (_, index) => `APT-${index + 1}`) + const after = openTab(openAll(ids), 'APT-50') + expect(strip(after)).toContain('APT-50') + expect(strip(after)).not.toContain('APT-1') + }) +}) + +describe('browseTab', () => { + test.each<[string, PanelTabs, string, string, string[], string]>([ + ['replaces the active tab in place', state(['APT-1', 'APT-2', 'APT-3'], ['APT-2', 'APT-3', 'APT-1']), 'APT-2', 'APT-7', ['APT-1', 'APT-7', 'APT-3'], 'APT-7'], + ['onto an open issue activates it and keeps the one browsed from', state(['APT-1', 'APT-2', 'APT-3'], ['APT-2', 'APT-3', 'APT-1']), 'APT-2', 'APT-3', ['APT-1', 'APT-2', 'APT-3'], 'APT-3'], + ['case-insensitive on both sides', state(['APT-1', 'APT-2']), 'apt-2', 'apt-1', ['APT-1', 'APT-2'], 'APT-1'], + ['onto itself changes nothing', state(['APT-1', 'APT-2']), 'APT-2', 'apt-2', ['APT-1', 'APT-2'], 'APT-2'], + ['from an issue without a tab opens the target', state(['APT-1']), 'APT-5', 'APT-6', ['APT-1', 'APT-6'], 'APT-6'], + ])('%s', (_name, before, from, to, tabs, current) => { + const after = browseTab(before, from, to) + expect(strip(after)).toEqual(tabs) + expect(active(after)).toBe(current) + expect([...after.recent].sort()).toEqual([...tabs].sort()) + }) + + test('walking a list three steps keeps the tab count', () => { + let current = openAll(['APT-1', 'APT-2', 'APT-3']) + for (const [from, to] of [['APT-3', 'APT-4'], ['APT-4', 'APT-5'], ['APT-5', 'APT-6']] as const) current = browseTab(current, from, to) + expect(strip(current)).toEqual(['APT-1', 'APT-2', 'APT-6']) + expect(active(current)).toBe('APT-6') + }) + + test('walking across issues that are open closes none of them', () => { + let current = openAll(['APT-1', 'APT-2', 'APT-3']) + for (const [from, to] of [['APT-3', 'APT-1'], ['APT-1', 'APT-2'], ['APT-2', 'APT-3']] as const) current = browseTab(current, from, to) + expect(strip(current)).toEqual(['APT-1', 'APT-2', 'APT-3']) + expect(active(current)).toBe('APT-3') + }) + + test('the replaced tab takes the new title, not the old one', () => { + const before = openTab(NO_PANEL_TABS, 'APT-1', 'Old') + expect(browseTab(before, 'APT-1', 'APT-2').tabs).toEqual([{ identifier: 'APT-2' }]) + expect(browseTab(before, 'APT-1', 'APT-2', 'New').tabs).toEqual([{ identifier: 'APT-2', title: 'New' }]) + }) +}) + +describe('closeTab', () => { + // [name, tabs in strip order, active, closed, tabs after, active after] + test.each<[string, string[], string, string, string[], string | undefined]>([ + ['active first: its right neighbour', ['APT-1', 'APT-2', 'APT-3'], 'APT-1', 'APT-1', ['APT-2', 'APT-3'], 'APT-2'], + ['active middle: its right neighbour', ['APT-1', 'APT-2', 'APT-3'], 'APT-2', 'APT-2', ['APT-1', 'APT-3'], 'APT-3'], + ['active last: its left neighbour', ['APT-1', 'APT-2', 'APT-3'], 'APT-3', 'APT-3', ['APT-1', 'APT-2'], 'APT-2'], + ['only: none, the panel closes', ['APT-1'], 'APT-1', 'APT-1', [], undefined], + ['a background tab: the active one stays', ['APT-1', 'APT-2', 'APT-3'], 'APT-3', 'APT-1', ['APT-2', 'APT-3'], 'APT-3'], + ['a background tab right of the active one', ['APT-1', 'APT-2', 'APT-3'], 'APT-1', 'APT-2', ['APT-1', 'APT-3'], 'APT-1'], + ['case-insensitive', ['APT-1', 'APT-2'], 'APT-1', 'apt-1', ['APT-2'], 'APT-2'], + ])('%s', (_name, ids, current, identifier, tabs, next) => { + const result = closeTab(openTab(state(ids), current), identifier) + expect(strip(result.state)).toEqual(tabs) + expect(result.next).toBe(next) + expect(result.state.recent[0]).toBe(next) + }) + + test('a tab that is not open: nothing changes', () => { + const before = state(['APT-1', 'APT-2']) + expect(closeTab(before, 'APT-9')).toEqual({ state: before, next: undefined }) + }) + + test('the closed tab leaves the recency order, so it is never evicted later', () => { + const { state: after } = closeTab(state(['APT-1', 'APT-2', 'APT-3']), 'APT-1') + expect(after.recent).toEqual(['APT-3', 'APT-2']) + }) +}) + +test('closeAllTabs leaves no tab', () => { + expect(closeAllTabs()).toEqual({ tabs: [], recent: [] }) +}) + +describe('reconcileTabs', () => { + test('no issue in the URL changes nothing', () => { + const before = state(['APT-1']) + expect(reconcileTabs(before, undefined)).toBe(before) + }) + + test('the URL issue already open becomes active (back/forward)', () => { + const after = reconcileTabs(state(['APT-1', 'APT-2']), 'APT-1') + expect(strip(after)).toEqual(['APT-1', 'APT-2']) + expect(active(after)).toBe('APT-1') + }) + + test('an issue without a tab gets one (deep link, back to a closed issue, unknown issue)', () => { + expect(strip(reconcileTabs(NO_PANEL_TABS, 'apt-9'))).toEqual(['APT-9']) + const after = reconcileTabs(state(['APT-1', 'APT-2']), 'NOPE-404') + expect(strip(after)).toEqual(['APT-1', 'APT-2', 'NOPE-404']) + expect(active(after)).toBe('NOPE-404') + }) + + test('an active URL issue already in front is stable', () => { + const before = state(['APT-1', 'APT-2']) + expect(reconcileTabs(before, 'apt-2')).toBe(before) + }) +}) + +describe('retitleTab', () => { + test('sets the title of one tab', () => { + expect(retitleTab(state(['APT-1', 'APT-2']), 'apt-2', 'Crash').tabs).toEqual([{ identifier: 'APT-1' }, { identifier: 'APT-2', title: 'Crash' }]) + }) + + test.each([ + ['an unknown tab', 'APT-9', 'Crash'], + ['the same title', 'APT-1', 'Known'], + ['an empty title', 'APT-1', ''], + ])('%s changes nothing', (_name, identifier, title) => { + const before = openTab(NO_PANEL_TABS, 'APT-1', 'Known') + expect(retitleTab(before, identifier, title)).toBe(before) + }) + + test('keeps the order and the active tab', () => { + const before = state(['APT-1', 'APT-2'], ['APT-1', 'APT-2']) + expect(retitleTab(before, 'APT-2', 'x').recent).toEqual(['APT-1', 'APT-2']) + }) +}) + +describe('parsePanelTabs', () => { + test('round-trips', () => { + const before = openTab(openTab(openTab(NO_PANEL_TABS, 'APT-1', 'One'), 'APT-2'), 'APT-1') + expect(parsePanelTabs(serializePanelTabs(before))).toEqual(before) + }) + + test.each([ + ['missing', null], + ['empty', ''], + ['not JSON', '{tabs:'], + ['not an object', '42'], + ['no tab list', '{"recent":["APT-1"]}'], + ['no usable tab', '{"tabs":[{"identifier":3},null,"APT-1",{"identifier":" "}]}'], + ])('%s storage starts empty', (_name, raw) => { + expect(parsePanelTabs(raw)).toEqual(NO_PANEL_TABS) + }) + + test('repairs case, duplicates, junk titles and a stale recency list', () => { + const raw = JSON.stringify({ tabs: [{ identifier: 'apt-1', title: 7 }, { identifier: 'APT-2', title: 'Two' }, { identifier: 'Apt-1' }], recent: ['APT-9', 'apt-2', 'APT-2'] }) + expect(parsePanelTabs(raw)).toEqual({ tabs: [{ identifier: 'APT-1' }, { identifier: 'APT-2', title: 'Two' }], recent: ['APT-2', 'APT-1'] }) + }) + + test(`keeps at most ${MAX_PANEL_TABS} tabs, dropping the least recently active`, () => { + const ids = Array.from({ length: MAX_PANEL_TABS + 2 }, (_, index) => `APT-${index + 1}`) + const parsed = parsePanelTabs(JSON.stringify({ tabs: ids.map((identifier) => ({ identifier })), recent: [...ids].reverse() })) + expect(parsed.tabs).toHaveLength(MAX_PANEL_TABS) + expect(strip(parsed)).toEqual(ids.slice(2)) + }) +}) diff --git a/web/src/model/panel-tabs.ts b/web/src/model/panel-tabs.ts new file mode 100644 index 0000000..cf9d736 --- /dev/null +++ b/web/src/model/panel-tabs.ts @@ -0,0 +1,143 @@ +// The issue side panel's tabs (design/README.md "Issue panel tabs"): the +// issues a person opened, in strip order, each with the title last seen. +// The active issue is the URL's `?issue=`, not part of this state; `recent` +// only orders the tabs by when they were last active, so the 21st open evicts +// the least recently active one and a new tab lands right of the last active. +// Identifiers compare upper-cased. Pure: storage and navigation live in +// features/issues/use-panel-tabs.ts. + +export const MAX_PANEL_TABS = 20 + +export type PanelTab = { identifier: string; title?: string } + +export type PanelTabs = { + /** Strip order, left to right; no duplicates. */ + tabs: PanelTab[] + /** The same identifiers, most recently active first. */ + recent: string[] +} + +export const NO_PANEL_TABS: PanelTabs = { tabs: [], recent: [] } + +export const normalizeIdentifier = (identifier: string) => identifier.trim().toUpperCase() + +const indexOf = (state: PanelTabs, identifier: string) => state.tabs.findIndex((tab) => tab.identifier === identifier) + +const touch = (recent: string[], identifier: string) => [identifier, ...recent.filter((id) => id !== identifier)] + +/** Drops the least recently active tabs beyond the cap, never `keep` (the one just opened). */ +function evict(state: PanelTabs, keep: string): PanelTabs { + let { tabs, recent } = state + while (tabs.length > MAX_PANEL_TABS) { + const victim = [...recent].reverse().find((id) => id !== keep) + if (victim === undefined) break + tabs = tabs.filter((tab) => tab.identifier !== victim) + recent = recent.filter((id) => id !== victim) + } + return tabs === state.tabs ? state : { tabs, recent } +} + +/** Open: the issue becomes the most recently active; a new tab goes right of the previously active one. */ +export function openTab(state: PanelTabs, identifier: string, title?: string): PanelTabs { + const id = normalizeIdentifier(identifier) + const at = indexOf(state, id) + if (at !== -1) { + const retitled = title !== undefined && title !== '' && title !== state.tabs[at]!.title + if (!retitled && state.recent[0] === id) return state + return { tabs: retitled ? state.tabs.map((tab, index) => (index === at ? { ...tab, title } : tab)) : state.tabs, recent: touch(state.recent, id) } + } + const previous = state.recent[0] === undefined ? -1 : indexOf(state, state.recent[0]) + const insertAt = previous === -1 ? state.tabs.length : previous + 1 + const tab: PanelTab = title ? { identifier: id, title } : { identifier: id } + const tabs = [...state.tabs.slice(0, insertAt), tab, ...state.tabs.slice(insertAt)] + return evict({ tabs, recent: touch(state.recent, id) }, id) +} + +/** + * Browse: the tab showing `from` shows `to` instead, in place. When `to` + * already has a tab, that tab becomes active and `from`'s stays: walking a + * list across issues a person opened must not close them. + */ +export function browseTab(state: PanelTabs, from: string, to: string, title?: string): PanelTabs { + const source = normalizeIdentifier(from) + const target = normalizeIdentifier(to) + const at = indexOf(state, source) + if (at === -1 || source === target || indexOf(state, target) !== -1) return openTab(state, target, title) + const tab: PanelTab = title ? { identifier: target, title } : { identifier: target } + return { + tabs: state.tabs.map((current, index) => (index === at ? tab : current)), + recent: touch( + state.recent.filter((id) => id !== source), + target + ), + } +} + +/** + * Close one tab. Closing the active tab (the most recently active one) + * activates the one to its right, else the one to its left; closing any other + * tab leaves the active one alone. `next` is the tab active afterwards: + * undefined when none is left (or the tab was not open). + */ +export function closeTab(state: PanelTabs, identifier: string): { state: PanelTabs; next: string | undefined } { + const id = normalizeIdentifier(identifier) + const at = indexOf(state, id) + if (at === -1) return { state, next: undefined } + const tabs = state.tabs.filter((tab) => tab.identifier !== id) + const recent = state.recent.filter((current) => current !== id) + const current = state.recent[0] + if (current !== undefined && current !== id && indexOf(state, current) !== -1) return { state: { tabs, recent }, next: current } + const next = (tabs[at] ?? tabs[at - 1])?.identifier + return { state: { tabs, recent: next === undefined ? recent : touch(recent, next) }, next } +} + +/** Close the panel: every tab closes. */ +export function closeAllTabs(): PanelTabs { + return NO_PANEL_TABS +} + +/** The URL's issue always has a tab (deep link, reload, back/forward) and is the most recently active. */ +export function reconcileTabs(state: PanelTabs, urlIssue: string | undefined): PanelTabs { + return urlIssue ? openTab(state, urlIssue) : state +} + +/** Remembers the title seen for a tab; other tabs and the order are untouched. */ +export function retitleTab(state: PanelTabs, identifier: string, title: string): PanelTabs { + const id = normalizeIdentifier(identifier) + const at = indexOf(state, id) + if (at === -1 || !title || state.tabs[at]!.title === title) return state + return { ...state, tabs: state.tabs.map((tab, index) => (index === at ? { ...tab, title } : tab)) } +} + +/** Stored tabs as JSON; anything missing, malformed or over the cap is repaired, never trusted. */ +export function parsePanelTabs(raw: string | null): PanelTabs { + if (!raw) return NO_PANEL_TABS + let parsed: unknown + try { + parsed = JSON.parse(raw) + } catch { + return NO_PANEL_TABS + } + if (!parsed || typeof parsed !== 'object' || !Array.isArray((parsed as PanelTabs).tabs)) return NO_PANEL_TABS + const tabs: PanelTab[] = [] + for (const entry of (parsed as PanelTabs).tabs as unknown[]) { + if (!entry || typeof entry !== 'object') continue + const { identifier, title } = entry as Record + if (typeof identifier !== 'string' || !identifier.trim()) continue + const id = normalizeIdentifier(identifier) + if (tabs.some((tab) => tab.identifier === id)) continue + tabs.push(typeof title === 'string' && title ? { identifier: id, title } : { identifier: id }) + } + const stored = Array.isArray((parsed as PanelTabs).recent) ? ((parsed as PanelTabs).recent as unknown[]) : [] + const known = new Set(tabs.map((tab) => tab.identifier)) + const recent: string[] = [] + for (const id of stored) if (typeof id === 'string' && known.has(normalizeIdentifier(id)) && !recent.includes(normalizeIdentifier(id))) recent.push(normalizeIdentifier(id)) + // Tabs the recency list forgot count as the least recently active, in strip order. + for (const tab of tabs) if (!recent.includes(tab.identifier)) recent.push(tab.identifier) + const state = { tabs, recent } + return recent[0] === undefined ? NO_PANEL_TABS : evict(state, recent[0]) +} + +export function serializePanelTabs(state: PanelTabs): string { + return JSON.stringify(state) +} diff --git a/web/src/routes/paths.ts b/web/src/routes/paths.ts index b41789e..18762f9 100644 --- a/web/src/routes/paths.ts +++ b/web/src/routes/paths.ts @@ -2,10 +2,11 @@ // `/current-sprint`, `/sprints/`, `/views/`) carry their state in the // query: `filter` (API.md Filter as JSON), `sort`, `layout` (built-in views, // sprints and views), `group` (`epic`, `story` or `sprint`; absent = the -// page's default, `none` overrides a view's grouping), `issue` (the -// identifier open in the side panel) and, on `/`, `/board`, `/reported` and -// `/epics`, `project` — the project scope (a project id or `none`; absent = -// all projects), kept out of `filter` so a scoped link stays readable. +// page's default, `none` overrides a view's grouping), `issue` (the side +// panel's active tab; the other open tabs are the browser tab's, not the +// URL's) and, on `/`, `/board`, `/reported` and `/epics`, `project` — the +// project scope (a project id or `none`; absent = all projects), kept out of +// `filter` so a scoped link stays readable. import type { Filter, GroupBy, Sort, ViewLayout } from '../api/tracker' import { compactFilter, GROUP_BYS, SORTS } from '../model/issues'