<script lang="ts">
import * as z from 'zod';
import { goto } from '$app/navigation';
import AuthShell from '#lib/components/site/AuthShell.svelte';
import Field from '#lib/components/site/Field.svelte';
import PasswordInput from '#lib/components/site/PasswordInput.svelte';
import PasswordMeter from '#lib/components/site/PasswordMeter.svelte';
import ProviderSignIn from '#lib/components/site/ProviderSignIn.svelte';
import { Button } from '#lib/components/ui/button/index.js';
import { Input } from '#lib/components/ui/input/index.js';
import { email as emailRule, firstErrors } from '#lib/forms.js';
import { clearBoot } from '#lib/live/boot.js';
import { ApiFailure, request } from '#lib/live/http.js';
const schema = z.object({
name: z.string().trim().min(1, 'Enter your name').max(100, 'Use 100 characters or fewer'),
email: emailRule,
password: z.string().min(12, 'Use at least 12 characters').max(128, 'Use 128 characters or fewer')
});
let name = $state('');
let email = $state('');
let password = $state('');
let errors = $state<Record<string, string>>({});
let pending = $state(false);
// The form has no handle field, so the handle starts as the part of the email before the @ and gets a random
// suffix when the server says it is taken or reserved.
const handleBase = (address: string) =>
address
.split('@')[0]!
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 32) || 'user';
const suffixed = (base: string) => `${base}-${Math.random().toString(36).slice(2, 6)}`;
const submit = async (event: SubmitEvent) => {
event.preventDefault();
const parsed = schema.safeParse({ name, email, password });
errors = parsed.success ? {} : firstErrors(parsed.error);
if (!parsed.success) return;
pending = true;
const base = handleBase(email);
let handle = base;
try {
for (let attempt = 0; ; attempt++) {
try {
await request('POST', '/api/auth/sign-up', { name: name.trim(), handle, email, password });
break;
} catch (err) {
const handleProblem = err instanceof ApiFailure && (err.status === 409 || err.status === 422) && err.message.includes('handle');
if (!handleProblem || attempt >= 4) throw err;
handle = suffixed(base);
}
}
clearBoot();
await goto(`/${handle}`);
} catch (err) {
errors =
err instanceof ApiFailure && err.status === 409
? { email: 'An account with this email already exists. Sign in instead.' }
: err instanceof ApiFailure && err.status === 422
? { password: err.message }
: { password: 'Could not create the account. Try again in a moment.' };
pending = false;
}
};
</script>
<svelte:head>
<title>Create your Sailfork account</title>
</svelte:head>
<AuthShell title="Create your account" intro="Push and clone with the git you already have.">
<ProviderSignIn verb="Sign up" />
<form novalidate class="grid gap-5" onsubmit={submit}>
<Field id="name" label="Name" error={errors.name}>
{#snippet children({ describedBy })}
<Input
id="name"
name="name"
autocomplete="name"
required
bind:value={name}
aria-invalid={errors.name ? true : undefined}
aria-describedby={describedBy}
/>
{/snippet}
</Field>
<Field id="email" label="Work email" error={errors.email}>
{#snippet children({ describedBy })}
<Input
id="email"
name="email"
type="email"
autocomplete="email"
required
bind:value={email}
aria-invalid={errors.email ? true : undefined}
aria-describedby={describedBy}
/>
{/snippet}
</Field>
<Field id="password" label="Password" error={errors.password}>
{#snippet children({ describedBy })}
<PasswordInput
id="password"
name="password"
autocomplete="new-password"
required
minlength={12}
bind:value={password}
aria-invalid={errors.password ? true : undefined}
aria-describedby={describedBy ? `${describedBy} password-rule` : 'password-rule'}
/>
<PasswordMeter id="password-rule" {password} userInputs={[name, email]} />
{/snippet}
</Field>
<Button type="submit" size="lg" class="mt-1 w-full" disabled={pending}>
{pending ? 'Creating account…' : 'Create account'}
</Button>
</form>
{#snippet footer()}
Already have an account? <a href="/sign-in" class="text-primary underline-offset-4 hover:underline">Sign in</a>
{/snippet}
</AuthShell>