Lint / JS (eslint) (push) Successful in 17s
Lint / PHP requirements (version + extensions) (push) Successful in 39s
Lint / JS (eslint) (pull_request) Successful in 33s
Lint / PHP (phpcs PSR-12) (pull_request) Successful in 1m3s
Lint / PHP requirements (version + extensions) (pull_request) Successful in 58s
Lint / Deploy (pull_request) Skipped
Lint / Notify on failure (pull_request) Skipped
Security / PHP Security (semgrep) (push) Successful in 2m52s
Security / PHP Security (semgrep) (pull_request) Successful in 3m2s
Lint / PHP (phpcs PSR-12) (push) Successful in 48s
Lint / Deploy (push) Skipped
Lint / Notify on failure (push) Skipped
The ticket page escaped descriptions to plain text, so headings, lists, tables, bold and code from Gandalf, MCP and manual tickets showed raw. renderDescriptionView() now uses parseMarkdown(), the same sanitising parser as comments, and the view drops pre-wrap for normal white space like markdown comments do. The edit view still shows the raw source. The parser also no longer treats underscores inside words as emphasis, so identifiers like node_network_up stay literal (in comments too). hwmonDaemon's fixed-width box layout loses its alignment as markdown; LotusGuild/hwmonDaemon#38 switches it to markdown and converts its past tickets. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
660 lines
25 KiB
JavaScript
660 lines
25 KiB
JavaScript
/**
|
||
* Simple Markdown Parser for Tinker Tickets
|
||
* Supports basic markdown formatting without external dependencies
|
||
*/
|
||
|
||
function parseMarkdown(markdown) {
|
||
if (!markdown) return '';
|
||
|
||
// Footnote labels are captured before the HTML-escape pass, so they must be
|
||
// sanitized to a safe slug before being interpolated into id/href attributes
|
||
// (otherwise a label like `x"><img onerror=...>` breaks out → stored XSS).
|
||
var fnSlug = function (label) {
|
||
return String(label).replace(/[^a-zA-Z0-9_-]/g, '-');
|
||
};
|
||
|
||
// Footnotes — collect definitions and mark references with placeholders
|
||
// (must happen before HTML escaping so <sup> tags don't get escaped)
|
||
const footnotes = {};
|
||
const footnoteOrder = [];
|
||
const fnRefs = [];
|
||
markdown = markdown.replace(/^\[\^([^\]]+)\]:\s+(.+)$/gm, function(_, label, text) {
|
||
footnotes[label] = text;
|
||
return '';
|
||
});
|
||
markdown = markdown.replace(/\[\^([^\]]+)\]/g, function(_, label) {
|
||
if (!footnotes[label]) return '[^' + label + ']';
|
||
if (!footnoteOrder.includes(label)) footnoteOrder.push(label);
|
||
const n = footnoteOrder.indexOf(label) + 1;
|
||
fnRefs.push({ label, n });
|
||
return '%%FNREF' + (fnRefs.length - 1) + '%%';
|
||
});
|
||
|
||
let html = markdown;
|
||
|
||
// Escape HTML first to prevent XSS. Quotes MUST be escaped too: user-controlled
|
||
// text (e.g. image/link URLs and alt text) is later interpolated into "..."
|
||
// attributes, so an unescaped " would break out and inject event handlers.
|
||
html = html.replace(/&/g, '&')
|
||
.replace(/</g, '<')
|
||
.replace(/>/g, '>')
|
||
.replace(/"/g, '"')
|
||
.replace(/'/g, ''');
|
||
|
||
// Code blocks (```lang\ncode\n```) - preserve content and don't process further
|
||
const codeBlocks = [];
|
||
html = html.replace(/```([a-zA-Z0-9_+-]*)\n?([\s\S]*?)```/g, function(match, lang, code) {
|
||
lang = lang ? lang.trim() : '';
|
||
const displayLang = lang || 'text';
|
||
|
||
// Build header with optional copy button if one exists in your UI, otherwise just lang
|
||
const header = '<div class="lt-code-header"><span class="lt-code-lang">' + displayLang + '</span></div>';
|
||
|
||
// Remove exactly one trailing newline from code block if it exists
|
||
if (code.endsWith('\n')) {
|
||
code = code.slice(0, -1);
|
||
}
|
||
|
||
// Wrap in the specific UI classes expected by base.css
|
||
codeBlocks.push('<div class="lt-code-block">' + header + '<pre><code>' + code + '</code></pre></div>');
|
||
return '%%CODEBLOCK' + (codeBlocks.length - 1) + '%%';
|
||
});
|
||
|
||
// Inline code (`code`) - preserve and don't process further
|
||
const inlineCodes = [];
|
||
html = html.replace(/`([^`]+)`/g, function(match, code) {
|
||
inlineCodes.push('<code class="inline-code">' + code + '</code>');
|
||
return '%%INLINECODE' + (inlineCodes.length - 1) + '%%';
|
||
});
|
||
|
||
// Ticket references (#123456789) - convert to clickable links.
|
||
// Runs AFTER code extraction so a literal #123456789 inside inline/fenced code
|
||
// (now replaced by a placeholder) is not turned into a link.
|
||
html = html.replace(/#(\d{9})\b/g, '<a href="/ticket/$1" class="ticket-link-ref">#$1</a>');
|
||
|
||
// Tables (must be processed before other block elements)
|
||
html = parseMarkdownTables(html);
|
||
|
||
// Emoji :name: — common set
|
||
html = replaceEmoji(html);
|
||
|
||
// Bold (**text** or __text__)
|
||
html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
|
||
// Underscores only count when not inside a word (as in CommonMark), so
|
||
// identifiers like node_network_up or __init__.py stay literal.
|
||
html = html.replace(/(?<![A-Za-z0-9_])__(?!\s)(.+?)(?<!\s)__(?![A-Za-z0-9_])/g, '<strong>$1</strong>');
|
||
|
||
// Italic (*text* or _text_)
|
||
html = html.replace(/\*(.+?)\*/g, '<em>$1</em>');
|
||
html = html.replace(/(?<![A-Za-z0-9_])_(?!\s)(.+?)(?<!\s)_(?![A-Za-z0-9_])/g, '<em>$1</em>');
|
||
|
||
// Strikethrough (~~text~~) — must run before subscript (~)
|
||
html = html.replace(/~~(.+?)~~/g, '<del>$1</del>');
|
||
|
||
// Highlight (==text==)
|
||
html = html.replace(/==(.+?)==/g, '<mark>$1</mark>');
|
||
|
||
// Subscript H~2~O — single tilde (not preceded/followed by another tilde)
|
||
html = html.replace(/(?<!~)~([^~\n]+?)~(?!~)/g, '<sub>$1</sub>');
|
||
|
||
// Superscript X^2^ — caret pair
|
||
html = html.replace(/\^([^\^\n]+?)\^/g, '<sup>$1</sup>');
|
||
|
||
// Images  - must come before link handler
|
||
html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, function(match, alt, url) {
|
||
if (/^https?:/i.test(url)) {
|
||
return '<img src="' + url + '" alt="' + alt + '" class="md-image" loading="lazy">';
|
||
}
|
||
return match;
|
||
});
|
||
|
||
// Links [text](url) - only allow safe protocols
|
||
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, function(match, text, url) {
|
||
// Only allow http, https, mailto protocols
|
||
if (/^(https?:|mailto:|\/)/i.test(url)) {
|
||
return '<a href="' + url + '" target="_blank" rel="noopener noreferrer">' + text + '</a>';
|
||
}
|
||
// Block potentially dangerous protocols (javascript:, data:, etc.)
|
||
return text;
|
||
});
|
||
|
||
// Auto-link bare URLs (http, https)
|
||
html = html.replace(/(?<!["\'>])(\bhttps?:\/\/[^\s<>\[\]()]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>');
|
||
|
||
// Headings with optional {#id} anchor — ### My Heading {#my-id}
|
||
html = html.replace(/^(#{1,6})\s+(.+?)\s*(?:\{#([a-z0-9_-]+)\})?$/gm, function(match, hashes, text, id) {
|
||
const level = hashes.length;
|
||
const idAttr = id ? ' id="' + id + '"' : '';
|
||
return '<h' + level + idAttr + '>' + text + '</h' + level + '>';
|
||
});
|
||
|
||
// Lists — tag each item type with a placeholder, then wrap consecutive runs
|
||
html = html.replace(/^\s*\d+\.\s+(.+)$/gm, '%%OLI%%$1');
|
||
html = html.replace(/^\s*[-*+]\s+\[x\]\s+(.+)$/gim, '%%TDI%%$1');
|
||
html = html.replace(/^\s*[-*+]\s+\[ \]\s+(.+)$/gm, '%%TTI%%$1');
|
||
html = html.replace(/^\s*[-*+]\s+(.+)$/gm, '%%ULI%%$1');
|
||
|
||
// Wrap consecutive ordered items in <ol>
|
||
html = html.replace(/(%%OLI%%.+(\n%%OLI%%.+)*)/g, function(block) {
|
||
return '<ol>' + block.replace(/%%OLI%%(.+)/g, '<li>$1</li>') + '</ol>';
|
||
});
|
||
|
||
// Wrap consecutive unordered/task items in <ul>
|
||
html = html.replace(/((?:%%(?:ULI|TDI|TTI)%%).+(?:\n(?:%%(?:ULI|TDI|TTI)%%).+)*)/g, function(block) {
|
||
return '<ul>' + block
|
||
.replace(/%%ULI%%(.+)/g, '<li>$1</li>')
|
||
.replace(/%%TDI%%(.+)/g, '<li class="task-item task-done"><span class="task-cb">☑</span> $1</li>')
|
||
.replace(/%%TTI%%(.+)/g, '<li class="task-item task-todo"><span class="task-cb">☐</span> $1</li>')
|
||
+ '</ul>';
|
||
});
|
||
|
||
// Blockquotes (> text)
|
||
html = html.replace(/^>\s+(.+)$/gm, '<blockquote>$1</blockquote>');
|
||
|
||
// Horizontal rules (--- or ***)
|
||
html = html.replace(/^(?:---|___|\*\*\*)$/gm, '<hr>');
|
||
|
||
// Line breaks (two spaces at end of line or double newline)
|
||
html = html.replace(/ \n/g, '<br>');
|
||
html = html.replace(/\n\n/g, '</p><p>');
|
||
|
||
// Restore code blocks and inline code. Use a function replacer so '$'
|
||
// sequences in user code (e.g. $&, $$, $`, $') are inserted literally rather
|
||
// than interpreted as String.replace replacement patterns.
|
||
codeBlocks.forEach((block, i) => {
|
||
html = html.replace('%%CODEBLOCK' + i + '%%', () => block);
|
||
});
|
||
inlineCodes.forEach((code, i) => {
|
||
html = html.replace('%%INLINECODE' + i + '%%', () => code);
|
||
});
|
||
|
||
// Restore footnote reference placeholders
|
||
fnRefs.forEach(function(ref, i) {
|
||
html = html.replace('%%FNREF' + i + '%%',
|
||
'<sup class="fn-ref"><a href="#fn-' + fnSlug(ref.label) + '" id="fnref-' + fnSlug(ref.label) + '">[' + ref.n + ']</a></sup>');
|
||
});
|
||
|
||
// Wrap in paragraph if not already wrapped
|
||
if (!html.startsWith('<')) {
|
||
html = '<p>' + html + '</p>';
|
||
}
|
||
|
||
// Append footnote definitions block
|
||
if (footnoteOrder.length) {
|
||
html += '<hr class="fn-hr"><ol class="fn-list">';
|
||
footnoteOrder.forEach(function(label) {
|
||
html += '<li id="fn-' + fnSlug(label) + '" class="fn-item">' +
|
||
parseMarkdown(footnotes[label]).replace(/<\/?p>/g, '') +
|
||
' <a href="#fnref-' + fnSlug(label) + '" class="fn-back">↩</a></li>';
|
||
});
|
||
html += '</ol>';
|
||
}
|
||
|
||
return html;
|
||
}
|
||
|
||
/**
|
||
* Replace :emoji: shortcodes with Unicode characters
|
||
*/
|
||
const _emojiMap = {
|
||
// Faces & emotions
|
||
smile: '😊', grin: '😁', joy: '😂', rofl: '🤣', smiley: '😃', sweat_smile: '😅',
|
||
wink: '😉', blush: '😊', heart_eyes: '😍', kissing: '😗', thinking: '🤔',
|
||
raised_eyebrow: '🤨', neutral_face: '😐', expressionless: '😑', unamused: '😒',
|
||
roll_eyes: '🙄', pensive: '😔', confused: '😕', worried: '😟', cry: '😢',
|
||
sob: '😭', scream: '😱', angry: '😠', rage: '😡', skull: '💀', sunglasses: '😎',
|
||
nerd: '🤓', monocle: '🧐', clown: '🤡', ghost: '👻', robot: '🤖', alien: '👽',
|
||
// Hands & people
|
||
thumbsup: '👍', '+1': '👍', thumbsdown: '👎', '-1': '👎', clap: '👏',
|
||
wave: '👋', raised_hands: '🙌', pray: '🙏', point_up: '☝️', point_right: '👉',
|
||
point_left: '👈', point_down: '👇', fist: '✊', punch: '👊', v: '✌️', ok_hand: '👌',
|
||
muscle: '💪', eyes: '👀', eye: '👁️', ear: '👂', brain: '🧠', man: '👨', woman: '👩',
|
||
// Hearts & symbols
|
||
heart: '❤️', orange_heart: '🧡', yellow_heart: '💛', green_heart: '💚',
|
||
blue_heart: '💙', purple_heart: '💜', black_heart: '🖤', broken_heart: '💔',
|
||
star: '⭐', star2: '🌟', sparkles: '✨', fire: '🔥', boom: '💥', zap: '⚡',
|
||
check: '✅', white_check_mark: '✅', x: '❌', heavy_check_mark: '✔️',
|
||
warning: '⚠️', no_entry: '⛔', stop_sign: '🛑', prohibited: '🚫',
|
||
question: '❓', exclamation: '❗', grey_question: '❔', grey_exclamation: '❕',
|
||
100: '💯', tada: '🎉', confetti_ball: '🎊', trophy: '🏆', medal: '🥇',
|
||
// Tech & work
|
||
bug: '🐛', rocket: '🚀', computer: '💻', keyboard: '⌨️', mouse: '🖱️',
|
||
printer: '🖨️', phone: '📱', email: '📧', inbox_tray: '📥', outbox_tray: '📤',
|
||
memo: '📝', pencil: '✏️', pen: '🖊️', paperclip: '📎', link: '🔗',
|
||
hammer: '🔨', wrench: '🔧', gear: '⚙️', lock: '🔒', unlock: '🔓',
|
||
key: '🔑', mag: '🔍', bar_chart: '📊', chart_increasing: '📈', chart_decreasing: '📉',
|
||
clipboard: '📋', calendar: '📅', clock: '🕐', hourglass: '⏳', bell: '🔔',
|
||
mute: '🔇', loud_sound: '🔊', bulb: '💡', battery: '🔋', electric_plug: '🔌',
|
||
recycle: '♻️', package: '📦', label: '🏷️', bookmark: '🔖', flag: '🚩',
|
||
// Nature & misc
|
||
sun: '☀️', moon: '🌙', cloud: '☁️', snowflake: '❄️', umbrella: '☂️',
|
||
dog: '🐶', cat: '🐱', pizza: '🍕', coffee: '☕', beer: '🍺',
|
||
white_flag: '🏳️', checkered_flag: '🏁', construction: '🚧', sos: '🆘',
|
||
info: 'ℹ️', new: '🆕', free: '🆓', cool: '🆒', up: '🆙', soon: '🔜',
|
||
};
|
||
|
||
function replaceEmoji(text) {
|
||
return text.replace(/:([a-z0-9_+\-]+):/g, function(match, name) {
|
||
return _emojiMap[name] || match;
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Parse markdown tables
|
||
* Supports: | Header | Header |
|
||
* |--------|--------|
|
||
* | Cell | Cell |
|
||
*/
|
||
function parseMarkdownTables(html) {
|
||
const lines = html.split('\n');
|
||
const result = [];
|
||
let inTable = false;
|
||
let tableRows = [];
|
||
|
||
for (let i = 0; i < lines.length; i++) {
|
||
const line = lines[i].trim();
|
||
|
||
// Check if line is a table row (starts and ends with |, or has | in the middle)
|
||
if (line.match(/^\|.*\|$/) || line.match(/^[^|]+\|[^|]+/)) {
|
||
// Check if next line is separator (|---|---|)
|
||
const nextLine = lines[i + 1] ? lines[i + 1].trim() : '';
|
||
const isSeparator = line.match(/^\|?[\s-:|]+\|[\s-:|]+\|?$/);
|
||
|
||
if (!inTable && !isSeparator) {
|
||
// Start of table - check if this is a header row
|
||
if (nextLine.match(/^\|?[\s-:|]+\|[\s-:|]+\|?$/)) {
|
||
inTable = true;
|
||
tableRows.push({ type: 'header', content: line });
|
||
continue;
|
||
}
|
||
}
|
||
|
||
if (inTable) {
|
||
if (isSeparator) {
|
||
// Skip separator line
|
||
continue;
|
||
}
|
||
tableRows.push({ type: 'body', content: line });
|
||
continue;
|
||
}
|
||
}
|
||
|
||
// Not a table row - flush any accumulated table
|
||
if (inTable && tableRows.length > 0) {
|
||
result.push(buildTable(tableRows));
|
||
tableRows = [];
|
||
inTable = false;
|
||
}
|
||
result.push(lines[i]);
|
||
}
|
||
|
||
// Flush remaining table
|
||
if (tableRows.length > 0) {
|
||
result.push(buildTable(tableRows));
|
||
}
|
||
|
||
return result.join('\n');
|
||
}
|
||
|
||
/**
|
||
* Build HTML table from parsed rows
|
||
*/
|
||
function buildTable(rows) {
|
||
if (rows.length === 0) return '';
|
||
|
||
let html = '<table class="markdown-table">';
|
||
let inThead = false;
|
||
let inTbody = false;
|
||
|
||
rows.forEach((row) => {
|
||
const cells = row.content.split('|').filter(cell => cell.trim() !== '');
|
||
const isHeader = row.type === 'header';
|
||
const tag = isHeader ? 'th' : 'td';
|
||
|
||
if (isHeader && !inThead) { html += '<thead>'; inThead = true; }
|
||
if (!isHeader && !inTbody) {
|
||
if (inThead) { html += '</thead>'; inThead = false; }
|
||
html += '<tbody>';
|
||
inTbody = true;
|
||
}
|
||
|
||
html += '<tr>';
|
||
cells.forEach(cell => {
|
||
html += `<${tag}>${cell.trim()}</${tag}>`;
|
||
});
|
||
html += '</tr>';
|
||
});
|
||
|
||
// Close whichever section is still open so tags are balanced for header-only,
|
||
// body-only, and header+body tables alike.
|
||
if (inThead) html += '</thead>';
|
||
if (inTbody) html += '</tbody>';
|
||
html += '</table>';
|
||
return html;
|
||
}
|
||
|
||
// Apply markdown rendering to all elements with data-markdown attribute
|
||
function renderMarkdownElements() {
|
||
document.querySelectorAll('[data-markdown]:not([data-rendered])').forEach(element => {
|
||
// Trim so template indentation/whitespace in the element's text content
|
||
// doesn't get parsed as a leading code block (which breaks headings,
|
||
// tables, etc. and diverges from the live preview).
|
||
const markdownText = (element.getAttribute('data-markdown') || element.textContent).trim();
|
||
element.innerHTML = parseMarkdown(markdownText);
|
||
element.dataset.rendered = '1';
|
||
});
|
||
}
|
||
|
||
// Apply markdown to description and comments on page load
|
||
document.addEventListener('DOMContentLoaded', renderMarkdownElements);
|
||
|
||
// Expose for manual use
|
||
window.parseMarkdown = parseMarkdown;
|
||
window.renderMarkdownElements = renderMarkdownElements;
|
||
|
||
// ========================================
|
||
// Rich Text Editor Toolbar Functions
|
||
// ========================================
|
||
|
||
/**
|
||
* Replace textarea.value.substring(selStart, selEnd) with replacementText,
|
||
* preserving the browser's native undo/redo stack via
|
||
* document.execCommand('insertText', ...) -- the same mechanism real typing
|
||
* uses -- instead of a direct .value assignment, which discards the entire
|
||
* undo history. Falls back to a direct assignment (losing undo, matching the
|
||
* old behavior) only if execCommand is unavailable or unsuccessful.
|
||
*/
|
||
function insertTextPreservingUndo(textarea, replacementText, selStart, selEnd) {
|
||
textarea.focus();
|
||
textarea.setSelectionRange(selStart, selEnd);
|
||
|
||
let inserted = false;
|
||
if (typeof document.execCommand === 'function') {
|
||
try {
|
||
inserted = document.execCommand('insertText', false, replacementText);
|
||
} catch (e) {
|
||
inserted = false;
|
||
}
|
||
}
|
||
|
||
if (!inserted) {
|
||
const text = textarea.value;
|
||
textarea.value = text.substring(0, selStart) + replacementText + text.substring(selEnd);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Insert markdown formatting around selection
|
||
*/
|
||
function insertMarkdownFormat(textareaId, prefix, suffix) {
|
||
const textarea = document.getElementById(textareaId);
|
||
if (!textarea) return;
|
||
|
||
const start = textarea.selectionStart;
|
||
const end = textarea.selectionEnd;
|
||
const selectedText = textarea.value.substring(start, end);
|
||
|
||
insertTextPreservingUndo(textarea, prefix + selectedText + suffix, start, end);
|
||
|
||
// Set cursor position
|
||
if (selectedText) {
|
||
textarea.setSelectionRange(start + prefix.length, start + prefix.length + selectedText.length);
|
||
} else {
|
||
textarea.setSelectionRange(start + prefix.length, start + prefix.length);
|
||
}
|
||
|
||
textarea.focus();
|
||
|
||
// Trigger input event to update preview if enabled
|
||
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||
}
|
||
|
||
/**
|
||
* Insert markdown at cursor position
|
||
*/
|
||
function insertMarkdownText(textareaId, text) {
|
||
const textarea = document.getElementById(textareaId);
|
||
if (!textarea) return;
|
||
|
||
const start = textarea.selectionStart;
|
||
|
||
// Matches the prior behavior: insert before the selection start without
|
||
// deleting any currently-selected text (a collapsed replace range).
|
||
insertTextPreservingUndo(textarea, text, start, start);
|
||
textarea.setSelectionRange(start + text.length, start + text.length);
|
||
textarea.focus();
|
||
|
||
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||
}
|
||
|
||
/**
|
||
* Toolbar button handlers
|
||
*/
|
||
function toolbarBold(textareaId) {
|
||
insertMarkdownFormat(textareaId, '**', '**');
|
||
}
|
||
|
||
function toolbarItalic(textareaId) {
|
||
insertMarkdownFormat(textareaId, '_', '_');
|
||
}
|
||
|
||
function toolbarCode(textareaId) {
|
||
const textarea = document.getElementById(textareaId);
|
||
if (!textarea) return;
|
||
|
||
const selectedText = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
|
||
|
||
// Use code block for multi-line, inline code for single line
|
||
if (selectedText.includes('\n')) {
|
||
insertMarkdownFormat(textareaId, '```\n', '\n```');
|
||
} else {
|
||
insertMarkdownFormat(textareaId, '`', '`');
|
||
}
|
||
}
|
||
|
||
function toolbarLink(textareaId) {
|
||
const textarea = document.getElementById(textareaId);
|
||
if (!textarea) return;
|
||
|
||
const selectedText = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
|
||
|
||
if (selectedText) {
|
||
// Wrap selected text as link text
|
||
insertMarkdownFormat(textareaId, '[', '](url)');
|
||
} else {
|
||
insertMarkdownText(textareaId, '[link text](url)');
|
||
}
|
||
}
|
||
|
||
function toolbarList(textareaId) {
|
||
const textarea = document.getElementById(textareaId);
|
||
if (!textarea) return;
|
||
|
||
const start = textarea.selectionStart;
|
||
const text = textarea.value;
|
||
|
||
// Find start of current line
|
||
let lineStart = start;
|
||
while (lineStart > 0 && text[lineStart - 1] !== '\n') {
|
||
lineStart--;
|
||
}
|
||
|
||
// Insert list marker at beginning of line
|
||
insertTextPreservingUndo(textarea, '- ', lineStart, lineStart);
|
||
textarea.setSelectionRange(start + 2, start + 2);
|
||
textarea.focus();
|
||
|
||
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||
}
|
||
|
||
function toolbarHeading(textareaId) {
|
||
const textarea = document.getElementById(textareaId);
|
||
if (!textarea) return;
|
||
|
||
const start = textarea.selectionStart;
|
||
const text = textarea.value;
|
||
|
||
// Find start of current line
|
||
let lineStart = start;
|
||
while (lineStart > 0 && text[lineStart - 1] !== '\n') {
|
||
lineStart--;
|
||
}
|
||
|
||
// Insert heading marker at beginning of line
|
||
insertTextPreservingUndo(textarea, '## ', lineStart, lineStart);
|
||
textarea.setSelectionRange(start + 3, start + 3);
|
||
textarea.focus();
|
||
|
||
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||
}
|
||
|
||
function toolbarTable(textareaId) {
|
||
const textarea = document.getElementById(textareaId);
|
||
if (!textarea) return;
|
||
|
||
const start = textarea.selectionStart;
|
||
const text = textarea.value;
|
||
|
||
// Insert on its own line(s), matching the blank-line-before convention
|
||
// toolbarList/toolbarHeading rely on the surrounding text for — a table
|
||
// needs a full line to itself both before and after the separator row.
|
||
const needsLeadingNewline = start > 0 && text[start - 1] !== '\n';
|
||
const template = (needsLeadingNewline ? '\n' : '')
|
||
+ '| Header 1 | Header 2 |\n'
|
||
+ '| --- | --- |\n'
|
||
+ '| Cell 1 | Cell 2 |\n';
|
||
|
||
insertMarkdownText(textareaId, template);
|
||
}
|
||
|
||
function toolbarQuote(textareaId) {
|
||
const textarea = document.getElementById(textareaId);
|
||
if (!textarea) return;
|
||
|
||
const start = textarea.selectionStart;
|
||
const text = textarea.value;
|
||
|
||
// Find start of current line
|
||
let lineStart = start;
|
||
while (lineStart > 0 && text[lineStart - 1] !== '\n') {
|
||
lineStart--;
|
||
}
|
||
|
||
// Insert quote marker at beginning of line
|
||
insertTextPreservingUndo(textarea, '> ', lineStart, lineStart);
|
||
textarea.setSelectionRange(start + 2, start + 2);
|
||
textarea.focus();
|
||
|
||
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||
}
|
||
|
||
/**
|
||
* Create and insert toolbar HTML for a textarea
|
||
*/
|
||
function createEditorToolbar(textareaId, containerId) {
|
||
const container = document.getElementById(containerId);
|
||
if (!container) return;
|
||
|
||
const toolbar = document.createElement('div');
|
||
toolbar.className = 'editor-toolbar';
|
||
toolbar.innerHTML = `
|
||
<button type="button" data-toolbar-action="bold" data-textarea="${textareaId}" title="Bold (Ctrl+B)"><b>B</b></button>
|
||
<button type="button" data-toolbar-action="italic" data-textarea="${textareaId}" title="Italic (Ctrl+I)"><i>I</i></button>
|
||
<button type="button" data-toolbar-action="code" data-textarea="${textareaId}" title="Code"></></button>
|
||
<span class="toolbar-separator"></span>
|
||
<button type="button" data-toolbar-action="heading" data-textarea="${textareaId}" title="Heading">H</button>
|
||
<button type="button" data-toolbar-action="list" data-textarea="${textareaId}" title="List">≡</button>
|
||
<button type="button" data-toolbar-action="quote" data-textarea="${textareaId}" title="Quote">"</button>
|
||
<button type="button" data-toolbar-action="table" data-textarea="${textareaId}" title="Table">▦</button>
|
||
<span class="toolbar-separator"></span>
|
||
<button type="button" data-toolbar-action="link" data-textarea="${textareaId}" title="Link">[ @ ]</button>
|
||
`;
|
||
|
||
// Add event delegation for toolbar buttons
|
||
toolbar.addEventListener('click', function(e) {
|
||
const btn = e.target.closest('[data-toolbar-action]');
|
||
if (!btn) return;
|
||
|
||
const action = btn.dataset.toolbarAction;
|
||
const targetId = btn.dataset.textarea;
|
||
|
||
switch (action) {
|
||
case 'bold': toolbarBold(targetId); break;
|
||
case 'italic': toolbarItalic(targetId); break;
|
||
case 'code': toolbarCode(targetId); break;
|
||
case 'heading': toolbarHeading(targetId); break;
|
||
case 'list': toolbarList(targetId); break;
|
||
case 'quote': toolbarQuote(targetId); break;
|
||
case 'table': toolbarTable(targetId); break;
|
||
case 'link': toolbarLink(targetId); break;
|
||
}
|
||
});
|
||
|
||
container.insertBefore(toolbar, container.firstChild);
|
||
}
|
||
|
||
// Expose toolbar functions globally
|
||
window.toolbarBold = toolbarBold;
|
||
window.toolbarItalic = toolbarItalic;
|
||
window.toolbarCode = toolbarCode;
|
||
window.toolbarLink = toolbarLink;
|
||
window.toolbarList = toolbarList;
|
||
window.toolbarHeading = toolbarHeading;
|
||
window.toolbarQuote = toolbarQuote;
|
||
window.toolbarTable = toolbarTable;
|
||
window.createEditorToolbar = createEditorToolbar;
|
||
window.insertMarkdownFormat = insertMarkdownFormat;
|
||
window.insertMarkdownText = insertMarkdownText;
|
||
|
||
// ========================================
|
||
// Auto-link URLs in plain text (non-markdown)
|
||
// ========================================
|
||
|
||
/**
|
||
* Convert plain text URLs to clickable links
|
||
* Used for non-markdown comments
|
||
*/
|
||
function autoLinkUrls(text) {
|
||
if (!text) return '';
|
||
// Match URLs that aren't already in an href attribute
|
||
return text.replace(/(?<!["\'>])(https?:\/\/[^\s<>\[\]()]+)/g,
|
||
'<a href="$1" target="_blank" rel="noopener noreferrer" class="auto-link">$1</a>');
|
||
}
|
||
|
||
/**
|
||
* Process all non-markdown comment elements to auto-link URLs
|
||
*/
|
||
function processPlainTextComments() {
|
||
document.querySelectorAll('.comment-text:not([data-markdown])').forEach(element => {
|
||
// Only process if not already processed
|
||
if (element.dataset.linksProcessed) return;
|
||
element.innerHTML = autoLinkUrls(element.innerHTML);
|
||
element.dataset.linksProcessed = 'true';
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Render all [data-markdown] comment elements that haven't been rendered yet
|
||
*/
|
||
function renderMarkdownComments() {
|
||
document.querySelectorAll('.comment-text[data-markdown]:not([data-rendered])').forEach(el => {
|
||
el.classList.add('lt-markdown');
|
||
// Trim template whitespace so the first line isn't parsed as an
|
||
// indented code block (matches the live-preview rendering).
|
||
el.innerHTML = parseMarkdown(el.textContent.trim());
|
||
el.dataset.rendered = '1';
|
||
});
|
||
}
|
||
|
||
// Run on page load
|
||
document.addEventListener('DOMContentLoaded', function() {
|
||
renderMarkdownComments();
|
||
processPlainTextComments();
|
||
});
|
||
|
||
window.renderMarkdownComments = renderMarkdownComments;
|
||
|
||
// Expose for manual use
|
||
window.autoLinkUrls = autoLinkUrls;
|
||
window.processPlainTextComments = processPlainTextComments;
|