Skip to content

Commit 597732e

Browse files
committed
🐛 Preserve Markdown formatting in AI editing selections #19023
1 parent 9d08f8f commit 597732e

1 file changed

Lines changed: 17 additions & 5 deletions

File tree

app/src/ai/editor.ts

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -154,11 +154,22 @@ const getSourceConflict = (task: IAIEditorTask) => {
154154
return {missing, changed};
155155
};
156156

157-
const sourcePartText = (protyle: IProtyle, range: Range) => {
157+
const isMarkdownInlineElement = (element: Element) => {
158+
return element.matches("span[data-type], code, strong, em, b, i, s, del, u, mark, sub, sup, kbd, a");
159+
};
160+
161+
const sourcePartMarkdown = (protyle: IProtyle, range: Range, editableElement: Element) => {
158162
const text = range.toString().replace(new RegExp(Constants.ZWSP, "g"), "");
159-
const fragment = range.cloneContents();
160-
if (!fragment.querySelector('.img, [data-type~="inline-math"], [data-type~="a"], [data-type~="block-ref"]')) {
161-
return text;
163+
let fragment: Node = range.cloneContents();
164+
let ancestor = range.commonAncestorContainer.nodeType === Node.ELEMENT_NODE ?
165+
range.commonAncestorContainer as Element : range.commonAncestorContainer.parentElement;
166+
while (ancestor && ancestor !== editableElement && editableElement.contains(ancestor)) {
167+
if (isMarkdownInlineElement(ancestor)) {
168+
const clone = ancestor.cloneNode(false) as Element;
169+
clone.append(fragment);
170+
fragment = clone;
171+
}
172+
ancestor = ancestor.parentElement;
162173
}
163174
const element = document.createElement("div");
164175
element.append(fragment);
@@ -180,7 +191,8 @@ const buildSelectionSource = (protyle: IProtyle, range: Range, action: string):
180191
kind: "selection",
181192
parts,
182193
ids: [],
183-
input: blockRanges.map(item => sourcePartText(protyle, item.range)).filter(Boolean).join("\n\n"),
194+
input: blockRanges.map(item => sourcePartMarkdown(protyle, item.range, item.editableElement))
195+
.filter(Boolean).join("\n\n"),
184196
action,
185197
insertSupported: !protyle.disabled,
186198
};

0 commit comments

Comments
 (0)