Jake Vanderwerf
2026-01-11 181938ea32cf2c11d10d56018df22586adff7860
assets/js/concise/DataStore.js
@@ -82,6 +82,7 @@
               endpoint: null,
               apiBase: jvbSettings.api,
               filters: {},
               ignore: [],       //any filters to ignore when filtering store locally
               required: null,
               // Cache
@@ -105,6 +106,11 @@
            _initialized: false
         };
         store.ignoreFilters = new Set([
            ... ['search', 'page', 'per_page', 'orderby', 'order'],
            ... store.config.ignore
         ]);
         store.config.headers = {
            'X-WP-Nonce': window.auth.getNonce(),
            ...store.config.headers
@@ -791,20 +797,20 @@
      // Reject functions
      if (type === 'function') {
         if (validate) return { valid: false, error: `Function at ${path}` };
         console.debug(`[DataStore] Stripped function at ${path}`);
         return { valid: true, data: undefined };
      }
      // DOM elements
      if (obj instanceof HTMLElement || obj.nodeType !== undefined) {
         if (validate) return { valid: false, error: `DOM element at ${path}` };
         console.debug(`[DataStore] Stripped DOM element at ${path}`);
         return { valid: true, data: undefined };
      }
      // FormData - convert and continue
      if (obj instanceof FormData) {
         console.debug(`[DataStore] Converting FormData at ${path}`);
         return { valid: true, data: this.formDataToObject(obj) };
      }
@@ -846,7 +852,7 @@
      }
      if (validate) return { valid: false, error: `Unknown type at ${path}` };
      console.debug(`[DataStore] Stripped unknown type at ${path}`);
      return { valid: true, data: undefined };
   }
@@ -939,51 +945,97 @@
      const cacheEntry = store.cache.get(cacheKey);
      // First check if we have cached results for exact filters
      if (cacheEntry && cacheEntry.items) {
         return cacheEntry.items.reduce((acc, id) => {
      if (cacheEntry?.items) {
         return this.applyOrdering(
            cacheEntry.items.reduce((acc, id) => {
            const item = store.data.get(id);
            if (item) acc.push(item);
            return acc;
         }, []);
            }, []),
            store
         );
      }
      // If we have a search filter and complete base data, filter locally
      if (store.filters.search && store.filters.search.trim()) {
         const searchQuery = store.filters.search.toLowerCase().trim();
         // Get all items and filter them locally
         const allItems = Array.from(store.data.values());
      const searchQuery = store.filters.search?.toLowerCase().trim() || '';
         // Filter by current filters (excluding search and page)
         let filtered = allItems.filter(item => {
            // Apply all filters except search and page
      const filtered = allItems.filter(item => {
         // Apply all non-ignored filters
            for (const [key, value] of Object.entries(store.filters)) {
               if (key === 'search' || key === 'page') continue;
            if (store.ignoreFilters.has(key)) continue;
            if (value === null || value === undefined || value === '') continue;
            if (value === 'all') continue;
               if (value !== null && value !== undefined && value !== '') {
                  if (item[key] !== value) return false;
            // Comma-separated values
            if (typeof value === 'string' && value.includes(',')) {
               const accepted = value.split(',').map(v => v.trim());
               if (!accepted.includes(String(item[key]))) return false;
               continue;
               }
            if (String(item[key]) !== String(value)) return false;
            }
         // Apply search if present
         return !(searchQuery && !this.searchObject(item, searchQuery));
      });
      return this.applyOrdering(filtered, store);
   }
   applyOrdering(items, store) {
      if (!Array.isArray(items)) items = Array.from(items);
      if (items.length === 0) return items;
      if (store.filters.orderby || store.filters.order) {
         const orderby = store.filters.orderby || 'date';
         const order = (store.filters.order || 'desc').toLowerCase();
         items.sort((a, b) => {
            let aVal, bVal;
            switch (orderby) {
               case 'alphabetical':
               case 'title':
                  aVal = (a.fields?.post_title || a.title || a.name || '').toLowerCase();
                  bVal = (b.fields?.post_title || b.title || b.name || '').toLowerCase();
                  break;
               case 'modified':
                  aVal = new Date(a.modified || 0);
                  bVal = new Date(b.modified || 0);
                  break;
               case 'date':
               default:
                  aVal = new Date(a.date || 0);
                  bVal = new Date(b.date || 0);
            }
            if (aVal < bVal) return order === 'asc' ? -1 : 1;
            if (aVal > bVal) return order === 'asc' ? 1 : -1;
            return 0;
         });
      }
      return items;
   }
   searchObject(obj, search) {
      if (!obj || typeof obj !== 'object') return false;
      for (const value of Object.values(obj)) {
         if (value === null || value === undefined) continue;
         if (typeof value === 'object') {
            if (this.searchObject(value, search)) return true;
            continue;
         }
         if (typeof value === 'string' && value.toLowerCase().includes(search)) {
            return true;
         });
         // Apply search filter to common searchable fields
         filtered = filtered.filter(item => {
            // Search in common fields: name, title, path, description
            const searchableFields = ['name', 'title', 'path', 'description', 'slug'];
            return searchableFields.some(field => {
               const value = item[field];
               if (!value) return false;
               return value.toLowerCase().includes(searchQuery);
            });
         });
         return filtered;
      }
      // Fallback to all data
      return this.getAll(name);
      }
      return false;
   }
   async clear(name) {
@@ -1017,14 +1069,18 @@
         }
      });
      const shouldFetch = await this.shouldFetchWithFilters(name, updates, oldFilters);
      this.notify(name, 'filters-changed', {
         oldFilters,
         filters: store.filters,
         updates
      });
      this.notify(name, 'data-loaded', {
         cached: true,
         items: this.getFiltered(name)
      });
      const shouldFetch = await this.shouldFetchWithFilters(name, updates, oldFilters);
      if (store.config.endpoint && shouldFetch) {
         await this.fetch(name);
      } else if (store.config.endpoint) {
@@ -1047,7 +1103,17 @@
         return true;
      }
      // PAGE OPTIMIZATION: Don't fetch if trying to go beyond available pages
      if (store.lastResponse.has_more === false) {
         // Check if new filters are a subset of what we have
         const isSubsetFilter = Object.entries(updates).every(([key, value]) => {
            if (store.ignoreFilters.has(key)) return true;
            if (key === 'page') return true; // Handle pagination locally
            return true; // We have all data, can filter locally
         });
         if (isSubsetFilter) return false;
      }
      if ('page' in updates) {
         const newPage = updates.page;
         const oldPage = oldFilters.page || 1;