mirror of
https://github.com/ankitects/anki.git
synced 2025-09-19 06:22:22 -04:00
Merge branch 'main' into color-palette
This commit is contained in:
parent
e036edd584
commit
ac4c88afdc
20 changed files with 337 additions and 205 deletions
|
@ -58,6 +58,7 @@ editing-toggle-visual-editor = Toggle Visual Editor
|
|||
editing-underline-text = Underline text
|
||||
editing-unordered-list = Unordered list
|
||||
editing-warning-cloze-deletions-will-not-work = Warning, cloze deletions will not work until you switch the type at the top to Cloze.
|
||||
editing-toggle-mathjax-rendering = Toggle MathJax Rendering
|
||||
|
||||
## You don't need to translate these strings, as they will be replaced with different ones soon.
|
||||
|
||||
|
|
|
@ -10,6 +10,7 @@ fields-font = Font:
|
|||
fields-new-position-1 = New position (1...{ $val }):
|
||||
fields-notes-require-at-least-one-field = Notes require at least one field.
|
||||
fields-reverse-text-direction-rtl = Reverse text direction (RTL)
|
||||
fields-html-by-default = Use HTML editor by default
|
||||
fields-size = Size:
|
||||
fields-sort-by-this-field-in-the = Sort by this field in the browser
|
||||
fields-that-field-name-is-already-used = That field name is already used.
|
||||
|
|
|
@ -72,6 +72,7 @@ message Notetype {
|
|||
string font_name = 3;
|
||||
uint32 font_size = 4;
|
||||
string description = 5;
|
||||
bool plain_text = 6;
|
||||
|
||||
bytes other = 255;
|
||||
}
|
||||
|
|
|
@ -14,8 +14,8 @@
|
|||
body {
|
||||
color: var(--text-fg);
|
||||
background: var(--window-bg);
|
||||
margin: 1em;
|
||||
transition: opacity 0.5s ease-out;
|
||||
margin: 2em;
|
||||
overscroll-behavior: none;
|
||||
}
|
||||
|
||||
|
@ -24,11 +24,6 @@ a {
|
|||
text-decoration: none;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 2em;
|
||||
overscroll-behavior: none;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin-bottom: 0.2em;
|
||||
}
|
||||
|
|
|
@ -125,6 +125,7 @@ class Editor:
|
|||
self.card: Card | None = None
|
||||
self._init_links()
|
||||
self.setupOuter()
|
||||
self.add_webview()
|
||||
self.setupWeb()
|
||||
self.setupShortcuts()
|
||||
gui_hooks.editor_did_init(self)
|
||||
|
@ -139,11 +140,12 @@ class Editor:
|
|||
self.widget.setLayout(l)
|
||||
self.outerLayout = l
|
||||
|
||||
def setupWeb(self) -> None:
|
||||
def add_webview(self) -> None:
|
||||
self.web = EditorWebView(self.widget, self)
|
||||
self.web.set_bridge_command(self.onBridgeCmd, self)
|
||||
self.outerLayout.addWidget(self.web, 1)
|
||||
|
||||
def setupWeb(self) -> None:
|
||||
if self.editorMode == EditorMode.ADD_CARDS:
|
||||
file = "note_creator"
|
||||
elif self.editorMode == EditorMode.BROWSER:
|
||||
|
@ -499,6 +501,7 @@ require("anki/ui").loaded.then(() => require("anki/NoteEditor").instances[0].too
|
|||
]
|
||||
|
||||
flds = self.note.note_type()["flds"]
|
||||
plain_texts = [fld.get("plainText", False) for fld in flds]
|
||||
descriptions = [fld.get("description", "") for fld in flds]
|
||||
|
||||
self.widget.show()
|
||||
|
@ -519,14 +522,26 @@ require("anki/ui").loaded.then(() => require("anki/NoteEditor").instances[0].too
|
|||
text_color = self.mw.pm.profile.get("lastTextColor", "#00f")
|
||||
highlight_color = self.mw.pm.profile.get("lastHighlightColor", "#00f")
|
||||
|
||||
js = "setFields({}); setDescriptions({}); setFonts({}); focusField({}); setNoteId({}); setColorButtons({}); setTags({}); ".format(
|
||||
js = """
|
||||
setFields({});
|
||||
setPlainTexts({});
|
||||
setDescriptions({});
|
||||
setFonts({});
|
||||
focusField({});
|
||||
setNoteId({});
|
||||
setColorButtons({});
|
||||
setTags({});
|
||||
setMathjaxEnabled({});
|
||||
""".format(
|
||||
json.dumps(data),
|
||||
json.dumps(plain_texts),
|
||||
json.dumps(descriptions),
|
||||
json.dumps(self.fonts()),
|
||||
json.dumps(focusTo),
|
||||
json.dumps(self.note.id),
|
||||
json.dumps([text_color, highlight_color]),
|
||||
json.dumps(self.note.tags),
|
||||
json.dumps(self.mw.col.get_config("renderMathjax", True)),
|
||||
)
|
||||
|
||||
if self.addMode:
|
||||
|
@ -1130,6 +1145,14 @@ require("anki/ui").loaded.then(() => require("anki/NoteEditor").instances[0].too
|
|||
def insertMathjaxChemistry(self) -> None:
|
||||
self.web.eval("wrap('\\\\(\\\\ce{', '}\\\\)');")
|
||||
|
||||
def toggleMathjax(self) -> None:
|
||||
self.mw.col.set_config(
|
||||
"renderMathjax", not self.mw.col.get_config("renderMathjax", False)
|
||||
)
|
||||
# hackily redraw the page
|
||||
self.setupWeb()
|
||||
self.loadNoteKeepingFocus()
|
||||
|
||||
# Links from HTML
|
||||
######################################################################
|
||||
|
||||
|
@ -1156,6 +1179,7 @@ require("anki/ui").loaded.then(() => require("anki/NoteEditor").instances[0].too
|
|||
mathjaxInline=Editor.insertMathjaxInline,
|
||||
mathjaxBlock=Editor.insertMathjaxBlock,
|
||||
mathjaxChemistry=Editor.insertMathjaxChemistry,
|
||||
toggleMathjax=Editor.toggleMathjax,
|
||||
)
|
||||
|
||||
|
||||
|
|
|
@ -243,6 +243,7 @@ class FieldDialog(QDialog):
|
|||
f.fontSize.setValue(fld["size"])
|
||||
f.sortField.setChecked(self.model["sortf"] == fld["ord"])
|
||||
f.rtl.setChecked(fld["rtl"])
|
||||
f.plainTextByDefault.setChecked(fld["plainText"])
|
||||
f.fieldDescription.setText(fld.get("description", ""))
|
||||
|
||||
def saveField(self) -> None:
|
||||
|
@ -264,6 +265,10 @@ class FieldDialog(QDialog):
|
|||
if fld["rtl"] != rtl:
|
||||
fld["rtl"] = rtl
|
||||
self.change_tracker.mark_basic()
|
||||
plain_text = f.plainTextByDefault.isChecked()
|
||||
if fld["plainText"] != plain_text:
|
||||
fld["plainText"] = plain_text
|
||||
self.change_tracker.mark_basic()
|
||||
desc = f.fieldDescription.text()
|
||||
if fld.get("description", "") != desc:
|
||||
fld["description"] = desc
|
||||
|
|
|
@ -6,8 +6,8 @@
|
|||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>586</width>
|
||||
<height>376</height>
|
||||
<width>598</width>
|
||||
<height>378</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
|
@ -84,13 +84,6 @@
|
|||
</item>
|
||||
<item>
|
||||
<layout class="QGridLayout" name="_2">
|
||||
<item row="1" column="0">
|
||||
<widget class="QLabel" name="label_font">
|
||||
<property name="text">
|
||||
<string>fields_editing_font</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="3" column="1">
|
||||
<widget class="QCheckBox" name="rtl">
|
||||
<property name="text">
|
||||
|
@ -98,13 +91,27 @@
|
|||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="2">
|
||||
<widget class="QSpinBox" name="fontSize">
|
||||
<property name="minimum">
|
||||
<number>5</number>
|
||||
<item row="1" column="1">
|
||||
<widget class="QFontComboBox" name="fontFamily">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<number>300</number>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="0">
|
||||
<widget class="QLabel" name="label_font">
|
||||
<property name="text">
|
||||
<string>fields_editing_font</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="0" column="1" colspan="2">
|
||||
<widget class="QLineEdit" name="fieldDescription">
|
||||
<property name="placeholderText">
|
||||
<string>fields_description_placeholder</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
|
@ -115,13 +122,6 @@
|
|||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="2" column="1">
|
||||
<widget class="QRadioButton" name="sortField">
|
||||
<property name="text">
|
||||
<string>fields_sort_by_this_field_in_the</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="0" column="0">
|
||||
<widget class="QLabel" name="label_description">
|
||||
<property name="sizePolicy">
|
||||
|
@ -135,20 +135,30 @@
|
|||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="1">
|
||||
<widget class="QFontComboBox" name="fontFamily">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
<item row="1" column="2">
|
||||
<widget class="QSpinBox" name="fontSize">
|
||||
<property name="minimum">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<number>300</number>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="0" column="1" colspan="2">
|
||||
<widget class="QLineEdit" name="fieldDescription">
|
||||
<property name="placeholderText">
|
||||
<string>fields_description_placeholder</string>
|
||||
<item row="2" column="1">
|
||||
<widget class="QRadioButton" name="sortField">
|
||||
<property name="text">
|
||||
<string>fields_sort_by_this_field_in_the</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="4" column="1">
|
||||
<widget class="QCheckBox" name="plainTextByDefault">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>fields_html_by_default</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
|
|
|
@ -42,6 +42,7 @@ impl NoteField {
|
|||
config: NoteFieldConfig {
|
||||
sticky: false,
|
||||
rtl: false,
|
||||
plain_text: false,
|
||||
font_name: "Arial".into(),
|
||||
font_size: 20,
|
||||
description: "".into(),
|
||||
|
|
|
@ -161,7 +161,7 @@ impl From<Notetype> for NotetypeSchema11 {
|
|||
|
||||
/// See [crate::deckconfig::schema11::clear_other_duplicates()].
|
||||
fn clear_other_field_duplicates(other: &mut HashMap<String, Value>) {
|
||||
for key in &["description"] {
|
||||
for key in &["description", "plainText"] {
|
||||
other.remove(*key);
|
||||
}
|
||||
}
|
||||
|
@ -195,6 +195,7 @@ impl From<CardRequirement> for CardRequirementSchema11 {
|
|||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteFieldSchema11 {
|
||||
pub(crate) name: String,
|
||||
pub(crate) ord: Option<u16>,
|
||||
|
@ -211,6 +212,9 @@ pub struct NoteFieldSchema11 {
|
|||
#[serde(default, deserialize_with = "default_on_invalid")]
|
||||
pub(crate) description: String,
|
||||
|
||||
#[serde(default, deserialize_with = "default_on_invalid")]
|
||||
pub(crate) plain_text: bool,
|
||||
|
||||
#[serde(flatten)]
|
||||
pub(crate) other: HashMap<String, Value>,
|
||||
}
|
||||
|
@ -222,6 +226,7 @@ impl Default for NoteFieldSchema11 {
|
|||
ord: None,
|
||||
sticky: false,
|
||||
rtl: false,
|
||||
plain_text: false,
|
||||
font: "Arial".to_string(),
|
||||
size: 20,
|
||||
description: String::new(),
|
||||
|
@ -238,6 +243,7 @@ impl From<NoteFieldSchema11> for NoteField {
|
|||
config: NoteFieldConfig {
|
||||
sticky: f.sticky,
|
||||
rtl: f.rtl,
|
||||
plain_text: f.plain_text,
|
||||
font_name: f.font,
|
||||
font_size: f.size as u32,
|
||||
description: f.description,
|
||||
|
@ -259,6 +265,7 @@ impl From<NoteField> for NoteFieldSchema11 {
|
|||
ord: p.ord.map(|o| o as u16),
|
||||
sticky: conf.sticky,
|
||||
rtl: conf.rtl,
|
||||
plain_text: conf.plain_text,
|
||||
font: conf.font_name,
|
||||
size: conf.font_size as u16,
|
||||
description: conf.description,
|
||||
|
|
|
@ -32,7 +32,7 @@ $utilities: (
|
|||
flex-basis: 75%;
|
||||
}
|
||||
|
||||
* {
|
||||
body {
|
||||
overscroll-behavior: none;
|
||||
}
|
||||
|
||||
|
|
|
@ -38,17 +38,6 @@
|
|||
}
|
||||
|
||||
onDestroy(() => tooltipObject?.dispose());
|
||||
|
||||
// hack to update field description tooltips
|
||||
let previousTooltip: string = tooltip;
|
||||
$: if (tooltip !== previousTooltip) {
|
||||
previousTooltip = tooltip;
|
||||
if (tooltipObject !== undefined) {
|
||||
const element: HTMLElement = tooltipObject["_element"];
|
||||
tooltipObject.dispose();
|
||||
createTooltip(element);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<slot {createTooltip} {tooltipObject} />
|
||||
|
|
|
@ -20,6 +20,10 @@ function trimBreaks(text: string): string {
|
|||
.replace(/\n*$/, "");
|
||||
}
|
||||
|
||||
export const mathjaxConfig = {
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
export const Mathjax: DecoratedElementConstructor = class Mathjax
|
||||
extends HTMLElement
|
||||
implements DecoratedElement
|
||||
|
@ -41,6 +45,9 @@ export const Mathjax: DecoratedElementConstructor = class Mathjax
|
|||
}
|
||||
|
||||
static toUndecorated(stored: string): string {
|
||||
if (!mathjaxConfig.enabled) {
|
||||
return stored;
|
||||
}
|
||||
return stored
|
||||
.replace(mathjaxBlockDelimiterPattern, (_match: string, text: string) => {
|
||||
const trimmed = trimBreaks(text);
|
||||
|
|
|
@ -12,6 +12,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
fontFamily: string;
|
||||
fontSize: number;
|
||||
direction: "ltr" | "rtl";
|
||||
plainText: boolean;
|
||||
description: string;
|
||||
}
|
||||
|
||||
|
|
|
@ -32,10 +32,13 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
<style>
|
||||
.field-description {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
|
||||
cursor: text;
|
||||
opacity: 0.4;
|
||||
pointer-events: none;
|
||||
|
||||
/* same as in ContentEditable */
|
||||
padding: 6px;
|
||||
|
|
|
@ -109,21 +109,29 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
fieldNames = newFieldNames;
|
||||
}
|
||||
|
||||
let plainTexts: boolean[] = [];
|
||||
let richTextsHidden: boolean[] = [];
|
||||
let plainTextsHidden: boolean[] = [];
|
||||
|
||||
export function setPlainTexts(fs: boolean[]): void {
|
||||
richTextsHidden = plainTexts = fs;
|
||||
plainTextsHidden = Array.from(fs, (v) => !v);
|
||||
}
|
||||
|
||||
function setMathjaxEnabled(enabled: boolean): void {
|
||||
mathjaxConfig.enabled = enabled;
|
||||
}
|
||||
|
||||
let fieldDescriptions: string[] = [];
|
||||
export function setDescriptions(fs: string[]): void {
|
||||
fieldDescriptions = fs;
|
||||
}
|
||||
|
||||
let fonts: [string, number, boolean][] = [];
|
||||
let richTextsHidden: boolean[] = [];
|
||||
let plainTextsHidden: boolean[] = [];
|
||||
const fields = clearableArray<EditorFieldAPI>();
|
||||
|
||||
export function setFonts(fs: [string, number, boolean][]): void {
|
||||
fonts = fs;
|
||||
|
||||
richTextsHidden = fonts.map((_, index) => richTextsHidden[index] ?? false);
|
||||
plainTextsHidden = fonts.map((_, index) => plainTextsHidden[index] ?? true);
|
||||
}
|
||||
|
||||
export function focusField(index: number | null): void {
|
||||
|
@ -171,6 +179,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
|
||||
$: fieldsData = fieldNames.map((name, index) => ({
|
||||
name,
|
||||
plainText: plainTexts[index],
|
||||
description: fieldDescriptions[index],
|
||||
fontFamily: quoteFontFamily(fonts[index][0]),
|
||||
fontSize: fonts[index][1],
|
||||
|
@ -223,6 +232,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
|
||||
const toolbar: Partial<EditorToolbarAPI> = {};
|
||||
|
||||
import { mathjaxConfig } from "../editable/mathjax-element";
|
||||
import { wrapInternal } from "../lib/wrap";
|
||||
import * as oldEditorAdapter from "./old-editor-adapter";
|
||||
|
||||
|
@ -239,6 +249,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
|
||||
Object.assign(globalThis, {
|
||||
setFields,
|
||||
setPlainTexts,
|
||||
setDescriptions,
|
||||
setFonts,
|
||||
focusField,
|
||||
|
@ -250,6 +261,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
getNoteId,
|
||||
setNoteId,
|
||||
wrap,
|
||||
setMathjaxEnabled,
|
||||
...oldEditorAdapter,
|
||||
});
|
||||
|
||||
|
|
|
@ -10,6 +10,8 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
import Popover from "../../components/Popover.svelte";
|
||||
import Shortcut from "../../components/Shortcut.svelte";
|
||||
import WithFloating from "../../components/WithFloating.svelte";
|
||||
import { mathjaxConfig } from "../../editable/mathjax-element";
|
||||
import { bridgeCommand } from "../../lib/bridgecommand";
|
||||
import * as tr from "../../lib/ftl";
|
||||
import { getPlatformString } from "../../lib/shortcuts";
|
||||
import { wrapInternal } from "../../lib/wrap";
|
||||
|
@ -50,6 +52,11 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
surround("[$$]", "[/$$]");
|
||||
}
|
||||
|
||||
function toggleShowMathjax(): void {
|
||||
mathjaxConfig.enabled = !mathjaxConfig.enabled;
|
||||
bridgeCommand("toggleMathjax");
|
||||
}
|
||||
|
||||
type LatexItem = [() => void, string, string];
|
||||
|
||||
const dropdownItems: LatexItem[] = [
|
||||
|
@ -93,6 +100,9 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
</DropdownItem>
|
||||
<Shortcut {keyCombination} on:action={callback} />
|
||||
{/each}
|
||||
<DropdownItem on:click={toggleShowMathjax}>
|
||||
<span>{tr.editingToggleMathjaxRendering()}</span>
|
||||
</DropdownItem>
|
||||
</Popover>
|
||||
</WithFloating>
|
||||
|
||||
|
|
|
@ -5,7 +5,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
|
||||
import Checkbox from "../../components/CheckBox.svelte";
|
||||
import CheckBox from "../../components/CheckBox.svelte";
|
||||
import DropdownItem from "../../components/DropdownItem.svelte";
|
||||
import DropdownMenu from "../../components/DropdownMenu.svelte";
|
||||
import { withButton } from "../../components/helpers";
|
||||
|
@ -14,7 +14,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
import WithDropdown from "../../components/WithDropdown.svelte";
|
||||
import type { MatchType } from "../../domlib/surround";
|
||||
import * as tr from "../../lib/ftl";
|
||||
import { altPressed } from "../../lib/keys";
|
||||
import { altPressed, shiftPressed } from "../../lib/keys";
|
||||
import { getPlatformString } from "../../lib/shortcuts";
|
||||
import { singleCallback } from "../../lib/typing";
|
||||
import { surrounder } from "../rich-text-input";
|
||||
|
@ -25,45 +25,22 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
|
||||
const { removeFormats } = editorToolbarContext.get();
|
||||
|
||||
const surroundElement = document.createElement("span");
|
||||
|
||||
function matcher(element: HTMLElement | SVGElement, match: MatchType<never>): void {
|
||||
if (
|
||||
element.tagName === "SPAN" &&
|
||||
element.className.length === 0 &&
|
||||
element.style.cssText.length === 0
|
||||
) {
|
||||
match.remove();
|
||||
function filterForKeys(formats: RemoveFormat[], value: boolean): string[] {
|
||||
return formats
|
||||
.filter((format) => format.active === value)
|
||||
.map((format) => format.key);
|
||||
}
|
||||
}
|
||||
|
||||
const key = "simple spans";
|
||||
const format = {
|
||||
matcher,
|
||||
surroundElement,
|
||||
};
|
||||
|
||||
removeFormats.update((formats) =>
|
||||
formats.concat({
|
||||
key,
|
||||
name: key,
|
||||
show: false,
|
||||
active: true,
|
||||
}),
|
||||
);
|
||||
|
||||
let activeKeys: string[];
|
||||
$: activeKeys = $removeFormats
|
||||
.filter((format) => format.active)
|
||||
.map((format) => format.key);
|
||||
$: activeKeys = filterForKeys($removeFormats, true);
|
||||
|
||||
let inactiveKeys: string[];
|
||||
$: inactiveKeys = $removeFormats
|
||||
.filter((format) => !format.active)
|
||||
.map((format) => format.key);
|
||||
$: inactiveKeys = filterForKeys($removeFormats, false);
|
||||
|
||||
let showFormats: RemoveFormat[];
|
||||
$: showFormats = $removeFormats.filter((format) => format.show);
|
||||
$: showFormats = $removeFormats.filter(
|
||||
(format: RemoveFormat): boolean => format.show,
|
||||
);
|
||||
|
||||
function remove(): void {
|
||||
surrounder.remove(activeKeys, inactiveKeys);
|
||||
|
@ -71,8 +48,10 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
|
||||
function onItemClick(event: MouseEvent, format: RemoveFormat): void {
|
||||
if (altPressed(event)) {
|
||||
const value = shiftPressed(event);
|
||||
|
||||
for (const format of showFormats) {
|
||||
format.active = false;
|
||||
format.active = value;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -84,12 +63,44 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
|
||||
let disabled: boolean;
|
||||
|
||||
onMount(() =>
|
||||
singleCallback(
|
||||
onMount(() => {
|
||||
const surroundElement = document.createElement("span");
|
||||
|
||||
function matcher(
|
||||
element: HTMLElement | SVGElement,
|
||||
match: MatchType<never>,
|
||||
): void {
|
||||
if (
|
||||
element.tagName === "SPAN" &&
|
||||
element.className.length === 0 &&
|
||||
element.style.cssText.length === 0
|
||||
) {
|
||||
match.remove();
|
||||
}
|
||||
}
|
||||
|
||||
const simpleSpans = {
|
||||
matcher,
|
||||
surroundElement,
|
||||
};
|
||||
|
||||
const key = "simple spans";
|
||||
|
||||
removeFormats.update((formats: RemoveFormat[]): RemoveFormat[] => [
|
||||
...formats,
|
||||
{
|
||||
key,
|
||||
name: key,
|
||||
show: false,
|
||||
active: true,
|
||||
},
|
||||
]);
|
||||
|
||||
return singleCallback(
|
||||
surrounder.active.subscribe((value) => (disabled = !value)),
|
||||
surrounder.registerFormat(key, format),
|
||||
),
|
||||
surrounder.registerFormat(key, simpleSpans),
|
||||
);
|
||||
});
|
||||
</script>
|
||||
|
||||
<IconButton
|
||||
|
@ -117,7 +128,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
<DropdownMenu on:mousedown={(event) => event.preventDefault()}>
|
||||
{#each showFormats as format (format.name)}
|
||||
<DropdownItem on:click={(event) => onItemClick(event, format)}>
|
||||
<Checkbox bind:value={format.active} />
|
||||
<CheckBox bind:value={format.active} />
|
||||
<span class="d-flex-inline ps-3">{format.name}</span>
|
||||
</DropdownItem>
|
||||
{/each}
|
||||
|
|
|
@ -3,6 +3,8 @@ Copyright: Ankitects Pty Ltd and contributors
|
|||
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
||||
-->
|
||||
<script context="module" lang="ts">
|
||||
import { writable } from "svelte/store";
|
||||
|
||||
import type { ContentEditableAPI } from "../../editable/ContentEditable.svelte";
|
||||
import type { InputHandlerAPI } from "../../sveltelib/input-handler";
|
||||
import type { EditingInputAPI, FocusableInputAPI } from "../EditingArea.svelte";
|
||||
|
@ -38,7 +40,8 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
const [globalInputHandler, setupGlobalInputHandler] = useInputHandler();
|
||||
const [lifecycle, instances, setupLifecycleHooks] =
|
||||
lifecycleHooks<RichTextInputAPI>();
|
||||
const surrounder = Surrounder.make();
|
||||
const apiStore = writable<SurroundedAPI | null>(null);
|
||||
const surrounder = Surrounder.make(apiStore);
|
||||
|
||||
registerPackage("anki/RichTextInput", {
|
||||
context,
|
||||
|
@ -176,16 +179,16 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|||
|
||||
function setFocus(): void {
|
||||
$focusedInput = api;
|
||||
surrounder.enable(api);
|
||||
$apiStore = api;
|
||||
}
|
||||
|
||||
function removeFocus(): void {
|
||||
// We do not unset focusedInput here.
|
||||
// If we did, UI components for the input would react the store
|
||||
// being unset, even though most likely it will be set to some other
|
||||
// field right away.
|
||||
}
|
||||
|
||||
function removeFocus(): void {
|
||||
surrounder.disable();
|
||||
$apiStore = null;
|
||||
}
|
||||
|
||||
$: pushUpdate(!hidden);
|
||||
|
|
|
@ -1,14 +1,15 @@
|
|||
// Copyright: Ankitects Pty Ltd and contributors
|
||||
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
||||
|
||||
import type { Writable } from "svelte/store";
|
||||
import { get, writable } from "svelte/store";
|
||||
import type { Readable } from "svelte/store";
|
||||
import { derived, get } from "svelte/store";
|
||||
|
||||
import type { Matcher } from "../domlib/find-above";
|
||||
import { findClosest } from "../domlib/find-above";
|
||||
import type { SurroundFormat } from "../domlib/surround";
|
||||
import { boolMatcher, reformat, surround, unsurround } from "../domlib/surround";
|
||||
import { getRange, getSelection } from "../lib/cross-browser";
|
||||
import { asyncNoop } from "../lib/functional";
|
||||
import { registerPackage } from "../lib/runtime-require";
|
||||
import type { TriggerItem } from "../sveltelib/handler-list";
|
||||
import type { InputHandlerAPI } from "../sveltelib/input-handler";
|
||||
|
@ -67,52 +68,55 @@ export interface SurroundedAPI {
|
|||
inputHandler: InputHandlerAPI;
|
||||
}
|
||||
|
||||
export class Surrounder<T = unknown> {
|
||||
static make<T>(): Surrounder<T> {
|
||||
return new Surrounder();
|
||||
}
|
||||
|
||||
private api: SurroundedAPI | null = null;
|
||||
private triggers: Map<string, TriggerItem<{ event: InputEvent; text: Text }>> =
|
||||
new Map();
|
||||
|
||||
active: Writable<boolean> = writable(false);
|
||||
|
||||
enable(api: SurroundedAPI): void {
|
||||
this.api = api;
|
||||
this.active.set(true);
|
||||
|
||||
for (const key of this.formats.keys()) {
|
||||
this.triggers.set(
|
||||
key,
|
||||
this.api.inputHandler.insertText.trigger({ once: true }),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
/**
|
||||
* After calling disable, using any of the surrounding methods will throw an
|
||||
* exception. Make sure to set the input before trying to use them again.
|
||||
*/
|
||||
disable(): void {
|
||||
this.api = null;
|
||||
this.active.set(false);
|
||||
export class Surrounder<T = unknown> {
|
||||
#api?: SurroundedAPI;
|
||||
|
||||
for (const [key, trigger] of this.triggers) {
|
||||
#triggers: Map<string, TriggerItem<{ event: InputEvent; text: Text }>> = new Map();
|
||||
#formats: Map<string, SurroundFormat<T>> = new Map();
|
||||
|
||||
active: Readable<boolean>;
|
||||
|
||||
private constructor(apiStore: Readable<SurroundedAPI | null>) {
|
||||
this.active = derived(apiStore, (api) => Boolean(api));
|
||||
|
||||
apiStore.subscribe((api: SurroundedAPI | null): void => {
|
||||
if (api) {
|
||||
this.#api = api;
|
||||
|
||||
for (const key of this.#formats.keys()) {
|
||||
this.#triggers.set(
|
||||
key,
|
||||
api.inputHandler.insertText.trigger({ once: true }),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
this.#api = undefined;
|
||||
|
||||
for (const [key, trigger] of this.#triggers) {
|
||||
trigger.off();
|
||||
this.triggers.delete(key);
|
||||
this.#triggers.delete(key);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async _assert_base(): Promise<HTMLElement> {
|
||||
if (!this.api) {
|
||||
throw new Error("Surrounder: No input set");
|
||||
static make<T>(apiStore: Readable<SurroundedAPI | null>): Surrounder<T> {
|
||||
return new Surrounder(apiStore);
|
||||
}
|
||||
|
||||
return this.api.element;
|
||||
#getBaseElement(): Promise<HTMLElement> {
|
||||
if (!this.#api) {
|
||||
throw new Error("Surrounder: No api set");
|
||||
}
|
||||
|
||||
private _toggleTrigger<T>(
|
||||
return this.#api.element;
|
||||
}
|
||||
|
||||
#toggleTrigger<T>(
|
||||
base: HTMLElement,
|
||||
selection: Selection,
|
||||
matcher: Matcher,
|
||||
|
@ -135,7 +139,7 @@ export class Surrounder<T = unknown> {
|
|||
}
|
||||
}
|
||||
|
||||
private _toggleTriggerOverwrite<T>(
|
||||
#toggleTriggerOverwrite<T>(
|
||||
base: HTMLElement,
|
||||
selection: Selection,
|
||||
format: SurroundFormat<T>,
|
||||
|
@ -154,51 +158,84 @@ export class Surrounder<T = unknown> {
|
|||
});
|
||||
}
|
||||
|
||||
private _toggleTriggerRemove<T>(
|
||||
#toggleTriggerRemove<T>(
|
||||
base: HTMLElement,
|
||||
selection: Selection,
|
||||
remove: SurroundFormat<T>[],
|
||||
triggers: TriggerItem<{ event: InputEvent; text: Text }>[],
|
||||
formats: {
|
||||
format: SurroundFormat<T>;
|
||||
trigger: TriggerItem<{ event: InputEvent; text: Text }>;
|
||||
}[],
|
||||
reformat: SurroundFormat<T>[] = [],
|
||||
): void {
|
||||
triggers.map((trigger) =>
|
||||
trigger.on(async ({ text }) => {
|
||||
const remainingFormats = formats
|
||||
.filter(({ trigger }) => {
|
||||
if (get(trigger.active)) {
|
||||
// Deactivate active triggers for active formats.
|
||||
trigger.off();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Otherwise you are within the format. This is why we activate
|
||||
// the trigger, so that the active button is set to inactive.
|
||||
// We still need to remove the format however.
|
||||
trigger.on(asyncNoop);
|
||||
return true;
|
||||
})
|
||||
.map(({ format }) => format);
|
||||
|
||||
// Use an anonymous insertText handler instead of some trigger associated with a name
|
||||
this.#api!.inputHandler.insertText.on(
|
||||
async ({ text }) => {
|
||||
const range = new Range();
|
||||
range.selectNode(text);
|
||||
|
||||
const clearedRange = removeFormats(range, base, remove, reformat);
|
||||
const clearedRange = removeFormats(
|
||||
range,
|
||||
base,
|
||||
remainingFormats,
|
||||
reformat,
|
||||
);
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(clearedRange);
|
||||
selection.collapseToEnd();
|
||||
}),
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
}
|
||||
|
||||
private formats: Map<string, SurroundFormat<T>> = new Map();
|
||||
|
||||
/**
|
||||
* Register a surround format under a certain name.
|
||||
* This name is then used with the surround functions to actually apply or
|
||||
* remove the given format
|
||||
*/
|
||||
registerFormat(key: string, format: SurroundFormat<T>): () => void {
|
||||
this.formats.set(key, format);
|
||||
|
||||
if (this.api) {
|
||||
this.triggers.set(
|
||||
key,
|
||||
this.api.inputHandler.insertText.trigger({ once: true }),
|
||||
);
|
||||
}
|
||||
|
||||
return () => this.formats.delete(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a surround format under the given key is registered.
|
||||
*/
|
||||
hasFormat(key: string): boolean {
|
||||
return this.formats.has(key);
|
||||
return this.#formats.has(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a surround format under a certain key.
|
||||
* This name is then used with the surround functions to actually apply or
|
||||
* remove the given format.
|
||||
*/
|
||||
registerFormat(key: string, format: SurroundFormat<T>): () => void {
|
||||
this.#formats.set(key, format);
|
||||
|
||||
if (this.#api) {
|
||||
this.#triggers.set(
|
||||
key,
|
||||
this.#api.inputHandler.insertText.trigger({ once: true }),
|
||||
);
|
||||
}
|
||||
|
||||
return () => this.#formats.delete(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a surround format under a specific key.
|
||||
*/
|
||||
updateFormat(
|
||||
key: string,
|
||||
update: (format: SurroundFormat<T>) => SurroundFormat<T>,
|
||||
): void {
|
||||
this.#formats.set(key, update(this.#formats.get(key)!));
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -206,11 +243,11 @@ export class Surrounder<T = unknown> {
|
|||
* If the range is already surrounded, it will unsurround instead.
|
||||
*/
|
||||
async surround(formatName: string, exclusiveNames: string[] = []): Promise<void> {
|
||||
const base = await this._assert_base();
|
||||
const base = await this.#getBaseElement();
|
||||
const selection = getSelection(base)!;
|
||||
const range = getRange(selection);
|
||||
const format = this.formats.get(formatName);
|
||||
const trigger = this.triggers.get(formatName);
|
||||
const format = this.#formats.get(formatName);
|
||||
const trigger = this.#triggers.get(formatName);
|
||||
|
||||
if (!format || !range || !trigger) {
|
||||
return;
|
||||
|
@ -219,11 +256,11 @@ export class Surrounder<T = unknown> {
|
|||
const matcher = boolMatcher(format);
|
||||
|
||||
const exclusives = exclusiveNames
|
||||
.map((name) => this.formats.get(name))
|
||||
.map((name) => this.#formats.get(name))
|
||||
.filter(isValid);
|
||||
|
||||
if (range.collapsed) {
|
||||
return this._toggleTrigger(
|
||||
return this.#toggleTrigger(
|
||||
base,
|
||||
selection,
|
||||
matcher,
|
||||
|
@ -248,22 +285,22 @@ export class Surrounder<T = unknown> {
|
|||
formatName: string,
|
||||
exclusiveNames: string[] = [],
|
||||
): Promise<void> {
|
||||
const base = await this._assert_base();
|
||||
const base = await this.#getBaseElement();
|
||||
const selection = getSelection(base)!;
|
||||
const range = getRange(selection);
|
||||
const format = this.formats.get(formatName);
|
||||
const trigger = this.triggers.get(formatName);
|
||||
const format = this.#formats.get(formatName);
|
||||
const trigger = this.#triggers.get(formatName);
|
||||
|
||||
if (!format || !range || !trigger) {
|
||||
return;
|
||||
}
|
||||
|
||||
const exclusives = exclusiveNames
|
||||
.map((name) => this.formats.get(name))
|
||||
.map((name) => this.#formats.get(name))
|
||||
.filter(isValid);
|
||||
|
||||
if (range.collapsed) {
|
||||
return this._toggleTriggerOverwrite(
|
||||
return this.#toggleTriggerOverwrite(
|
||||
base,
|
||||
selection,
|
||||
format,
|
||||
|
@ -285,13 +322,13 @@ export class Surrounder<T = unknown> {
|
|||
* text insert).
|
||||
*/
|
||||
async isSurrounded(formatName: string): Promise<boolean> {
|
||||
const base = await this._assert_base();
|
||||
const base = await this.#getBaseElement();
|
||||
const selection = getSelection(base)!;
|
||||
const range = getRange(selection);
|
||||
const format = this.formats.get(formatName);
|
||||
const trigger = this.triggers.get(formatName);
|
||||
const format = this.#formats.get(formatName);
|
||||
const trigger = this.#triggers.get(formatName);
|
||||
|
||||
if (!format || !range || !trigger) {
|
||||
if (!range || !format || !trigger) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@ -303,7 +340,7 @@ export class Surrounder<T = unknown> {
|
|||
* Clear/Reformat the provided formats in the current range.
|
||||
*/
|
||||
async remove(formatNames: string[], reformatNames: string[] = []): Promise<void> {
|
||||
const base = await this._assert_base();
|
||||
const base = await this.#getBaseElement();
|
||||
const selection = getSelection(base)!;
|
||||
const range = getRange(selection);
|
||||
|
||||
|
@ -311,29 +348,39 @@ export class Surrounder<T = unknown> {
|
|||
return;
|
||||
}
|
||||
|
||||
const formats = formatNames
|
||||
.map((name) => this.formats.get(name))
|
||||
.filter(isValid);
|
||||
const activeFormats = formatNames
|
||||
.map((name: string) => ({
|
||||
name,
|
||||
format: this.#formats.get(name)!,
|
||||
trigger: this.#triggers.get(name)!,
|
||||
}))
|
||||
.filter(({ format, trigger }): boolean => {
|
||||
if (!format || !trigger) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const triggers = formatNames
|
||||
.map((name) => this.triggers.get(name))
|
||||
.filter(isValid);
|
||||
const isSurrounded = isSurroundedInner(
|
||||
range,
|
||||
base,
|
||||
boolMatcher(format),
|
||||
);
|
||||
return get(trigger.active) ? !isSurrounded : isSurrounded;
|
||||
});
|
||||
|
||||
const reformats = reformatNames
|
||||
.map((name) => this.formats.get(name))
|
||||
.map((name) => this.#formats.get(name))
|
||||
.filter(isValid);
|
||||
|
||||
if (range.collapsed) {
|
||||
return this._toggleTriggerRemove(
|
||||
base,
|
||||
selection,
|
||||
formats,
|
||||
triggers,
|
||||
reformats,
|
||||
);
|
||||
return this.#toggleTriggerRemove(base, selection, activeFormats, reformats);
|
||||
}
|
||||
|
||||
const surroundedRange = removeFormats(range, base, formats, reformats);
|
||||
const surroundedRange = removeFormats(
|
||||
range,
|
||||
base,
|
||||
activeFormats.map(({ format }) => format),
|
||||
reformats,
|
||||
);
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(surroundedRange);
|
||||
}
|
||||
|
|
|
@ -5,6 +5,10 @@ export function noop(): void {
|
|||
/* noop */
|
||||
}
|
||||
|
||||
export async function asyncNoop(): Promise<void> {
|
||||
/* noop */
|
||||
}
|
||||
|
||||
export function id<T>(t: T): T {
|
||||
return t;
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue