From 0b3729faf1ad946af9e3d32a7743838e9ab56695 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sun, 29 Nov 2026 13:14:55 +0100 Subject: [PATCH] feat(ios): keep the caret above the keyboard in page mode With scrollEnabled off, avoidKeyboard put the keyboard into the editor's own bottom inset, so the editor scrolled its text inside its box, its first lines hid and the page stayed put. The editor now leaves that inset to scrolling editors and, while it has the focus, scrolls the nearest scroll view above it that has room, on every frame of the keyboard animation, after a caret move and when a scroll view above it changes size. A reveal that comes up short, as Enter on the last line does before the app grows the editor, runs again when the editor grows or the page gains room. keyboardOffset raises the keyboard's top only while the keyboard is up, so a keyboard guide at rest keeps the inset a scrolling editor has today. --- .../CodepadExample.xcodeproj/project.pbxproj | 4 + .../ios/CodepadTests/KeyboardInsetTests.swift | 11 +- .../ios/CodepadTests/PageKeyboardTests.swift | 252 ++++++++++++++++++ ios/Codepad/layout/KeyboardInset.swift | 5 + ios/Codepad/view/CodeEditorView.swift | 168 +++++++++++- ios/Codepad/view/KeyboardInsetTracker.swift | 28 +- tests/swift/KeyboardInsetTests.swift | 6 + 7 files changed, 448 insertions(+), 26 deletions(-) create mode 100644 example/ios/CodepadTests/PageKeyboardTests.swift diff --git a/example/ios/CodepadExample.xcodeproj/project.pbxproj b/example/ios/CodepadExample.xcodeproj/project.pbxproj index fe5ab328..b5f706ea 100644 --- a/example/ios/CodepadExample.xcodeproj/project.pbxproj +++ b/example/ios/CodepadExample.xcodeproj/project.pbxproj @@ -22,6 +22,7 @@ 761780ED2CA45674006654EE /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 761780EC2CA45674006654EE /* AppDelegate.swift */; }; 77E4DC2FD1B23B76EB060A44 /* ToolbarApiTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90EF449DDEB258D79CEA3F22 /* ToolbarApiTests.swift */; }; 789D6BA1A8D384C14452E7C6 /* LanguageSwitchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B813E2B1BCDEE1AE37F47D2 /* LanguageSwitchTests.swift */; }; + 7A3C91E2B04D5F6618C2A9E1 /* PageKeyboardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E1B8D47C93A2F0A6D4E7B13 /* PageKeyboardTests.swift */; }; 81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; }; 828B78BB2272434BF5005EAC /* GapLayoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC3DED79C5D26EBDEBBDB0A6 /* GapLayoutTests.swift */; }; 83260D5CF89F1C93CB5B7A0A /* SearchPaintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2F036F77C4601D08E5875C5 /* SearchPaintTests.swift */; }; @@ -70,6 +71,7 @@ 5BD68E46112559997B9B140B /* Pods-CodepadTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-CodepadTests.debug.xcconfig"; path = "Target Support Files/Pods-CodepadTests/Pods-CodepadTests.debug.xcconfig"; sourceTree = ""; }; 5DBB89C709979FAAE1972B1E /* ExpoModulesProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ExpoModulesProvider.swift; path = "Pods/Target Support Files/Pods-CodepadExample/ExpoModulesProvider.swift"; sourceTree = ""; }; 5DCACB8F33CDC322A6C60F78 /* libPods-CodepadExample.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-CodepadExample.a"; sourceTree = BUILT_PRODUCTS_DIR; }; + 5E1B8D47C93A2F0A6D4E7B13 /* PageKeyboardTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PageKeyboardTests.swift; sourceTree = ""; }; 6191685A83EE035E525D2D44 /* TextInputTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = TextInputTests.swift; sourceTree = ""; }; 6F5E9991D5A1AA0A5BA57DAB /* Pods-CodepadTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-CodepadTests.release.xcconfig"; path = "Target Support Files/Pods-CodepadTests/Pods-CodepadTests.release.xcconfig"; sourceTree = ""; }; 7133C4873626B3B59917468F /* RecordingTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = RecordingTests.swift; sourceTree = ""; }; @@ -218,6 +220,7 @@ 90EF449DDEB258D79CEA3F22 /* ToolbarApiTests.swift */, D8C50157F7EEE5B90548A381 /* UndoBridgeTests.swift */, 2FC5A2DC7199A9C215380CB2 /* KeyboardInsetTests.swift */, + 5E1B8D47C93A2F0A6D4E7B13 /* PageKeyboardTests.swift */, 7133C4873626B3B59917468F /* RecordingTests.swift */, 4A958039B4E3547886C83EB7 /* InitialTextTests.swift */, 0A9F1DCEAA80D2FE89C5BB26 /* KeyFrameHighlightTests.swift */, @@ -521,6 +524,7 @@ 77E4DC2FD1B23B76EB060A44 /* ToolbarApiTests.swift in Sources */, 1DECFFDCE384662B9BBE2BF7 /* UndoBridgeTests.swift in Sources */, 140C2EFB0059C4E49233BA8C /* KeyboardInsetTests.swift in Sources */, + 7A3C91E2B04D5F6618C2A9E1 /* PageKeyboardTests.swift in Sources */, 52B28AF3AAEE86E988E04DDF /* RecordingTests.swift in Sources */, 8CEE448DF1D2EBEE2DB4BB33 /* InitialTextTests.swift in Sources */, 886FE20130DB50D29808051C /* KeyFrameHighlightTests.swift in Sources */, diff --git a/example/ios/CodepadTests/KeyboardInsetTests.swift b/example/ios/CodepadTests/KeyboardInsetTests.swift index 4ee4c56a..f07893ea 100644 --- a/example/ios/CodepadTests/KeyboardInsetTests.swift +++ b/example/ios/CodepadTests/KeyboardInsetTests.swift @@ -42,11 +42,11 @@ final class KeyboardInsetTests: XCTestCase { let before = editor.contentOffset.y XCTAssertEqual(before, editor.contentSize.height - 400, accuracy: 0.5, "scrolled to the end") // The inset extends the range by its height and the reveal moves the caret row above the keyboard. - editor.applyKeyboardInset(300) + editor.applyKeyboardTop(editor.convert(editor.bounds, to: nil).maxY - 300) draw(editor) XCTAssertEqual(editor.contentOffset.y - before, 300, accuracy: 1) XCTAssertEqual(sizes.count, 1, "content size excludes the keyboard inset") - editor.applyKeyboardInset(0) + editor.applyKeyboardTop(.greatestFiniteMagnitude) draw(editor) XCTAssertEqual(editor.contentOffset.y, before, accuracy: 1, "the scroll clamps back to the end") XCTAssertEqual(sizes.count, 1) @@ -55,9 +55,10 @@ final class KeyboardInsetTests: XCTestCase { func testOverlapIsMeasuredInTheEditorsCoordinates() { let editor = launch(height: 300) editor.frame = CGRect(x: 0, y: 0, width: 300, height: 200) - let tracker = KeyboardInsetTracker(view: editor) { _ in } // A 300 pt keyboard over a 300 pt window: the editor ends 100 pt above the window bottom, so 200 pt overlap. - XCTAssertEqual(tracker.overlap(forKeyboardFrame: CGRect(x: 0, y: 0, width: 300, height: 300)), 200) - XCTAssertEqual(tracker.overlap(forKeyboardFrame: CGRect(x: 0, y: 300, width: 300, height: 300)), 0) + editor.applyKeyboardTop(0) + XCTAssertEqual(editor.keyboardInset, 200) + editor.applyKeyboardTop(300) + XCTAssertEqual(editor.keyboardInset, 0) } } diff --git a/example/ios/CodepadTests/PageKeyboardTests.swift b/example/ios/CodepadTests/PageKeyboardTests.swift new file mode 100644 index 00000000..ae1d2477 --- /dev/null +++ b/example/ios/CodepadTests/PageKeyboardTests.swift @@ -0,0 +1,252 @@ +import UIKit +import XCTest + +@testable import Codepad + +/// A page-mode editor under avoidKeyboard in a UIScrollView, with keyboard tops injected through the tracker's path. +@MainActor +final class PageKeyboardTests: XCTestCase { + private let text = (0..<60).map { "line \($0)" }.joined(separator: "\n") + + // The editor 300 pt wide and 1600 pt tall between spacers of above and below pt, in a 300 by 600 page. + private func page(above: CGFloat = 0, below: CGFloat = 1000, sideways: Bool = false) -> (UIScrollView, CodeEditorView) { + let editor = launch(width: 300, height: 600) + let window = editor.window! + let page = UIScrollView(frame: CGRect(x: 0, y: 0, width: 300, height: 600)) + // The window can run past the screen, whose safe area would inset the page. + page.contentInsetAdjustmentBehavior = .never + let controller = UIViewController() + controller.view = page + window.rootViewController = controller + var holder: UIView = page + if sideways { + let row = UIScrollView(frame: CGRect(x: 0, y: above, width: 300, height: 1600)) + row.contentSize = CGSize(width: 600, height: 1600) + page.addSubview(row) + holder = row + } + editor.frame = CGRect(x: 0, y: sideways ? 0 : above, width: 300, height: 1600) + holder.addSubview(editor) + page.contentSize = CGSize(width: 300, height: above + 1600 + below) + window.layoutIfNeeded() + editor.setScrollEnabled(false) + editor.setAvoidKeyboard(true) + editor.setInitialText(text) + draw(editor) + return (page, editor) + } + + // The caret row's window top and bottom in points, from the last published frame. + private func caretRow(_ editor: CodeEditorView) -> (top: CGFloat, bottom: CGFloat) { + guard let caret = editor.latestFrame.caret else { + XCTFail("no caret in the frame") + return (0, 0) + } + let top = editor.convert(CGPoint(x: 0, y: caret.minY + editor.contentOffset.y), to: nil).y + let bottom = editor.convert(CGPoint(x: 0, y: caret.maxY + editor.contentOffset.y), to: nil).y + return (top, bottom) + } + + // Puts the caret on the line whose row ends about 150 pt above the page's bottom, and draws. + private func caretLow(_ page: UIScrollView, _ editor: CodeEditorView) { + editor.core.setSelection(anchor: 0, head: 0) + draw(editor) + let row = caretRow(editor) + let pageBottom = page.convert(page.bounds, to: nil).maxY + let line = Int((pageBottom - 150 - row.top) / (row.bottom - row.top)) + let offset = (text as NSString).range(of: "line \(line)\n").location + editor.core.setSelection(anchor: offset, head: offset) + draw(editor) + } + + func testAKeyboardOverTheCaretScrollsThePageUntilTheRowClearsIt() { + let (page, editor) = page() + editor.focus() + caretLow(page, editor) + let row = caretRow(editor) + let keyboard = (row.bottom - 100).rounded() + editor.applyKeyboardTop(keyboard) + let after = caretRow(editor).bottom + XCTAssertLessThanOrEqual(after, keyboard + 0.5) + XCTAssertGreaterThan(after, keyboard - (row.bottom - row.top)) + XCTAssertGreaterThan(page.contentOffset.y, 0, "the page scrolled") + } + + func testPageModeLeavesTheKeyboardOutOfTheEditorsInset() { + let (page, editor) = page() + editor.focus() + caretLow(page, editor) + editor.applyKeyboardTop((caretRow(editor).bottom - 100).rounded()) + draw(editor) + XCTAssertEqual(editor.keyboardInset, 0) + XCTAssertEqual(editor.contentOffset.y, 0, accuracy: 0.5) + } + + func testKeyboardOffsetKeepsTheRowThatFarAboveTheKeyboard() { + let (page, editor) = page() + editor.focus() + editor.setKeyboardOffset(52) + caretLow(page, editor) + let keyboard = (caretRow(editor).bottom - 100).rounded() + editor.applyKeyboardTop(keyboard) + XCTAssertLessThanOrEqual(caretRow(editor).bottom, keyboard - 52 + 0.5) + } + + func testAnUnfocusedEditorLeavesThePageAlone() { + let (page, editor) = page() + caretLow(page, editor) + let before = page.contentOffset.y + editor.applyKeyboardTop((caretRow(editor).bottom - 100).rounded()) + XCTAssertEqual(page.contentOffset.y, before) + } + + func testAHorizontalScrollerBetweenIsSkipped() { + let (page, editor) = page(sideways: true) + editor.focus() + caretLow(page, editor) + let keyboard = (caretRow(editor).bottom - 100).rounded() + editor.applyKeyboardTop(keyboard) + XCTAssertGreaterThan(page.contentOffset.y, 0, "the page scrolled") + XCTAssertLessThanOrEqual(caretRow(editor).bottom, keyboard + 0.5) + } + + func testKeyboardOffsetCoversAScrollingEditorThatEndsJustAboveTheKeyboard() { + let editor = launch(width: 300, height: 400) + editor.frame = CGRect(x: 0, y: 0, width: 300, height: 300) + editor.setAvoidKeyboard(true) + editor.setInitialText(text) + editor.setKeyboardOffset(52) + editor.focus() + draw(editor) + let before = editor.keyboardInset + // The editor ends at 300 in a 400 pt window, 20 pt above the keyboard's top. + editor.applyKeyboardTop(320) + XCTAssertEqual(editor.keyboardInset - before, 32, accuracy: 0.5) + } + + func testKeyboardOffsetIsLeftOutWhileTheKeyboardRests() { + let editor = launch(width: 300, height: 400) + editor.window?.rootViewController?.additionalSafeAreaInsets.bottom = 34 + editor.window?.layoutIfNeeded() + editor.setAvoidKeyboard(true) + // With the keyboard down the guide rests at the bottom, and the inset stays what it was before the offset. + let resting = editor.keyboardInset + editor.setKeyboardOffset(52) + XCTAssertEqual(editor.keyboardInset, resting, accuracy: 0.5) + } + + func testTheScrollerShrinkingWhileTheKeyboardIsUpRevealsAgain() { + // The editor ends the page and the page sits at its end, so only room from a smaller scroller lifts the row. + let (page, editor) = page(below: 0) + editor.focus() + page.contentOffset.y = page.contentSize.height - page.bounds.height + // The last line, which the page at its end shows, so the caret move itself scrolls nothing. + editor.core.setSelection(anchor: text.utf16.count, head: text.utf16.count) + draw(editor) + let keyboard = (caretRow(editor).bottom - 100).rounded() + editor.applyKeyboardTop(keyboard) + XCTAssertGreaterThan(caretRow(editor).bottom, keyboard, "the row starts covered") + page.frame.size.height -= 200 + XCTAssertLessThanOrEqual(caretRow(editor).bottom, keyboard + 0.5) + } + + func testAPageScrolledByHandStaysWhereItIs() { + let (page, editor) = page() + editor.focus() + caretLow(page, editor) + editor.applyKeyboardTop((caretRow(editor).bottom - 100).rounded()) + page.contentOffset.y -= 50 + let scrolled = page.contentOffset.y + page.layoutIfNeeded() + draw(editor) + XCTAssertEqual(page.contentOffset.y, scrolled) + } + + func testAPageThatGainsRoomAfterFocusStillFollowsTheCaret() { + let (page, editor) = page() + // No vertical range at focus: the page fits, as a short exercise does before the keyboard opens. + let full = page.contentSize + page.contentSize = CGSize(width: 300, height: 600) + editor.focus() + draw(editor) + page.contentSize = full + caretLow(page, editor) + let keyboard = (caretRow(editor).bottom - 100).rounded() + editor.applyKeyboardTop(keyboard) + // An arrow key moves the caret, as the keyboard's input does. + let line = (text as NSString).range(of: "line 40\n").location + editor.core.setSelection(anchor: line, head: line) + editor.revealAfterInput() + draw(editor) + XCTAssertLessThanOrEqual(caretRow(editor).bottom, keyboard + 0.5) + } + + func testAPageThatFitsAtFocusRevealsOnceItShrinks() { + // No vertical range at focus, until the page gets shorter as a KeyboardAvoidingView makes it. + let (page, editor) = page() + page.contentSize = CGSize(width: 300, height: 600) + editor.focus() + caretLow(page, editor) + let keyboard = (caretRow(editor).bottom - 100).rounded() + editor.applyKeyboardTop(keyboard) + XCTAssertGreaterThan(caretRow(editor).bottom, keyboard, "the row starts covered") + page.frame.size.height -= 200 + XCTAssertLessThanOrEqual(caretRow(editor).bottom, keyboard + 0.5) + } + + func testTheEditorGrowingAfterAShortRevealShowsTheCaret() { + // The editor ends the page at its end, so the reveal comes up short until the app grows the editor. + let (page, editor) = page(below: 0) + editor.focus() + page.contentOffset.y = page.contentSize.height - page.bounds.height + editor.core.setSelection(anchor: text.utf16.count, head: text.utf16.count) + draw(editor) + let keyboard = (caretRow(editor).bottom - 100).rounded() + editor.applyKeyboardTop(keyboard) + XCTAssertGreaterThan(caretRow(editor).bottom, keyboard, "the row starts covered") + editor.frame.size.height += 150 + page.contentSize.height += 150 + draw(editor) + XCTAssertLessThanOrEqual(caretRow(editor).bottom, keyboard + 0.5) + } + + func testEnterOnTheLastLineShowsTheNewRowOnceTheEditorGrows() { + // Until the app grows the editor, its own reveal scrolls it a row, which the growth then gives back. + let (page, editor) = page(below: 100) + // Sizes the editor to its text, as an app does from onContentSizeChange. + func fit() { + let grow = editor.contentSize.height - editor.frame.height + editor.frame.size.height += grow + page.contentSize.height += grow + draw(editor) + } + fit() + editor.focus() + page.contentOffset.y = page.contentSize.height - page.bounds.height + editor.core.setSelection(anchor: text.utf16.count, head: text.utf16.count) + draw(editor) + let row = caretRow(editor) + let keyboard = (row.bottom + (row.bottom - row.top) / 2).rounded() + editor.applyKeyboardTop(keyboard) + editor.typeText("\n") + draw(editor) + fit() + XCTAssertLessThanOrEqual(caretRow(editor).bottom, keyboard + 0.5) + } + + func testThePageGainingRoomAfterTheEditorGrowsShowsTheCaret() { + // The editor takes its new height in one layout and the page's content size follows in a later one. + let (page, editor) = page(below: 0) + editor.focus() + page.contentOffset.y = page.contentSize.height - page.bounds.height + editor.core.setSelection(anchor: text.utf16.count, head: text.utf16.count) + draw(editor) + let keyboard = (caretRow(editor).bottom - 100).rounded() + editor.applyKeyboardTop(keyboard) + editor.frame.size.height += 150 + draw(editor) + XCTAssertGreaterThan(caretRow(editor).bottom, keyboard, "still covered with no room") + page.contentSize.height += 150 + XCTAssertLessThanOrEqual(caretRow(editor).bottom, keyboard + 0.5) + } +} diff --git a/ios/Codepad/layout/KeyboardInset.swift b/ios/Codepad/layout/KeyboardInset.swift index 1bf6f407..5fd80b46 100644 --- a/ios/Codepad/layout/KeyboardInset.swift +++ b/ios/Codepad/layout/KeyboardInset.swift @@ -7,4 +7,9 @@ enum KeyboardInset { static func overlap(viewBottomInWindow: CGFloat, windowHeight: CGFloat, keyboardTop: CGFloat) -> CGFloat { max(0, viewBottomInWindow - min(keyboardTop, windowHeight)) } + + /// Whether a keyboard layout guide's top sits above where it rests with the keyboard down, both in window points. + static func isUp(keyboardTop: CGFloat, restingTop: CGFloat) -> Bool { + keyboardTop < restingTop - 0.5 + } } diff --git a/ios/Codepad/view/CodeEditorView.swift b/ios/Codepad/view/CodeEditorView.swift index 26884367..ba7e328d 100644 --- a/ios/Codepad/view/CodeEditorView.swift +++ b/ios/Codepad/view/CodeEditorView.swift @@ -2,6 +2,10 @@ import CoreText import UIKit import os +#if canImport(CodepadCore) + import CodepadCore +#endif + /// Draws the document through a viewport (height map, layout cache, gutter, active line) in a scroll view /// whose content is TextInputView. layoutSubviews is the frame loop. @MainActor @@ -138,6 +142,13 @@ final class CodeEditorView: UIScrollView { private var contentInsetLeft: CGFloat = 0 private var contentInsetRight: CGFloat = 0 private(set) var keyboardInset: CGFloat = 0 + private var keyboardTop: CGFloat = .greatestFiniteMagnitude + // Page mode under avoidKeyboard: a reveal due at the end of the next layout, the scrollers above watched for their + // size, and whether the last reveal left the row short of where it should be. + private var pageRevealPending = false + private var pageWatch: [NSKeyValueObservation] = [] + private var pageSizes: [ObjectIdentifier: CGSize] = [:] + private var pageShort = false private var avoidsKeyboard = false private var keyboardOffset: CGFloat = 0 private(set) var keyboardTracker: KeyboardInsetTracker? @@ -322,17 +333,130 @@ final class CodeEditorView: UIScrollView { applyInsets() } - /// Points of the view under the keyboard, applied like a bottom inset. - func applyKeyboardInset(_ points: CGFloat) { - if points == keyboardInset { return } - keyboardInset = points + /// The top of the keyboard layout guide in window points from KeyboardInsetTracker, .greatestFiniteMagnitude with + /// none. Tests inject one here. + func applyKeyboardTop(_ points: CGFloat) { + keyboardTop = points + updateKeyboardInset() + revealInPage() + } + + // Up while the guide sits above where it rests, so a resting guide takes neither the offset nor a page reveal. + private var keyboardUp: Bool { + if keyboardTop == .greatestFiniteMagnitude { return false } + let resting = keyboardTracker?.restingTop() ?? window?.bounds.height ?? .greatestFiniteMagnitude + return KeyboardInset.isUp(keyboardTop: keyboardTop, restingTop: resting) + } + + // A scrolling editor takes its overlap with the guide's top, raised by keyboardOffset while the keyboard is up. + private func updateKeyboardInset() { + var inset: CGFloat = 0 + if scrollsVertically, keyboardTop != .greatestFiniteMagnitude, let window { + let bottom = convert(bounds, to: window).maxY + let top = keyboardUp ? keyboardTop - keyboardOffset : keyboardTop + inset = KeyboardInset.overlap(viewBottomInWindow: bottom, windowHeight: window.bounds.height, keyboardTop: top) + } + if inset == keyboardInset { return } + keyboardInset = inset applyInsets() } + /// Page mode under avoidKeyboard: scrolls the nearest vertical scroller the least that shows the caret row inside + /// it and above the keyboard's top raised by keyboardOffset. + private func revealInPage() { + guard !scrollsVertically, avoidsKeyboard, hasFocus, let window, let caret = latestFrame.caret else { return } + // No scroller has room yet, so the next size change tries again. + guard let page = pageScroller() else { + pageShort = true + return + } + let rowTop: CGFloat = convert(CGPoint(x: 0, y: caret.minY + contentOffset.y), to: window).y + let rowBottom: CGFloat = convert(CGPoint(x: 0, y: caret.maxY + contentOffset.y), to: window).y + let inset: UIEdgeInsets = page.adjustedContentInset + let band: CGRect = page.convert(page.bounds, to: window) + let up: CGFloat = page.contentOffset.y + inset.top + let down: CGFloat = max(0, page.contentSize.height + inset.bottom - page.bounds.height - page.contentOffset.y) + let keyboard: Int32 = keyboardUp ? Self.int32(keyboardTop.rounded(.down)) : Int32.max + let top = Self.int32(rowTop.rounded(.down)) + let bottom = Self.int32(rowBottom.rounded(.up)) + let visibleTop = Self.int32((band.minY + inset.top).rounded(.up)) + let visibleBottom = Self.int32((band.maxY - inset.bottom).rounded(.down)) + let offset = Self.int32(keyboardOffset.rounded()) + let delta: Int32 = cp_page_reveal_delta( + top, bottom, visibleTop, visibleBottom, keyboard, offset, Self.int32(up.rounded(.down)), + Self.int32(down.rounded(.down))) + let wanted: Int32 = cp_page_reveal_delta( + top, bottom, visibleTop, visibleBottom, keyboard, offset, Int32.max, Int32.max) + pageShort = delta != wanted + if delta == 0 { return } + page.setContentOffset(CGPoint(x: page.contentOffset.x, y: page.contentOffset.y + CGFloat(delta)), animated: false) + } + + private static func int32(_ value: CGFloat) -> Int32 { + Int32(max(-2_000_000_000, min(2_000_000_000, value))) + } + + // The nearest scroll view above this one with vertical range: a horizontal scroller in between is skipped. + private func pageScroller() -> UIScrollView? { + var view = superview + while let current = view { + if let scroller = current as? UIScrollView { + let inset = scroller.adjustedContentInset + if scroller.contentSize.height + inset.top + inset.bottom > scroller.bounds.height + 0.5 { return scroller } + } + view = current.superview + } + return nil + } + + private var watchesPage: Bool { hasFocus && window != nil && !scrollsVertically && avoidsKeyboard } + + // Any scroller above changing size shows the caret again, since the one with room can change after focus. + // A frame set (autoresizing does that) skips the bounds setter, and the bounds move on every scroll, so both are + // watched and only a new size counts. A new content size gives a short reveal another try. + private func watchPage() { + for watch in pageWatch { watch.invalidate() } + pageWatch = [] + pageSizes = [:] + guard watchesPage else { + pageRevealPending = false + pageShort = false + return + } + let resized: (UIScrollView) -> Void = { [weak self] scroller in + MainActor.assumeIsolated { self?.pageResized(scroller) } + } + let grew: () -> Void = { [weak self] in + MainActor.assumeIsolated { self?.pageGrew() } + } + var view = superview + while let current = view { + if let scroller = current as? UIScrollView { + pageSizes[ObjectIdentifier(scroller)] = scroller.bounds.size + pageWatch.append(scroller.observe(\.frame, options: []) { scroller, _ in resized(scroller) }) + pageWatch.append(scroller.observe(\.bounds, options: []) { scroller, _ in resized(scroller) }) + pageWatch.append(scroller.observe(\.contentSize, options: []) { _, _ in grew() }) + } + view = current.superview + } + } + + private func pageResized(_ page: UIScrollView) { + let id = ObjectIdentifier(page) + if pageSizes[id] == page.bounds.size { return } + pageSizes[id] = page.bounds.size + revealInPage() + } + + private func pageGrew() { + if pageShort { revealInPage() } + } + /// Follows the window's keyboard while attached; off by default. func setAvoidKeyboard(_ on: Bool) { avoidsKeyboard = on if on && window != nil { startKeyboardTracker() } else { stopKeyboardTracker() } + watchPage() } /// While the keyboard is up, its top counts this much higher, for a toolbar riding the keyboard. @@ -340,12 +464,13 @@ final class CodeEditorView: UIScrollView { let points = max(0, points) if points == keyboardOffset { return } keyboardOffset = points - applyInsets() + updateKeyboardInset() + revealInPage() } private func startKeyboardTracker() { if keyboardTracker != nil { return } - let tracker = KeyboardInsetTracker(view: self) { [weak self] points in self?.applyKeyboardInset(points) } + let tracker = KeyboardInsetTracker(view: self) { [weak self] top in self?.applyKeyboardTop(top) } keyboardTracker = tracker tracker.start() } @@ -364,6 +489,12 @@ final class CodeEditorView: UIScrollView { alwaysBounceVertical = enabled // A second scroll-to-top view in the window turns off the page's status bar tap. scrollsToTop = enabled + updateKeyboardInset() + watchPage() + if watchesPage { + pageRevealPending = true + setNeedsLayout() + } } override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { @@ -571,8 +702,16 @@ final class CodeEditorView: UIScrollView { lineScroll = nil } - /// Scrolls the least amount that shows the caret with the text padding around it. + /// Scrolls the least amount that shows the caret with the text padding around it, the page too in page mode. func revealSelection() { + revealCaret() + if watchesPage { + pageRevealPending = true + setNeedsLayout() + } + } + + private func revealCaret() { stopLineScroll() let m = rowMetrics() let doc = core.document @@ -674,6 +813,7 @@ final class CodeEditorView: UIScrollView { focusLock.withLock { $0 = focused } selectionViewsDirty = true if focused { revealPending = true } else { textInput.menu.hide() } + watchPage() setNeedsLayout() if focused { onEditorFocus?() } else { onEditorBlur?() } } @@ -690,9 +830,11 @@ final class CodeEditorView: UIScrollView { engine = nil snapshot = nil stopKeyboardTracker() + watchPage() } else { _ = ensureEngine() if avoidsKeyboard { startKeyboardTracker() } + watchPage() if autoFocusPending { runAutoFocus() } } } @@ -717,7 +859,8 @@ final class CodeEditorView: UIScrollView { } if revealPending { revealPending = false - revealSelection() + revealCaret() + if watchesPage { pageRevealPending = true } } var frame = readFrame() drawFrame = frame @@ -776,6 +919,10 @@ final class CodeEditorView: UIScrollView { onReady?() } if inputTime != 0 { logPaint() } else if scrolled { logFrame() } + if pageRevealPending { + pageRevealPending = false + revealInPage() + } } private func wire(_ core: EditorCore) { @@ -1067,12 +1214,17 @@ final class CodeEditorView: UIScrollView { private func sizeChanged(_ w: Int, _ h: Int) { let widthChanged = viewport.resize(width: w, height: h) cache.capacity = max(64, 3 * (h / rowMetrics().rowHeight + 1)) + var moved = widthChanged if widthChanged { relayout() } else if viewport.clamp() { pushScroll() onScrolled() + moved = true } + // An editor that grows with its text gives the page the room a short reveal lacked, and takes back the row its + // own reveal scrolled to, which moves the caret on screen. + if (pageShort || moved) && watchesPage { pageRevealPending = true } } /// Builds missing layouts for [first, last] with one highlight query per run of dirty lines: the lines the snapshot's diff --git a/ios/Codepad/view/KeyboardInsetTracker.swift b/ios/Codepad/view/KeyboardInsetTracker.swift index 3dc3ac1d..4d656e72 100644 --- a/ios/Codepad/view/KeyboardInsetTracker.swift +++ b/ios/Codepad/view/KeyboardInsetTracker.swift @@ -1,11 +1,12 @@ import UIKit -/// Follows the window's keyboard on behalf of one view and reports the points of the view under it. A zero height -/// tracking view pinned to the keyboard layout guide moves with the keyboard; its presentation layer gives the +/// Follows the window's keyboard on behalf of one view and reports the top of its keyboard layout guide in window +/// points. A zero height tracking view pinned to the guide moves with the keyboard; its presentation layer gives the /// in-flight edge while a notification's animation runs. @MainActor final class KeyboardInsetTracker { private weak var view: UIView? + private weak var host: UIView? private let apply: (CGFloat) -> Void private let trackingView = UIView() private var link: CADisplayLink? @@ -19,13 +20,15 @@ final class KeyboardInsetTracker { trackingView.translatesAutoresizingMaskIntoConstraints = false } - /// Pins the tracking view in the view's window and applies the current overlap; nothing happens outside a window. + /// Pins the tracking view in the view's window and applies the current top; nothing happens outside a window. func start() { guard !isTracking, let view, let window = view.window else { return } isTracking = true window.addSubview(trackingView) + let host = Self.keyboardHost(of: view, in: window) + self.host = host NSLayoutConstraint.activate([ - trackingView.topAnchor.constraint(equalTo: Self.keyboardHost(of: view, in: window).keyboardLayoutGuide.topAnchor), + trackingView.topAnchor.constraint(equalTo: host.keyboardLayoutGuide.topAnchor), trackingView.leadingAnchor.constraint(equalTo: window.leadingAnchor), trackingView.trailingAnchor.constraint(equalTo: window.trailingAnchor), trackingView.heightAnchor.constraint(equalToConstant: 0), @@ -38,21 +41,20 @@ final class KeyboardInsetTracker { applyCurrent() } - /// Stops following and clears the inset. + /// Stops following and reports no keyboard. func stop() { guard isTracking else { return } isTracking = false NotificationCenter.default.removeObserver(self) stopLink() trackingView.removeFromSuperview() - apply(0) + apply(.greatestFiniteMagnitude) } - /// Points of the view under a keyboard whose frame is in the window's coordinates. - func overlap(forKeyboardFrame frame: CGRect) -> CGFloat { - guard let view, let window = view.window else { return 0 } - let bottom = view.convert(view.bounds, to: window).maxY - return KeyboardInset.overlap(viewBottomInWindow: bottom, windowHeight: window.bounds.height, keyboardTop: frame.minY) + /// Where the guide's top sits with the keyboard down: the host's safe area bottom, in window points. + func restingTop() -> CGFloat { + guard let host, let window = host.window else { return .greatestFiniteMagnitude } + return host.convert(CGPoint(x: 0, y: host.bounds.maxY - host.safeAreaInsets.bottom), to: window).y } @objc private func keyboardWillMove(_ note: Notification) { @@ -68,7 +70,7 @@ final class KeyboardInsetTracker { /// Reads the presentation layer while the keyboard animates; the last tick applies the end value. @objc private func tick() { if CACurrentMediaTime() < deadline, let frame = trackingView.layer.presentation()?.frame { - apply(overlap(forKeyboardFrame: frame)) + apply(frame.minY) return } stopLink() @@ -76,7 +78,7 @@ final class KeyboardInsetTracker { } private func applyCurrent() { - apply(overlap(forKeyboardFrame: trackingView.frame)) + apply(trackingView.frame.minY) } private func stopLink() { diff --git a/tests/swift/KeyboardInsetTests.swift b/tests/swift/KeyboardInsetTests.swift index 231db904..3f8d0a74 100644 --- a/tests/swift/KeyboardInsetTests.swift +++ b/tests/swift/KeyboardInsetTests.swift @@ -12,4 +12,10 @@ final class KeyboardInsetTests: XCTestCase { // A keyboard frame below the window counts as the window bottom. XCTAssertEqual(KeyboardInset.overlap(viewBottomInWindow: 950, windowHeight: 900, keyboardTop: 1200), 50) } + + func testTheKeyboardIsUpOnlyAboveWhereTheGuideRests() { + XCTAssertFalse(KeyboardInset.isUp(keyboardTop: 866, restingTop: 866)) + XCTAssertFalse(KeyboardInset.isUp(keyboardTop: .greatestFiniteMagnitude, restingTop: 866)) + XCTAssertTrue(KeyboardInset.isUp(keyboardTop: 600, restingTop: 866)) + } }