add svelte app.

This commit is contained in:
Jason Schwarzenberger
2020-11-27 13:43:47 +13:00
parent 085dd47d13
commit fe4b02e8a1
27 changed files with 3827 additions and 0 deletions

39
webapp/src/ambient.d.ts vendored Normal file
View File

@@ -0,0 +1,39 @@
/**
* These declarations tell TypeScript that we allow import of images, e.g.
* ```
<script lang='ts'>
import successkid from 'images/successkid.jpg';
</script>
<img src="{successkid}">
```
*/
declare module "*.gif" {
const value: string;
export = value;
}
declare module "*.jpg" {
const value: string;
export = value;
}
declare module "*.jpeg" {
const value: string;
export = value;
}
declare module "*.png" {
const value: string;
export = value;
}
declare module "*.svg" {
const value: string;
export = value;
}
declare module "*.webp" {
const value: string;
export = value;
}

5
webapp/src/client.js Normal file
View File

@@ -0,0 +1,5 @@
import * as sapper from '@sapper/app';
sapper.start({
target: document.querySelector('#sapper')
});

View File

@@ -0,0 +1,60 @@
<script>
import fromUnixTime from "date-fns/fromUnixTime";
import formatDistanceToNow from "date-fns/formatDistanceToNow";
export let story;
export let comment;
export let showComments = true;
export let dateString = formatDistanceToNow(fromUnixTime(comment.date), {
addSuffix: true,
});
const author = comment.author.replace(" ", "");
export let id = `${author}-${comment.date}`;
export function toggleComments() {
showComments = !showComments;
}
</script>
<style>
.comment-author {
}
.comment-text {
padding: 0 0.5rem;
color: #333;
}
.comment-children {
margin-left: 1rem;
padding-left: 1rem;
border-left: solid 1px #000;
}
.link-button {
background: none;
border: none;
padding: 0 0.1rem;
color: inherit;
cursor: pointer;
}
</style>
<div class="comment" id="comment-{id}">
<div class="comment-author">
{comment.author}
|
<a href="{story.id}#comment-{id}">{dateString}</a>
{#if comment.comments.length}
<button
class="link-button"
on:click={toggleComments}>[{showComments ? '-' : '+'}]</button>
{/if}
</div>
<div class="comment-text">
{@html comment.text}
</div>
{#if showComments && comment.comments.length}
<div class="comment-children">
{#each comment.comments as child}
<svelte:self {story} comment={child} />
{/each}
</div>
{/if}
</div>

View File

@@ -0,0 +1,59 @@
<script>
export let segment;
</script>
<style>
nav {
border-bottom: 1px solid rgba(255, 62, 0, 0.1);
font-weight: 300;
padding: 0 1em;
}
ul {
margin: 0;
padding: 0;
}
/* clearfix */
ul::after {
content: "";
display: block;
clear: both;
}
li {
display: block;
float: left;
}
[aria-current] {
position: relative;
display: inline-block;
}
[aria-current]::after {
position: absolute;
content: "";
width: calc(100% - 1em);
height: 2px;
background-color: rgb(255, 62, 0);
display: block;
bottom: -1px;
}
a {
text-decoration: none;
padding: 1em 0.5em;
display: block;
}
</style>
<nav>
<ul>
<li>
<a
aria-current={segment === undefined ? 'page' : undefined}
href=".">News</a>
</li>
</ul>
</nav>

View File

@@ -0,0 +1,28 @@
<script>
import fromUnixTime from "date-fns/fromUnixTime";
import formatDistanceToNow from "date-fns/formatDistanceToNow";
export let story;
export let dateString = formatDistanceToNow(fromUnixTime(story.date), {
addSuffix: true,
});
</script>
<style>
</style>
<time
datetime={fromUnixTime(story.date).toISOString()}
title={fromUnixTime(story.date)}>{dateString}</time>
{#if story.author && story.author_link}
by
<a href={story.author_link}>{story.author}</a>
{:else if story.author}by {story.author}{/if}
on
{story.source}
{#if story.score}&bull; {story.score} points{/if}
{#if story.num_comments}
&bull;
<a rel="prefetch" href="/{story.id}#comments">{story.num_comments}
comments</a>
{/if}

BIN
webapp/src/node_modules/images/successkid.jpg generated vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

View File

@@ -0,0 +1,9 @@
import fetch from 'node-fetch';
export async function get(req, res) {
const response = await fetch(`http://localhost:33842/api/${req.params.id}`);
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(await response.text());
}

View File

@@ -0,0 +1,111 @@
<script context="module">
export async function preload({ params }) {
// the `slug` parameter is available because
// this file is called [slug].svelte
const res = await this.fetch(`${params.id}.json`);
const data = await res.json();
if (res.status === 200) {
const related = [];
const others = data.related.filter(
(r) => r.id !== data.story.id && !!r.num_comments
);
for (const other of others) {
const r = await this.fetch(`${other.id}.json`);
if (r.ok) {
const d = await r.json();
related.push(d.story);
}
}
return { story: data.story, related };
} else {
this.error(res.status, data.message);
}
}
</script>
<script>
import Comment from "../components/Comment.svelte";
import StoryInfo from "../components/StoryInfo.svelte";
export let story;
export let related;
let hasComments = story.num_comments || related.length;
</script>
<style>
/*
By default, CSS is locally scoped to the component,
and any unused styles are dead-code-eliminated.
In this page, Svelte can't know which elements are
going to appear inside the {{{post.html}}} block,
so we have to use the :global(...) modifier to target
all elements inside .content
*/
.content :global(h2) {
font-size: 1.4em;
font-weight: 500;
}
.content :global(pre) {
background-color: #f9f9f9;
box-shadow: inset 1px 1px 5px rgba(0, 0, 0, 0.05);
padding: 0.5em;
border-radius: 2px;
overflow-x: auto;
}
.content :global(pre) :global(code) {
background-color: transparent;
padding: 0;
}
.content :global(ul) {
line-height: 1.5;
}
.content :global(li) {
margin: 0 0 0.5em 0;
}
.content :global(img) {
max-width: 100%;
}
.spacer {
margin: 3rem 0;
}
</style>
<svelte:head>
<title>{story.title}</title>
</svelte:head>
<h1>{story.title}</h1>
<StoryInfo {story} />
<div class="content">
{@html story.text}
</div>
{#if hasComments}
<hr class="spacer" />
<h2 id="comments">Comments</h2>
{#if related.length}
<h3>
Other discussions:
{#each related as r}
{#if r.num_comments}
<a href="/{r.id}#comments" rel="prefetch">{r.source}</a>
{/if}
{/each}
</h3>
{/if}
{#if story.comments.length}
<div class="comments">
{#each story.comments as comment}
<Comment {story} {comment} />
{/each}
</div>
{/if}
{/if}

View File

@@ -0,0 +1,40 @@
<script>
export let status;
export let error;
const dev = process.env.NODE_ENV === 'development';
</script>
<style>
h1, p {
margin: 0 auto;
}
h1 {
font-size: 2.8em;
font-weight: 700;
margin: 0 0 0.5em 0;
}
p {
margin: 1em auto;
}
@media (min-width: 480px) {
h1 {
font-size: 4em;
}
}
</style>
<svelte:head>
<title>{status}</title>
</svelte:head>
<h1>{status}</h1>
<p>{error.message}</p>
{#if dev && error.stack}
<pre>{error.stack}</pre>
{/if}

View File

@@ -0,0 +1,21 @@
<script>
import Nav from "../components/Nav.svelte";
export let segment;
</script>
<style>
main {
position: relative;
max-width: 56em;
background-color: white;
padding: 2em;
margin: 0 auto;
box-sizing: border-box;
}
</style>
<Nav {segment} />
<main>
<slot {segment} />
</main>

View File

@@ -0,0 +1,9 @@
import fetch from 'node-fetch';
export async function get(req, res) {
const response = await fetch(`http://localhost:33842/api`);
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(await response.text());
}

View File

@@ -0,0 +1,50 @@
<script context="module">
export function preload() {
return this.fetch(`index.json`)
.then((r) => r.json())
.then(({ stories }) => {
return { stories };
});
}
</script>
<script>
import { getLogoUrl } from "../utils/logos.js";
import StoryInfo from "../components/StoryInfo.svelte";
export let stories;
</script>
<style>
article {
margin: 0.5rem 0;
}
</style>
<svelte:head>
<title>News</title>
</svelte:head>
<section>
{#each stories as story}
<!-- we're using the non-standard `rel=prefetch` attribute to
tell Sapper to load the data for the page as soon as
the user hovers over the link or taps it, instead of
waiting for the 'click' event -->
<article>
<header>
<img
src={getLogoUrl(story)}
alt="logo"
style="height: 1rem; width: 1rem;" />
<a rel="prefetch" href="/{story.id}">{story.title}</a>
(<a href={story.url || story.link}>
{new URL(story.url || story.link).hostname.replace(/^www\./, '')}
</a>)
</header>
<section>
<StoryInfo {story} />
</section>
</article>
{/each}
</section>

17
webapp/src/server.js Normal file
View File

@@ -0,0 +1,17 @@
import sirv from 'sirv';
import polka from 'polka';
import compression from 'compression';
import * as sapper from '@sapper/server';
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
polka() // You can also use Express
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
sapper.middleware(),
)
.listen(PORT, err => {
if (err) console.log('error', err);
});

View File

@@ -0,0 +1,86 @@
import { timestamp, files, shell } from '@sapper/service-worker';
const ASSETS = `cache${timestamp}`;
// `shell` is an array of all the files generated by the bundler,
// `files` is an array of everything in the `static` directory
const to_cache = shell.concat(files);
const staticAssets = new Set(to_cache);
self.addEventListener('install', event => {
event.waitUntil(
caches
.open(ASSETS)
.then(cache => cache.addAll(to_cache))
.then(() => {
self.skipWaiting();
})
);
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(async keys => {
// delete old caches
for (const key of keys) {
if (key !== ASSETS) await caches.delete(key);
}
self.clients.claim();
})
);
});
/**
* Fetch the asset from the network and store it in the cache.
* Fall back to the cache if the user is offline.
*/
async function fetchAndCache(request) {
const cache = await caches.open(`offline${timestamp}`)
try {
const response = await fetch(request);
cache.put(request, response.clone());
return response;
} catch (err) {
const response = await cache.match(request);
if (response) return response;
throw err;
}
}
self.addEventListener('fetch', event => {
if (event.request.method !== 'GET' || event.request.headers.has('range')) return;
const url = new URL(event.request.url);
// don't try to handle e.g. data: URIs
const isHttp = url.protocol.startsWith('http');
const isDevServerRequest = url.hostname === self.location.hostname && url.port !== self.location.port;
const isStaticAsset = url.host === self.location.host && staticAssets.has(url.pathname);
const skipBecauseUncached = event.request.cache === 'only-if-cached' && !isStaticAsset;
if (isHttp && !isDevServerRequest && !skipBecauseUncached) {
event.respondWith(
(async () => {
// always serve static files and bundler-generated assets from cache.
// if your application has other URLs with data that will never change,
// set this variable to true for them and they will only be fetched once.
const cachedAsset = isStaticAsset && await caches.match(event.request);
// for pages, you might want to serve a shell `service-worker-index.html` file,
// which Sapper has generated for you. It's not right for every
// app, but if it's right for yours then uncomment this section
/*
if (!cachedAsset && url.origin === self.origin && routes.find(route => route.pattern.test(url.pathname))) {
return caches.match('/service-worker-index.html');
}
*/
return cachedAsset || fetchAndCache(event.request);
})()
);
}
});

33
webapp/src/template.html Normal file
View File

@@ -0,0 +1,33 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta name="theme-color" content="#333333">
%sapper.base%
<link rel="stylesheet" href="global.css">
<link rel="manifest" href="manifest.json" crossorigin="use-credentials">
<link rel="icon" type="image/png" href="favicon.png">
<!-- Sapper creates a <script> tag containing `src/client.js`
and anything else it needs to hydrate the app and
initialise the router -->
%sapper.scripts%
<!-- Sapper generates a <style> tag containing critical CSS
for the current page. CSS for the rest of the app is
lazily loaded when it precaches secondary pages -->
%sapper.styles%
<!-- This contains the contents of the <svelte:head> component, if
the current page has one -->
%sapper.head%
</head>
<body>
<!-- The application will be rendered inside this element,
because `src/client.js` references it -->
<div id="sapper">%sapper.html%</div>
</body>
</html>

11
webapp/src/utils/logos.js Normal file

File diff suppressed because one or more lines are too long