on f181ace help sign in
webring/scripts/hallway.js
220 lines 8.6 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: filterAndPage[0].trim().replace('#', ''), 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._footer.innerHTML = `<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>`
23 this.install = function (host) {
24 this._el.appendChild(this._main)
25 this._el.appendChild(this._footer)
26 host.appendChild(this._el)
27 this.findFeeds()
28 }
30 this.start = function () {
31 this._main.innerHTML = 'Loading..'
32 this.fetchFeeds()
33 }
35 this.refresh = function (feeds = this.cache) {
36 const entries = this.findEntries(feeds)
37 const localEntries = entries.filter(entry => this.filterExternals(entry))
38 const channels = this.find(localEntries, 'channel')
39 const users = this.find(localEntries, 'author')
40 const tags = this.findTags(localEntries)
41 const relevantEntries = localEntries.filter(val => !this.finder.filter || (val.author === this.finder.filter || val.channel === this.finder.filter || val.tags.includes(this.finder.filter)))
43 const mainHtml = `
44 <div><ul>
45 ${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', '')}
46 </ul>
47 <div id='pagination'>
48 ${[...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>`, '')}
49 </div>
50 <a id='showbar' onclick="toggleVisibility('aside');"></a></div>`
52 const aside = `
53 <aside id='aside'>
54 <a id='hidebar' onclick="toggleVisibility('aside');"></a>
55 <ul id='channels'>
56 <li onclick='filter("")' class='${hallway.finder.filter === '' ? 'selected' : ''}'><a href='#'>hallway <span class='right'>${localEntries.length}</span></a></li>
57 ${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`, '')}
58 </ul>
59 <ul id='users'>
60 ${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`, '')}
61 </ul>
62 <ul id='tags'>
63 ${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`, '')}
64 </ul>
65 </aside>`
67 this._main.innerHTML = `${mainHtml}${aside}`
69 if (feeds) {
70 this.cache = feeds
71 }
72 }
74 // Entries
76 this.filterExternals = function (entry) {
77 const matches = entry.body.match(reUser)
78 const locals = Object.keys(feeds)
79 return matches ? matches.some(match => locals.some(local => match.indexOf(feeds[local].path) !== -1)) : true
80 }
82 this.find = function (entries, key) {
83 const h = {}
84 for (const entry of entries) {
85 if (entry && entry[key]) {
86 h[entry[key]] = h[entry[key]] ? h[entry[key]] + 1 : 1
87 }
88 }
89 return h
90 }
92 this.findTags = function (entries) {
93 const tags = {}
94 for (const entry of entries) {
95 entry.tags.map(tag => {
96 tags[tag] = tags[tag] ? tags[tag] + 1 : 1
97 })
98 }
99 return tags
100 }
102 this.findEntries = function (feeds) {
103 const a = []
104 for (const id in feeds) {
105 for (const i in feeds[id].content) {
106 a.push(feeds[id].content[i])
107 }
108 }
109 return a.sort((a, b) => a.offset - b.offset)
110 }
112 this.findMention = function (found) {
113 const mention = Object.keys(feeds).filter(user => found.indexOf(feeds[user].path) > -1)
114 return ` <span class='user local'>${mention[0]}</span>`
115 }
117 this.templateEntry = function (entry) {
118 entry.html = entry.body
119 .replace(reChannel, `$1<span class='channel'>/$2</span>`)
120 .replace(reUser, this.findMention)
121 .replace(reTag, '$1<span class="tag">$2</span>')
122 .replace(reUrl, `<a target="_blank" href='$1'>$1</a>`)
124 const filter = window.location.hash.substr(1).replace(/\+/g, ' ').toLowerCase()
125 const highlight = filter === entry.author.toLowerCase()
126 const origin = feeds[entry.author].path
128 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>`
129 }
131 // Feeds
133 this.findFeeds = function () {
134 console.log('Finding feeds..')
135 for (const site of sites) {
136 if (site.feed && site.author) {
137 feeds[site.author] = { path: site.feed }
138 }
139 }
140 console.log(`Found ${Object.keys(feeds).length} feeds.`)
141 }
143 this.fetchFeeds = function () {
144 console.log(`Fetching ${Object.keys(feeds).length} feeds..`)
145 for (const id in feeds) {
146 this.fetchFeed(id, feeds[id])
147 }
148 }
150 this.fetchFeed = function (id, feed) {
151 console.log(`Fetching ${id}(${feed.path})..`)
152 fetch(feed.path, { cache: 'no-store' }).then(x => x.text()).then((content) => {
153 feeds[id].content = parseFeed(id, content)
154 this.refresh(feeds)
155 }).catch((err) => {
156 console.warn(`${id}`, err)
157 })
158 }
160 // Utils
162 function parseFeed (author, feed) {
163 const lines = feed.split('\n').filter((line) => line.substr(0, 1) !== '#')
164 const entries = []
165 for (const id in lines) {
166 const line = lines[id].trim()
167 if (line === '') { continue }
168 const parts = line.replace(' ', '\t').split('\t')
169 const date = parts[0].trim()
170 const body = escapeHtml(parts[1].trim()).trim()
171 const channel = body.substr(0, 1) === '/' ? body.split(' ')[0].substr(1).toLowerCase() : body.substr(0, 1) === '@' ? 'veranda' : 'lobby'
172 const tags = (body.match(reTag) || []).map(a => a.substr(a.indexOf('#') + 1).toLowerCase())
173 const offset = new Date() - new Date(date)
174 entries.push({ date, body, author, offset, channel, tags })
175 }
176 return entries
177 }
179 function timeAgo (dateParam) {
180 const date = typeof dateParam === 'object' ? dateParam : new Date(dateParam)
181 const today = new Date()
182 const yesterday = new Date(today - 86400000)
183 const seconds = Math.round((today - date) / 1000)
184 const minutes = Math.round(seconds / 60)
185 const isToday = today.toDateString() === date.toDateString()
186 const isYesterday = yesterday.toDateString() === date.toDateString()
188 if (seconds < 5) {
189 return 'just now'
190 } else if (seconds < 60) {
191 return `${seconds} seconds ago`
192 } else if (seconds < 90) {
193 return 'a minute ago'
194 } else if (minutes < 60) {
195 return `${minutes} minutes ago`
196 } else if (isToday) {
197 return `${Math.floor(minutes / 60)} hours ago`
198 } else if (isYesterday) {
199 return 'yesterday'
200 }
202 return `${Math.floor(minutes / 1440)} days ago`
203 }
206function toggleVisibility (id) {
207 const e = document.getElementById(id)
208 if (e.style.display === 'block') { e.style.display = 'none' } else { e.style.display = 'block' }
211function escapeHtml (unsafe) {
212 return unsafe.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;')
215function filter (name) {
216 window.location.hash = name
217 const filterAndPage = window.location.hash.split('^')
218 hallway.finder = { filter: filterAndPage[0].trim().replace('#', ''), page: filterAndPage[1] || 1 }
219 hallway.refresh()