@@ -1,154 +1,136 @@
11'use strict'
22
3−function Wiki (sites) {
4− const feeds = {}
5− this.sites = sites
6− this._el = document.createElement('div')
7− this._el.id = 'wiki'
8− this._sidebar = document.createElement('div')
9− this._sidebar.id = 'sidebar'
10− this._categories = document.createElement('ul')
11− this._categories.id = 'categories'
12− this._entry = document.createElement('div')
13− this._entry.id = 'entry'
14−
15− this._footer = document.createElement('p')
16− this._footer.id = 'footer'
17− this._footer.innerHTML = `The <strong>Wiki</strong> is a decentralized encyclopedia, to join the conversation, add a <a href="https://github.com/XXIIVV/webring#joining-the-wiki">wiki:</a> field to your entry in the <a href="https://github.com/XXIIVV/Webring/">webring</a>.`
18−
19− this.loc = ''
20− this.byName = {}
21− this.byCat = {}
22− this.byAuthor = {}
23−
24− this.install = (host) => {
25− this._el.appendChild(this._entry)
26− this._sidebar.appendChild(this._categories)
27− this._el.appendChild(this._sidebar)
28− this._el.appendChild(this._footer)
29− host.appendChild(this._el)
30− this.fetch()
31− }
32−
33− this.start = () => {
34− this._entry.innerHTML = 'Loading..'
35− }
36−
37− this.refresh = () => {
38− // Main
39− if (this.loc) {
40− if (this.byCat[this.loc]) {
41− const formatHtml = (entries, entry) => `${entries} ${this.templateTerm(entry.name, this.byName[entry.name])}<br />`
42− const html = this.byCat[this.loc].reduce(formatHtml, '')
43− this._entry.innerHTML = html
44− } else if (this.byName[this.loc]) {
45− const html = `${this.templateTerm(this.loc, this.byName[this.loc])}<br />${this.templateRelated(this.loc)}`
46− this._entry.innerHTML = html
47− } else {
48− const html = `Unknown: ${this.loc}. Return <a href='#'>home</a>, or try a <a href='${this.random()}'>random page</a>.`
49− this._entry.innerHTML = html
50− }
3+const Wiki = sites => {
4+ const entries = {}
5+ const main = document.getElementById('main')
6+ const aside = document.getElementById('aside')
7+ const authors = new Set()
8+ const terms = new Set()
9+
10+ const storeEntry = (author, url, parent, cat, entry) => {
11+ if (!(parent in entries)) {
12+ entries[parent] = {}
13+ entries[parent][cat] = [{ entry, author, url }]
14+ } else if (!(cat in entries[parent])) {
15+ entries[parent][cat] = [{ entry, author, url }]
5116 } else {
52− this._entry.innerHTML = `Click a /topic to get started, or try a <a href='#${this.random()}'>random page</a>.<br />The wiki contains ${Object.keys(this.byName).length} terms, in ${Object.keys(this.byCat).length} categories, by ${Object.keys(this.byAuthor).length} authors.`
17+ entries[parent][cat].push({ entry, author, url })
5318 }
54− // Sidebar
55− this._categories.innerHTML = Object.keys(this.byCat).reduce((acc, id) =>
56− { return this.byCat[id].length > 5
57− ? `${acc}<li ${wiki.at(id) ? 'class="selected"' : ''}>
58− <a href='#${id}' data-msgs='${this.byCat[id].length}'>${id}</a>
59− </li>`
60− : acc
61− } , `<li ${wiki.at() ? 'class="selected"' : ''}>
62− <a href='#' data-msgs='${Object.keys(this.byName).length}'>home</a>
63− </li>`
64− )
19+ terms.add(cat)
20+ authors.add(author)
6521 }
6622
67− this.go = () => {
68− this.loc = decodeURIComponent( window.location.hash.substr(1) ).toUpperCase()
69− this.refresh()
23+ const storeEntries = (author, url, parent, entries) => {
24+ Array.isArray(entries)
25+ ? storeEntry(author, url, parent, 'list-definitions', entries)
26+ : Object.keys(entries).forEach(entry => storeEntry(author, url, parent, entry, entries[entry]))
7027 }
7128
72− this.at = (q = '') => {
73− return this.loc.toUpperCase() === q.toUpperCase() || (this.cat(this.loc).toUpperCase() === q.toUpperCase() && q !== '')
29+ const transform = (author, url, ndtl) => {
30+ Object.keys(ndtl).forEach(cat => storeEntries(author, url, cat, ndtl[cat]))
7431 }
7532
76− this.random = () => {
77− const keys = Object.keys(this.byCat)
78− return keys[Math.floor(Math.random() * keys.length)]
33+ const parse = (site, content) => {
34+ console.log('Wiki', 'Parsing ' + site.wiki)
35+ const ndtl = indental(content)
36+ transform(site.author, site.url, ndtl)
7937 }
8038
81− this.related = (name) => {
82− return this.byCat[this.cat(name)]
83− }
39+ const selected = (key, category) => key.toLowerCase() === category.toLowerCase()
40+ ? 'selected'
41+ : ''
8442
85− this.cat = (name) => {
86− return this.byName[name] ? this.byName[name][0].cat : ''
43+ const formatSideBarCat = (key, entries) => (currentHtml, cat) => {
44+ const catLength = Object.keys(entries[cat]).length
45+ const newHtml = `<li class='${selected(key, cat)}'}'>
46+ <a href='#${cat}' data-msgs='${catLength}'>${cat.toLowerCase()}</a>
47+ </li>`
48+ return `${currentHtml}${newHtml}`
8749 }
8850
89− this.templateRelated = (name) => {
90− const relatedWords = this.related(name)
91− const html = `<ul class='col3'>${relatedWords.reduce( (acc, item, id) =>
92− { return `${acc}<li ${wiki.at(item.name) ? 'class="selected"' : ''}>
93− <a href='#${item.name.toLowerCase()}'>${item.name.toLowerCase()}</a>
94− </li>`
95− }, '') }
96− </ul>`
97− return html
98− }
51+ const formatEntry = (definitions, definition) => {
52+ const formatEntryList = entryList => entryList.reduce((items, item) => `${items}<li>${item}</li>`, '')
9953
100− this.templateTerm = (name, entries) => {
101− const formatEntry = (acc, entry) => {
102− if (typeof entry.value === 'string') {
103− return `${acc}<li>${entry.value}<a class='author' target='_blank' href='${entry.origin.url}'> — @${entry.origin.author}</a></li>`
104− } else {
105− const listItems = entry.value.reduce((items, item) => `${items}<li>${item}</li>`, '')
106− return `${acc}<li><ul>${listItems}<a class='author' target='_blank' href='${entry.origin.url}'> — @${entry.origin.author}</a></ul></li>`
107− }
108− }
54+ const newHtml = typeof definition.entry === 'string'
55+ ? `<li>${definition.entry}
56+ <a class='author' target='_blank' href='${definition.url}'> - @${definition.author}</a>
57+ </li>`
58+ : `<li><ul>${formatEntryList(definition.entry)}
59+ <a class='author' target='_blank' href='${definition.url}'> — @${definition.author}</a>
60+ </ul></li>`
10961
110− const htmlEntries = entries.reduce(formatEntry, '')
111− return `<ul class="term"><li class="name"><strong>${name.toLowerCase()}</strong></li>${htmlEntries}</ul>`
62+ return `${definitions}${newHtml}`
11263 }
11364
114− this.fetch = () => {
115− console.log('Wiki', 'Fetching..')
116− for (const site of sites) {
117− if (!site.wiki || !site.author) { continue }
118− fetch(site.wiki, { cache: 'no-store' }).then(x => x.text()).then((content) => {
119− this.parse(site, content)
120− this.refresh(feeds)
121− }).catch((err) => {
122− console.warn(`${site.wiki}`, err)
123− })
124− }
65+ const formatEntries = entries => (currentHtml, category) => {
66+ const definitions = entries[category].reduce(formatEntry, '')
67+ const title = category === 'list-definitions'
68+ ? ''
69+ : `<li class='name'><strong>${category.toLowerCase()}</strong></li>`
70+ return `${currentHtml}<ul class='term'>${title}${definitions}</ul>`
12571 }
12672
127− this.add = (name, value, cat, origin) => {
128− this.byName[name] = this.byName[name] || []
129− this.byName[name].push({ name, value, cat, origin })
73+ const findRelated = key => {
74+ const searchOtherCategories = entry => {
75+ return Object.keys(entries)
76+ .filter(category => Object.keys(entries[category]).some(otherCat => otherCat === entry))
77+ }
13078
131− this.byCat[cat] = this.byCat[cat] || []
132− this.byCat[cat].push({ name, value, cat, origin })
79+ const foundMatches = Object.keys(entries[key])
80+ .filter(entry => entry !== 'list-definitions')
81+ .map(searchOtherCategories)
82+ const flattened = [].concat.apply([], foundMatches)
83+ return Array.from(new Set(flattened)).filter(related => related !== key)
84+ }
13385
134− this.byAuthor[origin.author] = this.byAuthor[origin.author] || []
135− this.byAuthor[origin.author].push({ name, value, cat, origin })
86+ const formatRelated = (allRelated, relatedCategory) => {
87+ const newHtml = `<span><a href='#${relatedCategory}'>/${relatedCategory.toLowerCase()}</a> </span>`
88+ return `${allRelated}${newHtml}`
13689 }
13790
138− this.parse = (site, content) => {
139− console.log('Wiki', 'Parsing ' + site.wiki)
140− const cats = indental(content)
141− for (const cat in cats) {
142− const terms = cats[cat]
143− for (const name in terms) {
144− this.add(name, terms[name], cat, site)
145− }
91+ const refresh = key => {
92+ if (key) {
93+ if (entries[key] === undefined) return
94+ const items = Object.keys(entries[key]).sort().reduce(formatEntries(entries[key]), '')
95+ const relatedCategories = findRelated(key)
96+ const relatedHtml = relatedCategories.length > 0
97+ ? relatedCategories.reduce(formatRelated, 'Related categories: ')
98+ : ''
99+ main.innerHTML = `<div class='related'><h1>${key}</h1>${relatedHtml}</div>${items}`
100+ } else {
101+ const html = `Click a /topic to get started, or try a random page`
102+ const stats = `The wiki contains ${terms.size} terms in ${Object.keys(entries).length} categories, from ${authors.size} authors.`
103+ main.innerHTML = `${html}<br />${stats}`
146104 }
105+
106+ const homeCat = `<li class='${selected(key, '')}'>
107+ <a href='#' data-msgs='${terms.size}'>home</a>
108+ </li>`
109+ const cats = Object.keys(entries).sort().reduce(formatSideBarCat(key, entries), homeCat)
110+ aside.innerHTML = `<ul>${cats}</ul>`
147111 }
148112
149− String.prototype.toUrl = function () { return this.toLowerCase().replace(/ /g, '+').replace(/[^0-9a-z+:\-./~]/gi, '').trim() }
113+ return {
114+ initialize: hash => {
115+ console.log('Wiki', 'Fetching...')
116+ sites.filter(site => site.wiki && site.author).forEach(site => {
117+ fetch(site.wiki, { cache: 'no-store' }).then(x => x.text()).then(content => {
118+ parse(site, content)
119+ refresh(stripHash(hash))
120+ }).catch((err) => {
121+ console.warn(`${site.wiki}`, err)
122+ })
123+ })
124+ },
125+ refresh: key => { refresh(key) }
126+ }
127+}
150128
151− window.onload = this.go
152− window.onhashchange = this.go
129+const stripHash = hash => {
130+ const decoded = decodeURIComponent(hash)
131+ return decoded.charAt(0) === '#' ? decoded.substring(1) : decoded
153132}
154133
134+window.addEventListener('hashchange', () => {
135+ wiki.refresh(stripHash(window.location.hash).toUpperCase())
136+})