CodeMirror and Brackets, Custom Mode with CSS Quick Edit - javascript

I'm making a Adobe Brackets Extension to add support for Laravel Blade syntax highlight.
Blade is a template system that runs on top of HTML (more specifically a .php file), without my extension active I can do CTRL+E Quick Edit on a css rule name to quickly find that rule on the stlye.css file.
But when I activate the extension, the CTRL+E is not working anymore, but the HTML syntax is working perfectly.
I'm using overlay mode over text/html.
Here is the main.js extension code:
define(function (require, exports, module) {
'use strict';
var LanguageManager = brackets.getModule("language/LanguageManager");
CodeMirror.defineMode("laravelblade", function (config, parserConfig) {
var mustacheOverlay = {
token: function (stream, state) {
var ch;
//Highlight Comments {{-- --}}
if (stream.match("{{--")) {
while ((ch = stream.next()) != null)
if (ch == "}" && stream.next() == "}") break;
stream.eat("}");
return "comment";
}
//--
//Highlight {{ $var }})
if (stream.match("{{")) {
while ((ch = stream.next()) != null)
if (ch == "}" && stream.next() == "}") break;
stream.eat("}");
return "def";
}
//Highlight {% $var %} (Laravel 5)
else if (stream.match('{%')) {
while ((ch = stream.next()) != null)
if (ch == "%" && stream.next() == "}") break;
stream.eat("}");
return "def";
}
//Highlight {% $var %} (Laravel 5)
else if (stream.match('{%')) {
while ((ch = stream.next()) != null)
if (ch == "%" && stream.next() == "}") break;
stream.eat("}");
return "def";
}
//Return Null if no condition was met.
else if (stream.next() != null) {
return null;
}
}
};
return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "php"), mustacheOverlay);
});
LanguageManager.defineLanguage("laravelblade", {
"name": "Laravel Blade",
"mode": "laravelblade",
"fileExtensions": ["blade.php"],
"blockComment": ["{{--", "--}}"]
});
});
The real question is:
How can I add support for Quick Edit on my custom mode and *blade.php files?

I think the problem is this part of your code:
else if (stream.next() != null) {
return null;
}
Looking at CodeMirror's overlay mode demo, it does something slightly different:
while (stream.next() != null && !stream.match("{{", false)) {}
return null;
Your code is returning null once for each ignored character, while the demo is only returning null once per contiguous chunk of ignored characters.
Returning separately for every character seems to make CodeMirror break up all of its normal tokens into separate one-char tokens, which the Brackets Quick Edit code can't recognize -- e.g. if your cursor is here - cl|ass - CodeMirror says it's in an attribute token where the name is just "l", while the Brackets code is looking attributes named "class".

Related

My if/else is not working like it should [duplicate]

This question already has answers here:
JavaScript if "x = (a || b || c)" statement not working
(2 answers)
Closed 7 years ago.
My if else is not working like it should. I have 1 if 1 else if and 1 else. When the function runs it executes the if even if the condition is "false".
Here is the JavaScript:
function onSearch(){
var site;
document.getElementById('bar').value = site;
//These are not the actuall links since it's not the actuall code.
if (site === "Google" || "google"){
location.href = "http://www.google.com";
}
else if (site === "Youtube" || "youtube"){
location.href = "http://www.youtube.com";
}
else{
document.getElementById("SearchFail01").innerHTML =
"The country " + site + " does not exist";
}
<!-- Here is the HTML -->
<input type='search' id='bar' list='countries' placeholder='Search..'>
<p id="SearchFail01"></p>
In Javascript, a string in a conditional statement is considered True. The "||" operator won't work the way you're trying to make it work so you'll have to spell it out.
if (site === "Google" || site === "google"){
location.href = "http://www.google.com";
}
else if (site === "Youtube" || site === "youtube"){
location.href = "http://www.youtube.com";
}
else{
document.getElementById("SearchFail01").innerHTML =
"The country " + site + " does not exist";
}
edit:
I also noticed this line:
document.getElementById('bar').value = site;
should probably be flipped if you want to assign bar's value to site
site = document.getElementById('bar').value;
The double pipe doesn't work like you expect. This is how it is supposed to be used.
var foo = someVar || "foo"; not to be used inside an if like that
In your case you could simply lowercase the site and use a single ===
if (site.toLowerCase() === "google") {
location.href = "http://www.google.com";
}
You might also want to consider using a switch.
switch (site) {
case "Google":
case "google":
location.href = "http://www.google.com";
break;
case "Youtube":
case "youtube":
location.href = "http://www.youtube.com";
break;
default:
document.getElementById("SearchFail01").innerHTML = "The country " + site + " does not exist";
break;
}
I believe you have a logic problem if your if and your endif conditions.
When you have 2 or more conditions in JavaScript, separated with the OR (||), or AND (&&) operators you need to make the comparisons in each condition.
Instead of:
if (site === "Google" || "google"){
you have to write:
if (site === "Google" || site === "google"){
And instead of:
else if (site === "Youtube" || "youtube"){
you have to write:
else if (site === "Youtube" || site === "youtube"){
Hope this is helpful!
Cheers mate!

Function for setting text of an element

// Function for setting text of an element:
function setText(elementId, message)
{
'use strict';
if ( (typeof elementId == 'string')&& (typeof message == 'string') )
{
var output = $(elementId);
if (output.textContent !== undefined)
{
output.textContent = $(elementId).string;
}
else
{
output.innerText =$(elementId).string ;
}
} // End of main if.
} // End of setText() function.
I need help with this code, I need to define a function name the setText() function as shown below, when I run this code in JS Bin the page shows the code won't run, I couldn't find where the error is. Can anyone give me a hint?
Your type checking for message is unnecessary, but in case you want to keep it:
function setText(elementId, message){
if((typeof elementId == 'string') && (typeof message == 'string')){
document.getElementById(elementId).innerHTML = message;
}
}
setText("foo", "1")
setText("foobar", "2")
setText("bar", "3")
setText("barfoo", "4")
<p id="foo"></p>
<p id="foobar"></p>
<p id="bar"></p>
<p id="barfoo"></p>
You can do it using JavaScript prototypical way. This is little advanced.
HTML:
<span id="spanText"> Your sample Text </span>
First of all augment the type by this code:
/*
Augmenting type
*/
Function.prototype.addMethod = function(funcName, funcBody){
if(!this.prototype[funcName]){
this.prototype[funcName] = funcBody;
return this;
}};
String.addMethod("setText", function(text){
document.getElementById(this).textContent = text;
});
var elementId = "spanText";
elementId.setText("kkkkkkkkkkk");
Load this JS below your HTML file.
You are able to add any of your custom string, number, array method by this way.
See the complete example here:
https://jsfiddle.net/dmsbilas/wu3cd88w/

Display meta-field mp3 and add to lightbox container on portfolio page

What I basically have now:
I have a portfolio gallery masonry grid (using JIG plugin) that queries my custom post_type.
For each post, clicking on the thumbnail will trigger a lightbox showing the photo.
JIG allows you to use many different lightbox versions (PrettyPhoto, JP Carousel, ColorBox , PhotoSwipe), The lightbox's can be configured to display descriptions, captions, authors, dates & times, alt text, and a few more fields from within JIG itself.
The desired goal:
In the lightbox, I want to display an audio player, and pulling its src from the current post shown just as if it were a title, alt text, or caption field.
I've setup the frontend add new post form for it to accept a mp3 url which saves the url to the mp3 in "my_meta_field"...
I use the shortcode which injects the url into the markup. Defaults to the current post, but can be configured to accept $parent_post, or any other variable.
Methods I've tried using to call the field from shortcode and standard methods.
[types field="my_meta_field"] or echo types_render_field( "my_meta_field", array("output" => "raw") or get_post_meta()
What's the most straightforward, and simple way to get the <audio mp3="my_custom_field"> </audio> code to pass through the lightbox's query and display it inside of the lightbox container?
Changes were to include the additional info for carusel (it works separately), remove the caption from the link of the thumbnail so you can interact with the player and not open the carousel immediately (and to allow HTML in it).
justified-image-grid.php v2.0.4
line 1304
wp_enqueue_script('justified-image-grid', plugins_url('js/justified-image-grid-min.js', __FILE__), 'jquery', self::PLUGIN_VERSION, true);
became
wp_enqueue_script('justified-image-grid', plugins_url('js/justified-image-grid.js', __FILE__), 'jquery', self::PLUGIN_VERSION, true);
(loading unminified JS)
after line 8117 New code is inserted:
if($recents_post_type == 'project'){
$audio_url = get_post_meta( $post->ID, 'pf_podsnack', true );
if(!empty($audio_url)){
if (strpos($audio_url, 'iframe') === false){
$d['description'] .= '<audio controls="controls" preload="auto">
<source src="'.$audio_url.'" type="audio/mpeg">
</audio>';
}else{
$d['description'] .= $audio_url;
}
}
}
In future versions the line numbering will change but you'll find this area 2 lines before the line:
switch ($recents_link_to) {
Line 8143
$data['carousel_data'] = $this->jig_add_carousel_data(get_post_thumbnail_id($post->ID), $link_title_field, $img_alt_field);
bacame
$data['carousel_data'] = $this->jig_add_carousel_data(get_post_thumbnail_id($post->ID), $d['title'], $d['description'], true);
Line 12136 new code inserted:
.justified-image-grid audio{
display: block;
width: 100%;
}
.jp-carousel-titleanddesc-desc audio,
.jp-carousel-titleanddesc-desc iframe{
display: block;
}
.justified-image-grid iframe{
display: block;
margin: 0 auto;
}
CSS styling of the audio and iframes.
12251
wp_enqueue_script('justified-image-grid', plugins_url('js/justified-image-grid-min.js', __FILE__), 'jquery', self::PLUGIN_VERSION, true);
became
wp_enqueue_script('justified-image-grid', plugins_url('js/justified-image-grid.js', __FILE__), 'jquery', self::PLUGIN_VERSION, true);
(loading unminified JS)
line 14856
function jig_add_carousel_data($attachment_id, $link_title_field, $img_alt_field){
became
function jig_add_carousel_data($attachment_id, $link_title_field, $img_alt_field, $ready = false){
line 14873-14882
// Get title
$d['title'] = esc_attr(stripslashes($attachment->post_title));
$d['caption'] = esc_attr(stripslashes($attachment->post_excerpt));
$d['description'] = esc_attr(stripslashes($attachment->post_content));
$d['alternate'] = esc_attr(stripslashes(get_post_meta($attachment->ID, '_wp_attachment_image_alt', true)));
$attachment_title = $d[$img_alt_field] ? wptexturize($d[$img_alt_field]) : '';
$attachment_desc = $d[$link_title_field] ? wpautop(wptexturize($d[$link_title_field])) : '';
became
if($ready == false){
// Get title
$d['title'] = esc_attr(stripslashes($attachment->post_title));
$d['caption'] = esc_attr(stripslashes($attachment->post_excerpt));
$d['description'] = esc_attr(stripslashes($attachment->post_content));
$d['alternate'] = esc_attr(stripslashes(get_post_meta($attachment->ID, '_wp_attachment_image_alt', true)));
$attachment_title = $d[$img_alt_field] ? wptexturize($d[$img_alt_field]) : '';
$attachment_desc = $d[$link_title_field] ? wpautop(wptexturize($d[$link_title_field])) : '';
}else{
$attachment_title = esc_attr($link_title_field);
$attachment_desc = esc_attr($img_alt_field);
}
----------
justified-image-grid.js
after 622 new code:
s.element.on("click", ".jig-caption", function(event){
event.stopPropagation();
});
1850-1867
if(captionContent !== ''){
captionContent = '<div class="jig-caption-wrapper"><div class="jig-caption">'+captionContent+'</div></div>';
if(s.caption !== 'below'){
link.append(captionContent);
}else if(s.middleBorderWidth !== 0 && s.innerBorder == 'always' && s.middleBorder !== 'always'){
imageContainer.append($(captionContent).width(overflow.width()-2*parseFloat(s.innerBorderWidth)));
}else{
imageContainer.append($(captionContent).css({'width':overflow.css("width")}));
}
}else if(s.caption == 'below'){
captionContent = '<div class="jig-caption-wrapper"></div>';
if(s.middleBorderWidth !== 0 && s.innerBorder == 'always' && s.middleBorder !== 'always'){
imageContainer.append($(captionContent).width(overflow.width()-2*parseFloat(s.innerBorderWidth)));
}else{
imageContainer.append($(captionContent).css({'width':overflow.css("width")}));
}
}
became
if(captionContent !== ''){
captionContent = '<div class="jig-caption-wrapper"><div class="jig-caption">'+captionContent+'</div></div>';
if(s.caption !== 'below'){
overflow.append(captionContent);
}else if(s.middleBorderWidth !== 0 && s.innerBorder == 'always' && s.middleBorder !== 'always'){
overflow.append($(captionContent).html(captionContent).width(overflow.width()-2*parseFloat(s.innerBorderWidth)));
}else{
overflow.append($(captionContent).html(captionContent).css({'width':overflow.css("width")}));
}
}else if(s.caption == 'below'){
captionContent = '<div class="jig-caption-wrapper"></div>';
if(s.middleBorderWidth !== 0 && s.innerBorder == 'always' && s.middleBorder !== 'always'){
overflow.append($(captionContent).html(captionContent).width(overflow.width()-2*parseFloat(s.innerBorderWidth)));
}else{
overflow.append($(captionContent).html(captionContent).css({'width':overflow.css("width")}));
}
}
line 2246-2255
input = htmlspecialchars_decode(input);
if(s.caption == 'below'){
return input; // Allowing links or anything when the caption is below the image (still need to decode)
}
allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
became
return $("<div/>").html(input).text();
/*input = htmlspecialchars_decode(input);
if(s.caption == 'below'){
return input; // Allowing links or anything when the caption is below the image (still need to decode)
}
allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});*/

jQuery issue in IE

Hello I'm using this function as an address book module, for selecting any employee from the sidebar it display all the content of the employee. It works fine in Chrome but not in IE. I'm not able to run the src variables declared in this function in IE. Please suggest me some other ways to declare these type of variables so that these will be compatible to all browsers.
function singleSelect(id)
{
if(flag){
unCheckAll();
userIds="";
//userIds= document.forms['frmSidebarSearch'].elements['userIds'].value + id +",";
var src = ($("#"+id).attr("src") === "<#core.basePath/>images/chk-box-img.gif")
? "<#core.basePath/>images/chk-box-img-tick.gif"
: "<#core.basePath/>images/chk-box-img.gif";
$("#"+id).attr("src",src);
var src2 = ($("#anchor"+id).attr("class") === "")
? "selected"
: "";
$("#anchor"+id).removeClass().addClass(src2);
var elementss = document.getElementById("all").getElementsByTagName('img');
for(i=0;i<elementss.length;i++) {
if($("#"+elementss[i].id).attr("src") === "<#core.basePath/>images/chk-box-img-tick.gif"){
userIds= userIds +"," +elementss[i].id;
}
}
unHilightAll();
highLightIndex(id);
document.forms['frmSidebarSearch'].elements['userIds'].value=userIds;
$('#frmSidebarSearch').ajaxSubmit({target:'#content',url:'<#core.basePath/>sp/manager/manageraddressbook/manager/'+id});
}
flag = true;
}
Have you tried it with double equals (I think triple equals sign is only in languages like php).
(condition == condition) ? true : false;

If Statement not working with And (&&) Operator

I'm having a hard time writing up what seems should be a simple if statement! I need it to say if mod does not equal a, b, or c - then do this. Here is what I was trying but have been unsuccessful:
var mod = CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
doSomething();
}
When I type this into my editor it says there is an error, specifically that "The entity name must immediately follow the '&' in the entity reference."
.. and is not working when I go to test.
Any help is appreciated!!
UPDATE:
The url: esber.squarespace.com
The full script:
<script type="text/javascript" src="/storage/scripts/sessvars.js"></script>
<script type="text/javascript">
<![CDATA[
onload=function(){
sessvars.browserConfirmation?'none':'';
sessvars.ageConfirmation?'none':'';
};
var mod = Squarespace.Constants.CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
if(sessvars.ageConfirmation != "yes"){
window.location = "/verify/";
};
};
]]>
</script>
I want every page in the site to automatically redirect on page load to the verify page, unless it is the verify page (/verify), the "You are not verified" page (/not-verified), or the login page (/login) -- unless the user already verified by setting the sessvars, then they can continue on to the homepage.
To test this I go to esber.squarespace.com and click on one the menu items at the right (this menu would eventually be hidden when I'm done with the page) -- when i try to go to another page without veriying my age first i should be redirected back to the /verify page but that isnt happening.
If i revise the script to:
<script type="text/javascript" src="/storage/scripts/sessvars.js"></script>
<script type="text/javascript">
onload=function(){
sessvars.browserConfirmation?'none':'';
sessvars.ageConfirmation?'none':'';
};
var mod = Squarespace.Constants.CURRENT_MODULE_ID;
if (mod != "5827289") {
if(sessvars.ageConfirmation != "yes"){
window.location = "/verify/";
};
};
</script>
then it works fine(?)
Try this:
// <![CDATA[
onload=function(){
sessvars.browserConfirmation?'none':'';
sessvars.ageConfirmation?'none':'';
};
var mod = Squarespace.Constants.CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
if(sessvars.ageConfirmation != "yes"){
window.location = "/verify/";
};
};
// ]]>
If this doesn't work, just leave the code there for a bit, so that we can debug it directly on your website
Wrap your script in a CDATA section.
<script type="text/javascript">
<![CDATA[
// script here
]]>
</script>
I tried the EXACT same code as yours and it works fine:
function doSomething() {alert("doing");}
var CURRENT_MODULE_ID = 5195103000;
var mod = CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
doSomething();
}
It did 'doSomething'. When value is changed to 5195103, nothing happens which is correct
The editor aside, what's the script error when you run it and what's the browser you used? I suspect it could be an error elsewhere or perhaps related to CURRENT_MODULE_ID ?
Are you embedding this javascript in an xml document?
It sounds like the xml document is not well formed, perhaps because the & should be escaped as &
The javascript by itself looks fine too me
Try:
var mod = CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
doSomething();
}
You'll find out that way whether the javasciprt needs to be escaped
Edit in response to comment:
Try the following:
<script type="text/javascript">
<![CDATA[
var mod = CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
doSomething();
}
]]>
</script>
It sounds like your editor just thinks you're working with an XML document. Have you tried actually running this in a browser? If so, does the browser also give an error?
Are you trying to compare the ID as a string or value? Did you try it without quotes?
var mod = CURRENT_MODULE_ID;
if (mod != 5827289 && mod != 5195103 && mod != 5181422) {
doSomething();
}
or another method would be to use match
var mod = CURRENT_MODULE_ID;
if (!mod.match("5827289|5195103|5181422")) {
doSomething();
}
I got this error within a script section in an XSL file.
Entity '&' not defined
I adapted the above answer within my script and it worked.
Note the CDATA section in the code segment below
<script>
var Quantity860=<xsl:value-of select="$QuantityOrdered_860" />;
var Quantity850=<xsl:value-of select="$QuantityOrdered_850" />;
var QuantityToReceive860=<xsl:value-of select="$QuantityLeftToReceive_860" />;
if(parseFloat(Quantity860.textContent) !== parseFloat(Quantity850.textContent) <![CDATA[ && ]]> parseFloat(QuantityToReceive860.textContent) !== parseFloat(Quantity850.textContent))
{
Quantity860.style.color="#FF6347";
Quantity850.style.color="#FF6347";
QuantityToReceive860.style.color="#FF6347";
}
</script>
just use != in comparison instead of == then && will work
if(val != "" && val != "") {
console.log("filled");
}else
{console.log("empty"); }

Categories