@opengeni/react-native 6.39.1-canary.45627434309001 → 6.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,9 @@ import {
2
2
  cloneElement,
3
3
  createContext,
4
4
  Fragment,
5
+ memo,
5
6
  useContext,
7
+ useEffect,
6
8
  useMemo,
7
9
  useRef,
8
10
  useState,
@@ -31,7 +33,15 @@ import {
31
33
  interactivePreviewKind,
32
34
  type InteractivePreviewKind,
33
35
  } from "@opengeni/react/native-previews";
34
- import { MAX_MARKDOWN_LENGTH, prepareBoundedMarkdown } from "./markdown-limit";
36
+ import {
37
+ MAX_MARKDOWN_CHUNK_LENGTH,
38
+ MAX_MARKDOWN_LENGTH,
39
+ createMarkdownSegmenter,
40
+ markdownItMathRanges,
41
+ mountedSegmentCount,
42
+ prepareBoundedMarkdown,
43
+ type MarkdownSegment,
44
+ } from "./markdown-limit";
35
45
  import { PlainTextMessage } from "./plain-text-message";
36
46
  import { Icon } from "./icon";
37
47
  import { isStandaloneLinkGroup, soleTextGroupOf } from "./markdown-standalone-links";
@@ -74,6 +84,16 @@ const MATH_PARSER = (() => {
74
84
  return parser;
75
85
  })();
76
86
 
87
+ /**
88
+ * The block parser that decides where a long message is cut: the same rules as PARSER,
89
+ * plus display math as the one block MATH_PARSER sees after math normalization.
90
+ */
91
+ const SEGMENT_PARSER = (() => {
92
+ const parser = MarkdownIt({ typographer: false, linkify: true });
93
+ parser.use(markdownItMathRanges);
94
+ return parser;
95
+ })();
96
+
77
97
  /* ----------------------------------------------------------------------------
78
98
  Web Markdown (components/markdown.tsx) styles for react-native-markdown-display.
79
99
  Prose 15/28 (`text-og-md leading-7`), paragraphs `my-2.5`, lists `ml-5 gap-1`,
@@ -608,27 +628,7 @@ function webRules(
608
628
  const content = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
609
629
  const info = (node as { sourceInfo?: unknown }).sourceInfo;
610
630
  const language = typeof info === "string" ? (info.trim().split(/\s+/)[0] ?? "") : "";
611
- if (language === INTERACTIVE_ANSWER_FENCE) {
612
- return (
613
- <AnswerFence
614
- key={node.key}
615
- content={content}
616
- renderSource={() => <CodeFence content={content} language={language} onCopy={onCopy} />}
617
- />
618
- );
619
- }
620
- const kind = interactivePreviewKind(language);
621
- if (kind && media.renderInteractiveBlock) {
622
- return (
623
- <InteractiveFence
624
- key={node.key}
625
- kind={kind}
626
- content={content}
627
- render={media.renderInteractiveBlock}
628
- />
629
- );
630
- }
631
- return <CodeFence key={node.key} content={content} language={language} onCopy={onCopy} />;
631
+ return fenceElement(node.key, content, language, onCopy, media);
632
632
  },
633
633
  image: (node) => {
634
634
  const attributes = (node as { attributes?: { src?: unknown; alt?: unknown } }).attributes;
@@ -671,6 +671,37 @@ function webRules(
671
671
  };
672
672
  }
673
673
 
674
+ /** A fenced block as Markdown draws it: an interactive answer, a preview or code. */
675
+ function fenceElement(
676
+ key: string,
677
+ content: string,
678
+ language: string,
679
+ onCopy: ((text: string) => void) | undefined,
680
+ media: MarkdownMediaOptions,
681
+ ): ReactElement {
682
+ if (language === INTERACTIVE_ANSWER_FENCE) {
683
+ return (
684
+ <AnswerFence
685
+ key={key}
686
+ content={content}
687
+ renderSource={() => <CodeFence content={content} language={language} onCopy={onCopy} />}
688
+ />
689
+ );
690
+ }
691
+ const kind = interactivePreviewKind(language);
692
+ if (kind && media.renderInteractiveBlock) {
693
+ return (
694
+ <InteractiveFence
695
+ key={key}
696
+ kind={kind}
697
+ content={content}
698
+ render={media.renderInteractiveBlock}
699
+ />
700
+ );
701
+ }
702
+ return <CodeFence key={key} content={content} language={language} onCopy={onCopy} />;
703
+ }
704
+
674
705
  /** An assistant-authored interactive preview fence, as the host should draw it. */
675
706
  export type NativeInteractiveBlock = {
676
707
  kind: InteractivePreviewKind;
@@ -808,6 +839,150 @@ function MarkdownImage({ src, alt }: { src: string; alt: string }) {
808
839
  );
809
840
  }
810
841
 
842
+ type ChunkRendering = {
843
+ styles: Record<string, TextStyle>;
844
+ rules: RenderRules;
845
+ onLinkPress?: ((url: string) => boolean) | undefined;
846
+ interactive: boolean;
847
+ };
848
+
849
+ /**
850
+ * One bounded Markdown parse. Memoized on its source, so while a long message streams
851
+ * only the chunk that changed is parsed again.
852
+ */
853
+ const MarkdownChunk = memo(
854
+ function MarkdownChunk({
855
+ segment,
856
+ last,
857
+ streaming,
858
+ rendering,
859
+ }: {
860
+ segment: Extract<MarkdownSegment, { kind: "markdown" }>;
861
+ last: boolean;
862
+ streaming: boolean;
863
+ rendering: ChunkRendering;
864
+ }) {
865
+ const { styles, rules, onLinkPress, interactive } = rendering;
866
+ const { source } = segment;
867
+ const prepared = useMemo(() => prepareBoundedMarkdown(source), [source]);
868
+ // Previews and interactive answers both need to know whether the last fence is still open.
869
+ const openTail = useMemo(
870
+ () =>
871
+ last && (interactive || source.includes(INTERACTIVE_ANSWER_FENCE))
872
+ ? trailingOpenFence(source)
873
+ : null,
874
+ [last, interactive, source],
875
+ );
876
+ const fenceState = useMemo(() => ({ openTail, streaming }), [openTail, streaming]);
877
+ // Math normalization can expand a chunk past one parse: show its source instead.
878
+ if (!prepared) {
879
+ return (
880
+ <View style={{ marginBottom: 10 }}>
881
+ <PlainTextMessage text={source} style={styles.body!} />
882
+ </View>
883
+ );
884
+ }
885
+ return (
886
+ <FenceStateContext.Provider value={fenceState}>
887
+ <Markdown
888
+ markdownit={prepared.hasMath ? MATH_PARSER : PARSER}
889
+ style={styles}
890
+ rules={rules}
891
+ {...(onLinkPress ? { onLinkPress } : {})}
892
+ >
893
+ {prepared.hasMath ? prepared.text : source}
894
+ </Markdown>
895
+ </FenceStateContext.Provider>
896
+ );
897
+ },
898
+ // The segment object is rebuilt on every delta; its source determines it.
899
+ (previous, next) =>
900
+ previous.segment.source === next.segment.source &&
901
+ previous.last === next.last &&
902
+ previous.streaming === next.streaming &&
903
+ previous.rendering === next.rendering,
904
+ );
905
+
906
+ /**
907
+ * A large top-level fence of a long message, drawn directly instead of through
908
+ * Markdown. Memoized, so mounting later chunks does not redraw a large code block.
909
+ */
910
+ const DirectFence = memo(
911
+ function DirectFence({
912
+ segment,
913
+ streaming,
914
+ onCopy,
915
+ media,
916
+ bodyStyle,
917
+ }: {
918
+ segment: Extract<MarkdownSegment, { kind: "fence" }>;
919
+ streaming: boolean;
920
+ onCopy?: ((text: string) => void) | undefined;
921
+ media: MarkdownMediaOptions;
922
+ bodyStyle: TextStyle;
923
+ }) {
924
+ const fenceState = useMemo(
925
+ () => ({ openTail: segment.closed ? null : segment.content, streaming }),
926
+ [segment.closed, segment.content, streaming],
927
+ );
928
+ const preview = !!interactivePreviewKind(segment.language) && !!media.renderInteractiveBlock;
929
+ // A code block longer than one parse would be one huge text view: page it instead.
930
+ if (!preview && segment.content.length > MAX_MARKDOWN_CHUNK_LENGTH) {
931
+ return (
932
+ <View style={{ marginBottom: 10 }}>
933
+ <PlainTextMessage text={segment.source} style={bodyStyle} />
934
+ </View>
935
+ );
936
+ }
937
+ return (
938
+ <FenceStateContext.Provider value={fenceState}>
939
+ {fenceElement("fence", segment.content, segment.language, onCopy, media)}
940
+ </FenceStateContext.Provider>
941
+ );
942
+ },
943
+ // The segment object is rebuilt on every delta; its source determines it.
944
+ (previous, next) =>
945
+ previous.segment.source === next.segment.source &&
946
+ previous.streaming === next.streaming &&
947
+ previous.onCopy === next.onCopy &&
948
+ previous.media === next.media &&
949
+ previous.bodyStyle === next.bodyStyle,
950
+ );
951
+
952
+ function nextFrame(run: () => void): () => void {
953
+ if (typeof requestAnimationFrame === "function") {
954
+ const handle = requestAnimationFrame(run);
955
+ return () => cancelAnimationFrame(handle);
956
+ }
957
+ const handle = setTimeout(run, 16);
958
+ return () => clearTimeout(handle);
959
+ }
960
+
961
+ /**
962
+ * How many leading segments are mounted: one bounded slice now and one more per frame,
963
+ * so a long message never blocks a frame for longer than one chunk would. The count
964
+ * survives streaming deltas, which only add segments at the end.
965
+ */
966
+ function useMountedSegments(segments: readonly MarkdownSegment[] | null): number {
967
+ const [mounted, setMounted] = useState(0);
968
+ const latest = useRef(segments);
969
+ useEffect(() => {
970
+ latest.current = segments;
971
+ });
972
+ const count = segments?.length ?? 0;
973
+ // A replaced, shorter message mounts its regrowth a slice per frame again.
974
+ if (mounted > count) setMounted(count);
975
+ const shown = segments ? Math.max(mounted, mountedSegmentCount(segments, 0)) : 0;
976
+ useEffect(() => {
977
+ if (shown >= count) return undefined;
978
+ return nextFrame(() => {
979
+ const current = latest.current;
980
+ if (current) setMounted(mountedSegmentCount(current, Math.min(shown, current.length)));
981
+ });
982
+ }, [count, shown]);
983
+ return Math.min(shown, count);
984
+ }
985
+
811
986
  /** Trim the trailing paragraph margin (web `last:mb-0`). */
812
987
  function TrimmedMarkdown({
813
988
  text,
@@ -827,34 +1002,57 @@ function TrimmedMarkdown({
827
1002
  media: MarkdownMediaOptions & MarkdownLinkOptions;
828
1003
  }) {
829
1004
  const theme = useNativeTimelineTheme();
830
- const math = useMemo(() => prepareBoundedMarkdown(text), [text]);
1005
+ // One segmenter per message, so streaming deltas re-parse only the blocks at its end.
1006
+ const [segmenter] = useState(() => createMarkdownSegmenter(SEGMENT_PARSER));
1007
+ const segments = useMemo(() => segmenter(text), [segmenter, text]);
1008
+ const shown = useMountedSegments(segments);
831
1009
  const styles = useMemo(() => {
832
1010
  const base = webMarkdownStyles(theme, tone);
833
1011
  return textStyle ? { ...base, body: { ...base.body, ...textStyle } } : base;
834
1012
  }, [theme, tone, textStyle]);
835
1013
  const rules = useMemo(() => webRules(theme, tone, onCopy, media), [theme, tone, onCopy, media]);
836
- // Previews and interactive answers both need to know whether the last fence is still open.
837
- const openTail = useMemo(
838
- () =>
839
- math && (media.renderInteractiveBlock || text.includes(INTERACTIVE_ANSWER_FENCE))
840
- ? trailingOpenFence(text)
841
- : null,
842
- [math, media.renderInteractiveBlock, text],
1014
+ const rendering = useMemo<ChunkRendering>(
1015
+ () => ({ styles, rules, onLinkPress, interactive: !!media.renderInteractiveBlock }),
1016
+ [styles, rules, onLinkPress, media.renderInteractiveBlock],
843
1017
  );
844
- const fenceState = useMemo(() => ({ openTail, streaming }), [openTail, streaming]);
845
- if (!math) return <PlainTextMessage text={text} style={styles.body!} />;
1018
+ if (!segments) return <PlainTextMessage text={text} style={styles.body!} />;
1019
+ let offset = 0;
846
1020
  return (
847
1021
  <View style={{ marginBottom: -10 }}>
848
- <FenceStateContext.Provider value={fenceState}>
849
- <Markdown
850
- markdownit={math.hasMath ? MATH_PARSER : PARSER}
851
- style={styles}
852
- rules={rules}
853
- {...(onLinkPress ? { onLinkPress } : {})}
854
- >
855
- {math.hasMath ? math.text : text}
856
- </Markdown>
857
- </FenceStateContext.Provider>
1022
+ {segments.slice(0, shown).map((segment, index) => {
1023
+ const last = index === segments.length - 1;
1024
+ // Keyed by where the segment starts, which stays put while later text streams in.
1025
+ const key = `${segment.kind}:${offset}`;
1026
+ offset += segment.source.length;
1027
+ if (segment.kind === "markdown") {
1028
+ return segment.source.trim() ? (
1029
+ <MarkdownChunk
1030
+ key={key}
1031
+ segment={segment}
1032
+ last={last}
1033
+ streaming={streaming && last}
1034
+ rendering={rendering}
1035
+ />
1036
+ ) : null;
1037
+ }
1038
+ if (segment.kind === "fence") {
1039
+ return (
1040
+ <DirectFence
1041
+ key={key}
1042
+ segment={segment}
1043
+ streaming={streaming && last}
1044
+ onCopy={onCopy}
1045
+ media={media}
1046
+ bodyStyle={styles.body!}
1047
+ />
1048
+ );
1049
+ }
1050
+ return (
1051
+ <View key={key} style={{ marginBottom: 10 }}>
1052
+ <PlainTextMessage text={segment.source} style={styles.body!} />
1053
+ </View>
1054
+ );
1055
+ })}
858
1056
  </View>
859
1057
  );
860
1058
  }