|
| 1 | +import { EventType } from 'overmind' |
| 2 | +import { onMount, afterUpdate, onDestroy } from 'svelte' |
| 3 | + |
| 4 | +const IS_PRODUCTION = process.env.NODE_ENV === 'production' |
| 5 | + |
| 6 | +let nextComponentId = 0 |
| 7 | + |
| 8 | +export function createMixin (overmind) { |
| 9 | + const componentId = nextComponentId++ |
| 10 | + let nextComponentInstanceId = 0 |
| 11 | + let currentFlushId = 0 |
| 12 | + |
| 13 | + const subscribe = listener => { |
| 14 | + const tree = overmind.proxyStateTree.getTrackStateTree() |
| 15 | + const componentInstanceId = nextComponentInstanceId++ |
| 16 | + let isUpdating = false |
| 17 | + |
| 18 | + tree.track((mutations, paths, flushId) => { |
| 19 | + currentFlushId = flushId |
| 20 | + isUpdating = true |
| 21 | + listener(tree) |
| 22 | + }) |
| 23 | + |
| 24 | + listener(tree) |
| 25 | + |
| 26 | + if (IS_PRODUCTION) { |
| 27 | + afterUpdate(() => { |
| 28 | + tree.stopTracking() |
| 29 | + isUpdating = false |
| 30 | + }) |
| 31 | + } else { |
| 32 | + onMount(() => { |
| 33 | + overmind.eventHub.emitAsync(EventType.COMPONENT_ADD, { |
| 34 | + componentId, |
| 35 | + componentInstanceId, |
| 36 | + name: '', |
| 37 | + paths: Array.from(tree.pathDependencies) |
| 38 | + }) |
| 39 | + }) |
| 40 | + |
| 41 | + afterUpdate(() => { |
| 42 | + tree.stopTracking() |
| 43 | + if (isUpdating) { |
| 44 | + overmind.eventHub.emitAsync(EventType.COMPONENT_UPDATE, { |
| 45 | + componentId, |
| 46 | + componentInstanceId, |
| 47 | + name: '', |
| 48 | + flushId: currentFlushId, |
| 49 | + paths: Array.from(tree.pathDependencies) |
| 50 | + }) |
| 51 | + } |
| 52 | + isUpdating = false |
| 53 | + }) |
| 54 | + } |
| 55 | + |
| 56 | + return () => { |
| 57 | + tree.stopTracking() |
| 58 | + overmind.proxyStateTree.disposeTree(tree) |
| 59 | + overmind.eventHub.emitAsync(EventType.COMPONENT_REMOVE, { |
| 60 | + componentId, |
| 61 | + componentInstanceId: componentInstanceId, |
| 62 | + name: '' |
| 63 | + }) |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + const reaction = (...args) => { |
| 68 | + const dispose = overmind.reaction(...args) |
| 69 | + |
| 70 | + onDestroy(() => { |
| 71 | + dispose() |
| 72 | + }) |
| 73 | + } |
| 74 | + |
| 75 | + return { |
| 76 | + subscribe, |
| 77 | + state: overmind.state, |
| 78 | + actions: overmind.actions, |
| 79 | + effects: overmind.effects, |
| 80 | + addMutationListener: overmind.addMutationListener, |
| 81 | + reaction: reaction |
| 82 | + } |
| 83 | +} |
0 commit comments