From f6436368229785836268a959164925549818b9f5 Mon Sep 17 00:00:00 2001 From: Marshall Polaris Date: Sun, 28 Aug 2022 20:40:01 -0700 Subject: [PATCH] Implement 'history state' idea --- web/hooks/use-persistent-state.ts | 34 ++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/web/hooks/use-persistent-state.ts b/web/hooks/use-persistent-state.ts index 81fc1b57..b34eb469 100644 --- a/web/hooks/use-persistent-state.ts +++ b/web/hooks/use-persistent-state.ts @@ -1,4 +1,4 @@ -import { useLayoutEffect, useEffect } from 'react' +import { useLayoutEffect, useEffect, useState } from 'react' import { useStateCheckEquality } from './use-state-check-equality' export type PersistenceOptions = { @@ -30,6 +30,38 @@ export const loadState = (key: string, store: Storage) => { } } +const STATE_KEY = '__manifold' + +const getHistoryState = (k: string) => { + if (typeof window !== 'undefined') { + return window.history.state?.options?.[STATE_KEY]?.[k] as T | undefined + } else { + return undefined + } +} + +const setHistoryState = (k: string, v: any) => { + if (typeof window !== 'undefined') { + const state = window.history.state ?? {} + const options = state.options ?? {} + const inner = options[STATE_KEY] ?? {} + window.history.replaceState( + { ...state, options: { ...options, [STATE_KEY]: { ...inner, [k]: v } } }, + '' + ) + } +} + +export const useHistoryState = (key: string, initialValue: T) => { + const [state, setState] = useState(getHistoryState(key) ?? initialValue) + const setter = (val: T) => { + console.log('Setting state: ', val) + setHistoryState(key, val) + setState(val) + } + return [state, setter] as const +} + export const usePersistentState = ( initial: T, persist?: PersistenceOptions