1 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css"
2 integrity="sha512-Evv84Mr4kqVGRNSgIGL/F/aIDqQb7xQ2vcrdIwxfjThSH8CSR7PBEakCr51Ck+w+/U6swU2Im1vVX0SVk9ABhg=="
3 crossorigin="anonymous" referrerpolicy="no-referrer" />
5 <script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/11.7.0/mermaid.min.js"
6 integrity="sha512-ecc+vlmmc1f51s2l/AeIC552wULnv9Q8bYJ4FbODxsL6jGrFoLaKnGkN5JUZNH6LBjkAYy9Q4fKqyTuFUIvvFA=="
7 crossorigin="anonymous" referrerpolicy="no-referrer"></script>
9 // Detect if BookStack's dark mode is enabled
10 const isDarkMode = document.documentElement.classList.contains('dark-mode');
12 // Initialize Mermaid.js, dynamically setting the theme based on BookStack's mode
15 securityLevel: 'loose',
16 theme: isDarkMode ? 'dark' : 'default'
19 // Zoom Level Configuration
20 const ZOOM_LEVEL_MIN = 0.5;
21 const ZOOM_LEVEL_MAX = 2.0;
22 const ZOOM_LEVEL_INCREMENT = 0.1;
23 const DEFAULT_ZOOM_SCALE = 1.0;
25 const DRAG_THRESHOLD_PIXELS = 3;
26 const ZOOM_ANIMATION_CLASS_TIMEOUT_MS = 200;
29 CONTAINER: 'mermaid-container',
30 VIEWPORT: 'mermaid-viewport',
31 CONTENT: 'mermaid-content',
32 DIAGRAM: 'mermaid-diagram',
33 CONTROLS: 'mermaid-controls',
34 ZOOM_CONTROLS: 'mermaid-zoom-controls',
35 INTERACTION_ENABLED: 'interaction-enabled',
38 LOCK_ICON: 'fa fa-lock',
39 UNLOCK_ICON: 'fa fa-unlock',
40 INTERACTIVE_HOVER: 'interactive-hover', // Class for 'grab' cursor state
41 INTERACTIVE_PAN: 'interactive-pan', // Class for 'grabbing' cursor state
42 BUTTON_BASE: 'mermaid-viewer-button-base' // Base class for all viewer buttons
45 class InteractiveMermaidViewer {
46 constructor(container, mermaidCode) {
47 this.container = container;
48 this.mermaidCode = mermaidCode;
52 this.isDragging = false;
53 this.dragStarted = false;
57 const numDecimalPlaces = (ZOOM_LEVEL_INCREMENT.toString().split('.')[1] || '').length;
58 this.zoomLevels = Array.from(
59 { length: Math.round((ZOOM_LEVEL_MAX - ZOOM_LEVEL_MIN) / ZOOM_LEVEL_INCREMENT) + 1 },
60 (_, i) => parseFloat((ZOOM_LEVEL_MIN + i * ZOOM_LEVEL_INCREMENT).toFixed(numDecimalPlaces))
63 this.currentZoomIndex = this.zoomLevels.findIndex(level => Math.abs(level - DEFAULT_ZOOM_SCALE) < 1e-9);
64 if (this.currentZoomIndex === -1) {
65 this.currentZoomIndex = Math.floor(this.zoomLevels.length / 2);
67 this.interactionEnabled = false;
68 this.initialContentOffset = { x: 0, y: 0 };
71 this.toggleInteractionBtn = null;
72 this.copyCodeBtn = null;
73 this.zoomInBtn = null;
74 this.zoomOutBtn = null;
75 this.zoomResetBtn = null;
77 // Use an AbortController for robust event listener cleanup.
78 this.abortController = new AbortController();
80 // Bind event handlers for proper addition and removal
81 this.boundMouseMoveHandler = this.handleMouseMove.bind(this);
82 this.boundMouseUpHandler = this.handleMouseUp.bind(this);
83 this.boundToggleInteraction = this.toggleInteraction.bind(this);
84 this.boundCopyCode = this.copyCode.bind(this);
85 this.boundZoomIn = this.handleZoomClick.bind(this, 1);
86 this.boundZoomOut = this.handleZoomClick.bind(this, -1);
87 this.boundResetZoom = this.resetZoom.bind(this);
88 this.boundHandleWheel = this.handleWheel.bind(this);
89 this.boundHandleMouseDown = this.handleMouseDown.bind(this);
90 this.boundPreventDefault = e => e.preventDefault();
91 this.boundPreventSelect = e => { if (this.isDragging || this.interactionEnabled) e.preventDefault(); };
94 this.setupEventListeners();
98 * Creates the DOM structure for the viewer programmatically.
99 * This is safer and more maintainable than using innerHTML with a large template string.
102 const createButton = (title, iconClass, ...extraClasses) => {
103 const button = document.createElement('div');
104 button.className = `${CSS_CLASSES.BUTTON_BASE} ${extraClasses.join(' ')}`;
105 button.title = title;
106 const icon = document.createElement('i');
107 icon.className = iconClass;
108 icon.setAttribute('aria-hidden', 'true');
113 const controls = document.createElement('div');
114 controls.className = CSS_CLASSES.CONTROLS;
115 this.toggleInteractionBtn = createButton('Toggle interaction', CSS_CLASSES.LOCK_ICON, 'mermaid-btn', 'toggle-interaction');
116 this.copyCodeBtn = createButton('Copy code', 'fa fa-copy', 'mermaid-btn');
117 controls.append(this.toggleInteractionBtn, this.copyCodeBtn);
119 const zoomControls = document.createElement('div');
120 zoomControls.className = CSS_CLASSES.ZOOM_CONTROLS;
121 this.zoomInBtn = createButton('Zoom in', 'fa fa-search-plus', 'mermaid-zoom-btn', 'zoom-in');
122 this.zoomOutBtn = createButton('Zoom out', 'fa fa-search-minus', 'mermaid-zoom-btn', 'zoom-out');
123 this.zoomResetBtn = createButton('Reset', 'fa fa-refresh', 'mermaid-zoom-btn', 'zoom-reset');
124 zoomControls.append(this.zoomInBtn, this.zoomOutBtn, this.zoomResetBtn);
126 this.diagram = document.createElement('div');
127 this.diagram.className = CSS_CLASSES.DIAGRAM;
128 // Use textContent for security, preventing any potential HTML injection.
129 // Mermaid will parse the text content safely.
130 this.diagram.textContent = this.mermaidCode;
132 this.content = document.createElement('div');
133 this.content.className = CSS_CLASSES.CONTENT;
134 this.content.append(this.diagram);
136 this.viewport = document.createElement('div');
137 this.viewport.className = CSS_CLASSES.VIEWPORT;
138 this.viewport.append(this.content);
140 // Clear the container and append the new structure
141 this.container.innerHTML = '';
142 this.container.append(controls, zoomControls, this.viewport);
144 // Function to render the diagram and perform post-render setup
145 const renderAndSetup = () => {
146 mermaid.run({ nodes: [this.diagram] }).then(() => {
147 this.adjustContainerHeight();
148 this.calculateInitialOffset();
149 this.centerDiagram();
151 console.error("Mermaid rendering error for diagram:", this.mermaidCode, error);
152 // Use BookStack's negative color variable and provide a clearer message for debugging.
153 this.diagram.innerHTML = `<p style="color: var(--color-neg); padding: 10px;">Error rendering diagram. Check browser console for details.</p>`;
157 // Check if Font Awesome is loaded before rendering
158 // This checks for the 'Font Awesome 6 Free' font family, which is common.
159 // Adjust if your Font Awesome version uses a different family name for its core icons.
160 if (document.fonts && typeof document.fonts.check === 'function' && document.fonts.check('1em "Font Awesome 6 Free"')) { // Check if Font Awesome is immediately available
162 } else if (document.fonts && document.fonts.ready) { // Simplified check for document.fonts.ready
163 document.fonts.ready.then(renderAndSetup).catch(err => {
164 renderAndSetup(); // Proceed with rendering even if font check fails after timeout/error
171 adjustContainerHeight() {
172 const svgElement = this.content.querySelector('svg');
174 // Ensure the viewport takes up the height of the rendered SVG
175 this.viewport.style.height = '100%';
179 calculateInitialOffset() {
180 const originalTransform = this.content.style.transform;
181 this.content.style.transform = '';
182 const contentRect = this.content.getBoundingClientRect();
183 const viewportRect = this.viewport.getBoundingClientRect();
184 this.initialContentOffset.x = contentRect.left - viewportRect.left;
185 this.initialContentOffset.y = contentRect.top - viewportRect.top;
186 this.content.style.transform = originalTransform;
189 _getViewportCenterClientCoords() {
190 const viewportRect = this.viewport.getBoundingClientRect();
192 clientX: viewportRect.left + viewportRect.width / 2,
193 clientY: viewportRect.top + viewportRect.height / 2,
197 setupEventListeners() {
198 const { signal } = this.abortController;
200 this.toggleInteractionBtn.addEventListener('click', this.boundToggleInteraction, { signal });
201 this.copyCodeBtn.addEventListener('click', this.boundCopyCode, { signal });
202 this.zoomInBtn.addEventListener('click', this.boundZoomIn, { signal });
203 this.zoomOutBtn.addEventListener('click', this.boundZoomOut, { signal });
204 this.zoomResetBtn.addEventListener('click', this.boundResetZoom, { signal });
206 this.viewport.addEventListener('wheel', this.boundHandleWheel, { passive: false, signal });
207 this.viewport.addEventListener('mousedown', this.boundHandleMouseDown, { signal });
209 // Listen on document for mousemove to handle dragging outside viewport
210 document.addEventListener('mousemove', this.boundMouseMoveHandler, { signal });
211 // Listen on window for mouseup to ensure drag ends even if mouse is released outside
212 window.addEventListener('mouseup', this.boundMouseUpHandler, { signal, capture: true });
214 this.viewport.addEventListener('contextmenu', this.boundPreventDefault, { signal });
215 this.viewport.addEventListener('selectstart', this.boundPreventSelect, { signal });
218 toggleInteraction() {
219 this.interactionEnabled = !this.interactionEnabled;
220 const icon = this.toggleInteractionBtn.querySelector('i');
221 this.toggleInteractionBtn.setAttribute('aria-pressed', this.interactionEnabled.toString());
223 if (this.interactionEnabled) {
224 icon.className = CSS_CLASSES.UNLOCK_ICON;
225 this.toggleInteractionBtn.title = 'Disable manual interaction';
226 this.viewport.classList.add(CSS_CLASSES.INTERACTION_ENABLED);
227 this.viewport.classList.add(CSS_CLASSES.INTERACTIVE_HOVER); // Set grab cursor state
228 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_PAN); // Ensure pan cursor state is off
230 icon.className = CSS_CLASSES.LOCK_ICON;
231 this.toggleInteractionBtn.title = 'Enable manual interaction';
232 this.viewport.classList.remove(CSS_CLASSES.INTERACTION_ENABLED);
233 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_HOVER);
234 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_PAN);
235 this.isDragging = false; // Ensure dragging stops if interaction is disabled mid-drag
236 this.dragStarted = false;
237 this.viewport.classList.remove(CSS_CLASSES.DRAGGING);
242 this.content.style.transform = `translate(${this.translateX}px, ${this.translateY}px) scale(${this.scale})`;
245 handleZoomClick(direction) {
246 const { clientX, clientY } = this._getViewportCenterClientCoords();
247 this.zoom(direction, clientX, clientY);
251 if (!this.interactionEnabled) return;
252 // Prevent default browser scroll/zoom behavior when wheeling over the diagram
254 this.content.classList.add(CSS_CLASSES.ZOOMING);
255 const clientX = e.clientX;
256 const clientY = e.clientY;
257 if (e.deltaY > 0) this.zoom(-1, clientX, clientY);
258 else this.zoom(1, clientX, clientY);
259 setTimeout(() => this.content.classList.remove(CSS_CLASSES.ZOOMING), ZOOM_ANIMATION_CLASS_TIMEOUT_MS);
263 if (!this.interactionEnabled || e.button !== 0) return;
265 this.isDragging = true;
266 this.dragStarted = false;
267 this.startX = e.clientX;
268 this.startY = e.clientY;
269 this.dragBaseTranslateX = this.translateX;
270 this.dragBaseTranslateY = this.translateY;
271 this.viewport.classList.add(CSS_CLASSES.DRAGGING);
272 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_HOVER);
273 this.viewport.classList.add(CSS_CLASSES.INTERACTIVE_PAN);
274 this.content.classList.remove(CSS_CLASSES.ZOOMING);
278 if (!this.isDragging) return;
279 // e.preventDefault() is called only after dragStarted is true to allow clicks if threshold isn't met.
280 const deltaX = e.clientX - this.startX;
281 const deltaY = e.clientY - this.startY;
282 if (!this.dragStarted && (Math.abs(deltaX) > DRAG_THRESHOLD_PIXELS || Math.abs(deltaY) > DRAG_THRESHOLD_PIXELS)) {
283 this.dragStarted = true;
285 if (this.dragStarted) {
286 e.preventDefault(); // Prevent text selection, etc., only when drag has truly started
287 this.translateX = this.dragBaseTranslateX + deltaX;
288 this.translateY = this.dragBaseTranslateY + deltaY;
289 this.updateTransform();
294 if (this.isDragging) {
295 this.isDragging = false;
296 this.dragStarted = false;
297 this.viewport.classList.remove(CSS_CLASSES.DRAGGING);
298 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_PAN);
299 if (this.interactionEnabled) { // Revert to grab cursor if interaction is still enabled
300 this.viewport.classList.add(CSS_CLASSES.INTERACTIVE_HOVER);
303 this.content.style.transform = `translate(${this.translateX}px, ${this.translateY}px) scale(${this.scale})`;
307 const svgElement = this.content.querySelector('svg');
309 const viewportRect = this.viewport.getBoundingClientRect();
310 const svgIntrinsicWidth = svgElement.viewBox.baseVal.width || svgElement.clientWidth;
311 const svgIntrinsicHeight = svgElement.viewBox.baseVal.height || svgElement.clientHeight;
313 const targetContentLeftRelativeToViewport = (viewportRect.width - (svgIntrinsicWidth * this.scale)) / 2;
314 const targetContentTopRelativeToViewport = (viewportRect.height - (svgIntrinsicHeight * this.scale)) / 2;
316 this.translateX = targetContentLeftRelativeToViewport - this.initialContentOffset.x;
317 this.translateY = targetContentTopRelativeToViewport - this.initialContentOffset.y;
319 // Initial centering constraints; may need adjustment for very large diagrams.
320 this.translateX = Math.max(0, this.translateX);
321 this.translateY = Math.max(0, this.translateY);
323 this.updateTransform();
327 zoom(direction, clientX, clientY) {
328 this.content.classList.add(CSS_CLASSES.ZOOMING);
329 const oldScale = this.scale;
330 let newZoomIndex = this.currentZoomIndex + direction;
332 if (newZoomIndex >= 0 && newZoomIndex < this.zoomLevels.length) {
333 this.currentZoomIndex = newZoomIndex;
334 const newScale = this.zoomLevels[this.currentZoomIndex];
336 const viewportRect = this.viewport.getBoundingClientRect();
337 const pointXInContent = (clientX - viewportRect.left - this.translateX) / oldScale;
338 const pointYInContent = (clientY - viewportRect.top - this.translateY) / oldScale;
340 this.translateX = (clientX - viewportRect.left) - (pointXInContent * newScale);
341 this.translateY = (clientY - viewportRect.top) - (pointYInContent * newScale);
342 this.scale = newScale;
343 this.updateTransform();
345 setTimeout(() => this.content.classList.remove(CSS_CLASSES.ZOOMING), ZOOM_ANIMATION_CLASS_TIMEOUT_MS);
349 this.content.classList.add(CSS_CLASSES.ZOOMING);
350 this.currentZoomIndex = this.zoomLevels.findIndex(level => Math.abs(level - DEFAULT_ZOOM_SCALE) < 1e-9);
351 if (this.currentZoomIndex === -1) { // Fallback if default not exactly in levels
352 this.currentZoomIndex = Math.floor(this.zoomLevels.length / 2);
354 this.scale = this.zoomLevels[this.currentZoomIndex];
355 // Use requestAnimationFrame to ensure layout is stable before centering
356 requestAnimationFrame(() => {
357 this.centerDiagram();
358 setTimeout(() => this.content.classList.remove(CSS_CLASSES.ZOOMING), ZOOM_ANIMATION_CLASS_TIMEOUT_MS);
364 await navigator.clipboard.writeText(this.mermaidCode);
365 this.showNotification('Copied!');
367 // Fallback for older browsers or if clipboard API fails
368 const textArea = document.createElement('textarea');
369 textArea.value = this.mermaidCode;
370 // Style to make it invisible
371 textArea.style.position = 'fixed';
372 textArea.style.top = '-9999px';
373 textArea.style.left = '-9999px';
374 document.body.appendChild(textArea);
377 document.execCommand('copy');
378 this.showNotification('Copied!');
379 } catch (copyError) {
380 console.error('Fallback copy failed:', copyError);
381 this.showNotification('Copy failed.', true); // Error
383 document.body.removeChild(textArea);
387 showNotification(message, isError = false) {
388 if (window.$events) {
389 const eventName = isError ? 'error' : 'success';
390 window.$events.emit(eventName, message);
392 // Fallback for if the event system is not available
393 console.warn('BookStack event system not found, falling back to console log for notification.');
395 console.error(message);
397 console.log(message);
403 // Abort all listeners attached with this controller's signal.
404 this.abortController.abort();
405 this.container.innerHTML = ''; // Clear the container's content
409 const mermaidViewers = [];
410 function initializeMermaidViewers() {
411 const codeBlocks = document.querySelectorAll('pre code.language-mermaid');
412 for (const codeBlock of codeBlocks) {
413 // Ensure we don't re-initialize if this script runs multiple times or content is dynamic
414 if (codeBlock.dataset.mermaidViewerInitialized) continue;
416 const mermaidCode = codeBlock.textContent || codeBlock.innerHTML; // textContent is usually better
417 const container = document.createElement('div');
418 container.className = CSS_CLASSES.CONTAINER;
420 const replaceTarget = (codeBlock.nodeName === 'CODE') ? codeBlock.parentElement : codeBlock;
422 // Check if replaceTarget is already a mermaid-container (e.g. from previous init)
423 if (replaceTarget.classList.contains(CSS_CLASSES.CONTAINER)) continue;
425 replaceTarget.after(container);
426 replaceTarget.remove(); // Remove the original <pre> or <pre><code> block
428 const viewer = new InteractiveMermaidViewer(container, mermaidCode);
429 mermaidViewers.push(viewer);
430 codeBlock.dataset.mermaidViewerInitialized = 'true'; // Mark as initialized
434 // Initialize on DOMContentLoaded
435 if (document.readyState === 'loading') {
436 document.addEventListener('DOMContentLoaded', initializeMermaidViewers);
438 // DOMContentLoaded has already fired
439 initializeMermaidViewers();
442 // Re-center diagrams on window load, as images/fonts inside SVG might affect size
443 window.addEventListener('load', () => {
444 mermaidViewers.forEach(viewer => {
445 // Delay slightly to ensure mermaid rendering is fully complete and dimensions are stable
446 setTimeout(() => viewer.centerDiagram(), 100);
452 /* Use BookStack's CSS variables for seamless theme integration */
454 background: var(--color-bg-alt);
455 border: 1px solid #d0d7de;
463 /* This will now be 100% of the dynamically set container height */
465 /* Keep this for panning/zooming when content exceeds viewport */
467 /* Default to normal system cursor */
470 /* Ensure viewport cursor is auto when locked, even if active.
471 The text selection (I-beam) cursor will still appear over selectable text within .mermaid-content. */
472 .mermaid-viewport:not(.interaction-enabled):active {
476 /* Set 'grab' cursor when the viewport has the 'interactive-hover' class. */
477 .mermaid-viewport.interactive-hover {
481 /* Set 'grabbing' cursor when the viewport has the 'interactive-pan' class. */
482 .mermaid-viewport.interactive-pan {
483 cursor: grabbing !important;
487 transform-origin: 0 0;
488 /* Allow text selection by default (when interaction is locked) */
491 will-change: transform;
494 /* Disable text selection ONLY when interaction is enabled on the viewport */
495 .mermaid-viewport.interaction-enabled .mermaid-content {
499 /* SVG elements inherit cursor from the viewport when interaction is enabled. */
500 .mermaid-viewport.interaction-enabled .mermaid-content svg,
501 .mermaid-viewport.interaction-enabled .mermaid-content svg * {
502 cursor: inherit !important;
503 /* Force inheritance from the viewport's cursor */
506 .mermaid-content.zooming {
507 transition: transform 0.2s ease;
519 .mermaid-viewer-button-base {
520 border: 1px solid #d0d7de;
525 justify-content: center;
527 background: var(--color-bg);
530 color: var(--color-text);
533 .mermaid-viewer-button-base:hover {
537 .dark-mode .mermaid-viewer-button-base:hover {
538 background: var(--color-bg-alt);
541 /* Override for pure white icons in dark mode */
542 .dark-mode .mermaid-viewer-button-base {
546 .mermaid-zoom-controls {
551 flex-direction: column;