How can I do the following with the Ace Editor.
User types the '#' character
Autocomplete pops up
User makes a selection from the dropdown
The '#' gets removed now that the selection has been made
I basically want the # as a trigger for the autocomplete, but I don't want it hanging around after.
Thank you
addAutoComplete() {
var me = this;
ace.require('./config').loadModule('ace/ext/language_tools', () => {
this.aceEditor.setOptions({
enableBasicAutocompletion: true,
enableSnippets: true,
enableLiveAutocompletion: false
});
me.include = /[a-z.]/i;
this.aceEditor.on('change', (obj, editor) => {
switch (obj.action) {
case 'insert':
let lines = obj.lines;
let char = lines[0];
if ((lines.length === 1) && (char.length === 1) && me.include.test(char)) {
setTimeout(() => {
me.aceEditor.commands.byName.startAutocomplete.exec(me.aceEditor);
}, 50);
}
break;
}
});
});
}
that's the demo. works fine
We can bind the '#' keyword and trigger the autocomplete:
editor.commands.addCommand({
name: "myCommand",
bindKey: { win: "#", mac: "#" },
exec: function (editor) {
autocomplete();
}
});
autocomplete: function () {
staticWordCompleter = {
var getWordList = function(editor, session, pos, prefix, callback, isRHSEditor) {
var wordList = []; // add your words to this list
callback(null, wordList.map(function(word) {
return {
caption: word,
value: word
};
}));
editor.completers = [staticWordCompleter];
}
None of the above approaches worked for me. I ended up rolling my own autocomplete/autosuggest for this to work. It's hard to contrive an example but in short the steps are:
Capture the onChange of the editor
If the editor action meets the criteria (i.e. the # symbol is pressed), display a box at the cursor position. This can be done by setting the box to position absolute, and setting the top/left attributes:
const {row, column} = window.editor.getCursorPosition();
const {pageX, pageY} = window.editor.renderer.textToScreenCoordinates(row, column)
const autosuggest = document.getElementById("ELEMENT_NAME")
autosuggest.style.left = pageX
autosuggest.style.top = pageY
Add commands to disable/redirect any actions such as the arrow keys/enter key, and re-enable when a selection is made.
function disableEnterKeyInEditor() {
editor.commands.addCommand(commmand_enter);
}
function enableEnterKeyInEditor() {
editor.commands.removeCommands(commmand_enter);
}
command_enter = {
name: "enterKeyPressedCommand",
bindKey: {win: "Enter", mac: "Enter"},
exec: function (editor) {
return true;
}
};
This was much easier than working with ace's autocomplete.
You can check with below code:
var getWordList = function(editor, session, pos, prefix, callback, isRHSEditor) {
var wordList = [];
if(prefix === '#') {
wordList.push('add you're name list here');
}
callback(null, wordList.map(function(word) {
return {
caption: word,
value: word
};
}));
}
Related
I'm using the DropdownList component from react-widget. In my code, there are a couple of dropdowns that get their values from an Ajax call. Some of them, like a list of languages, are too big and it's very slow to get the list from Ajax and render it (takes 4 to 5 seconds!). I would like to provide to the dropdwon a small list of languages and an 'Extend' or 'Load Full List' option; if clicking on Extend the dropdown would be refreshed with the full list of languages.
Here is my solution: the code of the parent component:
const languages = ajaxCalls.getLanguages();
const langs = {"languages": [["eng", "English"], ["swe", "Swedish"], ["deu", "German"], ["...", "Load Full List"]]};
const common_langs = langs.languages.map(([id, name]) => ({id, name}));
<SelectBig data={common_langs} extend={languages} onSelect={x=>this.setValue(schema, path, x)} value={this.getValue(path)} />;
And here is the code for SelectBig component:
import React from 'react/lib/ReactWithAddons';
import { DropdownList } from 'react-widgets';
const PT = React.PropTypes;
export const SelectBig = React.createClass({
propTypes: {
data: PT.array,
value: PT.string,
onSelect: PT.func.isRequired,
},
maxResults: 50,
shouldComponentUpdate(nextProps, nextState) {
console.log("nextProps = " , nextProps, " , nextState = ", nextState);
const len = x => (x && x.length !== undefined) ? x.length : 0;
// fast check, not exact, but should work for our use case
return nextProps.value !== this.props.value
|| len(nextProps.data) !== len(this.props.data);
},
getInitialState(){
return {
lastSearch: '',
results: 0,
dataList: [],
};
},
select(val) {
if(val.id === "..."){
this.setState({dataList: this.props.extend})
}
this.props.onSelect(val.id);
},
filter(item, search) { .... },
renderField(item) { .... },
render() {
const busy = !this.props.data;
let data;
if(!this.props.extend){
data = this.props.data || [];
} else {
data = this.state.dataList;
}
return (
<DropdownList
data={data}
valueField='id'
textField={this.renderField}
value={this.props.value}
onChange={this.select}
filter={this.filter}
caseSensitive={false}
minLength={2}
busy={busy} />
);
}
});
But it doesn't look good: When the user chooses 'Load Full List', the dropdown list will be closed and user need to click again to see the updated list. Does anyone have a better solution or a suggestion to improve my code?
The picture shows how it looks like right now!
https://www.npmjs.com/package/react-select-2
Better go with this link, it will work
As I reported at in this CKEditor this ticket, inline widgets in CKEditor (4.7.0) do not preserve trailing spaces, causing display issues.
Take the following simple widget:
CKEDITOR.plugins.add('spanwidget', {
requires: 'widget',
init: function (editor) {
editor.widgets.add('spanwidget', {
editables: {
content: {
selector: 'span'
}
},
upcast: function (element) {
return element.name == 'span';
}
});
}
});
When you load the following data <span>lorem </span>ipsum, you see this text in output: loremipsum (notice the missing space).
This can be seen in this JSFiddle.
How can I work around the problem (I do not control which data is loaded inside CKEditor)?
I found a workaround to force the last trailing space to be preserved. The idea is to replace the last space with a when upcasting the widget element, then remove it before downcasting it:
CKEDITOR.replace('ck', {
allowedContent: true,
extraPlugins: 'spanwidget'
});
CKEDITOR.plugins.add('spanwidget', {
requires: 'widget',
init: function (editor) {
editor.widgets.add('spanwidget', {
editables: {
content: { selector: 'span' }
},
upcast: function (element) {
// Matches?
if (element.name == 'span') {
// Ends with text?
var children = element.children,
childCount = children.length,
lastChild = childCount && children[childCount - 1];
if (lastChild instanceof CKEDITOR.htmlParser.text) {
// Replace the last space with a non breaking space
// (see https://github.com/ckeditor/ckeditor-dev/issues/605)
lastChild.value = lastChild.value.replace(/ $/, ' ');
}
// Match!
return true;
}
// No match
return false;
},
downcast: function (element) {
// Span with class "targetinfo"?
if (element.name == 'span') {
// Ends with text?
var children = element.children,
childCount = children.length,
lastChild = childCount && children[childCount - 1];
if (lastChild instanceof CKEDITOR.htmlParser.text) {
// Ends with a non breaking space?
var match = lastChild.value.match(/ $/i);
if (match) {
// Replace the non breaking space with a normal one
lastChild.value = lastChild.value.replace(/ $/i, ' ');
// Clone the element
var clone = element.clone();
// Reinsert all the children into that element
for (var i = 0; i < childCount; i++) {
clone.add(children[i]);
}
// Return the clone
return clone;
}
}
}
}
});
}
});
See updated JSFiddle here.
I have created a ckeditor plugin that wraps the selected text into a span.
I wonder how can I unwrap the selected when I apply this plugin on a text that has been previously wrapped into the span.
CKEDITOR.plugins.add('important', {
// Register the icons. They must match command names.
//trick to get a 16*16 icon : http://www.favicomatic.com
icons: 'important',
init: function (editor) {
editor.addCommand('important', {
// Define the function that will be fired when the command is executed.
exec: function (editor) {
var selected_text = editor.getSelection().getSelectedText();
console.log(editor.getSelection()) ;
var newElement = new CKEDITOR.dom.element("span");
newElement.setAttributes({class: 'important'});
newElement.setText(selected_text);
editor.insertElement(newElement);
//how to unwrap the selected text ?
});
// Create the toolbar button that executes the above command.
editor.ui.addButton('important', {
label: 'Set this as important',
command: 'important',
toolbar: 'insert'
});
}
});
Finally, using editor.getSelection().getStartElement(), I can check if the starting element has already been wrapped with the class and remove it if necessary.
CKEDITOR.plugins.add('important', {
//trick to get a 16*16 icon : http://www.favicomatic.com
icons: 'important',
init: function (editor) {
var className = 'important';
editor.addCommand('important', {
// Define the function that will be fired when the command is executed.
exec: function (editor) {
var editorSelection = editor.getSelection();
var selected_text = editorSelection.getSelectedText();
var startElement = editorSelection.getStartElement();
//if the element has already been wrapped, let's UNwrap it
if (className === startElement.$.className) {
var html = startElement.$.innerHTML;
editor.getSelection().getStartElement().remove();
editor.insertHtml(html);
} else {
//if the element has NOT already been wrapped, let's wrap it
var newElement = new CKEDITOR.dom.element("span");
newElement.setAttributes({class: 'important'});
newElement.setText(selected_text);
editor.insertElement(newElement);
}
}
});
// Create the toolbar button that executes the above command.
editor.ui.addButton('important', {
label: 'Set this as important',
command: 'important',
toolbar: 'insert'
});
}
});
I found this working example of Inheritance Patterns that separates business logic and framework code. I'm tempted to use it as a boilerplate, but since it is an inheritance Pattern, then how can I extend the business logic (the methods in var Speaker)?
For instance, how can I extend a walk: method into it?
/**
* Object Speaker
* An object representing a person who speaks.
*/
var Speaker = {
init: function(options, elem) {
// Mix in the passed in options with the default options
this.options = $.extend({},this.options,options);
// Save the element reference, both as a jQuery
// reference and a normal reference
this.elem = elem;
this.$elem = $(elem);
// Build the dom initial structure
this._build();
// return this so we can chain/use the bridge with less code.
return this;
},
options: {
name: "No name"
},
_build: function(){
this.$elem.html('<h1>'+this.options.name+'</h1>');
},
speak: function(msg){
// You have direct access to the associated and cached jQuery element
this.$elem.append('<p>'+msg+'</p>');
}
};
// Make sure Object.create is available in the browser (for our prototypal inheritance)
// Courtesy of Papa Crockford
// Note this is not entirely equal to native Object.create, but compatible with our use-case
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {} // optionally move this outside the declaration and into a closure if you need more speed.
F.prototype = o;
return new F();
};
}
$.plugin = function(name, object) {
$.fn[name] = function(options) {
// optionally, you could test if options was a string
// and use it to call a method name on the plugin instance.
return this.each(function() {
if ( ! $.data(this, name) ) {
$.data(this, name, Object.create(object).init(options, this));
}
});
};
};
// With the Speaker object, we could essentially do this:
$.plugin('speaker', Speaker);
Any ideas?
How about simply using JavaScript's regular prototype inheritance?
Consider this:
function Speaker(options, elem) {
this.elem = $(elem)[0];
this.options = $.extend(this.defaults, options);
this.build();
}
Speaker.prototype = {
defaults: {
name: "No name"
},
build: function () {
$('<h1>', {text: this.options.name}).appendTo(this.elem);
return this;
},
speak: function(message) {
$('<p>', {text: message}).appendTo(this.elem);
return this;
}
};
Now you can do:
var pp = new Speaker({name: "Porky Pig"}, $("<div>").appendTo("body"));
pp.speak("That's all folks!");
Speaker.prototype.walk = function (destination) {
$('<p>', {
text: this.options.name + " walks " + destination + ".",
css: { color: "red" }
}).appendTo(this.elem);
return this;
}
pp.walk("off the stage");
Runnable version:
function Speaker(options, elem) {
this.elem = $(elem)[0];
this.options = $.extend(this.defaults, options);
this.build();
}
Speaker.prototype = {
defaults: {
name: "No name"
},
build: function () {
$('<h1>', {text: this.options.name}).appendTo(this.elem);
return this;
},
speak: function(message) {
$('<p>', {text: message}).appendTo(this.elem);
return this;
}
};
var pp = new Speaker({name: "Porky Pig"}, $("<div>").appendTo("body"));
pp.speak("That's all folks!");
Speaker.prototype.walk = function (destination) {
$('<p>', {
text: this.options.name + " walks " + destination + ".",
css: { color: "red" }
}).appendTo(this.elem);
return this;
}
pp.walk("off the stage");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
I have created a plugin with following codes:
var myplugin = {
init: function(options) {
$.myplugin.settings = $.extend({}, $.myplugin.defaults, options);
},
method1: function(par1) {
.....
},
method2: function(par1) {
.....
}
};
$.myplugin = function(method){
if ( myplugin[method] ) {
return myplugin[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if (typeof method === 'object' || !method) {
return myplugin.init.apply(this, arguments);
} else {
$.error( 'Method "' + method + '" does not exist in myplugin!');
}
};
$.myplugin.defaults = {
option1: 'test',
option2: '',
option3: ''
};
$.myplugin.settings = {};
$.myplugin();
This works well but the issue is that when I try to set more than 1 option and try to return its values afterwards, it gives empty; setting one option works well. For eg.
If on changing the first combo box value I call this:
$.myplugin({option1: 'first test'});
it works, but when I try to call another on second combo box it doesn't save the option, instead it reset to empty.
Is there any fix?
I would re-organize the plugin to use this structure:
var methods = {
settings: {
foo: "foo",
bar: "bar"
},
init: function(options) {
this.settings = $.extend({}, this.settings, options);
},
method1: function(par1) {
alert(this.settings.foo);
},
method2: function(par1) {
alert(this.settings.bar);
}
};
function MyPlugin(options) {
this.init(options);
return this;
}
$.extend(MyPlugin.prototype, methods);
$.myPlugin = function(options) {
return new MyPlugin(options);
}
/* usage */
// without parameters
var obj1 = $.myPlugin();
// with parameters
var obj2 = $.myPlugin({foo: "foobar"});
// each has it's own settings
obj1.method1();
obj2.method1();
Demo: http://jsfiddle.net/ypXdS/
Essentially $.myPlugin simply creates and returns a new instance of the MyPlugin class. You could get rid of it completely and use new myPlugin(options) in it's place.