reimplemented editor

This commit is contained in:
evilchili committed 2025-11-27 01:57:25 -08:00
1 parent ce2c65cce1
commit c540073b66
10 files changed
+11779 -489

No files matched your search

+1
View File
@@ -36,6 +36,7 @@
{% endblock %}
</footer>
<script src="{{ url_for('static', filename='site.js') }}"></script>
{% block scripts %}{% endblock %}
</body>
</html>
+7 -13
View File
@@ -1,26 +1,20 @@
{% extends "base.html" %}
{% block styles %}
{% if user.can_write(page) %}
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='editor/editor.css' ) }}">
{% else %}
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='viewer/viewer.css' ) }}">
{% endif %}
{% endblock %}
{% block content %}
<div id='{% if user.can_write(page) %}editor{% else %}viewer{% endif %}' class='read-only'></div>
<div id='{% if user.can_write(page) %}editor{% else %}viewer{% endif %}' class='read-only'>
{{ page.body }}
</div>
{% endblock %}
{% block scripts %}
{% if user.can_write(page) %}
<script src="{{ url_for('static', filename='editor/toastui-editor-all.min.js' ) }}"></script>
<script src="{{ url_for('static', filename='editor/editor.js' ) }}"></script>
<script>initialize("{{ app.config.VIEW_URI }}");</script>
{% else %}
<script src="{{ url_for('static', filename='viewer/toastui-editor-viewer.min.js' ) }}"></script>
<script src="{{ url_for('static', filename='viewer/viewer.js' ) }}"></script>
{% endif %}
<script src="{{ url_for('static', filename='editor/commonmark.js' ) }}"></script>
<script src="{{ url_for('static', filename='editor/turndown.js' ) }}"></script>
<script src="{{ url_for('static', filename='editor/turndown-plugin-gfm.js' ) }}"></script>
<script src="{{ url_for('static', filename='editor/editor.js' ) }}"></script>
{% endblock %}
File diff suppressed because it is too large. Load diff
@@ -1,106 +1,22 @@
@import 'toastui-editor.min.css';
#editor {
display: inline;
}
.toastui-editor-defaultUI-toolbar {
padding: 0px !important;
margin: 0px !important;
border: 0px !important;
background: transparent !important;
}
.toastui-editor-toolbar {
box-shadow: 0px 3px 5px #CCC;
margin-bottom: 20px !important;
}
.toastui-editor-main-container {
display: contents;
}
.toastui-editor,
.toastui-editor-main,
.toastui-editor-md-container,
.toastui-editor-defaultUI,
.toastui-editor-contents,
.toastui-editor-ww-mode,
.toastui-editor-md-preview,
.toastui-editor-md,
.ProseMirror {
border: 0px !important;
padding: 0px !important;
margin: 0px !important;
font-size: var(--default-font-size) !important;
font-family: var(--default-font-family) !important;
}
#editor .toastui-editor-md-container > div > div,
#editor .toastui-editor-ww-container > div > div {
border: 1px dotted #ccc;
}
#editor .toastui-editor-defaultUI-toolbar {
margin-bottom: 20px;
}
#editor .toastui-editor-toolbar {
position: sticky !important;
top: 0 !important;
z-index: 99 !important;
width: 100% !important;
background: #FFF !important;
}
/* applied to #editor */
.read-only {
}
#editor.read-only .toastui-editor-toolbar {
box-shadow: none;
}
#editor.read-only .toastui-editor-ww-container > div > div {
background: #FFF;
}
div.toastui-editor-md-splitter,
div.toastui-editor-md-preview {
display: none !Important;
}
div.toastui-editor.md-mode {
width: 100% !important;
}
#editor button.toastui-editor-toolbar-icons {
filter:unset;
pointer-events: all;
opacity: 1.0;
}
#editor.read-only button.toastui-editor-toolbar-icons {
filter:saturate(0) !Important;
pointer-events: none;
opacity: 0.3;
}
#editor button.actions {
background-image: none;
margin: 0;
}
#editor.read-only button.actions {
display: none;
}
#editor.read-only #toggleButton {
display: block !important;
#editor.loaded {
display: block;
}
#editor.view {
}
.toastui-editor-defaultUI-toolbar > div:nth-child(5) {
flex: auto;
justify-content: flex-end;
#editor.edit {
font-family: monospace;
white-space: pre;
}
#editor.wysiwyg {
}
#editor.wysiwyg .md {
opacity: 0.5;
}
+335 -287
View File
@@ -1,295 +1,343 @@
var editor = document.querySelector("#editor");
class Editor {
var toolBar = null;
var contents = null;
var pageContent = null;
var saveButton = null;
var editorUI = null;
var VIEW_URI = null;;
APIv1 = {
get: function(doc_id, callback) {
(async () => {
const raw = await fetch('/_/v1/get/' + doc_id, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
const res = await raw.json();
if (res['code'] != 200) {
console.error("APIv1 error: ", res)
}
callback(res);
})();
},
put: function(data, callback) {
(async () => {
const raw = await fetch('/_/v1/put/' + window.location.pathname, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'body': data
}),
});
const res = await raw.json();
if (res['code'] != 200) {
console.error("APIv1 error: ", res)
}
callback(res);
})();
},
search: function(space, query, callback) {
(async () => {
const raw = await fetch('/_/v1/search/' + space, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'body': query
}),
});
const res = await raw.json();
if (res['code'] != 200) {
console.error("APIv1 error: ", res)
}
callback(res);
})();
},
};
isReadOnly = function() {
if (editor) {
return editor.className == 'read-only';
#states = {
VIEW: 'view',
EDIT: 'edit',
WYSIWYG: 'wysiwyg'
}
return undefined;
}
setReadOnly = function() {
pageContent.innerHTML = editorUI.getHTML();
editorUI.changeMode('wysiwig');
editorUI.blur();
editor.classList.add('read-only');
pageContent.contentEditable = false;
}
setEditable = function() {
editor.classList.remove('read-only');
pageContent.contentEditable = true;
editorUI.moveCursorToStart();
editorUI.focus();
}
makeMarkdownButton = function() {
button = document.createElement('button');
button.classList.add("toastui-editor-toolbar-icons");
button.classList.add("last");
button.ariaLabel = "Toggle Markdown";
button.style.backgroundImage = 'none';
button.innerHTML = 'MD';
button.style.margin = '0';
button.addEventListener('click', () => {
if (editorUI.isMarkdownMode()) {
editorUI.changeMode("wysiwig");
} else {
editorUI.changeMode("markdown");
}
});
return button;
};
makeSaveButton = function() {
const button = document.createElement('button');
button.className = 'actions';
button.innerHTML = 'save';
button.id = 'saveButton';
button.style.border = "1px solid black";
button.addEventListener('click', () => {
APIv1.put({
'body': editorUI.getMarkdown()
}, (res) => {
if (res['code'] == 200) {
button.style.border = "1px solid green";
} else {
button.style.border = "1px solid red";
}
});
});
saveButton = button;
return button;
};
toggleButton = function() {
const button = document.createElement('button');
button.className = 'actions';
button.id = 'toggleButton';
button.innerHTML = 'edit';
button.addEventListener('click', () => {
if (isReadOnly()) {
setEditable();
} else {
setReadOnly();
}
});
return button;
}
handleContentChange = function() {
}
autoComplete = function(search_string, matches, callback) {
id = `_ac_${search_string}`;
el = document.getElementById(id);
var addEl = false;
if (!el) {
el = document.createElement("ul");
el.id = id;
addEl = true;
}
el.className = 'autocomplete';
el.innerHTML = "";
el.addEventListener("keyup", function(e) {
// do navigation / selection
});
matches.forEach(match => {
var text = match.uri;
for (pos = 0; pos < match.uri.length - search_string.length; pos++) {
var substr = match.name.substring(pos, search_string.length);
if (substr.toLowerCase() == search_string.toLowerCase()) {
text = match.name.substring(0, pos) + "<strong>" + substr + "</strong>" + match.name.substr(pos + substr.length);
break;
}
}
var option = document.createElement("li");
option.innerHTML = text;
option.addEventListener("click", function(e) {
// do selection
});
el.appendChild(option);
});
if (addEl) {
var selection = window.getSelection();
if (selection.rangeCount > 0) {
var range = selection.getRangeAt(0);
range.insertNode(el);
}
}
}
initialize = function(base_uri) {
const macro_rule = /@(\S{3,})/;
VIEW_URI = base_uri;
const ed = new toastui.Editor({
el: editor,
initialEditType: 'wysiwyg',
initialValue: "",
hideModeSwitch : true,
previewStyle: 'vertical',
usageStatistics: false,
autofocus: false,
toolbarItems: [
['heading', 'bold', 'italic' ],
['ul', 'ol', 'indent', 'outdent'],
['table', 'image', 'link'],
[
{ el: makeMarkdownButton(), tooltip: 'Toggle MD' },
],
[
{ el: makeSaveButton(), command: 'save', tooltip: 'Save Changes' },
{ el: toggleButton(), tooltip: 'Toggle Edit Mode' }
],
],
widgetRules: [ ],
commonmark = null;
turndown = null;
#cachedHTML = null;
#cachedMarkdown = null;
#state = null;
#changed = false;
constructor(settings) {
/*
{
rule: macro_rule, toDOM(text) {
const matched = text.match(macro_rule);
const search_string = matched[1];
var replacement = "";
});
console.log(replacement);
return replacement;
},
},
],
*/
events: {
'loadUI': function(e) {
editorUI = e;
pageContent = document.querySelector(".toastui-editor-ww-container > div > div");
toolBar = document.querySelector('.toastui-editor-toolbar');
e.setMarkdown(document.getElementById("data_form__body").value);
setReadOnly();
},
'changeMode': function() {
if (editor && Array(editor.classList).includes('read-only')) {
setReadOnly();
}
},
'change': handleContentChange,
}
});
var searchPos = null;
ed.on('keyup', (editorType, ev) => {
const [start, end] = editorUI.getSelection();
console.log(start, end);
if (ev.key === '@') {
searchPos = start;
console.log(`Setting search position to ${searchPos}`);
return;
}
if (searchPos === null) {
return;
}
var range = window.getSelection().getRangeAt(0);
range.selectNodeContents(editor);
range.setStart(editor, 0);
range.setEnd(editor, end);
var search_string = range.toString();
console.log(search_string);
/*
APIv1.search("", search_string, (res) => {
if (res.code == 404) {
return;
}
const matches = res.response;
if (matches.length == 1) {
replacement = document.createElement('span');
replacement.innerHTML = `<a class="tooltip-preview" data-uri="${matches[0].uri}" href="${VIEW_URI}${matches[0].uri}">${matches[0].name}</a>`;
return;
}
autoComplete(search_string, matches, (selection) => {
console.log(`Selected ${selection}`);
document.remove(options.id);
});
* Create a new Editor instance.
*/
this.element = document.getElementById(settings.editorId || 'editor');
this.source = this.element.innerHTML;
this.commonmark = {
reader: new commonmark.Parser(),
writer: new commonmark.HtmlRenderer(),
};
*/
});
this.turndown = new TurndownService({
headingStyle: 'atx',
codeBlockStyle: 'fenced',
});
return ed;
this.plugins = {};
settings.plugins.forEach(plugin => {
this.plugins[plugin.name] = new plugin({name: plugin.name, editor: this});
});
this.#bindEvents();
this.getHTML();
this.element.classList.add("loaded");
}
#bindEvents() {
this.element.addEventListener('keydown', (evt) => {
if (this.#state === this.#states.VIEW) {
return;
}
if (event.key === 'Enter') {
if (this.#state === this.#states.EDIT) {
evt.preventDefault();
this.insertAtCursor(document.createTextNode("\n"));
}
}
if (this.#cachedMarkdown != this.element.innerHTML) {
this.#changed = true;
this.#cachedMarkdown = this.element.innerHTML;
}
});
};
getState() {
return this.#state;
}
setState(newState) {
this.#state = newState;
Object.values(this.#states).forEach(state => {
if (state == newState) {
this.element.classList.add(state);
} else {
this.element.classList.remove(state);
}
});
}
getHTML() {
/*
* Convert the markdown source to HTML.
*/
if (this.#changed || !this.#cachedHTML) {
var md = this.getMarkdown();
var parsed = this.commonmark.reader.parse(md);
var html = this.commonmark.writer.render(parsed);
Object.values(this.plugins).forEach(plugin => {
html = plugin.toHTML(html);
});
this.#cachedHTML = html;
}
return this.#cachedHTML;
}
getMarkdown() {
/*
* Return the current markdown.
*/
if (this.getState() === this.#states.EDIT) {
this.#cachedMarkdown = this.element.innerHTML;
} else if (this.getState() === this.#states.WYSIWYG) {
var md = this.element.innerHTML;
Object.values(this.plugins).forEach(plugin => {
md = plugin.toMarkdown(md);
});
this.#cachedMarkdown = this.turndown.turndown(md);
} else if (!this.#cachedMarkdown) {
this.#cachedMarkdown = this.source;
}
this.#cachedMarkdown = this.#cachedMarkdown.replaceAll(/^&gt;/mg, '>');
return this.#cachedMarkdown;
}
reset() {
/*
* Discard any unsaved edits and reset the editor to its initial state.
*/
this.#cachedHTML = null;
this.#cachedMarkdown = null;
this.view();
}
view() {
/*
* Convert the editor read-only mode and display the current HTML.
*/
if (this.getState() === this.#states.VIEW) {
return;
}
this.element.innerHTML = this.getHTML();
this.setState(this.#states.VIEW);
}
wysiwyg() {
/*
* Put the editor in WYSIWYG editing mode.
*/
if (this.getState() === this.#states.WYSIWYG) {
return;
}
this.#changed = false;
this.element.contentEditable = true;
this.element.innerHTML = this.getHTML();
this.setState(this.#states.WYSIWYG);
}
edit() {
/*
* Put the editor into source editing mode.
*/
if (this.#state === this.#states.EDIT) {
return;
}
this.#changed = false;
this.element.contentEditable = true;
this.element.innerHTML = this.getMarkdown();
this.setState(this.#states.EDIT);
}
insertAtCursor(node) {
var sel, range, html;
sel = window.getSelection();
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(node);
range.setStartAfter(node);
this.element.focus();
sel.removeAllRanges();
sel.addRange(range);
}
}
class EditorPlugin {
constructor(settings) {
this.name = settings.name;
this.editor = settings.editor;
};
cleanAttribute(attribute) {
return attribute ? attribute.replace(/(\n+\s*)+/g, '\n') : ''
}
toMarkdown(html) {
return html;
};
toHTML(md) {
return md;
};
};
class TablePlugin extends EditorPlugin {
constructor(settings) {
super(settings);
this.editor.turndown.use(turndownPluginGfm.tables);
this.pattern = /(?<contents>(?:\|[^|]+?)+\|[\s\n]*)(?:<|$)/gims;
this.dividerPattern = /\|\s*\-+\s*\|/;
}
toHTML(md) {
md.matchAll(this.pattern).forEach(matched => {
var html = '<table><thead>';
var cellTag = 'th';
matched.groups.contents.split("\n").forEach(line => {
if (this.dividerPattern.test(line)) {
html += "</thead><tbody>";
cellTag = 'td';
} else {
html += "<tr>";
var cells = line.split("|");
html += "<" + cellTag + ">" + cells.slice(1, cells.length - 1).join("</" + cellTag + "><" + cellTag + ">") + "</" + cellTag + ">";
html += "</tr>";
}
});
html += "</tbody></table>";
md = md.replaceAll(matched[1], html);
});
return md;
}
}
class MacroPlugin extends EditorPlugin {
macros = {
// image: {}
// toc {}
// widget {}
//
html: {
toHTML: (settings) => {
var html = settings.block.replaceAll("&gt;", ">").replaceAll("&lt;", "<");
return html;
},
toMarkdown: (node) => {
const utf8encoder = new TextEncoder();
return "{{html\n" + b64decode(node.dataset.block) + "\n}}";
}
},
user: {
toHTML: (settings) => {
return document.querySelector("nav > ul > li.user > a:first-child").outerHTML;
},
},
npc: {
toHTML: (settings) => {
var name = camelCase(settings.keywords).join(" ");
var target = name.replaceAll(" ", "");
return `<a href="/NPC/${target}" data-npc-name="${name}">👤 ${name}</a>`;
},
toMarkdown: (node) => {
return `{{npc ${node.firstChild.dataset.npcName}}}`;
},
},
spell: {
toHTML: (settings) => {
var name = camelCase(settings.keywords).join(" ");
var target = name.replaceAll(" ", "");
return `<a href="/Spell/${target}" data-spell-name="${name}">✨ ${name}</a>`;
},
toMarkdown: (node) => {
return `{{spell ${node.firstChild.dataset.spellName}}}`;
},
},
}
constructor(settings) {
super(settings);
this.pattern = /(?<contents>{{(?<name>\w+)(?<keywords>(?:\s*\w+)*)(?<parameters>(?:\s+\w+="[^"]*")*?)(?<block>\b.*?)?}})/gms;
this.paramPattern = /\b(?<name>[^=]+)="(?<value>[^"]*?)"\b/gm;
var plugin = this;
this.editor.turndown.addRule('macros', {
filter: ['span'],
replacement: function (content, node, options) {
const parser = plugin.macros[node.getAttribute('data-macro-name')].toMarkdown;
if (parser) {
return parser(node);
}
var md = '{{' + node.getAttribute('data-macro-name');
for (var param in node.getAttributeNames()) {
var val = node.getAttribute(param);
if (val) {
md += val + (param == 'data-macro-name' ? " " : `="${node.getAttribute(param)}" `);
}
}
md += '}}';
return md;
},
});
}
toHTML(md) {
const utf8encoder = new TextEncoder();
var output = md;
output.matchAll(this.pattern).forEach(matched => {
var macroName = matched.groups.name;
var html = `<span class='macro' data-macro-name='${macroName}'`;
var settings = {
block: matched.groups.block,
keywords: matched.groups.keywords,
params: {},
}
matched.groups.parameters.matchAll(this.paramPattern).forEach(param => {
settings.params[param.groups.name] = param.groups.value;
html += ` data-param-${param.groups.name}="${param.groups.value}"`;
});
html += ` data-block="${b64encode(matched.groups.block)}"`;
html += '>';
html += this.macros[macroName].toHTML(settings);
html += '</span>';
output = output.replaceAll(matched[1], html);
});
return output;
}
}
function camelCase(words) {
var output = [];
words.trim().split(/\s+/g).forEach(word => {
var lcWord = word.toLowerCase();
output.push(lcWord.charAt(0).toUpperCase() + lcWord.slice(1));
});
return output;
}
function b64encode(input) {
const utf8encoder = new TextEncoder();
return utf8encoder.encode(input).toBase64();
}
function b64decode(input) {
const utf8encoder = new TextEncoder();
return utf8encoder.decode(input.fromBase64());
}
editor = new Editor({
plugins: [TablePlugin, MacroPlugin]
});
editor.view();
@@ -1,24 +0,0 @@
/*!
* @toast-ui/editor
* @version 3.2.2 | Fri Feb 17 2023
* @author NHN Cloud FE Development Lab <dl_javascript@nhn.com>
* @license MIT
*/
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.toastui=t():(e.toastui=e.toastui||{},e.toastui.Editor=t())}(self,(function(){return function(){var e={368:function(e){
/*! @license DOMPurify 2.3.3 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.3.3/LICENSE */
e.exports=function(){"use strict";function e(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}var t=Object.hasOwnProperty,n=Object.setPrototypeOf,r=Object.isFrozen,o=Object.getPrototypeOf,i=Object.getOwnPropertyDescriptor,s=Object.freeze,a=Object.seal,l=Object.create,c="undefined"!=typeof Reflect&&Reflect,u=c.apply,d=c.construct;u||(u=function(e,t,n){return e.apply(t,n)}),s||(s=function(e){return e}),a||(a=function(e){return e}),d||(d=function(t,n){return new(Function.prototype.bind.apply(t,[null].concat(e(n))))});var p=x(Array.prototype.forEach),h=x(Array.prototype.pop),f=x(Array.prototype.push),m=x(String.prototype.toLowerCase),g=x(String.prototype.match),v=x(String.prototype.replace),y=x(String.prototype.indexOf),b=x(String.prototype.trim),w=x(RegExp.prototype.test),k=C(TypeError);function x(e){return function(t){for(var n=arguments.length,r=Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return u(e,t,r)}}function C(e){return function(){for(var t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return d(e,n)}}function T(e,t){n&&n(e,null);for(var o=t.length;o--;){var i=t[o];if("string"==typeof i){var s=m(i);s!==i&&(r(t)||(t[o]=s),i=s)}e[i]=!0}return e}function M(e){var n=l(null),r=void 0;for(r in e)u(t,e,[r])&&(n[r]=e[r]);return n}function S(e,t){for(;null!==e;){var n=i(e,t);if(n){if(n.get)return x(n.get);if("function"==typeof n.value)return x(n.value)}e=o(e)}function r(e){return console.warn("fallback value for",e),null}return r}var E=s(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),N=s(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),O=s(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),D=s(["animate","color-profile","cursor","discard","fedropshadow","feimage","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),A=s(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover"]),L=s(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),I=s(["#text"]),R=s(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","xmlns","slot"]),P=s(["accent-height","accumulatLine truncated
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};function t(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var o=function(){return o=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},o.apply(this,arguments)};Object.create;function i(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))}function s(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}Object.create;function a(e){this.content=e}a.prototype={constructor:a,find:function(e){for(var t=0;t<this.content.length;t+=2)if(this.content[t]===e)return t;return-1},get:function(e){var t=this.find(e);return-1==t?void 0:this.content[t+1]},update:function(e,t,n){var r=n&&n!=e?this.remove(n):this,o=r.find(e),i=r.content.slice();return-1==o?i.push(n||e,t):(i[o+1]=t,n&&(i[o]=n)),new a(i)},remove:function(e){var t=this.find(e);if(-1==t)return this;var n=this.content.slice();return n.splice(t,2),new a(n)},addToStart:function(e,t){return new a([e,t].concat(this.remove(e).content))},addToEnd:function(e,t){var n=this.remove(e).content.slice();return n.push(e,t),new a(n)},addBefore:function(e,t,n){var r=this.remove(t),o=r.content.slice(),i=r.find(e);return o.splice(-1==i?o.length:i,0,t,n),new a(o)},forEach:function(e){for(var t=0;t<this.content.length;t+=2)e(this.content[t],this.content[t+1])},prepend:function(e){return(e=a.from(e)).size?new a(e.content.concat(this.subtract(e).content)):this},append:function(e){return(e=a.from(e)).size?new a(this.subtract(e).content.concat(e.content)):this},subtract:function(e){var t=this;e=a.from(e);for(var n=0;n<e.content.length;n+=2)t=t.remove(e.content[n]);return t},get size(){return this.content.length>>1}},a.from=function(e){if(e instanceof a)return e;var t=[];if(e)for(var n in e)t.push(n,e[n]);return new a(t)};var l=a;function c(e,t,n){for(let r=0;;r++){if(r==e.childCount||r==t.childCount)return e.childCount==t.childCount?null:n;let o=e.child(r),i=t.child(r);if(o!=i){if(!o.sameMarkup(i))return n;if(o.isText&&o.text!=i.text){for(let e=0;o.text[e]==i.text[e];e++)n++;return n}if(o.content.size||i.content.size){let e=c(o.content,i.content,n+1);if(null!=e)return e}n+=o.nodeSize}else n+=o.nodeSize}}function u(e,t,n,r){for(let o=e.childCount,i=t.childCount;;){if(0==o||0==i)return o==i?null:{a:n,b:r};let s=e.child(--o),a=t.child(--i),l=s.nodeSize;if(s!=a){if(!s.sameMarkup(a))return{a:n,b:r};if(s.isText&&s.text!=a.text){let e=0,t=Math.min(s.text.length,a.text.length);for(;e<t&&s.text[s.text.length-e-1]==a.text[a.text.length-e-1];)e++,n--,r--;return{a:n,b:r}}if(s.content.size||a.content.size){let e=u(s.content,a.content,n-1,r-1);if(e)return e}n-=l,r-=l}else n-=l,r-=l}}class d{constructor(e,t){if(this.content=e,this.size=t||0,null==t)for(let t=0;t<e.length;t++)this.size+=e[t].nodeSize}nodesBetween(e,t,n,r=0,o){for(let i=0,s=0;s<t;i++){let a=this.content[i],l=s+a.nodeSize;if(l>e&&!1!==n(a,r+s,o||null,i)&&a.content.size){let o=s+1;a.nodesBetween(Math.max(0,e-o),Math.min(a.content.size,t-o),n,r+o)}s=l}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,n,r){let o="",i=!0;return this.nodesBetween(e,t,((s,a)=>{s.isText?(o+=s.text.slice(Math.max(e,a)-a,t-a),i=!n):s.isLeaf?(r?o+="function"==typeof r?r(s):r:s.type.spec.leafText&&(o+=s.type.spec.leafText(s)),i=!n):!i&&s.isBlock&&(o+=n,i=!0)}),0),o}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,n=e.firstChild,r=this.content.slice(),o=0;for(t.isText&&t.sameMarkup(n)&&(r[r.length-1]=t.withText(t.text+n.text),o=1);o<e.content.length;o++)r.push(e.content[o]);return new d(r,this.size+e.size)}cut(e,t=this.size){if(0==e&&t==this.size)return this;let n=[],r=0;if(t>e)for(let o=0,i=0;i<t;o++){let s=this.content[o],a=i+s.nodeSize;a>e&&((i<e||a>t)&&(s=s.isText?s.cut(Math.max(0,e-i),Math.min(s.text.length,t-i)):s.cut(Math.max(0,e-i-1),Math.min(s.content.size,t-i-1))),n.push(s),r+=s.nodeSize),i=a}return new d(n,r)}cutByIndex(e,t){return e==t?d.empty:0==e&&t==this.content.length?this:new d(this.content.slice(e,t))}replaceChild(e,t){let n=this.content[e];if(n==t)return this;let r=this.content.slice(),o=this.size+t.nodeSize-n.nodeSize;return r[e]=t,new d(r,o)}addToStart(e){return new d([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new d(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;t<this.content.length;t++)if(!this.content[t].eq(e.content[t]))return!1;return!0}get firstChild(){return Line truncated
@@ -1,6 +0,0 @@
/*!
* @toast-ui/editor
* @version 3.2.2 | Fri Feb 17 2023
* @author NHN Cloud FE Development Lab <dl_javascript@nhn.com>
* @license MIT
*/.ProseMirror{word-wrap:break-word;font-feature-settings:"liga" 0;-webkit-font-variant-ligatures:none;font-variant-ligatures:none;position:relative;white-space:pre-wrap;white-space:break-spaces}.ProseMirror pre{white-space:pre-wrap}.ProseMirror li{position:relative}.ProseMirror-hideselection ::selection{background:transparent}.ProseMirror-hideselection ::-moz-selection{background:transparent}.ProseMirror-hideselection{caret-color:transparent}.ProseMirror-selectednode{outline:2px solid #8cf}li.ProseMirror-selectednode{outline:none}li.ProseMirror-selectednode:after{border:2px solid #8cf;bottom:-2px;content:"";left:-32px;pointer-events:none;position:absolute;right:-2px;top:-2px}img.ProseMirror-separator{border:none!important;display:inline!important;margin:0!important}.auto-height,.auto-height .toastui-editor-defaultUI{height:auto}.auto-height .toastui-editor-md-container{position:relative}:not(.auto-height)>.toastui-editor-defaultUI,:not(.auto-height)>.toastui-editor-defaultUI>.toastui-editor-main{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}:not(.auto-height)>.toastui-editor-defaultUI>.toastui-editor-main{-ms-flex:1;flex:1}.toastui-editor-defaultUI-toolbar:after,.toastui-editor-md-container:after{clear:both;content:"";display:block;height:0}.toastui-editor-main{box-sizing:border-box;height:inherit;min-height:0;position:relative}.toastui-editor-md-container{display:none;height:100%;overflow:hidden}.toastui-editor-md-container .toastui-editor{line-height:1.5;position:relative}.toastui-editor-md-container .toastui-editor,.toastui-editor-md-container .toastui-editor-md-preview{box-sizing:border-box;height:inherit;padding:0}.toastui-editor-md-container .toastui-editor-md-preview{height:100%;overflow:auto;padding:0 25px}.toastui-editor-md-container .toastui-editor-md-preview>p:first-child{margin-top:0!important}.toastui-editor-md-container .toastui-editor-md-preview .toastui-editor-contents{padding-top:8px}.toastui-editor-main .toastui-editor-md-tab-style>.toastui-editor,.toastui-editor-main .toastui-editor-md-tab-style>.toastui-editor-md-preview{display:none;width:100%}.toastui-editor-main .toastui-editor-md-tab-style>.active{display:block}.toastui-editor-main .toastui-editor-md-vertical-style>.toastui-editor-tabs{display:none}.toastui-editor-main .toastui-editor-md-tab-style>.toastui-editor-tabs{display:block}.toastui-editor-main .toastui-editor-md-vertical-style .toastui-editor,.toastui-editor-main .toastui-editor-md-vertical-style .toastui-editor-md-preview{width:50%}.toastui-editor-main .toastui-editor-md-splitter{background-color:#ebedf2;display:none;height:100%;left:50%;position:absolute;width:1px}.toastui-editor-main .toastui-editor-md-vertical-style .toastui-editor-md-splitter{display:block}.toastui-editor-ww-container{background-color:#fff;display:none;height:inherit;overflow:hidden}.auto-height .toastui-editor-main-container{position:relative}.toastui-editor-main-container{color:#222;height:inherit;line-height:1;position:absolute;width:100%}.toastui-editor-ww-container>.toastui-editor{height:inherit;position:relative;width:100%}.toastui-editor-ww-container .toastui-editor-contents{box-sizing:border-box;height:inherit;margin:0;overflow:auto;padding:16px 25px 0}.toastui-editor-ww-container .toastui-editor-contents p{margin:0}.toastui-editor-md-mode .toastui-editor-md-container,.toastui-editor-ww-mode .toastui-editor-ww-container{display:block;z-index:20}.toastui-editor-md-mode .toastui-editor-md-vertical-style{display:-ms-flexbox;display:flex}.toastui-editor-defaultUI.hidden,.toastui-editor-main.hidden{display:none}.toastui-editor-defaultUI .ProseMirror{padding:18px 25px}.toastui-editor-defaultUI{border:1px solid #dadde6;border-radius:4px;font-family:Open Sans,Helvetica Neue,Helvetica,Arial,나눔바른고딕,Nanum Barun Gothic,맑은고딕,Malgun Gothic,sans-serif;height:100%;position:relative}.toastui-editor-defaultUI button{border:none;border-radius:2px;color:#333;cursor:pointer;font-size:13px;height:28px}.toastui-editor-defaultUI .toastui-editor-ok-button{background-color:#00a9ff;color:#fff;height:32px;min-width:63px;outline-color:#009bf2}.toastui-editor-defaultUI .toastui-editor-ok-button:hover{background-color:#009bf2}.toastui-editor-defaultUI .toastui-editor-close-button{background-color:#f7f9fc;border:1px solid #dadde6;height:32px;margin-right:5px;min-width:63px;outline-color:#cbcfdb}.toastui-editor-defaultUI .toastui-editor-close-button:hover{border-color:#cbcfdb}.toastui-editor-mode-switch{background-color:#fff;border-radius:0 0 3px 3px;border-top:1px solid #dadde6;font-size:12px;height:28px;padding-right:10px;text-align:right}.toastui-editor-mode-switch .tab-item{background:#f7f9fc;border:1px solid #dadde6;border-radius:0 0 4px 4px;box-sizing:border-box;color:#969aa5;cursor:pointer;display:inline-block;font-weight:500;height:24px;line-height:24px;margin-right:-1px;margin-top:-1px;text-align:center;width:96px}.toastui-editor-mode-switch .tab-item.active{bacLine truncated
@@ -0,0 +1,165 @@
var turndownPluginGfm = (function (exports) {
'use strict';
var highlightRegExp = /highlight-(?:text|source)-([a-z0-9]+)/;
function highlightedCodeBlock (turndownService) {
turndownService.addRule('highlightedCodeBlock', {
filter: function (node) {
var firstChild = node.firstChild;
return (
node.nodeName === 'DIV' &&
highlightRegExp.test(node.className) &&
firstChild &&
firstChild.nodeName === 'PRE'
)
},
replacement: function (content, node, options) {
var className = node.className || '';
var language = (className.match(highlightRegExp) || [null, ''])[1];
return (
'\n\n' + options.fence + language + '\n' +
node.firstChild.textContent +
'\n' + options.fence + '\n\n'
)
}
});
}
function strikethrough (turndownService) {
turndownService.addRule('strikethrough', {
filter: ['del', 's', 'strike'],
replacement: function (content) {
return '~' + content + '~'
}
});
}
var indexOf = Array.prototype.indexOf;
var every = Array.prototype.every;
var rules = {};
rules.tableCell = {
filter: ['th', 'td'],
replacement: function (content, node) {
return cell(content, node)
}
};
rules.tableRow = {
filter: 'tr',
replacement: function (content, node) {
var borderCells = '';
var alignMap = { left: ':--', right: '--:', center: ':-:' };
if (isHeadingRow(node)) {
for (var i = 0; i < node.childNodes.length; i++) {
var border = '---';
var align = (
node.childNodes[i].getAttribute('align') || ''
).toLowerCase();
if (align) border = alignMap[align] || border;
borderCells += cell(border, node.childNodes[i]);
}
}
return '\n' + content + (borderCells ? '\n' + borderCells : '')
}
};
rules.table = {
// Only convert tables with a heading row.
// Tables with no heading row are kept using `keep` (see below).
filter: function (node) {
return node.nodeName === 'TABLE' && isHeadingRow(node.rows[0])
},
replacement: function (content) {
// Ensure there are no blank lines
content = content.replace('\n\n', '\n');
return '\n\n' + content + '\n\n'
}
};
rules.tableSection = {
filter: ['thead', 'tbody', 'tfoot'],
replacement: function (content) {
return content
}
};
// A tr is a heading row if:
// - the parent is a THEAD
// - or if its the first child of the TABLE or the first TBODY (possibly
// following a blank THEAD)
// - and every cell is a TH
function isHeadingRow (tr) {
var parentNode = tr.parentNode;
return (
parentNode.nodeName === 'THEAD' ||
(
parentNode.firstChild === tr &&
(parentNode.nodeName === 'TABLE' || isFirstTbody(parentNode)) &&
every.call(tr.childNodes, function (n) { return n.nodeName === 'TH' })
)
)
}
function isFirstTbody (element) {
var previousSibling = element.previousSibling;
return (
element.nodeName === 'TBODY' && (
!previousSibling ||
(
previousSibling.nodeName === 'THEAD' &&
/^\s*$/i.test(previousSibling.textContent)
)
)
)
}
function cell (content, node) {
var index = indexOf.call(node.parentNode.childNodes, node);
var prefix = ' ';
if (index === 0) prefix = '| ';
return prefix + content + ' |'
}
function tables (turndownService) {
turndownService.keep(function (node) {
return node.nodeName === 'TABLE' && !isHeadingRow(node.rows[0])
});
for (var key in rules) turndownService.addRule(key, rules[key]);
}
function taskListItems (turndownService) {
turndownService.addRule('taskListItems', {
filter: function (node) {
return node.type === 'checkbox' && node.parentNode.nodeName === 'LI'
},
replacement: function (content, node) {
return (node.checked ? '[x]' : '[ ]') + ' '
}
});
}
function gfm (turndownService) {
turndownService.use([
highlightedCodeBlock,
strikethrough,
tables,
taskListItems
]);
}
exports.gfm = gfm;
exports.highlightedCodeBlock = highlightedCodeBlock;
exports.strikethrough = strikethrough;
exports.tables = tables;
exports.taskListItems = taskListItems;
return exports;
}({}));
@@ -0,0 +1,976 @@
var TurndownService = (function () {
'use strict';
function extend (destination) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (source.hasOwnProperty(key)) destination[key] = source[key];
}
}
return destination
}
function repeat (character, count) {
return Array(count + 1).join(character)
}
function trimLeadingNewlines (string) {
return string.replace(/^\n*/, '')
}
function trimTrailingNewlines (string) {
// avoid match-at-end regexp bottleneck, see #370
var indexEnd = string.length;
while (indexEnd > 0 && string[indexEnd - 1] === '\n') indexEnd--;
return string.substring(0, indexEnd)
}
function trimNewlines (string) {
return trimTrailingNewlines(trimLeadingNewlines(string))
}
var blockElements = [
'ADDRESS', 'ARTICLE', 'ASIDE', 'AUDIO', 'BLOCKQUOTE', 'BODY', 'CANVAS',
'CENTER', 'DD', 'DIR', 'DIV', 'DL', 'DT', 'FIELDSET', 'FIGCAPTION', 'FIGURE',
'FOOTER', 'FORM', 'FRAMESET', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEADER',
'HGROUP', 'HR', 'HTML', 'ISINDEX', 'LI', 'MAIN', 'MENU', 'NAV', 'NOFRAMES',
'NOSCRIPT', 'OL', 'OUTPUT', 'P', 'PRE', 'SECTION', 'TABLE', 'TBODY', 'TD',
'TFOOT', 'TH', 'THEAD', 'TR', 'UL'
];
function isBlock (node) {
return is(node, blockElements)
}
var voidElements = [
'AREA', 'BASE', 'BR', 'COL', 'COMMAND', 'EMBED', 'HR', 'IMG', 'INPUT',
'KEYGEN', 'LINK', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR'
];
function isVoid (node) {
return is(node, voidElements)
}
function hasVoid (node) {
return has(node, voidElements)
}
var meaningfulWhenBlankElements = [
'A', 'TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TH', 'TD', 'IFRAME', 'SCRIPT',
'AUDIO', 'VIDEO'
];
function isMeaningfulWhenBlank (node) {
return is(node, meaningfulWhenBlankElements)
}
function hasMeaningfulWhenBlank (node) {
return has(node, meaningfulWhenBlankElements)
}
function is (node, tagNames) {
return tagNames.indexOf(node.nodeName) >= 0
}
function has (node, tagNames) {
return (
node.getElementsByTagName &&
tagNames.some(function (tagName) {
return node.getElementsByTagName(tagName).length
})
)
}
var rules = {};
rules.paragraph = {
filter: 'p',
replacement: function (content) {
return '\n\n' + content + '\n\n'
}
};
rules.lineBreak = {
filter: 'br',
replacement: function (content, node, options) {
return options.br + '\n'
}
};
rules.heading = {
filter: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
replacement: function (content, node, options) {
var hLevel = Number(node.nodeName.charAt(1));
if (options.headingStyle === 'setext' && hLevel < 3) {
var underline = repeat((hLevel === 1 ? '=' : '-'), content.length);
return (
'\n\n' + content + '\n' + underline + '\n\n'
)
} else {
return '\n\n' + repeat('#', hLevel) + ' ' + content + '\n\n'
}
}
};
rules.blockquote = {
filter: 'blockquote',
replacement: function (content) {
content = trimNewlines(content).replace(/^/gm, '> ');
return '\n\n' + content + '\n\n'
}
};
rules.list = {
filter: ['ul', 'ol'],
replacement: function (content, node) {
var parent = node.parentNode;
if (parent.nodeName === 'LI' && parent.lastElementChild === node) {
return '\n' + content
} else {
return '\n\n' + content + '\n\n'
}
}
};
rules.listItem = {
filter: 'li',
replacement: function (content, node, options) {
var prefix = options.bulletListMarker + ' ';
var parent = node.parentNode;
if (parent.nodeName === 'OL') {
var start = parent.getAttribute('start');
var index = Array.prototype.indexOf.call(parent.children, node);
prefix = (start ? Number(start) + index : index + 1) + '. ';
}
var isParagraph = /\n$/.test(content);
content = trimNewlines(content) + (isParagraph ? '\n' : '');
content = content.replace(/\n/gm, '\n' + ' '.repeat(prefix.length)); // indent
return (
prefix + content + (node.nextSibling ? '\n' : '')
)
}
};
rules.indentedCodeBlock = {
filter: function (node, options) {
return (
options.codeBlockStyle === 'indented' &&
node.nodeName === 'PRE' &&
node.firstChild &&
node.firstChild.nodeName === 'CODE'
)
},
replacement: function (content, node, options) {
return (
'\n\n ' +
node.firstChild.textContent.replace(/\n/g, '\n ') +
'\n\n'
)
}
};
rules.fencedCodeBlock = {
filter: function (node, options) {
return (
options.codeBlockStyle === 'fenced' &&
node.nodeName === 'PRE' &&
node.firstChild &&
node.firstChild.nodeName === 'CODE'
)
},
replacement: function (content, node, options) {
var className = node.firstChild.getAttribute('class') || '';
var language = (className.match(/language-(\S+)/) || [null, ''])[1];
var code = node.firstChild.textContent;
var fenceChar = options.fence.charAt(0);
var fenceSize = 3;
var fenceInCodeRegex = new RegExp('^' + fenceChar + '{3,}', 'gm');
var match;
while ((match = fenceInCodeRegex.exec(code))) {
if (match[0].length >= fenceSize) {
fenceSize = match[0].length + 1;
}
}
var fence = repeat(fenceChar, fenceSize);
return (
'\n\n' + fence + language + '\n' +
code.replace(/\n$/, '') +
'\n' + fence + '\n\n'
)
}
};
rules.horizontalRule = {
filter: 'hr',
replacement: function (content, node, options) {
return '\n\n' + options.hr + '\n\n'
}
};
rules.inlineLink = {
filter: function (node, options) {
return (
options.linkStyle === 'inlined' &&
node.nodeName === 'A' &&
node.getAttribute('href')
)
},
replacement: function (content, node) {
var href = node.getAttribute('href');
if (href) href = href.replace(/([()])/g, '\\$1');
var title = cleanAttribute(node.getAttribute('title'));
if (title) title = ' "' + title.replace(/"/g, '\\"') + '"';
return '[' + content + '](' + href + title + ')'
}
};
rules.referenceLink = {
filter: function (node, options) {
return (
options.linkStyle === 'referenced' &&
node.nodeName === 'A' &&
node.getAttribute('href')
)
},
replacement: function (content, node, options) {
var href = node.getAttribute('href');
var title = cleanAttribute(node.getAttribute('title'));
if (title) title = ' "' + title + '"';
var replacement;
var reference;
switch (options.linkReferenceStyle) {
case 'collapsed':
replacement = '[' + content + '][]';
reference = '[' + content + ']: ' + href + title;
break
case 'shortcut':
replacement = '[' + content + ']';
reference = '[' + content + ']: ' + href + title;
break
default:
var id = this.references.length + 1;
replacement = '[' + content + '][' + id + ']';
reference = '[' + id + ']: ' + href + title;
}
this.references.push(reference);
return replacement
},
references: [],
append: function (options) {
var references = '';
if (this.references.length) {
references = '\n\n' + this.references.join('\n') + '\n\n';
this.references = []; // Reset references
}
return references
}
};
rules.emphasis = {
filter: ['em', 'i'],
replacement: function (content, node, options) {
if (!content.trim()) return ''
return options.emDelimiter + content + options.emDelimiter
}
};
rules.strong = {
filter: ['strong', 'b'],
replacement: function (content, node, options) {
if (!content.trim()) return ''
return options.strongDelimiter + content + options.strongDelimiter
}
};
rules.code = {
filter: function (node) {
var hasSiblings = node.previousSibling || node.nextSibling;
var isCodeBlock = node.parentNode.nodeName === 'PRE' && !hasSiblings;
return node.nodeName === 'CODE' && !isCodeBlock
},
replacement: function (content) {
if (!content) return ''
content = content.replace(/\r?\n|\r/g, ' ');
var extraSpace = /^`|^ .*?[^ ].* $|`$/.test(content) ? ' ' : '';
var delimiter = '`';
var matches = content.match(/`+/gm) || [];
while (matches.indexOf(delimiter) !== -1) delimiter = delimiter + '`';
return delimiter + extraSpace + content + extraSpace + delimiter
}
};
rules.image = {
filter: 'img',
replacement: function (content, node) {
var alt = cleanAttribute(node.getAttribute('alt'));
var src = node.getAttribute('src') || '';
var title = cleanAttribute(node.getAttribute('title'));
var titlePart = title ? ' "' + title + '"' : '';
return src ? '![' + alt + ']' + '(' + src + titlePart + ')' : ''
}
};
function cleanAttribute (attribute) {
return attribute ? attribute.replace(/(\n+\s*)+/g, '\n') : ''
}
/**
* Manages a collection of rules used to convert HTML to Markdown
*/
function Rules (options) {
this.options = options;
this._keep = [];
this._remove = [];
this.blankRule = {
replacement: options.blankReplacement
};
this.keepReplacement = options.keepReplacement;
this.defaultRule = {
replacement: options.defaultReplacement
};
this.array = [];
for (var key in options.rules) this.array.push(options.rules[key]);
}
Rules.prototype = {
add: function (key, rule) {
this.array.unshift(rule);
},
keep: function (filter) {
this._keep.unshift({
filter: filter,
replacement: this.keepReplacement
});
},
remove: function (filter) {
this._remove.unshift({
filter: filter,
replacement: function () {
return ''
}
});
},
forNode: function (node) {
if (node.isBlank) return this.blankRule
var rule;
if ((rule = findRule(this.array, node, this.options))) return rule
if ((rule = findRule(this._keep, node, this.options))) return rule
if ((rule = findRule(this._remove, node, this.options))) return rule
return this.defaultRule
},
forEach: function (fn) {
for (var i = 0; i < this.array.length; i++) fn(this.array[i], i);
}
};
function findRule (rules, node, options) {
for (var i = 0; i < rules.length; i++) {
var rule = rules[i];
if (filterValue(rule, node, options)) return rule
}
return void 0
}
function filterValue (rule, node, options) {
var filter = rule.filter;
if (typeof filter === 'string') {
if (filter === node.nodeName.toLowerCase()) return true
} else if (Array.isArray(filter)) {
if (filter.indexOf(node.nodeName.toLowerCase()) > -1) return true
} else if (typeof filter === 'function') {
if (filter.call(rule, node, options)) return true
} else {
throw new TypeError('`filter` needs to be a string, array, or function')
}
}
/**
* The collapseWhitespace function is adapted from collapse-whitespace
* by Luc Thevenard.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Luc Thevenard <lucthevenard@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* collapseWhitespace(options) removes extraneous whitespace from an the given element.
*
* @param {Object} options
*/
function collapseWhitespace (options) {
var element = options.element;
var isBlock = options.isBlock;
var isVoid = options.isVoid;
var isPre = options.isPre || function (node) {
return node.nodeName === 'PRE'
};
if (!element.firstChild || isPre(element)) return
var prevText = null;
var keepLeadingWs = false;
var prev = null;
var node = next(prev, element, isPre);
while (node !== element) {
if (node.nodeType === 3 || node.nodeType === 4) { // Node.TEXT_NODE or Node.CDATA_SECTION_NODE
var text = node.data.replace(/[ \r\n\t]+/g, ' ');
if ((!prevText || / $/.test(prevText.data)) &&
!keepLeadingWs && text[0] === ' ') {
text = text.substr(1);
}
// `text` might be empty at this point.
if (!text) {
node = remove(node);
continue
}
node.data = text;
prevText = node;
} else if (node.nodeType === 1) { // Node.ELEMENT_NODE
if (isBlock(node) || node.nodeName === 'BR') {
if (prevText) {
prevText.data = prevText.data.replace(/ $/, '');
}
prevText = null;
keepLeadingWs = false;
} else if (isVoid(node) || isPre(node)) {
// Avoid trimming space around non-block, non-BR void elements and inline PRE.
prevText = null;
keepLeadingWs = true;
} else if (prevText) {
// Drop protection if set previously.
keepLeadingWs = false;
}
} else {
node = remove(node);
continue
}
var nextNode = next(prev, node, isPre);
prev = node;
node = nextNode;
}
if (prevText) {
prevText.data = prevText.data.replace(/ $/, '');
if (!prevText.data) {
remove(prevText);
}
}
}
/**
* remove(node) removes the given node from the DOM and returns the
* next node in the sequence.
*
* @param {Node} node
* @return {Node} node
*/
function remove (node) {
var next = node.nextSibling || node.parentNode;
node.parentNode.removeChild(node);
return next
}
/**
* next(prev, current, isPre) returns the next node in the sequence, given the
* current and previous nodes.
*
* @param {Node} prev
* @param {Node} current
* @param {Function} isPre
* @return {Node}
*/
function next (prev, current, isPre) {
if ((prev && prev.parentNode === current) || isPre(current)) {
return current.nextSibling || current.parentNode
}
return current.firstChild || current.nextSibling || current.parentNode
}
/*
* Set up window for Node.js
*/
var root = (typeof window !== 'undefined' ? window : {});
/*
* Parsing HTML strings
*/
function canParseHTMLNatively () {
var Parser = root.DOMParser;
var canParse = false;
// Adapted from https://gist.github.com/1129031
// Firefox/Opera/IE throw errors on unsupported types
try {
// WebKit returns null on unsupported types
if (new Parser().parseFromString('', 'text/html')) {
canParse = true;
}
} catch (e) {}
return canParse
}
function createHTMLParser () {
var Parser = function () {};
{
if (shouldUseActiveX()) {
Parser.prototype.parseFromString = function (string) {
var doc = new window.ActiveXObject('htmlfile');
doc.designMode = 'on'; // disable on-page scripts
doc.open();
doc.write(string);
doc.close();
return doc
};
} else {
Parser.prototype.parseFromString = function (string) {
var doc = document.implementation.createHTMLDocument('');
doc.open();
doc.write(string);
doc.close();
return doc
};
}
}
return Parser
}
function shouldUseActiveX () {
var useActiveX = false;
try {
document.implementation.createHTMLDocument('').open();
} catch (e) {
if (root.ActiveXObject) useActiveX = true;
}
return useActiveX
}
var HTMLParser = canParseHTMLNatively() ? root.DOMParser : createHTMLParser();
function RootNode (input, options) {
var root;
if (typeof input === 'string') {
var doc = htmlParser().parseFromString(
// DOM parsers arrange elements in the <head> and <body>.
// Wrapping in a custom element ensures elements are reliably arranged in
// a single element.
'<x-turndown id="turndown-root">' + input + '</x-turndown>',
'text/html'
);
root = doc.getElementById('turndown-root');
} else {
root = input.cloneNode(true);
}
collapseWhitespace({
element: root,
isBlock: isBlock,
isVoid: isVoid,
isPre: options.preformattedCode ? isPreOrCode : null
});
return root
}
var _htmlParser;
function htmlParser () {
_htmlParser = _htmlParser || new HTMLParser();
return _htmlParser
}
function isPreOrCode (node) {
return node.nodeName === 'PRE' || node.nodeName === 'CODE'
}
function Node (node, options) {
node.isBlock = isBlock(node);
node.isCode = node.nodeName === 'CODE' || node.parentNode.isCode;
node.isBlank = isBlank(node);
node.flankingWhitespace = flankingWhitespace(node, options);
return node
}
function isBlank (node) {
return (
!isVoid(node) &&
!isMeaningfulWhenBlank(node) &&
/^\s*$/i.test(node.textContent) &&
!hasVoid(node) &&
!hasMeaningfulWhenBlank(node)
)
}
function flankingWhitespace (node, options) {
if (node.isBlock || (options.preformattedCode && node.isCode)) {
return { leading: '', trailing: '' }
}
var edges = edgeWhitespace(node.textContent);
// abandon leading ASCII WS if left-flanked by ASCII WS
if (edges.leadingAscii && isFlankedByWhitespace('left', node, options)) {
edges.leading = edges.leadingNonAscii;
}
// abandon trailing ASCII WS if right-flanked by ASCII WS
if (edges.trailingAscii && isFlankedByWhitespace('right', node, options)) {
edges.trailing = edges.trailingNonAscii;
}
return { leading: edges.leading, trailing: edges.trailing }
}
function edgeWhitespace (string) {
var m = string.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);
return {
leading: m[1], // whole string for whitespace-only strings
leadingAscii: m[2],
leadingNonAscii: m[3],
trailing: m[4], // empty for whitespace-only strings
trailingNonAscii: m[5],
trailingAscii: m[6]
}
}
function isFlankedByWhitespace (side, node, options) {
var sibling;
var regExp;
var isFlanked;
if (side === 'left') {
sibling = node.previousSibling;
regExp = / $/;
} else {
sibling = node.nextSibling;
regExp = /^ /;
}
if (sibling) {
if (sibling.nodeType === 3) {
isFlanked = regExp.test(sibling.nodeValue);
} else if (options.preformattedCode && sibling.nodeName === 'CODE') {
isFlanked = false;
} else if (sibling.nodeType === 1 && !isBlock(sibling)) {
isFlanked = regExp.test(sibling.textContent);
}
}
return isFlanked
}
var reduce = Array.prototype.reduce;
var escapes = [
[/\\/g, '\\\\'],
[/\*/g, '\\*'],
[/^-/g, '\\-'],
[/^\+ /g, '\\+ '],
[/^(=+)/g, '\\$1'],
[/^(#{1,6}) /g, '\\$1 '],
[/`/g, '\\`'],
[/^~~~/g, '\\~~~'],
[/\[/g, '\\['],
[/\]/g, '\\]'],
[/^>/g, '\\>'],
[/_/g, '\\_'],
[/^(\d+)\. /g, '$1\\. ']
];
function TurndownService (options) {
if (!(this instanceof TurndownService)) return new TurndownService(options)
var defaults = {
rules: rules,
headingStyle: 'setext',
hr: '* * *',
bulletListMarker: '*',
codeBlockStyle: 'indented',
fence: '```',
emDelimiter: '_',
strongDelimiter: '**',
linkStyle: 'inlined',
linkReferenceStyle: 'full',
br: ' ',
preformattedCode: false,
blankReplacement: function (content, node) {
return node.isBlock ? '\n\n' : ''
},
keepReplacement: function (content, node) {
return node.isBlock ? '\n\n' + node.outerHTML + '\n\n' : node.outerHTML
},
defaultReplacement: function (content, node) {
return node.isBlock ? '\n\n' + content + '\n\n' : content
}
};
this.options = extend({}, defaults, options);
this.rules = new Rules(this.options);
}
TurndownService.prototype = {
/**
* The entry point for converting a string or DOM node to Markdown
* @public
* @param {String|HTMLElement} input The string or DOM node to convert
* @returns A Markdown representation of the input
* @type String
*/
turndown: function (input) {
if (!canConvert(input)) {
throw new TypeError(
input + ' is not a string, or an element/document/fragment node.'
)
}
if (input === '') return ''
var output = process.call(this, new RootNode(input, this.options));
return postProcess.call(this, output)
},
/**
* Add one or more plugins
* @public
* @param {Function|Array} plugin The plugin or array of plugins to add
* @returns The Turndown instance for chaining
* @type Object
*/
use: function (plugin) {
if (Array.isArray(plugin)) {
for (var i = 0; i < plugin.length; i++) this.use(plugin[i]);
} else if (typeof plugin === 'function') {
plugin(this);
} else {
throw new TypeError('plugin must be a Function or an Array of Functions')
}
return this
},
/**
* Adds a rule
* @public
* @param {String} key The unique key of the rule
* @param {Object} rule The rule
* @returns The Turndown instance for chaining
* @type Object
*/
addRule: function (key, rule) {
this.rules.add(key, rule);
return this
},
/**
* Keep a node (as HTML) that matches the filter
* @public
* @param {String|Array|Function} filter The unique key of the rule
* @returns The Turndown instance for chaining
* @type Object
*/
keep: function (filter) {
this.rules.keep(filter);
return this
},
/**
* Remove a node that matches the filter
* @public
* @param {String|Array|Function} filter The unique key of the rule
* @returns The Turndown instance for chaining
* @type Object
*/
remove: function (filter) {
this.rules.remove(filter);
return this
},
/**
* Escapes Markdown syntax
* @public
* @param {String} string The string to escape
* @returns A string with Markdown syntax escaped
* @type String
*/
escape: function (string) {
return escapes.reduce(function (accumulator, escape) {
return accumulator.replace(escape[0], escape[1])
}, string)
}
};
/**
* Reduces a DOM node down to its Markdown string equivalent
* @private
* @param {HTMLElement} parentNode The node to convert
* @returns A Markdown representation of the node
* @type String
*/
function process (parentNode) {
var self = this;
return reduce.call(parentNode.childNodes, function (output, node) {
node = new Node(node, self.options);
var replacement = '';
if (node.nodeType === 3) {
replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue);
} else if (node.nodeType === 1) {
replacement = replacementForNode.call(self, node);
}
return join(output, replacement)
}, '')
}
/**
* Appends strings as each rule requires and trims the output
* @private
* @param {String} output The conversion output
* @returns A trimmed version of the ouput
* @type String
*/
function postProcess (output) {
var self = this;
this.rules.forEach(function (rule) {
if (typeof rule.append === 'function') {
output = join(output, rule.append(self.options));
}
});
return output.replace(/^[\t\r\n]+/, '').replace(/[\t\r\n\s]+$/, '')
}
/**
* Converts an element node to its Markdown equivalent
* @private
* @param {HTMLElement} node The node to convert
* @returns A Markdown representation of the node
* @type String
*/
function replacementForNode (node) {
var rule = this.rules.forNode(node);
var content = process.call(this, node);
var whitespace = node.flankingWhitespace;
if (whitespace.leading || whitespace.trailing) content = content.trim();
return (
whitespace.leading +
rule.replacement(content, node, this.options) +
whitespace.trailing
)
}
/**
* Joins replacement to the current output with appropriate number of new lines
* @private
* @param {String} output The current conversion output
* @param {String} replacement The string to append to the output
* @returns Joined output
* @type String
*/
function join (output, replacement) {
var s1 = trimTrailingNewlines(output);
var s2 = trimLeadingNewlines(replacement);
var nls = Math.max(output.length - s1.length, replacement.length - s2.length);
var separator = '\n\n'.substring(0, nls);
return s1 + separator + s2
}
/**
* Determines whether an input can be converted
* @private
* @param {String|HTMLElement} input Describe this parameter
* @returns Describe what it returns
* @type String|Object|Array|Boolean|Number
*/
function canConvert (input) {
return (
input != null && (
typeof input === 'string' ||
(input.nodeType && (
input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11
))
)
)
}
return TurndownService;
}());
+74 -61
View File
@@ -20,97 +20,110 @@ body {
}
h1 {
font-size: var(--h1-size) !important;
font-weight: var(--header-weight) !important;
font-family: var(--header-font) !important;
text-decoration: inherit !important;
font-variant: inherit !important;
border: none !important;
margin: initial !important;
line-height: initial !important;
padding: initial !important;
font-size: var(--h1-size);
font-weight: var(--header-weight);
font-family: var(--header-font);
text-decoration: inherit;
font-variant: inherit;
border: none;
line-height: initial;
padding: initial;
}
h2 {
font-size: var(--h2-size) !important;
font-weight: var(--header2-weight) !important;
font-family: var(--header-font) !important;
text-decoration: inherit !important;
font-variant: inherit !important;
border: none !important;
margin: initial !important;
line-height: initial !important;
padding: initial !important;
font-size: var(--h2-size);
font-weight: var(--header-weight);
font-family: var(--header-font);
text-decoration: inherit;
font-variant: inherit;
border: none;
margin: initial;
line-height: initial;
padding: initial;
}
h3 {
font-size: var(--h3-size) !important;
font-weight: var(--header3-weight) !important;
font-family: var(--header-font) !important;
text-decoration: inherit !important;
font-variant: inherit !important;
border: none !important;
margin: initial !important;
line-height: initial !important;
padding: initial !important;
font-size: var(--h3-size);
font-weight: var(--header-weight);
font-family: var(--header-font);
text-decoration: inherit;
font-variant: inherit;
border: none;
margin: initial;
line-height: initial;
padding: initial;
}
h4 {
font-size: var(--h4-size) !important;
font-weight: var(--header4-weight) !important;
font-family: var(--header-font) !important;
text-decoration: inherit !important;
font-variant: inherit !important;
border: none !important;
margin: initial !important;
line-height: initial !important;
padding: initial !important;
font-size: var(--h4-size);
font-weight: var(--header-weight);
font-family: var(--header-font);
text-decoration: inherit;
font-variant: inherit;
border: none;
margin: initial;
line-height: initial;
padding: initial;
}
h5 {
font-size: var(--h5-size) !important;
font-weight: var(--header5-weight) !important;
font-family: var(--header-font) !important;
text-decoration: inherit !important;
font-variant: inherit !important;
border: none !important;
margin: initial !important;
line-height: initial !important;
padding: initial !important;
font-size: var(--h5-size);
font-weight: var(--header-weight);
font-family: var(--header-font);
text-decoration: inherit;
font-variant: inherit;
border: none;
margin: initial;
line-height: initial;
padding: initial;
}
h6 {
font-size: var(--h6-size) !important;
font-weight: var(--header6-weight) !important;
font-family: var(--header-font) !important;
text-decoration: inherit !important;
font-variant: inherit !important;
border: none !important;
margin: initial !important;
line-height: initial !important;
padding: initial !important;
font-size: var(--h6-size);
font-weight: var(--header-weight);
font-family: var(--header-font);
text-decoration: inherit;
font-variant: inherit;
border: none;
margin: initial;
line-height: initial;
padding: initial;
}
* > h1:first-child {
margin-top: 0px;
}
a {text-decoration: none;}
q, blockquote {
margin-left: 30px;
font-size: 1.3em;
font-style: italic;
color: #555;
}
table {
width: 100%;
}
th {
border-bottom: 1px solid #000;
}
th, td {
padding: 2px;
}
nav ul.container {
height: 100%;
align-content: center;
margin: auto;
}
ul {
list-style: none;
padding-left: 0;
margin:0;
}
nav {
display: block;
margin: 0px;