Unable to set cursor in Draft.js editor - draftjs

I am trying to integrate the Draft.js editor in a project.
The way I am thinking of using it, is to create a new EditorState out of my own state on every render call (the reason for this approach are related to my specific context I am not going to detail here).
What I have not succeeded is to set the cursor position in the Editor.
I have created an example on Codepen:
http://codepen.io/nutrina/pen/JKaaOo?editors=0011
In this example any character I type is prepended to the beginning of the text, instead of being inserted at the cursor position.
I have tried setting the cursor by using:
state = EditorState.acceptSelection(state, this.state.selectionState);
state = EditorState.forceSelection(state, this.state.selectionState);
but without much success.
Any help would be appreciated.
Thanks,
Gerald

A easy way to move the cursor around is to use Editor.forceSelection and a key binding function!
This is what your render function would look like once you have it set up
render() {
return (
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
handleKeyCommand={this.handleKeyCommand}
keyBindingFn={this.myKeyBindingFn}
/>
);
}
Once you have your keybinding function, you can do something along the lines of
myKeyBindingFn = (e) => {
// on spacebar
if (e.keyCode == 32) {
const newSelection = selectionState.merge({
anchorOffset: selectionState.getAnchorOffset() + 1,
focusOffset: selectionState.getAnchorOffset() + 1,
});
const newEditorState = EditorState.forceSelection(
editorState,
newSelection,
);
this.setState({ editorState: newEditorState });
return 'space-press';
}
};
Feel free to replace anchorOffset and focusOffset with the position you would like the cursor to be in. Using a keybinding function allows better control over events
Your handleKeyCommand function would look something like this
handleKeyCommand = (command: string): DraftHandleValue => {
if (command === 'space-press') {
return 'handled';
}
return 'not-handled';
};

Related

Is it possible to set TextDocument as dirty programatically in VSCode?

Is it possible to set a TextDocument as dirty programatically in VSCode? Something like
openedDocument.setDirty()
There isn't a direct way to do it; TextDocument.isDirty is a read-only property.
However, I put together a workaround that sets isDirty by making an edit that has no effect (tested with VSCode 1.37.1):
// Set the dirty bit on 'textEditor'. This is meant to be called as a
// text editor command.
async function setDirty(textEditor: TextEditor, editBuilder: TextEditorEdit)
: Promise<void>
{
// The strategy here is to make a change that has no effect. If the
// document has text in it, we can replace some text with itself
// (simply inserting an empty string does not work). We prefer to
// edit text at the end of the file in order to minimize spurious
// recomputation by analyzers.
// Try to replace the last line.
if (textEditor.document.lineCount >= 2) {
const lineNumber = textEditor.document.lineCount-2;
const lastLineRange = new Range(
new Position(lineNumber, 0),
new Position(lineNumber+1, 0));
const lastLineText = textEditor.document.getText(lastLineRange);
editBuilder.replace(lastLineRange, lastLineText);
return;
}
// Try to replace the first character.
const range = new Range(new Position(0, 0), new Position(0, 1));
const text = textEditor.document.getText(range);
if (text.length > 0) {
editBuilder.replace(range, text);
return;
}
// With an empty file, we first add a character and then remove it.
// This has to be done as two edits, which can cause the cursor to
// visibly move and then return, but we can at least combine them
// into a single undo step.
await textEditor.edit(
(innerEditBuilder: TextEditorEdit) => {
innerEditBuilder.replace(range, " ");
},
{ undoStopBefore: true, undoStopAfter: false });
await textEditor.edit(
(innerEditBuilder: TextEditorEdit) => {
innerEditBuilder.replace(range, "");
},
{ undoStopBefore: false, undoStopAfter: true });
}
In your activate function, hook it up with something like:
context.subscriptions.push(
commands.registerTextEditorCommand("extension.setDirty", setDirty));

Ace Editor Autocomplete - two steps autocomplete

I am trying to make Ace Editor support autocomplete for my own query language.
The query itself is something like below
city:newyork color:red color:blue
In above case, I expect the user can see 'city' and 'color' when typing 'c'. And after he selects 'color', he can directly see the two options 'red' and 'blue' in the suggestions list.
I checked all arguments of getCompletions: function(editor, session, pos, prefix, callback). But still cannot figure out the better way to do this. Any suggestion will be appreciated.
It's not possible directly or through ace editors default auto complete.
But I have sample code which may full fill your requirement.
Step-1:
You have to create editor object and set options:
ace.require("ace/ext/language_tools");
var editor = ace.edit('div_id');
editor.setTheme("ace/theme/textmate");
editor.getSession().setMode("ace/mode/yaml");
editor.getSession().setTabSize(4);
editor.getSession().setUseSoftTabs(true);
editor.setDisplayIndentGuides(true);
editor.setShowInvisibles(true);
editor.setShowPrintMargin(false);
editor.setOption("vScrollBarAlwaysVisible", true);
editor.setOptions({
enableBasicAutocompletion: true,
enableLiveAutocompletion: true
});
var EditorWordCompleter = {
getCompletions: function(editor, session, pos, prefix, callback) {
getWordList(editor, session, pos, prefix, callback);
}
}
var getWordList = function(editor, session, pos, prefix, callback) {
var wordList = [];
if(prefix === 'T') {
wordList.push('List of tasks');
}
wordList = $.unique(wordList);
callback(null, wordList.map(function(word) {
return {
caption: word,
value: word
};
}));
}
Please change it as per you're requirements.

How to show different popups on click and on mouseover?

The SelectFeature method in Control class provides a way of adding and removing popups on the Vector layer by listening to events featureselected and featureunselected respectively. Below shows a sample code that I obtained from an example in the openlayers website:
// create the layer with listeners to create and destroy popups
var vector = new OpenLayers.Layer.Vector("Points",{
eventListeners:{
'featureselected':function(evt){
var feature = evt.feature;
var popup = new OpenLayers.Popup.FramedCloud("popup",
OpenLayers.LonLat.fromString(feature.geometry.toShortString()),
null,
"<div style='font-size:.8em'>Feature: " + feature.id +"<br>Foo: </div>",
null,
true
);
feature.popup = popup;
map.addPopup(popup);
},
'featureunselected':function(evt){
var feature = evt.feature;
map.removePopup(feature.popup);
feature.popup.destroy();
feature.popup = null;
}
}
});
vector.addFeatures(features);
// create the select feature control
var selector = new OpenLayers.Control.SelectFeature(vector,{
hover:true, # this line
autoActivate:true
});
The code above will allow a popup to be shown upon mouseover on the Geometry object (icon or marker on the map). If the line hover:true is removed, the popup will be shown only upon a mouse click on the Geometry object.
What I want, is to be able to display one type of popup (example, an image plus a title) upon mouseover and another type (example, detailed description) upon a mouse click. I am not sure how this could be done. Some help would be much appreciated. Thanks.
Also, there another way, it's rather hack than correct usage of API, but seems to work. You can overwrite over and out callbacks.
var selectControl = new OpenLayers.Control.SelectFeature(vectorLayer, {
callbacks: {
over: function(feat) {
console.log('Show popup type 1');
},
out: function(feat) {
console.log('Hide popup type 1');
}
},
eventListeners: {
featurehighlighted: function(feat) {
console.log('Show popup type 2');
},
featureunhighlighted: function(feat) {
console.log('Hide popup type 2');
}
}
});
Here's working example: http://jsfiddle.net/eW8DV/1/
Take a look on select control's source to understand details.

sort multiple items at once with jquery.ui.sortable

did somebody manage to sort multiple items at once with jquery.ui.sortable?
we are working on a photo managing app.
select multiple items
drag them to a new location.
thanx
I had a similar requirement, but the solution in the accepted answer has a bug. It says something like "insertBefore of null", because it removes the nodes.
And also i tried jQuery multisortable, it stacks the selected items on top of each other when dragging, which is not what i want.
So I rolled out my own implementation and hope it will save others some time.
Fiddle Link.
Source code:
$( "#sortable" ).sortable({
// force the cursor position, or the offset might be wrong
cursorAt: {
left: 50,
top: 45
},
helper: function (event, item) {
// make sure at least one item is selected.
if (!item.hasClass("ui-state-active")) {
item.addClass("ui-state-active").siblings().removeClass("ui-state-active");
}
var $helper = $("<li><ul></ul></li>");
var $selected = item.parent().children(".ui-state-active");
var $cloned = $selected.clone();
$helper.find("ul").append($cloned);
// hide it, don't remove!
$selected.hide();
// save the selected items
item.data("multi-sortable", $cloned);
return $helper;
},
stop: function (event, ui) {
// add the cloned ones
var $cloned = ui.item.data("multi-sortable");
ui.item.removeData("multi-sortable");
// append it
ui.item.after($cloned);
// remove the hidden ones
ui.item.siblings(":hidden").remove();
// remove self, it's duplicated
ui.item.remove();
}
});
There's a jQuery UI plugin for that: https://github.com/shvetsgroup/jquery.multisortable
jsFiddle: http://jsfiddle.net/neochief/KWeMM/
$('ul.sortable').multisortable();
... or just define a 'items' option to your multisortable that way (for example) :
$('table tbody').multisortable({
items: 'tr'
});
you can use shvetsgroup/jquery.multisortable
but it will create problem.. because, that js is designed only for tags...
but customize it to use it, its very simple i'll tell you how????
at first download that .js and use it in your program...
step 1. open the js file...now edit the following lines...
$.fn.multiselectable.defaults = {
click: function(event, elem) {},
mousedown: function(event, elem) {},
selectedClass: 'selected',
items: 'li'
};
the above are lines from 107 to 112....
there you can see "items: 'li'
in that use your tag which you are used to enclose those image like if you are using, or or anything you are using like this
$.fn.multiselectable.defaults = {
click: function(event, elem) {},
mousedown: function(event, elem) {},
selectedClass: 'selected',
items: 'div' // or any tag you want...
};
and 249 to 254
selectedClass: 'selected',
placeholder: 'placeholder',
items: 'li'
};
}(jQuery);
change the line " item:'li' " with your tag like this
selectedClass: 'selected',
placeholder: 'placeholder',
items: 'div' // or anything else
};
}(jQuery);
if you are working on textboxes inside those envelopes.. you have to get rid of these lines too
// If no previous selection found, start selecting from first selected item.
prev = prev.length ? prev : $(parent.find('.' + options.selectedClass)[0]).addClass('multiselectable-previous');
var prevIndex = prev.index();
after that comment line...
add a line code that search textbox or check box or any interaction element inside it...
like this..
// If no previous selection found, start selecting from first selected item.
item.children("input").focus(); // customize this code to get your element focus...
prev = prev.length ? prev : $(parent.find('.' + options.selectedClass)[0]).addClass('multiselectable-previous');
var prevIndex = prev.index();
and also to indicate selected tags or elements... use styles like this
div { margin: 2px 0; cursor: pointer; }
div.selected { background-color: orange }
div.child { margin-left: 20px; }
actually i used div.. instead of that you can use any tag you wish...
hope will help u.... if it is not... read again.. and ask again....
wishes

Drag from Tree to div

I am trying to implement a drag and drop senario from an extJs TreePanel into a div in the body of the page. I have been following an example by Saki here.
So far I have the below code:
var contentAreas = new Array();
var tree = new Ext.tree.TreePanel({
title : 'Widgets',
useArrows: true,
autoScroll: true,
animate: true,
enableDrag: true,
border: false,
layout:'fit',
ddGroup:'t2div',
loader:new Ext.tree.TreeLoader(),
root:new Ext.tree.AsyncTreeNode({
expanded:true,
leaf:false,
text:'Tree Root',
children:children
}),
listeners:{
startdrag:function() {
$('.content-area').css("outline", "5px solid #FFE767");
},
enddrag:function() {
$('.content-area').css("outline", "0");
}
}
});
var areaDivs = Ext.select('.content-area', true);
Ext.each(areaDivs, function(el) {
var dd = new Ext.dd.DropTarget(el, {
ddGroup:'t2div',
notifyDrop:function(ddt, e, node) {
alert('Drop');
return true;
}
});
contentAreas[contentAreas.length] = dd;
});
The drag begins and the div highlights but when I get over the div it does not show as a valid drop target and the drop fails.
This is my first foray into extJS. I'm JQuery through and through and I am struggling at the moment.
Any help would be appreciated.
Ian
Edit
Furthermore if I create a panel with a drop target in it, this works fine. What is the difference between creating an element and selecting an existing element from the dom. This is obviously where I am going wrong but I'm none the wiser. I have to be able to select existing dom elements and make them into drop targets so the code below is not an option.
Here is the drop target that works
var target = new Ext.Panel({
renderTo: document.body
,layout:'fit'
,id:'target'
,bodyStyle:'font-size:13px'
,title:'Drop Target'
,html:'<div class="drop-target" '
+'style="border:1px silver solid;margin:20px;padding:8px;height:140px">'
+'Drop a node here. I\'m the DropTarget.</div>'
// setup drop target after we're rendered
,afterRender:function() {
Ext.Panel.prototype.afterRender.apply(this, arguments);
this.dropTarget = this.body.child('div.drop-target');
var dd = new Ext.dd.DropTarget(this.dropTarget, {
// must be same as for tree
ddGroup:'t2div'
// what to do when user drops a node here
,notifyDrop:function(dd, e, node) {
alert('drop');
return true;
} // eo function notifyDrop
});
}
});
See if adding true as the second param here makes any difference:
var areaDivs = Ext.select('.content-area', true);
As a cosmetic note, the param name e conventionally indicates an event object (as in the second arg of notifyDrop). For an element, el is more typical. Doesn't matter functionally, but looks weird to someone used to Ext code to see e passed into the DropTarget constructor.
If you are having problem duplicating a working example such as that, copy the entire thing, then modify it to your needs line-by-line - you can't go wrong.
As i know you can't set DropZone to any Ext element, just to Ext component. So this might be you problem. Try to use DropTarget instead of DropZone.