Re-enable formatting for .ts files

There are some style differences compared to prettier, and not all are
necessarily an improvement, but it's much faster now.
This commit is contained in:
Damien Elmes 2022-11-28 09:33:04 +10:00
parent ea5153e7a4
commit b2049209ff
47 changed files with 174 additions and 258 deletions

View file

@ -18,7 +18,6 @@
"**/node_modules",
"out/**",
"**/*-lock.json",
"**/*.{ts}",
"qt/aqt/data/web/js/vendor/*.js",
"ftl/qt-repo",
"ftl/core-repo",

View file

@ -15,14 +15,10 @@ export function mergeTooltipAndShortcut(
return buf;
}
export const withButton =
(f: (button: HTMLButtonElement) => void) =>
({ detail }: CustomEvent): void => {
export const withButton = (f: (button: HTMLButtonElement) => void) => ({ detail }: CustomEvent): void => {
f(detail.button);
};
export const withSpan =
(f: (span: HTMLSpanElement) => void) =>
({ detail }: CustomEvent): void => {
export const withSpan = (f: (span: HTMLSpanElement) => void) => ({ detail }: CustomEvent): void => {
f(detail.span);
};

View file

@ -5,7 +5,6 @@
@typescript-eslint/no-explicit-any: "off",
*/
import { DeckConfig } from "@tslib/proto";
import { get } from "svelte/store";

View file

@ -13,13 +13,6 @@ registerPackage("anki/location", {
saveSelection,
});
export {
findNodeFromCoordinates,
getNodeCoordinates,
getRangeCoordinates,
Position,
restoreSelection,
saveSelection,
};
export { findNodeFromCoordinates, getNodeCoordinates, getRangeCoordinates, Position, restoreSelection, saveSelection };
export type { RangeCoordinates } from "./range";
export type { SelectionLocation } from "./selection";

View file

@ -62,9 +62,9 @@ function buildFromElement<T>(
if (
// blocking
only instanceof BlockNode ||
only instanceof BlockNode
// ascension
(only instanceof FormattingNode && format.tryAscend(only, matchNode))
|| (only instanceof FormattingNode && format.tryAscend(only, matchNode))
) {
return [only];
}

View file

@ -14,9 +14,9 @@ function nodeWithinRange(node: Node, range: Range): boolean {
nodeRange.selectNodeContents(node);
return (
range.compareBoundaryPoints(Range.START_TO_START, nodeRange) !==
Position.After &&
range.compareBoundaryPoints(Range.END_TO_END, nodeRange) !== Position.Before
range.compareBoundaryPoints(Range.START_TO_START, nodeRange)
!== Position.After
&& range.compareBoundaryPoints(Range.END_TO_END, nodeRange) !== Position.Before
);
}

View file

@ -69,8 +69,7 @@ export class FlatRange {
if (range.collapsed) {
// If the range is collapsed to a single element, move the range inside the element.
// This prevents putting the surround above the base element.
const selected =
range.commonAncestorContainer.childNodes[range.startOffset];
const selected = range.commonAncestorContainer.childNodes[range.startOffset];
if (nodeIsElement(selected)) {
range.selectNode(selected);

View file

@ -10,8 +10,8 @@ function length(node: Node): number {
if (node instanceof CharacterData) {
return node.length;
} else if (
node.nodeType === Node.DOCUMENT_TYPE_NODE ||
node.nodeType === Node.ATTRIBUTE_NODE
node.nodeType === Node.DOCUMENT_TYPE_NODE
|| node.nodeType === Node.ATTRIBUTE_NODE
) {
return 0;
}

View file

@ -3,18 +3,8 @@
import type { Matcher } from "../find-above";
import { findFarthest } from "../find-above";
import {
apply,
ApplyFormat,
ReformatApplyFormat,
UnsurroundApplyFormat,
} from "./apply";
import {
build,
BuildFormat,
ReformatBuildFormat,
UnsurroundBuildFormat,
} from "./build";
import { apply, ApplyFormat, ReformatApplyFormat, UnsurroundApplyFormat } from "./apply";
import { build, BuildFormat, ReformatBuildFormat, UnsurroundBuildFormat } from "./build";
import { boolMatcher } from "./match-type";
import { splitPartiallySelected } from "./split-text";
import type { SurroundFormat } from "./surround-format";
@ -53,7 +43,7 @@ function reformatInner<T>(
* Assumes that there are no matching ancestor elements above
* `range.commonAncestorContainer`. Make sure that the range is not placed
* inside the format before using this.
**/
*/
export function surround<T>(
range: Range,
base: Element,

View file

@ -3,9 +3,7 @@
import type { MatchType } from "./match-type";
export const matchTagName =
(tagName: string) =>
<T>(element: Element, match: MatchType<T>): void => {
export const matchTagName = (tagName: string) => <T>(element: Element, match: MatchType<T>): void => {
if (element.matches(tagName)) {
match.remove();
}

View file

@ -24,9 +24,7 @@ interface WithTagName {
tagName: string;
}
export interface DecoratedElementConstructor
extends CustomElementConstructor,
WithTagName {
export interface DecoratedElementConstructor extends CustomElementConstructor, WithTagName {
prototype: DecoratedElement;
/**
* Transforms elements in input HTML from undecorated to stored state.

View file

@ -3,7 +3,6 @@
/// <reference types="../lib/image-import" />
export { default as incrementClozeIcon } from "../icons/contain-plus.svg";
export { default as alertIcon } from "@mdi/svg/svg/alert.svg";
export { default as chevronDown } from "@mdi/svg/svg/chevron-down.svg";
export { default as chevronUp } from "@mdi/svg/svg/chevron-up.svg";
@ -11,3 +10,7 @@ export { default as plainTextIcon } from "@mdi/svg/svg/code-tags.svg";
export { default as clozeIcon } from "@mdi/svg/svg/contain.svg";
export { default as richTextIcon } from "@mdi/svg/svg/format-font.svg";
export { default as stickyIcon } from "@mdi/svg/svg/pin-outline.svg";
// This comment prevents disagreement between eslint-plugin-simple-sort and
// dprint about whether .. or @ should come first.
export { default as incrementClozeIcon } from "../icons/contain-plus.svg";

View file

@ -10,9 +10,11 @@ function normalizeFragment(fragment: DocumentFragment): void {
fragment.normalize();
for (const decorated of decoratedElements) {
for (const element of fragment.querySelectorAll(
for (
const element of fragment.querySelectorAll(
decorated.tagName,
) as NodeListOf<DecoratedElement>) {
) as NodeListOf<DecoratedElement>
) {
element.undecorate();
}
}

View file

@ -1,11 +1,7 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import {
fragmentToString,
nodeContainsInlineContent,
nodeIsElement,
} from "../../lib/dom";
import { fragmentToString, nodeContainsInlineContent, nodeIsElement } from "../../lib/dom";
import { createDummyDoc } from "../../lib/parsing";
import { decoratedElements } from "../decorated-elements";
@ -35,10 +31,10 @@ export function storedToFragment(storedHTML: string): DocumentFragment {
function adjustOutputFragment(fragment: DocumentFragment): void {
if (
fragment.hasChildNodes() &&
nodeIsElement(fragment.lastChild!) &&
nodeContainsInlineContent(fragment) &&
fragment.lastChild!.tagName === "BR"
fragment.hasChildNodes()
&& nodeIsElement(fragment.lastChild!)
&& nodeContainsInlineContent(fragment)
&& fragment.lastChild!.tagName === "BR"
) {
fragment.lastChild!.remove();
}

View file

@ -9,8 +9,7 @@ import * as tr from "@tslib/ftl";
import { localizedNumber } from "@tslib/i18n";
import { Stats } from "@tslib/proto";
import { dayLabel, timeSpan } from "@tslib/time";
import type { Bin ,
ScaleSequential} from "d3";
import type { Bin, ScaleSequential } from "d3";
import {
area,
axisBottom,

View file

@ -26,8 +26,7 @@ function showTooltipInner(msg: string, x: number, y: number): void {
tooltip.$set({ html: msg, x, y, show: true });
}
export const showTooltip: DebouncedFunc<(msg: string, x: number, y: number) => void> =
throttle(showTooltipInner, 16);
export const showTooltip: DebouncedFunc<(msg: string, x: number, y: number) => void> = throttle(showTooltipInner, 16);
export function hideTooltip(): void {
const tooltip = getOrCreateTooltip();

View file

@ -3,11 +3,7 @@
import { isHTMLElement, isNightMode } from "./helpers";
import { removeNode as removeElement } from "./node";
import {
filterStylingInternal,
filterStylingLightMode,
filterStylingNightMode,
} from "./styling";
import { filterStylingInternal, filterStylingLightMode, filterStylingNightMode } from "./styling";
interface TagsAllowed {
[tagName: string]: FilterMethod;
@ -32,9 +28,7 @@ function allowNone(element: Element): void {
filterAttributes(() => false, element);
}
const allow =
(attrs: string[]): FilterMethod =>
(element: Element): void =>
const allow = (attrs: string[]): FilterMethod => (element: Element): void =>
filterAttributes(
(attributeName: string) => attrs.includes(attributeName),
element,
@ -93,9 +87,7 @@ const tagsAllowedExtended: TagsAllowed = {
UL: allowNone,
};
const filterElementTagsAllowed =
(tagsAllowed: TagsAllowed) =>
(element: Element): void => {
const filterElementTagsAllowed = (tagsAllowed: TagsAllowed) => (element: Element): void => {
const tagName = element.tagName;
if (Object.prototype.hasOwnProperty.call(tagsAllowed, tagName)) {

View file

@ -13,35 +13,35 @@ describe("filterHTML", () => {
// font-size is filtered, weight is not
expect(
filterHTML(
'<div style="font-weight: bold; font-size: 10px;"></div>',
"<div style=\"font-weight: bold; font-size: 10px;\"></div>",
true,
true,
),
).toBe('<div style="font-weight: bold;"></div>');
).toBe("<div style=\"font-weight: bold;\"></div>");
});
test("background color", () => {
// transparent is stripped, other colors are not
expect(
filterHTML(
'<span style="background-color: transparent;"></span>',
"<span style=\"background-color: transparent;\"></span>",
false,
true,
),
).toBe('<span style=""></span>');
).toBe("<span style=\"\"></span>");
expect(
filterHTML('<span style="background-color: blue;"></span>', false, true),
).toBe('<span style="background-color: blue;"></span>');
filterHTML("<span style=\"background-color: blue;\"></span>", false, true),
).toBe("<span style=\"background-color: blue;\"></span>");
// except if extended mode is off
expect(
filterHTML('<span style="background-color: blue;">x</span>', false, false),
filterHTML("<span style=\"background-color: blue;\">x</span>", false, false),
).toBe("x");
// no filtering on internal paste
expect(
filterHTML(
'<span style="background-color: transparent;"></span>',
"<span style=\"background-color: transparent;\"></span>",
true,
true,
),
).toBe('<span style="background-color: transparent;"></span>');
).toBe("<span style=\"background-color: transparent;\"></span>");
});
});

View file

@ -1,11 +1,7 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import {
filterElementBasic,
filterElementExtended,
filterElementInternal,
} from "./element";
import { filterElementBasic, filterElementExtended, filterElementInternal } from "./element";
import { filterNode } from "./node";
enum FilterMode {
@ -31,8 +27,7 @@ function trim(value: string): string {
}
const outputHTMLProcessors: Record<FilterMode, (outputHTML: string) => string> = {
[FilterMode.Basic]: (outputHTML: string): string =>
trim(collapseWhitespace(outputHTML)),
[FilterMode.Basic]: (outputHTML: string): string => trim(collapseWhitespace(outputHTML)),
[FilterMode.Extended]: trim,
[FilterMode.Internal]: trim,
};

View file

@ -14,9 +14,7 @@ function iterateElement(
}
}
export const filterNode =
(elementFilter: (element: Element) => void) =>
(node: Node): void => {
export const filterNode = (elementFilter: (element: Element) => void) => (node: Node): void => {
switch (node.nodeType) {
case Node.COMMENT_NODE:
removeNode(node);

View file

@ -99,8 +99,8 @@ export function elementIsEmpty(element: Element): boolean {
export function nodeContainsInlineContent(node: Node): boolean {
for (const child of node.childNodes) {
if (
(nodeIsElement(child) && elementIsBlock(child)) ||
!nodeContainsInlineContent(child)
(nodeIsElement(child) && elementIsBlock(child))
|| !nodeContainsInlineContent(child)
) {
return false;
}
@ -122,8 +122,7 @@ export function fragmentToString(fragment: DocumentFragment): string {
}
const getAnchorParent =
<T extends Element>(predicate: (element: Element) => element is T) =>
(root: Node): T | null => {
<T extends Element>(predicate: (element: Element) => element is T) => (root: Node): T | null => {
const anchor = getSelection(root)?.anchorNode;
if (!anchor) {
@ -143,12 +142,10 @@ const getAnchorParent =
const isListItem = (element: Element): element is HTMLLIElement =>
window.getComputedStyle(element).display === "list-item";
const isParagraph = (element: Element): element is HTMLParamElement =>
element.tagName === "P";
const isParagraph = (element: Element): element is HTMLParamElement => element.tagName === "P";
const isBlockElement = (
element: Element,
): element is HTMLLIElement & HTMLParamElement =>
isListItem(element) || isParagraph(element);
): element is HTMLLIElement & HTMLParamElement => isListItem(element) || isParagraph(element);
export const getListItem = getAnchorParent(isListItem);
export const getParagraph = getAnchorParent(isParagraph);

View file

@ -1,24 +1,15 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
export type EventTargetToMap<A extends EventTarget> = A extends HTMLElement
? HTMLElementEventMap
: A extends Document
? DocumentEventMap
: A extends Window
? WindowEventMap
: A extends FileReader
? FileReaderEventMap
: A extends Element
? ElementEventMap
: A extends Animation
? AnimationEventMap
: A extends EventSource
? EventSourceEventMap
: A extends AbortSignal
? AbortSignalEventMap
: A extends AbstractWorker
? AbstractWorkerEventMap
export type EventTargetToMap<A extends EventTarget> = A extends HTMLElement ? HTMLElementEventMap
: A extends Document ? DocumentEventMap
: A extends Window ? WindowEventMap
: A extends FileReader ? FileReaderEventMap
: A extends Element ? ElementEventMap
: A extends Animation ? AnimationEventMap
: A extends EventSource ? EventSourceEventMap
: A extends AbortSignal ? AbortSignalEventMap
: A extends AbstractWorker ? AbstractWorkerEventMap
: never;
export function on<T extends EventTarget, K extends keyof EventTargetToMap<T>>(
@ -28,8 +19,7 @@ export function on<T extends EventTarget, K extends keyof EventTargetToMap<T>>(
options?: AddEventListenerOptions,
): () => void {
target.addEventListener(eventType, handler as EventListener, options);
return () =>
target.removeEventListener(eventType, handler as EventListener, options);
return () => target.removeEventListener(eventType, handler as EventListener, options);
}
export function preventDefault(event: Event): void {

View file

@ -12,18 +12,18 @@ import type { ModuleName } from "./modules";
export function supportsVerticalText(): boolean {
const firstLang = firstLanguage();
return (
firstLang.startsWith("ja") ||
firstLang.startsWith("zh") ||
firstLang.startsWith("ko")
firstLang.startsWith("ja")
|| firstLang.startsWith("zh")
|| firstLang.startsWith("ko")
);
}
export function direction(): string {
const firstLang = firstLanguage();
if (
firstLang.startsWith("ar") ||
firstLang.startsWith("he") ||
firstLang.startsWith("fa")
firstLang.startsWith("ar")
|| firstLang.startsWith("he")
|| firstLang.startsWith("fa")
) {
return "rtl";
} else {

View file

@ -3,9 +3,9 @@
export function isApplePlatform(): boolean {
// avoid deprecation warning
const platform = window.navigator["platform" + ""]
const platform = window.navigator["platform" + ""];
return (
platform.startsWith("Mac") ||
platform.startsWith("iP")
platform.startsWith("Mac")
|| platform.startsWith("iP")
);
}

View file

@ -3,12 +3,7 @@
import { on } from "./events";
import type { Modifier } from "./keys";
import {
checkIfModifierKey,
checkModifiers,
keyToPlatformString,
modifiersToPlatformString,
} from "./keys";
import { checkIfModifierKey, checkModifiers, keyToPlatformString, modifiersToPlatformString } from "./keys";
import { registerPackage } from "./runtime-require";
const keyCodeLookup = {
@ -65,7 +60,7 @@ export function getPlatformString(keyCombinationString: string): string {
function checkKey(event: KeyboardEvent, key: number): boolean {
// avoid deprecation warning
const which = event["which" + ""]
const which = event["which" + ""];
return which === key;
}
@ -101,8 +96,8 @@ const check =
(keyCode: number, requiredModifiers: Modifier[], optionalModifiers: Modifier[]) =>
(event: KeyboardEvent): boolean => {
return (
checkKey(event, keyCode) &&
checkModifiers(requiredModifiers, optionalModifiers)(event)
checkKey(event, keyCode)
&& checkModifiers(requiredModifiers, optionalModifiers)(event)
);
};
@ -166,8 +161,7 @@ export function registerShortcut(
event = defaultRegisterShortcutRestParams.event,
} = restParams;
const [check, ...restChecks] =
splitKeyCombinationString(keyCombinationString).map(keyCombinationToCheck);
const [check, ...restChecks] = splitKeyCombinationString(keyCombinationString).map(keyCombinationToCheck);
function handler(event: KeyboardEvent): void {
if (check(event)) {

View file

@ -9,9 +9,8 @@ export function randomUUID(): string {
return value.replace(/[018]/g, (character: string): string =>
(
Number(character) ^
(crypto.getRandomValues(new Uint8Array(1))[0] &
(15 >> (Number(character) / 4)))
).toString(16),
);
Number(character)
^ (crypto.getRandomValues(new Uint8Array(1))[0]
& (15 >> (Number(character) / 4)))
).toString(16));
}

View file

@ -45,8 +45,8 @@ export function wrapInternal(
}
if (
wasCollapsed &&
/* ugly solution: treat <anki-mathjax> differently than other wraps */ !front.includes(
wasCollapsed
/* ugly solution: treat <anki-mathjax> differently than other wraps */ && !front.includes(
"<anki-mathjax",
)
) {

View file

@ -19,18 +19,16 @@ export async function maybePreloadExternalCss(html: string): Promise<void> {
}
function clearPreloadedCss(): void {
[...document.head.getElementsByClassName(preloadCssClassName)].forEach((css) =>
css.remove(),
);
[...document.head.getElementsByClassName(preloadCssClassName)].forEach((css) => css.remove());
}
function extractExternalCssElements(fragment: DocumentFragment): CssElementType[] {
return <CssElementType[]> (
[...fragment.querySelectorAll("style, link")].filter(
(css) =>
(css instanceof HTMLStyleElement &&
css.innerHTML.includes("@import")) ||
(css instanceof HTMLLinkElement && css.rel === "stylesheet"),
(css instanceof HTMLStyleElement
&& css.innerHTML.includes("@import"))
|| (css instanceof HTMLLinkElement && css.rel === "stylesheet"),
)
);
}

View file

@ -31,7 +31,7 @@ function useAsyncReactive<T, E>(
const error = derived(
promise,
($promise, set: (error: E | null) => void): (() => void) => {
($promise, set: (error: E | null) => void): () => void => {
$promise?.catch((error: E) => set(error));
return (): void => set(null);
},
@ -40,7 +40,7 @@ function useAsyncReactive<T, E>(
const loading = derived(
promise,
($promise, set: (value: boolean) => void): (() => void) => {
($promise, set: (value: boolean) => void): () => void => {
$promise?.finally(() => set(false));
return (): void => set(true);
},

View file

@ -9,8 +9,7 @@ export interface DynamicSvelteComponent<
[k: string]: unknown;
}
export const dynamicComponent =
<
export const dynamicComponent = <
Comp extends typeof SvelteComponentDev,
DefaultProps = NonNullable<ConstructorParameters<Comp>[0]["props"]>,
>(

View file

@ -1,22 +1,8 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import type {
ComputePositionConfig,
FloatingElement,
Middleware,
Placement,
ReferenceElement,
} from "@floating-ui/dom";
import {
arrow,
computePosition,
flip,
hide,
inline,
offset,
shift,
} from "@floating-ui/dom";
import type { ComputePositionConfig, FloatingElement, Middleware, Placement, ReferenceElement } from "@floating-ui/dom";
import { arrow, computePosition, flip, hide, inline, offset, shift } from "@floating-ui/dom";
import type { PositionAlgorithm } from "./position-algorithm";

View file

@ -1,12 +1,7 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import type {
ComputePositionConfig,
FloatingElement,
Middleware,
ReferenceElement,
} from "@floating-ui/dom";
import type { ComputePositionConfig, FloatingElement, Middleware, ReferenceElement } from "@floating-ui/dom";
import { computePosition, inline, offset } from "@floating-ui/dom";
import type { PositionAlgorithm } from "./position-algorithm";

View file

@ -61,9 +61,11 @@ function preparePreferences<T>(
setter(constructPreferences());
}
for (const [key, value] of Object.entries(
for (
const [key, value] of Object.entries(
toObject(Preferences, { defaults: true }),
)) {
)
) {
preferences[key] = createPreference(value, savePreferences);
}