mirror of
https://github.com/sharevb/it-tools.git
synced 2026-11-20 21:23:08 +03:00
feat: mermaid live preview (#548)
This commit is contained in:
1 parent
671e8a11c7
commit
db3a344568
6 files changed
+788
-42
No files matched your search
@@ -2975,6 +2975,16 @@ tools:
|
||||
label-your-mermaid-to-convert: "Your Mermaid to convert:"
|
||||
title-preview: Preview
|
||||
tag-invalid-mermaid-syntax: Invalid Mermaid syntax
|
||||
tag-showing-last-valid-diagram: Showing the last valid diagram
|
||||
tag-hint-ctrl-scroll-to-zoom: Hold Ctrl (or ⌘) and scroll to zoom
|
||||
label-diagram-preview: Diagram preview — drag or use the arrow keys to pan, + and - to zoom
|
||||
label-zoom-level-reset: "Zoom {zoom}%, click to reset to 100%"
|
||||
title-zoom-in: Zoom in
|
||||
title-zoom-out: Zoom out
|
||||
title-reset-zoom: Reset zoom to 100%
|
||||
title-fit-view: Fit diagram to view
|
||||
title-fullscreen: Fullscreen
|
||||
title-exit-fullscreen: Exit fullscreen
|
||||
tag-export-as-png: Export as PNG
|
||||
tag-export-as-jpg: Export as JPG
|
||||
tag-export-as-svg: Export as SVG
|
||||
|
||||
@@ -4563,6 +4563,16 @@ tools:
|
||||
tag-export-as-png: Exporter comme PNG
|
||||
tag-export-as-svg: Exporter comme SVG
|
||||
tag-invalid-mermaid-syntax: Syntaxe de Mermaid non valide
|
||||
tag-showing-last-valid-diagram: Affichage du dernier diagramme valide
|
||||
tag-hint-ctrl-scroll-to-zoom: Maintenez Ctrl (ou ⌘) et faites défiler pour zoomer
|
||||
label-diagram-preview: Prévisualisation du diagramme — faites glisser ou utilisez les flèches pour vous déplacer, + et - pour zoomer
|
||||
label-zoom-level-reset: "Zoom {zoom} %, cliquez pour réinitialiser à 100 %"
|
||||
title-zoom-in: Zoomer
|
||||
title-zoom-out: Dézoomer
|
||||
title-reset-zoom: Réinitialiser le zoom à 100 %
|
||||
title-fit-view: Ajuster le diagramme à la vue
|
||||
title-fullscreen: Plein écran
|
||||
title-exit-fullscreen: Quitter le plein écran
|
||||
title-input-mermaid: Mermaid d'entrée
|
||||
title-preview: Prévisualisation
|
||||
title: Exportateur de Mermaid
|
||||
|
||||
@@ -6,13 +6,45 @@ test.describe('Mermaid Diagram Renderer', () => {
|
||||
});
|
||||
|
||||
test('should render the initial diagram', async ({ page }) => {
|
||||
const diagramContainer = page.locator('.diagram-container svg');
|
||||
const diagramContainer = page.locator('.viewport svg');
|
||||
// mermaid is a large lazy-loaded chunk; cold CI browsers (webkit
|
||||
// especially) can exceed the default 5s expect timeout
|
||||
await expect(diagramContainer).toBeVisible({ timeout: 30_000 });
|
||||
await expect(diagramContainer).toHaveAttribute('xmlns', 'http://www.w3.org/2000/svg');
|
||||
});
|
||||
|
||||
test('should zoom from the toolbar and reset to 100%', async ({ page }) => {
|
||||
await expect(page.locator('.viewport svg')).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// the default diagram is small enough to fit, so it starts at 1:1
|
||||
const zoomLevel = page.getByTestId('zoom-level');
|
||||
await expect(zoomLevel).toHaveText('100%');
|
||||
|
||||
await page.getByTestId('zoom-in').click();
|
||||
await expect(zoomLevel).toHaveText('125%');
|
||||
|
||||
await page.getByTestId('zoom-out').click();
|
||||
await expect(zoomLevel).toHaveText('100%');
|
||||
|
||||
await page.getByTestId('zoom-in').click();
|
||||
await zoomLevel.click();
|
||||
await expect(zoomLevel).toHaveText('100%');
|
||||
});
|
||||
|
||||
test('should pan with the keyboard once the preview is focused', async ({ page }) => {
|
||||
await expect(page.locator('.viewport svg')).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
const canvas = page.locator('.canvas');
|
||||
const before = await canvas.evaluate(el => getComputedStyle(el).transform);
|
||||
|
||||
await page.locator('.viewport').focus();
|
||||
await page.keyboard.press('ArrowRight');
|
||||
|
||||
await expect
|
||||
.poll(async () => canvas.evaluate(el => getComputedStyle(el).transform))
|
||||
.not.toBe(before);
|
||||
});
|
||||
|
||||
test('should update diagram when user edits Mermaid code', async ({ page }) => {
|
||||
const input = page.getByLabel('Your Mermaid to convert:');
|
||||
const updatedMermaid = `
|
||||
@@ -24,7 +56,7 @@ test.describe('Mermaid Diagram Renderer', () => {
|
||||
await input.fill(updatedMermaid);
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
const svg = page.locator('.diagram-container svg');
|
||||
const svg = page.locator('.viewport svg');
|
||||
await expect(svg).toContainText('Start');
|
||||
await expect(svg).toContainText('Success!');
|
||||
});
|
||||
@@ -38,4 +70,18 @@ test.describe('Mermaid Diagram Renderer', () => {
|
||||
await button.click();
|
||||
}
|
||||
});
|
||||
|
||||
test('should keep the last valid diagram but refuse to export it on a syntax error', async ({ page }) => {
|
||||
await expect(page.locator('.viewport svg')).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
await page.getByLabel('Your Mermaid to convert:').fill('graph TD\nA --> not valid {{{');
|
||||
|
||||
// the rendered diagram stays on screen, flagged as out of date
|
||||
await expect(page.locator('.error-overlay')).toBeVisible();
|
||||
await expect(page.locator('.canvas.stale')).toBeVisible();
|
||||
await expect(page.locator('.viewport svg')).toBeVisible();
|
||||
|
||||
// exporting now would hand back a file that does not match the code
|
||||
await expect(page.getByRole('button', { name: /Export as PNG/i })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
centerTransform,
|
||||
clampZoom,
|
||||
exceedsRefitThreshold,
|
||||
fitTransform,
|
||||
wheelZoomFactor,
|
||||
zoomAround,
|
||||
} from './mermaid-exporter.service';
|
||||
|
||||
const MIN = 0.05;
|
||||
const MAX = 10;
|
||||
|
||||
describe('mermaid-exporter service', () => {
|
||||
describe('clampZoom', () => {
|
||||
it('leaves a value inside the range untouched', () => {
|
||||
expect(clampZoom(1.5, MIN, MAX)).toBe(1.5);
|
||||
});
|
||||
|
||||
it('clamps to the bounds', () => {
|
||||
expect(clampZoom(0.001, MIN, MAX)).toBe(MIN);
|
||||
expect(clampZoom(1000, MIN, MAX)).toBe(MAX);
|
||||
});
|
||||
|
||||
it('clamps a non-finite value to the maximum', () => {
|
||||
expect(clampZoom(Number.POSITIVE_INFINITY, MIN, MAX)).toBe(MAX);
|
||||
});
|
||||
});
|
||||
|
||||
describe('zoomAround', () => {
|
||||
it('keeps the anchor point fixed', () => {
|
||||
const before = { zoom: 1, x: 0, y: 0 };
|
||||
const after = zoomAround(before, 2, 100, 50, MIN, MAX);
|
||||
|
||||
// the content point under the anchor must not move: at zoom z the point
|
||||
// is at (anchor - pan) / z in content space
|
||||
expect((100 - before.x) / before.zoom).toBeCloseTo((100 - after.x) / after.zoom, 6);
|
||||
expect((50 - before.y) / before.zoom).toBeCloseTo((50 - after.y) / after.zoom, 6);
|
||||
expect(after.zoom).toBe(2);
|
||||
});
|
||||
|
||||
it('does not drift the view once the zoom is clamped', () => {
|
||||
const atMax = { zoom: MAX, x: -120, y: -80 };
|
||||
expect(zoomAround(atMax, 4, 200, 100, MIN, MAX)).toEqual(atMax);
|
||||
|
||||
const atMin = { zoom: MIN, x: 10, y: 20 };
|
||||
expect(zoomAround(atMin, 0.1, 200, 100, MIN, MAX)).toEqual(atMin);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fitTransform', () => {
|
||||
it('scales a large diagram down and centres it', () => {
|
||||
const view = fitTransform({ width: 500, height: 400 }, { width: 4000, height: 2000 }, 20, MIN, MAX);
|
||||
|
||||
// width is the binding constraint: (500 - 20) / 4000
|
||||
expect(view.zoom).toBeCloseTo(0.12, 6);
|
||||
expect(view.x).toBeCloseTo((500 - 4000 * 0.12) / 2, 6);
|
||||
expect(view.y).toBeCloseTo((400 - 2000 * 0.12) / 2, 6);
|
||||
});
|
||||
|
||||
it('never scales a small diagram above 1:1', () => {
|
||||
const view = fitTransform({ width: 800, height: 600 }, { width: 100, height: 50 }, 20, MIN, MAX);
|
||||
|
||||
expect(view.zoom).toBe(1);
|
||||
expect(view.x).toBe(350);
|
||||
expect(view.y).toBe(275);
|
||||
});
|
||||
|
||||
it('honours the minimum zoom for a diagram that cannot fit', () => {
|
||||
const view = fitTransform({ width: 200, height: 200 }, { width: 100000, height: 100 }, 20, MIN, MAX);
|
||||
|
||||
expect(view.zoom).toBe(MIN);
|
||||
});
|
||||
});
|
||||
|
||||
describe('centerTransform', () => {
|
||||
it('centres the scaled content', () => {
|
||||
expect(centerTransform({ width: 600, height: 400 }, { width: 200, height: 100 }, 2)).toEqual({
|
||||
zoom: 2,
|
||||
x: 100,
|
||||
y: 100,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('wheelZoomFactor', () => {
|
||||
it('zooms in on a negative delta and out on a positive one', () => {
|
||||
expect(wheelZoomFactor(-100, 0, 0.0015)).toBeGreaterThan(1);
|
||||
expect(wheelZoomFactor(100, 0, 0.0015)).toBeLessThan(1);
|
||||
});
|
||||
|
||||
it('gives a line-mode notch the same weight as a pixel-mode one', () => {
|
||||
// Firefox reports ~3 lines where Chrome reports ~100 pixels
|
||||
const chrome = wheelZoomFactor(-100, 0, 0.0015);
|
||||
const firefox = wheelZoomFactor(-3, 1, 0.0015);
|
||||
|
||||
expect(firefox).toBeCloseTo(chrome, 1);
|
||||
expect(firefox).toBeGreaterThan(1.1);
|
||||
});
|
||||
|
||||
it('scales page-mode deltas up as well', () => {
|
||||
expect(wheelZoomFactor(-1, 2, 0.0015)).toBeGreaterThan(wheelZoomFactor(-1, 0, 0.0015));
|
||||
});
|
||||
});
|
||||
|
||||
describe('exceedsRefitThreshold', () => {
|
||||
it('ignores a change under the threshold', () => {
|
||||
expect(exceedsRefitThreshold({ width: 1000, height: 500 }, { width: 1010, height: 505 }, 0.02)).toBe(false);
|
||||
});
|
||||
|
||||
it('reports a change over the threshold in either dimension', () => {
|
||||
expect(exceedsRefitThreshold({ width: 1000, height: 500 }, { width: 1100, height: 500 }, 0.02)).toBe(true);
|
||||
expect(exceedsRefitThreshold({ width: 1000, height: 500 }, { width: 1000, height: 600 }, 0.02)).toBe(true);
|
||||
});
|
||||
|
||||
it('treats the first render, measured against a zero size, as a change', () => {
|
||||
expect(exceedsRefitThreshold({ width: 0, height: 0 }, { width: 300, height: 200 }, 0.02)).toBe(true);
|
||||
});
|
||||
|
||||
it('accumulates: small edits measured against the fitted size eventually refit', () => {
|
||||
const fitted = { width: 1000, height: 500 };
|
||||
// ten 1.5% edits never trip the threshold against the previous render,
|
||||
// but together they are 15% away from the size the view was fitted to
|
||||
expect(exceedsRefitThreshold(fitted, { width: 1150, height: 500 }, 0.02)).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
export interface ViewTransform { zoom: number; x: number; y: number }
|
||||
export interface Size { width: number; height: number }
|
||||
|
||||
/**
|
||||
* Keeps a zoom factor inside the supported range.
|
||||
*/
|
||||
export function clampZoom(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Zooms by `factor` while keeping the content point under (originX, originY) —
|
||||
* viewport coordinates, typically the cursor — anchored in place.
|
||||
*/
|
||||
export function zoomAround(
|
||||
view: ViewTransform,
|
||||
factor: number,
|
||||
originX: number,
|
||||
originY: number,
|
||||
min: number,
|
||||
max: number,
|
||||
): ViewTransform {
|
||||
const zoom = clampZoom(view.zoom * factor, min, max);
|
||||
const ratio = zoom / view.zoom;
|
||||
|
||||
return {
|
||||
zoom,
|
||||
x: originX - (originX - view.x) * ratio,
|
||||
y: originY - (originY - view.y) * ratio,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Scales the content down to fit entirely inside the viewport (never up past
|
||||
* 1:1) and centres it, leaving `padding` pixels of margin.
|
||||
*/
|
||||
export function fitTransform(viewport: Size, content: Size, padding: number, min: number, max: number): ViewTransform {
|
||||
const zoom = clampZoom(
|
||||
Math.min(
|
||||
(viewport.width - padding) / content.width,
|
||||
(viewport.height - padding) / content.height,
|
||||
1,
|
||||
),
|
||||
min,
|
||||
max,
|
||||
);
|
||||
|
||||
return centerTransform(viewport, content, zoom);
|
||||
}
|
||||
|
||||
/**
|
||||
* Centres the content in the viewport at the given zoom.
|
||||
*/
|
||||
export function centerTransform(viewport: Size, content: Size, zoom: number): ViewTransform {
|
||||
return {
|
||||
zoom,
|
||||
x: (viewport.width - content.width * zoom) / 2,
|
||||
y: (viewport.height - content.height * zoom) / 2,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a wheel event delta into a zoom factor. `deltaY` is normalised
|
||||
* because browsers report wheel notches in different units — Firefox in lines,
|
||||
* Chrome in pixels — which would otherwise make one of them barely zoom.
|
||||
*/
|
||||
export function wheelZoomFactor(deltaY: number, deltaMode: number, sensitivity: number): number {
|
||||
const LINE_HEIGHT = 33;
|
||||
const PAGE_HEIGHT = 400;
|
||||
const unit = deltaMode === 1 ? LINE_HEIGHT : deltaMode === 2 ? PAGE_HEIGHT : 1;
|
||||
|
||||
return Math.exp(-deltaY * unit * sensitivity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a newly rendered diagram differs enough from the one the view was
|
||||
* last fitted to that the view should be re-fitted. Comparing against the
|
||||
* fitted size rather than the previous render keeps a series of small edits
|
||||
* from drifting the diagram out of frame without ever crossing the threshold.
|
||||
*/
|
||||
export function exceedsRefitThreshold(fitted: Size, rendered: Size, ratio: number): boolean {
|
||||
const changed = (from: number, to: number) => Math.abs(to - from) / (from || 1) > ratio;
|
||||
|
||||
return changed(fitted.width, rendered.width) || changed(fitted.height, rendered.height);
|
||||
}
|
||||
@@ -1,11 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { nextTick, onMounted, ref, watch } from 'vue';
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { refAutoReset, useFullscreen, useResizeObserver, watchDebounced } from '@vueuse/core';
|
||||
import { useThemeVars } from 'naive-ui';
|
||||
import mermaid from 'mermaid';
|
||||
import type { ViewTransform } from './mermaid-exporter.service';
|
||||
import {
|
||||
centerTransform,
|
||||
exceedsRefitThreshold,
|
||||
fitTransform,
|
||||
wheelZoomFactor,
|
||||
zoomAround,
|
||||
} from './mermaid-exporter.service';
|
||||
import { useStyleStore } from '@/stores/style.store';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
mermaid.initialize({ startOnLoad: false });
|
||||
const themeVars = useThemeVars();
|
||||
const styleStore = useStyleStore();
|
||||
|
||||
const mermaidCode = ref<string>(`graph TD
|
||||
A[Start] --> B{Is it working?}
|
||||
@@ -14,32 +25,312 @@ B -- No --> D[Fix it!]
|
||||
`);
|
||||
|
||||
const mermaidContainer = ref<HTMLElement | null>(null);
|
||||
const viewport = ref<HTMLElement | null>(null);
|
||||
const previewWrapper = ref<HTMLElement | null>(null);
|
||||
|
||||
async function renderMermaid(): Promise<void> {
|
||||
if (mermaidContainer.value) {
|
||||
mermaidContainer.value.innerHTML = '';
|
||||
try {
|
||||
mermaid.parse(mermaidCode.value);
|
||||
const { svg } = await mermaid.render('graphDiv', mermaidCode.value);
|
||||
mermaidContainer.value.innerHTML = svg;
|
||||
}
|
||||
catch (error: unknown) {
|
||||
mermaidContainer.value.innerHTML = `<p class="error">${t('tools.mermaid-exporter.texts.tag-invalid-mermaid-syntax')}</p>`;
|
||||
console.error('Mermaid error:', error);
|
||||
}
|
||||
const { isFullscreen, isSupported: isFullscreenSupported, toggle: toggleFullscreen } = useFullscreen(previewWrapper);
|
||||
|
||||
const MIN_ZOOM = 0.05;
|
||||
const MAX_ZOOM = 10;
|
||||
const ZOOM_STEP = 1.25;
|
||||
const WHEEL_SENSITIVITY = 0.0015;
|
||||
// macOS trackpad pinch arrives as a ctrl+wheel event with much smaller deltas
|
||||
const PINCH_SENSITIVITY = 0.01;
|
||||
const FIT_PADDING = 20;
|
||||
const KEYBOARD_PAN_STEP = 40;
|
||||
const KEYBOARD_PAN_FAST_MULTIPLIER = 4;
|
||||
// PointerEvent.buttons bit for the primary (left) button
|
||||
const PRIMARY_BUTTON = 1;
|
||||
const RENDER_DEBOUNCE_MS = 300;
|
||||
const HINT_DURATION_MS = 2000;
|
||||
// how far the rendered diagram must differ from the one the view was fitted to
|
||||
// before it is re-fitted: a low bar while the view is still the automatic one, a
|
||||
// much higher one once the user has zoomed in deliberately, so that only a
|
||||
// wholesale change of diagram pulls them out of the region they are reading
|
||||
const REFIT_RATIO_FITTED = 0.02;
|
||||
const REFIT_RATIO_ADJUSTED = 0.5;
|
||||
|
||||
const zoom = ref(1);
|
||||
const pan = reactive({ x: 0, y: 0 });
|
||||
const contentSize = reactive({ width: 0, height: 0 });
|
||||
const isDragging = ref(false);
|
||||
const renderError = ref(false);
|
||||
// shown for a moment when a plain wheel scroll was let through to the page,
|
||||
// so that "the wheel does not zoom" does not read as a broken preview
|
||||
const showWheelHint = refAutoReset(false, HINT_DURATION_MS);
|
||||
|
||||
// view and drag state that nothing renders from, so plain variables
|
||||
let viewIsFitted = true;
|
||||
let fittedSize = { width: 0, height: 0 };
|
||||
let lastPointerX = 0;
|
||||
let lastPointerY = 0;
|
||||
let activePointerId: number | null = null;
|
||||
let renderSeq = 0;
|
||||
|
||||
const hasDiagram = computed(() => contentSize.width > 0);
|
||||
const canZoomIn = computed(() => hasDiagram.value && zoom.value < MAX_ZOOM);
|
||||
const canZoomOut = computed(() => hasDiagram.value && zoom.value > MIN_ZOOM);
|
||||
const canExport = computed(() => hasDiagram.value && !renderError.value);
|
||||
|
||||
const canvasStyle = computed(() => ({
|
||||
transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom.value})`,
|
||||
}));
|
||||
|
||||
function applyView({ zoom: newZoom, x, y }: ViewTransform): void {
|
||||
zoom.value = newZoom;
|
||||
pan.x = x;
|
||||
pan.y = y;
|
||||
}
|
||||
|
||||
function zoomAt(factor: number, originX: number, originY: number): void {
|
||||
applyView(zoomAround({ zoom: zoom.value, ...pan }, factor, originX, originY, MIN_ZOOM, MAX_ZOOM));
|
||||
viewIsFitted = false;
|
||||
}
|
||||
|
||||
function zoomAtCenter(factor: number): void {
|
||||
const vp = viewport.value;
|
||||
if (!vp) {
|
||||
return;
|
||||
}
|
||||
zoomAt(factor, vp.clientWidth / 2, vp.clientHeight / 2);
|
||||
}
|
||||
|
||||
function fitView(): void {
|
||||
const vp = viewport.value;
|
||||
if (!vp || !contentSize.width || !contentSize.height) {
|
||||
return;
|
||||
}
|
||||
const viewportSize = { width: vp.clientWidth, height: vp.clientHeight };
|
||||
applyView(fitTransform(viewportSize, contentSize, FIT_PADDING, MIN_ZOOM, MAX_ZOOM));
|
||||
viewIsFitted = true;
|
||||
fittedSize = { ...contentSize };
|
||||
}
|
||||
|
||||
function resetZoom(): void {
|
||||
const vp = viewport.value;
|
||||
if (!vp) {
|
||||
return;
|
||||
}
|
||||
applyView(centerTransform({ width: vp.clientWidth, height: vp.clientHeight }, contentSize, 1));
|
||||
viewIsFitted = false;
|
||||
}
|
||||
|
||||
function onWheel(event: WheelEvent): void {
|
||||
const vp = viewport.value;
|
||||
if (!vp) {
|
||||
return;
|
||||
}
|
||||
// a trackpad pinch reaches us as ctrl+wheel; in fullscreen there is no page
|
||||
// left to scroll, so the wheel can own the zoom there
|
||||
const isZoomGesture = event.ctrlKey || event.metaKey || isFullscreen.value;
|
||||
if (!isZoomGesture) {
|
||||
showWheelHint.value = true;
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
const rect = vp.getBoundingClientRect();
|
||||
const sensitivity = event.ctrlKey ? PINCH_SENSITIVITY : WHEEL_SENSITIVITY;
|
||||
const factor = wheelZoomFactor(event.deltaY, event.deltaMode, sensitivity);
|
||||
zoomAt(factor, event.clientX - rect.left, event.clientY - rect.top);
|
||||
}
|
||||
|
||||
function onPointerDown(event: PointerEvent): void {
|
||||
if (event.button !== 0) {
|
||||
return;
|
||||
}
|
||||
// a single pointer pans, extra fingers are ignored — but a new primary press
|
||||
// always takes over, so a drag whose pointerup never arrived cannot wedge the
|
||||
// canvas into following the cursor forever
|
||||
if (activePointerId !== null && event.isPrimary === false) {
|
||||
return;
|
||||
}
|
||||
activePointerId = event.pointerId;
|
||||
isDragging.value = true;
|
||||
lastPointerX = event.clientX;
|
||||
lastPointerY = event.clientY;
|
||||
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
|
||||
}
|
||||
|
||||
function onPointerMove(event: PointerEvent): void {
|
||||
if (event.pointerId !== activePointerId) {
|
||||
return;
|
||||
}
|
||||
// a mouse drag whose pointerup never arrived (released outside the window, or
|
||||
// interrupted by the OS) reports no button held: stop panning instead of
|
||||
// sticking to the cursor
|
||||
if (event.pointerType === 'mouse' && event.buttons === 0) {
|
||||
onPointerUp(event);
|
||||
return;
|
||||
}
|
||||
pan.x += event.clientX - lastPointerX;
|
||||
pan.y += event.clientY - lastPointerY;
|
||||
lastPointerX = event.clientX;
|
||||
lastPointerY = event.clientY;
|
||||
viewIsFitted = false;
|
||||
}
|
||||
|
||||
function onPointerUp(event: PointerEvent): void {
|
||||
if (event.pointerId !== activePointerId) {
|
||||
return;
|
||||
}
|
||||
// the pan ends when the primary button is released, not merely when an event
|
||||
// arrives: a right-click mid-drag makes Chrome drop the pointer capture, and
|
||||
// that must not strand the user holding a button that no longer pans
|
||||
const primaryStillHeld = (event.buttons & PRIMARY_BUTTON) === PRIMARY_BUTTON;
|
||||
if (primaryStillHeld) {
|
||||
return;
|
||||
}
|
||||
activePointerId = null;
|
||||
isDragging.value = false;
|
||||
}
|
||||
|
||||
// the viewport is focusable, so panning and zooming stay available without a
|
||||
// mouse: the pointer handlers above are the only other way to reach a region
|
||||
// that the fitted view clips
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
const step = event.shiftKey ? KEYBOARD_PAN_STEP * KEYBOARD_PAN_FAST_MULTIPLIER : KEYBOARD_PAN_STEP;
|
||||
switch (event.key) {
|
||||
case 'ArrowLeft':
|
||||
pan.x += step;
|
||||
break;
|
||||
case 'ArrowRight':
|
||||
pan.x -= step;
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
pan.y += step;
|
||||
break;
|
||||
case 'ArrowDown':
|
||||
pan.y -= step;
|
||||
break;
|
||||
case '+':
|
||||
case '=':
|
||||
zoomAtCenter(ZOOM_STEP);
|
||||
break;
|
||||
case '-':
|
||||
zoomAtCenter(1 / ZOOM_STEP);
|
||||
break;
|
||||
case '0':
|
||||
resetZoom();
|
||||
break;
|
||||
case 'f':
|
||||
fitView();
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
if (event.key.startsWith('Arrow')) {
|
||||
viewIsFitted = false;
|
||||
}
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sizes the freshly injected SVG and re-fits the view if the diagram changed
|
||||
* enough to warrant it. Kept out of the mermaid try/catch below so a failure to
|
||||
* measure is never reported as a syntax error.
|
||||
*/
|
||||
function measureAndFit(svgElement: SVGSVGElement): void {
|
||||
svgElement.style.maxWidth = 'none';
|
||||
const viewBox = svgElement.viewBox.baseVal;
|
||||
const hasViewBox = Boolean(viewBox?.width && viewBox?.height);
|
||||
// diagrams without a viewBox (e.g. `info`) may not start at the origin, so
|
||||
// the measured box has to become the viewBox or the content gets clipped
|
||||
const box = hasViewBox ? viewBox : svgElement.getBBox();
|
||||
if (!hasViewBox) {
|
||||
svgElement.setAttribute('viewBox', `${box.x} ${box.y} ${box.width} ${box.height}`);
|
||||
}
|
||||
svgElement.setAttribute('width', String(box.width));
|
||||
svgElement.setAttribute('height', String(box.height));
|
||||
|
||||
const rendered = { width: box.width, height: box.height };
|
||||
const ratio = viewIsFitted ? REFIT_RATIO_FITTED : REFIT_RATIO_ADJUSTED;
|
||||
const shouldRefit = exceedsRefitThreshold(fittedSize, rendered, ratio);
|
||||
Object.assign(contentSize, rendered);
|
||||
|
||||
if (shouldRefit) {
|
||||
fitView();
|
||||
}
|
||||
}
|
||||
|
||||
watch(mermaidCode, () => {
|
||||
nextTick(() => {
|
||||
renderMermaid();
|
||||
});
|
||||
});
|
||||
async function renderMermaid(): Promise<void> {
|
||||
const container = mermaidContainer.value;
|
||||
if (!container) {
|
||||
return;
|
||||
}
|
||||
// parse and render are async (mermaid lazy-loads diagram chunks): tag each
|
||||
// invocation so a stale result cannot overwrite the state of a newer one, and
|
||||
// snapshot the code so render cannot receive text that parse never validated
|
||||
const seq = ++renderSeq;
|
||||
const code = mermaidCode.value;
|
||||
try {
|
||||
await mermaid.parse(code);
|
||||
if (seq !== renderSeq) {
|
||||
return;
|
||||
}
|
||||
const { svg } = await mermaid.render('graphDiv', code);
|
||||
if (seq !== renderSeq) {
|
||||
return;
|
||||
}
|
||||
renderError.value = false;
|
||||
container.innerHTML = svg;
|
||||
}
|
||||
catch (error: unknown) {
|
||||
if (seq !== renderSeq) {
|
||||
return;
|
||||
}
|
||||
// keep the last-good diagram and the user's zoom/pan: the error is
|
||||
// shown as an overlay instead of replacing the rendered SVG
|
||||
renderError.value = true;
|
||||
console.error('Mermaid error:', error);
|
||||
return;
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
const svgElement = container.querySelector('svg');
|
||||
if (svgElement) {
|
||||
measureAndFit(svgElement);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mermaid renders with its light palette by default, which would leave a white
|
||||
* diagram inside dark chrome.
|
||||
*/
|
||||
function initMermaid(isDark: boolean): void {
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
// without this, a diagram that fails to render leaves its error SVG behind
|
||||
// in document.body instead of cleaning up before throwing
|
||||
suppressErrorRendering: true,
|
||||
theme: isDark ? 'dark' : 'default',
|
||||
});
|
||||
}
|
||||
|
||||
initMermaid(styleStore.isDarkTheme);
|
||||
|
||||
watch(() => styleStore.isDarkTheme, (isDark) => {
|
||||
initMermaid(isDark);
|
||||
renderMermaid();
|
||||
});
|
||||
|
||||
watchDebounced(mermaidCode, () => renderMermaid(), { debounce: RENDER_DEBOUNCE_MS });
|
||||
|
||||
// entering or leaving fullscreen is an explicit "show me the diagram" action,
|
||||
// so let the resize observer below refit once the new geometry has settled
|
||||
watch(isFullscreen, () => {
|
||||
viewIsFitted = true;
|
||||
});
|
||||
|
||||
// follow the viewport geometry (fullscreen transitions, window resizes) only
|
||||
// while the view is still the fitted one the tool chose by itself
|
||||
useResizeObserver(viewport, () => {
|
||||
if (viewIsFitted) {
|
||||
fitView();
|
||||
}
|
||||
});
|
||||
|
||||
onMounted(renderMermaid);
|
||||
|
||||
function fixSvgSize(svg: string): string {
|
||||
const match = svg.match(/viewBox="([\d\s.-]+)"/);
|
||||
if (!match) {
|
||||
@@ -64,7 +355,9 @@ function fixSvgSize(svg: string): string {
|
||||
|
||||
function exportAs(format: 'svg' | 'png' | 'jpg'): void {
|
||||
const container = mermaidContainer.value;
|
||||
if (!container) {
|
||||
// the preview keeps the last valid diagram on a syntax error: exporting it
|
||||
// would hand back a file that does not match the code on screen
|
||||
if (!container || !canExport.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -143,19 +436,99 @@ function exportAs(format: 'svg' | 'png' | 'jpg'): void {
|
||||
</c-card>
|
||||
|
||||
<c-card :title="t('tools.mermaid-exporter.texts.title-preview')" mb-2 flex-1>
|
||||
<div flex justify-center class="diagram-container">
|
||||
<div ref="mermaidContainer" />
|
||||
<div ref="previewWrapper" class="preview-wrapper" :class="{ fullscreen: isFullscreen }">
|
||||
<div class="toolbar">
|
||||
<c-button
|
||||
circle variant="text" size="small"
|
||||
data-test-id="zoom-out"
|
||||
:disabled="!canZoomOut"
|
||||
:aria-disabled="!canZoomOut"
|
||||
:title="t('tools.mermaid-exporter.texts.title-zoom-out')"
|
||||
@click="zoomAtCenter(1 / ZOOM_STEP)"
|
||||
>
|
||||
<icon-mdi-magnify-minus-outline />
|
||||
</c-button>
|
||||
<c-button
|
||||
variant="text" size="small"
|
||||
class="zoom-level"
|
||||
data-test-id="zoom-level"
|
||||
:disabled="!hasDiagram"
|
||||
:aria-disabled="!hasDiagram"
|
||||
:title="t('tools.mermaid-exporter.texts.title-reset-zoom')"
|
||||
:aria-label="t('tools.mermaid-exporter.texts.label-zoom-level-reset', { zoom: Math.round(zoom * 100) })"
|
||||
@click="resetZoom"
|
||||
>
|
||||
{{ Math.round(zoom * 100) }}%
|
||||
</c-button>
|
||||
<c-button
|
||||
circle variant="text" size="small"
|
||||
data-test-id="zoom-in"
|
||||
:disabled="!canZoomIn"
|
||||
:aria-disabled="!canZoomIn"
|
||||
:title="t('tools.mermaid-exporter.texts.title-zoom-in')"
|
||||
@click="zoomAtCenter(ZOOM_STEP)"
|
||||
>
|
||||
<icon-mdi-magnify-plus-outline />
|
||||
</c-button>
|
||||
<c-button
|
||||
circle variant="text" size="small"
|
||||
data-test-id="fit-view"
|
||||
:disabled="!hasDiagram"
|
||||
:aria-disabled="!hasDiagram"
|
||||
:title="t('tools.mermaid-exporter.texts.title-fit-view')"
|
||||
@click="fitView"
|
||||
>
|
||||
<icon-mdi-fit-to-screen-outline />
|
||||
</c-button>
|
||||
<c-button
|
||||
v-if="isFullscreenSupported"
|
||||
circle variant="text" size="small"
|
||||
data-test-id="toggle-fullscreen"
|
||||
:title="isFullscreen
|
||||
? t('tools.mermaid-exporter.texts.title-exit-fullscreen')
|
||||
: t('tools.mermaid-exporter.texts.title-fullscreen')"
|
||||
@click="toggleFullscreen"
|
||||
>
|
||||
<icon-mdi-fullscreen-exit v-if="isFullscreen" />
|
||||
<icon-mdi-fullscreen v-else />
|
||||
</c-button>
|
||||
</div>
|
||||
<div
|
||||
ref="viewport"
|
||||
class="viewport"
|
||||
:class="{ dragging: isDragging }"
|
||||
tabindex="0"
|
||||
role="group"
|
||||
:aria-label="t('tools.mermaid-exporter.texts.label-diagram-preview')"
|
||||
@wheel="onWheel"
|
||||
@pointerdown="onPointerDown"
|
||||
@pointermove="onPointerMove"
|
||||
@pointerup="onPointerUp"
|
||||
@pointercancel="onPointerUp"
|
||||
@lostpointercapture="onPointerUp"
|
||||
@keydown="onKeydown"
|
||||
@dblclick="fitView"
|
||||
>
|
||||
<div ref="mermaidContainer" class="canvas" :class="{ stale: renderError }" :style="canvasStyle" />
|
||||
</div>
|
||||
<div v-if="renderError" class="error-overlay" role="alert">
|
||||
<strong>{{ t('tools.mermaid-exporter.texts.tag-invalid-mermaid-syntax') }}</strong>
|
||||
<span>{{ t('tools.mermaid-exporter.texts.tag-showing-last-valid-diagram') }}</span>
|
||||
</div>
|
||||
<div v-else-if="showWheelHint" class="wheel-hint">
|
||||
{{ t('tools.mermaid-exporter.texts.tag-hint-ctrl-scroll-to-zoom') }}
|
||||
</div>
|
||||
</div>
|
||||
</c-card>
|
||||
</div>
|
||||
<div flex justify-center class="buttons">
|
||||
<n-button @click="exportAs('png')">
|
||||
<n-button :disabled="!canExport" @click="exportAs('png')">
|
||||
{{ t('tools.mermaid-exporter.texts.tag-export-as-png') }}
|
||||
</n-button>
|
||||
<n-button @click="exportAs('jpg')">
|
||||
<n-button :disabled="!canExport" @click="exportAs('jpg')">
|
||||
{{ t('tools.mermaid-exporter.texts.tag-export-as-jpg') }}
|
||||
</n-button>
|
||||
<n-button @click="exportAs('svg')">
|
||||
<n-button :disabled="!canExport" @click="exportAs('svg')">
|
||||
{{ t('tools.mermaid-exporter.texts.tag-export-as-svg') }}
|
||||
</n-button>
|
||||
</div>
|
||||
@@ -163,23 +536,118 @@ function exportAs(format: 'svg' | 'png' | 'jpg'): void {
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.diagram-container {
|
||||
border: 1px solid var(--theme-default-color);
|
||||
padding: 15px;
|
||||
border-radius: 6px;
|
||||
background-color: var(--theme-default-color);
|
||||
overflow-x: auto;
|
||||
margin-bottom: 20px;
|
||||
.preview-wrapper {
|
||||
position: relative;
|
||||
border: 1px solid v-bind('themeVars.borderColor');
|
||||
border-radius: 6px;
|
||||
// a recessed surface inside the card, so the floating toolbar and overlays
|
||||
// keep their cardColor and read as raised above it
|
||||
background-color: v-bind('themeVars.bodyColor');
|
||||
margin-bottom: 20px;
|
||||
|
||||
.error {
|
||||
color: var(--theme-error-color);
|
||||
font-weight: bold;
|
||||
&.fullscreen {
|
||||
margin-bottom: 0;
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
|
||||
.viewport {
|
||||
height: 100vh;
|
||||
// no page left to scroll: the preview can own every gesture
|
||||
touch-action: none;
|
||||
}
|
||||
}
|
||||
|
||||
.buttons {
|
||||
.toolbar {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 2px 6px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid v-bind('themeVars.borderColor');
|
||||
background-color: v-bind('themeVars.cardColor');
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.15);
|
||||
|
||||
.zoom-level {
|
||||
min-width: 42px;
|
||||
padding: 0 4px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
}
|
||||
|
||||
.error-overlay,
|
||||
.wheel-hint {
|
||||
position: absolute;
|
||||
bottom: 8px;
|
||||
left: 8px;
|
||||
z-index: 10;
|
||||
padding: 4px 10px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid v-bind('themeVars.borderColor');
|
||||
background-color: v-bind('themeVars.cardColor');
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.error-overlay {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
color: v-bind('themeVars.errorColor');
|
||||
|
||||
span {
|
||||
opacity: 0.75;
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.wheel-hint {
|
||||
font-size: 12px;
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
.viewport {
|
||||
position: relative;
|
||||
height: 450px;
|
||||
overflow: hidden;
|
||||
cursor: grab;
|
||||
// a vertical swipe still scrolls the page and pinch still zooms the page:
|
||||
// owning every touch gesture would trap the reader on the stacked layout
|
||||
touch-action: pan-y pinch-zoom;
|
||||
// dragging to pan must not sweep a native text selection across labels
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid v-bind('themeVars.primaryColor');
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
&.dragging {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
// position absolute so the untransformed content size does not blow up
|
||||
// the flex layout (CSS transform only affects painting, not layout)
|
||||
.canvas {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: max-content;
|
||||
transform-origin: 0 0;
|
||||
|
||||
// the diagram on screen no longer matches the code being edited
|
||||
&.stale {
|
||||
opacity: 0.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.buttons {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
</style>
|
||||
Reference in new issue
Block a user