Last active
September 14, 2026 04:57
-
-
Save justinkelly/0978787a67291f2fa91186f88cc75f5f to your computer and use it in GitHub Desktop.
Synology Notes - Markdown
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ==UserScript== | |
| // @name Synology Notes Markdown / Code Blocks | |
| // @homepage https://github.com/justinkelly/Synology-Notes-UI-update-tampermonkey | |
| // @version 0.0.1 | |
| // @description Markdown shortcuts, syntax-highlighted code blocks, and a raw markdown source view/editor for Synology Notes | |
| // @author Justin Kelly | |
| // @match https://YOUR-NAS-URL/?launchApp=SYNO.SDS.NoteStation.Application* | |
| // @match https://notes.YOUR-NAS | |
| // @match https://192.168.NAS.IP:5001/?launchApp=SYNO.SDS.NoteStation.Application* | |
| // @icon https://global.download.synology.com/download/Package/img/NoteStation/2.6.1-2450/thumb_256.png | |
| // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js | |
| // @grant none | |
| // @noframes | |
| // @run-at document-idle | |
| // ==/UserScript== | |
| (function () { | |
| 'use strict'; | |
| // highlight.js is loaded via @require above — Tampermonkey fetches and | |
| // injects it itself before this script runs, which bypasses the target | |
| // page's Content-Security-Policy (a <script src> pointed at a CDN, | |
| // inserted from inside the page, would otherwise get silently blocked | |
| // by a strict CSP — that's what "highlight.min.js (blocked)" in the | |
| // Network tab means). `hljs` below is that global. Since it's loaded | |
| // into the outer page's context (not the note's iframe), we call | |
| // hljs.highlightElement() directly on <code> elements that live inside | |
| // the iframe — that's fine, DOM nodes can be manipulated across | |
| // same-origin frames regardless of which frame's script created them. | |
| // Styling for fenced code blocks, injected into the TinyMCE content | |
| // iframe (a separate document from the outer page). | |
| const editorCss = ` | |
| /* fenced code blocks (\`\`\` style) */ | |
| body.mce-content-body pre { | |
| display: block; | |
| overflow-x: auto; | |
| white-space: pre; | |
| font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace; | |
| font-size: 13px; | |
| line-height: 1.5; | |
| background-color: #f6f8fa; | |
| color: rgb(55, 53, 47); | |
| border: 1px solid rgb(223, 225, 228); | |
| border-left: 3px solid rgb(8, 109, 214); | |
| padding: 10px 14px; | |
| margin: 8px 0; | |
| } | |
| body.mce-content-body pre code { | |
| background: none !important; | |
| padding: 0 !important; | |
| border: none !important; | |
| font-size: inherit; | |
| } | |
| body.mce-content-body pre[data-lang]::before { | |
| content: attr(data-lang); | |
| display: block; | |
| font-family: -apple-system, BlinkMacSystemFont, sans-serif; | |
| font-size: 11px; | |
| text-transform: uppercase; | |
| letter-spacing: .04em; | |
| color: #605e5c; | |
| margin-bottom: 6px; | |
| } | |
| /* inline \`code\` spans, kept distinct from full pre blocks */ | |
| body.mce-content-body code:not(pre code) { | |
| font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace; | |
| font-size: 0.9em; | |
| background-color: #f0f0f0; | |
| padding: 1px 5px; | |
| border: 1px solid rgb(223, 225, 228); | |
| } | |
| /* blockquote, styled like Notion's left-bar quote block */ | |
| body.mce-content-body blockquote { | |
| margin: 8px 0; | |
| padding: 2px 14px; | |
| border-left: 3px solid rgb(223, 225, 228); | |
| color: rgb(107, 107, 107); | |
| } | |
| /* horizontal rule from a typed --- or *** */ | |
| body.mce-content-body hr { | |
| border: none; | |
| border-top: 1px solid rgb(223, 225, 228); | |
| margin: 16px 0; | |
| } | |
| body.mce-content-body a { | |
| color: rgb(8, 109, 214); | |
| text-decoration: none; | |
| } | |
| body.mce-content-body a:hover { | |
| text-decoration: underline; | |
| } | |
| /* highlight.js token colors (hand-written, GitHub-light inspired — | |
| avoids a second external stylesheet fetch on top of the @require'd | |
| JS, so there's nothing left for a page CSP to block) */ | |
| .hljs-comment, .hljs-quote { color: #6a737d; font-style: italic; } | |
| .hljs-keyword, .hljs-selector-tag, .hljs-subst { color: #d73a49; } | |
| .hljs-number, .hljs-literal, .hljs-variable, | |
| .hljs-template-variable, .hljs-tag .hljs-attr { color: #005cc5; } | |
| .hljs-string, .hljs-doctag { color: #032f62; } | |
| .hljs-title, .hljs-section, .hljs-selector-id, | |
| .hljs-class .hljs-title { color: #6f42c1; font-weight: 600; } | |
| .hljs-type { color: #6f42c1; } | |
| .hljs-tag, .hljs-name, .hljs-attribute { color: #22863a; font-weight: 500; } | |
| .hljs-regexp, .hljs-link { color: #032f62; } | |
| .hljs-symbol, .hljs-bullet { color: #e36209; } | |
| .hljs-built_in, .hljs-builtin-name { color: #005cc5; } | |
| .hljs-meta { color: #6a737d; } | |
| .hljs-deletion { background: #ffeef0; } | |
| .hljs-addition { background: #f0fff4; } | |
| .hljs-emphasis { font-style: italic; } | |
| .hljs-strong { font-weight: 700; } | |
| `; | |
| function escapeHtml(str) { | |
| return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); | |
| } | |
| // Turns pasted text containing ```-fenced sections into real <pre><code> | |
| // blocks; any surrounding plain text becomes normal paragraphs. | |
| function convertFencedText(text) { | |
| const lines = text.split(/\r\n|\r|\n/); | |
| let html = ''; | |
| let inCode = false; | |
| let codeLines = []; | |
| let lang = ''; | |
| for (const line of lines) { | |
| const fence = line.match(/^```\s*(\w*)\s*$/); | |
| if (fence) { | |
| if (!inCode) { | |
| inCode = true; | |
| lang = fence[1] || ''; | |
| codeLines = []; | |
| } else { | |
| inCode = false; | |
| const langAttr = lang ? ` data-lang="${escapeHtml(lang)}"` : ''; | |
| html += `<pre${langAttr}><code>${escapeHtml(codeLines.join('\n'))}</code></pre>`; | |
| } | |
| continue; | |
| } | |
| if (inCode) { | |
| codeLines.push(line); | |
| } else if (line.trim() === '') { | |
| html += '<p> </p>'; | |
| } else { | |
| html += `<p>${escapeHtml(line)}</p>`; | |
| } | |
| } | |
| if (inCode) { | |
| // Unclosed fence — still render what we have as a code block. | |
| html += `<pre><code>${escapeHtml(codeLines.join('\n'))}</code></pre>`; | |
| } | |
| return html; | |
| } | |
| // Walks up from a selection node to the nearest block-level ancestor | |
| // (handles cursor sitting inside a nested inline <span> etc). | |
| function getBlockElement(node, idoc) { | |
| let el = node && (node.nodeType === 3 ? node.parentElement : node); | |
| while (el && el !== idoc.body && !/^(P|DIV|LI|H1|H2|H3|H4|H5|H6|PRE|TD|TH)$/.test(el.tagName)) { | |
| el = el.parentElement; | |
| } | |
| return el; | |
| } | |
| function placeCaretInEmpty(el, idoc) { | |
| const range = idoc.createRange(); | |
| range.selectNodeContents(el); | |
| range.collapse(true); | |
| const sel = idoc.getSelection(); | |
| sel.removeAllRanges(); | |
| sel.addRange(range); | |
| } | |
| function replaceBlock(oldEl, newEl, idoc) { | |
| if (oldEl.replaceWith) oldEl.replaceWith(newEl); | |
| else oldEl.parentNode.replaceChild(newEl, oldEl); | |
| } | |
| function replaceWithList(block, idoc, listTag) { | |
| const list = idoc.createElement(listTag); | |
| const li = idoc.createElement('li'); | |
| li.innerHTML = '<br>'; | |
| list.appendChild(li); | |
| replaceBlock(block, list, idoc); | |
| placeCaretInEmpty(li, idoc); | |
| } | |
| // ------------------------------------------------------------------ | |
| // Syntax highlighting (highlight.js, loaded via @require above) | |
| // ------------------------------------------------------------------ | |
| function ensureHighlighter(idoc, callback) { | |
| // hljs is a global in the outer page's context (this script's own | |
| // context, since @grant is "none"), normally loaded synchronously by | |
| // Tampermonkey's @require before this IIFE runs. If that fetch never | |
| // succeeded (Tampermonkey caches @require resources and can silently | |
| // fail to fetch them), loadHljsFallback() below tries to self-load it | |
| // via fetch() + Function() evaluation instead — a separate code path | |
| // that doesn't depend on Tampermonkey's require-caching at all. | |
| if (typeof window.hljs !== 'undefined') callback(); | |
| } | |
| let hljsFallbackInFlight = false; | |
| function loadHljsFallback() { | |
| if (window.hljs || hljsFallbackInFlight) return; | |
| hljsFallbackInFlight = true; | |
| fetch('https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js') | |
| .then(function (r) { | |
| return r.text(); | |
| }) | |
| .then(function (src) { | |
| if (window.hljs) return; | |
| // Evaluate with explicit module/exports objects so highlight.js's | |
| // UMD wrapper takes its CommonJS branch and hands us the export | |
| // directly, rather than relying on it correctly self-attaching to | |
| // window/globalThis — that self-attachment was silently not | |
| // sticking in Tampermonkey's execution context (repeated identical | |
| // "loaded via fetch fallback" log lines with no error was the | |
| // giveaway: the eval kept "succeeding" but window.hljs never | |
| // actually persisted for the next check to see). | |
| const moduleObj = { exports: {} }; | |
| const factory = new Function('module', 'exports', src); | |
| factory(moduleObj, moduleObj.exports); | |
| const hljsExport = | |
| moduleObj.exports && moduleObj.exports.default ? moduleObj.exports.default : moduleObj.exports; | |
| if (hljsExport && typeof hljsExport.highlightElement === 'function') { | |
| window.hljs = hljsExport; | |
| console.log('[Synology Notes Markdown] highlight.js loaded via fetch fallback (captured via module.exports).'); | |
| } else if (window.hljs) { | |
| console.log('[Synology Notes Markdown] highlight.js loaded via fetch fallback (self-attached to window).'); | |
| } else { | |
| console.warn( | |
| '[Synology Notes Markdown] highlight.js evaluated but no usable export was found — reporting the value for debugging:', | |
| hljsExport | |
| ); | |
| } | |
| }) | |
| .catch(function (err) { | |
| console.warn( | |
| '[Synology Notes Markdown] highlight.js fetch fallback failed — will retry. Error:', | |
| err | |
| ); | |
| }) | |
| .finally(function () { | |
| hljsFallbackInFlight = false; | |
| }); | |
| } | |
| console.log('[Synology Notes Markdown] hljs available at startup via @require:', typeof window.hljs !== 'undefined'); | |
| loadHljsFallback(); | |
| // Highlights any <pre><code> not yet processed (used after paste / after | |
| // closing a freshly-typed block, and as a periodic safety net below). | |
| function highlightNewBlocks(idoc) { | |
| ensureHighlighter(idoc, function () { | |
| const blocks = idoc.querySelectorAll('pre > code:not([data-hljs-done])'); | |
| blocks.forEach(function (codeEl) { | |
| const pre = codeEl.parentElement; | |
| const lang = pre.getAttribute('data-lang'); | |
| if (lang) codeEl.className = 'language-' + lang; | |
| delete codeEl.dataset.highlighted; // see note in scheduleHighlight | |
| window.hljs.highlightElement(codeEl); | |
| codeEl.setAttribute('data-hljs-done', '1'); | |
| }); | |
| }); | |
| } | |
| // Caret position saved/restored as a plain character offset within the | |
| // <code> element's text, so re-highlighting (which rewrites innerHTML) | |
| // doesn't throw the cursor to the end of the block. | |
| function saveCaretOffset(codeEl, idoc) { | |
| const sel = idoc.getSelection(); | |
| if (!sel || sel.rangeCount === 0) return 0; | |
| const range = sel.getRangeAt(0); | |
| const preRange = range.cloneRange(); | |
| preRange.selectNodeContents(codeEl); | |
| preRange.setEnd(range.endContainer, range.endOffset); | |
| return preRange.toString().length; | |
| } | |
| function restoreCaretOffset(codeEl, idoc, offset) { | |
| const sel = idoc.getSelection(); | |
| const range = idoc.createRange(); | |
| let remaining = offset; | |
| let found = false; | |
| (function walk(node) { | |
| if (found) return; | |
| if (node.nodeType === 3) { | |
| const len = node.textContent.length; | |
| if (remaining <= len) { | |
| range.setStart(node, remaining); | |
| range.collapse(true); | |
| found = true; | |
| } else { | |
| remaining -= len; | |
| } | |
| } else { | |
| for (let i = 0; i < node.childNodes.length && !found; i++) walk(node.childNodes[i]); | |
| } | |
| })(codeEl); | |
| if (!found) { | |
| range.selectNodeContents(codeEl); | |
| range.collapse(false); | |
| } | |
| sel.removeAllRanges(); | |
| sel.addRange(range); | |
| } | |
| function scheduleHighlight(codeEl, pre, idoc) { | |
| clearTimeout(codeEl._hlTimer); | |
| codeEl._hlTimer = setTimeout(function () { | |
| ensureHighlighter(idoc, function () { | |
| const offset = saveCaretOffset(codeEl, idoc); | |
| const lang = pre.getAttribute('data-lang'); | |
| if (lang) codeEl.className = 'language-' + lang; | |
| // Strip any spans from the previous highlight pass back down to | |
| // plain text first — calling highlightElement() on an element | |
| // that still has child <span> markup from an earlier pass is | |
| // what triggers highlight.js's "unescaped HTML" security warning | |
| // in the console (harmless here, since the text was always | |
| // properly escaped, but worth avoiding). | |
| codeEl.textContent = codeEl.textContent; | |
| // highlight.js v11 marks an element data-highlighted="yes" after | |
| // highlighting it once, and refuses to re-highlight that same | |
| // element again unless this is explicitly cleared first — without | |
| // this, every highlight pass after the very first one on a given | |
| // block gets silently skipped by highlight.js itself. | |
| delete codeEl.dataset.highlighted; | |
| window.hljs.highlightElement(codeEl); | |
| codeEl.setAttribute('data-hljs-done', '1'); | |
| restoreCaretOffset(codeEl, idoc, offset); | |
| }); | |
| }, 400); // wait for a pause in typing before re-rendering | |
| } | |
| function bindLiveHighlighting(idoc) { | |
| idoc.addEventListener('input', function () { | |
| const sel = idoc.getSelection(); | |
| const block = getBlockElement(sel && sel.anchorNode, idoc); | |
| const pre = block && block.closest && block.closest('pre'); | |
| if (!pre) return; | |
| const codeEl = pre.querySelector('code'); | |
| if (!codeEl) return; | |
| scheduleHighlight(codeEl, pre, idoc); | |
| }); | |
| } | |
| // ------------------------------------------------------------------ | |
| // Inline markdown shortcuts: **bold**, *italic*/_italic_, `code`, | |
| // [text](url) — converted the moment the closing marker is typed. | |
| // ------------------------------------------------------------------ | |
| // Finds the (node, offset) pair `charOffset` characters into `el`'s | |
| // flattened text — the counterpart to saveCaretOffset, but returning a | |
| // position instead of moving the live selection there. | |
| function getNodeAndOffset(el, charOffset) { | |
| let remaining = charOffset; | |
| let result = null; | |
| (function walk(node) { | |
| if (result) return; | |
| if (node.nodeType === 3) { | |
| const len = node.textContent.length; | |
| if (remaining <= len) { | |
| result = { node: node, offset: remaining }; | |
| } else { | |
| remaining -= len; | |
| } | |
| } else { | |
| for (let i = 0; i < node.childNodes.length && !result; i++) walk(node.childNodes[i]); | |
| } | |
| })(el); | |
| if (!result) result = { node: el, offset: el.childNodes.length }; | |
| return result; | |
| } | |
| // Places the caret in a fresh zero-width text node right after `node`, | |
| // so typing afterwards doesn't inherit the bold/italic/code/link | |
| // formatting we just applied. | |
| function placeCaretAfterNode(node, idoc) { | |
| const spacer = idoc.createTextNode('\u200B'); | |
| node.parentNode.insertBefore(spacer, node.nextSibling); | |
| const range = idoc.createRange(); | |
| range.setStart(spacer, 1); | |
| range.collapse(true); | |
| const sel = idoc.getSelection(); | |
| sel.removeAllRanges(); | |
| sel.addRange(range); | |
| } | |
| function replaceRangeWithElement(block, idoc, start, end, tagName, innerText) { | |
| const startPos = getNodeAndOffset(block, start); | |
| const endPos = getNodeAndOffset(block, end); | |
| const range = idoc.createRange(); | |
| range.setStart(startPos.node, startPos.offset); | |
| range.setEnd(endPos.node, endPos.offset); | |
| range.deleteContents(); | |
| const el = idoc.createElement(tagName); | |
| el.textContent = innerText; | |
| range.insertNode(el); | |
| placeCaretAfterNode(el, idoc); | |
| } | |
| function replaceRangeWithLink(block, idoc, start, end, text, url) { | |
| const startPos = getNodeAndOffset(block, start); | |
| const endPos = getNodeAndOffset(block, end); | |
| const range = idoc.createRange(); | |
| range.setStart(startPos.node, startPos.offset); | |
| range.setEnd(endPos.node, endPos.offset); | |
| range.deleteContents(); | |
| const a = idoc.createElement('a'); | |
| a.textContent = text; | |
| a.href = /^https?:\/\//i.test(url) ? url : 'https://' + url; | |
| range.insertNode(a); | |
| placeCaretAfterNode(a, idoc); | |
| } | |
| // Checked in order — bold before italic so "**bold**" doesn't get | |
| // half-converted to italic while the second closing "*" is still being | |
| // typed (the negative lookbehinds stop an in-progress "**" from ever | |
| // matching the single-marker italic/underscore patterns). | |
| const INLINE_PATTERNS = [ | |
| { re: /(?<!\*)\*\*([^*\n]+)\*\*$/, tag: 'strong' }, | |
| { re: /(?<!_)__([^_\n]+)__$/, tag: 'strong' }, | |
| { re: /(?<!\*)\*([^*\n]+)\*$/, tag: 'em' }, | |
| { re: /(?<!_)_([^_\n]+)_$/, tag: 'em' }, | |
| { re: /(?<!`)`([^`\n]+)`$/, tag: 'code' }, | |
| ]; | |
| function tryInlineMarkdown(block, idoc) { | |
| const sel = idoc.getSelection(); | |
| if (!sel || !sel.isCollapsed) return; | |
| const caretOffset = saveCaretOffset(block, idoc); | |
| const before = block.textContent.slice(0, caretOffset); | |
| for (let i = 0; i < INLINE_PATTERNS.length; i++) { | |
| const m = before.match(INLINE_PATTERNS[i].re); | |
| if (m) { | |
| const matchStart = caretOffset - m[0].length; | |
| replaceRangeWithElement(block, idoc, matchStart, caretOffset, INLINE_PATTERNS[i].tag, m[1]); | |
| return; | |
| } | |
| } | |
| const linkMatch = before.match(/\[([^\]\n]+)\]\(([^)\n]+)\)$/); | |
| if (linkMatch) { | |
| const matchStart = caretOffset - linkMatch[0].length; | |
| replaceRangeWithLink(block, idoc, matchStart, caretOffset, linkMatch[1], linkMatch[2]); | |
| } | |
| } | |
| function bindInlineMarkdown(idoc) { | |
| idoc.addEventListener('input', function (e) { | |
| if (!e.data || ['*', '_', '`', ')'].indexOf(e.data) === -1) return; | |
| const sel = idoc.getSelection(); | |
| const block = getBlockElement(sel && sel.anchorNode, idoc); | |
| if (!block || (block.closest && block.closest('pre'))) return; | |
| tryInlineMarkdown(block, idoc); | |
| }); | |
| } | |
| // Paste handling, the "type ``` then Enter" shortcut, and Backspace | |
| // handling to let you delete a code block, bound once per editor iframe | |
| // document (guarded so note-switches don't double-bind). | |
| function bindCodeBlockBehavior(idoc) { | |
| if (idoc.body.dataset.ccbBound) return; | |
| idoc.body.dataset.ccbBound = '1'; | |
| idoc.addEventListener( | |
| 'paste', | |
| function (e) { | |
| const cd = e.clipboardData || idoc.defaultView.clipboardData; | |
| const text = cd ? cd.getData('text/plain') : ''; | |
| if (!text || text.indexOf('```') === -1) return; // normal paste, let it through | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| idoc.execCommand('insertHTML', false, convertFencedText(text)); | |
| highlightNewBlocks(idoc); | |
| }, | |
| true | |
| ); | |
| // Bound in the CAPTURE phase so this runs *before* TinyMCE's own | |
| // Enter/Tab/Backspace handling on the editor body — otherwise TinyMCE | |
| // intercepts and stops the event first and our handler never sees it. | |
| idoc.addEventListener( | |
| 'keydown', | |
| function (e) { | |
| if (e.key === 'Tab') { | |
| const sel = idoc.getSelection(); | |
| const el = getBlockElement(sel && sel.anchorNode, idoc); | |
| if (el && el.closest && el.closest('pre')) { | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| idoc.execCommand('insertHTML', false, '	'); | |
| } | |
| return; | |
| } | |
| if (e.key === 'Backspace') { | |
| const sel = idoc.getSelection(); | |
| if (!sel || !sel.isCollapsed) return; // let default handle real selections | |
| const block = getBlockElement(sel.anchorNode, idoc); | |
| const preAncestor = block && block.closest && block.closest('pre'); | |
| if (!preAncestor) return; | |
| const codeEl = preAncestor.querySelector('code') || preAncestor; | |
| if (saveCaretOffset(codeEl, idoc) !== 0) return; // not at the very start — normal backspace inside the block | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| const prev = preAncestor.previousElementSibling; | |
| preAncestor.remove(); | |
| const range = idoc.createRange(); | |
| if (prev) { | |
| range.selectNodeContents(prev); | |
| range.collapse(false); | |
| } else { | |
| const p = idoc.createElement('p'); | |
| p.innerHTML = '<br>'; | |
| idoc.body.insertBefore(p, idoc.body.firstChild); | |
| range.selectNodeContents(p); | |
| range.collapse(true); | |
| } | |
| sel.removeAllRanges(); | |
| sel.addRange(range); | |
| return; | |
| } | |
| // Block-level markdown markers, converted the moment you hit the | |
| // space right after typing them on an otherwise-empty line. | |
| if (e.key === ' ') { | |
| const sel = idoc.getSelection(); | |
| if (!sel || sel.rangeCount === 0) return; | |
| const block = getBlockElement(sel.anchorNode, idoc); | |
| if (!block || (block.closest && block.closest('pre'))) return; | |
| const text = block.textContent; | |
| const headingMatch = text.match(/^(#{1,6})$/); | |
| if (headingMatch) { | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| const h = idoc.createElement('h' + headingMatch[1].length); | |
| h.innerHTML = '<br>'; | |
| replaceBlock(block, h, idoc); | |
| placeCaretInEmpty(h, idoc); | |
| return; | |
| } | |
| if (/^[-*]$/.test(text)) { | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| replaceWithList(block, idoc, 'ul'); | |
| return; | |
| } | |
| if (/^\d+\.$/.test(text)) { | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| replaceWithList(block, idoc, 'ol'); | |
| return; | |
| } | |
| if (text === '>') { | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| const bq = idoc.createElement('blockquote'); | |
| bq.innerHTML = '<br>'; | |
| replaceBlock(block, bq, idoc); | |
| placeCaretInEmpty(bq, idoc); | |
| return; | |
| } | |
| return; | |
| } | |
| if (e.key !== 'Enter' || e.shiftKey) return; | |
| const sel = idoc.getSelection(); | |
| if (!sel || sel.rangeCount === 0) return; | |
| const block = getBlockElement(sel.anchorNode, idoc); | |
| if (!block) return; | |
| const preAncestor = block.closest && block.closest('pre'); | |
| // Inside an existing code block: everything here is scoped to the | |
| // *current line*, not block.textContent — getBlockElement() | |
| // resolves to the <pre> itself once you're inside one (by design, | |
| // so preAncestor detection works), which means block.textContent | |
| // is the block's ENTIRE multi-line content. Checking that against | |
| // "is this line just \`\`\`" was the bug: it only ever matched on an | |
| // empty code block, so every Enter on a real multi-line block fell | |
| // through with no handling and hit the browser's own default | |
| // Enter-in-<pre> behavior — which tends to fragment/split the | |
| // block instead of inserting a clean newline. Fixed by computing | |
| // the actual current line from the last \n before the caret, and | |
| // by inserting newlines ourselves rather than ever letting the | |
| // browser touch Enter inside a <pre>. | |
| if (preAncestor) { | |
| const codeEl = preAncestor.querySelector('code') || preAncestor; | |
| // Defensively collapse first: if the selection is ever | |
| // non-collapsed here for any reason (a lingering autocomplete/ | |
| // spellcheck selection, etc.), range.deleteContents() further | |
| // down would silently delete whatever was selected — which is | |
| // exactly what intermittently wiped out the first line typed | |
| // into a fresh code block. Collapsing to the end guarantees we | |
| // only ever insert, never accidentally delete real content. | |
| if (!sel.isCollapsed) sel.collapseToEnd(); | |
| const caretOffset = saveCaretOffset(codeEl, idoc); | |
| const fullText = codeEl.textContent; | |
| const lastNewline = fullText.lastIndexOf('\n', caretOffset - 1); | |
| const currentLine = fullText.slice(lastNewline + 1, caretOffset).trim(); | |
| if (currentLine === '```') { | |
| // Close the code block: drop the ``` line, keep everything before it. | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| const beforeFence = fullText.slice(0, lastNewline + 1).replace(/\n$/, ''); | |
| codeEl.textContent = beforeFence; | |
| highlightNewBlocks(idoc); | |
| const p = idoc.createElement('p'); | |
| p.innerHTML = '<br>'; | |
| preAncestor.parentNode.insertBefore(p, preAncestor.nextSibling); | |
| const range = idoc.createRange(); | |
| range.setStart(p, 0); | |
| range.collapse(true); | |
| sel.removeAllRanges(); | |
| sel.addRange(range); | |
| return; | |
| } | |
| // Otherwise: a normal newline while continuing to type code — | |
| // insert a literal "\n" character ourselves. | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| const range = sel.getRangeAt(0); | |
| range.collapse(false); // belt-and-braces: guarantee a zero-length range before insertNode | |
| const newlineNode = idoc.createTextNode('\n'); | |
| range.insertNode(newlineNode); | |
| const after = idoc.createRange(); | |
| after.setStartAfter(newlineNode); | |
| after.collapse(true); | |
| sel.removeAllRanges(); | |
| sel.addRange(after); | |
| scheduleHighlight(codeEl, preAncestor, idoc); | |
| return; | |
| } | |
| const text = (block.textContent || '').trim(); | |
| // Horizontal rule: a line that's just --- or *** on its own | |
| if (/^(-{3,}|\*{3,})$/.test(text)) { | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| const hr = idoc.createElement('hr'); | |
| replaceBlock(block, hr, idoc); | |
| const p = idoc.createElement('p'); | |
| p.innerHTML = '<br>'; | |
| hr.parentNode.insertBefore(p, hr.nextSibling); | |
| const range = idoc.createRange(); | |
| range.setStart(p, 0); | |
| range.collapse(true); | |
| sel.removeAllRanges(); | |
| sel.addRange(range); | |
| return; | |
| } | |
| // Open a code block: current line is exactly ``` or ```lang | |
| const openMatch = text.match(/^```(\w*)$/); | |
| if (openMatch) { | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| const pre = idoc.createElement('pre'); | |
| if (openMatch[1]) pre.setAttribute('data-lang', openMatch[1]); | |
| const code = idoc.createElement('code'); | |
| code.innerHTML = '<br>'; | |
| pre.appendChild(code); | |
| replaceBlock(block, pre, idoc); | |
| const range = idoc.createRange(); | |
| range.selectNodeContents(code); | |
| range.collapse(true); | |
| sel.removeAllRanges(); | |
| sel.addRange(range); | |
| } | |
| }, | |
| true // capture phase — see note above | |
| ); | |
| bindLiveHighlighting(idoc); | |
| bindInlineMarkdown(idoc); | |
| } | |
| // ------------------------------------------------------------------ | |
| // Markdown source view: converts the note's HTML to/from plain | |
| // markdown text so you can view or edit it as raw markdown instead of | |
| // the rendered WYSIWYG. Intentionally covers only what this script | |
| // itself understands (headings, bold/italic/code, lists, blockquotes, | |
| // links, hr, fenced code) — anything else (tables, images, text | |
| // colors, nested lists) gets simplified or dropped on round-trip. | |
| // ------------------------------------------------------------------ | |
| function inlineNodeToMarkdown(node) { | |
| if (node.nodeType === 3) return node.textContent; | |
| if (node.nodeType !== 1) return ''; | |
| const inner = Array.prototype.map | |
| .call(node.childNodes, inlineNodeToMarkdown) | |
| .join(''); | |
| switch (node.tagName) { | |
| case 'STRONG': | |
| case 'B': | |
| return '**' + inner + '**'; | |
| case 'EM': | |
| case 'I': | |
| return '*' + inner + '*'; | |
| case 'CODE': | |
| return '`' + inner + '`'; | |
| case 'A': | |
| return '[' + inner + '](' + (node.getAttribute('href') || '') + ')'; | |
| case 'BR': | |
| return '\n'; | |
| case 'INPUT': | |
| return node.type === 'checkbox' ? (node.checked ? '[x] ' : '[ ] ') : ''; | |
| default: | |
| return inner; // unwrap anything we don't specifically model (spans, colors, etc.) | |
| } | |
| } | |
| function blockToMarkdown(el) { | |
| const inline = function (node) { | |
| return Array.prototype.map.call(node.childNodes, inlineNodeToMarkdown).join('').trim(); | |
| }; | |
| switch (el.tagName) { | |
| case 'H1': | |
| case 'H2': | |
| case 'H3': | |
| case 'H4': | |
| case 'H5': | |
| case 'H6': | |
| return '#'.repeat(Number(el.tagName[1])) + ' ' + inline(el); | |
| case 'PRE': { | |
| const code = el.querySelector('code') || el; | |
| const lang = el.getAttribute('data-lang') || ''; | |
| // Read the live code.textContent directly, not a cached snapshot — | |
| // .textContent correctly concatenates all text regardless of | |
| // highlight.js's <span> wrapping, and is always current. A prior | |
| // version of this cached a "data-raw" snapshot instead, hoping to | |
| // sidestep highlighting entirely, but that snapshot could itself | |
| // fall out of sync with the live (correct) content, which is | |
| // exactly what happened — worse than the problem it aimed to fix. | |
| return '```' + lang + '\n' + code.textContent + '\n```'; | |
| } | |
| case 'UL': | |
| return Array.prototype.map | |
| .call(el.children, function (li) { | |
| return '- ' + inline(li); | |
| }) | |
| .join('\n'); | |
| case 'OL': | |
| return Array.prototype.map | |
| .call(el.children, function (li, i) { | |
| return i + 1 + '. ' + inline(li); | |
| }) | |
| .join('\n'); | |
| case 'BLOCKQUOTE': | |
| return inline(el) | |
| .split('\n') | |
| .map(function (line) { | |
| return '> ' + line; | |
| }) | |
| .join('\n'); | |
| case 'HR': | |
| return '---'; | |
| default: | |
| return inline(el); // P, DIV, etc. | |
| } | |
| } | |
| function htmlToMarkdown(idoc) { | |
| const children = Array.prototype.slice.call(idoc.body.children); | |
| let out = ''; | |
| let prevWasPlainParagraph = false; | |
| let sawBlankLine = false; | |
| children.forEach(function (el) { | |
| const isPlainParagraph = el.tagName === 'P' || el.tagName === 'DIV'; | |
| const md = blockToMarkdown(el); | |
| if (md === '') { | |
| // An empty paragraph/div is a genuine blank line (the user pressed | |
| // Enter twice to add intentional spacing) — remember it so the | |
| // *next* real block gets a proper paragraph-break gap, instead of | |
| // this being silently dropped (which used to erase deliberately- | |
| // spaced paragraphs entirely) or tight-joined across the gap. | |
| sawBlankLine = true; | |
| return; | |
| } | |
| if (out !== '') { | |
| // Tight-join two consecutive plain paragraph lines with a single | |
| // newline (Note Station renders adjacent lines tight by default, | |
| // "Shift+Enter style") — UNLESS an intentional blank line separated | |
| // them, or we're transitioning to/from a "special" block type | |
| // (heading, list, quote, code, hr), either of which gets a real | |
| // paragraph-break gap instead. | |
| out += sawBlankLine || !(isPlainParagraph && prevWasPlainParagraph) ? '\n\n' : '\n'; | |
| } | |
| out += md; | |
| prevWasPlainParagraph = isPlainParagraph; | |
| sawBlankLine = false; | |
| }); | |
| return out; | |
| } | |
| function mdInlineToHtml(text) { | |
| let out = escapeHtml(text); | |
| out = out.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>'); | |
| out = out.replace(/__([^_]+)__/g, '<strong>$1</strong>'); | |
| out = out.replace(/`([^`]+)`/g, '<code>$1</code>'); | |
| out = out.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>'); | |
| out = out.replace(/\*([^*]+)\*/g, '<em>$1</em>'); | |
| out = out.replace(/_([^_]+)_/g, '<em>$1</em>'); | |
| return out; | |
| } | |
| function markdownToHtml(text) { | |
| const lines = text.split(/\r\n|\r|\n/); | |
| let html = ''; | |
| let i = 0; | |
| while (i < lines.length) { | |
| const line = lines[i]; | |
| const fenceMatch = line.match(/^```\s*(\w*)\s*$/); | |
| if (fenceMatch) { | |
| const lang = fenceMatch[1] || ''; | |
| const codeLines = []; | |
| i++; | |
| while (i < lines.length && !/^```\s*$/.test(lines[i])) { | |
| codeLines.push(lines[i]); | |
| i++; | |
| } | |
| i++; // skip closing fence | |
| const langAttr = lang ? ` data-lang="${escapeHtml(lang)}"` : ''; | |
| html += `<pre${langAttr}><code>${escapeHtml(codeLines.join('\n'))}</code></pre>`; | |
| continue; | |
| } | |
| const headingMatch = line.match(/^(#{1,6})\s+(.*)$/); | |
| if (headingMatch) { | |
| const level = headingMatch[1].length; | |
| html += `<h${level}>${mdInlineToHtml(headingMatch[2])}</h${level}>`; | |
| i++; | |
| continue; | |
| } | |
| if (/^(-{3,}|\*{3,})$/.test(line.trim())) { | |
| html += '<hr>'; | |
| i++; | |
| continue; | |
| } | |
| if (/^[-*]\s+.+/.test(line)) { | |
| let items = ''; | |
| while (i < lines.length && /^[-*]\s+.+/.test(lines[i])) { | |
| const m = lines[i].match(/^[-*]\s+(.*)$/); | |
| const taskMatch = m[1].match(/^\[( |x|X)\]\s*(.*)$/); | |
| if (taskMatch) { | |
| const checked = /x/i.test(taskMatch[1]) ? ' checked' : ''; | |
| items += `<li><input type="checkbox"${checked}> ${mdInlineToHtml(taskMatch[2])}</li>`; | |
| } else { | |
| items += `<li>${mdInlineToHtml(m[1])}</li>`; | |
| } | |
| i++; | |
| } | |
| html += `<ul>${items}</ul>`; | |
| continue; | |
| } | |
| if (/^\d+\.\s+.+/.test(line)) { | |
| let items = ''; | |
| while (i < lines.length && /^\d+\.\s+.+/.test(lines[i])) { | |
| const m = lines[i].match(/^\d+\.\s+(.*)$/); | |
| items += `<li>${mdInlineToHtml(m[1])}</li>`; | |
| i++; | |
| } | |
| html += `<ol>${items}</ol>`; | |
| continue; | |
| } | |
| if (/^>\s?.*/.test(line)) { | |
| const quoteLines = []; | |
| while (i < lines.length && /^>\s?.*/.test(lines[i])) { | |
| quoteLines.push(lines[i].replace(/^>\s?/, '')); | |
| i++; | |
| } | |
| html += `<blockquote>${quoteLines.map(mdInlineToHtml).join('<br>')}</blockquote>`; | |
| continue; | |
| } | |
| if (line.trim() === '') { | |
| i++; | |
| continue; | |
| } | |
| const paraLines = []; | |
| while ( | |
| i < lines.length && | |
| lines[i].trim() !== '' && | |
| !/^```/.test(lines[i]) && | |
| !/^#{1,6}\s/.test(lines[i]) && | |
| !/^[-*]\s+.+/.test(lines[i]) && | |
| !/^\d+\.\s+.+/.test(lines[i]) && | |
| !/^>\s?/.test(lines[i]) && | |
| !/^(-{3,}|\*{3,})$/.test(lines[i].trim()) | |
| ) { | |
| paraLines.push(lines[i]); | |
| i++; | |
| } | |
| html += `<p>${paraLines.map(mdInlineToHtml).join('<br>')}</p>`; | |
| } | |
| return html || '<p><br></p>'; | |
| } | |
| let sourceOverlay = null; | |
| function findEditorIframe() { | |
| return document.querySelector('.syno-ns-editor-normal-panel iframe, .mce-edit-area iframe'); | |
| } | |
| function makeToolbarButton(label, onClick, primary) { | |
| const b = document.createElement('button'); | |
| b.textContent = label; | |
| b.style.cssText = | |
| 'padding:4px 12px;border:1px solid rgb(223,225,228);cursor:pointer;font-size:13px;' + | |
| (primary ? 'background:rgb(8,109,214);color:#fff;' : 'background:#fff;color:rgb(55,53,47);'); | |
| b.addEventListener('click', onClick); | |
| return b; | |
| } | |
| function closeSourceOverlay() { | |
| if (sourceOverlay) { | |
| sourceOverlay.remove(); | |
| sourceOverlay = null; | |
| } | |
| } | |
| function openSourceView() { | |
| const iframe = findEditorIframe(); | |
| if (!iframe) return; | |
| const idoc = iframe.contentDocument; | |
| if (!idoc) return; | |
| const markdown = htmlToMarkdown(idoc); | |
| const rect = iframe.getBoundingClientRect(); | |
| const wrap = document.createElement('div'); | |
| wrap.style.cssText = | |
| `position:fixed;top:${rect.top}px;left:${rect.left}px;width:${rect.width}px;` + | |
| `height:${rect.height}px;z-index:100000;background:#fff;display:flex;flex-direction:column;` + | |
| 'border:1px solid rgb(223,225,228);box-shadow:0 4px 16px rgba(0,0,0,0.15);'; | |
| const toolbar = document.createElement('div'); | |
| toolbar.style.cssText = | |
| 'display:flex;align-items:center;gap:8px;padding:6px 8px;border-bottom:1px solid rgb(223,225,228);' + | |
| 'background:#fafafa;font-family:-apple-system,BlinkMacSystemFont,sans-serif;font-size:13px;'; | |
| const textarea = document.createElement('textarea'); | |
| textarea.value = markdown; | |
| textarea.style.cssText = | |
| 'flex:1;border:none;outline:none;resize:none;padding:12px 14px;' + | |
| "font-family:'SFMono-Regular',Consolas,Menlo,monospace;font-size:13px;line-height:1.5;white-space:pre;"; | |
| const applyBtn = makeToolbarButton( | |
| 'Apply & Close', | |
| function () { | |
| idoc.body.innerHTML = markdownToHtml(textarea.value); | |
| // Nudge NoteStation's change/autosave detection — direct innerHTML | |
| // writes don't fire a native 'input' event the way real typing | |
| // does, so this may or may not be enough on its own. Verify the | |
| // note actually saves before relying on this. | |
| idoc.body.dispatchEvent(new Event('input', { bubbles: true })); | |
| highlightNewBlocks(idoc); | |
| closeSourceOverlay(); | |
| }, | |
| true | |
| ); | |
| const cancelBtn = makeToolbarButton('Cancel', closeSourceOverlay, false); | |
| const copyBtn = makeToolbarButton( | |
| 'Copy', | |
| function () { | |
| navigator.clipboard.writeText(textarea.value).catch(function () {}); | |
| }, | |
| false | |
| ); | |
| const hint = document.createElement('span'); | |
| hint.textContent = 'Raw markdown — nested lists / colors / tables are simplified'; | |
| hint.style.cssText = 'color:#888;margin-left:auto;'; | |
| toolbar.appendChild(applyBtn); | |
| toolbar.appendChild(cancelBtn); | |
| toolbar.appendChild(copyBtn); | |
| toolbar.appendChild(hint); | |
| wrap.appendChild(toolbar); | |
| wrap.appendChild(textarea); | |
| document.body.appendChild(wrap); | |
| sourceOverlay = wrap; | |
| textarea.focus(); | |
| } | |
| function createMarkdownToggleButton() { | |
| if (document.getElementById('synology-notes-md-toggle-btn')) return; | |
| const btn = document.createElement('button'); | |
| btn.id = 'synology-notes-md-toggle-btn'; | |
| btn.textContent = '</> Markdown'; | |
| btn.style.cssText = | |
| 'position:fixed;bottom:16px;right:16px;z-index:99999;padding:8px 14px;' + | |
| 'background:rgb(8,109,214);color:#fff;border:none;cursor:pointer;' + | |
| "font-family:-apple-system,BlinkMacSystemFont,sans-serif;font-size:13px;" + | |
| 'box-shadow:0 2px 8px rgba(0,0,0,0.2);'; | |
| btn.addEventListener('click', function () { | |
| if (sourceOverlay) closeSourceOverlay(); | |
| else openSourceView(); | |
| }); | |
| document.body.appendChild(btn); | |
| } | |
| function setupEditorIframe() { | |
| const iframe = document.querySelector( | |
| '.syno-ns-editor-normal-panel iframe, .mce-edit-area iframe' | |
| ); | |
| if (!iframe) return; | |
| try { | |
| const idoc = iframe.contentDocument; | |
| if (!idoc) return; | |
| let editorStyle = idoc.getElementById('synology-notes-code-editor-tampermonkey'); | |
| if (!editorStyle) { | |
| editorStyle = idoc.createElement('style'); | |
| editorStyle.id = 'synology-notes-code-editor-tampermonkey'; | |
| idoc.head.appendChild(editorStyle); | |
| } | |
| if (editorStyle.textContent !== editorCss) { | |
| editorStyle.textContent = editorCss; | |
| } | |
| if (idoc.body) { | |
| bindCodeBlockBehavior(idoc); | |
| highlightNewBlocks(idoc); // catches blocks already in the note on load | |
| } | |
| } catch (e) { | |
| // Iframe not same-origin or not ready yet — safe to ignore. | |
| } | |
| } | |
| new MutationObserver(setupEditorIframe).observe(document.body, { | |
| childList: true, | |
| subtree: true, | |
| }); | |
| setupEditorIframe(); | |
| createMarkdownToggleButton(); | |
| // Periodic safety net: sweeps for any un-highlighted code blocks every | |
| // couple of seconds, independent of the input-event-driven live | |
| // highlighting. Cheap (skips anything already marked data-hljs-done), | |
| // and covers cases where a block's content changed in a way that | |
| // doesn't fire a native 'input' event, or where the debounced | |
| // highlight for some reason didn't fire. | |
| setInterval(function () { | |
| if (!window.hljs) loadHljsFallback(); | |
| const iframe = document.querySelector( | |
| '.syno-ns-editor-normal-panel iframe, .mce-edit-area iframe' | |
| ); | |
| if (!iframe) return; | |
| try { | |
| const idoc = iframe.contentDocument; | |
| if (idoc && idoc.body) highlightNewBlocks(idoc); | |
| } catch (e) { | |
| // Iframe not same-origin or not ready — safe to ignore. | |
| } | |
| }, 2000); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment