Skip to content
Closed
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
39 changes: 39 additions & 0 deletions docs-md/API_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,45 @@ Setting this callback makes plain text interactive on the native side; leaving i
| ------------------------------------- | ------------- | -------- |
| `(event: TextPressEvent) => void` | - | Both |

### `highlights`

Ranges of the rendered text to paint behind the glyphs, such as the sentence and the word a text-to-speech engine reads. Each entry has `start` and `end` (UTF-16 offsets into the text that [`onRenderedTextChange`](#onrenderedtextchange) reports), a `color`, and an optional `borderRadius` and `padding` for each line's box. Later entries paint over earlier ones, so a paragraph tint followed by a word tint shows the word on top.

Highlights are drawn, not added to the text: selection, copy, measuring and accessibility do not change, and a change of `highlights` does not render the Markdown again. Use translucent colors so the selection shows through. With `flavor="github"`, a code block or table is tinted as a whole. `PlatformColor` and `DynamicColorIOS` are not supported.

| Type | Default Value | Platform |
| --------------------------------- | ------------- | -------- |
| `ReadonlyArray<TextHighlight>` | - | Both |

```tsx
<EnrichedMarkdownText
markdown={markdown}
flavor="github"
onRenderedTextChange={({ text }) => setRendered(text)}
highlights={[
{ start: sentence.start, end: sentence.end, color: 'rgba(255, 204, 0, 0.2)' },
{ start: word.start, end: word.end, color: 'rgba(255, 149, 0, 0.45)', borderRadius: 4 },
]}
onHighlightLayout={({ highlights }) => scrollIntoView(highlights[1])}
/>
```

### `onRenderedTextChange`

Callback after each render with `text`, the text as the view shows it, and `blocks`, the part of it each block shows (`start`, `end`, and `kind`: `text`, `code` or `table`). Blocks are joined with `\n`; a table's cells are joined with tabs and its rows with newlines. `highlights` offsets index into `text`. It differs from the Markdown source and can differ between iOS and Android, so read it on each platform rather than computing it. With `flavor="commonmark"` there is one block, and `onTextPress` indexes into the same text; with `flavor="github"`, add the block's `start` to the `onTextPress` index.

| Type | Default Value | Platform |
| -------------------------------------------- | ------------- | -------- |
| `(event: RenderedTextChangeEvent) => void` | - | Both |

### `onHighlightLayout`

Callback when a highlight's box moves: after `highlights` change, and when a render or a new width moves the text. Receives `highlights`, one `{ index, x, y, width, height }` for each highlight that shows, where `index` is its position in `highlights` and the rect bounds all its lines in the component's coordinates. Use it to scroll the highlighted word into view.

| Type | Default Value | Platform |
| ----------------------------------------- | ------------- | -------- |
| `(event: HighlightLayoutEvent) => void` | - | Both |

### `onTaskListItemPress`

Callback when a task list checkbox is tapped. Receives `index` (0-based), `checked` (new state after toggling), and `text` (item text).
Expand Down
69 changes: 69 additions & 0 deletions docs/docs/react-native/api-reference/enriched-markdown-text.md
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,75 @@ interface TextPressEvent {
}
```

### `highlights`

Ranges of the rendered text to paint behind the glyphs, such as the sentence and the word a text-to-speech engine reads. Offsets are UTF-16 indices into the text that [`onRenderedTextChange`](#onrenderedtextchange) reports. Later entries paint over earlier ones, so a paragraph tint followed by a word tint shows the word on top.

- **Drawn, not styled:** selection, copy, measuring and accessibility do not change, and a change of `highlights` does not render the Markdown again, so moving a highlight word by word is cheap.
- **Colors:** use translucent colors so the selection shows through. `PlatformColor` and `DynamicColorIOS` are not supported.
- **Ignored entries:** an entry with an empty range or a color that is not supported draws nothing. It still counts, so the entries after it keep their index in [`onHighlightLayout`](#onhighlightlayout).
- **Code blocks and tables:** with `flavor="github"`, the whole block is tinted.
- **Renders:** a render keeps the offsets. When the text changes, map them again from the new `onRenderedTextChange` text.

<PropInfo type="ReadonlyArray<TextHighlight>" />

```ts
interface TextHighlight {
start: number; // UTF-16 offset in the rendered text
end: number; // exclusive
color: ColorValue;
borderRadius?: number; // of each line's box, default 0
padding?: number; // added around each line's box, default 0
}
```

```tsx
<EnrichedMarkdownText
markdown={markdown}
flavor="github"
onRenderedTextChange={({ text }) => setRendered(text)}
highlights={[
{ start: sentence.start, end: sentence.end, color: 'rgba(255, 204, 0, 0.2)' },
{ start: word.start, end: word.end, color: 'rgba(255, 149, 0, 0.45)', borderRadius: 4 },
]}
onHighlightLayout={({ highlights }) => scrollIntoView(highlights[1])}
/>
```

iOS and Android only.

### `onRenderedTextChange`

Callback fired with the text as the view shows it: once after the first render, then whenever a render changes that text or its blocks. A render that keeps both, such as `**Hello**` becoming `Hello`, does not fire it. The text is what [`highlights`](#highlights) offsets index into. It differs from the Markdown source (list markers, quotes and code fences are not in it) and can differ between iOS and Android, so read it on each platform rather than computing it. Blocks are joined with `\n`; a table's cells are joined with tabs and its rows with newlines.

With `flavor="commonmark"` there is one block, and [`onTextPress`](#ontextpress) indexes into the same text. With `flavor="github"`, `onTextPress` indexes into one block's text; add that block's `start`.

<PropInfo type="(event: RenderedTextChangeEvent) => void" />

```ts
interface RenderedTextChangeEvent {
text: string;
blocks: { start: number; end: number; kind: 'text' | 'code' | 'table' }[];
}
```

iOS and Android only.

### `onHighlightLayout`

Callback fired when a highlight's box moves: after [`highlights`](#highlights) change, and when a render or a new width moves the text. Each rect bounds all lines of its highlight, in the component's coordinates. Add the component's offset in a `ScrollView` to scroll the highlighted word into view.

<PropInfo type="(event: HighlightLayoutEvent) => void" />

```ts
interface HighlightLayoutEvent {
// One rect for each highlight that shows; `index` is its position in `highlights`.
highlights: { index: number; x: number; y: number; width: number; height: number }[];
}
```

iOS and Android only.

### `onTaskListItemPress`

Callback fired when a task list checkbox is tapped. The checkbox is toggled natively. Only fires when `flavor="github"`.
Expand Down
158 changes: 158 additions & 0 deletions packages/react-native-enriched-markdown/__tests__/highlights.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import { act } from 'react';
import type { ReactElement } from 'react';
import { createRoot } from 'test-renderer';
import type { Root, TestInstance } from 'test-renderer';
import { EnrichedMarkdownText } from '../src/native/EnrichedMarkdownText';
import type {
HighlightLayoutEvent,
RenderedTextChangeEvent,
} from '../src/types/events';
import type { TextHighlight } from '../src/types/MarkdownTextProps';

jest.mock('../src/EnrichedMarkdownNativeComponent', () => ({
__esModule: true,
default: 'EnrichedMarkdownNativeComponent',
}));

jest.mock('../src/EnrichedMarkdownTextNativeComponent', () => ({
__esModule: true,
default: 'EnrichedMarkdownTextNativeComponent',
}));

function renderNative(element: ReactElement): {
root: Root;
view: () => TestInstance;
} {
const root: Root = createRoot({
textComponentTypes: [
'EnrichedMarkdownNativeComponent',
'EnrichedMarkdownTextNativeComponent',
],
});
act(() => root.render(element));
const view = () => {
const [nativeView] = root.container.queryAll((instance) =>
String(instance.type).startsWith('EnrichedMarkdown')
);
if (!nativeView) throw new Error('Native markdown view was not rendered');
return nativeView;
};
return { root, view };
}

it('sends highlights with colors as signed 32-bit ARGB', () => {
const { view } = renderNative(
<EnrichedMarkdownText
markdown="Hello world"
highlights={[
{ start: 0, end: 5, color: '#FF0000' },
{ start: 6, end: 11, color: 'rgba(0, 0, 255, 0.5)', borderRadius: 4 },
]}
/>
);

expect(view().props.highlights).toEqual([
{ start: 0, end: 5, color: -65536, borderRadius: 0, padding: 0 },
{
start: 6,
end: 11,
color: 0x800000ff - 0x100000000,
borderRadius: 4,
padding: 0,
},
]);
});

it('sends an empty range for a highlight whose color cannot be processed', () => {
const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
const { view } = renderNative(
<EnrichedMarkdownText
markdown="Hello"
highlights={[
{ start: 0, end: 5, color: 'not-a-color' },
{ start: 1, end: 3, color: 'red' },
]}
/>
);

// The empty range draws nothing and keeps the next entry at index 1.
const highlights = view().props.highlights;
expect(highlights).toHaveLength(2);
expect(highlights[0]).toEqual({
start: 0,
end: 0,
color: 0,
borderRadius: 0,
padding: 0,
});
expect(highlights[1]).toMatchObject({ start: 1, end: 3 });
warn.mockRestore();
});

it('keeps the native highlights when the same array renders again', () => {
const highlights: TextHighlight[] = [{ start: 0, end: 1, color: 'red' }];
const { root, view } = renderNative(
<EnrichedMarkdownText markdown="a" highlights={highlights} />
);
const first = view().props.highlights;

act(() =>
root.render(<EnrichedMarkdownText markdown="a" highlights={highlights} />)
);

expect(view().props.highlights).toBe(first);
});

it('asks for the rendered text only when a listener is set', () => {
const { root, view } = renderNative(
<EnrichedMarkdownText markdown="a" flavor="github" />
);
expect(view().props.enableRenderedTextChange).toBe(false);

act(() =>
root.render(
<EnrichedMarkdownText
markdown="a"
flavor="github"
onRenderedTextChange={() => {}}
/>
)
);
expect(view().props.enableRenderedTextChange).toBe(true);
});

it('maps the rendered text event to the public callback', () => {
const onRenderedTextChange = jest.fn();
const { view } = renderNative(
<EnrichedMarkdownText
markdown="a"
flavor="github"
onRenderedTextChange={onRenderedTextChange}
/>
);
const event: RenderedTextChangeEvent = {
text: 'Title\nx = 1',
blocks: [
{ start: 0, end: 5, kind: 'text' },
{ start: 6, end: 11, kind: 'code' },
],
};

act(() => view().props.onRenderedTextChange({ nativeEvent: event }));

expect(onRenderedTextChange).toHaveBeenCalledWith(event);
});

it('maps the highlight layout event to the public callback', () => {
const onHighlightLayout = jest.fn();
const { view } = renderNative(
<EnrichedMarkdownText markdown="a" onHighlightLayout={onHighlightLayout} />
);
const event: HighlightLayoutEvent = {
highlights: [{ index: 1, x: 2, y: 3, width: 40, height: 20 }],
};

act(() => view().props.onHighlightLayout({ nativeEvent: event }));

expect(onHighlightLayout).toHaveBeenCalledWith(event);
});
Loading