From b22fd3ff2da5401b46660ec20f3d1371ebbbd54d Mon Sep 17 00:00:00 2001 From: ehonis Date: Mon, 16 Nov 2026 14:16:28 -0500 Subject: [PATCH] Pin the chat's task at its top right; open other tasks in a modal Published from the private repository by oss-sync. - Pin the chat's task at its top right; open other tasks in a modal 8 files changed, 387 insertions(+), 157 deletions(-) --- AGENTS.md | 2 +- docs/chat.md | 34 ++- web/src/components/ChatView.tsx | 6 + web/src/work/TaskBar.tsx | 5 +- web/src/work/TaskCard.test.tsx | 65 +++++- web/src/work/TaskCard.tsx | 357 ++++++++++++++++++++------------ web/src/work/card.ts | 25 ++- web/src/work/work.css | 50 ++++- 8 files changed, 387 insertions(+), 157 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 78feb00..fd5d02c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -93,7 +93,7 @@ open-ended work. The default provider and model come from Settings → Providers | Apple data | `apple/`, the "Apple" block in `bridge.mjs`, the Messages view in `web/src/messages/` | macOS only, off unless `APPLE_ENABLED=true`. Reads Messages (`chat.db`), Contacts and Photos (`Photos.sqlite` plus Photos' own search index) read-only; sends through the Messages app with `osascript`. The owner sends from the Messages tab (last on the desktop rail, not on the phone drawer; `/messages` still opens); agents only stage an `imessage` inbox proposal (`totem_apple_propose_message`), which only the dashboard can accept. `docs/apple.md`. | | Chat | `chat/`, the "Web chat" block in `bridge.mjs`, `web/src/chat/` | Server-owned threads and runs that outlive the browser, listed as summaries and read a window at a time with Load earlier (`GET /api/threads?view=summary`, `GET /api/threads/?turns=10&before=`; one merge file shared by web and app, `web/src/chat/history.ts`; each chat reopens where it was left, `scrollMemory.ts`; docs/chat.md → Loading chats) (`POST /api/chat` streams SSE; `GET /api/chat/runs//stream?since=` re-attaches; only `POST /api/chat/stop` ends a run early; `POST /api/chat/steer` sends the owner's words and files into a running reply, live for Claude, interrupt-and-resume for the rest, `chat/steer.mjs`; or the message waits in the thread's queue, which the bridge drains itself when a run ends and holds after a stop or failure, `chat/queue.mjs`, `POST /api/chat/queue`; Settings → Chat › Follow-up behaviour picks which Enter does, Ctrl/⌘ the other). Native per-provider session resume, attachments, named tool cards folded with the reply's in-between text into one line above the answer, led by the connectors' own logos stacked (`web/src/chat/workFold.ts`; Claude's `tool_use_meta`, `connectorLook` in `chat/tools.mjs`), per-reply stats (setting, effort, tokens, tok/s, cost; `chat/stats.mjs`, shown on hover by `TurnStats.tsx`), no modes (every chat run gets the browser, computer use where the account has it, and an hour; the agent decides, `chat/reach.mjs`), the model picker (`ModelPicker.tsx`; no automatic routing since Auto/Instant/Thinking were retired; picking another account mid-chat hands the chat over with what it missed, `handoffReplay`, docs/chat.md → Switching accounts), thread titles and icons, local whisper.cpp dictation and an optional OpenAI Realtime voice mode. `docs/chat.md`. | | Chat projects | `chat/projects.mjs`, `chat/memory-ref.mjs`, `web/src/chat/Project*.tsx` | Chats grouped with a shared default model (a new chat takes its own pick, else the folder's, else the project's, else Settings → Providers: `threadChoice`/`projectDefault` in `web/src/chat/store.ts`, `projectModelDefault` on the bridge; a pick in a draft never carries to another chat), owner-written instructions, an agent-kept `memory.md` and shared files (`data/chat-projects/`). Each turn names the memory file with a one-line summary (size, entries, last updated, headings) and the agent reads it on demand, again when the summary changed; only the owner's instructions are pasted (memory used to be, once per turn of a resumed session). OpenCode, which cannot read outside `AGENT_CWD` unattended, gets the file's start instead. One level of folders (`parentId`) that read the parent read-only and keep their own memory; a chat can turn project context off (`projectContextOff`); an uploaded image or a website's icon can stand in for the Tabler icon (`image`, `chat/favicon.mjs`); finished chats wait on the owner (`needsReply`) until the owner opens one, replies or marks it read; "Mark as unread" sets `keepUnread`, which opening does not clear. Every list (Home, project, folder) ends with its own Snoozed and Settled shelves, T3 Code style (`web/src/chat/settle.ts`; auto-settle and wake-up are computed on read, never written). An agent that finished a one-off request calls `mark_chat_done` (`chat/done.mjs`, on `/agent-mcp`): the row offers a one-tap Settle until the reply is read, then the chat settles itself once he moves off it (`doneAt`; dropped by a failed or stopped reply, a steer or his next message). The chats panel is scoped to Home or one project; chats drag onto folders and projects. `docs/chat.md` → Projects. | -| Tasks panel | `web/src/work/`, `chat/task-folders.mjs`, `chat/task-link.mjs`, `/api/chat/task-folders` in `bridge.mjs` | The chats panel's third face (Chats · Totems · Tasks): open local tasks and the shared sheet's action items, grouped by the chat project or folder each is filed under (a task's `folderId`; a sheet row's filing in `data/task-folders.json`, `TASK_FOLDERS_FILE`, `none` meaning Personal on purpose), each with its linked chats under it. A click on a task opens its floating card (`web/src/work/TaskCard.tsx`, mounted once in `App.tsx`; a bottom sheet on a phone): folder, due, priority, repeat, snooze, description, chats, Open in Tasks; the composer's task strip opens it too. A chat names at most one task (`thread.taskId`: a task id or a sheet row id), linked from its "…", by dropping it on a task, or by starting a chat from the task (`startTaskDraft`; the first send carries `taskId`, kept by `startChatTurn` on a new chat only). A linked chat's composer shows the task (Done, change, unlink; `TaskBar.tsx`) and every non-voice turn carries a `LINKED TASK.` block (`linkedTaskBlock`). Filing a task, Move to… and Link to task… share one T3 Code-style project-selector popover (`ComboPicker.tsx`: search, arrows, Enter, "New folder/project/task …" from what was typed). Tasks load only while the face, a strip or the composer's `$` menu is on screen. A chat not started yet is placed from its composer with `$` (Home, a project or folder, or a task, which starts it through `startTaskDraft` in the task's folder; `web/src/chat/destinations.ts`, `destinations` on `Composer`), and ⌘/Ctrl+Shift+O starts a blank chat at Home from any page (a hotkey: `hotkeys` in `web/src/shortcuts.ts`, Settings → Keyboard › Hotkeys; `docs/shortcuts.md` → Hotkeys). Not in the iPhone app yet. `docs/chat.md` → Tasks panel, → Placing a new chat with `$`. | +| Tasks panel | `web/src/work/`, `chat/task-folders.mjs`, `chat/task-link.mjs`, `/api/chat/task-folders` in `bridge.mjs` | The chats panel's third face (Chats · Totems · Tasks): open local tasks and the shared sheet's action items, grouped by the chat project or folder each is filed under (a task's `folderId`; a sheet row's filing in `data/task-folders.json`, `TASK_FOLDERS_FILE`, `none` meaning Personal on purpose), each with its linked chats under it. A task's card (`web/src/work/TaskCard.tsx`: folder, due, priority, repeat, snooze, description, chats, Open in Tasks) is pinned at the open chat's top right for that chat's own task (`PinnedTask` in `ChatView`; folds, never closes, the log moves left to clear it; opening that task anywhere unfolds it, `pinTask` in `card.ts`), and any other task opens it as a modal dialog (`TaskCardHost`, mounted once in `App.tsx`; a bottom sheet on a phone). A chat names at most one task (`thread.taskId`: a task id or a sheet row id), linked from its "…", by dropping it on a task, or by starting a chat from the task (`startTaskDraft`; the first send carries `taskId`, kept by `startChatTurn` on a new chat only). A linked chat's composer shows the task (Done, change, unlink; `TaskBar.tsx`) and every non-voice turn carries a `LINKED TASK.` block (`linkedTaskBlock`). Filing a task, Move to… and Link to task… share one T3 Code-style project-selector popover (`ComboPicker.tsx`: search, arrows, Enter, "New folder/project/task …" from what was typed). Tasks load only while the face, a strip or the composer's `$` menu is on screen. A chat not started yet is placed from its composer with `$` (Home, a project or folder, or a task, which starts it through `startTaskDraft` in the task's folder; `web/src/chat/destinations.ts`, `destinations` on `Composer`), and ⌘/Ctrl+Shift+O starts a blank chat at Home from any page (a hotkey: `hotkeys` in `web/src/shortcuts.ts`, Settings → Keyboard › Hotkeys; `docs/shortcuts.md` → Hotkeys). Not in the iPhone app yet. `docs/chat.md` → Tasks panel, → Placing a new chat with `$`. | | Chat files | `chat/files.mjs`, `web/src/chat/FilesPanel.tsx`, `/api/chat/files*` in `bridge.mjs`, `openFile` in `web/src/chat/store.ts`, `web/src/links.ts` | T3 Code's files viewer: the chat's outputs folder as a tree beside the chat, every file openable in the canvas and downloadable from any device. It, the canvas, Browser and Agents panels share one slot, drag-resizable per panel (`docs/chat.md` → Side panel widths). Serves `CHAT_OUTPUTS_DIR` plus `FILES_ROOTS`, by real path, never Totem's `data/`, `secrets/` or `.env`. A reply's link to an absolute path opens there, and the same path opened as a URL redirects to the chat (`?file=`). Every opener goes through `openFile(path)`: `GET /api/chat/files/link` checks the path and returns a signed link (real path + 12 h expiry + HMAC under a random per-process key), which the canvas, its frames and the native download read without the bearer (a Files row's Download signs on the click; the listing carries no links); only the exact spelling `/api/chat/files/raw?…&sig=` skips the sign-in gate, and the roots/deny check runs on every read. A bearer-only dashboard read the bare raw URL with no header and showed `{"error":"unauthorized"}`; `chat/files-bridge.test.mjs` boots a bridge to hold this. `docs/chat.md` → Files panel. | | Download activity | `web/src/downloads.ts`, `web/src/components/DownloadActivity.tsx`, `desktop/src-tauri/src/lib.rs` | App-wide activity for download links, chat and question attachments, generated files, previews, project files, Messages files and journal audio. Active repeats join one transfer; different files have separate progress, cancel/retry and dismiss controls. Browsers offering a save-file picker stream directly to the chosen file; otherwise transfers buffer at most 32 MiB before handing larger files to the browser. Browser handoff and application transfer completion explicitly tell the owner to check Downloads, never claim an OS save. Native wrappers advertising `downloads` stream through Tauri and report real saved/failed events (indeterminate: Tauri has no byte progress); this requires a new desktop build. A saved native download gets Show in folder (Show in Finder on a Mac): the app keeps the path (`Downloads` in `lib.rs`, the last 50) and the page asks by the download's URL through a cancelled `totem-desktop://reveal?u=` navigation, never seeing a path; older wrappers do not send `reveal`, so no button. Raw chat files and signed uploads accept authenticated HEAD preflights without reading file bodies; bearer-only users need a session or a signed URL (an upload's `?sig=`, a chat file's signed link) for native/browser navigation handoff. | | Sub-agents | `chat/subagents.mjs`, `web/src/chat/AgentsPanel.tsx` | Agents a chat's agent starts: Claude's Agent/Task sub-agents (events tagged `parent_tool_use_id`), Codex collab children, and another CLI run from a shell (`codex exec`, `claude -p`, …), whose own session log is found by start time and prompt and tailed. Each folds into its tool card as `part.agent` (status, model, tokens, steps). The Agents panel beside the chat lists them and opens each one's live log. Each writes an `agent.delegate` line to the action log. `docs/chat.md` → Agents panel. | diff --git a/docs/chat.md b/docs/chat.md index 5aed4be..05204f6 100644 --- a/docs/chat.md +++ b/docs/chat.md @@ -1306,15 +1306,29 @@ moves between a task and any of its chats (`web/src/work/`). from `GET /api/todos/sheet` already filed: its own filing, else the sheet's default folder (`docs/task-sheet.md`). Deleting a folder moves its tasks up to its project, deleting a project makes them Personal, as with its chats. -- **The task card** (`web/src/work/TaskCard.tsx`, `card.ts`). A click on a task opens a - floating card at the page's top right, T3 Code's thread card for a task: the check - circle and title, then one row per setting with a dropdown (Folder, Due, Priority, - Repeat, Snooze), the description, the chats working on it with New chat, Open in Tasks - (the Tasks page, scrolled to the task with its pane open) and Delete. Every change saves - at once and is drawn put back if refused. A sheet row's card is read-only but for its - folder, with Open in the sheet. Esc, × or a click elsewhere closes it; on a phone it is - a sheet from the bottom over a scrim. The count beside a task unfolds its chats; the - "…" has Edit task…, New chat, Move to folder… and Mark done. +- **The task card** (`web/src/work/TaskCard.tsx`, `card.ts`), T3 Code's thread card for a + task: the check circle and title, then one row per setting with a dropdown (Folder, Due, + Priority, Repeat, Snooze), the description, the chats working on it with New chat, Open + in Tasks (the Tasks page, scrolled to the task with its pane open) and Delete. Every + change saves at once and is drawn put back if refused. A sheet row's card is read-only + but for its folder, with Open in the sheet. It is drawn two ways: + - **Pinned.** The open chat's own task (a linked chat's `taskId`, or the task a new + chat is being started from) sits at the chat's top right under the header for as + long as the chat is open (`PinnedTask`, mounted by `ChatView`). Nothing outside + closes it; its chevron folds it to its title row, kept per device + (`totem.taskPin.folded`), and with no choice made it starts folded while the chat + column is under 1000px. Unfolded, the messages and composer move left just enough to + clear it (a `:has()` rule in `work.css`, percentages of `.vc`, no JS), keeping at + least 520px. Opening that task anywhere (the strip, its row in the chats panel) + unfolds and flashes it rather than opening a dialog (`pinTask` in `card.ts`), but only + while the chat is the page on screen. Not on a phone. + - **A dialog.** Any other task, opened from the chats panel's Tasks face (or the chat's + own task on a phone), opens in a modal over a backdrop (`TaskCardHost`, mounted once + in `App.tsx`). Esc, × or the backdrop close it; focus goes back where it was. On a + phone it is a sheet from the bottom. + + The count beside a task unfolds its chats; the "…" has Edit task…, New chat, Move to + folder… and Mark done. - **Live with the Tasks page.** The panel and the page keep their own copies of the list, so each tells the other when it changes something (`web/src/todos/bus.ts`: `announcing` wraps every call that writes; `onTasksChanged` reads again, once per burst, @@ -1329,7 +1343,7 @@ moves between a task and any of its chats (`web/src/work/`). - **The strip over the composer** (`web/src/work/TaskBar.tsx`) names a linked chat's task with its folder and due day, Done (local tasks), and the link button to change or unlink it; on a new chat from a task it says so, with × for a plain chat instead. The task's - title opens its card and turns every open chats panel to Tasks, scrolled to the task. + title unfolds and flashes the pinned card (the sheet on a phone) and turns every open chats panel to Tasks, scrolled to the task. (It used to only turn the panel, which did nothing visible when the panel was already on Tasks, as it is for a chat started there.) - **Tasks an agent makes.** `totem_create_task` from a chat run (the gateway names the run, diff --git a/web/src/components/ChatView.tsx b/web/src/components/ChatView.tsx index 51ddb7a..9571d0a 100644 --- a/web/src/components/ChatView.tsx +++ b/web/src/components/ChatView.tsx @@ -18,6 +18,7 @@ import { GroupPicker } from './TotemsView' import { isSnoozed, settledAt, wakeDescription } from '../chat/settle' import ProjectHome from '../chat/ProjectHome' import TaskBar from '../work/TaskBar' +import { PinnedTask } from '../work/TaskCard' import ProjectIcon from '../chat/ProjectIcon' import Composer, { type ComposerHandle, type FollowUpPayload } from '../chat/Composer' import QueuedMessages from '../chat/QueuedMessages' @@ -705,6 +706,9 @@ export default function ChatView({ onAuthError, visible = true, onOpenMenu, pane ? : null + // The task the strip over the composer names (TaskBar), pinned at the top right. + const pinnedTaskRef = (active && !empty ? active.taskId : null) || (active ? null : draftTaskId) || null + // The one side panel showing, if any, and its own remembered width. const sidePanel = artifact ? { id: 'canvas', label: 'Resize the canvas' } : agentsShown ? { id: 'agents', label: 'Resize the agents panel' } @@ -743,6 +747,8 @@ export default function ChatView({ onAuthError, visible = true, onOpenMenu, pane temporary={(!active || empty) && !project ? { on: temporary, onToggle: () => newChat(temporary ? 'regular' : 'temporary') } : undefined} newChatAtEnd={narrow} /> + {/* The chat's task, pinned at its top right while the chat is open (work/TaskCard.tsx). */} + {pinnedTaskRef && } {picking && active && !active.totemId && ( setPicking(false)}> { expect(prevented).toBe(true) }) - it('a description typed and then left by clicking the page is saved', async () => { + it('a description typed and then left by clicking the backdrop is saved', async () => { const user = await mount() act(() => openTaskCard('today')) const card = await screen.findByRole('dialog', { name: 'Task: Call the bank' }) + expect(card).toHaveAttribute('aria-modal', 'true') await user.click(within(card).getByRole('textbox', { name: 'Description' })) await user.keyboard('Ask about the fee') - await user.click(screen.getByRole('heading', { name: 'Tasks' })) + // A click inside the card leaves it open; the backdrop around it closes it. + await user.click(within(card).getByText('Folder')) + expect(screen.getByRole('dialog', { name: 'Task: Call the bank' })).toBeVisible() + await user.pointer({ keys: '[MouseLeft]', target: card.parentElement! }) await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Task: Call the bank' })).toBeNull()) await waitFor(() => expect(last(sent('PATCH', /\/api\/todos\/today$/))?.body).toEqual({ description: 'Ask about the fee' })) }) @@ -206,4 +210,59 @@ describe('the composer’s task strip', () => { }) }) +describe('the chat’s pinned task', () => { + function Chat({ visible = true }: { visible?: boolean }) { + return ( +
+ +

Messages

+ +
+ ) + } + + it('stays put while the page is clicked, folds, and saves from its rows', async () => { + // jsdom lays out a 0px column, which would start it folded. + localStorage.setItem('totem.taskPin.folded', '0') + const user = userEvent.setup() + render(<>) + const pin = await screen.findByRole('complementary', { name: /Call the bank/ }) + expect(screen.queryByRole('dialog')).toBeNull() + await user.click(screen.getByText('Messages')) + await user.keyboard('{Escape}') + expect(screen.getByRole('complementary', { name: /Call the bank/ })).toBeVisible() + + await user.click(within(pin).getByRole('button', { name: /Today/ })) + await user.click(await screen.findByRole('menuitemradio', { name: /^Tomorrow/ })) + await waitFor(() => expect(sent('PATCH', /\/api\/todos\/today$/)[0]?.body).toEqual({ dueDate: '2026-11-10' })) + + await user.click(within(pin).getByRole('button', { name: 'Fold the task' })) + expect(within(pin).queryByRole('textbox', { name: 'Description' })).toBeNull() + expect(localStorage.getItem('totem.taskPin.folded')).toBe('1') + await user.click(within(pin).getByRole('button', { name: 'Show the task’s settings', expanded: false })) + expect(within(pin).getByRole('textbox', { name: 'Description' })).toBeVisible() + }) + + it('opening the chat’s own task unfolds the pinned card instead of a dialog', async () => { + localStorage.setItem('totem.taskPin.folded', '1') + const user = userEvent.setup() + render(<>) + const pin = await screen.findByRole('complementary', { name: /Call the bank/ }) + expect(within(pin).queryByRole('textbox', { name: 'Description' })).toBeNull() + await user.click(within(screen.getByRole('group', { name: 'Linked task' })).getByRole('button', { name: /Call the bank/ })) + expect(within(pin).getByRole('textbox', { name: 'Description' })).toBeVisible() + expect(screen.queryByRole('dialog')).toBeNull() + // Any other task still opens as a dialog. + act(() => openTaskCard('site')) + expect(await screen.findByRole('dialog', { name: 'Task: Fix the footer' })).toBeVisible() + }) + + it('a chat behind another page does not catch its task: that opens as a dialog', async () => { + render(<>) + await screen.findByRole('complementary', { name: /Call the bank/ }) + act(() => openTaskCard('today')) + expect(await screen.findByRole('dialog', { name: 'Task: Call the bank' })).toBeVisible() + }) +}) + function last(list: T[]) { return list[list.length - 1] } diff --git a/web/src/work/TaskCard.tsx b/web/src/work/TaskCard.tsx index 2d0c49e..a132c4e 100644 --- a/web/src/work/TaskCard.tsx +++ b/web/src/work/TaskCard.tsx @@ -4,7 +4,7 @@ import { useChat } from '../chat/store' import { ThreadItem } from '../chat/ThreadList' import { TI } from '../chat/ui' import { - IconArrowUpRight, IconCalendar, IconChevronDown, IconCircle, IconCircleCheck, IconExternalLink, IconFlag, IconFolder, + IconArrowUpRight, IconCalendar, IconChevronDown, IconChevronUp, IconCircle, IconCircleCheck, IconExternalLink, IconFlag, IconFolder, IconMessage, IconPlus, IconRepeat, IconTable, IconTrash, IconX, IconZzz, } from '../chat/icons' import { SHEET_PRIORITY_WORD, wakeLabel } from '../todos/board' @@ -13,20 +13,32 @@ import { DueMenu, PriorityMenu, priorityName, RepeatMenu, SnoozeMenu } from '../ import { repeatWords } from '../todos/TaskRow' import '../todos/todos.css' import { chatsByTask, resolveRef, type WorkTask } from './groups' -import { closeTaskCard, newTaskChat, openTaskChat, showInTasks, useTaskCard } from './card' +import { closeTaskCard, newTaskChat, openTaskChat, pinTask, showInTasks, useTaskCard } from './card' import { FolderField } from './FolderField' import { completeTask, deleteTask, findTask, reopenTask, setTaskFolder, snoozeTask, updateTask, useWork } from './state' import './work.css' -// The floating task card, T3 Code's thread card for a task: opened from a task in -// the chats panel's Tasks face or from a chat's task strip, it hangs at the top -// right of the page with each of the task's settings as a row with a dropdown -// (folder, due day, priority, repeat, snooze), its description, the chats working -// on it and the way to the Tasks page. Every change saves at once, through the same -// store the panel reads, and the Tasks page reads it again (todos/bus.ts). On a -// phone it is a sheet from the bottom. A sheet row shows read-only, but can be filed. +// A task's card, T3 Code's thread card for a task: the check circle and title, one +// row per setting with a dropdown (folder, due day, priority, repeat, snooze), its +// description, the chats working on it and the way to the Tasks page. Every change +// saves at once, through the same store the chats panel reads, and the Tasks page +// reads it again (todos/bus.ts). A sheet row shows read-only, but can be filed. +// +// It is drawn two ways: +// - Pinned (PinnedTask): the open chat's own task sits at the chat's top right for +// as long as the chat is on screen. Nothing outside closes it; it folds to its +// title row, and folds itself while the chat column is too narrow to keep it +// beside the messages. When it is unfolded the messages and composer move left +// to clear it (work.css). Not on a phone, where the strip opens the sheet. +// - A dialog (TaskCardHost, mounted once by App): any other task, opened from the +// chats panel or the strip, in a modal over a backdrop, so it is edited without a +// card hanging over the page. Esc, × or the backdrop close it. On a phone it is a +// sheet from the bottom. const PHONE = '(max-width: 720px)' +/** Below this chat column width the pinned card starts folded, until the owner unfolds it. */ +const PIN_ROOM = 1000 +const PIN_FOLD_KEY = 'totem.taskPin.folded' function usePhone() { const [phone, setPhone] = useState(() => typeof window !== 'undefined' && Boolean(window.matchMedia?.(PHONE).matches)) @@ -40,31 +52,10 @@ function usePhone() { return phone } -/** - * Where the card sits on a desktop: at the page's right, below the page's own - * header (its search, New task and "…"), or below the page's top edge when the - * page has no header near the top. - */ -function usePlacement(on: boolean) { - const [place, setPlace] = useState({ top: 56, right: 16 }) - useLayoutEffect(() => { - if (!on) return - const measure = () => { - const main = document.querySelector('main.main') - const rect = main?.getBoundingClientRect() - if (!rect) return - const head = main?.querySelector('header')?.getBoundingClientRect() - const below = head && head.height > 0 && head.bottom - rect.top < 200 ? head.bottom + 8 : rect.top + 56 - setPlace({ top: Math.round(below), right: Math.max(8, Math.round(window.innerWidth - rect.right + 14)) }) - } - measure() - window.addEventListener('resize', measure) - return () => window.removeEventListener('resize', measure) - }, [on]) - return place -} +/** A menu or picker the card opened is up (they are portalled, and take Esc and outside clicks first). */ +const menuUp = () => Boolean(document.querySelector('.wk-combo, .tk-menu')) -/** Mounted once, by App: draws the card for whichever task is open. */ +/** Mounted once, by App: the dialog for whichever task is open. */ export default function TaskCardHost() { const ref = useTaskCard() // Subscribing keeps the task store fresh while a card is up. @@ -73,46 +64,136 @@ export default function TaskCardHost() { // A task that left the list (deleted elsewhere) closes its card once the list has been read. useEffect(() => { if (ref && loaded && !task) closeTaskCard() }, [ref, loaded, task]) if (!ref || !task) return null - return + return } -type MenuKind = 'due' | 'priority' | 'repeat' | 'snooze' - -function TaskCard({ task }: { task: WorkTask }) { +function TaskDialog({ task }: { task: WorkTask }) { const phone = usePhone() - const place = usePlacement(!phone) const card = useRef(null) - const [menu, setMenu] = useState<{ kind: MenuKind; anchor: HTMLElement } | null>(null) - const now = new Date() - const todo = task.todo - const sheet = task.sheet + + // Leaving saves the field being typed in first (WebKit fires no blur on a field that is removed). + const close = () => { + const active = document.activeElement as HTMLElement | null + if (active && card.current?.contains(active)) active.blur() + closeTaskCard() + } + const latestClose = useRef(close) + latestClose.current = close + + // Focus moves into the dialog, and back to what had it when it closes (unless + // closing went somewhere that took focus, like a chat's composer). + useEffect(() => { + const before = document.activeElement as HTMLElement | null + card.current?.focus({ preventScroll: true }) + return () => { + const now = document.activeElement + if (before && before.isConnected && (!now || now === document.body)) before.focus?.({ preventScroll: true }) + } + }, []) // Esc closes it, unless a menu or the folder picker over it is open (they close // themselves first); it takes the key, so a side panel listening on window stays. - // A click on the page closes it too, after the field being typed in has saved - // (WebKit fires no blur on a field that is removed). useEffect(() => { - const close = () => { - const active = document.activeElement as HTMLElement | null - if (active && card.current?.contains(active)) active.blur() - closeTaskCard() - } const onKey = (event: KeyboardEvent) => { - if (event.key !== 'Escape' || event.defaultPrevented || menu || document.querySelector('.wk-combo, .tk-menu')) return + if (event.key !== 'Escape' || event.defaultPrevented || menuUp()) return event.preventDefault() - close() - } - const onDown = (event: PointerEvent) => { - const target = event.target as Element | null - if (!target || card.current?.contains(target)) return - // Its own menus and pickers are portalled; a task row opens another card. - if (target.closest('[role="menu"], [role="dialog"], [role="listbox"], .wk-task, .wk-taskbar-title, .tk-menu, .wk-combo')) return - close() + latestClose.current() } document.addEventListener('keydown', onKey) - document.addEventListener('pointerdown', onDown) - return () => { document.removeEventListener('keydown', onKey); document.removeEventListener('pointerdown', onDown) } - }, [menu]) + return () => document.removeEventListener('keydown', onKey) + }, []) + + return createPortal( +
{ if (event.target === event.currentTarget && !menuUp()) close() }} + > + +
, + document.body, + ) +} + +/** + * The open chat's task, pinned at the chat's top right. ChatView mounts it inside + * `.vc`; `visible` is whether the chat is the page on screen (it stays mounted + * behind other pages), and only then does opening the task reveal this panel. + */ +export function PinnedTask({ taskRef, visible }: { taskRef: string; visible: boolean }) { + const phone = usePhone() + const task = useWork(() => findTask(taskRef)) + if (phone || !task) return null + return +} + +function readFoldPref(): boolean | null { + try { + const v = localStorage.getItem(PIN_FOLD_KEY) + return v === '1' ? true : v === '0' ? false : null + } catch { return null } +} + +function Pinned({ task, visible }: { task: WorkTask; visible: boolean }) { + const card = useRef(null) + // The owner's own fold, kept on this device; with none, it folds while the column is narrow. + const [pref, setPref] = useState(readFoldPref) + // Opening the task elsewhere unfolds it for now, without changing that choice. + const [revealed, setRevealed] = useState(false) + const [narrow, setNarrow] = useState(false) + const [flash, setFlash] = useState(0) + + useLayoutEffect(() => { + const column = card.current?.closest('.vc') + if (!column) return + const measure = () => setNarrow(column.clientWidth < PIN_ROOM) + measure() + if (typeof ResizeObserver === 'undefined') return + const ro = new ResizeObserver(measure) + ro.observe(column) + return () => ro.disconnect() + }, []) + + useEffect(() => { + if (!visible) return + return pinTask(task.ref, () => { setRevealed(true); setFlash((n) => n + 1) }) + }, [visible, task.ref]) + + useEffect(() => { + if (!flash) return + const t = window.setTimeout(() => setFlash(0), 900) + return () => window.clearTimeout(t) + }, [flash]) + + const folded = !revealed && (pref ?? narrow) + const setFolded = (next: boolean) => { + setRevealed(false) + setPref(next) + try { localStorage.setItem(PIN_FOLD_KEY, next ? '1' : '0') } catch { /* private window: this visit only */ } + } + + return 0} /> +} + +type MenuKind = 'due' | 'priority' | 'repeat' | 'snooze' +type Mode = 'dialog' | 'sheet' | 'pinned' + +interface BodyProps { + task: WorkTask + mode: Mode + cardRef: React.RefObject + /** A dialog's way out; a pinned card has none. */ + onClose?: () => void + folded?: boolean + onFold?: (folded: boolean) => void + flash?: boolean +} + +function CardBody({ task, mode, cardRef, onClose, folded = false, onFold, flash = false }: BodyProps) { + const [menu, setMenu] = useState<{ kind: MenuKind; anchor: HTMLElement } | null>(null) + const now = new Date() + const todo = task.todo + const sheet = task.sheet + const pinned = mode === 'pinned' const title = useDraft(task.title, (next) => { if (todo && next.trim() && next.trim() !== todo.title) void updateTask(task.ref, { title: next.trim() }) }) const description = useDraft(todo?.description ?? '', (next) => { if (todo && next !== todo.description) void updateTask(task.ref, { description: next }) }) @@ -124,83 +205,99 @@ function TaskCard({ task }: { task: WorkTask }) { if (!el) return el.style.height = 'auto' el.style.height = `${el.scrollHeight}px` - }, [title.bind.value]) + }, [title.bind.value, folded]) const open = (kind: MenuKind) => (event: React.MouseEvent) => setMenu({ kind, anchor: event.currentTarget }) - const body = ( -
-
- {todo ? ( - - ) : } - {todo ? ( -