mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-17 05:26:47 +03:00
feat(session-ui): maximize Mermaid diagrams to zoom and pan them (#59250)
This commit is contained in:
committed by
GitHub
Unverified
parent
1c53e40a7f
commit
b268a4e8b0
@@ -112,6 +112,7 @@ export type IconName =
|
||||
| "outline-list-changelog"
|
||||
| "outline-magnifier-minus"
|
||||
| "outline-magnifier-plus"
|
||||
| "outline-maximize"
|
||||
| "outline-pair"
|
||||
| "outline-photo"
|
||||
| "outline-quote"
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { expect, story } from "../../stories/playwright/story"
|
||||
|
||||
story("maximizes a Mermaid diagram to zoom into and move around", async ({ mount, page }) => {
|
||||
await page.setViewportSize({ width: 1280, height: 860 })
|
||||
const root = await mount("current-session-mermaid--state-graph")
|
||||
const inline = root.locator('[data-component="markdown-mermaid"] > svg')
|
||||
await expect(inline).toContainText("Boundary")
|
||||
await root.locator('[data-component="markdown-code"]').hover()
|
||||
await root.getByRole("button", { name: "Maximize diagram" }).click()
|
||||
|
||||
const preview = page.locator('[data-component="diagram-preview"]')
|
||||
const diagram = preview.locator('[data-slot="diagram-preview-canvas"] > svg')
|
||||
const level = preview.locator('[data-slot="diagram-preview-zoom-level"]')
|
||||
await expect(diagram).toContainText("Boundary")
|
||||
expect((await diagram.boundingBox())!.width).toBeGreaterThan((await inline.boundingBox())!.width)
|
||||
const fit = (await level.textContent())!
|
||||
|
||||
await preview.getByRole("button", { name: "Zoom in" }).click()
|
||||
await expect(level).not.toHaveText(fit)
|
||||
await expect(preview.locator('[data-slot="diagram-preview-body"]')).toHaveAttribute("data-zoomed", "")
|
||||
|
||||
// An arrow key moves the view right, so the diagram moves left.
|
||||
const x = (await diagram.boundingBox())!.x
|
||||
await page.keyboard.press("ArrowRight")
|
||||
await expect.poll(async () => (await diagram.boundingBox())!.x).toBeLessThan(x - 10)
|
||||
|
||||
// The first Escape zooms back to fit, the second closes, and the diagram is still in the message.
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(level).toHaveText(fit)
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(preview).toHaveCount(0)
|
||||
await expect(inline).toBeVisible()
|
||||
})
|
||||
|
||||
story("opens a small diagram at its drawn size", async ({ mount, page }) => {
|
||||
await page.setViewportSize({ width: 1280, height: 860 })
|
||||
const root = await mount("current-session-mermaid--diagrams")
|
||||
await root.locator('[data-component="markdown-code"]').first().hover()
|
||||
await root.getByRole("button", { name: "Maximize diagram" }).first().click()
|
||||
const preview = page.locator('[data-component="diagram-preview"]')
|
||||
await expect(preview.locator('[data-slot="diagram-preview-canvas"] > svg')).toContainText("Client")
|
||||
await expect(preview.locator('[data-slot="diagram-preview-zoom-level"]')).toHaveText("100%")
|
||||
})
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { DiagramPreview } from "@opencode/ui/diagram-preview"
|
||||
|
||||
// Opens a rendered Mermaid diagram maximized when its button is pressed. The preview gets its own copy, so the diagram
|
||||
// in the message stays where it is, and keeps updating while it streams.
|
||||
export function createDiagramPreview() {
|
||||
const dialog = useDialog()
|
||||
|
||||
return (root: HTMLElement) => {
|
||||
const open = (event: MouseEvent) => {
|
||||
const button = event.target instanceof Element && event.target.closest('[data-slot="markdown-mermaid-maximize"]')
|
||||
|
||||
if (!button) return
|
||||
|
||||
const svg = button.parentElement
|
||||
?.querySelector(':scope > [data-component="markdown-mermaid"] > svg')
|
||||
?.cloneNode(true)
|
||||
|
||||
if (!(svg instanceof SVGSVGElement)) return
|
||||
event.preventDefault()
|
||||
dialog.show(() => <DiagramPreview svg={svg} />)
|
||||
}
|
||||
|
||||
root.addEventListener("click", open)
|
||||
|
||||
return () => root.removeEventListener("click", open)
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,23 @@
|
||||
font-family: var(--font-family-mono);
|
||||
}
|
||||
|
||||
/* Pele colors a diagram from these, in a message and maximized. */
|
||||
:is([data-component="markdown-mermaid"], [data-component="diagram-preview"]) {
|
||||
--pele-bg: var(--v2-background-bg-layer-02);
|
||||
--pele-fg: var(--v2-text-text-base);
|
||||
--pele-muted: var(--v2-text-text-muted);
|
||||
--pele-line: var(--v2-icon-icon-muted);
|
||||
--pele-surface: var(--v2-background-bg-base);
|
||||
--pele-surface-alt: var(--v2-background-bg-layer-03);
|
||||
--pele-border: var(--v2-border-border-strong);
|
||||
--pele-accent: var(--v2-text-text-accent);
|
||||
--pele-critical: var(--v2-state-fg-danger);
|
||||
--pele-error: var(--v2-state-fg-danger);
|
||||
--pele-font: var(--font-family-sans);
|
||||
--pele-font-mono: var(--font-family-mono);
|
||||
--pele-radius: 6px;
|
||||
}
|
||||
|
||||
[data-component="markdown"] {
|
||||
--markdown-inline-code-path-color: var(--v2-text-text-code-path);
|
||||
--markdown-inline-code-color: var(--v2-text-text-code-accent);
|
||||
@@ -287,19 +304,6 @@
|
||||
}
|
||||
|
||||
[data-component="markdown-mermaid"] {
|
||||
--pele-bg: var(--v2-background-bg-layer-02);
|
||||
--pele-fg: var(--v2-text-text-base);
|
||||
--pele-muted: var(--v2-text-text-muted);
|
||||
--pele-line: var(--v2-icon-icon-muted);
|
||||
--pele-surface: var(--v2-background-bg-base);
|
||||
--pele-surface-alt: var(--v2-background-bg-layer-03);
|
||||
--pele-border: var(--v2-border-border-strong);
|
||||
--pele-accent: var(--v2-text-text-accent);
|
||||
--pele-critical: var(--v2-state-fg-danger);
|
||||
--pele-error: var(--v2-state-fg-danger);
|
||||
--pele-font: var(--font-family-sans);
|
||||
--pele-font-mono: var(--font-family-mono);
|
||||
--pele-radius: 6px;
|
||||
min-height: 96px;
|
||||
margin: 12px 0 24px;
|
||||
padding: 16px;
|
||||
@@ -318,6 +322,28 @@
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
[data-slot="markdown-mermaid-maximize"] {
|
||||
display: none;
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
inset-inline-end: 4px;
|
||||
transition: opacity 0.15s ease;
|
||||
z-index: 1;
|
||||
|
||||
@media (hover: hover) {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
[data-component="markdown-code"][data-mermaid-ready="true"] > [data-slot="markdown-mermaid-maximize"] {
|
||||
display: block;
|
||||
}
|
||||
|
||||
[data-component="markdown-code"]:hover > [data-slot="markdown-mermaid-maximize"],
|
||||
[data-slot="markdown-mermaid-maximize"]:focus-within {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
[data-component="markdown-code"][data-mermaid-pending="true"] > pre,
|
||||
[data-component="markdown-code"][data-mermaid-pending="true"] > [data-slot="markdown-copy-button"],
|
||||
[data-component="markdown-code"][data-mermaid-pending="true"] > [data-slot="markdown-code-actions"],
|
||||
|
||||
@@ -69,6 +69,7 @@ import {
|
||||
} from "../context/markdown"
|
||||
import { createMarkdownImages } from "./markdown-image"
|
||||
import { createImagePreview } from "./image-preview"
|
||||
import { createDiagramPreview } from "./diagram-preview"
|
||||
import { setupFragmentLinks } from "./markdown-fragment-links"
|
||||
import { markSessionLinks, sessionReferenceClipboardText, setupSessionLinks } from "./markdown-session-links"
|
||||
import { markdownClipboardHtml } from "./markdown-clipboard"
|
||||
@@ -144,18 +145,20 @@ async function code(text: string, language: string | undefined, key: string, com
|
||||
}
|
||||
}
|
||||
|
||||
type CopyLabels = {
|
||||
type CodeLabels = {
|
||||
copy: string
|
||||
copied: string
|
||||
maximize: string
|
||||
}
|
||||
|
||||
type CopyButtonState = {
|
||||
setLabels: Setter<CopyLabels>
|
||||
copy: (text: string) => void
|
||||
type CodeButtonState = {
|
||||
setLabels: Setter<CodeLabels>
|
||||
/** Only a copy button copies. */
|
||||
copy?: (text: string) => void
|
||||
dispose: () => void
|
||||
}
|
||||
|
||||
const copyButtonState = new WeakMap<HTMLElement, CopyButtonState>()
|
||||
const codeButtonState = new WeakMap<HTMLElement, CodeButtonState>()
|
||||
|
||||
const urlPattern = /^https?:\/\/[^\s<>()`"']+$/
|
||||
|
||||
@@ -173,11 +176,11 @@ function codeUrl(text: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function createCopyButton(labels: CopyLabels) {
|
||||
function createCopyButton(labels: CodeLabels) {
|
||||
const host = document.createElement("div")
|
||||
host.setAttribute("data-slot", "markdown-copy-button")
|
||||
|
||||
const state: Partial<CopyButtonState> = {}
|
||||
const state: Partial<CodeButtonState> = {}
|
||||
|
||||
const dispose = render(() => {
|
||||
const [labelState, setLabels] = createSignal(labels, { equals: false })
|
||||
@@ -194,12 +197,12 @@ function createCopyButton(labels: CopyLabels) {
|
||||
|
||||
state.dispose = dispose
|
||||
// SAFETY: `render` runs its function synchronously, so `setLabels` and `copy` are assigned before this line.
|
||||
copyButtonState.set(host, state as CopyButtonState)
|
||||
codeButtonState.set(host, state as CodeButtonState)
|
||||
|
||||
return host
|
||||
}
|
||||
|
||||
function MarkdownCopyButton(props: { labels: CopyLabels; copied: boolean }) {
|
||||
function MarkdownCopyButton(props: { labels: CodeLabels; copied: boolean }) {
|
||||
const label = () => (props.copied ? props.labels.copied : props.labels.copy)
|
||||
|
||||
return (
|
||||
@@ -220,7 +223,9 @@ function MarkdownCopyButton(props: { labels: CopyLabels; copied: boolean }) {
|
||||
)
|
||||
}
|
||||
|
||||
const codeHostSelector = '[data-slot="markdown-copy-button"], [data-component="markdown-code"]'
|
||||
const codeButtons = '[data-slot="markdown-copy-button"], [data-slot="markdown-mermaid-maximize"]'
|
||||
|
||||
const codeHostSelector = `${codeButtons}, [data-component="markdown-code"]`
|
||||
|
||||
function disposeCodeHosts(root: Element) {
|
||||
const hosts = [
|
||||
@@ -229,13 +234,49 @@ function disposeCodeHosts(root: Element) {
|
||||
]
|
||||
|
||||
hosts.forEach((host) => {
|
||||
copyButtonState.get(host)?.dispose()
|
||||
copyButtonState.delete(host)
|
||||
disposeCodeButton(host)
|
||||
codeDrivers.get(host)?.dispatch({ type: "disposed" })
|
||||
codeDrivers.delete(host)
|
||||
})
|
||||
}
|
||||
|
||||
function disposeCodeButton(host: HTMLElement) {
|
||||
codeButtonState.get(host)?.dispose()
|
||||
codeButtonState.delete(host)
|
||||
}
|
||||
|
||||
// Opens the diagram in a maximized view, where it zooms and pans. The click is handled by the Markdown root.
|
||||
function createDiagramButton(labels: CodeLabels) {
|
||||
const host = document.createElement("div")
|
||||
host.setAttribute("data-slot", "markdown-mermaid-maximize")
|
||||
|
||||
const state: Partial<CodeButtonState> = {}
|
||||
|
||||
const dispose = render(() => {
|
||||
const [labelState, setLabels] = createSignal(labels, { equals: false })
|
||||
state.setLabels = setLabels
|
||||
|
||||
return (
|
||||
<Tooltip placement="top" value={labelState().maximize}>
|
||||
<IconButton
|
||||
type="button"
|
||||
size="normal"
|
||||
variant="ghost-muted"
|
||||
aria-label={labelState().maximize}
|
||||
aria-haspopup="dialog"
|
||||
icon={<Icon name="outline-maximize" />}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
}, host)
|
||||
|
||||
state.dispose = dispose
|
||||
// SAFETY: `render` runs its function synchronously, so the setter is assigned before this line.
|
||||
codeButtonState.set(host, state as CodeButtonState)
|
||||
|
||||
return host
|
||||
}
|
||||
|
||||
function disposeRenderedMarkdown(root: Element) {
|
||||
const blocks = [
|
||||
...(root instanceof HTMLDivElement && root.hasAttribute("data-markdown-block") ? [root] : []),
|
||||
@@ -271,8 +312,12 @@ function applyCodeMetadata(wrapper: HTMLElement, language: string | undefined) {
|
||||
|
||||
type CodePlugins = { blocks: MarkdownCodeBlocks; match: MarkdownCodeBlockMatch }
|
||||
|
||||
// The plugins are the driver's input for mounting; the block's phase lives only in the machine's state.
|
||||
type CodeDriver = { plugins: CodePlugins | undefined; dispatch: (event: CodeDecorationEvent) => void }
|
||||
// The plugins and labels are the driver's input for mounting; the block's phase lives only in the machine's state.
|
||||
type CodeDriver = {
|
||||
plugins: CodePlugins | undefined
|
||||
labels: CodeLabels
|
||||
dispatch: (event: CodeDecorationEvent) => void
|
||||
}
|
||||
|
||||
const codeDrivers = new WeakMap<HTMLElement, CodeDriver>()
|
||||
|
||||
@@ -282,15 +327,22 @@ type CodeContent = { host: HTMLElement; dispose?: () => void }
|
||||
// Content for a block's language replaces its code only once the closing fence arrived, so it never receives half a
|
||||
// block; until then, and when the content declines or fails, the block shows its code (or the built-in diagram).
|
||||
// Blocks of other languages take the plain path and never get a driver.
|
||||
function decorateCode(wrapper: HTMLElement, code: HTMLElement, complete: boolean, plugins: CodePlugins | undefined) {
|
||||
function decorateCode(
|
||||
wrapper: HTMLElement,
|
||||
code: HTMLElement,
|
||||
complete: boolean,
|
||||
plugins: CodePlugins | undefined,
|
||||
labels: CodeLabels,
|
||||
) {
|
||||
const language = codeLanguage(wrapper.dataset.language)
|
||||
const existing = codeDrivers.get(wrapper)
|
||||
|
||||
if (!existing && !plugins && language !== "mermaid") return
|
||||
const driver = existing ?? createCodeDriver(wrapper)
|
||||
const driver = existing ?? createCodeDriver(wrapper, labels)
|
||||
|
||||
if (!existing) codeDrivers.set(wrapper, driver)
|
||||
driver.plugins = plugins
|
||||
driver.labels = labels
|
||||
driver.dispatch({ type: "sync", language, source: code.textContent ?? "", complete, match: plugins?.match })
|
||||
}
|
||||
|
||||
@@ -299,7 +351,7 @@ function codeLanguage(language: string | undefined) {
|
||||
return (language ?? "").toLowerCase().replace(/[^\w#+.-]/g, "")
|
||||
}
|
||||
|
||||
function createCodeDriver(wrapper: HTMLElement): CodeDriver {
|
||||
function createCodeDriver(wrapper: HTMLElement, labels: CodeLabels): CodeDriver {
|
||||
let state = INITIAL_CODE_DECORATION_STATE
|
||||
let actions: { host: HTMLElement; dispose: () => void } | undefined
|
||||
let content: CodeContent | undefined
|
||||
@@ -310,7 +362,7 @@ function createCodeDriver(wrapper: HTMLElement): CodeDriver {
|
||||
|
||||
if (next.state === previous) return
|
||||
state = next.state
|
||||
showCodeDecoration(wrapper, viewCodeDecoration(previous), viewCodeDecoration(state))
|
||||
showCodeDecoration(wrapper, viewCodeDecoration(previous), viewCodeDecoration(state), driver.labels)
|
||||
next.effects.forEach(run)
|
||||
}
|
||||
|
||||
@@ -365,7 +417,7 @@ function createCodeDriver(wrapper: HTMLElement): CodeDriver {
|
||||
mounted.dispose = dispose
|
||||
}
|
||||
|
||||
const driver: CodeDriver = { plugins: undefined, dispatch }
|
||||
const driver: CodeDriver = { plugins: undefined, labels, dispatch }
|
||||
|
||||
return driver
|
||||
}
|
||||
@@ -374,6 +426,7 @@ function showCodeDecoration(
|
||||
wrapper: HTMLElement,
|
||||
previous: ReturnType<typeof viewCodeDecoration>,
|
||||
view: ReturnType<typeof viewCodeDecoration>,
|
||||
labels: CodeLabels,
|
||||
) {
|
||||
if (view.pending) wrapper.dataset.mermaidPending = "true"
|
||||
else delete wrapper.dataset.mermaidPending
|
||||
@@ -383,12 +436,22 @@ function showCodeDecoration(
|
||||
wrapper.toggleAttribute("data-code-content", view.content)
|
||||
const existing = wrapper.querySelector(':scope > [data-component="markdown-mermaid"]')
|
||||
|
||||
if (!view.diagram) return existing?.remove()
|
||||
if (!view.diagram) {
|
||||
existing?.remove()
|
||||
const button = wrapper.querySelector<HTMLElement>(':scope > [data-slot="markdown-mermaid-maximize"]')
|
||||
|
||||
if (!button) return
|
||||
disposeCodeButton(button)
|
||||
|
||||
return button.remove()
|
||||
}
|
||||
|
||||
const diagram = existing ?? document.createElement("div")
|
||||
|
||||
// The maximize button comes and goes with the diagram, and shows once it is drawn.
|
||||
if (!existing) {
|
||||
diagram.setAttribute("data-component", "markdown-mermaid")
|
||||
wrapper.appendChild(diagram)
|
||||
wrapper.append(diagram, createDiagramButton(labels))
|
||||
}
|
||||
|
||||
if (!existing || view.svg !== previous.svg) diagram.innerHTML = view.svg ?? ""
|
||||
@@ -643,7 +706,7 @@ function setupCodeCopy(root: HTMLDivElement) {
|
||||
|
||||
if (!(button instanceof HTMLElement)) return
|
||||
const code = button.closest('[data-component="markdown-code"]')?.querySelector("code")
|
||||
copyButtonState.get(button)?.copy(code?.textContent ?? "")
|
||||
codeButtonState.get(button)?.copy?.(code?.textContent ?? "")
|
||||
}
|
||||
|
||||
root.addEventListener("click", handleClick)
|
||||
@@ -734,6 +797,7 @@ export function Markdown(
|
||||
const i18n = useI18n()
|
||||
const markdown = useMarkdown()
|
||||
const previewImages = createImagePreview()
|
||||
const previewDiagrams = createDiagramPreview()
|
||||
const [root, setRoot] = createSignal<HTMLDivElement>()
|
||||
const owner = createUniqueId()
|
||||
const lifetime = new AbortController()
|
||||
@@ -742,7 +806,7 @@ export function Markdown(
|
||||
const settledMarkdown = new Map<string, Exclude<RenderedBlock, { mode: "code" }>>()
|
||||
let renderedBlocks: RenderedBlock[] = []
|
||||
let lastRender: { base: string | undefined; blocks: Block[]; rendered: RenderedBlock[] } | undefined
|
||||
let appliedLabels: CopyLabels | undefined
|
||||
let appliedLabels: CodeLabels | undefined
|
||||
// The code block languages the blocks were decorated for; false before the first run.
|
||||
let decoratedMatch: MarkdownCodeBlockMatch | undefined | false = false
|
||||
// Every streamed delta dispatches a rendered event, so the driver reuses its events and the machine returns the same
|
||||
@@ -987,6 +1051,7 @@ export function Markdown(
|
||||
|
||||
let copyCleanup: (() => void) | undefined
|
||||
let linkCleanup: (() => void) | undefined
|
||||
let diagramCleanup: (() => void) | undefined
|
||||
let faviconCleanup: (() => void) | undefined
|
||||
let sessionLinkCleanup: (() => void) | undefined
|
||||
let fragmentLinkCleanup: (() => void) | undefined
|
||||
@@ -1037,6 +1102,7 @@ export function Markdown(
|
||||
const labels = {
|
||||
copy: i18n.t("ui.message.copy"),
|
||||
copied: i18n.t("ui.message.copied"),
|
||||
maximize: i18n.t("ui.diagramPreview.open"),
|
||||
}
|
||||
|
||||
const nextCodeKeys = new Set(content.filter((block) => block.mode === "code").map((block) => block.key))
|
||||
@@ -1070,7 +1136,8 @@ export function Markdown(
|
||||
container.querySelectorAll<HTMLElement>('[data-component="markdown-code"]').forEach((wrapper) => {
|
||||
const code = wrapper.querySelector<HTMLElement>(":scope > pre > code")
|
||||
|
||||
if (code) decorateCode(wrapper, code, wrapper.parentElement?.dataset.markdownComplete !== "false", plugins)
|
||||
if (code)
|
||||
decorateCode(wrapper, code, wrapper.parentElement?.dataset.markdownComplete !== "false", plugins, labels)
|
||||
})
|
||||
|
||||
if (sessionLinks) markSessionLinks(container, sessionLinks)
|
||||
@@ -1092,10 +1159,14 @@ export function Markdown(
|
||||
|
||||
// A button gets the labels of the run that creates it, so the others only need new ones when the language changes.
|
||||
// Relabelling every button on each streamed delta re-rendered each one's tooltip and icon button.
|
||||
if (appliedLabels?.copy !== labels.copy || appliedLabels?.copied !== labels.copied)
|
||||
if (
|
||||
appliedLabels?.copy !== labels.copy ||
|
||||
appliedLabels?.copied !== labels.copied ||
|
||||
appliedLabels?.maximize !== labels.maximize
|
||||
)
|
||||
container
|
||||
.querySelectorAll<HTMLElement>('[data-slot="markdown-copy-button"]')
|
||||
.forEach((button) => copyButtonState.get(button)?.setLabels(labels))
|
||||
.querySelectorAll<HTMLElement>(codeButtons)
|
||||
.forEach((button) => codeButtonState.get(button)?.setLabels(labels))
|
||||
|
||||
appliedLabels = labels
|
||||
|
||||
@@ -1103,6 +1174,8 @@ export function Markdown(
|
||||
|
||||
if (!linkCleanup) linkCleanup = setupLocalLinks(container, () => markdown?.openLocalFile)
|
||||
|
||||
if (!diagramCleanup) diagramCleanup = previewDiagrams(container)
|
||||
|
||||
if (!sessionLinkCleanup)
|
||||
sessionLinkCleanup = setupSessionLinks(
|
||||
container,
|
||||
@@ -1128,6 +1201,8 @@ export function Markdown(
|
||||
|
||||
if (linkCleanup) linkCleanup()
|
||||
|
||||
if (diagramCleanup) diagramCleanup()
|
||||
|
||||
if (sessionLinkCleanup) sessionLinkCleanup()
|
||||
|
||||
if (fragmentLinkCleanup) fragmentLinkCleanup()
|
||||
@@ -1207,7 +1282,7 @@ function updateBlock(
|
||||
container: HTMLDivElement,
|
||||
index: number,
|
||||
block: RenderedBlock,
|
||||
labels: CopyLabels,
|
||||
labels: CodeLabels,
|
||||
plugins: CodePlugins | undefined,
|
||||
sessionLinks: ((id: string) => string | undefined) | undefined,
|
||||
signal: AbortSignal,
|
||||
@@ -1285,7 +1360,7 @@ function updateBlock(
|
||||
pre.replaceWith(wrapper)
|
||||
wrapper.appendChild(pre)
|
||||
wrapper.appendChild(createCopyButton(labels))
|
||||
decorateCode(wrapper, code, true, plugins)
|
||||
decorateCode(wrapper, code, true, plugins, labels)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1308,7 +1383,7 @@ function updateCodeBlock(
|
||||
container: HTMLDivElement,
|
||||
current: Element | undefined,
|
||||
block: Extract<RenderedBlock, { mode: "code" }>,
|
||||
labels: CopyLabels,
|
||||
labels: CodeLabels,
|
||||
plugins: CodePlugins | undefined,
|
||||
) {
|
||||
const existing =
|
||||
@@ -1358,7 +1433,7 @@ function updateCodeBlock(
|
||||
raw: block.raw,
|
||||
})
|
||||
|
||||
if (wrapper instanceof HTMLElement) decorateCode(wrapper, code, block.complete, plugins)
|
||||
if (wrapper instanceof HTMLElement) decorateCode(wrapper, code, block.complete, plugins, labels)
|
||||
|
||||
return
|
||||
}
|
||||
@@ -1374,7 +1449,7 @@ function updateCodeBlock(
|
||||
pre.appendChild(codeElement)
|
||||
wrapper.appendChild(pre)
|
||||
wrapper.appendChild(createCopyButton(labels))
|
||||
decorateCode(wrapper, codeElement, block.complete, plugins)
|
||||
decorateCode(wrapper, codeElement, block.complete, plugins, labels)
|
||||
next.appendChild(wrapper)
|
||||
renderedCodeTokens.set(next, {
|
||||
language: block.language,
|
||||
|
||||
@@ -16,6 +16,67 @@ export const Diagrams = {
|
||||
render: (args: { streaming: boolean }) => <MermaidTimeline streaming={args.streaming} />,
|
||||
}
|
||||
|
||||
export const StateGraph = {
|
||||
render: () => <StateGraphTimeline />,
|
||||
}
|
||||
|
||||
// Wide enough that its labels are too small to read inline, which is what the maximized view is for.
|
||||
const SESSION_STATES = `stateDiagram-v2
|
||||
direction LR
|
||||
[*] --> Idle
|
||||
Idle --> Running: wake() or resume()
|
||||
state Running {
|
||||
direction LR
|
||||
[*] --> Boundary
|
||||
Boundary --> Step: next step to continue
|
||||
Boundary --> Compact: context over the limit
|
||||
Boundary --> Drain: inbox has queued items
|
||||
Step --> Boundary: step finished
|
||||
Compact --> Boundary: summary written
|
||||
Drain --> Boundary: item admitted
|
||||
}
|
||||
Running --> Stopping: interrupt() or cancel
|
||||
Stopping --> Settled: fiber exits
|
||||
Running --> Settled: no step and an empty inbox
|
||||
Running --> Suspended: waiting for a permission or question
|
||||
Suspended --> Running: answered
|
||||
Running --> Failed: unrecoverable error
|
||||
Settled --> Idle: execution.ended published
|
||||
Failed --> Idle: execution.ended with an error`
|
||||
|
||||
function StateGraphTimeline() {
|
||||
const document: SessionDocument = {
|
||||
sessionID: CURRENT_SESSION_ID,
|
||||
status: { type: "idle" },
|
||||
diffs: [],
|
||||
messages: [
|
||||
{
|
||||
id: "msg_state_graph_user",
|
||||
type: "user",
|
||||
text: "Show me the state graph of a session.",
|
||||
time: { created: STORY_TIME },
|
||||
metadata: { agent: "build", model: STORY_MODEL },
|
||||
},
|
||||
{
|
||||
id: "msg_state_graph_assistant",
|
||||
type: "assistant",
|
||||
agent: "build",
|
||||
model: STORY_MODEL,
|
||||
time: { created: STORY_TIME + 100, completed: STORY_TIME + 1000 },
|
||||
content: [{ type: "text", text: "## State graph\n\n```mermaid\n" + SESSION_STATES + "\n```" }],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
return (
|
||||
<section class="mx-auto flex w-full max-w-[840px] flex-col gap-4 p-6">
|
||||
<CurrentSessionProviders document={document}>
|
||||
<SessionTimeline document={document} />
|
||||
</CurrentSessionProviders>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function MermaidTimeline(props: { streaming: boolean }) {
|
||||
const [completed, setCompleted] = createSignal(!props.streaming)
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
[data-component="diagram-preview"] {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 50;
|
||||
pointer-events: none;
|
||||
|
||||
/* The diagram is shown over the dialog stack's overlay, fitted to the window with room for the controls under it. */
|
||||
[data-slot="diagram-preview-content"] {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: auto;
|
||||
|
||||
&:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
[data-slot="diagram-preview-content"][data-expanded] {
|
||||
animation: diagram-preview-in 150ms ease-out;
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="diagram-preview-body"] {
|
||||
position: absolute;
|
||||
inset: 44px clamp(8px, 3vw, 36px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 12px;
|
||||
overflow: hidden;
|
||||
user-select: none;
|
||||
/* A zoomed diagram fades out in the padding instead of being cut at the edge; a fitted one never reaches it. */
|
||||
mask-image:
|
||||
linear-gradient(to right, transparent, #000 12px, #000 calc(100% - 12px), transparent),
|
||||
linear-gradient(to bottom, transparent, #000 12px, #000 calc(100% - 12px), transparent);
|
||||
mask-composite: intersect;
|
||||
|
||||
&[data-zoomed] {
|
||||
cursor: grab;
|
||||
touch-action: pinch-zoom;
|
||||
}
|
||||
|
||||
&[data-dragging] {
|
||||
cursor: grabbing;
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="diagram-preview-canvas"] {
|
||||
flex: none;
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--v2-background-bg-layer-02);
|
||||
box-shadow: inset 0 0 0 0.5px var(--v2-border-border-base);
|
||||
transform-origin: center;
|
||||
|
||||
> svg {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="diagram-preview-controls"] {
|
||||
position: absolute;
|
||||
bottom: 12px;
|
||||
inset-inline: 0;
|
||||
width: fit-content;
|
||||
margin-inline: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 2px;
|
||||
border-radius: 8px;
|
||||
background: var(--v2-background-bg-layer-01);
|
||||
box-shadow: var(--v2-elevation-floating);
|
||||
}
|
||||
|
||||
[data-slot="diagram-preview-zoom-level"] {
|
||||
min-width: 52px;
|
||||
justify-content: center;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
[data-slot="diagram-preview-divider"] {
|
||||
width: 1px;
|
||||
height: 16px;
|
||||
margin-inline: 2px;
|
||||
background: var(--v2-border-border-base);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes diagram-preview-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.98);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
import { Dialog as Kobalte, useDialogContext } from "@kobalte/core/dialog"
|
||||
import { makeEventListener } from "@solid-primitives/event-listener"
|
||||
import { createResizeObserver } from "@solid-primitives/resize-observer"
|
||||
import { createMemo, createSignal, onCleanup } from "solid-js"
|
||||
import { useI18n } from "../context/i18n"
|
||||
import { Button } from "@opencode/ui/button"
|
||||
import { Icon } from "@opencode/ui/icon"
|
||||
import { IconButton } from "@opencode/ui/icon-button"
|
||||
import { frameLoop, prefersReducedMotion, Spring } from "../motion"
|
||||
import { FLIGHT_SPRING } from "./image-flight"
|
||||
import {
|
||||
clampView,
|
||||
detailScale,
|
||||
FIT_VIEW,
|
||||
panBy,
|
||||
wheelPixels,
|
||||
wheelZoomFactor,
|
||||
zoomAt,
|
||||
zoomShortcut,
|
||||
type ZoomView,
|
||||
} from "./image-zoom"
|
||||
|
||||
export interface DiagramPreviewProps {
|
||||
/** The diagram to show, which the preview takes over: pass a copy of one still on the page. */
|
||||
svg: SVGSVGElement
|
||||
}
|
||||
|
||||
const STEP = Math.SQRT2
|
||||
|
||||
// How far one arrow key press pans, as a share of the window; Shift pans a whole window.
|
||||
const ARROW_PAN = 0.15
|
||||
|
||||
// How far a diagram zooms in past the size it was drawn at: its labels are crisp at any size, so a few times is enough
|
||||
// to read the smallest.
|
||||
const MAX_ZOOM = 4
|
||||
|
||||
// The canvas around the diagram at its natural size, in pixels.
|
||||
const PADDING = 24
|
||||
|
||||
const CENTER = { x: 0, y: 0 }
|
||||
|
||||
/**
|
||||
* A diagram maximized over the page, zoomed and panned like an image preview. The diagram stays a live SVG, so it is
|
||||
* redrawn sharp at every zoom and keeps the page's fonts and theme.
|
||||
*/
|
||||
export function DiagramPreview(props: DiagramPreviewProps) {
|
||||
const i18n = useI18n()
|
||||
const dialog = useDialogContext()
|
||||
let viewport!: HTMLDivElement
|
||||
let canvas!: HTMLDivElement
|
||||
let close: HTMLButtonElement | undefined
|
||||
const [view, setView] = createSignal(FIT_VIEW)
|
||||
const [goal, setGoal] = createSignal(FIT_VIEW)
|
||||
const [fitRatio, setFitRatio] = createSignal(1)
|
||||
const [drag, setDrag] = createSignal<{ id: number; x: number; y: number }>()
|
||||
// Whether the press that ends in a click began on the backdrop around the diagram, and whether a pan moved since.
|
||||
let backdrop = false
|
||||
let panned = false
|
||||
const glide = [1, 0, 0].map((value) => Spring.fromDuration(value, FLIGHT_SPRING))
|
||||
let gliding: (() => void) | undefined
|
||||
|
||||
const percent = createMemo(() => new Intl.NumberFormat(i18n.locale(), { style: "percent", maximumFractionDigits: 0 }))
|
||||
|
||||
const bounds = () => ({
|
||||
width: canvas.offsetWidth,
|
||||
height: canvas.offsetHeight,
|
||||
viewportWidth: viewport.clientWidth,
|
||||
viewportHeight: viewport.clientHeight,
|
||||
maxScale: Math.max(1, MAX_ZOOM / fitRatio()),
|
||||
})
|
||||
|
||||
const show = (next: ZoomView) => {
|
||||
setView(next)
|
||||
canvas.style.transform = `translate(${next.x}px, ${next.y}px) scale(${next.scale})`
|
||||
}
|
||||
|
||||
const settle = () => {
|
||||
gliding?.()
|
||||
gliding = undefined
|
||||
}
|
||||
|
||||
onCleanup(settle)
|
||||
|
||||
// Pinch, wheel and drag follow the hand directly and take over from an eased zoom mid-flight.
|
||||
const follow = (next: ZoomView) => {
|
||||
settle()
|
||||
setGoal(next)
|
||||
show(next)
|
||||
}
|
||||
|
||||
const ease = (target: ZoomView) => {
|
||||
setGoal(target)
|
||||
|
||||
if (prefersReducedMotion()) return follow(target)
|
||||
|
||||
if (!gliding) [view().scale, view().x, view().y].forEach((value, index) => glide[index].snap(value))
|
||||
;[target.scale, target.x, target.y].forEach((value, index) => glide[index].set(value))
|
||||
gliding ??= frameLoop.add((dt) => {
|
||||
const [scale, x, y] = glide.map((spring) => spring.step(dt))
|
||||
show({ scale, x, y })
|
||||
|
||||
if (!glide.every((spring) => spring.resting)) return true
|
||||
gliding = undefined
|
||||
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
const step = (factor: number) => ease(zoomAt(goal(), goal().scale * factor, CENTER, bounds()))
|
||||
|
||||
// Fits the diagram to the window without enlarging it past the size it was drawn at, keeping the zoom it has. The
|
||||
// padding around it shrinks with it.
|
||||
const measure = () => {
|
||||
const width = props.svg.width.baseVal.value
|
||||
const height = props.svg.height.baseVal.value
|
||||
|
||||
// The window's own padding is where a zoomed diagram fades out, so a fitted one stays inside it.
|
||||
const inset = parseFloat(getComputedStyle(viewport).paddingLeft) * 2
|
||||
const room = { width: viewport.clientWidth - inset, height: viewport.clientHeight - inset }
|
||||
|
||||
if (room.width <= 0 || room.height <= 0) return
|
||||
const fit = Math.min(1, room.width / (width + PADDING * 2), room.height / (height + PADDING * 2))
|
||||
canvas.style.padding = `${PADDING * fit}px`
|
||||
props.svg.style.width = `${width * fit}px`
|
||||
props.svg.style.height = `${height * fit}px`
|
||||
setFitRatio(fit)
|
||||
follow(clampView(view(), bounds()))
|
||||
}
|
||||
|
||||
// Pele sizes the inline diagram to its column; here the preview sizes it.
|
||||
props.svg.style.maxWidth = "none"
|
||||
|
||||
createResizeObserver(() => viewport, measure)
|
||||
|
||||
const point = (event: MouseEvent) => {
|
||||
const rect = viewport.getBoundingClientRect()
|
||||
|
||||
return { x: event.clientX - rect.left - rect.width / 2, y: event.clientY - rect.top - rect.height / 2 }
|
||||
}
|
||||
|
||||
const detail = (event: MouseEvent) => {
|
||||
if (goal().scale > 1) return ease(FIT_VIEW)
|
||||
ease(zoomAt(goal(), detailScale(fitRatio()), point(event), bounds()))
|
||||
}
|
||||
|
||||
const grab = (event: PointerEvent) => {
|
||||
panned = false
|
||||
|
||||
if (event.button !== 0 || view().scale <= 1) return
|
||||
event.preventDefault()
|
||||
viewport.setPointerCapture(event.pointerId)
|
||||
setDrag({ id: event.pointerId, x: event.clientX, y: event.clientY })
|
||||
}
|
||||
|
||||
const pan = (event: PointerEvent) => {
|
||||
const current = drag()
|
||||
|
||||
if (current?.id !== event.pointerId) return
|
||||
backdrop = false
|
||||
panned = true
|
||||
setDrag({ id: current.id, x: event.clientX, y: event.clientY })
|
||||
follow(panBy(view(), { x: event.clientX - current.x, y: event.clientY - current.y }, bounds()))
|
||||
}
|
||||
|
||||
const release = (event: PointerEvent) => {
|
||||
if (drag()?.id === event.pointerId) setDrag(undefined)
|
||||
}
|
||||
|
||||
// The preview owns zoom gestures while it is open: the page behind must neither scroll nor zoom the whole window.
|
||||
makeEventListener(
|
||||
window,
|
||||
"wheel",
|
||||
(event: WheelEvent) => {
|
||||
const inside = event.target instanceof Node && viewport.contains(event.target)
|
||||
const zoom = event.ctrlKey || event.metaKey
|
||||
|
||||
if (!inside && !zoom) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
|
||||
if (!inside) return
|
||||
const current = view()
|
||||
|
||||
if (zoom) {
|
||||
follow(
|
||||
zoomAt(current, current.scale * wheelZoomFactor(wheelPixels(event, event.deltaY)), point(event), bounds()),
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const horizontal = event.shiftKey && event.deltaX === 0
|
||||
follow(
|
||||
panBy(
|
||||
current,
|
||||
{
|
||||
x: -wheelPixels(event, horizontal ? event.deltaY : event.deltaX),
|
||||
y: horizontal ? 0 : -wheelPixels(event, event.deltaY),
|
||||
},
|
||||
bounds(),
|
||||
),
|
||||
)
|
||||
},
|
||||
{ passive: false, capture: true },
|
||||
)
|
||||
|
||||
// Captured ahead of the desktop shell, which zooms the whole window on the same shortcuts.
|
||||
makeEventListener(
|
||||
window,
|
||||
"keydown",
|
||||
(event: KeyboardEvent) => {
|
||||
const bare = !event.metaKey && !event.ctrlKey && !event.altKey
|
||||
const arrow = bare ? arrowDirection(event.key) : undefined
|
||||
|
||||
if (arrow) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
const distance = event.shiftKey ? 1 : ARROW_PAN
|
||||
|
||||
return ease(
|
||||
panBy(
|
||||
goal(),
|
||||
{ x: arrow.x * distance * viewport.clientWidth, y: arrow.y * distance * viewport.clientHeight },
|
||||
bounds(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
const action = bare ? (event.key === "0" ? "fit" : undefined) : event.altKey ? undefined : zoomShortcut(event.key)
|
||||
|
||||
if (!action) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
|
||||
if (action === "fit") return ease(FIT_VIEW)
|
||||
step(action === "in" ? STEP : 1 / STEP)
|
||||
},
|
||||
{ capture: true },
|
||||
)
|
||||
|
||||
return (
|
||||
<div
|
||||
data-component="diagram-preview"
|
||||
// Zoomed in, the first Escape zooms back out; the dialog stack leaves it to the preview.
|
||||
data-owns-escape={goal().scale > 1 ? "" : undefined}
|
||||
>
|
||||
<Kobalte.Content
|
||||
data-slot="diagram-preview-content"
|
||||
aria-label={i18n.t("ui.diagramPreview.label")}
|
||||
onOpenAutoFocus={(event) => {
|
||||
event.preventDefault()
|
||||
close?.focus()
|
||||
}}
|
||||
onEscapeKeyDown={(event) => {
|
||||
if (goal().scale <= 1) return
|
||||
event.preventDefault()
|
||||
ease(FIT_VIEW)
|
||||
}}
|
||||
onPointerDown={(event: PointerEvent) => {
|
||||
backdrop = event.target === viewport
|
||||
}}
|
||||
onClick={(event: MouseEvent) => {
|
||||
// The preview fills the window, so a click on the backdrop around the diagram lands here.
|
||||
if (!backdrop || panned || event.target !== viewport) return
|
||||
dialog.close()
|
||||
}}
|
||||
>
|
||||
<div
|
||||
ref={viewport}
|
||||
data-slot="diagram-preview-body"
|
||||
data-zoomed={view().scale > 1 ? "" : undefined}
|
||||
data-dragging={drag() ? "" : undefined}
|
||||
onDblClick={detail}
|
||||
onPointerDown={grab}
|
||||
onPointerMove={pan}
|
||||
onPointerUp={release}
|
||||
onPointerCancel={release}
|
||||
>
|
||||
<div ref={canvas} data-slot="diagram-preview-canvas">
|
||||
{props.svg}
|
||||
</div>
|
||||
</div>
|
||||
<div data-slot="diagram-preview-controls">
|
||||
<IconButton
|
||||
data-slot="diagram-preview-zoom-out"
|
||||
icon={<Icon name="minus" />}
|
||||
variant="ghost"
|
||||
aria-label={i18n.t("ui.imagePreview.zoomOut")}
|
||||
onClick={() => step(1 / STEP)}
|
||||
/>
|
||||
<Button
|
||||
data-slot="diagram-preview-zoom-level"
|
||||
variant="ghost-muted"
|
||||
size="small"
|
||||
aria-label={i18n.t("ui.imagePreview.zoomToFit")}
|
||||
title={i18n.t("ui.imagePreview.zoomToFit")}
|
||||
onClick={() => ease(FIT_VIEW)}
|
||||
>
|
||||
{percent().format(view().scale * fitRatio())}
|
||||
</Button>
|
||||
<IconButton
|
||||
data-slot="diagram-preview-zoom-in"
|
||||
icon={<Icon name="plus" />}
|
||||
variant="ghost"
|
||||
aria-label={i18n.t("ui.imagePreview.zoomIn")}
|
||||
onClick={() => step(STEP)}
|
||||
/>
|
||||
<div data-slot="diagram-preview-divider" />
|
||||
<Kobalte.CloseButton
|
||||
ref={close}
|
||||
data-slot="diagram-preview-close"
|
||||
as={IconButton}
|
||||
icon={<Icon name="close" />}
|
||||
variant="ghost"
|
||||
aria-label={i18n.t("ui.common.close")}
|
||||
/>
|
||||
</div>
|
||||
</Kobalte.Content>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Arrow keys move the view over the diagram, so the diagram moves the other way.
|
||||
function arrowDirection(key: string) {
|
||||
if (key === "ArrowLeft") return { x: 1, y: 0 }
|
||||
|
||||
if (key === "ArrowRight") return { x: -1, y: 0 }
|
||||
|
||||
if (key === "ArrowUp") return { x: 0, y: 1 }
|
||||
|
||||
if (key === "ArrowDown") return { x: 0, y: -1 }
|
||||
}
|
||||
@@ -40,8 +40,10 @@ import {
|
||||
maxScale,
|
||||
panBy,
|
||||
viewBox,
|
||||
wheelPixels,
|
||||
wheelZoomFactor,
|
||||
zoomAt,
|
||||
zoomShortcut,
|
||||
type ZoomView,
|
||||
} from "./image-zoom"
|
||||
import {
|
||||
@@ -657,7 +659,7 @@ export function ImagePreview(props: ImagePreviewProps) {
|
||||
const current = view()
|
||||
|
||||
const next = pinch
|
||||
? zoomAt(current, current.scale * wheelZoomFactor(pixels(event, event.deltaY)), point(event), bounds)
|
||||
? zoomAt(current, current.scale * wheelZoomFactor(wheelPixels(event, event.deltaY)), point(event), bounds)
|
||||
: panBy(current, wheelPan(event), bounds)
|
||||
|
||||
follow(next.scale, next.x, next.y)
|
||||
@@ -682,7 +684,7 @@ export function ImagePreview(props: ImagePreviewProps) {
|
||||
return props.video.pause()
|
||||
}
|
||||
|
||||
const action = bare ? (event.key === "0" ? "fit" : undefined) : event.altKey ? undefined : shortcut(event.key)
|
||||
const action = bare ? (event.key === "0" ? "fit" : undefined) : event.altKey ? undefined : zoomShortcut(event.key)
|
||||
|
||||
if (!action) return
|
||||
event.preventDefault()
|
||||
@@ -895,28 +897,12 @@ function layout(element: HTMLElement, frame: Box, radius: number) {
|
||||
element.style.borderRadius = `${radius}px`
|
||||
}
|
||||
|
||||
function shortcut(key: string) {
|
||||
if (key === "=" || key === "+") return "in"
|
||||
|
||||
if (key === "-" || key === "_") return "out"
|
||||
|
||||
if (key === "0") return "fit"
|
||||
}
|
||||
|
||||
// A plain wheel pans; Shift turns a vertical wheel sideways.
|
||||
function wheelPan(event: WheelEvent) {
|
||||
const horizontal = event.shiftKey && event.deltaX === 0
|
||||
|
||||
return {
|
||||
x: -pixels(event, horizontal ? event.deltaY : event.deltaX),
|
||||
y: horizontal ? 0 : -pixels(event, event.deltaY),
|
||||
x: -wheelPixels(event, horizontal ? event.deltaY : event.deltaX),
|
||||
y: horizontal ? 0 : -wheelPixels(event, event.deltaY),
|
||||
}
|
||||
}
|
||||
|
||||
function pixels(event: WheelEvent, delta: number) {
|
||||
if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) return delta * 16
|
||||
|
||||
if (event.deltaMode === WheelEvent.DOM_DELTA_PAGE) return delta * window.innerHeight
|
||||
|
||||
return delta
|
||||
}
|
||||
|
||||
@@ -85,6 +85,24 @@ export function wheelZoomFactor(deltaY: number) {
|
||||
return Math.exp(-clamp(deltaY, -30, 30) / 100)
|
||||
}
|
||||
|
||||
/** The zoom a Cmd/Ctrl shortcut asks for, from the key it is pressed with. */
|
||||
export function zoomShortcut(key: string) {
|
||||
if (key === "=" || key === "+") return "in"
|
||||
|
||||
if (key === "-" || key === "_") return "out"
|
||||
|
||||
if (key === "0") return "fit"
|
||||
}
|
||||
|
||||
/** A wheel event's delta in pixels, whether it counts in pixels, lines or pages. */
|
||||
export function wheelPixels(event: WheelEvent, delta: number) {
|
||||
if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) return delta * 16
|
||||
|
||||
if (event.deltaMode === WheelEvent.DOM_DELTA_PAGE) return delta * window.innerHeight
|
||||
|
||||
return delta
|
||||
}
|
||||
|
||||
/** Keeps one axis of a zoomed image of `size` covering a `viewport` it overflows, and centered in one it fits. */
|
||||
export function clampAxis(offset: number, size: number, viewport: number) {
|
||||
const limit = Math.max(0, (size - viewport) / 2)
|
||||
|
||||
@@ -252,6 +252,8 @@ const source = {
|
||||
"ui.imagePreview.zoomIn": "Zoom in",
|
||||
"ui.imagePreview.zoomOut": "Zoom out",
|
||||
"ui.imagePreview.zoomToFit": "Zoom to fit",
|
||||
"ui.diagramPreview.label": "Diagram",
|
||||
"ui.diagramPreview.open": "Maximize diagram",
|
||||
"ui.scrollView.ariaLabel": "scrollable content",
|
||||
|
||||
"ui.tool.read": "Read",
|
||||
|
||||
@@ -262,6 +262,10 @@ const icons = {
|
||||
viewBox: "0 0 16 16",
|
||||
body: `<path d="M2 8.5V2H14V14H8M5 5.66667H10.3333V11M3.66797 12.333L9.94292 6.05806" stroke="currentColor" stroke-linecap="square"/>`,
|
||||
},
|
||||
"outline-maximize": {
|
||||
viewBox: "0 0 16 16",
|
||||
body: `<path d="M2.5 6V2.5H6M10 2.5H13.5V6M13.5 10V13.5H10M6 13.5H2.5V10" stroke="currentColor" stroke-linecap="square"/>`,
|
||||
},
|
||||
"outline-hexagonal-warning": {
|
||||
viewBox: "0 0 16 16",
|
||||
body: `<path d="M10.6667 1.33325H5.33272L1.33334 5.33325L1.33342 10.6917L5.3327 14.691L10.6667 14.6909L14.6911 10.6917V5.33255L10.6667 1.33325Z" stroke="currentColor"/><path d="M8 10.6667H8.00667" stroke="currentColor" stroke-linecap="square"/><path d="M8 7.99992V5.33325" stroke="currentColor" stroke-linecap="square"/>`,
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
@import "../components/hover-card.css" layer(components);
|
||||
@import "../components/provider-icon.css" layer(components);
|
||||
@import "../components/dock-surface.css" layer(components);
|
||||
@import "../components/diagram-preview.css" layer(components);
|
||||
@import "../components/image-preview.css" layer(components);
|
||||
@import "../forms/inline-input/inline-input.css" layer(components);
|
||||
@import "../components/text-field.css" layer(components);
|
||||
|
||||
Reference in New Issue
Block a user