Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/components/LayersPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type { ComponentDef } from '../../shared/components'
import { canEditOpenCanvas, pickedSelectors, useStore } from '../lib/store'
import { currentPageCanvas, usePageCanvas } from '../lib/pages'
import { PagesPanel, sectionHeading } from './PagesPanel'
import { usePagesPct } from '../lib/pagesSplit'
import { getIdentity } from '../lib/identity'
import { deleteFramesTracked } from '../lib/history'
import { api } from '../lib/api'
Expand Down Expand Up @@ -258,6 +259,8 @@ export function LayersPanel({
const setLayersOpen = useStore((s) => s.setLayersOpen)
const t = useT()
const [query, setQuery] = useState('')
/* the Pages section's share of the rail, once dragged; kept across reloads */
const [pagesPct, setPagesPct] = usePagesPct()
const [expanded, setExpanded] = useState<Set<string>>(() => new Set())
/* the row being dragged and where it would land; the pointer handlers are
bound to the window for the length of the press, so they read the rows
Expand Down Expand Up @@ -581,7 +584,7 @@ export function LayersPanel({
<>
{/* Figma's order: the pages at the top, the frames of the active page
under them, the search at the bottom within thumb's reach */}
<PagesPanel />
<PagesPanel pagesPct={pagesPct} onPagesPctChange={setPagesPct} />
<div className={cn('mt-1.5 flex h-6 flex-none items-center justify-between pr-2.5 pl-3.5', sectionHeading)}>
<span data-slot="frame-section-heading" className={sectionHeading}>
{t('panels.layersTitle')}
Expand Down
72 changes: 69 additions & 3 deletions src/components/PagesPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { ApiError } from '../lib/api'
import { Button } from './ui/button'
import { PageIcon, PlusIcon } from './ui/icons'
import { cn } from '../lib/utils'
import { clampPagesPx, pagesHeightCss, pagesPctOf, pagesPxAfterKey } from '../lib/pagesSplit'
import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem } from './ui/context-menu'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select'
import { useT } from '@/lib/i18n'
Expand All @@ -18,7 +19,15 @@ import { useT } from '@/lib/i18n'
export const sectionHeading = 'text-[11px] font-normal text-ink-faint'
const sectionBtn = 'size-5 rounded-[5px] text-ink-faint hover:bg-paper-deep hover:text-ink'

export function PagesPanel({ fill = false }: { fill?: boolean }) {
export function PagesPanel({
pagesPct = null,
onPagesPctChange,
}: {
/** the section's share of the rail's height once dragged; null keeps its own height */
pagesPct?: number | null
/** given in the Layers rail: the section's bottom edge is the handle that sets the share */
onPagesPctChange?: (pct: number) => void
}) {
const canvas = useStore((s) => s.canvas)
const activePageId = useStore((s) => s.activePageId)
const selectedIds = useStore((s) => s.selectedIds)
Expand Down Expand Up @@ -301,14 +310,20 @@ export function PagesPanel({ fill = false }: { fill?: boolean }) {
)

return (
<div className={cn('flex flex-none flex-col', fill && 'min-h-0 flex-1')}>
<div
data-slot="pages-panel"
className="relative flex flex-none flex-col"
style={pagesPct === null ? undefined : { height: pagesHeightCss(pagesPct) }}
>
<div className={cn('mt-1.5 flex h-6 flex-none items-center justify-between pr-2.5 pl-3.5', sectionHeading)}>
<span data-slot="page-section-heading" className={sectionHeading}>
{t('panels.pagesTitle')}
</span>
{!readOnly && addPage}
</div>
<div className={cn('overflow-y-auto px-2 pb-1', fill ? 'min-h-0 flex-1' : 'max-h-[30vh]')}>{list}</div>
<div className={cn('overflow-y-auto px-2 pb-1', pagesPct === null ? 'max-h-[30vh]' : 'min-h-0 flex-1')}>
{list}
</div>
{!readOnly && selectedIds.length > 0 && pages.length > 1 && (
/* the canvas shortcuts listen on window: ⌫ would delete the frames
being moved and typed letters would switch tools, so the picker's
Expand All @@ -331,6 +346,57 @@ export function PagesPanel({ fill = false }: { fill?: boolean }) {
</Select>
</div>
)}
{onPagesPctChange && <PagesSplitHandle onChange={onPagesPctChange} />}
</div>
)
}

/** The Pages section's bottom edge: dragged, or moved with the arrow keys, Home and End. Each step measures the
* section and its rail again, so it starts from what is on screen. The browser releases the pointer's capture
* when the drag ends, which resets the drag. */
function PagesSplitHandle({ onChange }: { onChange: (pct: number) => void }) {
const t = useT()
const drag = useRef<{ y: number; pagesPx: number; railPx: number } | null>(null)
return (
<div
role="separator"
tabIndex={0}
aria-orientation="horizontal"
aria-label={t('panels.pagesResize')}
data-slot="pages-split"
Comment thread
baekjosh marked this conversation as resolved.
Resolved
className="absolute inset-x-2 top-full h-1.5 cursor-row-resize touch-none rounded-full focus-visible:bg-ink/20 focus-visible:outline-none"
onPointerDown={(e) => {
if (e.button !== 0) return
e.preventDefault()
e.stopPropagation()
drag.current = { y: e.clientY, ...measurePages(e.currentTarget) }
e.currentTarget.setPointerCapture(e.pointerId)
}}
onPointerMove={(e) => {
const start = drag.current
if (!start) return
e.stopPropagation()
const px = clampPagesPx(start.pagesPx + e.clientY - start.y, start.railPx)
onChange(pagesPctOf(px, start.railPx))
}}
onLostPointerCapture={() => {
drag.current = null
}}
onKeyDown={(e) => {
const { pagesPx, railPx } = measurePages(e.currentTarget)
const px = pagesPxAfterKey(e.key, pagesPx, railPx)
if (px === undefined) return
e.preventDefault()
e.stopPropagation()
onChange(pagesPctOf(px, railPx))
}}
/>
)
}

/** The Pages section and the rail it sits in, both in px. */
function measurePages(handle: HTMLElement) {
const pages = handle.closest<HTMLElement>('[data-slot="pages-panel"]')!
const rail = handle.closest<HTMLElement>('[data-slot="panel"]')!
return { pagesPx: pages.getBoundingClientRect().height, railPx: rail.getBoundingClientRect().height }
}
1 change: 1 addition & 0 deletions src/lib/i18n/en/panels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export const panels = {
pagesMoveFailed: 'Could not move all selected frames to the page',
pagesSaveFailed: 'Could not save pages',
pagesDuplicateFailed: 'Could not duplicate the page',
pagesResize: 'Resize pages',

memoryIntro: 'Memory is how this canvas remembers your taste — and how every agent designs with it.',
memoryReferences: 'References',
Expand Down
1 change: 1 addition & 0 deletions src/lib/i18n/pt-BR/panels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export const panels: Catalog['panels'] = {
pagesMoveFailed: 'Não foi possível mover todos os frames selecionados para a página',
pagesSaveFailed: 'Não foi possível salvar as páginas',
pagesDuplicateFailed: 'Não foi possível duplicar a página',
pagesResize: 'Redimensionar páginas',

memoryIntro: 'A Memória é como este canvas lembra do seu gosto — e como cada agente cria designs com ele.',
memoryReferences: 'Referências',
Expand Down
77 changes: 77 additions & 0 deletions src/lib/pagesSplit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/* The split between the Pages list and the Layers tree in the canvas rail.
It is kept as a percentage of the rail's height, so one split fits any
window. `pagesHeightCss` clamps it again in CSS, so a window that shrinks
below the size the split was dragged in still shows both lists. */
import { useEffect, useState } from 'react'

/** the least the Pages section gets: its heading and one row */
export const PAGES_MIN_PX = 54
Comment thread
baekjosh marked this conversation as resolved.
Resolved
/** what the Layers tree always keeps: the rail's header, the Layers heading
* and search footer, and room for a few rows */
export const LAYERS_MIN_PX = 240
/** how far one arrow press moves the split */
export const PAGES_KEY_STEP_PX = 10

const STORAGE_KEY = 'doop:layers-pages-split'

/** a Pages height, held between its minimum and the room the Layers tree keeps */
export function clampPagesPx(px: number, railPx: number): number {
const max = Math.max(PAGES_MIN_PX, railPx - LAYERS_MIN_PX)
return Math.min(max, Math.max(PAGES_MIN_PX, px))
}

/** a Pages height as a percentage of the rail */
export function pagesPctOf(px: number, railPx: number): number {
return (px / railPx) * 100
}

/** the CSS height of the Pages section for a stored percentage, with the limits `clampPagesPx` applies */
export function pagesHeightCss(pct: number): string {
return `clamp(${PAGES_MIN_PX}px, ${pct}%, calc(100% - ${LAYERS_MIN_PX}px))`
}

/** the Pages height an arrow key, Home or End asks for; undefined for any other key.
* Home and End clamp infinity, so they stop at the same limits as a drag. */
export function pagesPxAfterKey(key: string, pagesPx: number, railPx: number): number | undefined {
switch (key) {
case 'ArrowUp':
return clampPagesPx(pagesPx - PAGES_KEY_STEP_PX, railPx)
case 'ArrowDown':
return clampPagesPx(pagesPx + PAGES_KEY_STEP_PX, railPx)
case 'Home':
return clampPagesPx(-Infinity, railPx)
case 'End':
return clampPagesPx(Infinity, railPx)
default:
return undefined
}
}

/** a stored split, or null when it is missing or not a percentage of the rail */
export function readPagesPct(raw: string | null): number | null {
if (raw === null) return null
const pct = Number(raw)
return Number.isFinite(pct) && pct > 0 && pct < 100 ? pct : null
}

/** The split as the user last left it, kept per browser; null until it is dragged. */
export function usePagesPct(): [number | null, (pct: number | null) => void] {
const [pct, setPct] = useState<number | null>(readStoredPct)
useEffect(() => {
try {
if (pct === null) localStorage.removeItem(STORAGE_KEY)
else localStorage.setItem(STORAGE_KEY, String(pct))
} catch {
/* the split still works when it cannot be saved */
}
}, [pct])
return [pct, setPct]
}

function readStoredPct(): number | null {
try {
return readPagesPct(localStorage.getItem(STORAGE_KEY))
} catch {
return null
}
}
24 changes: 17 additions & 7 deletions tests/canvasPageFixture.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import type { Page } from 'puppeteer-core'
import type { Frame } from '../shared/types'
import type { CanvasPageInfo, Frame } from '../shared/types'
import { fixtureUrl } from './browser'

declare global {
interface Window {
canvasPageHarness: { seed: (frames: Frame[]) => void }
canvasPageHarness: { seed: (frames: Frame[], pages?: CanvasPageInfo[]) => void }
}
}

Expand All @@ -18,11 +18,16 @@ export function canvasFrame(frame: Pick<Frame, 'id' | 'name' | 'x' | 'y' | 'widt
* whose subject is what the browser does with the page: the room's socket
* never opens, the session is a signed-in person, and every other API call is
* answered with an empty object. `search` is the page URL's query, as a deep
* link carries it.
* link carries it. `pages`, when given, are the canvas's pages.
*/
export async function openCanvasPage(page: Page, frames: Frame[], search = ''): Promise<void> {
export async function openCanvasPage(
page: Page,
frames: Frame[],
search = '',
pages?: CanvasPageInfo[],
): Promise<void> {
await prepareCanvasPage(page)
await showCanvasPage(page, frames, search)
await showCanvasPage(page, frames, search, pages)
}

/** The stubs alone, for a test that has something to do before the page loads. */
Expand Down Expand Up @@ -51,9 +56,14 @@ export async function prepareCanvasPage(page: Page): Promise<void> {
}

/** Load the fixture, or load it again, on a prepared page. */
export async function showCanvasPage(page: Page, frames: Frame[], search = ''): Promise<void> {
export async function showCanvasPage(
page: Page,
frames: Frame[],
search = '',
pages?: CanvasPageInfo[],
): Promise<void> {
await page.goto(fixtureUrl(`canvasPage.html${search}`))
await page.waitForFunction(() => !!window.canvasPageHarness && !!document.querySelector('.stage'))
await page.evaluate((frames) => window.canvasPageHarness.seed(frames), frames)
await page.evaluate((frames, pages) => window.canvasPageHarness.seed(frames, pages), frames, pages)
await page.waitForSelector('[data-frame-title]')
}
12 changes: 10 additions & 2 deletions tests/fixtures/canvasPage.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,16 @@
/* the canvas page as an editor has it open, with all its chrome; the
test hands it the canvas the room would have sent */
window.canvasPageHarness = {
seed: (frames) =>
useStore.getState().setCanvas({ id: 'c', name: 'Canvas', frames, role: 'edit', createdAt: 0, updatedAt: 0 }),
seed: (frames, pages) =>
useStore.getState().setCanvas({
id: 'c',
name: 'Canvas',
frames,
pages,
role: 'edit',
createdAt: 0,
updatedAt: 0,
}),
}
createRoot(document.getElementById('root')).render(
React.createElement(TooltipProvider, null, React.createElement(CanvasPage, { canvasId: 'c' })),
Expand Down
45 changes: 45 additions & 0 deletions tests/pagesSplit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { describe, expect, it } from 'vitest'
import { LAYERS_MIN_PX, PAGES_MIN_PX, clampPagesPx, pagesPxAfterKey, readPagesPct } from '../src/lib/pagesSplit'

describe('clampPagesPx', () => {
it('holds the Pages section between its minimum and the room the Layers tree keeps', () => {
expect(clampPagesPx(-500, 800)).toBe(PAGES_MIN_PX)
expect(clampPagesPx(10_000, 800)).toBe(800 - LAYERS_MIN_PX)
expect(clampPagesPx(300, 800)).toBe(300)
})

it('keeps one row of Pages in a rail too short to hold both lists', () => {
expect(clampPagesPx(400, 200)).toBe(PAGES_MIN_PX)
})
})

describe('pagesPxAfterKey', () => {
it('moves the split one step per arrow press and stops at its limits', () => {
expect(pagesPxAfterKey('ArrowDown', 300, 800)).toBe(310)
expect(pagesPxAfterKey('ArrowUp', 300, 800)).toBe(290)
expect(pagesPxAfterKey('ArrowUp', PAGES_MIN_PX, 800)).toBe(PAGES_MIN_PX)
})

it('takes Home and End to the two limits', () => {
expect(pagesPxAfterKey('Home', 300, 800)).toBe(PAGES_MIN_PX)
expect(pagesPxAfterKey('End', 300, 800)).toBe(800 - LAYERS_MIN_PX)
})

it('leaves every other key to the page', () => {
expect(pagesPxAfterKey('a', 300, 800)).toBeUndefined()
})
})

describe('readPagesPct', () => {
it('keeps a stored split', () => {
expect(readPagesPct('37.5')).toBe(37.5)
})

it('drops anything that is not a split of the rail, so a bad value falls back to the default', () => {
expect(readPagesPct(null)).toBeNull()
expect(readPagesPct('')).toBeNull()
expect(readPagesPct('tall')).toBeNull()
expect(readPagesPct('0')).toBeNull()
expect(readPagesPct('100')).toBeNull()
})
})
Loading
Loading