74 lines
2.0 KiB
TypeScript
74 lines
2.0 KiB
TypeScript
/**
|
|
* Browser wishlist: product `handle[]` in localStorage.
|
|
* Optional server sync: [`app/routes/api.wishlist-sync.tsx`](api.wishlist-sync.tsx) + CAA `metafieldsSet`.
|
|
*/
|
|
|
|
export const WISHLIST_STORAGE_KEY = 'abiir-wishlist-handles';
|
|
|
|
export const ABIIR_WISHLIST_CHANGE_EVENT = 'abiir-wishlist-changed';
|
|
|
|
const HANDLE_RE = /^[a-z0-9][a-z0-9-]*$/i;
|
|
|
|
export const WISHLIST_MAX_HANDLES = 50;
|
|
|
|
export function isValidProductHandle(s: string): boolean {
|
|
return s.length > 0 && s.length <= 200 && HANDLE_RE.test(s);
|
|
}
|
|
|
|
function normalizeHandlesList(handles: string[]): string[] {
|
|
const out: string[] = [];
|
|
for (const h of handles) {
|
|
const t = h.trim();
|
|
if (
|
|
t &&
|
|
isValidProductHandle(t) &&
|
|
!out.includes(t) &&
|
|
out.length < WISHLIST_MAX_HANDLES
|
|
) {
|
|
out.push(t);
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function parseArray(raw: unknown): string[] {
|
|
if (!Array.isArray(raw)) return [];
|
|
return normalizeHandlesList(
|
|
raw.filter((x): x is string => typeof x === 'string'),
|
|
);
|
|
}
|
|
|
|
function readFromStorageString(raw: string | null): string[] {
|
|
if (!raw) return [];
|
|
try {
|
|
return parseArray(JSON.parse(raw));
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
export function readWishlistHandlesFromWindow(): string[] {
|
|
if (typeof window === 'undefined') return [];
|
|
return readFromStorageString(window.localStorage.getItem(WISHLIST_STORAGE_KEY));
|
|
}
|
|
|
|
export function readWishlistHandlesString(raw: string | null): string[] {
|
|
return readFromStorageString(raw);
|
|
}
|
|
|
|
export function writeWishlistHandles(handles: string[]) {
|
|
if (typeof window === 'undefined') return;
|
|
const next = normalizeHandlesList(handles);
|
|
try {
|
|
window.localStorage.setItem(WISHLIST_STORAGE_KEY, JSON.stringify(next));
|
|
window.dispatchEvent(new CustomEvent(ABIIR_WISHLIST_CHANGE_EVENT));
|
|
} catch {
|
|
/* quota */
|
|
}
|
|
}
|
|
|
|
/** For API routes: validate JSON body array of handle strings. */
|
|
export function parseWishlistHandlesFromBody(raw: unknown): string[] {
|
|
return parseArray(raw);
|
|
}
|