anki/ts/editor/rich-text-input/RichTextInput.svelte
Matthias Metelka 5f6ac1a916
Field redesign (#2002)
* Adjust size of legacy buttons

* Revert "Adjust size of legacy buttons"

This reverts commit fb888fe1db9050c34b1a7b0820e6da5ac91ccee6.

* Remove unused function from #1476

* Use outline version for tag icon

* Add chevron icons

* Remove code icons, keep one pin icon version

* Add code-bg color

* Redesign fields

* Remove unused import

* Fix imports

* Move PlainTextBadge between editing inputs

where it belongs :)

* Make whole separator line clickable

* Fix transition

and format

* Don't show toggle when field is collapsed

* Show toggle only on hover

for mobile I'd like to implement a swipe mechanism.

* Use tweened SVG for triangle instead of CSS hack

* Implement more obvious HTML toggle on bottom right

* Reduce field height by a few pixels

* Reduce field height by two pixels

* Show HTML toggle when PlainTextInput is active, regardless of hover/focus

* Remove RichTextBadge.svelte

* Create separate collapsed field state

this means users can collapse fields with the HTML editor open and it will stay open when the field is expanded again.

* Add slide out animation to EditingArea, RichTextInput and PlainTextInput

only for collapsing, because it is choppy on expansion (common issue with Svelte transitions).

* Fix aliasing issue on focused field corners

* Make StickyBadge feel more responsive

* Move StickyBadge closer to field border

* Adjust field gutter/margins

* Make LabelContainer sticky

to make field operations accessible on fields with a lot of content.

* Add back html icons, remove visual editor icons

* Revert "Add code-bg color"

This reverts commit 4200f354193710b3acd9bcf84b67958e200ddcdb.

* Add rich text icon, remove strikethrough code icon

* Revert PlainTextBadge to original position

* Adjust margins in FieldState

* Rename PlainTextBadge to SecondaryInputBadge

in preparation for #1987

* Run eslint and prettier

* Make whole LabelContainer clickable area for collapse/expand

* Revert "Add slide out animation to EditingArea, RichTextInput and PlainTextInput"

This reverts commit 9a2b3410d0ead37ae1da408d68e14507a058a613.

* Fix error on collapse/expansion

this was caused by the {#if} blocks, which resulted in the deletion of original EditingAreas.

* Refocus when toggling chevron and secondary input badge

* Revert "Revert "Add code-bg color""

This reverts commit 1cfd3bda65354ab90c1ab4cbbef47596a1be8754.

* Use single rotating chevron icon and make it RTL-compatible

* Remove redundant CSS transition rule

* Introduce animated Collapsible component and fix refocus on toggle

* Do not try to force repaint, as it is not required

* Remove RTL store from LabelContainer

the direction is already applied globally.

* Collapse secondary input with field

* Add focusedField to NoteEditorAPI

* Replace :global CSS selector with class .visible

thus removing the assumption that the component is used inside an EditorField.

https://github.com/ankitects/anki/pull/2002#discussion_r944876448

* Use named function syntax instead of function expressions

* Add explanation comment

* Remove unnecessary :bind directive

* Create CollapseBadge component

* Move :global selector into .plain-text-input

* Add comment explaining box-shadow pseudo-element

* Move Collapsible from EditingArea, PlainTextInput and RichTextInput into user components

* Rename SecondaryInputBadge to PlainTextBadge and remove generalization logic

I kept the rich text icon inside icons.ts for future use.

* Sort imports

* Fix background-color for duplicates not showing

with yet another pseudo-element :)

The pseudo-element that covers up field borders on scroll caused this issue. Fighting fire with fire here.

* Increase size of plain text toggle to original value again

This makes the clickable area a bit bigger and looks slightly more consistent with StickyBadge.

* Scrap pseudo-element mess in LabelContainer and tackle the actual issue

* Add class .visible to StickyBadge too

This introduces a peculiar bug: The active prop of StickyBadge resets to false when the mouse leaves the field - regardless of the actual back-end value.

* Fix sticky badge resetting on mouseleave/blur

* Apply overflow: hidden only during transition

fixes MathJax handle getting cut off by fields

* Remove unused variable

* Fix visual bug caused by overflow:hidden not applying in time

I tried several asynchronous approaches, but they all caused issues: either they prevented the CSS transition or they made field inputs lose focus.

In the end I resorted to direct, synchronous DOM-manipulation and added an explanatory comment.

* Decrease Collapsible load time by blocking first transition

I noticed the sliding animation has a hefty performance impact when a large number of fields is loaded simultaneously.

Blocking the first transition (which isn't even visible) results in a big boost in load time.

* Replace usages of gap with margins for children

* Revert unnecessary removal of grid-gap definition

* Correct comments about flex-gap property

mistook that for grid-gap.

* Resolve style issues

* Add minimum targets to gap comment

Co-authored-by: Henrik Giesel <hengiesel@gmail.com>
2022-08-19 10:02:28 +10:00

254 lines
8.1 KiB
Svelte

<!--
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";
import type { SurroundedAPI } from "../surround";
import type CustomStyles from "./CustomStyles.svelte";
export interface RichTextInputAPI extends EditingInputAPI, SurroundedAPI {
name: "rich-text";
/** This is the contentEditable anki-editable element */
element: Promise<HTMLElement>;
moveCaretToEnd(): void;
toggle(): boolean;
preventResubscription(): () => void;
inputHandler: InputHandlerAPI;
/** The API exposed by the editable component */
editable: ContentEditableAPI;
customStyles: Promise<CustomStyles>;
}
function editingInputIsRichText(
editingInput: EditingInputAPI | null,
): editingInput is RichTextInputAPI {
return editingInput?.name === "rich-text";
}
import { registerPackage } from "../../lib/runtime-require";
import contextProperty from "../../sveltelib/context-property";
import lifecycleHooks from "../../sveltelib/lifecycle-hooks";
import { Surrounder } from "../surround";
const key = Symbol("richText");
const [context, setContextProperty] = contextProperty<RichTextInputAPI>(key);
const [globalInputHandler, setupGlobalInputHandler] = useInputHandler();
const [lifecycle, instances, setupLifecycleHooks] =
lifecycleHooks<RichTextInputAPI>();
const apiStore = writable<SurroundedAPI | null>(null);
const surrounder = Surrounder.make(apiStore);
registerPackage("anki/RichTextInput", {
context,
surrounder,
lifecycle,
instances,
});
export {
context,
editingInputIsRichText,
globalInputHandler as inputHandler,
surrounder,
};
</script>
<script lang="ts">
import { getAllContexts, getContext, onMount } from "svelte";
import type { Readable } from "svelte/store";
import { placeCaretAfterContent } from "../../domlib/place-caret";
import ContentEditable from "../../editable/ContentEditable.svelte";
import { directionKey, fontFamilyKey, fontSizeKey } from "../../lib/context-keys";
import { promiseWithResolver } from "../../lib/promise";
import { singleCallback } from "../../lib/typing";
import useDOMMirror from "../../sveltelib/dom-mirror";
import useInputHandler from "../../sveltelib/input-handler";
import { pageTheme } from "../../sveltelib/theme";
import { context as editingAreaContext } from "../EditingArea.svelte";
import { context as noteEditorContext } from "../NoteEditor.svelte";
import getNormalizingNodeStore from "./normalizing-node-store";
import useRichTextResolve from "./rich-text-resolve";
import RichTextStyles from "./RichTextStyles.svelte";
import { fragmentToStored, storedToFragment } from "./transform";
export let hidden: boolean;
const { focusedInput } = noteEditorContext.get();
const { content, editingInputs } = editingAreaContext.get();
const fontFamily = getContext<Readable<string>>(fontFamilyKey);
const fontSize = getContext<Readable<number>>(fontSizeKey);
const direction = getContext<Readable<"ltr" | "rtl">>(directionKey);
const nodes = getNormalizingNodeStore();
const [richTextPromise, resolve] = useRichTextResolve();
const { mirror, preventResubscription } = useDOMMirror();
const [inputHandler, setupInputHandler] = useInputHandler();
const [customStyles, stylesResolve] = promiseWithResolver<CustomStyles>();
export function attachShadow(element: Element): void {
element.attachShadow({ mode: "open" });
}
async function moveCaretToEnd(): Promise<void> {
const richText = await richTextPromise;
if (richText.textContent?.length === 0) {
// Calling this method when richText is empty will cause the first keystroke of
// ibus-based input methods with candidates to go double. For example, if you
// type "a" it becomes "aa". This problem exists in many linux distributions.
// When richText is empty, there is no need to place the caret, just return.
return;
}
placeCaretAfterContent(richText);
}
async function focus(): Promise<void> {
const richText = await richTextPromise;
richText.focus();
}
async function refocus(): Promise<void> {
const richText = await richTextPromise;
richText.blur();
richText.focus();
moveCaretToEnd();
}
function toggle(): boolean {
hidden = !hidden;
return hidden;
}
const className = "rich-text-editable";
let richTextDiv: HTMLElement;
async function getInputAPI(target: EventTarget): Promise<FocusableInputAPI | null> {
if (target === richTextDiv) {
return api;
}
return null;
}
export const api: RichTextInputAPI = {
name: "rich-text",
element: richTextPromise,
focus,
refocus,
focusable: !hidden,
toggle,
getInputAPI,
moveCaretToEnd,
preventResubscription,
inputHandler,
editable: {} as ContentEditableAPI,
customStyles,
};
const allContexts = getAllContexts();
function attachContentEditable(element: Element, { stylesDidLoad }): void {
(async () => {
await stylesDidLoad;
new ContentEditable({
target: element.shadowRoot!,
props: {
nodes,
resolve,
mirrors: [mirror],
inputHandlers: [setupInputHandler, setupGlobalInputHandler],
api: api.editable,
},
context: allContexts,
});
})();
}
function pushUpdate(isFocusable: boolean): void {
api.focusable = isFocusable;
$editingInputs = $editingInputs;
}
function setFocus(): void {
$focusedInput = 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.
$apiStore = null;
}
$: pushUpdate(!hidden);
onMount(() => {
$editingInputs.push(api);
$editingInputs = $editingInputs;
return singleCallback(
content.subscribe((html: string): void =>
nodes.setUnprocessed(storedToFragment(html)),
),
nodes.subscribe((fragment: DocumentFragment): void =>
content.set(fragmentToStored(fragment)),
),
);
});
setContextProperty(api);
setupLifecycleHooks(api);
</script>
<div class="rich-text-input" on:focusin={setFocus} on:focusout={removeFocus}>
<RichTextStyles
color={$pageTheme.isDark ? "white" : "black"}
fontFamily={$fontFamily}
fontSize={$fontSize}
direction={$direction}
callback={stylesResolve}
let:attachToShadow={attachStyles}
let:stylesDidLoad
>
<div
bind:this={richTextDiv}
class={className}
class:night-mode={$pageTheme.isDark}
use:attachShadow
use:attachStyles
use:attachContentEditable={{ stylesDidLoad }}
on:focusin
on:focusout
/>
{#await Promise.all([richTextPromise, stylesDidLoad]) then _}
<div class="rich-text-widgets">
<slot />
</div>
{/await}
</RichTextStyles>
<slot name="plain-text-badge" />
</div>
<style lang="scss">
.rich-text-input {
position: relative;
padding: 6px;
}
.hidden {
display: none;
}
</style>