Skip to content

Commit 310e749

Browse files
committed
fix bad JSON patch usage
We were not considering the fact that we need to add the patch prefix to the "from" key in a "mode" operation. To solve this we decide to apply the patch inplace at the given path. This is both faster and simpler.
1 parent 6b9d843 commit 310e749

File tree

1 file changed

+25
-27
lines changed

1 file changed

+25
-27
lines changed

Diff for: idom/client/app/core_modules/layout.js

+25-27
Original file line numberDiff line numberDiff line change
@@ -53,29 +53,12 @@ export function mountLayout(mountElement, saveUpdateHook, sendEvent) {
5353
}
5454

5555
export default function Layout({ saveUpdateHook, sendEvent }) {
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]);
56+
const [model, patchModel] = useInplaceJsonPatch({});
7357

74-
if (modelRef.current.tagName) {
75-
return html`<${Element}
76-
sendEvent=${sendEvent}
77-
model=${modelRef.current}
78-
/>`;
58+
react.useEffect(() => saveUpdateHook(patchModel), [patchModel]);
59+
60+
if (model.tagName) {
61+
return html`<${Element} sendEvent=${sendEvent} model=${model} />`;
7962
} else {
8063
return html`<div />`;
8164
}
@@ -204,9 +187,24 @@ function getPathProperty(obj, prop) {
204187
return value;
205188
}
206189

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];
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({}), []);
212210
}

0 commit comments

Comments
 (0)