MCPcopy
hub / github.com/loggerhead/json4u / applyTreeEdits

Method applyTreeEdits

src/lib/editor/editor.ts:165–210  ·  view source on GitHub ↗

* Applies a batch of structured tree edits, typically originating from UI components like the graph view, * to the Monaco editor. This function serves as a specialized bridge, translating high-level, intent-based * edit requests into precise, low-level text manipulations.

(treeEdits: Array<TreeEdit>)

Source from the content-addressed store, hash-verified

163 * edit requests into precise, low-level text manipulations.
164 */
165 applyTreeEdits(treeEdits: Array<TreeEdit>) {
166 // Keep the last value for each treeNodeId in edits
167 const uniqueEdits: Array<TreeEdit> = [];
168 const idMap = new Map<string, number>();
169 treeEdits.forEach((edit, index) => idMap.set(edit.treeNodeId, index));
170 idMap.forEach((index) => uniqueEdits.push(treeEdits[index]));
171
172 treeEdits = uniqueEdits.filter((edit) => edit.version === this.tree.version);
173
174 const nodes = treeEdits
175 .map((edit) => ({
176 ...this.tree.node(edit.treeNodeId),
177 newValue: edit.value,
178 editTarget: edit.target,
179 }))
180 .filter((node) => node);
181 if (nodes.length === 0) {
182 return;
183 }
184
185 const edits = nodes.map(({ editTarget, newValue, ...nd }) => {
186 let needQuotationMarks = false;
187 try {
188 JSON.parse(newValue);
189 needQuotationMarks = false;
190 } catch {
191 needQuotationMarks = true;
192 }
193 needQuotationMarks = needQuotationMarks || editTarget === "key";
194 needQuotationMarks = needQuotationMarks && !(newValue.startsWith('"') && newValue.endsWith('"'));
195
196 let text = newValue;
197 if (needQuotationMarks) {
198 text = `"${escape(newValue)}"`;
199 }
200
201 // Keys include double quotes, so the length needs +2
202 const range =
203 editTarget === "key" ? this.range(nd.boundOffset, nd.keyLength + 2) : this.range(nd.offset, nd.length);
204 return { text, range };
205 });
206
207 console.l("edit nodes: ", treeEdits, nodes, edits);
208 this.editor.executeEdits(null, edits);
209 this.editor.pushUndoStop();
210 }
211
212 async parseAndSet(
213 text: string,

Callers 1

useEditTreeFunction · 0.80

Calls 4

rangeMethod · 0.95
escapeFunction · 0.90
setMethod · 0.80
nodeMethod · 0.80

Tested by

no test coverage detected