Skip to content

Mixin return values #538

Closed
Closed

Description

@matthew-dean

Can I set a return value as a color? As in:

.myselector {
   border: 1px solid .custommixin(@colorValue);
}

Just wondering in response to another user's issue regarding color functions: #488

Activity

  1. cloudhead commented on Dec 28, 2011

    @cloudhead
    Member

    Oh I see, no. But you can do..

    .myselector () {
      @return: 2px;
    }
    
    .class {
      .myselector;
      border: @return solid red;
    }

    pretty ugly though.

  2. matthew-dean commented on Dec 28, 2011

    @matthew-dean
    MemberAuthor

    Ah, of course. It might be nice to have a returned value for custom color functions (and other custom value functions) when mixin guards are in place. @return could be a reserved variable for LESS. As you say, it's a bit ugly to just have a mixin do nothing but variable assignment when it's called.

    Would be nicer to see the first example I posted supported at some point. The rationale being that you have spin, lighten, darken, etc functioning as built-in mixins, so the logic for return values is already there in LESS, it would just be opening up the door for custom mixins.

  3. matthew-dean commented on Dec 28, 2011

    @matthew-dean
    MemberAuthor

    Not I think that programming said functionality is easy mind you, just that it would empower people to extend the logic a bit.

  4. cloudhead commented on Dec 29, 2011

    @cloudhead
    Member

    yes, true, but I also like how it currently is, where the 'functions' are all javascript..

  5. jacobrask commented on Jan 30, 2012

    @jacobrask

    Couldn't variables accept arguments the same way mixins do? My usecase would be for instance:

    @boxGlow(@spread: 5px, @color: #f00): inset 0 0 @spread @color;
    .myselector {
       box-shadow: 1px 1px 1px #000, @boxGlow(2px, #00f);
    }
    

    It's also fairly analogous with JavaScript where functions live in regular variables.

  6. jacobrask commented on Jan 31, 2012

    @jacobrask

    @cloudhead: If I spent some time implementing that feature (I haven't looked at the Less source yet, so I can't promise anything), would you be willing to add it if the code is good enough?

  7. tylertate commented on Mar 21, 2012

    @tylertate

    Adding a return capability to mixins would preserve the mapping of mixins to JavaScript functions, while still facilitating @jacobrask and @MatthewDL's use case. I've documented this a bit more on issue 637.

  8. lukeapage commented on Feb 25, 2013

    @lukeapage
    Member

    duplicate of #538

  9. lukeapage commented on Feb 25, 2013

    @lukeapage
    Member

    woops, this is #538

  10. akashivskyy commented on Mar 11, 2013

    @akashivskyy

    This would be a very, very useful solution.

    I'm trying to implement dynamically resizing images (like [UIImage resizable...] on iOS) and I would like to use a function which will return an URL string, not property/value pair.

    Curently I'm using @cloudhead's solution.

  11. matthew-dean commented on Dec 21, 2013

    @matthew-dean
    MemberAuthor

    Just to tie this in a nice bow, this should be included when the options.json support is added. Issue: #850

  12. cloudhead commented on Dec 30, 2013

    @cloudhead
    Member

    Mixins are mixins, we must not conflate their usage with functions. If having the ability to define custom functions in the style sheet is something we want though, that can be a separate discussion.

  13. 38 remaining items

  14. matthew-dean commented on Sep 20, 2016

    @matthew-dean
    MemberAuthor

    @andrewhosgood What happens here?

    .halfway-between(@large, @small) {
        max(@large, @small) - (abs(@large - @small) / 2);
    }
    .halfway-between(@large, @small) {
        property: value;
        foo: bar;
    }
    .rule {
        width: halfway-between(3, 2);
    }

    Ultimately, a mixin is a parameterized ruleset that can have multiple matches, and returns multiple values, and a function name can only have one match (per scope) and can only return one value.

    I think @battlesnake had the simplest and most straightforward syntax proposal:

    @function square(@x): @x * @x;

    A slight adjustment so that the scope of @x isn't confused:

    @function square(@x) { @x * @x; }

    Or (possibly) so that we don't confuse with JS-based functions:

    @expression square(@x) { @x * @x; }

    I think single-use expressions would be simplest to grok, and wouldn't pollute understanding of mixins. And, would also serve most of the examples given. Basically, you're just short-handing (aliasing) expressions for quick re-use. Thoughts? I do wonder if there's a way to "define" the expression name without an at-rule, though. Hmm.

  15. andrewhosgood commented on Sep 21, 2016

    @andrewhosgood

    @matthew-dean Point taken. Just trying to use existing patterns. Amending my request then, would it be:

    @function halfway-between(@large, @small) {
        max(@large, @small) - (abs(@large - @small) / 2);
    }

    Not worried about syntax, but this would then allow me to do the thing I can't do currently.

  16. matthew-dean commented on Sep 21, 2016

    @matthew-dean
    MemberAuthor

    Syntax is the hardest part to get right. And you want to get it right because it's a new language feature.

    I'm a little wary of @function now, more than I was when this discussion was active in the past, just because of @plugin-defined functions and existing functions in Less.js. And without a return statement it's not very function-y.

    @expr square(@x): { @x * @x };
    @expr halfway-between(@large, @small): {
        max(@large, @small) - (abs(@large - @small) / 2)
    };
    

    Thinking over it more, I think the colon : assignment and the semi-colon ; terminator is more logical. In that square(@x) is being assigned the value of the evaluated expression. This would seem to keep it more in line with detached rulesets. The braces {} indicate that the scope of @x is not the surrounding scope of the statement, but what is being assigned through the expression alias.

    I like this simpler concept of re-usable expressions rather than "functions" (which already means "defined by the parsing language" i.e. JavaScript). So @expression or @expr makes sense to me here. I think re-usable expressions has more wide-spread utility and is easier to understand.

  17. rjgotten commented on Sep 21, 2016

    @rjgotten
    Contributor

    I like this simpler concept of re-usable expressions rather than "functions"

    Basically; they're parametrized pre-processor macro expansions like in plain old C, right? But hopefully without the crazy abuse that came with those, since Less will have @plugin functions as a far more decent alternative for the heavier lifting and true complex functions.

  18. seven-phases-max commented on Sep 21, 2016

    @seven-phases-max
    Member

    @rjgotten

    a far more decent alternative for the heavier lifting and true complex functions.

    #538 (comment). Though never mind.


    And I still object the inventation of the special syntax hardcoded to specific "one liner" examples. Still smells like "I love to invent new cool syntaxes" syndrome.
    After all it's just asking for more issues from the parser implementation point of view... For instance recall #2785 and think how ambiguous

    {
       foo();
       foo() - bar();
       bar();
    }

    becomes actually. There you'll have to introduce a lot of new parsing rules to detect which statement is actually the function returning value and which are just root function calls (not even counting a friendly error messages if something goes wrong).
    So in short, I think everything I wrote in #538 (comment) is still in effect.

    And yes, stressing the Sassish @at-rule directive yet again - never been in Less yet, so why is it going to be now? (It seems like someone is just using too much PostCSS recently ;).

  19. matthew-dean commented on Sep 21, 2016

    @matthew-dean
    MemberAuthor

    @seven-phases-max

    {
       foo();
       foo() - bar();
       bar();
    }

    I was implying that multi-statements would be invalid here (would evaluate to a single expression), so that wouldn't apply, BUT....

    ...stressing the Sassish @at-rule directive yet again - never been in Less yet, so why is it going to be now? (It seems like someone is just using too much PostCSS recently ;).

    I haven't been using PostCSS, but yes, writing both @function and @expression made me feel somewhat dirty. As I mentioned when this issue was re-commented on, much of the syntax discussion has moved even further away from this possibility. Less just doesn't have a matching syntactical paradigm for this, because everything is declarative. Meaning, even in a return statement in a mixin, these two statements would reasonably be equal, since values are constants for a scope (once resolved).

    .function-sqralpha(@c) {
        @a: alpha(@c);
        return @a * @a;
    }
    .function-sqralpha(@c) {
      return @a * @a;
      @a: alpha(@c);
    }

    So, either way, with what's discussed so far, it seems somewhat square peg / round hole. I don't think mixins can reasonably pretend to be functions (without some compromises and unexpected behavior), and defining functions (or expressions or macro expansions) via Less (that is, in your stylesheet) has proven to also be problematic.


    On a separate note-

    One thing that might lean us even a bit more to closing this thread: when I was looking back through comments, including the one you linked to, you had this as a not an ideal way to solve the above problem.

    functions.addMultiple({
        sqralpha : function(c) {
            var a = c.alpha; // no docs and no guaranty this internal stays the same, but there's no easy way to reuse built-in Less `alpha()` here
            return new tree.Dimension(a * a); // Dimension? some kind of quantum mechanics?
        }
    });

    With Less 3.0, I've simplified returns so that any non-Node (other than falsey values) returned by a function is cast to an Anonymous Node, such that it's easily output into your final CSS. Obviously, if you want to include that result in another expression, you need to be explicit in the Node type. Buuuuut.... 3.0 also includes a "late parsing" feature (all values are Anonymous until referenced - this allows property referencing without creating extra parsing work or extra nodes), so that could be repurposed in order to just be like:

    functions.addMultiple({
        sqralpha : function(c) {
            var a = c.alpha; // docs have started! doing my best!
            return a * a;     // Cast to Dimension because Less is cool... maybe?
        }
    });

    And considering 3.0 should be all about functions and @plugin, and the remaining list of things it needs to release... I would say at the least, this isn't the right time for this feature. I did my best to simplify the latest examples, but even with that, your objections are valid, and I'm ok to close for now.

  20. rjgotten commented on Sep 26, 2016

    @rjgotten
    Contributor

    @seven-phases-max
    #538 (comment). Though never mind.

    No no; you raise a good point.

    There's substantial overhead for the middle-ground, where you have more than a simple one-liner expression to do, but not enough to warrant firing up a JS plugin and writing code that handles all the node-type mappings.

    While @matthew-dean raises a good point that node return types could be inferred, that still feels like a lot of overhead for some simple math or string interpolation. (In particular the latter; string interpolation requires a temporary variable, so you can never write a one-line expression for it.)

    If working a usable return into the syntax is the problem, then why not skip the explicit return statement altogether by specifying what name the out-variable will be bound to:

    .answer(@a, @b):@c {
      @c   : ~"The answer is @{sum}";
      @sum : @a + @b;
    }

    This feels natural with the order independence and declarative nature of the Less language. It also directly extends the signature of mixin declarations in a non-ambiguous manner, which the parser can look for and which avoids the need for an @expression or @function keyword or custom at-rule.

    This also means it can work together with mixin overloading and multicast calls. If a mixin is called like a function, it requires that a declaration exists which has both a matching parameter signature and a colon-separated out parameter specified. And if multiple matching overloads exist, the return value becomes a list of the relevant calls in mixin declaration order. (Just as how multiple matching overloads currently output rules in declaration order.)

  21. matthew-dean commented on Sep 26, 2016

    @matthew-dean
    MemberAuthor

    Huh. That's actually not so bad.

    Question: what happens then with properties, values, and other variables declared in the mixin (if called as a function). Safe to presume they're isolated from the caller scope (since properties couldn't be omitted in the location of the call, if the call is within a value expression)?

    That's not bad. We expanded functions to be called everywhere. So it could be that mixins could be called everywhere with the same checks to see if the resulting output node is legal in that location. So then functions = JS and mixins = LESS.

    I also liked how you addressed and resolved multiple matching mixins (a list as the result). Clever. And declarative.

    I was ready to give up on this idea but this is really not bad.

  22. matthew-dean commented on Sep 26, 2016

    @matthew-dean
    MemberAuthor

    We could also update the documentation that mixins, by default, "outputs" a ruleset, unless an output var (or vars, or $properties??) are specified.

  23. changed the title [-]Mixin return values (UPDATED: w/ discussion on @function syntax)[/-] [+]Mixin return values[/+] on Nov 7, 2016
  24. topokel commented on Mar 28, 2017

    @topokel

    Has there been an update for this?

  25. matthew-dean commented on Mar 29, 2017

    @matthew-dean
    MemberAuthor

    @distransient There has been more in-depth discussion around designing solutions for this in: less/less-meta#16.

    (Less-meta is a repo for higher-level goal planning for Less.js, rather than individual issues or bug reports.)

  26. stale commented on Nov 14, 2017

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions