2021-04-15 15:59:52 +02:00
|
|
|
// Copyright: Ankitects Pty Ltd and contributors
|
|
|
|
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
2021-04-20 14:23:28 +02:00
|
|
|
import type IconButton from "editor-toolbar/IconButton.svelte";
|
2021-04-20 02:07:15 +02:00
|
|
|
import type { IconButtonProps } from "editor-toolbar/IconButton";
|
2021-04-20 14:23:28 +02:00
|
|
|
import type { DynamicSvelteComponent } from "sveltelib/dynamicComponent";
|
2021-04-08 23:08:36 +02:00
|
|
|
|
|
|
|
import * as tr from "anki/i18n";
|
2021-04-20 14:23:28 +02:00
|
|
|
import { iconButton } from "editor-toolbar/dynamicComponents";
|
2021-04-08 23:08:36 +02:00
|
|
|
|
|
|
|
import bracketsIcon from "./code-brackets.svg";
|
|
|
|
|
2021-04-20 14:23:28 +02:00
|
|
|
import { forEditorField } from ".";
|
2021-04-20 15:41:26 +02:00
|
|
|
import { wrap } from "./wrap";
|
2021-04-20 14:23:28 +02:00
|
|
|
|
2021-04-08 23:08:36 +02:00
|
|
|
const clozePattern = /\{\{c(\d+)::/gu;
|
|
|
|
function getCurrentHighestCloze(increment: boolean): number {
|
|
|
|
let highest = 0;
|
|
|
|
|
|
|
|
forEditorField([], (field) => {
|
|
|
|
const matches = field.editingArea.editable.fieldHTML.matchAll(clozePattern);
|
|
|
|
highest = Math.max(
|
|
|
|
highest,
|
|
|
|
...[...matches].map((match: RegExpMatchArray): number => Number(match[1]))
|
|
|
|
);
|
|
|
|
});
|
|
|
|
|
|
|
|
if (increment) {
|
|
|
|
highest++;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Math.max(1, highest);
|
|
|
|
}
|
|
|
|
|
|
|
|
function onCloze(event: MouseEvent): void {
|
|
|
|
const highestCloze = getCurrentHighestCloze(!event.altKey);
|
|
|
|
wrap(`{{c${highestCloze}::`, "}}");
|
|
|
|
}
|
|
|
|
|
2021-04-15 14:58:13 +02:00
|
|
|
export function getClozeButton(): DynamicSvelteComponent<typeof IconButton> &
|
|
|
|
IconButtonProps {
|
2021-04-09 18:42:41 +02:00
|
|
|
return iconButton({
|
2021-04-08 23:08:36 +02:00
|
|
|
id: "cloze",
|
|
|
|
icon: bracketsIcon,
|
|
|
|
onClick: onCloze,
|
2021-04-09 18:42:41 +02:00
|
|
|
tooltip: tr.editingClozeDeletionCtrlandshiftandc(),
|
|
|
|
});
|
|
|
|
}
|