on 6096efe help sign in
webring/scripts/hallway.js
210 lines 8.3 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>`
53 this._sidebar.innerHTML = `
54 <a id='hidebar' onclick="toggleVisibility('sidebar');"></a>
55 <ul id='channels'>
56 <li onclick='filter("")' class='${hallway.finder.filter === '' ? 'selected' : ''}'><a href='#'>hallway <span class='right'>${entries.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>`
66 if (feeds) {
67 this.cache = feeds
68 }
69 }
71 // Entries
73 this.find = function (entries, p) {
74 const h = {}
75 for (const id in entries) {
76 if (entries[id] && entries[id][p]) { h[entries[id][p]] = h[entries[id][p]] ? h[entries[id][p]] + 1 : 1 }
77 }
78 return h
79 }
81 this.findTags = function (entries) {
82 const tags = {}
83 for (const id in entries) {
84 const entry = entries[id]
85 entry.tags.map(tag => {
86 tags[tag] = tags[tag] ? tags[tag] + 1 : 1
87 })
88 }
89 return tags
90 }
92 this.findEntries = function (feeds) {
93 const a = []
94 for (const id in feeds) {
95 for (const i in feeds[id].content) {
96 a.push(feeds[id].content[i])
97 }
98 }
99 return a.sort((a, b) => a.offset - b.offset)
100 }
102 this.findMention = function (found) {
103 const mention = Object.keys(feeds).filter(user => found.indexOf(feeds[user].path) > -1)
104 return mention.length === 1 ? ` <span class='user'>@${mention[0]}</span>` : ` <span class='user'>${found}</span>`
105 }
107 this.templateEntry = function (entry) {
108 entry.html = entry.body
109 .replace(re_channel, `$1<span class='channel'>/$2</span>`)
110 .replace(re_user, this.findMention)
111 .replace(re_tag, `$1<span class='tag'>#$2</span>`)
112 .replace(re_url, `<a target="_blank" href='$1'>$1</a>`)
114 const filter = window.location.hash.substr(1).replace(/\+/g, ' ').toLowerCase()
115 const highlight = filter === entry.author.toLowerCase()
116 const origin = feeds[entry.author].path
118 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>`
119 }
121 // Feeds
123 this.findFeeds = function () {
124 console.log('Finding feeds..')
125 for (const site of sites) {
126 if (site.feed && site.author) {
127 feeds[site.author] = { path: site.feed }
128 }
129 }
130 console.log(`Found ${Object.keys(feeds).length} feeds.`)
131 }
133 this.fetchFeeds = function () {
134 console.log(`Fetching ${Object.keys(feeds).length} feeds..`)
135 for (const id in feeds) {
136 this.fetchFeed(id, feeds[id])
137 }
138 }
140 this.fetchFeed = function (id, feed) {
141 console.log(`Fetching ${id}(${feed.path})..`)
142 fetch(feed.path, { cache: 'no-store' }).then(x => x.text()).then((content) => {
143 feeds[id].content = parseFeed(id, content)
144 this.refresh(feeds)
145 }).catch((err) => {
146 console.warn(`${id}`, err)
147 })
148 }
150 // Utils
152 function parseFeed (author, feed) {
153 const lines = feed.split('\n').filter((line) => line.substr(0, 1) !== '#')
154 const entries = []
155 for (const id in lines) {
156 const line = lines[id].trim()
157 if (line === '') { continue }
158 const parts = line.replace(' ', '\t').split('\t')
159 const date = parts[0].trim()
160 const body = escapeHtml(parts[1].trim()).trim()
161 const channel = body.substr(0, 1) === '/' ? body.split(' ')[0].substr(1).toLowerCase() : body.substr(0, 1) === '@' ? 'veranda' : 'lobby'
162 const tags = (body.match(re_tag) || []).map(a => a.substr(a.indexOf('#') + 1).toLowerCase())
163 const offset = new Date() - new Date(date)
164 entries.push({ date, body, author, offset, channel, tags })
165 }
166 return entries
167 }
169 function timeAgo (dateParam) {
170 const date = typeof dateParam === 'object' ? dateParam : new Date(dateParam)
171 const today = new Date()
172 const yesterday = new Date(today - 86400000)
173 const seconds = Math.round((today - date) / 1000)
174 const minutes = Math.round(seconds / 60)
175 const isToday = today.toDateString() === date.toDateString()
176 const isYesterday = yesterday.toDateString() === date.toDateString()
178 if (seconds < 5) {
179 return 'just now'
180 } else if (seconds < 60) {
181 return `${seconds} seconds ago`
182 } else if (seconds < 90) {
183 return 'a minute ago'
184 } else if (minutes < 60) {
185 return `${minutes} minutes ago`
186 } else if (isToday) {
187 return `${Math.floor(minutes / 60)} hours ago`
188 } else if (isYesterday) {
189 return 'yesterday'
190 }
192 return `${Math.floor(minutes / 1440)} days ago`
193 }
196function toggleVisibility (id) {
197 var e = document.getElementById(id)
198 if (e.style.display == 'block') { e.style.display = 'none' } else { e.style.display = 'block' }
201function escapeHtml (unsafe) {
202 return unsafe.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;')
205function filter (name) {
206 window.location.hash = name
207 const filterAndPage = window.location.hash.split('^')
208 hallway.finder = { filter: filterAndPage[0].trim().replace('#', ''), page: filterAndPage[1] || 1 }
209 hallway.refresh()