Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First steps to implement pasting external content #553

Merged
merged 18 commits into from
Feb 19, 2019
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@
"refx": "^3.0.0",
"rememo": "^3.0.0",
"shallowequal": "^1.0.2",
"showdown": "^1.8.6",
"simple-html-tokenizer": "^0.4.1",
"tannin": "^1.0.1",
"tinycolor2": "^1.4.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,11 @@ public Map<String, Object> getExportedCustomBubblingEventTypeConstants() {
MapBuilder.of(
"phasedRegistrationNames",
MapBuilder.of("bubbled", "onBackspace")))
.put(
"topTextInputPaste",
MapBuilder.of(
"phasedRegistrationNames",
MapBuilder.of("bubbled", "onPaste")))
.put(
"topFocus",
MapBuilder.of(
Expand Down Expand Up @@ -386,6 +391,11 @@ public void setOnBackspaceHandling(final ReactAztecText view, boolean onBackspac
view.shouldHandleOnBackspace = onBackspaceHandling;
}

@ReactProp(name = "onPaste", defaultBoolean = false)
public void setOnPasteHandling(final ReactAztecText view, boolean onPasteHandling) {
view.shouldHandleOnPaste = onPasteHandling;
}

@Override
public Map<String, Integer> getCommandsMap() {
return MapBuilder.<String, Integer>builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package org.wordpress.mobile.ReactNativeAztec;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.Event;
import com.facebook.react.uimanager.events.RCTEventEmitter;

/**
* Event emitted by Aztec native view when paste is detected.
*/
class ReactAztecPasteEvent extends Event<ReactAztecPasteEvent> {

private static final String EVENT_NAME = "topTextInputPaste";

private String mCurrentContent;
private int mSelectionStart;
private int mSelectionEnd;
private String mPastedText;
private String mPastedHtml;

public ReactAztecPasteEvent(int viewId, String currentContent, int selectionStart,
int selectionEnd, String pastedText, String pastedHtml) {
super(viewId);
mCurrentContent = currentContent;
mSelectionStart = selectionStart;
mSelectionEnd = selectionEnd;
mPastedText = pastedText;
mPastedHtml = pastedHtml;
}

@Override
public String getEventName() {
return EVENT_NAME;
}

@Override
public boolean canCoalesce() {
return false;
}

@Override
public void dispatch(RCTEventEmitter rctEventEmitter) {
rctEventEmitter.receiveEvent(getViewTag(), getEventName(), serializeEventData());
}

private WritableMap serializeEventData() {
WritableMap eventData = Arguments.createMap();
eventData.putInt("target", getViewTag());
eventData.putString("currentContent", mCurrentContent);
eventData.putInt("selectionStart", mSelectionStart);
eventData.putInt("selectionEnd", mSelectionEnd);
eventData.putString("pastedText", mPastedText);
eventData.putString("pastedHtml", mPastedHtml);
return eventData;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.wordpress.mobile.ReactNativeAztec;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.Nullable;
Expand Down Expand Up @@ -31,6 +33,8 @@
import java.util.Map;
import java.util.HashMap;

import static android.content.ClipData.*;

public class ReactAztecText extends AztecText {

private final InputMethodManager mInputMethodManager;
Expand All @@ -53,6 +57,7 @@ public class ReactAztecText extends AztecText {
String lastSentFormattingOptionsEventString = "";
boolean shouldHandleOnEnter = false;
boolean shouldHandleOnBackspace = false;
boolean shouldHandleOnPaste = false;
boolean shouldHandleOnSelectionChange = false;
boolean shouldHandleActiveFormatsChange = false;

Expand Down Expand Up @@ -115,6 +120,20 @@ void addPlugin(IAztecPlugin plugin) {
}
}

@Override
public boolean onTextContextMenuItem(int id) {
if (shouldHandleOnPaste) {
switch (id) {
case android.R.id.paste:
return onPaste(false);
case android.R.id.pasteAsPlainText:
return onPaste(true);
}
}

return super.onTextContextMenuItem(id);
}

// VisibleForTesting from {@link TextInputEventsTestCase}.
public void requestFocusFromJS() {
mIsJSSettingFocus = true;
Expand Down Expand Up @@ -336,6 +355,50 @@ private boolean onBackspace() {
return true;
}

/**
* Handle paste action by retrieving clipboard contents and dispatching a
* {@link ReactAztecPasteEvent} with the data
*
* @param isPastedAsPlainText boolean indicating whether the paste action chosen was
* "PASTE AS PLAIN TEXT"
*
* @return boolean to indicate that the action was handled (always true)
*/
private boolean onPaste(boolean isPastedAsPlainText) {
ClipboardManager clipboardManager = (ClipboardManager) getContext().getSystemService(
Context.CLIPBOARD_SERVICE);

StringBuilder text = new StringBuilder();
StringBuilder html = new StringBuilder();

if (clipboardManager != null && clipboardManager.hasPrimaryClip()) {
ClipData clipData = clipboardManager.getPrimaryClip();
int itemCount = clipData.getItemCount();

for (int i = 0; i < itemCount; i++) {
Item item = clipData.getItemAt(i);
text.append(item.coerceToText(getContext()));
if (!isPastedAsPlainText) {
html.append(item.coerceToHtmlText(getContext()));
}
}
}

// temporarily disable listener during call to toHtml()
disableTextChangedListener();
String content = toHtml(false);
int cursorPositionStart = getSelectionStart();
int cursorPositionEnd = getSelectionEnd();
enableTextChangedListener();
ReactContext reactContext = (ReactContext) getContext();
EventDispatcher eventDispatcher = reactContext.getNativeModule(UIManagerModule.class)
.getEventDispatcher();
eventDispatcher.dispatchEvent(new ReactAztecPasteEvent(getId(), content,
cursorPositionStart, cursorPositionEnd, text.toString(), html.toString())
mkevins marked this conversation as resolved.
Show resolved Hide resolved
);
return true;
}

public void setActiveFormats(Iterable<String> newFormats) {
Set<ITextFormat> selectedStylesSet = new HashSet<>(getSelectedStyles());
Set<ITextFormat> newFormatsSet = new HashSet<>();
Expand Down
3 changes: 3 additions & 0 deletions src/globals.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import { createElement } from '@wordpress/element';
import jsdom from 'jsdom-jscore';
import jsdomLevel1Core from 'jsdom-jscore/lib/jsdom/level1/core';

// Import for side-effects: Patches for jsdom-jscore, details commented in file.
import './jsdom-patches';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, this seems rather important since we're touching how jsdom-jscore is working. I'm sure we need the patches so, can you add some comments in the code on what do we need the patches for? Thanks!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea, I'll add some more comments to this to clarify.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @mkevins ! Can we expand on the reason(s) we replace each of the function prototypes? That insight will help anyone reading the code to understand why do we even replace these function.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added PR #826 to address this.


global.wp = {
element: {
createElement, // load the element creation function, needed by Gutenberg-web
Expand Down
123 changes: 123 additions & 0 deletions src/jsdom-patches.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/** @flow
* @format */

/**
* This file is used in src/globals.js to patch jsdom-jscore.
*
* Node.prototype.contains is implemented as a simple recursive function.
*
* Node.prototype.insertBefore is re-implemented (code copied) with the
* WrongDocumentError exception disabled.
*
* Element.prototype.matches is aliased to Element.prototype.matchesSelector.
*/

/**
* External dependencies
*/
import jsdom from 'jsdom-jscore';
import jsdomLevel1Core from 'jsdom-jscore/lib/jsdom/level1/core';

// must be called to initialize jsdom before patching prototypes
jsdom.html( '', null, null );

const { core } = jsdomLevel1Core.dom.level1;
const { Node, Element } = core;

// Exception codes
const {
NO_MODIFICATION_ALLOWED_ERR,
HIERARCHY_REQUEST_ERR,
NOT_FOUND_ERR,
} = core;

// Node types
const {
ATTRIBUTE_NODE,
DOCUMENT_FRAGMENT_NODE,
} = Node;

// Simple recursive implementation of Node.contains method
Node.prototype.contains = function( otherNode ) {
return this === otherNode ||
Array.prototype.some.call( this._childNodes, ( childNode ) => {
return childNode.contains( otherNode );
} );
};

// copied from jsdom-jscore, but without WRONG_DOCUMENT_ERR exception
Node.prototype.insertBefore = function( /* Node */ newChild, /* Node*/ refChild ) {
if ( this._readonly === true ) {
throw new core.DOMException( NO_MODIFICATION_ALLOWED_ERR, 'Attempting to modify a read-only node' );
}

// Adopt unowned children, for weird nodes like DocumentType
if ( ! newChild._ownerDocument ) {
newChild._ownerDocument = this._ownerDocument;
}

/*
* This is commented out to prevent WrongDocumentError
* see: https://github.com/jsdom/jsdom/issues/717
*
// TODO - if (!newChild) then?
if (newChild._ownerDocument !== this._ownerDocument) {
throw new core.DOMException(WRONG_DOCUMENT_ERR);
}
*/

if ( newChild.nodeType && newChild.nodeType === ATTRIBUTE_NODE ) {
throw new core.DOMException( HIERARCHY_REQUEST_ERR );
}

// search for parents matching the newChild
let current = this;
do {
if ( current === newChild ) {
throw new core.DOMException( HIERARCHY_REQUEST_ERR );
}
} while ( ( current = current._parentNode ) );

// fragments are merged into the element
if ( newChild.nodeType === DOCUMENT_FRAGMENT_NODE ) {
let tmpNode,
i = newChild._childNodes.length;
while ( i-- > 0 ) {
tmpNode = newChild.removeChild( newChild.firstChild );
this.insertBefore( tmpNode, refChild );
}
} else if ( newChild === refChild ) {
return newChild;
} else {
// if the newChild is already in the tree elsewhere, remove it first
if ( newChild._parentNode ) {
newChild._parentNode.removeChild( newChild );
}

if ( refChild === null ) {
// eslint-disable-next-line no-var
var refChildIndex = this._childNodes.length;
} else {
// eslint-disable-next-line no-redeclare, no-var
var refChildIndex = this._indexOf( refChild );
if ( refChildIndex === -1 ) {
throw new core.DOMException( NOT_FOUND_ERR );
}
}

Array.prototype.splice.call( this._childNodes, refChildIndex, 0, newChild );

newChild._parentNode = this;
if ( this._attached && newChild._attach ) {
newChild._attach();
}

this._modified();
}

return newChild;
}; // raises(DOMException);

// alias (polyfill not needed)
// see: https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill
Element.prototype.matches = Element.prototype.matchesSelector;
1 change: 1 addition & 0 deletions symlinked-packages/@wordpress/dom
1 change: 1 addition & 0 deletions symlinked-packages/@wordpress/shortcode
7 changes: 7 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -8217,6 +8217,13 @@ shortid@^2.2.6:
dependencies:
nanoid "^2.0.0"

showdown@^1.8.6:
version "1.9.0"
resolved "https://registry.yarnpkg.com/showdown/-/showdown-1.9.0.tgz#d49d2a0b6db21b7c2e96ef855f7b3b2a28ef46f4"
integrity sha512-x7xDCRIaOlicbC57nMhGfKamu+ghwsdVkHMttyn+DelwzuHOx4OHCVL/UW/2QOLH7BxfCcCCVVUix3boKXJKXQ==
dependencies:
yargs "^10.0.3"

sigmund@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/sigmund/-/sigmund-1.0.1.tgz#3ff21f198cad2175f9f3b781853fd94d0d19b590"
Expand Down