Skip to content
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

♻️ [Code] Various revisions #1

Merged
merged 2 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
772 changes: 412 additions & 360 deletions package-lock.json

Large diffs are not rendered by default.

16 changes: 8 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,20 @@
"react-transition-state": "^2.2.0"
},
"devDependencies": {
"@eslint/js": "^9.15.0",
"@types/node": "^22.10.0",
"@eslint/js": "^9.16.0",
"@types/node": "^22.10.1",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react-swc": "^3.7.2",
"eslint": "^9.15.0",
"eslint": "^9.16.0",
"eslint-plugin-react": "^7.37.2",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.14",
"globals": "^15.12.0",
"eslint-plugin-react-refresh": "^0.4.16",
"globals": "^15.13.0",
"lightningcss": "^1.28.2",
"typescript": "^5.6.3",
"typescript-eslint": "^8.15.0",
"vite": "^5.4.11",
"typescript": "^5.7.2",
"typescript-eslint": "^8.17.0",
"vite": "^6.0.2",
"vite-plugin-svgr": "^4.3.0"
}
}
62 changes: 62 additions & 0 deletions packages/classes/TypedStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
export class TypedStorage<T extends Record<string, unknown>> {
private registeredKeys = new Set<string>();

setItem<K extends keyof T>(key: K, value: T[K]) {
try {
const serializedValue = JSON.stringify(value);
localStorage.setItem(String(key), serializedValue);
this.registeredKeys.add(String(key));
} catch (error) {
console.error(`Failed to set item with key "${String(key)}":`, error);
}
}

getItem<K extends keyof T>(key: K) {
try {
const item = localStorage.getItem(String(key));
// It is possible we could consider some custom validator to be set
// when calling `setItem/getItem` that allows for stronger typing.
return item ? (JSON.parse(item) as T[K]) : null;
} catch (error) {
console.error(`Failed to get item with key "${String(key)}":`, error);
return null;
}
}

removeItem<K extends keyof T>(key: K) {
try {
localStorage.removeItem(String(key));
this.registeredKeys.delete(String(key));
} catch (error) {
console.error(`Failed to remove item with key "${String(key)}":`, error);
}
}

clear() {
try {
this.registeredKeys.forEach((key) => {
localStorage.removeItem(key);
});
this.registeredKeys.clear();
} catch (error) {
console.error(
'Failed to clear registered items from localStorage:',
error,
);
}
}
}

/*
// Usage example:

interface MyLocalStorageEntries {
userSettings: { theme: string; language: string };
sessionId: string;
}

const myLocalStorage = new TypedStorage<MyLocalStorageEntries>();

myLocalStorage.setItem('userSettings', { theme: 'dark', language: 'en' });
myLocalStorage.setItem('sessionId', 'abc123');
*/
1 change: 1 addition & 0 deletions packages/classes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {TypedStorage} from './TypedStorage.ts';
2 changes: 2 additions & 0 deletions packages/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ export {
type KeyPressOptions,
} from './useKeyPress.ts';

export {useLocalStorage} from './useLocalStorage.ts';

export {useMediaQuery, type MediaQueryOptions} from './useMediaQuery.ts';
export {useMounted} from './useMounted.ts';

Expand Down
99 changes: 99 additions & 0 deletions packages/hooks/useLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import {useCallback, useEffect, useSyncExternalStore} from 'react';
import type {AnyObj, Fn} from 'beeftools';

// Adapted from:
// https://usehooks.com/uselocalstorage

type AcceptedTypes = string | number | boolean | AnyObj;
type AcceptedFn = (arg: AnyObj) => AcceptedTypes;

type LocalStorageValue = AcceptedTypes | AcceptedTypes[] | AcceptedFn;
type ServerSnapshotFn = Parameters<typeof useSyncExternalStore>[2];

type LocalStorageReturn = [
state: LocalStorageValue,
setter: (value: LocalStorageValue) => void,
];

function dispatchStorageEvent(key: string, newValue?: string | null) {
window.dispatchEvent(new StorageEvent('storage', {key, newValue}));
}

function parseStore(store: unknown) {
return JSON.parse(store as string) as AnyObj;
}

function setLocalStorageItem(key: string, value: LocalStorageValue) {
const stringifiedValue = JSON.stringify(value);

window.localStorage.setItem(key, stringifiedValue);
dispatchStorageEvent(key, stringifiedValue);
}

function removeLocalStorageItem(key: string) {
window.localStorage.removeItem(key);
dispatchStorageEvent(key, null);
}

function getLocalStorageItem(key: string) {
return window.localStorage.getItem(key);
}

const getLocalStorageServerSnapshot: ServerSnapshotFn = () => {
throw Error('useLocalStorage is a client-only hook');
};

function useLocalStorageSubscribe(callback: Fn) {
window.addEventListener('storage', callback);

return () => {
window.removeEventListener('storage', callback);
};
}

// TODO: Fix this to accept a `generic` / infer the correct type from `initialValue`.
// For now, I prefer using the `TypedStorage` class.
export function useLocalStorage(key: string, initialValue: LocalStorageValue) {
const getSnapshot = () => getLocalStorageItem(key);

const store = useSyncExternalStore(
useLocalStorageSubscribe,
getSnapshot,
getLocalStorageServerSnapshot,
);

// Handles both `set` and `remove`. By passing `undefined` or `null`,
// `removeLocalStorageItem` is called on the provided `key`.
const setState = useCallback(
(value: LocalStorageValue) => {
try {
const isFn = typeof value === 'function';
const parsed = isFn ? parseStore(store) : undefined;
const nextState = parsed ?? value;

if (nextState === undefined || nextState === null) {
removeLocalStorageItem(key);
} else {
setLocalStorageItem(key, nextState);
}
} catch (error) {
console.warn(error);
}
},
[key, store],
);

useEffect(() => {
if (
getLocalStorageItem(key) === null &&
typeof initialValue !== 'undefined'
) {
setLocalStorageItem(key, initialValue);
}
}, [key, initialValue]);

const finalValue = store ? parseStore(store) : initialValue;
const finalTuple: LocalStorageReturn = [finalValue, setState];

return finalTuple;
}
6 changes: 2 additions & 4 deletions packages/hooks/useMediaQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,11 @@ export function useMediaQuery(query = '', options?: MediaQueryOptions) {
const initializeWithValue = options?.initializeWithValue ?? true;

function getMatches(query = '') {
if (IS_CLIENT) return window.matchMedia(query).matches;
return defaultValue;
return IS_CLIENT ? window.matchMedia(query).matches : defaultValue;
}

const [matches, setMatches] = useState(() => {
if (initializeWithValue) return getMatches(query);
return defaultValue;
return initializeWithValue ? getMatches(query) : defaultValue;
});

// Handles the change event of the media query.
Expand Down
20 changes: 20 additions & 0 deletions src/App.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,23 @@
grid-template-rows: auto 1fr auto;
min-height: 100%;
}

.Layout {
display: grid;
gap: 20px;
margin: 0 auto;
max-width: 960px;
}

.Card {
margin: 0 auto;
padding: 10px;
border-radius: var(--radius);
color: var(--color-text);
background-color: var(--shade-light-20);
}

.invert {
color: var(--color-bg);
background-color: var(--color-text);
}
32 changes: 30 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,43 @@
import {clx} from 'beeftools';

import {BreakpointProvider} from '@src/providers/BreakpointProvider.tsx';
import {ThemeProvider} from '@src/providers/ThemeProvider.tsx';

import {Footer} from '@src/components/sections/Footer/Footer.tsx';
import {Header} from '@src/components/sections/Header/Header.tsx';
import {Main} from '@src/components/sections/Main/Main.tsx';

import {AccordionTest} from '@src/components/ui/Accordion/Accordion.test.tsx';
import {ButtonTest} from '@src/components/ui/Button/Button.test.tsx';

import styles from './App.module.css';

function AppContent() {
// Separated from `<App />` to allow use of hooks available via "app providers".
return (
<div className={styles.App}>
<Header />
<Main />

<Main>
<div className={styles.Layout}>
<div
className={clx(styles.Card, {
[styles.invert]: false,
})}
>
<AccordionTest />
</div>

<div
className={clx(styles.Card, {
[styles.invert]: false,
})}
>
<ButtonTest />
</div>
</div>
</Main>

<Footer />
</div>
);
Expand All @@ -20,7 +46,9 @@ function AppContent() {
export function App() {
return (
<ThemeProvider>
<AppContent />
<BreakpointProvider>
<AppContent />
</BreakpointProvider>
</ThemeProvider>
);
}
2 changes: 1 addition & 1 deletion src/components/primitives/Overlay/Overlay.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
display: grid;
align-items: center;
justify-items: center;
background-color: var(--shade-black-80);
background-color: var(--shade-dark-80);

/* Relies on `react-transition-state` hook. */
opacity: 1;
Expand Down
4 changes: 2 additions & 2 deletions src/components/primitives/Spinner/Spinner.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
.Icon {
width: 1em;
height: 1em;
border: 0.125em solid var(--shade-white-20);
border-top: 0.125em solid var(--shade-white-80);
border: 0.125em solid color-mix(in srgb, currentColor, transparent 60%);
border-top: 0.125em solid currentColor;
border-radius: 50%;
animation: var(--motion-spin) var(--speed-slow) var(--ease) infinite both;
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@
/* `aspect-ratio` should be dynamic. */
aspect-ratio: 16 / 9;
width: 100%;
background-color: var(--shade-black-80);
background-color: var(--shade-dark-80);
}
}
44 changes: 8 additions & 36 deletions src/components/sections/Footer/Footer.module.css
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
@import '@src/styles/media-queries.css';

.Footer {
--footer-action-padding: 6px;
--footer-underline-width: 0%;

display: grid;
align-content: start;
gap: 20px;
padding: 20px;
width: 100%;
text-align: center;
Expand All @@ -18,42 +18,14 @@
gap: 64px;
margin: 0 auto;
max-width: var(--breakpoint-x-desktop);

@media (--min-tablet) {
grid-template-columns: repeat(3, 1fr);
align-items: center;
}
}

.LegalText {
font-size: 13px;
letter-spacing: 0.06em;
}

/* --- Social Links --- */

.SocialLinks {
display: grid;
grid-auto-flow: column;
justify-content: center;
justify-items: center;
gap: 16px;
}

.SocialLinkItem {
}

.SocialLinkAction {
display: block;
padding: var(--footer-action-padding);
border-radius: var(--radius);
background-color: transparent;
/* `focus-ring` + `transition` is inherited by `button-basic` */

&:hover {
color: var(--color-primary);
background-color: var(--shade-black-4);
}

&:active {
opacity: 0.8;
}
}

.SocialIconWrapper {
}
Loading
Loading