2615 stories
·
1 follower

Modern Python Developer's Toolkit

1 Share

Save this story

Read the whole story
emrox
19 hours ago
reply
Hamburg, Germany
Share this story
Delete

target=blank

1 Comment

Does that make your eye twitch a little bit? Like… it’s a typo. It should be target="_blank" with an underscore to start the value. As in…

<a target="_blank" href="https://codepen.io">
  Open CodePen in a New Tab
</a>

Welp, that’s correct syntax!

In the case of the no-underscore target="blank", the blank part is just a name. It could be anything. It could be target="foo" or, perhaps to foreshadow the purpose here: target="open-new-links-in-this-space".

The difference:

  • target="_blank" is a special keyword that will open links in a new tab every time.
  • target="blank" will open the first-clicked link in a new tab, but any future links that share target="blank" will open in that same newly-opened tab.

I never knew this! I credit this tweet explanation.

I created a very basic demo page to show off the functionality (code). Watch as a new tab opens when I click the first link. Then, subsequent clicks from either also open tab open that link in that new second tab.

Why?

I think use cases here are few and far between. Heck, I’m not even that big of a fan of target="_blank". But here’s one I could imagine: documentation.

Say you’ve got a web app where people actively do work. It might make sense to open links to documentation from within that app in a new tab, so they aren’t navigating away from active work. But, maybe you think they don’t need a new tab for every documentation link. You could do like…

<a target="codepen-documentation" 
  href="https://blog.codepen.io/documentation/">
  View CodePen Documentation
</a> 

<!-- elsewhere -->

<a target="codepen-documentation" 
  href="https://blog.codepen.io/documentation/">
  About Asset Hosting
</a>

The post target=blank appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Read the whole story
emrox
2 days ago
reply
remember the basics
Hamburg, Germany
Share this story
Delete

Equal Columns With Flexbox: It’s More Complicated Than You Might Think

1 Share

You get a nice-looking design handed to you and it has this nice big hero section, followed by one of those three-up columns right beneath it. You know, like almost every other website you’ve ever worked on.

You bang through the hero section and get to work on the three-column section. It’s time to pull out our trusty friend flexbox! Except, you write display: flex and you get this mess instead of getting the three equal columns you’d expect.

CodePen Embed Fallback

This happens because of how flexbox calculates the base size of an element. You’ve probably read lots of flexbox tutorials, and many of them (including my own) are an overly simplistic example of what flexbox does without really digging into the complex things that flexbox does for us that we take for granted.

I’m positive you’ve seen examples and tutorials that look at something like this, where three divs shrink down around the content that’s inside them:

CodePen Embed Fallback

In other words, we get some block-level elements shrinking down and slotting next to one another. It feels like flex wants things to be as small as possible. But in reality, flexbox actually wants things to be as big as possible.

Wait, what? Flex shrinks things by default — that can’t be right! Right?

As awesome as flexbox is, what it’s doing under the hood is actually a little strange because, by default, it is doing two things at once. It first looks at the content size which is what we would get if by declaring width: max-content on an element. But on top of that, flex-shrink is also doing some work allowing the items to be smaller, but only if needed.

To really understand what’s going on, let’s break those two down and see how they work together.

Diving into max-content

max-content is a pretty handy property value in certain situations, but we want to understand how it works in this particular situation where we are trying to get three seemingly simple equal columns. So let’s strip away flexbox for a moment and look at what max-content does on its own.

MDN does a good job of explaining it:

The max-content sizing keyword represents the intrinsic maximum width of the content. For text content this means that the content will not wrap at all even if it causes overflows.

Intrinsic might throw you off here, but it basically means we’re letting the content decide on the width, rather than us explicitly setting a set width. Uri Shaked aptly describes the behavior by saying “the browser pretends it has infinite space, and lays all the text in a single line while measuring its width.”

So, bottom line, max-content allows the content itself to define the width of the element. If you have a paragraph, the width of that paragraph will be the text inside it without any line breaks. If it’s a long enough paragraph, then you end up with some horizontal scrolling.

CodePen Embed Fallback

Let’s revisit that overly-simplistic example of three block-level elements that shrink down and slot next to one another. That isn’t happening because of flex-shrink; it’s happening because that’s the size of those elements when their declared width is max-content. That’s literally as wide as they go because that’s as wide as the combined content inside each element.

Here, take a look at those elements without flexbox doing it’s flexbox stuff, but with a width: max-content on there instead:

CodePen Embed Fallback

So, when there’s just a small amount of text, the intrinsic max-content shrinks things down instead of flex-shrink. Of course, flexbox also comes in with it’s default flex-direction: row behavior which turns the flex items into columns, putting them right next to one another. Here’s another look but with the free space highlighted.

CodePen Embed Fallback

Adding flex-shrink to the equation

So we see that declaring display: flex pushes that max-content intrinsic size on flex items. Those items want to be as big as their content. But there is another default that comes in here as well, which is flex-shrink.

flex-shrink is basically looking at all the flex items in a flexible container to make sure they don’t overflow the parent. If the flex items can all fit next to each other without overflowing the flexible container, then flex-shrink won’t do anything at all… it’s job is already done.

But if the flex items do overflow the container (thanks to that max-content intrinsic width thing), the flex items are allowed to shrink to prevent that overflow because flex-shrink is looking out for that.

CodePen Embed Fallback

This is why flex-shrink has a default value of 1. Without it, things would get messy pretty quickly.

Here’s why the columns aren’t equal

Going back to our design scenario where we need three equal columns beneath a hero, we saw that the columns aren’t equal widths. That’s because flexbox starts by looking at the content size of each flex item before even thinking about shrinking them.

Using Firefox’s DevTools (because it’s got some unique flexbox visualizations that others don’t), we can actually see how flexbox is calculating everything.

For simplicity’s sake, as we dive deeper into this, let’s work with some nice round numbers. We can do this by declaring widths on our flex items. When we declare a width on a flex item, we throw that intrinsic size out the window, as we’ve now declared an explicit value instead. This makes figuring out what’s really going on a lot easier.

In the Pen below, we have a parent that’s a 600px wide flexible container (display: flex). I’ve removed anything that might influence the numbers, so no gap or padding. I’ve also switched out the border for an outline so we can still visualize everything easily.

CodePen Embed Fallback

The first and third flex items have a width: 300px and the middle one a width: 600px. If we add that all up, it’s a total of 1200px. That’s bigger than the the 600px available within the parent, so flex-shrink kicks in.

flex-shrink is a ratio. If everything has the same flex-shrink (which is 1 by default), they all shrink at the same rate. That doesn’t mean they all shrink to the same size or by the same amount, but they all shrink at the same rate.

If we jump back into Firefox DevTools, we can see the base size, the flex-shrink and the final size. In this case, the two 300px elements are now 150px, and the 600px one is now 300px.

The two elements that have a base width of 300px become 150px.
The larger element with a base width of 600px becomes 300px.

If we add up all the base sizes of all three flex items (the actual widths we declared on them), the total comes out to 1200px. Our flex container is 600px wide. If we divide everything by 2, it fits! They are all shrinking by the same rate, dividing their own widths by 2.

It’s not often that we have nice round numbers like that in the real world, but I think this does a nice job illustrating how flexbox does what it does when figuring out how big to make things.

Getting the columns to be equal

There are a few different ways to get the three columns we want to be equal in width, but some are better than others. For all the approaches, the basic idea is that we want to get all the columns base size to be the same. If they have an equal base size, then they will shrink (or grow, if we use flex-grow) at an equal rate when flexbox does it’s flex things, and in theory, that should make them the same size.

There are a few common ways to do this, but as I discovered while diving into all of this, I have come to believe those approaches are flawed. Let’s look at two of the most common solutions that I see used in the wild, and I’ll explain why they don’t work.

Method 1: Using flex: 1

One way we can try to get all the flex items to have the same base size is by declaring flex: 1 on all of them:

.flex-parent { display: flex; }
.flex-parent > * { flex: 1; }

In a tutorial I made once, I used a different approach, and I must have had 100 people asking why I wasn’t using flex: 1 instead. I replied by saying I didn’t want to dive into the flex shorthand property. But then I used flex: 1 in a new demo, and to my surprise, it didn’t work.

The columns weren’t equal.

CodePen Embed Fallback

The middle column here is larger than the other two. It’s not by a ton, but the whole design pattern I’m creating is just so you have perfectly equal columns every single time, regardless of the content.

So why didn’t it work in this situation? The culprit here is the padding on the component in the middle column.

And maybe you’ll say it’s silly to add padding to one of the items and not the others, or that we can nest things (we’ll get to that). In my opinion, though, I should be able to have a layout that works regardless of the content that we’re putting in it. The web is all about components that we can plug and play these days, after all.

When I first set this up, I was sure it would work, and seeing this issue pop up made me want to learn what was really going on here.

The flex shorthand does more than just set the flex-grow: 1. If you don’t already know, flex is shorthand for flex-grow, flex-shrink, and flex-basis.

The default values for those constituent properties are:

.selector {
  flex-grow: 0;
  flex-shrink: 1;
  flex-basis: auto;
}

I’m not going to deep dive flex-basis in this article, as that’s something Robin has already done well. For now, we can think of it like width to keep things simple since we aren’t playing with flex-direction.

We’ve already seen how flex-shrink works. flex-grow is the opposite. If the size of all the flex items along the main axis is smaller than the parent, they can grow to fill that space.

So by default, flex items:

  • don’t grow;
  • if they would otherwise overflow the parent, they are allowed to shrink;
  • their width acts like max-content.

Putting that all together, the flex shorthand defaults to:

.selector {
  flex: 0 1 auto;
}

The fun thing with the flex shorthand is you can omit values. So, when we declare flex: 1, it’s setting the first value, flex-grow, to 1, which basically turns on flex-grow.

The strange thing here is what happens to the values that you omit. You’d expect them to stay at their defaults, but they don’t. Before we get to what happens, though, let’s first dive into what flex-grow even does.

As we’ve seen, flex-shrink allows elements to shrink if their base sizes add up to a computed value that’s bigger than the available width of the parent container. flex-grow is the opposite. If the grand total of the element base sizes is smaller than the value of the parent container’s width, then they will grow to fill the available space.

If we take that super basic example where we have three small divs next to one another and add flex-grow: 1, they grow to fill that leftover space.

CodePen Embed Fallback

But if we have three divs with unequal widths — like those ones we started with — adding flex-grow to them won’t do anything at all. They won’t grow because they’re already taking up all the available space —so much space, in fact, that flex-shrink needs to kick in and shrink them down to fit!

But, as folks have pointed out to me, setting flex: 1 can work to create equal columns. Well, sort of, as we saw above! In simple situations it does work though, as you can see below.

CodePen Embed Fallback

When we declare flex: 1 it works because, not only does this set the flex-grow to 1, but it also changes the flex-basis!

.selector {
  flex: 1;
  /* flex-grow: 1; */
  /* flex-shrink: 1; */
  /* flex-basis: 0%; Wait what? */
}

Yup, setting flex: 1 sets the flex-basis to 0%. This overwrites that intrinsic sizing we had before that behaved like max-content. All of our flex-items now want to have a base size of 0!

Looking at the expanded view of the flex: 1 shorthand in DevTools shows us that the flex-basis has changed to 0

So their base sizes are 0 now, but because of the flex-grow, they can all grow to fill up the empty space. And really, in this case, flex-shrink is no longer doing anything, as all the flex items now have a width of 0, and are growing to fill the available space.

FireFox’s DevTools showing an element with flex: 1 has a content size of 0 and is growing to fill the available space.

Just like the shrink example before, we’re taking the space that’s available, and letting all the flex items grow at an equal rate. Since they are all a base width of 0, growing at an equal rate means the available space is equally divided between them and they all have the same final size!

Except, as we saw, that’s not always the case…

The reason for this is because, when flexbox does all this stuff and distributes the space, whether it’s shrinking or growing a flex item, it’s looking at the content size of the element. If you remember back to the box model, we have the content size itself, then the padding, border, and margin outside of that.

And no, I didn’t forget * { box-sizing: border-box; }.

This is one of those strange quirks of CSS but it does make sense. If the browser looked at the width of those elements and included their padding and borders in the calculations, how could it shrink things down? Either the padding would also have to shrink or things are going to overflow the space. Both of those situations are terrible, so instead of looking at the box-size of elements when calculating the base size of them, it only looks at the content-box!

So, setting flex: 1 causes a problem in cases where you have borders or padding on some of your elements. I now have three elements that have a content-size of 0, but my middle one has padding on it. If we didn’t have that padding, we’d have the same math we did when we looked at how flex-shrink works.

A parent that is 600px and three flex items with a width of 0px. They all have a flex-grow: 1 so they grow at an equal rate, and they each end up 200px wide. But the padding mucks it all up. Instead, I end up with three divs with a content size of 0, but the middle one has padding: 1rem. That means it has a content size of 0, plus 32px padding as well.

We have 600 - 32 = 568px to divide equally, instead of 600px. All the divs want to grow at an equal rate, so 568 / 3 = 189.3333px.

And that’s what happens!

But… remember, that’s their content size, not the total width! That leaves us with two divs with a width of 189.333px, and another with a which of 189.333px + 32 = 221.333px. That’s a pretty substantial difference!

CodePen Embed Fallback

Method 2: flex-basis: 100%

I have always handled this like this:

.flex-parent {
  display: flex;
}

.flex-parent > * {
  flex-basis: 100%;
}

I thought this worked for the longest time. Actually, this was supposed to be my final solution after showing that flex: 1 doesn’t work. But while I was writing this article, I realized it also falls into the same problem, but it’s a lot less obvious. Enough so that I didn’t notice it with my eyes.

The elements are all trying to be 100% width, meaning they all want to match the width of the parent, which, again, is 600px (and in normal circumstances, is often much bigger, which further reduces the perceivable difference).

The thing is that 100% includes the padding in the computed values (because of * { box-size: border-box; }, which for the sake of this article, I’m assuming everyone is using). So, the outer divs end up with a content size of 600px, whereas the middle div ends up with a content size of 600 - 32 = 568px.

When the browser is working out how to evenly divide the space, it isn’t looking at how to evenly squish 1800px into a 600px space, but rather it’s looking at how to squish 1768px. Plus, as we saw earlier, flex items don’t shrink by the same amount, but at an equal pace! So, the element with padding shrinks slightly less in total than the others do.

This results in the .card having a final width of 214.483px while the others clock in at 192.75px. Again, this leads to unequal width values, though the difference is smaller than we saw with the flex: 1 solution.

CodePen Embed Fallback

Why CSS Grid is the better choice here

While all this is a little frustrating (and even a little confusing), it all happens for a good reason. If margins, padding, or borders changed sizes when flex gets involved, it would be a nightmare.

And maybe this means that CSS Grid might be a better solution to this really common design pattern.

I’ve long thought that flexbox was easier to pick up and start using than grid, but grid gives you more ultimate control in the long run, but that it’s a lot harder to figure out. I’ve changed my mind on that recently though, and I think not only does grid give us better control in this type of situation, but it’s actually more intuitive as well.

Normally, when we use grid, we explicitly declare our columns using grid-template-columns. We don’t have to do that though. We can make it behave a lot like flexbox does by using grid-auto-flow: column.

.grid-container {
  display: grid;
  grid-auto-flow: column;
}

Just like that, we end up with the same type of behavior as throwing display: flex on there. Like flex, the columns can potentially be unbalanced, but the advantage with grid is that the parent has total control over everything. So, rather than the content of the items having an impact like they would in flexbox, we only need one more line of code and we can solve the problem:

.grid-container {
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: 1fr;
}

I love that this is all on the parent selector, and that we don’t have to select the children to help get the layout that we are after!

CodePen Embed Fallback

The interesting thing here is how fr units work. They are literally called flex units in the spec, and they work just like flexbox does in dividing up space;. The big difference: they’re looking at the other tracks to determine how much space they have, paying no attention to the content inside those tracks.

That’s the real magic here. By declaring grid-auto-columns: 1fr, we are in essence saying, “by default, all my columns should have an equal width,” which is what we’ve been after from the start!

But what about at small screens?

What I love with this approach is we can keep it super simple:

.grid-container {
  display: grid;
  gap: 1em;
}

@media (min-width: 35em) {
  grid-auto-flow: column;
  grid-auto-columns: 1fr;
}

And just like that, it works perfectly. And by declaring display: grid from the start, we can include the gap to maintain equal spacing, whether the children are rows or columns.

I also find this to be a lot more intuitive than changing the flex-direction within a media query to get a similar result. As much as I love flexbox (and I really do still think it has great use cases), the fact that declaring flex-direction: column creates rows, and vice versa, is a little counter-intuitive at first glance.

And of course, if you prefer rolling without media queries, there is nothing stopping you from taking this to the next level with the help of auto-fit, which would be similar to setting something up with flex-wrap (though not exactly the same):

.grid-container {
  display: grid;
  gap: 1em;
  grid-template-columns: repeat(auto-fit, minmax(10em, 25em));
}

Making it work with flexbox

I realize that we can get around this with flexbox by nesting the element with the padding on it. We’ve done this since we started making layouts using floats, and Bootstrap really hammered home this type of design pattern.

<div class="container">
  <div class="row">
    <div class="col"> <div class="">... </div>
    <div class="col"> <div class="element-with-padding">...</div> </div>
    <div class="col"> ... </div>
  </div>
</div>

And there is nothing wrong with that. It works! But floats work too, and we’ve stopped using them for layouts as better solutions have been released in recent years.

One of the reasons that I love grid is because we can simplify our markup quite a bit. Just like we ditched floats for a better solution, I’d at least like to people to keep an open mind that maybe, just maybe, grid could be a better, and more intuitive solution for this type of design pattern.

Flexbox still has it’s place, of course

I still love flexbox, but I think its real power comes from times that we want to rely on the intrinsic width of the flex items, such as with navigations, or groups of elements, such as buttons or other items of varying width that you want to go next to one another.

In those situations, that behavior is an asset that makes things like even spacing between unequal items such a breeze! Flexbox is wonderful, and I have no plans to stop using.

In other situations though, when you find yourself fighting with how flexbox is trying to work, maybe you could turn to grid instead, even if it’s not a typical “2d” grid where you’re told you should be using it for.

People often tell me that they struggle to figure out grid because it’s too complicated, and while it can be, as we saw here, it doesn’t have to be.


The post Equal Columns With Flexbox: It’s More Complicated Than You Might Think appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Read the whole story
emrox
2 days ago
reply
Hamburg, Germany
Share this story
Delete

Implementing Private Fields for JavaScript

2 Shares

This post is cross-posted from Matthew Gaudet’s blog

When implementing a language feature for JavaScript, an implementer must make decisions about how the language in the specification maps to the implementation. Sometimes this is fairly simple, where the specification and implementation can share much of the same terminology and algorithms. Other times, pressures in the implementation make it more challenging, requiring or pressuring the implementation strategy diverge to diverge from the language specification.

Private fields is an example of where the specification language and implementation reality diverge, at least in SpiderMonkey– the JavaScript engine which powers Firefox. To understand more, I’ll explain what private fields are, a couple of models for thinking about them, and explain why our implementation diverges from the specification language.

Private Fields

Private fields are a language feature being added to the JavaScript language through the TC39 proposal process, as part of the class fields proposal, which is at Stage 4 in the TC39 process. We will ship private fields and private methods in Firefox 90.

The private fields proposal adds a strict notion of ‘private state’ to the language. In the following example, #x may only be accessed by instances of class A:

class A {
  #x = 10;
}

This means that outside of the class, it is impossible to access that field. Unlike public fields for example, as the following example shows:

class A {
  #x = 10; // Private field
  y = 12; // Public Field
}

var a = new A();
a.y; // Accessing public field y: OK
a.#x; // Syntax error: reference to undeclared private field

Even various other tools that JavaScript gives you for interrogating objects are prevented from accessing private fields (e.g. Object.getOwnProperty{Symbols,Names} don’t list private fields; there’s no way to use Reflect.get to access them).

A Feature Three Ways

When talking about a feature in JavaScript, there are often three different aspects in play: the mental model, the specification, and the implementation.

The mental model provides the high-level thinking that we expect programmers to use mostly. The specification in turn provides the detail of the semantics required by the feature. The implementation can look wildly different from the specification text, so long as the specification semantics are maintained.

These three aspects shouldn’t produce different results for people reasoning through things (though, sometimes a ‘mental model’ is shorthand, and doesn’t accurately capture semantics in edge case scenarios).

We can look at private fields using these three aspects:

Mental Model

The most basic mental model one can have for private fields is what it says on the tin: fields, but private. Now, JS fields become properties on objects, so the mental model is perhaps ‘properties that can’t be accessed from outside the class’.

However, when we encounter proxies, this mental model breaks down a bit; trying to specify the semantics for ‘hidden properties’ and proxies is challenging (what happens when a Proxy is trying to provide access control to properties, if you aren’t supposed to be able see private fields with Proxies? Can subclasses access private fields? Do private fields participate in prototype inheritance?) . In order to preserve the desired privacy properties an alternative mental model became the way the committee thinks about private fields.

This alternative model is called the ‘WeakMap’ model. In this mental model you imagine that each class has a hidden weak map associated with each private field, such that you could hypothetically ‘desugar’

class A {
  #x = 15;
  g() {
    return this.#x;
  }
}

into something like

class A_desugared {
  static InaccessibleWeakMap_x = new WeakMap();
  constructor() {
    A_desugared.InaccessibleWeakMap_x.set(this, 15);
  }

  g() {
    return A_desugared.InaccessibleWeakMap_x.get(this);
  }
}

The WeakMap model is, surprisingly, not how the feature is written in the specification, but is an important part of the design intention is behind them. I will cover a bit later how this mental model shows up in places later.

Specification

The actual specification changes are provided by the class fields proposal, specifically the changes to the specification text. I won’t cover every piece of this specification text, but I’ll call out specific aspects to help elucidate the differences between specification text and implementation.

First, the specification adds the notion of [[PrivateName]], which is a globally unique field identifier. This global uniqueness is to ensure that two classes cannot access each other’s fields merely by having the same name.

function createClass() {
  return class {
    #x = 1;
    static getX(o) {
      return o.#x;
    }
  };
}

let [A, B] = [0, 1].map(createClass);
let a = new A();
let b = new B();

A.getX(a); // Allowed: Same class
A.getX(b); // Type Error, because different class.

The specification also adds a new ‘internal slot’, which is a specification level piece of internal state associated with an object in the spec, called [[PrivateFieldValues]] to all objects. [[PrivateFieldValues]] is a list of records of the form:

{
  [[PrivateName]]: Private Name,
  [[PrivateFieldValue]]: ECMAScript value
}

To manipulate this list, the specification adds four new algorithms:

  1. PrivateFieldFind
  2. PrivateFieldAdd
  3. PrivateFieldGet
  4. PrivateFieldSet

These algorithms largely work as you would expect: PrivateFieldAdd appends an entry to the list (though, in the interest of trying to provide errors eagerly, if a matching Private Name already exists in the list, it will throw a TypeError. I’ll show how that can happen later). PrivateFieldGet retrieves a value stored in the list, keyed by a given Private name, etc.

The Constructor Override Trick

When I first started to read the specification, I was surprised to see that PrivateFieldAdd could throw. Given that it was only called from a constructor on the object being constructed, I had fully expected that the object would be freshly created, and therefore you’d not need to worry about a field already being there.

This turns out to be possible, a side effect of some of the specification’s handling of constructor return values. To be more concrete, the following is an example provided to me by André Bargull, which shows this in action.

class Base {
  constructor(o) {
    return o; // Note: We are returning the argument!
  }
}

class Stamper extends Base {
  #x = "stamped";
  static getX(o) {
    return o.#x;
  }
}

Stamper is a class which can ‘stamp’ its private field onto any object:

let obj = {};
new Stamper(obj); // obj now has private field #x
Stamper.getX(obj); // => "stamped"

This means that when we add private fields to an object we cannot assume it doesn’t have them already. This is where the pre-existence check in PrivateFieldAdd comes into play:

let obj2 = {};
new Stamper(obj2);
new Stamper(obj2); // Throws 'TypeError' due to pre-existence of private field

This ability to stamp private fields into arbitrary objects interacts with the WeakMap model a bit here as well. For example, given that you can stamp private fields onto any object, that means you could also stamp a private field onto a sealed object:

var obj3 = {};
Object.seal(obj3);
new Stamper(obj3);
Stamper.getX(obj3); // => "stamped"

If you imagine private fields as properties, this is uncomfortable, because it means you’re modifying an object that was sealed by a programmer to future modification. However, using the weak map model, it is totally acceptable, as you’re only using the sealed object as a key in the weak map.

PS: Just because you can stamp private fields into arbitrary objects, doesn’t mean you should: Please don’t do this.

Implementing the Specification

When faced with implementing the specification, there is a tension between following the letter of the specification, and doing something different to improve the implementation on some dimension.

Where it is possible to implement the steps of the specification directly, we prefer to do that, as it makes maintenance of features easier as specification changes are made. SpiderMonkey does this in many places. You will see sections of code that are transcriptions of specification algorithms, with step numbers for comments. Following the exact letter of the specification can also be helpful where the specification is highly complex and small divergences can lead to compatibility risks.

Sometimes however, there are good reasons to diverge from the specification language. JavaScript implementations have been honed for high performance for years, and there are many implementation tricks that have been applied to make that happen. Sometimes recasting a part of the specification in terms of code already written is the right thing to do, because that means the new code is also able to have the performance characteristics of the already written code.

Implementing Private Names

The specification language for Private Names already almost matches the semantics around Symbols, which already exist in SpiderMonkey. So adding PrivateNames as a special kind of Symbol is a fairly easy choice.

Implementing Private Fields

Looking at the specification for private fields, the specification implementation would be to add an extra hidden slot to every object in SpiderMonkey, which contains a reference to a list of {PrivateName, Value} pairs. However, implementing this directly has a number of clear downsides:

  • It adds memory usage to objects without private fields
  • It requires invasive addition of either new bytecodes or complexity to performance sensitive property access paths.

An alternative option is to diverge from the specification language, and implement only the semantics, not the actual specification algorithms. In the majority of cases, you really can think of private fields as special properties on objects that are hidden from reflection or introspection outside a class.

If we model private fields as properties, rather than a special side-list that is maintained with an object, we are able to take advantage of the fact that property manipulation is already extremely optimized in a JavaScript engine.

However, properties are subject to reflection. So if we model private fields as object properties, we need to ensure that reflection APIs don’t reveal them, and that you can’t get access to them via Proxies.

In SpiderMonkey, we elected to implement private fields as hidden properties in order to take advantage of all the optimized machinery that already exists for properties in the engine. When I started implementing this feature André Bargull – a SpiderMonkey contributor for many years – actually handed me a series of patches that had a good chunk of the private fields implementation already done, for which I was hugely grateful.

Using our special PrivateName symbols, we effectively desuagar

class A {
  #x = 10;
  x() {
    return this.#x;
  }
}

to something that looks closer to

class A_desugared {
  constructor() {
    this[PrivateSymbol(#x)] = 10;
  }
  x() {
    return this[PrivateSymbol(#x)];
  }
}

Private fields have slightly different semantics than properties however. They are designed to issue errors on patterns expected to be programming mistakes, rather than silently accepting it. For example:

  1. Accessing an a property on an object that doesn’t have it returns undefined. Private fields are specified to throw a TypeError, as a result of the PrivateFieldGet algorithm.
  2. Setting a property on an object that doesn’t have it simply adds the property. Private fields will throw a TypeError in PrivateFieldSet.
  3. Adding a private field to an object that already has that field also throws a TypeError in PrivateFieldAdd. See “The Constructor Override Trick” above for how this can happen.

To handle the different semantics, we modified the bytecode emission for private field accesses. We added a new bytecode op, CheckPrivateField which verifies an object has the correct state for a given private field. This means throwing an exception if the property is missing or present, as appropriate for Get/Set or Add. CheckPrivateField is emitted just before using the regular ‘computed property name’ path (the one used for A[someKey]).

CheckPrivateField is designed such that we can easily implement an inline cache using CacheIR. Since we are storing private fields as properties, we can use the Shape of an object as a guard, and simply return the appropriate boolean value. The Shape of an object in SpiderMonkey determines what properties it has, and where they are located in the storage for that object. Objects that have the same shape are guaranteed to have the same properties, and it’s a perfect check for an IC for CheckPrivateField.

Other modifications we made to make to the engine include omitting private fields from the property enumeration protocol, and allowing the extension of sealed objects if we are adding private field.

Proxies

Proxies presented us a bit of a new challenge. Concretely, using the Stamper class above, you can add a private field directly to a Proxy:

let obj3 = {};
let proxy = new Proxy(obj3, handler);
new Stamper(proxy)

Stamper.getX(proxy) // => "stamped"
Stamper.getX(obj3)  // TypeError, private field is stamped
                    // onto the Proxy Not the target!

I definitely found this surprising initially. The reason I found this surprising was I had expected that, like other operations, the addition of a private field would tunnel through the proxy to the target. However, once I was able to internalize the WeakMap mental model, I was able to understand this example much better. The trick is that in the WeakMap model, it is the Proxy, not the target object, used as the key in the #x WeakMap.

These semantics presented a challenge to our implementation choice to model private fields as hidden properties however, as SpiderMonkey’s Proxies are highly specialized objects that do not have room for arbitrary properties. In order to support this case, we added a new reserved slot for an ‘expando’ object. The expando is an object allocated lazily that acts as the holder for dynamically added properties on the proxy. This pattern is used already for DOM objects, which are typically implemented as C++ objects with no room for extra properties. So if you write document.foo = "hi", this allocates an expando object for document, and puts the foo property and value in there instead. Returning to private fields, when #x is accessed on a Proxy, the proxy code knows to go and look in the expando object for that property.

In Conclusion

Private Fields is an instance of implementing a JavaScript language feature where directly implementing the specification as written would be less performant than re-casting the specification in terms of already optimized engine primitives. Yet, that recasting itself can require some problem solving not present in the specification.

At the end, I am fairly happy with the choices made for our implementation of Private Fields, and am excited to see it finally enter the world!

Acknowledgements

I have to thank, again, André Bargull, who provided the first set of patches and laid down an excellent trail for me to follow. His work made finishing private fields much easier, as he’d already put a lot of thought into decision making.

Jason Orendorff has been an excellent and patient mentor as I have worked through this implementation, including two separate implementations of the private field bytecode, as well as two separate implementations of proxy support.

Thanks to Caroline Cullen, and Iain Ireland for helping to read drafts of this post, and to Steve Fink for fixing many typos.

The post Implementing Private Fields for JavaScript appeared first on Mozilla Hacks - the Web developer blog.

Read the whole story
emrox
4 days ago
reply
Hamburg, Germany
alvinashcraft
5 days ago
reply
West Grove, PA
Share this story
Delete

The Plan for React 18

1 Share

The React team is excited to share a few updates:

  1. We’ve started work on the React 18 release, which will be our next major version.
  2. We’ve created a Working Group to prepare the community for gradual adoption of new features in React 18.
  3. We’ve published a React 18 Alpha so that library authors can try it and provide feedback.

These updates are primarily aimed at maintainers of third-party libraries. If you’re learning, teaching, or using React to build user-facing applications, you can safely ignore this post. But you are welcome to follow the discussions in the React 18 Working Group if you’re curious!

What’s coming in React 18

When it’s released, React 18 will include out-of-the-box improvements (like automatic batching), new APIs (like startTransition), and a new streaming server renderer with built-in support for React.lazy.

These features are possible thanks to a new opt-in mechanism we’re adding in React 18. It’s called “concurrent rendering” and it lets React prepare multiple versions of the UI at the same time. This change is mostly behind-the-scenes, but it unlocks new possibilities to improve both real and perceived performance of your app.

If you’ve been following our research into the future of React (we don’t expect you to!), you might have heard of something called “concurrent mode” or that it might break your app. In response to this feedback from the community, we’ve redesigned the upgrade strategy for gradual adoption. Instead of an all-or-nothing “mode”, concurrent rendering will only be enabled for updates triggered by one of the new features. In practice, this means you will be able to adopt React 18 without rewrites and try the new features at your own pace.

A gradual adoption strategy

Since concurrency in React 18 is opt-in, there are no significant out-of-the-box breaking changes to component behavior. You can upgrade to React 18 with minimal or no changes to your application code, with a level of effort comparable to a typical major React release. Based on our experience converting several apps to React 18, we expect that many users will be able to upgrade within a single afternoon.

We successfully shipped concurrent features to tens of thousands of components at Facebook, and in our experience, we’ve found that most React components “just work” without additional changes. We’re committed to making sure this is a smooth upgrade for the entire community, so today we’re announcing the React 18 Working Group.

We’re trying something new for this release: We’ve invited a panel of experts, developers, library authors, and educators from across the React community to participate in our React 18 Working Group to provide feedback, ask questions, and collaborate on the release. We couldn’t invite everyone we wanted to this initial, small group, but if this experiment works out, we hope there will be more in the future!

The goal of the React 18 Working Group is to prepare the ecosystem for a smooth, gradual adoption of React 18 by existing applications and libraries. The Working Group is hosted on GitHub Discussions and is available for the public to read. Members of the working group can leave feedback, ask questions, and share ideas. The core team will also use the discussions repo to share our research findings. As the stable release gets closer, any important information will also be posted on this blog.

For more information on upgrading to React 18, or additional resources about the release, see the React 18 announcement post.

Accessing the React 18 Working Group

Everyone can read the discussions in the React 18 Working Group repo.

Because we expect an initial surge of interest in the Working Group, only invited members will be allowed to create or comment on threads. However, the threads are fully visible to the public, so everyone has access to the same information. We believe this is a good compromise between creating a productive environment for working group members, while maintaining transparency with the wider community.

As always, you can submit bug reports, questions, and general feedback to our issue tracker.

How to try React 18 Alpha today

New alphas are regularly published to npm using the @alpha tag. These releases are built using the most recent commit to our main repo. When a feature or bugfix is merged, it will appear in an alpha the following weekday.

There may be significant behavioral or API changes between alpha releases. Please remember that alpha releases are not recommended for user-facing, production applications.

Projected React 18 release timeline

We don’t have a specific release date scheduled, but we expect it will take several months of feedback and iteration before React 18 is ready for most production applications.

  • Library Alpha: Available today
  • Public Beta: At least several months
  • Release Candidate (RC): At least several weeks after Beta
  • General Availability: At least several weeks after RC

More details about our projected release timeline are available in the Working Group. We’ll post updates on this blog when we’re closer to a public release.

Read the whole story
emrox
4 days ago
reply
Hamburg, Germany
Share this story
Delete

The Art of Design Spec'ing

1 Share

What are design specs?

Design specs (short for specifications) are the instructions attached with a design file to help the front-end engineers with the implementation of the UI of a web or a mobile app.


A bit of history

In the past, these instructions needed to cover all sorts of measurements and spaces in a design. However, when Zeplin was launched it changed the game entirely; It allowed designers and engineers to automatically see parts of the design specs once a design file has been exported to Zeplin.

Things got easier and faster with the rise of Figma where basic design specs show up right in the tool and updates automatically whenever any changes are made to the design.


Why do you need it?

1: Implementation Accuracy: design specs help the engineer better understand how the design should be implemented and how it should behave when a user interacts with it. It also makes designers look at their work from a different perspective and angle, allowing them to cover more edge cases and discover design flows early on.

2: Consistency: creating clear specs makes a designer think more about the consistency & scalability of the UI elements they've built, and also gives them a chance to evaluate some of their decisions and adjust the design based on that.

3: Communication: design specs cuts down the time spent in back and forth conversations between design and engineering during the implementation process. It saves everyone time by providing answers to the most common questions about the implementation, and that helps speed the implementation process and makes it more efficient.


To Summarize: Spec'ing your designs removes a lot of friction between design and engineering and saves everyone a lot of time. This will be a little bit of an investment on the design side, but will have great payoffs; As a designer, you'll have to do a bit more work before you hand off your designs, but that will minimize the clarifying questions you'd get from the engineers working on implementing your design.


When you should create design specs?

If you're using Figma or Sketch, you might not need to spec out everything such as widths, height, or even font sizes since this is already displayed automatically in the tool. However, for other parts like responsive or sticky UI elements, you will need to spec them out manually.

In some cases if you're working in a fast-moving environment like a small startup it might not make a lot of sense for you to spend much time working out detailed specs, you can instead spend more time with the engineers discussing the implementation details.

That being said, even at startups I would highly recommend creating design specs for at least the main parts of your work. This would minimize the back and forth between you and the engineers and would allow them to be more efficient.


You can create the design specs in many ways, the most important thing is to make sure they're distinguished from the actual design. To achieve that, I recommend using bright unique colors and monospaced font for annotating your specs.

Most of the time I spec out my designs manually in Figma using the line tool with some text for annotation, and in some cases, I use Redlines to speed up the process.

The following are the colors, font, and supporting tool I use in my workflow:

  • Colors: I use the colors #ff00ff for spec'ing light UI's, and #00ffff for dark UI's, as both of these colors, are pretty vibrant and neutral and rarely used in any of my designs. I have these values memorized in my head, but you can of course create a color style for each one of them.
  • Font: I use Roboto Mono in fairly small sizes 12px, 14px, 16px depending on hierarchy the spec'ed element.
  • Supporting Plugin: I sometimes use a plugin called Redlines to help speed up my process as it can automatically calculate the distance between different elements in the design and has a few other cool features that I like.

How do you spec out your designs?

Now to the most fun and interesting part of this article!

Below we'll be going through a few different examples of design specs to explain when and why you should do these kinds of specs.

1: Describing Flows

A clear description below each screen of your flows explaining the logic and interactions on that screen. In many cases, it can just be a one-line explanation of what's happening on that screen, while in a few other cases it can be lengthly.

It all depends on how complex that screen is, and whether it's a completely new logic or just an update to an existing screen.


2: Responsive Layout Breakpoints

This is usually created to show the breakpoints in a responsive layout based on the browser window's width. This can also be applied to vertical responsive layout breakpoints based on the height of a browser window.


3: Sticky Elements

Elements that would stay sticky in a fixed position on the screen when scrolling.

In the example below, you're looking at a page mid-scroll where the header of that page is sticky at the top.

The same thing can be used to spec out elements fixed in other positions on the screen, like a sticky banner at the bottom right corner of the page which is commonly used for an in-app chat.


4: Relative Sizes

Elements with relative sizes (width/height) need to be spec'd with a maximum and minimum width for that element.

In the example below, you can see the middle container spec'd to have a 100% width with a min-width of 240px, and a max-width of 640px, which means that this element will be fluid based on the screen size while maintaining a width between 240px-640px.

This is also can be used to spec out buttons and other fluid UI elements like a button for example.


5: Buttons & Form Elements

This might be a little bit of a controversial topic, but I strongly believe that you should never specify a fixed value for the height & width of the button unless you really need to.

Instead, you should always let the padding around the text determine the size of the button. That way, it's guaranteed that your button is always going to work fine no matter what font size you have, font-family, or even text language in that button.

While on the other hand if you have specified a fixed height for the button and later on decided to increase the font size, the button might break because the padding around the text will shrink.

To make sure the button is going to be responsive but at the same time fit in our UI we can define a min & max-width to it.

And as for the height of the button, instead of specifying a max-height to it, we can have the text truncate if it exceeds the width of the button, and we can of course decide on how many lines of text we want to allow before we truncate. And if you're curious here's a good article explaining how it's done in CSS.


6: Elements States

This is to make sure the elements in your design have all the proper states like hover, active, focus, ...etc. which is important for the accessibility and usability of your design.

I also recommend including the proper cursor for each state to make sure it gets applied to each state during the implementation.

When you're spec'ing out a radio button or a checkbox element make sure to include specs for the checked state of that element.

Lastly, to make the UI feel a bit smoother you can always add specs for a transition between the different states. I usually add easing transition with 0.15s duration 0.15s ease-in-out (CSS code snippet but the same thing can be applied in other programming languages like Swift/Java).


7: Truncating Multiple Line Text

Usually, you would spec out truncation rules for the text if it exceeds a specific height or a specific number of lines by showing ellipses-...

Alternatively, you might want to fade out the text. When you spec that out you have to make sure to annotate the parts of the design that might not be very obvious, which would also help the engineers understand how you think this will be implemented.

In the example below I'm highlighting the lower part of the text to show that this will have a gradient layer on top of it to create the fading effect.


8: Animation & Transitions

In many cases you'll need to spec out an animated component / UI element, a common example of that is a modal.

In the example below, you'll see the specs of a modal that shows up from the top of a screen, where it starts right outside the boundaries of the screen with 0% opacity.

And of course, you'll need to specify the ending position of the modal and how you want it to transition.

When spec'ing an animated component you need to spec out both the starting and ending position of that component and in some cases the in-between state.

In the example below I'm showing the ending position of the modal with the animation specs (easing and duration). I also added the modal's max-height to help make sure it always be fully visible on the screen.

As you can see in the example above I'm using ease-in-out for the animation timing function, which basically means that the element will start transitioning slow, then get faster, and finally slow down before it stops.

Alternatively, you can specify a more sophisticated animation curve by inspecting a web page in your browser where you have an element with a transition set on it. I usually create a quick prototype with a basic transition on Codepen.io and then I start adjusting the animation curve (animation timing function) value to my liking.

P.S. Alternatively, if you don't have any experience in CSS you can get the animation curve values in Principle App.


9: Adding Code Snippets

You can always support your specs with a few code snippets to help give your engineers an idea of how you think the feature will be implemented. This doesn't necessarily mean that the engineer will use your code snippet, but it'll show them that you've spent some time thinking about the implementation and you came prepared with a solution for that, and in many other cases the engineer will actually use your code snippets.

An example of a useful CSS code snippet I shared with my engineering team which they find super helpful is the box-shadow trick to add multiple borders to an element.

box-shadow: 0px 0px 0px 4px #333333, 0px 0px 0px 6px #ffff00,
  0px 0px 48px 6px rgba(255, 255, 0, 0.24);

Another example is position: sticky which makes an element sticky on scroll, and flex: 1 which allows an element to expand to fill the space in its flex container.


10: Scrollbars

In some cases, you will need to have a scrollbar within a container.

In the example below a container with a max-height of 240px, while the content inside of it exceeded that height limit, therefore we're showing a vertical scrollbar. This, of course, can also be applied to horizontal scrolling.

Styling the scrollbars is usually missed out during the implementation process, and for that reason, it's always worth calling it out in the specs.

I also usually include a direct link to a great CSS Tricks article with tips for customizing a scrollbar (hint: links can be clickable in Figma!).


[Bonus] 11: Spec'ing With Prototypes

In some cases, these specs might not be enough to show the engineers how exactly you want your design to be implemented and to behave when a user interacts with it.

Creating a prototype for your design can be super helpful in these situations, and at the same time, this prototype can also be used for user testing and to collect feedback from the users.

11 A: Spec'ing in Figma/Sketch

There are different tools for creating prototypes, and usually, the fastest way to do it is by using the prototyping tool in Figma/Sketch, which can be sufficient for basic interactions.

11 B: Spec'ing in Principle App

In case you were working on a more sophisticated interaction and you needed a more detailed prototype to show and test that you can use Principle App which allows you to create prototypes with a lot of details in a short amount of time.

11 C: Spec'ing in Code

In some other cases, you might want to choose to create a prototype in code, where you can even use real data, make changes on the fly, and most importantly, build something the engineers can use partially or fully.

Below is an example of a prototype I created for the reactions feature in the Airtime app. I created this prototype using Vuejs and CSS, and it was the best way to show how it's supposed to work and be implemented, while at the same time was super helpful to make quick tweaks to the timing and the animation.

Another great advantage for creating a prototype in code is that you can add controls to manipulate parts of the UI to better test it and tweak it on the fly.

In the example below I've created a prototype for the micro-interaction of the appearance of a chat bubble in the Airtime app. I've also added a settings panel to help us test different animation styles and to change the duration of that animation.


Ending Thoughts

This was the end of my first article in my personal design tech blog. I hope that you liked the article and found the information to be helpful and useful.

I'd love to hear your thoughts and feedback on the topic, let's connect and chat about it on Twitter @mahdif.

Share = 💞

If you liked the article please share it with others on Twitter & other social networks! I would really appreciate that.

Read the whole story
emrox
4 days ago
reply
Hamburg, Germany
Share this story
Delete
Next Page of Stories