-
Notifications
You must be signed in to change notification settings - Fork 0
/
live-signals.js
39 lines (35 loc) · 1.47 KB
/
live-signals.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
import { signal } from '@preact/signals';
import { Signal } from 'signal-polyfill';
import LiveState from 'phx-live-state';
import subscript from 'subscript';
export const createPreactSignal = (liveStateOrOptions) => {
const { path, initialValue } = liveStateOrOptions;
const [liveState, dispatchEvent] = createLiveState(liveStateOrOptions);
const updater = path? subscript(path) : (state) => state;
const preactSignal = signal(initialValue ? initialValue : {});
liveState.eventTarget.addEventListener('livestate-change', ({detail: { state }}) => {
preactSignal.value = updater(state);
});
return [preactSignal, dispatchEvent];
}
export const createPolyfillSignal = (liveStateOrOptions) => {
const { path, initialValue } = liveStateOrOptions;
const [liveState, dispatchEvent] = createLiveState(liveStateOrOptions);
const updater = path? subscript(path) : (state) => state;
const polyfillSignal = new Signal.State(initialValue ? initialValue : {});
liveState.eventTarget.addEventListener('livestate-change', ({detail: { state }}) => {
polyfillSignal.set(updater(state));
});
return [polyfillSignal, dispatchEvent];
}
const createLiveState = (liveStateOrOptions) => {
let liveState;
if (liveStateOrOptions instanceof LiveState) {
liveState = liveStateOrOptions;
} else {
liveState = new LiveState(liveStateOrOptions);
}
const dispatchEvent = (event) => liveState.dispatchEvent(event);
liveState.connect();
return [liveState, dispatchEvent];
}