Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
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
26 changes: 26 additions & 0 deletions src/components/HTMLEngineProvider/BaseHTMLEngineProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,32 @@ function BaseHTMLEngineProvider({textSelectable = false, children, enableExperim
tagName: 'sparkles-icon',
contentModel: HTMLContentModel.mixed,
}),
table: HTMLElementModel.fromCustomModel({
tagName: 'table',
contentModel: HTMLContentModel.block,
}),
thead: HTMLElementModel.fromCustomModel({
tagName: 'thead',
contentModel: HTMLContentModel.block,
}),
tbody: HTMLElementModel.fromCustomModel({
tagName: 'tbody',
contentModel: HTMLContentModel.block,
}),
tr: HTMLElementModel.fromCustomModel({
tagName: 'tr',
contentModel: HTMLContentModel.block,
}),
th: HTMLElementModel.fromCustomModel({
tagName: 'th',
contentModel: HTMLContentModel.block,
mixedUAStyles: styles.htmlTableHeaderCellText,
}),
td: HTMLElementModel.fromCustomModel({
tagName: 'td',
contentModel: HTMLContentModel.block,
mixedUAStyles: styles.htmlTableCellText,
}),
...VICTORY_HTML_ELEMENT_MODELS,
};
/* eslint-enable @typescript-eslint/naming-convention */
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import useThemeStyles from '@hooks/useThemeStyles';

import {useMemo} from 'react';
import {View} from 'react-native';
import {Gesture, GestureDetector} from 'react-native-gesture-handler';
import Animated, {cancelAnimation, useAnimatedStyle, useSharedValue, withDecay} from 'react-native-reanimated';

import type HTMLTableScrollProps from './types';

/**
* Native horizontal scroller for HTML tables. A plain ScrollView rendered inside react-native-render-html never wins the
* pan on native, and a gesture-handler ScrollView can only ever claim one axis (blocking the chat's vertical scroll).
* This custom pan scrolls the table horizontally while activeOffsetX/failOffsetY let vertical drags fall through to the
* chat's vertical scroll.
*/
function HTMLTableScroll({viewportWidth, contentWidth, children}: HTMLTableScrollProps) {
const styles = useThemeStyles();
const maxScroll = Math.max(0, contentWidth - viewportWidth);

const translateX = useSharedValue(0);
const panGesture = useMemo(
() =>
Gesture.Pan()
.activeOffsetX([-10, 10])
.failOffsetY([-10, 10])
.onBegin(() => {
cancelAnimation(translateX);
})
.onChange((event) => {
translateX.set(Math.min(0, Math.max(-maxScroll, translateX.get() + event.changeX)));
})
.onEnd((event) => {
translateX.set(withDecay({velocity: event.velocityX, clamp: [-maxScroll, 0]}));
}),
[maxScroll, translateX],
);

const animatedStyle = useAnimatedStyle(() => ({transform: [{translateX: translateX.get()}]}));

return (
<View style={[styles.htmlTable, {width: viewportWidth}]}>
<GestureDetector gesture={panGesture}>
<Animated.View style={[{width: contentWidth}, animatedStyle]}>{children}</Animated.View>
</GestureDetector>
</View>
);
}

export default HTMLTableScroll;
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import ScrollView from '@components/ScrollView';

import useThemeStyles from '@hooks/useThemeStyles';

import {View} from 'react-native';

import type HTMLTableScrollProps from './types';

/**
* Web/default horizontal scroller for HTML tables. A plain ScrollView scrolls fine here because web is not affected by
* the native responder issue that requires the custom pan gesture in the native variant. The rows are wrapped in a
* column View because a horizontal ScrollView's content container lays its children out in a row by default.
*/
function HTMLTableScroll({viewportWidth, contentWidth, children}: HTMLTableScrollProps) {
const styles = useThemeStyles();

return (
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
style={{width: viewportWidth}}
>
<View style={[styles.htmlTable, {width: contentWidth}]}>{children}</View>
</ScrollView>
);
}

export default HTMLTableScroll;
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type {ReactNode} from 'react';

type HTMLTableScrollProps = {
/** Width of the visible scroll viewport, i.e. the available message width. */
viewportWidth: number;

/** Full width of the table content; at least the viewport width. */
contentWidth: number;

/** The rendered table rows. */
children: ReactNode;
};

export default HTMLTableScrollProps;
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import Text from '@components/Text';

import useThemeStyles from '@hooks/useThemeStyles';

import type {CustomRendererProps, TBlock} from 'react-native-render-html';

import {useContext} from 'react';
import {View} from 'react-native';
import {TNodeChildrenRenderer} from 'react-native-render-html';

import type {CellHorizontalAlignment} from './TableColumnAlignmentContext';

import {getElementChildren} from './TableChildrenRenderer';
import TableColumnAlignmentContext from './TableColumnAlignmentContext';

/** Reads an explicit `text-align` from the cell's inline style, if the HTML happens to carry one. */
function getExplicitCellAlignment(styleAttribute: string | undefined): CellHorizontalAlignment | undefined {
if (styleAttribute?.includes('text-align: right')) {
return 'right';
}
if (styleAttribute?.includes('text-align: center')) {
return 'center';
}
if (styleAttribute?.includes('text-align: left')) {
return 'left';
}
return undefined;
}

function TableCellRenderer({tnode}: CustomRendererProps<TBlock>) {
const styles = useThemeStyles();
const columnAlignments = useContext(TableColumnAlignmentContext);
const isHeaderCell = tnode.tagName === 'th';

// An explicit style wins; otherwise fall back to the column alignment derived by the table renderer.
// Guard the index so an unexpected -1 (cell without a parent row) does not wrap around to the last column.
const columnIndex = getElementChildren(tnode.parent).indexOf(tnode);
const columnAlignment = columnIndex >= 0 ? columnAlignments.at(columnIndex) : undefined;
const alignment = getExplicitCellAlignment(tnode.attributes.style) ?? columnAlignment ?? 'left';
const isRightAligned = alignment === 'right';

// Map the cell alignment to the shared named styles instead of building inline style objects.
const cellAlignmentStyle = {
left: styles.alignItemsStart,
center: styles.alignItemsCenter,
right: styles.alignItemsEnd,
}[alignment];
const textAlignmentStyle = {
left: styles.textAlignLeft,
center: styles.textAlignCenter,
right: styles.textAlignRight,
}[alignment];

return (
Comment thread
dukenv0307 marked this conversation as resolved.
Resolved
<View style={[styles.htmlTableCell, !isRightAligned && styles.htmlTableCellMaxWidth, cellAlignmentStyle]}>
<Text
numberOfLines={1}
style={[isHeaderCell ? styles.htmlTableHeaderCellText : styles.htmlTableCellText, styles.w100, textAlignmentStyle]}
>
<TNodeChildrenRenderer tnode={tnode} />
</Text>
</View>
);
}

export default TableCellRenderer;
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type {TNode} from 'react-native-render-html';

import {TNodeRenderer} from 'react-native-render-html';

/** Element (non-whitespace) children of a node, skipping whitespace-only text nodes that sit between block elements in the source HTML. */
function getElementChildren(node: TNode | null | undefined): TNode[] {
return node?.children?.filter((child) => !!child.tagName) ?? [];
}

/**
* Renders the element children of a table-related node through `TNodeRenderer`, skipping whitespace-only text nodes.
* Shared by the table, section and row renderers so the filter-and-render logic lives in a single place.
*/
function TableChildrenRenderer({tnode}: {tnode: TNode}) {
const children = getElementChildren(tnode);
return (
<>
{children.map((child, index) => (
<TNodeRenderer
key={`${child.tagName ?? 'node'}-${child.nodeIndex}`}
tnode={child}
renderIndex={index}
renderLength={children.length}
/>
))}
</>
);
}

export default TableChildrenRenderer;
export {getElementChildren};
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {createContext} from 'react';

type CellHorizontalAlignment = 'left' | 'center' | 'right';

/**
* Per-column horizontal alignment for the table currently being rendered, indexed by column position.
* The Concierge HTML never carries alignment attributes, so `TableRenderer` derives it from the cell
* contents and shares it here so both the header cell and the body cells of a column stay in sync.
*/
const TableColumnAlignmentContext = createContext<CellHorizontalAlignment[]>([]);

export default TableColumnAlignmentContext;
export type {CellHorizontalAlignment};
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import {createContext} from 'react';

/**
* The width available to the HTML content, measured at the comment level (above react-native-render-html's per-block
* wrappers). `TableRenderer` uses it to fill the message width, because the block wrappers shrink-wrap to their content
* and a width measured inside them collapses to the table's own content width instead of the available space.
*/
const TableContentWidthContext = createContext<number>(0);

export default TableContentWidthContext;
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import variables from '@styles/variables';

import type {CustomRendererProps, TBlock, TNode} from 'react-native-render-html';

import {useContext, useMemo} from 'react';
import {useContentWidth} from 'react-native-render-html';

import type {CellHorizontalAlignment} from './TableColumnAlignmentContext';

import HTMLTableScroll from './HTMLTableScroll';
import TableChildrenRenderer, {getElementChildren} from './TableChildrenRenderer';
import TableColumnAlignmentContext from './TableColumnAlignmentContext';
import TableContentWidthContext from './TableContentWidthContext';

/**
* Derives the horizontal alignment for each column from the table body. Concierge expense tables put the amount in
* the last column and carry no alignment attributes, so the last column is right-aligned to match how amounts are
* shown elsewhere in the app; every other column stays left-aligned.
*/
function getColumnAlignments(tableNode: TNode): CellHorizontalAlignment[] {
const bodyRows = getElementChildren(tableNode)
.filter((section) => section.tagName === 'tbody')
.flatMap((section) => getElementChildren(section));
if (bodyRows.length === 0) {
return [];
}

const columnCount = bodyRows.reduce((max, row) => Math.max(max, getElementChildren(row).length), 0);
return Array.from({length: columnCount}, (_, columnIndex) => (columnIndex === columnCount - 1 ? 'right' : 'left'));
}

function TableRenderer({tnode}: CustomRendererProps<TBlock>) {
const columnAlignments = useMemo(() => getColumnAlignments(tnode), [tnode]);

// The comment-level width fills the message exactly; fall back to the HTML content width when the table is rendered
// outside a comment. A concrete number is required because the scroller needs a fixed viewport and content width.
const measuredContentWidth = useContext(TableContentWidthContext);
const fallbackContentWidth = useContentWidth();
const viewportWidth = measuredContentWidth || fallbackContentWidth;
const columnsWidth = columnAlignments.length * variables.htmlTableColumnMaxWidth + 2 * variables.tableRowPaddingHorizontal;
const contentWidth = Math.max(viewportWidth, columnsWidth);

return (
<TableColumnAlignmentContext.Provider value={columnAlignments}>
<HTMLTableScroll
viewportWidth={viewportWidth}
contentWidth={contentWidth}
>
<TableChildrenRenderer tnode={tnode} />
</HTMLTableScroll>
</TableColumnAlignmentContext.Provider>
);
}

export default TableRenderer;
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import useThemeStyles from '@hooks/useThemeStyles';

import type {CustomRendererProps, TBlock, TNode} from 'react-native-render-html';

import {View} from 'react-native';

import TableChildrenRenderer, {getElementChildren} from './TableChildrenRenderer';

function isLastRowOfTable(tnode: TNode): boolean {
const section = tnode.parent;
const table = section?.parent;
if (!section || !table) {
return false;
}
const sectionRows = getElementChildren(section);
const tableSections = getElementChildren(table);
return sectionRows.at(-1) === tnode && tableSections.at(-1) === section;
}

function TableRowRenderer({tnode}: CustomRendererProps<TBlock>) {
const styles = useThemeStyles();

// Header rows (inside <thead>) use header padding; body rows use the compact min-height.
const isHeaderRow = tnode.parent?.tagName === 'thead';

return (
<View style={[isHeaderRow ? styles.htmlTableHeaderRow : styles.htmlTableRow, isLastRowOfTable(tnode) && styles.htmlTableLastRow]}>
<TableChildrenRenderer tnode={tnode} />
</View>
);
}

export default TableRowRenderer;
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type {CustomRendererProps, TBlock} from 'react-native-render-html';

import TableChildrenRenderer from './TableChildrenRenderer';

/**
* Renders an HTML <thead>/<tbody> by rendering its <tr> children directly into the table
* container, without adding an extra wrapping view, so rows stack with no gaps.
*/
function TableSectionRenderer({tnode}: CustomRendererProps<TBlock>) {
return <TableChildrenRenderer tnode={tnode} />;
}

export default TableSectionRenderer;
10 changes: 10 additions & 0 deletions src/components/HTMLEngineProvider/HTMLRenderers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ import PreRenderer from './PreRenderer';
import RBRRenderer from './RBRRenderer';
import ShortMentionRenderer from './ShortMentionRenderer';
import SparklesIconRenderer from './SparklesIconRenderer';
import TableCellRenderer from './TableCellRenderer';
import TableRenderer from './TableRenderer';
import TableRowRenderer from './TableRowRenderer';
import TableSectionRenderer from './TableSectionRenderer';
import TaskTitleRenderer from './TaskTitleRenderer';
import TransactionHistoryLinkRenderer from './TransactionHistoryLinkRenderer';
import ULRenderer from './ULRenderer';
Expand All @@ -37,6 +41,12 @@ const HTMLEngineProviderComponentList: CustomTagRendererRecord = {
ol: OLRenderer,
ul: ULRenderer,
video: VideoRenderer,
table: TableRenderer,
thead: TableSectionRenderer,
tbody: TableSectionRenderer,
tr: TableRowRenderer,
th: TableCellRenderer,
td: TableCellRenderer,

// Custom tag renderers
edited: EditedRenderer,
Expand Down
Loading
Loading