From 2b1e0c87ff56496f023262477676fafbb8c0f59c Mon Sep 17 00:00:00 2001 From: rlazarini <remi.lazarini@cea.fr> Date: Wed, 2 Oct 2024 14:45:38 +0200 Subject: [PATCH] [Ivette] add function in systme.ts to get a filecontent + hook useFileContent --- ivette/src/dome/misc/system.ts | 24 ++++++++++++++++++++++++ ivette/src/dome/renderer/dome.tsx | 13 +++++++++++++ 2 files changed, 37 insertions(+) diff --git a/ivette/src/dome/misc/system.ts b/ivette/src/dome/misc/system.ts index 82e0aefc1c0..ca044d74023 100644 --- a/ivette/src/dome/misc/system.ts +++ b/ivette/src/dome/misc/system.ts @@ -658,3 +658,27 @@ export default { }; // -------------------------------------------------------------------------- +// --- Get filecontent +// -------------------------------------------------------------------------- + +export function getFileContent( + path: string, + callback: (val: string) => void +): void { + fetch(path) + .then((response) => { + if (!response.ok) { + // Statut HTTP 404 ou autre erreur + throw new Error(`HTTP error! status: ${response.status}`); + } + return response.text(); + }) + .then(callback) + .catch((error) => { + // eslint-disable-next-line no-console + console.error('Error while loading the file :', error); + } + ); +} + +// -------------------------------------------------------------------------- diff --git a/ivette/src/dome/renderer/dome.tsx b/ivette/src/dome/renderer/dome.tsx index 19b04a7f0c4..1e03e03aba5 100644 --- a/ivette/src/dome/renderer/dome.tsx +++ b/ivette/src/dome/renderer/dome.tsx @@ -821,6 +821,19 @@ export function useProtected<A>(fn: Callback<A> | undefined): Callback<A> { return trigger; } +/** + * A hook to retrieve text from a file. + * The update is protected by the useProtected() hook. + */ +export function useFileContent( + path: string, +): string { + const [ fileContent, setFileContent ] = React.useState(""); + const callback = useProtected(setFileContent); + System.getFileContent(path, callback); + return fileContent; +} + /** Debounced callback (waiting time in milliseconds). The returned callback will be only fired when the component is mounted. -- GitLab