aberdeen 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,117 @@
1
+ import {withEmitHandler} from 'aberdeen'
2
+
3
+ type ObsCollection = any
4
+ type Patch = Map<ObsCollection, Map<any, [any, any]>>;
5
+
6
+
7
+ function recordPatch(func: () => void): Patch {
8
+ const recordingPatch = new Map()
9
+ withEmitHandler(function(index, newData, oldData) {
10
+ addToPatch(recordingPatch, this, index, newData, oldData)
11
+ }, func)
12
+ return recordingPatch
13
+ }
14
+
15
+ function addToPatch(patch: Patch, collection: ObsCollection, index: any, newData: any, oldData: any) {
16
+ let collectionMap = patch.get(collection)
17
+ if (!collectionMap) {
18
+ collectionMap = new Map()
19
+ patch.set(collection, collectionMap)
20
+ }
21
+ let prev = collectionMap.get(index)
22
+ if (prev) oldData = prev[1]
23
+ if (newData === oldData) collectionMap.delete(index)
24
+ else collectionMap.set(index, [newData, oldData])
25
+ }
26
+
27
+ function emitPatch(patch: Patch) {
28
+ for(let [collection, collectionMap] of patch) {
29
+ for(let [index, [newData, oldData]] of collectionMap) {
30
+ collection.emitChange(index, newData, oldData)
31
+ }
32
+ }
33
+ }
34
+
35
+ function mergePatch(target: Patch, source: Patch, reverse: boolean = false) {
36
+ for(let [collection, collectionMap] of source) {
37
+ for(let [index, [newData, oldData]] of collectionMap) {
38
+ addToPatch(target, collection, index, reverse ? oldData : newData, reverse ? newData : oldData)
39
+ }
40
+ }
41
+ }
42
+
43
+ function silentlyApplyPatch(patch: Patch, force: boolean = false): boolean {
44
+ for(let [collection, collectionMap] of patch) {
45
+ for(let [index, [newData, oldData]] of collectionMap) {
46
+ let actualData = collection.rawGet(index)
47
+ if (actualData !== oldData) {
48
+ if (force) setTimeout(() => { throw new Error(`Applying invalid patch: data ${actualData} is unequal to expected old data ${oldData} for index ${index}`)}, 0)
49
+ else return false
50
+ }
51
+ }
52
+ }
53
+ for(let [collection, collectionMap] of patch) {
54
+ for(let [index, [newData, oldData]] of collectionMap) {
55
+ collection.rawSet(index, newData)
56
+ }
57
+ }
58
+ return true
59
+ }
60
+
61
+
62
+ const appliedPredictions: Array<Patch> = []
63
+
64
+ /**
65
+ * Run the provided function, while treating all changes to Observables as predictions,
66
+ * meaning they will be reverted when changes come back from the server (or some other
67
+ * async source).
68
+ * @param predictFunc The function to run. It will generally modify some Observables
69
+ * to immediately reflect state (as closely as possible) that we expect the server
70
+ * to communicate back to us later on.
71
+ * @returns A `Patch` object. Don't modify it. This is only meant to be passed to `applyCanon`.
72
+ */
73
+ export function applyPrediction(predictFunc: () => void): Patch {
74
+ let patch = recordPatch(predictFunc)
75
+ appliedPredictions.push(patch)
76
+ emitPatch(patch)
77
+ return patch
78
+ }
79
+
80
+ /**
81
+ * Temporarily revert all outstanding predictions, optionally run the provided function
82
+ * (which will generally make authoritative changes to the data based on a server response),
83
+ * and then attempt to reapply the predictions on top of the new canonical state, dropping
84
+ * any predictions that can no longer be applied cleanly (the data has been modified) or
85
+ * that were specified in `dropPredictions`.
86
+ *
87
+ * All of this is done such that redraws are only triggered if the overall effect is an
88
+ * actual change to an `Observable`.
89
+ * @param canonFunc The function to run without any predictions applied. This will typically
90
+ * make authoritative changes to the data, based on a server response.
91
+ * @param dropPredictions An optional list of predictions (as returned by `applyPrediction`)
92
+ * to undo. Typically, when a server response for a certain request is being handled,
93
+ * you'd want to drop the prediction that was done for that request.
94
+ */
95
+ export function applyCanon(canonFunc?: (() => void), dropPredictions: Array<Patch> = []) {
96
+
97
+ let resultPatch = new Map()
98
+ for(let prediction of appliedPredictions) mergePatch(resultPatch, prediction, true)
99
+ silentlyApplyPatch(resultPatch, true)
100
+
101
+ for(let prediction of dropPredictions) {
102
+ let pos = appliedPredictions.indexOf(prediction)
103
+ if (pos >= 0) appliedPredictions.splice(pos, 1)
104
+ }
105
+ if (canonFunc) mergePatch(resultPatch, recordPatch(canonFunc))
106
+
107
+ for(let idx=0; idx<appliedPredictions.length; idx++) {
108
+ if (silentlyApplyPatch(appliedPredictions[idx])) {
109
+ mergePatch(resultPatch, appliedPredictions[idx])
110
+ } else {
111
+ appliedPredictions.splice(idx, 1)
112
+ idx--
113
+ }
114
+ }
115
+
116
+ emitPatch(resultPatch)
117
+ }
package/src/route.ts ADDED
@@ -0,0 +1,131 @@
1
+ import {Store, observe, immediateObserve, inhibitEffects} from 'aberdeen'
2
+
3
+ /**
4
+ * A `Store` object that holds the following keys:
5
+ * - `path`: The current path of the URL split into components. For instance `/` or `/users/123/feed`. Updates will be reflected in the URL and will *push* a new entry to the browser history.
6
+ * - `p`: Array containing the path segments. For instance `[]` or `['users', 123, 'feed']`. Updates will be reflected in the URL and will *push* a new entry to the browser history. Also, the values of `p` and `path` will be synced.
7
+ * - `search`: An observable object containing search parameters (a split up query string). For instance `{order: "date", title: "something"}` or just `{}`. Updates will be reflected in the URL, modifying the current history state.
8
+ * - `hash`: The document hash part of the URL. For instance `"#section-title"`. It can also be an empty string. Updates will be reflected in the URL, modifying the current history state.
9
+ * - `state`: The browser history *state* object for the current page. Creating or removing top-level keys will cause *pushing* a new entry to the browser history.
10
+ *
11
+ * The following key may also be written to `route` but will be immediately and silently removed:
12
+ * - `mode`: As described above, this library takes a best guess about whether pushing an item to the browser history makes sense or not. When `mode` is...
13
+ * - `"push"`: Force creation of a new browser history entry.
14
+ * - `"replace"`: Update the current history entry, even when updates to other keys would normally cause a *push*.
15
+ * - `"back"`: Unwind the history (like repeatedly pressing the *back* button) until we find a page that matches the given `path`, `search` and top-level `state` keys, and then *replace* that state by the full given state.
16
+ */
17
+ export const route = new Store()
18
+
19
+ // Contains url (path+search) and state for all history entries for this session, with the current
20
+ // entry on top. It is used for `mode: "back"`, to know how many entries to go back.
21
+ let stack: Array<{url: string, state: object}> = []
22
+
23
+ // Keep track of the initial history length, so we'll always know how long our `stack` should be.
24
+ const initialHistoryLength = history.length;
25
+
26
+ // Keep a copy of the last known history state, so we can tell if the user changed one of its
27
+ // top-level keys, so we can decide between push/replace when `mode` is not set.
28
+ let prevHistoryState: any
29
+
30
+ // Reflect changes to the browser URL (back/forward navigation) in the `route` and `stack`.
31
+ function handleLocationUpdate(event?: PopStateEvent) {
32
+ const search: any= {}
33
+ for(let [k, v] of new URLSearchParams(location.search)) {
34
+ search[k] = v
35
+ }
36
+ prevHistoryState = event ? (event.state || {}) : {}
37
+ stack.length = Math.max(1, history.length - initialHistoryLength + 1)
38
+ stack[stack.length-1] = {url: location.pathname + location.search, state: prevHistoryState}
39
+ route.set({
40
+ path: location.pathname,
41
+ p: location.pathname.slice(1).split('/'),
42
+ search: search,
43
+ hash: location.hash,
44
+ state: prevHistoryState,
45
+ })
46
+ }
47
+ handleLocationUpdate()
48
+ window.addEventListener("popstate", handleLocationUpdate);
49
+
50
+ // These immediate-mode observers will rewrite the data in `route` to its canonical form.
51
+ // We want to to this immediately, so that user-code running immediately after a user-code
52
+ // initiated `set` will see the canonical form (instead of doing a rerender shortly after,
53
+ // or crashing due to non-canonical data).
54
+ function updatePath(): void {
55
+ let path = route.get('path')
56
+ if (path == null && route.peek('p')) {
57
+ return updateP();
58
+ }
59
+ path = ''+path
60
+ if (!path.startsWith('/')) path = '/'+path
61
+ route.set('path', path)
62
+ route.set('p', path.slice(1).split('/'))
63
+ }
64
+ immediateObserve(updatePath)
65
+
66
+ function updateP(): void {
67
+ const p = route.get('p')
68
+ console.log('imm p', p)
69
+ if (p == null && route.peek('path')) {
70
+ return updatePath()
71
+ }
72
+ if (!(p instanceof Array)) {
73
+ console.error(`aberdeen route: 'p' must be a non-empty array, not ${JSON.stringify(p)}`)
74
+ route.set('p', ['']) // This will cause a recursive call this observer.
75
+ } else if (p.length == 0) {
76
+ route.set('p', ['']) // This will cause a recursive call this observer.
77
+ } else {
78
+ route.set('path', '/' + p.join('/'))
79
+ }
80
+ }
81
+ immediateObserve(updateP)
82
+
83
+ immediateObserve(() => {
84
+ if (route.getType('search') !== 'object') route.set('search', {})
85
+ })
86
+
87
+ immediateObserve(() => {
88
+ if (route.getType('state') !== 'object') route.set('state', {})
89
+ })
90
+
91
+ immediateObserve(() => {
92
+ let hash = ''+(route.get('hash') || '')
93
+ if (hash && !hash.startsWith('#')) hash = '#'+hash
94
+ route.set('hash', hash)
95
+ })
96
+
97
+ // This deferred-mode observer will update the URL and history based on `route` changes.
98
+ observe(() => {
99
+ // Get and delete mode without triggering anything.
100
+ const mode = route.get('mode')
101
+ if (mode) inhibitEffects(() => route.delete('mode'))
102
+ const state = route.get('state')
103
+
104
+ // Construct the URL.
105
+ const path = route.get('path')
106
+ const search = new URLSearchParams(route.get('search')).toString()
107
+ const url = (search ? path+'?'+search : path) + route.get('hash')
108
+
109
+ // Change browser state, according to `mode`.
110
+ if (mode === 'back') {
111
+ let goDelta = 0
112
+ while(stack.length > 1) {
113
+ const item = stack[stack.length-1]
114
+ if (item.url === url && JSON.stringify(Object.keys(state||{})) === JSON.stringify(Object.keys(item.state||{}))) break // Found it!
115
+ goDelta--
116
+ stack.pop()
117
+ }
118
+ if (goDelta) history.go(goDelta)
119
+ // We'll replace the state async, to give the history.go the time to take affect first.
120
+ setTimeout(() => history.replaceState(state, '', url), 0)
121
+ stack[stack.length-1] = {url,state}
122
+ } else if (mode === 'push' || (!mode && (location.pathname !== path || JSON.stringify(Object.keys(state||{})) !== JSON.stringify(Object.keys(prevHistoryState||{}))))) {
123
+ history.pushState(state, '', url)
124
+ stack.push({url,state})
125
+ } else {
126
+ history.replaceState(state, '', url)
127
+ stack[stack.length-1] = {url,state}
128
+ }
129
+ prevHistoryState = state
130
+ })
131
+
@@ -0,0 +1,73 @@
1
+ import {scheduleDomReader, scheduleDomWriter} from 'aberdeen'
2
+
3
+ const FADE_TIME = 400
4
+ const GROW_SHRINK_TRANSITION = `margin ${FADE_TIME}ms ease-out, transform ${FADE_TIME}ms ease-out`
5
+
6
+ function getGrowShrinkProps(el: HTMLElement) {
7
+ const parentStyle: any = el.parentElement ? getComputedStyle(el.parentElement) : {}
8
+ const isHorizontal = parentStyle.display === 'flex' && (parentStyle.flexDirection||'').startsWith('row')
9
+ return isHorizontal ?
10
+ {marginLeft: `-${el.offsetWidth/2}px`, marginRight: `-${el.offsetWidth/2}px`, transform: "scaleX(0)"} :
11
+ {marginBottom: `-${el.offsetHeight/2}px`, marginTop: `-${el.offsetHeight/2}px`, transform: "scaleY(0)"}
12
+
13
+ }
14
+
15
+ /** Do a grow transition for the given element. This is meant to be used as a
16
+ * handler for the `create` property.
17
+ *
18
+ * @param el The element to transition.
19
+ *
20
+ * The transition doesn't look great for table elements, and may have problems
21
+ * for other specific cases as well.
22
+ */
23
+ export function grow(el: HTMLElement): void {
24
+ // This timeout is to await all other elements having been added to the Dom
25
+ scheduleDomReader(() => {
26
+ // Make the element size 0 using transforms and negative margins.
27
+ // This causes a browser layout, as we're querying el.offset<>.
28
+ let props = getGrowShrinkProps(el)
29
+
30
+ // The timeout is in order to batch all reads and then all writes when there
31
+ // are multiple simultaneous grow transitions.
32
+ scheduleDomWriter(() => {
33
+ Object.assign(el.style, props)
34
+
35
+ // This timeout is to combine multiple transitions into a single browser layout
36
+ scheduleDomReader(() => {
37
+ // Make sure the layouting has been performed, to cause transitions to trigger
38
+ el.offsetHeight
39
+ scheduleDomWriter(() => {
40
+ // Do the transitions
41
+ el.style.transition = GROW_SHRINK_TRANSITION
42
+ for(let prop in props) el.style[prop as any] = ""
43
+ setTimeout(() => {
44
+ // Reset the element to a clean state
45
+ el.style.transition = ""
46
+ }, FADE_TIME)
47
+ })
48
+ })
49
+ })
50
+ })
51
+ }
52
+
53
+ /** Do a shrink transition for the given element, and remove it from the DOM
54
+ * afterwards. This is meant to be used as a handler for the `destroy` property.
55
+ *
56
+ * @param el The element to transition and remove.
57
+ *
58
+ * The transition doesn't look great for table elements, and may have problems
59
+ * for other specific cases as well.
60
+ */
61
+ export function shrink(el: HTMLElement): void {
62
+ scheduleDomReader(() => {
63
+ const props = getGrowShrinkProps(el)
64
+ // The timeout is in order to batch all reads and then all writes when there
65
+ // are multiple simultaneous shrink transitions.
66
+ scheduleDomWriter(() => {
67
+ el.style.transition = GROW_SHRINK_TRANSITION
68
+ Object.assign(el.style, props)
69
+
70
+ setTimeout(() => el.remove(), FADE_TIME)
71
+ })
72
+ })
73
+ }