From 94505772348f4a0c8a2c498a546bb4c4efb56bb0 Mon Sep 17 00:00:00 2001 From: Jonas Geiler Date: Sat, 20 Apr 2024 19:31:18 +0200 Subject: [PATCH] refactor: improved hackernews demo --- src/app.html | 2 +- src/routes/demos/hacker-news/+page.svelte | 146 +++++++++++++++------- 2 files changed, 101 insertions(+), 47 deletions(-) diff --git a/src/app.html b/src/app.html index f22aeaa..222350c 100644 --- a/src/app.html +++ b/src/app.html @@ -7,6 +7,6 @@ %sveltekit.head% -
%sveltekit.body%
+
%sveltekit.body%
diff --git a/src/routes/demos/hacker-news/+page.svelte b/src/routes/demos/hacker-news/+page.svelte index 8dc6299..9af1ba9 100644 --- a/src/routes/demos/hacker-news/+page.svelte +++ b/src/routes/demos/hacker-news/+page.svelte @@ -2,13 +2,16 @@ import VirtualList from '$lib/VirtualList.svelte'; import InfiniteLoading from 'svelte-infinite-loading'; - const api = 'https://hn.algolia.com/api/v1/search_by_date?tags=story'; + const api = + 'https://hn.algolia.com/api/v1/search_by_date' + + '?tags=story' + + `&numericFilters=created_at_i<=${Math.floor(Date.now() / 1000)}`; let page = 1; let listHeight = 0; let list = []; - function infiniteHandler({ detail: { loaded, complete } }) { + function infiniteHandler({ detail: { loaded, complete, error } }) { fetch(`${api}&page=${page}`) .then((response) => response.json()) .then((data) => { @@ -19,56 +22,97 @@ } else { complete(); } - }); + }) + .catch(() => error()); + } + + function formatSite(url) { + const domain = new URL(url).hostname; + return domain.startsWith('www.') ? domain.slice(4) : domain; + } + + const dateFormatter = new Intl.RelativeTimeFormat('en', { style: 'long' }); + function formatCreatedAt(createdAt) { + const seconds = Math.floor((new Date() - new Date(createdAt)) / 1000); + if (seconds <= 60) { + return dateFormatter.format(-seconds, 'second'); + } else if (seconds <= 3600) { + return dateFormatter.format(-Math.floor(seconds / 60), 'minute'); + } else if (seconds <= 86400) { + return dateFormatter.format(-Math.floor(seconds / 3600), 'hour'); + } else if (seconds <= 604800) { + return dateFormatter.format(-Math.floor(seconds / 86400), 'day'); + } else if (seconds <= 2592000) { + return dateFormatter.format(-Math.floor(seconds / 604800), 'week'); + } else if (seconds <= 31536000) { + return dateFormatter.format(-Math.floor(seconds / 2592000), 'month'); + } else { + return dateFormatter.format(-Math.floor(seconds / 31536000), 'year'); + } } -
-
- - Logo - +
+ + Logo Hacker News -
+ +
-
- -
- {list[index].title} -

- {list[index].points} - points by - {list[index].author} - | - {list[index].num_comments} comments -

-
+
+ + -
- -
-
-
+
+ +
+