@@ -1,154 +1,162 @@
1'use strict'
1'use strict'
3−function Wiki (sites) {
3+const Wiki = sites => {
4− const feeds = {}
4+ const entries = {}
5− this.sites = sites
5+ const main = document.getElementById('main')
6− this._el = document.createElement('div')
6+ const aside = document.getElementById('aside')
7− this._el.id = 'wiki'
7+ const progress = document.getElementById('progress')
8− this._sidebar = document.createElement('div')
8+ const progressCounter = Progress(sites.map(site => site.wiki))
9− this._sidebar.id = 'sidebar'
9+ const authors = new Set()
10− this._categories = document.createElement('ul')
10+ const terms = new Set()
11− this._categories.id = 'categories'
11+
12− this._entry = document.createElement('div')
12+ const storeEntry = (author, url, category, term, entry) => {
13− this._entry.id = 'entry'
13+ if (!(category in entries)) {
14−
14+ entries[category] = {}
15− this._footer = document.createElement('p')
15+ entries[category][term] = [{ entry, authors: [{ author, url }] }]
16− this._footer.id = 'footer'
16+ } else if (!(term in entries[category])) {
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>.`
17+ entries[category][term] = [{ entry, authors: [{ author, url }] }]
19− this.loc = ''
19+ const possibleIndex = entries[category][term].findIndex(existing => existing.entry === entry)
20− this.byName = {}
20+ possibleIndex > -1
21− this.byCat = {}
21+ ? entries[category][term][possibleIndex].authors.push({ author, url })
22− this.byAuthor = {}
22+ : entries[category][term].push({ entry, authors: [{ author, url }] })
24− this.install = (host) => {
24+ terms.add(term)
25− this._el.appendChild(this._entry)
25+ authors.add(author)
26− this._sidebar.appendChild(this._categories)
27− this._el.appendChild(this._sidebar)
28− this._el.appendChild(this._footer)
29− host.appendChild(this._el)
33− this.start = () => {
28+ const storeEntries = (author, url, category, entries) => {
34− this._entry.innerHTML = 'Loading..'
29+ Array.isArray(entries)
30+ ? storeEntry(author, url, category, 'list-definitions', entries)
31+ : Object.keys(entries).forEach(entry => storeEntry(author, url, category, entry, entries[entry]))
37− this.refresh = () => {
34+ const transform = (author, url, ndtl) => {
38− // Main
35+ Object.keys(ndtl).forEach(category => storeEntries(author, url, category, ndtl[category]))
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
48− const html = `Unknown: ${this.loc}. Retun <a href='#'>home</a>, or try a <a href='${this.random()}'>random page</a>.`
49− this._entry.innerHTML = html
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.`
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>
61− } , `<li ${wiki.at() ? 'class="selected"' : ''}>
62− <a href='#' data-msgs='${Object.keys(this.byName).length}'>home</a>
67− this.go = () => {
38+ const parse = (site, content) => {
68− this.loc = decodeURIComponent( window.location.hash.substr(1) ).toUpperCase()
39+ console.log('Wiki', 'Parsing ' + site.wiki)
69− this.refresh()
40+ const ndtl = indental(content)
41+ transform(site.author, site.url, ndtl)
72− this.at = (q = '') => {
44+ const selected = (key, category) => key.toLowerCase() === category.toLowerCase()
73− return this.loc.toUpperCase() === q.toUpperCase() || (this.cat(this.loc).toUpperCase() === q.toUpperCase() && q !== '')
45+ ? 'selected'
76− this.random = () => {
48+ const randomTerm = () => {
77− const keys = Object.keys(this.byCat)
49+ const keys = Object.keys(entries)
78 return keys[Math.floor(Math.random() * keys.length)]
50 return keys[Math.floor(Math.random() * keys.length)]
81− this.related = (name) => {
53+ const formatSideBarCat = (key, entries) => (currentHtml, cat) => {
82− return this.byCat[this.cat(name)]
54+ const catLength = Object.keys(entries[cat]).length
55+ const newHtml = `<li class='${selected(key, cat)}'}'>
56+ <a href='#${cat}' data-msgs='${catLength}'>${cat.toLowerCase()}</a>
58+ return `${currentHtml}${newHtml}`
85− this.cat = (name) => {
61+ const formatLinks = text => text.replace(
86− return this.byName[name] ? this.byName[name][0].cat : ''
62+ /\b((https?|dat):\/\/[^"\s]+)/g,
63+ '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>'
66+ const formatAuthor = (authors, author) => {
67+ return `${authors}<a class='author' target='_blank' href='${author.url}'> @${author.author}</a>`
89− this.templateRelated = (name) => {
70+ const formatEntry = (definitions, definition) => {
90− const relatedWords = this.related(name)
71+ const formatEntryList = entryList => entryList.reduce((items, item) => `${items}<li>${formatLinks(item)}</li>`, '')
91− const html = `<ul class='col3'>${relatedWords.reduce( (acc, item, id) =>
72+
92− { return `${acc}<li ${wiki.at(item.name) ? 'class="selected"' : ''}>
73+ const newHtml = typeof definition.entry === 'string'
93− <a href='#${item.name.toLowerCase()}'>${item.name.toLowerCase()}</a>
74+ ? `<li>${formatLinks(definition.entry)}
75+ - ${definition.authors.reduce(formatAuthor, '')}
95− }, '') }
77+ : `<li><ul>${formatEntryList(definition.entry)}
78+ - ${definition.authors.reduce(formatAuthor, '')}
96− </ul>`
79+ </ul></li>`
100− this.templateTerm = (name, entries) => {
81+ return `${definitions}${newHtml}`
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>`
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>`
84+ const formatEntries = entries => (currentHtml, category) => {
110− const htmlEntries = entries.reduce(formatEntry, '')
85+ const definitions = entries[category].reduce(formatEntry, '')
111− return `<ul class="term"><li class="name"><strong>${name.toLowerCase()}</strong></li>${htmlEntries}</ul>`
86+ const title = category === 'list-definitions'
88+ : `<li class='name'><strong>${category.toLowerCase()}</strong></li>`
89+ return `${currentHtml}<ul class='term'>${title}${definitions}</ul>`
114− this.fetch = () => {
92+ const findRelated = key => {
115− console.log('Wiki', 'Fetching..')
93+ const searchOtherCategories = entry => {
116− for (const site of sites) {
94+ return Object.keys(entries)
117− if (!site.wiki || !site.author) { continue }
95+ .filter(category => Object.keys(entries[category]).some(otherCat => otherCat === entry))
118− fetch(site.wiki, { cache: 'no-store' }).then(x => x.text()).then((content) => {
119− this.parse(site, content)
122− console.warn(`${site.wiki}`, err)
98+ const foundMatches = Object.keys(entries[key])
99+ .filter(entry => entry !== 'list-definitions')
100+ .map(searchOtherCategories)
101+ const flattened = [].concat.apply([], foundMatches)
102+ return Array.from(new Set(flattened)).filter(related => related !== key)
127− this.add = (name, value, cat, origin) => {
105+ const formatRelated = (allRelated, relatedCategory) => {
128− this.byName[name] = this.byName[name] || []
106+ const newHtml = `<span><a href='#${relatedCategory}'>/${relatedCategory.toLowerCase()}</a> </span>`
129− this.byName[name].push({ name, value, cat, origin })
107+ return `${allRelated}${newHtml}`
131− this.byCat[cat] = this.byCat[cat] || []
110+ const refresh = key => {
132− this.byCat[cat].push({ name, value, cat, origin })
111+ if (key) {
112+ if (entries[key] === undefined) return
113+ const items = Object.keys(entries[key]).sort().reduce(formatEntries(entries[key]), '')
114+ const relatedCategories = findRelated(key)
115+ const relatedHtml = relatedCategories.length > 0
116+ ? relatedCategories.reduce(formatRelated, 'Related categories: ')
118+ main.innerHTML = `<div class='related'><h1>${key}</h1>${relatedHtml}</div>${items}`
120+ const html = `Click a /topic to get started, or try a <a href='#${randomTerm()}'>random page</a>`
121+ const stats = `The wiki contains ${terms.size} terms in ${Object.keys(entries).length} categories, from ${authors.size} authors.`
122+ main.innerHTML = `<h1>WIKI</h1>${html}<br />${stats}`
134− this.byAuthor[origin.author] = this.byAuthor[origin.author] || []
125+ const homeCat = `<li class='${selected(key, '')}'>
135− this.byAuthor[origin.author].push({ name, value, cat, origin })
126+ <a href='#' data-msgs='${terms.size}'>home</a>
128+ const cats = Object.keys(entries).sort().reduce(formatSideBarCat(key, entries), homeCat)
129+ aside.innerHTML = `<ul>${cats}</ul>`
138− this.parse = (site, content) => {
132+ const refreshProgress = () => {
139− console.log('Wiki', 'Parsing ' + site.wiki)
133+ progress.innerHTML = `${progressCounter}`
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)
149− String.prototype.toUrl = function () { return this.toLowerCase().replace(/ /g, '+').replace(/[^0-9a-z+:\-./~]/gi, '').trim() }
136+ return {
137+ initialize: hash => {
138+ console.log('Wiki', 'Fetching...')
140+ sites.filter(site => site.wiki && site.author).forEach(site => {
141+ fetch(site.wiki, { cache: 'no-store' }).then(x => x.text()).then(content => {
142+ parse(site, content)
143+ refresh(stripHash(hash))
144+ progressCounter.success(site.wiki).then(refreshProgress)
146+ console.warn(`${site.wiki}`, err)
147+ progressCounter.failure(site.wiki).then(refreshProgress)
151+ refresh: key => { refresh(key) }
151− window.onload = this.go
155+const stripHash = hash => {
152− window.onhashchange = this.go
156+ const decoded = decodeURIComponent(hash)
157+ return decoded.charAt(0) === '#' ? decoded.substring(1) : decoded
160+window.addEventListener('hashchange', () => {
161+ wiki.refresh(stripHash(window.location.hash).toUpperCase())