feedStores.js raw

   1  import { writable } from 'svelte/store';
   2  
   3  // ==================== Feed State ====================
   4  
   5  // Array of kind 1 events from follows, sorted by created_at desc
   6  export const feedNotes = writable([]);
   7  
   8  // Pagination state
   9  export const feedLoading = writable(false);
  10  export const feedHasMore = writable(true);
  11  export const feedOldestTimestamp = writable(Math.floor(Date.now() / 1000));
  12  
  13  // ==================== Actions ====================
  14  
  15  /**
  16   * Prepend new notes to the feed (for real-time updates)
  17   * @param {Array} notes - New events to prepend
  18   */
  19  export function prependFeedNotes(notes) {
  20      feedNotes.update(existing => {
  21          const ids = new Set(existing.map(e => e.id));
  22          const newNotes = notes.filter(n => !ids.has(n.id));
  23          return [...newNotes, ...existing].sort((a, b) => b.created_at - a.created_at);
  24      });
  25  }
  26  
  27  /**
  28   * Append older notes (for pagination)
  29   * @param {Array} notes - Older events to append
  30   */
  31  export function appendFeedNotes(notes) {
  32      if (notes.length === 0) {
  33          feedHasMore.set(false);
  34          return;
  35      }
  36      feedNotes.update(existing => {
  37          const ids = new Set(existing.map(e => e.id));
  38          const newNotes = notes.filter(n => !ids.has(n.id));
  39          const merged = [...existing, ...newNotes].sort((a, b) => b.created_at - a.created_at);
  40          return merged;
  41      });
  42      // Update oldest timestamp for next page
  43      const oldest = notes.reduce((min, n) => Math.min(min, n.created_at), Infinity);
  44      feedOldestTimestamp.set(oldest);
  45  }
  46  
  47  /**
  48   * Reset feed state (on logout or relay change)
  49   */
  50  export function resetFeedState() {
  51      feedNotes.set([]);
  52      feedLoading.set(false);
  53      feedHasMore.set(true);
  54      feedOldestTimestamp.set(Math.floor(Date.now() / 1000));
  55  }
  56