Skip to content

Commit

Permalink
Add useStorage and useCache hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
Exidex committed Sep 10, 2024
1 parent 0eb1ba4 commit 2154131
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 3 deletions.
3 changes: 2 additions & 1 deletion dev_data/state/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
logs
logs
local_storage
6 changes: 6 additions & 0 deletions dev_plugin/src/command-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ export default function CommandGenerator(): GeneratedCommand[] {
name: 'Generated Item 2',
fn: () => {
console.log('generated-test-2')

sessionStorage.setItem("test", "test")
console.dir(sessionStorage.getItem("test"))

localStorage.setItem("test", "test")
console.dir(localStorage.getItem("test"))
}
},
{
Expand Down
8 changes: 7 additions & 1 deletion dev_plugin/src/grid-view.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import { Grid } from "@project-gauntlet/api/components";
import { ReactElement } from "react";
import { useStorage } from "@project-gauntlet/api/hooks";

export default function GridView(): ReactElement {
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19];

const [val1, setValue1] = useStorage("test", undefined);
const [val2, setValue2] = useStorage("test", { " test": "test" });
const [val3, setValue3] = useStorage("test", "");
const [val4, setValue4] = useStorage<string>("test", "");

return (
<Grid>
<Grid onSelectionChange={id => {}}>
{
numbers.map(value => (
<Grid.Item id={"id" + value} title={"Title " + value}>
Expand Down
44 changes: 43 additions & 1 deletion js/api/src/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ReactNode, useRef, useState, useCallback, useEffect, MutableRefObject } from 'react';
import { ReactNode, useRef, useState, useCallback, useEffect, MutableRefObject, Dispatch, SetStateAction } from 'react';
// @ts-ignore TODO how to add declaration for this?
import { useGauntletContext } from "gauntlet:renderer";

Expand Down Expand Up @@ -203,3 +203,45 @@ export function usePromise<T extends (...args: any[]) => Promise<any>, R>(
...state
};
}

// persistent, uses localStorage under the hood
export function useStorage<T>(key: string, initialState: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
return useWebStorage(key, initialState, localStorage)
}

// ephemeral, uses sessionStorage under the hood
export function useCache<T>(key: string, initialState: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
return useWebStorage(key, initialState, sessionStorage)
}

// keys are shared per plugin, across all entrypoints
// uses JSON.serialize
function useWebStorage<T>(
key: string,
initialState: T | (() => T),
storageObject: Storage
): [T, Dispatch<SetStateAction<T>>] {

const [value, setValue] = useState<T>(() => {
const jsonValue = storageObject.getItem(key)

if (jsonValue != null) {
return JSON.parse(jsonValue) as T
}

if (initialState instanceof Function) {
return initialState()
} else {
return initialState
}
})

useEffect(() => {
if (value === undefined) {
return storageObject.removeItem(key)
}
storageObject.setItem(key, JSON.stringify(value))
}, [key, value, storageObject])

return [value, setValue]
}
4 changes: 4 additions & 0 deletions rust/common/src/dirs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ impl Dirs {
(out_log_file, err_log_file)
}

pub fn plugin_local_storage(&self, plugin_uuid: &str) -> PathBuf {
self.state_dir().join("local_storage").join(&plugin_uuid)
}

pub fn state_dir(&self) -> PathBuf {
let state_dir = if cfg!(feature = "release") || cfg!(feature = "scenario_runner") {
let dir = match self.inner.state_dir() {
Expand Down
3 changes: 3 additions & 0 deletions rust/server/src/plugins/js/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,8 @@ async fn start_js_runtime(
(StdioPipe::Inherit, StdioPipe::Inherit)
};

let local_storage_dir = dirs.plugin_local_storage(&plugin_uuid);

// let _inspector_server = Arc::new(
// InspectorServer::new(
// "127.0.0.1:9229".parse::<SocketAddr>().unwrap(),
Expand Down Expand Up @@ -352,6 +354,7 @@ async fn start_js_runtime(
maybe_inspector_server: None,
should_wait_for_inspector_session: false,
should_break_on_first_statement: false,
origin_storage_dir: Some(local_storage_dir),
stdio: Stdio {
stdin: StdioPipe::Inherit,
stdout,
Expand Down

0 comments on commit 2154131

Please sign in to comment.