Paste as plain text Contenteditable div & textarea (word/excel...) - excel

I would like the to paste text in a contenteditable div, but reacting as a textarea.
Note that I want to keep the formatting as I would paste it in my textarea (from word, excel...).
So.
1) Paste text in contenteditable div
2) I get the text from clipboard
3) I push my value from clipboard to my textarea, (dont know how??)
4) Get value from my textarea and place it in my contenteditable div
Any suggestions?

I'm CKEditor's core developer and by coincidence for last 4 months I was working on clipboard support and related stuff :) Unfortunately I won't be able to describe you the entire way how pasting is handled, because the tales of the impl are too tricky for me even after writing impl by myself :D
However, here're some hints that may help you:
Don't write wysiwyg editor - use one that exists. It's going to consume all your time and still your editor will be buggy. We and guys from other... two main editors (guess why only three exist) are working on this for years and we still have full bugs lists ;).
If you really need to write your own editor check out http://dev.ckeditor.com/browser/CKEditor/trunk/_source/plugins/clipboard/plugin.js - it's the old impl, before I rewrote it, but it works everywhere where it's possible. The code is horrible... but it may help you.
You won't be possible to handle all browsers by just one event paste. To handle all ways of pasting we're using both - beforepaste and paste.
There's number (huge number :D) of browsers' quirks that you'll need to handle. I can't to describe you them, because even after few weeks I don't remember all of them. However, small excerpt from our docs may be useful for you:
Paste command (used by non-native paste - e.g. from our toolbar)
* fire 'paste' on editable ('beforepaste' for IE)
* !canceled && execCommand 'paste'
* !success && fire 'pasteDialog' on editor
Paste from native context menu & menubar
(Fx & Webkits are handled in 'paste' default listner.
Opera cannot be handled at all because it doesn't fire any events
Special treatment is needed for IE, for which is this part of doc)
* listen 'onpaste'
* cancel native event
* fire 'beforePaste' on editor
* !canceled && getClipboardDataByPastebin
* execIECommand( 'paste' ) -> this fires another 'paste' event, so cancel it
* fire 'paste' on editor
* !canceled && fire 'afterPaste' on editor
The rest of the trick - On IEs we listen for both paste events, on the rest only for paste. We need to prevent some events on IE, because since we're listening for both sometimes this may cause doubled handling. This is the trickiest part I guess.
Note that I want to keep the formatting as I would paste it in my textarea (from word, excel...).
Which parts of formatting do you want to keep? Textarea will keep only basic ones - blocks formatting.
See http://dev.ckeditor.com/browser/CKEditor/trunk/_source/plugins/wysiwygarea/plugin.js#L120 up to line 123 - this is the last part of the task - inserting content into selection.

Current solution works perfect in IE/SAF/FF
But still i need a fix for "non" keyboard events, when pasting with mouse click...
Current solution for keyboard "paste" events:
$(document).ready(function() {
bind_paste_textarea();
});
function bind_paste_textarea(){
var activeOnPaste = null;
$("#mypastediv").keydown(function(e){
var code = e.which || e.keyCode;
if((code == 86)){
activeOnPaste = $(this);
$("#mytextarea").val("").focus();
}
});
$("#mytextarea").keyup(function(){
if(activeOnPaste != null){
$(activeOnPaste).focus();
activeOnPaste = null;
}
});
}
<h2>DIV</h2>
<div id="mypastediv" contenteditable="true" style="width: 400px; height: 400px; border: 1px solid orange;">
</div>
<h2>TEXTAREA</h2>
<textarea id="mytextarea" style="width: 400px; height: 400px; border: 1px solid red;"></textarea>

I have achieved this using rangy library to save and restore selections.
I also perform some other work using the library in the same functions, which I have stripped out of this example, so this is not optimal code.
HTML
<div><div id="editor"contenteditable="true" type="text"></div><div>
Javascript
var inputArea = $element.find('#editor');
var debounceInterval = 200;
function highlightExcessCharacters() {
// Bookmark selection so we can restore it later
var sel = rangy.getSelection();
var savedSel = sel.saveCharacterRanges(editor);
// Strip HTML
// Prevent images etc being pasted into textbox
inputArea.text(inputArea[0].innerText);
// Restore the selection
sel.restoreCharacterRanges(editor, savedSel);
}
// Event to handle checking of text changes
var handleEditorChangeEvent = (function () {
var timer;
// Function to run after timer passed
function debouncer() {
if (timer) {
timer = null;
}
highlightExcessCharacters();
}
return function () {
if (timer) {
$timeout.cancel(timer);
}
// Pass the text area we want monitored for exess characters into debouncer here
timer = $timeout(debouncer, debounceInterval);
};
})();
function listen(target, eventName, listener) {
if (target.addEventListener) {
target.addEventListener(eventName, listener, false);
} else if (target.attachEvent) {
target.attachEvent("on" + eventName, listener);
}
}
// Start up library which allows saving of text selections
// This is useful for when you are doing anything that might destroy the original selection
rangy.init();
var editor = inputArea[0];
// Set up debounced event handlers
var editEvents = ["input", "keydown", "keypress", "keyup", "cut", "copy", "paste"];
for (var i = 0, eventName; eventName = editEvents[i++];) {
listen(editor, eventName, handleEditorChangeEvent);
}

Related

CKEditor 4 : how to apply via API a style to current text

I am fighting with CKEditor in order that after CKEditor is loaded with a content and without selecting any style from toolbar, the changes (new text) made from an user, are automatically set in bold (no toolbar needed for the user).
I tried executing a command on the "click" event setting the bold style but it does not work very well
myEditor.on("instanceReady", function() {
var editable = myEditor.editable();
editable.attachListener( editable, 'click', function() {
myEditor.commands.bold.exec();
});
});
so I changed inserting element with bold style on click event
myEditor.on("instanceReady", function() {
var editable = myEditor.editable();
editable.attachListener( editable, 'click', function() {
var parent = myEditor.getSelection().getStartElement()
//simplified code without check if span already exist
myEditor.insertHtml('<span class="boldStyle">');
myEditor.insertHtml('</span>');
});
});
This works a bit better but I wonder if this approach is a good idea or how I could do better
Thanks

Focus, blur, focusin, focusout, don't work with D3 and SVG Elements? Is there an alternative?

I'm using the d3 library to create a widget within a SVG. Within the SVG I'm trying to do the following:
There are small rectangles that are clickable. Once clickable, they should "enlarge" and show some input fields. When I click outside the rectangles I want them to "un-enlarge" and remove the input fields again.
Small rectangle:
Once clicked, they enlarge (no input fields yet):
When I click outside of the white rectangle, I want it to revert back to picture 1:
I trigger the enlargement with an on click event:
let whiteRect = node.append("g")
.on('click', function(a) {
// Trigger enlarge function
return a;
})};
And I would like to trigger the "click outside" using a blur or focusout event. But this doesn't seem to work for SVG. Something like this:
let whiteRect = node.append("g")
.on('blur', function(a) {
// Trigger "un-enlarge" function
return a;
})};
I've been doing some searching, and it seems that in SVG 2 this might be supported, but this doesn't seem to be implemented by any browsers.
Anyone have an idea how I could implement this? I know I can add an onclick event listener for the whole SVG and write some logic there to identify if I'm clicking on an enlarged rectangle. But I'd prefer using something easier like blur or focusout if possible. Any ideas?
Shortly after posting I found this tutorial on focusing svg elements: https://allyjs.io/tutorials/focusing-in-svg.html
Turns out if you add a focus event to an element it becomes focusable and also gets a blur event. So what I did was add an empty focus event to be able to use the blur.
let whiteRect = node.append("g")
.on('click', function(a) {
// Trigger enlarge function
return a;
})}
.on('focus', function(a) {
// Empty focus event
return a;
})}
.on('blur', function(a) {
// Trigger un-enlarge function
return a;
})};
Which worked for me.

how to make it in one line after onclick

I have a div in my html:
.row(id="div_amount")
.col-sm-2
label(for="amount") Amount:
.col-sm-1
input(type="text", name="amount")
which is perfect as I expected. It displays in one line for both elements.
I have a radio button which have an onclick event for toggle the display of this div section.
function div_toggle() {
div_amount = document.getElementById('div_amount');
if (radio_value === 0) {
div_amount.style.display = "block";
} else {
div_amount.style.display = "none";
}
}
However, after click on the radio button, it always displays as two lines.
How could I fix it to always display in one line?
Please take a look at https://stackoverflow.com/help/mcve and try to include a reproducible example.
In bootstrap4, rows are displayed as flex, i.e., "display: flex;". So in your JavaScript if you change it to display as block, the columns within the row would be broken.
You can set its display to flex, like
if (radio_value === 0) {
div_amount.style.display = "flex";
} else {
div_amount.style.display = "none";
}
although setting HTML element styles in JavaScript is considered as bad practice IMO.

How to use nightmare to press arrow key?

Is there any way to use nightmare (the nodeJS module) to press an arrow key? Either by sending the key to the specific element or by clicking on the element and sending the keypress to the page as a whole?
My problem is that there is a dropdown menu which, when clicked on, displays some options below it. These options do not appear to be clickable, I have tried click and even the realClick nightmare extension. Neither seem able of selecting any element of the dropdown. While playing around with the page, I found that by using the arrow keys and the enter key, I could select the options without clicking. So is there any way to send the keypress events to electron? Either through nightmare or by accessing electron directly?
It is called auto complete menu and there is no standard way of doing it.
I tried working with Google and came up with a method. I think, it will be tough to make generic solution, as it depends on how auto complete is implemented. Hope this helps!
var Nightmare = require('nightmare');
var nightmare = Nightmare({
show: true,
webPreferences: {}
})
nightmare
.goto('http://www.google.co.in')
.evaluate(function(searchTerm) {
var elem = document.querySelector('#lst-ib');
elem.value = searchTerm;
//Do mousedown to initiate auto complete window
var event = document.createEvent('MouseEvent');
event.initEvent('mousedown', true, true);
elem.dispatchEvent(event);
}, 'Leo')
.then(function() {
//Wait for results to appear
nightmare.wait(1000)
.evaluate(function() {
//Click the first option of List
var first = document.querySelector('#sbtc > div.gstl_0.sbdd_a > div:nth-child(2) > div.sbdd_b > div > ul > li:nth-child(1)');
first.firstElementChild.click();
}).then(function() {
console.log('All Done');
});
});

Allow only Copy/Paste Context Menu in System.Windows.Forms.WebBrowser Control

The WebBrowser control has a property called "IsWebBrowserContextMenuEnabled" that disables all ability to right-click on a web page and see a context menu. This is very close to what I want (I don't want anyone to be able to right-click and print, hit back, hit properties, view source, etc).
The only problem is this also disables the context menu that appears in TextBoxes for copy/paste, etc.
To make this clearer, this is what I don't want:
This is what I do want:
I would like to disable the main context menu, but allow the one that appears in TextBoxes. Anyone know how I would do that? The WebBrowser.Document.ContextMenuShowing event looks promising, but doesn't seem to properly identify the element the user is right-clicking on, either through the HtmlElementEventArgs parameter's "FromElement" and "ToElement" properties, nor is the sender anything but the HtmlDocument element.
Thanks in advance!
have you considered writing your own context menu in javascript? Just listen to the user right clicking on the body, then show your menu with copy and paste commands (hint: element.style.display = "block|none"). To copy, execute the following code:
CopiedTxt = document.selection.createRange();
CopiedTxt.execCommand("Copy");
And to paste:
CopiedTxt = document.selection.createRange();
CopiedTxt.execCommand("Paste");
Source:
http://www.geekpedia.com/tutorial126_Clipboard-cut-copy-and-paste-with-JavaScript.html
NOTE: This only works in IE (which is fine for your application).
I know its not bulletproof by any means, but here is a code sample that should get you started:
<html>
<head>
<script type = "text/javascript">
var lastForm = null;
window.onload = function(){
var menu = document.getElementById("ContextMenu");
var cpy = document.getElementById("CopyBtn");
var pst = document.getElementById("PasteBtn");
document.body.onmouseup = function(){
if (event.button == 2)
{
menu.style.left = event.clientX + "px";
menu.style.top = event.clientY + "px";
menu.style.display = "block";
return true;
}
menu.style.display = "none";
};
cpy.onclick = function(){
copy = document.selection.createRange();
copy.execCommand("Copy");
return false;
};
pst.onclick = function(){
if (lastForm)
{
copy = lastForm.createTextRange();
copy.execCommand("Paste");
}
return false;
};
};
</script>
</head>
<body oncontextmenu = "return false;">
<div id = "ContextMenu" style = "display : none; background: #fff; border: 1px solid #aaa; position: absolute;
width : 75px;">
Copy
Paste
</div>
sadgjghdskjghksghkds
<input type = "text" onfocus = "lastForm = this;" />
</body>
</html>
//Start:
function cutomizedcontextmenu(e)
{
var target = window.event ? window.event.srcElement : e ? e.target : null;
if( navigator.userAgent.toLowerCase().indexOf("msie") != -1 )
{
if (target.type != "text" && target.type != "textarea" && target.type != "password")
{
alert(message);
return false;
}
return true;
}
else if( navigator.product == "Gecko" )
{
alert(message);
return false;
}
}
document.oncontextmenu = cutomizedcontextmenu;
//End:
I hope this will help you Anderson Imes
A quick look at the MSDN documentation shows that none of the mouse events (click, button down/up etc) are supported to be used in your program. I'm afraid its either or: Either disable conetxt menus, or allow them.
If you disable them, the user can still copy & paste using keyboard shortcuts (Ctrl-C, Ctrl-V). Maybe that gives you the functionality you need.
We ended up using a combination of both of the above comments. Closer to the second, which is why I gave him credit.
There is a way to replace the context menu on both the client-side web code as well as through winforms, which is the approach we took. I really didn't want to rewrite the context menu, but this seems to have given us the right mix of control.

Resources