import * as cookies from 'es-cookie'; // utilities import { log } from '@gringlobal/client/utilities/debug'; /** * A very wordy comparison of two arrays */ export function arraysEqual(a: any[], b: any[]): boolean { if ((a === null || a === undefined) && (b === null || b === undefined)) { return true; } else if ((a === null || a === undefined) && (b !== null || b !== undefined)) { return false; } else if ((a !== null || a !== undefined) && (b === null || b === undefined)) { return false; } else if (a.length !== b.length) { return false; } else { for (let i = 0; i < a.length && i < b.length; i++) { if (a[i] !== b[i]) { return false; } } return true; } } export const withPermissionCheck = (...permissions) => (promised) => (dispatch, getState) => { return promised(dispatch, getState).then((res) => { if (!Object.entries(res._permissions).reduce((res, [key, val]) => res && (!permissions.includes(key) || val), true)) { throw { code: 401, message: 'You have no rights to view this page' }; } return res; }); }; export function saveCookies(resp, expireOn: number, apiUrl: string) { const domain = apiUrl.includes('.') ? `.${apiUrl.split('.').filter((item, index, arr) => index > arr.length - 3).join('.')}` : 'localhost'; const expDate = new Date(expireOn); log(`Saving cookies to expire on ${expDate}`); cookies.set('access_token', resp.access_token, { domain, path: '/', expires: expDate }); cookies.set('authorities', JSON.stringify(resp.authorities), { domain, path: '/', expires: expDate }); if (resp.refresh_token) { cookies.set('refresh_token', resp.refresh_token, { domain, path: '/', expires: expDate }); } else { cookies.remove('refresh_token'); } } export function clearCookies() { log('Clearing cookies'); ['authorities', 'access_token', 'refresh_token'].forEach((key) => cookies.remove(key)); } export function isNumeric(value: any): boolean { return !isNaN(value - parseFloat(value)); } /** * This function remaps reference-by-ID to full objects * * Examples: * dereferenceReferences2(paged.content, { uuid: [ 'owner', 'foobar' ], id: [ 'institute' ]}); * * `_self` allows you to handle top-level references: * dereferenceReferences2(paged.content, { _self: 'user', uuid: [ 'user', 'owner', 'foobar' ], id: [ 'institute' ]}); * * @param content The list of objects * @param referenceMap The map of ID-keys of properties */ export function dereferenceReferences(content: any[], referenceMap: any, refs: { [key: string]: any } = {}): any[] { // Convert cross-references to Partner object if (!content) { return content; } const { _self, ...refMap } = referenceMap; let _selfName = null; if (_self) { _selfName = Object.keys(refMap).filter((id) => { // check if mapping for this id contains _self name return refMap[id].filter((elem) => elem === _self).length === 1; }); if (_selfName.length === 1) { _selfName = _selfName[0]; console.log(`_Self ${_self} is by ${_selfName}`); if (! refs[`${_self}`]) { refs[`${_self}`] = {}; // initialize map } } } else { // console.log('No _self found in', referenceMap); } if (_selfName) { // scan for selfs first content.forEach((entry) => { if (entry && typeof entry === 'object') { // add self if declared // console.log(`Registered _self reference ${_self}.'${entry[_selfName]}' using ${_selfName}`); refs[`${_self}`][entry[`${_selfName}`]] = entry; } }); } // deep search first content.forEach((entry) => { if (entry && typeof entry === 'object') { for (const p of Object.keys(entry)) { if (entry[p] && typeof entry[p] === 'object') { dereferenceReferences([entry[p]], refMap, refs); } } } }); // console.log('Handling references', content); Object.keys(refMap).forEach((id) => { const props: string[] = refMap[id]; // iterate over unique prop names props.filter((elem, pos, arr) => arr.indexOf(elem) === pos).forEach((prop) => { const prop0 = Array.isArray(props) ? props[0] : props; // use 1st element as master prop key if (!refs[prop0]) { refs[prop0] = {} } // setup // console.log(`Dereferencing ${prop}.${id} as ${prop0}`); content.filter((entry) => entry && entry[prop] && typeof entry[prop] === 'object' && entry[prop][id]) .map((entry) => entry[prop]) .forEach((ref) => { refs[prop0][`${ref[id]}`] = ref; // console.log(`Registered ${prop0}.'${ref[id]}' using ${id} in`, refs[prop0]); }); content.filter((entry) => entry && entry[prop] && typeof entry[prop] !== 'object') .forEach((entry) => { // console.log(`Looking up ${prop0}.'${entry[prop]}' in`, refs[prop0]); entry[prop] = refs[prop0][`${entry[prop]}`] || entry[prop]; // keep original if not found }); }); }); if (_selfName) { content.forEach((entry, index) => { if (entry && typeof entry !== 'object') { // add self if declared // console.log(`Looking up _self reference ${_self}.'${entry}'`); content[index] = refs[`${_self}`][`${entry}`]; } }); } return content; } export function insertAtCaret(element, myValue) { const doc = document as any; if (doc.selection) { // For browsers like Internet Explorer element.focus(); const sel = doc.selection.createRange(); sel.text = myValue; element.focus(); } else if (element.selectionStart || element.selectionStart === '0') { // For browsers like Firefox and Webkit based const startPos = element.selectionStart; const endPos = element.selectionEnd; const scrollTop = element.scrollTop; element.value = element.value.substring(0, startPos) + myValue + element.value.substring(endPos, element.value.length); element.focus(); element.selectionStart = startPos + myValue.length; element.selectionEnd = startPos + myValue.length; element.scrollTop = scrollTop; } else { element.value += myValue; element.focus(); } }