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.setAttribute('role', 'button');
105 button.setAttribute('tabindex', '0');
106 button.className = `${CSS_CLASSES.BUTTON_BASE} ${extraClasses.join(' ')}`;
107 button.title = title;
108 const icon = document.createElement('i');
109 icon.className = iconClass;
110 icon.setAttribute('aria-hidden', 'true');
115 const controls = document.createElement('div');
116 controls.className = CSS_CLASSES.CONTROLS;
117 this.toggleInteractionBtn = createButton('Toggle interaction', CSS_CLASSES.LOCK_ICON, 'mermaid-btn', 'toggle-interaction');
118 this.copyCodeBtn = createButton('Copy code', 'fa fa-copy', 'mermaid-btn');
119 controls.append(this.toggleInteractionBtn, this.copyCodeBtn);
121 const zoomControls = document.createElement('div');
122 zoomControls.className = CSS_CLASSES.ZOOM_CONTROLS;
123 this.zoomInBtn = createButton('Zoom in', 'fa fa-search-plus', 'mermaid-zoom-btn', 'zoom-in');
124 this.zoomOutBtn = createButton('Zoom out', 'fa fa-search-minus', 'mermaid-zoom-btn', 'zoom-out');
125 this.zoomResetBtn = createButton('Reset', 'fa fa-refresh', 'mermaid-zoom-btn', 'zoom-reset');
126 zoomControls.append(this.zoomInBtn, this.zoomOutBtn, this.zoomResetBtn);
128 this.diagram = document.createElement('div');
129 this.diagram.className = CSS_CLASSES.DIAGRAM;
130 // Use textContent for security, preventing any potential HTML injection.
131 // Mermaid will parse the text content safely.
132 this.diagram.textContent = this.mermaidCode;
134 this.content = document.createElement('div');
135 this.content.className = CSS_CLASSES.CONTENT;
136 this.content.append(this.diagram);
138 this.viewport = document.createElement('div');
139 this.viewport.className = CSS_CLASSES.VIEWPORT;
140 this.viewport.append(this.content);
142 // Clear the container and append the new structure
143 this.container.innerHTML = '';
144 this.container.append(controls, zoomControls, this.viewport);
146 // Function to render the diagram and perform post-render setup
147 const renderAndSetup = () => {
148 mermaid.run({ nodes: [this.diagram] }).then(() => {
149 this.adjustContainerHeight();
150 this.calculateInitialOffset();
151 this.centerDiagram();
153 console.error("Mermaid rendering error for diagram:", this.mermaidCode, error);
154 // Use BookStack's negative color variable and provide a clearer message for debugging.
155 this.diagram.innerHTML = `<p style="color: var(--color-neg); padding: 10px;">Error rendering diagram. Check browser console for details.</p>`;
159 // Check if Font Awesome is loaded before rendering
160 // This checks for the 'Font Awesome 6 Free' font family, which is common.
161 // Adjust if your Font Awesome version uses a different family name for its core icons.
162 if (document.fonts && typeof document.fonts.check === 'function' && document.fonts.check('1em "Font Awesome 6 Free"')) { // Check if Font Awesome is immediately available
164 } else if (document.fonts && document.fonts.ready) { // Simplified check for document.fonts.ready
165 document.fonts.ready.then(renderAndSetup).catch(err => {
166 renderAndSetup(); // Proceed with rendering even if font check fails after timeout/error
173 adjustContainerHeight() {
174 const svgElement = this.content.querySelector('svg');
176 // Ensure the viewport takes up the height of the rendered SVG
177 this.viewport.style.height = '100%';
181 calculateInitialOffset() {
182 const originalTransform = this.content.style.transform;
183 this.content.style.transform = '';
184 const contentRect = this.content.getBoundingClientRect();
185 const viewportRect = this.viewport.getBoundingClientRect();
186 this.initialContentOffset.x = contentRect.left - viewportRect.left;
187 this.initialContentOffset.y = contentRect.top - viewportRect.top;
188 this.content.style.transform = originalTransform;
191 _getViewportCenterClientCoords() {
192 const viewportRect = this.viewport.getBoundingClientRect();
194 clientX: viewportRect.left + viewportRect.width / 2,
195 clientY: viewportRect.top + viewportRect.height / 2,
199 setupEventListeners() {
200 const { signal } = this.abortController;
202 this.toggleInteractionBtn.addEventListener('click', this.boundToggleInteraction, { signal });
203 this.copyCodeBtn.addEventListener('click', this.boundCopyCode, { signal });
204 this.zoomInBtn.addEventListener('click', this.boundZoomIn, { signal });
205 this.zoomOutBtn.addEventListener('click', this.boundZoomOut, { signal });
206 this.zoomResetBtn.addEventListener('click', this.boundResetZoom, { signal });
208 this.viewport.addEventListener('wheel', this.boundHandleWheel, { passive: false, signal });
209 this.viewport.addEventListener('mousedown', this.boundHandleMouseDown, { signal });
211 // Listen on document for mousemove to handle dragging outside viewport
212 document.addEventListener('mousemove', this.boundMouseMoveHandler, { signal });
213 // Listen on window for mouseup to ensure drag ends even if mouse is released outside
214 window.addEventListener('mouseup', this.boundMouseUpHandler, { signal, capture: true });
216 this.viewport.addEventListener('contextmenu', this.boundPreventDefault, { signal });
217 this.viewport.addEventListener('selectstart', this.boundPreventSelect, { signal });
220 toggleInteraction() {
221 this.interactionEnabled = !this.interactionEnabled;
222 const icon = this.toggleInteractionBtn.querySelector('i');
223 this.toggleInteractionBtn.setAttribute('aria-pressed', this.interactionEnabled.toString());
225 if (this.interactionEnabled) {
226 icon.className = CSS_CLASSES.UNLOCK_ICON;
227 this.toggleInteractionBtn.title = 'Disable manual interaction';
228 this.viewport.classList.add(CSS_CLASSES.INTERACTION_ENABLED);
229 this.viewport.classList.add(CSS_CLASSES.INTERACTIVE_HOVER); // Set grab cursor state
230 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_PAN); // Ensure pan cursor state is off
232 icon.className = CSS_CLASSES.LOCK_ICON;
233 this.toggleInteractionBtn.title = 'Enable manual interaction';
234 this.viewport.classList.remove(CSS_CLASSES.INTERACTION_ENABLED);
235 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_HOVER);
236 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_PAN);
237 this.isDragging = false; // Ensure dragging stops if interaction is disabled mid-drag
238 this.dragStarted = false;
239 this.viewport.classList.remove(CSS_CLASSES.DRAGGING);
244 this.content.style.transform = `translate(${this.translateX}px, ${this.translateY}px) scale(${this.scale})`;
247 handleZoomClick(direction) {
248 const { clientX, clientY } = this._getViewportCenterClientCoords();
249 this.zoom(direction, clientX, clientY);
253 if (!this.interactionEnabled) return;
254 // Prevent default browser scroll/zoom behavior when wheeling over the diagram
256 this.content.classList.add(CSS_CLASSES.ZOOMING);
257 const clientX = e.clientX;
258 const clientY = e.clientY;
259 if (e.deltaY > 0) this.zoom(-1, clientX, clientY);
260 else this.zoom(1, clientX, clientY);
261 setTimeout(() => this.content.classList.remove(CSS_CLASSES.ZOOMING), ZOOM_ANIMATION_CLASS_TIMEOUT_MS);
265 if (!this.interactionEnabled || e.button !== 0) return;
267 this.isDragging = true;
268 this.dragStarted = false;
269 this.startX = e.clientX;
270 this.startY = e.clientY;
271 this.dragBaseTranslateX = this.translateX;
272 this.dragBaseTranslateY = this.translateY;
273 this.viewport.classList.add(CSS_CLASSES.DRAGGING);
274 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_HOVER);
275 this.viewport.classList.add(CSS_CLASSES.INTERACTIVE_PAN);
276 this.content.classList.remove(CSS_CLASSES.ZOOMING);
280 if (!this.isDragging) return;
281 // e.preventDefault() is called only after dragStarted is true to allow clicks if threshold isn't met.
282 const deltaX = e.clientX - this.startX;
283 const deltaY = e.clientY - this.startY;
284 if (!this.dragStarted && (Math.abs(deltaX) > DRAG_THRESHOLD_PIXELS || Math.abs(deltaY) > DRAG_THRESHOLD_PIXELS)) {
285 this.dragStarted = true;
287 if (this.dragStarted) {
288 e.preventDefault(); // Prevent text selection, etc., only when drag has truly started
289 this.translateX = this.dragBaseTranslateX + deltaX;
290 this.translateY = this.dragBaseTranslateY + deltaY;
291 this.updateTransform();
296 if (this.isDragging) {
297 this.isDragging = false;
298 this.dragStarted = false;
299 this.viewport.classList.remove(CSS_CLASSES.DRAGGING);
300 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_PAN);
301 if (this.interactionEnabled) { // Revert to grab cursor if interaction is still enabled
302 this.viewport.classList.add(CSS_CLASSES.INTERACTIVE_HOVER);
305 this.content.style.transform = `translate(${this.translateX}px, ${this.translateY}px) scale(${this.scale})`;
309 const svgElement = this.content.querySelector('svg');
311 const viewportRect = this.viewport.getBoundingClientRect();
312 const svgIntrinsicWidth = svgElement.viewBox.baseVal.width || svgElement.clientWidth;
313 const svgIntrinsicHeight = svgElement.viewBox.baseVal.height || svgElement.clientHeight;
315 const targetContentLeftRelativeToViewport = (viewportRect.width - (svgIntrinsicWidth * this.scale)) / 2;
316 const targetContentTopRelativeToViewport = (viewportRect.height - (svgIntrinsicHeight * this.scale)) / 2;
318 this.translateX = targetContentLeftRelativeToViewport - this.initialContentOffset.x;
319 this.translateY = targetContentTopRelativeToViewport - this.initialContentOffset.y;
321 // Initial centering constraints; may need adjustment for very large diagrams.
322 this.translateX = Math.max(0, this.translateX);
323 this.translateY = Math.max(0, this.translateY);
325 this.updateTransform();
329 zoom(direction, clientX, clientY) {
330 this.content.classList.add(CSS_CLASSES.ZOOMING);
331 const oldScale = this.scale;
332 let newZoomIndex = this.currentZoomIndex + direction;
334 if (newZoomIndex >= 0 && newZoomIndex < this.zoomLevels.length) {
335 this.currentZoomIndex = newZoomIndex;
336 const newScale = this.zoomLevels[this.currentZoomIndex];
338 const viewportRect = this.viewport.getBoundingClientRect();
339 const pointXInContent = (clientX - viewportRect.left - this.translateX) / oldScale;
340 const pointYInContent = (clientY - viewportRect.top - this.translateY) / oldScale;
342 this.translateX = (clientX - viewportRect.left) - (pointXInContent * newScale);
343 this.translateY = (clientY - viewportRect.top) - (pointYInContent * newScale);
344 this.scale = newScale;
345 this.updateTransform();
347 setTimeout(() => this.content.classList.remove(CSS_CLASSES.ZOOMING), ZOOM_ANIMATION_CLASS_TIMEOUT_MS);
351 this.content.classList.add(CSS_CLASSES.ZOOMING);
352 this.currentZoomIndex = this.zoomLevels.findIndex(level => Math.abs(level - DEFAULT_ZOOM_SCALE) < 1e-9);
353 if (this.currentZoomIndex === -1) { // Fallback if default not exactly in levels
354 this.currentZoomIndex = Math.floor(this.zoomLevels.length / 2);
356 this.scale = this.zoomLevels[this.currentZoomIndex];
357 // Use requestAnimationFrame to ensure layout is stable before centering
358 requestAnimationFrame(() => {
359 this.centerDiagram();
360 setTimeout(() => this.content.classList.remove(CSS_CLASSES.ZOOMING), ZOOM_ANIMATION_CLASS_TIMEOUT_MS);
366 await navigator.clipboard.writeText(this.mermaidCode);
367 this.showNotification('Copied!');
369 // Fallback for older browsers or if clipboard API fails
370 console.error('Clipboard API copy failed, attempting fallback:', error);
371 const textArea = document.createElement('textarea');
372 textArea.value = this.mermaidCode;
373 // Style to make it invisible
374 textArea.style.position = 'fixed';
375 textArea.style.top = '-9999px';
376 textArea.style.left = '-9999px';
377 document.body.appendChild(textArea);
380 document.execCommand('copy');
381 this.showNotification('Copied!');
382 } catch (copyError) {
383 console.error('Fallback copy failed:', copyError);
384 this.showNotification('Copy failed.', true); // Error
386 document.body.removeChild(textArea);
390 showNotification(message, isError = false) {
391 if (window.$events) {
392 const eventName = isError ? 'error' : 'success';
393 window.$events.emit(eventName, message);
395 // Fallback for if the event system is not available
396 console.warn('BookStack event system not found, falling back to console log for notification.');
398 console.error(message);
400 console.log(message);
406 // Abort all listeners attached with this controller's signal.
407 this.abortController.abort();
408 this.container.innerHTML = ''; // Clear the container's content
412 const mermaidViewers = [];
413 function initializeMermaidViewers() {
414 const codeBlocks = document.querySelectorAll('pre code.language-mermaid');
415 for (const codeBlock of codeBlocks) {
416 // Ensure we don't re-initialize if this script runs multiple times or content is dynamic
417 if (codeBlock.dataset.mermaidViewerInitialized) continue;
419 const mermaidCode = codeBlock.textContent || codeBlock.innerHTML; // textContent is usually better
420 const container = document.createElement('div');
421 container.className = CSS_CLASSES.CONTAINER;
423 const replaceTarget = (codeBlock.nodeName === 'CODE') ? codeBlock.parentElement : codeBlock;
425 // Check if replaceTarget is already a mermaid-container (e.g. from previous init)
426 if (replaceTarget.classList.contains(CSS_CLASSES.CONTAINER)) continue;
428 replaceTarget.after(container);
429 replaceTarget.remove(); // Remove the original <pre> or <pre><code> block
431 const viewer = new InteractiveMermaidViewer(container, mermaidCode);
432 mermaidViewers.push(viewer);
433 codeBlock.dataset.mermaidViewerInitialized = 'true'; // Mark as initialized
437 // Initialize on DOMContentLoaded
438 if (document.readyState === 'loading') {
439 document.addEventListener('DOMContentLoaded', initializeMermaidViewers);
441 // DOMContentLoaded has already fired
442 initializeMermaidViewers();
445 // Re-center diagrams on window load, as images/fonts inside SVG might affect size
446 window.addEventListener('load', () => {
447 mermaidViewers.forEach(viewer => {
448 // Delay slightly to ensure mermaid rendering is fully complete and dimensions are stable
449 setTimeout(() => viewer.centerDiagram(), 100);
455 /* Use BookStack's CSS variables for seamless theme integration */
457 background: var(--color-bg-alt);
458 border: 1px solid #d0d7de;
466 /* This will now be 100% of the dynamically set container height */
468 /* Keep this for panning/zooming when content exceeds viewport */
470 /* Default to normal system cursor */
473 /* Ensure viewport cursor is auto when locked, even if active.
474 The text selection (I-beam) cursor will still appear over selectable text within .mermaid-content. */
475 .mermaid-viewport:not(.interaction-enabled):active {
479 /* Set 'grab' cursor when the viewport has the 'interactive-hover' class. */
480 .mermaid-viewport.interactive-hover {
484 /* Set 'grabbing' cursor when the viewport has the 'interactive-pan' class. */
485 .mermaid-viewport.interactive-pan {
486 cursor: grabbing !important;
490 transform-origin: 0 0;
491 /* Allow text selection by default (when interaction is locked) */
494 will-change: transform;
497 /* Disable text selection ONLY when interaction is enabled on the viewport */
498 .mermaid-viewport.interaction-enabled .mermaid-content {
502 /* SVG elements inherit cursor from the viewport when interaction is enabled. */
503 .mermaid-viewport.interaction-enabled .mermaid-content svg,
504 .mermaid-viewport.interaction-enabled .mermaid-content svg * {
505 cursor: inherit !important;
506 /* Force inheritance from the viewport's cursor */
509 .mermaid-content.zooming {
510 transition: transform 0.2s ease;
522 .mermaid-viewer-button-base {
523 border: 1px solid #C0C0C0;
528 justify-content: center;
532 color: var(--color-text);
533 /* The above color is overridden in dark mode below to ensure visibility */
536 .mermaid-viewer-button-base:hover {
540 .dark-mode .mermaid-viewer-button-base {
542 border: 1px solid #444444;
544 /* Explicitly set to white for dark mode icons */
547 .dark-mode .mermaid-viewer-button-base:hover {
551 .mermaid-zoom-controls {
556 flex-direction: column;