okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0fa4288d3
main
1import { tr } from '../lib/i18n' ; 2import { CopyBtn } from './CopyBtn' ; 3/** Safe, dependency-free rendering of the Markdown structures used in answers. */ 4import { Fragment , type ReactNode } from 'react' ; 5import { CodePreviewBtn } from './CodePreviewBtn' ; 6import { codePreview } from '../lib/code-preview' ; 7import type { PreviewArtifact } from '../lib/artifacts' ; 8import { SyntaxCode } from './SyntaxCode' ; 9import { MathView } from './MathView' ; 10import { displayBlock , hasMath , splitMath } from '../lib/math' ; 11import { imagePlan } from '../lib/markdown-images' ; 12function inlineMarks ( text :string , onOpenLink ?:( url :string ) => void , imageSession ?:string | null ) :ReactNode { 13return text . split ( / (!\[[^\]]*\]\([^\s)]+\)|`[^`]+`|\*\*[^*]+\*\*|\*[^*\n]+\*|\[[^\]]+\]\([^\s)]+\)) / g ). map (( part , i ) => { 14const image = part . match ( / ^!\[([^\]]*)\]\(([^\s)]+)\)$ / ); 15if ( image ) { 16const plan = imagePlan ( image [ 2 ], imageSession ); 17if ( plan . kind === 'img' ) 18return < img key = { i } src = { plan . src } alt = { image [ 1 ]} className = "md-image" loading = "lazy" referrerPolicy = "no-referrer" />; 19if ( plan . kind === 'link' ) 20return < a key = { i } href = { plan . href } target = "_blank" rel = "noreferrer" onClick = { e => { if ( onOpenLink ) { 21e . preventDefault (); 22onOpenLink ( plan . href ); 23} }}>{ image [ 1 ] || plan . href }</ a >; 24return < Fragment key = { i }>{ image [ 1 ] || part }</ Fragment >; 25} 26if ( part . startsWith ( '`' ) && part . endsWith ( '`' )) 27return < code key = { i } className = "md-code" >{ part . slice ( 1 , - 1 )}</ code >; 28if ( part . startsWith ( '**' ) && part . endsWith ( '**' )) 29return < strong key = { i }>{ part . slice ( 2 , - 2 )}</ strong >; 30if ( part . startsWith ( '*' ) && part . endsWith ( '*' )) 31return < em key = { i }>{ part . slice ( 1 , - 1 )}</ em >; 32const link = part . match ( / ^\[([^\]]+)\]\(([^)]+)\)$ / ); 33if ( link && / ^(https?:\/\/|mailto:|#) / i . test ( link [ 2 ])) 34return < a key = { i } href = { link [ 2 ]} target = "_blank" rel = "noreferrer" onClick = { e => { if ( onOpenLink && / ^https?: / i . test ( link [ 2 ])) { 35e . preventDefault (); 36onOpenLink ( link [ 2 ]); 37} }}>{ link [ 1 ]}</ a >; 38return < Fragment key = { i }>{ part }</ Fragment >; 39}); 40} 41/** Text with its inline marks and, outside code spans, its math (#3268). Math is cut out first: a * or _ inside a formula is not emphasis. */ 42function inline ( text :string , onOpenLink ?:( url :string ) => void , imageSession ?:string | null ) :ReactNode { 43if ( ! hasMath ( text )) 44return inlineMarks ( text , onOpenLink , imageSession ); 45return text . split ( / (`[^`]+`) / g ). map (( chunk , c ) => { 46if ( chunk . length > 1 && chunk . startsWith ( '`' ) && chunk . endsWith ( '`' )) 47return < Fragment key = { c }>{ inlineMarks ( chunk , onOpenLink , imageSession )}</ Fragment >; 48return < Fragment key = { c }>{ splitMath ( chunk ). map (( part , p ) => part . kind === 'math' 49 ?< MathView key = { p } tex = { part . tex } display = { part . display }/> 50 :< Fragment key = { p }>{ inlineMarks ( part . text , onOpenLink , imageSession )}</ Fragment >)}</ Fragment >; 51}); 52} 53/** Does this line continue the paragraph above it, or does it start a block of its own? */ 54export function continuesParagraph ( lines :string [], at :number ) :boolean { 55const line = lines [ at ]; 56if ( ! line . trim () || / ^\s*``` / . test ( line ) || / ^(#{1,6})\s+(.+)$ / . test ( line ) || / ^\s*[-*+]\s+\S / . test ( line ) || / ^\s*\d+[.)]\s+\S / . test ( line ) || / ^>\s? / . test ( line )) 57return false ; 58if ( line . includes ( '|' ) && at + 1 < lines . length && / ^\s*\|?\s*:?-{3,} / . test ( lines [ at + 1 ])) 59return false ; 60return ! displayBlock ( lines , at ); 61} 62export function Markdown ({ text, onOpenLink, previewId, onPreview, onClosePreview, imageSession} :{ 63text :string ; 64onOpenLink ?:( url :string ) => void ; 65/** Where an HTML or Markdown code block can be shown in the sidebar: the message it belongs to, and the handlers that open and close a preview. */ 66previewId ?:string ; 67onPreview ?:( a :PreviewArtifact ) => void ; 68onClosePreview ?:( id :string ) => void ; 69/** The chat whose folder a picture path in the answer is read from (the host serves only files inside it). */ 70imageSession ?:string | null ; 71}) { 72const nodes :ReactNode [] = []; 73// A file written on Windows has \r\n: the \r stays at the end of every line, where `.` does not match it, so a list line was never taken and the 74// list loop below never moved on (an endless loop that filled the page's memory, found in the sidebar preview). Line ends are read as one. 75const lines = text . split ( / \r\n|\r|\n / ); 76for ( let i = 0 ; i < lines . length ;) { 77const line = lines [ i ]; 78if ( ! line . trim ()) { 79i ++ ; 80continue ; 81} 82if ( / ^\s*``` / . test ( line )) { 83const language = line . trim (). slice ( 3 ); 84const body :string [] = []; 85const key = i ++ ; 86while ( i < lines . length && ! /^\s*``` / . test ( lines [ i ])) 87body . push ( lines [ i ++ ]); 88i ++ ; 89const code = body . join ( '\n' ); 90const preview = previewId && onPreview ?codePreview ( previewId , language , code ) :null ; 91nodes . push (< div className = "st-code" key = { key }>< div className = "st-code__head" >< span >{ language || tr ( 'code' )}</ span >< span className = "st-code__actions" >{ tr ( preview && onPreview ?< CodePreviewBtn artifact = { preview } onPreview = { onPreview } onClose = { onClosePreview }/> :null )}< CopyBtn text = { code } label = "Code" title = "Copy code" /></ span ></ div >< SyntaxCode text = { code } language = { language }/></ div >); 92continue ; 93} 94const block = displayBlock ( lines , i ); 95if ( block ) { 96nodes . push (< div className = "md-math-block" key = { i }>< MathView tex = { block . tex . trim ()} display /></ div >); 97i += block . used ; 98continue ; 99} 100const heading = line . match ( / ^(#{1,6})\s+(.+)$ / ); 101if ( heading ) { 102const Tag = heading [ 1 ]. length <= 2 ?'h2' :heading [ 1 ]. length === 3 ?'h3' :'h4' ; 103nodes . push (< Tag key = { i }>{ tr ( inline ( heading [ 2 ], onOpenLink , imageSession ))}</ Tag >); 104i ++ ; 105continue ; 106} 107if ( / ^\s*[-*+]\s+\S / . test ( line ) || / ^\s*\d+[.)]\s+\S / . test ( line )) { 108const ordered = / ^\s*\d+[.)] / . test ( line ); 109const items :ReactNode [] = []; 110const key = i ; 111const re = ordered ?/ ^\s*\d+[.)]\s+(.+)$ / :/ ^\s*[-*+]\s+(.+)$ / ; 112while ( i < lines . length && re . test ( lines [ i ])) { 113items . push (< li key = { i }>{ tr ( inline ( lines [ i ]. replace ( re , '$1' ), onOpenLink ))}</ li >); 114i ++ ; 115} 116if ( i === key ) { // never stand still: a line the list start accepted but the item pattern did not is shown as text and passed 117nodes . push (< p key = { key }>{ line }</ p >); 118i ++ ; 119continue ; 120} 121nodes . push ( ordered ?< ol key = { key }>{ tr ( items )}</ ol > :< ul key = { key }>{ tr ( items )}</ ul >); 122continue ; 123} 124if ( line . includes ( '|' ) && i + 1 < lines . length && / ^\s*\|?\s*:?-{3,} / . test ( lines [ i + 1 ])) { 125const cells = ( row :string ) => row . trim (). replace ( / ^\||\|$ / g , '' ). split ( '|' ). map ( s => s . trim ()); 126const header = cells ( line ); 127const rows :string [][] = []; 128const key = i ; 129i += 2 ; 130while ( i < lines . length && lines [ i ]. includes ( '|' )) 131rows . push ( cells ( lines [ i ++ ])); 132nodes . push (< div className = "md-table-wrap" key = { key }>< table className = "md-table" >< thead >< tr >{ tr ( header . map (( c , j ) => < th key = { j }>{ tr ( inline ( c , onOpenLink , imageSession ))}</ th >))}</ tr ></ thead >< tbody >{ tr ( rows . map (( r , j ) => < tr key = { j }>{ tr ( r . map (( c , k ) => < td key = { k }>{ tr ( inline ( c , onOpenLink , imageSession ))}</ td >))}</ tr >))}</ tbody ></ table ></ div >); 133continue ; 134} 135if ( / ^>\s? / . test ( line )) { 136nodes . push (< blockquote key = { i }>{ tr ( inline ( line . replace ( / ^>\s? / , '' ), onOpenLink ))}</ blockquote >); 137i ++ ; 138continue ; 139} 140// One paragraph: a single newline inside it is a soft break (a space); two spaces or a backslash at the end of a line is a hard break (#3818). 141const key = i , parts :ReactNode [] = []; 142let current = line ; 143i ++ ; 144while ( true ) { 145const hard = / ( {2,}|\\)$ / . test ( current ); 146parts . push (< Fragment key = { parts . length }>{ tr ( inline ( current . replace ( / ( {2,}|\\)$ / , '' ), onOpenLink , imageSession ))}</ Fragment >); 147if ( i >= lines . length || ! continuesParagraph ( lines , i )) 148break ; 149parts . push ( hard ?< br key = { `b ${ parts . length } ` }/> :' ' ); 150current = lines [ i ++ ]. trimStart (); 151} 152nodes . push (< p key = { key }>{ tr ( parts )}</ p >); 153} 154return <>{ tr ( nodes )}</>; 155}