π The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.
Vue dockergolangkanbanknowledge-baseknowledge-managementmarkdownnote-takingnotesnotes-appnotionnuxtnuxtjsoffline-firstoidcpwaselfhostedssovuevuejswiki
feat: implement scroll synchronization between editor and preview
Smaug6739861a6c27644c
diff --git a/frontend/app/components/MarkdownEditor/MarkdownEditor.vue b/frontend/app/components/MarkdownEditor/MarkdownEditor.vueindex c8ed2a0e..b3339e0b 100644--- a/frontend/app/components/MarkdownEditor/MarkdownEditor.vue+++ b/frontend/app/components/MarkdownEditor/MarkdownEditor.vue@@ -44,6 +44,7 @@ import { createKeymaps } from './modules/editorKeymaps';import { createUploadsHandlers } from './modules/editorUploads';import { createSnippetSource } from './modules/editorUtils';import { createCommands } from './modules/editorCommands';+import { createScrollSync } from './modules/scrollSync';import Toolbar from './Toolbar.vue';import NodeDocumentContentCompiled from '~/components/Node/Document/ContentCompiled.vue';@@ -65,6 +66,11 @@ const showPreview = ref(false);const autoSaveEnabled = preferences.get('documentAutoSave');+const scrollSync = createScrollSync({+ getView: () => editorView.value as EditorView | null,+ getPreview: () => markdownPreview.value,+});+const document = ref<Partial<Node>>({...props.doc,content_compiled: compile(props.doc?.content || ''),@@ -99,7 +105,7 @@ onMounted(() => {state,parent: editorContainer.value,});- editorView.value.scrollDOM.addEventListener('scroll', syncScroll);+ editorView.value.scrollDOM.addEventListener('scroll', scrollSync.syncEditorToPreview);window.addEventListener('keydown', handleGlobalKeys);});@@ -109,7 +115,8 @@ onBeforeUnmount(() => {emit('autoSave', document.value);}if (editorView.value) editorView.value.destroy();- editorView.value?.scrollDOM.removeEventListener('scroll', syncScroll);+ editorView.value?.scrollDOM.removeEventListener('scroll', scrollSync.syncEditorToPreview);+ scrollSync.dispose();window.removeEventListener('keydown', handleGlobalKeys);});@@ -127,11 +134,13 @@ function handleGlobalKeys(e: KeyboardEvent) {}}-function syncScroll() {- if (!editorView.value?.scrollDOM || !markdownPreview.value) return;- const scrollPercentage = editorView.value.scrollDOM.scrollTop / (editorView.value.scrollDOM.scrollHeight - editorView.value.scrollDOM.clientHeight);- markdownPreview.value.scrollTop = scrollPercentage * (markdownPreview.value.scrollHeight - markdownPreview.value.clientHeight);-}+// Re-sync scroll after the preview DOM updates (e.g. after typing new content)+watch(+ () => document.value.content_compiled,+ () => {+ nextTick(() => scrollSync.syncEditorToPreview());+ },+);function autoSaveConditional() {if (autoSaveEnabled.value) {diff --git a/frontend/app/components/MarkdownEditor/modules/scrollSync.ts b/frontend/app/components/MarkdownEditor/modules/scrollSync.tsnew file mode 100644index 00000000..602f4f72--- /dev/null+++ b/frontend/app/components/MarkdownEditor/modules/scrollSync.ts@@ -0,0 +1,206 @@+import type { EditorView } from '@codemirror/view';++/* ------------------------------------------------------------------ */+/* Types */+/* ------------------------------------------------------------------ */++/** A single mapping between a source line and a position in the preview. */+interface ScrollAnchor {+ /** 0-based line number in the markdown source */+ sourceLine: number;+ /** Offset (px) from the top of the preview's scrollable content */+ offsetTop: number;+}++/**+ * Subset of EditorView used by the scroll-sync logic.+ * Avoids tight coupling to the exact EditorView class (which can differ+ * across package versions when used through a Vue ref).+ */+type EditorViewLike = Pick<EditorView, 'scrollDOM' | 'state' | 'lineBlockAtHeight'>;++interface ScrollSyncOptions {+ getView: () => EditorViewLike | null;+ getPreview: () => HTMLElement | undefined;+}++/* ------------------------------------------------------------------ */+/* Helpers */+/* ------------------------------------------------------------------ */++/**+ * Build an ordered list of anchors by querying every element that carries a+ * `data-source-line` attribute inside the preview container.+ *+ * Each anchor records:+ * β the 0-based source line+ * β its vertical position (px) inside the scrollable preview content+ */+function buildAnchors(preview: HTMLElement): ScrollAnchor[] {+ const elements = preview.querySelectorAll<HTMLElement>('[data-source-line]');+ if (elements.length === 0) return [];++ const containerRect = preview.getBoundingClientRect();+ const scrollTop = preview.scrollTop;+ const anchors: ScrollAnchor[] = [];++ for (const el of elements) {+ const line = parseInt(el.getAttribute('data-source-line')!, 10);+ if (Number.isNaN(line)) continue;++ const rect = el.getBoundingClientRect();+ // Position relative to the preview's scroll content (not the viewport)+ anchors.push({+ sourceLine: line,+ offsetTop: rect.top - containerRect.top + scrollTop,+ });+ }++ anchors.sort((a, b) => a.sourceLine - b.sourceLine);+ return anchors;+}++/**+ * Determine which source line (0-based, fractional) is currently at the very+ * top of the CodeMirror viewport.+ */+function getEditorTopLine(view: EditorViewLike): number {+ const scrollTop = view.scrollDOM.scrollTop;+ if (scrollTop <= 0) return 0;++ const block = view.lineBlockAtHeight(scrollTop);+ const docLine = view.state.doc.lineAt(block.from);+ const fraction = block.height > 0 ? Math.max(0, Math.min(1, (scrollTop - block.top) / block.height)) : 0;++ return docLine.number - 1 + fraction; // 0-based + fraction+}++/**+ * Given a fractional source line and a sorted list of anchors, compute the+ * target scroll position (px) in the preview pane using linear interpolation+ * between the two closest anchors.+ */+function computePreviewScroll(effectiveLine: number, anchors: ScrollAnchor[], totalLines: number, previewScrollHeight: number): number {+ // Find the two bracketing anchors+ let lower: ScrollAnchor | null = null;+ let upper: ScrollAnchor | null = null;++ for (const a of anchors) {+ if (a.sourceLine <= effectiveLine) {+ lower = a;+ } else {+ upper = a;+ break;+ }+ }++ if (lower && upper) {+ // Standard case β interpolate between two known anchors+ const range = upper.sourceLine - lower.sourceLine;+ const t = range > 0 ? (effectiveLine - lower.sourceLine) / range : 0;+ return lower.offsetTop + t * (upper.offsetTop - lower.offsetTop);+ }++ if (lower && !upper) {+ // Past the last anchor β interpolate towards the very bottom+ const remainingLines = totalLines - lower.sourceLine;+ const remainingHeight = previewScrollHeight - lower.offsetTop;++ if (remainingLines > 0) {+ const t = (effectiveLine - lower.sourceLine) / remainingLines;+ return lower.offsetTop + t * remainingHeight;+ }+ return lower.offsetTop;+ }++ if (!lower && upper) {+ // Before the first anchor β interpolate from the top+ const t = upper.sourceLine > 0 ? effectiveLine / upper.sourceLine : 0;+ return t * upper.offsetTop;+ }++ return 0;+}++/* ------------------------------------------------------------------ */+/* Public API */+/* ------------------------------------------------------------------ */++/**+ * Creates a scroll synchronisation controller that maps the CodeMirror+ * editor's scroll position to the corresponding position in the rendered+ * markdown preview using source-line anchors.+ *+ * Unlike a naΓ―ve percentage-based approach this handles:+ * β images / media (1 line in source, large block in preview)+ * β code blocks, tables, math blocks+ * β typing at the end of the document (snaps preview to bottom)+ */+export function createScrollSync({ getView, getPreview }: ScrollSyncOptions) {+ let rafId: number | null = null;++ /**+ * Call this from the editor's `scroll` event listener (or after content+ * changes) to update the preview scroll position.+ */+ function syncEditorToPreview() {+ // Cancel any pending frame to avoid fighting with itself+ if (rafId !== null) cancelAnimationFrame(rafId);++ rafId = requestAnimationFrame(() => {+ rafId = null;++ const view = getView();+ const preview = getPreview();+ if (!view || !preview) return;++ const scrollDOM = view.scrollDOM;+ const maxEditorScroll = scrollDOM.scrollHeight - scrollDOM.clientHeight;+ const maxPreviewScroll = preview.scrollHeight - preview.clientHeight;++ // Nothing to scroll+ if (maxEditorScroll <= 0 || maxPreviewScroll <= 0) {+ preview.scrollTop = 0;+ return;+ }++ // ββ Edge: editor at the very top ββββββββββββββββββββββββββ+ if (scrollDOM.scrollTop <= 2) {+ preview.scrollTop = 0;+ return;+ }++ // ββ Edge: editor at the very bottom βββββββββββββββββββββββ+ if (scrollDOM.scrollTop >= maxEditorScroll - 2) {+ preview.scrollTop = maxPreviewScroll;+ return;+ }++ // ββ General case: anchor-based interpolation ββββββββββββββ+ const anchors = buildAnchors(preview);++ if (anchors.length === 0) {+ // Fallback β no anchors, use percentage+ preview.scrollTop = (scrollDOM.scrollTop / maxEditorScroll) * maxPreviewScroll;+ return;+ }++ const effectiveLine = getEditorTopLine(view);+ const totalLines = view.state.doc.lines;++ const targetScroll = computePreviewScroll(effectiveLine, anchors, totalLines, preview.scrollHeight);++ preview.scrollTop = Math.max(0, Math.min(maxPreviewScroll, targetScroll));+ });+ }++ /** Clean up any pending animation frame. */+ function dispose() {+ if (rafId !== null) {+ cancelAnimationFrame(rafId);+ rafId = null;+ }+ }++ return { syncEditorToPreview, dispose } as const;+}diff --git a/frontend/app/helpers/markdown/index.ts b/frontend/app/helpers/markdown/index.tsindex 9429b70f..8bae40a8 100644--- a/frontend/app/helpers/markdown/index.ts+++ b/frontend/app/helpers/markdown/index.ts@@ -12,6 +12,7 @@ import colorPlugin from './colors';import { subscriptPlugin, superscriptPlugin, footNotePlugin, html5MediaPlugin } from './other';import { markdownItCheckbox } from './checkbox';import { markdownItKatexPlugin } from './katex';+import { sourceMapPlugin } from './source-map';const md = new MarkdownIt({ html: true, linkify: true });md.use(containerPlugin);@@ -32,6 +33,7 @@ md.use(colorPlugin, {allowHex: true, // allow #rgb and #rrggbb});md.use(html5MediaPlugin);+md.use(sourceMapPlugin);export default function compile(str: string = ''): string {// Replace < > & to < > & (to avoid markdown-it escape)diff --git a/frontend/app/helpers/markdown/source-map.ts b/frontend/app/helpers/markdown/source-map.tsnew file mode 100644index 00000000..9616c62d--- /dev/null+++ b/frontend/app/helpers/markdown/source-map.ts@@ -0,0 +1,22 @@+import type MarkdownIt from 'markdown-it';+import type Token from 'markdown-it/lib/token.mjs';++/**+ * markdown-it plugin that injects `data-source-line` attributes on block-level+ * opening tags. markdown-it already tracks source-map info (`token.map`) for+ * every block token β this plugin simply surfaces it into the rendered HTML so+ * the editor's scroll-sync logic can correlate source lines with preview DOM+ * elements.+ */+export function sourceMapPlugin(md: MarkdownIt) {+ const originalRenderToken = md.renderer.renderToken.bind(md.renderer);++ md.renderer.renderToken = function (tokens: Token[], idx: number, options) {+ const token = tokens[idx] as Token;+ // Only tag opening block elements that carry source-map info+ if (token.map && token.nesting === 1) {+ token.attrSet('data-source-line', String(token.map[0]));+ }+ return originalRenderToken(tokens, idx, options);+ };+}