on 40697ed help sign in
webring/scripts/hallway.js
227 lines 9.0 kB history raw
1'use strict'
3const reChannel = /(\s|^)\/([a-zA-Z0-9]+)/g
4const reUser = /((\s|^)@<[a-zA-Z0-9./:\-_+~#= ]*>)/g
5const reTag = /(^|\s)(#[a-z\d-]+)/ig
6const reUrl = /((https?):\/\/(([-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b)([-a-zA-Z0-9@:%_+.~#?&//=]*)))/g
8function Hallway (sites) {
9 const feeds = {}
10 this.sites = sites
11 this._el = document.createElement('div')
12 this._el.id = 'hallway'
13 const filterAndPage = window.location.hash.split('^')
14 this.finder = { filter: stripHash(filterAndPage[0]), page: filterAndPage[1] || 1 }
15 this.cache = null
17 this._main = document.createElement('main')
18 this._main.id = 'entries'
19 this._footer = document.createElement('footer')
20 this._footer.id = 'footer'
21 this.readme = `<p>The <strong>Hallway</strong> is a decentralized forum, to join the conversation, add a <a href="https://github.com/XXIIVV/webring#joining-the-hallway">feed:</a> field to your entry in the <a href="https://github.com/XXIIVV/Webring/">webring</a>.</p>`
22 this.nav = `<p class='buttons'><a href='https://github.com/XXIIVV/webring'>Information</a> | <a href="index.html">The Portal</a> | <a href="wiki.html">The Wiki</a> | <a id="opml">OPML</a></p>`
23 this._footer.innerHTML = `${this.readme}${this.nav}`
25 this.install = function (host) {
26 this._el.appendChild(this._main)
27 this._el.appendChild(this._footer)
28 host.appendChild(this._el)
29 this.findFeeds()
30 }
32 this.start = function () {
33 this._main.innerHTML = 'Loading..'
34 this.fetchFeeds()
35 }
37 this.refresh = function (feeds = this.cache) {
38 const entries = this.findEntries(feeds)
39 const localEntries = entries.filter(entry => this.filterExternals(entry))
40 const channels = this.find(localEntries, 'channel')
41 const users = this.find(localEntries, 'author')
42 const tags = this.findTags(localEntries)
43 const relevantEntries = localEntries.filter(val => !this.finder.filter || (val.author === this.finder.filter || val.channel === this.finder.filter || val.tags.includes(this.finder.filter)))
45 const mainHtml = `
46 <div><ul>
47 ${localEntries.filter((val) => !this.finder.filter || (val.author === this.finder.filter || val.channel === this.finder.filter || val.tags.includes(this.finder.filter))).filter((_, id) => id < Number(this.finder.page) * 20 && id >= (Number(this.finder.page) - 1) * 20).reduce((acc, val) => acc + this.templateEntry(val) + '\n', '')}
48 </ul>
49 <div id='pagination'>
50 ${[...Array(Math.ceil(relevantEntries.length / 20)).keys()].reduce((acc, num) => `${acc}<span class='${Number(hallway.finder.page) === num + 1 ? 'selected' : ''}' onclick='filter("${this.finder.filter}^${num + 1}")'>${num + 1}</span>`, '')}
51 </div>
52 <a id='showbar' onclick="toggleVisibility('aside');"></a></div>`
54 const aside = `
55 <aside id='aside'>
56 <a id='hidebar' onclick="toggleVisibility('aside');"></a>
57 <ul id='channels'>
58 <li onclick='filter("")' class='${hallway.finder.filter === '' ? 'selected' : ''}'><a href='#'>hallway <span class='right'>${localEntries.length}</span></a></li>
59 ${Object.keys(channels).slice(0, 15).reduce((acc, val) => acc + `<li onclick='filter("${val}")' class='${hallway.finder.filter === val ? 'selected' : ''}'><a href='#${val}'>${val} <span class='right'>${channels[val]}</span></a></li>\n`, '')}
60 </ul>
61 <ul id='users'>
62 ${Object.keys(users).slice(0, 15).reduce((acc, val) => acc + `<li onclick='filter("${val}")' class='${hallway.finder.filter === val ? 'selected' : ''}' href='#${val}'>${val} <span class='right'>${users[val]}</span></li>\n`, '')}
63 </ul>
64 <ul id='tags'>
65 ${Object.keys(tags).slice(0, 15).reduce((acc, val) => acc + `<li onclick='filter("${val}")' class='${hallway.finder.filter === val ? 'selected' : ''}' href='#${val}'>#${val} <span class='right'>${tags[val]}</span></li>\n`, '')}
66 </ul>
67 </aside>`
69 this._main.innerHTML = `${mainHtml}${aside}`
71 if (feeds) {
72 this.cache = feeds
73 }
74 }
76 // Entries
78 this.filterExternals = function (entry) {
79 const matches = entry.body.match(reUser)
80 const locals = Object.keys(feeds)
81 return matches ? matches.some(match => locals.some(local => match.indexOf(feeds[local].path) !== -1)) : true
82 }
84 this.find = function (entries, key) {
85 const h = {}
86 for (const entry of entries) {
87 if (entry && entry[key]) {
88 h[entry[key]] = h[entry[key]] ? h[entry[key]] + 1 : 1
89 }
90 }
91 return h
92 }
94 this.findTags = function (entries) {
95 const tags = {}
96 for (const entry of entries) {
97 entry.tags.map(tag => {
98 tags[tag] = tags[tag] ? tags[tag] + 1 : 1
99 })
100 }
101 return tags
102 }
104 this.findEntries = function (feeds) {
105 const a = []
106 for (const id in feeds) {
107 for (const i in feeds[id].content) {
108 a.push(feeds[id].content[i])
109 }
110 }
111 return a.sort((a, b) => a.offset - b.offset)
112 }
114 this.findMention = function (found) {
115 const mention = Object.keys(feeds).filter(user => found.indexOf(feeds[user].path) > -1)
116 return ` <span class='user local'>${mention[0]}</span>`
117 }
119 this.templateEntry = function (entry) {
120 entry.html = entry.body
121 .replace(reChannel, `$1<span class='channel'>/$2</span>`)
122 .replace(reUser, this.findMention)
123 .replace(reTag, '$1<span class="tag">$2</span>')
124 .replace(reUrl, `<a target="_blank" href='$1'>$1</a>`)
126 const filter = window.location.hash.substr(1).replace(/\+/g, ' ').toLowerCase()
127 const highlight = filter === entry.author.toLowerCase()
128 const origin = feeds[entry.author].path
130 return `<li class='entry ${highlight ? 'highlight' : ''}'><span class='date'>${timeAgo(Date.parse(entry.date))}</span> <a class='author' href='${origin}' target='_blank'>${entry.author}</a> <span class='body'>${entry.html}</span></li>`
131 }
133 // Feeds
135 this.findFeeds = function () {
136 console.log('Finding feeds..')
137 for (const site of sites) {
138 if (site.feed && site.author) {
139 feeds[site.author] = { path: site.feed }
140 }
141 }
142 console.log(`Found ${Object.keys(feeds).length} feeds.`)
143 }
145 this.fetchFeeds = function () {
146 console.log(`Fetching ${Object.keys(feeds).length} feeds..`)
147 for (const id in feeds) {
148 this.fetchFeed(id, feeds[id])
149 }
150 }
152 this.fetchFeed = function (id, feed) {
153 console.log(`Fetching ${id}(${feed.path})..`)
154 fetch(feed.path, { cache: 'no-store' }).then(x => x.text()).then((content) => {
155 feeds[id].content = parseFeed(id, content)
156 this.refresh(feeds)
157 }).catch((err) => {
158 console.warn(`${id}`, err)
159 })
160 }
162 // Utils
164 function parseFeed (author, feed) {
165 const lines = feed.split('\n').filter((line) => line.substr(0, 1) !== '#')
166 const entries = []
167 for (const id in lines) {
168 const line = lines[id].trim()
169 if (line === '') { continue }
170 const parts = line.replace(' ', '\t').split('\t')
171 const date = parts[0].trim()
172 const body = escapeHtml(parts[1].trim()).trim()
173 const channel = body.substr(0, 1) === '/' ? body.split(' ')[0].substr(1).toLowerCase() : body.substr(0, 1) === '@' ? 'veranda' : 'lobby'
174 const tags = (body.match(reTag) || []).map(a => a.substr(a.indexOf('#') + 1).toLowerCase())
175 const offset = new Date() - new Date(date)
176 entries.push({ date, body, author, offset, channel, tags })
177 }
178 return entries
179 }
181 function timeAgo (dateParam) {
182 const date = typeof dateParam === 'object' ? dateParam : new Date(dateParam)
183 const today = new Date()
184 const yesterday = new Date(today - 86400000)
185 const seconds = Math.round((today - date) / 1000)
186 const minutes = Math.round(seconds / 60)
187 const isToday = today.toDateString() === date.toDateString()
188 const isYesterday = yesterday.toDateString() === date.toDateString()
190 if (seconds < 5) {
191 return 'just now'
192 } else if (seconds < 60) {
193 return `${seconds} seconds ago`
194 } else if (seconds < 90) {
195 return 'a minute ago'
196 } else if (minutes < 60) {
197 return `${minutes} minutes ago`
198 } else if (isToday) {
199 return `${Math.floor(minutes / 60)} hours ago`
200 } else if (isYesterday) {
201 return 'yesterday'
202 }
204 return `${Math.floor(minutes / 1440)} days ago`
205 }
208function toggleVisibility (id) {
209 const e = document.getElementById(id)
210 if (e.style.display === 'block') { e.style.display = 'none' } else { e.style.display = 'block' }
213function escapeHtml (unsafe) {
214 return unsafe.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;')
217function stripHash (hash) {
218 const decoded = decodeURIComponent(hash)
219 return decoded.charAt(0) === '#' ? decoded.substring(1) : decoded
222function filter (name) {
223 window.location.hash = name
224 const filterAndPage = window.location.hash.split('^')
225 hallway.finder = { filter: stripHash(filterAndPage[0]), page: filterAndPage[1] || 1 }
226 hallway.refresh()