<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Start Quitting Smoking]]></title><description><![CDATA[Start Quitting Smoking]]></description><link>https://startquittingsmoking.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 18 Nov 2026 14:06:43 GMT</lastBuildDate><atom:link href="https://startquittingsmoking.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Null Is Not Zero: Building an Honest "Time Back" Estimator in React With localStorage]]></title><description><![CDATA[We're the Start Quitting Smoking team, and we're building startquittingsmoking.com for the Ship or Die $100K hackathon. It's a small React app with a free…]]></description><link>https://startquittingsmoking.hashnode.dev/null-is-not-zero-building-an-honest-time-back-estimator-in-react-with-localstorage</link><guid isPermaLink="true">https://startquittingsmoking.hashnode.dev/null-is-not-zero-building-an-honest-time-back-estimator-in-react-with-localstorage</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[hackathon]]></category><category><![CDATA[Build In Public]]></category><dc:creator><![CDATA[Start Quitting Smoking]]></dc:creator><pubDate>Tue, 17 Nov 2026 10:25:41 GMT</pubDate><content:encoded><![CDATA[<p>We're the Start Quitting Smoking team, and we're building <a href="https://startquittingsmoking.com/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-timeback">startquittingsmoking.com</a> for the Ship or Die $100K hackathon. It's a small React app with a free, no-signup <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-timeback">30-day taper calculator</a> and a localStorage-first daily tracker. Earlier posts in this series covered the <a href="https://startquittingsmoking.hashnode.dev/we-built-a-free-straight-line-taper-calculator-and-a-9-30-day-quit-app">build story</a>, rounding, the session scheduler, backend-free Undo, dark mode without the flash, the install button, the PNG progress card, and the <a href="https://startquittingsmoking.hashnode.dev/one-checkbox-every-logo-syncing-a-per-habit-quit-flag-across-react-components-with-localstorage-and-a-custom-event">per-habit "quit" checkbox</a>.</p>
<p>This one is about a small panel called <strong>"Time back with people."</strong> You type how many times a day a habit takes you away from others (cannabis, cigarettes or alcohol) and how many minutes each time. The panel shows a daily and yearly estimate, plus "about X back so far" since a start time you've already set elsewhere in the app.</p>
<p>It's simple arithmetic. The hard part is making sure the panel never shows a number it can't back up. Everything below matches our production bundle. We renamed the minified identifiers so the code is readable.</p>
<h2>Rule 1: store what the user typed, not what you parsed</h2>
<p>The settings are one JSON blob under one key, with a default for every habit:</p>
<pre><code class="language-js">const TIME_BACK_KEY = "day-one-time-back-v1";
const HABITS = ["cannabis", "cigarettes", "alcohol"];
const DEFAULTS = {
  cannabis:   { sessions: "", minutes: "" },
  cigarettes: { sessions: "", minutes: "" },
  alcohol:    { sessions: "", minutes: "" },
};
</code></pre>
<p>The values are <strong>strings</strong>, and the empty string is the default. A controlled <code>&lt;input type="number"&gt;</code> that you force through <code>Number()</code> on every keystroke turns "" into <code>0</code>. Then the user can't clear the field, and "I haven't answered" looks the same as "zero times a day." Keeping the raw string means the input shows exactly what was typed. We parse only when we compute.</p>
<h2>Rule 2: merge stored data over defaults, per habit</h2>
<pre><code class="language-js">function loadTimeBack() {
  try {
    const raw = window.localStorage.getItem(TIME_BACK_KEY);
    if (!raw) return DEFAULTS;
    const saved = JSON.parse(raw);
    return {
      cannabis:   { ...DEFAULTS.cannabis,   ...saved.cannabis },
      cigarettes: { ...DEFAULTS.cigarettes, ...saved.cigarettes },
      alcohol:    { ...DEFAULTS.alcohol,    ...saved.alcohol },
    };
  } catch {
    return DEFAULTS;
  }
}
</code></pre>
<p>Two things make this safe:</p>
<ul>
<li><strong>The merge is per habit, not top level.</strong> <code>{ ...DEFAULTS, ...saved }</code> would let a saved <code>cannabis: { sessions: "3" }</code> with no <code>minutes</code> field wipe out the nested default. Spreading each habit separately means a missing field always falls back to <code>""</code>. That also covers a blob written before a field existed, or a habit we add later.</li>
<li><strong>Spreading <code>undefined</code> is a no-op.</strong> If <code>saved.alcohol</code> is missing, <code>{ ...DEFAULTS.alcohol, ...undefined }</code> is just the default. No guard needed.</li>
</ul>
<p>Anything that throws, like blocked storage in a private window or corrupted JSON, falls back to the defaults. The <code>-v1</code> suffix leaves room to change the format later without misreading old data.</p>
<h2>Rule 3: <code>null</code> means "not entered," and it is not zero</h2>
<pre><code class="language-js">function positiveOrZero(value) {
  const n = Number(value);
  return Number.isFinite(n) &amp;&amp; n &gt; 0 ? n : 0;
}

// minutes per day away for one habit, or null if we can't say
function dailyMinutes(settings, habit) {
  const sessions = positiveOrZero(settings[habit].sessions);
  const minutes  = positiveOrZero(settings[habit].minutes);
  return sessions &gt; 0 &amp;&amp; minutes &gt; 0 ? sessions * minutes : null;
}
</code></pre>
<p><code>positiveOrZero</code> absorbs everything weird: <code>""</code>, <code>"abc"</code>, <code>"-2"</code>, <code>"Infinity"</code>. Then <code>dailyMinutes</code> refuses to answer unless <strong>both</strong> inputs are positive. "3 times a day" with no duration isn't zero minutes. It's unknown, so the function returns <code>null</code> and the card says <strong>"Not entered."</strong></p>
<p>That one choice settles the rest of the UI:</p>
<ul>
<li>Each card shows either "Not entered" or <code>"&lt;daily&gt; a day, &lt;daily × 365&gt; a year"</code>.</li>
<li>The combined total adds only the non-null habits.</li>
<li>If every habit is <code>null</code>, the totals box doesn't show "0 min" at all. It says "Enter times for any habit to see an estimate."</li>
</ul>
<pre><code class="language-js">const perHabit = HABITS.map((h) =&gt; dailyMinutes(settings, h));
const anyEntered = perHabit.some((m) =&gt; m !== null);
const combinedDaily = perHabit.reduce((sum, m) =&gt; sum + (m ?? 0), 0);
</code></pre>
<p><code>?? 0</code> is only used <em>inside the sum</em>, after <code>anyEntered</code> has decided whether a total is shown at all.</p>
<h2>Rule 4: "so far" needs a real start time, in the past</h2>
<p>The "back so far" line multiplies the daily estimate by the days since a start time the user already set elsewhere in the app. That's a last-use time for cannabis and alcohol, and a nicotine-free date from the Nicotine plan for cigarettes:</p>
<pre><code class="language-js">const DAY_MS = 86_400_000;

function reclaimedSoFar(settings, startTimes, now) {
  const result = { cannabis: null, cigarettes: null, alcohol: null };
  HABITS.forEach((habit) =&gt; {
    const daily = dailyMinutes(settings, habit);
    const start = startTimes[habit];
    if (daily !== null &amp;&amp; start !== null &amp;&amp; start &lt;= now) {
      result[habit] = daily * ((now - start) / DAY_MS);
    }
  });
  return result;
}
</code></pre>
<ul>
<li><strong>No start time, no number.</strong> The card explains what's missing instead: "Add a nicotine-free date in Nicotine plan." for cigarettes, "Set a last-use time to estimate." for the others.</li>
<li><strong><code>start &lt;= now</code></strong> guards against a future date (a typo, or a clock change). We never show a negative "time back."</li>
<li>Days are fractional (<code>(now - start) / DAY_MS</code>), so the figure moves smoothly as <code>now</code> ticks instead of jumping at midnight.</li>
</ul>
<h2>Rule 5: format for humans, keep precision where it matters</h2>
<pre><code class="language-js">function formatMinutes(min) {
  if (min &lt; 60) return `${Math.round(min)} min`;
  const hours = min / 60;
  return `${hours &lt; 10 ? hours.toFixed(1) : Math.round(hours).toLocaleString()} hr`;
}
</code></pre>
<p>Under an hour we show whole minutes. Under ten hours one decimal ("2.5 hr") still carries information. Past that, decimals are noise, so we round and add thousands separators for the yearly figure.</p>
<h2>Rule 6: say what the number isn't</h2>
<p>The panel ends with a plain note, verbatim from the app:</p>
<blockquote>
<p>Estimates only. Overlap between habits is not counted. Time back assumes no use since each start time. It is time you could use, not a measure of time with people.</p>
</blockquote>
<p>The code adds habits together, so if two habits overlap in the same break, the total over-counts. We can't detect that from two numbers, so we say so instead of pretending. If saving fails, a <code>role="alert"</code> message tells the user the settings will reset when they leave. A silent failure would be worse.</p>
<p>Every input also carries <code>data-undo-keys="day-one-time-back-v1"</code>, so any edit goes through the same <a href="https://startquittingsmoking.hashnode.dev/undo-without-a-backend-snapshotting-localstorage-keys-in-a-react-app">backend-free Undo stack</a> as the rest of the app.</p>
<h2>Takeaways</h2>
<ol>
<li>Keep form values as the strings the user typed. Parse at compute time.</li>
<li>Merge persisted JSON over defaults <strong>per nested object</strong>, so missing fields can't wipe out defaults.</li>
<li>Use <code>null</code> for "can't say" and keep it apart from <code>0</code> all the way to the UI.</li>
<li>Guard time math against missing and future timestamps.</li>
<li>Put the limits of an estimate on screen, next to the estimate.</li>
</ol>
<h2>Try it</h2>
<p>The <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-timeback">30-day taper calculator</a> is free and needs no account. The full app at <a href="https://startquittingsmoking.com/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-timeback">startquittingsmoking.com</a> has a 24-hour free trial, then a one-time $9 (not a subscription). Records stay in your browser's local storage. The app is a planning and tracking tool, not medical advice, and a 30-day taper is a start, not a guaranteed quit.</p>
<p><em>Built by the Start Quitting Smoking team for the Ship or Die $100K hackathon.</em></p>
]]></content:encoded></item><item><title><![CDATA[One Checkbox, Every Logo: Syncing a Per-Habit "Quit" Flag Across React Components With localStorage and a Custom Event]]></title><description><![CDATA[We're the Start Quitting Smoking team, and we're building startquittingsmoking.com for the Ship or Die $100K hackathon. It's a small React app with a free…]]></description><link>https://startquittingsmoking.hashnode.dev/one-checkbox-every-logo-syncing-a-per-habit-quit-flag-across-react-components-with-localstorage-and-a-custom-event</link><guid isPermaLink="true">https://startquittingsmoking.hashnode.dev/one-checkbox-every-logo-syncing-a-per-habit-quit-flag-across-react-components-with-localstorage-and-a-custom-event</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[hackathon]]></category><category><![CDATA[Build In Public]]></category><dc:creator><![CDATA[Start Quitting Smoking]]></dc:creator><pubDate>Tue, 17 Nov 2026 09:21:48 GMT</pubDate><content:encoded><![CDATA[<p>We're the Start Quitting Smoking team, and we're building <a href="https://startquittingsmoking.com/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-quitstatus">startquittingsmoking.com</a> for the Ship or Die $100K hackathon. It's a small React app with a free <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-quitstatus">30-day taper calculator</a> and a localStorage-first daily tracker. Earlier posts in this series covered the <a href="https://startquittingsmoking.hashnode.dev/we-built-a-free-straight-line-taper-calculator-and-a-9-30-day-quit-app">build story</a>, rounding, the session scheduler, backend-free Undo, dark mode without the flash, an install button that never dead-ends, and a <a href="https://startquittingsmoking.hashnode.dev/turning-a-react-svg-into-a-downloadable-png-with-no-server-our-private-progress-card-export">server-free PNG progress card</a>.</p>
<p>This post is about the smallest feature in the app: one checkbox labelled <strong>"I've quit cigarettes"</strong> (or vaping, or weed). Checking it stops the little pixel-art logo from smoking, everywhere the logo appears, instantly. No backend, no global store, no context provider.</p>
<p>Everything below matches our production bundle. We renamed the minified identifiers so the code is readable.</p>
<h2>The requirements</h2>
<ol>
<li><strong>Per habit.</strong> The app supports three plans (cigarettes, vaping, weed). Marking one as quit must not mark the others.</li>
<li><strong>Every logo updates at once.</strong> The logo head is rendered in several places (header, footer, pages). They all have to agree.</li>
<li><strong>Other tabs update too.</strong> If the app is open in two tabs, both should flip.</li>
<li><strong>Reversible.</strong> The note under the checkbox says: "Stops the logo smoke. Your plan stays saved. You can uncheck this any time." And the change goes through the same Undo system as every other edit.</li>
<li><strong>Never crash on storage errors.</strong> Private modes and full quotas happen.</li>
</ol>
<h2>Step 1: one key per habit</h2>
<p>The selected plan and the quit flags are plain localStorage keys:</p>
<pre><code class="language-js">const SELECTED_PLAN_KEY = "day-one-taper-selected-v1";
const PREFS_EVENT = "day-one-habit-preferences";
const quitKey = (habit) =&gt; `day-one-quit-${habit}-v1`;

function getSelectedHabit() {
  try {
    const value = localStorage.getItem(SELECTED_PLAN_KEY);
    return value === "weed" || value === "vaping" || value === "cigarettes"
      ? value
      : "cigarettes";
  } catch {
    return "cigarettes";
  }
}
</code></pre>
<p>Keying by habit (<code>day-one-quit-cigarettes-v1</code>, <code>day-one-quit-vaping-v1</code>, ...) means requirement 1 is free. The <code>-v1</code> suffix lets us change the format later without misreading old values. We store <code>"true"</code> and <em>remove</em> the key when unchecked, so "no key" and "not quit" are the same state.</p>
<h2>Step 2: a tiny event bus made of one custom event</h2>
<p>React state lives inside components, and localStorage doesn't notify the tab that wrote to it. The browser's <code>storage</code> event only fires in <em>other</em> tabs. So we fire our own event in the current tab after every write:</p>
<pre><code class="language-js">function notifyHabitPrefsChanged() {
  window.dispatchEvent(new Event(PREFS_EVENT));
}
</code></pre>
<p>That's the whole bus. Any component that cares listens for <code>PREFS_EVENT</code> (same tab) and <code>storage</code> (other tabs).</p>
<h2>Step 3: a hook that reads the flag and re-reads on either event</h2>
<pre><code class="language-js">function useIsQuit(habit) {
  const read = () =&gt; {
    try {
      return localStorage.getItem(quitKey(habit ?? getSelectedHabit())) === "true";
    } catch {
      return false;
    }
  };

  const [isQuit, setIsQuit] = useState(read);

  useEffect(() =&gt; {
    const sync = () =&gt; setIsQuit(read());
    sync(); // catch anything that changed between render and effect
    window.addEventListener(PREFS_EVENT, sync);
    window.addEventListener("storage", sync);
    return () =&gt; {
      window.removeEventListener(PREFS_EVENT, sync);
      window.removeEventListener("storage", sync);
    };
  }, [habit]);

  return isQuit;
}
</code></pre>
<p>A few details that matter:</p>
<ul>
<li><strong>Lazy initial state</strong> (<code>useState(read)</code>) means the first paint is already correct, with no flicker from "smoking" to "quit".</li>
<li><strong><code>habit</code> is optional.</strong> The tracker passes the habit it's showing. The header logo passes nothing and falls back to whichever plan is selected.</li>
<li><strong>The <code>sync()</code> call inside the effect</strong> covers the gap between the first render and the listener being attached.</li>
<li><strong>Every read is wrapped in <code>try/catch</code>.</strong> If storage throws, the logo just keeps smoking, which is the safe default for a decoration.</li>
</ul>
<h2>Step 4: the logo is just an SVG that reads the hook</h2>
<p>The logo head is a 16x16 pixel-art SVG with <code>shapeRendering="crispEdges"</code>. The quit flag changes three things: the skin tone gets slightly lighter, the mouth path changes, and the smoke group isn't rendered at all.</p>
<pre><code class="language-jsx">function LivingHead({ habit }) {
  const isQuit = useIsQuit(habit);

  return (
    &lt;span
      className={`living-head${isQuit ? " is-quit" : ""}`}
      aria-hidden="true"
      data-quit={isQuit}
    &gt;
      &lt;svg viewBox="0 0 16 16" focusable="false" shapeRendering="crispEdges"&gt;
        {/* frame + face */}
        &lt;path d="M2 3h10v9h-1v1H3v-1H2z" fill={isQuit ? "#f2cba0" : "#dfb58d"} /&gt;
        {/* eyes ... */}
        {isQuit
          ? &lt;path d="M4 10h1v1h4v-1h1v2H4z" fill="#282a25" /&gt;      /* smile */
          : &lt;path d="M5 10h4v1h1v1H9v-1H5v1H4v-1h1z" fill="#282a25" /&gt; /* cigarette mouth */}
        {!isQuit &amp;&amp; (
          &lt;g className="living-head-smoke" fill="currentColor"&gt;
            &lt;path className="head-puff head-puff-one" d="..." /&gt;
            {/* more puffs */}
          &lt;/g&gt;
        )}
      &lt;/svg&gt;
    &lt;/span&gt;
  );
}
</code></pre>
<p>The puffs are animated with CSS, and we turn the animation off for people who ask for less motion:</p>
<pre><code class="language-css">@media (prefers-reduced-motion: reduce) {
  .living-head-eyes,
  .head-puff { animation: none; }
  .head-puff { opacity: .5; }
}
</code></pre>
<p>Because the head is <code>aria-hidden</code>, screen readers skip it. The checkbox is the accessible control. The logo is just a reflection of it.</p>
<h2>Step 5: the checkbox writes, notifies, and is undoable</h2>
<p>The toggle lives under a "Change my plan" disclosure in the tracker:</p>
<pre><code class="language-jsx">&lt;label className="do-quit-choice"&gt;
  &lt;input
    type="checkbox"
    checked={isQuit}
    onChange={(e) =&gt; setQuit(e.target.checked)}
  /&gt;
  &lt;span&gt;I've quit {habit === "weed" ? "weed" : habit === "vaping" ? "vaping" : "cigarettes"}&lt;/span&gt;
&lt;/label&gt;
&lt;p className="do-quit-note"&gt;
  Stops the logo smoke. Your plan stays saved. You can uncheck this any time.
&lt;/p&gt;
</code></pre>
<p>And the handler goes through <code>record(label, keys, mutate)</code> from our <a href="https://startquittingsmoking.hashnode.dev/undo-without-a-backend-snapshotting-localstorage-keys-in-a-react-app">backend-free Undo</a> system. <code>record</code> snapshots the listed keys before running the mutation, so "Undo" can restore them:</p>
<pre><code class="language-js">function setQuit(checked) {
  record(
    checked ? "Mark habit as quit" : "Unmark quit status",
    [quitKey(habit)],
    () =&gt; {
      try {
        checked
          ? localStorage.setItem(quitKey(habit), "true")
          : localStorage.removeItem(quitKey(habit));
        notifyHabitPrefsChanged();
        setError("");
      } catch {
        setError("Could not save your quit status on this device.");
      }
    }
  );
}
</code></pre>
<p>The tracker also calls <code>notifyHabitPrefsChanged()</code> in an effect whenever the selected habit changes or an Undo restores keys. That way the header logo follows plan switches and undos without knowing either of them exists.</p>
<h2>Why not Context or a store?</h2>
<p>We could have put <code>isQuit</code> in a React Context. But the source of truth is already localStorage, and it has to survive reloads and sync across tabs anyway. A context would be a second copy that we'd have to keep in sync with the first. With the hook-plus-event approach:</p>
<ul>
<li>The truth lives in exactly one place.</li>
<li>Any component can subscribe with one line.</li>
<li>Cross-tab sync comes free from the native <code>storage</code> event.</li>
<li>The whole thing is about 25 lines.</li>
</ul>
<p>The trade-off: every subscriber re-reads localStorage on every preference event. With a handful of logos and a synchronous read of one tiny key, that cost is negligible. With hundreds of subscribers or big JSON values, we'd reach for <code>useSyncExternalStore</code> and a cached snapshot.</p>
<h2>Try it</h2>
<p>The <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-quitstatus">30-day taper calculator</a> is free and needs no sign-up. The full tracker (where the checkbox lives) has a 24-hour free trial, then a one-time $9. A 30-day taper is a planning tool and a start, not a guaranteed quit or medical advice.</p>
<p>If you're building something for Ship or Die too, we'd like to hear what you're shipping. The <a href="https://startquittingsmoking.hashnode.dev/we-built-a-free-straight-line-taper-calculator-and-a-9-30-day-quit-app">build story</a> covers the rest of how we made it.</p>
]]></content:encoded></item><item><title><![CDATA[Turning a React SVG Into a Downloadable PNG With No Server: Our Private "Progress Card" Export]]></title><description><![CDATA[We're the Start Quitting Smoking team, and we're building startquittingsmoking.com for the Ship or Die $100K hackathon. It's a small React app with a free…]]></description><link>https://startquittingsmoking.hashnode.dev/turning-a-react-svg-into-a-downloadable-png-with-no-server-our-private-progress-card-export</link><guid isPermaLink="true">https://startquittingsmoking.hashnode.dev/turning-a-react-svg-into-a-downloadable-png-with-no-server-our-private-progress-card-export</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[hackathon]]></category><category><![CDATA[Build In Public]]></category><dc:creator><![CDATA[Start Quitting Smoking]]></dc:creator><pubDate>Tue, 17 Nov 2026 08:26:27 GMT</pubDate><content:encoded><![CDATA[<p>We're the Start Quitting Smoking team, and we're building <a href="https://startquittingsmoking.com/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-progresscard">startquittingsmoking.com</a> for the Ship or Die $100K hackathon. It's a small React app with a free <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-progresscard">30-day taper calculator</a> and a localStorage-first daily tracker. Earlier posts in this series covered the <a href="https://startquittingsmoking.hashnode.dev/we-built-a-free-straight-line-taper-calculator-and-a-9-30-day-quit-app">build story</a>, rounding, the session scheduler, backend-free Undo, honest cached timestamps, dark mode without the flash, and an <a href="https://startquittingsmoking.hashnode.dev/an-add-to-home-screen-button-that-never-dead-ends-beforeinstallprompt-standalone-detection-and-manual-fallbacks">install button that never dead-ends</a>.</p>
<p>This post is about a small feature with a strict constraint: a <strong>"Share my progress" card</strong> that someone can turn into an image, <strong>without our server ever seeing their data</strong>, and without anything posting automatically.</p>
<p>Everything below matches our production bundle. We renamed the minified identifiers so the code is readable.</p>
<h2>The rules we set</h2>
<ol>
<li><strong>Preview first.</strong> The card opens in a dialog that says "Review it first. Nothing will post automatically."</li>
<li><strong>No dates of use on the image.</strong> The card shows elapsed time and an "as of" timestamp, not the raw entries.</li>
<li><strong>No upload.</strong> The PNG is rendered in the browser and handed to the user as a download.</li>
<li><strong>Honest status messages.</strong> Every failure path says what happened; success says "Your PNG is ready. Nothing was posted."</li>
<li><strong>Missing data is labelled, not hidden.</strong> If a timer isn't set, the dialog says the card will show "Not set".</li>
</ol>
<h2>Step 1: draw the card as an inline SVG in React</h2>
<p>The card is plain JSX that renders an <code>&lt;svg&gt;</code> at a fixed 1200x675 (a 16:9 size that most social sites accept). We keep a ref to it so we can serialize exactly what the user is looking at.</p>
<pre><code class="language-jsx">const cardRef = useRef(null);

&lt;div className="progress-preview-frame"&gt;
  &lt;svg
    ref={cardRef}
    xmlns="http://www.w3.org/2000/svg"
    width="1200"
    height="675"
    viewBox="0 0 1200 675"
    role="img"
    aria-labelledby="progress-art-title progress-art-description"
  &gt;
    &lt;title id="progress-art-title"&gt;startquittingsmoking.com personal progress card&lt;/title&gt;
    &lt;desc id="progress-art-description"&gt;
      30-day challenge progress and elapsed time, with an as-of date. No use dates are shown.
    &lt;/desc&gt;
    &lt;ProgressArtwork challengeLabel={dayLabel} now={now} asOf={asOfLabel} /* ... */ /&gt;
  &lt;/svg&gt;
&lt;/div&gt;
</code></pre>
<p>Two details matter here:</p>
<ul>
<li><strong><code>xmlns</code> is required.</strong> When the SVG is serialized and loaded as an image, a missing namespace gives you a broken image with no useful error.</li>
<li><strong><code>&lt;title&gt;</code> and <code>&lt;desc&gt;</code></strong> make the preview accessible to screen readers, and they cost nothing.</li>
</ul>
<h2>Step 2: SVG -&gt; Blob -&gt; Image -&gt; canvas -&gt; PNG</h2>
<p>The browser can't download an SVG DOM node as a PNG directly, but it can take a few short hops:</p>
<pre><code class="language-js">const exportPng = () =&gt; {
  const svg = cardRef.current;
  if (!svg) return;
  setBusy(true);
  setStatus("");

  try {
    // 1. Serialize the live SVG node to a string
    const markup = new XMLSerializer().serializeToString(svg);
    // 2. Wrap it in a Blob and get a temporary object URL
    const svgBlob = new Blob([markup], { type: "image/svg+xml;charset=utf-8" });
    const svgUrl = URL.createObjectURL(svgBlob);
    // 3. Load it into an Image
    const img = new Image();

    img.onload = () =&gt; {
      // 4. Paint onto a canvas at the exact card size
      const canvas = document.createElement("canvas");
      canvas.width = 1200;
      canvas.height = 675;
      const ctx = canvas.getContext("2d");
      if (!ctx) {
        URL.revokeObjectURL(svgUrl);
        setBusy(false);
        setStatus("PNG export is not available in this browser.");
        return;
      }
      ctx.drawImage(img, 0, 0, 1200, 675);
      URL.revokeObjectURL(svgUrl);

      // 5. Encode to PNG and trigger a download
      canvas.toBlob((pngBlob) =&gt; {
        if (!pngBlob) {
          setBusy(false);
          setStatus("PNG export did not work. Please try again.");
          return;
        }
        const pngUrl = URL.createObjectURL(pngBlob);
        const a = document.createElement("a");
        a.href = pngUrl;
        a.download = "start-quitting-smoking-progress.png";
        a.click();
        setTimeout(() =&gt; URL.revokeObjectURL(pngUrl), 1000);
        setBusy(false);
        setStatus("Your PNG is ready. Nothing was posted.");
      }, "image/png");
    };

    img.onerror = () =&gt; {
      URL.revokeObjectURL(svgUrl);
      setBusy(false);
      setStatus("PNG export did not work. Please try again.");
    };

    img.src = svgUrl;
  } catch {
    setBusy(false);
    setStatus("PNG export did not work. Please try again.");
  }
};
</code></pre>
<h3>Why each guard is there</h3>
<table>
<thead>
<tr>
<th>Guard</th>
<th>What it protects against</th>
</tr>
</thead>
<tbody><tr>
<td><code>if (!svg) return</code></td>
<td>Button clicked before the dialog mounted the ref</td>
</tr>
<tr>
<td><code>getContext("2d")</code> null check</td>
<td>Locked-down or very old browsers</td>
</tr>
<tr>
<td><code>toBlob</code> null check</td>
<td>Encoding failure (rare, but it does happen)</td>
</tr>
<tr>
<td><code>img.onerror</code></td>
<td>Malformed SVG, e.g. a missing <code>xmlns</code></td>
</tr>
<tr>
<td>outer <code>try/catch</code></td>
<td><code>XMLSerializer</code> or <code>Blob</code> throwing</td>
</tr>
<tr>
<td><code>revokeObjectURL</code> on every path</td>
<td>Leaking object URLs each time someone retries</td>
</tr>
</tbody></table>
<p>The 1-second delay before revoking the PNG URL exists because some browsers start the download asynchronously after <code>a.click()</code>. Revoking it on the same tick can cancel the download.</p>
<h3>Why <code>toBlob</code> and not <code>toDataURL</code></h3>
<p><code>toDataURL</code> builds a base64 string about 33% larger than the PNG, all held in memory as a JS string. <code>toBlob</code> hands back binary data asynchronously, which is cheaper on phones.</p>
<h2>Step 3: a copyable caption with a fallback</h2>
<p>Next to the image, we show a plain-text caption built from the same state, plus a "Copy caption" button. The Clipboard API is not available everywhere (insecure contexts, some in-app browsers), so there's an old-school fallback:</p>
<pre><code class="language-js">const copyCaption = async () =&gt; {
  try {
    if (navigator.clipboard?.writeText) {
      await navigator.clipboard.writeText(caption);
    } else {
      const ta = document.createElement("textarea");
      ta.value = caption;
      ta.style.position = "fixed";
      ta.style.opacity = "0";
      document.body.appendChild(ta);
      ta.select();
      document.execCommand("copy");
      ta.remove();
    }
    setCopyStatus("Caption copied. Share it only if you choose.");
  } catch {
    setCopyStatus("Copy was not available. You can select the caption text.");
  }
};
</code></pre>
<p>The caption is also visible as selectable text, so even if both paths fail, the user can still copy it by hand.</p>
<h2>Step 4: announce status politely</h2>
<p>Both the export status and the copy status render into one <code>role="status"</code> + <code>aria-live="polite"</code> region, and the download button changes its label to "Making PNG..." and disables itself while busy. Screen-reader users hear the result, and nobody can double-click their way into two downloads.</p>
<pre><code class="language-jsx">&lt;button onClick={exportPng} disabled={busy}&gt;
  {busy ? "Making PNG..." : "Download PNG"}
&lt;/button&gt;
&lt;div role="status" aria-live="polite"&gt;{copyStatus || status}&lt;/div&gt;
</code></pre>
<h2>What we'd tell another hackathon team</h2>
<ul>
<li><strong>An SVG is the easiest "image template" in React.</strong> It's just JSX with real text, so it stays sharp, and you can diff it in code review.</li>
<li><strong>Client-side rendering keeps privacy simple.</strong> Nothing goes over the network, so there's nothing to secure, store or delete.</li>
<li><strong>Write every failure message.</strong> Exporting an image has four or five ways to fail, and a silent failure looks like a broken app.</li>
<li><strong>Don't auto-share.</strong> A preview plus a download plus a copy button puts the user in control.</li>
</ul>
<h2>Try it</h2>
<p>The free <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-progresscard">30-day taper calculator</a> needs no signup. The full tracker (including the progress card) is at <a href="https://startquittingsmoking.com/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-progresscard">startquittingsmoking.com</a>. The rest of the build story, including what's free and what's paid, is in <a href="https://startquittingsmoking.hashnode.dev/we-built-a-free-straight-line-taper-calculator-and-a-9-30-day-quit-app">our first post</a>.</p>
<p><em>Built by the Start Quitting Smoking team for the Ship or Die $100K hackathon.</em></p>
]]></content:encoded></item><item><title><![CDATA[An "Add to Home Screen" Button That Never Dead-Ends: beforeinstallprompt, Standalone Detection, and Manual Fallbacks]]></title><description><![CDATA[We're the Start Quitting Smoking team, and we're building startquittingsmoking.com for the Ship or Die $100K hackathon. It's a small React app with a free…]]></description><link>https://startquittingsmoking.hashnode.dev/an-add-to-home-screen-button-that-never-dead-ends-beforeinstallprompt-standalone-detection-and-manual-fallbacks</link><guid isPermaLink="true">https://startquittingsmoking.hashnode.dev/an-add-to-home-screen-button-that-never-dead-ends-beforeinstallprompt-standalone-detection-and-manual-fallbacks</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[hackathon]]></category><category><![CDATA[Build In Public]]></category><dc:creator><![CDATA[Start Quitting Smoking]]></dc:creator><pubDate>Tue, 17 Nov 2026 07:25:34 GMT</pubDate><content:encoded><![CDATA[<p>We're the Start Quitting Smoking team, and we're building <a href="https://startquittingsmoking.com/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-install">startquittingsmoking.com</a> for the Ship or Die $100K hackathon. It's a small React app with a free <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-install">30-day taper calculator</a> and a localStorage-first daily tracker. Earlier posts in this series covered the <a href="https://startquittingsmoking.hashnode.dev/we-built-a-free-straight-line-taper-calculator-and-a-9-30-day-quit-app">build story</a>, rounding, the session scheduler, backend-free Undo, honest cached timestamps, and <a href="https://startquittingsmoking.hashnode.dev/dark-mode-without-the-flash-one-localstorage-key-one-inline-script-and-a-custom-dom-event">dark mode without the flash</a>.</p>
<p>This one is about a feature that matters for any daily-habit app: <strong>getting the app onto someone's home screen.</strong> A plan you check several times a day only works if it's one tap away. The catch is that browsers disagree about how installing works, so a single "Install" button is unreliable.</p>
<p>Everything below matches our production manifest and bundle. We renamed the minified identifiers so the code is readable.</p>
<h2>The rules we set</h2>
<ol>
<li>If the app is <strong>already running installed</strong>, show nothing.</li>
<li>If the browser <strong>offers a native install prompt</strong>, show a one-click "Add app to this device" button.</li>
<li><strong>Always</strong> show written steps for iPhone/iPad, Android, desktop, and "set as browser home page", because many browsers never offer the native prompt.</li>
<li>Be upfront: installing does <strong>not</strong> sync data. Records live in this browser's localStorage.</li>
</ol>
<h2>Step 1: the manifest</h2>
<p>Installability starts with a web app manifest linked from <code>index.html</code>:</p>
<pre><code class="language-html">&lt;link rel="manifest" href="/manifest.webmanifest" /&gt;
&lt;meta name="theme-color" content="#131c16" /&gt;
&lt;meta name="apple-mobile-web-app-capable" content="yes" /&gt;
&lt;meta name="apple-mobile-web-app-title" content="Quit Smoking" /&gt;
&lt;link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png?v=2" /&gt;
</code></pre>
<pre><code class="language-json">{
  "id": "./",
  "name": "Start Quitting Smoking",
  "short_name": "Quit Smoking",
  "start_url": "./",
  "scope": "./",
  "display": "standalone",
  "background_color": "#131c16",
  "theme_color": "#131c16",
  "icons": [
    { "src": "app-icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
    { "src": "app-icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" }
  ]
}
</code></pre>
<p><code>short_name</code> is what fits under the icon. The <code>apple-touch-icon</code> and <code>apple-mobile-web-app-*</code> tags are for iOS Safari, which takes its home-screen icon and title from those tags.</p>
<p>We don't ship a service worker yet. That's a deliberate trade-off for a hackathon build (more on it below). It also means whether a given browser fires a native install prompt is up to that browser's own install rules, which is one more reason the manual steps are always there.</p>
<h2>Step 2: one component, three pieces of state</h2>
<pre><code class="language-jsx">function AddToDevice() {
  const [open, setOpen] = useState(false);          // steps panel expanded?
  const [deferred, setDeferred] = useState(null);   // saved beforeinstallprompt event
  const [installed, setInstalled] = useState(false);
  const [status, setStatus] = useState("");

  useEffect(() =&gt; {
    const mq = window.matchMedia("(display-mode: standalone)");
    const sync = () =&gt; setInstalled(mq.matches || !!navigator.standalone);
    const onPrompt = (e) =&gt; { e.preventDefault(); setDeferred(e); };
    const onInstalled = () =&gt; { setInstalled(true); setDeferred(null); setOpen(false); };

    sync();
    mq.addEventListener("change", sync);
    window.addEventListener("beforeinstallprompt", onPrompt);
    window.addEventListener("appinstalled", onInstalled);
    return () =&gt; {
      mq.removeEventListener("change", sync);
      window.removeEventListener("beforeinstallprompt", onPrompt);
      window.removeEventListener("appinstalled", onInstalled);
    };
  }, []);

  if (installed) return null;
  // ...render toggle + panel
}
</code></pre>
<p>What each piece does:</p>
<ul>
<li><strong><code>matchMedia("(display-mode: standalone)")</code></strong> is true when the app was launched from an installed icon in browsers that support it. <strong><code>navigator.standalone</code></strong> is the older iOS Safari flag for the same thing. We check both, and we listen for <code>change</code> so the UI updates if the display mode flips.</li>
<li><strong><code>beforeinstallprompt</code></strong>: browsers that support it fire this when they're willing to install. We call <code>preventDefault()</code> to stop any automatic mini-infobar and <strong>keep the event</strong>, because it's the only handle we get for showing the prompt later on our own button.</li>
<li><strong><code>appinstalled</code></strong> fires after a successful install. We hide the whole section and drop the saved event.</li>
</ul>
<h2>Step 3: the native button, with a soft landing</h2>
<pre><code class="language-jsx">async function installNow() {
  if (!deferred) return;
  try {
    await deferred.prompt();
    const { outcome } = await deferred.userChoice;
    if (outcome === "accepted") {
      setStatus("Follow your browser's instructions to finish adding the app.");
    }
  } catch {
    setStatus("Use the steps below to add the app from your browser menu.");
  } finally {
    setDeferred(null); // a prompt event can only be used once
  }
}
</code></pre>
<p>Two details:</p>
<ol>
<li><strong><code>finally { setDeferred(null) }</code>.</strong> A saved prompt event can only be used once. Clearing it hides the native button whether the user accepted, dismissed, or the call threw, so we never show a button that does nothing.</li>
<li><strong>The error path points to the manual steps</strong> instead of failing silently. The status text renders in a <code>role="status"</code> element, so screen readers announce it.</li>
</ol>
<p>The native button only renders when <code>deferred</code> is set:</p>
<pre><code class="language-jsx">{deferred &amp;&amp; (
  &lt;button className="add-device-install" type="button" onClick={installNow}&gt;
    Add app to this device
  &lt;/button&gt;
)}
</code></pre>
<h2>Step 4: the manual steps are the real feature</h2>
<p>Collapsed by default, the section is one toggle: <strong>"Add app icon or set home page"</strong>, with <code>aria-expanded</code> and <code>aria-controls</code> pointing at the panel. Opened, it shows a four-card grid:</p>
<table>
<thead>
<tr>
<th>Card</th>
<th>What it says (paraphrased)</th>
</tr>
</thead>
<tbody><tr>
<td>iPhone or iPad</td>
<td>In Safari: Share, then Add to Home Screen, then Add</td>
</tr>
<tr>
<td>Android</td>
<td>In Chrome: three-dot menu, then Add to Home screen or Install app</td>
</tr>
<tr>
<td>Desktop app icon</td>
<td>Chrome or Edge: browser menu, look for Install or Apps. Mac Safari: File, then Add to Dock</td>
</tr>
<tr>
<td>Browser home page</td>
<td>Settings, Home page or On startup, paste the site address</td>
</tr>
</tbody></table>
<p>The "browser home page" card is the one people don't expect. Some people won't install anything but are happy to have the plan open when the browser starts. The address sits in a read-only <code>&lt;input&gt;</code> that selects itself on focus, so it's easy to copy on any device:</p>
<pre><code class="language-jsx">&lt;input
  aria-label="Address for your browser home page"
  readOnly
  value="https://startquittingsmoking.com/"
  onFocus={(e) =&gt; e.currentTarget.select()}
/&gt;
</code></pre>
<p>Two notes go under the grid, and we think both are worth copying:</p>
<ul>
<li><em>"Menu names vary by browser. Your browser asks before adding anything. To remove it, delete the icon or change your home page back."</em></li>
<li><em>"Use the same device and browser for your saved plan. An app icon does not sync your records to other devices."</em></li>
</ul>
<p>The second one matters because of how the app stores data. Records live in localStorage, and an installed icon doesn't sync them anywhere. Saying that next to the install button avoids a nasty surprise later.</p>
<h2>Trade-offs we accepted</h2>
<ul>
<li><strong>No service worker yet</strong>, so no offline mode. The panel says outright that an internet connection is required. For a hackathon build we'd rather ship honest copy than a half-tested offline cache.</li>
<li><strong>Standalone detection hides the section entirely.</strong> If you launch from the icon, you'll never see the install UI again. That's what we want, but it means there's no in-app "uninstall" hint; the removal note lives in the panel shown before install.</li>
</ul>
<h2>Takeaways</h2>
<ol>
<li>Save <code>beforeinstallprompt</code>, call <code>prompt()</code> from your own button, and clear the event in <code>finally</code>.</li>
<li>Check <code>display-mode: standalone</code> <strong>and</strong> <code>navigator.standalone</code>, and hide install UI once installed.</li>
<li>Always ship manual, per-platform steps. The native prompt is a bonus, not the plan.</li>
<li>If your data is device-local, say so right next to the install button.</li>
</ol>
<p>You can try the <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-install">free 30-day taper calculator</a> without signing up, or open <a href="https://startquittingsmoking.com/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-install">the app</a> and look for "Add app icon or set home page". The full app has a 24-hour free trial, then a $9 one-time unlock. We built it, so we're biased, and we'd love feedback from other builders in the comments.</p>
]]></content:encoded></item><item><title><![CDATA[Dark Mode Without the Flash: One localStorage Key, One Inline Script, and a Custom DOM Event]]></title><description><![CDATA[We're the Start Quitting Smoking team, and we're building startquittingsmoking.com for the Ship or Die $100K hackathon. It's a small React app with a free…]]></description><link>https://startquittingsmoking.hashnode.dev/dark-mode-without-the-flash-one-localstorage-key-one-inline-script-and-a-custom-dom-event</link><guid isPermaLink="true">https://startquittingsmoking.hashnode.dev/dark-mode-without-the-flash-one-localstorage-key-one-inline-script-and-a-custom-dom-event</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[hackathon]]></category><category><![CDATA[Build In Public]]></category><dc:creator><![CDATA[Start Quitting Smoking]]></dc:creator><pubDate>Tue, 17 Nov 2026 06:26:20 GMT</pubDate><content:encoded><![CDATA[<p>We're the Start Quitting Smoking team, and we're building <a href="https://startquittingsmoking.com/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-darkmode">startquittingsmoking.com</a> for the Ship or Die $100K hackathon. It's a small React app with a free <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-darkmode">30-day taper calculator</a> and a localStorage-first tracker. Earlier posts in this series covered the <a href="https://startquittingsmoking.hashnode.dev/we-built-a-free-straight-line-taper-calculator-and-a-9-30-day-quit-app">build story</a>, rounding, the session scheduler, backend-free Undo, and keeping a cached timestamp honest. This one covers a smaller job that's easy to get wrong: <strong>a light/dark toggle that never flashes the wrong theme on load.</strong></p>
<p>Everything below matches what's in our production HTML and bundle. We renamed the minified identifiers so the code is readable.</p>
<h2>The rule: system preference by default, an explicit choice wins</h2>
<p>There are only three states:</p>
<ul>
<li>nothing saved: follow <code>prefers-color-scheme</code></li>
<li><code>"dark"</code> saved: dark</li>
<li><code>"light"</code> saved: light</li>
</ul>
<p>Any other value in storage, including garbage from an old version, counts as "nothing saved". Storage lives under one versioned key, <code>day-one-theme-v1</code>, so we can change the format later without parsing old values.</p>
<h2>Step 1: decide before the first paint (inline script in <code>&lt;head&gt;</code>)</h2>
<p>A React app only knows the theme once the bundle has downloaded and run. If you wait until then, a dark-mode user sees a white page for a moment. So the decision runs as a tiny synchronous script in <code>index.html</code>, before the module script:</p>
<pre><code class="language-html">&lt;script&gt;
  (function () {
    var dark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    try {
      var saved = localStorage.getItem('day-one-theme-v1');
      if (saved === 'dark' || saved === 'light') dark = saved === 'dark';
    } catch (_) {}
    document.documentElement.classList.toggle('dark', dark);
    document.documentElement.style.colorScheme = dark ? 'dark' : 'light';
  })();
&lt;/script&gt;
</code></pre>
<p>Three details matter:</p>
<ol>
<li><strong><code>try/catch</code> around storage.</strong> <code>localStorage</code> can throw (privacy modes, blocked storage). If it does, we fall back to the system preference instead of crashing the page.</li>
<li><strong><code>color-scheme</code> as well as the class.</strong> The <code>.dark</code> class drives our CSS variables. <code>color-scheme</code> tells the browser to render scrollbars, form controls and the default canvas in the matching mode, so even native widgets don't flash.</li>
<li><strong>ES5 syntax.</strong> It runs unbundled, so we keep it plain <code>var</code> and <code>function</code>.</li>
</ol>
<h2>Step 2: the bundle applies the same rule again</h2>
<p>The bundle repeats the same logic once before <code>createRoot</code>:</p>
<pre><code class="language-js">const THEME_KEY = "day-one-theme-v1";

function applyTheme(dark) {
  document.documentElement.classList.toggle("dark", dark);
  document.documentElement.style.colorScheme = dark ? "dark" : "light";
  window.dispatchEvent(new Event("day-one-theme-change"));
}

function initTheme() {
  let dark = window.matchMedia("(prefers-color-scheme: dark)").matches;
  try {
    const saved = localStorage.getItem(THEME_KEY);
    if (saved === "dark" || saved === "light") dark = saved === "dark";
  } catch {}
  applyTheme(dark);
}

initTheme();
createRoot(document.getElementById("root")).render(&lt;App /&gt;);
</code></pre>
<p>Doing it twice looks redundant, but it's cheap, and the bundle doesn't depend on the HTML template staying in sync. If someone edits <code>index.html</code> and drops the inline script, the worst case is a brief flash, not the wrong theme.</p>
<h2>Step 3: the DOM is the source of truth, and an event keeps components in sync</h2>
<p>We don't keep the theme in React context. The <code>dark</code> class on <code>&lt;html&gt;</code> <em>is</em> the state. Components that need to know read it once, then listen for a custom event:</p>
<pre><code class="language-js">function useIsDark() {
  const [dark, setDark] = useState(
    () =&gt; document.documentElement.classList.contains("dark")
  );
  useEffect(() =&gt; {
    const sync = () =&gt; setDark(document.documentElement.classList.contains("dark"));
    window.addEventListener("day-one-theme-change", sync);
    return () =&gt; window.removeEventListener("day-one-theme-change", sync);
  }, []);
  return dark;
}
</code></pre>
<p>The toggle button needs it for its label. Our auth provider wrapper needs it too: the hosted sign-in components take an <code>appearance</code> object, so we memoize two palettes (light and dark hex values) keyed on that boolean. Switching the theme reskins the sign-in UI without touching our own CSS, and without passing a provider through the tree.</p>
<h2>Step 4: the toggle saves, applies, and is undoable</h2>
<pre><code class="language-js">function setTheme(dark) {
  try {
    localStorage.setItem(THEME_KEY, dark ? "dark" : "light");
    setError("");
  } catch {
    setError("Theme changed, but this device could not save your preference.");
  }
  applyTheme(dark);
}

function onToggle() {
  const wasDark = document.documentElement.classList.contains("dark");
  setTheme(!wasDark);
  pushAction("Change color mode", () =&gt; setTheme(wasDark)); // app-wide Undo
}
</code></pre>
<ul>
<li><strong>The theme still changes if saving fails.</strong> The user gets what they clicked, plus an honest note that it won't persist. Same "tell the truth about storage" rule as the rest of the app.</li>
<li><strong>It plugs into the app-wide Undo stack</strong> from an earlier post, so even a theme change can be undone like any other action.</li>
<li><strong>The button label says what will happen next</strong> ("Switch to light mode"), via both <code>aria-label</code> and <code>title</code>.</li>
</ul>
<h2>A trade-off we accepted</h2>
<p>The OS preference is only read at load. We don't subscribe to <code>matchMedia(...).addEventListener("change")</code>, so if someone flips their OS theme mid-session with no saved choice, the app updates on the next load. For a tracker people open a few times a day, that's fine. If you want live following, add a listener that runs only when nothing is saved.</p>
<h2>Takeaways</h2>
<ol>
<li>Decide the theme in a synchronous inline <code>&lt;head&gt;</code> script; set both the class and <code>color-scheme</code>.</li>
<li>Wrap every storage read and write in <code>try/catch</code>; fall back to the system preference.</li>
<li>Treat the <code>&lt;html&gt;</code> class as the single source of truth and broadcast changes with one custom event.</li>
<li>Version your storage key.</li>
</ol>
<p>You can try the <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-darkmode">free 30-day taper calculator</a> without signing up. The full app has a 24-hour free trial, then a $9 one-time unlock. We built it, so we're obviously biased, and we'd love feedback from other builders in the comments.</p>
]]></content:encoded></item><item><title><![CDATA[Edit and Delete Without Lying: Keeping a Cached "Last At" Timestamp Honest in localStorage]]></title><description><![CDATA[We're the Start Quitting Smoking team, and we're building startquittingsmoking.com for the Ship or Die $100K hackathon. Earlier posts covered the rounding…]]></description><link>https://startquittingsmoking.hashnode.dev/edit-and-delete-without-lying-keeping-a-cached-last-at-timestamp-honest-in-localstorage</link><guid isPermaLink="true">https://startquittingsmoking.hashnode.dev/edit-and-delete-without-lying-keeping-a-cached-last-at-timestamp-honest-in-localstorage</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[hackathon]]></category><category><![CDATA[Build In Public]]></category><dc:creator><![CDATA[Start Quitting Smoking]]></dc:creator><pubDate>Tue, 17 Nov 2026 05:24:07 GMT</pubDate><content:encoded><![CDATA[<p>We're the Start Quitting Smoking team, and we're building <a href="https://startquittingsmoking.com/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-editdelete">startquittingsmoking.com</a> for the Ship or Die $100K hackathon. Earlier posts covered the rounding rule behind our free <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-editdelete">30-day taper calculator</a>, the scheduler that spaces sessions across a day, and a backend-free Undo. This one is about a small bug class that shows up the moment you let users <strong>edit or delete</strong> time-stamped log entries.</p>
<h2>The setup: a log plus a cached "last at"</h2>
<p>Each habit log in the app is stored in two localStorage keys:</p>
<ul>
<li>a JSON array of entries: <code>{ id, at, label }</code>, where <code>at</code> is a millisecond timestamp</li>
<li>a separate number: the time of the most recent entry ("last at"), which the UI reads constantly for things like "time since last"</li>
</ul>
<p>Caching "last at" in its own key keeps reads cheap and simple. The cost is that it is <em>derived</em> data, and derived data goes stale the moment someone deletes or back-dates the entry it came from.</p>
<p>The names below are ours for this post; the logic matches what's in the production bundle.</p>
<h2>Reading the log defensively</h2>
<p>Old data from earlier versions didn't always have an <code>id</code>. Rather than migrating storage, the reader synthesises a stable id and drops anything malformed:</p>
<pre><code class="language-js">function readLog(logKey) {
  try {
    const raw = localStorage.getItem(logKey);
    if (!raw) return [];
    const parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) return [];
    return parsed
      .map((entry, index) =&gt; ({ entry, index }))
      .filter(({ entry }) =&gt; typeof entry?.at === "number" &amp;&amp; typeof entry?.label === "string")
      .map(({ entry, index }) =&gt; ({
        id: typeof entry.id === "string" &amp;&amp; entry.id ? entry.id : `legacy-${entry.at}-${index}`,
        at: entry.at,
        label: entry.label,
      }));
  } catch {
    return [];
  }
}

// New entries get the timestamp plus 6 random base-36 chars.
const newId = at =&gt; `${at}-${Math.random().toString(36).slice(2, 8)}`;
</code></pre>
<p>Including the array index in the legacy id means two old entries with the same timestamp still get different ids, so "delete this one" deletes exactly one.</p>
<h2>Delete: only recompute when the cache pointed at the deleted entry</h2>
<pre><code class="language-js">function deleteEntry(logKey, lastKey, id) {
  const log = readLog(logKey);
  const target = log.find(e =&gt; e.id === id);
  if (!target) return { ok: false, message: "That entry could not be found. Nothing changed." };

  const cachedLast = readNumber(lastKey); // null if missing or not a finite number
  const remaining = log.filter(e =&gt; e.id !== id);

  let nextLast = "keep";
  if (cachedLast === null || cachedLast === target.at) {
    nextLast = remaining.length ? Math.max(...remaining.map(e =&gt; e.at)) : null;
  }
  return save(logKey, lastKey, remaining, nextLast)
    ? { ok: true, log: remaining, last: nextLast === "keep" ? cachedLast : nextLast }
    : { ok: false, message: "Could not save on this device. Nothing changed." };
}
</code></pre>
<p>Three outcomes are encoded in <code>nextLast</code>:</p>
<table>
<thead>
<tr>
<th><code>nextLast</code></th>
<th>Meaning</th>
<th>Storage effect</th>
</tr>
</thead>
<tbody><tr>
<td><code>"keep"</code></td>
<td>the cache didn't come from this entry</td>
<td>don't touch the last-at key</td>
</tr>
<tr>
<td>a number</td>
<td>recomputed max of what's left</td>
<td>overwrite the last-at key</td>
</tr>
<tr>
<td><code>null</code></td>
<td>the log is now empty</td>
<td><strong>remove</strong> the last-at key</td>
</tr>
</tbody></table>
<p>The <code>null</code> case matters: if you delete the only entry, the UI should say "nothing logged yet", not "last one was 3 hours ago".</p>
<p>Why "keep" instead of always recomputing? The cached value isn't guaranteed to be one of the entries in this array, so blindly replacing it with <code>max(remaining)</code> could move it backwards for no reason. We only touch it when we know it was derived from the entry being removed, or when it's missing.</p>
<h2>Edit: three cases</h2>
<p>Editing is trickier because the entry can move forwards <em>or</em> backwards in time.</p>
<pre><code class="language-js">function editEntry(logKey, lastKey, id, patch) {
  const log = readLog(logKey);
  const target = log.find(e =&gt; e.id === id);
  if (!target) return { ok: false, message: "That entry could not be found. Nothing changed." };

  const cachedLast = readNumber(lastKey);
  const updated = log.map(e =&gt; (e.id === id ? { ...e, at: patch.at, label: patch.label ?? e.label } : e));
  const newestInLog = Math.max(...updated.map(e =&gt; e.at));

  let nextLast = "keep";
  if (cachedLast === null || cachedLast === target.at) {
    nextLast = newestInLog;          // cache came from this entry: recompute
  } else if (patch.at &gt; cachedLast) {
    nextLast = patch.at;             // edited entry is now the newest thing we know about
  }
  return save(logKey, lastKey, updated, nextLast)
    ? { ok: true, log: updated, last: nextLast === "keep" ? cachedLast : nextLast }
    : { ok: false, message: "Could not save on this device. Nothing changed." };
}
</code></pre>
<ul>
<li>Back-dating the newest entry: the cache equalled <code>target.at</code>, so it's recomputed from the whole log and correctly falls back to the next-newest entry.</li>
<li>Moving an older entry <em>later than</em> the cache: the cache moves forward to the edited time.</li>
<li>Anything else: leave it alone.</li>
</ul>
<p><code>save()</code> is the two-key write with manual rollback from our Undo post: write both keys, and if either throws (quota, private mode), restore both previous raw values so the log and its cache never disagree.</p>
<h2>Validate before you write</h2>
<p>The edit form rejects bad input before any of this runs, with plain-language messages:</p>
<pre><code class="language-js">if (!value || !Number.isFinite(t)) return "Enter a valid date and time.";
if (t &gt; Date.now())                 return "That time is in the future. Choose now or earlier.";
if (labelEditable &amp;&amp; !label)        return "Enter what you did.";
if (labelEditable &amp;&amp; label.length &gt; 40) return "Keep it under 40 letters.";
if (t === entry.at &amp;&amp; (!labelEditable || label === entry.label)) return closeWithoutSaving();
</code></pre>
<p>The last line is easy to forget: an "edit" that changes nothing shouldn't write to storage, and with our Undo stack it shouldn't create an undo entry either.</p>
<h2>Takeaways</h2>
<ol>
<li>If you cache a derived value next to the data, every mutation needs a rule for that cache, not just the add path.</li>
<li>Use a sentinel like <code>"keep"</code> to separate "don't touch" from "set to null/remove".</li>
<li>Synthesize ids for legacy rows on read instead of migrating storage.</li>
<li>Every failure path returns "Nothing changed." and that's only true because the write is transactional.</li>
</ol>
<p>You can try the <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-editdelete">free 30-day taper calculator</a> without signing up. The full app has a 24-hour free trial, then a $9 one-time unlock. We built it, so we're obviously biased, and we'd love feedback from other builders in the comments.</p>
]]></content:encoded></item><item><title><![CDATA[Undo Without a Backend: Snapshotting localStorage Keys in a React App]]></title><description><![CDATA[We're the Start Quitting Smoking team, and we're building startquittingsmoking.com for the Ship or Die $100K hackathon. Earlier posts covered the rounding…]]></description><link>https://startquittingsmoking.hashnode.dev/undo-without-a-backend-snapshotting-localstorage-keys-in-a-react-app</link><guid isPermaLink="true">https://startquittingsmoking.hashnode.dev/undo-without-a-backend-snapshotting-localstorage-keys-in-a-react-app</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[hackathon]]></category><category><![CDATA[Build In Public]]></category><dc:creator><![CDATA[Start Quitting Smoking]]></dc:creator><pubDate>Tue, 17 Nov 2026 04:19:07 GMT</pubDate><content:encoded><![CDATA[<p>We're the Start Quitting Smoking team, and we're building <a href="https://startquittingsmoking.com/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-undo">startquittingsmoking.com</a> for the Ship or Die $100K hackathon. Earlier posts covered the rounding rule (<code>Math.ceil</code>) and the little scheduler behind our free <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-undo">30-day taper calculator</a>. This one is about something less visible: a global <strong>Undo</strong> that works even though the app has no server-side database.</p>
<p>Everything a user enters (the plan they picked, daily logs, settings) lives in <code>localStorage</code> on their own device. That's good for privacy and means there's no sign-up wall, but it also means there's no server history to roll back to. If someone deletes a log entry by accident, the app itself has to be able to put it back.</p>
<p>Below is a readable rewrite of the pattern we shipped. The names are ours for this post; the logic matches the production bundle.</p>
<h2>Idea: undo = "the values these keys had before"</h2>
<p>Instead of modelling every action as a command with an inverse, we record the <em>previous raw string values</em> of the localStorage keys an action touches. Undo writes those strings back.</p>
<pre><code class="language-js">// Read the current raw values for a set of keys (null = key absent).
function snapshot(keys) {
  try {
    return Object.fromEntries(keys.map(k =&gt; [k, localStorage.getItem(k)]));
  } catch {
    return null; // storage unavailable (private mode, blocked, etc.)
  }
}

function changed(before, after) {
  return after ? Object.keys(before).some(k =&gt; before[k] !== after[k]) : false;
}

function applySnapshot(snap) {
  for (const [k, v] of Object.entries(snap)) {
    v === null ? localStorage.removeItem(k) : localStorage.setItem(k, v);
  }
}
</code></pre>
<p>Storing <code>null</code> for "this key didn't exist" matters: undoing the very first write has to <em>remove</em> the key, not set it to an empty string.</p>
<h2>Recording an action</h2>
<p>Every mutating action goes through one helper. It snapshots the keys, runs the change, and only pushes an undo entry if something actually changed. No-op clicks don't pollute the stack.</p>
<pre><code class="language-js">function track(label, keys, mutate) {
  const before = snapshot(keys);
  mutate();
  if (before &amp;&amp; changed(before, snapshot(keys))) {
    push({ kind: "storage", label, before });
  }
}

// push() keeps only the most recent 40 entries
setStack(s =&gt; [...s, { ...entry, id: nextId++ }].slice(-40));
</code></pre>
<p>Each entry carries a human label ("Switch smoking plan", "Mark habit as quit"), so the status line can say "Done: Switch smoking plan." and later "Undone: Switch smoking plan."</p>
<h2>Undo that can fail safely</h2>
<p><code>localStorage.setItem</code> can throw (quota, blocked storage). If undo writes three keys and the second one throws, you've made things worse. So the restore takes a snapshot of the current state first and tries to roll back to it if anything goes wrong, reporting one of three outcomes:</p>
<pre><code class="language-js">function restore(before) {
  const current = snapshot(Object.keys(before));
  if (!current) return "failed";
  try {
    applySnapshot(before);
    return "ok";
  } catch {
    try {
      applySnapshot(current); // put things back the way they were
      return "failed";        // nothing changed
    } catch {
      return "partial";       // tell the user to check this section
    }
  }
}
</code></pre>
<p>The UI uses that result directly: "failed" shows <em>"Could not undo â€¦ nothing changed"</em> and keeps the entry on the stack; "partial" shows a warning to check that section; only "ok" removes the entry.</p>
<h2>Form fields for free, via data attributes</h2>
<p>Wrapping every <code>onChange</code> in <code>track()</code> would be tedious, so form inputs opt in declaratively:</p>
<pre><code class="language-html">&lt;input data-undo-keys="some-storage-key" data-undo-label="Edit daily target" /&gt;
</code></pre>
<p>One provider at the root listens in the <strong>capture</strong> phase at the document level:</p>
<pre><code class="language-js">// focusin: remember what the keys held when the field got focus
document.addEventListener("focusin", e =&gt; {
  const keys = undoKeys(e.target);
  if (keys.length) baseline.set(e.target, snapshot(keys));
}, true);

// change: after a short 80 ms debounce, compare and record
document.addEventListener("change", e =&gt; {
  const keys = undoKeys(e.target);
  const before = baseline.get(e.target);
  if (!keys.length || !before) return;
  clearTimeout(pending.get(e.target)?.timer);
  const commit = () =&gt; {
    const after = snapshot(keys);
    if (changed(before, after)) push({ kind: "storage", label: e.target.dataset.undoLabel ?? "Edit", before });
    if (after) baseline.set(e.target, after);
  };
  pending.set(e.target, { timer: setTimeout(commit, 80), commit });
}, true);
</code></pre>
<p>The debounce gives the component's own <code>onChange</code> time to write storage before we compare. Before an undo runs, any pending commits are flushed immediately, so the latest edit is on the stack before we pop it. Baselines live in a <code>WeakMap</code> keyed by the element, so unmounted inputs don't leak.</p>
<p>After a restore, the provider bumps a <code>{ revision, keys }</code> value in context. Components that read those keys re-read storage when the revision changes, which keeps React state in sync with what undo just wrote.</p>
<h2>Two keys, one write</h2>
<p>Some data spans two keys: e.g. a log array plus a "last entry at" timestamp. Writing them one after another risks a half-saved state, so they're written with a tiny manual transaction:</p>
<pre><code class="language-js">function writePair(logKey, lastKey, log, last) {
  let oldLog, oldLast;
  try { oldLog = localStorage.getItem(logKey); oldLast = localStorage.getItem(lastKey); }
  catch { return false; }
  try {
    localStorage.setItem(logKey, JSON.stringify(log));
    if (last === null) localStorage.removeItem(lastKey);
    else if (last !== "keep") localStorage.setItem(lastKey, String(last));
    return true;
  } catch {
    try {
      oldLog === null ? localStorage.removeItem(logKey) : localStorage.setItem(logKey, oldLog);
      oldLast === null ? localStorage.removeItem(lastKey) : localStorage.setItem(lastKey, oldLast);
    } catch {}
    return false;
  }
}
</code></pre>
<p>Callers turn <code>false</code> into a plain-language message ("Could not save on this device. Nothing changed.") instead of silently diverging.</p>
<h2>Why this approach</h2>
<ul>
<li><strong>Generic.</strong> Any feature that writes storage gets undo by listing its keys. No per-action inverse logic.</li>
<li><strong>Honest errors.</strong> Every storage failure path ends in a message that says whether anything changed.</li>
<li><strong>Cheap.</strong> Snapshots are just the raw strings for a handful of keys; 40 entries is tiny.</li>
</ul>
<p>The trade-off: it only covers state in localStorage. Anything outside it (like a non-storage UI action) needs an explicit <code>revert</code> callback, which the stack also supports as a second entry kind.</p>
<h2>Try it</h2>
<p>The <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-undo">30-day taper calculator</a> is free and needs no sign-up. The full app (<a href="https://startquittingsmoking.com/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-undo">startquittingsmoking.com</a>) has a 24-hour free trial and then costs $9 one-time. We built it for the Ship or Die hackathon, and we'd love feedback on the undo pattern from anyone who has solved this differently.</p>
]]></content:encoded></item><item><title><![CDATA[Spreading N Events Across a Day: The 8-Line Scheduler Behind Our Taper Calculator]]></title><description><![CDATA[We're the Start Quitting Smoking team, and we're building startquittingsmoking.com for the Ship or Die $100K hackathon. In an earlier post we wrote about…]]></description><link>https://startquittingsmoking.hashnode.dev/spreading-n-events-across-a-day-the-8-line-scheduler-behind-our-taper-calculator</link><guid isPermaLink="true">https://startquittingsmoking.hashnode.dev/spreading-n-events-across-a-day-the-8-line-scheduler-behind-our-taper-calculator</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[hackathon]]></category><category><![CDATA[Build In Public]]></category><dc:creator><![CDATA[Start Quitting Smoking]]></dc:creator><pubDate>Tue, 17 Nov 2026 03:26:20 GMT</pubDate><content:encoded><![CDATA[<p>We're the Start Quitting Smoking team, and we're building <a href="https://startquittingsmoking.com/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-scheduler">startquittingsmoking.com</a> for the Ship or Die $100K hackathon. In an earlier post we wrote about the one-line rounding decision (<code>Math.ceil</code>) that turns a straight-line target into whole-number daily limits. This post is about the next problem: once you know a day has, say, 9 slots, <strong>when</strong> should they go?</p>
<p>The free <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-scheduler">30-day taper calculator</a> shows a "suggested times" column for every day. It's a planning aid, not a protocol, but it has to behave sensibly for any count from 1 to 100 and for three different modes (cigarettes, vaping, weed). Here's how we did it.</p>
<h2>The requirements</h2>
<ol>
<li>Fixed end of day. The last slot of every day lands at 8:00 p.m.</li>
<li>A start that drifts later. On day 1 the first slot is 8:00 a.m. As the month goes on, the first slot moves later, so the day gradually has a longer gap before it begins.</li>
<li>The drift depends on the mode. We used a 90-minute drift for cigarettes, 180 for vaping, and 360 for weed.</li>
<li>Even spacing between first and last.</li>
<li>Human-readable times rounded to 5 minutes. Nobody wants "9:23 a.m."</li>
<li>Edge cases: a day with 1 slot gets only the first time, and a day with 0 slots gets nothing.</li>
</ol>
<h2>Work in minutes since midnight</h2>
<p>Everything is easier as integers: 8:00 a.m. is <code>480</code>, 8:00 p.m. is <code>1200</code>. Formatting happens once, at the end.</p>
<pre><code class="language-js">const DAY_START = 480;   // 8:00 a.m.
const DAY_END   = 1200;  // 8:00 p.m.
const DRIFT = { cigarettes: 90, vaping: 180, weed: 360 };

function suggestedTimes(mode, dayIndex, count) {        // dayIndex: 0..29
  const first = DAY_START + Math.round((dayIndex / 29) * DRIFT[mode]);
  const step  = count &gt; 1 ? (DAY_END - first) / (count - 1) : 0;
  return Array.from({ length: count }, (_, i) =&gt;
    Math.round((first + i * step) / 5) * 5              // snap to 5 minutes
  );
}
</code></pre>
<p>That's the whole scheduler. <code>dayIndex / 29</code> runs from 0 on day 1 to 1 on day 30, the same normalization the target line uses, so the drift and the taper move in lockstep.</p>
<h2>Why snap at the end, not the step</h2>
<p>The tempting shortcut is to round <code>step</code> to 5 minutes first and then add it repeatedly. That accumulates error: with 9 slots, a step of 88.875 minutes rounds to 90, and after 8 steps the last slot lands around 8:10 p.m. instead of 8:00. Snapping each computed time independently keeps the last slot pinned exactly where requirement 1 says it should be, because <code>first + (count - 1) * step === DAY_END</code> before rounding, and 1200 is already a multiple of 5.</p>
<p>Here's day 4 for a starting amount of 10 (limit 9, <code>first = 480 + round(3/29 × 90) = 489</code>):</p>
<pre><code>raw:     489  577.9  666.8  755.6  844.5  933.4  1022.2  1111.1  1200
snapped: 490  580    665    755    845    935    1020    1110    1200
display: 8:10 a.m. · 9:40 a.m. · 11:05 a.m. · 12:35 p.m. · 2:05 p.m. · 3:35 p.m. · 5 p.m. · 6:30 p.m. · 8 p.m.
</code></pre>
<p>That last line matches what the live calculator shows for day 4.</p>
<h2>The edge cases fall out for free</h2>
<ul>
<li><code>count === 1</code>: <code>step</code> is 0, so the only slot is <code>first</code>. For cigarettes starting at 10, days 28 and 29 show a single 9:25 a.m. slot.</li>
<li><code>count === 0</code> (day 30, always): <code>Array.from({ length: 0 })</code> returns <code>[]</code>, so the planned-zero day has no times at all. No special-casing in the UI.</li>
<li>High counts: at 100 per day the step is about 7 minutes, so neighboring slots can snap to the same 5-minute mark. We accepted that; the column is a rough guide, and the daily limit is the number that matters.</li>
</ul>
<h2>Formatting</h2>
<p>The display format drops <code>:00</code> ("8 a.m.", "12 p.m.") and uses <code>a.m.</code>/<code>p.m.</code>, which reads better in a printed table than <code>08:00</code>:</p>
<pre><code class="language-js">function fmt(m) {
  const h24 = Math.floor(m / 60), min = m % 60;
  const h = h24 % 12 || 12, ampm = h24 &lt; 12 ? "a.m." : "p.m.";
  return min ? `${h}:${String(min).padStart(2, "0")} ${ampm}` : `${h} ${ampm}`;
}
</code></pre>
<h2>What we'd do differently</h2>
<ul>
<li>Let people set their own waking window. 8 a.m. to 8 p.m. is a reasonable default, but a night-shift worker needs a different pair of constants.</li>
<li>Show the drift. Right now the start moving later is implicit; a small note like "first time moves about 3 minutes later each day" (for cigarettes) would make the column easier to trust.</li>
</ul>
<h2>Try it</h2>
<p>The <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-scheduler">calculator</a> is free and needs no signup: pick a mode, type a number, and the table (limits plus suggested times) updates as you type. We built it as a planning tool; it isn't medical advice. If you're building something for Ship or Die too, we'd love to hear how you handled your own "make the numbers feel human" problems in the comments.</p>
]]></content:encoded></item><item><title><![CDATA[Floor, round, or ceil? The one-line rounding decision behind our 30-day taper calculator]]></title><description><![CDATA[We're the Start Quitting Smoking team. We built Start Quitting Smoking, a 30-day taper web app for cigarettes, vaping, and weed, as our entry in the Ship…]]></description><link>https://startquittingsmoking.hashnode.dev/floor-round-or-ceil-the-one-line-rounding-decision-behind-our-30-day-taper-calculator</link><guid isPermaLink="true">https://startquittingsmoking.hashnode.dev/floor-round-or-ceil-the-one-line-rounding-decision-behind-our-30-day-taper-calculator</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Mathematics]]></category><category><![CDATA[hackathon]]></category><category><![CDATA[Build In Public]]></category><dc:creator><![CDATA[Start Quitting Smoking]]></dc:creator><pubDate>Tue, 17 Nov 2026 02:25:30 GMT</pubDate><content:encoded><![CDATA[<p>We're the Start Quitting Smoking team. We built <a href="https://startquittingsmoking.com/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-rounding">Start Quitting Smoking</a>, a 30-day taper web app for cigarettes, vaping, and weed, as our entry in the Ship or Die $100K Hackathon. This post is about one small engineering decision in the <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-rounding">free 30-day taper calculator</a>: how to turn a smooth straight line into whole numbers a person can actually count.</p>
<p>It's a technical note, not health advice. The calculator itself says it is a planning tool, not medical advice, and that its day-30 zero is a goal, not a guaranteed quit.</p>
<h2>The straight line</h2>
<p>The schedule starts at your usual daily amount on day 1 and reaches 0 on day 30. That's 29 equal steps, so for day <em>n</em>:</p>
<pre><code class="language-js">const exact = start * (30 - n) / 29;
</code></pre>
<p>With a start of 10, day 2 is 9.6552, day 3 is 9.3103, and so on. The calculator shows that "exact target" column on purpose, next to the daily limit, so you can see where the whole number came from.</p>
<p>The problem: nobody smokes 9.6552 cigarettes. Counts are integers, so we need a rounding rule, and the choice changes the shape of the whole month.</p>
<h2>Three candidates</h2>
<p>Here is the same line rounded three ways for a starting amount of 10 (days 1 to 30):</p>
<pre><code>floor: 10,9,9,8,8,8,7,7,7,6,6,6,5,5,5,4,4,4,3,3,3,2,2,2,1,1,1,0,0,0
round: 10,10,9,9,9,8,8,8,7,7,7,6,6,6,5,5,4,4,4,3,3,3,2,2,2,1,1,1,0,0
ceil:  10,10,10,9,9,9,8,8,8,7,7,7,6,6,6,5,5,5,4,4,4,3,3,3,2,2,2,1,1,0
</code></pre>
<p>At 10 the differences look small. They get big when the starting number is small. Here is a start of 3:</p>
<pre><code>floor: 3,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0
round: 3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0
ceil:  3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,0
</code></pre>
<ul>
<li><strong>floor</strong> drops a third of the starting amount overnight on day 2 and hits 0 on day 21. Ten of the "30 days" are just zeros, so it isn't really a 30-day plan.</li>
<li><strong>round</strong> is fairer, but still reaches 0 on day 26 for a start of 3.</li>
<li><strong>ceil</strong> keeps every step in equal-length blocks (ten days at 3, ten at 2, nine at 1) and reaches 0 exactly on day 30.</li>
</ul>
<p>We went with ceil. The calculator states it plainly: "Daily limits round up to a whole number, so some days stay the same." The visible number never drops ahead of the line, the first zero always lands on day 30, and the plan length a person chose is the plan length they get.</p>
<p>The tradeoff is that some days repeat. Day 2 and day 3 both show 10 even though the exact target keeps falling. We think showing the exact target next to the limit makes that understandable rather than confusing.</p>
<h2>A floating-point footnote</h2>
<p><code>Math.ceil</code> is unforgiving: if a value that should be exactly 2 comes out as 2.0000000000000004, you get 3. We guard against that with a tiny epsilon:</p>
<pre><code class="language-js">const limit = Math.max(0, Math.ceil(start * (30 - n) / 29 - 1e-9));
</code></pre>
<p>To check, we ran the formula for every day with starting amounts of 1, 2, 3, 7, 10, 20, 29 and 100. None hit the problem with this exact expression (multiply first, then divide), but the guard is cheap and it protects against a later refactor like <code>start * ((30 - n) / 29)</code> that changes the order of operations. The <code>Math.max(0, â€¦)</code> just avoids printing <code>-0</code> on day 30.</p>
<p>Running that line for a start of 10 reproduces the live calculator's default table exactly: 10, 10, 10, 9 â€¦ 1, 1, 0, with exact targets 10.0000, 9.6552, 9.3103 and so on.</p>
<h2>Spacing the day's sessions</h2>
<p>The calculator also suggests times. From the live default table for 10 cigarettes, you can see the pattern: day 1 starts at 8 a.m., the first slot moves a little later as the plan goes on (8:05 on day 2, 8:20 on day 7, 9:25 on day 28), sessions are spread out so the last lands around 8 p.m., and times round to five minutes. Vaping and weed plans push the first slot later than cigarette plans. Day 30 has no times.</p>
<p>Here is a simplified sketch of that idea. It is <strong>not</strong> the production code, and its output lands within five minutes of the live table, not on it:</p>
<pre><code class="language-js">const round5 = (m) =&gt; Math.round(m / 5) * 5;

function suggestedTimes(limit, n, maxDelayMin = 90) {
  if (limit &lt;= 0) return [];
  const first = 8 * 60 + round5((maxDelayMin * (n - 1)) / 29);
  const last = 20 * 60;
  if (limit === 1) return [first];
  return Array.from({ length: limit }, (_, i) =&gt;
    round5(first + ((last - first) * i) / (limit - 1))
  );
}
</code></pre>
<p>The point of the times isn't precision. Fewer sessions spread over the same waking window means a longer gap between them as the plan goes on, and a concrete time is easier to plan around than "fewer than yesterday." The calculator tells people to adjust times to fit their day.</p>
<h2>Counting sessions, not chemistry</h2>
<p>For vaping and weed, the same math counts sessions instead of cigarettes. That keeps the code identical across all three, but it's a deliberate limit: the site's safety notice says session counts don't measure nicotine, THC, potency, puff size, or time spent, and it tells people not to compensate with bigger sessions or deeper puffs. A count is something the app can track honestly, so that's all it tracks.</p>
<h2>Why this matters for a hackathon product</h2>
<p>Ship or Die judges entries on verified profit, so it would be tempting to put all the effort into the paid side. We kept the calculator free with no signup because the schedule only works if people trust it, and a rounding rule that quietly ends the plan on day 21 wouldn't earn that trust. The paid part is a tracker (a 24-hour free trial, then $9 once, not a subscription) for people who want to check off sessions on their phone. Habit records stay in the browser's local storage.</p>
<p>If you build anything that turns a continuous curve into daily integer targets (habit apps, training plans, savings goals), it's worth printing all three rounding rules for a small input before you pick one. Ours took one line to change and decided how the whole month feels.</p>
<p>Try the <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot-rounding">30-day taper calculator</a> with a small starting number and look at the "exact target" column next to the daily limit.</p>
<p><em>Disclosure: we, the Start Quitting Smoking team, built the app and the calculator described here. It is a planning tool, not medical advice. Ask a doctor or pharmacist about quitting support.</em></p>
]]></content:encoded></item><item><title><![CDATA[We Built a Free Straight-Line Taper Calculator and a $9 30-Day Quit App]]></title><description><![CDATA[A product breakdown of Start Quitting Smoking, a cigarettes, vapes, and weed tracker shipped for the Ship or Die $100K Hackathon]]></description><link>https://startquittingsmoking.hashnode.dev/we-built-a-free-straight-line-taper-calculator-and-a-9-30-day-quit-app</link><guid isPermaLink="true">https://startquittingsmoking.hashnode.dev/we-built-a-free-straight-line-taper-calculator-and-a-9-30-day-quit-app</guid><category><![CDATA[Web Development]]></category><category><![CDATA[showdev]]></category><category><![CDATA[indiehackers]]></category><category><![CDATA[buildinpublic]]></category><category><![CDATA[side project]]></category><dc:creator><![CDATA[Start Quitting Smoking]]></dc:creator><pubDate>Mon, 16 Nov 2026 23:11:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6afb8c1f15bf2ad6f811f0b1/40079d11-6b75-4de2-9be6-c7f412229d3a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We're the Start Quitting Smoking team, and we built <a href="https://startquittingsmoking.com/?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot">Start Quitting Smoking</a>, a 30-day taper web app for cigarettes, vaping, and weed, as a project for the Ship or Die $100K Hackathon. This post is a product and technical look at what is actually live on the site: the pricing, the math, and the constraints. It is not a personal quitting story, and it is not a claim that the app will make anyone quit.</p>
<h2>What the hackathon is, and what shipped</h2>
<p>The $100K Hackathon is a 30-day, free-to-enter challenge organized by Higgsfield, Marc Lou, and Jack Friks. It started on Monday, November 16, 2026, and runs until December 16. Entrants start a new digital product business and are judged on verified profit, not revenue, with manual review as part of the process.</p>
<p>The live product is a web app that starts at a person's usual daily amount, follows smaller daily limits, and plans a limit of 0 on day 30. People can check off each session. It covers cigarettes, vaping, and weed. The homepage states that this is a goal, not a guaranteed quit, and that the app is a tracking tool, not a medical taper prescription. It is for adults 18 and older.</p>
<h2>A free calculator in front of the paid tracker</h2>
<p>The first product decision visible on the site is a split between a free planning tool and a paid tracker.</p>
<p>The <a href="https://startquittingsmoking.com/30-day-taper-calculator?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=content-bot">30-day taper calculator</a> is labeled as a free planning tool with no signup. You choose cigarettes, vaping, or weed, enter a usual daily amount as a whole number from 1 to 100, and get a day-by-day table: daily limit, exact target, and suggested times. You can print the table or copy it. No account is required.</p>
<p>The calculator shows the default generated plan. The in-app plan is editable. If someone wants to check off sessions on a device, the app offers a 24-hour free trial, then a one-time purchase. The schedule is useful on its own; the tracker is optional.</p>
<h2>The schedule is a straight-line taper, rounded up</h2>
<p>The calculator and the tracker use the same math. The exact target falls in a straight line from the starting amount on day 1 to zero on day 30 — equal reductions across the 29 intervals between those two days.</p>
<p>For day <em>n</em> (with day 1 as the start):</p>
<p><code>exact target = starting amount × (30 − n) ÷ 29</code></p>
<p>Daily limits then round up to a whole cigarette or session. Some days show the same whole number even though the exact target keeps falling — a feature of rounding, so a small starting amount is not snapped to zero on day two.</p>
<p>A default example on the calculator, starting at 10 cigarettes a day, shows a limit of 10 on day 1, 6 on day 15, 1 on day 29, and 0 on day 30. The exact target on day 2 is already 9.6552, but the daily limit stays at 10 until the rounded-up value drops. Every generated plan, including a start of 20, ends at a planned 0 on day 30.</p>
<p>Suggested times are part of the same default plan. Day 1 starts at 8 a.m. On later days with planned use, the first suggested session moves later, with a longer delay for vaping and weed than for cigarettes. Remaining sessions are spaced through the day and end around 8 p.m. Times round to five minutes. Day 30 has no planned sessions. These are suggestions, not medical instructions.</p>
<p>For vaping and weed, the same method counts sessions rather than cigarettes.</p>
<h2>One tracker for cigarettes, vaping, and weed</h2>
<p>The app does not treat these as three separate products. The homepage and calculator both offer a simple choice: cigarettes, vaping, or weed. The daily UI shows "I'm cutting back on" those options, a day-n-of-30 header, today's limit, how many have been used and how many are left, and a checkbox for each suggested time.</p>
<p>That choice has tradeoffs. Session counts do not measure nicotine, THC, potency, puff size, or time spent using — the medical and safety notice says so explicitly. A session is a countable unit, which keeps the math simple and means the app is not dosing anything. The same notice tells people not to compensate for a lower count with stronger products, longer sessions, or deeper puffs.</p>
<h2>A 24-hour trial, then $9 once — not a subscription</h2>
<p>Pricing is stated in the homepage FAQ and in the terms: the first 24 hours are free; continued access costs US $9 once, not a subscription; the free day does not charge automatically. You have to choose to purchase. Checkout is hosted by Whop, and any taxes or fees are shown at checkout before payment.</p>
<p>The terms also spell out what the purchase is not: it is not a guarantee of lifetime service, a health outcome, or a particular quit date. Sign in with the same app account to restore paid access. When a trial ends, saved device records are not deleted, and a download of those records plus the public legal notices remains available without payment.</p>
<p>For a hackathon judged on profit, a one-time $9 price is a simple offer. It also avoids an auto-converting trial: the site is explicit that the free day does not bill on its own.</p>
<h2>Habit records stay in the browser</h2>
<p>Habit records — plans, use logs, timestamps, notes, daily exercises, settings, and preferences — stay in the browser's local storage on that device. The app does not send those entries to an app database or sync them across devices. Signing in links paid access, not habit history. Clearing browser storage can remove the records, and there is no backup service.</p>
<p>Sign-in is handled by Clerk. A necessary, HTTP-only cookie identifies the 24-hour trial, and signing in is linked to the original trial start so that creating an account does not restart the clock. The site is hosted on Replit.</p>
<p>That keeps habit history off the operator's servers, at the cost of no cross-device sync and no operator-side restore if someone clears storage or changes devices. The privacy notice is direct: the operator cannot retrieve habit records that exist only in the browser.</p>
<h2>What the live daily UI actually does</h2>
<p>On a plan day, the app shows today's limit ("10 cigarettes or fewer today" in the default example), session checkboxes at the suggested times, a control to mark "I stayed under my limit today," and a way to change today. A "See all 30 days" view tracks completed days. There is a "Change my plan" action, which matches the claim that plans are editable, and an "I need help now" entry point. The chrome also offers adding an app icon or setting a home page, so the tracker can live on a phone as a web app.</p>
<p>The homepage includes short motivational copy and links to NHS guidance, noting that health advice is different for cigarettes and vaping. The medical and safety page repeats the limits: this is a tracker, not a treatment; it does not diagnose, treat, cure, or prevent disease; zero on day 30 is a planned goal, not a promise.</p>
<h2>What we are not claiming</h2>
<p>We are not clinicians, and this is not a medically prescribed taper. The straight-line schedule is a mathematical planning default. Public-health guidance the site points to often still presents stopping on a set date as the usual approach, and treats cutting down as a possible way to get started if someone plans well and follows through. Anyone with medical questions should talk to a doctor, a pharmacist, or a quitline.</p>
<p>If you want to see the math without an account, use the free calculator. The tracker is on the same site.</p>
]]></content:encoded></item></channel></rss>