anki/ts/editor/wrap.ts

58 lines
1.8 KiB
TypeScript
Raw Normal View History

2021-04-13 10:57:08 +02:00
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
2021-02-09 04:38:04 +01:00
2021-05-06 23:33:28 +02:00
/* eslint
@typescript-eslint/no-non-null-assertion: "off",
*/
import { getCurrentField } from "./helpers";
import { setFormat } from ".";
2021-02-08 21:02:46 +01: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];
}
2021-02-08 22:13:49 +01:00
function moveCursorPastPostfix(selection: Selection, postfix: string): void {
const range = selection.getRangeAt(0);
range.setStart(range.startContainer, range.startOffset - postfix.length);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
2021-02-08 21:02:46 +01:00
function wrapInternal(front: string, back: string, plainText: boolean): void {
const currentField = getCurrentField()!;
2021-02-08 22:13:49 +01:00
const selection = currentField.getSelection();
const range = selection.getRangeAt(0);
const content = range.cloneContents();
2021-02-08 21:02:46 +01:00
const span = document.createElement("span");
span.appendChild(content);
if (plainText) {
const new_ = wrappedExceptForWhitespace(span.innerText, front, back);
setFormat("inserttext", new_);
} else {
const new_ = wrappedExceptForWhitespace(span.innerHTML, front, back);
setFormat("inserthtml", new_);
}
if (!span.innerHTML) {
2021-02-08 22:13:49 +01:00
moveCursorPastPostfix(selection, back);
2021-02-08 21:02:46 +01:00
}
}
export function wrap(front: string, back: string): void {
wrapInternal(front, back, false);
}
export function wrapCurrent(front: string, back: string): void {
const currentField = getCurrentField()!;
currentField.surroundSelection(front, back);
}
2021-02-08 21:02:46 +01:00
/* currently unused */
export function wrapIntoText(front: string, back: string): void {
wrapInternal(front, back, true);
}