π 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(markdown): add internal links feature & add editor integration corresponding #577 (#584)
Nipun Milinda Kumaraefe6ba908e41
diff --git a/frontend/app/components/MarkdownEditor/MarkdownEditor.vue b/frontend/app/components/MarkdownEditor/MarkdownEditor.vueindex 349caf54..d2240ba7 100644--- a/frontend/app/components/MarkdownEditor/MarkdownEditor.vue+++ b/frontend/app/components/MarkdownEditor/MarkdownEditor.vue@@ -47,6 +47,7 @@ import { createEditorState } from './modules/editorState';import { createKeymaps } from './modules/editorKeymaps';import { createUploadsHandlers } from './modules/editorUploads';import { createSnippetSource } from './modules/editorUtils';+import { createInternalLinks } from './modules/internalLinks';import { createCommands } from './modules/editorCommands';import { createScrollSync } from './modules/scrollSync';import compile from '~/helpers/markdown';@@ -77,9 +78,11 @@ const scrollSync = createScrollSync({getPreview: () => markdownPreview.value,});+const resolveNode = (id: string) => nodesStore.getById(id)?.name;+const document = ref<Partial<Node>>({...props.doc,- content_compiled: compile(props.doc?.content || ''),+ content_compiled: compile(props.doc?.content || '', resolveNode),});const commands = createCommands({@@ -111,6 +114,10 @@ const state = createEditorState({themeExtension: loadTheme(),keymaps: createKeymaps(commands),snippetSource: createSnippetSource(preferences.get('editorSnippetsEnabled'), preferences.get('snippets')),+ internalLinks: createInternalLinks({+ getName: id => nodesStore.getById(id)?.name,+ getDocuments: () => nodesStore.documents,+ }),onDocChanged: () => {updateDocumentContent();autoSaveConditional();@@ -173,7 +180,7 @@ function autoSaveConditional() {const updateDocumentContent = debounce(() => {const content = editorView.value?.state.doc.toString() || '';document.value.content = content;- document.value.content_compiled = compile(content);+ document.value.content_compiled = compile(content, resolveNode);}, 100);const save = debounce(() => {diff --git a/frontend/app/components/MarkdownEditor/modules/editorState.ts b/frontend/app/components/MarkdownEditor/modules/editorState.tsindex d5e854e2..65df5886 100644--- a/frontend/app/components/MarkdownEditor/modules/editorState.ts+++ b/frontend/app/components/MarkdownEditor/modules/editorState.ts@@ -6,6 +6,7 @@ import { autocompletion, closeBrackets, closeBracketsKeymap } from '@codemirror/import { markdown, markdownLanguage } from '@codemirror/lang-markdown';import { rainbowBrackets } from './bracketsRainbow';import { containerHighlight } from './customBlocks';+import type { createInternalLinks } from './internalLinks';export interface CreateEditorStateParams {initialDoc: string;@@ -13,6 +14,7 @@ export interface CreateEditorStateParams {themeExtension: Extension;keymaps: readonly KeyBinding[];snippetSource: object;+ internalLinks?: ReturnType<typeof createInternalLinks>;onDocChanged: () => void;uploadsHandlers: ReturnType<typeof EditorView.domEventHandlers>;}@@ -39,6 +41,14 @@ export function createEditorState(params: CreateEditorStateParams) {markdownLanguage.data.of({autocomplete: params.snippetSource,}),+ ...(params.internalLinks+ ? [+ params.internalLinks.extension,+ markdownLanguage.data.of({+ autocomplete: params.internalLinks.completionSource,+ }),+ ]+ : []),updateListener,params.uploadsHandlers,themeCompartment.of(params.themeExtension),diff --git a/frontend/app/components/MarkdownEditor/modules/internalLinks.ts b/frontend/app/components/MarkdownEditor/modules/internalLinks.tsnew file mode 100644index 00000000..2717fe15--- /dev/null+++ b/frontend/app/components/MarkdownEditor/modules/internalLinks.ts@@ -0,0 +1,109 @@+import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet, type ViewUpdate } from '@codemirror/view';+import type { Range } from '@codemirror/state';+import type { CompletionContext, CompletionResult } from '@codemirror/autocomplete';+import type { Node } from '~/stores';++// Internal links: #726782907684193440 is displayed as "#<document name>" in the editor+const INTERNAL_LINK_REGEX = /#(\d{15,20})(?!\d)/g;++export interface InternalLinkProvider {+ getName: (id: string) => string | undefined;+ getDocuments: () => Node[];+}++class InternalLinkWidget extends WidgetType {+ constructor(+ readonly id: string,+ readonly name: string,+ ) {+ super();+ }++ override eq(other: InternalLinkWidget) {+ return other.id === this.id && other.name === this.name;+ }++ toDOM() {+ const span = document.createElement('span');+ span.className = 'cm-internal-link';+ span.textContent = `#${this.name}`;+ span.title = `#${this.id}`;+ return span;+ }+}++function buildDecorations(view: EditorView, provider: InternalLinkProvider): DecorationSet {+ const decorations: Range<Decoration>[] = [];+ const { selection } = view.state;++ for (const { from, to } of view.visibleRanges) {+ const text = view.state.doc.sliceString(from, to);+ for (const match of text.matchAll(INTERNAL_LINK_REGEX)) {+ const start = from + match.index;+ const end = start + match[0].length;++ // Keep the raw id editable when the cursor/selection touches it+ if (selection.ranges.some(range => range.from <= end && range.to >= start)) continue;++ const id = match[1]!;+ const name = provider.getName(id);+ if (!name) continue; // Unknown document: leave the raw id visible++ decorations.push(Decoration.replace({ widget: new InternalLinkWidget(id, name) }).range(start, end));+ }+ }++ return Decoration.set(decorations);+}++export function createInternalLinks(provider: InternalLinkProvider) {+ const plugin = ViewPlugin.fromClass(+ class {+ decorations: DecorationSet;++ constructor(view: EditorView) {+ this.decorations = buildDecorations(view, provider);+ }++ update(update: ViewUpdate) {+ if (update.docChanged || update.selectionSet || update.viewportChanged) {+ this.decorations = buildDecorations(update.view, provider);+ }+ }+ },+ {+ decorations: v => v.decorations,+ },+ );++ const theme = EditorView.baseTheme({+ '.cm-internal-link': {+ color: 'var(--primary)',+ background: 'var(--accent-bg)',+ borderRadius: '4px',+ padding: '0 4px',+ },+ });++ // Autocomplete source: type "#" to search and insert a document link+ const completionSource = (context: CompletionContext): CompletionResult | null => {+ const word = context.matchBefore(/#[^\s#]*/);+ if (!word) return null;++ const documents = provider.getDocuments();+ if (!documents.length) return null;++ return {+ from: word.from,+ options: documents.map(doc => ({+ label: `#${doc.name}`,+ type: 'reference',+ detail: 'Document',+ apply: `#${doc.id}`,+ })),+ validFor: /^#[^\s#]*$/,+ };+ };++ return { extension: [plugin, theme], completionSource };+}diff --git a/frontend/app/components/Node/Document/ContentCompiled.vue b/frontend/app/components/Node/Document/ContentCompiled.vueindex 6c5d38c1..7be4e0a0 100644--- a/frontend/app/components/Node/Document/ContentCompiled.vue+++ b/frontend/app/components/Node/Document/ContentCompiled.vue@@ -5,6 +5,7 @@:class="['markdown-preview', `${theme}-theme`, `document-content`]":style="{ fontSize: documentFontSize + 'px', fontFamily: documentFontFamily, lineHeight: documentLineHeight }"@change="handleCheckboxChange"+ @click="handleInternalLinkClick"v-html="node?.content_compiled"/></template>@@ -17,6 +18,7 @@ const props = defineProps<{ node?: Partial<Node> }>();const preferences = usePreferencesStore();const nodesStore = useNodesStore();+const router = useRouter();const theme = computed(() => {if (props.node?.theme) return props.node.theme;@@ -48,6 +50,17 @@ const updateMarkdownCheckbox = (markdown: string, indexToTarget: number, shouldC});};+// Navigate internal document links (#<id>) through the router, without a full page reload+const handleInternalLinkClick = (event: MouseEvent) => {+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;+ const link = (event.target as HTMLElement).closest<HTMLAnchorElement>('a[data-internal-link]');+ if (!link) return;+ const id = link.dataset.internalLink;+ if (!id) return;+ event.preventDefault();+ router.push(`/dashboard/docs/${id}`);+};+const handleCheckboxChange = (event: Event) => {const target = event.target as HTMLInputElement;diff --git a/frontend/app/helpers/markdown/index.ts b/frontend/app/helpers/markdown/index.tsindex bf93414f..30800d15 100644--- a/frontend/app/helpers/markdown/index.ts+++ b/frontend/app/helpers/markdown/index.ts@@ -13,6 +13,7 @@ import { subscriptPlugin, superscriptPlugin, footNotePlugin, html5MediaPlugin, simport { markdownItCheckbox } from './checkbox';import { markdownItKatexPlugin } from './katex';import { sourceMapPlugin } from './source-map';+import { internalLinkPlugin } from './internal-links';const md = new MarkdownIt({ html: true, linkify: true });md.use(containerPlugin);@@ -34,12 +35,14 @@ md.use(colorPlugin, {});md.use(html5MediaPlugin);md.use(svgObjectPlugin);+md.use(internalLinkPlugin);md.use(sourceMapPlugin);-export default function compile(str: string = ''): string {+export default function compile(str: string = '', resolveNode?: (id: string) => string | undefined): string {// Replace < > & to < > & (to avoid markdown-it escape)str = str.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');return md.render(str, {html: true,+ resolveNode,});}diff --git a/frontend/app/helpers/markdown/internal-links.ts b/frontend/app/helpers/markdown/internal-links.tsnew file mode 100644index 00000000..f649e16b--- /dev/null+++ b/frontend/app/helpers/markdown/internal-links.ts@@ -0,0 +1,43 @@+import type MarkdownIt from 'markdown-it';+import type { StateInline } from 'markdown-it/dist/index.cjs.js';++// Internal links: #726782907684193440 => link to the document, displayed as "#<document name>"+export const INTERNAL_LINK_REGEX = /#(\d{15,20})(?!\d)/g;++export interface InternalLinkEnv {+ resolveNode?: (id: string) => string | undefined;+}++export function internalLinkPlugin(md: MarkdownIt) {+ md.inline.ruler.after('emphasis', 'internal_link', (state: StateInline, silent: boolean) => {+ const start = state.pos;+ if (state.src.charCodeAt(start) !== 0x23 /* # */) return false;++ // Word boundary before the # (avoid matching inside entities or other syntaxes)+ const prev = start > 0 ? state.src[start - 1] : '';+ if (prev && /[\w#&]/.test(prev)) return false;++ let end = start + 1;+ while (end < state.posMax && state.src.charCodeAt(end) >= 0x30 && state.src.charCodeAt(end) <= 0x39) {+ end++;+ }++ const digits = end - start - 1;+ if (digits < 15 || digits > 20) return false;++ if (!silent) {+ const token = state.push('internal_link', '', 0);+ token.meta = { id: state.src.slice(start + 1, end) };+ }++ state.pos = end;+ return true;+ });++ md.renderer.rules.internal_link = (tokens, idx, options, env) => {+ const id: string = tokens[idx]?.meta?.id || '';+ const name = (env as InternalLinkEnv)?.resolveNode?.(id);+ const label = md.utils.escapeHtml(name ? `#${name}` : `#${id}`);+ return `<a href="/dashboard/docs/${id}" class="internal-link" data-internal-link="${id}">${label}</a>`;+ };+}diff --git a/frontend/app/styles/features/markdown.scss b/frontend/app/styles/features/markdown.scssindex eb21c87a..0f57229e 100644--- a/frontend/app/styles/features/markdown.scss+++ b/frontend/app/styles/features/markdown.scss@@ -244,4 +244,18 @@.bordered {border: 1px solid var(--border);-}\ No newline at end of file+}++/* Internal document links (#<id>) */+.internal-link {+ padding: 1px 5px;+ border-radius: var(--radius-sm);+ font-weight: 500;+ color: var(--primary);+ background: var(--accent-bg);+ text-decoration: none;++ &:hover {+ text-decoration: underline;+ }+}