5f6ac1a916
* 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>
452 lines
16 KiB
Svelte
452 lines
16 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 type { Writable } from "svelte/store";
|
|
|
|
import Collapsible from "../components/Collapsible.svelte";
|
|
import type { EditingInputAPI } from "./EditingArea.svelte";
|
|
import type { EditorToolbarAPI } from "./editor-toolbar";
|
|
import type { EditorFieldAPI } from "./EditorField.svelte";
|
|
import FieldState from "./FieldState.svelte";
|
|
import LabelContainer from "./LabelContainer.svelte";
|
|
import LabelName from "./LabelName.svelte";
|
|
|
|
export interface NoteEditorAPI {
|
|
fields: EditorFieldAPI[];
|
|
hoveredField: Writable<EditorFieldAPI | null>;
|
|
focusedField: Writable<EditorFieldAPI | null>;
|
|
focusedInput: Writable<EditingInputAPI | null>;
|
|
toolbar: EditorToolbarAPI;
|
|
}
|
|
|
|
import { registerPackage } from "../lib/runtime-require";
|
|
import contextProperty from "../sveltelib/context-property";
|
|
import lifecycleHooks from "../sveltelib/lifecycle-hooks";
|
|
|
|
const key = Symbol("noteEditor");
|
|
const [context, setContextProperty] = contextProperty<NoteEditorAPI>(key);
|
|
const [lifecycle, instances, setupLifecycleHooks] = lifecycleHooks<NoteEditorAPI>();
|
|
|
|
export { context };
|
|
|
|
registerPackage("anki/NoteEditor", {
|
|
context,
|
|
lifecycle,
|
|
instances,
|
|
});
|
|
</script>
|
|
|
|
<script lang="ts">
|
|
import { onMount, tick } from "svelte";
|
|
import { get, writable } from "svelte/store";
|
|
|
|
import Absolute from "../components/Absolute.svelte";
|
|
import Badge from "../components/Badge.svelte";
|
|
import StickyContainer from "../components/StickyContainer.svelte";
|
|
import { bridgeCommand } from "../lib/bridgecommand";
|
|
import { TagEditor } from "../tag-editor";
|
|
import { ChangeTimer } from "./change-timer";
|
|
import DecoratedElements from "./DecoratedElements.svelte";
|
|
import { clearableArray } from "./destroyable";
|
|
import DuplicateLink from "./DuplicateLink.svelte";
|
|
import EditorToolbar from "./editor-toolbar";
|
|
import type { FieldData } from "./EditorField.svelte";
|
|
import EditorField from "./EditorField.svelte";
|
|
import FieldDescription from "./FieldDescription.svelte";
|
|
import Fields from "./Fields.svelte";
|
|
import FieldsEditor from "./FieldsEditor.svelte";
|
|
import FrameElement from "./FrameElement.svelte";
|
|
import { alertIcon } from "./icons";
|
|
import ImageHandle from "./image-overlay";
|
|
import MathjaxHandle from "./mathjax-overlay";
|
|
import MathjaxElement from "./MathjaxElement.svelte";
|
|
import Notification from "./Notification.svelte";
|
|
import PlainTextInput from "./plain-text-input";
|
|
import PlainTextBadge from "./PlainTextBadge.svelte";
|
|
import RichTextInput, { editingInputIsRichText } from "./rich-text-input";
|
|
|
|
function quoteFontFamily(fontFamily: string): string {
|
|
// generic families (e.g. sans-serif) must not be quoted
|
|
if (!/^[-a-z]+$/.test(fontFamily)) {
|
|
fontFamily = `"${fontFamily}"`;
|
|
}
|
|
return fontFamily;
|
|
}
|
|
|
|
const size = 1.6;
|
|
const wrap = true;
|
|
|
|
const fieldStores: Writable<string>[] = [];
|
|
let fieldNames: string[] = [];
|
|
export function setFields(fs: [string, string][]): void {
|
|
// this is a bit of a mess -- when moving to Rust calls, we should make
|
|
// sure to have two backend endpoints for:
|
|
// * the note, which can be set through this view
|
|
// * the fieldname, font, etc., which cannot be set
|
|
|
|
const newFieldNames: string[] = [];
|
|
|
|
for (const [index, [fieldName]] of fs.entries()) {
|
|
newFieldNames[index] = fieldName;
|
|
}
|
|
|
|
for (let i = fieldStores.length; i < newFieldNames.length; i++) {
|
|
const newStore = writable("");
|
|
fieldStores[i] = newStore;
|
|
newStore.subscribe((value) => updateField(i, value));
|
|
}
|
|
|
|
for (
|
|
let i = fieldStores.length;
|
|
i > newFieldNames.length;
|
|
i = fieldStores.length
|
|
) {
|
|
fieldStores.pop();
|
|
}
|
|
|
|
for (const [index, [, fieldContent]] of fs.entries()) {
|
|
fieldStores[index].set(fieldContent);
|
|
}
|
|
|
|
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 fieldsCollapsed: boolean[] = [];
|
|
|
|
const fields = clearableArray<EditorFieldAPI>();
|
|
|
|
export function setFonts(fs: [string, number, boolean][]): void {
|
|
fonts = fs;
|
|
fieldsCollapsed = fonts.map((_, index) => fieldsCollapsed[index] ?? false);
|
|
}
|
|
|
|
export function focusField(index: number | null): void {
|
|
tick().then(() => {
|
|
if (typeof index === "number") {
|
|
if (!(index in fields)) {
|
|
return;
|
|
}
|
|
|
|
fields[index].editingArea?.refocus();
|
|
} else {
|
|
$focusedInput?.refocus();
|
|
}
|
|
});
|
|
}
|
|
|
|
const tags = writable<string[]>([]);
|
|
export function setTags(ts: string[]): void {
|
|
$tags = ts;
|
|
}
|
|
|
|
let noteId: number | null = null;
|
|
export function setNoteId(ntid: number): void {
|
|
// TODO this is a hack, because it requires the NoteEditor to know implementation details of the PlainTextInput.
|
|
// It should be refactored once we work on our own Undo stack
|
|
for (const pi of plainTextInputs) {
|
|
pi.api.codeMirror.editor.then((editor) => editor.clearHistory());
|
|
}
|
|
noteId = ntid;
|
|
}
|
|
|
|
function getNoteId(): number | null {
|
|
return noteId;
|
|
}
|
|
|
|
let cols: ("dupe" | "")[] = [];
|
|
export function setBackgrounds(cls: ("dupe" | "")[]): void {
|
|
cols = cls;
|
|
}
|
|
|
|
let hint: string = "";
|
|
export function setClozeHint(hnt: string): void {
|
|
hint = hnt;
|
|
}
|
|
|
|
$: fieldsData = fieldNames.map((name, index) => ({
|
|
name,
|
|
plainText: plainTexts[index],
|
|
description: fieldDescriptions[index],
|
|
fontFamily: quoteFontFamily(fonts[index][0]),
|
|
fontSize: fonts[index][1],
|
|
direction: fonts[index][2] ? "rtl" : "ltr",
|
|
})) as FieldData[];
|
|
|
|
function saveTags({ detail }: CustomEvent): void {
|
|
bridgeCommand(`saveTags:${JSON.stringify(detail.tags)}`);
|
|
}
|
|
|
|
const fieldSave = new ChangeTimer();
|
|
|
|
function updateField(index: number, content: string): void {
|
|
fieldSave.schedule(
|
|
() => bridgeCommand(`key:${index}:${getNoteId()}:${content}`),
|
|
600,
|
|
);
|
|
}
|
|
|
|
export function saveFieldNow(): void {
|
|
/* this will always be a key save */
|
|
fieldSave.fireImmediately();
|
|
}
|
|
|
|
export function saveOnPageHide() {
|
|
if (document.visibilityState === "hidden") {
|
|
// will fire on session close and minimize
|
|
saveFieldNow();
|
|
}
|
|
}
|
|
|
|
export function focusIfField(x: number, y: number): boolean {
|
|
const elements = document.elementsFromPoint(x, y);
|
|
const first = elements[0];
|
|
|
|
if (first.shadowRoot) {
|
|
const richTextInput = first.shadowRoot.lastElementChild! as HTMLElement;
|
|
richTextInput.focus();
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
let richTextInputs: RichTextInput[] = [];
|
|
$: richTextInputs = richTextInputs.filter(Boolean);
|
|
|
|
let plainTextInputs: PlainTextInput[] = [];
|
|
$: plainTextInputs = plainTextInputs.filter(Boolean);
|
|
|
|
const toolbar: Partial<EditorToolbarAPI> = {};
|
|
|
|
import { mathjaxConfig } from "../editable/mathjax-element";
|
|
import { wrapInternal } from "../lib/wrap";
|
|
import * as oldEditorAdapter from "./old-editor-adapter";
|
|
|
|
onMount(() => {
|
|
function wrap(before: string, after: string): void {
|
|
if (!$focusedInput || !editingInputIsRichText($focusedInput)) {
|
|
return;
|
|
}
|
|
|
|
$focusedInput.element.then((element) => {
|
|
wrapInternal(element, before, after, false);
|
|
});
|
|
}
|
|
|
|
Object.assign(globalThis, {
|
|
setFields,
|
|
setPlainTexts,
|
|
setDescriptions,
|
|
setFonts,
|
|
focusField,
|
|
setTags,
|
|
setBackgrounds,
|
|
setClozeHint,
|
|
saveNow: saveFieldNow,
|
|
focusIfField,
|
|
getNoteId,
|
|
setNoteId,
|
|
wrap,
|
|
setMathjaxEnabled,
|
|
...oldEditorAdapter,
|
|
});
|
|
|
|
document.addEventListener("visibilitychange", saveOnPageHide);
|
|
return () => document.removeEventListener("visibilitychange", saveOnPageHide);
|
|
});
|
|
|
|
let apiPartial: Partial<NoteEditorAPI> = {};
|
|
export { apiPartial as api };
|
|
|
|
const hoveredField: NoteEditorAPI["hoveredField"] = writable(null);
|
|
const focusedField: NoteEditorAPI["focusedField"] = writable(null);
|
|
const focusedInput: NoteEditorAPI["focusedInput"] = writable(null);
|
|
|
|
const api: NoteEditorAPI = {
|
|
...apiPartial,
|
|
hoveredField,
|
|
focusedField,
|
|
focusedInput,
|
|
toolbar: toolbar as EditorToolbarAPI,
|
|
fields,
|
|
};
|
|
|
|
setContextProperty(api);
|
|
setupLifecycleHooks(api);
|
|
</script>
|
|
|
|
<!--
|
|
@component
|
|
Serves as a pre-slotted convenience component which combines all the common
|
|
components and functionality for general note editing.
|
|
|
|
Functionality exclusive to specifc note-editing views (e.g. in the browser or
|
|
the AddCards dialog) should be implemented in the user of this component.
|
|
-->
|
|
<div class="note-editor">
|
|
<FieldsEditor>
|
|
<EditorToolbar {size} {wrap} api={toolbar}>
|
|
<slot slot="notetypeButtons" name="notetypeButtons" />
|
|
</EditorToolbar>
|
|
|
|
{#if hint}
|
|
<Absolute bottom right --margin="10px">
|
|
<Notification>
|
|
<Badge --badge-color="tomato" --icon-align="top"
|
|
>{@html alertIcon}</Badge
|
|
>
|
|
<span>{@html hint}</span>
|
|
</Notification>
|
|
</Absolute>
|
|
{/if}
|
|
|
|
<Fields>
|
|
<DecoratedElements>
|
|
{#each fieldsData as field, index}
|
|
{@const content = fieldStores[index]}
|
|
|
|
<EditorField
|
|
{field}
|
|
{content}
|
|
api={fields[index]}
|
|
on:focusin={() => {
|
|
$focusedField = fields[index];
|
|
bridgeCommand(`focus:${index}`);
|
|
}}
|
|
on:focusout={() => {
|
|
$focusedField = null;
|
|
bridgeCommand(
|
|
`blur:${index}:${getNoteId()}:${get(content)}`,
|
|
);
|
|
}}
|
|
on:mouseenter={() => {
|
|
$hoveredField = fields[index];
|
|
}}
|
|
on:mouseleave={() => {
|
|
$hoveredField = null;
|
|
}}
|
|
collapsed={fieldsCollapsed[index]}
|
|
--label-color={cols[index] === "dupe"
|
|
? "var(--flag1-bg)"
|
|
: "var(--window-bg)"}
|
|
>
|
|
<svelte:fragment slot="field-label">
|
|
<LabelContainer
|
|
collapsed={fieldsCollapsed[index]}
|
|
on:toggle={async () => {
|
|
fieldsCollapsed[index] = !fieldsCollapsed[index];
|
|
|
|
if (!fieldsCollapsed[index]) {
|
|
await tick();
|
|
richTextInputs[index].api.refocus();
|
|
} else {
|
|
plainTextsHidden[index] = true;
|
|
}
|
|
}}
|
|
>
|
|
<svelte:fragment slot="field-name">
|
|
<LabelName>
|
|
{field.name}
|
|
</LabelName>
|
|
</svelte:fragment>
|
|
<FieldState>
|
|
{#if cols[index] === "dupe"}
|
|
<DuplicateLink />
|
|
{/if}
|
|
<PlainTextBadge
|
|
visible={!fieldsCollapsed[index] &&
|
|
(fields[index] === $hoveredField ||
|
|
fields[index] === $focusedField)}
|
|
bind:off={plainTextsHidden[index]}
|
|
on:toggle={async () => {
|
|
plainTextsHidden[index] =
|
|
!plainTextsHidden[index];
|
|
|
|
if (!plainTextsHidden[index]) {
|
|
await tick();
|
|
plainTextInputs[index].api.refocus();
|
|
}
|
|
}}
|
|
/>
|
|
<slot
|
|
name="field-state"
|
|
{field}
|
|
{index}
|
|
visible={fields[index] === $hoveredField ||
|
|
fields[index] === $focusedField}
|
|
/>
|
|
</FieldState>
|
|
</LabelContainer>
|
|
</svelte:fragment>
|
|
<svelte:fragment slot="editing-inputs">
|
|
<Collapsible collapsed={richTextsHidden[index]}>
|
|
<RichTextInput
|
|
bind:hidden={richTextsHidden[index]}
|
|
on:focusout={() => {
|
|
saveFieldNow();
|
|
$focusedInput = null;
|
|
}}
|
|
bind:this={richTextInputs[index]}
|
|
>
|
|
<ImageHandle maxWidth={250} maxHeight={125} />
|
|
<MathjaxHandle />
|
|
<FieldDescription>
|
|
{field.description}
|
|
</FieldDescription>
|
|
</RichTextInput>
|
|
</Collapsible>
|
|
|
|
<Collapsible collapsed={plainTextsHidden[index]}>
|
|
<PlainTextInput
|
|
bind:hidden={plainTextsHidden[index]}
|
|
on:focusout={() => {
|
|
saveFieldNow();
|
|
$focusedInput = null;
|
|
}}
|
|
bind:this={plainTextInputs[index]}
|
|
/>
|
|
</Collapsible>
|
|
</svelte:fragment>
|
|
</EditorField>
|
|
{/each}
|
|
|
|
<MathjaxElement />
|
|
<FrameElement />
|
|
</DecoratedElements>
|
|
</Fields>
|
|
</FieldsEditor>
|
|
|
|
<StickyContainer --gutter-block="0.1rem" --sticky-borders="1px 0 0" class="d-flex">
|
|
<TagEditor {tags} on:tagsupdate={saveTags} />
|
|
</StickyContainer>
|
|
</div>
|
|
|
|
<style lang="scss">
|
|
.note-editor {
|
|
height: 100%;
|
|
display: flex;
|
|
flex-direction: column;
|
|
}
|
|
</style>
|