Merge pull request 'development' (#13) from development into main
All checks were successful
Build Docker image / build (push) Successful in 1m9s
Build Docker image / deploy (push) Successful in 2s
Build Docker image / verify (push) Successful in 26s

Reviewed-on: #13
This commit is contained in:
2025-06-29 17:17:20 +02:00
11 changed files with 468 additions and 167 deletions

View File

@@ -1,16 +1,26 @@
<script lang="ts">
import { onMount } from 'svelte';
import SingleEvent from './SingleEvent.svelte';
let { data } = $props();
let events: any[] = $state([]);
let archived_events: any[] = $state([]);
let loading = $state(true);
onMount(async () => {
const { data: evs } = await data.supabase
.from('events')
.select('*')
.select('id, name, date')
.order('date', { ascending: false });
const { data: aevs } = await data.supabase
.from('events_archived')
.select('id, name, date')
.order('date', { ascending: false });
events = evs || [];
archived_events = aevs || [];
loading = false;
});
</script>
@@ -28,15 +38,10 @@
{/each}
{:else}
{#each events as event}
<a
href={`/private/events/event?id=${event.id}`}
class="block border border-gray-300 rounded bg-white p-4 shadow-none transition cursor-pointer hover:border-blue-500 group min-h-[72px] h-full w-full"
>
<div class="flex flex-col gap-1">
<span class="font-semibold text-lg text-black-700 group-hover:underline">{event.name}</span>
<span class="text-gray-500 text-sm">{event.date}</span>
</div>
</a>
<SingleEvent id={event.id} name={event.name} date={event.date} archived={false} />
{/each}
{#each archived_events as event}
<SingleEvent id={event.id} name={event.name} date={event.date} archived={true} />
{/each}
{/if}
</div>

View File

@@ -0,0 +1,19 @@
<script lang="ts">
const { id, name, date, archived = false } = $props();
</script>
<a
href={archived ? `/private/events/archived?id=${id}` : `/private/events/event?id=${id}`}
class="block border border-gray-300 rounded bg-white p-4 shadow-none transition cursor-pointer hover:border-blue-500 group min-h-[72px] h-full w-full"
aria-label={archived ? `View archived event ${name}` : `View event ${name}`}
>
<div class="flex flex-col gap-1">
<span class="font-semibold text-lg text-black-700 group-hover:underline flex items-center gap-2">
{#if archived}
<svg class="inline w-5 h-5 text-gray-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="8" width="16" height="10" rx="2" stroke="currentColor" stroke-width="2" fill="none"/><path d="M8 8V6a4 4 0 1 1 8 0v2" stroke="currentColor" stroke-width="2" fill="none"/></svg>
{/if}
{name}
</span>
<span class="text-gray-500 text-sm">{date}</span>
</div>
</a>

View File

@@ -0,0 +1,75 @@
<script lang="ts">
import { onMount } from 'svelte';
let { data } = $props();
let event_data = $state();
let loading = $state(true);
onMount(async () => {
const event_id = new URLSearchParams(window.location.search).get('id');
if (!event_id) {
loading = false;
return;
}
const { data: event } = await data.supabase
.from('events_archived')
.select('*')
.eq('id', event_id)
.single();
event_data = event;
loading = false;
});
</script>
<h1 class="mt-2 mb-4 text-center text-2xl font-bold">Archived Event Overview</h1>
<div class="mb-2 rounded border border-gray-300 bg-white p-4">
<div class="flex flex-col gap-1">
{#if loading}
<div class="h-6 w-40 bg-gray-200 rounded animate-pulse mb-2"></div>
<div class="h-4 w-24 bg-gray-100 rounded animate-pulse"></div>
{:else}
<span class="text-black-700 text-lg font-semibold">{event_data?.name}</span>
<span class="text-black-500 text-sm">{event_data?.date}</span>
{/if}
</div>
</div>
<div class="mb-2 flex items-center rounded border border-gray-300 bg-white p-4">
<div class="flex flex-1 items-center justify-center gap-2">
<svg
class="inline h-4 w-4 text-blue-600"
fill="none"
stroke="currentColor"
stroke-width="2"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none" />
</svg>
{#if loading}
<div class="h-4 w-20 bg-gray-200 rounded animate-pulse"></div>
{:else}
<span class="text-sm text-gray-700">Total participants ({event_data?.total_participants})</span>
{/if}
</div>
<div class="mx-4 h-8 w-px bg-gray-300"></div>
<div class="flex flex-1 items-center justify-center gap-2">
<svg
class="inline h-4 w-4 text-green-600"
fill="none"
stroke="currentColor"
stroke-width="2"
viewBox="0 0 24 24"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
</svg>
{#if loading}
<div class="h-4 w-28 bg-gray-200 rounded animate-pulse"></div>
{:else}
<span class="text-sm text-gray-700">Scanned participants ({event_data?.scanned_participants})</span>
{/if}
</div>
</div>

View File

@@ -1,94 +1,129 @@
<script lang="ts">
import StepConnectGoogle from "./steps/StepConnectGoogle.svelte";
import StepCraftEmail from "./steps/StepCraftEmail.svelte";
import StepCreateEvent from "./steps/StepCreateEvent.svelte";
import StepOverview from "./steps/StepOverview.svelte";
import StepUploadParticipants from "./steps/StepUploadParticipants.svelte";
import StepConnectGoogle from './steps/StepConnectGoogle.svelte';
import StepCraftEmail from './steps/StepCraftEmail.svelte';
import StepCreateEvent from './steps/StepCreateEvent.svelte';
import StepOverview from './steps/StepOverview.svelte';
import StepUploadParticipants from './steps/StepUploadParticipants.svelte';
import { onMount } from 'svelte';
import { page } from '$app/state';
let { data, form } = $props();
let { data, form } = $props();
let event = $state({});
let participants = $state([]);
let email = $state({'body': '', 'subject': ''});
let authorized = $state(false);
let event = $state({});
let participants = $state([]);
let email = $state({ body: '', subject: '' });
let authorized = $state(false);
let existingEventId = $state(null);
let isAddingParticipants = $state(false);
$effect(() => {
if (form && form.event) {
event = form.event;
}
if (form && form.participants) {
participants = form.participants;
}
});
onMount(async () => {
const eventId = page.url.searchParams.get('id');
if (eventId) {
existingEventId = eventId;
isAddingParticipants = true;
// Array of step components in order
const steps = [
StepConnectGoogle,
StepCreateEvent,
StepUploadParticipants,
StepCraftEmail,
StepOverview
];
// Fetch existing event data to prefill the form
const { data: existingEvent } = await data.supabase
.from('events')
.select('*')
.eq('id', eventId)
.single();
let step: number = $state(0);
if (existingEvent) {
event = {
name: existingEvent.name,
date: existingEvent.date,
id: existingEvent.id
};
}
}
});
// let stepConditions = $derived([
// authorized,
// !!new_event?.name,
// !!participants?.length,
// !!subject && !!body
// ]);
$effect(() => {
if (form && form.event) {
event = form.event;
}
if (form && form.participants) {
participants = form.participants;
}
});
// for debugging purpouses
let stepConditions = [
true,
true,
true,
true
];
// Array of step components in order
const steps = [
StepConnectGoogle,
StepCreateEvent,
StepUploadParticipants,
StepCraftEmail,
StepOverview
];
function nextStep() {
if (step < steps.length - 1) step += 1;
}
function prevStep() {
if (step > 0) step -= 1;
}
let step: number = $state(0);
let stepConditions = $derived([
authorized,
!!event?.name,
!!participants?.length,
!!email.subject
]);
function nextStep() {
if (step < steps.length - 1) step += 1;
}
function prevStep() {
if (step > 0) step -= 1;
}
</script>
<div class="flex items-center justify-between mb-4 mt-2">
<button
onclick={prevStep}
disabled={step === 0}
class="min-w-[100px] py-2 px-4 bg-white border border-gray-300 text-gray-700 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition"
>
Previous
</button>
<span class="flex-1 text-center text-gray-600 font-medium">
Step {step + 1} of {steps.length}
</span>
<button
onclick={nextStep}
disabled={step === steps.length - 1 || !stepConditions[step]}
class="min-w-[100px] py-2 px-4 bg-white border border-gray-300 text-gray-700 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition"
>
Next
</button>
<div class="mt-2 mb-4">
{#if isAddingParticipants}
<h1 class="text-xl font-semibold text-gray-700 text-center">Add Participants to "{event.name}"</h1>
{/if}
</div>
{#if step == 0}
<StepConnectGoogle bind:authorized />
<StepConnectGoogle bind:authorized />
{:else if step == 1}
<StepCreateEvent bind:event />
<StepCreateEvent bind:event readonly={isAddingParticipants} />
{:else if step == 2}
<StepUploadParticipants bind:participants />
<StepUploadParticipants bind:participants />
{:else if step == 3}
<StepCraftEmail bind:email />
<StepCraftEmail bind:email />
{:else if step == 4}
<StepOverview
{data}
{event}
{participants}
{email}
{stepConditions}
/>
<StepOverview
{data}
{event}
{participants}
{email}
{stepConditions}
{existingEventId}
{isAddingParticipants}
/>
{/if}
<div class="pb-20"></div>
<div
class="fixed bottom-0 left-0 z-10 flex w-full items-center justify-between gap-4 border-t border-gray-300 bg-white px-4 py-2"
style="max-width: 100vw;"
>
<div class="container mx-auto max-w-2xl p-2 flex justify-content-center">
<button
onclick={prevStep}
disabled={step === 0}
class="min-w-[100px] rounded-md border border-gray-300 bg-white px-4 py-2 text-gray-700 transition hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
aria-label="Previous step"
>
Previous
</button>
<span class="flex-1 flex items-center justify-center text-center font-medium text-gray-600">
Step {step + 1} of {steps.length}
</span>
<button
onclick={nextStep}
disabled={step === steps.length - 1 || !stepConditions[step]}
class="min-w-[100px] rounded border border-gray-300 bg-white px-4 py-2 text-gray-700 transition hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
>
Next
</button>
</div>
</div>

View File

@@ -29,9 +29,18 @@
all_data = JSON.parse(sessionStorage.getItem(session_storage_id) || '{}');
try {
event_status = StepStatus.Loading;
const createdEvent = await createEventInSupabase(all_data.event);
event_status = StepStatus.Success;
let createdEvent;
if (all_data.isAddingParticipants && all_data.existingEventId) {
// Skip event creation for existing events
event_status = StepStatus.Success;
createdEvent = { id: all_data.existingEventId, ...all_data.event };
} else {
// Create new event
event_status = StepStatus.Loading;
createdEvent = await createEventInSupabase(all_data.event);
event_status = StepStatus.Success;
}
participants_status = StepStatus.Loading;
createdParticipants = await createParticipantsInSupabase(all_data.participants, createdEvent);
@@ -141,13 +150,17 @@
<!-- Creating Event Entry -->
<div class="mb-4 rounded border border-gray-300 bg-white p-4">
<h2 class="mb-2 text-xl font-bold">Creating event</h2>
<h2 class="mb-2 text-xl font-bold">
{all_data.isAddingParticipants ? 'Using existing event' : 'Creating event'}
</h2>
{#if event_status === StepStatus.Waiting}
<span class="text-black-600">Waiting...</span>
{:else if event_status === StepStatus.Loading}
<span class="text-black-600">Creating event...</span>
{:else if event_status === StepStatus.Success}
<span class="text-green-600">Event created successfully.</span>
<span class="text-green-600">
{all_data.isAddingParticipants ? 'Using existing event.' : 'Event created successfully.'}
</span>
{:else if event_status === StepStatus.Failure}
<span class="text-red-600">Failed to create event.</span>
{/if}
@@ -155,21 +168,22 @@
<!-- Creating Database Entries -->
<div class="mb-4 rounded border border-gray-300 bg-white p-4">
<h2 class="mb-2 text-xl font-bold">Creating database entries</h2>
<h2 class="mb-2 text-xl font-bold">Creating QR codes for participants</h2>
{#if participants_status === StepStatus.Waiting}
<span class="text-black-600">Waiting...</span>
{:else if participants_status === StepStatus.Loading}
<span class="text-black-600">Creating entries...</span>
{:else if participants_status === StepStatus.Success}
<span class="text-green-600">Database entries created successfully.</span>
<span class="text-green-600">QR codes created successfully.</span>
{:else if participants_status === StepStatus.Failure}
<span class="text-red-600">Failed to create database entries.</span>
<span class="text-red-600">Failed to create QR codes.</span>
{/if}
</div>
<!-- Sending Emails -->
<div class="rounded border border-gray-300 bg-white p-4">
<h2 class="mb-2 text-xl font-bold">Sending emails</h2>
<h2 class="mb-1 text-xl font-bold">Sending emails</h2>
<p class="text-sm text-red-500 mb-2">After pressing send, you must not exit this window until the mail are all sent!</p>
{#if email_status === StepStatus.Waiting}
<div class="flex items-center justify-between">
<span class="text-black-600">Waiting...</span>
@@ -179,7 +193,7 @@
class="ml-4 px-6 py-2 rounded font-semibold transition disabled:opacity-50 disabled:cursor-not-allowed
{event_status === StepStatus.Success && participants_status === StepStatus.Success ? 'bg-blue-600 hover:bg-blue-700 text-white' : 'bg-gray-400 text-white'}"
>
Launch Mail Campaign
Send all emails
</button>
</div>
{:else}

View File

@@ -57,10 +57,13 @@
>
Edit email
</button>
<div class="rounded border-l-4 border-green-500 p-4 text-green-700 bg-green-100">
<ol>
<li><strong>{email.subject}</strong></li>
<li class="whitespace-pre-line">{email.body}</li>
</ol>
<div class="rounded border border-gray-300 bg-white p-4">
<h2 class="mb-2 text-xl font-bold">Email Preview</h2>
<div class="mb-2">
<span class="block font-semibold">{email.subject}</span>
</div>
<div class="whitespace-pre-line text-gray-800">
{email.body}
</div>
</div>
{/if}

View File

@@ -1,8 +1,8 @@
<script lang="ts">
let { event = $bindable() } = $props();
let { event = $bindable(), readonly = false } = $props();
let loading = $state(false);
let showForm = $derived(!event.name || !event.date);
let showForm = $derived((!event.name || !event.date) && !readonly);
function handleSubmit(e: Event) {
e.preventDefault();
@@ -18,7 +18,9 @@
}
function showEditForm() {
showForm = true;
if (!readonly) {
showForm = true;
}
}
</script>
@@ -59,28 +61,22 @@
{/if}
{#if !showForm}
<button
class="mb-4 w-full rounded bg-blue-600 py-2 text-white transition hover:bg-blue-700"
onclick={showEditForm}
aria-label="Edit event"
>
Edit the event
</button>
{/if}
{#if !showForm}
<div
class="rounded border-l-4 border-green-500 p-4 text-green-700"
class:bg-gray-100={loading}
class:bg-green-100={!loading}
>
{#if loading}
<strong class="text-gray-700">Loading...</strong>
{:else if Object.keys(event).length > 0}
<ol>
<li><strong>{event.name}</strong></li>
<li>{event.date}</li>
</ol>
{#if !readonly}
<button
class="mb-4 w-full rounded bg-blue-600 py-2 text-white transition hover:bg-blue-700"
onclick={showEditForm}
aria-label="Edit event"
>
Edit the event
</button>
{/if}
<div class="rounded border border-gray-300 bg-white p-4">
<h2 class="mb-2 text-xl font-bold">Event Preview</h2>
{#if Object.keys(event).length > 0}
<ul>
<li><span class="font-semibold">{event.name}</span></li>
<li class="text-gray-700">{event.date}</li>
</ul>
{:else}
<strong class="text-gray-700">No event created yet...</strong>
{/if}

View File

@@ -1,7 +1,7 @@
<script lang="ts">
import { goto } from '$app/navigation';
let { data, event, participants, email, stepConditions } = $props();
let { data, event, participants, email, stepConditions, existingEventId = null, isAddingParticipants = false } = $props();
function redirectToFinish() {
// Generate a random variable name
@@ -9,7 +9,7 @@
// Save the data to sessionStorage
sessionStorage.setItem(
varName,
JSON.stringify({ event, participants, email })
JSON.stringify({ event, participants, email, existingEventId, isAddingParticipants })
);
// Redirect with the variable name as a query parameter
goto(`/private/events/creator/finish?data=${encodeURIComponent(varName)}`);
@@ -58,7 +58,7 @@
disabled:cursor-not-allowed disabled:bg-gray-300 disabled:text-gray-500"
disabled={!stepConditions.every(Boolean)}
>
Generate QR codes and send
{isAddingParticipants ? 'Add participants and send emails' : 'Generate QR codes and send'}
</button>
<div class="mt-2 space-y-1">

View File

@@ -2,19 +2,20 @@
import Papa from 'papaparse';
let { participants = $bindable() } = $props();
let loading = $state(false);
let showForm = $derived(participants.length === 0);
let errors = $state([]);
function isValidEmail(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
async function handleSubmit(e: Event) {
e.preventDefault();
loading = true;
errors = [];
const form = e.target as HTMLFormElement;
const fileInput = form.elements.namedItem('participants') as HTMLInputElement;
const file = fileInput?.files?.[0];
if (!file) {
loading = false;
return;
}
if (!file) return;
const csvText = await file.text();
const { data: parsedRows } = Papa.parse<string[]>(csvText, {
skipEmptyLines: true,
@@ -24,13 +25,36 @@
if (parsedRows.length > 0) {
parsedRows.shift();
}
participants = parsedRows.map((row: string[]) => ({
name: row[0],
surname: row[1],
email: row[2]
}));
const validated = [];
parsedRows.forEach((row, idx) => {
if (!row || row.length < 3) {
errors.push(`Row ${idx + 2} is missing columns.`);
return;
}
const [name, surname, email] = row;
if (!name || !surname || !email) {
errors.push(`Row ${idx + 2} has missing values.`);
return;
}
validated.push({
name,
surname,
email,
email_valid: isValidEmail(email)
});
});
if (errors.length > 0) {
return; // Do not proceed if there are errors
}
if (validated.length === 0) {
participants = [];
return;
}
participants = validated.sort((a, b) => {
if (a.email_valid === b.email_valid) return 0;
return a.email_valid ? 1 : -1;
});
showForm = false;
loading = false;
}
function showEditForm() {
@@ -39,6 +63,15 @@
</script>
{#if showForm}
{#if errors.length > 0}
<div class="mb-4 rounded border border-red-400 bg-red-50 p-4 text-red-700">
<ul class="list-disc ml-4">
{#each errors as err}
<li>{err}</li>
{/each}
</ul>
</div>
{/if}
<form
onsubmit={handleSubmit}
autocomplete="off"
@@ -75,22 +108,51 @@
{/if}
{#if !showForm}
<div class="mt-4 rounded border-l-4 border-green-500 bg-green-50 p-4 text-green-700">
{#if loading}
<strong class="text-gray-700">Loading...</strong>
{:else if participants.length === 0}
<strong class="text-gray-700">No participants yet...</strong>
{:else}
<ul class="space-y-2">
{#each participants as p, i}
<li class="flex items-center justify-between border-b pb-1">
<div>
<div class="font-semibold">{p.name} {p.surname}</div>
<div class="font-mono text-xs text-gray-600">{p.email}</div>
</div>
</li>
{/each}
</ul>
{/if}
<div class="mt-4 rounded border border-gray-300 bg-white p-4">
<div class="mb-2 flex items-center justify-between">
<h2 class="text-xl font-bold">Participants ({participants.length})</h2>
{#if participants.length > 0}
{#if participants.some((p) => !p.email_valid)}
<span class="text-xs text-gray-500">Some emails appear invalid</span>
{:else}
<span class="text-xs text-gray-500">All emails appear valid</span>
{/if}
{/if}
</div>
<ul class="space-y-1">
{#each participants as p}
<li class="flex items-center gap-2 border-b pb-1 last:border-b-0">
{#if p.email_valid}
<svg
title="Valid email"
class="mr-2 inline h-4 w-4 text-green-600"
fill="none"
stroke="currentColor"
stroke-width="2"
viewBox="0 0 24 24"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
</svg>
{:else}
<svg
title="Invalid email"
class="mr-2 inline h-4 w-4 text-red-600"
fill="none"
stroke="currentColor"
stroke-width="2"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none" />
<line x1="8" y1="8" x2="16" y2="16" stroke="currentColor" stroke-width="2" />
<line x1="16" y1="8" x2="8" y2="16" stroke="currentColor" stroke-width="2" />
</svg>
{/if}
<span class="font-semibold">{p.name} {p.surname}</span>
<span class="flex-1"></span>
<span class="text-right font-mono text-xs text-gray-600">{p.email}</span>
</li>
{/each}
</ul>
</div>
{/if}

View File

@@ -37,13 +37,25 @@
<h1 class="mt-2 mb-4 text-center text-2xl font-bold">Event Overview</h1>
<div class="mb-2 rounded border border-gray-300 bg-white p-4">
<div class="flex flex-col gap-1">
<div class="flex items-center justify-between gap-4">
<div class="flex flex-col gap-1">
{#if loading}
<div class="mb-2 h-6 w-40 animate-pulse rounded bg-gray-200"></div>
<div class="h-4 w-24 animate-pulse rounded bg-gray-100"></div>
{:else}
<span class="text-gray-700 text-lg font-semibold">{event_data?.name}</span>
<span class="text-gray-500 text-sm">{event_data?.date}</span>
{/if}
</div>
{#if loading}
<div class="h-6 w-40 bg-gray-200 rounded animate-pulse mb-2"></div>
<div class="h-4 w-24 bg-gray-100 rounded animate-pulse"></div>
{:else}
<span class="text-black-700 text-lg font-semibold">{event_data?.name}</span>
<span class="text-black-500 text-sm">{event_data?.date}</span>
<div class="h-10 w-32 animate-pulse rounded bg-gray-200"></div>
{:else if event_data}
<a
href={`/private/events/creator?eventId=${event_data.id}`}
class="rounded border border-gray-300 bg-blue-600 px-6 py-2 font-semibold text-white transition hover:bg-blue-700"
>
Add Participants
</a>
{/if}
</div>
</div>
@@ -60,7 +72,7 @@
<path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
</svg>
{#if loading}
<div class="h-4 w-16 bg-gray-200 rounded animate-pulse"></div>
<div class="h-4 w-16 animate-pulse rounded bg-gray-200"></div>
{:else}
<span class="text-sm text-gray-700">Scanned ({scannedCount})</span>
{/if}
@@ -79,7 +91,7 @@
<line x1="16" y1="8" x2="8" y2="16" stroke="currentColor" stroke-width="2" />
</svg>
{#if loading}
<div class="h-4 w-24 bg-gray-200 rounded animate-pulse"></div>
<div class="h-4 w-24 animate-pulse rounded bg-gray-200"></div>
{:else}
<span class="text-sm text-gray-700">Not scanned ({notScannedCount})</span>
{/if}
@@ -89,7 +101,7 @@
<div class="rounded border border-gray-300 bg-white p-4">
<h2 class="mb-2 rounded text-xl font-bold">
{#if loading}
<div class="h-6 w-32 bg-gray-200 rounded animate-pulse"></div>
<div class="h-6 w-32 animate-pulse rounded bg-gray-200"></div>
{:else}
Participants ({participants.length})
{/if}
@@ -97,7 +109,7 @@
<ul class="space-y-1">
{#if loading}
<li>
<div class="h-10 w-full bg-gray-200 rounded animate-pulse"></div>
<div class="h-10 w-full animate-pulse rounded bg-gray-200"></div>
</li>
{:else}
{#each participants as p}

80
src/service-worker.ts Normal file
View File

@@ -0,0 +1,80 @@
/// <reference types="@sveltejs/kit" />
import { build, files, version } from '$service-worker';
// Create a unique cache name for this deployment
const CACHE = `cache-${version}`;
const ASSETS = [
...build, // the app itself
...files // everything in `static`
];
self.addEventListener('install', (event) => {
// Create a new cache and add all files to it
async function addFilesToCache() {
const cache = await caches.open(CACHE);
await cache.addAll(ASSETS);
}
event.waitUntil(addFilesToCache());
});
self.addEventListener('activate', (event) => {
// Remove previous cached data from disk
async function deleteOldCaches() {
for (const key of await caches.keys()) {
if (key !== CACHE) await caches.delete(key);
}
}
event.waitUntil(deleteOldCaches());
});
self.addEventListener('fetch', (event) => {
// ignore POST requests etc
if (event.request.method !== 'GET') return;
async function respond() {
const url = new URL(event.request.url);
const cache = await caches.open(CACHE);
// `build`/`files` can always be served from the cache
if (ASSETS.includes(url.pathname)) {
const response = await cache.match(url.pathname);
if (response) {
return response;
}
}
// for everything else, try the network first, but
// fall back to the cache if we're offline
try {
const response = await fetch(event.request);
// if we're offline, fetch can return a value that is not a Response
// instead of throwing - and we can't pass this non-Response to respondWith
if (!(response instanceof Response)) {
throw new Error('invalid response from fetch');
}
if (response.status === 200) {
cache.put(event.request, response.clone());
}
return response;
} catch (err) {
const response = await cache.match(event.request);
if (response) {
return response;
}
// if there's no cache, then just error out
// as there is nothing we can do to respond to this request
throw err;
}
}
event.respondWith(respond());
});