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