ElectronJS - Make bold text in Teaxtarea with local keyboard shortcut - javascript

I'm trying to make a text editor in ElectronJS as my first application in Electron.
I got the Textarea and the shortcut setup as it should be, but I cant get the selected text in the textarea to get bold, when pressing CTRL+B. I could use some help in the right direction on how this is done.
I have tried to use the execCommand so far to toggle the bold, but are getting the error:
Document is not defined
Main.js
menu.append(new MenuItem({
label: 'Shortcuts',
submenu: [{
role: 'Bold',
accelerator: process.platform === 'darwin' ? 'Cmd+B' : 'Ctrl+B',
click: () => {
document.execCommand('bold');
}
}]
}))
Menu.setApplicationMenu(menu)
I have also tried this in renderer.js, but not working aswell.
What am I doing wrong?

This actually answered the question: https://stackoverflow.com/a/12831155/652535
Content from link:
If you need to customize your textarea, reproduce its behavior using another element (like a DIV) with the contenteditable attribute.
It's more customizable, and a more modern approach, textarea is just for plain text content, not for rich content.
<div id='fake_textarea' contenteditable></div>
The scrollbars can be reproduced with the CSS overflow property.
You can use this fake textarea in a form normally, i.e: if you have to submit its content through POST method, you could do something like(with jQuery):
<input type='hidden' id='fake_textarea_content' name='foobar' />
...
$('#your_form').submit(function()
{
$('#fake_textarea_content').val($('#fake_textarea').html());
});

Related

Remove unwanted text in the select box label

In my project the select box is loading dynamically using knockout js, In the label field i can see the unwanted text(select). so i want to remove it.
<label style="display: inline-block" data-bind="html: label, css: { 'fiori3-incomplete-labelsss': incompleteaa() && $root.highlightIncompleteaaa(), 'pull-left': hinaaat(), 'required-attribute': requiredaa }, attr: { for: stdAttrCodeaaa }" for="9152"></label>
Is this 'Select' unwanted text fixed?
If yes, then you can just remove it using jQuery after page loaded.
e.g.
$(document).ready(() => {
$('#TheLabel').text((index, text) => text.replace("Select", ""));
});
or any other similar script.
If no, then it is a dynamic text which you have to clean it up in back-end. There is no way for the front-end script to guess what the text is.

Add class style to CKEditor text with javascript

I'm building a self contained web page and am using CKEditor 4.6.2 for input. My last hurdle, for now, is trying to apply a css class style to text inserted via javascript. My css is in the head tag, nothing special there. I have defined a styleset as directed by CKEditor documentation.
CKEDITOR.stylesSet.add('my_custom_styles', [
// Block-level Styles
{ name: 'My Custom Block', element: 'p',
styles:{
'color': 'dimgray',
'padding-left':'15px',
'border-left-style':'solid',
'border-width':'3px',
'border-color':'#52bab3',
'margin-left':'2px',
}
},
{ name: 'MyCustomInline', element: 'span', attributes: {'class': 'redText'}
}
]);
And added it in CKEditor
CKEDITOR.replace('LogBook', {
language: 'en',
uiColor: '#9AB8F3',
toolbar: [
['Undo','Redo','-'],
['Bold','Italic','Underline','Strike','-'],
['RemoveFormat','-'],
['NumberedList','BulletedList','-'],
['HorizontalRule'],
'/',
['Styles','-','Source','-','About','Maximize'],
],
removeButtons: 'Subscript,Superscript,Cut,Copy,Paste,Anchor,Scayt,PasteText,PasteFromWord,Image,SpecialChar,Link,Unlink,Table,Indent,Outdent,Blockquote,Format',
removePlugins: 'wsc,scayt',
stylesSet:'my_custom_styles',
allowedContent: true
})
But for the life of me I can't figure out how to apply a class to an element in the editor with javascript like so...
<p class="My Custom Block">Some text here</p>
I have turned off content filtering and have a custom function that inserts the above code, but the paragraph element does not get styled.
I have also tried applying styles right from my style sheet like:
<p class="redText">Some text here</p>
But again the paragraph element isn't getting styled.
Any help would be great, thank you.
After a long search I finally ran across an answer (by surtyaar towards the bottom) to add a class to a CKEditor elements.
CKEDITOR.addCss( '.redText { border-bottom: 1px dotted red }' );
This needs to be called before the CKEditor instances are declared.
From the CKEditor docs.

Load data into TinyMCE programmatically

I have multiple text-areas that I'd like to enhance using tinyMCE. I can get the text areas to show as the Rich Text Editors by initializing TinyMCE on all text areas in the page as below:
$(function () {
tinymce.init({
selector: "textarea",
statusbar: false,
setup: function (editor) {
editor.on('change', function () {
editor.save();
});
}
});
});
This also handles the sync process between the Tiny editor and the actual textarea.
My html, that populates the text areas looks like this:
<div id="divEditor1" class="container-fieldset">
<div class="editor-label-field" style="left: 50px">
<%:Html.LabelFor(Function(model) model.divEditor1, "divEditor1")%>
</div>
<div class="editor-field-fn">
<%:Html.TextBoxFor(Function(model) model.divEditor1, New With { Key .class = "ucase-input" } )%>
<%:Html.ValidationMessageFor(Function(model) model.divEditor1)%>
</div>
</div>
<div id="divEditor2" class="container-fieldset">
<div class="editor-label-field" style="left: 50px">
<%:Html.LabelFor(Function(model) model.divEditor2, "divEditor2")%>
</div>
<div class="editor-field-fn">
<%:Html.TextBoxFor(Function(model) model.divEditor2, New With { Key .class = "ucase-input" } )%>
<%:Html.ValidationMessageFor(Function(model) model.divEditor2)%>
</div>
</div>
... etc
I can read the content from the TinyMCE editors like this:
for (var i = 0; i < numberOfEditors; i++) {
sFieldValue = document.getElementById("FormFieldText" + i).value;
//sFieldValue = tinyMCE.get("FormFieldText" + i).getContent(); -> or like this, works just as well.
};
The problem I am having is getting the TinyMCE editor box to display the already existing text on page load (text read from a database), since it always shows up as an empty text box. However, the text is imported correctly in the original textarea in the background. Formatted and escaped, since it goes through some ajax calls.
I've seen I can set the content of tiny like this:
tinyMCE.get('my_editor').setContent(data);
However, I need to do it programmatically, in a way that all textareas on my page export the information to tiny. Just like the above
setup: function (editor) {
editor.on('change', function () {
editor.save();
});
}
Also, what would be the right time to un-encode the text so tiny can read it? (I assume this step is necessary)
If you initialize TinyMCE on each textarea before each textarea has its content then TinyMCE won't auto-magically go back and update itself when the textarea gets updated with content - it just does not work that way.
You could use TinyMCE APIs (as you already know from your post) to update the editor's content once you get the data. Alternatively you could delay initializing TinyMCE until after the data is fetched into each textarea.
Neither approach is better/worse - there are certainly multiple ways to solve this and they all work if implemented appropriately.
I ended up parsing the list of active tinymce instances by ID and populating each one with the corresponding text from the textareas in the background.
I came across this post looking for a solution to get the data from the database back into tinymce, and I ended up with
<textarea id="textarea"><?= htmlspecialchars($description); ?></textarea>
Just using php and the variable from the array from the database.

Copy content from WYSIWYG editor to textarea

I try to copy the content from a WYSIWYG-Editor (What you see is what you get), to a textarea and It needs to be structured. I am using Quill https://www.quilljs.com/docs/quickstart
I added a textarea, the content from the Editor is pasted into it, on click at the button Edit HTML.
$("#editHTML").click(function() {
var content = $("#editor .ql-editor").html();
$("#htmlEditForm").html(content);
});
It works, but as you can see it is not structured at all. Everything is in one line:
I need it like this:
<p>FOO</p>
<p>BAR</p>
<p class="ql-align-center"><span style="color: rgb(230, 0, 0);">I am centered</span></p>
I need it to be in a textarea, because I want to use it as HTML editor. Later on I will add another button which pastes the html code back into the WYSIWYG-editor.
The goal is, to give advanced users the possibilty to edit the HTML.
I am not sure how I can do this, I was thinking of replacing any closing tags with this: e.g. </p> -> </p>\n but it just outputs </p>\n in the textarea instead of creating a new line.
Is this even possible?
UPDATE:
I tried to use getContents as suggested:
var toolbarOptions = [
['image'],
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
['bold', 'italic', 'underline', 'strike'], // toggled buttons
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'align': [] }],
['blockquote', 'code-block'],
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
[{ 'script': 'sub'}, { 'script': 'super' }], // superscript/subscript
[{ 'direction': 'rtl' }], // text direction
[{ 'font': [ 'arial', 'Monotype Corsiva', 'fantasy', 'serif' ] }],
['clean'] // remove formatting button
];
var quill = new Quill('#editor', {
theme: 'snow',
modules: {
toolbar: toolbarOptions
}
});
$("#editHTML").click(function() {
$("#htmlEditForm").html(quill.getContents());
});
But the textarea stays empty.
quill.getContents() does just return an object:
Unfortunately Quill is not meant to do this. Quill uses it's own document model called Parchment. It tracks everything that changes in the editor so that it can understand it's contents and make changes, but it has some limits on what can be added. For example, you can't add an element that doesn't match an existing blot/format.
If someone were to edit the HTML arbitrarily and add a div for example, the editor's document model would no longer match it's contents. When switching back to the wysiwyg view, some functions wouldn't work until it tries to recreate it's document model and messes up the changes made in the HTML view.
Edit
Also, for the original problem of how to format the HTML with new lines and indention, what your seeing is how it's formatted. The editor is not breaking to new lines for each block element or adding indentation for nesting as someone would when they're writing code.
If you want it to be formatted in some way, you'd have to do it manually. Either by parsing the getContents() output or by writing or finding a script that can format HTML.
You can combine your text area with Ace Editor (https://ace.c9.io/) which allows code editing features.
Instead of detecting .click event use the built-in quill mechanism 'text-change' ... also to get the HTML of the rich text editor all in one go use .container.childNodes[0].innerHTML
quill.on('text-change', function (delta, oldDelta, source) {
// your code here e.g.
$("#htmlEditForm").html(quill.container.childNodes[0].innerHTML);
});
Text area is not capable of showing you the formats of rich text editors. A simple solution can be strip all tags if you do not want the tags in text area. Or if you want tags like bold, italic etc you have to use WYSIWYG editor. You can disable all tools of the editor and it would be looking like a textarea.

TinyMce copies the classes from the current block element when pressing Return

When using tinyMce in Wordpress, In the visual editor, I'f I'm entering content in an element and press return the classes from the parent element are copied over, i would want simply to create a new <p> element.
For example, I'm editing
<p class="blip blip--gray one-sixth push-huge--top push--bottom">d aasdas d</p>
Then i press return and the following is added:
<p class="blip blip--gray one-sixth push-huge--top push--bottom"></p>
where i would want only to add
<p></p>
I have forced_root_block option set to p
This is tinymce default behaviour.
You could add a tinymce handler to your editor that gets triggered by the keyup event. Testing for charCode 13 you can detect if ENTER has been pressed. If so you could remove the classes from the actual paragraph in the editor:
$(tinymce.get('youreditor_id').getNode()).closest('p').removeAttr('class');
This might be the solution to this problem:
tinymce.init({
selector: 'textarea', // change this value according to your HTML
keep_styles: false
});
tinymce - content filtering docs
The complete answer, based on #thariama post is
tinyMCE.editors.content.on('keyup',function(e){
if ( 13 === e.keyCode ) {
$(tinyMCE.editors.content.selection.getNode()).closest('p').removeAttr('class');
}
});

Categories