-
Notifications
You must be signed in to change notification settings - Fork 106
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
refactor(libraries): type safe local storage json #6455
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
70d40b1
refactor(libraries): type safe local storage json
jasonkuhrt 345baa2
doc
jasonkuhrt e93ac88
fix
jasonkuhrt f07a764
tweak
jasonkuhrt a3493be
take ai feedback
jasonkuhrt def8e81
Merge branch 'main' into console-995
jasonkuhrt 0017cf1
lint
jasonkuhrt adc1bb3
Merge branch 'main' into console-995
jasonkuhrt 9b2805a
pnpm stuff
jasonkuhrt ecb1af7
changeset
jasonkuhrt 7f3a7a1
work around storybook limitation
jasonkuhrt 61f259d
improve grammar
jasonkuhrt c090d66
eslint
jasonkuhrt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
'hive': patch | ||
--- | ||
|
||
A minor defect in Laboratory has been fixed that previously caused the application to crash when local storage was in a particular state. |
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
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
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
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 |
---|---|---|
@@ -1,23 +1,75 @@ | ||
import { useCallback, useState } from 'react'; | ||
import { z } from 'zod'; | ||
import { Kit } from '../kit'; | ||
|
||
export function useLocalStorageJson<T>(key: string, defaultValue: T) { | ||
const [value, setValue] = useState<T>(() => { | ||
const json = localStorage.getItem(key); | ||
export function useLocalStorageJson<$Schema extends z.ZodType>(...args: ArgsInput<$Schema>) { | ||
const [key, schema, manualDefaultValue] = args as any as Args<$Schema>; | ||
// The parameter types will force the user to give a manual default | ||
// if their given Zod schema does not have default. | ||
// | ||
// We resolve that here because in the event of a Zod parse failure, we fallback | ||
// to the default value, meaning we are needing a reference to the Zod default outside | ||
// of the regular parse process. | ||
// | ||
const defaultValue = | ||
manualDefaultValue !== undefined | ||
? manualDefaultValue | ||
: Kit.ZodHelpers.isDefaultType(schema) | ||
? (schema._def.defaultValue() as z.infer<$Schema>) | ||
: Kit.never(); | ||
|
||
const [value, setValue] = useState<z.infer<$Schema>>(() => { | ||
// Note: `null` is returned for missing values. However Zod only kicks in | ||
// default values for `undefined`, not `null`. However-however, this is ok, | ||
// because we manually pre-compute+return the default value, thus we don't | ||
// rely on Zod's behaviour. If that changes this should have `?? undefined` | ||
// added. | ||
const storedValue = localStorage.getItem(key); | ||
|
||
if (!storedValue) { | ||
return defaultValue; | ||
} | ||
|
||
// todo: Some possible improvements: | ||
// - Monitor json/schema parse failures. | ||
// - Let caller choose an error strategy: 'return' / 'default' / 'throw' | ||
try { | ||
const result = json ? JSON.parse(json) : defaultValue; | ||
return result; | ||
} catch (_) { | ||
return schema.parse(JSON.parse(storedValue)); | ||
} catch (error) { | ||
if (error instanceof SyntaxError) { | ||
console.warn(`useLocalStorageJson: JSON parsing failed for key "${key}"`, error); | ||
} else if (error instanceof z.ZodError) { | ||
console.warn(`useLocalStorageJson: Schema validation failed for key "${key}"`, error); | ||
} else { | ||
Kit.neverCatch(error); | ||
} | ||
return defaultValue; | ||
} | ||
}); | ||
|
||
const set = useCallback( | ||
(value: T) => { | ||
(value: z.infer<$Schema>) => { | ||
localStorage.setItem(key, JSON.stringify(value)); | ||
setValue(value); | ||
}, | ||
[setValue], | ||
[key], | ||
); | ||
|
||
return [value, set] as const; | ||
} | ||
|
||
type ArgsInput<$Schema extends z.ZodType> = | ||
$Schema extends z.ZodDefault<z.ZodType> | ||
? [key: string, schema: ArgsInputGuardZodJsonSchema<$Schema>] | ||
: [key: string, schema: ArgsInputGuardZodJsonSchema<$Schema>, defaultValue: z.infer<$Schema>]; | ||
|
||
type ArgsInputGuardZodJsonSchema<$Schema extends z.ZodType> = | ||
z.infer<$Schema> extends Kit.Json.Value | ||
? $Schema | ||
: 'Error: Your Zod schema is or contains a type that is not valid JSON.'; | ||
|
||
type Args<$Schema extends z.ZodType> = [ | ||
key: string, | ||
schema: $Schema, | ||
defaultValue?: z.infer<$Schema>, | ||
]; |
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 |
---|---|---|
@@ -1,6 +1,14 @@ | ||
// eslint-disable-next-line import/no-self-import | ||
export * as Kit from './index'; | ||
// Storybook (or the version we are using) | ||
// is using a version of Babel that does not | ||
// support re-exporting as namespaces: | ||
// | ||
// export * as Kit from './index'; | ||
// | ||
// So we have to re-export everything manually | ||
// and incur an additional index_ file for it | ||
// too: | ||
|
||
export * from './never'; | ||
export * from './types/headers'; | ||
export * from './helpers'; | ||
import * as Kit from './index_'; | ||
|
||
// eslint-disable-next-line unicorn/prefer-export-from | ||
export { Kit }; |
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,5 @@ | ||
export * from './never'; | ||
export * from './types/headers'; | ||
export * from './helpers'; | ||
export * from './json'; | ||
export * from './zod-helpers'; |
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,19 @@ | ||
import { z } from 'zod'; | ||
import { ZodHelpers } from './zod-helpers'; | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-namespace | ||
export namespace Json { | ||
export const Primitive = z.union([z.string(), z.number(), z.boolean(), z.null()]); | ||
export type Primitive = z.infer<typeof Primitive>; | ||
export const isPrimitive = ZodHelpers.createTypeGuard(Primitive); | ||
|
||
export const Value: z.ZodType<Value> = z.lazy(() => | ||
z.union([Primitive, z.array(Value), z.record(Value)]), | ||
); | ||
export type Value = Primitive | { [key: string]: Value } | Value[]; | ||
export const isValue = ZodHelpers.createTypeGuard(Value); | ||
|
||
export const Object: z.ZodType<Object> = z.record(Value); | ||
export type Object = { [key: string]: Value }; | ||
export const isObject = ZodHelpers.createTypeGuard(Object); | ||
jasonkuhrt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} |
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
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,15 @@ | ||
import { z } from 'zod'; | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-namespace | ||
export namespace ZodHelpers { | ||
export const isDefaultType = (zodType: z.ZodType): zodType is z.ZodDefault<z.ZodType> => { | ||
return 'defaultValue' in zodType._def; | ||
}; | ||
|
||
export const createTypeGuard = | ||
<$Schema extends z.ZodType, $Value = z.infer<$Schema>>(schema: $Schema) => | ||
(value: unknown): value is $Value => { | ||
const result = schema.safeParse(value); | ||
return result.success; | ||
}; | ||
} |
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
This file was deleted.
Oops, something went wrong.
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
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
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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Remove unsafe type casting.
The use of
as any
bypasses TypeScript's type checking. Consider using type predicates or type guards instead.