mirror of
https://github.com/webodf/WebODF.git
synced 2026-12-01 16:56:05 +01:00
Merge pull request #169 from peitschie/insert-fragment
Add support for pasting plain text with line breaks
This commit is contained in:
@@ -322,6 +322,7 @@ set(LIBJSFILES lib/packages.js lib/runtime.js lib/core/Base64.js
|
||||
lib/gui/ShadowCursor.js
|
||||
lib/gui/Avatar.js
|
||||
lib/gui/Caret.js
|
||||
lib/gui/PlainTextPasteboard.js
|
||||
lib/gui/Clipboard.js
|
||||
lib/gui/DirectTextStyler.js
|
||||
lib/gui/DirectParagraphStyler.js
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
Clipboard behaviour and support
|
||||
==================================
|
||||
|
||||
Overview
|
||||
--------
|
||||
Clipboard implementations and availability are extremely different between browsers and versions of various browsers.
|
||||
This makes it challenging to access data, or add extra data on a cut/copy or paste event.
|
||||
|
||||
The high level goal is for webodf to support internal copying and pasting, as well as allow the ability to paste from
|
||||
external sources such as other browser tabs or documents. Ideally support will match the copy/paste experience that
|
||||
googledocs is able to provide.
|
||||
|
||||
Technical challenges
|
||||
--------------------
|
||||
1. Read/write clipboard access
|
||||
Only webkit-based or blink JS engines (Chrome, Safari, Opera, etc.) and very recent version of Firefox (22, July 2013 [4])
|
||||
provide full read-write access to the browser's clipboard. Internet Explorer provides some simplistic access[3]. Older
|
||||
versions of Firefox provide practically no direct access to the clipboard content (read or write).
|
||||
|
||||
Firefox has recently improved clipboard support enormously though, so this situation is slowly improving.
|
||||
|
||||
2. Browser events
|
||||
For security reasons, access to the browser's clipboard is only allowed during a cut, copy or paste event [1].
|
||||
Though the w3 specs require that implementations always allow these events to be fired on any element in a page (even
|
||||
if it will have no impact on the document)[2], the only browser that properly does this is Chrome.
|
||||
|
||||
Safari & firefox will only allow a cut or paste event if the current focus node is an editable area such as a text field
|
||||
or a contentEditable div.
|
||||
|
||||
3. Styling support
|
||||
Browsers have different levels of support for including style-related information for the copied text selection.
|
||||
Firefox includes some font size information, HTML attributes (id., class) the fragment DOM structure, but no other style
|
||||
information. This means that coloured text copied in Firefox will always paste in the current font colour of the paste
|
||||
location (e.g., black if that is the colour of the destination text).
|
||||
|
||||
Chrome includes ALL style information as if it were inline css on each individual element, as well
|
||||
as HTML attributes and the fragment DOM structure in a text/html data blob on the clipboard. When pasted, all direct
|
||||
formatting is preserved and displayed.
|
||||
|
||||
Safari only adds the plain text to the clipboard, meaning that the only way to access the complex HTML is to allow
|
||||
the paste to occur in a contentEditable div, and then extract the resulting HTML (e.g., using setTimeout [5]).
|
||||
|
||||
4. Image support
|
||||
Generally, images are not copied directly to the clipboard alongside the relevant DOM fragments. This means that on paste,
|
||||
the receiving application must go and download the image from the remote URL.
|
||||
|
||||
The behaviour is also inconsistent when copying a standalone image. For example, viewing an image (e.g.,
|
||||
http://www.w3.org/Icons/w3c_home) and right-click + copying this in Chrome results in the png itself being placed on the
|
||||
clipboard as an item. In firefox, this still pastes as a normal HTML fragment with a link to the original URL.
|
||||
|
||||
Safari will place the image on the clipboard, and will additionally add a plain-text entry with the original URL
|
||||
(which means that the default paste action in most other applications is to paste the plain text rather than the image!).
|
||||
|
||||
5. All or nothing clipboard write access
|
||||
The default action for a cut or copy event *must* be prevented in order for anything added to the clipboard using setData
|
||||
to remain available [6]. This is because the handler is called before the browser has populated the clipboard, and the
|
||||
browser then subsequently overwrites the clipboard with the current selection.
|
||||
|
||||
What this means is that if a web-app wants to add additional meta-data to the clipboard (e.g., a webodf/fragment data
|
||||
type), it also becomes responsible for populating text/plain & text/html with the correct data as well. This task is quite
|
||||
difficult to do correctly as there is no way provided to access the browser's default implementation (e.g., Chrome's
|
||||
which does things such as inlining css information).
|
||||
|
||||
6. Inter-browser clipboard types
|
||||
Custom data types are generally not preserved when pasting between browsers.
|
||||
|
||||
For example, copying a block of text in googledocs in Chrome and pasting in the clipboard test harness shows a type
|
||||
'application/x-vnd.google-docs-document-slice+wrapped' entry as present. If this is then pasted in Safari, an entry for
|
||||
'org.chromium.web-custom-data' is shown instead. If pasted into firefox, only text/plain &
|
||||
text/html entries exist.
|
||||
|
||||
Googledocs Clipboard implementation
|
||||
-----------------------------------
|
||||
Googledocs has good cross-browser (and version) clipboard support. This is achieved using the following techniques
|
||||
|
||||
1. Virtual cursors - workaround for technical challenge #2
|
||||
As mentioned previously, most browsers only allow limited access to the cut, copy & paste commands.
|
||||
The displayed caret on screen, and associated selection rectangles are NOT the browser caret or selection. These are
|
||||
actually cleverly placed divs and highlights. Viewing the page source, it can be observed that there is a hidden
|
||||
contentEditable div or iframe (class=docs-texteventtarget-iframe) that is the window's current selection and active element
|
||||
(window.getSelection() && document.activeElement) at all times. This means the cut, copy & paste events can be selectively
|
||||
enabled by adding or removing content from the hidden div.
|
||||
|
||||
2. Web Pasteboard
|
||||
One of the most common uses for cut/copy/paste is actually copying or moving data within an open document, or multiple
|
||||
open documents. To improve the user experience in this area, google implemented a whole new clipboard system called a
|
||||
web paste board (see links below). This greatly simplifies the problem of copy & paste within a document, as data can
|
||||
now be added alongside the clipboard selection data without needing to clear & regenerate all the clipboard data.
|
||||
|
||||
This would allow googledocs to function without access to the browser clipboard at all when copying and pasting
|
||||
between internal documents.
|
||||
|
||||
3. Custom HTML serializer - workaround for technical challenges #3, #4 & #6
|
||||
Examining the content of the text/html data type when copying from a googledoc shows significant differences to Firefox's
|
||||
normal generated HTML. This indicates that google has written a custom JS HTML serializer that creates rendered HTML
|
||||
based on the current selection in the document. No copy of this exist in the viewed page, so it is clearly generated
|
||||
on-the-fly when a cut/copy event is invoked.
|
||||
|
||||
Due to technical challenge #5, this also indicates that a custom serializer is also implemented to generate the
|
||||
text/plain clipboard data.
|
||||
|
||||
To provide good cut & copy support on earlier versions of FF, when a cut or copy operation is received the current
|
||||
selection is shadowed into the hidden contentEditable div using the custom serializer. At the completion of the event, the
|
||||
div is immediately cleared again. This allows the clipboard to receive the sanitized HTML equivalent of the current
|
||||
selection, in spite of there being no direct clipboard interface.
|
||||
|
||||
* http://googledocs.blogspot.com.au/2010/02/web-clipboard-for-google-docs.html
|
||||
* http://googleappsupdates.blogspot.com.au/2010/02/new-web-clipboard-for-google-docs-that.html
|
||||
* https://support.google.com/drive/answer/161768?hl=en
|
||||
* http://googlesystem.blogspot.com.au/2012/03/google-docs-and-clipboard-access.html
|
||||
|
||||
|
||||
Footnotes
|
||||
---------
|
||||
[1] http://www.w3.org/TR/clipboard-apis
|
||||
[2] http://www.w3.org/TR/clipboard-apis, 4.1.2, paragraph 2
|
||||
[3] http://msdn.microsoft.com/en-us/library/ms535220%28v=vs.85%29.aspx
|
||||
[4] https://bugzilla.mozilla.org/show_bug.cgi?id=407983
|
||||
[5] http://stackoverflow.com/questions/2176861/javascript-get-clipboard-data-on-paste-event-cross-browser
|
||||
[6] http://www.w3.org/TR/clipboard-apis, 4.1.2, paragraph 4
|
||||
@@ -0,0 +1,85 @@
|
||||
Copy & paste behaviour and support
|
||||
==================================
|
||||
|
||||
Overview
|
||||
--------
|
||||
Paste support is extremely important to get right for an editor. Users have an expectation that data can be replicated
|
||||
with a high degree of accuracy when copied and pasted. This includes things such as pasting images, styled text (e.g.,
|
||||
bold, underline), paragraph breaks, lists etc.
|
||||
|
||||
This README does not cover details about how data is written or retrieved from the clipboard. For that information, please
|
||||
see README_clipboard.txt.
|
||||
|
||||
Desired paste support
|
||||
---------------------
|
||||
* Plain text with paragraphs, tabs, spaces
|
||||
* HTML text with direct formatting
|
||||
* HTML tables
|
||||
* HTML table rows & columns
|
||||
* Images (standalone)
|
||||
* Images within mixed HTML fragments (e.g., HTML fragment with paragraphs & images etc.)
|
||||
* Lists (bulleted & numbered)
|
||||
|
||||
Requirements
|
||||
------------
|
||||
1. Paste should be able to be undone/redone safely
|
||||
2. Extra "formatting" steps should be able to be undone without removing the pasted content. E.g., automatically converting
|
||||
to a list or table (optional advanced feature)
|
||||
3. Want to avoid duplicating logic in other operations (e.g., paragraph splitting & merging behaviours, image insertion,
|
||||
style addition, adding new list items etc.)
|
||||
4. Any new operations must be able to be OT'ed easily
|
||||
|
||||
Design
|
||||
------
|
||||
There are effectively two opposing approaches that can be taken to handle pasting of new data:
|
||||
1. Create a complex operation (e.g., OpPasteData) that is responsible for determining how to insert a fragment into the
|
||||
document
|
||||
2. Create a paste handler that attempts to break the paste fragment into a series of smaller operations
|
||||
|
||||
Option 1
|
||||
- Pro: Easily integrates with existing undo/redo manager
|
||||
- Con: OpPasteData likely to contain a lot of duplication of existing ops however
|
||||
- Pro: Less operations generated (less on-the-wire traffic)
|
||||
|
||||
Option 2
|
||||
- Pro: Better re-use of existing operations
|
||||
- Pro: Less complex operations required
|
||||
- Con: Need significant re-work of undo operation grouping to allow paste to be undone/redone
|
||||
|
||||
OT adaption of a paste command is relatively straightforward for both options, as both largely generate insert-only
|
||||
operations. This means that usually the start position just needs to be shifted around to cope with added or removed
|
||||
characters.
|
||||
|
||||
Based on the pro's and con's, Option 2 is the best approach for paste handling. The key argument for this is that it makes
|
||||
better use of existing operations (requirement#3). The existing undo manager grouping logic is not very extensible, and
|
||||
should be reworked anyways.
|
||||
|
||||
Example paste steps
|
||||
-------------------
|
||||
1. Extract data from clipboard. Order of preference is
|
||||
- Custom webodf fragment ("application/vnd.webodf")
|
||||
- LO/MSWord fragment (??)
|
||||
- RTF fragment (??)
|
||||
- HTML ("text/html")
|
||||
- Plain text ("text/plain")
|
||||
2. Convert data into webodf fragment (and associated styles) using appropriate import filter
|
||||
3. Split the fragment up into separate paragraphs
|
||||
4. Start a new transaction/undo group (this is a new feature...)
|
||||
5. Add any new named styles (Op???)
|
||||
6. Add any new auto styles (Op???)
|
||||
7. For each paragraph
|
||||
- start a new paragraph at the current position (OpSplitParagraph)
|
||||
- insert the new paragraph (OpInsertFragment)
|
||||
8. After all paragraphs have been inserted, remove the FIRST created split to merge the first inserted paragraph with
|
||||
it's previous sibling (allows the paragraphs to merge with the correct paragraph merge logic)
|
||||
9. Finish transaction/undo group (Actually, this probably happens on the next edit op start)
|
||||
10. Auto-convert things to lists, links, etc. (optional). This should be in a new transaction/undo group
|
||||
|
||||
Questions
|
||||
---------
|
||||
* Should pasting multiple paragraphs into a list should result in a new list item per paragraph?
|
||||
* Should links be automatically converted?
|
||||
|
||||
Links of interest
|
||||
-----------------
|
||||
* https://trac.webkit.org/browser/trunk/Source/WebCore/editing/SimplifyMarkupCommand.cpp
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright (C) 2013 KO GmbH <copyright@kogmbh.com>
|
||||
*
|
||||
* @licstart
|
||||
* The JavaScript code in this page is free software: you can redistribute it
|
||||
* and/or modify it under the terms of the GNU Affero General Public License
|
||||
* (GNU AGPL) as published by the Free Software Foundation, either version 3 of
|
||||
* the License, or (at your option) any later version. The code is distributed
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU AGPL for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this code. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
* As additional permission under GNU AGPL version 3 section 7, you
|
||||
* may distribute non-source (e.g., minimized or compacted) forms of
|
||||
* that code without the copy of the GNU GPL normally required by
|
||||
* section 4, provided you include this license notice and a URL
|
||||
* through which recipients can access the Corresponding Source.
|
||||
*
|
||||
* As a special exception to the AGPL, any HTML file which merely makes function
|
||||
* calls to this code, and for that purpose includes it by reference shall be
|
||||
* deemed a separate work for copyright law purposes. In addition, the copyright
|
||||
* holders of this code give you permission to combine this code with free
|
||||
* software libraries that are released under the GNU LGPL. You may copy and
|
||||
* distribute such a system following the terms of the GNU AGPL for this code
|
||||
* and the LGPL for the libraries. If you modify this code, you may extend this
|
||||
* exception to your version of the code, but you are not obligated to do so.
|
||||
* If you do not wish to do so, delete this exception statement from your
|
||||
* version.
|
||||
*
|
||||
* This license applies to this entire compilation.
|
||||
* @licend
|
||||
* @source: http://www.webodf.org/
|
||||
* @source: https://github.com/kogmbh/WebODF/
|
||||
*/
|
||||
|
||||
/*global runtime, gui, ops*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {!ops.OdtDocument} odtDocument
|
||||
* @param {!string} inputMemberId
|
||||
* @constructor
|
||||
*/
|
||||
gui.PlainTextPasteboard = function PlainTextPasteboard(odtDocument, inputMemberId) {
|
||||
"use strict";
|
||||
|
||||
function createOp(op, data) {
|
||||
op.init(data);
|
||||
return op;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {!string} data
|
||||
* @return {!Array.<!ops.Operation>}
|
||||
*/
|
||||
this.createPasteOps = function(data) {
|
||||
var originalCursorPosition = odtDocument.getCursorPosition(inputMemberId),
|
||||
cursorPosition = originalCursorPosition,
|
||||
operations = [],
|
||||
paragraphs;
|
||||
|
||||
paragraphs = data.replace(/\\r/g, "").split("\n");
|
||||
paragraphs.forEach(function(text) {
|
||||
operations.push(createOp(new ops.OpSplitParagraph(), {
|
||||
memberid: inputMemberId,
|
||||
position: cursorPosition
|
||||
}));
|
||||
cursorPosition += 1; // Splitting a paragraph introduces 1 walkable position, bumping the cursor forward
|
||||
operations.push(createOp(new ops.OpInsertText(), {
|
||||
memberid: inputMemberId,
|
||||
position: cursorPosition,
|
||||
text: text
|
||||
}));
|
||||
cursorPosition += text.length;
|
||||
});
|
||||
|
||||
// Merge the first element back into the first paragraph
|
||||
operations.push(createOp(new ops.OpRemoveText(), {
|
||||
memberid: inputMemberId,
|
||||
position: originalCursorPosition,
|
||||
length: 1
|
||||
}));
|
||||
|
||||
return operations;
|
||||
};
|
||||
};
|
||||
@@ -54,6 +54,7 @@ runtime.loadClass("gui.ImageSelector");
|
||||
runtime.loadClass("gui.TextManipulator");
|
||||
runtime.loadClass("gui.AnnotationManager");
|
||||
runtime.loadClass("gui.EventManager");
|
||||
runtime.loadClass("gui.PlainTextPasteboard");
|
||||
|
||||
/**
|
||||
* @constructor
|
||||
@@ -101,7 +102,8 @@ gui.SessionController = (function () {
|
||||
imageManager = new gui.ImageManager(session, inputMemberId, objectNameGenerator),
|
||||
imageSelector = new gui.ImageSelector(odtDocument.getOdfCanvas()),
|
||||
shadowCursorIterator = gui.SelectionMover.createPositionIterator(odtDocument.getRootNode()),
|
||||
drawShadowCursorTask;
|
||||
drawShadowCursorTask,
|
||||
pasteHandler = new gui.PlainTextPasteboard(odtDocument, inputMemberId);
|
||||
|
||||
runtime.assert(window !== null,
|
||||
"Expected to be run in an environment which has a global window, like a browser.");
|
||||
@@ -788,7 +790,8 @@ gui.SessionController = (function () {
|
||||
}
|
||||
|
||||
if (plainText) {
|
||||
textManipulator.insertText(plainText);
|
||||
textManipulator.removeCurrentSelection();
|
||||
session.enqueue(pasteHandler.createPasteOps(plainText));
|
||||
cancelEvent(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@
|
||||
"gui/AnnotationViewManager.js",
|
||||
"gui/Avatar.js",
|
||||
"gui/Caret.js",
|
||||
"gui/PlainTextPasteboard.js",
|
||||
"gui/Clipboard.js",
|
||||
"gui/DirectTextStyler.js",
|
||||
"gui/DirectParagraphStyler.js",
|
||||
|
||||
@@ -88,9 +88,18 @@ odf.TextSerializer = function TextSerializer() {
|
||||
* @return {!string}
|
||||
*/
|
||||
this.writeToString = function (node) {
|
||||
var plainText;
|
||||
if (!node) {
|
||||
return "";
|
||||
}
|
||||
return serializeNode(node);
|
||||
plainText = serializeNode(node);
|
||||
if (plainText[plainText.length - 1] === "\n") {
|
||||
// By the serializing logic, the selection <p>text</p> would generate "text\n"
|
||||
// This is slightly unexpected though, as partially selecting two paragraphs (<p>p1</p><p>p2</p>)
|
||||
// the user would expect the text to be "p1\np2"
|
||||
// Easiest way to meet this expectation is to throw away the last new line (if present)
|
||||
plainText = plainText.substr(0, plainText.length - 1);
|
||||
}
|
||||
return plainText;
|
||||
};
|
||||
};
|
||||
@@ -20,8 +20,9 @@
|
||||
var logNode;
|
||||
|
||||
function dumpTypes(clipboard) {
|
||||
var typesTable = $("<table/>");
|
||||
clipboard.types.forEach(function(type) {
|
||||
var i, typesTable = $("<table/>");
|
||||
|
||||
function addType(type) {
|
||||
var row = $("<tr/>"),
|
||||
nameCell = $("<td/>"),
|
||||
valueCell = $("<td/>");
|
||||
@@ -32,7 +33,11 @@
|
||||
row.append(nameCell);
|
||||
row.append(valueCell);
|
||||
typesTable.append(row);
|
||||
});
|
||||
}
|
||||
|
||||
for(i = 0; i < clipboard.types.length; i++) {
|
||||
addType(clipboard.types[i]);
|
||||
}
|
||||
return typesTable;
|
||||
}
|
||||
|
||||
@@ -91,16 +96,41 @@
|
||||
};
|
||||
}
|
||||
|
||||
function onCopy(e) {
|
||||
recordEvent("copy", e);
|
||||
if (e.clipboardData) {
|
||||
log("adding custom data: " + e.clipboardData.setData('custom/data', 'Copy - clipboard.html ' + new Date()));
|
||||
}
|
||||
}
|
||||
|
||||
function onCut(e) {
|
||||
recordEvent("cut", e);
|
||||
if (e.clipboardData) {
|
||||
log("adding custom data: " + e.clipboardData.setData('custom/data', 'Cut - clipboard.html ' + new Date()));
|
||||
}
|
||||
}
|
||||
|
||||
function onPaste(e) {
|
||||
var clipboardTable = $("#clipboardData"),
|
||||
keys = ["types", "files", "items"],
|
||||
capturedRow = $("<tr/>"),
|
||||
capturedName = $("<td/>"),
|
||||
capturedHtml = $("<td/>");
|
||||
|
||||
clipboardTable.empty();
|
||||
log("paste");
|
||||
recordEvent("paste", e);
|
||||
if (e.clipboardData) {
|
||||
Object.keys(e.clipboardData).forEach(function(key) {
|
||||
if (Object.keys(e.clipboardData).length > 0) {
|
||||
keys = Object.keys(e.clipboardData);
|
||||
} else {
|
||||
// We only want properties on the clipboard such as types or files.
|
||||
// FF does not report these in the keys array however (potentially they are
|
||||
// specified higher up the prototype).
|
||||
// In this case, see if any of the keys we *know* we want are available on
|
||||
// the clipboard object.
|
||||
keys = keys.filter(function(key) { return key in e.clipboardData; });
|
||||
}
|
||||
keys.forEach(function(key) {
|
||||
var row = $("<tr/>"),
|
||||
nameCell = $("<td/>"),
|
||||
valueCell = $("<td/>");
|
||||
@@ -135,13 +165,16 @@
|
||||
|
||||
$("#content").empty();
|
||||
setTimeout(captureHtml(capturedHtml), 500);
|
||||
// e.preventDefault();
|
||||
}
|
||||
|
||||
function recordEvent(name, e) {
|
||||
log(name + (e.clipboardData ? " (clipboardData accessible)" : ""));
|
||||
}
|
||||
|
||||
function record(msg, result) {
|
||||
return function(e) {
|
||||
e.preventDefault();
|
||||
log(msg);
|
||||
log(msg + (e.clipboardData ? " (clipboardData accessible)" : ""));
|
||||
return result;
|
||||
};
|
||||
}
|
||||
@@ -166,9 +199,9 @@
|
||||
$(function() {
|
||||
var content = $('body');
|
||||
logNode = $("#log");
|
||||
listenEvent(content[0], "cut", record("cut"));
|
||||
listenEvent(content[0], "cut", onCut);
|
||||
listenEvent(content[0], "beforecut", record("beforecut", false));
|
||||
listenEvent(content[0], "copy", record("copy"));
|
||||
listenEvent(content[0], "copy", onCopy);
|
||||
listenEvent(content[0], "beforecopy", record("beforecopy"));
|
||||
listenEvent(content[0], "paste", onPaste);
|
||||
listenEvent(content[0], "beforepaste", record("beforepaste", false));
|
||||
|
||||
@@ -77,6 +77,7 @@
|
||||
<script src="../lib/gui/Avatar.js" type="text/javascript" charset="utf-8"></script>
|
||||
<script src="../lib/gui/Caret.js" type="text/javascript" charset="utf-8"></script>
|
||||
<script src="../lib/gui/KeyboardHandler.js" type="text/javascript" charset="utf-8"></script>
|
||||
<script src="../lib/gui/PlainTextPasteboard.js" type="text/javascript" charset="utf-8"></script>
|
||||
<script src="../lib/gui/Clipboard.js" type="text/javascript" charset="utf-8"></script>
|
||||
<script src="../lib/gui/DirectTextStyler.js" type="text/javascript" charset="utf-8"></script>
|
||||
<script src="../lib/gui/DirectParagraphStyler.js" type="text/javascript" charset="utf-8"></script>
|
||||
|
||||
Reference in New Issue
Block a user