An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
feat(data-table): redesign the profiling table (#524)
Elwynn Chen869f5af40fbd
diff --git a/packages/graphic-walker/src/components/dataTable/columnHeader.tsx b/packages/graphic-walker/src/components/dataTable/columnHeader.tsxnew file mode 100644index 00000000..70bf9569--- /dev/null+++ b/packages/graphic-walker/src/components/dataTable/columnHeader.tsx@@ -0,0 +1,190 @@+import React, { useRef } from 'react';+import { useTranslation } from 'react-i18next';+import { ArrowDownIcon, ArrowUpIcon, CheckIcon, ChevronDownIcon, FunnelIcon, XMarkIcon } from '@heroicons/react/16/solid';+import type { IMutField, ISemanticType } from '../../interfaces';+import { cn } from '../../utils';+import DataTypeIcon from '../dataTypeIcon';+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '../ui/dropdown-menu';++export type ISortDirection = 'ascending' | 'descending';++interface ColumnHeaderProps {+ field: IMutField;+ sort?: ISortDirection;+ filtered?: boolean;+ hideSemanticType?: boolean;+ semanticTypeOptions: { value: ISemanticType; label: string }[];+ /** cycles descending → ascending → none; omitted when sorting is disabled */+ onToggleSort?: () => void;+ onSort?: (sort: ISortDirection | null) => void;+ /** opens the filter dialog; omitted when filtering is disabled */+ onFilter?: () => void;+ onClearFilter?: () => void;+ /** omitted when the semantic type is read-only */+ onChangeSemanticType?: (semanticType: ISemanticType) => void;+}++const itemClassName = 'gap-2.5 text-[13px]';++function SemanticTypeItems(props: Pick<ColumnHeaderProps, 'field' | 'semanticTypeOptions' | 'onChangeSemanticType'>) {+ const { field, semanticTypeOptions, onChangeSemanticType } = props;+ return (+ <>+ {semanticTypeOptions.map((option) => (+ <DropdownMenuItem key={option.value} className={itemClassName} onSelect={() => onChangeSemanticType?.(option.value)}>+ <span className="flex w-4 justify-center">+ <DataTypeIcon dataType={option.value} analyticType={field.analyticType} />+ </span>+ <span className="first-letter:uppercase">{option.label}</span>+ {option.value === field.semanticType && <CheckIcon className="ml-auto h-4 w-4" />}+ </DropdownMenuItem>+ ))}+ </>+ );+}++export function ColumnHeader(props: ColumnHeaderProps) {+ const { field, sort, filtered, hideSemanticType, semanticTypeOptions, onToggleSort, onSort, onFilter, onClearFilter, onChangeSemanticType } = props;+ const { t } = useTranslation('translation', { keyPrefix: 'data_table' });+ const name = field.basename || field.name || field.fid;+ const typeLabel = semanticTypeOptions.find((x) => x.value === field.semanticType)?.label ?? field.semanticType;+ const chipClassName = cn(+ 'inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-md transition-colors',+ field.analyticType === 'dimension' ? 'bg-dimension/[0.14]' : 'bg-measure/[0.14]'+ );+ const canChangeType = !!onChangeSemanticType && !hideSemanticType;+ const hasMenu = !!(onSort || onFilter || canChangeType);+ // keeps focus inside the filter dialog instead of handing it back to the menu trigger+ const openingDialog = useRef(false);++ return (+ <div className="relative flex h-[22px] min-w-0 items-center gap-2">+ {!hideSemanticType &&+ (canChangeType ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ data-testid="data-table-semantic-type"+ aria-label={`${t('semantic_type')}: ${typeLabel}`}+ title={typeLabel}+ className={cn(+ chipClassName,+ 'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',+ field.analyticType === 'dimension'+ ? 'hover:bg-dimension/25 data-[state=open]:bg-dimension/25'+ : 'hover:bg-measure/25 data-[state=open]:bg-measure/25'+ )}+ >+ <DataTypeIcon dataType={field.semanticType} analyticType={field.analyticType} />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-48">+ <DropdownMenuLabel className="text-[11px] font-normal text-muted-foreground">{t('semantic_type')}</DropdownMenuLabel>+ <SemanticTypeItems field={field} semanticTypeOptions={semanticTypeOptions} onChangeSemanticType={onChangeSemanticType} />+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (+ <span className={chipClassName} title={typeLabel}>+ <DataTypeIcon dataType={field.semanticType} analyticType={field.analyticType} />+ </span>+ ))}+ {onToggleSort ? (+ <button+ type="button"+ className="min-w-0 truncate rounded-sm text-[13px] font-semibold focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ title={name}+ onClick={onToggleSort}+ >+ {name}+ </button>+ ) : (+ <span className="min-w-0 truncate text-[13px] font-semibold" title={name}>+ {name}+ </span>+ )}+ {sort === 'descending' && <ArrowDownIcon className="h-3 w-3 shrink-0" aria-hidden />}+ {sort === 'ascending' && <ArrowUpIcon className="h-3 w-3 shrink-0" aria-hidden />}+ {filtered && <FunnelIcon className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden />}+ {hasMenu && (+ <DropdownMenu modal={false}>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ data-testid="data-table-column-menu"+ aria-label={t('column_options', { name })}+ className={cn(+ 'absolute right-0 top-0 flex h-[22px] w-[22px] items-center justify-center rounded-md bg-background text-muted-foreground',+ 'shadow-[-10px_0_8px_-2px_hsl(var(--background))] transition-opacity hover:bg-muted hover:text-foreground',+ 'opacity-0 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring group-hover/th:opacity-100',+ 'data-[state=open]:bg-muted data-[state=open]:text-foreground data-[state=open]:opacity-100'+ )}+ >+ <ChevronDownIcon className="h-3.5 w-3.5" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="w-52"+ onCloseAutoFocus={(e) => {+ if (openingDialog.current) {+ openingDialog.current = false;+ e.preventDefault();+ }+ }}+ >+ {onSort && (+ <>+ <DropdownMenuItem className={itemClassName} onSelect={() => onSort('ascending')}>+ <ArrowUpIcon className="h-4 w-4 text-muted-foreground" />+ {t('sort_asc')}+ {sort === 'ascending' && <CheckIcon className="ml-auto h-4 w-4" />}+ </DropdownMenuItem>+ <DropdownMenuItem className={itemClassName} onSelect={() => onSort('descending')}>+ <ArrowDownIcon className="h-4 w-4 text-muted-foreground" />+ {t('sort_desc')}+ {sort === 'descending' && <CheckIcon className="ml-auto h-4 w-4" />}+ </DropdownMenuItem>+ {sort && (+ <DropdownMenuItem className={itemClassName} onSelect={() => onSort(null)}>+ <XMarkIcon className="h-4 w-4 text-muted-foreground" />+ {t('clear_sort')}+ </DropdownMenuItem>+ )}+ </>+ )}+ {onFilter && (+ <>+ {onSort && <DropdownMenuSeparator />}+ <DropdownMenuItem+ className={itemClassName}+ data-testid="data-table-filter"+ onSelect={() => {+ openingDialog.current = true;+ onFilter();+ }}+ >+ <FunnelIcon className="h-4 w-4 text-muted-foreground" />+ {t('filter')}+ </DropdownMenuItem>+ {filtered && onClearFilter && (+ <DropdownMenuItem className={itemClassName} onSelect={onClearFilter}>+ <XMarkIcon className="h-4 w-4 text-muted-foreground" />+ {t('clear_filter')}+ </DropdownMenuItem>+ )}+ </>+ )}+ {canChangeType && (+ <>+ {(onSort || onFilter) && <DropdownMenuSeparator />}+ <DropdownMenuLabel className="text-[11px] font-normal text-muted-foreground">{t('semantic_type')}</DropdownMenuLabel>+ <SemanticTypeItems field={field} semanticTypeOptions={semanticTypeOptions} onChangeSemanticType={onChangeSemanticType} />+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </div>+ );+}diff --git a/packages/graphic-walker/src/components/dataTable/headers.test.ts b/packages/graphic-walker/src/components/dataTable/headers.test.tsnew file mode 100644index 00000000..891a1fce--- /dev/null+++ b/packages/graphic-walker/src/components/dataTable/headers.test.ts@@ -0,0 +1,42 @@+import type { IMutField } from '../../interfaces';+import { getHeaders } from './headers';++const field = (...path: string[]): IMutField => ({+ fid: path.join('.'),+ name: path.join('.'),+ basename: path[path.length - 1],+ path,+ semanticType: 'nominal',+ analyticType: 'dimension',+});++const summarize = (metas: IMutField[]) =>+ getHeaders(metas).map((row) => row.map((x) => (x.type === 'name' ? `[${x.value}]x${x.colSpan}` : `${x.value.fid}/${x.rowSpan}`)));++describe('getHeaders', () => {+ test('flat fields share one header row', () => {+ expect(summarize([field('a'), field('b')])).toEqual([['a/1', 'b/1']]);+ });++ test('adjacent groups at the same depth stay separate', () => {+ expect(summarize([field('student'), field('scores', 'math'), field('scores', 'reading'), field('meta', 'lunch'), field('meta', 'prep')])).toEqual([+ ['student/2', '[scores]x2', '[meta]x2'],+ ['scores.math/1', 'scores.reading/1', 'meta.lunch/1', 'meta.prep/1'],+ ]);+ });++ test('a group interrupted by another field is opened again', () => {+ expect(summarize([field('a', 'x'), field('b'), field('a', 'y')])).toEqual([+ ['[a]x1', 'b/2', '[a]x1'],+ ['a.x/1', 'a.y/1'],+ ]);+ });++ test('nested groups only merge under the same parent', () => {+ expect(summarize([field('a', 'b', 'x'), field('a', 'b', 'y'), field('a', 'c', 'z'), field('d', 'c', 'w')])).toEqual([+ ['[a]x3', '[d]x1'],+ ['[b]x2', '[c]x1', '[c]x1'],+ ['a.b.x/1', 'a.b.y/1', 'a.c.z/1', 'd.c.w/1'],+ ]);+ });+});diff --git a/packages/graphic-walker/src/components/dataTable/headers.ts b/packages/graphic-walker/src/components/dataTable/headers.tsnew file mode 100644index 00000000..2c37dd8b--- /dev/null+++ b/packages/graphic-walker/src/components/dataTable/headers.ts@@ -0,0 +1,54 @@+import type { IMutField } from '../../interfaces';++export type wrapMutField = {+ colSpan: number;+ rowSpan: number;+} & (+ | { type: 'field'; value: IMutField; fIndex: number }+ | {+ type: 'name';+ value: string;+ }+);++export const getHeaders = (metas: IMutField[]): wrapMutField[][] => {+ const height = metas.map((x) => x.path?.length ?? 1).reduce((a, b) => Math.max(a, b), 0);+ const result: wrapMutField[][] = [...Array(height)].map(() => []);+ let prevPath: string[] = [];+ metas.forEach((x, fIndex) => {+ const path = x.path ?? [x.name ?? x.fid];+ // group levels shared with the previous field widen its group headers, the others open new ones+ let shared = 0;+ while (shared < path.length - 1 && shared < prevPath.length - 1 && path[shared] === prevPath[shared]) {+ shared++;+ }+ for (let i = 0; i < path.length - 1; i++) {+ if (i < shared) {+ result[i][result[i].length - 1].colSpan++;+ } else {+ result[i].push({+ colSpan: 1,+ rowSpan: 1,+ type: 'name',+ value: path[i],+ });+ }+ }+ prevPath = path;+ result[path.length - 1].push({+ type: 'field',+ value: x,+ colSpan: 1,+ rowSpan: height - path.length + 1,+ fIndex,+ });+ });+ return result;+};++export const getHeaderKey = (f: wrapMutField) => {+ if (f.type === 'name') {+ return f.value;+ }+ return f.value.name ?? f.value.fid;+};diff --git a/packages/graphic-walker/src/components/dataTable/index.tsx b/packages/graphic-walker/src/components/dataTable/index.tsxindex 09fa06fa..de5e8269 100644--- a/packages/graphic-walker/src/components/dataTable/index.tsx+++ b/packages/graphic-walker/src/components/dataTable/index.tsx@@ -1,22 +1,20 @@import React, { useMemo, useState, useRef, useEffect, useCallback, forwardRef, useImperativeHandle, ForwardedRef } from 'react';-import styled from 'styled-components';-import type { IMutField, IRow, IComputationFunction, IFilterFiledSimple, IFilterRule, IFilterField, IFilterWorkflowStep, IField, IVisFilter } from '../../interfaces';-import { useTranslation } from 'react-i18next';-import LoadingLayer from '../loadingLayer';+import { Trans, useTranslation } from 'react-i18next';+import { XMarkIcon } from '@heroicons/react/16/solid';+import type { IMutField, IRow, IComputationFunction, IFilterRule, IFilterField, IFilterWorkflowStep, IVisFilter, ISemanticType } from '../../interfaces';import { dataReadRaw } from '../../computation';import Pagination from './pagination';-import DropdownContext from '../dropdownContext';-import DataTypeIcon from '../dataTypeIcon';+import { getHeaderKey, getHeaders } from './headers';import { PureFilterEditDialog } from '../../fields/filterField/filterEditDialog';-import { BarsArrowDownIcon, BarsArrowUpIcon, FunnelIcon } from '@heroicons/react/24/outline';import { ComputationContext } from '../../store';import { parsedOffsetDate } from '../../lib/op/offset';-import { cn, formatDate } from '../../utils';-import { FieldProfiling } from './profiling';+import { _unstable_encodeRuleValue, cn, formatDate } from '../../utils';+import { FieldProfiling, formatNumber } from './profiling';+import { ColumnHeader, type ISortDirection } from './columnHeader';import { addFilterForQuery, createFilter } from '../../utils/workflow';-import { Button, buttonVariants } from '../ui/button';-import { Badge } from '../ui/badge';+import { Button } from '../ui/button';import { HoverCard, HoverCardContent, HoverCardTrigger } from '../ui/hover-card';+import Spinner from '../spinner';interface DataTableProps {/** page limit */@@ -31,103 +29,10 @@ interface DataTableProps {hidePaginationAtOnepage?: boolean;displayOffset?: number;}-const Container = styled.div`- overflow-x: auto;- height: 100%;- display: flex;- flex-direction: column;- table {- box-sizing: content-box;- border-collapse: collapse;- font-size: 12px;- tbody {- td {- }- td.number {- text-align: right;- }- td.text {- text-align: left;- }- }- }-`;-// const ANALYTIC_TYPE_LIST = ['dimension', 'measure'];-const SEMANTIC_TYPE_LIST = ['nominal', 'ordinal', 'quantitative', 'temporal'];-// function getCellType(field: IMutField): 'number' | 'text' {-// return field.dataType === 'number' || field.dataType === 'integer' ? 'number' : 'text';-// }-function getHeaderType(field: IMutField): 'number' | 'text' {- return field.analyticType === 'dimension' ? 'text' : 'number';-}--function getHeaderClassNames(field: IMutField) {- return field.analyticType === 'dimension' ? 'border-t-2 border-dimension' : 'border-t-2 border-measure';-}-function getSemanticColors(field: IMutField): string {- switch (field.semanticType) {- case 'nominal':- return 'border border-transparent bg-sky-100 text-sky-800 dark:bg-sky-900 dark:text-sky-100 dark:border-sky-600';- case 'ordinal':- return 'border border-transparent bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-100 dark:border-indigo-600';- case 'quantitative':- return 'border border-transparent bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-100 dark:border-purple-600';- case 'temporal':- return 'border border-transparent bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-100 dark:border-yellow-600';- default:- return 'border border-transparent bg-gray-400';- }-}+const SEMANTIC_TYPE_LIST: ISemanticType[] = ['nominal', 'ordinal', 'quantitative', 'temporal'];-type wrapMutField = {- colSpan: number;- rowSpan: number;-} & (- | { type: 'field'; value: IMutField; fIndex: number }- | {- type: 'name';- value: string;- }-);--const getHeaders = (metas: IMutField[]): wrapMutField[][] => {- const height = metas.map((x) => x.path?.length ?? 1).reduce((a, b) => Math.max(a, b), 0);- const result: wrapMutField[][] = [...Array(height)].map(() => []);- let now = 1;- metas.forEach((x, fIndex) => {- const path = x.path ?? [x.name ?? x.fid];- if (path.length > now) {- for (let i = now - 1; i < path.length - 1; i++) {- result[i].push({- colSpan: 0,- rowSpan: 1,- type: 'name',- value: path[i],- });- }- }- now = path.length;- for (let i = 0; i < path.length - 1; i++) {- result[i][result[i].length - 1].colSpan++;- }- result[path.length - 1].push({- type: 'field',- value: x,- colSpan: 1,- rowSpan: height - path.length + 1,- fIndex,- });- });- return result;-};--const getHeaderKey = (f: wrapMutField) => {- if (f.type === 'name') {- return f.value;- }- return f.value.name ?? f.value.fid;-};+const formatCount = (n: number) => n.toLocaleString();function useFilters(metas: IMutField[]) {const [filters, setFilters] = useState<IFilterField[]>([]);@@ -163,13 +68,31 @@ function useFilters(metas: IMutField[]) {const onWriteFilter = useCallback((index: number, rule: IFilterRule | null) => {setFilters((f) => f.map((x, i) => (i === index ? { ...x, rule } : x)));}, []);- const onDeleteFilter = useCallback((index: number) => {- setFilters((f) => f.filter((_, i) => i !== index));- }, []);const onClose = useCallback(() => {setEditingFilterIdx(null);+ // a filter that was opened but never given a rule should not linger as an empty chip+ setFilters((f) => (f.every((x) => x.rule) ? f : f.filter((x) => x.rule)));}, []);- return { filters, options, editingFilterIdx, onSelectFilter, onDeleteFilter, onWriteFilter, onClose };+ /** creates, replaces or (with `null`) removes the filter of a field */+ const setFieldRule = useCallback(+ (fid: string, rule: IFilterRule | null) => {+ setFilters((fs) => {+ const i = fs.findIndex((x) => x.fid === fid);+ if (!rule) {+ return i > -1 ? fs.filter((_, j) => j !== i) : fs;+ }+ if (i > -1) {+ return fs.map((x, j) => (j === i ? { ...x, rule } : x));+ }+ const meta = metas.find((x) => x.fid === fid);+ if (!meta) return fs;+ return fs.concat({ fid, rule, analyticType: meta.analyticType, name: meta.name ?? meta.fid, semanticType: meta.semanticType });+ });+ },+ [metas]+ );+ const clearFilters = useCallback(() => setFilters([]), []);+ return { filters, options, editingFilterIdx, onSelectFilter, onWriteFilter, onClose, setFieldRule, clearFilters };}function fieldValue(props: { field: IMutField; item: IRow; displayOffset?: number }) {@@ -234,6 +157,58 @@ function TruncateDector(props: { value: string }) {);}+function useRuleDescription(displayOffset?: number) {+ const { t } = useTranslation('translation', { keyPrefix: 'data_table' });+ return useCallback(+ (rule: IFilterRule) => {+ switch (rule.type) {+ case 'one of':+ case 'not in': {+ const values = rule.value.map((x) => `${x}`);+ const text = values.length > 2 ? t('n_values', { count: values.length }) : values.join(', ');+ return rule.type === 'not in' ? `≠ ${text}` : text;+ }+ case 'range':+ return `${rule.value[0] === null ? '…' : formatNumber(rule.value[0])} – ${rule.value[1] === null ? '…' : formatNumber(rule.value[1])}`;+ case 'temporal range': {+ const format = (x: number | null) => (x === null ? '…' : formatDate(parsedOffsetDate(displayOffset, rule.offset)(x)));+ return `${format(rule.value[0])} – ${format(rule.value[1])}`;+ }+ case 'regexp':+ return `/${rule.value}/`;+ }+ },+ [t, displayOffset]+ );+}++function FilterChip(props: { name: string; description: string; analyticType: IMutField['analyticType']; onEdit: () => void; onRemove: () => void }) {+ const { t } = useTranslation('translation', { keyPrefix: 'data_table' });+ return (+ <span className="inline-flex h-[26px] shrink-0 items-center gap-1.5 rounded-md border pl-2 pr-0.5 text-xs">+ <span className={cn('h-1.5 w-1.5 shrink-0 rounded-[2px]', props.analyticType === 'dimension' ? 'bg-dimension' : 'bg-measure')} />+ <button+ type="button"+ className="flex min-w-0 items-center gap-1.5 rounded-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ onClick={props.onEdit}+ >+ <span className="text-muted-foreground">{props.name}</span>+ <span className="max-w-[180px] truncate font-medium text-foreground">{props.description}</span>+ </button>+ <button+ type="button"+ aria-label={t('remove_filter', { name: props.name })}+ className="flex h-5 w-5 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ onClick={props.onRemove}+ >+ <XMarkIcon className="h-3 w-3" />+ </button>+ </span>+ );+}++const strong = <b className="font-semibold tabular-nums text-foreground" />;+const DataTable = forwardRef((props: DataTableProps,@@ -241,161 +216,411 @@ const DataTable = forwardRef(getFilters: () => IVisFilter[];}>) => {- const {- size = 10,- onMetaChange,- metas,- computation,- disableFilter,- disableSorting,- hideSemanticType,- displayOffset,- hidePaginationAtOnepage,- hideProfiling,- } = props;- const [pageIndex, setPageIndex] = useState(0);- const { t } = useTranslation();- const computationFunction = computation;-- const semanticTypeList = useMemo<{ value: string; label: string }[]>(() => {- return SEMANTIC_TYPE_LIST.map((st) => ({- value: st,- label: t(`constant.semantic_type.${st}`),- }));- }, []);+ const {+ size = 10,+ onMetaChange,+ metas,+ computation,+ disableFilter,+ disableSorting,+ hideSemanticType,+ displayOffset,+ hidePaginationAtOnepage,+ hideProfiling,+ } = props;+ const [pageIndex, setPageIndex] = useState(0);+ const { t } = useTranslation();+ const computationFunction = computation;- const [rows, setRows] = useState<IRow[]>([]);- const [dataLoading, setDataLoading] = useState(false);- const taskIdRef = useRef(0);+ const semanticTypeList = useMemo(() => {+ return SEMANTIC_TYPE_LIST.map((st) => ({+ value: st,+ label: t(`constant.semantic_type.${st}`),+ }));+ }, [t]);- const [sorting, setSorting] = useState<{ fid: string; sort: 'ascending' | 'descending' } | undefined>();+ const [rows, setRows] = useState<IRow[]>([]);+ const [dataLoading, setDataLoading] = useState(false);+ const taskIdRef = useRef(0);- const { filters, editingFilterIdx, onClose, onDeleteFilter, onSelectFilter, onWriteFilter, options } = useFilters(metas);+ const [sorting, setSorting] = useState<{ fid: string; sort: ISortDirection } | undefined>();- const filtersRef = useRef(filters);- filtersRef.current = filters;+ const { filters, editingFilterIdx, onClose, onSelectFilter, onWriteFilter, setFieldRule, clearFilters, options } = useFilters(metas);- useImperativeHandle(ref, () => ({- getFilters: () => filtersRef.current.filter(x => x.rule) as IVisFilter[],- }));+ const filtersRef = useRef(filters);+ filtersRef.current = filters;- const [total, setTotal] = useState(0);- const [statLoading, setStatLoading] = useState(false);+ useImperativeHandle(ref, () => ({+ getFilters: () => filtersRef.current.filter((x) => x.rule) as IVisFilter[],+ }));- // Get count when filter changed- useEffect(() => {- const f = filters.filter((x) => x.rule).map((x) => ({ ...x, rule: x.rule }));- setStatLoading(true);- computation({- workflow: [- ...(!disableFilter && f && f.length > 0- ? [- {- type: 'filter',- filters: f,- } as IFilterWorkflowStep,- ]- : []),- {- type: 'view',- query: [+ const activeFilters = useMemo(() => (disableFilter ? [] : filters.filter((x) => x.rule)), [disableFilter, filters]);+ const filterRules = useMemo(() => activeFilters.map(createFilter), [activeFilters]);+ const describeRule = useRuleDescription(displayOffset);++ const [total, setTotal] = useState(0);+ const [unfilteredTotal, setUnfilteredTotal] = useState(0);+ const [statLoading, setStatLoading] = useState(false);++ // Get count when filter changed+ useEffect(() => {+ setStatLoading(true);+ const countOf = (f: IVisFilter[]) =>+ computation({+ workflow: [+ ...(f.length > 0+ ? [+ {+ type: 'filter',+ filters: f,+ } as IFilterWorkflowStep,+ ]+ : []),{- op: 'aggregate',- groupBy: [],- measures: [+ type: 'view',+ query: [{- field: '*',- agg: 'count',- asFieldKey: 'count',+ op: 'aggregate',+ groupBy: [],+ measures: [+ {+ field: '*',+ agg: 'count',+ asFieldKey: 'count',+ },+ ],},],},],- },- ],- }).then((v) => {- setTotal(v[0]?.count ?? 0);- setStatLoading(false);- });- }, [disableFilter, filters, computation]);-- const from = pageIndex * size;- const to = Math.min((pageIndex + 1) * size - 1, total - 1);+ }).then((v) => (v[0]?.count ?? 0) as number);+ let alive = true;+ countOf(filterRules).then((count) => {+ if (!alive) return;+ setTotal(count);+ setStatLoading(false);+ });+ if (filterRules.length > 0) {+ countOf([]).then((count) => alive && setUnfilteredTotal(count));+ }+ return () => {+ alive = false;+ };+ }, [filterRules, computation]);- useEffect(() => {- if (from > total) {+ // a new filter or sort order starts from the first page+ useEffect(() => {setPageIndex(0);- }- }, [from, total]);+ }, [filterRules, sorting]);- useEffect(() => {- setDataLoading(true);- const taskId = ++taskIdRef.current;- dataReadRaw(computationFunction, size, pageIndex, {- sorting: disableSorting ? undefined : sorting,- filters: filters.filter((x) => x.rule).map((x) => ({ ...x, rule: x.rule! })),- })- .then((data) => {- if (taskId === taskIdRef.current) {- setDataLoading(false);- setRows(data);- }+ const from = pageIndex * size;+ const to = Math.min((pageIndex + 1) * size - 1, total - 1);++ useEffect(() => {+ if (from > total) {+ setPageIndex(0);+ }+ }, [from, total]);++ useEffect(() => {+ setDataLoading(true);+ const taskId = ++taskIdRef.current;+ dataReadRaw(computationFunction, size, pageIndex, {+ sorting: disableSorting ? undefined : sorting,+ filters: filterRules,})- .catch((err) => {- if (taskId === taskIdRef.current) {- console.error(err);- setDataLoading(false);- setRows([]);- }- });- return () => {- taskIdRef.current++;- };- }, [computationFunction, pageIndex, size, sorting, filters, disableSorting]);+ .then((data) => {+ if (taskId === taskIdRef.current) {+ setDataLoading(false);+ setRows(data);+ }+ })+ .catch((err) => {+ if (taskId === taskIdRef.current) {+ console.error(err);+ setDataLoading(false);+ setRows([]);+ }+ });+ return () => {+ taskIdRef.current++;+ };+ }, [computationFunction, pageIndex, size, sorting, filterRules, disableSorting]);- const filteredComputation = useMemo((): IComputationFunction => {- const filterRules = filters.filter((f) => f.rule).map(createFilter);- return (query) => computation(addFilterForQuery(query, filterRules));- }, [computation, filters]);+ // Each column is profiled against every filter except its own, so a filtered column keeps showing its whole+ // distribution with the selection highlighted. Functions are reused while a column's filters are unchanged,+ // which keeps its profile from being fetched again.+ const profileCache = useRef(new Map<string, { key: string; base: IComputationFunction; fn: IComputationFunction }>());+ const profileComputations = useMemo(() => {+ const next = new Map<string, { key: string; base: IComputationFunction; fn: IComputationFunction }>();+ for (const meta of metas) {+ const rules = filterRules.filter((x) => x.fid !== meta.fid);+ const key = JSON.stringify(rules);+ const prev = profileCache.current.get(meta.fid);+ if (prev && prev.key === key && prev.base === computation) {+ next.set(meta.fid, prev);+ } else {+ next.set(meta.fid, {+ key,+ base: computation,+ fn: rules.length > 0 ? (query) => computation(addFilterForQuery(query, rules)) : computation,+ });+ }+ }+ profileCache.current = next;+ return next;+ }, [computation, filterRules, metas]);- const loading = statLoading || dataLoading;+ const loading = statLoading || dataLoading;- const headers = useMemo(() => getHeaders(metas), [metas]);+ const headers = useMemo(() => getHeaders(metas), [metas]);- const [isSticky, setIsSticky] = useState(false);+ const [isSticky, setIsSticky] = useState(false);- const obRef = useRef<IntersectionObserver>(null);- const stickyDector = useCallback((node: HTMLDivElement) => {- obRef.current?.disconnect();- if (node) {- const observer = new IntersectionObserver((entries) => {- entries.forEach((entry) => {- setIsSticky(!entry.isIntersecting);+ const obRef = useRef<IntersectionObserver>(null);+ const stickyDector = useCallback((node: HTMLDivElement) => {+ obRef.current?.disconnect();+ if (node) {+ const observer = new IntersectionObserver((entries) => {+ entries.forEach((entry) => {+ setIsSticky(!entry.isIntersecting);+ });});+ observer.observe(node);+ obRef.current = observer;+ }+ }, []);++ const filterByFid = useMemo(() => new Map(activeFilters.map((x) => [x.fid, x])), [activeFilters]);++ const toggleValue = useCallback(+ (fid: string, value: any) => {+ const rule = filterByFid.get(fid)?.rule;+ const values = rule?.type === 'one of' ? [...rule.value] : [];+ const encoded = _unstable_encodeRuleValue(value);+ const i = values.findIndex((x) => _unstable_encodeRuleValue(x) === encoded);+ if (i > -1) {+ values.splice(i, 1);+ } else {+ values.push(value);+ }+ setFieldRule(fid, values.length > 0 ? { type: 'one of', value: values } : null);+ },+ [filterByFid, setFieldRule]+ );++ const selectRange = useCallback(+ (fid: string, [lo, hi]: [number, number], extend: boolean) => {+ const rule = filterByFid.get(fid)?.rule;+ if (rule?.type === 'range') {+ if (extend) {+ setFieldRule(fid, { type: 'range', value: [Math.min(rule.value[0] ?? lo, lo), Math.max(rule.value[1] ?? hi, hi)] });+ return;+ }+ if (rule.value[0] === lo && rule.value[1] === hi) {+ setFieldRule(fid, null);+ return;+ }+ }+ setFieldRule(fid, { type: 'range', value: [lo, hi] });+ },+ [filterByFid, setFieldRule]+ );++ const toggleSort = useCallback((fid: string) => {+ setSorting((s) => {+ if (s?.fid !== fid) return { fid, sort: 'descending' };+ if (s.sort === 'descending') return { fid, sort: 'ascending' };+ return undefined;});- observer.observe(node);- obRef.current = observer;- }- }, []);- return (- <Container className="relative">- {!disableFilter && filters.length > 0 && (- <div className="flex items-center p-2 space-x-2">- <span>Filters: </span>- {filters.map((x, i) => (- <FilterPill key={x.fid} name={x.name} onClick={() => onSelectFilter(x.fid)} onRemove={() => onDeleteFilter(i)} />- ))}+ }, []);++ const showFooter = !(hidePaginationAtOnepage && total <= size);+ const headerRowCount = headers.length + (hideProfiling ? 0 : 1);++ return (+ <div className="relative flex h-full flex-col overflow-hidden rounded-lg border bg-background text-[13px] text-foreground">+ <div className="flex h-12 shrink-0 items-center gap-3 border-b px-4">+ <span className="whitespace-nowrap text-muted-foreground">+ {activeFilters.length > 0 ? (+ <Trans+ i18nKey="data_table.rows_filtered"+ count={total}+ values={{ value: formatCount(total), total: formatCount(unfilteredTotal) }}+ components={{ b: strong }}+ />+ ) : (+ <Trans i18nKey="data_table.rows" count={total} values={{ value: formatCount(total) }} components={{ b: strong }} />+ )}+ </span>+ <span className="h-4 w-px shrink-0 bg-border" />+ <span className="whitespace-nowrap text-muted-foreground">+ <Trans i18nKey="data_table.columns" count={metas.length} values={{ value: formatCount(metas.length) }} components={{ b: strong }} />+ </span>+ {activeFilters.length > 0 && (+ <>+ <span className="h-4 w-px shrink-0 bg-border" />+ <div className="flex min-w-0 items-center gap-1.5 overflow-x-auto">+ {activeFilters.map((x) => (+ <FilterChip+ key={x.fid}+ name={x.name}+ analyticType={x.analyticType}+ description={describeRule(x.rule!)}+ onEdit={() => onSelectFilter(x.fid)}+ onRemove={() => setFieldRule(x.fid, null)}+ />+ ))}+ <button+ type="button"+ className="shrink-0 rounded px-1.5 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ onClick={clearFilters}+ >+ {t('data_table.clear')}+ </button>+ </div>+ </>+ )}+ {loading && <Spinner className="ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground" />}</div>- )}- {!(hidePaginationAtOnepage && total <= size) && (- <nav className="flex items-center justify-end space-x-2 p-2" aria-label="Pagination">- <div className="hidden sm:block flex-1">- <p className="text-sm text-muted-foreground">- Showing <span className="font-medium">{from + 1}</span> to <span className="font-medium">{to + 1}</span> of{' '}- <span className="font-medium">{total}</span> results- </p>- </div>- <div className="space-x-2">+ <div className="relative min-h-0 flex-1 overflow-auto" style={{ maxHeight: '600px' }}>+ <div className="h-0 w-full" ref={stickyDector}></div>+ <table className="w-full border-separate border-spacing-0">+ <thead className={cn('sticky top-0 z-10 bg-background', isSticky && 'shadow-[0_8px_16px_-12px_rgba(0,0,0,0.35)]')}>+ {headers.map((row, rowIndex) => (+ <tr key={`row_${rowIndex}`}>+ {rowIndex === 0 && (+ <th+ rowSpan={headerRowCount}+ scope="col"+ className="w-11 min-w-[44px] border-b pr-2.5 pt-[15px] text-right align-top text-[11px] font-normal text-muted-foreground/70"+ >+ #+ </th>+ )}+ {row.map((f, i) => {+ if (f.type === 'name') {+ return (+ <th+ key={`group_${i}_${f.value}`}+ colSpan={f.colSpan}+ rowSpan={f.rowSpan}+ scope="colgroup"+ className="border-b border-border/60 px-3 pb-1.5 pt-3 text-left align-bottom text-[11px] font-medium uppercase tracking-wide text-muted-foreground"+ >+ <span className="sticky left-3 whitespace-nowrap">{f.value}</span>+ </th>+ );+ }+ const field = f.value;+ const sort = sorting?.fid === field.fid ? sorting.sort : undefined;+ return (+ <th+ key={getHeaderKey(f)}+ colSpan={f.colSpan}+ rowSpan={f.rowSpan}+ scope="col"+ aria-sort={sort ?? 'none'}+ className={cn(+ 'group/th min-w-[128px] px-3 pt-3 text-left align-bottom font-normal',+ hideProfiling ? 'border-b pb-3' : 'pb-2.5',+ sort && 'bg-foreground/[0.025]'+ )}+ >+ <ColumnHeader+ field={field}+ sort={sort}+ filtered={filterByFid.has(field.fid)}+ hideSemanticType={hideSemanticType}+ semanticTypeOptions={semanticTypeList}+ onToggleSort={disableSorting ? undefined : () => toggleSort(field.fid)}+ onSort={disableSorting ? undefined : (s) => setSorting(s ? { fid: field.fid, sort: s } : undefined)}+ onFilter={disableFilter ? undefined : () => onSelectFilter(field.fid)}+ onClearFilter={disableFilter ? undefined : () => setFieldRule(field.fid, null)}+ onChangeSemanticType={+ onMetaChange ? (semanticType) => onMetaChange(field.fid, f.fIndex, { semanticType }) : undefined+ }+ />+ </th>+ );+ })}+ </tr>+ ))}+ {!hideProfiling && (+ <tr>+ {metas.map((field) => (+ <th+ key={field.fid}+ className={cn(+ 'border-b px-3 pb-3 text-left align-top font-normal',+ sorting?.fid === field.fid && 'bg-foreground/[0.025]'+ )}+ >+ <FieldProfiling+ field={field.fid}+ semanticType={field.semanticType}+ analyticType={field.analyticType}+ computation={profileComputations.get(field.fid)?.fn ?? computation}+ displayOffset={displayOffset}+ offset={field.offset}+ rule={filterByFid.get(field.fid)?.rule}+ onToggleValue={disableFilter ? undefined : (value) => toggleValue(field.fid, value)}+ onSelectRange={disableFilter ? undefined : (range, extend) => selectRange(field.fid, range, extend)}+ />+ </th>+ ))}+ </tr>+ )}+ </thead>+ <tbody className={cn('transition-opacity', dataLoading && rows.length > 0 && 'opacity-60')}>+ {rows.map((row, index) => (+ <tr className="hover:bg-muted/50" key={index}>+ <td className="border-b border-border/60 pr-2.5 text-right text-[11.5px] tabular-nums text-muted-foreground/70">+ {formatCount(from + index + 1)}+ </td>+ {metas.map((field) => {+ const value = fieldValue({ field, item: row, displayOffset });+ return (+ <td+ key={field.fid + index}+ className={cn(+ 'h-9 max-w-[280px] whitespace-nowrap border-b border-border/60 px-3',+ field.analyticType === 'measure'+ ? 'text-right tabular-nums text-foreground'+ : 'text-left text-foreground/80',+ sorting?.fid === field.fid && 'bg-foreground/[0.025]'+ )}+ >+ <TruncateDector value={value} />+ </td>+ );+ })}+ </tr>+ ))}+ </tbody>+ </table>+ {!loading && rows.length === 0 && (+ <div className="flex flex-col items-center gap-3 py-16 text-muted-foreground">+ <span>{activeFilters.length > 0 ? t('data_table.no_matching_rows') : t('data_table.no_rows')}</span>+ {activeFilters.length > 0 && (+ <Button variant="outline" size="sm" onClick={clearFilters}>+ {t('data_table.clear_filters')}+ </Button>+ )}+ </div>+ )}+ </div>+ {showFooter && (+ <div className="flex h-12 shrink-0 items-center justify-between gap-4 border-t pl-4 pr-3">+ <span className="whitespace-nowrap text-muted-foreground">+ {total > 0 && (+ <Trans+ i18nKey="data_table.range"+ values={{ from: formatCount(from + 1), to: formatCount(to + 1), total: formatCount(total) }}+ components={{ b: strong }}+ />+ )}+ </span><Paginationtotal={total}pageSize={size}@@ -411,186 +636,26 @@ const DataTable = forwardRef(}}/></div>- </nav>- )}- <div className="overflow-y-auto h-full" style={{ maxHeight: '600px' }}>- <div className="h-0 w-full" ref={stickyDector}></div>- <table className="min-w-full relative border-x">- <thead className={`sticky top-0 bg-background ${isSticky ? 'shadow-md' : ''}`}>- {headers.map((row) => (- <tr className="divide-x divide-border" key={`row_${getHeaderKey(row[0])}`}>- {row.map((f, i) => (- <th- colSpan={f.colSpan}- rowSpan={f.rowSpan}- key={getHeaderKey(f)}- className="align-top p-0 border-b bg-background"- style={{ zIndex: row.length - i }}- >- {f.type === 'name' && (- <div- className={- 'inset-x-0 border-t-4 border-yellow-400 whitespace-nowrap py-3.5 text-left text-xs font-medium text-foreground'- }- >- <b className="sticky inset-x-0 w-fit px-4 sm:pl-6">{f.value}</b>- </div>- )}- {f.type === 'field' && (- <div- className={- getHeaderClassNames(f.value) +- ' whitespace-nowrap py-3.5 px-4 text-left text-xs font-medium text-foreground flex items-center gap-1 group'- }- >- <div className="font-normal block">- {!hideSemanticType && !onMetaChange && (- <span className={'inline-flex p-0.5 text-xs mt-1 rounded ' + getSemanticColors(f.value)}>- <DataTypeIcon dataType={f.value.semanticType} analyticType={f.value.analyticType} />- </span>- )}- {!hideSemanticType && onMetaChange && (- <DropdownContext- options={semanticTypeList}- onSelect={(value) => {- onMetaChange(f.value.fid, f.fIndex, {- semanticType: value as IMutField['semanticType'],- });- }}- >- <span- className={- 'cursor-pointer inline-flex p-0.5 text-xs mt-1 rounded hover:scale-125 ' +- getSemanticColors(f.value)- }- >- <DataTypeIcon dataType={f.value.semanticType} analyticType={f.value.analyticType} />- </span>- </DropdownContext>- )}- </div>- <b- className="inline-block"- onClick={() => {- if (disableSorting) return;- setSorting((s) => {- if (s?.fid === f.value.fid && s.sort === 'descending') {- return {- fid: f.value.fid,- sort: 'ascending',- };- }- return {- fid: f.value.fid,- sort: 'descending',- };- });- }}- >- {f.value.basename || f.value.name || f.value.fid}- </b>- {!disableSorting && sorting?.fid === f.value.fid && (- <div className="mx-1">- {sorting.sort === 'ascending' && <BarsArrowUpIcon className="w-3" />}- {sorting.sort === 'descending' && <BarsArrowDownIcon className="w-3" />}- </div>- )}- {!disableFilter && (- <div- className={buttonVariants({- variant: 'ghost',- className: 'cursor-pointer invisible group-hover:visible',- size: 'icon-sm',- })}- onClick={() => onSelectFilter(f.value.fid)}- >- <FunnelIcon className="w-4 inline-block" />- </div>- )}- </div>- )}- </th>- ))}- </tr>- ))}- {!props.hideProfiling && (- <tr className="divide-x divide-border border-b">- {metas.map((field) => (- <th key={field.fid} className={getHeaderType(field) + ' whitespace-nowrap py-2 px-3 text-xs text-muted-foreground'}>- <FieldProfiling- field={field.fid}- semanticType={field.semanticType}- computation={filteredComputation}- displayOffset={displayOffset}- offset={field.offset}- />- </th>- ))}- </tr>- )}- </thead>- <tbody className="divide-y divide-border bg-background font-mono">- {rows.map((row, index) => (- <tr className="divide-x divide-border" key={index}>- {metas.map((field) => {- const value = fieldValue({ field, item: row, displayOffset });- return (- <td- key={field.fid + index}- className={getHeaderType(field) + ' whitespace-nowrap py-2 px-4 text-xs text-muted-foreground max-w-[240px]'}- >- <TruncateDector value={value} />- </td>- );- })}- </tr>- ))}- </tbody>- </table>+ )}+ {!disableFilter && (+ <ComputationContext.Provider value={computation}>+ <div className="text-xs">+ <PureFilterEditDialog+ editingFilterIdx={editingFilterIdx}+ meta={metas}+ onClose={onClose}+ onSelectFilter={onSelectFilter}+ onWriteFilter={onWriteFilter}+ options={options}+ viewFilters={filters}+ displayOffset={displayOffset}+ />+ </div>+ </ComputationContext.Provider>+ )}</div>-- {loading && <LoadingLayer />}- {!disableFilter && (- <ComputationContext.Provider value={computation}>- <div className="text-xs">- <PureFilterEditDialog- editingFilterIdx={editingFilterIdx}- meta={metas}- onClose={onClose}- onSelectFilter={onSelectFilter}- onWriteFilter={onWriteFilter}- options={options}- viewFilters={filters}- displayOffset={displayOffset}- />- </div>- </ComputationContext.Provider>- )}- </Container>- );-});+ );+ }+);export default DataTable;--const FilterPill = (props: { name: string; onRemove?: () => void; onClick?: () => void }) => {- return (- <Badge onClick={props.onClick} className="gap-x-0.5">- {props.name}- <Button- onClick={(e) => {- e.stopPropagation();- props.onRemove?.();- }}- variant="ghost"- size="none"- className="relative -mr-1 h-3.5 w-3.5 rounded-sm"- >- <span className="sr-only">Remove</span>- <svg viewBox="0 0 14 14" className="h-3.5 w-3.5 stroke-current">- <path d="M4 4l6 6m0-6l-6 6" />- </svg>- <span className="absolute -inset-1"></span>- </Button>- </Badge>- );-};diff --git a/packages/graphic-walker/src/components/dataTable/pagination.tsx b/packages/graphic-walker/src/components/dataTable/pagination.tsxindex 5ed74361..58a58e18 100644--- a/packages/graphic-walker/src/components/dataTable/pagination.tsx+++ b/packages/graphic-walker/src/components/dataTable/pagination.tsx@@ -1,14 +1,7 @@import React, { useMemo } from 'react';import { useTranslation } from 'react-i18next';-import {- Pagination as PaginationRoot,- PaginationEllipsis,- PaginationItem,- PaginationNext,- PaginationPrevious,- PaginationContent,- PaginationLink,-} from '../ui/pagination';+import { ChevronLeftIcon, ChevronRightIcon } from '@heroicons/react/16/solid';+import { cn } from '../../utils';type IPageItem = {index: number;@@ -73,56 +66,63 @@ export default function Pagination(props: PaginationProps) {() => getShowIndices(total, pageIndex, pageSize, extendPageNumber),[pageIndex, pageSize, extendPageNumber, total, pageIndex]);+ const pageCount = Math.ceil(total / (pageSize || 1));- const pageButton = (index: number) => {- return (- <PaginationItem key={index}>- <PaginationLink- size="default"- className='px-3 min-w-[2.25rem]'- isActive={index === pageIndex}- onClick={() => {- onPageChange && onPageChange(index);- }}- >- {index + 1}- </PaginationLink>- </PaginationItem>- );- };+ if (showIndices.length === 0) {+ return null;+ }- return showIndices.length > 0 ? (- <PaginationRoot>- <PaginationContent>- <PaginationItem>- <PaginationPrevious- onClick={() => {- onPrev();- }}- >- {t('actions.prev')}- </PaginationPrevious>- </PaginationItem>- {showIndices.map((x) => {- if (x.type === 'placeholder') {- return (- <PaginationItem key={x.index}>- <PaginationEllipsis />- </PaginationItem>- );- }- return pageButton(x.index);- })}- <PaginationItem>- <PaginationNext+ const buttonClassName =+ 'inline-flex h-7 min-w-[28px] items-center justify-center rounded-md px-1.5 text-[13px] tabular-nums text-foreground/80 transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-30';++ return (+ <nav aria-label="pagination" className="flex items-center gap-0.5">+ <button+ type="button"+ className={buttonClassName}+ aria-label={t('actions.prev')}+ title={t('actions.prev')}+ disabled={pageIndex <= 0}+ onClick={onPrev}+ >+ <ChevronLeftIcon className="h-4 w-4" />+ </button>+ {showIndices.map((x, i) => {+ if (x.type === 'placeholder') {+ return (+ <span key={`gap-${i}`} aria-hidden className="w-6 text-center text-muted-foreground">+ …+ </span>+ );+ }+ const active = x.index === pageIndex;+ return (+ <button+ key={x.index}+ type="button"+ aria-current={active ? 'page' : undefined}+ className={cn(+ buttonClassName,+ active && 'bg-primary font-semibold text-primary-foreground hover:bg-primary hover:text-primary-foreground'+ )}onClick={() => {- onNext();+ onPageChange && onPageChange(x.index);}}>- {t('actions.next')}- </PaginationNext>- </PaginationItem>- </PaginationContent>- </PaginationRoot>- ) : null;+ {x.index + 1}+ </button>+ );+ })}+ <button+ type="button"+ className={buttonClassName}+ aria-label={t('actions.next')}+ title={t('actions.next')}+ disabled={pageIndex >= pageCount - 1}+ onClick={onNext}+ >+ <ChevronRightIcon className="h-4 w-4" />+ </button>+ </nav>+ );}diff --git a/packages/graphic-walker/src/components/dataTable/profiling.tsx b/packages/graphic-walker/src/components/dataTable/profiling.tsxindex 7fd518af..57c3ad32 100644--- a/packages/graphic-walker/src/components/dataTable/profiling.tsx+++ b/packages/graphic-walker/src/components/dataTable/profiling.tsx@@ -1,177 +1,356 @@-import { ComponentType, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';-import { IComputationFunction, ISemanticType } from '../../interfaces';-import { profileNonmialField, profileQuantitativeField, wrapComputationWithTag } from '../../computation';-import React from 'react';-import { formatDate, isNotEmpty } from '../../utils';-import Tooltip from '../tooltip';-import { themeContext, vegaThemeContext } from '../../store/theme';-import { parsedOffsetDate } from '../../lib/op/offset';-import embed, { VisualizationSpec } from 'vega-embed';+import React, { ComponentType, useCallback, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';import { format } from 'd3-format';-import { getTheme } from '../../utils/useTheme';+import type { IAnalyticType, IComputationFunction, IFilterRule, ISemanticType } from '../../interfaces';+import { profileNonmialField, profileQuantitativeField, wrapComputationWithTag, type IQuantitativeProfileBin } from '../../computation';+import { _unstable_encodeRuleValue, cn, formatDate, isNotEmpty } from '../../utils';+import { parsedOffsetDate } from '../../lib/op/offset';export interface FieldProfilingProps {field: string;computation: IComputationFunction;}-function NominalProfiling({ computation, field, valueRenderer = (s) => `${s}` }: FieldProfilingProps & { valueRenderer?: (v: string | number) => string }) {- const [stat, setStat] = useState<Awaited<ReturnType<typeof profileNonmialField>>>();+interface ProfilingInteractionProps {+ analyticType: IAnalyticType;+ /** the filter currently applied on this field, used to highlight the selection */+ rule?: IFilterRule | null;+ /** toggles a value in a `one of` filter; omitted when filtering is disabled */+ onToggleValue?: (value: any) => void;+ /** filters the field to a range; `extend` merges the range into the current one */+ onSelectRange?: (range: [number, number], extend: boolean) => void;+}++const CHART_HEIGHT = 'h-[58px]';++// Tailwind needs the full class names to be present in the source, so every accent variant is spelled out.+const ACCENT = {+ dimension: {+ wash: 'bg-dimension/[0.16]',+ washHover: 'group-hover/value:bg-dimension/30',+ washOn: 'bg-dimension/40',+ bar: 'bg-dimension',+ },+ measure: {+ wash: 'bg-measure/[0.16]',+ washHover: 'group-hover/value:bg-measure/30',+ washOn: 'bg-measure/40',+ bar: 'bg-measure',+ },+} as const;++const formatCount = (n: number) => n.toLocaleString();++const siFormatter = format('.3~s');+const decimalFormatter = format(',.2~f');+const smallFormatter = format('.3~g');+export function formatNumber(x: number) {+ if (!Number.isFinite(x)) return `${x}`;+ const abs = Math.abs(x);+ if (abs >= 1e5) return siFormatter(x);+ if (abs >= 1 || x === 0) return decimalFormatter(x);+ return smallFormatter(x);+}++const approxFormatter = format(',.3~r');+/** A glanceable summary number, e.g. an average. */+function formatApprox(x: number) {+ if (!Number.isFinite(x)) return `${x}`;+ return Math.abs(x) >= 1e5 ? siFormatter(x) : approxFormatter(x);+}++/** Integer percentages that always add up to 100 (largest remainder). */+function toPercents(counts: number[], total: number) {+ if (!total) return counts.map(() => 0);+ const raw = counts.map((c) => (c * 100) / total);+ const result = raw.map(Math.floor);+ let left = 100 - result.reduce((a, b) => a + b, 0);+ const order = raw.map((v, i) => [v - result[i], i] as const).sort((a, b) => b[0] - a[0]);+ for (let k = 0; left > 0 && k < order.length; k++, left--) {+ result[order[k][1]] += 1;+ }+ return result;+}++/** Keeps the previous result on screen while a new one loads, and drops stale responses. */+function useProfile<T>(load: () => Promise<T>, deps: React.DependencyList) {+ const [state, setState] = useState<{ data?: T; loading: boolean }>({ loading: true });useEffect(() => {- profileNonmialField(wrapComputationWithTag(computation, "profiling"), field).then(setStat);- }, [computation, field]);+ let alive = true;+ setState((s) => ({ data: s.data, loading: true }));+ load().then(+ (data) => alive && setState({ data, loading: false }),+ (err) => {+ if (!alive) return;+ console.error(err);+ setState((s) => ({ data: s.data, loading: false }));+ }+ );+ return () => {+ alive = false;+ };+ }, deps);+ return state;+}++function Caption({ children }: { children?: React.ReactNode }) {+ return <div className="mt-2 h-3.5 truncate text-[11.5px] leading-[14px] text-muted-foreground">{children}</div>;+}++function Skeleton({ kind }: { kind: 'nominal' | 'quantitative' }) {+ if (kind === 'quantitative') {+ return (+ <div className={cn(CHART_HEIGHT, 'flex items-end gap-0.5 pb-[18px]')}>+ {[18, 30, 55, 80, 100, 85, 60, 40, 22, 12].map((h, i) => (+ <div key={i} className="flex-1 animate-pulse rounded-t-[3px] bg-muted" style={{ height: `${h}%` }} />+ ))}+ </div>+ );+ }+ return (+ <div className={cn(CHART_HEIGHT, 'flex flex-col gap-[3px]')}>+ {[72, 54, 38].map((w) => (+ <div key={w} className="h-[17px] animate-pulse rounded-[5px] bg-muted" style={{ width: `${w}%` }} />+ ))}+ </div>+ );+}++function Constant({ children }: { children: React.ReactNode }) {+ return <div className={cn(CHART_HEIGHT, 'flex items-center truncate text-[15px] text-foreground/80')}>= {children}</div>;+}++function NominalProfiling({+ computation,+ field,+ analyticType,+ rule,+ onToggleValue,+ valueRenderer = (s) => `${s}`,+}: FieldProfilingProps & ProfilingInteractionProps & { valueRenderer?: (v: string | number) => string }) {+ const { t } = useTranslation('translation', { keyPrefix: 'data_table' });+ const { data: stat, loading } = useProfile(() => profileNonmialField(wrapComputationWithTag(computation, 'profiling'), field), [computation, field]);if (!isNotEmpty(stat)) {- return <div className="h-24 flex items-center justify-center">Loading...</div>;+ return (+ <>+ <Skeleton kind="nominal" />+ <Caption />+ </>+ );}- const render = (value) => {+ const [meta, tops] = stat;+ const render = (value: string | number) => {const displayValue = valueRenderer(value);if (!displayValue) {- return <span className="text-destructive">(Empty)</span>;+ return <span className="text-destructive">{t('empty_value')}</span>;}return displayValue;};- const [meta, tops] = stat;- // shows top 2 when the maximum quantity is more than 1.3x the average quantity, and over 1%.- // or there are lower than 10 unique values.- const showsTops = meta.distinctTotal < 10 || (tops[0].count > (1.3 * meta.total) / meta.distinctTotal && tops[0].count > meta.total / 100);+ if (meta.total === 0 || tops.length === 0) {+ return (+ <>+ <div className={cn(CHART_HEIGHT, 'flex items-center text-muted-foreground')}>—</div>+ <Caption />+ </>+ );+ }if (meta.distinctTotal === 1) {- return <div className="h-24 flex items-center justify-center text-xl">= {render(tops[0].value)}</div>;+ return (+ <>+ <Constant>{render(tops[0].value)}</Constant>+ <Caption>{t('unique_count', { count: 1, value: formatCount(1) })}</Caption>+ </>+ );+ }++ // shows the top values when the most frequent one is more than 1.3x the average and over 1%,+ // or when there are fewer than 10 unique values.+ const showsTops = meta.distinctTotal < 10 || (tops[0].count > (1.3 * meta.total) / meta.distinctTotal && tops[0].count > meta.total / 100);+ if (!showsTops) {+ return (+ <div className={cn('transition-opacity', loading && 'opacity-50')}>+ <div className={cn(CHART_HEIGHT, 'flex flex-col justify-center')}>+ <div className="text-lg font-semibold leading-6">{formatCount(meta.distinctTotal)}</div>+ <div className="text-[11.5px] text-muted-foreground">{t('unique_values')}</div>+ </div>+ <Caption>{t('distinct_ratio', { percent: Math.round((meta.distinctTotal * 100) / meta.total) })}</Caption>+ </div>+ );}+ const shown = meta.distinctTotal <= tops.length ? tops : tops.slice(0, 2);+ const otherCount = meta.total - shown.reduce((sum, x) => sum + x.count, 0);+ const otherValues = meta.distinctTotal - shown.length;+ const percents = toPercents(otherValues > 0 ? [...shown.map((x) => x.count), otherCount] : shown.map((x) => x.count), meta.total);++ const selected = rule?.type === 'one of' || rule?.type === 'not in' ? new Set(rule.value.map(_unstable_encodeRuleValue)) : null;+ const isOn = (value: unknown) => {+ if (!selected || !rule) return false;+ const has = selected.has(_unstable_encodeRuleValue(value));+ return rule.type === 'one of' ? has : !has;+ };+ const accent = ACCENT[analyticType];+return (- <div className="h-24 flex items-center justify-center flex-col gap-2 text-xs">- {showsTops && (- <>- {tops.map(({ count, value }, idx) => {- const displayValue = render(value);- return (- <Tooltip key={idx} content={displayValue}>- <div className="w-full rounded-md px-2 py-1 hover:bg-accent flex justify-between space-x-2">- <div className="min-w-[0px] flex-shrink truncate max-w-[180px]">{displayValue}</div>- <div className="flex-shrink-0">{Math.floor((100 * count) / meta.total)}%</div>- </div>- </Tooltip>- );- })}- {meta.distinctTotal > tops.length && (- <div className="w-full rounded-md px-2 py-1 text-muted-foreground hover:bg-accent flex justify-between space-x-2">- <div className="min-w-[0px] flex-shrink whitespace-nowrap text-ellipsis overflow-hidden">- Other ({meta.distinctTotal - tops.length})- </div>- <div className="flex-shrink-0">- {100 - tops.reduce((totalPercent, { count }) => totalPercent + Math.floor((100 * count) / meta.total), 0)}%- </div>+ <div className={cn('transition-opacity', loading && 'opacity-50')}>+ <div className={cn(CHART_HEIGHT, 'flex flex-col gap-[3px]')}>+ {shown.map(({ value, count }, i) => {+ const on = isOn(value);+ const content = (+ <>+ <span+ className={cn(+ 'absolute inset-y-0 left-0 rounded-[5px] transition-[background-color,opacity]',+ on ? accent.washOn : cn(accent.wash, onToggleValue && accent.washHover),+ selected && !on && 'opacity-[0.45]'+ )}+ style={{ width: `${(count * 100) / meta.total}%` }}+ />+ <span className={cn('relative min-w-0 truncate', on ? 'font-semibold text-foreground' : 'text-foreground/80')}>+ {render(value)}+ </span>+ <span className={cn('relative shrink-0 text-[11.5px] tabular-nums', on ? 'text-foreground' : 'text-muted-foreground')}>+ {percents[i]}%+ </span>+ </>+ );+ const className = 'group/value relative flex h-[17px] w-full items-center justify-between gap-2 rounded-[5px] px-1.5 text-left text-xs';+ return onToggleValue ? (+ <button+ key={i}+ type="button"+ className={cn(className, 'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring')}+ title={`${valueRenderer(value) || t('empty_value')} · ${formatCount(count)}`}+ aria-label={`${valueRenderer(value) || t('empty_value')}, ${percents[i]}%`}+ aria-pressed={on}+ onClick={() => onToggleValue(value)}+ >+ {content}+ </button>+ ) : (+ <div key={i} className={className} title={`${valueRenderer(value) || t('empty_value')} · ${formatCount(count)}`}>+ {content}</div>- )}- </>- )}- {!showsTops && (- <>- <div className="text-lg">{meta.distinctTotal}</div>- <div>unique values</div>- </>- )}+ );+ })}+ {otherValues > 0 && (+ <div className="relative flex h-[17px] w-full items-center justify-between gap-2 rounded-[5px] px-1.5 text-xs">+ <span+ className="absolute inset-y-0 left-0 rounded-[5px] bg-muted-foreground/[0.13]"+ style={{ width: `${(otherCount * 100) / meta.total}%` }}+ />+ <span className="relative min-w-0 truncate text-muted-foreground">{t('other', { count: otherValues })}</span>+ <span className="relative shrink-0 text-[11.5px] tabular-nums text-muted-foreground">{percents[percents.length - 1]}%</span>+ </div>+ )}+ </div>+ <Caption>{t('unique_count', { count: meta.distinctTotal, value: formatCount(meta.distinctTotal) })}</Caption></div>);}-const formatter = format('~s');+function binIsOn(bin: IQuantitativeProfileBin, rule?: IFilterRule | null) {+ if (rule?.type !== 'range' || bin.count === 0) return false;+ const lo = rule.value[0] ?? -Infinity;+ const hi = rule.value[1] ?? Infinity;+ return (bin.min ?? bin.from) <= hi && (bin.max ?? bin.to) >= lo;+}++function QuantitativeProfiling({ computation, field, analyticType, rule, onSelectRange }: FieldProfilingProps & ProfilingInteractionProps) {+ const { t } = useTranslation('translation', { keyPrefix: 'data_table' });+ const { data: stat, loading } = useProfile(() => profileQuantitativeField(wrapComputationWithTag(computation, 'profiling'), field), [computation, field]);-function QuantitativeProfiling({ computation, field }: FieldProfilingProps) {- const [stat, setStat] = useState<Awaited<ReturnType<typeof profileQuantitativeField>>>();- useEffect(() => {- profileQuantitativeField(wrapComputationWithTag(computation, "profiling"), field).then(setStat);- }, [computation, field]);if (!isNotEmpty(stat)) {- return <div className="h-24 flex items-center justify-center">Loading...</div>;+ return (+ <>+ <Skeleton kind="quantitative" />+ <Caption />+ </>+ );+ }+ if (stat.total === 0 || stat.binValues.length === 0) {+ return (+ <>+ <div className={cn(CHART_HEIGHT, 'flex items-center text-muted-foreground')}>—</div>+ <Caption />+ </>+ );}if (stat.min === stat.max) {- return <div className="h-24 flex items-center justify-center text-xl">= {stat.min}</div>;+ return (+ <>+ <Constant>{formatNumber(stat.min)}</Constant>+ <Caption>{t('avg', { value: formatApprox(stat.mean) })}</Caption>+ </>+ );}++ const peak = Math.max(...stat.binValues.map((b) => b.count));+ const hasSelection = rule?.type === 'range';+ const accent = ACCENT[analyticType];+ const lastIndex = stat.binValues.length - 1;+return (- <div className="h-24 w-full flex flex-col space-y-1">- <BinRenderer data={stat} />- <div className="flex justify-between w-full text-xs font-medium leading-none">- <div>{formatter(stat.min)}</div>- <div>{formatter(stat.max)}</div>+ <div className={cn('transition-opacity', loading && 'opacity-50')}>+ <div className={CHART_HEIGHT}>+ <div className="flex h-10 items-end gap-0.5 border-b">+ {stat.binValues.map((bin, i) => {+ const on = binIsOn(bin, rule);+ const lo = bin.min ?? bin.from;+ const hi = bin.max ?? bin.to;+ const label = `${formatNumber(bin.from)} – ${formatNumber(bin.to)}`;+ const interactive = onSelectRange && bin.count > 0;+ return (+ <button+ key={i}+ type="button"+ disabled={!interactive}+ aria-label={`${label}: ${t('row_count', { count: bin.count, value: formatCount(bin.count) })}`}+ aria-pressed={interactive ? on : undefined}+ className="group/bin relative flex h-full min-w-0 flex-1 items-end focus-visible:outline-none enabled:cursor-pointer disabled:cursor-default"+ onClick={(e) => onSelectRange?.([lo, hi], e.shiftKey)}+ >+ <span+ className={cn(+ 'w-full rounded-t-[3px] transition-opacity',+ accent.bar,+ hasSelection+ ? on+ ? 'opacity-100'+ : 'opacity-25'+ : 'opacity-80 group-hover/bin:opacity-100 group-focus-visible/bin:opacity-100'+ )}+ style={{ height: bin.count ? `${Math.max(4, (bin.count / peak) * 100)}%` : 0 }}+ />+ <span+ className={cn(+ 'pointer-events-none absolute bottom-[calc(100%+6px)] z-20 flex items-baseline gap-1.5 whitespace-nowrap rounded-md border bg-popover px-2 py-1 text-[11.5px] leading-4 text-popover-foreground opacity-0 shadow-md transition-opacity group-hover/bin:opacity-100 group-focus-visible/bin:opacity-100',+ i < 2 ? 'left-0' : i > lastIndex - 2 ? 'right-0' : 'left-1/2 -translate-x-1/2'+ )}+ >+ <b className="font-semibold tabular-nums">{label}</b>+ <span className="tabular-nums text-muted-foreground">+ {t('row_count', { count: bin.count, value: formatCount(bin.count) })}+ </span>+ </span>+ </button>+ );+ })}+ </div>+ <div className="mt-[5px] flex justify-between text-[11px] leading-3 tabular-nums text-muted-foreground">+ <span>{formatNumber(stat.min)}</span>+ <span>{formatNumber(stat.max)}</span>+ </div></div>+ <Caption>{t('avg', { value: formatApprox(stat.mean) })}</Caption></div>);}-function BinRenderer({ data }: { data: Awaited<ReturnType<typeof profileQuantitativeField>> }) {- const mediaTheme = useContext(themeContext);- const { vizThemeConfig } = useContext(vegaThemeContext);-- const theme = getTheme({- mediaTheme,- vizThemeConfig,- });-- const vegaConfig = useMemo(() => {- const config: any = {- ...theme,- background: 'transparent',- };- return config;- }, [theme]);-- const ref = useCallback(- (node: HTMLDivElement) => {- if (!node) {- return;- }- const { width } = node.getBoundingClientRect();- const spec = {- width: width - 10,- height: 70,- autosize: 'fit',- data: {- values: data.binValues.map(({ from, to, count }) => ({- value: `${formatter(from)} - ${formatter(to)}`,- sort: from,- count,- })),- },- mark: { type: 'bar', opacity: 0.96, tooltip: { content: 'data' } },- encoding: {- x: {- field: 'value',- type: 'ordinal',- sort: { op: 'sum', field: 'sort' },- axis: false,- },- y: {- field: 'count',- type: 'quantitative',- axis: false,- },- tooltip: [- { field: 'value', type: 'ordinal', title: 'Value' },- { field: 'count', type: 'quantitative', title: 'Count' },- ],- },- config: { view: { stroke: null } },- };- embed(node, spec as unknown as VisualizationSpec, {- renderer: 'canvas',- mode: 'vega-lite',- actions: false,- config: vegaConfig,- tooltip: {- theme: mediaTheme,- },- });- },- [data, vegaConfig]- );- return <div ref={ref} />;-}-function LazyLoaded<T>(Component: ComponentType<T>) {return function (props: T & { key?: React.Key }) {const [loaded, setLoaded] = useState(false);@@ -200,7 +379,9 @@ function LazyLoaded<T>(Component: ComponentType<T>) {};}-function FieldProfilingElement(props: FieldProfilingProps & { semanticType: ISemanticType; displayOffset?: number; offset?: number }) {+function FieldProfilingElement(+ props: FieldProfilingProps & ProfilingInteractionProps & { semanticType: ISemanticType; displayOffset?: number; offset?: number }+) {const { semanticType, displayOffset, offset, ...fieldProps } = props;switch (semanticType) {case 'nominal':@@ -208,7 +389,8 @@ function FieldProfilingElement(props: FieldProfilingProps & { semanticType: ISemreturn <NominalProfiling {...fieldProps} />;case 'temporal': {const formatter = (date: string | number) => formatDate(parsedOffsetDate(displayOffset, offset)(date));- return <NominalProfiling {...fieldProps} valueRenderer={formatter} />;+ // temporal filters are edited as ranges, so picking single dates from the profile is not offered+ return <NominalProfiling {...fieldProps} onToggleValue={undefined} valueRenderer={formatter} />;}case 'quantitative':return <QuantitativeProfiling {...fieldProps} />;diff --git a/packages/graphic-walker/src/computation/index.ts b/packages/graphic-walker/src/computation/index.tsindex ffa10b5e..18574d93 100644--- a/packages/graphic-walker/src/computation/index.ts+++ b/packages/graphic-walker/src/computation/index.ts@@ -532,15 +532,28 @@ export async function getFieldDistinctCounts(}export async function profileNonmialField(service: IComputationFunction, field: string) {- const TOPS_NUM = 2;+ const TOPS_NUM = 3;const meta = getFieldDistinctMeta(service, field);const tops = getFieldDistinctCounts(service, field, { sortBy: 'count_dsc', valuesLimit: TOPS_NUM });return Promise.all([meta, tops] as const);}+export interface IQuantitativeProfileBin {+ from: number;+ to: number;+ count: number;+ /** smallest value inside the bin, only present for non-empty bins */+ min?: number;+ /** largest value inside the bin, only present for non-empty bins */+ max?: number;+}+export async function profileQuantitativeField(service: IComputationFunction, field: string) {const BIN_FIELD = `bin_${field}`;const ROW_NUM_FIELD = `${COUNT_FIELD_ID}_sum`;+ const MIN_FIELD = `min_${field}`;+ const MAX_FIELD = `max_${field}`;+ const SUM_FIELD = `sum_${field}`;const BIN_SIZE = 10;const workflow: IDataQueryWorkflowStep[] = [@@ -583,6 +596,21 @@ export async function profileQuantitativeField(service: IComputationFunction, fiagg: 'sum',asFieldKey: ROW_NUM_FIELD,},+ {+ field,+ agg: 'min',+ asFieldKey: MIN_FIELD,+ },+ {+ field,+ agg: 'max',+ asFieldKey: MAX_FIELD,+ },+ {+ field,+ agg: 'sum',+ asFieldKey: SUM_FIELD,+ },],},],@@ -595,15 +623,23 @@ export async function profileQuantitativeField(service: IComputationFunction, fireturn {max: 0,min: 0,- binValues: [],+ total: 0,+ mean: 0,+ binValues: [] as IQuantitativeProfileBin[],};}+ let total = 0;+ let sum = 0;+ for (const row of values) {+ total += Number(row[ROW_NUM_FIELD]) || 0;+ sum += Number(row[SUM_FIELD]) || 0;+ }const min = values[0][BIN_FIELD][0];const max = values[values.length - 1][BIN_FIELD][1];const step = (max - min) / BIN_SIZE;const binValues = range(0, BIN_SIZE).map((x) => x * step + min)- .map((bin) => {+ .map((bin): IQuantitativeProfileBin => {const row = binarySearchClosest(values, bin, (row) => row[BIN_FIELD][0]);const binValue = row[BIN_FIELD][0] as number;if (Math.abs(binValue - bin) * 2 < step) {@@ -613,6 +649,8 @@ export async function profileQuantitativeField(service: IComputationFunction, fifrom: bin,to: bin + step,count,+ min: Number(row[MIN_FIELD]),+ max: Number(row[MAX_FIELD]),};} else {// not found@@ -626,6 +664,8 @@ export async function profileQuantitativeField(service: IComputationFunction, fireturn {min,max,+ total,+ mean: total ? sum / total : 0,binValues,};}diff --git a/packages/graphic-walker/src/dataSource/table.tsx b/packages/graphic-walker/src/dataSource/table.tsxindex fffd1295..8e790a51 100644--- a/packages/graphic-walker/src/dataSource/table.tsx+++ b/packages/graphic-walker/src/dataSource/table.tsx@@ -18,7 +18,7 @@ const Table: React.FC<TableProps> = ({ commonStore, size = 10 }) => {const computation = React.useMemo(() => getComputation(tmpDataSource), [tmpDataSource]);return (- <div className="rounded border">+ <div><DataTablesize={size}metas={metas}diff --git a/packages/graphic-walker/src/locales/en-US.json b/packages/graphic-walker/src/locales/en-US.jsonindex b85be45a..efbec6f6 100644--- a/packages/graphic-walker/src/locales/en-US.json+++ b/packages/graphic-walker/src/locales/en-US.json@@ -494,5 +494,35 @@"need_lon_lat": "Needs longitude & latitude fields","need_geo_feature": "Needs a configured GeoJSON boundary"}+ },+ "data_table": {+ "rows_one": "<b>{{value}}</b> row",+ "rows_other": "<b>{{value}}</b> rows",+ "rows_filtered": "<b>{{value}}</b> of {{total}} rows",+ "columns_one": "<b>{{value}}</b> column",+ "columns_other": "<b>{{value}}</b> columns",+ "range": "<b>{{from}}–{{to}}</b> of {{total}}",+ "clear": "Clear",+ "clear_filters": "Clear filters",+ "no_rows": "No data",+ "no_matching_rows": "No rows match the current filters",+ "remove_filter": "Remove filter on {{name}}",+ "n_values_one": "{{count}} value",+ "n_values_other": "{{count}} values",+ "semantic_type": "Semantic type",+ "column_options": "Column options for {{name}}",+ "sort_asc": "Sort ascending",+ "sort_desc": "Sort descending",+ "clear_sort": "Clear sort",+ "filter": "Filter…",+ "clear_filter": "Clear filter",+ "empty_value": "(Empty)",+ "unique_count": "{{value}} unique",+ "unique_values": "unique values",+ "distinct_ratio": "{{percent}}% distinct",+ "other": "Other ({{count}})",+ "avg": "avg {{value}}",+ "row_count_one": "{{value}} row",+ "row_count_other": "{{value}} rows"}}diff --git a/packages/graphic-walker/src/locales/ja-JP.json b/packages/graphic-walker/src/locales/ja-JP.jsonindex a5ae49f5..a19de6f8 100644--- a/packages/graphic-walker/src/locales/ja-JP.json+++ b/packages/graphic-walker/src/locales/ja-JP.json@@ -487,5 +487,31 @@"need_lon_lat": "経度・緯度フィールドが必要です","need_geo_feature": "GeoJSON 境界の設定が必要です"}+ },+ "data_table": {+ "rows_other": "<b>{{value}}</b> 行",+ "rows_filtered": "<b>{{value}}</b> / {{total}} 行",+ "columns_other": "<b>{{value}}</b> 列",+ "range": "<b>{{from}}–{{to}}</b> 行目 / 全 {{total}} 行",+ "clear": "クリア",+ "clear_filters": "フィルターをクリア",+ "no_rows": "データがありません",+ "no_matching_rows": "現在のフィルターに一致する行はありません",+ "remove_filter": "{{name}} のフィルターを削除",+ "n_values_other": "{{count}} 個の値",+ "semantic_type": "セマンティックタイプ",+ "column_options": "{{name}} 列のオプション",+ "sort_asc": "昇順に並べ替える",+ "sort_desc": "降順に並べ替える",+ "clear_sort": "並べ替えを解除",+ "filter": "フィルター…",+ "clear_filter": "フィルターを解除",+ "empty_value": "(空)",+ "unique_count": "ユニーク値 {{value}}",+ "unique_values": "ユニーク値",+ "distinct_ratio": "{{percent}}% がユニーク",+ "other": "その他 ({{count}})",+ "avg": "平均 {{value}}",+ "row_count_other": "{{value}} 行"}}diff --git a/packages/graphic-walker/src/locales/zh-CN.json b/packages/graphic-walker/src/locales/zh-CN.jsonindex 40edec23..a6581f83 100644--- a/packages/graphic-walker/src/locales/zh-CN.json+++ b/packages/graphic-walker/src/locales/zh-CN.json@@ -493,5 +493,31 @@"need_lon_lat": "需要经度和纬度字段","need_geo_feature": "需要先配置 GeoJSON 边界"}+ },+ "data_table": {+ "rows_other": "<b>{{value}}</b> 行",+ "rows_filtered": "<b>{{value}}</b> / {{total}} 行",+ "columns_other": "<b>{{value}}</b> 列",+ "range": "第 <b>{{from}}–{{to}}</b> 行,共 {{total}} 行",+ "clear": "清除",+ "clear_filters": "清除筛选",+ "no_rows": "暂无数据",+ "no_matching_rows": "没有符合当前筛选条件的数据",+ "remove_filter": "移除 {{name}} 的筛选",+ "n_values_other": "{{count}} 个值",+ "semantic_type": "语义类型",+ "column_options": "{{name}} 列选项",+ "sort_asc": "升序排序",+ "sort_desc": "降序排序",+ "clear_sort": "取消排序",+ "filter": "筛选…",+ "clear_filter": "清除筛选",+ "empty_value": "(空)",+ "unique_count": "{{value}} 个唯一值",+ "unique_values": "个唯一值",+ "distinct_ratio": "{{percent}}% 的值互不相同",+ "other": "其他 ({{count}})",+ "avg": "均值 {{value}}",+ "row_count_other": "{{value}} 行"}}diff --git a/packages/graphic-walker/tailwind.config.js b/packages/graphic-walker/tailwind.config.jsindex 53512064..30658c94 100644--- a/packages/graphic-walker/tailwind.config.js+++ b/packages/graphic-walker/tailwind.config.js@@ -70,9 +70,9 @@ module.exports = {filter: {darkmap: 'var(--map-tiles-filter)',},- },- minWidth: {- 96: '96px',+ minWidth: {+ 96: '96px',+ },},},darkMode: 'class', // or 'media' or 'classdiff --git a/packages/graphic-walker/tests/e2e/issue-501-shadow-overlays.spec.ts b/packages/graphic-walker/tests/e2e/issue-501-shadow-overlays.spec.tsindex 6cb028bf..ac4d8931 100644--- a/packages/graphic-walker/tests/e2e/issue-501-shadow-overlays.spec.ts+++ b/packages/graphic-walker/tests/e2e/issue-501-shadow-overlays.spec.ts@@ -18,7 +18,7 @@ for (const scale of [1, 0.8]) {document.querySelector<HTMLElement>('#host-scroll')!.scrollTo(48, 72);});- const semanticTypeTrigger = shadowHost.locator('thead span.cursor-pointer').first();+ const semanticTypeTrigger = shadowHost.getByTestId('data-table-semantic-type').first();await semanticTypeTrigger.click();const menu = page.getByRole('menu');diff --git a/packages/graphic-walker/tests/e2e/issue-501.helpers.ts b/packages/graphic-walker/tests/e2e/issue-501.helpers.tsindex 871410ad..d6aff86c 100644--- a/packages/graphic-walker/tests/e2e/issue-501.helpers.ts+++ b/packages/graphic-walker/tests/e2e/issue-501.helpers.ts@@ -49,9 +49,10 @@ export async function selectTab(page: Page, name: string) {}export async function openFilterDialog(page: Page, shadowHost: Locator) {- const header = shadowHost.locator('thead th').first();+ const header = shadowHost.locator('thead th[aria-sort]').first();await header.hover();- await header.locator('div.group > div').last().click();+ await header.getByTestId('data-table-column-menu').click();+ await page.getByTestId('data-table-filter').click();const dialog = page.getByRole('dialog');await expect(dialog).toBeVisible();await waitForAnimations(dialog);