@gloom-sh/terminal 0.20.10 → 0.20.11

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.
Files changed (103) hide show
  1. package/package.json +1 -1
  2. package/patches/@opentui%2Fcore@0.3.2.patch +16 -0
  3. package/src/api-client/socket-connection.ts +355 -0
  4. package/src/api-client/socket-features.ts +75 -0
  5. package/src/api-client/socket-frames.ts +161 -0
  6. package/src/api-client/socket-listeners.ts +207 -0
  7. package/src/api-client/socket-quotes.ts +332 -0
  8. package/src/api-client/socket.ts +150 -983
  9. package/src/brokers/signed-in/adapter.ts +19 -5
  10. package/src/brokers/signed-in/client.ts +13 -1
  11. package/src/brokers/signed-in/sign-in-dialog.tsx +33 -9
  12. package/src/components/chart/native/kitty/manager.ts +2 -0
  13. package/src/components/chart/native/surface/manager.ts +211 -11
  14. package/src/components/command-bar/panel/index.tsx +2 -13
  15. package/src/components/command-bar/panel/layout.ts +1 -7
  16. package/src/components/command-bar/panel/runtime.ts +0 -1
  17. package/src/components/command-bar/panel/types.ts +0 -2
  18. package/src/components/data-table/column-menu.tsx +89 -0
  19. package/src/components/data-table/sort-menu.tsx +9 -2
  20. package/src/components/data-table/view.tsx +33 -6
  21. package/src/components/form-modal/content.tsx +10 -0
  22. package/src/components/index.ts +1 -1
  23. package/src/components/layout/pane/footer/index.tsx +25 -11
  24. package/src/components/layout/pane/footer/model.ts +62 -20
  25. package/src/components/layout/pane/sidebar.tsx +125 -15
  26. package/src/components/layout/shell/active-drag.ts +18 -13
  27. package/src/components/layout/shell/drag/magnets.ts +34 -18
  28. package/src/components/ticker/list-table-view.tsx +5 -0
  29. package/src/components/ui/data-table/column-order.ts +180 -0
  30. package/src/components/ui/data-table/index.tsx +12 -1
  31. package/src/components/ui/data-table/opentui/index.tsx +267 -23
  32. package/src/components/ui/data-table/opentui/model.ts +43 -4
  33. package/src/components/ui/data-table/types.ts +49 -0
  34. package/src/components/ui/data-table/use-column-order.ts +135 -0
  35. package/src/components/ui/index.ts +1 -1
  36. package/src/components/ui/table-layout.ts +120 -0
  37. package/src/docs/snapshot.json +3 -2
  38. package/src/i18n/es.ts +2 -0
  39. package/src/i18n/ja.ts +2 -0
  40. package/src/i18n/ko.ts +2 -0
  41. package/src/i18n/zh-cn.ts +2 -0
  42. package/src/i18n/zh-tw.ts +2 -0
  43. package/src/market-data/coordinator/index.ts +4 -3
  44. package/src/market-data/coordinator/quotes.ts +12 -4
  45. package/src/market-data/quotes/freshness.ts +12 -0
  46. package/src/market-data/quotes/live-valuation.ts +1 -1
  47. package/src/market-data/quotes/regular-session-valuation.ts +1 -1
  48. package/src/plugins/builtin/broker-manager/detail.tsx +5 -3
  49. package/src/plugins/builtin/broker-manager/index.tsx +6 -6
  50. package/src/plugins/builtin/broker-manager/model.ts +15 -6
  51. package/src/plugins/builtin/broker-manager/pane-actions.tsx +11 -4
  52. package/src/plugins/builtin/broker-manager/sign-in-end.ts +50 -19
  53. package/src/plugins/builtin/broker-manager/table.ts +10 -4
  54. package/src/plugins/builtin/chat/sidebar.tsx +33 -16
  55. package/src/plugins/builtin/cloud/askg/tool-timeline.tsx +2 -0
  56. package/src/plugins/builtin/equity-screener/live.ts +74 -18
  57. package/src/plugins/builtin/equity-screener/model.ts +19 -4
  58. package/src/plugins/builtin/equity-screener/pane.tsx +19 -14
  59. package/src/plugins/builtin/equity-screener/refresh-anchor.ts +45 -0
  60. package/src/plugins/builtin/equity-screener/results.ts +22 -2
  61. package/src/plugins/builtin/equity-screener/screen-check.ts +9 -3
  62. package/src/plugins/builtin/futures/index.tsx +15 -1
  63. package/src/plugins/builtin/futures/table.tsx +1 -1
  64. package/src/plugins/builtin/fx-matrix/index.tsx +2 -0
  65. package/src/plugins/builtin/holders/pane.tsx +30 -20
  66. package/src/plugins/builtin/iv-history/events.ts +5 -0
  67. package/src/plugins/builtin/iv-history/headless.ts +7 -2
  68. package/src/plugins/builtin/kelly-sizer/sections.tsx +2 -0
  69. package/src/plugins/builtin/macro-day/headless.ts +12 -3
  70. package/src/plugins/builtin/options/view.tsx +2 -0
  71. package/src/plugins/builtin/options-scenario/pane.tsx +2 -1
  72. package/src/plugins/builtin/perps/cascade-tabs.tsx +2 -1
  73. package/src/plugins/builtin/portfolio-list/pane/index.tsx +13 -0
  74. package/src/plugins/builtin/portfolio-list/table.tsx +5 -0
  75. package/src/plugins/builtin/rate-path/pane.tsx +2 -0
  76. package/src/plugins/builtin/revenue-breakdown/pane.tsx +2 -0
  77. package/src/plugins/builtin/reverse-dcf/pane.tsx +2 -1
  78. package/src/plugins/builtin/seasonality/pane.tsx +2 -1
  79. package/src/plugins/builtin/thirteenf/pane.tsx +2 -0
  80. package/src/plugins/builtin/ticker-detail/financials/model.ts +28 -6
  81. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +26 -9
  82. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +58 -35
  83. package/src/plugins/builtin/vol-surface/heat-grid.tsx +2 -1
  84. package/src/plugins/builtin/vol-surface/pane.tsx +2 -1
  85. package/src/plugins/builtin/world-indices/index.tsx +5 -1
  86. package/src/plugins/builtin/yield-curve/index.tsx +2 -1
  87. package/src/renderers/dom/data-table/column-drag.ts +147 -0
  88. package/src/renderers/dom/data-table/index.tsx +22 -0
  89. package/src/renderers/dom/data-table/row.tsx +27 -5
  90. package/src/renderers/dom/styles.css +22 -0
  91. package/src/renderers/opentui/chart-surface.tsx +1 -0
  92. package/src/renderers/opentui/frame-hits.ts +33 -0
  93. package/src/renderers/opentui/host.tsx +2 -0
  94. package/src/renderers/opentui/native-surface.ts +14 -21
  95. package/src/renderers/opentui/test-utils.tsx +3 -0
  96. package/src/state/app/context/index.tsx +22 -0
  97. package/src/test-support/app-store.ts +24 -1
  98. package/src/time-series/live-quotes.ts +3 -9
  99. package/src/ui/host.tsx +18 -0
  100. package/src/ui/pointer-drag.ts +11 -2
  101. package/src/utils/fundamentals.ts +14 -3
  102. package/src/utils/share-multiples.cases.json +780 -2
  103. package/src/utils/share-multiples.ts +154 -24
@@ -1,10 +1,11 @@
1
- import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
2
- import { Box, ScrollBox, Span, Text, TextAttributes, useNativeRenderer } from "../../../../ui";
1
+ import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
2
+ import { Box, ScrollBox, Span, Text, TextAttributes, useNativeRenderer, type BoxRenderable } from "../../../../ui";
3
+ import { capturePointerDrag, releasePointerDrag } from "../../../../ui/pointer-drag";
3
4
  import { hoverBg } from "../../../../theme/colors";
4
5
  import { selectedRowCellColor } from "../../../../theme/tone-contrast";
5
6
  import { useThemeColors } from "../../../../theme/theme-context";
6
7
  import { usePaneInstance } from "../../../../state/app/context";
7
- import { useViewport } from "../../../../react/input";
8
+ import { useShortcut, useViewport } from "../../../../react/input";
8
9
  import { measurePerf } from "../../../../utils/perf-marks";
9
10
  import { displayWidth } from "../../../../utils/format";
10
11
  import { useDoubleClickActivation } from "../../../use-double-click-activation";
@@ -13,6 +14,9 @@ import { EmptyState } from "../../status";
13
14
  import { observeScrollBoxContentSize, observeScrollBoxViewportSize } from "../../../../renderers/opentui/scrollbox-layout";
14
15
  import {
15
16
  expandTableColumns,
17
+ drawnTableColumns,
18
+ fitTableColumns,
19
+ tableColumnWidth,
16
20
  fitTableHeaderText,
17
21
  getTableWidth,
18
22
  hasMeaningfulTableHorizontalOverflow,
@@ -31,12 +35,15 @@ import type {
31
35
  import { resolveDataTableScrollTop } from "../visible-range";
32
36
  import { useFocusOwningPane, useVisibleRangeEmitter } from "../hooks";
33
37
  import { useStableColumns } from "../stable-columns";
38
+ import { COLUMN_DRAG_THRESHOLD_CELLS, columnDropBoundary, columnDropIndex } from "../column-order";
34
39
  import {
40
+ columnsShownWhole,
35
41
  cutColumnText,
36
42
  fitColumnCellText,
37
43
  resolveDataTableColumnClips,
38
44
  resolveDataTableVisibleWindow,
39
45
  resolveMoreColumnsHint,
46
+ MORE_COLUMNS_HINT_WIDTH,
40
47
  reuseDataTableColumnClips,
41
48
  type DataTableColumnClip,
42
49
  } from "./model";
@@ -46,6 +53,26 @@ interface DataTableRowPointerTarget<T> {
46
53
  index: number;
47
54
  }
48
55
 
56
+ /** A press on a header that may become a drag of its column. */
57
+ interface HeaderPress {
58
+ columnId: string;
59
+ from: number;
60
+ startX: number;
61
+ dragging: boolean;
62
+ }
63
+
64
+ interface HeaderDragEvent {
65
+ x?: number;
66
+ preventDefault?: () => void;
67
+ stopPropagation?: () => void;
68
+ }
69
+
70
+ /** A column being dragged, and the gap it would drop into (null where it would stay). */
71
+ interface ColumnDrag {
72
+ from: number;
73
+ boundary: number | null;
74
+ }
75
+
49
76
  type ManagedScrollBar = {
50
77
  visible: boolean;
51
78
  resetVisibilityControl?: () => void;
@@ -61,6 +88,12 @@ function setScrollBarVisible(scrollBar: unknown, visible: boolean): void {
61
88
  bar.visible = visible;
62
89
  }
63
90
 
91
+ /** The widths of what a row drew in each column, null for a cell of its own (`content`) that gives none (`contentWidth`). */
92
+ interface RowCellWidths {
93
+ columnsKey: string;
94
+ widths: (number | null)[];
95
+ }
96
+
64
97
  function OpenTuiDataTableRowInner<
65
98
  T,
66
99
  C extends DataTableColumn,
@@ -69,6 +102,7 @@ function OpenTuiDataTableRowInner<
69
102
  columnGap,
70
103
  columnStarts,
71
104
  contentWidth,
105
+ cellColumns,
72
106
  displayColumns,
73
107
  focusPane,
74
108
  frozenColumnOffset,
@@ -88,7 +122,12 @@ function OpenTuiDataTableRowInner<
88
122
  selected,
89
123
  selectedTextOverridesCellColor,
90
124
  columnClips,
125
+ cellWidths,
126
+ columnsKey,
91
127
  }: {
128
+ /** Where the row leaves the width of each column's text as it draws it, for the table to fit its columns to. */
129
+ cellWidths: Map<string, RowCellWidths>;
130
+ columnsKey: string;
92
131
  /** Only compared by the row memo; see `getRowVersion`. */
93
132
  rowVersion?: unknown;
94
133
  /** Columns of the row in view, which a section header's action keeps to. */
@@ -97,6 +136,12 @@ function OpenTuiDataTableRowInner<
97
136
  columnGap: number;
98
137
  columnStarts: number[];
99
138
  contentWidth: number;
139
+ /**
140
+ * The columns as each cell's text is made for and measured at: as an unfitted table draws them, so
141
+ * text that fits itself to its column (a price's digits) neither shrinks with the blank the fit took
142
+ * from it nor grows with the room the fit gave it.
143
+ */
144
+ cellColumns: C[];
100
145
  displayColumns: C[];
101
146
  focusPane: () => void;
102
147
  frozenColumnOffset?: number;
@@ -182,6 +227,8 @@ function OpenTuiDataTableRowInner<
182
227
  }
183
228
 
184
229
  const rowState = { selected };
230
+ const widths: (number | null)[] = [];
231
+ cellWidths.set(itemKey, { columnsKey, widths });
185
232
  const rowBackgroundColor = getRowBackgroundColor?.(item, index, rowState);
186
233
  const rowBg = selected ? colors.selected : rowBackgroundColor ?? colors.bg;
187
234
  const rowHoverBg = selected ? undefined : hoverBg(colors);
@@ -210,7 +257,11 @@ function OpenTuiDataTableRowInner<
210
257
  {displayColumns.map((column, columnIndex) => {
211
258
  const frozen = columnIndex === 0 && frozenColumnOffset !== undefined;
212
259
  const clip = columnClips?.[columnIndex] ?? null;
213
- const cell = renderCell(item, column, index, rowState);
260
+ const cellColumn = cellColumns[columnIndex] ?? column;
261
+ const made = renderCell(item, cellColumn, index, rowState);
262
+ // A drawn cell lays itself out in the column as drawn; its width is the one made for its column unfitted.
263
+ const cell = made.content !== undefined && cellColumn !== column ? renderCell(item, column, index, rowState) : made;
264
+ widths[columnIndex] = made.content === undefined ? displayWidth(made.text) : made.contentWidth ?? null;
214
265
  const columnStart = columnStarts[columnIndex] ?? 0;
215
266
  const leadGap = tableColumnLeadGap(displayColumns, columnIndex, columnGap);
216
267
  const inset = clip ? clip.inset : !frozen && frozenColumnOffset !== undefined
@@ -281,6 +332,8 @@ export function OpenTuiDataTable<T, C extends DataTableColumn = DataTableColumn>
281
332
  sortColumnId,
282
333
  sortDirection,
283
334
  onHeaderClick,
335
+ onColumnMove,
336
+ anchoredColumns = 1,
284
337
  headerScrollRef,
285
338
  scrollRef,
286
339
  syncHeaderScroll,
@@ -368,48 +421,210 @@ export function OpenTuiDataTable<T, C extends DataTableColumn = DataTableColumn>
368
421
  ],
369
422
  );
370
423
  const { endIndex, startIndex, viewportHeight, visibleItems } = tableWindow;
371
- const tableWidth = useMemo(
424
+ const setTableWidth = useMemo(
372
425
  () => getTableWidth(columns, columnGap, horizontalPadding),
373
426
  [columnGap, columns, horizontalPadding],
374
427
  );
375
428
  const {
376
- contentWidth: measuredContentWidth,
377
429
  viewportWidth: measuredViewportWidth,
378
430
  measureContentWidth,
379
- } = useMeasuredTableContentWidth(tableWidth, headerScrollRef, scrollRef);
431
+ } = useMeasuredTableContentWidth(setTableWidth, headerScrollRef, scrollRef);
432
+ // The widest text each column holds in the rows drawn so far, kept while the columns, the rows and the
433
+ // pane's width stay the same, so a column never narrows as the rows under it scroll by; new rows or a new
434
+ // width start it over from the rows in view. Each row reports its cells' widths as it draws them (a drawn
435
+ // cell, `content`, gives its `contentWidth` or keeps its column's width), so no cell is made twice.
436
+ const columnsKey = columns.map((column) => `${column.id}:${column.width}:${column.label}`).join("\u0000");
437
+ const rowCellWidths = useRef(new Map<string, RowCellWidths>()).current;
438
+ const [measuredWidths, setMeasuredWidths] = useState<{ key: string; widths: (number | null)[] } | null>(null);
439
+ const measuredFrom = useRef<{ items: readonly T[]; viewportWidth: number } | null>(null);
440
+ const contentWidths = measuredWidths?.key === columnsKey ? measuredWidths.widths : null;
441
+ useLayoutEffect(() => {
442
+ const from = measuredFrom.current;
443
+ const fresh = !from || from.items !== items || from.viewportWidth !== measuredViewportWidth;
444
+ measuredFrom.current = { items, viewportWidth: measuredViewportWidth };
445
+ const previous = measuredWidths?.key === columnsKey ? measuredWidths.widths : null;
446
+ const kept = fresh ? null : previous;
447
+ const widths: (number | null)[] = columns.map((_, index) => kept?.[index] ?? 0);
448
+ if (kept) kept.forEach((width, index) => { if (width === null) widths[index] = null; });
449
+ visibleItems.forEach((item, offset) => {
450
+ const row = rowCellWidths.get(getItemKey(item, startIndex + offset));
451
+ if (!row || row.columnsKey !== columnsKey) return;
452
+ row.widths.forEach((width, index) => {
453
+ const known = widths[index];
454
+ widths[index] = known === null || width === null ? null : Math.max(known ?? 0, width);
455
+ });
456
+ });
457
+ if (rowCellWidths.size > visibleItems.length * 4 + 64) rowCellWidths.clear();
458
+ if (previous && widths.every((width, index) => width === previous[index])) return;
459
+ setMeasuredWidths({ key: columnsKey, widths });
460
+ });
461
+ // A header as drawn, with its sort mark.
462
+ const sortedLabel = useCallback(
463
+ (column: { id: string; label: string }) => (sortColumnId === column.id ? `${column.label}${column.label ? " " : ""}▲` : column.label),
464
+ [sortColumnId],
465
+ );
466
+ // The header row has a blank cell past its scroll box, over the body's vertical scrollbar, which the
467
+ // "more ⇧→" hint takes first (resolveMoreColumnsHint).
468
+ const besideHeader = Math.max(0, Math.min(1, (scrollRef.current?.width ?? 0) - measuredViewportWidth));
469
+ // Fitted to the viewport and what the columns hold: blank past their text gives way before a column is
470
+ // cut or pushed out of view (fitTableColumns).
471
+ const fittedColumns = useMemo(
472
+ () => contentWidths
473
+ ? fitTableColumns(columns, contentWidths, measuredViewportWidth, columnGap, horizontalPadding, showHorizontalScrollbar ? {
474
+ ...MORE_COLUMNS_HINT_WIDTH,
475
+ shownWhole: (fitted) => columnsShownWhole({
476
+ columns: fitted.map((column) => ({ width: column.width, align: column.align, label: sortedLabel(column) })),
477
+ columnGap,
478
+ besideHeader,
479
+ horizontalPadding,
480
+ viewportWidth: measuredViewportWidth,
481
+ }),
482
+ } : undefined)
483
+ : columns,
484
+ [besideHeader, columnGap, columns, contentWidths, horizontalPadding, measuredViewportWidth, showHorizontalScrollbar, sortedLabel],
485
+ );
486
+ const tableWidth = useMemo(
487
+ () => getTableWidth(fittedColumns, columnGap, horizontalPadding),
488
+ [columnGap, fittedColumns, horizontalPadding],
489
+ );
490
+ const measuredContentWidth = Math.max(tableWidth, measuredViewportWidth);
380
491
  const horizontalScrollbarVisible = showHorizontalScrollbar
381
492
  && hasMeaningfulTableHorizontalOverflow(tableWidth, measuredViewportWidth, columnGap);
382
493
  const freezeFirstColumn = tableFreezesFirstColumn({
383
- freezeFirstColumn: freezeFirstColumnProp, columns, columnGap, horizontalPadding, viewportWidth: measuredViewportWidth,
494
+ freezeFirstColumn: freezeFirstColumnProp, columns: fittedColumns, columnGap, horizontalPadding, viewportWidth: measuredViewportWidth,
384
495
  overflows: horizontalScrollbarVisible,
385
496
  });
386
497
  const contentWidth = fillAvailableWidth ? measuredContentWidth : tableWidth;
387
498
  const sectionWidth = measuredViewportWidth > 0 ? Math.min(contentWidth, measuredViewportWidth) : contentWidth;
388
499
  const displayColumns = useMemo(
389
- () => expandTableColumns(columns, contentWidth, columnGap, horizontalPadding),
390
- [columnGap, columns, contentWidth, horizontalPadding],
500
+ () => expandTableColumns(fittedColumns, contentWidth, columnGap, horizontalPadding),
501
+ [columnGap, fittedColumns, contentWidth, horizontalPadding],
391
502
  );
503
+ // What each cell's text is made for, and measured at: the columns as an unfitted table draws them, never the
504
+ // fit's. Text that fits itself to its column (a price's digits) does not shrink with the blank the fit took
505
+ // from it, nor, made for the room the fit gave it, measure wider and so take more on the next fit.
506
+ const cellColumns = useMemo(() => {
507
+ if (fittedColumns === columns) return displayColumns;
508
+ const unfitted = expandTableColumns(
509
+ columns,
510
+ fillAvailableWidth ? Math.max(setTableWidth, measuredViewportWidth) : setTableWidth,
511
+ columnGap,
512
+ horizontalPadding,
513
+ );
514
+ return displayColumns.map((column, index) => {
515
+ const width = unfitted[index]?.width ?? column.width;
516
+ return width === column.width ? column : { ...column, width };
517
+ });
518
+ }, [columnGap, columns, displayColumns, fillAvailableWidth, fittedColumns, horizontalPadding, measuredViewportWidth, setTableWidth]);
392
519
  const columnStarts = useMemo(
393
520
  () => tableColumnStarts(displayColumns, columnGap),
394
521
  [columnGap, displayColumns],
395
522
  );
523
+ // Sideways steps and the column a table opens on go by the widths drawn where the fit moved them.
524
+ useEffect(() => {
525
+ const body = scrollRef.current;
526
+ if (!body) return;
527
+ const moved = fittedColumns !== columns && fittedColumns.some((column, index) => column.width !== tableColumnWidth(columns[index]!));
528
+ if (moved) drawnTableColumns.set(body, fittedColumns);
529
+ else drawnTableColumns.delete(body);
530
+ }, [columns, fittedColumns, scrollRef]);
531
+ // A press on a movable header sorts on release, or drags its column once it moves two cells: the header row
532
+ // takes the drag (capturePointerDrag), marks the gap the column would drop into, and moves it on release.
533
+ const headerRowRef = useRef<BoxRenderable | null>(null);
534
+ const headerPressRef = useRef<HeaderPress | null>(null);
535
+ const [columnDrag, setColumnDrag] = useState<ColumnDrag | null>(null);
536
+ const columnSpans = useMemo(
537
+ () => displayColumns.map((column, index) => ({ start: columnStarts[index] ?? 0, end: (columnStarts[index] ?? 0) + column.width })),
538
+ [columnStarts, displayColumns],
539
+ );
540
+ // Scrolled sideways, a frozen first column covers the columns under it: it ends here, in the row's
541
+ // coordinates past its padding, and nothing drops among the columns it covers.
542
+ const frozenEnd = freezeFirstColumn ? frozenColumnOffset + (displayColumns[0]?.width ?? 0) + columnGap : undefined;
543
+ const dropBoundaryAt = useCallback((event?: { x?: number }) => {
544
+ const row = headerRowRef.current;
545
+ if (typeof event?.x !== "number" || !row) return null;
546
+ // row.x is where the scrolled row starts on screen, so this is the pointer's place among the columns.
547
+ return columnDropBoundary(columnSpans, event.x - (row.x ?? 0) - horizontalPadding, anchoredColumns, frozenEnd);
548
+ }, [anchoredColumns, columnSpans, frozenEnd, horizontalPadding]);
549
+ const dragHeader = useCallback((event?: HeaderDragEvent) => {
550
+ const press = headerPressRef.current;
551
+ if (!press || typeof event?.x !== "number") return;
552
+ if (!press.dragging && Math.abs(event.x - press.startX) < COLUMN_DRAG_THRESHOLD_CELLS) return;
553
+ press.dragging = true;
554
+ event.preventDefault?.();
555
+ event.stopPropagation?.();
556
+ const boundary = dropBoundaryAt(event);
557
+ const next = { from: press.from, boundary: boundary !== null && columnDropIndex(press.from, boundary) !== null ? boundary : null };
558
+ setColumnDrag((current) => current?.from === next.from && current.boundary === next.boundary ? current : next);
559
+ }, [dropBoundaryAt]);
560
+ // A press that never sees its release (let go outside the window) ends at the next move with no button
561
+ // held, the next press or the terminal losing focus: no move, no sort, and the header is put down.
562
+ const cancelHeaderPress = useCallback(() => {
563
+ if (!headerPressRef.current) return;
564
+ headerPressRef.current = null;
565
+ setColumnDrag(null);
566
+ releasePointerDrag(nativeRenderer);
567
+ }, [nativeRenderer]);
568
+ const dragging = columnDrag !== null;
569
+ useEffect(() => {
570
+ if (!dragging || typeof nativeRenderer?.on !== "function") return;
571
+ nativeRenderer.on("blur", cancelHeaderPress);
572
+ return () => nativeRenderer.off("blur", cancelHeaderPress);
573
+ }, [cancelHeaderPress, dragging, nativeRenderer]);
574
+ // Esc while a column drags puts it back; the release then does nothing.
575
+ useShortcut((event) => {
576
+ if (event.name !== "escape" || !headerPressRef.current?.dragging) return;
577
+ event.preventDefault?.();
578
+ event.stopPropagation?.();
579
+ headerPressRef.current = null;
580
+ setColumnDrag(null);
581
+ }, { enabled: dragging, phase: "capture" });
582
+ const releaseHeader = useCallback((event?: HeaderDragEvent) => {
583
+ const press = headerPressRef.current;
584
+ headerPressRef.current = null;
585
+ setColumnDrag(null);
586
+ if (!press) return;
587
+ event?.preventDefault?.();
588
+ event?.stopPropagation?.();
589
+ if (!press.dragging) {
590
+ onHeaderClick?.(press.columnId);
591
+ return;
592
+ }
593
+ const boundary = dropBoundaryAt(event);
594
+ const to = boundary === null ? null : columnDropIndex(press.from, boundary);
595
+ if (to !== null) onColumnMove?.(press.columnId, to);
596
+ }, [dropBoundaryAt, onColumnMove, onHeaderClick]);
396
597
  // A frozen board's rows run on past the last column, blank, so scrolled to its far end it starts a column
397
598
  // whole beside the frozen one, as each step does (tableScrollStep).
398
599
  const scrollContentWidth = contentWidth + (freezeFirstColumn && horizontalScrollbarVisible
399
600
  ? tableFarEdgePad({ columns: displayColumns, columnGap, horizontalPadding, contentWidth, viewportWidth: measuredViewportWidth })
400
601
  : 0);
602
+ const lastColumn = displayColumns.length - 1;
603
+ // The gap's own blank cell, before the column it would land in front of or after the last one; never under a
604
+ // frozen first column, but in its trailing blank cell when the column it lands before is partly behind it, and
605
+ // at the viewport's last cell when the gap after the last column is past it.
606
+ const dropMarkerLeft = columnDrag?.boundary == null ? null : Math.min(
607
+ scrollContentWidth - 1,
608
+ measuredViewportWidth > 0 ? frozenColumnOffset + measuredViewportWidth - 1 : Number.POSITIVE_INFINITY,
609
+ horizontalPadding + Math.max(
610
+ frozenEnd === undefined ? Number.NEGATIVE_INFINITY : frozenEnd - 1,
611
+ columnDrag.boundary <= lastColumn
612
+ ? (columnStarts[columnDrag.boundary] ?? 0) - 1
613
+ : (columnStarts[lastColumn] ?? 0) + (displayColumns[lastColumn]?.width ?? 0),
614
+ ),
615
+ );
401
616
  // Columns out of view past the right edge: the header row ends in "more ⇧→" there, a press on it scrolls to
402
617
  // them, and the rows leave its cells blank, so a narrow pane says it has more than it shows. The header's
403
- // scroll box is as wide as the body's viewport (measuredViewportWidth), so the header row has a blank cell
404
- // past it, over the body's vertical scrollbar; the hint is laid over the row, not inside the scroll box,
405
- // and takes that cell first.
406
- const besideHeader = Math.max(0, Math.min(1, (scrollRef.current?.width ?? 0) - measuredViewportWidth));
407
- const moreColumns = horizontalScrollbarVisible ? resolveMoreColumnsHint({
408
- columns: displayColumns.map((column) => ({
409
- width: column.width,
410
- align: column.align,
411
- label: sortColumnId === column.id ? `${column.label}${column.label ? " " : ""}▲` : column.label,
412
- })),
618
+ // scroll box is as wide as the body's viewport (measuredViewportWidth); the hint is laid over the row, not
619
+ // inside the scroll box, and takes the cell past it first (besideHeader).
620
+ // An empty table has nothing past the edge to scroll to.
621
+ const hintColumns = useMemo(() => displayColumns.map((column) => ({
622
+ width: column.width,
623
+ align: column.align,
624
+ label: sortedLabel(column),
625
+ })), [displayColumns, sortedLabel]);
626
+ const moreColumns = horizontalScrollbarVisible && items.length > 0 ? resolveMoreColumnsHint({
627
+ columns: hintColumns,
413
628
  columnGap,
414
629
  columnStarts,
415
630
  frozenFirstColumn: freezeFirstColumn,
@@ -433,8 +648,9 @@ export function OpenTuiDataTable<T, C extends DataTableColumn = DataTableColumn>
433
648
  // A table that cannot scroll sideways fits its own columns; one it cut could never be scrolled to.
434
649
  viewportWidth: showHorizontalScrollbar ? measuredViewportWidth : 0,
435
650
  widths: displayColumns.map((column) => column.width),
651
+ labels: hintColumns,
436
652
  })),
437
- [columnGap, columnStarts, displayColumns, freezeFirstColumn, horizontalPadding, measuredViewportWidth, moreColumnsReserve, scrollLeft, showHorizontalScrollbar],
653
+ [columnGap, columnStarts, displayColumns, freezeFirstColumn, hintColumns, horizontalPadding, measuredViewportWidth, moreColumnsReserve, scrollLeft, showHorizontalScrollbar],
438
654
  );
439
655
  const reportVisibleRange = useVisibleRangeEmitter({
440
656
  itemCount: items.length,
@@ -649,14 +865,25 @@ export function OpenTuiDataTable<T, C extends DataTableColumn = DataTableColumn>
649
865
  onSizeChange={measureContentWidth}
650
866
  >
651
867
  <Box
868
+ ref={headerRowRef}
652
869
  flexDirection="row"
653
870
  height={1}
654
871
  {...tableContentWidthProps(scrollContentWidth)}
655
872
  paddingX={horizontalPadding}
656
873
  backgroundColor={colors.panel}
874
+ onMouseDrag={onColumnMove ? dragHeader : undefined}
875
+ onMouseDragEnd={onColumnMove ? releaseHeader : undefined}
876
+ // While the row holds a press, every other mouse event comes here: one with no button held, or a
877
+ // new press (sent to the row itself, not bubbled up from a header), means the release went missing.
878
+ onMouseMove={onColumnMove ? cancelHeaderPress : undefined}
879
+ onMouseDown={onColumnMove ? (event: any) => {
880
+ if (event?.target === headerRowRef.current) cancelHeaderPress();
881
+ } : undefined}
657
882
  >
658
883
  {displayColumns.map((column, columnIndex) => {
659
884
  const frozen = freezeFirstColumn && columnIndex === 0;
885
+ const movable = !!onColumnMove && columnIndex >= anchoredColumns;
886
+ const dragged = columnDrag?.from === columnIndex;
660
887
  const columnStart = columnStarts[columnIndex] ?? 0;
661
888
  const clip = columnClips?.[columnIndex] ?? null;
662
889
  const inset = clip ? clip.inset : freezeFirstColumn && !frozen
@@ -688,10 +915,17 @@ export function OpenTuiDataTable<T, C extends DataTableColumn = DataTableColumn>
688
915
  position="relative"
689
916
  left={frozen ? frozenColumnOffset : undefined}
690
917
  zIndex={frozen ? 1 : undefined}
691
- backgroundColor={column.headerBackgroundColor ?? colors.panel}
918
+ backgroundColor={dragged ? hoverBg(colors) : column.headerBackgroundColor ?? colors.panel}
692
919
  onMouseDown={(event: any) => {
693
920
  focusPane();
694
921
  onTableMouseDown?.(event);
922
+ if (movable && (event.button ?? 0) === 0) {
923
+ // Sorted on release, unless the press drags the column first.
924
+ event.preventDefault();
925
+ headerPressRef.current = { columnId: column.id, from: columnIndex, startX: event.x, dragging: false };
926
+ capturePointerDrag(nativeRenderer, headerRowRef.current);
927
+ return;
928
+ }
695
929
  if (!onHeaderClick) return;
696
930
  event.preventDefault();
697
931
  onHeaderClick(column.id);
@@ -699,13 +933,20 @@ export function OpenTuiDataTable<T, C extends DataTableColumn = DataTableColumn>
699
933
  >
700
934
  <Text
701
935
  attributes={TextAttributes.BOLD}
702
- fg={isSorted ? colors.text : column.headerColor ?? colors.textDim}
936
+ fg={dragged ? colors.textBright : isSorted ? colors.text : column.headerColor ?? colors.textDim}
937
+ // A press here may drag the column, which a text selection would take over.
938
+ selectable={onColumnMove ? false : undefined}
703
939
  >
704
940
  {frozen ? `${" ".repeat(horizontalPadding)}${labelText}${" ".repeat(columnGap)}` : labelText}
705
941
  </Text>
706
942
  </Box>
707
943
  );
708
944
  })}
945
+ {dropMarkerLeft !== null ? (
946
+ <Box position="absolute" left={dropMarkerLeft} top={0} width={1} height={1} zIndex={3}>
947
+ <Text fg={colors.borderFocused}>│</Text>
948
+ </Box>
949
+ ) : null}
709
950
  </Box>
710
951
  </ScrollBox>
711
952
  {moreColumns ? (
@@ -768,6 +1009,7 @@ export function OpenTuiDataTable<T, C extends DataTableColumn = DataTableColumn>
768
1009
  columnGap={columnGap}
769
1010
  columnStarts={columnStarts}
770
1011
  contentWidth={scrollContentWidth}
1012
+ cellColumns={cellColumns}
771
1013
  displayColumns={displayColumns}
772
1014
  focusPane={focusPane}
773
1015
  frozenColumnOffset={freezeFirstColumn ? frozenColumnOffset : undefined}
@@ -788,6 +1030,8 @@ export function OpenTuiDataTable<T, C extends DataTableColumn = DataTableColumn>
788
1030
  selected={isSelected(item, index)}
789
1031
  selectedTextOverridesCellColor={selectedTextOverridesCellColor}
790
1032
  columnClips={columnClips}
1033
+ cellWidths={rowCellWidths}
1034
+ columnsKey={columnsKey}
791
1035
  />
792
1036
  );
793
1037
  }),
@@ -1,5 +1,5 @@
1
1
  import { displayWidth } from "../../../../utils/format";
2
- import { fitTableCellText, tableColumnLeadGap } from "../../table-layout";
2
+ import { fitTableCellText, tableColumnLeadGap, tableColumnStarts } from "../../table-layout";
3
3
 
4
4
  /**
5
5
  * Where the viewport cuts a column: `inset` cells hidden on its left (past the
@@ -101,6 +101,11 @@ export function reuseDataTableColumnClips(
101
101
  * the only sign.
102
102
  */
103
103
  const MORE_COLUMNS_LABELS = ["more ⇧→", "⇧→", "→"] as const;
104
+ /** The cells the "more ⇧→" hint takes at the right edge with the blank before it, whole and at its shortest with a key. */
105
+ export const MORE_COLUMNS_HINT_WIDTH = {
106
+ whole: displayWidth(MORE_COLUMNS_LABELS[0]) + 1,
107
+ least: displayWidth(MORE_COLUMNS_LABELS[1]) + 1,
108
+ } as const;
104
109
 
105
110
  export interface MoreColumnsHint {
106
111
  /** The cells the hint draws: its label, after a blank unless it takes the last column's own. */
@@ -164,8 +169,7 @@ export function resolveMoreColumnsHint({
164
169
  scrollLeft: number;
165
170
  viewportWidth: number;
166
171
  }): MoreColumnsHint | null {
167
- const longest = displayWidth(MORE_COLUMNS_LABELS[0]) + 1;
168
- if (columns.length === 0 || viewportWidth < longest * 2) return null;
172
+ if (columns.length === 0 || viewportWidth < MORE_COLUMNS_HINT_WIDTH.whole * 2) return null;
169
173
  const right = scrollLeft + viewportWidth;
170
174
  const starts = columns.map((_, index) => horizontalPadding + (columnStarts[index] ?? 0));
171
175
  if (!hasColumnsPastRightEdge(columns, starts, right)) return null;
@@ -195,6 +199,31 @@ export function resolveMoreColumnsHint({
195
199
  return null;
196
200
  }
197
201
 
202
+ /**
203
+ * How many leading columns a table scrolled to its start shows whole, the
204
+ * rows' cells under the "more ⇧→" hint aside (`resolveMoreColumnsHint`).
205
+ */
206
+ export function columnsShownWhole({
207
+ columns,
208
+ columnGap,
209
+ besideHeader = 0,
210
+ horizontalPadding,
211
+ viewportWidth,
212
+ }: {
213
+ columns: readonly HintColumn[];
214
+ columnGap: number;
215
+ besideHeader?: number;
216
+ horizontalPadding: number;
217
+ viewportWidth: number;
218
+ }): number {
219
+ const columnStarts = tableColumnStarts(columns, columnGap);
220
+ const hint = resolveMoreColumnsHint({ columns, columnGap, columnStarts, besideHeader, horizontalPadding, scrollLeft: 0, viewportWidth });
221
+ const right = viewportWidth - (hint?.reserve ?? 0);
222
+ let count = 0;
223
+ while (count < columns.length && horizontalPadding + columnStarts[count]! + columns[count]!.width <= right) count += 1;
224
+ return count;
225
+ }
226
+
198
227
  /**
199
228
  * Each column's clip at the current scroll, null for a column shown whole.
200
229
  * A frozen first column stays, and what slides under it counts as cut on the
@@ -211,6 +240,7 @@ export function resolveDataTableColumnClips({
211
240
  scrollLeft,
212
241
  viewportWidth,
213
242
  widths,
243
+ labels,
214
244
  }: {
215
245
  columnGap: number;
216
246
  /** Where each column's content starts, from the first column (tableColumnStarts). */
@@ -223,6 +253,12 @@ export function resolveDataTableColumnClips({
223
253
  viewportWidth: number;
224
254
  /** Each column's drawn width. */
225
255
  widths: readonly number[];
256
+ /**
257
+ * Each column's header as drawn, with its alignment. Text the right edge leaves fewer cells than its
258
+ * label shows none of them: a sliver would read as a stray ellipsis, and "more ⇧→" counts the column
259
+ * as past the edge (hasColumnsPastRightEdge).
260
+ */
261
+ labels?: readonly HintColumn[];
226
262
  }): (DataTableColumnClip | null)[] | null {
227
263
  if (viewportWidth <= 0 || widths.length === 0) return null;
228
264
  const right = scrollLeft + viewportWidth - Math.max(0, rightReserve);
@@ -235,7 +271,10 @@ export function resolveDataTableColumnClips({
235
271
  if (start >= left && end <= right) return null;
236
272
  cut = true;
237
273
  const inset = Math.min(width, Math.max(0, left - start));
238
- return { inset, width: Math.max(0, Math.min(end, right) - start - inset) };
274
+ const shown = Math.max(0, Math.min(end, right) - start - inset);
275
+ const header = labels?.[index];
276
+ const sliver = !!header && (header.align ?? "left") !== "right" && inset + shown < width && shown < displayWidth(header.label);
277
+ return { inset, width: sliver ? 0 : shown };
239
278
  });
240
279
  return cut ? clips : null;
241
280
  }
@@ -54,6 +54,12 @@ export interface DataTableCell {
54
54
  */
55
55
  valueUnit?: string;
56
56
  content?: ReactNode;
57
+ /**
58
+ * The cells `content` takes to show whole in the terminal, where a table
59
+ * fits its columns to what they hold before it cuts one or pushes one out of
60
+ * view. Without it a drawn cell's column keeps the width the pane set.
61
+ */
62
+ contentWidth?: number;
57
63
  /**
58
64
  * Artwork drawn before `text` on the desktop and the web, such as a flag.
59
65
  * It is decoration: the terminal does not draw it, and exports, automation
@@ -99,6 +105,36 @@ export interface DataTableSectionHeader {
99
105
  };
100
106
  }
101
107
 
108
+ /** How a table's columns move when the reader drags a header (`DataTableProps.columnReorder`). */
109
+ export interface DataTableColumnReorder {
110
+ /** How many leading columns stay first. Unset, the first column and the narrow marks before it (`rowAnchorColumnCount`). */
111
+ anchored?: number;
112
+ /**
113
+ * Names this table's remembered order, for a pane that shows several
114
+ * tables naming their rows with the same column whose other columns
115
+ * differ. Unset, the id of the column that names the row (the last
116
+ * anchored one).
117
+ */
118
+ key?: string;
119
+ /**
120
+ * The pane's own ordered list of the columns it shows, for a pane whose
121
+ * settings choose and order them (an ordered-multi-select): a drag rewrites
122
+ * that list instead of keeping an order of its own, so Settings and the
123
+ * table agree.
124
+ */
125
+ control?: {
126
+ order: readonly string[];
127
+ /**
128
+ * The list the pane shows while its setting is unset. Reset Columns puts
129
+ * the list back in this order (without it the pane menu offers none),
130
+ * and a list that comes out the same is `undefined` to `onChange`.
131
+ */
132
+ defaultOrder?: readonly string[];
133
+ /** The list to keep, or undefined to remove the setting, so columns later added to the defaults reach the pane. */
134
+ onChange: (order: string[] | undefined) => void;
135
+ };
136
+ }
137
+
102
138
  /** Where `scrollToIndex` puts its row: the nearest edge, the middle, or the top of the viewport. */
103
139
  export type DataTableScrollAlign = "nearest" | "center" | "start";
104
140
 
@@ -123,6 +159,19 @@ export interface DataTableProps<
123
159
  sortDirection: "asc" | "desc";
124
160
  /** Sorts by a column. Without it the header is plain labels and ignores clicks. */
125
161
  onHeaderClick?: (columnId: string) => void;
162
+ /**
163
+ * Dragging a header moves its column (once the press moves a few pixels or
164
+ * two cells; a click still sorts, on the release rather than the press),
165
+ * and the pane remembers the order under `pane.columnOrder`: Reset
166
+ * Columns in the pane menu puts the pane's own back. The columns that name
167
+ * the row stay first. `false` keeps the pane's order, for columns that are
168
+ * one ordered axis (periods, tenors, strikes) or a fixed format.
169
+ */
170
+ columnReorder?: false | DataTableColumnReorder;
171
+ /** Set by `DataTable` from `columnReorder` for the renderer: moves a column to an index. Absent where the order is fixed. */
172
+ onColumnMove?: (columnId: string, toIndex: number) => void;
173
+ /** Set by `DataTable` with `onColumnMove`: the leading columns a drag neither moves nor drops before. */
174
+ anchoredColumns?: number;
126
175
  headerScrollRef: RefObject<ScrollBoxRenderable | null>;
127
176
  scrollRef: RefObject<ScrollBoxRenderable | null>;
128
177
  syncHeaderScroll: () => void;