From 3eb87e9e6ca6af2f8f7be71a934257f29b897b04 Mon Sep 17 00:00:00 2001 From: Stephan Terning Date: Sun, 1 Nov 2026 22:16:29 +0100 Subject: [PATCH 1/3] Improve task documents, safe editing, images and workspace navigation --- apps/api/src/content/files.ts | 21 +- apps/api/src/content/routes.ts | 4 +- apps/api/src/content/search.ts | 7 +- apps/api/src/tasks/tasks.integration.test.ts | 19 +- apps/web/src/components/ui/dialog.tsx | 33 +- apps/web/src/content/ContentPanel.tsx | 139 +++++--- apps/web/src/content/LinkDialog.tsx | 45 +++ apps/web/src/content/RichEditor.tsx | 311 ++++++++---------- apps/web/src/content/Search.tsx | 34 +- apps/web/src/content/UploadQueue.ts | 66 ++++ apps/web/src/content/Uploads.tsx | 41 +++ apps/web/src/content/api.ts | 57 ++-- apps/web/src/content/i18n.ts | 33 +- apps/web/src/content/imagePlacement.test.ts | 35 ++ apps/web/src/content/imagePlacement.ts | 65 ++++ apps/web/src/content/searchHighlight.test.ts | 10 + apps/web/src/content/searchHighlight.ts | 40 +++ apps/web/src/content/uploads.test.ts | 45 +++ apps/web/src/navigation/Navigation.tsx | 23 ++ apps/web/src/navigation/routes.test.ts | 78 +++++ apps/web/src/navigation/routes.ts | 94 ++++++ apps/web/src/navigation/useDraftGuard.tsx | 30 ++ apps/web/src/style.css | 176 +++++++++- apps/web/src/tasks/TaskEditor.tsx | 250 +++++++++++--- apps/web/src/tasks/TaskFields.tsx | 15 +- apps/web/src/tasks/Workspace.tsx | 78 +++-- apps/web/src/tasks/api.ts | 12 +- apps/web/src/tasks/draft.test.ts | 196 +++++++++++ apps/web/src/tasks/draft.ts | 171 ++++++++++ apps/web/src/tasks/i18n.ts | 45 +++ apps/web/src/views/Editors.tsx | 32 +- apps/web/src/views/QuickBar.tsx | 26 +- apps/web/src/views/TaskPresentation.tsx | 26 +- .../decisions/0004-content-collaboration.md | 38 +++ docs/design/ux-ui-specification.md | 23 +- packages/shared/openapi.json | 10 + packages/shared/src/generated/api.ts | 4 +- tests/content-journey.ts | 114 +++++-- tests/tasks-journey.ts | 22 +- tests/views.spec.ts | 20 +- 40 files changed, 2065 insertions(+), 423 deletions(-) create mode 100644 apps/web/src/content/LinkDialog.tsx create mode 100644 apps/web/src/content/UploadQueue.ts create mode 100644 apps/web/src/content/Uploads.tsx create mode 100644 apps/web/src/content/imagePlacement.test.ts create mode 100644 apps/web/src/content/imagePlacement.ts create mode 100644 apps/web/src/content/searchHighlight.test.ts create mode 100644 apps/web/src/content/searchHighlight.ts create mode 100644 apps/web/src/content/uploads.test.ts create mode 100644 apps/web/src/navigation/Navigation.tsx create mode 100644 apps/web/src/navigation/routes.test.ts create mode 100644 apps/web/src/navigation/routes.ts create mode 100644 apps/web/src/navigation/useDraftGuard.tsx create mode 100644 apps/web/src/tasks/draft.test.ts create mode 100644 apps/web/src/tasks/draft.ts diff --git a/apps/api/src/content/files.ts b/apps/api/src/content/files.ts index 7973ec7..6eebe87 100644 --- a/apps/api/src/content/files.ts +++ b/apps/api/src/content/files.ts @@ -1,4 +1,4 @@ -import { eq } from 'drizzle-orm'; +import { eq, sql } from 'drizzle-orm'; import { randomUUID } from 'node:crypto'; import { mkdir, rm, stat, readdir } from 'node:fs/promises'; import { createWriteStream } from 'node:fs'; @@ -39,14 +39,29 @@ export class FileStore { if (!record) await rm(path, { force: true }); } } - async upload(actor: Actor, householdId: string, taskId: string, part: MultipartFile) { + async upload(actor: Actor, householdId: string, taskId: string, part: MultipartFile, uploadId: string = randomUUID()) { await this.service.task(actor, householdId, taskId); + // The same attempt keeps its ID after a lost response. A database lock also + // protects the original bytes from overlapping retries across API processes. + return this.service.db.transaction(async tx => { + const lock = await tx.execute(sql`select pg_try_advisory_xact_lock(hashtextextended(${uploadId}, 0)) as acquired`); + if (!lock.rows[0]?.acquired) { part.file.resume(); throw new AccountError('uploads_busy', 503); } + const [existing] = await tx.select().from(attachments).where(eq(attachments.id, uploadId)); + if (existing) { + part.file.resume(); + if (existing.householdId !== householdId || existing.taskId !== taskId || existing.deleted) + throw new AccountError('upload_id_conflict', 409); + return { ...existing, createdAt: existing.createdAt.toISOString() }; + } + return this.store(actor, householdId, taskId, part, uploadId); + }); + } + private async store(actor: Actor, householdId: string, taskId: string, part: MultipartFile, id: string) { if (this.active >= 2) { part.file.resume(); throw new AccountError('uploads_busy', 503); } this.active++; - const id = randomUUID(); try { await mkdir(this.root, { recursive: true }); await pipeline(part.file, createWriteStream(this.path(id), { flags: 'wx', mode: 0o600 })); diff --git a/apps/api/src/content/routes.ts b/apps/api/src/content/routes.ts index 1e33c96..294d61c 100644 --- a/apps/api/src/content/routes.ts +++ b/apps/api/src/content/routes.ts @@ -140,7 +140,7 @@ export async function registerContentRoutes( '/api/v1/households/:householdId/tasks/:taskId/attachments', { config: { fileUpload: true }, - schema: { params: task, response: { 200: attachmentSchema } }, + schema: { params: task, headers: z.object({ 'x-upload-id': z.uuid().optional() }), response: { 200: attachmentSchema } }, preHandler: async (r) => { await service.task(await actor(r), r.params.householdId, r.params.taskId); }, @@ -148,7 +148,7 @@ export async function registerContentRoutes( async (r) => { const part = await r.file(); if (!part) throw new AccountError('empty_file'); - return files.upload(await actor(r), r.params.householdId, r.params.taskId, part); + return files.upload(await actor(r), r.params.householdId, r.params.taskId, part, r.headers['x-upload-id']); }, ); for (const mode of ['download', 'preview', 'thumbnail'] as const) { diff --git a/apps/api/src/content/search.ts b/apps/api/src/content/search.ts index 0b6fc84..9e0e5a3 100644 --- a/apps/api/src/content/search.ts +++ b/apps/api/src/content/search.ts @@ -62,7 +62,7 @@ export async function searchContent( ) continue; if (matched++ >= offset) - items.push(searchHitSchema.parse({ ...row, snippet: text.slice(0, 250) })); + items.push(searchHitSchema.parse({ ...row, snippet: searchSnippet(text, needle) })); if (items.length === 51) break; } if (batch.rows.length < 256) break; @@ -77,3 +77,8 @@ export async function searchContent( { isolationLevel: 'repeatable read', accessMode: 'read only' }, ); } + +function searchSnippet(text: string, needle: string) { + const start = Math.max(0, text.toLowerCase().indexOf(needle) - 70); + return (start ? '…' : '') + text.slice(start, start + 250) + (start + 250 < text.length ? '…' : ''); +} diff --git a/apps/api/src/tasks/tasks.integration.test.ts b/apps/api/src/tasks/tasks.integration.test.ts index f00e7a4..75162b1 100644 --- a/apps/api/src/tasks/tasks.integration.test.ts +++ b/apps/api/src/tasks/tasks.integration.test.ts @@ -182,9 +182,22 @@ it('preserves rich content, enforces comment authorship/versioning and scopes se const bytes=await readFile(new URL('../../../../tests/fixtures/'+name,import.meta.url)); const boundary='tendly-test-boundary'; const payload=Buffer.concat([Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${name}"\r\nContent-Type: application/octet-stream\r\n\r\n`),bytes,Buffer.from(`\r\n--${boundary}--\r\n`)]); - const upload=await app.inject({method:'POST',url:path+'/attachments',headers:{...headers(sessionA),'content-type':`multipart/form-data; boundary=${boundary}`},payload}); - expect(upload.statusCode,upload.body).toBe(200); - const f=upload.json();expect(f.preview).toBe(true); + const uploadId = randomUUID(); + const request = {method:'POST' as const,url:path+'/attachments',headers:{...headers(sessionA),'x-upload-id':uploadId,'content-type':`multipart/form-data; boundary=${boundary}`},payload}; + const [upload, concurrent] = await Promise.all([app.inject(request), app.inject(request)]); + const succeeded = upload.statusCode === 200 ? upload : concurrent; + expect([200, 503]).toContain(upload.statusCode); + expect([200, 503]).toContain(concurrent.statusCode); + if (upload.statusCode === 200 && concurrent.statusCode === 200) expect(upload.json().id).toBe(concurrent.json().id); + const retry = await app.inject(request); + expect(retry.statusCode).toBe(200); + expect(retry.json().id).toBe(succeeded.json().id); + const listing = await app.inject({url:path+'/attachments',headers:headers(sessionA)}); + expect(listing.json().filter((item: {id:string}) => item.id === uploadId)).toHaveLength(1); + const foreignRetry = await app.inject({...request, url:`/api/v1/households/${householdB}/tasks/${task.id}/attachments`,headers:{...request.headers,cookie:headers(sessionB).cookie}}); + expect(foreignRetry.statusCode).toBe(404); + expect(succeeded.statusCode,succeeded.body).toBe(200); + const f=succeeded.json();expect(f.preview).toBe(true); const url=`/api/v1/households/${householdA}/attachments/${f.id}`; expect((await app.inject({url:url+'/download',headers:headers(sessionA)})).rawPayload).toEqual(bytes); const preview=await app.inject({url:url+'/preview',headers:headers(sessionA)}); diff --git a/apps/web/src/components/ui/dialog.tsx b/apps/web/src/components/ui/dialog.tsx index ac79e39..8640c97 100644 --- a/apps/web/src/components/ui/dialog.tsx +++ b/apps/web/src/components/ui/dialog.tsx @@ -1,25 +1,44 @@ import * as DialogPrimitive from '@radix-ui/react-dialog'; import { useRef, type ReactNode } from 'react'; -import { X } from 'lucide-react'; +import { ArrowLeft, X } from 'lucide-react'; import { useTranslation } from 'react-i18next'; // shadcn/ui's Radix composition: focus trapping, Escape and focus restoration live // in the primitive; Tendly supplies its responsive sheet treatment. -export function Dialog({ open, onOpenChange, title, children, sheet = false, wide = false }: { +export function Dialog({ open, onOpenChange, title, children, sheet = false, wide = false, className = '', headerContent, mobileBack = false, onReturnFocus, onInitialFocus }: { open: boolean; onOpenChange: (open: boolean) => void; title: string; children: ReactNode; sheet?: boolean; wide?: boolean; + className?: string; headerContent?: ReactNode; mobileBack?: boolean; + onReturnFocus?: () => void; + onInitialFocus?: () => void; }) { const { t } = useTranslation(); const returnFocus = useRef(document.activeElement); return - { + { + if (onInitialFocus) { event.preventDefault(); onInitialFocus(); } + }} onCloseAutoFocus={event => { event.preventDefault(); - const target = returnFocus.current; - if (target instanceof HTMLElement && target.isConnected) target.focus(); - else document.querySelector('.workspace-main')?.focus(); + if (onReturnFocus) { onReturnFocus(); return; } + const closing = event.currentTarget; + requestAnimationFrame(() => { + const nextDialog = [...document.querySelectorAll('[role="dialog"]')].filter(el => el !== closing && el.getClientRects().length).at(-1); + if (nextDialog) { + if (!nextDialog.contains(document.activeElement)) (nextDialog.querySelector('input:not([disabled]), textarea:not([disabled]), button:not([disabled])') ?? nextDialog).focus({ preventScroll: true }); + return; + } + const target = returnFocus.current; + if (target instanceof HTMLElement && target.isConnected) target.focus({ preventScroll: true }); + else document.querySelector('.workspace-main')?.focus({ preventScroll: true }); + }); }}>
{title} - +
{headerContent} + +
{children}
diff --git a/apps/web/src/content/ContentPanel.tsx b/apps/web/src/content/ContentPanel.tsx index 6858142..7fea1b4 100644 --- a/apps/web/src/content/ContentPanel.tsx +++ b/apps/web/src/content/ContentPanel.tsx @@ -1,10 +1,12 @@ -import { useEffect, useId, useState } from 'react'; +import { useEffect, useId, useRef, useState } from 'react'; +import { Camera, ChevronLeft, ChevronRight, FileText, Plus } from 'lucide-react'; import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'; import { useTranslation } from 'react-i18next'; import { toDocument, documentSchema, plainText, type TaskFields } from '@tendly/shared'; import { api, result } from '../accounts/api.js'; import { RichEditor } from './RichEditor.js'; -import { uploadFiles } from './api.js'; +import { uploadFile, type UploadedFile } from './api.js'; +import { Uploads, useUploads } from './Uploads.js'; import { Dialog } from '../components/ui/dialog.js'; import type { Member } from '../tasks/TaskFields.js'; export function ContentPanel({ @@ -12,11 +14,18 @@ export function ContentPanel({ taskId, userId, members, + onBusyChange, + onPendingChange, + onInsert, commentId = '', searchMatch = '', }: { householdId: string; + commentId?: string; searchMatch?: string; taskId: string; userId: string; members: Member[]; + onBusyChange?: (busy: boolean) => void; + onPendingChange?: (pending: boolean) => void; + onInsert?: (file: UploadedFile) => void; }) { const { t, i18n } = useTranslation(); const tabsId = useId(); @@ -52,6 +61,8 @@ export function ContentPanel({ } }, [draftKey, draft, editing]); const [undo, setUndo] = useState<{ id: string; version: number } | null>(null); + const [editorBusy, setEditorBusy] = useState(false); + const [editorPending, setEditorPending] = useState(false); const [busy, setBusy] = useState(false), [error, setError] = useState(''), [preview, setPreview] = useState<{ @@ -59,6 +70,9 @@ export function ContentPanel({ name: string; image: boolean; } | null>(null); + const uploads = useUploads((...args) => upload(...args)); + useEffect(() => { onBusyChange?.(busy || editorBusy || uploads.busy); }, [busy, editorBusy, uploads.busy, onBusyChange]); + useEffect(() => { onPendingChange?.(editorPending || uploads.pending); }, [editorPending, uploads.pending, onPendingChange]); const policy = useQuery({ queryKey: ['planning', householdId, 'upload-policy'], queryFn: () => @@ -101,16 +115,31 @@ export function ContentPanel({ }), ), }); + const landedComment = useRef(''); + const targetComment = comments.data?.pages.flatMap(p => p.items).find(c => c.id === commentId); + useEffect(() => { + if (!commentId || landedComment.current === commentId || comments.isError || files.isPending) return; + if (!targetComment) { + if (comments.hasNextPage && !comments.isFetching) void comments.fetchNextPage(); + return; + } + setTab('comments'); + const frame = requestAnimationFrame(() => { + const element = document.getElementById('comment-' + commentId); + if (element) { element.scrollIntoView({ block: 'center' }); element.focus({ preventScroll: true }); landedComment.current = commentId; } + }); + return () => cancelAnimationFrame(frame); + }, [commentId, targetComment, comments, files.isPending]); const refresh = (key = 'comments') => queries.invalidateQueries({ queryKey: ['planning', householdId, key, taskId], }); - const upload = async (selected: File[]) => { + const upload = async (file: File, id: string, progress: (percent: number) => void) => { setError(''); try { - return await uploadFiles(householdId, taskId, selected); + return await uploadFile(householdId, taskId, file, id, progress); } finally { - await refresh('attachments'); + void refresh('attachments'); } }; async function post() { @@ -162,6 +191,12 @@ export function ContentPanel({ setBusy(false); } } + const images = files.data?.filter(file => file.preview) ?? []; + const imageIndex = images.findIndex(file => file.id === preview?.id); + function navigateImage(direction: number) { + const file = images[(imageIndex + direction + images.length) % images.length]; + if (file) setPreview({ id: file.id, name: file.name, image: true }); + } const date = (v: string) => new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium', @@ -169,83 +204,70 @@ export function ContentPanel({ }).format(new Date(v)); return (
-

{t('attachments')}

-

- {t('fileHelp', { - max: (policy.data?.maxBytes ?? 50_000_000) / 1_000_000, - })} -

-
+
+

{t('attachments')}{files.data && {files.data.length}}

+
+
+ {files.isLoading &&

{t('loadingFiles')}

} {files.isError && (

{t('network_error')}

)} -
    - {files.data?.map((f) => ( -
  • - {f.preview && ( - - )} - - {f.name} - {(f.size / 1_000_000).toFixed(1)} MB - - {(f.preview || f.mime === 'application/pdf') && ( - - )} - - {t('download')} - + +
      + {files.data?.map(file => ( +
    • + {file.preview || file.mime === 'application/pdf' ? :
      {file.name}
      } +
      {(file.size / 1_000_000).toFixed(1)} MB + {t('download')} +
      + {file.preview && onInsert && }
    • ))}
    + {!files.isLoading && !files.isError && files.data?.length === 0 &&

    {t('emptyAttachments')}

    } +
    {t('fileInformation')}

    {t('fileHelp', { max: (policy.data?.maxBytes ?? 50_000_000) / 1_000_000 })}

    { + if (editorPending || busy) return; if (['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) { event.preventDefault(); const next = @@ -275,6 +297,7 @@ export function ContentPanel({ {editing && (

    )} + {commentId && !targetComment && !comments.hasNextPage && !comments.isFetching && !comments.isError &&

    {t('searchTargetGone')}

    } {comments.data?.pages .flatMap((p) => p.items) .map((c) => ( -
    +
    {c.author} @@ -359,12 +386,12 @@ export function ContentPanel({ {t('edited')} )}
    - + {c.authorId === userId && (
    + {imageIndex + 1} / {images.length} + +
    } {t('downloadOriginal')} diff --git a/apps/web/src/content/LinkDialog.tsx b/apps/web/src/content/LinkDialog.tsx new file mode 100644 index 0000000..25d6620 --- /dev/null +++ b/apps/web/src/content/LinkDialog.tsx @@ -0,0 +1,45 @@ +import { useRef, useState } from 'react'; +import type { Editor } from '@tiptap/react'; +import { safeLink } from '@tendly/shared'; +import { ExternalLink } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { Dialog } from '../components/ui/dialog.js'; + +export function LinkDialog({ editor, onClose }: { editor: Editor; onClose: () => void }) { + const { t } = useTranslation(); + const [original] = useState(() => String(editor.getAttributes('link').href ?? '')); + const [address, setAddress] = useState(original); + const [invalid, setInvalid] = useState(false); + const input = useRef(null); + function save() { + const href = address.trim(); + if (!href || !safeLink(href)) { setInvalid(true); return; } + if (editor.state.selection.empty && !editor.isActive('link')) + editor.chain().insertContent({ type: 'text', text: href, marks: [{ type: 'link', attrs: { href } }] }).run(); + else editor.chain().extendMarkRange('link').setLink({ href }).run(); + onClose(); + } + return { if (!open) onClose(); }} + onInitialFocus={() => input.current?.focus()} + onReturnFocus={() => { editor.commands.focus(undefined, { scrollIntoView: false }); }}> +
    + {original && safeLink(original) && + {t('openLink')}{original} + } + + {invalid &&

    {t('invalid_link')}

    } +
    + + + {original && } +
    +
    +
    ; +} diff --git a/apps/web/src/content/RichEditor.tsx b/apps/web/src/content/RichEditor.tsx index ca9f6bb..7f24fda 100644 --- a/apps/web/src/content/RichEditor.tsx +++ b/apps/web/src/content/RichEditor.tsx @@ -1,6 +1,7 @@ +import { SearchHighlight, searchHighlightKey } from './searchHighlight.js'; import { EditorState } from '@tiptap/pm/state'; import { useEffect, useRef, useState } from 'react'; -import { useEditor, EditorContent } from '@tiptap/react'; +import { useEditor, useEditorState, EditorContent } from '@tiptap/react'; import StarterKit from '@tiptap/starter-kit'; import TaskList from '@tiptap/extension-task-list'; import TaskItem from '@tiptap/extension-task-item'; @@ -8,6 +9,12 @@ import Image from '@tiptap/extension-image'; import Mention from '@tiptap/extension-mention'; import { documentSchema, toDocument, safeLink, type TaskFields } from '@tendly/shared'; import { useTranslation } from 'react-i18next'; +import { ImagePlus, Link, ListChecks, ChevronDown, Expand, Bold, Italic } from 'lucide-react'; +import { Dialog } from '../components/ui/dialog.js'; +import { LinkDialog } from './LinkDialog.js'; +import { ImagePlacements, addPlacements, imagePlacements, insertUploadedFile, removePlacement } from './imagePlacement.js'; +import { Uploads, useUploads } from './Uploads.js'; +import type { FileUploader, UploadedFile } from './api.js'; import type { Member } from '../tasks/TaskFields.js'; const SafeImage = Image.extend({ parseHTML() { @@ -32,16 +39,31 @@ export function RichEditor({ readOnly = false, onUpload, onValidityChange, + onBusyChange, + onPendingChange, + insertion, + documentMode = false, + searchMatch = '', }: { value: TaskFields['description']; + searchMatch?: string; + documentMode?: boolean; onValidityChange?: (valid: boolean) => void; + onBusyChange?: (busy: boolean) => void; + onPendingChange?: (pending: boolean) => void; + insertion?: { file: UploadedFile } | undefined; onChange?: (value: TaskFields['description']) => void; label: string; members?: Member[]; readOnly?: boolean; - onUpload?: (files: File[]) => Promise<{ src: string; name: string; image: boolean }[]>; + onUpload?: FileUploader; }) { const { t } = useTranslation(); + const [imagePreview, setImagePreview] = useState<{ src: string; name: string } | null>(null); + const uploads = useUploads((...args) => { + if (!upload.current) return Promise.reject(new Error('operation_failed')); + return upload.current(...args); + }, onBusyChange, onPendingChange); const validity = useRef(onValidityChange); validity.current = onValidityChange; const change = useRef(onChange); @@ -50,8 +72,7 @@ export function RichEditor({ upload.current = onUpload; const memberRef = useRef(members); memberRef.current = members; - const [link, setLink] = useState(''), - [linkOpen, setLinkOpen] = useState(false), + const [linkOpen, setLinkOpen] = useState(false), [error, setError] = useState(''); const editor = useEditor({ extensions: [ @@ -63,7 +84,9 @@ export function RichEditor({ }, }), TaskList, - TaskItem.configure({ nested: true }), + ImagePlacements, + SearchHighlight, + TaskItem.configure({ nested: true, a11y: { checkboxLabel: node => node.firstChild?.textContent || t('emptyChecklistItem') } }), SafeImage.configure({ allowBase64: false }), Mention.configure({ HTMLAttributes: { class: 'mention' }, @@ -141,6 +164,23 @@ export function RichEditor({ 'aria-label': label, 'aria-multiline': 'true', 'aria-readonly': String(readOnly), + 'data-placeholder': t('descriptionPrompt'), + }, + handleClick: (view, pos, event) => { + const anchor = event.target instanceof Element ? event.target.closest('a') : null; + if (readOnly || !anchor || !view.dom.contains(anchor)) return false; + event.preventDefault(); + editor?.chain().setTextSelection(pos).extendMarkRange('link').run(); + setLinkOpen(true); + return true; + }, + handleKeyDown: (_view, event) => { + if (!readOnly && (event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') { + event.preventDefault(); + setLinkOpen(true); + return true; + } + return false; }, handlePaste: (_view, event) => { const files = Array.from(event.clipboardData?.files ?? []); @@ -149,11 +189,12 @@ export function RichEditor({ void addFiles(files); return true; }, - handleDrop: (_view, event) => { + handleDrop: (view, event) => { const files = Array.from(event.dataTransfer?.files ?? []); if (!upload.current || !files.length) return false; event.preventDefault(); - void addFiles(files); + const pos = view.posAtCoords({ left: event.clientX, top: event.clientY })?.pos; + addFiles(files, pos); return true; }, }, @@ -168,28 +209,25 @@ export function RichEditor({ } }, }); - async function addFiles(files: File[]) { - try { - for (const file of (await upload.current?.(files)) ?? []) { - if (file.image) editor?.chain().focus().setImage({ src: file.src, alt: file.name }).run(); - else - editor - ?.chain() - .focus() - .insertContent([ - { - type: 'text', - text: file.name, - marks: [{ type: 'link', attrs: { href: file.src } }], - }, - { type: 'text', text: ' ' }, - ]) - .run(); - } - } catch (e) { - setError(e instanceof Error ? e.message : 'operation_failed'); - } + useEffect(() => { + if (!editor) return; + editor.view.dispatch(editor.state.tr.setMeta(searchHighlightKey, searchMatch).setMeta('addToHistory', false)); + if (!searchMatch || !documentMode) return; + const frame = requestAnimationFrame(() => editor.view.dom.querySelector('.search-match')?.scrollIntoView({ block: 'center' })); + return () => cancelAnimationFrame(frame); + }, [editor, searchMatch, documentMode]); + function addFiles(files: File[], position = editor?.state.selection.from) { + if (!editor || position === undefined || !files.length || readOnly) return; + const anchors = files.map(file => ({ id: crypto.randomUUID(), name: file.name, pos: position })); + addPlacements(editor, anchors); + files.forEach((file, index) => { + const id = anchors[index]!.id; + uploads.queue.add(id, file, result => insertUploadedFile(editor, result, id), () => removePlacement(editor, id)); + }); } + useEffect(() => { + if (editor && insertion) insertUploadedFile(editor, insertion.file); + }, [editor, insertion]); useEffect(() => { if (!editor) return; const current = documentSchema.safeParse(editor.getJSON()); @@ -199,6 +237,8 @@ export function RichEditor({ incoming.success && !editor.schema.nodeFromJSON(incoming.data).eq(editor.state.doc) ) { + setLinkOpen(false); + editor.view.dispatch(editor.state.tr.setMeta(imagePlacements, { clear: true })); editor.commands.setContent(toDocument(incoming.data), { emitUpdate: false, }); @@ -212,158 +252,93 @@ export function RichEditor({ plugins: editor.state.plugins, }), ); + editor.view.dispatch(editor.state.tr.setMeta(searchHighlightKey, searchMatch).setMeta('addToHistory', false)); } }, [editor, value]); - if (!editor) return null; - const action = (name: string, run: () => void, active = false) => ( - ); return ( -
    +
    { + const image = event.target; + if (image instanceof HTMLImageElement && image.closest('.tiptap')) + setImagePreview({ src: image.getAttribute('src') ?? '', name: image.alt || t('image') }); + }}> {!readOnly && (
    - {action( - 'bold', - () => { - editor.chain().focus().toggleBold().run(); - }, - editor.isActive('bold'), - )} - {action( - 'italic', - () => { - editor.chain().focus().toggleItalic().run(); - }, - editor.isActive('italic'), - )} - {action( - 'heading', - () => { - editor.chain().focus().toggleHeading({ level: 2 }).run(); - }, - editor.isActive('heading'), - )} - {action( - 'bulletList', - () => { - editor.chain().focus().toggleBulletList().run(); - }, - editor.isActive('bulletList'), - )} - {action( - 'orderedList', - () => { - editor.chain().focus().toggleOrderedList().run(); - }, - editor.isActive('orderedList'), - )} - {action( - 'checklist', - () => { - editor.chain().focus().toggleTaskList().run(); - }, - editor.isActive('taskList'), - )} - {action( - 'quote', - () => { - editor.chain().focus().toggleBlockquote().run(); - }, - editor.isActive('blockquote'), - )} - {action( - 'codeBlock', - () => { - editor.chain().focus().toggleCodeBlock().run(); - }, - editor.isActive('codeBlock'), - )} - {action( - 'link', - () => { - setLinkOpen(!linkOpen); - setLink(String(editor.getAttributes('link').href ?? '')); - }, - editor.isActive('link'), - )} - {action('undo', () => { - editor.chain().focus().undo().run(); - })} - {action('redo', () => { - editor.chain().focus().redo().run(); - })} - {members.length > 0 && ( - - )} - {onUpload && ( - - )} -
    - )} - {linkOpen && ( -
    - - - + + + + {onUpload && } + +
    + Aa +
    + {action('heading', () => { editor.chain().focus().toggleHeading({ level: 2 }).run(); }, controls.heading)} + {action('bulletList', () => { editor.chain().focus().toggleBulletList().run(); }, controls.bulletList)} + {action('orderedList', () => { editor.chain().focus().toggleOrderedList().run(); }, controls.orderedList)} + {action('quote', () => { editor.chain().focus().toggleBlockquote().run(); }, controls.blockquote)} + {action('codeBlock', () => { editor.chain().focus().toggleCodeBlock().run(); }, controls.codeBlock)} + + + {members.length > 0 && } + {onUpload && } +
    +
    + {controls.image && }
    )} + {linkOpen && setLinkOpen(false)} />} + {!readOnly && { insertUploadedFile(editor, file); }} />} + {documentMode &&

    {t('inlineImageRetention')}

    } {error &&

    {t(error)}

    } + {imagePreview && { if (!open) setImagePreview(null); }}> + {imagePreview.name} +
    + {t('downloadOriginal')} + {!readOnly && controls.image && editor.getAttributes('image').src === imagePreview.src && } +
    + {!readOnly &&

    {t('inlineImageRetention')}

    } +
    }
    ); } diff --git a/apps/web/src/content/Search.tsx b/apps/web/src/content/Search.tsx index 43c9a09..7cdcf47 100644 --- a/apps/web/src/content/Search.tsx +++ b/apps/web/src/content/Search.tsx @@ -1,3 +1,4 @@ +import { routeUrl, type Route } from '../navigation/routes.js'; import { useViewCatalog, filterName } from '../views/api.js'; import { useEffect, useState } from 'react'; import { useInfiniteQuery } from '@tanstack/react-query'; @@ -6,17 +7,20 @@ import { api, result } from '../accounts/api.js'; export function Search({ householdId, openTask, - openLibrary, + openLibrary, route, onSearch, }: { householdId: string; - openTask: (id: string) => void; + openTask: (id: string, comment: string, match: string) => void; + route: Route; + onSearch: (q: string, filters: string[]) => void; openLibrary: (id: string) => void; }) { const { t } = useTranslation(); const catalog = useViewCatalog(householdId); - const [filterIds, setFilterIds] = useState([]); - const [input, setInput] = useState(''), - [q, setQ] = useState(''); + const filterIds = route.filters, input = route.q; + const setFilterIds = (ids: string[]) => onSearch(input, ids); + const setInput = (text: string) => onSearch(text, filterIds); + const [q, setQ] = useState(input.trim()); useEffect(() => { const timer = setTimeout(() => setQ(input.trim()), 250); return () => clearTimeout(timer); @@ -93,15 +97,17 @@ export function Search({ {search.hasNextPage && ( } + {entry.state === 'unplaced' && insert && } + {!['uploading', 'processing'].includes(entry.state) && } +
    +
  • )}
+ {completed.length > 0 &&
+
{t('uploadsComplete', { count: completed.length })} +
    {completed.map(entry =>
  • {entry.name}
  • )}
+
+ +
} +
; +} diff --git a/apps/web/src/content/api.ts b/apps/web/src/content/api.ts index f20d475..6e43890 100644 --- a/apps/web/src/content/api.ts +++ b/apps/web/src/content/api.ts @@ -1,28 +1,39 @@ import { api, result } from '../accounts/api.js'; import { attachmentSchema } from '@tendly/shared'; -export async function uploadFiles(householdId: string, taskId: string, files: File[]) { - const policy = await result( - api.GET('/api/v1/households/{householdId}/upload-policy', { - params: { path: { householdId } }, - }), - ); - const uploaded = []; - for (const file of files) { - if (file.size > policy.maxBytes) throw new Error('file_too_large'); +export type UploadedFile = { src: string; name: string; image: boolean; width?: number; height?: number }; +export type FileUploader = (file: File, id: string, progress: (percent: number) => void) => Promise; +export async function uploadFile(householdId: string, taskId: string, file: File, id: string, progress: (percent: number) => void): Promise { + const policy = await result(api.GET('/api/v1/households/{householdId}/upload-policy', { + params: { path: { householdId } }, signal: AbortSignal.timeout(12_000), + })); + if (!file.size) throw new Error('empty_file'); + if (file.size > policy.maxBytes) throw new Error('file_too_large'); + const data = await new Promise((resolve, reject) => { + const request = new XMLHttpRequest(); + request.open('POST', `/api/v1/households/${householdId}/tasks/${taskId}/attachments`); + request.setRequestHeader('X-Upload-Id', id); + request.timeout = 120_000; + request.upload.onprogress = event => { if (event.lengthComputable) progress(Math.round(event.loaded / event.total * 100)); }; + request.onerror = request.ontimeout = () => reject(new Error('upload_connection_lost')); + request.onload = () => { + try { + const response = JSON.parse(request.responseText); + if (request.status >= 200 && request.status < 300) resolve(response); + else reject(new Error(response.error ?? 'operation_failed')); + } catch { reject(new Error('upload_connection_lost')); } + }; const body = new FormData(); body.append('file', file); - const response = await fetch(`/api/v1/households/${householdId}/tasks/${taskId}/attachments`, { - method: 'POST', - body, - }); - const data: unknown = await response.json(); - if (!response.ok) throw new Error((data as { error?: string }).error ?? 'operation_failed'); - const item = attachmentSchema.parse(data); - uploaded.push({ - src: `/api/v1/households/${householdId}/attachments/${item.id}/${item.preview ? 'preview' : 'download'}`, - name: item.name, - image: item.preview, - }); - } - return uploaded; + request.send(body); + }); + const item = attachmentSchema.parse(data); + const src = `/api/v1/households/${householdId}/attachments/${item.id}/${item.preview ? 'preview' : 'download'}`; + const dimensions = item.preview ? await new Promise<{ width: number; height: number }>((resolve, reject) => { + const image = new Image(); + const timeout = setTimeout(() => { image.onload = image.onerror = null; reject(new Error('upload_connection_lost')); }, 12_000); + image.onload = () => { clearTimeout(timeout); resolve({ width: image.naturalWidth, height: image.naturalHeight }); }; + image.onerror = () => { clearTimeout(timeout); reject(new Error('upload_connection_lost')); }; + image.src = src; + }) : {}; + return { src, name: item.name, image: item.preview, ...dimensions }; } diff --git a/apps/web/src/content/i18n.ts b/apps/web/src/content/i18n.ts index 832b89f..4d1866f 100644 --- a/apps/web/src/content/i18n.ts +++ b/apps/web/src/content/i18n.ts @@ -1,4 +1,30 @@ export const contentCopy: Record = { + uploads: ['Uploads', 'Uppladdningar'], + uploadsComplete: ['Uploaded files: {{count}}', 'Uppladdade filer: {{count}}'], + clearCompletedUploads: ['Clear finished', 'Rensa klara'], + upload_queued: ['Waiting to upload', 'Väntar på uppladdning'], + upload_uploading: ['Uploading · {{percent}}%', 'Laddar upp · {{percent}} %'], + upload_processing: ['Preparing preview…', 'Förbereder förhandsvisning…'], + upload_done: ['Uploaded', 'Uppladdad'], + upload_unplaced: ['Uploaded to Images & files. The insertion point was removed; choose a new position in the text.', 'Uppladdad till Bilder och filer. Infogningsplatsen togs bort; välj en ny plats i texten.'], + upload_connection_lost: ['The connection was interrupted. Retry to check and finish this upload without making another copy.', 'Anslutningen avbröts. Försök igen för att kontrollera och slutföra uppladdningen utan en extra kopia.'], + upload_id_conflict: ['This upload could not be reused. Dismiss it and select the file again.', 'Uppladdningen kunde inte återanvändas. Ta bort den ur kön och välj filen igen.'], + dismissUpload: ['Dismiss from queue', 'Ta bort ur kön'], + insertHere: ['Insert at cursor', 'Infoga vid markören'], + insertInDescription: ['Insert in description', 'Infoga i beskrivningen'], + removeInlineImage: ['Remove from text', 'Ta bort ur texten'], + inlineImageRetention: ['Removing an image from the text keeps its original in Images & files.', 'Tar du bort en bild ur texten finns originalet kvar i Bilder och filer.'], + image: ['Image', 'Bild'], + descriptionPrompt: ['Collect ideas, links, decisions and small checklists…', 'Samla idéer, länkar, beslut och små checklistor…'], + insertImage: ['Insert image in text', 'Infoga bild i texten'], + moreFormatting: ['More formatting', 'Mer formatering'], + enlargeImage: ['Enlarge selected image', 'Förstora vald bild'], + previousImage: ['Previous image', 'Föregående bild'], + nextImage: ['Next image', 'Nästa bild'], + addFiles: ['Add', 'Lägg till'], + loadingFiles: ['Loading images and files…', 'Hämtar bilder och filer…'], + emptyAttachments: ['Collect inspiration, photos and files here, or insert images directly in the description.', 'Samla inspiration, foton och filer här, eller infoga bilder direkt i beskrivningen.'], + fileInformation: ['File types and upload limit', 'Filtyper och storleksgräns'], edit: ['Edit', 'Redigera'], delete: ['Delete', 'Radera'], redo: ['Redo', 'Gör om'], @@ -17,13 +43,18 @@ export const contentCopy: Record = { codeBlock: ['Code', 'Kod'], link: ['Link', 'Länk'], linkAddress: ['Link address', 'Länkadress'], + insertLink: ['Insert link', 'Infoga länk'], + editLink: ['Edit link', 'Redigera länk'], + openLink: ['Open link in new tab', 'Öppna länk i ny flik'], + removeLink: ['Remove link', 'Ta bort länk'], + emptyChecklistItem: ['Empty checklist item', 'Tom punkt i checklistan'], mentionMember: ['Mention someone', 'Omnämn någon'], content_invalid: [ 'This content is too large or contains unsupported formatting. Shorten it before saving.', 'Innehållet är för stort eller har formatering som inte stöds. Korta texten innan du sparar.', ], invalid_link: ['Enter an http, https or email link.', 'Ange en http-, https- eller e-postlänk.'], - attachments: ['Files & photos', 'Filer och bilder'], + attachments: ['Images & files', 'Bilder och filer'], attachFiles: ['Attach files', 'Bifoga filer'], takePhoto: ['Take a photo', 'Ta en bild'], preview: ['Preview', 'Förhandsvisa'], diff --git a/apps/web/src/content/imagePlacement.test.ts b/apps/web/src/content/imagePlacement.test.ts new file mode 100644 index 0000000..beafbe3 --- /dev/null +++ b/apps/web/src/content/imagePlacement.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest'; +import { Schema } from '@tiptap/pm/model'; +import { EditorState, TextSelection } from '@tiptap/pm/state'; +import { imagePlacements, mapPlacements } from './imagePlacement.js'; +const schema = new Schema({ nodes: { + doc: { content: 'block+' }, paragraph: { group: 'block', content: 'inline*' }, + text: { group: 'inline' }, image: { group: 'block', attrs: { src: {} } }, +} }); +const doc = schema.node('doc', null, [schema.node('paragraph', null, schema.text('Before after')), schema.node('paragraph', null, schema.text('Decision'))]); +const state = EditorState.create({ schema, doc, selection: TextSelection.create(doc, 20) }); +const anchor = { id: 'first', pos: 8, name: 'tiles.png' }; + +describe('image insertion positions', () => { + it('tracks edits before a position, ignores cursor moves and stays before typing at that position', () => { + expect(mapPlacements([anchor], state.tr.insertText('New ', 1))[0]?.pos).toBe(12); + expect(mapPlacements([anchor], state.tr.setSelection(TextSelection.create(doc, 2)))[0]?.pos).toBe(8); + expect(mapPlacements([anchor], state.tr.insertText('Continue ', 8))[0]?.pos).toBe(8); + }); + it('preserves batch order including a retry before a later image, and maps the current selection', () => { + const anchors = [anchor, { ...anchor, id: 'second' }, { ...anchor, id: 'third' }]; + const tr = state.tr.replaceRangeWith(8, 8, schema.node('image', { src: 'second.jpg' })).setMeta(imagePlacements, { inserted: 'second' }); + const remaining = mapPlacements(anchors, tr); + const next = state.apply(tr); + expect(remaining[0]?.pos).toBeLessThan(remaining[1]!.pos); + expect(next.doc.resolve(next.selection.from).parent.textContent).toBe('Decision'); + const retry = next.tr.replaceRangeWith(remaining[0]!.pos, remaining[0]!.pos, schema.node('image', { src: 'first.jpg' })); + const images: string[] = []; retry.doc.descendants(n => { if (n.type.name === 'image') images.push(n.attrs.src); }); + expect(images).toEqual(['first.jpg', 'second.jpg']); + expect(retry.doc.textContent).toBe('Before afterDecision'); + }); + it('does not move an upload to unrelated text after its surrounding content is deleted or replaced', () => { + expect(mapPlacements([anchor], state.tr.delete(1, 13))).toEqual([]); + expect(mapPlacements([anchor], state.tr.setMeta(imagePlacements, { clear: true }))).toEqual([]); + }); +}); diff --git a/apps/web/src/content/imagePlacement.ts b/apps/web/src/content/imagePlacement.ts new file mode 100644 index 0000000..8c75cca --- /dev/null +++ b/apps/web/src/content/imagePlacement.ts @@ -0,0 +1,65 @@ +import { Extension, type Editor } from '@tiptap/react'; +import { Plugin, PluginKey, type Transaction } from '@tiptap/pm/state'; +import { Decoration, DecorationSet } from '@tiptap/pm/view'; +import { Fragment, Slice } from '@tiptap/pm/model'; +import { closeHistory } from '@tiptap/pm/history'; +import type { UploadedFile } from './api.js'; +type Anchor = { id: string; pos: number; name: string }; +type PlacementChange = { add?: Anchor[]; remove?: string; inserted?: string; clear?: boolean }; +export const imagePlacements = new PluginKey('imagePlacements'); +export function mapPlacements(anchors: Anchor[], tr: Transaction): Anchor[] { + const change = tr.getMeta(imagePlacements) as PlacementChange | undefined; + if (change?.clear) return []; + const completed = anchors.findIndex(anchor => anchor.id === change?.inserted); + const origin = anchors[completed]?.pos; + return [...anchors.flatMap((anchor, index) => { + if (anchor.id === change?.remove || anchor.id === change?.inserted) return []; + // Typing at the insertion point stays after the placeholder. Later files + // at that same point move after each completed image, retaining batch order. + const association = completed >= 0 && index > completed && anchor.pos === origin ? 1 : -1; + const mapped = tr.mapping.mapResult(anchor.pos, association); + return mapped.deletedAcross ? [] : [{ ...anchor, pos: mapped.pos }]; + }), ...(change?.add ?? [])]; +} +export const ImagePlacements = Extension.create({ + name: 'imagePlacements', + addProseMirrorPlugins() { + return [new Plugin({ + key: imagePlacements, + state: { init: () => [], apply: (tr, anchors) => mapPlacements(anchors, tr) }, + props: { + decorations(state) { + return DecorationSet.create(state.doc, (imagePlacements.getState(state) ?? []).map(anchor => Decoration.widget(anchor.pos, () => { + const placeholder = document.createElement('span'); + placeholder.className = 'image-upload-placeholder'; + placeholder.textContent = anchor.name; + placeholder.contentEditable = 'false'; + return placeholder; + }, { key: anchor.id, side: -1 }))); + }, + }, + })]; + }, +}); +export function addPlacements(editor: Editor, anchors: Anchor[]) { + editor.view.dispatch(editor.state.tr.setMeta(imagePlacements, { add: anchors })); +} +export function removePlacement(editor: Editor, id: string) { + if (!editor.isDestroyed) editor.view.dispatch(editor.state.tr.setMeta(imagePlacements, { remove: id })); +} +export function insertUploadedFile(editor: Editor, file: UploadedFile, id?: string) { + if (editor.isDestroyed) return false; + const anchor = id ? imagePlacements.getState(editor.state)?.find(item => item.id === id) : null; + if (id && !anchor) return false; + const pos = anchor?.pos ?? editor.state.selection.from; + const { schema } = editor; + const nodes = file.image ? [schema.nodes.image!.create({ src: file.src, alt: file.name, width: file.width ?? null, height: file.height ?? null })] + : [schema.text(file.name, [schema.marks.link!.create({ href: file.src })]), schema.text(' ')]; + const tr = closeHistory(editor.state.tr).replaceRange(pos, pos, new Slice(Fragment.fromArray(nodes), 0, 0)); + if (id) tr.setMeta(imagePlacements, { inserted: id }); + // Do not focus, replace selected text or scroll to an asynchronous insertion. + editor.view.dispatch(tr); + // A gallery/recovery button is an explicit navigation back to the editor. + if (!id) editor.commands.focus(); + return true; +} diff --git a/apps/web/src/content/searchHighlight.test.ts b/apps/web/src/content/searchHighlight.test.ts new file mode 100644 index 0000000..c636f23 --- /dev/null +++ b/apps/web/src/content/searchHighlight.test.ts @@ -0,0 +1,10 @@ +import { expect, it } from 'vitest'; +import { Schema } from '@tiptap/pm/model'; +import { matchingText } from './searchHighlight.js'; +const schema = new Schema({ nodes: { doc: { content: 'paragraph+' }, paragraph: { content: 'text*', group: 'block' }, text: { group: 'inline' } }, marks: { bold: {} } }); +it('finds a passage across formatting marks without changing document content', () => { + const doc = schema.node('doc', null, [schema.node('paragraph', null, [schema.text('Ljust '), schema.text('matt', [schema.mark('bold')]), schema.text(' kakel.')])]); + const original = doc.toJSON(); + expect(matchingText(doc, 'matt kakel')).toEqual([{ from: 7, to: 17 }]); + expect(doc.toJSON()).toEqual(original); +}); diff --git a/apps/web/src/content/searchHighlight.ts b/apps/web/src/content/searchHighlight.ts new file mode 100644 index 0000000..e165a5a --- /dev/null +++ b/apps/web/src/content/searchHighlight.ts @@ -0,0 +1,40 @@ +import { Extension } from '@tiptap/react'; +import { Plugin, PluginKey } from '@tiptap/pm/state'; +import { Decoration, DecorationSet } from '@tiptap/pm/view'; +import type { Node } from '@tiptap/pm/model'; +export const searchHighlightKey = new PluginKey<{ query: string; decorations: DecorationSet }>('searchHighlight'); +export function matchingText(doc: Node, query: string) { + const ranges: { from: number; to: number }[] = []; + const needle = query.toLowerCase(); + if (!needle) return ranges; + doc.descendants((node, pos) => { + if (!node.isTextblock) return; + // Preserve positions across formatting marks and inline non-text nodes. + const text = node.textBetween(0, node.content.size, '', '\uFFFC').toLowerCase(); + let from = text.indexOf(needle); + while (from >= 0) { + ranges.push({ from: pos + 1 + from, to: pos + 1 + from + needle.length }); + from = text.indexOf(needle, from + needle.length); + } + return false; + }); + return ranges; +} +export const SearchHighlight = Extension.create({ + name: 'searchHighlight', + addProseMirrorPlugins() { + return [new Plugin({ + key: searchHighlightKey, + state: { + init: () => ({ query: '', decorations: DecorationSet.empty }), + apply(tr, previous) { + const query = tr.getMeta(searchHighlightKey) as string | undefined ?? previous.query; + if (!tr.docChanged && query === previous.query) return previous; + return { query, decorations: DecorationSet.create(tr.doc, matchingText(tr.doc, query).map(({ from, to }) => + Decoration.inline(from, to, { class: 'search-match' }))) }; + }, + }, + props: { decorations: state => searchHighlightKey.getState(state)?.decorations }, + })]; + }, +}); diff --git a/apps/web/src/content/uploads.test.ts b/apps/web/src/content/uploads.test.ts new file mode 100644 index 0000000..8583abc --- /dev/null +++ b/apps/web/src/content/uploads.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it, vi } from 'vitest'; +import { UploadQueue } from './UploadQueue.js'; +import type { FileUploader } from './api.js'; +const result = { src: '/preview', name: 'Tiles', image: true }; +const file = new File(['photo'], 'tiles.png'); +const settle = async (queue: UploadQueue) => vi.waitFor(() => expect(queue.getSnapshot().some(e => ['queued', 'uploading', 'processing'].includes(e.state))).toBe(false)); + +describe('independent file uploads', () => { + it('continues past a failure and retries only that file with its original ID', async () => { + const upload = vi.fn().mockResolvedValue(result).mockRejectedValueOnce(new Error('upload_connection_lost')); + const queue = new UploadQueue(upload); + const place = vi.fn(() => true); + queue.add('first', file, place); queue.add('second', file, place); + await settle(queue); + expect(queue.getSnapshot().map(e => e.state)).toEqual(['failed', 'done']); + expect(place).toHaveBeenCalledTimes(1); + queue.retry('first'); queue.retry('first'); + await settle(queue); + expect(upload.mock.calls.map(args => args[1])).toEqual(['first', 'second', 'first']); + expect(place).toHaveBeenCalledTimes(2); + }); + it('keeps an uploaded file available when its insertion point was removed, without uploading again', async () => { + const upload = vi.fn().mockResolvedValue(result); + const queue = new UploadQueue(upload); + queue.add('first', file, () => false); + await settle(queue); + expect(queue.getSnapshot()[0]).toMatchObject({ state: 'unplaced', result }); + queue.retry('first'); queue.placed('first'); + expect(upload).toHaveBeenCalledTimes(1); + expect(queue.getSnapshot()[0]?.state).toBe('done'); + }); + it('discards a waiting file and stops late insertion after unmount', async () => { + let finish!: (value: typeof result) => void; + const upload = vi.fn(() => new Promise(resolve => { finish = resolve; })); + const queue = new UploadQueue(upload); + const place = vi.fn(() => true), remove = vi.fn(); + queue.add('first', file, place); queue.add('second', file, place, remove); + queue.remove('second'); + expect(remove).toHaveBeenCalledTimes(1); + queue.dispose(); finish(result); + await Promise.resolve(); + expect(place).not.toHaveBeenCalled(); + expect(upload).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/web/src/navigation/Navigation.tsx b/apps/web/src/navigation/Navigation.tsx new file mode 100644 index 0000000..e6671f9 --- /dev/null +++ b/apps/web/src/navigation/Navigation.tsx @@ -0,0 +1,23 @@ +import { createContext, useContext, useEffect, useRef, useState, useSyncExternalStore } from 'react'; +import { Navigation, readRoute, type LeaveGuard } from './routes.js'; +export const NavigationContext = createContext(null); +export function useWorkspaceNavigation(fallback: string, settings: boolean) { + const [navigation] = useState(() => new Navigation({ + url: () => location.href, + state: () => window.history.state?.tendly ?? null, + write: (url, entry, replace) => window.history[replace ? 'replaceState' : 'pushState']({ tendly: entry }, '', url), + go: delta => window.history.go(delta), + }, { ...readRoute(location.href, fallback), ...(settings ? { view: 'settings' as const, task: '' } : {}) })); + const route = useSyncExternalStore(navigation.subscribe, navigation.getSnapshot); + useEffect(() => { + window.addEventListener('popstate', navigation.pop); + return () => window.removeEventListener('popstate', navigation.pop); + }, [navigation]); + return { navigation, route }; +} +export function useNavigationGuard(guard: LeaveGuard) { + const navigation = useContext(NavigationContext); + const current = useRef(guard); + current.current = guard; + useEffect(() => navigation?.block(next => current.current(next)), [navigation]); +} diff --git a/apps/web/src/navigation/routes.test.ts b/apps/web/src/navigation/routes.test.ts new file mode 100644 index 0000000..0f0c775 --- /dev/null +++ b/apps/web/src/navigation/routes.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from 'vitest'; +import { Navigation, readRoute, routeUrl, type NavigationPort } from './routes.js'; +const household = '11111111-1111-4111-8111-111111111111'; +const task = '22222222-2222-4222-8222-222222222222'; +function setup() { + const entries: { url: string; state: ReturnType }[] = [{ url: '/', state: null }]; + let index = 0; + const port: NavigationPort = { + url: () => entries[index]!.url, state: () => entries[index]!.state, + write(url, state, replace) { + if (!replace) { entries.splice(index + 1); index++; } + entries[index] = { url, state }; + }, + go(delta) { index += delta; navigation.pop(); }, + }; + const navigation = new Navigation(port, readRoute('/', household)); + return { navigation, port, entries }; +} +describe('workspace navigation', () => { + it('preserves search context through task, back, forward and reload', () => { + const { navigation: nav, port } = setup(); + nav.navigate({ view: 'search' }); + nav.navigate({ q: 'matt kakel', filters: [household] }, true); + const searchUrl = port.url(); + nav.navigate({ task, comment: task, match: 'matt kakel' }); + const link = port.url(); + expect(readRoute(link, '')).toEqual(nav.getSnapshot()); + nav.closeTask(); + expect(port.url()).toBe(searchUrl); + port.go(1); + expect(port.url()).toBe(link); + expect(nav.getSnapshot().task).toBe(task); + }); + it('restores URL before guarding browser back and preserves the draft on cancellation', () => { + const { navigation: nav, port } = setup(); + nav.navigate({ task }); + const link = port.url(); + let proceed: (() => void) | undefined; + const unblock = nav.block(next => { proceed = next; }); + port.go(-1); + expect(port.url()).toBe(link); + expect(nav.getSnapshot().task).toBe(task); + proceed!(); + expect(nav.getSnapshot().task).toBe(''); + unblock(); + port.go(1); + expect(nav.getSnapshot().task).toBe(task); + }); + it('guards internal navigation and closes a direct link within the app', () => { + const { navigation: nav, port, entries } = setup(); + nav.navigate({ task }, true); + let proceed: (() => void) | undefined; + nav.block(next => { proceed = next; }); + nav.closeTask(); + expect(nav.getSnapshot().task).toBe(task); + proceed!(); + expect(nav.getSnapshot().task).toBe(''); + expect(entries).toHaveLength(1); + expect(port.url()).toBe(routeUrl(nav.getSnapshot())); + }); + it('validates identifiers and never includes authentication fragments', () => { + const route = readRoute('/?household=bad&task=javascript:foo&view=unknown#invite=secret', household); + expect(route.task).toBe(''); + expect(route.view).toBe('now'); + expect(route.household).toBe(household); + expect(routeUrl(route)).not.toContain('secret'); + }); + it('returns to the selected board column after leaving and reopening a task', () => { + const { navigation: nav, port } = setup(); + nav.navigate({ view: 'board', column: 'within_month' }); + nav.navigate({ task }); + nav.closeTask(); + expect(readRoute(port.url(), household).column).toBe('within_month'); + port.go(-1); + port.go(1); + expect(nav.getSnapshot().column).toBe('within_month'); + }); +}); diff --git a/apps/web/src/navigation/routes.ts b/apps/web/src/navigation/routes.ts new file mode 100644 index 0000000..3b7a879 --- /dev/null +++ b/apps/web/src/navigation/routes.ts @@ -0,0 +1,94 @@ +import { columns, type TaskColumn } from '@tendly/shared'; +export const workspaceViews = ['now', 'board', 'more', 'library', 'settings', 'search', 'custom', 'views'] as const; +export type WorkspaceView = typeof workspaceViews[number]; +export type Route = { + household: string; view: WorkspaceView; custom: string; task: string; + column: TaskColumn; q: string; filters: string[]; comment: string; match: string; +}; +const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +export function readRoute(url: string, fallback: string): Route { + const p = new URL(url, 'http://local').searchParams; + const id = (key: string) => uuid.test(p.get(key) ?? '') ? p.get(key)! : ''; + const view = p.get('view'); + return { household: id('household') || fallback, + view: workspaceViews.includes(view as WorkspaceView) ? view as WorkspaceView : 'now', + custom: id('custom'), task: id('task'), column: columns.includes(p.get('column') as TaskColumn) ? p.get('column') as TaskColumn : 'todo', q: (p.get('q') ?? '').slice(0, 200), + filters: p.getAll('filter').filter(v => uuid.test(v)).slice(0, 100), + comment: id('comment'), match: (p.get('match') ?? '').slice(0, 200) }; +} +export function routeUrl(route: Route) { + const p = new URLSearchParams({ household: route.household, view: route.view }); + if (route.view === 'custom' && route.custom) p.set('custom', route.custom); + if (route.view === 'board' || route.view === 'custom') p.set('column', route.column); + if (route.view === 'search') { + if (route.q) p.set('q', route.q); + route.filters.forEach(id => p.append('filter', id)); + } + if (route.task) { + p.set('task', route.task); + if (route.comment) p.set('comment', route.comment); + if (route.match) p.set('match', route.match); + } + return '/?' + p; +} +export type LeaveGuard = (continueNavigation: () => void) => void; +type Entry = { index: number; parent?: string }; +export type NavigationPort = { + url: () => string; state: () => Entry | null; + write: (url: string, entry: Entry, replace: boolean) => void; + go: (delta: number) => void; +}; +// Restore the current history entry before asking about unsaved work. Cancel then +// leaves both URL and document intact; approval traverses the original history. +export class Navigation { + private entry: Entry; + private restoring: (() => void) | null = null; + private approved = false; + private listeners = new Set<() => void>(); + private guards = new Set(); + constructor(private port: NavigationPort, private route: Route) { + this.entry = port.state() ?? { index: 0 }; + port.write(routeUrl(route), this.entry, true); + } + getSnapshot = () => this.route; + subscribe = (listener: () => void) => { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }; + block = (guard: LeaveGuard) => { this.guards.add(guard); return () => { this.guards.delete(guard); }; }; + private ask(action: () => void) { + const guards = [...this.guards].reverse(); + const next = () => { const guard = guards.shift(); if (guard) guard(next); else action(); }; + next(); + } + private publish(route: Route) { this.route = route; this.listeners.forEach(fn => fn()); } + navigate = (changes: Partial, replace = false) => { + if (this.restoring) return; + const next = { ...this.route, ...changes }; + if (routeUrl(next) === routeUrl(this.route)) return; + const commit = () => { + this.entry = { index: this.entry.index + (replace ? 0 : 1), + ...(!replace && next.task && !this.route.task ? { parent: routeUrl(this.route) } : replace ? { parent: this.entry.parent } : {}) }; + this.port.write(routeUrl(next), this.entry, replace); + this.publish(next); + }; + // Search typing only replaces its current workspace entry. + if (replace && !this.route.task) commit(); else this.ask(commit); + }; + closeTask = () => { + if (this.entry.parent) this.ask(() => { this.approved = true; this.port.go(-1); }); + else this.navigate({ task: '', comment: '', match: '' }, true); + }; + pop = () => { + if (this.restoring) { const restored = this.restoring; this.restoring = null; restored(); return; } + const target = this.port.state(); + const next = readRoute(this.port.url(), this.route.household); + if (this.approved || !this.guards.size || !target) { + this.approved = false; + this.entry = target ?? { index: 0 }; + this.publish(next); + return; + } + const delta = target.index - this.entry.index; + if (!delta) return; + this.restoring = () => this.ask(() => { this.approved = true; this.port.go(delta); }); + this.port.go(-delta); + }; +} diff --git a/apps/web/src/navigation/useDraftGuard.tsx b/apps/web/src/navigation/useDraftGuard.tsx new file mode 100644 index 0000000..e3264b6 --- /dev/null +++ b/apps/web/src/navigation/useDraftGuard.tsx @@ -0,0 +1,30 @@ +import { useEffect, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Dialog } from '../components/ui/dialog.js'; +import { useNavigationGuard } from './Navigation.js'; +// Explicit-save editors keep their draft mounted until the owner chooses to leave. +export function useDraftGuard(dirty: boolean, busy: boolean) { + const { t } = useTranslation(); + const [confirming, setConfirming] = useState(false); + const action = useRef<() => void>(() => {}); + const request = (next: () => void) => { + if (busy) return; + if (!dirty) { next(); return; } + action.current = next; + setConfirming(true); + }; + useNavigationGuard(request); + useEffect(() => { + if (!dirty && !busy) return; + const warn = (event: BeforeUnloadEvent) => event.preventDefault(); + window.addEventListener('beforeunload', warn); + return () => window.removeEventListener('beforeunload', warn); + }, [dirty, busy]); + return { request, confirmation: confirming && +

{t('definitionDraftHelp')}

+
+ + +
+
}; +} diff --git a/apps/web/src/style.css b/apps/web/src/style.css index 514af73..d61e51d 100644 --- a/apps/web/src/style.css +++ b/apps/web/src/style.css @@ -238,7 +238,7 @@ p { margin: .65rem 0; } .attachment-list,.search-results { padding:0;list-style:none; }.attachment-list li { display:flex;align-items:center;gap:10px;padding-block:10px;border-bottom:1px solid var(--line);flex-wrap:wrap; } .attachment-list img { width:56px;height:56px;object-fit:cover;border-radius:6px; }.attachment-list span { flex:1;min-width:100px;overflow-wrap:anywhere; }.attachment-list small { display:block;opacity:.7; } .file-preview { max-width:100%;max-height:70vh;object-fit:contain; }.pdf-preview { width:100%;height:65vh;border:0; } -.search-results button { display:flex;flex-direction:column;align-items:start;text-align:left;width:100%;padding:14px;margin-top:8px;overflow-wrap:anywhere; } +.search-results a,.search-results button { display:flex;flex-direction:column;align-items:start;text-align:left;width:100%;padding:14px;margin-top:8px;overflow-wrap:anywhere; } .search-results span { font-size:.85rem;opacity:.75;white-space:pre-wrap; }.global-search { max-width:900px; } @media (max-width:600px) { .rich-toolbar button { min-height:44px; }.attachment-list a { font-size:.8rem; }.task-content .button-row { flex-wrap:wrap; } } @@ -312,3 +312,177 @@ button.primary:hover:not(:disabled) { background:var(--accent); } .editor-actions { position: sticky; bottom: -1.5rem; background: var(--surface); padding: .85rem 0; border-top: 1px solid var(--line); z-index: 2; } .mobile-preview-link { display: none; } @media (max-width: 720px) { .mobile-preview-link { display: inline-flex; } .dialog-wide>.dialog-heading { top: -1rem; } .filter-preview { scroll-margin-top: 85px; } } +.field-error { color: var(--error); margin: .25rem 0 .75rem; } +.conflict-comparison { display: grid; gap: 1rem; margin: 1rem 0; } +.conflict-comparison section { min-width: 0; border: 1px solid currentColor; border-radius: .5rem; padding: .75rem; overflow-wrap: anywhere; } +.conflict-comparison h3 { margin-bottom: .5rem; } + +/* Task details keep the living document primary; planning uses the same controls at every width. */ +.dialog-heading-actions { display: flex; align-items: center; gap: .5rem; min-width: 0; } +.task-back-arrow,.task-back-label { display: none; } +.dialog-content.task-sheet.task-detail { width: min(660px,calc(100vw - 64px)); padding: 0 2rem 2rem; } +.task-detail>.dialog-heading { position: sticky; top: 0; z-index: 5; margin-inline: -2rem; padding: .65rem 2rem; background: var(--surface); border-bottom: 1px solid var(--line); } +.task-detail>.dialog-heading h2 { color: var(--muted); font-size: .8rem; font-weight: 500; } +.task-detail .save-status { margin: 0; min-height: 0; font-size: .75rem; max-width: 240px; text-align: right; } +.task-title-section { margin: 1.5rem 0; } +.task-detail .task-title-input { display: block; width: 100%; min-height: 0; overflow: hidden; resize: none; margin: 0; padding: .25rem 0; font-size: 2rem; line-height: 1.25; letter-spacing: -.035em; } +.task-detail-body { display: grid; grid-template-areas: 'planning' 'document'; gap: 1.5rem; align-items: start; } +.task-document-column { grid-area: document; min-width: 0; } +.task-planning { grid-area: planning; min-width: 0; border-bottom: 1px solid var(--line); } +.task-planning h3,.task-description>h3 { font-size: .8rem; font-weight: 550; color: var(--muted); margin: 0 0 .75rem; } +.planning-toggle { width: 100%; justify-content: space-between; padding: .6rem 0; text-align: left; font-size: .8rem; font-weight: 400; gap: 1rem; } +.planning-toggle>span:first-child { overflow-wrap: anywhere; } +.planning-toggle-label { display: flex; gap: .4rem; align-items: center; color: var(--muted); flex-shrink: 0; } +.planning-toggle[aria-expanded=true] svg { transform: rotate(180deg); } +.task-planning>fieldset { padding-block: 1rem; } +.task-planning label { font-size: .8rem; } +.task-planning .form-grid { gap: .75rem; } +.task-planning .properties summary { font-size: .8rem; } +.task-planning .choice-list { display: grid; gap: .25rem; } +.task-detail>.alert { margin-top: 1rem; } +.document-editor { border: 0; border-radius: 0; margin: 0; } +.document-editor>.rich-toolbar { position: sticky; top: 66px; z-index: 3; background: var(--surface); padding: 0 0 .6rem; } +.rich-toolbar svg { flex-shrink: 0; } +.rich-toolbar .file-button { flex-direction: row; gap: .4rem; min-height: 44px; margin: 0; padding: 5px 8px; } +.rich-toolbar .rich-image-button { font-size: .75rem; font-weight: 550; } +.rich-toolbar>button { min-height: 44px; height: auto; } +.rich-more { margin-left: auto; min-width: 44px; } +.rich-more>summary { display: flex; justify-content: center; align-items: center; gap: 4px; list-style: none; border-radius: 8px; font-size: .85rem; } +.rich-more>summary::-webkit-details-marker { display: none; } +.rich-more>summary:hover { background: var(--tint); } +.rich-more[open] { flex: 1 0 100%; } +.rich-more[open]>summary { width: fit-content; margin-left: auto; padding-inline: .75rem; background: var(--tint); } +.rich-more-tools { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; padding-block: .5rem; } +.rich-more-tools button { min-height: 44px; height: auto; } +.rich-toolbar .rich-icon-tool { width: 44px; padding: 0; } +.rich-link-form { display: grid; gap: 1rem; padding-block: .5rem; } +.rich-link-form label { min-width: 0; margin: 0; } +.rich-link-form .button-row { flex-wrap: wrap; } +.rich-link-open { display: flex; gap: .75rem; align-items: center; min-height: 44px; color: var(--accent); overflow-wrap: anywhere; } +.rich-link-open svg { flex-shrink: 0; } +.rich-link-open small { display: block; color: var(--muted); font-size: .8rem; } +@media (max-width: 600px) { + .rich-toolbar .rich-tool-label { display: none; } + .rich-toolbar>button,.rich-toolbar .rich-image-button { min-width: 44px; justify-content: center; } +} +.document-editor .tiptap { padding: 1rem 0; min-height: 200px; font-size: 1rem; line-height: 1.75; } +.document-editor .tiptap:focus-visible { outline-offset: 4px; border-radius: 4px; } +.document-editor .tiptap h2 { display: block; font-size: 1.2rem; line-height: 1.4; margin: 1.5rem 0 .6rem; } +.document-editor .tiptap p { margin: .6rem 0; } +.document-editor .tiptap ul,.document-editor .tiptap ol { margin-block: .7rem; } +.document-editor .tiptap ul[data-type=taskList] li p { margin: .45rem 0; } +.document-editor .tiptap ul[data-type=taskList] li[data-checked=true]>div>p { text-decoration: line-through; color: var(--muted); } +.tiptap img { cursor: zoom-in; } +.document-editor .tiptap img { display: block; width: auto; max-width: 100%; margin-block: 1.25rem; } +.document-editor .tiptap code { display: inline; padding: .1rem .3rem; } +.document-editor .tiptap pre code { display: block; padding: 0; } +.task-content { margin-top: 1.75rem; padding-top: 1.5rem; } +.attachment-heading { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .5rem; } +.attachment-heading h3 { display: flex; align-items: baseline; gap: .5rem; font-size: 1rem; font-weight: 600; } +.file-count { font-size: .8rem; font-weight: 400; } +.attachment-actions { display: flex; gap: .4rem; flex-wrap: wrap; } +.attachment-actions .file-button { display: flex; flex-direction: row; gap: .4rem; margin: 0; min-height: 44px; font-size: .75rem; } +.attachment-gallery { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: 1rem; list-style: none; margin: 1rem 0 0; padding: 0; } +.attachment-gallery>li { min-width: 0; } +.attachment-preview { display: flex; flex-direction: column; align-items: stretch; padding: 0; width: 100%; border: 0; border-radius: 8px; background: transparent; text-align: left; font-weight: 500; gap: .5rem; } +.attachment-preview img,.attachment-file-icon { width: 100%; aspect-ratio: 4 / 3; object-fit: cover; border-radius: 8px; background: var(--tint); } +.attachment-file-icon { display: flex; align-items: center; justify-content: center; color: var(--muted); } +.attachment-name { font-size: .8rem; overflow-wrap: anywhere; } +.attachment-caption { display: flex; align-items: baseline; flex-wrap: wrap; gap: .5rem; justify-content: space-between; font-size: .7rem; color: var(--muted); } +.attachment-caption a { display: inline-flex; align-items: center; min-height: 44px; color: var(--accent); } +.attachment-empty { font-size: .85rem; } +.file-help { margin-top: .5rem; } +.file-help summary { font-size: .75rem; color: var(--muted); } +.content-tabs { gap: 1.25rem; margin-top: 1.5rem; } +.content-tabs button { border: 0; border-radius: 0; background: transparent; padding-inline: 0; font-size: .85rem; } +.content-tabs [aria-selected=true] { border-bottom-color: var(--accent); } +.image-preview-dialog { width: min(960px,calc(100vw - 2rem)); } +.image-preview-dialog .dialog-heading h2 { overflow-wrap: anywhere; min-width: 0; } +.image-preview-dialog .file-preview { display: block; margin: 1rem auto; } +.image-navigation { display: flex; align-items: center; justify-content: space-between; gap: 1rem; } +@media (min-width: 1100px) { + .dialog-content.task-sheet.task-detail-expanded { width: min(1140px,calc(100vw - 240px)); } + .task-detail-expanded .task-detail-body { grid-template-columns: minmax(0,1fr) 216px; grid-template-areas: 'document planning'; gap: 2rem; } + .task-detail-expanded .task-planning { padding: 1rem; background: color-mix(in srgb,var(--line) 20%,var(--surface)); border: 0; border-radius: 10px; } + .task-detail-expanded .task-planning>fieldset { padding: 0; } + .task-detail-expanded .task-planning .form-grid { grid-template-columns: minmax(0,1fr); gap: .25rem; } + .task-detail-expanded .task-planning .check-label { margin-bottom: .75rem; } +} +@media (max-width: 720px) { + .dialog-content.task-sheet.task-detail { width: 100%; padding: 0 1.2rem max(1.5rem,env(safe-area-inset-bottom)); } + .task-detail>.dialog-heading { margin-inline: -1.2rem; padding: max(.5rem,env(safe-area-inset-top)) 1.2rem .5rem; min-height: 64px; } + .task-detail>.dialog-heading h2,.task-expand,.task-back .dialog-close-icon { display: none; } + .task-detail .dialog-heading-actions { width: 100%; justify-content: space-between; flex-direction: row-reverse; } + .task-back-arrow,.task-back-label { display: inline; } + .task-back { width: auto; padding-inline: 0; } + .task-detail .save-status { max-width: 55%; font-size: .7rem; } + .task-title-section { margin: 1.25rem 0 1rem; } + .task-detail .task-title-input { font-size: 1.65rem; } + .task-detail-body { gap: 1.25rem; } + .planning-toggle { font-size: .75rem; gap: .5rem; } + .planning-toggle-label { font-size: .7rem; } + .document-editor>.rich-toolbar { top: calc(60px + env(safe-area-inset-top)); } + .document-editor .tiptap { min-height: 180px; } + .attachment-gallery { grid-template-columns: repeat(2,minmax(0,1fr)); gap: .75rem; } +} +@media (max-width: 360px) { + .task-detail .rich-toolbar>button,.task-detail .rich-toolbar .rich-image-button { gap: .25rem; padding-inline: 5px; } + .task-detail .rich-toolbar { gap: 2px; } + .planning-toggle-label { font-size: 0; } +} +.document-editor[data-empty=true] .tiptap::before { content: attr(data-placeholder); float: left; height: 0; color: var(--muted); font-size: .95rem; pointer-events: none; } + +.upload-status { margin-block: 1rem; padding: .75rem; border: 1px solid var(--line); border-radius: 10px; } +.upload-status ul { list-style: none; padding: 0; margin: 0; } +.upload-status li { display: flex; align-items: center; flex-wrap: wrap; gap: .5rem 1rem; padding-block: .5rem; } +.upload-status li+li { border-top: 1px solid var(--line); } +.upload-file { flex: 1 1 180px; min-width: 0; font-size: .85rem; overflow-wrap: anywhere; } +.upload-file strong,.upload-file span { display: block; } +.upload-file span { font-size: .8rem; color: var(--muted); margin-top: .25rem; } +.upload-status progress { max-width: 100%; width: 100px; accent-color: var(--accent); } +.upload-actions { display: flex; gap: .5rem; flex-wrap: wrap; } +.upload-actions button,.attachment-insert { min-height: 44px; font-size: .75rem; } +.attachment-insert { width: 100%; } +.image-upload-placeholder { display: inline-block; max-width: 100%; padding: .5rem .75rem; margin: .5rem .25rem; border: 1px dashed var(--accent); border-radius: 8px; color: var(--muted); background: var(--surface); font-size: .8rem; font-weight: 500; line-height: 1.5; overflow-wrap: anywhere; vertical-align: middle; } +.image-retention-note { margin-block: 1rem; } +.upload-completed { display: flex; flex-wrap: wrap; gap: .5rem; align-items: start; font-size: .85rem; } +.upload-completed details { flex: 1; min-width: 160px; } +.upload-completed button { min-height: 44px; font-size: .75rem; } + +/* Task and search links retain native new-tab and copy-link behavior. */ +a.card-open { display: flex; align-items: center; color: inherit; text-decoration: none; } +.search-results a,.search-results button { color: inherit; text-decoration: none; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); } +.search-results a:hover { background: var(--tint); } +a:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } +.search-match { background: #ffe178; color: #25200b; border-radius: 2px; scroll-margin-block: 100px; } +.search-landing { outline: 2px solid var(--accent); outline-offset: 5px; scroll-margin-block: 100px; } + +.page-heading { margin-bottom: 1rem; } +.workspace-main { padding-top: 1.5rem; } +.view-secondary { margin-block: .4rem .8rem; } +.view-secondary>summary { width: fit-content; color: var(--muted); font-size: .85rem; min-height: 44px; padding-block: .7rem; cursor: pointer; } +.view-secondary-controls { margin-top: .25rem; } +.empty-state { padding: 2rem 1rem; } +@media (min-width: 721px) and (max-width: 1024px) { + .workspace,.nav-collapsed { grid-template-columns: 160px minmax(0,1fr); } + .workspace-nav { padding-inline: .65rem; } + .workspace-nav nav button { gap: .5rem; } + .workspace-nav>.quiet small { display: none; } + .workspace-main { padding-inline: 1rem; } + .mobile-column-select { display: flex; margin-bottom: 1rem; } + .board { display: block; padding: .2rem; overflow: visible; } + .board-column { display: none; } + .board-column[data-active=true] { display: block; } + .nav-collapsed { grid-template-columns: 80px minmax(0,1fr); } +} +@media (max-width: 720px) { + .workspace-main { padding-top: 1rem; } + .page-heading { margin-bottom: .7rem; } + .page-heading h1 { font-size: 1.65rem; margin-bottom: .25rem; } + .page-heading .muted { margin-top: .25rem; } + .view-controls { margin-bottom: .5rem; } +} + +.favorite-views button { min-width: 0; text-align: left; justify-content: flex-start; } +.favorite-views button span { min-width: 0; white-space: normal; overflow-wrap: anywhere; } +.favorite-views button svg { flex-shrink: 0; } diff --git a/apps/web/src/tasks/TaskEditor.tsx b/apps/web/src/tasks/TaskEditor.tsx index 9c43191..07df396 100644 --- a/apps/web/src/tasks/TaskEditor.tsx +++ b/apps/web/src/tasks/TaskEditor.tsx @@ -1,67 +1,223 @@ +import { useNavigationGuard } from '../navigation/Navigation.js'; import { ContentPanel } from '../content/ContentPanel.js'; -import { uploadFiles } from '../content/api.js'; -import { useEffect, useRef, useState } from 'react'; +import { RichEditor } from '../content/RichEditor.js'; +import { uploadFile, type UploadedFile } from '../content/api.js'; +import { useEffect, useId, useLayoutEffect, useRef, useState, useSyncExternalStore } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { ChevronDown, Maximize2, Minimize2, Link } from 'lucide-react'; import { useTranslation } from 'react-i18next'; -import { taskFields, type Task, type TaskChanges, type Entity } from '@tendly/shared'; +import { plainText, taskFields, type Task, type TaskChanges, type Entity } from '@tendly/shared'; import { Dialog } from '../components/ui/dialog.js'; import { TaskFields, type Member } from './TaskFields.js'; -import { EditFailure } from './api.js'; -export function TaskEditor({ userId, task, entities, members, timezone, onSave, onRefresh, onClose }: { +import { loadTask } from './api.js'; +import { TaskDraft, draftStorage, isDirty, type DraftBackup } from './draft.js'; + +export function TaskEditor({ userId, task, entities, members, timezone, onSave, onRefresh, onClose, onReturnFocus, searchMatch, commentId }: { userId: string; task: Task; entities: Entity[]; members: Member[]; timezone: string; onRefresh: (task: Task) => void; - onSave: (base: Task, changes: TaskChanges, confirm?: boolean) => Promise; onClose: () => void; + onSave: (base: Task, changes: TaskChanges, confirm?: boolean) => Promise; + onClose: () => void; onReturnFocus: () => void; searchMatch: string; commentId: string; }) { const { t } = useTranslation(); - const [base, setBase] = useState(task); - const [draft, setDraft] = useState(taskFields.parse(task)); - const [failure, setFailure] = useState(null); - const [pending, setPending] = useState(false); - const saving = useRef(false); - const [contentValid,setContentValid]=useState(true); - const changes: TaskChanges = Object.fromEntries(Object.entries(draft).filter(([key, value]) => JSON.stringify(value) !== JSON.stringify(base[key as keyof Task]))); - const signature = JSON.stringify(changes); - async function save(from = base, confirmed = false): Promise { - if (saving.current || !contentValid) return false; - if (signature === '{}') return true; - if (!draft.title.trim()) { setFailure(new EditFailure('invalid_input')); return false; } - saving.current = true; setPending(true); setFailure(null); - try { - const next = await onSave(from, changes, confirmed); - setBase(next); setDraft(current => ({ ...taskFields.parse(next), ...Object.fromEntries(Object.entries(current).filter(([key,value]) => JSON.stringify(value) !== JSON.stringify(draft[key as keyof typeof draft]))) })); return true; - } catch (error) { - setFailure(error instanceof EditFailure ? error : new EditFailure('network_error')); return false; - } finally { saving.current = false; setPending(false); } + const queries = useQueryClient(); + const planningId = useId(); + const [titleElement, setTitleElement] = useState(null); + const [expanded, setExpanded] = useState(true); + const [planningOpen, setPlanningOpen] = useState(false); + const [wideScreen, setWideScreen] = useState(() => window.matchMedia('(min-width: 1100px)').matches); + useEffect(() => { + const media = window.matchMedia('(min-width: 1100px)'); + const update = () => setWideScreen(media.matches); + media.addEventListener('change', update); + return () => media.removeEventListener('change', update); + }, []); + const callbacks = useRef({ onSave, onRefresh }); + callbacks.current = { onSave, onRefresh }; + const [editor] = useState(() => { + let storage: ReturnType | undefined; + let backup: DraftBackup | undefined; + let storageFailed = false; + try { storage = draftStorage(userId, task, sessionStorage); backup = storage.read(); } + catch { storageFailed = true; } + return new TaskDraft(task, { + save: (base, changes, confirm) => callbacks.current.onSave(base, changes, confirm), + load: async () => { + const latest = await loadTask(task.householdId, task.id); + callbacks.current.onRefresh(latest); + return latest; + }, + backup: value => { if (!storage) throw new Error('storage unavailable'); storage.write(value); }, + }, backup, storageFailed); + }); + const state = useSyncExternalStore(editor.subscribe, editor.getSnapshot); + const { draft, failure } = state; + const dirty = isDirty(state); + const [contentValid, setContentValid] = useState(true); + const [uploading, setUploading] = useState(false); + const [descriptionPending, setDescriptionPending] = useState(false); + const [panelPending, setPanelPending] = useState(false); + const [insertion, setInsertion] = useState<{ file: UploadedFile }>(); + const [contentBusy, setContentBusy] = useState(false); + const [leaving, setLeaving] = useState(false); + const [closing, setClosing] = useState(false); + const [copied, setCopied] = useState(''); + const closeRequest = useRef(0); + const busyContent = uploading || contentBusy; + const pendingContent = busyContent || descriptionPending || panelPending; + const contentState = useRef({ busyContent: pendingContent, contentValid }); + contentState.current = { busyContent: pendingContent, contentValid }; + const parse = taskFields.safeParse(draft); + const invalidFields = parse.success ? [] : parse.error.issues.map(issue => String(issue.path[0])); + const titleInvalid = invalidFields.includes('title'); + const pinnedPlanning = expanded && wideScreen; + const showPlanning = pinnedPlanning || planningOpen || invalidFields.some(field => field !== 'title' && field !== 'description'); + const epic = entities.find(entity => entity.id === draft.epicId); + const planningSummary = [t('column_' + draft.column), draft.size, epic?.name, draft.high ? t('high') : null, + draft.deadlineDate ? `${t('deadlineDate')}: ${draft.deadlineDate}` : null].filter(Boolean).join(' · '); + useLayoutEffect(() => { + const title = titleElement; + if (title) { title.style.height = 'auto'; title.style.height = title.scrollHeight + 2 + 'px'; } + }, [draft.title, expanded, wideScreen, titleElement]); + useEffect(() => { + const title = titleElement; + if (!title) return; + let width = 0, frame = 0; + const resize = () => { + cancelAnimationFrame(frame); + frame = requestAnimationFrame(() => { title.style.height = 'auto'; title.style.height = title.scrollHeight + 2 + 'px'; }); + }; + const observer = new ResizeObserver(([entry]) => { + if (!entry || entry.contentRect.width === width) return; + width = entry.contentRect.width; + resize(); + }); + observer.observe(title); + window.addEventListener('resize', resize); + return () => { observer.disconnect(); window.removeEventListener('resize', resize); cancelAnimationFrame(frame); }; + }, [titleElement]); + async function uploadDescription(file: File, id: string, progress: (percent: number) => void) { + try { return await uploadFile(task.householdId, task.id, file, id, progress); } + finally { void queries.invalidateQueries({ queryKey: ['planning', task.householdId, 'attachments', task.id] }); } } + + useEffect(() => editor.receive(task), [editor, task, state]); useEffect(() => { - // Conflict resolution may be newer than the query cache. Never move backwards. - if (signature === '{}' && !pending && task.version > base.version) { - setBase(task); setDraft(taskFields.parse(task)); - } - }, [task, signature, pending, base.version]); + if (!dirty || state.busy || failure || state.restored || !contentValid || leaving) return; + const timer = window.setTimeout(() => void editor.flush(), 650); + return () => window.clearTimeout(timer); + }, [editor, state, dirty, failure, contentValid, busyContent, leaving]); useEffect(() => { - // Conflict resolution may be newer than the query cache. Never move backwards. - if (signature === '{}' && !pending) return; + if (!dirty && !state.busy && !state.uncertain && contentValid && !pendingContent) return; const warn = (event: BeforeUnloadEvent) => { event.preventDefault(); }; window.addEventListener('beforeunload', warn); return () => window.removeEventListener('beforeunload', warn); - }, [signature, pending]); - useEffect(() => { - if (signature === '{}' || failure || pending) return; - const timer = window.setTimeout(() => void save(), 650); - return () => window.clearTimeout(timer); - }); // Restart debounce whenever the draft changes; failed edits never retry silently. - return { if (!open) void save().then(ok => { if (ok) onClose(); }); }} title={t('taskDetails')} sheet> -

{pending ? t('saving') : failure ? t('taskSaveFailed') : signature === '{}' ? t('taskSaved') : t('saving')}

+ }, [dirty, state.busy, state.uncertain, contentValid, pendingContent]); + useEffect(() => () => { closeRequest.current++; }, []); + + const leaveAction = useRef(onClose); + useNavigationGuard(next => { leaveAction.current = next; void requestClose(); }); + async function requestClose() { + const request = ++closeRequest.current; + if (!contentValid || pendingContent || state.restored) { setLeaving(true); return; } + setClosing(true); + const saved = await editor.flush(); + setClosing(false); + if (request !== closeRequest.current) return; + if (saved && !contentState.current.busyContent && contentState.current.contentValid) leaveAction.current(); else setLeaving(true); + } + async function retry() { + if (busyContent || !contentValid) return; + await editor.flush({ retry: true, confirm: failure?.message === 'confirm_unavailable' }); + } + async function copyDescription(value: Task['description']) { + try { await navigator.clipboard.writeText(plainText(value)); setCopied(t('draftCopied')); } + catch { setCopied(t('copyDraftManually')); } + } + const labelFor = (field: string) => t(field === 'epicId' ? 'epic' : field); + const fieldText = (value: typeof draft, field: string) => { + const fieldValue = value[field as keyof typeof draft]; + if (field === 'column') return t('column_' + value.column); + if (field === 'high') return value.high ? t('high') : t('none'); + if (field === 'epicId') return entities.find(entity => entity.id === value.epicId)?.name ?? t('noEpic'); + if (Array.isArray(fieldValue)) return fieldValue.map(id => + members.find(member => member.id === id)?.name ?? entities.find(entity => entity.id === id)?.name ?? t('unavailable')).join(', ') || t('none'); + return fieldValue === null ? t('none') : String(fieldValue); + }; + const conflictFields = failure?.fields ?? []; + const status = !busyContent && pendingContent ? 'uploadsNeedAttention' : busyContent ? 'contentBusy' : state.busy ? (state.uncertain && failure ? 'checkingSave' : 'saving') + : !contentValid || failure ? 'taskSaveFailed' : state.restored ? 'draftRestored' : dirty ? 'unsavedChanges' : 'taskSaved'; + return { if (!open) onClose(); }} title={t('taskDetails')} sheet mobileBack onReturnFocus={onReturnFocus} + className={'task-detail' + (expanded ? ' task-detail-expanded' : '')} + headerContent={<> + +

{t(status)}

+ + }> + {copied &&

{copied}

} + {state.storageFailed &&

{t('draftStorageFailed')}

} + {state.restored &&

{t('draftRestoredHelp')}

} {failure &&
-

{t(failure.message === 'task_conflict' ? 'conflictText' : failure.message)}

- {failure.current ?
- : } +

{t(failure.message === 'task_conflict' ? 'conflictReview' : failure.message === 'invalid_input' ? 'fixInvalidFields' : failure.message)}

+ {failure.current ? <> +

{conflictFields.map(labelFor).join(', ')}

+
+ {([['myDraft', draft], ['latestSaved', failure.current]] as const).map(([label, value]) =>
+

{t(label)}

+ {conflictFields.map(field => field === 'description' ?
+ + +
:

{labelFor(field)}: {fieldText(value, field)}

)} +
)} +
+

{t('conflictEditHelp')}

+
+ + +
+ {copied &&

{copied}

} + : }
} -
+
-