Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ Foyer is a pure static SvelteKit 5 SPA (`ssr = false`, `prerender = true`, `200.

- **`src/lib/config.ts`**: Runtime `/config.json` parser and loader (`parsePortalConfig`, `loadPortalConfig`, URL scheme sanitization, duplicate-ID filtering). Upstream ships a neutral default in `static/config.json`; fleet deployments inject site inventory via `/config.json`.
- **`src/lib/portal.ts`**: Pure domain logic for bookmark validation/creation, multi-token `⌘K` palette search (`#host`, `@category`, `!network`, `>`), category grouping, health metrics, and Open-Meteo parsing.
- **`src/lib/data/gatus.ts`**: Optional client-side Gatus `/api/v1/endpoints/statuses` health polling and endpoint resolution.
- **`src/lib/components/`**: Svelte 5 runes UI components (`Header`, `WeatherWidget`, `HostBar`, `LayoutToggle`, `BookmarksSection`, `CategorySection`, `ServiceCard`, `CommandPalette`). Modals use native `<dialog>` (`showModal()`).
- **`src/lib/data/gatus.ts`**: Optional client-side Gatus `/api/v1/endpoints/statuses` health polling and endpoint resolution (`fetchGatusSnapshot`: status plus response time, check history and failure reason per endpoint).
- **`src/lib/poll.ts`**: `startPolling`, the visibility-aware poller behind the Gatus and attention-feed refresh; each call owns and aborts its own requests.
- **`src/lib/data/attention.ts`**: The "Needs attention" list: services that are down plus the optional `attentionUrl` JSON feed (`parseAttentionFeed` validates it).
- **`src/lib/components/`**: Svelte 5 runes UI components (`Header`, `WeatherWidget`, `HostBar`, `LayoutToggle`, `BookmarksSection`, `AttentionPanel`, `CategorySection`, `ServiceCard`, `CommandPalette`). Modals use native `<dialog>` (`showModal()`).
- **`test/`**: Hermetic Node `node:test` + Svelte 5 SSR test suite (`test/setup.ts` compiles `.svelte` and `.svelte.js`/`.svelte.ts` on the fly with zero extra npm dependencies).
- **`nix/package.nix`**: `nixpkgs`-compliant `buildNpmPackage` derivation (`fetchNpmDeps`, `strictDeps = true`, `__structuredAttrs = true`, `checkPhase`, `installCheckPhase`, and offline Caddy `passthru.tests.smoke`).

Expand Down
32 changes: 29 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ Foyer compiles to a pure static SPA (`index.html`, `200.html`, `_app/`) with zer
## Features

- **Runtime `/config.json` Catalogue**: Deploy one immutable static build anywhere and mount or serve `/config.json` per environment with strict runtime schema and URL validation.
- **Command Palette (`⌘K` / `/`)**: Multi-token keyboard search across services, pinned bookmarks, and host nodes with `#host`, `@category`, `!network`, and `>` web-search prefixes.
- **Command Palette (`⌘K` / `/`)**: Multi-token keyboard search across services, pinned bookmarks, and host nodes with `#host`, `@category`, `!network`, and `>` web-search prefixes. Matches in the name come first. With `typeToSearch`, typing a letter or digit anywhere on the page opens it.
- **Network Reachability Badges**: Distinct indicators for `public`, `mesh`, and `lan` endpoints plus one-click filter chips.
- **Live Gatus Health**: Optional client-side polling against a [Gatus](https://gatus.io) `/api/v1/endpoints/statuses` endpoint with visibility-aware refresh and stale-data indication.
- **Host Node Bar**: Per-host service counts, one-click host filtering, and IP clipboard copy.
- **Live Gatus Health**: Optional client-side polling against a [Gatus](https://gatus.io) `/api/v1/endpoints/statuses` endpoint with visibility-aware refresh and stale-data indication. Each card shows the response time, the outcome of the last 20 checks, and why a failing check failed; the tab title counts the services that are down.
- **Needs Attention**: A panel that lists every service that is down, plus the items of an optional JSON feed (`attentionUrl`), most severe first. It is hidden when there is nothing to show.
- **Host Node Bar**: Per-host service counts and health, one-click host filtering, and IP clipboard copy.
- **Instant Start**: The last loaded `/config.json` is kept in the browser, so the page renders at once and stays usable when the file cannot be fetched.
- **Shared Pinned Links**: Optional `links` in `/config.json` show the same pinned links to every visitor, ahead of their own bookmarks.
- **Local Quick Bookmarks**: Browser-stored personal links (`localStorage`) in a dedicated native `<dialog>` modal, immediately searchable from `⌘K`.
- **Optional Weather & Clock**: Minute-aligned UTC/local header clock and optional [Open-Meteo](https://open-meteo.com) telemetry widget.
Expand All @@ -25,6 +27,8 @@ Serve a `/config.json` file at the web root alongside Foyer's static assets (an
"subtitle": "Homelab Launchpad",
"gatusUrl": "https://status.example.com",
"searchUrlTemplate": "https://duckduckgo.com/?q=%s",
"typeToSearch": true,
"attentionUrl": "/attention.json",
"weather": {
"latitude": 51.5072,
"longitude": -0.1276,
Expand Down Expand Up @@ -69,6 +73,28 @@ Serve a `/config.json` file at the web root alongside Foyer's static assets (an
}
```

### Attention feed

`attentionUrl` points to a JSON file that anything can write: a cron job, a CI step, a script. Foyer fetches it every five minutes and never sends credentials of its own, so keep tokens in whatever generates the file.

```json
{
"items": [
{
"id": "pr-42",
"title": "Review requested: fix the flux capacitor",
"url": "https://git.example.com/lab/core/pulls/42",
"detail": "Waiting for two days",
"source": "Forgejo",
"severity": "warning",
"updatedAt": "2026-01-15T09:30:00Z"
}
]
}
```

Only `title` is required. `severity` is `critical`, `warning` or `info` (the default). A bare array of items works too; at most 50 items are shown.

## Development

```bash
Expand Down
77 changes: 77 additions & 0 deletions src/lib/components/AttentionPanel.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<script lang="ts">
import { formatRelativeTime } from '../portal';
import type { AttentionItem, AttentionSeverity } from '../types';

const COLLAPSED_COUNT = 5;

let { items }: { items: AttentionItem[] } = $props();

let expanded = $state(false);
let visible = $derived(expanded ? items : items.slice(0, COLLAPSED_COUNT));
let worst = $derived<AttentionSeverity>(
items.some((i) => i.severity === 'critical') ? 'critical'
: items.some((i) => i.severity === 'warning') ? 'warning'
: 'info'
);

const SEVERITY = {
critical: { icon: '🔴', label: 'Critical', border: 'border-status-danger-border', text: 'text-status-danger' },
warning: { icon: '🟠', label: 'Warning', border: 'border-status-warning-border', text: 'text-status-warning' },
info: { icon: '🔵', label: 'Info', border: 'border-line', text: 'text-heading' }
} as const;
</script>

{#if items.length > 0}
<section aria-label="Needs attention" class="p-3.5 rounded-2xl glass-panel shadow-2xs border {SEVERITY[worst].border}">
<div class="flex items-center gap-2 mb-2 px-1">
<h2 class="text-xs font-semibold {SEVERITY[worst].text}">Needs attention</h2>
<span class="text-[10px] font-mono px-1.5 py-0.5 rounded bg-surface-high text-muted">{items.length}</span>
</div>

<ul class="space-y-1">
{#each visible as item (item.id)}
{@const sev = SEVERITY[item.severity]}
{@const when = formatRelativeTime(item.updatedAt)}
<li class="flex items-start gap-2.5 px-2 py-1.5 rounded-xl hover:bg-surface-high/60 transition-colors">
<span class="text-[10px] leading-5 select-none shrink-0" role="img" aria-label={sev.label}>{sev.icon}</span>
<div class="min-w-0 flex-1">
{#if item.url}
<a
href={item.url}
target="_blank"
rel="noopener noreferrer"
class="text-xs font-medium text-heading hover:text-accent hover:underline break-words"
>
{item.title}
</a>
{:else}
<span class="text-xs font-medium text-heading break-words">{item.title}</span>
{/if}
{#if item.detail}
<p class="text-[11px] text-muted font-mono line-clamp-2" title={item.detail}>{item.detail}</p>
{/if}
</div>
<div class="flex items-center gap-2 shrink-0 text-[10px] font-mono text-muted leading-5">
{#if item.source}
<span class="px-1.5 rounded bg-surface-high">{item.source}</span>
{/if}
{#if when}
<time datetime={item.updatedAt}>{when}</time>
{/if}
</div>
</li>
{/each}
</ul>

{#if items.length > COLLAPSED_COUNT}
<button
type="button"
aria-expanded={expanded}
onclick={() => (expanded = !expanded)}
class="mt-1.5 ml-2 text-[11px] font-mono text-accent hover:underline cursor-pointer"
>
{expanded ? 'Show fewer' : `Show ${items.length - COLLAPSED_COUNT} more`}
</button>
{/if}
</section>
{/if}
8 changes: 5 additions & 3 deletions src/lib/components/CategorySection.svelte
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
<script lang="ts">
import { resolveHealth } from '../data/gatus';
import { resolveDetail, resolveHealth } from '../data/gatus';
import { getCategoryIcon } from '../portal';
import type { HealthStatus, LayoutDensity, ServiceItem } from '../types';
import type { EndpointDetail, HealthStatus, LayoutDensity, ServiceItem } from '../types';
import ServiceCard from './ServiceCard.svelte';

let {
category,
services,
healthMap = {},
healthDetails = {},
density = 'comfortable',
categoryIcons
}: {
category: string;
services: ServiceItem[];
healthMap?: Record<string, HealthStatus>;
healthDetails?: Record<string, EndpointDetail>;
density?: LayoutDensity;
categoryIcons?: Record<string, string>;
} = $props();
Expand Down Expand Up @@ -43,7 +45,7 @@
<div class={containerClass}>
{#each services as service (service.id)}
{@const health = resolveHealth(service, healthMap)}
<ServiceCard {service} {health} {density} />
<ServiceCard {service} {health} detail={resolveDetail(service, healthDetails)} {density} />
{/each}
</div>
</section>
Expand Down
47 changes: 30 additions & 17 deletions src/lib/components/CommandPalette.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
buildPaletteEntries,
filterPaletteEntries,
formatWebSearchUrl,
isTypeToSearchKey,
type PaletteEntry
} from '../portal';
import type { HostInfo, PinnedLink, ServiceItem } from '../types';
Expand All @@ -15,13 +16,16 @@
hosts = [],
searchUrlTemplate = DEFAULT_SEARCH_URL_TEMPLATE,
onSelectHost,
typeToSearch = false,
open = $bindable(false)
}: {
services: ServiceItem[];
bookmarks?: PinnedLink[];
hosts?: HostInfo[];
searchUrlTemplate?: string;
onSelectHost?: (hostId: string) => void;
/** Typing a letter or digit anywhere on the page opens the palette with it. */
typeToSearch?: boolean;
open: boolean;
} = $props();

Expand Down Expand Up @@ -111,24 +115,33 @@
}
}

// Keys typed into a field, or while another dialog is open, belong there.
function pageHasKeyboardFocus(): boolean {
const active = document.activeElement as HTMLElement | null;
return (
['INPUT', 'TEXTAREA', 'SELECT'].includes(active?.tagName ?? '') ||
active?.isContentEditable === true ||
document.querySelector('dialog[open]') !== null
);
}

function openWith(initialQuery: string) {
query = initialQuery;
copyNotice = null;
open = true;
}

function handleWindowKeyDown(e: KeyboardEvent) {
if (!open) {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
e.preventDefault();
query = '';
copyNotice = null;
open = true;
} else if (
e.key === '/' &&
!(e.metaKey || e.ctrlKey || e.altKey) &&
!['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement?.tagName ?? '') &&
!(document.activeElement as HTMLElement | null)?.isContentEditable
) {
e.preventDefault();
query = '';
copyNotice = null;
open = true;
}
if (open || e.defaultPrevented) return;
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
e.preventDefault();
openWith('');
} else if (e.key === '/' && !(e.metaKey || e.ctrlKey || e.altKey) && !pageHasKeyboardFocus()) {
e.preventDefault();
openWith('');
} else if (typeToSearch && isTypeToSearchKey(e) && !pageHasKeyboardFocus()) {
e.preventDefault();
openWith(e.key);
}
}

Expand Down
13 changes: 12 additions & 1 deletion src/lib/components/HostBar.svelte
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
<script lang="ts">
import type { HostInfo } from '../types';
import StatusDot from '@kleinbem/web-config/components/StatusDot';
import type { HealthStatus, HostInfo } from '../types';

let {
hosts,
counts = {},
health = {},
selectedHost = $bindable<string | null>(null)
}: {
hosts: HostInfo[];
counts?: Record<string, number>;
/** Worst health among each host's checked services; hosts without checks are absent. */
health?: Record<string, HealthStatus>;
selectedHost?: string | null;
} = $props();

Expand Down Expand Up @@ -77,6 +81,13 @@
<span aria-hidden="true">{host.icon}</span>
{/if}
<span class="truncate">{host.name}</span>
{#if health[host.id]}
<StatusDot
status={health[host.id]}
size="sm"
label={health[host.id] === 'healthy' ? 'All checked services up' : 'Has services that are down'}
/>
{/if}
</span>
<div class="flex items-center gap-1 shrink-0">
{#if host.arch}
Expand Down
45 changes: 41 additions & 4 deletions src/lib/components/ServiceCard.svelte
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
<script lang="ts">
import StatusDot from '@kleinbem/web-config/components/StatusDot';
import type { HealthStatus, LayoutDensity, ServiceItem } from '../types';
import { describeHealth, formatResponseTime } from '../portal';
import type { EndpointDetail, HealthStatus, LayoutDensity, ServiceItem } from '../types';

let {
service,
health = 'unknown',
detail,
density = 'comfortable'
}: {
service: ServiceItem;
health?: HealthStatus;
/** Latest Gatus data for this service: response time, recent checks, failure reason. */
detail?: EndpointDetail;
density?: LayoutDensity;
} = $props();

Expand All @@ -27,6 +31,9 @@

let networkBadge = $derived(NETWORK_BADGES[service.network]);
let displayUrl = $derived(service.url.replace(/^https?:\/\//, ''));
let healthTitle = $derived(describeHealth(health, detail));
let history = $derived(detail && detail.history.length > 1 ? detail.history : []);
let passed = $derived(history.filter(Boolean).length);

async function copyUrl() {
try {
Expand All @@ -51,6 +58,21 @@
</span>
{/snippet}

{#snippet historyBar(cls: string)}
{#if history.length > 0}
<div
class="items-center gap-px {cls}"
role="img"
aria-label="{passed} of {history.length} recent checks passed"
title="{passed} of {history.length} recent checks passed"
>
{#each history as ok, i (i)}
<span class="w-1 h-2.5 rounded-[1px] {ok ? 'bg-status-success/60' : 'bg-status-danger'}"></span>
{/each}
</div>
{/if}
{/snippet}

{#snippet copyBtn(label: string, cls: string)}
<button
type="button"
Expand Down Expand Up @@ -79,7 +101,7 @@
</div>
</a>
<div class="flex items-center gap-1.5 shrink-0">
<StatusDot status={health} />
<StatusDot status={health} title={healthTitle} />
{@render copyBtn(copied ? '✓' : '📋', 'opacity-0 group-hover:opacity-100 focus-visible:opacity-100 text-muted hover:text-heading p-1 rounded transition-opacity text-[10px] font-mono')}
</div>
</div>
Expand All @@ -104,8 +126,12 @@
</div>
</a>
<div class="flex items-center gap-2 shrink-0">
{#if detail?.responseMs !== undefined && health === 'healthy'}
<span class="hidden md:inline text-[10px] font-mono text-muted tabular-nums">{formatResponseTime(detail.responseMs)}</span>
{/if}
{@render historyBar('hidden lg:flex')}
{@render netBadge(true)}
<StatusDot status={health} />
<StatusDot status={health} title={healthTitle} />
{@render copyBtn(copied ? '✓' : '📋', 'text-muted hover:text-heading p-1 rounded transition-colors text-xs font-mono')}
</div>
</div>
Expand All @@ -121,13 +147,24 @@
</div>
</a>
<div class="flex items-center gap-1.5 shrink-0">
<StatusDot status={health} />
<StatusDot status={health} title={healthTitle} />
{@render netBadge(false)}
</div>
</div>
{#if service.description}
<p class="text-xs text-fg line-clamp-2 leading-relaxed">{service.description}</p>
{/if}
{#if health === 'down' && detail?.reason}
<p class="mt-1.5 text-[11px] font-mono text-status-danger line-clamp-2" title={detail.reason}>{detail.reason}</p>
{/if}
{#if history.length > 0}
<div class="mt-2.5 flex items-center justify-between gap-2">
{@render historyBar('flex')}
{#if detail?.responseMs !== undefined && health === 'healthy'}
<span class="text-[10px] font-mono text-muted tabular-nums">{formatResponseTime(detail.responseMs)}</span>
{/if}
</div>
{/if}
</div>
<div class="mt-3 pt-2.5 border-t border-line flex items-center justify-between text-[11px] text-muted font-mono">
<span class="truncate max-w-[200px]">{displayUrl}</span>
Expand Down
Loading
Loading