fix dem bugs

This commit is contained in:
JCEEE
2026-09-15 09:05:13 +01:00
parent f9fa99f5ff
commit 29d50985df
8 changed files with 181 additions and 121 deletions
+1 -5
View File
@@ -1,19 +1,16 @@
<script lang="ts"> <script lang="ts">
import type { Snippet } from 'svelte';
let { let {
announcement = '', announcement = '',
role = '', role = '',
seasons = [], seasons = [],
connected = true, connected = true,
children, children
left
}: { }: {
announcement?: string announcement?: string
role?: string role?: string
seasons?: { id: string; name: string; color: string; active: boolean }[] seasons?: { id: string; name: string; color: string; active: boolean }[]
connected?: boolean connected?: boolean
children?: any children?: any
left?: Snippet
} = $props(); } = $props();
</script> </script>
@@ -22,7 +19,6 @@
{#if role} {#if role}
<span class="role-pill {role}">{role}</span> <span class="role-pill {role}">{role}</span>
{/if} {/if}
{@render left?.()}
<span <span
class="conn-dot" class="conn-dot"
class:up={connected} class:up={connected}
+9 -2
View File
@@ -1,6 +1,7 @@
import { pb } from '$lib/pocketbase'; import { pb } from '$lib/pocketbase';
import type { ChatMessage, TypingRow, MentionMember } from '$lib/types'; import type { ChatMessage, TypingRow, MentionMember } from '$lib/types';
import { addAutoDismissNotice } from './notices.svelte'; import { addAutoDismissNotice } from './notices.svelte';
import { famStore } from './fam.svelte';
interface ChatInit { interface ChatInit {
famId: string; famId: string;
@@ -119,7 +120,10 @@ class ChatStore {
this.onMessage(data.action, data.record); this.onMessage(data.action, data.record);
}) })
.then((unsub) => this.unsubs.push(unsub)) .then((unsub) => this.unsubs.push(unsub))
.catch((err: Error) => console.error('[chatStore] messages subscribe failed:', err)); .catch((err: Error) => {
console.error('[chatStore] messages subscribe failed:', err);
famStore.connectionDown = true;
});
const typingSub = pb const typingSub = pb
.collection('chat_typing') .collection('chat_typing')
@@ -128,7 +132,10 @@ class ChatStore {
this.onTyping(data.action, data.record); this.onTyping(data.action, data.record);
}) })
.then((unsub) => this.unsubs.push(unsub)) .then((unsub) => this.unsubs.push(unsub))
.catch((err: Error) => console.error('[chatStore] typing subscribe failed:', err)); .catch((err: Error) => {
console.error('[chatStore] typing subscribe failed:', err);
famStore.connectionDown = true;
});
await Promise.allSettled([msgSub, typingSub]); await Promise.allSettled([msgSub, typingSub]);
} }
+13 -3
View File
@@ -203,8 +203,11 @@ class FamStore {
this.bonusTemplates = bonusTemplatesRes; this.bonusTemplates = bonusTemplatesRes;
this.rewards = rewardsRes; this.rewards = rewardsRes;
this.seasons = seasonsRes; this.seasons = seasonsRes;
// A completed resync proves the pipe is healthy again.
this.connectionDown = false;
} catch (e) { } catch (e) {
console.error('FamStore.resync failed:', e); console.error('FamStore.resync failed:', e);
if (!this.destroyed) this.connectionDown = true;
} finally { } finally {
this.resyncing = false; this.resyncing = false;
} }
@@ -228,7 +231,10 @@ class FamStore {
.then((unsub) => { .then((unsub) => {
this.connWatchers.push(unsub); this.connWatchers.push(unsub);
}) })
.catch(() => {}); .catch(() => {
// We never even got the connect signal — surface it.
if (!this.destroyed) this.connectionDown = true;
});
const onDisc = pb.realtime.onDisconnect; const onDisc = pb.realtime.onDisconnect;
pb.realtime.onDisconnect = (active: string[]) => { pb.realtime.onDisconnect = (active: string[]) => {
try { try {
@@ -238,9 +244,10 @@ class FamStore {
if (active.length > 0 && !this.destroyed) this.connectionDown = true; if (active.length > 0 && !this.destroyed) this.connectionDown = true;
}; };
// Browser-level: sleep/wake and offline/online can kill SSE without the // Browser-level: sleep/wake and offline/online can kill SSE without the
// SDK noticing promptly — resync when the network/tab comes back. // SDK noticing promptly. Don't touch the flag here — resync() sets it
// from the actual outcome (clearing it early is what left the dot
// green while the console showed errors).
const onOnline = () => { const onOnline = () => {
this.connectionDown = false;
this.resync().catch(() => {}); this.resync().catch(() => {});
}; };
const onVisible = () => { const onVisible = () => {
@@ -284,6 +291,9 @@ class FamStore {
}) })
.catch((err: Error) => { .catch((err: Error) => {
console.error(`[famStore] subscribe failed for ${collection}:`, err); console.error(`[famStore] subscribe failed for ${collection}:`, err);
// A failed subscribe IS the outage the console shows while
// the dot stayed green — flag it; PB_CONNECT/resync clears it.
if (!this.destroyed) this.connectionDown = true;
}); });
}); });
@@ -0,0 +1,60 @@
import { isSharedDevice, setSharedDevice } from '$lib/client/shared-device';
import { notices } from './notices.svelte';
// Per-device shared-computer mode (NOT a fam setting — see
// lib/client/shared-device.ts). One reactive home for the flag so the fam
// layout (switcher + idle-lock gating) and the dashboard hero toggle stay in
// sync. Anyone holding the device can flip it; the server sees the cookie
// mirror as data.sharedDevice.
class SharedDeviceStore {
on = $state(
typeof localStorage !== 'undefined' ? isSharedDevice() : false
);
async toggle() {
this.on = !this.on;
setSharedDevice(this.on);
if (!this.on) return;
// Just enabled — remind about PIN state. Kids without a PIN can't be
// picked until one is set (picker shows "ask a parent"); kids with one
// get a nudge to remember it. Values never exposed — only set/unset.
try {
const res = await fetch('/api/pins/status');
if (!res.ok) throw new Error();
const s = await res.json();
if (Array.isArray(s.children)) {
// Parent view: roster of who still needs a PIN.
const missing = s.children.filter((c: any) => !c.hasPin).map((c: any) => c.name);
const ready = s.children.filter((c: any) => c.hasPin).map((c: any) => c.name);
if (missing.length > 0) {
notices.warning(
'Shared mode on',
`Still need a PIN: ${missing.join(', ')} (set in Settings → Members).` +
(ready.length > 0 ? ` Ready: ${ready.join(', ')}.` : '')
);
} else {
notices.success(
'Shared mode on',
`PINs ready for ${ready.length > 0 ? ready.join(', ') : 'everyone'}. Remind the kids!`
);
}
} else if (typeof s.hasPin === 'boolean') {
// Child view: only their own state.
if (s.hasPin) {
notices.success('Shared mode on', 'Remember your 3-digit PIN to switch back in!');
} else {
notices.warning(
'Shared mode on',
'You need a PIN first. Ask a parent to set one up.'
);
}
} else {
notices.info('Shared mode on', 'This computer now uses profile PINs.');
}
} catch {
notices.info('Shared mode on', 'This computer now uses profile PINs.');
}
}
}
export const sharedDevice = new SharedDeviceStore();
+10 -2
View File
@@ -20,7 +20,11 @@ import {
PawPrint, PawPrint,
Guitar, Guitar,
Medal, Medal,
Wrench Wrench,
PenLine,
SprayCan,
Droplets,
CookingPot
} from '@lucide/svelte'; } from '@lucide/svelte';
export const ICON_MAP: Record<string, any> = { export const ICON_MAP: Record<string, any> = {
@@ -45,7 +49,11 @@ export const ICON_MAP: Record<string, any> = {
PawPrint, PawPrint,
Guitar, Guitar,
Medal, Medal,
Wrench Wrench,
PenLine,
SprayCan,
Droplets,
CookingPot
}; };
export const ICON_NAMES = Object.keys(ICON_MAP); export const ICON_NAMES = Object.keys(ICON_MAP);
+4 -101
View File
@@ -7,10 +7,10 @@
import { chatStore } from '$lib/stores/chat.svelte'; import { chatStore } from '$lib/stores/chat.svelte';
import { notices } from '$lib/stores/notices.svelte'; import { notices } from '$lib/stores/notices.svelte';
import { Sidebar, TopNav, Footer, Chat, SharedPicker } from '$lib/components'; import { Sidebar, TopNav, Footer, Chat, SharedPicker } from '$lib/components';
import { chatIcon, monitorIcon } from '$lib/components/icons'; import { chatIcon } from '$lib/components/icons';
import { recordShortcut } from '$lib/shortcut'; import { recordShortcut } from '$lib/shortcut';
import { installLockTracking, lockDue } from '$lib/client/lock'; import { installLockTracking, lockDue } from '$lib/client/lock';
import { isSharedDevice, setSharedDevice } from '$lib/client/shared-device'; import { sharedDevice } from '$lib/stores/shared-device.svelte';
import { themeShades } from '$lib/theme'; import { themeShades } from '$lib/theme';
import '$lib/theme-patterns.css'; import '$lib/theme-patterns.css';
import { themeDraft } from '$lib/stores/theme.svelte'; import { themeDraft } from '$lib/stores/theme.svelte';
@@ -44,59 +44,13 @@
.map((m: any) => ({ id: m.id, name: m.name, color: m.color, username: m.username })) .map((m: any) => ({ id: m.id, name: m.name, color: m.color, username: m.username }))
); );
// Shared-computer mode (per-device flag, NOT a fam setting — see
// lib/client/shared-device.ts). Makes the PIN system functional on this
// browser: profile switcher + idle lock. Anyone logged in (or not) can
// flip it; server sees the cookie mirror as data.sharedDevice.
let sharedOn = $state(
typeof localStorage !== 'undefined' ? isSharedDevice() : !!(data as any).sharedDevice
);
let sharedToast = $state('');
async function toggleShared() {
sharedOn = !sharedOn;
setSharedDevice(sharedOn);
if (!sharedOn) {
sharedToast = '';
return;
}
// Just enabled — remind about PIN state. Kids without a PIN can't be
// picked until one is set (picker shows "ask a parent"); kids with one
// get a nudge to remember it. Values never exposed — only set/unset.
try {
const res = await fetch('/api/pins/status');
if (!res.ok) throw new Error();
const s = await res.json();
if (Array.isArray(s.children)) {
// Parent view: roster of who still needs a PIN.
const missing = s.children.filter((c: any) => !c.hasPin).map((c: any) => c.name);
const ready = s.children.filter((c: any) => c.hasPin).map((c: any) => c.name);
sharedToast =
missing.length > 0
? `Shared mode on — still need a PIN: ${missing.join(', ')} (set in Settings → Members).` +
(ready.length > 0 ? ` Ready: ${ready.join(', ')}.` : '')
: `Shared mode on — PINs ready for ${ready.length > 0 ? ready.join(', ') : 'everyone'}. Remind the kids!`;
} else if (typeof s.hasPin === 'boolean') {
// Child view: only their own state.
sharedToast = s.hasPin
? 'Shared mode on — remember your 3-digit PIN to switch back in!'
: 'Shared mode on — you need a PIN first. Ask a parent to set one up.';
} else {
sharedToast = 'Shared mode on for this computer.';
}
} catch {
sharedToast = 'Shared mode on for this computer.';
}
setTimeout(() => (sharedToast = ''), 8000);
}
// Idle lock (children on shared devices only): return to the picker after // Idle lock (children on shared devices only): return to the picker after
// `lockMins` of no interaction. localStorage-backed (see lib/client/lock.ts) // `lockMins` of no interaction. localStorage-backed (see lib/client/lock.ts)
// so a closed browser still trips the lock on next launch. // so a closed browser still trips the lock on next launch.
$effect(() => { $effect(() => {
const isChild = data.session?.role === 'child'; const isChild = data.session?.role === 'child';
const lockMins = Number(data.lockMins) || 0; const lockMins = Number(data.lockMins) || 0;
if (!isChild || !sharedOn || lockMins <= 0 || data.picker) return; if (!isChild || !sharedDevice.on || lockMins <= 0 || data.picker) return;
installLockTracking(); installLockTracking();
if (lockDue(lockMins)) pickerOpen = true; if (lockDue(lockMins)) pickerOpen = true;
if (!lockTimer) { if (!lockTimer) {
@@ -306,25 +260,13 @@
announcement={disabled && !activating ? accessMessage(accessReason, isParent) : ''} announcement={disabled && !activating ? accessMessage(accessReason, isParent) : ''}
connected={!famStore.connectionDown} connected={!famStore.connectionDown}
> >
{#snippet left()}
<button
class="shared-toggle"
class:on={sharedOn}
onclick={toggleShared}
aria-label="Toggle shared computer mode"
aria-pressed={sharedOn}
title={sharedOn ? 'Shared computer mode is ON' : 'Mark this as a shared computer'}
>
{@html monitorIcon}
</button>
{/snippet}
<button class="chat-toggle" onclick={() => chatStore.toggle()} aria-label="Open chat"> <button class="chat-toggle" onclick={() => chatStore.toggle()} aria-label="Open chat">
{@html chatIcon} {@html chatIcon}
{#if chatStore.unread > 0} {#if chatStore.unread > 0}
<span class="chat-badge">{chatStore.unread > 9 ? '9+' : chatStore.unread}</span> <span class="chat-badge">{chatStore.unread > 9 ? '9+' : chatStore.unread}</span>
{/if} {/if}
</button> </button>
{#if data.session && sharedOn && (data.deviceChildIds?.length || 0) > 0} {#if data.session && sharedDevice.on && (data.deviceChildIds?.length || 0) > 0}
<button <button
class="kid-switch" class="kid-switch"
onclick={() => (pickerOpen = true)} onclick={() => (pickerOpen = true)}
@@ -370,9 +312,6 @@
{claimToast} — view dashboard → {claimToast} — view dashboard →
</a> </a>
{/if} {/if}
{#if sharedToast}
<div class="shared-toast" role="status">{sharedToast}</div>
{/if}
<Footer sidebar /> <Footer sidebar />
</div> </div>
{#if chatStore.open} {#if chatStore.open}
@@ -578,42 +517,6 @@
border: 2px solid #fff; border: 2px solid #fff;
box-shadow: 0 0 0 1px #e2e8f0; box-shadow: 0 0 0 1px #e2e8f0;
} }
.shared-toggle {
width: 40px;
height: 40px;
border: none;
border-radius: 10px;
background: #f3f4f6;
color: #9ca3af;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
.shared-toggle:hover {
background: #e5e7eb;
}
.shared-toggle.on {
background: #6366f1;
color: #fff;
box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.25);
}
.shared-toast {
position: fixed;
bottom: 1rem;
left: 50%;
transform: translateX(-50%);
background: #1f2937;
color: #fff;
padding: 0.6rem 1.2rem;
border-radius: 12px;
font-size: 0.85rem;
font-weight: 600;
z-index: 96;
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.3);
max-width: min(92vw, 560px);
text-align: center;
}
.picker-stage { .picker-stage {
min-height: 100vh; min-height: 100vh;
width: 100%; width: 100%;
+62 -2
View File
@@ -5,11 +5,28 @@
import { ViewHeader, CardGrid, Card } from '$lib/components'; import { ViewHeader, CardGrid, Card } from '$lib/components';
import { formatDDMMYY } from '$lib/format'; import { formatDDMMYY } from '$lib/format';
import { famStore } from '$lib/stores/fam.svelte'; import { famStore } from '$lib/stores/fam.svelte';
import { sharedDevice } from '$lib/stores/shared-device.svelte';
import { monitorIcon } from '$lib/components/icons';
import { handleOf } from '@shared/slugify'; import { handleOf } from '@shared/slugify';
import { addDaysStr, resolveTz, todayInTz } from '@shared/timezone'; import { addDaysStr, resolveTz, todayInTz } from '@shared/timezone';
Chart.register(...registerables); Chart.register(...registerables);
// Time-of-day greeting, picked once per load (not a ticking clock).
const GREETINGS: { from: number; to: number; lines: string[] }[] = [
{ from: 5, to: 12, lines: ['Good morning', 'Rise and shine', 'Morning, crew'] },
{ from: 12, to: 17, lines: ['Good afternoon', 'Back on it', 'Afternoon push'] },
{ from: 17, to: 22, lines: ['Good evening', 'Welcome back', 'Evening shift'] },
{ from: 22, to: 29, lines: ['Night owls', 'Still at it', 'Burning the midnight oil'] }
];
let greeting = $state(
(() => {
const h = new Date().getHours();
const band = GREETINGS.find((g) => (h >= g.from && h < g.to) || (g.to > 24 && h < g.to - 24)) || GREETINGS[0];
return band.lines[Math.floor(Math.random() * band.lines.length)];
})()
);
let { data } = $props(); let { data } = $props();
let famSlug = $derived(page.data.famSlug ?? page.params.fam); let famSlug = $derived(page.data.famSlug ?? page.params.fam);
@@ -314,8 +331,8 @@
</script> </script>
<ViewHeader <ViewHeader
title={page.data.fam?.name || famSlug} title={greeting}
subtitle={summary?.weekStart ? `Week of ${formatDDMMYY(summary.weekStart)}` : 'Dashboard'} subtitle={`${page.data.fam?.name || famSlug}${summary?.weekStart ? ` · Week of ${formatDDMMYY(summary.weekStart)}` : ''}`}
hero hero
> >
<!-- All-time family totals, large in the header --> <!-- All-time family totals, large in the header -->
@@ -329,6 +346,19 @@
<span class="vh-lbl">cash earned all time</span> <span class="vh-lbl">cash earned all time</span>
</span> </span>
</div> </div>
<!-- Shared-computer toggle, bottom-left of the hero -->
<div class="vh-foot">
<button
class="shared-hero-toggle"
class:on={sharedDevice.on}
onclick={() => sharedDevice.toggle()}
aria-pressed={sharedDevice.on}
title={sharedDevice.on ? 'Shared computer mode is ON' : 'Mark this as a shared computer'}
>
{@html monitorIcon}
<span>Shared computer {sharedDevice.on ? '· On' : '· Off'}</span>
</button>
</div>
</ViewHeader> </ViewHeader>
<!-- STAT TILES --> <!-- STAT TILES -->
@@ -496,6 +526,36 @@
letter-spacing: 0.08em; letter-spacing: 0.08em;
opacity: 0.85; opacity: 0.85;
} }
/* Shared-computer toggle row, bottom-left of the hero */
.vh-foot {
flex: 1 1 100%;
display: flex;
justify-content: flex-start;
margin-top: 0.75rem;
}
.shared-hero-toggle {
display: inline-flex;
align-items: center;
gap: 0.45rem;
background: rgba(255, 255, 255, 0.16);
color: rgba(255, 255, 255, 0.9);
border: 1px solid rgba(255, 255, 255, 0.35);
border-radius: 999px;
padding: 0.4rem 0.95rem;
font-size: 0.8rem;
font-weight: 700;
cursor: pointer;
}
.shared-hero-toggle:hover {
background: rgba(255, 255, 255, 0.28);
color: #fff;
}
.shared-hero-toggle.on {
background: #fff;
color: #4338ca;
border-color: transparent;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
/* ── Chores card totals ── */ /* ── Chores card totals ── */
.chores-totals { .chores-totals {
@@ -242,10 +242,11 @@
showTodoModal = true; showTodoModal = true;
} }
function openCreateChore() { function openCreateChore(memberId = '') {
assignModal = { t: null as any, memberId: members[0]?.id || '' }; const target = memberId || members[0]?.id || '';
assignModal = { t: null as any, memberId: target };
assignStep = 1; assignStep = 1;
assignTarget = 'member'; assignTarget = target ? 'member' : 'shared';
assignName = ''; assignName = '';
assignDescription = ''; assignDescription = '';
assignColor = ''; assignColor = '';
@@ -390,12 +391,14 @@
{/if} {/if}
<CardGrid stackTablet> <CardGrid stackTablet>
<!-- Templates Section (at top, like bonuses) --> <!-- Templates Section (at top, like bonuses). Desktop only — dragging
<Card cols={3}> needs pointer precision; below desktop each member card gets its own
"Create a chore" button instead. -->
<Card cols={3} class="chores-templates-card">
<div class="template-section"> <div class="template-section">
<div class="template-header"> <div class="template-header">
<h3>Templates — Drag to assign</h3> <h3>Templates — Drag to assign</h3>
<button class="add-inline" onclick={openCreateChore}>+ Create a chore</button> <button class="add-inline" onclick={() => openCreateChore()}>+ Create a chore</button>
</div> </div>
<div class="template-list"> <div class="template-list">
{#each templates as t} {#each templates as t}
@@ -607,6 +610,9 @@
{#if assignedForMember(m.id).length === 0} {#if assignedForMember(m.id).length === 0}
<p class="empty">Drop a chore here</p> <p class="empty">Drop a chore here</p>
{/if} {/if}
<button class="add-inline accordion-add" onclick={() => openCreateChore(m.id)}
>+ Create a chore</button
>
</div> </div>
{/if} {/if}
</div> </div>
@@ -690,6 +696,9 @@
{:else} {:else}
<p class="empty">Drop a chore here</p> <p class="empty">Drop a chore here</p>
{/each} {/each}
<button class="add-inline accordion-add" onclick={() => openCreateChore('')}
>+ Create a chore</button
>
</div> </div>
{/if} {/if}
</div> </div>
@@ -1193,6 +1202,12 @@
.template-list .card.template { .template-list .card.template {
width: 100%; width: 100%;
} }
/* Below desktop there's no drag-and-drop — hide the templates strip
(each member/shared card carries its own Create button instead).
:global because the class lives on the Card component's root. */
:global(.chores-templates-card) {
display: none;
}
} }
/* ── Kanban (3 columns, scrolls via Card scrollX) ── */ /* ── Kanban (3 columns, scrolls via Card scrollX) ── */
.kanban { .kanban {
@@ -1266,6 +1281,7 @@
.add-inline:hover { .add-inline:hover {
border-color: #6366f1; border-color: #6366f1;
background: #eef2ff; background: #eef2ff;
color: #4338ca;
} }
.card { .card {