@elastics-ai/host-kit 0.1.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 +18 -13
- package/host-kit.css +3 -3
- package/host-kit.js +1043 -23
- package/package.json +6 -1
package/README.md
CHANGED
|
@@ -1,42 +1,47 @@
|
|
|
1
1
|
# @elastics-ai/host-kit
|
|
2
2
|
|
|
3
|
-
Elastics design tokens and
|
|
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.
|
|
7
|
-
<script src="https://cdn.jsdelivr.net/npm/@elastics-ai/host-kit@0.
|
|
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>
|
|
11
11
|
<ex-book></ex-book>
|
|
12
12
|
</ex-card>
|
|
13
13
|
<script>
|
|
14
|
-
document.querySelector('ex-book').bids = [['62', '150'], ['61', '90']];
|
|
14
|
+
document.querySelector('ex-book').bids = [['0.62', '150'], ['0.61', '90']];
|
|
15
15
|
</script>
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
-
Take
|
|
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
|
|---|---|
|
|
22
22
|
| `ex-card` | `heading`, `state`, `label`; children go in the card |
|
|
23
|
-
| `ex-stat` | `label`, `value`, `change`, `trend` (`up` or `down`) |
|
|
23
|
+
| `ex-stat` | `label`, `value`, `format`, `change`, `trend` (`up` or `down`) |
|
|
24
24
|
| `ex-badge` | `state` (`live`, `stale`, `failed`, `off`), `label` |
|
|
25
|
-
| `ex-table` | `.columns = [{key, label, numeric}]`, `.rows = [{...}]` |
|
|
26
|
-
| `ex-book` | `.asks`, `.bids` as `[[price, size]]` or `[{price, size}]` |
|
|
25
|
+
| `ex-table` | `.columns = [{key, label, numeric, format, side}]`, `.rows = [{...}]` |
|
|
26
|
+
| `ex-book` | `.asks`, `.bids` as `[[price, size]]` or `[{price, size}]`; `price="quote"` for an instrument |
|
|
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
|
|
|
33
|
-
|
|
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.
|
|
34
37
|
|
|
35
|
-
`
|
|
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.
|
|
36
39
|
|
|
37
|
-
|
|
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.
|
|
38
41
|
|
|
39
|
-
|
|
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.
|
|
43
|
+
|
|
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
|
|
|
41
46
|
## License
|
|
42
47
|
|
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);--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}
|
|
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:
|
|
4
|
-
ex-stat,ex-table,ex-book,ex-news-row,ex-notification-row,ex-run-row{display:block}
|
|
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
|
+
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}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:
|
|
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.
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// The file has no import or export, so it loads as <script src> as well as
|
|
7
7
|
// type="module". Chrome refuses module scripts from a file:// page.
|
|
8
8
|
(() => {
|
|
9
|
-
/** @typedef {{ key: string, label: string, numeric?: boolean }} Column */
|
|
9
|
+
/** @typedef {{ key: string, label: string, numeric?: boolean, format?: string, side?: boolean | string }} Column */
|
|
10
10
|
/** @typedef {{ price: number | string, size: number | string }} Level */
|
|
11
11
|
/** @typedef {Level | [number | string, number | string]} LevelIn */
|
|
12
12
|
|
|
@@ -71,6 +71,88 @@
|
|
|
71
71
|
);
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
// A number from a feed: a finite number, or a decimal string that may
|
|
75
|
+
// group its thousands with commas. Anything else is not a number. The
|
|
76
|
+
// rules of parseNumericValue (packages/core/src/math/parse.ts:5-24).
|
|
77
|
+
/** @param {unknown} value */
|
|
78
|
+
function num(value) {
|
|
79
|
+
if (typeof value === 'number') return Number.isFinite(value) ? value : null;
|
|
80
|
+
if (typeof value !== 'string') return null;
|
|
81
|
+
const text = value.trim();
|
|
82
|
+
if (!text) return null;
|
|
83
|
+
if (text.includes(',') && !/^-?\d{1,3}(,\d{3})+(\.\d+)?$/.test(text))
|
|
84
|
+
return null;
|
|
85
|
+
const n = Number(text.replace(/,/g, ''));
|
|
86
|
+
return Number.isFinite(n) ? n : null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const USD = new Intl.NumberFormat('en-US', {
|
|
90
|
+
style: 'currency',
|
|
91
|
+
currency: 'USD',
|
|
92
|
+
minimumFractionDigits: 2,
|
|
93
|
+
maximumFractionDigits: 2,
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
// The web app's own number formats, from packages/core/src.
|
|
97
|
+
/** @type {Record<string, (n: number) => string>} */
|
|
98
|
+
const FORMATS = {
|
|
99
|
+
// A 0 to 1 price in cents to one decimal, "0.4¢":
|
|
100
|
+
// formatOrderBookPrice, math/orderbook.ts:112-114.
|
|
101
|
+
cents: (n) =>
|
|
102
|
+
`${(n * 100).toLocaleString('en-US', { maximumFractionDigits: 1 })}¢`,
|
|
103
|
+
// Dollars, "$3,113.68": formatCurrency, formatters/currency.ts:4-9,36-37.
|
|
104
|
+
usd: (n) => {
|
|
105
|
+
const text = USD.format(n);
|
|
106
|
+
return text === '-$0.00' ? '$0.00' : text;
|
|
107
|
+
},
|
|
108
|
+
// Grouped to two decimals, "169,439.48": formatOrderBookAmount,
|
|
109
|
+
// math/orderbook.ts:117-122.
|
|
110
|
+
amount: (n) =>
|
|
111
|
+
n.toLocaleString('en-US', {
|
|
112
|
+
minimumFractionDigits: 2,
|
|
113
|
+
maximumFractionDigits: 2,
|
|
114
|
+
}),
|
|
115
|
+
// Grouped, at most two decimals, "1,250" or "12.5": formatQuantity,
|
|
116
|
+
// formatters/quantity.ts:3-5,12-17.
|
|
117
|
+
number: (n) => {
|
|
118
|
+
const text = n.toLocaleString('en-US', { maximumFractionDigits: 2 });
|
|
119
|
+
return text === '-0' ? '0' : text;
|
|
120
|
+
},
|
|
121
|
+
// A numeric column without a format: grouped, with every digit kept,
|
|
122
|
+
// so 0.0000123 stays 0.0000123.
|
|
123
|
+
grouped: (n) => {
|
|
124
|
+
const text = n.toLocaleString('en-US', { maximumFractionDigits: 20 });
|
|
125
|
+
return text === '-0' ? '0' : text;
|
|
126
|
+
},
|
|
127
|
+
// An instrument's price in its quote currency: formatPrice,
|
|
128
|
+
// formatters/currency.ts:108-116.
|
|
129
|
+
quote: (n) =>
|
|
130
|
+
n === 0
|
|
131
|
+
? '—'
|
|
132
|
+
: n.toLocaleString('en-US', {
|
|
133
|
+
minimumFractionDigits: 0,
|
|
134
|
+
maximumFractionDigits: n >= 1000 ? 2 : n >= 1 ? 4 : 8,
|
|
135
|
+
}),
|
|
136
|
+
// An instrument's size in its base asset: formatSize,
|
|
137
|
+
// formatters/quantity.ts:22-26.
|
|
138
|
+
base: (n) =>
|
|
139
|
+
n === 0
|
|
140
|
+
? '—'
|
|
141
|
+
: n.toLocaleString('en-US', { maximumSignificantDigits: 6 }),
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
// A value in a named format; a value that is not a number, or a format
|
|
145
|
+
// the kit does not know, prints as it came.
|
|
146
|
+
/** @param {unknown} value @param {unknown} format */
|
|
147
|
+
function fmt(value, format) {
|
|
148
|
+
const f =
|
|
149
|
+
typeof format === 'string' && Object.hasOwn(FORMATS, format)
|
|
150
|
+
? FORMATS[format]
|
|
151
|
+
: undefined;
|
|
152
|
+
const n = f ? num(value) : null;
|
|
153
|
+
return f && n !== null ? f(n) : (value ?? '');
|
|
154
|
+
}
|
|
155
|
+
|
|
74
156
|
class KitElement extends HTMLElement {
|
|
75
157
|
/** Properties that a page can set before this script defines the tag. */
|
|
76
158
|
static props = /** @type {string[]} */ ([]);
|
|
@@ -130,13 +212,13 @@
|
|
|
130
212
|
}
|
|
131
213
|
|
|
132
214
|
class ExStat extends KitElement {
|
|
133
|
-
static observedAttributes = ['label', 'value', 'change', 'trend'];
|
|
215
|
+
static observedAttributes = ['label', 'value', 'format', 'change', 'trend'];
|
|
134
216
|
|
|
135
217
|
render() {
|
|
136
218
|
const box = node('div', 'ex-stat');
|
|
137
219
|
box.append(
|
|
138
220
|
node('span', 'ex-muted', this.text('label')),
|
|
139
|
-
node('b', '', this.text('value'))
|
|
221
|
+
node('b', '', fmt(this.text('value'), this.getAttribute('format')))
|
|
140
222
|
);
|
|
141
223
|
if (this.hasAttribute('change')) {
|
|
142
224
|
const trend = this.getAttribute('trend');
|
|
@@ -177,8 +259,29 @@
|
|
|
177
259
|
const body = node('tbody');
|
|
178
260
|
for (const row of this.#rows) {
|
|
179
261
|
const tr = node('tr');
|
|
180
|
-
for (const c of this.#columns)
|
|
181
|
-
|
|
262
|
+
for (const c of this.#columns) {
|
|
263
|
+
const value = cell(row, c.key);
|
|
264
|
+
// side: true tints a cell that says Buy or Sell; side: "<key>"
|
|
265
|
+
// tints the cell by the row's own side, as the web app's tape
|
|
266
|
+
// tints its price (MarketTapeRow,
|
|
267
|
+
// packages/ui/src/components/patterns/market-book.tsx).
|
|
268
|
+
const said =
|
|
269
|
+
c.side === true
|
|
270
|
+
? value
|
|
271
|
+
: typeof c.side === 'string'
|
|
272
|
+
? cell(row, c.side)
|
|
273
|
+
: '';
|
|
274
|
+
const side = String(said).trim().toLowerCase();
|
|
275
|
+
const tone =
|
|
276
|
+
side === 'buy' ? 'ex-up' : side === 'sell' ? 'ex-down' : '';
|
|
277
|
+
tr.append(
|
|
278
|
+
node(
|
|
279
|
+
'td',
|
|
280
|
+
[c.numeric ? 'n' : '', tone].filter(Boolean).join(' '),
|
|
281
|
+
fmt(value, c.format ?? (c.numeric ? 'grouped' : null))
|
|
282
|
+
)
|
|
283
|
+
);
|
|
284
|
+
}
|
|
182
285
|
body.append(tr);
|
|
183
286
|
}
|
|
184
287
|
const thead = node('thead');
|
|
@@ -190,9 +293,10 @@
|
|
|
190
293
|
}
|
|
191
294
|
|
|
192
295
|
// Asks above with the best ask last, bids below with the best bid first,
|
|
193
|
-
// as in the product's book.
|
|
296
|
+
// as in the product's book.
|
|
194
297
|
class ExBook extends KitElement {
|
|
195
298
|
static props = ['asks', 'bids'];
|
|
299
|
+
static observedAttributes = ['price'];
|
|
196
300
|
/** @type {Level[]} */
|
|
197
301
|
#asks = [];
|
|
198
302
|
/** @type {Level[]} */
|
|
@@ -213,29 +317,133 @@
|
|
|
213
317
|
this.attributeChangedCallback();
|
|
214
318
|
}
|
|
215
319
|
|
|
320
|
+
// The web app's book (apps/web/components/markets/order-book.tsx and
|
|
321
|
+
// instrument-order-book.tsx): Price, Size and Total, the spread on its
|
|
322
|
+
// own row between the halves. A prediction market's 0 to 1 prices print
|
|
323
|
+
// in cents and its Total is the running dollar value; price="quote"
|
|
324
|
+
// prints an instrument's prices and its Total is the running size.
|
|
216
325
|
render() {
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
326
|
+
const quote = this.getAttribute('price') === 'quote';
|
|
327
|
+
/** @param {Level[]} side */
|
|
328
|
+
const parse = (side) =>
|
|
329
|
+
side.map((l) => ({
|
|
330
|
+
l,
|
|
331
|
+
price: num(l?.price),
|
|
332
|
+
size: Math.max(0, num(l?.size) ?? 0),
|
|
333
|
+
cumQty: 0,
|
|
334
|
+
cumValue: 0,
|
|
335
|
+
}));
|
|
336
|
+
/** @typedef {ReturnType<typeof parse>[number]} Row */
|
|
337
|
+
// A level whose price is not a number is shown as it came, at the far
|
|
338
|
+
// end of its side, and takes no part in the depth or the spread.
|
|
339
|
+
/** @param {Row[]} rows */
|
|
340
|
+
const priced = (rows) =>
|
|
341
|
+
rows
|
|
342
|
+
.filter((r) => r.price !== null)
|
|
343
|
+
.sort((a, b) => Number(b.price) - Number(a.price));
|
|
344
|
+
/** @param {Row[]} rows */
|
|
345
|
+
const unpriced = (rows) => rows.filter((r) => r.price === null);
|
|
346
|
+
const allAsks = parse(this.#asks);
|
|
347
|
+
const allBids = parse(this.#bids);
|
|
348
|
+
const asks = priced(allAsks);
|
|
349
|
+
const bids = priced(allBids);
|
|
350
|
+
// Depth runs outward from the top of book, and the bars share one
|
|
351
|
+
// scale: the running size 13 levels out on the deeper side
|
|
352
|
+
// (processOrderBookLevels and computeMaxCumQty,
|
|
353
|
+
// packages/core/src/math/orderbook.ts:12,30-67).
|
|
354
|
+
/** @param {Row[]} outward */
|
|
355
|
+
const accumulate = (outward) => {
|
|
356
|
+
let cumQty = 0;
|
|
357
|
+
let cumValue = 0;
|
|
358
|
+
for (const r of outward) {
|
|
359
|
+
cumQty += r.size;
|
|
360
|
+
cumValue += Number(r.price) * r.size;
|
|
361
|
+
r.cumQty = cumQty;
|
|
362
|
+
r.cumValue = cumValue;
|
|
363
|
+
}
|
|
364
|
+
return outward.slice(0, 13).at(-1)?.cumQty ?? 0;
|
|
221
365
|
};
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
366
|
+
const scale = Math.max(
|
|
367
|
+
accumulate([...asks].reverse()),
|
|
368
|
+
accumulate(bids),
|
|
369
|
+
1
|
|
370
|
+
);
|
|
371
|
+
const priceFormat = quote ? 'quote' : 'cents';
|
|
372
|
+
/** @param {Row} r @param {'ask' | 'bid'} side */
|
|
373
|
+
const row = (r, side) => {
|
|
229
374
|
const bar = node('i');
|
|
230
|
-
bar.style.width = `${
|
|
375
|
+
bar.style.width = `${Math.min(100, (r.cumQty / scale) * 100)}%`;
|
|
231
376
|
const el = node('div', `ex-lvl ${side}`);
|
|
232
|
-
|
|
377
|
+
const total =
|
|
378
|
+
r.price === null
|
|
379
|
+
? '—'
|
|
380
|
+
: quote
|
|
381
|
+
? fmt(r.cumQty, 'base')
|
|
382
|
+
: `$${fmt(r.cumValue, 'amount')}`;
|
|
383
|
+
el.append(
|
|
384
|
+
bar,
|
|
385
|
+
node(
|
|
386
|
+
'span',
|
|
387
|
+
side === 'bid' ? 'ex-up' : 'ex-down',
|
|
388
|
+
fmt(r.l?.price, priceFormat)
|
|
389
|
+
),
|
|
390
|
+
node('span', '', fmt(r.size, quote ? 'base' : 'amount')),
|
|
391
|
+
node('span', quote ? 'm' : '', total)
|
|
392
|
+
);
|
|
233
393
|
return el;
|
|
234
394
|
};
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
395
|
+
// An empty side says so, as the web app's book does
|
|
396
|
+
// (order-book.tsx emptyText).
|
|
397
|
+
/** @param {Row[]} rows @param {'ask' | 'bid'} side @param {string} text */
|
|
398
|
+
const half = (rows, side, text) => {
|
|
399
|
+
if (rows.length) return rows.map((r) => row(r, side));
|
|
400
|
+
const el = node('div', `ex-lvl ${side}`);
|
|
401
|
+
el.append(node('span', 'm e', text));
|
|
402
|
+
return [el];
|
|
403
|
+
};
|
|
404
|
+
// Asks run far to near, bids near to far, so an unpriced level sits
|
|
405
|
+
// first among the asks and last among the bids.
|
|
406
|
+
const askRows = [...unpriced(allAsks), ...asks];
|
|
407
|
+
const bidRows = [...bids, ...unpriced(allBids)];
|
|
408
|
+
// The best bid and ask, and the spread as a share of the mid, or for
|
|
409
|
+
// an instrument of the best bid to three places (spreadReading,
|
|
410
|
+
// packages/core/src/math/orderbook.ts:76-104; instrumentSpread,
|
|
411
|
+
// packages/core/src/math/instruments.ts:452-462).
|
|
412
|
+
const bestAsk = asks.at(-1)?.price ?? null;
|
|
413
|
+
const bestBid = bids[0]?.price ?? null;
|
|
414
|
+
const spread =
|
|
415
|
+
bestAsk != null && bestBid != null ? Math.abs(bestAsk - bestBid) : null;
|
|
416
|
+
const mid =
|
|
417
|
+
bestAsk != null && bestBid != null
|
|
418
|
+
? (bestAsk + bestBid) / 2
|
|
419
|
+
: (bestBid ?? bestAsk ?? 0);
|
|
420
|
+
const base = quote ? (bestBid ?? 0) : mid;
|
|
421
|
+
const spreadRow = node('div', 'ex-spread');
|
|
422
|
+
spreadRow.append(
|
|
423
|
+
node('span', 'm', 'Spread'),
|
|
424
|
+
node('span', '', spread === null ? '—' : fmt(spread, priceFormat)),
|
|
425
|
+
node(
|
|
426
|
+
'span',
|
|
427
|
+
'm',
|
|
428
|
+
spread !== null && base > 0
|
|
429
|
+
? `${((spread / base) * 100).toFixed(quote ? 3 : 2)}%`
|
|
430
|
+
: '—'
|
|
431
|
+
)
|
|
238
432
|
);
|
|
433
|
+
const head = node('div', 'ex-bk-head');
|
|
434
|
+
head.append(
|
|
435
|
+
node('span', '', 'Price'),
|
|
436
|
+
node('span', '', 'Size'),
|
|
437
|
+
node('span', '', 'Total')
|
|
438
|
+
);
|
|
439
|
+
const book = node('div', quote ? 'ex-bk q' : 'ex-bk');
|
|
440
|
+
book.append(
|
|
441
|
+
head,
|
|
442
|
+
...half(askRows, 'ask', 'No Asks'),
|
|
443
|
+
spreadRow,
|
|
444
|
+
...half(bidRows, 'bid', 'No Bids')
|
|
445
|
+
);
|
|
446
|
+
this.replaceChildren(book);
|
|
239
447
|
}
|
|
240
448
|
}
|
|
241
449
|
|
|
@@ -299,6 +507,802 @@
|
|
|
299
507
|
}
|
|
300
508
|
}
|
|
301
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
|
+
|
|
302
1306
|
/** @type {[string, CustomElementConstructor][]} */
|
|
303
1307
|
const elements = [
|
|
304
1308
|
['ex-card', ExCard],
|
|
@@ -309,7 +1313,23 @@
|
|
|
309
1313
|
['ex-news-row', ExNewsRow],
|
|
310
1314
|
['ex-notification-row', ExNotificationRow],
|
|
311
1315
|
['ex-run-row', ExRunRow],
|
|
1316
|
+
['ex-chart', ExChart],
|
|
1317
|
+
['ex-tabs', ExTabs],
|
|
1318
|
+
['ex-markets', ExMarkets],
|
|
312
1319
|
];
|
|
313
1320
|
for (const [name, element] of elements)
|
|
314
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
|
+
}
|
|
315
1335
|
})();
|
package/package.json
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@elastics-ai/host-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Elastics design tokens and custom elements for pages that Claude or ChatGPT publish.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "https://github.com/elastics-ai/elastics-dev-ui",
|
|
8
|
+
"directory": "packages/host-kit"
|
|
9
|
+
},
|
|
5
10
|
"license": "UNLICENSED",
|
|
6
11
|
"type": "module",
|
|
7
12
|
"sideEffects": true,
|