demarches-normaliennes/app/javascript/shared/utils.ts

198 lines
4.9 KiB
TypeScript
Raw Normal View History

import Rails from '@rails/ujs';
2018-10-09 11:32:27 +02:00
import debounce from 'debounce';
2022-04-28 19:10:21 +02:00
import { session } from '@hotwired/turbo';
2018-10-09 11:32:27 +02:00
export { debounce };
2022-04-28 19:10:21 +02:00
export const { fire, csrfToken, cspNonce } = Rails;
2018-10-09 11:32:27 +02:00
2022-05-06 19:35:14 +02:00
export function show(el: HTMLElement | null) {
el?.classList.remove('hidden');
2018-09-06 19:23:27 +02:00
}
2022-05-06 19:35:14 +02:00
export function hide(el: HTMLElement | null) {
el?.classList.add('hidden');
2018-09-06 19:23:27 +02:00
}
2022-05-06 19:35:14 +02:00
export function toggle(el: HTMLElement | null, force?: boolean) {
if (force == undefined) {
2022-05-06 19:35:14 +02:00
el?.classList.toggle('hidden');
} else if (force) {
2022-05-06 19:35:14 +02:00
el?.classList.remove('hidden');
} else {
2022-05-06 19:35:14 +02:00
el?.classList.add('hidden');
}
2018-09-06 19:23:27 +02:00
}
2018-10-09 11:32:27 +02:00
2022-05-06 19:35:14 +02:00
export function enable(el: HTMLInputElement | HTMLButtonElement | null) {
2019-11-19 17:55:30 +01:00
el && (el.disabled = false);
}
2022-05-06 19:35:14 +02:00
export function disable(el: HTMLInputElement | HTMLButtonElement | null) {
2019-11-19 17:55:30 +01:00
el && (el.disabled = true);
}
2022-05-06 19:35:14 +02:00
export function hasClass(el: HTMLElement | null, cssClass: string) {
return el?.classList.contains(cssClass);
2019-11-19 17:55:30 +01:00
}
2022-05-06 19:35:14 +02:00
export function addClass(el: HTMLElement | null, cssClass: string) {
el?.classList.add(cssClass);
2019-11-19 17:55:30 +01:00
}
2022-05-06 19:35:14 +02:00
export function removeClass(el: HTMLElement | null, cssClass: string) {
el?.classList.remove(cssClass);
2019-11-19 17:55:30 +01:00
}
export function delegate<E extends Event = Event>(
2022-02-02 17:16:50 +01:00
eventNames: string,
selector: string,
callback: (event: E) => void
2022-02-02 17:16:50 +01:00
) {
2018-10-09 11:32:27 +02:00
eventNames
.split(' ')
2020-04-30 15:42:29 +02:00
.forEach((eventName) =>
Rails.delegate(
document,
selector,
eventName,
callback as (event: Event) => void
)
2018-10-09 11:32:27 +02:00
);
}
2022-04-28 19:10:21 +02:00
export class ResponseError extends Error {
response: Response;
constructor(response: Response) {
super(String(response.statusText || response.status));
this.response = response;
}
}
2022-04-28 19:10:21 +02:00
const FETCH_TIMEOUT = 30 * 1000; // 30 sec
// Perform an HTTP request using `fetch` API,
// and handle the result depending on the MIME type.
//
// Usage:
//
// Execute a GET request, and return the response as parsed JSON
// const parsedJson = await httpRequest(url).json();
//
// Execute a POST request with some JSON payload
// const parsedJson = await httpRequest(url, { method: 'POST', json: '{ "foo": 1 }').json();
//
// Execute a GET request, and apply the Turbo stream in the Response
// await httpRequest(url).turbo();
//
export function httpRequest(
url: string,
{
csrf = true,
timeout = FETCH_TIMEOUT,
json,
controller,
...init
}: RequestInit & {
csrf?: boolean;
json?: unknown;
timeout?: number | false;
controller?: AbortController;
} = {}
) {
const headers = init.headers ? new Headers(init.headers) : new Headers();
2022-04-28 19:10:21 +02:00
if (csrf) {
headers.set('x-csrf-token', csrfToken() ?? '');
headers.set('x-requested-with', 'XMLHttpRequest');
init.credentials = 'same-origin';
}
init.headers = headers;
init.method = init.method?.toUpperCase() ?? 'GET';
if (json) {
headers.set('content-type', 'application/json');
init.body = JSON.stringify(json);
}
2020-10-08 11:19:16 +02:00
2022-04-28 19:10:21 +02:00
let timer: number;
if (!init.signal) {
controller = createAbortController(controller);
if (controller) {
init.signal = controller.signal;
if (timeout != false) {
timer = setTimeout(() => controller?.abort(), timeout);
}
}
}
const request = (init: RequestInit, accept?: string): Promise<Response> => {
if (accept && init.headers instanceof Headers) {
init.headers.set('accept', accept);
}
return fetch(url, init)
.then((response) => {
clearTimeout(timer);
if (response.ok) {
return response;
} else if (response.status == 401) {
location.reload(); // reload whole page so Devise will redirect to sign-in
}
throw new ResponseError(response);
})
.catch((error) => {
clearTimeout(timer);
throw error;
});
};
return {
async json<T>(): Promise<T | null> {
const response = await request(init, 'application/json');
if (response.status == 204) {
2020-10-08 11:19:16 +02:00
return null;
}
return response.json();
2022-04-28 19:10:21 +02:00
},
async turbo(): Promise<void> {
const response = await request(init, 'text/vnd.turbo-stream.html');
if (response.status != 204) {
const stream = await response.text();
session.renderStreamMessage(stream);
}
2020-10-08 11:19:16 +02:00
}
2022-04-28 19:10:21 +02:00
};
}
function createAbortController(controller?: AbortController) {
if (controller) {
return controller;
} else if (window.AbortController) {
return new AbortController();
}
return;
2018-10-09 11:32:27 +02:00
}
export function scrollTo(container: HTMLElement, scrollTo: HTMLElement) {
2018-10-09 11:43:38 +02:00
container.scrollTop =
offset(scrollTo).top - offset(container).top + container.scrollTop;
2018-10-09 11:32:27 +02:00
}
2022-02-02 17:16:50 +01:00
export function scrollToBottom(container: HTMLElement) {
2018-10-09 11:43:38 +02:00
container.scrollTop = container.scrollHeight;
2018-10-09 11:32:27 +02:00
}
2022-02-23 13:07:23 +01:00
export function isNumeric(s: string) {
const n = parseFloat(s);
return !isNaN(n) && isFinite(n);
2020-01-23 15:12:19 +01:00
}
2022-02-02 17:16:50 +01:00
function offset(element: HTMLElement) {
2018-10-09 11:43:38 +02:00
const rect = element.getBoundingClientRect();
return {
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
};
}