29 lines · 912 B
import { useSyncExternalStore } from "react";

/**
 * Avatar keys learned in this tab (after an upload), by lowercased account name. By-name avatar URLs go through
 * a redirect that edges and browsers cache for a few minutes; once the new key is known, every Avatar for that
 * name points straight at the immutable keyed URL instead.
 */
const keys = new Map<string, string>();
const listeners = new Set<() => void>();

export function setKnownAvatarKey(name: string, key: string): void {
  keys.set(name.toLowerCase(), key);
  for (const listener of listeners) listener();
}

function subscribe(listener: () => void): () => void {
  listeners.add(listener);
  return () => listeners.delete(listener);
}

export function useKnownAvatarKey(name: string): string | null {
  const lower = name.toLowerCase();
  return useSyncExternalStore(
    subscribe,
    () => keys.get(lower) ?? null,
    () => null,
  );
}