git ssb

10+

Matt McKegg / patchwork



Tree: 19dac8af2306fc228373a25ca2bf52c090e05e2e

Files: 19dac8af2306fc228373a25ca2bf52c090e05e2e / modules / app / views.js

2959 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) {
90 if (page.uniqueKey) {
91 views.keys().forEach(k => {
92 if (views.get(k).uniqueKey === page.uniqueKey) {
93 views.delete(k)
94 }
95 })
96 }
97 views.put(view, page)
98 }
99 }
100 }
101
102 function setView (view) {
103 loadView(view)
104
105 if (views.has(view)) {
106 if (lastViewed[view] !== true) {
107 lastViewed[view] = Date.now()
108 }
109
110 if (currentView() && lastViewed[currentView()] !== true) {
111 lastViewed[currentView()] = Date.now()
112 }
113
114 if (view !== currentView()) {
115 canGoForward.set(false)
116 canGoBack.set(true)
117 forwardHistory.length = 0
118 backHistory.push(currentView())
119 currentView.set(view)
120 }
121 }
122 }
123 })
124}
125

Built with git-ssb-web