2021-08-07 20:26:39 +02:00
|
|
|
// Copyright: Ankitects Pty Ltd and contributors
|
|
|
|
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|
|
|
|
2022-02-04 09:36:34 +01:00
|
|
|
import { getRange, getSelection } from "./cross-browser";
|
2021-12-13 05:00:35 +01:00
|
|
|
|
2021-08-07 20:26:39 +02:00
|
|
|
function wrappedExceptForWhitespace(text: string, front: string, back: string): string {
|
|
|
|
const match = text.match(/^(\s*)([^]*?)(\s*)$/)!;
|
|
|
|
return match[1] + front + match[2] + back + match[3];
|
|
|
|
}
|
|
|
|
|
2022-02-25 02:07:44 +01:00
|
|
|
function moveCursorInside(selection: Selection, postfix: string): void {
|
|
|
|
const range = getRange(selection)!;
|
|
|
|
|
|
|
|
range.setEnd(range.endContainer, range.endOffset - postfix.length);
|
|
|
|
range.collapse(false);
|
2022-01-08 02:46:01 +01:00
|
|
|
|
2021-08-07 20:26:39 +02:00
|
|
|
selection.removeAllRanges();
|
|
|
|
selection.addRange(range);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function wrapInternal(
|
2021-12-13 05:00:35 +01:00
|
|
|
base: Element,
|
2021-08-07 20:26:39 +02:00
|
|
|
front: string,
|
|
|
|
back: string,
|
2021-10-19 01:06:00 +02:00
|
|
|
plainText: boolean,
|
2021-08-07 20:26:39 +02:00
|
|
|
): void {
|
2021-12-13 05:00:35 +01:00
|
|
|
const selection = getSelection(base)!;
|
2022-01-08 02:46:01 +01:00
|
|
|
const range = getRange(selection);
|
|
|
|
|
|
|
|
if (!range) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-02-25 02:07:44 +01:00
|
|
|
const wasCollapsed = range.collapsed;
|
2021-08-07 20:26:39 +02:00
|
|
|
const content = range.cloneContents();
|
|
|
|
const span = document.createElement("span");
|
|
|
|
span.appendChild(content);
|
|
|
|
|
|
|
|
if (plainText) {
|
|
|
|
const new_ = wrappedExceptForWhitespace(span.innerText, front, back);
|
|
|
|
document.execCommand("inserttext", false, new_);
|
|
|
|
} else {
|
|
|
|
const new_ = wrappedExceptForWhitespace(span.innerHTML, front, back);
|
|
|
|
document.execCommand("inserthtml", false, new_);
|
|
|
|
}
|
|
|
|
|
2021-09-17 20:12:11 +02:00
|
|
|
if (
|
2022-11-28 00:33:04 +01:00
|
|
|
wasCollapsed
|
|
|
|
/* ugly solution: treat <anki-mathjax> differently than other wraps */ && !front.includes(
|
2021-10-19 01:06:00 +02:00
|
|
|
"<anki-mathjax",
|
2021-09-17 20:12:11 +02:00
|
|
|
)
|
|
|
|
) {
|
2022-02-25 02:07:44 +01:00
|
|
|
moveCursorInside(selection, back);
|
2021-08-07 20:26:39 +02:00
|
|
|
}
|
|
|
|
}
|