8b84368e3a
* Clarify some comments * Don't destructure insertion trigger * Make superscript and subscript use domlib/surround * Create new {Text,Highlight}ColorButton * Use domlib/surround for textcolor - However there's still a crucial bug, when you're breaking existing colored span when unsurrounding, their color is not restored * Add underline format to removeFormats * Simplify type of ElementMatcher and ElementClearer for end users * Add some comments for normalize-insertion-ranges * Split normalize-insertion-ranges into remove-adjacent and remove-within * Factor out find-remove from unsurround.ts * Rename merge-mach, simplify remove-within * Clarify some comments * Refactor first reduce * Refactor reduceRight * Flatten functions in merge-ranges * Move some functionality to merge-ranges and do not export * Refactor merge-ranges * Remove createInitialMergeMatch * Finish refactoring of merge-ranges * Refactor merge-ranges to minimal-ranges and add some unit testing * Move more logic into text-node * Remove most most of the logic from remove-adjacent - remove-adjacent is still part of the "merging" logic, as it increases the scope of the child node ranges * Add some tests for edge cases * Merge remove-adjacent logic into minimal-ranges * Refactor unnecessary list destructuring * Add some TODOs * Put removing nodes and adding new nodes into sequence * Refactor MatchResult to MatchType and return clear from matcher * Inline surround/helpers * Shorten name of param * Add another edge case test * Add an example where commonAncestorContainer != normalization level * Fix bug in find-adjacent when find more than one nested nodes * Allow comments for Along type * Simplify find-adjacent by removing intermediate and/or curried functions * Remove extend-adjacent * Add more tests when find-adjacent finds by descension * Fix find-adjacent descending into block-level elements * Add clarifying comment to refusing to descend into block-level elements * Move shifting logic into find-adjacent * Rename file matcher to match-type * Give a first implemention of TreeVertex * Remove MatchType.ALONG - findAdjacent now directly modifies the range * Rename MatchType.MATCH into MatchType.REMOVE * Implement a version of find-within that utilizies match-tree * Turn child node range into a class * Fix bug in new find-adjacent function * Make all find-adjacent tests test for ranges * Surrounding within farthestMatchingAncestor when available * Fix an issue with negligable elements - also rename "along" elements to "negligable" * Add two TODOs to SurroundFormat interface * Have a messy first implementation of the new tree-node algorithm * Maintain whether formatting nodes are covered or within user selection * Move covered and insideRange into TreeNode superclass * Reimplement findAdjacent logic * Add extension logic * Add an evaluate method to nodes * Introduce BlockNode * Add a first evaluate implementation * Add left shift and inner shift logic * Implement SurroundFormatUser * Allow pass in formatter, ascender and merger from outside * Fix insideRange and covered switch-up * Fix MatchNode.prototype.isAscendable * Fix another switch-up of covered and insideRange... * Remove a lot of old code * Have surround functions only return the range - I still cannot think of a good reason why we should return addedNodes and removedNodes, except for testing. * Create formatting-tree directory * Create build-tree directory + Move find-above up to /domlib * Remove range-anchors * Move unsurround logic into no-splitting * Fix extend-merge * Fix inner shift being eroneusly returned as left shift * Fix oversight in SplitRange * Redefine how ranges are recreated * Rename covered to insideMatch and put as fourth parameter instead of third * Keep track of match holes and match leaves * Rename ChildNodeRange to FlatRange * Change signature of matcher * Fix bug in extend-merge * Improve Match class * Utilize cache in TextColorButton * Implement getBaseSurrounder for TextColorButton * Add matchAncestors field to FormattingNode * Introduce matchAncestors and getCache * Do clearing during parsing already - This way, you know whether elements will be removed before getting to Formatting nodes * Make HighlightColorButton use our surround mechanism * Fix a bug with calling .removeAttribute and .hasAttribute * Add side button to RemoveFormat button * Add disabled to remove format side button * Expose remove formats on RemoveFormat button * Reinvent editor/surround as Surrounder class * Fix split-text when working with insert trigger * Try counteracting the contenteditable's auto surrounding * Remove matching elements before normalizing * Rewrite match-type * Move setting match leaves into build * Change editing strings - So that color strings match bold/italic strings better * Fix border radius of List options menu * Implement extensions functionality * Remove some unnecessary code * Fix split range endOffset * Type MatchType * Reformat MatchType + add docs * Fix domlib/surround/apply * Satisfy last tests * Register Surrounder as package * Clarify some comments * Correctly implement reformat * Reformat with inactive eraser formats * Clear empty spans with RemoveFormatButton * Fix Super/Subscript button * Use ftl string for hardcoded tooltip * Adjust wording
292 lines
9.0 KiB
Svelte
292 lines
9.0 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 { ContentEditableAPI } from "../../editable/ContentEditable.svelte";
|
|
import contextProperty from "../../sveltelib/context-property";
|
|
import type {
|
|
OnInputCallback,
|
|
OnInsertCallback,
|
|
Trigger,
|
|
} from "../../sveltelib/input-manager";
|
|
import { pageTheme } from "../../sveltelib/theme";
|
|
import type { EditingInputAPI } from "../EditingArea.svelte";
|
|
import type CustomStyles from "./CustomStyles.svelte";
|
|
|
|
export interface RichTextInputAPI extends EditingInputAPI, ContentEditableAPI {
|
|
name: "rich-text";
|
|
shadowRoot: Promise<ShadowRoot>;
|
|
element: Promise<HTMLElement>;
|
|
moveCaretToEnd(): void;
|
|
toggle(): boolean;
|
|
preventResubscription(): () => void;
|
|
getTriggerOnNextInsert(): Trigger<OnInsertCallback>;
|
|
getTriggerOnInput(): Trigger<OnInputCallback>;
|
|
getTriggerAfterInput(): Trigger<OnInputCallback>;
|
|
}
|
|
|
|
export function editingInputIsRichText(
|
|
editingInput: EditingInputAPI | null,
|
|
): editingInput is RichTextInputAPI {
|
|
return editingInput?.name === "rich-text";
|
|
}
|
|
|
|
export interface RichTextInputContextAPI {
|
|
styles: CustomStyles;
|
|
container: HTMLElement;
|
|
api: RichTextInputAPI;
|
|
}
|
|
|
|
const key = Symbol("richText");
|
|
const [context, setContextProperty] = contextProperty<RichTextInputContextAPI>(key);
|
|
|
|
import getInputManager from "../../sveltelib/input-manager";
|
|
import getDOMMirror from "../../sveltelib/mirror-dom";
|
|
|
|
const {
|
|
manager: globalInputManager,
|
|
getTriggerAfterInput,
|
|
getTriggerOnInput,
|
|
getTriggerOnNextInsert,
|
|
} = getInputManager();
|
|
|
|
export { context, getTriggerAfterInput, getTriggerOnInput, getTriggerOnNextInsert };
|
|
</script>
|
|
|
|
<script lang="ts">
|
|
import { getAllContexts, onMount } from "svelte";
|
|
|
|
import { placeCaretAfterContent } from "../../domlib/place-caret";
|
|
import ContentEditable from "../../editable/ContentEditable.svelte";
|
|
import type { DecoratedElement } from "../../editable/decorated";
|
|
import { bridgeCommand } from "../../lib/bridgecommand";
|
|
import {
|
|
fragmentToString,
|
|
nodeContainsInlineContent,
|
|
nodeIsElement,
|
|
} from "../../lib/dom";
|
|
import { on } from "../../lib/events";
|
|
import { promiseWithResolver } from "../../lib/promise";
|
|
import { nodeStore } from "../../sveltelib/node-store";
|
|
import { context as decoratedElementsContext } from "../DecoratedElements.svelte";
|
|
import { context as editingAreaContext } from "../EditingArea.svelte";
|
|
import RichTextStyles from "./RichTextStyles.svelte";
|
|
import SetContext from "./SetContext.svelte";
|
|
|
|
export let hidden: boolean;
|
|
|
|
const { content, editingInputs } = editingAreaContext.get();
|
|
const decoratedElements = decoratedElementsContext.get();
|
|
|
|
function normalizeFragment(fragment: DocumentFragment): void {
|
|
fragment.normalize();
|
|
|
|
for (const decorated of decoratedElements) {
|
|
for (const element of fragment.querySelectorAll(
|
|
decorated.tagName,
|
|
) as NodeListOf<DecoratedElement>) {
|
|
element.undecorate();
|
|
}
|
|
}
|
|
}
|
|
|
|
const nodes = nodeStore<DocumentFragment>(undefined, normalizeFragment);
|
|
|
|
function adjustInputHTML(html: string): string {
|
|
for (const component of decoratedElements) {
|
|
html = component.toUndecorated(html);
|
|
}
|
|
|
|
return html;
|
|
}
|
|
|
|
function adjustInputFragment(fragment: DocumentFragment): void {
|
|
if (nodeContainsInlineContent(fragment)) {
|
|
fragment.appendChild(document.createElement("br"));
|
|
}
|
|
}
|
|
|
|
function writeFromEditingArea(html: string): void {
|
|
/* We need .createContextualFragment so that customElements are initialized */
|
|
const fragment = document
|
|
.createRange()
|
|
.createContextualFragment(adjustInputHTML(html));
|
|
adjustInputFragment(fragment);
|
|
nodes.setUnprocessed(fragment);
|
|
}
|
|
|
|
function adjustOutputFragment(fragment: DocumentFragment): void {
|
|
if (
|
|
fragment.hasChildNodes() &&
|
|
nodeIsElement(fragment.lastChild!) &&
|
|
nodeContainsInlineContent(fragment) &&
|
|
fragment.lastChild!.tagName === "BR"
|
|
) {
|
|
fragment.lastChild!.remove();
|
|
}
|
|
}
|
|
|
|
function adjustOutputHTML(html: string): string {
|
|
for (const component of decoratedElements) {
|
|
html = component.toStored(html);
|
|
}
|
|
|
|
return html;
|
|
}
|
|
|
|
function writeToEditingArea(fragment: DocumentFragment): void {
|
|
const clone = document.importNode(fragment, true);
|
|
adjustOutputFragment(clone);
|
|
|
|
const output = adjustOutputHTML(fragmentToString(clone));
|
|
content.set(output);
|
|
}
|
|
|
|
const [shadowPromise, shadowResolve] = promiseWithResolver<ShadowRoot>();
|
|
|
|
function attachShadow(element: Element): void {
|
|
shadowResolve(element.attachShadow({ mode: "open" }));
|
|
}
|
|
|
|
const [richTextPromise, richTextResolve] = promiseWithResolver<HTMLElement>();
|
|
|
|
function resolve(richTextInput: HTMLElement): { destroy: () => void } {
|
|
function onPaste(event: Event): void {
|
|
event.preventDefault();
|
|
bridgeCommand("paste");
|
|
}
|
|
|
|
function onCutOrCopy(): void {
|
|
bridgeCommand("cutOrCopy");
|
|
}
|
|
|
|
const removePaste = on(richTextInput, "paste", onPaste);
|
|
const removeCopy = on(richTextInput, "copy", onCutOrCopy);
|
|
const removeCut = on(richTextInput, "cut", onCutOrCopy);
|
|
richTextResolve(richTextInput);
|
|
|
|
return {
|
|
destroy() {
|
|
removePaste();
|
|
removeCopy();
|
|
removeCut();
|
|
},
|
|
};
|
|
}
|
|
|
|
const { mirror, preventResubscription } = getDOMMirror();
|
|
const localInputManager = getInputManager();
|
|
|
|
function moveCaretToEnd() {
|
|
richTextPromise.then(placeCaretAfterContent);
|
|
}
|
|
|
|
export const api = {
|
|
name: "rich-text",
|
|
shadowRoot: shadowPromise,
|
|
element: richTextPromise,
|
|
focus() {
|
|
richTextPromise.then((richText) => {
|
|
richText.focus();
|
|
});
|
|
},
|
|
refocus() {
|
|
richTextPromise.then((richText) => {
|
|
richText.blur();
|
|
richText.focus();
|
|
moveCaretToEnd();
|
|
});
|
|
},
|
|
focusable: !hidden,
|
|
toggle(): boolean {
|
|
hidden = !hidden;
|
|
return hidden;
|
|
},
|
|
moveCaretToEnd,
|
|
preventResubscription,
|
|
getTriggerOnNextInsert: localInputManager.getTriggerOnNextInsert,
|
|
getTriggerOnInput: localInputManager.getTriggerOnInput,
|
|
getTriggerAfterInput: localInputManager.getTriggerAfterInput,
|
|
} as RichTextInputAPI;
|
|
|
|
const allContexts = getAllContexts();
|
|
|
|
function attachContentEditable(element: Element, { stylesDidLoad }): void {
|
|
stylesDidLoad.then(
|
|
() =>
|
|
new ContentEditable({
|
|
target: element.shadowRoot!,
|
|
props: {
|
|
nodes,
|
|
resolve,
|
|
mirrors: [mirror],
|
|
managers: [globalInputManager, localInputManager.manager],
|
|
api,
|
|
},
|
|
context: allContexts,
|
|
}),
|
|
);
|
|
}
|
|
|
|
function pushUpdate(): void {
|
|
api.focusable = !hidden;
|
|
$editingInputs = $editingInputs;
|
|
}
|
|
|
|
$: {
|
|
hidden;
|
|
pushUpdate();
|
|
}
|
|
|
|
onMount(() => {
|
|
$editingInputs.push(api);
|
|
$editingInputs = $editingInputs;
|
|
|
|
const unsubscribeFromEditingArea = content.subscribe(writeFromEditingArea);
|
|
const unsubscribeToEditingArea = nodes.subscribe(writeToEditingArea);
|
|
|
|
return () => {
|
|
unsubscribeFromEditingArea();
|
|
unsubscribeToEditingArea();
|
|
};
|
|
});
|
|
</script>
|
|
|
|
<div class="rich-text-input">
|
|
<RichTextStyles
|
|
color={$pageTheme.isDark ? "white" : "black"}
|
|
let:attachToShadow={attachStyles}
|
|
let:promise={stylesPromise}
|
|
let:stylesDidLoad
|
|
>
|
|
<div
|
|
class="rich-text-editable"
|
|
class:hidden
|
|
class:night-mode={$pageTheme.isDark}
|
|
use:attachShadow
|
|
use:attachStyles
|
|
use:attachContentEditable={{ stylesDidLoad }}
|
|
on:focusin
|
|
on:focusout
|
|
/>
|
|
|
|
<div class="rich-text-widgets">
|
|
{#await Promise.all( [richTextPromise, stylesPromise], ) then [container, styles]}
|
|
<SetContext
|
|
setter={setContextProperty}
|
|
value={{ container, styles, api }}
|
|
>
|
|
<slot />
|
|
</SetContext>
|
|
{/await}
|
|
</div>
|
|
</RichTextStyles>
|
|
</div>
|
|
|
|
<style lang="scss">
|
|
.hidden {
|
|
display: none;
|
|
}
|
|
</style>
|