How to change tinymce editor font style and size on the fly? - tinymce

tinymce's FAQ explains how to change the editor's default font style by referencing a custom content_css file.
But I'd like to change the editor's font style on the fly programmatically. Any ideas? Thanks.

This is possible, but requires some knowledge.
You will need to call something like
self.switchStyle(url, ed);
where switchStyle is
// url is the url to the stylesheet file to be added to the editor iframes head
// ed is the editor object or editor id
switchStyle: function(url, ed) {
if (typeof ed != 'object') {
ed = tinymce.get(ed);
}
//replace the custom content_css if set
var url_to_replace = ed.getParam('content_css');
var doc = ed.getDoc();
var $doc = $(doc);
var sheets_urls = [];
if (url_to_replace){
sheets_urls.push(url_to_replace);
}
// remove all stylesheets from sheets_urls
$doc.find('link').each(function() {
if (tinymce.inArray(sheets_urls, $(this).attr('href').split('?')[0]) !== -1) {
$(this).remove();
}
});
var link = doc.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
// setstylesheet
$doc.find('head:first').append(link);
},

Related

tinyMCE editor setting localised path as src of uploaded image

I've setup tinyMCE to do image uploading and it displays uploaded images in the editor, but on inspecting the source of the editors HTML I can see that the src attribute is set like it would be a file path:
<img src="../../../api/images/1"/>
I have a file_picker_callback which POSTs the image to my backend server to save the image, and returns an absolute URL in the "location" key as specified in the tinyMCE docs: https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_url
But I am unsure why regardless of providing an absolute URL the src set on the image begins with "../../../".
The relevant tinyMCE configuration:
tinymce.init({
file_picker_types: 'file image',
file_picker_callback: function(cb, value, meta) {
let tinyMCE = this;
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*,.doc,.docx,.txt,.rtf,.odt,.pdf');
input.onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function () {
// Register the blob in TinyMCEs image blob registry.
var id = 'blobid' + (new Date()).getTime();
var blobCache = tinyMCE.editorUpload.blobCache;
var base64 = reader.result.split(',')[1];
var blobInfo = blobCache.create(id, file, base64);
blobCache.add(blobInfo);
backend.save(file).then(
fileLocation => {
let options = {};
if (meta.filetype == 'file') {
options = {
title: file.name,
text: 'My Attachment'
};
}
cb(fileLocation, options);
},
(/* error */) => {
blobCache.removeByUri(blobInfo.blobUri());
}
);
};
reader.readAsDataURL(file);
};
input.click();
}
});
I can see that there is an options object I can pass to the callback which sets some element attributes of the image, but I can't find a reference to what this object can contain in the docs :(
Would like some help to solve this and get absolute URLs in my image srcs, thanks
convert_urls: false,
By default all URLs are automatically converted to relative URLs. If you want to insert the real URL of the uploaded image, set convert_urls option to false. It will restore URLs to their original values.

How to add html in autocomplete ace editor?

Somebody can help me how to custom autocomplete for ace editor?
I need to display the emoji images such as below:
This editor is work well for me, but i need to insert the emoji images to the result of autocomplete.
var editor = ace.edit('editor');
editor.setTheme('ace/theme/github');
editor.getSession().setMode('ace/mode/markdown');
editor.$blockScrolling = Infinity; //prevents ace from logging annoying warnings
editor.getSession().on('change', function () {
draceditor.val(editor.getSession().getValue());
});
editor.setOptions({
enableBasicAutocompletion: true,
enableSnippets: true,
enableLiveAutocompletion: true
});
// Ace autocomplete
var emojiWordCompleter = {
getCompletions: function(editor, session, pos, prefix, callback) {
var wordList = emojis; // list emojis from `atwho/emojis.min.js`
var obj = editor.getSession().getTokenAt(pos.row, pos.column.count);
var curTokens = obj.value.split(/\s+/);
var lastToken = curTokens[curTokens.length-1];
if (lastToken[0] == ':') {
console.log(lastToken);
callback(null, wordList.map(function(word) {
return {
caption: word,
value: word.replace(':', '') + ' ',
meta: 'emoji' // this should return as text only.
};
}));
}
}
}
editor.completers = [emojiWordCompleter]
my bad idea, i try with this meta: '<img src="/path/to/emoji.png">', but of course it can't be work.
Any idea how to solve this? Thank so much before..
There is no built in way to do this.
You can create a custom renderer similar to https://github.com/c9/c9.ide.language.core/blob/bfb5dd2acc/completedp.js#L44, or modify https://github.com/ajaxorg/ace/blob/master/lib/ace/autocomplete/popup.js and create pull request to ace.

Can I use slider for font size plugin in TinyMCE editor

I am using TinyMCE plugin. Currently, my font-size option comes with list dropdown but I want slider for font size.
Is this possible with the TinyMCE. Anyone know how can I achieve this with TinyMCE editor?
TinyMCE does not have a built in way to select font size via a "slider". As TinyMCE is open source you can always modify the editor's code to meet your needs.
If you look in the main tinymce.js file you will find code like this:
editor.addButton('fontsizeselect', function() {
var items = [], defaultFontsizeFormats = '8pt 10pt 12pt 14pt 18pt 24pt 36pt';
var fontsize_formats = editor.settings.fontsize_formats || defaultFontsizeFormats;
each(fontsize_formats.split(' '), function(item) {
var text = item, value = item;
// Allow text=value font sizes.
var values = item.split('=');
if (values.length > 1) {
text = values[0];
value = values[1];
}
items.push({text: text, value: value});
});
return {
type: 'listbox',
text: 'Font Sizes',
tooltip: 'Font Sizes',
values: items,
fixedWidth: true,
onPostRender: createListBoxChangeHandler(items, 'fontsize'),
onclick: function(e) {
if (e.control.settings.value) {
editor.execCommand('FontSize', false, e.control.settings.value);
}
}
};
});
This is how the current select list is implemented - you can always replace this with logic to implement font selection in a different manner.

html2canvas loading issue when saving the image

I am using the following code to save the content of div (image and text) as an image using html2canvas.
$(function() {
$("#save").click(function() {
var flag = true;
var imgpath = document.getElementById('file').value;
if(imgpath.length == 0)
{
alert('Please select image file to upload.');
flag = false;
}
else
{
html2canvas($('.body740'), {
onrendered: function(canvas) {
theCanvas = canvas;
var url = canvas.toDataURL("image/png");
var br = document.createElement("br");
var center = document.createElement("center");
var newImg = document.createElement("img"); // create img tag
newImg.src = url;
$(".body740").hide();
$("#canvas").show(); //div where the final image is shown
document.getElementById("rsimg").src=url;
document.getElementById("rsa").href=url;
}
});
}
});
});
This is my link : http://www.aamras.com/greetings2/
But, when I click the save image button, it takes a lot of time to generate the image. Why is it taking so much time to load? What is the issue?
Solved : Change the version of html2cannvas. I was previously using html2canvas 0.5.0-alpha 2014 version
I Switched to html2canvas 0.5.0-alpha1. It generates the image properly and takes no time to do so. You can download the files from https://github.com/niklasvh/html2canvas/releases

can I build a css class on the fly in tiny mce?

I'm using tiny mce, but I found it adds multiple spans with inline styles to the content for any applied style. Inline styles are not W3c Compliant, so must avoid inline css. Is it possible to create css class on the fly and apply to the selection, while editing content in tiny mce ?
Yes that is possible, but it took me some effort. What needs to be done is to write the class into the head of the editors iframe. Here is some example code which should work for IE,FF, Safari and point you into the right direction:
fonturl = "http://myfonts.com/arial.ttf"
csstext_to_add = '#font-face {font-family: "ownfont";src: url("'+fonturl+'");}'; // example
iframe_id = ed.id;
with(document.getElementById(iframe_id).contentWindow){
var h=document.getElementsByTagName("head");
if (!h.length) {
return;
}
var newStyleSheet=document.createElement("style");
newStyleSheet.type="text/css";
h[0].appendChild(newStyleSheet);
try{
if (typeof newStyleSheet.styleSheet !== "undefined") {
newStyleSheet.styleSheet.cssText = csstext_to_add;
}
else {
newStyleSheet.appendChild(document.createTextNode(csstext_to_add));
newStyleSheet.innerHTML=csstext_to_add;
}
}
catch(e){}
}
It is also possible to add that class as option into a dropdown (what takes some effort).
Thariama's answer was perfect. I'm using the tinyMCE jQuery connector for some of my pages and I have multiple instances of tinyMCE on the page. I made some modifications, but essentially its the same thing. I've created a text area field on the page that people can provide their own CSS. Also, I needed to change some CSS rules on the fly...
// function to change tinyMCE css on the fly
function checkCustomCSS() {
var $css = $('#page_css'),
newcss;
if ($css.val().length > 0) {
// since front end, we are wrapping their HTML in a wrapper and
// the tinyMCE edit iFrame is just using <body>, we need to change
// some rules so they can see the changes
newcss = $css.val().replace('#content_wrapper', 'body');
// loop through each tinyMCE editor and apply the code changes
// You could check the editor.id to make sure that the correct
// editor gets the appropriate changes.
$.each(tinyMCE.editors, function() {
var $this = $(this),
editorID = $this[0].id,
$ifrm = $('#' + editorID+ '_ifr'),
cwin, head, sheet;
if ($ifrm.length > 0 /* && editorID === 'OUR_EDITOR_ID_NAME' */) {
cwin = $ifrm[0].contentWindow;
head = cwin.document.getElementsByTagName("head");
if (!head.length) {
return;
}
sheet = cwin.document.createElement("style");
sheet.type = "text/css";
head[0].appendChild(sheet);
try {
if (typeof sheet.styleSheet !== "undefined") {
sheet.styleSheet.cssText = newcss;
} else {
sheet.appendChild(cwin.document.createTextNode(newcss));
sheet.innerHTML = newcss;
}
} catch (e) {}
}
});
}
}
Then in the tinyMCE init call I added and onInit call to setup changes to the #page_css , like this:
oninit: function() {
$('#page_css').on('change', function() {
checkCustomCSS();
});
}
Works like a charm.