Tomorrowish

Today for Habitica: source code

Version 1.0.0 · widget id dev.tomorrowish.todayhabitica · every file in the package, as shipped.

Habitica asks that every third-party tool other people use has code anyone can review. This page is that review copy: the full contents of the Today for Habitica widget for the CORSAIR XENEON EDGE. It talks only to habitica.com, sends the X-Client header Habitica requires, waits at least 30 seconds between reads, and never runs your day's cron for you. Questions: hello@tomorrowish.dev. All widgets.

Today for Habitica is not created by, affiliated with, or endorsed by Habitica or HabitRPG, Inc.

Files

Binary files in the package (fonts under the SIL Open Font License, licence text included above where shipped):

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>tr('Today for Habitica')</title>
  <link rel="icon" type="image/svg+xml" href="resources/icon.svg" />
  <meta name="x-icue-widget-preview" content="resources/preview.png" />

  <meta name="x-icue-property" content="userId" data-label="tr('Habitica User ID')" data-type="textfield" data-default="''" />
  <meta name="x-icue-property" content="apiToken" data-label="tr('Habitica API Token')" data-type="textfield" data-default="''" />
  <meta name="x-icue-property" content="showHabits" data-label="tr('Show Habits')" data-type="switch" data-default="true" />
  <meta name="x-icue-property" content="showTodos" data-label="tr('Show To Dos Due Today')" data-type="switch" data-default="true" />
  <meta name="x-icue-property" content="showStats" data-label="tr('Show Health, Experience and Mana')" data-type="switch" data-default="true" />
  <meta name="x-icue-property" content="tapActions" data-label="tr('Tap to Check Off and Score')" data-type="switch" data-default="true" />
  <meta name="x-icue-property" content="refreshMinutes" data-label="tr('Refresh Every')" data-type="slider" data-default="5" data-min="2" data-max="30" data-step="1" data-unit-label="' min'" />

  <meta name="x-icue-property" content="textColor" data-label="tr('Text Color')" data-type="color" data-default="'#eef3f1'" />
  <meta name="x-icue-property" content="accentColor" data-label="tr('Accent Color')" data-type="color" data-default="'#2ec4a6'" />
  <meta name="x-icue-property" content="backgroundColor" data-label="tr('Background Color')" data-type="color" data-default="'#121718'" />
  <meta name="x-icue-property" content="transparency" data-label="tr('Background Transparency')" data-type="slider" data-default="100" data-min="0" data-max="100" data-step="1" data-unit-label="'%'" />

  <script id="x-icue-groups" type="application/json">
  [
    { "title": "tr('Today for Habitica')", "properties": ["userId", "apiToken", "showHabits", "showTodos", "showStats", "tapActions", "refreshMinutes"], "info": "tr('Copy your User ID and API Token from Habitica Settings, Site Data (API). They stay in iCUE and are only sent to habitica.com. Not created by, affiliated with, or endorsed by Habitica or HabitRPG, Inc.')" },
    { "title": "tr('Widget Personalization')", "properties": ["textColor", "accentColor", "backgroundColor", "transparency"] }
  ]
  </script>

  <link rel="stylesheet" type="text/css" href="styles/board.css" />
</head>
<body>
  <div class="hb" id="root" data-state="loading" data-layout="stack">
    <div class="hb-ground" aria-hidden="true"></div>
    <div class="hb-frame">
      <section class="hb-hero" id="hero">
        <div class="hb-day"><span id="date"></span><span class="hb-rest" id="rest"></span></div>
        <div class="hb-tally"><b id="tally">&#160;</b><span id="tally-of"></span></div>
        <div class="hb-stats" id="stats"></div>
      </section>
      <div class="hb-lists" id="lists">
        <section class="hb-sec" id="sec-dailies"><h2>Dailies <em id="d-note"></em><span class="hb-more"></span></h2><ul id="dailies" aria-label="Dailies"></ul></section>
        <section class="hb-sec" id="sec-habits"><h2>Habits<span class="hb-more"></span></h2><ul id="habits" aria-label="Habits"></ul></section>
        <section class="hb-sec" id="sec-todos"><h2>To Do's due<span class="hb-more"></span></h2><ul id="todos" aria-label="To Do's due"></ul></section>
      </div>
    </div>
    <div class="hb-foot" id="foot"></div>
    <div class="hb-card" id="card" hidden="hidden"><b id="card-title"></b><span id="card-body"></span></div>
  </div>

  <script src="scripts/ledger.js"></script>
  <script src="scripts/board.js"></script>
  <script>
    icueEvents = {
      'onICUEInitialized': habiticaReady,
      'onDataUpdated': habiticaSettings
    };
    HabitBoard.boot();
  </script>
</body>
</html>

manifest.json

{
  "author": "Tomorrowish",
  "id": "dev.tomorrowish.todayhabitica",
  "name": "Today for Habitica",
  "description": "Your Habitica day on your XENEON EDGE: due Dailies with streaks, Habits with plus and minus, To Do's due today and your health, experience and mana, with tap to check off.",
  "version": "1.0.0",
  "preview_icon": "resources/icon.svg",
  "min_app_version": "5.47",
  "min_framework_version": "1.0.0",
  "os": [
    { "platform": "windows" }
  ],
  "supported_devices": [
    { "type": "dashboard_lcd" }
  ],
  "interactive": true,
  "permissions": [
    { "type": "url", "domain": "habitica.com", "port": 443 }
  ]
}

resources/fonts/OFL-Nunito.txt

Copyright 2014 The Nunito Project Authors (https://github.com/googlefonts/nunito)

This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL


-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded, 
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

resources/icon.svg

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">
  <rect width="256" height="256" rx="56" fill="#121718"/>
  <rect x="34" y="70" width="104" height="104" rx="26" fill="#2ec4a6"/>
  <path d="M60 122 l22 22 l38 -44" fill="none" stroke="#121718" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"/>
  <circle cx="186" cy="122" r="44" fill="none" stroke="#4cc38a" stroke-width="12"/>
  <path d="M186 100 v44 M164 122 h44" stroke="#4cc38a" stroke-width="12" stroke-linecap="round"/>
  <rect x="34" y="196" width="188" height="14" rx="7" fill="#eef3f1" opacity="0.18"/>
  <rect x="34" y="196" width="120" height="14" rx="7" fill="#f2b33d"/>
</svg>

scripts/board.js

/* Today for Habitica: the board. Draws the day sheet, handles taps (every score waits 4 s so a second tap
 * cancels it), and paces reads the way Habitica's API guidelines ask. */
var HabitBoard = (function () {
  'use strict';

  var HOLD_MS = 4000;          // the undo window before a score is sent
  var SPACING_MS = 30000;      // guideline: 30 s between automatic calls
  var TAP_GAP_MS = 1200;       // taps the player made are sent one at a time
  var raw = { user: null, tasks: null };
  var st = {
    sheet: null, syncedAt: 0, error: null, hold: 0, stopped: false,
    waiting: {},   // id -> { dir, timer } for Dailies and To Do's
    habitWait: {}, // id -> { up, down, timer }
    outbox: [], sending: false, flash: null, flashUntil: 0, rollover: false
  };
  var cycleTimer = null, tasksTimer = null, started = false, lastKey = null;

  // ---- settings ---------------------------------------------------------------------------------

  function read(name, fallback) {
    var v;
    if (Object.prototype.hasOwnProperty.call(window, name)) v = window[name];
    if (v === undefined) {
      try { v = Function('return typeof ' + name + ' !== "undefined" ? ' + name + ' : undefined')(); } catch (e) {}
    }
    return v === undefined || v === null ? fallback : v;
  }
  function on(name, fallback) { var v = read(name, fallback); return v === true || v === 'true' || v === 1; }
  function creds() { return { user: String(read('userId', '')).trim(), key: String(read('apiToken', '')).trim() }; }
  function hasCreds() { var c = creds(); return !!(c.user && c.key); }
  function everyMs() { var m = Number(read('refreshMinutes', 5)); return Math.max(2, isFinite(m) ? m : 5) * 60000; }
  function tapsOn() { return on('tapActions', true); }

  function paint() {
    var r = document.documentElement.style;
    r.setProperty('--ink', String(read('textColor', '#eef3f1')));
    r.setProperty('--glow', String(read('accentColor', '#2ec4a6')));
    r.setProperty('--ground', String(read('backgroundColor', '#121718')));
    var t = Number(read('transparency', 100));
    r.setProperty('--ground-alpha', String(isFinite(t) ? Math.min(100, Math.max(0, t)) / 100 : 1));
  }

  // ---- tiny DOM helpers -----------------------------------------------------------------------------

  function $(id) { return document.getElementById(id); }
  function make(tag, cls, text) { var n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n; }
  function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }

  function layoutFor(w, h) {
    if (h <= 450) return 'compact';
    if (w >= 2400 && h < 1000) return 'cols3';
    if (w >= 1600 && h < 1000) return 'cols2';
    return 'stack';
  }

  function ago(ms) { var m = Math.round(ms / 60000); return m < 1 ? 'just now' : m < 60 ? m + 'm ago' : Math.round(m / 60) + 'h ago'; }
  function clock(ms) { var d = new Date(ms), h = d.getHours(), m = d.getMinutes(); return (h % 12 || 12) + ':' + (m < 10 ? '0' : '') + m + (h < 12 ? ' AM' : ' PM'); }

  // ---- drawing -----------------------------------------------------------------------------------------

  function card(title, body) {
    $('card').hidden = !title;
    $('card-title').textContent = title || '';
    $('card-body').textContent = body || '';
  }

  function bar(label, value, max, cls) {
    var row = make('div', 'hb-bar ' + cls);
    row.appendChild(make('span', 'hb-bar-name', label));
    var track = make('span', 'hb-track');
    var fill = make('span', 'hb-fill');
    fill.style.width = (max > 0 ? Math.max(0, Math.min(100, value / max * 100)) : 0) + '%';
    track.appendChild(fill);
    row.appendChild(track);
    row.appendChild(make('span', 'hb-bar-num', max > 0 ? Math.floor(value) + ' / ' + Math.round(max) : String(Math.floor(value))));
    return row;
  }

  function drawHero(s) {
    var day = new Date(s.day + 'T12:00:00Z');
    $('date').textContent = day.toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric', timeZone: 'UTC' });
    $('rest').textContent = s.hero.resting ? 'Resting in the Inn' : '';
    $('tally').textContent = String(s.doneCount);
    $('tally-of').textContent = s.dueCount ? 'of ' + s.dueCount + ' Dailies done' : 'Dailies due today';
    var stats = $('stats');
    clear(stats);
    stats.hidden = !on('showStats', true);
    if (stats.hidden) return;
    var h = s.hero;
    stats.appendChild(bar('HP', h.hp, h.maxHp, 'is-hp'));
    stats.appendChild(bar('XP', h.exp, h.toNext, 'is-xp'));
    if (h.showMp) stats.appendChild(bar('MP', h.mp, h.maxMp, 'is-mp'));
    stats.appendChild(make('div', 'hb-level', 'Level ' + h.lvl + (h.cls ? ' ' + h.cls : '') + '  ·  ' + Math.floor(h.gp) + ' gold'));
  }

  function tickRow(item) {
    var w = st.waiting[item.id];
    var showDone = w ? w.dir === 'up' : item.done;
    var li = make('li', 'hb-row t-' + item.tint + (showDone ? ' is-done' : '') + (w ? ' is-waiting' : '') + (item.late ? ' is-late' : ''));
    var b = make('button', 'hb-tick');
    b.type = 'button';
    b.disabled = !tapsOn() || locked();
    b.setAttribute('aria-label', (showDone ? 'Uncheck ' : 'Check ') + item.text);
    b.addEventListener('click', function () { tapTick(item); });
    li.appendChild(b);
    var body = make('div', 'hb-body');
    body.appendChild(make('span', 'hb-text', item.text));
    var meta = make('span', 'hb-meta');
    if (w) meta.appendChild(make('span', 'hb-undo', w.dir === 'up' ? 'Tap again to undo' : 'Unchecking, tap again to keep'));
    else {
      if (item.kind === 'daily' && item.streak > 0) meta.appendChild(make('span', 'hb-streak', item.streak + ' day streak'));
      if (item.checks) meta.appendChild(make('span', 'hb-checks', 'checklist ' + item.checks.done + '/' + item.checks.total));
      if (item.kind === 'todo') meta.appendChild(make('span', 'hb-due' + (item.late ? ' is-late' : ''), item.late ? 'overdue' : 'due today'));
    }
    if (meta.firstChild) body.appendChild(meta);
    li.appendChild(body);
    // open Dailies and To Do's show their checklist lines underneath (not in the small slots)
    var showItems = item.items && item.items.length && !showDone && $('root').dataset.layout !== 'compact';
    if (!showItems) return li;
    var frag = document.createDocumentFragment();
    frag.appendChild(li);
    item.items.forEach(function (c) { frag.appendChild(itemRow(item, c)); });
    return frag;
  }

  function itemKey(task, c) { return 'c:' + task.id + ':' + c.id; }

  function itemRow(task, c) {
    var key = itemKey(task, c);
    var w = st.waiting[key];
    var done = w ? !c.done : c.done;
    var li = make('li', 'hb-row hb-sub t-' + task.tint + (done ? ' is-done' : '') + (w ? ' is-waiting' : ''));
    var b = make('button', 'hb-tick');
    b.type = 'button';
    b.disabled = !tapsOn() || locked();
    b.setAttribute('aria-label', (done ? 'Uncheck ' : 'Check ') + c.text);
    b.addEventListener('click', function () { tapItem(task, c); });
    li.appendChild(b);
    var body = make('div', 'hb-body');
    body.appendChild(make('span', 'hb-text', c.text));
    if (w) { var m = make('span', 'hb-meta'); m.appendChild(make('span', 'hb-undo', 'Tap again to undo')); body.appendChild(m); }
    li.appendChild(body);
    return li;
  }

  function habitRow(item) {
    var w = st.habitWait[item.id];
    var li = make('li', 'hb-row hb-habit t-' + item.tint + (w ? ' is-waiting' : ''));
    var lock = !tapsOn() || locked();
    function btn(dir, glyph) {
      var b = make('button', 'hb-step is-' + dir, glyph);
      b.type = 'button';
      b.disabled = lock;
      b.setAttribute('aria-label', (dir === 'up' ? 'Plus ' : 'Minus ') + item.text);
      b.addEventListener('click', function () { tapHabit(item, dir); });
      return b;
    }
    if (item.down) li.appendChild(btn('down', '−'));
    else li.appendChild(make('span', 'hb-step-gap'));
    var body = make('div', 'hb-body');
    body.appendChild(make('span', 'hb-text', item.text));
    var meta = make('span', 'hb-meta');
    if (w) {
      var parts = [];
      if (w.up) parts.push('+' + w.up);
      if (w.down) parts.push('−' + w.down);
      meta.appendChild(make('span', 'hb-undo', parts.join(' ') + ' in a moment, tap here to undo'));
      body.addEventListener('click', function () { undoHabit(item.id); });
    } else {
      var span = { daily: 'today', weekly: 'this week', monthly: 'this month' }[item.every] || 'today';
      var bits = [];
      if (item.up) bits.push('+' + item.plus);
      if (item.down) bits.push('−' + item.minus);
      if (bits.length) meta.appendChild(make('span', 'hb-count', bits.join('  ') + ' ' + span));
    }
    if (meta.firstChild) body.appendChild(meta);
    li.appendChild(body);
    if (item.up) li.appendChild(btn('up', '+'));
    return li;
  }

  function fill(listId, items, render, emptyText) {
    var ul = $(listId);
    clear(ul);
    items.forEach(function (it) { ul.appendChild(render(it)); });
    if (!items.length && emptyText) ul.appendChild(make('li', 'hb-empty', emptyText));
  }

  // Rows are added one at a time until the next one would not fit: every section first gets one row,
  // then Dailies fill up, then Habits, then To Do's. Hidden rows are counted in the section header
  // ("+3 more"); text never shrinks. A section that cannot show a single row is hidden whole.
  function fit() {
    var lists = $('lists');
    var secs = ['sec-dailies', 'sec-habits', 'sec-todos'].map($).filter(function (x) { return !x.hidden && getComputedStyle(x).display !== 'none'; });
    var rowsOf = function (sec) { return Array.prototype.slice.call(sec.querySelector('ul').children); };
    var over = function () {
      if (lists.scrollHeight > lists.clientHeight + 1) return true;
      return secs.some(function (x) {
        if (x.dataset.off === '1') return false;
        var ul = x.querySelector('ul');
        return ul.scrollHeight > ul.clientHeight + 1 || x.scrollHeight > x.clientHeight + 1;
      });
    };
    secs.forEach(function (x) { x.dataset.off = ''; rowsOf(x).forEach(function (n) { n.classList.add('is-cut'); }); });
    var tryAdd = function (sec) {
      var next = rowsOf(sec).filter(function (n) { return n.classList.contains('is-cut'); })[0];
      if (!next) return false;
      next.classList.remove('is-cut');
      if (over()) { next.classList.add('is-cut'); return false; }
      return true;
    };
    secs.forEach(function (x) {
      if (rowsOf(x).length && !tryAdd(x) && x.id !== 'sec-dailies') x.dataset.off = '1';
    });
    secs.forEach(function (x) { if (x.dataset.off !== '1') while (tryAdd(x)) {} });
    secs.forEach(function (x) {
      var hidden = rowsOf(x).filter(function (n) { return n.classList.contains('is-cut') && !n.classList.contains('hb-sub'); }).length;
      var tag = x.querySelector('h2 .hb-more');
      tag.textContent = hidden && x.dataset.off !== '1' ? '+' + hidden + ' more' : '';
    });
  }

  function locked() { return !st.sheet || st.sheet.needsCron || st.rollover || Date.now() < st.hold; }

  function draw() {
    paint();
    var root = $('root');
    var now = Date.now();
    root.dataset.layout = layoutFor(innerWidth, innerHeight);
    var s = st.sheet;
    if (s && !st.rollover && Ledger.sheetDay(now, s.tz, s.dayStart) !== s.day) { st.rollover = true; kick(1500); }

    if (!hasCreds()) {
      root.dataset.state = 'setup';
      card('Connect Habitica', 'In Habitica open Settings, then Site Data (API), and copy your User ID and API Token into this widget\'s settings in iCUE.');
    } else if (st.error && st.error.status === 401) {
      root.dataset.state = 'badcreds';
      card('Habitica did not accept those', 'Check the User ID and API Token in the widget settings. Both are on Habitica\'s Settings, Site Data (API) page.');
    } else if (!s && st.error) {
      root.dataset.state = 'error';
      if (st.error.status === 429) card('Habitica asked us to wait', 'Too many requests right now. Trying again at ' + clock(st.hold) + '.');
      else card('Habitica unreachable', 'No connection to habitica.com. Trying again in a couple of minutes.');
    } else if (!s) {
      root.dataset.state = 'loading';
      card('Opening your day', 'Reading your Dailies from Habitica...');
    } else if (s.needsCron) {
      root.dataset.state = 'cron';
      card('A new day is waiting', 'Open Habitica to check off anything you did yesterday and start today. Taps here stay paused until then, so nothing counts toward the wrong day.');
    } else {
      root.dataset.state = 'content';
      card('');
    }

    if (root.dataset.state === 'content') {
      drawHero(s);
      var showHabits = on('showHabits', true) && s.habits.length > 0;
      var showTodos = on('showTodos', true) && s.todos.length > 0;
      var dNote = $('d-note');
      dNote.textContent = s.dueCount && s.doneCount === s.dueCount ? 'all done' : (s.notDue ? s.notDue + ' not due today' : '');
      dNote.className = s.dueCount && s.doneCount === s.dueCount ? 'is-clear' : '';
      fill('dailies', s.dailies, tickRow, s.dueCount ? null : 'No Dailies due today.');
      fill('habits', showHabits ? s.habits : [], habitRow);
      fill('todos', showTodos ? s.todos : [], tickRow);
      ['sec-dailies', 'sec-habits', 'sec-todos'].forEach(function (id) { $(id).dataset.off = ''; });
      $('sec-habits').hidden = !showHabits;
      $('sec-todos').hidden = !showTodos;
      $('lists').className = 'hb-lists' + (showHabits ? '' : ' no-habits') + (showTodos ? '' : ' no-todos');
      fit();
    }

    var foot = $('foot');
    var text = '', warn = false;
    if (st.flash && now < st.flashUntil) { text = st.flash; warn = true; }
    else if (s && root.dataset.state === 'content') {
      if (now < st.hold) { text = 'Habitica asked us to slow down, next read ' + clock(st.hold); warn = true; }
      else if (st.error && st.error.offline && now - st.syncedAt > 5 * 60000) { text = 'Offline, last synced ' + ago(now - st.syncedAt); warn = true; }
      else if (st.rollover) text = 'New Habitica day, checking...';
      else text = 'Synced ' + ago(now - st.syncedAt);
    }
    foot.textContent = text;
    foot.className = 'hb-foot' + (warn ? ' is-warn' : '');
  }

  function say(text) { st.flash = text; st.flashUntil = Date.now() + 8000; draw(); setTimeout(draw, 8100); }

  // ---- taps --------------------------------------------------------------------------------------------

  function tapTick(item) {
    if (!tapsOn() || locked()) return;
    var w = st.waiting[item.id];
    if (w) { clearTimeout(w.timer); delete st.waiting[item.id]; draw(); return; }
    var dir = item.done ? 'down' : 'up';
    st.waiting[item.id] = { dir: dir, timer: setTimeout(function () { delete st.waiting[item.id]; send(item.id, dir); }, HOLD_MS) };
    draw();
  }

  // Habits wait too: sending the opposite direction would not undo a + (a − costs health), so the
  // undo is simply not sending. Several taps inside the window add up.
  function tapHabit(item, dir) {
    if (!tapsOn() || locked()) return;
    var w = st.habitWait[item.id] || (st.habitWait[item.id] = { up: 0, down: 0, timer: null });
    w[dir]++;
    clearTimeout(w.timer);
    w.timer = setTimeout(function () {
      var n = st.habitWait[item.id]; delete st.habitWait[item.id];
      for (var i = 0; i < n.up; i++) send(item.id, 'up');
      for (var j = 0; j < n.down; j++) send(item.id, 'down');
      draw();
    }, HOLD_MS);
    draw();
  }

  function tapItem(task, c) {
    if (!tapsOn() || locked()) return;
    var key = itemKey(task, c);
    var w = st.waiting[key];
    if (w) { clearTimeout(w.timer); delete st.waiting[key]; draw(); return; }
    st.waiting[key] = { dir: 'item', timer: setTimeout(function () { delete st.waiting[key]; st.outbox.push({ id: task.id, item: c.id }); pump(); }, HOLD_MS) };
    draw();
  }

  function undoHabit(id) {
    var w = st.habitWait[id];
    if (!w) return;
    clearTimeout(w.timer);
    delete st.habitWait[id];
    draw();
  }

  function send(id, dir) { st.outbox.push({ id: id, dir: dir }); pump(); }

  function pump() {
    if (st.sending || !st.outbox.length) return;
    if (locked()) {
      st.outbox = [];
      say(Date.now() < st.hold ? 'Habitica asked us to slow down, that tap was not sent.' : 'Habitica\'s day changed, that tap was not sent.');
      return;
    }
    var job = st.outbox.shift();
    st.sending = true;
    var call = job.item ? Ledger.scoreItem(creds(), job.id, job.item) : Ledger.score(creds(), job.id, job.dir);
    call.then(function (res) {
      if (job.item) Ledger.applyCheck(raw, job.id, job.item, res.data);
      else Ledger.applyScore(raw, job.id, job.dir, res.data);
      if (res.hold) st.hold = Math.max(st.hold, res.hold);
      rebuild();
    }, function (e) {
      if (e.status === 401) { st.error = e; st.stopped = true; }
      else if (e.status === 429) { st.hold = Math.max(st.hold, e.hold || Date.now() + 60000); st.outbox = []; say('Habitica is busy, that tap was not sent. Try again in a minute.'); }
      else if (e.offline) { st.outbox = []; say('No connection, that tap was not sent.'); }
      else say('Habitica did not take that tap (' + e.status + ').');
    }).then(function () {
      st.sending = false;
      draw();
      if (st.outbox.length) setTimeout(pump, TAP_GAP_MS);
    });
  }

  // ---- reads: /user first (needsCron, stats), then /tasks/user -------------------------------------------

  function rebuild() {
    if (raw.user && raw.tasks) st.sheet = Ledger.sheet(raw.user, raw.tasks, Date.now());
    draw();
  }

  function later(ms) { clearTimeout(cycleTimer); cycleTimer = setTimeout(function () { cycle(false); }, Math.max(0, ms)); }
  // a read the player caused (start, settings change, day rollover) only waits a moment between its two calls
  function kick(ms) { clearTimeout(cycleTimer); cycleTimer = setTimeout(function () { cycle(true); }, ms || 0); }

  function failed(e) {
    st.error = e;
    if (e.status === 401) { st.stopped = true; raw.user = raw.tasks = null; st.sheet = null; draw(); return; } // no point calling again
    if (e.status === 429 || e.hold) st.hold = Math.max(st.hold, e.hold || Date.now() + 60000);
    draw();
    later(Math.max(st.hold - Date.now(), 2 * 60000));
  }

  function cycle(byPlayer) {
    clearTimeout(tasksTimer);
    if (!hasCreds()) { raw.user = raw.tasks = null; st.sheet = null; st.error = null; draw(); return; }
    if (st.stopped) { draw(); return; }
    var wait = st.hold - Date.now();
    if (wait > 0) { draw(); later(wait); return; }
    var c = creds();
    Ledger.readUser(c).then(function (u) {
      raw.user = u.data;
      if (u.hold) st.hold = Math.max(st.hold, u.hold);
      var gap = Math.max(byPlayer ? 1500 : SPACING_MS, st.hold - Date.now());
      if (raw.tasks) rebuild(); else draw();
      tasksTimer = setTimeout(function () {
        Ledger.readTasks(c).then(function (t) {
          raw.tasks = t.data;
          if (t.hold) st.hold = Math.max(st.hold, t.hold);
          st.error = null; st.rollover = false; st.syncedAt = Date.now();
          rebuild();
          later(Math.max(everyMs() - gap, SPACING_MS, st.hold - Date.now()));
        }, failed);
      }, gap);
    }, failed);
  }

  // ---- lifecycle ---------------------------------------------------------------------------------------------

  function keyOf() { var c = creds(); return c.user + '|' + c.key + '|' + read('refreshMinutes', 5); }

  function start() {
    if (started) { settingsChanged(); return; }
    started = true;
    lastKey = keyOf();
    raw._who = creds().user + creds().key;
    draw();
    window.addEventListener('resize', draw);
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(draw);
    setInterval(draw, 60000);
    kick(0);
  }

  function settingsChanged() {
    if (!started) { paint(); return; }
    var k = keyOf();
    var changed = k !== lastKey;
    lastKey = k;
    if (changed) {
      st.stopped = false; st.error = null;
      if (k.split('|')[0] + k.split('|')[1] !== (raw._who || '')) { raw.user = raw.tasks = null; st.sheet = null; }
      raw._who = k.split('|')[0] + k.split('|')[1];
      draw();
      kick(1500); // let typing settle
    } else draw();
  }

  var tries = 0;
  function boot() {
    if (typeof iCUE_initialized !== 'undefined' && iCUE_initialized) return start();
    if (tries++ < 15) return setTimeout(boot, 100);
    start();
  }

  return { boot: boot, start: start, settingsChanged: settingsChanged };
})();

function habiticaReady() { HabitBoard.start(); }
function habiticaSettings() { HabitBoard.settingsChanged(); }

scripts/ledger.js

/* Today for Habitica: the data side. Reads Habitica API v3 answers into one "day sheet" and sends scores.
 * No DOM here, so Node tests can load it. The user ID and API token only travel as request headers to
 * habitica.com; nothing is logged, cached or written to storage. */
var Ledger = (function () {
  'use strict';

  var BASE = 'https://habitica.com/api/v3';
  // Habitica requires "<creator user id>-<tool name>" on every call (API Usage Guidelines, X-Client header).
  var X_CLIENT = 'bf231dca-c666-483f-a993-fac07ef000b8-TodayForHabitica';
  var TIMEOUT_MS = 15000;

  function two(n) { return (n < 10 ? '0' : '') + n; }
  function ymdUTC(d) { return d.getUTCFullYear() + '-' + two(d.getUTCMonth() + 1) + '-' + two(d.getUTCDate()); }

  // Habitica's day: the player's clock (preferences.timezoneOffset, minutes behind UTC like JS) minus the
  // custom day start hour. At 2 AM with a 4 AM day start it is still "yesterday".
  function sheetDay(nowMs, tzOffset, dayStart) {
    return ymdUTC(new Date(nowMs - (tzOffset || 0) * 60000 - (dayStart || 0) * 3600000));
  }

  // To Do due dates arrive as ISO strings. Clients that send a bare date get UTC midnight back
  // ("2026-11-10T00:00:00.000Z"), the web app sends the player's local midnight. Read both as a calendar day.
  function todoDay(value, tzOffset) {
    if (!value) return null;
    var d = new Date(value);
    if (isNaN(d.getTime())) return null;
    if (d.getUTCHours() === 0 && d.getUTCMinutes() === 0 && d.getUTCSeconds() === 0) return ymdUTC(d);
    return ymdUTC(new Date(d.getTime() - (tzOffset || 0) * 60000));
  }

  // Task "value" is how red or blue Habitica paints a task. Seven bands, our own names.
  function tint(value) {
    var v = Number(value) || 0;
    if (v < -20) return 'ember';
    if (v < -10) return 'rust';
    if (v < -1) return 'amber';
    if (v < 1) return 'sand';
    if (v < 5) return 'moss';
    if (v < 10) return 'sea';
    return 'deep';
  }

  // Task text is Markdown and may carry emoji shortcodes. Keep words, drop the markup.
  function plain(text) {
    return String(text || '')
      .replace(/!\[[^\]]*\]\([^)]*\)/g, '')
      .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
      .replace(/(\*\*|__)(.+?)\1/g, '$2')
      .replace(/(\*|_)(.+?)\1/g, '$2')
      .replace(/`([^`]+)`/g, '$1')
      .replace(/~~(.+?)~~/g, '$1')
      .replace(/^#+\s*/, '')
      .replace(/\s+/g, ' ')
      .trim();
  }

  function num(v, fallback) { var n = Number(v); return isFinite(n) ? n : fallback; }

  // Checklist lines under a Daily or To Do: the count for the meta line, and the lines themselves
  function checks(t) {
    var list = (t && t.checklist) || [];
    return list.length ? { done: list.filter(function (c) { return c && c.completed; }).length, total: list.length } : null;
  }
  function items(t) {
    return ((t && t.checklist) || []).filter(function (c) { return c && c.id; })
      .map(function (c) { return { id: c.id, text: plain(c.text), done: !!c.completed }; });
  }

  function hero(user) {
    var s = (user && user.stats) || {};
    var prefs = (user && user.preferences) || {};
    var flags = (user && user.flags) || {};
    var classOn = !!flags.classSelected && !prefs.disableClasses;
    var names = { warrior: 'Warrior', rogue: 'Rogue', wizard: 'Mage', healer: 'Healer' };
    return {
      name: (user && user.profile && user.profile.name) || '',
      lvl: num(s.lvl, 1),
      cls: classOn ? (names[s['class']] || '') : '',
      hp: num(s.hp, 0), maxHp: num(s.maxHealth, 50),
      exp: num(s.exp, 0), toNext: num(s.toNextLevel, 0),
      mp: num(s.mp, 0), maxMp: num(s.maxMP, 0), showMp: classOn,
      gp: num(s.gp, 0),
      resting: !!prefs.sleep
    };
  }

  /* user = GET /user data, tasks = GET /tasks/user data. Returns the sheet the board draws. */
  function sheet(user, tasks, nowMs) {
    var prefs = (user && user.preferences) || {};
    var tz = prefs.timezoneOffset != null ? num(prefs.timezoneOffset, 0) : new Date(nowMs).getTimezoneOffset();
    var dayStart = num(prefs.dayStart, 0);
    var today = sheetDay(nowMs, tz, dayStart);
    var dailies = [], habits = [], todos = [], notDue = 0;

    (tasks || []).forEach(function (t, i) {
      if (!t || !t.id) return;
      if (t.type === 'daily') {
        if (!t.isDue) { notDue++; return; }
        dailies.push({
          id: t.id, kind: 'daily', text: plain(t.text), done: !!t.completed, streak: num(t.streak, 0),
          checks: checks(t), items: items(t), tint: tint(t.value), at: i
        });
      } else if (t.type === 'habit') {
        habits.push({
          id: t.id, kind: 'habit', text: plain(t.text), up: !!t.up, down: !!t.down,
          plus: num(t.counterUp, 0), minus: num(t.counterDown, 0), every: t.frequency || 'daily', tint: tint(t.value), at: i
        });
      } else if (t.type === 'todo') {
        if (t.completed) return;
        var due = todoDay(t.date, tz);
        if (!due || due > today) return;
        todos.push({ id: t.id, kind: 'todo', text: plain(t.text), done: false, due: due, late: due < today, checks: checks(t), items: items(t), tint: tint(t.value), at: i });
      }
    });

    // still-open Dailies first in the player's own order, finished ones sink to the bottom
    dailies.sort(function (a, b) { return (a.done - b.done) || (a.at - b.at); });
    // overdue first, oldest due date first, then the player's own order
    todos.sort(function (a, b) { return (b.late - a.late) || (a.due < b.due ? -1 : a.due > b.due ? 1 : 0) || (a.at - b.at); });

    return {
      day: today, tz: tz, dayStart: dayStart,
      needsCron: !!(user && user.needsCron),
      hero: hero(user),
      dailies: dailies, habits: habits, todos: todos, notDue: notDue,
      doneCount: dailies.filter(function (d) { return d.done; }).length,
      dueCount: dailies.length
    };
  }

  // A score answer carries the player's new stats. Patch them, and the task itself, into the raw
  // answers we keep, so the next sheet (built before the next read) already shows the tap.
  function applyScore(raw, taskId, direction, data) {
    if (!raw) return raw;
    var st = data || {};
    var stats = raw.user && raw.user.stats;
    if (stats) {
      if (st.lvl != null && num(st.lvl, stats.lvl) !== stats.lvl) stats.toNextLevel = 0; // new level: next /user read brings the target
      ['hp', 'mp', 'exp', 'gp', 'lvl'].forEach(function (k) { if (st[k] != null) stats[k] = num(st[k], stats[k]); });
    }
    (raw.tasks || []).forEach(function (t) {
      if (!t || t.id !== taskId) return;
      if (t.type === 'daily') {
        t.completed = direction === 'up';
        t.streak = Math.max(0, num(t.streak, 0) + (direction === 'up' ? 1 : -1));
      } else if (t.type === 'habit') {
        if (direction === 'up') t.counterUp = num(t.counterUp, 0) + 1; else t.counterDown = num(t.counterDown, 0) + 1;
      } else if (t.type === 'todo') {
        t.completed = direction === 'up';
      }
    });
    return raw;
  }

  // A checklist score answer is the whole task. Take its checklist; without one, flip the line ourselves.
  function applyCheck(raw, taskId, itemId, data) {
    if (!raw) return raw;
    (raw.tasks || []).forEach(function (t) {
      if (!t || t.id !== taskId) return;
      if (data && data.checklist && data.checklist.length) { t.checklist = data.checklist; return; }
      (t.checklist || []).forEach(function (c) { if (c && c.id === itemId) c.completed = !c.completed; });
    });
    return raw;
  }

  // ---- pacing: Habitica's rate limit headers and 429 Retry-After --------------------------------

  // Returns the earliest time (ms) the next automatic call may go out, given one answer's headers.
  function holdUntil(status, header, nowMs) {
    var get = function (k) { var v = header(k); return v == null ? null : String(v); };
    if (status === 429) {
      var ra = num(get('Retry-After'), NaN);
      return nowMs + (isFinite(ra) && ra > 0 ? ra * 1000 : 60000);
    }
    var left = num(get('X-RateLimit-Remaining'), NaN);
    var reset = get('X-RateLimit-Reset');
    if (isFinite(left) && left <= 2 && reset) {
      var at = Date.parse(reset);
      if (isFinite(at) && at > nowMs) return at + 1000;
    }
    return 0;
  }

  // ---- network ------------------------------------------------------------------------------------

  var fetcher = function () { return fetch.apply(null, arguments); };

  function request(creds, method, path) {
    var ctl = typeof AbortController !== 'undefined' ? new AbortController() : null;
    var timer = ctl ? setTimeout(function () { ctl.abort(); }, TIMEOUT_MS) : null;
    return Promise.resolve(fetcher(BASE + path, {
      method: method,
      headers: { 'x-api-user': creds.user, 'x-api-key': creds.key, 'x-client': X_CLIENT },
      signal: ctl ? ctl.signal : undefined
    })).then(function (r) {
      var header = function (k) { return r.headers && r.headers.get ? r.headers.get(k) : null; };
      var hold = holdUntil(r.status, header, Date.now());
      return r.text().then(function (body) {
        var j = null;
        try { j = body ? JSON.parse(body) : null; } catch (e) { j = null; }
        if (!r.ok || !j || j.success === false) {
          var err = new Error('Habitica answered ' + r.status);
          err.status = r.status; err.code = j && j.error; err.hold = hold;
          throw err;
        }
        return { data: j.data, hold: hold };
      });
    }).then(function (v) { if (timer) clearTimeout(timer); return v; },
      function (e) { if (timer) clearTimeout(timer); if (!e.status) e.offline = true; throw e; });
  }

  function readUser(creds) { return request(creds, 'GET', '/user'); }
  function readTasks(creds) { return request(creds, 'GET', '/tasks/user'); }
  function score(creds, taskId, direction) {
    return request(creds, 'POST', '/tasks/' + encodeURIComponent(taskId) + '/score/' + (direction === 'down' ? 'down' : 'up'));
  }

  // Ticks or unticks one checklist line (Habitica toggles it; there is no direction).
  function scoreItem(creds, taskId, itemId) {
    return request(creds, 'POST', '/tasks/' + encodeURIComponent(taskId) + '/checklist/' + encodeURIComponent(itemId) + '/score');
  }

  function credsOk(user, key) {
    var uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
    return uuid.test(String(user || '').trim()) && uuid.test(String(key || '').trim());
  }

  return {
    X_CLIENT: X_CLIENT, BASE: BASE,
    sheet: sheet, applyScore: applyScore, applyCheck: applyCheck, scoreItem: scoreItem, sheetDay: sheetDay, todoDay: todoDay, tint: tint, plain: plain,
    holdUntil: holdUntil, readUser: readUser, readTasks: readTasks, score: score, credsOk: credsOk,
    _setFetch: function (f) { fetcher = f; }
  };
})();

if (typeof module !== 'undefined') module.exports = Ledger;

styles/board.css

@font-face { font-family: 'HB Nunito'; src: url('../resources/fonts/nunito.woff2') format('woff2'); font-weight: 400 800; font-display: block; }

:root {
  --ink: #eef3f1;
  --glow: #2ec4a6;
  --ground: #121718;
  --ground-alpha: 1;

  /* task colour by value, worst to best */
  --t-ember: #e5484d;
  --t-rust: #f2774b;
  --t-amber: #f5a524;
  --t-sand: #e3cf6a;
  --t-moss: #4cc38a;
  --t-sea: #3eb6d8;
  --t-deep: #5b8cff;

  --pad: 28px;
  --txt: 30px;
  --meta: 20px;
  --big: 92px;
  --tick: 46px;
  --line: color-mix(in srgb, var(--ink) 9%, transparent);
}

* { box-sizing: border-box; }
html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: transparent; }
body { color: var(--ink); font: 600 var(--txt)/1.22 'HB Nunito', 'Segoe UI', system-ui, sans-serif; -webkit-font-smoothing: antialiased; user-select: none; }
[hidden] { display: none !important; }

.hb { position: relative; width: 100%; height: 100%; overflow: hidden; }
.hb-ground { position: absolute; inset: 0; background: var(--ground); opacity: var(--ground-alpha); }
.hb-frame { position: absolute; inset: 0; display: flex; gap: 34px; padding: 26px 30px 52px; min-width: 0; min-height: 0; }
.hb:not([data-state="content"]) .hb-frame { visibility: hidden; }

/* ---- hero: the day, the tally, the bars ---- */
.hb-hero { display: flex; flex-direction: column; min-width: 0; min-height: 0; flex: 0 0 auto; }
.hb-day { display: flex; flex-wrap: wrap; gap: 4px 16px; font-size: var(--meta); font-weight: 800; letter-spacing: 0.1em; text-transform: uppercase; color: var(--glow); }
.hb-rest { color: var(--ink); opacity: 0.6; letter-spacing: 0.04em; text-transform: none; font-weight: 700; }
.hb-tally { display: flex; align-items: baseline; gap: 16px; margin-top: 8px; }
.hb-tally b { font-size: var(--big); font-weight: 800; line-height: 0.92; font-variant-numeric: tabular-nums; letter-spacing: -0.02em; }
.hb-tally span { font-size: 26px; font-weight: 700; opacity: 0.72; }
.hb-stats { display: flex; flex-direction: column; gap: 9px; min-width: 0; }
.hb-bar { display: grid; grid-template-columns: 44px minmax(0, 1fr) auto; align-items: center; gap: 12px; font-size: var(--meta); }
.hb-bar-name { font-weight: 800; opacity: 0.7; letter-spacing: 0.06em; }
.hb-track { height: 12px; border-radius: 6px; background: color-mix(in srgb, var(--ink) 12%, transparent); overflow: hidden; }
.hb-fill { display: block; height: 100%; border-radius: 6px; }
.is-hp .hb-fill { background: #ef5a5a; }
.is-xp .hb-fill { background: #f2b33d; }
.is-mp .hb-fill { background: #4f9cf9; }
.hb-bar-num { font-variant-numeric: tabular-nums; opacity: 0.75; min-width: 92px; text-align: right; }
.hb-level { font-size: var(--meta); font-weight: 700; opacity: 0.7; white-space: pre; }

/* ---- lists ---- */
.hb-lists { flex: 1 1 auto; min-width: 0; min-height: 0; overflow: hidden; }
.hb-sec { display: flex; flex-direction: column; min-width: 0; min-height: 0; overflow: hidden; }
.hb-sec[data-off="1"] { display: none; }
.hb-sec h2 { display: flex; align-items: baseline; white-space: nowrap; margin: 0 0 4px; font-size: var(--meta); font-weight: 800; letter-spacing: 0.12em; text-transform: uppercase; opacity: 0.6; flex: 0 0 auto; }
.hb-sec h2 em { font-style: normal; letter-spacing: 0.02em; text-transform: none; margin-left: 10px; opacity: 0.85; }
.hb-sec h2 em.is-clear { color: var(--glow); opacity: 1; }
.hb-sec ul { list-style: none; margin: 0; padding: 0; flex: 1 1 auto; min-height: 0; overflow: hidden; }

.hb-row { display: flex; align-items: center; gap: 16px; padding: 9px 0; border-bottom: 1px solid var(--line); min-width: 0; }
.hb-body { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; }
.hb-text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.hb-meta { display: flex; gap: 14px; font-size: var(--meta); font-weight: 600; opacity: 0.62; white-space: nowrap; overflow: hidden; }
.hb-undo { color: var(--glow); opacity: 1; font-weight: 800; }
.hb-row.is-waiting .hb-meta { opacity: 1; }
.hb-due.is-late { color: var(--t-rust); }

.hb-tick, .hb-step {
  flex: 0 0 auto; width: var(--tick); height: var(--tick); padding: 0; cursor: pointer; position: relative;
  border: 3px solid var(--tint, var(--t-sand)); background: color-mix(in srgb, var(--tint, var(--t-sand)) 16%, transparent); color: var(--ink);
}
.hb-tick { border-radius: 12px; }
.hb-step { border-radius: 50%; font: 800 34px/1 'HB Nunito', system-ui, sans-serif; display: flex; align-items: center; justify-content: center; }
.hb-tick:disabled, .hb-step:disabled { cursor: default; opacity: 0.55; }
.is-done .hb-tick { background: var(--tint, var(--t-sand)); }
.is-done .hb-tick::after {
  content: ''; position: absolute; left: 50%; top: 45%; width: 11px; height: 21px; transform: translate(-50%, -50%) rotate(45deg);
  border: solid var(--ground); border-width: 0 5px 5px 0;
}
.is-done .hb-text { opacity: 0.45; text-decoration: line-through; text-decoration-thickness: 2px; }
.is-waiting .hb-tick, .is-waiting .hb-step { outline: 4px solid var(--glow); outline-offset: -4px; animation: hb-wait 1s ease-in-out infinite alternate; }
@keyframes hb-wait { from { outline-color: var(--glow); } to { outline-color: transparent; } }

.t-ember { --tint: var(--t-ember); } .t-rust { --tint: var(--t-rust); } .t-amber { --tint: var(--t-amber); }
.t-sand { --tint: var(--t-sand); } .t-moss { --tint: var(--t-moss); } .t-sea { --tint: var(--t-sea); } .t-deep { --tint: var(--t-deep); }

.hb-empty { font-size: 26px; opacity: 0.6; padding: 10px 0; }
.hb-sec h2 .hb-more { margin-left: auto; padding-left: 16px; letter-spacing: 0.04em; text-transform: none; }
.hb-step-gap { flex: 0 0 auto; width: var(--tick); height: var(--tick); }
.hb-sub { padding: 5px 0 5px 62px; gap: 14px; border-bottom: 0; }
.hb-sub .hb-tick { --tick: 34px; border-width: 3px; border-radius: 9px; }
.hb-sub .hb-text { font-size: 25px; font-weight: 600; }
.hb-sub.is-done .hb-tick::after { width: 8px; height: 16px; border-width: 0 4px 4px 0; }
.is-cut { display: none !important; }

/* ---- layouts ---- */
/* small slots: the tally beside the open Dailies, nothing else */
[data-layout="compact"] .hb-frame { flex-direction: row; gap: 30px; }
[data-layout="compact"] .hb-hero { width: 230px; }
[data-layout="compact"] .hb-tally { flex-direction: column; align-items: flex-start; gap: 4px; }
[data-layout="compact"] .hb-stats, [data-layout="compact"] #sec-habits, [data-layout="compact"] #sec-todos, [data-layout="compact"] .hb-rest { display: none !important; }
[data-layout="compact"] .hb-lists { display: flex; flex-direction: column; }
[data-layout="compact"] #sec-dailies { flex: 1 1 auto; }

/* medium and tall slots: hero on top, lists stacked */
[data-layout="stack"] .hb-frame { flex-direction: column; gap: 22px; }
[data-layout="stack"] .hb-hero { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 330px); grid-template-areas: "day stats" "tally stats"; column-gap: 30px; align-items: start; }
[data-layout="stack"] .hb-day { grid-area: day; }
[data-layout="stack"] .hb-tally { grid-area: tally; }
[data-layout="stack"] .hb-stats { grid-area: stats; }
[data-layout="stack"] .hb-tally { flex-wrap: wrap; }
[data-layout="stack"] .hb-lists { display: flex; flex-direction: column; gap: 18px; }
[data-layout="stack"] .hb-sec { flex: 0 0 auto; }

/* wide slots: hero column, then two or three list columns */
[data-layout="cols2"] .hb-hero, [data-layout="cols3"] .hb-hero { width: 380px; }
[data-layout="cols2"] .hb-stats, [data-layout="cols3"] .hb-stats { margin-top: auto; }
[data-layout="cols2"] .hb-tally, [data-layout="cols3"] .hb-tally { flex-direction: column; align-items: flex-start; gap: 6px; }
[data-layout="cols2"] .hb-lists { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); grid-template-rows: minmax(0, 1fr) minmax(0, 1fr); column-gap: 44px; row-gap: 18px; }
[data-layout="cols2"] #sec-dailies { grid-column: 1; grid-row: 1 / span 2; }
[data-layout="cols2"] #sec-habits { grid-column: 2; grid-row: 1; }
[data-layout="cols2"] #sec-todos { grid-column: 2; grid-row: 2; }
[data-layout="cols2"] .no-todos #sec-habits, [data-layout="cols2"] .no-habits #sec-todos { grid-row: 1 / span 2; }
[data-layout="cols2"] .no-habits.no-todos #sec-dailies { grid-column: 1 / -1; }
[data-layout="cols3"] .hb-lists { display: flex; gap: 48px; }
[data-layout="cols3"] .hb-sec { flex: 1 1 0; }
[data-layout="cols3"] #sec-dailies { flex-grow: 1.25; }

/* ---- foot and state card ---- */
.hb-foot { position: absolute; right: 30px; bottom: 14px; font-size: 18px; font-weight: 700; opacity: 0.5; white-space: nowrap; }
.hb-foot.is-warn { color: var(--t-amber); opacity: 1; }
.hb-card {
  position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: min(1100px, calc(100% - 80px));
  display: flex; flex-direction: column; gap: 10px; text-align: center;
}
.hb-card b { font-size: 36px; font-weight: 800; color: var(--glow); }
.hb-card span { font-size: 24px; font-weight: 600; opacity: 0.78; line-height: 1.3; }

translation.json

{
  "en": {
    "translation": {
      "Accent Color": "Accent Color",
      "Background Color": "Background Color",
      "Background Transparency": "Background Transparency",
      "Copy your User ID and API Token from Habitica Settings, Site Data (API). They stay in iCUE and are only sent to habitica.com. Not created by, affiliated with, or endorsed by Habitica or HabitRPG, Inc.": "Copy your User ID and API Token from Habitica Settings, Site Data (API). They stay in iCUE and are only sent to habitica.com. Not created by, affiliated with, or endorsed by Habitica or HabitRPG, Inc.",
      "Habitica API Token": "Habitica API Token",
      "Habitica User ID": "Habitica User ID",
      "Refresh Every": "Refresh Every",
      "Show Habits": "Show Habits",
      "Show Health, Experience and Mana": "Show Health, Experience and Mana",
      "Show To Dos Due Today": "Show To Dos Due Today",
      "Tap to Check Off and Score": "Tap to Check Off and Score",
      "Text Color": "Text Color",
      "Today for Habitica": "Today for Habitica",
      "Widget Personalization": "Widget Personalization"
    }
  }
}