📚 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
New editor: Textarea
Smaug6739f290b8de07c7
diff --git a/frontend/components/MarkdownEditor/Editor.ts b/frontend/components/MarkdownEditor/Editor.tsindex f33d26fa..1efa1565 100644--- a/frontend/components/MarkdownEditor/Editor.ts+++ b/frontend/components/MarkdownEditor/Editor.ts@@ -1,20 +1,19 @@-import { ref } from 'vue';-import type { Ref } from 'vue';-import MarkdownUtil from '~/components/MarkdownEditor/Utils';+import { type Snippet, snippets } from './snippets';export class Editor extends EventTarget {- public area: Ref<HTMLDivElement | undefined>; // The editor area+ public area: Ref<HTMLTextAreaElement | undefined>; // The editor areapublic util: MarkdownUtil; // The markdown utility formatterpublic showPreview: Ref<boolean> = ref(false); // Whether to show the preview or not-+ public container: Ref<HTMLElement | undefined>; // The container elementpublic inlineToolbar: Ref<{ element: HTMLElement } | undefined>;- constructor(area: Ref<HTMLDivElement | undefined>, inlineToolbar: Ref<{ element: HTMLElement } | undefined>) {+ constructor(area: Ref<HTMLTextAreaElement | undefined>, inlineToolbar: Ref<{ element: HTMLElement } | undefined>, container: Ref<HTMLElement | undefined>) {super();this.area = area;this.inlineToolbar = inlineToolbar as Ref<{ element: HTMLElement }>;this.util = new MarkdownUtil(area);+ this.container = container;}public format(action: string) {@@ -35,10 +34,10 @@ export class Editor extends EventTarget {this.util.inlineFormat('<pink>', '</pink>');break;case 'bold':- this.util.inlineFormat('<b>', '</b>');+ this.util.inlineFormat('**', '**');break;case 'italic':- this.util.inlineFormat('<em>', '</em>');+ this.util.inlineFormat('*', '*');break;case 'underline':this.util.inlineFormat('__', '__');@@ -64,29 +63,11 @@ export class Editor extends EventTarget {case 'orderedList':this.util.inlineFormat('1. ', '');break;- case 'clear':- this.util.clear();- break;}}public handleKeydown(event: KeyboardEvent) {if (!event.ctrlKey && !event.altKey && !event.metaKey) this.inlineToolbar.value!.element.style.display = 'none';- if (event.key === 'Enter') {- event.preventDefault();- const selection = window.getSelection();- if (!selection) return;- const range = selection.getRangeAt(0);-- // IF the cursor is at the end of the line, insert two new lines instead of one else insert one new line- const textNode = range.startContainer.textContent?.length == range.startOffset ? document.createTextNode('\n\n') : document.createTextNode('\n');- range.insertNode(textNode);-- range.setStartAfter(textNode);- range.setEndAfter(textNode);- selection.removeAllRanges();- selection.addRange(range);- }if (event.key === 'Tab') {event.preventDefault();this.util.addContent(' ');@@ -121,68 +102,88 @@ export class Editor extends EventTarget {event.preventDefault();this.showPreview.value = !this.showPreview.value;}- // Détection du snippet !def+ // Snippets detectionif (event.key === ' ') {- const selection = window.getSelection();- if (!selection) return;- const range = selection.getRangeAt(0);- const text = range.startContainer.textContent;- if (!text) return;- const match = text.substring(0, range.startOffset).match(/!def$/);- if (match) {- event.preventDefault();- this.insertSnippet(range);- }+ if (this.handleSnippets()) event.preventDefault();}}- private insertSnippet(range: Range) {- const snippet = ':::definition Définition: $\n$\n:::';- const snippetParts = snippet.split('$');+ private handleSnippets() {+ const cursorPosition = this.area.value!.selectionStart;+ const text = this.area.value!.value;+ const textBeforeCursor = text.substring(0, cursorPosition);+ const textAfterCursor = text.substring(cursorPosition);+ const snippet = snippets.find(snippet => textBeforeCursor.trim().endsWith(snippet.cmd));+ if (!snippet) return;+ const beforeWord = textBeforeCursor.substring(0, textBeforeCursor.length - snippet.cmd.length);+ const newText = beforeWord + snippet.value + textAfterCursor;+ // Update the this.area.value! value+ this.area.value!.value = newText;+ // Find the position of {$} in the snippet value and set the cursor position+ const placeholderIndex = beforeWord.length + snippet.value.indexOf('{$}');+ if (placeholderIndex == -1) return;+ this.area.value!.value = newText.replace('{$}', '');+ this.area.value!.setSelectionRange(placeholderIndex, placeholderIndex);+ // Prevent the default space character from being inserted+ return true;+ }+ public handleInlineToolbar() {+ if (!this.inlineToolbar?.value?.element) return;+ const toolbarElement = this.inlineToolbar.value.element;+ toolbarElement.style.display = 'none';+ const selection = window.getSelection();+ if (!selection || selection.rangeCount === 0 || selection.toString().length == 0) return;+ const { top, left } = this.getCaretPosition();+ if (top - this.area.value!.scrollTop + 25 < 0) return;+ toolbarElement.style.top = `${top - this.area.value!.scrollTop + 25}px`;+ toolbarElement.style.left = `${left - this.area.value!.scrollLeft}px`;+ toolbarElement.style.display = 'flex';+ }+ private getCaretPosition() {+ const textarea = this.area.value!;+ const cursorPos = textarea.selectionStart;+ // Create a mirrored element+ const mirroredEle = document.createElement('div');+ const copyStyle = getComputedStyle(textarea);- // Supprime la commande !def- const commandLength = 4;- range.setStart(range.startContainer, range.startOffset - commandLength);- range.deleteContents();+ for (const prop of copyStyle) {+ mirroredEle.style[prop as any] = copyStyle[prop as any] as any;+ }++ // Add specific styles+ mirroredEle.style.position = 'absolute';+ mirroredEle.style.visibility = 'hidden';+ mirroredEle.style.width = textarea.clientWidth + 'px';+ mirroredEle.style.height = textarea.clientHeight + 'px';+ mirroredEle.style.overflow = 'auto';++ // Text with caret+ const textBeforeCursor = textarea.value.substring(0, cursorPos);+ const textAfterCursor = textarea.value.substring(cursorPos);++ const pre = document.createTextNode(textBeforeCursor);+ const post = document.createTextNode(textAfterCursor);+ const caretEle = document.createElement('span');+ caretEle.textContent = '|'; // Utilisation d'un caractère pour le caret++ mirroredEle.append(pre, caretEle, post);+ // Use document fragment to append the mirrored element (to avoid reflow)const fragment = document.createDocumentFragment();- snippetParts.forEach((part, index) => {- fragment.appendChild(document.createTextNode(part));- if (index != 0) return;- const marker = document.createElement('span');- marker.className = 'cursor-marker';- fragment.appendChild(marker);- });+ fragment.appendChild(mirroredEle);- range.insertNode(fragment);- const selection = window.getSelection();- if (!selection) return;- selection.removeAllRanges();+ // Add fragment to the body (to get the correct position)+ this.container.value!.appendChild(fragment);- const markers = document.getElementsByClassName('cursor-marker');- if (markers.length > 0) {- const newRange = document.createRange();- newRange.setStartBefore(markers[0]!);- newRange.setEndBefore(markers[0]!);- selection.addRange(newRange);- }- }+ // Get the caret position+ const rect = caretEle.getBoundingClientRect();+ const containerRect = textarea.getBoundingClientRect();++ // Calculate relative position+ const top = rect.top - containerRect.top;+ const left = rect.left - containerRect.left;+ // Delete the mirrored element+ this.container.value!.removeChild(mirroredEle);- public updateContextMenu() {- setTimeout(() => {- const toolbarElement = this.inlineToolbar.value!.element;- toolbarElement.style.display = 'none';- if (!this.area?.value) return;- const selection = window.getSelection();- if (!selection || selection.rangeCount === 0 || selection.toString().length == 0) return;- const range = selection.getRangeAt(0);- if (!this.area.value.contains(range.startContainer) || !this.area.value.contains(range.endContainer)) return;- const containerRect = this.area.value?.getBoundingClientRect(); //const selectionRect = range.getBoundingClientRect();- const rects = range.getClientRects();- if (!containerRect) return;- const last_rect = rects[rects.length - 1];- toolbarElement.style.top = `${last_rect.top - containerRect.top + 25}px`;- toolbarElement.style.left = `${last_rect.left - containerRect.left}px`;- toolbarElement.style.display = 'flex';- }, 10);+ return { top, left };}}diff --git a/frontend/components/MarkdownEditor/LazyMarkdownEditor.vue b/frontend/components/MarkdownEditor/LazyMarkdownEditor.vueindex f56e433d..5c9378bf 100644--- a/frontend/components/MarkdownEditor/LazyMarkdownEditor.vue+++ b/frontend/components/MarkdownEditor/LazyMarkdownEditor.vue@@ -1,18 +1,14 @@<template>- <div class="editor-container" @keydown="editor.handleKeydown">- <Toolbar style="height: fit-content;" :document="document" @execute-action="(a: string) => exec(a)" />- <input placeholder="Title" class="title" v-model="document.name" />- <input placeholder="Description" class="description" v-model="document.description" />- <div class="markdown">- <InlineToolbar ref="toolbar" @execute-action="(a: string) => exec(a)" />- <div contenteditable="true" ref="textarea" class="textarea content markdown-input" @scroll="syncScroll"- @input="update" @blur="update" v-html="document.content_markdown || ''"- placeholder="Write something or use the toolbar to create your document...">- </div>- <div v-if="editor.showPreview.value" class="markdown-preview document-theme" ref="markdownPreview"- v-html="document.content_html"></div>- </div>- </div>+ <div class="editor-container" @keydown="editor.handleKeydown">+ <Toolbar style="height: fit-content" :document="document" @execute-action="(a: string) => exec(a)" />+ <input placeholder="Title" class="title" v-model="document.name" />+ <input placeholder="Description" class="description" v-model="document.description" />+ <div class="markdown" ref="container">+ <InlineToolbar ref="toolbar" @execute-action="(a: string) => exec(a)" />+ <textarea ref="textarea" class="textarea content markdown-input" @scroll="syncScroll" @input="update" v-html="document.content_markdown || ''" placeholder="Write something or use the toolbar to create your document..."></textarea>+ <div v-if="editor.showPreview.value" class="markdown-preview document-theme" ref="markdownPreview" v-html="document.content_html"></div>+ </div>+ </div></template><script setup lang="ts">@@ -25,14 +21,14 @@ import type { Document } from '~/stores';const props = defineProps<{ doc?: Document }>();const document = ref<Document | Partial<Document>>({ ...props.doc });const toolbar = ref<{ element: HTMLDivElement }>();-const textarea = ref<HTMLDivElement>();+const container = ref<HTMLDivElement>();+const textarea = ref<HTMLTextAreaElement>();-const editor = new Editor(textarea, toolbar);+const editor = new Editor(textarea, toolbar, container);const emit = defineEmits(['save']);-const update = () => document.value.content_html = compile(textarea.value?.innerHTML || '');-const handleClick = () => editor.updateContextMenu();-+const update = () => (document.value.content_html = compile(textarea.value?.value || ''));+const handleClick = () => editor.handleInlineToolbar();const markdownPreview = ref<HTMLDivElement>();editor.addEventListener('save', saveDocument);@@ -40,95 +36,99 @@ onMounted(() => window.addEventListener('mouseup', handleClick));onBeforeUnmount(() => window.removeEventListener('mouseup', handleClick));function exec(action: string) {- editor.format(action);- switch (action) {- case 'exit':- useRouter().push(document.value.id ? `/dashboard/docs/${document.value.id}` : '/dashboard');- break;- case 'preview':- editor.showPreview.value = !editor.showPreview.value;- break;- case 'save':- saveDocument();- }- update();+ editor.format(action);+ switch (action) {+ case 'exit':+ useRouter().push(document.value.id ? `/dashboard/docs/${document.value.id}` : '/dashboard');+ break;+ case 'preview':+ editor.showPreview.value = !editor.showPreview.value;+ break;+ case 'save':+ saveDocument();+ }+ update();}function syncScroll() {- if (!textarea.value || !markdownPreview.value) return;- const scrollPercentage = textarea.value.scrollTop / (textarea.value.scrollHeight - textarea.value.clientHeight);- markdownPreview.value.scrollTop = scrollPercentage * (markdownPreview.value.scrollHeight - markdownPreview.value.clientHeight);+ editor.handleInlineToolbar();+ if (!textarea.value || !markdownPreview.value) return;+ const scrollPercentage = textarea.value.scrollTop / (textarea.value.scrollHeight - textarea.value.clientHeight);+ markdownPreview.value.scrollTop = scrollPercentage * (markdownPreview.value.scrollHeight - markdownPreview.value.clientHeight);}function saveDocument() {- document.value.content_markdown = textarea.value?.innerHTML;- document.value.content_html = compile(document.value.content_markdown, true);- emit('save', document.value);+ document.value.content_markdown = textarea.value?.innerHTML;+ document.value.content_html = compile(document.value.content_markdown);+ emit('save', document.value);}-</script><style scoped lang="scss">.editor-container {- height: 90%;- width: 100%;+ height: 90%;+ width: 100%;}.markdown {- position: relative;- height: 80%;- display: flex;+ position: relative;+ height: 80%;+ display: flex;}.markdown-input,.markdown-preview {- padding: 5px;- flex: 1;- overflow: auto;+ padding: 5px;+ flex: 1;+ overflow: auto;}.markdown-preview {- border-left: 1px solid var(--border-color);- position: relative;+ border-left: 1px solid var(--border-color);+ position: relative;}input,.textarea {- border: none;- outline: none;- background-color: var(--bg-color);- padding-left: 0;+ border: none;+ outline: none;+ background-color: var(--bg-color);+ padding-left: 0;}input {- display: block;- width: 100%;+ display: block;+ width: 100%;}[placeholder]:empty::before {- content: attr(placeholder);- color: #757575;- font-weight: 500;- font-size: 18px;- opacity: 1+ content: attr(placeholder);+ color: #757575;+ font-weight: 500;+ font-size: 18px;+ opacity: 1;}[placeholder]:empty {- content: "";+ content: '';}.textarea {- white-space: break-spaces;+ white-space: break-spaces;+ font-family: monospace;+ line-height: 1.2;+ font-size: 16px;+ letter-spacing: -0.6px;}.title {- font-size: 24px;- font-weight: bold;- margin-bottom: 10px;+ font-size: 24px;+ font-weight: bold;+ margin-bottom: 10px;}.description {- font-size: 18px;- font-weight: bold;- margin-bottom: 10px;+ font-size: 18px;+ font-weight: bold;+ margin-bottom: 10px;}</style>diff --git a/frontend/components/MarkdownEditor/Utils.ts b/frontend/components/MarkdownEditor/Utils.tsindex 41db5d1b..90ca75c6 100644--- a/frontend/components/MarkdownEditor/Utils.ts+++ b/frontend/components/MarkdownEditor/Utils.ts@@ -1,7 +1,7 @@class MarkdownUtil {- private editor: Ref<HTMLDivElement | undefined>;+ private editor: Ref<HTMLTextAreaElement | undefined>;- constructor(editor: Ref<HTMLDivElement | undefined>) {+ constructor(editor: Ref<HTMLTextAreaElement | undefined>) {this.editor = editor;}private getEditorRange() {@@ -20,37 +20,20 @@ class MarkdownUtil {return tempDiv;}public inlineFormat(tag1: string, tag2: string) {- const range = this.getEditorRange();- if (!range) return;- const tempDiv = this.createTempDiv(range.cloneContents());- const fragment = document.createDocumentFragment();- tempDiv.innerHTML = tag1 + tempDiv.innerHTML.trim().replaceAll('\n', '') + tag2;- while (tempDiv.firstChild) {- fragment.appendChild(tempDiv.firstChild);- }- range.deleteContents();- range.insertNode(fragment);+ const selectedText = window.getSelection()?.toString() || '';+ const startTag = `${tag1}`;+ const endTag = `${tag2}`;+ const startIndex = this.editor.value!.selectionStart;+ const endIndex = this.editor.value!.selectionEnd;+ const beforeSelected = this.editor.value!.value.substring(0, startIndex);+ const afterSelected = this.editor.value!.value.substring(endIndex, this.editor.value!.value.length);+ this.editor.value!.value = beforeSelected + startTag + selectedText + endTag + afterSelected;+ const newStartIndex = startIndex + startTag.length;+ const newEndIndex = newStartIndex + selectedText.length;+ this.editor.value!.setSelectionRange(newStartIndex, newEndIndex);+ this.editor.value!.focus();}- public clear() {- const range = this.getEditorRange();- if (!range) return;- const tempDiv = this.createTempDiv(range.cloneContents());- const parentElement: Element | null =- range.commonAncestorContainer.nodeType === 3- ? (range.commonAncestorContainer.parentElement as Element)- : (range.commonAncestorContainer as Element);- if (parentElement != this.editor.value) {- const text = parentElement.textContent || '';- const textNode = document.createTextNode(text);- parentElement.replaceWith(textNode);- } else if (tempDiv.innerHTML != '') {- const text = tempDiv.textContent || '';- const textNode = document.createTextNode(text);- range.deleteContents();- range.insertNode(textNode);- }- }public addContent(content: string) {const selection = window.getSelection();if (!selection) return;diff --git a/frontend/components/MarkdownEditor/snippets.ts b/frontend/components/MarkdownEditor/snippets.tsnew file mode 100644index 00000000..84ca29fd--- /dev/null+++ b/frontend/components/MarkdownEditor/snippets.ts@@ -0,0 +1,23 @@+// Declare all snippets here++interface Snippet {+ cmd: string;+ value: string;+}++const snippets = [+ {+ cmd: '!def',+ value: ':::definition Définition: {$}\n:::',+ },+ {+ cmd: '!thm',+ value: ':::theorem Théorème:{$}\n:::',+ },+ {+ cmd: '!m',+ value: '${$}$',+ },+];++export { type Snippet, snippets };diff --git a/frontend/helpers/markdown/index.ts b/frontend/helpers/markdown/index.tsindex 842a00c0..9741d5ea 100644--- a/frontend/helpers/markdown/index.ts+++ b/frontend/helpers/markdown/index.ts@@ -62,9 +62,9 @@ function markdownItKatexPlugin(md: any) {};}-export default function compile(str: string = '', plugins: boolean = true): string {- // Replace fix use of & in katex expressions- str = str.replaceAll('&', '&');+export default function compile(str: string = ''): string {+ // Replace < > & to < > & (to avoid markdown-it escape)+ str = str.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');return md.render(str, {html: true,});diff --git a/frontend/stores/_utils.ts b/frontend/stores/_utils.tsindex 6cc259eb..92337215 100644--- a/frontend/stores/_utils.ts+++ b/frontend/stores/_utils.ts@@ -34,14 +34,11 @@ export async function makeRequest<T>(route: string, method: string, body: Object} else treatQueue(false);return promise;- } else if (!response.ok) {- return { status: 'error', message: 'Failed to fetch' };}-const decoded = await response.json();return decoded;- } catch {- return { status: 'error', message: 'Failed to fetch.' };+ } catch (e) {+ return { status: 'error', message: String(e) };}}