app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

search-view.ts (5396B)


      1 import {
      2   subscribePublicViewVisibility,
      3   type PublicView
      4 } from '../runtime/public-runtime.ts';
      5 import type { PublicHead } from './heads.ts';
      6 import type { WallClock } from './clock-policy.ts';
      7 import type { SearchSnapshot } from './search-state.ts';
      8 import {
      9   createFoodSearchCoordinator,
     10   beginFoodSearch,
     11   sampleFoodSearch,
     12   chronologicalFoodSearch,
     13   foodSearchSnapshot,
     14   resolveFoodSearchPublishers,
     15   showMoreFoodSearch,
     16   searchOlderFoodSearch,
     17   closeFoodSearchCoordinator,
     18   type FoodSearchRun
     19 } from './search-run.ts';
     20 export type SearchViewSnapshot = SearchSnapshot<FoodSearchRun>;
     21 export type ForegroundSchedule = (
     22   callback: () => void,
     23   delay: number
     24 ) => () => void;
     25 declare const viewBrand: unique symbol;
     26 export type SearchView = Readonly<{ readonly [viewBrand]: true }>;
     27 interface Owner {
     28   readonly start: (query: unknown, known: readonly PublicHead[]) => void;
     29   readonly more: () => void;
     30   readonly older: () => void;
     31   readonly snapshot: () => SearchViewSnapshot | undefined;
     32   readonly close: () => void;
     33 }
     34 const owners = new WeakMap<SearchView, Owner>();
     35 function ownerOf(view: SearchView): Owner {
     36   const owner = owners.get(view);
     37   if (!owner) throw Error('search_view_invalid');
     38   return owner;
     39 }
     40 function foreground(callback: () => void, delay: number): () => void {
     41   const timer = setTimeout(() => {
     42     callback();
     43   }, delay);
     44   return () => {
     45     clearTimeout(timer);
     46   };
     47 }
     48 // This owner observes a finite public run; it never creates a background poll,
     49 // transport, shared cache or new deadline. Explicit actions alone restart runs.
     50 export function createSearchView(
     51   view: PublicView,
     52   clock: WallClock,
     53   onUpdate: (value: SearchViewSnapshot) => void,
     54   schedule: ForegroundSchedule = foreground
     55 ): SearchView {
     56   const coordinator = createFoodSearchCoordinator(view, clock);
     57   let generation: FoodSearchRun | undefined,
     58     cancel: (() => void) | undefined,
     59     closed = false;
     60   function stop() {
     61     const previous = cancel;
     62     cancel = undefined;
     63     previous?.();
     64   }
     65   function current(token: FoodSearchRun) {
     66     return !closed && generation === token;
     67   }
     68   function requireOpen() {
     69     if (closed) throw Error('search_view_closed');
     70   }
     71   function publish(token: FoodSearchRun) {
     72     const value = foodSearchSnapshot(coordinator);
     73     if (value && current(token) && value.generation === token) onUpdate(value);
     74     return value;
     75   }
     76   function queue(token: FoodSearchRun) {
     77     if (!current(token)) return;
     78     const value = foodSearchSnapshot(coordinator);
     79     if (!value?.run?.active || !current(token)) return;
     80     const pending = schedule(() => {
     81       if (!current(token)) return;
     82       cancel = undefined;
     83       observe(token);
     84     }, 250);
     85     if (current(token)) cancel = pending;
     86     else pending();
     87   }
     88   function observe(token: FoodSearchRun) {
     89     if (!current(token)) return;
     90     const value = foodSearchSnapshot(coordinator);
     91     if (!value || !current(token)) return;
     92     if (value.run?.active && value.available && value.listings.length) {
     93       try {
     94         resolveFoodSearchPublishers(token);
     95       } catch {
     96         /* Failed metadata retains key fallback and source uncertainty. */
     97       }
     98     }
     99     if (!current(token)) return;
    100     const updated = publish(token);
    101     if (updated?.run?.active && updated.run.activeRequests > 0) queue(token);
    102   }
    103   const token = Object.freeze({}) as SearchView;
    104   const offVisibility = subscribePublicViewVisibility(view, () => {
    105     if (!closed && generation) publish(generation);
    106   });
    107   owners.set(token, {
    108     start(query, known) {
    109       requireOpen();
    110       // Coordinator validates the complete query and seeds before any effects;
    111       // a rejected edit cannot cancel a previously accepted foreground observer.
    112       const next = beginFoodSearch(coordinator, query, known);
    113       stop();
    114       generation = next;
    115       try {
    116         sampleFoodSearch(next);
    117       } catch {
    118         /* Retain ordinary chronological fallback. */
    119       }
    120       if (!current(next)) return;
    121       try {
    122         chronologicalFoodSearch(next);
    123       } catch {
    124         /* Snapshot reports the actual failed source; known rows survive. */
    125       }
    126       if (current(next)) {
    127         publish(next);
    128         queue(next);
    129       }
    130     },
    131     more() {
    132       requireOpen();
    133       if (!generation) throw Error('search_view_inactive');
    134       const next = generation;
    135       showMoreFoodSearch(next);
    136       stop();
    137       publish(next);
    138       queue(next);
    139     },
    140     older() {
    141       requireOpen();
    142       const next = searchOlderFoodSearch(coordinator);
    143       stop();
    144       generation = next;
    145       publish(next);
    146       queue(next);
    147     },
    148     snapshot: () => foodSearchSnapshot(coordinator),
    149     close() {
    150       closed = true;
    151       offVisibility();
    152       stop();
    153       closeFoodSearchCoordinator(coordinator);
    154       generation = undefined;
    155     }
    156   });
    157   return token;
    158 }
    159 export function startSearchView(
    160   view: SearchView,
    161   query: unknown,
    162   known: readonly PublicHead[] = []
    163 ): void {
    164   ownerOf(view).start(query, known);
    165 }
    166 export function moreSearchView(view: SearchView): void {
    167   ownerOf(view).more();
    168 }
    169 export function olderSearchView(view: SearchView): void {
    170   ownerOf(view).older();
    171 }
    172 export function searchViewSnapshot(
    173   view: SearchView
    174 ): SearchViewSnapshot | undefined {
    175   return ownerOf(view).snapshot();
    176 }
    177 export function closeSearchView(view: SearchView): void {
    178   ownerOf(view).close();
    179 }