<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bence Meszaros on Medium]]></title>
        <description><![CDATA[Stories by Bence Meszaros on Medium]]></description>
        <link>https://medium.com/@decketts?source=rss-c2de8845fa94------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*saij1DjGbxdpCf51SubV7Q.jpeg</url>
            <title>Stories by Bence Meszaros on Medium</title>
            <link>https://medium.com/@decketts?source=rss-c2de8845fa94------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 17:37:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@decketts/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to create custom elements without Web Components]]></title>
            <link>https://decketts.medium.com/how-to-create-custom-elements-without-web-components-cd48fae1f29f?source=rss-c2de8845fa94------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd48fae1f29f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[uiscript]]></category>
            <dc:creator><![CDATA[Bence Meszaros]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 17:27:10 GMT</pubDate>
            <atom:updated>2024-11-28T18:51:10.596Z</atom:updated>
            <content:encoded><![CDATA[<h4>UIScript DevBlog, Part 21</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VHw36PBzQiY-PtIN3KoVOA.png" /></figure><h4>Intro</h4><p>In the past couple of weeks I’ve been posting about a lot of things but let’s go back to hardcore UIScript.</p><p>My goal is to create a library to enable JS-first web app development, without using even a single line of HTML or CSS code.</p><p>One of the biggest issues I’m facing is to create a new inheritance tree for my new Views in UIScript, without clashing with existing stuff already in the browser.</p><h4>Prototypes</h4><p>JS solves the problem of inheritance by using a prototype chain. If you don’t know how prototypes work, take a look at <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">this article on MDN</a> before you continue.</p><p>Since every HTML element is an object (hence the DOM), they are represented in the prototype chain just like any other object.</p><p>This is roughly how they look:</p><pre>HTMLElement: abbr, address, article, aside, b, bdi, bdo, cite, code, dd, dfn, dt, em, figcaption, figure, footer, header hgroup, i, kbd, main, mark, nav, noscript, rp, rt, ruby, s, samp, search, section, small, strong, sub, summary, sup, u, var, wbr<br>- HTMLAnchorElement: a<br>- HTMLAreaElement: area<br>- HTMLBaseElement: base<br>- HTMLBodyElement: body<br>- HTMLBRElement: br<br>- HTMLButtonElement: button<br>- HTMLCanvasElement: canvas<br>- HTMLDataElement: data<br>- HTMLDataListElement: datalist<br>- HTMLDetailsElement: details<br>- HTMLDialogElement: dialog<br>- HTMLDivElement: div<br>- HTMLDListElement: dl<br>- HTMLEmbedElement: embed<br>- HTMLFieldSetElement: fieldset<br>- HTMLFormElement: form<br>- HTMLHeadElement: head<br>- HTMLHeadingElement: h1, h2, h3, h4, h5, h6<br>- HTMLHRElement: hr<br>- HTMLHtmlElement: html<br>- HTMLIFrameElement: iframe<br>- HTMLImageElement: img<br>- HTMLInputElement: input<br>- HTMLLabelElement: label<br>- HTMLLegendElement: legend<br>- HTMLLIElement: li<br>- HTMLLinkElement: link<br>- HTMLMapElement: map<br>- HTMLMediaElement<br>  - HTMLAudioElement: audio<br>  - HTMLVideoElement: video<br>- HTMLMenuElement: menu<br>- HTMLMetaElement: meta<br>- HTMLMeterElement: meter<br>- HTMLModElement: del, ins<br>- HTMLObjectElement: object<br>- HTMLOListElement: ol<br>- HTMLOptGroupElement: optgroup<br>- HTMLOptionElement: option<br>- HTMLOutputElement: output<br>- HTMLParagraphElement: p<br>- HTMLPictureElement: picture<br>- HTMLPreElement: pre<br>- HTMLProgressElement: progress<br>- HTMLQuoteElement: blockquote, q<br>- HTMLScriptElement: script<br>- HTMLSelectElement: select<br>- HTMLSlotElement: slot<br>- HTMLSourceElement: source<br>- HTMLSpanElement: span<br>- HTMLStyleElement: style<br>- HTMLTableCaptionElement: caption<br>- HTMLTableCellElement: td, th<br>- HTMLTableColElement: col, colgroup<br>- HTMLTableElement: table<br>- HTMLTableRowElement: tr<br>- HTMLTableSectionElement: tbody, tfoot, thead<br>- HTMLTemplateElement: template<br>- HTMLTextAreaElement: textarea<br>- HTMLTimeElement: time<br>- HTMLTitleElement: title<br>- HTMLTrackElement: track<br>- HTMLUListElement: ul<br>- HTMLUnknownElement: fencedframe, portal (deprecated tags, unknown/custom tags)<br>MathMLElement<br>  - MathMLMathElement: math<br>SVGElement<br>  - SVGGraphicsElement<br>    - SVGSVGElement: svg</pre><blockquote>There are a couple of things to note here.</blockquote><blockquote>First, there are officially 116 HTML elements (currently) but browsers define them using only around 66 constructors. This means, that several HTML elements share significant amount of characteristics: the base HTMLElement constructor directly defines 39, HTMLHeadingElement defines 6, HTMLTableSectionElement defines 3, and HTMLModElement, HTMLQuoteElement, HTMLTableCellElement, HTMLTableColElement and HTMLUnknownElement each define 2 elements.</blockquote><blockquote>Second, &lt;audio&gt; and &lt;video&gt; elements introduce an intermediate HTMLMediaElement that cannot be instantiated directly (i.e. there is no &lt;media&gt; element in HTML), but extremely helpful in deduplicating features and already shows the power of inheritance. In this case, using simply HTMLMedia would make much more sense.</blockquote><blockquote>And third, <a href="https://decketts.medium.com/how-to-fix-html-form-inputs-526193da6dde">as discussed in a previous article</a>, the input element shouldn’t be a single element. This could be implemented the same way as multimedia elements using a shared, intermediate parent but we won’t go into details here.</blockquote><h4>The power of prototypes</h4><p>The best thing about the prototype chain is that it is extensible: we can add any new children prototype to any existing prototype and inherit its functionality right away.</p><p>Unfortunately, even though the prototype chain of HTML elements looks promising — after all HTML doesn’t even have a type system, let alone inheritance — it has a lot of problems we need to address.</p><p>We need to also discuss why Web Components cannot solve these issues, even though this is one of the main reasons they were introduced in the first place.</p><p>Let’s dive in.</p><h4>The problems</h4><p>First off, HTML constructors cannot be used directly, unlike other regular constructors in JS.</p><p>This might make sense for intermediate constructors like HTMLElement, HTMLMediaElement, or even HTMLUnknownElement that don’t have a direct HTML counterpart, but sadly, this is true for all HTML constructors as well:</p><pre>HTMLElement(); //TypeError: Illegal constructor<br>new HTMLElement(); //TypeError: Illegal constructor<br><br>HTMLMediaElement(); //TypeError: Illegal constructor<br>new HTMLMediaElement(); //TypeError: Illegal constructor<br><br>HTMLDivElement(); //TypeError: Illegal constructor<br>new HTMLDivElement(); //TypeError: Illegal constructor</pre><p>Luckily, their prototypes work without issues:</p><pre>HTMLDivElement.prototype.foo = &quot;foo&quot;;<br>const div = document.createElement(&quot;div&quot;);<br>div.foo; //&quot;foo&quot;</pre><p>Modifying existing prototypes can be considered a way to implement custom elements, but this is a dirty and cheap approach that has obscure pitfalls all over the place.</p><h4>Web Components</h4><p>Instead, the recommended way is to define a new class that extends, rather than modifies, an existing prototype.</p><p>This would look something like this:</p><pre>class Stack extends HTMLDivElement {<br>  constructor() {<br>    super();<br>  }<br>}</pre><p>The first issue with this is that we cannot call a class without the new keyword:</p><pre>Stack(); //TypeError: Cannot call a class constructor without |new|</pre><p>Sure, no big deal, let’s call it with new:</p><pre>new Stack(); //TypeError: Illegal constructor</pre><p>Oops, it still doesn’t work, because we also need to register this class before using it:</p><pre>customElements.define(&quot;stack&quot;, Stack); //SyntaxError: Custom element name must contain a hyphen</pre><p>Ah, yes, we also need a fucking hyphen:</p><pre>customElements.define(&quot;ui-stack&quot;, Stack);<br>new Stack(); //TypeError: Illegal constructor</pre><p>Nope, it still doesn’t work, because custom built-in elements need a third argument, which is an object, even though it has only one key, extends, which is the name of the element we already said we are extending.</p><p>Never mind, let’s do it:</p><pre>customElements.define(&quot;ui-stack&quot;, Stack, {extends: &quot;div&quot;});<br>new Stack(); //TypeError: Illegal constructor</pre><p>Aaand it still doesn’t work, because I am in Safari, and it turns out Safari doesn’t support customized built-in elements, only autonomous custom elements.</p><p>OK, let’s try everything in Firefox, then:</p><pre>class Stack extends HTMLDivElement {<br>  constructor() {<br>    super();<br>  }<br>}<br><br>customElements.define(&quot;ui-stack&quot;, Stack, {extends: &quot;div&quot;});<br><br>new Stack(); //&lt;div&gt;&lt;/div&gt;</pre><p>Everything seems to work, except the tag name is div. The class name is Stack, it is registered as ui-stack, and yet, the tag name of the element is somehow still div.</p><p>Are you kidding me?</p><p>All right, so, how about if we try the classical instantiation? Would that work?</p><pre>class Stack extends HTMLDivElement {<br>  constructor() {<br>    super();<br>  }<br>}<br><br>customElements.define(&quot;ui-stack&quot;, Stack, {extends: &quot;div&quot;});<br><br>const stack = document.createElement(&quot;ui-stack&quot;); //&lt;ui-stack&gt;&lt;/ui-stack&gt;<br><br>stack instanceof Stack; //false<br><br>stack.constructor; //HTMLElement</pre><p>Well, the tag name is correct, but the element is not a Stack anymore, and its constructor became HTMLElement, not even HTMLDivElement.</p><p>Wonderful.</p><p>This is because document.createElement() is pretty quirky, too. Even though we manually registered our new element and made sure not to clash with any default HTML element, we still cannot use its tag name as the first argument.</p><p>Instead, we need to create the parent element and supply the new element as the second argument:</p><pre>document.createElement(&quot;div&quot;); //HTMLDivElement (all valid tags)<br>document.createElement(&quot;stack&quot;); //HTMLUnknownElement (all custom tags without a hyphen)<br>document.createElement(&quot;ui-stack&quot;); //HTMLElement (all custom tags with a hyphen, registered or not)<br>document.createElement(&quot;div&quot;, {is: &quot;ui-stack&quot;}); //HTMLDivElement (all custom tags, not registered, second argument is ignored)<br>document.createElement(&quot;div&quot;, {is: &quot;ui-stack&quot;}); //Stack but &lt;div&gt; (all custom tags, registered)</pre><p>In essence, since there is no inheritance in HTML whatsoever, customized built-in elements (custom elements that extend for example HTMLDivElement) cannot have custom tag names. Custom tag names are only available for autonomous custom elements (custom elements that extend HTMLElement).</p><p>If you cannot wrap your head around all this, don’t worry, nobody does.</p><p>So, considering all of this, here’s our final, fully compliant Web Components example (just remember, that it doesn’t work in Safari):</p><pre>//define the new class that has to extend the HTML element<br>class Stack extends HTMLDivElement {<br>  constructor() {<br>    super();<br>  }<br>}<br><br>//define the customized built-in element, make sure to add the third argument<br>customElements.define(&quot;ui-stack&quot;, Stack, {extends: &quot;div&quot;});<br><br>//instantiate the object, make sure to add the second argument<br>const stack = document.createElement(&quot;div&quot;, {is: &quot;ui-stack&quot;}); //&lt;div&gt;&lt;/div&gt;</pre><p>At this point I seriously think that the Web Components committee is just trolling everyone. There is no way in hell someone thought that this is how extending HTML should work.</p><h4>Prototype Injection</h4><p>I was pretty disappointed by how poorly custom elements performed but I really needed to find a solution for UIScript.</p><p>Luckily, after experimenting a ton with HTML prototypes, I stumbled upon a pretty clever solution that I think might work. I like to call this <em>prototype injection</em>.</p><p>In short, the basic idea is to insert one or several prototypes between existing ones.</p><p>Here is an example of how prototype injection works using the same class:</p><pre>function Stack() {<br>  const element = document.createElement(&quot;div&quot;); //step 2<br>  Object.setPrototypeOf(element, Stack.prototype); //step 3<br>  return element;<br>}<br><br>Object.setPrototypeOf(Stack.prototype, HTMLDivElement.prototype); //step 1</pre><p>How does it work?</p><p>First, we create a constructor that extends HTMLDivElement. Then, we create a regular div element. Finally, we switch its prototype to Stack.prototype.</p><p>With this approach almost all problems have been eliminated:</p><ul><li>we can call the constructor with or without new</li><li>we don’t need to register anything</li><li>we don’t need to use a hyphen, we can namespace however we like</li><li>we don’t touch anything default</li><li>we honor the prototype-based nature of JS</li></ul><p>The only drawback is that the tag name is still div, but since we are 100% in JS, this is the least of our concerns (and as we saw earlier, a custom tag name isn’t even possible anyway).</p><p>You can test this concept yourself:</p><pre>let stack = Stack(); //or new Stack() if you prefer<br>stack instanceof Stack; //true<br>stack instanceof HTMLDivElement; //true<br>stack instanceof HTMLElement; //true</pre><p>We are essentially achieved customized built-in elements without Web Components. The best part is that this approach works in any browser that adheres to the prototype chain of HTML elements, even in Safari.</p><h4>A new Tree of Life</h4><p>With this single mechanism, we can build a new inheritance tree from HTML elements, completely independent from, but fully compatible with the existing one.</p><p>We can create fully custom elements based on any HTML element, define arbitrary behavior and add them to shared prototypes to optimize performance.</p><p>We can essentially rebuild the DOM API in any way we like.</p><p>And this is exactly what I did with UIScript.</p><h4>The tree of UIScript</h4><p>The inheritance tree in UIScript starts with the View prototype, the root class, that stores the most common functionalities:</p><pre>function View() {} //abstract constructor (we just need its prototype, we don&#39;t want to instantiate)<br><br>View.prototype.opacity = function (value) { //add some shared behavior<br>    this.style.opacity = value;<br>};<br><br>Object.setPrototypeOf(View.prototype, HTMLElement.prototype);</pre><p>It then defines various Views that inherit from this root class, for example like this:</p><pre>function Image() {<br>  const image = document.createElement(&quot;img&quot;);<br>  Object.setPrototypeOf(image, Image.prototype);<br>  return image;<br>}<br><br>Object.setPrototypeOf(Image.prototype, View.prototype);</pre><p>Now, this Image class cannot fetch, much less display any images yet, because we severed its connection to HTMLImageElement.prototype.</p><p>But here comes the best part.</p><p>All we need to do is to mix in the original behavior from HTMLImageElement.prototype into the new Image.prototype and we are good to go. You can even rename any property or method, if you like.</p><p>This is the full example with some minor adjustments:</p><pre>function View() {<br>  throw new TypeError(&quot;Illegal constructor&quot;);<br>}<br><br>Object.defineProperties(View.prototype, {<br>  value: function (value) {<br>    this.style.opacity = value;<br>  }<br>});<br><br>Object.setPrototypeOf(View.prototype, HTMLElement.prototype);<br><br>function Image() {<br>  const image = document.createElement(&quot;img&quot;);<br>  Object.setPrototypeOf(image, Image.prototype);<br>  return image;<br>}<br><br>Object.defineProperties(Image.prototype, {<br>  url: Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, &quot;src&quot;)<br>});<br><br>Object.setPrototypeOf(Image.prototype, View.prototype);</pre><p>With this, we just created a brand new, fully functional and fully custom branch in the prototype chain:</p><pre>HTMLElement<br>- View<br>  - Image</pre><p>We just injected two prototypes between the img instance and HTMLElement.</p><p>You can go ahead and test this new class:</p><pre>const image = Image();<br>image.url = &quot;fun.jpg&quot;;<br>document.body.append(image); //loads and displays the image</pre><p>Here are some additional tests to demonstrate how this new Image instance behaves:</p><pre>image instanceof HTMLImageElement; //false<br>image instanceof Image; //true<br>image instanceof View; //true<br>image instanceof HTMLElement; //true<br><br>image.url; //&quot;http://example.com/fun.jpg&quot;;<br>image.src; //undefined<br>image.getAttribute(&quot;src&quot;); //&quot;fun.jpg&quot;<br><br>image.tagName; //&quot;IMG&quot; (the only thing we cannot change)</pre><p>This new Image instance has access to everything on HTMLElement.prototype and beyond, making it fully compatible with the DOM and any other HTML element.</p><p>And if you still prefer the old &lt;img&gt; element or load a regular HTML document that has this element, it will function just like it did before.</p><h4>But why do we need all this?</h4><p>UIScript is a proof of concept project.</p><p>It is a way to demonstrate solutions to many long standing and fundamental issues in HTML and CSS that their respective communities are refusing to fix.</p><p>Many bad concepts are entrenched in these languages because they keep pushing backwards compatibility above all else, essentially killing all innovation and forward thinking in the field.</p><p>With a clean slate we could go far beyond fixing current problems — we could open a new chapter in web development.</p><p>So, what do you think?</p><p>What would you like to be fixed in web dev if you had the opportunity?</p><p>⬅️ <a href="https://medium.com/p/cff119ae4b2d">Part 20 — So, you wanna be a pro?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd48fae1f29f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[So, you wanna be a pro, right?]]></title>
            <link>https://decketts.medium.com/so-you-wanna-be-a-pro-right-cff119ae4b2d?source=rss-c2de8845fa94------2</link>
            <guid isPermaLink="false">https://medium.com/p/cff119ae4b2d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[lifestyle]]></category>
            <category><![CDATA[uiscript]]></category>
            <category><![CDATA[mental-health]]></category>
            <dc:creator><![CDATA[Bence Meszaros]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 19:03:24 GMT</pubDate>
            <atom:updated>2024-11-20T09:36:53.196Z</atom:updated>
            <content:encoded><![CDATA[<h4>UIScript DevBlog, Part 20 (Special Edition)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2AS5FGr6NQ6TH2bUGrSvhw.jpeg" /><figcaption>Photo by Gentrit Sylejmani on Unsplash</figcaption></figure><h4>Intro</h4><p>Software development doesn’t happen in a vacuum, so once in a while I’d like to talk about non-technical aspects as well.</p><p>This time about mental health.</p><h4>The egocentric bias</h4><p>In the Summer Olympics back in 2000, there was a swimmer named Eric Moussambani who became famous as Eric the Eel after almost drowning during his heat.</p><p>His performance wasn’t a surprise though, given that he had never seen a 50-meter-long Olympic-size swimming pool prior to his race.</p><p>In fact, he took up swimming just months before the Olympics, he had only practiced in a lake and in a 12-meter-long pool in a hotel and even that pool was only available to him between 5 and 6 am.</p><p>Most people find his story inspiring because we want to believe that our success is the direct result of our own hard work and that we can overcome any obstacle if we are dedicated enough.</p><blockquote>“If you really want something, surely you can walk the extra mile. This is an opportunity to prove your dedication.”</blockquote><p>The only problem is, it isn’t true.</p><p>So much so that if you are highly ambitious and like to constantly push yourself to become better, but face terrible circumstances, this mentality might completely grind you down.</p><p>I had to find this out the hard way.</p><h4>Jack of all trades, master of none</h4><p>During the past ten years, I have been working on endless number of projects that went literally nowhere.</p><p>They always shared the same characteristics: they didn’t have enough funding, enough team members, enough time, a clear vision, a competent leadership or even a proper tech stack.</p><p>Everything was makeshift, critical hardware was second hand and more often than not we were even forced to use pirated software just to meet impossible business requirements.</p><blockquote>“But you are a genius, you can do this.”</blockquote><p>For several years it made me feel proud. I thought to myself I was doing the impossible, I was making my superiors and my clients proud, I could do the job of an entire team. Nobody else could achieve so much from so little, let alone a self-taught beginner.</p><p>I was the best value for money.</p><p>Then it slowly began to dawn on me that I was Eric the Eel, a wannabe professional without even the most basic tools required.</p><p>My lowest point (yet) was an all-nighter to recover one of our production servers that crashed right before my day ended. It was a 10+ year old Mac Mini on prem, running the latest macOS using OpenCore.</p><p>Great idea, right?</p><p>The OS crashed due to the patch, corrupting the backups as well, so the machine had to be rebuilt from scratch.</p><p>Before you judge this setup you should know that our only alternative was a 15+ year old unmanaged Windows server, running 5+ year old WordPress and we didn’t even get root access to update that shit, we could barely remove the random Chinese viagra ads from our international website as they were.</p><p>That, or a similarly aged NAS to host a dozen “production grade” web apps.</p><p>Oh, and by the way my actual responsibility was to develop one of those apps, not IT or any kind of operations.</p><h4>Opportunity cost</h4><p>At some point you have to realize that the thing you are trying to do is entirely pointless or even outright impossible.</p><p>You can cut some corners here and there, optimize costs, be resourceful, but having absolutely zero tools, zero support and zero budget to do production grade work is a delusion.</p><p>There is this false notion that everyone starts with bad projects and once you prove yourself and gain enough experience, then you’ll be entitled to move on to better projects.</p><blockquote>“You gotta earn it man. You gotta prove yourself first, before anyone can trust you.”</blockquote><p>This is an outright lie designed to manipulate you.</p><p>The thing is, a shitty project is just that, a shitty project. It is shit, because nothing works as it should, so you can’t do your job either.</p><p>You’ll gain no experience, because instead of doing your actual job, you are constantly sidetracked, forced to put out fires, step in to do things far outside of your role (and usually way above your pay grade), all because nobody else is doing their job and you cannot rely on anyone or anything.</p><p>Most of the shitty things I had to do gave me knowledge that is absolutely useless, because the problems I had to solve shouldn’t even exist in a professional environment.</p><p>To put it simply, I was wasting my time building a pool instead of exercising inside one.</p><h4>🚩🚩🚩</h4><p>Now, if you’re like me you’ll have a hard time learning that most people in corporate have a vested interest not to achieve anything tangible at all.</p><p>You can blame it on the iron law of bureaucracy, capitalism or even on pure human greed, but the result is the same: professionals will suffer.</p><p>Instead of focusing on growing as a professional, the game is now to out-manipulate everyone else, whether you like it or not, and boy are they good at manipulation.</p><p>They will tell you anything and everything to keep you from leaving, even though it is clear as day that neither the project, nor the company is going anywhere.</p><p>And with that, you can say goodbye to your professional ambitions as well.</p><blockquote>“But if I don’t do it, nobody will and the project will definitely fail.”</blockquote><p>Yeah, that is exactly the point.</p><p>Why should you care if literally nobody does, including your superiors and even the client? What kind of teamwork is it, where you are the only one moving the ball forward and everyone else is actively working against you?</p><p>What are you even trying to prove?</p><p>I think one of the biggest difficulties ambitious professionals are facing is the lack of a functional environment.</p><p>It is your job, however painful it might be, to recognize when the circumstances are completely stacked against you, take the hint and move on.</p><p>For some people, it is fairly easy, but it is pretty difficult if you are diligent and you don’t want to let anyone down.</p><p>And this is precisely why you need to do it.</p><h4>Outro</h4><p>I cannot help but wonder what would have happened had Moussambani been born in a developed country or at least had access to a proper training facility and a professional coach.</p><p>Sure, he became famous for a brief moment, but for all the wrong reasons.</p><p>There are only so many battles you can possibly fight in your lifetime so you have to be careful to pick which hill to die on.</p><p>I, for one, want to do meaningful work instead of battling the elements just to get to the start line.</p><p>What do you choose?</p><p>⬅️ <a href="https://medium.com/@decketts/get-type-safety-with-js-descriptors-843f294da61a">Part 19 — 🛟 Get type safety with JS descriptors</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cff119ae4b2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Get type safety with JS descriptors]]></title>
            <link>https://decketts.medium.com/get-type-safety-with-js-descriptors-843f294da61a?source=rss-c2de8845fa94------2</link>
            <guid isPermaLink="false">https://medium.com/p/843f294da61a</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Bence Meszaros]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 18:22:53 GMT</pubDate>
            <atom:updated>2024-11-11T18:23:26.623Z</atom:updated>
            <content:encoded><![CDATA[<h4>UIScript DevBlog, Part 19</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVdNQfPd_4AG-PPAtqDfMQ.png" /><figcaption>Excellent choice, sir! Right away, sir!</figcaption></figure><p>Last week was pretty rough.</p><p>By the end of the week, I needed a break, so a couple of friends and I hit up a local bar for some craft beers.</p><p>They had around 30 different beers on tap, all listed beautifully: name, type, ABV, everything, even the city of origin.</p><p>One of my friends got the menu first and after a few seconds he started laughing. When I got mine I understood why: almost half of the beers came from a city called “undefined”.</p><p>I guess you never really escape JavaScript, do you?</p><h4>The “beauty” of dynamic languages</h4><p>We’ve all been there: you build a beautiful user interface, pay extra attention to every single detail and consider every single edge case — only to find undefined, NaN, [object Object] and similar artifacts popping up all over the place.</p><p>Pretty annoying, right?</p><p>Well, this is the price we pay for having a dynamic language: it keeps reconciling everything under the hood, instead of throwing a single error.</p><p>For small projects it’s not a big deal. But if your project grows you want certain checkpoints to guarantee that data beyond those points is always correct.</p><p>So, how do we do that?</p><h4>Runtime persistence</h4><p>The obvious idea would be to just use TypeScript, but it doesn’t really help in validating data loaded from the server, which is my biggest concern.</p><p>Another idea would be a validation library, but those checks aren’t persistent either, some code might alter the data after validation and I am back to square one.</p><p>I wanted something persistent, right inside vanilla JS.</p><h4>Property descriptors</h4><p>The best thing I could come up with is to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#description">accessor descriptors</a>. This is a neat little feature in JS to process a property value right before getting or setting it.</p><p>A basic example is this:</p><pre>let person = {<br>  get name() {},<br>  set name(value) {},<br>};</pre><p>So, to achieve type safety all we have to do is put our type (and even value) checks right inside the setter method, and we are good to go:</p><pre>let person = {<br>  get name() {},<br>  set name(value) {<br>    if (typeof value !== &quot;string&quot;) throw new TypeError(`Property &#39;name&#39; expects string, received ${typeof value}`);<br>    if (value === &quot;&quot;) throw new TypeError(`Property &#39;name&#39; cannot be empty`);<br>  },<br>};</pre><p>Of course, if we use a getter/setter pair for a property then we also need to store the actual value somewhere, so the final example is this:</p><pre>let name;<br>let person = {<br>  get name() {<br>    return name;<br>  },<br>  set name(value) {<br>    if (typeof value !== &quot;string&quot;) throw new TypeError(`Property &#39;name&#39; expects string, received ${typeof value}`);<br>    if (value === &quot;&quot;) throw new TypeError(`Property &#39;name&#39; cannot be empty`);<br>    name = value;<br>  },<br>};</pre><p>It isn’t pretty, but from this point on, this property is type safe:</p><pre>Person.name = 42; //TypeError: Property &#39;name&#39; expects string, received number<br>Person.name = &quot;&quot;; //TypeError: Property &#39;name&#39; cannot be empty</pre><h4>Going one step further</h4><p>A property descriptor can do even more, but those options are only available if we create the property like this:</p><pre>let person = Object.defineProperties({}, {<br>  name: {<br>    get() {},<br>    set(value) {},<br>    enumerable: true, //defaults to false<br>    configurable: false //defaults to false<br>  }<br>});</pre><blockquote>Note: Pay attention to the slight difference between get name()/set name() in object literals and get()/set() in property descriptors.</blockquote><p>If the property is not enumerable, it won’t show up in loops, Object.keys(), Object.entries(), or when encoded into JSON. However, it doesn’t affect direct access, so in that regard business as usual.</p><p>If the property is not configurable we cannot change its descriptor anymore, so we can’t change get(), set(), enumerable and configurable and we can’t even delete the property. It doesn’t affect direct access either.</p><p>One additional cool feature is that if we skip the set() method (or always throw inside), the property essentially becomes read only.</p><pre>let name = &quot;Tom&quot;;<br><br>let person = Object.defineProperties({}, {<br>  name: {<br>    get() {<br>      return name;<br>    },<br>    set(value) {<br>      throw new TypeError(`Trying to set a read only property`);<br>    },<br>    enumerable: true, //defaults to false<br>    configurable: false //defaults to false<br>  }<br>});<br><br>person.name = &quot;Bob&quot;; //TypeError: Trying to set a read only property</pre><h4>A quick recap</h4><p>This is a list of what we’ve achieved so far:</p><ol><li>we have an object property that throws on invalid types and values</li><li>these checks are persistent throughout the application</li><li>the property cannot be deleted</li><li>the property can be set to be read only</li><li>we can hide the property from enumerations, if needed</li><li>aside from these, the property looks and works like any other property</li></ol><p>Bonus point is that, so far, we don’t even have any dependencies.</p><h4>Further examples</h4><p>Using get()/set() is a powerful, yet very simple tool to achieve a wide range of automatic validations:</p><ul><li>we can check min and max values for numbers and dates</li><li>we can check min and max lengths for strings and arrays</li><li>we can validate a format using regex</li><li>we can disallow specific values like the empty string or NaN</li><li>we can disallow strings with specific characters</li><li>and so on…</li></ul><p>For example, creating a property for a color object might look something like this:</p><pre>let red;<br>let color = Object.defineProperty({}, &quot;red&quot;, {<br>  get() {<br>    return red;<br>  },<br>  set(value) {<br>    if (typeof value !== &quot;number&quot;) throw new TypeError(`Property &#39;red&#39; expects number, received ${typeof value}`);<br>    if (Number.isNaN(value)) throw new TypeError(`Value for &#39;red&#39; cannot be NaN`);<br>    if (value &gt; 255) throw new TypeError(`Value for &#39;red&#39; is bigger than max`);<br>    if (value &lt; 0) throw new TypeError(`Value for &#39;red&#39; is smaller than min`);<br>    red = value;<br>  },<br>  enumerable: true,<br>  configurable: false<br>});</pre><h4>Outro</h4><p>Using JS getters/setters is basically our only option and the only construct where we can achieve persistent and automatic type checks during runtime.</p><p>We achieve this by relying on get()/set() to handle our data validation automatically and behind the scenes.</p><p>It’s a pity, that <a href="https://github.com/airbnb/javascript?tab=readme-ov-file#accessors--no-getters-setters">Airbnb doesn’t recommend using JS getters/setters</a>, but I can understand it from a practical point of view: without a proper abstraction, this approach can become messy in the long term.</p><p>Fortunately, this abstraction is exactly what I am planning to show you next week.</p><p>So stay tuned, follow my account and keep coding.</p><p>⬅️ <a href="https://medium.com/@decketts/but-whatabout-semantics-e85c8684c91a">Part 18 — bUt WhAtAbOuT sEmAnTiCs?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=843f294da61a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[bUt WhAtAbOuT sEmAnTiCs?]]></title>
            <link>https://decketts.medium.com/but-whatabout-semantics-e85c8684c91a?source=rss-c2de8845fa94------2</link>
            <guid isPermaLink="false">https://medium.com/p/e85c8684c91a</guid>
            <category><![CDATA[uiscript]]></category>
            <category><![CDATA[semantics]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Bence Meszaros]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 18:29:21 GMT</pubDate>
            <atom:updated>2024-11-05T18:40:59.031Z</atom:updated>
            <content:encoded><![CDATA[<h4>UIScript DevBlog, Part 18</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZzgRooYvkHTN-YcHyL3ug.png" /><figcaption>The entirety of the HTML language</figcaption></figure><p>I always find it hilarious when HTML cultists are trying to explain what semantics are.</p><p>I mean, <a href="https://stackoverflow.com/questions/49739784/what-are-semantics">look at this poor guy</a>, getting downvoted into oblivion just because he asked the exact same question. Not a single proper answer, just a petition to close this thread because apparently HTML semantics is not about programming.</p><p>If so, then please, enlighten us genius, what is it about?</p><p>Is it about layout structure?</p><p>Of course not. HTML semantics should never describe the layout. You should use CSS for that.</p><p>OK, is it about styling? I mean, we do have tags like &lt;b&gt; (bold), &lt;i&gt; (italic), &lt;u&gt; (underline) and &lt;s&gt; (strikethrough).</p><p>No. These tags are the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b">Bring Attention To</a>, the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i">Idiomatic Text</a> and the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/u">Unarticulated Annotation</a>. Semantics should never be used to describe styling either. Except maybe the &lt;s&gt; tag. We still call that the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/s">Strikethrough element</a>.</p><p>How about interactivity, then? We do have multiple button implementations and even the &lt;a&gt; tag acts like one. How else would a website be interactive without JS?</p><p>No, sorry, semantics is not about interactivity either. Things like linking external resources, loading files, submitting forms and making HTTP requests don’t count.</p><p>So, accessibility then?</p><p>No, we have <a href="https://www.w3.org/TR/wai-aria-1.2/">ARIA</a> for that. It defines its own semantics, API, even its own accessibility tree.</p><p>How about SEO? Is it about boosting your rankings?</p><p>No, it’s not. <a href="https://developers.google.com/search/docs/fundamentals/seo-starter-guide#focusing">At least according to Google</a>.</p><p>Then what? What is HTML semantics about?</p><p>Well, semantics is the meaning of the information. We use it to categorize and make sense of our data.</p><p>Like the type of the data, right?</p><p>Well, yeah, duh.</p><p>Well, I hate to break it to you, but you just reinvented data types. You know, the literal cornerstone of any programming language, ever.</p><p>Ouch.</p><h4>OK, but seriously though, what does semantics mean?</h4><p>As I see it, it just means “organize your code”.</p><p>The problem is, it is hard to do in HTML, because it is a badly organized language that discourages good practices and encourages bad ones.</p><p>You can bitch and moan about the fact that nobody cares about semantic HTML, but it is pretty disingenuous considering that the language itself is clearly missing the mark in the semantics department, to put it mildly.</p><p>Let’s see some examples.</p><h4>Inside, outside or in-between</h4><p>Our first stop is the various implementations of a thing called titles.</p><p>First, tables use the &lt;caption&gt; element, but it doesn’t work for &lt;img&gt; elements, because they are void. So we need to wrap images in a &lt;figure&gt; element, then use the &lt;figcaption&gt; (and not simply the &lt;caption&gt;) inside of it.</p><p>But then, we have the &lt;fieldset&gt; that isn’t void, but it uses neither &lt;caption&gt; nor &lt;figcaption&gt; and instead introduces &lt;legend&gt;, a third element, to achieve the exact same thing.</p><p>So, what about an article, then? Its title is literally called the TITLE. How does HTML handle that?</p><p>Well, there is a &lt;title&gt; element, but that works for the entire document. The title of an article is called heading. No, not &lt;head&gt; or &lt;header&gt;, but heading, you know &lt;h1&gt; through &lt;h6&gt;.</p><p>But wait, there is also the title attribute that is global, thus valid for every single HTML element.</p><p>Now what?</p><pre>&lt;html title=&quot;I am not the title of the document&quot;&gt;<br>  &lt;head title=&quot;I am not the title either&quot;&gt;<br>    &lt;title title=&quot;Me neither&quot;&gt;I am the title&lt;/title&gt;<br>  &lt;/head&gt;<br>&lt;/html&gt;</pre><p>Are you beginning to see the problem here?</p><p>Not only is HTML using various names for the exact same thing, but it also uses three naive and fundamentally different approaches.</p><p>Let’s say we want to set a title for a video. How would you do that?</p><p>Like this?</p><pre>&lt;video&gt;<br>  &lt;title&gt;My favorite video&lt;/title&gt;<br>&lt;/video&gt;</pre><p>This?</p><pre>&lt;wrapper&gt;<br>  &lt;title&gt;My favorite video&lt;/title&gt;<br>  &lt;video&gt;&lt;/video&gt;<br>&lt;/wrapper&gt;</pre><p>Or this?</p><pre>&lt;video title=&quot;My favorite video&quot;&gt;</pre><p>Aside from the fact that you can choose from a multitude of names, you have three wildly different options: set the title inside the element, set the title outside of the element or set the title in between the two using an attribute.</p><p>Since there are no rules to settle this in HTML, all three are actively being used by the language:</p><ul><li>the &lt;img&gt; element cannot have elements inside of it, so it has to set its title outside using a wrapper</li><li>on the other hand the document cannot have elements outside of it, so it does the opposite</li><li>and many elements are using the title attribute (eg. &lt;p&gt;, &lt;input&gt;, &lt;abbr&gt;, &lt;th&gt;) albeit for tooltips, that isn’t a semantic use of this attribute at all, but who cares about semantics right?</li></ul><p>And since we don’t have a general rule, we don’t know which option to choose for which elements.</p><p>How does a title work for an svg for example? Or for a math formula?</p><p>What about &lt;embed&gt; or &lt;object&gt;?</p><p>Which approach is considered “semantic” for which elements and why?</p><h4>Visible vs non-visible</h4><p>Another intrinsic semantic issue is that HTML fails to understand the difference between data and metadata or visible and non-visible data.</p><p>The question here is simple: which elements are visible and which are not?</p><p>Elements like &lt;head&gt;, &lt;meta&gt;, &lt;link&gt; and &lt;script&gt; are all about metadata so they shouldn’t be visible. But it turns out that all of these and basically all elements can be made visible through CSS, even though this shouldn’t be possible.</p><p>That’s right, we can make any of these elements visible by simply changing their display properties:</p><pre>&lt;head style=&quot;display: block&quot;&gt;<br>  &lt;meta style=&quot;display: block&quot;&gt;<br>  &lt;link style=&quot;display: block&quot;&gt;<br>  &lt;script style=&quot;display: block&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;</pre><p>You can say that this is an anti-pattern, this is invalid code, this is against the rules, but this code is actually perfectly valid HTML.</p><p>What we can’t do is to make for example the style attribute visible on its own, or a transition inside of it, which by the way are also objects, just like the element itself:</p><pre>&lt;div style=&quot;transition: top 4s ease-in-out&quot;&gt;</pre><pre>//same element, but represented using actual objects<br>let div = {<br>  style: {<br>    transition: {<br>      property: &quot;top&quot;,<br>      duration: 4,<br>      easing: &quot;ease-in-out&quot;<br>    }<br>  }<br>}</pre><p>The HTML syntax suggests, that elements are always visible, but data stored in their attributes aren’t, because they always act as metadata.</p><p>But then, you also have &lt;input type=&quot;hidden&quot;&gt; that is truly invisible, regardless of CSS. Well, until you change the type attribute, that is.</p><p>But wait, there is also the hidden global attribute that works on any element. So, is it</p><ul><li>&lt;input hidden&gt;, or</li><li>&lt;input hidden=&quot;hidden&quot;&gt;, or</li><li>&lt;input type=&quot;hidden&quot;&gt;, or</li><li>&lt;input hidden type=&quot;hidden&quot;&gt;, or</li><li>&lt;input hidden=&quot;hidden&quot; type=&quot;hidden&quot;&gt;?</li></ul><p>Or should we throw in some CSS too, just to be on the safe side?</p><pre>&lt;input hidden=&quot;hidden&quot; type=&quot;hidden&quot; style=&quot;display: hidden&quot;&gt;</pre><p>Again, I want to remind you that these are not theoretical examples, everything here is completely valid HTML.</p><p>At this point HTML cultists usually argue that having options is actually a good thing and yes, I do tend to agree.</p><p>But what we see here, however, has nothing to do with having options but rather, it is the identity crisis of HTML, the opposite of semantics.</p><p>HTML fails to recognize that its syntax has created two distinct classes of objects: actual elements and objects stored in their attributes. If we want actual, visible data, we should rely on elements and if we want meta, non-visible data, we should rely on attributes.</p><p>Take a look at this theoretical example:</p><pre>&lt;html head=&quot;meta: ...; link: ...; script: ...&quot;&gt;</pre><p>Anything that is stored inside an attribute will never clash with actual data, it is always hidden and we cannot change this or manipulate it in any way whatsoever using CSS. Plus, we don’t even need the hidden attribute, the separation is crystal clear and unambiguous.</p><p>It is hard to beat the semantics of this example, but sadly, this isn’t valid HTML.</p><h4>Loading</h4><p>Then, there is the problem of loading an external resource into an HTML document.</p><p>Again, a fairly simple thing to do and yet, we have a plethora of naive implementations that have basically nothing in common.</p><p>For example, there are only two supplementary languages to HTML — CSS and JavaScript — but the way HTML handles them couldn’t be more different:</p><ul><li>&lt;script&gt; can work with both internal and external scripts, while &lt;style&gt; can only work with internal styles</li><li>we need the &lt;link&gt; tag to load external styles, even though we barely use &lt;link&gt; with anything else other than .css files</li><li>&lt;script&gt; uses the src attribute, &lt;link&gt; uses href but it also needs the rel attribute</li><li>&lt;link&gt; is a void element, but &lt;script&gt; can never lose its closing tag</li></ul><pre>&lt;script&gt;let foo = &quot;foo&quot;;&lt;/script&gt;<br>&lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;<br><br>&lt;style&gt;#foo {color: black;}&lt;/style&gt;<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;</pre><p>Going beyond these two, the landscape becomes even more chaotic.</p><p>We cannot load one html document into another by simply using href, src, rel or any other attribute directly on an &lt;html&gt; element, we need an additional &lt;iframe&gt; element for that.</p><p>&lt;svg&gt; suffers the same way, we either include an &lt;image&gt; element inside of it and use that to load an external file or use the &lt;object&gt; element. Neither allows further content manipulation.</p><p>Loading .json is even worse, since there isn’t any HTML element that supports it natively, so we need to rely entirely on JS to load it.</p><p>And the list goes on.</p><p>So, what if, instead of this mess, HTML would look something like this:</p><pre>&lt;image  url=&quot;image.jpg&quot;&gt;<br>&lt;svg    url=&quot;svg.svg&quot;&gt;<br>&lt;audio  url=&quot;audio.mp3&quot;&gt;<br>&lt;video  url=&quot;video.mp4&quot;&gt;<br>&lt;track  url=&quot;track.vtt&quot;&gt;<br>&lt;style  url=&quot;style.css&quot;&gt;<br>&lt;script url=&quot;script.js&quot;&gt;<br>&lt;html   url=&quot;html.html&quot;&gt;<br>&lt;xml    url=&quot;xml.xml&quot;&gt;<br>&lt;math   url=&quot;math.mml&quot;&gt;<br>&lt;object url=&quot;object.pdf&quot;&gt;<br>&lt;text   url=&quot;text.txt&quot;&gt;</pre><p>Would you still think that the current state of HTML is more semantic than this?</p><h4>Further examples</h4><p>HTML is so badly structured that we find semantic issues everywhere:</p><ul><li>whitespace elements: code formatting and data isn’t separated, so we need things like &lt;br&gt;, &lt;wbr&gt; and &lt;pre&gt; to make working with whitespace barely possible</li><li>form elements: they shouldn’t even be considered form elements because they happily work outside of them too, forms are just one specific use case</li><li>input elements: &lt;textarea&gt; and &lt;select&gt; should be input too, but &lt;button&gt; shouldn’t be, also, &lt;input&gt; should be several separate elements</li><li>table elements: chaotic names for tags and for attributes as well, eg. &lt;td&gt; instead of &lt;tc&gt;, &lt;tr&gt; for table row, but &lt;col&gt; for table column, &lt;colgroup&gt; with span vs &lt;td&gt; with colspan, and so on</li><li>attributes: fully inconsistent as well, like type in itself, type vs kind, src vs href vs rel vs data and so on</li></ul><p>Now, I understand that it is paramount to debate whether &lt;s&gt; or &lt;del&gt; is the appropriate label for a piece of text, or to advocate for the use of elements like &lt;header&gt;, &lt;section&gt;, &lt;main&gt;, &lt;aside&gt; and &lt;footer&gt; in a text heavy environment instead of using generic or even incorrect containers, but the thing is, there are an overwhelming number of websites that just aren’t text heavy.</p><p>Instead, they are focusing on graphic design, multimedia and interactivity where text is just one of many media types we need to work with.</p><p>Unfortunately, more than half of all HTML elements (61 out of 116) are designed specifically for text and textual documents while the remaining narrow half includes everything else from metadata, multimedia (including raster and vector graphics, audio and video), interactivity, embedding, scripting and styling, to web components, forms, tables and even math.</p><p>You don’t have to be a genius to see where this leads.</p><h4>Outro</h4><p>That’s all I have for you today.</p><p>Thank you for making it to the end and I hope that you’ve found it interesting.</p><p>If you like my project, please consider clapping, commenting and sharing my work with others.</p><p>Thank you again, take care and stay tuned.</p><p>⬅️ <a href="https://decketts.medium.com/how-to-fix-html-form-inputs-526193da6dde">Part 17 — How to fix HTML form inputs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e85c8684c91a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to fix HTML form inputs]]></title>
            <link>https://decketts.medium.com/how-to-fix-html-form-inputs-526193da6dde?source=rss-c2de8845fa94------2</link>
            <guid isPermaLink="false">https://medium.com/p/526193da6dde</guid>
            <category><![CDATA[uiscript]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[forms]]></category>
            <dc:creator><![CDATA[Bence Meszaros]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 16:27:41 GMT</pubDate>
            <atom:updated>2024-10-29T16:27:41.896Z</atom:updated>
            <content:encoded><![CDATA[<h4>UIScript DevBlog, Part 17</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqlbHsX14WFybsy6nToO6Q.png" /><figcaption>tl;dr (well, kinda)</figcaption></figure><h4>Intro</h4><p>HTML is a mess.</p><p>I’ve said this numerous times already, but this language is truly a gift that just keeps on giving.</p><p>In HTML, <a href="https://medium.com/@decketts/understanding-digital-line-breaks-5ddfaa66677b">working with text is a mess</a>, <a href="https://medium.com/@decketts/there-is-no-box-model-in-css-and-this-is-why-html-tables-are-a-disgrace-9407dfbce823">building tables is a mess</a>, and yes, building a fucking form is a complete mess.</p><p>I cannot wrap my head around the fact that this “tech” has been around for 30+ years already and we still haven’t been able to figure out why we need an &lt;input type=&quot;button&quot;&gt; when we already have the &lt;button&gt; element, or why &lt;textarea&gt; and &lt;select&gt; aren’t input types when they clearly input values, or why button is an input type when it clearly doesn’t input anything but instead performs an action.</p><p>What exactly is semantic about having a hidden input field, or better yet, an &lt;input type=&quot;image&quot;&gt; that is a button, that is an image?</p><p>Yeah, I know, I am probably too dumb to understand that the best way to separate semantics, presentation and functionality is to mix them together as much as possible.</p><p>Skill issue, I know. I promise I will double my daily self-flagellation with the HTML specs.</p><p>But here is the thing. Forms are actually pretty easy. The hard part is the language that’s actively working against you.</p><p>Let me explain what I mean by that.</p><h4>Types</h4><p>The concept of data types is the cornerstone of programming. It doesn’t matter if the language is strongly or weakly typed, or if it uses static or dynamic types, as long as it has a formal definition of this concept.</p><p>The problem is, the HTML specs define a lot of shit from content models to tags and semantics, just not proper types.</p><p>Think about it. Why do you need a form?</p><p>To ask the user for a boolean, a number, a string, an array or an object.</p><p>That’s it.</p><p>You can twist and turn this however you want, use shiny abstractions, create a metric ton of obscure concepts and specifications, but at the end of the day, underneath of it all, you are just working with simple data types.</p><p>Once you understand this, all the random pieces suddenly fall into place.</p><p>Let’s see how.</p><h4>Boolean</h4><p>The simplest value we can get from the user is a boolean. It can be true or false, enabled or disabled, yes or no, on or off or whatever value pair you can come up with.</p><p>In HTML, we can use a checkbox for this:</p><pre>&lt;input type=&quot;checkbox&quot;&gt;</pre><h4>Number</h4><p>Numbers are a little bit trickier, because we usually represent them as strings: 0b1000 (binary), 42.5 (decimal), 1e3 (decimal exponential), 0o644 (octal), 0xFFFF (hexadecimal) and so on. But make no mistake, these are handled and stored as numbers under the hood (or at least they should be).</p><blockquote>Note: A good way to distinguish a number from a string is to check whether it works in an arithmetic operation. For example, a hexadecimal number might be incremented but we’ll never do arithmetic operations on a phone number or a street address.</blockquote><p>Another way to represent numbers is with a slider.</p><p>HTML actually supports them both:</p><pre>&lt;input type=&quot;number&quot;&gt;<br>&lt;input type=&quot;range&quot;&gt;</pre><h4>String</h4><p>Arguably the most chaotic in HTML is to get a string.</p><p>I can understand that HTML struggles with other data types, but I always find it hilarious when it fails spectacularly to work with text, even though literally everything is text/string in HTML.</p><p>In HTML, the following elements all expect a string input:</p><pre>&lt;input type=&quot;text&quot;&gt;<br>&lt;input type=&quot;email&quot;&gt;<br>&lt;input type=&quot;password&quot;&gt;<br>&lt;input type=&quot;search&quot;&gt;<br>&lt;input type=&quot;tel&quot;&gt;<br>&lt;input type=&quot;url&quot;&gt;<br>&lt;textarea&gt;</pre><p>It is a complete mystery to me why &lt;textarea&gt; isn’t an input element and even more so why all the other types aren’t simply the modifications of a single text input element. They differ only in presentation and/or data validation — features that have nothing to do with semantics at all.</p><h4>Object</h4><p>Then, there are situations where we need multiple pieces of data together. In these cases, we are talking about an object.</p><p>There are virtually endless objects we can ask from the user but the most common ones are date/time, color and file. Unfortunately, these are also pretty chaotic.</p><pre>&lt;input type=&quot;color&quot;&gt;<br>&lt;input type=&quot;date&quot;&gt;<br>&lt;input type=&quot;datetime-local&quot;&gt;<br>&lt;input type=&quot;time&quot;&gt;<br>&lt;input type=&quot;month&quot;&gt;<br>&lt;input type=&quot;week&quot;&gt;<br>&lt;input type=&quot;file&quot;&gt;</pre><ul><li>First, the simple datetime type is obsolete, because it used UTC that didn’t really make much sense. But it is unclear whether time is UTC or not, I would assume that time would be UTC and time-local would be local following the same logic, but I don’t think this is the case.</li><li>Second, month is actually month and year, and week is also week and year, they just have incorrect names. Pretty annoying, but this is the best all of humanity can offer. Also, there is no day type because why would there be, right?</li><li>And third, these fields are designed to gracefully degrade into a single text input in unsupported browsers. This is a nice concept in theory, but completely useless in reality. The problem is, these are objects and serializing them into a string is ambiguous. How can I consume a date string for example, when I don’t even know what format it is using?</li></ul><p>Also, week doesn’t even degrade into a text field on iOS (tested on iOS 18), it is just fully broken.</p><blockquote>Note: If you are an eager beaver, you might have noticed that urls, email addresses and even phone numbers are objects, too. This is why it is difficult to validate them as strings, but at least they have much less formatting options than for example a date or a color. And they don’t have a non-degraded mode, so I classify them as text inputs.</blockquote><h4>Enum</h4><p>This data type is less common but very simple: it defines a list of possible values to choose from. It is extremely useful in UI/UX situations, because instead of asking the user for, then trying to validate a raw value, we present a list of valid options to choose from right away.</p><p>HTML provides two implementations for this that are functionally equivalent:</p><pre>&lt;select&gt;<br>&lt;input type=&quot;radio&quot;&gt;</pre><p>Wait, what? These are the same?</p><p>That’s right, take a look at this:</p><pre>&lt;!-- this is the select tree --&gt;<br>&lt;select size=&quot;3&quot;&gt;<br>  &lt;option value=&quot;huey&quot; selected&gt;Huey&lt;/option&gt;<br>  &lt;option value=&quot;dewey&quot;&gt;Dewey&lt;/option&gt;<br>  &lt;option value=&quot;louie&quot;&gt;Louie&lt;/option&gt;<br>&lt;/select&gt;<br><br>&lt;!-- and this is the radio tree --&gt;<br>&lt;fieldset&gt;<br>  &lt;div&gt;<br>    &lt;input type=&quot;radio&quot; id=&quot;huey&quot; name=&quot;drone&quot; value=&quot;huey&quot; checked /&gt;<br>    &lt;label for=&quot;huey&quot;&gt;Huey&lt;/label&gt;<br>  &lt;/div&gt;<br><br>  &lt;div&gt;<br>    &lt;input type=&quot;radio&quot; id=&quot;dewey&quot; name=&quot;drone&quot; value=&quot;dewey&quot; /&gt;<br>    &lt;label for=&quot;dewey&quot;&gt;Dewey&lt;/label&gt;<br>  &lt;/div&gt;<br><br>  &lt;div&gt;<br>    &lt;input type=&quot;radio&quot; id=&quot;louie&quot; name=&quot;drone&quot; value=&quot;louie&quot; /&gt;<br>    &lt;label for=&quot;louie&quot;&gt;Louie&lt;/label&gt;<br>  &lt;/div&gt;<br>&lt;/fieldset&gt;</pre><p>These two are essentially the same.</p><p>The main difference is that &lt;select&gt; represents the enum itself, while &lt;input type=&quot;radio&quot;&gt; represents one potential value within an enum. One radio button doesn’t even work or input anything on its own, we need to bolt together a set of them to represent an entire enum.</p><blockquote>Note: Confusion once again stems from bad terminology. You might intuitively think that radio refers to the collection of several radio buttons, because this is what we see in the real world, but it is not the case. It would be much better to call this &lt;input type=&quot;radio-button&quot;&gt; instead.</blockquote><p>Another difference is that &lt;input&gt; is a void element (it cannot have any children), but &lt;select&gt; is not. That’s why it is much easier to understand how &lt;select&gt; works, and that is why select couldn’t be an &lt;input&gt; subtype.</p><blockquote>Note: The concept of a void element doesn’t make much sense either. We clearly need to add children to &lt;input&gt; elements, in fact, it does have a shadow tree for various subtypes. This begs the question, why not simply allow this:</blockquote><pre>&lt;input type=&quot;radio&quot;&gt;<br>  &lt;input type=&quot;radio-button&quot;&gt;<br>  &lt;input type=&quot;radio-button&quot;&gt;<br>  &lt;input type=&quot;radio-button&quot;&gt;<br>&lt;/input&gt;</pre><p>Anyway, the point is, select and radio represent the exact same concept, they differ only in representation, again, something that has nothing to do with semantics whatsoever.</p><h4>Array</h4><p>In some cases, we need more than a single value. HTML allows &lt;select&gt; to be multi-select and in that case we can represent the selected values using an array.</p><p>Thus, while it would make sense to combine &lt;select&gt; and &lt;input type=&quot;radio&quot;&gt;, because they expect the same values, it would also make sense to separate single-select and multi-select, because they expect different values:</p><pre>&lt;select&gt;<br>&lt;select-multiple&gt;</pre><h4>Null</h4><p>The last data type we need to talk about is null. It represents the absence of a value when a field is optional.</p><p>Enums, arrays, objects and numbers can all be nullable.</p><p>Strings are a bit tricky, because the value of an empty text field is the empty string. We can convert this to null for optional text fields if needed, but we can also work with the empty string as well.</p><p>Booleans, however, cannot be null by design. This is because a boolean is actually an enum with two possible values and null would be the third. Think of it like this: a checkbox is either empty or selected, it cannot be anything else.</p><h4>Putting it all together</h4><p>To make sense of HTML form elements, first we need to reclassify them according to the type of value they expect from the user:</p><pre>boolean<br>  &lt;input type=&quot;checkbox&quot;&gt;<br>number<br>  &lt;input type=&quot;number&quot;&gt;<br>  &lt;input type=&quot;range&quot;&gt;<br>string<br>  &lt;input type=&quot;text&quot;&gt;<br>  &lt;input type=&quot;email&quot;&gt;<br>  &lt;input type=&quot;password&quot;&gt;<br>  &lt;input type=&quot;search&quot;&gt;<br>  &lt;input type=&quot;tel&quot;&gt;<br>  &lt;input type=&quot;url&quot;&gt;<br>  &lt;textarea&gt;<br>object<br>  &lt;input type=&quot;color&quot;&gt;<br>  &lt;input type=&quot;date&quot;&gt;<br>  &lt;input type=&quot;datetime-local&quot;&gt;<br>  &lt;input type=&quot;time&quot;&gt;<br>  &lt;input type=&quot;month&quot;&gt;<br>  &lt;input type=&quot;week&quot;&gt;<br>  &lt;input type=&quot;file&quot;&gt;<br>enum<br>  &lt;input type=&quot;radio&quot;&gt;<br>  &lt;select&gt;</pre><p>Next, we merge elements/types that shouldn’t be separate and separate that shouldn’t be merged.</p><p>We’ll also choose better names as well:</p><pre>Toggle(); //&lt;input type=&quot;checkbox&quot;&gt;<br><br>NumberField(); //&lt;input type=&quot;number&quot;&gt;<br>NumberPicker(); //&lt;input type=&quot;range&quot;&gt;<br><br>TextField(); //&lt;input type=&quot;text&quot;&gt; &lt;input type=&quot;email&quot;&gt; &lt;input type=&quot;search&quot;&gt; &lt;input type=&quot;tel&quot;&gt; &lt;input type=&quot;url&quot;&gt; &lt;textarea&gt;<br>SecureField(); //&lt;input type=&quot;password&quot;&gt;<br><br>ColorPicker(); //&lt;input type=&quot;color&quot;&gt;<br>DatePicker(); //&lt;input type=&quot;date&quot;&gt;<br>TimePicker(); //&lt;input type=&quot;time&quot;&gt;<br>DateTimePicker(); //&lt;input type=&quot;datetime-local&quot;&gt;<br>FilePicker(); //&lt;input type=&quot;file&quot;&gt;<br><br>Picker(); //&lt;select&gt; &lt;input type=&quot;radio&quot;&gt;<br>PickerMultiple(); //&lt;select multiple&gt;</pre><blockquote>Note: Since there is no day input, week is buggy and doesn’t make sense, just like the month input, I did not implement them yet. But the point is, they would still easily fit this new model, along with any other similar inputs.</blockquote><p>Finally, any current behavior that isn’t covered by a separate construct should be achieved by a modifier:</p><pre>TextField()<br>  .textFieldStyle(&quot;email&quot;); //email, search, tel, url</pre><pre>TextField()<br>  .whiteSpace(&quot;pre&quot;); //same as the white-space CSS property</pre><pre>Picker()<br>  .pickerStyle(&quot;radio&quot;); //radio, dropdown, ...</pre><h4>Final notes</h4><p>There are many other aspects of HTML forms but there is only so much I can shoehorn into a single article.</p><p>This is an ongoing project and I am working on many other aspects as well, like buttons, validation, grouping and output elements and I am hoping that I can explore them in another installment.</p><p>But your support means a lot.</p><p>If you like my articles please clap and share it with your friends and colleagues.</p><p>And if you are interested in a particular topic or just want to point out the flaws in my design then please let me know in a comment. I aim to answer all of your messages.</p><p>Thank you for reaching the end of this article, have a great day and stay tuned.</p><p>⬅️ <a href="https://medium.com/@decketts/how-to-unfuck-css-flex-the-abc-of-xyz-c4ca157be1d1">Part 16 — How to unfuck CSS flex — The ABC of XYZ</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=526193da6dde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to unfuck CSS flex — The ABC of XYZ]]></title>
            <link>https://decketts.medium.com/how-to-unfuck-css-flex-the-abc-of-xyz-c4ca157be1d1?source=rss-c2de8845fa94------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4ca157be1d1</guid>
            <category><![CDATA[uiscript]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[flexbox]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Bence Meszaros]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 13:55:19 GMT</pubDate>
            <atom:updated>2024-10-21T13:55:19.740Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to unfuck CSS flex — The ABC of XYZ</h3><h4>UIScript DevBlog, Part 16</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O29z8-MRSOocUddb9rTueg.png" /><figcaption>tl;dr</figcaption></figure><h4>Intro</h4><p>So far I&#39;ve only talked about why the design of flex sucks so in this article I want to show you my idea of a redesign.</p><p>This might be a bit more technical, but a lot of fun if you have a little bit of experience (and patience) with this layout model.</p><p>Let&#39;s get started.</p><h4>Flex is dimension agnostic</h4><p>I think the biggest problem with the design of flex is that it tries to be dimension agnostic. This means that the entire configuration of a horizontal and a vertical distribution is identical (well, almost), the only difference is their main direction:</p><pre>#horizontal-or-vertical {<br>  display: flex;<br>  flex-wrap: wrap;<br>  justify-content: flex-start;<br>  align-items: flex-start;<br>  align-content: flex-start;<br>}</pre><p>As you can see, without the flex-direction property, we have no way of knowing what the actual horizontal and vertical layout is supposed to be, everything is abstract.</p><p>This design is only beneficial in a single scenario, where we want to transpose the distribution later on — in other words, we want to flip the axes without needing to adjust any additional properties.</p><p>This means that by changing only a single property (flex-direction), we want the previous horizontal alignment to become the new vertical alignment and the previous vertical alignment to become the new horizontal alignment, automatically.</p><p>This scenario is so weird, rare and unnatural that I can’t clearly demonstrate it.</p><p>In all other (and much simpler) scenarios, this design is extremely confusing and obscure.</p><h4>A tiny detour</h4><p>Aside from the fact that this dimension agnostic approach is bad, even the implementation of this idea was fumbled.</p><p>If you don’t care about UIScript and still want to keep using flex in CSS then here is a little dictionary to help you cope with all this nonsense:</p><ul><li><strong>item(s):</strong> the actual child elements of a flex container</li><li><strong>row, column</strong>: virtual “boxes” around items</li><li><strong>content:</strong> either row or column, depending on the direction</li></ul><p>Using these definitions, we can understand a little bit better what flex properties are trying to do:</p><ul><li><strong>justify-content</strong>: how to fill a row or column with items</li><li><strong>align-items: </strong>how to position items relative to each other</li><li><strong>align-content:</strong> how to position rows or columns in the container</li></ul><p>But these alignment properties are still cringe, for one specific reason: justify shouldn’t be a property name but a value (just like when working with text), but flex needs three alignment controls and items and content are already taken.</p><p>So, what about the main axis and the cross axis? Why not use those?</p><ul><li><strong>align-items-main,</strong> instead of justify-content</li><li><strong>align-items-cross,</strong> instead of align-items</li><li><strong>align-content-cross,</strong> instead of align-content</li></ul><p>We are still in dimension agnostic land, all three are alignments, all three are self-explanatory, all three are consistent and all three are using the very same concepts flex has already defined. I didn’t even have to make up anything new.</p><p>It truly eludes me why these aren’t the actual names of these properties.</p><h4>A new design</h4><p>Now, back to the actual redesign.</p><p>I wanted to design something that is far more generic and I also wanted to drop this dimension agnostic bullshit.</p><p>To build a better system, we need to understand three concepts. First, the concept of axes. This is the easiest, we have X, Y (and Z), we just need to use them in our model.</p><p>Second, we need to list what features we want to control using this container. A linear distribution (including flex) has five:</p><ul><li>size</li><li>spacing</li><li>alignment</li><li>overflow</li><li>direction</li></ul><p>And third, we need to be able to control these features for all views, including the container and each and every content view. This is where things get a bit more complex, for two reasons:</p><ul><li>children can be controlled in two ways: all children together on the parent or one by one individually on themselves</li><li>containers can be nested inside each other, so a View can be a parent and a child at the same time</li></ul><p>Again, even though we are dealing with a simple linear distribution, we can easily end up with a complex scenario. But if you take a moment to understand these three concepts, you’ll be able to use this layout model much more efficiently.</p><p>Here is a raw but comprehensive list of all the possible properties defined by this logic:</p><pre>//manipulate the child itself<br>child.sizeX<br>child.sizeY<br>child.spacingX<br>child.spacingY<br>child.alignX<br>child.alignY<br>child.overflowX<br>child.overflowY<br>child.directionX<br>child.directionY<br><br>//manipulate the parent itself<br>parent.sizeX<br>parent.sizeY<br>parent.spacingX<br>parent.spacingY<br>parent.alignX<br>parent.alignY<br>parent.overflowX<br>parent.overflowY<br>parent.directionX<br>parent.directionY<br><br>//manipulate all children from the parent<br>parent.childSizeX<br>parent.childSizeY<br>parent.childSpacingX<br>parent.childSpacingY<br>parent.childAlignX<br>parent.childAlignY<br>parent.childOverflowX<br>parent.childOverflowY<br>parent.childDirectionX<br>parent.childDirectionY</pre><p>Some of these might not make sense right away, some might be confusing or misleading, but let’s break them down and see what’s what.</p><h4>Size</h4><p>Let’s start with something simple. Every View in our layout has to have a horizontal and vertical size. We can call this sizeX and sizeY, or simply width and height:</p><pre>View()<br>  .width(100)  //sizeX (horizontal size)<br>  .height(50); //sizeY (vertical size)</pre><p>This is true for the container and for all of its contents, too:</p><pre>Stack(<br>  View().width(50)<br>  View().width(70)<br>  View().width(90)<br>)<br>  .width(300);</pre><p>But the whole point of a container is to have the ability to control all contents simultaneously, right from the container. This would look something like this:</p><pre>Stack(<br>  View(),<br>  View(),<br>  View()<br>)<br>  .width(300)<br>  .childWidth(100);</pre><p>Unfortunately, CSS flex kind of forgot about this.</p><h4>Spacing</h4><p>Spacing is also fairly simple and a bit better supported in CSS flex than size.</p><p>When we control spacing directly on children, we use margin:</p><pre>Stack(<br>  View().marginX(10),<br>  View().marginX(20),<br>  View().marginX(30)<br>);</pre><p>and when we control spacing from the parent, we use gap:</p><pre>Stack(<br>  View(),<br>  View(),<br>  View()<br>)<br>  .gapX(20);</pre><p>Spacing is where the importance of having control directly on the parent vs having control on the children becomes clear: gaps don’t belong to any children logically, they sit between them, so it is cumbersome to handle them directly on children.</p><p>So, for example this:</p><pre>Stack(<br>  View().marginRight(10)<br>  View().marginLeft(10)<br>);</pre><p>is much better like this:</p><pre>Stack(<br>  View(),<br>  View()<br>)<br>  .gapX(20);</pre><h4>Alignment</h4><p>Alignment is a bit more nuanced, but should work the exact same way. We need a way to handle alignment horizontally, vertically and control children from the parent or directly from themselves.</p><p>To control children from the parent we could do something like this:</p><pre>HStack(<br>  View(),<br>  View(),<br>  View()<br>)<br>  .childAlignY(&quot;center&quot;);</pre><p>and to control alignment directly on children we could do something like this:</p><pre>HStack(<br>  View().alignY(&quot;top&quot;),<br>  View().alignY(&quot;middle&quot;),<br>  View().alignY(&quot;bottom&quot;)<br>);</pre><p>However, there are two differences between horizontal and vertical alignments:</p><ol><li>Overriding horizontal align on children in a horizontal distribution doesn’t make sense (or vertical align in a vertical distribution), because that would conflict with the entire point of a Stack/distribution.</li><li>If the distribution is wrapping, we need an additional vertical align value in a horizontal (or an additional horizontal align value in a vertical) distribution. This value is analogous to align-content.</li></ol><p>So, instead of two values on the parent and two on each child, we need three values on the parent and one value on each child, like this:</p><pre>HStack(<br>  View().alignY(&quot;top&quot;),           //same as align-self, overrides childAlignY<br>  View().alignY(&quot;middle&quot;),        //same as align-self, overrides childAlignY<br>  View().alignY(&quot;bottom&quot;)         //same as align-self, overrides childAlignY<br>)<br>  .childAlignX(&quot;left&quot;)            //same as justify-content<br>  .childAlignY(&quot;top&quot;, &quot;middle&quot;);  //same as align-items and align-content</pre><p>and this:</p><pre>VStack(<br>  View().alignX(&quot;left&quot;),          //same as align-self, overrides childAlignX<br>  View().alignX(&quot;center&quot;),        //same as align-self, overrides childAlignX<br>  View().alignX(&quot;right&quot;)          //same as align-self, overrides childAlignX<br>)<br>  .childAlignX(&quot;left&quot;, &quot;center&quot;)  //same as align-items and align-content<br>  .childAlignY(&quot;top&quot;);            //same as justify-content</pre><p>Make no mistake, you do the exact same thing with flex, the only difference is that you need a ton of extra concepts like item, content, justify, and self.</p><h4>Overflow</h4><p>Overflow is a generic container feature. It handles content that is bigger than the container.</p><p>There are two important things here:</p><ol><li>Stacks (flex) introduce the wrap, which is an overflow strategy, not a standalone feature. Overflow strategies are mutually exclusive, meaning that if we use for example crop or scroll, the content cannot wrap anymore, because it makes no sense. Conversely, if the content wraps, it cannot be cropped or scrolled.</li><li>Overriding the overflow strategy on children is a weird concept. Flex doesn’t support it and it doesn’t make much sense so there is no solution for this in UIScript either.</li></ol><p>Since we don’t need this on children, we need only two properties on the parent: overflowX and overflowY:</p><pre>HStack(<br>  View(),<br>  View(),<br>  View()<br>)<br>  .overflowX(&quot;top-bottom&quot;) //visible, crop, scroll, top-bottom (wrap), bottom-top (wrap)<br>  .overflowY(&quot;scroll&quot;); //visible, crop, scroll (not possible to wrap)</pre><p>However, there are some rules that we need to keep in mind:</p><ul><li>If the parent is bigger than its children, overflow (including wrapping) cannot happen. This includes the scenario where the parent inherits its size from its children (the parent is always the same size as the sum of its children). You can read all about Stack sizing in <a href="https://medium.com/@decketts/css-flex-isnt-flexible-here-s-why-acb2aa519b6a">this article</a>.</li><li>If the parent is smaller than its children (overflow happens), then no alignment can happen, it just doesn’t make much sense.</li><li>Wrapping can only be set as an overflow strategy in the direction of the distribution. A Stack (flex) cannot wrap into two dimensions or even into two directions at the same time, it doesn’t make much sense either.</li><li>Wrapping can happen in two directions: a horizontal Stack can wrap from top to bottom or from bottom to top, a vertical Stack can wrap from left to right, or from right to left.</li></ul><h4>Direction</h4><p>Direction in a Stack (flex) is similar to overflow in that it is only relevant for the parent and overriding it on children makes little to no sense.</p><p>There are two ways to think about direction in Stacks:</p><ol><li>either there is one direction value and one overflow value if wrap is needed,</li><li>or there are two direction values: one for the distribution and one for wrap if needed.</li></ol><p>These are just different mental models, they both describe the same thing:</p><pre>//directionX + overflowX<br>Stack()<br>  .directionX(&quot;left right&quot;)<br>  .overflowX(&quot;top bottom&quot;);<br><br>//directionX + directionY<br>Stack()<br>  .direction(&quot;left right&quot;, &quot;top bottom&quot;);</pre><p>To learn more about Stack directions, you can check out <a href="https://medium.com/@decketts/how-to-unfuck-css-flex-the-basics-a70aad5df1f2">this article</a>.</p><h4>Putting it all together</h4><p>Remember the comprehensive list from earlier? We can now change a few names and it’ll all come together as one system:</p><pre>//manipulate the child itself<br>View()<br>  .width()        //sizeX<br>  .height()       //sizeY<br>  .marginX()      //spacingX<br>  .marginY()      //spacingY<br>  .alignX()       //alignX<br>  .alignY();      //alignY<br>  //.overflowX()  //overflowX, not allowed on children<br>  //.overflowY()  //overflowY, not allowed on children<br>  //.directionX() //directionX, not allowed on children<br>  //.directionY() //directionY, not allowed on children<br><br>//manipulate the parent itself<br>Stack()<br>  .width()        //sizeX<br>  .height()       //sizeY<br>  .marginX()      //spacingX<br>  .marginY()      //spacingY<br>  .alignX()       //alignX<br>  .alignY()       //alignY<br>  //.overflowX()  //overflowX, not allowed on children<br>  //.overflowY()  //overflowY, not allowed on children<br>  //.directionX() //directionX, not allowed on children<br>  //.directionY() //directionY, not allowed on children<br><br>//manipulate all children from the parent<br>  .childWidth()   //childSizeX<br>  .childHeight()  //childSizeY<br>  .gapX()         //childSpacingX<br>  .gapY()         //childSpacingY<br>  .childAlignX()  //childAlignX<br>  .childAlignY()  //childAlignY<br>  .overflowX()    //childOverflowX<br>  .overflowY()    //childOverflowY<br>  .direction();   //childDirectionX and childDirectionY</pre><p>As you can see, the basic features are the same on the parent and on the children, because any View might be a child, but only a container can be a parent.</p><p>This way, we can simplify and adjust our model a little bit:</p><pre>View()<br>  .width()<br>  .height()<br>  .marginX() //marginLeft, marginRight is also available<br>  .marginY() //marginTop, marginBottom is also available<br>  .alignX()<br>  .alignY();<br><br>Container() //same as View, plus these<br>  .childWidth()<br>  .childHeight()<br>  .gapX()<br>  .gapY()<br>  .childAlignX()<br>  .childAlignY()<br>  .overflowX()<br>  .overflowY()<br><br>Stack() //same as Container, plus this<br>  .direction();</pre><blockquote>Note: There are two more features that we need to mention: padding and order. Padding is the spacing between the parent and its children so it would be wise to only work with it on containers, while order should be defined by the actual order of Views inside the parent. If we want a different order, we can simply change it, I wouldn’t want to introduce a property for this neither on the parent, nor on the children. But I will experiment with this in the future.</blockquote><h4>Conclusion</h4><p>A dimension agnostic approach has very limited upside and only in rare and specific cases, but severe downsides in simpler and far more common cases.</p><p>For this, I suggest to use proper axes (X and Y) instead to define various features of containers, including distributions.</p><p>There are five such features:</p><ul><li>size</li><li>spacing</li><li>alignment</li><li>overflow</li><li>direction</li></ul><p>There are two ways to control these features on a View: directly on themselves or centrally on their parent/container.</p><p>Since any View can act as a child but only a container can act as a parent, all Views should have the same set of controls to define themselves and/or override the settings coming from their parent.</p><p>The most confusing aspect we need to pay special attention to, is when a container is also a content and it controls its own features as well as its children:</p><pre>HStack(<br>  VStack(<br>    View(),<br>    View(),<br>    View()<br>  )<br>    .alignY(&quot;center&quot;) //sets its own alignment (overrides its parent)<br>    .childAlignY(&quot;center&quot;) //sets the alignment of its children<br>);</pre><h4>Outro</h4><p>Thank you for reading this article, I hope you found it interesting and useful. If so, please consider clapping, commenting and sharing my work with others.</p><p>Thanks, and take care.</p><p>⬅️ <a href="https://medium.com/@decketts/css-flex-isnt-flexible-here-s-why-acb2aa519b6a">Part 15 — CSS flex isn’t flexible, here’s why</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4ca157be1d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS flex isn’t flexible, here’s why]]></title>
            <link>https://decketts.medium.com/css-flex-isnt-flexible-here-s-why-acb2aa519b6a?source=rss-c2de8845fa94------2</link>
            <guid isPermaLink="false">https://medium.com/p/acb2aa519b6a</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[uiscript]]></category>
            <dc:creator><![CDATA[Bence Meszaros]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 17:13:25 GMT</pubDate>
            <atom:updated>2024-10-14T17:13:25.499Z</atom:updated>
            <content:encoded><![CDATA[<h4>UIScript DevBlog, Part 15</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCOrYB-c12MNqAMTzOHrbA.png" /><figcaption>The three sizing scenarios in a container</figcaption></figure><h4>Intro</h4><p>As promised, let’s talk about why flex isn’t actually flexible in most cases.</p><p>When we discuss flex, we tend to focus on many properties like the flex-flow, flex-wrap and flex-basis, but almost always forget about two very important properties: the width and height of the container.</p><p>Take a look at <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/">this well-known cheat sheet from CSS-Tricks</a>. It only mentions width three times, and height only once, neither is about the size of the container.</p><p>When you introduce the width and height of the container into the mix, flex suddenly becomes much easier to digest.</p><p>Let’s see why.</p><h4>Size, not flex</h4><p>All containers, including flex, have only three options to manage sizes:</p><ol><li>set the size of the parent and the size of the children independently</li><li>derive the size of the parent from the size of the children</li><li>derive the size of the children from the size of the parent</li></ol><blockquote>Note: The 4th option would be when we derive the size of the parent from the children, while also deriving the size of the children from the parent, which is impossible.</blockquote><p>According to <a href="https://www.w3.org/TR/css-flexbox-1/#flexibility">CSS Flexible Box Layout Module Level 1, § 7. Flexibility</a> <em>“the defining aspect of flex layout is the ability to make the flex items “flex”, altering their width/height to fill the available space in the main dimension”</em>.</p><p>This statement is completely false, for several reasons:</p><ul><li>The defining aspect of this layout model is not that the children “flex”, but that they are distributed along an axis (either horizontally or vertically)</li><li>Children only “flex” in one out of three scenarios</li><li>The parent can also “flex”, but again, only in a single scenario</li><li>We always care about both dimensions, not just the main</li></ul><p>Instead of focusing on the “flex” aspect, I suggest that you focus on the sizing aspect. Use these 3 options as the basis of your mental model and always start by picking the one that fits your use case whenever you need a distribution in your layout.</p><p>Let’s see some actual examples.</p><h4>1. Independent sizes</h4><p>In this scenario, we set the size of the parent and the size of each children independently. This is useful for example for a carousel or a scrollable list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1Nix171_miPTmjwTIa-CQ.png" /><figcaption>Horizontal and vertical scrollable Stacks</figcaption></figure><p>This model is quite literally everywhere. This is the macOS System Settings with two vertical Stacks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RzPcgdrDbj97qrnPI5tFnA.png" /><figcaption>macOS System Settings</figcaption></figure><p>The key thing here is that if we add/remove children or shrink/grow them, they will not affect the size of their parent. Excessive children will simply overflow the given size and we can crop or scroll them.</p><p>Even though neither the parent nor its children are flexible, the layout is still responsive and automatic layout changes are fully under our control.</p><p>In UIScript, this would look something like this:</p><pre>HStack(<br>  View().width(50), //explicit<br>  View().width(50), //explicit<br>  View().width(50)  //explicit<br>)<br>  .width(100); //explicit</pre><h4>2. Parent size from children sizes</h4><p>In this scenario, we derive the size of the parent from the size of its children. This is useful for example for vertical or horizontal tab bars:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2XYie-W-cqu1mOpT1kvtg.png" /><figcaption>Horizontal and vertical tab bars from Stacks</figcaption></figure><p>But the Dock in macOS also works in a similar way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1jZxzhZ4WqLwp2vnXWfOg.png" /><figcaption>macOS Dock as a horizontal Stack</figcaption></figure><p>The key thing here is that if we add/remove children or shrink/grow them, the parent will shrink/grow as well. The children do not “flex”.</p><p>This is also an easy scenario, because making smaller sizes add up to a bigger size is usually a straightforward process.</p><p>In UIScript, this would look something like this:</p><pre>HStack(<br>  View().width(50), //explicit<br>  View().width(50), //explicit<br>  View().width(50)  //explicit<br>)<br>  .width(children.width); //implicit</pre><h4>3. Children sizes from parent size</h4><p>In this scenario, we derive the sizes of children from the size of their parent.</p><p>This is where the flexibility of children comes into play and this was also the most touted feature of this model, because people saw this as the ultimate layout solution after the failures of flow-based and table-based approaches.</p><p>However, this isn’t some ultimate solution either, it is merely one special case of the distribution model.</p><p>A good example for this scenario is when we need multiple columns of text to fill the available space equally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-f4mC94-TEet9I1ph-esrw.png" /><figcaption>Multiple text blocks fill the available width</figcaption></figure><p>But of course, the distribution doesn’t have to be equal. Here is an example with two columns and a sidebar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2Dndxng5eE-kgdp1DzxVg.png" /><figcaption>Sidebar and text blocks fill the available width</figcaption></figure><p>The problem is, deriving the size of children from the size of the parent is the hardest scenario, because unlike adding things up, dividing something up can happen in virtually endless ways, with various consequences that we need to address.</p><p>The complexity of this scenario is well beyond the scope of this article, but I’ll try to touch on this in future articles.</p><p>In UIScript, this would look something like this:</p><pre>HStack(<br>  View().width(parent.width / 3), //implicit<br>  View().width(parent.width / 3), //implicit<br>  View().width(parent.width / 3)  //implicit<br>)<br>  .width(1000); //explicit</pre><h4>Necessary complexity</h4><p>There are several factors that naturally complicate sizing in containers:</p><ul><li>We have only 3 scenarios but we need to consider them in both directions (horizontally and vertically), so in reality we are working with 9 different scenarios.</li><li>We can (or should be able to) control the sizes of children centrally, from the parent, regardless of scenarios or from individual children directly.</li><li>We can nest containers inside each other, making it quite complex to reconcile a top-down sizing (child size from parent size) with a bottom-up sizing (parent size from child size).</li></ul><h4>Unnecessary complexity</h4><p>Unfortunately, there are several issues that further and unnecessarily complicate sizing in CSS flex:</p><ul><li>Sizing is mixed up with positioning in the align-items and align-content properties. Both of these properties should be purely about positioning, they should not alter the size of any children in any way, yet, the stretch value does exactly that.</li><li>There is no stretch value for justify-content, making vertical and horizontal sizing inconsistent.</li><li>There aren’t any properties on the parent to control the width and height of all children centrally. There should be a concept similar to grid-template-rows and grid-template-columns.</li><li>Sizing on the children is also extremely chaotic: we can use the width and height properties (even with relative units), but there are also properties like flex-grow, flex-shrink, and flex-basis that greatly convolute them.</li></ul><p>In an upcoming article I will discuss why these issues are severe and propose a much better design.</p><h4>Conclusion</h4><p>The CSS flex layout model is not about flexibility, but distribution.</p><p>Instead of flexibility, we should focus on sizing.</p><p>We can set sizes in a container in three ways:</p><ul><li>the parent and children are independent</li><li>the size of the parent is derived from its children, or</li><li>the size of the children are derived from the parent.</li></ul><p>Once we use this as the basis of our mental model, creating distributions will become much easier.</p><p>There are factors that naturally complicate this model, such as horizontal and vertical sizing at the same time, different control possibilities and container nesting.</p><p>There are also factors that unnecessarily complicate this model, such as inconsistent properties, mixed up values and bad terminology.</p><p>The goal of UIScript is to ease both, as much as possible. In the coming weeks I will discuss a better design of this model as part of UIScript.</p><p>If you like what I’m doing, please clap, comment and share my work with others.</p><p>Thank you and stay tuned.</p><p>⬅️ <a href="https://medium.com/@decketts/how-to-unfuck-css-flex-the-basics-a70aad5df1f2">Part 14 — How to unfuck CSS flex — The basics</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acb2aa519b6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to unfuck CSS flex — The basics]]></title>
            <link>https://decketts.medium.com/how-to-unfuck-css-flex-the-basics-a70aad5df1f2?source=rss-c2de8845fa94------2</link>
            <guid isPermaLink="false">https://medium.com/p/a70aad5df1f2</guid>
            <category><![CDATA[flexbox]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[uiscript]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Bence Meszaros]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 14:44:18 GMT</pubDate>
            <atom:updated>2024-10-02T14:46:29.247Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to unfuck CSS flex — The basics</h3><h4>UIScript DevBlog, Part 14</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NkqtG96YHsx86vx6ni7EcA.png" /><figcaption>Ooh-la-la</figcaption></figure><p>Do you find flexbox confusing?</p><p>Have you tried checking the <a href="https://www.w3.org/TR/css-flexbox-1/">official specification</a>? Or <a href="https://stackoverflow.com/questions/tagged/flexbox">Stackoverflow</a>?</p><p>How about a clever <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/">cheat sheet</a>? Or a <a href="https://flexboxfroggy.com/">fun little game</a>?</p><p>Nothing?</p><p>Then maybe this is your lucky day. What if I told you that the problem isn’t you or your lack of cognitive ability to understand and memorize a boatload of random concepts but the lack of cognitive ability on the part of the people who pulled these concepts out of their asses?</p><p>What if, instead of <a href="https://css-tricks.com/a-quick-way-to-remember-difference-between-justify-content-align-items/">mnemonic devices</a> (I mean, really?), we would redesign this model so that we wouldn’t need any of this junk just to use a f*cking layout model?</p><p>Wouldn’t that be great?</p><p>Well, this is exactly what I did.</p><p>Since there are only a handful of layout models provided by browsers, I really want to make this model work for UIScript. My idea is to wrap this model in JS and fix whatever properties and values I can to make it simple, intuitive and consistent both internally and externally.</p><p>There is a lot to unpack here and there is only so much I can put into a single article so I will gradually cover each aspect of this layout model in the coming weeks.</p><p>In this article I will delve into the basics: how to better name this model and how to better define its direction.</p><blockquote>Note: If you aren’t interested in UIScript, don’t worry, this article might still be useful to you to decipher flexbox.</blockquote><p>Let’s get started.</p><h4>Introducing the Stack</h4><p>Right off the bat, we need a better name. Flexbox is neither a box (in fact, <a href="https://medium.com/@decketts/there-is-no-box-model-in-css-and-this-is-why-borders-are-terrible-dd7e4b736955">there aren’t even any boxes in CSS</a>), nor is it flexible in most cases (we’ll get there in another installment).</p><p>Instead, let’s call this model a <strong>Stack</strong>.</p><p>A Stack is a simple collection of ordered views that might be familiar to you if you are a Swiftie (no, not <a href="https://en.wikipedia.org/wiki/Swifties">that</a> kind of Swiftie, but the programmer kind), but even beyond <a href="https://developer.apple.com/documentation/swiftui/building-layouts-with-stack-views">SwiftUI</a> and programming, stacks are essentially everywhere.</p><p>Here is one in action:</p><pre>Stack(<br>  Text(&quot;Hello&quot;),<br>  Text(&quot;World&quot;)<br>);</pre><p>This syntax is also a much more direct approach. Instead of adding a layout mode to an element, the constructor itself defines the layout:</p><pre>/* instead of this in CSS */<br>#flex-container {<br>  display: flex;<br>}</pre><pre>//we do this in UIScript<br>Stack();</pre><p>What can be more semantic than this?</p><h4>Deranged directions</h4><p>Our next stop is the direction of the distribution. This is where things go from bad to worse.</p><p>The problem with flex-direction is that a row is not a direction, neither is a column. They are structures that don’t have a direction.</p><p>In fact, we don’t even know whether row means “left to right” or “right to left” without consulting a separate property — direction — that sets the direction of a whole different thing (text).</p><p>Never mind the fact that flex direction is called flex-direction and text direction is called simply direction, and the fact that flex direction uses completely different values than text direction, text direction doesn’t even have a ttb or btt value, so we still don’t know what column actually means.</p><pre>#left-to-right {<br>  direction: ltr; /* sure thing */<br>}<br><br>#right-to-left {<br>  direction: rtl; /* no problem */<br>}<br><br>#top-to-bottom {<br>  direction: ttb; /* no such value, sowwy */<br>}<br><br>#bottom-to-top {<br>  direction: btt; /* no such value either */<br>}</pre><p>Is it “top to bottom” or “bottom to top”? Sure, we can consider the former the default, but are there any other properties affecting this? What about writing-mode and/or text-orientation?</p><p>Maybe, maybe not. Who knows?</p><p>But hey, did you know that we can also reverse them, even though it makes even less sense. What exactly does it mean to reverse a row? Or a column?</p><pre>/* stranger things */<br><br>#mirror-mirror {<br>  flex-direction: row-reverse;<br>}<br><br>#upside-down {<br>  flex-direction: column-reverse;<br>}</pre><p>Are you kidding me?</p><p>And then, we have the wrap. Since CSS cannot comprehend that wrap settings belong to the overflow property, we have yet another property called flex-wrap that sets the direction of the wrap.</p><p>No, not flex-wrap-direction, but simply flex-wrap. You know, to make it easy to remember.</p><p>Now, I can understand wrapping rows of text, but what does it even mean to wrap a column? Or to reverse wrap a reversed column? 😵‍💫</p><p>I mean, it’s just diabolical.</p><p>I get it, you can write a thousand pretty specifications and redefine every single word in the English language, but that doesn’t make your junk, well, less junk.</p><p>At this point I could argue that even this would be better:</p><pre>#your-present {<br>  flex-wrap: wrap;<br>}<br><br>#my-present {<br>  flex-wrap: unwrap;<br>}</pre><p>Or this:</p><pre>#yummy {<br>  flex-wrap: 🌯;<br>}<br><br>#yucky {<br>  flex-wrap: -🌯;<br>}</pre><p>They sure save some bandwidth and typing time, and easy to spot, even in a large codebase. What can be more important than that?</p><h4>Some fresh water in hell</h4><p>Now, onto the solution.</p><p>Instead of new properties like flex-direction and flex-wrap, and new words like</p><ul><li>row</li><li>column</li><li>wrap</li><li>reverse</li></ul><p>Stacks in UIScript simply use the .direction() and .overflow() getter/setters with common words like</p><ul><li>left</li><li>right</li><li>top</li><li>bottom</li></ul><p>Here is a simple example:</p><pre>Stack()<br>  .direction(&quot;top bottom&quot;)<br>  .overflowY(&quot;left right&quot;);</pre><p>We don’t even need a third property for shorthand access, like flex-flow, we can combine the two inside .direction():</p><pre>Stack()<br>  .direction(&quot;top bottom&quot;, &quot;left right&quot;);</pre><blockquote>Note: Verbosity is up for debate: we could use “ltr”, “left right”, “left to right”, or “from left to right”, but the point is they are actual directions.</blockquote><p>The most confusing part about flex is that it obfuscates the fact that there are exactly 8 different multiline/multicolumn layouts in total.</p><p>These are all the options using CSS:</p><pre>#flexbox {<br>  flex-flow: row wrap;<br>  flex-flow: row wrap-reverse;<br>  flex-flow: row-reverse wrap;<br>  flex-flow: row-reverse wrap-reverse;<br>  flex-flow: column wrap;<br>  flex-flow: column wrap-reverse;<br>  flex-flow: column-reverse wrap;<br>  flex-flow: column-reverse wrap-reverse;<br>}</pre><p>And these are all the options using UIScript:</p><pre>Stack()<br>  .direction(&quot;left right&quot;, &quot;top bottom&quot;)<br>  .direction(&quot;left right&quot;, &quot;bottom top&quot;)<br>  .direction(&quot;right left&quot;, &quot;top bottom&quot;)<br>  .direction(&quot;right left&quot;, &quot;bottom top&quot;)<br>  .direction(&quot;top bottom&quot;, &quot;left right&quot;)<br>  .direction(&quot;top bottom&quot;, &quot;right left&quot;)<br>  .direction(&quot;bottom top&quot;, &quot;left right&quot;)<br>  .direction(&quot;bottom top&quot;, &quot;right left&quot;);</pre><p>What’s even more interesting is once we make an exhaustive list like this, it becomes clear what text direction and text wrap is missing, even though they shouldn’t:</p><pre>#text {<br>  direction: ltr ttb;<br>  direction: ltr btt; /* no such option */<br>  direction: rtl ttb;<br>  direction: rtl btt; /* no such option */<br>  direction: ttb ltr; /* no such option */<br>  direction: ttb rtl; /* no such option */<br>  direction: btt ltr; /* no such option */<br>  direction: btt rtl; /* no such option */<br>}</pre><p>Sure, some options like “bottom to top” text or “bottom to top” wrap may feel alien to you, but all of these are valid options nonetheless.</p><p>In fact, the designers of the direction property clearly thought that even “top to bottom” text wasn’t a thing, even though major languages like Chinese, Japanese, Mongolian and Korean are still using it, let alone older languages and scripts that have to be supported too.</p><p>For a community that prides itself on accessibility and diversity, it sure feels ironic.</p><p>Why not just implement all possible options in a single, comprehensive model? Why does everything feel like an afterthought in CSS?</p><h4>A quick word about defaults</h4><p>Once we make a comprehensive list of all of our options, it becomes much easier to define defaults.</p><p>For example, we can still tie the direction of the basic Stack to the writing direction, but now it is much clearer:</p><pre>//text is left to right<br>Stack(); //same as Stack().direction(&quot;left right&quot;)<br><br>//text is right to left<br>Stack(); //same as Stack().direction(&quot;right left&quot;)<br><br>//text is top to bottom<br>Stack(); //same as Stack().direction(&quot;top bottom&quot;);<br><br>//text is bottom to top<br>Stack(); //same as Stack().direction(&quot;bottom top&quot;);</pre><p>In addition, we can introduce SwiftUI-style constructors like VStack() and HStack() that create “top to bottom” and “left to right” distributions by default, but ZStack is where flexbox absolutely shits the bed.</p><p>Just as with the text direction, poor flexbox completely skipped over one third of all possible options.</p><p>But that’s a rage for another day.</p><pre>HStack(); //same as Stack().direction(&quot;left right&quot;)<br>VStack(); //same as Stack().direction(&quot;top bottom&quot;)<br>ZStack(); //not possible using flex, under development using another model</pre><h4>That’s a wrap (pun unintended)</h4><p>That’s all I have for you today. Thank you for making it to the very end and I hope you’ve found it interesting.</p><p>In the coming weeks I will discuss the rest of flexbox/Stacks, including alignments, margins, paddings, gaps, and sizes, so stay tuned.</p><p>Until then, if you like UIScript, please clap, comment and share my work with others.</p><p>Thank you.</p><p>⬅️ <a href="https://medium.com/@decketts/css-relative-units-are-terrible-heres-why-b94407b94e7e">Part 13 — CSS relative units are terrible, here’s why</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a70aad5df1f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS relative units are terrible, here’s why]]></title>
            <link>https://decketts.medium.com/css-relative-units-are-terrible-heres-why-b94407b94e7e?source=rss-c2de8845fa94------2</link>
            <guid isPermaLink="false">https://medium.com/p/b94407b94e7e</guid>
            <category><![CDATA[uiscript]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Bence Meszaros]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 18:10:39 GMT</pubDate>
            <atom:updated>2024-09-17T18:14:19.581Z</atom:updated>
            <content:encoded><![CDATA[<h4>UIScript DevBlog, Part 13</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EC8rB2kmENPVUynaX2OXJg.png" /><figcaption>tl;dr</figcaption></figure><h4>Intro</h4><p>While CSS relative units seem like a nice addition to the language, they do more harm than good. In this article I will dive into the reasons why I think CSS relative units are bad and show you how UIScript provides a much more robust and much more capable alternative.</p><p>Let’s get started.</p><h4>The problem(s)</h4><p>Let’s say we want the width of an element to be 50% of the viewport. How do we do that?</p><p>It’s simple, we can simply use the vw unit like this:</p><pre>#ermahgerd {<br>    width: 50vw;<br>}</pre><p>OK, how do we set the height of an element to be 50% of the height of the viewport?</p><p>It’s simple, too:</p><pre>#ermahgerd {<br>    height: 50vh;<br>}</pre><p>And can we set the width of an element to be 50% of the height of the viewport?</p><p>Sure, here it is:</p><pre>#ermahgerd {<br>    width: 50vh;<br>}</pre><p>So, how about doing the same with the parent instead? It should be something like pw and ph, right?</p><p>Well, not really. When using percents for the viewport, we use units like vw and vh, but when we use percents for the parent, we use %. It’s simple.</p><p>OK, but you mean %w for the width of the parent, and %h for the height of the parent, right?</p><p>Well, not quite. We use % for both the vertical and horizontal dimension, because it just means “the percent of the same property on the parent”.</p><p>But then how do we set the width of an element to be 50% of the height of the parent?</p><p>It’s simple, we don’t. It is considered an uncommon scenario so there is no solution for that. But it’s not a big deal.</p><p>OK, so if % means percent of the same property on the parent, then setting a font size can be done like this, right?</p><pre>#ermahgerd {<br>    font-size: 50%;<br>}</pre><p>Well, you can do that, but it’s considered bad practice. Instead, you should use em, because it sounds cooler. But even better, you should use rem because that refers to the root element.</p><p>OK, but can I reference the size of the root element, like rw and rh, too?</p><p>No, not really.</p><p>So, how about referencing a sibling, then? Is there a unit for that?</p><p>No, there is none.</p><p>What about referencing the parent of the parent? Or the parent of that element?</p><p>No, we can&#39;t do that either, there is no unit for that.</p><p>So, then what do you do if you need to reference anything other than these few?</p><p>Well, I suppose we can write a new specification, get it approved, convince all the major browsers to implement it and then we can use it. We can introduce gem for font sizes relative to the font size of the grandparent, or gg% for referencing the size of the great-grandparent. Or we could introduce this to reference the font size of the first sibling of the parent of the element:</p><pre>#ermahgerd {<br>  font-size: 2.5ps01em; /* for real? */<br>}</pre><p>But then, what do we do if we want anything other than these?</p><p>Simple, we just repeat these steps again. It takes a bit of time, but if we are lucky we should be able to use the new units within a couple of years. Maybe a decade tops. Isn’t it great?</p><p>Yeah, it sure is.</p><h4>The solution — use proper logic</h4><p>Sarcasm aside, it doesn’t take a CS degree to understand that the reason we are in this mess is because relative units are trying to solve a fundamentally different problem than real units. The purpose of units is to make numeric values standard and compatible (and thus comparable) with each other, but if I set, for example, the same em values for elements that have different parents, then I lose the very concept of what a unit is.</p><p>Instead, what we actually want is a way to reference a property value from another property, or in other words, create an arithmetic relationship between two properties. But since CSS doesn’t support writing proper logic, we can’t define custom equations. Fortunately, we don’t have to, since JS already has all the tools we need.</p><p>For example, this would be an element that has its width set to 50% of the width of its parent:</p><pre>view.width = view.parent.width * 0.5;</pre><p>And these would be all the previous examples using the exact same syntax:</p><pre>view.width = viewport.width * 0.5;<br>view.height = viewport.height * 0.5;<br>view.width = viewport.height * 0.5; //referencing height from width<br><br>view.width = view.parent.width * 0.5;<br>view.height = view.parent.height * 0.5;<br>view.width = view.parent.height * 0.5; //referencing height from width<br><br>view.width = document.documentElement.width * 0.5;<br>view.height = document.documentElement.height * 0.5;<br>view.width = document.documentElement.height * 0.5; //referencing height from width<br><br>view.width = view.parent.parent.width * 0.5; //referencing a grandparent<br><br>view.width = view.parent.children[0].width * 0.5; //referencing a sibling<br><br>view.fontSize = view.parent.fontSize * 0.5; //referencing font properties</pre><blockquote>Note: For simplicity, I do not include the <em>.style</em> object in my examples. So, a valid example like <em>view.style.width</em> is simplified to <em>view.width</em>.</blockquote><p>This approach enables us to build virtually any relationships between any properties on any elements using nothing more than basic programming concepts such as objects, properties and operators. We can push this approach however we like:</p><pre>ermahgerd.width = (ermahgerd.parent.fontSize + ermahgerd.height) * viewport.opacity;</pre><p>This approach might look ridiculous until you realize that this is all we need to center a div:</p><pre>div.center = div.parent.center; //horizontal alignment<br>div.middle = div.parent.middle; //vertical alignment</pre><p>But wait a minute, these are simple assignments that aren’t reactive. How are they going to update when a dependency changes?</p><p>Worry not, my friend, enter UIScript.</p><h4>Reactive properties in UIScript</h4><p>The point of reactive programming is to create assignments that are automatically re-evaluated whenever the dependency of said assignment changes. These are often called <a href="https://learn.svelte.dev/tutorial/reactive-declarations">reactive declarations</a> (if you know Svelte or basically any other major front end framework), <a href="https://github.com/tc39/proposal-signals">signals</a> (if you’ve heard about this new proposal in JS) or <a href="https://developer.apple.com/documentation/swiftui/state">state</a> (if you’re familiar with property wrappers in SwiftUI).</p><p>The general idea is to convert every single style and layout property to a reactive property. For example, instead of this:</p><pre>view.width = viewport.width;</pre><p>We do this:</p><pre>view.width(viewport.width);</pre><p>In this example, if the width of the viewport changes, view.width is recalculated automatically. The width method is a getter/setter, which is also an object that wraps a primitive value (a boolean, a number, a string, etc.), just like a reactive variable.</p><p>I’ve written an entire article about how I envision <a href="https://medium.com/@decketts/designing-a-new-style-system-to-replace-css-182d68d2d11b">replacing CSS with these style and layout methods</a> but they can do much, much more than that. Since these are essentially function calls, it is up to UIScript to provide as much functionality during execution as possible: handling default units, allowing method chaining, pushing style and layout updates to the DOM automatically, and in this case, enabling reactivity.</p><p>In terms of static vs reactive assignments, here are the different use cases:</p><pre>view.width(100); //static value from primitive literal<br>view.width(width); //static value from variable evaluation<br>view.width(otherView.width()); //static value from property evaluation<br>view.width(otherView.width() * 2); //static value from expression evaluation<br><br>view.width(otherView.width); //reactive value from property evaluation<br>view.width(() =&gt; otherView.width() * 2); //reactive value from callback evaluation</pre><h4>Conclusion</h4><p>CSS relative units distort the meaning of real units as they try to solve an entirely different problem. Units like cm, s, deg or Hz are designed to make numeric values standard and comparable with each other, while relative units mimic arithmetic relationships between properties instead. Even then, CSS relative units offer only an extremely narrow subset of possible relationships and even those are confusing and unintuitive to use, like % versus vw and vh, or % versus em. Anything beyond these options are impossible to achieve without introducing further and further units into the language.</p><p>Instead of reinventing the wheel, we can leverage UIScript to describe style and layout relationships with actual arithmetic operators and various other basic and well-known scripting concepts. We can define virtually endless relationships without using a single relative unit, introducing a new concept or changing anything in the language itself. We achieve this using style and layout methods that wrap the actual primitive values using either a static or a reactive assignment.</p><h4>That&#39;s a wrap</h4><p>Thank you for taking the time to finish this article. I hope you&#39;ve found it interesting and if so, please consider clapping, commenting and sharing my work with others.</p><p>Until the next part — stay tuned!</p><p>⬅️ <a href="https://medium.com/@decketts/what-is-the-least-amount-of-html-you-can-serve-to-a-browser-f1d394c83ec0">Part 12 — What is the least amount of HTML you can serve to a browser?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b94407b94e7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the least amount of HTML you can serve to a browser?]]></title>
            <link>https://decketts.medium.com/what-is-the-least-amount-of-html-you-can-serve-to-a-browser-f1d394c83ec0?source=rss-c2de8845fa94------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1d394c83ec0</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[uiscript]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Bence Meszaros]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 09:50:59 GMT</pubDate>
            <atom:updated>2024-09-17T14:56:11.247Z</atom:updated>
            <content:encoded><![CDATA[<h4>UIScript DevBlog, Part 12</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0nk24hCD_GrC2IjuOYdEA.png" /><figcaption>tl;dr</figcaption></figure><h4>Intro</h4><p>One key feature of UIScript is that we can remove all HTML and CSS code from our projects and focus solely on JS. Well, almost. While CSS can, in theory, be fully eliminated, HTML cannot. This is because browsers can only parse html files automatically, they cannot parse and execute a standalone js file without an html host. If you open a js file directly in a browser (or any other script file as a matter of fact), it will show up as raw text, just like a regular txt file would.</p><p>To put it simply, there has to be at least one HTML file in our project. This is a hard rule set by the browsers, an axiom if you will, that we cannot circumvent.</p><p>But if we are forced to embed our JS application into an HTML file, then what is the least amount of HTML we can serve to the browser?</p><h4>The basics</h4><p>Web developers are typically taught, that a valid HTML file consists of four required parts: a doctype declaration, an html element, a head element and a body element, like so:</p><pre>&lt;!doctype html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;&lt;/head&gt;<br>  &lt;body&gt;&lt;/body&gt;<br>&lt;/html&gt;</pre><p>This isn’t actually true at all. According to the <a href="https://html.spec.whatwg.org/multipage/syntax.html#optional-tags">HTML Living Standard § 13.1.2.4</a>, the head, the body and even the html element are all optional (more precisely conditionally required, but precision is not exactly the strong suit of this spec).</p><p>In this case, this is a perfectly valid html file:</p><pre>&lt;!doctype html&gt;</pre><p>When the browser parses this file it inserts an html, a head and a body element automatically so we always end up with the same skeleton as the previous example. This approach is a perfectly valid and standard simplification.</p><h4>The doctype</h4><p>This begs the question: can we go even further and remove the doctype declaration as well? Well, according to <a href="https://html.spec.whatwg.org/multipage/syntax.html#the-doctype">HTML Living Standard § 13.1.1</a>, a DOCTYPE is a required preamble, meaning that it is officially required, but <a href="https://developer.mozilla.org/en-US/docs/Glossary/Doctype">according to MDN, its sole purpose is to prevent a browser from switching into quirks mode</a>.</p><p>Quirks mode is the non-standard, browser specific rendering mode maintained for legacy reasons. In this mode, our document, including stuff that we create through JS, will render in an unpredictable way, causing a wide range of issues from incorrect character encodings to broken layouts.</p><p>So, basically, browsers accept so much legacy garbage and broken HTML that you have to explicitly notify the browser when you want to serve a fully standard document. Instead of opting in to legacy mode for old, pre-HTML5 documents, we need to opt out of legacy mode every single time we are serving a proper, standard HTML5 document. If you think this is beyond absurd, you are quite right.</p><blockquote>Note: According to w3techs.com, <a href="https://w3techs.com/technologies/details/ml-html5">HTML5 is used by 93.5% of all the websites</a>, and <a href="https://w3techs.com/technologies/details/ml-html_any">HTML5 is used by 97.2% of all the websites that use HTML</a>. So, every single time you create a new HTML document, just remember that the reason you are forced to include this boilerplate is that 6.5% of websites wouldn&#39;t have to update their 30-year-old code, even with a single legacy flag.</blockquote><p>This leads to yet another question. What exactly is the point of file extensions, MIME types, the Content-type HTTP header and the type HTML attribute, if none of them can be used to differentiate between HTML5 and other document types and we still need to write the document type into the actual document itself? Have you ever considered how absurd it is to serve HTML5 documents using HTTP with a ton of metadata fields but still needing to mess up your actual content with a stupid declaration?</p><p>So, apparently neither of this was acceptable:</p><pre>hello-world.html5<br>hello-world.legacyhtml</pre><p>Nor this:</p><pre>Content-type: text/html5<br>Content-type: text/legacyhtml</pre><p>Or this:</p><pre>&lt;html type=&quot;text/html5&quot;&gt;<br>&lt;html type=&quot;text/legacyhtml&quot;&gt;</pre><p>Or just introducing a new HTML attribute, or putting this info into the &lt;head&gt; element along with the rest of the document metadata using the type attribute, or using a new attribute, or a new element, or a new element with a type attribute or a new element with a new attribute.</p><p>No, they wanted to reinvent the wheel with the document type as well and introduce a new tag, which is not an element, but a node, which is a preamble but also a declaration, which is a completely unique construct within the language and we should only use &lt;!doctype html&gt; anyway, because other values aren’t parsed by the browser as actual websites.</p><p>Splendid.</p><h4>Including scripts</h4><p>We have removed as much HTML from our projects as possible, now we need to execute our scripts somehow. To do that, we can simply add them to the minimized HTML file:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;script defer src=&quot;index.js&quot;&gt;&lt;/script&gt;</pre><p>That’s it. When the browser parses this HTML file, it inserts the html, head and body elements, moves this script tag into the head automatically and fetches and executes the index.js file. It is, unfortunately, an extra round trip, but as we discussed before, we cannot bypass the HTML host.</p><blockquote>Notice, that we also added the defer attribute to the &lt;script&gt; element. This is needed, because when the browser fetches our script file it doesn’t have an HTML body yet so the script cannot access it. With the defer flag we can tell the browser to only execute the script after finishing building the HTML skeleton. But if our script doesn&#39;t need the body tag, we can skip adding this attribute.</blockquote><blockquote>Notice also, that the closing &lt;/script&gt; tag is mandatory, even when the src attribute is being used. The reason for this is that the HTML5 committee wanted new HTML5 websites to run in old, legacy browsers as well but those browsers had no concept of self-closing script tags and considered everything after an opening script tag as JS code, or in case of elements, as children of the script element. <a href="https://stackoverflow.com/questions/69913/why-dont-self-closing-script-elements-work">There had been several proposals to resolve this in a far more elegant way, but all of them were ultimately rejected, just like the entirety of XHTML</a>. As a result, the web will carry this (and many, many more) bloat until the end of time.</blockquote><p>For some time, I was trying to rationalize this limitation as having some sort of app manifest, a list of assets that my project needs, but HTML is spectacularly bad at this too. Linking style sheets, bitmaps, vector graphics, fonts, scripts and various other files all work with a different element, with a different tag or both. How awesome would it be to have a manifest like this in HTML:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;script url=&quot;index.js&quot;&gt;<br>&lt;style url=&quot;index.css&quot;&gt;<br>&lt;image url=&quot;profile-picture.png&quot;&gt;<br>&lt;vector url=&quot;logo.svg&quot;&gt;<br>&lt;data url=&quot;user-from-database.json&quot;&gt;<br>&lt;font url=&quot;Inter-Regular.otf&quot;&gt;</pre><p>This idea was short lived and I migrated this &quot;manifest&quot; concept to JS as well.</p><h4>What about JS-in-HTML?</h4><p>Technically, we could write all of our JS code inside &lt;script&gt; tags instead of linking it from an external file, saving one round trip to the server as well as an extra project file, but then the code would be tightly coupled to HTML and wouldn’t be able to run on its own, in a different environment.</p><p>Another “sinister” argument against this is that the goal is to fully separate JS from HTML so that one day browsers could load and execute JS code completely independently, without any HTML host.</p><p>And finally, it would also look much uglier, because the two syntaxes of the two languages would mix. But that’s just my subjective opinion, you are free to decide if this is what you prefer:</p><pre>&lt;!doctype html&gt;<br>&lt;script defer&gt;<br>let welcome = &quot;Hello World!&quot;;<br>&lt;/script&gt;</pre><h4>Conclusion</h4><p>Technically, this is a valid HTML file:</p><pre>⁣</pre><p>But if we want a standard HTML5 file, we need at least this:</p><pre>&lt;!doctype html&gt;</pre><p>We can add a script tag, but this won’t work in any browsers:</p><pre>&lt;!doctype html&gt;&lt;script src=&quot;ui.js&quot;&gt;</pre><p>Unless, we also include a closing tag:</p><pre>&lt;!doctype html&gt;&lt;script src=&quot;ui.js&quot;&gt;&lt;/script&gt;</pre><p>And set defer on the script tag to execute after building the skeleton:</p><pre>&lt;!doctype html&gt;&lt;script defer src=&quot;ui.js&quot;&gt;&lt;/script&gt;</pre><h4>That’s a wrap</h4><p>Thank you for reading this article and making it to the end. If you like what I am doing please consider clapping, commenting and sharing my work with your friends, colleagues and other web enthusiasts. Your support helps me tremendously.</p><p>Thank you again, and have a great day.</p><p>⬅️ <a href="https://decketts.medium.com/frankensteins-display-property-b92e8b966ee9">Week 11 — Frankenstein’s display property</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1d394c83ec0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>