49 lines
1.4 KiB
TypeScript
49 lines
1.4 KiB
TypeScript
import { atom } from 'jotai';
|
|||
|
|
import { atomWithStorage, createJSONStorage } from 'jotai/utils';
|
||
|
|
|
||
|
|
export type RecentGif = {
|
||
|
|
url: string;
|
||
|
|
width: number;
|
||
|
|
height: number;
|
||
|
|
};
|
||
|
|
|
||
|
|
const STORAGE_KEY = 'cinny_recent_gifs_v1';
|
||
|
|
const MAX_RECENT_GIFS = 16;
|
||
|
|
|
||
|
|
// getOnInit reads localStorage synchronously so the Recent row is present on the
|
||
|
|
// first render of the GIF picker (no flash of the empty default).
|
||
|
|
const internalAtom = atomWithStorage<RecentGif[]>(
|
||
|
|
STORAGE_KEY,
|
||
|
|
[],
|
||
|
|
createJSONStorage(() => localStorage),
|
||
|
|
{ getOnInit: true },
|
||
|
|
);
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Global atom: the most recently sent GIFs, newest first, deduped by url, capped
|
||
|
|
* at MAX_RECENT_GIFS. Backed by localStorage (device-local convenience).
|
||
|
|
*/
|
||
|
|
export const recentGifsAtom = atom(
|
||
|
|
(get): RecentGif[] => get(internalAtom),
|
||
|
|
(_get, set, updater: RecentGif[] | ((prev: RecentGif[]) => RecentGif[])) => {
|
||
|
|
set(internalAtom, (prev) => {
|
||
|
|
const prevList = Array.isArray(prev) ? prev : [];
|
||
|
|
return typeof updater === 'function' ? updater(prevList) : updater;
|
||
|
|
});
|
||
|
|
},
|
||
|
|
);
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Prepend a GIF: ignores an empty url, de-dupes by url (moving an existing entry
|
||
|
|
* to the front), and caps the list at `max`. Pure — returns a new array.
|
||
|
|
*/
|
||
|
|
export const addRecentGif = (
|
||
|
|
prev: RecentGif[],
|
||
|
|
gif: RecentGif,
|
||
|
|
max = MAX_RECENT_GIFS,
|
||
|
|
): RecentGif[] => {
|
||
|
|
if (!gif.url) return prev;
|
||
|
|
const withoutDupe = prev.filter((g) => g.url !== gif.url);
|
||
|
|
return [gif, ...withoutDupe].slice(0, max);
|
||
|
|
};
|