Files
itflow/js/document_markdown.js

713 lines
31 KiB
JavaScript

/*
* Documents written in Markdown (agent/modals/document/document_form.php, functions/markdown.php).
*
* A document's form has both editors - the rich text one (TinyMCE, js/app.js) and a plain box for
* Markdown with Write and Preview - and shows the one it is written in. The Markdown box has a
* toolbar like the rich text editor's (headings, bold, italic, struck, link, lists, checklist,
* quote, code, table, line, picture), Ctrl+B, Ctrl+I and Ctrl+K, and Enter in a list starts the
* next item. Switching converts what is
* written into the other, through agent/ajax.php, so nothing has to be typed again; switching to
* Markdown says when some of it stays as HTML, or alignment was dropped.
*
* A picture pasted or dropped into the Markdown box goes in as ![Pasted image 1](pasted:1), with
* the picture itself held here - put back as its data for Preview and when the form is saved,
* where it becomes a file of the document's (markdownSaveImages()).
*
* New Document starts in the way the agent wrote last (data-format-remember, kept in this
* browser). On a page of its own, leaving with the Markdown changed asks first, as leaving with
* the rich text editor changed does.
*
* Markdown pasted into a document's rich text editor - copied from GitHub's source view, VS Code,
* Obsidian, an AI chat - goes in formatted. Ctrl+Shift+V pastes it as it is.
*
* Loaded on every agent page (includes/footer.php), once - and on New Document in the client
* portal (client/includes/footer.php), which turns Markdown into HTML at client/post.php.
*/
(function () {
'use strict';
if (window.itflowDocumentFormat) {
return;
}
var REMEMBER = 'itflow.documentFormat';
// Where Markdown is turned into HTML and back - agent/ajax.php, or in the client portal the
// address its <script> tag gives (data-markdown-url, client/includes/footer.php)
var script = document.currentScript;
var URL_BASE = (script && script.getAttribute('data-markdown-url')) || '/agent/ajax.php';
function post(action, data) {
// What is written goes as a file, past a web application firewall (js/http.js)
var body = window.itflowFields ? window.itflowFields.body(new URLSearchParams(data), ['html', 'markdown']) : new URLSearchParams(data).toString();
return fetch(URL_BASE + '?' + action, {
method: 'POST',
headers: typeof body === 'string' ? { 'Content-Type': 'application/x-www-form-urlencoded' } : {},
credentials: 'same-origin',
body: body
}).then(function (response) {
return response.json().catch(function () {
throw new Error('');
});
}).then(function (answer) {
if (answer.error) {
throw new Error(answer.error);
}
return answer;
});
}
function remembered() {
try {
return window.localStorage.getItem(REMEMBER);
} catch (e) {
return null;
}
}
function remember(format) {
try {
window.localStorage.setItem(REMEMBER, format);
} catch (e) {
// a private window - it simply isn't remembered
}
}
function richEditor(box) {
var textarea = box.querySelector('[data-editor-rich] textarea');
if (!window.tinymce || !textarea) {
return null;
}
return tinymce.get().filter(function (editor) {
return editor.getElement() === textarea;
})[0] || null;
}
function take(box) {
if (box.itflowMarkdown) {
return;
}
var form = box.closest('form');
var input = box.querySelector('[data-markdown-input]');
var preview = box.querySelector('[data-markdown-preview]');
var rich = box.querySelector('[data-editor-rich]');
var markdown = box.querySelector('[data-editor-markdown]');
var note = box.querySelector('[data-format-note]');
var toolbar = box.querySelector('[data-markdown-toolbar]');
var radios = box.querySelectorAll('input[name="format"]');
if (!form || !input || !rich || !markdown) {
return;
}
var state = {
pictures: {}, // pasted:N -> its data
count: 0,
shownFor: null, // what Preview last showed
busy: false,
saving: false,
initial: input.value
};
box.itflowMarkdown = state;
function format() {
var checked = box.querySelector('input[name="format"]:checked');
return checked ? checked.value : 'html';
}
function say(text, tone) {
if (!note) {
return;
}
note.className = 'small' + (tone ? ' text-' + tone + '-emphasis' : ' text-body-secondary');
note.textContent = text || '';
}
// What the Markdown says with its pasted pictures put back
function withPictures(text) {
return text.replace(/\]\(pasted:(\d+)\)/g, function (all, n) {
return state.pictures[n] ? '](' + state.pictures[n] + ')' : all;
});
}
// Pictures written out as data (in HTML switched over) become pasted:N, so the box stays readable
function holdPictures(text) {
return text.replace(/data:image\/(png|jpe?g|gif|webp);base64,[A-Za-z0-9+\/=\s]+/gi, function (data) {
state.count += 1;
state.pictures[state.count] = data.replace(/\s+/g, '');
return 'pasted:' + state.count;
});
}
function insertAtCursor(text) {
var start = input.selectionStart;
var end = input.selectionEnd;
input.setRangeText(text, start, end, 'end');
input.dispatchEvent(new Event('input', { bubbles: true }));
input.focus();
}
function addPicture(file) {
if (!file || !/^image\/(png|jpeg|gif|webp)$/.test(file.type)) {
return false;
}
var reader = new FileReader();
reader.onload = function () {
state.count += 1;
state.pictures[state.count] = reader.result;
var before = input.value.slice(0, input.selectionStart);
var gap = before === '' || /\n\n$/.test(before) ? '' : (/\n$/.test(before) ? '\n' : '\n\n');
insertAtCursor(gap + '![Pasted image ' + state.count + '](pasted:' + state.count + ')\n');
};
reader.readAsDataURL(file);
return true;
}
input.addEventListener('paste', function (e) {
var items = e.clipboardData ? e.clipboardData.items : [];
for (var i = 0; i < items.length; i++) {
if (items[i].kind === 'file' && addPicture(items[i].getAsFile())) {
e.preventDefault();
return;
}
}
});
input.addEventListener('dragover', function (e) {
if (e.dataTransfer && Array.prototype.indexOf.call(e.dataTransfer.types || [], 'Files') !== -1) {
e.preventDefault();
}
});
input.addEventListener('drop', function (e) {
var files = e.dataTransfer ? e.dataTransfer.files : [];
var added = false;
for (var i = 0; i < files.length; i++) {
added = addPicture(files[i]) || added;
}
if (added) {
e.preventDefault();
}
});
/*
* The toolbar, and Ctrl+B, Ctrl+I and Ctrl+K - each on what is picked, or where the cursor
* is. Changes go in as typing would, so Ctrl+Z takes them back.
*/
function put(start, end, text, selectStart, selectEnd) {
input.focus();
input.setSelectionRange(start, end);
if (text === '' && start === end) {
input.setSelectionRange(selectStart, selectEnd);
return;
}
var typed = false;
try {
typed = text === '' ? document.execCommand('delete') : document.execCommand('insertText', false, text);
} catch (e) {
typed = false;
}
if (!typed || input.value.slice(start, start + text.length) !== text) {
input.setRangeText(text, start, end, 'end');
input.dispatchEvent(new Event('input', { bubbles: true }));
}
input.setSelectionRange(selectStart, selectEnd);
}
// Around what is picked: **bold** - or taken off again when it is already there
function wrap(before, after, example) {
var v = input.value;
var start = input.selectionStart;
var end = input.selectionEnd;
var picked = v.slice(start, end);
if (picked.length >= before.length + after.length && picked.indexOf(before) === 0 && picked.slice(-after.length) === after) {
var bare = picked.slice(before.length, picked.length - after.length);
put(start, end, bare, start, start + bare.length);
return;
}
if (v.slice(start - before.length, start) === before && v.slice(end, end + after.length) === after) {
put(start - before.length, end + after.length, picked, start - before.length, end - before.length);
return;
}
// Spaces picked at either end stay outside, as Markdown wants
var lead = picked.match(/^\s*/)[0];
var trail = picked.slice(lead.length).match(/\s*$/)[0];
var text = picked.slice(lead.length, picked.length - trail.length) || example;
put(start, end, lead + before + text + after + trail, start + lead.length + before.length, start + lead.length + before.length + text.length);
}
// The whole lines the cursor or what is picked is on: [start, end]
function lineRange() {
var v = input.value;
var start = v.lastIndexOf('\n', input.selectionStart - 1) + 1;
var to = input.selectionEnd > input.selectionStart && v[input.selectionEnd - 1] === '\n' ? input.selectionEnd - 1 : input.selectionEnd;
var end = v.indexOf('\n', to);
return [start, end === -1 ? v.length : end];
}
var MARKS = {
bullets: /^(\s*)[-*+] (?!\[[ xX]\] )/,
numbers: /^(\s*)\d+[.)] /,
tasks: /^(\s*)[-*+] \[[ xX]\] /,
quote: /^(\s*)> ?/
};
var ANY_LIST = /^(\s*)([-*+] \[[ xX]\] |[-*+] |\d+[.)] )/;
// Each line made a list item, a checklist item or a quote - or back to text when all of them were
function prefixLines(kind) {
var range = lineRange();
var lines = input.value.slice(range[0], range[1]).split('\n');
var filled = lines.filter(function (line) { return line.trim() !== ''; });
var all = filled.length > 0 && filled.every(function (line) { return MARKS[kind].test(line); });
var number = 0;
var out = lines.map(function (line) {
if (all) {
return line.replace(MARKS[kind], '$1');
}
if (line.trim() === '' && lines.length > 1) {
return line;
}
var indent = line.match(/^\s*/)[0];
var text = kind === 'quote' ? line.replace(MARKS.quote, '$1').slice(indent.length) : line.replace(ANY_LIST, '$1').slice(indent.length);
number += 1;
var mark = kind === 'bullets' ? '- ' : kind === 'numbers' ? number + '. ' : kind === 'tasks' ? '- [ ] ' : '> ';
return indent + mark + text;
}).join('\n');
if (lines.length === 1) {
put(range[0], range[1], out, range[0] + out.length, range[0] + out.length);
} else {
put(range[0], range[1], out, range[0], range[0] + out.length);
}
}
// The lines made a heading of that level - again, or Normal text, back to text
function heading(level) {
var range = lineRange();
var lines = input.value.slice(range[0], range[1]).split('\n');
var filled = lines.filter(function (line) { return line.trim() !== ''; });
var same = level > 0 && filled.length > 0 && filled.every(function (line) { return new RegExp('^#{' + level + '} ').test(line); });
var out = lines.map(function (line) {
var text = line.replace(/^#{1,6}\s+/, '');
if (level === 0 || same || (line.trim() === '' && lines.length > 1)) {
return text;
}
return '#'.repeat(level) + ' ' + text;
}).join('\n');
put(range[0], range[1], out, range[0] + out.length, range[0] + out.length);
}
// Something that goes on lines of its own - a blank line before and after it
function block(text, selectFrom, selectTo) {
var v = input.value;
var start = input.selectionStart;
var end = input.selectionEnd;
var before = v.slice(0, start);
var gap = before === '' || /\n\n$/.test(before) ? '' : (/\n$/.test(before) ? '\n' : '\n\n');
var after = v.slice(end);
var tail = after === '' || /^\n\n/.test(after) ? '\n' : (/^\n/.test(after) ? '\n' : '\n\n');
put(start, end, gap + text + tail, start + gap.length + selectFrom, start + gap.length + selectTo);
}
var actions = {
h1: function () { heading(1); },
h2: function () { heading(2); },
h3: function () { heading(3); },
paragraph: function () { heading(0); },
bold: function () { wrap('**', '**', 'bold text'); },
italic: function () { wrap('_', '_', 'italic text'); },
strike: function () { wrap('~~', '~~', 'struck text'); },
code: function () {
var picked = input.value.slice(input.selectionStart, input.selectionEnd);
if (picked.indexOf('\n') !== -1) {
actions.codeblock();
} else {
wrap('`', '`', 'code');
}
},
codeblock: function () {
var picked = input.value.slice(input.selectionStart, input.selectionEnd).replace(/\n$/, '');
block('```\n' + picked + '\n```', 4, 4 + picked.length);
},
link: function () {
var start = input.selectionStart;
var end = input.selectionEnd;
var picked = input.value.slice(start, end);
if (/^(https?:\/\/|mailto:)\S+$/i.test(picked)) {
put(start, end, '[](' + picked + ')', start + 1, start + 1);
} else {
var words = picked || 'link text';
var text = '[' + words + '](https://)';
// The address to type over - or the words, when there were none
var at = picked ? start + words.length + 3 : start + 1;
put(start, end, text, at, picked ? at + 8 : at + words.length);
}
},
bullets: function () { prefixLines('bullets'); },
numbers: function () { prefixLines('numbers'); },
tasks: function () { prefixLines('tasks'); },
quote: function () { prefixLines('quote'); },
table: function () {
block('| Column 1 | Column 2 |\n|---|---|\n| | |', 2, 10);
},
line: function () {
block('---', 3, 3);
},
picture: function () {
var picker = box.querySelector('[data-markdown-picture]');
if (picker) {
picker.click();
}
}
};
if (toolbar) {
toolbar.addEventListener('click', function (e) {
var button = e.target.closest('[data-md]');
if (!button || !actions[button.getAttribute('data-md')]) {
return;
}
e.preventDefault();
actions[button.getAttribute('data-md')]();
});
// Keeps what is picked in the box picked while a button is pressed
toolbar.addEventListener('mousedown', function (e) {
if (e.target.closest('.itflow-markdown-button[data-md]')) {
e.preventDefault();
}
});
var picker = box.querySelector('[data-markdown-picture]');
if (picker) {
picker.addEventListener('change', function () {
Array.prototype.forEach.call(picker.files || [], addPicture);
picker.value = '';
});
}
}
input.addEventListener('keydown', function (e) {
var key = (e.key || '').toLowerCase();
if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && (key === 'b' || key === 'i' || key === 'k')) {
e.preventDefault();
actions[key === 'b' ? 'bold' : key === 'i' ? 'italic' : 'link']();
return;
}
// Enter in a list, checklist or quote starts the next item - and on an empty one, ends it
if (e.key !== 'Enter' || e.shiftKey || e.ctrlKey || e.metaKey || e.altKey || e.isComposing || input.selectionStart !== input.selectionEnd) {
return;
}
var v = input.value;
var at = input.selectionStart;
var lineStart = v.lastIndexOf('\n', at - 1) + 1;
var lineEnd = v.indexOf('\n', at);
var line = v.slice(lineStart, lineEnd === -1 ? v.length : lineEnd);
var m = line.match(/^(\s*)([-*+] \[[ xX]\] |[-*+] |(\d+)([.)]) |> )/);
if (!m || at < lineStart + m[0].length) {
return;
}
e.preventDefault();
// An empty item ends the list, with a blank line after it, so what comes next isn't part of it
if (line.slice(m[0].length).trim() === '') {
put(lineStart, lineStart + line.length, '\n', lineStart + 1, lineStart + 1);
return;
}
var mark = m[3] ? m[1] + (parseInt(m[3], 10) + 1) + m[4] + ' ' : m[1] + m[2].replace(/\[[xX]\]/, '[ ]');
put(at, at, '\n' + mark, at + 1 + mark.length, at + 1 + mark.length);
});
// Write and Preview
function showTab(which) {
box.querySelectorAll('[data-markdown-tab]').forEach(function (tab) {
tab.classList.toggle('active', tab.getAttribute('data-markdown-tab') === which);
});
input.hidden = which === 'preview';
if (toolbar) {
toolbar.hidden = which === 'preview';
}
preview.hidden = which !== 'preview';
if (which !== 'preview') {
input.focus();
return;
}
var text = withPictures(input.value);
if (state.shownFor === text) {
return;
}
preview.innerHTML = '<p class="text-body-secondary"><i class="fas fa-spinner fa-spin me-2"></i>Getting the preview</p>';
if (text.trim() === '') {
state.shownFor = text;
preview.innerHTML = '<p class="text-body-secondary">Nothing written yet.</p>';
return;
}
post('markdown_to_html', { markdown: text }).then(function (answer) {
state.shownFor = text;
preview.innerHTML = answer.html;
}).catch(function (error) {
preview.innerHTML = '';
var p = document.createElement('p');
p.className = 'text-danger-emphasis';
p.textContent = (error && error.message) || 'The preview couldn\'t be made - try again.';
preview.appendChild(p);
});
}
box.querySelectorAll('[data-markdown-tab]').forEach(function (tab) {
tab.addEventListener('click', function () {
showTab(tab.getAttribute('data-markdown-tab'));
});
});
// On a page of its own the box fills the window, as the rich text editor does there
var onPage = !box.closest('.modal');
function fit() {
if (!onPage || markdown.hidden) {
return;
}
input.style.height = Math.max(420, window.innerHeight - input.getBoundingClientRect().top - 24) + 'px';
}
if (onPage) {
window.addEventListener('resize', fit);
fit();
}
function showEditor(which) {
rich.hidden = which !== 'html';
markdown.hidden = which !== 'markdown';
if (which === 'markdown') {
showTab('write');
fit();
} else {
var editor = richEditor(box);
if (editor) {
if (editor.plugins.autoresize) {
editor.execCommand('mceAutoResize');
}
window.dispatchEvent(new Event('resize'));
editor.focus();
}
}
}
function setRadio(which) {
radios.forEach(function (radio) {
radio.checked = radio.value === which;
});
}
// Switching: what is written goes over to the other editor
function switchTo(which) {
var editor = richEditor(box);
var from = which === 'markdown' ? 'html' : 'markdown';
if (state.busy) {
setRadio(from);
return;
}
var fromText = from === 'html' ? (editor ? editor.getContent() : rich.querySelector('textarea').value) : withPictures(input.value);
var empty = from === 'html' ? fromText.replace(/<[^>]*>|&nbsp;|\s/g, '') === '' && !/<(img|table|hr)\b/i.test(fromText) : fromText.trim() === '';
if (box.hasAttribute('data-format-remember')) {
remember(which);
}
if (empty) {
if (which === 'markdown') {
input.value = '';
} else if (editor) {
editor.setContent('');
}
say('');
showEditor(which);
return;
}
state.busy = true;
radios.forEach(function (radio) {
radio.disabled = true;
});
say(which === 'markdown' ? 'Turning it into Markdown...' : 'Turning it into rich text...');
var asked = which === 'markdown' ? post('html_to_markdown', { html: fromText }) : post('markdown_to_html', { markdown: fromText });
asked.then(function (answer) {
if (which === 'markdown') {
input.value = holdPictures(answer.markdown);
input.dispatchEvent(new Event('input', { bubbles: true }));
state.shownFor = null;
var notes = [];
if (answer.kept) {
notes.push('Some formatting Markdown has no way to write - colours, merged table cells, a picture\'s size - is kept as HTML in it.');
}
if (answer.dropped) {
notes.push('Alignment and indents don\'t carry over.');
}
say(notes.join(' '), notes.length ? 'warning' : '');
} else {
if (editor) {
editor.undoManager.transact(function () {
editor.setContent(answer.html);
});
editor.setDirty(true);
} else {
rich.querySelector('textarea').value = answer.html;
}
say('');
}
showEditor(which);
}).catch(function (error) {
setRadio(from);
say((error && error.message) || 'It couldn\'t be switched - try again.', 'danger');
}).finally(function () {
state.busy = false;
radios.forEach(function (radio) {
radio.disabled = false;
});
});
}
radios.forEach(function (radio) {
radio.addEventListener('change', function () {
if (radio.checked) {
switchTo(radio.value);
}
});
});
// New Document, empty, in the way the agent wrote last
if (box.hasAttribute('data-format-remember') && remembered() === 'markdown' && format() === 'html'
&& input.value === '' && rich.querySelector('textarea').value.trim() === '') {
setRadio('markdown');
showEditor('markdown');
}
// Saved: the pictures go with it, and leaving isn't leaving with changes unsaved
form.addEventListener('submit', function () {
state.saving = true;
if (format() === 'markdown') {
input.value = withPictures(input.value);
}
});
if (onPage) {
window.addEventListener('beforeunload', function (e) {
if (!state.saving && format() === 'markdown' && input.value !== state.initial) {
e.preventDefault();
e.returnValue = '';
}
});
}
}
window.itflowDocumentFormat = {
start: function () {
(window.itflowDocumentForms || []).splice(0).forEach(function (box) {
if (box && box.isConnected) {
take(box);
}
});
},
// Whether a form is being written in Markdown
isMarkdown: function (form) {
var checked = form ? form.querySelector('[data-document-editors] input[name="format"]:checked') : null;
return !!checked && checked.value === 'markdown';
},
// HTML made elsewhere (AI's draft) put into a form written in Markdown - as Markdown
putHtml: function (form, html) {
var box = form.querySelector('[data-document-editors]');
var input = box ? box.querySelector('[data-markdown-input]') : null;
if (!input) {
return Promise.reject(new Error(''));
}
return post('html_to_markdown', { html: html }).then(function (answer) {
input.value = answer.markdown;
input.dispatchEvent(new Event('input', { bubbles: true }));
if (box.itflowMarkdown) {
box.itflowMarkdown.shownFor = null;
}
});
}
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', window.itflowDocumentFormat.start);
} else {
window.itflowDocumentFormat.start();
}
/*
* Markdown pasted into the rich text editor of a document, an article or a template (.tinymce,
* .tinymce-document, .tinymce-page). Only what is plainly Markdown is turned into formatting: a fenced code block,
* a table, a checklist, a link written as Markdown, or a heading with more Markdown after it.
* A script with # comments, or a few lines starting with a dash, goes in as it was.
*/
function looksLikeMarkdown(text) {
if (!text || text.length > 2000000) {
return false;
}
if (/^\s{0,3}(```|~~~)/m.test(text)
|| /^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/m.test(text)
|| /^\s*[-*+]\s+\[[ xX]\]\s+\S/m.test(text)
|| /!?\[[^\]\n]+\]\((https?:\/\/|\/|#|mailto:)[^)\s]*\)/.test(text)) {
return true;
}
var score = 0;
if (/^\s{0,3}#{1,6}\s+\S/m.test(text)) {
score += 2;
}
if (/(\*\*|__)[^\s*_][^\n]*?[^\s*_]\1/.test(text)) {
score += 1;
}
if (/(^|[^`])`[^`\n]+`/.test(text)) {
score += 1;
}
if ((text.match(/^\s*([-*+]|\d+[.)])\s+\S/gm) || []).length >= 2) {
score += 1;
}
if (/^\s{0,3}>\s+\S/m.test(text)) {
score += 1;
}
return score >= 3;
}
// HTML that is only the text in a code editor's colours (VS Code) - its plain text is the Markdown
function onlyCodeEditorHtml(html) {
if (!html || typeof DOMParser !== 'function') {
return !html;
}
var body = new DOMParser().parseFromString(html, 'text/html').body;
return !body.querySelector('p, h1, h2, h3, h4, h5, h6, ul, ol, table, img, blockquote, pre')
&& /white-space:\s*pre/i.test(html);
}
if (window.tinymce) {
tinymce.on('AddEditor', function (added) {
var editor = added.editor;
var element = editor.getElement ? editor.getElement() : null;
if (!element || !element.classList || !['tinymce', 'tinymce-document', 'tinymce-page'].some(function (name) { return element.classList.contains(name); })) {
return;
}
var plainNext = false;
editor.on('keydown', function (e) {
plainNext = (e.ctrlKey || e.metaKey) && e.shiftKey && (e.key || '').toLowerCase() === 'v';
});
editor.on('paste', function (e) {
var plain = plainNext;
plainNext = false;
var clipboard = e.clipboardData;
if (plain || e.isDefaultPrevented() || !clipboard) {
return;
}
var text = clipboard.getData('text/plain');
var html = clipboard.getData('text/html');
if (Array.prototype.indexOf.call(clipboard.types || [], 'x-tinymce/html') !== -1
|| !looksLikeMarkdown(text) || (html && !onlyCodeEditorHtml(html))) {
return;
}
e.preventDefault();
var bookmark = editor.selection.getBookmark(2, true);
post('markdown_to_html', { markdown: text }).then(function (answer) {
editor.selection.moveToBookmark(bookmark);
editor.undoManager.transact(function () {
// Without the wrapper a Markdown document's HTML comes in - it joins what is there
editor.insertContent(answer.html.replace(/^\s*<div class="itflow-markdown">([\s\S]*)<\/div>\s*$/, '$1'));
});
editor.notificationManager.open({ text: 'Pasted as formatting from Markdown - Ctrl+Shift+V pastes it as it is.', type: 'info', timeout: 4000 });
}).catch(function () {
editor.selection.moveToBookmark(bookmark);
editor.execCommand('mceInsertClipboardContent', false, { text: text });
});
}, true);
});
}
})();