A clean and minimal youtube frontend, without all the ads and whistles
JavaScript
templates, spa, /settings, /videos route
Christian Feid28a53bafcc9
diff --git a/client/components/add-channel-form.js b/client/components/add-channel-form.jsindex c0f74e3..56128c0 100644--- a/client/components/add-channel-form.js+++ b/client/components/add-channel-form.js@@ -17,10 +17,11 @@ class AddChannelForm extends HTMLElement {}render () {this.innerHTML = /*html*/`- <form id="add-channel-form">- <label for="channel-name">Add a new channel</label>- <input type="text" id="channel-name" placeholder="Channel Name" required>- <button type="submit">Submit</button>+ <form id="add-channel-form" class="p-1 border-light">+ <div class="flex space-between">+ <label for="channel-name">Add a new channel</label>+ <input type="text" id="channel-name" placeholder="Channel Name" required>+ </div><span class="loader"></span></form>`@@ -30,15 +31,14 @@ class AddChannelForm extends HTMLElement {event.preventDefault()const form = event.target- const button = form.querySelector('button')const input = form.querySelector('input')const loader = form.querySelector('.loader')- freezeForm()const channelName = document.getElementById('channel-name').value-- if (!channelName) return alert('empty channel name'), unfreezeForm();-+ if (!channelName) return alert('empty channel name')++ freezeForm()+fetch('/channels', {method: 'POST',headers: { 'Content-Type': 'application/json' },@@ -50,12 +50,10 @@ class AddChannelForm extends HTMLElement {function freezeForm() {input.disabled = true- button.disabled = trueloader.classList.add('show')}function unfreezeForm() {input.disabled = false- button.disabled = falseloader.classList.remove('show')}}diff --git a/client/index.html b/client/index.htmlindex 6cf743d..ea0a09a 100644--- a/client/index.html+++ b/client/index.html@@ -9,12 +9,19 @@</head><body><header>- <h1 class="">My-YT</h1>+ <h1><a href="/">My-YT</a></h1><search-videos></search-videos><a href="/settings">🔧 Settings</a></header>- <main>+ <main></main>++ <dialog id="summary">+ <button id="close">X</button>+ <div></div>+ </dialog>++ <template id="main-template"><channels-list></channels-list><div class="flex space-around"><button id="show-downloaded-videos">Downloaded videos</button>@@ -26,23 +33,18 @@<summary>Download Log</summary><div class="lines"></div></details>- </main>-- <dialog id="summary">- <button id="close">X</button>- <div></div>- </dialog>+ </template><template id="settings-template">- <div id="settings">- <button id="close">X</button>+ <div id="settings" class="contain"><div>- <h5>Settings </h5>+ <h2>Settings </h2></div><br><add-channel-form></add-channel-form><br>+ <!--<form><label for="show-thumbnails">Show video thumbnails@@ -50,13 +52,20 @@<input type="checkbox" id="show-thumbnails"/></form><br>+ -->+ <!--<div><input type="text" id="add-ignored-term"/><ul id="ignored-terms"></ul></div>+ --></div></template>+ <template id="not-found-template">+ <h1>404 Not Found</h1>+ </template>+<script type="module" src="/components/channels-list.js"></script><script type="module" src="/components/search-videos.js"></script><script type="module" src="/components/add-channel-form.js"></script>diff --git a/client/main.css b/client/main.cssindex 6a17f54..92f39b3 100644--- a/client/main.css+++ b/client/main.css@@ -16,6 +16,21 @@ body {}}+main {+ padding: 0.5rem;+}++.contain {+ max-width: 50em;+ margin: 0 auto;+}+.border-light {+ border: 1px solid #ccc;+}+.p-1 {+ padding: 0.5rem;+}+form {margin-bottom: 20px;}@@ -153,15 +168,6 @@ form {}--#settings {- position: relative;-}-#settings #close {- position:absolute;- top: 0.5rem;- right: 0.5rem;-}::backdrop {background-image: linear-gradient(45deg,@@ -230,8 +236,12 @@ details {.flex {display: flex;justify-content: space-around;+ align-items: center;margin-top: 0.3em;}+.space-between {+ justify-content: space-between;+}.play-video-placeholder {height: 157px;diff --git a/client/main.js b/client/main.jsindex 24b6a4e..0826672 100644--- a/client/main.js+++ b/client/main.js@@ -2,9 +2,67 @@ import Store from '/lib/store.js'const store = new Store()window.store = store+++function handleRoute(route = window.location.pathname) {+ console.log('handling route', route)+ if (routes[route]) {+ document.querySelector('main').replaceChildren(routes[route].template.content.cloneNode(true))+ routes[route].initialize && routes[route].initialize()+ } else {+ document.querySelector('main').replaceChildren(routes['/404'].template.content.cloneNode(true))+ routes['/404'].initialize && routes['/404'].initialize()+ }+}++const routes = {+ '/': { template: document.getElementById('main-template'), title: 'My YT', async initialize() {+ console.log('initialize /')+ let $videosContainer = document.querySelector('.main-videos-container')+ if (!$videosContainer) return+ let videos = await fetch('/videos').then(res => res.json())++ $videosContainer.innerHTML = ''+ const ignoredTerms = window.store.get(window.store.ignoreTermsKey)++ videos = videos+ .filter(video => video.title.split(' ').every(word => !ignoredTerms.includes(word.toLowerCase().replace(/('s|"|,|:)/,''))))+ .sort((a, b) => +new Date(b.publishedAt) - +new Date(a.publishedAt))+ .filter((_, i) => i < 1000)++ videos.forEach(video => $videosContainer.appendChild(createVideoElement(video)))++ const channelsList = videos.reduce((acc, video) => {+ if (!acc.includes(video.channelName)) acc.push(video.channelName)+ return acc+ }, []).join(',')+ document.querySelector('channels-list').dataset['list'] = channelsList+ } },+ '/settings': { template: document.getElementById('settings-template'), title: 'My YT - Settings', async initialize () {+ console.log('initalize /settings')+ } },+ '/404': { template: document.getElementById('not-found-template'), title: 'Not Found' }+}++handleRoute()+window.addEventListener('popstate', (event) => {+ console.log('popstate', window.location.pathname)+ handleRoute()+})+document.querySelectorAll('[href="/"],[href="/settings"]').forEach(($el) => {+ $el.addEventListener('click', (event) => {+ event.preventDefault()+ const path = new URL($el.href, window.location.origin).pathname+ console.log('navigating ->', path)+ window.history.pushState({}, '', path)+ var popStateEvent = new PopStateEvent('popstate', {})+ dispatchEvent(popStateEvent)+ })+})+// app: sse updates and rendersconst eventSource = new window.EventSource('/')-const $videosContainer = document.querySelector('.main-videos-container')+let $videosContainer = document.querySelector('.main-videos-container')eventSource.onmessage = (message) => {if (!message || !message.data) return console.error('skipping empty message')@@ -21,27 +79,13 @@ eventSource.onmessage = (message) => {lines = lines.join('\n') + '\n' + data.line$downloadLogLines.innerText = lines$downloadLogLines.scrollTop = $downloadLogLines.scrollHeight;+ return}- if (data.type === 'all' && data.videos) {- $videosContainer.innerHTML = ''- const ignoredTerms = window.store.get(window.store.ignoreTermsKey)-- const allVideos = data.videos- .filter(video => video.title.split(' ').every(word => !ignoredTerms.includes(word.toLowerCase().replace(/('s|"|,|:)/,''))))- .sort((a, b) => +new Date(b.publishedAt) - +new Date(a.publishedAt))- .filter((_, i) => i < 1000)-- allVideos.forEach(video => $videosContainer.appendChild(createVideoElement(video)))-- const channelsList = data.videos.reduce((acc, video) => {- if (!acc.includes(video.channelName)) acc.push(video.channelName)- return acc- }, []).join(',')- document.querySelector('channels-list').dataset['list'] = channelsList- }if (data.type === 'new-videos' && data.videos) {- console.warn('new-videos', data)+ $videosContainer = document.querySelector('.main-videos-container')+ if (!$videosContainer) return+data.videos.forEach(video => {const $videoElement = $videosContainer.querySelector('video-element')if (!$videoElement) {@@ -50,10 +94,12 @@ eventSource.onmessage = (message) => {}$videoElement.parentNode.insertBefore(createVideoElement(video), $videoElement.nextSibling)})+ return}if (data.type === 'summary-error' && data.videoId) {const $videoElement = document.querySelector(`[data-video-id="${data.videoId}"]`)$videoElement && $videoElement.render && $videoElement.render()+ return}if (data.type === 'summary' && data.videoId && data.summary && data.transcript) {;[...document.querySelectorAll(`[data-video-id="${data.videoId}"]`)].forEach($video => {@@ -62,6 +108,7 @@ eventSource.onmessage = (message) => {Object.assign(videoData, { summary: data.summary, transcript: data.transcript })$video.dataset['data'] = JSON.stringify(videoData)})+ return}if (data.type === 'downloaded' && data.videoId) {;[...document.querySelectorAll(`[data-video-id="${data.videoId}"]`)].forEach($video => {@@ -70,7 +117,9 @@ eventSource.onmessage = (message) => {videoData.downloaded = true$video.dataset['data'] = JSON.stringify(videoData)})+ return}+ console.warn('unhandled', data)} catch (err) {console.error('sse parse error', err)}@@ -155,7 +204,7 @@ function observeDialogOpenPreventScroll (dialog) {// } else {// document.body.classList.add('hide-thumbnails')// }-// const $showThumbnailsCheckbox = document.querySelector('#show-thumbnails')+// const $showThumbnailsCheckbox = document.getElementById('show-thumbnails')// if ($showThumbnailsCheckbox) $showThumbnailsCheckbox.checked = showThumbnails// }diff --git a/lib/server.js b/lib/server.jsindex 7dac3a1..573eebb 100644--- a/lib/server.js+++ b/lib/server.js@@ -24,10 +24,8 @@ export function createServer ({repo, connections = []}) {return http.createServer(async (req, res) => {const url = new URL(req.url, `http://${req.headers.host}`)- if (req.headers.accept && req.headers.accept.indexOf('text/event-stream') >= 0) {- handleSSE(res, connections)- return broadcastSSE(JSON.stringify({type: 'all', videos: repo.getVideos()}), [res])- }+ /* initialize SSE */+ if (req.headers.accept && req.headers.accept.indexOf('text/event-stream') >= 0) return handleSSE(res, connections)/* api */if (url.pathname === '/channels' && req.method === 'POST')@@ -38,6 +36,8 @@ export function createServer ({repo, connections = []}) {return summarizeVideoHandler(req, res, repo, connections)if (url.pathname === '/ignore-video' && req.method === 'POST')return ignoreVideoHandler(req, res, repo, connections)+ if (url.pathname === '/videos' && req.method === 'GET')+ return allVideosHandler(req, res, repo, connections)if (url.pathname.match('\/videos\/.*') && req.method === 'GET')return watchVideoHandler(req, res)if (url.pathname.match('\/captions\/.*') && req.method === 'GET')@@ -60,10 +60,8 @@ export function createServer ({repo, connections = []}) {return fileHandler('client/components/channels-list.js', 'application/javascript')(req, res)if (url.pathname === '/lib/store.js')return fileHandler('client/lib/store.js', 'application/javascript')(req, res)- if (url.pathname === '/' || url.pathname === '/index.html')- return fileHandler('client/index.html', 'text/html')(req, res)- res.writeHead(404, { 'Content-Type': 'text/plain' })- res.end('Not found')++ return fileHandler('client/index.html', 'text/html')(req, res)})function fileHandler (filePath, contentType) {@@ -210,6 +208,11 @@ export function createServer ({repo, connections = []}) {}}+ function allVideosHandler(req, res) {+ const videos = repo.getVideos()+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(videos))+ }function captionsHandler(req, res) {// return vtt file of videoconst captionsPath = './data' + req.url.replace('captions', 'videos') + '.en.vtt'