Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client: improve tab switching speed
Adorian Doran6901fb3399a2
diff --git a/apps/client/src/stylesheets/ckeditor-theme.css b/apps/client/src/stylesheets/ckeditor-theme.cssindex 781fc7acad..8fb1e82931 100644--- a/apps/client/src/stylesheets/ckeditor-theme.css+++ b/apps/client/src/stylesheets/ckeditor-theme.css@@ -98,8 +98,6 @@ body {--ck-color-labeled-field-label-background: var(--accented-background-color);- --ck-color-editable-blur-selection: var(--accented-background-color);-/* todo lists */--ck-color-todo-list-checkmark-border: var(--main-border-color);diff --git a/apps/client/src/stylesheets/css_invalidation.spec.ts b/apps/client/src/stylesheets/css_invalidation.spec.tsindex ebd6b78359..7995a763a1 100644--- a/apps/client/src/stylesheets/css_invalidation.spec.ts+++ b/apps/client/src/stylesheets/css_invalidation.spec.ts@@ -51,6 +51,10 @@ describe("findSlowSelectors", () => {expect(shapes(".row > :nth-child(2) { color: red }")).toEqual([ "keyless-nth" ]);expect(shapes(".card { header { &:not(:first-of-type) { color: red } } }")).toEqual([ "keyless-nth" ]);+ expect(shapes(".ck-editor__editable.ck-blurred ::selection { color: red }"))+ .toEqual([ "focus-then-universal" ]);+ expect(shapes(".ck-editor__editable { &:not(.ck-focused) svg * { color: red } }"))+ .toEqual([ "focus-then-universal" ]);expect(shapes([".list > .ck + .ck",@@ -58,13 +62,16 @@ describe("findSlowSelectors", () => {".row > .item:nth-child(2)",".a > li:first-child",".a + .b",- ".transcript-paragraph + .transcript-paragraph"+ ".transcript-paragraph + .transcript-paragraph",+ ".ck-blurred .ck-widget > .ck-button",+ ".ck-focused svg",+ ".ck-blurred::selection"].map((selector) => `${selector} { color: red }`).join("\n"))).toEqual([]);});});describe("Stylesheets", () => {- it("have no selector that restyles a whole container when an element is inserted", () => {+ it("have no selector that restyles a whole container on an insert or a focus change", () => {const found: string[] = [];for (const dir of SOURCES) {for (const file of cssFiles(join(ROOT, dir))) {diff --git a/apps/client/src/test/css_invalidation.ts b/apps/client/src/test/css_invalidation.tsindex db4e198c0b..3f2d03c4cf 100644--- a/apps/client/src/test/css_invalidation.ts+++ b/apps/client/src/test/css_invalidation.ts@@ -2,11 +2,13 @@ import { type Selector, type SelectorComponent, transform } from "lightningcss";/*** A selector shape that makes Chromium restyle a whole container when an element is inserted- * into it. Chromium keys sibling and position invalidation by class, id and attribute only.+ * into it, or a whole editor when it gains or loses focus. Chromium keys sibling and position+ * invalidation by class, id and attribute only, and descendant invalidation also by tag.*/export type SlowShape =| "sibling-then-universal"| "positional-then-universal"+ | "focus-then-universal"| "keyless-sibling"| "keyless-nth";@@ -51,6 +53,8 @@ const NTH = new Set([]);const POSITIONAL = new Set([ ...NTH, "first-child", "last-child", "only-child" ]);const LOGICAL = new Set([ "is", "where" ]);+/** The classes CKEditor toggles on the editable each time it gains or loses focus. */+const FOCUS_CLASSES = new Set([ "ck-focused", "ck-blurred" ]);interface Compound {combinator: string | null;@@ -74,6 +78,10 @@ export function classifySelector(selector: Selector): SlowShape | null {}}const subject = compounds[compounds.length - 1];+ const ancestors = compounds.slice(0, -1);+ if (isBare(subject) && ancestors.some((compound) => hasClass(compound.parts, FOCUS_CLASSES))) {+ return "focus-then-universal";+ }for (const [ index, compound ] of compounds.entries()) {if (isSibling(compound) && !hasKey(compounds[index - 1].parts) && !hasKey(subject.parts)) {return "keyless-sibling";@@ -117,6 +125,12 @@ function hasPseudo(parts: SelectorComponent[], kinds: Set<string>): boolean {splitCompounds(argument).some((compound) => hasPseudo(compound.parts, kinds)))));}+function hasClass(parts: SelectorComponent[], names: Set<string>): boolean {+ return parts.some((part) => (part.type === "class" && names.has(part.name))+ || argumentsOf(part).some((argument) =>+ splitCompounds(argument).some((compound) => hasClass(compound.parts, names))));+}+/** The selector list of `:not()`, `:is()` or `:where()`, and none for other components. */function argumentsOf(part: SelectorComponent): Selector[] {if (part.type === "pseudo-class" && (part.kind === "not" || part.kind === "is"diff --git a/apps/client/src/types-lib.d.ts b/apps/client/src/types-lib.d.tsindex 8686945761..7386254fe2 100644--- a/apps/client/src/types-lib.d.ts+++ b/apps/client/src/types-lib.d.ts@@ -22,7 +22,10 @@ declare module "draggabilly" {containment: HTMLElement});element: HTMLElement;- on(event: "staticClick" | "dragStart" | "dragEnd" | "dragMove", callback: Callback);+ on(+ event: "pointerDown" | "staticClick" | "dragStart" | "dragEnd" | "dragMove",+ callback: Callback+ );dragEnd();isDragging: boolean;positionDrag: () => void;diff --git a/apps/client/src/widgets/tab_row.spec.ts b/apps/client/src/widgets/tab_row.spec.tsindex 1b4ac109e3..f6ff2f5df1 100644--- a/apps/client/src/widgets/tab_row.spec.ts+++ b/apps/client/src/widgets/tab_row.spec.ts@@ -1,6 +1,8 @@import { afterEach, describe, expect, it, vi } from "vitest";+import appContext from "../components/app_context";import type NoteContext from "../components/note_context";+import type TabManager from "../components/tab_manager";import protectedSessionHolder from "../services/protected_session_holder";import { buildNote } from "../test/easy-froca";import TabRowWidget from "./tab_row";@@ -46,3 +48,46 @@ describe("TabRowWidget.updateTabTitle", () => {expect($unlocked.attr("data-tab-title")).toBe("Secret");});});++describe("TabRowWidget tab activation", () => {+ const originalTabManager = appContext.tabManager;++ afterEach(() => {+ appContext.tabManager = originalTabManager;+ document.body.replaceChildren();+ });++ it("switches on a mouse press and on the release of a touch", () => {+ const activateTabContext = vi.fn();+ const mainContexts: { ntxId: string }[] = [];+ appContext.tabManager = {+ activateTabContext,+ getMainNoteContexts: () => mainContexts+ } as unknown as TabManager;+ const widget = new TabRowWidget();+ document.body.append(widget.render()[0]);+ for (const ntxId of [ "mouse-tab", "touch-tab" ]) {+ mainContexts.push({ ntxId });+ widget.addTab(ntxId);+ }++ /** Presses and releases the tab, returning the activations made before the release. */+ const tap = (ntxId: string, pointerType: string, pointerId: number) => {+ const handle = widget.$widget+ .find(`.note-tab[data-ntx-id="${ntxId}"] .note-tab-drag-handle`)[0];+ expect(handle).toBeInstanceOf(HTMLElement);+ handle.dispatchEvent(new PointerEvent("pointerdown",+ { bubbles: true, pointerType, pointerId }));+ const pressed = [ ...activateTabContext.mock.calls ];+ window.dispatchEvent(new PointerEvent("pointerup", { pointerType, pointerId }));+ return pressed;+ };++ expect(tap("mouse-tab", "mouse", 1)).toEqual([ [ "mouse-tab" ] ]);+ expect(activateTabContext.mock.calls).toEqual([ [ "mouse-tab" ] ]);++ activateTabContext.mockClear();+ expect(tap("touch-tab", "touch", 2)).toEqual([]);+ expect(activateTabContext.mock.calls).toEqual([ [ "touch-tab" ] ]);+ });+});diff --git a/apps/client/src/widgets/tab_row.ts b/apps/client/src/widgets/tab_row.tsindex 0d9276365a..775bb6ab30 100644--- a/apps/client/src/widgets/tab_row.ts+++ b/apps/client/src/widgets/tab_row.ts@@ -823,9 +823,17 @@ export default class TabRowWidget extends BasicWidget {this.draggabillies.push(draggabilly);- draggabilly.on("staticClick", () => {- // restore the tab's last-focused split rather than always jumping to its main split+ // restore the tab's last-focused split rather than always jumping to its main split+ const activate = () =>appContext.tabManager.activateTabContext(tabEl.getAttribute("data-ntx-id"));++ // A mouse switches tabs on press, as browsers do. A touch switches on release, as a+ // long press opens the context menu instead.+ draggabilly.on("pointerDown", (event: PointerEvent) => {+ if (event.pointerType === "mouse") activate();+ });+ draggabilly.on("staticClick", (event: PointerEvent) => {+ if (event.pointerType !== "mouse") activate();});draggabilly.on("dragStart", () => {diff --git a/apps/client/vite-plugins.mts b/apps/client/vite-plugins.mtsindex dceabbc390..8c736456c6 100644--- a/apps/client/vite-plugins.mts+++ b/apps/client/vite-plugins.mts@@ -120,6 +120,8 @@ function replaceOnce(code: string, pattern: RegExp, replacer: (match: string, ..* Rewrites the third-party selectors that make Chromium restyle a whole container each time an* element is inserted into it, which in a large note is the whole note on every Enter: a `*`* after `+`, `~` or a position pseudo-class, and a sibling or `:nth-*` compound without a class.+ * Also a `*` or bare pseudo-element after `.ck-focused` or `.ck-blurred`, which restyles the+ * whole note each time the editor gains or loses focus.* `vite-plugins.spec.ts` checks every rewrite still matches the installed stylesheet.*/export function narrowThirdPartySelectors(): Plugin {@@ -213,7 +215,20 @@ const CKEDITOR_REWRITES: SelectorRewrite[] = [{ from: "& > * + * {", to: "& > .ck + .ck {", count: 2 },{ from: "& + * {", to: "&.ck + .ck {", count: 3 },// The keys of a keystroke, with only text between them.- { from: "& + kbd {", to: "&:not(:first-child) {", count: 1 }+ { from: "& + kbd {", to: "&:not(:first-child) {", count: 1 },+ // A blurred editor shows its selection in the same color as a focused one.+ {+ from: "&.ck-blurred ::selection {\n"+ + " background: var(--ck-color-editable-blur-selection, #d9d9d9);\n }",+ to: "",+ count: 1+ },+ // The icon's `svg *` rule reads its stroke from this variable.+ {+ from: "& svg * {\n stroke: var(--ck-color-widget-blurred-border);\n }",+ to: "--ck-color-widget-type-around-button-icon: var(--ck-color-widget-blurred-border);",+ count: 1+ }];/**diff --git a/apps/client/vite-plugins.spec.ts b/apps/client/vite-plugins.spec.tsindex d951dd9152..c9871cfec9 100644--- a/apps/client/vite-plugins.spec.ts+++ b/apps/client/vite-plugins.spec.ts@@ -325,17 +325,20 @@ describe("checkHostedGroups", () => {/*** Canary for `narrowThirdPartySelectors`. An upgrade of Bootstrap or CKEditor can reword a* selector the plugin rewrites, or add another `* + *`, which brings back a whole-note restyle- * on every Enter.+ * on every Enter or every focus change.*/describe("narrowThirdPartySelectors", () => {- it("rewrites every listed selector, leaving no `*` after a sibling or position", () => {+ it("rewrites every listed selector, leaving no `*` after a sibling, position or focus", () => {+ const universalShapes = [+ "sibling-then-universal", "positional-then-universal", "focus-then-universal"+ ];for (const { specifier } of THIRD_PARTY_STYLESHEETS) {const path = createRequire(import.meta.url).resolve(specifier);const narrowed = narrowSelectorsSource(readFileSync(path, "utf8"), path);expect(narrowed, specifier).not.toBeNull();const universal = findSlowSelectors(narrowed ?? "", path).filter(({ shape }) =>- shape === "sibling-then-universal" || shape === "positional-then-universal");+ universalShapes.includes(shape));expect(universal, specifier).toEqual([]);}});