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: tweak CSS selectors to improve performance
Adorian Dorancfc64344fd34
diff --git a/apps/client/src/stylesheets/css_invalidation.spec.ts b/apps/client/src/stylesheets/css_invalidation.spec.tsnew file mode 100644index 0000000000..ebd6b78359--- /dev/null+++ b/apps/client/src/stylesheets/css_invalidation.spec.ts@@ -0,0 +1,100 @@+import { readdirSync, readFileSync, statSync } from "fs";+import { join, relative } from "path";+import { describe, expect, it } from "vitest";++import { findSlowSelectors } from "../test/css_invalidation";++const ROOT = join(__dirname, "../../../..");+const SOURCES = [ "apps/client/src", "packages/ckeditor5/src" ];++/** The stylesheet of the login and setup pages, which never show a note. */+const SEPARATE_PAGES = new Set([ "apps/client/src/setup.css" ]);++/**+ * `<p>`, `<div>` and `<td>` already depend on their position through CKEditor's content+ * stylesheet (`li > p:first-of-type`, `.ck-fake-panel div:nth-child(2)`,+ * `:is(td, th):last-of-type`), so these add nothing; `<h5>` and `<header>` add only themselves.+ */+const ACCEPTED: Record<string, string[]> = {+ "apps/client/src/stylesheets/style.css": [ ".tooltip-inner p:last-of-type" ],+ "apps/client/src/stylesheets/theme-next/notes/text.css": [+ ".ck-content blockquote p:last-of-type"+ ],+ "apps/client/src/stylesheets/theme-next/pages.css": [+ ".options-section-card h5:first-of-type",+ ".options-section-card p:last-of-type:not(:first-of-type)"+ ],+ "apps/client/src/stylesheets/theme-next/shell.css": [+ "div.promoted-attribute-cell.promoted-attribute-label-boolean > div:first-of-type"+ ],+ "apps/client/src/widgets/mobile_widgets/TabSwitcher.css": [+ ".modal.tab-bar-modal .tabs .tab-card header:not(:first-of-type)"+ ],+ "apps/client/src/widgets/type_widgets/SqlConsole.css": [+ ".sql-console-widget-container .sql-table-schemas-widget .dropdown .table-schema"+ + " td:nth-child(0n+2)"+ ]+};++describe("findSlowSelectors", () => {+ it("finds each shape, nested or not, and passes the keyed forms", () => {+ // LightningCSS drops a rule without declarations, so each fixture has one.+ const shapes = (css: string) =>+ findSlowSelectors(css, "test.css").map(({ shape }) => shape);++ expect(shapes(".list > * + * { color: red }")).toEqual([ "sibling-then-universal" ]);+ expect(shapes(".list { & > * { & + * { color: red } } }"))+ .toEqual([ "sibling-then-universal" ]);+ expect(shapes(".table tr:nth-of-type(odd) > * { color: red }"))+ .toEqual([ "positional-then-universal" ]);+ expect(shapes(".alert p + p { color: red }")).toEqual([ "keyless-sibling" ]);+ 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([+ ".list > .ck + .ck",+ ".alert p:not(:first-child)",+ ".row > .item:nth-child(2)",+ ".a > li:first-child",+ ".a + .b",+ ".transcript-paragraph + .transcript-paragraph"+ ].map((selector) => `${selector} { color: red }`).join("\n"))).toEqual([]);+ });+});++describe("Stylesheets", () => {+ it("have no selector that restyles a whole container when an element is inserted", () => {+ const found: string[] = [];+ for (const dir of SOURCES) {+ for (const file of cssFiles(join(ROOT, dir))) {+ const path = relative(ROOT, file).replace(/\\/g, "/");+ if (SEPARATE_PAGES.has(path)) {+ continue;+ }+ const code = readFileSync(file, "utf8");+ for (const { shape, selector } of findSlowSelectors(code, file)) {+ if (!ACCEPTED[path]?.includes(selector)) {+ found.push(`${path} :: ${selector} (${shape})`);+ }+ }+ }+ }++ expect(found).toEqual([]);+ });+});++function* cssFiles(dir: string): Generator<string> {+ for (const name of readdirSync(dir)) {+ const path = join(dir, name);+ if (name === "node_modules" || name === "test-output" || name === "dist") {+ continue;+ }+ if (statSync(path).isDirectory()) {+ yield* cssFiles(path);+ } else if (name.endsWith(".css")) {+ yield path;+ }+ }+}diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex d73bf9de88..10314b3c0c 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -2459,7 +2459,20 @@ footer.webview-footer button {100% { opacity: 0.3; }}+/* Reset on every item, so the nested items of a checked item are not struck through. */+.ck-content ul.todo-list li {+ --todo-description-decoration: none;+ --todo-description-opacity: 1;+}++.ck-content ul.todo-list li:has(> span.todo-list__label input[type="checkbox"]:checked) {+ --todo-description-decoration: line-through;+ --todo-description-opacity: 0.6;+}+.ck-content ul.todo-list li span.todo-list__label__description {+ text-decoration: var(--todo-description-decoration);+ opacity: var(--todo-description-opacity);transition: opacity 200ms ease;}@@ -2480,11 +2493,6 @@ footer.webview-footer button {min-width: 1px;}-.ck-content ul.todo-list li:has(> span.todo-list__label input[type="checkbox"]:checked) > span.todo-list__label span.todo-list__label__description {- text-decoration: line-through;- opacity: 0.6;-}-.chat-options-container {display: flex;margin: 5px 0;diff --git a/apps/client/src/stylesheets/table.css b/apps/client/src/stylesheets/table.cssindex 16c67830c1..c654bfbaaf 100644--- a/apps/client/src/stylesheets/table.css+++ b/apps/client/src/stylesheets/table.css@@ -256,7 +256,8 @@/* Align items without children/expander to the ones with. */.tabulator-cell[tabulator-field="title"] > span:first-child, /* 1st level */-.tabulator-cell[tabulator-field="title"] > div:first-child + span { /* sub-level */+.tabulator-cell[tabulator-field="title"]+ > .tabulator-data-tree-branch-empty:first-child + span { /* sub-level */padding-inline-start: 21px;}diff --git a/apps/client/src/stylesheets/theme-next/base.css b/apps/client/src/stylesheets/theme-next/base.cssindex 76a75c9530..6d64956c52 100644--- a/apps/client/src/stylesheets/theme-next/base.css+++ b/apps/client/src/stylesheets/theme-next/base.css@@ -370,6 +370,6 @@ div.alert {font-size: .85em;}-div.alert p + p {+div.alert p:not(:first-child) {margin-block: 1em 0;}diff --git a/apps/client/src/stylesheets/theme-next/dialogs.css b/apps/client/src/stylesheets/theme-next/dialogs.cssindex 0171815570..23b451c738 100644--- a/apps/client/src/stylesheets/theme-next/dialogs.css+++ b/apps/client/src/stylesheets/theme-next/dialogs.css@@ -297,7 +297,7 @@ body.desktop .jump-to-note-dialog .input-group {}/* Item title & path container */-.recent-changes-content ul li > span:nth-child(2) {+.recent-changes-content ul li > span:not(:first-child) {display: inline-block;}@@ -317,7 +317,7 @@ body.desktop .jump-to-note-dialog .input-group {}/* Item path */-.recent-changes-content ul li > span:nth-child(2) small {+.recent-changes-content ul li > span:not(:first-child) small {display: block;line-height: 1;opacity: 0.75;@@ -346,7 +346,7 @@ body.desktop .jump-to-note-dialog .input-group {}/* The first item of the timeline */-.recent-changes-content > div:first-child > *:first-child {+.recent-changes-content > div:first-child > b:first-child {--connector-top: 50%;--connector-radius: calc(var(--timeline-connector-size) / 2);}@@ -425,7 +425,7 @@ body.desktop .jump-to-note-dialog .input-group {padding: 0;}-.help-dialog .help-cards li + li {+.help-dialog .help-cards li:not(:first-child) {margin-top: 0.4em;}diff --git a/apps/client/src/stylesheets/theme-next/notes/canvas.css b/apps/client/src/stylesheets/theme-next/notes/canvas.cssindex ffd05ed484..56143ee820 100644--- a/apps/client/src/stylesheets/theme-next/notes/canvas.css+++ b/apps/client/src/stylesheets/theme-next/notes/canvas.css@@ -149,7 +149,7 @@}/* The parent element of the "Library" button */-.excalidraw .App-menu.App-menu_top > div:nth-child(3) {+.excalidraw .App-menu.App-menu_top > .layer-ui__wrapper__top-right:nth-child(3) {flex-direction: row-reverse;}diff --git a/apps/client/src/stylesheets/theme-next/notes/text.css b/apps/client/src/stylesheets/theme-next/notes/text.cssindex 3fe60e674e..9fb78a6d5d 100644--- a/apps/client/src/stylesheets/theme-next/notes/text.css+++ b/apps/client/src/stylesheets/theme-next/notes/text.css@@ -606,7 +606,7 @@ div.ck-template-form .ck-search__info > span {color: var(--muted-text-color);}-div.ck-template-form .ck-search__info span:nth-child(2) {+div.ck-template-form .ck-search__info span:last-child {display: block;opacity: .5;margin-top: 8px;diff --git a/apps/client/src/stylesheets/theme-next/shell.css b/apps/client/src/stylesheets/theme-next/shell.cssindex fbbf189fa7..4322a9dc2e 100644--- a/apps/client/src/stylesheets/theme-next/shell.css+++ b/apps/client/src/stylesheets/theme-next/shell.css@@ -1219,7 +1219,7 @@ body.mobile .note-title {margin-inline-end: 0;}-.title-row > *:nth-child(2) {+.title-row > .component:nth-child(2) {margin-inline-start: 0;}@@ -1424,7 +1424,7 @@ div.promoted-attribute-cell.promoted-attribute-label-color .input-group {padding: 8px;}-.find-replace-widget > div + div {+.find-replace-widget > .replace-widget-box {padding-top: 0;}diff --git a/apps/client/src/test/css_invalidation.ts b/apps/client/src/test/css_invalidation.tsnew file mode 100644index 0000000000..db4e198c0b--- /dev/null+++ b/apps/client/src/test/css_invalidation.ts@@ -0,0 +1,155 @@+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.+ */+export type SlowShape =+ | "sibling-then-universal"+ | "positional-then-universal"+ | "keyless-sibling"+ | "keyless-nth";++export interface SlowSelector {+ shape: SlowShape;+ selector: string;+}++/** Lists the selectors of the stylesheet `code` that have a {@link SlowShape}. */+export function findSlowSelectors(code: string, filename: string): SlowSelector[] {+ // Lowering for an engine without nesting turns each `&` into the full selector.+ const flat = transform({+ filename,+ code: new TextEncoder().encode(code),+ targets: { chrome: 100 << 16 },+ errorRecovery: true+ }).code;+ const found: SlowSelector[] = [];+ transform({+ filename,+ code: flat,+ errorRecovery: true,+ visitor: {+ Rule: {+ style(rule) {+ for (const selector of rule.value.selectors) {+ const shape = classifySelector(selector);+ if (shape) {+ found.push({ shape, selector: serializeSelector(selector) });+ }+ }+ }+ }+ }+ });+ return found;+}++const NTH = new Set([+ "nth-child", "nth-last-child", "nth-of-type", "nth-last-of-type",+ "first-of-type", "last-of-type", "only-of-type"+]);+const POSITIONAL = new Set([ ...NTH, "first-child", "last-child", "only-child" ]);+const LOGICAL = new Set([ "is", "where" ]);++interface Compound {+ combinator: string | null;+ parts: SelectorComponent[];+}++/** The {@link SlowShape} of `selector`, or `null`. */+export function classifySelector(selector: Selector): SlowShape | null {+ const compounds = splitCompounds(selector);+ const isSibling = (compound: Compound) =>+ compound.combinator === "next-sibling" || compound.combinator === "later-sibling";++ for (const [ index, compound ] of compounds.entries()) {+ if (isSibling(compound) && compounds.slice(index).some(isBare)) {+ return "sibling-then-universal";+ }+ }+ for (const [ index, compound ] of compounds.entries()) {+ if (hasPseudo(compound.parts, POSITIONAL) && compounds.slice(index + 1).some(isBare)) {+ return "positional-then-universal";+ }+ }+ const subject = compounds[compounds.length - 1];+ for (const [ index, compound ] of compounds.entries()) {+ if (isSibling(compound) && !hasKey(compounds[index - 1].parts) && !hasKey(subject.parts)) {+ return "keyless-sibling";+ }+ }+ if (compounds.some((compound) => hasPseudo(compound.parts, NTH) && !hasKey(compound.parts))) {+ return "keyless-nth";+ }+ return null;+}++function splitCompounds(selector: Selector): Compound[] {+ const compounds: Compound[] = [ { combinator: null, parts: [] } ];+ for (const component of selector) {+ if (component.type === "combinator") {+ compounds.push({ combinator: component.value, parts: [] });+ } else {+ compounds[compounds.length - 1].parts.push(component);+ }+ }+ return compounds;+}++/** Whether the compound names a class, id or attribute, the features Chromium keys on. */+function hasKey(parts: SelectorComponent[]): boolean {+ return parts.some((part) => part.type === "class" || part.type === "id"+ || part.type === "attribute"+ || (part.type === "pseudo-class" && LOGICAL.has(part.kind)+ && argumentsOf(part).every((argument) =>+ hasKey(splitCompounds(argument).at(-1)?.parts ?? []))));+}++/** Whether the compound matches any element: no class, id, attribute or tag. */+function isBare(compound: Compound): boolean {+ return !hasKey(compound.parts) && !compound.parts.some((part) => part.type === "type");+}++function hasPseudo(parts: SelectorComponent[], kinds: Set<string>): boolean {+ return parts.some((part) => part.type === "pseudo-class" && (kinds.has(part.kind)+ || argumentsOf(part).some((argument) =>+ splitCompounds(argument).some((compound) => hasPseudo(compound.parts, kinds)))));+}++/** 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"+ || part.kind === "where")) {+ return part.selectors;+ }+ return [];+}++const COMBINATORS: Record<string, string> = {+ child: " > ", descendant: " ", "next-sibling": " + ", "later-sibling": " ~ "+};++/** A readable form of `selector` for test messages. */+function serializeSelector(selector: Selector): string {+ return selector.map((part) => {+ switch (part.type) {+ case "combinator": return COMBINATORS[part.value] ?? ` ${part.value} `;+ case "class": return `.${part.name}`;+ case "id": return `#${part.name}`;+ case "type": return part.name;+ case "universal": return "*";+ case "attribute": return `[${part.name}]`;+ case "pseudo-element": return `::${part.kind}`;+ case "pseudo-class": {+ const selectors = argumentsOf(part);+ if (selectors.length) {+ return `:${part.kind}(${selectors.map(serializeSelector).join(", ")})`;+ }+ if ("a" in part) return `:${part.kind}(${part.a}n+${part.b})`;+ return `:${part.kind}`;+ }+ default: return `<${part.type}>`;+ }+ }).join("");+}diff --git a/apps/client/src/widgets/collections/geomap/GeoMapProperties.css b/apps/client/src/widgets/collections/geomap/GeoMapProperties.cssindex 66bda8f44c..ceccf901ce 100644--- a/apps/client/src/widgets/collections/geomap/GeoMapProperties.css+++ b/apps/client/src/widgets/collections/geomap/GeoMapProperties.css@@ -2,7 +2,7 @@.geo-map-corner input {width: 8em;- & + input {+ &.form-control + input {margin-inline-start: 0.5em;}}diff --git a/apps/client/src/widgets/dialogs/import/import_dialog.css b/apps/client/src/widgets/dialogs/import/import_dialog.cssindex 1253c33ff6..857fa68723 100644--- a/apps/client/src/widgets/dialogs/import/import_dialog.css+++ b/apps/client/src/widgets/dialogs/import/import_dialog.css@@ -37,7 +37,7 @@margin: 0;}- .option-row-description p + p {+ .option-row-description p:not(:first-child) {margin-top: 0.4em;}diff --git a/apps/client/src/widgets/layout/Breadcrumb.css b/apps/client/src/widgets/layout/Breadcrumb.cssindex 71d142cffe..656d1f63d6 100644--- a/apps/client/src/widgets/layout/Breadcrumb.css+++ b/apps/client/src/widgets/layout/Breadcrumb.css@@ -67,11 +67,6 @@}}- > span:last-of-type a {- max-width: 300px;- flex-shrink: 1;- }-ul {flex-direction: column;list-style-type: none;diff --git a/apps/client/src/widgets/layout/NoteActions.css b/apps/client/src/widgets/layout/NoteActions.cssindex 0da685e2fe..940f557286 100644--- a/apps/client/src/widgets/layout/NoteActions.css+++ b/apps/client/src/widgets/layout/NoteActions.css@@ -21,7 +21,7 @@height: 36px;gap: var(--button-gap);- &> button:last-of-type {+ &> button.icon-action:last-of-type {margin-inline-end: 0.5em;}}diff --git a/apps/client/src/widgets/sidebar/TableOfContents.css b/apps/client/src/widgets/sidebar/TableOfContents.cssindex 05637f1577..2518c469a5 100644--- a/apps/client/src/widgets/sidebar/TableOfContents.css+++ b/apps/client/src/widgets/sidebar/TableOfContents.css@@ -9,7 +9,7 @@display:none;}-.toc li + ol:before {+.toc ol > ol:before {content: "";position: absolute;height: 100%;diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.cssindex f7e272e16b..786a29d635 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css@@ -139,7 +139,7 @@ body.background-effects.theme-supports-background-effects .llm-chat-message-userpadding: 0.25rem 0.75rem;}-.llm-chat-citations-list tr + tr td {+.llm-chat-citations-list tr:not(:first-child) td {border-top: 1px solid var(--main-border-color);}@@ -416,7 +416,7 @@ body.background-effects.theme-supports-background-effects .llm-chat-message-userown: a dot that belongs to the item it precedes can never be orphaned onto a line byitself, and it always shares that item's baseline. `gap` spaces the dot from the itembefore it, the margin from the item it introduces. */-.llm-chat-footer > * + *::before {+.llm-chat-footer > :not(:first-child)::before {content: "·";margin-inline-end: 0.375rem;opacity: 0.5;diff --git a/apps/client/src/widgets/type_widgets/options/components/CheckboxList.css b/apps/client/src/widgets/type_widgets/options/components/CheckboxList.cssindex 621606cccf..06779de165 100644--- a/apps/client/src/widgets/type_widgets/options/components/CheckboxList.css+++ b/apps/client/src/widgets/type_widgets/options/components/CheckboxList.css@@ -6,7 +6,7 @@column-width: var(--checkbox-list-column-width, 400px);list-style-type: none;- > li + li {+ > li:not(:first-child) {margin-block-start: 6px;}}diff --git a/apps/client/src/widgets/type_widgets/options/database.css b/apps/client/src/widgets/type_widgets/options/database.cssindex ad47bf81c6..7ec6de518d 100644--- a/apps/client/src/widgets/type_widgets/options/database.css+++ b/apps/client/src/widgets/type_widgets/options/database.css@@ -11,7 +11,7 @@.admonition.start-over-pending {margin-bottom: 16px;- p:last-of-type {+ p:last-child {margin-bottom: 12px;}}diff --git a/apps/client/src/widgets/type_widgets/transcript/TranscriptView.css b/apps/client/src/widgets/type_widgets/transcript/TranscriptView.cssindex e170fdfb36..b08d2f29cf 100644--- a/apps/client/src/widgets/type_widgets/transcript/TranscriptView.css+++ b/apps/client/src/widgets/type_widgets/transcript/TranscriptView.css@@ -102,7 +102,7 @@white-space: pre-wrap;}- p + p {+ .transcript-paragraph + .transcript-paragraph {margin-top: 0.5rem;}diff --git a/apps/client/src/widgets/type_widgets/transcript/TranscriptView.tsx b/apps/client/src/widgets/type_widgets/transcript/TranscriptView.tsxindex 637ee9754e..beeece9beb 100644--- a/apps/client/src/widgets/type_widgets/transcript/TranscriptView.tsx+++ b/apps/client/src/widgets/type_widgets/transcript/TranscriptView.tsx@@ -161,7 +161,7 @@ export default function TranscriptView({ attachment }: { attachment: FAttachment<TurnTime startedAt={transcript.startedAt} offsetMs={turn.offsetMs} /></div>{turn.paragraphs.map((paragraph, index) => (- <p key={index}>+ <p key={index} className="transcript-paragraph">{paragraph.map((utterance, position) => {const text = shownTexts.get(utterance) ?? utterance.text;return (diff --git a/apps/client/vite-plugins.mts b/apps/client/vite-plugins.mtsindex 8cb0626159..0f5450adf1 100644--- a/apps/client/vite-plugins.mts+++ b/apps/client/vite-plugins.mts@@ -116,6 +116,128 @@ function replaceOnce(code: string, pattern: RegExp, replacer: (match: string, ..return code.replace(pattern, replacer);}+/**+ * 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.+ * `vite-plugins.spec.ts` checks every rewrite still matches the installed stylesheet.+ */+export function narrowThirdPartySelectors(): Plugin {+ return {+ name: "narrow-third-party-selectors",+ enforce: "pre",+ transform: (code, id) => narrowSelectorsSource(code, id)+ };+}++/**+ * Returns `code` with the rewrites of the stylesheet `id` applied, and `null` for other+ * modules.+ */+export function narrowSelectorsSource(code: string, id: string): string | null {+ const path = id.replace(/\\/g, "/").replace(/\?.*$/, "");+ const stylesheet = THIRD_PARTY_STYLESHEETS.find(({ file }) =>+ path.endsWith(`/node_modules/${file}`));+ if (!stylesheet) {+ return null;+ }++ let narrowed = code;+ for (const { from, to, count } of stylesheet.rewrites) {+ const found = narrowed.split(from).length - 1;+ if (found !== count) {+ throw new Error(`narrow-third-party-selectors: expected ${count} × "${from}" in `+ + `${stylesheet.file}, found ${found}; update vite-plugins.mts.`);+ }+ narrowed = narrowed.replaceAll(from, to);+ }+ return narrowed;+}++interface SelectorRewrite {+ from: string;+ to: string;+ /** How often `from` occurs in the installed stylesheet. */+ count: number;+}++/**+ * Bootstrap's minified selectors, the same in its LTR and RTL builds. Trilium uses no `<legend>`,+ * `.table-striped-columns` or `.has-validation`; floating labels need `.form-control` or+ * `.form-select` on the field.+ */+const BOOTSTRAP_REWRITES: SelectorRewrite[] = [+ // The cells only read the stripe's custom properties, so the row can set them.+ {+ from: ".table-striped>tbody>tr:nth-of-type(odd)>*",+ to: ".table-striped>tbody>tr:nth-of-type(odd)",+ count: 1+ },+ {+ from: ".table-striped-columns>:not(caption)>tr>:nth-child(2n)",+ to: ".table-striped-columns>:not(caption)>tr>td:nth-child(2n),"+ + ".table-striped-columns>:not(caption)>tr>th:nth-child(2n)",+ count: 1+ },+ {+ from: ".form-floating>textarea:focus~",+ to: ".form-floating>textarea.form-control:focus~",+ count: 1+ },+ {+ from: ".form-floating>textarea:not(:placeholder-shown)~",+ to: ".form-floating>textarea.form-control:not(:placeholder-shown)~",+ count: 1+ },+ {+ from: ".form-floating>textarea:disabled~",+ to: ".form-floating>textarea.form-control:disabled~",+ count: 1+ },+ {+ from: ".form-floating>:disabled~label",+ to: ".form-floating>.form-select:disabled~label",+ count: 1+ },+ {+ from: ",.input-group.has-validation>:nth-last-child(n+3)"+ + ":not(.dropdown-toggle):not(.dropdown-menu):not(.form-floating)",+ to: "",+ count: 1+ }+];++/** CKEditor's nested selectors. Its UI views all carry the `ck` class. */+const CKEDITOR_REWRITES: SelectorRewrite[] = [+ { from: "&:not(.ck-hidden) ~ * {", to: "&:not(.ck-hidden) ~ .ck {", count: 1 },+ { 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 }+];++/**+ * The stylesheets rewritten: `specifier` resolves to the file, `file` is its path in+ * `node_modules`.+ */+export const THIRD_PARTY_STYLESHEETS = [+ {+ specifier: "bootstrap/dist/css/bootstrap.min.css",+ file: "bootstrap/dist/css/bootstrap.min.css",+ rewrites: [ { from: "legend+*{clear:left}", to: "", count: 1 }, ...BOOTSTRAP_REWRITES ]+ },+ {+ specifier: "bootstrap/dist/css/bootstrap.rtl.min.css",+ file: "bootstrap/dist/css/bootstrap.rtl.min.css",+ rewrites: [ { from: "legend+*{clear:right}", to: "", count: 1 }, ...BOOTSTRAP_REWRITES ]+ },+ {+ specifier: "ckeditor5/ckeditor5.css",+ file: "ckeditor5/dist/ckeditor5.css",+ rewrites: CKEDITOR_REWRITES+ }+];+/** The share theme's sources, which the app build bundles into the files shared pages load. */const SHARE_THEME_SRC = join(import.meta.dirname, "../../packages/share-theme/src");diff --git a/apps/client/vite-plugins.spec.ts b/apps/client/vite-plugins.spec.tsindex 493d9dace0..81855fde8c 100644--- a/apps/client/vite-plugins.spec.ts+++ b/apps/client/vite-plugins.spec.ts@@ -5,14 +5,17 @@ import { tmpdir } from "os";import { dirname, join } from "path";import { describe, expect, it } from "vitest";+import { findSlowSelectors } from "./src/test/css_invalidation";import {buildShareThemeManifest,checkHostedGroups,ENGINE_RENDER_ENTRY,LANGUAGE_DETECTOR_PACKAGE,+ narrowSelectorsSource,readLoaderTable,resolveUniverHyphenationStub,stripUniverEmojiSource,+ THIRD_PARTY_STYLESHEETS,UI_ENTRY} from "./vite-plugins.mjs";@@ -319,6 +322,33 @@ 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.+ */+describe("narrowThirdPartySelectors", () => {+ it("rewrites every listed selector, leaving no `*` after a sibling or position", () => {+ 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");+ expect(universal, specifier).toEqual([]);+ }+ });++ it("leaves other modules alone and fails once a selector no longer matches", () => {+ const other = "/app/node_modules/other/dist/a.css";+ const ckeditor = "/app/node_modules/ckeditor5/dist/ckeditor5.css?direct";+ expect(narrowSelectorsSource("a + * { color: red }", other)).toBeNull();+ expect(() => narrowSelectorsSource("", ckeditor))+ .toThrow("narrow-third-party-selectors: expected 1");+ });+});+/** Reads the generated `PATTERN_LOADERS` map, whose keys are the locales Univer hyphenates. */function patternLoaders(): { locale: string; source: string }[] {const entries = entrySource.matchAll(/\["([a-z0-9-]+)"\]\s*:\s*\(\)\s*=>\s*import\("(\.[^"]*)"\)/g);diff --git a/apps/client/vite.config.mts b/apps/client/vite.config.mtsindex 068a53a242..6a0c5ddf1f 100644--- a/apps/client/vite.config.mts+++ b/apps/client/vite.config.mts@@ -5,7 +5,9 @@ import { join } from 'path';import { defineConfig } from 'vite';import { viteStaticCopy } from 'vite-plugin-static-copy'-import { shareTheme, stripUniverEmojiData, stripUniverHyphenation } from './vite-plugins.mjs';+import {+ narrowThirdPartySelectors, shareTheme, stripUniverEmojiData, stripUniverHyphenation+} from './vite-plugins.mjs';const assets = [ "assets", "stylesheets", "fonts", "translations" ];@@ -20,12 +22,14 @@ if (isDev) {...(process.env.TRILIUM_NO_HMR ? [] : [ prefresh() ]),stripUniverHyphenation(),stripUniverEmojiData(),+ narrowThirdPartySelectors(),...shareTheme()];} else {plugins = [stripUniverHyphenation(),stripUniverEmojiData(),+ narrowThirdPartySelectors(),...shareTheme(),viteStaticCopy({targets: assets.map((asset) => ({diff --git a/apps/standalone/vite.config.mts b/apps/standalone/vite.config.mtsindex 18fbf8977f..1ff240e653 100644--- a/apps/standalone/vite.config.mts+++ b/apps/standalone/vite.config.mts@@ -6,7 +6,9 @@ import prefresh from "@prefresh/vite";import { defaultClientConditions, defineConfig, type Plugin } from "vite";import { viteStaticCopy } from "vite-plugin-static-copy";-import { shareTheme, stripUniverEmojiData, stripUniverHyphenation } from "../client/vite-plugins.mjs";+import {+ narrowThirdPartySelectors, shareTheme, stripUniverEmojiData, stripUniverHyphenation+} from "../client/vite-plugins.mjs";const clientAssets = ["assets", "stylesheets", "fonts", "translations"];@@ -194,6 +196,7 @@ function copyHelpAssetsPlugin(): Plugin {let plugins: any = [stripUniverHyphenation(),stripUniverEmojiData(),+ narrowThirdPartySelectors(),sqliteWasmDedupePlugin(),sqliteWasmPlugin,viteStaticCopy({diff --git a/packages/ckeditor5/src/theme/multicolumn.css b/packages/ckeditor5/src/theme/multicolumn.cssindex 069110e462..4a91fd76ae 100644--- a/packages/ckeditor5/src/theme/multicolumn.css+++ b/packages/ckeditor5/src/theme/multicolumn.css@@ -69,7 +69,7 @@}.ck-content .trilium-multicolumn-layout.ck-widget- > :nth-child(even of .trilium-multicolumn-column) {+ > .trilium-multicolumn-column:nth-child(even of .trilium-multicolumn-column) {background: var(--multicolumn-layout-stacked-background);}}