Codemirror editor is not loading content of the textarea - javascript

I'm trying to apply CodeMirror to this mini web app that I'm using. It has two has 2 textareas. I'd like to add CM for better visibility, so I can edit some stuff on the get to go. So far, I managed to apply the Eclipse theme, but the tool doesn't work anymore. It seems like CodeMirror is not copying the content to the textarea.
When I remove the Codemirror js the tool works again.
Here's my
JSFiddle
HTML
<textarea id="input" rows="10" cols="80"></textarea>
<textarea id="output" rows="10" cols="80" readonly></textarea>
JS
$('textarea').each(function(index, elem) {
CodeMirror.fromTextArea(elem, {
lineWrapping: true,
mode: "javascript",
theme: "eclipse",
lineNumbers: true,
});
});

It seems to me that the problem is in http://dean.edwards.name/packer/bindings.js, exactly, at the following code:
"#pack-script": {
disabled: false,
onclick: function() {
try {
output.value = "";
if (input.value) {
var value = packer.pack(input.value, base62.checked, shrink.checked);
output.value = value;
message.update();
}
} catch (error) {
message.error("error packing script", error);
} finally {
saveScript.disabled = !output.value;
decodeScript.disabled = !output.value || !base62.checked;
}
}
},
CodeMirror uses internal formatting, and applies custom styling to the textareas. So, the direct methods for the textarea, such as input.value won't work. You will need to tweak it so that it uses CodeMirror's methods to get/set the values as described in this guide under Content manipulation methods section.
Edit 1:
Apart from correcting some syntax errors, I got that working in this fiddle.
Changes done:
Returned the CodeMirror object from the editor function, so that it can be assigned to a variable.
Changed the onclick method. In finally block, there are undefined references to saveScript, and decodeScript, which I commented. And used CodeMirror's getValue(), and setValue() methods to get/set values respectively.
There still are some errors in the console, if observed, but that doesn't hamper the functionality of packer.

Related

Vue and Summernote - content from model not showing in form when loaded from db

Ok, I have a form in which I am using the wysiwyg editor summernote several times. When I fill in my form, the model is updated correctly, the content is shown and the results are saved correctly to the database. BUT when I want to edit and load the data from the database, the model is showing the contents correctly in the developer tools, but nothing makes it on to the screen.
This is what I have:
I have a component to load and initiate the summernote editor
<template>
<textarea class="form-control"></textarea>
</template>
<script>
export default{
props : {
model: {
required: true
},
height: {
type: String,
default: '150'
}
},
mounted() {
let config = {
height: this.height,
};
let vm = this;
config.callbacks = {
onInit: function () {
$(vm.$el).summernote("code", vm.model);
},
onChange: function () {
vm.$emit('update:model', $(vm.$el).summernote('code'));
},
};
$(this.$el).summernote(config);
}
}
</script>
I have a form (here is only one part of it) where I load the Summernote component as html-editor:
<html-editor
:model.sync="form.areaOfWork"
:class="{ 'is-invalid': form.errors.has('areaOfWork') }"
name="areaOfWork"
id="areaOfWork"></html-editor>
In the props, after loading from the DB, the data shows correctly, i.e.:
model:"<p> ... my content ...</p>"
Likewise, in my form it shows correctly, i.e.:
form: Object
areaOfWork: "<p> ... my content ...</p>"
...
But it is not shown in html-editor. I am stuck - maybe it is something super simple I am overlooking, but I did not find anything that helped me so far. Thanks for ideas and inputs
I think the problem stemmed from using jquery and vue in one project!
Because vue uses virtual DOM and jquery changes the real DOM, this makes the conflict!
So it is better not to use both of them in one project or use jquery safe in it like link below:
https://vuejsdevelopers.com/2017/05/20/vue-js-safely-jquery-plugin/
Thanks for your answer, #soroush, but that doesn't seem to be the problem. There is a communication and it seems to work. I do see my form being filled with correct data as well.
After playing around with numerous ideas, I found a simple work-around: watcher
I added
watch: {
areaOfWork: (val) => {
$('#areaOfWork').summernote("code", val);
}
},
to my template and the according variables to my data().
When I call my database and read the item, I provide the data for the watcher and it works.
Still, I do not get why vm.model in the onInit callback is not shown, but as it seems to work, I wanted to provide you with an answer. Maybe it helps someone else
HTML:
<textarea class="summernote-editor"name="memo_content"id="memo_content"</textarea>
JS:
$('#memo_content').summernote("code", response.data.res.memo_content);

TinyMCE: how to let user mark text when "readonly: true;"

I want to let users select (and copy) text within TinyMCE.
I'm not quite sure, but it seems regarding security that browsers don't allow that.
This Codepen is from the official TinyMCE site:
https://codepen.io/tinymce/pen/NGegZK
Here you can select text.
When you add there the following parameter in the 2nd line of the JavaScript as followed, then you can't longer select text.
readonly: true,
How can I set "readonly: true" and let the user still select text?
I appreciate any help.
I faced this problem too. Moreover, the inability to select text is nothing compared to the inability to click links. I've submitted an issue about this a while ago, but there is still no reaction.
You can use a workaround for now (codepen):
readonly: 1,
setup: function(editor) {
editor.on('SwitchMode', function() {
if (editor.readonly) {
editor.readonly = 1;
}
});
}
It exploits the fact that the event-blocking code uses strict comparison internally (readonly === true) while the rest of the code works fine with any other truthy value, e.g. 1. Of course, this hack might stop working after an update in the future, but it's much better than nothing.
Update: better switch to the inline mode (codepen) if you use this hack. Otherwise clicking links leads to a mess.
I have checked the source code of the lastest nightly and it seems that the behavior is hardcoded. All events are discarded if the editor is in readonly mode. Which means that selection events are discarded too :
var isListening = function (editor) {
return !editor.hidden && !editor.readonly;
};
var fireEvent = function (editor, eventName, e) {
if (isListening(editor)) {
editor.fire(eventName, e);
} else if (isReadOnly(editor)) {
e.preventDefault();
}
};
I might be wrong but I don't think you can change this behavior through customization.
Regards
I solved this issue for achieve readonly mode by myself, I would create an iframe dom node and put the editor's html segment into it.
renderReportPreview = contentHtml => {
const iframe = document.querySelector('iframe[name=preview]')
if (iframe) {
const cssLink = document.createElement('link')
// cssLink.href = 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css'
// I prefer semantic-ui, semantic-ui is more like tinyMce style
cssLink.href = 'https://cdn.bootcss.com/semantic-ui/2.3.1/semantic.min.css'
cssLink.rel = 'stylesheet'
cssLink.type = 'text/css'
iframe.contentWindow.document.head.appendChild(cssLink)
// I escape the origin editor's content, so I need decode them back
iframe.contentWindow.document.body.innerHTML = htmlDecode(contentHtml)
const allTables = iframe.contentWindow.document.body.querySelectorAll(
'table'
)
Array.from(allTables).forEach(table => {
// ui celled table for compatible semantic-ui
// table table-bordered for compatible bootstrap
table.className = 'ui celled table table-bordered'
})
this.setState({
previewRendered: true,
})
}
}
More detail on https://github.com/tinymce/tinymce/issues/4575
It was previously possible to select text in readonly mode, until the fix for #4249 broke it in 4.7.12.
We've just started tracking a fix that allows text to be selected and links to be clicked, follow either of the tickets linked here to be updated when we release a fix.

Handle Ctrl+Z (undo/redo) for text editor in single page application

I have single page application which consists of a text editor (kendo Editor). The data in the text editor are replaced somewhat like this
$("#editor").kendoEditor({
resizable: {
content: false,
toolbar: true
}
});
var editor = $("#editor").data("kendoEditor");
var setValue = function () {
editor.value($("#value").val());
};
see demo here.
The Issue:
So I am changing record of A then save it. Then I switch to B. Now if I do Ctrl+Z the text editor shows the record of A. How can I prevent this behavior.
Is a way to remove the undo history on demand, or something which would prevent the text editor replacing text with previous record?
Updated: Better Solution.
I contacted Kendo devs and they provided a neat solution.
var editor = $("#editor").data("kendoEditor");
editor.undoRedoStack.clear();
Note: this function is not documented in the public api and is
may change in newer version. This is working as of version
2016.3.1118
demo
Old Solution.
I ended up destroying and rebinding the widget to the textarea.
http://dojo.telerik.com/OjIZe
$("#destroy").click(function(){
var copy=$("#editor").clone();
$("#editor").data('kendoEditor').wrapper.find("iframe").remove();
$("#editor").data('kendoEditor').destroy();
$("#test").empty();
$("#test").append(copy);
$("#editor").kendoEditor({ resizable: {
content: false, toolbar: true
}
});
});

Froala editor v2 (new) inline destroy bug(?)

Using the newest version of the froala editor (v2) doesn't seem to work when destroying an inline editor.
It leaves this element in the editor element: <i class="fa fa-code"></i>. You can see this behaviour if you go to the inline example-site: https://www.froala.com/wysiwyg-editor/v2.0/docs/examples/inline
And enter the following into the developer console: $('div#froala-editor').froalaEditor('destroy');
Does anyone know how to mend this? It also leaves the editors wrappers inside the editorcontainer and preserves editorclasses on it even though the documentation states that the destroy command will remove the editor in its entirety and the element back to its pre-init state.
Thank you very much!
Please refer this JSFiddle -
https://jsfiddle.net/froala/8yxLcg5k/
$(function() {
$('div#froala-editor').froalaEditor();
});
// Destroy action.
$('a#btn-destroy').on('click', function (e) {
e.preventDefault();
if ($('div#froala-editor').data('froala.editor')) {
$('div#froala-editor').froalaEditor('destroy');
}
});
// Initialize action.
$('a#btn-init').on('click', function (e) {
e.preventDefault();
if (!$('div#froala-editor').data('froala.editor')) {
$('div#froala-editor').froalaEditor();
}
});

Changing the default font family in TinyMCE

I've successfully changed the default font inside the editor using the documentation here but that leaves me with a problem. The original default font no longer works in the font drop down list.
Original default: Verdana
New default: MyCustomFont
When I type into the editor I see my MyCustomFont font by default. If I try to change that to Verdana (original default) nothing happens. I can change it to any font family except Verdana. I noticed also that when I select MyCustomFont in the drop down list the content gets surrounded with a span with inline styles. This does not happen with the original default font (hence why nothing happens).
It seems to me like there's a key piece of documentation missing - how to tell the editor (the font feature in particular) that the font I've defined by default in the css is the default font.
I've Googled quite a bit but had no results. Everybody else seems to be settling for the documentation mentioned above. Am I the only one having this problem? If not, please help! :)
Please note, the answers to this question do not answer my question.
maybe too late but...
$('.tinymce').tinymce({
setup : function(ed) {
ed.onInit.add(function(ed) {
ed.execCommand("fontName", false, "Arial");
ed.execCommand("fontSize", false, "2");
});
}
});
EDIT
For TinyMCE 4, as #jason-tolliver and #georg states, the syntax is:
ed.on('init', function (ed) {
ed.target.editorCommands.execCommand("fontName", false, "Arial");
});
// Init TinyMCE
$('#content').tinymce({
setup : function(ed)
{
ed.on('init', function()
{
this.getDoc().body.style.fontSize = '12px';
this.getDoc().body.style.fontFamily = 'serif';
});
}
});
For those who init timymce with tinymce.init({ and cannot implement Radius Kuntoro answer directly.
My init looks like
tinymce.init({
selector: '#editor',
menubar: false,
plugins: ['bbcode'],
toolbar: 'undo redo | bold italic underline',
setup : function(ed)
{
ed.on('init', function()
{
this.getDoc().body.style.fontSize = '12';
this.getDoc().body.style.fontFamily = 'Arial';
});
},
});
For TinyMCE 4.6.3 this seems to be the way to go:
tinymce.init({
setup: function (ed) {
ed.on('init', function (e) {
ed.execCommand("fontName", false, "Verdana");
});
}
});
As refer to TinyMce website you can embed style sheet within your init function like this :
tinymce.init({
content_css : 'path/to/style/sheet',
body_class: 'define-class-name-without-dot-at-the-first'
});
It works and you do not need to setup anything.
check it out on tinyMCE webpage
Some of you will be working within the confines of the TinyMCE EditorManager, which offers two events: AddEditor and RemoveEditor. When a new instance of TinyMCE is being spawned and AddEditor is fired, the editor isn't actually initialized and so calling getDoc() will return null.
What you need to do is create an init listener within.
tinyMCE.EditorManager.on('AddEditor', function (event) {
... other code ...
event.editor.on('init', function() {
this.activeEditor.getDoc().body.style.fontSize = '12px';
this.activeEditor.getDoc().body.style.fontFamily = 'Times New Roman';
});
... other code ...
}
});
This is at least true as of version 4.3.8
I had difficulties with all solutions here in tinymce 4.x
I couldn't change neither fontsize nor fontname. After trying out a lot I found the solution.
First of all I can confirm Jareds answer, thank you for it! Those two commands will not work by default settings:
tinymce.EditorManager.execCommand("fontName", false, "12px");
tinymce.EditorManager.execCommand("fonSize", false, "Arial");
The default fontsize size is "pt", not "px." So either define displayed fontSize as "px" by [fontsize_formats][1] or just handover the desired size with "pt". With tinymce.EditorManager.execCommand tinymce is also not happy. You have to handover the whole font-family like 'arial, helvetica, sans-serif'. These commands worked on my site:
tinymce.EditorManager.execCommand("fontName", false, "12pt");
tinymce.EditorManager.execCommand("fonSize", false, "arial, helvetica, sans-serif");
None of the above solutions worked for me. So, somehow I managed to fix it using custom logic.
editor.on('change', function (e) {
let node = e.target.selection.getNode();
if (node.nodeName === 'P' || node.parentNode.nodeName === 'BODY') {
editor.dom.setStyle(node, 'font-size', "16px");
}
tinymce.triggerSave(); // to keep your textarea synced with above changes
});
This worked for me:
Look for functions.php in root of your themes directory inside /wp-content/themes/yourtheme/, open it up and add one line after php tag.
add_editor_style('custom-editor-style.css');
In the same directory, create a file called custom-editor-style.css with the following lines in it:
#import url(https://fonts.googleapis.com/css?family=Open+Sans:400,700);
* { font-family: 'Open Sans', sans-serif, Arial, Helvetica;}
Go ahead, clear your browser's cache and this is what you’ll see.
Refer link: https://blog.phi9.com/wordpress-editor-and-its-font/
I tried doing this way.
I use TinyMce 5 and inside the editor there is a body tag generated.
While initialising the editor I set the forced_root_block:'div', which means everytime something is being typed my root element will always be a div.
let tinyMceBody = tinymce.activeEditor.getBody();
let divs = $(tinyMceBody).children('div');
for(let i =0; i<divs.length; i++) {
divs[i].style.fontFamily = 'Nunito';
}
So I try catching all the root elements and set default styles to them.
When you edit something, tinymce surrounds whatever you have edited with a span block with a style attribute, so what ever you manually edit in the editor will be overrided. If you don't edit the text in editor then the default styling that we have attached on the parent element forced_root_block:'div' will be retained.
Try formulating a solution as per your custom req. using the above mentioned technique. Seems like the library doesn't have a prominent internal support for this. z
P.S:-
tinymce.activeEditor.dom.setStyles(tinymce.activeEditor.dom.select('div'), {'font-family' : 'Nunito'});
applies to all divs , but I wanted to apply only for the first level children of the body tag and not all divs( includes children of children). Otherwise this could be a solution too.
For tinymce 5 you can add fullpage plugin to plugins array then new key called
fullpage_default_font_family but i don't know if it works the same way for old versions or not.
This is the Answer. It work for me:
STEP # 1:
Look for functions.php in root of your themes directory inside /wp-content/themes/yourtheme/, open it up and add one line after php tag.
add_editor_style('custom-editor-style.css');
STEP # 2:
In the same directory, create a file called custom-editor-style.css with below lines in it
#import url(https://fonts.googleapis.com/css?family=Open+Sans:400,700);
* { font-family: 'Open Sans', sans-serif, Arial, Helvetica;}
Go ahead, clear your browsers cache and this is what you’ll see.
Tony Ngo

Categories

Resources