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" />
4 <script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
6 // Detect if BookStack's dark mode is enabled
7 const isDarkMode = document.documentElement.classList.contains('dark-mode');
9 // Initialize Mermaid.js, dynamically setting the theme based on BookStack's mode
12 securityLevel: 'loose',
13 theme: isDarkMode ? 'dark' : 'default'
16 // Zoom Level Configuration
17 const ZOOM_LEVEL_MIN = 0.5;
18 const ZOOM_LEVEL_MAX = 2.0;
19 const ZOOM_LEVEL_INCREMENT = 0.1;
20 const DEFAULT_ZOOM_SCALE = 1.0;
22 const DRAG_THRESHOLD_PIXELS = 3;
23 const ZOOM_ANIMATION_CLASS_TIMEOUT_MS = 200;
26 CONTAINER: 'mermaid-container',
27 VIEWPORT: 'mermaid-viewport',
28 CONTENT: 'mermaid-content',
29 DIAGRAM: 'mermaid-diagram',
30 CONTROLS: 'mermaid-controls',
31 ZOOM_CONTROLS: 'mermaid-zoom-controls',
32 INTERACTION_ENABLED: 'interaction-enabled',
35 LOCK_ICON: 'fa fa-lock',
36 UNLOCK_ICON: 'fa fa-unlock',
37 INTERACTIVE_HOVER: 'interactive-hover', // Class for 'grab' cursor state
38 INTERACTIVE_PAN: 'interactive-pan', // Class for 'grabbing' cursor state
39 BUTTON_BASE: 'mermaid-viewer-button-base' // Base class for all viewer buttons
42 class InteractiveMermaidViewer {
43 constructor(container, mermaidCode) {
44 this.container = container;
45 this.mermaidCode = mermaidCode;
49 this.isDragging = false;
50 this.dragStarted = false;
54 const numDecimalPlaces = (ZOOM_LEVEL_INCREMENT.toString().split('.')[1] || '').length;
55 this.zoomLevels = Array.from(
56 { length: Math.round((ZOOM_LEVEL_MAX - ZOOM_LEVEL_MIN) / ZOOM_LEVEL_INCREMENT) + 1 },
57 (_, i) => parseFloat((ZOOM_LEVEL_MIN + i * ZOOM_LEVEL_INCREMENT).toFixed(numDecimalPlaces))
60 this.currentZoomIndex = this.zoomLevels.findIndex(level => Math.abs(level - DEFAULT_ZOOM_SCALE) < 1e-9);
61 if (this.currentZoomIndex === -1) {
62 this.currentZoomIndex = Math.floor(this.zoomLevels.length / 2);
64 this.interactionEnabled = false;
65 this.initialContentOffset = { x: 0, y: 0 };
68 this.toggleInteractionBtn = null;
69 this.copyCodeBtn = null;
70 this.zoomInBtn = null;
71 this.zoomOutBtn = null;
72 this.zoomResetBtn = null;
74 // Bind event handlers for proper addition and removal
75 this.boundMouseMoveHandler = this.handleMouseMove.bind(this);
76 this.boundMouseUpHandler = this.handleMouseUp.bind(this);
77 this.boundToggleInteraction = this.toggleInteraction.bind(this);
78 this.boundCopyCode = this.copyCode.bind(this);
79 this.boundZoomIn = () => {
80 const { clientX, clientY } = this._getViewportCenterClientCoords();
81 this.zoom(1, clientX, clientY);
83 this.boundZoomOut = () => {
84 const { clientX, clientY } = this._getViewportCenterClientCoords();
85 this.zoom(-1, clientX, clientY);
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 this.diagram.innerHTML = `<p style="color: red; padding: 10px;">Error rendering diagram. Check console.</p>`;
156 // Check if Font Awesome is loaded before rendering
157 // This checks for the 'Font Awesome 6 Free' font family, which is common.
158 // Adjust if your Font Awesome version uses a different family name for its core icons.
159 if (document.fonts && typeof document.fonts.check === 'function' && document.fonts.check('1em "Font Awesome 6 Free"')) { // Check if Font Awesome is immediately available
161 } else if (document.fonts && document.fonts.ready) { // Simplified check for document.fonts.ready
162 document.fonts.ready.then(renderAndSetup).catch(err => {
163 renderAndSetup(); // Proceed with rendering even if font check fails after timeout/error
170 adjustContainerHeight() {
171 const svgElement = this.content.querySelector('svg');
173 // Ensure the viewport takes up the height of the rendered SVG
174 this.viewport.style.height = '100%';
178 calculateInitialOffset() {
179 const originalTransform = this.content.style.transform;
180 this.content.style.transform = '';
181 const contentRect = this.content.getBoundingClientRect();
182 const viewportRect = this.viewport.getBoundingClientRect();
183 this.initialContentOffset.x = contentRect.left - viewportRect.left;
184 this.initialContentOffset.y = contentRect.top - viewportRect.top;
185 this.content.style.transform = originalTransform;
188 _getViewportCenterClientCoords() {
189 const viewportRect = this.viewport.getBoundingClientRect();
191 clientX: viewportRect.left + viewportRect.width / 2,
192 clientY: viewportRect.top + viewportRect.height / 2,
196 setupEventListeners() {
197 this.toggleInteractionBtn.addEventListener('click', this.boundToggleInteraction);
198 this.copyCodeBtn.addEventListener('click', this.boundCopyCode);
199 this.zoomInBtn.addEventListener('click', this.boundZoomIn);
200 this.zoomOutBtn.addEventListener('click', this.boundZoomOut);
201 this.zoomResetBtn.addEventListener('click', this.boundResetZoom);
203 this.viewport.addEventListener('wheel', this.boundHandleWheel, { passive: false });
204 this.viewport.addEventListener('mousedown', this.boundHandleMouseDown);
206 // Listen on document for mousemove to handle dragging outside viewport
207 document.addEventListener('mousemove', this.boundMouseMoveHandler);
208 // Listen on window for mouseup to ensure drag ends even if mouse is released outside
209 window.addEventListener('mouseup', this.boundMouseUpHandler, true); // Use capture phase
211 this.viewport.addEventListener('contextmenu', this.boundPreventDefault);
212 this.viewport.addEventListener('selectstart', this.boundPreventSelect);
215 toggleInteraction() {
216 this.interactionEnabled = !this.interactionEnabled;
217 const icon = this.toggleInteractionBtn.querySelector('i');
218 this.toggleInteractionBtn.setAttribute('aria-pressed', this.interactionEnabled.toString());
220 if (this.interactionEnabled) {
221 icon.className = CSS_CLASSES.UNLOCK_ICON;
222 this.toggleInteractionBtn.title = 'Disable manual interaction';
223 this.viewport.classList.add(CSS_CLASSES.INTERACTION_ENABLED);
224 this.viewport.classList.add(CSS_CLASSES.INTERACTIVE_HOVER); // Set grab cursor state
225 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_PAN); // Ensure pan cursor state is off
227 icon.className = CSS_CLASSES.LOCK_ICON;
228 this.toggleInteractionBtn.title = 'Enable manual interaction';
229 this.viewport.classList.remove(CSS_CLASSES.INTERACTION_ENABLED);
230 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_HOVER);
231 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_PAN);
232 this.isDragging = false; // Ensure dragging stops if interaction is disabled mid-drag
233 this.dragStarted = false;
234 this.viewport.classList.remove(CSS_CLASSES.DRAGGING);
239 this.content.style.transform = `translate(${this.translateX}px, ${this.translateY}px) scale(${this.scale})`;
243 if (!this.interactionEnabled) return;
244 // Prevent default browser scroll/zoom behavior when wheeling over the diagram
246 this.content.classList.add(CSS_CLASSES.ZOOMING);
247 const clientX = e.clientX;
248 const clientY = e.clientY;
249 if (e.deltaY > 0) this.zoom(-1, clientX, clientY);
250 else this.zoom(1, clientX, clientY);
251 setTimeout(() => this.content.classList.remove(CSS_CLASSES.ZOOMING), ZOOM_ANIMATION_CLASS_TIMEOUT_MS);
255 if (!this.interactionEnabled || e.button !== 0) return;
257 this.isDragging = true;
258 this.dragStarted = false;
259 this.startX = e.clientX;
260 this.startY = e.clientY;
261 this.dragBaseTranslateX = this.translateX;
262 this.dragBaseTranslateY = this.translateY;
263 this.viewport.classList.add(CSS_CLASSES.DRAGGING);
264 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_HOVER);
265 this.viewport.classList.add(CSS_CLASSES.INTERACTIVE_PAN);
266 this.content.classList.remove(CSS_CLASSES.ZOOMING);
270 if (!this.isDragging) return;
271 // e.preventDefault() is called only after dragStarted is true to allow clicks if threshold isn't met.
272 const deltaX = e.clientX - this.startX;
273 const deltaY = e.clientY - this.startY;
274 if (!this.dragStarted && (Math.abs(deltaX) > DRAG_THRESHOLD_PIXELS || Math.abs(deltaY) > DRAG_THRESHOLD_PIXELS)) {
275 this.dragStarted = true;
277 if (this.dragStarted) {
278 e.preventDefault(); // Prevent text selection, etc., only when drag has truly started
279 this.translateX = this.dragBaseTranslateX + deltaX;
280 this.translateY = this.dragBaseTranslateY + deltaY;
281 this.updateTransform();
286 if (this.isDragging) {
287 this.isDragging = false;
288 this.dragStarted = false;
289 this.viewport.classList.remove(CSS_CLASSES.DRAGGING);
290 this.viewport.classList.remove(CSS_CLASSES.INTERACTIVE_PAN);
291 if (this.interactionEnabled) { // Revert to grab cursor if interaction is still enabled
292 this.viewport.classList.add(CSS_CLASSES.INTERACTIVE_HOVER);
295 this.content.style.transform = `translate(${this.translateX}px, ${this.translateY}px) scale(${this.scale})`;
299 const svgElement = this.content.querySelector('svg');
301 const viewportRect = this.viewport.getBoundingClientRect();
302 const svgIntrinsicWidth = svgElement.viewBox.baseVal.width || svgElement.clientWidth;
303 const svgIntrinsicHeight = svgElement.viewBox.baseVal.height || svgElement.clientHeight;
305 const targetContentLeftRelativeToViewport = (viewportRect.width - (svgIntrinsicWidth * this.scale)) / 2;
306 const targetContentTopRelativeToViewport = (viewportRect.height - (svgIntrinsicHeight * this.scale)) / 2;
308 this.translateX = targetContentLeftRelativeToViewport - this.initialContentOffset.x;
309 this.translateY = targetContentTopRelativeToViewport - this.initialContentOffset.y;
311 // Initial centering constraints; may need adjustment for very large diagrams.
312 this.translateX = Math.max(0, this.translateX);
313 this.translateY = Math.max(0, this.translateY);
315 this.updateTransform();
319 zoom(direction, clientX, clientY) {
320 this.content.classList.add(CSS_CLASSES.ZOOMING);
321 const oldScale = this.scale;
322 let newZoomIndex = this.currentZoomIndex + direction;
324 if (newZoomIndex >= 0 && newZoomIndex < this.zoomLevels.length) {
325 this.currentZoomIndex = newZoomIndex;
326 const newScale = this.zoomLevels[this.currentZoomIndex];
328 const viewportRect = this.viewport.getBoundingClientRect();
329 const pointXInContent = (clientX - viewportRect.left - this.translateX) / oldScale;
330 const pointYInContent = (clientY - viewportRect.top - this.translateY) / oldScale;
332 this.translateX = (clientX - viewportRect.left) - (pointXInContent * newScale);
333 this.translateY = (clientY - viewportRect.top) - (pointYInContent * newScale);
334 this.scale = newScale;
335 this.updateTransform();
337 setTimeout(() => this.content.classList.remove(CSS_CLASSES.ZOOMING), ZOOM_ANIMATION_CLASS_TIMEOUT_MS);
341 this.content.classList.add(CSS_CLASSES.ZOOMING);
342 this.currentZoomIndex = this.zoomLevels.findIndex(level => Math.abs(level - DEFAULT_ZOOM_SCALE) < 1e-9);
343 if (this.currentZoomIndex === -1) { // Fallback if default not exactly in levels
344 this.currentZoomIndex = Math.floor(this.zoomLevels.length / 2);
346 this.scale = this.zoomLevels[this.currentZoomIndex];
347 // Use requestAnimationFrame to ensure layout is stable before centering
348 requestAnimationFrame(() => {
349 this.centerDiagram();
350 setTimeout(() => this.content.classList.remove(CSS_CLASSES.ZOOMING), ZOOM_ANIMATION_CLASS_TIMEOUT_MS);
356 await navigator.clipboard.writeText(this.mermaidCode);
357 this.showNotification('Copied!');
359 // Fallback for older browsers or if clipboard API fails
360 const textArea = document.createElement('textarea');
361 textArea.value = this.mermaidCode;
362 // Style to make it invisible
363 textArea.style.position = 'fixed';
364 textArea.style.top = '-9999px';
365 textArea.style.left = '-9999px';
366 document.body.appendChild(textArea);
369 document.execCommand('copy');
370 this.showNotification('Copied!');
371 } catch (copyError) {
372 console.error('Fallback copy failed:', copyError);
373 this.showNotification('Copy failed.', true); // Error
375 document.body.removeChild(textArea);
379 showNotification(message, isError = false) {
380 if (window.$events) {
381 const eventName = isError ? 'error' : 'success';
382 window.$events.emit(eventName, message);
384 // Fallback for if the event system is not available
385 console.warn('BookStack event system not found, falling back to console log for notification.');
387 console.error(message);
389 console.log(message);
395 // Remove event listeners specific to this instance
396 this.toggleInteractionBtn.removeEventListener('click', this.boundToggleInteraction);
397 this.copyCodeBtn.removeEventListener('click', this.boundCopyCode);
398 this.zoomInBtn.removeEventListener('click', this.boundZoomIn);
399 this.zoomOutBtn.removeEventListener('click', this.boundZoomOut);
400 this.zoomResetBtn.removeEventListener('click', this.boundResetZoom);
402 this.viewport.removeEventListener('wheel', this.boundHandleWheel, { passive: false });
403 this.viewport.removeEventListener('mousedown', this.boundHandleMouseDown);
404 this.viewport.removeEventListener('contextmenu', this.boundPreventDefault);
405 this.viewport.removeEventListener('selectstart', this.boundPreventSelect);
407 document.removeEventListener('mousemove', this.boundMouseMoveHandler);
408 window.removeEventListener('mouseup', this.boundMouseUpHandler, true);
410 this.container.innerHTML = ''; // Clear the container's content
414 const mermaidViewers = [];
415 function initializeMermaidViewers() {
416 // Adjust the selector if your CMS wraps mermaid code blocks differently
417 const codeBlocks = document.querySelectorAll('pre code.language-mermaid');
418 for (const codeBlock of codeBlocks) {
419 // Ensure we don't re-initialize if this script runs multiple times or content is dynamic
420 if (codeBlock.dataset.mermaidViewerInitialized) continue;
422 const mermaidCode = codeBlock.textContent || codeBlock.innerHTML; // textContent is usually better
423 const container = document.createElement('div');
424 container.className = CSS_CLASSES.CONTAINER;
426 const replaceTarget = (codeBlock.nodeName === 'CODE') ? codeBlock.parentElement : codeBlock;
428 // Check if replaceTarget is already a mermaid-container (e.g. from previous init)
429 if (replaceTarget.classList.contains(CSS_CLASSES.CONTAINER)) continue;
431 replaceTarget.after(container);
432 replaceTarget.remove(); // Remove the original <pre> or <pre><code> block
434 const viewer = new InteractiveMermaidViewer(container, mermaidCode);
435 mermaidViewers.push(viewer);
436 codeBlock.dataset.mermaidViewerInitialized = 'true'; // Mark as initialized
440 // Initialize on DOMContentLoaded
441 if (document.readyState === 'loading') {
442 document.addEventListener('DOMContentLoaded', initializeMermaidViewers);
444 // DOMContentLoaded has already fired
445 initializeMermaidViewers();
448 // Re-center diagrams on window load, as images/fonts inside SVG might affect size
449 window.addEventListener('load', () => {
450 mermaidViewers.forEach(viewer => {
451 // Delay slightly to ensure mermaid rendering is fully complete and dimensions are stable
452 setTimeout(() => viewer.centerDiagram(), 100);
456 // Optional: If your CMS dynamically adds content, you might need a way to re-run initialization
457 // For example, using a MutationObserver or a custom event.
458 // document.addEventListener('myCMSContentLoaded', () => initializeMermaidViewers());
462 /* Use BookStack's CSS variables for seamless theme integration */
464 background: var(--color-bg-alt);
465 border: 1px solid #d0d7de;
473 /* This will now be 100% of the dynamically set container height */
475 /* Keep this for panning/zooming when content exceeds viewport */
477 /* Default to normal system cursor */
480 /* Ensure viewport cursor is auto when locked, even if active.
481 The text selection (I-beam) cursor will still appear over selectable text within .mermaid-content. */
482 .mermaid-viewport:not(.interaction-enabled):active {
486 /* Set 'grab' cursor when the viewport has the 'interactive-hover' class. */
487 .mermaid-viewport.interactive-hover {
491 /* Set 'grabbing' cursor when the viewport has the 'interactive-pan' class. */
492 .mermaid-viewport.interactive-pan {
493 cursor: grabbing !important;
497 transform-origin: 0 0;
498 /* Allow text selection by default (when interaction is locked) */
501 will-change: transform;
504 /* Disable text selection ONLY when interaction is enabled on the viewport */
505 .mermaid-viewport.interaction-enabled .mermaid-content {
509 /* SVG elements inherit cursor from the viewport when interaction is enabled. */
510 .mermaid-viewport.interaction-enabled .mermaid-content svg,
511 .mermaid-viewport.interaction-enabled .mermaid-content svg * {
512 cursor: inherit !important;
513 /* Force inheritance from the viewport's cursor */
516 .mermaid-content.zooming {
517 transition: transform 0.2s ease;
529 .mermaid-viewer-button-base {
530 border: 1px solid #d0d7de;
535 justify-content: center;
537 background: var(--color-bg);
540 color: var(--color-text);
543 .mermaid-viewer-button-base:hover {
547 .dark-mode .mermaid-viewer-button-base:hover {
548 background: var(--color-bg-alt);
551 /* Override for pure white icons in dark mode */
552 .dark-mode .mermaid-viewer-button-base {
556 .mermaid-zoom-controls {
561 flex-direction: column;