anki/ts/editor/mathjax-overlay/MathjaxOverlay.svelte
Henrik Giesel 3642dc6245
Use WithFloating for MathjaxOverlay (#2011)
* Allow passing in reference into WithFloating as prop

* Fix WithAutocomplete

* Fix WithFloating for MathjaxOverlay

* Add resize-store

* Allow passing debug=True to jest_test for debugger support (#2013)

* Disable auto-closing of HTML tags

https://forums.ankiweb.net/t/set-html-editor-as-a-default-editor-instead-of-visual-editor/20988/3

Closes #1963

* Add slight margin to MathjaxEditor

* Enable passing offset and shift to WithFloating

* Hide overflow of mathjax editor

* Add automatic hide functionality to sveltelib/position

* Last polishes for Surrounder class (#2017)

* Make private properties in Surrounder truly private

* Fix remove logic of Surrounder

* No reason for toggleTriggerRemove to be async

* Allow using alt-shift to set all remove formats but this one

* modifyFormat => updateFormat

* Fix formatting

* Fix field descriptions blocking cursor from being set (#2018)

- happens when focus is in HTML editor

* Remove hiding functionality again until it's really useful

* Add support for autoPlacement

* Implement new WithFloating that supports manually calling position()

* Implement hide mechanisms

* Add option in math dropdown to toggle MathJax rendering (#2014)

* Add option in math dropdown to toggle MathJax rendering

Closes #1942

* Hackily redraw the page when toggling MathJax

* Add Fluent string

* Default input setting in fields dialog (#1987) (kleinerpirat)

* Introduce field setting to use plain text editor by default (kleinerpirat)

* Remove leftover function from #1476

* Use boolean instead of string

* Simplify clear_other_field_duplicates

* Convert plain text key to camelCase

* Move HTML item below the existing checkbox, instead of to the right (dae)

Showing it on the right is more space efficient, but feels a bit
cluttered IMHO.

* Fix not being able to scroll when mouse hovers PlainTextInput (#2019)

* Remove overscroll-behavior: none for * (all elements)

* Revert "Remove overscroll-behavior: none for * (all elements)"

This reverts commit 189358908cecd03027e19d8fe47822735319ec17.

* Use body instead of *, but keep CSS rule

* Unify two CSS rules

* Remove console.logs

* Reposition mathjax menu on switching between inline/block

* Implement WithOverlay

* Implement FloatingArrow

* Display overlay with padding and brighter background

* Rename to MathjaxOverlay

* Simplify MathjaxOverlay component overall

* Rename ImageHandle to image overlay

* Generally fix ImageOverlay again

* Increase z-index of StickyContainer

* Fix setting block or inline on mathjax

* Add reasons in closing-{click,keyup}

* Have both WithFloating and WithOverlay use a simple show flag instead of a store

* Remove subscribe-trigger

* Fix clicking from one mathjax element to another

* Check before executing cleanup

* Do not wait for elements to mount before slotting in With{Floating,Overlay}

* Allow using reference slot for WithFloating and WithOveray

* Add inline argument to options

* Add support for inline slot in WithOvelay

* Use WithFloating for RemoveFormatButton

* Remove last uses of DropdownMenu and WithDropdown

* Remove all of the bootstrap dropdown components

* Fix closing behavior of several buttons and ImageOverlay

* Increase popover padding to 6px

* Find a different way to create some padding at the bottom of the fields

...before the tag editor

@kleinerpirat I think is what this css what trying to achieve?

* Satisfy tests

* Use removeStyleProperties in ImageOverlay

* Use notify function in WithOverlay and WithFloating

* Do not use portal for WithFloating and WithOverlay

Allows for scrolling

* Set hidden to default false in Rich/Plain TextInput

* Reset handle when changing mathjax elements via click

* Restrict size of empty mathjax image

* Prevent sticky labels from obscuring menus

* Remove several overflow-hidden

* Fix empty string being falsy bug when editing mathjax

* Do not import portal anymore

* Use { reason, originalEvent } instead of symbol as update to modified event store

* Fix closing behavior of image overlay (do not close after resize)

* Simplify Collapsible

* Use removeStyleProperties in Collapsible

* Satisfy eslint

* Fix latex shortcuts being mounted

* Fix mathjax overlay not focusable in first field

* Neither hide image overlay on escaped

* Fix Block ButtonDropdown wrapping

* Bring back portal to fix tag editor
2022-09-05 17:20:00 +10:00

245 lines
8.4 KiB
Svelte

<!--
Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import type CodeMirrorLib from "codemirror";
import { onMount, tick } from "svelte";
import { writable } from "svelte/store";
import Popover from "../../components/Popover.svelte";
import Shortcut from "../../components/Shortcut.svelte";
import WithFloating from "../../components/WithFloating.svelte";
import WithOverlay from "../../components/WithOverlay.svelte";
import { placeCaretAfter } from "../../domlib/place-caret";
import { escapeSomeEntities, unescapeSomeEntities } from "../../editable/mathjax";
import { Mathjax } from "../../editable/mathjax-element";
import { hasBlockAttribute } from "../../lib/dom";
import { on } from "../../lib/events";
import { noop } from "../../lib/functional";
import type { Callback } from "../../lib/typing";
import { singleCallback } from "../../lib/typing";
import HandleBackground from "../HandleBackground.svelte";
import { context } from "../rich-text-input";
import MathjaxButtons from "./MathjaxButtons.svelte";
import MathjaxEditor from "./MathjaxEditor.svelte";
const { editable, element, preventResubscription } = context.get();
let activeImage: HTMLImageElement | null = null;
let mathjaxElement: HTMLElement | null = null;
let allow = noop;
let unsubscribe = noop;
let selectAll = false;
let position: CodeMirrorLib.Position | undefined = undefined;
/**
* Will contain the Mathjax text with unescaped entities.
* This is the text displayed in the actual editor window.
*/
const code = writable("");
function showOverlay(image: HTMLImageElement, pos?: CodeMirrorLib.Position): void {
allow = preventResubscription();
position = pos;
/* Setting the activeImage and mathjaxElement to a non-nullish value is
* what triggers the Mathjax editor to show */
activeImage = image;
mathjaxElement = activeImage.closest(Mathjax.tagName)!;
code.set(unescapeSomeEntities(mathjaxElement.dataset.mathjax ?? ""));
unsubscribe = code.subscribe((value: string) => {
mathjaxElement!.dataset.mathjax = escapeSomeEntities(value);
});
}
function placeHandle(after: boolean): void {
editable.focusHandler.flushCaret();
if (after) {
(mathjaxElement as any).placeCaretAfter();
} else {
(mathjaxElement as any).placeCaretBefore();
}
}
async function resetHandle(): Promise<void> {
selectAll = false;
position = undefined;
if (activeImage && mathjaxElement) {
unsubscribe();
activeImage = null;
mathjaxElement = null;
}
allow();
// Wait for a tick, so that moving from one Mathjax element to
// another will remount the MathjaxEditor
await tick();
}
let errorMessage: string;
let cleanup: Callback | null = null;
async function updateErrorMessage(): Promise<void> {
errorMessage = activeImage!.title;
}
async function updateImageErrorCallback(image: HTMLImageElement | null) {
cleanup?.();
cleanup = null;
if (!image) {
return;
}
cleanup = on(image, "resize", updateErrorMessage);
}
$: updateImageErrorCallback(activeImage);
async function showOverlayIfMathjaxClicked({ target }: Event): Promise<void> {
if (target instanceof HTMLImageElement && target.dataset.anki === "mathjax") {
await resetHandle();
showOverlay(target);
}
}
async function showOnAutofocus({
detail,
}: CustomEvent<{
image: HTMLImageElement;
position?: [number, number];
}>): Promise<void> {
let position: CodeMirrorLib.Position | undefined = undefined;
if (detail.position) {
const [line, ch] = detail.position;
position = { line, ch };
}
showOverlay(detail.image, position);
}
async function showSelectAll({
detail,
}: CustomEvent<HTMLImageElement>): Promise<void> {
selectAll = true;
showOverlay(detail);
}
onMount(async () => {
const container = await element;
return singleCallback(
on(container, "click", showOverlayIfMathjaxClicked),
on(container, "movecaretafter" as any, showOnAutofocus),
on(container, "selectall" as any, showSelectAll),
);
});
let isBlock: boolean;
$: isBlock = mathjaxElement ? hasBlockAttribute(mathjaxElement) : false;
async function updateBlockAttribute(): Promise<void> {
mathjaxElement!.setAttribute("block", String(isBlock));
// We assume that by the end of this tick, the image will have
// adjusted its styling to either block or inline
await tick();
}
const acceptShortcut = "Enter";
const newlineShortcut = "Shift+Enter";
</script>
<div class="mathjax-overlay">
{#if activeImage && mathjaxElement}
<WithOverlay
reference={activeImage}
padding={isBlock ? 10 : 3}
keepOnKeyup
let:position={positionOverlay}
>
<WithFloating
reference={activeImage}
placement="auto"
offset={20}
keepOnKeyup
let:position={positionFloating}
on:close={resetHandle}
>
<Popover slot="floating">
<MathjaxEditor
{acceptShortcut}
{newlineShortcut}
{code}
{selectAll}
{position}
on:moveoutstart={async () => {
placeHandle(false);
await resetHandle();
}}
on:moveoutend={async () => {
placeHandle(true);
await resetHandle();
}}
on:tab={async () => {
// Instead of resetting on blur, we reset on tab
// Otherwise, when clicking from Mathjax element to another,
// the user has to click twice (focus is called before blur?)
await resetHandle();
}}
let:editor={mathjaxEditor}
>
<Shortcut
keyCombination={acceptShortcut}
on:action={async () => {
placeHandle(true);
await resetHandle();
}}
/>
<MathjaxButtons
{isBlock}
on:setinline={async () => {
isBlock = false;
await updateBlockAttribute();
positionOverlay();
positionFloating();
}}
on:setblock={async () => {
isBlock = true;
await updateBlockAttribute();
positionOverlay();
positionFloating();
}}
on:delete={async () => {
placeCaretAfter(activeImage);
activeImage.remove();
await resetHandle();
}}
on:surround={async ({ detail }) => {
const editor = await mathjaxEditor.editor;
const { prefix, suffix } = detail;
editor.replaceSelection(
prefix + editor.getSelection() + suffix,
);
}}
/>
</MathjaxEditor>
</Popover>
</WithFloating>
<svelte:fragment slot="overlay">
<HandleBackground tooltip={errorMessage} />
</svelte:fragment>
</WithOverlay>
{/if}
</div>