Move SquireUI into libs.js

This commit is contained in:
djmaze 2020-09-11 12:39:56 +02:00
parent ecb9bd8ac1
commit a7cc115bfb
6 changed files with 340 additions and 312 deletions

View file

@ -25,6 +25,7 @@ module.exports = {
'openpgp': "readonly", 'openpgp': "readonly",
'CKEDITOR': "readonly", 'CKEDITOR': "readonly",
'Squire': "readonly", 'Squire': "readonly",
'SquireUI': "readonly",
// node_modules/knockout but dev/External/ko.js is used // node_modules/knockout but dev/External/ko.js is used
// 'ko': "readonly", // 'ko': "readonly",
// node_modules/simplestatemanager // node_modules/simplestatemanager

View file

@ -88,23 +88,23 @@ Things might work in Edge 18, Firefox 50-62 and Chrome 54-68 due to one polyfill
|js/* |1.14.0 |native | |js/* |1.14.0 |native |
|----------- |--------: |--------: | |----------- |--------: |--------: |
|admin.js |2.130.942 |1.000.931 | |admin.js |2.130.942 | 941.623 |
|app.js |4.184.455 |2.618.339 | |app.js |4.184.455 |2.559.130 |
|boot.js | 671.522 | 5.834 | |boot.js | 671.522 | 5.834 |
|libs.js | 647.614 | 312.343 | |libs.js | 647.614 | 326.686 |
|polyfills.js | 325.834 | 0 | |polyfills.js | 325.834 | 0 |
|TOTAL |7.960.367 |3.937.447 | |TOTAL |7.960.367 |3.833.273 |
|js/min/* |1.14.0 |native |gzip 1.14 |gzip |brotli | |js/min/* |1.14.0 |native |gzip 1.14 |gzip |brotli |
|--------------- |--------: |--------: |--------: |--------: |--------: | |--------------- |--------: |--------: |--------: |--------: |--------: |
|admin.min.js | 252.147 | 136.658 | 73.657 | 40.569 | 34.783 | |admin.min.js | 252.147 | 128.739 | 73.657 | 37.549 | 32.265 |
|app.min.js | 511.202 | 357.183 |140.462 | 94.834 | 76.231 | |app.min.js | 511.202 | 349.263 |140.462 | 91.754 | 73.588 |
|boot.min.js | 66.007 | 3.166 | 22.567 | 1.571 | 1.345 | |boot.min.js | 66.007 | 3.166 | 22.567 | 1.571 | 1.345 |
|libs.min.js | 572.545 | 295.754 |176.720 | 91.521 | 80.871 | |libs.min.js | 572.545 | 303.770 |176.720 | 94.774 | 83.577 |
|polyfills.min.js | 32.452 | 0 | 11.312 | 0 | 0 | |polyfills.min.js | 32.452 | 0 | 11.312 | 0 | 0 |
|TOTAL |1.434.353 | 792.761 |424.718 |228.495 |193.230 | |TOTAL |1.434.353 | 784.938 |424.718 |225.648 |190.775 |
641.592 bytes (196.223 gzip) is not much, but it feels faster. 649.415 bytes (199.070 gzip) is not much, but it feels faster.
### CSS changes ### CSS changes

View file

@ -1,5 +1,4 @@
import { EventKeyCode } from 'Common/Enums'; import { EventKeyCode } from 'Common/Enums';
import { SquireUI } from 'External/SquireUI';
/** /**
* @type {Object} * @type {Object}

View file

@ -1,309 +1,322 @@
/* eslint max-len: 0 */ /* eslint max-len: 0 */
(() => {
'use strict'; 'use strict';
const doc = document, const doc = document,
allowedElements = 'A,B,BLOCKQUOTE,BR,DIV,FONT,H1,H2,H3,H4,H5,H6,HR,IMG,LABEL,LI,OL,P,SPAN,STRONG,TABLE,TD,TH,TR,U,UL', removeElements = 'HEAD,LINK,META,NOSCRIPT,SCRIPT,TEMPLATE,TITLE',
allowedAttributes = 'abbr,align,background,bgcolor,border,cellpadding,cellspacing,class,color,colspan,dir,face,frame,height,href,hspace,id,lang,rowspan,rules,scope,size,src,style,target,type,usemap,valign,vspace,width'.split(','), allowedElements = 'A,B,BLOCKQUOTE,BR,DIV,FONT,H1,H2,H3,H4,H5,H6,HR,IMG,LI,OL,P,SPAN,STRONG,TABLE,TD,TH,TR,U,UL',
allowedAttributes = 'abbr,align,background,bgcolor,border,cellpadding,cellspacing,class,color,colspan,dir,face,frame,height,href,hspace,id,lang,rowspan,rules,scope,size,src,style,target,type,usemap,valign,vspace,width'.split(','),
i18n = (str, def) => rl.i18n(str) || def, i18n = (str, def) => rl.i18n(str) || def,
SquireDefaultConfig = { ctrlKey = /Mac OS X/.test( navigator.userAgent ) ? 'meta + ' : 'Ctrl + ',
/*
blockTag: 'P', getFragmentOfChildren = parent => {
blockAttributes: null, let frag = doc.createDocumentFragment();
tagAttributes: { frag.append(...parent.childNodes);
blockquote: null,
ul: null,
ol: null,
li: null,
a: null
},
classNames: {
colour: 'colour',
fontFamily: 'font',
fontSize: 'size',
highlight: 'highlight'
},
leafNodeNames: leafNodeNames,
undo: {
documentSizeThreshold: -1, // -1 means no threshold
undoLimit: -1 // -1 means no limit
},
isInsertedHTMLSanitized: true,
isSetHTMLSanitized: true,
willCutCopy: null,
addLinks: true // allow_smart_html_links
*/
sanitizeToDOMFragment: (html, isPaste/*, squire*/) => {
const frag = doc.createDocumentFragment(),
tpl = doc.createElement('div');
tpl.innerHTML = html;
if (isPaste) {
tpl.querySelectorAll(':not('+allowedElements+',signature)').forEach(el => el.remove());
tpl.querySelectorAll(allowedElements).forEach(el => {
if (el.hasAttributes()) {
Array.from(el.attributes).forEach(attr => {
let name = attr.name.toLowerCase();
if (!allowedAttributes.includes(name)) {
el.removeAttribute(name);
}
});
}
});
}
frag.append(...tpl.childNodes);
return frag; return frag;
} },
},
rl_signature_replacer = (editor, text, signature, isHtml, insertBefore) => { SquireDefaultConfig = {
let /*
prevSignature = editor.__previous_signature, blockTag: 'P',
skipInsert = false, blockAttributes: null,
isEmptyText = false, tagAttributes: {
newLine = (isHtml ? '<br />' : "\n"), blockquote: null,
clearHtmlLine = html => rl.Utils.htmlToPlain(html).trim(); ul: null,
ol: null,
li: null,
a: null
},
classNames: {
colour: 'colour',
fontFamily: 'font',
fontSize: 'size',
highlight: 'highlight'
},
leafNodeNames: leafNodeNames,
undo: {
documentSizeThreshold: -1, // -1 means no threshold
undoLimit: -1 // -1 means no limit
},
isInsertedHTMLSanitized: true,
isSetHTMLSanitized: true,
willCutCopy: null,
addLinks: true // allow_smart_html_links
*/
sanitizeToDOMFragment: (html, isPaste/*, squire*/) => {
let tpl = doc.createElement('div');
tpl.innerHTML = html
.replace(/<\/?(BODY|HTML)[^>]*>/gi,'')
.replace(/<!--[^>]+-->/g,'')
.trim();
if (isPaste) {
tpl.querySelectorAll(removeElements).forEach(el => el.remove());
tpl.querySelectorAll(':not('+allowedElements+',signature)').forEach(el => el.replaceWith(getFragmentOfChildren(el)));
tpl.querySelectorAll('*').forEach(el => {
if (el.hasAttributes()) {
Array.from(el.attributes).forEach(attr => {
let name = attr.name.toLowerCase();
if (!allowedAttributes.includes(name)) {
el.removeAttribute(name);
}
});
}
});
}
return getFragmentOfChildren(tpl);
}
},
isEmptyText = !text.trim(); rl_signature_replacer = (editor, text, signature, isHtml, insertBefore) => {
if (!isEmptyText && isHtml) { let
isEmptyText = !clearHtmlLine(text); prevSignature = editor.__previous_signature,
} skipInsert = false,
isEmptyText = false,
newLine = (isHtml ? '<br />' : "\n"),
clearHtmlLine = html => rl.Utils.htmlToPlain(html).trim();
if (prevSignature && !isEmptyText) { isEmptyText = !text.trim();
if (isHtml && !prevSignature.isHtml) { if (!isEmptyText && isHtml) {
prevSignature = { isEmptyText = !clearHtmlLine(text);
body: rl.Utils.plainToHtml(prevSignature.body),
isHtml: true
};
} else if (!isHtml && prevSignature.isHtml) {
prevSignature = {
body: rl.Utils.htmlToPlain(prevSignature.body),
isHtml: true
};
} }
if (isHtml) { if (prevSignature && !isEmptyText) {
var clearSig = clearHtmlLine(prevSignature.body); if (isHtml && !prevSignature.isHtml) {
text = text.replace(/<signature>([\s\S]*)<\/signature>/igm, all => { prevSignature = {
var c = clearSig === clearHtmlLine(all); body: rl.Utils.plainToHtml(prevSignature.body),
if (!c) { isHtml: true
skipInsert = true; };
} } else if (!isHtml && prevSignature.isHtml) {
return c ? '' : all; prevSignature = {
}); body: rl.Utils.htmlToPlain(prevSignature.body),
} else { isHtml: true
var textLen = text.length; };
text = text }
.replace('' + prevSignature.body, '')
.replace('' + prevSignature.body, ''); if (isHtml) {
skipInsert = textLen === text.length; var clearSig = clearHtmlLine(prevSignature.body);
text = text.replace(/<signature>([\s\S]*)<\/signature>/igm, all => {
var c = clearSig === clearHtmlLine(all);
if (!c) {
skipInsert = true;
}
return c ? '' : all;
});
} else {
var textLen = text.length;
text = text
.replace('' + prevSignature.body, '')
.replace('' + prevSignature.body, '');
skipInsert = textLen === text.length;
}
} }
}
if (!skipInsert) { if (!skipInsert) {
signature = newLine + newLine + (isHtml ? '<signature>' : '') + signature + (isHtml ? '</signature>' : ''); signature = newLine + newLine + (isHtml ? '<signature>' : '') + signature + (isHtml ? '</signature>' : '');
text = insertBefore ? signature + text : text + signature; text = insertBefore ? signature + text : text + signature;
if (10 < signature.length) { if (10 < signature.length) {
prevSignature = { prevSignature = {
body: signature, body: signature,
isHtml: isHtml isHtml: isHtml
}; };
}
} }
}
editor.__previous_signature = prevSignature; editor.__previous_signature = prevSignature;
return text; return text;
}; };
class SquireUI class SquireUI
{ {
constructor(container) { constructor(container) {
const const
ctrlKey = /Mac OS X/.test( navigator.userAgent ) ? 'meta + ' : 'Ctrl + ', actions = {
actions = { mode: {
mode: { plain: {
plain: { html: '〈〉',
html: '〈〉', cmd: () => this.setMode('plain' == this.mode ? 'wysiwyg' : 'plain'),
cmd: () => this.setMode('plain' == this.mode ? 'wysiwyg' : 'plain'), hint: i18n('EDITOR/TEXT_SWITCHER_PLAINT_TEXT', 'Plain')
hint: i18n('EDITOR/TEXT_SWITCHER_PLAINT_TEXT', 'Plain') }
} },
}, font: {
font: { fontFamily: {
fontFamily: { select: {
select: { 'sans-serif': {
'sans-serif': { Arial: "'Nimbus Sans L', 'Liberation sans', 'Arial Unicode MS', Arial, Helvetica, Garuda, Utkal, FreeSans, sans-serif",
Arial: "'Nimbus Sans L', 'Liberation sans', 'Arial Unicode MS', Arial, Helvetica, Garuda, Utkal, FreeSans, sans-serif", Tahoma: "'Luxi Sans', Tahoma, Loma, Geneva, Meera, sans-serif",
Tahoma: "'Luxi Sans', Tahoma, Loma, Geneva, Meera, sans-serif", Trebuchet: "'DejaVu Sans Condensed', Trebuchet, 'Trebuchet MS', sans-serif",
Trebuchet: "'DejaVu Sans Condensed', Trebuchet, 'Trebuchet MS', sans-serif", Lucida: "'Lucida Sans Unicode', 'Lucida Sans', 'DejaVu Sans', 'Bitstream Vera Sans', 'DejaVu LGC Sans', sans-serif",
Lucida: "'Lucida Sans Unicode', 'Lucida Sans', 'DejaVu Sans', 'Bitstream Vera Sans', 'DejaVu LGC Sans', sans-serif", Verdana: "'DejaVu Sans', Verdana, Geneva, 'Bitstream Vera Sans', 'DejaVu LGC Sans', sans-serif"
Verdana: "'DejaVu Sans', Verdana, Geneva, 'Bitstream Vera Sans', 'DejaVu LGC Sans', sans-serif" },
monospace: {
Courier: "'Liberation Mono', 'Courier New', FreeMono, Courier, monospace",
Lucida: "'DejaVu Sans Mono', 'DejaVu LGC Sans Mono', 'Bitstream Vera Sans Mono', 'Lucida Console', Monaco, monospace"
},
sans: {
Times: "'Nimbus Roman No9 L', 'Times New Roman', Times, FreeSerif, serif",
Palatino: "'Bitstream Charter', 'Palatino Linotype', Palatino, Palladio, 'URW Palladio L', 'Book Antiqua', Times, serif",
Georgia: "'URW Palladio L', Georgia, Times, serif"
}
}, },
monospace: { cmd: s => squire.setFontFace(s.value)
Courier: "'Liberation Mono', 'Courier New', FreeMono, Courier, monospace",
Lucida: "'DejaVu Sans Mono', 'DejaVu LGC Sans Mono', 'Bitstream Vera Sans Mono', 'Lucida Console', Monaco, monospace"
},
sans: {
Times: "'Nimbus Roman No9 L', 'Times New Roman', Times, FreeSerif, serif",
Palatino: "'Bitstream Charter', 'Palatino Linotype', Palatino, Palladio, 'URW Palladio L', 'Book Antiqua', Times, serif",
Georgia: "'URW Palladio L', Georgia, Times, serif"
}
}, },
cmd: s => squire.setFontFace(s.value) fontSize: {
select: ['11px','13px','16px','20px','24px','30px'],
cmd: s => squire.setFontSize(s.value)
}
}, },
fontSize: { colors: {
select: ['11px','13px','16px','20px','24px','30px'], textColor: {
cmd: s => squire.setFontSize(s.value) input: 'color',
} cmd: s => squire.setTextColour(s.value),
}, hint: 'Text color'
colors: { },
textColor: { backgroundColor: {
input: 'color', input: 'color',
cmd: s => squire.setTextColour(s.value), cmd: s => squire.setHighlightColour(s.value),
hint: 'Text color' hint: 'Background color'
},
}, },
backgroundColor: {
input: 'color',
cmd: s => squire.setHighlightColour(s.value),
hint: 'Background color'
},
},
/* /*
bidi: { bidi: {
allowHtmlEditorBitiButtons allowHtmlEditorBitiButtons
}, },
*/ */
inline: { inline: {
bold: { bold: {
html: '𝐁', html: '𝐁',
cmd: () => this.doAction('bold','B'), cmd: () => this.doAction('bold','B'),
key: 'B', key: 'B',
hint: 'Bold' hint: 'Bold'
},
italic: {
html: '𝐼',
cmd: () => this.doAction('italic','I'),
key: 'I',
hint: 'Italic'
},
underline: {
html: '<u>U</u>',
cmd: () => this.doAction('underline','U'),
key: 'U',
hint: 'Underline'
},
strike: {
html: '<s>S</s>',
cmd: () => this.doAction('strikethrough','S'),
key: 'Shift + 7',
hint: 'Strikethrough'
},
sub: {
html: 'S<sub>x</sub>',
cmd: () => this.doAction('subscript','SUB'),
key: 'Shift + 5',
hint: 'Subscript'
},
sup: {
html: 'S<sup>x</sup>',
cmd: () => this.doAction('superscript','SUP'),
key: 'Shift + 6',
hint: 'Superscript'
}
},
block: {
ol: {
html: '#',
cmd: () => this.doList('OL'),
key: 'Shift + 8',
hint: 'Ordered list'
},
ul: {
html: '⋮',
cmd: () => this.doList('UL'),
key: 'Shift + 9',
hint: 'Unordered list'
},
quote: {
html: '"',
cmd: () => {
let parent = this.getParentNodeName('UL,OL');
(parent && 'BLOCKQUOTE' == parent) ? squire.decreaseQuoteLevel() : squire.increaseQuoteLevel();
}, },
hint: 'Blockquote' italic: {
}, html: '𝐼',
indentDecrease: { cmd: () => this.doAction('italic','I'),
html: '⇤', key: 'I',
cmd: () => squire.changeIndentationLevel('decrease'), hint: 'Italic'
key: ']',
hint: 'Decrease indent'
},
indentIncrease: {
html: '⇥',
cmd: () => squire.changeIndentationLevel('increase'),
key: '[',
hint: 'Increase indent'
}
},
targets: {
link: {
html: '🔗',
cmd: () => {
if ('A' === this.getParentNodeName()) {
squire.removeLink();
} else {
let url = prompt("Link","https://");
url != null && url.length && squire.makeLink(url);
}
}, },
hint: 'Link' underline: {
}, html: '<u>U</u>',
image: { cmd: () => this.doAction('underline','U'),
html: '🖼️', key: 'U',
cmd: () => { hint: 'Underline'
if ('IMG' === this.getParentNodeName()) {
// squire.removeLink();
} else {
let src = prompt("Image","https://");
src != null && src.length && squire.insertImage(src);
}
}, },
hint: 'Image' strike: {
html: '<s>S</s>',
cmd: () => this.doAction('strikethrough','S'),
key: 'Shift + 7',
hint: 'Strikethrough'
},
sub: {
html: 'S<sub>x</sub>',
cmd: () => this.doAction('subscript','SUB'),
key: 'Shift + 5',
hint: 'Subscript'
},
sup: {
html: 'S<sup>x</sup>',
cmd: () => this.doAction('superscript','SUP'),
key: 'Shift + 6',
hint: 'Superscript'
}
},
block: {
ol: {
html: '#',
cmd: () => this.doList('OL'),
key: 'Shift + 8',
hint: 'Ordered list'
},
ul: {
html: '⋮',
cmd: () => this.doList('UL'),
key: 'Shift + 9',
hint: 'Unordered list'
},
quote: {
html: '"',
cmd: () => {
let parent = this.getParentNodeName('UL,OL');
(parent && 'BLOCKQUOTE' == parent) ? squire.decreaseQuoteLevel() : squire.increaseQuoteLevel();
},
hint: 'Blockquote'
},
indentDecrease: {
html: '⇤',
cmd: () => squire.changeIndentationLevel('decrease'),
key: ']',
hint: 'Decrease indent'
},
indentIncrease: {
html: '⇥',
cmd: () => squire.changeIndentationLevel('increase'),
key: '[',
hint: 'Increase indent'
}
},
targets: {
link: {
html: '🔗',
cmd: () => {
if ('A' === this.getParentNodeName()) {
squire.removeLink();
} else {
let url = prompt("Link","https://");
url != null && url.length && squire.makeLink(url);
}
},
hint: 'Link'
},
image: {
html: '🖼️',
cmd: () => {
if ('IMG' === this.getParentNodeName()) {
// squire.removeLink();
} else {
let src = prompt("Image","https://");
src != null && src.length && squire.insertImage(src);
}
},
hint: 'Image'
},
/*
imageUpload: {
// TODO
}
*/
}, },
/* /*
imageUpload: { table: {
// TODO // TODO
}
*/
},
/*
table: {
// TODO
},
*/
changes: {
undo: {
html: '↶',
cmd: () => squire.undo(),
key: 'Z',
hint: 'Undo'
}, },
redo: { */
html: '↷', changes: {
cmd: () => squire.redo(), undo: {
key: 'Y', html: '↶',
hint: 'Redo' cmd: () => squire.undo(),
key: 'Z',
hint: 'Undo'
},
redo: {
html: '↷',
cmd: () => squire.redo(),
key: 'Y',
hint: 'Redo'
}
} }
} },
},
plain = doc.createElement('textarea'), plain = doc.createElement('textarea'),
wysiwyg = doc.createElement('div'), wysiwyg = doc.createElement('div'),
toolbar = doc.createElement('div'), toolbar = doc.createElement('div'),
squire = new Squire(wysiwyg, SquireDefaultConfig); squire = new Squire(wysiwyg, SquireDefaultConfig);
plain.className = 'squire-plain cke_plain cke_editable'; plain.className = 'squire-plain cke_plain cke_editable';
wysiwyg.className = 'squire-wysiwyg cke_wysiwyg_div cke_editable'; wysiwyg.className = 'squire-wysiwyg cke_wysiwyg_div cke_editable';
@ -331,7 +344,7 @@ class SquireUI
if (cfg.input) { if (cfg.input) {
input = doc.createElement('input'); input = doc.createElement('input');
input.type = cfg.input; input.type = cfg.input;
input.addEventListener('input', () => cfg.cmd(input)); input.addEventListener('change', () => cfg.cmd(input));
} else if (cfg.select) { } else if (cfg.select) {
input = doc.createElement('select'); input = doc.createElement('select');
if (Array.isArray(cfg.select)) { if (Array.isArray(cfg.select)) {
@ -372,12 +385,10 @@ class SquireUI
} }
toolbar.addEventListener('click', e => { toolbar.addEventListener('click', e => {
let t = e.target; let t = e.target;
if ('plain' != this.mode || 'plain' == t.dataset.action) { t.action_cmd && t.action_cmd(t);
t.action_cmd && t.action_cmd(t);
}
}); });
let changes = actions.changes let changes = actions.changes;
changes.undo.input.disabled = changes.redo.input.disabled = true; changes.undo.input.disabled = changes.redo.input.disabled = true;
squire.addEventListener('undoStateChange', state => { squire.addEventListener('undoStateChange', state => {
changes.undo.input.disabled = !state.canUndo; changes.undo.input.disabled = !state.canUndo;
@ -502,7 +513,7 @@ squire-raw.js:4089: this.fireEvent( 'willPaste', event );
} }
focus() { focus() {
('plain' == this.editor.mode ? this.plain : this.squire).focus(); ('plain' == this.mode ? this.plain : this.squire).focus();
} }
resize(width, height) { resize(width, height) {
@ -517,4 +528,6 @@ squire-raw.js:4089: this.fireEvent( 'willPaste', event );
} }
} }
export { SquireUI, SquireUI as default }; window.SquireUI = SquireUI;
})();

View file

@ -95,7 +95,8 @@ config.paths.js = {
'vendors/lightgallery/dist/js/lg-thumbnail.min.js', 'vendors/lightgallery/dist/js/lg-thumbnail.min.js',
'vendors/lightgallery/dist/js/lg-zoom.min.js', 'vendors/lightgallery/dist/js/lg-zoom.min.js',
'vendors/lightgallery/dist/js/lg-autoplay.min.js', 'vendors/lightgallery/dist/js/lg-autoplay.min.js',
'dev/External/ifvisible.js' 'dev/External/ifvisible.js',
'dev/External/SquireUI.js'
] ]
}, },
app: { app: {

View file

@ -1,6 +1,13 @@
/* Copyright © 2011-2015 by Neil Jenkins. MIT Licensed. */ /* Copyright © 2011-2015 by Neil Jenkins. MIT Licensed. */
/* eslint max-len: 0 */ /* eslint max-len: 0 */
/**
TODO: modifyBlocks function doesn't work very good.
For example you have: UL > LI > [cursor here in text]
Then create blockquote at cursor, the result is: BLOCKQUOTE > UL > LI
not UL > LI > BLOCKQUOTE
*/
( doc => { ( doc => {
"use strict"; "use strict";
@ -58,8 +65,7 @@ const
11: 1024 11: 1024
}, },
// blockElementNames = /^(?:ADDRESS|ARTICLE|ASIDE|BLOCKQUOTE|CANVAS|DETAILS|DIALOG|DIV|D[DLT]|FIELDSET|FIG(CAPTION|URE)|FOOTER|FORM|H[1-6]|HEADER|HGROUP|HR|LI|MAIN|NAV|OL|P|PRE|SECTION|TABLE|UL|VIDEO)$/, inlineNodeNames = /^(?:#text|A|ABBR|ACRONYM|B|BR|BD[IO]|CITE|CODE|DATA|DEL|DFN|EM|FONT|HR|IMG|INPUT|INS|KBD|Q|RP|RT|RUBY|SAMP|SMALL|SPAN|STR(IKE|ONG)|SU[BP]|TIME|U|VAR|WBR)$/,
inlineNodeNames = /^(?:#text|A|ABBR|ACRONYM|B|BR|BDI|BDO|CITE|CODE|DATA|DEL|DFN|EM|FONT|HR|IMG|INPUT|INS|KBD|Q|RP|RT|RUBY|SAMP|SMALL|SPAN|STRIKE|STRONG|SUB|SUP|TIME|U|VAR|WBR)$/,
leafNodeNames = { leafNodeNames = {
BR: 1, BR: 1,
@ -110,10 +116,12 @@ const
return walker; return walker;
}, },
getPreviousBlock = ( node, root ) => { getPreviousBlock = ( node, root ) => {
// node = getClosest( node, root, blockElementNames );
node = getBlockWalker( node, root ).previousNode(); node = getBlockWalker( node, root ).previousNode();
return node !== root ? node : null; return node !== root ? node : null;
}, },
getNextBlock = ( node, root ) => { getNextBlock = ( node, root ) => {
// node = getClosest( node, root, blockElementNames );
node = getBlockWalker( node, root ).nextNode(); node = getBlockWalker( node, root ).nextNode();
return node !== root ? node : null; return node !== root ? node : null;
}, },
@ -261,7 +269,7 @@ const
child = node.firstChild; child = node.firstChild;
while ( isWebKit && child && while ( isWebKit && child &&
child.nodeType === TEXT_NODE && !child.data ) { child.nodeType === TEXT_NODE && !child.data ) {
node.removeChild( child ); child.remove( );
child = node.firstChild; child = node.firstChild;
} }
if ( !child ) { if ( !child ) {
@ -467,7 +475,7 @@ const
// Remove extra <BR> fixer if present. // Remove extra <BR> fixer if present.
last = block.lastChild; last = block.lastChild;
if ( last && last.nodeName === 'BR' ) { if ( last && last.nodeName === 'BR' ) {
block.removeChild( last ); last.remove( );
--offset; --offset;
} }
@ -817,7 +825,7 @@ const
moveRangeBoundariesDownTree( range ); moveRangeBoundariesDownTree( range );
}, },
isNodeContainedInRange = ( range, node, partial ) => { isNodeContainedInRange = ( range, node, partial = true ) => {
let nodeRange = doc.createRange(); let nodeRange = doc.createRange();
nodeRange.selectNode( node ); nodeRange.selectNode( node );
@ -970,7 +978,7 @@ const
block = getNextBlock( block, root ); block = getNextBlock( block, root );
} }
// Check the block actually intersects the range // Check the block actually intersects the range
return block && isNodeContainedInRange( range, block, true ) ? block : null; return block && isNodeContainedInRange( range, block ) ? block : null;
}, },
// Returns the last block at least partially contained by the range, // Returns the last block at least partially contained by the range,
@ -995,7 +1003,7 @@ const
block = getPreviousBlock( block, root ); block = getPreviousBlock( block, root );
} }
// Check the block actually intersects the range // Check the block actually intersects the range
return block && isNodeContainedInRange( range, block, true ) ? block : null; return block && isNodeContainedInRange( range, block ) ? block : null;
}, },
newContentWalker = root => doc.createTreeWalker( root, newContentWalker = root => doc.createTreeWalker( root,
@ -1065,10 +1073,12 @@ const
parent; parent;
if ( start && end ) { if ( start && end ) {
parent = start.parentNode; range.setStart( start, 0 );
range.setStart( parent, indexOf( parent.childNodes, start ) ); range.setEnd( end, end.childNodes.length );
parent = end.parentNode; // parent = start.parentNode;
range.setEnd( parent, indexOf( parent.childNodes, end ) + 1 ); // range.setStart( parent, indexOf( parent.childNodes, start ) );
// parent = end.parentNode;
// range.setEnd( parent, indexOf( parent.childNodes, end ) + 1 );
} }
}; };
@ -1185,7 +1195,7 @@ let afterDelete = ( self, range ) => {
indexOf( parent.childNodes, node ) ); indexOf( parent.childNodes, node ) );
range.collapse( true ); range.collapse( true );
// Remove empty inline(s) // Remove empty inline(s)
parent.removeChild( node ); node.remove( );
// Fix cursor in block // Fix cursor in block
if ( !isBlock( parent ) ) { if ( !isBlock( parent ) ) {
parent = getPreviousBlock( parent, self._root ); parent = getPreviousBlock( parent, self._root );
@ -1785,6 +1795,10 @@ let stylesRewriters = {
newTreeBottom.append( empty( node ) ); newTreeBottom.append( empty( node ) );
return newTreeBottom; return newTreeBottom;
}, },
// KBD:
// VAR:
// CODE:
// SAMP:
TT: ( node, parent, config ) => { TT: ( node, parent, config ) => {
let el = createElement( doc, 'SPAN', { let el = createElement( doc, 'SPAN', {
'class': config.classNames.fontFamily, 'class': config.classNames.fontFamily,
@ -1822,13 +1836,13 @@ let cleanTree = ( node, config, preserveWS ) => {
child = children[i]; child = children[i];
nodeName = child.nodeName; nodeName = child.nodeName;
nodeType = child.nodeType; nodeType = child.nodeType;
rewriter = stylesRewriters[ nodeName ];
if ( nodeType === ELEMENT_NODE ) { if ( nodeType === ELEMENT_NODE ) {
rewriter = stylesRewriters[ nodeName ];
childLength = child.childNodes.length; childLength = child.childNodes.length;
if ( rewriter ) { if ( rewriter ) {
child = rewriter( child, node, config ); child = rewriter( child, node, config );
} else if ( blacklist.test( nodeName ) ) { } else if ( blacklist.test( nodeName ) ) {
node.removeChild( child ); child.remove( );
--i; --i;
--l; --l;
continue; continue;
@ -1888,7 +1902,7 @@ let cleanTree = ( node, config, preserveWS ) => {
continue; continue;
} }
} }
node.removeChild( child ); child.remove( );
--i; --i;
--l; --l;
} }
@ -1907,10 +1921,10 @@ let removeEmptyInlines = node => {
if ( child.nodeType === ELEMENT_NODE && !isLeaf( child ) ) { if ( child.nodeType === ELEMENT_NODE && !isLeaf( child ) ) {
removeEmptyInlines( child ); removeEmptyInlines( child );
if ( isInline( child ) && !child.firstChild ) { if ( isInline( child ) && !child.firstChild ) {
node.removeChild( child ); child.remove( );
} }
} else if ( child.nodeType === TEXT_NODE && !child.data ) { } else if ( child.nodeType === TEXT_NODE && !child.data ) {
node.removeChild( child ); child.remove( );
} }
} }
}; };
@ -1996,7 +2010,7 @@ let setClipboardData =
body.append( node ); body.append( node );
text = node.innerText || node.textContent; text = node.innerText || node.textContent;
text = text.replace( NBSP, ' ' ); // Replace nbsp with regular space text = text.replace( NBSP, ' ' ); // Replace nbsp with regular space
body.removeChild( node ); node.remove( );
} }
// Firefox (and others?) returns unix line endings (\n) even on Windows. // Firefox (and others?) returns unix line endings (\n) even on Windows.
// If on Windows, normalise to \r\n, since Notepad and some other crappy // If on Windows, normalise to \r\n, since Notepad and some other crappy
@ -2668,7 +2682,7 @@ proto.getCursorPosition = function ( range ) {
insertNodeInRange( range, node ); insertNodeInRange( range, node );
rect = node.getBoundingClientRect(); rect = node.getBoundingClientRect();
parent = node.parentNode; parent = node.parentNode;
parent.removeChild( node ); node.remove( );
mergeInlines( parent, range ); mergeInlines( parent, range );
} }
return rect; return rect;
@ -2749,7 +2763,7 @@ proto.selectionContains = function (selector) {
node = range && range.commonAncestorContainer; node = range && range.commonAncestorContainer;
if (node && !range.collapsed) { if (node && !range.collapsed) {
node = node.querySelector ? node : node.parentElement; node = node.querySelector ? node : node.parentElement;
// TODO: startContainer / endContainer for real selection match? // TODO: isNodeContainedInRange( range, node ) for real selection match?
return !!(node && node.querySelector(selector)); return !!(node && node.querySelector(selector));
} }
return false; return false;
@ -2763,7 +2777,7 @@ proto.getSelectedText = function () {
let walker = doc.createTreeWalker( let walker = doc.createTreeWalker(
range.commonAncestorContainer, range.commonAncestorContainer,
SHOW_TEXT|SHOW_ELEMENT, SHOW_TEXT|SHOW_ELEMENT,
node => isNodeContainedInRange( range, node, true ) node => isNodeContainedInRange( range, node )
); );
let startContainer = range.startContainer; let startContainer = range.startContainer;
let endContainer = range.endContainer; let endContainer = range.endContainer;
@ -2821,7 +2835,7 @@ let removeZWS = ( root, keepNode ) => {
if ( node.length === 1 ) { if ( node.length === 1 ) {
do { do {
parent = node.parentNode; parent = node.parentNode;
parent.removeChild( node ); node.remove( );
node = parent; node = parent;
walker.currentNode = parent; walker.currentNode = parent;
} while ( isInline( node ) && !getLength( node ) ); } while ( isInline( node ) && !getLength( node ) );
@ -3146,7 +3160,7 @@ proto.hasFormat = function ( tag, attributes, range ) {
// Otherwise, check each text node at least partially contained within // Otherwise, check each text node at least partially contained within
// the selection and make sure all of them have the format we want. // the selection and make sure all of them have the format we want.
walker = doc.createTreeWalker( common, SHOW_TEXT, node => isNodeContainedInRange( range, node, true ) ); walker = doc.createTreeWalker( common, SHOW_TEXT, node => isNodeContainedInRange( range, node ) );
let seenNode = false; let seenNode = false;
while ( node = walker.nextNode() ) { while ( node = walker.nextNode() ) {
@ -3248,7 +3262,7 @@ proto._addFormat = function ( tag, attributes, range ) {
node => ( node.nodeType === TEXT_NODE || node => ( node.nodeType === TEXT_NODE ||
node.nodeName === 'BR' || node.nodeName === 'BR' ||
node.nodeName === 'IMG' node.nodeName === 'IMG'
) && isNodeContainedInRange( range, node, true ) ) && isNodeContainedInRange( range, node )
); );
// Start at the beginning node of the range and iterate through // Start at the beginning node of the range and iterate through
@ -3356,7 +3370,7 @@ proto._removeFormat = function ( tag, attributes, range, partial ) {
// If not at least partially contained, wrap entire contents // If not at least partially contained, wrap entire contents
// in a clone of the tag we're removing and we're done. // in a clone of the tag we're removing and we're done.
if ( !isNodeContainedInRange( range, node, true ) ) { if ( !isNodeContainedInRange( range, node ) ) {
// Ignore bookmarks and empty text nodes // Ignore bookmarks and empty text nodes
if ( node.nodeName !== 'INPUT' && if ( node.nodeName !== 'INPUT' &&
( !isText || node.data ) ) { ( !isText || node.data ) ) {
@ -3387,7 +3401,7 @@ proto._removeFormat = function ( tag, attributes, range, partial ) {
}, },
formatTags = Array.prototype.filter.call( formatTags = Array.prototype.filter.call(
root.getElementsByTagName( tag ), function ( el ) { root.getElementsByTagName( tag ), function ( el ) {
return isNodeContainedInRange( range, el, true ) && return isNodeContainedInRange( range, el ) &&
hasTagAttributes( el, tag, attributes ); hasTagAttributes( el, tag, attributes );
} }
); );
@ -3758,7 +3772,7 @@ proto.decreaseListLevel = function ( range ) {
makeNotList = !/^[OU]L$/.test( newParent.nodeName ); makeNotList = !/^[OU]L$/.test( newParent.nodeName );
do { do {
next = startLi === endLi ? null : startLi.nextSibling; next = startLi === endLi ? null : startLi.nextSibling;
list.removeChild( startLi ); startLi.remove( );
if ( makeNotList && startLi.nodeName === 'LI' ) { if ( makeNotList && startLi.nodeName === 'LI' ) {
startLi = this.createDefaultBlock([ empty( startLi ) ]); startLi = this.createDefaultBlock([ empty( startLi ) ]);
} }
@ -3859,7 +3873,7 @@ proto.setHTML = function ( html ) {
// Remove existing root children // Remove existing root children
while ( child = root.lastChild ) { while ( child = root.lastChild ) {
root.removeChild( child ); child.remove( );
} }
// And insert new content // And insert new content