refactor(frontend): replace legacy utils JS files with typed TS equivalents

This commit is contained in:
Yiannis
2026-03-11 01:51:53 +02:00
parent df4b0422d5
commit 1b8e8aae6a
48 changed files with 711 additions and 502 deletions

View File

@@ -1,19 +0,0 @@
export function csrfToken() {
var i,
cookies,
cookie,
cookieVal = null;
if (document.cookie && '' !== document.cookie) {
cookies = document.cookie.split(';');
i = 0;
while (i < cookies.length) {
cookie = cookies[i].trim();
if ('csrftoken=' === cookie.substring(0, 10)) {
cookieVal = decodeURIComponent(cookie.substring(10));
break;
}
i += 1;
}
}
return cookieVal;
}

View File

@@ -0,0 +1,18 @@
export function csrfToken() {
let cookieVal = null;
if (document.cookie && '' !== document.cookie) {
const cookies = document.cookie.split(';');
let i = 0;
while (i < cookies.length) {
const cookie = cookies[i].trim();
if ('csrftoken=' === cookie.substring(0, 10)) {
cookieVal = decodeURIComponent(cookie.substring(10));
break;
}
i += 1;
}
}
return cookieVal;
}

View File

@@ -1,79 +0,0 @@
export function supportsSvgAsImg() {
// @link: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/svg/asimg.js
return document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#Image', '1.1');
}
export function removeClassname(el, cls) {
if (el.classList) {
el.classList.remove(cls);
} else {
el.className = el.className.replace(new RegExp('(^|\\b)' + cls.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
}
export function addClassname(el, cls) {
if (el.classList) {
el.classList.add(cls);
} else {
el.className += ' ' + cls;
}
}
export function hasClassname(el, cls) {
return el.className && new RegExp('(\\s|^)' + cls + '(\\s|$)').test(el.className);
}
export const cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;
export const requestAnimationFrame =
window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
export function BrowserEvents() {
const callbacks = {
document: {
visibility: [],
},
window: {
resize: [],
scroll: [],
},
};
function onDocumentVisibilityChange() {
callbacks.document.visibility.map((fn) => fn());
}
function onWindowResize() {
callbacks.window.resize.map((fn) => fn());
}
function onWindowScroll() {
callbacks.window.scroll.map((fn) => fn());
}
function windowEvents(resizeCallback, scrollCallback) {
if ('function' === typeof resizeCallback) {
callbacks.window.resize.push(resizeCallback);
}
if ('function' === typeof scrollCallback) {
callbacks.window.scroll.push(scrollCallback);
}
}
function documentEvents(visibilityChangeCallback) {
if ('function' === typeof visibilityChangeCallback) {
callbacks.document.visibility.push(visibilityChangeCallback);
}
}
document.addEventListener('visibilitychange', onDocumentVisibilityChange);
window.addEventListener('resize', onWindowResize);
window.addEventListener('scroll', onWindowScroll);
return {
doc: documentEvents,
win: windowEvents,
};
}

View File

@@ -0,0 +1,95 @@
export function supportsSvgAsImg() {
// @link: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/svg/asimg.js
return document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#Image', '1.1');
}
export function removeClassname(el: HTMLElement, cls: string) {
if (el.classList) {
el.classList.remove(cls);
} else {
el.className = el.className.replace(new RegExp('(^|\\b)' + cls.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
}
export function addClassname(el: HTMLElement, cls: string) {
if (el.classList) {
el.classList.add(cls);
} else {
el.className += ' ' + cls;
}
}
export function hasClassname(el: HTMLElement, cls: string) {
return el.className && new RegExp('(\\s|^)' + cls + '(\\s|$)').test(el.className);
}
type LegacyWindow = Window & {
mozCancelAnimationFrame?: Window['cancelAnimationFrame'];
mozRequestAnimationFrame?: Window['requestAnimationFrame'];
msRequestAnimationFrame?: Window['requestAnimationFrame'];
webkitRequestAnimationFrame?: Window['requestAnimationFrame'];
};
const legacyWindow = window as LegacyWindow;
export const cancelAnimationFrame: Window['cancelAnimationFrame'] =
legacyWindow.cancelAnimationFrame ||
legacyWindow.mozCancelAnimationFrame ||
((id: number) => window.clearTimeout(id));
export const requestAnimationFrame: Window['requestAnimationFrame'] =
legacyWindow.requestAnimationFrame ||
legacyWindow.mozRequestAnimationFrame ||
legacyWindow.webkitRequestAnimationFrame ||
legacyWindow.msRequestAnimationFrame ||
((callback: FrameRequestCallback) => window.setTimeout(() => callback(performance.now()), 16));
export function BrowserEvents() {
const callbacks = {
document: {
visibility: [] as Function[],
},
window: {
resize: [] as Function[],
scroll: [] as Function[],
},
};
function onDocumentVisibilityChange() {
callbacks.document.visibility.map((fn) => fn());
}
function onWindowResize() {
callbacks.window.resize.map((fn) => fn());
}
function onWindowScroll() {
callbacks.window.scroll.map((fn) => fn());
}
function windowEvents(resizeCallback?: Function, scrollCallback?: Function) {
if ('function' === typeof resizeCallback) {
callbacks.window.resize.push(resizeCallback);
}
if ('function' === typeof scrollCallback) {
callbacks.window.scroll.push(scrollCallback);
}
}
function documentEvents(visibilityChangeCallback?: Function) {
if ('function' === typeof visibilityChangeCallback) {
callbacks.document.visibility.push(visibilityChangeCallback);
}
}
document.addEventListener('visibilitychange', onDocumentVisibilityChange);
window.addEventListener('resize', onWindowResize);
window.addEventListener('scroll', onWindowScroll);
return {
doc: documentEvents,
win: windowEvents,
};
}

View File

@@ -7,7 +7,7 @@ export function inEmbeddedApp() {
sessionStorage.setItem('media_cms_embed_mode', 'true');
return true;
}
if (mode === 'standard') {
sessionStorage.removeItem('media_cms_embed_mode');
return false;

View File

@@ -1,27 +0,0 @@
// TODO: Improve or (even better) remove this file code.
import { error as logErrFn, warn as logWarnFn } from './log';
function logAndReturnError(logFn, msgArr, ErrorConstructor) {
let err;
switch (ErrorConstructor) {
case TypeError:
case RangeError:
case SyntaxError:
case ReferenceError:
err = new ErrorConstructor(msgArr[0]);
break;
default:
err = new Error(msgArr[0]);
}
logFn(err.message, ...msgArr.slice(1));
return err;
}
export function logErrorAndReturnError(msgArr, ErrorConstructor) {
return logAndReturnError(logErrFn, msgArr, ErrorConstructor);
}
export function logWarningAndReturnError(msgArr, ErrorConstructor) {
return logAndReturnError(logWarnFn, msgArr, ErrorConstructor);
}

View File

@@ -0,0 +1,15 @@
// @todo: Improve or (even better) remove this file.
import { error, warn } from './log';
export function logErrorAndReturnError(msgArr: string[]) {
const err = new Error(msgArr[0]);
error(...msgArr);
return err;
}
export function logWarningAndReturnError(msgArr: string[]) {
const err = new Error(msgArr[0]);
warn(...msgArr);
return err;
}

View File

@@ -1,5 +0,0 @@
import * as dispatcher from '../dispatcher.js';
export default function (store, handler) {
dispatcher.register(store[handler].bind(store));
return store;
}

View File

@@ -0,0 +1,28 @@
import EventEmitter from 'events';
import { dispatcher } from '../dispatcher';
// type ClassProperties<C> = {
// [Key in keyof C as C[Key] extends Function ? never : Key]: C[Key];
// };
type ClassMethods<C> = {
[Key in keyof C as C[Key] extends Function ? Key : never]: C[Key];
};
// @todo: Check this again
export function exportStore<TStore extends EventEmitter, THandler extends keyof ClassMethods<TStore>>(
store: TStore,
handler: THandler
) {
const method = store[handler] as Function;
const callback: (payload: unknown) => void = method.bind(store);
dispatcher.register(callback);
return store;
}
// @todo: Remove older vesion.
// export function exportStore_OLD(store, handler) {
// const callback = store[handler].bind(store);
// dispatcher.register(callback);
// return store;
// }

View File

@@ -1,11 +0,0 @@
import urlParse from 'url-parse';
export function formatInnerLink(url, baseUrl) {
let link = urlParse(url, {});
if ('' === link.origin || 'null' === link.origin || !link.origin) {
link = urlParse(baseUrl + '/' + url.replace(/^\//g, ''), {});
}
return link.toString();
}

View File

@@ -0,0 +1,11 @@
import urlParse from 'url-parse';
export function formatInnerLink(url: string, baseUrl: string) {
let link = urlParse(url, {});
if ('' === link.origin || 'null' === link.origin || !link.origin) {
link = urlParse(baseUrl + '/' + url.replace(/^\//g, ''), {});
}
return link.toString();
}

View File

@@ -1,15 +0,0 @@
import { months as monthList } from '../constants/';
export function formatManagementTableDate(date) {
const day = date.getDate();
const month = monthList[date.getMonth()].substring(0, 3);
const year = date.getFullYear();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
let ret = month + ' ' + day + ', ' + year;
ret += ' ' + (hours < 10 ? '0' : '') + hours;
ret += ':' + (minutes < 10 ? '0' : '') + minutes;
ret += ':' + (seconds < 10 ? '0' : '') + seconds;
return ret;
}

View File

@@ -0,0 +1,15 @@
import { months as monthList } from '../constants';
export function formatManagementTableDate(date: Date) {
const day = date.getDate();
const month = monthList[date.getMonth()].substring(0, 3);
const year = date.getFullYear();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
let ret = month + ' ' + day + ', ' + year;
ret += ' ' + (hours < 10 ? '0' : '') + hours;
ret += ':' + (minutes < 10 ? '0' : '') + minutes;
ret += ':' + (seconds < 10 ? '0' : '') + seconds;
return ret;
}

View File

@@ -1,18 +0,0 @@
export default function (views_number, fullNumber) {
function formattedValue(val, lim, unit) {
return Number(parseFloat(val / lim).toFixed(val < 10 * lim ? 1 : 0)) + unit;
}
function format(i, views, mult, compare, limit, units) {
while (views >= compare) {
limit *= mult;
compare *= mult;
i += 1;
}
return i < units.length
? formattedValue(views, limit, units[i])
: formattedValue(views * (mult * (i - (units.length - 1))), limit, units[units.length - 1]);
}
return fullNumber ? views_number.toLocaleString() : format(0, views_number, 1000, 1000, 1, ['', 'K', 'M', 'B', 'T']);
}

View File

@@ -0,0 +1,17 @@
const formattedValue = (val: number, lim: number, unit: string) =>
Number((val / lim).toFixed(val < 10 * lim ? 1 : 0)) + unit;
function format(cntr: number, views: number, mult: number, compare: number, limit: number, units: string[]) {
let i = cntr;
while (views >= compare) {
limit *= mult;
compare *= mult;
i += 1;
}
return i < units.length
? formattedValue(views, limit, units[i])
: formattedValue(views * (mult * (i - (units.length - 1))), limit, units[units.length - 1]);
}
export const formatViewsNumber = (views_number: number, fullNumber?: boolean) =>
fullNumber ? views_number.toLocaleString() : format(0, views_number, 1000, 1000, 1, ['', 'K', 'M', 'B', 'T']);

View File

@@ -1,7 +0,0 @@
export const imageExtension = (img) => {
if (!img) {
return;
}
const ext = img.split('.');
return ext[ext.length - 1];
};

View File

@@ -0,0 +1,5 @@
export const imageExtension = (img: string) => {
if (img) {
return img.split('.').pop();
}
};

View File

@@ -1,17 +0,0 @@
export * from './dom';
export * from './errors';
export { default as exportStore } from './exportStore';
export { formatInnerLink } from './formatInnerLink';
export * from './formatManagementTableDate';
export { default as formatViewsNumber } from './formatViewsNumber';
export * from './csrfToken';
export { imageExtension } from './imageExtension';
export * from './log';
export * from './math';
export * from './propTypeFilters';
export { default as publishedOnDate } from './publishedOnDate';
export * from './quickSort';
export * from './requests';
export { translateString } from './translate';
export { replaceString } from './replacementStrings';
export * from './embeddedApp';

View File

@@ -0,0 +1,17 @@
export * from './csrfToken';
export * from './dom';
export * from './embeddedApp';
export * from './errors';
export * from './exportStore';
export * from './formatInnerLink';
export * from './formatManagementTableDate';
export * from './formatViewsNumber';
export * from './imageExtension';
export * from './log';
export * from './math';
export * from './propTypeFilters';
export * from './publishedOnDate';
export * from './quickSort';
export * from './requests';
export * from './translate';
export * from './replacementStrings';

View File

@@ -1,4 +0,0 @@
const log = (...x) => console[x[0]](...x.slice(1));
export const warn = (...x) => log('warn', ...x);
export const error = (...x) => log('error', ...x);

View File

@@ -0,0 +1,9 @@
// @todo: Delete this file
export const warn = (...x: string[]) => {
console.warn(...x);
};
export const error = (...x: string[]) => {
console.error(...x);
};

View File

@@ -1,10 +0,0 @@
export const isGt = (x, y) => x > y;
export const isZero = (x) => 0 === x;
export const isNumber = (x) => !isNaN(x) && x === 0 + x;
export const isInteger = (x) => x === Math.trunc(x);
export const isPositive = (x) => isGt(x, 0);
export const isPositiveNumber = (x) => isNumber(x) && isPositive(x);
export const isPositiveInteger = (x) => isInteger(x) && isPositive(x);
export const isPositiveIntegerOrZero = (x) => isInteger(x) && (isPositive(x) || isZero(x));
export const greaterCommonDivision = (a, b) => (!b ? a : greaterCommonDivision(b, a % b));

View File

@@ -0,0 +1,10 @@
export const isGt = (x: number, y: number) => x > y;
export const isZero = (x: number) => 0 === x;
export const isNumber = (x: number) => 'number' === typeof x && !Number.isNaN(x);
export const isInteger = (x: number) => x === Math.trunc(x);
export const isPositive = (x: number) => isGt(x, 0);
export const isPositiveNumber = (x: number) => isNumber(x) && isPositive(x);
export const isPositiveInteger = (x: number) => isInteger(x) && isPositive(x);
export const isPositiveIntegerOrZero = (x: number) => isInteger(x) && (isPositive(x) || isZero(x));
export const greaterCommonDivision = (a: number, b: number): number => (!b ? a : greaterCommonDivision(b, a % b));

View File

@@ -1,10 +1,10 @@
import { logErrorAndReturnError } from './errors';
import { isPositiveInteger, isPositiveIntegerOrZero } from './math';
// @todo: Check this
export const PositiveIntegerOrZero = (function () {
const isPositiveIntegerOrZero = (x) => x === Math.trunc(x) && x >= 0;
return function (obj, key, comp) {
return void 0 === obj[key] || isPositiveIntegerOrZero(obj[key])
return function (obj: Record<string, number>, key: string, comp: string) {
return obj[key] === undefined || isPositiveIntegerOrZero(obj[key])
? null
: logErrorAndReturnError([
'Invalid prop `' +
@@ -20,11 +20,10 @@ export const PositiveIntegerOrZero = (function () {
};
})();
// @todo: Check this
export const PositiveInteger = (function () {
const isPositiveInteger = (x) => x === Math.trunc(x) && x > 0;
return function (obj, key, comp) {
return void 0 === obj[key] || isPositiveInteger(obj[key])
return function (obj: Record<string, number>, key: string, comp: string) {
return obj[key] === undefined || isPositiveInteger(obj[key])
? null
: logErrorAndReturnError([
'Invalid prop `' +

View File

@@ -1,17 +0,0 @@
import { months } from '../constants';
export default function publishedOnDate(date, type) {
if (date instanceof Date) {
type = 0 + type;
type = 0 < type ? type : 1;
switch (type) {
case 1:
return months[date.getMonth()].substring(0, 3) + ' ' + date.getDate() + ', ' + date.getFullYear();
case 2:
return date.getDate() + ' ' + months[date.getMonth()].substring(0, 3) + ' ' + date.getFullYear();
case 3:
return date.getDate() + ' ' + months[date.getMonth()] + ' ' + date.getFullYear();
}
}
return null;
}

View File

@@ -0,0 +1,17 @@
import { months } from '../constants';
export function publishedOnDate(date: Date, type: 1 | 2 | 3 = 1) {
if (!(date instanceof Date)) {
return null;
}
if (type === 2) {
return date.getDate() + ' ' + months[date.getMonth()].substring(0, 3) + ' ' + date.getFullYear();
}
if (type === 3) {
return date.getDate() + ' ' + months[date.getMonth()] + ' ' + date.getFullYear();
}
return months[date.getMonth()].substring(0, 3) + ' ' + date.getDate() + ', ' + date.getFullYear();
}

View File

@@ -1,35 +0,0 @@
function swap(arr, i, j) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
function partition(arr, pivot, left, right) {
var pivotValue = arr[pivot],
partitionIndex = left;
for (var i = left; i < right; i++) {
if (arr[i] < pivotValue) {
swap(arr, i, partitionIndex);
partitionIndex++;
}
}
swap(arr, right, partitionIndex);
return partitionIndex;
}
export function quickSort(arr, left, right) {
var len = arr.length,
pivot,
partitionIndex;
if (left < right) {
pivot = right;
partitionIndex = partition(arr, pivot, left, right);
//sort left and right
quickSort(arr, left, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, right);
}
return arr;
}

View File

@@ -0,0 +1,29 @@
function swap(arr: unknown[], i: number, j: number) {
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
function partition(arr: number[], pivot: number, left: number, right: number) {
const pivotValue = arr[pivot];
let partitionIndex = left;
for (let i = left; i < right; i++) {
if (arr[i] < pivotValue) {
swap(arr, i, partitionIndex);
partitionIndex++;
}
}
swap(arr, right, partitionIndex);
return partitionIndex;
}
export function quickSort(arr: number[], left: number, right: number) {
if (left < right) {
const pivot = right;
const partitionIndex = partition(arr, pivot, left, right);
//sort left and right
quickSort(arr, left, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, right);
}
return arr;
}

View File

@@ -1,15 +0,0 @@
// check templates/config/installation/translations.html for more
export function replaceString(word) {
if (!window.REPLACEMENTS) {
return word;
}
let result = word;
for (const [search, replacement] of Object.entries(window.REPLACEMENTS)) {
result = result.split(search).join(replacement);
}
return result;
}

View File

@@ -0,0 +1,47 @@
// check templates/config/installation/translations.html for more
declare global {
interface Window {
REPLACEMENTS?: Record<string, string>;
}
}
export function replaceString(word: string) {
if (!window.REPLACEMENTS) {
return word;
}
let result = word;
for (const [search, replacement] of Object.entries(window.REPLACEMENTS)) {
result = result.split(search).join(replacement);
}
return result;
}
// @todo: Check this alterative.
/*function replaceStringRegExp(word: string) {
if (!window.REPLACEMENTS) {
return word;
}
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
let result = word;
for (const [search, replacement] of Object.entries(window.REPLACEMENTS)) {
const regex = new RegExp(escapeRegExp(search), 'g');
result = result.replace(regex, replacement);
}
return result;
}*/
// @todo: Remove older vesion.
/*export function replaceString_OLD(string: string) {
for (const key in window.REPLACEMENTS) {
string = string.replace(key, window.REPLACEMENTS[key]);
}
return string;
}*/

View File

@@ -1,135 +0,0 @@
import axios from 'axios';
export async function getRequest(url, sync, callback, errorCallback) {
const requestConfig = {
timeout: null,
maxContentLength: null,
};
function responseHandler(result) {
if (callback instanceof Function || typeof callback === 'function') {
callback(result);
}
}
function errorHandler(error) {
if (errorCallback instanceof Function || typeof errorCallback === 'function') {
let err = error;
if (void 0 === error.response) {
err = {
type: 'network',
error: error,
};
} else if (void 0 !== error.response.status) {
// TODO: Improve this, it's valid only in case of media requests.
switch (error.response.status) {
case 401:
err = {
type: 'private',
error: error,
message: 'Media is private',
};
break;
case 400:
err = {
type: 'unavailable',
error: error,
message: 'Media is unavailable',
};
break;
}
}
errorCallback(err);
}
}
if (sync) {
await axios.get(url, requestConfig)
.then(responseHandler)
.catch(errorHandler || null);
} else {
axios.get(url, requestConfig)
.then(responseHandler)
.catch(errorHandler || null);
}
}
export async function postRequest(url, postData, configData, sync, callback, errorCallback) {
postData = postData || {};
function responseHandler(result) {
if (callback instanceof Function || typeof callback === 'function') {
callback(result);
}
}
function errorHandler(error) {
if (errorCallback instanceof Function || typeof errorCallback === 'function') {
errorCallback(error);
}
}
if (sync) {
await axios.post(url, postData, configData || null)
.then(responseHandler)
.catch(errorHandler || null);
} else {
axios.post(url, postData, configData || null)
.then(responseHandler)
.catch(errorHandler || null);
}
}
export async function putRequest(url, putData, configData, sync, callback, errorCallback) {
putData = putData || {};
function responseHandler(result) {
if (callback instanceof Function || typeof callback === 'function') {
callback(result);
}
}
function errorHandler(error) {
if (errorCallback instanceof Function || typeof errorCallback === 'function') {
errorCallback(error);
}
}
if (sync) {
await axios.put(url, putData, configData || null)
.then(responseHandler)
.catch(errorHandler || null);
} else {
axios.put(url, putData, configData || null)
.then(responseHandler)
.catch(errorHandler || null);
}
}
export async function deleteRequest(url, configData, sync, callback, errorCallback) {
configData = configData || {};
function responseHandler(result) {
if (callback instanceof Function || typeof callback === 'function') {
callback(result);
}
}
function errorHandler(error) {
if (errorCallback instanceof Function || typeof errorCallback === 'function') {
errorCallback(error);
}
}
if (sync) {
await axios
.delete(url, configData || null)
.then(responseHandler)
.catch(errorHandler || null);
} else {
axios
.delete(url, configData || null)
.then(responseHandler)
.catch(errorHandler || null);
}
}

View File

@@ -0,0 +1,169 @@
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
export async function getRequest(
url: string,
sync: boolean = false,
callback?: (response: AxiosResponse<any, any, {}>) => void,
errorCallback?: (err: any) => void
) {
const requestConfig = {
timeout: undefined,
maxContentLength: undefined,
};
function responseHandler(result: AxiosResponse<any, any, {}>) {
if (callback) {
callback(result);
}
}
function errorHandler(reason: any) {
if (!errorCallback) {
return;
}
let err = reason;
if (reason.response === undefined) {
err = {
type: 'network',
error: reason,
};
} else if (reason.response.status !== undefined) {
// @todo: Improve this, it's valid only in case of media requests.
switch (reason.response.status) {
case 401:
err = {
type: 'private',
error: reason,
message: 'Media is private',
};
break;
case 400:
err = {
type: 'unavailable',
error: reason,
message: 'Media is unavailable',
};
break;
}
}
errorCallback(err);
}
if (sync) {
await axios
.get(url, requestConfig)
.then(responseHandler)
.catch(errorHandler || null);
} else {
axios
.get(url, requestConfig)
.then(responseHandler)
.catch(errorHandler || null);
}
}
export async function postRequest(
url: string,
postData: any,
configData?: AxiosRequestConfig<any>,
sync: boolean = false,
callback?: (response: AxiosResponse<any, any, {}>) => void,
errorCallback?: (error: any) => void
) {
postData = postData || {};
function responseHandler(result: AxiosResponse<any, any, {}>) {
if (callback) {
callback(result);
}
}
function errorHandler(error: any) {
if (errorCallback) {
errorCallback(error);
}
}
if (sync) {
await axios
.post(url, postData, configData)
.then(responseHandler)
.catch(errorHandler || null);
} else {
axios
.post(url, postData, configData)
.then(responseHandler)
.catch(errorHandler || null);
}
}
export async function putRequest(
url: string,
putData: any,
configData?: AxiosRequestConfig<any>,
sync: boolean = false,
callback?: (response: AxiosResponse<any, any, {}>) => void,
errorCallback?: (error: any) => void
) {
putData = putData || {};
function responseHandler(result: AxiosResponse<any, any, {}>) {
if (callback) {
callback(result);
}
}
function errorHandler(error: any) {
if (errorCallback) {
errorCallback(error);
}
}
if (sync) {
await axios
.put(url, putData, configData)
.then(responseHandler)
.catch(errorHandler || null);
} else {
axios
.put(url, putData, configData)
.then(responseHandler)
.catch(errorHandler || null);
}
}
export async function deleteRequest(
url: string,
configData?: AxiosRequestConfig<any>,
sync: boolean = false,
callback?: (response: AxiosResponse<any, any, {}>) => void,
errorCallback?: (error: any) => void
) {
configData = configData || {};
function responseHandler(result: AxiosResponse<any, any, {}>) {
if (callback) {
callback(result);
}
}
function errorHandler(error: any) {
if (errorCallback) {
errorCallback(error);
}
}
if (sync) {
await axios
.delete(url, configData)
.then(responseHandler)
.catch(errorHandler || null);
} else {
axios
.delete(url, configData || null)
.then(responseHandler)
.catch(errorHandler || null);
}
}

View File

@@ -1,5 +0,0 @@
// check templates/config/installation/translations.html for more
export function translateString(str) {
return window.TRANSLATION?.[str] ?? str;
}

View File

@@ -0,0 +1,11 @@
// check templates/config/installation/translations.html for more
declare global {
interface Window {
TRANSLATION?: Record<string, string>;
}
}
export function translateString(word: string) {
return window.TRANSLATION?.[word] ?? word;
}