@elastics-ai/host-kit 0.1.0 → 0.2.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,42 +1,42 @@
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 to load these files.
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.
4
4
 
5
5
  ```html
6
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@elastics-ai/host-kit@0.1.0/host-kit.css" integrity="sha384-…" crossorigin="anonymous">
7
- <script src="https://cdn.jsdelivr.net/npm/@elastics-ai/host-kit@0.1.0/host-kit.js" integrity="sha384-…" crossorigin="anonymous"></script>
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>
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 the full tags, with their `integrity` values, from `get_style_kit` or from `HOST_KIT_TAGS` in `src/index.ts`. The browser then refuses a file whose bytes differ from the ones this repository built.
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.
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
30
 
31
- 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.
31
+ `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
32
 
33
- A Claude artifact loads stylesheets only from Google Fonts. There, put the `css` from `get_style_kit` (the same rules as `host-kit.css`) in a `<style>` tag and load only the script.
33
+ `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
34
 
35
- `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.
35
+ 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
36
 
37
- ## Change the kit
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.
38
38
 
39
- `host-kit.css` and `src/tokens.generated.ts` are generated from `packages/ui/src/styles/globals.css` and `src/styles.ts`. `src/sri.generated.json` holds the sha384 of `host-kit.css` and `host-kit.js`. After a change to any of them, run `pnpm --filter @elastics-ai/host-kit gen`. A test fails while a generated file is out of date. A published version never changes, so a change to a published file also needs a version bump.
39
+ `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
40
 
41
41
  ## License
42
42
 
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:flex;flex-direction:column;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-sm)}.ex-table th{text-align:left;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.n,.ex-table th.n{text-align:right;font-variant-numeric:tabular-nums}.ex-lvl{position:relative;display:flex;justify-content:space-between;padding:2px 8px;font:var(--text-xs)/1.6 var(--font-mono)}.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-lvl>span{position:relative}.ex-lvl.bid>i+span{color:var(--positive-foreground)}.ex-lvl.ask>i+span{color:var(--negative-foreground)}.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:9999px;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:9999px;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}
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}
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
4
  ex-stat,ex-table,ex-book,ex-news-row,ex-notification-row,ex-run-row{display:block}
package/host-kit.js CHANGED
@@ -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
- tr.append(node('td', c.numeric ? 'n' : '', cell(row, c.key)));
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. Bar width is size over the largest size shown.
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
- /** @param {Level} l */
218
- const size = (l) => {
219
- const n = Number(l?.size);
220
- return Number.isFinite(n) && n > 0 ? n : 0;
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
- /** @param {Level} a @param {Level} b */
223
- const byPriceDesc = (a, b) => Number(b?.price) - Number(a?.price);
224
- const asks = [...this.#asks].sort(byPriceDesc);
225
- const bids = [...this.#bids].sort(byPriceDesc);
226
- const largest = Math.max(0, ...asks.map(size), ...bids.map(size));
227
- /** @param {Level} l @param {'ask' | 'bid'} side */
228
- const row = (l, side) => {
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 = `${largest ? (size(l) / largest) * 100 : 0}%`;
375
+ bar.style.width = `${Math.min(100, (r.cumQty / scale) * 100)}%`;
231
376
  const el = node('div', `ex-lvl ${side}`);
232
- el.append(bar, node('span', '', l?.price), node('span', '', l?.size));
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
- this.replaceChildren(
236
- ...asks.map((l) => row(l, 'ask')),
237
- ...bids.map((l) => row(l, 'bid'))
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
+ )
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')
238
445
  );
446
+ this.replaceChildren(book);
239
447
  }
240
448
  }
241
449
 
package/package.json CHANGED
@@ -1,7 +1,12 @@
1
1
  {
2
2
  "name": "@elastics-ai/host-kit",
3
- "version": "0.1.0",
3
+ "version": "0.2.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,