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 // Bind event handlers for proper addition and removal
78 this.boundMouseMoveHandler = this.handleMouseMove.bind(this);
79 this.boundMouseUpHandler = this.handleMouseUp.bind(this);
80 this.boundToggleInteraction = this.toggleInteraction.bind(this);
81 this.boundCopyCode = this.copyCode.bind(this);
82 this.boundZoomIn = this.handleZoomClick.bind(this, 1);
83 this.boundZoomOut = this.handleZoomClick.bind(this, -1);
84 this.boundResetZoom = this.resetZoom.bind(this);
85 this.boundHandleWheel = this.handleWheel.bind(this);
86 this.boundHandleMouseDown = this.handleMouseDown.bind(this);
87 this.boundPreventDefault = e => e.preventDefault();
88 this.boundPreventSelect = e => { if (this.isDragging || this.interactionEnabled) e.preventDefault(); };
91 this.setupEventListeners();
95 * Creates the DOM structure for the viewer programmatically.
96 * This is safer and more maintainable than using innerHTML with a large template string.
99 const createButton = (title, iconClass, ...extraClasses) => {
100 const button = document.createElement('div');
101 button.className = `${CSS_CLASSES.BUTTON_BASE} ${extraClasses.join(' ')}`;
102 button.title = title;
103 const icon = document.createElement('i');
104 icon.className = iconClass;
105 icon.setAttribute('aria-hidden', 'true');
110 const controls = document.createElement('div');
111 controls.className = CSS_CLASSES.CONTROLS;
112 this.toggleInteractionBtn = createButton('Toggle interaction', CSS_CLASSES.LOCK_ICON, 'mermaid-btn', 'toggle-interaction');
113 this.copyCodeBtn = createButton('Copy code', 'fa fa-copy', 'mermaid-btn');
114 controls.append(this.toggleInteractionBtn, this.copyCodeBtn);
116 const zoomControls = document.createElement('div');
117 zoomControls.className = CSS_CLASSES.ZOOM_CONTROLS;
118 this.zoomInBtn = createButton('Zoom in', 'fa fa-search-plus', 'mermaid-zoom-btn', 'zoom-in');
119 this.zoomOutBtn = createButton('Zoom out', 'fa fa-search-minus', 'mermaid-zoom-btn', 'zoom-out');
120 this.zoomResetBtn = createButton('Reset', 'fa fa-refresh', 'mermaid-zoom-btn', 'zoom-reset');
121 zoomControls.append(this.zoomInBtn, this.zoomOutBtn, this.zoomResetBtn);
123 this.diagram = document.createElement('div');
124 this.diagram.className = CSS_CLASSES.DIAGRAM;
125 // Use textContent for security, preventing any potential HTML injection.
126 // Mermaid will parse the text content safely.
127 this.diagram.textContent = this.mermaidCode;
129 this.content = document.createElement('div');
130 this.content.className = CSS_CLASSES.CONTENT;
131 this.content.append(this.diagram);
133 this.viewport = document.createElement('div');
134 this.viewport.className = CSS_CLASSES.VIEWPORT;
135 this.viewport.append(this.content);
137 // Clear the container and append the new structure
138 this.container.innerHTML = '';
139 this.container.append(controls, zoomControls, this.viewport);
141 // Function to render the diagram and perform post-render setup
142 const renderAndSetup = () => {
143 mermaid.run({ nodes: [this.diagram] }).then(() => {
144 this.adjustContainerHeight();
145 this.calculateInitialOffset();
146 this.centerDiagram();
148 console.error("Mermaid rendering error for diagram:", this.mermaidCode, error);
149 this.diagram.innerHTML = `<p style="color: red; padding: 10px;">Error rendering diagram. Check console.</p>`;
153 // Check if Font Awesome is loaded before rendering
154 // This checks for the 'Font Awesome 6 Free' font family, which is common.
155 // Adjust if your Font Awesome version uses a different family name for its core icons.
156 if (document.fonts && typeof document.fonts.check === 'function' && document.fonts.check('1em "Font Awesome 6 Free"')) { // Check if Font Awesome is immediately available
158 } else if (document.fonts && document.fonts.ready) { // Simplified check for document.fonts.ready
159 document.fonts.ready.then(renderAndSetup).catch(err => {
160 renderAndSetup(); // Proceed with rendering even if font check fails after timeout/error
167 adjustContainerHeight() {
168 const svgElement = this.content.querySelector('svg');
170 // Ensure the viewport takes up the height of the rendered SVG
171 this.viewport.style.height = '100%';
175 calculateInitialOffset() {
176 const originalTransform = this.content.style.transform;
177 this.content.style.transform = '';
178 const contentRect = this.content.getBoundingClientRect();
179 const viewportRect = this.viewport.getBoundingClientRect();
180 this.initialContentOffset.x = contentRect.left - viewportRect.left;
181 this.initialContentOffset.y = contentRect.top - viewportRect.top;
182 this.content.style.transform = originalTransform;
185 _getViewportCenterClientCoords() {
186 const viewportRect = this.viewport.getBoundingClientRect();
188 clientX: viewportRect.left + viewportRect.width / 2,
189 clientY: viewportRect.top + viewportRect.height / 2,
193 setupEventListeners() {
194 this.toggleInteractionBtn.addEventListener('click', this.boundToggleInteraction);
195 this.copyCodeBtn.addEventListener('click', this.boundCopyCode);
196 this.zoomInBtn.addEventListener('click', this.boundZoomIn);
197 this.zoomOutBtn.addEventListener('click', this.boundZoomOut);
198 this.zoomResetBtn.addEventListener('click', this.boundResetZoom);
200 this.viewport.addEventListener('wheel', this.boundHandleWheel, { passive: false });
201 this.viewport.addEventListener('mousedown', this.boundHandleMouseDown);
203 // Listen on document for mousemove to handle dragging outside viewport
204 document.addEventListener('mousemove', this.boundMouseMoveHandler);
205 // Listen on window for mouseup to ensure drag ends even if mouse is released outside
206 window.addEventListener('mouseup', this.boundMouseUpHandler, true); // Use capture phase
208 this.viewport.addEventListener('contextmenu', this.boundPreventDefault);
209 this.viewport.addEventListener('selectstart', this.boundPreventSelect);
212 toggleInteraction() {
213 this.interactionEnabled = !this.interactionEnabled;
214 const icon = this.toggleInteractionBtn.querySelector('i');
215 this.toggleInteractionBtn.setAttribute('aria-pressed', this.interactionEnabled.toString());
217 if (this.interactionEnabled) {
218 icon.className = CSS_CLASSES.UNLOCK_ICON;
219 this.toggleInteractionBtn.title = 'Disable manual interaction';
220 this.viewport.classList.add(CSS_CLASSES.INTERACTION_ENABLED);
221 this.viewport.classList.add(CSS_CLASSES.INTERACTIVE_HOVER); // Set grab cursor state
222 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_PAN); // Ensure pan cursor state is off
224 icon.className = CSS_CLASSES.LOCK_ICON;
225 this.toggleInteractionBtn.title = 'Enable manual interaction';
226 this.viewport.classList.remove(CSS_CLASSES.INTERACTION_ENABLED);
227 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_HOVER);
228 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_PAN);
229 this.isDragging = false; // Ensure dragging stops if interaction is disabled mid-drag
230 this.dragStarted = false;
231 this.viewport.classList.remove(CSS_CLASSES.DRAGGING);
236 this.content.style.transform = `translate(${this.translateX}px, ${this.translateY}px) scale(${this.scale})`;
239 handleZoomClick(direction) {
240 const { clientX, clientY } = this._getViewportCenterClientCoords();
241 this.zoom(direction, clientX, clientY);
245 if (!this.interactionEnabled) return;
246 // Prevent default browser scroll/zoom behavior when wheeling over the diagram
248 this.content.classList.add(CSS_CLASSES.ZOOMING);
249 const clientX = e.clientX;
250 const clientY = e.clientY;
251 if (e.deltaY > 0) this.zoom(-1, clientX, clientY);
252 else this.zoom(1, clientX, clientY);
253 setTimeout(() => this.content.classList.remove(CSS_CLASSES.ZOOMING), ZOOM_ANIMATION_CLASS_TIMEOUT_MS);
257 if (!this.interactionEnabled || e.button !== 0) return;
259 this.isDragging = true;
260 this.dragStarted = false;
261 this.startX = e.clientX;
262 this.startY = e.clientY;
263 this.dragBaseTranslateX = this.translateX;
264 this.dragBaseTranslateY = this.translateY;
265 this.viewport.classList.add(CSS_CLASSES.DRAGGING);
266 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_HOVER);
267 this.viewport.classList.add(CSS_CLASSES.INTERACTIVE_PAN);
268 this.content.classList.remove(CSS_CLASSES.ZOOMING);
272 if (!this.isDragging) return;
273 // e.preventDefault() is called only after dragStarted is true to allow clicks if threshold isn't met.
274 const deltaX = e.clientX - this.startX;
275 const deltaY = e.clientY - this.startY;
276 if (!this.dragStarted && (Math.abs(deltaX) > DRAG_THRESHOLD_PIXELS || Math.abs(deltaY) > DRAG_THRESHOLD_PIXELS)) {
277 this.dragStarted = true;
279 if (this.dragStarted) {
280 e.preventDefault(); // Prevent text selection, etc., only when drag has truly started
281 this.translateX = this.dragBaseTranslateX + deltaX;
282 this.translateY = this.dragBaseTranslateY + deltaY;
283 this.updateTransform();
288 if (this.isDragging) {
289 this.isDragging = false;
290 this.dragStarted = false;
291 this.viewport.classList.remove(CSS_CLASSES.DRAGGING);
292 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_PAN);
293 if (this.interactionEnabled) { // Revert to grab cursor if interaction is still enabled
294 this.viewport.classList.add(CSS_CLASSES.INTERACTIVE_HOVER);
297 this.content.style.transform = `translate(${this.translateX}px, ${this.translateY}px) scale(${this.scale})`;
301 const svgElement = this.content.querySelector('svg');
303 const viewportRect = this.viewport.getBoundingClientRect();
304 const svgIntrinsicWidth = svgElement.viewBox.baseVal.width || svgElement.clientWidth;
305 const svgIntrinsicHeight = svgElement.viewBox.baseVal.height || svgElement.clientHeight;
307 const targetContentLeftRelativeToViewport = (viewportRect.width - (svgIntrinsicWidth * this.scale)) / 2;
308 const targetContentTopRelativeToViewport = (viewportRect.height - (svgIntrinsicHeight * this.scale)) / 2;
310 this.translateX = targetContentLeftRelativeToViewport - this.initialContentOffset.x;
311 this.translateY = targetContentTopRelativeToViewport - this.initialContentOffset.y;
313 // Initial centering constraints; may need adjustment for very large diagrams.
314 this.translateX = Math.max(0, this.translateX);
315 this.translateY = Math.max(0, this.translateY);
317 this.updateTransform();
321 zoom(direction, clientX, clientY) {
322 this.content.classList.add(CSS_CLASSES.ZOOMING);
323 const oldScale = this.scale;
324 let newZoomIndex = this.currentZoomIndex + direction;
326 if (newZoomIndex >= 0 && newZoomIndex < this.zoomLevels.length) {
327 this.currentZoomIndex = newZoomIndex;
328 const newScale = this.zoomLevels[this.currentZoomIndex];
330 const viewportRect = this.viewport.getBoundingClientRect();
331 const pointXInContent = (clientX - viewportRect.left - this.translateX) / oldScale;
332 const pointYInContent = (clientY - viewportRect.top - this.translateY) / oldScale;
334 this.translateX = (clientX - viewportRect.left) - (pointXInContent * newScale);
335 this.translateY = (clientY - viewportRect.top) - (pointYInContent * newScale);
336 this.scale = newScale;
337 this.updateTransform();
339 setTimeout(() => this.content.classList.remove(CSS_CLASSES.ZOOMING), ZOOM_ANIMATION_CLASS_TIMEOUT_MS);
343 this.content.classList.add(CSS_CLASSES.ZOOMING);
344 this.currentZoomIndex = this.zoomLevels.findIndex(level => Math.abs(level - DEFAULT_ZOOM_SCALE) < 1e-9);
345 if (this.currentZoomIndex === -1) { // Fallback if default not exactly in levels
346 this.currentZoomIndex = Math.floor(this.zoomLevels.length / 2);
348 this.scale = this.zoomLevels[this.currentZoomIndex];
349 // Use requestAnimationFrame to ensure layout is stable before centering
350 requestAnimationFrame(() => {
351 this.centerDiagram();
352 setTimeout(() => this.content.classList.remove(CSS_CLASSES.ZOOMING), ZOOM_ANIMATION_CLASS_TIMEOUT_MS);
358 await navigator.clipboard.writeText(this.mermaidCode);
359 this.showNotification('Copied!');
361 // Fallback for older browsers or if clipboard API fails
362 const textArea = document.createElement('textarea');
363 textArea.value = this.mermaidCode;
364 // Style to make it invisible
365 textArea.style.position = 'fixed';
366 textArea.style.top = '-9999px';
367 textArea.style.left = '-9999px';
368 document.body.appendChild(textArea);
371 document.execCommand('copy');
372 this.showNotification('Copied!');
373 } catch (copyError) {
374 console.error('Fallback copy failed:', copyError);
375 this.showNotification('Copy failed.', true); // Error
377 document.body.removeChild(textArea);
381 showNotification(message, isError = false) {
382 if (window.$events) {
383 const eventName = isError ? 'error' : 'success';
384 window.$events.emit(eventName, message);
386 // Fallback for if the event system is not available
387 console.warn('BookStack event system not found, falling back to console log for notification.');
389 console.error(message);
391 console.log(message);
397 // Remove event listeners specific to this instance
398 this.toggleInteractionBtn.removeEventListener('click', this.boundToggleInteraction);
399 this.copyCodeBtn.removeEventListener('click', this.boundCopyCode);
400 this.zoomInBtn.removeEventListener('click', this.boundZoomIn);
401 this.zoomOutBtn.removeEventListener('click', this.boundZoomOut);
402 this.zoomResetBtn.removeEventListener('click', this.boundResetZoom);
404 this.viewport.removeEventListener('wheel', this.boundHandleWheel, { passive: false });
405 this.viewport.removeEventListener('mousedown', this.boundHandleMouseDown);
406 this.viewport.removeEventListener('contextmenu', this.boundPreventDefault);
407 this.viewport.removeEventListener('selectstart', this.boundPreventSelect);
409 document.removeEventListener('mousemove', this.boundMouseMoveHandler);
410 window.removeEventListener('mouseup', this.boundMouseUpHandler, true);
412 this.container.innerHTML = ''; // Clear the container's content
416 const mermaidViewers = [];
417 function initializeMermaidViewers() {
418 // Adjust the selector if your CMS wraps mermaid code blocks differently
419 const codeBlocks = document.querySelectorAll('pre code.language-mermaid');
420 for (const codeBlock of codeBlocks) {
421 // Ensure we don't re-initialize if this script runs multiple times or content is dynamic
422 if (codeBlock.dataset.mermaidViewerInitialized) continue;
424 const mermaidCode = codeBlock.textContent || codeBlock.innerHTML; // textContent is usually better
425 const container = document.createElement('div');
426 container.className = CSS_CLASSES.CONTAINER;
428 const replaceTarget = (codeBlock.nodeName === 'CODE') ? codeBlock.parentElement : codeBlock;
430 // Check if replaceTarget is already a mermaid-container (e.g. from previous init)
431 if (replaceTarget.classList.contains(CSS_CLASSES.CONTAINER)) continue;
433 replaceTarget.after(container);
434 replaceTarget.remove(); // Remove the original <pre> or <pre><code> block
436 const viewer = new InteractiveMermaidViewer(container, mermaidCode);
437 mermaidViewers.push(viewer);
438 codeBlock.dataset.mermaidViewerInitialized = 'true'; // Mark as initialized
442 // Initialize on DOMContentLoaded
443 if (document.readyState === 'loading') {
444 document.addEventListener('DOMContentLoaded', initializeMermaidViewers);
446 // DOMContentLoaded has already fired
447 initializeMermaidViewers();
450 // Re-center diagrams on window load, as images/fonts inside SVG might affect size
451 window.addEventListener('load', () => {
452 mermaidViewers.forEach(viewer => {
453 // Delay slightly to ensure mermaid rendering is fully complete and dimensions are stable
454 setTimeout(() => viewer.centerDiagram(), 100);
458 // Optional: If your CMS dynamically adds content, you might need a way to re-run initialization
459 // For example, using a MutationObserver or a custom event.
460 // document.addEventListener('myCMSContentLoaded', () => initializeMermaidViewers());
464 /* Use BookStack's CSS variables for seamless theme integration */
466 background: var(--color-bg-alt);
467 border: 1px solid #d0d7de;
475 /* This will now be 100% of the dynamically set container height */
477 /* Keep this for panning/zooming when content exceeds viewport */
479 /* Default to normal system cursor */
482 /* Ensure viewport cursor is auto when locked, even if active.
483 The text selection (I-beam) cursor will still appear over selectable text within .mermaid-content. */
484 .mermaid-viewport:not(.interaction-enabled):active {
488 /* Set 'grab' cursor when the viewport has the 'interactive-hover' class. */
489 .mermaid-viewport.interactive-hover {
493 /* Set 'grabbing' cursor when the viewport has the 'interactive-pan' class. */
494 .mermaid-viewport.interactive-pan {
495 cursor: grabbing !important;
499 transform-origin: 0 0;
500 /* Allow text selection by default (when interaction is locked) */
503 will-change: transform;
506 /* Disable text selection ONLY when interaction is enabled on the viewport */
507 .mermaid-viewport.interaction-enabled .mermaid-content {
511 /* SVG elements inherit cursor from the viewport when interaction is enabled. */
512 .mermaid-viewport.interaction-enabled .mermaid-content svg,
513 .mermaid-viewport.interaction-enabled .mermaid-content svg * {
514 cursor: inherit !important;
515 /* Force inheritance from the viewport's cursor */
518 .mermaid-content.zooming {
519 transition: transform 0.2s ease;
531 .mermaid-viewer-button-base {
532 border: 1px solid #d0d7de;
537 justify-content: center;
539 background: var(--color-bg);
542 color: var(--color-text);
545 .mermaid-viewer-button-base:hover {
549 .dark-mode .mermaid-viewer-button-base:hover {
550 background: var(--color-bg-alt);
553 /* Override for pure white icons in dark mode */
554 .dark-mode .mermaid-viewer-button-base {
558 .mermaid-zoom-controls {
563 flex-direction: column;