Skip to content

Commit

Permalink
[Console Monaco Migration] Add autosave to localStorage
Browse files Browse the repository at this point in the history
  • Loading branch information
ElenaStoeva committed Apr 11, 2024
1 parent 357b6f8 commit cdca683
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { CodeEditor } from '@kbn/code-editor';
import { css } from '@emotion/react';
import { CONSOLE_LANG_ID, CONSOLE_THEME_ID } from '@kbn/monaco';
import { useSetInitialValue } from './use_set_initial_value';
import { useSetupAutosave } from './use_setup_autosave';
import { useServicesContext, useEditorReadContext } from '../../../contexts';

export interface EditorProps {
Expand All @@ -33,6 +34,8 @@ export const MonacoEditor = ({ initialTextValue }: EditorProps) => {
setInitialValue({ initialTextValue, setValue, toasts });
}, [initialTextValue, setInitialValue, toasts]);

useSetupAutosave({ value });

return (
<div
css={css`
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { useEffect, useRef } from 'react';
import { useSaveCurrentTextObject } from '../../../hooks';

interface SetupAutosaveParams {
/** The current input value in the Console editor. */
value: string;
}

/**
* Hook that sets up autosaving the Console editor input to localStorage.
*
* @param params The {@link SetupAutosaveParams} to use.
*/
export const useSetupAutosave = (params: SetupAutosaveParams) => {
const { value } = params;
const saveCurrentTextObject = useSaveCurrentTextObject();
const timerRef = useRef<number | undefined>();

useEffect(() => {
function saveCurrentState() {
try {
saveCurrentTextObject(value);
} catch (e) {
// Ignoring saving error
}
}

const saveDelay = 500;

if (timerRef.current) {
clearTimeout(timerRef.current);
}
timerRef.current = window.setTimeout(saveCurrentState, saveDelay);

return () => {
if (timerRef.current) {
clearTimeout(timerRef.current);
}
};
}, [saveCurrentTextObject, value]);
};

0 comments on commit cdca683

Please sign in to comment.