<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 17 Nov 2026 00:37:08 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Build and Train a GLM-5.3-Flash Model From Scratch with Python ]]>
                </title>
                <description>
                    <![CDATA[ GLM-5.3-Flash combines linear and sparse attention, a mixture-of-experts design, and manifold constrained hyperconnections. A scaled-down version with 25 million parameters can be built in Python and  ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-and-train-a-glm-53-flash-model-from-scratch-with-python/</link>
                <guid isPermaLink="false">6af88630044134836d5c4f7d</guid>
                
                    <category>
                        <![CDATA[ llm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Sat, 14 Nov 2026 16:02:56 +0000</pubDate>
                <media:content url="https://i.ytimg.com/vi/-gfgQfw2g_E/maxresdefault.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>GLM-5.3-Flash combines linear and sparse attention, a mixture-of-experts design, and manifold constrained hyperconnections. A scaled-down version with 25 million parameters can be built in Python and trained on a standard CPU.</p>
<p>We just published a course on the freeCodeCamp.org YouTube channel that will teach you how to build and train a multimodal language model from scratch, covering both pre-training and post-training. The course is from @vukrosic, and all of the code, slides, and experiments are in the GitHub repository linked in the video description.</p>
<p>The model uses a 260-token byte-level vocabulary, a 192-token context, and a small vision encoder that turns a 32 by 32 image into 16 tokens.</p>
<p>In this course, you will learn:</p>
<ul>
<li><strong>Tokenization &amp; Embeddings</strong><br>Why a small model needs a small byte-level vocabulary and how weight tying shares one matrix between the embeddings and the output head.</li>
<li><strong>Linear &amp; Sparse Attention</strong><br>How linear attention keeps a fixed-size memory of recent tokens while every fourth layer uses sparse attention with an indexer to find distant details.</li>
<li><strong>Mixture of Experts</strong><br>How tokens are routed to a few chosen experts plus a shared expert that learns information common to every token.</li>
<li><strong>Adding Vision</strong><br>How images are split into patches with 2D RoPE and merged into image tokens so the model can recognize digits.</li>
<li><strong>Pre-Training Experiments</strong><br>How data diversity, interleaving, and curriculums affect learning, including how interleaving helps prevent catastrophic forgetting.</li>
<li><strong>Reinforcement Learning</strong><br>How to design reward functions, compute advantages as in GRPO, update only the final layers, and test group size, temperature, and seeds.</li>
</ul>
<p>After reinforcement learning, the model goes from solving 0 of 24 Python tasks to 16 of 24.</p>
<p>Watch the full course on the <a href="https://youtu.be/-gfgQfw2g_E">freeCodeCamp.org YouTube channel</a> (44-minute watch).</p>
<div class="embed-wrapper"><iframe width="560" height="315" src="https://www.youtube.com/embed/-gfgQfw2g_E" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Speed Up CI in the Age of AI-Written Code ]]>
                </title>
                <description>
                    <![CDATA[ Coding agents now write code faster than most CI pipelines can check it. In April 2026, GitHub COO Kyle Daigle said that his platform was handling 275 million commits a week, on pace for 14 billion in ]]>
                </description>
                <link>https://www.freecodecamp.org/news/speed-up-ci-in-the-age-of-ai-written-code/</link>
                <guid isPermaLink="false">6af7069e2028f50f83240511</guid>
                
                    <category>
                        <![CDATA[ GitHub ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ci ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ci-cd ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ agentic AI ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Manish Shivanandhan ]]>
                </dc:creator>
                <pubDate>Fri, 13 Nov 2026 12:46:22 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5fc16e412cae9c5b190b6cdd/d1609f3b-9a5c-402f-b04d-30349dd2e10e.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Coding agents now write code faster than most <a href="https://www.freecodecamp.org/news/learn-continuous-integration-delivery-and-deployment/">CI pipelines</a> can check it. In April 2026, <a href="https://x.com/kdaigle/status/2040164759836778878">GitHub COO Kyle Daigle said</a> that his platform was handling 275 million commits a week, on pace for 14 billion in the year, up from about 1 billion in 2025. In the same post, he put GitHub Actions at 2.1 billion minutes in a single week, up from 500 million a week in 2023.</p>
<p>That second figure shows where all those commits end up: in CI. A 15-minute pipeline is tolerable if a dev pushes a few times a day. When an agent opens ten PRs in an afternoon, that pipeline turns into a queue. You wait for results, agents wait to retry, and the time saved writing code is lost checking it.</p>
<p>Most of that delay comes from a few causes, and each has a known fix. You can speed up CI in five ways:</p>
<ol>
<li>measure where the time goes</li>
<li>cache what you can reuse</li>
<li>run jobs on faster hardware</li>
<li>split tests across parallel jobs</li>
<li>skip work that doesn't need to run.</li>
</ol>
<p>In this article, we'll walk through each fix in order. You’ll learn how to find the slowest steps in your GitHub Actions workflows, cache dependencies and Docker layers with stable keys, and move heavy jobs to faster runners. You’ll also see how to shard tests across a matrix of parallel jobs, and how to skip unneeded work with path filters, affected-only tests, and concurrency groups.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><a href="#heading-measure-first-then-optimize">Measure First, Then Optimize</a></li>
<li><a href="#heading-cache-dependencies-and-build-layers">Cache Dependencies and Build Layers</a></li>
<li><a href="#heading-run-on-faster-hardware">Run on Faster Hardware</a></li>
<li><a href="#heading-parallelize-and-shard-your-tests">Parallelize and Shard Your Tests</a></li>
<li><a href="#heading-do-less-work-on-every-run">Do Less Work on Every Run</a></li>
<li><a href="#heading-putting-it-together">Putting It Together</a></li>
</ul>
<h2 id="heading-measure-first-then-optimize">Measure First, Then Optimize</h2>
<p>Most teams try to guess which step is slowing things down, and they're often wrong. A job that feels like a test problem may be 90 seconds of installs and 30 seconds of tests.</p>
<p>Start with data you already have. GitHub shows <a href="https://docs.github.com/en/actions/how-tos/monitor-workflows/view-job-execution-time">job execution time</a> for every run, with a timing for each step. Open the last ten runs of your slowest workflow and note the three longest steps. Use the median, not the worst case, since one slow run can be a network blip.</p>
<p>Also separate waiting from working. Queue time, setup time, and run time need different fixes. If jobs sit in a queue for a minute, no test tuning will help.</p>
<h2 id="heading-cache-dependencies-and-build-layers">Cache Dependencies and Build Layers</h2>
<p>The fastest work is work you never repeat. Every run starts on a fresh machine, so without a cache you download the same packages again and again.</p>
<p>The <a href="https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching">dependency caching reference</a> explains how <code>actions/cache</code> works. You give it a path and a key. If the key matches a saved cache, the files are restored. If not, the step runs, and the files are saved when the job ends.</p>
<p>Everything depends on that key. The usual pattern hashes your lockfile, so the key changes only when your dependencies change.</p>
<pre><code class="language-yaml">- uses: actions/cache@v6
  with:
    path: ~/.npm
    # Key changes only when the lockfile changes
    key: npm-${{ runner.os }}-${{ hashFiles('**/package-lock.json') }}
    restore-keys: |
      npm-${{ runner.os }}-
</code></pre>
<p>The <code>restore-keys</code> line is the part that tends to get skipped. When the exact key misses, it restores the closest older cache. You still install a few new packages, but not all of them. Be careful with keys that include a timestamp or a commit SHA. Those never match twice, so you save a new cache on every run and never reuse one.</p>
<p>Docker builds need the same thinking. Docker images are built in layers, and a layer is reused only if everything above it is unchanged. Copy your lockfile and install dependencies first, then copy your source code. That way a code change doesn't rebuild the install layer. To keep layers between runs, point BuildKit at the <a href="https://docs.docker.com/build/cache/backends/gha/">GitHub Actions cache backend</a> with <code>cache-from</code> and <code>cache-to</code> set to <code>type=gha</code>.</p>
<p>One catch is that these caches live in remote storage. Each restore is a network download, which on a big cache can rival the install it replaces.</p>
<h2 id="heading-run-on-faster-hardware">Run on Faster Hardware</h2>
<p>Caching avoids repeating work. This improvement is different. It runs the work itself on faster machines.</p>
<p>Standard GitHub-hosted runners for private repositories have 2 vCPUs and 7 GB of RAM. <a href="https://avrea.com/">Avrea</a> is a drop-in replacement for GitHub Actions runners. You change one line, from <code>runs-on: ubuntu-latest</code> to an Avrea label such as <code>runs-on: avrea-ubuntu-latest</code>, and the rest of your workflow stays the same. By Avrea's own numbers, jobs run about 2x faster on hardware alone, and up to 10x faster with cache hits.</p>
<p>Independent numbers point the same way. RunsOn maintains a <a href="https://runs-on.com/benchmarks/runners/">public runner benchmark</a> that builds three open-source projects on nine runner services with build caches turned off: a Rust test suite, TypeScript typechecks, and a production Docker build of PostHog. In the 4-vCPU x64 category, as of November 2026, Avrea finished all three in about 7 minutes of build time, compared with about 18.5 minutes on GitHub's 4-core runner, not counting runner start-up.</p>
<p>Built-in caching is the other half, and it connects to the section above. Avrea keeps its caches in the same datacenter as its runners, so a restore doesn't cross a slow network. Most of it is pre-configured.</p>
<p>The GitHub Actions cache and package downloads for npm, pip, Go modules, and Cargo work with no workflow changes. Build caches for tools such as Go, Bazel, Gradle, Turborepo, Nx, and sccache are set up on the runner, and some need a small workflow addition. So a team gets cache hits without writing key logic for each tool.</p>
<p>Other providers take other routes. <a href="https://depot.dev/">Depot</a> offers faster GitHub Actions runners and remote Docker builds, and now runs its own CI engine that accepts GitHub Actions workflows. <a href="https://runs-on.com/">RunsOn</a> is self-hosted: it starts EC2 instances inside your own AWS account, so you pay AWS for compute plus a flat yearly license, instead of a per-minute fee to RunsOn. GitHub's own <a href="https://docs.github.com/en/actions/concepts/runners/larger-runners">larger runners</a>, available on Team and Enterprise Cloud plans, add more CPU, RAM, and disk, plus options like static IPs and GPUs, billed by the minute. Check each provider's site for current details, since all of them change often.</p>
<h2 id="heading-parallelize-and-shard-your-tests">Parallelize and Shard Your Tests</h2>
<p>Once each job is fast, make sure jobs don't wait in a line. A long test suite on one runner is the classic bottleneck.</p>
<p>Start with independent jobs. Lint, type checks, unit tests, and build rarely need each other. GitHub runs jobs in parallel unless you add <code>needs</code>, so remove any <code>needs</code> line that's only there for habit.</p>
<p>Next, use a matrix. A <a href="https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/run-job-variations">matrix strategy</a> creates one job per combination of values, and they all run at once. Teams often use it for Node versions, but it's also the simplest way to shard tests.</p>
<pre><code class="language-yaml">strategy:
  fail-fast: false
  matrix:
    shard: [1, 2, 3, 4]
steps:
  # Each job runs one quarter of the suite
  - run: npx jest --shard=${{ matrix.shard }}/4
</code></pre>
<p>Jest's <code>--shard</code> flag splits the suite across jobs by test file. Four shards can turn a twelve-minute suite into about three, plus setup time, if the files take similar time. If a few files are much heavier, one shard will run long, so split those files up. Setting <code>fail-fast: false</code> lets every shard finish, so you see all failures at once.</p>
<p>Playwright works the same way. Run <a href="https://playwright.dev/docs/test-sharding"><code>npx playwright test --shard=1/4</code></a> in each matrix job, then merge the reports at the end.</p>
<p>Sharding has a limit. Each shard pays its own setup cost, so past a point more shards add cost without saving time. Inside a single job, tools like <a href="https://pytest-xdist.readthedocs.io/en/stable/">pytest-xdist</a> spread tests across the CPUs on the machine.</p>
<h2 id="heading-do-less-work-on-every-run">Do Less Work on Every Run</h2>
<p>The last one is the cheapest: don't run what you don't need to run.</p>
<p>Path filters are the easiest start. In the <a href="https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax">workflow syntax</a>, the <code>paths</code> and <code>paths-ignore</code> keys let a workflow run only when certain files change. A change to the docs folder shouldn't trigger a full backend build.</p>
<p>One warning: if a required status check never runs because of a path filter, the pull request stays stuck on a pending check. For required checks, let the workflow run and skip the job with an <code>if:</code> condition instead, since GitHub counts a skipped job as passed.</p>
<p>In a monorepo, go further and run only affected tests. Tools such as Nx, Turborepo, and Bazel work out which packages a change touches and skip the rest. In Nx that's <code>nx affected -t test</code>, and in Turborepo it's <code>turbo run test --affected</code>. Both compare your branch against <code>main</code>, so check out enough Git history for that comparison, since <code>actions/checkout</code> fetches a single commit by default.</p>
<p>Most commits touch a small part of a large codebase, so the savings add up. This matters more when agents open many small pull requests, each touching a package or two.</p>
<p>Finally, stop paying for runs that no one needs. When you push twice in a row, the first run is already out of date. A <a href="https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency">concurrency group</a> cancels it.</p>
<pre><code class="language-yaml">concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  # Cancel the older run when a new push arrives
  cancel-in-progress: true
</code></pre>
<p>This matters more as AI tools push more commits. Agents may update a branch many times an hour, and each push starts a full run. Don't use it on deploy workflows, though. Cancelling a deploy halfway can leave a bad state, so queue those instead.</p>
<h2 id="heading-putting-it-together">Putting It Together</h2>
<p>Measure first, because that shows which of the other four fixes is worth your time. Cache with stable keys and order your Dockerfile so slow layers stay put. Move heavy jobs to faster runners, and compare providers on your own workflow. Shard tests until setup time dominates. Then cut needless work with path filters, affected-only tests, and cancelled stale runs.</p>
<p>Make one change at a time and re-check your timings after each. Saving two minutes on a job that runs fifty times a day beats a clever fix on a job that runs once.</p>
<p>Hope you enjoyed this article. You can <a href="https://linkedin.com/in/manishmshiva"><u>connect with me on LinkedIn</u></a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Schema Drift vs. Semantic Drift in Data Pipelines ]]>
                </title>
                <description>
                    <![CDATA[ When a column is removed from a source database or dataset, the next pipeline run usually fails, making the problem easy to detect. But when a field keeps the same name and data type but its meaning c ]]>
                </description>
                <link>https://www.freecodecamp.org/news/schema-drift-vs-semantic-drift-in-data-pipelines/</link>
                <guid isPermaLink="false">6af6f326f94aa3564f351d31</guid>
                
                    <category>
                        <![CDATA[ Data pipelines ]]>
                    </category>
                
                    <category>
                        <![CDATA[ pydantic ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data-engineering ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Yemi Ojedapo ]]>
                </dc:creator>
                <pubDate>Fri, 13 Nov 2026 11:23:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/ae47b7ae-2c13-49b9-bad7-a20a28edbecb.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When a column is removed from a source database or dataset, the next pipeline run usually fails, making the problem easy to detect. But when a field keeps the same name and data type but its meaning changes (known as semantic drift), the pipeline can continue running normally, allowing the problem to go unnoticed.</p>
<p>This happens because a schema describes the structure of data, not what the values actually represent. It tells us which fields exist, their data types, and whether they can contain null values, but not whether a timestamp uses UTC, a durability score should range from 10 to 100, or an empty string means something different from null.</p>
<p>As a result, most pipeline checks are designed to catch obvious errors, such as missing columns or incorrect data types, but often fail to detect less obvious problems where the data looks correct but its meaning or values have changed.</p>
<p>I wanted to see how far this limitation reaches in practice, so I built a small lab where I introduced nine types of pipeline failures and tested four detectors against each one. This article looks at what each detector caught and what happened when changes went unnoticed and corrupted the data.</p>
<p>You can find the code <a href="https://github.com/hyemiie/game_inventory-schema_drift_lab-">here</a> and reproduce the experiment with a few commands.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><a href="#heading-how-the-lab-works">How the Lab Works</a></li>
<li><a href="#heading-understanding-data-shape-and-meaning">Understanding Data Shape and Meaning</a></li>
<li><a href="#heading-the-results-matrix">The Results Matrix</a></li>
<li><a href="#heading-detecting-changes-in-data-shape">Detecting Changes in Data Shape</a></li>
<li><a href="#heading-semantic-changes-what-the-wrong-numbers-looked-like">Semantic Changes: What the Wrong Numbers Looked Like</a></li>
<li><a href="#heading-damage-vs-visibility">Damage vs. Visibility</a></li>
<li><a href="#heading-detecting-changes-in-data-meaning">Detecting Changes in Data Meaning</a></li>
<li><a href="#heading-what-this-experiment-suggests">What this Experiment Suggests</a></li>
<li><a href="#heading-limitations">Limitations</a></li>
</ul>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>To follow along and run the lab yourself, you’ll need:</p>
<ul>
<li><strong>Python 3.10 or newer</strong>, and basic comfort reading Python code</li>
<li><strong>Pydantic v2</strong>, installed with <code>pip install pydantic</code></li>
<li><strong>Git</strong>, to clone the repository</li>
<li><strong>A terminal</strong>, to run the scripts</li>
<li><strong>Basic SQL</strong>, such as <code>GROUP BY</code> and <code>WHERE ... IS NULL</code>. SQLite comes with Python, so there is nothing extra to install.</li>
<li><strong>A general idea of what a data pipeline does</strong>: reading data from a source, transforming it, and loading it somewhere else</li>
</ul>
<h2 id="heading-how-the-lab-works">How the Lab Works</h2>
<p>I intentionally kept the pipeline simple. It reads 1,000 game-inventory records from a JSONL file, flattens the nested <code>stats</code> and <code>attributes</code> objects, loads the data into SQLite, and calculates six metrics: total number of records, unequipped items, item counts by rarity, average attack per category, items acquired per day, and average durability. I also left out defensive checks so that each change could affect the pipeline in the same way it might affect a real pipeline when someone assumes the source data is reliable.</p>
<p>Each drift applies a deterministic function that takes one record and returns a changed one, so every result is repeatable. For instance, the timezone drift shifts each UTC timestamp to UTC+4 wall time and drops the offset:</p>
<pre><code class="language-python">def local_time_without_offset(row):
    timestamp = row["acquired_at"]
    if not timestamp.endswith("Z"):
        raise ValueError(f"Expected UTC timestamp ending in Z, got: {timestamp!r}")

    utc_time = datetime.fromisoformat(timestamp.removesuffix("Z") + "+00:00")
    local_time = utc_time + timedelta(hours=4)
    row["acquired_at"] = local_time.replace(tzinfo=None).isoformat()
    return row
</code></pre>
<p>After applying each drift, I ran the pipeline and saved its output in a separate SQLite database. I then compared it with the database generated from the original data, checking each row and column for differences. This step helped identify whether the pipeline had produced correct results, rather than simply checking whether it ran successfully.</p>
<p>The comparison placed each change into one of four categories:</p>
<ul>
<li>failed loudly (the error names a field the drift touched)</li>
<li>failed confusingly (the pipeline crashed but the error doesn't mention the cause)</li>
<li>passed with corruption (it finished, but values differ from the baseline)</li>
<li>or passed clean (the database matches the baseline exactly).</li>
</ul>
<p>I tested each drifted file with four detectors. Each detector follows the same structure: it takes the baseline file and the incoming file as input, checks for changes, and returns whether it found a problem along with a message. This shared interface keeps the setup simple and makes it easy to add more detectors.</p>
<p>The four detectors are:</p>
<ol>
<li><strong>Schema snapshot diff:</strong> Compares the fields and data types in the incoming file against the baseline to identify schema changes.</li>
<li><strong>Loose Pydantic model:</strong> Validates the data against a basic set of rules and restricts <code>rarity</code> to the five known values.</li>
<li><strong>Strict Pydantic model:</strong> Applies additional validation rules. It also restricts <code>rarity</code> to the five known values, requires timezone-aware timestamps, limits <code>equipped_slot</code> to five known values, and rejects unknown top-level fields. This refers to the validation rules in the model, not Pydantic's <code>strict=True</code> mode.</li>
<li><strong>Statistical profile:</strong> Compares the statistical profile of the incoming data with the baseline. It checks each field's mean, category shares, and null rate to identify changes that the other detectors might miss</li>
</ol>
<h2 id="heading-understanding-data-shape-and-meaning">Understanding Data Shape and Meaning</h2>
<p>The rest of this article uses two terms: <strong>data shape</strong> and <strong>data meaning</strong>. Data shape refers to the fields in a dataset, their paths, and the types of values they contain. The schema detector captures this information by checking each field and the types found in it.</p>
<pre><code class="language-python">def walk(obj, prefix, schema):
    for key, value in obj.items():
        field = f"{prefix}{key}"
        if isinstance(value, dict):
            walk(value, field + ".", schema)
        else:
            schema.setdefault(field, set()).add(type(value).__name__)
</code></pre>
<p>For the baseline, this returns entries like <code>acquired_at: {'str'}</code>, <code>equipped_slot: {'NoneType', 'str'}</code>, and <code>attributes.durability: {'int'}</code>.<br><br>Data meaning, however, includes everything the dictionary leaves out including the unit and time zone of a value, its expected range, the set of valid strings, and what a null value represents. This reveals a limitation of any detector that only looks at data shape. Since the schema detector bases its results on the dictionary of field paths and data types, it can't distinguish between datasets that produce the same dictionary but contain values with different meanings.</p>
<p>Three of the nine drifts left this dictionary unchanged: the timezone shift, the new enum value, and the durability scaling. As a result, the schema detector didn't flag any of them.</p>
<p>Detectors can check data at different levels:</p>
<ol>
<li>Shape: Checks which fields exist and the types of values they contain.</li>
<li>Value constraints: Checks whether individual values follow specific rules, such as requiring timezone information or limiting a field to a known set of values.</li>
<li>Distribution: Compares statistics, such as averages, category shares, and null rates, against a baseline. This can reveal changes in the data without defining exactly what each value should mean.</li>
<li>Semantics: Checks what the data actually represents, including units, timezone conventions, and the meaning of null values. These rules require knowledge of the data and must come from the people or systems that produce and use it.</li>
</ol>
<p>The four detectors cover the first three levels. The fourth level goes beyond what these detectors can establish because a dataset can pass checks on its structure, individual values, and statistical distributions while its meaning has changed. To know what the data means, we need context that can't be gotten from its values alone.</p>
<h2 id="heading-the-results-matrix">The Results Matrix</h2>
<p>The results matrix summarizes how each of the four detectors responded to the nine drift scenarios.</p>
<pre><code class="language-python">for drift in ALL_DRIFTS:
    dst = ROOT / "data" / "drifted" / f"{drift.name}.jsonl"
    drifted_db = DB_DIR / f"{drift.name}.db"

    apply_drift(drift, BASELINE, dst)
    result = run_pipeline(dst, db_path=str(drifted_db))
    outcome = classify(result, baseline_db, drifted_db, drift.fields)

    detected = {
        det.name: det.check(str(BASELINE), str(dst))["detected"]
        for det in DETECTORS
    }

    rows.append((drift, outcome, detected, result.get("error")))
</code></pre>
<p>It shows which changes they caught, which they missed, and whether the pipeline failed or continued with incorrect data.</p>
<table>
<thead>
<tr>
<th>Drift</th>
<th>What changed</th>
<th>Pipeline outcome</th>
<th>Rows corrupted</th>
<th>Schema diff</th>
<th>Pydantic (loose)</th>
<th>Pydantic (strict)</th>
<th>Statistical profile</th>
</tr>
</thead>
<tbody><tr>
<td><code>rename_rarity</code></td>
<td><code>rarity</code> renamed</td>
<td>Failed loudly</td>
<td>n/a</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td><code>drop_equipped_slot</code></td>
<td><code>equipped_slot</code> removed</td>
<td>Failed loudly</td>
<td>n/a</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td><code>stats_become_list</code></td>
<td><code>stats</code> object became an array</td>
<td>Failed confusingly</td>
<td>n/a</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td><code>add_column</code></td>
<td>New <code>guild</code> field</td>
<td>Passed clean</td>
<td>0</td>
<td>Yes</td>
<td>No</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td><code>type_change_level</code></td>
<td><code>level</code> int became string</td>
<td>Passed clean</td>
<td>0</td>
<td>Yes (only)</td>
<td>No</td>
<td>No</td>
<td>No</td>
</tr>
<tr>
<td><code>empty_equipped_slot</code></td>
<td>Null slots became <code>""</code></td>
<td>Passed with corruption</td>
<td>205</td>
<td>Yes</td>
<td>No</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td><code>new_enum_value</code></td>
<td>20 rows relabeled <code>mythic</code></td>
<td>Passed with corruption</td>
<td>20</td>
<td>No</td>
<td>Yes</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td><code>local_time_without_offset</code></td>
<td>Timestamps shifted to UTC+4, offset dropped</td>
<td>Passed with corruption</td>
<td>1,000</td>
<td>No</td>
<td>No</td>
<td>Yes (only)</td>
<td>No</td>
</tr>
<tr>
<td><code>durability_scaled</code></td>
<td>Durability multiplied by 10</td>
<td>Passed with corruption</td>
<td>1,000</td>
<td>No</td>
<td>No</td>
<td>No</td>
<td>Yes (only)</td>
</tr>
<tr>
<td><strong>Total caught</strong></td>
<td></td>
<td></td>
<td></td>
<td><strong>6 / 9</strong></td>
<td><strong>4 / 9</strong></td>
<td><strong>7 / 9</strong></td>
<td><strong>2 / 9</strong></td>
</tr>
</tbody></table>
<p>"Yes (only)” means that detector was the only one to catch the change. “n/a” means the pipeline crashed, so no rows were loaded.</p>
<h3 id="heading-pipeline-errors">Pipeline Errors</h3>
<table>
<thead>
<tr>
<th>Drift</th>
<th>Label</th>
<th>Error</th>
</tr>
</thead>
<tbody><tr>
<td><code>rename_rarity</code></td>
<td>Failed loudly</td>
<td><code>KeyError: 'rarity'</code></td>
</tr>
<tr>
<td><code>drop_equipped_slot</code></td>
<td>Failed loudly</td>
<td><code>KeyError: 'equipped_slot'</code></td>
</tr>
<tr>
<td><code>stats_become_list</code></td>
<td>Failed confusingly</td>
<td><code>TypeError: list indices must be integers or slices, not str</code></td>
</tr>
</tbody></table>
<p>The strict model detected the most changes (7 out of 9), followed by the schema diff (6), the loose model (4), and the statistical profile (2).</p>
<p>But each detector missed some changes. Three drifts were detected by only one detector: the strict model caught the timezone shift, the schema diff caught the <code>level</code> change, and the statistical profile caught the durability scaling.</p>
<h2 id="heading-detecting-changes-in-data-shape">Detecting Changes in Data Shape</h2>
<p>Five of the nine drifts changed the data structure. These included renaming <code>rarity</code>, removing <code>equipped_slot</code>, adding a <code>guild</code> field, replacing the <code>stats</code> object with an array, and changing <code>level</code> from an integer to a string.</p>
<p>The schema diff detected all five changes. The strict model detected four, and the loose model detected three. This shows that the schema diff was the most effective at detecting structural changes.</p>
<p>The pipeline failed on three of the drifts, but some error messages were more useful than others. Renaming <code>rarity</code> caused a <code>KeyError: 'rarity'</code>, which tells us exactly which field is missing. Replacing <code>stats</code> with <code>[attack, defense, speed]</code> caused a <code>TypeError: list indices must be integers or slices, not str</code>. This message explains the type of error but doesn't identify the field involved. To find the cause, the reader has to trace the error back through the transformation code.</p>
<p>The classifier labels the first error loud and the second <a href="http://confusing.It">confusing.It</a> makes this distinction by checking whether the error message mentions a field affected by the drift.</p>
<pre><code class="language-python">if result["status"] == "error":
    error_text = result["error"].lower()
    names_cause = any(f.lower() in error_text for f in drift_fields)
    return {
        "label": "failed_loudly" if names_cause else "failed_confusingly",
        "rows_affected": None,
        "loss_cells": 0,
        "corrupt_cells": 0,
        "extra_rows": 0,
    }
</code></pre>
<p>The Pydantic detectors ran on the same file and reported <code>stats: Input should be a valid dictionary</code>, directly identifying the field with the problem.</p>
<p>The <code>level</code> change reveals another way a structural change can go undetected. Both Pydantic models accepted it because Pydantic's default lax mode converts the string <code>"42"</code> into the integer <code>42</code>. The pipeline also accepted it because SQLite's INTEGER affinity converts text that looks like a number when inserting it into an INTEGER column. As a result, the database matched the baseline, and the classifier labeled the run <code>passed_clean</code>.</p>
<p>Only the schema diff detected the change because it checks the type of the raw value before any conversion takes place. This shows the limitation of checking data after coercion: once a value has been converted, the original type change is no longer visible. In this case, the simplest detector caught a change that both Pydantic models accepted.</p>
<p>The experiment also showed that not every detected change causes a problem. Adding <code>guild</code> and changing <code>level</code> from an integer to a string both triggered alerts. The schema diff detected both changes, while the strict model detected only the addition of <code>guild</code>. But neither change corrupted any rows because the load step reads only the fields it expects.</p>
<p>This highlights the need to distinguish between changes that should stop a pipeline and those that only need to be logged. If detectors flag too many harmless changes, users may start to ignore their warnings.</p>
<h2 id="heading-semantic-changes-what-the-wrong-numbers-looked-like">Semantic Changes: What the Wrong Numbers Looked Like</h2>
<p>The remaining drifts didn't change the fields or data types. They changed what the values represented. These changes were harder to detect but had real effects on the results. The table below shows the impact of each drift and whether it was visible in the pipeline's output.</p>
<table>
<thead>
<tr>
<th>Drift</th>
<th>Rows corrupted</th>
<th>Metric that moved</th>
<th>Before</th>
<th>After</th>
</tr>
</thead>
<tbody><tr>
<td>Timestamps shifted to UTC+4, offset dropped</td>
<td>1,000</td>
<td>items acquired per day</td>
<td>Jan 2: 9, Jan 3: 3</td>
<td>Jan 2: 6, Jan 3: 6</td>
</tr>
<tr>
<td>Null slots replaced with <code>""</code></td>
<td>205</td>
<td>unequipped item count</td>
<td>205</td>
<td>0</td>
</tr>
<tr>
<td>New <code>mythic</code> rarity on 20 rows</td>
<td>20</td>
<td>item count per rarity</td>
<td>common: 619</td>
<td>common: 609, mythic: 20</td>
</tr>
<tr>
<td>Durability multiplied by 10</td>
<td>1,000</td>
<td>average durability</td>
<td>54.78</td>
<td>547.85</td>
</tr>
</tbody></table>
<p>A major thing I noticed is that most of the numbers still look normal. For example, moving timestamps forward by four hours shifts some items onto the next calendar day. Since four hours is one-sixth of a day, roughly one in six items moves to a different day. Each day loses some items to the next day but also gains items from the previous day.</p>
<p>The total number of items remains 1,000, and the daily counts change very little overall. With an average of about 5.5 items per day, the counts already vary by two or three items. So a drop from 9 items to 6 can easily look like typical variation rather than a data problem.</p>
<p>The pipeline's total-row-count check still passed because no items were lost. Any check that only compares totals would also miss the problem. The total is correct, but some items are now counted under the wrong day.</p>
<p>I also looked at why the pipeline didn't report a problem. The original timestamp, <code>2026-01-02T22:30:00+00:00</code>, changed to <code>2026-01-03T02:30:00</code> after the drift. The new timestamp has no timezone offset, so <code>datetime.fromisoformat</code> reads it as a naïve datetime. The <code>isoformat()</code> method then writes it back without an offset. SQLite's <code>DATE()</code> treats this offset-free timestamp as UTC, placing the item on January 3 instead of January 2.</p>
<p>The pipeline processed the timestamp without errors but assigned the item to the wrong day. If the producer had written <code>2026-01-03T02:30:00+04:00</code> instead, the timestamp would have represented the same instant as the original. SQLite would have converted it to UTC, and the item would still have been counted on January 2.</p>
<p>The problem was the missing timezone offset. Without it, the pipeline had no way to know which timezone the timestamp represented, so it treated the time as UTC.</p>
<p>The empty-string drift caused a different problem. Replacing <code>null</code> with <code>""</code> kept the field as a string, so checks that only verify the data type still passed.</p>
<p>The schema diff caught the change because the type set for <code>equipped_slot</code> changed from <code>{'NoneType', 'str'}</code> to <code>{'str'}</code>. The pipeline raised no errors, but the query <code>WHERE equipped_slot IS NULL</code> returned no rows. The dashboard would show 0 unequipped items instead of 205, making it look as though every player had equipped their gear.</p>
<p>The statistical profile showed what had happened: <code>equipped_slot: null rate 20% -&gt; 0%; equipped_slot='': share 0% -&gt; 20%</code>. The null values had been replaced with empty strings, not real values.</p>
<p>The new <code>mythic</code> rarity went through the pipeline without an error for a similar reason. The drift changed 20 records to <code>mythic</code>: 10 from <code>common</code> (619 to 609), 9 from <code>uncommon</code> (236 to 227), and 1 from <code>rare</code> (98 to 97). The query <code>GROUP BY rarity</code> accepted the new value without any error. It simply created a new row for <code>mythic</code> and reduced the counts for the other rarities. A dashboard that only knows the five original rarities might hide <code>mythic</code> or group it under "other", depending on how it handles unknown values.</p>
<p>The durability change shows most clearly how data can keep the same structure but mean something different. In the original data, durability ranges from 10 to 100, so an average of 547.85 is clearly wrong. But the field kept the same name and integer type, so the schema diff didn't detect the change.</p>
<p>The pipeline also accepted the values because nothing checked them against the expected range. Only a check that knows durability should be between 10 and 100 can catch this problem. To test this, I added a range constraint to the strict Pydantic model:</p>
<pre><code class="language-python">class RangedAttributes(Attributes):
    durability: int = Field(ge=10, le=100)


class StrictWithRange(StrictItem):
    attributes: RangedAttributes


flagged = 0
for row in drifted:
    try:
        StrictWithRange(**row)
    except ValidationError:
        flagged += 1
</code></pre>
<p>This caught 985 of the 1,000 drifted records. The remaining 15 had an original durability value of 10, which became 100 after scaling by 10. Since 100 still falls within the allowed range, those records passed validation.</p>
<h2 id="heading-damage-vs-visibility">Damage vs. Visibility</h2>
<p>The four drifts corrupted 1,000, 205, 20, and 1,000 rows, but each one changed only one of the six metrics the pipeline calculates. The other five metrics stayed the same. Anyone monitoring the pipeline could miss the damage unless they checked the affected metric and knew its expected value.</p>
<p>The main finding is that data can change across many rows without changing most of the results people monitor. People only notice the problem if they check the metric that the drift affects.</p>
<h2 id="heading-detecting-changes-in-data-meaning">Detecting Changes in Data Meaning</h2>
<p>To catch changes beyond the data structure, we need checks that examine the values themselves.</p>
<p>The strict model checks whether values follow specific rules. It caught the timezone drift because <code>AwareDatetime</code> rejects timestamps without a timezone offset (<code>acquired_at: Input should have timezone info</code>). It also caught the empty-string slot because its <code>Literal</code> rule only accepts five known slot names and rejects <code>""</code>.</p>
<p>The loose model has fewer restrictions. It accepts any string for <code>acquired_at</code>, any string or <code>None</code> for <code>equipped_slot</code>, and unknown fields. As a result, it missed the timezone shift, the empty-string slot, and the new column.</p>
<p>The strict model also missed the durability change because I hadn't defined an allowed range for that field. In a separate run, I added <code>Field(ge=10, le=100)</code> to a copy of the model. This caught 985 of the 1,000 changed rows. It missed the remaining 15 because their original durability was 10, which became exactly 100 after scaling and still passed the check.</p>
<p>The statistical profile compares data distributions with the baseline. It was the only detector to catch the durability scaling because it doesn't need a predefined range. It simply detected that the average durability rose from 54.8 to 547.9.</p>
<p>But it may also flag normal changes in the data. To test this, I scaled durability by factors from 1.02 to 1.3 and tried four mean-change thresholds. I also tested the detector on 200 clean files generated with different seeds to see how often it raised false alarms. I excluded the baseline seed because it would produce identical data.</p>
<table>
<thead>
<tr>
<th>Mean threshold</th>
<th>False alarms, durability only</th>
<th>False alarms, any numeric field</th>
<th>Shifts caught</th>
</tr>
</thead>
<tbody><tr>
<td>25%</td>
<td>0 / 200</td>
<td>0 / 200</td>
<td>1.3x only</td>
</tr>
<tr>
<td>10%</td>
<td>0 / 200</td>
<td>0 / 200</td>
<td>1.1x and above</td>
</tr>
<tr>
<td>5%</td>
<td>0 / 200</td>
<td>23 / 200 (11.5%)</td>
<td>1.05x and above</td>
</tr>
<tr>
<td>2%</td>
<td>37 / 200 (18.5%)</td>
<td>188 / 200 (94%)</td>
<td>every shift tested</td>
</tr>
</tbody></table>
<p>The 2% threshold shows how easily the detector can flag normal variation. Durability is roughly uniform from 10 to 100, so a 1,000-row sample has a standard deviation of about 26. That means the sample mean typically lands within about 0.8 of the true mean, which is roughly 1.5% of its value. A 2% threshold is only a little bigger than that, so it should fire on roughly 18% of clean files. It fired on 37 of 200 (18.5%). This shows a tradeoff that lowering the threshold helps catch small changes but also increases false alarms.</p>
<p>The results also show why one threshold doesn't work for every numeric field. <code>stats.attack</code>, <code>level</code>, and <code>player_id</code> vary more than durability relative to their averages. At a 2% threshold, at least one of these fields triggered an alarm in 188 of 200 clean files. At 5%, they caused all 23 false alarms, while durability caused none. <code>stats.attack</code> caused 15 of those alarms. Even <code>player_id</code> triggered alarms, although its average has no useful meaning.</p>
<p>Using a single threshold treats every numeric field the same, even though some vary more than others and some shouldn't be checked by their average at all.</p>
<p>The category-share check uses a fixed 5-percentage-point threshold, so changing the mean threshold doesn't affect its results. It raised 26 alarms across 22 of the 200 clean files (11%). Seventeen alarms involved <code>equipped_slot</code>, and 16 of those involved <code>chest</code> or <code>off_hand</code>.</p>
<p>There are two reasons for these alarms. First, the check calculates each slot's share using only the 795 non-null rows, not all 1,000. This gives each share a standard error of about 1.4 percentage points.</p>
<p>Second, my baseline doesn't match the intended shares exactly. <code>chest</code> makes up 17.2% of the baseline instead of the intended 20%. As a result, a clean file only needs to reach 22.2% to trigger an alarm. This happens in roughly 6% of files. <code>off_hand</code> has the opposite problem: its baseline share is higher than intended, at 22.3%. This shows that a baseline can contain its own sampling errors, which then affect every comparison.</p>
<p>One more limitation comes from the detector design, not from a measured result. I didn't test this case, but the code shows why it would go undetected. The strict model caught the timezone drift because the timestamp lost its offset. But a producer could shift the clock and keep the <code>Z</code> suffix. Every detector would then accept the data. The strict model checks only whether a timestamp has an offset, not whether the time is correct. The statistical profile skips timestamp strings because they have too many distinct values to treat as categories and aren't numeric.</p>
<p>This is a limitation of the fourth layer: the timestamp still looks valid, but it represents the wrong time. None of the detectors checks whether the timestamp matches the actual time it is supposed to represent.</p>
<h2 id="heading-what-this-experiment-suggests">What this Experiment Suggests</h2>
<p>The results suggest that combining all four detectors provides better coverage because each one catches changes the others miss.</p>
<p>The schema diff is simple and cheap to run on every load. It caught six of the nine drifts, including the <code>level</code> change that both Pydantic models missed because they converted the value before checking it. It also identified the field that caused an error when the pipeline's own error message did not. But it caught only one of the four drifts that corrupted data.</p>
<p>The strict model and statistical profile caught all four harmful drifts between them. I'd use the strict model for fields with known rules, such as timezone-aware timestamps, allowed values, and numeric ranges. I'd use statistical checks for important metrics that have no clear validation rules, setting a separate threshold for each field based on past data.</p>
<p>The lab showed why one threshold doesn't work for every field. A global 5% mean threshold raised 23 false alarms across 200 clean files, all from fields other than durability. I'd only apply statistical checks to fields where the average is meaningful and set thresholds based on how much each field normally varies.</p>
<p>The fourth layer requires the producer and consumers to agree on what the data means. If the producer changes a field's unit, time zone, or allowed values without telling anyone, consumers can't interpret it correctly. Both sides should agree on clear rules, such as the unit of measurement, the time zone, and the allowed values.</p>
<p>This is a recommendation based on what my detectors couldn't catch. I haven't tested this approach in the lab yet.</p>
<h2 id="heading-limitations">Limitations</h2>
<p>The data is synthetic and independent, so it's much simpler than real data, which often has seasonal patterns and natural growth. Real-world false-alarm rates may therefore be higher than the ones I measured. I also used one fixed baseline, so any sampling error in that sample affects every comparison. A production system would likely use a rolling baseline instead.</p>
<p>I used the same thresholds across fields. Setting a separate threshold based on how much each field normally varies might work better, but I didn't test this. I also tested only four detectors from a much larger set of available tools. These results show where the detectors have blind spots, not which tools are best.</p>
<p>Finally, I chose to group changes into "shape" and "meaning," but some changes, such as replacing <code>null</code> with an empty string, could fit into either group.</p>
<p>My first threshold test also contained a bug. I used the wrong variable name (<code>SEED</code> instead of <code>seed</code>) in the data generator, which caused all 20 clean files to match the baseline exactly. This produced zero false alarms. A result that good at a 2% threshold seemed unlikely, so I checked the code and found the mistake. I corrected the bug and excluded seed 42, the baseline's own seed, because it would generate identical data and could never trigger an alarm. All results in this article use the corrected run.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The experiment showed that schema changes are not the only source of pipeline failures. The schema diff caught all five structural changes but missed semantic changes that left field names and types untouched. For example, timestamps shifted to the wrong day, null values became empty strings, and durability values increased tenfold. In each case, the pipeline ran successfully but produced incorrect results.</p>
<p>The four detectors caught different types of changes, and using them together improved detection coverage. However, detecting changes is only part of the problem. Pipeline checks also need to validate whether values fall within expected ranges and whether they still represent what downstream calculations assume.</p>
<p>A pipeline completing successfully doesn't necessarily mean the data is correct. It’s just as important to check that the data retains its intended meaning and that downstream calculations still produce reliable results.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Browser-Based Image Storyboard to PDF Tool Using JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Before anyone films a video, shoots an ad or draws the final pages of a comic, someone usually sketches the plan as a storyboard: one picture per shot, in order, with a short note about what happens a ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-image-storyboard-to-pdf-tool-javascript/</link>
                <guid isPermaLink="false">6af6ea1b6758a8ccb76659d6</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ pdf ]]>
                    </category>
                
                    <category>
                        <![CDATA[ canvas ]]>
                    </category>
                
                    <category>
                        <![CDATA[ indexeddb ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bhavin Sheth ]]>
                </dc:creator>
                <pubDate>Fri, 13 Nov 2026 10:44:43 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5fc16e412cae9c5b190b6cdd/eb2e1525-11db-47ef-a27c-b0672184efe8.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Before anyone films a video, shoots an ad or draws the final pages of a comic, someone usually sketches the plan as a storyboard: one picture per shot, in order, with a short note about what happens and how long it lasts.</p>
<p>Most people already have those pictures. They are phone photos, screenshots, rough sketches or AI-generated frames sitting in a folder. What they don't have is a quick way to turn that folder into clean, numbered sheets they can print or send to a client.</p>
<p>In this tutorial, you'll build a browser-based tool that does exactly that. You'll add a set of images, give each one a title, a description and a duration, choose a layout, preview the sheets, and download a print-ready PDF.</p>
<p>Everything runs in the browser. The images are never uploaded to a server, which matters when the frames are unreleased product shots or client work.</p>
<p>Along the way, you'll learn how to fix sideways phone photos, sort files the way people expect, lay out a page in PDF points, wrap text on a canvas, save a draft with IndexedDB, and build a PDF that keeps photos sharp without making the file huge.</p>
<p>I built this tool for AllInOneTools, where it runs as the Image Storyboard to PDF tool. This article walks through a simplified version that you can build in three files.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a href="#heading-what-this-image-storyboard-tool-does-and-how-it-works">What This Image Storyboard Tool Does and How It Works</a></li>
<li><a href="#heading-project-setup">Project Setup</a></li>
<li><a href="#heading-libraries-and-browser-apis-used">Libraries and Browser APIs Used</a></li>
<li><a href="#heading-creating-the-html-layout">Creating the HTML Layout</a></li>
<li><a href="#heading-adding-and-loading-images">Adding and Loading Images</a></li>
<li><a href="#heading-managing-the-frames">Managing the Frames</a></li>
<li><a href="#heading-building-the-board-settings">Building the Board Settings</a></li>
<li><a href="#heading-laying-out-a-storyboard-sheet">Laying Out a Storyboard Sheet</a></li>
<li><a href="#heading-drawing-a-sheet-on-the-canvas">Drawing a Sheet on the Canvas</a></li>
<li><a href="#heading-previewing-the-sheets">Previewing the Sheets</a></li>
<li><a href="#heading-saving-a-draft-with-indexeddb">Saving a Draft with IndexedDB</a></li>
<li><a href="#heading-generating-the-pdf-with-pdf-lib">Generating the PDF with PDF-lib</a></li>
<li><a href="#heading-renaming-and-downloading">Renaming and Downloading</a></li>
<li><a href="#heading-demo-how-the-image-storyboard-tool-works">Demo: How the Image Storyboard Tool Works</a></li>
<li><a href="#heading-performance-tips">Performance Tips</a></li>
<li><a href="#heading-common-mistakes">Common Mistakes</a></li>
<li><a href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-this-image-storyboard-tool-does-and-how-it-works">What This Image Storyboard Tool Does and How It Works</h2>
<p>The tool takes a list of images and turns them into storyboard sheets. Each image becomes a <strong>frame</strong> with:</p>
<ul>
<li>a label, such as <code>Shot 1</code> or <code>Scene 1</code></li>
<li>an optional title</li>
<li>a description of what happens</li>
<li>an optional duration in seconds</li>
</ul>
<p>The frames are placed on sheets in one of four layouts:</p>
<ul>
<li><strong>One frame per page</strong>, for presenting each shot large</li>
<li><strong>Grid</strong>, for seeing the whole sequence at a glance</li>
<li><strong>Panels with notes</strong>, with ruled lines for handwritten notes on set</li>
<li><strong>Film strip</strong>, with sprocket holes for a classic look</li>
</ul>
<p>Each sheet has a title, the total running time and a sheet number at the top.</p>
<p>Here's the flow from start to finish:</p>
<pre><code class="language-text">Images → frames (title, description, duration)
       → layout (where each box goes, in PDF points)
       → canvas (labels, text, lines)
       → PDF (photos as JPEG + one text layer per sheet)
       → download
</code></pre>
<h3 id="heading-why-the-text-is-drawn-on-a-canvas">Why the Text Is Drawn on a Canvas</h3>
<p>PDF-lib can write real text into a PDF, but only with a font file you embed. The standard PDF fonts only cover basic Latin characters, so a description in Hindi, Gujarati, Arabic or Japanese would fail.</p>
<p>A canvas, on the other hand, can draw any text the device can show, using the fonts the device already has. So this tool draws all the text on a canvas at 300 dpi and puts that canvas into the PDF as an image.</p>
<p>The trade-off is that the text in the PDF isn't selectable or searchable. For a storyboard, which is mostly printed and looked at, that's usually fine. If you need searchable text, you'd embed a font with PDF-lib's <code>fontkit</code> support instead.</p>
<h2 id="heading-project-setup">Project Setup</h2>
<p>You need only three files:</p>
<pre><code class="language-text">image-storyboard/
├── index.html
├── style.css
└── script.js
</code></pre>
<p>Open <code>index.html</code> through a local server (for example, the Live Server extension in VS Code) rather than as a <code>file://</code> page, so that IndexedDB and downloads behave the same way they will on a real site.</p>
<h2 id="heading-libraries-and-browser-apis-used">Libraries and Browser APIs Used</h2>
<p>This project uses one library and a few built-in browser APIs:</p>
<ul>
<li><strong>PDF-lib</strong> creates the PDF, embeds the JPEG and PNG images, and saves the file.</li>
<li><strong>Canvas API</strong> draws the sheets for the preview and the text layer of the PDF.</li>
<li><code>createImageBitmap</code> decodes images and applies the rotation stored in phone photos.</li>
<li><strong>IndexedDB</strong> keeps a draft in the browser so the work survives a page reload.</li>
</ul>
<p>You don't need PDF.js here, because there's no PDF to read. Everything starts from images.</p>
<p>Add PDF-lib with a pinned version at the end of the <code>body</code>, before your own script:</p>
<pre><code class="language-html">&lt;script src="https://unpkg.com/pdf-lib@1.17.1/dist/pdf-lib.min.js"&gt;&lt;/script&gt;
&lt;script src="script.js"&gt;&lt;/script&gt;
</code></pre>
<p>Pinning the version means a future release of the library can't break your tool without you knowing.</p>
<h2 id="heading-creating-the-html-layout">Creating the HTML Layout</h2>
<p>The page has four parts:</p>
<ol>
<li>An upload area with a file input</li>
<li>A bar that offers to restore a saved draft</li>
<li>A frames panel with one card per image</li>
<li>A settings panel and a preview panel</li>
</ol>
<p>Here's the upload area and the draft bar:</p>
<pre><code class="language-html">&lt;!-- 1. Upload --&gt;
&lt;section id="uploadArea" class="upload-area"&gt;
  &lt;p&gt;Drop images here or&lt;/p&gt;
  &lt;button type="button" id="selectBtn"&gt;Select images&lt;/button&gt;
  &lt;input type="file" id="fileInput" accept="image/jpeg,image/png,image/webp,image/gif" multiple hidden&gt;
  &lt;p id="statusText" class="status" aria-live="polite"&gt;&lt;/p&gt;
&lt;/section&gt;

&lt;div id="draftBar" class="draft-bar" hidden&gt;
  &lt;span id="draftText"&gt;&lt;/span&gt;
  &lt;button type="button" id="restoreBtn"&gt;Restore&lt;/button&gt;
  &lt;button type="button" id="discardBtn"&gt;Discard&lt;/button&gt;
&lt;/div&gt;
</code></pre>
<p>The file input only accepts the formats every browser can decode: JPEG, PNG, WebP and GIF.</p>
<p>The workspace holds the three panels:</p>
<pre><code class="language-html">&lt;!-- 2. Workspace --&gt;
&lt;section id="workspace" class="workspace" hidden&gt;
  &lt;div class="frames-panel"&gt;
    &lt;div class="panel-head"&gt;
      &lt;h2&gt;Frames&lt;/h2&gt;
      &lt;span id="totalTime"&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;label&gt;Storyboard title
      &lt;input type="text" id="boardTitle" placeholder="My video"&gt;
    &lt;/label&gt;
    &lt;ol id="frameList" class="frame-list"&gt;&lt;/ol&gt;
    &lt;button type="button" id="undoBtn" hidden&gt;Undo delete&lt;/button&gt;
    &lt;button type="button" id="addMoreBtn"&gt;Add more images&lt;/button&gt;
  &lt;/div&gt;
</code></pre>
<p>The settings panel is a list of <code>select</code> and <code>number</code> inputs. Each one has an <code>id</code> that matches a key in the settings object you'll create in JavaScript:</p>
<pre><code class="language-html">&lt;div class="settings-panel"&gt;
  &lt;h2&gt;Board settings&lt;/h2&gt;
  &lt;label&gt;Layout
    &lt;select id="layout"&gt;
      &lt;option value="page"&gt;One frame per page&lt;/option&gt;
      &lt;option value="grid" selected&gt;Grid&lt;/option&gt;
      &lt;option value="notes"&gt;Panels with notes&lt;/option&gt;
      &lt;option value="strip"&gt;Film strip&lt;/option&gt;
    &lt;/select&gt;
  &lt;/label&gt;
  &lt;label&gt;Columns &lt;input type="number" id="cols" min="1" max="6" value="3"&gt;&lt;/label&gt;
  &lt;label&gt;Rows &lt;input type="number" id="rows" min="1" max="6" value="2"&gt;&lt;/label&gt;
  &lt;!-- Paper, Orientation, Frame label, Font, Text size and
       Description lines follow the same pattern --&gt;
&lt;/div&gt;
</code></pre>
<p>The preview panel has the canvas, the sheet navigation and the download controls:</p>
<pre><code class="language-html">&lt;div class="preview-panel"&gt;
  &lt;h2&gt;Preview&lt;/h2&gt;
  &lt;canvas id="previewCanvas"&gt;&lt;/canvas&gt;
  &lt;div class="pager"&gt;
    &lt;button type="button" id="prevBtn"&gt;Previous&lt;/button&gt;
    &lt;span id="sheetInfo"&gt;&lt;/span&gt;
    &lt;button type="button" id="nextBtn"&gt;Next&lt;/button&gt;
  &lt;/div&gt;

  &lt;label&gt;File name &lt;input type="text" id="fileName" value="storyboard"&gt;&lt;/label&gt;
  &lt;label&gt;Image quality
    &lt;select id="quality"&gt;
      &lt;option value="300"&gt;Print, 300 dpi&lt;/option&gt;
      &lt;option value="150"&gt;Smaller file, 150 dpi&lt;/option&gt;
    &lt;/select&gt;
  &lt;/label&gt;
  &lt;button type="button" id="downloadBtn" class="primary"&gt;Download PDF&lt;/button&gt;
  &lt;button type="button" id="resetBtn"&gt;Start over&lt;/button&gt;
  &lt;p id="resultText" class="status" aria-live="polite"&gt;&lt;/p&gt;
&lt;/div&gt;
</code></pre>
<p>In <code>style.css</code>, add one rule that's easy to forget:</p>
<pre><code class="language-css">[hidden] { display: none !important; }
</code></pre>
<p>The workspace uses <code>display: grid</code> and the draft bar uses <code>display: flex</code>. Those rules are more specific than the browser's default style for the <code>hidden</code> attribute, so without this line, hidden elements would still show.</p>
<h3 id="heading-selecting-the-main-elements">Selecting the Main Elements</h3>
<p>At the top of <code>script.js</code>, set up the constants, the state and the element references:</p>
<pre><code class="language-javascript">// ---------- Constants ----------
const PAPERS = {
  a4: [595.28, 841.89],
  letter: [612, 792],
  a3: [841.89, 1190.55],
  slide: [405, 720],
};
const FONTS = {
  sans: "Arial, Helvetica, 'Noto Sans', sans-serif",
  serif: "Georgia, 'Times New Roman', 'Noto Serif', serif",
  mono: "'Courier New', Courier, monospace",
};
const THUMB_SIZE = 1000;
const ACCEPTED = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];

// ---------- State ----------
const state = {
  frames: [],
  title: '',
  sheet: 0,
  nextId: 1,
  lastDeleted: null,
  opts: {
    layout: 'grid', cols: 3, rows: 2, paper: 'a4', orient: 'landscape',
    label: 'shot', font: 'sans', textSize: 'm', lines: 3,
  },
};

// ---------- Elements ----------
const $ = (id) =&gt; document.getElementById(id);
const els = {
  uploadArea: $('uploadArea'), fileInput: $('fileInput'), selectBtn: $('selectBtn'),
  statusText: $('statusText'), workspace: $('workspace'), frameList: $('frameList'),
  totalTime: $('totalTime'), boardTitle: $('boardTitle'), undoBtn: $('undoBtn'),
  addMoreBtn: $('addMoreBtn'), canvas: $('previewCanvas'), prevBtn: $('prevBtn'),
  nextBtn: $('nextBtn'), sheetInfo: $('sheetInfo'), fileName: $('fileName'),
  quality: $('quality'), downloadBtn: $('downloadBtn'), resetBtn: $('resetBtn'),
  resultText: $('resultText'), draftBar: $('draftBar'), draftText: $('draftText'),
  restoreBtn: $('restoreBtn'), discardBtn: $('discardBtn'),
};
const SETTING_IDS = ['layout', 'cols', 'rows', 'paper', 'orient', 'label', 'font', 'textSize', 'lines'];
</code></pre>
<p>The <code>state</code> object is the single source of truth. The frame list, the preview and the PDF are all built from it, which keeps them in sync.</p>
<p>The paper sizes are in <strong>PDF points</strong>. One point is 1/72 of an inch, so an A4 page is 595.28 × 841.89 points. You'll do all layout math in points and only convert to pixels when drawing.</p>
<h2 id="heading-adding-and-loading-images">Adding and Loading Images</h2>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/c8b91f4a-2a88-490c-b52e-fd9cb215e46d.png" alt="c8b91f4a-2a88-490c-b52e-fd9cb215e46d" style="display: block;" width="763" height="436" loading="lazy">

<h3 id="heading-opening-files-from-the-button-or-by-dropping-them">Opening Files from the Button or by Dropping Them</h3>
<p>The "Select images" button opens the hidden file input, and dropping files anywhere on the page adds them too:</p>
<pre><code class="language-javascript">// ---------- Upload area ----------
els.selectBtn.addEventListener('click', () =&gt; els.fileInput.click());
els.addMoreBtn.addEventListener('click', () =&gt; els.fileInput.click());
els.fileInput.addEventListener('change', () =&gt; {
  addFiles(els.fileInput.files);
  els.fileInput.value = '';
});

['dragenter', 'dragover'].forEach((type) =&gt; {
  document.addEventListener(type, (e) =&gt; {
    if (!e.dataTransfer.types.includes('Files')) return;
    e.preventDefault();
    els.uploadArea.classList.add('dragover');
  });
});
['dragleave', 'drop'].forEach((type) =&gt; {
  document.addEventListener(type, () =&gt; els.uploadArea.classList.remove('dragover'));
});
document.addEventListener('drop', (e) =&gt; {
  if (!e.dataTransfer.files.length) return;
  e.preventDefault();
  addFiles(e.dataTransfer.files);
});

function showWorkspace() {
  els.uploadArea.hidden = true;
  els.draftBar.hidden = true;
  els.workspace.hidden = false;
}
</code></pre>
<p>Resetting <code>fileInput.value</code> after each pick lets the user choose the same file again later. The <code>dataTransfer.types.includes('Files')</code> check makes sure the drop highlight only appears for files, not for frames being dragged inside the list.</p>
<h3 id="heading-fixing-phone-photo-rotation">Fixing Phone Photo Rotation</h3>
<p>Phones don't rotate the pixels when you hold them sideways. They save the image in the sensor's orientation and add an EXIF tag that says "rotate this 90° when you show it."</p>
<p>If you draw such a photo on a canvas with an <code>img</code> element in some browsers, or read its width and height before the rotation is applied, the frame comes out sideways or with the wrong shape.</p>
<p><code>createImageBitmap</code> with <code>imageOrientation: 'from-image'</code> asks the browser to apply the EXIF rotation while decoding:</p>
<pre><code class="language-javascript">// ---------- Loading images ----------
// Phone photos store their rotation in EXIF. imageOrientation: 'from-image'
// asks the browser to apply it, so the picture comes out the right way up.
function decodeImage(blob) {
  if ('createImageBitmap' in window) {
    return createImageBitmap(blob, { imageOrientation: 'from-image' })
      .catch(() =&gt; loadWithImgTag(blob));
  }
  return loadWithImgTag(blob);
}

function loadWithImgTag(blob) {
  return new Promise((resolve, reject) =&gt; {
    const url = URL.createObjectURL(blob);
    const img = new Image();
    img.onload = () =&gt; { URL.revokeObjectURL(url); resolve(img); };
    img.onerror = () =&gt; { URL.revokeObjectURL(url); reject(new Error('decode')); };
    img.src = url;
  });
}

function canvasToBlob(canvas, type, quality) {
  return new Promise((resolve, reject) =&gt; {
    canvas.toBlob((b) =&gt; (b ? resolve(b) : reject(new Error('encode'))), type, quality);
  });
}
</code></pre>
<p>If <code>createImageBitmap</code> isn't available or fails, the code falls back to a normal <code>img</code> element. Modern browsers apply EXIF rotation to <code>img</code> elements by default too.</p>
<p><code>canvasToBlob</code> wraps the callback-based <code>canvas.toBlob()</code> in a Promise, so you can use it with <code>await</code>.</p>
<h3 id="heading-making-a-frame-object-with-a-thumbnail">Making a Frame Object with a Thumbnail</h3>
<p>A phone photo can be 4000 × 3000 pixels or more. Drawing dozens of those every time the user types a letter would make the preview slow.</p>
<p>So each frame keeps the original file for the PDF, plus a small JPEG copy (at most 1000 pixels on its longest side) for the frame list and the preview:</p>
<pre><code class="language-javascript">async function makeFrame(file) {
  const pic = await decodeImage(file);
  const w = pic.naturalWidth || pic.width;
  const h = pic.naturalHeight || pic.height;

  // A small copy for the frame list and the preview
  const scale = Math.min(1, THUMB_SIZE / Math.max(w, h));
  const c = document.createElement('canvas');
  c.width = Math.round(w * scale);
  c.height = Math.round(h * scale);
  const ctx = c.getContext('2d');
  ctx.fillStyle = '#ffffff';
  ctx.fillRect(0, 0, c.width, c.height);
  ctx.drawImage(pic, 0, 0, c.width, c.height);
  if (pic.close) pic.close();

  const thumb = await canvasToBlob(c, 'image/jpeg', 0.86);
  return {
    id: 'f' + state.nextId++,
    blob: file, name: file.name, w, h,
    thumb, thumbUrl: URL.createObjectURL(thumb), thumbPic: null,
    title: '', desc: '', dur: '',
  };
}
</code></pre>
<p>Notice that <code>w</code> and <code>h</code> are read after decoding, so they're the size <strong>after</strong> rotation. A portrait phone photo gets a portrait frame.</p>
<p>The white fill before drawing matters for PNG images with transparency. JPEG has no transparency, so transparent areas would otherwise turn black.</p>
<h3 id="heading-sorting-by-file-name">Sorting by File Name</h3>
<p>People name their files <code>shot-1.jpg</code>, <code>shot-2.jpg</code> … <code>shot-10.jpg</code>. A normal string sort puts <code>shot-10</code> before <code>shot-2</code>, because it compares the character <code>1</code> with <code>2</code>.</p>
<p><code>localeCompare</code> with the <code>numeric</code> option compares the numbers inside the names as numbers:</p>
<pre><code class="language-javascript">// "shot-2.jpg" before "shot-10.jpg"
function naturalCompare(a, b) {
  return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
}
</code></pre>
<h3 id="heading-adding-the-files">Adding the Files</h3>
<p><code>addFiles</code> filters out unsupported files, sorts the rest, turns each into a frame and reports anything it skipped:</p>
<pre><code class="language-javascript">async function addFiles(fileList) {
  const files = Array.from(fileList);
  const images = files.filter((f) =&gt; ACCEPTED.includes(f.type))
    .sort((a, b) =&gt; naturalCompare(a.name, b.name));
  const skipped = files.length - images.length;
  let failed = 0;

  for (let i = 0; i &lt; images.length; i++) {
    els.statusText.textContent = `Reading image ${i + 1} of ${images.length}...`;
    try {
      state.frames.push(await makeFrame(images[i]));
    } catch (err) {
      failed++;
    }
  }

  const notes = [];
  if (skipped) notes.push(`${skipped} file(s) skipped: not JPG, PNG, WebP or GIF`);
  if (failed) notes.push(`${failed} image(s) couldn't be read`);
  els.statusText.textContent = notes.join('. ');

  if (state.frames.length) {
    showWorkspace();
    renderFrameList();
    drawPreview();
    saveDraftSoon();
  }
}
</code></pre>
<p>The images are read one at a time, not all at once with <code>Promise.all</code>. Decoding 50 large photos in parallel can run a phone out of memory, and reading them in order also keeps the status message accurate.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/e1448353-0611-4577-9f23-fff32621dd03.png" alt="The workspace after adding images: frame cards on the left, settings in the middle, the preview on the right" style="display: block;" width="988" height="687" loading="lazy">

<h2 id="heading-managing-the-frames">Managing the Frames</h2>
<h3 id="heading-the-frame-card">The Frame Card</h3>
<p>Each frame gets a card with its thumbnail, a title field, a description box, a duration field and three buttons:</p>
<pre><code class="language-javascript">// ---------- Frame list ----------
function escapeHtml(s) {
  const map = { '&amp;': '&amp;amp;', '&lt;': '&amp;lt;', '&gt;': '&amp;gt;', '"': '&amp;quot;', "'": '&amp;#39;' };
  return String(s).replace(/[&amp;&lt;&gt;"']/g, (c) =&gt; map[c]);
}

function renderFrameList() {
  els.frameList.innerHTML = state.frames.map((f, i) =&gt; `
    &lt;li class="frame-card" data-id="${f.id}"&gt;
      &lt;img src="${f.thumbUrl}" alt="" draggable="true"&gt;
      &lt;div&gt;
        &lt;span class="num"&gt;${i + 1}. ${escapeHtml(f.name)}&lt;/span&gt;
        &lt;input type="text" data-field="title" placeholder="Title" value="${escapeHtml(f.title)}"&gt;
        &lt;textarea data-field="desc" placeholder="What happens"&gt;${escapeHtml(f.desc)}&lt;/textarea&gt;
        &lt;input type="number" data-field="dur" min="0" step="0.5" placeholder="Seconds" value="${f.dur}"&gt;
        &lt;div class="frame-tools"&gt;
          &lt;button type="button" data-act="up" aria-label="Move frame ${i + 1} up"&gt;Up&lt;/button&gt;
          &lt;button type="button" data-act="down" aria-label="Move frame ${i + 1} down"&gt;Down&lt;/button&gt;
          &lt;button type="button" data-act="delete" aria-label="Delete frame ${i + 1}"&gt;Delete&lt;/button&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/li&gt;`).join('');
  updateTotal();
}

function updateTotal() {
  const total = totalDuration();
  els.totalTime.textContent = `${state.frames.length} frames` + (total ? `, ${formatDuration(total)}` : '');
}

function findFrame(el) {
  const li = el.closest('[data-id]');
  return li ? state.frames.findIndex((f) =&gt; f.id === li.dataset.id) : -1;
}
</code></pre>
<p>Titles and descriptions come from the user, so they're escaped before going into the HTML. Without <code>escapeHtml</code>, a title like <code>Shot "A"</code> would break the <code>value</code> attribute.</p>
<h3 id="heading-updating-the-state-while-typing">Updating the State While Typing</h3>
<p>If you rebuilt the whole list on every key press, the text field would lose focus after each letter. Instead, one <code>input</code> listener on the list updates only the state:</p>
<pre><code class="language-javascript">els.frameList.addEventListener('input', (e) =&gt; {
  const i = findFrame(e.target);
  const field = e.target.dataset.field;
  if (i &lt; 0 || !field) return;
  state.frames[i][field] = e.target.value;
  updateTotal();
  drawPreviewSoon();
  saveDraftSoon();
});
</code></pre>
<p>This uses <strong>event delegation</strong>: one listener on the list handles every field in every card, including cards added later. The <code>data-field</code> attribute tells it which property to update.</p>
<p>The preview redraw is delayed with <code>drawPreviewSoon()</code>, which you'll write later, so it runs once when the user pauses typing rather than on every letter.</p>
<h3 id="heading-durations-and-the-total-running-time">Durations and the Total Running Time</h3>
<p>Durations are stored in seconds and shown as <code>4.5 s</code> under a minute or <code>1:10</code> from one minute up:</p>
<pre><code class="language-javascript">// ---------- Durations ----------
function formatDuration(seconds) {
  const s = Number(seconds) || 0;
  if (s &lt;= 0) return '';
  if (s &lt; 60) return `${Math.round(s * 10) / 10} s`;
  const m = Math.floor(s / 60);
  const r = Math.round(s - m * 60);
  return `${m}:${String(r).padStart(2, '0')}`;
}

function totalDuration() {
  return state.frames.reduce((sum, f) =&gt; sum + (Number(f.dur) || 0), 0);
}
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/da223063-25f9-41e3-bb7e-c790862be4f9.png" alt="A frame card with a title, description and duration filled" style="display: block;" width="630" height="701" loading="lazy">

<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/8e63a168-7ccc-43bf-a791-55e88aed6e6a.png" alt="8e63a168-7ccc-43bf-a791-55e88aed6e6a" style="display: block;" width="615" height="453" loading="lazy">

<h3 id="heading-reordering-frames">Reordering Frames</h3>
<p>The Up and Down buttons, and the Delete button, are handled by one click listener:</p>
<pre><code class="language-javascript">els.frameList.addEventListener('click', (e) =&gt; {
  const btn = e.target.closest('[data-act]');
  if (!btn) return;
  const i = findFrame(btn);
  if (btn.dataset.act === 'up') moveFrame(i, i - 1);
  if (btn.dataset.act === 'down') moveFrame(i, i + 1);
  if (btn.dataset.act === 'delete') deleteFrame(i);
});

function moveFrame(from, to) {
  if (to &lt; 0 || to &gt;= state.frames.length || from === to) return;
  const [frame] = state.frames.splice(from, 1);
  state.frames.splice(to, 0, frame);
  renderFrameList();
  drawPreview();
  saveDraftSoon();
}
</code></pre>
<p><code>splice(from, 1)</code> removes the frame, and <code>splice(to, 0, frame)</code> puts it back at its new position.</p>
<p>For mouse users, dragging a thumbnail onto another card moves it there. The HTML5 drag and drop API needs <code>preventDefault()</code> in <code>dragover</code>, or the browser won't allow the drop:</p>
<pre><code class="language-javascript">// Drag a thumbnail onto another card to move it there
let dragIndex = -1;
els.frameList.addEventListener('dragstart', (e) =&gt; {
  dragIndex = findFrame(e.target);
  e.dataTransfer.effectAllowed = 'move';
  e.target.closest('li').classList.add('dragging');
});
els.frameList.addEventListener('dragover', (e) =&gt; {
  if (dragIndex &gt; -1) e.preventDefault();
});
els.frameList.addEventListener('drop', (e) =&gt; {
  if (dragIndex &lt; 0) return;
  e.preventDefault();
  e.stopPropagation();
  const to = findFrame(e.target);
  moveFrame(dragIndex, to &lt; 0 ? state.frames.length - 1 : to);
  dragIndex = -1;
});
els.frameList.addEventListener('dragend', () =&gt; {
  dragIndex = -1;
  els.frameList.querySelectorAll('.dragging').forEach((li) =&gt; li.classList.remove('dragging'));
});
</code></pre>
<p><code>stopPropagation()</code> in the <code>drop</code> handler stops the document-level drop handler from treating the move as a new file drop.</p>
<p>Keep the Up and Down buttons even with drag and drop. Drag and drop doesn't work with a keyboard, and it's awkward on touch screens.</p>
<h3 id="heading-deleting-a-frame-with-undo">Deleting a Frame with Undo</h3>
<p>Deleting a frame that has a long description typed into it is painful if it was a mistake. So the tool keeps the last deleted frame and its position:</p>
<pre><code class="language-javascript">function deleteFrame(i) {
  const [frame] = state.frames.splice(i, 1);
  state.lastDeleted = { frame, index: i };
  els.undoBtn.hidden = false;
  renderFrameList();
  drawPreview();
  saveDraftSoon();
}

els.undoBtn.addEventListener('click', () =&gt; {
  if (!state.lastDeleted) return;
  const { frame, index } = state.lastDeleted;
  state.frames.splice(Math.min(index, state.frames.length), 0, frame);
  state.lastDeleted = null;
  els.undoBtn.hidden = true;
  renderFrameList();
  drawPreview();
  saveDraftSoon();
});
</code></pre>
<p><code>Math.min(index, state.frames.length)</code> puts the frame back at the end if the list got shorter in the meantime.</p>
<h2 id="heading-building-the-board-settings">Building the Board Settings</h2>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/8a3aec24-4fd1-4f31-8cfc-af63f04b1112.png" alt="The Board settings panel with Layout, Columns, Rows, Paper, Orientation, Frame label, Font and Text size" style="display: block;" width="589" height="575" loading="lazy">

<p>All settings are read into <code>state.opts</code> in one place, with the number fields limited to a sensible range:</p>
<pre><code class="language-javascript">// ---------- Settings ----------
function readSettings() {
  const o = state.opts;
  SETTING_IDS.forEach((id) =&gt; { o[id] = $(id).value; });
  o.cols = Math.min(6, Math.max(1, parseInt(o.cols, 10) || 1));
  o.rows = Math.min(6, Math.max(1, parseInt(o.rows, 10) || 1));
  o.lines = Math.min(6, Math.max(1, parseInt(o.lines, 10) || 1));
}

SETTING_IDS.forEach((id) =&gt; {
  $(id).addEventListener('change', () =&gt; {
    readSettings();
    state.sheet = 0;
    drawPreview();
  });
});

els.boardTitle.addEventListener('input', () =&gt; {
  state.title = els.boardTitle.value.trim();
  drawPreviewSoon();
  saveDraftSoon();
});
</code></pre>
<p>Any change goes back to the first sheet and redraws the preview. The board title is saved as a draft too, because it's part of the user's work.</p>
<p>The four layouts change only the arrangement. The frame data stays the same, so users can switch layouts freely without losing anything.</p>
<h2 id="heading-laying-out-a-storyboard-sheet">Laying Out a Storyboard Sheet</h2>
<p>This is the heart of the tool. Before drawing anything, the code works out <strong>where every box goes</strong>, in PDF points from the top-left corner of the sheet.</p>
<p>Keeping layout separate from drawing means the same layout is used for the small preview on screen and for the 300 dpi PDF. They can't drift apart.</p>
<h3 id="heading-calculating-the-sheet-size">Calculating the Sheet Size</h3>
<pre><code class="language-javascript">// ---------- Layout: where everything goes, in PDF points from the top-left ----------
function sheetSize(o) {
  const [a, b] = PAPERS[o.paper];
  const short = Math.min(a, b);
  const long = Math.max(a, b);
  return o.orient === 'portrait' ? [short, long] : [long, short];
}
</code></pre>
<p>The paper sizes are stored once. Landscape just swaps the short and long sides.</p>
<h3 id="heading-laying-out-the-frame-boxes">Laying Out the Frame Boxes</h3>
<pre><code class="language-javascript">function computeLayout(o, frameCount) {
  const [W, H] = sheetSize(o);
  const short = Math.min(W, H);
  const margin = short * 0.05;
  const gap = 10;
  const cols = o.layout === 'page' ? 1 : o.cols;
  const rows = o.layout === 'page' ? 1 : o.rows;
  const perSheet = cols * rows;
  const sheets = Math.max(1, Math.ceil(frameCount / perSheet));

  const headH = short * 0.045;              // the title row at the top of each sheet
  const top = margin + headH + margin * 0.5;
  const box = { x: margin, y: top, w: W - 2 * margin, h: H - top - margin };
  const sizeScale = { s: 0.85, m: 1, l: 1.2 }[o.textSize];

  const cellW = (box.w - (cols - 1) * gap) / cols;
  const cellH = (box.h - (rows - 1) * gap) / rows;
  const cells = [];

  for (let r = 0; r &lt; rows; r++) {
    for (let c = 0; c &lt; cols; c++) {
      const x = box.x + c * (cellW + gap);
      const y = box.y + r * (cellH + gap);
      const fs = Math.min(13, Math.max(6.5, cellW * 0.05)) * sizeScale;
      const lh = fs * 1.3;

      if (o.layout === 'notes') {
        // picture on the left, title and ruled lines on the right
        const imgW = Math.min(cellW * 0.5, cellH * 1.6);
        const tx = x + imgW + 8;
        cells.push({ img: { x, y, w: imgW, h: cellH }, text: { x: tx, y, w: x + cellW - tx, h: cellH }, fs, lh, notes: true });
      } else {
        // picture on top, text underneath
        const textH = lh * (1.2 + Number(o.lines)) + fs * 0.6;
        const imgH = Math.max(10, cellH - textH);
        cells.push({ img: { x, y, w: cellW, h: imgH }, text: { x, y: y + imgH + fs * 0.6, w: cellW, h: textH - fs * 0.6 }, fs, lh, strip: o.layout === 'strip' });
      }
    }
  }
  return { W, H, margin, headH, perSheet, sheets, cells };
}
</code></pre>
<p>Here's what happens step by step:</p>
<ol>
<li>The margin is <code>5%</code> of the short side, so it scales with the paper.</li>
<li>The "One frame per page" layout is a 1 × 1 grid.</li>
<li>The number of sheets is the number of frames divided by the frames per sheet, rounded up.</li>
<li>A row at the top is kept for the sheet heading.</li>
<li>The remaining box is split into equal cells with a fixed gap.</li>
<li>The font size depends on the cell width (<code>5%</code> of it), kept between <code>6.5</code> and <code>13</code> points, then scaled by the Text size setting.</li>
<li>In most layouts, the picture sits on top and the text underneath. The text area is sized for the label line plus the chosen number of description lines.</li>
<li>In "Panels with notes", the picture is on the left and the text and ruled lines on the right.</li>
</ol>
<p>Each cell ends up with an <code>img</code> box and a <code>text</code> box, and that's all the drawing code needs to know.</p>
<h3 id="heading-fitting-an-image-without-stretching-it">Fitting an Image Without Stretching It</h3>
<p>A cell is rarely the same shape as the picture. Stretching would distort faces and products, and cropping might cut off what matters. So the picture is scaled to fit inside the box, keeping its proportions, and centered:</p>
<pre><code class="language-javascript">function fitContain(imgW, imgH, box) {
  const s = Math.min(box.w / imgW, box.h / imgH);
  const w = imgW * s;
  const h = imgH * s;
  return { x: box.x + (box.w - w) / 2, y: box.y + (box.h - h) / 2, w, h };
}
</code></pre>
<p>This is the same idea as <code>object-fit: contain</code> in CSS. The smaller of the two scale factors wins, so the whole picture always fits.</p>
<h2 id="heading-drawing-a-sheet-on-the-canvas">Drawing a Sheet on the Canvas</h2>
<h3 id="heading-wrapping-text-into-lines">Wrapping Text into Lines</h3>
<p>Canvas has no automatic line wrapping. <code>fillText</code> draws one line, however long it is. So you measure words with <code>measureText</code> and build the lines yourself:</p>
<pre><code class="language-javascript">// ---------- Text ----------
function wrapText(ctx, text, maxWidth, maxLines) {
  const words = String(text).trim().split(/\s+/).filter(Boolean);
  const lines = [];
  let line = '';
  for (const word of words) {
    const test = line ? line + ' ' + word : word;
    if (ctx.measureText(test).width &lt;= maxWidth || !line) {
      line = test;
    } else {
      lines.push(line);
      line = word;
    }
  }
  if (line) lines.push(line);

  if (lines.length &gt; maxLines) {
    lines.length = maxLines;
    let last = lines[maxLines - 1];
    while (last &amp;&amp; ctx.measureText(last + '…').width &gt; maxWidth) last = last.slice(0, -1);
    lines[maxLines - 1] = last.trimEnd() + '…';
  }
  return lines;
}
</code></pre>
<p>If the description is longer than the lines available, the last line ends with an ellipsis, so the user can see that text was cut.</p>
<h3 id="heading-drawing-labels-titles-and-durations">Drawing Labels, Titles and Durations</h3>
<pre><code class="language-javascript">function frameLabel(o, index) {
  if (o.label === 'number') return String(index + 1);
  if (o.label === 'scene') return `Scene ${index + 1}`;
  if (o.label === 'shot') return `Shot ${index + 1}`;
  return '';
}

function drawFrameText(ctx, o, cell, frame, index, k) {
  const fs = cell.fs * k;
  const lh = cell.lh * k;
  const x = cell.text.x * k;
  const w = cell.text.w * k;
  let y = cell.text.y * k + fs;

  ctx.fillStyle = '#16181b';
  ctx.textBaseline = 'alphabetic';

  // Line 1: label and title on the left, duration on the right
  const dur = formatDuration(frame.dur);
  let room = w;
  if (dur) {
    ctx.font = `${fs}px ${FONTS.mono}`;
    ctx.textAlign = 'right';
    ctx.fillText(dur, x + w, y);
    room -= ctx.measureText(dur).width + fs;
  }
  ctx.textAlign = 'left';
  const head = [frameLabel(o, index), frame.title.trim()].filter(Boolean).join('  ');
  if (head) {
    ctx.font = `bold ${fs}px ${FONTS[o.font]}`;
    ctx.fillText(wrapText(ctx, head, room, 1)[0] || '', x, y);
  }
  y += lh * 1.2;

  // Description, wrapped and cut to the chosen number of lines
  ctx.font = `${fs}px ${FONTS[o.font]}`;
  const maxLines = cell.notes ? Math.floor((cell.text.h * k - lh * 1.2) / lh) : Number(o.lines);
  const lines = frame.desc.trim() ? wrapText(ctx, frame.desc, w, maxLines) : [];
  lines.forEach((line, j) =&gt; ctx.fillText(line, x, y + j * lh));

  // Ruled lines for handwritten notes
  if (cell.notes) {
    ctx.strokeStyle = '#c9c6bd';
    ctx.lineWidth = Math.max(1, 0.6 * k);
    const bottom = (cell.text.y + cell.text.h) * k;
    for (let ly = y + lines.length * lh; ly &lt; bottom - 2; ly += lh * 1.25) {
      ctx.beginPath();
      ctx.moveTo(x, ly);
      ctx.lineTo(x + w, ly);
      ctx.stroke();
    }
  }
}
</code></pre>
<p>The parameter <code>k</code> is the scale from points to pixels. All positions come from the layout in points and are multiplied by <code>k</code> just before drawing. That's what lets the same function draw a 600-pixel preview and a 300 dpi PDF page.</p>
<p>The duration is drawn first, right-aligned, and the space it takes is subtracted from the room left for the label and title. That way a long title never runs into the duration.</p>
<h3 id="heading-drawing-the-whole-sheet">Drawing the Whole Sheet</h3>
<p><code>drawSheet</code> draws the heading, then each frame on the sheet:</p>
<pre><code class="language-javascript">// ---------- Drawing one sheet ----------
// k turns PDF points into canvas pixels. With mode 'preview' the pictures are
// drawn too; with mode 'overlay' their boxes are left transparent for the PDF.
async function drawSheet(ctx, o, L, sheetIndex, k, mode) {
  const W = L.W * k;
  const H = L.H * k;
  const placed = [];

  ctx.clearRect(0, 0, W, H);
  ctx.fillStyle = '#ffffff';
  ctx.fillRect(0, 0, W, H);

  // Sheet heading: title on the left, total time and sheet number on the right
  const headFs = L.headH * 0.6 * k;
  const base = (L.margin + L.headH * 0.78) * k;
  const total = totalDuration();
  const right = [total ? `Total ${formatDuration(total)}` : '', `Sheet ${sheetIndex + 1} of ${L.sheets}`].filter(Boolean).join(', ');
  ctx.font = `${headFs * 0.72}px ${FONTS.mono}`;
  ctx.fillStyle = '#55585e';
  ctx.textAlign = 'right';
  ctx.fillText(right, W - L.margin * k, base);
  if (state.title) {
    ctx.font = `bold ${headFs}px ${FONTS[o.font]}`;
    ctx.fillStyle = '#16181b';
    ctx.textAlign = 'left';
    ctx.fillText(state.title, L.margin * k, base);
  }
  ctx.strokeStyle = '#c9c6bd';
  ctx.lineWidth = Math.max(1, 0.75 * k);
  ctx.beginPath();
  ctx.moveTo(L.margin * k, (L.margin + L.headH) * k);
  ctx.lineTo(W - L.margin * k, (L.margin + L.headH) * k);
  ctx.stroke();

  const start = sheetIndex * L.perSheet;
  const items = state.frames.slice(start, start + L.perSheet);

  for (let i = 0; i &lt; items.length; i++) {
    const cell = L.cells[i];
    const frame = items[i];

    // Film strip: a dark band with sprocket holes behind the picture
    if (cell.strip) {
      const b = cell.img;
      const hole = b.h * 0.08;
      ctx.fillStyle = '#16181b';
      ctx.fillRect(b.x * k, b.y * k, b.w * k, b.h * k);
      ctx.fillStyle = '#ffffff';
      for (let hx = b.x + hole; hx + hole &lt; b.x + b.w; hx += hole * 2) {
        ctx.fillRect(hx * k, (b.y + hole * 0.3) * k, hole * k, hole * 0.5 * k);
        ctx.fillRect(hx * k, (b.y + b.h - hole * 0.8) * k, hole * k, hole * 0.5 * k);
      }
    }

    const area = cell.strip
      ? { x: cell.img.x, y: cell.img.y + cell.img.h * 0.12, w: cell.img.w, h: cell.img.h * 0.76 }
      : cell.img;
    const rect = fitContain(frame.w, frame.h, area);
    placed.push({ frame, rect });

    const px = { x: Math.round(rect.x * k), y: Math.round(rect.y * k), w: Math.round(rect.w * k), h: Math.round(rect.h * k) };
    if (mode === 'overlay') {
      ctx.clearRect(px.x, px.y, px.w, px.h);
    } else {
      if (!frame.thumbPic) frame.thumbPic = await decodeImage(frame.thumb);
      ctx.drawImage(frame.thumbPic, px.x, px.y, px.w, px.h);
    }
    if (!cell.strip) {
      ctx.strokeStyle = '#16181b';
      ctx.lineWidth = Math.max(1, 0.9 * k);
      ctx.strokeRect(cell.img.x * k, cell.img.y * k, cell.img.w * k, cell.img.h * k);
    }
    drawFrameText(ctx, o, cell, frame, start + i, k);
  }
  return placed;
}
</code></pre>
<p>The <code>mode</code> parameter is the important trick here:</p>
<ul>
<li>In <code>'preview'</code> mode, the pictures are drawn from the thumbnails.</li>
<li>In <code>'overlay'</code> mode, the picture areas are <strong>cleared</strong> to transparent, and the function returns where each picture should go.</li>
</ul>
<p>You'll see why in the PDF section. For the film strip, the dark band and the sprocket holes are drawn first, and the picture sits in the middle of the band.</p>
<h2 id="heading-previewing-the-sheets">Previewing the Sheets</h2>
<p>The preview draws the current sheet at the canvas's on-screen width, multiplied by the device pixel ratio so it stays sharp on high-density screens:</p>
<pre><code class="language-javascript">// ---------- Preview ----------
let previewTimer = null;
function drawPreviewSoon() {
  clearTimeout(previewTimer);
  previewTimer = setTimeout(drawPreview, 150);
}

async function drawPreview() {
  if (!state.frames.length) return;
  const o = state.opts;
  const L = computeLayout(o, state.frames.length);
  state.sheet = Math.min(state.sheet, L.sheets - 1);

  // Draw at the canvas's on-screen width, sharp on high-density screens
  const cssWidth = els.canvas.clientWidth || 600;
  const k = (cssWidth * Math.min(2, window.devicePixelRatio || 1)) / L.W;
  els.canvas.width = Math.round(L.W * k);
  els.canvas.height = Math.round(L.H * k);
  await drawSheet(els.canvas.getContext('2d'), o, L, state.sheet, k, 'preview');

  els.sheetInfo.textContent = `Sheet ${state.sheet + 1} of ${L.sheets}`;
  els.prevBtn.disabled = state.sheet === 0;
  els.nextBtn.disabled = state.sheet &gt;= L.sheets - 1;
}

els.prevBtn.addEventListener('click', () =&gt; { state.sheet--; drawPreview(); });
els.nextBtn.addEventListener('click', () =&gt; { state.sheet++; drawPreview(); });
</code></pre>
<p>The device pixel ratio is capped at 2. A 3× phone screen would otherwise create a canvas nine times the size of the CSS box, which is slow and adds little you can see.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/302d3915-0eec-4a62-a53f-85a617bd7c5b.png" alt="The preview of a grid sheet with 6 frames, the sheet title, total time and &quot;Sheet 1 of 2&quot;" style="display: block;" width="929" height="574" loading="lazy">

<h2 id="heading-saving-a-draft-with-indexeddb">Saving a Draft with IndexedDB</h2>
<p>Writing descriptions for 30 frames takes time. Losing that work to an accidental reload is frustrating, so the tool saves a draft as the user works.</p>
<p><code>localStorage</code> won't do here. It only stores strings, and most browsers limit it to about 5 MB, which is less than two phone photos. IndexedDB can store <code>Blob</code> objects directly and allows far more space.</p>
<h3 id="heading-opening-the-database">Opening the Database</h3>
<pre><code class="language-javascript">// ---------- Draft in IndexedDB ----------
const DB_NAME = 'image-storyboard';
let dbPromise = null;

function openDb() {
  if (!dbPromise) {
    dbPromise = new Promise((resolve, reject) =&gt; {
      const req = indexedDB.open(DB_NAME, 1);
      req.onupgradeneeded = () =&gt; req.result.createObjectStore('drafts');
      req.onsuccess = () =&gt; resolve(req.result);
      req.onerror = () =&gt; reject(req.error);
    });
  }
  return dbPromise;
}

async function dbRun(mode, work) {
  const db = await openDb();
  return new Promise((resolve, reject) =&gt; {
    const tx = db.transaction('drafts', mode);
    const result = work(tx.objectStore('drafts'));
    tx.oncomplete = () =&gt; resolve(result &amp;&amp; result.result);
    tx.onerror = () =&gt; reject(tx.error);
  });
}
</code></pre>
<p><code>dbRun</code> wraps a transaction in a Promise. It resolves when the transaction completes, so a write is only reported as done once it's actually stored.</p>
<h3 id="heading-saving-the-draft">Saving the Draft</h3>
<pre><code class="language-javascript">let saveTimer = null;
function saveDraftSoon() {
  clearTimeout(saveTimer);
  saveTimer = setTimeout(saveDraft, 800);
}

function saveDraft() {
  const draft = {
    title: state.title,
    savedAt: Date.now(),
    frames: state.frames.map(({ blob, name, title, desc, dur }) =&gt; ({ blob, name, title, desc, dur })),
  };
  return dbRun('readwrite', (store) =&gt; store.put(draft, 'current')).catch(() =&gt; {
    els.resultText.textContent = 'This browser could not save a draft. Download the PDF before closing the tab.';
  });
}
</code></pre>
<p>The draft stores the original image files as Blobs, along with the text the user typed. Thumbnails and object URLs aren't stored, because they can be made again from the files.</p>
<p><code>saveDraftSoon</code> waits until the user pauses for 800 ms, so typing a description doesn't write to the database on every key press.</p>
<p>If saving fails, for example in a private window with storage blocked, the tool tells the user to download the PDF before closing the tab instead of failing silently.</p>
<h3 id="heading-restoring-the-draft">Restoring the Draft</h3>
<p>When the page loads, the tool checks for a draft and offers to restore it:</p>
<pre><code class="language-javascript">async function checkDraft() {
  try {
    const draft = await dbRun('readonly', (store) =&gt; store.get('current'));
    if (!draft || !draft.frames.length) return;
    els.draftText.textContent = `You have a saved storyboard with ${draft.frames.length} frames.`;
    els.draftBar.hidden = false;
  } catch (err) { /* no storage: nothing to restore */ }
}

els.restoreBtn.addEventListener('click', async () =&gt; {
  const draft = await dbRun('readonly', (store) =&gt; store.get('current'));
  for (const saved of draft.frames) {
    const file = new File([saved.blob], saved.name, { type: saved.blob.type });
    const frame = await makeFrame(file);
    Object.assign(frame, { title: saved.title, desc: saved.desc, dur: saved.dur });
    state.frames.push(frame);
  }
  state.title = draft.title || '';
  els.boardTitle.value = state.title;
  showWorkspace();
  renderFrameList();
  drawPreview();
});

els.discardBtn.addEventListener('click', () =&gt; {
  dbRun('readwrite', (store) =&gt; store.delete('current'));
  els.draftBar.hidden = true;
});
</code></pre>
<p>Each saved Blob goes back through <code>makeFrame</code>, so restored frames get fresh thumbnails, and then the saved text is copied onto them.</p>
<h2 id="heading-generating-the-pdf-with-pdf-lib">Generating the PDF with PDF-lib</h2>
<p>The simplest way to make the PDF would be to draw each whole sheet on a canvas, with the pictures, and put that canvas in the PDF as one image. It works, but it forces a choice:</p>
<ul>
<li>Save it as PNG and the photos make the file huge.</li>
<li>Save it as JPEG and the text and thin lines get blurry edges.</li>
</ul>
<p>So the tool uses <strong>two layers</strong> on each page:</p>
<ol>
<li><strong>Pictures</strong> as JPEG, each at the resolution the user chose, placed exactly in its box</li>
<li><strong>Text, labels and lines</strong> as one transparent PNG at 300 dpi, covering the whole page on top</li>
</ol>
<p>JPEG is good for photos, and PNG keeps text sharp. This is why <code>drawSheet</code> has the <code>'overlay'</code> mode that leaves holes where the pictures go.</p>
<h3 id="heading-turning-each-picture-into-a-jpeg">Turning Each Picture into a JPEG</h3>
<pre><code class="language-javascript">// ---------- Making the PDF ----------
async function imageAsJpeg(frame, widthPx, heightPx) {
  const pic = await decodeImage(frame.blob);
  const c = document.createElement('canvas');
  c.width = Math.max(1, Math.round(widthPx));
  c.height = Math.max(1, Math.round(heightPx));
  const ctx = c.getContext('2d');
  ctx.fillStyle = '#ffffff';              // transparent PNGs get a white background
  ctx.fillRect(0, 0, c.width, c.height);
  ctx.imageSmoothingQuality = 'high';
  ctx.drawImage(pic, 0, 0, c.width, c.height);
  if (pic.close) pic.close();
  const blob = await canvasToBlob(c, 'image/jpeg', 0.9);
  return new Uint8Array(await blob.arrayBuffer());
}
</code></pre>
<p>The picture is decoded again from the <strong>original</strong> file, not from the thumbnail, so the PDF has full quality.</p>
<h3 id="heading-building-the-pages">Building the Pages</h3>
<pre><code class="language-javascript">async function buildPdf() {
  const { PDFDocument } = PDFLib;
  const o = state.opts;
  const L = computeLayout(o, state.frames.length);
  const dpi = Number(els.quality.value);
  const k = 300 / 72;                         // text layer at 300 dpi

  const pdf = await PDFDocument.create();
  for (let s = 0; s &lt; L.sheets; s++) {
    els.resultText.textContent = `Making sheet ${s + 1} of ${L.sheets}...`;
    const page = pdf.addPage([L.W, L.H]);

    // 1. Text, labels and lines on a canvas, with holes where the pictures go
    const c = document.createElement('canvas');
    c.width = Math.round(L.W * k);
    c.height = Math.round(L.H * k);
    const placed = await drawSheet(c.getContext('2d'), o, L, s, k, 'overlay');

    // 2. Each picture as a JPEG at the chosen resolution, placed in its hole
    for (const { frame, rect } of placed) {
      const scale = Math.min(1, (rect.w * dpi / 72) / frame.w);
      const jpg = await pdf.embedJpg(await imageAsJpeg(frame, frame.w * scale, frame.h * scale));
      // PDF y runs from the bottom of the page, the canvas y from the top
      page.drawImage(jpg, { x: rect.x, y: L.H - rect.y - rect.h, width: rect.w, height: rect.h });
    }

    // 3. The text layer on top, as one transparent PNG covering the page
    const pngBlob = await canvasToBlob(c, 'image/png');
    const png = await pdf.embedPng(new Uint8Array(await pngBlob.arrayBuffer()));
    page.drawImage(png, { x: 0, y: 0, width: L.W, height: L.H });
    c.width = 1;                               // free the canvas memory
  }

  pdf.setTitle(state.title || 'Storyboard');
  return pdf.save();
}
</code></pre>
<p>Here's what happens on each page:</p>
<ol>
<li><code>addPage([L.W, L.H])</code> creates a page in points, the same units as the layout.</li>
<li>The text layer is drawn at <code>k = 300 / 72</code>, which is 300 pixels per inch.</li>
<li>Each picture is resized to the chosen dpi for the size it has on the page. A 4000-pixel photo shown 2 inches wide only needs 600 pixels at 300 dpi, so the file stays small. <code>Math.min(1, ...)</code> makes sure small pictures are never enlarged.</li>
<li>The pictures are drawn first, then the transparent PNG on top of them.</li>
</ol>
<p>Note the y coordinate: <code>L.H - rect.y - rect.h</code>. The layout and the canvas measure y from the <strong>top</strong> of the page, but PDF measures y from the <strong>bottom</strong>. Forgetting this flip puts every picture upside down in the page, the classic PDF-lib mistake.</p>
<p>Setting <code>c.width = 1</code> after use frees the canvas memory right away, which matters on phones when there are many sheets.</p>
<h2 id="heading-renaming-and-downloading">Renaming and Downloading</h2>
<p>The file name comes from a text field, cleaned of characters that aren't allowed in file names:</p>
<pre><code class="language-javascript">// ---------- Download ----------
function cleanFileName(name) {
  const n = name.trim().replace(/\.pdf$/i, '').replace(/[\\/:*?"&lt;&gt;|]+/g, '-');
  return (n || 'storyboard') + '.pdf';
}

function formatSize(bytes) {
  return bytes &lt; 1024 * 1024 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}

els.downloadBtn.addEventListener('click', async () =&gt; {
  if (!state.frames.length) return;
  els.downloadBtn.disabled = true;
  try {
    const bytes = await buildPdf();
    const name = cleanFileName(els.fileName.value);
    const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
    const a = document.createElement('a');
    a.href = url;
    a.download = name;
    a.click();
    setTimeout(() =&gt; URL.revokeObjectURL(url), 60000);
    els.resultText.textContent = `Saved ${name} (${formatSize(bytes.length)}).`;
  } catch (err) {
    console.error(err);
    els.resultText.textContent = 'The PDF could not be made. Try fewer images or the 150 dpi setting.';
  } finally {
    els.downloadBtn.disabled = false;
  }
});
</code></pre>
<p>The object URL is revoked after a minute, which is long enough for the download to start and frees the memory afterwards. The button is disabled while the PDF is being made, so a double click can't start two exports.</p>
<p>Finally, "Start over" clears the state, the draft and the object URLs. The last two lines of the file read the default settings and check for a saved draft when the page loads:</p>
<pre><code class="language-javascript">// ---------- Start over ----------
els.resetBtn.addEventListener('click', () =&gt; {
  clearTimeout(saveTimer);
  state.frames.forEach((f) =&gt; URL.revokeObjectURL(f.thumbUrl));
  state.frames = [];
  state.title = '';
  state.sheet = 0;
  state.lastDeleted = null;
  els.boardTitle.value = '';
  els.undoBtn.hidden = true;
  els.resultText.textContent = '';
  els.workspace.hidden = true;
  els.uploadArea.hidden = false;
  dbRun('readwrite', (store) =&gt; store.delete('current')).catch(() =&gt; {});
});

readSettings();
checkDraft();
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/fdad77c5-a9f5-4906-8cad-f54190b9f3b2.png" alt="Fille rename, image qulaity download various option" style="display: block;" width="351" height="276" loading="lazy">

<h2 id="heading-demo-how-the-image-storyboard-tool-works">Demo: How the Image Storyboard Tool Works</h2>
<p>Here's the whole workflow in the finished tool.</p>
<h3 id="heading-step-1-add-your-images">Step 1: Add Your Images</h3>
<p>Drop a folder's worth of images on the page or click Select images. They're sorted by file name, so <code>shot-1</code>, <code>shot-2</code> … <code>shot-10</code> land in the right order.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/5ad4654c-d0d8-49f6-b6c1-737407aa1c1d.png" alt="5ad4654c-d0d8-49f6-b6c1-737407aa1c1d" style="display: block;" width="391" height="422" loading="lazy">

<h3 id="heading-step-2-put-the-frames-in-order">Step 2: Put the Frames in Order</h3>
<p>Drag a thumbnail onto another card, or use the Up and Down buttons.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/ffc1cdbd-2114-45e1-8f57-26a5d2557d01.png" alt="A frame being dragged to a new position" style="display: block;" width="940" height="559" loading="lazy">

<h3 id="heading-step-3-write-the-script">Step 3: Write the Script</h3>
<p>Give each frame a title, a description and a duration. The total running time updates as you type.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/015b8081-985b-4965-b392-43630e890bdc.png" alt=" Several frame cards filled in" style="display: block;" width="630" height="701" loading="lazy">

<h3 id="heading-step-4-choose-a-layout">Step 4: Choose a Layout</h3>
<p>Pick one frame per page, a grid, panels with notes or a film strip, then set the paper size and orientation.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/7e512b96-8a4e-42a4-9dc6-4c0d7960c9d1.png" alt="The settings panel with a layout selected" style="display: block;" width="277" height="158" loading="lazy">

<h3 id="heading-step-5-check-the-preview">Step 5: Check the Preview</h3>
<p>Use Previous and Next to look at every sheet before you download.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/3e781d95-ca13-417a-9e2f-bf88e6112cba.png" alt="The preview of the frames" style="display: block;" width="615" height="453" loading="lazy">

<h3 id="heading-step-6-download-the-pdf">Step 6: Download the PDF</h3>
<p>Type a file name, choose the image quality and click Download PDF.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/d9690b9d-7a43-4421-9167-a95d8813b2b3.png" alt="The downloaded PDF open in a PDF viewer" style="display: block;" width="352" height="196" loading="lazy">

<h2 id="heading-performance-tips">Performance Tips</h2>
<p><strong>Use thumbnails for everything on screen.</strong> The preview redraws often, while the user types and changes settings. Drawing 1000-pixel thumbnails instead of full photos keeps it fast. Only the PDF export touches the original files.</p>
<p><strong>Decode thumbnails once.</strong> In <code>drawSheet</code>, each frame keeps its decoded thumbnail in <code>frame.thumbPic</code>, so switching sheets doesn't decode the same image again.</p>
<p><strong>Process images one at a time.</strong> Reading or exporting dozens of large photos with <code>Promise.all</code> can use more memory than a phone has. A simple <code>for</code> loop with <code>await</code> keeps only one large image in memory at a time.</p>
<p><strong>Size pictures for the page, not the camera.</strong> A picture's pixel size in the PDF should depend on how big it is on the page and the chosen dpi. That one line in <code>buildPdf</code> is often the difference between a 3 MB file and a 60 MB file.</p>
<p><strong>Release memory as you go.</strong> Call <code>close()</code> on an <code>ImageBitmap</code> when you're done with it, set used canvases to <code>width = 1</code>, and revoke object URLs you no longer need.</p>
<h2 id="heading-common-mistakes">Common Mistakes</h2>
<p><strong>Sideways phone photos.</strong> If you read an image's size or draw it without applying EXIF orientation, portrait photos come out landscape. Use <code>createImageBitmap(blob, { imageOrientation: 'from-image' })</code>.</p>
<p><strong>Stretched pictures.</strong> Drawing an image straight into a cell with <code>drawImage(img, x, y, cellW, cellH)</code> stretches it. Always fit it with a "contain" calculation like <code>fitContain</code> first.</p>
<p><strong>Wrong order of files.</strong> The order files arrive from a file picker or a drop isn't guaranteed. Sort them yourself, and use a numeric sort so <code>shot-10</code> comes after <code>shot-9</code>.</p>
<p><strong>Forgetting to flip the y axis.</strong> Canvas y goes down from the top, PDF y goes up from the bottom. Convert with <code>pageHeight - y - height</code> when placing anything with PDF-lib.</p>
<p><strong>Black backgrounds on transparent PNGs.</strong> JPEG has no transparency. Fill the canvas with white before drawing a PNG you'll save as JPEG.</p>
<p><strong>Rebuilding the list while the user types.</strong> Re-rendering inputs on every key press moves the cursor and loses focus. Update the state from the <code>input</code> event and only rebuild the list when the order changes.</p>
<p><strong>Canvases that are too large.</strong> Browsers limit canvas size, and phones have tight limits. An A3 page at 300 dpi is about 4960 × 3508 pixels, which is fine, but don't multiply that by the device pixel ratio as well.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you built a browser-based tool that turns a set of images into storyboard sheets and a print-ready PDF.</p>
<p>You learned how to apply phone photo rotation with <code>createImageBitmap</code>, sort file names numerically, keep layout math in PDF points so the preview and the PDF always match, wrap text on a canvas, save a draft of images and text in IndexedDB, and build a two-layer PDF with sharp text and compact photos using PDF-lib.</p>
<p>All of it runs locally in the browser, so the images stay on the user's device.</p>
<p>You can try the full version of this tool, with more options such as sheet colors, a handwritten font, one PDF per frame and PNG export, at <a href="https://allinonetools.net/image-storyboard-to-pdf/">Image Storyboard to PDF</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Agentic Coding with Codex & AI Coding Agents ]]>
                </title>
                <description>
                    <![CDATA[ AI coding agents such as Codex read your codebase, edit multiple files, and run commands and tests while they work through larger tasks with you. In Codex, an AGENTS.md file holds persistent instructi ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-agentic-coding-with-codex-ai-coding-agents/</link>
                <guid isPermaLink="false">6af33ff6e6a1d476dd025c20</guid>
                
                    <category>
                        <![CDATA[ codex ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Tue, 10 Nov 2026 16:01:58 +0000</pubDate>
                <media:content url="https://i.ytimg.com/vi/ajfQWhGQGLE/maxresdefault.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>AI coding agents such as Codex read your codebase, edit multiple files, and run commands and tests while they work through larger tasks with you. In Codex, an AGENTS.md file holds persistent instructions for a project, and config.toml holds the agent's configuration.</p>
<p>We just published a course on the freeCodeCamp.org YouTube channel that will teach you how to get reliable results from a coding agent by giving it the right context, planning the work, controlling its permissions, and verifying every change. This course is taught by Tom Chant, Head of Education at Scrimba.</p>
<p>You'll work through realistic tasks, including challenges on skills, characterization tests, and config.toml. The course is aimed at experienced developers adding AI to their workflow and at non-coders who want to build software with AI help. You can also study it interactively on Scrimba.</p>
<p>In this course, you will learn:</p>
<ul>
<li><strong>Prompting &amp; Project Setup</strong><br>How to write effective prompts and comment prompts for a coding agent, then initialize a project and use multiple AGENTS.md files.</li>
<li><strong>Plan Mode &amp; Skills</strong><br>How to break larger development tasks down with Plan Mode and extend a coding agent with skills.</li>
<li><strong>Testing Agent Changes</strong><br>How to verify an agent's changes with characterization tests and test-driven development (TDD), and which testing pitfalls to look out for.</li>
<li><strong>Git &amp; Secrets</strong><br>How to use Git safely alongside a coding agent and keep API keys, credentials, and other secrets safe.</li>
<li><strong>Context, Permissions &amp; config.toml</strong><br>How to use the VS Code Codex extension, manage context, control what an agent can access and change, and configure it with config.toml.</li>
<li><strong>MCP &amp; shadcn</strong><br>How to connect agents to external tools with the Model Context Protocol (MCP), including shadcn.</li>
</ul>
<p>Watch the full course on the <a href="https://youtu.be/ajfQWhGQGLE">freeCodeCamp.org YouTube channel</a> (2-hour watch).</p>
<div class="embed-wrapper"><iframe width="560" height="315" src="https://www.youtube.com/embed/ajfQWhGQGLE" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Happens When You Upload a Large File & Generate a Temporary Download Link ]]>
                </title>
                <description>
                    <![CDATA[ Sending a 5 GB video file might seem simple. You select the file, click Upload, wait for the progress bar to finish, and share a link with someone. But there are several things happening in the backgr ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-file-transfer-services-work/</link>
                <guid isPermaLink="false">6af31a20042fa071f004461c</guid>
                
                    <category>
                        <![CDATA[ webdev ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Programming Blogs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ backend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reetain Raina ]]>
                </dc:creator>
                <pubDate>Tue, 10 Nov 2026 13:20:32 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5fc16e412cae9c5b190b6cdd/5ab5b73d-ffb5-4c71-91b7-648b69bb79b7.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Sending a 5 GB video file might seem simple. You select the file, click Upload, wait for the progress bar to finish, and share a link with someone. But there are several things happening in the background while the file is being uploaded.</p>
<p>The file has to travel across a network, reach a server, and be stored somewhere before another person can download it. The service also needs to make sure that the recipient can access the file without accessing the sender's account. If the internet connection drops halfway through the upload, it needs a way to continue without sending the entire file again.</p>
<p>File transfer services use HTTP requests, storage systems, databases, encryption, and background processes to manage these tasks. But how does a website actually handle a file that's several gigabytes in size? Does it upload everything in one request? Where does the file go after the upload finishes? And what happens when its download link expires?</p>
<p>In this article, we'll look at how file transfer services handle large uploads, store files, generate download links, and manage interrupted connections and expired transfers. Then, once you understand the theory behind how it all works, we'll also build a basic chunked file uploader using Node.js to see some of these processes in action.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><a href="#heading-why-email-attachments-fail-smtp-wasnt-designed-for-large-files">Why Email Attachments Fail: SMTP Wasn't Designed for Large Files</a><ul>
<li><a href="#heading-smtp-and-attachment-size-limits">SMTP and Attachment Size Limits</a></li>
<li><a href="#heading-the-base64-problem">The Base64 Problem</a></li>
</ul>
</li>
<li><a href="#heading-the-core-architecture-what-happens-behind-a-file-transfer-service">The Core Architecture: What Happens Behind a File Transfer Service?</a><ul>
<li><a href="#heading-the-client">The Client</a></li>
<li><a href="#heading-the-upload-server">The Upload Server</a></li>
<li><a href="#heading-the-storage-layer">The Storage Layer</a></li>
<li><a href="#heading-the-metadata-database">The Metadata Database</a></li>
<li><a href="#heading-the-download-server">The Download Server</a></li>
</ul>
</li>
<li><a href="#heading-chunked-and-resumable-uploads-how-large-files-survive-bad-internet-connections">Chunked and Resumable Uploads: How Large Files Survive Bad Internet Connections</a><ul>
<li><a href="#heading-breaking-a-large-file-into-smaller-chunks">Breaking a Large File Into Smaller Chunks</a></li>
<li><a href="#heading-what-happens-when-the-internet-disconnects">What Happens When the Internet Disconnects?</a></li>
<li><a href="#heading-checksums-making-sure-nothing-gets-corrupted">Checksums: Making Sure Nothing Gets Corrupted</a></li>
</ul>
</li>
<li><a href="#heading-storage-and-link-generation-where-does-your-file-actually-go">Storage and Link Generation: Where Does Your File Actually Go?</a><ul>
<li><a href="#heading-why-services-use-object-storage">Why Services Use Object Storage</a></li>
<li><a href="#heading-how-a-download-link-is-created">How a Download Link Is Created</a></li>
<li><a href="#heading-why-are-these-links-difficult-to-guess">Why Are These Links Difficult to Guess?</a></li>
</ul>
</li>
<li><a href="#heading-expiry-and-cleanup-what-happens-when-a-transfer-expires">Expiry and Cleanup: What Happens When a Transfer Expires?</a><ul>
<li><a href="#heading-time-to-live-ttl">Time to Live (TTL)</a></li>
<li><a href="#heading-automated-cleanup-jobs">Automated Cleanup Jobs</a></li>
<li><a href="#heading-download-limits">Download Limits</a></li>
</ul>
</li>
<li><a href="#heading-security-layers-protecting-files-during-transfer-and-storage">Security Layers: Protecting Files During Transfer and Storage</a><ul>
<li><a href="#heading-tls-encryption-in-transit">TLS Encryption in Transit</a></li>
<li><a href="#heading-encryption-at-rest">Encryption at Rest</a></li>
<li><a href="#heading-password-protected-links">Password-Protected Links</a></li>
</ul>
</li>
<li><a href="#heading-real-world-examples-how-popular-file-transfer-services-handle-file-sharing">Real-World Examples: How Popular File Transfer Services Handle File Sharing</a><ul>
<li><a href="#heading-wetransfer-temporary-transfers-and-password-protection">WeTransfer: Temporary Transfers and Password Protection</a></li>
<li><a href="#heading-dropbox-transfer-sending-files-without-collaboration">Dropbox Transfer: Sending Files Without Collaboration</a></li>
<li><a href="#heading-send-anywhere-direct-transfers-and-temporary-links">Send Anywhere: Direct Transfers and Temporary Links</a></li>
<li><a href="#heading-filemail-large-transfers-and-expiration-controls">Filemail: Large Transfers and Expiration Controls</a></li>
</ul>
</li>
<li><a href="#heading-hands-on-build-a-minimal-chunked-file-uploader-using-nodejs">Hands-On: Build a Minimal Chunked File Uploader Using Node.js</a><ul>
<li><a href="#heading-step-1-set-up-the-nodejs-project">Step 1: Set Up the Node.js Project</a></li>
<li><a href="#heading-step-2-divide-the-file-into-smaller-chunks">Step 2: Divide the File Into Smaller Chunks</a></li>
<li><a href="#heading-step-3-create-an-upload-endpoint-in-express">Step 3: Create an Upload Endpoint in Express</a></li>
<li><a href="#heading-step-4-reassemble-the-original-file">Step 4: Reassemble the Original File</a></li>
<li><a href="#heading-step-5-test-the-upload">Step 5: Test the Upload</a></li>
</ul>
</li>
<li><a href="#heading-conclusion-a-simple-link-hides-a-lot-of-engineering">Conclusion: A Simple Link Hides a Lot of Engineering</a></li>
</ul>
<h2 id="heading-why-email-attachments-fail-smtp-wasnt-designed-for-large-files">Why Email Attachments Fail: SMTP Wasn't Designed for Large Files</h2>
<p>Before looking at dedicated file transfer services, it helps to understand why we can't just attach massive files to an email. Sending large files through email is fundamentally flawed because the underlying architecture was built for text, not high-resolution media.</p>
<h3 id="heading-smtp-and-attachment-size-limits">SMTP and Attachment Size Limits</h3>
<p>Simple Mail Transfer Protocol (SMTP) handles the transmission of email messages across the internet. Because servers have limited bandwidth and storage, email providers impose strict attachment size limits, usually capping out around 25 MB. However, these limits apply to the encoded message size, not just the original file sitting on your hard drive.</p>
<h3 id="heading-the-base64-problem">The Base64 Problem</h3>
<p>Email attachments are commonly encoded using MIME and Base64 formats. Base64 is necessary because it converts binary data into text-compatible characters that email servers can safely route. While this solves the transmission problem, it creates a massive efficiency issue: this encoding increases the data size by approximately 33%.</p>
<p>You can read the foundational specifications for this in <a href="https://datatracker.ietf.org/doc/html/rfc2045"><u>RFC 2045</u></a>, which defines MIME's Base64 transfer encoding. In practice, this means a 30 MB video file will require roughly 40 MB of space before additional message overhead is even calculated, guaranteeing it will bounce back from most email servers.</p>
<h2 id="heading-the-core-architecture-what-happens-behind-a-file-transfer-service">The Core Architecture: What Happens Behind a File Transfer Service?</h2>
<p>To bypass the limitations of email, file transfer services use a specialized, decoupled architecture. Having built a few of these systems myself, I believe establishing a clear mental model of the five major components is crucial for understanding the flow of data.</p>
<h3 id="heading-the-client">The Client</h3>
<p>The journey begins in the client, which is usually a web browser or a desktop application where the sender selects a file. Modern browsers use JavaScript's File API to access file metadata, read the raw contents and intelligently divide the file into smaller, manageable parts before any data hits the network.</p>
<h3 id="heading-the-upload-server">The Upload Server</h3>
<p>Once the client starts sending data, the upload server steps in. This server receives the upload requests, authenticates the user, validates incoming data and coordinates the entire upload process. It acts as the traffic cop, ensuring that chunks of data are arriving in the correct format.</p>
<h3 id="heading-the-storage-layer">The Storage Layer</h3>
<p>Traditional application servers are terrible at holding massive files, so the storage layer handles the actual heavy lifting. Uploaded files are typically routed directly to object storage solutions. This allows the system to scale infinitely without crashing the primary upload servers.</p>
<h3 id="heading-the-metadata-database">The Metadata Database</h3>
<p>While the physical file goes to object storage, the application needs a way to remember what that file is. The metadata database stores critical information, including the original filename, file size, content type, the specific object storage key, a unique transfer identifier and the exact expiration timestamp.</p>
<h3 id="heading-the-download-server">The Download Server</h3>
<p>When someone opens a shared link, the download server takes over. It checks the database to verify permissions and expiration dates, and if everything is valid, it retrieves the stored object from the storage layer for delivery.</p>
<h2 id="heading-chunked-and-resumable-uploads-how-large-files-survive-bad-internet-connections">Chunked and Resumable Uploads: How Large Files Survive Bad Internet Connections</h2>
<p>Transferring a 5 GB file in one continuous network request is a disaster waiting to happen. If a connection drops at 99%, a single-request architecture forces the user to start all over again.</p>
<h3 id="heading-breaking-a-large-file-into-smaller-chunks">Breaking a Large File Into Smaller Chunks</h3>
<p>To solve this, modern clients divide large files into smaller parts, such as 10 MB chunks. Each chunk is uploaded to the server as an independent HTTP request. The server meticulously tracks which chunks have arrived. Some advanced systems even allow multiple chunks to upload simultaneously in parallel, drastically reducing the overall waiting time.</p>
<p>It's important to note that chunked uploads are an architectural pattern, which is entirely different from HTTP chunked transfer encoding (a mechanism for framing an HTTP message body).</p>
<h3 id="heading-what-happens-when-the-internet-disconnects">What Happens When the Internet Disconnects?</h3>
<p>Suppose 80% of a massive file has successfully uploaded when your Wi-Fi randomly disconnects. Without resumable uploads, that progress is lost. With resumable architecture, the client reconnects and asks the server for the upload offset, the exact number of bytes successfully received and stored. The client then seamlessly continues uploading from that exact position.</p>
<h3 id="heading-checksums-making-sure-nothing-gets-corrupted">Checksums: Making Sure Nothing Gets Corrupted</h3>
<p>Network transfers can sometimes flip bits, resulting in corrupted files. To prevent this, clients generate a cryptographic hash (checksum) for an individual chunk before sending it. The server receives the chunk, calculates its own hash, and compares the two. If the checksums don't match, the server rejects the chunk and asks the client to try again.</p>
<p>If you're looking to implement this, the <a href="https://tus.io/"><u>TUS Resumable Upload Protocol</u></a> is a fantastic, standardized reference for managing upload offsets and checksum verification. Also, the <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html"><u>Amazon S3 Multipart Upload Documentation</u></a> provides an industry-standard blueprint for handling parallel transfers and retrying failed parts.</p>
<h2 id="heading-storage-and-link-generation-where-does-your-file-actually-go">Storage and Link Generation: Where Does Your File Actually Go?</h2>
<p>Once every chunk is verified and reassembled, the service needs a secure place to keep the file until the recipient is ready to download it.</p>
<h3 id="heading-why-services-use-object-storage">Why Services Use Object Storage</h3>
<p>In my opinion, attempting to store gigabytes of user uploads on a traditional local server directory is architectural malpractice. Instead, services rely on object storage. Files are stored as flat objects and each object is assigned a unique key. Object storage is highly durable and scales quite easily to accommodate millions of massive files simultaneously.</p>
<h3 id="heading-how-a-download-link-is-created">How a Download Link Is Created</h3>
<p>The relationship between the stored file and its shareable link relies on the metadata database. When the upload finishes, the application saves the file's storage key in the database and generates a unique access token. The recipient receives a URL containing that specific token. When they click the link, the server reads the token, locates the relevant file in the database and checks the download permissions.</p>
<h3 id="heading-why-are-these-links-difficult-to-guess">Why Are These Links Difficult to Guess?</h3>
<p>A secure file transfer link relies heavily on high entropy, which is randomness that makes tokens mathematically near-impossible to predict. Also, secure systems use signed URLs. These are URLs containing cryptographic signatures that authorize access for a limited, strictly-enforced period.</p>
<p>As outlined in the <a href="https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html"><u>OWASP Session Management Cheat Sheet</u></a>, a random link isn't automatically secure without appropriate access controls, expiration policies, and protection against token leakage.</p>
<h2 id="heading-expiry-and-cleanup-what-happens-when-a-transfer-expires">Expiry and Cleanup: What Happens When a Transfer Expires?</h2>
<p>File transfer services process petabytes of data, meaning they can't store uploaded files forever without going bankrupt. They rely on aggressive lifecycle management.</p>
<h3 id="heading-time-to-live-ttl">Time to Live (TTL)</h3>
<p>Every transfer is assigned a Time to Live (TTL) or expiration timestamp. Once that time passes, the database instantly invalidates the transfer identifier, ensuring that the download link no longer authorizes access.</p>
<h3 id="heading-automated-cleanup-jobs">Automated Cleanup Jobs</h3>
<p>Because link expiration and physical deletion aren't necessarily simultaneous, background workers or scheduled cron jobs handle the actual cleanup. These workers periodically scan the database to find expired transfers, mark them as permanently unavailable, delete the associated multi-gigabyte objects from the storage layer, and finally remove the outdated metadata.</p>
<h3 id="heading-download-limits">Download Limits</h3>
<p>Some services also allow senders to limit how many times a file can be downloaded. Once the download count reaches the threshold, the link behaves exactly as if the TTL had expired, offering an excellent way to control unauthorized distribution.</p>
<h2 id="heading-security-layers-protecting-files-during-transfer-and-storage">Security Layers: Protecting Files During Transfer and Storage</h2>
<p>Security in file transfers is never about a single magic feature. It requires multiple layers of defense to keep data safe from interception or theft.</p>
<h3 id="heading-tls-encryption-in-transit">TLS Encryption in Transit</h3>
<p>When data travels between the sender, the transfer service, and the recipient, it's heavily encrypted. Modern platforms use HTTPS backed by strict TLS protocols to ensure no one can snoop on the data packets mid-route.</p>
<p>For a deep dive into how this is configured at an enterprise level, <a href="https://csrc.nist.gov/publications/detail/sp/800-52/rev-2/final"><u>NIST SP 800-52 Rev. 2</u></a> offers exhaustive guidelines for TLS implementations.</p>
<h3 id="heading-encryption-at-rest">Encryption at Rest</h3>
<p>Once the file arrives at the storage layer, encryption at rest ensures that even if a bad actor physically accessed the server hardware, they would only find scrambled, unreadable data. It's important to note that encryption at rest isn't the same as end to end encryption. The service provider still manages the encryption keys in a standard setup.</p>
<h3 id="heading-password-protected-links">Password-Protected Links</h3>
<p>To prevent unauthorized users from accessing a valid URL, senders can add a password. This creates a secondary access-control layer that must be cleared before the server will even attempt to fetch the file from object storage. Additional safeguards, like rate-limiting against automated password guessing, ensure this layer remains effective.</p>
<h2 id="heading-real-world-examples-how-popular-file-transfer-services-handle-file-sharing">Real-World Examples: How Popular File Transfer Services Handle File Sharing</h2>
<p>Seeing how established companies implement these concepts helps bridge the gap between theory and practice.</p>
<h3 id="heading-wetransfer-temporary-transfers-and-password-protection">WeTransfer: Temporary Transfers and Password Protection</h3>
<p>WeTransfer is built entirely around temporary shareable links. Transfers have strict expiration timelines and premium users can enforce password protection. According to their security documentation, they utilize standard TLS encryption during transit and AES-256 encryption at rest to secure files on their servers.</p>
<h3 id="heading-dropbox-transfer-sending-files-without-collaboration">Dropbox Transfer: Sending Files Without Collaboration</h3>
<p>Unlike a standard shared folder, Dropbox Transfer creates standalone downloadable links. Recipients don't need a Dropbox account to download the payload. They utilize configurable expiration dates, passwords, and automated download notifications, with maximum file size limits dictated by the sender's specific subscription plan.</p>
<h3 id="heading-send-anywhere-direct-transfers-and-temporary-links">Send Anywhere: Direct Transfers and Temporary Links</h3>
<p>Send Anywhere takes a fascinating hybrid approach. Its six-digit key transfer mechanism operates in real-time for one-time use within a 10-minute window, often leveraging peer to peer connections. Conversely, its standard Share Link option falls back to a server-based architecture, uploading files and keeping the link valid for up to 48 hours.</p>
<h3 id="heading-filemail-large-transfers-and-expiration-controls">Filemail: Large Transfers and Expiration Controls</h3>
<p>Offering robust email and shareable-link delivery options, Filemail handles massive payloads easily. They provide highly configurable expiration controls and rigorous password protection. Their free service tier currently allows a 5 GB transfer limit, holding the data securely for a maximum seven-day storage period before automated cleanup takes over.</p>
<h2 id="heading-hands-on-build-a-minimal-chunked-file-uploader-using-nodejs">Hands-On: Build a Minimal Chunked File Uploader Using Node.js</h2>
<p>Understanding the theory is great, but building it yourself proves how it actually works. Let's create a simple application that divides a file into smaller chunks in the browser, uploads them to a Node.js server and stitches them back together.</p>
<h3 id="heading-step-1-set-up-the-nodejs-project">Step 1: Set Up the Node.js Project</h3>
<p>You'll need Node.js, the Express framework, and multer for handling incoming file chunks. The built-in fs module will handle our file operations. First, create a Node project and install the required dependencies:</p>
<pre><code class="language-shell">mkdir file-transfer
cd file-transfer
npm init -y
npm install express multer
</code></pre>
<h3 id="heading-step-2-divide-the-file-into-smaller-chunks">Step 2: Divide the File Into Smaller Chunks</h3>
<p>First, create a <code>public</code> directory inside your project folder if it doesn't already exist. Then, create a file named <code>upload.js</code> inside that directory. We'll use the browser's JavaScript File API and its <code>slice()</code> method to read smaller portions of a file without loading the entire 5 GB payload into your computer's RAM.</p>
<pre><code class="language-javascript">const chunkSize = 5 * 1024 * 1024;

async function uploadFile(file) {
    const totalChunks = Math.ceil(file.size / chunkSize);
    const uploadId = crypto.randomUUID();

    for (let index = 0; index &lt; totalChunks; index++) {
        const chunk = file.slice(
            index * chunkSize,
            (index + 1) * chunkSize
        );

        const formData = new FormData();
        formData.append("chunk", chunk);

        const response = await fetch(
            `/upload/${uploadId}/${index}/${totalChunks}`,
            {
                method: "POST",
                body: formData
            }
        );

        if (!response.ok) {
            throw new Error(`Chunk ${index} failed to upload`);
        }
    }

    const response = await fetch(`/complete/${uploadId}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
            totalChunks,
            filename: file.name
        })
    });

    if (!response.ok) {
        throw new Error("File reassembly failed");
    }
}
</code></pre>
<p>Here, <code>crypto.randomUUID()</code> generates a unique ID for the upload. The browser sends each chunk separately and uses the same ID to associate all the chunks with the original file.</p>
<h3 id="heading-step-3-create-an-upload-endpoint-in-express">Step 3: Create an Upload Endpoint in Express</h3>
<p>On the server side (<code>server.js</code>), we need an endpoint to receive and temporarily store each chunk. The server uses the upload ID and chunk index to determine where each part belongs, while the total number of chunks helps validate the upload. We use multer to parse the incoming multipart form data.</p>
<pre><code class="language-javascript">const express = require("express");
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const { pipeline } = require("stream/promises");

const app = express();

app.use(express.static(path.join(__dirname, "public")));

const chunksDir = path.join(__dirname, "chunks");
const tempDir = path.join(chunksDir, "temp");

fs.mkdirSync(tempDir, { recursive: true });

const upload = multer({
    dest: tempDir,
    limits: { fileSize: 5 * 1024 * 1024 }
});

app.post(
    "/upload/:id/:index/:total",
    upload.single("chunk"),
    async (req, res) =&gt; {
        try {
            const { id, index, total } = req.params;

            if (!req.file) {
                return res.status(400).send("No chunk received");
            }

            if (
                !/^[a-f0-9-]{36}$/i.test(id) ||
                !Number.isInteger(Number(index)) ||
                !Number.isInteger(Number(total)) ||
                Number(total) &lt; 1 ||
                Number(total) &gt; 10000 ||
                Number(index) &lt; 0 ||
                Number(index) &gt;= Number(total)
            ) {
                return res.status(400).send("Invalid upload details");
            }

            const folder = path.join(chunksDir, id);

            await fs.promises.mkdir(folder, {
                recursive: true
            });

            await fs.promises.rename(
                req.file.path,
                path.join(folder, `${index}.part`)
            );

            res.send("Chunk received");

        } catch (error) {
            res.status(500).send("Upload failed");
        }
    }
);
</code></pre>
<p>The server stores each chunk using its upload ID and index, making it possible to identify and retrieve the individual parts when the upload is complete.</p>
<h3 id="heading-step-4-reassemble-the-original-file">Step 4: Reassemble the Original File</h3>
<p>Once the client confirms all chunks have been transmitted, it triggers a final reassembly route. The server first checks whether every expected chunk exists in the <code>chunks/</code> directory. It then reads the chunks sequentially using <code>fs.createReadStream()</code> and writes them to the same output file using <code>fs.createWriteStream()</code>. The first chunk creates the file, while subsequent chunks are appended to it. Once the original file has been reassembled, the server deletes the temporary chunks to free up space.</p>
<pre><code class="language-javascript">const uploadsDir = path.join(__dirname, "uploads");

fs.mkdirSync(uploadsDir, { recursive: true });

app.use(express.json());

app.post("/complete/:id", async (req, res) =&gt; {
    try {
        const { id } = req.params;
        const { totalChunks, filename } = req.body;

        if (
            !/^[a-f0-9-]{36}$/i.test(id) ||
            !Number.isInteger(totalChunks) ||
            totalChunks &lt; 1 ||
            totalChunks &gt; 10000 ||
            typeof filename !== "string"
        ) {
            return res.status(400).send("Invalid upload details");
        }

        const folder = path.join(chunksDir, id);

        for (let i = 0; i &lt; totalChunks; i++) {
            const chunkPath = path.join(folder, `${i}.part`);

            if (!fs.existsSync(chunkPath)) {
                return res.status(400).send(`Missing chunk ${i}`);
            }
        }

        const safeName =
            path.basename(filename).replace(/[^\w.-]/g, "_") ||
            "upload.bin";

        const outputPath = path.join(
            uploadsDir,
            `${id}-${safeName}`
        );

        await fs.promises.rm(outputPath, { force: true });

        for (let i = 0; i &lt; totalChunks; i++) {
            const chunkPath = path.join(folder, `${i}.part`);

            await pipeline(
                fs.createReadStream(chunkPath),
                fs.createWriteStream(outputPath, {
                    flags: i === 0 ? "w" : "a"
                })
            );
        }

        await fs.promises.rm(folder, {
            recursive: true,
            force: true
        });

        res.json({
            message: "File assembled successfully"
        });

    } catch (error) {
        res.status(500).send("Reassembly failed");
    }
});
</code></pre>
<p>Finally, add the following code at the bottom of <code>server.js</code> to start the Express server:</p>
<pre><code class="language-javascript">app.listen(3000, () =&gt; {
    console.log("Server running at http://localhost:3000");
});
</code></pre>
<h3 id="heading-step-5-test-the-upload">Step 5: Test the Upload</h3>
<p>Start the server by running <code>node server.js</code> in your terminal. Then, open <a href="http://localhost:3000"><code>http://localhost:3000</code></a> in your browser and select a medium-sized video file to test the upload. Open your browser's Network tab to observe how the file is divided into chunks and sent sequentially. Finally, check your server's <code>uploads/</code> directory. The assembled file should have the same byte size as the original and should open correctly.</p>
<p>Create <code>public/index.html</code>:</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;File Uploader&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h2&gt;Upload a File&lt;/h2&gt;

    &lt;input type="file" id="fileInput"&gt;
    &lt;button id="uploadButton"&gt;Upload&lt;/button&gt;

    &lt;p id="status"&gt;&lt;/p&gt;

    &lt;script src="upload.js"&gt;&lt;/script&gt;

    &lt;script&gt;
        const button = document.getElementById("uploadButton");
        const fileInput = document.getElementById("fileInput");
        const status = document.getElementById("status");

        button.addEventListener("click", async () =&gt; {
            const file = fileInput.files[0];

            if (!file) {
                status.textContent = "Select a file first.";
                return;
            }

            button.disabled = true;

            try {
                await uploadFile(file);
                status.textContent = "Upload completed!";
            } catch (error) {
                status.textContent = error.message;
            } finally {
                button.disabled = false;
            }
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p><strong>Note:</strong> This implementation demonstrates the basic mechanics of chunked uploads and file reassembly. It doesn't implement resumable uploads, checksum verification, authentication, object storage, or temporary download links.</p>
<p>A production-grade file transfer service would also require persistent upload states, access controls, retry handling, integrity checks, and automated cleanup.</p>
<h2 id="heading-conclusion-a-simple-link-hides-a-lot-of-engineering">Conclusion: A Simple Link Hides a Lot of Engineering</h2>
<p>Sending a large file involves several processes working together. From upload handling and chunk management in the browser to object storage, metadata tracking, encryption, and automated cleanup, each component has a specific role in making file transfers work.</p>
<p>These processes also explain how services handle interrupted uploads, control access to shared files, and remove data when a transfer expires. Understanding how these components work together makes it easier to see what happens behind the scenes whenever someone uploads a large file and shares a download link.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a PDF Storyboard Generator Using JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ PDF files are commonly used to share presentations, scripts, reports, lesson materials, comic pages, and other visual documents. But reviewing a long PDF page by page can take time, especially when so ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-pdf-storyboard-generator-javascript/</link>
                <guid isPermaLink="false">6aee2d6e123f77519047915d</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ pdf ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bhavin Sheth ]]>
                </dc:creator>
                <pubDate>Fri, 06 Nov 2026 19:41:34 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/e8109e42-db7b-4690-9d2b-2be82ab57943.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>PDF files are commonly used to share presentations, scripts, reports, lesson materials, comic pages, and other visual documents. But reviewing a long PDF page by page can take time, especially when someone needs to understand the overall sequence of scenes, slides, or visual content.</p>
<p>A storyboard provides a more organized way to review this information. Instead of opening every page individually, users can arrange selected PDF pages into a single sheet containing multiple panels. Each panel can include a page number, a caption, and a visual preview of the original page.</p>
<p>In this tutorial, we'll explore how to build a browser-based PDF Storyboard Generator using JavaScript, PDF.js, and PDF-lib.</p>
<p>The application takes pages from an existing PDF and arranges them into printable storyboard sheets. Users can choose different layouts, select the pages they want to include, add captions, customize the appearance, preview the result, and download the finished storyboard.</p>
<p>The application runs directly in the browser. The uploaded PDF is processed locally rather than uploaded to the website's server.</p>
<p>We'll examine the implementation step by step, including PDF rendering, page selection, caption handling, layout calculations, preview generation, and file export.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><a href="#heading-what-is-a-pdf-storyboard-generator">What Is a PDF Storyboard Generator?</a></li>
<li><a href="#heading-main-features-of-the-application">Main Features of the Application</a></li>
<li><a href="#heading-understanding-the-browser-based-workflow">Understanding the Browser-Based Workflow</a></li>
<li><a href="#heading-project-setup">Project Setup</a></li>
<li><a href="#heading-libraries-used">Libraries Used</a></li>
<li><a href="#heading-preparing-the-html-workspace">Preparing the HTML Workspace</a></li>
<li><a href="#heading-selecting-the-main-dom-elements">Selecting the Main DOM Elements</a></li>
<li><a href="#heading-defining-important-configuration-values">Defining Important Configuration Values</a></li>
<li><a href="#heading-understanding-the-application-state">Understanding the Application State</a></li>
<li><a href="#heading-uploading-a-pdf">Uploading a PDF</a></li>
<li><a href="#heading-loading-the-pdf-with-pdfjs">Loading the PDF with PDF.js</a></li>
<li><a href="#heading-measuring-pdf-pages">Measuring PDF Pages</a></li>
<li><a href="#heading-rendering-pdf-pages-on-canvas">Rendering PDF Pages on Canvas</a></li>
<li><a href="#heading-reusing-rendered-page-previews">Reusing Rendered Page Previews</a></li>
<li><a href="#heading-reading-text-from-pdf-pages">Reading Text from PDF Pages</a></li>
<li><a href="#heading-filling-empty-captions-automatically">Filling Empty Captions Automatically</a></li>
<li><a href="#heading-updating-the-preview">Updating the Preview</a></li>
<li><a href="#heading-choosing-the-storyboard-layout">Choosing the Storyboard Layout</a></li>
<li><a href="#heading-controlling-rows-columns-and-paper-size">Controlling Rows, Columns, and Paper Size</a></li>
<li><a href="#heading-selecting-pdf-pages-and-their-order">Selecting PDF Pages and Their Order</a></li>
<li><a href="#heading-adding-panel-labels">Adding Panel Labels</a></li>
<li><a href="#heading-drawing-the-storyboard-sheet">Drawing the Storyboard Sheet</a></li>
<li><a href="#heading-updating-the-live-preview">Updating the Live Preview</a></li>
<li><a href="#heading-adjusting-caption-appearance">Adjusting Caption Appearance</a></li>
<li><a href="#heading-navigating-between-storyboard-sheets">Navigating Between Storyboard Sheets</a></li>
<li><a href="#heading-reading-scanned-pages-with-ocr">Reading Scanned Pages with OCR</a></li>
<li><a href="#heading-generating-the-final-storyboard-pdf">Generating the Final Storyboard PDF</a></li>
<li><a href="#heading-downloading-png-storyboard-sheets">Downloading PNG Storyboard Sheets</a></li>
<li><a href="#heading-downloading-individual-page-pictures">Downloading Individual Page Pictures</a></li>
<li><a href="#heading-performance-and-important-considerations">Performance and Important Considerations</a></li>
<li><a href="#heading-demo-pdf-storyboard-generator">Demo: PDF Storyboard Generator</a></li>
<li><a href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-is-a-pdf-storyboard-generator">What Is a PDF Storyboard Generator?</h2>
<p>A PDF Storyboard Generator converts selected pages from an existing PDF into a structured visual sheet.</p>
<p>For example, imagine that you have a PDF containing 20 presentation slides. Instead of sharing all 20 slides separately, you can arrange them into a storyboard containing three columns and two rows per sheet.</p>
<p>Each panel displays a scaled version of its original PDF page. You can also add a number or label and write a short description underneath.</p>
<p>The same approach can be useful for:</p>
<ul>
<li>Reviewing presentation slides.</li>
<li>Organizing comic pages.</li>
<li>Planning video scenes.</li>
<li>Preparing visual scripts.</li>
<li>Reviewing scanned documents.</li>
<li>Creating printable teaching materials.</li>
<li>Organizing page sequences for creative projects.</li>
</ul>
<p>The application doesn't create new scenes or draw illustrations. It arranges existing PDF pages into a storyboard layout.</p>
<h2 id="heading-main-features-of-the-application">Main Features of the Application</h2>
<p>Before writing the code, let's understand the features we're going to implement.</p>
<h3 id="heading-1-pdf-upload">1. PDF Upload</h3>
<p>Users can select a PDF from their device or drag and drop it into the upload area.</p>
<h3 id="heading-2-multiple-storyboard-layouts">2. Multiple Storyboard Layouts</h3>
<p>The application supports three layouts:</p>
<ul>
<li>Grid: Arranges pages in rows and columns.</li>
<li>Panels with notes: Provides space for written notes alongside the page panels.</li>
<li>Film strip: Arranges pages in a film-strip style.</li>
</ul>
<h3 id="heading-3-page-selection-and-ordering"><strong>3. Page Selection and Ordering</strong></h3>
<p>Users can choose which PDF pages should appear in the storyboard. They can also specify a custom order rather than following the original PDF sequence.</p>
<h3 id="heading-4-captions">4. Captions</h3>
<p>Users can type captions manually, fill empty captions using extracted PDF page text, or use OCR to read text from scanned pages.</p>
<h3 id="heading-5-customization">5. Customization</h3>
<p>Users can customize the paper size, orientation, number of columns and rows, panel labels, sheet colors, caption font, text size, spacing, and panel frames.</p>
<h3 id="heading-6-live-preview">6. Live Preview</h3>
<p>The application generates a preview of the storyboard sheets. Users can review the arrangement before downloading the final output.</p>
<p><strong>7. Multiple Export Formats</strong></p>
<p>Users can export their work as:</p>
<ul>
<li>A PDF storyboard.</li>
<li>PNG storyboard sheets.</li>
<li>A ZIP file containing individual page pictures.</li>
</ul>
<p>The PDF export preserves original page content as vectors when possible, helping maintain sharp text and graphics.</p>
<h2 id="heading-understanding-the-browser-based-workflow">Understanding the Browser-Based Workflow</h2>
<p>The application follows a straightforward process.</p>
<ol>
<li>The user selects or drops a PDF file into the upload area.</li>
<li>PDF.js loads the document and renders its pages.</li>
<li>The application displays page previews and caption fields.</li>
<li>The user selects pages, changes their order, and enters captions.</li>
<li>The user configures the storyboard layout and appearance.</li>
<li>JavaScript calculates the position and dimensions of every panel.</li>
<li>The preview is updated to reflect the selected settings.</li>
<li>PDF-lib and browser canvas functionality are used to generate the requested output.</li>
<li>The browser downloads the finished file.</li>
</ol>
<p><strong>PDF Upload Workspace</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/1d23ecf5-1677-4549-84e1-03a08e8943eb.png" alt="PDF Storyboard Generator upload workspace with a drag-and-drop area and PDF selection button." style="display: block;" width="1295" height="461" loading="lazy">

<p><strong>Panels and Captions</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/996d2382-8020-4ddc-b1b8-5956ec86bbdd.png" alt="PDF pages displayed in a storyboard workspace with page previews, caption fields, and OCR controls." style="display: block;" width="1239" height="661" loading="lazy">

<p><strong>Board Settings and Preview</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/882dbe78-4c8c-4d21-aa64-6519fea5a4bf.png" alt="Storyboard settings panel showing layout, page selection, paper size, orientation, captions, and a live preview." style="display: block;" width="1234" height="854" loading="lazy">

<p><strong>Final Storyboard Preview</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/74d7c855-7a6f-44f0-83c2-09efe38a5c3c.png" alt="Final PDF storyboard preview with three numbered panels and captions arranged on an A4 landscape sheet." style="display: block;" width="833" height="828" loading="lazy">

<p><strong>Downloaded PDF</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/64397878-ad42-46eb-b5b6-d39fbf104335.png" alt="Downloaded PDF storyboard containing three arranged panels with page numbers and captions." style="display: block;" width="1134" height="803" loading="lazy">

<h2 id="heading-project-setup">Project Setup</h2>
<p>Before writing the JavaScript functionality, we need to understand how the application is organized.</p>
<p>The PDF Storyboard Generator combines HTML, CSS, and JavaScript. HTML provides the interface, CSS controls the appearance of the workspace and storyboard sheets, and JavaScript handles PDF processing, page previews, captions, layout calculations, and downloads.</p>
<p>For a standalone development project, we can organize the files like this:</p>
<pre><code class="language-text">pdf-storyboard-generator/
├── index.html
├── style.css
├── script.js
└── assets/
</code></pre>
<p>The <code>index.html</code> file contains the application structure, including the upload area, page panels, caption fields, board settings, and preview.</p>
<p>The <code>style.css</code> file controls the appearance of the application. It defines the workspace, panel grid, form controls, buttons, preview area, and responsive layout.</p>
<p>The <code>script.js</code> file contains the main application logic. It loads PDF documents, renders their pages, manages captions, processes OCR requests, calculates storyboard layouts, and generates downloadable files.</p>
<p>The <code>assets</code> directory can hold any additional local resources required by the project.</p>
<p>In the existing AllInOneTools implementation, these components are integrated into the website's tool page rather than being deployed as four separate files. The same separation of responsibilities still applies.</p>
<h2 id="heading-libraries-used">Libraries Used</h2>
<p>The application uses three main JavaScript libraries or browser technologies for its PDF and image-processing workflow.</p>
<h3 id="heading-1-pdfjs">1. PDF.js</h3>
<p>We'll use PDF.js to open PDF documents and render their pages inside the browser.</p>
<p>It allows JavaScript to access individual pages, retrieve their dimensions, create viewports, and draw page content onto an HTML canvas.</p>
<p>For this project, PDF.js is responsible for the original PDF page previews.</p>
<p>The application uses the PDF.js document API to retrieve pages and render them at the required dimensions. This is important because the storyboard must display a visual representation of each selected page before the user downloads the finished sheet.</p>
<h3 id="heading-2-pdf-lib">2. PDF-lib</h3>
<p>We'll use PDF-lib used when generating the final PDF document.</p>
<p>PDF.js and PDF-lib have different responsibilities. PDF.js reads and renders the source document, while PDF-lib creates the new storyboard PDF.</p>
<p>The application uses PDF-lib to create output pages, embed the original PDF pages when possible, and place the finished storyboard elements onto those pages.</p>
<p>Keeping the original PDF pages as vector content helps preserve text and line quality when users zoom in or print the exported document. The implementation also uses a raster-based fallback for password-protected PDFs that can't be loaded through the regular PDF embedding path.</p>
<h3 id="heading-3-tesseractjs">3. Tesseract.js</h3>
<p>This library provides optional Optical Character Recognition (OCR).</p>
<p>Not every PDF contains selectable text. A scanned document, for example, may contain photographs of printed pages instead of actual text data.</p>
<p>When the user selects the OCR option, the application loads Tesseract.js and its English language data. It then processes eligible scanned pages and attempts to extract their text for captions.</p>
<p>OCR is optional, so users don't need to load the OCR engine when they only want to arrange PDF pages and write captions manually.</p>
<p>The following example illustrates how a standalone project could include the libraries through CDN scripts:</p>
<pre><code class="language-html">&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.4.168/pdf.min.js"&gt;&lt;/script&gt;
&lt;script src="https://unpkg.com/pdf-lib/dist/pdf-lib.min.js"&gt;&lt;/script&gt;
&lt;script src="script.js"&gt;&lt;/script&gt;
</code></pre>
<p>For a production application, use library versions that you've tested and configure the matching PDF.js worker file as required by your chosen PDF.js build.</p>
<h3 id="heading-why-these-libraries-work-together">Why These Libraries Work Together</h3>
<p>Each library has a separate responsibility.</p>
<p>PDF.js reads the source PDF and renders its pages. Tesseract.js optionally extracts text from scanned pages. PDF-lib creates the final storyboard PDF.</p>
<p>JavaScript connects these operations and manages the user interface.</p>
<p>This separation makes the application easier to understand and maintain. It also avoids using one library for tasks that are better handled by another.</p>
<h2 id="heading-preparing-the-html-workspace">Preparing the HTML Workspace</h2>
<p>The interface needs several areas to support the complete storyboard workflow.</p>
<p>The upload area accepts the source PDF. The panel area displays rendered pages and caption fields. The board settings area contains layout and appearance controls. Finally, the preview area displays the generated storyboard sheets.</p>
<p>A simplified HTML structure looks like this:</p>
<pre><code class="language-html">&lt;section id="aiot-sb"&gt;
    &lt;div id="aiot-sb-drop"&gt;
        &lt;input
            type="file"
            id="aiot-sb-file-input"
            accept="application/pdf,.pdf"
        &gt;
        &lt;button type="button" data-act="browse"&gt;
            Select a PDF
        &lt;/button&gt;
    &lt;/div&gt;
    &lt;div id="aiot-sb-grid"&gt;&lt;/div&gt;
    &lt;div id="aiot-sb-settings"&gt;&lt;/div&gt;
    &lt;div id="aiot-sb-preview"&gt;&lt;/div&gt;
&lt;/section&gt;
</code></pre>
<p>This is an illustrative structure showing the main interface areas. The actual application contains additional controls, accessibility attributes, and elements for its different operations.</p>
<p>The <code>aiot-sb</code> container provides a common root for the application. JavaScript can use this root to find the relevant interface elements without searching the entire website.</p>
<h2 id="heading-selecting-the-main-dom-elements">Selecting the Main DOM Elements</h2>
<p>JavaScript needs references to the interface elements before it can respond to user actions.</p>
<p>The application starts by finding its root container and checking whether initialization has already taken place:</p>
<pre><code class="language-javascript">var root = document.getElementById("aiot-sb");
if (!root || root.getAttribute("data-aiot-sb-ready")) {
    return;
}
root.setAttribute("data-aiot-sb-ready", "1");
</code></pre>
<p>This prevents the application from initializing again if the script is executed more than once.</p>
<p>The implementation uses a small helper to find elements inside the application:</p>
<pre><code class="language-javascript">function q(selector) {
    return root.querySelector(selector);
}
</code></pre>
<p>For example, <code>q('[data-act="browse"]')</code> finds the button used to open the PDF file picker.</p>
<p>Using a root-specific helper also helps keep the application code organized when the website contains other tools or interface components.</p>
<h2 id="heading-defining-important-configuration-values">Defining Important Configuration Values</h2>
<p>The application needs a few shared configuration values for its layouts and output settings.</p>
<p>For example, it defines supported paper dimensions and font families:</p>
<pre><code class="language-javascript">var MM = 72 / 25.4;
var PAPERS = {
    a4: [595.28, 841.89],
    letter: [612, 792],
    a3: [841.89, 1190.55],
    slide: [405, 720]
};
var PAPER_NAMES = {
    a4: "A4",
    letter: "Letter",
    a3: "A3",
    slide: "16:9 slide"
};
</code></pre>
<p>PDF page dimensions are commonly expressed in points, while some of the storyboard spacing settings are easier to understand in millimeters. The <code>MM</code> conversion value helps translate between these units.</p>
<p>The <code>PAPERS</code> object stores the available page dimensions. The application can use these values when calculating the size of each storyboard sheet.</p>
<p>The <code>PAPER_NAMES</code> object provides readable labels for the corresponding settings.</p>
<p>The application also defines font families for captions and other text:</p>
<pre><code class="language-javascript">var FONTS = {
    sans: "Arial, 'Helvetica Neue', Helvetica, sans-serif",
    serif: "Georgia, 'Times New Roman', serif",
    mono: "'Courier New', Courier, monospace",
    hand: "'Segoe Print', 'Bradley Hand', cursive"
};
</code></pre>
<p>These values allow the storyboard renderer to use different text styles without repeating font definitions throughout the code.</p>
<h2 id="heading-understanding-the-application-state">Understanding the Application State</h2>
<p>The application needs to remember information about the currently loaded PDF, its pages, captions, selected layout, and export process.</p>
<p>Instead of relying on individual variables scattered throughout the application, the implementation groups related information into a shared state object.</p>
<p>For example, the application tracks information such as:</p>
<ul>
<li>The loaded PDF document.</li>
<li>The original PDF bytes.</li>
<li>The current filename.</li>
<li>Page captions.</li>
<li>Page preview data.</li>
<li>Loading and export status.</li>
<li>The OCR worker when OCR is active.</li>
<li>Cancellation and loading tokens.</li>
</ul>
<p>The actual implementation manages these values within its application state and uses them throughout the rendering and export functions.</p>
<p>This becomes especially important when the user changes a caption or layout setting. The application needs to know which values have changed so it can update the storyboard preview without unnecessarily reopening the source document.</p>
<h2 id="heading-uploading-a-pdf">Uploading a PDF</h2>
<p>The first step is allowing users to select a PDF from their device. The PDF Storyboard Generator supports two methods: selecting a file through the file picker or dragging and dropping it into the upload area.</p>
<p>The file input uses the following HTML:</p>
<pre><code class="language-html">&lt;input
    type="file"
    id="aiot-sb-file-input"
    accept="application/pdf,.pdf"
&gt;
</code></pre>
<p>Let's understand the <code>accept</code> attribute:</p>
<ul>
<li><code>application/pdf</code> is the MIME type for PDF files.</li>
<li><code>.pdf</code> is the file extension.</li>
</ul>
<p>A MIME type (Multipurpose Internet Mail Extensions type) identifies the format of a file. Browsers use MIME types to describe the kind of content a file contains. For example, <code>application/pdf</code> identifies a PDF document.</p>
<p>The application checks both the MIME type and the filename extension. This is useful because some browsers or operating systems may provide an empty or incorrect MIME type for a selected file.</p>
<p>The actual application uses this helper:</p>
<pre><code class="language-javascript">function isPdf(file) {
    return file.type === 'application/pdf' ||
        /\.pdf$/i.test(file.name || '');
}
</code></pre>
<p>The first condition checks the file's MIME type. The second checks whether its filename ends with <code>.pdf</code>. The <code>i</code> flag makes the extension check case-insensitive, so filenames such as <code>document.PDF</code> are also accepted.</p>
<p>After validation, both upload methods use the same <code>handleFiles()</code> function. Its initial steps are:</p>
<pre><code class="language-javascript">function handleFiles(list, password) {
    var all = Array.prototype.slice.call(list || []);
    ui.input.value = '';

    if (!all.length) {
        return Promise.resolve();
    }

    var file = all.filter(isPdf)[0];

    if (!file) {
        toast("That isn't a PDF. Choose a PDF file.", 'error');
        return Promise.resolve();
    }

    var note = all.length &gt; 1
        ? ' Only ' + file.name + ' was opened; a storyboard uses one PDF.'
        : '';

    var token = ++state.loadToken;
    var hadDoc = !!state.doc;
    var task, bytes;

    if (hadDoc) {
        ui.fileMeta.textContent = 'Opening ' + file.name + '…';
    }

    setStatus('Opening ' + file.name + '…', true);

    // The remaining function loads and processes the selected PDF.
}
</code></pre>
<p>The function converts the supplied file list into an array and selects the first valid PDF. If no valid PDF is found, it displays an error message and stops.</p>
<p>The <code>loadToken</code> value helps the application distinguish the current loading operation from an older one. This matters when a user selects another document while a previous document is still being processed.</p>
<p>Next, the application waits for the PDF libraries to become available and reads the selected file:</p>
<pre><code class="language-javascript">return engine().then(function () {
    return file.arrayBuffer();
}).then(function (buf) {
    bytes = buf;

    var opts = {
        data: new Uint8Array(buf.slice(0))
    };

    if (password) {
        opts.password = password;
    }

    task = window.pdfjsLib.getDocument(pdfjsOptions(opts));
    return task.promise;
});
</code></pre>
<p>The <code>file.arrayBuffer()</code> method reads the PDF into browser memory. The application converts the data into a <code>Uint8Array</code> and passes it to PDF.js through <code>getDocument()</code>.</p>
<p>If a password was supplied, it's added to the PDF.js options before the document is opened.</p>
<p>The complete function continues by measuring the PDF pages, checking whether the original pages can be embedded as vectors, updating the application state, and displaying the workspace.</p>
<p>This means the selected PDF is processed in the browser. It isn't uploaded to the website's server.</p>
<h2 id="heading-loading-the-pdf-with-pdfjs">Loading the PDF with PDF.js</h2>
<p>Once a file has been selected, the application reads its contents and passes the data to PDF.js.</p>
<p>The PDF.js loading process returns a document object. This object provides access to the document's pages and metadata.</p>
<p>In the actual application, PDF.js is initialized inside the file-loading process. The application first waits for the PDF libraries to load, reads the selected file, and then passes its data to PDF.js.</p>
<pre><code class="language-javascript">return engine().then(function () {
    return file.arrayBuffer();
}).then(function (buf) {
    bytes = buf;

    var opts = {
        data: new Uint8Array(buf.slice(0))
    };

    if (password) {
        opts.password = password;
    }

    task = window.pdfjsLib.getDocument(pdfjsOptions(opts));
    return task.promise;
});
</code></pre>
<p>The <code>engine()</code> function ensures that the required PDF libraries are available before processing begins. The application then uses <code>file.arrayBuffer()</code> to read the selected PDF into browser memory.</p>
<p>The <code>Uint8Array</code> constructor converts the file data into a format that PDF.js can process. If the user has supplied a password, it's added to the PDF.js options before the document is opened.</p>
<p>The <code>getDocument()</code> method starts the PDF loading process, and <code>task.promise</code> resolves when PDF.js has successfully opened the document.</p>
<p>The resulting document object provides access to the PDF's pages and metadata. The application stores this document for later operations, including measuring pages, extracting text, rendering previews, and generating the storyboard.</p>
<h2 id="heading-measuring-pdf-pages">Measuring PDF Pages</h2>
<p>Before arranging pages into storyboard panels, the application needs to know their dimensions.</p>
<p>PDF documents can contain pages with different sizes and orientations. Measuring each page helps the layout engine fit it correctly inside its panel.</p>
<p>The actual application uses the <code>pageFacts()</code> function to measure every page and periodically update the interface while processing large PDFs.</p>
<pre><code class="language-javascript">async function pageFacts(doc, token) {
    var sizes = [];

    for (var n = 1; n &lt;= doc.numPages; n++) {
        if (token !== state.loadToken) {
            return null;
        }

        if (n % 25 === 0) {
            setStatus(
                'Measuring pages: ' + n + ' of ' + doc.numPages + '…',
                true
            );
            await nextFrame();
        }

        var p = await doc.getPage(n);
        var vp = p.getViewport({ scale: 1 });

        sizes.push([vp.width, vp.height]);
    }

    return sizes;
}
</code></pre>
<p>The function starts by creating an empty <code>sizes</code> array. It then loops through all pages using <code>doc.numPages</code> and retrieves each page with <code>doc.getPage(n)</code>.</p>
<p>The <code>getViewport({ scale: 1 })</code> method measures the page at its original scale. The function stores the resulting width and height in the <code>sizes</code> array.</p>
<p>The <code>token</code> parameter helps prevent an outdated loading operation from continuing. If the current token no longer matches <code>state.loadToken</code>, the function stops and returns <code>null</code>.</p>
<p>For larger PDFs, the application updates the loading status after every 25 pages and calls <code>nextFrame()</code> to give the browser an opportunity to update the interface.</p>
<p>Finally, the function returns the array containing the dimensions of all measured pages. These measurements are used later by the storyboard layout calculations.</p>
<h2 id="heading-rendering-pdf-pages-on-canvas">Rendering PDF Pages on Canvas</h2>
<p>The next task is displaying the PDF pages in the workspace.</p>
<p>PDF.js can render an individual page onto an HTML canvas. The canvas provides a visual representation that can be used in the page cards and storyboard preview.</p>
<p>The core rendering function looks like this:</p>
<pre><code class="language-javascript">async function renderPage(n, w, h) {
    var page = await state.doc.getPage(n);
    var b = page.getViewport({ scale: 1 });

    var vp = page.getViewport({
        scale: Math.min(w / b.width, h / b.height)
    });

    var c = document.createElement('canvas');
    c.width = Math.max(1, Math.round(vp.width));
    c.height = Math.max(1, Math.round(vp.height));

    var g = c.getContext('2d');
    g.fillStyle = '#FFFFFF';
    g.fillRect(0, 0, c.width, c.height);

    await page.render({
        canvas: c,
        canvasContext: g,
        viewport: vp
    }).promise;

    return c;
}
</code></pre>
<p>The function accepts three parameters: <code>n</code> is the PDF page number, while <code>w</code> and <code>h</code> define the available width and height for the preview.</p>
<p>First, <code>state.doc.getPage(n)</code> retrieves the requested PDF page. The function then creates a viewport at scale 1 to obtain the page's original dimensions.</p>
<p>Next, <code>Math.min(w / b.width, h / b.height)</code> calculates a scale that fits the page inside the available space without changing its proportions.</p>
<p>The function creates an HTML canvas and sets its width and height using the calculated viewport dimensions. It fills the canvas with white before rendering the PDF page.</p>
<p>Finally, <code>page.render()</code> draws the page onto the canvas. The function waits for rendering to finish and returns the completed canvas for use in the page previews and storyboard.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/fb6abec4-c11f-44e7-b91e-730afd066723.png" alt="PDF Storyboard Generator displaying three PDF page previews rendered on canvas, including text and graphics from the original document." style="display: block;" width="1213" height="393" loading="lazy">

<h2 id="heading-reusing-rendered-page-previews">Reusing Rendered Page Previews</h2>
<p>Rendering the same PDF page repeatedly can consume unnecessary processing time. For example, a page might be rendered once for its card preview and again when the storyboard preview is updated.</p>
<p>The application uses a page-picture cache to reuse previously rendered canvases.</p>
<pre><code class="language-javascript">var picCache = new Map();

// For the preview: reuse a page picture when one at least as big is already made.
async function cachedPic(n, w, h) {
    var got = picCache.get(n);

    if (got &amp;&amp; got.w &gt;= w * 0.92) {
        picCache.delete(n);
        picCache.set(n, got);
        return got.c;
    }

    var c = await renderPage(
        n,
        Math.ceil(w * 1.15),
        Math.ceil(h * 1.15)
    );

    picCache.set(n, { c: c, w: c.width });

    while (picCache.size &gt; 60) {
        var old = picCache.keys().next().value;
        picCache.get(old).c.width = 1;
        picCache.delete(old);
    }

    return c;
}
</code></pre>
<p>The application stores rendered page previews in a JavaScript <code>Map</code> called <code>picCache</code>. Each entry contains the rendered canvas and its width.</p>
<p>When <code>cachedPic()</code> is called, it first checks whether a cached image exists for the requested page. If the cached image is at least 92% of the requested width, the application reuses it instead of rendering the page again.</p>
<p>The function moves a reused entry to the end of the Map. This helps the application keep recently used previews available.</p>
<p>If a suitable cached image isn't available, the function calls <code>renderPage()</code> to create a new canvas. It renders the page at 1.15 times the requested width and height, providing some extra resolution for the preview.</p>
<p>To control memory usage, the cache is limited to 60 entries. When that limit is exceeded, the oldest entry is removed, and its canvas width is reduced to 1 to release its drawing resources.</p>
<p>This caching approach avoids unnecessary PDF rendering while keeping memory usage under control, especially when users work with longer documents.</p>
<h2 id="heading-reading-text-from-pdf-pages">Reading Text from PDF Pages</h2>
<p>The storyboard generator can create captions in three ways:</p>
<ol>
<li>The user writes captions manually.</li>
<li>The application extracts text from the PDF.</li>
<li>OCR reads text from scanned pages.</li>
</ol>
<p>For PDFs containing selectable text, PDF.js provides the <code>getTextContent()</code> method.</p>
<p>The actual application uses the <code>readTexts()</code> function to extract and store text from every page in the loaded PDF.</p>
<pre><code class="language-javascript">async function readTexts(token) {
    var doc = state.doc, out = [];

    for (var n = 1; n &lt;= doc.numPages; n++) {
        if (token !== state.loadToken) {
            return;
        }

        try {
            var tc = await (await doc.getPage(n)).getTextContent();

            out.push(tc.items.map(function (it) {
                return (it.str || '') + (it.hasEOL ? '\n' : '');
            }).join(''));
        } catch (e) {
            out.push('');
        }

        if (n % 20 === 0) {
            await nextFrame();
        }
    }

    if (token !== state.loadToken) {
        return;
    }

    state.texts = out;
    refreshTags(board());
}
</code></pre>
<p>The function starts by accessing the loaded PDF document through <code>state.doc</code> and creating an empty array called <code>out</code> to store the extracted text.</p>
<p>It then loops through every page and calls <code>getTextContent()</code> to retrieve its text items. The <code>map()</code> method combines each item's text into a single string. It also adds a newline when the PDF.js item indicates the end of a line through <code>hasEOL</code>.</p>
<p>If text extraction fails for a page, the function adds an empty string to the results instead of stopping the entire process.</p>
<p>The <code>token</code> check prevents an older PDF-loading operation from updating the current application state. The function also calls <code>nextFrame()</code> after every 20 pages to give the browser an opportunity to update the interface.</p>
<p>After processing all pages, the extracted text is stored in <code>state.texts</code>. The application then calls <code>refreshTags(board())</code> to update the page information displayed in the workspace.</p>
<p>This stored text is used later when users choose to fill empty captions automatically.</p>
<h2 id="heading-filling-empty-captions-automatically">Filling Empty Captions Automatically</h2>
<p>Once the application has extracted text from the PDF pages, it can use that text to create captions.</p>
<p>The important behaviour is that the application fills only empty caption fields. It doesn't overwrite captions that users have already entered.</p>
<p>The application uses the <code>captionFromText()</code> helper to clean and shorten the extracted text:</p>
<pre><code class="language-javascript">function captionFromText(t) {
    var s = String(t || '')
        .replace(/\s+/g, ' ')
        .trim();

    if (letters(s) &lt; 3) {
        return '';
    }

    if (s.length &lt;= 200) {
        return s;
    }

    var cut = s.slice(0, 200);
    var end = Math.max(
        cut.lastIndexOf('. '),
        cut.lastIndexOf('? '),
        cut.lastIndexOf('! '),
        cut.lastIndexOf('। ')
    );

    return end &gt; 60
        ? cut.slice(0, end + 1)
        : cut.replace(/\s+\S*$/, '') + '…';
}
</code></pre>
<p>Here's what this function does:</p>
<ol>
<li>Converts the supplied value into a string.</li>
<li>Replaces repeated whitespace with single spaces and removes whitespace from the beginning and end.</li>
<li>Checks whether the text contains enough letters to be useful as a caption.</li>
<li>Returns the complete text if it contains no more than 200 characters.</li>
<li>For longer text, tries to end the caption at a sentence boundary. If there isn't a suitable boundary, it removes the incomplete final word and adds an ellipsis.</li>
</ol>
<p>The application then uses <code>fillFromText()</code> to apply the generated captions to the selected storyboard pages.</p>
<pre><code class="language-javascript">function fillFromText() {
    var bd = board(), list = bd.error ? [] : unique(bd.list), filled = 0, scans = 0;

    list.forEach(function (n) {
        if (captionFor(n)) { return; }

        var c = captionFromText(state.texts[n - 1]);

        if (c) {
            state.captions[n] = c;
            filled++;

            var ta = ui.grid.querySelector('[data-cap="' + n + '"]');
            if (ta) { ta.value = c; }
        } else if (isScan(n)) {
            scans++;
        }
    });

    if (!state.opts.captions &amp;&amp; filled) {
        state.opts.captions = true;
        savePrefs();
    }

    redrawSoon(0);

    if (!list.length) {
        toast(bd.error || 'No pages on the board.', 'error');
        return;
    }

    toast(
        filled
            ? plural(filled, 'caption', 'captions') +
              ' filled from the page text. Edit them in the cards below.' +
              (scans
                  ? ' ' + plural(scans, 'scanned page has', 'scanned pages have') +
                    ' no text; use OCR for ' + (scans === 1 ? 'it' : 'them') + '.'
                  : '')
            : scans
                ? 'The empty pages are scans with no text. Use Read with OCR.'
                : 'Every panel already has a caption.'
    );
}
</code></pre>
<p>The <code>fillFromText()</code> function starts by calling <code>board()</code> to get the currently selected storyboard pages. It uses <code>unique()</code> to avoid processing the same page more than once.</p>
<p>For each selected page, <code>captionFor(n)</code> checks whether a caption already exists. If one is present, the function skips that page so the user's existing caption isn't overwritten.</p>
<p>If the caption is empty, the function retrieves the extracted text from <code>state.texts</code> and passes it to <code>captionFromText()</code>. When useful text is available, it saves the generated caption in <code>state.captions</code> and updates the corresponding textarea in the page card.</p>
<p>If a page has no extractable text and is identified as a scan, the function increases the scanned-page counter. Users can process these pages separately using OCR.</p>
<p>Finally, the application enables captions if necessary, saves the updated preferences, and schedules a preview refresh. It also displays a message showing how many captions were filled or whether OCR is needed.</p>
<p>This allows users to generate starting captions automatically while keeping their manually written descriptions intact.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/ded521e8-6e44-42c4-b02f-115683f40ea3.png" alt="PDF Storyboard Generator showing automatically generated captions below PDF page previews." style="display: block;" width="1302" height="787" loading="lazy">

<h2 id="heading-updating-the-preview">Updating the Preview</h2>
<p>Whenever a caption or relevant setting changes, the storyboard preview needs to be refreshed.</p>
<p>The application uses a small scheduling function to avoid redrawing the preview immediately after every individual change:</p>
<pre><code class="language-javascript">function redrawSoon(ms) {
    clearTimeout(drawTimer);
    drawTimer = setTimeout(
        drawPreview,
        ms === undefined ? 120 : ms
    );
}
</code></pre>
<p>The <code>redrawSoon()</code> function first cancels any previously scheduled preview update using <code>clearTimeout()</code>. It then schedules <code>drawPreview()</code> using <code>setTimeout()</code>.</p>
<p>By default, the application waits 120 milliseconds before refreshing the preview. If another change happens during that time, the previous scheduled redraw is cancelled and a new one is scheduled.</p>
<p>This helps prevent unnecessary repeated rendering when users are typing captions or adjusting settings.</p>
<h3 id="heading-drawing-the-updated-preview">Drawing the Updated Preview</h3>
<p>Once the redraw is scheduled, the <code>drawPreview()</code> function calculates the current storyboard configuration and updates the visible preview canvas.</p>
<p>The following is the actual implementation from the application:</p>
<pre><code class="language-javascript">async function drawPreview() {
    if (!state.doc) { return; }

    var my = ++drawToken, bd = board();
    refreshTags(bd);
    syncPanel();

    if (bd.error) {
        ui.boardMsg.textContent = bd.error;
        ui.sheetPos.textContent = 'No sheets';
        ui.sheetCount.textContent = '';
        root.querySelectorAll('[data-needs-board]').forEach(function (b) {
            b.disabled = true;
        });
        return;
    }

    root.querySelectorAll('[data-needs-board]').forEach(function (b) {
        b.disabled = state.busy;
    });

    var L = bd.L, o = state.opts;
    state.sheet = clamp(state.sheet, 0, L.sheets - 1);

    ui.boardMsg.textContent = L.tight
        ? 'Captions leave little room for the pages. Use fewer caption lines, fewer rows or a smaller text size.'
        : '';

    ui.sheetPos.textContent = 'Sheet ' + (state.sheet + 1) + ' of ' + L.sheets;
    ui.sheetCount.textContent =
        plural(bd.list.length, 'panel', 'panels') + ' on ' +
        plural(L.sheets, 'sheet', 'sheets') + ', ' +
        PAPER_NAMES[o.paper] + ' ' + o.orient;

    q('[data-act="sheet-prev"]').disabled = state.sheet &lt;= 0;
    q('[data-act="sheet-next"]').disabled = state.sheet &gt;= L.sheets - 1;

    ui.sheetWrap.style.aspectRatio = L.W + ' / ' + L.H;

    var cssW = ui.sheetWrap.clientWidth || 600;
    var dpr = Math.min(window.devicePixelRatio || 1, 2);
    var k = cssW * dpr / L.W;

    var off = document.createElement('canvas');
    off.width = Math.round(L.W * k);
    off.height = Math.round(L.H * k);

    var done = await drawSheet(
        off.getContext('2d'),
        o,
        bd.list,
        L,
        state.sheet,
        k,
        'full',
        function (n, w, h) {
            return my === drawToken
                ? cachedPic(n, w, h)
                : Promise.resolve(null);
        }
    );

    if (!done || my !== drawToken) { return; }

    ui.sheet.width = off.width;
    ui.sheet.height = off.height;
    ui.sheet.getContext('2d').drawImage(off, 0, 0);

    off.width = 1;

    var start = state.sheet * L.per;
    var on = bd.list.slice(start, start + L.per);

    ui.sheet.setAttribute(
        'aria-label',
        'Sheet ' + (state.sheet + 1) + ' of ' + L.sheets + ': ' +
        (on.length === 1 ? 'page ' + on[0] : 'pages ' + on.join(', '))
    );

    ui.sheet.setAttribute('data-drawn', String(state.sheet + 1));
}
</code></pre>
<p>The function first checks whether a PDF document is loaded. It then calls <code>board()</code> to retrieve the selected pages and calculate the storyboard layout.</p>
<p>The <code>drawToken</code> value helps prevent an older preview-rendering operation from replacing a newer one. The function also calls <code>refreshTags()</code> and <code>syncPanel()</code> to update the page information and settings panel.</p>
<p>Next, it checks whether the selected board has any errors. If the selection is valid, it calculates the current sheet position and updates the sheet counter, panel count, paper information, and Previous and Next buttons.</p>
<p>The function then calculates the canvas scale using the available preview width and the device pixel ratio. The device pixel ratio is capped at 2 to limit the amount of rendering work.</p>
<p>The <code>drawSheet()</code> function draws the selected storyboard sheet onto a temporary canvas. It receives <code>cachedPic()</code> as a callback so previously rendered PDF page previews can be reused.</p>
<p>After drawing finishes, the function checks whether the operation is still current. If it is, the completed temporary canvas is copied onto the visible preview canvas.</p>
<p>Finally, the temporary canvas is released by reducing its width to 1. The application also updates the preview's accessibility label and records which sheet has been drawn.</p>
<p>This process allows users to see their storyboard changes without downloading a new PDF every time they adjust a caption or setting.</p>
<h2 id="heading-choosing-the-storyboard-layout">Choosing the Storyboard Layout</h2>
<p>The tool supports three layout styles: Grid, Panels with notes, and Film strip. Each layout is designed for a different type of project.</p>
<p>Grid layout arranges PDF pages in rows and columns. It works well for reviewing presentation slides, comic pages, and documents.</p>
<p>Panels with notes provides additional writing space below each page. It's useful for lecture notes, planning, and reviewing visual material.</p>
<p>Film strip arranges pages as a sequence of frames. It's useful for planning videos, reels, and scenes.</p>
<p>The selected layout is stored in the application's state. When users choose a different layout, the application updates the number of columns and rows to provide suitable default settings.</p>
<p>The following excerpt from the actual <code>onField()</code> function handles layout changes:</p>
<pre><code class="language-javascript">if (f === 'layout' &amp;&amp; e.type === 'change') {
    // sensible panel counts for each layout
    if (o.layout === 'notes') {
        o.cols = o.orient === 'landscape' ? 2 : 1;
        o.rows = o.orient === 'landscape' ? 3 : 4;
    }

    if (o.layout === 'strip') {
        o.cols = 4;
        o.rows = o.orient === 'landscape' ? 2 : 4;
    }

    if (o.layout === 'grid') {
        o.cols = o.orient === 'landscape' ? 3 : 2;
        o.rows = o.orient === 'landscape' ? 2 : 3;
    }
}

savePrefs();

if (f === 'cols' || f === 'rows' || f === 'layout') {
    state.sheet = 0;
}

redrawSoon(f === 'gap' ? 60 : 0);
</code></pre>
<p>This code checks which layout the user has selected and adjusts the default column and row counts according to the layout and paper orientation.</p>
<p>For example:</p>
<ul>
<li><strong>Panels with notes:</strong> Uses 2 columns and 3 rows in landscape orientation, or 1 column and 4 rows in portrait orientation.</li>
<li><strong>Film strip:</strong> Uses 4 columns, with 2 rows in landscape orientation or 4 rows in portrait orientation.</li>
<li><strong>Grid:</strong> Uses 3 columns and 2 rows in landscape orientation, or 2 columns and 3 rows in portrait orientation.</li>
</ul>
<p>After updating these values, <code>savePrefs()</code> saves the settings. The application resets the current sheet to the first sheet when the layout changes and calls <code>redrawSoon()</code> to refresh the preview.</p>
<p>Users can still adjust the number of rows and columns manually using the board settings.</p>
<h2 id="heading-controlling-rows-columns-and-paper-size">Controlling Rows, Columns, and Paper Size</h2>
<p>Users can choose between 1 and 6 columns and rows per sheet. This gives them control over how many PDF pages appear together.</p>
<p>The application also supports different paper sizes, including A4, Letter, A3, and a 16:9 slide format. Each format can be displayed in portrait or landscape orientation.</p>
<p>For example, a 3-column and 2-row layout can display six PDF pages on one sheet. A 4-column and 3-row layout can display twelve pages.</p>
<p>The application calculates the number of panels that fit on each sheet by multiplying the selected columns by the selected rows. It then determines how many sheets are needed for all selected pages.</p>
<p>The following function from the actual application calculates the sheet dimensions based on the selected paper size and orientation:</p>
<pre><code class="language-javascript">function sheetSize(o) {
    var p = PAPERS[o.paper] || PAPERS.a4;
    var a = Math.min(p[0], p[1]);
    var b = Math.max(p[0], p[1]);

    return o.orient === 'portrait' ? [a, b] : [b, a];
}
</code></pre>
<p>The <code>PAPERS</code> object contains the dimensions for each supported paper format. The function retrieves the selected dimensions and arranges them according to the chosen orientation.</p>
<p>For portrait orientation, the shorter dimension becomes the width and the longer dimension becomes the height. For landscape orientation, these dimensions are reversed.</p>
<p>The layout calculation then uses the selected rows and columns to determine the number of panels per sheet:</p>
<pre><code class="language-javascript">var per = o.cols * o.rows;
var sheets = Math.max(1, Math.ceil(list.length / per));
</code></pre>
<p>Here, <code>per</code> represents the number of panels on one sheet. The <code>Math.ceil()</code> function rounds up the total number of required sheets so that any remaining pages are placed on an additional sheet.</p>
<p>The layout engine also calculates the available space and positions each panel so that the pages fit within the selected sheet dimensions.</p>
<p>When more pages are selected than can fit on one sheet, the remaining panels are placed on additional sheets.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/6f6ef0dd-5d4b-40db-adfb-265687c4c576.png" alt="PDF Storyboard Generator board settings for choosing layout, columns, rows, paper size, and orientation." style="display: block;" width="761" height="728" loading="lazy">

<h2 id="heading-selecting-pdf-pages-and-their-order">Selecting PDF Pages and Their Order</h2>
<p>Users don't always need every page in the original PDF.</p>
<p>The tool supports using all pages, selecting a page range, or entering a custom page sequence.</p>
<p>For example, a user could enter:</p>
<pre><code class="language-text">1-4, 9, 6
</code></pre>
<p>This creates a storyboard using pages 1, 2, 3, 4, 9, and 6 in that exact order.</p>
<p>The application uses the <code>parseList()</code> function to process the custom page selection and check whether the requested page numbers are valid.</p>
<p>Here is the actual implementation from the application:</p>
<pre><code class="language-javascript">function parseList(text) {
    var t = String(text || '').trim();

    if (!t) {
        return { error: 'Type the pages, for example 1-4, 7, 5.' };
    }

    var out = [], parts = t.split(/[,;\s]+/).filter(Boolean);

    for (var i = 0; i &lt; parts.length; i++) {
        var part = parts[i],
            m = /^(\d+)(?:\s*[-–]\s*(\d*))?$/.exec(part);

        if (!m) {
            return { error: '"' + part + '" isn\'t a page number or range.' };
        }

        var a = parseInt(m[1], 10),
            b = m[2] === undefined
                ? a
                : (m[2] === '' ? state.count : parseInt(m[2], 10));

        if (a &lt; 1) {
            return { error: 'Pages start at 1, so "' + part + '" doesn\'t work.' };
        }

        if (b &lt; a) {
            return { error: '"' + part + '" is backwards. Did you mean ' + b + '-' + a + '?' };
        }

        if (a &gt; state.count) {
            return {
                error: 'Page ' + a + ' is past the end; this PDF has ' +
                    plural(state.count, 'page', 'pages') + '.'
            };
        }

        if (b &gt; state.count) {
            return {
                error: 'Page ' + b + ' is past the end. Type ' + a +
                    '- to go to the last page.'
            };
        }

        for (var n = a; n &lt;= b; n++) {
            out.push(n);
        }
    }

    if (out.length &gt; 500) {
        return { error: 'That\'s ' + out.length + ' panels. Use 500 or fewer.' };
    }

    return { pages: out };
}
</code></pre>
<p>The function first converts the input into a trimmed string. It then splits the selection using commas, semicolons, or spaces.</p>
<p>The regular expression checks whether each entry is a single page number or a page range. For example, <code>3</code> represents page 3, while <code>2-5</code> represents pages 2 through 5.</p>
<p>The function also supports an open-ended range such as <code>4-</code>. In this case, the application uses <code>state.count</code> as the final page number.</p>
<p>Before adding pages to the result, it checks that page numbers start at 1, ranges are in ascending order, and no requested page exceeds the total number of pages in the PDF.</p>
<p>The application also limits custom selections to 500 panels. If the input is valid, the function returns an array of page numbers in the exact order entered by the user.</p>
<p>The <code>panels()</code> function then uses this result when building the storyboard. If the user selects all pages instead of entering a custom list, it returns every page in the original order.</p>
<p>This feature is helpful when creating a storyboard from selected scenes or important slides without including the entire PDF.</p>
<h2 id="heading-adding-panel-labels">Adding Panel Labels</h2>
<p>Panel labels help users identify individual pages when reviewing or discussing a storyboard.</p>
<p>The application supports different label styles, including numbers, scene labels, original PDF page numbers, and no labels.</p>
<p>For example, a storyboard could display:</p>
<ul>
<li>1, 2, 3, 4</li>
<li>Scene 1, Scene 2, Scene 3</li>
<li>Page 5, Page 6, Page 7</li>
</ul>
<p>Users can select their preferred label style from the Panel label setting.</p>
<p>The application uses the <code>labelFor()</code> function to generate the appropriate label for each panel:</p>
<pre><code class="language-javascript">function labelFor(o, idx, n) {
    if (o.label === 'panel') {
        return String(idx + 1);
    }

    if (o.label === 'page') {
        return 'Page ' + n;
    }

    if (o.label === 'scene') {
        return 'Scene ' + (idx + 1);
    }

    return '';
}
</code></pre>
<p>The function accepts three parameters:</p>
<ul>
<li><code>o</code> contains the storyboard settings, including the selected label style.</li>
<li><code>idx</code> represents the panel's position in the selected storyboard sequence. It starts at 0.</li>
<li><code>n</code> represents the original PDF page number.</li>
</ul>
<p>When the user selects the panel number option, <code>idx + 1</code> generates labels such as 1, 2, and 3.</p>
<p>When the user selects the page number option, the function uses <code>n</code> to display the original PDF page number. This is useful when the storyboard contains selected pages in a custom order.</p>
<p>For the scene label option, the function generates labels such as Scene 1, Scene 2, and Scene 3. If the user selects No label, it returns an empty string.</p>
<p>The drawing function uses this result when rendering each panel on the storyboard sheet. This helps users identify individual panels without changing the original PDF pages.</p>
<h2 id="heading-drawing-the-storyboard-sheet">Drawing the Storyboard Sheet</h2>
<p>Once the layout has been calculated, the application draws the storyboard sheet on an HTML canvas.</p>
<p>The drawing process places each selected PDF page inside its calculated panel area. It then adds panel labels and captions according to the user's settings.</p>
<p>The actual application uses the asynchronous <code>drawSheet()</code> function for this process. The following excerpt shows how it prepares the sheet and selects the pages that belong on it:</p>
<pre><code class="language-javascript">async function drawSheet(ctx, o, list, L, sheetIdx, k, mode, getPic) {
    var C = COLORS[o.colors] || COLORS.paper;
    var W = L.W * k;
    var H = L.H * k;
    var token = state.loadToken;
    var drawn = [];

    ctx.save();
    ctx.fillStyle = C.bg;
    ctx.fillRect(0, 0, W, H);
    ctx.textBaseline = 'alphabetic';

    var start = sheetIdx * L.per;
    var items = list.slice(start, start + L.per);
</code></pre>
<p>The function receives the canvas context, storyboard settings, selected page list, calculated layout, sheet index, and rendering scale.</p>
<p>It first selects the sheet colors and paints the background. The <code>start</code> variable determines the first panel on the current sheet, while <code>items</code> contains the PDF pages assigned to that sheet.</p>
<p>The following excerpt shows how the application fits each PDF page inside its panel and retrieves its rendered image:</p>
<pre><code class="language-javascript">for (var i = 0; i &lt; items.length; i++) {
    var cell = L.cells[i], n = items[i], idx = start + i;
    var area = cell.img;
    var strip = o.layout === 'strip';

    if (strip) {
        ctx.fillStyle = C.bandMat;
        ctx.fillRect(
            area.x * k, area.y * k,
            area.w * k, area.h * k
        );
    } else if (o.frame) {
        ctx.fillStyle = C.mat;
        ctx.fillRect(
            area.x * k, area.y * k,
            area.w * k, area.h * k
        );
    }

    var inset = strip ? 0 :
        o.frame ? Math.min(area.w, area.h) * 0.04 : 0;

    var pr = fitPage(n, area, inset);

    var px = {
        x: Math.round(pr.x * k),
        y: Math.round(pr.y * k),
        w: Math.max(1, Math.round(pr.w * k)),
        h: Math.max(1, Math.round(pr.h * k))
    };

    drawn.push({ n: n, rect: pr });

    if (mode === 'overlay') {
        ctx.clearRect(px.x, px.y, px.w, px.h);
    } else {
        ctx.fillStyle = '#FFFFFF';
        ctx.fillRect(px.x, px.y, px.w, px.h);

        var pic = getPic ? await getPic(n, px.w, px.h) : null;

        if (token !== state.loadToken) {
            ctx.restore();
            return null;
        }

        if (pic) {
            ctx.drawImage(pic, px.x, px.y, px.w, px.h);
        }
    }
}
</code></pre>
<p>The <code>fitPage()</code> function calculates the position and dimensions needed to fit the original PDF page inside the panel without changing its proportions.</p>
<p>The application then uses <code>getPic()</code> to retrieve the rendered page image. If the image is available, <code>drawImage()</code> places it on the storyboard canvas.</p>
<p>The function also supports an overlay mode, which leaves the page picture areas transparent. This is useful when exporting PDFs while preserving the original PDF page content.</p>
<h3 id="heading-drawing-panel-labels-and-captions">Drawing Panel Labels and Captions</h3>
<p>After positioning the page previews, the application draws the panel labels and captions.</p>
<p>The following excerpt from the actual <code>drawSheet()</code> function shows how panel labels and captions are drawn on the canvas:</p>
<pre><code class="language-javascript">var t = cell.text;
var fs = cell.fs * k;
var lh = cell.lh * k;
var y = t.y * k + fs;

var label = labelFor(o, idx, n);
ctx.textAlign = 'left';

if (label) {
    ctx.font = '700 ' + fs + 'px ' + FONTS.mono;
    ctx.fillStyle = C.ink;
    ctx.fillText(label, t.x * k, y);
    y += lh * 1.05;
}

var lines = [];

if (o.captions &amp;&amp; captionFor(n)) {
    ctx.font = '400 ' + fs + 'px ' + FONTS[o.font];
    ctx.fillStyle = C.ink;

    var maxL = cell.notes
        ? Math.max(1, Math.floor(
            (t.y * k + t.h * k - y + lh - fs) / lh
        ))
        : o.lines;

    lines = wrap(
        ctx,
        captionFor(n),
        t.w * k,
        Math.min(maxL, cell.notes ? 40 : o.lines)
    );

    lines.forEach(function (ln, j) {
        ctx.fillText(ln, t.x * k, y + j * lh);
    });
}
</code></pre>
<p>The <code>labelFor()</code> function generates the selected panel label. The application then uses <code>fillText()</code> to draw it on the canvas.</p>
<p>If captions are enabled and a caption exists, the application uses <code>captionFor()</code> to retrieve it. The <code>wrap()</code> function breaks the caption into lines that fit within the available panel space.</p>
<p>For the Panels with notes layout, the application also draws ruled lines below the caption area. This provides additional writing space for users.</p>
<p>The drawing process combines the original PDF page previews with the labels, captions, frames, and other selected settings to create the completed storyboard sheet.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/4acf38c9-c401-4e11-86d9-cdf62bb67912.png" alt=" Live PDF storyboard preview showing multiple page panels arranged on an A4 landscape sheet." style="display: block;" width="990" height="746" loading="lazy">

<h2 id="heading-updating-the-live-preview">Updating the Live Preview</h2>
<p>One of the most useful features is the live preview. Users can change the layout, paper size, orientation, captions, font, spacing, and other settings without creating a new PDF every time.</p>
<p>The application uses the <code>board()</code> function to calculate the current storyboard configuration before drawing the preview.</p>
<p>Here's the actual implementation:</p>
<pre><code class="language-javascript">function board() {
    var sel = panels();

    if (sel.error) {
        return { error: sel.error };
    }

    var L = layout(state.opts, sel.pages);

    return {
        list: sel.pages,
        L: L
    };
}
</code></pre>
<p>The function first calls <code>panels()</code> to retrieve the selected PDF pages. If the selection contains an error, it returns that error instead of continuing.</p>
<p>Next, it calls <code>layout()</code> with the current storyboard settings and selected pages. The layout function calculates how the pages should be arranged on the storyboard sheets.</p>
<p>Finally, <code>board()</code> returns an object containing the selected page list and the calculated layout. The <code>drawPreview()</code> function uses this information to render the selected sheet onto a temporary canvas.</p>
<p>Once drawing is complete, the result is copied to the visible preview canvas. The application also updates the sheet counter, such as <code>Sheet 1 of 3</code>, and enables or disables the Previous and Next buttons depending on the current position.</p>
<p>This allows users to move between storyboard sheets and review their changes before downloading the result.</p>
<h2 id="heading-adjusting-caption-appearance">Adjusting Caption Appearance</h2>
<p>Captions help explain what's happening on each page.</p>
<p>The application provides options for enabling captions, selecting a font, changing text size, and controlling the number of caption lines.</p>
<p>Users can also choose whether to display panel frames and sheet numbers.</p>
<p>These settings are stored in <code>state.opts</code>. The <code>syncPanel()</code> function updates the settings controls to match the current application state.</p>
<p>Here's the actual implementation:</p>
<pre><code class="language-javascript">function syncPanel() {
    var o = state.opts;

    ['layout', 'cols', 'rows', 'paper', 'orient', 'label',
     'lines', 'tsize', 'font', 'colors'].forEach(function (f) {
        q('[data-field="' + f + '"]').value = String(o[f]);
    });

    q('[data-field="captions"]').checked = o.captions;
    q('[data-field="frame"]').checked = o.frame;
    q('[data-field="numbers"]').checked = o.numbers;

    q('[data-field="gap"]').value = String(o.gap);
    q('[data-out="gap-val"]').textContent = o.gap + ' mm';

    q('[data-field="pages"]').value = state.pages;

    if (document.activeElement !== q('[data-field="title"]')) {
        q('[data-field="title"]').value = state.title;
    }

    var strip = o.layout === 'strip';

    q('[data-out="cols-label"]').textContent =
        strip ? 'Frames per strip' : 'Columns';

    q('[data-out="rows-label"]').textContent =
        strip ? 'Strips per sheet' : 'Rows';

    q('[data-field="lines"]').disabled =
        !o.captions || o.layout === 'notes';

    q('[data-field="frame"]').disabled = strip;

    ui.listWrap.hidden = state.pages !== 'list';
}
</code></pre>
<p>The function reads the current options from <code>state.opts</code> and updates the corresponding controls. For example, it sets the selected font, text size, caption line count, and paper settings.</p>
<p>It also handles layout-specific controls. In Film strip mode, the columns and rows labels change to Frames per strip and Strips per sheet. The caption-line control is disabled when captions are turned off or when the Panels with notes layout is selected.</p>
<h3 id="heading-fitting-captions-inside-panels">Fitting Captions Inside Panels</h3>
<p>Long captions need to fit inside the available panel space. The application uses a <code>wrap()</code> helper to divide text into lines based on the available canvas width.</p>
<p>Here's how the actual drawing code uses that helper:</p>
<pre><code class="language-javascript">if (o.captions &amp;&amp; captionFor(n)) {
    ctx.font = '400 ' + fs + 'px ' + FONTS[o.font];
    ctx.fillStyle = C.ink;

    var maxL = cell.notes
        ? Math.max(1, Math.floor(
            (t.y * k + t.h * k - y + lh - fs) / lh
        ))
        : o.lines;

    lines = wrap(
        ctx,
        captionFor(n),
        t.w * k,
        Math.min(maxL, cell.notes ? 40 : o.lines)
    );

    lines.forEach(function (ln, j) {
        ctx.fillText(ln, t.x * k, y + j * lh);
    });
}
</code></pre>
<p>The application selects the font using <code>FONTS[o.font]</code> and calculates the available number of caption lines based on the panel layout.</p>
<p>For regular layouts, the selected <code>o.lines</code> setting controls the maximum number of lines. For Panels with notes, the available space determines how many lines can be displayed.</p>
<p>The <code>wrap()</code> function breaks the caption into lines that fit the available width. The <code>fillText()</code> method then draws each line onto the canvas.</p>
<p>When there isn't enough space for the selected caption settings, the preview displays a warning suggesting fewer caption lines, fewer rows, or a smaller text size.</p>
<p>The application also supports panel frames and sheet numbers. These options are stored in the application state and applied when the storyboard is drawn.</p>
<p>This gives users control over the appearance and readability of their storyboard captions without changing the original PDF.</p>
<h2 id="heading-navigating-between-storyboard-sheets">Navigating Between Storyboard Sheets</h2>
<p>A large PDF may require several storyboard sheets.</p>
<p>The application provides Previous and Next controls so users can review each sheet individually. It also displays the current sheet number and the total number of sheets.</p>
<p>The selected sheet is stored in <code>state.sheet</code>. The application uses this value to determine which storyboard sheet should be displayed.</p>
<h3 id="heading-handling-the-previous-and-next-buttons">Handling the Previous and Next Buttons</h3>
<p>The application handles sheet navigation inside its main click event listener. Here's the actual implementation:</p>
<pre><code class="language-javascript">case 'sheet-prev':
    if (state.sheet &gt; 0) {
        state.sheet--;
        drawPreview();
    }
    break;

case 'sheet-next':
    state.sheet++;
    drawPreview();
    break;
</code></pre>
<p>When the user clicks Previous, the application checks whether the current sheet number is greater than zero. If it is, <code>state.sheet</code> is decreased by one and <code>drawPreview()</code> refreshes the displayed sheet.</p>
<p>When the user clicks Next, the sheet number is increased and the preview is refreshed.</p>
<p>The application also prevents users from moving beyond the available sheets. Inside <code>drawPreview()</code>, it checks the current sheet position and disables the navigation buttons when necessary:</p>
<pre><code class="language-javascript">state.sheet = clamp(state.sheet, 0, L.sheets - 1);

ui.sheetPos.textContent =
    'Sheet ' + (state.sheet + 1) + ' of ' + L.sheets;

q('[data-act="sheet-prev"]').disabled = state.sheet &lt;= 0;
q('[data-act="sheet-next"]').disabled =
    state.sheet &gt;= L.sheets - 1;
</code></pre>
<p>The <code>clamp()</code> function keeps the selected sheet within the valid range. The sheet counter displays the current position, starting from 1, and the total number of sheets.</p>
<p>The Previous button is disabled on the first sheet, while the Next button is disabled on the last sheet. This makes it easier to review large documents without displaying every storyboard sheet at once.</p>
<h2 id="heading-reading-scanned-pages-with-ocr">Reading Scanned Pages with OCR</h2>
<p>Some PDF documents contain selectable text, while others contain scanned images of printed pages.</p>
<p>PDF.js can extract text from pages containing actual text data. But it can't directly extract words from a scanned page that contains only an image.</p>
<p>To handle these pages, the application provides an optional OCR feature using Tesseract.js.</p>
<p>When users select Read scanned pages with OCR, the application identifies scanned pages that don't already have captions and processes them using the OCR engine.</p>
<h3 id="heading-loading-tesseractjs-when-needed">Loading Tesseract.js When Needed</h3>
<p>The application loads Tesseract.js only when the user requests OCR. It first checks whether the library is already available and reuses an existing loading promise if the script is still being loaded.</p>
<p>Here's the actual <code>loadTesseract()</code> implementation:</p>
<pre><code class="language-javascript">var tessPromise = null;

function loadTesseract() {
    if (window.Tesseract) {
        return Promise.resolve(window.Tesseract);
    }

    if (tessPromise) {
        return tessPromise;
    }

    tessPromise = new Promise(function (resolve, reject) {
        var s = document.createElement('script');
        s.src = TESS + 'tesseract.min.js';
        s.async = true;

        s.onload = function () {
            if (window.Tesseract) {
                resolve(window.Tesseract);
            } else {
                tessPromise = null;
                reject(new Error('engine'));
            }
        };

        s.onerror = function () {
            tessPromise = null;
            reject(new Error('engine'));
        };

        document.head.appendChild(s);

        setTimeout(function () {
            reject(new Error('engine'));
        }, 45000);
    });

    return tessPromise;
}
</code></pre>
<p>The function checks <code>window.Tesseract</code> to see whether the OCR library is already available. If it is, the function returns it immediately.</p>
<p>If the library is still loading, the existing <code>tessPromise</code> is returned instead of creating another script request.</p>
<p>Otherwise, the application creates a script element, sets its source to the Tesseract.js library, and adds it to the document. The <code>onload</code> and <code>onerror</code> handlers detect whether loading succeeds or fails.</p>
<h3 id="heading-creating-the-ocr-worker">Creating the OCR Worker</h3>
<p>After the library loads, the application creates a Tesseract worker configured for English text recognition.</p>
<p>The following excerpt comes from the actual <code>runOcr()</code> function:</p>
<pre><code class="language-javascript">var T = await loadTesseract();
checkCancel();

var w = await T.createWorker('eng', 1, {
    workerPath: TESS + 'worker.min.js',
    corePath: TESS_CORE,
    logger: function (m) {
        if (!m || token !== state.loadToken || !state.busy) {
            return;
        }

        if (/loading language/i.test(m.status)) {
            setProgress(
                m.progress || 0,
                'Getting the English language data (first time only)…'
            );
        } else if (/recogniz/i.test(m.status)) {
            setProgress(
                (done + (m.progress || 0)) / list.length,
                'Reading page ' + list[done] +
                ' (' + (done + 1) + ' of ' + list.length + ')…'
            );
        }
    }
});

state.worker = w;
checkCancel();

await w.setParameters({ debug_file: '/dev/null' });
</code></pre>
<p>The <code>createWorker()</code> method initializes the OCR engine with the English language data. The worker and core paths tell Tesseract.js where to load its supporting files.</p>
<p>The logger reports language-loading and text-recognition progress. The application uses this information to update its progress indicator while OCR is running.</p>
<h3 id="heading-recognizing-text-from-scanned-pages">Recognizing Text from Scanned Pages</h3>
<p>The application processes each eligible scanned page individually. It renders the page at a higher resolution before sending it to Tesseract.js.</p>
<p>Here's the actual page-processing excerpt from <code>runOcr()</code>:</p>
<pre><code class="language-javascript">for (; done &lt; list.length; done++) {
    checkCancel();

    var n = list[done],
        page = await state.doc.getPage(n),
        b = page.getViewport({ scale: 1 });

    var c = await renderPage(
        n,
        Math.min(b.width * 300 / 72, 2600),
        Math.min(b.height * 300 / 72, 2600)
    );

    checkCancel();

    var png = await pngBytes(c);
    c.width = 1;

    var res = await w.recognize(png);

    checkCancel();

    if (token !== state.loadToken) {
        return;
    }

    var cap = captionFromText(res.data &amp;&amp; res.data.text);

    if (cap &amp;&amp; !captionFor(n)) {
        state.captions[n] = cap;

        var ta = ui.grid.querySelector('[data-cap="' + n + '"]');

        if (ta) {
            ta.value = cap;
        }
    }
}
</code></pre>
<p>The function retrieves each scanned PDF page and calculates its original dimensions. It then renders the page at approximately 300 DPI, with a maximum dimension of 2,600 pixels.</p>
<p>The <code>pngBytes()</code> helper converts the rendered canvas into PNG image data. Tesseract.js receives this data through <code>w.recognize(png)</code> and returns the recognized text.</p>
<p>The application passes the recognized text to <code>captionFromText()</code> to clean and shorten it. If the result is useful and the page still has no caption, the application saves it in <code>state.captions</code> and updates the corresponding caption field.</p>
<p>The application also checks for cancellation and verifies that the PDF-loading operation is still current before updating the results.</p>
<p>After processing, the application displays a message asking users to review the generated captions. OCR isn't guaranteed to recognize every word correctly. Image quality, handwriting, unusual fonts, and page orientation can affect the result.</p>
<p>Users should review generated captions before downloading the storyboard.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/100aaec2-33a2-440a-956e-79d078692589.png" alt="PDF Storyboard Generator showing the OCR option for extracting text from scanned PDF pages." style="display: block;" width="1239" height="661" loading="lazy">

<h2 id="heading-generating-the-final-storyboard-pdf">Generating the Final Storyboard PDF</h2>
<p>Once the user is satisfied with the layout and captions, the application can generate the final PDF.</p>
<p>This process uses PDF-lib to create a new PDF document. The application creates one output page for each storyboard sheet. It then places the original PDF pages inside their calculated panel positions and adds the storyboard's titles, labels, and captions.</p>
<h3 id="heading-creating-the-pdf-document">Creating the PDF Document</h3>
<p>The actual application uses the <code>exportPdf()</code> function to generate the storyboard. It first creates a new PDF document and checks whether the original PDF pages can be embedded as vector content.</p>
<p>Here's the first part of the actual implementation:</p>
<pre><code class="language-javascript">async function exportPdf(snap, token) {
    await engine();

    var PL = window.PDFLib,
        L = snap.L,
        o = snap.o,
        list = snap.list;

    var out = await PL.PDFDocument.create(),
        src = null,
        embedded = {};

    if (state.vector) {
        try {
            src = await PL.PDFDocument.load(
                state.bytes.slice(0),
                { updateMetadata: false }
            );
        } catch (e) {
            src = null;
        }
    }

    var k = exportScale(L, 300, 14e6);

    for (var s = 0; s &lt; L.sheets; s++) {
        checkCancel();

        if (token !== state.loadToken) {
            return;
        }

        setProgress(
            s / L.sheets,
            'Making sheet ' + (s + 1) + ' of ' + L.sheets + '…'
        );

        var page = out.addPage([L.W, L.H]);
        var c = document.createElement('canvas');

        c.width = Math.round(L.W * k);
        c.height = Math.round(L.H * k);

        var drawn = await drawSheet(
            c.getContext('2d'),
            o,
            list,
            L,
            s,
            k,
            'overlay',
            null
        );

        if (!drawn) {
            return;
        }
</code></pre>
<p>The function first waits for the required PDF libraries using <code>engine()</code>. It then creates a new PDF document with <code>PDFDocument.create()</code>.</p>
<p>The <code>snap</code> parameter contains a snapshot of the selected layout, options, and page list. The application uses these values so the export follows the settings selected by the user.</p>
<p>The <code>state.vector</code> check determines whether the original PDF can be loaded through PDF-lib for vector embedding. The application also calculates a rendering scale targeting 300 DPI, subject to a maximum pixel limit.</p>
<p>The loop creates one output PDF page for every storyboard sheet. It also calls <code>drawSheet()</code> in <code>overlay</code> mode to prepare the titles, panel labels, and captions that will be placed over the original PDF pages.</p>
<h3 id="heading-preserving-original-pdf-pages">Preserving Original PDF Pages</h3>
<p>When vector embedding is available, the application embeds the original PDF pages rather than converting them into ordinary images.</p>
<p>The following excerpt shows how it handles each selected panel:</p>
<pre><code class="language-javascript">for (var i = 0; i &lt; drawn.length; i++) {
    checkCancel();

    var d = drawn[i],
        r = d.rect,
        yb = L.H - r.y - r.h;

    page.drawRectangle({
        x: r.x,
        y: yb,
        width: r.w,
        height: r.h,
        color: PL.rgb(1, 1, 1)
    });

    if (src) {
        var sp = src.getPage(d.n - 1);

        if (!embedded[d.n]) {
            var cb = sp.getCropBox();

            embedded[d.n] = await out.embedPage(sp, {
                left: cb.x,
                bottom: cb.y,
                right: cb.x + cb.width,
                top: cb.y + cb.height
            });
        }

        var em = embedded[d.n],
            rot = ((sp.getRotation().angle % 360) + 360) % 360;

        var turned = rot === 90 || rot === 270,
            sx = r.w / (turned ? em.height : em.width);

        var ew = em.width * sx,
            eh = em.height * sx,
            at = { x: r.x, y: yb };

        if (rot === 90) {
            at = { x: r.x, y: yb + ew };
        } else if (rot === 180) {
            at = { x: r.x + ew, y: yb + eh };
        } else if (rot === 270) {
            at = { x: r.x + eh, y: yb };
        }

        page.drawPage(em, {
            x: at.x,
            y: at.y,
            width: ew,
            height: eh,
            rotate: PL.degrees(-rot)
        });
    }
</code></pre>
<p>The application retrieves the original PDF page using its page number. It then uses <code>embedPage()</code> to embed that page into the new PDF document.</p>
<p>The <code>embedded</code> object caches embedded pages so the same original page doesn't need to be embedded repeatedly.</p>
<p>The code also checks the original page rotation and adjusts its position and dimensions before drawing it. This helps preserve the correct orientation when placing pages inside storyboard panels.</p>
<h3 id="heading-handling-protected-pdfs">Handling Protected PDFs</h3>
<p>If the original PDF can't be embedded as vector content, the application uses a raster fallback.</p>
<p>Here's the actual fallback code:</p>
<pre><code class="language-javascript">else {
    var pic = await renderPage(
        d.n,
        r.w * k,
        r.h * k
    );

    var jpg = await new Promise(function (res) {
        pic.toBlob(function (b) {
            b.arrayBuffer().then(function (a) {
                res(new Uint8Array(a));
            });
        }, 'image/jpeg', 0.92);
    });

    pic.width = 1;

    page.drawImage(
        await out.embedJpg(jpg),
        {
            x: r.x,
            y: yb,
            width: r.w,
            height: r.h
        }
    );
}
</code></pre>
<p>In this case, the application renders the original PDF page onto a canvas and converts it into JPEG image data. PDF-lib then embeds the image inside the corresponding storyboard panel.</p>
<p>This fallback is used when vector embedding is unavailable, including protected PDFs that can't follow the normal vector workflow.</p>
<h3 id="heading-adding-captions-and-saving-the-pdf">Adding Captions and Saving the PDF</h3>
<p>After the original page images or vector content have been placed, the application adds the storyboard's titles, labels, captions, and other drawing elements as an overlay.</p>
<p>The following excerpt shows how the overlay is added and the final PDF is saved:</p>
<pre><code class="language-javascript">var over = await out.embedPng(await pngBytes(c));
c.width = 1;

page.drawImage(over, {
    x: 0,
    y: 0,
    width: L.W,
    height: L.H
});

await nextFrame();
</code></pre>
<p>After all sheets have been processed, the application checks for cancellation and prepares the final PDF:</p>
<pre><code class="language-javascript">checkCancel();

setProgress(1, 'Saving the PDF…');

out.setTitle(state.title || state.base + ' storyboard');
out.setCreator('AllInOneTools PDF Storyboard');
out.setProducer('AllInOneTools (pdf-lib)');

var bytes = await out.save();

if (token !== state.loadToken) {
    return;
}

save(
    new Blob([bytes], { type: 'application/pdf' }),
    state.base + '-storyboard.pdf'
);

toast(
    'Saved ' + plural(L.sheets, 'sheet', 'sheets') +
    ' as ' + state.base + '-storyboard.pdf.'
);
</code></pre>
<p>The <code>embedPng()</code> method adds the storyboard overlay to the PDF page. This overlay contains the titles, panel labels, captions, and other visual elements.</p>
<p>The application then sets the PDF metadata, saves the document as bytes, and creates a downloadable PDF file.</p>
<p>Progress updates and cancellation checks are used throughout the export process, which is particularly helpful when generating storyboards with multiple sheets.</p>
<p>The final PDF combines the original PDF pages with the storyboard layout and captions, ready to download, share, or print.</p>
<h2 id="heading-downloading-png-storyboard-sheets">Downloading PNG Storyboard Sheets</h2>
<p>Users who don't need a PDF can choose PNG sheets.</p>
<p>The application renders each complete storyboard sheet as a PNG image at 200 DPI. If the storyboard contains only one sheet, the browser downloads a single PNG file. If it contains multiple sheets, the application packages them into a ZIP archive.</p>
<h3 id="heading-exporting-the-storyboard-as-png">Exporting the Storyboard as PNG</h3>
<p>The application handles PNG exports inside the <code>exportJob()</code> function. It first calculates the rendering scale and then processes each storyboard sheet.</p>
<p>The following excerpt shows the actual PNG export implementation:</p>
<pre><code class="language-javascript">var k = exportScale(L, 200, 16e6),
    files = [];

for (var s = 0; s &lt; L.sheets; s++) {
    checkCancel();

    setProgress(
        s / L.sheets,
        'Drawing sheet ' + (s + 1) + ' of ' + L.sheets + '…'
    );

    var c = document.createElement('canvas');

    c.width = Math.round(L.W * k);
    c.height = Math.round(L.H * k);

    var ok = await drawSheet(
        c.getContext('2d'),
        o,
        list,
        L,
        s,
        k,
        'full',
        function (n, w, h) {
            checkCancel();
            return renderPage(n, w, h);
        }
    );

    if (!ok) { return; }

    files.push({
        name: state.base + '-storyboard-sheet-' +
            pad2(s + 1) + '.png',
        data: await pngBytes(c)
    });

    c.width = 1;
}

if (files.length === 1) {
    save(
        new Blob([files[0].data], { type: 'image/png' }),
        state.base + '-storyboard.png'
    );
} else {
    save(makeZip(files), state.base + '-storyboard-sheets.zip');
}

toast(
    files.length === 1
        ? 'Saved the storyboard as a PNG.'
        : 'Saved ' + files.length + ' sheets as PNG files in a ZIP.'
);
</code></pre>
<p>The application uses <code>exportScale()</code> to calculate a suitable rendering scale for 200 DPI while keeping the canvas within a maximum pixel limit of 16 million pixels.</p>
<p>For every sheet, it creates a canvas and calls <code>drawSheet()</code> in <code>full</code> mode. This draws the PDF page previews together with the storyboard titles, labels, captions, and other selected settings.</p>
<p>The <code>pngBytes()</code> helper converts the completed canvas into PNG data. Each image is added to the <code>files</code> array with a filename containing its sheet number.</p>
<p>After processing all sheets, the application checks how many PNG files were generated. A single sheet is downloaded directly as a PNG. Multiple sheets are packaged into a ZIP archive using <code>makeZip()</code>.</p>
<p>This format is useful for sharing storyboard previews in presentations, messages, and other applications.</p>
<h2 id="heading-downloading-individual-page-pictures">Downloading Individual Page Pictures</h2>
<p>The third export option is Page pictures (ZIP).</p>
<p>Unlike the PNG sheets option, this export contains individual pictures of the PDF pages selected for the storyboard.</p>
<p>The application renders each selected page separately and places the resulting PNG files into a ZIP archive.</p>
<h3 id="heading-exporting-individual-pdf-pages">Exporting Individual PDF Pages</h3>
<p>The actual application handles this option inside the <code>exportJob()</code> function. It first creates a unique list of selected pages and then renders each page individually.</p>
<p>Here's the actual implementation:</p>
<pre><code class="language-javascript">var pages = unique(list),
    out = [];

for (var i = 0; i &lt; pages.length; i++) {
    checkCancel();

    setProgress(
        i / pages.length,
        'Saving page ' + pages[i] +
        ' (' + (i + 1) + ' of ' + pages.length + ')…'
    );

    var pg = await state.doc.getPage(pages[i]),
        vb = pg.getViewport({ scale: 1 }),
        sc = Math.min(
            2,
            Math.sqrt(12e6 / (vb.width * vb.height))
        );

    var pc = await renderPage(
        pages[i],
        vb.width * sc,
        vb.height * sc
    );

    out.push({
        name: 'panel-' +
            pad2(list.indexOf(pages[i]) + 1) +
            '-page-' + pad2(pages[i]) + '.png',
        data: await pngBytes(pc)
    });

    pc.width = 1;
}

save(makeZip(out), state.base + '-panels.zip');

toast(
    'Saved ' +
    plural(out.length, 'page picture', 'page pictures') +
    ' in a ZIP.'
);
</code></pre>
<p>The function first calls <code>unique()</code> to remove duplicate page numbers from the selected list.</p>
<p>It then processes each page individually. The <code>getPage()</code> method retrieves the original PDF page, and <code>getViewport()</code> obtains its dimensions.</p>
<p>The scale calculation limits the rendering scale to 2 while keeping the rendered page within approximately 12 million pixels. This helps control memory usage when processing large pages.</p>
<p>The <code>renderPage()</code> function creates the page image, while <code>pngBytes()</code> converts the canvas into PNG data.</p>
<p>Each image is added to the <code>out</code> array with a filename containing both its panel position and original PDF page number. This makes it easier to identify the pictures and maintain their storyboard order.</p>
<p>Finally, <code>makeZip()</code> packages all the generated PNG images into a ZIP archive, which the browser downloads.</p>
<p>This option is useful when users want to work with individual PDF page pictures rather than complete storyboard sheets.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/895e4a25-0a30-4402-a728-d4a51fb97b38.png" alt="Board settings and preview, including the PDF, PNG sheets, and Page pictures download buttons." style="display: block;" width="336" height="212" loading="lazy">

<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/bacaaf21-ffb9-476d-abca-9b0a0d8dc537.png" alt="Exported storyboard PDF opened in a PDF viewer." style="display: block;" width="1134" height="803" loading="lazy">

<h2 id="heading-performance-and-important-considerations">Performance and Important Considerations</h2>
<p>Rendering large PDFs and generating high-resolution images can consume significant browser memory.</p>
<p>The application uses page-preview caching, temporary canvases, progress reporting, and cancellation controls to manage this work.</p>
<p>For better results, use fewer panels per sheet when working with large documents. A3 paper can also provide more room when a storyboard contains many panels.</p>
<p>Remember that layout preferences are remembered on the device, but the PDF and captions remain in the current browser tab. Download your work before closing the tab.</p>
<h2 id="heading-demo-pdf-storyboard-generator">Demo: PDF Storyboard Generator</h2>
<p>You can try the finished application here:</p>
<p><a href="https://allinonetools.net/pdf-storyboard-generator/?utm_source=chatgpt.com">PDF Storyboard Generator – AllInOneTools</a></p>
<p>Upload a PDF, arrange its pages, add captions, customize the storyboard, and download the finished result.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Building a PDF Storyboard Generator combines several useful browser technologies into one application.</p>
<p>PDF.js handles PDF loading and page rendering. Tesseract.js provides optional text recognition for scanned pages. PDF-lib creates the final storyboard PDF, while HTML canvas handles previews and image exports.</p>
<p>By connecting these components with JavaScript, we can create a practical tool for organizing presentation slides, comic pages, scripts, and other PDF documents.</p>
<p>The project also demonstrates how browser-based applications can process documents locally without requiring users to upload their files to a server.</p>
<p>With the complete workflow in place, users can turn ordinary PDF pages into organized storyboard sheets that are easier to review, print, and share.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Godot 4 Roguelike Course – Build a Complete Top-Down Action Game ]]>
                </title>
                <description>
                    <![CDATA[ A top-down action roguelite only works when combat feels sharp, rooms feel connected, and every run asks you to trade power for risk. Godot 4 has the tools for that, but most tutorials stop before tho ]]>
                </description>
                <link>https://www.freecodecamp.org/news/godot-4-roguelike-course-build-a-complete-top-down-action-game/</link>
                <guid isPermaLink="false">6aedfb097070ca4b7e00e608</guid>
                
                    <category>
                        <![CDATA[ Godot ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Fri, 06 Nov 2026 16:06:33 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/gql/5f68e7df6dfc523d0a894e7c/1bca1e16-d488-4afc-bc2f-ede5902092c4.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A top-down action roguelite only works when combat feels sharp, rooms feel connected, and every run asks you to trade power for risk. Godot 4 has the tools for that, but most tutorials stop before those systems fit together into a game someone else can open and play.</p>
<p>We just published a comprehensive 10-hour course on the freeCodeCamp.org YouTube channel that will teach you how to build a complete top-down action roguelite in Godot 4.7.2, from an empty project to an exported game. This course is taught by Omar Zaki, creator of Coding Quests, and most lessons include a Your Turn section where you build the next piece yourself before you see the solution.</p>
<p>Here is what the course covers:</p>
<ul>
<li><strong>Dash Combat &amp; I-Frames</strong><br>Build weighty movement, aiming, and a dodge with invincibility frames so combat feels fair instead of cheap.</li>
<li><strong>Enemies, Telegraphs &amp; a Boss Tell</strong><br>Create five enemy types from a shared base, then add a boss with a clear warning before the hard hit lands.</li>
<li><strong>Procedural Connected Rooms</strong><br>Generate random floors of linked rooms in code, track where you are, and lock a fight until the room is clear.</li>
<li><strong>Items, Corruption &amp; Shops</strong><br>Stack items into builds, take corruption that trades power for fragility, and risk gold at shops and a gambling altar.</li>
<li><strong>Run Loop, Unlocks &amp; Export</strong><br>Wire death, permanent unlocks, a title screen, sound, and an export so a stranger can download and play your game.</li>
</ul>
<p>Watch the full course on <a href="https://youtu.be/eHHxRJulX74">the freeCodeCamp.org YouTube channel</a> (10-hour watch).</p>
<div class="embed-wrapper"><iframe width="560" height="315" src="https://www.youtube.com/embed/eHHxRJulX74" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use shadcn/ui in React Native Applications [Full Handbook] ]]>
                </title>
                <description>
                    <![CDATA[ If you've built a couple of React Native apps, the following probably feels familiar. You start with a colors.ts file and a simple Button component. Everything looks fine at first. Then the design cha ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-shadcn-ui-in-react-native-applications-full-handbook/</link>
                <guid isPermaLink="false">6aecb9efa7a2ab6fb8e3fe94</guid>
                
                    <category>
                        <![CDATA[ shadcn ]]>
                    </category>
                
                    <category>
                        <![CDATA[ shadcn ui ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React Native ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ajay Patel ]]>
                </dc:creator>
                <pubDate>Thu, 05 Nov 2026 17:16:30 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/ddea2027-27b4-407e-83a5-d84bfd295627.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you've built a couple of React Native apps, the following probably feels familiar. You start with a <code>colors.ts</code> file and a simple <code>Button</code> component. Everything looks fine at first. Then the design changes a few times, and that small color file starts growing. Your Button also picks up another prop every time someone asks for a slightly different style.</p>
<p>The setup works at first, but after a few design changes, even a small update can mean checking several files across the project.</p>
<p>Here's what a typical color file looks like after a while:</p>
<pre><code class="language-tsx">export const colors = {
  primary: '#6e4836',
  primaryPressed: '#5a3a2b',
  textPrimary: '#261d16',
  textSecondary: '#72665e',
  // and forty more
};
</code></pre>
<p>And here's what a typical <code>Button</code> looks like after a few redesigns:</p>
<pre><code class="language-tsx">&lt;Button
  variant="primary"
  size="md"
  fullWidth
  loading={busy}
  containerStyle={styles.checkoutButton}
  labelStyle={styles.checkoutLabel}
/&gt;
</code></pre>
<p>These are simplified examples, but you get the idea. The color object keeps growing, and the Button collects more props to handle every new design request.</p>
<p>Each change seems reasonable when you make it. But the annoying part comes later, when changing one design decision means checking several files to see that nothing else has changed unexpectedly.</p>
<p>Part of the problem is how many component libraries are distributed. Their code lives in <code>node_modules</code>, so you usually customize them through the props and options they expose. When the library doesn't cover your exact use case, you add another prop or override. Keep doing that and the component can become harder to maintain than the original problem you were trying to solve.</p>
<p>This is one reason I like shadcn/ui's approach. You don't install a traditional component package and treat its components as fixed. The CLI copies the source code into your project, where you can change it whenever you need to. For React Native, there's a project built around the same idea called <a href="https://reactnativereusables.com/">React Native Reusables</a>.</p>
<p>To make this practical, I'll use React Native Reusables, Expo, and Uniwind to build a <strong>cart and checkout screen for a coffee shop's pickup orders</strong>. It includes order items with quantity controls, a pickup-time dropdown, a name field, an "own cup" toggle, a bill summary, a checkout bar that stays at the bottom, and an order-confirmation dialog. If you want to see how reusable sections come together in complete interfaces, you can also browse <a href="https://shadcnstudio.com/templates">shadcn templates</a>.</p>
<p>I'll also point out a few things that are easy to miss when working with these components, including:</p>
<ul>
<li>How shadcn/ui and its CLI work, and why you own the component code</li>
<li>How design tokens (named colors) replace a <code>colors.ts</code> file</li>
<li>How to use components such as Card, Select, Switch, and AlertDialog in React Native</li>
<li>How to handle mobile-specific issues, such as safe areas, keyboards, and tap targets</li>
<li>How to switch between light and dark mode, and how to change the whole theme from one file</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a href="#heading-prerequisites">Prerequisites</a></li>
<li><a href="#heading-tools-you-will-use">Tools You Will Use</a></li>
<li><a href="#heading-how-shadcnui-works">How shadcn/ui Works</a></li>
<li><a href="#heading-what-react-native-reusables-gives-you">What React Native Reusables Gives You</a></li>
<li><a href="#heading-what-youre-building">What You're Building</a></li>
<li><a href="#heading-step-1-create-the-app">Step 1: Create the App</a><ul>
<li><a href="#heading-answer-the-clis-questions">Answer the CLI's Questions</a></li>
<li><a href="#heading-look-at-the-project-structure">Look at the Project Structure</a></li>
<li><a href="#heading-run-the-app">Run the App</a></li>
</ul>
</li>
<li><a href="#heading-step-2-understand-the-theme-file">Step 2: Understand the Theme File</a><ul>
<li><a href="#heading-the-palette-also-exists-in-libthemets">The Palette Also Exists inlib/theme.ts</a></li>
<li><a href="#heading-try-it-change-one-color">Try It: Change One Color</a></li>
</ul>
</li>
<li><a href="#heading-step-3-read-three-core-components">Step 3: Read Three Core Components</a><ul>
<li><a href="#heading-the-text-component">The Text Component</a></li>
<li><a href="#heading-the-button-component">The Button Component</a></li>
<li><a href="#heading-the-icon-component">The Icon Component</a></li>
</ul>
</li>
<li><a href="#heading-step-4-add-the-components-you-need">Step 4: Add the Components You Need</a></li>
<li><a href="#heading-step-5-set-up-the-data-and-the-screen">Step 5: Set Up the Data and the Screen</a><ul>
<li><a href="#heading-the-screen-layout">The Screen Layout</a></li>
</ul>
</li>
<li><a href="#heading-step-6-build-the-order-rows">Step 6: Build the Order Rows</a></li>
<li><a href="#heading-step-7-build-the-pickup-options">Step 7: Build the Pickup Options</a><ul>
<li><a href="#heading-problem-1-portals-and-the-portalhost">Problem 1: Portals and the PortalHost</a></li>
<li><a href="#heading-problem-2-safe-area-insets">Problem 2: Safe Area Insets</a></li>
<li><a href="#heading-problem-3-the-select-value-is-an-object">Problem 3: The Select Value Is an Object</a></li>
<li><a href="#heading-making-the-label-tappable">Making the Label Tappable</a></li>
<li><a href="#heading-keyboard-props-for-the-name-field">Keyboard Props for the Name Field</a></li>
</ul>
</li>
<li><a href="#heading-step-8-build-the-bill-component">Step 8: Build the Bill Component</a></li>
<li><a href="#heading-step-9-build-the-fixed-checkout-bar">Step 9: Build the Fixed Checkout Bar</a><ul>
<li><a href="#heading-handling-the-home-indicator">Handling the Home Indicator</a></li>
<li><a href="#heading-a-note-on-thin-borders">A Note on Thin Borders</a></li>
</ul>
</li>
<li><a href="#heading-step-10-add-the-confirmation-and-put-the-screen-together">Step 10: Add the Confirmation and Put the Screen Together</a><ul>
<li><a href="#heading-1-it-also-needs-the-portalhost">1. It Also Needs thePortalHost</a></li>
<li><a href="#heading-2-the-footer-reverses-its-order-on-phones">2. The Footer Reverses its Order on Phones</a></li>
<li><a href="#heading-haptics">Haptics</a></li>
<li><a href="#heading-the-full-screen">The Full Screen</a></li>
</ul>
</li>
<li><a href="#heading-step-11-add-dark-mode">Step 11: Add Dark Mode</a><ul>
<li><a href="#heading-1-the-navigation-header">1. The Navigation Header</a></li>
<li><a href="#heading-2-the-status-bar">2. The Status Bar</a></li>
<li><a href="#heading-3-saving-the-choice">3. Saving the Choice</a></li>
</ul>
</li>
<li><a href="#heading-step-12-create-your-own-theme">Step 12: Create Your Own Theme</a><ul>
<li><a href="#heading-update-the-tokens">Update the Tokens</a></li>
<li><a href="#heading-update-libthemets">Update lib/theme.ts</a></li>
</ul>
</li>
<li><a href="#heading-common-mistakes-and-how-to-fix-them">Common Mistakes and How to Fix Them</a></li>
<li><a href="#heading-conclusion">Conclusion</a><ul>
<li><a href="#heading-resources">Resources</a></li>
</ul>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along, you should have:</p>
<ul>
<li><strong>Node.js 20 or newer.</strong> You can use pnpm, npm, yarn, or bun. The commands in this tutorial use pnpm, so swap the prefix if you use something else.</li>
<li><strong>Basic knowledge of React and TypeScript</strong>, especially hooks such as <code>useState</code>.</li>
<li><strong>Some familiarity with React Native</strong>, such as <code>View</code>, <code>Text</code>, and <code>ScrollView</code>. You don't need to know Tailwind, but it helps.</li>
<li><strong>Optional:</strong> Xcode or Android Studio if you want to run the app in a simulator. Everything also runs in a web browser through React Native Web, and that's how the screenshots in this tutorial were taken.</li>
</ul>
<p>You don't need any accounts or API keys, and nothing here costs money.</p>
<h2 id="heading-tools-you-will-use">Tools You Will Use</h2>
<p>Before creating the app, let's look at the tools in this project. Each one has a specific job, and knowing that will make the setup easier to follow.</p>
<p><strong>shadcn/ui</strong> is a collection of UI components for the web. It's not installed as a package. Instead, a command-line tool (CLI) copies the source code of each component into your project, and from then on the code is yours to edit.</p>
<p><strong>React Native Reusables</strong> is the React Native version of shadcn/ui. It gives you components such as Button, Card, Select, and Dialog that are written for React Native and styled with Tailwind-style class names. It uses the same CLI idea as shadcn/ui.</p>
<p><strong>RN Primitives</strong> is a React Native port of Radix UI, which is the library that shadcn/ui uses for behavior on the web. A "primitive" is a component that handles the behavior but has no styling. For example, the <code>select</code> primitive knows how a dropdown opens and closes and how it's announced to screen readers, but it has no colors or borders. React Native Reusables adds the looks on top.</p>
<p><strong>Uniwind</strong> is a tool that lets you style React Native components with Tailwind CSS class names, such as <code>className="bg-primary p-4"</code>. It converts those classes into regular React Native styles while the app is being bundled, so there's no extra work at runtime. <a href="https://www.nativewind.dev/">Nativewind</a> does a similar job, and React Native Reusables supports both. This tutorial uses Uniwind.</p>
<p><strong>Expo and Expo Router</strong> provide the project setup, the development server, and file-based navigation. If you have used Next.js, Expo Router works in a similar way.</p>
<h2 id="heading-how-shadcnui-works">How shadcn/ui Works</h2>
<p>The React Native Reusables documentation opens with a quote from shadcn:</p>
<blockquote>
<p>This is not a component library. It is how you build your component library.</p>
</blockquote>
<p>You won't add shadcn/ui as a regular dependency in <code>package.json</code>. It uses a <strong>registry</strong> instead. A registry is a collection of JSON files hosted on a server. Each file describes a component and includes the information the CLI needs to add it to your project. When you run the CLI, it reads the relevant file and copies the component's source code into your project.</p>
<p>To see what this looks like, here's the registry entry for the <strong>Badge</strong> component. A Badge is a small label, such as the "Medium" tag next to a coffee in the cart you will build later. This is a shortened version of the real file:</p>
<pre><code class="language-json">{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "badge",
  "type": "registry:ui",
  "title": "Badge",
  "author": "@mrzachnugent",
  "description": "Displays a badge or a component that looks like a badge.",
  "dependencies": ["@rn-primitives/slot"],
  "registryDependencies": ["https://reactnativereusables.com/r/uniwind/text.json"],
  "files": [
    {
      "path": "./node_modules/@rnr/registry/src/uniwind/components/ui/badge.tsx",
      "content": "import { TextClassContext } from '@/components/ui/text';\nimport ...",
      "type": "registry:ui"
    }
  ]
}
</code></pre>
<p>The file is public, so you can look at it yourself:</p>
<pre><code class="language-bash">curl https://reactnativereusables.com/r/uniwind/badge.json
</code></pre>
<p>Here's what the important fields mean:</p>
<ul>
<li><code>content</code> holds the full source code of the component, stored as a string.</li>
<li><code>dependencies</code> lists npm packages that the component needs. The CLI installs these first.</li>
<li><code>registryDependencies</code> lists other registry entries that the component needs. In this case, Badge needs the <strong>Text</strong> component, which is a small wrapper around React Native's <code>Text</code> that you will read about in Step 3. When you run the CLI to add Badge, it also adds Text for you because of this field.</li>
</ul>
<p>That's how a component gets from the registry into your app. The registry stores the component information, and the CLI uses it to create the files in your repository. React Native Reusables uses the shadcn CLI behind the scenes, so you can follow the same workflow when adding React Native components.</p>
<p>There are a few reasons this approach is useful when you're building an app:</p>
<ol>
<li><strong>You own the file:</strong> A component such as <code>components/ui/button.tsx</code> sits in your repository and shows up in your Git diffs. If you want a darker pressed state, you edit that line. You don't need to invent a new prop, maintain a fork, or open an issue.</li>
<li><strong>Design lives in named colors instead of props:</strong> Colors are declared once as named roles, such as <code>primary</code>, <code>muted</code>, <code>border</code>, and <code>destructive</code>. You then use them in class names, like <code>className="bg-primary"</code>. This replaces the <code>colors.ts</code> file from the introduction, because there's one place that defines your colors, and every component reads from it. You'll set this up in Step 2.</li>
<li><strong>Behavior comes from a separate package:</strong> Things such as focus handling, open and close state, and screen reader support live in RN Primitives. You only write the styling.</li>
</ol>
<p>There's one trade-off to keep in mind. Since the component code is copied into your project, updates from the registry aren't applied automatically. If a bug is fixed upstream, you'll need to run the CLI again with <code>--overwrite</code>. If you have customized that component, you may also need to reapply your changes. This is worth considering before you make large changes to several components.</p>
<h2 id="heading-what-react-native-reusables-gives-you">What React Native Reusables Gives You</h2>
<p>At the time of writing, React Native Reusables includes thirty components: accordion, alert, alert-dialog, aspect-ratio, avatar, badge, button, card, checkbox, collapsible, context-menu, dialog, dropdown-menu, hover-card, input, label, menubar, popover, progress, radio-group, select, separator, skeleton, switch, tabs, text, textarea, toggle, toggle-group, and tooltip. The available components cover many of the building blocks you need for a typical app interface.</p>
<p>React Native is different from the web in several ways, so the components can't be an exact copy of the web version. The documentation lists the main differences, and you'll run into each of them in this tutorial. If you're also building web interfaces with shadcn/ui, <a href="https://shadcnstudio.com/components">shadcn components</a> can be useful when you need more ready-made examples to work from.</p>
<table>
<thead>
<tr>
<th>The difference</th>
<th>What it means</th>
<th>Where you will see it</th>
</tr>
</thead>
<tbody><tr>
<td>Portals need a <code>PortalHost</code></td>
<td>On the web, floating content such as dropdowns renders into <code>document.body</code>. React Native has no <code>document.body</code>, so you need a <code>PortalHost</code> component to render into.</td>
<td>Step 7</td>
</tr>
<tr>
<td>Styles don't cascade</td>
<td>A text color set on a parent view doesn't reach the text inside it, so React Native Reusables uses a <code>Text</code> component with a workaround.</td>
<td>Step 3</td>
</tr>
<tr>
<td>There are no <code>data-*</code> attributes</td>
<td>Web shadcn changes styles based on attributes like <code>data-state</code>. React Native has none, so variants depend on props and state.</td>
<td>Step 7</td>
</tr>
<tr>
<td>Icons take props instead of classes</td>
<td>Icon libraries expect <code>color</code> and <code>size</code> props, so icons are wrapped to accept class names.</td>
<td>Step 3</td>
</tr>
</tbody></table>
<h2 id="heading-what-youre-building">What You're Building</h2>
<p>We'll build a cart and checkout screen for a coffee shop where customers place an order and pick it up at the counter. The screen uses twelve components from the registry. While putting it together, I'll also explain a few React Native details that are easy to miss, including how dropdowns are rendered, how safe areas affect the layout, and how to keep the checkout bar visible while the rest of the page scrolls:</p>
<table>
<thead>
<tr>
<th>Part of the screen</th>
<th>Components used</th>
<th>The mobile problem it teaches</th>
</tr>
</thead>
<tbody><tr>
<td>Item rows</td>
<td>Card, Avatar, Badge, Button</td>
<td>No cascading styles, no <code>truncate</code>, small tap targets</td>
</tr>
<tr>
<td>Quantity stepper</td>
<td>Button, Icon</td>
<td>Icons take props, not classes</td>
</tr>
<tr>
<td>Pickup time</td>
<td>Select, Label</td>
<td>Dropdowns need a portal</td>
</tr>
<tr>
<td>Name field</td>
<td>Input, Label</td>
<td>The keyboard can cover the field</td>
</tr>
<tr>
<td>Own cup toggle</td>
<td>Switch, Label</td>
<td>Making the label text tappable</td>
</tr>
<tr>
<td>Bill</td>
<td>Separator, Text</td>
<td>Digits that don't line up</td>
</tr>
<tr>
<td>Checkout bar</td>
<td>Button, AlertDialog</td>
<td>No <code>position: fixed</code>, and the home indicator</td>
</tr>
</tbody></table>
<p>Here's the finished screen:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/a30e05d8-efcb-41ed-ad2c-fd22763d7ea2.png" alt="The finished cart screen in light mode" style="display: block;" width="414" height="896" loading="lazy">

<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/f24bc348-c9a2-4197-92a6-c60479fb3686.png" alt="The finished cart screen in dark mode" style="display: block;" width="414" height="896" loading="lazy">

<p>The complete code is available in the <a href="https://github.com/shadcnstudio/shadcn-react-native-app">GitHub repository</a> if you want to compare your work with the final result.</p>
<h2 id="heading-step-1-create-the-app">Step 1: Create the App</h2>
<p>We can let the React Native Reusables CLI create the initial project for us. It sets up Expo Router, the styling configuration, the theme file, and a few starter components. Run the following command to get started:</p>
<pre><code class="language-bash">pnpm dlx @react-native-reusables/cli@latest init
</code></pre>
<h3 id="heading-answer-the-clis-questions">Answer the CLI's Questions</h3>
<p>The CLI asks four questions.</p>
<p><strong>What is the name of your project?</strong> The name you type becomes the folder name. It suggests <code>my-app</code>.</p>
<p><strong>Select a template.</strong> There are three options, and the one you need isn't the one selected by default:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/7ce945cb-ac0e-49f0-990b-c0c2cf956f29.png" alt="The template selection prompt in the terminal" style="display: block;" width="556" height="141" loading="lazy">

<pre><code class="language-plaintext">❯ Minimal (Nativewind)
  Minimal (Uniwind)
  Clerk auth (Nativewind)
</code></pre>
<p>Press the down arrow once and choose <strong>Minimal (Uniwind)</strong>. This is the one choice that's tricky to change later. Nativewind and Uniwind are two different ways to use Tailwind in React Native, and the CLI keeps a separate registry for each one. The components it writes for Uniwind are different from the ones it writes for Nativewind, so the code in this tutorial won't match if you pick Nativewind.</p>
<p><strong>Would you like to install dependencies?</strong> Choose yes, and select the package manager you use.</p>
<p><strong>Would you like to initialize a Git repository?</strong> Choose yes. You're about to replace the starter screen, and having a commit to compare against is helpful.</p>
<h3 id="heading-look-at-the-project-structure">Look at the Project Structure</h3>
<p>The CLI creates the following files:</p>
<pre><code class="language-plaintext">shadcn-react-native-app/
├── app/
│   ├── _layout.tsx        # ThemeProvider, Stack, and the PortalHost
│   ├── +html.tsx          # web only, the root HTML shell
│   ├── +not-found.tsx
│   └── index.tsx          # the starter screen
├── components/ui/
│   ├── button.tsx
│   ├── icon.tsx
│   └── text.tsx
├── lib/
│   ├── theme.ts           # the same palette again, in JavaScript
│   └── utils.ts           # cn()
├── global.css             # the theme tokens
├── components.json        # the shadcn config, same as on the web
├── metro.config.js        # withUniwindConfig
└── uniwind-types.d.ts     # generated, do not edit
</code></pre>
<p>Before moving on, let's take a look at a few files in this structure. You'll use them throughout the tutorial:</p>
<ul>
<li><code>components.json</code> is the same shadcn configuration file used on the web. It tells the CLI where to put components (<code>@/components/ui</code>) and where the <code>cn()</code> helper lives (<code>@/lib/utils</code>).</li>
<li><code>global.css</code> holds your theme tokens, which you'll learn about in Step 2.</li>
<li><code>lib/utils.ts</code> exports <code>cn()</code>, a helper that combines class names and resolves conflicts between them.</li>
<li><code>app/_layout.tsx</code> contains a <code>PortalHost</code> component. It looks like leftover scaffolding, but you must not delete it. Step 7 explains why.</li>
</ul>
<p>Uniwind reads <code>global.css</code> while Metro bundles the app and turns your class strings into React Native style objects. This happens at build time, so a long <code>className</code> string doesn't slow down your app.</p>
<h3 id="heading-run-the-app">Run the App</h3>
<p>Start the development server:</p>
<pre><code class="language-bash">pnpm dev
</code></pre>
<p>Press <code>w</code> to open it in the browser, <code>i</code> for the iOS simulator, or <code>a</code> for Android. The starter screen has a theme toggle in the header, which shows that the theme setup is working.</p>
<p>You can also run a diagnostic command at any point if something seems wrong:</p>
<pre><code class="language-bash">pnpm dlx @react-native-reusables/cli@latest doctor
</code></pre>
<p>It checks your setup and reports which styling library it detects. For this project, the output should be:</p>
<pre><code class="language-plaintext">ℹ Styling Library: Uniwind
✔ All checks passed.
</code></pre>
<p>If it says Nativewind, fix that before you add any components.</p>
<p>Once the setup is working, you should see the starter screen. Try the theme toggle in the header to make sure light and dark mode both work, and check that the console is free of errors:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/72fbc819-a026-41cb-824d-6f50b9e88625.png" alt="The starter screen" style="display: block;" width="414" height="896" loading="lazy">

<h2 id="heading-step-2-understand-the-theme-file">Step 2: Understand the Theme File</h2>
<p>Now that the app is running, let's look at its theme setup. The <code>global.css</code> file is where we'll define the colors used by the components. If you've previously kept these values in a <code>colors.ts</code> or <code>theme.ts</code> file, this is the setup that replaces it.</p>
<pre><code class="language-css">@import "tailwindcss";
@import "uniwind";

@import "tw-animate-css";

@theme {
  --radius: 10px;
  --radius-sm: calc(var(--radius) - 4px);
  --radius-md: calc(var(--radius) - 2px);
  --radius-lg: var(--radius);
  --radius-xl: calc(var(--radius) + 4px);

  --spacing-hairline: hairlineWidth();
}

@layer theme {
  :root {
    @variant light {
      --color-background: oklch(1 0 0);
      --color-foreground: oklch(0.145 0 0);
      --color-card: oklch(1 0 0);
      --color-primary: oklch(0.205 0 0);
      --color-muted-foreground: oklch(0.556 0 0);
      --color-border: oklch(0.922 0 0);
      /* the rest of the list */
    }

    @variant dark {
      --color-background: oklch(0.145 0 0);
      --color-foreground: oklch(0.985 0 0);
      --color-card: oklch(0.205 0 0);
      --color-primary: oklch(0.922 0 0);
      --color-muted-foreground: oklch(0.708 0 0);
      --color-border: oklch(1 0 0 / 10%);
      /* the rest of the list */
    }
  }
}
</code></pre>
<p>There are two conventions in this file that you need to know.</p>
<p>First, the <code>--color-</code> prefix creates the class names. When you declare <code>--color-primary</code>, Tailwind automatically creates <code>bg-primary</code>, <code>text-primary</code>, and <code>border-primary</code>. If you declare <code>--primary</code> instead, you only get a CSS variable that nothing uses.</p>
<p>This is important because most shadcn theme generators produce the web format, where the variables are named <code>--primary</code>. If you paste that output without renaming the variables, nothing breaks, but nothing changes either. Step 12 shows you how to convert them.</p>
<p>Second, <code>@variant light</code> and <code>@variant dark</code> replace <code>:root</code> and <code>.dark</code>. On the web, dark mode works by adding a <code>.dark</code> class to the page. A phone has no page to add a class to, so Uniwind manages the switch. When you call <code>Uniwind.setTheme</code>, it swaps the active values. You'll use this in Step 11.</p>
<p>You may also notice that the file uses <code>oklch()</code> colors. Phones don't have a browser to read that format, but Uniwind converts the colors to a format React Native understands while bundling, so you can use modern color syntax anyway.</p>
<h3 id="heading-the-palette-also-exists-in-libthemets">The Palette Also Exists in <code>lib/theme.ts</code></h3>
<p>If you open <code>lib/theme.ts</code>, you'll find the same colors again as a JavaScript object. This duplication is needed because React Navigation, which draws the header and screen background, reads colors from a plain JavaScript object and can't read CSS variables. As a result, you have to keep two copies of your palette in sync. Step 12 shows what happens when they differ.</p>
<h3 id="heading-try-it-change-one-color">Try It: Change One Color</h3>
<p>Let's change one of the tokens to see how the theme works. Update the primary color in the light theme to a value that's easy to notice:</p>
<pre><code class="language-css">--color-primary: oklch(0.6 0.24 25);
</code></pre>
<p>Save the file and look at the starter screen. The <strong>Browse the Docs</strong> button is now red, even though you didn't edit <code>button.tsx</code>:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/0d2116eb-9052-40a1-9163-69f1a89dbd14.png" alt="The starter button turned red after changing one token" style="display: block;" width="414" height="896" loading="lazy">

<p>Notice that every component using <code>bg-primary</code> picks up the new color. You only changed one token, but the button updated without touching its component file. Change the value back before continuing.</p>
<h2 id="heading-step-3-read-three-core-components">Step 3: Read Three Core Components</h2>
<p>The starter project already gives us three components: <code>Text</code>, <code>Button</code>, and <code>Icon</code>. I'd take a few minutes to look through them before building the screen. They introduce patterns you'll see again in the other registry components.</p>
<h3 id="heading-the-text-component">The Text Component</h3>
<p>In React Native, styles don't cascade the way they do in CSS. If you set a text color on a <code>View</code>, the text inside it doesn't inherit that color. This is a problem for a component such as <code>&lt;Button variant="destructive"&gt;</code>, which needs its label to be white. The label is a <code>Text</code> component that the Button doesn't control, because it comes in through <code>children</code>. On the web, the Button would simply set a color and let it flow down to the label.</p>
<p>React Native Reusables solves this with React context. This is the code in <code>components/ui/text.tsx</code>:</p>
<pre><code class="language-tsx">const TextClassContext = React.createContext&lt;string | undefined&gt;(undefined);

function Text({ className, asChild = false, variant = 'default', ...props }) {
  const textClass = React.useContext(TextClassContext);
  const Component = asChild ? Slot : RNText;
  return (
    &lt;Component
      className={cn(textVariants({ variant }), textClass, className)}
      role={variant ? ROLE[variant] : undefined}
      aria-level={variant ? ARIA_LEVEL[variant] : undefined}
      {...props}
    /&gt;
  );
}
</code></pre>
<p>A parent component, such as Button, puts a class string into the context. Every <code>Text</code> inside it reads that string and applies it. Your own <code>className</code> still wins because it comes last in the <code>cn()</code> call.</p>
<p>The <code>Text</code> component also has a <code>variant</code> prop with options like <code>h1</code> to <code>h4</code>, <code>p</code>, <code>code</code>, <code>lead</code>, <code>large</code>, <code>small</code>, and <code>muted</code>. For example, <code>&lt;Text variant="muted"&gt;</code> gives you the mobile version of <code>text-muted-foreground text-sm</code>. The variants also set the <code>role</code> and <code>aria-level</code> props, so screen readers announce headings correctly without any extra work.</p>
<h3 id="heading-the-button-component">The Button Component</h3>
<p>The Button in <code>components/ui/button.tsx</code> uses <code>cva</code> (class-variance-authority) the same way the web version does. Here's a shortened version:</p>
<pre><code class="language-tsx">const buttonVariants = cva(
  cn(
    'group shrink-0 flex-row items-center justify-center gap-2 rounded-md shadow-none',
    Platform.select({
      web: "focus-visible:border-ring focus-visible:ring-ring/50 ... transition-all",
    })
  ),
  {
    variants: {
      variant: {
        default: cn(
          'bg-primary active:bg-primary/90 shadow-sm shadow-black/5',
          Platform.select({ web: 'hover:bg-primary/90' })
        ),
        /* ... */
      },
    },
  }
);
</code></pre>
<p>There are four differences from the web version:</p>
<ul>
<li><code>flex-row</code> <strong>is written out:</strong> React Native lays out children in a column by default, which is the opposite of CSS. Every horizontal layout in this tutorial includes <code>flex-row</code> for that reason.</li>
<li><code>active:</code> <strong>replaces</strong> <code>hover:</code><strong>:</strong> A finger can't really hover, so <code>active:</code> is the pressed state on a phone.</li>
<li><strong>Web-only classes are wrapped in</strong> <code>Platform.select</code><strong>:</strong> Classes such as <code>focus-visible:ring-[3px]</code> mean nothing in React Native, so they're only included in the web build.</li>
<li><strong>A</strong> <code>TextClassContext.Provider</code> <strong>wraps the</strong> <code>Pressable</code><strong>:</strong> This uses the context from the previous section, and it's why <code>&lt;Button variant="destructive"&gt;&lt;Text&gt;Delete&lt;/Text&gt;&lt;/Button&gt;</code> has white text automatically.</li>
</ul>
<h3 id="heading-the-icon-component">The Icon Component</h3>
<p>Icons from <code>lucide-react-native</code> take <code>color</code> and <code>size</code> as props, not as class names. The <code>Icon</code> component in <code>components/ui/icon.tsx</code> teaches Uniwind how to convert one into the other:</p>
<pre><code class="language-tsx">const StyledIcon = withUniwind(IconImpl, {
  size: { fromClassName: 'className', styleProperty: 'width' },
  color: { fromClassName: 'className', styleProperty: 'color' },
});
</code></pre>
<p>This code reads the <code>width</code> from the class string and passes it as <code>size</code>, and it reads the <code>color</code> and passes it as <code>color</code>. That's why <code>&lt;Icon as={PlusIcon} className="size-4 text-muted-foreground" /&gt;</code> works the way you would expect. <code>withUniwind</code> is useful any time you use a third-party component that takes props where you want to use classes.</p>
<p>You don't need to run anything for this step. The important part is understanding what <code>TextClassContext</code> is doing. Once that clicks, the other components in the registry are much easier to follow.</p>
<h2 id="heading-step-4-add-the-components-you-need">Step 4: Add the Components You Need</h2>
<p>We already have three components from the template. For the checkout screen, we need a few more. The CLI can add all of them in one go:</p>
<pre><code class="language-bash">pnpm dlx @react-native-reusables/cli@latest add card separator input label select switch badge alert-dialog avatar
</code></pre>
<p>The CLI detects that you're using Uniwind and writes the matching versions. It also installs any required <code>@rn-primitives</code> packages and adds a file called <code>native-only-animated-view.tsx</code>, which Select and AlertDialog use for their animations.</p>
<p>The output looks like this:</p>
<pre><code class="language-plaintext">ℹ Styling Library: Uniwind
✔ Created 10 files:
  - components/ui/separator.tsx
  - components/ui/input.tsx
  - components/ui/label.tsx
  - components/ui/switch.tsx
  - components/ui/avatar.tsx
  - components/ui/native-only-animated-view.tsx
  - components/ui/card.tsx
  - components/ui/badge.tsx
  - components/ui/select.tsx
  - components/ui/alert-dialog.tsx
ℹ Skipped 3 files: (files might be identical, use --overwrite to overwrite)
  - components/ui/text.tsx
  - components/ui/icon.tsx
  - components/ui/button.tsx
</code></pre>
<p>The CLI created ten files, which is more than the nine you asked for, because <code>native-only-animated-view.tsx</code> is a dependency of Select and AlertDialog. It skipped the three files that the template already gave you, so it does not overwrite your copies. This is the "you own the file" idea at work.</p>
<p>Run <code>pnpm dev</code> again to make sure the app still starts. The <code>components/ui/</code> folder should now contain thirteen files.</p>
<h2 id="heading-step-5-set-up-the-data-and-the-screen">Step 5: Set Up the Data and the Screen</h2>
<p>Before we start building the UI, let's add the sample menu data and decide where the screen state will live. I'm going to store prices in cents rather than floating-point numbers. This avoids calculation results such as <code>$4.7499999</code>.</p>
<p>We'll also keep the state in the main screen component and pass the relevant values down as props. That way, changing an item quantity or selecting the own-cup option automatically updates the bill.</p>
<p>Create <code>lib/menu.ts</code>:</p>
<pre><code class="language-tsx">export type CartItem = {
  id: string;
  name: string;
  detail: string;
  size?: 'Small' | 'Medium' | 'Large';
  emoji: string;
  /** Cents. Money in floats is how you end up charging someone $4.7499999. */
  unitPrice: number;
  qty: number;
};

export const INITIAL_CART: CartItem[] = [
  {
    id: 'flat-white',
    name: 'Flat white',
    detail: 'Oat milk, extra shot',
    size: 'Medium',
    emoji: '☕️',
    unitPrice: 475,
    qty: 2,
  },
  {
    id: 'cold-brew',
    name: 'Cold brew',
    detail: 'Hold the ice',
    size: 'Large',
    emoji: '🧋',
    unitPrice: 525,
    qty: 1,
  },
  {
    id: 'croissant',
    name: 'Almond croissant',
    detail: 'Warmed',
    emoji: '🥐',
    unitPrice: 390,
    qty: 1,
  },
];

export const PICKUP_TIMES = [
  { value: 'asap', label: 'As soon as it is ready' },
  { value: '15', label: 'In 15 minutes' },
  { value: '30', label: 'In 30 minutes' },
  { value: '60', label: 'In an hour' },
];

export const CUP_DISCOUNT = 25;
export const TAX_RATE = 0.0825;

export function money(cents: number) {
  const sign = cents &lt; 0 ? '-' : '';
  return `${sign}$${(Math.abs(cents) / 100).toFixed(2)}`;
}

export function billFor(items: CartItem[], ownCup: boolean) {
  const subtotal = items.reduce((sum, item) =&gt; sum + item.unitPrice * item.qty, 0);
  const discount = ownCup &amp;&amp; subtotal &gt; 0 ? CUP_DISCOUNT : 0;
  const tax = Math.round((subtotal - discount) * TAX_RATE);

  return { subtotal, discount, tax, total: subtotal - discount + tax };
}
</code></pre>
<p>The <code>PICKUP_TIMES</code> list is in this file instead of inside a component because two different components need it. You'll see why in Step 7.</p>
<h3 id="heading-the-screen-layout">The Screen Layout</h3>
<p>This is basically how <code>app/index.tsx</code> looks. The parts that don't exist yet are left as comments, and you'll write the full file later in Step 10.</p>
<pre><code class="language-tsx">&lt;View className="bg-background flex-1"&gt;
  &lt;ScrollView
    className="flex-1"
    contentContainerClassName="gap-4 p-4 pb-8"
    keyboardShouldPersistTaps="handled"
    automaticallyAdjustKeyboardInsets&gt;
    {/* the three cards */}
  &lt;/ScrollView&gt;

  &lt;CheckoutBar {...} /&gt;
&lt;/View&gt;
</code></pre>
<p>There are three details in this layout that you should examine more closely:</p>
<ul>
<li>First, <code>className</code> on a <code>ScrollView</code> styles the scroll container, not its content. This is the class name version of the <code>style</code> and <code>contentContainerStyle</code> split in React Native. If you put padding in <code>className</code>, it gets clipped, and <code>gap</code> has no effect. Use <code>contentContainerClassName</code> for anything that should apply to the content. Uniwind adds this prop to <code>ScrollView</code>.</li>
<li>There's no <code>space-y-4</code>. In CSS, <code>space-y-*</code> works by selecting siblings, and React Native has no selectors. Use <code>gap-4</code> on the parent instead, which React Native supports on iOS, Android, and the web.</li>
<li><code>keyboardShouldPersistTaps="handled"</code> keeps taps working while the keyboard is open. Without it, the first tap after the keyboard appears only closes the keyboard, so the user has to tap twice. <code>automaticallyAdjustKeyboardInsets</code> is an iOS feature that scrolls the content so the focused input isn't hidden behind the keyboard.</li>
</ul>
<p>At this stage, you should see only a header with the new title and an empty page below it:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/02188707-8809-4cc8-bc1d-1a79330bebd3.png" alt="An empty screen with the new header title" style="display: block;" width="414" height="896" loading="lazy">

<h2 id="heading-step-6-build-the-order-rows">Step 6: Build the Order Rows</h2>
<p>The order row has quite a bit going on in a small space: an avatar, product name, size badge, price, and quantity controls. Long names make this especially tricky on a phone, so we'll handle the layout carefully.</p>
<p>Create <code>components/cart/order-row.tsx</code>:</p>
<pre><code class="language-tsx">import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
import { Text } from '@/components/ui/text';
import { money, type CartItem } from '@/lib/menu';
import { MinusIcon, PlusIcon, Trash2Icon } from 'lucide-react-native';
import { View } from 'react-native';

type OrderRowProps = {
  item: CartItem;
  onChangeQty: (id: string, qty: number) =&gt; void;
};

export function OrderRow({ item, onChangeQty }: OrderRowProps) {
  const lastOne = item.qty &lt;= 1;

  return (
    &lt;View className="flex-row gap-3"&gt;
      &lt;Avatar alt={item.name} className="size-14 rounded-2xl"&gt;
        &lt;AvatarFallback className="bg-muted rounded-2xl"&gt;
          &lt;Text className="text-2xl"&gt;{item.emoji}&lt;/Text&gt;
        &lt;/AvatarFallback&gt;
      &lt;/Avatar&gt;

      &lt;View className="flex-1 gap-2"&gt;
        &lt;View className="flex-row items-start gap-3"&gt;
          &lt;View className="flex-1 gap-1"&gt;
            &lt;View className="flex-row items-center gap-2"&gt;
              &lt;Text numberOfLines={1} className="shrink font-medium"&gt;
                {item.name}
              &lt;/Text&gt;
              {item.size ? (
                &lt;Badge variant="secondary"&gt;
                  &lt;Text&gt;{item.size}&lt;/Text&gt;
                &lt;/Badge&gt;
              ) : null}
            &lt;/View&gt;
            &lt;Text numberOfLines={1} variant="muted"&gt;
              {item.detail}
            &lt;/Text&gt;
          &lt;/View&gt;
          &lt;Text className="text-sm font-medium tabular-nums"&gt;
            {money(item.unitPrice * item.qty)}
          &lt;/Text&gt;
        &lt;/View&gt;

        &lt;View className="border-border flex-row items-center gap-1 self-start rounded-full border p-0.5"&gt;
          &lt;Button
            size="icon"
            variant="ghost"
            hitSlop={8}
            className="size-7 rounded-full"
            accessibilityLabel={lastOne ? `Remove ${item.name}` : `One fewer ${item.name}`}
            onPress={() =&gt; onChangeQty(item.id, item.qty - 1)}&gt;
            &lt;Icon as={lastOne ? Trash2Icon : MinusIcon} className="size-4" /&gt;
          &lt;/Button&gt;
          &lt;Text className="w-5 text-center text-sm font-medium tabular-nums"&gt;{item.qty}&lt;/Text&gt;
          &lt;Button
            size="icon"
            variant="ghost"
            hitSlop={8}
            className="size-7 rounded-full"
            accessibilityLabel={`One more ${item.name}`}
            onPress={() =&gt; onChangeQty(item.id, item.qty + 1)}&gt;
            &lt;Icon as={PlusIcon} className="size-4" /&gt;
          &lt;/Button&gt;
        &lt;/View&gt;
      &lt;/View&gt;
    &lt;/View&gt;
  );
}
</code></pre>
<p>A few details in this component deserve a closer look.</p>
<p>First, <code>Avatar</code> requires the <code>alt</code> prop. TypeScript won't compile without it. The value becomes the accessibility label, so a screen reader says "Flat white" instead of just "image".</p>
<p>The radius is repeated on the avatar fallback. <code>Avatar</code> and <code>AvatarFallback</code> are each <code>rounded-full</code> by default. If you only set <code>rounded-2xl</code> on <code>Avatar</code>, the emoji background stays a circle and pokes out of the rounded square.</p>
<p>You should also use <code>numberOfLines={1}</code> instead of <code>truncate</code>. Tailwind's <code>truncate</code> relies on <code>text-overflow: ellipsis</code>, which React Native doesn't support, and Uniwind doesn't convert it. The class compiles to nothing, so a long product name pushes the price off the screen. The <code>numberOfLines</code> prop is the React Native way to do this, and it also works in the web build.</p>
<p>The name has <code>shrink</code> and its column has <code>flex-1</code>. Without <code>shrink</code>, a long name won't get smaller and will push the badge out of the row. This is regular Flexbox behavior, but it shows up more on a phone because there's less width to work with.</p>
<p><code>hitSlop={8}</code> makes small buttons easier to tap. Apple recommends touch targets of at least 44 points and Android recommends 48dp, but a <code>size-7</code> button is only 28 points wide. The <code>hitSlop</code> prop makes the touchable area larger without changing how the button looks. There's no CSS equivalent.</p>
<p>Finally, <code>tabular-nums</code> keeps digits the same width. In most fonts, the digit <code>1</code> is narrower than <code>8</code>, so prices would shift sideways every time the quantity changes. Uniwind converts <code>tabular-nums</code> to React Native's <code>fontVariant</code>, so it works on iOS, Android, and the web.</p>
<p>After adding this component and rendering it inside a Card (which you'll do in Step 10), you should see three rows:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/d361c2e7-8eaa-466d-aed1-7b162b6ace95.png" alt="The order rows inside a card" style="display: block;" width="414" height="896" loading="lazy">

<p>Tapping plus on the flat white should change its price from <code>$9.50</code> to <code>$14.25</code>. Tapping the trash icon on an item with a quantity of one should remove the row. The minus button turns into a trash icon whenever the quantity is one.</p>
<h2 id="heading-step-7-build-the-pickup-options">Step 7: Build the Pickup Options</h2>
<p>The pickup card brings together three controls: a Select, an Input, and a Switch. The input and switch are fairly straightforward. The Select needs a little more attention because it has three platform-related quirks, and two of them can fail silently.</p>
<p>Create <code>components/cart/pickup-card.tsx</code>:</p>
<pre><code class="language-tsx">import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Text } from '@/components/ui/text';
import { PICKUP_TIMES } from '@/lib/menu';
import { View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

type PickupCardProps = {
  pickupValue: string;
  onPickupValueChange: (value: string) =&gt; void;
  name: string;
  onNameChange: (value: string) =&gt; void;
  ownCup: boolean;
  onOwnCupChange: (value: boolean) =&gt; void;
};

export function PickupCard({
  pickupValue,
  onPickupValueChange,
  name,
  onNameChange,
  ownCup,
  onOwnCupChange,
}: PickupCardProps) {
  const insets = useSafeAreaInsets();
  // Look the label up from our own data. The Option handed back by onValueChange
  // does not carry a usable label on web. See the note below.
  const selected = PICKUP_TIMES.find((time) =&gt; time.value === pickupValue);
  const contentInsets = {
    top: insets.top,
    bottom: insets.bottom,
    left: 16,
    right: 16,
  };

  return (
    &lt;View className="gap-5"&gt;
      &lt;View className="gap-2"&gt;
        &lt;Label nativeID="pickup-time"&gt;Pickup time&lt;/Label&gt;
        &lt;Select
          value={selected}
          onValueChange={(option) =&gt; {
            if (option) {
              onPickupValueChange(option.value);
            }
          }}&gt;
          &lt;SelectTrigger className="w-full" aria-labelledby="pickup-time"&gt;
            &lt;SelectValue placeholder="Pick a time" /&gt;
          &lt;/SelectTrigger&gt;
          &lt;SelectContent insets={contentInsets} className="w-full"&gt;
            {PICKUP_TIMES.map((time) =&gt; (
              &lt;SelectItem key={time.value} value={time.value} label={time.label} /&gt;
            ))}
          &lt;/SelectContent&gt;
        &lt;/Select&gt;
      &lt;/View&gt;

      &lt;View className="gap-2"&gt;
        &lt;Label nativeID="order-name"&gt;Name for the order&lt;/Label&gt;
        &lt;Input
          aria-labelledby="order-name"
          value={name}
          onChangeText={onNameChange}
          placeholder="Who is picking it up?"
          autoCapitalize="words"
          autoComplete="name"
          returnKeyType="done"
        /&gt;
      &lt;/View&gt;

      &lt;View className="flex-row items-center justify-between gap-4"&gt;
        &lt;View className="flex-1 gap-1"&gt;
          &lt;Label nativeID="own-cup" onPress={() =&gt; onOwnCupChange(!ownCup)}&gt;
            Bringing my own cup
          &lt;/Label&gt;
          &lt;Text variant="muted"&gt;Takes 25¢ off and saves a lid.&lt;/Text&gt;
        &lt;/View&gt;
        &lt;Switch nativeID="own-cup" checked={ownCup} onCheckedChange={onOwnCupChange} /&gt;
      &lt;/View&gt;
    &lt;/View&gt;
  );
}
</code></pre>
<h3 id="heading-problem-1-portals-and-the-portalhost">Problem 1: Portals and the PortalHost</h3>
<p>When a dropdown opens, it needs to appear above the other content on the screen. For that reason, <code>SelectContent</code> isn't rendered in the same place where you declare it in the component tree. It uses <code>@rn-primitives/portal</code> to render the content in another part of the app. This technique is called a portal.</p>
<p>On the web, a portal renders into <code>document.body</code>, and every page has one. React Native has nothing like that. So the portal package keeps a list of portal contents in memory, and a component called <code>PortalHost</code> reads that list and displays it. This is a simplified version of that code from <code>node_modules/@rn-primitives/portal/dist/index.js</code>:</p>
<pre><code class="language-jsx">var DEFAULT_PORTAL_HOST = "INTERNAL_PRIMITIVE_DEFAULT_HOST_NAME";
var updatePortal = (hostName, name, children) =&gt; { /* writes into the map */ };
function PortalHost({ name = DEFAULT_PORTAL_HOST }) { /* reads the map */ }
</code></pre>
<p>If no <code>PortalHost</code> is mounted, the content is saved but never displayed. The dropdown opens into nothing, and you get no error or warning.</p>
<p>The template already includes a <code>PortalHost</code> at the bottom of the root layout:</p>
<pre><code class="language-tsx">&lt;ThemeProvider value={NAV_THEME[theme ?? 'light']}&gt;
  &lt;StatusBar style={theme === 'dark' ? 'light' : 'dark'} /&gt;
  &lt;Stack /&gt;
  &lt;PortalHost /&gt;
&lt;/ThemeProvider&gt;
</code></pre>
<p>It looks like unnecessary code, but you need to keep it. The AlertDialog in Step 10 uses it too.</p>
<h3 id="heading-problem-2-safe-area-insets">Problem 2: Safe Area Insets</h3>
<p>There's another issue to consider when showing a dropdown on a phone. Parts of the screen are reserved for the operating system, such as the area around the notch and the home indicator. If a dropdown opens near the bottom of the screen, one of its options could appear underneath the home indicator. In that area, a tap may be handled by the operating system instead of your app.</p>
<p>To avoid this, pass the safe area insets to the content:</p>
<pre><code class="language-tsx">const insets = useSafeAreaInsets();
const contentInsets = { top: insets.top, bottom: insets.bottom, left: 16, right: 16 };

&lt;SelectContent insets={contentInsets} className="w-full"&gt;
</code></pre>
<p>The <code>insets</code> prop is part of <code>PositionedContentProps</code> in <code>@rn-primitives/types</code>, so every positioned component in the registry accepts it, including Popover, DropdownMenu, HoverCard, Tooltip, and Select. It's a good habit to pass it every time.</p>
<h3 id="heading-problem-3-the-select-value-is-an-object">Problem 3: The Select Value Is an Object</h3>
<p>One more thing to watch out for is the value returned by <code>onValueChange</code>. It may look like you're selecting a string, but the callback returns an <code>Option</code> object:</p>
<pre><code class="language-tsx">type Option = { value: string; label: string } | undefined;
</code></pre>
<p>This causes a bug that only appears on one platform. If you store the whole <code>Option</code> in state and show <code>option.label</code> later, such as in a confirmation dialog, it displays correctly on a phone ("In 30 minutes") but incorrectly in the browser ("30").</p>
<p>The reason is in the primitive's source code. This is the native version, from <code>select.js</code>:</p>
<pre><code class="language-jsx">onValueChange({ value: itemValue, label });
</code></pre>
<p>And this is the web version, from <code>select.web.js</code>. It uses Radix, which only returns a value:</p>
<pre><code class="language-jsx">onValueChange({ value: val, label: val });
</code></pre>
<p>So the label is correct on native, but on the web it's a copy of the value. If you only test in a simulator, you won't notice this problem.</p>
<p>The fix is to keep only the value in state and look up the label from your own list:</p>
<pre><code class="language-tsx">const selected = PICKUP_TIMES.find((time) =&gt; time.value === pickupValue);
</code></pre>
<p>This is why <code>PICKUP_TIMES</code> is in <code>lib/menu.ts</code>. The pickup card needs it to build the options, and the main screen needs it to write the confirmation message.</p>
<h3 id="heading-making-the-label-tappable">Making the Label Tappable</h3>
<p>The switch itself is quite small, so users may tap the label next to it instead. It makes sense to let that label toggle the switch as well. You can do that by adding an <code>onPress</code> handler to the <code>Label</code>:</p>
<pre><code class="language-tsx">&lt;Label nativeID="own-cup" onPress={() =&gt; onOwnCupChange(!ownCup)}&gt;
  Bringing my own cup
&lt;/Label&gt;
&lt;Switch nativeID="own-cup" checked={ownCup} onCheckedChange={onOwnCupChange} /&gt;
</code></pre>
<p>Giving both elements the same <code>nativeID</code> connects them for screen readers. The <code>onPress</code> on the <code>Label</code> is what makes the text toggle the switch, because React Native has no automatic <code>&lt;label for&gt;</code> behavior.</p>
<p>While you're here, open <code>components/ui/switch.tsx</code>. On the web, shadcn colors a switch with <code>data-[state=checked]:bg-primary</code>, which reads an attribute set in the DOM. React Native has no <code>data-*</code> attributes, so the component checks the prop in JavaScript:</p>
<pre><code class="language-tsx">props.checked ? 'bg-primary' : 'bg-input dark:bg-input/80',
</code></pre>
<p>The result is the same. Keep this in mind if you copy a <code>data-[state=...]</code> selector from a web example and it has no effect.</p>
<h3 id="heading-keyboard-props-for-the-name-field">Keyboard Props for the Name Field</h3>
<p><code>Input</code> is a <code>TextInput</code> with your border and radius applied. You should set these four props on every text input:</p>
<ul>
<li><code>autoCapitalize="words"</code> capitalizes each word, which suits a name.</li>
<li><code>autoComplete="name"</code> lets the operating system offer to fill in the name.</li>
<li><code>returnKeyType="done"</code> changes the return key label to "Done".</li>
<li><code>keyboardType="number-pad"</code> shows a numeric keyboard when you need digits.</li>
</ul>
<p>Together with <code>automaticallyAdjustKeyboardInsets</code> on the ScrollView from Step 5, this keeps the field visible while the keyboard is open. If you need more control, <code>react-native-keyboard-controller</code> is already a dependency of the template, and it provides <code>KeyboardAwareScrollView</code> and <code>KeyboardProvider</code>.</p>
<p>When you open the dropdown, it should appear right under the trigger at the same width, with a check mark next to the current value:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/d5234c02-19f7-4938-b889-24be5f13c175.png" alt="The open pickup time dropdown" style="display: block;" width="414" height="896" loading="lazy">

<p>Try picking a time and check that the trigger updates. Tap the words "Bringing my own cup" and confirm the switch flips. Type in the name field and confirm the keyboard doesn't cover it. If the dropdown opens and shows nothing, check your <code>PortalHost</code>.</p>
<h2 id="heading-step-8-build-the-bill-component">Step 8: Build the Bill Component</h2>
<p>The bill component is pretty small, but there are two details you should pay particular attention to here, especially when the values change while someone is editing their order.</p>
<p>Create <code>components/cart/bill.tsx</code>:</p>
<pre><code class="language-tsx">import { Separator } from '@/components/ui/separator';
import { Text } from '@/components/ui/text';
import { cn } from '@/lib/utils';
import { money } from '@/lib/menu';
import { View } from 'react-native';

type BillProps = {
  subtotal: number;
  discount: number;
  tax: number;
  total: number;
};

function Line({ label, value, tone }: { label: string; value: number; tone?: 'muted' | 'credit' }) {
  return (
    &lt;View className="flex-row items-center justify-between"&gt;
      &lt;Text className={cn('text-sm', tone === 'muted' &amp;&amp; 'text-muted-foreground')}&gt;{label}&lt;/Text&gt;
      &lt;Text
        className={cn(
          'text-sm tabular-nums',
          tone === 'muted' &amp;&amp; 'text-muted-foreground',
          tone === 'credit' &amp;&amp; 'text-foreground'
        )}&gt;
        {money(value)}
      &lt;/Text&gt;
    &lt;/View&gt;
  );
}

export function Bill({ subtotal, discount, tax, total }: BillProps) {
  return (
    &lt;View className="gap-2"&gt;
      &lt;Line label="Subtotal" value={subtotal} tone="muted" /&gt;
      {discount &gt; 0 ? &lt;Line label="Own cup" value={-discount} tone="credit" /&gt; : null}
      &lt;Line label="Tax" value={tax} tone="muted" /&gt;
      &lt;Separator className="my-1" /&gt;
      &lt;View className="flex-row items-center justify-between"&gt;
        &lt;Text className="font-medium"&gt;Total&lt;/Text&gt;
        &lt;Text className="text-lg font-semibold tabular-nums"&gt;{money(total)}&lt;/Text&gt;
      &lt;/View&gt;
    &lt;/View&gt;
  );
}
</code></pre>
<p>First, use <code>tabular-nums</code> on every number. Right-aligned prices in a proportional font don't line up at the decimal point, and using <code>tabular-nums</code> fixes that, as in the order rows.</p>
<p>Second, only show the discount row when it applies. The code uses <code>{discount &gt; 0 ? &lt;Line /&gt; : null}</code> instead of <code>{discount &amp;&amp; &lt;Line /&gt;}</code>. In JSX, if the left side of <code>&amp;&amp;</code> is the number <code>0</code>, React renders the <code>0</code>. In React Native, a bare number outside a <code>Text</code> component throws the error <code>Text strings must be rendered within a &lt;Text&gt; component</code>. Using a boolean check and returning <code>null</code> avoids this whole category of bugs.</p>
<p>To test it, turn on the own cup switch and scroll down. An <strong>Own cup</strong> line should appear with <code>-$0.25</code>, and the tax should change from <code>$1.54</code> to <code>$1.52</code>, because tax is calculated on the discounted subtotal:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/5fd0c79e-fcf4-4d7e-9129-bfb1e4d120d5.png" alt="The bill with the own cup discount applied" style="display: block;" width="414" height="896" loading="lazy">

<p>The total changes from <code>$20.19</code> to <code>$19.92</code>, which is 27 cents lower instead of 25. The extra two cents come from the lower tax.</p>
<h2 id="heading-step-9-build-the-fixed-checkout-bar">Step 9: Build the Fixed Checkout Bar</h2>
<p>I want the total and checkout button to remain visible while the user scrolls through the cart. On the web, you might reach for <code>position: sticky</code> and <code>bottom: 0</code>. React Native doesn't work that way, but we can get the same result with a simple flex layout.</p>
<p>You can get the same result with Flexbox. This is the layout from Step 5 again:</p>
<pre><code class="language-tsx">&lt;View className="bg-background flex-1"&gt;
  &lt;ScrollView className="flex-1" ...&gt;{/* content */}&lt;/ScrollView&gt;
  &lt;CheckoutBar ... /&gt;
&lt;/View&gt;
</code></pre>
<p>The outer <code>View</code> is a column. The <code>ScrollView</code> has <code>flex-1</code>, so it takes all the leftover height. The checkout bar is a sibling placed after it, so it sits at the bottom and doesn't scroll. You don't need any positioning or z-index.</p>
<h3 id="heading-handling-the-home-indicator">Handling the Home Indicator</h3>
<p>On phones without a home button, the bottom 34 points or so belong to the system. A button drawn there is hard or impossible to press. To avoid this, add the bottom safe area inset as padding.</p>
<pre><code class="language-tsx">const insets = useSafeAreaInsets();

&lt;View
  className="border-border bg-background flex-row items-center gap-4 border-t px-4 pt-3"
  style={{ paddingBottom: insets.bottom + 12 }}&gt;
</code></pre>
<p>The bottom padding is an inline <code>style</code> instead of a class because its value depends on the device and is only known when the app runs. Using <code>className</code> and <code>style</code> on the same element is fine, and this is the case it's meant for.</p>
<p>On devices with no gesture bar, and in a browser tab, <code>insets.bottom</code> is 0, so the extra <code>12</code> keeps the bar from looking cramped.</p>
<p>Create the full component in <code>components/cart/checkout-bar.tsx</code>. It includes the confirmation dialog, which Step 10 explains.</p>
<pre><code class="language-tsx">import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
import { Text } from '@/components/ui/text';
import { money } from '@/lib/menu';
import * as Haptics from 'expo-haptics';
import { ArrowRightIcon } from 'lucide-react-native';
import { View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

type CheckoutBarProps = {
  total: number;
  itemCount: number;
  pickupLabel: string;
  name: string;
  onConfirm: () =&gt; void;
};

export function CheckoutBar({ total, itemCount, pickupLabel, name, onConfirm }: CheckoutBarProps) {
  const insets = useSafeAreaInsets();
  const empty = itemCount === 0;

  function confirm() {
    // expo-haptics ships a web implementation that falls back to navigator.vibrate,
    // so this needs no platform guard.
    Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
    onConfirm();
  }

  return (
    &lt;View
      className="border-border bg-background flex-row items-center gap-4 border-t px-4 pt-3"
      style={{ paddingBottom: insets.bottom + 12 }}&gt;
      &lt;View className="flex-1"&gt;
        &lt;Text variant="muted" className="text-xs"&gt;
          {empty ? 'Nothing in the cart' : `${itemCount} ${itemCount === 1 ? 'item' : 'items'}`}
        &lt;/Text&gt;
        &lt;Text className="text-xl font-semibold tabular-nums"&gt;{money(total)}&lt;/Text&gt;
      &lt;/View&gt;

      &lt;AlertDialog&gt;
        &lt;AlertDialogTrigger asChild&gt;
          &lt;Button size="lg" disabled={empty}&gt;
            &lt;Text&gt;Place order&lt;/Text&gt;
            &lt;Icon as={ArrowRightIcon} /&gt;
          &lt;/Button&gt;
        &lt;/AlertDialogTrigger&gt;
        &lt;AlertDialogContent&gt;
          &lt;AlertDialogHeader&gt;
            &lt;AlertDialogTitle&gt;Send this to the counter?&lt;/AlertDialogTitle&gt;
            &lt;AlertDialogDescription&gt;
              {`${money(total)} for ${name.trim() || 'pickup'}, ${pickupLabel.toLowerCase()}. We start making it right away, so it cannot be cancelled after this.`}
            &lt;/AlertDialogDescription&gt;
          &lt;/AlertDialogHeader&gt;
          &lt;AlertDialogFooter&gt;
            &lt;AlertDialogCancel&gt;
              &lt;Text&gt;Not yet&lt;/Text&gt;
            &lt;/AlertDialogCancel&gt;
            &lt;AlertDialogAction onPress={confirm}&gt;
              &lt;Text&gt;Send it&lt;/Text&gt;
            &lt;/AlertDialogAction&gt;
          &lt;/AlertDialogFooter&gt;
        &lt;/AlertDialogContent&gt;
      &lt;/AlertDialog&gt;
    &lt;/View&gt;
  );
}
</code></pre>
<h3 id="heading-a-note-on-thin-borders">A Note on Thin Borders</h3>
<p><code>border-t</code> draws a line that's one logical point thick, which is two or three physical pixels on most modern screens. Next to a true one-pixel line, it looks heavy. React Native's <code>StyleSheet.hairlineWidth</code> gives you the thinnest line the screen can draw, and the template connects it to Tailwind with this line in <code>global.css</code>:</p>
<pre><code class="language-css">--spacing-hairline: hairlineWidth();
</code></pre>
<p>This adds <code>hairline</code> to Tailwind's spacing scale, so <code>h-hairline</code> gives you a divider that's one physical pixel tall. The Common Mistakes section later explains one catch when you try to use it as an override.</p>
<p>That's the checkout bar in place. Scroll to the bottom of the screen and check that it stays below the bill:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/a0c4a55c-a723-4a00-b6ff-c46e75c27b30.png" alt="The checkout bar at the bottom after scrolling down" style="display: block;" width="414" height="896" loading="lazy">

<p>Scroll back to the top and the bar stays in the same place:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/5af1750b-9b8c-422d-9273-6b2321096e73.png" alt="The checkout bar at the bottom after scrolling up" style="display: block;" width="414" height="896" loading="lazy">

<p>On a phone with a notch, the button should be above the gesture bar. If you remove all items with the trash buttons, the button should be disabled and the label should say "Nothing in the cart".</p>
<h2 id="heading-step-10-add-the-confirmation-and-put-the-screen-together">Step 10: Add the Confirmation and Put the Screen Together</h2>
<p>The checkout bar already contains the confirmation dialog. Before putting the full screen together, there are two differences between the React Native implementation and the web version that are worth looking at.</p>
<h3 id="heading-1-it-also-needs-the-portalhost">1. It Also Needs the <code>PortalHost</code></h3>
<p>On iOS, it also wraps itself in <code>FullWindowOverlay</code> from <code>react-native-screens</code>, so it draws above the native navigation header instead of under it. This is handled inside <code>alert-dialog.tsx</code>, which is why that file imports something that looks unrelated.</p>
<h3 id="heading-2-the-footer-reverses-its-order-on-phones">2. The Footer Reverses its Order on Phones</h3>
<p><code>AlertDialogFooter</code> uses <code>flex-col-reverse</code> and only becomes a row at the <code>sm:</code> breakpoint. On a phone, the button you write last is shown on top. Writing Cancel first and Action second puts the confirm button where the thumb is and the cancel button below it.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/0187ff24-1e34-414c-8189-e6f816f64d48.png" alt="The confirmation dialog" style="display: block;" width="414" height="896" loading="lazy">

<h3 id="heading-haptics">Haptics</h3>
<p>When the customer confirms the order, the <code>confirm</code> function calls <code>Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success)</code>. This gives a short success vibration on supported devices.</p>
<p>You might expect to wrap this call in a platform check because browsers don't have the same haptics support as native apps. In this case, <code>expo-haptics</code> already includes a web implementation that uses <code>navigator.vibrate</code>, with a fallback for iOS Safari. If the browser can't provide haptics, the call simply does nothing, so we don't need an extra platform check.</p>
<p><code>notificationAsync</code> is meant for outcomes such as success or failure. <code>impactAsync</code> is for physical collisions, and <code>selectionAsync</code> is for moving through a list of options. Using the wrong one won't cause an error, but it feels slightly off.</p>
<h3 id="heading-the-full-screen">The Full Screen</h3>
<p>Now we can bring everything together in the main screen. This is where we'll keep the state, calculate the bill using <code>billFor</code>, and pass the required values and callbacks to each component.</p>
<p>When an order is placed, it sets <code>orderNumber</code>, and the screen shows a confirmation instead. Inside that confirmation, <code>&lt;Stack.Screen options&gt;</code> changes the header title to "Order sent" without navigating anywhere, so the whole flow stays in one file and one route.</p>
<p>Replace <code>app/index.tsx</code> with:</p>
<pre><code class="language-tsx">import { Bill } from '@/components/cart/bill';
import { CheckoutBar } from '@/components/cart/checkout-bar';
import { OrderRow } from '@/components/cart/order-row';
import { PickupCard } from '@/components/cart/pickup-card';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Icon } from '@/components/ui/icon';
import { Separator } from '@/components/ui/separator';
import { Text } from '@/components/ui/text';
import { billFor, INITIAL_CART, PICKUP_TIMES, type CartItem } from '@/lib/menu';
import { Stack } from 'expo-router';
import { CircleCheckIcon, MoonStarIcon, SunIcon } from 'lucide-react-native';
import * as React from 'react';
import { ScrollView, View } from 'react-native';
import { Uniwind, useUniwind } from 'uniwind';

const SCREEN_OPTIONS = {
  title: 'Your order',
  headerRight: () =&gt; &lt;ThemeToggle /&gt;,
};

export default function CartScreen() {
  const [items, setItems] = React.useState&lt;CartItem[]&gt;(INITIAL_CART);
  const [pickupValue, setPickupValue] = React.useState(PICKUP_TIMES[0].value);
  const [name, setName] = React.useState('');
  const [ownCup, setOwnCup] = React.useState(false);
  const [orderNumber, setOrderNumber] = React.useState&lt;string | null&gt;(null);

  const bill = billFor(items, ownCup);
  const itemCount = items.reduce((count, item) =&gt; count + item.qty, 0);
  const pickupLabel =
    PICKUP_TIMES.find((time) =&gt; time.value === pickupValue)?.label ?? PICKUP_TIMES[0].label;

  function changeQty(id: string, qty: number) {
    setItems((current) =&gt;
      qty &lt;= 0
        ? current.filter((item) =&gt; item.id !== id)
        : current.map((item) =&gt; (item.id === id ? { ...item, qty } : item))
    );
  }

  function placeOrder() {
    setOrderNumber(`A-${Math.floor(Math.random() * 90 + 10)}`);
  }

  function startOver() {
    setItems(INITIAL_CART);
    setOwnCup(false);
    setName('');
    setPickupValue(PICKUP_TIMES[0].value);
    setOrderNumber(null);
  }

  if (orderNumber) {
    return (
      &lt;&gt;
        &lt;Stack.Screen options={{ ...SCREEN_OPTIONS, title: 'Order sent' }} /&gt;
        &lt;View className="bg-background flex-1 items-center justify-center gap-6 p-8"&gt;
          &lt;Icon as={CircleCheckIcon} className="text-primary size-16" /&gt;
          &lt;View className="gap-2"&gt;
            &lt;Text variant="h3" className="text-center"&gt;
              We are on it
            &lt;/Text&gt;
            &lt;Text variant="muted" className="text-center"&gt;
              {`Order ${orderNumber} for ${name.trim() || 'pickup'}. Come to the far end of the counter and look for your name on the cup.`}
            &lt;/Text&gt;
          &lt;/View&gt;
          &lt;Button variant="outline" onPress={startOver}&gt;
            &lt;Text&gt;Start another order&lt;/Text&gt;
          &lt;/Button&gt;
        &lt;/View&gt;
      &lt;/&gt;
    );
  }

  return (
    &lt;&gt;
      &lt;Stack.Screen options={SCREEN_OPTIONS} /&gt;
      &lt;View className="bg-background flex-1"&gt;
        &lt;ScrollView
          className="flex-1"
          contentContainerClassName="gap-4 p-4 pb-8"
          keyboardShouldPersistTaps="handled"
          automaticallyAdjustKeyboardInsets&gt;
          &lt;Card className="gap-3 py-4"&gt;
            &lt;CardHeader className="px-4"&gt;
              &lt;CardTitle&gt;Fernwood Coffee&lt;/CardTitle&gt;
              &lt;CardDescription&gt;112 Marine Drive, counter pickup&lt;/CardDescription&gt;
            &lt;/CardHeader&gt;
            &lt;CardContent className="gap-4 px-4"&gt;
              {items.length === 0 ? (
                &lt;Text variant="muted"&gt;Your cart is empty. Add something warm.&lt;/Text&gt;
              ) : null}
              {items.map((item, index) =&gt; (
                &lt;React.Fragment key={item.id}&gt;
                  {index &gt; 0 ? &lt;Separator /&gt; : null}
                  &lt;OrderRow item={item} onChangeQty={changeQty} /&gt;
                &lt;/React.Fragment&gt;
              ))}
            &lt;/CardContent&gt;
          &lt;/Card&gt;

          &lt;Card className="gap-3 py-4"&gt;
            &lt;CardHeader className="px-4"&gt;
              &lt;CardTitle&gt;Pickup&lt;/CardTitle&gt;
            &lt;/CardHeader&gt;
            &lt;CardContent className="px-4"&gt;
              &lt;PickupCard
                pickupValue={pickupValue}
                onPickupValueChange={setPickupValue}
                name={name}
                onNameChange={setName}
                ownCup={ownCup}
                onOwnCupChange={setOwnCup}
              /&gt;
            &lt;/CardContent&gt;
          &lt;/Card&gt;

          &lt;Card className="gap-3 py-4"&gt;
            &lt;CardHeader className="px-4"&gt;
              &lt;CardTitle&gt;Bill&lt;/CardTitle&gt;
            &lt;/CardHeader&gt;
            &lt;CardContent className="px-4"&gt;
              &lt;Bill {...bill} /&gt;
            &lt;/CardContent&gt;
          &lt;/Card&gt;
        &lt;/ScrollView&gt;

        &lt;CheckoutBar
          total={bill.total}
          itemCount={itemCount}
          pickupLabel={pickupLabel}
          name={name}
          onConfirm={placeOrder}
        /&gt;
      &lt;/View&gt;
    &lt;/&gt;
  );
}

const THEME_ICONS = {
  light: SunIcon,
  dark: MoonStarIcon,
};

function ThemeToggle() {
  const { theme } = useUniwind();

  return (
    &lt;Button
      onPressIn={() =&gt; Uniwind.setTheme(theme === 'dark' ? 'light' : 'dark')}
      size="icon"
      variant="ghost"
      className="ios:size-9 web:mx-4 rounded-full"
      accessibilityLabel="Switch theme"&gt;
      &lt;Icon as={THEME_ICONS[theme ?? 'light']} className="size-5" /&gt;
    &lt;/Button&gt;
  );
}
</code></pre>
<p>Notice that <code>pickupLabel</code> is the fix from Step 7 in use. The screen looks up the label from <code>PICKUP_TIMES</code> and passes a plain string to <code>CheckoutBar</code>, so <code>CheckoutBar</code> never touches an <code>Option</code> object or the incorrect web label.</p>
<p>To test it, place an order. The dialog should show your name and the pickup time you chose (such as "in 30 minutes"), not the raw value <code>30</code>. Confirm the order, and you should see the confirmation screen:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/36e526dd-72aa-4ed6-84f0-ae16abf720a2.png" alt="The order sent screen" style="display: block;" width="414" height="896" loading="lazy">

<p>Tap "Start another order" and the cart returns to its original state.</p>
<p>The checkout screen is now working, and each part is kept in its own component. You can use the same approach when you build other screens: keep the component focused, pass the data it needs through props, and let the shared theme handle the styling.</p>
<h2 id="heading-step-11-add-dark-mode">Step 11: Add Dark Mode</h2>
<p>We already added the theme toggle in Step 10. Here's the component again so we can look at how it switches between light and dark mode:</p>
<pre><code class="language-tsx">import { Uniwind, useUniwind } from 'uniwind';

function ThemeToggle() {
  const { theme } = useUniwind();

  return (
    &lt;Button
      onPressIn={() =&gt; Uniwind.setTheme(theme === 'dark' ? 'light' : 'dark')}
      size="icon"
      variant="ghost"
      className="ios:size-9 web:mx-4 rounded-full"
      accessibilityLabel="Switch theme"&gt;
      &lt;Icon as={THEME_ICONS[theme ?? 'light']} className="size-5" /&gt;
    &lt;/Button&gt;
  );
}
</code></pre>
<p><code>Uniwind.setTheme</code> changes the values behind every token, so everything that uses <code>bg-card</code>, <code>text-muted-foreground</code>, and similar classes updates at once. <code>useUniwind</code> subscribes the component to the current theme, so the icon changes too.</p>
<p>This code also uses the <code>ios:</code> and <code>web:</code> prefixes. Uniwind supports platform variants, so <code>web:mx-4</code> only adds margin in the browser, and <code>ios:size-9</code> only applies on iOS. It's similar to <code>Platform.select</code>, but it stays inside the class string.</p>
<p>Three things aren't handled by <code>setTheme</code>, and if you forget them, you end up with a screen that's only partly dark. The template already sets up the first two.</p>
<h3 id="heading-1-the-navigation-header">1. The Navigation Header</h3>
<p>React Navigation takes its colors from a plain object, so the root layout needs to pass it the right one:</p>
<pre><code class="language-tsx">const { theme } = useUniwind();

&lt;ThemeProvider value={NAV_THEME[theme ?? 'light']}&gt;
</code></pre>
<h3 id="heading-2-the-status-bar">2. The Status Bar</h3>
<p>The clock and battery icons are drawn by the operating system, so you need to tell it which style to use. Without this, you can get dark text on a dark bar.</p>
<pre><code class="language-tsx">&lt;StatusBar style={theme === 'dark' ? 'light' : 'dark'} /&gt;
</code></pre>
<h3 id="heading-3-saving-the-choice">3. Saving the Choice</h3>
<p><code>Uniwind.setTheme</code> only applies to the current session. The next time the app starts, it follows the system setting again. To keep the user's choice, save it with <code>expo-secure-store</code> or <code>AsyncStorage</code> and call <code>setTheme</code> when the app starts. You can call <code>setTheme('system')</code> to go back to following the operating system.</p>
<p>When you tap the header icon, the cards, borders, inputs, switch, header, and status bar should all change together. You can explore more ready-made <a href="https://shadcnstudio.com/blocks">shadcn blocks</a> if you want examples of how these components are used in larger interfaces:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/4e54a370-5335-42fe-95df-8eee7b033e78.png" alt="The screen in dark mode" style="display: block;" width="414" height="896" loading="lazy">

<p>Look for anything that stays light while the rest goes dark. A light header usually means the <code>ThemeProvider</code> is not receiving the new <code>NAV_THEME</code>.</p>
<h2 id="heading-step-12-create-your-own-theme">Step 12: Create Your Own Theme</h2>
<p>The screen is currently using the default gray theme. Let's change it to a coffee-inspired palette with warm cream backgrounds and brown accents. This will also help us see why the palette needs to be updated in both <code>global.css</code> and <code>lib/theme.ts</code>.</p>
<h3 id="heading-update-the-tokens">Update the Tokens</h3>
<p>Replace the <code>@layer theme</code> block in <code>global.css</code> with this coffee palette:</p>
<pre><code class="language-css">@layer theme {
  :root {
    @variant light {
      --color-background: oklch(0.98 0.008 75);
      --color-foreground: oklch(0.24 0.02 60);
      --color-card: oklch(1 0.003 90);
      --color-card-foreground: oklch(0.24 0.02 60);
      --color-popover: oklch(1 0.003 90);
      --color-popover-foreground: oklch(0.24 0.02 60);
      --color-primary: oklch(0.44 0.06 45);
      --color-primary-foreground: oklch(0.99 0.01 85);
      --color-secondary: oklch(0.93 0.03 80);
      --color-secondary-foreground: oklch(0.35 0.05 45);
      --color-muted: oklch(0.95 0.012 80);
      --color-muted-foreground: oklch(0.52 0.02 60);
      --color-accent: oklch(0.92 0.04 78);
      --color-accent-foreground: oklch(0.32 0.05 45);
      --color-destructive: oklch(0.577 0.245 27.325);
      --color-border: oklch(0.89 0.02 75);
      --color-input: oklch(0.89 0.02 75);
      --color-ring: oklch(0.44 0.06 45);
    }

    @variant dark {
      --color-background: oklch(0.17 0.012 60);
      --color-foreground: oklch(0.96 0.008 85);
      --color-card: oklch(0.22 0.016 62);
      --color-card-foreground: oklch(0.96 0.008 85);
      --color-popover: oklch(0.22 0.016 62);
      --color-popover-foreground: oklch(0.96 0.008 85);
      --color-primary: oklch(0.85 0.09 75);
      --color-primary-foreground: oklch(0.22 0.03 55);
      --color-secondary: oklch(0.29 0.022 62);
      --color-secondary-foreground: oklch(0.94 0.01 85);
      --color-muted: oklch(0.27 0.018 62);
      --color-muted-foreground: oklch(0.72 0.015 75);
      --color-accent: oklch(0.31 0.03 65);
      --color-accent-foreground: oklch(0.95 0.01 85);
      --color-destructive: oklch(0.704 0.191 22.216);
      --color-border: oklch(1 0 0 / 12%);
      --color-input: oklch(1 0 0 / 15%);
      --color-ring: oklch(0.85 0.09 75);
    }
  }
}
</code></pre>
<p>If you don't want to choose thirty colors by hand, you can generate a theme with the <a href="https://shadcnstudio.com/theme-generator">shadcn theme generator</a> or <a href="https://tweakcn.com/">tweakcn</a>. Both export CSS variables, but you need to make two changes before the output works in this project:</p>
<ol>
<li>Rename each variable to include the <code>--color-</code> prefix. For example, <code>--primary</code> becomes <code>--color-primary</code>.</li>
<li>Move the <code>:root</code> block inside <code>@variant light</code>, and the <code>.dark</code> block inside <code>@variant dark</code>.</li>
</ol>
<p>Also remove <code>--radius</code> from what you paste, because the template already defines it along with the derived sizes. Remove any <code>--shadow-*</code> variables too, since nothing in the registry reads them.</p>
<h3 id="heading-update-libthemets">Update lib/theme.ts</h3>
<p>After you save and reload, the result looks like this:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/eb94958b-f7d3-4d64-9703-2b9153e4ea6f.png" alt="The new theme with a white header" style="display: block;" width="414" height="896" loading="lazy">

<p>The page is cream, the button is brown, and the badges have the right color, but the header is still white with a visible line under it. The reason is that React Navigation draws the header using <code>lib/theme.ts</code>, and that file still has the old palette. Nothing is broken and nothing warns you, so this mistake is easy to miss. If you're designing the same interface in Figma, the <a href="https://shadcnstudio.com/figma">shadcn Figma resources</a> can also help you keep the design and implementation aligned.</p>
<p>Update <code>lib/theme.ts</code> to match:</p>
<pre><code class="language-tsx">import { DarkTheme, DefaultTheme, type Theme } from 'expo-router/react-navigation';

export const THEME = {
  light: {
    background: '#fcf8f3',
    foreground: '#261d16',
    card: '#fffffd',
    primary: '#6e4836',
    border: '#e3d9cd',
    destructive: '#e7000b',
    /* the rest of the list */
  },
  dark: {
    background: '#130e0a',
    foreground: '#f4f1ec',
    card: '#201913',
    primary: '#f1c68b',
    border: '#3a3129',
    destructive: '#ff6467',
    /* the rest of the list */
  },
};

export const NAV_THEME: Record&lt;'light' | 'dark', Theme&gt; = {
  light: {
    ...DefaultTheme,
    colors: {
      background: THEME.light.background,
      border: THEME.light.border,
      card: THEME.light.background,
      notification: THEME.light.destructive,
      primary: THEME.light.primary,
      text: THEME.light.foreground,
    },
  },
  dark: {
    ...DarkTheme,
    colors: {
      background: THEME.dark.background,
      border: THEME.dark.border,
      card: THEME.dark.background,
      notification: THEME.dark.destructive,
      primary: THEME.dark.primary,
      text: THEME.dark.foreground,
    },
  },
};
</code></pre>
<p>This isn't a direct copy of <code>global.css</code>, so three points need explanation:</p>
<ul>
<li><strong>Use hex colors instead of</strong> <code>oklch()</code><strong>:</strong> Uniwind converts <code>oklch()</code> for your classes, but React Navigation does not, so give it a format that React Native can read directly. You can convert a color with any online converter, or paste the <code>oklch()</code> value into your browser's developer tools color picker and read the hex value.</li>
<li><strong>Map React Navigation's</strong> <code>card</code> <strong>to your</strong> <code>background</code><strong>, not your</strong> <code>card</code><strong>.</strong> The two names look the same but mean different things. In shadcn, <code>card</code> is a raised surface on top of the page. In React Navigation, <code>card</code> is the background of the screen and header. If you map them by name, the header ends up a shade lighter than the page. You won't notice this with the stock template because it uses the same value for <code>card</code> and <code>background</code>. It only shows up once you create a theme where cards stand out from the page, like this one.</li>
<li><strong>Use a solid color in place of a transparent border.</strong> In dark mode, <code>--color-border</code> is <code>oklch(1 0 0 / 12%)</code>, which is white at 12% opacity. A navigation theme needs a solid color, so work out what that border looks like on your background and use that value.</li>
</ul>
<p>After this change, the header and page match in both light and dark mode, and you didn't edit any component files:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/f24b38ac-9742-44d3-92d6-2061477bc314.png" alt="The final theme with a matching header" style="display: block;" width="414" height="896" loading="lazy">

<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/8627fc51-5083-4f8f-bae4-370f860b389e.png" alt="The final theme in the other mode" style="display: block;" width="414" height="896" loading="lazy">

<p>Switch between light and dark a few times and watch the header. If it's a shade lighter or darker than the page, one of the values in <code>lib/theme.ts</code> is still from the old palette.</p>
<h2 id="heading-common-mistakes-and-how-to-fix-them">Common Mistakes and How to Fix Them</h2>
<p>If you're coming from web development, some of these differences may catch you off guard. I've collected the issues covered in the tutorial in the table below, along with the fix for each one. You can refer back to it when something doesn't behave as expected.</p>
<table>
<thead>
<tr>
<th>What you do</th>
<th>What happens</th>
<th>The fix</th>
</tr>
</thead>
<tbody><tr>
<td><code>&lt;Badge&gt;Medium&lt;/Badge&gt;</code></td>
<td>Red screen: "Text strings must be rendered within a <code>&lt;Text&gt;</code>."</td>
<td>Wrap the text: <code>&lt;Badge&gt;&lt;Text&gt;Medium&lt;/Text&gt;&lt;/Badge&gt;</code>. The same applies to <code>Button</code>.</td>
</tr>
<tr>
<td><code>{count &amp;&amp; &lt;Line/&gt;}</code> when <code>count</code> is <code>0</code></td>
<td>The same error, caused by a stray <code>0</code></td>
<td><code>{count &gt; 0 ? &lt;Line/&gt; : null}</code></td>
</tr>
<tr>
<td><code>space-y-3</code> on a column</td>
<td>Nothing happens and there is no warning</td>
<td>Use <code>gap-3</code> on the parent</td>
</tr>
<tr>
<td><code>className="p-4"</code> on a <code>ScrollView</code></td>
<td>Padding is clipped and gaps are ignored</td>
<td>Use <code>contentContainerClassName</code></td>
</tr>
<tr>
<td><code>truncate</code> on a long name</td>
<td>The text isn't truncated and the price is pushed off screen</td>
<td>Use <code>numberOfLines={1}</code></td>
</tr>
<tr>
<td>Using <code>flex</code> and expecting a row</td>
<td>Items stack vertically</td>
<td>React Native defaults to a column, so add <code>flex-row</code></td>
</tr>
<tr>
<td><code>hover:bg-accent</code></td>
<td>Nothing happens on a device</td>
<td>Use <code>active:</code> for the pressed state</td>
</tr>
<tr>
<td>Deleting <code>PortalHost</code> from the layout</td>
<td>Dropdowns open into nothing, with no error</td>
<td>Put it back</td>
</tr>
<tr>
<td>A Select near the bottom of the screen</td>
<td>The last option is under the home indicator</td>
<td>Pass <code>insets</code> to <code>SelectContent</code></td>
</tr>
<tr>
<td>Showing <code>option.label</code> from <code>onValueChange</code></td>
<td>Correct on native, but the raw value on the web</td>
<td>Look up the label from your own data</td>
</tr>
<tr>
<td>A bottom bar with only <code>p-4</code></td>
<td>The button is under the gesture bar</td>
<td>Use <code>paddingBottom: insets.bottom + 12</code> in <code>style</code></td>
</tr>
<tr>
<td>28-point stepper buttons</td>
<td>Hard to tap with a thumb</td>
<td>Add <code>hitSlop={8}</code></td>
</tr>
<tr>
<td>Changing only <code>global.css</code> for a new theme</td>
<td>The header keeps the old colors</td>
<td>Update <code>lib/theme.ts</code> too</td>
</tr>
<tr>
<td><code>&lt;Avatar&gt;</code> without <code>alt</code></td>
<td>TypeScript won't compile</td>
<td><code>alt</code> is required, and it becomes the accessibility label</td>
</tr>
<tr>
<td><code>rounded-2xl</code> on <code>Avatar</code> only</td>
<td>A circular fallback inside rounded corners</td>
<td>Repeat it on <code>AvatarFallback</code></td>
</tr>
<tr>
<td>Guarding haptics with <code>Platform.OS !== 'web'</code></td>
<td>A working web fallback is removed</td>
<td><code>expo-haptics</code> already handles the web</td>
</tr>
<tr>
<td>Right-aligned prices in a normal font</td>
<td>Digits shift whenever the number changes</td>
<td>Use <code>tabular-nums</code>, which also works on native</td>
</tr>
<tr>
<td><code>&lt;Separator className="h-hairline" /&gt;</code></td>
<td>Both height classes are kept</td>
<td>See below</td>
</tr>
</tbody></table>
<p>The last row needs more explanation, because it looks like a bug in <code>cn()</code>, but it's not.</p>
<p><code>cn()</code> uses <code>tailwind-merge</code>, which resolves conflicts between classes. It knows the default Tailwind scale, but it doesn't know about custom values you declare in <code>global.css</code>. The value <code>hairline</code> comes from <code>--spacing-hairline: hairlineWidth()</code>, so <code>tailwind-merge</code> can't tell that <code>h-hairline</code> and <code>h-[1px]</code> set the same property, and it keeps both:</p>
<pre><code class="language-jsx">cn('h-[1px] w-full', 'h-hairline my-1')  // 'h-[1px] w-full h-hairline my-1'
cn('h-[1px] w-full', 'h-2 my-1')         // 'w-full h-2 my-1'
</code></pre>
<p>The second result is correct. In the first, which height wins depends on the order of the CSS. The other overrides in this tutorial, such as <code>size-14</code> over <code>size-8</code>, work correctly because those are names <code>tailwind-merge</code> recognizes. If you want it to understand your custom scale, you can teach it with <code>extendTailwindMerge</code> in <code>lib/utils.ts</code>. Otherwise, use an arbitrary value, or edit the component file directly, since you own it.</p>
<p>There's a related case in the stepper buttons. They pass <code>size-7</code> to a <code>Button</code> whose icon size is <code>h-10 w-10 sm:h-9 sm:w-9</code>:</p>
<pre><code class="language-jsx">cn('h-10 w-10 sm:h-9 sm:w-9', 'size-7 rounded-full')
// 'sm:h-9 sm:w-9 size-7 rounded-full'
</code></pre>
<p><code>size-7</code> replaces the base <code>h-10 w-10</code>, but the two <code>sm:</code> classes stay, because <code>tailwind-merge</code> treats a responsive variant as a different class. On a phone this makes no difference, since <code>sm:</code> starts at 640px and phones are narrower than that. In a desktop browser, though, those buttons grow to 36 points.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we built a coffee shop cart and checkout screen with React Native Reusables, Expo, and Uniwind. We added the order rows, pickup options, bill summary, fixed checkout bar, and confirmation dialog. We also looked at how the registry and CLI add component source code to the project and how the theme tokens control the app's colors.</p>
<p>One thing worth getting into the habit of is checking the component source when something doesn't behave the way you expect. Since the components live in your project, you can open them and see how they work. That's how we understood the difference in the Select label between web and native. It also makes customization easier because you can see which part of the component needs to change instead of adding more workarounds around it.</p>
<p>You can find the complete project in the <a href="https://github.com/shadcnstudio/shadcn-react-native-app">GitHub repository</a>. If you run into an issue or want to compare your code with the finished screen, clone the repository and check the implementation. If you're looking for more complete starting points for your next project, take a look at <a href="https://shadcnstudio.com/templates">shadcn templates</a>.</p>
<p>I captured the screenshots using the React Native Web build at a phone-sized viewport. The same project also runs on iOS and Android. I've called out the platform differences in the relevant sections, including the Select label and portal host in Step 7, safe area handling in Step 9, and haptics in Step 10.</p>
<h3 id="heading-resources">Resources</h3>
<p><strong>React Native Reusables</strong></p>
<ul>
<li><a href="https://reactnativereusables.com/">reactnativereusables.com</a>: documentation and the registry</li>
<li><a href="https://reactnativereusables.com/docs">Introduction</a>: the list of differences from web shadcn</li>
<li><a href="https://reactnativereusables.com/docs/cli">CLI reference</a>: the <code>init</code>, <code>add</code>, and <code>doctor</code> commands</li>
<li><a href="https://reactnativereusables.com/docs/create-your-own-registry">Create your own registry</a>: publish components your team can add with the CLI</li>
<li><a href="https://github.com/founded-labs/react-native-reusables">The repository</a>: MIT licensed</li>
<li>Any registry entry is a public URL: <code>reactnativereusables.com/r/uniwind/&lt;name&gt;.json</code> or <code>.../r/nativewind/&lt;name&gt;.json</code></li>
</ul>
<p><strong>Tools used</strong></p>
<ul>
<li><a href="https://rnprimitives.com/">RN Primitives</a></li>
<li><a href="https://docs.uniwind.dev/">Uniwind</a></li>
<li><a href="https://www.nativewind.dev/">Nativewind</a></li>
<li><a href="https://docs.expo.dev/router/introduction/">Expo Router</a></li>
<li><a href="https://ui.shadcn.com/">shadcn/ui</a> and the <a href="https://ui.shadcn.com/docs/registry">registry specification</a></li>
</ul>
<p><strong>APIs used</strong></p>
<ul>
<li><a href="https://github.com/appandflow/react-native-safe-area-context"><code>useSafeAreaInsets</code></a></li>
<li><a href="https://docs.expo.dev/versions/latest/sdk/haptics/"><code>expo-haptics</code></a></li>
<li><a href="https://reactnative.dev/docs/view#hitslop"><code>hitSlop</code></a></li>
<li><a href="https://reactnative.dev/docs/text#numberoflines"><code>numberOfLines</code></a></li>
<li><a href="https://github.com/dcastil/tailwind-merge"><code>tailwind-merge</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/color_value/oklch"><code>oklch()</code></a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What a CAPTCHA Farm Attack Actually Looks Like ]]>
                </title>
                <description>
                    <![CDATA[ CAPTCHAs are something most of us have come across while browsing the internet. Sometimes we're asked to identify traffic lights in pictures, solve a small puzzle, or simply tick a box to confirm we'r ]]>
                </description>
                <link>https://www.freecodecamp.org/news/captcha-farm-attack/</link>
                <guid isPermaLink="false">6aeba47df91e889efe09a17a</guid>
                
                    <category>
                        <![CDATA[ cybersecurity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ captcha ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ethical Hacking ]]>
                    </category>
                
                    <category>
                        <![CDATA[ internet security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ automation ]]>
                    </category>
                
                    <category>
                        <![CDATA[ online fraud ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reetain Raina ]]>
                </dc:creator>
                <pubDate>Wed, 04 Nov 2026 21:32:45 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/392975d9-8fb2-4311-bbd9-8ec42af322ef.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>CAPTCHAs are something most of us have come across while browsing the internet. Sometimes we're asked to identify traffic lights in pictures, solve a small puzzle, or simply tick a box to confirm we're human. Websites use these challenges to help distinguish real users from automated bots.</p>
<p>But there's an interesting problem with this approach. What happens when a bot doesn't need to solve the CAPTCHA itself because a real person can solve it for them?</p>
<p>This is how CAPTCHA farms work. Attackers use services where real people solve CAPTCHA challenges on behalf of automated programs. The person completing the challenge is human, but the activity happening behind it may still be controlled by a bot. This makes it harder for websites to identify suspicious requests, even when their CAPTCHA system appears to be working correctly.</p>
<p>Here, we'll look at how CAPTCHA farm attacks work, why attackers use human solvers, and what makes these attacks difficult to detect. We'll also go through some of the security measures developers can use to identify suspicious activity and better protect their websites.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><a href="#heading-what-is-a-captcha-farm-attack">What Is a CAPTCHA Farm Attack?</a></li>
<li><a href="#heading-behind-the-scenes-the-four-part-infrastructure">Behind the Scenes: The Four-Part Infrastructure</a></li>
<li><a href="#heading-how-an-attack-unfolds-a-step-by-step-look">How an Attack Unfolds: A Step-by-Step Look</a></li>
<li><a href="#heading-why-attackers-rely-on-human-solvers">Why Attackers Rely on Human Solvers</a></li>
<li><a href="#heading-what-captcha-farms-target">What CAPTCHA Farms Target</a></li>
<li><a href="#heading-why-these-attacks-are-difficult-to-stop">Why These Attacks Are Difficult to Stop</a></li>
<li><a href="#heading-how-websites-can-defend-themselves">How Websites Can Defend Themselves</a><ul>
<li><a href="#heading-behavioral-telemetry-and-biometrics">Behavioral Telemetry and Biometrics</a></li>
<li><a href="#heading-network-and-device-fingerprinting">Network and Device Fingerprinting</a></li>
<li><a href="#heading-modern-rate-limiting-models">Modern Rate-Limiting Models</a></li>
<li><a href="#heading-post-authentication-anomaly-detection">Post-Authentication Anomaly Detection</a></li>
</ul>
</li>
<li><a href="#heading-security-beyond-the-checkbox">Security Beyond the Checkbox</a></li>
<li><a href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-is-a-captcha-farm-attack">What Is a CAPTCHA Farm Attack?</h2>
<p>To understand how these attacks work, it helps to distinguish between the two primary ways attackers deal with verification gates: machine-driven recognition and human-driven outsourcing.</p>
<p>In an automated CAPTCHA-solving attack, an attacker uses computer vision models, optical character recognition (OCR), or neural networks to parse the challenge image and guess the answer without human intervention.</p>
<p>This approach is fast and computationally cheap, but it frequently fails when security vendors update their visual distortions, introduce interactive logic puzzles, or assess human-like mouse kinematics.</p>
<p>A CAPTCHA farm attack takes the opposite route. Instead of attempting to outsmart the defensive algorithm with software, the attacker routes the challenge to a human solving service. These commercial operations maintain large networks of manual workers who solve puzzles continuously around the clock. By inserting a human into the loop, the attacker converts what should be a technical roadblock into an outsourced labor pipeline.</p>
<p>The attack doesn't break the cryptography or reverse-engineer the underlying challenge code. Instead, it relies on a CAPTCHA relay attack: software manages the speed and scale of the attack, while real human eyes provide the cognitive validation the website expects.</p>
<h2 id="heading-behind-the-scenes-the-four-part-infrastructure">Behind the Scenes: The Four-Part Infrastructure</h2>
<p>A functional CAPTCHA farm is neither an ad-hoc group of rogue hackers nor an obscure black-box script. It's a commercial, multi-tiered infrastructure built around standard web development protocols.</p>
<p>Four distinct components work together to make the relay happen in a matter of seconds.</p>
<p>First is the attacker’s automated script. This client bot typically runs headlessly via browser automation tools like Puppeteer, Playwright, or custom HTTP client libraries. The script navigates to a target platform, such as a user registration portal, and fills in usernames, passwords, and demographic fields at machine speed until it hits a defensive challenge.</p>
<p>Second is the CAPTCHA-solving platform's API. Commercial solver platforms act as brokers between abuse operators and manual laborers. When the attacker's script encounters a challenge, it intercepts the site's public key, the challenge URL, and the visual assets, packaging them into an HTTP POST request directed at the solving service’s application programming interface (API).</p>
<p>Third is the distributed human workforce. Workers access these services through dedicated web dashboards, mobile apps, or browser plug-ins. When the API receives a task from an attacker, it pushes the image directly onto a worker’s screen. The worker identifies the bicycles or fire hydrants, types the distorted characters, or drags the puzzle slider into place, earning a microscopic payout, often ranging from $0.50 to $2.00 per thousand puzzles solved.</p>
<p>Fourth is the payload delivery back to the target. Once the worker submits the correct solution, the broker API returns the generated verification token back to the attacker’s script. The script injects this validation token into the target website's hidden form field and fires the final submission request. To the receiving server, the request bears an authentic verification signature generated by a real human session.</p>
<h2 id="heading-how-an-attack-unfolds-a-step-by-step-look">How an Attack Unfolds: A Step-by-Step Look</h2>
<p>To see how these parts interact in practice, consider a credential-stuffing or mass-account registration campaign against an online service.</p>
<ol>
<li><strong>Initiation:</strong> The attacker's script dispatches an HTTP request to establish a session with the target registration page, populating the input fields with generated credentials.</li>
<li><strong>Challenge trigger:</strong> The target application evaluates the incoming request. Detecting an unfamiliar IP address or an incomplete browser fingerprint, it triggers a CAPTCHA modal, pausing the registration sequence until a valid solution token is supplied.</li>
<li><strong>Extraction and dispatch:</strong> The bot reads the page DOM, captures the puzzle iframe parameters, site key, and challenge payload, and forwards this data to the CAPTCHA farm API.</li>
<li><strong>Human execution:</strong> The farm's queuing system allocates the challenge to an active human worker. The worker completes the puzzle within an average response window of 10 to 25 seconds.</li>
<li><strong>Token retrieval:</strong> The worker’s response yields an official validation token from the CAPTCHA provider's origin server. The solving farm's API returns this signed string to the attacker’s script.</li>
<li><strong>Form finalization:</strong> The script injects the token into the page's response payload (such as g-recaptcha-response) and submits the form. The website’s backend queries the CAPTCHA provider's verification API, receives a confirmation that the challenge was successfully passed, and creates the account.</li>
</ol>
<p>The entire loop completes well before typical session timeouts kick in, leaving the target server with no obvious visual anomaly to flag.</p>
<h2 id="heading-why-attackers-rely-on-human-solvers">Why Attackers Rely on Human Solvers</h2>
<p>Building and maintaining custom neural networks to break modern visual challenges requires constant development effort. Defensive providers frequently alter noise patterns, camera angles, distortion algorithms and semantic puzzles specifically to break automated image classifiers.</p>
<p>Human solvers bypass this arms race entirely because the human visual cortex processes semantic context effortlessly. A person instantly understands what constitutes a "motorcycle," even if the image is cropped awkwardly, partially obscured by street foliage, or rendered under strange lighting.</p>
<p>This human adaptability is supported by extensive security research. In a foundational study, <a href="https://www.researchgate.net/publication/333536967_Towards_understanding_the_security_of_modern_image_captchas_and_underground_captcha-solving_services"><u>Towards Understanding the Security of Modern Image Captchas and Underground Captcha-Solving Services</u></a>, researchers analyzed the commercial ecosystem across 152 solving platforms. They found that human-solving services achieved near-flawless accuracy rates across complex, diverse image challenges where purely automated computer vision solvers repeatedly struggled or degraded over time.</p>
<p>Outsourcing the problem is also remarkably inexpensive. Because labor pools are drawn from regions with low living costs, attackers can bypass thousands of protective checkpoints for less than the price of a cup of coffee. The workflow is highly scalable: software handles millions of connections, while human labor is summoned on-demand only for the few seconds required to clear a barrier.</p>
<h2 id="heading-what-captcha-farms-target">What CAPTCHA Farms Target</h2>
<p>CAPTCHA farms rarely serve as self-contained attacks. Instead, they act as an operational enabler for wider abusive campaigns across the web.</p>
<p>First, they enable mass fake account creation. Malicious actors generate millions of disposable profiles on social media, dating networks, and developer platforms to distribute phishing links, spam search engines, or run coordinated disinformation campaigns.</p>
<p>They also facilitate credential stuffing. When attackers test databases of leaked usernames and passwords against banking or retail portals, defensive systems usually throw a CAPTCHA after a handful of failed attempts. Solver APIs allow the credential-testing bots to continue cycling through login credentials uninterrupted.</p>
<p>Inventory hoarding and scalping is another common use case. High-demand retail drops, concert tickets, and travel bookings are frequent targets. Security researchers tracking real-world bot traffic at <a href="https://datadome.co/threat-research/how-datadome-stopped-a-captcha-farm-behind-18-million-ticket-scalping-attempts/"><u>DataDome</u></a> documented an operation where an attacker combined bot automation with a CAPTCHA farm to orchestrate 18 million automated ticket-scalping attempts, successfully bypassing front-line interactive verification.</p>
<p>And they enable data scraping at scale. Web crawlers harvesting competitive pricing, directory databases, or intellectual property frequently utilize solver APIs whenever protected search and discovery pages present challenge gates.</p>
<p>In every case, the CAPTCHA farm doesn't execute the underlying abuse: it merely removes the specific verification tripwire meant to halt it.</p>
<h2 id="heading-why-these-attacks-are-difficult-to-stop">Why These Attacks Are Difficult to Stop</h2>
<p>Stopping CAPTCHA farms is inherently difficult because they exploit the core assumption behind standard challenge-response security: that the entity answering the challenge is the entity making the request.</p>
<p>This systemic blind spot is analyzed in the research paper <a href="https://link.springer.com/chapter/10.1007/978-3-319-66399-9_24"><u>On the Security and Usability of Dynamic Cognitive Game CAPTCHAs</u></a>, which evaluated how puzzle formats hold up against relay systems. The study demonstrated that regardless of how cognitively engaging, gamified, or technically dynamic a test is, relay architectures successfully decouple cognitive processing from the requesting client. The server receives a mathematically legitimate, human-generated solution token, making the puzzle itself effectively irrelevant.</p>
<p>Also, attackers route their client requests through residential proxy networks. The initial HTTP request comes from one residential IP address, the CAPTCHA is rendered by an automated browser mimicking common hardware profiles, and the solution is completed remotely. The defender’s server can't verify the physical proximity between the solver and the requesting client, creating an asymmetric advantage for the attacker.</p>
<h2 id="heading-how-websites-can-defend-themselves">How Websites Can Defend Themselves</h2>
<p>Because human solvers can easily clear visual and cognitive challenges, treating a solved puzzle as a blanket guarantee of trustworthiness is no longer a viable defensive strategy. Web applications require a defense-in-depth model that monitors behaviors before, during, and long after a verification challenge appears.</p>
<h3 id="heading-behavioral-telemetry-and-biometrics">Behavioral Telemetry and Biometrics</h3>
<p>Automated scripts can easily spoof screen resolutions and user-agent strings, but reproducing organic human cursor movement across an entire page requires far more work. Real users demonstrate micro-deviations, variable acceleration curves, pauses, and continuous mouse tremors.</p>
<p>When a CAPTCHA farm attack takes place, there's often a distinct behavioral mismatch: the form fields are filled out instantaneously or via scripted keyboard events, followed by an abrupt pause while the remote worker solves the puzzle, followed by an instantaneous token injection. Monitoring telemetry across the whole lifecycle of the page exposes this artificial stitching.</p>
<h3 id="heading-network-and-device-fingerprinting">Network and Device Fingerprinting</h3>
<p>Defenders must assess context beyond the single page interaction. Inspecting TCP/IP packet behavior, TLS fingerprints (JA3/JA4 fingerprints), HTTP/2 frame parameters, and device APIs reveals whether the underlying runtime environment is a standard consumer browser or an orchestrated automation tool running inside a data center.</p>
<h3 id="heading-modern-rate-limiting-models">Modern Rate-Limiting Models</h3>
<p>Relying entirely on puzzle solving often introduces accessibility barriers for real users while doing little to stop funded attackers. As explored in research published by the Association for Computing Machinery regarding <a href="https://dl.acm.org/doi/10.1145/3638759"><u>mCaptcha and Proof-of-Work Rate Limiting</u></a>, defensive architectures can enforce cryptographic proof of work puzzles at the transport layer.</p>
<p>By forcing the connecting client's CPU to compute complex mathematical problems proportional to the platform's current traffic load, defense systems raise the economic and computational cost of running automated campaigns, neutralizing attacks without demanding manual human puzzle-solving.</p>
<h3 id="heading-post-authentication-anomaly-detection">Post-Authentication Anomaly Detection</h3>
<p>Passing an authentication challenge should never grant unconditional trust. Web architectures should monitor post-login activity for anomalous actions:</p>
<ul>
<li>Does an account immediately attempt hundreds of data queries per minute right after registering?</li>
<li>Does it immediately navigate directly to high-value purchase endpoints without loading associated asset stylesheets or images?</li>
<li>Does the session change IP ranges and geographic locations between the initial page load and the final transaction?</li>
</ul>
<p>Identifying these signals allows security teams to invalidate sessions even if the initial challenge was solved cleanly.</p>
<h2 id="heading-security-beyond-the-checkbox">Security Beyond the Checkbox</h2>
<p>CAPTCHA farms show why websites can't rely on a single security check to keep automated attacks away. Even when someone successfully completes a CAPTCHA, the request may still be part of an automated operation.</p>
<p>CAPTCHAs are designed to check whether a person can solve a particular challenge. But they can't tell whether that person is the actual user trying to access the website or someone solving the challenge on behalf of a bot. This is one of the reasons CAPTCHA farms can bypass a security measure that would normally stop automated traffic.</p>
<p>For developers, this means a completed CAPTCHA should be treated as just one part of the verification process. Websites also need to monitor user behavior, network activity, and suspicious requests to identify possible attacks. Combining these checks makes it easier to spot activity that a CAPTCHA alone might miss.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>CAPTCHA farms make it difficult for websites to tell whether a completed verification challenge actually came from a legitimate user. Even when a real person solves the puzzle, the request may still be part of an automated attack.</p>
<p>For developers, this means it's worth paying attention to what happens before and after a CAPTCHA is completed. Things like unusual login attempts, repeated requests, unexpected changes in user behavior, and suspicious account activity can provide useful clues.</p>
<p>Using CAPTCHA alongside rate limiting, behavioral monitoring, and other security checks can help websites identify these attacks more effectively. It's also important to review these protections regularly as attackers change how they operate.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
