aboutsummaryrefslogtreecommitdiff
path: root/frontend/src/routes/+page.svelte
blob: 6a57fd4607798395dc0a8fff7fdeec5f5a33cfe2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
<script lang="ts">
	import { onMount, tick } from 'svelte';
	import { deleteService } from '$lib/api';
	import ServiceCard from '$lib/components/ServiceCard.svelte';
	import AddServiceModal from '$lib/components/AddServiceModal.svelte';
	import ActivityLog from '$lib/components/ActivityLog.svelte';
	import { subscribeHeartbeats } from '$lib/realtime';
	import type { Service, Heartbeat } from '$lib/types';

	import type { InitialLogEntry } from './+page.ts';

	let { data } = $props<{
		data: { services: (Service & { heartbeats: Heartbeat[] })[]; error: string; initialLog: InitialLogEntry[] };
	}>();

	let initialized = $state(false);
	let services = $state<(Service & { heartbeats: Heartbeat[] })[]>([]);
	let error = $state('');
	let showModal = $state(false);

	let isKiosk = $state(false);
	let kioskFloating = $state(false);
	let kioskTimer: ReturnType<typeof setTimeout> | undefined;
	let wakeLock: WakeLockSentinel | null = $state(null);
	let pulseId = $state(0);

	$effect(() => {
		if (!initialized && data) {
			services = [...data.services];
			error = data.error;
			initialized = true;
		}
	});

	interface LogEntry {
		kind: 'check' | 'created' | 'deleted' | 'transition';
		serviceName: string;
		serviceUrl: string;
		timestamp: Date;
		hb?: Heartbeat;
		wasUp?: boolean;
	}

	let logEntries = $state<LogEntry[]>([]);

	$effect(() => {
		if (data?.initialLog && logEntries.length === 0) {
			logEntries = data.initialLog.map((e) => ({ ...e, timestamp: new Date(e.timestamp) }));
		}
	});

	function pushEntry(entry: LogEntry) {
		logEntries = [...logEntries, entry];
		if (logEntries.length > 200) {
			logEntries = logEntries.slice(-150);
		}
	}

	function handleCreated(svc: Service) {
		services = [{ ...svc, heartbeats: [] }, ...services];
		pushEntry({
			kind: 'created',
			serviceName: svc.name,
			serviceUrl: svc.url,
			timestamp: new Date()
		});
	}

	async function handleDeleted(id: number) {
		const svc = services.find((s) => s.id === id);
		try {
			await deleteService(id);
			services = services.filter((s) => s.id !== id);
			if (svc) {
				pushEntry({
					kind: 'deleted',
					serviceName: svc.name,
					serviceUrl: svc.url,
					timestamp: new Date()
				});
			}
		} catch {
			// silent
		}
	}

	function toggleKiosk() {
		isKiosk = !isKiosk;
		requestAnimationFrame(() => {
			if (isKiosk) {
				document.documentElement.classList.add('kiosk-mode');
				requestWakeLock();
			} else {
				document.documentElement.classList.remove('kiosk-mode');
				releaseWakeLock();
				kioskFloating = false;
			}
		});
	}

	async function requestWakeLock() {
		try {
			if ('wakeLock' in navigator) {
				wakeLock = await navigator.wakeLock.request('screen');
				wakeLock.addEventListener('release', () => { wakeLock = null; });
			}
		} catch { /* wake lock not available */ }
	}

	function releaseWakeLock() {
		if (wakeLock) {
			wakeLock.release();
			wakeLock = null;
		}
	}

	function handleKioskMouseMove() {
		if (!isKiosk) return;
		kioskFloating = true;
		clearTimeout(kioskTimer);
		kioskTimer = setTimeout(() => { kioskFloating = false; }, 3000);
	}

	onMount(() => {
		const unsub = subscribeHeartbeats((hb) => {
			let wasUp: boolean | undefined;
			let changed = false;
			services = services.map((s) => {
				if (s.id !== hb.service_id) return s;
				if (s.last_heartbeat) {
					wasUp = s.last_heartbeat.is_up;
				}
				changed = true;
				return {
					...s,
					last_heartbeat: hb,
					heartbeats: [...s.heartbeats, hb].slice(-30)
				};
			});
			if (changed) pulseId += 1;

			const svc = services.find((s) => s.id === hb.service_id);
			if (!svc) return;

			const kind = wasUp !== undefined && wasUp !== hb.is_up ? 'transition' : 'check';
			pushEntry({
				kind,
				serviceName: svc.name,
				serviceUrl: svc.url,
				timestamp: new Date(),
				hb,
				wasUp
			});
		});
		return unsub;
	});
</script>

<svelte:head>
	<title>YAUM — Yet Another Uptime Monitor</title>
</svelte:head>

<div class="mb-8 flex items-start justify-between" class:kiosk-hidden={isKiosk}>
	<div>
		<h1 class="text-2xl font-semibold tracking-tight text-white">Dashboard</h1>
		<p class="mt-1 text-sm text-[var(--text-muted)]">Status dos serviços monitorados</p>
	</div>
	<button
		onclick={toggleKiosk}
		class="kiosk-hidden shrink-0 rounded-xl border border-[var(--border-color)] bg-[var(--bg-card)] px-3.5 py-2 text-xs font-medium text-[var(--text-muted)] transition-all hover:border-[var(--green)]/30 hover:text-[var(--green)]"
		title="Modo TV — tela cheia para monitores de parede"
	>
		<svg class="-ml-0.5 mr-1.5 inline h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
			<path stroke-linecap="round" stroke-linejoin="round" d="M9 17.25v1.007a3 3 0 01-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0115 18.257V17.25m6-12V15a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 15V5.25A2.25 2.25 0 015.25 3h13.5A2.25 2.25 0 0121 5.25z" />
		</svg>
		Modo TV
	</button>
</div>

<!-- Floating exit button (kiosk only) -->
{#if isKiosk}
	<button
		onclick={toggleKiosk}
		class="fixed bottom-6 right-6 z-50 rounded-xl border border-white/10 bg-black/60 px-4 py-2.5 text-xs font-medium text-white/70 backdrop-blur-sm transition-all duration-300 hover:bg-black/80 hover:text-white"
		class:opacity-0={!kioskFloating}
		class:opacity-100={kioskFloating}
		class:pointer-events-none={!kioskFloating}
	>
		Sair do Modo TV
	</button>
{/if}

<!-- eslint-disable-next-line svelte/no-reactive-reassign -->
<div onmousemove={handleKioskMouseMove} role="region" class:kiosk-active={isKiosk} class:pulse={pulseId > 0} data-pulse={pulseId}>
{#if error}
	<div class="rounded-2xl border border-[var(--red)]/20 bg-[var(--red)]/5 p-8 text-center">
		<svg class="mx-auto mb-3 h-8 w-8 text-[var(--red)]/60" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
			<path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z" />
		</svg>
		<p class="text-sm text-[var(--red)]">{error}</p>
		<button
			onclick={() => location.reload()}
			class="mt-4 text-xs font-medium text-[var(--text-muted)] underline underline-offset-2 transition-colors hover:text-white"
		>
			Tentar novamente
		</button>
	</div>
{:else if services.length === 0}
	<div class="rounded-2xl border border-dashed border-[var(--border-color)] p-16 text-center">
		<div class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-xl bg-[var(--bg-card)]">
			<svg class="h-6 w-6 text-[var(--text-muted)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
				<path stroke-linecap="round" stroke-linejoin="round" d="M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z" />
			</svg>
		</div>
		<p class="text-sm font-medium text-[var(--text-secondary)]">Nenhum serviço sendo monitorado</p>
		<p class="mt-1 text-xs text-[var(--text-muted)]">Adicione o primeiro serviço para começar</p>
		<button
			onclick={() => (showModal = true)}
			class="mt-6 rounded-xl border border-[var(--green)]/30 bg-[var(--green)]/5 px-5 py-2 text-sm font-medium text-[var(--green)] transition-all hover:bg-[var(--green)]/10"
		>
			+ Adicionar Serviço
		</button>
	</div>
{:else}
	{#each [...new Set(services.map((s) => s.group_name || 'Geral'))].sort() as group}
		<div class="mb-8">
			<h2 class="mb-4 text-xs font-semibold uppercase tracking-wider text-[var(--text-secondary)]">{group}</h2>
			<div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
				{#each services.filter((s) => (s.group_name || 'Geral') === group) as svc (svc.id)}
					<ServiceCard service={svc} heartbeats={svc.heartbeats} ondeleted={handleDeleted} />
				{/each}
			</div>
		</div>
	{/each}

	<div class="mt-8">
		<ActivityLog entries={logEntries} />
	</div>
{/if}
</div>

<AddServiceModal
	show={showModal}
	onclose={() => (showModal = false)}
	oncreated={handleCreated}
/>