Skip to content

Commit

Permalink
Merge pull request #65 from wordpress-mobile/issue/167-intercept-back…
Browse files Browse the repository at this point in the history
…space

Backspace interception for iOS.
  • Loading branch information
daniloercoli authored Oct 25, 2018
2 parents c07e661 + b7c2874 commit b2ecf28
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 9 deletions.
47 changes: 38 additions & 9 deletions ios/RNTAztecView/RCTAztecView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Foundation
import UIKit

class RCTAztecView: Aztec.TextView {
@objc var onBackspace: RCTBubblingEventBlock? = nil
@objc var onChange: RCTBubblingEventBlock? = nil
@objc var onEnter: RCTBubblingEventBlock? = nil
@objc var onContentSizeChange: RCTBubblingEventBlock? = nil
Expand Down Expand Up @@ -62,26 +63,47 @@ class RCTAztecView: Aztec.TextView {
// MARK: - Edits

open override func insertText(_ text: String) {
guard text != "\n" else {
let data: [AnyHashable: Any] = [
"text": getHTML(),
"selectionStart": selectedRange.location,
"selectionEnd": selectedRange.location + selectedRange.length,
]

onEnter?(data)
guard !interceptEnter(text) else {
return
}

super.insertText(text)
updatePlaceholderVisibility()
}

open override func deleteBackward() {
guard !interceptBackspace() else {
return
}

super.deleteBackward()
updatePlaceholderVisibility()
}

// MARK: - Custom Edit Intercepts

private func interceptEnter(_ text: String) -> Bool {
guard text == "\n",
let onEnter = onEnter else {
return false
}

let caretData = packCaretDataForRN()
onEnter(caretData)
return true
}

private func interceptBackspace() -> Bool {
guard selectedRange.location == 0,
let onBackspace = onBackspace else {
return false
}

let caretData = packCaretDataForRN()
onBackspace(caretData)
return true
}

// MARK: - Native-to-RN Value Packing Logic

func packForRN(_ text: String, withName name: String) -> [AnyHashable: Any] {
Expand All @@ -96,6 +118,13 @@ class RCTAztecView: Aztec.TextView {

return [name: size]
}

func packCaretDataForRN() -> [AnyHashable: Any] {
return ["text": getHTML(),
"selectionStart": selectedRange.location,
"selectionEnd": selectedRange.location + selectedRange.length,
]
}

// MARK: - RN Properties

Expand Down
1 change: 1 addition & 0 deletions ios/RNTAztecView/RCTAztecViewManager.m
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ @implementation RCTAztecViewManager (RCTExternModule)

RCT_REMAP_VIEW_PROPERTY(text, contents, NSDictionary)
RCT_EXPORT_VIEW_PROPERTY(onContentSizeChange, RCTBubblingEventBlock)
RCT_EXPORT_VIEW_PROPERTY(onBackspace, RCTBubblingEventBlock)
RCT_EXPORT_VIEW_PROPERTY(onChange, RCTBubblingEventBlock)
RCT_EXPORT_VIEW_PROPERTY(onEnter, RCTBubblingEventBlock)

Expand Down

0 comments on commit b2ecf28

Please sign in to comment.