code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
it.skip('should convert the "\'" character to the corresponding HTML entity', function () { return scribeNode.getInnerHTML().then(function (innerHTML) { expect(innerHTML).to.have.html('<p>&#39;</p>'); }); });
FIXME: Fails because `element.insertHTML = '<p>&#39;</p>'` unescapes the HTML entity (for double and single quotes). This can be fixed by replacing these tests with unit tests.
(anonymous) ( )
javascript
guardian/scribe
test-old/formatters.spec.js
https://github.com/guardian/scribe/blob/master/test-old/formatters.spec.js
Apache-2.0
it('should convert HTML characters to their corresponding HTML entities', function () { return scribeNode.getInnerHTML().then(function (innerHTML) { expect(innerHTML).to.have.html('<p>&lt;p&gt;1&lt;/p&gt;</p>'); }); });
FIXME: "&", "<" and ">" are escaped natively when you set `Element.innerHTML`. Thus, those tests would pass with or without the formatter. This test brings everything together to make sure it really works. This could be fixed by having unit tests.
(anonymous) ( )
javascript
guardian/scribe
test-old/formatters.spec.js
https://github.com/guardian/scribe/blob/master/test-old/formatters.spec.js
Apache-2.0
require(['../../bower_components/scribe-plugin-sanitizer/src/scribe-plugin-sanitizer'], function (scribePluginSanitizer) { window.scribe.use(scribePluginSanitizer({ tags: { p: {}, b: {} }})); done(); });
The file below contains the formatter which corrects invalid HTML, ideally it should live in core and we wouldn't need to require it *
(anonymous) ( scribePluginSanitizer )
javascript
guardian/scribe
test-old/formatters.spec.js
https://github.com/guardian/scribe/blob/master/test-old/formatters.spec.js
Apache-2.0
describe('remove invalid B tags wrapping block elements', function () { beforeEach(function () { return driver.executeAsyncScript(function (done) { /** * The file below contains the formatter which corrects invalid HTML, * ideally it should live in core and we wouldn't need to require it **/ require(['../../bower_components/scribe-plugin-sanitizer/src/scribe-plugin-sanitizer'], function (scribePluginSanitizer) { window.scribe.use(scribePluginSanitizer({ tags: { p: {}, b: {} }})); done(); }); }); }); whenInsertingHTMLOf('<b><p>1</p></b>', function() { it("should delete the wrapping B", function() { return scribeNode.getInnerHTML().then(function (innerHTML) { expect(innerHTML).to.have.html('<p>1</p>'); }); }); }); whenInsertingHTMLOf('<b><p>1</p>2</b>', function () { it('should delete invalid B and wrap second text node in a P', function () { return scribeNode.getInnerHTML().then(function (innerHTML) { expect(innerHTML).to.have.html('<p>1</p><p>2</p>'); }); }); }); });
Tags in form <p><b></p> etc. should be removed *
(anonymous) ( )
javascript
guardian/scribe
test-old/formatters.spec.js
https://github.com/guardian/scribe/blob/master/test-old/formatters.spec.js
Apache-2.0
function removeChromeArtifacts(parentElement) { function isInlineWithStyle(parentStyle, element) { return window.getComputedStyle(element).lineHeight === parentStyle.lineHeight; } var nodes = Immutable.List(parentElement.querySelectorAll(inlineElementNames .map(function(elName) { return elName + '[style*="line-height"]' }) .join(',') )); nodes = nodes.filter(isInlineWithStyle.bind(null, window.getComputedStyle(parentElement))); var emptySpans = Immutable.List(); nodes.forEach(function(node) { node.style.lineHeight = null; if (node.getAttribute('style') === '') { node.removeAttribute('style'); } if (node.nodeName === 'SPAN' && node.attributes.length === 0) { emptySpans = emptySpans.push(node); } }); emptySpans.forEach(function(node) { unwrap(node.parentNode, node); }); }
Chrome: If a parent node has a CSS `line-height` when we apply the insertHTML command, Chrome appends a SPAN to plain content with inline styling replicating that `line-height`, and adjusts the `line-height` on inline elements. As per: http://jsbin.com/ilEmudi/4/edit?css,js,output More from the web: http://stackoverflow.com/q/15015019/40352
removeChromeArtifacts ( parentElement )
javascript
guardian/scribe
src/node.js
https://github.com/guardian/scribe/blob/master/src/node.js
Apache-2.0
function checkOptions(userSuppliedOptions) { var options = userSuppliedOptions || {}; // Remove invalid plugins if (options.defaultPlugins) { options.defaultPlugins = options.defaultPlugins.filter(filterByPluginExists(defaultOptions.defaultPlugins)); } if (options.defaultFormatters) { options.defaultFormatters = options.defaultFormatters.filter(filterByPluginExists(defaultOptions.defaultFormatters)); } return Object.freeze(defaults(options, defaultOptions)); }
Overrides defaults with user's options @param {Object} userSuppliedOptions The user's options @return {Object} The overridden options
checkOptions ( userSuppliedOptions )
javascript
guardian/scribe
src/config.js
https://github.com/guardian/scribe/blob/master/src/config.js
Apache-2.0
function sortByPlugin(priorityPlugin) { return function (pluginCurrent, pluginNext) { if (pluginCurrent === priorityPlugin) { // pluginCurrent comes before plugin next return -1; } else if (pluginNext === priorityPlugin) { // pluginNext comes before pluginCurrent return 1; } // Do no swap return 0; } }
Sorts a plugin list by a specified plugin name @param {String} priorityPlugin The plugin name to be given priority @return {Function} Sorting function for the given plugin name
sortByPlugin ( priorityPlugin )
javascript
guardian/scribe
src/config.js
https://github.com/guardian/scribe/blob/master/src/config.js
Apache-2.0
function filterByPluginExists(pluginList) { return function (plugin) { return pluginList.indexOf(plugin) !== -1; } }
Filters a list of plugins by their validity @param {Array<String>} pluginList List of plugins to check against @return {Function} Filtering function based upon the given list
filterByPluginExists ( pluginList )
javascript
guardian/scribe
src/config.js
https://github.com/guardian/scribe/blob/master/src/config.js
Apache-2.0
function filterByBlockLevelMode(isBlockLevelMode) { return function (plugin) { return (isBlockLevelMode ? blockModePlugins : inlineModePlugins).indexOf(plugin) !== -1; } } /** * Filters a list of plugins by their validity * * @param {Array<String>} pluginList List of plugins to check against * @return {Function} Filtering function based upon the given list */ function filterByPluginExists(pluginList) { return function (plugin) { return pluginList.indexOf(plugin) !== -1; } } return { defaultOptions: defaultOptions, checkOptions: checkOptions, sortByPlugin: sortByPlugin, filterByBlockLevelMode: filterByBlockLevelMode, filterByPluginExists: filterByPluginExists } });
Filters a list of plugins by block level / inline level mode. @param {Boolean} isBlockLevelMode Whether block level mode is enabled @return {Function} Filtering function based upon the given mode
filterByBlockLevelMode ( isBlockLevelMode )
javascript
guardian/scribe
src/config.js
https://github.com/guardian/scribe/blob/master/src/config.js
Apache-2.0
Scribe.prototype.registerHTMLFormatter = function (phase, formatter) { this._htmlFormatterFactory.formatters[phase] = this._htmlFormatterFactory.formatters[phase].push(formatter); };
Applies HTML formatting to all editor text. @param {String} phase sanitize/normalize/export are the standard phases @param {Function} fn Function that takes the current editor HTML and returns a formatted version.
Scribe.prototype.registerHTMLFormatter ( phase , formatter )
javascript
guardian/scribe
src/scribe.js
https://github.com/guardian/scribe/blob/master/src/scribe.js
Apache-2.0
function Selection() { this.selection = rootDoc.getSelection(); if (this.selection.rangeCount && this.selection.anchorNode) { var startNode = this.selection.anchorNode; var startOffset = this.selection.anchorOffset; var endNode = this.selection.focusNode; var endOffset = this.selection.focusOffset; // if the range starts and ends on the same node, then we must swap the // offsets if ever focusOffset is smaller than anchorOffset if (startNode === endNode && endOffset < startOffset) { var tmp = startOffset; startOffset = endOffset; endOffset = tmp; } // if the range ends *before* it starts, then we must reverse the range else if (nodeHelpers.isBefore(endNode, startNode)) { var tmpNode = startNode, tmpOffset = startOffset; startNode = endNode; startOffset = endOffset; endNode = tmpNode; endOffset = tmpOffset; } // create the range to avoid chrome bug from getRangeAt / window.getSelection() // https://code.google.com/p/chromium/issues/detail?id=380690 this.range = document.createRange(); this.range.setStart(startNode, startOffset); this.range.setEnd(endNode, endOffset); } }
Wrapper for object holding currently selected text.
Selection ( )
javascript
guardian/scribe
src/api/selection.js
https://github.com/guardian/scribe/blob/master/src/api/selection.js
Apache-2.0
Selection.prototype.getContaining = function (nodeFilter) { var range = this.range; if (!range) { return; } var node = this.range.commonAncestorContainer; return ! (node && scribe.el === node) && nodeFilter(node) ? node : nodeHelpers.getAncestor(node, scribe.el, nodeFilter); };
@returns Closest ancestor Node satisfying nodeFilter. Undefined if none exist before reaching Scribe container.
Selection.prototype.getContaining ( nodeFilter )
javascript
guardian/scribe
src/api/selection.js
https://github.com/guardian/scribe/blob/master/src/api/selection.js
Apache-2.0
scribe.el.addEventListener('keydown', function (event) { if (event.keyCode === 13) { // enter var selection = new scribe.api.Selection(); var range = selection.range; var blockNode = selection.getContaining(function (node) { return node.nodeName === 'LI' || (/^(H[1-6])$/).test(node.nodeName); }); if (! blockNode) { event.preventDefault(); scribe.transactionManager.run(function () { if (!range.collapsed) { range.deleteContents(); } /** * Firefox: Delete the bogus BR as we insert another one later. * We have to do this because otherwise the browser will believe * there is content to the right of the selection. */ if (scribe.el.lastChild && scribe.el.lastChild.nodeName === 'BR') { scribe.el.removeChild(scribe.el.lastChild); } var brNode = document.createElement('br'); range.insertNode(brNode); // Safari does not update the endoffset after inserting the BR element // so we have to do it ourselves. // References: // https://bugs.webkit.org/show_bug.cgi?id=63538#c3 // https://dom.spec.whatwg.org/#dom-range-selectnode range.setEndAfter(brNode); // After inserting the BR into the range is no longer collapsed, so // we have to collapse it again. // TODO: Older versions of Firefox require this argument even though // it is supposed to be optional. Proxy/polyfill? range.collapse(false); /** * Chrome: If there is no right-hand side content, inserting a BR * will not appear to create a line break. * Firefox: If there is no right-hand side content, inserting a BR * will appear to create a weird "half-line break". * * Possible solution: Insert two BRs. * ✓ Chrome: Inserting two BRs appears to create a line break. * Typing will then delete the bogus BR element. * Firefox: Inserting two BRs will create two line breaks. * * Solution: Only insert two BRs if there is no right-hand * side content. * * If the user types on a line immediately after a BR element, * Chrome will replace the BR element with the typed characters, * whereas Firefox will not. Thus, to satisfy Firefox we have to * insert a bogus BR element on initialization (see below). */ var contentToEndRange = range.cloneRange(); if (scribe.el.lastChild) { contentToEndRange.setEndAfter(scribe.el.lastChild); } // Get the content from the range to the end of the heading var contentToEndFragment = contentToEndRange.cloneContents(); // If there is not already a right hand side content we need to // insert a bogus BR element. if (! hasContent(contentToEndFragment)) { var bogusBrNode = document.createElement('br'); range.insertNode(bogusBrNode); } var newRange = range.cloneRange(); newRange.setStartAfter(brNode); newRange.setEndAfter(brNode); selection.selection.removeAllRanges(); selection.selection.addRange(newRange); }); } } }.bind(this));
Firefox has a `insertBrOnReturn` command, but this is not a part of any standard. One day we might have an `insertLineBreak` command, proposed by this spec: https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#the-insertlinebreak-command As per: http://jsbin.com/IQUraXA/1/edit?html,js,output
(anonymous) ( event )
javascript
guardian/scribe
src/plugins/core/inline-elements-mode.js
https://github.com/guardian/scribe/blob/master/src/plugins/core/inline-elements-mode.js
Apache-2.0
scribe.el.addEventListener('focus', function placeCaretOnFocus() { var selection = new scribe.api.Selection(); // In Chrome, the range is not created on or before this event loop. // It doesn’t matter because this is a fix for Firefox. if (selection.range) { var isFirefoxBug = scribe.allowsBlockElements() && selection.range.startContainer === scribe.el; if (isFirefoxBug) { var focusElement = nodeHelpers.firstDeepestChild(scribe.el); var range = selection.range; range.setStart(focusElement, 0); range.setEnd(focusElement, 0); selection.selection.removeAllRanges(); selection.selection.addRange(range); } } }.bind(scribe));
Firefox: Giving focus to a `contenteditable` will place the caret outside of any block elements. Chrome behaves correctly by placing the caret at the earliest point possible inside the first block element. As per: http://jsbin.com/eLoFOku/1/edit?js,console,output We detect when this occurs and fix it by placing the caret ourselves.
placeCaretOnFocus ( )
javascript
guardian/scribe
src/plugins/core/events.js
https://github.com/guardian/scribe/blob/master/src/plugins/core/events.js
Apache-2.0
var applyFormatters = function() { if (!scribe._skipFormatters) { var selection = new scribe.api.Selection(); var isEditorActive = selection.range; var runFormatters = function () { if (isEditorActive) { selection.placeMarkers(); } scribe.setHTML(scribe._htmlFormatterFactory.format(scribe.getHTML())); selection.selectMarkers(); }.bind(scribe); // We only want to wrap the formatting in a transaction if the editor is // active. If the DOM is mutated when the editor isn't active (e.g. // `scribe.setContent`), we do not want to push to the history. (This // happens on the first `focus` event). // The previous check is no longer needed, and the above comments are no longer valid. // Now `scribe.setContent` updates the content manually, and `scribe.pushHistory` // will not detect any changes, and nothing will be push into the history. // Any mutations made without `scribe.getContent` will be pushed into the history normally. // Pass content through formatters, place caret back scribe.transactionManager.run(runFormatters); } delete scribe._skipFormatters; }.bind(scribe);
Apply the formatters when there is a DOM mutation.
applyFormatters ( )
javascript
guardian/scribe
src/plugins/core/events.js
https://github.com/guardian/scribe/blob/master/src/plugins/core/events.js
Apache-2.0
scribe.el.addEventListener('paste', function handlePaste(event) { /** * Browsers without the Clipboard API (specifically `ClipboardEvent.clipboardData`) * will execute the second branch here. * * Chrome on android provides `ClipboardEvent.clipboardData` but the types array is not filled */ if (event.clipboardData && event.clipboardData.types.length > 0) { event.preventDefault(); if (Immutable.List(event.clipboardData.types).includes('text/html')) { scribe.insertHTML(event.clipboardData.getData('text/html')); } else { scribe.insertPlainText(event.clipboardData.getData('text/plain')); } } else { /** * If the browser doesn't have `ClipboardEvent.clipboardData`, we run through a * sequence of events: * * - Save the text selection * - Focus another, hidden textarea so we paste there * - Copy the pasted content of said textarea * - Give focus back to the scribe * - Restore the text selection * * This is required because, without access to the Clipboard API, there is literally * no other way to manipulate content on paste. * As per: https://github.com/jejacks0n/mercury/issues/23#issuecomment-2308347 * * Firefox <= 21 * https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent.clipboardData */ var selection = new scribe.api.Selection(); // Store the caret position selection.placeMarkers(); var bin = document.createElement('div'); document.body.appendChild(bin); bin.setAttribute('contenteditable', true); bin.focus(); // Wait for the paste to happen (next loop?) setTimeout(function () { var data = bin.innerHTML; bin.parentNode.removeChild(bin); // Restore the caret position selection.selectMarkers(); /** * Firefox 19 (and maybe others): even though the applied range * exists within the Scribe instance, we need to focus it. */ scribe.el.focus(); scribe.insertHTML(data); }, 1); } });
TODO: could we implement this as a polyfill for `event.clipboardData` instead? I also don't like how it has the authority to perform `event.preventDefault`.
handlePaste ( event )
javascript
guardian/scribe
src/plugins/core/events.js
https://github.com/guardian/scribe/blob/master/src/plugins/core/events.js
Apache-2.0
function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); }
Converts `value` to a string if it is not one. An empty string is returned for `null` or `undefined` values. @private @param {*} value The value to process. @returns {string} Returns the string.
baseToString ( value )
javascript
guardian/scribe
src/plugins/core/formatters/plain-text/escape-html-characters.js
https://github.com/guardian/scribe/blob/master/src/plugins/core/formatters/plain-text/escape-html-characters.js
Apache-2.0
function escapeHtmlChar(chr) { return htmlEscapes[chr]; }
Used by `_.escape` to convert characters to HTML entities. @private @param {string} chr The matched character to escape. @returns {string} Returns the escaped character.
escapeHtmlChar ( chr )
javascript
guardian/scribe
src/plugins/core/formatters/plain-text/escape-html-characters.js
https://github.com/guardian/scribe/blob/master/src/plugins/core/formatters/plain-text/escape-html-characters.js
Apache-2.0
function wrapChildNodes(parentNode) { var index = 0; Immutable.List(parentNode.childNodes) .filterNot(function(node) { return nodeHelpers.isWhitespaceOnlyTextNode(Node, node); }) .filter(function(node) { return node.nodeType === Node.TEXT_NODE || !nodeHelpers.isBlockElement(node); }) .groupBy(function(node, key, list) { return key === 0 || node.previousSibling === list.get(key - 1) ? index : index += 1; }) .forEach(function(nodeGroup) { nodeHelpers.wrap(nodeGroup.toArray(), document.createElement('p')); }); }
Wrap consecutive inline elements and text nodes in a P element.
wrapChildNodes ( parentNode )
javascript
guardian/scribe
src/plugins/core/formatters/html/enforce-p-elements.js
https://github.com/guardian/scribe/blob/master/src/plugins/core/formatters/html/enforce-p-elements.js
Apache-2.0
scribe.transactionManager.run(function () { // Store the caret position selection.placeMarkers(); nodeHelpers.removeChromeArtifacts(containerPElement); selection.selectMarkers(); }, true);
The 'input' event listener has already triggered and recorded the faulty content as an item in the UndoManager. We interfere with the undoManager by force merging that transaction with the next transaction which produce a clean one instead. FIXME: ideally we would not trigger a 'content-changed' event with faulty HTML at all, but it's too late to cancel it at this stage (and it's not happened yet at keydown time).
(anonymous) ( )
javascript
guardian/scribe
src/plugins/core/patches/events.js
https://github.com/guardian/scribe/blob/master/src/plugins/core/patches/events.js
Apache-2.0
boldCommand.queryEnabled = function () { var selection = new scribe.api.Selection(); var headingNode = selection.getContaining(function (node) { return (/^(H[1-6])$/).test(node.nodeName); }); return scribe.api.CommandPatch.prototype.queryEnabled.apply(this, arguments) && ! headingNode; }; // TODO: We can't use STRONGs because this would mean we have to // re-implement the `queryState` command, which would be difficult. scribe.commandPatches.bold = boldCommand; };
Chrome: Executing the bold command inside a heading corrupts the markup. Disabling for now.
boldCommand.queryEnabled ( )
javascript
guardian/scribe
src/plugins/core/patches/commands/bold.js
https://github.com/guardian/scribe/blob/master/src/plugins/core/patches/commands/bold.js
Apache-2.0
var pNode = selection.getContaining(function (node) { return node.nodeName === 'P'; });
Chrome: If we apply the outdent command on a P, the contents of the P will be outdented instead of the whole P element. As per: http://jsbin.com/IfaRaFO/1/edit?html,js,output
(anonymous) ( node )
javascript
guardian/scribe
src/plugins/core/patches/commands/outdent.js
https://github.com/guardian/scribe/blob/master/src/plugins/core/patches/commands/outdent.js
Apache-2.0
function command(type) { try { return document.execCommand(type); } catch (err) { return false; } }
Executes a given operation type. @param {String} type @return {Boolean}
command ( type )
javascript
openchatai/OpenChat
dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
MIT
var ClipboardActionCut = function ClipboardActionCut(target) { var selectedText = select_default()(target); command('cut'); return selectedText; };
Cut action wrapper. @param {String|HTMLElement} target @return {String}
ClipboardActionCut ( target )
javascript
openchatai/OpenChat
dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
MIT
function createFakeElement(value) { var isRTL = document.documentElement.getAttribute('dir') === 'rtl'; var fakeElement = document.createElement('textarea'); // Prevent zooming on iOS fakeElement.style.fontSize = '12pt'; // Reset box model fakeElement.style.border = '0'; fakeElement.style.padding = '0'; fakeElement.style.margin = '0'; // Move element out of screen horizontally fakeElement.style.position = 'absolute'; fakeElement.style[isRTL ? 'right' : 'left'] = '-9999px'; // Move element to the same position vertically var yPosition = window.pageYOffset || document.documentElement.scrollTop; fakeElement.style.top = "".concat(yPosition, "px"); fakeElement.setAttribute('readonly', ''); fakeElement.value = value; return fakeElement; }
Creates a fake textarea element with a value. @param {String} value @return {HTMLElement}
createFakeElement ( value )
javascript
openchatai/OpenChat
dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
MIT
var fakeCopyAction = function fakeCopyAction(value, options) { var fakeElement = createFakeElement(value); options.container.appendChild(fakeElement); var selectedText = select_default()(fakeElement); command('copy'); fakeElement.remove(); return selectedText; };
Create fake copy action wrapper using a fake element. @param {String} target @param {Object} options @return {String}
fakeCopyAction ( value , options )
javascript
openchatai/OpenChat
dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
MIT
var ClipboardActionDefault = function ClipboardActionDefault() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; // Defines base properties passed from constructor. var _options$action = options.action, action = _options$action === void 0 ? 'copy' : _options$action, container = options.container, target = options.target, text = options.text; // Sets the `action` to be performed which can be either 'copy' or 'cut'. if (action !== 'copy' && action !== 'cut') { throw new Error('Invalid "action" value, use either "copy" or "cut"'); } // Sets the `target` property using an element that will be have its content copied. if (target !== undefined) { if (target && _typeof(target) === 'object' && target.nodeType === 1) { if (action === 'copy' && target.hasAttribute('disabled')) { throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute'); } if (action === 'cut' && (target.hasAttribute('readonly') || target.hasAttribute('disabled'))) { throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes'); } } else { throw new Error('Invalid "target" value, use a valid Element'); } } // Define selection strategy based on `text` property. if (text) { return actions_copy(text, { container: container }); } // Defines which selection strategy based on `target` property. if (target) { return action === 'cut' ? actions_cut(target) : actions_copy(target, { container: container }); } };
Inner function which performs selection from either `text` or `target` properties and then executes copy or cut operations. @param {Object} options
ClipboardActionDefault ( )
javascript
openchatai/OpenChat
dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
MIT
function getAttributeValue(suffix, element) { var attribute = "data-clipboard-".concat(suffix); if (!element.hasAttribute(attribute)) { return; } return element.getAttribute(attribute); }
Helper function to retrieve attribute value. @param {String} suffix @param {Element} element
getAttributeValue ( suffix , element )
javascript
openchatai/OpenChat
dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
MIT
function Clipboard(trigger, options) { var _this; _classCallCheck(this, Clipboard); _this = _super.call(this); _this.resolveOptions(options); _this.listenClick(trigger); return _this; }
@param {String|HTMLElement|HTMLCollection|NodeList} trigger @param {Object} options
Clipboard ( trigger , options )
javascript
openchatai/OpenChat
dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
MIT
value: function defaultText(trigger) { return getAttributeValue('text', trigger); }
Default `text` lookup function. @param {Element} trigger
defaultText ( trigger )
javascript
openchatai/OpenChat
dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
MIT
var Clipboard = /*#__PURE__*/function (_Emitter) { _inherits(Clipboard, _Emitter); var _super = _createSuper(Clipboard); /** * @param {String|HTMLElement|HTMLCollection|NodeList} trigger * @param {Object} options */ function Clipboard(trigger, options) { var _this; _classCallCheck(this, Clipboard); _this = _super.call(this); _this.resolveOptions(options); _this.listenClick(trigger); return _this; } /** * Defines if attributes would be resolved using internal setter functions * or custom functions that were passed in the constructor. * @param {Object} options */ _createClass(Clipboard, [{ key: "resolveOptions", value: function resolveOptions() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.action = typeof options.action === 'function' ? options.action : this.defaultAction; this.target = typeof options.target === 'function' ? options.target : this.defaultTarget; this.text = typeof options.text === 'function' ? options.text : this.defaultText; this.container = clipboard_typeof(options.container) === 'object' ? options.container : document.body; } /** * Adds a click event listener to the passed trigger. * @param {String|HTMLElement|HTMLCollection|NodeList} trigger */ }, { key: "listenClick", value: function listenClick(trigger) { var _this2 = this; this.listener = listen_default()(trigger, 'click', function (e) { return _this2.onClick(e); }); } /** * Defines a new `ClipboardAction` on each click event. * @param {Event} e */ }, { key: "onClick", value: function onClick(e) { var trigger = e.delegateTarget || e.currentTarget; var action = this.action(trigger) || 'copy'; var text = actions_default({ action: action, container: this.container, target: this.target(trigger), text: this.text(trigger) }); // Fires an event based on the copy operation result. this.emit(text ? 'success' : 'error', { action: action, text: text, trigger: trigger, clearSelection: function clearSelection() { if (trigger) { trigger.focus(); } window.getSelection().removeAllRanges(); } }); } /** * Default `action` lookup function. * @param {Element} trigger */ }, { key: "defaultAction", value: function defaultAction(trigger) { return getAttributeValue('action', trigger); } /** * Default `target` lookup function. * @param {Element} trigger */ }, { key: "defaultTarget", value: function defaultTarget(trigger) { var selector = getAttributeValue('target', trigger); if (selector) { return document.querySelector(selector); } } /** * Allow fire programmatically a copy action * @param {String|HTMLElement} target * @param {Object} options * @returns Text copied. */ }, { key: "defaultText", /** * Default `text` lookup function. * @param {Element} trigger */ value: function defaultText(trigger) { return getAttributeValue('text', trigger); } /** * Destroy lifecycle. */ }, { key: "destroy", value: function destroy() { this.listener.destroy(); } }], [{ key: "copy", value: function copy(target) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { container: document.body }; return actions_copy(target, options); } /** * Allow fire programmatically a cut action * @param {String|HTMLElement} target * @returns Text cutted. */ }, { key: "cut", value: function cut(target) { return actions_cut(target); } /** * Returns the support of the given action, or all actions if no action is * given. * @param {String} [action] */ }, { key: "isSupported", value: function isSupported() { var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['copy', 'cut']; var actions = typeof action === 'string' ? [action] : action; var support = !!document.queryCommandSupported; actions.forEach(function (action) { support = support && !!document.queryCommandSupported(action); }); return support; } }]); return Clipboard; }((tiny_emitter_default())); /* harmony default export */ var clipboard = (Clipboard); /***/ }), /***/ 828: /***/ (function(module) { var DOCUMENT_NODE_TYPE = 9; /** * A polyfill for Element.matches() */ if (typeof Element !== 'undefined' && !Element.prototype.matches) { var proto = Element.prototype; proto.matches = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector; } /** * Finds the closest parent that matches a selector. * * @param {Element} element * @param {String} selector * @return {Function} */ function closest (element, selector) { while (element && element.nodeType !== DOCUMENT_NODE_TYPE) { if (typeof element.matches === 'function' && element.matches(selector)) { return element; } element = element.parentNode; } } module.exports = closest; /***/ }), /***/ 438: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var closest = __webpack_require__(828); /** * Delegates event to a selector. * * @param {Element} element * @param {String} selector * @param {String} type * @param {Function} callback * @param {Boolean} useCapture * @return {Object} */ function _delegate(element, selector, type, callback, useCapture) { var listenerFn = listener.apply(this, arguments); element.addEventListener(type, listenerFn, useCapture); return { destroy: function() { element.removeEventListener(type, listenerFn, useCapture); } } } /** * Delegates event to a selector. * * @param {Element|String|Array} [elements] * @param {String} selector * @param {String} type * @param {Function} callback * @param {Boolean} useCapture * @return {Object} */ function delegate(elements, selector, type, callback, useCapture) { // Handle the regular Element usage if (typeof elements.addEventListener === 'function') { return _delegate.apply(null, arguments); } // Handle Element-less usage, it defaults to global delegation if (typeof type === 'function') { // Use `document` as the first parameter, then apply arguments // This is a short way to .unshift `arguments` without running into deoptimizations return _delegate.bind(null, document).apply(null, arguments); } // Handle Selector-based usage if (typeof elements === 'string') { elements = document.querySelectorAll(elements); } // Handle Array-like based usage return Array.prototype.map.call(elements, function (element) { return _delegate(element, selector, type, callback, useCapture); }); } /** * Finds closest match and invokes callback. * * @param {Element} element * @param {String} selector * @param {String} type * @param {Function} callback * @return {Function} */ function listener(element, selector, type, callback) { return function(e) { e.delegateTarget = closest(e.target, selector); if (e.delegateTarget) { callback.call(element, e); } } } module.exports = delegate; /***/ }), /***/ 879: /***/ (function(__unused_webpack_module, exports) { /** * Check if argument is a HTML element. * * @param {Object} value * @return {Boolean} */ exports.node = function(value) { return value !== undefined && value instanceof HTMLElement && value.nodeType === 1; }; /** * Check if argument is a list of HTML elements. * * @param {Object} value * @return {Boolean} */ exports.nodeList = function(value) { var type = Object.prototype.toString.call(value); return value !== undefined && (type === '[object NodeList]' || type === '[object HTMLCollection]') && ('length' in value) && (value.length === 0 || exports.node(value[0])); }; /** * Check if argument is a string. * * @param {Object} value * @return {Boolean} */ exports.string = function(value) { return typeof value === 'string' || value instanceof String; }; /** * Check if argument is a function. * * @param {Object} value * @return {Boolean} */ exports.fn = function(value) { var type = Object.prototype.toString.call(value); return type === '[object Function]'; }; /***/ }), /***/ 370: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var is = __webpack_require__(879); var delegate = __webpack_require__(438); /** * Validates all params and calls the right * listener function based on its target type. * * @param {String|HTMLElement|HTMLCollection|NodeList} target * @param {String} type * @param {Function} callback * @return {Object} */ function listen(target, type, callback) { if (!target && !type && !callback) { throw new Error('Missing required arguments'); } if (!is.string(type)) { throw new TypeError('Second argument must be a String'); } if (!is.fn(callback)) { throw new TypeError('Third argument must be a Function'); } if (is.node(target)) { return listenNode(target, type, callback); } else if (is.nodeList(target)) { return listenNodeList(target, type, callback); } else if (is.string(target)) { return listenSelector(target, type, callback); } else { throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList'); } } /** * Adds an event listener to a HTML element * and returns a remove listener function. * * @param {HTMLElement} node * @param {String} type * @param {Function} callback * @return {Object} */ function listenNode(node, type, callback) { node.addEventListener(type, callback); return { destroy: function() { node.removeEventListener(type, callback); } } } /** * Add an event listener to a list of HTML elements * and returns a remove listener function. * * @param {NodeList|HTMLCollection} nodeList * @param {String} type * @param {Function} callback * @return {Object} */ function listenNodeList(nodeList, type, callback) { Array.prototype.forEach.call(nodeList, function(node) { node.addEventListener(type, callback); }); return { destroy: function() { Array.prototype.forEach.call(nodeList, function(node) { node.removeEventListener(type, callback); }); } } } /** * Add an event listener to a selector * and returns a remove listener function. * * @param {String} selector * @param {String} type * @param {Function} callback * @return {Object} */ function listenSelector(selector, type, callback) { return delegate(document.body, selector, type, callback); } module.exports = listen; /***/ }), /***/ 817: /***/ (function(module) { function select(element) { var selectedText; if (element.nodeName === 'SELECT') { element.focus(); selectedText = element.value; } else if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') { var isReadOnly = element.hasAttribute('readonly'); if (!isReadOnly) { element.setAttribute('readonly', ''); } element.select(); element.setSelectionRange(0, element.value.length); if (!isReadOnly) { element.removeAttribute('readonly'); } selectedText = element.value; } else { if (element.hasAttribute('contenteditable')) { element.focus(); } var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(element); selection.removeAllRanges(); selection.addRange(range); selectedText = selection.toString(); } return selectedText; } module.exports = select; /***/ }), /***/ 279: /***/ (function(module) { function E () { // Keep this empty so it's easier to inherit from // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3) } E.prototype = { on: function (name, callback, ctx) { var e = this.e || (this.e = {}); (e[name] || (e[name] = [])).push({ fn: callback, ctx: ctx }); return this; }, once: function (name, callback, ctx) { var self = this; function listener () { self.off(name, listener); callback.apply(ctx, arguments); }; listener._ = callback return this.on(name, listener, ctx); }, emit: function (name) { var data = [].slice.call(arguments, 1); var evtArr = ((this.e || (this.e = {}))[name] || []).slice(); var i = 0; var len = evtArr.length; for (i; i < len; i++) { evtArr[i].fn.apply(evtArr[i].ctx, data); } return this; }, off: function (name, callback) { var e = this.e || (this.e = {}); var evts = e[name]; var liveEvents = []; if (evts && callback) { for (var i = 0, len = evts.length; i < len; i++) { if (evts[i].fn !== callback && evts[i].fn._ !== callback) liveEvents.push(evts[i]); } } // Remove event from queue to prevent memory leak // Suggested by https://github.com/lazd // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910 (liveEvents.length) ? e[name] = liveEvents : delete e[name]; return this; } }; module.exports = E; module.exports.TinyEmitter = E; /***/ }) /******/ });
Base class which takes one or more elements, adds event listeners to them, and instantiates a new `ClipboardAction` on each click.
Clipboard ( _Emitter )
javascript
openchatai/OpenChat
dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/dashboard/js/vendors/clipboard.js
MIT
function onMove(e, isTouch) { if (disabled === true || isRating === true) { return; } var xCoor = null; var percent; var width = elem.offsetWidth; var parentOffset = elem.getBoundingClientRect(); if (reverse) { if (isTouch) { xCoor = e.changedTouches[0].pageX - parentOffset.left; } else { xCoor = e.pageX - window.scrollX - parentOffset.left; } var relXRtl = width - xCoor; var valueForDivision = width / 100; percent = relXRtl / valueForDivision; } else { if (isTouch) { xCoor = e.changedTouches[0].pageX - parentOffset.left; } else { xCoor = e.offsetX; } percent = xCoor / width * 100; } if (percent < 101) { if (step === 1) { currentRating = Math.ceil(percent / 100 * stars); } else { var rat = percent / 100 * stars; for (var i = 0;; i += step) { if (i >= rat) { currentRating = i; break; } } } //todo: check why this happens and fix if (currentRating > stars) { currentRating = stars; } elem.querySelector(".star-value").style.width = currentRating / stars * 100 + "%"; if (showToolTip) { var toolTip = ratingText.replace("{rating}", currentRating); toolTip = toolTip.replace("{maxRating}", stars); elem.setAttribute("title", toolTip); } if (typeof onHover === "function") { onHover(currentRating, rating); } } }
Called by eventhandlers when mouse or touch events are triggered @param {MouseEvent} e
onMove ( e , isTouch )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/rater-js/index.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/rater-js/index.js
MIT
function onStarOut(e) { if (!rating) { elem.querySelector(".star-value").style.width = "0%"; elem.removeAttribute("data-rating"); } else { elem.querySelector(".star-value").style.width = rating / stars * 100 + "%"; elem.setAttribute("data-rating", rating); } if (typeof onLeave === "function") { onLeave(currentRating, rating); } }
Called when mouse is released. This function will update the view with the rating. @param {MouseEvent} e
onStarOut ( e )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/rater-js/index.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/rater-js/index.js
MIT
function onStarClick(e) { if (disabled === true) { return; } if (isRating === true) { return; } if (typeof callback !== "undefined") { isRating = true; myRating = currentRating; if (typeof isBusyText === "undefined") { elem.removeAttribute("title"); } else { elem.setAttribute("title", isBusyText); } elem.classList.add("is-busy"); callback.call(this, myRating, function () { if (disabled === false) { elem.removeAttribute("title"); } isRating = false; elem.classList.remove("is-busy"); }); } }
Called when star is clicked. @param {MouseEvent} e
onStarClick ( e )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/rater-js/index.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/rater-js/index.js
MIT
function enable() { disabled = false; elem.removeAttribute("title"); elem.classList.remove("disabled"); }
Enabled the rater so that it's possible to click the stars.
enable ( )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/rater-js/index.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/rater-js/index.js
MIT
function clear() { rating = null; elem.querySelector(".star-value").style.width = "0px"; elem.removeAttribute("title"); }
Set the rating to a value to inducate it's not rated.
clear ( )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/rater-js/index.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/rater-js/index.js
MIT
function handleMove(e) { e.preventDefault(); onMove(e, true); }
Handles touchmove event. @param {TouchEvent} e
handleMove ( e )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/rater-js/index.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/rater-js/index.js
MIT
function handleStart(e) { e.preventDefault(); onMove(e, true); }
Handles touchstart event. @param {TouchEvent} e
handleStart ( e )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/rater-js/index.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/rater-js/index.js
MIT
function handleEnd(evt) { evt.preventDefault(); onMove(evt, true); onStarClick.call(module); }
Handles touchend event. @param {TouchEvent} e
handleEnd ( evt )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/rater-js/index.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/rater-js/index.js
MIT
function disable() { disabled = true; elem.classList.add("disabled"); if (showToolTip && !!disableText) { var toolTip = disableText.replace("{rating}", !!rating ? rating : 0); toolTip = toolTip.replace("{maxRating}", stars); elem.setAttribute("title", toolTip); } else { elem.removeAttribute("title"); } } /** * Enabled the rater so that it's possible to click the stars. */ function enable() { disabled = false; elem.removeAttribute("title"); elem.classList.remove("disabled"); } /** * Sets the rating */ function setRating(value) { if (typeof value === "undefined") { throw new Error("Value not set."); } if (value === null) { throw new Error("Value cannot be null."); } if (typeof value !== "number") { throw new Error("Value must be a number."); } if (value < 0 || value > stars) { throw new Error("Value too high. Please set a rating of " + stars + " or below."); } rating = value; elem.querySelector(".star-value").style.width = value / stars * 100 + "%"; elem.setAttribute("data-rating", value); } /** * Gets the rating */ function getRating() { return rating; } /** * Set the rating to a value to inducate it's not rated. */ function clear() { rating = null; elem.querySelector(".star-value").style.width = "0px"; elem.removeAttribute("title"); } /** * Remove event handlers. */ function dispose() { elem.removeEventListener("mousemove", onMouseMove); elem.removeEventListener("mouseleave", onStarOut); elem.removeEventListener("click", onStarClick); elem.removeEventListener("touchmove", handleMove, false); elem.removeEventListener("touchstart", handleStart, false); elem.removeEventListener("touchend", handleEnd, false); elem.removeEventListener("touchcancel", handleCancel, false); } elem.addEventListener("mousemove", onMouseMove); elem.addEventListener("mouseleave", onStarOut); var module = { setRating: setRating, getRating: getRating, disable: disable, enable: enable, clear: clear, dispose: dispose, get element() { return elem; } }; /** * Handles touchmove event. * @param {TouchEvent} e */ function handleMove(e) { e.preventDefault(); onMove(e, true); } /** * Handles touchstart event. * @param {TouchEvent} e */ function handleStart(e) { e.preventDefault(); onMove(e, true); } /** * Handles touchend event. * @param {TouchEvent} e */ function handleEnd(evt) { evt.preventDefault(); onMove(evt, true); onStarClick.call(module); } /** * Handles touchend event. * @param {TouchEvent} e */ function handleCancel(e) { e.preventDefault(); onStarOut(e); } elem.addEventListener("click", onStarClick.bind(module)); elem.addEventListener("touchmove", handleMove, false); elem.addEventListener("touchstart", handleStart, false); elem.addEventListener("touchend", handleEnd, false); elem.addEventListener("touchcancel", handleCancel, false); return module; };
Disables the rater so that it's not possible to click the stars.
disable ( )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/rater-js/index.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/rater-js/index.js
MIT
this.setContextMenu = function(options) { window.context_menu[self.el.id][options.control] = {}; var i, ul = doc.createElement('ul'); for (i in options.options) { if (options.options.hasOwnProperty(i)) { var option = options.options[i]; window.context_menu[self.el.id][options.control][option.name] = { title: option.title, action: option.action }; } } ul.id = 'gmaps_context_menu'; ul.style.display = 'none'; ul.style.position = 'absolute'; ul.style.minWidth = '100px'; ul.style.background = 'white'; ul.style.listStyle = 'none'; ul.style.padding = '8px'; ul.style.boxShadow = '2px 2px 6px #ccc'; if (!getElementById('gmaps_context_menu')) { doc.body.appendChild(ul); } var context_menu_element = getElementById('gmaps_context_menu'); google.maps.event.addDomListener(context_menu_element, 'mouseout', function(ev) { if (!ev.relatedTarget || !this.contains(ev.relatedTarget)) { window.setTimeout(function(){ context_menu_element.style.display = 'none'; }, 400); } }, false); };
Add a context menu for a map or a marker. @param {object} options - The `options` object should contain: * `control` (string): Kind of control the context menu will be attached. Can be "map" or "marker". * `options` (array): A collection of context menu items: * `title` (string): Item's title shown in the context menu. * `name` (string): Item's identifier. * `action` (function): Function triggered after selecting the context menu item.
this.setContextMenu ( options )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
MIT
this.refresh = function() { google.maps.event.trigger(this.map, 'resize'); };
Trigger a `resize` event, useful if you need to repaint the current map (for changes in the viewport or display / hide actions).
this.refresh ( )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
MIT
this.fitZoom = function() { var latLngs = [], markers_length = this.markers.length, i; for (i = 0; i < markers_length; i++) { if(typeof(this.markers[i].visible) === 'boolean' && this.markers[i].visible) { latLngs.push(this.markers[i].getPosition()); } } this.fitLatLngBounds(latLngs); };
Adjust the map zoom to include all the markers added in the map.
this.fitZoom ( )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
MIT
this.fitLatLngBounds = function(latLngs) { var total = latLngs.length, bounds = new google.maps.LatLngBounds(), i; for(i = 0; i < total; i++) { bounds.extend(latLngs[i]); } this.map.fitBounds(bounds); };
Adjust the map zoom to include all the coordinates in the `latLngs` array. @param {array} latLngs - Collection of `google.maps.LatLng` objects.
this.fitLatLngBounds ( latLngs )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
MIT
this.setCenter = function(lat, lng, callback) { this.map.panTo(new google.maps.LatLng(lat, lng)); if (callback) { callback(); } };
Center the map using the `lat` and `lng` coordinates. @param {number} lat - Latitude of the coordinate. @param {number} lng - Longitude of the coordinate. @param {function} [callback] - Callback that will be executed after the map is centered.
this.setCenter ( lat , lng , callback )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
MIT
this.getElement = function() { return this.el; };
Return the HTML element container of the map. @returns {HTMLElement} the element container.
this.getElement ( )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
MIT
this.zoomIn = function(value) { value = value || 1; this.zoom = this.map.getZoom() + value; this.map.setZoom(this.zoom); };
Increase the map's zoom. @param {number} [magnitude] - The number of times the map will be zoomed in.
this.zoomIn ( value )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
MIT
this.zoomOut = function(value) { value = value || 1; this.zoom = this.map.getZoom() - value; this.map.setZoom(this.zoom); };
Decrease the map's zoom. @param {number} [magnitude] - The number of times the map will be zoomed out.
this.zoomOut ( value )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
MIT
var GMaps = function(options) { if (!(typeof window.google === 'object' && window.google.maps)) { if (typeof window.console === 'object' && window.console.error) { console.error('Google Maps API is required. Please register the following JavaScript library https://maps.googleapis.com/maps/api/js.'); } return function() {}; } if (!this) return new GMaps(options); options.zoom = options.zoom || 15; options.mapType = options.mapType || 'roadmap'; var valueOrDefault = function(value, defaultValue) { return value === undefined ? defaultValue : value; }; var self = this, i, events_that_hide_context_menu = [ 'bounds_changed', 'center_changed', 'click', 'dblclick', 'drag', 'dragend', 'dragstart', 'idle', 'maptypeid_changed', 'projection_changed', 'resize', 'tilesloaded', 'zoom_changed' ], events_that_doesnt_hide_context_menu = ['mousemove', 'mouseout', 'mouseover'], options_to_be_deleted = ['el', 'lat', 'lng', 'mapType', 'width', 'height', 'markerClusterer', 'enableNewStyle'], identifier = options.el || options.div, markerClustererFunction = options.markerClusterer, mapType = google.maps.MapTypeId[options.mapType.toUpperCase()], map_center = new google.maps.LatLng(options.lat, options.lng), zoomControl = valueOrDefault(options.zoomControl, true), zoomControlOpt = options.zoomControlOpt || { style: 'DEFAULT', position: 'TOP_LEFT' }, zoomControlStyle = zoomControlOpt.style || 'DEFAULT', zoomControlPosition = zoomControlOpt.position || 'TOP_LEFT', panControl = valueOrDefault(options.panControl, true), mapTypeControl = valueOrDefault(options.mapTypeControl, true), scaleControl = valueOrDefault(options.scaleControl, true), streetViewControl = valueOrDefault(options.streetViewControl, true), overviewMapControl = valueOrDefault(overviewMapControl, true), map_options = {}, map_base_options = { zoom: this.zoom, center: map_center, mapTypeId: mapType }, map_controls_options = { panControl: panControl, zoomControl: zoomControl, zoomControlOptions: { style: google.maps.ZoomControlStyle[zoomControlStyle], position: google.maps.ControlPosition[zoomControlPosition] }, mapTypeControl: mapTypeControl, scaleControl: scaleControl, streetViewControl: streetViewControl, overviewMapControl: overviewMapControl }; if (typeof(options.el) === 'string' || typeof(options.div) === 'string') { if (identifier.indexOf("#") > -1) { /** * Container element * * @type {HTMLElement} */ this.el = getElementById(identifier, options.context); } else { this.el = getElementsByClassName.apply(this, [identifier, options.context]); } } else { this.el = identifier; } if (typeof(this.el) === 'undefined' || this.el === null) { throw 'No element defined.'; } window.context_menu = window.context_menu || {}; window.context_menu[self.el.id] = {}; /** * Collection of custom controls in the map UI * * @type {array} */ this.controls = []; /** * Collection of map's overlays * * @type {array} */ this.overlays = []; /** * Collection of KML/GeoRSS and FusionTable layers * * @type {array} */ this.layers = []; /** * Collection of data layers (See {@link GMaps#addLayer}) * * @type {object} */ this.singleLayers = {}; /** * Collection of map's markers * * @type {array} */ this.markers = []; /** * Collection of map's lines * * @type {array} */ this.polylines = []; /** * Collection of map's routes requested by {@link GMaps#getRoutes}, {@link GMaps#renderRoute}, {@link GMaps#drawRoute}, {@link GMaps#travelRoute} or {@link GMaps#drawSteppedRoute} * * @type {array} */ this.routes = []; /** * Collection of map's polygons * * @type {array} */ this.polygons = []; this.infoWindow = null; this.overlay_el = null; /** * Current map's zoom * * @type {number} */ this.zoom = options.zoom; this.registered_events = {}; this.el.style.width = options.width || this.el.scrollWidth || this.el.offsetWidth; this.el.style.height = options.height || this.el.scrollHeight || this.el.offsetHeight; google.maps.visualRefresh = options.enableNewStyle; for (i = 0; i < options_to_be_deleted.length; i++) { delete options[options_to_be_deleted[i]]; } if(options.disableDefaultUI != true) { map_base_options = extend_object(map_base_options, map_controls_options); } map_options = extend_object(map_base_options, options); for (i = 0; i < events_that_hide_context_menu.length; i++) { delete map_options[events_that_hide_context_menu[i]]; } for (i = 0; i < events_that_doesnt_hide_context_menu.length; i++) { delete map_options[events_that_doesnt_hide_context_menu[i]]; } /** * Google Maps map instance * * @type {google.maps.Map} */ this.map = new google.maps.Map(this.el, map_options); if (markerClustererFunction) { /** * Marker Clusterer instance * * @type {object} */ this.markerClusterer = markerClustererFunction.apply(this, [this.map]); } var buildContextMenuHTML = function(control, e) { var html = '', options = window.context_menu[self.el.id][control]; for (var i in options){ if (options.hasOwnProperty(i)) { var option = options[i]; html += '<li><a id="' + control + '_' + i + '" href="#">' + option.title + '</a></li>'; } } if (!getElementById('gmaps_context_menu')) return; var context_menu_element = getElementById('gmaps_context_menu'); context_menu_element.innerHTML = html; var context_menu_items = context_menu_element.getElementsByTagName('a'), context_menu_items_count = context_menu_items.length, i; for (i = 0; i < context_menu_items_count; i++) { var context_menu_item = context_menu_items[i]; var assign_menu_item_action = function(ev){ ev.preventDefault(); options[this.id.replace(control + '_', '')].action.apply(self, [e]); self.hideContextMenu(); }; google.maps.event.clearListeners(context_menu_item, 'click'); google.maps.event.addDomListenerOnce(context_menu_item, 'click', assign_menu_item_action, false); } var position = findAbsolutePosition.apply(this, [self.el]), left = position[0] + e.pixel.x - 15, top = position[1] + e.pixel.y- 15; context_menu_element.style.left = left + "px"; context_menu_element.style.top = top + "px"; // context_menu_element.style.display = 'block'; }; this.buildContextMenu = function(control, e) { if (control === 'marker') { e.pixel = {}; var overlay = new google.maps.OverlayView(); overlay.setMap(self.map); overlay.draw = function() { var projection = overlay.getProjection(), position = e.marker.getPosition(); e.pixel = projection.fromLatLngToContainerPixel(position); buildContextMenuHTML(control, e); }; } else { buildContextMenuHTML(control, e); } var context_menu_element = getElementById('gmaps_context_menu'); setTimeout(function() { context_menu_element.style.display = 'block'; }, 0); }; /** * Add a context menu for a map or a marker. * * @param {object} options - The `options` object should contain: * * `control` (string): Kind of control the context menu will be attached. Can be "map" or "marker". * * `options` (array): A collection of context menu items: * * `title` (string): Item's title shown in the context menu. * * `name` (string): Item's identifier. * * `action` (function): Function triggered after selecting the context menu item. */ this.setContextMenu = function(options) { window.context_menu[self.el.id][options.control] = {}; var i, ul = doc.createElement('ul'); for (i in options.options) { if (options.options.hasOwnProperty(i)) { var option = options.options[i]; window.context_menu[self.el.id][options.control][option.name] = { title: option.title, action: option.action }; } } ul.id = 'gmaps_context_menu'; ul.style.display = 'none'; ul.style.position = 'absolute'; ul.style.minWidth = '100px'; ul.style.background = 'white'; ul.style.listStyle = 'none'; ul.style.padding = '8px'; ul.style.boxShadow = '2px 2px 6px #ccc'; if (!getElementById('gmaps_context_menu')) { doc.body.appendChild(ul); } var context_menu_element = getElementById('gmaps_context_menu'); google.maps.event.addDomListener(context_menu_element, 'mouseout', function(ev) { if (!ev.relatedTarget || !this.contains(ev.relatedTarget)) { window.setTimeout(function(){ context_menu_element.style.display = 'none'; }, 400); } }, false); }; /** * Hide the current context menu */ this.hideContextMenu = function() { var context_menu_element = getElementById('gmaps_context_menu'); if (context_menu_element) { context_menu_element.style.display = 'none'; } }; var setupListener = function(object, name) { google.maps.event.addListener(object, name, function(e){ if (e == undefined) { e = this; } options[name].apply(this, [e]); self.hideContextMenu(); }); }; //google.maps.event.addListener(this.map, 'idle', this.hideContextMenu); google.maps.event.addListener(this.map, 'zoom_changed', this.hideContextMenu); for (var ev = 0; ev < events_that_hide_context_menu.length; ev++) { var name = events_that_hide_context_menu[ev]; if (name in options) { setupListener(this.map, name); } } for (var ev = 0; ev < events_that_doesnt_hide_context_menu.length; ev++) { var name = events_that_doesnt_hide_context_menu[ev]; if (name in options) { setupListener(this.map, name); } } google.maps.event.addListener(this.map, 'rightclick', function(e) { if (options.rightclick) { options.rightclick.apply(this, [e]); } if(window.context_menu[self.el.id]['map'] != undefined) { self.buildContextMenu('map', e); } }); /** * Trigger a `resize` event, useful if you need to repaint the current map (for changes in the viewport or display / hide actions). */ this.refresh = function() { google.maps.event.trigger(this.map, 'resize'); }; /** * Adjust the map zoom to include all the markers added in the map. */ this.fitZoom = function() { var latLngs = [], markers_length = this.markers.length, i; for (i = 0; i < markers_length; i++) { if(typeof(this.markers[i].visible) === 'boolean' && this.markers[i].visible) { latLngs.push(this.markers[i].getPosition()); } } this.fitLatLngBounds(latLngs); }; /** * Adjust the map zoom to include all the coordinates in the `latLngs` array. * * @param {array} latLngs - Collection of `google.maps.LatLng` objects. */ this.fitLatLngBounds = function(latLngs) { var total = latLngs.length, bounds = new google.maps.LatLngBounds(), i; for(i = 0; i < total; i++) { bounds.extend(latLngs[i]); } this.map.fitBounds(bounds); }; /** * Center the map using the `lat` and `lng` coordinates. * * @param {number} lat - Latitude of the coordinate. * @param {number} lng - Longitude of the coordinate. * @param {function} [callback] - Callback that will be executed after the map is centered. */ this.setCenter = function(lat, lng, callback) { this.map.panTo(new google.maps.LatLng(lat, lng)); if (callback) { callback(); } }; /** * Return the HTML element container of the map. * * @returns {HTMLElement} the element container. */ this.getElement = function() { return this.el; }; /** * Increase the map's zoom. * * @param {number} [magnitude] - The number of times the map will be zoomed in. */ this.zoomIn = function(value) { value = value || 1; this.zoom = this.map.getZoom() + value; this.map.setZoom(this.zoom); }; /** * Decrease the map's zoom. * * @param {number} [magnitude] - The number of times the map will be zoomed out. */ this.zoomOut = function(value) { value = value || 1; this.zoom = this.map.getZoom() - value; this.map.setZoom(this.zoom); }; var native_methods = [], method; for (method in this.map) { if (typeof(this.map[method]) == 'function' && !this[method]) { native_methods.push(method); } } for (i = 0; i < native_methods.length; i++) { (function(gmaps, scope, method_name) { gmaps[method_name] = function(){ return scope[method_name].apply(scope, arguments); }; })(this, this.map, native_methods[i]); } };
Creates a new GMaps instance, including a Google Maps map. @class GMaps @constructs @param {object} options - `options` accepts all the [MapOptions](https://developers.google.com/maps/documentation/javascript/reference#MapOptions) and [events](https://developers.google.com/maps/documentation/javascript/reference#Map) listed in the Google Maps API. Also accepts: * `lat` (number): Latitude of the map's center * `lng` (number): Longitude of the map's center * `el` (string or HTMLElement): container where the map will be rendered * `markerClusterer` (function): A function to create a marker cluster. You can use MarkerClusterer or MarkerClustererPlus.
GMaps ( options )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.core.js
MIT
GMaps.prototype.addControl = function(options) { var control = this.createControl(options); this.controls.push(control); this.map.controls[control.position].push(control); return control; };
Add a custom control to the map UI. @param {object} options - The `options` object should contain: * `style` (object): The keys and values of this object should be valid CSS properties and values. * `id` (string): The HTML id for the custom control. * `classes` (string): A string containing all the HTML classes for the custom control. * `content` (string or HTML element): The content of the custom control. * `position` (string): Any valid [`google.maps.ControlPosition`](https://developers.google.com/maps/documentation/javascript/controls#ControlPositioning) value, in lower or upper case. * `events` (object): The keys of this object should be valid DOM events. The values should be functions. * `disableDefaultStyles` (boolean): If false, removes the default styles for the controls like font (family and size), and box shadow. @returns {HTMLElement}
GMaps.prototype.addControl ( options )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.controls.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.controls.js
MIT
GMaps.prototype.removeControl = function(control) { var position = null, i; for (i = 0; i < this.controls.length; i++) { if (this.controls[i] == control) { position = this.controls[i].position; this.controls.splice(i, 1); } } if (position) { for (i = 0; i < this.map.controls.length; i++) { var controlsForPosition = this.map.controls[control.position]; if (controlsForPosition.getAt(i) == control) { controlsForPosition.removeAt(i); break; } } } return control; };
Remove a control from the map. `control` should be a control returned by `addControl()`. @param {HTMLElement} control - One of the controls returned by `addControl()`. @returns {HTMLElement} the removed control.
GMaps.prototype.removeControl ( control )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.controls.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/gmaps/lib/gmaps.controls.js
MIT
function guid() { return ("0000" + (Math.random()*Math.pow(36,5) << 0).toString(36)).slice(-5); }
Method that returns a 5 letter/digit id, enough for 36^5 = 60466176 elements @returns {string} id
guid ( )
javascript
openchatai/OpenChat
dj_backend_server/web/static/assets/libs/raphael/dev/raphael.svg.js
https://github.com/openchatai/OpenChat/blob/master/dj_backend_server/web/static/assets/libs/raphael/dev/raphael.svg.js
MIT
const registerCustomFormat = (name, extension, { fromFile, toFile }) => { customFileFormats[name] = { extension, parser: fromFile, formatter: toFile }; };
Register a custom entry file format. @param {string} name Format name. This should match the `format` option of a collection where the custom format will be used.. @param {string} extension File extension. @param {{ fromFile?: FileParser, toFile?: FileFormatter }} methods Parser and/or formatter methods. Async functions can be used. @see https://decapcms.org/docs/custom-formatters/
registerCustomFormat
javascript
sveltia/sveltia-cms
src/lib/main.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/main.js
MIT
const registerEditorComponent = (definition) => { customComponents[definition.id] = definition; };
Register a custom component. @param {EditorComponentDefinition} definition Component definition. @see https://decapcms.org/docs/custom-widgets/#registereditorcomponent
registerEditorComponent
javascript
sveltia/sveltia-cms
src/lib/main.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/main.js
MIT
const registerEventListener = (eventListener) => { // eslint-disable-next-line no-console console.error('Event hooks are not yet supported in Sveltia CMS.'); void [eventListener]; };
Register an event listener. @param {AppEventListener} eventListener Event listener. @see https://decapcms.org/docs/registering-events/
registerEventListener
javascript
sveltia/sveltia-cms
src/lib/main.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/main.js
MIT
const registerPreviewStyle = (style, { raw = false } = {}) => { // eslint-disable-next-line no-console console.error('Custom preview styles are not yet supported in Sveltia CMS.'); void [style, raw]; };
Register a custom preview style. @param {string} style File path or raw CSS string. @param {object} [options] Options. @param {boolean} [options.raw] Whether to use a CSS string. @see https://decapcms.org/docs/customization/#registerpreviewstyle
registerPreviewStyle
javascript
sveltia/sveltia-cms
src/lib/main.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/main.js
MIT
const registerPreviewTemplate = (name, component) => { // eslint-disable-next-line no-console console.error('Custom preview templates are not yet supported in Sveltia CMS.'); void [name, component]; };
Register a custom preview template. @param {string} name Template name. @param {ComponentType<CustomPreviewTemplateProps>} component React component. @see https://decapcms.org/docs/customization/#registerpreviewtemplate
registerPreviewTemplate
javascript
sveltia/sveltia-cms
src/lib/main.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/main.js
MIT
const registerWidget = (name, control, preview, schema) => { // eslint-disable-next-line no-console console.error('Custom widgets are not yet supported in Sveltia CMS.'); void [name, control, preview, schema]; };
Register a custom widget. @param {string} name Widget name. @param {ComponentType<CustomWidgetControlProps> | string} control Component for the edit pane. @param {ComponentType<CustomWidgetPreviewProps>} [preview] Component for the preview pane. @param {CustomWidgetSchema} [schema] Field schema. @see https://decapcms.org/docs/custom-widgets/
registerWidget
javascript
sveltia/sveltia-cms
src/lib/main.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/main.js
MIT
export const getFolderLabelByCollection = (collectionName) => { if (collectionName === '*') { return get(_)('all_assets'); } if (!collectionName) { return get(_)('uncategorized'); } return get(siteConfig)?.collections.find(({ name }) => name === collectionName)?.label ?? ''; };
Get the label for the given collection. It can be a category name if the folder is a collection-specific asset folder. @param {string | undefined} collectionName Collection name. @returns {string} Human-readable label. @see https://decapcms.org/docs/collection-folder/#media-and-public-folder
getFolderLabelByCollection
javascript
sveltia/sveltia-cms
src/lib/services/assets/view.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/view.js
MIT
export const getFolderLabelByPath = (folderPath) => { const { media_folder: defaultMediaFolder } = /** @type {InternalSiteConfig} */ (get(siteConfig)); if (!folderPath) { return getFolderLabelByCollection('*'); } if (folderPath === defaultMediaFolder) { return getFolderLabelByCollection(undefined); } const folder = get(allAssetFolders).find(({ internalPath }) => internalPath === folderPath); if (folder) { return getFolderLabelByCollection(folder.collectionName); } return ''; };
Get the label for the given folder path. It can be a category name if the folder is a collection-specific asset folder. @param {string | undefined} folderPath Media folder path. @returns {string} Human-readable label. @see https://decapcms.org/docs/collection-folder/#media-and-public-folder
getFolderLabelByPath
javascript
sveltia/sveltia-cms
src/lib/services/assets/view.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/view.js
MIT
const getValue = (asset) => { const { commitAuthor: { name, login, email } = {}, commitDate } = asset; if (key === 'commit_author') { return name || login || email; } if (key === 'commit_date') { return commitDate; } // Exclude the file extension when sorting by name to sort numbered files properly, e.g. // `hero.png`, `hero-1.png`, `hero-2.png` instead of `hero-1.png`, `hero-2.png`, `hero.png` if (key === 'name') { return asset.name.split('.')[0]; } return /** @type {Record<string, any>} */ (asset)[key] ?? ''; };
Get an asset’s property value. @param {Asset} asset Asset. @returns {any} Value.
getValue
javascript
sveltia/sveltia-cms
src/lib/services/assets/view.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/view.js
MIT
const filterAssets = (assets, { field, pattern } = { field: '', pattern: '' }) => { if (!field) { return assets; } if (field === 'fileType') { return assets.filter(({ path }) => getAssetKind(path) === pattern); } const regex = typeof pattern === 'string' ? new RegExp(pattern) : undefined; return assets.filter((asset) => { const value = /** @type {Record<string, any>} */ (asset)[field]; if (regex) { return regex.test(String(value ?? '')); } return value === pattern; }); };
Filter the given assets. @param {Asset[]} assets Asset list. @param {FilteringConditions} [conditions] Filtering conditions. @returns {Asset[]} Filtered asset list.
filterAssets
javascript
sveltia/sveltia-cms
src/lib/services/assets/view.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/view.js
MIT
const groupAssets = (assets, { field, pattern } = { field: '', pattern: undefined }) => { if (!field) { return assets.length ? { '*': assets } : {}; } const regex = typeof pattern === 'string' ? new RegExp(pattern) : undefined; /** @type {Record<string, Asset[]>} */ const groups = {}; const otherKey = get(_)('other'); assets.forEach((asset) => { const value = /** @type {Record<string, any>} */ (asset)[field]; /** @type {string} */ let key; if (regex) { [key = otherKey] = String(value ?? '').match(regex) ?? []; } else { key = value; } if (!(key in groups)) { groups[key] = []; } groups[key].push(asset); }); // Sort groups by key return Object.fromEntries(Object.entries(groups).sort(([aKey], [bKey]) => compare(aKey, bKey))); };
Group the given assets. @param {Asset[]} assets Asset list. @param {GroupingConditions} [conditions] Grouping conditions. @returns {Record<string, Asset[]>} Grouped assets, where key is a group label and value is an asset list.
groupAssets
javascript
sveltia/sveltia-cms
src/lib/services/assets/view.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/view.js
MIT
const initSettings = async ({ repository }) => { const { databaseName } = repository ?? {}; const settingsDB = databaseName ? new IndexedDB(databaseName, 'ui-settings') : null; const storageKey = 'assets-view'; assetListSettings.set((await settingsDB?.get(storageKey)) ?? {}); assetListSettings.subscribe((_settings) => { (async () => { try { if (!equal(_settings, await settingsDB?.get(storageKey))) { await settingsDB?.set(storageKey, _settings); } } catch { // } })(); }); selectedAssetFolder.subscribe((folder) => { const view = get(assetListSettings)?.[folder?.internalPath || '*'] ?? structuredClone(defaultView); if (!equal(view, get(currentView))) { currentView.set(view); } }); currentView.subscribe((view) => { const path = get(selectedAssetFolder)?.internalPath || '*'; const savedView = get(assetListSettings)?.[path] ?? {}; if (!equal(view, savedView)) { assetListSettings.update((_settings) => ({ ..._settings, [path]: view })); } }); };
Initialize {@link assetListSettings} and relevant subscribers. @param {BackendService} _backend Backend service.
initSettings
javascript
sveltia/sveltia-cms
src/lib/services/assets/view.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/view.js
MIT
const addSavingEntryData = async (collectionFile) => { const { fields = [] } = collectionFile ?? collection; /** @type {EntryDraft} */ const draft = { ...draftProps, canPreview, collection, collectionName: collection.name, collectionFile, fileName: collectionFile?.name, fields, }; const { savingEntry, changes: savingEntryChanges } = await createSavingEntryData({ draft, slugs: getSlugs({ draft }), }); savingEntries.push(savingEntry); changes.push(...savingEntryChanges); }; const collectionFiles = getFilesByEntry(collection, entry); if (collectionFiles.length) { await Promise.all(collectionFiles.map(addSavingEntryData)); } else { await addSavingEntryData(); } }),
Add saving entry data to the stack. @param {InternalCollectionFile} [collectionFile] Collection file. File collection only.
addSavingEntryData
javascript
sveltia/sveltia-cms
src/lib/services/assets/data.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/data.js
MIT
export const deleteAssets = async (assets) => { await get(backend)?.commitChanges( assets.map(({ path }) => ({ action: 'delete', path })), { commitType: 'deleteMedia' }, ); allAssets.update((_allAssets) => _allAssets.filter((asset) => !assets.includes(asset))); // Clear asset info in the sidebar focusedAsset.update((_focusedAsset) => assets.some(({ path }) => _focusedAsset?.path === path) ? undefined : _focusedAsset, ); assetUpdatesToast.set({ ...updatesToastDefaultState, deleted: true, count: assets.length, }); };
Delete the given assets. @param {Asset[]} assets List of assets to be deleted. @todo Update entries to remove these asset paths. If an asset is used for a required field, show an error message and abort the operation.
deleteAssets
javascript
sveltia/sveltia-cms
src/lib/services/assets/data.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/data.js
MIT
export const getMaxFileSize = (fieldConfig) => { const size = getMediaLibraryOption('max_file_size', fieldConfig); if (typeof size === 'number' && Number.isInteger(size)) { return size; } return Infinity; };
Get the maximum file size for uploads. @param {ImageField | FileField} [fieldConfig] Field configuration. @returns {number} Size.
getMaxFileSize
javascript
sveltia/sveltia-cms
src/lib/services/assets/media-library.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/media-library.js
MIT
export const getFileTransformations = (fieldConfig) => { const option = getMediaLibraryOption('transformations', fieldConfig); if (isObject(option)) { return option; } return undefined; };
Get file transformation options. @param {ImageField | FileField} [fieldConfig] Field configuration. @returns {FileTransformations | undefined} Options.
getFileTransformations
javascript
sveltia/sveltia-cms
src/lib/services/assets/media-library.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/media-library.js
MIT
export const globalAssetFolder = derived([allAssetFolders], ([_allAssetFolders], set) => { set(_allAssetFolders.find(({ collectionName }) => !collectionName)); });
@type {Readable<CollectionAssetFolder | undefined>}
(anonymous)
javascript
sveltia/sveltia-cms
src/lib/services/assets/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/index.js
MIT
export const isMediaKind = (kind) => mediaKinds.includes(kind);
Check if the given asset kind is media. @param {string} kind Kind, e.g. `image` or `video`. @returns {boolean} Result.
isMediaKind
javascript
sveltia/sveltia-cms
src/lib/services/assets/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/index.js
MIT
export const canPreviewAsset = (asset) => { const type = mime.getType(asset.path); return isMediaKind(asset.kind) || type === 'application/pdf' || (!!type && isTextFileType(type)); };
Whether the given asset is previewable. @param {Asset} asset Asset. @returns {boolean} Result.
canPreviewAsset
javascript
sveltia/sveltia-cms
src/lib/services/assets/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/index.js
MIT
export const getMediaKind = async (source) => { let mimeType = ''; if (typeof source === 'string') { if (source.startsWith('blob:')) { try { mimeType = (await (await fetch(source)).blob()).type; } catch { // } } else { mimeType = mime.getType(source) ?? ''; } } else if (source instanceof Blob) { mimeType = source.type; } if (!mimeType) { return undefined; } const [type, subType] = mimeType.split('/'); if (isMediaKind(type) && !subType.startsWith('x-')) { return /** @type {AssetKind} */ (type); } return undefined; };
Get the media type of the given blob or path. @param {Blob | string} source Blob, blob URL, or asset path. @returns {Promise<AssetKind | undefined>} Kind.
getMediaKind
javascript
sveltia/sveltia-cms
src/lib/services/assets/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/index.js
MIT
export const canEditAsset = (asset) => { const type = mime.getType(asset.path); return !!type && isTextFileType(type); };
Whether the given asset is editable. @param {Asset} asset Asset. @returns {boolean} Result. @todo Support image editing.
canEditAsset
javascript
sveltia/sveltia-cms
src/lib/services/assets/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/index.js
MIT
export const getCollectionsByAsset = (asset) =>
Get a list of collections the given asset belongs to. @param {Asset} asset Asset. @returns {InternalCollection[]} Collections.
getCollectionsByAsset
javascript
sveltia/sveltia-cms
src/lib/services/assets/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/index.js
MIT
export const getAssetsByDirName = (dirname) =>
Get a list of assets stored in the given internal directory. @param {string} dirname Directory path. @returns {Asset[]} Assets.
getAssetsByDirName
javascript
sveltia/sveltia-cms
src/lib/services/assets/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/assets/index.js
MIT
export const fetchSiteConfig = async () => { /** @type {{ href: string, type?: string }[]} */ const links = /** @type {HTMLLinkElement[]} */ ([ ...document.querySelectorAll('link[rel="cms-config-url"]'), ]).map(({ href, type }) => ({ href, type })); if (!links.length) { links.push({ // Depending on the server or framework configuration, the trailing slash may be removed from // the CMS `/admin/` URL. In that case, fetch the config file from a root-relative URL instead // of a regular relative URL to avoid 404 Not Found. href: window.location.pathname === '/admin' ? '/admin/config.yml' : './config.yml', }); } const objects = await Promise.all(links.map((link) => fetchFile(link))); if (objects.length === 1) { return objects[0]; } return merge.all(objects); };
Fetch the YAML/JSON site configuration file(s) and return a parsed, merged object. @returns {Promise<object>} Configuration. @throws {Error} When fetching or parsing has failed.
fetchSiteConfig
javascript
sveltia/sveltia-cms
src/lib/services/config/loader.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/config/loader.js
MIT
export const goto = (path, { state = {}, replaceState = false, notifyChange = true } = {}) => { const oldURL = window.location.hash; const newURL = `#${path}`; /** @type {[any, string, string]} */ const args = [{ ...state, from: oldURL }, '', newURL]; if (replaceState) { window.history.replaceState(...args); } else { window.history.pushState(...args); } if (notifyChange) { window.dispatchEvent(new HashChangeEvent('hashchange', { oldURL, newURL })); } };
Navigate to a different URL or replace the current URL. This is similar to SvelteKit’s `goto` method but assumes hash-based SPA routing. @param {string} path URL path. It will appear in th URL hash but omit the leading `#` sign here. @param {object} [options] Options. @param {object} [options.state] History state to be included. @param {boolean} [options.replaceState] Whether to replace the history state. @param {boolean} [options.notifyChange] Whether to dispatch a `hashchange` event.
goto
javascript
sveltia/sveltia-cms
src/lib/services/app/navigation.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/app/navigation.js
MIT
export const goBack = (path, options = {}) => { if (window.history.state?.from) { window.history.back(); } else { goto(path, options); } };
Go back to the previous page if possible, or navigate to the given fallback URL. @param {string} path Fallback URL path. @param {object} [options] Options to be passed to {@link goto}.
goBack
javascript
sveltia/sveltia-cms
src/lib/services/app/navigation.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/app/navigation.js
MIT
export const openProductionSite = () => { const { display_url: displayURL, _siteURL: siteURL } = /** @type {InternalSiteConfig} */ ( get(siteConfig) ); window.open(displayURL || siteURL || '/', '_blank'); };
Open the production site in a new browser tab.
openProductionSite
javascript
sveltia/sveltia-cms
src/lib/services/app/navigation.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/app/navigation.js
MIT
export const getUnpkgURL = (name) => { const url = `https://unpkg.com/${name}`; const version = /** @type {Record<string, string>} */ (dependencies)[name]?.replace(/^\D/, ''); return version ? `${url}@${version}` : url; };
Get the UNPKG CDN URL for the given dependency. @param {string} name Dependency name. @returns {string} URL.
getUnpkgURL
javascript
sveltia/sveltia-cms
src/lib/services/app/dependencies.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/app/dependencies.js
MIT
const hasMatch = (label) => normalize(label).includes(terms);
Check if the given label matches the search terms. @param {string} label Label. @returns {boolean} Result.
hasMatch
javascript
sveltia/sveltia-cms
src/lib/services/search/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/search/index.js
MIT
const init = () => {};
Initialize the test backend. There is nothing to do here.
init
javascript
sveltia/sveltia-cms
src/lib/services/backends/test.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/test.js
MIT
const signOut = async () => {};
Sign out from the test backend. There is nothing to do here.
signOut
javascript
sveltia/sveltia-cms
src/lib/services/backends/test.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/test.js
MIT
const fetchFiles = async () => { await loadFiles(/** @type {FileSystemDirectoryHandle} */ (rootDirHandle)); };
Load file list and all the entry files from the file system, then cache them in the {@link allEntries} and {@link allAssets} stores.
fetchFiles
javascript
sveltia/sveltia-cms
src/lib/services/backends/test.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/test.js
MIT
get: (obj, key) => { if (key in obj) { return obj[key]; } const { baseURL, branch } = obj; if (key === 'treeBaseURL') { return branch ? `${baseURL}/-/tree/${branch}` : baseURL; } if (key === 'blobBaseURL') { return branch ? `${baseURL}/-/blob/${branch}` : ''; } return undefined; },
Define the getter. @param {Record<string, any>} obj Object itself. @param {string} key Property name. @returns {any} Property value.
get
javascript
sveltia/sveltia-cms
src/lib/services/backends/gitlab.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/gitlab.js
MIT
const checkStatus = async () => { try { const { result: { status_overall: { status_code: status }, }, } = /** @type {{ result: { status_overall: { status_code: number } } }} */ ( await sendRequest(statusCheckURL) ); if (status === 100) { return 'none'; } if ([200, 300, 400].includes(status)) { return 'minor'; } if ([500, 600].includes(status)) { return 'major'; } } catch { // } return 'unknown'; };
Check the GitLab service status. @returns {Promise<BackendServiceStatus>} Current status. @see https://kb.status.io/developers/public-status-api/
checkStatus
javascript
sveltia/sveltia-cms
src/lib/services/backends/gitlab.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/gitlab.js
MIT
const getRepositoryInfo = () => { const { repo: projectPath, branch } = /** @type {InternalSiteConfig} */ (get(siteConfig)).backend; const { origin, isSelfHosted } = apiConfig; /** * In GitLab terminology, an owner is called a namespace, and a repository is called a project. A * namespace can contain a group and a subgroup concatenated with a `/` so we cannot simply use * `split('/')` here. A project name should not contain a `/`. * @see https://docs.gitlab.com/ee/user/namespace/ * @see https://gitlab.com/gitlab-org/gitlab/-/merge_requests/80055 */ const { owner, repo } = /** @type {string} */ (projectPath).match(/(?<owner>.+)\/(?<repo>[^/]+)$/)?.groups ?? {};
Get the configured repository’s basic information. @returns {RepositoryInfo} Repository info.
getRepositoryInfo
javascript
sveltia/sveltia-cms
src/lib/services/backends/gitlab.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/gitlab.js
MIT
const signOut = async () => undefined;
Sign out from GitLab. Nothing to do here. @returns {Promise<void>}
signOut
javascript
sveltia/sveltia-cms
src/lib/services/backends/gitlab.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/gitlab.js
MIT
const fetchFileList = async () => { const { owner, repo, branch } = repository; /** @type {{ type: string, path: string, sha: string }[]} */ const blobs = []; let cursor = ''; // Since GitLab has a limit of 100 records per query, use pagination to fetch all the files for (;;) { const result = // /** * @type {{ project: { repository: { tree: { blobs: { * nodes: { type: string, path: string, sha: string }[], * pageInfo: { endCursor: string, hasNextPage: boolean } * } } } } }} */ ( await fetchGraphQL(` query { project(fullPath: "${owner}/${repo}") { repository { tree(ref: "${branch}", recursive: true) { blobs(after: "${cursor}") { nodes { type path sha } pageInfo { endCursor hasNextPage } } } } } } `) ); const { nodes, pageInfo: { endCursor, hasNextPage }, } = result.project.repository.tree.blobs; blobs.push(...nodes); cursor = endCursor; if (!hasNextPage) { break; } } // The `size` is not available here; it will be retrieved in `fetchFileContents` below. return blobs.filter(({ type }) => type === 'blob').map(({ path, sha }) => ({ path, sha })); };
Fetch the repository’s complete file list, and return it in the canonical format. @returns {Promise<BaseFileListItem[]>} File list. @see https://docs.gitlab.com/ee/api/graphql/reference/index.html#repositorytree @see https://stackoverflow.com/questions/18952935/how-to-get-subfolders-and-files-using-gitlab-api
fetchFileList
javascript
sveltia/sveltia-cms
src/lib/services/backends/gitlab.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/gitlab.js
MIT
const fetchFiles = async () => { await checkRepositoryAccess(); await fetchAndParseFiles({ repository, fetchDefaultBranchName, fetchLastCommit, fetchFileList, fetchFileContents, }); };
Fetch file list from the backend service, download/parse all the entry files, then cache them in the {@link allEntries} and {@link allAssets} stores.
fetchFiles
javascript
sveltia/sveltia-cms
src/lib/services/backends/gitlab.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/gitlab.js
MIT
const fetchBlob = async (asset) => { const { owner, repo, branch = '' } = repository; const { path } = asset; return /** @type {Promise<Blob>} */ ( fetchAPI( `/projects/${encodeURIComponent(`${owner}/${repo}`)}/repository/files` + `/${encodeURIComponent(path)}/raw?ref=${encodeURIComponent(branch)}`, {}, { responseType: 'blob' }, ) ); };
Fetch an asset as a Blob via the API. @param {Asset} asset Asset to retrieve the file content. @returns {Promise<Blob>} Blob data. @see https://docs.gitlab.com/ee/api/repository_files.html#get-raw-file-from-repository
fetchBlob
javascript
sveltia/sveltia-cms
src/lib/services/backends/gitlab.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/gitlab.js
MIT
const checkStatus = async () => { try { const { status: { indicator }, } = /** @type {{ status: { indicator: string }}} */ (await sendRequest(statusCheckURL)); if (indicator === 'none') { return 'none'; } if (indicator === 'minor') { return 'minor'; } if (indicator === 'major' || indicator === 'critical') { return 'major'; } } catch { // } return 'unknown'; };
Check the GitHub service status. @returns {Promise<BackendServiceStatus>} Current status. @see https://www.githubstatus.com/api
checkStatus
javascript
sveltia/sveltia-cms
src/lib/services/backends/github.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/github.js
MIT
const signIn = async ({ token: cachedToken, auto = false }) => { if (auto && !cachedToken) { return undefined; } const { hostname } = window.location; const { site_domain: siteDomain = hostname, base_url: baseURL = 'https://api.netlify.com', auth_endpoint: path = 'auth', } = /** @type {InternalSiteConfig} */ (get(siteConfig)).backend; const token = cachedToken || (await initServerSideAuth({ backendName, siteDomain, authURL: `${stripSlashes(baseURL)}/${stripSlashes(path)}`, scope: 'repo,user', })); const { id, name, login, email, avatar_url: avatarURL, html_url: profileURL, } = /** @type {any} */ (await fetchAPI('/user', {}, { token })); return { backendName, token, id, name, login, email, avatarURL, profileURL, }; };
Retrieve the repository configuration and sign in with GitHub REST API. @param {SignInOptions} options Options. @returns {Promise<User | void>} User info, or nothing when the sign-in flow cannot be started. @throws {Error} When there was an authentication error. @see https://docs.github.com/en/rest/users/users#get-the-authenticated-user
signIn
javascript
sveltia/sveltia-cms
src/lib/services/backends/github.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/github.js
MIT
const fetchFileList = async (lastHash) => { const { owner, repo, branch } = repository; const result = /** @type {{ tree: { type: string, path: string, sha: string, size: number }[] }} */ ( await fetchAPI(`/repos/${owner}/${repo}/git/trees/${lastHash ?? branch}?recursive=1`) ); return result.tree .filter(({ type }) => type === 'blob') .map(({ path, sha, size }) => ({ path, sha, size })); };
Fetch the repository’s complete file list, and return it in the canonical format. @param {string} [lastHash] The last commit’s SHA-1 hash. @returns {Promise<BaseFileListItem[]>} File list.
fetchFileList
javascript
sveltia/sveltia-cms
src/lib/services/backends/github.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/github.js
MIT
const getQuery = (chunk, startIndex) => { const innerQuery = chunk .map(({ type, path, sha }, i) => { const str = []; const index = startIndex + i; if (type === 'entry') { str.push(` content_${index}: object(oid: "${sha}") { ... on Blob { text } } `); } str.push(` commit_${index}: ref(qualifiedName: "${branch}") { target { ... on Commit { history(first: 1, path: "${path}") { nodes { author { name email user { id: databaseId login } } committedDate } } } } } `); return str.join(''); }) .join(''); return ` query { repository(owner: "${owner}", name: "${repo}") { ${innerQuery} } } `; };
Get a query string for a new API request. @param {any[]} chunk Sliced `fetchingFileList`. @param {number} startIndex Start index. @returns {string} Query string.
getQuery
javascript
sveltia/sveltia-cms
src/lib/services/backends/github.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/github.js
MIT
const triggerDeployment = async () => { const { owner, repo } = repository; return /** @type {Promise<Response>} */ ( fetchAPI( `/repos/${owner}/${repo}/dispatches`, { method: 'POST', body: { event_type: 'sveltia-cms-publish' }, }, { responseType: 'raw' }, ) ); };
Manually trigger a deployment with GitHub Actions by dispatching the `repository_dispatch` event. @returns {Promise<Response>} Response. @see https://docs.github.com/en/rest/repos/repos#create-a-repository-dispatch-event
triggerDeployment
javascript
sveltia/sveltia-cms
src/lib/services/backends/github.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/github.js
MIT
const getRootDirHandle = async ({ forceReload = false, showPicker = true } = {}) => { if (!('showDirectoryPicker' in window)) { throw new Error('unsupported'); } /** @type {FileSystemDirectoryHandle | null} */ let handle = forceReload ? null : ((await rootDirHandleDB?.get(rootDirHandleKey)) ?? null); if (handle) { if ((await handle.requestPermission({ mode: 'readwrite' })) !== 'granted') { handle = null; } else { try { await handle.entries().next(); } catch (/** @type {any} */ ex) { // The directory may have been (re)moved. Let the user pick the directory again handle = null; // eslint-disable-next-line no-console console.error(ex); } } } if (!handle && showPicker) { // This wil throw `AbortError` when the user dismissed the picker handle = await window.showDirectoryPicker(); if (handle) { // This will throw `NotFoundError` when it’s not a project root directory await handle.getDirectoryHandle('.git'); // If it looks fine, cache the directory handle await rootDirHandleDB?.set(rootDirHandleKey, handle); } } return /** @type {FileSystemDirectoryHandle | null} */ (handle); };
Get the project’s root directory handle so the app can read all the files under the directory. The handle will be cached in IndexedDB for later use. @param {object} [options] Options. @param {boolean} [options.forceReload] Whether to force getting the handle. @param {boolean} [options.showPicker] Whether to show the directory picker. @returns {Promise<FileSystemDirectoryHandle | null>} Directory handle. @throws {Error | AbortError | NotFoundError} When the File System Access API is not supported by the user’s browser, when the directory picker was dismissed, or when the selected directory is not a project root directory. There might be other reasons to throw. @see https://developer.chrome.com/articles/file-system-access/#stored-file-or-directory-handles-and-permissions
getRootDirHandle
javascript
sveltia/sveltia-cms
src/lib/services/backends/local.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/local.js
MIT
const signIn = async ({ auto = false }) => { const handle = await getRootDirHandle({ showPicker: !auto }); if (handle) { rootDirHandle = handle; } else { throw new Error('Directory handle could not be acquired'); } return { backendName }; };
Sign in with the local Git repository. There is no actual sign-in; just show the directory picker to get the handle, so we can read/write files. @param {SignInOptions} options Options. @returns {Promise<User>} User info. Since we don’t have any details for the local user, just return the backend name. @throws {Error} When the directory handle could not be acquired.
signIn
javascript
sveltia/sveltia-cms
src/lib/services/backends/local.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/local.js
MIT
const signOut = async () => { await rootDirHandleDB?.delete(rootDirHandleKey); };
Sign out from the local Git repository. There is no actual sign-out; just discard the cached root directory handle.
signOut
javascript
sveltia/sveltia-cms
src/lib/services/backends/local.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/local.js
MIT
export const backend = derived([backendName], ([name], _set, update) => { update((currentService) => { const newService = name ? allBackendServices[name] : undefined; if (newService && newService !== currentService) { newService.init(); } return newService; }); });
@type {Readable<BackendService | undefined>}
(anonymous)
javascript
sveltia/sveltia-cms
src/lib/services/backends/index.js
https://github.com/sveltia/sveltia-cms/blob/master/src/lib/services/backends/index.js
MIT