@topgrid/grid
Meta package — aggregates all @topgrid/grid-* packages (MIT + Pro facade) · 상용 (EULA)
이 페이지는 소스 코드의 TSDoc 주석에서 자동 생성됩니다(내부 표식 정제). 큐레이트된 시작용 요약은 API 레퍼런스 참고.
총 491개 public export — 함수 138 · 훅 21 · 컴포넌트 59 · 타입 264 · 상수 9.
컴포넌트
AggregationGrid
AggregationGrid — Pro component for row grouping + aggregation.
AggregationGrid(__namedParameters: AggregationGridProps<TData>): Element
예시
<AggregationGrid
data={rows}
columns={columns}
enableAggregation
grouping={['region']}
showFooter
/>
AvatarCell
Avatar cell — image with initials fallback ( handles broken src by swapping to the initials chip via onError state).
AvatarCell(__namedParameters: AvatarCellProps): Element
BaseGrid
BaseGrid — DEPRECATED alias of <Grid> ( props mapping).
AS-IS legacy BaseGrid 의
sort+filter ALWAYS wiring + pagination conditional 패턴을 유지.
BaseGrid(props: BaseGridProps<TData>): Element
ButtonCell
Button cell — small action button suitable for grid action columns.
Click handler stops propagation so it never triggers a row click (L0 pattern preserved). Variant Tailwind classes equal the L0 mapping with renamed keys ( — no visual change).
When both value and label are undefined, renders an empty <button>
(new behaviour — previously impossible since label was required; spec §5.1 fallback).
ButtonCell(__namedParameters: ButtonCellProps): Element
ChangeTrackingGrid
ChangeTrackingGrid(props: ChangeTrackingGridProps<TData> & { … }): ReactElement
ChartCard
RangeChart wrapped with an interactive type-switcher toolbar.
The toolbar buttons use inline styles (not Tailwind) so they are testable in the Tailwind-less
storybook harness (P27-1) and visibly reflect the active type via aria-pressed. Clicking a
button re-renders the chart with the new type — the chart shape genuinely changes
(data-chart-type), which is the non-vacuous claim the gate checks.
ChartCard(__namedParameters: ChartCardProps): Element
CheckCell
Checkbox cell — wraps a native <input type="checkbox"> centred inside
a flex container (L0 markup preserved). Both onClick and onChange call
stopPropagation so they never bubble to the grid row click handler.
CheckCell(__namedParameters: CheckCellProps): Element
ColumnPinGrid
ColumnPinGrid(props: ColumnPinGridProps<TData>): Element
ContextMenuGrid
ContextMenuGrid(props: ContextMenuGridProps<TData> & { … }): ReactElement
DataMapCell
DataMapCell<TData>: TanStack CellContext 수신 → column.dataMap.getDisplay(value) → 레이블 렌더.
- 정적 dataMap: column.columnDef.dataMap가 DataMap 인스턴스
- 함수형 dataMap: column.columnDef.dataMap(row.original) → DataMap 인스턴스
- getDisplay 결과 없음(undefined) → String(value ?? '') fallback (.3)
- dataMap 미설정 시 → String(value ?? '') fallback (.1)
: TanStack CellContext 표준 API 사용 : no any (DataMapColumnDef<TData> 타입 캐스팅 — DataMap 전용 확장 필드 접근용) : 가상화 호환 — resolveDataMap + getDisplay 모두 O(1)
DataMapCell(info: CellContext<TData, unknown>): Element
| 파라미터 | 타입 | 설명 |
|---|---|---|
info | CellContext<TData, unknown> | TanStack CellContext<TData, unknown> (createColumns.ts L128-130 패턴) |
반환 — span 엘리먼트 — 레이블 텍스트 또는 fallback
DataMapEditor
DataMapEditor<TItem>: 편집 셀 필터-타이핑 드롭다운 컴포넌트.
- 마운트 시 input에 자동 포커스
- 타이핑 → items 필터링 (대소문자 무관, IME 조합 중 필터 억제)
- 드롭다운: absolute z-50 bg-white border border-gray-200 rounded shadow-md max-h-48 overflow-y-auto
- 키보드: ArrowDown/Up 이동, Enter 선택, Escape 취소
- ARIA: role="combobox" + aria-expanded + role="listbox" + role="option"
- highlightedIndex: filtered.length 변경 시 -1 리셋 (spec Section 11.2 risk #4)
- isComposing: useRef<boolean> 사용 — setState 불필요 (spec Section 11.2 risk #3)
: DataMapEditorProps<TItem> 표준 API (spec Section 3.1) : no any — TItem 제네릭 상한 : Tailwind CSS only : getItems + Array.filter — O(n), 가상화 호환
DataMapEditor(props: DataMapEditorProps<TItem>): Element
| 파라미터 | 타입 | 설명 |
|---|---|---|
props | DataMapEditorProps<TItem> | DataMapEditorProps<TItem> |
반환 — 입력 필드 + 조건부 드롭다운 컨테이너
DateCell
Date/time cell renderer with locale-aware formatting.
Uses formatDateTimeFromDateTimeString (extracted from L0 inline toLocaleDateString + FORMAT_OPTIONS pattern). Returns dash for empty/invalid.
DateCell(__namedParameters: DateCellProps): Element
DateFilter
날짜 범위 필터 컴포넌트.
FilterPopover + FilterIndicator를 재사용하여 from/to DatePicker를 렌더.
column.setFilterValue 로 TanStack Table 필터링을 트리거.
DateFilter(__namedParameters: DateFilterProps<TData>): Element
예시
columnHelper.accessor('orderDate', {
filterFn: dateRangeFilterFn,
header: ({ column }) => (
<div>
주문일
<DateFilter column={column} />
</div>
),
});
DragFillHandle
DragFillHandle(__namedParameters: DragFillHandleProps<TCell>): null | ReactElement<any, string | JSXElementConstructor<any>>
DropIndicator
드래그 drop 위치에 렌더되는 파란 수직선 인디케이터.
DropIndicator(__namedParameters: { … }): null | Element
EditableCell
Inline editable cell with view ↔ edit mode transitions.
Markup contract (spec — absorbs L0 EditableGrid L82-126):
- View mode:
<div onClick={onStartEdit}>showingString(value ?? ''). - Edit mode (
isEditing === true): 'select'→<select>with options (or(옵션 없음)placeholder).'textarea'→<textarea>(Enter inserts newline; Tab/Blur commits).- default →
<input type={'text'|'number'|'date'}>.
Keyboard handling (L0 L65-72 preserved):
- Enter →
onCommit(draft)(excepttextarea— newline preserved). - Escape →
onCancel. - Tab →
e.preventDefault+onCommit(draft).
Local draft state is reset to String(value ?? '') whenever the cell
enters edit mode (via useEffect), which also schedules inputRef.focus.
When initialDraft is provided, the draft is initialised to it on the first
render (lazy useState) and the useEffect reset is skipped — the typed
character is already in the input when the <input> mounts.
EditableCell(__namedParameters: EditableCellProps): Element
FilterIndicator
활성 필터 인디케이터 — 파란 dot.
column.getIsFiltered 결과값을 isFiltered prop으로 전달.
필터 비활성 시 null 반환 (DOM 요소 없음).
FilterIndicator(__namedParameters: FilterIndicatorProps): null | Element
예시
<FilterIndicator isFiltered={column.getIsFiltered()} />
FilterPopover
텍스트 필터용 Popover 컨테이너.
trigger prop으로 트리거 요소를 받고, children으로 팝오버 내용을 렌더. open/close 상태를 내부적으로 관리 (외부 제어 불필요).
FilterPopover(__namedParameters: FilterPopoverProps): Element
FilterResetButton
필터 전체 초기화 버튼 컴포넌트.
FilterResetButton(__namedParameters: FilterResetButtonProps<TData>): Element
FiltersToolPanel
FiltersToolPanel — unified column-filter editing surface with an active-filter count.
Callback-only (no grid state). Pro watermark composited when unlicensed (root is relative).
FiltersToolPanel(__namedParameters: FiltersToolPanelProps): Element
GlobalSearchInput
전체 행 검색 입력 컴포넌트 (debounce 300ms).
GlobalSearchInput(__namedParameters: GlobalSearchInputProps<TData>): Element
Grid
Grid(props: GridProps<TData> & { … }): ReactElement
GridPagination
Pagination UI 컨테이너 컴포넌트.
GridPagination(__namedParameters: GridPaginationProps<TData>): Element
GroupedHeaderGrid
Legacy self-contained grid component with grouped multi-row headers.
Delegates header rendering to MultiRowHeader from @topgrid/grid-pro-header.
tbody and pagination are ported verbatim from AS-IS L0.
GroupedHeaderGrid(__namedParameters: GroupedHeaderGridProps<TData>): Element
GroupPanel
GroupPanel — drag-and-drop grouping bar.
Renders above the grid table. Column <th> elements in AggregationGrid
are marked draggable={true} when showGroupPanel=true, allowing users to
drag a column header here to add it to the grouping.
Chip X click removes the column from grouping ( uncontrolled support).
GroupPanel(__namedParameters: GroupPanelProps<TData>): ReactElement
IconCell
Icon cell — display an icon (with optional supporting label and click handler). The component is library-agnostic: it accepts any ReactNode for the icon prop ( — no external icon package dependency).
IconCell(__namedParameters: IconCellProps): Element
LinkCell
Link cell — renders one of three forms based on :
hrefprovided →<a href>(with onClick passthrough if any)- only
onClick→<button>(L0 behaviour preserved) - neither →
<span>(plain text or empty)
When both value and label are undefined, renders an empty <span> (new
behaviour — previously impossible since label was required; spec §5.1 fallback).
Click handlers call e.stopPropagation to prevent grid row click bubbling
(L0 ButtonCell/LinkCell pattern preserved).
LinkCell(__namedParameters: LinkCellProps): Element
MasterDetailGrid
MasterDetailGrid(props: MasterDetailGridProps<TData> & { … }): ReactElement
MergingGrid
셀 병합(rowSpan) 기능을 제공하는 Pro 그리드 컴포넌트.
enableMerging=false(기본값) 시 일반 그리드와 동일하게 동작.
enableMerging=true 시 meta.mergeRows가 설정된 컬럼에서 연속 행 병합.
enableVirtualization=true 시 @tanstack/react-virtual useVirtualizer로 대규모 데이터 렌더링.
MergingGrid(props: MergingGridProps<TData>): Element
예시
// 기본 사용 (G-001)
<MergingGrid data={rows} columns={columns} enableMerging />
MultiFilter
컬럼당 복합(AND/OR) 필터 빌더 — 2 조건 행.
MultiFilter(variant: { … }): Element
| 파라미터 | 타입 | 설명 |
|---|---|---|
variant | { … } | 'text'(contains 등) | 'number'(=,>,… ). column.filterFn 은 각각 multiTextFilterFn / multiNumberFilterFn 으로 등록되어야 한다. |
MultiRowHeader
Renders a multi-row <thead> element from a TanStack table instance.
Iterates table.getHeaderGroups to produce one <tr> per header row.
Group header cells use header.colSpan (computed by TanStack automatically).
Placeholder cells (header.isPlaceholder) are rendered as empty <th> elements.
Sorting is enabled only on leaf columns (!header.subHeaders.length).
MultiRowHeader(props: MultiRowHeaderProps<TData>): Element
| 파라미터 | 타입 | 설명 |
|---|---|---|
props | MultiRowHeaderProps<TData> | MultiRowHeaderProps<TData>. |
반환 — A <thead> JSX element with all header rows.
NumberCell
Numeric cell renderer with locale-aware formatting + optional unit + optional negative color.
Uses formatNumberString (extracted from L0 inline toLocaleString pattern).
NumberCell(__namedParameters: NumberCellProps): Element
NumberFilter
숫자 필터 UI — 7가지 연산자 select + 조건부 input + clear 버튼.
FilterPopover + FilterIndicator를 조합한 메인 컴포넌트 ( 재사용).
column.setFilterValue로 TanStack columnFilters에 연결.
디바운스 300ms (Section 4.6).
between 연산자: min/max 두 input 조건부 렌더 (, Section 5.3).
NumberFilter(__namedParameters: NumberFilterProps<TData>): Element
예시
// columnDef header에 렌더:
header: ({ column }) => (
<div className="flex items-center gap-1">
<span>가격</span>
<NumberFilter column={column} defaultOperator="=" />
</div>
),
filterFn: numberFilterFn,
NumberFloatingFilter
숫자 floating 필터 — always-visible 입력 1개. 연산자 =(정확히 일치) 고정, 300ms 디바운스 후
NumberFilterValue set(빈 값=해제). filterFn: numberFilterFn 컬럼에 사용.
NumberFloatingFilter(__namedParameters: { … }): Element
PageSizeSelect
PageSizeSelect(props: PageSizeSelectProps): ReactNode
PivotGrid
PivotGrid — declarative 2-D pivot table over grid-core <Grid>.
PivotGrid(__namedParameters: PivotGridProps<TData>): Element
예시
<PivotGrid
data={sales}
config={{
rows: ['region'],
columns: ['quarter'],
values: [{ field: 'sales', aggregationFn: 'sum' }],
}}
/>
PivotPanel
PivotPanel — drag fields between Available / Rows / Columns / Values to
configure a pivot. Pair it with a <PivotGrid> driven by the same config
state so dropping a field re-pivots the grid.
PivotPanel(__namedParameters: PivotPanelProps): ReactElement
ProgressCell
Progress cell — Tailwind track + bar (h-2 rounded) with optional percent
label. Bar width uses a dynamic style={{ width }} value (spec
deviation: Tailwind JIT arbitrary widths cannot be runtime-driven).
ProgressCell(__namedParameters: ProgressCellProps): Element
RangeChart
Built-in cartesian range chart — pure SVG, zero chart-library dependency (/AP-001).
Layout/scaling is delegated to computeChartGeometry (the node-tested core); this
component turns the computed pixel coordinates into <rect>/<polyline>/<polygon>/axis
elements, plus an in-SVG legend and hover tooltip (kept INSIDE the <svg> — no HTML overlay —
to stay consistent with the pure-SVG decision and avoid a wrapper-positioning refactor).
RangeChart(__namedParameters: RangeChartProps): Element
RangeChartPanel
Range chart panel — renders an injected chart for one or more numeric series.
This package bundles no charting library; the caller supplies renderChart
(adapter injection, / AP-001). Without a valid Pro license a watermark
is composited over the panel (the root is relative so the absolutely
positioned <Watermark> anchors to it).
RangeChartPanel(__namedParameters: RangeChartPanelProps): Element
RangeSelectGrid
RangeSelectGrid — 5-hook 완전 통합.
Rules of Hooks: 5개 hook 전부 무조건 호출. enable* = behavior gate (not hook invocation gate). onKeyDown 합성: editKeyDown → navKeyDown → clipKeyDown.
RangeSelectGrid(props: RangeSelectGridAllProps<TData, TCell>): ReactElement
예시
// v0.1.x 그대로 동작 (C-6 backward compat)
<RangeSelectGrid data={rows} columns={columns} />
// v0.2.0 — Drag-fill + Clipboard 활성화
<RangeSelectGrid<MyData, string>
data={data}
columns={columns}
enableDragFill
enableClipboard
getCellValue={(row, col) => getValue(row, col)}
onFillComplete={(cells) => apply(cells)}
onPaste={(cells) => apply(cells)}
/>
RowGroupPanel
RowGroupPanel — the drag-and-drop grouping bar.
REUSE: all grouping behaviour (HTML5 drag, chips, remove) is delegated to the
agg GroupPanel; this wrapper only composites the Pro watermark. The root is
relative so the absolutely positioned <Watermark> anchors to it.
RowGroupPanel(props: RowGroupPanelProps<TData>): Element
SelectFilter
Excel-style 다중선택 체크박스 필터 컴포넌트.
SelectFilter(__namedParameters: SelectFilterProps<TData>): Element
SheetGrid
SheetGrid(__namedParameters: SheetGridProps): Element
SideBar
SideBar — accordion container for tool panels. One section open at a time; clicking an open
section's header collapses it. Pro watermark composited when unlicensed (root is relative).
SideBar(__namedParameters: SideBarProps): Element
SortBadge
다중 정렬 우선순위 배지 — grid-core canonical source.
SortBadge(__namedParameters: SortBadgeProps): null | Element
SortClearButton
현재 정렬 상태를 전부 지우는 버튼.
onClear 콜백에 table.setSorting([]) 를 연결하여 사용.
SortClearButton(__namedParameters: SortClearButtonProps): Element
예시
<SortClearButton onClear={() => table.setSorting([])} />
참고 — SortClearButtonProps
SparklineCell
Sparkline cell — compact inline SVG chart for a numeric series.
Library-agnostic and zero-dependency: the chart is drawn with native SVG
<polyline>/<polygon>/<rect> elements, so no charting peer is required
( / AP-001 — the package imports no chart library).
SparklineCell(__namedParameters: SparklineCellProps): Element
StatusBadgeCell
Status badge cell — renders value as a Tailwind rounded-full chip coloured by colorMap (or a 7-state default).
Equivalent to the legacy BadgeCell;
the shim there re-exports this component under the legacy name ( alias).
StatusBadgeCell(__namedParameters: StatusBadgeCellProps): Element
StatusBar
StatusBar — a horizontal bar of label: value segments.
Pure prop-driven UI: the consumer passes whatever items it wants to surface
(selection counts, aggregate summaries, etc.). It composites no grid. Without
a valid Pro license a watermark is composited over the bar (the root is
relative so the absolutely positioned <Watermark> anchors to it).
StatusBar(__namedParameters: StatusBarProps): Element
TagCell
Tag cell — renders a flex-wrap row of tag chips. Used for multi-valued label columns (e.g. priority tags, category tags). Each chip's colour comes from colorMap or defaults to neutral gray.
TagCell(__namedParameters: TagCellProps): Element
TextCell
Plain text cell renderer with null/empty dash placeholder.
Distinguishes empty (null/undefined/'') from falsy zero — 0 renders as "0".
TextCell(__namedParameters: TextCellProps): Element
TextFilter
텍스트 필터 UI — 연산자 select + 값 input + clear 버튼.
FilterPopover + FilterIndicator를 조합한 메인 컴포넌트.
column.setFilterValue로 TanStack columnFilters에 연결.
디바운스 300ms (Section 4.5).
TextFilter(__namedParameters: TextFilterProps<TData>): Element
예시
// columnDef header에 렌더:
header: ({ column }) => (
<div className="flex items-center gap-1">
<span>이름</span>
<TextFilter column={column} defaultOperator="contains" />
</div>
),
filterFn: textFilterFn,
TextFloatingFilter
텍스트 floating 필터 — always-visible 입력 1개. 연산자 contains 고정(기존 값의 연산자는 보존),
300ms 디바운스 후 TextFilterValue set(빈 값=해제). filterFn: textFilterFn 컬럼에 사용.
TextFloatingFilter(__namedParameters: { … }): Element
ToolPanel
ToolPanel — a declarative column visibility / order control surface.
A checkbox per column toggles visibility (onVisibilityChange); optional
up/down buttons request a reorder (onReorder). The panel holds no column
state machine of its own — it emits callbacks the consumer applies to its
grid-core columnVisibility / columnOrder state. It composites no grid.
Without a valid Pro license a watermark is composited over the panel (the
root is relative so the absolutely positioned <Watermark> anchors to it).
ToolPanel(__namedParameters: ToolPanelProps): Element
TotalCount
TotalCount(props: TotalCountProps): ReactNode
TreeGrid
TreeGrid(props: TreeGridProps<TData>): Element
VirtualGrid
VirtualGrid(props: VirtualGridProps<TData>): Element
Watermark
Pro 라이선스가 없을 때 그리드 위에 표시되는 워터마크 컴포넌트.
required=false 이면 null 반환 (렌더링 없음).
Watermark(__namedParameters: WatermarkProps): null | ReactElement<any, string | JSXElementConstructor<any>>
훅 (Hooks)
useCellComments
셀 코멘트 + storage 영속 훅 — (AC ③).
마운트 시 storage 에서 hydrate, 변경 시 persist(버전 봉투). SSR/storage 비가용 시 in-memory
no-op(throw 없음). 순수 직렬화/키 로직은 ./commentStore([[commentStore]], node 검증).
useCellComments(options: UseCellCommentsOptions): CellCommentsAPI
useCellRange
마우스 드래그/Shift+Click 셀 범위 선택 훅.
useCellRange(onRangeChange: (…) => …): UseCellRangeReturn
| 파라미터 | 타입 | 설명 |
|---|---|---|
onRangeChange | (…) => … | 범위 변경 시 호출되는 콜백. |
반환 — 범위 state + 이벤트 핸들러 3종.
예시
const { range, handleMouseDown, handleMouseEnter, handleMouseUp } =
useCellRange((r) => console.log('range changed:', r));
useChangeTracking
React hook for tracking row-level added/edited/deleted changes (/ —..).
rows/added/edited/deletedare stable across renders that leave the underlying state unchanged (memoized viauseMemo).addRowreturns the assigned row key synchronously so callers can immediately reference it (e.g. focus the new row, schedule a follow-upupdateRow).undoRowandcommitChangesremain stubs — implemented in / and respectively.
useChangeTracking(config: ChangeTrackingConfig<TData>): ChangeTrackingAPI<TData>
useClipboard
useClipboard(props: UseClipboardProps<TData, TCell>): UseClipboardReturn
useColumnDrag
HTML5 Drag and Drop API 기반 컬럼 재정렬 hook.
useColumnDrag(props: UseColumnDragProps<TData>): UseColumnDragReturn
| 파라미터 | 타입 | 설명 |
|---|---|---|
props | UseColumnDragProps<TData> | UseColumnDragProps |
반환 — UseColumnDragReturn
useColumnOrderPersist
컬럼 순서를 localStorage에 저장/복원하는 hook.
- 반환:
{ saveOrder }— useColumnDrag 내부 handleColumnOrderChange에서 호출 - mount 시: localStorage.getItem → JSON.parse → table.setColumnOrder ( 복원)
- save 방법:
saveOrder(order)호출 → localStorage.setItem - 모든 localStorage 접근: adapter 가 try/catch
- SSR guard: adapter 가 처리
- QuotaExceededError: adapter 가 console.warn + silent skip
useColumnOrderPersist(__namedParameters: UseColumnOrderPersistProps<TData>): { … }
useExpandedPersistence
Pro-tier hook — persists TanStack ExpandedState to Web Storage.
useExpandedPersistence(options: UseExpandedPersistenceOptions): [ExpandedState, ExpandedStateSetter]
| 파라미터 | 타입 | 설명 |
|---|---|---|
options | UseExpandedPersistenceOptions | Persistence options (storageKey, storageType, initialExpanded). |
반환 — [expanded, setExpanded] tuple compatible with TanStack ExpandedState.
useGridState
8개 TanStack 표준 state + setter를 한 번에 반환하는 통합 훅.
기존 variant(BaseGrid/VirtualGrid/...) 에서 각각 선언하던 5~7개의
useState<StateType> 호출을 1줄로 대체한다.
** 확장 (controlled/uncontrolled/initialState)**:
options미제공 시 과 동일 동작 (모든 state uncontrolled, 기본값).initialState: uncontrolled 모드에서 특정 키의 초기값 지정.state: 키 단위 controlled 모드 (state.sorting이 있으면 sorting controlled, 나머지 uncontrolled).onStateChange(next, key): state 변경 시 통보 — controlled/uncontrolled 양쪽 호출.
** (controlled + initialState 동시 제공)**: state 제공 시 해당 키의 initialState는 무시됨 (controlled 우선).
useGridState(options: UseGridStateOptions<TData>): GridState<TData>
반환 — GridState<TData> — 8 state 값 + 8 OnChangeFn<StateType> setter 객체.
예시
// G-001 호환 (파라미터 없음)
const s = useGridState<User>();
// uncontrolled + initialState (G-002)
const s = useGridState<Slip>({
initialState: { sorting: [{ id: 'date', desc: true }], pagination: { pageIndex: 0, pageSize: 20 } },
});
// controlled mode — Redux 연동 (G-002)
const s = useGridState<Attendance>({
state: { sorting: externalSorting },
onStateChange: (next, key) => {
if (key === 'sorting') dispatch(setGridSorting(next.sorting));
},
});
// TanStack useReactTable 직접 소비
const table = useReactTable<User>({
data,
columns,
state: {
sorting: s.sorting,
columnFilters: s.columnFilters,
rowSelection: s.rowSelection,
pagination: s.pagination,
},
onSortingChange: s.setSorting,
onColumnFiltersChange: s.setColumnFilters,
onRowSelectionChange: s.setRowSelection,
onPaginationChange: s.setPagination,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
});
G-004 확장 (resetState / resetSection / clearSelectionKey):
resetState(): 8개 state 모두initialState(or defaultValues) 로 복원.resetSection(key): 단일 또는 배열 key 의 state 만 선택적 복원 (Set dedup 멱등).options.clearSelectionKey: 외부 트리거 (string | number) 변경 시rowSelection자동 reset. XxgridTableclearSelectionKey패턴 흡수 (R-A). mount 시 reset 미발생 (isFirstClearRender flag).
참고 — - GridState, - UseGridStateOptions
useKeyboardEdit
useKeyboardEdit — Delete/F2/Enter/printable key 분기 hook.
useKeyboardEdit(props: UseKeyboardEditProps<TData, TCell>): UseKeyboardEditReturn
반환 — { onKeyDown } — Grid container에 부착할 keydown 핸들러.
예시
const { onKeyDown: editKeyDown } = useKeyboardEdit({ selection, activeCell, ... });
// D7: G-005 앞에 배치 (D5 Enter 우선순위)
const onKeyDown = useCallback((e: React.KeyboardEvent) => {
editKeyDown(e);
if (e.defaultPrevented) return;
navKeyDown(e); // G-002
clipKeyDown(e); // G-004
}, [editKeyDown, navKeyDown, clipKeyDown]);
useKeyboardNav
useKeyboardNav(options: UseKeyboardNavOptions<TData>): UseKeyboardNavReturn
useLicenseStatus
React hook returning the current license check result. Re-renders when the
license state changes (e.g. async setLicenseKey resolution).
Backed by useSyncExternalStore — no tearing under React 18 concurrent mode.
useLicenseStatus(): LicenseCheckResult
예시
function MyGrid() {
const lic = useLicenseStatus();
return (
<div className="relative">
<table>{ ... }</table>
{lic.watermarkRequired && <Watermark required />}
</div>
);
}
useMultiSort
useReactTable 직접 사용자가 다중 정렬 옵션을 구성할 때 사용하는 헬퍼.
useMultiSort(opts: UseMultiSortOptions): UseMultiSortResult
예시
const { enableMultiSort, isMultiSortEvent } = useMultiSort({ enableMultiSort: true });
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
enableMultiSort,
isMultiSortEvent,
});
usePivot
Compute a memoised PivotModel from flat data + a pivot config.
usePivot(data: TData[], config: PivotConfig): PivotModel
| 파라미터 | 타입 | 설명 |
|---|---|---|
data | TData[] | Flat source rows. |
config | PivotConfig | Row/column dimensions + value (measure) definitions. |
반환 — A memoised pivot model (recomputed when data or config change).
예시
const model = usePivot(rows, {
rows: ['region'],
columns: ['quarter'],
values: [{ field: 'sales', aggregationFn: 'sum' }],
});
useServerSideData
useServerSideData(datasource: ServerSideDatasource<TData>, options: UseServerSideDataOptions): UseServerSideDataResult<TData>
useServerSideTree
useServerSideTree(datasource: ServerSideDatasource<TData>, options: UseServerSideTreeOptions): UseServerSideTreeResult<TData>
useSheet
useSheet(): UseSheetResult
useStoragePersist
GridStateValues ↔ localStorage / sessionStorage 동기화 옵션 helper.
- state 변경 시
debounceMs(기본 300ms) 후 storage에 저장 - mount 시 storage → state 역방향 hydration (
onHydrate콜백 — ) - version mismatch / parse 실패 →
removeItem+onHydrate미호출 - SSR safe (
typeof windowguard inside useEffect body — ) - 완전 준수: option 3 (eslint-disable) 0줄 (Option A saveRef 패턴 — )
useStoragePersist(state: GridStateValues<TData>, options: UseStoragePersistOptions<TData>): void
| 파라미터 | 타입 | 설명 |
|---|---|---|
state | GridStateValues<TData> | useGridState 또는 기타 소스의 GridStateValues |
options | UseStoragePersistOptions<TData> | UseStoragePersistOptions (storageKey 필수) |
예시
const state = useGridState();
useStoragePersist(state, {
storageKey: 'my-grid-v1',
version: 1,
onHydrate: (partial) => {
if (partial.sorting) state.setSorting(partial.sorting);
if (partial.columnFilters) state.setColumnFilters(partial.columnFilters);
},
});
useUndoRedo
제네릭 undo/redo 명령 스택 훅 —.
동작을 수행한 뒤 그 동작의 {undo, redo} 명령을 push 한다. tracking 연산 명령은
makeUpdateCommand/makeAddCommand 로 만든다([[bindings]]). tracking 은 연산 히스토리를
노출하지 않으므로 본 스택이 외부 히스토리 역할을 한다(Option B, advisor).
명령의 부작용은 state updater 밖(이벤트 핸들러)에서 실행한다 — ref 가 진실, bump 는
재렌더만 유발(StrictMode 이중 실행 회피).
useUndoRedo(): UndoRedoAPI
useUrlSync
GridStateValues의 임의 subset을 URL search params에 동기화하는 옵션 helper.
- state 변경 시
window.history.replaceState로 URL 갱신 - mount 시 URL → state 역방향 hydration (
onHydrate콜백 — ) - debounce 지원 (
debounceMs옵션 —useDebouncedCallback재사용) - router 라이브러리 의존 없음
- SSR safe (:
typeof window체크는 useEffect body 내부)
useUrlSync(state: GridStateValues<TData>, options: UseUrlSyncOptions<TData>): void
| 파라미터 | 타입 | 설명 |
|---|---|---|
state | GridStateValues<TData> | useGridState 또는 기타 소스의 GridStateValues |
options | UseUrlSyncOptions<TData> | UseUrlSyncOptions (전부 optional) |
예시
const state = useGridState();
useUrlSync(state, {
keys: ['sorting', 'columnFilters'],
onHydrate: (partial) => {
if (partial.sorting) state.setSorting(partial.sorting);
if (partial.columnFilters) state.setColumnFilters(partial.columnFilters);
},
});
useViewportRowModel
useViewportRowModel(datasource: ViewportDatasource<TData>, options: UseViewportRowModelOptions): UseViewportRowModelResult<TData>
useWatermarkEnforcement
Void registration hook for license watermark enforcement via a singleton
portal mounted at document.body.
- Each mount increments a module-level ref-count.
- First mount creates the singleton portal + React root.
- License state changes (
setLicenseKey) re-render the portal viasubscribeLicense. - Last unmount (ref-count → 0) tears down the portal.
Use case: per-cell renderers (e.g. DataMapCell) where the component
itself has no host DOM suitable for wrapper-based watermarking.
SSR-safe: portal setup is skipped when document is undefined.
useWatermarkEnforcement(): void
예시
export function DataMapCell(info) {
useWatermarkEnforcement(); // void — no return value
return <span>{...}</span>;
}
함수
acceptBlock
Accept a block response. Rejected (state unchanged) if responseEpoch !== cache.epoch —
the request was issued for a query that has since been invalidated. On accept, the block is
stored as loaded; lastRow (when provided) sets the known total row count.
acceptBlock(cache: BlockCacheState<TData>, blockIndex: number, rows: TData[], responseEpoch: number, lastRow: number): BlockCacheState<TData>
acceptTreeBlock
Accept a child block — discarded unless (a) epoch === tree.epoch AND (b) the node still
exists (the invariant). On accept, stores into that node's cache.
acceptTreeBlock(tree: TreeCacheState<TData>, pathKey: string, blockIndex: number, rows: TData[], epoch: number, lastRow: number): TreeCacheState<TData>
advancedGlobalFilterFn
: TanStack globalFilterFn 어댑터 — global filter 값을 AdvancedFilterExpr 로 보고
행 단위로 평가한다(columnId 무시 = 행-레벨). null/undefined 식 → 무제약(true).
이것이 차트 cross-filter 의 실 setFilter 배선이다: setGlobalFilter(selectionsToFilter(selections))
로 차트 선택을 그리드의 getFilteredRowModel 에 흘려보내면 그리드가 내부적으로 필터한다(필터 상태가
data prop 가 아니라 테이블에 산다 — global search ✅ 와 동일 구조의 raw-table 배선).
advancedGlobalFilterFn(row: { … }, _columnId: string, filterValue: undefined | null | AdvancedFilterExpr): boolean
예시
const table = useReactTable({ data, columns, state: { globalFilter },
onGlobalFilterChange: setGlobalFilter, globalFilterFn: advancedGlobalFilterFn,
getColumnCanGlobalFilter: () => true, getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel() });
// chart: onSelectCategory={(i) => table.setGlobalFilter(selectionsToFilter([{ field, type, value: cats[i] }]))}
applyReducer
Apply a pivot value reducer (built-in key OR custom (number[]) => number)
to a set of values.
applyReducer(reducer: AggregationFnKey | PivotValueReducer, values: number[]): null | number
| 파라미터 | 타입 | 설명 |
|---|---|---|
reducer | AggregationFnKey | PivotValueReducer | An AggregationFnKey or a custom PivotValueReducer. |
values | number[] | Raw numeric values (may contain non-finite entries). |
반환 — The aggregated number, or null for an empty finite set.
autoSizeColumn
Compute the content-fit width (px) for one column:
max(measure(header),...measure(cellValues)) + padding, clamped to
[min, max] when provided.
autoSizeColumn(options: AutoSizeColumnOptions): number
autoSizeColumns
Auto-size multiple columns at once, returning a Record<columnId, px> width
map (consistent with TanStack's ColumnSizingState).
autoSizeColumns(options: AutoSizeColumnsOptions): Record<string, number>
bandScale
Band scale over [r0,r1] for count categories. paddingRatio (0..1) is the fraction of each
slot left empty as gap. Bars/vertices sit at band centres, evenly spaced and symmetric within
the range.
bandScale(count: number, range: [number, number], paddingRatio: number): BandScale
blockBounds
Half-open absolute row range [startRow, endRow) of a block.
blockBounds(blockIndex: number, blockSize: number): { … }
blockIndexOf
Block index containing an absolute row index.
blockIndexOf(rowIndex: number, blockSize: number): number
buildCellClassName
선언적 셀 룰 배열 → grid-core CellClassNameCallback 컴파일.
술어는 ctx.value(값)와 ctx.row(행 데이터)을 받는다(grid-core 1.0 : clean ctx).
join/undefined 규칙은 buildRowClassName 과 동일. 순수 함수.
buildCellClassName(rules: CellFormatRule<TData, TValue>[]): CellClassNameCallback<TData>
예시
<Grid cellClassName={buildCellClassName<Order, number>([
{ when: (v) => v < 0, className: 'text-red-600' },
])} />
buildChangeSet
Build a server payload from a ChangeMapState<TData>.
Algorithm (spec Section 1 L1 + Section 2.4):
removed— everystate.statusMap[key] === 'deleted'row → applyMapping (no validator call — deletes need only the PK).added— every'added'row → runValidator (type:'added'). Failing rows are excluded fromadded[]and recorded inerrors[].updated— every'edited'row → runValidator (type:'updated'). Same exclusion/error policy asadded.- Return
{ added, updated, removed, errors }.
Mapping function throws ( + ):
applyMappingpropagates throws (0 try/catch internally).buildChangeSetwraps added/updated mapping in per-row try/catch. On throw: push{ index, message: '(mapping threw: <error>)', type }to errors[].- Deleted mapping throw: fallback raw row (spec silent on deleted throw → conservative).
Index numbering in errors[] is per-group 0-based (pre-exclusion sequence).
Pure — no React import, no console.warn, no IO.
buildChangeSet(state: ChangeMapState<TData>, options: BuildChangeSetOptions<TData>): ChangeSet
buildPivotColumns
Build the full <Grid> column set from a pivot model.
buildPivotColumns(model: PivotModel, sort: PivotSortOpts, collapse: PivotCollapseOpts, colCollapse: PivotColumnCollapseOpts): ColumnDef<PivotRow>[]
| 파라미터 | 타입 | 설명 |
|---|---|---|
model | PivotModel | The headless pivot model. |
sort | PivotSortOpts | |
collapse | PivotCollapseOpts | |
colCollapse | PivotColumnCollapseOpts |
반환 — Declarative ColumnDef<PivotRow>[] (leading row-dimension columns + nested value column groups + grand-total group).
buildRowClassName
선언적 행 룰 배열 → grid-core RowClassNameCallback 컴파일.
매칭되는 모든 룰의 className 을 룰 순서대로 공백 join 한다(다중 적용 허용).
매칭 0 → undefined(콜백 계약: 추가 없음). 순수 함수 — 부작용 없음.
buildRowClassName(rules: RowFormatRule<TData>[]): RowClassNameCallback<TData>
예시
<Grid rowClassName={buildRowClassName([
{ when: (_, i) => i % 2 === 1, className: 'bg-gray-50' }, // 줄무늬(alternating)
{ when: (d) => d.status === 'error', className: 'text-red-600' },
])} />
buildRowsCsv
행 배열 + ExcelColumn[] 을 RFC 4180 CSV 문자열로 직렬화한다(헤더 1행 + 데이터 N행, CRLF 구분).
순수 함수 — Blob/DOM 비의존이라 node 단위 테스트로 실제 출력 문자열을 단언할 수 있다. null/undefined 셀은 빈 문자열로 직렬화(EC: exportToCSV 동작과 일치).
buildRowsCsv(rows: TData[], columns: ExcelColumn[], delimiter: string): string
| 파라미터 | 타입 | 설명 |
|---|---|---|
rows | TData[] | 직렬화할 데이터 행 |
columns | ExcelColumn[] | 컬럼 정의(key=행 키, header=헤더 텍스트) |
delimiter | string | 구분자 — ',' (기본) 또는 '\t' |
buildRowsPdfTable
buildRowsPdfTable(rows: TData[], columns: ExcelColumn[]): PdfTableData
buildServerPivotColumns
Build a nested pivot-result column tree from the server's flat field keys.
buildServerPivotColumns(fields: string[], separator: string): ServerPivotColumn[]
| 파라미터 | 타입 | 설명 |
|---|---|---|
fields | string[] | server-generated pivot-result field keys (order = desired column order). |
separator | string | segment delimiter within a field key (default '|'). |
buildValidationCellClass
선언적 검증 룰 배열 → grid-core CellClassNameCallback<TData> 컴파일.
field 가 지정된 룰만 셀 표시에 참여한다 — 해당 컬럼(ctx.columnId === rule.field) 셀이
위반(!validate(row))이면 룰의 className(기본 topgrid-cell-invalid)을 부여한다.
buildCellClassName 과 동일 계약·동형 패턴(선언적 룰 → 기존 콜백). 순수 함수.
grid-core 1.0 : clean ctx — cell.column.id→ctx.columnId·cell.row.original→ctx.row.
buildValidationCellClass(rules: ValidationRule<TData>[]): CellClassNameCallback<TData>
예시
<Grid cellClassName={buildValidationCellClass<Row>([
{ field: 'age', validate: (r) => r.age >= 0, message: '', className: 'border-red-500' },
])} />
buildValidator
선언적 검증 룰 배열 → @topgrid/grid-pro-tracking 의 Validator<TData> 컴파일.
반환 validator 를 tracking ChangeTrackingConfig.validator 로 주입하면 tracking 이 기존 동작
으로 invalid 행을 added/updated 에서 제외하고 getChangeSet.errors 에 수집한다 — 즉
커밋 차단은 재구현 없이 tracking 계약 재사용([[]]). 순수 함수.
buildValidator(rules: ValidationRule<TData>[]): Validator<TData>
예시
const tracking = useChangeTracking({
data, rowKey: 'id',
validator: buildValidator<Row>([
{ field: 'age', validate: (r) => r.age >= 0, message: '나이는 0 이상' },
]),
});
cellError
Construct an error value.
cellError(code: ErrorCode): CellError
cellValueToClipboardText
셀 값 → 클립보드 텍스트 (순수, W1 Phase 0, grid-pro-master 에서 이관).
브라우저 navigator.clipboard 배선과 분리된 값→텍스트 매핑. framework-agnostic —
React copy(makeCopyCellItem)·Vue copy 어댑터가 공유한다.
매핑: null/undefined→''(빈문자, "null"/"undefined" 아님) · object(배열 포함)→JSON.stringify · 그 외(string/number/boolean)→String.
cellValueToClipboardText(cell: { … }): string
checkLicense
현재 라이선스 상태를 동기 검사하여 LicenseCheckResult를 반환한다.
- valid=false 이면
watermarkRequired=true. - 유효하고
expiresAt까지 60일 미만이면expiryWarning='soon-expiring'+console.warn(1회). - 유효하고 만료 여유가 충분하면
{ valid: true, watermarkRequired: false }.
checkLicense(): LicenseCheckResult
clearBlock
Drop an in-flight block so it can be re-requested — call on a failed getRows (the
datasource contract says a rejected fetch leaves the block unloaded, re-requestable). No-op if
the epoch has since changed (invalidate already cleared it) or the block is no longer loading,
so a late failure can't disturb a fresh query.
clearBlock(cache: BlockCacheState<TData>, blockIndex: number, epoch: number): BlockCacheState<TData>
clearTreeBlock
Drop a failed in-flight child block so it can be re-requested (epoch + node-existence guarded).
clearTreeBlock(tree: TreeCacheState<TData>, pathKey: string, blockIndex: number, epoch: number): TreeCacheState<TData>
coerceLiteral
Coerce raw literal text → a CellValue (number / boolean / string; "" for empty).
coerceLiteral(raw: string): CellValue
collapsePivotRows
collapse 된 subtotal(__id ∈ collapsedIds)의 후손 행을 제거한 가시 행 배열. subtotal 자신은 그룹
대표로 잔존, grandTotal 불변.
collapsePivotRows(rows: readonly PivotRow[], collapsedIds: ReadonlySet<string>): PivotRow[]
| 파라미터 | 타입 | 설명 |
|---|---|---|
rows | readonly PivotRow[] | pivot 행(원본 model.rows 또는 sortPivotRows 결과 — 합성 체인 가능). |
collapsedIds | ReadonlySet<string> | collapse 된 subtotal 의 __id 집합. |
commentKey
충돌 없는 셀 코멘트 키.
commentKey(rowKey: string, columnId: string): string
compileCell
Compile a cell's raw input: a =-prefixed formula (parsed + qualified + refs), else a literal.
compileCell(raw: string, ctx: CompileContext): CompiledCell
computeAggregateRow
: source 행 집합 → 컬럼별 집계값 한 행(grand-total footer / auto-agg floating 공유).
computeAggregateRow(data: readonly Record<string, unknown>[], spec: AggregateSpec): Record<string, null | number>
| 파라미터 | 타입 | 설명 |
|---|---|---|
data | readonly Record<string, unknown>[] | 집계할 source 행(grand-total=전체, 부분집합도 가능). |
spec | AggregateSpec | 컬럼별 집계 함수 키. |
반환 — { [columnId]: number | null } (빈 집합 avg/min/max=null).
computeChartGeometry
Compute the full pixel geometry for a cartesian (line/bar) chart from raw series.
- y domain is the niced range of ALL finite values across ALL series, so axis ticks land on round numbers and every series shares one scale (comparable).
- x is a band scale over the longest series' length.
- Non-finite values (NaN/±Infinity) keep their slot index but are omitted from
points(a gap), never silently shifting later points left.
computeChartGeometry(seriesList: ChartSeries[], opts: { … }): ChartGeometry
computeColSpans
데이터 배열과 컬럼별 colSpan 콜백을 받아 본문 셀의 가로 병합(colSpan) Map을 계산한다.
**computeMergeSpans(rowSpan)의 수평 쌍둥이 **: 행마다 컬럼을 왼쪽→오른쪽으로 순회. 어떤 셀이 colSpan=n(>1)을 선언하면 그 셀이 시작 셀이 되고 우측 n-1개 셀은 "피복(covered)"되어 skip(0)으로 표시된다. 피복된 셀 자신의 colSpan 콜백은 평가하지 않는다(skip-of-skip — 이미 가려진 셀은 스팬을 시작할 수 없음).
clamp: colSpan 이 행의 남은 컬럼 수를 초과하면 남은 수로 절단한다(행 경계 밖 스팬 방지). 비유한/1 미만 값은 1( 스팬 없음)로 정규화한다.
★colSpan 은 한 행 안에서만 작동한다 — rowSpan(computeMergeSpans)의 행간 ancestorBoundary 전파나 L-01 orphan(시작 셀이 가상 윈도 밖으로 스크롤) 문제가 구조적으로 없다.
computeColSpans(rows: TData[], columns: { … }[]): ColSpanMap
| 파라미터 | 타입 | 설명 |
|---|---|---|
rows | TData[] | 렌더링 순서의 TData 배열 (getSortedRowModel / getFilteredRowModel 결과) |
columns | { … }[] | 컬럼 정보 배열 (id + 선택적 colSpan 콜백). 배열 순서 = 좌→우 = getVisibleCells 순서. |
반환 — - 키 ${rowIdx}_${colId} → colSpan 숫자의 Map. >1 = 스팬 시작 셀, 0 = 피복되어 skip(MergingGrid 에서 null 반환), 1/미존재 = 일반 셀. rows 가 빈 배열이면 빈 Map.
예시
// row 0 의 'b' 셀이 3컬럼(b,c,d) 스팬 → c,d 는 skip
const map = computeColSpans(
[{ a: 1, b: 2, c: 3, d: 4, e: 5 }],
[
{ id: 'a' },
{ id: 'b', colSpan: () => 3 },
{ id: 'c' }, { id: 'd' }, { id: 'e' },
]
);
// map.get('0_b') === 3 ; map.get('0_c') === 0 ; map.get('0_d') === 0
// 'a','e' 미존재(=일반 셀)
computeMergeSpans
데이터 배열과 병합 대상 컬럼 목록을 받아 MergeSpanMap을 계산한다.
Hierarchical ancestorBoundary 알고리즘 (ADR-):
단일 패스 O(N×C) — 행(i)을 순회하면서 컬럼(j)을 왼쪽에서 오른쪽 순서로 평가.
좌측 컬럼에서 경계(boundary)가 발생하면 우측 컬럼에도 강제 경계를 전파한다.
(ancestorBoundary 플래그 — 행 전환마다 초기화)
Regression Invariant (ADR-):
columns.length === 1 시 좌측 컬럼이 없으므로 ancestorBoundary는 항상 false.
결과적으로 자신의 compareFn만 평가하며, 출력과 비트 동일한 Map을 생성한다.
computeMergeSpans(rows: TData[], columns: { … }[]): MergeSpanMap
| 파라미터 | 타입 | 설명 |
|---|---|---|
rows | TData[] | 렌더링 순서의 TData 배열 (getSortedRowModel / getFilteredRowModel 결과) |
columns | { … }[] | 병합 컬럼 정보 배열 (id + mergeRows 설정). 배열 순서 = 좌→우 = 높→낮 우선순위 (ADR-) |
반환 — - 키 ${rowIdx}_${colId} → rowSpan 숫자의 Map skip 셀은 0으로 존재 (MergingGrid에서 null 반환 트리거) rows가 빈 배열이면 빈 Map 반환
예시
// 단일 컬럼 — G-001과 동일 출력 (Regression Invariant)
const spanMap = computeMergeSpans(
[{ dept: 'A' }, { dept: 'A' }, { dept: 'B' }],
[{ id: 'dept', mergeRows: true }]
);
// spanMap.get('0_dept') === 2
// spanMap.get('1_dept') === 0
// spanMap.get('2_dept') === 1
computePivot
The pure pivot transform — flat data → PivotModel.
Emits, in render order:
- leaf data rows (deepest row-dimension combination),
- per-row-group subtotal rows (one when each non-leaf row group closes),
- a final grand-total row (all rows aggregated).
When config.rows is empty, a single grand-total row carries the column
aggregation. When config.columns is empty, every value collapses into the
grand-total column (still one cell per value-def).
computePivot(data: TData[], config: PivotConfig): PivotModel
computeReplacements
검색 결과를 치환 패치로 변환(AC ②). ** 조합**: 반환의 {rowKey, columnId, prior, next} 는
tracking.updateRow(rowKey, {[columnId]: next}) + makeUpdateCommand(...) 로 바로 undo 가능하게 적용된다.
'whole' → next = replacement. 'substring' → String(value) 의 모든 일치를 replacement 로
치환(대소문자 구분 시 단순 split/join, 비구분 시 gi 정규식). next 는 항상 문자열.
computeReplacements(matches: readonly CellMatch[], query: string, replacement: string, options: FindOptions): Replacement[]
copyToClipboard
TanStack Table 데이터를 TSV 포맷으로 클립보드에 복사한다. TSV(탭 구분, 줄바꿈 행 구분) — Excel 붙여넣기 호환.
navigator.clipboard 미지원 환경: document.execCommand('copy') fallback 시도. fallback도 실패 시 Error('[grid-export] copyToClipboard: Clipboard API not supported') throw.
copyToClipboard(table: Table<TData>, options: ClipboardOptions): Promise<void>
| 파라미터 | 타입 | 설명 |
|---|---|---|
table | Table<TData> | TanStack v8 Table<TData> 인스턴스 (useReactTable 반환값) |
options | ClipboardOptions | 클립보드 복사 옵션 (scope, emptyBehavior) |
반환 — Promise<void> — navigator.clipboard.writeText 는 async
예시
await copyToClipboard(table);
createAsyncDataMap
createAsyncDataMap<TItem>: AsyncDataMap 팩토리.
- DataMap<TItem> 완전 구현: getDisplay, getItems, getValue
- 4-state 상태머신: idle → loading → loaded/error (Section 12)
- staleTime 기반 캐싱 + invalidate
- pendingPromise de-dupe: 동시 load 호출 시 동일 Promise 공유
- onStateChange?: 구독 콜백 등록 → 구독 해제 함수 반환 (Section 3.1)
createAsyncDataMap(options: CreateAsyncDataMapOptions<TItem>): AsyncDataMap<TItem>
| 파라미터 | 타입 | 설명 |
|---|---|---|
options | CreateAsyncDataMapOptions<TItem> | CreateAsyncDataMapOptions<TItem> |
반환 — AsyncDataMap<TItem>
createBlockCache
Create an empty cache at epoch 0.
createBlockCache(blockSize: number): BlockCacheState<TData>
createCanvasMeasureText
Create a MeasureText backed by the browser canvas 2D API.
In a browser, returns a measurer using
document.createElement('canvas').getContext('2d').measureText(text).width,
applying the optional CSS font shorthand per call. In node/SSR (no
document, or no 2D context), returns the estimateTextWidth fallback.
Never throws.
createCanvasMeasureText(): MeasureText
createColumnGroup
Creates a TanStack GroupColumnDef<TData> from a typed config object.
This is a thin wrapper — no logic beyond type narrowing. The returned
object is identical to writing { header, columns } inline, but provides
generic type-checking at the call site.
createColumnGroup(config: ColumnGroupConfig<TData>): GroupColumnDef<TData>
| 파라미터 | 타입 | 설명 |
|---|---|---|
config | ColumnGroupConfig<TData> | ColumnGroupConfig<TData> with header and columns. |
반환 — A GroupColumnDef<TData> suitable for passing to useReactTable.
createColumns
TopgridColumnDef<TData>[] | ColumnInfo[] 를 받아 ColumnDef<TData>[] 반환.
type필드 기반 자동 renderer 분기 (rendererRegistry 조회)'checkbox'type → DisplayColumnDef (accessorKey 없음, enableSorting 강제 false)- registry 미등록 type → plain text fallback + console.warn
ColumnInfo[]입력 시 내부에서TopgridColumnDef로 narrowingwidth,enableSorting,enableResizing,meta표준 매핑
createColumns(defs: TopgridColumnDef<TData>[] | ColumnInfo[]): ColumnDef<TData>[]
| 파라미터 | 타입 | 설명 |
|---|---|---|
defs | TopgridColumnDef<TData>[] | ColumnInfo[] | column 정의 배열. TopgridColumnDef<TData>[] 또는 ColumnInfo[]. |
반환 — TanStack ColumnDef<TData>[] — useReactTable({ columns }) 에 직접 주입 가능.
예시
// TopgridColumnDef 직접 사용 (권장)
const defs: TopgridColumnDef<User>[] = [
{ id: 'name', name: '이름', type: 'text', align: 'left', width: '150' },
{ id: 'salary', name: '급여', type: 'number', align: 'right', width: '120' },
{ id: 'sel', name: '', type: 'checkbox', align: 'center', width: '50' },
];
const columns = createColumns<User>(defs);
// 기존 ColumnInfo[] 호환 (AC-005)
const legacyDefs: ColumnInfo[] = [...];
const columns = createColumns(legacyDefs);
참고 — - TopgridColumnDef, - ColumnInfo, - defaultRendererRegistry
createDataMap
createDataMap<TItem>: DataMap 팩토리 함수. items 배열과 valuePath/displayPath 설정으로 DataMap 인스턴스 생성.
createDataMap(options: CreateDataMapOptions<TItem>): DataMap<TItem>
예시
const map = createDataMap({
items: [{ code: 'A', name: '항목A' }],
valuePath: 'code',
displayPath: 'name',
});
map.getDisplay('A'); // '항목A'
map.getValue('항목A'); // 'A'
createServerSideController
createServerSideController(datasource: ServerSideDatasource<TData>, options: ServerSideControllerOptions, onChange: (…) => …): ServerSideController<TData>
| 파라미터 | 타입 | 설명 |
|---|---|---|
datasource | ServerSideDatasource<TData> | |
options | ServerSideControllerOptions | |
onChange | (…) => … | called whenever the materialized data changes (a block resolved / invalidated). The hook wires this to setState. NOT called synchronously from ensureRange for an unchanged cache — so a scroll→render→onChange loop cannot form (materialize is range-independent; placeholders exist from construction). |
createServerSideTreeController
createServerSideTreeController(datasource: ServerSideDatasource<TData>, options: ServerSideTreeControllerOptions, onChange: (…) => …): ServerSideTreeController<TData>
createSheet
createSheet(onChange: (…) => …): Sheet
createTreeCache
createTreeCache(blockSize: number, rowGroupCols: string[]): TreeCacheState<TData>
createViewportRowModel
Create a viewport row-model controller. Calls datasource.init once with push callbacks, forwards
visible ranges via setRange, and re-emits a materialized array whenever the datasource pushes a
count or rows (including live in-place updates).
createViewportRowModel(datasource: ViewportDatasource<TData>, options: ViewportRowModelOptions, onChange: (…) => …): ViewportRowModel<TData>
customizePivotTotals
model.rows 에 row-total 커스터마이즈 적용(순수, 새 배열). data 행·상대 순서 보존(grandTotal 이동 제외).
customizePivotTotals(rows: readonly PivotRow[], opts: PivotTotalsOpts): PivotRow[]
| 파라미터 | 타입 | 설명 |
|---|---|---|
rows | readonly PivotRow[] | pivot 행(원본 model.rows 또는 변환 결과 — 합성 체인 가능). |
opts | PivotTotalsOpts | PivotTotalsOpts. |
dateRangeFilterFn
dateRangeFilterFn(row: Row<unknown>, columnId: string, filterValue: any, addMeta: (…) => …): boolean
deserializeComments
버전 봉투 JSON → 코멘트 Map. null/파싱 실패/버전 불일치/형식 오류 → 빈 Map(throw 없음).
deserializeComments(raw: null | string, version: number): Map<string, string>
detectSeriesStep
detectSeriesStep(values: number[]): null | number
distributeStarWidths
Distribute totalWidth across columns. Fixed columns take their px first;
the remaining width is split among star columns proportional to their factor.
Min-clamp re-distribution is ITERATIVE: when a star column's proportional
share falls below its min, that column is clamped to min, removed from the
star pool, its px subtracted from the remaining width, and the remaining star
columns are re-distributed. The loop repeats until no remaining star column
violates its min (clamping one column shrinks the pool and can push another
below its min — a single pass is insufficient).
Returns float px (no rounding) so ratios are exact (e.g. 133.33 / 266.67).
distributeStarWidths(options: DistributeStarWidthsOptions): Record<string, number>
ensureNode
Create the node for pathKey if missing, stamped with the current global epoch.
ensureNode(tree: TreeCacheState<TData>, pathKey: string): TreeCacheState<TData>
ensureVisibleNodes
Ensure every node referenced by the current display range exists (so its blocks can be planned).
ensureVisibleNodes(tree: TreeCacheState<TData>, displayStart: number, displayEnd: number): TreeCacheState<TData>
escapeCsvValue
RFC 4180 §2: 구분자/큰따옴표/개행 포함 시 큰따옴표 래핑 + 내부 따옴표 이중화. 순수 string 조작 — 외부 라이브러리 0.
escapeCsvValue(value: string, delimiter: string): string
evaluate
Evaluate a formula AST to a scalar CellValue. Errors propagate; never throws.
evaluate(ast: Ast, getCell: CellGetter): CellValue
evaluateAdvancedFilter
: 고급 필터 식을 행에 평가(순수, 재귀). group=inert 자식 제거 후 reduce(빈/all-inert→true=무제약).
evaluateAdvancedFilter(expr: AdvancedFilterExpr, row: Record<string, unknown>): boolean
| 파라미터 | 타입 | 설명 |
|---|---|---|
expr | AdvancedFilterExpr | 식 트리. |
row | Record<string, unknown> | 평가할 행(필드 record). |
expandRange
Expand A1:B2 (inclusive, order-normalized) → cell refs [A1, A2, B1, B2] (column-major).
expandRange(from: string, to: string): string[]
exportRowsToCsv
exportRowsToCsv — 행 배열 기반 CSV export ( 평행, exportRowsToExcel 의 CSV 형)
TanStack Table 인스턴스 없이 raw row array + ExcelColumn[] 로 CSV 파일 다운로드.
직렬화 로직(buildRowsCsv)은 순수 함수로 분리되어 node 테스트 가능하고, 본 함수는
BOM + Blob + a[download] 의 브라우저 전용 다운로드 래퍼다.
exportRowsToCsv(rows: TData[], columns: ExcelColumn[], options: ExportRowsCsvOptions): void
예시
exportRowsToCsv(rows, columns, { fileName: '데이터.csv' });
exportRowsToCsv(rows, columns, { fileName: '데이터.tsv', delimiter: '\t' });
exportRowsToExcel
행 배열을 Excel 파일(.xlsx)로 다운로드한다.
TanStack Table<TData> 인스턴스 없이 사용 가능.
@topgrid/grid-export 의 exportToExcel(table, options) 와 평행 지원 ( 옵션 A).
exportRowsToExcel(rows: TData[], columns: ExcelColumn[], options: ExportRowsOptions): void