forked from WebMemex/webmemex-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactions.js
66 lines (51 loc) · 2.34 KB
/
actions.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
import { createAction } from 'redux-act'
import { onDatabaseChange } from 'src/pouchdb'
import { filterVisitsByQuery } from 'src/search'
import { ourState } from './selectors'
// == Simple commands to change the state in reducers ==
export const setQuery = createAction('overview/setQuery')
export const setSearchResult = createAction('overview/setSearchResult')
export const showLoadingIndicator = createAction('overview/showLoadingIndicator')
export const hideLoadingIndicator = createAction('overview/hideLoadingIndicator')
// == Actions that trigger other actions ==
// Initialisation
export function init() {
return function (dispatch, getState) {
// Perform an initial search to populate the view (empty query = get all docs)
dispatch(refreshSearch({loadingIndicator:true}))
// Track database changes, to e.g. trigger search result refresh
onDatabaseChange(change => dispatch(handlePouchChange({change})))
}
}
// Search for docs matching the current query, update the results
export function refreshSearch({loadingIndicator=false}) {
return function (dispatch, getState) {
const query = ourState(getState()).query
const oldResult = ourState(getState()).searchResult
if (loadingIndicator) {
// Show to the user that search is busy
dispatch(showLoadingIndicator())
}
filterVisitsByQuery({
query,
includeContext: true,
}).then(searchResult => {
if (loadingIndicator) {
// Hide our nice loading animation again.
dispatch(hideLoadingIndicator())
}
// First check if the query and result changed in the meantime.
if (ourState(getState()).query !== query
&& ourState(getState()).searchResult !== oldResult) {
// The query already changed while we were searching, and the
// currently displayed result may already be more recent than
// ours. So we did all that effort for nothing.
return
}
// Set the result to have it displayed to the user.
dispatch(setSearchResult({searchResult}))
})
}
}
// Report a change in the database, to e.g. trigger a search refresh
export const handlePouchChange = createAction('overview/handlePouchChange')