\");return r.before(o),n.before(r),o.before(n).remove(),r};var z=F;const B=(e,t,r=!0)=>{const n=[];let o=[\"none\",\"block\"];r&&(o=o.reverse());for(let r=e.length-1;r>=0;r--)-1!==e[r].textContent.toLowerCase().indexOf(t.toLowerCase())?(e[r].style.display=o[0],n.push(e[r])):e[r].style.display=o[1];return n};function H(e){let t;return\"function\"==typeof Event?t=new Event(e):(t=document.createEvent(\"Event\"),t.initEvent(e,!0,!0)),t}new RegExp(`(${[\"select\",\"checkbox-group\",\"checkbox\",\"radio-group\",\"autocomplete\"].join(\"|\")})`);var $={loaded:H(\"loaded\"),viewData:H(\"viewData\"),userDeclined:H(\"userDeclined\"),modalClosed:H(\"modalClosed\"),modalOpened:H(\"modalOpened\"),formSaved:H(\"formSaved\"),fieldAdded:H(\"fieldAdded\"),fieldRemoved:H(\"fieldRemoved\"),fieldRendered:H(\"fieldRendered\"),fieldEditOpened:H(\"fieldEditOpened\"),fieldEditClosed:H(\"fieldEditClosed\"),stageEmptied:H(\"stageEmptied\")};const U=[\"label\",\"type\"];class I{constructor(e,t){this.rawConfig=jQuery.extend({},e),e=jQuery.extend({},e),this.preview=t,delete e.isPreview,this.preview&&delete e.required;const r=[\"label\",\"description\",\"subtype\",\"required\",\"disabled\"];for(const t of r)this[t]=e[t],delete e[t];e.id||(e.name?e.id=e.name:e.id=\"control-\"+Math.floor(1e7*Math.random()+1)),this.id=e.id,this.type=e.type,this.description&&(e.title=this.description),I.controlConfig||(I.controlConfig={});const n=this.subtype?this.type+\".\"+this.subtype:this.type;this.classConfig=jQuery.extend({},I.controlConfig[this.type]||{},I.controlConfig[n]||{}),this.subtype&&(e.type=this.subtype),this.required&&(e.required=\"required\",e[\"aria-required\"]=\"true\"),this.disabled&&(e.disabled=\"disabled\"),this.config=e,this.configure()}static get definition(){return{}}static register(e,t,r){const n=r?r+\".\":\"\";I.classRegister||(I.classRegister={}),Array.isArray(e)||(e=[e]);for(const r of e)-1===r.indexOf(\".\")?I.classRegister[n+r]=t:I.error(`Ignoring type ${r}. Cannot use the character '.' in a type name.`)}static getRegistered(e=!1){const t=Object.keys(I.classRegister);return t.length?t.filter((t=>e?t.indexOf(e+\".\")>-1:-1===t.indexOf(\".\"))):t}static getRegisteredSubtypes(){const e={};for(const t in I.classRegister)if(I.classRegister.hasOwnProperty(t)){const[r,n]=t.split(\".\");if(!n)continue;e[r]||(e[r]=[]),e[r].push(n)}return e}static getClass(e,t){const r=t?e+\".\"+t:e;return I.classRegister[r]||I.classRegister[e]||I.error(\"Invalid control type. (Type: \"+e+\", Subtype: \"+t+\"). Please ensure you have registered it, and imported it correctly.\")}static loadCustom(e){let t=[];if(e&&(t=t.concat(e)),window.fbControls&&(t=t.concat(window.fbControls)),!this.fbControlsLoaded){for(const e of t)e(I,I.classRegister);this.fbControlsLoaded=!0}}static mi18n(e,t){const n=this.definition;let o=n.i18n||{};o=o[r().locale]||o.default||o;const i=this.camelCase(e),s=\"object\"==typeof o?o[i]||o[e]:o;if(s)return s;let a=n.mi18n;return\"object\"==typeof a&&(a=a[i]||a[e]),a||(a=i),r().get(a,t)}static active(e){return!Array.isArray(this.definition.inactive)||-1===this.definition.inactive.indexOf(e)}static label(e){return this.mi18n(e)}static icon(e){const t=this.definition;return t&&\"object\"==typeof t.icon?t.icon[e]:t.icon}configure(){}build(){const e=this.config,{label:t,type:r}=e,n=function(e,t){if(null==e)return{};var r,n,o=function(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n
=0||{}.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}(e,U);return this.markup(r,A(t),n)}on(e){const t={prerender:e=>e,render:e=>{const t=()=>{this.onRender&&this.onRender(e)};this.css&&N(this.css),this.js&&!D(this.js)?R(this.js).done(t):t()}};return e?t[e]:t}static error(e){throw new Error(e)}markup(e,t=\"\",r={}){return this.element=j(e,t,r),this.element}parsedHtml(e){return A(e)}static camelCase(e){return w(e)}}const _=(e,t)=>{let r=e.id?`formbuilder-${e.type} form-group field-${e.id}`:\"\";if(e.className){const n=(e=>\"string\"==typeof e?e.split(\" \").filter((e=>M.test(e)||e.startsWith(\"row-\"))):[])(e.className);n&&n.length>0&&(r+=` ${n.join(\" \")}`,Array.isArray(t)||(t=[t]),t.forEach((e=>{e.classList&&e.classList.remove(...n),e.querySelectorAll(\"[class*=row-],[class*=col-]\").forEach((e=>{e.classList&&e.classList.remove(...n)}))})))}return r};class V{constructor(e,t=!1,r=!1,n={}){this.preview=null!=t&&t,this.disableHTMLLabels=null!=r&&r,this.controlConfig=null!=n?n:{},this.templates={label:null,help:null,default:(e,t,r,n)=>(r&&t.appendChild(r),this.markup(\"div\",[t,e],{className:_(n,e)})),noLabel:(e,t,r,n)=>this.markup(\"div\",e,{className:_(n,e)}),hidden:e=>e},e&&(this.templates=jQuery.extend(this.templates,e)),this.configure()}configure(){}build(e,t,r){this.preview&&(t.name?t.name=t.name+\"-preview\":t.name=z.nameAttr(t)+\"-preview\"),t.id=t.name,this.data=jQuery.extend({},t),I.controlConfig=this.controlConfig;const n=new e(t,this.preview);let o=n.build();if(\"object\"==typeof o&&o.field||(o={field:o}),\"string\"==typeof o.field){const e=this.markup(\"div\",o.field,{});1===e.childElementCount?o.field=e.children.item(0):o.field=Array.from(e.children)}const i=this.label(),s=this.help();let a;a=r&&this.isTemplate(r)?r:this.isTemplate(o.layout)?o.layout:\"default\";const l=this.processTemplate(a,o.field,i,s);return n.on(\"prerender\")(l),l.addEventListener(\"fieldRendered\",n.on(\"render\")),l}label(){const e=this.data.label||\"\",t=[this.disableHTMLLabels?document.createTextNode(e):z.parsedHtml(e)];return this.data.required&&t.push(this.markup(\"span\",\"*\",{className:\"formbuilder-required\"})),this.isTemplate(\"label\")?this.processTemplate(\"label\",t):this.markup(\"label\",t,{for:this.data.id,className:`formbuilder-${this.data.type}-label`})}help(){return this.data.description?this.isTemplate(\"help\")?this.processTemplate(\"help\",this.data.description):this.markup(\"span\",\"?\",{className:\"tooltip-element\",tooltip:this.data.description}):null}isTemplate(e){return\"function\"==typeof this.templates[e]}processTemplate(e,...t){let r=this.templates[e](...t,this.data);return r.jquery&&(r=r[0]),r}markup(e,t=\"\",r={}){return z.markup(e,t,r)}}const Q=[\"values\",\"type\"];I.register(\"autocomplete\",class extends I{static get definition(){return{mi18n:{requireValidOption:\"requireValidOption\"}}}build(){const e=this.config,{values:t,type:r}=e,n=function(e,t){if(null==e)return{};var r,n,o=function(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||{}.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}(e,Q),o=e=>{const t=e.target.nextSibling.nextSibling,r=e.target.nextSibling,n=this.getActiveOption(t);let o=new Map([[38,()=>{const e=this.getPreviousOption(n);e&&this.selectOption(t,e)}],[40,()=>{const e=this.getNextOption(n);e&&this.selectOption(t,e)}],[13,()=>{n?(e.target.value=n.innerHTML,r.value=n.getAttribute(\"value\"),\"none\"===t.style.display?this.showList(t,n):this.hideList(t)):this.config.requireValidOption&&(this.isOptionValid(t,e.target.value)||(e.target.value=\"\",e.target.nextSibling.value=\"\")),e.preventDefault()}],[27,()=>{this.hideList(t)}]]).get(e.keyCode);return o||(o=()=>!1),o()},i={focus:e=>{const t=e.target.nextSibling.nextSibling,r=B(t.querySelectorAll(\"li\"),e.target.value);if(e.target.addEventListener(\"keydown\",o),e.target.value.length>0){const e=r.length>0?r[r.length-1]:null;this.showList(t,e)}},blur:e=>{e.target.removeEventListener(\"keydown\",o);const t=setTimeout((()=>{e.target.nextSibling.nextSibling.style.display=\"none\",clearTimeout(t)}),200);if(this.config.requireValidOption){const t=e.target.nextSibling.nextSibling;this.isOptionValid(t,e.target.value)||(e.target.value=\"\",e.target.nextSibling.value=\"\")}},input:e=>{const t=e.target.nextSibling.nextSibling;e.target.nextSibling.value=e.target.value;const r=B(t.querySelectorAll(\"li\"),e.target.value);if(0==r.length)this.hideList(t);else{let e=this.getActiveOption(t);e||(e=r[r.length-1]),this.showList(t,e)}}},s=Object.assign({},n,{id:`${n.id}-input`,autocomplete:\"off\",events:i}),a=Object.assign({},n,{type:\"hidden\"});delete s.name;const l=[this.markup(\"input\",null,s),this.markup(\"input\",null,a)],d=t.map((e=>{const t=e.label,r={events:{click:t=>{const r=t.target.parentElement,n=r.previousSibling.previousSibling;n.value=e.label,n.nextSibling.value=e.value,this.hideList(r)}},value:e.value};return this.markup(\"li\",t,r)}));return l.push(this.markup(\"ul\",d,{id:`${n.id}-list`,className:`formbuilder-${r}-list`})),l}hideList(e){this.selectOption(e,null),e.style.display=\"none\"}showList(e,t){this.selectOption(e,t),e.style.display=\"block\",e.style.width=e.parentElement.offsetWidth+\"px\"}getActiveOption(e){const t=e.getElementsByClassName(\"active-option\")[0];return t&&\"none\"!==t.style.display?t:null}getPreviousOption(e){let t=e;do{t=t?t.previousSibling:null}while(null!=t&&\"none\"===t.style.display);return t}getNextOption(e){let t=e;do{t=t?t.nextSibling:null}while(null!=t&&\"none\"===t.style.display);return t}selectOption(e,t){const r=e.querySelectorAll(\"li\");for(let e=0;e=0)continue;r[n]=e[n]}return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||{}.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}(e,J);let n=t;const o={paragraph:\"p\",header:this.subtype};return o[t]&&(n=o[t]),{field:this.markup(n,z.parsedHtml(this.label),r),layout:\"noLabel\"}}}I.register([\"paragraph\",\"header\"],G),I.register([\"p\",\"address\",\"blockquote\",\"canvas\",\"output\"],G,\"paragraph\"),I.register([\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\"h6\"],G,\"header\");const Z=[\"values\",\"value\",\"placeholder\",\"type\",\"inline\",\"other\",\"toggle\"],K=[\"label\"];function Y(e,t){if(null==e)return{};var r,n,o=function(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||{}.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}I.register([\"select\",\"checkbox-group\",\"radio-group\",\"checkbox\"],class extends I{static get definition(){return{inactive:[\"checkbox\"],mi18n:{minSelectionRequired:\"minSelectionRequired\"}}}build(){const e=[],t=this.config,{values:r,value:n,placeholder:o,type:i,inline:s,other:a,toggle:l}=t,d=Y(t,Z),c=i.replace(\"-group\",\"\"),u=\"select\"===i;if((d.multiple||\"checkbox-group\"===i)&&(d.name=d.name+\"[]\"),\"checkbox-group\"===i&&d.required){const e=this,t=this.onRender.bind(this);this.onRender=function(){t(),e.groupRequired()}}if(delete d.title,r){o&&u&&e.push(this.markup(\"option\",o,{disabled:!0,selected:!0,value:\"\"}));for(let t=0;t{const t=e.target;t.parentElement.previousElementSibling.value=t.value}},id:`${t.id}-value`,className:\"other-val\"},i=this.markup(\"input\",null,n),a=[document.createTextNode(I.mi18n(\"other\")),this.markup(\"input\",null,o)],l=this.markup(\"label\",a,{for:n.id}),u=this.markup(\"div\",[i,l],{className:r});e.push(u)}}return this.dom=\"select\"==i?this.markup(c,e,h(d,!0)):this.markup(\"div\",e,{className:i}),this.dom}groupRequired(){const e=this.element.getElementsByTagName(\"input\"),t=()=>{const t=[].some.call(e,(e=>e.checked));((e,t)=>{[].forEach.call(e,(e=>{t?e.removeAttribute(\"required\"):e.setAttribute(\"required\",\"required\"),((e,t)=>{const r=I.mi18n(\"minSelectionRequired\",1);t?e.setCustomValidity(\"\"):e.setCustomValidity(r)})(e,t)}))})(e,t)};for(let r=e.length-1;r>=0;r--)e[r].addEventListener(\"change\",t);t()}onRender(){if(this.config.userData){const t=this.config.userData.slice();\"select\"===this.config.type?e(this.dom).val(t).prop(\"selected\",!0):this.config.type.endsWith(\"-group\")&&(\"checkbox-group\"===this.config.type&&this.dom.querySelectorAll(\"input[type=checkbox]\").forEach((e=>{e.removeAttribute(\"checked\")})),this.dom.querySelectorAll(\"input\").forEach((e=>{if(!e.classList.contains(\"other-val\")){for(let r=0;r0){const r=this.dom.querySelector(`#${e.id}-value`);e.setAttribute(\"checked\",\"checked\"),r.value=e.value=t[0],r.style.display=\"inline-block\"}}})))}}});class ee extends I{static get definition(){return{mi18n:{date:\"dateField\",file:\"fileUpload\"}}}build(){let{name:e}=this.config;e=this.config.multiple?`${e}[]`:e;const t=Object.assign({},this.config,{name:e});return this.dom=this.markup(\"input\",null,t),this.dom}onRender(){this.config.userData&&e(this.dom).val(this.config.userData[0])}}I.register([\"text\",\"file\",\"date\",\"number\"],ee),I.register([\"text\",\"password\",\"email\",\"color\",\"tel\"],ee,\"text\"),I.register([\"date\",\"time\",\"datetime-local\"],ee,\"date\"),I.register([\"number\",\"range\"],ee,\"number\");const te=[\"value\"];class re extends I{static get definition(){return{mi18n:{textarea:\"textArea\"}}}build(){const e=this.config,{value:t=\"\"}=e,r=function(e,t){if(null==e)return{};var r,n,o=function(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||{}.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}(e,te);return delete r.type,this.field=this.markup(\"textarea\",this.parsedHtml(t),r),this.field}onRender(){this.config.userData&&e(this.field).val(this.config.userData[0])}on(t){return\"prerender\"==t&&this.preview?t=>{this.field&&(t=this.field),e(t).on(\"mousedown\",(e=>{e.stopPropagation()}))}:super.on(t)}}I.register(\"textarea\",re),I.register(\"textarea\",re,\"textarea\");const ne=[\"value\"];re.register(\"tinymce\",class extends re{configure(){if(this.js=[],window.tinymce||this.js.push(\"https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.9.11/tinymce.min.js\"),this.classConfig.js){let e=this.classConfig.js;Array.isArray(e)||(e=new Array(e)),this.js=this.js.concat(e),delete this.classConfig.js}this.classConfig.css&&(this.css=this.classConfig.css),this.editorOptions={height:250,paste_data_images:!0,plugins:[\"advlist\",\"autolink\",\"lists\",\"link\",\"image\",\"charmap\",\"print\",\"preview\",\"anchor\",\"searchreplace\",\"visualblocks\",\"code\",\"fullscreen\",\"insertdatetime\",\"media\",\"table\",\"contextmenu\",\"paste\",\"code\"],toolbar:\"undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | table\"}}build(){const e=this.config,{value:t=\"\"}=e,r=function(e,t){if(null==e)return{};var r,n,o=function(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||{}.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}(e,ne);return delete r.type,this.field=this.markup(\"textarea\",this.parsedHtml(t),r),r.disabled&&(this.editorOptions.readonly=!0),this.field}onRender(){const e=window.tinymce.get(this.id);e&&window.tinymce.remove(e);const t=jQuery.extend(this.editorOptions,this.classConfig);t.target=this.field;const r=[];Number(window.tinymce.majorVersion)>=5&&r.push(\"contextmenu\"),Number(window.tinymce.majorVersion)>=6&&r.push(\"paste\",\"print\"),t.plugins=t.plugins.filter((e=>-1===r.indexOf(e)));const n=this.config.userData?this.parsedHtml(this.config.userData[0]):void 0,o=window.lastFormBuilderCopiedTinyMCE?this.parsedHtml(window.lastFormBuilderCopiedTinyMCE):void 0;window.lastFormBuilderCopiedTinyMCE=null;const i=function(e){o?e[0].setContent(o):n&&e[0].setContent(n)};setTimeout((()=>{window.tinymce.init(t).then(i)}),0)}},\"textarea\");const oe=[\"value\"];function ie(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function se(e){for(var t=1;t=0)continue;r[n]=e[n]}return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||{}.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}(e,oe);return delete r.type,this.field=this.markup(\"div\",null,r),this.field.classList.contains(\"form-control\")&&this.field.classList.remove(\"form-control\"),this.field}onRender(e){const t=this.config.value||\"\",r=window.Quill.import(\"delta\");window.fbEditors.quill[this.id]={};const n=window.fbEditors.quill[this.id];return n.instance=new window.Quill(this.field,this.editorConfig),n.data=new r,t&&n.instance.setContents(window.JSON.parse(this.parsedHtml(t))),n.instance.on(\"text-change\",(function(e){n.data=n.data.compose(e)})),e}},\"textarea\"),r().addLanguage(\"en-US\",{NATIVE_NAME:\"English (US)\",ENGLISH_NAME:\"English\",addOption:\"Add Option +\",allFieldsRemoved:\"All fields were removed.\",allowMultipleFiles:\"Allow users to upload multiple files\",allowSelect:\"Allow selection\",autocomplete:\"Autocomplete\",button:\"Button\",cannotBeEmpty:\"This field cannot be empty\",checkboxGroup:\"Checkbox Group\",checkbox:\"Checkbox\",checkboxes:\"Checkboxes\",className:\"Class\",clearAllMessage:\"Are you sure you want to clear all fields?\",clear:\"Clear\",close:\"Close\",content:\"Content\",copy:\"Copy To Clipboard\",copyButton:\"+\",copyButtonTooltip:\"Copy\",dateField:\"Date Field\",description:\"Help Text\",descriptionField:\"Description\",devMode:\"Developer Mode\",editNames:\"Edit Names\",editorTitle:\"Form Elements\",editXML:\"Edit XML\",enableOther:\"Enable "Other"\",enableOtherMsg:\"Let users enter an unlisted option\",fieldDeleteWarning:\"false\",fieldVars:\"Field Variables\",fieldNonEditable:\"This field cannot be edited.\",fieldRemoveWarning:\"Are you sure you want to remove this field?\",fileUpload:\"File Upload\",formUpdated:\"Form Updated\",getStarted:\"Drag a field from the right to this area\",header:\"Header\",hide:\"Edit\",hidden:\"Hidden Input\",inline:\"Inline\",inlineDesc:\"Display {type} inline\",label:\"Label\",labelEmpty:\"Field Label cannot be empty\",limitRole:\"Limit access to one or more of the following roles:\",mandatory:\"Mandatory\",maxlength:\"Max Length\",minOptionMessage:\"This field requires a minimum of 2 options\",minSelectionRequired:\"Minimum {min} selections required\",multipleFiles:\"Multiple Files\",name:\"Name\",no:\"No\",noFieldsToClear:\"There are no fields to clear\",number:\"Number\",off:\"Off\",on:\"On\",option:\"Option\",optionCount:\"Option {count}\",options:\"Options\",optional:\"optional\",optionLabelPlaceholder:\"Label\",optionValuePlaceholder:\"Value\",optionEmpty:\"Option value required\",other:\"Other\",paragraph:\"Paragraph\",placeholder:\"Placeholder\",\"placeholders.value\":\"Value\",\"placeholders.label\":\"Label\",\"placeholders.email\":\"Enter your email\",\"placeholders.className\":\"space separated classes\",\"placeholders.password\":\"Enter your password\",preview:\"Preview\",radioGroup:\"Radio Group\",radio:\"Radio\",removeMessage:\"Remove Element\",removeOption:\"Remove Option\",remove:\"×\",required:\"Required\",reset:\"Reset\",requireValidOption:\"Only accept a pre-defined Option\",richText:\"Rich Text Editor\",roles:\"Access\",rows:\"Rows\",save:\"Save\",selectOptions:\"Options\",select:\"Select\",selectColor:\"Select Color\",selectionsMessage:\"Allow Multiple Selections\",size:\"Size\",sizes:\"Sizes\",\"size.xs\":\"Extra Small\",\"size.sm\":\"Small\",\"size.m\":\"Default\",\"size.lg\":\"Large\",step:\"Step\",style:\"Style\",styles:\"Styles\",\"styles.btn\":\"Button Styles\",\"styles.btn.default\":\"Default\",\"styles.btn.danger\":\"Danger\",\"styles.btn.info\":\"Info\",\"styles.btn.primary\":\"Primary\",\"styles.btn.success\":\"Success\",\"styles.btn.warning\":\"Warning\",submit:\"Submit\",subtype:\"Type\",text:\"Text Field\",textArea:\"Text Area\",toggle:\"Toggle\",warning:\"Warning!\",value:\"Value\",viewJSON:\"[{…}]\",viewXML:\"</>\",yes:\"Yes\"});const le={location:\"assets/lang/\"};n(700);class de{constructor(e={},t=[]){this.customRegister={},this.templateControlRegister={},this.def={icon:{},i18n:{}},this.register(e,t)}register(e={},t=[]){const n=r().locale;this.def.i18n[n]||(this.def.i18n[n]={});const o=this;Object.keys(e).forEach((t=>{const r=function(r,n){this.customControl=new W(r,n,e[t]),this.build=function(){return this.customControl.build()},this.on=function(e){return this.customControl.on(e)}};r.definition={},r.label=e=>o.label(e),r.icon=e=>o.icon(e),this.templateControlRegister[t]=r}));for(const o of t){let t=o.type;if(o.attrs=o.attrs||{},!t){if(!o.attrs.type){I.error(\"Ignoring invalid custom field definition. Please specify a type property.\");continue}t=o.attrs.type}let i=o.subtype||t;if(e[t]){const e=this.templateControlRegister[t];e.definition=o,this.customRegister[i]=jQuery.extend(o,{type:t,class:e})}else try{const e=I.getClass(t,o.subtype);i=o.datatype?o.datatype:`${t}-${Math.floor(9e3*Math.random()+1e3)}`,this.customRegister[i]=jQuery.extend(o,{type:t,class:e})}catch(e){I.error(\"Error while registering custom field: \"+t+(o.subtype?\":\"+o.subtype:\"\")+\". Unable to find any existing defined control or template for rendering.\")}this.def.i18n[n][i]=Array.isArray(o.label)?r().get(...o.label)||o.label[0]:o.label,this.def.icon[i]=o.icon}}label(e){const t=this.def;let n=t.i18n||{};n=n[r().locale]||n.default||n;const o=I.camelCase(e),i=\"object\"==typeof n?n[o]||n[e]:n;if(i)return i;{let n=t.mi18n;return\"object\"==typeof n&&(n=n[o]||n[e]),n||(n=o),r().get(n)}}get definition(){return{}}icon(e){const t=this.def;return t&&\"object\"==typeof t.icon?t.icon[e]:t.icon}getRegistered(e=!1){var t;return e?null!==(t=this.templateControlRegister[e])&&void 0!==t?t:void 0:Object.keys(this.customRegister)}getClass(e){var t;return null!==(t=this.templateControlRegister[e])&&void 0!==t?t:void 0}lookup(e){return this.customRegister[e]}}class ce{constructor(e={}){const t={layout:V,layoutTemplates:{},controls:{},controlConfig:{},container:!1,dataType:\"json\",disableHTMLLabels:!1,formData:[],i18n:Object.assign({},le),messages:{formRendered:\"Form Rendered\",noFormData:\"No form data.\",other:\"Other\",selectColor:\"Select Color\",invalidControl:\"Invalid control\"},onRender:()=>{},render:!0,sanitizerOptions:{clobberingProtection:{document:!0,form:!1,namespaceAttributes:!0},backendOrder:[\"dompurify\",\"sanitizer\",\"fallback\"]},templates:{},notify:{error:e=>{console.log(e)},success:e=>{console.log(e)},warning:e=>{console.warn(e)}}};this.options=jQuery.extend(!0,t,e),this.instanceContainers=[],(e=>{if(\"object\"!=typeof e)throw\"Invalid value given to setSanitizerConfig, expected config object\";if(e.hasOwnProperty(\"clobberingProtection\")&&[\"document\",\"form\",\"namespaceAttributes\"].forEach((t=>{e.clobberingProtection.hasOwnProperty(t)&&\"boolean\"==typeof e.clobberingProtection[t]&&(o.clobberingProtection[t]=e.clobberingProtection[t])})),e.hasOwnProperty(\"backends\")){if(\"object\"!=typeof e.backends)throw\"backends config expected to be an Object\";Object.keys(e.backends).forEach((t=>o.backends[t]=e.backends[t]))}if(e.hasOwnProperty(\"backendOrder\")){if(o.backendOrder=[],!Array.isArray(e.backendOrder))throw\"backendOrder config expected to be an Array of backend keys as strings\";e.backendOrder.forEach((e=>{if(!o.backends.hasOwnProperty(e))throw\"unknown sanitizer backend \"+e;o.backendOrder.push(e)}))}})(this.options.sanitizerOptions),r().current||r().init(this.options.i18n),this.options.formData?this.options.formData=this.parseFormData(this.options.formData):this.options.formData=[],I.controlConfig=e.controlConfig||{},I.loadCustom(e.controls),this.templatedControls=new de(this.options.templates),\"function\"!=typeof Element.prototype.appendFormFields&&(Element.prototype.appendFormFields=function(e){Array.isArray(e)||(e=[e]);const t=z.markup(\"div\",e,{className:\"rendered-form formbuilder-embedded-bootstrap\"});this.appendChild(t),e.forEach((e=>{const[r]=e.className.match(/row-([^\\s]+)/)||[];if(r){const n=this.id?`${this.id}-row-${r}`:`row-${r}`;let o=document.getElementById(n);o||(o=z.markup(\"div\",null,{id:n,className:\"row\"}),t.appendChild(o)),o.appendChild(e)}else t.appendChild(e);e.dispatchEvent($.fieldRendered)}))}),\"function\"!=typeof Element.prototype.emptyContainer&&(Element.prototype.emptyContainer=function(){const e=this;for(;e.lastChild;)e.removeChild(e.lastChild)})}sanitizeField(e,t){let r=Object.assign({},e);return t&&(r.id=e.id&&`${e.id}-${t}`,r.name=e.name&&`${e.name}-${t}`),r.className=Array.isArray(e.className)?z.unique(e.className.join(\" \").split(\" \")).join(\" \"):e.className||e.class||null,delete r.class,e.values&&(r.values=e.values.map((e=>z.trimObj(e)))),r=z.trimObj(r),Array.isArray(e.userData)&&0===e.userData.length&&(r.userData=[]),r}getElement(e){return(e=this.options.container||e)instanceof jQuery?e=e[0]:\"string\"==typeof e&&(e=document.querySelector(e)),e}render(e=null,t=0){const r=this,n=this.options;e=this.getElement(e);const o=[],i=new n.layout(n.layoutTemplates,!1,n.disableHTMLLabels,n.controlConfig);if(n.formData.length)for(let e=0;ee.map((e=>e.innerHTML)).join(\"\");r.markup=e(o)}if(!0===n.disableInjectedStyle){const e=document.getElementsByClassName(\"formBuilder-injected-style\");L(e,(t=>(e=>{e.parentNode&&e.parentNode.removeChild(e)})(e[t])))}else\"bootstrap\"===n.disableInjectedStyle&&n.render&&e&&e.getElementsByClassName(\"formbuilder-embedded-bootstrap\").item(0)?.classList.remove(\"formbuilder-embedded-bootstrap\");return r}renderControl(e=null){const t=this.options,r=t.formData;if(!r||Array.isArray(r))throw new Error(\"To render a single element, please specify a single object of formData for the field in question\");const n=this.sanitizeField(r),o=new t.layout,i=this.templatedControls.getClass(r.type)||I.getClass(r.type,r.subtype),s=t.forceTemplate||\"hidden\",a=o.build(i,n,s);return e.appendFormFields(a),t.notify.success(t.messages.formRendered),this}get userData(){const t=this.options.formData.slice();return t.filter((e=>\"tinymce\"===e.subtype)).forEach((e=>window.tinymce.get(e.name).save())),this.instanceContainers.forEach((r=>{const n=e(\"select, input, textarea\",r).serializeArray().reduce(((e,{name:t,value:r})=>(e[t=t.replace(\"[]\",\"\")]?e[t].push(r):e[t]=[r],e)),{}),o=t.length;for(let e=0;e{this.options.formData.slice().filter((e=>\"tinymce\"===e.subtype)).forEach((e=>window.tinymce.get(e.name).setContent(\"\"))),e.querySelectorAll(\"input, select, textarea\").forEach((e=>{[\"checkbox\",\"radio\"].includes(e.type)?e.checked=!1:e.value=\"\"}))}))}parseFormData(e){const t={xml:e=>S(e),json:e=>window.JSON.parse(e)};return\"object\"!=typeof e&&(e=t[this.options.dataType](e)||!1),e}}!function(e){let t;const r={init:(e,n={})=>(t=e,r.instance=new ce(n),e.each((t=>r.instance.render(e[t],t))),r.instance),userData:()=>r.instance&&r.instance.userData,clear:()=>r.instance&&r.instance.clear(),setData:e=>{if(r.instance){const t=r.instance;t.options.formData=t.parseFormData(e)}},render:(e,n={})=>{if(r.instance){const o=r.instance;e||(e=o.options.formData),o.options=Object.assign({},o.options,n,{formData:o.parseFormData(e)}),t.each((e=>r.instance.render(t[e],e)))}},html:()=>t.map((e=>t[e])).html()};e.fn.formRender=function(e={},...t){if(r[e])return r[e].apply(this,t);{const t=r.init(this,e);return Object.assign(r,t),t}},e.fn.controlRender=function(e,t={}){t.formData=e,t.dataType=\"string\"==typeof e?\"json\":\"xml\";const r=new ce(t),n=this;return n.each((e=>r.renderControl(n[e]))),n}}(jQuery)}()}()}(jQuery);","/*global require,module*/\r\n'use strict';\r\nvar CodeMirror = require('codemirror');\r\nrequire('codemirror/addon/edit/continuelist.js');\r\nrequire('./codemirror/tablist');\r\nrequire('codemirror/addon/display/fullscreen.js');\r\nrequire('codemirror/mode/markdown/markdown.js');\r\nrequire('codemirror/addon/mode/overlay.js');\r\nrequire('codemirror/addon/display/placeholder.js');\r\nrequire('codemirror/addon/selection/mark-selection.js');\r\nrequire('codemirror/mode/gfm/gfm.js');\r\nrequire('codemirror/mode/xml/xml.js');\r\nvar CodeMirrorSpellChecker = require('codemirror-spell-checker');\r\nvar marked = require('marked');\r\n\r\n\r\n// Some variables\r\nvar isMac = /Mac/.test(navigator.platform);\r\n\r\n// Mapping of actions that can be bound to keyboard shortcuts or toolbar buttons\r\nvar bindings = {\r\n 'toggleBold': toggleBold,\r\n 'toggleItalic': toggleItalic,\r\n 'drawLink': drawLink,\r\n 'toggleHeadingSmaller': toggleHeadingSmaller,\r\n 'toggleHeadingBigger': toggleHeadingBigger,\r\n 'drawImage': drawImage,\r\n 'toggleBlockquote': toggleBlockquote,\r\n 'toggleOrderedList': toggleOrderedList,\r\n 'toggleUnorderedList': toggleUnorderedList,\r\n 'toggleCodeBlock': toggleCodeBlock,\r\n 'togglePreview': togglePreview,\r\n 'toggleStrikethrough': toggleStrikethrough,\r\n 'toggleHeading1': toggleHeading1,\r\n 'toggleHeading2': toggleHeading2,\r\n 'toggleHeading3': toggleHeading3,\r\n 'cleanBlock': cleanBlock,\r\n 'drawTable': drawTable,\r\n 'drawHorizontalRule': drawHorizontalRule,\r\n 'undo': undo,\r\n 'redo': redo,\r\n 'toggleSideBySide': toggleSideBySide,\r\n 'toggleFullScreen': toggleFullScreen\r\n};\r\n\r\nvar shortcuts = {\r\n 'toggleBold': 'Cmd-B',\r\n 'toggleItalic': 'Cmd-I',\r\n 'drawLink': 'Cmd-K',\r\n 'toggleHeadingSmaller': 'Cmd-H',\r\n 'toggleHeadingBigger': 'Shift-Cmd-H',\r\n 'cleanBlock': 'Cmd-E',\r\n 'drawImage': 'Cmd-Alt-I',\r\n 'toggleBlockquote': 'Cmd-\\'',\r\n 'toggleOrderedList': 'Cmd-Alt-L',\r\n 'toggleUnorderedList': 'Cmd-L',\r\n 'toggleCodeBlock': 'Cmd-Alt-C',\r\n 'togglePreview': 'Cmd-P',\r\n 'toggleSideBySide': 'F9',\r\n 'toggleFullScreen': 'F11'\r\n};\r\n\r\nvar getBindingName = function (f) {\r\n for (var key in bindings) {\r\n if (bindings[key] === f) {\r\n return key;\r\n }\r\n }\r\n return null;\r\n};\r\n\r\nvar isMobile = function () {\r\n var check = false;\r\n (function (a) {\r\n if (/(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(a.substr(0, 4))) check = true;\r\n })(navigator.userAgent || navigator.vendor || window.opera);\r\n return check;\r\n};\r\n\r\n\r\n/**\r\n * Fix shortcut. Mac use Command, others use Ctrl.\r\n */\r\nfunction fixShortcut(name) {\r\n if (isMac) {\r\n name = name.replace('Ctrl', 'Cmd');\r\n } else {\r\n name = name.replace('Cmd', 'Ctrl');\r\n }\r\n return name;\r\n}\r\n\r\n\r\n/**\r\n * Create icon element for toolbar.\r\n */\r\nfunction createIcon(options, enableTooltips, shortcuts) {\r\n options = options || {};\r\n var el = document.createElement('button');\r\n enableTooltips = (enableTooltips == undefined) ? true : enableTooltips;\r\n\r\n if (options.title && enableTooltips) {\r\n el.title = createTooltip(options.title, options.action, shortcuts);\r\n\r\n if (isMac) {\r\n el.title = el.title.replace('Ctrl', '⌘');\r\n el.title = el.title.replace('Alt', '⌥');\r\n }\r\n }\r\n\r\n if (options.noDisable) {\r\n el.classList.add('no-disable');\r\n }\r\n\r\n if (options.noMobile) {\r\n el.classList.add('no-mobile');\r\n }\r\n\r\n el.tabIndex = -1;\r\n\r\n // Create icon element and append as a child to the button\r\n var icon = document.createElement('i');\r\n icon.className = options.className;\r\n el.appendChild(icon);\r\n\r\n return el;\r\n}\r\n\r\nfunction createSep() {\r\n var el = document.createElement('i');\r\n el.className = 'separator';\r\n el.innerHTML = '|';\r\n return el;\r\n}\r\n\r\nfunction createTooltip(title, action, shortcuts) {\r\n var actionName;\r\n var tooltip = title;\r\n\r\n if (action) {\r\n actionName = getBindingName(action);\r\n if (shortcuts[actionName]) {\r\n tooltip += ' (' + fixShortcut(shortcuts[actionName]) + ')';\r\n }\r\n }\r\n\r\n return tooltip;\r\n}\r\n\r\n/**\r\n * The state of CodeMirror at the given position.\r\n */\r\nfunction getState(cm, pos) {\r\n pos = pos || cm.getCursor('start');\r\n var stat = cm.getTokenAt(pos);\r\n if (!stat.type) return {};\r\n\r\n var types = stat.type.split(' ');\r\n\r\n var ret = {},\r\n data, text;\r\n for (var i = 0; i < types.length; i++) {\r\n data = types[i];\r\n if (data === 'strong') {\r\n ret.bold = true;\r\n } else if (data === 'variable-2') {\r\n text = cm.getLine(pos.line);\r\n if (/^\\s*\\d+\\.\\s/.test(text)) {\r\n ret['ordered-list'] = true;\r\n } else {\r\n ret['unordered-list'] = true;\r\n }\r\n } else if (data === 'atom') {\r\n ret.quote = true;\r\n } else if (data === 'em') {\r\n ret.italic = true;\r\n } else if (data === 'quote') {\r\n ret.quote = true;\r\n } else if (data === 'strikethrough') {\r\n ret.strikethrough = true;\r\n } else if (data === 'comment') {\r\n ret.code = true;\r\n } else if (data === 'link') {\r\n ret.link = true;\r\n } else if (data === 'tag') {\r\n ret.image = true;\r\n } else if (data.match(/^header(-[1-6])?$/)) {\r\n ret[data.replace('header', 'heading')] = true;\r\n }\r\n }\r\n return ret;\r\n}\r\n\r\n\r\n// Saved overflow setting\r\nvar saved_overflow = '';\r\n\r\n/**\r\n * Toggle full screen of the editor.\r\n */\r\nfunction toggleFullScreen(editor) {\r\n // Set fullscreen\r\n var cm = editor.codemirror;\r\n cm.setOption('fullScreen', !cm.getOption('fullScreen'));\r\n\r\n\r\n // Prevent scrolling on body during fullscreen active\r\n if (cm.getOption('fullScreen')) {\r\n saved_overflow = document.body.style.overflow;\r\n document.body.style.overflow = 'hidden';\r\n } else {\r\n document.body.style.overflow = saved_overflow;\r\n }\r\n\r\n\r\n // Update toolbar class\r\n var wrap = cm.getWrapperElement();\r\n\r\n if (!/fullscreen/.test(wrap.previousSibling.className)) {\r\n wrap.previousSibling.className += ' fullscreen';\r\n } else {\r\n wrap.previousSibling.className = wrap.previousSibling.className.replace(/\\s*fullscreen\\b/, '');\r\n }\r\n\r\n\r\n // Update toolbar button\r\n if (editor.toolbarElements.fullscreen) {\r\n var toolbarButton = editor.toolbarElements.fullscreen;\r\n\r\n if (!/active/.test(toolbarButton.className)) {\r\n toolbarButton.className += ' active';\r\n } else {\r\n toolbarButton.className = toolbarButton.className.replace(/\\s*active\\s*/g, '');\r\n }\r\n }\r\n\r\n\r\n // Hide side by side if needed\r\n var sidebyside = cm.getWrapperElement().nextSibling;\r\n if (/editor-preview-active-side/.test(sidebyside.className))\r\n toggleSideBySide(editor);\r\n}\r\n\r\n\r\n/**\r\n * Action for toggling bold.\r\n */\r\nfunction toggleBold(editor) {\r\n _toggleBlock(editor, 'bold', editor.options.blockStyles.bold);\r\n}\r\n\r\n\r\n/**\r\n * Action for toggling italic.\r\n */\r\nfunction toggleItalic(editor) {\r\n _toggleBlock(editor, 'italic', editor.options.blockStyles.italic);\r\n}\r\n\r\n\r\n/**\r\n * Action for toggling strikethrough.\r\n */\r\nfunction toggleStrikethrough(editor) {\r\n _toggleBlock(editor, 'strikethrough', '~~');\r\n}\r\n\r\n/**\r\n * Action for toggling code block.\r\n */\r\nfunction toggleCodeBlock(editor) {\r\n var fenceCharsToInsert = editor.options.blockStyles.code;\r\n\r\n function fencing_line(line) {\r\n /* return true, if this is a ``` or ~~~ line */\r\n if (typeof line !== 'object') {\r\n throw 'fencing_line() takes a \\'line\\' object (not a line number, or line text). Got: ' + typeof line + ': ' + line;\r\n }\r\n return line.styles && line.styles[2] && line.styles[2].indexOf('formatting-code-block') !== -1;\r\n }\r\n\r\n function token_state(token) {\r\n // base goes an extra level deep when mode backdrops are used, e.g. spellchecker on\r\n return token.state.base.base || token.state.base;\r\n }\r\n\r\n function code_type(cm, line_num, line, firstTok, lastTok) {\r\n /*\r\n * Return \"single\", \"indented\", \"fenced\" or false\r\n *\r\n * cm and line_num are required. Others are optional for efficiency\r\n * To check in the middle of a line, pass in firstTok yourself.\r\n */\r\n line = line || cm.getLineHandle(line_num);\r\n firstTok = firstTok || cm.getTokenAt({\r\n line: line_num,\r\n ch: 1\r\n });\r\n lastTok = lastTok || (!!line.text && cm.getTokenAt({\r\n line: line_num,\r\n ch: line.text.length - 1\r\n }));\r\n var types = firstTok.type ? firstTok.type.split(' ') : [];\r\n if (lastTok && token_state(lastTok).indentedCode) {\r\n // have to check last char, since first chars of first line aren\"t marked as indented\r\n return 'indented';\r\n } else if (types.indexOf('comment') === -1) {\r\n // has to be after \"indented\" check, since first chars of first indented line aren\"t marked as such\r\n return false;\r\n } else if (token_state(firstTok).fencedChars || token_state(lastTok).fencedChars || fencing_line(line)) {\r\n return 'fenced';\r\n } else {\r\n return 'single';\r\n }\r\n }\r\n\r\n function insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert) {\r\n var start_line_sel = cur_start.line + 1,\r\n end_line_sel = cur_end.line + 1,\r\n sel_multi = cur_start.line !== cur_end.line,\r\n repl_start = fenceCharsToInsert + '\\n',\r\n repl_end = '\\n' + fenceCharsToInsert;\r\n if (sel_multi) {\r\n end_line_sel++;\r\n }\r\n // handle last char including \\n or not\r\n if (sel_multi && cur_end.ch === 0) {\r\n repl_end = fenceCharsToInsert + '\\n';\r\n end_line_sel--;\r\n }\r\n _replaceSelection(cm, false, [repl_start, repl_end]);\r\n cm.setSelection({\r\n line: start_line_sel,\r\n ch: 0\r\n }, {\r\n line: end_line_sel,\r\n ch: 0\r\n });\r\n }\r\n\r\n var cm = editor.codemirror,\r\n cur_start = cm.getCursor('start'),\r\n cur_end = cm.getCursor('end'),\r\n tok = cm.getTokenAt({\r\n line: cur_start.line,\r\n ch: cur_start.ch || 1\r\n }), // avoid ch 0 which is a cursor pos but not token\r\n line = cm.getLineHandle(cur_start.line),\r\n is_code = code_type(cm, cur_start.line, line, tok);\r\n var block_start, block_end, lineCount;\r\n\r\n if (is_code === 'single') {\r\n // similar to some InscrybMDE _toggleBlock logic\r\n var start = line.text.slice(0, cur_start.ch).replace('`', ''),\r\n end = line.text.slice(cur_start.ch).replace('`', '');\r\n cm.replaceRange(start + end, {\r\n line: cur_start.line,\r\n ch: 0\r\n }, {\r\n line: cur_start.line,\r\n ch: 99999999999999\r\n });\r\n cur_start.ch--;\r\n if (cur_start !== cur_end) {\r\n cur_end.ch--;\r\n }\r\n cm.setSelection(cur_start, cur_end);\r\n cm.focus();\r\n } else if (is_code === 'fenced') {\r\n if (cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {\r\n // use selection\r\n\r\n // find the fenced line so we know what type it is (tilde, backticks, number of them)\r\n for (block_start = cur_start.line; block_start >= 0; block_start--) {\r\n line = cm.getLineHandle(block_start);\r\n if (fencing_line(line)) {\r\n break;\r\n }\r\n }\r\n var fencedTok = cm.getTokenAt({\r\n line: block_start,\r\n ch: 1\r\n });\r\n var fence_chars = token_state(fencedTok).fencedChars;\r\n var start_text, start_line;\r\n var end_text, end_line;\r\n // check for selection going up against fenced lines, in which case we don't want to add more fencing\r\n if (fencing_line(cm.getLineHandle(cur_start.line))) {\r\n start_text = '';\r\n start_line = cur_start.line;\r\n } else if (fencing_line(cm.getLineHandle(cur_start.line - 1))) {\r\n start_text = '';\r\n start_line = cur_start.line - 1;\r\n } else {\r\n start_text = fence_chars + '\\n';\r\n start_line = cur_start.line;\r\n }\r\n if (fencing_line(cm.getLineHandle(cur_end.line))) {\r\n end_text = '';\r\n end_line = cur_end.line;\r\n if (cur_end.ch === 0) {\r\n end_line += 1;\r\n }\r\n } else if (cur_end.ch !== 0 && fencing_line(cm.getLineHandle(cur_end.line + 1))) {\r\n end_text = '';\r\n end_line = cur_end.line + 1;\r\n } else {\r\n end_text = fence_chars + '\\n';\r\n end_line = cur_end.line + 1;\r\n }\r\n if (cur_end.ch === 0) {\r\n // full last line selected, putting cursor at beginning of next\r\n end_line -= 1;\r\n }\r\n cm.operation(function () {\r\n // end line first, so that line numbers don't change\r\n cm.replaceRange(end_text, {\r\n line: end_line,\r\n ch: 0\r\n }, {\r\n line: end_line + (end_text ? 0 : 1),\r\n ch: 0\r\n });\r\n cm.replaceRange(start_text, {\r\n line: start_line,\r\n ch: 0\r\n }, {\r\n line: start_line + (start_text ? 0 : 1),\r\n ch: 0\r\n });\r\n });\r\n cm.setSelection({\r\n line: start_line + (start_text ? 1 : 0),\r\n ch: 0\r\n }, {\r\n line: end_line + (start_text ? 1 : -1),\r\n ch: 0\r\n });\r\n cm.focus();\r\n } else {\r\n // no selection, search for ends of this fenced block\r\n var search_from = cur_start.line;\r\n if (fencing_line(cm.getLineHandle(cur_start.line))) { // gets a little tricky if cursor is right on a fenced line\r\n if (code_type(cm, cur_start.line + 1) === 'fenced') {\r\n block_start = cur_start.line;\r\n search_from = cur_start.line + 1; // for searching for \"end\"\r\n } else {\r\n block_end = cur_start.line;\r\n search_from = cur_start.line - 1; // for searching for \"start\"\r\n }\r\n }\r\n if (block_start === undefined) {\r\n for (block_start = search_from; block_start >= 0; block_start--) {\r\n line = cm.getLineHandle(block_start);\r\n if (fencing_line(line)) {\r\n break;\r\n }\r\n }\r\n }\r\n if (block_end === undefined) {\r\n lineCount = cm.lineCount();\r\n for (block_end = search_from; block_end < lineCount; block_end++) {\r\n line = cm.getLineHandle(block_end);\r\n if (fencing_line(line)) {\r\n break;\r\n }\r\n }\r\n }\r\n cm.operation(function () {\r\n cm.replaceRange('', {\r\n line: block_start,\r\n ch: 0\r\n }, {\r\n line: block_start + 1,\r\n ch: 0\r\n });\r\n cm.replaceRange('', {\r\n line: block_end - 1,\r\n ch: 0\r\n }, {\r\n line: block_end,\r\n ch: 0\r\n });\r\n });\r\n cm.focus();\r\n }\r\n } else if (is_code === 'indented') {\r\n if (cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {\r\n // use selection\r\n block_start = cur_start.line;\r\n block_end = cur_end.line;\r\n if (cur_end.ch === 0) {\r\n block_end--;\r\n }\r\n } else {\r\n // no selection, search for ends of this indented block\r\n for (block_start = cur_start.line; block_start >= 0; block_start--) {\r\n line = cm.getLineHandle(block_start);\r\n if (line.text.match(/^\\s*$/)) {\r\n // empty or all whitespace - keep going\r\n continue;\r\n } else {\r\n if (code_type(cm, block_start, line) !== 'indented') {\r\n block_start += 1;\r\n break;\r\n }\r\n }\r\n }\r\n lineCount = cm.lineCount();\r\n for (block_end = cur_start.line; block_end < lineCount; block_end++) {\r\n line = cm.getLineHandle(block_end);\r\n if (line.text.match(/^\\s*$/)) {\r\n // empty or all whitespace - keep going\r\n continue;\r\n } else {\r\n if (code_type(cm, block_end, line) !== 'indented') {\r\n block_end -= 1;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n // if we are going to un-indent based on a selected set of lines, and the next line is indented too, we need to\r\n // insert a blank line so that the next line(s) continue to be indented code\r\n var next_line = cm.getLineHandle(block_end + 1),\r\n next_line_last_tok = next_line && cm.getTokenAt({\r\n line: block_end + 1,\r\n ch: next_line.text.length - 1\r\n }),\r\n next_line_indented = next_line_last_tok && token_state(next_line_last_tok).indentedCode;\r\n if (next_line_indented) {\r\n cm.replaceRange('\\n', {\r\n line: block_end + 1,\r\n ch: 0\r\n });\r\n }\r\n\r\n for (var i = block_start; i <= block_end; i++) {\r\n cm.indentLine(i, 'subtract'); // TODO: this doesn't get tracked in the history, so can't be undone :(\r\n }\r\n cm.focus();\r\n } else {\r\n // insert code formatting\r\n var no_sel_and_starting_of_line = (cur_start.line === cur_end.line && cur_start.ch === cur_end.ch && cur_start.ch === 0);\r\n var sel_multi = cur_start.line !== cur_end.line;\r\n if (no_sel_and_starting_of_line || sel_multi) {\r\n insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert);\r\n } else {\r\n _replaceSelection(cm, false, ['`', '`']);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Action for toggling blockquote.\r\n */\r\nfunction toggleBlockquote(editor) {\r\n var cm = editor.codemirror;\r\n _toggleLine(cm, 'quote');\r\n}\r\n\r\n/**\r\n * Action for toggling heading size: normal -> h1 -> h2 -> h3 -> h4 -> h5 -> h6 -> normal\r\n */\r\nfunction toggleHeadingSmaller(editor) {\r\n var cm = editor.codemirror;\r\n _toggleHeading(cm, 'smaller');\r\n}\r\n\r\n/**\r\n * Action for toggling heading size: normal -> h6 -> h5 -> h4 -> h3 -> h2 -> h1 -> normal\r\n */\r\nfunction toggleHeadingBigger(editor) {\r\n var cm = editor.codemirror;\r\n _toggleHeading(cm, 'bigger');\r\n}\r\n\r\n/**\r\n * Action for toggling heading size 1\r\n */\r\nfunction toggleHeading1(editor) {\r\n var cm = editor.codemirror;\r\n _toggleHeading(cm, undefined, 1);\r\n}\r\n\r\n/**\r\n * Action for toggling heading size 2\r\n */\r\nfunction toggleHeading2(editor) {\r\n var cm = editor.codemirror;\r\n _toggleHeading(cm, undefined, 2);\r\n}\r\n\r\n/**\r\n * Action for toggling heading size 3\r\n */\r\nfunction toggleHeading3(editor) {\r\n var cm = editor.codemirror;\r\n _toggleHeading(cm, undefined, 3);\r\n}\r\n\r\n\r\n/**\r\n * Action for toggling ul.\r\n */\r\nfunction toggleUnorderedList(editor) {\r\n var cm = editor.codemirror;\r\n _toggleLine(cm, 'unordered-list');\r\n}\r\n\r\n\r\n/**\r\n * Action for toggling ol.\r\n */\r\nfunction toggleOrderedList(editor) {\r\n var cm = editor.codemirror;\r\n _toggleLine(cm, 'ordered-list');\r\n}\r\n\r\n/**\r\n * Action for clean block (remove headline, list, blockquote code, markers)\r\n */\r\nfunction cleanBlock(editor) {\r\n var cm = editor.codemirror;\r\n _cleanBlock(cm);\r\n}\r\n\r\n/**\r\n * Action for drawing a link.\r\n */\r\nfunction drawLink(editor) {\r\n var cm = editor.codemirror;\r\n var stat = getState(cm);\r\n var options = editor.options;\r\n var url = 'https://';\r\n if (options.promptURLs) {\r\n url = prompt(options.promptTexts.link);\r\n if (!url) {\r\n return false;\r\n }\r\n }\r\n _replaceSelection(cm, stat.link, options.insertTexts.link, url);\r\n}\r\n\r\n/**\r\n * Action for drawing an img.\r\n */\r\nfunction drawImage(editor) {\r\n var cm = editor.codemirror;\r\n var stat = getState(cm);\r\n var options = editor.options;\r\n var url = 'https://';\r\n if (options.promptURLs) {\r\n url = prompt(options.promptTexts.image);\r\n if (!url) {\r\n return false;\r\n }\r\n }\r\n _replaceSelection(cm, stat.image, options.insertTexts.image, url);\r\n}\r\n\r\n/**\r\n * Action for drawing a table.\r\n */\r\nfunction drawTable(editor) {\r\n var cm = editor.codemirror;\r\n var stat = getState(cm);\r\n var options = editor.options;\r\n _replaceSelection(cm, stat.table, options.insertTexts.table);\r\n}\r\n\r\n/**\r\n * Action for drawing a horizontal rule.\r\n */\r\nfunction drawHorizontalRule(editor) {\r\n var cm = editor.codemirror;\r\n var stat = getState(cm);\r\n var options = editor.options;\r\n _replaceSelection(cm, stat.image, options.insertTexts.horizontalRule);\r\n}\r\n\r\n\r\n/**\r\n * Undo action.\r\n */\r\nfunction undo(editor) {\r\n var cm = editor.codemirror;\r\n cm.undo();\r\n cm.focus();\r\n}\r\n\r\n\r\n/**\r\n * Redo action.\r\n */\r\nfunction redo(editor) {\r\n var cm = editor.codemirror;\r\n cm.redo();\r\n cm.focus();\r\n}\r\n\r\n\r\n/**\r\n * Toggle side by side preview\r\n */\r\nfunction toggleSideBySide(editor) {\r\n var cm = editor.codemirror;\r\n var wrapper = cm.getWrapperElement();\r\n var preview = wrapper.nextSibling;\r\n var toolbarButton = editor.toolbarElements['side-by-side'];\r\n var useSideBySideListener = false;\r\n if (/editor-preview-active-side/.test(preview.className)) {\r\n preview.className = preview.className.replace(\r\n /\\s*editor-preview-active-side\\s*/g, ''\r\n );\r\n toolbarButton.className = toolbarButton.className.replace(/\\s*active\\s*/g, '');\r\n wrapper.className = wrapper.className.replace(/\\s*CodeMirror-sided\\s*/g, ' ');\r\n } else {\r\n // When the preview button is clicked for the first time,\r\n // give some time for the transition from editor.css to fire and the view to slide from right to left,\r\n // instead of just appearing.\r\n setTimeout(function () {\r\n if (!cm.getOption('fullScreen'))\r\n toggleFullScreen(editor);\r\n preview.className += ' editor-preview-active-side';\r\n }, 1);\r\n toolbarButton.className += ' active';\r\n wrapper.className += ' CodeMirror-sided';\r\n useSideBySideListener = true;\r\n }\r\n\r\n // Hide normal preview if active\r\n var previewNormal = wrapper.lastChild;\r\n if (/editor-preview-active/.test(previewNormal.className)) {\r\n previewNormal.className = previewNormal.className.replace(\r\n /\\s*editor-preview-active\\s*/g, ''\r\n );\r\n var toolbar = editor.toolbarElements.preview;\r\n var toolbar_div = wrapper.previousSibling;\r\n toolbar.className = toolbar.className.replace(/\\s*active\\s*/g, '');\r\n toolbar_div.className = toolbar_div.className.replace(/\\s*disabled-for-preview*/g, '');\r\n }\r\n\r\n var sideBySideRenderingFunction = function () {\r\n preview.innerHTML = editor.options.previewRender(editor.value(), preview);\r\n };\r\n\r\n if (!cm.sideBySideRenderingFunction) {\r\n cm.sideBySideRenderingFunction = sideBySideRenderingFunction;\r\n }\r\n\r\n if (useSideBySideListener) {\r\n preview.innerHTML = editor.options.previewRender(editor.value(), preview);\r\n cm.on('update', cm.sideBySideRenderingFunction);\r\n } else {\r\n cm.off('update', cm.sideBySideRenderingFunction);\r\n }\r\n\r\n // Refresh to fix selection being off (#309)\r\n cm.refresh();\r\n}\r\n\r\n\r\n/**\r\n * Preview action.\r\n */\r\nfunction togglePreview(editor) {\r\n var cm = editor.codemirror;\r\n var wrapper = cm.getWrapperElement();\r\n var toolbar_div = wrapper.previousSibling;\r\n var toolbar = editor.options.toolbar ? editor.toolbarElements.preview : false;\r\n var preview = wrapper.lastChild;\r\n if (!preview || !/editor-preview/.test(preview.className)) {\r\n preview = document.createElement('div');\r\n preview.className = 'editor-preview';\r\n wrapper.appendChild(preview);\r\n }\r\n if (/editor-preview-active/.test(preview.className)) {\r\n preview.className = preview.className.replace(\r\n /\\s*editor-preview-active\\s*/g, ''\r\n );\r\n if (toolbar) {\r\n toolbar.className = toolbar.className.replace(/\\s*active\\s*/g, '');\r\n toolbar_div.className = toolbar_div.className.replace(/\\s*disabled-for-preview*/g, '');\r\n }\r\n } else {\r\n // When the preview button is clicked for the first time,\r\n // give some time for the transition from editor.css to fire and the view to slide from right to left,\r\n // instead of just appearing.\r\n setTimeout(function () {\r\n preview.className += ' editor-preview-active';\r\n }, 1);\r\n if (toolbar) {\r\n toolbar.className += ' active';\r\n toolbar_div.className += ' disabled-for-preview';\r\n }\r\n }\r\n preview.innerHTML = editor.options.previewRender(editor.value(), preview);\r\n\r\n // Turn off side by side if needed\r\n var sidebyside = cm.getWrapperElement().nextSibling;\r\n if (/editor-preview-active-side/.test(sidebyside.className))\r\n toggleSideBySide(editor);\r\n}\r\n\r\nfunction _replaceSelection(cm, active, startEnd, url) {\r\n if (/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))\r\n return;\r\n\r\n var text;\r\n var start = startEnd[0];\r\n var end = startEnd[1];\r\n var startPoint = {},\r\n endPoint = {};\r\n Object.assign(startPoint, cm.getCursor('start'));\r\n Object.assign(endPoint, cm.getCursor('end'));\r\n if (url) {\r\n end = end.replace('#url#', url);\r\n }\r\n if (active) {\r\n text = cm.getLine(startPoint.line);\r\n start = text.slice(0, startPoint.ch);\r\n end = text.slice(startPoint.ch);\r\n cm.replaceRange(start + end, {\r\n line: startPoint.line,\r\n ch: 0\r\n });\r\n } else {\r\n text = cm.getSelection();\r\n cm.replaceSelection(start + text + end);\r\n\r\n startPoint.ch += start.length;\r\n if (startPoint !== endPoint) {\r\n endPoint.ch += start.length;\r\n }\r\n }\r\n cm.setSelection(startPoint, endPoint);\r\n cm.focus();\r\n}\r\n\r\n\r\nfunction _toggleHeading(cm, direction, size) {\r\n if (/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))\r\n return;\r\n\r\n var startPoint = cm.getCursor('start');\r\n var endPoint = cm.getCursor('end');\r\n for (var i = startPoint.line; i <= endPoint.line; i++) {\r\n (function (i) {\r\n var text = cm.getLine(i);\r\n var currHeadingLevel = text.search(/[^#]/);\r\n\r\n if (direction !== undefined) {\r\n if (currHeadingLevel <= 0) {\r\n if (direction == 'bigger') {\r\n text = '###### ' + text;\r\n } else {\r\n text = '# ' + text;\r\n }\r\n } else if (currHeadingLevel == 6 && direction == 'smaller') {\r\n text = text.substr(7);\r\n } else if (currHeadingLevel == 1 && direction == 'bigger') {\r\n text = text.substr(2);\r\n } else {\r\n if (direction == 'bigger') {\r\n text = text.substr(1);\r\n } else {\r\n text = '#' + text;\r\n }\r\n }\r\n } else {\r\n if (size == 1) {\r\n if (currHeadingLevel <= 0) {\r\n text = '# ' + text;\r\n } else if (currHeadingLevel == size) {\r\n text = text.substr(currHeadingLevel + 1);\r\n } else {\r\n text = '# ' + text.substr(currHeadingLevel + 1);\r\n }\r\n } else if (size == 2) {\r\n if (currHeadingLevel <= 0) {\r\n text = '## ' + text;\r\n } else if (currHeadingLevel == size) {\r\n text = text.substr(currHeadingLevel + 1);\r\n } else {\r\n text = '## ' + text.substr(currHeadingLevel + 1);\r\n }\r\n } else {\r\n if (currHeadingLevel <= 0) {\r\n text = '### ' + text;\r\n } else if (currHeadingLevel == size) {\r\n text = text.substr(currHeadingLevel + 1);\r\n } else {\r\n text = '### ' + text.substr(currHeadingLevel + 1);\r\n }\r\n }\r\n }\r\n\r\n cm.replaceRange(text, {\r\n line: i,\r\n ch: 0\r\n }, {\r\n line: i,\r\n ch: 99999999999999\r\n });\r\n })(i);\r\n }\r\n cm.focus();\r\n}\r\n\r\n\r\nfunction _toggleLine(cm, name) {\r\n if (/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))\r\n return;\r\n\r\n var listRegexp = /^(\\s*)(\\*|-|\\+|\\d*\\.)(\\s+)/;\r\n var whitespacesRegexp = /^\\s*/;\r\n\r\n var stat = getState(cm);\r\n var startPoint = cm.getCursor('start');\r\n var endPoint = cm.getCursor('end');\r\n var repl = {\r\n 'quote': /^(\\s*)>\\s+/,\r\n 'unordered-list': listRegexp,\r\n 'ordered-list': listRegexp\r\n };\r\n\r\n var _getChar = function (name, i) {\r\n var map = {\r\n 'quote': '>',\r\n 'unordered-list': '*',\r\n 'ordered-list': '%%i.'\r\n };\r\n\r\n return map[name].replace('%%i', i);\r\n };\r\n\r\n var _checkChar = function (name, char) {\r\n var map = {\r\n 'quote': '>',\r\n 'unordered-list': '*',\r\n 'ordered-list': 'd+.'\r\n };\r\n var rt = new RegExp(map[name]);\r\n\r\n return char && rt.test(char);\r\n };\r\n\r\n var line = 1;\r\n for (var i = startPoint.line; i <= endPoint.line; i++) {\r\n (function (i) {\r\n var text = cm.getLine(i);\r\n if (stat[name]) {\r\n text = text.replace(repl[name], '$1');\r\n } else {\r\n var arr = listRegexp.exec(text);\r\n var char = _getChar(name, line);\r\n if (arr !== null) {\r\n if (_checkChar(name, arr[2])) {\r\n char = '';\r\n }\r\n text = arr[1] + char + arr[3] + text.replace(whitespacesRegexp, '').replace(repl[name], '$1');\r\n } else {\r\n text = char + ' ' + text;\r\n }\r\n line += 1;\r\n }\r\n cm.replaceRange(text, {\r\n line: i,\r\n ch: 0\r\n }, {\r\n line: i,\r\n ch: 99999999999999\r\n });\r\n })(i);\r\n }\r\n cm.focus();\r\n}\r\n\r\nfunction _toggleBlock(editor, type, start_chars, end_chars) {\r\n if (/editor-preview-active/.test(editor.codemirror.getWrapperElement().lastChild.className))\r\n return;\r\n\r\n end_chars = (typeof end_chars === 'undefined') ? start_chars : end_chars;\r\n var cm = editor.codemirror;\r\n var stat = getState(cm);\r\n\r\n var text;\r\n var start = start_chars;\r\n var end = end_chars;\r\n\r\n var startPoint = cm.getCursor('start');\r\n var endPoint = cm.getCursor('end');\r\n\r\n if (stat[type]) {\r\n text = cm.getLine(startPoint.line);\r\n start = text.slice(0, startPoint.ch);\r\n end = text.slice(startPoint.ch);\r\n if (type == 'bold') {\r\n start = start.replace(/(\\*\\*|__)(?![\\s\\S]*(\\*\\*|__))/, '');\r\n end = end.replace(/(\\*\\*|__)/, '');\r\n } else if (type == 'italic') {\r\n start = start.replace(/(\\*|_)(?![\\s\\S]*(\\*|_))/, '');\r\n end = end.replace(/(\\*|_)/, '');\r\n } else if (type == 'strikethrough') {\r\n start = start.replace(/(\\*\\*|~~)(?![\\s\\S]*(\\*\\*|~~))/, '');\r\n end = end.replace(/(\\*\\*|~~)/, '');\r\n }\r\n cm.replaceRange(start + end, {\r\n line: startPoint.line,\r\n ch: 0\r\n }, {\r\n line: startPoint.line,\r\n ch: 99999999999999\r\n });\r\n\r\n if (type == 'bold' || type == 'strikethrough') {\r\n startPoint.ch -= 2;\r\n if (startPoint !== endPoint) {\r\n endPoint.ch -= 2;\r\n }\r\n } else if (type == 'italic') {\r\n startPoint.ch -= 1;\r\n if (startPoint !== endPoint) {\r\n endPoint.ch -= 1;\r\n }\r\n }\r\n } else {\r\n text = cm.getSelection();\r\n if (type == 'bold') {\r\n text = text.split('**').join('');\r\n text = text.split('__').join('');\r\n } else if (type == 'italic') {\r\n text = text.split('*').join('');\r\n text = text.split('_').join('');\r\n } else if (type == 'strikethrough') {\r\n text = text.split('~~').join('');\r\n }\r\n cm.replaceSelection(start + text + end);\r\n\r\n startPoint.ch += start_chars.length;\r\n endPoint.ch = startPoint.ch + text.length;\r\n }\r\n\r\n cm.setSelection(startPoint, endPoint);\r\n cm.focus();\r\n}\r\n\r\nfunction _cleanBlock(cm) {\r\n if (/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))\r\n return;\r\n\r\n var startPoint = cm.getCursor('start');\r\n var endPoint = cm.getCursor('end');\r\n var text;\r\n\r\n for (var line = startPoint.line; line <= endPoint.line; line++) {\r\n text = cm.getLine(line);\r\n text = text.replace(/^[ ]*([# ]+|\\*|-|[> ]+|[0-9]+(.|\\)))[ ]*/, '');\r\n\r\n cm.replaceRange(text, {\r\n line: line,\r\n ch: 0\r\n }, {\r\n line: line,\r\n ch: 99999999999999\r\n });\r\n }\r\n}\r\n\r\n// Merge the properties of one object into another.\r\nfunction _mergeProperties(target, source) {\r\n for (var property in source) {\r\n if (source.hasOwnProperty(property)) {\r\n if (source[property] instanceof Array) {\r\n target[property] = source[property].concat(target[property] instanceof Array ? target[property] : []);\r\n } else if (\r\n source[property] !== null &&\r\n typeof source[property] === 'object' &&\r\n source[property].constructor === Object\r\n ) {\r\n target[property] = _mergeProperties(target[property] || {}, source[property]);\r\n } else {\r\n target[property] = source[property];\r\n }\r\n }\r\n }\r\n\r\n return target;\r\n}\r\n\r\n// Merge an arbitrary number of objects into one.\r\nfunction extend(target) {\r\n for (var i = 1; i < arguments.length; i++) {\r\n target = _mergeProperties(target, arguments[i]);\r\n }\r\n\r\n return target;\r\n}\r\n\r\n/* The right word count in respect for CJK. */\r\nfunction wordCount(data) {\r\n var pattern = /[a-zA-Z0-9_\\u0392-\\u03c9\\u0410-\\u04F9]+|[\\u4E00-\\u9FFF\\u3400-\\u4dbf\\uf900-\\ufaff\\u3040-\\u309f\\uac00-\\ud7af]+/g;\r\n var m = data.match(pattern);\r\n var count = 0;\r\n if (m === null) return count;\r\n for (var i = 0; i < m.length; i++) {\r\n if (m[i].charCodeAt(0) >= 0x4E00) {\r\n count += m[i].length;\r\n } else {\r\n count += 1;\r\n }\r\n }\r\n return count;\r\n}\r\n\r\nvar toolbarBuiltInButtons = {\r\n 'bold': {\r\n name: 'bold',\r\n action: toggleBold,\r\n className: 'fa fa-bold',\r\n title: 'Bold',\r\n default: true\r\n },\r\n 'italic': {\r\n name: 'italic',\r\n action: toggleItalic,\r\n className: 'fa fa-italic',\r\n title: 'Italic',\r\n default: true\r\n },\r\n 'strikethrough': {\r\n name: 'strikethrough',\r\n action: toggleStrikethrough,\r\n className: 'fa fa-strikethrough',\r\n title: 'Strikethrough'\r\n },\r\n 'heading': {\r\n name: 'heading',\r\n action: toggleHeadingSmaller,\r\n className: 'fa fa-header fa-heading',\r\n title: 'Heading',\r\n default: true\r\n },\r\n 'heading-smaller': {\r\n name: 'heading-smaller',\r\n action: toggleHeadingSmaller,\r\n className: 'fa fa-header fa-header-x fa-header-smaller',\r\n title: 'Smaller Heading'\r\n },\r\n 'heading-bigger': {\r\n name: 'heading-bigger',\r\n action: toggleHeadingBigger,\r\n className: 'fa fa-header fa-header-x fa-header-bigger',\r\n title: 'Bigger Heading'\r\n },\r\n 'heading-1': {\r\n name: 'heading-1',\r\n action: toggleHeading1,\r\n className: 'fa fa-header fa-header-x fa-header-1 fa-h1',\r\n title: 'Big Heading'\r\n },\r\n 'heading-2': {\r\n name: 'heading-2',\r\n action: toggleHeading2,\r\n className: 'fa fa-header fa-header-x fa-header-2 fa-h2',\r\n title: 'Medium Heading'\r\n },\r\n 'heading-3': {\r\n name: 'heading-3',\r\n action: toggleHeading3,\r\n className: 'fa fa-header fa-header-x fa-header-3 fa-h3',\r\n title: 'Small Heading'\r\n },\r\n 'separator-1': {\r\n name: 'separator-1'\r\n },\r\n 'code': {\r\n name: 'code',\r\n action: toggleCodeBlock,\r\n className: 'fa fa-code',\r\n title: 'Code'\r\n },\r\n 'quote': {\r\n name: 'quote',\r\n action: toggleBlockquote,\r\n className: 'fa fa-quote-left',\r\n title: 'Quote',\r\n default: true\r\n },\r\n 'unordered-list': {\r\n name: 'unordered-list',\r\n action: toggleUnorderedList,\r\n className: 'fa fa-list-ul',\r\n title: 'Generic List',\r\n default: true\r\n },\r\n 'ordered-list': {\r\n name: 'ordered-list',\r\n action: toggleOrderedList,\r\n className: 'fa fa-list-ol',\r\n title: 'Numbered List',\r\n default: true\r\n },\r\n 'clean-block': {\r\n name: 'clean-block',\r\n action: cleanBlock,\r\n className: 'fa fa-eraser fa-clean-block',\r\n title: 'Clean block'\r\n },\r\n 'separator-2': {\r\n name: 'separator-2'\r\n },\r\n 'link': {\r\n name: 'link',\r\n action: drawLink,\r\n className: 'fa fa-link',\r\n title: 'Create Link',\r\n default: true\r\n },\r\n 'image': {\r\n name: 'image',\r\n action: drawImage,\r\n className: 'fa fa-image',\r\n title: 'Insert Image',\r\n default: true\r\n },\r\n 'table': {\r\n name: 'table',\r\n action: drawTable,\r\n className: 'fa fa-table',\r\n title: 'Insert Table'\r\n },\r\n 'horizontal-rule': {\r\n name: 'horizontal-rule',\r\n action: drawHorizontalRule,\r\n className: 'fa fa-minus',\r\n title: 'Insert Horizontal Line'\r\n },\r\n 'separator-3': {\r\n name: 'separator-3'\r\n },\r\n 'preview': {\r\n name: 'preview',\r\n action: togglePreview,\r\n className: 'fa fa-eye',\r\n noDisable: true,\r\n title: 'Toggle Preview',\r\n default: true\r\n },\r\n 'side-by-side': {\r\n name: 'side-by-side',\r\n action: toggleSideBySide,\r\n className: 'fa fa-columns',\r\n noDisable: true,\r\n noMobile: true,\r\n title: 'Toggle Side by Side',\r\n default: true\r\n },\r\n 'fullscreen': {\r\n name: 'fullscreen',\r\n action: toggleFullScreen,\r\n className: 'fa fa-arrows-alt',\r\n noDisable: true,\r\n noMobile: true,\r\n title: 'Toggle Fullscreen',\r\n default: true\r\n },\r\n 'separator-4': {\r\n name: 'separator-4'\r\n },\r\n 'guide': {\r\n name: 'guide',\r\n action: 'https://www.inscryb.com/InscrybMDE/markdown-guide/',\r\n className: 'fa fa-question-circle',\r\n noDisable: true,\r\n title: 'Markdown Guide',\r\n default: true\r\n },\r\n 'separator-5': {\r\n name: 'separator-5'\r\n },\r\n 'undo': {\r\n name: 'undo',\r\n action: undo,\r\n className: 'fa fa-undo',\r\n noDisable: true,\r\n title: 'Undo'\r\n },\r\n 'redo': {\r\n name: 'redo',\r\n action: redo,\r\n className: 'fa fa-repeat',\r\n noDisable: true,\r\n title: 'Redo'\r\n }\r\n};\r\n\r\nvar insertTexts = {\r\n link: ['[', '](#url#)'],\r\n image: [''],\r\n table: ['', '\\n\\n| Column 1 | Column 2 | Column 3 |\\n| -------- | -------- | -------- |\\n| Text | Text | Text |\\n\\n'],\r\n horizontalRule: ['', '\\n\\n-----\\n\\n']\r\n};\r\n\r\nvar promptTexts = {\r\n link: 'URL for the link:',\r\n image: 'URL of the image:'\r\n};\r\n\r\nvar blockStyles = {\r\n 'bold': '**',\r\n 'code': '```',\r\n 'italic': '*'\r\n};\r\n\r\n/**\r\n * Interface of InscrybMDE.\r\n */\r\nfunction InscrybMDE(options) {\r\n // Handle options parameter\r\n options = options || {};\r\n\r\n\r\n // Used later to refer to it\"s parent\r\n options.parent = this;\r\n\r\n\r\n // Check if Font Awesome needs to be auto downloaded\r\n var autoDownloadFA = true;\r\n\r\n if (options.autoDownloadFontAwesome === false) {\r\n autoDownloadFA = false;\r\n }\r\n\r\n if (options.autoDownloadFontAwesome !== true) {\r\n var styleSheets = document.styleSheets;\r\n for (var i = 0; i < styleSheets.length; i++) {\r\n if (!styleSheets[i].href)\r\n continue;\r\n\r\n if (styleSheets[i].href.indexOf('//maxcdn.bootstrapcdn.com/font-awesome/') > -1) {\r\n autoDownloadFA = false;\r\n }\r\n }\r\n }\r\n\r\n if (autoDownloadFA) {\r\n var link = document.createElement('link');\r\n link.rel = 'stylesheet';\r\n link.href = 'https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css';\r\n document.getElementsByTagName('head')[0].appendChild(link);\r\n }\r\n\r\n\r\n // Find the textarea to use\r\n if (options.element) {\r\n this.element = options.element;\r\n } else if (options.element === null) {\r\n // This means that the element option was specified, but no element was found\r\n console.log('InscrybMDE: Error. No element was found.');\r\n return;\r\n }\r\n\r\n\r\n // Handle toolbar\r\n if (options.toolbar === undefined) {\r\n // Initialize\r\n options.toolbar = [];\r\n\r\n\r\n // Loop over the built in buttons, to get the preferred order\r\n for (var key in toolbarBuiltInButtons) {\r\n if (toolbarBuiltInButtons.hasOwnProperty(key)) {\r\n if (key.indexOf('separator-') != -1) {\r\n options.toolbar.push('|');\r\n }\r\n\r\n if (toolbarBuiltInButtons[key].default === true || (options.showIcons && options.showIcons.constructor === Array && options.showIcons.indexOf(key) != -1)) {\r\n options.toolbar.push(key);\r\n }\r\n }\r\n }\r\n }\r\n\r\n\r\n // Handle status bar\r\n if (!options.hasOwnProperty('status')) {\r\n options.status = ['autosave', 'lines', 'words', 'cursor'];\r\n }\r\n\r\n\r\n // Add default preview rendering function\r\n if (!options.previewRender) {\r\n options.previewRender = function (plainText) {\r\n // Note: \"this\" refers to the options object\r\n return this.parent.markdown(plainText);\r\n };\r\n }\r\n\r\n\r\n // Set default options for parsing config\r\n options.parsingConfig = extend({\r\n highlightFormatting: true // needed for toggleCodeBlock to detect types of code\r\n }, options.parsingConfig || {});\r\n\r\n\r\n // Merging the insertTexts, with the given options\r\n options.insertTexts = extend({}, insertTexts, options.insertTexts || {});\r\n\r\n\r\n // Merging the promptTexts, with the given options\r\n options.promptTexts = extend({}, promptTexts, options.promptTexts || {});\r\n\r\n\r\n // Merging the blockStyles, with the given options\r\n options.blockStyles = extend({}, blockStyles, options.blockStyles || {});\r\n\r\n\r\n // Merging the shortcuts, with the given options\r\n options.shortcuts = extend({}, shortcuts, options.shortcuts || {});\r\n\r\n options.minHeight = options.minHeight || '300px';\r\n\r\n\r\n // Change unique_id to uniqueId for backwards compatibility\r\n if (options.autosave != undefined && options.autosave.unique_id != undefined && options.autosave.unique_id != '')\r\n options.autosave.uniqueId = options.autosave.unique_id;\r\n\r\n\r\n // Update this options\r\n this.options = options;\r\n\r\n\r\n // Auto render\r\n this.render();\r\n\r\n\r\n // The codemirror component is only available after rendering\r\n // so, the setter for the initialValue can only run after\r\n // the element has been rendered\r\n if (options.initialValue && (!this.options.autosave || this.options.autosave.foundSavedValue !== true)) {\r\n this.value(options.initialValue);\r\n }\r\n}\r\n\r\n/**\r\n * Default markdown render.\r\n */\r\nInscrybMDE.prototype.markdown = function (text) {\r\n if (marked) {\r\n // Initialize\r\n var markedOptions;\r\n if (this.options && this.options.renderingConfig && this.options.renderingConfig.markedOptions) {\r\n markedOptions = this.options.renderingConfig.markedOptions;\r\n } else {\r\n markedOptions = {};\r\n }\r\n\r\n // Update options\r\n if (this.options && this.options.renderingConfig && this.options.renderingConfig.singleLineBreaks === false) {\r\n markedOptions.breaks = false;\r\n } else {\r\n markedOptions.breaks = true;\r\n }\r\n\r\n if (this.options && this.options.renderingConfig && this.options.renderingConfig.codeSyntaxHighlighting === true) {\r\n\r\n /* Get HLJS from config or window */\r\n var hljs = this.options.renderingConfig.hljs || window.hljs;\r\n\r\n /* Check if HLJS loaded */\r\n if (hljs) {\r\n markedOptions.highlight = function (code) {\r\n return hljs.highlightAuto(code).value;\r\n };\r\n }\r\n }\r\n\r\n\r\n // Set options\r\n marked.setOptions(markedOptions);\r\n\r\n\r\n // Return\r\n return marked(text);\r\n }\r\n};\r\n\r\n/**\r\n * Render editor to the given element.\r\n */\r\nInscrybMDE.prototype.render = function (el) {\r\n if (!el) {\r\n el = this.element || document.getElementsByTagName('textarea')[0];\r\n }\r\n\r\n if (this._rendered && this._rendered === el) {\r\n // Already rendered.\r\n return;\r\n }\r\n\r\n this.element = el;\r\n var options = this.options;\r\n\r\n var self = this;\r\n var keyMaps = {};\r\n\r\n for (var key in options.shortcuts) {\r\n // null stands for \"do not bind this command\"\r\n if (options.shortcuts[key] !== null && bindings[key] !== null) {\r\n (function (key) {\r\n keyMaps[fixShortcut(options.shortcuts[key])] = function () {\r\n bindings[key](self);\r\n };\r\n })(key);\r\n }\r\n }\r\n\r\n keyMaps['Enter'] = 'newlineAndIndentContinueMarkdownList';\r\n keyMaps['Tab'] = 'tabAndIndentMarkdownList';\r\n keyMaps['Shift-Tab'] = 'shiftTabAndUnindentMarkdownList';\r\n keyMaps['Esc'] = function (cm) {\r\n if (cm.getOption('fullScreen')) toggleFullScreen(self);\r\n };\r\n\r\n document.addEventListener('keydown', function (e) {\r\n e = e || window.event;\r\n\r\n if (e.keyCode == 27) {\r\n if (self.codemirror.getOption('fullScreen')) toggleFullScreen(self);\r\n }\r\n }, false);\r\n\r\n var mode, backdrop;\r\n if (options.spellChecker !== false) {\r\n mode = 'spell-checker';\r\n backdrop = options.parsingConfig;\r\n backdrop.name = 'gfm';\r\n backdrop.gitHubSpice = false;\r\n\r\n CodeMirrorSpellChecker({\r\n codeMirrorInstance: CodeMirror\r\n });\r\n } else {\r\n mode = options.parsingConfig;\r\n mode.name = 'gfm';\r\n mode.gitHubSpice = false;\r\n }\r\n\r\n this.codemirror = CodeMirror.fromTextArea(el, {\r\n mode: mode,\r\n backdrop: backdrop,\r\n theme: 'paper',\r\n tabSize: (options.tabSize != undefined) ? options.tabSize : 2,\r\n indentUnit: (options.tabSize != undefined) ? options.tabSize : 2,\r\n indentWithTabs: (options.indentWithTabs === false) ? false : true,\r\n lineNumbers: false,\r\n autofocus: (options.autofocus === true) ? true : false,\r\n extraKeys: keyMaps,\r\n lineWrapping: (options.lineWrapping === false) ? false : true,\r\n allowDropFileTypes: ['text/plain'],\r\n placeholder: options.placeholder || el.getAttribute('placeholder') || '',\r\n styleSelectedText: (options.styleSelectedText != undefined) ? options.styleSelectedText : !isMobile(),\r\n inputStyle: (options.inputStyle != undefined) ? options.inputStyle : isMobile() ? 'contenteditable' : 'textarea',\r\n });\r\n\r\n this.codemirror.getScrollerElement().style.minHeight = options.minHeight;\r\n\r\n if (options.forceSync === true) {\r\n var cm = this.codemirror;\r\n cm.on('change', function () {\r\n cm.save();\r\n });\r\n }\r\n\r\n this.gui = {};\r\n\r\n if (options.toolbar !== false) {\r\n this.gui.toolbar = this.createToolbar();\r\n }\r\n if (options.status !== false) {\r\n this.gui.statusbar = this.createStatusbar();\r\n }\r\n if (options.autosave != undefined && options.autosave.enabled === true) {\r\n this.autosave();\r\n }\r\n\r\n this.gui.sideBySide = this.createSideBySide();\r\n\r\n this._rendered = this.element;\r\n\r\n\r\n // Fixes CodeMirror bug (#344)\r\n var temp_cm = this.codemirror;\r\n setTimeout(function () {\r\n temp_cm.refresh();\r\n }.bind(temp_cm), 0);\r\n};\r\n\r\n// Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem throw QuotaExceededError. We're going to detect this and set a variable accordingly.\r\nfunction isLocalStorageAvailable() {\r\n if (typeof localStorage === 'object') {\r\n try {\r\n localStorage.setItem('smde_localStorage', 1);\r\n localStorage.removeItem('smde_localStorage');\r\n } catch (e) {\r\n return false;\r\n }\r\n } else {\r\n return false;\r\n }\r\n\r\n return true;\r\n}\r\n\r\nInscrybMDE.prototype.autosave = function () {\r\n if (isLocalStorageAvailable()) {\r\n var inscrybmde = this;\r\n\r\n if (this.options.autosave.uniqueId == undefined || this.options.autosave.uniqueId == '') {\r\n console.log('InscrybMDE: You must set a uniqueId to use the autosave feature');\r\n return;\r\n }\r\n\r\n if (inscrybmde.element.form != null && inscrybmde.element.form != undefined) {\r\n inscrybmde.element.form.addEventListener('submit', function () {\r\n localStorage.removeItem('smde_' + inscrybmde.options.autosave.uniqueId);\r\n });\r\n }\r\n\r\n if (this.options.autosave.loaded !== true) {\r\n if (typeof localStorage.getItem('smde_' + this.options.autosave.uniqueId) == 'string' && localStorage.getItem('smde_' + this.options.autosave.uniqueId) != '') {\r\n this.codemirror.setValue(localStorage.getItem('smde_' + this.options.autosave.uniqueId));\r\n this.options.autosave.foundSavedValue = true;\r\n }\r\n\r\n this.options.autosave.loaded = true;\r\n }\r\n\r\n localStorage.setItem('smde_' + this.options.autosave.uniqueId, inscrybmde.value());\r\n\r\n if (typeof this.options.autosave.callback === 'function')\r\n this.options.autosave.callback.call(this);\r\n\r\n var el = document.getElementById('autosaved');\r\n if (el != null && el != undefined && el != '') {\r\n var d = new Date();\r\n var hh = d.getHours();\r\n var m = d.getMinutes();\r\n var dd = 'am';\r\n var h = hh;\r\n if (h >= 12) {\r\n h = hh - 12;\r\n dd = 'pm';\r\n }\r\n if (h == 0) {\r\n h = 12;\r\n }\r\n m = m < 10 ? '0' + m : m;\r\n\r\n el.innerHTML = 'Autosaved: ' + h + ':' + m + ' ' + dd;\r\n }\r\n\r\n this.autosaveTimeoutId = setTimeout(function () {\r\n inscrybmde.autosave();\r\n }, this.options.autosave.delay || 10000);\r\n } else {\r\n console.log('InscrybMDE: localStorage not available, cannot autosave');\r\n }\r\n};\r\n\r\nInscrybMDE.prototype.clearAutosavedValue = function () {\r\n if (isLocalStorageAvailable()) {\r\n if (this.options.autosave == undefined || this.options.autosave.uniqueId == undefined || this.options.autosave.uniqueId == '') {\r\n console.log('InscrybMDE: You must set a uniqueId to clear the autosave value');\r\n return;\r\n }\r\n\r\n localStorage.removeItem('smde_' + this.options.autosave.uniqueId);\r\n } else {\r\n console.log('InscrybMDE: localStorage not available, cannot autosave');\r\n }\r\n};\r\n\r\nInscrybMDE.prototype.createSideBySide = function () {\r\n var cm = this.codemirror;\r\n var wrapper = cm.getWrapperElement();\r\n var preview = wrapper.nextSibling;\r\n\r\n if (!preview || !/editor-preview-side/.test(preview.className)) {\r\n preview = document.createElement('div');\r\n preview.className = 'editor-preview-side';\r\n wrapper.parentNode.insertBefore(preview, wrapper.nextSibling);\r\n }\r\n\r\n if (this.options.syncSideBySidePreviewScroll === false) return preview;\r\n // Syncs scroll editor -> preview\r\n var cScroll = false;\r\n var pScroll = false;\r\n cm.on('scroll', function (v) {\r\n if (cScroll) {\r\n cScroll = false;\r\n return;\r\n }\r\n pScroll = true;\r\n var height = v.getScrollInfo().height - v.getScrollInfo().clientHeight;\r\n var ratio = parseFloat(v.getScrollInfo().top) / height;\r\n var move = (preview.scrollHeight - preview.clientHeight) * ratio;\r\n preview.scrollTop = move;\r\n });\r\n\r\n // Syncs scroll preview -> editor\r\n preview.onscroll = function () {\r\n if (pScroll) {\r\n pScroll = false;\r\n return;\r\n }\r\n cScroll = true;\r\n var height = preview.scrollHeight - preview.clientHeight;\r\n var ratio = parseFloat(preview.scrollTop) / height;\r\n var move = (cm.getScrollInfo().height - cm.getScrollInfo().clientHeight) * ratio;\r\n cm.scrollTo(0, move);\r\n };\r\n return preview;\r\n};\r\n\r\nInscrybMDE.prototype.createToolbar = function (items) {\r\n items = items || this.options.toolbar;\r\n\r\n if (!items || items.length === 0) {\r\n return;\r\n }\r\n var i;\r\n for (i = 0; i < items.length; i++) {\r\n if (toolbarBuiltInButtons[items[i]] != undefined) {\r\n items[i] = toolbarBuiltInButtons[items[i]];\r\n }\r\n }\r\n\r\n var bar = document.createElement('div');\r\n bar.className = 'editor-toolbar';\r\n\r\n var self = this;\r\n\r\n var toolbarData = {};\r\n self.toolbar = items;\r\n\r\n for (i = 0; i < items.length; i++) {\r\n if (items[i].name == 'guide' && self.options.toolbarGuideIcon === false)\r\n continue;\r\n\r\n if (self.options.hideIcons && self.options.hideIcons.indexOf(items[i].name) != -1)\r\n continue;\r\n\r\n // Fullscreen does not work well on mobile devices (even tablets)\r\n // In the future, hopefully this can be resolved\r\n if ((items[i].name == 'fullscreen' || items[i].name == 'side-by-side') && isMobile())\r\n continue;\r\n\r\n\r\n // Don't include trailing separators\r\n if (items[i] === '|') {\r\n var nonSeparatorIconsFollow = false;\r\n\r\n for (var x = (i + 1); x < items.length; x++) {\r\n if (items[x] !== '|' && (!self.options.hideIcons || self.options.hideIcons.indexOf(items[x].name) == -1)) {\r\n nonSeparatorIconsFollow = true;\r\n }\r\n }\r\n\r\n if (!nonSeparatorIconsFollow)\r\n continue;\r\n }\r\n\r\n\r\n // Create the icon and append to the toolbar\r\n (function (item) {\r\n var el;\r\n if (item === '|') {\r\n el = createSep();\r\n } else {\r\n el = createIcon(item, self.options.toolbarTips, self.options.shortcuts);\r\n }\r\n\r\n // bind events, special for info\r\n if (item.action) {\r\n if (typeof item.action === 'function') {\r\n el.onclick = function (e) {\r\n e.preventDefault();\r\n item.action(self);\r\n };\r\n } else if (typeof item.action === 'string') {\r\n el.onclick = function (e) {\r\n e.preventDefault();\r\n window.open(item.action, '_blank');\r\n };\r\n }\r\n }\r\n\r\n toolbarData[item.name || item] = el;\r\n bar.appendChild(el);\r\n })(items[i]);\r\n }\r\n\r\n self.toolbarElements = toolbarData;\r\n\r\n var cm = this.codemirror;\r\n cm.on('cursorActivity', function () {\r\n var stat = getState(cm);\r\n\r\n for (var key in toolbarData) {\r\n (function (key) {\r\n var el = toolbarData[key];\r\n if (stat[key]) {\r\n el.className += ' active';\r\n } else if (key != 'fullscreen' && key != 'side-by-side') {\r\n el.className = el.className.replace(/\\s*active\\s*/g, '');\r\n }\r\n })(key);\r\n }\r\n });\r\n\r\n var cmWrapper = cm.getWrapperElement();\r\n cmWrapper.parentNode.insertBefore(bar, cmWrapper);\r\n return bar;\r\n};\r\n\r\nInscrybMDE.prototype.createStatusbar = function (status) {\r\n // Initialize\r\n status = status || this.options.status;\r\n var options = this.options;\r\n var cm = this.codemirror;\r\n\r\n\r\n // Make sure the status variable is valid\r\n if (!status || status.length === 0)\r\n return;\r\n\r\n\r\n // Set up the built-in items\r\n var items = [];\r\n var i, onUpdate, defaultValue;\r\n\r\n for (i = 0; i < status.length; i++) {\r\n // Reset some values\r\n onUpdate = undefined;\r\n defaultValue = undefined;\r\n\r\n\r\n // Handle if custom or not\r\n if (typeof status[i] === 'object') {\r\n items.push({\r\n className: status[i].className,\r\n defaultValue: status[i].defaultValue,\r\n onUpdate: status[i].onUpdate\r\n });\r\n } else {\r\n var name = status[i];\r\n\r\n if (name === 'words') {\r\n defaultValue = function (el) {\r\n el.innerHTML = wordCount(cm.getValue());\r\n };\r\n onUpdate = function (el) {\r\n el.innerHTML = wordCount(cm.getValue());\r\n };\r\n } else if (name === 'lines') {\r\n defaultValue = function (el) {\r\n el.innerHTML = cm.lineCount();\r\n };\r\n onUpdate = function (el) {\r\n el.innerHTML = cm.lineCount();\r\n };\r\n } else if (name === 'cursor') {\r\n defaultValue = function (el) {\r\n el.innerHTML = '0:0';\r\n };\r\n onUpdate = function (el) {\r\n var pos = cm.getCursor();\r\n el.innerHTML = pos.line + ':' + pos.ch;\r\n };\r\n } else if (name === 'autosave') {\r\n defaultValue = function (el) {\r\n if (options.autosave != undefined && options.autosave.enabled === true) {\r\n el.setAttribute('id', 'autosaved');\r\n }\r\n };\r\n }\r\n\r\n items.push({\r\n className: name,\r\n defaultValue: defaultValue,\r\n onUpdate: onUpdate\r\n });\r\n }\r\n }\r\n\r\n\r\n // Create element for the status bar\r\n var bar = document.createElement('div');\r\n bar.className = 'editor-statusbar';\r\n\r\n\r\n // Create a new span for each item\r\n for (i = 0; i < items.length; i++) {\r\n // Store in temporary variable\r\n var item = items[i];\r\n\r\n\r\n // Create span element\r\n var el = document.createElement('span');\r\n el.className = item.className;\r\n\r\n\r\n // Ensure the defaultValue is a function\r\n if (typeof item.defaultValue === 'function') {\r\n item.defaultValue(el);\r\n }\r\n\r\n\r\n // Ensure the onUpdate is a function\r\n if (typeof item.onUpdate === 'function') {\r\n // Create a closure around the span of the current action, then execute the onUpdate handler\r\n this.codemirror.on('update', (function (el, item) {\r\n return function () {\r\n item.onUpdate(el);\r\n };\r\n }(el, item)));\r\n }\r\n\r\n\r\n // Append the item to the status bar\r\n bar.appendChild(el);\r\n }\r\n\r\n\r\n // Insert the status bar into the DOM\r\n var cmWrapper = this.codemirror.getWrapperElement();\r\n cmWrapper.parentNode.insertBefore(bar, cmWrapper.nextSibling);\r\n return bar;\r\n};\r\n\r\n/**\r\n * Get or set the text content.\r\n */\r\nInscrybMDE.prototype.value = function (val) {\r\n var cm = this.codemirror;\r\n if (val === undefined) {\r\n return cm.getValue();\r\n } else {\r\n cm.getDoc().setValue(val);\r\n if (this.isPreviewActive()) {\r\n var wrapper = cm.getWrapperElement();\r\n var preview = wrapper.lastChild;\r\n preview.innerHTML = this.options.previewRender(val, preview);\r\n }\r\n return this;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Bind static methods for exports.\r\n */\r\nInscrybMDE.toggleBold = toggleBold;\r\nInscrybMDE.toggleItalic = toggleItalic;\r\nInscrybMDE.toggleStrikethrough = toggleStrikethrough;\r\nInscrybMDE.toggleBlockquote = toggleBlockquote;\r\nInscrybMDE.toggleHeadingSmaller = toggleHeadingSmaller;\r\nInscrybMDE.toggleHeadingBigger = toggleHeadingBigger;\r\nInscrybMDE.toggleHeading1 = toggleHeading1;\r\nInscrybMDE.toggleHeading2 = toggleHeading2;\r\nInscrybMDE.toggleHeading3 = toggleHeading3;\r\nInscrybMDE.toggleCodeBlock = toggleCodeBlock;\r\nInscrybMDE.toggleUnorderedList = toggleUnorderedList;\r\nInscrybMDE.toggleOrderedList = toggleOrderedList;\r\nInscrybMDE.cleanBlock = cleanBlock;\r\nInscrybMDE.drawLink = drawLink;\r\nInscrybMDE.drawImage = drawImage;\r\nInscrybMDE.drawTable = drawTable;\r\nInscrybMDE.drawHorizontalRule = drawHorizontalRule;\r\nInscrybMDE.undo = undo;\r\nInscrybMDE.redo = redo;\r\nInscrybMDE.togglePreview = togglePreview;\r\nInscrybMDE.toggleSideBySide = toggleSideBySide;\r\nInscrybMDE.toggleFullScreen = toggleFullScreen;\r\n\r\n/**\r\n * Bind instance methods for exports.\r\n */\r\nInscrybMDE.prototype.toggleBold = function () {\r\n toggleBold(this);\r\n};\r\nInscrybMDE.prototype.toggleItalic = function () {\r\n toggleItalic(this);\r\n};\r\nInscrybMDE.prototype.toggleStrikethrough = function () {\r\n toggleStrikethrough(this);\r\n};\r\nInscrybMDE.prototype.toggleBlockquote = function () {\r\n toggleBlockquote(this);\r\n};\r\nInscrybMDE.prototype.toggleHeadingSmaller = function () {\r\n toggleHeadingSmaller(this);\r\n};\r\nInscrybMDE.prototype.toggleHeadingBigger = function () {\r\n toggleHeadingBigger(this);\r\n};\r\nInscrybMDE.prototype.toggleHeading1 = function () {\r\n toggleHeading1(this);\r\n};\r\nInscrybMDE.prototype.toggleHeading2 = function () {\r\n toggleHeading2(this);\r\n};\r\nInscrybMDE.prototype.toggleHeading3 = function () {\r\n toggleHeading3(this);\r\n};\r\nInscrybMDE.prototype.toggleCodeBlock = function () {\r\n toggleCodeBlock(this);\r\n};\r\nInscrybMDE.prototype.toggleUnorderedList = function () {\r\n toggleUnorderedList(this);\r\n};\r\nInscrybMDE.prototype.toggleOrderedList = function () {\r\n toggleOrderedList(this);\r\n};\r\nInscrybMDE.prototype.cleanBlock = function () {\r\n cleanBlock(this);\r\n};\r\nInscrybMDE.prototype.drawLink = function () {\r\n drawLink(this);\r\n};\r\nInscrybMDE.prototype.drawImage = function () {\r\n drawImage(this);\r\n};\r\nInscrybMDE.prototype.drawTable = function () {\r\n drawTable(this);\r\n};\r\nInscrybMDE.prototype.drawHorizontalRule = function () {\r\n drawHorizontalRule(this);\r\n};\r\nInscrybMDE.prototype.undo = function () {\r\n undo(this);\r\n};\r\nInscrybMDE.prototype.redo = function () {\r\n redo(this);\r\n};\r\nInscrybMDE.prototype.togglePreview = function () {\r\n togglePreview(this);\r\n};\r\nInscrybMDE.prototype.toggleSideBySide = function () {\r\n toggleSideBySide(this);\r\n};\r\nInscrybMDE.prototype.toggleFullScreen = function () {\r\n toggleFullScreen(this);\r\n};\r\n\r\nInscrybMDE.prototype.isPreviewActive = function () {\r\n var cm = this.codemirror;\r\n var wrapper = cm.getWrapperElement();\r\n var preview = wrapper.lastChild;\r\n\r\n return /editor-preview-active/.test(preview.className);\r\n};\r\n\r\nInscrybMDE.prototype.isSideBySideActive = function () {\r\n var cm = this.codemirror;\r\n var wrapper = cm.getWrapperElement();\r\n var preview = wrapper.nextSibling;\r\n\r\n return /editor-preview-active-side/.test(preview.className);\r\n};\r\n\r\nInscrybMDE.prototype.isFullscreenActive = function () {\r\n var cm = this.codemirror;\r\n\r\n return cm.getOption('fullScreen');\r\n};\r\n\r\nInscrybMDE.prototype.getState = function () {\r\n var cm = this.codemirror;\r\n\r\n return getState(cm);\r\n};\r\n\r\nInscrybMDE.prototype.toTextArea = function () {\r\n var cm = this.codemirror;\r\n var wrapper = cm.getWrapperElement();\r\n\r\n if (wrapper.parentNode) {\r\n if (this.gui.toolbar) {\r\n wrapper.parentNode.removeChild(this.gui.toolbar);\r\n }\r\n if (this.gui.statusbar) {\r\n wrapper.parentNode.removeChild(this.gui.statusbar);\r\n }\r\n if (this.gui.sideBySide) {\r\n wrapper.parentNode.removeChild(this.gui.sideBySide);\r\n }\r\n }\r\n\r\n cm.toTextArea();\r\n\r\n if (this.autosaveTimeoutId) {\r\n clearTimeout(this.autosaveTimeoutId);\r\n this.autosaveTimeoutId = undefined;\r\n this.clearAutosavedValue();\r\n }\r\n};\r\n\r\nmodule.exports = InscrybMDE;\r\n"],"names":["module","exports","Constructor","hasOwnProperty","Object","prototype","slice","Array","createObject","properties","result","create","extendObject","extend","name","constructor","statics","superConstructor","this","apply","arguments","class_","super_","own","target","sources","property","source","i","length","call","extend_1","Nevis","lite","Utilities","forOwn","object","callback","context","key","hasOwn","leftPad","string","times","padding","Utilities_1","Conversion","europa","options","atLeft","atNoWhiteSpace","atParagraph","buffer","inCodeBlock","inOrderedList","inPreformattedBlock","last","left","listDepth","listIndex","_document","document","_element","_tagName","_window","window","append","appendParagraph","output","clean","replace","replacements","value","replacementsRegExp","test","replaceLeft","defineProperties","get","element","set","tagName","toLowerCase","RegExp","Conversion_1","DOMUtilities_1","isVisible","style","getComputedStyle","getPropertyValue","Option","defaultValue","_defaultValue","defineProperty","Option_1","OptionParser_1","exists","some","option","parse","forEach","Plugin_1","after","conversion","afterAll","before","beforeAll","convert","getTagNames","ServiceManager","_services","getService","service","Error","setService","plugins","serviceManager","Europa","_options","getDefaultBaseUri","html","root","createElement","innerHTML","wrapper","contains","display","appendChild","body","plugin","convertElement","removeChild","trim","convertChildren","nodeType","Node","ELEMENT_NODE","childNodes","TEXT_NODE","nodeValue","release","closeWindow","Plugin","register","tag","use","getName","getWindow","baseUri","Europa_1$2","AnchorPlugin","anchors","anchorMap","href","absolute","getAttribute","index","title","inline","push","BlockQuotePlugin","previousLeft","BreakPlugin","CodePlugin","skipped","previousInCodeBlock","DefinitionTermPlugin","DetailsPlugin","hasAttribute","summary","querySelector","EmphasisPlugin","EmptyPlugin","FramePlugin","previousWindow","contentWindow","HeadingPlugin","level","parseInt","match","heading","HorizontalRulePlugin","ImagePlugin","images","imageMap","src","alternativeText","ListItemPlugin","OrderedListPlugin","previousInOrderedList","previousListIndex","ParagraphPlugin","PreformattedPlugin","previousInPreformattedBlock","QuotePlugin","StrongPlugin","UnorderedListPlugin","BrowserWindowService_1","isCloseable","close","baseURI","factory","e","t","r","n","o","s","id","default","toString","map","concat","join","a","l","d","c","m","enumerable","Symbol","toStringTag","__esModule","bind","p","iterator","isArray","isArrayBuffer","isBuffer","isFormData","FormData","isArrayBufferView","ArrayBuffer","isView","isString","isNumber","isObject","isUndefined","isDate","isFile","isBlob","isFunction","isStream","pipe","isURLSearchParams","URLSearchParams","isStandardBrowserEnv","navigator","product","merge","adapter","XMLHttpRequest","transformRequest","JSON","stringify","transformResponse","timeout","xsrfCookieName","xsrfHeaderName","maxContentLength","validateStatus","headers","common","Accept","btoa","Promise","u","data","f","h","XDomainRequest","url","onprogress","ontimeout","auth","b","username","g","password","Authorization","open","method","toUpperCase","params","paramsSerializer","readyState","status","responseURL","indexOf","getAllResponseHeaders","responseType","response","responseText","statusText","config","request","onerror","y","v","withCredentials","read","setRequestHeader","onDownloadProgress","addEventListener","onUploadProgress","upload","cancelToken","promise","then","abort","send","__CANCEL__","message","I18N","configurable","writable","extension","location","langs","locale","override","TypeError","loaded","processConfig","assign","preloaded","entries","reduce","applyLanguage","init","setCurrent","addLanguage","processFile","getValue","getFallbackValue","values","find","makeSafe","put","current","substring","fromFile","split","loadLang","catch","Axios","Cancel","CancelToken","isCancel","all","spread","readFloatLE","_isBuffer","defaults","interceptors","resolve","unshift","fulfilled","rejected","shift","setTimeout","clearTimeout","run","fun","array","nextTick","browser","env","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","umask","code","encodeURIComponent","toISOString","substr","userAgent","setAttribute","protocol","host","search","hash","hostname","port","pathname","charAt","String","charCodeAt","write","Date","toGMTString","cookie","decodeURIComponent","remove","now","handlers","eject","throwIfRequested","baseURL","reject","reason","token","cancel","attributes","class","insert","singleton","locals","HTMLIFrameElement","contentDocument","head","identifier","base","css","media","sourceMap","references","updater","nonce","nc","keys","filter","Boolean","styleSheet","cssText","createTextNode","insertBefore","removeAttribute","unescape","firstChild","parentNode","atob","splice","clobberingProtection","form","namespaceAttributes","backendOrder","backends","sanitizer","Sanitizer","dompurify","DOMPurify","setConfig","SANITIZE_DOM","ADD_ATTR","fallback","startsWith","includes","implementation","createHTMLDocument","parseHTML","addBack","each","nodeName","parentElement","from","removeAttr","isSupported","sanitize","setHTML","getOwnPropertySymbols","getOwnPropertyDescriptor","getOwnPropertyDescriptors","toPrimitive","propertyIsEnumerable","fbLoaded","js","fbEditors","quill","tinymce","structuredClone","T","className","w","x","type","label","O","HTMLElement","dom","j","events","textContent","content","node","function","undefined","P","k","L","C","E","getElementsByTagName","S","DOMParser","parseFromString","userData","A","R","jQuery","D","dataType","cache","ajax","done","Deferred","when","every","N","rel","attr","appendTo","q","M","F","addEventListeners","attrString","camelCase","capitalize","closest","classList","getContentType","escapeAttr","escapeAttrs","escapeHtml","forceNumber","getScripts","getStyles","hyphenCase","isCached","markup","mobileClass","vendor","opera","nameAttr","parsedHtml","parseXML","removeFromArray","safeAttr","safeAttrName","safename","subtract","trimObj","unique","validAttr","titleCase","firstNumberOrUndefined","splitObject","fn","swapWith","z","B","reverse","H","Event","createEvent","initEvent","$","viewData","userDeclined","modalClosed","modalOpened","formSaved","fieldAdded","fieldRemoved","fieldRendered","fieldEditOpened","fieldEditClosed","stageEmptied","U","I","rawConfig","preview","isPreview","required","Math","floor","random","description","controlConfig","subtype","classConfig","disabled","configure","definition","static","classRegister","error","fbControls","fbControlsLoaded","i18n","mi18n","inactive","icon","build","prerender","render","onRender","_","querySelectorAll","V","disableHTMLLabels","templates","help","noLabel","hidden","field","childElementCount","children","item","isTemplate","layout","processTemplate","for","tooltip","jquery","Q","requireValidOption","nextSibling","getActiveOption","Map","getPreviousOption","selectOption","getNextOption","showList","hideList","isOptionValid","preventDefault","keyCode","focus","blur","removeEventListener","input","autocomplete","click","previousSibling","width","offsetWidth","getElementsByClassName","add","next","prev","val","X","W","super","template","J","G","paragraph","header","Z","K","Y","minSelectionRequired","placeholder","other","toggle","multiple","groupRequired","selected","checked","previousElementSibling","setCustomValidity","prop","endsWith","ee","date","file","te","re","textarea","stopPropagation","ne","editorOptions","height","paste_data_images","toolbar","readonly","Number","majorVersion","lastFormBuilderCopiedTinyMCE","setContent","oe","ie","se","ae","modules","theme","editorConfig","Quill","import","instance","setContents","compose","NATIVE_NAME","ENGLISH_NAME","addOption","allFieldsRemoved","allowMultipleFiles","allowSelect","button","cannotBeEmpty","checkboxGroup","checkbox","checkboxes","clearAllMessage","clear","copy","copyButton","copyButtonTooltip","dateField","descriptionField","devMode","editNames","editorTitle","editXML","enableOther","enableOtherMsg","fieldDeleteWarning","fieldVars","fieldNonEditable","fieldRemoveWarning","fileUpload","formUpdated","getStarted","hide","inlineDesc","labelEmpty","limitRole","mandatory","maxlength","minOptionMessage","multipleFiles","no","noFieldsToClear","number","optionCount","optional","optionLabelPlaceholder","optionValuePlaceholder","optionEmpty","radioGroup","radio","removeMessage","removeOption","reset","richText","roles","rows","save","selectOptions","select","selectColor","selectionsMessage","size","sizes","step","styles","submit","text","textArea","warning","viewJSON","viewXML","yes","le","de","customRegister","templateControlRegister","def","customControl","attrs","getClass","datatype","getRegistered","lookup","ce","layoutTemplates","controls","container","formData","messages","formRendered","noFormData","invalidControl","sanitizerOptions","notify","console","log","success","warn","instanceContainers","parseFormData","loadCustom","templatedControls","Element","appendFormFields","getElementById","dispatchEvent","emptyContainer","lastChild","sanitizeField","getElement","disableInjectedStyle","renderControl","forceTemplate","serializeArray","xml","json","setData","formRender","controlRender","CodeMirror","CodeMirrorSpellChecker","marked","isMac","platform","bindings","toggleBold","toggleItalic","drawLink","toggleHeadingSmaller","toggleHeadingBigger","drawImage","toggleBlockquote","toggleOrderedList","toggleUnorderedList","toggleCodeBlock","togglePreview","toggleStrikethrough","toggleHeading1","toggleHeading2","toggleHeading3","cleanBlock","drawTable","drawHorizontalRule","undo","redo","toggleSideBySide","toggleFullScreen","shortcuts","isMobile","check","fixShortcut","createIcon","enableTooltips","el","action","actionName","getBindingName","createTooltip","noDisable","noMobile","tabIndex","createSep","getState","cm","pos","getCursor","stat","getTokenAt","types","ret","bold","getLine","line","quote","italic","strikethrough","link","image","saved_overflow","editor","codemirror","setOption","getOption","overflow","wrap","getWrapperElement","toolbarElements","fullscreen","toolbarButton","sidebyside","_toggleBlock","blockStyles","fenceCharsToInsert","fencing_line","token_state","state","code_type","line_num","firstTok","lastTok","getLineHandle","ch","indentedCode","fencedChars","block_start","block_end","lineCount","cur_start","cur_end","tok","is_code","start","end","replaceRange","setSelection","start_text","start_line","end_text","end_line","fence_chars","operation","search_from","next_line","next_line_last_tok","indentLine","no_sel_and_starting_of_line","sel_multi","start_line_sel","end_line_sel","repl_start","repl_end","_replaceSelection","insertFencingAtSelection","_toggleLine","_toggleHeading","startPoint","endPoint","_cleanBlock","promptURLs","prompt","promptTexts","insertTexts","table","horizontalRule","useSideBySideListener","previewNormal","toolbar_div","sideBySideRenderingFunction","previewRender","refresh","active","startEnd","getSelection","replaceSelection","direction","currHeadingLevel","listRegexp","whitespacesRegexp","repl","_getChar","_checkChar","char","rt","arr","exec","start_chars","end_chars","_mergeProperties","wordCount","count","toolbarBuiltInButtons","InscrybMDE","parent","autoDownloadFA","autoDownloadFontAwesome","styleSheets","showIcons","plainText","markdown","parsingConfig","highlightFormatting","minHeight","autosave","unique_id","uniqueId","initialValue","foundSavedValue","isLocalStorageAvailable","localStorage","setItem","removeItem","markedOptions","renderingConfig","singleLineBreaks","breaks","codeSyntaxHighlighting","hljs","highlight","highlightAuto","setOptions","_rendered","mode","backdrop","self","keyMaps","event","spellChecker","gitHubSpice","codeMirrorInstance","fromTextArea","tabSize","indentUnit","indentWithTabs","lineNumbers","autofocus","extraKeys","lineWrapping","allowDropFileTypes","styleSelectedText","inputStyle","getScrollerElement","forceSync","gui","createToolbar","statusbar","createStatusbar","enabled","sideBySide","createSideBySide","temp_cm","inscrybmde","getItem","setValue","hh","getHours","getMinutes","dd","autosaveTimeoutId","delay","clearAutosavedValue","syncSideBySidePreviewScroll","cScroll","pScroll","getScrollInfo","clientHeight","ratio","parseFloat","top","move","scrollHeight","scrollTop","onscroll","scrollTo","items","bar","toolbarData","toolbarGuideIcon","hideIcons","nonSeparatorIconsFollow","toolbarTips","onclick","cmWrapper","onUpdate","getDoc","isPreviewActive","isSideBySideActive","isFullscreenActive","toTextArea"],"sourceRoot":""}