How to make a string to point to a variable in Less? - javascript

I extended default less functions to support some basic lists. I added a function 'nth' given as following:
"nth": function(obj, index){
var list = obj.value.split(",");
var n = index.value;
obj.value = list[n-1].trim();
return new tree.Anonymous(obj);
}
Then I added another function 'convertstrtovar' as following:
convertstrtovar: function(obj){
var str = obj.value.toString();
str = str.replace(/(#)/gi, '');
str = '~"#{' + str + '}"';
obj.value = str;
return new tree.Anonymous(obj);
}
This receives String like '#white' and converts it to ~"#{white}". Sample code for less mixin is given below.
#button-text-colors: "#white, #dark, #red"; //parsed as a comma separated list.
#white: white;
#dark: black;
#red: red;
.something(#color){
color: #color;
}
.some{
#t: convertstrtovar(nth(#button-text-colors, 1));
.something(#t);
}
This gives me output as following:
.some {
color: ~"#{white}";
}
Why is ~"#{white}" being printed out as string and not evaluated as variable white when usually ~"#{white}" in less get the value stored in #white?

Why is ~"#{white}" being printed out as string and not evaluated as variable white when usually ~"#{white}"
Because LESS evaluates those things when it parses the input (but your function creates a new string object after that).
Actually you can achieve what you want just with default LESS language constructs (w/o any need for custom function hacks):
#button-text-colors: 'white', 'dark', 'red';
#white: white;
#dark: black;
#red: red;
.something(#color){
color: #color;
}
.some{
#t: extract(#button-text-colors, 1);
.something(##t);
}
No, seriously, I would suggest you to consider to learn more about existing LESS features before trying to extend it with you own custom functions... (Though I must admit the outdated LESS documentation is a significant problem - well, at least take a look at https://github.com/SomMeri/less4j/wiki/_pages - this is the most detailed LESS documentation for the moment).

Related

Variable in JSON Path - JavaScript

I already searched for similar issues but I didn't find anything that could help me yet.
I'm trying to reach a picture path (using JSON format) depending on the material type of the picked element. Actually, my code is built like this:
if (globalData.Material.Mat_type == "OSCILLOSCOPE") {
var picture = (globalData.Material.Oscilloscope.picture);
}
if (globalData.Material.Mat_type == "ALIMENTATION") {
var picture = (globalData.Material.Alim.picture);
}
But not optimized at all, so Im trying to make it this way :
var mat_type = (globalData.Material.Mat_type);
var picture = (globalData.Material[mat_type].picture);
But it doesn't work... Got some exception:
TypeError : globalData.Material[mat_type] is undefined.
I already tried a lot of things, have you got any idea? Thanks!
I outlined the issue with character case in the comment under the question, so presumably adjusting value of globalData.Material.Mat_type could do the trick:
var mat_type =
globalData.Material.Mat_type.charAt(0).toUpperCase() +
globalData.Material.Mat_type.substr(1).toLowerCase();
I can also see that this general rule may not be applicable in all cases. If it's not a typo, it won't work for the second case where Mat_type == "ALIMENTATION", because then you try to access Alim property of Material instead of Alimentation. In this case you could access property by prefix:
function pictureOf(material) {
if (!material || !String(material.Mat_type)) {
return null;
}
let mat_type = String(material.Mat_type).toUpperCase();
for (var propertyName in material) {
if (mat_type.startsWith(propertyName.toUpperCase())) {
return material[propertyName].picture || null;
}
}
return null;
}
console.log(pictureOf({
Mat_type: "OSCILLOSCOPE",
Oscilloscope: {
picture: "picture of oscilloscope"
}
}));
console.log(pictureOf({
Mat_type: "ALIMENTATION",
Alim: {
picture: "picture of alimentation"
}
}));
But this kind of approach can be error prone, if multiple properties share the same prefix. There's also a hidden issue with case-insensitive prefix matching in case you use some special unicode characters in property names. Lastly this method is not efficient, because it has to iterate over all properties of the object (worst case scenario). It can be replaced with much safer property mapping:
const matTypeMapping = {
"ALIMENTATION": "Alim"
};
function pictureOf(material) {
if (!material || !String(material.Mat_type)) {
return null;
}
let matType = String(material.Mat_type);
// find property mapping or apply general rule, if mapping not defined
let propertyName = matTypeMapping[matType] ||
matType.charAt(0).toUpperCase() + matType.substr(1).toLowerCase();
return material[propertyName].picture || null;
}
console.log(pictureOf({
Mat_type: "OSCILLOSCOPE",
Oscilloscope: {
picture: "picture of oscilloscope"
}
}));
console.log(pictureOf({
Mat_type: "ALIMENTATION",
Alim: {
picture: "picture of alimentation"
}
}));
NB: To avoid headaches, maybe you should prefer strict equality operator over loose equality operator.
Problem Solved
Peter Wolf was right ! It was a case-sensitive issue
I actually don't know how to promote his comment, sorry for this..
Anyway, thank you guys !
var mat_type = (globalData.Material.Mat_type);
if(mat_type!==undefined)
var picture = (globalData.Material[mat_type].picture)
Just do an existential check before accessing the value, for keys that may not be present.

Adding meta data to a primitive in javascript

Background
We have much of our data formatted like
var X = {value:'some val',error:'maybe an error',valid:true}
as a result we find ourselves calling X.value ALL the time.
We don't use the .error or .valid nearly as much, but we do use it.
What I want
To quit calling .value everywhere, but to still have access to meta data on a per data point level.
The Question
Is there one of
A) A way to put meta data on a primitive? attaching .error to an int for example? Is it possible for bools or strings?
B) A way to make a class that can be treated as a primitive, providing a specific data member when I do? IE X.value = 5, X+3 returns 8.
C) A better design for our data? Did we just lay this out wrong somehow?
You can set the method toString() to your object and return value.
var X = {
value: 1,
error:'maybe an error',
valid:true,
toString: function() {
return this.value;
}
}
X.value = 5;
console.log(X+3);
You can represent you data as a function object that also has properties:
var X = () => 1;
X.value = 1;
X.error = 'maybe an error';
X.valid = true,
console.log(X()); // 1
console.log(X.valid); // true
For better design you can encapsulate the creation of the data object in another function.

Convert data types in d3.js without prior knowledge of property names (detect if a string contains only digits)

In d3.js. I can read in a user-uploaded CSV file in my web app like this:
d3.csv("upload.csv", function(data) {
console.log(data[0]);
});
This results in everything being read in as a string. However, I need to be able to treat numeric data types as numbers.
If I knew the property names ahead of time, I could do something like this:
d3.csv("upload.csv", function(data) {
data.forEach(function(d) {
d.population = +d.population;
d["land area"] = +d["land area"];
});
console.log(data[0]);
});
However, as this is user-provided data, there's no way to know the property names ahead of time. Is there a way to detect that the fields only contain numbers, then change the data type accordingly? Perhaps some sort of conditional statement with a regex test or something?
The examples were adapted from this tutorial.
New Answer:
D3 v5.8 introduced the very handy method d3.autotype, which makes this task quite easy:
var data = d3.csvParse(d3.select("#csv").text(), d3.autoType);
console.log(data);
pre {
display: none;
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<pre id="csv">header1,header2,header3
foo,foo2,1212
bar,bar2,2345
baz,baz2,7623</pre>
(Original Answer)
As discussed in the comments, you can use a regex to check if the string contains only digits. Then, if it does, you coerce it to a number.
In the following demo I'm using a <pre> to store the data, since I cannot use the actual d3.csv function in the Stack snippet.
In the simulated CSV there are three columns. One of them, header3, has numbers. We know that, but the code doesn't: it just check all values using the regex and coerce the strings containing only digits to numbers.
var data = d3.csvParse(d3.select("#csv").text());
data.forEach(function(d) {
for (var key in d) {
if (/^\d+$/.test(d[key])) {
d[key] = +d[key]
}
}
});
console.log(data);
pre {
display: none;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<pre id="csv">header1,header2,header3
foo,foo2,1212
bar,bar2,2345
baz,baz2,7623</pre>
This addresses your question, which is "detect if a string contains only digits". However, if you want to deal with negative numbers, scientific notation and floats as well, you can drop the regex and use something way more elegant:
In JavaScript, NaN is not equal to anything, not even to itself. Since using the unary operator with something that is not a number returns NaN, you can simply do:
if (+d[key]===+d[key]) {
d[key] = +d[key]
}
Here is another demo, with negatives, floats and scientific notation:
var data = d3.csvParse(d3.select("#csv").text());
data.forEach(function(d) {
for (var key in d) {
if (+d[key]===+d[key]) {
d[key] = +d[key]
}
}
});
console.log(data);
pre {
display: none;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<pre id="csv">header1,header2,header3
foo,foo2,12.12
bar,bar2,-2345
baz,baz2,2.4e6</pre>
I'd use parseFloat (or parseInt if you know you don't have to care about floats)
function maybeNumber(someString) {
var result = parseFloat(someString, 10);
if (isNaN(result)) {
return someString;
}
return result;
}
data = data.map(maybeNumber);
It's safer than letting type coercion loose on your data.

Get element's custom css properties (-mystyle) using JavaScript

In an application where certain elements have custom CSS properties, is there any way to retrieve such a value via JavaScript?
e.g.
<div id="myDiv" style="color:#f00;-my-custom-property:upsidedown;" />
I can access the color attribute via these two methods:
document.getElementById('myDiv').style.getPropertyValue("color")
document.getElementById('myDiv').style.color
But these do not work for custom properties. Is this supported at all?
CSS values not understood by the browser are discarded, which explains why -my-custom-property was unavailable via .style.
In the past, you would have had to rely on storing the data with data attributes and dealing with inheritance yourself via JavaScript.
However, "custom properties", aka "CSS variables", have since been introduced into the standard and implemented by browsers, with ~92% support globally as of 2019-05-09. At a quick glance, Edge seems to have been the last major browser to implement, with version 16 on October 16, 2017.
Essentially, you need to set a custom property (eg, --my-custom-property: 'foobar';) on an element, and it can be accessed with something like getComputedStyle(your_el).getPropertyValue("--my-custom-property") which would return 'foobar' (with a leading space). Note the leading space and quotation marks. It will return the value exactly as it was provided.
Example:
console.log(getComputedStyle(document.getElementById("a")).getPropertyValue("--my-custom-property-1"))
console.log(getComputedStyle(document.getElementById("b")).getPropertyValue("--my-custom-property-2"))
#b-div { --my-custom-property-2: 'world' }
<div style="--my-custom-property-1: 'hello'"><h1 id="a">#a 'hello'</h1></div>
<div id="b-div"><h1 id="b">#b 'world'</h1></div>
Here's some testing using one and two leading hyphens, inheritance, and different methods of retrieving the value:
function log(computed, selector, prop, value) {
let method = computed ? "getComputedStyle(el)" : "el.style"
let method_id = computed ? "computed" : "raw"
// Build first level of list (tag name)
let first = document.querySelector("#" + selector)
if (!first) {
first = document.createElement("li")
first.appendChild(document.createTextNode(selector))
first.setAttribute("id", selector)
first.appendChild(document.createElement("ul"))
document.querySelector("ul").appendChild(first)
}
// Build second level of list (method of style retrieval)
let second = document.querySelector("#" + selector + "-" + method_id)
if (!second) {
second = document.createElement("li")
second.appendChild(document.createTextNode(method))
second.setAttribute("id", selector + "-" + method_id)
second.appendChild(document.createElement("ul"))
first.querySelector("ul").appendChild(second)
}
// Build third level of list (property accessed)
let third = document.querySelector("#" + selector + "-prop" + prop)
if (!third) {
third = document.createElement("li")
third.appendChild(document.createTextNode(prop + ": `" + value + "`"))
third.setAttribute("id", "prop" + prop)
second.querySelector("ul").appendChild(third)
if (value === "") {
third.classList.add("bad")
} else {
third.classList.add("good")
}
}
}
// Uses .style
function getStyleAttr(selector, prop) {
let value = document.querySelector(selector).style.getPropertyValue(prop)
log(false, selector, prop, value)
}
// Uses getComputedStyle()
function getStyleComputed(selector, prop) {
let value = getComputedStyle(document.querySelector(selector)).getPropertyValue(prop)
log(true, selector, prop, value)
}
// Loop through each property for each element and output the value
let selectors = ["article", "h1", "p"]
let props = ["--my-custom-property", "-my-custom-property"]
selectors.forEach(function(selector) {
props.forEach(function(prop) {
getStyleAttr(selector, prop)
getStyleComputed(selector, prop)
})
})
code {
background: #eee;
padding: .2em;
}
.bad {
color: #800;
}
.good {
color: #080;
}
<article class="custom-prop-inheritance" style="--my-custom-property: 'foobar'; -my-custom-property: 'foobar'">
<h1>Title</h1>
<p>Custom properties require two leading hyphens (<code>-my-custom-property</code> <em>never</em> works). Using <code>el.style</code> does not support inheritance. To support both inheritance and custom properties, you must use <code>getComputedStyle(<b>el</b>)</code> along with two leading hyphens on the custom property (eg, <code>--my-custom-property</code>).</p>
</article>
<ul></ul>
CSS:
:root {
--custom-property: #000000;
}
Javascript:
var custom_property = window.getComputedStyle(document.body).getPropertyValue('--custom-property').trim()
Non-recognised CSS properties will be ignored when put within the style attribute, or in the style.cssText property.
If you want to define a property at a specific element, I recommend data-attributes:
HTML:
<div id="myDiv" style="color:#f00;" data-custom-property="upsidedown" />
JavaScript:
//jQuery's method to retrieve value:
$("#myDiv").data("custom-property");
//jQuery, without parsing:
$("#myDiv").attr("data-custom-property");
// Modern browsers, native JS:
document.getElementById("myDiv").dataset["custom-property"];
// Older browsers, native JS:
document.getElementById("myDiv").getAttribute("data-custom-property");
This is actually now possible for all browsers using a specialized CSS hack via the CSS content tag. This article explains how to do it:
http://www.yearofmoo.com/2015/04/cross-browser-custom-css-properties.html
function getCustomCssProperty(elementID, propertyName){
var style = document.getElementById(elementID).getAttribute("style");
var entries = style.split(";");
for (var i=0; i<entries.length; i++){
var entry = entries[i].split(":");
if(entry[0] == propertyName){
return entry[1];
}
}
return null;
}
You can't use data-* attributes (html5)?
That would at least be valid and not a strange hack.

How to get an HTML element's style values in JavaScript?

I am looking for a way to retrieve the style from an element that has a style set upon it by the style tag.
<style>
#box {width: 100px;}
</style>
In the body
<div id="box"></div>
I'm looking for straight javascript without the use of libraries.
I tried the following, but keep receiving blanks:
alert (document.getElementById("box").style.width);
alert (document.getElementById("box").style.getPropertyValue("width"));
I noticed that I'm only able to use the above if I have set the style using javascript, but unable to with the style tags.
The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.
Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.
The two ways have differences, for example, the IE element.currentStyle property expect that you access the CCS property names composed of two or more words in camelCase (e.g. maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height, font-size, background-color, etc).
Also, the IE element.currentStyle will return all the sizes in the unit that they were specified, (e.g. 12pt, 50%, 5em), the standard way will compute the actual size in pixels always.
I made some time ago a cross-browser function that allows you to get the computed styles in a cross-browser way:
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hypen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
The above function is not perfect for some cases, for example for colors, the standard method will return colors in the rgb(...) notation, on IE they will return them as they were defined.
I'm currently working on an article in the subject, you can follow the changes I make to this function here.
I believe you are now able to use Window.getComputedStyle()
Documentation MDN
var style = window.getComputedStyle(element[, pseudoElt]);
Example to get width of an element:
window.getComputedStyle(document.querySelector('#mainbar')).width
In jQuery, you can do alert($("#theid").css("width")).
-- if you haven't taken a look at jQuery, I highly recommend it; it makes many simple javascript tasks effortless.
Update
for the record, this post is 5 years old. The web has developed, moved on, etc. There are ways to do this with Plain Old Javascript, which is better.
Use getComputedStyle function, Computed style contains all the CSS properties set to an element. Even if do not set a property to an element. You will still find that property in the computed styles.
Example:
<style>
#Body_element {
color: green;
}
</style>
<body id="Body_element">
<script>
alert(getComputedStyle(Body_element).color)
</script>
</body>
This is a helper function if you want to get multiple style rules from the same element.
You pass it the element and the styles you want as arguments, and it will return their values
const convertRestArgsIntoStylesArr = ([...args]) => {
return args.slice(1);
}
const getStyles = function () {
const args = [...arguments];
const [element] = args;
let stylesProps = [...args][1] instanceof Array ? args[1] : convertRestArgsIntoStylesArr(args);
const styles = window.getComputedStyle(element);
const stylesObj = stylesProps.reduce((acc, v) => {
acc[v] = styles.getPropertyValue(v);
return acc;
}, {});
return stylesObj;
};
Now, you can use this function like this:
const styles = getStyles(document.body, "height", "width");
OR
const styles = getStyles(document.body, ["height", "width"]);

Categories

Resources