Socket
Socket
Sign inDemoInstall

@ckeditor/ckeditor5-source-editing

Package Overview
Dependencies
Maintainers
1
Versions
582
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ckeditor/ckeditor5-source-editing - npm Package Compare versions

Comparing version 36.0.1 to 37.0.0-alpha.0

src/index.d.ts

2

build/source-editing.js

@@ -5,2 +5,2 @@ !function(e){const t=e.en=e.en||{};t.dictionary=Object.assign(t.dictionary||{},{Source:"Source"})}(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={})),

* For licensing, see LICENSE.md.
*/(()=>{var e={821:(e,t,i)=>{"use strict";i.d(t,{Z:()=>r});var n=i(609),o=i.n(n)()((function(e){return e[1]}));o.push([e.id,'.ck-source-editing-area{overflow:hidden;position:relative}.ck-source-editing-area textarea,.ck-source-editing-area:after{border:1px solid transparent;font-family:monospace;font-size:var(--ck-font-size-normal);line-height:var(--ck-line-height-base);margin:0;padding:var(--ck-spacing-large);white-space:pre-wrap}.ck-source-editing-area:after{content:attr(data-value) " ";display:block;visibility:hidden}.ck-source-editing-area textarea{border-color:var(--ck-color-base-border);border-radius:0;box-sizing:border-box;height:100%;outline:none;overflow:hidden;position:absolute;resize:none;width:100%}.ck-rounded-corners .ck-source-editing-area textarea,.ck-source-editing-area textarea.ck-rounded-corners{border-radius:var(--ck-border-radius);border-top-left-radius:0;border-top-right-radius:0}.ck-source-editing-area textarea:not([readonly]):focus{border:var(--ck-focus-ring);box-shadow:var(--ck-inner-shadow),0 0;outline:none}',""]);const r=o},609:e=>{"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var i=e(t);return t[2]?"@media ".concat(t[2]," {").concat(i,"}"):i})).join("")},t.i=function(e,i,n){"string"==typeof e&&(e=[[null,e,""]]);var o={};if(n)for(var r=0;r<this.length;r++){var a=this[r][0];null!=a&&(o[a]=!0)}for(var s=0;s<e.length;s++){var d=[].concat(e[s]);n&&o[d[0]]||(i&&(d[2]?d[2]="".concat(i," and ").concat(d[2]):d[2]=i),t.push(d))}},t}},62:(e,t,i)=>{"use strict";var n,o=function(){return void 0===n&&(n=Boolean(window&&document&&document.all&&!window.atob)),n},r=function(){var e={};return function(t){if(void 0===e[t]){var i=document.querySelector(t);if(window.HTMLIFrameElement&&i instanceof window.HTMLIFrameElement)try{i=i.contentDocument.head}catch(e){i=null}e[t]=i}return e[t]}}(),a=[];function s(e){for(var t=-1,i=0;i<a.length;i++)if(a[i].identifier===e){t=i;break}return t}function d(e,t){for(var i={},n=[],o=0;o<e.length;o++){var r=e[o],d=t.base?r[0]+t.base:r[0],c=i[d]||0,l="".concat(d," ").concat(c);i[d]=c+1;var u=s(l),h={css:r[1],media:r[2],sourceMap:r[3]};-1!==u?(a[u].references++,a[u].updater(h)):a.push({identifier:l,updater:p(h,t),references:1}),n.push(l)}return n}function c(e){var t=document.createElement("style"),n=e.attributes||{};if(void 0===n.nonce){var o=i.nc;o&&(n.nonce=o)}if(Object.keys(n).forEach((function(e){t.setAttribute(e,n[e])})),"function"==typeof e.insert)e.insert(t);else{var a=r(e.insert||"head");if(!a)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");a.appendChild(t)}return t}var l,u=(l=[],function(e,t){return l[e]=t,l.filter(Boolean).join("\n")});function h(e,t,i,n){var o=i?"":n.media?"@media ".concat(n.media," {").concat(n.css,"}"):n.css;if(e.styleSheet)e.styleSheet.cssText=u(t,o);else{var r=document.createTextNode(o),a=e.childNodes;a[t]&&e.removeChild(a[t]),a.length?e.insertBefore(r,a[t]):e.appendChild(r)}}function m(e,t,i){var n=i.css,o=i.media,r=i.sourceMap;if(o?e.setAttribute("media",o):e.removeAttribute("media"),r&&"undefined"!=typeof btoa&&(n+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(r))))," */")),e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}var f=null,g=0;function p(e,t){var i,n,o;if(t.singleton){var r=g++;i=f||(f=c(t)),n=h.bind(null,i,r,!1),o=h.bind(null,i,r,!0)}else i=c(t),n=m.bind(null,i,t),o=function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(i)};return n(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;n(e=t)}else o()}}e.exports=function(e,t){(t=t||{}).singleton||"boolean"==typeof t.singleton||(t.singleton=o());var i=d(e=e||[],t);return function(e){if(e=e||[],"[object Array]"===Object.prototype.toString.call(e)){for(var n=0;n<i.length;n++){var o=s(i[n]);a[o].references--}for(var r=d(e,t),c=0;c<i.length;c++){var l=s(i[c]);0===a[l].references&&(a[l].updater(),a.splice(l,1))}i=r}}}},704:(e,t,i)=>{e.exports=i(79)("./src/core.js")},273:(e,t,i)=>{e.exports=i(79)("./src/ui.js")},209:(e,t,i)=>{e.exports=i(79)("./src/utils.js")},79:e=>{"use strict";e.exports=CKEditor5.dll}},t={};function i(n){var o=t[n];if(void 0!==o)return o.exports;var r=t[n]={id:n,exports:{}};return e[n](r,r.exports,i),r.exports}i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.nc=void 0;var n={};(()=>{"use strict";i.r(n),i.d(n,{SourceEditing:()=>h});var e=i(704),t=i(273),o=i(209);function r(e){const t=[{name:"address",isVoid:!1},{name:"article",isVoid:!1},{name:"aside",isVoid:!1},{name:"blockquote",isVoid:!1},{name:"br",isVoid:!0},{name:"details",isVoid:!1},{name:"dialog",isVoid:!1},{name:"dd",isVoid:!1},{name:"div",isVoid:!1},{name:"dl",isVoid:!1},{name:"dt",isVoid:!1},{name:"fieldset",isVoid:!1},{name:"figcaption",isVoid:!1},{name:"figure",isVoid:!1},{name:"footer",isVoid:!1},{name:"form",isVoid:!1},{name:"h1",isVoid:!1},{name:"h2",isVoid:!1},{name:"h3",isVoid:!1},{name:"h4",isVoid:!1},{name:"h5",isVoid:!1},{name:"h6",isVoid:!1},{name:"header",isVoid:!1},{name:"hgroup",isVoid:!1},{name:"hr",isVoid:!0},{name:"input",isVoid:!0},{name:"li",isVoid:!1},{name:"main",isVoid:!1},{name:"nav",isVoid:!1},{name:"ol",isVoid:!1},{name:"p",isVoid:!1},{name:"section",isVoid:!1},{name:"table",isVoid:!1},{name:"tbody",isVoid:!1},{name:"td",isVoid:!1},{name:"textarea",isVoid:!1},{name:"th",isVoid:!1},{name:"thead",isVoid:!1},{name:"tr",isVoid:!1},{name:"ul",isVoid:!1}],i=t.map((e=>e.name)).join("|"),n=e.replace(new RegExp(`</?(${i})( .*?)?>`,"g"),"\n$&\n").split("\n");let o=0;return n.filter((e=>e.length)).map((e=>function(e,t){return t.some((t=>!t.isVoid&&!!new RegExp(`<${t.name}( .*?)?>`).test(e)))}(e,t)?a(e,o++):function(e,t){return t.some((t=>new RegExp(`</${t.name}>`).test(e)))}(e,t)?a(e,--o):a(e,o))).join("\n")}function a(e,t,i=" "){return`${i.repeat(Math.max(0,t))}${e}`}var s=i(62),d=i.n(s),c=i(821),l={injectType:"singletonStyleTag",attributes:{"data-cke":!0},insert:"head",singleton:!0};d()(c.Z,l);c.Z.locals;const u="SourceEditingMode";class h extends e.Plugin{static get pluginName(){return"SourceEditing"}static get requires(){return[e.PendingActions]}constructor(e){super(e),this.set("isSourceEditingMode",!1),this._elementReplacer=new o.ElementReplacer,this._replacedRoots=new Map,this._dataFromRoots=new Map}init(){const i=this.editor,n=i.t;i.ui.componentFactory.add("sourceEditing",(o=>{const r=new t.ButtonView(o);return r.set({label:n("Source"),icon:'<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="m12.5 0 5 4.5v15.003h-16V0h11zM3 1.5v3.25l-1.497 1-.003 8 1.5 1v3.254L7.685 18l-.001 1.504H17.5V8.002L16 9.428l-.004-4.22-4.222-3.692L3 1.5z"/><path d="M4.06 6.64a.75.75 0 0 1 .958 1.15l-.085.07L2.29 9.75l2.646 1.89c.302.216.4.62.232.951l-.058.095a.75.75 0 0 1-.951.232l-.095-.058-3.5-2.5V9.14l3.496-2.5zm4.194 6.22a.75.75 0 0 1-.958-1.149l.085-.07 2.643-1.89-2.646-1.89a.75.75 0 0 1-.232-.952l.058-.095a.75.75 0 0 1 .95-.232l.096.058 3.5 2.5v1.22l-3.496 2.5zm7.644-.836 2.122 2.122-5.825 5.809-2.125-.005.003-2.116zm2.539-1.847 1.414 1.414a.5.5 0 0 1 0 .707l-1.06 1.06-2.122-2.12 1.061-1.061a.5.5 0 0 1 .707 0z"/></svg>',tooltip:!0,withText:!0,class:"ck-source-editing-button"}),r.bind("isOn").to(this,"isSourceEditingMode"),r.bind("isEnabled").to(this,"isEnabled",i,"isReadOnly",i.plugins.get(e.PendingActions),"hasAny",((e,t,i)=>!!e&&(!t&&!i))),this.listenTo(r,"execute",(()=>{this.isSourceEditingMode=!this.isSourceEditingMode})),r})),this._isAllowedToHandleSourceEditingMode()&&(this.on("change:isSourceEditingMode",((e,t,i)=>{i?(this._showSourceEditing(),this._disableCommands()):(this._hideSourceEditing(),this._enableCommands())})),this.on("change:isEnabled",((e,t,i)=>this._handleReadOnlyMode(!i))),this.listenTo(i,"change:isReadOnly",((e,t,i)=>this._handleReadOnlyMode(i)))),i.data.on("get",(()=>{this.isSourceEditingMode&&this._updateEditorData()}),{priority:"high"})}afterInit(){const e=this.editor;["RealTimeCollaborativeEditing","CommentsEditing","TrackChangesEditing","RevisionHistory"].some((t=>e.plugins.has(t)))&&console.warn("You initialized the editor with the source editing feature and at least one of the collaboration features. Please be advised that the source editing feature may not work, and be careful when editing document source that contains markers created by the collaboration features."),e.plugins.has("RestrictedEditingModeEditing")&&console.warn("You initialized the editor with the source editing feature and restricted editing feature. Please be advised that the source editing feature may not work, and be careful when editing document source that contains markers created by the restricted editing feature.")}_showSourceEditing(){const e=this.editor,t=e.editing.view,i=e.model;i.change((e=>{e.setSelection(null),e.removeSelectionAttribute(i.document.selection.getAttributeKeys())}));for(const[i,n]of t.domRoots){const r=m(e.data.get({rootName:i})),a=(0,o.createElement)(n.ownerDocument,"textarea",{rows:"1","aria-label":"Source code editing area"}),s=(0,o.createElement)(n.ownerDocument,"div",{class:"ck-source-editing-area","data-value":r},[a]);a.value=r,a.setSelectionRange(0,0),a.addEventListener("input",(()=>{s.dataset.value=a.value})),t.change((e=>{const n=t.document.getRoot(i);e.addClass("ck-hidden",n)})),e.ui.setEditableElement("sourceEditing:"+i,a),this._replacedRoots.set(i,s),this._elementReplacer.replace(n,s),this._dataFromRoots.set(i,r)}this._focusSourceEditing()}_hideSourceEditing(){const e=this.editor.editing.view;this._updateEditorData(),e.change((t=>{for(const[i]of this._replacedRoots)t.removeClass("ck-hidden",e.document.getRoot(i))})),this._elementReplacer.restore(),this._replacedRoots.clear(),this._dataFromRoots.clear(),e.focus()}_updateEditorData(){const e=this.editor,t={};for(const[e,i]of this._replacedRoots){const n=this._dataFromRoots.get(e),o=i.dataset.value;n!==o&&(t[e]=o)}Object.keys(t).length&&e.data.set(t,{batchType:{isUndoable:!0}})}_focusSourceEditing(){const e=this.editor,[t]=this._replacedRoots.values(),i=t.querySelector("textarea");e.editing.view.document.isFocused=!1,i.focus()}_disableCommands(){const e=this.editor;for(const t of e.commands.commands())t.forceDisabled(u)}_enableCommands(){const e=this.editor;for(const t of e.commands.commands())t.clearForceDisabled(u)}_handleReadOnlyMode(e){if(this.isSourceEditingMode)for(const[,t]of this._replacedRoots)t.querySelector("textarea").readOnly=e}_isAllowedToHandleSourceEditingMode(){const e=this.editor.ui.view.editable;return e&&!e._hasExternalElement}}function m(e){return function(e){return e.startsWith("<")}(e)?r(e):e}})(),(window.CKEditor5=window.CKEditor5||{}).sourceEditing=n})();
*/(()=>{var e={821:(e,t,i)=>{"use strict";i.d(t,{Z:()=>r});var n=i(609),o=i.n(n)()((function(e){return e[1]}));o.push([e.id,'.ck-source-editing-area{overflow:hidden;position:relative}.ck-source-editing-area textarea,.ck-source-editing-area:after{border:1px solid transparent;font-family:monospace;font-size:var(--ck-font-size-normal);line-height:var(--ck-line-height-base);margin:0;padding:var(--ck-spacing-large);white-space:pre-wrap}.ck-source-editing-area:after{content:attr(data-value) " ";display:block;visibility:hidden}.ck-source-editing-area textarea{border-color:var(--ck-color-base-border);border-radius:0;box-sizing:border-box;height:100%;outline:none;overflow:hidden;position:absolute;resize:none;width:100%}.ck-rounded-corners .ck-source-editing-area textarea,.ck-source-editing-area textarea.ck-rounded-corners{border-radius:var(--ck-border-radius);border-top-left-radius:0;border-top-right-radius:0}.ck-source-editing-area textarea:not([readonly]):focus{border:var(--ck-focus-ring);box-shadow:var(--ck-inner-shadow),0 0;outline:none}',""]);const r=o},609:e=>{"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var i=e(t);return t[2]?"@media ".concat(t[2]," {").concat(i,"}"):i})).join("")},t.i=function(e,i,n){"string"==typeof e&&(e=[[null,e,""]]);var o={};if(n)for(var r=0;r<this.length;r++){var a=this[r][0];null!=a&&(o[a]=!0)}for(var s=0;s<e.length;s++){var d=[].concat(e[s]);n&&o[d[0]]||(i&&(d[2]?d[2]="".concat(i," and ").concat(d[2]):d[2]=i),t.push(d))}},t}},62:(e,t,i)=>{"use strict";var n,o=function(){return void 0===n&&(n=Boolean(window&&document&&document.all&&!window.atob)),n},r=function(){var e={};return function(t){if(void 0===e[t]){var i=document.querySelector(t);if(window.HTMLIFrameElement&&i instanceof window.HTMLIFrameElement)try{i=i.contentDocument.head}catch(e){i=null}e[t]=i}return e[t]}}(),a=[];function s(e){for(var t=-1,i=0;i<a.length;i++)if(a[i].identifier===e){t=i;break}return t}function d(e,t){for(var i={},n=[],o=0;o<e.length;o++){var r=e[o],d=t.base?r[0]+t.base:r[0],c=i[d]||0,l="".concat(d," ").concat(c);i[d]=c+1;var u=s(l),h={css:r[1],media:r[2],sourceMap:r[3]};-1!==u?(a[u].references++,a[u].updater(h)):a.push({identifier:l,updater:p(h,t),references:1}),n.push(l)}return n}function c(e){var t=document.createElement("style"),n=e.attributes||{};if(void 0===n.nonce){var o=i.nc;o&&(n.nonce=o)}if(Object.keys(n).forEach((function(e){t.setAttribute(e,n[e])})),"function"==typeof e.insert)e.insert(t);else{var a=r(e.insert||"head");if(!a)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");a.appendChild(t)}return t}var l,u=(l=[],function(e,t){return l[e]=t,l.filter(Boolean).join("\n")});function h(e,t,i,n){var o=i?"":n.media?"@media ".concat(n.media," {").concat(n.css,"}"):n.css;if(e.styleSheet)e.styleSheet.cssText=u(t,o);else{var r=document.createTextNode(o),a=e.childNodes;a[t]&&e.removeChild(a[t]),a.length?e.insertBefore(r,a[t]):e.appendChild(r)}}function m(e,t,i){var n=i.css,o=i.media,r=i.sourceMap;if(o?e.setAttribute("media",o):e.removeAttribute("media"),r&&"undefined"!=typeof btoa&&(n+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(r))))," */")),e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}var f=null,g=0;function p(e,t){var i,n,o;if(t.singleton){var r=g++;i=f||(f=c(t)),n=h.bind(null,i,r,!1),o=h.bind(null,i,r,!0)}else i=c(t),n=m.bind(null,i,t),o=function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(i)};return n(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;n(e=t)}else o()}}e.exports=function(e,t){(t=t||{}).singleton||"boolean"==typeof t.singleton||(t.singleton=o());var i=d(e=e||[],t);return function(e){if(e=e||[],"[object Array]"===Object.prototype.toString.call(e)){for(var n=0;n<i.length;n++){var o=s(i[n]);a[o].references--}for(var r=d(e,t),c=0;c<i.length;c++){var l=s(i[c]);0===a[l].references&&(a[l].updater(),a.splice(l,1))}i=r}}}},704:(e,t,i)=>{e.exports=i(79)("./src/core.js")},273:(e,t,i)=>{e.exports=i(79)("./src/ui.js")},209:(e,t,i)=>{e.exports=i(79)("./src/utils.js")},79:e=>{"use strict";e.exports=CKEditor5.dll}},t={};function i(n){var o=t[n];if(void 0!==o)return o.exports;var r=t[n]={id:n,exports:{}};return e[n](r,r.exports,i),r.exports}i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.nc=void 0;var n={};(()=>{"use strict";i.r(n),i.d(n,{SourceEditing:()=>h});var e=i(704),t=i(273),o=i(209);function r(e){const t=[{name:"address",isVoid:!1},{name:"article",isVoid:!1},{name:"aside",isVoid:!1},{name:"blockquote",isVoid:!1},{name:"br",isVoid:!0},{name:"details",isVoid:!1},{name:"dialog",isVoid:!1},{name:"dd",isVoid:!1},{name:"div",isVoid:!1},{name:"dl",isVoid:!1},{name:"dt",isVoid:!1},{name:"fieldset",isVoid:!1},{name:"figcaption",isVoid:!1},{name:"figure",isVoid:!1},{name:"footer",isVoid:!1},{name:"form",isVoid:!1},{name:"h1",isVoid:!1},{name:"h2",isVoid:!1},{name:"h3",isVoid:!1},{name:"h4",isVoid:!1},{name:"h5",isVoid:!1},{name:"h6",isVoid:!1},{name:"header",isVoid:!1},{name:"hgroup",isVoid:!1},{name:"hr",isVoid:!0},{name:"input",isVoid:!0},{name:"li",isVoid:!1},{name:"main",isVoid:!1},{name:"nav",isVoid:!1},{name:"ol",isVoid:!1},{name:"p",isVoid:!1},{name:"section",isVoid:!1},{name:"table",isVoid:!1},{name:"tbody",isVoid:!1},{name:"td",isVoid:!1},{name:"textarea",isVoid:!1},{name:"th",isVoid:!1},{name:"thead",isVoid:!1},{name:"tr",isVoid:!1},{name:"ul",isVoid:!1}],i=t.map((e=>e.name)).join("|"),n=e.replace(new RegExp(`</?(${i})( .*?)?>`,"g"),"\n$&\n").split("\n");let o=0;return n.filter((e=>e.length)).map((e=>function(e,t){return t.some((t=>!t.isVoid&&!!new RegExp(`<${t.name}( .*?)?>`).test(e)))}(e,t)?a(e,o++):function(e,t){return t.some((t=>new RegExp(`</${t.name}>`).test(e)))}(e,t)?a(e,--o):a(e,o))).join("\n")}function a(e,t,i=" "){return`${i.repeat(Math.max(0,t))}${e}`}var s=i(62),d=i.n(s),c=i(821),l={injectType:"singletonStyleTag",attributes:{"data-cke":!0},insert:"head",singleton:!0};d()(c.Z,l);c.Z.locals;const u="SourceEditingMode";class h extends e.Plugin{static get pluginName(){return"SourceEditing"}static get requires(){return[e.PendingActions]}constructor(e){super(e),this.set("isSourceEditingMode",!1),this._elementReplacer=new o.ElementReplacer,this._replacedRoots=new Map,this._dataFromRoots=new Map}init(){const i=this.editor,n=i.t;i.ui.componentFactory.add("sourceEditing",(o=>{const r=new t.ButtonView(o);return r.set({label:n("Source"),icon:'<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="m12.5 0 5 4.5v15.003h-16V0h11zM3 1.5v3.25l-1.497 1-.003 8 1.5 1v3.254L7.685 18l-.001 1.504H17.5V8.002L16 9.428l-.004-4.22-4.222-3.692L3 1.5z"/><path d="M4.06 6.64a.75.75 0 0 1 .958 1.15l-.085.07L2.29 9.75l2.646 1.89c.302.216.4.62.232.951l-.058.095a.75.75 0 0 1-.951.232l-.095-.058-3.5-2.5V9.14l3.496-2.5zm4.194 6.22a.75.75 0 0 1-.958-1.149l.085-.07 2.643-1.89-2.646-1.89a.75.75 0 0 1-.232-.952l.058-.095a.75.75 0 0 1 .95-.232l.096.058 3.5 2.5v1.22l-3.496 2.5zm7.644-.836 2.122 2.122-5.825 5.809-2.125-.005.003-2.116zm2.539-1.847 1.414 1.414a.5.5 0 0 1 0 .707l-1.06 1.06-2.122-2.12 1.061-1.061a.5.5 0 0 1 .707 0z"/></svg>',tooltip:!0,withText:!0,class:"ck-source-editing-button"}),r.bind("isOn").to(this,"isSourceEditingMode"),r.bind("isEnabled").to(this,"isEnabled",i,"isReadOnly",i.plugins.get(e.PendingActions),"hasAny",((e,t,i)=>!!e&&(!t&&!i))),this.listenTo(r,"execute",(()=>{this.isSourceEditingMode=!this.isSourceEditingMode})),r})),this._isAllowedToHandleSourceEditingMode()&&(this.on("change:isSourceEditingMode",((e,t,i)=>{i?(this._showSourceEditing(),this._disableCommands()):(this._hideSourceEditing(),this._enableCommands())})),this.on("change:isEnabled",((e,t,i)=>this._handleReadOnlyMode(!i))),this.listenTo(i,"change:isReadOnly",((e,t,i)=>this._handleReadOnlyMode(i)))),i.data.on("get",(()=>{this.isSourceEditingMode&&this._updateEditorData()}),{priority:"high"})}afterInit(){const e=this.editor;["RealTimeCollaborativeEditing","CommentsEditing","TrackChangesEditing","RevisionHistory"].some((t=>e.plugins.has(t)))&&console.warn("You initialized the editor with the source editing feature and at least one of the collaboration features. Please be advised that the source editing feature may not work, and be careful when editing document source that contains markers created by the collaboration features."),e.plugins.has("RestrictedEditingModeEditing")&&console.warn("You initialized the editor with the source editing feature and restricted editing feature. Please be advised that the source editing feature may not work, and be careful when editing document source that contains markers created by the restricted editing feature.")}_showSourceEditing(){const e=this.editor,t=e.editing.view,i=e.model;i.change((e=>{e.setSelection(null),e.removeSelectionAttribute(i.document.selection.getAttributeKeys())}));for(const[i,n]of t.domRoots){const r=m(e.data.get({rootName:i})),a=(0,o.createElement)(n.ownerDocument,"textarea",{rows:"1","aria-label":"Source code editing area"}),s=(0,o.createElement)(n.ownerDocument,"div",{class:"ck-source-editing-area","data-value":r},[a]);a.value=r,a.setSelectionRange(0,0),a.addEventListener("input",(()=>{s.dataset.value=a.value})),t.change((e=>{const n=t.document.getRoot(i);e.addClass("ck-hidden",n)})),e.ui.setEditableElement("sourceEditing:"+i,a),this._replacedRoots.set(i,s),this._elementReplacer.replace(n,s),this._dataFromRoots.set(i,r)}this._focusSourceEditing()}_hideSourceEditing(){const e=this.editor.editing.view;this._updateEditorData(),e.change((t=>{for(const[i]of this._replacedRoots)t.removeClass("ck-hidden",e.document.getRoot(i))})),this._elementReplacer.restore(),this._replacedRoots.clear(),this._dataFromRoots.clear(),e.focus()}_updateEditorData(){const e=this.editor,t={};for(const[e,i]of this._replacedRoots){const n=this._dataFromRoots.get(e),o=i.dataset.value;n!==o&&(t[e]=o)}Object.keys(t).length&&e.data.set(t,{batchType:{isUndoable:!0}})}_focusSourceEditing(){const e=this.editor,[t]=this._replacedRoots.values(),i=t.querySelector("textarea");e.editing.view.document.isFocused=!1,i.focus()}_disableCommands(){const e=this.editor;for(const t of e.commands.commands())t.forceDisabled(u)}_enableCommands(){const e=this.editor;for(const t of e.commands.commands())t.clearForceDisabled(u)}_handleReadOnlyMode(e){if(this.isSourceEditingMode)for(const[,t]of this._replacedRoots)t.querySelector("textarea").readOnly=e}_isAllowedToHandleSourceEditingMode(){const e=this.editor.ui.view.editable;return e&&!e.hasExternalElement}}function m(e){return function(e){return e.startsWith("<")}(e)?r(e):e}})(),(window.CKEditor5=window.CKEditor5||{}).sourceEditing=n})();
{
"name": "@ckeditor/ckeditor5-source-editing",
"version": "36.0.1",
"version": "37.0.0-alpha.0",
"description": "Source editing feature for CKEditor 5.",

@@ -15,17 +15,18 @@ "keywords": [

"dependencies": {
"@ckeditor/ckeditor5-theme-lark": "^36.0.1",
"ckeditor5": "^36.0.1"
"@ckeditor/ckeditor5-theme-lark": "^37.0.0-alpha.0",
"ckeditor5": "^37.0.0-alpha.0"
},
"devDependencies": {
"@ckeditor/ckeditor5-core": "^36.0.1",
"@ckeditor/ckeditor5-dev-utils": "^32.0.0",
"@ckeditor/ckeditor5-editor-classic": "^36.0.1",
"@ckeditor/ckeditor5-engine": "^36.0.1",
"@ckeditor/ckeditor5-essentials": "^36.0.1",
"@ckeditor/ckeditor5-heading": "^36.0.1",
"@ckeditor/ckeditor5-markdown-gfm": "^36.0.1",
"@ckeditor/ckeditor5-paragraph": "^36.0.1",
"@ckeditor/ckeditor5-table": "^36.0.1",
"@ckeditor/ckeditor5-ui": "^36.0.1",
"@ckeditor/ckeditor5-utils": "^36.0.1",
"@ckeditor/ckeditor5-core": "^37.0.0-alpha.0",
"@ckeditor/ckeditor5-dev-utils": "^34.0.0",
"@ckeditor/ckeditor5-editor-classic": "^37.0.0-alpha.0",
"@ckeditor/ckeditor5-engine": "^37.0.0-alpha.0",
"@ckeditor/ckeditor5-essentials": "^37.0.0-alpha.0",
"@ckeditor/ckeditor5-heading": "^37.0.0-alpha.0",
"@ckeditor/ckeditor5-markdown-gfm": "^37.0.0-alpha.0",
"@ckeditor/ckeditor5-paragraph": "^37.0.0-alpha.0",
"@ckeditor/ckeditor5-table": "^37.0.0-alpha.0",
"@ckeditor/ckeditor5-ui": "^37.0.0-alpha.0",
"@ckeditor/ckeditor5-utils": "^37.0.0-alpha.0",
"typescript": "^4.8.4",
"webpack": "^5.58.1",

@@ -49,3 +50,4 @@ "webpack-cli": "^4.9.0"

"lang",
"src",
"src/**/*.js",
"src/**/*.d.ts",
"theme",

@@ -57,4 +59,7 @@ "build",

"scripts": {
"build": "tsc -p ./tsconfig.release.json",
"postversion": "npm run build",
"dll:build": "webpack"
}
},
"types": "src/index.d.ts"
}

@@ -5,7 +5,5 @@ /**

*/
/**
* @module source-editing
*/
export { default as SourceEditing } from './sourceediting';

@@ -5,9 +5,6 @@ /**

*/
/**
* @module source-editing/sourceediting
*/
/* global console */
import { Plugin, PendingActions } from 'ckeditor5/src/core';

@@ -17,9 +14,5 @@ import { ButtonView } from 'ckeditor5/src/ui';

import { formatHtml } from './utils/formathtml';
import '../theme/sourceediting.css';
import sourceEditingIcon from '../theme/icons/source-editing.svg';
const COMMAND_FORCE_DISABLE_ID = 'SourceEditingMode';
/**

@@ -32,386 +25,276 @@ * The source editing feature.

* {@glink api/source-editing package page}.
*
* @extends module:core/plugin~Plugin
*/
export default class SourceEditing extends Plugin {
/**
* @inheritDoc
*/
static get pluginName() {
return 'SourceEditing';
}
/**
* @inheritDoc
*/
static get requires() {
return [ PendingActions ];
}
/**
* @inheritDoc
*/
constructor( editor ) {
super( editor );
/**
* Flag indicating whether the document source mode is active.
*
* @observable
* @member {Boolean}
*/
this.set( 'isSourceEditingMode', false );
/**
* The element replacer instance used to replace the editing roots with the wrapper elements containing the document source.
*
* @private
* @member {module:utils/elementreplacer~ElementReplacer}
*/
this._elementReplacer = new ElementReplacer();
/**
* Maps all root names to wrapper elements containing the document source.
*
* @private
* @member {Map.<String,HTMLElement>}
*/
this._replacedRoots = new Map();
/**
* Maps all root names to their document data.
*
* @private
* @member {Map.<String,String>}
*/
this._dataFromRoots = new Map();
}
/**
* @inheritDoc
*/
init() {
const editor = this.editor;
const t = editor.t;
editor.ui.componentFactory.add( 'sourceEditing', locale => {
const buttonView = new ButtonView( locale );
buttonView.set( {
label: t( 'Source' ),
icon: sourceEditingIcon,
tooltip: true,
withText: true,
class: 'ck-source-editing-button'
} );
buttonView.bind( 'isOn' ).to( this, 'isSourceEditingMode' );
// The button should be disabled if one of the following conditions is met:
buttonView.bind( 'isEnabled' ).to(
this, 'isEnabled',
editor, 'isReadOnly',
editor.plugins.get( PendingActions ), 'hasAny',
( isEnabled, isEditorReadOnly, hasAnyPendingActions ) => {
// (1) The plugin itself is disabled.
if ( !isEnabled ) {
return false;
}
// (2) The editor is in read-only mode.
if ( isEditorReadOnly ) {
return false;
}
// (3) Any pending action is scheduled. It may change the model, so modifying the document source should be prevented
// until the model is finally set.
if ( hasAnyPendingActions ) {
return false;
}
return true;
}
);
this.listenTo( buttonView, 'execute', () => {
this.isSourceEditingMode = !this.isSourceEditingMode;
} );
return buttonView;
} );
// Currently, the plugin handles the source editing mode by itself only for the classic editor. To use this plugin with other
// integrations, listen to the `change:isSourceEditingMode` event and act accordingly.
if ( this._isAllowedToHandleSourceEditingMode() ) {
this.on( 'change:isSourceEditingMode', ( evt, name, isSourceEditingMode ) => {
if ( isSourceEditingMode ) {
this._showSourceEditing();
this._disableCommands();
} else {
this._hideSourceEditing();
this._enableCommands();
}
} );
this.on( 'change:isEnabled', ( evt, name, isEnabled ) => this._handleReadOnlyMode( !isEnabled ) );
this.listenTo( editor, 'change:isReadOnly', ( evt, name, isReadOnly ) => this._handleReadOnlyMode( isReadOnly ) );
}
// Update the editor data while calling editor.getData() in the source editing mode.
editor.data.on( 'get', () => {
if ( this.isSourceEditingMode ) {
this._updateEditorData();
}
}, { priority: 'high' } );
}
/**
* @inheritDoc
*/
afterInit() {
const editor = this.editor;
const collaborationPluginNamesToWarn = [
'RealTimeCollaborativeEditing',
'CommentsEditing',
'TrackChangesEditing',
'RevisionHistory'
];
// Currently, the basic integration with Collaboration Features is to display a warning in the console.
if ( collaborationPluginNamesToWarn.some( pluginName => editor.plugins.has( pluginName ) ) ) {
console.warn(
'You initialized the editor with the source editing feature and at least one of the collaboration features. ' +
'Please be advised that the source editing feature may not work, and be careful when editing document source ' +
'that contains markers created by the collaboration features.'
);
}
// Restricted Editing integration can also lead to problems. Warn the user accordingly.
if ( editor.plugins.has( 'RestrictedEditingModeEditing' ) ) {
console.warn(
'You initialized the editor with the source editing feature and restricted editing feature. ' +
'Please be advised that the source editing feature may not work, and be careful when editing document source ' +
'that contains markers created by the restricted editing feature.'
);
}
}
/**
* Creates source editing wrappers that replace each editing root. Each wrapper contains the document source from the corresponding
* root.
*
* The wrapper element contains a textarea and it solves the problem, that the textarea element cannot auto expand its height based on
* the content it contains. The solution is to make the textarea more like a plain div element, which expands in height as much as it
* needs to, in order to display the whole document source without scrolling. The wrapper element is a parent for the textarea and for
* the pseudo-element `::after`, that replicates the look, content, and position of the textarea. The pseudo-element replica is hidden,
* but it is styled to be an identical visual copy of the textarea with the same content. Then, the wrapper is a grid container and both
* of its children (the textarea and the `::after` pseudo-element) are positioned within a CSS grid to occupy the same grid cell. The
* content in the pseudo-element `::after` is set in CSS and it stretches the grid to the appropriate size based on the textarea value.
* Since both children occupy the same grid cell, both have always the same height.
*
* @private
*/
_showSourceEditing() {
const editor = this.editor;
const editingView = editor.editing.view;
const model = editor.model;
model.change( writer => {
writer.setSelection( null );
writer.removeSelectionAttribute( model.document.selection.getAttributeKeys() );
} );
// It is not needed to iterate through all editing roots, as currently the plugin supports only the Classic Editor with a single
// main root, but this code may help understand and use this feature in external integrations.
for ( const [ rootName, domRootElement ] of editingView.domRoots ) {
const data = formatSource( editor.data.get( { rootName } ) );
const domSourceEditingElementTextarea = createElement( domRootElement.ownerDocument, 'textarea', {
rows: '1',
'aria-label': 'Source code editing area'
} );
const domSourceEditingElementWrapper = createElement( domRootElement.ownerDocument, 'div', {
class: 'ck-source-editing-area',
'data-value': data
}, [ domSourceEditingElementTextarea ] );
domSourceEditingElementTextarea.value = data;
// Setting a value to textarea moves the input cursor to the end. We want the selection at the beginning.
domSourceEditingElementTextarea.setSelectionRange( 0, 0 );
// Bind the textarea's value to the wrapper's `data-value` property. Each change of the textarea's value updates the
// wrapper's `data-value` property.
domSourceEditingElementTextarea.addEventListener( 'input', () => {
domSourceEditingElementWrapper.dataset.value = domSourceEditingElementTextarea.value;
} );
editingView.change( writer => {
const viewRoot = editingView.document.getRoot( rootName );
writer.addClass( 'ck-hidden', viewRoot );
} );
// Register the element so it becomes available for Alt+F10 and Esc navigation.
editor.ui.setEditableElement( 'sourceEditing:' + rootName, domSourceEditingElementTextarea );
this._replacedRoots.set( rootName, domSourceEditingElementWrapper );
this._elementReplacer.replace( domRootElement, domSourceEditingElementWrapper );
this._dataFromRoots.set( rootName, data );
}
this._focusSourceEditing();
}
/**
* Restores all hidden editing roots and sets the source data in them.
*
* @private
*/
_hideSourceEditing() {
const editor = this.editor;
const editingView = editor.editing.view;
this._updateEditorData();
editingView.change( writer => {
for ( const [ rootName ] of this._replacedRoots ) {
writer.removeClass( 'ck-hidden', editingView.document.getRoot( rootName ) );
}
} );
this._elementReplacer.restore();
this._replacedRoots.clear();
this._dataFromRoots.clear();
editingView.focus();
}
/**
* Updates the source data in all hidden editing roots.
*
* @private
*/
_updateEditorData() {
const editor = this.editor;
const data = {};
for ( const [ rootName, domSourceEditingElementWrapper ] of this._replacedRoots ) {
const oldData = this._dataFromRoots.get( rootName );
const newData = domSourceEditingElementWrapper.dataset.value;
// Do not set the data unless some changes have been made in the meantime.
// This prevents empty undo steps after switching to the normal editor.
if ( oldData !== newData ) {
data[ rootName ] = newData;
}
}
if ( Object.keys( data ).length ) {
editor.data.set( data, { batchType: { isUndoable: true } } );
}
}
/**
* Focuses the textarea containing document source from the first editing root.
*
* @private
*/
_focusSourceEditing() {
const editor = this.editor;
const [ domSourceEditingElementWrapper ] = this._replacedRoots.values();
const textarea = domSourceEditingElementWrapper.querySelector( 'textarea' );
// The FocusObserver was disabled by View.render() while the DOM root was getting hidden and the replacer
// revealed the textarea. So it couldn't notice that the DOM root got blurred in the process.
// Let's sync this state manually here because otherwise Renderer will attempt to render selection
// in an invisible DOM root.
editor.editing.view.document.isFocused = false;
textarea.focus();
}
/**
* Disables all commands.
*
* @private
*/
_disableCommands() {
const editor = this.editor;
for ( const command of editor.commands.commands() ) {
command.forceDisabled( COMMAND_FORCE_DISABLE_ID );
}
}
/**
* Clears forced disable for all commands, that was previously set through {@link #_disableCommands}.
*
* @private
*/
_enableCommands() {
const editor = this.editor;
for ( const command of editor.commands.commands() ) {
command.clearForceDisabled( COMMAND_FORCE_DISABLE_ID );
}
}
/**
* Adds or removes the `readonly` attribute from the textarea from all roots, if document source mode is active.
*
* @param {Boolean} isReadOnly Indicates whether all textarea elements should be read-only.
*/
_handleReadOnlyMode( isReadOnly ) {
if ( !this.isSourceEditingMode ) {
return;
}
for ( const [ , domSourceEditingElementWrapper ] of this._replacedRoots ) {
domSourceEditingElementWrapper.querySelector( 'textarea' ).readOnly = isReadOnly;
}
}
/**
* Checks, if the plugin is allowed to handle the source editing mode by itself. Currently, the source editing mode is supported only
* for the {@link module:editor-classic/classiceditor~ClassicEditor classic editor}.
*
* @private
* @returns {Boolean}
*/
_isAllowedToHandleSourceEditingMode() {
const editor = this.editor;
const editable = editor.ui.view.editable;
// Checks, if the editor's editable belongs to the editor's DOM tree.
return editable && !editable._hasExternalElement;
}
/**
* @inheritDoc
*/
static get pluginName() {
return 'SourceEditing';
}
/**
* @inheritDoc
*/
static get requires() {
return [PendingActions];
}
/**
* @inheritDoc
*/
constructor(editor) {
super(editor);
this.set('isSourceEditingMode', false);
this._elementReplacer = new ElementReplacer();
this._replacedRoots = new Map();
this._dataFromRoots = new Map();
}
/**
* @inheritDoc
*/
init() {
const editor = this.editor;
const t = editor.t;
editor.ui.componentFactory.add('sourceEditing', locale => {
const buttonView = new ButtonView(locale);
buttonView.set({
label: t('Source'),
icon: sourceEditingIcon,
tooltip: true,
withText: true,
class: 'ck-source-editing-button'
});
buttonView.bind('isOn').to(this, 'isSourceEditingMode');
// The button should be disabled if one of the following conditions is met:
buttonView.bind('isEnabled').to(this, 'isEnabled', editor, 'isReadOnly', editor.plugins.get(PendingActions), 'hasAny', (isEnabled, isEditorReadOnly, hasAnyPendingActions) => {
// (1) The plugin itself is disabled.
if (!isEnabled) {
return false;
}
// (2) The editor is in read-only mode.
if (isEditorReadOnly) {
return false;
}
// (3) Any pending action is scheduled. It may change the model, so modifying the document source should be prevented
// until the model is finally set.
if (hasAnyPendingActions) {
return false;
}
return true;
});
this.listenTo(buttonView, 'execute', () => {
this.isSourceEditingMode = !this.isSourceEditingMode;
});
return buttonView;
});
// Currently, the plugin handles the source editing mode by itself only for the classic editor. To use this plugin with other
// integrations, listen to the `change:isSourceEditingMode` event and act accordingly.
if (this._isAllowedToHandleSourceEditingMode()) {
this.on('change:isSourceEditingMode', (evt, name, isSourceEditingMode) => {
if (isSourceEditingMode) {
this._showSourceEditing();
this._disableCommands();
}
else {
this._hideSourceEditing();
this._enableCommands();
}
});
this.on('change:isEnabled', (evt, name, isEnabled) => this._handleReadOnlyMode(!isEnabled));
this.listenTo(editor, 'change:isReadOnly', (evt, name, isReadOnly) => this._handleReadOnlyMode(isReadOnly));
}
// Update the editor data while calling editor.getData() in the source editing mode.
editor.data.on('get', () => {
if (this.isSourceEditingMode) {
this._updateEditorData();
}
}, { priority: 'high' });
}
/**
* @inheritDoc
*/
afterInit() {
const editor = this.editor;
const collaborationPluginNamesToWarn = [
'RealTimeCollaborativeEditing',
'CommentsEditing',
'TrackChangesEditing',
'RevisionHistory'
];
// Currently, the basic integration with Collaboration Features is to display a warning in the console.
if (collaborationPluginNamesToWarn.some(pluginName => editor.plugins.has(pluginName))) {
console.warn('You initialized the editor with the source editing feature and at least one of the collaboration features. ' +
'Please be advised that the source editing feature may not work, and be careful when editing document source ' +
'that contains markers created by the collaboration features.');
}
// Restricted Editing integration can also lead to problems. Warn the user accordingly.
if (editor.plugins.has('RestrictedEditingModeEditing')) {
console.warn('You initialized the editor with the source editing feature and restricted editing feature. ' +
'Please be advised that the source editing feature may not work, and be careful when editing document source ' +
'that contains markers created by the restricted editing feature.');
}
}
/**
* Creates source editing wrappers that replace each editing root. Each wrapper contains the document source from the corresponding
* root.
*
* The wrapper element contains a textarea and it solves the problem, that the textarea element cannot auto expand its height based on
* the content it contains. The solution is to make the textarea more like a plain div element, which expands in height as much as it
* needs to, in order to display the whole document source without scrolling. The wrapper element is a parent for the textarea and for
* the pseudo-element `::after`, that replicates the look, content, and position of the textarea. The pseudo-element replica is hidden,
* but it is styled to be an identical visual copy of the textarea with the same content. Then, the wrapper is a grid container and both
* of its children (the textarea and the `::after` pseudo-element) are positioned within a CSS grid to occupy the same grid cell. The
* content in the pseudo-element `::after` is set in CSS and it stretches the grid to the appropriate size based on the textarea value.
* Since both children occupy the same grid cell, both have always the same height.
*/
_showSourceEditing() {
const editor = this.editor;
const editingView = editor.editing.view;
const model = editor.model;
model.change(writer => {
writer.setSelection(null);
writer.removeSelectionAttribute(model.document.selection.getAttributeKeys());
});
// It is not needed to iterate through all editing roots, as currently the plugin supports only the Classic Editor with a single
// main root, but this code may help understand and use this feature in external integrations.
for (const [rootName, domRootElement] of editingView.domRoots) {
const data = formatSource(editor.data.get({ rootName }));
const domSourceEditingElementTextarea = createElement(domRootElement.ownerDocument, 'textarea', {
rows: '1',
'aria-label': 'Source code editing area'
});
const domSourceEditingElementWrapper = createElement(domRootElement.ownerDocument, 'div', {
class: 'ck-source-editing-area',
'data-value': data
}, [domSourceEditingElementTextarea]);
domSourceEditingElementTextarea.value = data;
// Setting a value to textarea moves the input cursor to the end. We want the selection at the beginning.
domSourceEditingElementTextarea.setSelectionRange(0, 0);
// Bind the textarea's value to the wrapper's `data-value` property. Each change of the textarea's value updates the
// wrapper's `data-value` property.
domSourceEditingElementTextarea.addEventListener('input', () => {
domSourceEditingElementWrapper.dataset.value = domSourceEditingElementTextarea.value;
});
editingView.change(writer => {
const viewRoot = editingView.document.getRoot(rootName);
writer.addClass('ck-hidden', viewRoot);
});
// Register the element so it becomes available for Alt+F10 and Esc navigation.
editor.ui.setEditableElement('sourceEditing:' + rootName, domSourceEditingElementTextarea);
this._replacedRoots.set(rootName, domSourceEditingElementWrapper);
this._elementReplacer.replace(domRootElement, domSourceEditingElementWrapper);
this._dataFromRoots.set(rootName, data);
}
this._focusSourceEditing();
}
/**
* Restores all hidden editing roots and sets the source data in them.
*/
_hideSourceEditing() {
const editor = this.editor;
const editingView = editor.editing.view;
this._updateEditorData();
editingView.change(writer => {
for (const [rootName] of this._replacedRoots) {
writer.removeClass('ck-hidden', editingView.document.getRoot(rootName));
}
});
this._elementReplacer.restore();
this._replacedRoots.clear();
this._dataFromRoots.clear();
editingView.focus();
}
/**
* Updates the source data in all hidden editing roots.
*/
_updateEditorData() {
const editor = this.editor;
const data = {};
for (const [rootName, domSourceEditingElementWrapper] of this._replacedRoots) {
const oldData = this._dataFromRoots.get(rootName);
const newData = domSourceEditingElementWrapper.dataset.value;
// Do not set the data unless some changes have been made in the meantime.
// This prevents empty undo steps after switching to the normal editor.
if (oldData !== newData) {
data[rootName] = newData;
}
}
if (Object.keys(data).length) {
editor.data.set(data, { batchType: { isUndoable: true } });
}
}
/**
* Focuses the textarea containing document source from the first editing root.
*/
_focusSourceEditing() {
const editor = this.editor;
const [domSourceEditingElementWrapper] = this._replacedRoots.values();
const textarea = domSourceEditingElementWrapper.querySelector('textarea');
// The FocusObserver was disabled by View.render() while the DOM root was getting hidden and the replacer
// revealed the textarea. So it couldn't notice that the DOM root got blurred in the process.
// Let's sync this state manually here because otherwise Renderer will attempt to render selection
// in an invisible DOM root.
editor.editing.view.document.isFocused = false;
textarea.focus();
}
/**
* Disables all commands.
*/
_disableCommands() {
const editor = this.editor;
for (const command of editor.commands.commands()) {
command.forceDisabled(COMMAND_FORCE_DISABLE_ID);
}
}
/**
* Clears forced disable for all commands, that was previously set through {@link #_disableCommands}.
*/
_enableCommands() {
const editor = this.editor;
for (const command of editor.commands.commands()) {
command.clearForceDisabled(COMMAND_FORCE_DISABLE_ID);
}
}
/**
* Adds or removes the `readonly` attribute from the textarea from all roots, if document source mode is active.
*
* @param isReadOnly Indicates whether all textarea elements should be read-only.
*/
_handleReadOnlyMode(isReadOnly) {
if (!this.isSourceEditingMode) {
return;
}
for (const [, domSourceEditingElementWrapper] of this._replacedRoots) {
domSourceEditingElementWrapper.querySelector('textarea').readOnly = isReadOnly;
}
}
/**
* Checks, if the plugin is allowed to handle the source editing mode by itself. Currently, the source editing mode is supported only
* for the {@link module:editor-classic/classiceditor~ClassicEditor classic editor}.
*/
_isAllowedToHandleSourceEditingMode() {
const editor = this.editor;
const editable = editor.ui.view.editable;
// Checks, if the editor's editable belongs to the editor's DOM tree.
return editable && !editable.hasExternalElement;
}
}
// Formats the content for a better readability.
//
// For a non-HTML source the unchanged input string is returned.
//
// @param {String} input Input string to check.
// @returns {Boolean}
function formatSource( input ) {
if ( !isHtml( input ) ) {
return input;
}
return formatHtml( input );
/**
* Formats the content for a better readability.
*
* For a non-HTML source the unchanged input string is returned.
*
* @param input Input string to check.
*/
function formatSource(input) {
if (!isHtml(input)) {
return input;
}
return formatHtml(input);
}
// Checks, if the document source is HTML. It is sufficient to just check the first character from the document data.
//
// @param {String} input Input string to check.
// @returns {Boolean}
function isHtml( input ) {
return input.startsWith( '<' );
/**
* Checks, if the document source is HTML. It is sufficient to just check the first character from the document data.
*
* @param input Input string to check.
*/
function isHtml(input) {
return input.startsWith('<');
}

@@ -5,7 +5,5 @@ /**

*/
/**
* @module source-editing/utils/formathtml
*/
/**

@@ -20,126 +18,113 @@ * A simple (and naive) HTML code formatter that returns a formatted HTML markup that can be easily

*
* @param {String} input An HTML string to format.
* @returns {String}
* @param input An HTML string to format.
*/
export function formatHtml( input ) {
// A list of block-like elements around which the new lines should be inserted, and within which
// the indentation of their children should be increased.
// The list is partially based on https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements that contains
// a full list of HTML block-level elements.
// A void element is an element that cannot have any child - https://html.spec.whatwg.org/multipage/syntax.html#void-elements.
// Note that <pre> element is not listed on this list to avoid breaking whitespace formatting.
const elementsToFormat = [
{ name: 'address', isVoid: false },
{ name: 'article', isVoid: false },
{ name: 'aside', isVoid: false },
{ name: 'blockquote', isVoid: false },
{ name: 'br', isVoid: true },
{ name: 'details', isVoid: false },
{ name: 'dialog', isVoid: false },
{ name: 'dd', isVoid: false },
{ name: 'div', isVoid: false },
{ name: 'dl', isVoid: false },
{ name: 'dt', isVoid: false },
{ name: 'fieldset', isVoid: false },
{ name: 'figcaption', isVoid: false },
{ name: 'figure', isVoid: false },
{ name: 'footer', isVoid: false },
{ name: 'form', isVoid: false },
{ name: 'h1', isVoid: false },
{ name: 'h2', isVoid: false },
{ name: 'h3', isVoid: false },
{ name: 'h4', isVoid: false },
{ name: 'h5', isVoid: false },
{ name: 'h6', isVoid: false },
{ name: 'header', isVoid: false },
{ name: 'hgroup', isVoid: false },
{ name: 'hr', isVoid: true },
{ name: 'input', isVoid: true },
{ name: 'li', isVoid: false },
{ name: 'main', isVoid: false },
{ name: 'nav', isVoid: false },
{ name: 'ol', isVoid: false },
{ name: 'p', isVoid: false },
{ name: 'section', isVoid: false },
{ name: 'table', isVoid: false },
{ name: 'tbody', isVoid: false },
{ name: 'td', isVoid: false },
{ name: 'textarea', isVoid: false },
{ name: 'th', isVoid: false },
{ name: 'thead', isVoid: false },
{ name: 'tr', isVoid: false },
{ name: 'ul', isVoid: false }
];
const elementNamesToFormat = elementsToFormat.map( element => element.name ).join( '|' );
// It is not the fastest way to format the HTML markup but the performance should be good enough.
const lines = input
// Add new line before and after `<tag>` and `</tag>`.
// It may separate individual elements with two new lines, but this will be fixed below.
.replace( new RegExp( `</?(${ elementNamesToFormat })( .*?)?>`, 'g' ), '\n$&\n' )
// Divide input string into lines, which start with either an opening tag, a closing tag, or just a text.
.split( '\n' );
let indentCount = 0;
return lines
.filter( line => line.length )
.map( line => {
if ( isNonVoidOpeningTag( line, elementsToFormat ) ) {
return indentLine( line, indentCount++ );
}
if ( isClosingTag( line, elementsToFormat ) ) {
return indentLine( line, --indentCount );
}
return indentLine( line, indentCount );
} )
.join( '\n' );
export function formatHtml(input) {
// A list of block-like elements around which the new lines should be inserted, and within which
// the indentation of their children should be increased.
// The list is partially based on https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements that contains
// a full list of HTML block-level elements.
// A void element is an element that cannot have any child - https://html.spec.whatwg.org/multipage/syntax.html#void-elements.
// Note that <pre> element is not listed on this list to avoid breaking whitespace formatting.
const elementsToFormat = [
{ name: 'address', isVoid: false },
{ name: 'article', isVoid: false },
{ name: 'aside', isVoid: false },
{ name: 'blockquote', isVoid: false },
{ name: 'br', isVoid: true },
{ name: 'details', isVoid: false },
{ name: 'dialog', isVoid: false },
{ name: 'dd', isVoid: false },
{ name: 'div', isVoid: false },
{ name: 'dl', isVoid: false },
{ name: 'dt', isVoid: false },
{ name: 'fieldset', isVoid: false },
{ name: 'figcaption', isVoid: false },
{ name: 'figure', isVoid: false },
{ name: 'footer', isVoid: false },
{ name: 'form', isVoid: false },
{ name: 'h1', isVoid: false },
{ name: 'h2', isVoid: false },
{ name: 'h3', isVoid: false },
{ name: 'h4', isVoid: false },
{ name: 'h5', isVoid: false },
{ name: 'h6', isVoid: false },
{ name: 'header', isVoid: false },
{ name: 'hgroup', isVoid: false },
{ name: 'hr', isVoid: true },
{ name: 'input', isVoid: true },
{ name: 'li', isVoid: false },
{ name: 'main', isVoid: false },
{ name: 'nav', isVoid: false },
{ name: 'ol', isVoid: false },
{ name: 'p', isVoid: false },
{ name: 'section', isVoid: false },
{ name: 'table', isVoid: false },
{ name: 'tbody', isVoid: false },
{ name: 'td', isVoid: false },
{ name: 'textarea', isVoid: false },
{ name: 'th', isVoid: false },
{ name: 'thead', isVoid: false },
{ name: 'tr', isVoid: false },
{ name: 'ul', isVoid: false }
];
const elementNamesToFormat = elementsToFormat.map(element => element.name).join('|');
// It is not the fastest way to format the HTML markup but the performance should be good enough.
const lines = input
// Add new line before and after `<tag>` and `</tag>`.
// It may separate individual elements with two new lines, but this will be fixed below.
.replace(new RegExp(`</?(${elementNamesToFormat})( .*?)?>`, 'g'), '\n$&\n')
// Divide input string into lines, which start with either an opening tag, a closing tag, or just a text.
.split('\n');
let indentCount = 0;
return lines
.filter(line => line.length)
.map(line => {
if (isNonVoidOpeningTag(line, elementsToFormat)) {
return indentLine(line, indentCount++);
}
if (isClosingTag(line, elementsToFormat)) {
return indentLine(line, --indentCount);
}
return indentLine(line, indentCount);
})
.join('\n');
}
// Checks, if an argument is an opening tag of a non-void element to be formatted.
//
// @param {String} line String to check.
// @param {Array} elementsToFormat Elements to be formatted.
// @param {String} elementsToFormat.name Element name.
// @param {Boolean} elementsToFormat.isVoid Flag indicating whether element is a void one.
// @returns {Boolean}
function isNonVoidOpeningTag( line, elementsToFormat ) {
return elementsToFormat.some( element => {
if ( element.isVoid ) {
return false;
}
if ( !new RegExp( `<${ element.name }( .*?)?>` ).test( line ) ) {
return false;
}
return true;
} );
/**
* Checks, if an argument is an opening tag of a non-void element to be formatted.
*
* @param line String to check.
* @param elementsToFormat Elements to be formatted.
*/
function isNonVoidOpeningTag(line, elementsToFormat) {
return elementsToFormat.some(element => {
if (element.isVoid) {
return false;
}
if (!new RegExp(`<${element.name}( .*?)?>`).test(line)) {
return false;
}
return true;
});
}
// Checks, if an argument is a closing tag.
//
// @param {String} line String to check.
// @param {Array} elementsToFormat Elements to be formatted.
// @param {String} elementsToFormat.name Element name.
// @param {Boolean} elementsToFormat.isVoid Flag indicating whether element is a void one.
// @returns {Boolean}
function isClosingTag( line, elementsToFormat ) {
return elementsToFormat.some( element => {
return new RegExp( `</${ element.name }>` ).test( line );
} );
/**
* Checks, if an argument is a closing tag.
*
* @param line String to check.
* @param elementsToFormat Elements to be formatted.
*/
function isClosingTag(line, elementsToFormat) {
return elementsToFormat.some(element => {
return new RegExp(`</${element.name}>`).test(line);
});
}
// Indents a line by a specified number of characters.
//
// @param {String} line Line to indent.
// @param {Number} indentCount Number of characters to use for indentation.
// @param {String} [indentChar] Indentation character(s). 4 spaces by default.
// @returns {String}
function indentLine( line, indentCount, indentChar = ' ' ) {
// More about Math.max() here in https://github.com/ckeditor/ckeditor5/issues/10698.
return `${ indentChar.repeat( Math.max( 0, indentCount ) ) }${ line }`;
/**
* Indents a line by a specified number of characters.
*
* @param line Line to indent.
* @param indentCount Number of characters to use for indentation.
* @param indentChar Indentation character(s). 4 spaces by default.
*/
function indentLine(line, indentCount, indentChar = ' ') {
// More about Math.max() here in https://github.com/ckeditor/ckeditor5/issues/10698.
return `${indentChar.repeat(Math.max(0, indentCount))}${line}`;
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc