Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import {
getMarkdownTableOptions,
parseMarkdownTable,
} from '@nemo/common/src/components/Chat/MessageContent/helpers';
import { MarkdownTableCell } from '@nemo/common/src/components/Chat/MessageContent/MarkdownTableCell';
import type {
MarkdownDataViewTableProps,
MarkdownTableRow,
} from '@nemo/common/src/components/Chat/MessageContent/types';
import * as DataView from '@nemo/common/src/components/DataView/internal';
import { type FC, type MouseEvent, useCallback, useMemo, useState } from 'react';

export const MarkdownDataViewTable: FC<MarkdownDataViewTableProps> = ({ children, options }) => {
const tableOptions = useMemo(() => getMarkdownTableOptions(options), [options]);
const { columns, rows } = useMemo(() => parseMarkdownTable(children), [children]);
const dataViewState = DataView.useDataViewState();
const [expandedRowIds, setExpandedRowIds] = useState<ReadonlySet<string>>(() => new Set());
const data = useMemo(
() => rows.map((row) => ({ ...row, expandedRowIds })),
[expandedRowIds, rows]
);
const toggleExpandedRow = useCallback((rowId: string) => {
setExpandedRowIds((current) => {
const next = new Set(current);
if (next.has(rowId)) {
next.delete(rowId);
} else {
next.add(rowId);
}
return next;
});
}, []);
const handleTableClick = useCallback(
(event: MouseEvent<HTMLTableElement>) => {
if (!tableOptions.expandableCells || !(event.target instanceof Element)) return;

const rowElement = event.target.closest('tbody tr[data-row-id]');
const rowId = rowElement?.getAttribute('data-row-id');
if (!rowId) return;

toggleExpandedRow(rowId);
},
[tableOptions.expandableCells, toggleExpandedRow]
);
const makeColumns = useMemo<DataView.MakeColumns<MarkdownTableRow>>(
() => (columnHelper) =>
columns.map((column, columnIndex) =>
columnHelper.accessor((row) => row.cellValues[columnIndex] ?? '', {
id: column.id,
header: () => column.header,
cell: ({ row }) => {
return (
<MarkdownTableCell
expanded={row.original.expandedRowIds?.has(row.original.id) ?? false}
expandable={tableOptions.expandableCells}
onToggle={() => toggleExpandedRow(row.original.id)}
>
{row.original.cells[columnIndex] ?? ''}
</MarkdownTableCell>
);
},
enableResizing: false,
enableSorting: true,
})
),
[columns, tableOptions, toggleExpandedRow]
);

if (!columns.length) return null;

return (
<DataView.Root
autoCellTooltips={false}
className="my-density-md min-w-0 max-w-full overflow-hidden [&>div]:min-h-0"
data={data}
dataMode="sort-filter-only"
makeColumns={makeColumns}
state={dataViewState}
totalCount={rows.length}
>
<DataView.Toolbar>
<DataView.SearchBar debounce={0} placeholder="Search table" />
</DataView.Toolbar>
<DataView.TableContent
className={`min-h-0 border-0 [&_.nv-table-head]:border-b-0 [&_.nv-table-row]:border-b-0 [&_thead_th>.data-view-header-control]:!max-w-none [&_.data-view-header-control>span]:!overflow-visible [&_.data-view-header-control>span]:!text-clip ${tableOptions.expandableCells ? '[&_tbody_tr]:cursor-pointer' : ''}`}
density="compact"
layout="auto"
onClick={handleTableClick}
stickyTableHeader={false}
/>
</DataView.Root>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import { Text } from '@nvidia/foundations-react-core';
import { type FC, type PropsWithChildren } from 'react';

export const MarkdownParagraph: FC<PropsWithChildren> = ({ children }) => (
<Text asChild kind="body/regular/md">
<p className="mb-density-xl text-sm leading-[160%] last:mb-0">{children}</p>
</Text>
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import { getNodeText } from '@nemo/common/src/components/Chat/MessageContent/helpers';
import type { MarkdownTableCellProps } from '@nemo/common/src/components/Chat/MessageContent/types';

export const MarkdownTableCell = ({
children,
expanded,
expandable,
onToggle,
}: MarkdownTableCellProps) => {
if (!expandable) {
return <span className="block whitespace-normal break-words">{children}</span>;
}

const text = getNodeText(children);

return (
<button
aria-label={text || undefined}
aria-expanded={expanded}
className="block w-full min-w-0 max-w-full cursor-pointer appearance-none overflow-hidden border-0 bg-transparent p-0 text-left font-inherit text-inherit"
onClick={(event) => {
event.stopPropagation();
onToggle();
}}
type="button"
>
<span
className={`min-w-0 max-w-full whitespace-normal break-words [&_span]:whitespace-normal ${
expanded ? 'block' : 'line-clamp-2'
}`}
data-collapsed={!expanded || undefined}
>
{children}
</span>
</button>
Comment thread
coderabbitai[bot] marked this conversation as resolved.
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import type { MarkdownTableOptions } from '@nemo/common/src/components/Chat/MessageContent/types';

export const INLINE_CODE_CLASS =
'rounded bg-gray-050 px-1 py-0.5 font-sans text-sm dark:bg-gray-800';

export const DEFAULT_MARKDOWN_TABLE_OPTIONS: Required<MarkdownTableOptions> = {
expandableCells: true,
};
100 changes: 100 additions & 0 deletions web/packages/common/src/components/Chat/MessageContent/helpers.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import { DEFAULT_MARKDOWN_TABLE_OPTIONS } from '@nemo/common/src/components/Chat/MessageContent/constants';
import { MarkdownParagraph } from '@nemo/common/src/components/Chat/MessageContent/MarkdownParagraph';
import type {
ElementWithChildrenProps,
MarkdownTableData,
MarkdownTableOptions,
} from '@nemo/common/src/components/Chat/MessageContent/types';
import { Text } from '@nvidia/foundations-react-core';
import { childrenToText } from '@nvidia/foundations-react-core/lib';
import { Children, isValidElement, type ReactElement, type ReactNode } from 'react';

export const isElementWithChildren = (
node: ReactNode
): node is ReactElement<ElementWithChildrenProps> => isValidElement<ElementWithChildrenProps>(node);

export const isElementNamed = (
node: ReactNode,
elementName: 'thead' | 'tbody' | 'tr' | 'th' | 'td' | 'p'
): node is ReactElement<ElementWithChildrenProps> =>
isElementWithChildren(node) && node.type === elementName;

export const getChildNodes = (node: ReactElement<ElementWithChildrenProps>): ReactNode[] =>
Children.toArray(node.props.children);

export const isWhitespaceTextNode = (node: ReactNode): node is string =>
typeof node === 'string' && node.trim().length === 0;

export const isMarkdownParagraphElement = (
node: ReactNode
): node is ReactElement<ElementWithChildrenProps> =>
isElementWithChildren(node) && (node.type === MarkdownParagraph || isElementNamed(node, 'p'));

export const renderListItemChildren = (children: ReactNode): ReactNode => {
const childNodes = Children.toArray(children);
const firstContentIndex = childNodes.findIndex((child) => !isWhitespaceTextNode(child));
const firstContent = childNodes[firstContentIndex];

if (firstContentIndex === -1 || !isMarkdownParagraphElement(firstContent)) {
return children;
}

return [
<Text asChild kind="body/regular/md" key="leading-list-paragraph">
<span className="text-sm leading-[160%]">{getChildNodes(firstContent)}</span>
</Text>,
...childNodes.slice(firstContentIndex + 1),
];
};

export const getRowCells = (row: ReactElement<ElementWithChildrenProps>): readonly ReactNode[] =>
getChildNodes(row)
.filter((cell) => isElementNamed(cell, 'th') || isElementNamed(cell, 'td'))
.map((cell) => cell.props.children ?? '');

export const getSectionRows = (
section: ReactElement<ElementWithChildrenProps> | undefined
): readonly (readonly ReactNode[])[] => {
if (!section) return [];

return getChildNodes(section)
.filter((child) => isElementNamed(child, 'tr'))
.map(getRowCells);
};

export const getNodeText = (node: ReactNode): string => childrenToText(node).trim();

export const getMarkdownTableOptions = (
options: MarkdownTableOptions | undefined
): Required<MarkdownTableOptions> => ({
...DEFAULT_MARKDOWN_TABLE_OPTIONS,
...options,
});

export const parseMarkdownTable = (children: ReactNode): MarkdownTableData => {
const tableChildren = Children.toArray(children);
const head = tableChildren.find((child) => isElementNamed(child, 'thead'));
const bodies = tableChildren.filter((child) => isElementNamed(child, 'tbody'));
const headerRows = getSectionRows(head);
const bodyRows = bodies.flatMap(getSectionRows);
const headerCells = headerRows[0] ?? bodyRows[0] ?? [];
const dataRows = headerRows.length > 0 ? bodyRows : bodyRows.slice(1);
const columnCount = Math.max(headerCells.length, ...dataRows.map((row) => row.length));

return {
columns: Array.from({ length: columnCount }, (_, index) => ({
id: `column-${index}`,
header: headerCells[index] ?? `Column ${index + 1}`,
})),
rows: dataRows.map((cells, rowIndex) => ({
id: `row-${rowIndex}`,
cells: Array.from({ length: columnCount }, (_, cellIndex) => cells[cellIndex] ?? ''),
cellValues: Array.from({ length: columnCount }, (_, cellIndex) =>
getNodeText(cells[cellIndex] ?? '')
),
})),
};
};
Loading
Loading