@@ -8,7 +8,20 @@ interface BroadcastState {
8
8
getBroadcastProvider : ( ) => HocuspocusProvider | undefined ;
9
9
provider ?: HocuspocusProvider ;
10
10
setBroadcastProvider : ( provider : HocuspocusProvider ) => void ;
11
- tasks : { [ taskLabel : string ] : Y . Array < string > } ;
11
+ setTask : (
12
+ taskLabel : string ,
13
+ task : Y . Array < string > ,
14
+ action : ( ) => void ,
15
+ ) => void ;
16
+ tasks : {
17
+ [ taskLabel : string ] : {
18
+ task : Y . Array < string > ;
19
+ observer : (
20
+ event : Y . YArrayEvent < string > ,
21
+ transaction : Y . Transaction ,
22
+ ) => void ;
23
+ } ;
24
+ } ;
12
25
}
13
26
14
27
export const useBroadcastStore = create < BroadcastState > ( ( set , get ) => ( {
@@ -25,26 +38,47 @@ export const useBroadcastStore = create<BroadcastState>((set, get) => ({
25
38
return provider ;
26
39
} ,
27
40
addTask : ( taskLabel , action ) => {
28
- const taskExistAlready = get ( ) . tasks [ taskLabel ] ;
29
41
const provider = get ( ) . getBroadcastProvider ( ) ;
30
- if ( taskExistAlready || ! provider ) {
42
+ if ( ! provider ) {
43
+ return ;
44
+ }
45
+
46
+ const existingTask = get ( ) . tasks [ taskLabel ] ;
47
+ if ( existingTask ) {
48
+ existingTask . task . unobserve ( existingTask . observer ) ;
49
+ get ( ) . setTask ( taskLabel , existingTask . task , action ) ;
31
50
return ;
32
51
}
33
52
34
53
const task = provider . document . getArray < string > ( taskLabel ) ;
35
- task . observe ( ( ) => {
36
- action ( ) ;
37
- } ) ;
54
+ get ( ) . setTask ( taskLabel , task , action ) ;
55
+ } ,
56
+ setTask : ( taskLabel : string , task : Y . Array < string > , action : ( ) => void ) => {
57
+ let isInitializing = true ;
58
+ const observer = ( ) => {
59
+ if ( ! isInitializing ) {
60
+ action ( ) ;
61
+ }
62
+ } ;
63
+
64
+ task . observe ( observer ) ;
65
+
66
+ setTimeout ( ( ) => {
67
+ isInitializing = false ;
68
+ } , 1000 ) ;
38
69
39
70
set ( ( state ) => ( {
40
71
tasks : {
41
72
...state . tasks ,
42
- [ taskLabel ] : task ,
73
+ [ taskLabel ] : {
74
+ task,
75
+ observer,
76
+ } ,
43
77
} ,
44
78
} ) ) ;
45
79
} ,
46
80
broadcast : ( taskLabel ) => {
47
- const task = get ( ) . tasks [ taskLabel ] ;
81
+ const { task } = get ( ) . tasks [ taskLabel ] ;
48
82
if ( ! task ) {
49
83
console . warn ( `Task ${ taskLabel } is not defined` ) ;
50
84
return ;
0 commit comments