+import events from './services/events';
+import httpInstance from './services/http';
+import Translations from './services/translations';
+
+import * as components from './services/components';
+import * as componentMap from './components';
+
// Url retrieval function
window.baseUrl = function(path) {
let basePath = document.querySelector('meta[name="base-url"]').getAttribute('content');
- if (basePath[basePath.length-1] === '/') basePath = basePath.slice(0, basePath.length-1);
+ if (basePath[basePath.length - 1] === '/') basePath = basePath.slice(0, basePath.length - 1);
if (path[0] === '/') path = path.slice(1);
- return basePath + '/' + path;
+ return `${basePath}/${path}`;
};
window.importVersioned = function(moduleName) {
};
// Set events and http services on window
-import events from "./services/events"
-import httpInstance from "./services/http"
window.$http = httpInstance;
window.$events = events;
// Translation setup
-// Creates a global function with name 'trans' to be used in the same way as Laravel's translation system
-import Translations from "./services/translations"
+// Creates a global function with name 'trans' to be used in the same way as the Laravel translation system
const translator = new Translations();
window.trans = translator.get.bind(translator);
window.trans_choice = translator.getPlural.bind(translator);
window.trans_plural = translator.parsePlural.bind(translator);
-// Load Components
-import * as components from "./services/components"
-import * as componentMap from "./components";
+// Load & initialise components
components.register(componentMap);
window.$components = components;
components.init();
-import {EditorView, keymap} from "@codemirror/view";
+import {EditorView, keymap} from '@codemirror/view';
-import {copyTextToClipboard} from "../services/clipboard.js"
-import {viewerExtensions, editorExtensions} from "./setups.js";
-import {createView} from "./views.js";
-import {SimpleEditorInterface} from "./simple-editor-interface.js";
+import {copyTextToClipboard} from '../services/clipboard';
+import {viewerExtensions, editorExtensions} from './setups';
+import {createView} from './views';
+import {SimpleEditorInterface} from './simple-editor-interface';
/**
* Highlight pre elements on a page
*/
function highlightElem(elem) {
const innerCodeElem = elem.querySelector('code[class^=language-]');
- elem.innerHTML = elem.innerHTML.replace(/<br\s*[\/]?>/gi ,'\n');
+ elem.innerHTML = elem.innerHTML.replace(/<br\s*[\/]?>/gi, '\n');
const content = elem.textContent.trimEnd();
let langName = '';
* @param {EditorView} editorView
*/
function addCopyIcon(editorView) {
- const copyIcon = `<svg viewBox="0 0 24 24" width="16" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>`;
- const checkIcon = `<svg viewBox="0 0 24 24" width="16" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>`;
+ const copyIcon = '<svg viewBox="0 0 24 24" width="16" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>';
+ const checkIcon = '<svg viewBox="0 0 24 24" width="16" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>';
const copyButton = document.createElement('button');
- copyButton.setAttribute('type', 'button')
+ copyButton.setAttribute('type', 'button');
copyButton.classList.add('cm-copy-button');
copyButton.innerHTML = copyIcon;
editorView.dom.appendChild(copyButton);
return editor;
}
-
/**
* Create a CodeMirror instance to show in the WYSIWYG pop-up editor
* @param {HTMLElement} elem
doc: content,
extensions: [
...editorExtensions(elem.parentElement),
- EditorView.updateListener.of((v) => {
+ EditorView.updateListener.of(v => {
if (v.docChanged) {
// textArea.value = v.state.doc.toString();
}
doc: content,
extensions: [
...editorExtensions(textArea.parentElement),
- EditorView.updateListener.of((v) => {
+ EditorView.updateListener.of(v => {
if (v.docChanged) {
textArea.value = v.state.doc.toString();
}
extensions: [
keymap.of(keyBindings),
...editorExtensions(elem.parentElement),
- EditorView.updateListener.of((v) => {
+ EditorView.updateListener.of(v => {
onChange(v);
}),
EditorView.domEventHandlers(domEventHandlers),
elem.style.display = 'none';
return ev;
-}
\ No newline at end of file
+}
-import {StreamLanguage} from "@codemirror/language"
+import {StreamLanguage} from '@codemirror/language';
import {css} from '@codemirror/lang-css';
import {json} from '@codemirror/lang-json';
import {javascript} from '@codemirror/lang-javascript';
-import {html} from "@codemirror/lang-html";
+import {html} from '@codemirror/lang-html';
import {markdown} from '@codemirror/lang-markdown';
import {php} from '@codemirror/lang-php';
-import {twig} from "@ssddanbrown/codemirror-lang-twig";
-import {xml} from "@codemirror/lang-xml";
+import {twig} from '@ssddanbrown/codemirror-lang-twig';
+import {xml} from '@codemirror/lang-xml';
-const legacyLoad = async (mode) => {
+const legacyLoad = async mode => {
const modes = await window.importVersioned('legacy-modes');
return StreamLanguage.define(modes[mode]);
};
-
// Mapping of possible languages or formats from user input to their codemirror modes.
// Value can be a mode string or a function that will receive the code content & return the mode string.
// The function option is used in the event the exact mode could be dynamic depending on the code.
pascal: () => legacyLoad('pascal'),
perl: () => legacyLoad('perl'),
pgsql: () => legacyLoad('pgSQL'),
- php: async (code) => {
+ php: async code => {
const hasTags = code.includes('<?php');
return php({plain: !hasTags});
},
}
return language(content);
-}
\ No newline at end of file
+}
-export {c, cpp, csharp, java, kotlin, scala, dart} from '@codemirror/legacy-modes/mode/clike';
+export {
+ c, cpp, csharp, java, kotlin, scala, dart,
+} from '@codemirror/legacy-modes/mode/clike';
export {diff} from '@codemirror/legacy-modes/mode/diff';
export {fortran} from '@codemirror/legacy-modes/mode/fortran';
export {go} from '@codemirror/legacy-modes/mode/go';
export {rust} from '@codemirror/legacy-modes/mode/rust';
export {scheme} from '@codemirror/legacy-modes/mode/scheme';
export {shell} from '@codemirror/legacy-modes/mode/shell';
-export {standardSQL, pgSQL, msSQL, mySQL, sqlite, plSQL} from '@codemirror/legacy-modes/mode/sql';
+export {
+ standardSQL, pgSQL, msSQL, mySQL, sqlite, plSQL,
+} from '@codemirror/legacy-modes/mode/sql';
export {stex} from '@codemirror/legacy-modes/mode/stex';
-export {swift} from "@codemirror/legacy-modes/mode/swift";
+export {swift} from '@codemirror/legacy-modes/mode/swift';
export {toml} from '@codemirror/legacy-modes/mode/toml';
export {vb} from '@codemirror/legacy-modes/mode/vb';
export {vbScript} from '@codemirror/legacy-modes/mode/vbscript';
export {yaml} from '@codemirror/legacy-modes/mode/yaml';
-export {smarty} from "@ssddanbrown/codemirror-lang-smarty";
\ No newline at end of file
+export {smarty} from '@ssddanbrown/codemirror-lang-smarty';
-import {EditorView, keymap, drawSelection, highlightActiveLine, dropCursor,
- rectangularSelection, lineNumbers, highlightActiveLineGutter} from "@codemirror/view"
-import {bracketMatching} from "@codemirror/language"
-import {defaultKeymap, history, historyKeymap, indentWithTab} from "@codemirror/commands"
-import {EditorState} from "@codemirror/state"
-import {getTheme} from "./themes";
+import {
+ EditorView, keymap, drawSelection, highlightActiveLine, dropCursor,
+ rectangularSelection, lineNumbers, highlightActiveLineGutter,
+} from '@codemirror/view';
+import {bracketMatching} from '@codemirror/language';
+import {
+ defaultKeymap, history, historyKeymap, indentWithTab,
+} from '@codemirror/commands';
+import {EditorState} from '@codemirror/state';
+import {getTheme} from './themes';
/**
* @param {Element} parentEl
]),
EditorView.lineWrapping,
];
-}
\ No newline at end of file
+}
-import {updateViewLanguage} from "./views";
-
+import {updateViewLanguage} from './views';
export class SimpleEditorInterface {
+
/**
* @param {EditorView} editorView
*/
* @param content
*/
setContent(content) {
- const doc = this.ev.state.doc;
+ const {doc} = this.ev.state;
this.ev.dispatch({
- changes: {from: 0, to: doc.length, insert: content}
+ changes: {from: 0, to: doc.length, insert: content},
});
}
setMode(mode, content = '') {
updateViewLanguage(this.ev, mode, content);
}
-}
\ No newline at end of file
+
+}
-import {tags} from "@lezer/highlight";
-import {HighlightStyle, syntaxHighlighting} from "@codemirror/language";
-import {EditorView} from "@codemirror/view";
-import {oneDarkHighlightStyle, oneDarkTheme} from "@codemirror/theme-one-dark";
+import {tags} from '@lezer/highlight';
+import {HighlightStyle, syntaxHighlighting} from '@codemirror/language';
+import {EditorView} from '@codemirror/view';
+import {oneDarkHighlightStyle, oneDarkTheme} from '@codemirror/theme-one-dark';
const defaultLightHighlightStyle = HighlightStyle.define([
- { tag: tags.meta,
- color: "#388938" },
- { tag: tags.link,
- textDecoration: "underline" },
- { tag: tags.heading,
- textDecoration: "underline",
- fontWeight: "bold" },
- { tag: tags.emphasis,
- fontStyle: "italic" },
- { tag: tags.strong,
- fontWeight: "bold" },
- { tag: tags.strikethrough,
- textDecoration: "line-through" },
- { tag: tags.keyword,
- color: "#708" },
- { tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName],
- color: "#219" },
- { tag: [tags.literal, tags.inserted],
- color: "#164" },
- { tag: [tags.string, tags.deleted],
- color: "#a11" },
- { tag: [tags.regexp, tags.escape, tags.special(tags.string)],
- color: "#e40" },
- { tag: tags.definition(tags.variableName),
- color: "#00f" },
- { tag: tags.local(tags.variableName),
- color: "#30a" },
- { tag: [tags.typeName, tags.namespace],
- color: "#085" },
- { tag: tags.className,
- color: "#167" },
- { tag: [tags.special(tags.variableName), tags.macroName],
- color: "#256" },
- { tag: tags.definition(tags.propertyName),
- color: "#00c" },
- { tag: tags.compareOperator,
- color: "#708" },
- { tag: tags.comment,
- color: "#940" },
- { tag: tags.invalid,
- color: "#f00" }
+ {
+ tag: tags.meta,
+ color: '#388938',
+ },
+ {
+ tag: tags.link,
+ textDecoration: 'underline',
+ },
+ {
+ tag: tags.heading,
+ textDecoration: 'underline',
+ fontWeight: 'bold',
+ },
+ {
+ tag: tags.emphasis,
+ fontStyle: 'italic',
+ },
+ {
+ tag: tags.strong,
+ fontWeight: 'bold',
+ },
+ {
+ tag: tags.strikethrough,
+ textDecoration: 'line-through',
+ },
+ {
+ tag: tags.keyword,
+ color: '#708',
+ },
+ {
+ tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName],
+ color: '#219',
+ },
+ {
+ tag: [tags.literal, tags.inserted],
+ color: '#164',
+ },
+ {
+ tag: [tags.string, tags.deleted],
+ color: '#a11',
+ },
+ {
+ tag: [tags.regexp, tags.escape, tags.special(tags.string)],
+ color: '#e40',
+ },
+ {
+ tag: tags.definition(tags.variableName),
+ color: '#00f',
+ },
+ {
+ tag: tags.local(tags.variableName),
+ color: '#30a',
+ },
+ {
+ tag: [tags.typeName, tags.namespace],
+ color: '#085',
+ },
+ {
+ tag: tags.className,
+ color: '#167',
+ },
+ {
+ tag: [tags.special(tags.variableName), tags.macroName],
+ color: '#256',
+ },
+ {
+ tag: tags.definition(tags.propertyName),
+ color: '#00c',
+ },
+ {
+ tag: tags.compareOperator,
+ color: '#708',
+ },
+ {
+ tag: tags.comment,
+ color: '#940',
+ },
+ {
+ tag: tags.invalid,
+ color: '#f00',
+ },
]);
const defaultThemeSpec = {
- "&": {
- backgroundColor: "#FFF",
- color: "#000",
+ '&': {
+ backgroundColor: '#FFF',
+ color: '#000',
},
- "&.cm-focused": {
- outline: "none",
+ '&.cm-focused': {
+ outline: 'none',
},
- ".cm-line": {
- lineHeight: "1.6",
+ '.cm-line': {
+ lineHeight: '1.6',
},
};
if (tagStyles.length) {
highlightStyle = HighlightStyle.define(tagStyles);
}
- }
+ },
};
window.$events.emitPublic(viewParentEl, 'library-cm6::configure-theme', eventData);
return [viewTheme, syntaxHighlighting(highlightStyle)];
-}
\ No newline at end of file
+}
-import {Compartment} from "@codemirror/state";
-import {EditorView} from "@codemirror/view";
-import {getLanguageExtension} from "./languages";
+import {Compartment} from '@codemirror/state';
+import {EditorView} from '@codemirror/view';
+import {getLanguageExtension} from './languages';
const viewLangCompartments = new WeakMap();
const language = await getLanguageExtension(modeSuggestion, content);
ev.dispatch({
- effects: compartment.reconfigure(language ? language : [])
+ effects: compartment.reconfigure(language || []),
});
-}
\ No newline at end of file
+}
-import {onChildEvent} from "../services/dom";
-import {uniqueId} from "../services/util";
-import {Component} from "./component";
+import {onChildEvent} from '../services/dom';
+import {uniqueId} from '../services/util';
+import {Component} from './component';
/**
* AddRemoveRows
* Needs a model row to use when adding a new row.
*/
export class AddRemoveRows extends Component {
+
setup() {
this.modelRow = this.$refs.model;
this.addButton = this.$refs.add;
setupListeners() {
this.addButton.addEventListener('click', this.add.bind(this));
- onChildEvent(this.$el, this.removeSelector, 'click', (e) => {
+ onChildEvent(this.$el, this.removeSelector, 'click', e => {
const row = e.target.closest(this.rowSelector);
row.remove();
});
*/
setClonedInputNames(clone) {
const rowId = uniqueId();
- const randRowIdElems = clone.querySelectorAll(`[name*="randrowid"]`);
+ const randRowIdElems = clone.querySelectorAll('[name*="randrowid"]');
for (const elem of randRowIdElems) {
elem.name = elem.name.split('randrowid').join(rowId);
}
}
-}
\ No newline at end of file
+
+}
-import {onSelect} from "../services/dom";
-import {Component} from "./component";
+import {onSelect} from '../services/dom';
+import {Component} from './component';
export class AjaxDeleteRow extends Component {
+
setup() {
this.row = this.$el;
this.url = this.$opts.url;
this.row.style.pointerEvents = null;
});
}
-}
\ No newline at end of file
+
+}
-import {onEnterPress, onSelect} from "../services/dom";
-import {Component} from "./component";
+import {onEnterPress, onSelect} from '../services/dom';
+import {Component} from './component';
/**
* Ajax Form
* otherwise will act as a fake form element.
*/
export class AjaxForm extends Component {
+
setup() {
this.container = this.$el;
this.responseContainer = this.container;
}
setupListeners() {
-
if (this.container.tagName === 'FORM') {
this.container.addEventListener('submit', this.submitRealForm.bind(this));
return;
submitFakeForm() {
const fd = new FormData();
- const inputs = this.container.querySelectorAll(`[name]`);
+ const inputs = this.container.querySelectorAll('[name]');
for (const input of inputs) {
fd.append(input.getAttribute('name'), input.value);
}
this.responseContainer.style.pointerEvents = null;
}
-}
\ No newline at end of file
+}
-import {Component} from "./component";
+import {Component} from './component';
/**
* Attachments List
}
setupListeners() {
- const isExpectedKey = (event) => event.key === 'Control' || event.key === 'Meta';
+ const isExpectedKey = event => event.key === 'Control' || event.key === 'Meta';
window.addEventListener('keydown', event => {
- if (isExpectedKey(event)) {
+ if (isExpectedKey(event)) {
this.addOpenQueryToLinks();
- }
+ }
}, {passive: true});
window.addEventListener('keyup', event => {
if (isExpectedKey(event)) {
const links = this.container.querySelectorAll('a.attachment-file');
for (const link of links) {
if (link.href.split('?')[1] !== 'open=true') {
- link.href = link.href + '?open=true';
+ link.href += '?open=true';
link.setAttribute('target', '_blank');
}
}
link.removeAttribute('target');
}
}
-}
\ No newline at end of file
+
+}
-import {showLoading} from "../services/dom";
-import {Component} from "./component";
+import {showLoading} from '../services/dom';
+import {Component} from './component';
export class Attachments extends Component {
this.listContainer.classList.remove('hidden');
}
-}
\ No newline at end of file
+}
-import {Component} from "./component";
+import {Component} from './component';
export class AutoSubmit extends Component {
this.form.submit();
}
-}
\ No newline at end of file
+}
-import {escapeHtml} from "../services/util";
-import {onChildEvent} from "../services/dom";
-import {Component} from "./component";
-import {KeyboardNavigationHandler} from "../services/keyboard-navigation";
+import {escapeHtml} from '../services/util';
+import {onChildEvent} from '../services/dom';
+import {Component} from './component';
+import {KeyboardNavigationHandler} from '../services/keyboard-navigation';
const ajaxCache = {};
* AutoSuggest
*/
export class AutoSuggest extends Component {
+
setup() {
this.parent = this.$el.parentElement;
this.container = this.$el;
const search = this.input.value.toLowerCase();
const suggestions = await this.loadSuggestions(search, nameFilter);
- const toShow = suggestions.filter(val => {
- return search === '' || val.toLowerCase().startsWith(search);
- }).slice(0, 10);
+ const toShow = suggestions.filter(val => search === '' || val.toLowerCase().startsWith(search)).slice(0, 10);
this.displaySuggestions(toShow);
}
this.hideSuggestions();
}
}
-}
\ No newline at end of file
+
+}
-import {Component} from "./component";
+import {Component} from './component';
export class BackToTop extends Component {
}
onPageScroll() {
- let scrollTopPos = document.documentElement.scrollTop || document.body.scrollTop || 0;
+ const scrollTopPos = document.documentElement.scrollTop || document.body.scrollTop || 0;
if (!this.showing && scrollTopPos > this.breakPoint) {
this.button.style.display = 'block';
this.showing = true;
}
scrollToTop() {
- let targetTop = this.targetElem.getBoundingClientRect().top;
- let scrollElem = document.documentElement.scrollTop ? document.documentElement : document.body;
- let duration = 300;
- let start = Date.now();
- let scrollStart = this.targetElem.getBoundingClientRect().top;
+ const targetTop = this.targetElem.getBoundingClientRect().top;
+ const scrollElem = document.documentElement.scrollTop ? document.documentElement : document.body;
+ const duration = 300;
+ const start = Date.now();
+ const scrollStart = this.targetElem.getBoundingClientRect().top;
function setPos() {
- let percentComplete = (1-((Date.now() - start) / duration));
- let target = Math.abs(percentComplete * scrollStart);
+ const percentComplete = (1 - ((Date.now() - start) / duration));
+ const target = Math.abs(percentComplete * scrollStart);
if (percentComplete > 0) {
scrollElem.scrollTop = target;
requestAnimationFrame(setPos.bind(this));
requestAnimationFrame(setPos.bind(this));
}
-}
\ No newline at end of file
+}
-import Sortable, {MultiDrag} from "sortablejs";
-import {Component} from "./component";
-import {htmlToDom} from "../services/dom";
+import Sortable, {MultiDrag} from 'sortablejs';
+import {Component} from './component';
+import {htmlToDom} from '../services/dom';
// Auto sort control
const sortOperations = {
- name: function(a, b) {
+ name(a, b) {
const aName = a.getAttribute('data-name').trim().toLowerCase();
const bName = b.getAttribute('data-name').trim().toLowerCase();
return aName.localeCompare(bName);
},
- created: function(a, b) {
+ created(a, b) {
const aTime = Number(a.getAttribute('data-created'));
const bTime = Number(b.getAttribute('data-created'));
return bTime - aTime;
},
- updated: function(a, b) {
+ updated(a, b) {
const aTime = Number(a.getAttribute('data-updated'));
const bTime = Number(b.getAttribute('data-updated'));
return bTime - aTime;
},
- chaptersFirst: function(a, b) {
+ chaptersFirst(a, b) {
const aType = a.getAttribute('data-type');
const bType = b.getAttribute('data-type');
if (aType === bType) {
}
return (aType === 'chapter' ? -1 : 1);
},
- chaptersLast: function(a, b) {
+ chaptersLast(a, b) {
const aType = a.getAttribute('data-type');
const bType = b.getAttribute('data-type');
if (aType === bType) {
run(elem, parent, book) {
const newSibling = elem.previousElementSibling || parent;
newSibling.insertAdjacentElement('beforebegin', elem);
- }
+ },
},
down: {
active(elem, parent, book) {
run(elem, parent, book) {
const newSibling = elem.nextElementSibling || parent;
newSibling.insertAdjacentElement('afterend', elem);
- }
+ },
},
next_book: {
active(elem, parent, book) {
run(elem, parent, book) {
const newList = book.nextElementSibling.querySelector('ul');
newList.prepend(elem);
- }
+ },
},
prev_book: {
active(elem, parent, book) {
run(elem, parent, book) {
const newList = book.previousElementSibling.querySelector('ul');
newList.appendChild(elem);
- }
+ },
},
next_chapter: {
active(elem, parent, book) {
const topItems = Array.from(topLevel.parentElement.children);
const index = topItems.indexOf(topLevel);
return topItems.slice(index + 1).find(elem => elem.dataset.type === 'chapter');
- }
+ },
},
prev_chapter: {
active(elem, parent, book) {
const topItems = Array.from(topLevel.parentElement.children);
const index = topItems.indexOf(topLevel);
return topItems.slice(0, index).reverse().find(elem => elem.dataset.type === 'chapter');
- }
+ },
},
book_end: {
active(elem, parent, book) {
},
run(elem, parent, book) {
book.querySelector('ul').append(elem);
- }
+ },
},
book_start: {
active(elem, parent, book) {
},
run(elem, parent, book) {
book.querySelector('ul').prepend(elem);
- }
+ },
},
before_chapter: {
active(elem, parent, book) {
},
run(elem, parent, book) {
parent.insertAdjacentElement('beforebegin', elem);
- }
+ },
},
after_chapter: {
active(elem, parent, book) {
},
run(elem, parent, book) {
parent.insertAdjacentElement('afterend', elem);
- }
+ },
},
};
let sortFunction = sortOperations[sort];
if (reverse && reversibleTypes.includes(sort)) {
sortFunction = function(a, b) {
- return 0 - sortOperations[sort](a, b)
+ return 0 - sortOperations[sort](a, b);
};
}
- for (let list of sortLists) {
+ for (const list of sortLists) {
const directItems = Array.from(list.children).filter(child => child.matches('li'));
directItems.sort(sortFunction).forEach(sortedItem => {
list.appendChild(sortedItem);
const alreadyAdded = this.container.querySelector(`[data-type="book"][data-id="${entityInfo.id}"]`) !== null;
if (alreadyAdded) return;
- const entitySortItemUrl = entityInfo.link + '/sort-item';
+ const entitySortItemUrl = `${entityInfo.link}/sort-item`;
window.$http.get(entitySortItemUrl).then(resp => {
const newBookContainer = htmlToDom(resp.data);
this.sortContainer.append(newBookContainer);
const chapterGroupConfig = {
name: 'chapter',
pull: ['book', 'chapter'],
- put: function(toList, fromList, draggedElem) {
+ put(toList, fromList, draggedElem) {
return draggedElem.getAttribute('data-type') === 'page';
- }
+ },
};
for (const sortElem of sortElems) {
animation: 150,
fallbackOnBody: true,
swapThreshold: 0.65,
- onSort: (event) => {
- this.ensureNoNestedChapters()
+ onSort: event => {
+ this.ensureNoNestedChapters();
this.updateMapInput();
this.updateMoveActionStateForAll();
},
const entityMap = [];
const lists = this.container.querySelectorAll('.sort-list');
- for (let list of lists) {
+ for (const list of lists) {
const bookId = list.closest('[data-type="book"]').getAttribute('data-id');
const directChildren = Array.from(list.children)
.filter(elem => elem.matches('[data-type="page"], [data-type="chapter"]'));
entityMap.push({
id: childId,
sort: index,
- parentChapter: parentChapter,
- type: type,
- book: bookId
+ parentChapter,
+ type,
+ book: bookId,
});
const subPages = childElem.querySelectorAll('[data-type="page"]');
sort: i,
parentChapter: childId,
type: 'page',
- book: bookId
+ book: bookId,
});
}
}
this.updateMoveActionState(item);
}
}
-}
\ No newline at end of file
+
+}
-import {slideUp, slideDown} from "../services/animations";
-import {Component} from "./component";
+import {slideUp, slideDown} from '../services/animations';
+import {Component} from './component';
export class ChapterContents extends Component {
click(event) {
event.preventDefault();
- this.isOpen ? this.close() : this.open();
+ this.isOpen ? this.close() : this.open();
}
+
}
-import {onChildEvent, onEnterPress, onSelect} from "../services/dom";
-import {Component} from "./component";
-
+import {onChildEvent, onEnterPress, onSelect} from '../services/dom';
+import {Component} from './component';
export class CodeEditor extends Component {
editor = null;
callback = null;
+
history = {};
+
historyKey = 'code_history';
setup() {
button.setAttribute('data-favourite', isFavorite ? 'true' : 'false');
window.$http.patch('/preferences/update-code-language-favourite', {
- language: language,
- active: isFavorite
+ language,
+ active: isFavorite,
});
this.sortLanguageList();
if (isFavorite) {
- button.scrollIntoView({block: "center", behavior: "smooth"});
+ button.scrollIntoView({block: 'center', behavior: 'smooth'});
}
});
}
if (aFav && !bFav) {
return -1;
- } else if (bFav && !aFav) {
+ } if (bFav && !aFav) {
return 1;
}
this.getPopup().show(() => {
this.editor.focus();
}, () => {
- this.addHistory()
+ this.addHistory();
});
}
const isMatch = inputLang === lang;
link.classList.toggle('active', isMatch);
if (isMatch) {
- link.scrollIntoView({block: "center", behavior: "smooth"});
+ link.scrollIntoView({block: 'center', behavior: 'smooth'});
}
}
}
const historyKeys = Object.keys(this.history).reverse();
this.historyDropDown.classList.toggle('hidden', historyKeys.length === 0);
this.historyList.innerHTML = historyKeys.map(key => {
- const localTime = (new Date(parseInt(key))).toLocaleTimeString();
- return `<li><button type="button" data-time="${key}" class="text-item">${localTime}</button></li>`;
+ const localTime = (new Date(parseInt(key))).toLocaleTimeString();
+ return `<li><button type="button" data-time="${key}" class="text-item">${localTime}</button></li>`;
}).join('');
}
window.sessionStorage.setItem(this.historyKey, historyString);
}
-}
\ No newline at end of file
+}
-import {Component} from "./component";
+import {Component} from './component';
-export class CodeHighlighter extends Component{
+export class CodeHighlighter extends Component {
setup() {
const container = this.$el;
const codeBlocks = container.querySelectorAll('pre');
if (codeBlocks.length > 0) {
window.importVersioned('code').then(Code => {
- Code.highlightWithin(container);
+ Code.highlightWithin(container);
});
}
}
-}
\ No newline at end of file
+}
* A simple component to render a code editor within the textarea
* this exists upon.
*/
-import {Component} from "./component";
+import {Component} from './component';
export class CodeTextarea extends Component {
async setup() {
- const mode = this.$opts.mode;
+ const {mode} = this.$opts;
const Code = await window.importVersioned('code');
Code.inlineEditor(this.$el, mode);
}
-}
\ No newline at end of file
+}
-import {slideDown, slideUp} from "../services/animations";
-import {Component} from "./component";
+import {slideDown, slideUp} from '../services/animations';
+import {Component} from './component';
/**
* Collapsible
}
}
-}
\ No newline at end of file
+}
const componentName = this.$name;
const event = new CustomEvent(`${componentName}-${eventName}`, {
bubbles: true,
- detail: data
+ detail: data,
});
this.$el.dispatchEvent(event);
}
-}
\ No newline at end of file
+
+}
-import {onSelect} from "../services/dom";
-import {Component} from "./component";
+import {onSelect} from '../services/dom';
+import {Component} from './component';
/**
* Custom equivalent of window.confirm() using our popup component.
});
return new Promise((res, rej) => {
- this.res = res;
+ this.res = res;
});
}
*/
sendResult(result) {
if (this.res) {
- this.res(result)
+ this.res(result);
this.res = null;
}
}
-}
\ No newline at end of file
+}
-import {Component} from "./component";
+import {Component} from './component';
export class CustomCheckbox extends Component {
this.display.setAttribute('aria-checked', checked);
}
-}
\ No newline at end of file
+}
-import {Component} from "./component";
+import {Component} from './component';
export class DetailsHighlighter extends Component {
}
this.dealtWith = true;
}
-}
\ No newline at end of file
+
+}
-import {debounce} from "../services/util";
-import {transitionHeight} from "../services/animations";
-import {Component} from "./component";
+import {debounce} from '../services/util';
+import {transitionHeight} from '../services/animations';
+import {Component} from './component';
export class DropdownSearch extends Component {
runLocalSearch(searchTerm) {
const listItems = this.listContainerElem.querySelectorAll(this.localSearchSelector);
- for (let listItem of listItems) {
+ for (const listItem of listItems) {
const match = !searchTerm || listItem.textContent.toLowerCase().includes(searchTerm);
listItem.style.display = match ? 'flex' : 'none';
listItem.classList.toggle('hidden', !match);
this.loadingElem.style.display = show ? 'block' : 'none';
}
-}
\ No newline at end of file
+}
-import {onSelect} from "../services/dom";
-import {KeyboardNavigationHandler} from "../services/keyboard-navigation";
-import {Component} from "./component";
+import {onSelect} from '../services/dom';
+import {KeyboardNavigationHandler} from '../services/keyboard-navigation';
+import {Component} from './component';
/**
* Dropdown
this.menu.style.position = 'fixed';
this.menu.style.width = `${menuOriginalRect.width}px`;
this.menu.style.left = `${menuOriginalRect.left}px`;
- heightOffset = dropUpwards ? (window.innerHeight - menuOriginalRect.top - toggleHeight / 2) : menuOriginalRect.top;
+ heightOffset = dropUpwards ? (window.innerHeight - menuOriginalRect.top - toggleHeight / 2) : menuOriginalRect.top;
}
// Adjust menu to display upwards if near the bottom of the screen
}
hideAll() {
- for (let dropdown of window.$components.get('dropdown')) {
+ for (const dropdown of window.$components.get('dropdown')) {
dropdown.hide();
}
}
}
setupListeners() {
- const keyboardNavHandler = new KeyboardNavigationHandler(this.container, (event) => {
+ const keyboardNavHandler = new KeyboardNavigationHandler(this.container, event => {
this.hide();
this.toggle.focus();
if (!this.bubbleEscapes) {
event.stopPropagation();
}
- }, (event) => {
+ }, event => {
if (event.target.nodeName === 'INPUT') {
event.preventDefault();
event.stopPropagation();
// Hide menu on option click
this.container.addEventListener('click', event => {
- const possibleChildren = Array.from(this.menu.querySelectorAll('a'));
- if (possibleChildren.includes(event.target)) {
- this.hide();
- }
+ const possibleChildren = Array.from(this.menu.querySelectorAll('a'));
+ if (possibleChildren.includes(event.target)) {
+ this.hide();
+ }
});
onSelect(this.toggle, event => {
-import DropZoneLib from "dropzone";
-import {fadeOut} from "../services/animations";
-import {Component} from "./component";
+import DropZoneLib from 'dropzone';
+import {fadeOut} from '../services/animations';
+import {Component} from './component';
export class Dropzone extends Component {
+
setup() {
this.container = this.$el;
this.url = this.$opts.url;
this.dz.on('sending', _this.onSending.bind(_this));
this.dz.on('success', _this.onSuccess.bind(_this));
this.dz.on('error', _this.onError.bind(_this));
- }
+ },
});
}
onSending(file, xhr, data) {
-
const token = window.document.querySelector('meta[name=token]').getAttribute('content');
data.append('_token', token);
- xhr.ontimeout = (e) => {
+ xhr.ontimeout = e => {
this.dz.emit('complete', file);
this.dz.emit('error', file, this.timeoutMessage);
- }
+ };
}
onSuccess(file, data) {
onError(file, errorMessage, xhr) {
this.$emit('error', {file, errorMessage, xhr});
- const setMessage = (message) => {
+ const setMessage = message => {
const messsageEl = file.previewElement.querySelector('[data-dz-errormessage]');
messsageEl.textContent = message;
- }
+ };
if (xhr && xhr.status === 413) {
setMessage(this.uploadLimitMessage);
removeAll() {
this.dz.removeAllFiles(true);
}
-}
\ No newline at end of file
+
+}
-import {Component} from "./component";
+import {Component} from './component';
export class EditorToolbox extends Component {
}
setActiveTab(tabName, openToolbox = false) {
-
// Set button visibility
for (const button of this.buttons) {
button.classList.remove('active');
- const bName = button.dataset.tab;
+ const bName = button.dataset.tab;
if (bName === tabName) button.classList.add('active');
}
}
}
-}
\ No newline at end of file
+}
-import {htmlToDom} from "../services/dom";
-import {Component} from "./component";
+import {htmlToDom} from '../services/dom';
+import {Component} from './component';
export class EntityPermissions extends Component {
this.container.addEventListener('click', event => {
const button = event.target.closest('button');
if (button && button.dataset.roleId) {
- this.removeRowOnButtonClick(button)
+ this.removeRowOnButtonClick(button);
}
});
removeRowOnButtonClick(button) {
const row = button.closest('.item-list-row');
- const roleId = button.dataset.roleId;
- const roleName = button.dataset.roleName;
+ const {roleId} = button.dataset;
+ const {roleName} = button.dataset;
const option = document.createElement('option');
option.value = roleId;
row.remove();
}
-}
\ No newline at end of file
+}
-import {onSelect} from "../services/dom";
-import {Component} from "./component";
+import {onSelect} from '../services/dom';
+import {Component} from './component';
export class EntitySearch extends Component {
+
setup() {
this.entityId = this.$opts.entityId;
this.entityType = this.$opts.entityType;
this.loadingBlock.classList.add('hidden');
this.searchInput.value = '';
}
-}
\ No newline at end of file
+
+}
-import {Component} from "./component";
+import {Component} from './component';
export class EntitySelectorPopup extends Component {
this.getSelector().reset();
if (this.callback && entity) this.callback(entity);
}
-}
\ No newline at end of file
+
+}
-import {onChildEvent} from "../services/dom";
-import {Component} from "./component";
+import {onChildEvent} from '../services/dom';
+import {Component} from './component';
/**
* Entity Selector
if (e.code === 'ArrowDown') {
this.focusAdjacent(true);
}
- })
+ });
}
focusAdjacent(forward = true) {
const items = Array.from(this.resultsContainer.querySelectorAll('[data-entity-type]'));
const selectedIndex = items.indexOf(document.activeElement);
- const newItem = items[selectedIndex+ (forward ? 1 : -1)] || items[0];
+ const newItem = items[selectedIndex + (forward ? 1 : -1)] || items[0];
if (newItem) {
newItem.focus();
}
window.$http.get(this.searchUrl()).then(resp => {
this.resultsContainer.innerHTML = resp.data;
this.hideLoading();
- })
+ });
}
searchUrl() {
const link = item.getAttribute('href');
const name = item.querySelector('.entity-list-item-name').textContent;
- const data = {id: Number(id), name: name, link: link};
+ const data = {id: Number(id), name, link};
if (isSelected) {
item.classList.add('selected');
this.selectedItemData = data;
} else {
- window.$events.emit('entity-select-change', null)
+ window.$events.emit('entity-select-change', null);
}
if (!isDblClick && !isSelected) return;
this.confirmSelection(data);
}
if (isSelected) {
- window.$events.emit('entity-select-change', data)
+ window.$events.emit('entity-select-change', data);
}
}
this.selectedItemData = null;
}
-}
\ No newline at end of file
+}
-import {onSelect} from "../services/dom";
-import {Component} from "./component";
+import {onSelect} from '../services/dom';
+import {Component} from './component';
/**
* EventEmitSelect
* All options will be set as the "detail" of the event with
* their values included.
*/
-export class EventEmitSelect extends Component{
+export class EventEmitSelect extends Component {
+
setup() {
this.container = this.$el;
this.name = this.$opts.name;
-
onSelect(this.$el, () => {
this.$emit(this.name, this.$opts);
});
}
-}
\ No newline at end of file
+}
-import {slideUp, slideDown} from "../services/animations";
-import {Component} from "./component";
+import {slideUp, slideDown} from '../services/animations';
+import {Component} from './component';
export class ExpandToggle extends Component {
event.preventDefault();
const matchingElems = document.querySelectorAll(this.targetSelector);
- for (let match of matchingElems) {
- this.isOpen ? this.close(match) : this.open(match);
+ for (const match of matchingElems) {
+ this.isOpen ? this.close(match) : this.open(match);
}
this.isOpen = !this.isOpen;
updateSystemAjax(isOpen) {
window.$http.patch(this.updateEndpoint, {
- expand: isOpen ? 'true' : 'false'
+ expand: isOpen ? 'true' : 'false',
});
}
-}
\ No newline at end of file
+}
-import {htmlToDom} from "../services/dom";
-import {debounce} from "../services/util";
-import {KeyboardNavigationHandler} from "../services/keyboard-navigation";
-import {Component} from "./component";
+import {htmlToDom} from '../services/dom';
+import {debounce} from '../services/util';
+import {KeyboardNavigationHandler} from '../services/keyboard-navigation';
+import {Component} from './component';
/**
* Global (header) search box handling.
// Handle search input changes
this.input.addEventListener('input', () => {
- const value = this.input.value;
+ const {value} = this.input;
if (value.length > 0) {
this.loadingWrap.style.display = 'block';
this.suggestionResultsWrap.style.opacity = '0.5';
updateSuggestionsDebounced(value);
- } else {
+ } else {
this.hideSuggestions();
}
});
if (!this.input.value) {
return;
}
-
+
const resultDom = htmlToDom(results);
this.suggestionResultsWrap.innerHTML = '';
this.container.classList.add('search-active');
window.requestAnimationFrame(() => {
this.suggestions.classList.add('search-suggestions-animation');
- })
+ });
}
hideSuggestions() {
this.suggestions.classList.remove('search-suggestions-animation');
this.suggestionResultsWrap.innerHTML = '';
}
-}
\ No newline at end of file
+
+}
-import {Component} from "./component";
+import {Component} from './component';
export class HeaderMobileToggle extends Component {
this.toggleButton.setAttribute('aria-expanded', this.open ? 'true' : 'false');
if (this.open) {
this.elem.addEventListener('keydown', this.onKeyDown);
- window.addEventListener('click', this.onWindowClick)
+ window.addEventListener('click', this.onWindowClick);
} else {
this.elem.removeEventListener('keydown', this.onKeyDown);
- window.removeEventListener('click', this.onWindowClick)
+ window.removeEventListener('click', this.onWindowClick);
}
event.stopPropagation();
}
this.onToggle(event);
}
-}
\ No newline at end of file
+}
-import {onChildEvent, onSelect, removeLoading, showLoading} from "../services/dom";
-import {Component} from "./component";
+import {
+ onChildEvent, onSelect, removeLoading, showLoading,
+} from '../services/dom';
+import {Component} from './component';
export class ImageManager extends Component {
window.$components.init(this.formContainer);
}
-}
\ No newline at end of file
+}
-import {Component} from "./component";
+import {Component} from './component';
export class ImagePicker extends Component {
this.removeInput.setAttribute('disabled', 'disabled');
}
- for (let file of this.imageInput.files) {
+ for (const file of this.imageInput.files) {
this.imageElem.src = window.URL.createObjectURL(file);
}
this.imageElem.classList.remove('none');
this.resetInput.setAttribute('disabled', 'disabled');
}
-}
\ No newline at end of file
+}
-export {AddRemoveRows} from "./add-remove-rows.js"
-export {AjaxDeleteRow} from "./ajax-delete-row.js"
-export {AjaxForm} from "./ajax-form.js"
-export {Attachments} from "./attachments.js"
-export {AttachmentsList} from "./attachments-list.js"
-export {AutoSuggest} from "./auto-suggest.js"
-export {AutoSubmit} from "./auto-submit.js"
-export {BackToTop} from "./back-to-top.js"
-export {BookSort} from "./book-sort.js"
-export {ChapterContents} from "./chapter-contents.js"
-export {CodeEditor} from "./code-editor.js"
-export {CodeHighlighter} from "./code-highlighter.js"
-export {CodeTextarea} from "./code-textarea.js"
-export {Collapsible} from "./collapsible.js"
-export {ConfirmDialog} from "./confirm-dialog"
-export {CustomCheckbox} from "./custom-checkbox.js"
-export {DetailsHighlighter} from "./details-highlighter.js"
-export {Dropdown} from "./dropdown.js"
-export {DropdownSearch} from "./dropdown-search.js"
-export {Dropzone} from "./dropzone.js"
-export {EditorToolbox} from "./editor-toolbox.js"
-export {EntityPermissions} from "./entity-permissions"
-export {EntitySearch} from "./entity-search.js"
-export {EntitySelector} from "./entity-selector.js"
-export {EntitySelectorPopup} from "./entity-selector-popup.js"
-export {EventEmitSelect} from "./event-emit-select.js"
-export {ExpandToggle} from "./expand-toggle.js"
-export {GlobalSearch} from "./global-search.js"
-export {HeaderMobileToggle} from "./header-mobile-toggle.js"
-export {ImageManager} from "./image-manager.js"
-export {ImagePicker} from "./image-picker.js"
-export {ListSortControl} from "./list-sort-control.js"
-export {MarkdownEditor} from "./markdown-editor.js"
-export {NewUserPassword} from "./new-user-password.js"
-export {Notification} from "./notification.js"
-export {OptionalInput} from "./optional-input.js"
-export {PageComments} from "./page-comments.js"
-export {PageDisplay} from "./page-display.js"
-export {PageEditor} from "./page-editor.js"
-export {PagePicker} from "./page-picker.js"
-export {PermissionsTable} from "./permissions-table.js"
-export {Pointer} from "./pointer.js"
-export {Popup} from "./popup.js"
-export {SettingAppColorScheme} from "./setting-app-color-scheme.js"
-export {SettingColorPicker} from "./setting-color-picker.js"
-export {SettingHomepageControl} from "./setting-homepage-control.js"
-export {ShelfSort} from "./shelf-sort.js"
-export {Shortcuts} from "./shortcuts"
-export {ShortcutInput} from "./shortcut-input"
-export {SortableList} from "./sortable-list.js"
-export {SubmitOnChange} from "./submit-on-change.js"
-export {Tabs} from "./tabs.js"
-export {TagManager} from "./tag-manager.js"
-export {TemplateManager} from "./template-manager.js"
-export {ToggleSwitch} from "./toggle-switch.js"
-export {TriLayout} from "./tri-layout.js"
-export {UserSelect} from "./user-select.js"
-export {WebhookEvents} from "./webhook-events"
-export {WysiwygEditor} from "./wysiwyg-editor.js"
+export {AddRemoveRows} from './add-remove-rows.js';
+export {AjaxDeleteRow} from './ajax-delete-row.js';
+export {AjaxForm} from './ajax-form.js';
+export {Attachments} from './attachments.js';
+export {AttachmentsList} from './attachments-list.js';
+export {AutoSuggest} from './auto-suggest.js';
+export {AutoSubmit} from './auto-submit.js';
+export {BackToTop} from './back-to-top.js';
+export {BookSort} from './book-sort.js';
+export {ChapterContents} from './chapter-contents.js';
+export {CodeEditor} from './code-editor.js';
+export {CodeHighlighter} from './code-highlighter.js';
+export {CodeTextarea} from './code-textarea.js';
+export {Collapsible} from './collapsible.js';
+export {ConfirmDialog} from './confirm-dialog';
+export {CustomCheckbox} from './custom-checkbox.js';
+export {DetailsHighlighter} from './details-highlighter.js';
+export {Dropdown} from './dropdown.js';
+export {DropdownSearch} from './dropdown-search.js';
+export {Dropzone} from './dropzone.js';
+export {EditorToolbox} from './editor-toolbox.js';
+export {EntityPermissions} from './entity-permissions';
+export {EntitySearch} from './entity-search.js';
+export {EntitySelector} from './entity-selector.js';
+export {EntitySelectorPopup} from './entity-selector-popup.js';
+export {EventEmitSelect} from './event-emit-select.js';
+export {ExpandToggle} from './expand-toggle.js';
+export {GlobalSearch} from './global-search.js';
+export {HeaderMobileToggle} from './header-mobile-toggle.js';
+export {ImageManager} from './image-manager.js';
+export {ImagePicker} from './image-picker.js';
+export {ListSortControl} from './list-sort-control.js';
+export {MarkdownEditor} from './markdown-editor.js';
+export {NewUserPassword} from './new-user-password.js';
+export {Notification} from './notification.js';
+export {OptionalInput} from './optional-input.js';
+export {PageComments} from './page-comments.js';
+export {PageDisplay} from './page-display.js';
+export {PageEditor} from './page-editor.js';
+export {PagePicker} from './page-picker.js';
+export {PermissionsTable} from './permissions-table.js';
+export {Pointer} from './pointer.js';
+export {Popup} from './popup.js';
+export {SettingAppColorScheme} from './setting-app-color-scheme.js';
+export {SettingColorPicker} from './setting-color-picker.js';
+export {SettingHomepageControl} from './setting-homepage-control.js';
+export {ShelfSort} from './shelf-sort.js';
+export {Shortcuts} from './shortcuts';
+export {ShortcutInput} from './shortcut-input';
+export {SortableList} from './sortable-list.js';
+export {SubmitOnChange} from './submit-on-change.js';
+export {Tabs} from './tabs.js';
+export {TagManager} from './tag-manager.js';
+export {TemplateManager} from './template-manager.js';
+export {ToggleSwitch} from './toggle-switch.js';
+export {TriLayout} from './tri-layout.js';
+export {UserSelect} from './user-select.js';
+export {WebhookEvents} from './webhook-events';
+export {WysiwygEditor} from './wysiwyg-editor.js';
* ListSortControl
* Manages the logic for the control which provides list sorting options.
*/
-import {Component} from "./component";
+import {Component} from './component';
export class ListSortControl extends Component {
this.form.submit();
}
-}
\ No newline at end of file
+}
-import {Component} from "./component";
-import {init as initEditor} from "../markdown/editor";
+import {Component} from './component';
+import {init as initEditor} from '../markdown/editor';
export class MarkdownEditor extends Component {
this.divider = this.$refs.divider;
this.displayWrap = this.$refs.displayWrap;
- const settingContainer = this.$refs.settingContainer;
+ const {settingContainer} = this.$refs;
const settingInputs = settingContainer.querySelectorAll('input[type="checkbox"]');
this.editor = null;
}
setupListeners() {
-
// Button actions
this.elem.addEventListener('click', event => {
- let button = event.target.closest('button[data-action]');
+ const button = event.target.closest('button[data-action]');
if (button === null) return;
const action = button.getAttribute('data-action');
handleDividerDrag() {
this.divider.addEventListener('pointerdown', event => {
const wrapRect = this.elem.getBoundingClientRect();
- const moveListener = (event) => {
+ const moveListener = event => {
const xRel = event.pageX - wrapRect.left;
const xPct = Math.min(Math.max(20, Math.floor((xRel / wrapRect.width) * 100)), 80);
- this.displayWrap.style.flexBasis = `${100-xPct}%`;
+ this.displayWrap.style.flexBasis = `${100 - xPct}%`;
this.editor.settings.set('editorWidth', xPct);
};
- const upListener = (event) => {
+ const upListener = event => {
window.removeEventListener('pointermove', moveListener);
window.removeEventListener('pointerup', upListener);
this.display.style.pointerEvents = null;
});
const widthSetting = this.editor.settings.get('editorWidth');
if (widthSetting) {
- this.displayWrap.style.flexBasis = `${100-widthSetting}%`;
+ this.displayWrap.style.flexBasis = `${100 - widthSetting}%`;
}
}
-import {Component} from "./component";
+import {Component} from './component';
export class NewUserPassword extends Component {
this.inputContainer.style.display = inviting ? 'none' : 'block';
}
-}
\ No newline at end of file
+}
-import {Component} from "./component";
+import {Component} from './component';
-export class Notification extends Component {
+export class Notification extends Component {
setup() {
this.container = this.$el;
this.type = this.$opts.type;
this.textElem = this.container.querySelector('span');
this.autoHide = this.$opts.autoHide === 'true';
- this.initialShow = this.$opts.show === 'true'
+ this.initialShow = this.$opts.show === 'true';
this.container.style.display = 'grid';
window.$events.listen(this.type, text => {
this.container.removeEventListener('transitionend', this.hideCleanup);
}
-}
\ No newline at end of file
+}
-import {onSelect} from "../services/dom";
-import {Component} from "./component";
+import {onSelect} from '../services/dom';
+import {Component} from './component';
export class OptionalInput extends Component {
+
setup() {
this.removeButton = this.$refs.remove;
this.showButton = this.$refs.show;
});
}
-}
\ No newline at end of file
+}
-import {scrollAndHighlightElement} from "../services/util";
-import {Component} from "./component";
-import {htmlToDom} from "../services/dom";
+import {scrollAndHighlightElement} from '../services/util';
+import {Component} from './component';
+import {htmlToDom} from '../services/dom';
export class PageComments extends Component {
}
handleAction(event) {
- let actionElem = event.target.closest('[action]');
+ const actionElem = event.target.closest('[action]');
if (event.target.matches('a[href^="#"]')) {
const id = event.target.href.split('#')[1];
- scrollAndHighlightElement(document.querySelector('#' + id));
+ scrollAndHighlightElement(document.querySelector(`#${id}`));
}
if (actionElem === null) return;
if (this.editingComment) this.closeUpdateForm();
commentElem.querySelector('[comment-content]').style.display = 'none';
commentElem.querySelector('[comment-edit-container]').style.display = 'block';
- let textArea = commentElem.querySelector('[comment-edit-container] textarea');
- let lineCount = textArea.value.split('\n').length;
- textArea.style.height = ((lineCount * 20) + 40) + 'px';
+ const textArea = commentElem.querySelector('[comment-edit-container] textarea');
+ const lineCount = textArea.value.split('\n').length;
+ textArea.style.height = `${(lineCount * 20) + 40}px`;
this.editingComment = commentElem;
}
updateComment(event) {
- let form = event.target;
+ const form = event.target;
event.preventDefault();
- let text = form.querySelector('textarea').value;
- let reqData = {
- text: text,
+ const text = form.querySelector('textarea').value;
+ const reqData = {
+ text,
parent_id: this.parentId || null,
};
this.showLoading(form);
- let commentId = this.editingComment.getAttribute('comment');
+ const commentId = this.editingComment.getAttribute('comment');
window.$http.put(`/comment/${commentId}`, reqData).then(resp => {
- let newComment = document.createElement('div');
+ const newComment = document.createElement('div');
newComment.innerHTML = resp.data;
this.editingComment.innerHTML = newComment.children[0].innerHTML;
window.$events.success(this.updatedText);
}
deleteComment(commentElem) {
- let id = commentElem.getAttribute('comment');
+ const id = commentElem.getAttribute('comment');
this.showLoading(commentElem.querySelector('[comment-content]'));
window.$http.delete(`/comment/${id}`).then(resp => {
commentElem.parentNode.removeChild(commentElem);
saveComment(event) {
event.preventDefault();
event.stopPropagation();
- let text = this.formInput.value;
- let reqData = {
- text: text,
+ const text = this.formInput.value;
+ const reqData = {
+ text,
parent_id: this.parentId || null,
};
this.showLoading(this.form);
}
updateCount() {
- let count = this.container.children.length;
+ const count = this.container.children.length;
this.elem.querySelector('[comments-title]').textContent = window.trans_plural(this.countText, count, {count});
}
this.formContainer.parentNode.style.display = 'block';
this.addButtonContainer.style.display = 'none';
this.formInput.focus();
- this.formInput.scrollIntoView({behavior: "smooth"});
+ this.formInput.scrollIntoView({behavior: 'smooth'});
}
hideForm() {
this.formContainer.style.display = 'none';
this.formContainer.parentNode.style.display = 'none';
if (this.getCommentCount() > 0) {
- this.elem.appendChild(this.addButtonContainer)
+ this.elem.appendChild(this.addButtonContainer);
} else {
this.commentCountBar.appendChild(this.addButtonContainer);
}
showLoading(formElem) {
const groups = formElem.querySelectorAll('.form-group');
- for (let group of groups) {
+ for (const group of groups) {
group.style.display = 'none';
}
formElem.querySelector('.form-group.loading').style.display = 'block';
hideLoading(formElem) {
const groups = formElem.querySelectorAll('.form-group');
- for (let group of groups) {
+ for (const group of groups) {
group.style.display = 'block';
}
formElem.querySelector('.form-group.loading').style.display = 'none';
}
-}
\ No newline at end of file
+}
-import * as DOM from "../services/dom";
-import {scrollAndHighlightElement} from "../services/util";
-import {Component} from "./component";
+import * as DOM from '../services/dom';
+import {scrollAndHighlightElement} from '../services/util';
+import {Component} from './component';
export class PageDisplay extends Component {
window.$components.first('tri-layout').showContent();
const contentId = child.getAttribute('href').substr(1);
this.goToText(contentId);
- window.history.pushState(null, null, '#' + contentId);
+ window.history.pushState(null, null, `#${contentId}`);
});
}
}
// Setup the intersection observer.
const intersectOpts = {
rootMargin: '0px 0px 0px 0px',
- threshold: 1.0
+ threshold: 1.0,
};
const pageNavObserver = new IntersectionObserver(headingVisibilityChange, intersectOpts);
}
function toggleAnchorHighlighting(elementId, shouldHighlight) {
- DOM.forEach('a[href="#' + elementId + '"]', anchor => {
+ DOM.forEach(`a[href="#${elementId}"]`, anchor => {
anchor.closest('li').classList.toggle('current-heading', shouldHighlight);
});
}
const details = [...this.container.querySelectorAll('details')];
details.forEach(detail => detail.addEventListener('toggle', onToggle));
}
-}
\ No newline at end of file
+
+}
-import * as Dates from "../services/dates";
-import {onSelect} from "../services/dom";
-import {debounce} from "../services/util";
-import {Component} from "./component";
+import * as Dates from '../services/dates';
+import {onSelect} from '../services/dom';
+import {debounce} from '../services/util';
+import {Component} from './component';
export class PageEditor extends Component {
+
setup() {
// Options
this.draftsEnabled = this.$opts.draftsEnabled === 'true';
runAutoSave() {
// Stop if manually saved recently to prevent bombarding the server
- const savedRecently = (Date.now() - this.autoSave.last < (this.autoSave.frequency)/2);
+ const savedRecently = (Date.now() - this.autoSave.last < (this.autoSave.frequency) / 2);
if (savedRecently || !this.autoSave.pendingChange) {
return;
}
- this.saveDraft()
+ this.saveDraft();
}
savePage() {
this.startAutoSave();
}, 1000);
window.$events.emit('success', this.draftDiscardedText);
-
}
updateChangelogDisplay() {
if (summary.length === 0) {
summary = this.setChangelogText;
} else if (summary.length > 16) {
- summary = summary.slice(0, 16) + '...';
+ summary = `${summary.slice(0, 16)}...`;
}
this.changelogDisplay.innerText = summary;
}
event.preventDefault();
const link = event.target.closest('a').href;
- /** @var {ConfirmDialog} **/
+ /** @var {ConfirmDialog} * */
const dialog = window.$components.firstOnElement(this.switchDialogContainer, 'confirm-dialog');
const [saved, confirmed] = await Promise.all([this.saveDraft(), dialog.show()]);
-import {Component} from "./component";
+import {Component} from './component';
export class PagePicker extends Component {
}
showPopup() {
- /** @type {EntitySelectorPopup} **/
+ /** @type {EntitySelectorPopup} * */
const selectorPopup = window.$components.first('entity-selector-popup');
selectorPopup.show(entity => {
this.setValue(entity.id, entity.name);
toggleElem(this.defaultDisplay, !hasValue);
toggleElem(this.display, hasValue);
if (hasValue) {
- let id = this.getAssetIdFromVal();
+ const id = this.getAssetIdFromVal();
this.display.textContent = `#${id}, ${name}`;
this.display.href = window.baseUrl(`/link/${id}`);
}
function toggleElem(elem, show) {
elem.style.display = show ? null : 'none';
-}
\ No newline at end of file
+}
-import {Component} from "./component";
+import {Component} from './component';
export class PermissionsTable extends Component {
const tableRows = this.container.querySelectorAll(this.rowSelector);
const inputsToToggle = [];
- for (let row of tableRows) {
+ for (const row of tableRows) {
const targetCell = row.children[colIndex];
if (targetCell) {
inputsToToggle.push(...targetCell.querySelectorAll('input[type=checkbox]'));
toggleAllInputs(inputsToToggle) {
const currentState = inputsToToggle.length > 0 ? inputsToToggle[0].checked : false;
- for (let checkbox of inputsToToggle) {
+ for (const checkbox of inputsToToggle) {
checkbox.checked = !currentState;
checkbox.dispatchEvent(new Event('change'));
}
}
-}
\ No newline at end of file
+}
-import * as DOM from "../services/dom";
-import {Component} from "./component";
-import {copyTextToClipboard} from "../services/clipboard";
-
+import * as DOM from '../services/dom';
+import {Component} from './component';
+import {copyTextToClipboard} from '../services/clipboard';
export class Pointer extends Component {
updateForTarget(element) {
let inputText = this.pointerModeLink ? window.baseUrl(`/link/${this.pageId}#${this.pointerSectionId}`) : `{{@${this.pageId}#${this.pointerSectionId}}}`;
if (this.pointerModeLink && !inputText.startsWith('http')) {
- inputText = window.location.protocol + "//" + window.location.host + inputText;
+ inputText = `${window.location.protocol}//${window.location.host}${inputText}`;
}
this.input.value = inputText;
// Update anchor if present
const editAnchor = this.container.querySelector('#pointer-edit');
if (editAnchor && element) {
- const editHref = editAnchor.dataset.editHref;
+ const {editHref} = editAnchor.dataset;
const elementId = element.id;
// get the first 50 characters.
editAnchor.href = `${editHref}?content-id=${elementId}&content-text=${encodeURIComponent(queryContent)}`;
}
}
-}
\ No newline at end of file
+
+}
-import {fadeIn, fadeOut} from "../services/animations";
-import {onSelect} from "../services/dom";
-import {Component} from "./component";
+import {fadeIn, fadeOut} from '../services/animations';
+import {onSelect} from '../services/dom';
+import {Component} from './component';
/**
* Popup window that will contain other content.
show(onComplete = null, onHide = null) {
fadeIn(this.container, 120, onComplete);
- this.onkeyup = (event) => {
+ this.onkeyup = event => {
if (event.key === 'Escape') {
this.hide();
}
this.onHide = onHide;
}
-}
\ No newline at end of file
+}
-import {Component} from "./component";
+import {Component} from './component';
export class SettingAppColorScheme extends Component {
this.handleModeChange(newMode);
});
- const onInputChange = (event) => {
+ const onInputChange = event => {
this.updateAppColorsFromInputs();
if (event.target.name.startsWith('setting-app-color')) {
cssId = 'primary';
}
- const varName = '--color-' + cssId;
+ const varName = `--color-${cssId}`;
document.body.style.setProperty(varName, input.value);
}
}
const lightName = input.name.replace('-color', '-color-light');
const hexVal = input.value;
const rgb = this.hexToRgb(hexVal);
- const rgbLightVal = 'rgba('+ [rgb.r, rgb.g, rgb.b, '0.15'].join(',') +')';
+ const rgbLightVal = `rgba(${[rgb.r, rgb.g, rgb.b, '0.15'].join(',')})`;
- console.log(input.name, lightName, hexVal, rgbLightVal)
+ console.log(input.name, lightName, hexVal, rgbLightVal);
const lightColorInput = this.container.querySelector(`input[name="${lightName}"][type="hidden"]`);
lightColorInput.value = rgbLightVal;
}
return {
r: result ? parseInt(result[1], 16) : 0,
g: result ? parseInt(result[2], 16) : 0,
- b: result ? parseInt(result[3], 16) : 0
+ b: result ? parseInt(result[3], 16) : 0,
};
}
-import {Component} from "./component";
+import {Component} from './component';
export class SettingColorPicker extends Component {
this.colorInput.value = value;
this.colorInput.dispatchEvent(new Event('change', {bubbles: true}));
}
-}
\ No newline at end of file
+
+}
-import {Component} from "./component";
+import {Component} from './component';
export class SettingHomepageControl extends Component {
const showPagePicker = this.typeControl.value === 'page';
this.pagePickerContainer.style.display = (showPagePicker ? 'block' : 'none');
}
-}
\ No newline at end of file
+
+}
-import Sortable from "sortablejs";
-import {Component} from "./component";
+import Sortable from 'sortablejs';
+import {Component} from './component';
/**
* @type {Object<string, function(HTMLElement, HTMLElement, HTMLElement)>}
this.filterBooksByName(this.bookSearchInput.value);
});
- this.sortButtonContainer.addEventListener('click' , event => {
+ this.sortButtonContainer.addEventListener('click', event => {
const button = event.target.closest('button[data-sort]');
if (button) {
this.sortShelfBooks(button.dataset.sort);
* @param {String} filterVal
*/
filterBooksByName(filterVal) {
-
// Set height on first search, if not already set, to prevent the distraction
// of the list height jumping around
if (!this.allBookList.style.height) {
- this.allBookList.style.height = this.allBookList.getBoundingClientRect().height + 'px';
+ this.allBookList.style.height = `${this.allBookList.getBoundingClientRect().height}px`;
}
const books = this.allBookList.children;
*/
sortItemActionClick(sortItemAction) {
const sortItem = sortItemAction.closest('.scroll-box-item');
- const action = sortItemAction.dataset.action;
+ const {action} = sortItemAction.dataset;
const actionFunction = itemActions[action];
actionFunction(sortItem, this.shelfBookList, this.allBookList);
this.onChange();
}
-}
\ No newline at end of file
+}
-import {Component} from "./component";
+import {Component} from './component';
/**
* Keys to ignore when recording shortcuts.
this.listenerRecordKey = this.listenerRecordKey.bind(this);
this.input.addEventListener('focus', () => {
- this.startListeningForInput();
+ this.startListeningForInput();
});
this.input.addEventListener('blur', () => {
this.stopListeningForInput();
- })
+ });
}
startListeningForInput() {
- this.input.addEventListener('keydown', this.listenerRecordKey)
+ this.input.addEventListener('keydown', this.listenerRecordKey);
}
/**
this.input.removeEventListener('keydown', this.listenerRecordKey);
}
-}
\ No newline at end of file
+}
-import {Component} from "./component";
+import {Component} from './component';
function reverseMap(map) {
const reversed = {};
return reversed;
}
-
export class Shortcuts extends Component {
setup() {
setupListeners() {
window.addEventListener('keydown', event => {
-
if (event.target.closest('input, select, textarea')) {
return;
}
* @param {KeyboardEvent} event
*/
handleShortcutPress(event) {
-
const keys = [
event.ctrlKey ? 'Ctrl' : '',
event.metaKey ? 'Cmd' : '',
return true;
}
- console.error(`Shortcut attempted to be ran for element type that does not have handling setup`, el);
+ console.error('Shortcut attempted to be ran for element type that does not have handling setup', el);
return false;
}
const linkage = document.createElement('div');
linkage.classList.add('shortcut-linkage');
- linkage.style.left = targetBounds.x + 'px';
- linkage.style.top = targetBounds.y + 'px';
- linkage.style.width = targetBounds.width + 'px';
- linkage.style.height = targetBounds.height + 'px';
+ linkage.style.left = `${targetBounds.x}px`;
+ linkage.style.top = `${targetBounds.y}px`;
+ linkage.style.width = `${targetBounds.width}px`;
+ linkage.style.height = `${targetBounds.height}px`;
wrapper.append(label, linkage);
this.hintsShowing = false;
}
-}
\ No newline at end of file
+
+}
-import Sortable from "sortablejs";
-import {Component} from "./component";
+import Sortable from 'sortablejs';
+import {Component} from './component';
/**
* SortableList
* the data to set on the data-transfer.
*/
export class SortableList extends Component {
+
setup() {
this.container = this.$el;
this.handleSelector = this.$opts.handleSelector;
dragoverBubble: false,
});
}
-}
\ No newline at end of file
+
+}
-import {Component} from "./component";
+import {Component} from './component';
/**
* Submit on change
setup() {
this.filter = this.$opts.filter;
- this.$el.addEventListener('change', (event) => {
-
+ this.$el.addEventListener('change', event => {
if (this.filter && !event.target.matches(this.filter)) {
return;
}
});
}
-}
\ No newline at end of file
+}
-import {Component} from "./component";
+import {Component} from './component';
/**
* Tabs
this.$emit('change', {showing: sectionId});
}
-}
\ No newline at end of file
+}
-import {Component} from "./component";
+import {Component} from './component';
export class TagManager extends Component {
+
setup() {
this.addRemoveComponentEl = this.$refs.addRemove;
this.container = this.$el;
setupListeners() {
this.container.addEventListener('input', event => {
-
- /** @var {AddRemoveRows} **/
+ /** @var {AddRemoveRows} * */
const addRemoveComponent = window.$components.firstOnElement(this.addRemoveComponentEl, 'add-remove-rows');
if (!this.hasEmptyRows() && event.target.value) {
addRemoveComponent.add();
hasEmptyRows() {
const rows = this.container.querySelectorAll(this.rowSelector);
- const firstEmpty = [...rows].find(row => {
- return [...row.querySelectorAll('input')].filter(input => input.value).length === 0;
- });
+ const firstEmpty = [...rows].find(row => [...row.querySelectorAll('input')].filter(input => input.value).length === 0);
return firstEmpty !== undefined;
}
-}
\ No newline at end of file
+
+}
-import * as DOM from "../services/dom";
-import {Component} from "./component";
+import * as DOM from '../services/dom';
+import {Component} from './component';
export class TemplateManager extends Component {
async insertTemplate(templateId, action = 'replace') {
const resp = await window.$http.get(`/templates/${templateId}`);
- const eventName = 'editor::' + action;
+ const eventName = `editor::${action}`;
window.$events.emit(eventName, resp.data);
}
async performSearch() {
const searchTerm = this.searchInput.value;
- const resp = await window.$http.get(`/templates`, {
- search: searchTerm
+ const resp = await window.$http.get('/templates', {
+ search: searchTerm,
});
this.searchCancel.style.display = searchTerm ? 'block' : 'none';
this.list.innerHTML = resp.data;
}
-}
\ No newline at end of file
+
+}
-import {Component} from "./component";
+import {Component} from './component';
export class ToggleSwitch extends Component {
this.input.dispatchEvent(changeEvent);
}
-}
\ No newline at end of file
+}
-import {Component} from "./component";
+import {Component} from './component';
export class TriLayout extends Component {
this.lastLayoutType = 'none';
this.onDestroy = null;
this.scrollCache = {
- 'content': 0,
- 'info': 0,
+ content: 0,
+ info: 0,
};
this.lastTabShown = 'content';
updateLayout() {
let newLayout = 'tablet';
- if (window.innerWidth <= 1000) newLayout = 'mobile';
- if (window.innerWidth >= 1400) newLayout = 'desktop';
+ if (window.innerWidth <= 1000) newLayout = 'mobile';
+ if (window.innerWidth >= 1400) newLayout = 'desktop';
if (newLayout === this.lastLayoutType) return;
if (this.onDestroy) {
for (const tab of this.tabs) {
tab.removeEventListener('click', this.mobileTabClick);
}
- }
+ };
}
setupDesktop() {
//
}
-
/**
* Action to run when the mobile info toggle bar is clicked/tapped
* @param event
*/
mobileTabClick(event) {
- const tab = event.target.dataset.tab;
+ const {tab} = event.target.dataset;
this.showTab(tab);
}
this.lastTabShown = tabName;
}
-}
\ No newline at end of file
+}
-import {onChildEvent} from "../services/dom";
-import {Component} from "./component";
+import {onChildEvent} from '../services/dom';
+import {Component} from './component';
export class UserSelect extends Component {
}
hide() {
- /** @var {Dropdown} **/
+ /** @var {Dropdown} * */
const dropdown = window.$components.firstOnElement(this.container, 'dropdown');
dropdown.hide();
}
-}
\ No newline at end of file
+}
* Webhook Events
* Manages dynamic selection control in the webhook form interface.
*/
-import {Component} from "./component";
+import {Component} from './component';
export class WebhookEvents extends Component {
}
}
-}
\ No newline at end of file
+}
-import {build as buildEditorConfig} from "../wysiwyg/config";
-import {Component} from "./component";
+import {build as buildEditorConfig} from '../wysiwyg/config';
+import {Component} from './component';
export class WysiwygEditor extends Component {
*/
getContent() {
return {
- html: this.editor.getContent()
+ html: this.editor.getContent(),
};
}
-}
\ No newline at end of file
+}
-import DrawIO from "../services/drawio";
+import DrawIO from '../services/drawio';
export class Actions {
+
/**
* @param {MarkdownEditor} editor
*/
}
showImageInsert() {
- /** @type {ImageManager} **/
+ /** @type {ImageManager} * */
const imageManager = window.$components.first('image-manager');
imageManager.show(image => {
const imageUrl = image.thumbs.display || image.url;
const selectedText = this.#getSelectionText();
- const newText = "[](" + image.url + ")";
+ const newText = `[](${image.url})`;
this.#replaceSelection(newText, newText.length);
}, 'gallery');
}
const selectedText = this.#getSelectionText();
const newText = `[${selectedText}]()`;
const cursorPosDiff = (selectedText === '') ? -3 : -1;
- this.#replaceSelection(newText, newText.length+cursorPosDiff);
+ this.#replaceSelection(newText, newText.length + cursorPosDiff);
}
showImageManager() {
const selectionRange = this.#getSelectionRange();
- /** @type {ImageManager} **/
+ /** @type {ImageManager} * */
const imageManager = window.$components.first('image-manager');
imageManager.show(image => {
this.#insertDrawing(image, selectionRange);
showLinkSelector() {
const selectionRange = this.#getSelectionRange();
- /** @type {EntitySelectorPopup} **/
+ /** @type {EntitySelectorPopup} * */
const selector = window.$components.first('entity-selector-popup');
selector.show(entity => {
const selectedText = this.#getSelectionText(selectionRange) || entity.name;
const selectionRange = this.#getSelectionRange();
- DrawIO.show(url,() => {
- return Promise.resolve('');
- }, (pngData) => {
-
+ DrawIO.show(url, () => Promise.resolve(''), pngData => {
const data = {
image: pngData,
uploaded_to: Number(this.editor.config.pageId),
};
- window.$http.post("/images/drawio", data).then(resp => {
+ window.$http.post('/images/drawio', data).then(resp => {
this.#insertDrawing(resp.data, selectionRange);
DrawIO.close();
}).catch(err => {
// Show draw.io if enabled and handle save.
editDrawing(imgContainer) {
- const drawioUrl = this.editor.config.drawioUrl;
+ const {drawioUrl} = this.editor.config;
if (!drawioUrl) {
return;
}
const selectionRange = this.#getSelectionRange();
const drawingId = imgContainer.getAttribute('drawio-diagram');
- DrawIO.show(drawioUrl, () => {
- return DrawIO.load(drawingId);
- }, (pngData) => {
-
+ DrawIO.show(drawioUrl, () => DrawIO.load(drawingId), pngData => {
const data = {
image: pngData,
uploaded_to: Number(this.editor.config.pageId),
};
- window.$http.post("/images/drawio", data).then(resp => {
+ window.$http.post('/images/drawio', data).then(resp => {
const newText = `<div drawio-diagram="${resp.data.id}"><img src="${resp.data.url}"></div>`;
const newContent = this.#getText().split('\n').map(line => {
if (line.indexOf(`drawio-diagram="${drawingId}"`) !== -1) {
// Make the editor full screen
fullScreen() {
- const container = this.editor.config.container;
+ const {container} = this.editor.config;
const alreadyFullscreen = container.classList.contains('fullscreen');
container.classList.toggle('fullscreen', !alreadyFullscreen);
document.body.classList.toggle('markdown-fullscreen', !alreadyFullscreen);
content = this.#cleanTextForEditor(content);
const selectionRange = this.#getSelectionRange();
const selectFrom = selectionRange.from + content.length + 1;
- this.#dispatchChange(0, 0, content + '\n', selectFrom);
+ this.#dispatchChange(0, 0, `${content}\n`, selectFrom);
this.focus();
}
*/
appendContent(content) {
content = this.#cleanTextForEditor(content);
- this.#dispatchChange(this.editor.cm.state.doc.length, '\n' + content);
+ this.#dispatchChange(this.editor.cm.state.doc.length, `\n${content}`);
this.focus();
}
* @param {String} content
*/
replaceContent(content) {
- this.#setText(content)
+ this.#setText(content);
}
/**
if (alreadySymbol) {
newLineContent = lineContent.replace(lineStart, newStart).trim();
} else if (newStart !== '') {
- newLineContent = newStart + ' ' + lineContent;
+ newLineContent = `${newStart} ${lineContent}`;
}
const selectFrom = selectionRange.from + (newLineContent.length - lineContent.length);
const number = (Number(listMatch[2]) || 0) + 1;
const whiteSpace = listMatch[1] || '';
- const listMark = listMatch[3] || '.'
+ const listMark = listMatch[3] || '.';
const prefix = `${whiteSpace}${number}${listMark}`;
return this.replaceLineStart(prefix);
* @param {File} file
* @param {?Number} position
*/
- async uploadImage(file, position= null) {
+ async uploadImage(file, position = null) {
if (file === null || file.type.indexOf('image') !== 0) return;
let ext = 'png';
}
if (file.name) {
- let fileNameMatches = file.name.match(/\.(.+)$/);
+ const fileNameMatches = file.name.match(/\.(.+)$/);
if (fileNameMatches.length > 1) ext = fileNameMatches[1];
}
// Insert image into markdown
- const id = "image-" + Math.random().toString(16).slice(2);
+ const id = `image-${Math.random().toString(16).slice(2)}`;
const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
const placeHolderText = ``;
this.#dispatchChange(position, position, placeHolderText, position);
- const remoteFilename = "image-" + Date.now() + "." + ext;
+ const remoteFilename = `image-${Date.now()}.${ext}`;
const formData = new FormData();
formData.append('file', file, remoteFilename);
formData.append('uploaded_to', this.editor.config.pageId);
* @return {String}
*/
#cleanTextForEditor(text) {
- return text.replace(/\r\n|\r/g, "\n");
+ return text.replace(/\r\n|\r/g, '\n');
}
/**
* @param {?Number} selectTo
*/
#dispatchChange(from, to = null, text = null, selectFrom = null, selectTo = null) {
- const tr = {changes: {from, to: to, insert: text}};
+ const tr = {changes: {from, to, insert: text}};
if (selectFrom) {
tr.selection = {anchor: selectFrom};
scrollIntoView,
});
}
-}
\ No newline at end of file
+
+}
-import {provideKeyBindings} from "./shortcuts";
-import {debounce} from "../services/util";
-import Clipboard from "../services/clipboard";
+import {provideKeyBindings} from './shortcuts';
+import {debounce} from '../services/util';
+import Clipboard from '../services/clipboard';
/**
* Initiate the codemirror instance for the markdown editor.
const domEventHandlers = {
// Handle scroll to sync display view
- scroll: (event) => syncActive && onScrollDebounced(event),
+ scroll: event => syncActive && onScrollDebounced(event),
// Handle image & content drag n drop
- drop: (event) => {
+ drop: event => {
const templateId = event.dataTransfer.getData('bookstack/template');
if (templateId) {
event.preventDefault();
}
},
// Handle image paste
- paste: (event) => {
+ paste: event => {
const clipboard = new Clipboard(event.clipboardData || event.dataTransfer);
// Don't handle the event ourselves if no items exist of contains table-looking data
for (const image of images) {
editor.actions.uploadImage(image);
}
- }
- }
+ },
+ };
const cm = Code.markdownEditor(
editor.config.inputEl,
window.mdEditorView = cm;
return cm;
-}
\ No newline at end of file
+}
* @param {MarkdownEditor} editor
*/
export function listen(editor) {
-
- window.$events.listen('editor::replace', (eventContent) => {
+ window.$events.listen('editor::replace', eventContent => {
const markdown = getContentToInsert(eventContent);
editor.actions.replaceContent(markdown);
});
- window.$events.listen('editor::append', (eventContent) => {
+ window.$events.listen('editor::append', eventContent => {
const markdown = getContentToInsert(eventContent);
editor.actions.appendContent(markdown);
});
- window.$events.listen('editor::prepend', (eventContent) => {
+ window.$events.listen('editor::prepend', eventContent => {
const markdown = getContentToInsert(eventContent);
editor.actions.prependContent(markdown);
});
- window.$events.listen('editor::insert', (eventContent) => {
+ window.$events.listen('editor::insert', eventContent => {
const markdown = getContentToInsert(eventContent);
editor.actions.insertContent(markdown);
});
window.$events.listen('editor::focus', () => {
editor.actions.focus();
});
-}
\ No newline at end of file
+}
-import {patchDomFromHtmlString} from "../services/vdom";
+import {patchDomFromHtmlString} from '../services/vdom';
export class Display {
* @param {String} html
*/
patchWithHtml(html) {
- const body = this.doc.body;
+ const {body} = this.doc;
if (body.children.length === 0) {
const wrap = document.createElement('div');
const elems = this.doc.body?.children[0]?.children;
if (elems && elems.length <= index) return;
- const topElem = (index === -1) ? elems[elems.length-1] : elems[index];
- topElem.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth'});
+ const topElem = (index === -1) ? elems[elems.length - 1] : elems[index];
+ topElem.scrollIntoView({block: 'start', inline: 'nearest', behavior: 'smooth'});
}
-}
\ No newline at end of file
+}
-import {Markdown} from "./markdown";
-import {Display} from "./display";
-import {Actions} from "./actions";
-import {Settings} from "./settings";
-import {listen} from "./common-events";
-import {init as initCodemirror} from "./codemirror";
-
+import {Markdown} from './markdown';
+import {Display} from './display';
+import {Actions} from './actions';
+import {Settings} from './settings';
+import {listen} from './common-events';
+import {init as initCodemirror} from './codemirror';
/**
* Initiate a new markdown editor instance.
* @returns {Promise<MarkdownEditor>}
*/
export async function init(config) {
-
/**
* @type {MarkdownEditor}
*/
return editor;
}
-
/**
* @typedef MarkdownEditorConfig
* @property {String} pageId
* @property {Actions} actions
* @property {EditorView} cm
* @property {Settings} settings
- */
\ No newline at end of file
+ */
-import MarkdownIt from "markdown-it";
+import MarkdownIt from 'markdown-it';
import mdTasksLists from 'markdown-it-task-lists';
export class Markdown {
render(markdown) {
return this.renderer.render(markdown);
}
-}
-
-
+}
listeners.push(callback);
this.changeListeners[key] = listeners;
}
-}
\ No newline at end of file
+
+}
shortcuts['Mod-8'] = cm => editor.actions.wrapSelection('`', '`');
shortcuts['Shift-Mod-e'] = cm => editor.actions.wrapSelection('`', '`');
shortcuts['Mod-9'] = cm => editor.actions.cycleCalloutTypeAtSelection();
- shortcuts['Mod-p'] = cm => editor.actions.replaceLineStart('-')
- shortcuts['Mod-o'] = cm => editor.actions.replaceLineStartForOrderedList()
+ shortcuts['Mod-p'] = cm => editor.actions.replaceLineStart('-');
+ shortcuts['Mod-o'] = cm => editor.actions.replaceLineStartForOrderedList();
return shortcuts;
}
* @return {{key: String, run: function, preventDefault: boolean}[]}
*/
export function provideKeyBindings(editor) {
- const shortcuts= provide(editor);
+ const shortcuts = provide(editor);
const keyBindings = [];
- const wrapAction = (action) => {
- return () => {
- action();
- return true;
- };
+ const wrapAction = action => () => {
+ action();
+ return true;
};
for (const [shortcut, action] of Object.entries(shortcuts)) {
}
return keyBindings;
-}
\ No newline at end of file
+}
cleanupExistingElementAnimation(element);
element.style.display = 'block';
animateStyles(element, {
- opacity: ['0', '1']
+ opacity: ['0', '1'],
}, animTime, () => {
if (onComplete) onComplete();
});
export function fadeOut(element, animTime = 400, onComplete = null) {
cleanupExistingElementAnimation(element);
animateStyles(element, {
- opacity: ['1', '0']
+ opacity: ['1', '0'],
}, animTime, () => {
element.style.display = 'none';
if (onComplete) onComplete();
*/
function animateStyles(element, styles, animTime = 400, onComplete = null) {
const styleNames = Object.keys(styles);
- for (let style of styleNames) {
+ for (const style of styleNames) {
element.style[style] = styles[style][0];
}
const cleanup = () => {
- for (let style of styleNames) {
+ for (const style of styleNames) {
element.style[style] = null;
}
element.style.transition = null;
setTimeout(() => {
element.style.transition = `all ease-in-out ${animTime}ms`;
- for (let style of styleNames) {
+ for (const style of styleNames) {
element.style[style] = styles[style][1];
}
const oldCleanup = animateStylesCleanupMap.get(element);
oldCleanup();
}
-}
\ No newline at end of file
+}
-
export class Clipboard {
/**
* @return {boolean}
*/
containsTabularData() {
- const rtfData = this.data.getData( 'text/rtf');
+ const rtfData = this.data.getData('text/rtf');
return rtfData && rtfData.includes('\\trowd');
}
* @return {Array<File>}
*/
getImages() {
- const types = this.data.types;
- const files = this.data.files;
+ const {types} = this.data;
+ const {files} = this.data;
const images = [];
for (const type of types) {
return images;
}
+
}
export async function copyTextToClipboard(text) {
}
// Backup option where we can't use the navigator.clipboard API
- const tempInput = document.createElement("textarea");
- tempInput.style = "position: absolute; left: -1000px; top: -1000px;";
+ const tempInput = document.createElement('textarea');
+ tempInput.style = 'position: absolute; left: -1000px; top: -1000px;';
tempInput.value = text;
document.body.appendChild(tempInput);
tempInput.select();
- document.execCommand("copy");
+ document.execCommand('copy');
document.body.removeChild(tempInput);
}
-export default Clipboard;
\ No newline at end of file
+export default Clipboard;
-import {kebabToCamel, camelToKebab} from "./text";
+import {kebabToCamel, camelToKebab} from './text';
/**
* A mapping of active components keyed by name, with values being arrays of component
* @param {Element} element
*/
function initComponent(name, element) {
- /** @type {Function<Component>|undefined} **/
+ /** @type {Function<Component>|undefined} * */
const componentModel = componentModelMap[name];
if (componentModel === undefined) return;
// Create our component instance
- /** @type {Component} **/
+ /** @type {Component} * */
let instance;
try {
instance = new componentModel();
}
// Add to global listing
- if (typeof components[name] === "undefined") {
+ if (typeof components[name] === 'undefined') {
components[name] = [];
}
components[name].push(instance);
const refs = {};
const manyRefs = {};
- const prefix = `${name}@`
+ const prefix = `${name}@`;
const selector = `[refs*="${prefix}"]`;
const refElems = [...element.querySelectorAll(selector)];
if (element.matches(selector)) {
* @param {Element|Document} parentElement
*/
export function init(parentElement = document) {
- const componentElems = parentElement.querySelectorAll(`[component],[components]`);
+ const componentElems = parentElement.querySelectorAll('[component],[components]');
for (const el of componentElems) {
const componentNames = `${el.getAttribute('component') || ''} ${(el.getAttribute('components'))}`.toLowerCase().split(' ').filter(Boolean);
export function firstOnElement(element, name) {
const elComponents = elementComponentMap.get(element) || {};
return elComponents[name] || null;
-}
\ No newline at end of file
+}
-
export function getCurrentDay() {
- let date = new Date();
- let month = date.getMonth() + 1;
- let day = date.getDate();
+ const date = new Date();
+ const month = date.getMonth() + 1;
+ const day = date.getDate();
- return `${date.getFullYear()}-${(month>9?'':'0') + month}-${(day>9?'':'0') + day}`;
+ return `${date.getFullYear()}-${(month > 9 ? '' : '0') + month}-${(day > 9 ? '' : '0') + day}`;
}
export function utcTimeStampToLocalTime(timestamp) {
- let date = new Date(timestamp * 1000);
- let hours = date.getHours();
- let mins = date.getMinutes();
- return `${(hours>9?'':'0') + hours}:${(mins>9?'':'0') + mins}`;
+ const date = new Date(timestamp * 1000);
+ const hours = date.getHours();
+ const mins = date.getMinutes();
+ return `${(hours > 9 ? '' : '0') + hours}:${(mins > 9 ? '' : '0') + mins}`;
}
export function formatDateTime(date) {
- let month = date.getMonth() + 1;
- let day = date.getDate();
- let hours = date.getHours();
- let mins = date.getMinutes();
+ const month = date.getMonth() + 1;
+ const day = date.getDate();
+ const hours = date.getHours();
+ const mins = date.getMinutes();
- return `${date.getFullYear()}-${(month>9?'':'0') + month}-${(day>9?'':'0') + day} ${(hours>9?'':'0') + hours}:${(mins>9?'':'0') + mins}`;
-}
\ No newline at end of file
+ return `${date.getFullYear()}-${(month > 9 ? '' : '0') + month}-${(day > 9 ? '' : '0') + day} ${(hours > 9 ? '' : '0') + hours}:${(mins > 9 ? '' : '0') + mins}`;
+}
*/
export function forEach(selector, callback) {
const elements = document.querySelectorAll(selector);
- for (let element of elements) {
+ for (const element of elements) {
callback(element);
}
}
* @param {Function<Event>} callback
*/
export function onEvents(listenerElement, events, callback) {
- for (let eventName of events) {
+ for (const eventName of events) {
listenerElement.addEventListener(eventName, callback);
}
}
for (const listenerElement of elements) {
listenerElement.addEventListener('click', callback);
- listenerElement.addEventListener('keydown', (event) => {
+ listenerElement.addEventListener('keydown', event => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
callback(event);
if (event.key === 'Enter') {
callback(event);
}
- }
+ };
elements.forEach(e => e.addEventListener('keypress', listener));
}
* @param {Function} callback
*/
export function onChildEvent(listenerElement, childSelector, eventName, callback) {
- listenerElement.addEventListener(eventName, function(event) {
+ listenerElement.addEventListener(eventName, event => {
const matchingChild = event.target.closest(childSelector);
if (matchingChild) {
callback.call(matchingChild, event, matchingChild);
export function findText(selector, text) {
const elements = document.querySelectorAll(selector);
text = text.toLowerCase();
- for (let element of elements) {
+ for (const element of elements) {
if (element.textContent.toLowerCase().includes(text)) {
return element;
}
* @param {Element} element
*/
export function showLoading(element) {
- element.innerHTML = `<div class="loading-container"><div></div><div></div><div></div></div>`;
+ element.innerHTML = '<div class="loading-container"><div></div><div></div><div></div></div>';
}
/**
wrap.innerHTML = html;
window.$components.init(wrap);
return wrap.children[0];
-}
\ No newline at end of file
+}
let iFrame = null;
let lastApprovedOrigin;
-let onInit, onSave;
+let onInit; let
+ onSave;
/**
* Show the draw.io editor.
}
function drawEventSave(message) {
- drawPostMessage({action: 'export', format: 'xmlpng', xml: message.xml, spin: 'Updating drawing'});
+ drawPostMessage({
+ action: 'export', format: 'xmlpng', xml: message.xml, spin: 'Updating drawing',
+ });
}
function drawEventInit() {
if (!onInit) return;
onInit().then(xml => {
- drawPostMessage({action: 'load', autosave: 1, xml: xml});
+ drawPostMessage({action: 'load', autosave: 1, xml});
});
}
}
async function upload(imageData, pageUploadedToId) {
- let data = {
+ const data = {
image: imageData,
uploaded_to: pageUploadedToId,
};
- const resp = await window.$http.post(window.baseUrl(`/images/drawio`), data);
+ const resp = await window.$http.post(window.baseUrl('/images/drawio'), data);
return resp.data;
}
}
}
-export default {show, close, upload, load};
\ No newline at end of file
+export default {
+ show, close, upload, load,
+};
function emit(eventName, eventData) {
stack.push({name: eventName, data: eventData});
if (typeof listeners[eventName] === 'undefined') return this;
- let eventsToStart = listeners[eventName];
+ const eventsToStart = listeners[eventName];
for (let i = 0; i < eventsToStart.length; i++) {
- let event = eventsToStart[i];
+ const event = eventsToStart[i];
event(eventData);
}
}
function emitPublic(targetElement, eventName, eventData) {
const event = new CustomEvent(eventName, {
detail: eventData,
- bubbles: true
+ bubbles: true,
});
targetElement.dispatchEvent(event);
}
emit,
emitPublic,
listen,
- success: (msg) => emit('success', msg),
- error: (msg) => emit('error', msg),
+ success: msg => emit('success', msg),
+ error: msg => emit('error', msg),
showValidationErrors,
showResponseError,
-}
\ No newline at end of file
+};
-
/**
* Perform a HTTP GET request.
* Can easily pass query parameters as the second parameter.
*/
async function dataRequest(method, url, data = null) {
const options = {
- method: method,
+ method,
body: data,
};
options.method = 'post';
}
- return request(url, options)
+ return request(url, options);
}
/**
if (options.params) {
const urlObj = new URL(url);
- for (let paramName of Object.keys(options.params)) {
+ for (const paramName of Object.keys(options.params)) {
const value = options.params[paramName];
if (typeof value !== 'undefined' && value !== null) {
urlObj.searchParams.set(paramName, value);
}
const csrfToken = document.querySelector('meta[name=token]').getAttribute('content');
- options = Object.assign({}, options, {
- 'credentials': 'same-origin',
- });
- options.headers = Object.assign({}, options.headers || {}, {
- 'baseURL': window.baseUrl(''),
+ options = {...options, credentials: 'same-origin'};
+ options.headers = {
+ ...options.headers || {},
+ baseURL: window.baseUrl(''),
'X-CSRF-TOKEN': csrfToken,
- });
+ };
const response = await fetch(url, options);
const content = await getResponseContent(response);
}
class HttpError extends Error {
+
constructor(response, content) {
super(response.statusText);
this.data = content;
this.url = response.url;
this.original = response;
}
+
}
export default {
- get: get,
- post: post,
- put: put,
- patch: patch,
+ get,
+ post,
+ put,
+ patch,
delete: performDelete,
- HttpError: HttpError,
-};
\ No newline at end of file
+ HttpError,
+};
* @param {KeyboardEvent} event
*/
#keydownHandler(event) {
-
// Ignore certain key events in inputs to allow text editing.
if (event.target.matches('input') && (event.key === 'ArrowRight' || event.key === 'ArrowLeft')) {
return;
} else if (event.key === 'Escape') {
if (this.onEscape) {
this.onEscape(event);
- } else if (document.activeElement) {
+ } else if (document.activeElement) {
document.activeElement.blur();
}
} else if (event.key === 'Enter' && this.onEnter) {
const focusable = [];
const selector = '[tabindex]:not([tabindex="-1"]),[href],button:not([tabindex="-1"],[disabled]),input:not([type=hidden])';
for (const container of this.containers) {
- focusable.push(...container.querySelectorAll(selector))
+ focusable.push(...container.querySelectorAll(selector));
}
return focusable;
}
-}
\ No newline at end of file
+
+}
* @returns {string}
*/
export function kebabToCamel(kebab) {
- const ucFirst = (word) => word.slice(0,1).toUpperCase() + word.slice(1);
+ const ucFirst = word => word.slice(0, 1).toUpperCase() + word.slice(1);
const words = kebab.split('-');
return words[0] + words.slice(1).map(ucFirst).join('');
}
* @returns {String}
*/
export function camelToKebab(camelStr) {
- return camelStr.replace(/[A-Z]/g, (str, offset) => (offset > 0 ? '-' : '') + str.toLowerCase());
-}
\ No newline at end of file
+ return camelStr.replace(/[A-Z]/g, (str, offset) => (offset > 0 ? '-' : '') + str.toLowerCase());
+}
*/
parseTranslations() {
const translationMetaTags = document.querySelectorAll('meta[name="translation"]');
- for (let tag of translationMetaTags) {
+ for (const tag of translationMetaTags) {
const key = tag.getAttribute('key');
const value = tag.getAttribute('value');
this.store.set(key, value);
const rangeRegex = /^\[([0-9]+),([0-9*]+)]/;
let result = null;
- for (let t of splitText) {
+ for (const t of splitText) {
// Parse exact matches
const exactMatches = t.match(exactCountRegex);
if (exactMatches !== null && Number(exactMatches[1]) === count) {
-
-
/**
* Returns a function, that, as long as it continues to be invoked, will not
* be triggered. The function will be called after it stops being called for
export function debounce(func, wait, immediate) {
let timeout;
return function() {
- const context = this, args = arguments;
+ const context = this; const
+ args = arguments;
const later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
-};
+}
/**
* Scroll and highlight an element.
*/
export function escapeHtml(unsafe) {
return unsafe
- .replace(/&/g, "&")
- .replace(/</g, "<")
- .replace(/>/g, ">")
- .replace(/"/g, """)
- .replace(/'/g, "'");
+ .replace(/&/g, '&')
+ .replace(/</g, '<')
+ .replace(/>/g, '>')
+ .replace(/"/g, '"')
+ .replace(/'/g, ''');
}
/**
* @returns {string}
*/
export function uniqueId() {
- const S4 = () => (((1+Math.random())*0x10000)|0).toString(16).substring(1);
- return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
-}
\ No newline at end of file
+ const S4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
+ return (`${S4() + S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`);
+}
import {
init,
attributesModule,
- toVNode
-} from "snabbdom";
+ toVNode,
+} from 'snabbdom';
let patcher;
function getPatcher() {
if (patcher) return patcher;
-
patcher = init([
attributesModule,
]);
const contentDom = document.createElement('div');
contentDom.innerHTML = html;
getPatcher()(toVNode(domTarget), toVNode(contentDom));
-}
\ No newline at end of file
+}
* @param {Editor} editor
*/
export function listen(editor) {
-
// Replace editor content
window.$events.listen('editor::replace', ({html}) => {
editor.setContent(html);
editor.focus();
}
});
-}
\ No newline at end of file
+}
-import {register as registerShortcuts} from "./shortcuts";
-import {listen as listenForCommonEvents} from "./common-events";
-import {scrollToQueryString} from "./scrolling";
-import {listenForDragAndPaste} from "./drop-paste-handling";
-import {getPrimaryToolbar, registerAdditionalToolbars} from "./toolbars";
-import {registerCustomIcons} from "./icons";
+import {register as registerShortcuts} from './shortcuts';
+import {listen as listenForCommonEvents} from './common-events';
+import {scrollToQueryString} from './scrolling';
+import {listenForDragAndPaste} from './drop-paste-handling';
+import {getPrimaryToolbar, registerAdditionalToolbars} from './toolbars';
+import {registerCustomIcons} from './icons';
-import {getPlugin as getCodeeditorPlugin} from "./plugin-codeeditor";
-import {getPlugin as getDrawioPlugin} from "./plugin-drawio";
-import {getPlugin as getCustomhrPlugin} from "./plugins-customhr";
-import {getPlugin as getImagemanagerPlugin} from "./plugins-imagemanager";
-import {getPlugin as getAboutPlugin} from "./plugins-about";
-import {getPlugin as getDetailsPlugin} from "./plugins-details";
-import {getPlugin as getTasklistPlugin} from "./plugins-tasklist";
+import {getPlugin as getCodeeditorPlugin} from './plugin-codeeditor';
+import {getPlugin as getDrawioPlugin} from './plugin-drawio';
+import {getPlugin as getCustomhrPlugin} from './plugins-customhr';
+import {getPlugin as getImagemanagerPlugin} from './plugins-imagemanager';
+import {getPlugin as getAboutPlugin} from './plugins-about';
+import {getPlugin as getDetailsPlugin} from './plugins-details';
+import {getPlugin as getTasklistPlugin} from './plugins-tasklist';
const style_formats = [
- {title: "Large Header", format: "h2", preview: 'color: blue;'},
- {title: "Medium Header", format: "h3"},
- {title: "Small Header", format: "h4"},
- {title: "Tiny Header", format: "h5"},
- {title: "Paragraph", format: "p", exact: true, classes: ''},
- {title: "Blockquote", format: "blockquote"},
+ {title: 'Large Header', format: 'h2', preview: 'color: blue;'},
+ {title: 'Medium Header', format: 'h3'},
+ {title: 'Small Header', format: 'h4'},
+ {title: 'Tiny Header', format: 'h5'},
{
- title: "Callouts", items: [
- {title: "Information", format: 'calloutinfo'},
- {title: "Success", format: 'calloutsuccess'},
- {title: "Warning", format: 'calloutwarning'},
- {title: "Danger", format: 'calloutdanger'}
- ]
+ title: 'Paragraph', format: 'p', exact: true, classes: '',
+ },
+ {title: 'Blockquote', format: 'blockquote'},
+ {
+ title: 'Callouts',
+ items: [
+ {title: 'Information', format: 'calloutinfo'},
+ {title: 'Success', format: 'calloutsuccess'},
+ {title: 'Warning', format: 'calloutwarning'},
+ {title: 'Danger', format: 'calloutdanger'},
+ ],
},
];
calloutsuccess: {block: 'p', exact: true, attributes: {class: 'callout success'}},
calloutinfo: {block: 'p', exact: true, attributes: {class: 'callout info'}},
calloutwarning: {block: 'p', exact: true, attributes: {class: 'callout warning'}},
- calloutdanger: {block: 'p', exact: true, attributes: {class: 'callout danger'}}
+ calloutdanger: {block: 'p', exact: true, attributes: {class: 'callout danger'}},
};
const color_map = [
'#34495E', '',
'#000000', '',
- '#ffffff', ''
+ '#ffffff', '',
];
function file_picker_callback(callback, value, meta) {
-
// field_name, url, type, win
if (meta.filetype === 'file') {
- /** @type {EntitySelectorPopup} **/
+ /** @type {EntitySelectorPopup} * */
const selector = window.$components.first('entity-selector-popup');
selector.show(entity => {
callback(entity.link, {
if (meta.filetype === 'image') {
// Show image manager
- /** @type {ImageManager} **/
+ /** @type {ImageManager} * */
const imageManager = window.$components.first('image-manager');
- imageManager.show(function (image) {
+ imageManager.show(image => {
callback(image.url, {alt: image.name});
}, 'gallery');
}
-
}
/**
*/
function gatherPlugins(options) {
const plugins = [
- "image",
- "table",
- "link",
- "autolink",
- "fullscreen",
- "code",
- "customhr",
- "autosave",
- "lists",
- "codeeditor",
- "media",
- "imagemanager",
- "about",
- "details",
- "tasklist",
+ 'image',
+ 'table',
+ 'link',
+ 'autolink',
+ 'fullscreen',
+ 'code',
+ 'customhr',
+ 'autosave',
+ 'lists',
+ 'codeeditor',
+ 'media',
+ 'imagemanager',
+ 'about',
+ 'details',
+ 'tasklist',
options.textDirection === 'rtl' ? 'directionality' : '',
];
* Fetch custom HTML head content from the parent page head into the editor.
*/
function fetchCustomHeadContent() {
- const headContentLines = document.head.innerHTML.split("\n");
+ const headContentLines = document.head.innerHTML.split('\n');
const startLineIndex = headContentLines.findIndex(line => line.trim() === '<!-- Start: custom user content -->');
const endLineIndex = headContentLines.findIndex(line => line.trim() === '<!-- End: custom user content -->');
if (startLineIndex === -1 || endLineIndex === -1) {
- return ''
+ return '';
}
return headContentLines.slice(startLineIndex + 1, endLineIndex).join('\n');
}
* @param {Editor} editor
*/
function setupBrFilter(editor) {
- editor.serializer.addNodeFilter('br', function(nodes) {
+ editor.serializer.addNodeFilter('br', nodes => {
for (const node of nodes) {
if (node.parent && node.parent.name === 'code') {
const newline = tinymce.html.Node.create('#text');
icon: 'sourcecode',
onAction() {
editor.execCommand('mceToggleFormat', false, 'code');
- }
- })
- }
+ },
+ });
+ };
}
/**
* @return {Object}
*/
export function build(options) {
-
// Set language
window.tinymce.addI18n(options.language, options.translationMap);
width: '100%',
height: '100%',
selector: '#html-editor',
- cache_suffix: '?version=' + version,
+ cache_suffix: `?version=${version}`,
content_css: [
window.baseUrl('/dist/styles.css'),
],
automatic_uploads: false,
custom_elements: 'doc-root,code-block',
valid_children: [
- "-div[p|h1|h2|h3|h4|h5|h6|blockquote|code-block]",
- "+div[pre|img]",
- "-doc-root[doc-root|#text]",
- "-li[details]",
- "+code-block[pre]",
- "+doc-root[p|h1|h2|h3|h4|h5|h6|blockquote|code-block|div]"
+ '-div[p|h1|h2|h3|h4|h5|h6|blockquote|code-block]',
+ '+div[pre|img]',
+ '-doc-root[doc-root|#text]',
+ '-li[details]',
+ '+code-block[pre]',
+ '+doc-root[p|h1|h2|h3|h4|h5|h6|blockquote|code-block|div]',
].join(','),
plugins: gatherPlugins(options),
contextmenu: false,
color_map,
file_picker_callback,
paste_preprocess(plugin, args) {
- const content = args.content;
+ const {content} = args;
if (content.indexOf('<img src="file://') !== -1) {
args.content = '';
}
* @property {int} pageId
* @property {Object} translations
* @property {Object} translationMap
- */
\ No newline at end of file
+ */
-import Clipboard from "../services/clipboard";
+import Clipboard from '../services/clipboard';
let wrap;
let draggedContentEditable;
const images = clipboard.getImages();
for (const imageFile of images) {
-
- const id = "image-" + Math.random().toString(16).slice(2);
+ const id = `image-${Math.random().toString(16).slice(2)}`;
const loadingImage = window.baseUrl('/loading.gif');
event.preventDefault();
*/
async function uploadImageFile(file, pageId) {
if (file === null || file.type.indexOf('image') !== 0) {
- throw new Error(`Not an image file`);
+ throw new Error('Not an image file');
}
const remoteFilename = file.name || `image-${Date.now()}.png`;
* @param {WysiwygConfigOptions} options
*/
function dragStart(editor, options) {
- let node = editor.selection.getNode();
+ const node = editor.selection.getNode();
if (node.nodeName === 'IMG') {
wrap = editor.dom.getParent(node, '.mceTemp');
* @param {DragEvent} event
*/
function drop(editor, options, event) {
- let dom = editor.dom,
- rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
+ const {dom} = editor;
+ const rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
// Template insertion
const templateId = event.dataTransfer && event.dataTransfer.getData('bookstack/template');
event.preventDefault();
window.$http.get(`/templates/${templateId}`).then(resp => {
editor.selection.setRng(rng);
- editor.undoManager.transact(function () {
+ editor.undoManager.transact(() => {
editor.execCommand('mceInsertContent', false, resp.data.html);
});
});
} else if (wrap) {
event.preventDefault();
- editor.undoManager.transact(function () {
+ editor.undoManager.transact(() => {
editor.selection.setRng(rng);
editor.selection.setNode(wrap);
dom.remove(wrap);
// Handle contenteditable section drop
if (!event.isDefaultPrevented() && draggedContentEditable) {
event.preventDefault();
- editor.undoManager.transact(function () {
+ editor.undoManager.transact(() => {
const selectedNode = editor.selection.getNode();
const range = editor.selection.getRng();
const selectedNodeRoot = selectedNode.closest('body > *');
*/
export function listenForDragAndPaste(editor, options) {
editor.on('dragstart', () => dragStart(editor, options));
- editor.on('drop', event => drop(editor, options, event));
+ editor.on('drop', event => drop(editor, options, event));
editor.on('paste', event => paste(editor, options, event));
-}
\ No newline at end of file
+}
'table-insert-column-before': '<svg width="24" height="24"><path d="M8 19h5V5H8C6.764 5 6.766 3 8 3h11a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H8c-1.229 0-1.236-2 0-2zm7-6v6h4v-6zm0-8v6h4V5ZM3.924 11h2V9c0-1.333 2-1.333 2 0v2h2c1.335 0 1.335 2 0 2h-2v2c0 1.333-2 1.333-2 0v-2h-1.9c-1.572 0-1.113-2-.1-2z"/></svg>',
'table-insert-row-above': '<svg width="24" height="24"><path d="M5 8v5h14V8c0-1.235 2-1.234 2 0v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8C3 6.77 5 6.764 5 8zm6 7H5v4h6zm8 0h-6v4h6zM13 3.924v2h2c1.333 0 1.333 2 0 2h-2v2c0 1.335-2 1.335-2 0v-2H9c-1.333 0-1.333-2 0-2h2v-1.9c0-1.572 2-1.113 2-.1z"/></svg>',
'table-insert-row-after': '<svg width="24" height="24"><path d="M19 16v-5H5v5c0 1.235-2 1.234-2 0V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v11c0 1.229-2 1.236-2 0zm-6-7h6V5h-6zM5 9h6V5H5Zm6 11.076v-2H9c-1.333 0-1.333-2 0-2h2v-2c0-1.335 2-1.335 2 0v2h2c1.333 0 1.333 2 0 2h-2v1.9c0 1.572-2 1.113-2 .1z"/></svg>',
- 'table': '<svg width="24" height="24" xmlns="http://www.w3.org/2000/svg"><path d="M19 3a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5c0-1.1.9-2 2-2ZM5 14v5h6v-5zm14 0h-6v5h6zm0-7h-6v5h6zM5 12h6V7H5Z"/></svg>',
+ table: '<svg width="24" height="24" xmlns="http://www.w3.org/2000/svg"><path d="M19 3a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5c0-1.1.9-2 2-2ZM5 14v5h6v-5zm14 0h-6v5h6zm0-7h-6v5h6zM5 12h6V7H5Z"/></svg>',
'table-delete-table': '<svg width="24" height="24"><path d="M5 21a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14c0 1.1-.9 2-2 2zm0-2h14V5H5v14z"/><path d="m13.711 15.423-1.71-1.712-1.712 1.712c-1.14 1.14-2.852-.57-1.71-1.712l1.71-1.71-1.71-1.712c-1.143-1.142.568-2.853 1.71-1.71L12 10.288l1.711-1.71c1.141-1.142 2.852.57 1.712 1.71L13.71 12l1.626 1.626c1.345 1.345-.76 2.663-1.626 1.797z" style="fill-rule:nonzero;stroke-width:1.20992"/></svg>',
};
-
/**
* @param {Editor} editor
*/
export function registerCustomIcons(editor) {
-
for (const [name, svg] of Object.entries(icons)) {
editor.ui.registry.addIcon(name, svg);
}
-}
\ No newline at end of file
+}
*/
function showPopup(editor, code, language, callback) {
window.$components.first('code-editor').open(code, language, (newCode, newLang) => {
- callback(newCode, newLang)
- editor.focus()
+ callback(newCode, newLang);
+ editor.focus();
});
}
}
getLanguage() {
- const getLanguageFromClassList = (classes) => {
+ const getLanguageFromClassList = classes => {
const langClasses = classes.split(' ').filter(cssClass => cssClass.startsWith('language-'));
return (langClasses[0] || '').replace('language-', '');
};
this.style.height = `${height}px`;
const container = this.shadowRoot.querySelector('.CodeMirrorContainer');
- const renderEditor = (Code) => {
+ const renderEditor = Code => {
this.editor = Code.wysiwygView(container, this.shadowRoot, content, this.getLanguage());
setTimeout(() => this.style.height = null, 12);
};
- window.importVersioned('code').then((Code) => {
+ window.importVersioned('code').then(Code => {
const timeout = (Date.now() - connectedTime < 20) ? 20 : 0;
setTimeout(() => renderEditor(Code), timeout);
});
}
}
}
+
}
win.customElements.define('code-block', CodeBlockElement);
}
-
/**
* @param {Editor} editor
* @param {String} url
*/
function register(editor, url) {
-
- editor.ui.registry.addIcon('codeblock', '<svg width="24" height="24"><path d="M4 3h16c.6 0 1 .4 1 1v16c0 .6-.4 1-1 1H4a1 1 0 0 1-1-1V4c0-.6.4-1 1-1Zm1 2v14h14V5Z"/><path d="M11.103 15.423c.277.277.277.738 0 .922a.692.692 0 0 1-1.106 0l-4.057-3.78a.738.738 0 0 1 0-1.107l4.057-3.872c.276-.277.83-.277 1.106 0a.724.724 0 0 1 0 1.014L7.6 12.012ZM12.897 8.577c-.245-.312-.2-.675.08-.955.28-.281.727-.27 1.027.033l4.057 3.78a.738.738 0 0 1 0 1.107l-4.057 3.872c-.277.277-.83.277-1.107 0a.724.724 0 0 1 0-1.014l3.504-3.412z"/></svg>')
+ editor.ui.registry.addIcon('codeblock', '<svg width="24" height="24"><path d="M4 3h16c.6 0 1 .4 1 1v16c0 .6-.4 1-1 1H4a1 1 0 0 1-1-1V4c0-.6.4-1 1-1Zm1 2v14h14V5Z"/><path d="M11.103 15.423c.277.277.277.738 0 .922a.692.692 0 0 1-1.106 0l-4.057-3.78a.738.738 0 0 1 0-1.107l4.057-3.872c.276-.277.83-.277 1.106 0a.724.724 0 0 1 0 1.014L7.6 12.012ZM12.897 8.577c-.245-.312-.2-.675.08-.955.28-.281.727-.27 1.027.033l4.057 3.78a.738.738 0 0 1 0 1.107l-4.057 3.872c-.277.277-.83.277-1.107 0a.724.724 0 0 1 0-1.014l3.504-3.412z"/></svg>');
editor.ui.registry.addButton('codeeditor', {
tooltip: 'Insert code block',
icon: 'codeblock',
onAction() {
editor.execCommand('codeeditor');
- }
+ },
});
editor.ui.registry.addButton('editcodeeditor', {
icon: 'edit-block',
onAction() {
editor.execCommand('codeeditor');
- }
+ },
});
editor.addCommand('codeeditor', () => {
});
editor.on('dblclick', event => {
- let selectedNode = editor.selection.getNode();
+ const selectedNode = editor.selection.getNode();
if (elemIsCodeBlock(selectedNode)) {
showPopupForCodeBlock(editor, selectedNode);
}
});
editor.on('PreInit', () => {
- editor.parser.addNodeFilter('pre', function(elms) {
+ editor.parser.addNodeFilter('pre', elms => {
for (const el of elms) {
const wrapper = tinymce.html.Node.create('code-block', {
contenteditable: 'false',
}
});
- editor.parser.addNodeFilter('code-block', function(elms) {
+ editor.parser.addNodeFilter('code-block', elms => {
for (const el of elms) {
el.attr('contenteditable', 'false');
}
});
- editor.serializer.addNodeFilter('code-block', function(elms) {
+ editor.serializer.addNodeFilter('code-block', elms => {
for (const el of elms) {
el.unwrap();
}
});
editor.ui.registry.addContextToolbar('codeeditor', {
- predicate: function (node) {
+ predicate(node) {
return node.nodeName.toLowerCase() === 'code-block';
},
items: 'editcodeeditor',
position: 'node',
- scope: 'node'
+ scope: 'node',
});
editor.on('PreInit', () => {
*/
export function getPlugin(options) {
return register;
-}
\ No newline at end of file
+}
-import DrawIO from "../services/drawio";
+import DrawIO from '../services/drawio';
let pageEditor = null;
let currentNode = null;
pageEditor = mceEditor;
currentNode = selectedNode;
- /** @type {ImageManager} **/
+ /** @type {ImageManager} * */
const imageManager = window.$components.first('image-manager');
- imageManager.show(function (image) {
+ imageManager.show(image => {
if (selectedNode) {
const imgElem = selectedNode.querySelector('img');
- pageEditor.undoManager.transact(function () {
+ pageEditor.undoManager.transact(() => {
pageEditor.dom.setAttrib(imgElem, 'src', image.url);
pageEditor.dom.setAttrib(selectedNode, 'drawio-diagram', image.id);
});
}
async function updateContent(pngData) {
- const id = "image-" + Math.random().toString(16).slice(2);
+ const id = `image-${Math.random().toString(16).slice(2)}`;
const loadingImage = window.baseUrl('/loading.gif');
- const handleUploadError = (error) => {
+ const handleUploadError = error => {
if (error.status === 413) {
window.$events.emit('error', options.translations.serverUploadLimitText);
} else {
// Handle updating an existing image
if (currentNode) {
DrawIO.close();
- let imgElem = currentNode.querySelector('img');
+ const imgElem = currentNode.querySelector('img');
try {
const img = await DrawIO.upload(pngData, options.pageId);
- pageEditor.undoManager.transact(function () {
+ pageEditor.undoManager.transact(() => {
pageEditor.dom.setAttrib(imgElem, 'src', img.url);
pageEditor.dom.setAttrib(currentNode, 'drawio-diagram', img.id);
});
DrawIO.close();
try {
const img = await DrawIO.upload(pngData, options.pageId);
- pageEditor.undoManager.transact(function () {
+ pageEditor.undoManager.transact(() => {
pageEditor.dom.setAttrib(id, 'src', img.url);
pageEditor.dom.get(id).parentNode.setAttribute('drawio-diagram', img.id);
});
}, 5);
}
-
function drawingInit() {
if (!currentNode) {
return Promise.resolve('');
export function getPlugin(providedOptions) {
options = providedOptions;
return function(editor, url) {
-
editor.addCommand('drawio', () => {
const selectedNode = editor.selection.getNode();
showDrawingEditor(editor, isDrawing(selectedNode) ? selectedNode : null);
});
- editor.ui.registry.addIcon('diagram', `<svg width="24" height="24" fill="${options.darkMode ? '#BBB' : '#000000'}" xmlns="http://www.w3.org/2000/svg"><path d="M20.716 7.639V2.845h-4.794v1.598h-7.99V2.845H3.138v4.794h1.598v7.99H3.138v4.794h4.794v-1.598h7.99v1.598h4.794v-4.794h-1.598v-7.99zM4.736 4.443h1.598V6.04H4.736zm1.598 14.382H4.736v-1.598h1.598zm9.588-1.598h-7.99v-1.598H6.334v-7.99h1.598V6.04h7.99v1.598h1.598v7.99h-1.598zm3.196 1.598H17.52v-1.598h1.598zM17.52 6.04V4.443h1.598V6.04zm-4.21 7.19h-2.79l-.582 1.599H8.643l2.717-7.191h1.119l2.724 7.19h-1.302zm-2.43-1.006h2.086l-1.039-3.06z"/></svg>`)
+ editor.ui.registry.addIcon('diagram', `<svg width="24" height="24" fill="${options.darkMode ? '#BBB' : '#000000'}" xmlns="http://www.w3.org/2000/svg"><path d="M20.716 7.639V2.845h-4.794v1.598h-7.99V2.845H3.138v4.794h1.598v7.99H3.138v4.794h4.794v-1.598h7.99v1.598h4.794v-4.794h-1.598v-7.99zM4.736 4.443h1.598V6.04H4.736zm1.598 14.382H4.736v-1.598h1.598zm9.588-1.598h-7.99v-1.598H6.334v-7.99h1.598V6.04h7.99v1.598h1.598v7.99h-1.598zm3.196 1.598H17.52v-1.598h1.598zM17.52 6.04V4.443h1.598V6.04zm-4.21 7.19h-2.79l-.582 1.599H8.643l2.717-7.191h1.119l2.724 7.19h-1.302zm-2.43-1.006h2.086l-1.039-3.06z"/></svg>`);
editor.ui.registry.addSplitButton('drawio', {
tooltip: 'Insert/edit drawing',
type: 'choiceitem',
text: 'Drawing manager',
value: 'drawing-manager',
- }
+ },
]);
},
onItemAction(api, value) {
const selectedNode = editor.selection.getNode();
showDrawingManager(editor, isDrawing(selectedNode) ? selectedNode : null);
}
- }
+ },
});
editor.on('dblclick', event => {
- let selectedNode = editor.selection.getNode();
+ const selectedNode = editor.selection.getNode();
if (!isDrawing(selectedNode)) return;
showDrawingEditor(editor, selectedNode);
});
- editor.on('SetContent', function () {
+ editor.on('SetContent', () => {
const drawings = editor.dom.select('body > div[drawio-diagram]');
if (!drawings.length) return;
- editor.undoManager.transact(function () {
+ editor.undoManager.transact(() => {
for (const drawing of drawings) {
drawing.setAttribute('contenteditable', 'false');
}
});
});
-
};
-}
\ No newline at end of file
+}
* @param {String} url
*/
function register(editor, url) {
-
const aboutDialog = {
title: 'About the WYSIWYG Editor',
url: window.baseUrl('/help/wysiwyg'),
tooltip: 'About the editor',
onAction() {
tinymce.activeEditor.windowManager.openUrl(aboutDialog);
- }
+ },
});
-
}
-
/**
* @param {WysiwygConfigOptions} options
* @return {register}
*/
export function getPlugin(options) {
return register;
-}
\ No newline at end of file
+}
* @param {String} url
*/
function register(editor, url) {
- editor.addCommand('InsertHorizontalRule', function () {
- let hrElem = document.createElement('hr');
- let cNode = editor.selection.getNode();
- let parentNode = cNode.parentNode;
+ editor.addCommand('InsertHorizontalRule', () => {
+ const hrElem = document.createElement('hr');
+ const cNode = editor.selection.getNode();
+ const {parentNode} = cNode;
parentNode.insertBefore(hrElem, cNode);
});
tooltip: 'Insert horizontal line',
onAction() {
editor.execCommand('InsertHorizontalRule');
- }
+ },
});
}
-
/**
* @param {WysiwygConfigOptions} options
* @return {register}
*/
export function getPlugin(options) {
return register;
-}
\ No newline at end of file
+}
* @param {Editor} editor
* @param {String} url
*/
-import {blockElementTypes} from "./util";
+import {blockElementTypes} from './util';
function register(editor, url) {
-
editor.ui.registry.addIcon('details', '<svg width="24" height="24"><path d="M8.2 9a.5.5 0 0 0-.4.8l4 5.6a.5.5 0 0 0 .8 0l4-5.6a.5.5 0 0 0-.4-.8ZM20.122 18.151h-16c-.964 0-.934 2.7 0 2.7h16c1.139 0 1.173-2.7 0-2.7zM20.122 3.042h-16c-.964 0-.934 2.7 0 2.7h16c1.139 0 1.173-2.7 0-2.7z"/></svg>');
editor.ui.registry.addIcon('togglefold', '<svg height="24" width="24"><path d="M8.12 19.3c.39.39 1.02.39 1.41 0L12 16.83l2.47 2.47c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41l-3.17-3.17c-.39-.39-1.02-.39-1.41 0l-3.17 3.17c-.4.38-.4 1.02-.01 1.41zm7.76-14.6c-.39-.39-1.02-.39-1.41 0L12 7.17 9.53 4.7c-.39-.39-1.02-.39-1.41 0-.39.39-.39 1.03 0 1.42l3.17 3.17c.39.39 1.02.39 1.41 0l3.17-3.17c.4-.39.4-1.03.01-1.42z"/></svg>');
editor.ui.registry.addIcon('togglelabel', '<svg height="18" width="18" viewBox="0 0 24 24"><path d="M21.41,11.41l-8.83-8.83C12.21,2.21,11.7,2,11.17,2H4C2.9,2,2,2.9,2,4v7.17c0,0.53,0.21,1.04,0.59,1.41l8.83,8.83 c0.78,0.78,2.05,0.78,2.83,0l7.17-7.17C22.2,13.46,22.2,12.2,21.41,11.41z M6.5,8C5.67,8,5,7.33,5,6.5S5.67,5,6.5,5S8,5.67,8,6.5 S7.33,8,6.5,8z"/></svg>');
tooltip: 'Insert collapsible block',
onAction() {
editor.execCommand('InsertDetailsBlock');
- }
+ },
});
editor.ui.registry.addButton('removedetails', {
icon: 'table-delete-table',
tooltip: 'Unwrap',
onAction() {
- unwrapDetailsInSelection(editor)
- }
+ unwrapDetailsInSelection(editor);
+ },
});
editor.ui.registry.addButton('editdetials', {
tooltip: 'Edit label',
onAction() {
showDetailLabelEditWindow(editor);
- }
+ },
});
editor.on('dblclick', event => {
const details = getSelectedDetailsBlock(editor);
details.toggleAttribute('open');
editor.focus();
- }
+ },
});
- editor.addCommand('InsertDetailsBlock', function () {
+ editor.addCommand('InsertDetailsBlock', () => {
let content = editor.selection.getContent({format: 'html'});
const details = document.createElement('details');
const summary = document.createElement('summary');
- const id = 'details-' + Date.now();
- details.setAttribute('data-id', id)
+ const id = `details-${Date.now()}`;
+ details.setAttribute('data-id', id);
details.appendChild(summary);
if (!content) {
});
editor.ui.registry.addContextToolbar('details', {
- predicate: function (node) {
+ predicate(node) {
return node.nodeName.toLowerCase() === 'details';
},
items: 'editdetials toggledetails removedetails',
position: 'node',
- scope: 'node'
+ scope: 'node',
});
editor.on('PreInit', () => {
buttons: [
{
type: 'cancel',
- text: 'Cancel'
+ text: 'Cancel',
},
{
type: 'submit',
text: 'Save',
primary: true,
- }
+ },
],
onSubmit(api) {
const {summary} = api.getData();
setSummary(editor, summary);
api.close();
- }
- }
+ },
+ };
}
function setSummary(editor, summaryContent) {
* @param {Editor} editor
*/
function setupElementFilters(editor) {
- editor.parser.addNodeFilter('details', function(elms) {
+ editor.parser.addNodeFilter('details', elms => {
for (const el of elms) {
ensureDetailsWrappedInEditable(el);
}
});
- editor.serializer.addNodeFilter('details', function(elms) {
+ editor.serializer.addNodeFilter('details', elms => {
for (const el of elms) {
unwrapDetailsEditable(el);
el.attr('open', null);
}
});
- editor.serializer.addNodeFilter('doc-root', function(elms) {
+ editor.serializer.addNodeFilter('doc-root', elms => {
for (const el of elms) {
el.unwrap();
}
}
}
-
/**
* @param {WysiwygConfigOptions} options
* @return {register}
*/
export function getPlugin(options) {
return register;
-}
\ No newline at end of file
+}
icon: 'image',
tooltip: 'Insert image',
onAction() {
- /** @type {ImageManager} **/
+ /** @type {ImageManager} * */
const imageManager = window.$components.first('image-manager');
- imageManager.show(function (image) {
+ imageManager.show(image => {
const imageUrl = image.thumbs.display || image.url;
let html = `<a href="${image.url}" target="_blank">`;
html += `<img src="${imageUrl}" alt="${image.name}">`;
html += '</a>';
editor.execCommand('mceInsertContent', false, html);
}, 'gallery');
- }
+ },
});
}
-
/**
* @param {WysiwygConfigOptions} options
* @return {register}
*/
export function getPlugin(options) {
return register;
-}
\ No newline at end of file
+}
}
-
/**
* @param {WysiwygConfigOptions} options
* @return {register}
*/
export function getPlugin(options) {
return register;
-}
\ No newline at end of file
+}
* @param {String} url
*/
function register(editor, url) {
-
// Tasklist UI buttons
editor.ui.registry.addIcon('tasklist', '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M22,8c0-0.55-0.45-1-1-1h-7c-0.55,0-1,0.45-1,1s0.45,1,1,1h7C21.55,9,22,8.55,22,8z M13,16c0,0.55,0.45,1,1,1h7 c0.55,0,1-0.45,1-1c0-0.55-0.45-1-1-1h-7C13.45,15,13,15.45,13,16z M10.47,4.63c0.39,0.39,0.39,1.02,0,1.41l-4.23,4.25 c-0.39,0.39-1.02,0.39-1.42,0L2.7,8.16c-0.39-0.39-0.39-1.02,0-1.41c0.39-0.39,1.02-0.39,1.41,0l1.42,1.42l3.54-3.54 C9.45,4.25,10.09,4.25,10.47,4.63z M10.48,12.64c0.39,0.39,0.39,1.02,0,1.41l-4.23,4.25c-0.39,0.39-1.02,0.39-1.42,0L2.7,16.16 c-0.39-0.39-0.39-1.02,0-1.41s1.02-0.39,1.41,0l1.42,1.42l3.54-3.54C9.45,12.25,10.09,12.25,10.48,12.64L10.48,12.64z"/></svg>');
editor.ui.registry.addToggleButton('tasklist', {
const inList = parentListEl && parentListEl.classList.contains('task-list-item');
api.setActive(Boolean(inList));
});
- }
+ },
});
// Tweak existing bullet list button active state to not be active
// Instead we quickly jump through an ordered list first if we're within a tasklist.
if (elementWithinTaskList(editor.selection.getNode())) {
editor.execCommand('InsertOrderedList', null, {
- 'list-item-attributes': {class: null}
+ 'list-item-attributes': {class: null},
});
}
editor.execCommand('InsertUnorderedList', null, {
- 'list-item-attributes': {class: null}
+ 'list-item-attributes': {class: null},
});
};
// Tweak existing number list to not allow classes on child items
const existingNumListButton = editor.ui.registry.getAll().buttons.numlist;
existingNumListButton.onAction = function() {
editor.execCommand('InsertOrderedList', null, {
- 'list-item-attributes': {class: null}
+ 'list-item-attributes': {class: null},
});
};
// Setup filters on pre-init
editor.on('PreInit', () => {
- editor.parser.addNodeFilter('li', function(nodes) {
+ editor.parser.addNodeFilter('li', nodes => {
for (const node of nodes) {
if (node.attributes.map.class === 'task-list-item') {
parseTaskListNode(node);
}
}
});
- editor.serializer.addNodeFilter('li', function(nodes) {
+ editor.serializer.addNodeFilter('li', nodes => {
for (const node of nodes) {
if (node.attributes.map.class === 'task-list-item') {
serializeTaskListNode(node);
});
// Handle checkbox click in editor
- editor.on('click', function(event) {
+ editor.on('click', event => {
const clickedEl = event.target;
if (clickedEl.nodeName === 'LI' && clickedEl.classList.contains('task-list-item')) {
handleTaskListItemClick(event, clickedEl, editor);
editor.undoManager.transact(() => {
if (clickedEl.hasAttribute('checked')) {
clickedEl.removeAttribute('checked');
- } else {
+ } else {
clickedEl.setAttribute('checked', 'checked');
}
});
*/
export function getPlugin(options) {
return register;
-}
\ No newline at end of file
+}
editor.selection.select(element, true);
editor.selection.collapse(false);
editor.focus();
-}
\ No newline at end of file
+}
export function register(editor) {
// Headers
for (let i = 1; i < 5; i++) {
- editor.shortcuts.add('meta+' + i, '', ['FormatBlock', false, 'h' + (i+1)]);
+ editor.shortcuts.add(`meta+${i}`, '', ['FormatBlock', false, `h${i + 1}`]);
}
// Other block shortcuts
});
// Loop through callout styles
- editor.shortcuts.add('meta+9', '', function() {
+ editor.shortcuts.add('meta+9', '', () => {
const selectedNode = editor.selection.getNode();
const callout = selectedNode ? selectedNode.closest('.callout') : null;
const newFormatIndex = (currentFormatIndex + 1) % formats.length;
const newFormat = formats[newFormatIndex];
- editor.formatter.apply('callout' + newFormat);
+ editor.formatter.apply(`callout${newFormat}`);
});
// Link selector shortcut
- editor.shortcuts.add('meta+shift+K', '', function() {
- /** @var {EntitySelectorPopup} **/
+ editor.shortcuts.add('meta+shift+K', '', () => {
+ /** @var {EntitySelectorPopup} * */
const selectorPopup = window.$components.first('entity-selector-popup');
- selectorPopup.show(function(entity) {
-
+ selectorPopup.show(entity => {
if (editor.selection.isCollapsed()) {
editor.insertContent(editor.dom.createHTML('a', {href: entity.link}, editor.dom.encode(entity.name)));
} else {
editor.selection.collapse(false);
editor.focus();
- })
+ });
});
-}
\ No newline at end of file
+}
'bullist numlist listoverflow',
textDirPlugins,
'link table imagemanager-insert insertoverflow',
- 'code about fullscreen'
+ 'code about fullscreen',
];
return toolbar.filter(row => Boolean(row)).join(' | ');
editor.ui.registry.addGroupToolbarButton('formatoverflow', {
icon: 'more-drawer',
tooltip: 'More',
- items: 'strikethrough superscript subscript inlinecode removeformat'
+ items: 'strikethrough superscript subscript inlinecode removeformat',
});
editor.ui.registry.addGroupToolbarButton('listoverflow', {
icon: 'more-drawer',
tooltip: 'More',
- items: 'tasklist outdent indent'
+ items: 'tasklist outdent indent',
});
editor.ui.registry.addGroupToolbarButton('insertoverflow', {
icon: 'more-drawer',
tooltip: 'More',
- items: 'customhr codeeditor drawio media details'
+ items: 'customhr codeeditor drawio media details',
});
}
},
position: 'node',
scope: 'node',
- items: 'link unlink openlink'
+ items: 'link unlink openlink',
});
}
},
position: 'node',
scope: 'node',
- items: 'image'
+ items: 'image',
});
}
registerPrimaryToolbarGroups(editor);
registerLinkContextToolbar(editor);
registerImageContextToolbar(editor);
-}
\ No newline at end of file
+}
-
-
export const blockElementTypes = [
'p',
'h1',
'details',
'ul',
'ol',
- 'table'
-];
\ No newline at end of file
+ 'table',
+];