Skip to content

Build your personal knowledge base with Trilium Notes

client: reduce the usage of selectors using the :has pseudo-class, refactor

Adorian Doran06f73ee6997b
diff --git a/apps/client/src/layouts/mobile_layout.css b/apps/client/src/layouts/mobile_layout.css
index d844f8019f..9991e5b9d5 100644
--- a/apps/client/src/layouts/mobile_layout.css
+++ b/apps/client/src/layouts/mobile_layout.css
@@ -3,11 +3,7 @@
}
@media (max-width: 991px) {
- body.mobile:not(.ios):has(
- #context-menu-cover.show,
- > .tn-dropdown-portal > .tn-dropdown-backdrop,
- .tn-popover-backdrop
- ) #background-color-tracker {
+ body.mobile:not(.ios):is(.context-menu-shown, .backdrop-open) #background-color-tracker {
/* `--mobile-backdrop-color` (style.css) laid over the page background. */
color: color-mix(in srgb, var(--main-background-color), black 50%) !important;
}
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index 10314b3c0c..112de0ce8f 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -1916,7 +1916,7 @@ pre.code-embed-editor.read-only .cm-activeLine {
}
}
- body:has(#mobile-sidebar-wrapper.show) #detail-container::before {
+ body.mobile-sidebar-open #detail-container::before {
opacity: 0;
}
@@ -2612,7 +2612,7 @@ iframe.print-iframe {
/* Scrolling container */
-.note-split > .scrolling-container:has(> :is(.note-detail.full-height, .note-list-widget.full-height)) {
+.note-split > .scrolling-container:is(.detail-full-height, .list-full-height) {
display: flex;
flex-direction: column;
}
@@ -2634,7 +2634,7 @@ iframe.print-iframe {
/* A full-height note fills the container instead of scrolling it, so the padding that lets
flowing content scroll past its end would only take height away from the note. */
-.scrolling-container:has(> .note-detail.full-height) > .scroll-padding-widget {
+.scrolling-container.detail-full-height > .scroll-padding-widget {
display: none;
}
diff --git a/apps/client/src/stylesheets/theme-next/ios.css b/apps/client/src/stylesheets/theme-next/ios.css
index c740791d90..1996cfae18 100644
--- a/apps/client/src/stylesheets/theme-next/ios.css
+++ b/apps/client/src/stylesheets/theme-next/ios.css
@@ -177,7 +177,7 @@ body.mobile.ios {
/* Safari tints its bars from the page's background and from `theme-color`, which
`#initThemeColor()` in root_container.ts copies from `#background-color-tracker`. */
- &:has(#mobile-sidebar-wrapper.show) {
+ &.mobile-sidebar-open {
background-color: var(--grouped-background-color);
#root-widget {
diff --git a/apps/client/src/stylesheets/theme-next/shell.css b/apps/client/src/stylesheets/theme-next/shell.css
index 4322a9dc2e..ec4bfd147a 100644
--- a/apps/client/src/stylesheets/theme-next/shell.css
+++ b/apps/client/src/stylesheets/theme-next/shell.css
@@ -122,8 +122,7 @@ body.background-effects.theme-supports-background-effects #center-pane .note-spl
--note-split-bottom-border-radius: var(--center-pane-border-radius);
}
-/* Matches when a status bar panel is open */
-#horizontal-main-container:has(#rest-pane > .status-bar.status-bar-panel-open) {
+body.status-bar-panel-open #horizontal-main-container {
--note-split-bottom-border-radius: 0;
}
@@ -1185,8 +1184,9 @@ body.layout-horizontal #rest-pane > .classic-toolbar-widget {
}
/* The active split in a multi-split view */
-#center-pane > .split-note-container-widget:has(> .note-split.visible ~ .note-split.visible) > .note-split.active::after,
-body.mobile #detail-container > .split-note-container-widget:has(> .note-split.visible ~ .note-split.visible) > .note-split.active::after {
+#center-pane > .split-note-container-widget.multiple-splits > .note-split.active::after,
+body.mobile #detail-container > .split-note-container-widget.multiple-splits
+ > .note-split.active::after {
border-color: var(--link-selection-outline-color);
}
diff --git a/apps/client/src/stylesheets/zen.css b/apps/client/src/stylesheets/zen.css
index 83cdab65a5..56c879362e 100644
--- a/apps/client/src/stylesheets/zen.css
+++ b/apps/client/src/stylesheets/zen.css
@@ -144,7 +144,7 @@ body.zen {
}
/* An open dropdown holds the toolbar up: hovering its submenu takes focus out of the split. */
- #root-widget:has(.note-split.type-text:focus-within) .classic-toolbar-widget,
+ .classic-toolbar-widget.split-focused,
.classic-toolbar-widget:focus-within,
.classic-toolbar-widget:has(.ck-dropdown__panel-visible) {
opacity: 1; /* Show when the note split is focused */
diff --git a/apps/client/src/widgets/NoteDetail.spec.ts b/apps/client/src/widgets/NoteDetail.spec.ts
index 51c26b2875..97b671f614 100644
--- a/apps/client/src/widgets/NoteDetail.spec.ts
+++ b/apps/client/src/widgets/NoteDetail.spec.ts
@@ -14,8 +14,8 @@ import froca from "../services/froca";
vi.mock("./note_tree", () => ({ default: class {} }));
import {
- getExtendedWidgetType, NoteDetailWrapper, shouldFocusOnNoteChange, useDeferredDetailFocus,
- useNoteInfo
+ checkFillsPane, getExtendedWidgetType, NoteDetailWrapper, shouldFocusOnNoteChange,
+ useDeferredDetailFocus, useNoteInfo
} from "./NoteDetail";
import { useLegacyImperativeHandlers, useTriliumEvent } from "./react/hooks";
import {
@@ -75,6 +75,17 @@ describe("getExtendedWidgetType blob-stub routing", () => {
});
});
+describe("checkFillsPane", () => {
+ it("lets the space usage page fill the pane, in its own view only", () => {
+ const spaceUsage = { noteId: "_spaceUsage" } as unknown as NoteContext;
+ const backendLog = { noteId: "_backendLog" } as unknown as NoteContext;
+ expect(checkFillsPane(spaceUsage, "contentWidget")).toBe(true);
+ expect(checkFillsPane(spaceUsage, "attachmentList")).toBe(false);
+ expect(checkFillsPane(backendLog, "contentWidget")).toBe(false);
+ expect(checkFillsPane(undefined, "contentWidget")).toBe(false);
+ });
+});
+
describe("useDeferredDetailFocus", () => {
const replay = vi.fn();
let request: ReturnType<typeof useDeferredDetailFocus> | undefined;
diff --git a/apps/client/src/widgets/NoteDetail.tsx b/apps/client/src/widgets/NoteDetail.tsx
index d56111a21b..27b80c0be1 100644
--- a/apps/client/src/widgets/NoteDetail.tsx
+++ b/apps/client/src/widgets/NoteDetail.tsx
@@ -28,6 +28,7 @@ import {
useGetContextDataFrom,
useLegacyComponentElement,
useNoteContext,
+ useParentClass,
useTriliumEvent
} from "./react/hooks";
import Icon from "./react/Icon";
@@ -52,6 +53,9 @@ export default function NoteDetail() {
const { note, type, mime, noteContext, parentComponent } = useNoteInfo();
const { ntxId, viewScope } = noteContext ?? {};
const isFullHeight = checkFullHeight(noteContext, type);
+ const fillsPane = checkFillsPane(noteContext, type);
+ useParentClass(containerRef, "detail-full-height", isFullHeight);
+ useParentClass(containerRef, "detail-fills-pane", fillsPane);
const [ noteTypesToRender, setNoteTypesToRender ] = useState<{ [ key in ExtendedNoteType ]?: (props: TypeWidgetProps) => VNode }>({});
const [ activeNoteType, setActiveNoteType ] = useState<ExtendedNoteType>();
const widgetRequestId = useRef(0);
@@ -250,7 +254,8 @@ export default function NoteDetail() {
<div
ref={containerRef}
class={clsx("component note-detail", {
- "full-height": isFullHeight
+ "full-height": isFullHeight,
+ "fills-pane": fillsPane
})}
>
{Object.entries(noteTypesToRender).map(([ itemType, Element ]) => {
@@ -587,6 +592,13 @@ export function checkFullHeight(noteContext: NoteContext | undefined, type: Exte
|| isBackendNote;
}
+/** Whether the note's page lays itself out across the pane and scrolls inside itself. */
+export function checkFillsPane(
+ noteContext: NoteContext | undefined, type: ExtendedNoteType | undefined
+) {
+ return type === "contentWidget" && noteContext?.noteId === "_spaceUsage";
+}
+
function showToast(type: "printing" | "exporting_pdf", progress: number = 0) {
toast.showPersistent({
icon: "bx bx-loader-circle bx-spin",
diff --git a/apps/client/src/widgets/collections/NoteList.tsx b/apps/client/src/widgets/collections/NoteList.tsx
index 6819cd76bc..4bc1858da7 100644
--- a/apps/client/src/widgets/collections/NoteList.tsx
+++ b/apps/client/src/widgets/collections/NoteList.tsx
@@ -8,7 +8,10 @@ import { useEffect, useRef, useState } from "preact/hooks";
import FNote from "../../entities/fnote";
import type { PrintReport } from "../../print";
import { subscribeToMessages, unsubscribeToMessage as unsubscribeFromMessage } from "../../services/ws";
-import { useGetContextDataFrom, useNoteContext, useNoteLabel, useNoteLabelBoolean, useNoteLabelInt, useNoteProperty, useTriliumEvent } from "../react/hooks";
+import {
+ useGetContextDataFrom, useNoteContext, useNoteLabel, useNoteLabelBoolean, useNoteLabelInt,
+ useNoteProperty, useParentClass, useTriliumEvent
+} from "../react/hooks";
import { ViewModeMedia, ViewModeProps, resolveViewType, ViewTypeOptions } from "./interface";
import ViewModeStorage, { type ViewModeStorageType } from "./view_mode_storage";
@@ -102,6 +105,7 @@ export function CustomNoteList({ note, viewType, isEnabled: shouldEnable, conten
const [ isIntersecting, setIsIntersecting ] = useState(false);
const shouldRender = shouldRenderNoteList(note, viewType, isIntersecting, media);
const isEnabled = (note && shouldEnable && !!viewType && shouldRender);
+ useParentClass(widgetRef, "list-full-height", !!(isFullHeight && isEnabled));
useEffect(() => {
if (isFullHeight || displayOnlyCollections || note?.type === "book") {
diff --git a/apps/client/src/widgets/containers/left_pane_container.css b/apps/client/src/widgets/containers/left_pane_container.css
index f7f8a4bd46..d354b89c50 100644
--- a/apps/client/src/widgets/containers/left_pane_container.css
+++ b/apps/client/src/widgets/containers/left_pane_container.css
@@ -26,7 +26,8 @@ body.layout-horizontal #horizontal-main-container {
--peek-button-collapse-background-color: var(--left-pane-peek-button-collapse-background-color);
}
-body.desktop.background-effects.layout-horizontal #horizontal-main-container:has(.note-split.visible.bgfx:not(.visible ~ .visible)) > .left-pane-peek-button {
+body.desktop.background-effects.layout-horizontal.first-split-bgfx
+ #horizontal-main-container > .left-pane-peek-button {
--peek-button-expand-background-color: var(--center-pane-background-color-bgfx, var(--main-background-color));
}
diff --git a/apps/client/src/widgets/containers/split_note_container.ts b/apps/client/src/widgets/containers/split_note_container.ts
index eb95f04bb6..367b642a93 100644
--- a/apps/client/src/widgets/containers/split_note_container.ts
+++ b/apps/client/src/widgets/containers/split_note_container.ts
@@ -6,6 +6,7 @@ import { isMobile } from "../../services/utils.js";
import type BasicWidget from "../basic_widget.js";
import { getTabToward } from "../mobile_widgets/tab_swipe.js";
import NoteContextAwareWidget from "../note_context_aware_widget.js";
+import { markVisibleSplits } from "../note_wrapper.js";
import FlexContainer from "./flex_container.js";
interface SplitNoteWidget extends BasicWidget {
@@ -275,12 +276,7 @@ export default class SplitNoteContainer extends FlexContainer<SplitNoteWidget> {
child.$widget.toggleClass("active", !!child.noteContext?.isActive());
}
- // Mark the rightmost visible split. CSS can't reach a split from outside #center-pane, so
- // siblings of it (the right pane peek button) need this hook to match its background.
- // Read the DOM, not `this.children`: splits are reordered in place, the array is not.
- const $visibleSplits = this.$widget.children(".note-split:not(.hidden-ext)");
- $visibleSplits.removeClass("last-visible");
- $visibleSplits.last().addClass("last-visible");
+ markVisibleSplits(this.$widget[0]);
}
toggleInt(show: boolean) {} // not needed
diff --git a/apps/client/src/widgets/layout/FormattingToolbar.tsx b/apps/client/src/widgets/layout/FormattingToolbar.tsx
index 64654a70e7..51117c5258 100644
--- a/apps/client/src/widgets/layout/FormattingToolbar.tsx
+++ b/apps/client/src/widgets/layout/FormattingToolbar.tsx
@@ -6,7 +6,10 @@ import { useEffect, useRef, useState } from "preact/hooks";
import NoteContext from "../../components/note_context";
import FNote from "../../entities/fnote";
import options from "../../services/options";
-import { useActiveNoteContext, useNoteContext, useNoteProperty, useTriliumEvent, useTriliumEvents, useTriliumOption } from "../react/hooks";
+import {
+ useActiveNoteContext, useDocumentFocus, useNoteContext, useNoteProperty, useTriliumEvent,
+ useTriliumEvents, useTriliumOption
+} from "../react/hooks";
import { useNestedEditor } from "../type_widgets/text/editable_embed";
/**
@@ -74,6 +77,8 @@ export function FixedFormattingToolbar() {
const { note, noteContext, ntxId } = useActiveNoteContext();
const noteType = useNoteProperty(note, "type");
const renderState = useRenderState(noteContext, note);
+ // In zen mode, the toolbar shows only while a text note's split has the focus.
+ const isTextSplitFocused = useDocumentFocus(".note-split.type-text");
const [ toolbarToRender, setToolbarToRender ] = useState<HTMLElement | null | undefined>();
const nestedEditor = useNestedEditor(ntxId);
const shownToolbar = nestedEditor?.ui.view.toolbar?.element ?? toolbarToRender;
@@ -134,7 +139,8 @@ export function FixedFormattingToolbar() {
ref={containerRef}
className={clsx("classic-toolbar-widget", {
"hidden-ext": renderState === "hidden",
- "disabled": renderState === "disabled"
+ "disabled": renderState === "disabled",
+ "split-focused": isTextSplitFocused
})}
/>
);
diff --git a/apps/client/src/widgets/layout/StatusBar.spec.tsx b/apps/client/src/widgets/layout/StatusBar.spec.tsx
index 04b64caf50..ee11413810 100644
--- a/apps/client/src/widgets/layout/StatusBar.spec.tsx
+++ b/apps/client/src/widgets/layout/StatusBar.spec.tsx
@@ -83,11 +83,20 @@ describe("StatusBar panels", () => {
fire("toggleRibbonTabSimilarNotes");
// The panel carries the list, which is the whole point of the action reaching the bar at all.
expect(container.querySelector(".similar-notes-pane .similar-notes-widget")).not.toBeNull();
- expect(container.querySelector(".status-bar")?.className).toContain("status-bar-panel-open");
+ expect(document.body.classList.contains("status-bar-panel-open")).toBe(true);
fire("toggleRibbonTabSimilarNotes");
expect(container.querySelector(".similar-notes-pane")).toBeNull();
- expect(container.querySelector(".status-bar")?.className).not.toContain("status-bar-panel-open");
+ expect(document.body.classList.contains("status-bar-panel-open")).toBe(false);
+ });
+
+ it("removes the body class when unmounted with a panel open", () => {
+ renderBar();
+ fire("toggleRibbonTabSimilarNotes");
+ expect(document.body.classList.contains("status-bar-panel-open")).toBe(true);
+
+ act(() => render(null, container));
+ expect(document.body.classList.contains("status-bar-panel-open")).toBe(false);
});
it("shows one panel at a time, the newer taking the place of the one already open", () => {
diff --git a/apps/client/src/widgets/layout/StatusBar.tsx b/apps/client/src/widgets/layout/StatusBar.tsx
index 9843da5ae2..e4fb2ff984 100644
--- a/apps/client/src/widgets/layout/StatusBar.tsx
+++ b/apps/client/src/widgets/layout/StatusBar.tsx
@@ -29,8 +29,9 @@ import Dropdown, { type DropdownHandle, DropdownPanel, type DropdownPanelProps }
import { FormDropdownDivider, FormListItem } from "../react/FormList";
import HelpDropdown from "../react/HelpDropdown";
import {
- useActiveNoteContext, useAttachments, useGetContextDataFrom, useLegacyImperativeHandlers,
- useNoteLabel, useNoteProperty, useStaticTooltip, useTriliumEvent, useTriliumEvents
+ useActiveNoteContext, useAttachments, useBodyClass, useGetContextDataFrom,
+ useLegacyImperativeHandlers, useNoteLabel, useNoteProperty, useStaticTooltip, useTriliumEvent,
+ useTriliumEvents
} from "../react/hooks";
import Icon from "../react/Icon";
import LinkButton from "../react/LinkButton";
@@ -76,8 +77,11 @@ export default function StatusBar() {
const isHiddenNote = note?.isHiddenCompletely();
const canEditAttributes = note?.isContentWritable !== false;
+ // The note split comes before the bar in the DOM, so its corner rule keys on a body class.
+ useBodyClass("status-bar-panel-open", !!activePane);
+
return (
- <div className={clsx("status-bar", {"status-bar-panel-open": !!activePane})}>
+ <div className="status-bar">
{attributesContext && canEditAttributes && <AttributesPane {...attributesContext} />}
{noteInfoContext && <SimilarNotesPane {...noteInfoContext} />}
diff --git a/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.css b/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.css
index c98d7f9c35..7a50a44ed8 100644
--- a/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.css
+++ b/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.css
@@ -60,7 +60,7 @@ body.mobile[dir="rtl"] .hide-keyboard-button {
left: var(--safe-area-inset-left, env(safe-area-inset-left));
}
-body.mobile:has(.classic-toolbar-outer-container.active) .hide-keyboard-button,
-body.mobile:not(:has(:focus)) .hide-keyboard-button {
+body.mobile.mobile-toolbar-active .hide-keyboard-button,
+body.mobile .hide-keyboard-button.no-focus {
display: none;
}
diff --git a/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.spec.tsx b/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.spec.tsx
index a9b80ff1f3..ca64b74387 100644
--- a/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.spec.tsx
+++ b/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.spec.tsx
@@ -46,6 +46,22 @@ describe("HideKeyboardButton", () => {
expect(document.activeElement).not.toBe(input);
});
+ it("is marked while nothing holds the focus", () => {
+ input = document.createElement("input");
+ document.body.append(input);
+ let container: HTMLElement | undefined;
+ act(() => { container = renderInto(<HideKeyboardButton />); });
+ const button = container?.querySelector(".hide-keyboard-button");
+ expect(button).toBeInstanceOf(HTMLElement);
+ expect(button?.classList.contains("no-focus")).toBe(true);
+
+ act(() => input?.focus());
+ expect(button?.classList.contains("no-focus")).toBe(false);
+
+ act(() => input?.blur());
+ expect(button?.classList.contains("no-focus")).toBe(true);
+ });
+
it("closes the menu instead, as an X, while it is given one to close", () => {
input = document.createElement("input");
document.body.append(input);
diff --git a/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.tsx b/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.tsx
index f800448e2a..014e9a2694 100644
--- a/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.tsx
+++ b/apps/client/src/widgets/mobile_widgets/hide_keyboard_button.tsx
@@ -7,6 +7,7 @@ import { useCallback, useEffect, useRef } from "preact/hooks";
import { t } from "../../services/i18n";
import { isIOS, isMobileApp } from "../../services/utils";
import ActionButton from "../react/ActionButton";
+import { useDocumentFocus } from "../react/hooks";
/**
* Closes the virtual keyboard by blurring the focused element. The button stands at the bottom-end
@@ -18,9 +19,15 @@ import ActionButton from "../react/ActionButton";
*/
export default function HideKeyboardButton() {
const containerRef = useRef<HTMLDivElement>(null);
+ const hasFocus = useDocumentFocus();
usePositioningOniOS(containerRef);
- return <HideKeyboardAction className="hide-keyboard-button" containerRef={containerRef} />;
+ return (
+ <HideKeyboardAction
+ className={clsx("hide-keyboard-button", !hasFocus && "no-focus")}
+ containerRef={containerRef}
+ />
+ );
}
/**
diff --git a/apps/client/src/widgets/mobile_widgets/sidebar_container.spec.ts b/apps/client/src/widgets/mobile_widgets/sidebar_container.spec.ts
index a3fcc7be17..423c417de0 100644
--- a/apps/client/src/widgets/mobile_widgets/sidebar_container.spec.ts
+++ b/apps/client/src/widgets/mobile_widgets/sidebar_container.spec.ts
@@ -94,6 +94,17 @@ describe("SidebarContainer", () => {
expect(tree.style.transform).toBe("translateX(-30%)");
});
+ it("marks the body while the tree is open", () => {
+ const sidebar = render(true);
+
+ sidebar.activeScreenChangedEvent({ activeScreen: "tree" });
+ expect(tree.classList.contains("show")).toBe(true);
+ expect(document.body.classList.contains("mobile-sidebar-open")).toBe(true);
+
+ sidebar.activeScreenChangedEvent({ activeScreen: "detail" });
+ expect(document.body.classList.contains("mobile-sidebar-open")).toBe(false);
+ });
+
it("marks the tree as dragged while a swipe from the edge reveals it", () => {
render(true);
const touch = (type: string, clientX: number) => document.dispatchEvent(
diff --git a/apps/client/src/widgets/mobile_widgets/sidebar_container.ts b/apps/client/src/widgets/mobile_widgets/sidebar_container.ts
index ad2fdddcd0..4c29a5c187 100644
--- a/apps/client/src/widgets/mobile_widgets/sidebar_container.ts
+++ b/apps/client/src/widgets/mobile_widgets/sidebar_container.ts
@@ -191,6 +191,7 @@ export default class SidebarContainer extends FlexContainer<BasicWidget> {
}
this.sidebarEl.classList.toggle("show", isOpen);
+ document.body.classList.toggle("mobile-sidebar-open", isOpen);
this.#applyTranslate(isOpen ? 0 : -100);
this.sidebarEl.style.transition = this.originalSidebarTransition;
if (this.detailEl) this.detailEl.style.transition = this.originalDetailTransition;
diff --git a/apps/client/src/widgets/note_wrapper.spec.ts b/apps/client/src/widgets/note_wrapper.spec.ts
index 12b9ba2b60..d00ba5bbdc 100644
--- a/apps/client/src/widgets/note_wrapper.spec.ts
+++ b/apps/client/src/widgets/note_wrapper.spec.ts
@@ -1,9 +1,11 @@
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import type NoteContext from "../components/note_context";
import type FNote from "../entities/fnote";
import { buildNote } from "../test/easy-froca";
-import NoteWrapperWidget, { hasBackgroundEffects, isAlwaysFullWidthByType, isFullWidthNote } from "./note_wrapper";
+import NoteWrapperWidget, {
+ hasBackgroundEffects, isAlwaysFullWidthByType, isFullWidthNote, markVisibleSplits
+} from "./note_wrapper";
describe("NoteWrapperWidget", () => {
it("preserves the classes owned by SplitNoteContainer in refresh()", () => {
@@ -92,6 +94,56 @@ describe("NoteWrapperWidget", () => {
doc.mime = "application/msword";
expect(hasBackgroundEffects(doc)).toBe(false);
});
+
+ it("updates the body classes of the outer splits when its note changes translucency", () => {
+ const container = document.createElement("div");
+ const widget = new NoteWrapperWidget();
+ widget.render();
+ container.append(widget.$widget[0]);
+
+ showNote(widget, buildNote({ title: "Photo", type: "image" }));
+ expect(document.body.classList.contains("first-split-bgfx")).toBe(true);
+ expect(document.body.classList.contains("last-split-bgfx")).toBe(true);
+
+ showNote(widget, buildNote({ title: "Plain", type: "text" }));
+ expect(document.body.classList.contains("first-split-bgfx")).toBe(false);
+ expect(document.body.classList.contains("last-split-bgfx")).toBe(false);
+ });
+});
+
+describe("markVisibleSplits", () => {
+ afterEach(() => {
+ document.body.classList.remove("first-split-bgfx", "last-split-bgfx");
+ });
+
+ function buildContainer(...splitClasses: string[]) {
+ const container = document.createElement("div");
+ for (const classes of splitClasses) {
+ const split = document.createElement("div");
+ split.className = `note-split ${classes}`;
+ container.append(split);
+ }
+ return container;
+ }
+
+ it("marks the last visible split, multiple splits and the translucent outer splits", () => {
+ const container = buildContainer("bgfx", "", "bgfx hidden-ext last-visible");
+ const [ first, second, hidden ] = container.children;
+
+ markVisibleSplits(container);
+ expect(first.classList.contains("last-visible")).toBe(false);
+ expect(second.classList.contains("last-visible")).toBe(true);
+ expect(hidden.classList.contains("last-visible")).toBe(false);
+ expect(container.classList.contains("multiple-splits")).toBe(true);
+ expect(document.body.classList.contains("first-split-bgfx")).toBe(true);
+ expect(document.body.classList.contains("last-split-bgfx")).toBe(false);
+
+ second.classList.add("hidden-ext");
+ markVisibleSplits(container);
+ expect(first.classList.contains("last-visible")).toBe(true);
+ expect(container.classList.contains("multiple-splits")).toBe(false);
+ expect(document.body.classList.contains("last-split-bgfx")).toBe(true);
+ });
});
describe("isAlwaysFullWidthByType", () => {
diff --git a/apps/client/src/widgets/note_wrapper.ts b/apps/client/src/widgets/note_wrapper.ts
index ea48f5ddd9..f4023c69f4 100644
--- a/apps/client/src/widgets/note_wrapper.ts
+++ b/apps/client/src/widgets/note_wrapper.ts
@@ -60,6 +60,12 @@ export default class NoteWrapperWidget extends FlexContainer<BasicWidget> {
classList.add(cls);
}
}
+
+ // `bgfx` can change here without SplitNoteContainer refreshing.
+ const container = this.$widget[0].parentElement;
+ if (container) {
+ markVisibleSplits(container);
+ }
}
/** The classes of the split, each entry holding one or more class names split by whitespace. */
@@ -111,6 +117,28 @@ export default class NoteWrapperWidget extends FlexContainer<BasicWidget> {
/** Classes set on the split by `SplitNoteContainer`, based on the split's position among its siblings. */
const CONTAINER_OWNED_CLASSES = [ "active", "last-visible" ];
+/**
+ * Marks the rightmost visible split of `container` with `last-visible`, and the container with
+ * `multiple-splits` while it shows more than one. Sets `first-split-bgfx` and `last-split-bgfx` on
+ * `body` while the outer visible splits are translucent, for the peek buttons on either side of
+ * `#center-pane`. Reads the DOM order, since `SplitNoteContainer` reorders the splits in place.
+ */
+export function markVisibleSplits(container: HTMLElement) {
+ const splits = [ ...container.children ]
+ .filter((child) => child.classList.contains("note-split"));
+ const visibleSplits = splits.filter((split) => !split.classList.contains("hidden-ext"));
+ const firstVisible = visibleSplits.at(0);
+ const lastVisible = visibleSplits.at(-1);
+ for (const split of splits) {
+ split.classList.toggle("last-visible", split === lastVisible);
+ }
+
+ const bodyClasses = document.body.classList;
+ container.classList.toggle("multiple-splits", visibleSplits.length > 1);
+ bodyClasses.toggle("first-split-bgfx", !!firstVisible?.classList.contains("bgfx"));
+ bodyClasses.toggle("last-split-bgfx", !!lastVisible?.classList.contains("bgfx"));
+}
+
/**
* Whether the split should be translucent (`bgfx`), letting the window background effect show through.
* This suits notes that render their content on a bare background (media, option pages, and the
diff --git a/apps/client/src/widgets/react/Dropdown.spec.tsx b/apps/client/src/widgets/react/Dropdown.spec.tsx
index 6eea688841..320e9a36e0 100644
--- a/apps/client/src/widgets/react/Dropdown.spec.tsx
+++ b/apps/client/src/widgets/react/Dropdown.spec.tsx
@@ -644,6 +644,11 @@ describe("Dropdown", () => {
await vi.waitFor(() => expect(popup()).not.toBeNull());
const drawn = [ ...popup()?.parentElement?.children ?? [] ].map((child) => child.classList[0]);
expect(drawn).toEqual([ "tn-dropdown-backdrop", "tn-popup" ]);
+ expect(document.body.classList.contains("backdrop-open")).toBe(true);
+
+ click(toggle);
+ await vi.waitFor(() => expect(popup()).toBeNull());
+ expect(document.body.classList.contains("backdrop-open")).toBe(false);
});
});
});
diff --git a/apps/client/src/widgets/react/Dropdown.tsx b/apps/client/src/widgets/react/Dropdown.tsx
index 11c94bd18d..11e0680ef1 100644
--- a/apps/client/src/widgets/react/Dropdown.tsx
+++ b/apps/client/src/widgets/react/Dropdown.tsx
@@ -9,7 +9,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } fr
import type { MenuItem } from "../../menus/context_menu";
import { isMobile, isNarrowLayout, onNarrowLayoutChange } from "../../services/utils";
import { focusListItem } from "./FormList";
-import { useTooltip, useUniqueName } from "./hooks";
+import { useBodyClass, useTooltip, useUniqueName } from "./hooks";
import { suspendModalFocusTraps } from "./modal_focustrap";
import Menu from "./Menu";
import Popup, { type PopupProps } from "./Popup";
@@ -202,6 +202,7 @@ function DropdownToggle({ id, className, buttonClassName, title, text, dropdownC
const triggerRef = useRef<HTMLButtonElement | null>(null);
const popupRef = useRef<HTMLDivElement | null>(null);
const [ shown, setShown ] = useState(false);
+ useBodyClass("backdrop-open", shown && !!backdrop);
/** The item to start at once the popup shows, for a popup a key on the toggle opened. */
const [ startAt, setStartAt ] = useState<"first" | "last">();
diff --git a/apps/client/src/widgets/react/Popover.tsx b/apps/client/src/widgets/react/Popover.tsx
index f2300d6a82..2fbb0e2993 100644
--- a/apps/client/src/widgets/react/Popover.tsx
+++ b/apps/client/src/widgets/react/Popover.tsx
@@ -6,6 +6,7 @@ import { ComponentChildren, createPortal } from "preact";
import { useEffect, useRef } from "preact/hooks";
import { FLOATING_LAYER_SELECTOR, isWithinFloatingLayer } from "./floating_layers";
+import { useBodyClass } from "./hooks";
import { placeFloating } from "./Popup";
export interface PopoverProps {
@@ -67,6 +68,7 @@ export default function Popover({ getAnchorRect, placement, updateKey, className
const elRef = useRef<HTMLDivElement>(null);
const arrowRef = useRef<HTMLDivElement>(null);
const updateRef = useRef<(() => void) | undefined>(undefined);
+ useBodyClass("backdrop-open", !!maximized);
// In a ref, so the placement set up once reads the latest `getAnchorRect`. Setting it up again
// on every render would reset the position mid-interaction.
diff --git a/apps/client/src/widgets/react/hooks.spec.tsx b/apps/client/src/widgets/react/hooks.spec.tsx
index 0ff82f96d9..d2d47ad48c 100644
--- a/apps/client/src/widgets/react/hooks.spec.tsx
+++ b/apps/client/src/widgets/react/hooks.spec.tsx
@@ -12,13 +12,16 @@ import { buildNote } from "../../test/easy-froca";
import { setupHoldContextMenu } from "../widget_utils";
import {
type DelayedVisibilityPhase,
+ useBodyClass,
useDelayedVisibility,
useDetachedNoteContext,
+ useDocumentFocus,
useFocusWithin,
useHoldContextMenu,
useImperativeSearchHighlighlighting,
useMediaQuery,
useNoteLabelBoolean,
+ useParentClass,
useStaticTooltip,
useTooltip,
useWhenShown
@@ -238,6 +241,112 @@ describe("useFocusWithin", () => {
});
});
+describe("useParentClass", () => {
+ function Child({ enabled }: { enabled: boolean }) {
+ const ref = useRef<HTMLDivElement>(null);
+ useParentClass(ref, "child-is-tall", enabled);
+ return <div ref={ref} />;
+ }
+
+ it("marks the parent while enabled, and unmarks it when disabled or unmounted", () => {
+ const parent = document.createElement("div");
+ document.body.appendChild(parent);
+
+ act(() => render(<Child enabled={true} />, parent));
+ expect(parent.classList.contains("child-is-tall")).toBe(true);
+
+ act(() => render(<Child enabled={false} />, parent));
+ expect(parent.classList.contains("child-is-tall")).toBe(false);
+
+ act(() => render(<Child enabled={true} />, parent));
+ expect(parent.classList.contains("child-is-tall")).toBe(true);
+ act(() => render(null, parent));
+ expect(parent.classList.contains("child-is-tall")).toBe(false);
+ parent.remove();
+ });
+});
+
+describe("useBodyClass", () => {
+ function Marker({ enabled }: { enabled: boolean }) {
+ useBodyClass("probe-open", enabled);
+ return null;
+ }
+
+ it("keeps the class while any component enables it", () => {
+ const first = document.createElement("div");
+ const second = document.createElement("div");
+ act(() => render(<Marker enabled={true} />, first));
+ act(() => render(<Marker enabled={true} />, second));
+ expect(document.body.classList.contains("probe-open")).toBe(true);
+
+ act(() => render(<Marker enabled={false} />, first));
+ expect(document.body.classList.contains("probe-open")).toBe(true);
+
+ act(() => render(null, second));
+ expect(document.body.classList.contains("probe-open")).toBe(false);
+ act(() => render(null, first));
+ });
+});
+
+describe("useDocumentFocus", () => {
+ let host: HTMLElement;
+ let root: HTMLElement;
+ let isFocused: boolean | undefined;
+
+ function Probe({ selector }: { selector?: string }) {
+ isFocused = useDocumentFocus(selector);
+ return null;
+ }
+
+ beforeEach(() => {
+ host = document.createElement("div");
+ host.innerHTML = `
+ <div class="note-split type-text"><input class="in-text"></div>
+ <div class="note-split type-code"><input class="in-code"></div>`;
+ root = document.createElement("div");
+ document.body.append(host, root);
+ });
+
+ afterEach(() => {
+ act(() => render(null, root));
+ host.remove();
+ root.remove();
+ });
+
+ function inputs() {
+ const inText = host.querySelector<HTMLInputElement>(".in-text");
+ const inCode = host.querySelector<HTMLInputElement>(".in-code");
+ expect(inText && inCode).toBeTruthy();
+ return { inText, inCode };
+ }
+
+ it("follows the focus into an element that matches the selector and out of it", () => {
+ const { inText, inCode } = inputs();
+ act(() => render(<Probe selector=".note-split.type-text" />, root));
+ expect(isFocused).toBe(false);
+
+ act(() => inText?.focus());
+ expect(isFocused).toBe(true);
+
+ act(() => inCode?.focus());
+ expect(isFocused).toBe(false);
+
+ act(() => inText?.focus());
+ act(() => inText?.blur());
+ expect(isFocused).toBe(false);
+ });
+
+ it("follows any focus without a selector, including one held before it mounts", () => {
+ const { inCode } = inputs();
+ act(() => inCode?.focus());
+ act(() => render(<Probe />, root));
+ expect(isFocused).toBe(true);
+
+ act(() => inCode?.blur());
+ expect(isFocused).toBe(false);
+ });
+});
+
describe("useStaticTooltip", () => {
let container: HTMLElement;
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index c423795a86..1b03334598 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -1151,6 +1151,74 @@ export function useIsOnScreen(ref: RefObject<Element | null>, enabled: boolean)
return isOnScreen;
}
+/**
+ * Puts `className` on the parent of the element in `ref` while `enabled` holds, for a parent laid
+ * out by what the component renders, such as a legacy `ScrollingContainer`. The parent is read when
+ * `enabled` turns true: a legacy container renders its Preact children into a fragment first.
+ */
+export function useParentClass(
+ ref: RefObject<HTMLElement | null>, className: string, enabled: boolean
+) {
+ useLayoutEffect(() => {
+ const parent = ref.current?.parentElement;
+ if (!enabled || !parent) return;
+ parent.classList.add(className);
+ return () => parent.classList.remove(className);
+ }, [ ref, className, enabled ]);
+}
+
+/**
+ * Puts `className` on `body` while at least one mounted component enables it, for an element whose
+ * style depends on a state it has no DOM relation to.
+ */
+export function useBodyClass(className: string, enabled: boolean) {
+ useLayoutEffect(() => {
+ if (!enabled) return;
+ bodyClassCounts.set(className, (bodyClassCounts.get(className) ?? 0) + 1);
+ document.body.classList.add(className);
+ return () => {
+ const remaining = (bodyClassCounts.get(className) ?? 1) - 1;
+ if (remaining > 0) {
+ bodyClassCounts.set(className, remaining);
+ return;
+ }
+ bodyClassCounts.delete(className);
+ document.body.classList.remove(className);
+ };
+ }, [ className, enabled ]);
+}
+
+/** How many mounted components enable each class of {@link useBodyClass}. */
+const bodyClassCounts = new Map<string, number>();
+
+/**
+ * Whether an element holds the focus anywhere in the document and, given `selector`, sits in an
+ * element that matches it. Unlike {@link useFocusWithin}, it needs no element of its own.
+ */
+export function useDocumentFocus(selector?: string) {
+ const [ isFocused, setIsFocused ] = useState(() => isFocusIn(document.activeElement, selector));
+
+ useEffect(() => {
+ // During `focusout`, `relatedTarget` is the element that receives the focus, if any.
+ const update = (e: FocusEvent) => {
+ setIsFocused(isFocusIn(e.type === "focusin" ? e.target : e.relatedTarget, selector));
+ };
+ document.addEventListener("focusin", update);
+ document.addEventListener("focusout", update);
+ return () => {
+ document.removeEventListener("focusin", update);
+ document.removeEventListener("focusout", update);
+ };
+ }, [ selector ]);
+
+ return isFocused;
+}
+
+function isFocusIn(target: EventTarget | null, selector: string | undefined) {
+ return target instanceof Element && target !== document.body
+ && (!selector || !!target.closest(selector));
+}
+
/**
* Whether the focus is in the element, including in an `<iframe>` or a `<webview>` inside it,
* which the document reports as its `activeElement`. Switching to another window keeps the value.
diff --git a/apps/client/src/widgets/sidebar/RightPanelContainer.css b/apps/client/src/widgets/sidebar/RightPanelContainer.css
index cd9697c3e7..4934192ac7 100644
--- a/apps/client/src/widgets/sidebar/RightPanelContainer.css
+++ b/apps/client/src/widgets/sidebar/RightPanelContainer.css
@@ -30,7 +30,7 @@ body.layout-vertical .right-pane-peek-button {
}
/* The button follows the translucency of the rightmost split. */
-body.desktop.background-effects #center-pane:has(.note-split.last-visible.bgfx) ~ .right-pane-peek-button {
+body.desktop.background-effects.last-split-bgfx #center-pane ~ .right-pane-peek-button {
--peek-button-expand-background-color: var(--center-pane-background-color-bgfx, var(--main-background-color));
}
diff --git a/apps/client/src/widgets/type_widgets/options/active_content.css b/apps/client/src/widgets/type_widgets/options/active_content.css
index 2eacc939f9..b194ee984a 100644
--- a/apps/client/src/widgets/type_widgets/options/active_content.css
+++ b/apps/client/src/widgets/type_widgets/options/active_content.css
@@ -6,7 +6,7 @@
--options-card-max-width: 100%;
}
-.note-detail-content-widget-content.options:has(.active-content-toolbar) > *:not(.options-page-header) {
+.note-detail-content-widget-content.options > .active-content-list {
margin-bottom: 0;
}
diff --git a/apps/client/src/widgets/type_widgets/space_usage/index.css b/apps/client/src/widgets/type_widgets/space_usage/index.css
index 85eaee095f..1c566dab25 100644
--- a/apps/client/src/widgets/type_widgets/space_usage/index.css
+++ b/apps/client/src/widgets/type_widgets/space_usage/index.css
@@ -1,14 +1,14 @@
/* The page replaces the note's scrolling with a viewport-filling layout: the flex chain runs from
the scroll container down to the section, so the charts get the pane's full height. */
-.scrolling-container:has(.space-usage-page) {
+.scrolling-container.detail-fills-pane {
display: flex;
flex-direction: column;
overflow: hidden;
}
-.note-detail:has(.space-usage-page),
-.note-detail:has(.space-usage-page) .note-detail-content-widget,
-.note-detail:has(.space-usage-page) .note-detail-content-widget-content {
+.note-detail.fills-pane,
+.note-detail.fills-pane .note-detail-content-widget,
+.note-detail.fills-pane .note-detail-content-widget-content {
display: flex;
flex: 1 1 auto;
flex-direction: column;
diff --git a/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.tsx b/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.tsx
index be7b12952f..14a360a695 100644
--- a/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.tsx
+++ b/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.tsx
@@ -8,7 +8,9 @@ import { isIOS } from "../../../services/utils";
import {
HideKeyboardAction, holdVisibleBottom, usePositioningOniOS
} from "../../mobile_widgets/hide_keyboard_button";
-import { useIsNoteReadOnly, useNoteContext, useNoteProperty, useTriliumEvent } from "../../react/hooks";
+import {
+ useBodyClass, useIsNoteReadOnly, useNoteContext, useNoteProperty, useTriliumEvent
+} from "../../react/hooks";
import { useNestedEditor } from "./editable_embed";
/**
@@ -31,6 +33,8 @@ export default function MobileEditorToolbar() {
const editor = nestedEditor?.ui.view.toolbar ? nestedEditor : noteEditor;
const toolbarElement = useShownToolbarElement(editor);
const isActive = useEditorsFocused(noteEditor, nestedEditor) || dropdownActive;
+ // The toolbar has its own hide-keyboard action; this class hides `HideKeyboardButton`.
+ useBodyClass("mobile-toolbar-active", shouldDisplay && isActive);
// A press outside the menu closes it as it starts, so the X's click only brings the keyboard
// back, focusing the text within the tap.
const isPanelOpen = useIsKeyboardPanelOpen();