forked from WorldBrain/Memex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathomnibar.js
151 lines (128 loc) · 4.5 KB
/
omnibar.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import debounce from 'lodash/fp/debounce'
import escapeHtml from 'lodash/fp/escape'
import urlRegex from 'url-regex'
import qs from 'query-string'
import moment from 'moment'
import analytics from 'src/analytics'
import shortUrl from 'src/util/short-url'
import { search } from 'src/search'
import extractTimeFiltersFromQuery, {
queryFiltersDisplay,
} from 'src/util/nlp-time-filter'
import { OVERVIEW_URL } from 'src/background'
// Read which browser we are running in.
let browserName
;(async () => {
// XXX Firefox seems the only one currently implementing this function, but
// luckily that is enough for our current needs.
if (browser.runtime.getBrowserInfo !== undefined) {
const browserInfo = await browser.runtime.getBrowserInfo()
browserName = browserInfo.name
}
})()
function formatTime(timestamp, showTime) {
const m = moment(timestamp)
const inLastSevenDays = moment().diff(m, 'days') <= 7
if (showTime) {
return inLastSevenDays
? `🕒 ${m.format('HH:mm a ddd')}`
: `🕒 ${m.format('HH:mm a D/M/YYYY')}`
}
return inLastSevenDays ? m.format('ddd') : m.format('D/M/YYYY')
}
function setOmniboxMessage(text) {
browser.omnibox.setDefaultSuggestion({
description: text,
})
}
const pageToSuggestion = timeFilterApplied => doc => {
const url = escapeHtml(shortUrl(doc.url))
const title = escapeHtml(doc.content.title)
const time = formatTime(+doc.displayTime, timeFilterApplied)
return {
content: doc.url,
description:
browserName === 'Firefox'
? `${url} ${title} - ${time}`
: `<url>${url}</url> <dim>${title}</dim> - ${time}`,
}
}
let currentQuery
let latestResolvedQuery
async function makeSuggestion(query, suggest) {
currentQuery = query
// Show no suggestions if there is no query.
if (query.trim() === '') {
setOmniboxMessage('Type to search your memory.')
suggest([])
latestResolvedQuery = query
return
}
setOmniboxMessage('Searching your memory.. (press enter to search deeper)')
const queryForOldSuggestions = latestResolvedQuery
const queryFilters = extractTimeFiltersFromQuery(query)
const searchResults = await search({
...queryFilters,
limit: 5,
getTotalCount: true,
})
analytics.trackEvent({
category: 'Search',
action:
searchResults.totalCount > 0
? 'Successful omnibar search'
: 'Unsuccessful omnibar search',
name: queryFiltersDisplay(queryFilters),
value: searchResults.totalCount,
})
// A subsequent search could have already started and finished while we
// were busy searching, so we ensure we do not overwrite its results.
if (
currentQuery !== query &&
latestResolvedQuery !== queryForOldSuggestions
) {
return
}
if (searchResults.isBadTerm === true) {
setOmniboxMessage(
'Your search terms are very vague, please try and use more unique language',
)
} else if (searchResults.docs.length === 0) {
setOmniboxMessage('No results found for this query.')
} else {
setOmniboxMessage(
`Found these ${searchResults.totalCount} pages in your memory: (press enter to see all results)`,
)
}
const suggestions = searchResults.docs.map(
pageToSuggestion(queryFilters.startDate || queryFilters.endDate),
)
suggest(suggestions)
latestResolvedQuery = query
}
/**
* @param {string} text The omnibar text input.
* @returns {string} Overview page URL with `text` formatted as query string params.
*/
const formOverviewQuery = text => {
const queryFilters = extractTimeFiltersFromQuery(text)
const queryParams = qs.stringify(queryFilters)
return `${OVERVIEW_URL}?${queryParams}`
}
const acceptInput = (text, disposition) => {
// Either go to URL if input is valid URL, else form query for overview search using input terms
const url = urlRegex().test(text) ? text : formOverviewQuery(text)
switch (disposition) {
case 'currentTab':
browser.tabs.update({ url })
break
case 'newForegroundTab':
browser.tabs.create({ url })
break
case 'newBackgroundTab':
browser.tabs.create({ url, active: false })
break
}
}
browser.omnibox.onInputChanged.addListener(debounce(500)(makeSuggestion))
browser.omnibox.onInputEntered.addListener(acceptInput)