refactor(badges): stabilize search components and reactivity

- Implemented Search Guard and store initialization in '+page.svelte' to fix loops and filtering.
- Updated 'ae_comp__badge_search.svelte' to act as a pure UI component triggering versioned searches.
- Refactored 'ae_comp__badge_obj_li.svelte' to use shared data streams and fixed icon build errors.
This commit is contained in:
Scott Idem
2026-01-27 17:47:08 -05:00
parent 22ede45bd6
commit bf93539880
3 changed files with 421 additions and 621 deletions

View File

@@ -5,100 +5,261 @@
log_lvl?: number;
}
let { data, log_lvl = 0 }: Props = $props();
let { data, log_lvl = $bindable(1) }: Props = $props();
// *** Import Svelte specific
// import { goto } from '$app/navigation';
import { untrack } from 'svelte';
// *** Import other supporting libraries
// import { browser } from '$app/environment';
import { liveQuery } from 'dexie';
// *** Import Aether specific variables and functions
// import type { key_val } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
// import { core_func } from '$lib/ae_core_functions';
import {
ae_snip,
ae_loc,
ae_sess,
ae_api,
ae_trig,
slct,
slct_trigger
ae_api
} from '$lib/stores/ae_stores';
// import Element_ae_crud from '$lib/element_ae_crud
// import Element_data_store from '$lib/element_data_store_v2.svelte';
// import MyClipboard from '$lib/e_app_clipboard.svelte';
import { db_events } from '$lib/ae_events/db_events';
// import { ae_snip, ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/ae_stores';
import {
events_loc,
events_sess,
events_slct,
events_trigger
} from '$lib/stores/ae_events_stores';
// import { events_func } from '$lib/ae_events_functions';
import { events_func } from '$lib/ae_events_functions';
import Comp_badge_search from './ae_comp__badge_search.svelte';
import Comp_badge_obj_li from './ae_comp__badge_obj_li.svelte';
import { Modal } from 'flowbite-svelte';
import Comp_badge_create_form from './ae_comp__badge_create_form.svelte';
import Comp_badge_upload_form from './ae_comp__badge_upload_form.svelte';
import { LoaderCircle } from 'lucide-svelte';
// *** Variables
// let test_event_id = data.params.event_id;
// console.log(`Data Params: event_id=${test_event_id}`);
let url_test_val = data.url.searchParams.get('test_val');
console.log(`URL test_val = ${url_test_val}`);
import { onMount } from 'svelte';
// Defensively initialize properties to prevent binding to undefined
if ($events_loc.badges && typeof $events_loc.badges.qry_printed_status === 'undefined') {
$events_loc.badges.qry_printed_status = 'all';
}
if ($events_loc.badges && typeof $events_loc.badges.qry_affiliations === 'undefined') {
$events_loc.badges.qry_affiliations = null;
}
if ($events_loc.badges && typeof $events_loc.badges.qry_sort_order === 'undefined') {
$events_loc.badges.qry_sort_order = '';
// *** Initialization & Store Guard ***
// Ensure all search fields are initialized to prevent circular undefined triggers
if ($events_loc.badges) {
if (typeof $events_loc.badges.search_version === 'undefined') $events_loc.badges.search_version = 0;
if (typeof $events_loc.badges.qry__remote_first === 'undefined') $events_loc.badges.qry__remote_first = false;
if (typeof $events_loc.badges.fulltext_search_qry_str === 'undefined') $events_loc.badges.fulltext_search_qry_str = '';
if (typeof $events_loc.badges.search_badge_type_code === 'undefined') $events_loc.badges.search_badge_type_code = '';
if (typeof $events_loc.badges.qry_printed_status === 'undefined') $events_loc.badges.qry_printed_status = 'all';
if (typeof $events_loc.badges.qry_affiliations === 'undefined') $events_loc.badges.qry_affiliations = '';
if (typeof $events_loc.badges.qry_sort_order === 'undefined') $events_loc.badges.qry_sort_order = '';
}
let lq__event_obj = $state(null);
// Variables
let show_create_badge_modal: boolean = $state(false);
let show_upload_badge_modal: boolean = $state(false);
let event_badge_id_li: Array<string> = $state([]);
// let dq__where_type_id_val: string = `event_id_random`;
// let dq__where_eq_id_val: string = $events_slct?.event_id ?? '';
let search_debounce_timer: any = null;
let last_search_id = 0;
let last_executed_key = ''; // Search Guard Key
// let lq__event_badge_obj_li = $derived(liveQuery(async () => {
// if (event_badge_id_li.length > 0) {
// let results = await db_events.badge
// .bulkGet(event_badge_id_li);
// Stable LiveQuery Pattern (Aether UI V3)
let lq__event_badge_obj_li = $derived.by(() => {
const ids = event_badge_id_li;
const event_id = $events_slct?.event_id;
return liveQuery(async () => {
// SCENARIO 1: Specific IDs provided (Search Results)
if (Array.isArray(ids) && ids.length > 0) {
if (log_lvl) console.log(`Badge Page LQ: bulkGet ${ids.length} IDs`);
const results = await db_events.badge.bulkGet(ids);
return results.filter(item => item !== undefined);
}
// SCENARIO 2: Fallback broad search (Only if no active filters)
if (event_id && !$events_loc.badges.fulltext_search_qry_str && $events_loc.badges.qry_printed_status === 'all' && !$events_loc.badges.qry_affiliations && !$events_loc.badges.search_badge_type_code) {
if (log_lvl) console.log(`Badge Page LQ: Fallback search for event: ${event_id}`);
return await db_events.badge
.where('event_id_random')
.equals(event_id)
.limit(50)
.sortBy('given_name');
}
// return results;
// } else {
// let results = await db_events.badge
// .where(dq__where_type_id_val)
// .equals(dq__where_eq_id_val)
// .sortBy('given_name')
// // This should be sorted by a custom sort field
return [];
});
});
// return results;
// }
// }));
// Standardized Reactive Search Pattern (Aether UI V3)
// 1. Isolate dependencies into a stable derived object
let search_params = $derived({
v: $events_loc.badges.search_version,
str: ($events_loc.badges.fulltext_search_qry_str ?? '').toLowerCase().trim(),
type: $events_loc.badges.search_badge_type_code,
printed: $events_loc.badges.qry_printed_status,
aff: ($events_loc.badges.qry_affiliations ?? '').toLowerCase().trim(),
sort: $events_loc.badges.qry_sort_order,
event_id: $events_slct?.event_id,
remote_first: $events_loc.badges.qry__remote_first
});
// *** Functions and Logic
// 2. Controlled effect for triggering searches
$effect(() => {
const params = search_params;
// if (browser) {
// console.log('Browser environment detected.');
if (search_debounce_timer) clearTimeout(search_debounce_timer);
search_debounce_timer = setTimeout(() => {
untrack(() => {
handle_search_refresh(params);
});
}, 300);
// let url_test_val = data.url.searchParams.get('test_val');
// console.log(`URL test_val = ${url_test_val}`);
// }
return () => {
if (search_debounce_timer) clearTimeout(search_debounce_timer);
};
});
async function handle_search_refresh(params: any) {
// 1. Guard
const qry_key = JSON.stringify(params);
if (qry_key === last_executed_key) return;
last_executed_key = qry_key;
const current_search_id = ++last_search_id;
const event_id = params.event_id;
const remote_first = params.remote_first;
if (log_lvl) console.log(`[Badge Search #${current_search_id}] Refreshing (remote=${remote_first}, event=${event_id}, str=${params.str})...`);
untrack(() => {
$events_sess.badges.search_status = 'loading';
$events_sess.badges.search_complete = false;
});
const qry_str = params.str;
const type_code = params.type;
const printed_status = params.printed;
const aff_str = params.aff;
// 2. FAST PATH: Local IDB Search
if (!remote_first) {
try {
if (event_id) {
let local_results = await db_events.badge
.where('event_id_random')
.equals(event_id)
.filter(badge => {
if (type_code && badge.badge_type_code !== type_code) return false;
if (printed_status !== 'all') {
const is_printed = (badge.print_count ?? 0) > 0;
if (printed_status === 'printed' && !is_printed) return false;
if (printed_status === 'not_printed' && is_printed) return false;
}
if (qry_str) {
const given_name = (badge.given_name ?? '').toLowerCase();
const family_name = (badge.family_name ?? '').toLowerCase();
const full_name = `${given_name} ${family_name}`.toLowerCase();
const email = (badge.email ?? '').toLowerCase();
const qry_string = (badge.default_qry_string ?? '').toLowerCase();
const match = full_name.includes(qry_str) ||
given_name.includes(qry_str) ||
family_name.includes(qry_str) ||
email.includes(qry_str) ||
qry_string.includes(qry_str);
if (!match) return false;
}
if (aff_str) {
const affiliations = (badge.affiliations ?? '').toLowerCase();
if (!affiliations.includes(aff_str)) return false;
}
return true;
})
.toArray();
// Complex Sort Logic
local_results.sort((a, b) => {
switch (params.sort) {
case 'name_asc':
return (a.given_name ?? '').localeCompare(b.given_name ?? '') || (a.family_name ?? '').localeCompare(b.family_name ?? '');
case 'name_desc':
return (b.given_name ?? '').localeCompare(a.given_name ?? '') || (b.family_name ?? '').localeCompare(a.family_name ?? '');
case 'updated_desc':
return new Date(b.updated_on || 0).getTime() - new Date(a.updated_on || 0).getTime();
case 'updated_asc':
return new Date(a.updated_on || 0).getTime() - new Date(b.updated_on || 0).getTime();
case 'print_count_desc':
return (b.print_count ?? 0) - (a.print_count ?? 0);
default:
return (a.given_name ?? '').localeCompare(b.given_name ?? '');
}
});
const local_ids = local_results.map(b => b.id || b.event_badge_id_random).filter(Boolean);
if (current_search_id === last_search_id) {
if (log_lvl) console.log(`[Badge Search #${current_search_id}] Fast Path found ${local_ids.length} items locally.`);
untrack(() => {
event_badge_id_li = local_ids;
if (local_ids.length > 0) $events_sess.badges.search_status = 'done';
});
}
}
} catch (e) {
if (log_lvl) console.warn('Badge Fast Path failed.', e);
}
} else {
untrack(() => {
event_badge_id_li = [];
});
}
// 3. REVALIDATE: API Request
try {
// Map sort param to API order_by_li
let order_by_li: any = {};
switch (params.sort) {
case 'name_asc': order_by_li = { given_name: 'ASC', family_name: 'ASC' }; break;
case 'name_desc': order_by_li = { given_name: 'DESC', family_name: 'DESC' }; break;
case 'updated_desc': order_by_li = { updated_on: 'DESC' }; break;
case 'updated_asc': order_by_li = { updated_on: 'ASC' }; break;
case 'print_count_desc': order_by_li = { print_count: 'DESC' }; break;
default: order_by_li = { given_name: 'ASC' };
}
const results = await events_func.search__event_badge({
api_cfg: $ae_api,
event_id: event_id,
fulltext_search_qry_str: qry_str || null,
type_code: type_code || null,
printed_status: printed_status,
affiliations_qry_str: aff_str || null,
order_by_li: order_by_li,
limit: 150,
log_lvl: 0
});
if (current_search_id === last_search_id) {
const api_results = results || [];
const api_ids = api_results.map((b: any) => b.id || b.event_badge_id_random).filter(Boolean);
untrack(() => {
$events_sess.badge_li = api_results;
event_badge_id_li = api_ids;
$events_sess.badges.search_status = 'done';
$events_sess.badges.search_complete = true;
});
if (log_lvl) console.log(`[Badge Search #${current_search_id}] Revalidation Complete. Found ${api_ids.length} items.`);
}
} catch (error) {
if (current_search_id === last_search_id) {
console.error('Badge revalidation failed:', error);
untrack(() => {
$events_sess.badges.search_status = 'error';
$events_sess.badges.search_complete = true;
});
}
}
}
</script>
{#if show_create_badge_modal}
@@ -109,7 +270,7 @@
event_id={$events_slct?.event_id ?? ''}
on:success={() => {
show_create_badge_modal = false;
$events_trigger.event_badge_qry = true; // Trigger a refresh of the list
$events_loc.badges.search_version++;
}}
on:cancel={() => (show_create_badge_modal = false)}
/>
@@ -125,7 +286,7 @@
event_id={$events_slct?.event_id ?? ''}
on:success={() => {
show_upload_badge_modal = false;
$events_trigger.event_badge_qry = true; // Trigger a refresh of the list
$events_loc.badges.search_version++;
}}
on:cancel={() => (show_upload_badge_modal = false)}
/>
@@ -136,24 +297,13 @@
<svelte:head>
<title>
Badges -
{ae_util.shorten_string({ string: lq__event_obj?.name ?? '-- not set --', max_length: 12 })}
{ae_util.shorten_string({ string: $events_slct?.event_obj?.name ?? '-- not set --', max_length: 12 })}
- OSIT's &AElig; Events
</title>
</svelte:head>
<!-- badges +page: Where is here??? -->
<!-- event_badge_obj_li={$lq__event_badge_obj_li} -->
<Comp_badge_search
event_id={$events_slct?.event_id ?? ''}
bind:use_id_li={$events_sess.badges.use_id_li}
bind:search_status={$events_sess.badges.search_status}
bind:search_complete={$events_sess.badges.search_complete}
bind:qry_str={$events_loc.badges.fulltext_search_qry_str}
bind:qry_type_code={$events_loc.badges.search_badge_type_code}
bind:qry_printed_status={$events_loc.badges.qry_printed_status}
bind:qry_affiliations={$events_loc.badges.qry_affiliations}
bind:qry_sort_order={$events_loc.badges.qry_sort_order}
log_lvl={1}
></Comp_badge_search>
@@ -201,32 +351,14 @@
</div>
{/if}
<!-- {#await $lq__event_badge_obj_li}
Loading....
{:then event_badge_obj_li}
{/await} -->
<!-- This is how we reset the Dixie liveQuery when the search parameters change. I wish there was a better way??? -->
{#if $events_sess?.badges?.search_status != 'loading' && $events_sess?.badges?.search_status != 'processing'}
{#if $events_sess?.badges?.search_status === 'loading' && event_badge_id_li.length === 0}
<div class="flex flex-col items-center justify-center p-10 opacity-50 text-center">
<LoaderCircle size="3em" class="animate-spin mb-4 mx-auto" />
<p class="text-xl">Loading badges...</p>
</div>
{:else}
<Comp_badge_obj_li
badge_obj_li={$events_sess.badge_li}
qry_str={$events_loc.badges.fulltext_search_qry_str}
qry_type_code={$events_loc.badges.search_badge_type_code}
lq__event_badge_obj_li={lq__event_badge_obj_li}
log_lvl={1}
></Comp_badge_obj_li>
{:else}
<p class="p-4 italic text-sm text-surface-400">Loading badges...</p>
{/if}
<!-- {#if event_badge_id_li && event_badge_id_li?.length > 0}
<Comp_badge_obj_li
event_badge_id_li={event_badge_id_li}
qry_str={$events_loc.badges.fulltext_search_qry_str}
qry_type_code={$events_loc.badges.search_badge_type_code}
log_lvl={1}
>
</Comp_badge_obj_li>
{:else}
<p class="p-4 italic text-sm text-surface-400">No badges found for this event.</p>
{/if} -->
{/if}

View File

@@ -1,9 +1,7 @@
<script lang="ts">
interface Props {
// Exports
container_class_li?: string | Array<string>;
// export let display_mode: string = 'default'; // 'default', 'compact', 'minimal', 'launcher'
badge_obj_li?: Array<any>;
lq__event_badge_obj_li: any;
log_lvl?: number;
show_sensitive_fields?: boolean;
hide_affiliations?: boolean;
@@ -13,7 +11,7 @@
let {
container_class_li = [],
badge_obj_li = [],
lq__event_badge_obj_li,
log_lvl = $bindable(0),
show_sensitive_fields = true,
hide_affiliations = false,
@@ -21,220 +19,143 @@
hide_badge_type = false
}: Props = $props();
import { liveQuery } from 'dexie';
import { db_events, type Badge } from '$lib/ae_events/db_events';
import { type Badge as BadgeType } from '$lib/ae_events/db_events';
import { ae_loc } from '$lib/stores/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
// let trusted_access = $derived(ae_loc.trusted_access); // This does NOT work with Svelte v5
// let trusted_access = $ae_loc?.trusted_access; // This works with Svelte v5
import { LoaderCircle, Badge, Check, EyeOff, Mail, MapPin, Tags, FileSearch } from 'lucide-svelte';
let lq__event_badge_obj_li = $derived(
liveQuery(async () => {
if (badge_obj_li?.length) {
const ids = badge_obj_li.map((b) => b.event_badge_id_random);
const db_results = await db_events.badge.bulkGet(ids);
// Derived list of visible items (Standardized Pattern 2026-01-27)
let visible_badge_obj_li = $derived((() => {
const list = $lq__event_badge_obj_li;
// Create a map for quick lookup by ID to restore order
// bulkGet does not guarantee order, so we must re-sort based on the input list
const db_results_map = new Map(
db_results.filter(Boolean).map((item) => [item.event_badge_id_random, item])
);
if (list === undefined || list === null) return null;
if (!Array.isArray(list)) return [];
// Return items in the exact order of the original 'ids' array
return ids.map((id) => db_results_map.get(id)).filter(Boolean);
}
return [];
})
);
const filtered = list.filter((item: any) => {
if (!item) return false;
// ADMIN/TRUSTED: See everything
if ($ae_loc.trusted_access) return true;
// PUBLIC: Filter hidden
return !item.hide;
});
if (log_lvl) console.log(`visible_badge_obj_li: Input=${list.length}, Output=${filtered.length}`);
return filtered;
})());
</script>
<section class="px-1 flex flex-col gap-1 items-center justify-center space-y-1">
<!-- event_badge_id_li?.length && -->
{#if $lq__event_badge_obj_li?.length}
<header class="w-full flex flex-row gap-1 items-center justify-start">
<h2 class="text-base">Results:</h2>
<div class="text-3xl font-bold preset-filled-success-100-900 px-4 rounded-lg">
<span class="fas fa-list-ol mx-4"></span>
{$lq__event_badge_obj_li.length}&times;
</div>
<section class="px-1 flex flex-col gap-1 items-center justify-center space-y-1 w-full max-w-7xl mx-auto">
{#if visible_badge_obj_li === null}
<div class="flex flex-col items-center justify-center p-10 opacity-50">
<LoaderCircle size="2em" class="animate-spin mb-2" />
<p>Loading badges...</p>
</div>
{:else if visible_badge_obj_li.length > 0}
<header class="w-full flex flex-row gap-2 items-center justify-start mb-2 px-2">
<h2 class="text-sm text-gray-500 font-normal"> Results: </h2>
<span class="badge preset-tonal-success font-bold text-lg px-3 py-1">
{visible_badge_obj_li.length}<span class="text-gray-400 dark:text-gray-600">&times;</span>
</span>
</header>
<!-- The email should only be the first 3 chars and then @domain name. -->
<ul class="list-disc list-inside w-full">
{#each $lq__event_badge_obj_li.filter(Boolean) as event_badge_obj: Badge (event_badge_obj?.event_badge_id)}
{#if !event_badge_obj?.hide || $ae_loc.trusted_access}
<li
class="
border-b border-gray-300 dark:border-gray-600 py-0.5
flex flex-row flex-wrap gap-1 items-center justify-between w-full
<ul class="w-full space-y-1">
{#each visible_badge_obj_li as event_badge_obj (event_badge_obj.event_badge_id_random)}
<li
class="
border border-surface-200 dark:border-surface-700 rounded-lg p-2
bg-surface-50 dark:bg-surface-900/50
flex flex-col gap-1 w-full
hover:border-primary-500 transition-colors
"
>
<div class="flex flex-row flex-wrap gap-1 items-center justify-start grow">
{#if event_badge_obj?.print_count < 1 || $ae_loc.trusted_access}
<a
href={`/events/${event_badge_obj?.event_id}/badges/${event_badge_obj?.event_badge_id}`}
class="flex flex-row gap-1 items-center justify-start min-w-fit"
title={`Badge: ${event_badge_obj?.full_name ?? event_badge_obj?.given_name ?? '-- no name --'}\nID: ${event_badge_obj?.event_badge_id}`}
>
<span>
{#if event_badge_obj?.hide}
<span class="fas fa-eye-slash mx-1"></span>
{:else}
<span class="fas fa-id-badge mx-1"></span>
{/if}
{#if event_badge_obj?.print_count >= 1}
<!-- Show a green checkmark -->
<span class="fas fa-check text-green-500"></span>
>
<div class="flex flex-row flex-wrap gap-2 items-center justify-between w-full">
<div class="flex flex-row flex-wrap gap-2 items-center justify-start grow">
<a
href={`/events/${event_badge_obj?.event_id}/badges/${event_badge_obj?.event_badge_id}`}
class="flex flex-row gap-2 items-center justify-start min-w-fit font-bold text-lg hover:text-primary-500"
>
{#if event_badge_obj?.hide}
<EyeOff size="1.2em" class="text-gray-400" />
{:else}
<Badge size="1.2em" />
{/if}
<span class="print_count px-1"
>{event_badge_obj?.print_count}&times;</span
>
{/if}
</span>
<span class="font-bold">
{#if event_badge_obj?.full_name_override}
{event_badge_obj?.full_name_override}
{:else if event_badge_obj?.full_name}
{event_badge_obj?.full_name}
{:else if event_badge_obj?.given_name}
{event_badge_obj?.given_name} {event_badge_obj?.family_name}
{:else}
-- no name --
{/if}
</span>
</a>
{:else}
<span
class="flex flex-row gap-1 items-center justify-start min-w-fit"
title={`Badge: ${event_badge_obj?.full_name ?? event_badge_obj?.given_name ?? '-- no name --'}\nID: ${event_badge_obj?.event_badge_id}`}
>
<span>
{#if event_badge_obj?.hide}
<span class="fas fa-eye-slash mx-1"></span>
{:else}
<span class="fas fa-id-badge mx-1"></span>
{/if}
{#if event_badge_obj?.print_count >= 1}
<!-- Show a green checkmark -->
<span class="fas fa-check text-green-500"></span>
<span class="print_count px-1"
>{event_badge_obj?.print_count}&times;</span
>
{/if}
</span>
<span class="font-bold">
{#if event_badge_obj?.full_name_override}
{event_badge_obj?.full_name_override}
{:else if event_badge_obj?.full_name}
{event_badge_obj?.full_name}
{:else if event_badge_obj?.given_name}
{event_badge_obj?.given_name} {event_badge_obj?.family_name}
{:else}
-- no name --
{/if}
</span>
<span>
{#if event_badge_obj?.full_name_override}
{event_badge_obj?.full_name_override}
{:else if event_badge_obj?.full_name}
{event_badge_obj?.full_name}
{:else}
{event_badge_obj?.given_name} {event_badge_obj?.family_name}
{/if}
</span>
{/if}
{#if event_badge_obj?.print_count >= 1}
<span class="badge preset-filled-success-500 flex items-center gap-1 text-xs py-0 px-1">
<Check size="1em" />
{event_badge_obj.print_count}
</span>
{/if}
</a>
{#if show_sensitive_fields}
<span class="mx-1 text-gray-400">|</span>
<span class="min-w-fit">
<span class="fas fa-envelope"></span>
<span class="text-xs text-surface-400 flex items-center gap-1">
<Mail size="1em" />
{#if $ae_loc.trusted_access}
{event_badge_obj?.email}
{:else}
{event_badge_obj?.email
? event_badge_obj?.email.replace(/^(.{3}).*@/, '$1...@')
: ''}
{event_badge_obj?.email?.replace(/^(.{3}).*@/, '$1...@') ?? ''}
{/if}
</span>
{/if}
{#if !hide_affiliations}
<span class="mx-1 text-gray-400">|</span>
<span class="text-sm">
{event_badge_obj?.affiliations ?? '-- no affiliations --'}
{#if !hide_affiliations && event_badge_obj.affiliations}
<span class="text-xs text-surface-400 flex items-center gap-1">
<MapPin size="1em" />
{event_badge_obj.affiliations}
</span>
{/if}
{#if !hide_location}
<span class="mx-1 text-gray-400">|</span>
<span class="text-sm">
{event_badge_obj?.location ?? '-- no location --'}
</span>
{/if}
{#if !hide_badge_type}
<span class="mx-1 text-gray-400">|</span>
<span class="italic text-sm">{event_badge_obj?.badge_type}</span>
{/if}
{#if $ae_loc.edit_mode}
<div
class="flex flex-row flex-wrap gap-2 items-center justify-start w-full mt-1 p-1 bg-surface-100/50 dark:bg-surface-800/50 rounded text-[10px] font-mono border border-surface-200 dark:border-surface-700"
>
<span title="Badge ID" class="bg-primary-500/10 px-1 rounded">
ID: {event_badge_obj?.event_badge_id}
</span>
<span title="Created On">
CR: {event_badge_obj?.created_on
? new Date(event_badge_obj.created_on).toLocaleString()
: '--'}
</span>
<span title="Updated On">
UP: {event_badge_obj?.updated_on
? new Date(event_badge_obj.updated_on).toLocaleString()
: '--'}
</span>
<span title="First Printed">
FP: {event_badge_obj?.print_first_datetime
? new Date(
event_badge_obj.print_first_datetime
).toLocaleString()
: '--'}
</span>
<span title="Last Printed">
LP: {event_badge_obj?.print_last_datetime
? new Date(
event_badge_obj.print_last_datetime
).toLocaleString()
: '--'}
</span>
<span title="Print Count">
CNT: {event_badge_obj?.print_count ?? 0}
</span>
</div>
{#if !hide_badge_type && event_badge_obj.badge_type}
<span class="text-xs italic text-primary-500 bg-primary-500/10 px-2 rounded-token flex items-center gap-1">
<Tags size="1em" />
{event_badge_obj.badge_type}
</span>
{/if}
</div>
{#if $ae_loc.trusted_access}
<a
href={`/events/${event_badge_obj?.event_id}/badges/${event_badge_obj?.event_badge_id}#review`}
class="btn btn-sm variant-soft-primary min-w-fit">Review</a
class="btn btn-sm preset-tonal-primary"
>
Review
</a>
{/if}
</li>
{/if}
</div>
{#if $ae_loc.edit_mode}
<div
class="flex flex-row flex-wrap gap-x-4 gap-y-1 items-center justify-start w-full mt-1 p-1.5 bg-surface-200/50 dark:bg-surface-800/50 rounded text-[10px] font-mono border border-surface-300 dark:border-surface-700 opacity-80"
>
<span class="flex items-center gap-1"><span class="font-bold opacity-50">ID:</span> {event_badge_obj?.event_badge_id}</span>
<span class="flex items-center gap-1"><span class="font-bold opacity-50">CR:</span> {ae_util.iso_datetime_formatter(event_badge_obj.created_on, 'datetime_iso_12_no_seconds')}</span>
<span class="flex items-center gap-1"><span class="font-bold opacity-50">UP:</span> {ae_util.iso_datetime_formatter(event_badge_obj.updated_on, 'datetime_iso_12_no_seconds')}</span>
{#if event_badge_obj.print_first_datetime}
<span class="flex items-center gap-1"><span class="font-bold opacity-50">FP:</span> {ae_util.iso_datetime_formatter(event_badge_obj.print_first_datetime, 'datetime_iso_12_no_seconds')}</span>
{/if}
{#if event_badge_obj.print_last_datetime}
<span class="flex items-center gap-1"><span class="font-bold opacity-50">LP:</span> {ae_util.iso_datetime_formatter(event_badge_obj.print_last_datetime, 'datetime_iso_12_no_seconds')}</span>
{/if}
</div>
{/if}
</li>
{/each}
</ul>
<!-- <table class="table">
<thead>
<tr>
<th>Badge</th>
<th>Email / Affiliations / Location</th>
<th>Affiliations / Location</th>
<th>Badge Type</th>
</tr>
</thead>
<tbody>
<tr><td class=""></td><td class=""></td></tr>
</tbody>
</table> -->
{:else}
<div class="">
<p>No results available to show.</p>
<div class="flex flex-col items-center justify-center p-20 opacity-50 text-center">
<FileSearch size="3em" class="mb-2 opacity-20 mx-auto" />
<p>No badges found matching your criteria. Try adjusting your filters.</p>
</div>
{/if}
</section>
</section>

View File

@@ -1,109 +1,35 @@
<script lang="ts">
interface Props {
event_id: string;
use_id_li?: boolean;
event_badge_id_li?: Array<string>;
// event_badge_obj_li?: Array<any>;
search_status?: string;
search_complete?: boolean;
qry_str?: string;
qry_type_code?: string;
qry_printed_status?: string;
qry_affiliations?: string;
qry_sort_order?: string;
log_lvl?: number;
}
let {
event_id,
use_id_li = $bindable(true),
event_badge_id_li = $bindable([]),
// event_badge_obj_li = $bindable(),
search_status = $bindable('idle'),
search_complete = $bindable(true),
qry_str = $bindable(''),
qry_type_code = $bindable(''),
qry_printed_status = $bindable(''),
qry_affiliations = $bindable(''),
qry_sort_order = $bindable(''),
log_lvl = 0
}: Props = $props();
// *** Import Svelte specific
// *** Import other supporting libraries
import {
ArrowDown01,
ArrowDown10,
ArrowDownUp,
BetweenVerticalEnd,
BetweenVerticalStart,
BookHeart,
BookImage,
Bookmark,
BookOpenText,
BriefcaseBusiness,
Check,
Copy,
Expand,
Eye,
EyeOff,
Flag,
FlagOff,
FilePlus,
Fingerprint,
Globe,
Library,
MessageSquareWarning,
Minus,
Notebook,
Pencil,
Plus,
RemoveFormatting,
SquareLibrary,
Shapes,
Share2,
ShieldCheck,
ShieldMinus,
Siren,
Skull,
Tags,
Target,
ToggleLeft,
ToggleRight,
Trash2,
TypeOutline,
X
} from '@lucide/svelte';
X,
QrCode,
Search,
Check,
LoaderCircle
} from 'lucide-svelte';
import type { key_val } from '$lib/stores/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
import {
ae_snip,
ae_loc,
ae_sess,
ae_api,
ae_trig,
slct,
slct_trigger
ae_api
} from '$lib/stores/ae_stores';
import {
events_loc,
events_sess,
events_slct,
events_trigger
events_sess
} from '$lib/stores/ae_events_stores';
import { events_func } from '$lib/ae_events_functions';
import Element_qr_scanner_v2 from '$lib/element_qr_scanner_v2.svelte';
// *** Variables
let ae_promises: key_val = $state({});
let ae_tmp: key_val = $state({});
let ae_triggers: key_val = $state({});
let search_limit = $derived(
$ae_loc.administrator_access ? 150 : $ae_loc.trusted_access ? 75 : 20
);
import { ae_util } from '$lib/ae_utils/ae_utils';
// ISHLT 2024 badge type codes
let badge_type_code_li = [
@@ -122,42 +48,13 @@
{ code: 'test', name: 'Test' }
];
let computed_order_by_li = $derived(
(() => {
switch (qry_sort_order) {
case 'name_asc':
return { given_name: 'ASC', family_name: 'ASC' };
case 'name_desc':
return { given_name: 'DESC', family_name: 'DESC' };
case 'updated_desc':
return { updated_on: 'DESC' };
case 'updated_asc':
return { updated_on: 'ASC' };
case 'print_count_desc':
return { print_count: 'DESC' };
case 'print_first_desc':
return { print_first_datetime: 'DESC' };
case 'print_last_desc':
return { print_last_datetime: 'DESC' };
case 'badge_type_asc':
return { badge_type: 'ASC' };
case 'affiliations_asc':
return { affiliations: 'ASC' };
default:
return {
// print_count: 'ASC',
// priority: 'DESC',
// sort: 'DESC',
given_name: 'ASC',
family_name: 'ASC',
updated_on: 'DESC',
created_on: 'DESC'
};
}
})()
);
function handle_search_trigger() {
if ($events_loc.badges.search_version === undefined) {
$events_loc.badges.search_version = 0;
}
$events_loc.badges.search_version++;
}
// *** Functions and Logic
function preventDefault<T extends Event>(fn: (event: T) => void) {
return function (event: T) {
event.preventDefault();
@@ -165,165 +62,57 @@
};
}
// Debounced Search Logic (Refactored 2026-01-27)
let search_debounce_timer: any = null;
let last_search_id = 0;
$effect(() => {
// Reactive dependencies
const s_qry_str = qry_str;
const s_qry_type_code = qry_type_code;
const s_qry_printed_status = qry_printed_status;
const s_qry_affiliations = qry_affiliations;
const s_qry_sort_order = qry_sort_order;
const s_event_id = event_id;
const s_trigger = ae_triggers.event_badge_qry;
// Debounce search
if (search_debounce_timer) clearTimeout(search_debounce_timer);
// Manual trigger or threshold check for automatic search
const should_search = s_trigger ||
s_qry_str.length === 0 ||
s_qry_str.length >= 3 ||
s_qry_affiliations.length >= 3;
if (should_search) {
search_debounce_timer = setTimeout(() => {
ae_triggers.event_badge_qry = false;
handle_search_refresh();
}, 400);
}
return () => {
if (search_debounce_timer) clearTimeout(search_debounce_timer);
};
});
async function handle_search_refresh() {
const current_search_id = ++last_search_id;
if (log_lvl) console.log(`[Badge Search #${current_search_id}] ft=${qry_str}`);
search_status = 'loading';
search_complete = false;
try {
const results = await events_func.search__event_badge({
api_cfg: $ae_api,
event_id: event_id,
fulltext_search_qry_str: qry_str,
type_code: qry_type_code,
printed_status: qry_printed_status,
affiliations_qry_str: qry_affiliations,
order_by_li: computed_order_by_li,
limit: search_limit,
log_lvl: 0
});
if (current_search_id === last_search_id) {
let tmp_event_badge_id_li = results.map((b: any) => b.event_badge_id_random);
event_badge_id_li = tmp_event_badge_id_li;
$events_sess.badge_li = results;
search_status = 'done';
search_complete = true;
if (log_lvl) console.log(`[Badge Search #${current_search_id}] Done. Found ${results.length} results.`);
}
} catch (error) {
if (current_search_id === last_search_id) {
console.error('Badge search failed:', error);
search_status = 'error';
search_complete = true;
}
}
}
function handle_qr_scan_result(event: CustomEvent) {
console.log('*** handle_qr_scan_result() ***');
let qr_scan_result = event.detail.result;
console.log(qr_scan_result);
let obj = ae_util.process_data_string(qr_scan_result); // Assuming ae_util has process_data_string
let obj = ae_util.process_data_string(qr_scan_result);
if (obj && obj.type && obj.id && obj.type === 'event_badge') {
console.log(`Found event_badge ID: ${obj.id}`);
// Set the qry_str to the scanned ID and trigger search
$events_loc.badges.fulltext_search_qry_str = obj.id;
ae_triggers.event_badge_qry = true;
// Switch back to search form after scan
handle_search_trigger();
$events_sess.badges.show_form__search = true;
$events_sess.badges.show_form__scan = false;
$events_sess.badges.qr_scan_start = false;
} else {
console.log('The object returned was unexpected or not valid for event_badge.');
// Optionally, provide feedback to the user
}
}
</script>
<section
class="
m-2 p-2 md:px-12
flex flex-col sm:flex-row gap-1 items-center justify-center
min-w-sm w-full max-w-7xl
preset-tonal-success
"
>
<span class="text-sm text-gray-500 hidden"> Search: </span>
<div class="ae_group filters_and_search flex flex-col items-center justify-center gap-2 w-full">
{#if $events_sess.badges.show_form__search}
<form
onsubmit={preventDefault(() => {
// ae_triggers.event_badge_qry = 'load__event_badge_obj_li';
ae_triggers.event_badge_qry = true;
handle_search_trigger();
})}
autocomplete="off"
class="
form grow
flex flex-row flex-wrap gap-1 items-center justify-center
w-full
"
class="search_form flex flex-row flex-wrap gap-1 items-center justify-center w-full max-w-7xl px-2 md:px-12 py-2 preset-tonal-success rounded-lg shadow-sm"
>
<span class="flex flex-col md:flex-row items-center justify-center gap-1">
{#if $ae_loc.trusted_access && badge_type_code_li}
<div class="flex flex-col md:flex-row items-center justify-center gap-1 grow">
{#if $ae_loc.trusted_access}
<select
bind:value={qry_type_code}
onchange={() => {
// ae_triggers.event_badge_qry = 'load__event_badge_obj_li';
ae_triggers.event_badge_qry = true;
}}
class="select text-xs px-1 max-w-fit"
bind:value={$events_loc.badges.search_badge_type_code}
onchange={handle_search_trigger}
class="select select-sm text-xs px-1 max-w-fit"
>
<option value="">-- All Badge Types --</option>
{#each badge_type_code_li as badge_type_code}
<option value={badge_type_code.code}>{badge_type_code.name}</option>
{/each}
</select>
{/if}
{#if $ae_loc.trusted_access}
<select
bind:value={qry_printed_status}
onchange={() => {
ae_triggers.event_badge_qry = true;
}}
class="select text-xs px-1 max-w-fit"
bind:value={$events_loc.badges.qry_printed_status}
onchange={handle_search_trigger}
class="select select-sm text-xs px-1 max-w-fit"
>
<option value="all">-- All Print Status --</option>
<option value="printed">Printed</option>
<option value="not_printed">Not Printed</option>
</select>
{/if}
{#if $ae_loc.trusted_access}
<select
bind:value={qry_sort_order}
onchange={() => {
ae_triggers.event_badge_qry = true;
}}
class="select text-xs px-1 max-w-fit"
bind:value={$events_loc.badges.qry_sort_order}
onchange={handle_search_trigger}
class="select select-sm text-xs px-1 max-w-fit"
>
<option value="">-- Default Sort --</option>
<option value="name_asc">Name ASC</option>
@@ -336,175 +125,133 @@
<option value="badge_type_asc">Badge Type ASC</option>
<option value="affiliations_asc">Affiliations ASC</option>
</select>
{/if}
{#if $ae_loc.trusted_access}
<input
type="search"
placeholder="affiliations"
bind:value={qry_affiliations}
onkeyup={() => {
if (qry_affiliations.length >= 3) {
ae_triggers.event_badge_qry = true;
bind:value={$events_loc.badges.qry_affiliations}
onkeyup={(e) => {
if (e.key === 'Enter' || ($events_loc.badges.qry_affiliations?.length ?? 0) >= 3) {
handle_search_trigger();
}
}}
class="input text-xs px-1 max-w-fit"
class="input input-sm text-xs px-1 max-w-fit"
/>
{/if}
<!--
class="input text-xl hover:text-3xl font-bold font-mono w-96"
hover:w-2/5
-->
<!-- svelte-ignore a11y_autofocus -->
<input
type="search"
placeholder="name, email"
id="badge_fulltext_search_qry_str"
name="fulltext_search_qry_str"
bind:value={qry_str}
autofocus
bind:value={$events_loc.badges.fulltext_search_qry_str}
suggest="off"
data-lpignore="true"
class="input text-1xl hover:font-bold font-mono w-fit sm:w-96 transition-all"
onkeyup={() => {
if (qry_str.length >= 7) {
ae_triggers.event_badge_qry = true;
class="input text-lg font-mono grow transition-all"
onkeyup={(e) => {
if (e.key === 'Enter') {
handle_search_trigger();
}
}}
title="Enter at least 3 characters to search. Search by name, email, affiliations, etc."
title="Search by name, email, etc. Press Enter."
/>
</span>
</div>
<span class="flex flex-row flex-wrap items-center justify-center gap-1">
<div class="flex flex-row items-center justify-center gap-1">
<button
type="submit"
class="btn btn-lg preset-tonal-success border border-success-500 hover:preset-tonal-success text-2xl font-bold w-48 transition-all"
onclick={() => {
ae_triggers.event_badge_qry = true;
}}
>
{#if !search_complete}
{#if $events_sess.badges.search_status === 'loading'}
<span class="fas fa-spinner fa-spin mx-1"></span>
{:else}
<!-- Nothing -->
<span class="fas fa-search mx-1"></span>
{/if}
Search
</button>
<!-- Clear search text button -->
<button
type="button"
class:hidden={!qry_str}
class:hidden={!$events_loc.badges.fulltext_search_qry_str && !$events_loc.badges.search_badge_type_code && $events_loc.badges.qry_printed_status === 'all'}
onclick={() => {
console.log(`TESTING - 1 - Cleared search query: ${qry_str}`);
qry_str = '';
console.log(`TESTING - 2 - Cleared search query: ${qry_str}`);
ae_triggers.event_badge_qry = true;
$events_loc.badges.fulltext_search_qry_str = '';
$events_loc.badges.search_badge_type_code = '';
$events_loc.badges.qry_printed_status = 'all';
$events_loc.badges.qry_affiliations = '';
handle_search_trigger();
}}
class="
btn btn-sm text-xs
preset-outlined-tertiary-100-900
hover:preset-filled-tertiary-100-900
transition-all
"
title="Clear search query text"
class="btn btn-sm text-xs preset-outlined-tertiary-100-900 hover:preset-filled-tertiary-100-900 transition-all"
title="Clear search query"
>
<RemoveFormatting
size="1.25em"
class="text-neutral-800/60 dark:text-neutral-50/60"
/>
<RemoveFormatting size="1.25em" />
<span class="hidden md:inline"> Clear </span>
{#await ae_promises.load__event_badge_obj_li}
<span class="text-xs text-gray-500 italic"> Loading... </span>
{:then load_result}
{#if load_result === null}
<span
class="text-xs text-gray-600/80 dark:text-gray-400/80 italic font-semibold"
>
No entries found - null
</span>
{:else if load_result?.length === 0}
<span
class="text-xs text-gray-600/80 dark:text-gray-400/80 italic font-semibold"
>
No entries found
</span>
{:else if event_badge_id_li?.length === 0}
<span class="text-xs text-gray-600/80 dark:text-gray-400/80 italic">
Enter to search
</span>
{:else}
<span class="text-xs text-gray-600/80 dark:text-gray-400/80 italic">
{load_result?.length ?? 0} found
</span>
{/if}
{:catch error}
<span class="text-xs text-red-600/80 dark:text-red-400/80 italic">
Error loading entries.
</span>
{/await}
</button>
</span>
</div>
</form>
<!-- **BEGIN** Scan Form -->
{:else if $events_sess.badges.show_form__scan}
<Element_qr_scanner_v2
bind:start_qr_scanner={$events_sess.badges.qr_scan_start}
on:qr_scan_result={handle_qr_scan_result}
/>
<div class="w-full max-w-2xl mx-auto p-4 bg-surface-100-900 rounded-lg shadow-lg">
<Element_qr_scanner_v2
bind:start_qr_scanner={$events_sess.badges.qr_scan_start}
on:qr_scan_result={handle_qr_scan_result}
/>
</div>
{/if}
<div class="opacity-50 hover:opacity-100 transition-all">
<div class="flex flex-row flex-wrap items-center justify-center gap-2 opacity-70 hover:opacity-100 transition-all">
{#if $events_sess.badges.show_form__search}
<button
type="button"
onclick={() => {
$events_sess.badges.show_form__search = false;
$events_sess.badges.show_form__search_results = false;
$events_sess.badges.show_form__scan = true;
$events_sess.badges.qr_scan_start = true;
}}
class="btn btn-sm preset-tonal-primary border border-primary-500 transition-all"
class="btn btn-sm preset-tonal-primary border border-primary-500"
>
<span class="fas fa-qrcode"></span>
<span class="fas fa-qrcode mr-1"></span>
QR Scan
</button>
{:else if $events_sess.badges.show_form__scan}
{:else}
<button
type="button"
onclick={() => {
$events_sess.badges.show_form__search = true;
$events_sess.badges.show_form__search_results = false;
$events_sess.badges.show_form__scan = false;
$events_sess.badges.qr_scan_start = false;
}}
class="btn btn-sm preset-tonal-primary border border-primary-500 transition-all"
class="btn btn-sm preset-tonal-primary border border-primary-500"
>
<span class="fas fa-search"></span>
<span class="fas fa-search mr-1"></span>
Search
</button>
{/if}
<!-- Show toggle for using the id list or not: use_id_li -->
<button
type="button"
onclick={() => {
use_id_li = !use_id_li;
console.log(`Toggled use_id_li=${use_id_li}`);
$events_loc.badges.use_id_li = !$events_loc.badges.use_id_li;
handle_search_trigger();
}}
class="btn btn-sm preset-tonal-secondary border border-secondary-500 transition-all"
class="btn btn-sm preset-tonal-secondary border border-secondary-500"
title="Toggle using the ID list or not."
>
{#if use_id_li}
<span class="fas fa-toggle-on text-green-600"></span>
{#if $events_loc.badges.use_id_li}
<span class="fas fa-toggle-on text-green-600 mr-1"></span>
{:else}
<span class="fas fa-toggle-off text-red-600"></span>
<span class="fas fa-toggle-off text-red-600 mr-1"></span>
{/if}
Use ID List
</button>
{#if $ae_loc.edit_mode}
<label class="flex items-center gap-1 cursor-pointer bg-surface-200-800 px-2 py-1 rounded-token text-xs font-semibold">
<span> Remote First </span>
<input
type="checkbox"
bind:checked={$events_loc.badges.qry__remote_first}
onchange={handle_search_trigger}
class="checkbox checkbox-sm"
/>
</label>
{/if}
</div>
</section>
</div>