@kermodes/react 0.0.0-stage → 0.3.13-dev.68.g32b767a

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.
@@ -0,0 +1,280 @@
1
+ // react/src/index.tsx
2
+ import {
3
+ createContext,
4
+ useContext,
5
+ useEffect,
6
+ useMemo,
7
+ useRef,
8
+ useState
9
+ } from "react";
10
+ import { tableFromIPC } from "apache-arrow";
11
+ import {
12
+ KermodesConnection,
13
+ toBytes
14
+ } from "@kermodes/client";
15
+
16
+ // react/src/rows.ts
17
+ import { DataType } from "apache-arrow";
18
+ function windowRows2(table, start, from, count) {
19
+ const first = Math.max(from - start, 0);
20
+ const last = Math.min(from + count - start, table.numRows);
21
+ const columns = table.schema.fields.map((field, index) => ({
22
+ name: field.name,
23
+ vector: table.getChildAt(index),
24
+ isTime: DataType.isTimestamp(field.type) || DataType.isDate(field.type)
25
+ }));
26
+ const rows = [];
27
+ for (let i = first;i < last; i += 1) {
28
+ const row = {};
29
+ for (const { name, vector, isTime } of columns) {
30
+ row[name] = plain(vector?.get(i) ?? null, isTime);
31
+ }
32
+ rows.push(row);
33
+ }
34
+ return rows;
35
+ }
36
+ function plain(value, isTime) {
37
+ if (value == null) {
38
+ return null;
39
+ }
40
+ if (typeof value === "bigint") {
41
+ const number = Number(value);
42
+ return Number.isSafeInteger(number) ? isTime ? new Date(number) : number : value;
43
+ }
44
+ if (isTime && typeof value === "number") {
45
+ return new Date(value);
46
+ }
47
+ return value;
48
+ }
49
+ function rowRange2(total, { offset = 0, limit = 100, last }) {
50
+ if (last != null) {
51
+ return { from: Math.max(total - last, 0), count: last };
52
+ }
53
+ return { from: offset, count: limit };
54
+ }
55
+ function sortKeys2(names) {
56
+ return names.map((name) => name.startsWith("-") ? { column: name.slice(1), descending: true } : { column: name, descending: false });
57
+ }
58
+ function tableStatus2(state, hasRows) {
59
+ if (state.error != null) {
60
+ return state.retrying === true ? "reconnecting" : "failed";
61
+ }
62
+ if (!hasRows || state.status.startsWith("loading")) {
63
+ return "loading";
64
+ }
65
+ return state.status === "static" ? "static" : "live";
66
+ }
67
+
68
+ // react/src/fake.ts
69
+ import { tableFromJSON, tableToIPC, Table } from "apache-arrow";
70
+ function fakeKermodes2(tables) {
71
+ const data = new Map(Object.entries(tables));
72
+ const views = new Set;
73
+ const changes = new Set;
74
+ let cycle = 0;
75
+ const listing = () => [...data].map(([name, rows]) => ({ name, columns: columnsOf(rows), refreshing: true }));
76
+ const push = (view) => {
77
+ const rows = data.get(view.table);
78
+ if (rows == null || view.viewport == null) {
79
+ return;
80
+ }
81
+ const { top, bottom } = view.viewport;
82
+ const window = rows.slice(top, bottom + 1);
83
+ const ipc = tableToIPC(window.length > 0 ? tableFromJSON(window) : new Table, "stream");
84
+ const keys = BigUint64Array.from(window, (_, i) => BigInt(top + i));
85
+ const header = { type: "rows", start: top, total: rows.length, cycle };
86
+ view.messages.forEach((handler) => handler(header, [ipc, keys]));
87
+ };
88
+ const update = (view) => {
89
+ const rows = data.get(view.table);
90
+ view.state = rows == null ? { ...view.state, error: `no table ${view.table}`, retrying: false } : { ...view.state, columns: columnsOf(rows), row_count: rows.length, status: "ticking" };
91
+ view.states.forEach((handler) => handler());
92
+ };
93
+ return {
94
+ get tables() {
95
+ return listing();
96
+ },
97
+ onChange(listener) {
98
+ changes.add(listener);
99
+ return () => changes.delete(listener);
100
+ },
101
+ open(table) {
102
+ const view = {
103
+ table,
104
+ viewport: null,
105
+ state: {
106
+ columns: [],
107
+ row_count: 0,
108
+ status: "loading",
109
+ sort: [],
110
+ filters: {},
111
+ filter_errors: {},
112
+ applied: 0
113
+ },
114
+ messages: new Set,
115
+ states: new Set
116
+ };
117
+ views.add(view);
118
+ update(view);
119
+ return {
120
+ send(message) {
121
+ if (message.type === "viewport") {
122
+ view.viewport = { top: message.top, bottom: message.bottom };
123
+ push(view);
124
+ }
125
+ },
126
+ onMessage(handler) {
127
+ view.messages.add(handler);
128
+ return () => view.messages.delete(handler);
129
+ },
130
+ state: () => view.state,
131
+ onState(handler) {
132
+ view.states.add(handler);
133
+ return () => view.states.delete(handler);
134
+ },
135
+ close() {
136
+ views.delete(view);
137
+ }
138
+ };
139
+ },
140
+ close() {
141
+ views.clear();
142
+ },
143
+ set(table, rows) {
144
+ const isNew = !data.has(table);
145
+ data.set(table, rows);
146
+ cycle += 1;
147
+ for (const view of views) {
148
+ if (view.table === table) {
149
+ update(view);
150
+ push(view);
151
+ }
152
+ }
153
+ if (isNew) {
154
+ changes.forEach((listener) => listener());
155
+ }
156
+ }
157
+ };
158
+ }
159
+ function columnsOf(rows) {
160
+ const first = rows[0] ?? {};
161
+ return Object.entries(first).map(([name, value]) => ({
162
+ name,
163
+ type: typeof value === "number" ? "float64" : typeof value === "bigint" ? "int64" : typeof value === "boolean" ? "bool" : value instanceof Date ? "timestamp" : "utf8"
164
+ }));
165
+ }
166
+
167
+ // react/src/index.tsx
168
+ import { jsx } from "react/jsx-runtime";
169
+ var ConnectionContext = createContext(null);
170
+ function sameOrigin() {
171
+ return `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/ws`;
172
+ }
173
+ function KermodesProvider2({
174
+ url,
175
+ connection: given,
176
+ children
177
+ }) {
178
+ const connection = useMemo(() => given ?? new KermodesConnection(url ?? sameOrigin()), [given, url]);
179
+ useEffect(() => given == null ? () => connection.close() : undefined, [connection, given]);
180
+ return /* @__PURE__ */ jsx(ConnectionContext.Provider, {
181
+ value: connection,
182
+ children
183
+ });
184
+ }
185
+ function useKermodes2() {
186
+ const connection = useContext(ConnectionContext);
187
+ if (connection == null) {
188
+ throw new Error("useKermodes needs a KermodesProvider around it");
189
+ }
190
+ return connection;
191
+ }
192
+ function useTables2() {
193
+ const connection = useKermodes2();
194
+ const [tables, setTables] = useState(connection.tables);
195
+ useEffect(() => {
196
+ setTables(connection.tables);
197
+ return connection.onChange(() => setTables(connection.tables));
198
+ }, [connection]);
199
+ return tables;
200
+ }
201
+ function useTable2(name, { sort = [], filters = {}, offset = 0, limit = 100, last } = {}) {
202
+ const connection = useKermodes2();
203
+ const [state, setState] = useState({
204
+ rows: [],
205
+ total: 0,
206
+ columns: [],
207
+ status: "loading",
208
+ error: null
209
+ });
210
+ const view = useRef(null);
211
+ const range = useRef({ offset, limit, last });
212
+ range.current = { offset, limit, last };
213
+ const sentViewport = useRef("");
214
+ const sendViewport = useRef((total) => {
215
+ const { from, count } = rowRange2(total, range.current);
216
+ const asked = `${from}:${count}`;
217
+ if (view.current != null && asked !== sentViewport.current) {
218
+ sentViewport.current = asked;
219
+ view.current.send({ type: "viewport", top: from, bottom: from + Math.max(count, 1) - 1 });
220
+ }
221
+ }).current;
222
+ useEffect(() => {
223
+ const opened = connection.open(name);
224
+ view.current = opened;
225
+ sentViewport.current = "";
226
+ let window = null;
227
+ const publish = () => {
228
+ const current = opened.state();
229
+ const { from, count } = rowRange2(current.row_count, range.current);
230
+ setState({
231
+ rows: window == null ? [] : windowRows2(window.table, window.start, from, count),
232
+ total: current.row_count,
233
+ columns: current.columns,
234
+ status: tableStatus2(current, window != null),
235
+ error: current.error ?? null
236
+ });
237
+ sendViewport(current.row_count);
238
+ };
239
+ const stopRows = opened.onMessage((header, buffers) => {
240
+ if (header.type === "rows") {
241
+ window = { start: header.start, table: tableFromIPC(toBytes(buffers[0])) };
242
+ publish();
243
+ }
244
+ });
245
+ const stopState = opened.onState(publish);
246
+ sendViewport(opened.state().row_count);
247
+ return () => {
248
+ stopRows();
249
+ stopState();
250
+ opened.close();
251
+ view.current = null;
252
+ };
253
+ }, [connection, name, sendViewport]);
254
+ const sortKey = JSON.stringify(sort);
255
+ const filterKey = JSON.stringify(filters);
256
+ const sent = useRef({ name: "", sort: "[]", filters: "{}" });
257
+ useEffect(() => {
258
+ const current = view.current;
259
+ if (current == null) {
260
+ return;
261
+ }
262
+ if (sent.current.name !== name) {
263
+ sent.current = { name, sort: "[]", filters: "{}" };
264
+ }
265
+ if (sortKey !== sent.current.sort) {
266
+ current.send({ type: "sort", by: sortKeys2(JSON.parse(sortKey)) });
267
+ sent.current.sort = sortKey;
268
+ }
269
+ if (filterKey !== sent.current.filters) {
270
+ current.send({ type: "filter", filters: JSON.parse(filterKey) });
271
+ sent.current.filters = filterKey;
272
+ }
273
+ }, [name, sortKey, filterKey]);
274
+ useEffect(() => {
275
+ sendViewport(state.total);
276
+ }, [offset, limit, last, state.total, sendViewport]);
277
+ return state;
278
+ }
279
+
280
+ export { windowRows2, rowRange2, sortKeys2, tableStatus2, fakeKermodes2, KermodesProvider2, useKermodes2, useTables2, useTable2 };
@@ -0,0 +1,10 @@
1
+ import type { TableInfo, ViewerChannel } from '@kermodes/client';
2
+ /** What the hooks use of a connection: a `KermodesConnection`, or `fakeKermodes` in tests */
3
+ export type Connection = {
4
+ readonly tables: readonly TableInfo[];
5
+ onChange(listener: () => void): () => void;
6
+ open(table: string): ViewerChannel & {
7
+ close(): void;
8
+ };
9
+ close(): void;
10
+ };
package/dist/fake.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ import type { Connection } from './connection';
2
+ import type { TableRow } from './rows';
3
+ /** A connection serving fixed rows, for testing components that use `useTable` */
4
+ export type FakeKermodes = Connection & {
5
+ /** Replaces a table's rows, as a tick would: every view of it gets them */
6
+ set(table: string, rows: readonly TableRow[]): void;
7
+ };
8
+ /**
9
+ * A stand-in for a Kermodes server, serving `tables` (name to rows) to `useTable` through the
10
+ * same Arrow decoding as the real one. Rows come in the order given: sorting and filtering are
11
+ * the server's, so tests give the rows a component should see. A table it does not have fails
12
+ * as a missing table does.
13
+ *
14
+ * const kermodes = fakeKermodes({ 'md.ticks': [{ sym: 'AAPL', price: 189.5 }] });
15
+ * render(<KermodesProvider connection={kermodes}><Tape /></KermodesProvider>);
16
+ * kermodes.set('md.ticks', [...]);
17
+ */
18
+ export declare function fakeKermodes(tables: Readonly<Record<string, readonly TableRow[]>>): FakeKermodes;
@@ -0,0 +1,54 @@
1
+ import { type ReactNode } from 'react';
2
+ import { type TableInfo, type ViewportColumn } from '@kermodes/client';
3
+ import type { Connection } from './connection';
4
+ import { type TableRow, type TableStatus } from './rows';
5
+ export type { Connection } from './connection';
6
+ export { fakeKermodes, type FakeKermodes } from './fake';
7
+ export { rowRange, sortKeys, tableStatus, windowRows, type TableRow, type TableStatus, } from './rows';
8
+ /**
9
+ * One connection to a Kermodes server for everything inside it, reconnecting by itself. `url`
10
+ * is the server's WebSocket (`wss://kermodes.example.com/ws`); by default the page's own. Tests
11
+ * pass `connection` instead: `fakeKermodes`.
12
+ */
13
+ export declare function KermodesProvider({ url, connection: given, children, }: {
14
+ url?: string;
15
+ connection?: Connection;
16
+ children: ReactNode;
17
+ }): import("react").JSX.Element;
18
+ /** The connection of the nearest `KermodesProvider` */
19
+ export declare function useKermodes(): Connection;
20
+ /** The tables the server lists, kept current */
21
+ export declare function useTables(): readonly TableInfo[];
22
+ export type TableOptions = {
23
+ /** Sort keys, highest priority first: `'ts'` ascending, `'-ts'` descending */
24
+ sort?: readonly string[];
25
+ /** Quick filters by column in the grid's syntax: `{ sym: '=AAPL', px: '> 100' }` */
26
+ filters?: Readonly<Record<string, string>>;
27
+ /** The first row to give, after sorting and filtering; 0 by default */
28
+ offset?: number;
29
+ /** How many rows to give; 100 by default */
30
+ limit?: number;
31
+ /**
32
+ * Instead of `offset` and `limit`: the last rows, following the table as it grows. For the
33
+ * newest rows of an append-only table, this needs no sort, so the server reads them by
34
+ * position instead of holding the table to sort it.
35
+ */
36
+ last?: number;
37
+ };
38
+ export type TableState<Row extends TableRow = TableRow> = {
39
+ rows: Row[];
40
+ /** Rows in the table after filtering, of which `rows` are the asked range */
41
+ total: number;
42
+ columns: ViewportColumn[];
43
+ status: TableStatus;
44
+ error: string | null;
45
+ };
46
+ /**
47
+ * Rows of a Kermodes table, live: sorted and filtered by the server, the asked range of them,
48
+ * updated as the table ticks. Only those rows travel, so a table of billions costs what its
49
+ * window does. Render them with any component.
50
+ *
51
+ * const { rows } = useTable('md.quotes', { sort: ['sym'] });
52
+ * const tape = useTable('md.ticks', { last: 15 });
53
+ */
54
+ export declare function useTable<Row extends TableRow = TableRow>(name: string, { sort, filters, offset, limit, last }?: TableOptions): TableState<Row>;
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ import {
2
+ windowRows2,
3
+ rowRange2,
4
+ sortKeys2,
5
+ tableStatus2,
6
+ fakeKermodes2,
7
+ KermodesProvider2,
8
+ useKermodes2,
9
+ useTables2,
10
+ useTable2
11
+ } from "./chunk-dcena2cz.js";
12
+ export {
13
+ KermodesProvider2 as KermodesProvider,
14
+ fakeKermodes2 as fakeKermodes,
15
+ rowRange2 as rowRange,
16
+ sortKeys2 as sortKeys,
17
+ tableStatus2 as tableStatus,
18
+ useKermodes2 as useKermodes,
19
+ useTable2 as useTable,
20
+ useTables2 as useTables,
21
+ windowRows2 as windowRows
22
+ };
package/dist/rows.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { type Table } from 'apache-arrow';
2
+ import type { SortKey, ViewerState } from '@kermodes/client';
3
+ /** A row as `useTable` gives it: column name to a plain JavaScript value */
4
+ export type TableRow = Record<string, unknown>;
5
+ /**
6
+ * Rows `from` to `from + count` of a window of the table that starts at row `start`, as plain
7
+ * objects: integers as numbers (as bigints past 2^53), dates and timestamps as `Date`s, nulls
8
+ * as null. Rows outside the window are left out.
9
+ */
10
+ export declare function windowRows(table: Table, start: number, from: number, count: number): TableRow[];
11
+ /**
12
+ * Which rows to give of a table of `total` rows: `limit` from `offset`, or with `last` the last
13
+ * that many (all of them when there are fewer).
14
+ */
15
+ export declare function rowRange(total: number, { offset, limit, last }: {
16
+ offset?: number;
17
+ limit?: number;
18
+ last?: number;
19
+ }): {
20
+ from: number;
21
+ count: number;
22
+ };
23
+ /** Sort keys from names, highest priority first: `ts` ascending, `-ts` descending */
24
+ export declare function sortKeys(names: readonly string[]): SortKey[];
25
+ /**
26
+ * How a table's rows stand: `loading` until the first arrive (or while a live table catches up
27
+ * with its store), `live` while they tick, `static` for a table that never changes,
28
+ * `reconnecting` while the view comes back by itself, `failed` with an error otherwise.
29
+ */
30
+ export type TableStatus = 'loading' | 'live' | 'static' | 'reconnecting' | 'failed';
31
+ export declare function tableStatus(state: Pick<ViewerState, 'status' | 'error' | 'retrying'>, hasRows: boolean): TableStatus;
@@ -0,0 +1,16 @@
1
+ import { type CSSProperties } from 'react';
2
+ /**
3
+ * A Kermodes table as the platform's own viewer shows it: live, the cells that change flashing,
4
+ * any number of rows scrolled by the server, with sort, quick filters, and copy, in the page's
5
+ * theme (@kermodes/theme's tokens). It fills its parent, which needs a height. With `follow`, it
6
+ * starts at the table's end and stays there as rows arrive: an append table's newest rows, read
7
+ * by position, with no sort for the server to hold.
8
+ *
9
+ * <div className="h-96"><Table name="md.ticks" follow /></div>
10
+ */
11
+ export declare function Table({ name, follow, className, style, }: {
12
+ name: string;
13
+ follow?: boolean;
14
+ className?: string;
15
+ style?: CSSProperties;
16
+ }): import("react").JSX.Element;
package/dist/table.js ADDED
@@ -0,0 +1,45 @@
1
+ import {
2
+ useKermodes2
3
+ } from "./chunk-dcena2cz.js";
4
+
5
+ // react/src/table.tsx
6
+ import { useEffect, useLayoutEffect, useRef, useState } from "react";
7
+ import { TableViewer, gridThemeOf } from "@kermodes/grid";
8
+ import { jsx } from "react/jsx-runtime";
9
+ function Table({
10
+ name,
11
+ follow = false,
12
+ className,
13
+ style
14
+ }) {
15
+ const connection = useKermodes2();
16
+ const [view, setView] = useState(null);
17
+ useEffect(() => {
18
+ const opened = connection.open(name);
19
+ setView(opened);
20
+ return () => {
21
+ opened.close();
22
+ setView(null);
23
+ };
24
+ }, [connection, name]);
25
+ const host = useRef(null);
26
+ const [theme, setTheme] = useState(null);
27
+ useLayoutEffect(() => {
28
+ if (host.current != null) {
29
+ setTheme(gridThemeOf(host.current));
30
+ }
31
+ }, []);
32
+ return /* @__PURE__ */ jsx("div", {
33
+ ref: host,
34
+ className,
35
+ style: { position: "relative", height: "100%", ...style },
36
+ children: view != null && theme != null && /* @__PURE__ */ jsx(TableViewer, {
37
+ channel: view,
38
+ theme,
39
+ follow
40
+ })
41
+ });
42
+ }
43
+ export {
44
+ Table
45
+ };
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@kermodes/react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.13-dev.68.g32b767a",
4
+ "license": "Apache-2.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/reecetec/kermodes.git",
8
+ "directory": "web/react"
9
+ },
10
+ "type": "module",
11
+ "main": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ },
18
+ "./table": {
19
+ "types": "./dist/table.d.ts",
20
+ "import": "./dist/table.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "dependencies": {
27
+ "@kermodes/client": "0.3.13-dev.68.g32b767a",
28
+ "@kermodes/grid": "0.3.13-dev.68.g32b767a",
29
+ "apache-arrow": "^21.0.0"
30
+ },
31
+ "peerDependencies": {
32
+ "react": "^19.0.0"
33
+ }
6
34
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.