Ace modes for XML, JSON work, but not liquid - ace-editor

Setting an ACE editor instance to JSON or XML language mode works great.
But my statement
LiquidMode = ace.require("ace/mode/liquid").Mode,
// fails, ace.require("ace/mode/liquid") returns undefined
Yet the ace/mode/liquid file is defined on the cdn and is returned by it.
Thank you for any ideas or alternatives.
The cdn call and more:
<script src="https://cdn.jsdelivr.net/g/ace#1.2.6(noconflict/ace.js+noconflict/mode-hjson.js+noconflict/mode-liquid.js+noconflict/mode-xml.js+noconflict/theme-chrome.js)">
</script>
// Javascript file
var XMLMode = ace.require("ace/mode/xml").Mode,
JSONMode = ace.require("ace/mode/json").Mode,
LiquidMode = ace.require("ace/mode/liquid").Mode; // fails,
// ace.require("ace/mode/liquid") returns undefined
...
ace_session.setMode(new JSONMode()); // works great
...
ace_session.setMode(new LiquidMode());

When you load ace.js with multiple file syntax, dynamic loading doesn't work, because ace can't determine the url from which it was loaded.
As a workaround you can use
var url = "https://cdn.jsdelivr.net/ace/1.2.6/noconflict/"
ace.config.set("basePath", url)
see https://github.com/ajaxorg/ace/blob/v1.2.6/lib/ace/config.js#L185
Note that you don't need to pass mode object, setMode("ace/mode/liquid") works too.
<script src="https://cdn.jsdelivr.net/g/ace#1.2.6(noconflict/ace.js+noconflict/mode-json.js+noconflict/mode-liquid.js+noconflict/mode-xml.js+noconflict/theme-chrome.js)">
</script>
<script >
// Javascript file
var XMLMode = ace.require("ace/mode/xml").Mode,
JSONMode = ace.require("ace/mode/json").Mode,
LiquidMode = ace.require("ace/mode/liquid").Mode;
debugger
var editor = ace.edit()
var url = "https://cdn.jsdelivr.net/ace/1.2.6/noconflict/";
ace.config.set("basePath", url)
editor.setValue("use core::rand::RngUtil;\n\nfn main() {\n \n}", -1)
editor.setOptions({
autoScrollEditorIntoView: true,
maxLines: 15,
});
document.body.appendChild(editor.container)
editor.session.setMode("ace/mode/rust");
</script>

Related

Rich Text Editor (WYSIWYG) in CRM 2013

Sometimes it is useful to have the HTML editor in CRM interface. It is possible to implement the editor directly to CRM 2013. As editor we will use ckeditor which allows to use it without installation on the server.
Identify the field where you would like to use the rich text editor.
Create html-webresource which will define ckeditor. Go to Settings-Customizations-Customize the System-Web Resources.
In html editor of web resource, select the Source tab and insert the following code:
<html>
<head>
<title></title>
<script src="//cdn.ckeditor.com/4.4.7/standard/ckeditor.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function getTextFieldName()
{
var vals = new Array();
if (location.search != "")
{
vals = location.search.substr(1).split("&");
for (var i in vals)
{
vals[i] = vals[i].replace(/\+/g, " ").split("=");
}
//look for the parameter named 'data'
for (var i in vals)
{
if (vals[i][0].toLowerCase() == "data")
{
var datavalue = vals[i][2];
var vals2 = new Array();
var textFieldName = "";
vals2 = decodeURIComponent(datavalue).split("&");
for (var i in vals2)
{
var queryParam = vals2[i].replace(/\+/g, " ").split("=");
if (queryParam[0] != null && queryParam[0].toLowerCase() == "datafieldname")
{
textFieldName = queryParam[1];
}
}
if (textFieldName == "")
{
alert('No "dataFieldName" parameter has been passed to Rich Text Box Editor.');
return null;
}
else
{
return textFieldName;
}
}
else
{
alert('No data parameter has been passed to Rich Text Box Editor.');
}
}
}
else
{
alert('No data parameter has been passed to Rich Text Box Editor.');
}
return null;
}
CKEDITOR.timestamp = null;
​// Maximize the editor window, i.e. it will be stretched to target field
CKEDITOR.on('instanceReady',
function( evt )
{
var editor = evt.editor;
editor.execCommand('maximize');
});
var Xrm;
$(document).ready(function ()
{
​ // Get the target field name from query string
var fieldName = getTextFieldName();
var Xrm = parent.Xrm;
var data = Xrm.Page.getAttribute(fieldName).getValue();
document.getElementById('editor1').value = data;
/*
// Uncomment only if you would like to update original field on lost focus instead of property change in editor
//Update textbox on lost focus
CKEDITOR.instances.editor1.on('blur', function ()
{
var value = CKEDITOR.instances.editor1.getData();
Xrm.Page.getAttribute(fieldName).setValue(value);
});
*/
// Update textbox on change in editor
CKEDITOR.instances.editor1.on('change', function ()
{
var value = CKEDITOR.instances.editor1.getData();
Xrm.Page.getAttribute(fieldName).setValue(value);
});
// Following settings define that the editor allows whole HTML content without removing tags like head, style etc.
CKEDITOR.config.allowedContent = true;
CKEDITOR.config.fullPage = true;
});
</script>
<meta>
</head>
<body style="word-wrap: break-word;">
<textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"></textarea>
</body>
</html>
Note:
As you can see, there are a few important sections
a) The following code loads the ckeditor and jquery from web so that they don't have to be installed on server.
<script src="//cdn.ckeditor.com/4.4.7/standard/ckeditor.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
b) Function getTextFieldName() which gets the name of target field where should be rich text editor placed. This information is obtained from query string. This will allow to use this web resource on multiple forms.
c) Initialization of ckeditor itself - setting the target field and properties of ckeditor. Also binding the editor with predefined textarea on the page.
Open the form designer on the form where you would like to use ​WYSIWYG editor. Create a text field with sufficient length (e.g. 100 000 chars) which will hold the html source code.
Insert the iframe on the form. As a webresource use the resource created in previous steps. Also define Custom Parameter(data) where you should define the name of the text field defined in step 4. In our situation we created new_bodyhtml text field so the parameter holds this value. This value is returned by the getTextFieldName() of the web resource.
Do not forget to save and publish all changes in CRM customization otherwise added webresources and updated form are not available.
That's all, here is example how it looks like:
Yes, you can use CKEditor, but when I implemented the CKEditor on a form, it turns out it is quite limited in the functionality in provides. Also, the HTML it generates leaves much to be desired. So, I tried a similar idea to Pavel's but using a backing field to store the actual HTML using TinyMCE. You can find the code here:
Javascript
HTML
Documentation
I have package my solution as a managed and unmanaged CRM solution that can be imported and utilised on any form. Moreover, it works on both CRM 2013 and CRM 2015

Twitter Bootstrap 3 dropdown menu disappears when used with prototype.js

I have an issue when using bootstrap 3 & prototype.js together on a magento website.
Basically if you click on the dropdown menu (Our Products) & then click on the background, the dropdown menu (Our Products) disappears (prototype.js adds "display: none;" to the li).
Here is a demo of the issue:
http://ridge.mydevelopmentserver.com/contact.html
You can see that the dropdown menu works like it should without including prototype.js on the page at the link below:
http://ridge.mydevelopmentserver.com/
Has anyone else ran into this issue before or have a possible solution for the conflict?
EASY FIX:
Just replace Magento's prototype.js file with this bootstrap friendly one:
https://raw.github.com/zikula/core/079df47e7c1f536a0d9eea2993ae19768e1f0554/src/javascript/ajax/original_uncompressed/prototype.js
You can see the changes made in the prototype.js file to fix the bootstrap issue here:
https://github.com/zikula/core/commit/079df47e7c1f536a0d9eea2993ae19768e1f0554
NOTE: JQuery must be include in your magento skin before prototype.js.. Example:
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/prototype/prototype.js"></script>
<script type="text/javascript" src="/js/lib/ccard.js"></script>
<script type="text/javascript" src="/js/prototype/validation.js"></script>
<script type="text/javascript" src="/js/scriptaculous/builder.js"></script>
<script type="text/javascript" src="/js/scriptaculous/effects.js"></script>
<script type="text/javascript" src="/js/scriptaculous/dragdrop.js"></script>
<script type="text/javascript" src="/js/scriptaculous/controls.js"></script>
<script type="text/javascript" src="/js/scriptaculous/slider.js"></script>
<script type="text/javascript" src="/js/varien/js.js"></script>
<script type="text/javascript" src="/js/varien/form.js"></script>
<script type="text/javascript" src="/js/varien/menu.js"></script>
<script type="text/javascript" src="/js/mage/translate.js"></script>
<script type="text/javascript" src="/js/mage/cookies.js"></script>
<script type="text/javascript" src="/js/mage/captcha.js"></script>
I've also used code from here: http://kk-medienreich.at/techblog/magento-bootstrap-integration-mit-prototype-framework but without a need to modify any source. Just put code below somewhere after prototype and jquery includes:
(function() {
var isBootstrapEvent = false;
if (window.jQuery) {
var all = jQuery('*');
jQuery.each(['hide.bs.dropdown',
'hide.bs.collapse',
'hide.bs.modal',
'hide.bs.tooltip',
'hide.bs.popover',
'hide.bs.tab'], function(index, eventName) {
all.on(eventName, function( event ) {
isBootstrapEvent = true;
});
});
}
var originalHide = Element.hide;
Element.addMethods({
hide: function(element) {
if(isBootstrapEvent) {
isBootstrapEvent = false;
return element;
}
return originalHide(element);
}
});
})();
Late to the party, but found this github issue which links to this informational page which links to this jsfiddle which works really nicely. It doesn't patch on every jQuery selector and is, I think, the nicest fix by far. Copying the code here to help future peoples:
jQuery.noConflict();
if (Prototype.BrowserFeatures.ElementExtensions) {
var pluginsToDisable = ['collapse', 'dropdown', 'modal', 'tooltip', 'popover'];
var disablePrototypeJS = function (method, pluginsToDisable) {
var handler = function (event) {
event.target[method] = undefined;
setTimeout(function () {
delete event.target[method];
}, 0);
};
pluginsToDisable.each(function (plugin) {
jQuery(window).on(method + '.bs.' + plugin, handler);
});
};
disablePrototypeJS('show', pluginsToDisable);
disablePrototypeJS('hide', pluginsToDisable);
}
Using the * selector with jQuery is not advised. This takes every DOM object on the page and puts it in the variable.
I would advice to select the elements that use a Bootstrap component specific. Solution below only uses the dropdown component:
(function() {
var isBootstrapEvent = false;
if (window.jQuery) {
var all = jQuery('.dropdown');
jQuery.each(['hide.bs.dropdown'], function(index, eventName) {
all.on(eventName, function( event ) {
isBootstrapEvent = true;
});
});
}
var originalHide = Element.hide;
Element.addMethods({
hide: function(element) {
if(isBootstrapEvent) {
isBootstrapEvent = false;
return element;
}
return originalHide(element);
}
});
})();
Very late to the party: if you don't feel like having extra scripts running, you can add a simple CSS override to prevent it from getting hidden.
.dropdown {
display: inherit !important;
}
Generally the use of !important in CSS is advised against, but I think this counts as an acceptable use in my opinion.
see http://kk-medienreich.at/techblog/magento-bootstrap-integration-mit-prototype-framework/.
It's quite an easy fix to validate the namespace of the element clicked.
Add a validation function to prototype.js:
and after that, validate the namespace before the element will be hidden:
hide: function(element) {
element = $(element);
if(!isBootstrapEvent)
{
element.style.display = 'none';
}
return element;
},
Replacing Magento's prototype.js file with the bootstrap friendly version suggested by MWD is throwing an error that prevents saving configurable products:
Uncaught TypeError: Object [object Array] has no method 'gsub' prototype.js:5826
(Running Magento Magento 1.7.0.2)
evgeny.myasishchev solution worked great.
(function() {
var isBootstrapEvent = false;
if (window.jQuery) {
var all = jQuery('*');
jQuery.each(['hide.bs.dropdown',
'hide.bs.collapse',
'hide.bs.modal',
'hide.bs.tooltip'], function(index, eventName) {
all.on(eventName, function( event ) {
isBootstrapEvent = true;
});
});
}
var originalHide = Element.hide;
Element.addMethods({
hide: function(element) {
if(isBootstrapEvent) {
isBootstrapEvent = false;
return element;
}
return originalHide(element);
}
});
})();
This answer helped me to get rid of bootstrap and prototype conflict issue.
As #GeekNum88 describe the matter,
PrototypeJS adds methods to the Element prototype so when jQuery tries
to trigger the hide() method on an element it is actually firing the
PrototypeJS hide() method, which is equivalent to the jQuery
hide() method and sets the style of the element to display:none;
As you suggest in the question itself either you can use bootstrap friendly prototype or else you can simply comment out few lines in bootstrap as bellow,
inside the Tooltip.prototype.hide function
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
I realise that this is a pretty old post by now, but an answer that no-one else seems to have mentioned is simply "modify jQuery". You just need a couple of extra checks in jQuery's trigger function which can be found around line 332.
Extend this if statement:
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
... to say this:
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
// Check for global Element variable (PrototypeJS) and ensure we're not triggering one of its methods.
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) &&
( !window.Element || !jQuery.isFunction( window.Element[ type ] ) ) ) {
"#6170" only seems to be mentioned in jQuery once so you can do a quick check for that string if you're working with a compiled (complete) jQuery library.

Loading excanvas polyfill via Modernizr.load fails

I'm attempting to load the excanvas polyfill in the page-specific js file for my page. This script file is inserted after the body tag on my page.
The odd bit is that if I use
<script type='text/javascript' src='/Scripts/polyfills/excanvas.compiled.js'></script>
in my head tag, everything works great, but I don't necessarily want to load this script for HTML5 compliant browsers if I don't have to.
So naturally I tried to use Modernizr to load it selectively. This is my perfectly executing, but non-functioning javascript code:
<!-- language: lang-js -->
$(function () {
Modernizr.load({
test: Modernizr.canvas,
nope: '/Scripts/polyfills/excanvas.compiled.js',
complete: function () {
setImage();
}
});
});
This seems to work fine. The excanvas script appears to load successfully.
The setImage function creates the canvas element dynamically and adds it to a div on the page.
This works fine in IE9 but fails to render in IE8.
<!-- language: lang-js -->
function setImage() {
var canvasHello = document.createElement('canvas');
canvasHello.id = 'canvasHello';
$('#divContent').append(canvasHello);
if (!Modernizr.canvas) {
G_vmlCanvasManager.initElement(canvasHello);
}
var canvasContext = canvasHello.getContext('2d');
canvasContext.width = 800;
canvasContext.height = 600;
canvasContext.fillStyle = "#000000";
canvasContext.fillRect(0, 0, 600, 800);
var img = document.createElement('img');
img.src = '/Content/images/hello.png';
img.onload = function () {
canvasContext.drawImage(img, 100, 25, 100, 100);
}
}
Did I miss something or does the excanvas script not function outside of the head tag?
in the given requirement you could use the IE conditional statements like this...
<!--[if lt IE 9]>
<script src="script/excanvas.js"></script>
<![endif]-->
would suffice....
the statement will only be understood by IE version less than 9 and the script tag gets attached.
The only thing you missed is the instructions on how to use excanvas:
The excanvas.js file must be included in the page before any occurrences of canvas elements in the markup. This is due to limitations in IE and we need to do our magic before IE sees any instance of in the markup. It is recommended to put it in the head.

does tapestry 5 support vbscript?

I've been asked to 'sniff' users' windows username via a vbscript snippet and am having trouble getting this to work in the tapestry (5.1.0.5) application.
It seems tapestry is trying to interpret the vbscript as javascript and therefore failing.
The vbscript snippet (below) is embedded within a component which is in turn loaded conditionally inside a zone as part of a multizoneupdate.
pseudo tml:
<page>
<t:zone>
<t:if>
<t:mycomponent>
<vbscript />
vbscript:
<script type="text/vbscript" language="vbscript">
Dim shell
set shell = createobject("wscript.shell")
set env = shell.environment("process")
set field = document.getElementById("windowsLoginField")
if field is nothing then
alert("no field")
else
field.value = env("username")
end if
</script>
I am aware that this should only work for IE, however other browsers should fail gracefully (not run the script).
When the zone is re-loaded in a state where the vbscript should be rendered, I get the following error in firebug:
missing ; before statement
Dim shell
This is because the script is being evaluated by prototypejs:
evalScripts: function() {
return this.extractScripts().map(function(script) { return eval(script) });
},
Does anyone know of a way to avoid prototype evaluating this script so that it can make it through and be executed as vbscript?
I notice there is no #IncludeVbScriptLibrary annotation ...
thanks, p.
Tapestry inherits this problem from prototype. One solution is to patch the prototype extractScripts and evalScripts so that they do what you want when they see vbscript.
This code works (tested in IE7 and Chrome), but it could be made more flexible (keys off of type and not language for instance)
<script type="text/javascript">
String.prototype.extractScripts = function() {
var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
var matchVBScript = new RegExp('<script.*type=(["\'])text\/vbscript\\1');
return (this.match(matchAll) || []).map(function(scriptTag) {
return [matchVBScript.match(scriptTag), (scriptTag.match(matchOne) || ['', ''])[1]];
});
}
String.prototype.evalScripts = function() {
return this.extractScripts().map(function(script) {
// if it's vbscript and we're in IE then exec it.
if ( script[0] && Prototype.Browser.IE ) return execScript(script[1], "VBScript");
// if it's not vbscript then eval it
if ( !script[0] ) return eval(script[1]);
});
}
</script>

How to inject CSS located on /skin?

I want to inject a css file located on the skin folder in a browser page.
It is located on chrome://orkutmanager/skin/om.css, accessing manually show the file contents correctly.
I've tried this, but it's not working... What am I missing, or is it impossible?
You can also use the nsIStyleSheetService:
loadCSS: function() {
var sss = Components.classes["#mozilla.org/content/style-sheet-service;1"]
.getService(Components.interfaces.nsIStyleSheetService);
var ios = Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var uri = ios.newURI("chrome://addon/skin/style.css", null, null);
if(!sss.sheetRegistered(uri, sss.USER_SHEET))
sss.loadAndRegisterSheet(uri, sss.USER_SHEET);
}
If you use USER_SHEET, the website's own CSS rules have higher priority than yours. Using AGENT_SHEET, your CSS should have higher priority.
In any way I needed to enforce some rules by using hte !important keyword.
I found this workaround. Read the file then inject it's contents...
function Read(file)
{
var ioService=Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var scriptableStream=Components
.classes["#mozilla.org/scriptableinputstream;1"]
.getService(Components.interfaces.nsIScriptableInputStream);
var channel=ioService.newChannel(file,null,null);
var input=channel.open();
scriptableStream.init(input);
var str=scriptableStream.read(input.available());
scriptableStream.close();
input.close();
return str;
}
var style = $("<style type='text/css' />");
style.html(Read("chrome://orkutmanager/skin/om.css"));
$("head").append(style);
I found that the link you referred to works if you reference the page document. In my case, using gBrowser.contentDocument worked.
var fileref = gBrowser.contentDocument.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", "resource://extensionid/content/skin/style.css");
gBrowser.contentDocument.getElementsByTagName("head")[0].appendChild(fileref);
Obviously make sure that you can access your css via the resource:// protocol.

Resources