mirror of
https://github.com/BookStackApp/BookStack.git
synced 2025-07-31 15:24:31 +03:00
Upgraded app to Laravel 5.7
This commit is contained in:
106
resources/js/services/animations.js
Normal file
106
resources/js/services/animations.js
Normal file
@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Fade out the given element.
|
||||
* @param {Element} element
|
||||
* @param {Number} animTime
|
||||
* @param {Function|null} onComplete
|
||||
*/
|
||||
export function fadeOut(element, animTime = 400, onComplete = null) {
|
||||
animateStyles(element, {
|
||||
opacity: ['1', '0']
|
||||
}, animTime, () => {
|
||||
element.style.display = 'none';
|
||||
if (onComplete) onComplete();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide the element by sliding the contents upwards.
|
||||
* @param {Element} element
|
||||
* @param {Number} animTime
|
||||
*/
|
||||
export function slideUp(element, animTime = 400) {
|
||||
const currentHeight = element.getBoundingClientRect().height;
|
||||
const computedStyles = getComputedStyle(element);
|
||||
const currentPaddingTop = computedStyles.getPropertyValue('padding-top');
|
||||
const currentPaddingBottom = computedStyles.getPropertyValue('padding-bottom');
|
||||
const animStyles = {
|
||||
height: [`${currentHeight}px`, '0px'],
|
||||
overflow: ['hidden', 'hidden'],
|
||||
paddingTop: [currentPaddingTop, '0px'],
|
||||
paddingBottom: [currentPaddingBottom, '0px'],
|
||||
};
|
||||
|
||||
animateStyles(element, animStyles, animTime, () => {
|
||||
element.style.display = 'none';
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the given element by expanding the contents.
|
||||
* @param {Element} element - Element to animate
|
||||
* @param {Number} animTime - Animation time in ms
|
||||
*/
|
||||
export function slideDown(element, animTime = 400) {
|
||||
element.style.display = 'block';
|
||||
const targetHeight = element.getBoundingClientRect().height;
|
||||
const computedStyles = getComputedStyle(element);
|
||||
const targetPaddingTop = computedStyles.getPropertyValue('padding-top');
|
||||
const targetPaddingBottom = computedStyles.getPropertyValue('padding-bottom');
|
||||
const animStyles = {
|
||||
height: ['0px', `${targetHeight}px`],
|
||||
overflow: ['hidden', 'hidden'],
|
||||
paddingTop: ['0px', targetPaddingTop],
|
||||
paddingBottom: ['0px', targetPaddingBottom],
|
||||
};
|
||||
|
||||
animateStyles(element, animStyles, animTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* Used in the function below to store references of clean-up functions.
|
||||
* Used to ensure only one transitionend function exists at any time.
|
||||
* @type {WeakMap<object, any>}
|
||||
*/
|
||||
const animateStylesCleanupMap = new WeakMap();
|
||||
|
||||
/**
|
||||
* Animate the css styles of an element using FLIP animation techniques.
|
||||
* Styles must be an object where the keys are style properties, camelcase, and the values
|
||||
* are an array of two items in the format [initialValue, finalValue]
|
||||
* @param {Element} element
|
||||
* @param {Object} styles
|
||||
* @param {Number} animTime
|
||||
* @param {Function} onComplete
|
||||
*/
|
||||
function animateStyles(element, styles, animTime = 400, onComplete = null) {
|
||||
const styleNames = Object.keys(styles);
|
||||
for (let style of styleNames) {
|
||||
element.style[style] = styles[style][0];
|
||||
}
|
||||
|
||||
const cleanup = () => {
|
||||
for (let style of styleNames) {
|
||||
element.style[style] = null;
|
||||
}
|
||||
element.style.transition = null;
|
||||
element.removeEventListener('transitionend', cleanup);
|
||||
if (onComplete) onComplete();
|
||||
};
|
||||
|
||||
setTimeout(() => {
|
||||
requestAnimationFrame(() => {
|
||||
element.style.transition = `all ease-in-out ${animTime}ms`;
|
||||
for (let style of styleNames) {
|
||||
element.style[style] = styles[style][1];
|
||||
}
|
||||
|
||||
if (animateStylesCleanupMap.has(element)) {
|
||||
const oldCleanup = animateStylesCleanupMap.get(element);
|
||||
element.removeEventListener('transitionend', oldCleanup);
|
||||
}
|
||||
|
||||
element.addEventListener('transitionend', cleanup);
|
||||
animateStylesCleanupMap.set(element, cleanup);
|
||||
});
|
||||
}, 10);
|
||||
}
|
280
resources/js/services/code.js
Normal file
280
resources/js/services/code.js
Normal file
@ -0,0 +1,280 @@
|
||||
import CodeMirror from "codemirror";
|
||||
import Clipboard from "clipboard/dist/clipboard.min";
|
||||
|
||||
// Modes
|
||||
import 'codemirror/mode/css/css';
|
||||
import 'codemirror/mode/clike/clike';
|
||||
import 'codemirror/mode/diff/diff';
|
||||
import 'codemirror/mode/go/go';
|
||||
import 'codemirror/mode/htmlmixed/htmlmixed';
|
||||
import 'codemirror/mode/javascript/javascript';
|
||||
import 'codemirror/mode/julia/julia';
|
||||
import 'codemirror/mode/lua/lua';
|
||||
import 'codemirror/mode/haskell/haskell';
|
||||
import 'codemirror/mode/markdown/markdown';
|
||||
import 'codemirror/mode/mllike/mllike';
|
||||
import 'codemirror/mode/nginx/nginx';
|
||||
import 'codemirror/mode/php/php';
|
||||
import 'codemirror/mode/powershell/powershell';
|
||||
import 'codemirror/mode/python/python';
|
||||
import 'codemirror/mode/ruby/ruby';
|
||||
import 'codemirror/mode/rust/rust';
|
||||
import 'codemirror/mode/shell/shell';
|
||||
import 'codemirror/mode/sql/sql';
|
||||
import 'codemirror/mode/toml/toml';
|
||||
import 'codemirror/mode/xml/xml';
|
||||
import 'codemirror/mode/yaml/yaml';
|
||||
|
||||
// Addons
|
||||
import 'codemirror/addon/scroll/scrollpastend';
|
||||
|
||||
const modeMap = {
|
||||
css: 'css',
|
||||
c: 'text/x-csrc',
|
||||
java: 'text/x-java',
|
||||
scala: 'text/x-scala',
|
||||
kotlin: 'text/x-kotlin',
|
||||
'c++': 'text/x-c++src',
|
||||
'c#': 'text/x-csharp',
|
||||
csharp: 'text/x-csharp',
|
||||
diff: 'diff',
|
||||
go: 'go',
|
||||
haskell: 'haskell',
|
||||
hs: 'haskell',
|
||||
html: 'htmlmixed',
|
||||
javascript: 'javascript',
|
||||
json: {name: 'javascript', json: true},
|
||||
js: 'javascript',
|
||||
jl: 'julia',
|
||||
julia: 'julia',
|
||||
lua: 'lua',
|
||||
md: 'markdown',
|
||||
mdown: 'markdown',
|
||||
markdown: 'markdown',
|
||||
ml: 'mllike',
|
||||
nginx: 'nginx',
|
||||
powershell: 'powershell',
|
||||
ocaml: 'mllike',
|
||||
php: 'php',
|
||||
py: 'python',
|
||||
python: 'python',
|
||||
ruby: 'ruby',
|
||||
rust: 'rust',
|
||||
rb: 'ruby',
|
||||
rs: 'rust',
|
||||
shell: 'shell',
|
||||
sh: 'shell',
|
||||
bash: 'shell',
|
||||
toml: 'toml',
|
||||
sql: 'text/x-sql',
|
||||
xml: 'xml',
|
||||
yaml: 'yaml',
|
||||
yml: 'yaml',
|
||||
};
|
||||
|
||||
/**
|
||||
* Highlight pre elements on a page
|
||||
*/
|
||||
function highlight() {
|
||||
let codeBlocks = document.querySelectorAll('.page-content pre, .comment-box .content pre');
|
||||
for (let i = 0; i < codeBlocks.length; i++) {
|
||||
highlightElem(codeBlocks[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add code highlighting to a single element.
|
||||
* @param {HTMLElement} elem
|
||||
*/
|
||||
function highlightElem(elem) {
|
||||
let innerCodeElem = elem.querySelector('code[class^=language-]');
|
||||
let mode = '';
|
||||
if (innerCodeElem !== null) {
|
||||
let langName = innerCodeElem.className.replace('language-', '');
|
||||
mode = getMode(langName);
|
||||
}
|
||||
elem.innerHTML = elem.innerHTML.replace(/<br\s*[\/]?>/gi ,'\n');
|
||||
let content = elem.textContent.trim();
|
||||
|
||||
let cm = CodeMirror(function(elt) {
|
||||
elem.parentNode.replaceChild(elt, elem);
|
||||
}, {
|
||||
value: content,
|
||||
mode: mode,
|
||||
lineNumbers: true,
|
||||
theme: getTheme(),
|
||||
readOnly: true
|
||||
});
|
||||
|
||||
addCopyIcon(cm);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a button to a CodeMirror instance which copies the contents to the clipboard upon click.
|
||||
* @param cmInstance
|
||||
*/
|
||||
function addCopyIcon(cmInstance) {
|
||||
const copyIcon = `<svg viewBox="0 0 24 24" width="16" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>`;
|
||||
const copyButton = document.createElement('div');
|
||||
copyButton.classList.add('CodeMirror-copy');
|
||||
copyButton.innerHTML = copyIcon;
|
||||
cmInstance.display.wrapper.appendChild(copyButton);
|
||||
|
||||
const clipboard = new Clipboard(copyButton, {
|
||||
text: function(trigger) {
|
||||
return cmInstance.getValue()
|
||||
}
|
||||
});
|
||||
|
||||
clipboard.on('success', event => {
|
||||
copyButton.classList.add('success');
|
||||
setTimeout(() => {
|
||||
copyButton.classList.remove('success');
|
||||
}, 240);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for a codemirror code based off a user suggestion
|
||||
* @param suggestion
|
||||
* @returns {string}
|
||||
*/
|
||||
function getMode(suggestion) {
|
||||
suggestion = suggestion.trim().replace(/^\./g, '').toLowerCase();
|
||||
return (typeof modeMap[suggestion] !== 'undefined') ? modeMap[suggestion] : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Ge the theme to use for CodeMirror instances.
|
||||
* @returns {*|string}
|
||||
*/
|
||||
function getTheme() {
|
||||
return window.codeTheme || 'base16-light';
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a CodeMirror instance for showing inside the WYSIWYG editor.
|
||||
* Manages a textarea element to hold code content.
|
||||
* @param {HTMLElement} elem
|
||||
* @returns {{wrap: Element, editor: *}}
|
||||
*/
|
||||
function wysiwygView(elem) {
|
||||
let doc = elem.ownerDocument;
|
||||
let codeElem = elem.querySelector('code');
|
||||
|
||||
let lang = (elem.className || '').replace('language-', '');
|
||||
if (lang === '' && codeElem) {
|
||||
lang = (codeElem.className || '').replace('language-', '')
|
||||
}
|
||||
|
||||
elem.innerHTML = elem.innerHTML.replace(/<br\s*[\/]?>/gi ,'\n');
|
||||
let content = elem.textContent;
|
||||
let newWrap = doc.createElement('div');
|
||||
let newTextArea = doc.createElement('textarea');
|
||||
|
||||
newWrap.className = 'CodeMirrorContainer';
|
||||
newWrap.setAttribute('data-lang', lang);
|
||||
newWrap.setAttribute('dir', 'ltr');
|
||||
newTextArea.style.display = 'none';
|
||||
elem.parentNode.replaceChild(newWrap, elem);
|
||||
|
||||
newWrap.appendChild(newTextArea);
|
||||
newWrap.contentEditable = false;
|
||||
newTextArea.textContent = content;
|
||||
|
||||
let cm = CodeMirror(function(elt) {
|
||||
newWrap.appendChild(elt);
|
||||
}, {
|
||||
value: content,
|
||||
mode: getMode(lang),
|
||||
lineNumbers: true,
|
||||
theme: getTheme(),
|
||||
readOnly: true
|
||||
});
|
||||
setTimeout(() => {
|
||||
cm.refresh();
|
||||
}, 300);
|
||||
return {wrap: newWrap, editor: cm};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a CodeMirror instance to show in the WYSIWYG pop-up editor
|
||||
* @param {HTMLElement} elem
|
||||
* @param {String} modeSuggestion
|
||||
* @returns {*}
|
||||
*/
|
||||
function popupEditor(elem, modeSuggestion) {
|
||||
let content = elem.textContent;
|
||||
|
||||
return CodeMirror(function(elt) {
|
||||
elem.parentNode.insertBefore(elt, elem);
|
||||
elem.style.display = 'none';
|
||||
}, {
|
||||
value: content,
|
||||
mode: getMode(modeSuggestion),
|
||||
lineNumbers: true,
|
||||
theme: getTheme(),
|
||||
lineWrapping: true
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the mode of a codemirror instance.
|
||||
* @param cmInstance
|
||||
* @param modeSuggestion
|
||||
*/
|
||||
function setMode(cmInstance, modeSuggestion) {
|
||||
cmInstance.setOption('mode', getMode(modeSuggestion));
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the content of a cm instance.
|
||||
* @param cmInstance
|
||||
* @param codeContent
|
||||
*/
|
||||
function setContent(cmInstance, codeContent) {
|
||||
cmInstance.setValue(codeContent);
|
||||
setTimeout(() => {
|
||||
cmInstance.refresh();
|
||||
}, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a CodeMirror instace to use for the markdown editor.
|
||||
* @param {HTMLElement} elem
|
||||
* @returns {*}
|
||||
*/
|
||||
function markdownEditor(elem) {
|
||||
let content = elem.textContent;
|
||||
|
||||
return CodeMirror(function (elt) {
|
||||
elem.parentNode.insertBefore(elt, elem);
|
||||
elem.style.display = 'none';
|
||||
}, {
|
||||
value: content,
|
||||
mode: "markdown",
|
||||
lineNumbers: true,
|
||||
theme: getTheme(),
|
||||
lineWrapping: true,
|
||||
scrollPastEnd: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the 'meta' key dependant on the user's system.
|
||||
* @returns {string}
|
||||
*/
|
||||
function getMetaKey() {
|
||||
let mac = CodeMirror.keyMap["default"] == CodeMirror.keyMap.macDefault;
|
||||
return mac ? "Cmd" : "Ctrl";
|
||||
}
|
||||
|
||||
export default {
|
||||
highlight: highlight,
|
||||
wysiwygView: wysiwygView,
|
||||
popupEditor: popupEditor,
|
||||
setMode: setMode,
|
||||
setContent: setContent,
|
||||
markdownEditor: markdownEditor,
|
||||
getMetaKey: getMetaKey,
|
||||
};
|
24
resources/js/services/dates.js
Normal file
24
resources/js/services/dates.js
Normal file
@ -0,0 +1,24 @@
|
||||
|
||||
export function getCurrentDay() {
|
||||
let date = new Date();
|
||||
let month = date.getMonth() + 1;
|
||||
let day = date.getDate();
|
||||
|
||||
return `${date.getFullYear()}-${(month>9?'':'0') + month}-${(day>9?'':'0') + day}`;
|
||||
}
|
||||
|
||||
export function utcTimeStampToLocalTime(timestamp) {
|
||||
let date = new Date(timestamp * 1000);
|
||||
let hours = date.getHours();
|
||||
let mins = date.getMinutes();
|
||||
return `${(hours>9?'':'0') + hours}:${(mins>9?'':'0') + mins}`;
|
||||
}
|
||||
|
||||
export function formatDateTime(date) {
|
||||
let month = date.getMonth() + 1;
|
||||
let day = date.getDate();
|
||||
let hours = date.getHours();
|
||||
let mins = date.getMinutes();
|
||||
|
||||
return `${date.getFullYear()}-${(month>9?'':'0') + month}-${(day>9?'':'0') + day} ${(hours>9?'':'0') + hours}:${(mins>9?'':'0') + mins}`;
|
||||
}
|
75
resources/js/services/dom.js
Normal file
75
resources/js/services/dom.js
Normal file
@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Run the given callback against each element that matches the given selector.
|
||||
* @param {String} selector
|
||||
* @param {Function<Element>} callback
|
||||
*/
|
||||
export function forEach(selector, callback) {
|
||||
const elements = document.querySelectorAll(selector);
|
||||
for (let element of elements) {
|
||||
callback(element);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to listen to multiple DOM events
|
||||
* @param {Element} listenerElement
|
||||
* @param {Array<String>} events
|
||||
* @param {Function<Event>} callback
|
||||
*/
|
||||
export function onEvents(listenerElement, events, callback) {
|
||||
for (let eventName of events) {
|
||||
listenerElement.addEventListener(eventName, callback);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to run an action when an element is selected.
|
||||
* A "select" is made to be accessible, So can be a click, space-press or enter-press.
|
||||
* @param listenerElement
|
||||
* @param callback
|
||||
*/
|
||||
export function onSelect(listenerElement, callback) {
|
||||
listenerElement.addEventListener('click', callback);
|
||||
listenerElement.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
callback(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a listener on an element for an event emitted by a child
|
||||
* matching the given childSelector param.
|
||||
* Used in a similar fashion to jQuery's $('listener').on('eventName', 'childSelector', callback)
|
||||
* @param {Element} listenerElement
|
||||
* @param {String} childSelector
|
||||
* @param {String} eventName
|
||||
* @param {Function} callback
|
||||
*/
|
||||
export function onChildEvent(listenerElement, childSelector, eventName, callback) {
|
||||
listenerElement.addEventListener(eventName, function(event) {
|
||||
const matchingChild = event.target.closest(childSelector);
|
||||
if (matchingChild) {
|
||||
callback.call(matchingChild, event, matchingChild);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Look for elements that match the given selector and contain the given text.
|
||||
* Is case insensitive and returns the first result or null if nothing is found.
|
||||
* @param {String} selector
|
||||
* @param {String} text
|
||||
* @returns {Element}
|
||||
*/
|
||||
export function findText(selector, text) {
|
||||
const elements = document.querySelectorAll(selector);
|
||||
text = text.toLowerCase();
|
||||
for (let element of elements) {
|
||||
if (element.textContent.toLowerCase().includes(text)) {
|
||||
return element;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
88
resources/js/services/drawio.js
Normal file
88
resources/js/services/drawio.js
Normal file
@ -0,0 +1,88 @@
|
||||
|
||||
const drawIoUrl = 'https://www.draw.io/?embed=1&ui=atlas&spin=1&proto=json';
|
||||
let iFrame = null;
|
||||
|
||||
let onInit, onSave;
|
||||
|
||||
/**
|
||||
* Show the draw.io editor.
|
||||
* @param onInitCallback - Must return a promise with the xml to load for the editor.
|
||||
* @param onSaveCallback - Is called with the drawing data on save.
|
||||
*/
|
||||
function show(onInitCallback, onSaveCallback) {
|
||||
onInit = onInitCallback;
|
||||
onSave = onSaveCallback;
|
||||
|
||||
iFrame = document.createElement('iframe');
|
||||
iFrame.setAttribute('frameborder', '0');
|
||||
window.addEventListener('message', drawReceive);
|
||||
iFrame.setAttribute('src', drawIoUrl);
|
||||
iFrame.setAttribute('class', 'fullscreen');
|
||||
iFrame.style.backgroundColor = '#FFFFFF';
|
||||
document.body.appendChild(iFrame);
|
||||
}
|
||||
|
||||
function close() {
|
||||
drawEventClose();
|
||||
}
|
||||
|
||||
function drawReceive(event) {
|
||||
if (!event.data || event.data.length < 1) return;
|
||||
let message = JSON.parse(event.data);
|
||||
if (message.event === 'init') {
|
||||
drawEventInit();
|
||||
} else if (message.event === 'exit') {
|
||||
drawEventClose();
|
||||
} else if (message.event === 'save') {
|
||||
drawEventSave(message);
|
||||
} else if (message.event === 'export') {
|
||||
drawEventExport(message);
|
||||
}
|
||||
}
|
||||
|
||||
function drawEventExport(message) {
|
||||
if (onSave) {
|
||||
onSave(message.data);
|
||||
}
|
||||
}
|
||||
|
||||
function drawEventSave(message) {
|
||||
drawPostMessage({action: 'export', format: 'xmlpng', xml: message.xml, spin: 'Updating drawing'});
|
||||
}
|
||||
|
||||
function drawEventInit() {
|
||||
if (!onInit) return;
|
||||
onInit().then(xml => {
|
||||
drawPostMessage({action: 'load', autosave: 1, xml: xml});
|
||||
});
|
||||
}
|
||||
|
||||
function drawEventClose() {
|
||||
window.removeEventListener('message', drawReceive);
|
||||
if (iFrame) document.body.removeChild(iFrame);
|
||||
}
|
||||
|
||||
function drawPostMessage(data) {
|
||||
iFrame.contentWindow.postMessage(JSON.stringify(data), '*');
|
||||
}
|
||||
|
||||
async function upload(imageData, pageUploadedToId) {
|
||||
let data = {
|
||||
image: imageData,
|
||||
uploaded_to: pageUploadedToId,
|
||||
};
|
||||
const resp = await window.$http.post(window.baseUrl(`/images/drawio`), data);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load an existing image, by fetching it as Base64 from the system.
|
||||
* @param drawingId
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async function load(drawingId) {
|
||||
const resp = await window.$http.get(window.baseUrl(`/images/drawio/base64/${drawingId}`));
|
||||
return `data:image/png;base64,${resp.data.content}`;
|
||||
}
|
||||
|
||||
export default {show, close, upload, load};
|
28
resources/js/services/events.js
Normal file
28
resources/js/services/events.js
Normal file
@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Simple global events manager
|
||||
*/
|
||||
class Events {
|
||||
constructor() {
|
||||
this.listeners = {};
|
||||
this.stack = [];
|
||||
}
|
||||
|
||||
emit(eventName, eventData) {
|
||||
this.stack.push({name: eventName, data: eventData});
|
||||
if (typeof this.listeners[eventName] === 'undefined') return this;
|
||||
let eventsToStart = this.listeners[eventName];
|
||||
for (let i = 0; i < eventsToStart.length; i++) {
|
||||
let event = eventsToStart[i];
|
||||
event(eventData);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
listen(eventName, callback) {
|
||||
if (typeof this.listeners[eventName] === 'undefined') this.listeners[eventName] = [];
|
||||
this.listeners[eventName].push(callback);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
export default Events;
|
146
resources/js/services/http.js
Normal file
146
resources/js/services/http.js
Normal file
@ -0,0 +1,146 @@
|
||||
|
||||
/**
|
||||
* Perform a HTTP GET request.
|
||||
* Can easily pass query parameters as the second parameter.
|
||||
* @param {String} url
|
||||
* @param {Object} params
|
||||
* @returns {Promise<{headers: Headers, original: Response, data: (Object|String), redirected: boolean, statusText: string, url: string, status: number}>}
|
||||
*/
|
||||
async function get(url, params = {}) {
|
||||
return request(url, {
|
||||
method: 'GET',
|
||||
params,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a HTTP POST request.
|
||||
* @param {String} url
|
||||
* @param {Object} data
|
||||
* @returns {Promise<{headers: Headers, original: Response, data: (Object|String), redirected: boolean, statusText: string, url: string, status: number}>}
|
||||
*/
|
||||
async function post(url, data = null) {
|
||||
return dataRequest('POST', url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a HTTP PUT request.
|
||||
* @param {String} url
|
||||
* @param {Object} data
|
||||
* @returns {Promise<{headers: Headers, original: Response, data: (Object|String), redirected: boolean, statusText: string, url: string, status: number}>}
|
||||
*/
|
||||
async function put(url, data = null) {
|
||||
return dataRequest('PUT', url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a HTTP PATCH request.
|
||||
* @param {String} url
|
||||
* @param {Object} data
|
||||
* @returns {Promise<{headers: Headers, original: Response, data: (Object|String), redirected: boolean, statusText: string, url: string, status: number}>}
|
||||
*/
|
||||
async function patch(url, data = null) {
|
||||
return dataRequest('PATCH', url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a HTTP DELETE request.
|
||||
* @param {String} url
|
||||
* @param {Object} data
|
||||
* @returns {Promise<{headers: Headers, original: Response, data: (Object|String), redirected: boolean, statusText: string, url: string, status: number}>}
|
||||
*/
|
||||
async function performDelete(url, data = null) {
|
||||
return dataRequest('DELETE', url, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a HTTP request to the back-end that includes data in the body.
|
||||
* Parses the body to JSON if an object, setting the correct headers.
|
||||
* @param {String} method
|
||||
* @param {String} url
|
||||
* @param {Object} data
|
||||
* @returns {Promise<{headers: Headers, original: Response, data: (Object|String), redirected: boolean, statusText: string, url: string, status: number}>}
|
||||
*/
|
||||
async function dataRequest(method, url, data = null) {
|
||||
const options = {
|
||||
method: method,
|
||||
body: data,
|
||||
};
|
||||
|
||||
if (typeof data === 'object' && !(data instanceof FormData)) {
|
||||
options.headers = {'Content-Type': 'application/json'};
|
||||
options.body = JSON.stringify(data);
|
||||
}
|
||||
|
||||
return request(url, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new HTTP request, setting the required CSRF information
|
||||
* to communicate with the back-end. Parses & formats the response.
|
||||
* @param {String} url
|
||||
* @param {Object} options
|
||||
* @returns {Promise<{headers: Headers, original: Response, data: (Object|String), redirected: boolean, statusText: string, url: string, status: number}>}
|
||||
*/
|
||||
async function request(url, options = {}) {
|
||||
if (!url.startsWith('http')) {
|
||||
url = window.baseUrl(url);
|
||||
}
|
||||
|
||||
if (options.params) {
|
||||
const urlObj = new URL(url);
|
||||
for (let paramName of Object.keys(options.params)) {
|
||||
const value = options.params[paramName];
|
||||
if (typeof value !== 'undefined' && value !== null) {
|
||||
urlObj.searchParams.set(paramName, value);
|
||||
}
|
||||
}
|
||||
url = urlObj.toString();
|
||||
}
|
||||
|
||||
const csrfToken = document.querySelector('meta[name=token]').getAttribute('content');
|
||||
options = Object.assign({}, options, {
|
||||
'credentials': 'same-origin',
|
||||
});
|
||||
options.headers = Object.assign({}, options.headers || {}, {
|
||||
'baseURL': window.baseUrl(''),
|
||||
'X-CSRF-TOKEN': csrfToken,
|
||||
});
|
||||
|
||||
const response = await fetch(url, options);
|
||||
const content = await getResponseContent(response);
|
||||
return {
|
||||
data: content,
|
||||
headers: response.headers,
|
||||
redirected: response.redirected,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
url: response.url,
|
||||
original: response,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the content from a fetch response.
|
||||
* Checks the content-type header to determine the format.
|
||||
* @param response
|
||||
* @returns {Promise<Object|String>}
|
||||
*/
|
||||
async function getResponseContent(response) {
|
||||
const responseContentType = response.headers.get('Content-Type');
|
||||
const subType = responseContentType.split('/').pop();
|
||||
|
||||
if (subType === 'javascript' || subType === 'json') {
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
return await response.text();
|
||||
}
|
||||
|
||||
export default {
|
||||
get: get,
|
||||
post: post,
|
||||
put: put,
|
||||
patch: patch,
|
||||
delete: performDelete,
|
||||
};
|
120
resources/js/services/translations.js
Normal file
120
resources/js/services/translations.js
Normal file
@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Translation Manager
|
||||
* Handles the JavaScript side of translating strings
|
||||
* in a way which fits with Laravel.
|
||||
*/
|
||||
class Translator {
|
||||
|
||||
/**
|
||||
* Create an instance, Passing in the required translations
|
||||
* @param translations
|
||||
*/
|
||||
constructor(translations) {
|
||||
this.store = new Map();
|
||||
this.parseTranslations();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse translations out of the page and place into the store.
|
||||
*/
|
||||
parseTranslations() {
|
||||
const translationMetaTags = document.querySelectorAll('meta[name="translation"]');
|
||||
for (let tag of translationMetaTags) {
|
||||
const key = tag.getAttribute('key');
|
||||
const value = tag.getAttribute('value');
|
||||
this.store.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a translation, Same format as laravel's 'trans' helper
|
||||
* @param key
|
||||
* @param replacements
|
||||
* @returns {*}
|
||||
*/
|
||||
get(key, replacements) {
|
||||
const text = this.getTransText(key);
|
||||
return this.performReplacements(text, replacements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get pluralised text, Dependant on the given count.
|
||||
* Same format at laravel's 'trans_choice' helper.
|
||||
* @param key
|
||||
* @param count
|
||||
* @param replacements
|
||||
* @returns {*}
|
||||
*/
|
||||
getPlural(key, count, replacements) {
|
||||
const text = this.getTransText(key);
|
||||
const splitText = text.split('|');
|
||||
const exactCountRegex = /^{([0-9]+)}/;
|
||||
const rangeRegex = /^\[([0-9]+),([0-9*]+)]/;
|
||||
let result = null;
|
||||
|
||||
for (let t of splitText) {
|
||||
// Parse exact matches
|
||||
const exactMatches = t.match(exactCountRegex);
|
||||
if (exactMatches !== null && Number(exactMatches[1]) === count) {
|
||||
result = t.replace(exactCountRegex, '').trim();
|
||||
break;
|
||||
}
|
||||
|
||||
// Parse range matches
|
||||
const rangeMatches = t.match(rangeRegex);
|
||||
if (rangeMatches !== null) {
|
||||
const rangeStart = Number(rangeMatches[1]);
|
||||
if (rangeStart <= count && (rangeMatches[2] === '*' || Number(rangeMatches[2]) >= count)) {
|
||||
result = t.replace(rangeRegex, '').trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (result === null && splitText.length > 1) {
|
||||
result = (count === 1) ? splitText[0] : splitText[1];
|
||||
}
|
||||
|
||||
if (result === null) {
|
||||
result = splitText[0];
|
||||
}
|
||||
|
||||
return this.performReplacements(result, replacements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetched translation text from the store for the given key.
|
||||
* @param key
|
||||
* @returns {String|Object}
|
||||
*/
|
||||
getTransText(key) {
|
||||
const value = this.store.get(key);
|
||||
|
||||
if (value === undefined) {
|
||||
console.warn(`Translation with key "${key}" does not exist`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform replacements on a string.
|
||||
* @param {String} string
|
||||
* @param {Object} replacements
|
||||
* @returns {*}
|
||||
*/
|
||||
performReplacements(string, replacements) {
|
||||
if (!replacements) return string;
|
||||
const replaceMatches = string.match(/:([\S]+)/g);
|
||||
if (replaceMatches === null) return string;
|
||||
replaceMatches.forEach(match => {
|
||||
const key = match.substring(1);
|
||||
if (typeof replacements[key] === 'undefined') return;
|
||||
string = string.replace(match, replacements[key]);
|
||||
});
|
||||
return string;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default Translator;
|
48
resources/js/services/util.js
Normal file
48
resources/js/services/util.js
Normal file
@ -0,0 +1,48 @@
|
||||
|
||||
|
||||
/**
|
||||
* Returns a function, that, as long as it continues to be invoked, will not
|
||||
* be triggered. The function will be called after it stops being called for
|
||||
* N milliseconds. If `immediate` is passed, trigger the function on the
|
||||
* leading edge, instead of the trailing.
|
||||
* @attribution https://davidwalsh.name/javascript-debounce-function
|
||||
* @param func
|
||||
* @param wait
|
||||
* @param immediate
|
||||
* @returns {Function}
|
||||
*/
|
||||
export function debounce(func, wait, immediate) {
|
||||
let timeout;
|
||||
return function() {
|
||||
const context = this, args = arguments;
|
||||
const later = function() {
|
||||
timeout = null;
|
||||
if (!immediate) func.apply(context, args);
|
||||
};
|
||||
const callNow = immediate && !timeout;
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(later, wait);
|
||||
if (callNow) func.apply(context, args);
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Scroll and highlight an element.
|
||||
* @param {HTMLElement} element
|
||||
*/
|
||||
export function scrollAndHighlightElement(element) {
|
||||
if (!element) return;
|
||||
element.scrollIntoView({behavior: 'smooth'});
|
||||
|
||||
const color = document.getElementById('custom-styles').getAttribute('data-color-light');
|
||||
const initColor = window.getComputedStyle(element).getPropertyValue('background-color');
|
||||
element.style.backgroundColor = color;
|
||||
setTimeout(() => {
|
||||
element.classList.add('selectFade');
|
||||
element.style.backgroundColor = initColor;
|
||||
}, 10);
|
||||
setTimeout(() => {
|
||||
element.classList.remove('selectFade');
|
||||
element.style.backgroundColor = '';
|
||||
}, 3000);
|
||||
}
|
Reference in New Issue
Block a user