/* * 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. 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. */ (function () { 'use strict'; if (window.itflowDocumentFormat) { return; } var REMEMBER = 'itflow.documentFormat'; function post(action, data) { return fetch('/agent/ajax.php?' + action, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, credentials: 'same-origin', body: new URLSearchParams(data).toString() }).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 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(); } }); // 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'; preview.hidden = which !== 'preview'; if (which !== 'preview') { input.focus(); return; } var text = withPictures(input.value); if (state.shownFor === text) { return; } preview.innerHTML = '

Getting the preview

'; if (text.trim() === '') { state.shownFor = text; preview.innerHTML = '

Nothing written yet.

'; 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(/<[^>]*>| |\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-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 || !(element.classList.contains('tinymce') || element.classList.contains('tinymce-page'))) { 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*
([\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); }); } })();