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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,13 @@ Import the component stylesheet once in your application entry point:
import "@aeven-ai/hypermarkdown/styles.css";
```

If you render the code or diagram toolbars, tippy.js — an optional peer — also
needs its stylesheet, the same way KaTeX does:

```tsx
import "tippy.js/dist/tippy.css";
```

Then import the component:

```tsx
Expand Down
9 changes: 9 additions & 0 deletions example/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,15 @@
href="./katex.css"
/>

<!--
Toolbar tooltips are drawn by tippy.js, an optional peer, which ships its
own stylesheet. jsDelivr rather than esm.sh, for the same MIME reason.
-->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/tippy.js@6.3.7/dist/tippy.css"
/>

<link rel="stylesheet" href="./example.css" />

<!--
Expand Down
48 changes: 39 additions & 9 deletions lib/code/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ export interface CodeBlockProps {
events?: Emitter | undefined;
ui?: UiConfig | undefined;
scrollDown?: unknown;
/** Line total from the streaming cache, when it is the one rendering. */
/**
* Line total from the code cache. It is passed in both phases: the settled
* tree holds the same lines, and withdrawing the tally at the settle is what
* made the gutter rebuild every entry it had.
*/
lineCount?: number | undefined;
}

Expand All @@ -37,6 +41,8 @@ class MarkdownCode extends PureComponent<CodeBlockProps, CodeBlockState> {
private currentScrollHeight = 0;
private readonly codeRef = React.createRef<HTMLDivElement>();
private readonly wrapperRef = React.createRef<HTMLDivElement>();
/** Whether the settle has been decided; kept apart from what it produced. */
private settled = false;
private settledChildren: ReactNode | undefined;
private settleTimeout: ReturnType<typeof setTimeout> | undefined;

Expand Down Expand Up @@ -75,6 +81,7 @@ class MarkdownCode extends PureComponent<CodeBlockProps, CodeBlockState> {
) {
clearTimeout(vm.settleTimeout);
vm.settleTimeout = undefined;
vm.settled = false;
vm.settledChildren = undefined;
vm.scheduleSettledChildren();
}
Expand Down Expand Up @@ -204,9 +211,17 @@ class MarkdownCode extends PureComponent<CodeBlockProps, CodeBlockState> {
fullscreen = " fullscreen";
}

// The settle is the final render, so the gutter stops animating with it —
// while it is still streaming, and during the wait before the settled tree
// is adopted, the entries keep fading in as their lines arrive.
const lineAnimation = vm.settled === true ? false : props.animation;

children = props.children;

if (vm.settledChildren) {
// The flag is the decision, the content is only the payload: a settle that
// came back with nothing to adopt must leave the cached tree on screen
// rather than blank the block.
if (vm.settled === true && vm.settledChildren) {
children = vm.settledChildren;
}

Expand Down Expand Up @@ -237,8 +252,8 @@ class MarkdownCode extends PureComponent<CodeBlockProps, CodeBlockState> {
{ui.lineNumbers === false ? null : (
<LineNumber
codeRef={vm.codeRef}
animation={props.animation}
lineCount={vm.settledChildren ? undefined : props.lineCount}
animation={lineAnimation}
lineCount={props.lineCount}
/>
)}

Expand All @@ -258,24 +273,39 @@ class MarkdownCode extends PureComponent<CodeBlockProps, CodeBlockState> {
const vm = this;
const props = vm.props;

if (props.stream === true || vm.settleTimeout !== undefined) {
if (
props.stream === true ||
vm.settled === true ||
vm.settleTimeout !== undefined
) {
return;
}

delay = props.animation === true ? 1000 : 0;

if (delay === 0) {
vm.settledChildren = props.preChildren;
vm.setState({ finalStream: true });
vm.applySettledChildren();
return;
}

vm.settleTimeout = setTimeout(() => {
vm.settledChildren = vm.props.preChildren;
vm.settleTimeout = undefined;
vm.setState({ finalStream: true });
vm.applySettledChildren();
}, delay);
}

/**
* Adopt the settled tree, once. The flag — not the children — is what stops
* a second pass, so a settle that produced nothing to adopt cannot put the
* block back on the timer or leave the guard re-evaluating on every render.
*/
private applySettledChildren(): void {
const vm = this;

vm.settled = true;
vm.settledChildren = vm.props.preChildren;
vm.setState({ finalStream: true });
}
}

export default MarkdownCode;
17 changes: 15 additions & 2 deletions lib/code/line-numbers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ interface LineNumberProps {
* `textContent` back off the DOM — that re-serialises the whole fence on
* every chunk, so a long block spends more time counting its gutter than
* rendering its code.
*
* The caller may stop passing it — there is nothing left to count once the
* block has settled, and a host with no cache never passes it at all. The
* last tally is kept, so a withdrawn tally cannot take the gutter with it.
*/
lineCount?: number | undefined;
}
Expand All @@ -29,6 +33,9 @@ class LineNumber extends Component<LineNumberProps, LineNumberState> {
private cachedGroups: ReactNode[] = [];
private cachedAnimation: boolean | undefined;

/** The last tally the caller gave, kept for when it is withdrawn. */
private lastKnownTotal = 0;

/** Lines per memoised group. Small enough that the tail stays cheap. */
private static readonly groupSize = 64;

Expand Down Expand Up @@ -69,15 +76,21 @@ class LineNumber extends Component<LineNumberProps, LineNumberState> {
* state only catches up in componentDidUpdate, which would render the gutter
* from the previous count and leave every line number one pass behind the
* line it belongs to.
*
* It is remembered as well as returned, because the caller may withdraw it.
* Nothing has been counted while the prop was there, so state would still be
* zero, and that zero renders the empty-state span for a pass — unmounting
* every entry and restarting the fade on all of them.
*/
private total(): number {
const vm = this;

if (typeof vm.props.lineCount === "number") {
return vm.props.lineCount;
vm.lastKnownTotal = vm.props.lineCount;
return vm.lastKnownTotal;
}

return vm.state.lineNumberTotal;
return vm.state.lineNumberTotal || vm.lastKnownTotal;
}

lineNumberCount() {
Expand Down
109 changes: 104 additions & 5 deletions lib/renderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ class Renderer {
private codeCache = new CodeCache();
private tableCache = new TableCache();
private listCache = new ListCache();
/** Pending settled passes, one per closed block; dropped on reset. */
private settleTimers = new Map<number, ReturnType<typeof setTimeout>>();
private components!: ReturnType<typeof createComponents> & RendererComponents;
/** Host-supplied component overrides, applied to every component map. */
private componentOverrides!: RendererComponents;
Expand Down Expand Up @@ -275,6 +277,13 @@ class Renderer {
this.cachedFootnotes = null;

this.resetLineCache();

this.settleTimers.forEach((timer) => {
clearTimeout(timer);
});

this.settleTimers.clear();

this.applyState({});
}

Expand Down Expand Up @@ -825,6 +834,14 @@ class Renderer {
}
}

// Only a live block has animation to strip: when the message is not
// streaming, processMd() already rendered it through the plain shape.
if (streaming === true) {
vm.scheduleSettle(blockId, animation, () =>
vm.settledMarkupBlock(mdBuffer, streaming),
);
}

vm.mdBuffer = closeObject.mdNext;

vm.applyState({ md: mdState }, () => {
Expand Down Expand Up @@ -1080,14 +1097,19 @@ class Renderer {
}

// Both the streaming frames and the closed one are built here, so React
// sees the same shape throughout and never remounts the table.
private tableElement(stream: boolean): ReactElement {
// sees the same shape throughout and never remounts the table. The settled
// pass brings a cache of its own: the same rows, built without the word
// spans the streaming shape wraps them in.
private tableElement(
stream: boolean,
cache: TableCache = this.tableCache,
): ReactElement {
let hasRows;

const vm = this;

// Only whether any row exists matters; filtering copies the whole array.
hasRows = vm.tableCache.data.some((row) => row);
hasRows = cache.data.some((row) => row);

return (
<MarkdownTable
Expand All @@ -1097,12 +1119,83 @@ class Renderer {
ui={vm.ui}
scrollDown={vm.options.scrollDown}
>
<thead>{vm.tableCache.head}</thead>
{hasRows ? <tbody>{vm.tableCache.data}</tbody> : null}
<thead>{cache.head}</thead>
{hasRows ? <tbody>{cache.data}</tbody> : null}
</MarkdownTable>
);
}

/**
* Book a settled pass for a closed block.
*
* Nothing is deferred when the animation is off: the shape it closed in is
* already the settled one, so the pass would re-render identical markup.
*/
private scheduleSettle(
blockId: number,
animation: boolean,
rebuild: () => ReactNode,
): void {
const vm = this;

if (animation !== true) {
return;
}

vm.settleTimers.set(
blockId,
setTimeout(() => {
vm.settleTimers.delete(blockId);
vm.settleBlock(blockId, rebuild);
}, 1000),
);
}

/**
* Replace a closed block's element once its fades have run, so the finished
* block is a plain render. Waiting is what makes it invisible: content caught
* mid-fade would jump from its partial opacity to full the moment the
* animated spans and markers go.
*/
private settleBlock(blockId: number, rebuild: () => ReactNode): void {
const vm = this;
const block = vm.streamDataMap.get(blockId);
const element = rebuild();

if (!block || !element) {
return;
}

block.time = runtime.timeNow();
block.element = element;
vm.applyState({ md: vm.mdState });
}

/** A closed table's rows again, built without the streaming word spans. */
private settledTableBlock(mdBuffer: string): ReactElement {
const vm = this;
const cache = new TableCache();

cache.append(mdBuffer, vm.processorFor("cached-table"), {
...cellComponents(vm),
...vm.componentOverrides,
});

return vm.tableElement(false, cache);
}

/**
* The same markup again, through the same pipeline minus the animation
* stage: prose, lists and maths lose their word spans, links their
* `data-animate-key`, and items their fading marker.
*/
private settledMarkupBlock(
mdBuffer: string,
streaming: boolean,
): ReactNode {
return this.processMd(mdBuffer, streaming, false);
}

// The list wrapper. Its attributes follow from the items themselves: the
// start number from the first marker, the task-list class from whether any
// item rendered a checkbox.
Expand Down Expand Up @@ -1248,6 +1341,12 @@ class Renderer {
}
}

if (vm.tableCache.head) {
vm.scheduleSettle(blockId, animation, () =>
vm.settledTableBlock(mdBuffer),
);
}

vm.mdBuffer = closeObject.mdNext;

vm.applyState({ md: mdState }, () => {
Expand Down
Loading