@@ -53,12 +53,29 @@ export function mountLayout(mountElement, saveUpdateHook, sendEvent) {
53
53
}
54
54
55
55
export default function Layout ( { saveUpdateHook, sendEvent } ) {
56
- const [ model , patchModel ] = useInplaceJsonPatch ( { } ) ;
57
-
58
- react . useEffect ( ( ) => saveUpdateHook ( patchModel ) , [ patchModel ] ) ;
56
+ const [ modelRef , setModel ] = useStateRef ( { } ) ;
57
+
58
+ react . useEffect ( ( ) => {
59
+ saveUpdateHook ( ( pathPrefix , patch ) => {
60
+ setModel (
61
+ jsonpatch . applyPatch (
62
+ modelRef . current ,
63
+ patch . map ( ( op ) => {
64
+ op . path = pathPrefix + op . path ;
65
+ return op ;
66
+ } ) ,
67
+ undefined ,
68
+ false
69
+ ) . newDocument
70
+ ) ;
71
+ } ) ;
72
+ } , [ modelRef ] ) ;
59
73
60
- if ( model . tagName ) {
61
- return html `< ${ Element } sendEvent =${ sendEvent } model=${ model } /> ` ;
74
+ if ( modelRef . current . tagName ) {
75
+ return html `< ${ Element }
76
+ sendEvent =${ sendEvent }
77
+ model=${ modelRef . current }
78
+ /> ` ;
62
79
} else {
63
80
return html `< div /> ` ;
64
81
}
@@ -187,24 +204,9 @@ function getPathProperty(obj, prop) {
187
204
return value ;
188
205
}
189
206
190
- function useInplaceJsonPatch ( doc ) {
191
- const ref = react . useRef ( doc ) ;
192
- const forceUpdate = useForceUpdate ( ) ;
193
-
194
- const applyPatch = react . useCallback (
195
- ( path , patch ) => {
196
- jsonpatch . applyPatch (
197
- jsonpatch . getValueByPointer ( ref . current , path ) ,
198
- patch
199
- ) ;
200
- forceUpdate ( ) ;
201
- } ,
202
- [ ref , forceUpdate ]
203
- ) ;
204
- return [ ref . current , applyPatch ] ;
205
- }
206
-
207
- function useForceUpdate ( ) {
208
- const [ , updateState ] = react . useState ( ) ;
209
- return react . useCallback ( ( ) => updateState ( { } ) , [ ] ) ;
207
+ function useStateRef ( initialValue ) {
208
+ const ref = react . useRef ( initialValue ) ;
209
+ const [ state , setState ] = react . useState ( initialValue ) ;
210
+ ref . current = state ;
211
+ return [ ref , setState ] ;
210
212
}
0 commit comments