git ssb

10+

Matt McKegg / patchwork



Tree: 6fd3ee341a376214993d0363c4c72161700b7fbc

Files: 6fd3ee341a376214993d0363c4c72161700b7fbc / modules / app / views.js

2850 bytesRaw
1var { h, Value, Dict, dictToCollection, map, computed } = require('mutant')
2var nest = require('depnest')
3
4exports.gives = nest('app.views')
5
6exports.create = function (api) {
7 return nest('app.views', function (renderPage, defaultViews) {
8 var views = Dict({})
9
10 var forwardHistory = []
11 var backHistory = []
12
13 if (defaultViews) {
14 defaultViews.forEach((view) => {
15 views.put(view, renderPage(view))
16 })
17 }
18
19 var lastViewed = {}
20
21 // delete cached view after 5 mins of last seeing
22 setInterval(() => {
23 views.keys().forEach((view) => {
24 if (!defaultViews.includes(view)) {
25 if (lastViewed[view] !== true && Date.now() - lastViewed[view] > (5 * 60e3) && view !== currentView()) {
26 views.delete(view)
27 }
28 }
29 })
30 }, 60e3)
31
32 var canGoForward = Value(false)
33 var canGoBack = Value(false)
34 var currentView = Value(defaultViews && defaultViews[0] || null)
35
36 var viewCollection = dictToCollection(views)
37 var html = h('div.main', map(viewCollection, (item) => {
38 return h('div.view', {
39 attributes: {
40 'data-href': item.key
41 },
42 hidden: computed([item.key, currentView], (a, b) => a !== b)
43 }, [ item.value ])
44 }))
45
46 return {
47 get: views.get,
48 defaultViews,
49 canGoForward,
50 canGoBack,
51 currentView,
52 setView,
53 goBack,
54 goForward,
55 html
56 }
57
58 // scoped
59
60 function goBack () {
61 if (backHistory.length) {
62 canGoForward.set(true)
63 forwardHistory.push(currentView())
64
65 var view = backHistory.pop()
66 loadView(view)
67
68 currentView.set(view)
69 canGoBack.set(backHistory.length > 0)
70 }
71 }
72
73 function goForward () {
74 if (forwardHistory.length) {
75 backHistory.push(currentView())
76
77 var view = forwardHistory.pop()
78 loadView(view)
79
80 currentView.set(view)
81 canGoForward.set(forwardHistory.length > 0)
82 canGoBack.set(true)
83 }
84 }
85
86 function loadView (view) {
87 if (!views.has(view)) {
88 var page = renderPage(view)
89 if (page.uniqueKey) {
90 views.keys().forEach(k => {
91 if (views.get(k).uniqueKey === page.uniqueKey) {
92 views.delete(k)
93 }
94 })
95 }
96 views.put(view, page)
97 }
98 }
99
100 function setView (view) {
101 loadView(view)
102
103 if (lastViewed[view] !== true) {
104 lastViewed[view] = Date.now()
105 }
106
107 if (currentView() && lastViewed[currentView()] !== true) {
108 lastViewed[currentView()] = Date.now()
109 }
110
111 if (view !== currentView()) {
112 canGoForward.set(false)
113 canGoBack.set(true)
114 forwardHistory.length = 0
115 backHistory.push(currentView())
116 currentView.set(view)
117 }
118 }
119 })
120}
121

Built with git-ssb-web