<?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 Ibon on Medium]]></title>
        <description><![CDATA[Stories by Ibon on Medium]]></description>
        <link>https://medium.com/@mazesym?source=rss-0bb85ddadff5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MWwAMQIQQpIbFjNdfH2iUw.png</url>
            <title>Stories by Ibon on Medium</title>
            <link>https://medium.com/@mazesym?source=rss-0bb85ddadff5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:27:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mazesym/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[Understanding in the Age of Black-Box AI]]></title>
            <link>https://medium.com/@mazesym/understanding-in-the-age-of-black-box-ai-9c64446f1599?source=rss-0bb85ddadff5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c64446f1599</guid>
            <category><![CDATA[webgpu]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[mnist]]></category>
            <dc:creator><![CDATA[Ibon]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 12:52:48 GMT</pubDate>
            <atom:updated>2026-02-01T12:52:48.579Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZIgOzK-lo2w9l7Tr_ZixLw.png" /><figcaption>Sample prediction errors</figcaption></figure><h3>Training MNIST From Scratch in TypeScript + WebGPU</h3><p>TL;DR try it here: <a href="https://hyperandroid.github.io/MNIST/">https://hyperandroid.github.io/MNIST/</a></p><p>Over the past months, I’ve watched LLMs catch up to tasks I once thought were uniquely human.</p><p>They’ve become invaluable for making sense of my own thoughts. They have an unbelievable ability to put into words what I couldn’t articulate myself. Fragments, intuitions, half-formed ideas… somehow, they write them down with clarity.</p><p>It feels like magic. And it will more as time goes by.</p><p>But then I realized something uncomfortable: I understood nothing about how they worked. Nor how they trained. Nor how they reasoned. Nor why they failed.</p><p>I was using tools I couldn’t see inside.</p><p>And that felt asymmetrical.</p><h3>When Knowledge Becomes Free, Understanding Becomes Everything</h3><p>We are entering an era where knowledge and software have an amortized cost of zero.</p><p>Tutorials are everywhere.<br>We live in the era of software on demand.<br>Entire systems can be scaffolded in seconds.</p><p>But if you don’t build the intuition yourself, the tools will become more like magic over time.</p><p>And eventually, your tools may even replace you.</p><p>Fortunately, I don’t define myself by my coding skills. But one of my traits is a hacker mindset: to understand systems from the ground up.</p><p>And so I decided to start from fundamentals.</p><h3>A Simple Project With a Serious Goal</h3><p>I didn’t start by trying to build an LLM. I started with something older. Smaller. An MLP. Multilayer perceptrons date back to the 1950s. They are not glamorous. They are not state of the art. But they are the foundation.</p><p>So I trained MNIST without using any ML framework. No PyTorch. No TensorFlow. No libraries.</p><p>Just TypeScript, WebGPU, and first principles.</p><h3>What “From Scratch” Actually Means</h3><p>This project involved rebuilding the entire foundation tier of a deep learning system:</p><ul><li>A minimal 2D tensor implementation</li><li>Matrix operations (matmul, add, reductions…)</li><li>Layers and activations</li><li>A custom autograd engine. Relying on the forward pass</li><li>Backpropagation and gradient flow</li><li>Stochastic Gradient Descent (no momentum, lazy boy)</li><li>Training + evaluation loops</li><li>WebGPU compute pipelines for every operation. Every tensor operation runs through WebGPU, no CPU fallback.</li></ul><h3>Autograd: The Graph You Don’t See in Frameworks</h3><p>Frameworks make automatic differentiation feel effortless. Under the hood, the idea is simple:</p><p>During the forward pass, every operation is tracked.</p><p>Each tensor records:</p><ul><li>what produced it</li><li>what inputs were involved</li><li>how to compute its gradient</li></ul><p>This builds a differentiation graph dynamically.</p><p>Then when .backward() is called, gradients flow backward through that graph, applying the chain rule step by step. The concept is elegant. Implementing it correctly is not. It is a hacky, unoptimized implementation that just does the job.</p><p>Needless to say gradient flow was one of the hardest parts of this entire project.</p><h3>WebGPU: Training Neural Networks in the Browser</h3><p>The most exciting part of this work was using WebGPU as the compute backend.</p><p>All tensor operations are implemented as WGSL compute shaders:</p><ul><li>matrix multiplication with tiled shared memory</li><li>reduction kernels with parallel workgroup accumulation</li><li>GPU-native softmax and cross-entropy with numerical stability</li><li>scoped WebGPU buffers for transient results.</li></ul><p>The result is something that still feels surreal:</p><p>A neural network training entirely inside the browser, on the GPU, with no ML libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tuzjzb4fxa0OTsH2loXTRQ.png" /><figcaption>Trained model testing hand written digits.</figcaption></figure><h3>The Model: As Simple As It Gets</h3><p>The architecture is intentionally minimal with an old-school perceptron technology:</p><pre>Sequence[ Dense(784 -&gt; 128), ReLU, Dense(128 -&gt;10) ]</pre><p>In code:</p><pre>// tm = TensorManager<br>// kernelRegistry = registry of compute piplelines. <br><br>this.model = new Sequential(<br>  new Linear(tm, kernelRegistry, {<br>    name: &quot;first&quot;,<br>    inputFeatures: MNISTDatasource.imageSize,<br>    outputFeatures: 128,<br>    useBias: true,<br>    initializer<br>  }),<br>  new ReLU(tm, kernelRegistry, &quot;ReLU1&quot;),<br>  new Linear(tm, kernelRegistry, {<br>    name: &quot;second&quot;,<br>    inputFeatures: 128,<br>    outputFeatures: 10,<br>    useBias: true,<br>    initializer<br>  }),<br>);</pre><h3>Training Loop: Forward, Loss, Backward, Step</h3><p>At its core, training is always the same:</p><pre>for (let epoch = 0; epoch &lt; epochs; epoch++) {<br>  for (const batch of dataloader) {<br>    // Forward pass<br>    const logits = model.forward(batch.images);<br>    // Loss computation<br>    const loss = softmaxCrossEntropy(logits, batch.labels);<br>    // Backward pass<br>    loss.backward();<br>    // Optimizer step<br>    optimizer.step();<br>    optimizer.zeroGrad();<br>  }<br>}</pre><p>Frameworks hide this machinery. Building it myself forced me to confront every moving part.</p><h3>Results</h3><p>Despite its simplicity, the model reaches: 97+% test accuracy</p><p>Training setup:</p><ul><li>15 epochs</li><li>batch size 32</li><li>vanilla SGD (no momentum)</li><li>raw MNIST data. Preprocess to normalize images and onehot labels.</li></ul><p>On a 14” MacBook Pro M3 Max (30 GPU cores, 36 GB RAM) full training completes in: under 8 minutes. With batch size 64, around 4 minutes.</p><p>For a scratch-built framework running in-browser, this was deeply satisfying.</p><p>What I Built Is Naive — And That’s the Point</p><p>This system is not production-ready. It is unoptimized. Limited to 2D tensors. Missing many features real frameworks have.</p><p>But it trains. It learns. And I know exactly why.</p><p>With a model of the form:</p><pre>Sequence [ <br>    Dense(768–512), ReLU, Dropout(.5),<br>    Dense(512–256), ReLU, Dropout(.25),<br>    Dense(256–128), ReLU,<br>    Dense(128–10)<br>]</pre><p>test accuracy is 98.5+%. Training times are more or less the same.</p><h3>Acknowledgment</h3><p>Big thanks to TiniTorch, which inspired this work.</p><p>This project is essentially a TypeScript + WebGPU implementation of its Foundation Tier: <a href="https://mlsysbook.ai/tinytorch/tiers/foundation.html">https://mlsysbook.ai/tinytorch/tiers/foundation.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c64446f1599" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Warped Gradients in Jetpack Compose]]></title>
            <link>https://medium.com/@mazesym/warped-gradients-in-jetpack-compose-6049ae0ebf2d?source=rss-0bb85ddadff5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6049ae0ebf2d</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[ui-design]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Ibon]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 14:32:23 GMT</pubDate>
            <atom:updated>2026-01-05T14:32:23.714Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTMuo35eB60lzFBSLYpUbg.png" /><figcaption>Polar, Spiral, Wavy and Hatched gradients with different presets.</figcaption></figure><p>If you like gradients but you’re tired of seeing the same linear and radial backgrounds everywhere, this post is for you. We are going to build four gradient families in Jetpack Compose using AGSL namely spiral polar wavy and hatch. They are customizable. Animation is optional..</p><p>The key move is simple. Keep using a regular LinearGradient to handle colors, stops, bounds, and TileMode. Feed that gradient into an AGSL RuntimeShader as a uniform shader. Then, instead of inventing a new interpolation system, just transform the sampling space. Your shader computes a single parameter t from normalized coordinates, and samples the existing gradient with gradient.eval(float2(t, 0.0)). Different transformations, same palette pipeline.</p><p>You will end up with a small set of reusable brushes that animate cleanly, scale to any size, and let designers keep working with familiar gradient inputs. The collage above shows the four families and a few presets for each, all driven by the same underlying ramp.</p><h3>Requirements</h3><ul><li>Android API 33 or higher</li><li>AGSL RuntimeShader</li><li>Jetpack Compose UI graphics</li><li>A 1D LinearGradient ramp used as a shader uniform</li></ul><h3>Why write new gradients</h3><p>Compose already gives you Brush.linearGradient and friends, so why add more? Because it lets you build looks that bitmaps struggle with and it stays theme friendly.</p><p>Writing a gradient from scratch is not hard in the academic sense. It is hard in the production sense. Stops are fiddly. Edge behavior matters. Banding appears at the worst time. You also have to decide what happens outside the ramp range. Clamp. Repeat. Mirror. Decal. You end up reimplementing parts Compose already solved.</p><p>That is why this approach leans on a simple yet solid building block. LinearGradient already solves the color side. It already understands stops. It already tiles. Instead of rebuilding that machinery, we keep it as a palette ramp and focus on what actually creates the new looks: the mapping from screen space to sampling space. We do not write new gradients. We write new ways to read an existing one.</p><h3>The trick: keep a palette, bend the space</h3><p>Think of a 1D LinearGradient as a palette you can sample.</p><ul><li>Normalize your fragment coordinates to uv in 0 to 1</li><li>Warp uv into a single scalar t</li><li>Remap sampling coordinates and note that for some effects you sample with float2(t, 0.0) and for others you feed a 2D coordinate into the same 1D ramp. For a strictly 1D ramp, we keep one axis constant. In a few shaders we reuse the same ramp by feeding a 2D coordinate, where one axis still ends up constant or effectively irrelevant for the chosen orientation.</li></ul><p>In AGSL that core loop can be almost embarrassingly small:</p><pre>// defined LinearGradient used as color ramp.<br>uniform shader gradient;<br>// composable size.<br>uniform float2 iResolution;<br><br>float warp(float2 uv) {<br>  float t = 0.0;<br>  // apply a coordinate transform.<br>  return t;<br>}<br><br>half4 main(float2 fragCoord) {<br>    float2 uv = fragCoord / iResolution;  // uv -&gt; 0..1<br>    float t = warp(uv);<br>    return gradient.eval(float2(t, 0.0));    // returns a half4 color.<br>}</pre><p>A deliberate decision sits inside that simplicity. I do not clamp t. I rely on TileMode in the underlying LinearGradient to clamp, repeat, mirror or decal. That keeps each warp focused. It also keeps behavior consistent across all new gradient types.</p><h3>Make the hard parts someone else’s problem: SamplerFactory</h3><p>The core of the reuse is a shared sampler. It creates a normalized 1D LinearGradient that acts as the palette ramp. Every custom gradient shader consumes that palette through a uniform shader.</p><p>Bounds are handled here too. The warp produces a normalized t. The sampler maps it into the configured domain. TileMode then decides what happens beyond it.</p><p>This is the surface that matters</p><pre>object SamplerFactory {<br><br>  fun createSampler(<br>      orientation: GradientSamplerOrientation,<br>      bounds: GradientDomain = 0f to 1f,<br>      colors: GradientColors,<br>      tileMode: Shader.TileMode,<br>      hardColorTransition: Boolean = false,<br>  ): GradientSampler<br><br>  ...<br>}</pre><p>A note on hardColorTransition. This is not a shader trick. It is a palette trick. It duplicates colors and color stops so the ramp returns discrete palette colors instead of blended ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*7iGTkbFFfl9yni2BSOMZvw.png" /><figcaption>Spiral gradient: hardColorTransition left = true, right = false.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*uiBIwt1shiwA3yqoe704OQ.png" /><figcaption>Polar gradient: hardColorTransition left = true, right = false.</figcaption></figure><p>Orientation applies only to the ramp construction</p><ul><li>Horizontal ramp<br> LinearGradient(0f, 0f, 1f, 0f, colors, stops, tileMode)</li><li>Vertical ramp<br> LinearGradient(0f, 0f, 0f, 1f, colors, stops, tileMode)</li></ul><p>The rest of the system stays unchanged. Warps do not care how the palette was built. They only output t.</p><p>Keep in mind that the ramp is normalized, but bounds remap the sampling domain, so you can zoom into a range or stretch it without touching the shader. You will find this in the wavy and hatched gradient presets.</p><h3>Wiring: feeding a shader uniform into RuntimeShader</h3><p>On the AGSL side each gradient type is a separate shader string. That keeps the code readable. It also keeps parameters honest. Spiral and polar need a center. Wavy and hatch do not.</p><p>A typical AGSL header looks like this</p><pre>uniform shader gradient;<br>uniform float2 iResolution;<br>uniform float iTime;<br>uniform float iTimeScale;<br>// Plus type specific uniforms such as iCenter or iDirection</pre><p>On the Kotlin side the pattern is stable</p><ul><li>Build the palette ramp with SamplerFactory.</li><li>Create a RuntimeShader from the AGSL string.</li><li>Bind the palette into the shader as the gradient uniform by calling shader.setInputShader(&quot;gradient&quot;, samplerShader).</li><li>Update uniforms as needed.</li><li>Keep aspect ratio. Spiral and Polar need it for correctness, while wavy and hatch use it as a stylistic consistency choice, typically on x only.</li></ul><p>Keep the plumbing short. Your future self will thank you.</p><h3>Drawing and animation in Compose</h3><p>I keep the brush remembered and update time during drawing. That avoids recreating shaders per frame. It also keeps recomposition pressure low. This will trigger just the draw phase.</p><p>This is the WavyGradient composable, with animation source code:</p><pre>@Composable<br>fun WavyGradient(<br>    modifier: Modifier = Modifier,<br>    animate: Boolean = true,<br>    direction: GradientSamplerOrientation = GradientSamplerOrientation.Horizontal,<br>    amplitude: Float = .1f,<br>    period: Float = 4f,<br>    timeScale: Float = .2f,<br>    angle: Float = 0f,<br><br>    hardSampler: Boolean = false,<br>    bounds: GradientDomain = 0f to 1f,<br>    colors: List&lt;Color&gt; = samplePalettes[0],<br>    tileMode: Shader.TileMode = Shader.TileMode.CLAMP,<br>    onClick: () -&gt; Unit = {}<br>) {<br><br>    // 1. create color ramp. A plain LinearGradient.<br>    <br>    // 2. create a unique brush for the lifetime of this composable.<br><br>    // 3. set brush parameters on recomposition.<br>    //    this will set custom shader uniforms, including the color ramp.<br><br>    // 4. animate continuously<br>    PausableAnimatedTime(isPaused = !animate) { time -&gt;<br>        Box(<br>            modifier = modifier<br>                .fillMaxSize()<br>                .clickable {<br>                    onClick()<br>                }<br>                .drawWithCache {<br><br>                    // render composable background using the Brush.<br>                    // no recomposition, just repaint.<br>                    onDrawBehind {<br>                        // animate brush.<br>                        brush.setTime(time)<br>                        drawRect(brush)<br>                    }<br>                }<br>        )<br>    }<br>}</pre><p>Time can come from an infinite transition, a physics animation, or user input. The only requirement is that it ends up in a float uniform.</p><h3>Gradient Shaders and Brush</h3><p>All new gradient types share in common at least time control, the LinearGradient color ramp and, a resolution uniform. Other parameters are just to customize the visual appearance of each specific gradient.</p><p>To give a grasp of its simplicity, <a href="https://github.com/hyperandroid/compose_animation/blob/main/app/src/main/java/com/spellington/animationtest/gradient/brush/WavyGradientBrush.kt#L102">this is the complete AGSL </a><a href="https://github.com/hyperandroid/compose_animation/blob/main/app/src/main/java/com/spellington/animationtest/gradient/brush/WavyGradientBrush.kt#L102">WavyGradientShader source code</a>. It bends the uv space based on a sin function multiplied by some amplitude. We first normalize the uv space, so the iAmplitude uniform should be something in the range -1..1. The iPeriod uniform tells how many waves per horizontal or vertical scan. To spice it up, we can pass a rotation angle by setting the iAngle uniform.</p><p><a href="https://github.com/hyperandroid/compose_animation/blob/main/app/src/main/java/com/spellington/animationtest/gradient/WavyGradient.kt#L86">And the associated brush source code is here</a>.</p><p>The pattern repeats on every new gradient type. Just change the Brush initialisation parameters, and the custom shader source.</p><h4>Pitfalls and notes</h4><p>A few things are worth mentioning</p><ul><li>TileMode is doing the work outside the LinearGradient 0 to 1 definition domain. Choose it deliberately. MIRROR can hide seams. REPEAT can emphasize periodicity. CLAMP can flatten extremes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*BRyGkqJ2hQ-rVW0HeMlypA.png" /><figcaption>Hatch gradient with different Shader.TileMode sets and hardColorTransition.</figcaption></figure><ul><li>Aspect ratio correction is not optional for spiral and polar. If it is skipped, the math is correct and the image is wrong.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*F5MPczXozfLaHBB4jMnOfA.png" /><figcaption>Aspect ratio: left = wrong, right = correct</figcaption></figure><ul><li>Hard transitions can intensify aliasing. That is expected. It is also sometimes the point.</li><li>Shaders are per pixel. Trig is not free. Use these brushes where they add value. Backgrounds and hero surfaces are ideal.</li></ul><p>When debugging a new warp, visualize t first. Render it as grayscale. When it looks right, plug the palette back in.</p><h3>Wrap up</h3><p>The pattern is stable</p><ul><li>Build a reusable 1D palette ramp with LinearGradient</li><li>Keep colors, stops, bounds, and TileMode in that ramp</li><li>In AGSL, warp normalized coordinates into a scalar t</li><li>Sample the palette with gradient.eval(float2(t, 0.0))</li></ul><p>Once you have that, new gradient families become small coordinate functions. That is the win. You bend space. You do not reinvent LinearGradients.</p><p>If you want to explore the full implementation, including the SamplerFactory and the preset sets, the code is <a href="https://github.com/hyperandroid/compose_animation/">available in the project repository and is published under MIT</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6049ae0ebf2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Old-school marquee effect in Compose]]></title>
            <link>https://medium.com/@mazesym/old-school-marquee-effect-in-compose-68bb14116521?source=rss-0bb85ddadff5------2</link>
            <guid isPermaLink="false">https://medium.com/p/68bb14116521</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ibon]]></dc:creator>
            <pubDate>Thu, 04 Dec 2025 18:55:39 GMT</pubDate>
            <atom:updated>2026-01-07T15:42:08.930Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*aa5IVaIeAcHbB8tj47t7cQ.gif" /><figcaption>Old school marquee effect demo.</figcaption></figure><p>While a simple idea, its implementation can be quite tricky. We’d need knowledge of how to create new Modifier s, measure @Composable widgets with unbounded constraints, supply efficient custom drawing, etc.</p><p>Let’s solve these problems one by one.</p><h4>1 — Create a new Modifier Type</h4><p>For the sake of simplicity, we’d be creating a new modifier type so that it can be invoked on any Composable like:</p><pre>Text(<br>  modifier = Modifier.marquee(duration = 3000),<br>  text = &quot;some text to marquee...&quot;<br>)</pre><p>For this purpose, we need to create the following simple class structure relying on a Node-based modifier model. We removed constructor parameters for simplicity:</p><pre>// create a new modifier type<br>fun Modifier.marquee() = <br>  this.then(MarqueeModifierElement())<br><br>// using a class extending ModifierNodeElement<br>internal data class MarqueeModifierElement(...): <br>  ModifierNodeElement&lt;MarqueeModifierNode&gt;() { ... }<br><br>// Our Modifier.Node implementation<br>internal class MarqueeModifierNode():<br>    Modifier.Node(),<br>    LayoutModifierNode,<br>    DrawModifierNode<br>{ ... }</pre><h4>2 — Measure a Composable unbounded.</h4><p>When designing in Compose, composables get their position and size during the Layout phase by, among other things, solving a set of constraints.</p><p>The marquee, on the other hand, must measure itself unbounded from its parent’s horizontal constraint so that it can slide left-to-right or right-to-left in a pixel-perfect fashion.</p><p>This is achieved by overriding MeasureScope.measure:</p><pre>override fun MeasureScope.measure(<br>        measurable: Measurable,<br>        constraints: Constraints<br>): MeasureResult {<br><br>    // unbounded horizontally<br>    val childConstraints = constraints.copy(maxWidth = Constraints.Infinity)<br>    val placeable = measurable.measure(childConstraints)<br><br>    val newContainerWidth = constraints.constrainWidth(placeable.width)<br>    val newContentsWidth = placeable.width<br><br>    val sizeChanged = newContainerWidth != containerWidth<br>            || newContentsWidth != contentsWidth<br><br><br>    // The width used for layout, constrained by the parent<br>    containerWidth = newContainerWidth<br><br>    // The full width of the composable we want to scroll<br>    contentsWidth = newContentsWidth<br><br>    // start animation coroutine if possible<br>    if (isAttached &amp;&amp; sizeChanged) {<br>        restartMarquee()<br>    }<br><br>    return layout(containerWidth, placeable.height) {<br>        placeable.placeWithLayer(<br>            x = 0,<br>            y = 0<br>        )<br>    }<br>}</pre><h4>3 — Custom draw</h4><p>Our example Marquee modifier will scroll the composable’s contents in an infinite loop. To avoid triggering recomposition, we just translate the current DrawScope contents. If we just did this, it’d make the composable’s content leak into other composable’s visual space as seen in the image, where the text should never leak to the red area:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*_x21JHAsjl-cjzwjXhY0OQ.png" /><figcaption>Row { Separator(), Text(…) }</figcaption></figure><p>to avoid this, we just clip the DrawScope like:</p><pre>override fun ContentDrawScope.draw() {<br>  // clip defaults to the whole height of the Text container.<br>  clipRect(left = 0f, right = containerWidth.toFloat()) {<br>    // offset goes from containerWidth to -contentsWidth<br>    // which effectively makes the text slide right to left until <br>    // it completely disappears.<br>    translate(left = offset.value) {<br>      this@draw.drawContent()<br>    }<br>  }<br>}</pre><p>Giving us the correct expected visual result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*GYrptB9Mc6-YSigB1_wdkw.png" /></figure><h4>4 — Trigger redraw</h4><p>This is the simplest part of it all. We keep an Animatable in the modifier Node and update it in a coroutine. Each update invalidates the draw pass, causing only the drawing stage to run again, not full recomposition of the parent composable. This code is triggered whenever we need to restart the marquee, either when the marquee is updated or when the Node is measured.</p><pre>private fun restartMarquee() {<br>    val previousJob = animationJob<br>    previousJob?.cancel()<br><br>    animationJob = coroutineScope.launch {<br><br>        previousJob?.join()<br><br>        withContext(object : MotionDurationScale {<br>            override val scaleFactor: Float<br>                get() = 1f<br>        }) {<br><br>            offset.snapTo(containerWidth.toFloat())<br>            offset.animateTo(<br>                -contentsWidth.toFloat(),<br>                infiniteRepeatable(<br>                    animation = tween(<br>                        durationMillis = this@MarqueeModifierNode.duration,<br>                        easing = LinearEasing<br>                    ),<br>                )<br>            )<br><br>        }<br>    }<br>}</pre><h4>5 — Clarifying things</h4><p>Redrawing happens automatically because Animatable updates a snapshot state value, and the Node’s draw() function reads it. This creates a dependency that tells Compose:</p><blockquote>Whenever the animation updates the state, invalidate the draw layer.</blockquote><p>Compose then efficiently re-runs only the draw pass, not recomposition or layout.</p><h4>Conclusion</h4><p>We had to dig into some internals just to slide a node’s content inside its parent’s bounds. At a high level, Compose abstracts most of this complexity away, but even a simple sliding text effect exposes how layout, drawing, and snapshot state interact under the hood.</p><p>This is an intentionally minimal implementation of a marquee. It always scrolls , it does not handle RTL or accessibility to name a few. Still, it demonstrates the core building blocks of a marquee.</p><p><a href="https://github.com/hyperandroid/compose_animation/">Get the code here</a>.</p><blockquote>For the record, Compose includes a <a href="https://developer.android.com/develop/ui/compose/text/style-text#apply-marquee">basicMarquee</a> modifier, which this example is based on.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68bb14116521" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>