Skip to content

Commit

Permalink
Allow local storage settings to be overridden (#1129)
Browse files Browse the repository at this point in the history
Required for classroom language switching via query param.
  • Loading branch information
microbit-robert authored Sep 19, 2023
1 parent ba691aa commit 7269d44
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
4 changes: 3 additions & 1 deletion src/common/use-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ export function useStorage<T>(
storageType: storageType,
key: string,
defaultValue: T,
validate?: (x: unknown) => x is T
validate?: (x: unknown) => x is T,
overrides?: Partial<T>
): [T, (value: T) => void] {
const [state, setState] = useState<T>(() => {
const storage =
Expand All @@ -29,6 +30,7 @@ export function useStorage<T>(
parsed = {
...defaultValue,
...parsed,
...overrides,
};
// Remove any top-level keys that aren't present in defaults.
const unknownKeys = new Set(Object.keys(parsed));
Expand Down
8 changes: 5 additions & 3 deletions src/settings/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { createContext, ReactNode, useContext } from "react";
import { useStorage } from "../common/use-storage";
import { defaultCodeFontSizePt } from "../deployment/misc";
import { stage } from "../environment";
import { flags } from "../flags";

export interface Language {
id: string;
Expand Down Expand Up @@ -168,14 +169,15 @@ export const useSettings = (): SettingsContextValue => {
};

const SettingsProvider = ({ children }: { children: ReactNode }) => {
const settings = useStorage<Settings>(
const [settings, setSettings] = useStorage<Settings>(
"local",
"settings",
defaultSettings,
isValidSettingsObject
isValidSettingsObject,
flags.noLang ? { languageId: getLanguageFromQuery() } : {}
);
return (
<SettingsContext.Provider value={settings}>
<SettingsContext.Provider value={[settings, setSettings]}>
{children}
</SettingsContext.Provider>
);
Expand Down

0 comments on commit 7269d44

Please sign in to comment.