Files
accounted/app/api/user/ui-state/route.ts
T
Mattsson b4b7549004 feat(agent): resizable, undockable assistant panel (#1467)
* feat(agent): resizable, undockable assistant panel

User report: the assistant chat sheet sometimes covers the page content
the user is asking about, with no way to resize or move it.

- Docked mode is now drag-resizable from its left edge (380-800px,
  clamped so the page keeps a 480px readable column) and the page
  reflows beside it via the existing --agent-dock-w reservation.
- Expanded (focus) mode reserves page margin like the compact dock
  instead of overlaying up to 1100px of the page.
- New undock toggle turns the sheet into a floating window that can be
  dragged by its header and resized from edges/corners, clamped so the
  header always stays reachable. Desktop only; mobile keeps the
  full-screen sheet.
- Geometry (mode, dock width, float rect) persists per user in
  user_preferences.ui_state.agent_panel, server-seeded to avoid a
  first-paint jump; the ui-state API schema gains a strict agent_panel
  key with nested merge.
- Pure clamp/resize math lives in lib/agent-panel/geometry with unit
  tests; drag frames write styles imperatively and commit one
  preference update on release.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(agent): address review findings on panel drag, a11y, and persistence

CodeRabbit round 1, all six findings fixed:

- Bind drag listeners to window (plus lostpointercapture) so a failed
  pointer capture or mid-drag unmount can never leave the transition
  suppression and data-agent-resizing stuck for the session.
- Keyboard resize now steps from the visible width (expandedW in focus
  mode) instead of jumping to the persisted dock width.
- The width handle exposes window-splitter semantics: aria-valuenow,
  aria-valuemin, aria-valuemax.
- --nav-w is read reactively via a MutationObserver on #dash-shell
  instead of computed-style reads in the render body and per drag frame.
- The ui-state POST in updatePanelPrefs gets a 300ms trailing debounce
  (state stays immediate) so key auto-repeat cannot produce one
  read-merge-write per repeat; pending write flushes on unmount.
- globals.css keeps one :root token block; the agent-resizing rule moved
  below it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(agent): filter drag events by pointer id, clear fired debounce timer

CodeRabbit round 2, both findings fixed:

- Window-level drag listeners now ignore events from pointers other than
  the initiating one, so a second touch or pen cannot move the panel or
  end the first pointer's drag.
- The persist debounce timer ref is nulled when the timer fires, so the
  unmount flush only writes genuinely pending values instead of
  replaying an already-persisted (possibly stale) geometry.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-08 16:13:02 +02:00

94 lines
3.0 KiB
TypeScript

import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireAuth } from '@/lib/auth/require-auth'
import type { UserUiState } from '@/types'
// Partial update: the client sends only the keys it changed. Strict schemas
// so typos fail loudly instead of accumulating junk in the jsonb bag.
const BodySchema = z
.object({
nav_collapsed: z.boolean().optional(),
nav_folds: z
.object({
register: z.boolean().optional(),
bokslut: z.boolean().optional(),
})
.strict()
.optional(),
create_mode: z.record(z.string(), z.string().max(64)).optional(),
// Assistant panel geometry. Bounds are deliberately looser than the
// client's viewport clamps: a size saved on a large screen must round-trip
// even when later read on a small one (the client re-clamps on use).
agent_panel: z
.object({
mode: z.enum(['docked', 'floating']).optional(),
dock_width: z.number().int().min(320).max(1600).optional(),
float: z
.object({
x: z.number().int().min(-8000).max(16000),
y: z.number().int().min(-8000).max(16000),
w: z.number().int().min(280).max(4000),
h: z.number().int().min(280).max(4000),
})
.strict()
.optional(),
})
.strict()
.optional(),
})
.strict()
// User-scoped preference endpoint: no company context exists or is needed,
// so requireAuth() directly (same opt-out as /api/user/locale). RLS scopes
// user_preferences to the caller's own row.
export async function POST(request: Request) {
const { user, supabase, error } = await requireAuth()
if (error) return error
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
}
const parsed = BodySchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid ui_state payload' }, { status: 400 })
}
// Read-merge-write: last write wins per key. Fine for cosmetic UI state;
// concurrent tabs converge on the next read.
const { data: existing } = await supabase
.from('user_preferences')
.select('ui_state')
.eq('user_id', user.id)
.maybeSingle()
const current: UserUiState = (existing?.ui_state as UserUiState) ?? {}
const patch = parsed.data
const next: UserUiState = {
...current,
...patch,
...(patch.nav_folds
? { nav_folds: { ...current.nav_folds, ...patch.nav_folds } }
: {}),
...(patch.create_mode
? { create_mode: { ...current.create_mode, ...patch.create_mode } }
: {}),
...(patch.agent_panel
? { agent_panel: { ...current.agent_panel, ...patch.agent_panel } }
: {}),
}
const { error: upsertError } = await supabase
.from('user_preferences')
.upsert({ user_id: user.id, ui_state: next }, { onConflict: 'user_id' })
if (upsertError) {
return NextResponse.json({ error: 'Could not save UI preferences' }, { status: 500 })
}
return NextResponse.json({ data: { ui_state: next } })
}