on 393ddf9 help sign in
webring/scripts/hallway.js
219 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 = /([^&]|^)#([a-zA-Z0-9]+)/g
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._entries = document.createElement('div')
18 this._entries.id = 'entries'
19 this._sidebar = document.createElement('div')
20 this._sidebar.id = 'sidebar'
21 this._footer = document.createElement('p')
22 this._footer.id = 'footer'
23 this._footer.innerHTML = `The <b>Wiki</b> 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>.`
25 this.install = function (host) {
26 this._el.appendChild(this._entries)
27 this._el.appendChild(this._sidebar)
28 this._el.appendChild(this._footer)
29 host.appendChild(this._el)
30 this.findFeeds()
31 }
33 this.start = function () {
34 this._entries.innerHTML = 'Loading..'
35 this.fetchFeeds()
36 }
38 this.refresh = function (feeds = this.cache) {
39 const entries = this.findEntries(feeds)
40 const localEntries = entries.filter(entry => this.filterExternals(entry))
41 const channels = this.find(localEntries, 'channel')
42 const users = this.find(localEntries, 'author')
43 const tags = this.findTags(localEntries)
44 const relevantEntries = localEntries.filter(val => !this.finder.filter || (val.author === this.finder.filter || val.channel === this.finder.filter || val.tags.includes(this.finder.filter)))
46 this._entries.innerHTML = `
47 <ul>
48 ${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', '')}
49 </ul>
50 <div id='pagination'>
51 ${[...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>`, '')}
52 </div>
53 <a id='showbar' onclick="toggleVisibility('sidebar');"></a>`
55 this._sidebar.innerHTML = `
56 <a id='hidebar' onclick="toggleVisibility('sidebar');"></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>`
68 if (feeds) {
69 this.cache = feeds
70 }
71 }
73 // Entries
75 this.filterExternals = function (entry) {
76 const matches = entry.body.match(reUser)
77 const locals = Object.keys(feeds)
78 return matches ? matches.some(match => locals.some(local => match.indexOf(feeds[local].path) !== -1)) : true
79 }
81 this.find = function (entries, key) {
82 const h = {}
83 for (const entry of entries) {
84 if (entry && entry[key]) {
85 h[entry[key]] = h[entry[key]] ? h[entry[key]] + 1 : 1
86 }
87 }
88 return h
89 }
91 this.findTags = function (entries) {
92 const tags = {}
93 for (const entry of entries) {
94 entry.tags.map(tag => {
95 tags[tag] = tags[tag] ? tags[tag] + 1 : 1
96 })
97 }
98 return tags
99 }
101 this.findEntries = function (feeds) {
102 const a = []
103 for (const id in feeds) {
104 for (const i in feeds[id].content) {
105 a.push(feeds[id].content[i])
106 }
107 }
108 return a.sort((a, b) => a.offset - b.offset)
109 }
111 this.findMention = function (found) {
112 const mention = Object.keys(feeds).filter(user => found.indexOf(feeds[user].path) > -1)
113 return ` <span class='user local'>${mention[0]}</span>`
114 }
116 this.templateEntry = function (entry) {
117 entry.html = entry.body
118 .replace(reChannel, `$1<span class='channel'>/$2</span>`)
119 .replace(reUser, this.findMention)
120 .replace(reTag, `$1<span class='tag'>#$2</span>`)
121 .replace(reUrl, `<a target="_blank" href='$1'>$1</a>`)
123 const filter = window.location.hash.substr(1).replace(/\+/g, ' ').toLowerCase()
124 const highlight = filter === entry.author.toLowerCase()
125 const origin = feeds[entry.author].path
127 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>`
128 }
130 // Feeds
132 this.findFeeds = function () {
133 console.log('Finding feeds..')
134 for (const site of sites) {
135 if (site.feed && site.author) {
136 feeds[site.author] = { path: site.feed }
137 }
138 }
139 console.log(`Found ${Object.keys(feeds).length} feeds.`)
140 }
142 this.fetchFeeds = function () {
143 console.log(`Fetching ${Object.keys(feeds).length} feeds..`)
144 for (const id in feeds) {
145 this.fetchFeed(id, feeds[id])
146 }
147 }
149 this.fetchFeed = function (id, feed) {
150 console.log(`Fetching ${id}(${feed.path})..`)
151 fetch(feed.path, { cache: 'no-store' }).then(x => x.text()).then((content) => {
152 feeds[id].content = parseFeed(id, content)
153 this.refresh(feeds)
154 }).catch((err) => {
155 console.warn(`${id}`, err)
156 })
157 }
159 // Utils
161 function parseFeed (author, feed) {
162 const lines = feed.split('\n').filter((line) => line.substr(0, 1) !== '#')
163 const entries = []
164 for (const id in lines) {
165 const line = lines[id].trim()
166 if (line === '') { continue }
167 const parts = line.replace(' ', '\t').split('\t')
168 const date = parts[0].trim()
169 const body = escapeHtml(parts[1].trim()).trim()
170 const channel = body.substr(0, 1) === '/' ? body.split(' ')[0].substr(1).toLowerCase() : body.substr(0, 1) === '@' ? 'veranda' : 'lobby'
171 const tags = (body.match(reTag) || []).map(a => a.substr(a.indexOf('#') + 1).toLowerCase())
172 const offset = new Date() - new Date(date)
173 entries.push({ date, body, author, offset, channel, tags })
174 }
175 return entries
176 }
178 function timeAgo (dateParam) {
179 const date = typeof dateParam === 'object' ? dateParam : new Date(dateParam)
180 const today = new Date()
181 const yesterday = new Date(today - 86400000)
182 const seconds = Math.round((today - date) / 1000)
183 const minutes = Math.round(seconds / 60)
184 const isToday = today.toDateString() === date.toDateString()
185 const isYesterday = yesterday.toDateString() === date.toDateString()
187 if (seconds < 5) {
188 return 'just now'
189 } else if (seconds < 60) {
190 return `${seconds} seconds ago`
191 } else if (seconds < 90) {
192 return 'a minute ago'
193 } else if (minutes < 60) {
194 return `${minutes} minutes ago`
195 } else if (isToday) {
196 return `${Math.floor(minutes / 60)} hours ago`
197 } else if (isYesterday) {
198 return 'yesterday'
199 }
201 return `${Math.floor(minutes / 1440)} days ago`
202 }
205function toggleVisibility (id) {
206 const e = document.getElementById(id)
207 if (e.style.display === 'block') { e.style.display = 'none' } else { e.style.display = 'block' }
210function escapeHtml (unsafe) {
211 return unsafe.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;')
214function filter (name) {
215 window.location.hash = name
216 const filterAndPage = window.location.hash.split('^')
217 hallway.finder = { filter: filterAndPage[0].trim().replace('#', ''), page: filterAndPage[1] || 1 }
218 hallway.refresh()