Monaco Editor: only show part of document - javascript

Is there a way to only show part of a document, or in monacos case of a model, while still getting intellisense for the whole document?
I only want a user to edit a part of a document, but the user should be able to get the right contextual intellisense.
It would be best for my usecase to hide the uneditable sections, but deactivating them would also be ok.
In case this is not possible, is there any embedded editor that can do this, or can this be achived by modifying the language server?

Monaco editor loads every line as a container under a section with the class name "view-lines". Once the editor content has loaded, set "display: none" to the corresponding container for each line that you want to hide.
Implementation: https://jsfiddle.net/renatodc/s6fxedo2/
let value = `function capitalizeFirstLetter(string) {
\treturn string.charAt(0).toUpperCase() + string.slice(1);
}
$(function() {
\tlet word = "script";
\tlet result = capitalizeFirstLetter(word);
\tconsole.log(result);
});
`
let linesToDisable = [1,2,3];
let editor = monaco.editor.create(document.getElementById('container'), {
value,
language: 'javascript',
theme: 'vs-dark',
scrollbar: {
vertical: "hidden",
handleMouseWheel: false
},
scrollBeyondLastLine: false
});
// onLoad event for Monaco Editor: https://github.com/Microsoft/monaco-editor/issues/115
let didScrollChangeDisposable = editor.onDidScrollChange(function() {
didScrollChangeDisposable.dispose();
setTimeout(function() {
$(".monaco-editor .view-lines > div").each(function(i) {
if(linesToDisable.includes(i+1)) {
$(this).css("display","none");
$(this).css("pointer-events","none");
}
});
},1000);
});
Scrolling from Monaco will render the lines again and break the implementation. To prevent this, disable the scrolling feature in Monaco, set a fixed height for the editor container, and use the browser or a parent container to scroll instead.
If you use the arrow keys 'up' or 'down' to navigate to the hidden content, the cursor will still work, and typing will break the implementation. You might be able to use the editor's onKeyDown event to prevent this.
If you're looking for a break-proof implementation, I would suggest loading Monaco editor only with the portion of the document that you wish to edit. Then extend the completion provider (Intellisense) as shown in this example: https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-completion-provider-example
monaco.languages.registerCompletionItemProvider('javascript', {
provideCompletionItems: function(model, position) {
return {
suggestions: [
{
label: "capitalizeFirstLetter",
kind: monaco.languages.CompletionItemKind.Method,
documentation: "Capitalize the first letter of a word",
insertText: "capitalizeFirstLetter("
}
]
};
}
});
monaco.editor.create(document.getElementById("container"), {
value: `$(function() {
\tlet word = "script";
\tlet result = capitalizeFirstLetter(word);
\tconsole.log(result);
});
`,
language: "javascript"
});
Use an AST parser like Esprima to get the identifiers from your source document, and plug these into the suggestions array.

Related

CKEditor 5 : Unable to add multiple attributes to 'img' tag

I have implemented a custom math plugin and integrated it into ck5. this plugin will convert math latex to image equation and I'm able to render the converted math equation image into a ck5 editor using the below code.
editor.model.change(writer => {
const imageElement = writer.createElement('image', {
src: data.detail.imgURL
});
editor.model.insertContent(imageElement, selection);
});
Still here everything is working fine. when i'm trying to store original latex equation value in image tag as custom attribute (attribute name is data-mathml ). It strips out custom attributes.
So I have gone through the documentation and tried but was not able to add the custom attribute.
Below is my code :
class InsertImage extends Plugin {
init() {
const editor = this.editor;
const view = editor.editing.view;
const viewDocument = view.document;
// Somewhere in your plugin's init() callback:
view.addObserver( ClickObserver );
editor.ui.componentFactory.add('insertImage', locale => {
const view = new ButtonView(locale);
view.set({
label: 'Add Equations',
withText: true,
tooltip: true
});
// Callback executed once the image is clicked.
this.listenTo(view, 'execute', () => {
openModel();
});
return view;
});
window.addEventListener('setDatatoCK', function(data){
const selection = editor.model.document.selection;
editor.model.change( writer => {
const imageElement = writer.createElement( 'image', {
src: data.detail.imgURL,
'data-mthml': data.detail.latexFrmla,
} );
editor.model.insertContent( imageElement, selection );
} );
})
this.listenTo( editor.editing.view.document, 'click', ( evt, data ) => {
if ( data.domEvent.detail == 2 ) {
editorToPopupdoubleClickHandler( data.domTarget, data.domEvent );
evt.stop();
}
}, { priority: 'highest' } );
}
};
I want to add multiple attributes to the image tag. What should I do to add multiple attributes?
(Note: I'm able to create a new custom tag (tag named "math") with multiple attributes but not for image tag)
Please help me with this. this blocker for me.
Methods tried:
In order to achieve this, I have created one custom tag with multiple attributes and append image tags under this custom tag. It's working fine as expected but I want to add multiple attributes to image tag not with the custom tag.
✔️ Expected result
❌ Actual result
📃 Other details
Browser: Google Chrome Version 78.0.3904.108 (Official Build) (64-bit)
OS: macOS Mojave 10.14.6
CKEditor version: CKEditor 5
Installed CKEditor plugins: ckeditor5-editor-classic,ckeditor5-image,ckeditor5-essentials,ckeditor5-basic-styles,ckeditor5-core,ckeditor5-ui
Hope you've already found a solution to this answer. After spending several hours on searching a solution to a similar problem, I've made it working. See below:
// you have to import the insertImage fn to be able to override default imageinsert fn
import { insertImage } from '#ckeditor/ckeditor5-image/src/image/utils.js'
// this method HAVE to be automatically called when ckeditor is onready.
// You can add custom eventlistener or on the html tag just define listener:
// in Vue2 we used to do like this: <ckeditor #ready="someFnOnCkEditorReadyState()" />
someFnOnCkEditorReadyState() {
// as for img tag the options supported by ckeditor is very limited, we must define our properties to extend the used schema
editor.model.schema.extend('image', { allowAttributes: ['data-mathml'] })
// add conversion for downcast
editor.conversion.for('downcast').add(modelToViewAttributeConverter('data-mathml'))
// add conversion for upcast
editor.conversion.for('upcast').attributeToAttribute({
view: {
name: 'image',
key: 'data-mathml',
},
model: 'data-mathml',
})
}
// then you have to implement your custom image insert method
// from now on this will be your default insertImage fn
// this modification might require other modifications for example to add a custom image browser button to the toolbar
otherFnToInsertImg() {
insertImage(editor.model, {
src: image.url,
'data-mathml': 'here comes the magic',
})
}
Hope it helps someone to save some hours. ;)

Custom plugin with DOM manipulation CKEditor 4.x

I am developing one custom plugin for the CKEditor 4.7 which do a simple think take in case user select some stuff it will put it in a div with specific class, else it will put a div with same class just with text like 'Add content here'
I try to use some functions according to CKEditor docs but have something really wrong.
here is the code for the plugin folder name=> customdiv, file=> plugin.js
CKEDITOR.plugins.add('customdiv', {
icons: 'smile',
init: function (editor) {
editor.addCommand( 'customdiv',{
exec : function( editor ){
var selection = editor.getSelection();
if(selection.length>0){
selection='<div class="desktop">'+selection+'</div>';
}else{
selection='<div class="desktop">Add your text here </div>';
}
return {
selection
};
}
});
editor.ui.addButton( 'Customdiv',
{
label : 'Custom div',
command : 'customdiv',
toolbar: 'customdiv',
icon : this.path + 'smile.png'
});
if (editor.contextMenu) {
editor.addMenuGroup('divGroup');
editor.addMenuItem('customdiv', {
label: 'Customdiv',
icon: this.path + 'icons/smile.png',
command: 'customdiv',
group: 'divGroup'
});
editor.contextMenu.addListener(function (element) {
if (element.getAscendant('customdiv', true)) {
}
});
}
}
});
According to some docs it have to return the result good.
Also this is how I call them in my config.js file
CKEDITOR.editorConfig = function (config) {
config.extraPlugins = 'templates,customdiv';
config.allowedContent = true;
config.toolbar = 'Custom';
config.toolbar_Custom = [
{ name: 'divGroup', items: [ 'Customdiv' ] },
{name: 'document', items: ['Source', '-', 'Save', 'Preview', '-', 'Newplugin']},
/* MOre plugins options here */
];
};
Note: the official forum was close and moved here :(
UPDATE
I have change the function like this
exec : function( editor ){
var selection = editor.getSelection();
if(selection.length>0){
selection='<div class="desktop">'+selection+'</div>';
CKEDITOR.instances.editor1.insertHtml( selection );
}else{
selection='<div class="desktop">Add your text here </div>';
CKEDITOR.instances.editor1.insertHtml( selection );
}
}
This makes it work for the else part, but still can't get the selected one.
UPDATE 2
After change of the if I can get data if is selected, but when I do insert selected between <div> I face a problem.
var selection = editor.getSelection();
give like result an object, and I funded out a more complex function and I get collected data like this
var selection = editor.getSelection().getNative();
alert(selection);
from this in alert I see the proper selection and not just object,but when I insert it like
CKEDITOR.instances.editor1.insertHtml('<div class="desktop">' + selection + '</div>');
it just put all selected in one line and not adding the div, new div for else case working with this syntax.
UPDATE 3
The problem now is this function
CKEDITOR.instances.editor1.insertHtml('<div>' + selection + '<div>');
it delete all existing HTML tags even if I add just selection without <div> I am not sure if this is because of the way I insert data or way I collect data, just in alert when I collect data I see correct space like in the editor.
user select some stuff it will put it in a div with specific class
If you want to check if selection is not empty, please instead of selection.length>0 try using !selection().getRanges()[0].collapsed.
If you need something more advanced you could also try using
!!CKEDITOR.instances.editor1.getSelection().getSelectedText() to see if any text was selected and !!CKEDITOR.instances.editor1.getSelection().getSelectedElement() to see if any element like e.g. image, tabl,e widget or anchor was selected.
EDIT:
If you need selected HTML please use CKEDITOR.instances.editor1.getSelectedHtml().getHtml();
Please also have a look at CKEditor documentation:
https://docs.ckeditor.com/#!/api/CKEDITOR.editor-method-getSelectedHtml
https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dom_documentFragment.html#method-getHtml
https://docs.ckeditor.com/#!/api/CKEDITOR.dom.selection-method-getSelectedText
https://docs.ckeditor.com/#!/api/CKEDITOR.dom.selection-method-getSelectedElement

intro.js show and hide data-hint

I want to have a button that can turn on and off the 'hints' function in intro.js.
I have a working version to show and then hide but the show only works once. How can I get it to work repeatedly? This functionality works for the standard data-intro but not for data-hint.
<div class="jumbotron">
<h1 id='step1'>Hints</h1>
<p class="lead">Adding hints using JSON + callbacks</p>
<a id='step2' class="btn btn-large btn-success" href="javascript:void(0);">Add hints</a>
</div>
function addHints(){
intro = introJs();
intro.setOptions({
hints: [
{
element: document.querySelector('#step1'),
hint: "This is a tooltip.",
hintPosition: 'top-middle'
},
{
element: '#step2',
hint: 'More features, more fun.',
position: 'left'
},
{
element: '#step4',
hint: "<b>Another</b> step.",
hintPosition: 'top-middle'
}
]
});
intro.onhintsadded(function() {
console.log('all hints added');
});
intro.onhintclick(function(hintElement, item, stepId) {
console.log('hint clicked', hintElement, item, stepId);
});
intro.onhintclose(function (stepId) {
console.log('hint closed', stepId);
});
intro.addHints();
}
$(function() {
$('#step2').click(function(){
if ( $('#step2').hasClass('clicked') ) {
introJs().hideHints();
$('#step2').removeClass('clicked');
} else {
addHints();
$('#step2').addClass('clicked');
}
});
});
Instead of using hideHints intro.js API method just remove the div block of intro.js from DOM:
var introDiv = document.getElementsByClassName("introjs-hints")[0];
introDiv.parentNode.removeChild(introDiv);
(You can do the same thing with jQuery if you want to).
When the div is removed from DOM, just initialize hints once again as you do with your addHints method when you want to show hints and it'll work.
Instead of deleting the div block with javascript. You can use .removeHints()
This function is part of intro.js, but is not included in the documentation.
Perhaps a bit hacky, but this works for me...
First, put your hints into their own variable:
hints = [{...}, ...]
then, reset your hints in the intro options
intro.onhintclose(function(stepId) {
if (document.querySelectorAll('.introjs-hidehint').length === hints.length) {
intro.setOptions({hints: hints})
}
})
The hidden hints are given a class of introjs-hidehint, and document.querySelectorAll will return all of them in an array. Once that array is the same size as your hints array, reset your hints in your intro options and that will reset all your hints so you can show them all again.
Here's a more complete example that also allows:
(a) toggling hints on/off by clicking a button (located on a nav bar so used across multiple pages).
(b) once all hints have been clicked, the hints div gets removed so that clicking show hints button will again actually...show hints...
(c) allow you to store hints for multiple pages in a single json object array (re: nav bar).
var jquery = require('jquery');
var introJs = require('intro.js');
* ===========================================================================
* define onclick of hints button
* =========================================================================*/
jquery('#hints_button').on('click', function() {
if (document.getElementsByClassName('introjs-hints').length == 0){
addSomeHints();
}
else {
destroyHints();
};
});
/* ===========================================================================
* Add hints using the IntroJS library
* =========================================================================*/
/* define hints */
var theHints = [
{
element: document.querySelector('#step1'),
hint: "This is a tooltip.",
hintPosition: 'top-middle'
},
{
element: '#step2',
hint: 'More features, more fun.',
hintPosition: 'left'
},
{
element: '#step4',
hint: "<b>Another</b> step.",
hintPosition: 'top-middle'
}
];
/* generate hints with introjs */
function addSomeHints() {
intro = introJs();
intro.setOptions({
hints: theHints
});
intro.onhintclose(function (stepId) {
var remaining_hints = all_hints - document.getElementsByClassName("introjs-hidehint").length;
if (remaining_hints == 0) {
destroyHints();
};
});
/* add hints */
intro.addHints();
/* store number of hints created */
var all_hints = document.getElementsByClassName('introjs-hint').length;
};
/* remove hints div */
function destroyHints() {
var hintsDiv = document.getElementsByClassName("introjs-hints")[0]
hintsDiv.parentNode.removeChild(hintsDiv);
};
... hopefully this saves someone the 20 minutes it took me to piece together the answers and adapt it for what seems like a super common use case.

Predefined buttons in CKEditor Mathjax plugin

CKEditor's Mathjax plugin contains several elements in the dialog: one textarea (id: equation) and one div (id: preview).
https://github.com/ckeditor/ckeditor-dev/blob/master/plugins/mathjax/dialogs/mathjax.js
When some mathjax code is entered in the textarea, the formula is written in the div. I am trying to add several predefined buttons that add usual formulae mathjax text to the textarea, so users only have to populate these formulae.
Adding a button into the elements works nice, but I can only access to change the div element. Accessing the textarea does not work, it seems that is not available in any scope at all.
id: 'info',
elements: [
{
id: 'testButton',
type: 'button',
button: 'aaaa',
onClick: function() {
// Changing the ID value does work
preview.setValue('Test');
// but changing the textarea does not.
// equation.setValue('Test');
// document.getElementById('equation').setValue('Test');
}
},
{
id: 'equation',
type: 'textarea',
label: lang.dialogInput,
onLoad: function() {
var that = this;
if ( !( CKEDITOR.env.ie && CKEDITOR.env.version == 8 ) ) {
this.getInputElement().on( 'keyup', function() {
// Add \( and \) for preview.
preview.setValue( '\\(' + that.getInputElement().getValue() + '\\)' );
} );
}
},
Sorry if this is a simple question, but how can I access to equation textarea?
After much reading, it seems that this is a way, not sure it's the best way though.
onClick: function() {
this._.dialog.setValueOf("info","equation","TEST");
}

How to add a dropdown for line-height selection in tinyMCE for WP 3.9

I am looking for some code which would add a dropdown to my WYSIWYG fields in the WordPress backend through which I would be able to choose an inline line-height for the selected text. I find the tinyMCE documentation very confusing. Additionally it is mostly aimed at TM 3, but WP 3.9 uses the fourth version…
My tinyMCE Plugin looks something like this:
tinymce.PluginManager.add('ad_lineheight', function(editor, url) {
…
editor.addButton('ad_lineheight', {
type: 'splitbutton',
text: 'line-height',
icon: false,
menu: menuval
});
});
How would you integrate the function, which adds inline-styles to the selected input, like so <span style="line-height: 120%; display: inline-block;">selected text</span>?
EDIT: I already managed to add the dropdown to the editor, it shows the line-heights I defined programmatically like 80%, 90%, 100% and so on.
EDIT2: With this code I am able to change the line-height:
editor.addCommand('lineHeight', function(com, value) {
var selected = tinyMCE.activeEditor.selection.getContent();
var content = '<span style="line-height: '+value+';">' + (selected != '' ? selected : '') + '</span>';
editor.execCommand('mceInsertContent', false, content);
});
editor.addButton('lineheightselect', function() {
…
…
return {
type: 'listbox',
text: 'line-height',
tooltip: 'line-height',
values: items,
fixedWidth: true,
onclick: function(e) {
if (e.control.settings.value) {
editor.execCommand('lineHeight', false, e.control.settings.value);
}
}
};
});
But it is not very practical as it ignores inline-styles that are already there leading to code like this:
<span class="h3" style="font-size: 90%;"><span style="line-height: 160%;">AND</span></span>
this is an old question but I am adding the answer here just in case anyone still need it.
you can use getNode() instead of getContent()
you command code will be
editor.addCommand('lineHeight', function(com, value) {
var node = tinyMCE.activeEditor.selection.getNode();
$(node).css('line-height', value);
});
You need to add custom button to TinyMCE editor, you need also to create your style in some CSS stylesheet. Maybe some WP function may be needed. I don't think you will need adding anything in JS - there is already possibility to add custom style button in TinyMCE and you could achieve that using PHP.
http://codex.wordpress.org/TinyMCE_Custom_Buttons
http://codex.wordpress.org/TinyMCE_Custom_Styles

Categories