ChemPal Documentation - v1.18.0
    Preparing search index...

    Function useBadgeController

    • Mount-once hook that subscribes to all search-lifecycle events, IDB_SEARCH_RESULTS_CLEARED and the price alerts, runs them through reduceBadge, and applies the result to the badge. Call this exactly once, near the top of App, before any code that emits search events.

      Returns void

      function App() {
      useBadgeController();
      // …
      }
      export function useBadgeController(): void {
      useEffect(() => {
      // Badge state is external; keep it in the closure, not React state.
      let state = initialBadgeState;
      // Skip re-emitting an identical output (e.g. repeated mid-search 0 → animate).
      let lastOutput: BadgeOutput | null = null;
      const isOwner = () => state.isSearching || document.visibilityState === 'visible';
      const releaseBadge = claimBadge(isOwner);
      // Newest drop already shown; undefined until the alerts have loaded.
      let latestDrop: number | undefined;
      const alerts = watchPriceAlerts((loaded) => {
      const unseen = getUnseenDrops(loaded);
      const newest = Math.max(0, ...unseen.map(({ lastDrop }) => lastDrop?.at ?? 0));
      const isNew = latestDrop !== undefined && newest > latestDrop;
      latestDrop = Math.max(latestDrop ?? 0, newest);
      // Nothing to show yet, and the badge may hold the results of an earlier session.
      if (unseen.length === 0 && state.drops === 0) return;
      handle({ type: PRICE_DROPS_CHANGED, drops: unseen.length, isNew });
      // The worker is changing the badge, so what was applied last no longer holds.
      if (!isOwner()) lastOutput = null;
      });
      // Serialize applies so their async getBadgeText reads don't interleave. Starts once the price
      // drops are known, so they don't replace a result count that was only just shown.
      let applyChain = alerts.ready;

      const handle = (event: BadgeEvent) => {
      const result = reduceBadge(state, event);
      state = result.state;
      if (event.type === PRICE_DROPS_CHANGED && !isOwner()) return;
      if (isSameBadgeOutput(lastOutput, result.output)) return;
      lastOutput = result.output;
      const output = result.output;
      const previous = applyChain;
      applyChain = (async () => {
      await previous;
      // A newer output may have replaced it while it waited.
      if (output === lastOutput) await applyBadgeOutput(output);
      })();
      };

      const unsubscribers = [
      onSearchEvent(SearchEvent.STARTED, () => handle({ type: SearchEvent.STARTED })),
      onSearchEvent(SearchEvent.RESULTS_COUNT, ({ count }) =>
      handle({ type: SearchEvent.RESULTS_COUNT, count }),
      ),
      onSearchEvent(SearchEvent.COMPLETED, ({ count }) =>
      handle({ type: SearchEvent.COMPLETED, count }),
      ),
      onSearchEvent(SearchEvent.ABORTED, () => handle({ type: SearchEvent.ABORTED })),
      onSearchEvent(SearchEvent.FAILED, () => handle({ type: SearchEvent.FAILED })),
      ];

      const onResultsCleared = () => handle({ type: IDB_SEARCH_RESULTS_CLEARED });
      window.addEventListener(IDB_SEARCH_RESULTS_CLEARED, onResultsCleared);

      // Catches up on drops that were left to the worker.
      const onVisible = () => {
      if (isOwner()) handle({ type: PRICE_DROPS_CHANGED, drops: state.drops, isNew: false });
      };
      document.addEventListener('visibilitychange', onVisible);

      return () => {
      document.removeEventListener('visibilitychange', onVisible);
      alerts.stop();
      releaseBadge();
      for (const unsubscribe of unsubscribers) unsubscribe();
      window.removeEventListener(IDB_SEARCH_RESULTS_CLEARED, onResultsCleared);
      };
      }, []);
      }