less.js icon indicating copy to clipboard operation
less.js copied to clipboard

[Question] Retain Variables in CSS?

Open RandyBuchholz opened this issue 9 years ago • 9 comments

Hope this isn't too out of scope/guidelines.

Background

I have no js skills so I wouldn't know how to do this myself. In C#/Razor I can do "substitutions" in my code with variables.

@{
   var widthvar = "10px"
}
<style>
   .element-width{ width:@widthvar; }
</style>

LESS is not supported "in page", so I need to compile my less to css, parse it and do substitutions, etc. to get to the final results.

Need

I'm wondering if anyone would be interested in going down a fork where the LESS is compiled into CSS, but the variables are left intact? I realize this would be invalid CSS and the general utility of this would be pretty limited. But, (hopefully), it never hurts to ask.

RandyBuchholz avatar Dec 21 '16 14:12 RandyBuchholz

Less is not supported in terms of guaranteed to work in the browser (in a production environment), but that doesn't mean it doesn't work to compile in-browser. Even though it's not recommended for production use (in-browser compiling is recommended just for development), some people use Less in that way.

Less couldn't really do what you're proposing without some major re-writing. Variables can do a lot in Less, including evaluation of mixins and even which imports are loaded. In other words, it really has to be evaluated every time.

However, what I could see Less doing is making it so your Less doesn't have to be parsed every time.

What some compiling engines do is allow you to compile into a JSON AST, which very quickly gets imported into the compiler's AST, making evaluation very fast. So, in theory, Less could compile into an "evaluation-ready" format, that would be make it very fast to do variable substitutions in-browser.

I think this would be great for Less, but it would take a dedicated developer (new person for the Less.js core team) to make this possible.

matthew-dean avatar Dec 21 '16 18:12 matthew-dean

What I'm doing with the variables is actually compile time. I should have noted I'm doing this in a cshtml file, which is a ASP.Net hybrid file of C# and HTML. I write my Less, and then compile it into css, which I DI inject into the cshtml file. When the page is being served, net builds an html page from the cshtml. That's when the variables get resolved. So in my case, I do want the mixin's, etc. resolved to plain css early in the process. Or, pre-process in this case I guess... I'm just looking to be able to carry some of the variable I use just as attribute values through to the css as variables.

It's a coincidence that Less and Razor both use @ to signify a variable, so it may have looked like I was using Less in a browser.

The coincidental @ works in my favor though. @herrquark over at dotless showed me that if I prefix my vars with ~, I seem to get something of what I want - at least for where I am with the proof of concept.

.coloredBox { background-color: ~"@backgroundColor"; } in my Less will compile to .coloredBox { background-color: @backgroundColor; } in my css, leaving the variable intact, (but it's a string so no intellisense.). It would be nice if I could use that without the quotes so Less still saw it as a variable for checking.

.coloredBox { background-color: ~@backgroundColor; }

If the compiler saw (some sequence like) " : ~@" it could indicate that by seeing the : it knows what follows is an attribute value, the ~ means literal, and then if it sees the @ and not " it knows to not resolve that instance of the variable. The ~@ syntax in Visual Studio (using the Web Compiler wrapper on less.js) doesn't complain, gives me intellisense, and compiles without error, but produces an empty file.

Update: Sorry, I was wrong, it does error when I try to compile. So while I'm here, my thought was that it may be possible to just change the way literals are handled without touching much else. When the compiler sees ~ it will either pass through everything between quotes (when it sees ~"All of this" => "All of this") or the single word prefixed by @. With:

@varname : 10px; 
@varname2: 20px; 

when it sees ~@varname @varname2 => @varname1 20px.

RandyBuchholz avatar Dec 21 '16 22:12 RandyBuchholz

Well, hang on. If you want the variable designator preserved at the end of compile, what kind of transform are you doing with it after that? With the resulting HTML/CSS? Are you doing a second compile in-browser? I don't get it.

matthew-dean avatar Dec 23 '16 00:12 matthew-dean

@matthew-dean He wants to do some simple token subsitution on the compiled CSS output to replace e.g. a few colors. But Less already supports compile-time 'replacement' just fine by specifying variable values on the compile commandline.

@RandyBuchholz I'm going to give you the proverbial "You're doing it wrong."

Create an HtmlHelper.CompiledLess(string path, IDictionary<string,string> variables) extension method that uses Process.Start to start the Less compiler and offer it the dictionary of variable values to take along into compilation. Cache the output using both the path and a serialization of the variables as a cache key for repeat requests that use the same variable values.

rjgotten avatar Dec 23 '16 07:12 rjgotten

@rjgotten, I'm exploring doing something differently, not sure if it is wrong yet. :) @matthew-dean, @rjgotten, - sorry long post here...

What I'm exploring kind-of boils down to turning css into C# classes, that emit css. The basic chain is: Less -> css with vars -> C# Classes where vars become method params and css becomes interpolated strings -> properties that emit clean css at page-build (run) time, based on runtime parameters. Since a Razor page is not html, but a C# class that produces html, packaging my css as classes opens up some interesting approaches. I don't have a demo yet, but this chunk has several concepts crammed together. These are just some data classes for the org chart, not part of the concept.

public class Person {...omitted...}
public class OrgRow : IEnumerable<Person> {...omitted...}
public class Chart : IEnumerable<OrgRow> {
     ....
    // I can declare css here, but it's usually a really bad idea. Just an example.
    public static string RowContainer => "border none; height: 20px; text-align: center; margin:0 0 8px 0;";
}

I'm going to produce an Org Chart from a Chart instance. It is layed-out server-side at runtime, based on the Chart runtime values. It ends up looking like this image

This is a Css# Class. (That's what I call this stuff) It takes some parameters in the constructor, and has a property that returns some rules. (The .ToPx() is an extension that just converts int to string and adds "px"). I can use these classes in my cshtml to generate css at runtime, using runtime values.

public class OrgChartRowCss {
    private int LeftMargin;
    private int BoxWidth;

    public OrgChartRowCss(int count, int containerSize, int gutter) {
        LeftMargin = gutter;
        var gutterTotalSize = (count + 1) * gutter;
        BoxWidth = ((int)Math.Floor((decimal)(containerSize - gutterTotalSize) / count)) - 4;
	}
   public string BoxStyle => $"width:{BoxWidth.ToPx()}; margin-left:{LeftMargin.ToPx()};";
	// Is a simple template for interpolation.
        // This is where the Less comes in. If I can convert my less with var intact, it will be easier to build complex ones.
        // I'm working on an extension for VS to help automate this.
}

This is my cshtml page

@{
    // These can be declared in the page or be passed into the page.
    var containerWidth = 800;
    var gutterWidth = 80;

    /* These live in a "stylesheet" or can be declared in page. I can inject the stylesheet I want to use. 
    var Raw = "box-sizing: border-box; text-align: left; vertical-align:top; padding: 0; margin:0;";
    var baseStyle = "display:inline-block; border: 1px solid #000; height: 20px; text-align: center;";
    var rowContainer = "border none; height: 20px; text-align: center; margin:0 0 8px 0;";

    // This would be passed into my page
    var myChart = new Chart {
        new OrgRow() { new Person("Top") },
        new OrgRow() { new Person("1-1"), new Person("1-2") },
        new OrgRow() { new Person("2-1"), new Person("2-2"), new Person("2-3") },
        new OrgRow() { new Person("3-1"), new Person("3-2"), new Person("3-3"), new Person("3-4") },
        new OrgRow() { new Person("4-1"), new Person("4-2"), new Person("4-3"), new Person("4-4"), new Person("4-5") },};
    };

<!-- I turned my styles into a class (not shown here) that emits style strings, I can inject them. I can even derive sub-styles from them.-->

@inject IDefaultStyles styles

// I can build my styles in my cshtml a little like less, but I can use constants, runtime variable, or injected values. 
<style>
    /* This class is built using the LayoutDiv "template" from the class that was injected */
    .layout-div { @Raw @styles.LayoutDiv }

    .base {@Raw @baseStyle}
    .box-container {@Raw @rowContainer}

    /* This comes from the Chart class in the library. Not a good example, but shows capability.  */
    .box-from-chart-class { @(Chart.RowContainer) }
</style>

<!-- This does the work.  I loop through the Org Chart rows, and then the People. 
For each row I get the number of people and calculate styles based in that using my OrgChartRowCss class.
Not shown is that because I would know first, last, etc in my loops, I can apply specific styling to them here, when I first encounter the ordering.
Maybe this can minimize css complexity by getting rid of some needs for pseudo classes, and saving work in the CSSOM. 
-->

@{
    @:<div class="layout-div">
        foreach (OrgRow r in myChart) {
            @:<div class="box-container">
            var rowStyle = new OrgChartRowCss(r.Count(), containerWidth, gutterWidth);
            foreach (Person p in r) {
                @:<div class="base" style="@rowStyle.BoxStyle">@p.Name</div>
            }
            @:</div>
        }
        @:</div>
}

This is what shows up in the browser

<style>
    .layout-div { box-sizing: border-box; text-align: left; vertical-align:top; padding: 0; margin:0; display: inline-block }
    .base {box-sizing: border-box; text-align: left; vertical-align:top; padding: 0; margin:0; display:inline-block; border: 1px solid #000; height: 20px; text-align: center;}
    .box-container {box-sizing: border-box; text-align: left; vertical-align:top; padding: 0; margin:0; border none; height: 20px; text-align: center; margin:0 0 8px 0;}

    /* This comes from the Chart class in the library. Not a good example, but shows capability.  */
    .box-from-chart-class { border none; height: 20px; text-align: center; margin:0 0 8px 0; }
</style>
    <div class="layout-div">
        <div class="box-container">
            <div class="base" style="width: 636px; margin-left: 80px;">Top</div>
        </div>
        <div class="box-container">
            <div class="base" style="width: 276px; margin-left: 80px;">1-1</div>
            <div class="base" style="width: 276px; margin-left: 80px;">1-2</div>
        </div>
        <div class="box-container">
            <div class="base" style="width: 156px; margin-left: 80px;">2-1</div>
            <div class="base" style="width: 156px; margin-left: 80px;">2-2</div>
            <div class="base" style="width: 156px; margin-left: 80px;">2-3</div>
        </div>
        <div class="box-container">
            <div class="base" style="width: 96px; margin-left: 80px;">3-1</div>
            <div class="base" style="width: 96px; margin-left: 80px;">3-2</div>
            <div class="base" style="width: 96px; margin-left: 80px;">3-3</div>
            <div class="base" style="width: 96px; margin-left: 80px;">3-4</div>
        </div>
        <div class="box-container">
            <div class="base" style="width: 60px; margin-left: 80px;">4-1</div>
            <div class="base" style="width: 60px; margin-left: 80px;">4-2</div>
            <div class="base" style="width: 60px; margin-left: 80px;">4-3</div>
            <div class="base" style="width: 60px; margin-left: 80px;">4-4</div>
            <div class="base" style="width: 60px; margin-left: 80px;">4-5</div>
        </div>
    </div>
</body>

Which looks like this image

Still early in the concept, but I think it shows some promise, especially when building reusable components.

RandyBuchholz avatar Dec 23 '16 18:12 RandyBuchholz

@RandyBuchholz Same remarks stil hold: call the Less compiler with Process.start, using stdio redirection to push a stylesheet and variables into the compiler and get the compiled CSS out, then cache it keyed on the input. You can do that with string snippits as well as you can with actual files on disk.

Apart from that; this idea of yours is, quite frankly, insane. There's no way you're going to end up making this work in any kind of performant manner without bundling your generated CSS together, at which point: congratulations, you've reinvented Less's @import mechanic in an obtuse, inner platform no-one other than yourself will ever gain any kind of exposure to or aptitude with.

rjgotten avatar Dec 23 '16 19:12 rjgotten

Errrrr..... yeah, as far as I can tell, now that you've explained a bit more, it seems quite out of scope.

matthew-dean avatar Dec 28 '16 06:12 matthew-dean

Closing as out of Less scope.

Besides what @matthew-dean and @rjgotten wrote:

The ~@foo syntax in Visual Studio (using the Web Compiler wrapper on less.js) doesn't complain, gives me intellisense

A language should not be modified to meet some occasional quirk in a syntax-highlighter (i.e. Intellisense in this case).

seven-phases-max avatar Dec 30 '16 00:12 seven-phases-max

@seven-phases-max, yeah, I was getting way off track there.

RandyBuchholz avatar Dec 30 '16 16:12 RandyBuchholz