Skip to content

Build your personal knowledge base with Trilium Notes

fix(mobile/ios): viewpoint not changing when keyboard open

AndreeaCorlacia5ba45b6d4a7
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index f0ac3ba111..e39f6cbb0c 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -235,6 +235,100 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
document.body.style.setProperty("--code-block-tab-width", codeBlockTabWidth || "4");
}, [codeBlockTabWidth]);
+ // Mobile-only: when the keyboard opens, scroll the caret into view.
+ //
+ // Under iOS WKWebView the outer scroll view is pinned to zero (see
+ // ViewController.swift) so the toolbar doesn't get dragged off-screen
+ // — which also suppresses iOS's native scroll-focused-element-into-
+ // view behaviour. Without this effect, tapping near the bottom of a
+ // long note leaves the view stuck at the top with the caret behind
+ // the keyboard.
+ //
+ // Find the nearest scrollable ancestor of the caret, clamp its
+ // "visible bottom" to `visualViewport.height` (so the caret lands
+ // above the keyboard, not merely inside the container's rect), and
+ // adjust scrollTop directly.
+ useEffect(() => {
+ if (!isMobile()) return;
+
+ const CARET_BOTTOM_MARGIN_PX = 48;
+
+ const findScrollableAncestor = (start: Node | null | undefined): HTMLElement | null => {
+ let el: Node | null | undefined = start;
+ while (el) {
+ if (el instanceof HTMLElement) {
+ const overflowY = getComputedStyle(el).overflowY;
+ if ((overflowY === "auto" || overflowY === "scroll")
+ && el.scrollHeight > el.clientHeight + 1) {
+ return el;
+ }
+ }
+ el = el.parentNode;
+ }
+ return null;
+ };
+
+ const getCaretRect = (): DOMRect | null => {
+ const sel = window.getSelection();
+ if (!sel || sel.rangeCount === 0) return null;
+ let rect = sel.getRangeAt(0).getBoundingClientRect();
+ // Collapsed carets at end-of-line return a zero rect; fall
+ // back to the containing element.
+ if (rect.width === 0 && rect.height === 0) {
+ const el = sel.focusNode instanceof Element
+ ? sel.focusNode
+ : sel.focusNode?.parentElement;
+ if (el) rect = el.getBoundingClientRect();
+ }
+ return rect;
+ };
+
+ const scrollCaretIntoView = () => {
+ const caretRect = getCaretRect();
+ if (!caretRect) return;
+ const scroller = findScrollableAncestor(window.getSelection()?.focusNode);
+ if (!scroller) return;
+
+ const vv = window.visualViewport;
+ const containerRect = scroller.getBoundingClientRect();
+ const viewportBottom = vv ? vv.offsetTop + vv.height : window.innerHeight;
+ const viewportTop = vv?.offsetTop ?? 0;
+ const visibleBottom = Math.min(containerRect.bottom, viewportBottom);
+ const visibleTop = Math.max(containerRect.top, viewportTop);
+
+ const overshoot = caretRect.bottom - (visibleBottom - CARET_BOTTOM_MARGIN_PX);
+ if (overshoot > 0) {
+ scroller.scrollTop += overshoot;
+ return;
+ }
+ const undershoot = (visibleTop + CARET_BOTTOM_MARGIN_PX) - caretRect.top;
+ if (undershoot > 0) {
+ scroller.scrollTop -= undershoot;
+ }
+ };
+
+ let pending: number | null = null;
+ const schedule = () => {
+ if (pending !== null) return;
+ // Double rAF lets the keyboard animation, WebView resize, and
+ // CKEditor's post-focus layout all settle before we measure.
+ pending = requestAnimationFrame(() => {
+ pending = requestAnimationFrame(() => {
+ pending = null;
+ scrollCaretIntoView();
+ });
+ });
+ };
+
+ window.visualViewport?.addEventListener("resize", schedule);
+ document.addEventListener("focusin", schedule);
+ return () => {
+ window.visualViewport?.removeEventListener("resize", schedule);
+ document.removeEventListener("focusin", schedule);
+ if (pending !== null) cancelAnimationFrame(pending);
+ };
+ }, []);
+
// Mobile-only: toggle todo-list checkboxes on the first tap and widen the
// hit area so finger taps don't have to land precisely on the ~16px box.
// Two problems are being solved:
diff --git a/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.css b/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.css
index 1ccc139f87..c187e752d4 100644
--- a/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.css
+++ b/apps/client/src/widgets/type_widgets/text/mobile_editor_toolbar.css
@@ -22,6 +22,11 @@ body.mobile {
user-select: none;
touch-action: pan-x;
scrollbar-width: 0 !important;
+ /* On iOS, `--tn-keyboard-gap` is updated continuously by the
+ ViewController (Swift) as the keyboard frame changes, so the
+ toolbar follows a finger-dragged keyboard during interactive
+ dismiss. Zero elsewhere — no effect on Android or non-Capacitor. */
+ transform: translateY(var(--tn-keyboard-gap, 0px));
}
.classic-toolbar-widget::-webkit-scrollbar:horizontal {
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 c5e5882746..8ecffd7815 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
@@ -66,32 +66,35 @@ export default function MobileEditorToolbar({ inPopupEditor }: MobileEditorToolb
}
function usePositioningOniOS(enabled: boolean, wrapperRef: MutableRef<HTMLDivElement | null>) {
- // Capture the baseline offset (Safari nav bar height) before the keyboard opens.
- const baselineOffset = useRef(window.innerHeight - (window.visualViewport?.height ?? window.innerHeight));
-
+ // Fallback path for plain mobile Safari (no Capacitor): the WKWebView
+ // isn't resized when the keyboard opens, so visualViewport.height
+ // shrinks while window.innerHeight stays the same. Push the toolbar
+ // up by the difference. Under Capacitor `resize: native` both values
+ // shrink together, so `obscured` is 0 and we leave CSS in charge.
const adjustPosition = useCallback(() => {
if (!wrapperRef.current) return;
const viewport = window.visualViewport;
if (!viewport) return;
- // Subtract the baseline so only the keyboard's contribution remains.
- const bottom = window.innerHeight - viewport.height - viewport.offsetTop;
- if (bottom - baselineOffset.current <= 0) {
- // Keyboard is hidden — clear the inline style so CSS controls positioning.
+
+ const obscured = Math.max(0, Math.round(
+ window.innerHeight - viewport.height - viewport.offsetTop
+ ));
+
+ if (obscured <= 1) {
wrapperRef.current.style.removeProperty("bottom");
} else {
- wrapperRef.current.style.bottom = `${bottom}px`;
+ wrapperRef.current.style.bottom = `${obscured}px`;
}
}, [ wrapperRef ]);
useEffect(() => {
if (!isIOS() || !enabled) return;
-
+ // Run once in case the keyboard is already up when mounting
+ // (e.g. returning from a dialog).
+ adjustPosition();
window.visualViewport?.addEventListener("resize", adjustPosition);
- window.addEventListener("scroll", adjustPosition);
-
return () => {
window.visualViewport?.removeEventListener("resize", adjustPosition);
- window.removeEventListener("scroll", adjustPosition);
};
}, [ enabled, adjustPosition ]);
}
diff --git a/apps/mobile/ios/App/App/ViewController.swift b/apps/mobile/ios/App/App/ViewController.swift
index f9c3bf14a2..37d2835b65 100644
--- a/apps/mobile/ios/App/App/ViewController.swift
+++ b/apps/mobile/ios/App/App/ViewController.swift
@@ -4,10 +4,144 @@ import WebKit
import ObjectiveC.runtime
class ViewController: CAPBridgeViewController {
+ // True between keyboardWillShow and keyboardDidShow. During that
+ // window we pin the outer WKWebView scroll offset to zero so iOS's
+ // auto-scroll-to-focus can't drag the toolbar off-screen.
+ private var isKeyboardAnimating = false
+ private var scrollOffsetObservation: NSKeyValueObservation?
+ // Display link that samples the keyboard's current top edge every
+ // render frame while the keyboard is visible or animating. Drives
+ // the `--tn-keyboard-gap` CSS variable so the web-side editor toolbar
+ // follows the keyboard smoothly during interactive swipe-dismiss.
+ private var keyboardFrameTracker: CADisplayLink?
+ private var lastKeyboardGap: CGFloat = -1
+
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardInputAccessoryView()
enableInteractiveKeyboardDismiss()
+ observeKeyboard()
+ }
+
+ deinit {
+ NotificationCenter.default.removeObserver(self)
+ scrollOffsetObservation?.invalidate()
+ keyboardFrameTracker?.invalidate()
+ }
+
+ // When a page element receives focus and the keyboard animates in,
+ // WKWebView reflexively scrolls its outer UIScrollView upward to keep
+ // the focused element visible. Our layout is `body { position: fixed;
+ // height: 100vh }` with an internal ScrollingContainer for note
+ // content — the outer scroll has nothing useful to scroll, so iOS's
+ // auto-scroll just drags the whole layout (toolbar included) off the
+ // top of the viewport. We can't disable the scroll view outright
+ // because the interactive swipe-down-to-dismiss gesture needs it, so
+ // we KVO the contentOffset and revert any non-zero value written
+ // during the keyboard animation.
+ //
+ // Separately, we run a CADisplayLink while the keyboard is present
+ // and sample the live keyboard window frame each frame. Keyboard
+ // notifications only fire on commit (not per-frame during an
+ // interactive drag), and `keyboardLayoutGuide.layoutFrame` only
+ // reflects the keyboard's final resting position — neither is
+ // sufficient for tracking mid-drag. The keyboard window's frame, by
+ // contrast, is updated by UIKit every frame. We push the position
+ // into the `--tn-keyboard-gap` CSS variable, which translates the
+ // web-side editor toolbar so it follows the keyboard.
+ private func observeKeyboard() {
+ let nc = NotificationCenter.default
+ nc.addObserver(self, selector: #selector(keyboardWillShow),
+ name: UIResponder.keyboardWillShowNotification, object: nil)
+ nc.addObserver(self, selector: #selector(keyboardDidShow),
+ name: UIResponder.keyboardDidShowNotification, object: nil)
+ nc.addObserver(self, selector: #selector(keyboardDidHide),
+ name: UIResponder.keyboardDidHideNotification, object: nil)
+
+ scrollOffsetObservation = self.webView?.scrollView.observe(\.contentOffset, options: [.new]) { [weak self] scrollView, _ in
+ guard let self = self, self.isKeyboardAnimating else { return }
+ if scrollView.contentOffset != .zero {
+ scrollView.setContentOffset(.zero, animated: false)
+ }
+ }
+ }
+
+ @objc private func keyboardWillShow() {
+ isKeyboardAnimating = true
+ startKeyboardFrameTracker()
+ }
+
+ @objc private func keyboardDidShow() {
+ isKeyboardAnimating = false
+ }
+
+ @objc private func keyboardDidHide() {
+ stopKeyboardFrameTracker()
+ setKeyboardGap(0)
+ }
+
+ private func startKeyboardFrameTracker() {
+ if keyboardFrameTracker != nil { return }
+ let link = CADisplayLink(target: self, selector: #selector(onDisplayLinkTick))
+ link.add(to: .main, forMode: .common)
+ keyboardFrameTracker = link
+ }
+
+ private func stopKeyboardFrameTracker() {
+ keyboardFrameTracker?.invalidate()
+ keyboardFrameTracker = nil
+ }
+
+ @objc private func onDisplayLinkTick() {
+ guard let webView = self.webView else { return }
+ // Gap = how far below the webview's bottom edge the keyboard's
+ // top sits. Zero when the keyboard is fully shown (Capacitor's
+ // `resize: native` has matched the webview bottom to keyboard
+ // top); positive while the user drags the keyboard downward.
+ let kbTop = currentKeyboardTopY()
+ let gap = max(0, kbTop - webView.frame.maxY)
+ if abs(gap - lastKeyboardGap) < 0.5 { return }
+ lastKeyboardGap = gap
+ setKeyboardGap(gap)
+ }
+
+ // Returns the live top edge of the on-screen keyboard in the view's
+ // coordinate space. Walks the window hierarchy to find the keyboard
+ // window (class name contains "Keyboard" on all recent iOS versions)
+ // and measures its hosting subview directly — this tracks per-frame
+ // during an interactive drag, unlike `keyboardLayoutGuide.layoutFrame`
+ // which only reports the resting position.
+ private func currentKeyboardTopY() -> CGFloat {
+ for scene in UIApplication.shared.connectedScenes {
+ guard let windowScene = scene as? UIWindowScene else { continue }
+ for window in windowScene.windows
+ where NSStringFromClass(type(of: window)).contains("Keyboard") {
+ if let kbView = keyboardHostingView(in: window) {
+ return kbView.convert(kbView.bounds, to: view).minY
+ }
+ return window.convert(window.bounds, to: view).minY
+ }
+ }
+ return view.keyboardLayoutGuide.layoutFrame.minY
+ }
+
+ private func keyboardHostingView(in container: UIView) -> UIView? {
+ for sub in container.subviews {
+ let name = NSStringFromClass(type(of: sub))
+ if name.contains("Input") || name.contains("Keyboard") {
+ return sub
+ }
+ if let nested = keyboardHostingView(in: sub) {
+ return nested
+ }
+ }
+ return nil
+ }
+
+ private func setKeyboardGap(_ gap: CGFloat) {
+ lastKeyboardGap = gap
+ let js = "document.documentElement.style.setProperty('--tn-keyboard-gap','\(gap)px')"
+ self.webView?.evaluateJavaScript(js, completionHandler: nil)
}
// Because we hide iOS's input accessory bar (which contains the Done