Skip to content

add watchTree #166

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion packages/client/src/listeners.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import _ from 'lodash/fp.js'
import { eventEmitter, hasSome } from './util/futil.js'
import { encode } from './util/tree.js'

let matchesKeys = (keys, delta) => _.isEmpty(keys) || hasSome(keys, delta)

export let setupListeners = (tree) => {
let { on, emit } = eventEmitter()
let { on, onAny, emit } = eventEmitter()
// Assume first arg is node which might have path
tree.onChange = (node = {}, delta) => emit(encode(node.path), node, delta)
// Public API
Expand All @@ -12,4 +14,14 @@ export let setupListeners = (tree) => {
// Trigger watcher if keys match or no keys passed
if (_.isEmpty(keys) || hasSome(keys, delta)) f(node, delta)
})
tree.watchTree = (f, keys, path) =>
onAny((eventPath, node, delta) => {
// already encoded, so isParent not needed
// Use case is, for example, watching a group and all its children
// might be better solved by watchable group flags
let matchesPath = _.isEmpty(path) || _.startsWith(path, eventPath)
// TODO: should getNode return root for [] or empty paths?
let treeNode = path ? tree.getNode(path) : tree.tree
if (matchesPath && matchesKeys(keys, delta)) f(treeNode, node, delta)
})
}
45 changes: 45 additions & 0 deletions packages/client/src/listeners.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,51 @@ let AllTests = (ContextureClient) => {
await tree.mutate(['root', 'results'], { pageSize: 2 })
expect(resultWatcher).toBeCalledTimes(2)
})
it('watchTree', async () => {
let service = jest.fn(mockService({ delay: 10 }))
let tree = ContextureClient(
{ service, debounce: 1 },
{
key: 'root',
join: 'and',
children: [
{
key: 'filter',
type: 'facet',
field: 'facetfield',
values: ['some value'],
},
{ key: 'results', type: 'results' },
],
}
)
let filterDom = ''
let resultsDom = ''
tree.watchTree((root) => {
filterDom = `<div>
<h1>Facet<h1>
<b>Field: ${root.children[0].field}</b>
values: ${_.join(', ', root.children[0].values)}
</div>`
resultsDom = `<table>${_.map(
(result) =>
`\n<tr>${_.map((val) => `<td>${val}</td>`, _.values(result))}</tr>`,
root.children[1].context.results
)}
</table>`
})
expect(filterDom).toBe('')
let action = tree.mutate(['root', 'filter'], { values: ['other Value'] })
expect(filterDom).toBe(`<div>
<h1>Facet<h1>
<b>Field: facetfield</b>
values: other Value
</div>`)
await action
expect(resultsDom).toBe(`<table>
<tr><td>some result</td></tr>
</table>`)
})
})
}

Expand Down
18 changes: 12 additions & 6 deletions packages/client/src/util/futil.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,24 @@ export let hasSome = (keys, obj) => _.some(F.hasIn(obj), keys)

// Sets up basic event emitter/listener registry with an array of listeners per topic
// e.g. listeners: { topic1: [fn1, fn2, ...], topic2: [...], ... }
export let eventEmitter = (listeners = {}) => ({
listeners,
emit: (topic, ...args) => _.over(listeners[topic])(...args),
on(topic, fn) {
// Also emit on a special symbol for all topics
let allTopics = Symbol('allTopics')
export let eventEmitter = (listeners = {}) => {
let emit = (topic, ...args) => {
_.over(listeners[topic])(...args)
_.over(listeners[allTopics])(topic, ...args)
}
let on = (topic, fn) => {
if (!listeners[topic]) listeners[topic] = []
listeners[topic].push(fn)
// unlisten
return () => {
listeners[topic] = _.without(fn, listeners[topic])
}
},
})
}
let onAny = (fn) => on(allTopics, fn)
return { listeners, emit, on, onAny }
}

export let transformTreePostOrder = (next = F.traverse) =>
_.curry((f, x) => {
Expand Down