on 727ceb6 help sign in
webring/scripts/hallway.js
211 lines 8.4 kB history raw
1'use strict'
3const re_channel = /(\s|^)\/([a-zA-Z0-9]+)/g
4const re_user = /((\s|^)@<[a-zA-Z0-9./:\-_\+~#= ]*>)/g
5const re_tag = /([^&]|^)\#([a-zA-Z0-9]+)/g
6const re_url = /((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 channels = this.find(entries, 'channel')
41 const users = this.find(entries, 'author')
42 const tags = this.findTags(entries)
43 const relevantEntries = entries.filter(val => !this.finder.filter || (val.author === this.finder.filter || val.channel === this.finder.filter || val.tags.includes(this.finder.filter)))
45 this._entries.innerHTML = `
46 <ul>
47 ${entries.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('sidebar');"></a>`
54 this._sidebar.innerHTML = `
55 <a id='hidebar' onclick="toggleVisibility('sidebar');"></a>
56 <ul id='channels'>
57 <li onclick='filter("")' class='${hallway.finder.filter === '' ? 'selected' : ''}'><a href='#'>hallway <span class='right'>${entries.length}</span></a></li>
58 ${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`, '')}
59 </ul>
60 <ul id='users'>
61 ${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`, '')}
62 </ul>
63 <ul id='tags'>
64 ${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`, '')}
65 </ul>`
67 if (feeds) {
68 this.cache = feeds
69 }
70 }
72 // Entries
74 this.find = function (entries, p) {
75 const h = {}
76 for (const id in entries) {
77 if (entries[id] && entries[id][p]) { h[entries[id][p]] = h[entries[id][p]] ? h[entries[id][p]] + 1 : 1 }
78 }
79 return h
80 }
82 this.findTags = function (entries) {
83 const tags = {}
84 for (const id in entries) {
85 const entry = entries[id]
86 entry.tags.map(tag => {
87 tags[tag] = tags[tag] ? tags[tag] + 1 : 1
88 })
89 }
90 return tags
91 }
93 this.findEntries = function (feeds) {
94 const a = []
95 for (const id in feeds) {
96 for (const i in feeds[id].content) {
97 a.push(feeds[id].content[i])
98 }
99 }
100 return a.sort((a, b) => a.offset - b.offset)
101 }
103 this.findMention = function (found) {
104 const mention = Object.keys(feeds).filter(user => found.indexOf(feeds[user].path) > -1)
105 return mention.length === 1 ? ` <span class='user'>@${mention[0]}</span>` : ` <span class='user'>${found}</span>`
106 }
108 this.templateEntry = function (entry) {
109 entry.html = entry.body
110 .replace(re_channel, `$1<span class='channel'>/$2</span>`)
111 .replace(re_user, this.findMention)
112 .replace(re_tag, `$1<span class='tag'>#$2</span>`)
113 .replace(re_url, `<a target="_blank" href='$1'>$1</a>`)
115 const filter = window.location.hash.substr(1).replace(/\+/g, ' ').toLowerCase()
116 const highlight = filter === entry.author.toLowerCase()
117 const origin = feeds[entry.author].path
119 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>`
120 }
122 // Feeds
124 this.findFeeds = function () {
125 console.log('Finding feeds..')
126 for (const site of sites) {
127 if (site.feed && site.author) {
128 feeds[site.author] = { path: site.feed }
129 }
130 }
131 console.log(`Found ${Object.keys(feeds).length} feeds.`)
132 }
134 this.fetchFeeds = function () {
135 console.log(`Fetching ${Object.keys(feeds).length} feeds..`)
136 for (const id in feeds) {
137 this.fetchFeed(id, feeds[id])
138 }
139 }
141 this.fetchFeed = function (id, feed) {
142 console.log(`Fetching ${id}(${feed.path})..`)
143 fetch(feed.path, { cache: 'no-store' }).then(x => x.text()).then((content) => {
144 feeds[id].content = parseFeed(id, content)
145 this.refresh(feeds)
146 }).catch((err) => {
147 console.warn(`${id}`, err)
148 })
149 }
151 // Utils
153 function parseFeed (author, feed) {
154 const lines = feed.split('\n').filter((line) => line.substr(0, 1) !== '#')
155 const entries = []
156 for (const id in lines) {
157 const line = lines[id].trim()
158 if (line === '') { continue }
159 const parts = line.replace(' ', '\t').split('\t')
160 const date = parts[0].trim()
161 const body = escapeHtml(parts[1].trim()).trim()
162 const channel = body.substr(0, 1) === '/' ? body.split(' ')[0].substr(1).toLowerCase() : body.substr(0, 1) === '@' ? 'veranda' : 'lobby'
163 const tags = (body.match(re_tag) || []).map(a => a.substr(a.indexOf('#') + 1).toLowerCase())
164 const offset = new Date() - new Date(date)
165 entries.push({ date, body, author, offset, channel, tags })
166 }
167 return entries
168 }
170 function timeAgo (dateParam) {
171 const date = typeof dateParam === 'object' ? dateParam : new Date(dateParam)
172 const today = new Date()
173 const yesterday = new Date(today - 86400000)
174 const seconds = Math.round((today - date) / 1000)
175 const minutes = Math.round(seconds / 60)
176 const isToday = today.toDateString() === date.toDateString()
177 const isYesterday = yesterday.toDateString() === date.toDateString()
179 if (seconds < 5) {
180 return 'just now'
181 } else if (seconds < 60) {
182 return `${seconds} seconds ago`
183 } else if (seconds < 90) {
184 return 'a minute ago'
185 } else if (minutes < 60) {
186 return `${minutes} minutes ago`
187 } else if (isToday) {
188 return `${Math.floor(minutes / 60)} hours ago`
189 } else if (isYesterday) {
190 return 'yesterday'
191 }
193 return `${Math.floor(minutes / 1440)} days ago`
194 }
197function toggleVisibility (id) {
198 var e = document.getElementById(id)
199 if (e.style.display == 'block') { e.style.display = 'none' } else { e.style.display = 'block' }
202function escapeHtml (unsafe) {
203 return unsafe.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;')
206function filter (name) {
207 window.location.hash = name
208 const filterAndPage = window.location.hash.split('^')
209 hallway.finder = { filter: filterAndPage[0].trim().replace('#', ''), page: filterAndPage[1] || 1 }
210 hallway.refresh()