Files: 6dbc799416e7828344ed4ab645ebde51f3ddaea0 / app / html / tabs.js
2235 bytesRaw
1 | const nest = require('depnest') |
2 | const { h } = require('mutant') |
3 | const Tabs = require('hypertabs') |
4 | |
5 | exports.gives = nest({ |
6 | 'app.html.tabs': true |
7 | }) |
8 | |
9 | exports.needs = nest({ |
10 | 'app.html.menu': 'first', |
11 | 'app.html.searchBar': 'first', |
12 | 'app.sync.goTo': 'first', |
13 | 'app.sync.locationId': 'first', |
14 | 'history.obs.store': 'first', |
15 | 'history.sync.push': 'first' |
16 | }) |
17 | |
18 | exports.create = function (api) { |
19 | var _tabs |
20 | |
21 | return nest({ |
22 | 'app.html.tabs': tabs |
23 | }) |
24 | |
25 | function tabs (initialTabs = []) { |
26 | if (_tabs) return _tabs |
27 | |
28 | const onSelect = (indexes) => { |
29 | const { id } = _tabs.get(indexes[0]).content |
30 | |
31 | try { |
32 | var location = JSON.parse(id) |
33 | } catch (e) { |
34 | throw new Error('app.html.tabs expects all page ids to be stringified location objects') |
35 | } |
36 | |
37 | api.history.sync.push(location) |
38 | search.input.value = buildSearchBarTermFromLocation(location) |
39 | } |
40 | const onClose = (page) => { |
41 | var history = api.history.obs.store() |
42 | const prunedHistory = history().filter(loc => { |
43 | return api.app.sync.locationId(loc) !== page.id |
44 | }) |
45 | history.set(prunedHistory) |
46 | } |
47 | |
48 | const search = api.app.html.searchBar() |
49 | const menu = api.app.html.menu() |
50 | |
51 | _tabs = Tabs({ |
52 | onSelect, |
53 | onClose, |
54 | append: h('div.navExtra', [ search, menu ]) |
55 | }) |
56 | _tabs.currentPage = () => { |
57 | const currentPage = _tabs.get(_tabs.selected[0]) |
58 | return currentPage && currentPage.firstChild |
59 | } |
60 | _tabs.nextTab = () => _tabs.currentPage() && _tabs.selectRelative(1) |
61 | _tabs.previousTab = () => _tabs.currentPage() && _tabs.selectRelative(-1) |
62 | _tabs.closeCurrentTab = () => { _tabs.currentPage() && _tabs.remove(_tabs.selected[0]) } |
63 | |
64 | // # TODO: review - this works but is strange |
65 | initialTabs.forEach(p => api.app.sync.goTo(p)) |
66 | if (initialTabs[0]) api.app.sync.goTo(initialTabs[0]) |
67 | return _tabs |
68 | } |
69 | } |
70 | |
71 | // TODO - move this responsibility out to the searchBar? |
72 | function buildSearchBarTermFromLocation (location) { |
73 | const { page, query } = location |
74 | |
75 | if (page === 'search') return '?' + query |
76 | |
77 | const keys = Object.keys(location) |
78 | if (page && keys.length === 1) return '/' + page |
79 | |
80 | return keys |
81 | .map(k => location[k]) |
82 | .join(', ') |
83 | } |
84 |
Built with git-ssb-web