ghost-user-maker/src/App.svelte
Badri Sunderarajan 80427068ea Validate fields (and auto-update slug)
The slug is intelligently computed from the other fields, until
the user decides to manually override it.
2022-08-05 11:07:41 +05:30

134 lines
2.9 KiB
Svelte

<script lang="ts">
import * as EmailValidator from 'email-validator'
import Slug from 'slug'
export let name: string;
export let email: string;
export let slug: string;
export let bio: string;
let slugIsAuto = true;
function generateAuthor(e) {
e.preventDefault()
// Check the formatting
let errors = []
// First, make sure the required fields are filled
for (let [k,v] of [
['name', name],
['email', email],
['slug', slug]])
{
console.log(`it is ${k} called ${v}`)
if (!v) {
errors.push(`${k} cannot be left blank`)
}
}
// Validate email formatting
if (!EmailValidator.validate(email)) {
errors.push(`"${email}" is not a valid email address`)
}
// Validate slug formatting
if (errors.length) {
alert(`There are some errors: ${errors}`)
} else {
alert(`Name: ${name} email, ${email} has slug ${slug} and bio ${bio}`)
}
}
function computeSlug() {
/*
Compute the slug from email or name, if it
isn't already computed.
*/
if (!slug || slugIsAuto) {
if (email) {
slug = Slug(email.split('@')[0])
} else if (name) {
slug = Slug(name)
}
}
/*
Of course, if neither email nor name is
set, then we can't do anything about it
*/
}
function updateSlug() {
/*
Marks the slug as manually set (which means
we should stop doing our automatic stuff)
*/
if (slug) {
slugIsAuto = false
// slugify it, just in case
slug = Slug(slug)
} else {
slugIsAuto = true
computeSlug()
}
}
</script>
<main>
<h1>Ghost User Maker</h1>
<p>Enter your new author details below. Once done, click on the "Generate" button to receive a special file that you can import to Ghost to add the author details to the "staff". This will let you select them as the author when publishing a post.</p>
<form>
<fieldset>
<legend>{name || 'Author'}</legend>
<div>
<label for="input-name">Name</label>
<input id="input-name" name="name" bind:value={name} on:change={computeSlug}/>
</div>
<div>
<label for="input-email">Email</label>
<input id="input-email" name="email" type="email" bind:value={email} on:change={computeSlug}/>
</div>
<div>
<label for="input-slug">Slug</label>
<input id="input-slug" name="slug" bind:value={slug} on:change={updateSlug}/>
</div>
<div>
<label for="input-bio">Bio</label>
<input id="input-bio" name="bio" bind:value={bio}/>
</div>
<button on:click={generateAuthor}>Generate</button>
</fieldset>
</form>
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: none;
margin: 0 auto;
}
fieldset label {
display: inline-block;
}
@media (min-width: 640px) {
main {
max-width: 480px;
}
}
</style>