• SMASHINGMAGAZINE.COM
    The Modern Guide For Making CSS Shapes
    You have for sure googled how to create [shape_name] with CSS at least once in your front-end career if its not something you already have bookmarked. And the number of articles and demos you will find out there is endless.Good, right? Copy that code and drop it into the ol stylesheet. Ship it!The problem is that you dont understand how the copied code works. Sure, it got the job done, but many of the most widely used CSS shape snippets are often dated and rely on things like magic numbers to get the shapes just right. So, the next time you go into the code needing to make a change to it, it either makes little sense or is inflexible to the point that you need an entirely new solution.So, here it is, your one-stop modern guide for how to create shapes in CSS! We are going to explore the most common CSS shapes while highlighting different CSS tricks and techniques that you can easily re-purpose for any kind of shape. The goal is not to learn how to create specific shapes but rather to understand the modern tricks that allow you to create any kind of shape you want.Table of ContentsYou can jump directly to the topic youre interested in to find relevant shapes or browse the complete list. Enjoy! Hexagons Octagons Stars Polygons & Starbursts Parallelograms & Trapezoids Circles & Holes Border Edges Rounded Arcs Dashed Circles Rounded Tabs Triangles Hearts Ribbons Tooltips & Speech Bubbles Cutting Corners Cut-Out Shapes Section Dividers Floral ShapesWhy Not SVG?I get asked this question often, and my answer is always the same: Use SVG if you can! I have nothing against SVG. Its just another approach for creating shapes using another syntax with another set of considerations. If SVG was my expertise, then I would be writing about that instead!CSS is my field of expertise, so thats the approach were covering for drawing shapes with code. Choosing CSS or SVG is typically a matter of choice. There may very well be a good reason why SVG is a better fit for your specific needs.Many times, CSS will be your best bet for decorative things or when youre working with a specific element in the markup that contains real content to be styled. Ultimately, though, you will need to consider what your projects requirements are and decide whether a CSS shape is really what you are looking for.Your First ResourceBefore we start digging into code, please spend a few minutes over at my CSS Shape website. You will find many examples of CSS-only shapes. This is an ever-growing collection that I regularly maintain with new shapes and techniques. Bookmark it and use it as a reference as we make our way through this guide.Is it fairly easy to modify and tweak the CSS for those shapes?Yes! The CSS for each and every shape is optimized to be as flexible and efficient as possible. The CSS typically targets a single HTML element to prevent you from having to touch too much markup besides dropping the element on the page. Additionally, I make liberal use of CSS variables that allow you to modify things easily for your needs.Most of you don't have time to grasp all the techniques and tricks to create different shapes, so an online resource with ready-to-use snippets of code can be a lifesaver!Clipping Shapes In CSSThe CSS clip-path property and its polygon() function is what we commonly reach for when creating CSS Shapes. Through the creation of common CSS shapes, we will learn a few tricks that can help you create other shapes easily.HexagonsLets start with one of the easiest shapes; the hexagon. We first define the shapes dimensions, then provide the coordinates for the six points and we are done..hexagon { width: 200px; aspect-ratio: 0.866; clip-path: polygon( 0% 25%, 0% 75%, 50% 100%, 100% 75%, 100% 25%, 50% 0%);}Were basically drawing the shape of a diamond where two of the points are set way outside the bounds of the hexagon were trying to make. This is perhaps the very first lesson for drawing CSS shapes: Allow yourself to think outside the box or at least the shapes boundaries.Look how much simpler the code already looks:.hexagon { width: 200px; aspect-ratio: cos(30deg); clip-path: polygon( -50% 50%, 50% 100%, 150% 50%, 50% 0 );}Did you notice that I updated the aspect-ratio property in there? Im using a trigonometric function, cos(), to replace the magic number 0.866. The exact value of the ratio is equal to cos(30deg) (or sin(60deg)). Besides, cos(30deg) is a lot easier to remember than 0.866.Heres something fun we can do: swap the X and Y coordinate values. In other words, lets change the polygon() coordinates from this pattern:clip-path: polygon(X1 Y1, X2 Y2, ..., Xn Yn)to this, where the Y values come before the X values:clip-path: polygon(Y1 X1, Y2 X2, ..., Yn Xn)What we get is a new variation of the hexagon:I know that visualizing the shape with outside points can be somewhat difficult because were practically turning the concept of clipping on its head. But with some practice, you get used to this mental model and develop muscle memory for it.Notice that the CSS is remarkably similar to what we used to create a hexagon:.octagon { width: 200px; aspect-ratio: 1; --o: calc(50% * tan(-22.5deg)); clip-path: polygon( var(--o) 50%, 50% var(--o), calc(100% - var(--o)) 50%, 50% calc(100% - var(--o)) );}Except for the small trigonometric formula, the structure of the code is identical to the last hexagon shape set the shapes dimensions, then clip the points. And notice how I saved the math calculation as a CSS variable to avoid repeating that code.If math isnt really your thing and thats totally fine! remember that the formulas are simply one part of the puzzle. Theres no need to go back to your high school geometry textbooks. You can always find the formulas you need for specific shapes in my online collection. Again, that collection is your first resource for creating CSS shapes!And, of course, we can apply this shape to an <img> element as easily as we can a <div>:It may sound impossible to make a star out of only five points, but its perfectly possible, and the trick is how the points inside polygon() are ordered. If we were to draw a star with pencil on paper in a single continuous line, we would follow the following order:Its the same way we used to draw stars as kids and it fits perfectly in CSS with polygon()! This is another hidden trick about clip-path with polygon(), and it leads to another key lesson for drawing CSS shapes: the lines we establish can intersect. Again, were sort of turning a concept on its head, even if its a pattern we all grew up making by hand.Heres how those five points translate to CSS:.star { width: 200px; aspect-ratio: 1; clip-path: polygon(50% 0, /* (1) */ calc(50%*(1 + sin(.4turn))) calc(50%*(1 - cos(.4turn))), /* (2) */ calc(50%*(1 - sin(.2turn))) calc(50%*(1 - cos(.2turn))), /* (3) */ calc(50%*(1 + sin(.2turn))) calc(50%*(1 - cos(.2turn))), /* (4) */ calc(50%*(1 - sin(.4turn))) calc(50%*(1 - cos(.4turn))) /* (5) */ ); }The funny thing is that starbursts are basically the exact same thing as polygons, just with half the points that we can move inward.Figure 6.I often advise people to use my online generators for shapes like these because the clip-path coordinates can get tricky to write and calculate by hand.Polygon generatorStarburst generatorThat said, I really believe its still a very good idea to understand how the coordinates are calculated and how they affect the overall shape. I have an entire article on the topic for you to learn the nuances of calculating coordinates.Parallelograms & TrapezoidsAnother common shape we always build is a rectangle shape where we have one or two slanted sides. They have a lot of names depending on the final result (e.g., parallelogram, trapezoid, skewed rectangle, and so on), but all of them are built using the same CSS technique.First, we start by creating a basic rectangle by linking the four corner points together:clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%)This code produces nothing because our element is already a rectangle. Also, note that 0 and 100% are the only values were using.Next, offset some values to get the shape you want. Lets say our offset needs to be equal to 10px. If the value is 0, we update it with 10px, and if its 100% we update it with calc(100% - 10px). As simple as that!But which value do I need to update and when?Try and see! Open your browsers developer tools and update the values in real-time to see how the shape changes, and you will understand what points you need to update. I would lie if I told you that I write all the shapes from memory without making any mistakes. In most cases, I start with the basic rectangle, and I add or update points until I get the shape I want. Try this as a small homework exercise and create the shapes in Figure 11 by yourself. You can still find all the correct code in my online collection for reference.If you want more CSS tricks around the clip-path property, check my article CSS Tricks To Master The clip-path Property which is a good follow-up to this section.Masking Shapes In CSSWe just worked with a number of shapes that required us to figure out a number of points and clip-path by plotting their coordinates in a polygon(). In this section, we will cover circular and curvy shapes while introducing the other property you will use the most when creating CSS shapes: the mask property.Like the previous section, we will create some shapes while highlighting the main tricks you need to know. Dont forget that the goal is not to learn how to create specific shapes but to learn the tricks that allow you to create any kind of shape.Circles & HolesWhen talking about the mask property, gradients are certain to come up. We can, for example, cut (but really mask) a circular hole out of an element with a radial-gradient:mask: radial-gradient(50px, #0000 98%, #000);Why arent we using a simple background instead? The mask property allows us more flexibility, like using any color we want and applying the effect on a variety of other elements, such as <img>. If the color and flexible utility arent a big deal, then you can certainly reach for the background property instead of cutting a hole.Heres the mask working on both a <div> and <img>:Once again, its all about CSS masks and gradients. In the following articles, I provide you with examples and recipes for many different possibilities:Fancy CSS Borders Using Masks (CSS-Tricks)How to Create Wavy Shapes & Patterns in CSS (CSS-Tricks)Be sure to make it to the end of the second article to see how this technique can be used as decorative background patterns.This time, we are going to introduce another technique which is composition. Its an operation we perform between two gradient layers. We either use mask-composite to define it, or we declare the values on the mask property.The figure below illustrates the gradient configuration and the composition between each layer.We start with a radial-gradient to create a full circle shape. Then we use a conic-gradient to create the shape below it. Between the two gradients, we perform an intersect composition to get the unclosed circle. Then we tack on two more radial gradients to the mask to get those nice rounded endpoints on the unclosed circle. This time we consider the default composition, add.Gradients arent something new as we use them a lot with the background property but composition is the new concept I want you to keep in mind. Its a very handy one that unlocks a lot of possibilities.Ready for the CSS?.arc { --b: 40px; /* border thickness */ --a: 240deg; /* progression */--_g:/var(--b) var(--b) radial-gradient(50% 50%,#000 98%,#0000) no-repeat;mask:top var(--_g),calc(50% + 50% sin(var(--a)))calc(50% - 50% cos(var(--a))) var(--_g),conic-gradient(#000 var(--a), #0000 0) intersect,radial-gradient(50% 50%, #0000 calc(100% - var(--b)), #000 0 98%, #0000)} We could get clever and use a pseudo-element for the shape thats positioned behind the set of panels, but that introduces more complexity and fixed values than we ought to have. Instead, we can continue using CSS masks to get the perfect shape with a minimal amount of reusable code.Its not really the rounded top edges that are difficult to pull off, but the bottom portion that curves inwards instead of rounding in like the top. And even then, we already know the secret sauce: using CSS masks by combining gradients that reveal just the parts we want.We start by adding a border around the element excluding the bottom edge and applying a border-radius on the top-left and top-right corners..tab { --r: 40px; /* radius size */border: var(--r) solid #0000; / transparent black /border-bottom: 0;border-radius: calc(2 var(--r)) calc(2 var(--r)) 0 0;} Next, we add the first mask layer. We only want to show the padding area (i.e., the red area highlighted in Figure 10).mask: linear-gradient(#000 0 0) padding-box;Lets add two more gradients, both radial, to show those bottom curves.mask: radial-gradient(100% 100% at 0 0, #0000 98%, #000) 0 100% / var(--r) var(--r), radial-gradient(100% 100% at 100% 0, #0000 98%, #000) 100% 100% / var(--r) var(--r), linear-gradient(#000 0 0) padding-box;Here is how the full code comes together:.tab { --r: 40px; /* control the radius */border: var(--r) solid #0000;border-bottom: 0;border-radius: calc(2 var(--r)) calc(2 var(--r)) 0 0;mask:radial-gradient(100% 100% at 0 0, #0000 98%, #000) 0 100% / var(--r) var(--r),radial-gradient(100% 100% at 100% 0, #0000 98%, #000) 100% 100% / var(--r) var(--r),linear-gradient(#000 0 0) padding-box;mask-repeat: no-repeat;background: linear-gradient(60deg, #BD5532, #601848) border-box;} As usual, all it takes is one variable to control the shape. Lets zero-in on the border-radius declaration for a moment:border-radius: calc(2 * var(--r)) calc(2 * var(--r)) 0 0;Notice that the shapes rounded top edges are equal to two times the radius (--r) value. If youre wondering why we need a calculation here at all, its because we have a transparent border hanging out there, and we need to double the radius to account for it. The radius of the blue areas highlighted in Figure 13 is equal to 2 * R while the red area highlighted in the same figure is equal to 2 * R - R, or simply R.We can actually optimize the code so that we only need two gradients one linear and one radial instead of three. Ill drop that into the following demo for you to pick apart. Can you figure out how we were able to eliminate one of the gradients?Ill throw in two additional variations for you to investigate:These arent tabs at all but tooltips! We can absolutely use the exact same masking technique we used to create the tabs for these shapes. Notice how the curves that go inward are consistent in each shape, no matter if they are positioned on the left, right, or both.You can always find the code over at my online collection if you want to reference it.More CSS ShapesAt this point, weve seen the main tricks to create CSS shapes. You will rely on mask and gradients if you have curves and rounded parts or clip-path when there are no curves. It sounds simple but theres still more to learn, so I am going to provide a few more common shapes for you to explore.Instead of going into a detailed explanation of the shapes in this section, Im going to give you the recipes for how to make them and all of the ingredients you need to make it happen. In fact, I have written other articles that are directly related to everything we are about to cover and will link them up so that you have guides you can reference in your work.TrianglesA triangle is likely the first shape that you will ever need. Theyre used in lots of places, from play buttons for videos, to decorative icons in links, to active state indicators, to open/close toggles in accordions, to the list goes on.Creating a triangle shape is as simple as using a 3-point polygon in addition to defining the size:.triangle { width: 200px; aspect-ratio: 1; clip-path: polygon(50% 0, 100% 100%, 0 100%);}But we can get even further by adding more points to have border-only variations:We can cut all the corners or just specific ones. We can make circular cuts or sharp ones. We can even create an outline of the overall shape. Take a look at my online generator to play with the code, and check out my full article on the topic where I am detailing all the different cases.Cut-Out ShapesIn addition to cutting corners, we can also cut a shape out of a rectangle. They are also called inverted shapes.The technique is all about setting the CSS clip-path property with the shapes coordinates in the polygon() function. So, technically, this is something you already know, thanks to the examples weve looked at throughout this guide.I hope you see the pattern now: sometimes, were clipping an element or masking portions of it. The fact that we can sort of carve into things this way using polygon() coordinates and gradients opens up so many possibilities that would have required clever workarounds and super-specific code in years past.See my article How to Create a Section Divider Using CSS on the freeCodeCamp blog for a deep dive into the concepts, which weve also covered here quite extensively already in earlier sections.Floral ShapesWeve created circles. Weve made wave shapes. Lets combine those two ideas together to create floral shapes.These shapes are pretty cool on their own. But like a few of the other shapes weve covered, this one works extremely well with images. If you need something fancier than the typical box, then masking the edges can come off like a custom-framed photo.Here is a demo where I am using such shapes to create a fancy hover effect:See the Pen Fancy Pop Out hover effect! by Temani Afif.Theres a lot of math involved with this, specifically trigonometric functions. I have a two-part series that gets into the weeds if youre interested in that side of things:Creating Flower Shapes using CSS Mask & Trigonometric Functions (Frontend Masters)Creating Wavy Circles with Fancy Animations in CSS (Frontend Masters)As always, remember that my online collection is your Number One resource for all things related to CSS shapes. The math has already been worked out for your convenience, but you also have the references you need to understand how it works under the hood.ConclusionI hope you see CSS Shapes differently now as a result of reading this comprehensive guide. We covered a few shapes, but really, its hundreds upon hundreds of shapes because you see how flexible they are to configure into a slew of variations.At the end of the day, all of the shapes use some combination of different CSS concepts such as clipping, masking, composition, gradients, CSS variables, and so on. Not to mention a few hidden tricks like the one related to the polygon() function:It accepts points outside the [0% 100%] range.Switching axes is a solid approach for creating shape variations.The lines we establish can intersect.Its not that many things, right? We looked at each of these in great detail and then whipped through the shapes to demonstrate how the concepts come together. Its not so much about memorizing snippets than it is thoroughly understanding how CSS works and leveraging its features to produce any number of things, like shapes.Dont forget to bookmark my CSS Shape website and use it as a reference as well as a quick stop to get a specific shape you need for a project. I avoid re-inventing the wheel in my work, and the online collection is your wheel for snagging shapes made with pure CSS.Please also use it as inspiration for your own shape-shifting experiments. And post a comment if you think of a shape that would be a nice addition to the collection.ReferencesCSS Shapes: Polygon & Starburst (Verpex Blog)CSS Tricks To Master The clip-path Property (Verpex Blog)Fancy CSS Borders Using Masks (CSS-Tricks)How to Create Wavy Shapes & Patterns in CSS (CSS-Tricks)CSS Shapes: The Triangle (Verpex Blog)CSS Shapes: The Heart (Verpex Blog)CSS Responsive Multi-Line Ribbon Shapes, Part 1 (Smashing Magazine)CSS Responsive Multi-Line Ribbon Shapes, Part 2 (Smashing Magazine)CSS Shapes: The Ribbon (Verpex Blog)How to Create CSS Ribbon Shapes with a Single Element (SitePoint)Modern CSS Tooltips And Speech Bubbles, Part 1 (Smashing Magazine)Modern CSS Tooltips And Speech Bubbles, Part 2 (Smashing Magazine)Tricks to Cut Corners Using CSS Mask and Clip-Path PropertiesHow to Create a Section Divider Using CSS (freeCodeCamp Blog)Re-Creating The Pop-Out Hover Effect With Modern CSS (Part 1) (Smashing Magazine)Creating Flower Shapes using CSS Mask & Trigonometric Functions (Frontend Masters)Creating Wavy Circles with Fancy Animations in CSS (Frontend Masters)Mask Compositing: The Crash Course by Ana Tudor (CSS-Tricks)
    0 Σχόλια 0 Μοιράστηκε 342 Views
  • SMASHINGMAGAZINE.COM
    The Forensics Of React Server Components (RSCs)
    This article is a sponsored by Sentry.ioIn this article, were going to look deeply at React Server Components (RSCs). They are the latest innovation in Reacts ecosystem, leveraging both server-side and client-side rendering as well as streaming HTML to deliver content as fast as possible.We will get really nerdy to get a full understanding of how RFCs fit into the React picture, the level of control they offer over the rendering lifecycle of components, and what page loads look like with RFCs in place.But before we dive into all of that, I think its worth looking back at how React has rendered websites up until this point to set the context for why we need RFCs in the first place.The Early Days: React Client-Side RenderingThe first React apps were rendered on the client side, i.e., in the browser. As developers, we wrote apps with JavaScript classes as components and packaged everything up using bundlers, like Webpack, in a nicely compiled and tree-shaken heap of code ready to ship in a production environment.The HTML that returned from the server contained a few things, including:An HTML document with metadata in the <head> and a blank <div> in the <body> used as a hook to inject the app into the DOM;JavaScript resources containing Reacts core code and the actual code for the web app, which would generate the user interface and populate the app inside of the empty <div>.A web app under this process is only fully interactive once JavaScript has fully completed its operations. You can probably already see the tension here that comes with an improved developer experience (DX) that negatively impacts the user experience (UX).The truth is that there were (and are) pros and cons to CSR in React. Looking at the positives, web applications delivered smooth, quick transitions that reduced the overall time it took to load a page, thanks to reactive components that update with user interactions without triggering page refreshes. CSR lightens the server load and allows us to serve assets from speedy content delivery networks (CDNs) capable of delivering content to users from a server location geographically closer to the user for even more optimized page loads.There are also not-so-great consequences that come with CSR, most notably perhaps that components could fetch data independently, leading to waterfall network requests that dramatically slow things down. This may sound like a minor nuisance on the UX side of things, but the damage can actually be quite large on a human level. Eric Baileys Modern Health, frameworks, performance, and harm should be a cautionary tale for all CSR work.Other negative CSR consequences are not quite as severe but still lead to damage. For example, it used to be that an HTML document containing nothing but metadata and an empty <div> was illegible to search engine crawlers that never get the fully-rendered experience. While thats solved today, the SEO hit at the time was an anchor on company sites that rely on search engine traffic to generate revenue.The Shift: Server-Side Rendering (SSR)Something needed to change. CSR presented developers with a powerful new approach for constructing speedy, interactive interfaces, but users everywhere were inundated with blank screens and loading indicators to get there. The solution was to move the rendering experience from the client to the server. I know it sounds funny that we needed to improve something by going back to the way it was before.So, yes, React gained server-side rendering (SSR) capabilities. At one point, SSR was such a topic in the React community that it had a moment in the spotlight. The move to SSR brought significant changes to app development, specifically in how it influenced React behavior and how content could be delivered by way of servers instead of browsers.Addressing CSR LimitationsInstead of sending a blank HTML document with SSR, we rendered the initial HTML on the server and sent it to the browser. The browser was able to immediately start displaying the content without needing to show a loading indicator. This significantly improves the First Contentful Paint (FCP) performance metric in Web Vitals.Server-side rendering also fixed the SEO issues that came with CSR. Since the crawlers received the content of our websites directly, they were then able to index it right away. The data fetching that happens initially also takes place on the server, which is a plus because its closer to the data source and can eliminate fetch waterfalls if done properly.HydrationSSR has its own complexities. For React to make the static HTML received from the server interactive, it needs to hydrate it. Hydration is the process that happens when React reconstructs its Virtual Document Object Model (DOM) on the client side based on what was in the DOM of the initial HTML.Note: React maintains its own Virtual DOM because its faster to figure out updates on it instead of the actual DOM. It synchronizes the actual DOM with the Virtual DOM when it needs to update the UI but performs the diffing algorithm on the Virtual DOM.We now have two flavors of Reacts:A server-side flavor that knows how to render static HTML from our component tree,A client-side flavor that knows how to make the page interactive.Were still shipping React and code for the app to the browser because in order to hydrate the initial HTML React needs the same components on the client side that were used on the server. During hydration, React performs a process called reconciliation in which it compares the server-rendered DOM with the client-rendered DOM and tries to identify differences between the two. If there are differences between the two DOMs, React attempts to fix them by rehydrating the component tree and updating the component hierarchy to match the server-rendered structure. And if there are still inconsistencies that cannot be resolved, React will throw errors to indicate the problem. This problem is commonly known as a hydration error.SSR DrawbacksSSR is not a silver bullet solution that addresses CSR limitations. SSR comes with its own drawbacks. Since we moved the initial HTML rendering and data fetching to the server, those servers are now experiencing a much greater load than when we loaded everything on the client.Remember when I mentioned that SSR generally improves the FCP performance metric? That may be true, but the Time to First Byte (TTFB) performance metric took a negative hit with SSR. The browser literally has to wait for the server to fetch the data it needs, generate the initial HTML, and send the first byte. And while TTFB is not a Core Web Vital metric in itself, it influences the metrics. A negative TTFB leads to negative Core Web Vitals metrics.Another drawback of SSR is that the entire page is unresponsive until client-side React has finished hydrating it. Interactive elements cannot listen and react to user interactions before React hydrates them, i.e., React attaches the intended event listeners to them. The hydration process is typically fast, but the internet connection and hardware capabilities of the device in use can slow down rendering by a noticeable amount.The Present: A Hybrid ApproachSo far, we have covered two different flavors of React rendering: CSR and SSR. While the two were attempts to improve one another, we now get the best of both worlds, so to speak, as SSR has branched into three additional React flavors that offer a hybrid approach in hopes of reducing the limitations that come with CSR and SSR.Well look at the first two static site generation and incremental static regeneration before jumping into an entire discussion on React Server Components, the third flavor.Static Site Generation (SSG)Instead of regenerating the same HTML code on every request, we came up with SSG. This React flavor compiles and builds the entire app at build time, generating static (as in vanilla HTML and CSS) files that are, in turn, hosted on a speedy CDN.As you might suspect, this hybrid approach to rendering is a nice fit for smaller projects where the content doesnt change much, like a marketing site or a personal blog, as opposed to larger projects where content may change with user interactions, like an e-commerce site.SSG reduces the burden on the server while improving performance metrics related to TTFB because the server no longer has to perform heavy, expensive tasks for re-rendering the page.Incremental Static Regeneration (ISR)One SSG drawback is having to rebuild all of the apps code when a content change is needed. The content is set in stone being static and all and theres no way to change just one part of it without rebuilding the whole thing.The Next.js team created the second hybrid flavor of React that addresses the drawback of complete SSG rebuilds: incremental static regeneration (ISR). The name says a lot about the approach in that ISR only rebuilds whats needed instead of the entire thing. We generate the initial version of the page statically during build time but are also able to rebuild any page containing stale data after a user lands on it (i.e., the server request triggers the data check).From that point on, the server will serve new versions of that page statically in increments when needed. That makes ISR a hybrid approach that is neatly positioned between SSG and traditional SSR.At the same time, ISR does not address the stale content symptom, where users may visit a page before it has finished being generated. Unlike SSG, ISR needs an actual server to regenerate individual pages in response to a users browser making a server request. That means we lose the valuable ability to deploy ISR-based apps on a CDN for optimized asset delivery.The Future: React Server ComponentsUp until this point, weve juggled between CSR, SSR, SSG, and ISR approaches, where all make some sort of trade-off, negatively affecting performance, development complexity, and user experience. Newly introduced React Server Components (RSC) aim to address most of these drawbacks by allowing us the developer to choose the right rendering strategy for each individual React component.RSCs can significantly reduce the amount of JavaScript shipped to the client since we can selectively decide which ones to serve statically on the server and which render on the client side. Theres a lot more control and flexibility for striking the right balance for your particular project.Note: Its important to keep in mind that as we adopt more advanced architectures, like RSCs, monitoring solutions become invaluable. Sentry offers robust performance monitoring and error-tracking capabilities that help you keep an eye on the real-world performance of your RSC-powered application. Sentry also helps you gain insights into how your releases are performing and how stable they are, which is yet another crucial feature to have while migrating your existing applications to RSCs. Implementing Sentry in an RSC-enabled framework like Next.js is as easy as running a single terminal command.But what exactly is an RSC? Lets pick one apart to see how it works under the hood.The Anatomy of React Server ComponentsThis new approach introduces two types of rendering components: Server Components and Client Components. The differences between these two are not how they function but where they execute and the environments theyre designed for. At the time of this writing, the only way to use RSCs is through React frameworks. And at the moment, there are only three frameworks that support them: Next.js, Gatsby, and RedwoodJS.Server ComponentsServer Components are designed to be executed on the server, and their code is never shipped to the browser. The HTML output and any props they might be accepting are the only pieces that are served. This approach has multiple performance benefits and user experience enhancements:Server Components allow for large dependencies to remain on the server side.Imagine using a large library for a component. If youre executing the component on the client side, it means that youre also shipping the full library to the browser. With Server Components, youre only taking the static HTML output and avoiding having to ship any JavaScript to the browser. Server Components are truly static, and they remove the whole hydration step.Server Components are located much closer to the data sources e.g., databases or file systems they need to generate code.They also leverage the servers computational power to speed up compute-intensive rendering tasks and send only the generated results back to the client. They are also generated in a single pass, which avoids request waterfalls and HTTP round trips.Server Components safely keep sensitive data and logic away from the browser.Thats thanks to the fact that personal tokens and API keys are executed on a secure server rather than the client.The rendering results can be cached and reused between subsequent requests and even across different sessions.This significantly reduces rendering time, as well as the overall amount of data that is fetched for each request.This architecture also makes use of HTML streaming, which means the server defers generating HTML for specific components and instead renders a fallback element in their place while it works on sending back the generated HTML. Streaming Server Components wrap components in <Suspense> tags that provide a fallback value. The implementing framework uses the fallback initially but streams the newly generated content when its ready. Well talk more about streaming, but lets first look at Client Components and compare them to Server Components.Client ComponentsClient Components are the components we already know and love. Theyre executed on the client side. Because of this, Client Components are capable of handling user interactions and have access to the browser APIs like localStorage and geolocation.The term Client Component doesnt describe anything new; they merely are given the label to help distinguish the old CSR components from Server Components. Client Components are defined by a "use client" directive at the top of their files."use client"export default function LikeButton() { const likePost = () => { // ... } return ( <button onClick={likePost}>Like</button> )}In Next.js, all components are Server Components by default. Thats why we need to explicitly define our Client Components with "use client". Theres also a "use server" directive, but its used for Server Actions (which are RPC-like actions that invoked from the client, but executed on the server). You dont use it to define your Server Components.You might (rightfully) assume that Client Components are only rendered on the client, but Next.js renders Client Components on the server to generate the initial HTML. As a result, browsers can immediately start rendering them and then perform hydration later.The Relationship Between Server Components and Client ComponentsClient Components can only explicitly import other Client Components. In other words, were unable to import a Server Component into a Client Component because of re-rendering issues. But we can have Server Components in a Client Components subtree only passed through the children prop. Since Client Components live in the browser and they handle user interactions or define their own state, they get to re-render often. When a Client Component re-renders, so will its subtree. But if its subtree contains Server Components, how would they re-render? They dont live on the client side. Thats why the React team put that limitation in place.But hold on! We actually can import Server Components into Client Components. Its just not a direct one-to-one relationship because the Server Component will be converted into a Client Component. If youre using server APIs that you cant use in the browser, youll get an error; if not youll have a Server Component whose code gets leaked to the browser.This is an incredibly important nuance to keep in mind as you work with RSCs.The Rendering LifecycleHeres the order of operations that Next.js takes to stream contents:The app router matches the pages URL to a Server Component, builds the component tree, and instructs the server-side React to render that Server Component and all of its children components.During render, React generates an RSC Payload. The RSC Payload informs Next.js about the page and what to expect in return, as well as what to fall back to during a <Suspense>.If React encounters a suspended component, it pauses rendering that subtree and uses the suspended components fallback value.When React loops through the last static component, Next.js prepares the generated HTML and the RSC Payload before streaming it back to the client through one or multiple chunks.The client-side React then uses the instructions it has for the RSC Payload and client-side components to render the UI. It also hydrates each Client Component as they load.The server streams in the suspended Server Components as they become available as an RSC Payload. Children of Client Components are also hydrated at this time if the suspended component contains any.We will look at the RSC rendering lifecycle from the browsers perspective momentarily. For now, the following figure illustrates the outlined steps we covered.Well see this operation flow from the browsers perspective in just a bit.RSC PayloadThe RSC payload is a special data format that the server generates as it renders the component tree, and it includes the following:The rendered HTML,Placeholders where the Client Components should be rendered,References to the Client Components JavaScript files,Instructions on which JavaScript files it should invoke,Any props passed from a Server Component to a Client Component.Theres no reason to worry much about the RSC payload, but its worth understanding what exactly the RSC payload contains. Lets examine an example (truncated for brevity) from a demo app I created:1:HL["/_next/static/media/c9a5bc6a7c948fb0-s.p.woff2","font",{"crossOrigin":"","type":"font/woff2"}]2:HL["/_next/static/css/app/layout.css?v=1711137019097","style"]0:"$L3"4:HL["/_next/static/css/app/page.css?v=1711137019097","style"]5:I["(app-pages-browser)/./node_modules/next/dist/client/components/app-router.js",["app-pages-internals","static/chunks/app-pages-internals.js"],""]8:"$Sreact.suspense"a:I["(app-pages-browser)/./node_modules/next/dist/client/components/layout-router.js",["app-pages-internals","static/chunks/app-pages-internals.js"],""]b:I["(app-pages-browser)/./node_modules/next/dist/client/components/render-from-template-context.js",["app-pages-internals","static/chunks/app-pages-internals.js"],""]d:I["(app-pages-browser)/./src/app/global-error.jsx",["app/global-error","static/chunks/app/global-error.js"],""]f:I["(app-pages-browser)/./src/components/clearCart.js",["app/page","static/chunks/app/page.js"],"ClearCart"]7:["$","main",null,{"className":"page_main__GlU4n","children":[["$","$Lf",null,{}],["$","$8",null,{"fallback":["$","p",null,{"children":" loading products..."}],"children":"$L10"}]]}]c:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}]...9:["$","p",null,{"children":[" ",3]}]11:I["(app-pages-browser)/./src/components/addToCart.js",["app/page","static/chunks/app/page.js"],"AddToCart"]10:["$","ul",null,{"children":[["$","li","1",{"children":["Gloves"," - $",20,["$...To find this code in the demo app, open your browsers developer tools at the Elements tab and look at the <script> tags at the bottom of the page. Theyll contain lines like:self.__next_f.push([1,"PAYLOAD_STRING_HERE"]).Every line from the snippet above is an individual RSC payload. You can see that each line starts with a number or a letter, followed by a colon, and then an array thats sometimes prefixed with letters. We wont get into too deep in detail as to what they mean, but in general:HL payloads are called hints and link to specific resources like CSS and fonts.I payloads are called modules, and they invoke specific scripts. This is how Client Components are being loaded as well. If the Client Component is part of the main bundle, itll execute. If its not (meaning its lazy-loaded), a fetcher script is added to the main bundle that fetches the components CSS and JavaScript files when it needs to be rendered. Theres going to be an I payload sent from the server that invokes the fetcher script when needed."$" payloads are DOM definitions generated for a certain Server Component. They are usually accompanied by actual static HTML streamed from the server. Thats what happens when a suspended component becomes ready to be rendered: the server generates its static HTML and RSC Payload and then streams both to the browser.StreamingStreaming allows us to progressively render the UI from the server. With RSCs, each component is capable of fetching its own data. Some components are fully static and ready to be sent immediately to the client, while others require more work before loading. Based on this, Next.js splits that work into multiple chunks and streams them to the browser as they become ready. So, when a user visits a page, the server invokes all Server Components, generates the initial HTML for the page (i.e., the page shell), replaces the suspended components contents with their fallbacks, and streams all of that through one or multiple chunks back to the client.The server returns a Transfer-Encoding: chunked header that lets the browser know to expect streaming HTML. This prepares the browser for receiving multiple chunks of the document, rendering them as it receives them. We can actually see the header when opening Developer Tools at the Network tab. Trigger a refresh and click on the document request.We can also debug the way Next.js sends the chunks in a terminal with the curl command:curl -D - --raw localhost:3000 > chunked-response.txtYou probably see the pattern. For each chunk, the server responds with the chunks size before sending the chunks contents. Looking at the output, we can see that the server streamed the entire page in 16 different chunks. At the end, the server sends back a zero-sized chunk, indicating the end of the stream.The first chunk starts with the <!DOCTYPE html> declaration. The second-to-last chunk, meanwhile, contains the closing </body> and </html> tags. So, we can see that the server streams the entire document from top to bottom, then pauses to wait for the suspended components, and finally, at the end, closes the body and HTML before it stops streaming.Even though the server hasnt completely finished streaming the document, the browsers fault tolerance features allow it to draw and invoke whatever it has at the moment without waiting for the closing </body> and </html> tags.Suspending ComponentsWe learned from the render lifecycle that when a page is visited, Next.js matches the RSC component for that page and asks React to render its subtree in HTML. When React stumbles upon a suspended component (i.e., async function component), it grabs its fallback value from the <Suspense> component (or the loading.js file if its a Next.js route), renders that instead, then continues loading the other components. Meanwhile, the RSC invokes the async component in the background, which is streamed later as it finishes loading.At this point, Next.js has returned a full page of static HTML that includes either the components themselves (rendered in static HTML) or their fallback values (if theyre suspended). It takes the static HTML and RSC payload and streams them back to the browser through one or multiple chunks.As the suspended components finish loading, React generates HTML recursively while looking for other nested <Suspense> boundaries, generates their RSC payloads and then lets Next.js stream the HTML and RSC Payload back to the browser as new chunks. When the browser receives the new chunks, it has the HTML and RSC payload it needs and is ready to replace the fallback element from the DOM with the newly-streamed HTML. And so on.In Figures 7 and 8, notice how the fallback elements have a unique ID in the form of B:0, B:1, and so on, while the actual components have a similar ID in a similar form: S:0 and S:1, and so on.Along with the first chunk that contains a suspended components HTML, the server also ships an $RC function (i.e., completeBoundary from Reacts source code) that knows how to find the B:0 fallback element in the DOM and replace it with the S:0 template it received from the server. Thats the replacer function that lets us see the component contents when they arrive in the browser.The entire page eventually finishes loading, chunk by chunk.Lazy-Loading ComponentsIf a suspended Server Component contains a lazy-loaded Client Component, Next.js will also send an RSC payload chunk containing instructions on how to fetch and load the lazy-loaded components code. This represents a significant performance improvement because the page load isnt dragged out by JavaScript, which might not even be loaded during that session.At the time Im writing this, the dynamic method to lazy-load a Client Component in a Server Component in Next.js does not work as you might expect. To effectively lazy-load a Client Component, put it in a wrapper Client Component that uses the dynamic method itself to lazy-load the actual Client Component. The wrapper will be turned into a script that fetches and loads the Client Components JavaScript and CSS files at the time theyre needed.TL;DRI know thats a lot of plates spinning and pieces moving around at various times. What it boils down to, however, is that a page visit triggers Next.js to render as much HTML as it can, using the fallback values for any suspended components, and then sends that to the browser. Meanwhile, Next.js triggers the suspended async components and gets them formatted in HTML and contained in RSC Payloads that are streamed to the browser, one by one, along with an $RC script that knows how to swap things out.The Page Load TimelineBy now, we should have a solid understanding of how RSCs work, how Next.js handles their rendering, and how all the pieces fit together. In this section, well zoom in on what exactly happens when we visit an RSC page in the browser.The Initial LoadAs we mentioned in the TL;DR section above, when visiting a page, Next.js will render the initial HTML minus the suspended component and stream it to the browser as part of the first streaming chunks.To see everything that happens during the page load, well visit the Performance tab in Chrome DevTools and click on the reload button to reload the page and capture a profile. Heres what that looks like:When we zoom in at the very beginning, we can see the first Parse HTML span. Thats the server streaming the first chunks of the document to the browser. The browser has just received the initial HTML, which contains the page shell and a few links to resources like fonts, CSS files, and JavaScript. The browser starts to invoke the scripts.After some time, we start to see the pages first frames appear, along with the initial JavaScript scripts being loaded and hydration taking place. If you look at the frame closely, youll see that the whole page shell is rendered, and loading components are used in the place where there are suspended Server Components. You might notice that this takes place around 800ms, while the browser started to get the first HTML at 100ms. During those 700ms, the browser is continuously receiving chunks from the server.Bear in mind that this is a Next.js demo app running locally in development mode, so its going to be slower than when its running in production mode.The Suspended ComponentFast forward few seconds and we see another Parse HTML span in the page load timeline, but this one it indicates that a suspended Server Component finished loading and is being streamed to the browser.We can also see that a lazy-loaded Client Component is discovered at the same time, and it contains CSS and JavaScript files that need to be fetched. These files werent part of the initial bundle because the component isnt needed until later on; the code is split into their own files.This way of code-splitting certainly improves the performance of the initial page load. It also makes sure that the Client Components code is shipped only if its needed. If the Server Component (which acts as the Client Components parent component) throws an error, then the Client Component does not load. It doesnt make sense to load all of its code before we know whether it will load or not.Figure 12 shows the DOMContentLoaded event is reported at the end of the page load timeline. And, just before that, we can see that the localhost HTTP request comes to an end. That means the server has likely sent the last zero-sized chunk, indicating to the client that the data is fully transferred and that the streaming communication can be closed.The End ResultThe main localhost HTTP request took around five seconds, but thanks to streaming, we began seeing page contents load much earlier than that. If this was a traditional SSR setup, we would likely be staring at a blank screen for those five seconds before anything arrives. On the other hand, if this was a traditional CSR setup, we would likely have shipped a lot more of JavaScript and put a heavy burden on both the browser and network.This way, however, the app was fully interactive in those five seconds. We were able to navigate between pages and interact with Client Components that have loaded as part of the initial main bundle. This is a pure win from a user experience standpoint.ConclusionRSCs mark a significant evolution in the React ecosystem. They leverage the strengths of server-side and client-side rendering while embracing HTML streaming to speed up content delivery. This approach not only addresses the SEO and loading time issues we experience with CSR but also improves SSR by reducing server load, thus enhancing performance.Ive refactored the same RSC app I shared earlier so that it uses the Next.js Page router with SSR. The improvements in RSCs are significant:Looking at these two reports I pulled from Sentry, we can see that streaming allows the page to start loading its resources before the actual request finishes. This significantly improves the Web Vitals metrics, which we see when comparing the two reports.The conclusion: Users enjoy faster, more reactive interfaces with an architecture that relies on RSCs.The RSC architecture introduces two new component types: Server Components and Client Components. This division helps React and the frameworks that rely on it like Next.js streamline content delivery while maintaining interactivity.However, this setup also introduces new challenges in areas like state management, authentication, and component architecture. Exploring those challenges is a great topic for another blog post!Despite these challenges, the benefits of RSCs present a compelling case for their adoption. We definitely will see guides published on how to address RSCs challenges as they mature, but, in my opinion, they already look like the future of rendering practices in modern web development.
    0 Σχόλια 0 Μοιράστηκε 368 Views
  • SMASHINGMAGAZINE.COM
    How To Run UX Research Without Access To Users
    UX research without users isnt research. We can shape design ideas with bias, assumptions, guesstimates, and even synthetic users, but its anything but UX research. Yet some of us might find ourselves in situations where we literally dont have access to users because of legal constraints, high costs, or perhaps users just dont exist yet. What do we do then?Luckily, there are some workarounds that help us better understand pain points and issues that users might have when using our products. This holds true even when stakeholders cant give us time or resources to run actual research, or strict NDAs or privacy regulations prevent us from speaking to users.Lets explore how we can make UX research work when there is no or only limited access to users and what we can do to make a strong case for UX research.This article is part of our ongoing series on design patterns. Its also an upcoming part of the 10h-video library on Smart Interface Design Patterns and the upcoming live UX training as well. Use code BIRDIE to save 15% off.Find Colleagues Who Are The Closest To Your CustomersWhen you dont have access to users, I always try to establish a connection with colleagues who are the closest to our customers. Connect with people in the organization who speak with customers regularly, especially people in sales, customer success, support, and QA. Ultimately, you could convey your questions indirectly via them.As Paul Adams noted, there has never been more overlap between designers and salespeople than today. Since many products are subscription-based, sales teams need to maintain relationships with customers over time. This requires a profound understanding of user needs and meeting these needs well over time to keep retention and increase loyalty.Thats where research comes in and thats exactly where the overlap between UX and sales comes in. In fact, its not surprising to find UX researchers sitting within marketing teams under the disguise of Customer Success teams, so whenever you can befriend colleagues from sales and Customer Success teams.Gaining Insights Without Direct Access To UsersIf you cant get users to come to you, perhaps you could go where they are. You could ask to silently observe and shadow them at their workplace. You could listen in to customer calls and interview call center staff to uncover pain points that users have when interacting with your product. Analytics, CRM reports, and call center logs are also a great opportunity to gain valuable insights, and Google Trends can help you find product-related search queries.To learn more about potential issues and user frustrations, also turn to search logs, Jira backlogs, and support tickets. Study reviews, discussions, and comments for your or your competitors product, and take a look at TrustPilot and app stores to map key themes and user sentiment. Or get active yourself and recruit users via tools like UserTesting, Maze, or UserInterviews.These techniques wont always work, but they can help you get off the ground. Beware of drawing big conclusions from very little research, though. You need multiple sources to reduce the impact of assumptions and biases at a very minimum, you need five users to discover patterns.Making A Strong Case For UX ResearchIronically, as H Locke noted, the stakeholders who cant give you time or resources to talk to users often are the first to demand evidence to support your design work. Tap into it and explain what you need. Research doesnt have to be time-consuming or expensive; ask for a small but steady commitment to gather evidence. Explain that you dont need much to get started: 5 users 30 minutes once a month might already be enough to make a positive change.Sometimes, the reason why companies are reluctant to grant access to users is simply the lack of trust. They dont want to disturb relationships with big clients, which are carefully maintained by the customer success team. They might feel that research is merely a technical detail that clients shouldnt be bothered with.Typically, if you work in B2B or enterprise, you wont have direct access to users. This might be due to strict NDAs or privacy regulations, or perhaps the user group is very difficult to recruit (e.g., lawyers or doctors).Show that you care about that relationship. Show the value that your work brings. Explain that design without research is merely guesswork and that designing without enough research is inherently flawed.Once your impact becomes visible, it will be so much easier to gain access to users that seemed almost impossible initially.Key TakeawaysAsk for reasons for no access to users: there might be none.Find colleagues who are the closest to your customers.Make friends with sales, customer success, support, QA.Convey your questions indirectly via your colleagues.If you cant get users to come to you, go where they are.Ask to observe or shadow customers at their workplace.Listen in to customer calls and interview call center staff.Gather insights from search logs, Jira backlog, and support tickets.Map key themes and user sentiment on TrustPilot, AppStore, etc.Recruit users via UserTesting, Maze, UserInterviews, etc.Ask for small but steady commitments: 5 users 30 mins, 1 month.Avoid ad-hoc research: set up regular check-ins and timelines.Useful ResourcesThe End Of Navel Gazing, by Paul AdamsUX Research Cheat Sheet, by Susan FarrellOvercoming Limited Access To Users in UX Research, by Debbie LevittWhat Can You Do When You Have No Access To Users?, by H LockeUX Research When You Cant Talk To Users, by Chris MyhillHow To Conduct UX Research Without Users, by Mariia KasymUser Research When You Cant Talk to Your Users, by Jon PetersonMeet Smart Interface Design PatternsIf you are interested in similar insights around UX, take a look at Smart Interface Design Patterns, our 10h-video course with 100s of practical examples from real-life projects with a live UX training later this year. Everything from mega-dropdowns to complex enterprise tables with 5 new segments added every year. Jump to a free preview.Meet Smart Interface Design Patterns, our video course on interface design & UX.Jump to the video course100 design patterns & real-life examples.10h-video course + live UX training. Free preview.
    0 Σχόλια 0 Μοιράστηκε 362 Views
  • SMASHINGMAGAZINE.COM
    How To Harness Mouse Interaction Data For Practical Machine Learning Solutions
    Mouse data is a subcategory of interaction data, a broad family of data about users generated as the immediate result of human interaction with computers. Its siblings from the same data family include logs of key presses or page visits. Businesses commonly rely on interaction data, including the mouse, to gather insights about their target audience. Unlike data that you could obtain more explicitly, lets say via a survey, the advantage of interaction data is that it describes the actual behavior of actual people.Collecting interaction data is completely unobtrusive since it can be obtained even as users go about their daily lives as usual, meaning it is a quantitative data source that scales very well. Once you start collecting it continuously as part of regular operation, you do not even need to do anything, and youll still have fresh, up-to-date data about users at your fingertips potentially from your entire user base, without them even needing to know about it. Having data on specific users means that you can cater to their needs more accurately.Of course, mouse data has its limitations. It simply cannot be obtained from people using touchscreens or those who rely on assistive tech. But if anything, that should not discourage us from using mouse data. It just illustrates that we should look for alternative methods that cater to the different ways that people interact with software. Among these, the mouse just happens to be very common.When using the mouse, the mouse pointer is the de facto conduit for the users intent in a visual user interface. The mouse pointer is basically an extension of your arm that lets you interact with things in a virtual space that you cannot directly touch. Because of this, mouse interactions tend to be data-intensive. Even the simple mouse action of moving the pointer to an area and clicking it can yield a significant amount of data.Mouse data is granular, even when compared with other sources of interaction data, such as the history of visited pages. However, with machine learning, it is possible to investigate jumbles of complicated data and uncover a variety of complex behavioral patterns. It can reveal more about the user holding the mouse without needing to provide any more information explicitly than normal. For starters, let us venture into what kind of information can be obtained by processing mouse interaction data.What Are Mouse Dynamics?Mouse dynamics refer to the features that can be extracted from raw mouse data to describe the users operation of a mouse. Mouse data by itself corresponds with the simple mechanics of mouse controls. It consists of mouse events: the X and Y coordinates of the cursor on the screen, mouse button presses, and scrolling, each dated with a timestamp. Despite the innate simplicity of the mouse events themselves, the mouse dynamics using them as building blocks can capture users behavior from a diverse and emergently complex variety of perspectives. If you are concerned about user privacy, as well you should be, mouse dynamics are also your friend. For the calculation of mouse dynamics to work, raw mouse data does not need to inherently contain any details about the actual meaning of the interaction. Without the context of what the user saw as they moved their pointer around and clicked, the data is quite safe and harmless. Some examples of mouse dynamics include measuring the velocity and the acceleration at which the mouse cursor is moving or describing how direct or jittery the mouse trajectories are. Another example is whether the user presses and lets go of the primary mouse button quickly or whether there is a longer pause before they release their press. Four categories of over twenty base measures can be identified: temporal, spatial, spatial-temporal, and performance. Features do not need to be just metrics either, with other approaches using a time series of mouse events. Temporal mouse dynamics:Movement duration: The time between two clicks;Response time: The time it takes to click something in response to a stimulus (e.g., from the moment when a page is displayed);Initiation time: The time it takes from an initial stimulus for the cursor to start moving;Pause time: The time measuring the cursors period of idleness.Spatial mouse dynamics:Distance: Length of the path traversed on the screen;Straightness: The ratio between the traversed path and the optimal direct path;Path deviation: Perpendicular distance of the traversed path from the optimal path;Path crossing: Counted instances of the traversed and optimal path intersecting;Jitter: The ratio of the traversed path length to its smoothed version;Angle: The direction of movement;Flips: Counted instances of change in direction;Curvature: Change in angle over distance;Inflection points: Counted instances of change in curvature.Spatial-temporal mouse dynamics:Velocity: Change of distance over time;Acceleration: Change of velocity over time;Jerk: Change of acceleration over time;Snap: Change in jerk over time;Angular velocity: Change in angle over time.Performance mouse dynamics:Clicks: The number of mouse button events pressing down or up;Hold time: Time between mouse down and up events;Click error: Length of the distance between the clicked point and the correct user task solution;Time to click: Time between the hover event on the clicked point and the click event;Scroll: Distance scrolled on the screen.Note: For detailed coverage of varied mouse dynamics and their extraction, see the paper Is mouse dynamics information credible for user behavior research? An empirical investigation.The spatial angular measures cited above are a good example of how the calculation of specific mouse dynamics can work. The direction angle of the movements between points A and B is the angle between the vector AB and the horizontal X axis. Then, the curvature angle in a sequence of points ABC is the angle between vectors AB and BC. Curvature distance can be defined as the ratio of the distance between points A and C and the perpendicular distance between point B and line AC. (Definitions sourced from the paper An efficient user verification system via mouse movements.)Even individual features (e.g., mouse velocity by itself) can be delved into deeper. For example, on pages with a lot of scrolling, horizontal mouse velocity along the X-axis may be more indicative of something capturing the users attention than velocity calculated from direct point-to-point (Euclidean) distance in the screen's 2D space. The maximum velocity may be a good indicator of anomalies, such as user frustration, while the mean or median may tell you more about the user as a person. From Data To Tangible ValueThe introduction of mouse dynamics above, of course, is an oversimplification for illustrative purposes. Just by looking at the physical and geometrical measurements of users mouse trajectories, you cannot yet tell much about the user. That is the job of the machine learning algorithm. Even features that may seem intuitively useful to you as a human (see examples cited at the end of the previous section) can prove to be of low or zero value for a machine-learning algorithm.Meanwhile, a deceptively generic or simplistic feature may turn out unexpectedly quite useful. This is why it is important to couple broad feature generation with a good feature selection method, narrowing the dimensionality of the model down to the mouse dynamics that help you achieve good accuracy without overfitting. Some feature selection techniques are embedded directly into machine learning methods (e.g., LASSO, decision trees) while others can be used as a preliminary filter (e.g., ranking features by significance assessed via a statistical test).As we can see, there is a sequential process to transforming mouse data into mouse dynamics, into a well-tuned machine learning model to field its predictions, and into an applicable solution that generates value for you and your organization. This can be visualized as the pipeline below.Machine Learning Applications Of Mouse DynamicsTo set the stage, we must realize that companies arent really known for letting go of their competitive advantage by divulging the ins and outs of what they do with the data available to them. This is especially true when it comes to tech giants with access to potentially some of the most interesting datasets on the planet (including mouse interaction data), such as Google, Amazon, Apple, Meta, or Microsoft. Still, recording mouse data is known to be a common practice. With a bit of grit, you can find some striking examples of the use of mouse dynamics, not to mention a surprising versatility in techniques. For instance, have you ever visited an e-commerce site just to see it recommend something specific to you, such as a gendered line of cosmetics all the while, you never submitted any information about your sex or gender anywhere explicitly?Mouse data transcends its obvious applications, as is replaying the users session and highlighting which visual elements people interact with. A surprising amount of internal and external factors that shape our behavior are reflected in data as subtle indicators and can thus be predicted.Lets take a look at some further applications. Starting some simple categorization of users.Example 1: Biological Sex PredictionFor businesses, knowing users well allows them to provide accurate recommendations and personalization in all sorts of ways, opening the gates for higher customer satisfaction, retention, and average order value. By itself, the prediction of user characteristics, such as gender, isnt anything new. The reason for basing it on mouse dynamics, however, is that mouse data is generated virtually by the truckload. With that, you will have enough data to start making accurate predictions very early.If you waited for higher-level interactions, such as which products the user visited or what they typed into the search bar, by the time youd have enough data, the user may have already placed an order or, even worse, left unsatisfied.The selection of the machine learning algorithm matters for a problem. In one published scientific paper, six various models have been compared for the prediction of biological gender using mouse dynamics. The dataset for the development and evaluation of the models provides mouse dynamics from participants moving the cursor in a broad range of trajectory lengths and directions. Among the evaluated models Logistic regression, Support vector machine, Random forest, XGBoost, CatBoost, and LightGBM CatBoost achieved the best F1 score. Putting people into boxes is far from everything that can be done with mouse dynamics, though. Lets take a look at a potentially more exciting use case trying to predict the future.Example 2: Purchase PredictionAnother e-commerce application predicts whether the user has the intent to make a purchase or even whether they are likely to become a repeat customer. Utilizing such predictions, businesses can adapt personalized sales and marketing tactics to be more effective and efficient, for example, by catering more to likely purchasers to increase their value or the opposite, which is investigating unlikely purchasers to find ways to turn them into likely ones.Interestingly, a paper dedicated to the prediction of repeat customership reports that when a gradient boosting model is validated on data obtained from a completely different online store than where it was trained and tuned, it still achieves respectable performance in the prediction of repeat purchases with a combination of mouse dynamics and other interaction and non-interaction features.It is plausible that though machine-learning applications tend to be highly domain-specific, some models could be used as a starting seed, carried over between domains, especially while still waiting for user data to materialize.Additional ExamplesApplications of mouse dynamics are a lot more far-reaching than just the domain of e-commerce. To give you some ideas, here are a couple of other variables that have been predicted with mouse dynamics:The truthfulness of answers given in a questionnaire.Source: Detecting faking-good response style in personality questionnaires with four choice alternativesWhether the user is experiencing confusion with the interface of a web application.Source: YesElf: Personalized Onboarding for Web ApplicationsThe arm dexterity of cerebral palsy patients.Source: Using cursor measures to investigate the effects of impairment severity on cursor control for youths with cerebral palsyPersonal identities for biometric authentication.Source: User Authentication Based on Mouse Dynamics Using Deep Neural Networks: A Comprehensive StudyDistinguishing bots from real users.Source: Bot or Human? A Behavior-Based Online Bot Detection SystemPersonality traits to psychologically profile users.Source: Measuring personality from keyboard and mouse useThe Mouse-Shaped CaveatWhen you think about mouse dynamics in-depth, some questions will invariably start to emerge. The user isnt the only variable that could determine what mouse data looks like. What about the mouse itself?Many brands and models are available for purchase to people worldwide. Their technical specifications deviate in attributes such as resolution (measured in DPI or, more accurately, CPI), weight, polling rate, and tracking speed. Some mouse devices have multiple profile settings that can be swapped between at will. For instance, the common CPI of an office mouse is around 800-1,600, while a gaming mouse can go to extremes, from 100 to 42,000. To complicate things further, the operating system has its own mouse settings, such as sensitivity and acceleration. Even the surface beneath the mouse can differ in its friction and optical properties. Can we be sure that mouse data is reliable, given that basically everyone potentially works under different mouse conditions?For the sake of argument, lets say that as a part of a web app youre developing, you implement biometric authentication with mouse dynamics as a security feature. You sell it by telling customers that this form of auth is capable of catching attackers who try to meddle in a tab that somebody in the customers organization left open on an unlocked computer. Recognizing the intruder, the app can sign the user out of the account and trigger a warning sent to the company. Kicking out the real authorized user and sounding the alarm just because somebody bought a new mouse would not be a good look. Recalibration to the new mouse would also produce friction. Some people like to change their mouse sensitivity or use different computers quite often, so frequent calibration could potentially present a critical flaw.We found that up until now, there was barely anything written about whether or how mouse configuration affects mouse dynamics. By mouse configuration, we refer to all properties of the environment that could impact mouse behavior, including both hardware and software.From the authors of papers and articles about mouse dynamics, there is barely a mention of mouse devices and settings involved in development and testing. This could be seen as concerning. Though hypothetically, there might not be an actual reason for concern, that is exactly the problem. There was just not even enough information to make a judgment on whether mouse configuration matters or not. This question is what drove the study conducted by UXtweak Research (as covered in the peer-reviewed paper in Computer Standards & Interfaces). The quick answer? Mouse configuration does detrimentally affect mouse dynamics. How?It may cause the majority of mouse dynamics values to change in a statistically significant way between different mouse configurations.It may lower the prediction performance of a machine learning model if it was trained on a different set of mouse configurations than it was tested on.It is not automatically guaranteed that prediction based on mouse dynamics will work equally well for people on different devices. Even the same person making the exact same mouse movements does not necessarily produce the same mouse dynamics if you give them a different mouse or change their settings.We cannot say for certain how big an impact mouse configuration can have in a specific instance. For the problem that you are trying to solve (specific domain, machine learning model, audience), the impact could be big, or it could be negligible. But to be sure, it should definitely receive attention. After all, even a deceptively small percentage of improvement in prediction performance can translate to thousands of satisfied users.Tackling Mouse Device VariabilityKnowledge is half the battle, and so it is also with the realization that mouse configuration is not something that can be just ignored when working with mouse dynamics. You can perform tests to evaluate the size of the effect that mouse configuration has on your models performance. If, in some configurations, the number of false positives and false negatives rises above levels that you are willing to tolerate, you can start looking for potential solutions by tweaking your prediction model.Because of the potential variability in real-world conditions, differences between mouse configurations can be seen as a concern. Of course, if you can rely on controlled conditions (such as in apps only accessible via standardized kiosks or company-issued computers and mouse devices where all system mouse settings are locked), you can avoid the concern altogether. Given that the training dataset uses the same mouse configuration as the configuration used in production, that is. Otherwise, that may be something new for you to optimize.Some predicted variables can be observed repeatedly from the same user (e.g., emotional state or intent to make a purchase). In the case of these variables, to mitigate the problem of different users utilizing different mouse configurations, it would be possible to build personalized models trained and tuned on the data from the individual user and the mouse configurations they normally use. You also could try to normalize mouse dynamics by adjusting them to the specific users normal mouse behavior. The challenge is how to accurately establish normality. Note that this still doesnt address situations when the user changes their mouse or settings.Where To Take It From HereSo, we arrive at the point where we discuss the next steps for anyone who cant wait to apply mouse dynamics to machine learning purposes of their own. For web-based solutions, you can start by looking at MouseEvents in JavaScript, which is how youll obtain the elementary mouse data necessary.Mouse events will serve as the base for calculating mouse dynamics and the features in your model. Pick any that you think could be relevant to the problem you are trying to solve (see our list above, but dont be afraid to design your own features). Dont forget that you can also combine mouse dynamics with domain and application-specific features.Problem awareness is key to designing the right solutions. Is your prediction problem within-subject or between-subject? A classification or a regression? Should you use the same model for your whole audience, or could it be more effective to tailor separate models to the specifics of different user segments?For example, the mouse behavior of freshly registered users may differ from that of regular users, so you may want to divide them up. From there, you can consider the suitable machine/deep learning algorithm. For binary classification, a Support vector machine, Logistic regression, or a Random Forest could do the job. To delve into more complex patterns, you may wish to reach for a Neural network.Of course, the best way to uncover which machine/deep learning algorithm works best for your problem is to experiment. Most importantly, dont give up if you dont succeed at first. You may need to go back to the drawing board a few times to reconsider your feature engineering, expand your dataset, validate your data, or tune the hyperparameters.ConclusionWith the ongoing trend of more and more online traffic coming from mobile devices, some futurist voices in tech might have you believe that the computer mouse is dead. Nevertheless, those voices have been greatly exaggerated. One look at statistics reveals that while mobile devices are excessively popular, the desktop computer and the computer mouse are not going anywhere anytime soon. Classifying users as either mobile or desktop is a false dichotomy. Some people prefer the desktop computer for tasks that call for exact controls while interacting with complex information. Working, trading, shopping, or managing finances all, coincidentally, are tasks with a good amount of importance in peoples lives.To wrap things up, mouse data can be a powerful information source for improving digital products and services and getting yourself a headway against the competition. Advantageously, data for mouse dynamics does not need to involve anything sensitive or in breach of the users privacy. Even without identifying the person, machine learning with mouse dynamics can shine a light on the user, letting you serve them more proper personalization and recommendations, even when other data is sparse. Other uses include biometrics and analytics. Do not underestimate the impact of differences in mouse devices and settings, and you may arrive at useful and innovative mouse-dynamics-driven solutions to help you stand out.
    0 Σχόλια 0 Μοιράστηκε 367 Views
  • DESIGN-MILK.COM
    A Partially Constructed Commercial Building Transformed Into a Vibrant Public Preschool
    Circular transformed a partially constructed commercial building into a vibrant public preschool, part of a city initiative to provide modern school facilities where they are most needed. The Corona 3K Center is located in one of the fastest-growing yet under-served areas in Corona, a neighborhood in the Queens borough of New York City. The area boasts a large population of newly arrived families with young children, where quality childcare is in high demand and suitable options are all-too limited.The Roosevelt Avenue corner site is on a busy commercial corridor fronted by an elevated subway train and vehicular traffic, which presented several challenges for the architects. They were tasked with an overhaul of the existing structure, which was originally supposed to include a ground-floor retail space and an office on the upper level. This building was actively under construction, says Jordan Parnass, principal at Circular. A big part of our responsibility was to quickly identify how we could change what the landlord had planned to do and turn it into a school.A series of bright panels enlivens the re-designed facade, chosen to represent a progression along the color spectrum and provide some respite from the surrounding gray streetscape. The same shades are repeated as stripes in the playroom, and again as accents in the individual classrooms.The footprint was already built to the lot line and couldnt be changed, so an interior layout was devised that allows for seven classrooms over two floors. By incorporating Passive House principles, the Circular team achieved considerable enhancements to sustainability. A mechanical system, for example, preconditions, dehumidifies, and filters fresh air. Triple-pane windows mitigate noise, while the wall and roof insulation boosts thermal performance. Every element ensures that children are comfortable in the education setting year-round.Spaces within meet a range of stringent health, durability. and functionality requirements, but the interiors are still inviting, with color playing a central role. Cheery primary tints are a staple in learning environments, but they can be overstimulating. At the center, sophisticated, low-saturation neutrals are a base. Custom geometric wall tiles are paired with natural wood to create warmth. A continuous trip of tackboards serves as linear galleries. Showcasing student artwork in the hallways, they are placed at an eye level perfect for toddlers and their parents.Each classroom is identifiable by signature hues like red, orange, or yellow, found on doors, frames, accent floor tiles, and millwork. This color coding is ideal for preliterate youngsters, because it allows them to easily find a particular spot without signage or symbols. This is a space for education, and it is appropriate for children and adults, Parnass notes. Theres an underlying sense of playfulness throughout, and its that essence that we wanted to celebrate.Photography by Frank Oudeman.
    0 Σχόλια 0 Μοιράστηκε 258 Views
  • DESIGN-MILK.COM
    Elegance Is Encore in the New Connexion Collection From 808: Studio
    If you could sit on a painting, would you? YuoNing Chien presents the Connexion Collection for 808: Studio. The Milan-based designer focuses on playful incarnations of graphic design and minimalism with the beauty of small, regular, and repetitive connections on full display. This makes them easy on the eyes satisfying our inclination for symmetry.Our fascination with the unique languages and reasons behind each framing system is the concept of the collection, a painting that you can sit on, Chien says. The simplicity and harmony of the interaction between the base and seat is understated, yet feels secure. Theres an unadorned quality to the form, which speaks to its clarity and confidence a visibly sturdy shape with a beautiful handmade cushion atop to heighten and adorn the seat.Intuitive MaterialityThe construction is simple, yet incredibly strong. Half-lap joints create a super secure grid with small divots for the cushion to rest perfectly within the setting. The structure is made of solid oak, which adds enough weight to the piece without it becoming overly cumbersome in construction. The lap joints also provide for intuitive assembly and disassembly, without the need for any hardware or tools.In an era of overconsumption and materialism, the allure of something that is made simply, well, and beautifully, by thoughtful people, can be overwhelming at times. The Connexion Collection aims to honor those concepts through a graphic, gridded solution.Warp + WeftFabric construction techniques used for millennia inform the language seen here in the interaction between the cushion and stool. The gridded base seems to continue seamlessly into the cushion, almost forming a stitch-like junction between the two forms. This translates beautifully throughout the stool, from the cushion fabric to the base construction.The grid created by the base is cleverly replicated in the form language of the cushion fabric. The cloth, a Chinese handwoven ramie, is sourced from the master artisans of Chongqing. This handmade broadcloth nods to the ecological significance of hand weaving in Chinese culture, celebrating the fabrics unique blend of softness and strength. This specific linen has a bit of texture, yet is very durable and will last for years to come.The Collection comes in three different sizes, Small, Medium, and Large, with a selection of hand-dyed cushion colors. This custom hand-dyeing process ensures that each hue remains true and regular, while also preserving traditional techniques still used within the local community.For more information on the Connexion Collection, visit yuoning.com or email hi808studio@gmail.com.Photography by Agota Lukyte.
    0 Σχόλια 0 Μοιράστηκε 236 Views
  • DESIGN-MILK.COM
    Pro-Ject Makes Coordinating Audio With Decor a Simply Colorful Experience
    Heres something most self-identifying audiophiles wont willingly admit: aesthetics plays an important part in decision-making when looking to add speakers, turntables, amplifiers, and other components to a home stereo system. Good looking gear has become a vibe all over again, but specifically vintage-style components from an era characterized by designs intended to blend into home decor. Thankfully, the home audio and turntable specialists at Pro-Ject have no qualms about considering the importance of color and design as evidenced by their Colourful Audio System line.Anyone who has done even a tiny bit of research about turntables has probably seen Pro-Jects Debut Carbon EVO at one time or another. Its the brands top seller, making it an ideal choice for the centerpiece of an analog-focused sound system.But the allure of the Colourful Audio System is evident in its name. Where many audio brands sell complementary components separately, Pro-Ject has done something so obvious its perplexing more brands have not already followed suit. Instead of prepackaging systems by size, amplification, or application, the all-in-one Colourful Audio System is color-coordinated across 5 satin painted finishes Golden Yellow, Steel Blue, Fir Green, White, and Black alongside an organic Walnut finish. In doing so, Pro-Ject has eliminated the guesswork associated with picking out the right components and the deliberation of how it all looks within its intended space.Pro-Ject pairs the turntable with their own MaiA S3, a micro amplifier equipped to handle up to 8 different input devices, stream from connected mobile devices, and power a pair of Speaker Box 5 S2 2-way monitor speakers. Optional speaker stands are also available.Only the MaiA S3 amplifier is left untouched by color, but is also small enough in size not to distract from the colorful impact of turntable and speakers.Everything from special rubber feet for optimal isolation from speaker vibrations to high quality cables are included to accommodate easy listening immediately after unpacking and connecting the 4-piece system. The Colourful Audio Systems 1,799.00 price tag may denotes this isnt a budget solution, but instead an investment in something beautiful.To explore all the options and colorways, visit project-audio.com.
    0 Σχόλια 0 Μοιράστηκε 232 Views
  • UXDESIGN.CC
    Simple recall testing for B2B UX
    Ive tried a simple recall method with cashiers to determine if it could be a useful and cheaper alternative for B2B UX testing.Continue reading on UX Collective
    0 Σχόλια 0 Μοιράστηκε 235 Views
  • UXDESIGN.CC
    Design has a granularity issue
    Why we need to move towards a new design philosophy & practice.Continue reading on UX Collective
    0 Σχόλια 0 Μοιράστηκε 225 Views
  • UXDESIGN.CC
    The future is up for grabs when anyone can make designs
    How AI generates design and what it means for creators.Continue reading on UX Collective
    0 Σχόλια 0 Μοιράστηκε 234 Views