So I'm trying to make an SCXML editor which is basically XML (state machine) with JavaScript blocks in it. I'm close, but I'm having trouble adding hints. It seems to boil down to I don't know the editing mode I'm in when it comes time to hint. I've looked in the CodeMirror object for clues but I'm not seeing it. I'm doing the multiplexing like so:
CodeMirror.defineMode("scxml", function (config) {
return CodeMirror.multiplexingMode(
CodeMirror.getMode(config, "text/xml"),
{
open: "<script>", close: "</script>",
mode: CodeMirror.getMode(config, "text/javascript"),
delimStyle: "delimit"
}
);
});
editorXml = CodeMirror.fromTextArea(document.getElementById("editXmlFile"), {
lineNumbers: true,
mode: 'scxml',
indentUnit: 4,
autoCloseTags: true,
matchBrackets: true,
extraKeys: {
"'>'": function (cm) { cm.closeTag(cm, '>'); },
"'/'": function (cm) { cm.closeTag(cm, '/'); },
"' '": function (cm) { CodeMirror.xmlHint(cm, ' '); },
"'<'": function (cm) { CodeMirror.xmlHint(cm, '<'); },
"Ctrl-Space": function (cm) { CodeMirror.xmlHint(cm, ''); }
}
});
Note in the extraKeys where the XML hinting is working, how do I get the JavaScript hinting in there? From the JavaScript hinting help, it appears I'd do something along the lines of:
CodeMirror.commands.autocomplete = function(cm) {
CodeMirror.simpleHint(cm, CodeMirror.javascriptHint);
}
... extraKeys: {"Ctrl-Space": "autocomplete"} ...
But either way, I need to know the mode I'm in (XML or JavaScript) to know to use simpleHint versus xmlHint. Anyone know how this might be done?
EDIT: cm.getMode().name and cm.getOption('mode') just return scxml when I'm in either section
Thanks!
I think you should be able to dispatch on CodeMirror.innerMode(cm.getMode(), cm.getTokenAt(POS).state).mode.name, where POS is the {line, ch} position that you're interested in. It will return a name like "xml" or "javascript", describing the inner mode at that position.
Related
I'm using the shouldLoad functionality to set a minimum length of characters before data loads from a remote source, like the example here
shouldLoad:function(query){
if ( query.length < 3 ) return false;
return true;
},
Is there a way to show the user that they must then enter this minimum number of characters, like select2 does?
Thanks
Of course,
You can use not_loading in your renderer function which is triggered when you return false from shouldLoad.
Example:
render: {
option: function(item, escape) {
return `<div>${ escape(item.name) }</div>`;
},
item: function(item, escape) {
return `<div>${ escape(item.name) }</div>`;
},
not_loading:function(data,escape){
return `<div>Please enter 2 or more characters </div>`;
},
},
});
You can learn more from their official doc.
Hope it helps.
I have a map wher we can classically switch from one style to another, streets to satellite for example.
I want to be informed that the style is loaded to then add a layer.
According to the doc, I tried to wait that the style being loaded to add a layer based on a GEOJson dataset.
That works perfectly when the page is loaded which fires map.on('load') but I get an error when I just change the style, so when adding layer from map.on('styledataloading'), and I even get memory problems in Firefox.
My code is:
mapboxgl.accessToken = 'pk.token';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v10',
center: [5,45.5],
zoom: 7
});
map.on('load', function () {
loadRegionMask();
});
map.on('styledataloading', function (styledata) {
if (map.isStyleLoaded()) {
loadRegionMask();
}
});
$('#typeMap').on('click', function switchLayer(layer) {
var layerId = layer.target.control.id;
switch (layerId) {
case 'streets':
map.setStyle('mapbox://styles/mapbox/' + layerId + '-v10');
break;
case 'satellite':
map.setStyle('mapbox://styles/mapbox/satellite-streets-v9');
break;
}
});
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'regions.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
function loadRegionMask() {
loadJSON(function(response) {
var geoPoints_JSON = JSON.parse(response);
map.addSource("region-boundaries", {
'type': 'geojson',
'data': geoPoints_JSON,
});
map.addLayer({
'id': 'region-fill',
'type': 'fill',
'source': "region-boundaries",
'layout': {},
'paint': {
'fill-color': '#C4633F',
'fill-opacity': 0.5
},
"filter": ["==", "$type", "Polygon"]
});
});
}
And the error is:
Uncaught Error: Style is not done loading
at t._checkLoaded (mapbox-gl.js:308)
at t.addSource (mapbox-gl.js:308)
at e.addSource (mapbox-gl.js:390)
at map.js:92 (map.addSource("region-boundaries",...)
at XMLHttpRequest.xobj.onreadystatechange (map.js:63)
Why do I get this error whereas I call loadRegionMask() after testing that the style is loaded?
1. Listen styledata event to solve your problem
You may need to listen styledata event in your project, since this is the only standard event mentioned in mapbox-gl-js documents, see https://docs.mapbox.com/mapbox-gl-js/api/#map.event:styledata.
You can use it in this way:
map.on('styledata', function() {
addLayer();
});
2. Reasons why you shouldn't use other methods mentioned above
setTimeout may work but is not a recommend way to solve the problem, and you would got unexpected result if your render work is heavy;
style.load is a private event in mapbox, as discussed in issue https://github.com/mapbox/mapbox-gl-js/issues/7579, so we shouldn't listen to it apparently;
.isStyleLoaded() works but can't be called all the time until style is full loaded, you need a listener rather than a judgement method;
Ok, this mapbox issue sucks, but I have a solution
myMap.on('styledata', () => {
const waiting = () => {
if (!myMap.isStyleLoaded()) {
setTimeout(waiting, 200);
} else {
loadMyLayers();
}
};
waiting();
});
I mix both solutions.
I was facing a similar issue and ended up with this solution:
I created a small function that would check if the style was done loading:
// Check if the Mapbox-GL style is loaded.
function checkIfMapboxStyleIsLoaded() {
if (map.isStyleLoaded()) {
return true; // When it is safe to manipulate layers
} else {
return false; // When it is not safe to manipulate layers
}
}
Then whenever I swap or otherwise modify layers in the app I use the function like this:
function swapLayer() {
var check = checkIfMapboxStyleIsLoaded();
if (!check) {
// It's not safe to manipulate layers yet, so wait 200ms and then check again
setTimeout(function() {
swapLayer();
}, 200);
return;
}
// Whew, now it's safe to manipulate layers!
the rest of the swapLayer logic goes here...
}
Use the style.load event. It will trigger once each time a new style loads.
map.on('style.load', function() {
addLayer();
});
My working example:
when I change style
map.setStyle()
I get error Uncaught Error: Style is not done loading
This solved my problem
Do not use map.on("load", loadTiles);
instead use
map.on('styledata', function() {
addLayer();
});
when you change style, map.setStyle(), you must wait for setStyle() finished, then to add other layers.
so far map.setStyle('xxx', callback) Does not allowed. To wait until callback, work around is use map.on("styledata"
map.on("load" not work, if you change map.setStyle(). you will get error: Uncaught Error: Style is not done loading
The current style event structure is broken (at least as of Mapbox GL v1.3.0). If you check map.isStyleLoaded() in the styledata event handler, it always resolves to false:
map.on('styledata', function (e) {
if (map.isStyleLoaded()){
// This never happens...
}
}
My solution is to create a new event called "style_finally_loaded" that gets fired only once, and only when the style has actually loaded:
var checking_style_status = false;
map.on('styledata', function (e) {
if (checking_style_status){
// If already checking style status, bail out
// (important because styledata event may fire multiple times)
return;
} else {
checking_style_status = true;
check_style_status();
}
});
function check_style_status() {
if (map.isStyleLoaded()) {
checking_style_status = false;
map._container.trigger('map_style_finally_loaded');
} else {
// If not yet loaded, repeat check after delay:
setTimeout(function() {check_style_status();}, 200);
return;
}
}
I had the same problem, when adding real estate markers to the map. For the first time addding the markers I wait till the map turns idle. After it was added once I save this in realEstateWasInitialLoaded and just add it afterwards without any waiting. But make sure to reset realEstateWasInitialLoaded to false when changing the base map or something similar.
checkIfRealEstateLayerCanBeAddedAndAdd() {
/* The map must exist and real estates must be ready */
if (this.map && this.realEstates) {
this.map.once('idle', () => {
if (!this.realEstateWasInitialLoaded) {
this.addRealEstatesLayer();
this.realEstateWasInitialLoaded = true
}
})
if(this.realEstateWasInitialLoaded) {
this.addRealEstatesLayer();
}
}
},
I ended up with :
map.once("idle", ()=>{ ... some function here});
In case you have a bunch of stuff you want to do , i would do something like this =>
add them to an array which looks like [{func: function, param: params}], then you have another function which does this:
executeActions(actions) {
actions.forEach((action) => {
action.func(action.params);
});
And at the end you have
this.map.once("idle", () => {
this.executeActions(actionsArray);
});
I have created simple solution. Give 1 second for mapbox to load the style after you set the style and you can draw the layer
map.setStyle(styleUrl);
setTimeout(function(){
reDrawMapSourceAndLayer(); /// your function layer
}, 1000);
when you use map.on('styledataloading') it will trigger couple of time when you changes the style
map.on('styledataloading', () => {
const waiting = () => {
if (!myMap.isStyleLoaded()) {
setTimeout(waiting, 200);
} else {
loadMyLayers();
}
};
waiting();
});
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';
};
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.
I have just noticed an annoying behavior of TinyMCE editor. When I have written, let's say, a few paragraphs of text, and I want to select some of it and make it a heading (Heading 2 style), the whole text gets that heading style, not only the text I have selected.
This is not happening when I want to apply bolding - in this case it works as expected; only the selected text becomes bolded.
How can I change this behavior? I know there is HTML mode where I can change the style, but I am afraid my clients are not so familiar with HTML and they'd want to use visual mode only.
I guess it is because h2-tags usually are not valid as child nodes of paragraphs.
You may try to adjust the tinymce configuration parameter valid_children according to your needs.
This is the native behavior of TinyMCE and it cannot be changed.
Here is the workaround that I've found. Works great for me
tinyMCE.PluginManager.add('FormatingToolbarButtons', function (editor, url) {
['pre', 'p', 'code', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'].forEach(function (name) {
editor.addButton("style-" + name, {
tooltip: "Toggle " + name,
text: name.toUpperCase(),
onClick: function () {
if (this.active()) {
editor.execCommand('mceToggleFormat', false, name);
this.active(false)
}
else {
editor.selection.setContent('<' + name + '>' + editor.selection.getContent() + '</' + name + '>');
this.active(true)
}
},
onPostRender: function () {
var self = this, setup = function () {
editor.formatter.formatChanged(name, function (state) {
self.active(state);
});
};
editor.formatter ? setup() : editor.on('init', setup);
}
})
});
});
Could you try below:
https://www.tiny.cloud/docs-3x/reference/Configuration3x/Configuration3x#force_br_newlines/
Try force_p_newlines : true, and see if it works.