okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4fb068a8c
main
1import { useSyncExternalStore } from 'react' ; 2import type { PreviewArtifact } from './artifacts' ; 3 4/** 5* Code blocks that can be shown in the sidebar preview: an HTML page, or Markdown. The block's id comes from the message and the code itself, 6* so two blocks in one answer are two previews, and the block's button can tell whether its own preview is the one open. 7*/ 8const hash = ( text :string ) => { let h = 5381 ; for ( let i = 0 ; i < text . length ; i ++ ) h = (( h << 5 ) + h + text . charCodeAt ( i )) | 0 ; return ( h >>> 0 ). toString ( 36 ); }; 9 10export function codePreviewKind ( language :string ) :'website' | 'markdown' | null { 11const name = language . trim (). toLowerCase (); 12return name === 'html' ?'website' :name === 'markdown' || name === 'md' ?'markdown' :null ; 13} 14 15export function codePreview ( base :string , language :string , code :string ) :PreviewArtifact | null { 16const kind = codePreviewKind ( language ); 17if ( ! kind ) return null ; 18return { id :` ${ base } - ${ hash ( code )} ` , kind, title :kind === 'website' ?'HTML preview' :'Markdown preview' , content :code }; 19} 20 21/** The one complete page in a finished answer, or null: exactly one fenced html block that is a whole document (a snippet stays a button). */ 22export function mainCodePreview ( base :string , content :string ) :PreviewArtifact | null { 23const blocks = [ ...content . matchAll ( / ^[ \t]*```([^\n`]*)\n([\s\S]*?)\n[ \t]*```[ \t]*$ / gm )]. map ( m => ({ language :m [ 1 ]. trim (), code :m [ 2 ] })). filter ( b => codePreviewKind ( b . language )); 24if ( blocks . length !== 1 || codePreviewKind ( blocks [ 0 ]. language ) !== 'website' ) return null ; 25return / <!doctype\s+html|<html[\s>] / i . test ( blocks [ 0 ]. code ) ?codePreview ( base , blocks [ 0 ]. language , blocks [ 0 ]. code ) :null ; 26} 27 28let selected :string | null = null ; 29const listeners = new Set <() => void >(); 30/** The chat tells which preview is showing in the sidebar; only the code blocks' buttons listen, so no message re-renders for it. */ 31export function setSelectedPreviewId ( id :string | null ) { 32if ( id === selected ) return ; 33selected = id ; 34listeners . forEach ( fn => fn ()); 35} 36export const useSelectedPreviewId = () => useSyncExternalStore ( fn => { listeners . add ( fn ); return () => { listeners . delete ( fn ); }; }, () => selected , () => null );