@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
@@ -15,17 +15,19 @@ import {
15
15
  } from "../../../../components";
16
16
  import { colors, priceColor } from "../../../../theme/colors";
17
17
  import { fiscalYearEndMonth } from "../../../../utils/fiscal-period";
18
- import { padTo } from "../../../../utils/format";
18
+ import { displayWidth, padTo } from "../../../../utils/format";
19
19
  import { filledPeriodPublications, filledPeriodsNote, stalePeriodNote } from "../../../../utils/financial-statements";
20
20
  import {
21
21
  FINANCIAL_COL_W,
22
22
  financialLabelWidth,
23
+ financialPeriodWidth,
23
24
  FINANCIAL_SUB_TABS,
24
25
  buildFinancialRows,
25
26
  canCompareFinancialRow,
26
27
  collectDefaultCollapsedGroupIds,
27
28
  collectGroupIds,
28
29
  computeGrowth,
30
+ financialCellValue,
29
31
  financialColumnLabel,
30
32
  formatFinancialCell,
31
33
  financialStatementCurrency,
@@ -41,7 +43,6 @@ import {
41
43
  selectFinancialStatements,
42
44
  shareFinancialUnit,
43
45
  splitPeriodsNotInYet,
44
- statementMetricValue,
45
46
  type FinancialPeriod,
46
47
  type FinancialTableRow,
47
48
  } from "./model";
@@ -72,6 +73,32 @@ type FinancialTableColumn = DataTableColumn & (
72
73
  | { id: string; kind: "statement"; statement: FinancialTableStatement }
73
74
  );
74
75
 
76
+ const NO_COLLAPSED_GROUPS: ReadonlySet<string> = new Set();
77
+
78
+ /**
79
+ * A group's name in the metric column. It draws its indent (an empty one still takes a cell), its disclosure
80
+ * and its name a cell apart, and says that width (`contentWidth`) so the table fits the column to it whole.
81
+ * The desktop draws the disclosure as a path, not a glyph.
82
+ */
83
+ export function financialGroupNameCell(
84
+ row: Extract<FinancialTableRow, { kind: "group" }>,
85
+ color: string,
86
+ attributes: number,
87
+ ): Pick<DataTableCell, "text" | "contentWidth" | "content"> {
88
+ const indent = " ".repeat(row.depth * 2);
89
+ const marker = row.toggleable ? (row.expanded ? "\u25be" : "\u25b8") : " ";
90
+ return {
91
+ text: `${indent}${marker} ${row.unitLabel}`,
92
+ contentWidth: Math.max(1, displayWidth(indent)) + 1 + displayWidth(marker) + 1 + displayWidth(row.unitLabel),
93
+ content: (
94
+ <Box flexDirection="row" alignItems="center" gap={1}>
95
+ <Text fg={color}>{indent}</Text>
96
+ {row.toggleable ? <DisclosureMarker expanded={!!row.expanded} color={color} /> : <Text> </Text>}
97
+ <Text fg={color} attributes={attributes}>{row.unitLabel}</Text>
98
+ </Box>
99
+ ),
100
+ };
101
+ }
75
102
  const financialRowKey = (row: FinancialTableRow) => row.id;
76
103
  const financialRowBackground = (row: FinancialTableRow) => (
77
104
  row.kind === "group" && row.depth === 0 ? colors.panel : undefined
@@ -318,6 +345,24 @@ export function ResolvedFinancialsTab({
318
345
  const moneyUnit = [comparisonCurrency, unit].filter(Boolean).join(" ");
319
346
  const unitMarked = !!unit && rows.some((row) => row.unitLabel !== row.label);
320
347
  const metricHeader = moneyUnit ? `${moneyUnit}${unitMarked ? " unless marked" : ""}` : "Metric";
348
+ // The annual balance sheet leads with a newer quarter-end position.
349
+ const periodHeaders = useMemo(() => displayStatements.map((statement) => financialColumnHeader(
350
+ statement,
351
+ isAnnual && (statement.date === "TTM" || annualDates.has(statement.date)) ? "annual" : "quarterly",
352
+ yearEndMonth,
353
+ comparisonCurrency,
354
+ )), [annualDates, comparisonCurrency, displayStatements, isAnnual, yearEndMonth]);
355
+ // In the terminal a period is as wide as its widest value and growth, so each pair sits as far from the next
356
+ // as from its own growth and more periods fit. The ratio tabs keep the statement columns' width. Every line of
357
+ // the statement counts, a collapsed group's too, so opening or closing one leaves the periods where they are.
358
+ const periodWidth = useMemo(() => {
359
+ if (nativePaneChrome || ratioTab) return FINANCIAL_COL_W;
360
+ const everyRow = shareFinancialUnit(buildFinancialRows(subTab.rows, displayStatements, NO_COLLAPSED_GROUPS)).rows;
361
+ const values = [...everyRow, ...rows].flatMap((row) => displayStatements.map((statement) => (
362
+ formatFinancialValue(financialCellValue(row, statement), row, statement)
363
+ )));
364
+ return financialPeriodWidth(values, periodHeaders);
365
+ }, [displayStatements, nativePaneChrome, periodHeaders, ratioTab, rows, subTab.rows]);
321
366
  const columns = useMemo<FinancialTableColumn[]>(() => [
322
367
  {
323
368
  id: "metric",
@@ -330,18 +375,12 @@ export function ResolvedFinancialsTab({
330
375
  id: `statement:${statement.date}:${index}`,
331
376
  kind: "statement",
332
377
  statement,
333
- // The annual balance sheet leads with a newer quarter-end position.
334
- label: padTo(financialColumnHeader(
335
- statement,
336
- isAnnual && (statement.date === "TTM" || annualDates.has(statement.date)) ? "annual" : "quarterly",
337
- yearEndMonth,
338
- comparisonCurrency,
339
- ), FINANCIAL_COL_W, "center"),
340
- width: FINANCIAL_COL_W,
378
+ label: padTo(periodHeaders[index]!, periodWidth, "center"),
379
+ width: periodWidth,
341
380
  align: "right",
342
381
  headerColor: statement.date === "TTM" ? colors.textBright : colors.textDim,
343
382
  })),
344
- ], [annualDates, comparisonCurrency, displayStatements, isAnnual, metricHeader, width, yearEndMonth]);
383
+ ], [displayStatements, metricHeader, periodHeaders, periodWidth, width]);
345
384
  const periodEnd = latestFinancialPeriodEnd(displayStatements);
346
385
  const renderCell = useCallback((
347
386
  row: FinancialTableRow,
@@ -349,22 +388,12 @@ export function ResolvedFinancialsTab({
349
388
  ): DataTableCell => {
350
389
  if (column.kind === "metric") {
351
390
  if (row.kind === "group") {
352
- const indent = " ".repeat(row.depth * 2);
353
- const marker = row.toggleable ? (row.expanded ? "\u25be" : "\u25b8") : " ";
354
391
  const labelColor = row.depth === 0 ? colors.textBright : colors.textDim;
355
392
  const labelAttributes = row.depth === 0 ? TextAttributes.BOLD : TextAttributes.NONE;
356
393
  return {
357
- text: `${indent}${marker} ${row.unitLabel}`,
394
+ ...financialGroupNameCell(row, labelColor, labelAttributes),
358
395
  color: labelColor,
359
396
  attributes: labelAttributes,
360
- // The desktop draws the disclosure as a path, not a glyph.
361
- content: (
362
- <Box flexDirection="row" alignItems="center" gap={1}>
363
- <Text fg={labelColor}>{indent}</Text>
364
- {row.toggleable ? <DisclosureMarker expanded={!!row.expanded} color={labelColor} /> : <Text> </Text>}
365
- <Text fg={labelColor} attributes={labelAttributes}>{row.unitLabel}</Text>
366
- </Box>
367
- ),
368
397
  onMouseDown: row.toggleable
369
398
  ? (event) => {
370
399
  event.preventDefault?.();
@@ -381,31 +410,24 @@ export function ResolvedFinancialsTab({
381
410
  };
382
411
  }
383
412
 
384
- const key = row.kind === "group" ? row.summaryKey : undefined;
385
- if (row.kind === "group" && !key) return {
413
+ if (row.kind === "group" && !row.summaryKey) return {
386
414
  text: "",
387
415
  };
388
416
 
389
417
  const previous = previousStatementMap.get(column.statement.date);
390
- const value = row.kind === "group"
391
- ? column.statement[key!] as number | undefined
392
- : statementMetricValue(row, column.statement);
393
- const previousValue = previous
394
- ? row.kind === "group"
395
- ? previous[key!] as number | undefined
396
- : statementMetricValue(row, previous)
397
- : undefined;
418
+ const value = financialCellValue(row, column.statement);
419
+ const previousValue = previous ? financialCellValue(row, previous) : undefined;
398
420
  const growth = (row.kind === "metric" && !row.showGrowth)
399
421
  || !canCompareFinancialRow(row, column.statement, previous, comparisonCurrency)
400
422
  ? undefined : computeGrowth(value, previousValue);
401
423
  const formattedValue = formatFinancialValue(value, row, column.statement);
402
- const cell = formatFinancialCell(formattedValue, growth);
424
+ const cell = formatFinancialCell(formattedValue, growth, column.width);
403
425
  const growthColorValue = semanticGrowthValue(growth, row.growthDirection);
404
426
 
405
427
  return {
406
428
  text: `${cell.valueText}${cell.growthText}`,
407
429
  content: (
408
- <Box flexDirection="row" width={FINANCIAL_COL_W}>
430
+ <Box flexDirection="row" width={column.width}>
409
431
  <Text
410
432
  attributes={row.kind === "group" ? TextAttributes.BOLD : TextAttributes.NONE}
411
433
  fg={colors.text}
@@ -547,7 +569,6 @@ export function ResolvedFinancialsTab({
547
569
  // Desktop: the query bar and table run edge to edge like every other
548
570
  // pane; the table keeps its own inline padding.
549
571
  paddingX={nativePaneChrome ? 0 : 1}
550
- paddingBottom={nativePaneChrome ? 0 : 1}
551
572
  overflow="hidden"
552
573
  >
553
574
  {isValuation && oldestPeriodEnd ? <PeriodEndHistoryLoader oldestPeriodEnd={oldestPeriodEnd} onChange={setHistory} /> : null}
@@ -578,6 +599,8 @@ export function ResolvedFinancialsTab({
578
599
  headerScrollId={headerScrollId}
579
600
  bodyScrollId={bodyScrollId}
580
601
  columns={columns}
602
+ // Fiscal periods, oldest to newest: an axis, not columns to arrange.
603
+ columnReorder={false}
581
604
  items={rows}
582
605
  selection={{
583
606
  kind: "id",
@@ -84,7 +84,8 @@ export function SurfaceHeatGrid({ grid, range, ticks, selected, onSelect, width,
84
84
  const first = ticks[0], last = ticks.at(-1);
85
85
  return <Box flexDirection="column" width={width} height={height} data-gloom-role="surface-grid" data-gloom-surface-renderer="grid">
86
86
  {notice ? <Box paddingX={1}><Notice tone="muted">{notice}</Notice></Box> : null}
87
- <DataTableView<HeatRow> rootWidth={width} rootHeight={Math.max(2, height - 1 - noticeRows)} columns={columns} items={rows}
87
+ {/* Moneyness or delta in order across the tenors: the surface's axis. */}
88
+ <DataTableView<HeatRow> rootWidth={width} rootHeight={Math.max(2, height - 1 - noticeRows)} columns={columns} columnReorder={false} items={rows}
88
89
  getItemKey={(row) => String(row.index)}
89
90
  selection={{ kind: "id", selectedId: selected ? String(selected.tenorIndex) : null, getId: (row) => String(row.index),
90
91
  onChange: (_id, row) => onSelect({ tenorIndex: row.index, moneynessIndex: selected?.moneynessIndex ?? 0 }) }}
@@ -500,7 +500,8 @@ export function VolSurfacePane({ focused, width, height }: PaneProps) {
500
500
  return sort.direction === "asc" ? delta : -delta;
501
501
  });
502
502
  const table = <DataTableView<SurfaceGridRow> focused={focused} rootWidth={width} rootHeight={tableHeight}
503
- columns={columns} items={sortedRows} getItemKey={(row) => row.label} scrollRef={scrollRef} onBodyScrollActivity={onScroll}
503
+ // Moneyness or delta in order across the tenors: the surface's axis.
504
+ columns={columns} columnReorder={false} items={sortedRows} getItemKey={(row) => row.label} scrollRef={scrollRef} onBodyScrollActivity={onScroll}
504
505
  sortColumnId={sort.columnId} sortDirection={sort.direction} onHeaderClick={(id) => setSort((current) => nextHeaderSort(current, id))}
505
506
  selection={{ kind: "id", selectedId: tableSelectedRow?.label ?? null, getId: (row) => row.label, onChange: (_id, row) => onSelectRow(row) }}
506
507
  onActivate={onSelectRow} onRootKeyDown={handleKey} getExportMetadata={exportMetadata} freezeFirstColumn
@@ -1,5 +1,5 @@
1
1
  import { useCallback, useEffect, useMemo, useState } from "react";
2
- import { DataTableView, type DataTableVisibleRange } from "../../../components";
2
+ import { DataTableView, type DataTableColumnReorder, type DataTableVisibleRange } from "../../../components";
3
3
  import type { PaneProps } from "../../../types/plugin";
4
4
  import type { PluginModule } from "../plugin-module";
5
5
  import { TICKER_RESEARCH_PANE_ID } from "../../../types/config";
@@ -39,6 +39,8 @@ function renderRegionHeader(row: WorldIndexTableRow) {
39
39
  return row.type === "header" ? { text: REGION_LABELS[row.region] } : null;
40
40
  }
41
41
 
42
+ const WORLD_INDEX_COLUMN_REORDER: DataTableColumnReorder = { anchored: 2 };
43
+
42
44
  function WorldIndicesPane({ focused, width, height }: PaneProps) {
43
45
  const { pinTicker } = usePluginTickerActions();
44
46
  const dataProvider = useAssetData();
@@ -124,6 +126,8 @@ function WorldIndicesPane({ focused, width, height }: PaneProps) {
124
126
  rootWidth={width}
125
127
  rootHeight={height}
126
128
  columns={columns}
129
+ // The session mark and the index name the row, whether or not the mark has a heading at this width.
130
+ columnReorder={WORLD_INDEX_COLUMN_REORDER}
127
131
  items={dataProvider ? flatRows : []}
128
132
  sortable
129
133
  sortColumnId={sortPreference.columnId}
@@ -471,7 +471,8 @@ function WorldTab({ onOpen, focused, width, height }: {
471
471
  <PaneStatusBody loading={loading && !data} error={!data ? error : null} loadingLabel="Loading world curves..." subject="world curves">
472
472
  <DataTableView<WorldRow>
473
473
  focused={focused} rootWidth={width} rootHeight={height}
474
- columns={WORLD_COLUMNS} items={rows} getItemKey={worldKey} renderCell={renderCell}
474
+ // Maturities in order, each beside its own change.
475
+ columns={WORLD_COLUMNS} columnReorder={false} items={rows} getItemKey={worldKey} renderCell={renderCell}
475
476
  selection={{ kind: "id", selectedId, getId: worldKey, onChange: (id) => setSelected(id) }}
476
477
  onActivate={(row) => onOpen(row.id)} sortColumnId={null} sortDirection="asc"
477
478
  emptyStateTitle="No curves yet."
@@ -0,0 +1,147 @@
1
+ import { useCallback, useEffect, useRef, useState, type MouseEvent as ReactMouseEvent, type RefObject } from "react";
2
+ import { COLUMN_DRAG_THRESHOLD_PX, columnDropBoundary, columnDropIndex } from "../../../components/ui/data-table/column-order";
3
+ import { hideDragShield, showDragShield } from "../host/drag-shield";
4
+
5
+ /** A header being dragged: the column's index, and where the drop line stands in the table's content (null where it would stay). */
6
+ export interface WebColumnDrag {
7
+ from: number;
8
+ dropLeft: number | null;
9
+ }
10
+
11
+ /** How near the body's side edge the pointer scrolls a wide table toward it while it drags a column, and how far each frame. */
12
+ const AUTO_SCROLL_EDGE_PX = 24;
13
+ const AUTO_SCROLL_STEP_PX = 8;
14
+
15
+ interface Span {
16
+ start: number;
17
+ end: number;
18
+ }
19
+
20
+ /** Where the line between two columns stands: in the middle of the gap, or just past the last column. */
21
+ function dropLineX(spans: readonly Span[], boundary: number): number | null {
22
+ const before = spans[boundary - 1];
23
+ const after = spans[boundary];
24
+ if (before && after) return (before.end + after.start) / 2;
25
+ const gap = spans.length > 1 ? Math.max(0, spans[1]!.start - spans[0]!.end) : 0;
26
+ if (before) return before.end + gap / 2;
27
+ if (after) return after.start - gap / 2;
28
+ return null;
29
+ }
30
+
31
+ /**
32
+ * A press on a movable header: released where it was, it sorts as a click
33
+ * does; moved past a few pixels, it drags the column, an accent line marks
34
+ * the gap it would drop into, and the release moves it there. A table wider
35
+ * than its body scrolls while the pointer holds at its side edge. Escape, or
36
+ * the window losing focus, puts the column back.
37
+ */
38
+ export function useWebColumnDrag({
39
+ contentRef,
40
+ bodyRef,
41
+ anchoredColumns,
42
+ onColumnMove,
43
+ onHeaderClick,
44
+ }: {
45
+ contentRef: RefObject<HTMLDivElement | null>;
46
+ bodyRef: RefObject<HTMLDivElement | null>;
47
+ anchoredColumns: number;
48
+ onColumnMove?: (columnId: string, toIndex: number) => void;
49
+ onHeaderClick?: (columnId: string) => void;
50
+ }) {
51
+ const [drag, setDrag] = useState<WebColumnDrag | null>(null);
52
+ const cleanupRef = useRef<(() => void) | null>(null);
53
+ const latest = useRef({ anchoredColumns, onColumnMove, onHeaderClick });
54
+ latest.current = { anchoredColumns, onColumnMove, onHeaderClick };
55
+ useEffect(() => () => cleanupRef.current?.(), []);
56
+
57
+ const startPress = useCallback((columnId: string, from: number, event: ReactMouseEvent<HTMLElement>) => {
58
+ cleanupRef.current?.();
59
+ const startX = event.clientX;
60
+ let pointerX = startX;
61
+ let dragging = false;
62
+ let frame = 0;
63
+ const measure = () => {
64
+ const cells = contentRef.current?.querySelectorAll<HTMLElement>(
65
+ '[data-gloom-role="data-table-header-row"] > [data-gloom-role="data-table-header-cell"]',
66
+ ) ?? [];
67
+ const spans = [...cells].map((cell) => {
68
+ const bounds = cell.getBoundingClientRect();
69
+ return { start: bounds.left, end: bounds.right };
70
+ });
71
+ // A frozen first column stays put while the others scroll under it: nothing drops among those it covers.
72
+ const frozenEnd = cells[0]?.style.position === "sticky" ? spans[0]?.end : undefined;
73
+ return { spans, frozenEnd, boundary: columnDropBoundary(spans, pointerX, latest.current.anchoredColumns, frozenEnd) };
74
+ };
75
+ const show = () => {
76
+ const { spans, frozenEnd, boundary } = measure();
77
+ const content = contentRef.current?.getBoundingClientRect();
78
+ const gapX = columnDropIndex(from, boundary) === null ? null : dropLineX(spans, boundary);
79
+ const lineX = gapX === null || frozenEnd === undefined ? gapX : Math.max(gapX, frozenEnd);
80
+ const dropLeft = lineX === null || !content ? null : lineX - content.left;
81
+ setDrag((current) => current?.from === from && current.dropLeft === dropLeft ? current : { from, dropLeft });
82
+ };
83
+ const autoScroll = () => {
84
+ frame = requestAnimationFrame(autoScroll);
85
+ const body = bodyRef.current;
86
+ if (!body || body.scrollWidth <= body.clientWidth) return;
87
+ const bounds = body.getBoundingClientRect();
88
+ const step = pointerX < bounds.left + AUTO_SCROLL_EDGE_PX ? -AUTO_SCROLL_STEP_PX
89
+ : pointerX > bounds.right - AUTO_SCROLL_EDGE_PX ? AUTO_SCROLL_STEP_PX : 0;
90
+ if (step === 0) return;
91
+ const before = body.scrollLeft;
92
+ body.scrollLeft = before + step;
93
+ if (body.scrollLeft !== before) show();
94
+ };
95
+ const cleanup = () => {
96
+ document.removeEventListener("mousemove", handleMove, true);
97
+ document.removeEventListener("mouseup", handleUp, true);
98
+ window.removeEventListener("keydown", handleKey, true);
99
+ window.removeEventListener("blur", cleanup);
100
+ cancelAnimationFrame(frame);
101
+ if (dragging) hideDragShield();
102
+ cleanupRef.current = null;
103
+ setDrag(null);
104
+ };
105
+ const handleMove = (moveEvent: MouseEvent) => {
106
+ if (moveEvent.buttons === 0) {
107
+ cleanup();
108
+ return;
109
+ }
110
+ pointerX = moveEvent.clientX;
111
+ if (!dragging) {
112
+ if (Math.abs(pointerX - startX) < COLUMN_DRAG_THRESHOLD_PX) return;
113
+ dragging = true;
114
+ showDragShield();
115
+ frame = requestAnimationFrame(autoScroll);
116
+ }
117
+ moveEvent.preventDefault();
118
+ show();
119
+ };
120
+ const handleUp = (upEvent: MouseEvent) => {
121
+ pointerX = upEvent.clientX;
122
+ const wasDragging = dragging;
123
+ const { boundary } = measure();
124
+ cleanup();
125
+ const { onColumnMove: move, onHeaderClick: sort } = latest.current;
126
+ if (!wasDragging) {
127
+ sort?.(columnId);
128
+ return;
129
+ }
130
+ const to = columnDropIndex(from, boundary);
131
+ if (to !== null) move?.(columnId, to);
132
+ };
133
+ const handleKey = (keyEvent: KeyboardEvent) => {
134
+ if (keyEvent.key !== "Escape" || !dragging) return;
135
+ keyEvent.preventDefault();
136
+ keyEvent.stopPropagation();
137
+ cleanup();
138
+ };
139
+ document.addEventListener("mousemove", handleMove, true);
140
+ document.addEventListener("mouseup", handleUp, true);
141
+ window.addEventListener("keydown", handleKey, true);
142
+ window.addEventListener("blur", cleanup);
143
+ cleanupRef.current = cleanup;
144
+ }, [bodyRef, contentRef]);
145
+
146
+ return { drag, startPress };
147
+ }
@@ -44,6 +44,7 @@ import {
44
44
  useScrollbarState,
45
45
  } from "./dom";
46
46
  import { WebDataTableHeader, WebDataTableRow } from "./row";
47
+ import { useWebColumnDrag } from "./column-drag";
47
48
 
48
49
  interface VirtualRow {
49
50
  index: number;
@@ -84,6 +85,8 @@ export function WebDataTable<T, C extends DataTableColumn = DataTableColumn>({
84
85
  sortColumnId,
85
86
  sortDirection,
86
87
  onHeaderClick,
88
+ onColumnMove,
89
+ anchoredColumns = 1,
87
90
  headerScrollRef,
88
91
  scrollRef,
89
92
  syncHeaderScroll: _syncHeaderScroll,
@@ -124,6 +127,14 @@ export function WebDataTable<T, C extends DataTableColumn = DataTableColumn>({
124
127
  const paneInstanceId = usePaneInstance()?.instanceId ?? null;
125
128
  const focusPane = useFocusOwningPane();
126
129
  const bodyElementRef = useRef<HTMLDivElement | null>(null);
130
+ const contentElementRef = useRef<HTMLDivElement | null>(null);
131
+ const { drag: columnDrag, startPress: pressMovableHeader } = useWebColumnDrag({
132
+ contentRef: contentElementRef,
133
+ bodyRef: bodyElementRef,
134
+ anchoredColumns,
135
+ onColumnMove,
136
+ onHeaderClick,
137
+ });
127
138
  const headerHorizontal = useScrollbarState(false);
128
139
  const headerVertical = useScrollbarState(false);
129
140
  const bodyHorizontal = useScrollbarState(showHorizontalScrollbar);
@@ -427,6 +438,7 @@ export function WebDataTable<T, C extends DataTableColumn = DataTableColumn>({
427
438
  onTouchMove={() => { controlledScrollOffsetRef.current = null; }}
428
439
  >
429
440
  <div
441
+ ref={contentElementRef}
430
442
  data-gloom-role="data-table-scroll-content"
431
443
  style={{
432
444
  position: "relative",
@@ -446,9 +458,19 @@ export function WebDataTable<T, C extends DataTableColumn = DataTableColumn>({
446
458
  onTableMouseDown={onTableMouseDown}
447
459
  gridTemplateColumns={gridTemplateColumns}
448
460
  onHeaderClick={onHeaderClick}
461
+ onMovableHeaderPress={onColumnMove ? pressMovableHeader : undefined}
462
+ anchoredColumns={anchoredColumns}
463
+ draggedColumn={columnDrag?.from ?? null}
449
464
  sortColumnId={sortColumnId}
450
465
  sortDirection={sortDirection}
451
466
  />
467
+ {columnDrag?.dropLeft != null ? (
468
+ <div
469
+ data-gloom-role="data-table-drop-indicator"
470
+ aria-hidden="true"
471
+ style={{ left: columnDrag.dropLeft }}
472
+ />
473
+ ) : null}
452
474
  {items.length === 0 ? (
453
475
  emptyContent ?? (
454
476
  <EmptyBody body={bodyElementRef}>
@@ -1,5 +1,5 @@
1
1
  /** @jsxImportSource react */
2
- import { memo, type CSSProperties, type ReactNode } from "react";
2
+ import { memo, type CSSProperties, type MouseEvent as ReactMouseEvent, type ReactNode } from "react";
3
3
  import { TextAttributes } from "../../../ui/host";
4
4
  import { DisclosureMarker } from "../../../components/ui/disclosure-marker";
5
5
  import type {
@@ -84,6 +84,9 @@ export function WebDataTableHeader<C extends DataTableColumn>({
84
84
  onTableMouseDown,
85
85
  gridTemplateColumns,
86
86
  onHeaderClick,
87
+ onMovableHeaderPress,
88
+ anchoredColumns = 1,
89
+ draggedColumn = null,
87
90
  sortColumnId,
88
91
  sortDirection,
89
92
  }: {
@@ -97,6 +100,11 @@ export function WebDataTableHeader<C extends DataTableColumn>({
97
100
  onTableMouseDown?: (event: any) => void;
98
101
  gridTemplateColumns: string;
99
102
  onHeaderClick?: (columnId: string) => void;
103
+ /** A left press on a header past the anchored ones, which sorts on release or drags the column (useWebColumnDrag). */
104
+ onMovableHeaderPress?: (columnId: string, index: number, event: ReactMouseEvent<HTMLElement>) => void;
105
+ anchoredColumns?: number;
106
+ /** The column being dragged, drawn lifted. */
107
+ draggedColumn?: number | null;
100
108
  sortColumnId: string | null;
101
109
  sortDirection: "asc" | "desc";
102
110
  }) {
@@ -125,11 +133,21 @@ export function WebDataTableHeader<C extends DataTableColumn>({
125
133
  {columns.map((column, columnIndex) => {
126
134
  const isSorted = sortColumnId === column.id;
127
135
  const color = isSorted ? CSS_TEXT : column.headerColor ?? CSS_TEXT_DIM;
136
+ const pressMovable = columnIndex >= anchoredColumns ? onMovableHeaderPress : undefined;
137
+ const movable = pressMovable !== undefined;
138
+ const sortOnPress = onHeaderClick ? (event: ReactMouseEvent<HTMLElement>) => {
139
+ focusPane();
140
+ onTableMouseDown?.(event);
141
+ event.preventDefault();
142
+ onHeaderClick(column.id);
143
+ } : undefined;
128
144
  return (
129
145
  <div
130
146
  key={column.id}
131
147
  data-gloom-role="data-table-header-cell"
132
- data-gloom-interactive={onHeaderClick ? "true" : undefined}
148
+ data-gloom-interactive={onHeaderClick || movable ? "true" : undefined}
149
+ data-gloom-movable={movable ? "true" : undefined}
150
+ data-gloom-dragging={draggedColumn === columnIndex ? "true" : undefined}
133
151
  data-gloom-tinted={column.headerColor ? "true" : undefined}
134
152
  style={{
135
153
  minWidth: 0,
@@ -152,12 +170,16 @@ export function WebDataTableHeader<C extends DataTableColumn>({
152
170
  backgroundColor: column.headerBackgroundColor ?? CSS_PANEL,
153
171
  boxShadow: freezeFirstColumn && columnIndex === 0 ? `-${inlinePaddingPx(horizontalPadding)}px 0 0 ${column.headerBackgroundColor ?? CSS_PANEL}, ${columnGap * WEB_CELL_WIDTH}px 0 0 ${column.headerBackgroundColor ?? CSS_PANEL}` : undefined,
154
172
  }}
155
- onMouseDown={onHeaderClick ? (event) => {
173
+ onMouseDown={pressMovable ? (event) => {
174
+ if (event.button !== 0) {
175
+ sortOnPress?.(event);
176
+ return;
177
+ }
156
178
  focusPane();
157
179
  onTableMouseDown?.(event);
158
180
  event.preventDefault();
159
- onHeaderClick(column.id);
160
- } : undefined}
181
+ pressMovable(column.id, columnIndex, event);
182
+ } : sortOnPress}
161
183
  >
162
184
  {column.headerLeading !== undefined ? <Leading>{column.headerLeading}</Leading> : null}
163
185
  <span
@@ -1694,6 +1694,28 @@ html[data-gloom-screenshot="true"] [data-gloom-role="chart-watermark"] {
1694
1694
  color: var(--gloom-text) !important;
1695
1695
  }
1696
1696
 
1697
+ /* A header that moves its column takes the grab cursor, as a tab that
1698
+ reorders does. Dragged, it takes the hover fill and its label brightens,
1699
+ and an accent line through the header and rows marks the gap it drops
1700
+ into (renderers/dom/data-table/column-drag.ts). */
1701
+ [data-gloom-role="data-table-header-cell"][data-gloom-movable="true"] { cursor: grab; }
1702
+ [data-gloom-role="data-table-header-cell"][data-gloom-dragging="true"] {
1703
+ background-image: linear-gradient(var(--gloom-hover-fill), var(--gloom-hover-fill));
1704
+ }
1705
+ [data-gloom-role="data-table-header-cell"][data-gloom-dragging="true"] > * {
1706
+ color: var(--gloom-text-bright) !important;
1707
+ }
1708
+ [data-gloom-role="data-table-drop-indicator"] {
1709
+ position: absolute;
1710
+ top: 0;
1711
+ bottom: 0;
1712
+ width: 2px;
1713
+ transform: translateX(-50%);
1714
+ z-index: 4;
1715
+ pointer-events: none;
1716
+ background: var(--gloom-accent);
1717
+ }
1718
+
1697
1719
  /* A link is the text around it, underlined (external-link.tsx); the pointer or keyboard focus brightens it. */
1698
1720
  [data-gloom-link="true"] { text-underline-offset: 2px; }
1699
1721
  [data-gloom-link="true"]:is(:hover, :focus-visible) { color: var(--gloom-link-hover) !important; }
@@ -133,6 +133,7 @@ export const OpenTuiChartSurface = forwardRef<unknown, ChartSurfaceProps>(functi
133
133
  bitmap: strip.bitmap,
134
134
  bitmapKey: `${strip.key}@${stripRect.x}:${stripRect.y}:${stripRect.width}x${stripRect.height}`,
135
135
  imageZIndex: CROSSHAIR_Z_INDEX,
136
+ anchor: { ...target.anchor, region: strip.rect },
136
137
  });
137
138
  });
138
139
  renderer.requestRender();
@@ -0,0 +1,33 @@
1
+ import { Renderable, RGBA, type CliRenderer } from "@opentui/core";
2
+ import type { NativeFrameHits } from "../../ui/host";
3
+
4
+ function filled(color: unknown): boolean {
5
+ return color instanceof RGBA && color.a > 0;
6
+ }
7
+
8
+ /**
9
+ * The terminal's hit grid as the image layer reads it: every renderable the
10
+ * frame drew claims its cells, the one drawn last on top, so it says what
11
+ * covers a kitty image whichever pane, menu, toast or bar drew it.
12
+ */
13
+ export function createFrameHits(renderer: CliRenderer): NativeFrameHits {
14
+ return {
15
+ at(x, y) {
16
+ if (renderer.isDestroyed) return null;
17
+ return Renderable.renderablesByNumber.get(renderer.hitTest(x, y)) ?? null;
18
+ },
19
+ paints(renderable) {
20
+ const node = renderable as { backgroundColor?: unknown; bg?: unknown };
21
+ return filled(node.backgroundColor) || filled(node.bg);
22
+ },
23
+ attached(renderable) {
24
+ let node = renderable as { parent?: unknown; isDestroyed?: boolean } | null;
25
+ if (!node || node.isDestroyed) return false;
26
+ for (let depth = 0; node && depth < 512; depth += 1) {
27
+ if (node === renderer.root) return true;
28
+ node = (node.parent ?? null) as typeof node;
29
+ }
30
+ return false;
31
+ },
32
+ };
33
+ }
@@ -13,6 +13,7 @@ import { installInteractionPerformanceRecorder } from "./interaction-performance
13
13
  import { provideKittyServices } from "./kitty-services";
14
14
  import { setTerminalReportsControlKeys } from "../../app/keybindings/terminal-keys";
15
15
  import { captureRendererFrame } from "./frame-capture";
16
+ import { createFrameHits } from "./frame-hits";
16
17
  import {
17
18
  createTimerFrameDriver,
18
19
  installMarketDataFrameDriver,
@@ -245,6 +246,7 @@ export async function createOpenTuiHost(): Promise<OpenTuiHost> {
245
246
  removePostProcessFn: (processFn) => renderer.removePostProcessFn(processFn as any),
246
247
  copyToClipboardOSC52: (text) => renderer.copyToClipboardOSC52(text),
247
248
  captureFrame: () => captureRendererFrame(renderer),
249
+ frameHits: createFrameHits(renderer),
248
250
  async capturePaneImage(rect) {
249
251
  if (renderer.isDestroyed) throw new Error("The terminal has closed.");
250
252
  // Loaded on first use: the glyph atlas is only needed for a picture.