@elastics-ai/host-kit 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # @elastics-ai/host-kit
2
2
 
3
- Elastics design tokens and eight custom elements for a page that a host builds and publishes, such as a Claude artifact or a ChatGPT Site. The Elastics MCP tool `get_style_kit` tells the model which published version to load.
3
+ Elastics design tokens and eleven custom elements for a page that a host builds and publishes, such as a Claude artifact or a ChatGPT Site. The Elastics MCP tool `get_style_kit` tells the model which published version to load.
4
4
 
5
5
  ```html
6
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@elastics-ai/host-kit@0.2.0/host-kit.css" integrity="sha384-…" crossorigin="anonymous">
7
- <script src="https://cdn.jsdelivr.net/npm/@elastics-ai/host-kit@0.2.0/host-kit.js" integrity="sha384-…" crossorigin="anonymous"></script>
6
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@elastics-ai/host-kit@0.3.0/host-kit.css" integrity="sha384-…" crossorigin="anonymous">
7
+ <script src="https://cdn.jsdelivr.net/npm/@elastics-ai/host-kit@0.3.0/host-kit.js" integrity="sha384-…" crossorigin="anonymous"></script>
8
8
 
9
9
  <ex-card heading="Will BTC close above $100k?" state="live">
10
10
  <ex-stat label="Yes price" value="62¢" change="+3¢" trend="up"></ex-stat>
@@ -15,7 +15,7 @@ Elastics design tokens and eight custom elements for a page that a host builds a
15
15
  </script>
16
16
  ```
17
17
 
18
- This example documents version 0.2.0. Take its full tags, with their `integrity` values, from `HOST_KIT_TAGS` in `src/index.ts` at this version. `get_style_kit` sends the tags of the version that it serves. The browser then refuses a file whose bytes differ from the ones this repository built.
18
+ This example documents version 0.3.0. Take its full tags, with their `integrity` values, from `HOST_KIT_TAGS` in `src/index.ts` at this version. `get_style_kit` sends the tags of the version that it serves. The browser then refuses a file whose bytes differ from the ones this repository built.
19
19
 
20
20
  | Element | Input |
21
21
  |---|---|
@@ -27,14 +27,19 @@ This example documents version 0.2.0. Take its full tags, with their `integrity`
27
27
  | `ex-news-row` | `headline`, `url` (linked only when https), `source`, `time` |
28
28
  | `ex-notification-row` | `headline`, `body`, `time`, `read` |
29
29
  | `ex-run-row` | `status` (`running`, `failed`, other), `action`, `time` |
30
+ | `ex-chart` | `.points = [[time, price]]` or `[{time, price}]`, time in Unix seconds, price 0 to 1; `label`, `height` (200) |
31
+ | `ex-tabs` | children with `data-label` (and `data-disabled`) are the panels; `label`, `value`; fires `change` |
32
+ | `ex-markets` | `.markets = [{title, price, volume, url, image}]` |
30
33
 
31
34
  `ex-book` takes prediction-market prices from 0 to 1 and prints them in cents, with Price, Size and Total columns and the spread between the asks and the bids. With `price="quote"`, it prints an instrument's prices in its quote currency in an 80px column, and the spread as a percentage of the best bid. A side with no levels says `No Asks` or `No Bids`. A level whose price is not a number shows at the far end of its side, outside the spread and the depth bars.
32
35
 
36
+ `ex-chart` draws a price line as the web app's line chart: cents on the price axis, dotted rules at its ticks, dates or the web app's 12h clock on the time axis, a dot on the last reading, and the moment and price under the pointer. `ex-tabs` draws pill tabs over its panels: the arrow keys move between tabs, Home and End jump, and Enter, Space or a click picks one. `ex-markets` lists markets as the web app's search rows: the title, then the Yes price in cents and the volume in compact dollars (`$1.4M`). A row links out only to an https `url`, and its tile shows an https `image` over the title's first two letters.
37
+
33
38
  `format` prints a number as the web app does: `cents` for a 0 to 1 price (`0.004` prints `0.4¢`), `usd` for dollars (`$3,113.68`), `amount` for two decimals (`169,439.48`) and `number` for at most two (`1,250`). A numeric column without a format groups its thousands and keeps every decimal (`0.0000123`). A value that is not a number prints as it came. A column with `side: true` tints `Buy` and `Sell`, and `side: "<key>"` tints the cell by the row's side under that key, as the web app's tape tints its price.
34
39
 
35
40
  Every element writes values with `textContent`, so markup in a feed value shows as text. The colours follow `prefers-color-scheme`, and a `.light` or `.dark` class on any ancestor pins one scheme.
36
41
 
37
- A Claude artifact loads stylesheets only from Google Fonts. There, put the rules of `host-kit.css` in a `<style>` tag (`get_style_kit` sends them as `css` for the version it serves) and load only the script.
42
+ A Claude artifact loads stylesheets only from Google Fonts. There, put the rules of `host-kit.css` in a `<style>` tag (`get_style_kit` sends them as `css` for the version it serves) and load only the script. The script inserts the rules of `ex-chart`, `ex-tabs` and `ex-markets` itself, once per document.
38
43
 
39
44
  `host-kit.js` has no import or export, so it loads as a classic script or as a module, and from a `file://` page. Open `demo.html` to see every element in both schemes.
40
45
 
package/host-kit.css CHANGED
@@ -1,4 +1,4 @@
1
1
  /* @elastics-ai/host-kit. Generated by scripts/gen.ts. Do not edit. */
2
- :root{color-scheme:light dark;--background:light-dark(#fafafa,#0c0c0e);--surface:light-dark(#efeff0,#161618);--subtle:light-dark(#ebebed,#1b1b1d);--foreground:light-dark(#161618,#efeff0);--muted-foreground:light-dark(#58585d,#9a9a9e);--card:light-dark(#e7e7e9,#1f1f23);--card-foreground:light-dark(#161618,#efeff0);--border:light-dark(#e7e7e9,#1f1f23);--accent:light-dark(#ebebed,#1b1b1d);--accent-foreground:light-dark(#161618,#efeff0);--primary:light-dark(#0c0c0e,#fafafa);--primary-foreground:light-dark(#fafafa,#0c0c0e);--ring:#6e6e73;--positive:light-dark(#cdf1df,#002b20);--positive-foreground:light-dark(#09684b,#1ebf88);--negative:light-dark(#ffdcdf,#3a161e);--negative-foreground:light-dark(#b81f43,#fe6b80);--caution:light-dark(#fff0cc,#3b290d);--caution-foreground:light-dark(#8a5300,#fdae31);--info:light-dark(#f1e4ff,#3b126f);--info-foreground:light-dark(#7d2be6,#ae6cf5);--chart-cat-1:light-dark(#0a66fb,#4f84fe);--chart-cat-2:light-dark(#b37903,#b47d06);--chart-cat-3:light-dark(#f416aa,#ed16ce);--chart-cat-4:light-dark(#008ab3,#0b7699);--chart-cat-5:#697005;--chart-positive:#0b9d6f;--chart-negative:#fe546d;--radius-sm:4px;--radius-md:6px;--radius-lg:8px;--radius-3xl:16px;--text-xs:0.75rem;--text-sm:0.8125rem;--text-base:0.875rem;--text-2xl:1.5rem;--font-sans:Geist, ui-sans-serif, system-ui, sans-serif;--font-mono:'Geist Mono', ui-monospace, 'SF Mono', monospace}.light{color-scheme:light}.dark{color-scheme:dark}
2
+ :root{color-scheme:light dark;--background:light-dark(#fafafa,#0c0c0e);--surface:light-dark(#efeff0,#161618);--subtle:light-dark(#ebebed,#1b1b1d);--foreground:light-dark(#161618,#efeff0);--muted-foreground:light-dark(#58585d,#9a9a9e);--card:light-dark(#e7e7e9,#1f1f23);--card-foreground:light-dark(#161618,#efeff0);--border:light-dark(#e7e7e9,#1f1f23);--accent:light-dark(#ebebed,#1b1b1d);--accent-foreground:light-dark(#161618,#efeff0);--accent-emphasis:light-dark(#dfdfe1,#242428);--raised:light-dark(#d0d0d2,#2c2c30);--background-hover:light-dark(#efeff0,#161618);--border-emphasis:light-dark(#b6b6b8,#2c2c30);--rule-dotted:light-dark(#dfdfe1,#242428);--muted-foreground-emphasis:light-dark(#49494e,#9a9a9e);--tooltip:light-dark(#1b1b1d,#2c2c30);--tooltip-foreground:#efeff0;--primary:light-dark(#0c0c0e,#fafafa);--primary-foreground:light-dark(#fafafa,#0c0c0e);--ring:#6e6e73;--positive:light-dark(#cdf1df,#002b20);--positive-foreground:light-dark(#09684b,#1ebf88);--negative:light-dark(#ffdcdf,#3a161e);--negative-foreground:light-dark(#b81f43,#fe6b80);--caution:light-dark(#fff0cc,#3b290d);--caution-foreground:light-dark(#8a5300,#fdae31);--info:light-dark(#f1e4ff,#3b126f);--info-foreground:light-dark(#7d2be6,#ae6cf5);--chart-cat-1:light-dark(#0a66fb,#4f84fe);--chart-cat-2:light-dark(#b37903,#b47d06);--chart-cat-3:light-dark(#f416aa,#ed16ce);--chart-cat-4:light-dark(#008ab3,#0b7699);--chart-cat-5:#697005;--chart-positive:#0b9d6f;--chart-negative:#fe546d;--chart-1-2:light-dark(#6d6d87,#83839a);--radius-sm:4px;--radius-md:6px;--radius-lg:8px;--radius-3xl:16px;--radius-full:9999px;--ease-smooth:cubic-bezier(0.65, 0, 0.35, 1);--text-xs:0.75rem;--text-sm:0.8125rem;--text-base:0.875rem;--text-sm--line-height:1.125rem;--text-base--line-height:1.375rem;--spacing:0.25rem;--text-2xl:1.5rem;--font-sans:Geist, ui-sans-serif, system-ui, sans-serif;--font-mono:'Geist Mono', ui-monospace, 'SF Mono', monospace}.light{color-scheme:light}.dark{color-scheme:dark}
3
3
  body{margin:0;background:var(--background);color:var(--foreground);font:400 var(--text-base)/1.5 var(--font-sans)}.ex-num{font-variant-numeric:tabular-nums}.ex-muted{color:var(--muted-foreground);font-size:var(--text-xs)}.ex-card{background:var(--card);color:var(--card-foreground);border-radius:var(--radius-3xl);padding:16px;display:flex;flex-direction:column;gap:12px;overflow:hidden}.ex-card>h2{margin:0;font-size:var(--text-sm);font-weight:500;display:flex;justify-content:space-between;align-items:center;gap:8px}.ex-stat{display:grid;gap:4px}.ex-stat b{font-size:var(--text-2xl);font-weight:500;font-variant-numeric:tabular-nums}.ex-up{color:var(--positive-foreground)}.ex-down{color:var(--negative-foreground)}.ex-table{width:100%;border-collapse:collapse;font-size:var(--text-base)}.ex-table th{text-align:left;font-size:var(--text-sm);font-weight:500;color:var(--muted-foreground)}.ex-table th,.ex-table td{padding:6px 8px;border-bottom:1px solid var(--border)}.ex-table td{font-weight:500;font-variant-numeric:tabular-nums}.ex-table .n{text-align:end}.ex-bk{display:grid;gap:4px;font:500 var(--text-base)/32px var(--font-sans);font-variant-numeric:tabular-nums}.ex-bk>*{position:relative;display:grid;grid:auto/64px 1fr 1fr;padding:0 8px}.ex-bk.q>*{grid:auto/80px 1fr 1fr}.ex-bk span{position:relative;padding:0 6px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.ex-bk span+span{text-align:end}.ex-bk-head{background:var(--surface);font-size:var(--text-sm);font-weight:400}.ex-lvl>i{position:absolute;inset:0 auto 0 0;border-radius:var(--radius-md);background:var(--positive)}.ex-lvl.ask>i{background:var(--negative)}.ex-bk .m,.ex-bk-head{color:var(--muted-foreground)}.ex-bk .e{grid-column:1/-1;text-align:center;font-size:var(--text-xs)}.ex-spread{background:var(--subtle);border-radius:var(--radius-md)}.ex-badge{display:inline-flex;align-items:center;gap:4px;font-size:var(--text-xs);font-weight:500;color:var(--muted-foreground)}.ex-badge::before{content:"";width:6px;height:6px;border-radius:50%;background:currentColor}.ex-badge[data-state=live]{color:var(--positive-foreground)}.ex-badge[data-state=stale]{color:var(--caution-foreground)}.ex-badge[data-state=failed]{color:var(--negative-foreground)}.ex-row{display:flex;gap:12px;align-items:flex-start;padding:8px 0;border-bottom:1px solid var(--border)}.ex-row>div{flex:1;min-width:0}.ex-row p{margin:0;overflow:hidden;text-overflow:ellipsis}.ex-row a{color:inherit;text-decoration:none}.ex-row a:hover{text-decoration:underline}.ex-dot{width:8px;height:8px;margin-top:6px;border-radius:50%;background:var(--info-foreground);flex:none}.ex-dot[data-read]{background:transparent}.ex-btn{background:var(--primary);color:var(--primary-foreground);border:0;border-radius:var(--radius-lg);padding:8px 14px;font:500 var(--text-sm) var(--font-sans);cursor:pointer}:focus-visible{outline:2px solid var(--ring);outline-offset:2px}
4
- ex-stat,ex-table,ex-book,ex-news-row,ex-notification-row,ex-run-row{display:block}
4
+ ex-stat,ex-table,ex-book,ex-news-row,ex-notification-row,ex-run-row{display:block}ex-chart,ex-markets{display:block}.ex-chart{position:relative}.ex-chart svg{display:block;overflow:visible;touch-action:pan-y;font:400 var(--text-xs)/calc(var(--spacing)*4) var(--font-sans);font-variant-numeric:tabular-nums}.ex-chart text{fill:var(--muted-foreground)}.ex-chart [hidden]{display:none}.ex-ch-grid line{stroke:var(--rule-dotted);stroke-width:1;stroke-dasharray:1 5;stroke-linecap:square}.ex-ch-line{fill:none;stroke:var(--chart-1-2);stroke-width:2;stroke-linecap:round;stroke-linejoin:round}.ex-ch-end,.ex-ch-dot{fill:var(--chart-1-2)}.ex-ch-cross{stroke:var(--border-emphasis);stroke-width:1}.ex-ch-tip{position:absolute;z-index:1;pointer-events:none;transform:translate(-50%,-100%);display:grid;gap:calc(var(--spacing)*.5);padding:var(--spacing) calc(var(--spacing)*2.5);border-radius:var(--radius-3xl);background:var(--tooltip);color:var(--tooltip-foreground);font:500 var(--text-sm)/var(--text-sm--line-height) var(--font-sans);white-space:nowrap}.ex-ch-tip[hidden]{display:none}.ex-ch-tip span+span{font-variant-numeric:tabular-nums}ex-tabs{display:flex;flex-direction:column;gap:calc(var(--spacing)*2)}.ex-tabs-list{position:relative;display:flex;align-items:center;gap:calc(var(--spacing)*2);width:fit-content;max-width:100%;overflow-x:auto}.ex-tab{display:inline-flex;align-items:center;gap:var(--spacing);flex-shrink:0;white-space:nowrap;user-select:none;height:calc(var(--spacing)*8);padding:0 calc(var(--spacing)*3);border:0;border-radius:var(--radius-full);background:none;color:var(--muted-foreground);font:500 var(--text-base)/var(--text-base--line-height) var(--font-sans);cursor:pointer;outline:none;transition:color .3s var(--ease-smooth),background-color .3s var(--ease-smooth)}.ex-tab:hover,.ex-tab[aria-selected=true]{color:var(--foreground)}.ex-tab[aria-selected=true]{background:var(--accent-emphasis)}.ex-tab:focus-visible{outline:none;box-shadow:0 0 0 2px var(--ring)}.ex-tab[data-disabled]{opacity:.5;pointer-events:none}.ex-tab-panel{flex:1;font-size:var(--text-sm);line-height:var(--text-sm--line-height);outline:none}.ex-tab-panel[hidden]{display:none}@media (prefers-reduced-motion:reduce){.ex-tab{transition:none}}.ex-mkt{display:flex;align-items:center;gap:calc(var(--spacing)*3);box-sizing:border-box;min-height:3.5rem;padding:var(--spacing) calc(var(--spacing)*4) var(--spacing) calc(var(--spacing)*3);color:inherit;text-decoration:none}.ex-mkt:hover{background:var(--background-hover)}.ex-mkt:focus-visible{outline-offset:-2px}.ex-mkt>div{flex:1;min-width:0}.ex-mkt p{margin:0;font:500 var(--text-base)/var(--text-base--line-height) var(--font-sans);overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.ex-mkt-meta{display:flex;flex-wrap:wrap;column-gap:calc(var(--spacing)*2);color:var(--muted-foreground);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-variant-numeric:tabular-nums}.ex-mkt-meta b,.ex-mkt-meta i{font-weight:inherit;font-style:normal}.ex-av{position:relative;flex:none;display:grid;place-items:center;width:calc(var(--spacing)*9);height:calc(var(--spacing)*9);overflow:hidden;border-radius:var(--radius-full);background:var(--raised);color:var(--muted-foreground-emphasis);font:500 var(--text-base)/var(--text-base--line-height) var(--font-sans)}.ex-av img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}.ex-av::after{content:"";position:absolute;inset:0;border-radius:inherit;box-shadow:inset 0 0 0 1px var(--border-emphasis)}
package/host-kit.js CHANGED
@@ -1,4 +1,4 @@
1
- // @elastics-ai/host-kit: eight custom elements for a page that Claude or
1
+ // @elastics-ai/host-kit: eleven custom elements for a page that Claude or
2
2
  // ChatGPT publishes, styled by host-kit.css. Values go in through attributes
3
3
  // or properties and come out through textContent only: no element parses
4
4
  // HTML, so a market title or news headline from a feed renders as text.
@@ -507,6 +507,802 @@
507
507
  }
508
508
  }
509
509
 
510
+ // Dollars in compact notation, "$1.4M", "$12.5K", "$950", as the web
511
+ // app prints a market's volume: formatCompactCurrency,
512
+ // packages/core/src/formatters/currency.ts:84-89.
513
+ const COMPACT_USD = new Intl.NumberFormat('en-US', {
514
+ style: 'currency',
515
+ currency: 'USD',
516
+ notation: 'compact',
517
+ minimumFractionDigits: 0,
518
+ maximumFractionDigits: 1,
519
+ });
520
+
521
+ const SVG = 'http://www.w3.org/2000/svg';
522
+
523
+ /** @param {string} tag @param {Record<string, string | number>} [attrs] @param {string} [className] */
524
+ function svg(tag, attrs = {}, className) {
525
+ const el = document.createElementNS(SVG, tag);
526
+ if (className) el.setAttribute('class', className);
527
+ for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, String(v));
528
+ return el;
529
+ }
530
+
531
+ // d3's ticks: steps of 1, 2 or 5 times a power of ten inside the
532
+ // readings' own range, which the chart does not round outward
533
+ // (scaleLinear().ticks(4), chart-line.tsx yTickCount and 916-923).
534
+ /** @param {number} lo @param {number} hi @param {number} count */
535
+ function linearTicks(lo, hi, count) {
536
+ const raw = (hi - lo) / count;
537
+ const power = 10 ** Math.floor(Math.log10(raw));
538
+ const error = raw / power;
539
+ const step =
540
+ power * (error >= 7.07 ? 10 : error >= 3.16 ? 5 : error >= 1.41 ? 2 : 1);
541
+ const ticks = [];
542
+ for (
543
+ let i = Math.ceil(lo / step - 1e-9);
544
+ i <= Math.floor(hi / step + 1e-9);
545
+ i++
546
+ )
547
+ ticks.push(Math.round(i * step * 1e9) / 1e9);
548
+ return ticks;
549
+ }
550
+
551
+ const SECOND = 1e3;
552
+ const MINUTE = 60 * SECOND;
553
+ const HOUR = 60 * MINUTE;
554
+ const DAY = 24 * HOUR;
555
+
556
+ // d3-time's calendar units in the viewer's zone (timeSecond, timeMinute,
557
+ // timeHour, timeDay, timeSunday, timeMonth, timeYear): how a Date is
558
+ // floored to one, moved n of them on, and the field every(k) keeps the
559
+ // multiples of.
560
+ /** @typedef {[(d: Date) => unknown, (d: Date, n: number) => unknown, (d: Date) => number]} Unit */
561
+ /** @type {Unit} */
562
+ const SECONDS = [
563
+ (d) => d.setTime(+d - d.getMilliseconds()),
564
+ (d, n) => d.setTime(+d + n * SECOND),
565
+ (d) => d.getUTCSeconds(),
566
+ ];
567
+ /** @type {Unit} */
568
+ const MINUTES = [
569
+ (d) => d.setTime(+d - d.getMilliseconds() - d.getSeconds() * SECOND),
570
+ (d, n) => d.setTime(+d + n * MINUTE),
571
+ (d) => d.getMinutes(),
572
+ ];
573
+ /** @type {Unit} */
574
+ const HOURS = [
575
+ (d) =>
576
+ d.setTime(
577
+ +d -
578
+ d.getMilliseconds() -
579
+ d.getSeconds() * SECOND -
580
+ d.getMinutes() * MINUTE
581
+ ),
582
+ (d, n) => d.setTime(+d + n * HOUR),
583
+ (d) => d.getHours(),
584
+ ];
585
+ /** @type {Unit} */
586
+ const DAYS = [
587
+ (d) => d.setHours(0, 0, 0, 0),
588
+ (d, n) => d.setDate(d.getDate() + n),
589
+ (d) => d.getDate() - 1,
590
+ ];
591
+ /** @type {Unit} */
592
+ const WEEKS = [
593
+ (d) => {
594
+ d.setDate(d.getDate() - d.getDay());
595
+ d.setHours(0, 0, 0, 0);
596
+ },
597
+ (d, n) => d.setDate(d.getDate() + 7 * n),
598
+ () => 0,
599
+ ];
600
+ /** @type {Unit} */
601
+ const MONTHS = [
602
+ (d) => {
603
+ d.setDate(1);
604
+ d.setHours(0, 0, 0, 0);
605
+ },
606
+ (d, n) => d.setMonth(d.getMonth() + n),
607
+ (d) => d.getMonth(),
608
+ ];
609
+ /** @type {Unit} */
610
+ const YEARS = [
611
+ (d) => {
612
+ d.setMonth(0, 1);
613
+ d.setHours(0, 0, 0, 0);
614
+ },
615
+ (d, n) => d.setFullYear(d.getFullYear() + n),
616
+ (d) => d.getFullYear(),
617
+ ];
618
+ // d3-time's tickIntervals: a unit, every how many, about how long.
619
+ /** @type {[Unit, number, number][]} */
620
+ const TICK_INTERVALS = [
621
+ [SECONDS, 1, SECOND],
622
+ [SECONDS, 5, 5 * SECOND],
623
+ [SECONDS, 15, 15 * SECOND],
624
+ [SECONDS, 30, 30 * SECOND],
625
+ [MINUTES, 1, MINUTE],
626
+ [MINUTES, 5, 5 * MINUTE],
627
+ [MINUTES, 15, 15 * MINUTE],
628
+ [MINUTES, 30, 30 * MINUTE],
629
+ [HOURS, 1, HOUR],
630
+ [HOURS, 3, 3 * HOUR],
631
+ [HOURS, 6, 6 * HOUR],
632
+ [HOURS, 12, 12 * HOUR],
633
+ [DAYS, 1, DAY],
634
+ [DAYS, 2, 2 * DAY],
635
+ [WEEKS, 1, 7 * DAY],
636
+ [MONTHS, 1, 30 * DAY],
637
+ [MONTHS, 3, 90 * DAY],
638
+ [YEARS, 1, 365 * DAY],
639
+ ];
640
+
641
+ // d3-array's tickStep: 1, 2 or 5 times a power of ten.
642
+ /** @param {number} lo @param {number} hi @param {number} count @returns {number} */
643
+ function tickStep(lo, hi, count) {
644
+ const raw = (hi - lo) / count;
645
+ const power = 10 ** Math.floor(Math.log10(raw));
646
+ const error = raw / power;
647
+ const step =
648
+ power *
649
+ (error >= Math.sqrt(50)
650
+ ? 10
651
+ : error >= Math.sqrt(10)
652
+ ? 5
653
+ : error >= Math.sqrt(2)
654
+ ? 2
655
+ : 1);
656
+ return count >= 0.5 && count < 2 && Math.ceil(lo / step) > hi / step
657
+ ? tickStep(lo, hi, count * 2)
658
+ : step;
659
+ }
660
+
661
+ // d3's scaleTime().ticks(count) from a to b (ms): the interval whose
662
+ // length is nearest (b - a) / count, every boundary of it from a to b.
663
+ /** @param {number} a @param {number} b @param {number} count */
664
+ function d3TimeTicks(a, b, count) {
665
+ const target = (b - a) / count;
666
+ let i = TICK_INTERVALS.findIndex(([, , ms]) => ms > target);
667
+ /** @type {Unit} */
668
+ let unit;
669
+ let every;
670
+ if (i < 0) {
671
+ unit = YEARS;
672
+ every = Math.floor(tickStep(a / (365 * DAY), b / (365 * DAY), count));
673
+ } else if (i === 0) {
674
+ const k = Math.max(Math.floor(tickStep(a, b, count)), 1);
675
+ unit = [
676
+ (d) => d.setTime(Math.floor(+d / k) * k),
677
+ (d, n) => d.setTime(+d + n * k),
678
+ () => 0,
679
+ ];
680
+ every = 1;
681
+ } else {
682
+ const lower = TICK_INTERVALS[i - 1];
683
+ const upper = TICK_INTERVALS[i];
684
+ if (lower && upper && target / lower[2] < upper[2] / target) i -= 1;
685
+ [unit, every] = TICK_INTERVALS[i] ?? [YEARS, 1];
686
+ }
687
+ const [floor, step, field] = unit;
688
+ const next = (/** @type {Date} */ d) => {
689
+ do {
690
+ step(d, 1);
691
+ floor(d);
692
+ } while (field(d) % every);
693
+ };
694
+ const d = new Date(a - 1);
695
+ floor(d);
696
+ next(d);
697
+ const out = [];
698
+ for (let prev = -Infinity; +d <= b && +d > prev; next(d)) {
699
+ prev = +d;
700
+ out.push(prev);
701
+ }
702
+ return out;
703
+ }
704
+
705
+ // A row d3 steps every second day, from each month's 1st, stepped from
706
+ // the epoch instead, so a month's end leaves no short step
707
+ // (chart-time-ticks.ts evenDays).
708
+ /** @param {number[]} ticks @param {number} a @param {number} b */
709
+ function evenDays(ticks, a, b) {
710
+ const gaps = ticks.slice(1).map((t, i) => t - (ticks[i] ?? 0));
711
+ if (
712
+ !gaps.some((g) => Math.abs(g - 2 * DAY) <= HOUR) ||
713
+ !gaps.every((g) => g <= 2 * DAY + HOUR)
714
+ )
715
+ return ticks;
716
+ const out = [];
717
+ const d = new Date(a);
718
+ d.setHours(0, 0, 0, 0);
719
+ if (+d < a) d.setDate(d.getDate() + 1);
720
+ for (; +d <= b; d.setDate(d.getDate() + 1))
721
+ if (
722
+ Math.round(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) / DAY) %
723
+ 2 ===
724
+ 0
725
+ )
726
+ out.push(+d);
727
+ return out;
728
+ }
729
+
730
+ /** @param {number} t */
731
+ const wallClock = (t) => {
732
+ const d = new Date(t);
733
+ return `${d.toDateString()} ${d.getHours()}:${d.getMinutes()}`;
734
+ };
735
+ /** @param {number} t */
736
+ const midnight = (t) => {
737
+ const d = new Date(t);
738
+ return d.getHours() === 0 && d.getMinutes() === 0;
739
+ };
740
+ /** @param {number} t */
741
+ const monthStart = (t) => midnight(t) && new Date(t).getDate() === 1;
742
+ /** @param {number} a @param {number} b */
743
+ const sameDay = (a, b) =>
744
+ new Date(a).toDateString() === new Date(b).toDateString();
745
+
746
+ // The product's one clock: en-US, 12h (DEFAULT_HOUR12,
747
+ // packages/core/src/formatters/time.ts:7-8), in the formats of
748
+ // chart-time-ticks.ts.
749
+ const dateFormat = (/** @type {Intl.DateTimeFormatOptions} */ o) =>
750
+ new Intl.DateTimeFormat('en-US', o);
751
+ const CLOCK = dateFormat({
752
+ hour: 'numeric',
753
+ minute: '2-digit',
754
+ hour12: true,
755
+ });
756
+ const DATE = dateFormat({ month: 'short', day: 'numeric' });
757
+ const DATE_CLOCK = dateFormat({
758
+ month: 'short',
759
+ day: 'numeric',
760
+ hour: 'numeric',
761
+ minute: '2-digit',
762
+ hour12: true,
763
+ });
764
+ const MONTH = dateFormat({ month: 'short' });
765
+ const MONTH_YEAR = dateFormat({ month: 'short', year: 'numeric' });
766
+ const YEAR = dateFormat({ year: 'numeric' });
767
+
768
+ // The labels of a row of ticks at the grain the row steps through
769
+ // (chart-time-ticks.ts timeTickLabels).
770
+ /** @param {number[]} ticks @param {number} span */
771
+ function timeLabels(ticks, span) {
772
+ const first = ticks[0] ?? 0;
773
+ const grain =
774
+ ticks.length < 2
775
+ ? span <= 1.5 * DAY
776
+ ? 'clock'
777
+ : span <= 300 * DAY
778
+ ? 'day'
779
+ : 'month'
780
+ : ticks.every((t) => monthStart(t) && new Date(t).getMonth() === 0)
781
+ ? 'year'
782
+ : ticks.every(monthStart)
783
+ ? 'month'
784
+ : ticks.every(midnight)
785
+ ? 'day'
786
+ : 'clock';
787
+ // The first tick goes undated where the midnight that ends its day
788
+ // comes next: "12:00 PM | Mar 6".
789
+ const next = ticks.find((t) => !sameDay(t, first));
790
+ const end = new Date(first);
791
+ end.setHours(0, 0, 0, 0);
792
+ end.setDate(end.getDate() + 1);
793
+ const named = next !== undefined && midnight(next) && +end === next;
794
+ return ticks.map((t, i) => {
795
+ const before = ticks[i - 1];
796
+ if (grain === 'year') return YEAR.format(t);
797
+ if (grain === 'month')
798
+ return new Date(t).getMonth() === 0 ||
799
+ (before !== undefined &&
800
+ new Date(before).getFullYear() !== new Date(t).getFullYear())
801
+ ? MONTH_YEAR.format(t)
802
+ : MONTH.format(t);
803
+ if (grain === 'day' || midnight(t)) return DATE.format(t);
804
+ const dated = before === undefined ? !named : !sameDay(before, t);
805
+ return (dated ? DATE_CLOCK : CLOCK).format(t);
806
+ });
807
+ }
808
+
809
+ // Where a label starts, held inside the plot: the first from its tick
810
+ // on, the last up to its tick, any other centred under its own
811
+ // (chart-time-ticks.ts axisLabelStart).
812
+ /** @param {number} x @param {number} w @param {number} i @param {number} last @param {number} width */
813
+ function labelStart(x, w, i, last, width) {
814
+ const start = i === 0 ? x : i === last ? x - w : x - w / 2;
815
+ return Math.min(Math.max(start, 0), Math.max(width - w, 0));
816
+ }
817
+
818
+ // Whether labels at `at`, `widths` wide, stand 12px apart, each where
819
+ // labelStart puts it (chart-time-ticks.ts axisLabelsApart).
820
+ /** @param {number[]} at @param {number[]} widths @param {number} width */
821
+ function labelsApart(at, widths, width) {
822
+ let end = Number.NEGATIVE_INFINITY;
823
+ for (const [i, x] of at.entries()) {
824
+ const w = widths[i] ?? 0;
825
+ const start = labelStart(x, w, i, at.length - 1, width);
826
+ if (start < end + 12) return false;
827
+ end = start + w;
828
+ }
829
+ return true;
830
+ }
831
+
832
+ // The moments the time axis names from a to b (ms) on a plot `width`
833
+ // wide: d3's row for five, then four and fewer, thinned to every second
834
+ // or third, the first whose labels stand 12px apart at about 7px a
835
+ // character (chart-time-ticks.ts timeTicks).
836
+ /** @param {number} a @param {number} b @param {number} width */
837
+ function timeAxis(a, b, width) {
838
+ /** @param {number[]} ticks */
839
+ const fits = (ticks) => {
840
+ const labels = timeLabels(ticks, b - a);
841
+ return labelsApart(
842
+ ticks.map((t) => ((t - a) / (b - a)) * width),
843
+ labels.map((l) => l.length * 7),
844
+ width
845
+ )
846
+ ? labels
847
+ : null;
848
+ };
849
+ if (b > a && width > 0)
850
+ for (const least of [2, 1])
851
+ for (let count = 5; count >= 1; count--) {
852
+ const all = evenDays(d3TimeTicks(a, b, count), a, b).filter(
853
+ (t, i, row) =>
854
+ i === 0 || wallClock(t) !== wallClock(row[i - 1] ?? t)
855
+ );
856
+ for (let n = 1; n <= all.length; n++) {
857
+ const ticks = all.filter((_, i) => i % n === 0);
858
+ if (ticks.length < least) break;
859
+ const labels = fits(ticks);
860
+ if (labels) return { ticks, labels };
861
+ }
862
+ }
863
+ return { ticks: [a], labels: timeLabels([a], b - a) };
864
+ }
865
+
866
+ // The read-out's moment, "Mar 5, 18:00", with the year when it is not
867
+ // this one (formatMoment, chart-time-ticks.ts).
868
+ /** @param {number} at */
869
+ function moment(at) {
870
+ const d = new Date(at);
871
+ return new Intl.DateTimeFormat('en-US', {
872
+ month: 'short',
873
+ day: 'numeric',
874
+ year:
875
+ d.getFullYear() === new Date().getFullYear() ? undefined : 'numeric',
876
+ hour: 'numeric',
877
+ minute: '2-digit',
878
+ hour12: true,
879
+ }).format(d);
880
+ }
881
+
882
+ // A price chart drawn as the design system's line chart
883
+ // (packages/ui/src/components/charts/chart.tsx and chart-line.tsx): a 2px
884
+ // line on --chart-1-2, dotted rules at the price ticks, labels in the
885
+ // frame, an end dot, and a crosshair with a bubble under the pointer.
886
+ // Readings are [unix seconds, 0 to 1 price]; the axis prints cents.
887
+ class ExChart extends KitElement {
888
+ static props = ['points'];
889
+ static observedAttributes = ['label', 'height'];
890
+ /** @type {{ t: number, p: number }[]} */
891
+ #points = [];
892
+ #width = 0;
893
+ /** @type {ResizeObserver | null} */
894
+ #resize = null;
895
+
896
+ get points() {
897
+ return this.#points.map((r) => [r.t / 1000, r.p]);
898
+ }
899
+ set points(value) {
900
+ this.#points = list(value)
901
+ .map((r) => {
902
+ const pair = Array.isArray(r)
903
+ ? r
904
+ : r && typeof r === 'object'
905
+ ? [Reflect.get(r, 'time'), Reflect.get(r, 'price')]
906
+ : [];
907
+ const t = num(pair[0]);
908
+ const p = num(pair[1]);
909
+ return t === null || p === null ? null : { t: t * 1000, p };
910
+ })
911
+ .filter((r) => r !== null)
912
+ .sort((x, y) => x.t - y.t);
913
+ this.attributeChangedCallback();
914
+ }
915
+
916
+ connectedCallback() {
917
+ super.connectedCallback();
918
+ if (!this.#resize && typeof ResizeObserver === 'function') {
919
+ this.#resize = new ResizeObserver(() => {
920
+ if (this.clientWidth && this.clientWidth !== this.#width)
921
+ this.render();
922
+ });
923
+ this.#resize.observe(this);
924
+ }
925
+ }
926
+
927
+ disconnectedCallback() {
928
+ this.#resize?.disconnect();
929
+ this.#resize = null;
930
+ }
931
+
932
+ render() {
933
+ this.classList.add('ex-chart');
934
+ const points = this.#points;
935
+ if (!points.length) {
936
+ this.replaceChildren(node('span', 'ex-muted', 'No data'));
937
+ return;
938
+ }
939
+ // A hidden chart (an ex-tabs panel not shown) has no width: it draws
940
+ // at 600px with unmeasured labels and keeps 0, so the observer draws
941
+ // it again at its real width once it shows.
942
+ this.#width = this.clientWidth;
943
+ const width = this.#width || 600;
944
+ const height = Math.max(40, num(this.getAttribute('height')) ?? 200);
945
+ const cents = points.map((r) => r.p * 100);
946
+ let lo = Math.min(...cents);
947
+ const hi = Math.max(...cents);
948
+ if (lo === hi) lo = hi - 1;
949
+ const yTicks = linearTicks(lo, hi, 4);
950
+ const yLabels = yTicks.map(
951
+ (v) => `${v.toLocaleString('en-US', { maximumFractionDigits: 1 })}¢`
952
+ );
953
+ const m = {
954
+ top: 8,
955
+ right: 8,
956
+ bottom: 28,
957
+ left: Math.max(44, Math.max(...yLabels.map((l) => l.length)) * 7 + 12),
958
+ };
959
+ const plotW = Math.max(1, width - m.left - m.right);
960
+ const plotH = Math.max(1, height - m.top - m.bottom);
961
+ const t0 = points[0]?.t ?? 0;
962
+ const t1 = points.at(-1)?.t ?? 0;
963
+ const xOf = (/** @type {number} */ t) =>
964
+ t1 === t0 ? plotW / 2 : ((t - t0) / (t1 - t0)) * plotW;
965
+ const yOf = (/** @type {number} */ c) =>
966
+ plotH - ((c - lo) / (hi - lo)) * plotH;
967
+
968
+ const root = svg('svg', { width: '100%', height, role: 'img' });
969
+ root.setAttribute('aria-label', this.text('label'));
970
+ const plot = svg('g', { transform: `translate(${m.left},${m.top})` });
971
+ const grid = svg('g', {}, 'ex-ch-grid');
972
+ const yAxis = svg('g', {}, 'ex-ch-y');
973
+ for (const [i, v] of yTicks.entries()) {
974
+ const at = yOf(v).toFixed(2);
975
+ grid.append(svg('line', { x1: 0, x2: plotW, y1: at, y2: at }));
976
+ const label = svg('text', {
977
+ x: -12,
978
+ y: at,
979
+ dy: '0.32em',
980
+ 'text-anchor': 'end',
981
+ });
982
+ label.textContent = yLabels[i] ?? '';
983
+ yAxis.append(label);
984
+ }
985
+ const xAxis = svg('g', {}, 'ex-ch-x');
986
+ const axis = timeAxis(t0, t1, plotW);
987
+ for (const [i, t] of axis.ticks.entries()) {
988
+ const anchor =
989
+ i === 0 ? 'start' : i === axis.ticks.length - 1 ? 'end' : 'middle';
990
+ const label = svg('text', {
991
+ x: xOf(t).toFixed(2),
992
+ y: plotH + 8,
993
+ dy: '1em',
994
+ 'text-anchor': t1 === t0 ? 'middle' : anchor,
995
+ });
996
+ label.textContent = axis.labels[i] ?? '';
997
+ xAxis.append(label);
998
+ }
999
+ const d = points
1000
+ .map(
1001
+ (r, i) =>
1002
+ `${i ? 'L' : 'M'}${xOf(r.t).toFixed(2)},${yOf(r.p * 100).toFixed(2)}`
1003
+ )
1004
+ .join('');
1005
+ const last = points[points.length - 1] ?? { t: t0, p: 0 };
1006
+ const end = svg(
1007
+ 'circle',
1008
+ {
1009
+ cx: xOf(last.t).toFixed(2),
1010
+ cy: yOf(last.p * 100).toFixed(2),
1011
+ r: Math.min(5, plotH / 8),
1012
+ },
1013
+ 'ex-ch-end'
1014
+ );
1015
+ const cross = svg('line', { y1: 0, y2: plotH }, 'ex-ch-cross');
1016
+ const dot = svg('circle', { r: 5 }, 'ex-ch-dot');
1017
+ cross.setAttribute('hidden', '');
1018
+ dot.setAttribute('hidden', '');
1019
+ plot.append(
1020
+ grid,
1021
+ yAxis,
1022
+ xAxis,
1023
+ svg('path', { d }, 'ex-ch-line'),
1024
+ end,
1025
+ cross,
1026
+ dot
1027
+ );
1028
+ root.append(plot);
1029
+
1030
+ const tip = node('div', 'ex-ch-tip');
1031
+ tip.hidden = true;
1032
+ const when = node('span');
1033
+ const value = node('span');
1034
+ tip.append(when, value);
1035
+
1036
+ root.addEventListener('pointermove', (e) => {
1037
+ const box = root.getBoundingClientRect();
1038
+ const x = e.clientX - box.left - m.left;
1039
+ const at = t0 + (x / plotW) * (t1 - t0);
1040
+ let r = points[0] ?? last;
1041
+ for (const p of points)
1042
+ if (Math.abs(p.t - at) < Math.abs(r.t - at)) r = p;
1043
+ const px = xOf(r.t);
1044
+ const py = yOf(r.p * 100);
1045
+ for (const [k, v] of [
1046
+ ['x1', px],
1047
+ ['x2', px],
1048
+ ])
1049
+ cross.setAttribute(String(k), Number(v).toFixed(2));
1050
+ dot.setAttribute('cx', px.toFixed(2));
1051
+ dot.setAttribute('cy', py.toFixed(2));
1052
+ cross.removeAttribute('hidden');
1053
+ dot.removeAttribute('hidden');
1054
+ end.setAttribute('visibility', 'hidden');
1055
+ when.textContent = moment(r.t);
1056
+ value.textContent = String(fmt(r.p, 'cents'));
1057
+ tip.hidden = false;
1058
+ const half = tip.offsetWidth / 2;
1059
+ const left = Math.min(Math.max(px + m.left, half), width - half);
1060
+ tip.style.left = `${left}px`;
1061
+ tip.style.top = `${py + m.top - 8}px`;
1062
+ });
1063
+ root.addEventListener('pointerleave', () => {
1064
+ cross.setAttribute('hidden', '');
1065
+ dot.setAttribute('hidden', '');
1066
+ end.removeAttribute('visibility');
1067
+ tip.hidden = true;
1068
+ });
1069
+ this.replaceChildren(root, tip);
1070
+ if (t1 !== t0) {
1071
+ const at = axis.ticks.map(xOf);
1072
+ place(xAxis, at, plotW);
1073
+ document.fonts?.ready.then(() => place(xAxis, at, plotW));
1074
+ }
1075
+ }
1076
+ }
1077
+
1078
+ // The time labels as drawn: each measured, started where labelStart
1079
+ // puts it, and every second or third hidden where the measured row
1080
+ // crowds (chart.tsx ChartAxisBottom). Unmeasured, they keep their
1081
+ // anchors.
1082
+ /** @param {SVGElement} axis @param {number[]} at @param {number} width */
1083
+ function place(axis, at, width) {
1084
+ const texts = [...axis.querySelectorAll('text')];
1085
+ if (!texts.every((t) => typeof t.getComputedTextLength === 'function'))
1086
+ return;
1087
+ const widths = texts.map((t) => t.getComputedTextLength());
1088
+ let step = 1;
1089
+ for (; step < texts.length; step++) {
1090
+ const shown = at.filter((_, i) => i % step === 0);
1091
+ if (
1092
+ labelsApart(
1093
+ shown,
1094
+ widths.filter((_, i) => i % step === 0),
1095
+ width
1096
+ )
1097
+ )
1098
+ break;
1099
+ }
1100
+ const last = Math.floor((texts.length - 1) / step) * step;
1101
+ for (const [i, text] of texts.entries()) {
1102
+ const w = widths[i] ?? 0;
1103
+ text.setAttribute('text-anchor', 'start');
1104
+ text.setAttribute(
1105
+ 'x',
1106
+ labelStart(at[i] ?? 0, w, i, last, width).toFixed(2)
1107
+ );
1108
+ if (i % step) {
1109
+ text.setAttribute('visibility', 'hidden');
1110
+ text.setAttribute('aria-hidden', 'true');
1111
+ } else {
1112
+ text.removeAttribute('visibility');
1113
+ text.removeAttribute('aria-hidden');
1114
+ }
1115
+ }
1116
+ }
1117
+
1118
+ let tabsSeen = 0;
1119
+
1120
+ // Pill tabs as the web app's Tabs (packages/ui/src/components/tab/
1121
+ // tabs.tsx on Base UI): each child with data-label is a panel, the tab
1122
+ // list is the element's first child. Arrows move focus with wrap, Home
1123
+ // and End jump, and Enter, Space or a click selects; focus alone does
1124
+ // not. A child with data-disabled takes focus but never selects.
1125
+ class ExTabs extends KitElement {
1126
+ static observedAttributes = ['label', 'value'];
1127
+ /** @type {HTMLElement | null} */
1128
+ list = null;
1129
+ #id = `ex-tabs-${++tabsSeen}`;
1130
+ /** @type {MutationObserver | null} */
1131
+ #watch = null;
1132
+
1133
+ connectedCallback() {
1134
+ super.connectedCallback();
1135
+ this.#watch ??= new MutationObserver((records) => {
1136
+ const own = (/** @type {Node} */ n) => n === this.list;
1137
+ if (
1138
+ records.some((r) => ![...r.addedNodes, ...r.removedNodes].every(own))
1139
+ )
1140
+ this.render();
1141
+ });
1142
+ this.#watch.observe(this, { childList: true });
1143
+ }
1144
+
1145
+ disconnectedCallback() {
1146
+ this.#watch?.disconnect();
1147
+ this.#watch = null;
1148
+ }
1149
+
1150
+ /** @param {HTMLElement} panel */
1151
+ #select(panel) {
1152
+ const value = panel.dataset.label ?? '';
1153
+ this.setAttribute('value', value);
1154
+ this.dispatchEvent(
1155
+ new CustomEvent('change', { bubbles: true, detail: { value } })
1156
+ );
1157
+ }
1158
+
1159
+ render() {
1160
+ const first = this.firstElementChild;
1161
+ this.list ??=
1162
+ first instanceof HTMLElement && first.getAttribute('role') === 'tablist'
1163
+ ? first
1164
+ : node('div');
1165
+ const list = this.list;
1166
+ list.className = 'ex-tabs-list';
1167
+ list.setAttribute('role', 'tablist');
1168
+ const label = this.getAttribute('label');
1169
+ if (label) list.setAttribute('aria-label', label);
1170
+ else list.removeAttribute('aria-label');
1171
+ const panels = /** @type {HTMLElement[]} */ (
1172
+ [...this.children].filter(
1173
+ (c) =>
1174
+ c !== list &&
1175
+ c instanceof HTMLElement &&
1176
+ c.dataset.label !== undefined
1177
+ )
1178
+ );
1179
+ const wanted = this.getAttribute('value');
1180
+ const chosen =
1181
+ panels.find(
1182
+ (p) => p.dataset.label === wanted && p.dataset.disabled === undefined
1183
+ ) ?? panels.find((p) => p.dataset.disabled === undefined);
1184
+ const focused = list.contains(document.activeElement);
1185
+ const tabs = panels.map((panel, i) => {
1186
+ const on = panel === chosen;
1187
+ const off = panel.dataset.disabled !== undefined;
1188
+ const tab = node('button', 'ex-tab', panel.dataset.label);
1189
+ tab.setAttribute('type', 'button');
1190
+ tab.id = `${this.#id}-tab-${i}`;
1191
+ panel.id ||= `${this.#id}-panel-${i}`;
1192
+ tab.setAttribute('role', 'tab');
1193
+ tab.setAttribute('aria-selected', String(on));
1194
+ tab.setAttribute('aria-controls', panel.id);
1195
+ tab.tabIndex = on ? 0 : -1;
1196
+ if (off) {
1197
+ tab.setAttribute('aria-disabled', 'true');
1198
+ tab.dataset.disabled = '';
1199
+ }
1200
+ tab.addEventListener('click', () => {
1201
+ if (!off && !on) this.#select(panel);
1202
+ });
1203
+ panel.classList.add('ex-tab-panel');
1204
+ panel.setAttribute('role', 'tabpanel');
1205
+ panel.setAttribute('aria-labelledby', tab.id);
1206
+ panel.tabIndex = on ? 0 : -1;
1207
+ panel.hidden = !on;
1208
+ return tab;
1209
+ });
1210
+ list.onkeydown = (e) => {
1211
+ const at = tabs.indexOf(/** @type {HTMLElement} */ (e.target));
1212
+ if (at < 0) return;
1213
+ const n = tabs.length;
1214
+ const to =
1215
+ e.key === 'ArrowRight'
1216
+ ? (at + 1) % n
1217
+ : e.key === 'ArrowLeft'
1218
+ ? (at - 1 + n) % n
1219
+ : e.key === 'Home'
1220
+ ? 0
1221
+ : e.key === 'End'
1222
+ ? n - 1
1223
+ : -1;
1224
+ if (to < 0) return;
1225
+ e.preventDefault();
1226
+ tabs[to]?.focus();
1227
+ };
1228
+ list.replaceChildren(...tabs);
1229
+ if (this.firstChild !== list) this.prepend(list);
1230
+ this.#watch?.takeRecords();
1231
+ if (focused) tabs[chosen ? panels.indexOf(chosen) : 0]?.focus();
1232
+ }
1233
+ }
1234
+
1235
+ // The web app's market rows: the search window's EventsTable
1236
+ // (apps/web/components/discovery/events-table.tsx, SearchRowTitle and
1237
+ // SearchRowLabel in packages/ui/src/components/nav/search-list.tsx): a
1238
+ // 36px round tile, the title on one line, and under it the Yes price,
1239
+ // and the volume in compact dollars, parted by dots.
1240
+ class ExMarkets extends KitElement {
1241
+ static props = ['markets'];
1242
+ /** @type {Record<string, unknown>[]} */
1243
+ #markets = [];
1244
+
1245
+ get markets() {
1246
+ return this.#markets;
1247
+ }
1248
+ set markets(value) {
1249
+ this.#markets = list(value).filter((m) => m && typeof m === 'object');
1250
+ this.attributeChangedCallback();
1251
+ }
1252
+
1253
+ render() {
1254
+ if (!this.#markets.length) {
1255
+ this.replaceChildren(node('span', 'ex-muted', 'No markets'));
1256
+ return;
1257
+ }
1258
+ const rows = this.#markets.map((market) => {
1259
+ const title = String(cell(market, 'title'));
1260
+ const href = httpsUrl(String(cell(market, 'url')) || null);
1261
+ const row = node(href ? 'a' : 'div', 'ex-mkt');
1262
+ if (row instanceof HTMLAnchorElement && href) {
1263
+ row.href = href;
1264
+ row.target = '_blank';
1265
+ row.rel = 'noopener noreferrer';
1266
+ }
1267
+ const tile = node('span', 'ex-av', title.slice(0, 2));
1268
+ const src = httpsUrl(String(cell(market, 'image')) || null);
1269
+ if (src) {
1270
+ const img = node('img');
1271
+ if (img instanceof HTMLImageElement) {
1272
+ img.alt = '';
1273
+ img.src = src;
1274
+ img.onerror = () => img.remove();
1275
+ }
1276
+ tile.append(img);
1277
+ }
1278
+ const price = num(cell(market, 'price'));
1279
+ const volume = num(cell(market, 'volume'));
1280
+ const yes = node('span', '', 'Yes ');
1281
+ yes.append(
1282
+ node(
1283
+ 'b',
1284
+ price === null ? '' : 'ex-up',
1285
+ price === null ? '—' : fmt(price, 'cents')
1286
+ )
1287
+ );
1288
+ /** @type {HTMLElement[]} */
1289
+ const parts = [yes];
1290
+ if (volume !== null && volume > 0)
1291
+ parts.push(node('span', '', `Volume ${COMPACT_USD.format(volume)}`));
1292
+ const meta = node('div', 'ex-mkt-meta');
1293
+ for (const [i, p] of parts.entries()) {
1294
+ if (i) meta.append(node('span', '', '·'));
1295
+ meta.append(p);
1296
+ }
1297
+ const box = node('div');
1298
+ box.append(node('p', '', title), meta);
1299
+ row.append(tile, box);
1300
+ return row;
1301
+ });
1302
+ this.replaceChildren(...rows);
1303
+ }
1304
+ }
1305
+
510
1306
  /** @type {[string, CustomElementConstructor][]} */
511
1307
  const elements = [
512
1308
  ['ex-card', ExCard],
@@ -517,7 +1313,23 @@
517
1313
  ['ex-news-row', ExNewsRow],
518
1314
  ['ex-notification-row', ExNotificationRow],
519
1315
  ['ex-run-row', ExRunRow],
1316
+ ['ex-chart', ExChart],
1317
+ ['ex-tabs', ExTabs],
1318
+ ['ex-markets', ExMarkets],
520
1319
  ];
521
1320
  for (const [name, element] of elements)
522
1321
  if (!customElements.get(name)) customElements.define(name, element);
1322
+
1323
+ // ex-chart, ex-tabs and ex-markets bring their own rules, so they draw on
1324
+ // a page that inlines only the older rules, as a Claude artifact does.
1325
+ // Generated by scripts/gen.ts from SELF_CSS in src/styles.ts.
1326
+ const SELF_CSS =
1327
+ 'ex-chart,ex-markets{display:block}.ex-chart{position:relative}.ex-chart svg{display:block;overflow:visible;touch-action:pan-y;font:400 var(--text-xs)/calc(var(--spacing)*4) var(--font-sans);font-variant-numeric:tabular-nums}.ex-chart text{fill:var(--muted-foreground)}.ex-chart [hidden]{display:none}.ex-ch-grid line{stroke:var(--rule-dotted);stroke-width:1;stroke-dasharray:1 5;stroke-linecap:square}.ex-ch-line{fill:none;stroke:var(--chart-1-2);stroke-width:2;stroke-linecap:round;stroke-linejoin:round}.ex-ch-end,.ex-ch-dot{fill:var(--chart-1-2)}.ex-ch-cross{stroke:var(--border-emphasis);stroke-width:1}.ex-ch-tip{position:absolute;z-index:1;pointer-events:none;transform:translate(-50%,-100%);display:grid;gap:calc(var(--spacing)*.5);padding:var(--spacing) calc(var(--spacing)*2.5);border-radius:var(--radius-3xl);background:var(--tooltip);color:var(--tooltip-foreground);font:500 var(--text-sm)/var(--text-sm--line-height) var(--font-sans);white-space:nowrap}.ex-ch-tip[hidden]{display:none}.ex-ch-tip span+span{font-variant-numeric:tabular-nums}ex-tabs{display:flex;flex-direction:column;gap:calc(var(--spacing)*2)}.ex-tabs-list{position:relative;display:flex;align-items:center;gap:calc(var(--spacing)*2);width:fit-content;max-width:100%;overflow-x:auto}.ex-tab{display:inline-flex;align-items:center;gap:var(--spacing);flex-shrink:0;white-space:nowrap;user-select:none;height:calc(var(--spacing)*8);padding:0 calc(var(--spacing)*3);border:0;border-radius:var(--radius-full);background:none;color:var(--muted-foreground);font:500 var(--text-base)/var(--text-base--line-height) var(--font-sans);cursor:pointer;outline:none;transition:color .3s var(--ease-smooth),background-color .3s var(--ease-smooth)}.ex-tab:hover,.ex-tab[aria-selected=true]{color:var(--foreground)}.ex-tab[aria-selected=true]{background:var(--accent-emphasis)}.ex-tab:focus-visible{outline:none;box-shadow:0 0 0 2px var(--ring)}.ex-tab[data-disabled]{opacity:.5;pointer-events:none}.ex-tab-panel{flex:1;font-size:var(--text-sm);line-height:var(--text-sm--line-height);outline:none}.ex-tab-panel[hidden]{display:none}@media (prefers-reduced-motion:reduce){.ex-tab{transition:none}}.ex-mkt{display:flex;align-items:center;gap:calc(var(--spacing)*3);box-sizing:border-box;min-height:3.5rem;padding:var(--spacing) calc(var(--spacing)*4) var(--spacing) calc(var(--spacing)*3);color:inherit;text-decoration:none}.ex-mkt:hover{background:var(--background-hover)}.ex-mkt:focus-visible{outline-offset:-2px}.ex-mkt>div{flex:1;min-width:0}.ex-mkt p{margin:0;font:500 var(--text-base)/var(--text-base--line-height) var(--font-sans);overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.ex-mkt-meta{display:flex;flex-wrap:wrap;column-gap:calc(var(--spacing)*2);color:var(--muted-foreground);font-size:var(--text-sm);line-height:var(--text-sm--line-height);font-variant-numeric:tabular-nums}.ex-mkt-meta b,.ex-mkt-meta i{font-weight:inherit;font-style:normal}.ex-av{position:relative;flex:none;display:grid;place-items:center;width:calc(var(--spacing)*9);height:calc(var(--spacing)*9);overflow:hidden;border-radius:var(--radius-full);background:var(--raised);color:var(--muted-foreground-emphasis);font:500 var(--text-base)/var(--text-base--line-height) var(--font-sans)}.ex-av img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}.ex-av::after{content:"";position:absolute;inset:0;border-radius:inherit;box-shadow:inset 0 0 0 1px var(--border-emphasis)}';
1328
+ // One <style> per document, however often the script loads. Rules equal
1329
+ // to host-kit.css's own change nothing where that file is loaded too.
1330
+ if (!document.getElementById('ex-kit-css')) {
1331
+ const style = node('style', '', SELF_CSS);
1332
+ style.id = 'ex-kit-css';
1333
+ document.head.append(style);
1334
+ }
523
1335
  })();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elastics-ai/host-kit",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Elastics design tokens and custom elements for pages that Claude or ChatGPT publish.",
5
5
  "repository": {
6
6
  "type": "git",