const smarkt = require('smarkt') const _ = require('lodash') const html = require('nanohtml') var archive = new DatArchive(window.location) function store (state, emitter) { state.library = [] state.info = {} state.covers = {} state.identity = '' emitter.on('DOMContentLoaded', function () { setIdentity() archive.readdir('zines') .then(zines => mapToState(zines)) }) emitter.on('update library', function (zine) { addToLibrary(zine) addZineInfo(zine.url) addZineCover(zine.url) }) function mapToState (zines) { zines.map(zine => { archive.readFile(`zines/${zine}`) .then(rawText => { var textJson = smarkt.parse(rawText) addToLibrary(textJson) addZineInfo(textJson.url) addZineCover(textJson.url) }) }) } function addToLibrary (text) { state.library = [...state.library, text] emitter.emit('pushState') } function addZineInfo (datUrl) { var zine = new DatArchive(datUrl) zine.readFile('distro/info.txt') .then(text => { mapInfoToState(text, zine['url']) }) } function addZineCover (datUrl) { var zine = new DatArchive(datUrl) zine.readdir('distro') .then(files => { mapCoverToState(files, zine['url']) }) } function mapInfoToState (info, datUrl) { var infoJson = smarkt.parse(info) state.info[datUrl] = infoJson emitter.emit('pushState') } function mapCoverToState (files, datUrl) { var cover = files.find(file => sansExtension(file) === 'cover') state.covers[datUrl] = `${datUrl}/distro/${cover}` emitter.emit('pushState') } async function setIdentity () { var info = await archive.getInfo() if (info.isOwner) { state.identity = 'librarian' emitter.emit('pushState') } else { state.identity = 'visitor' emitter.emit('pushstate') } } } function sansExtension (file) { return file.split('.')[0] } module.exports = store