-
Notifications
You must be signed in to change notification settings - Fork 8.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Console Monaco Migration] Add autosave to localStorage
- Loading branch information
1 parent
357b6f8
commit cdca683
Showing
2 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
49 changes: 49 additions & 0 deletions
49
src/plugins/console/public/application/containers/editor/monaco/use_setup_autosave.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); | ||
}; |