Documentation
¶
Overview ¶
Package markstream provides independent native MyGo components for streaming Markdown. Session is the concurrent UTF-8 transport; Parser owns incremental syntax and immutable Markstream nodes; View and Stream build native controls. VirtualState virtualizes individual documents, while Messages virtualizes conversations. File, FileDiff and Compare expose native code/diff surfaces.
The optional rich subpackage provides offline math/diagram/HTML engines using a background Chromium process. The application window has no WebView.
Package markstream provides native MyGo components for streaming Markdown.
Index ¶
- Constants
- Variables
- func Compare(c *ui.Context, old, new FileData, o CompareOptions) ui.Element
- func FenceFilename(b *CodeBlock) string
- func File(c *ui.Context, data FileData, o FileOptions) ui.Element
- func FileDiff(c *ui.Context, source string, o FileOptions) ui.Element
- func ImageLoader(o ImageOptions, renderer RichRenderer) func(string) (ui.ImageSource, error)
- func Messages(c *ui.Context, state *ui.ListState, messages []Message, p Props) ui.Element
- func RenderCode(c *ui.Context, b *CodeBlock, o CodeOptions) ui.Element
- func Revealed(el ui.Element) bool
- func RichView(c *ui.Context, r RichRequest, o RichOptions) ui.Element
- func SafeLink(dest string) bool
- func Stream(c *ui.Context, s *Session, p Props) ui.Element
- func View(c *ui.Context, source string, p Props) ui.Element
- type CodeBlock
- type CodeOptions
- type CompareOptions
- type DiffKind
- type DiffLine
- type DiffMode
- type Document
- type Export
- type Extensions
- type FileData
- type FileOptions
- type FilePatch
- type HeadingStyle
- type HeightEntry
- type ImageOptions
- type InlineObject
- type Labels
- type LineEvent
- type Message
- type Node
- type Parser
- type Props
- type RenderStatus
- type Reveal
- type RevealUnit
- type RichLink
- type RichOptions
- type RichRenderState
- type RichRenderer
- type RichRequest
- type RichResult
- type Session
- func (s *Session) Append(chunk string) error
- func (s *Session) Cancel()
- func (s *Session) Consume(ctx context.Context, r io.Reader) error
- func (s *Session) Fail(err error)
- func (s *Session) Finish() error
- func (s *Session) Reset()
- func (s *Session) Snapshot() Snapshot
- func (s *Session) Subscribe(wake func()) func()
- func (s *Session) Write(p []byte) (int, error)
- type Snapshot
- type State
- type Theme
- type Variant
- type VirtualMetrics
- type VirtualSnapshot
- type VirtualState
Examples ¶
Constants ¶
const ( GFM = parser.GFM DefaultExtensions = parser.Default | parser.ExtDollarMath Tables = parser.ExtTables TaskLists = parser.ExtTaskLists Strikethrough = parser.ExtStrikethrough Autolinks = parser.ExtAutolinks Footnotes = parser.ExtFootnotes Math = parser.ExtMath DollarMath = parser.ExtDollarMath Alerts = parser.ExtAlerts )
Variables ¶
Functions ¶
func Compare ¶
Compare is the full native FileDiff surface for original/updated files: virtualized syntax highlighting, word/character diffs, split/unified layout, line selections, gutter actions, annotations and context expansion.
func FenceFilename ¶
FenceFilename returns filename metadata from a fence such as ```go title=main.go or ```go filename="hello world.go". It does not read files.
func File ¶
File is a native, line-virtualized highlighted file, with a stable gutter, per-line interactions and annotations. Its copy action copies all source.
func FileDiff ¶
FileDiff displays unified patches with native unified/split switching and expandable unchanged regions. Its internal list only builds visible rows.
func ImageLoader ¶
func ImageLoader(o ImageOptions, renderer RichRenderer) func(string) (ui.ImageSource, error)
ImageLoader loads bounded HTTP(S)/data images off the UI thread. Native MyGo decodes raster formats; a configured rich renderer handles full SVG layout.
func RenderCode ¶
RenderCode draws the same native code surface used by View when CodeOptions is set. Custom renderers can call it for fallback without losing copy behavior.
func RichView ¶
func RichView(c *ui.Context, r RichRequest, o RichOptions) ui.Element
RichView displays an actual rendered graphic in native controls. Parsing and layout happen in the configured background renderer. Invalid progressive input keeps the most recent valid preview and exposes its source and error.
Types ¶
type CodeBlock ¶
type CodeOptions ¶
type CodeOptions struct {
ShowFontSize bool
HeaderLeft, HeaderRight func(*ui.Context, *CodeBlock)
Labels Labels
File *FileOptions
Collapsible bool
DefaultCollapsed bool
// MaxHeight bounds the body with a vertical scroll container (DIPs).
MaxHeight float32
HideCopy bool
HideLanguage bool
// Filename is optional metadata computed from a fence's Info string.
Filename func(*CodeBlock) string
}
CodeOptions configures the native code surface. Zero values retain the built-in highlighted, selectable body and Copy action. Language renderers take priority.
type CompareOptions ¶
type CompareOptions struct {
FileOptions
Inline editor.DiffInline
Indicators editor.DiffIndicators
TabSize int
FontFamily string
NoBackground bool
ExpansionLines int
LineSelection bool
OnLineSelection func(editor.DiffLineRange)
OnGutterUtility func(editor.DiffLineRange)
Annotations []editor.DiffAnnotation
RenderAnnotation func(*ui.Context, editor.DiffAnnotation)
Controller func(*editor.DiffState)
}
type Document ¶
Document is MyGo's incremental Markdown syntax tree. Block indices and spans remain valid until the next mutation. It is owned by one goroutine; Session is the concurrent transport. Reusing a document preserves completed-block caches.
func NewDocument ¶
func NewDocument(extensions Extensions) *Document
Example ¶
package main
import (
"fmt"
markstream "github.com/zerob13/markstream-go"
)
func main() {
doc := markstream.NewDocument(0)
doc.SetStreaming(true)
doc.Append("Hello **wor")
doc.Append("ld**")
doc.SetStreaming(false)
fmt.Println(doc.Source())
}
Output: Hello **world**
type Extensions ¶
type Extensions = parser.Extensions
Extensions selects syntax beyond CommonMark. NewDocument(0) uses the defaults.
type FileOptions ¶
type FileOptions struct {
Labels Labels
TabSize int
Font string
Theme *editor.Theme
Streaming bool
Language string
Compare *CompareOptions
FontSize, LineHeight, MaxHeight float32
HideLineNumbers bool
Wrap bool
DiffMode DiffMode
HideUnchanged bool
ContextLines int
OnLineClick func(LineEvent)
// Annotation builds an optional native annotation following a file line.
Annotation func(*ui.Context, LineEvent)
}
type HeadingStyle ¶
type HeightEntry ¶
type ImageOptions ¶
type InlineObject ¶
type Labels ¶
Labels overrides built-in control text. Keys are the default English labels. Native editor menus additionally follow MyGo's platform locale.
type Node ¶
type Node struct {
ID, Type, Raw, Content, Language, Info, URL, Title, Label, LocalSource string
Attributes map[string]string
Start, End, Index, Level, Number int
Loading, Ordered, Header bool
Task int
Align []int
Children []*Node
}
Node is Markstream's renderer-independent tree. MyGo's low-level CommonMark parser is only a tokenizer dependency; no MyGo Markdown widget is used.
func ParseNodes ¶
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser owns the incremental low-level syntax document and Markstream node cache. It is single-goroutine state; returned nodes are immutable snapshots and may be handed to the UI through Props.Nodes without using a Markdown widget.
func NewParser ¶
func NewParser(extensions Extensions) *Parser
type Props ¶
type Props struct {
Pending int
Locale string
Labels Labels
MaxLiveNodes int
DisableVirtualization bool
Nodes []*Node
TransformNodes func([]*Node) []*Node
NodeRenderers map[string]func(*ui.Context, *Node)
CustomHTML map[string]func(*ui.Context, *Node)
OnTaskToggle func(*Node, bool)
OnUpdate func(RenderStatus)
OnSettled func(RenderStatus)
OnFinal func(RenderStatus)
ParseRevision uint64
ImageOptions *ImageOptions
DisableImages bool
Emoji bool
EmojiAliases map[string]string
SourceTransform func(string) string
DocumentTransform func(*Document)
Document *Document
Rich *RichOptions
MeasurementKey string
Virtual *VirtualState
Streaming bool
Variant Variant
Theme *Theme
Reveal *Reveal
Extensions Extensions
OnLink func(string)
LoadImage func(string) (ui.ImageSource, error)
WrapCode bool
// PlainCode omits the enhanced language/copy header. Body remains selectable.
PlainCode bool
CodeOptions *CodeOptions
CodeBlock func(*ui.Context, *CodeBlock)
// Code provides per-language renderers, e.g. mermaid, d2, or infographic.
// While a fence is open, the default code surface is retained. Finalization
// also releases an unclosed fence. RenderOpenCode opts into incomplete input.
Code map[string]func(*ui.Context, *CodeBlock)
RenderOpenCode bool
Math func(*ui.Context, string)
InlineMath func(string, float32) (InlineObject, bool)
HTML func(*ui.Context, string)
Block func(*ui.Context, *Document, int) bool
Anchor string
AnchorVersion uint64
}
type RenderStatus ¶
type RenderStatus struct {
Receiving, Revealing, Settled, Final bool
Pending int
Metrics VirtualMetrics
}
type Reveal ¶
type Reveal struct {
Unit RevealUnit
CatchUp, Fade time.Duration
}
type RevealUnit ¶
type RevealUnit uint8
const ( ByWord RevealUnit = iota ByCharacter BySentence ByLine ByParagraph AtOnce )
type RichOptions ¶
type RichOptions struct {
// Config contains per-kind engine options (e.g. math macros or Mermaid themeVariables).
// Sandbox, sanitization and resource limits remain enforced by the bundled engine.
Config map[string]map[string]any
Labels Labels
OnRender func(RichRenderState)
Renderer RichRenderer
Width int
MaxHeight float32
// Progressive renders valid diagram prefixes while a fence is still open.
Progressive bool
// OnExport receives the real SVG or PNG. A nil handler opens the native Save dialog.
OnExport func(Export)
// contains filtered or unexported fields
}
type RichRenderState ¶
RichRenderState is delivered on the UI thread after a render completes.
type RichRenderer ¶
type RichRenderer interface {
Render(context.Context, RichRequest) (RichResult, error)
}
RichRenderer computes a graphic away from MyGo's UI thread. The rich package provides the bundled Mermaid/KaTeX/D2/Infographic/HTML implementation.
type RichRequest ¶
type RichResult ¶
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session accepts io.Writer chunks from background goroutines. Render calls Snapshot once per frame, coalescing multiple writes into one UI invalidation. The zero value is ready to use. Do not copy a Session after use.
Example ¶
package main
import (
"fmt"
markstream "github.com/zerob13/markstream-go"
)
func main() {
reply := markstream.NewSession(1024)
_ = reply.Append("Hello **世界**")
_ = reply.Finish()
snapshot := reply.Snapshot()
fmt.Println(snapshot.Source)
fmt.Println(snapshot.State)
}
Output: Hello **世界** completed
func NewSession ¶
NewSession limits incoming bytes when maxBytes > 0. Zero means unlimited.
func (*Session) Cancel ¶
func (s *Session) Cancel()
Cancel stops receiving while retaining all complete text. It is idempotent.
func (*Session) Consume ¶
Consume reads raw Markdown (not SSE framing) until EOF, then calls Finish. Cancellation is checked between reads: to interrupt a blocked Read, cancel the HTTP request context or close the reader. The reader is owned by the caller.
func (*Session) Finish ¶
Finish marks EOF and flushes the parser to strict Markdown on the next frame. An incomplete final UTF-8 rune fails the stream instead of displaying corruption.
func (*Session) Reset ¶
func (s *Session) Reset()
Reset starts a new reply. Reads started for an older generation cannot write to it.
func (*Session) Subscribe ¶
func (s *Session) Subscribe(wake func()) func()
Subscribe registers a nonblocking wake-up callback. It may run on the writer's goroutine and must not build UI. MyGo Services.Invalidate is suitable. The returned function removes the subscription; an already-running call may finish.
type Snapshot ¶
type Snapshot struct {
Source string
State State
Err error
Revision uint64
Generation uint64
PendingBytes int
}
Snapshot is immutable and safe to retain while a producer writes more data. Source contains complete UTF-8 only; PendingBytes counts a split rune held back.
type State ¶
type State uint8
State is the lifecycle of a streaming reply. Its zero value is Receiving.
type Theme ¶
type Theme struct {
FontSize float32
Font, CodeFont string
LineHeight, CodeLineHeight float32
Text, Muted, Link, Strong ui.Color
StrongWeight, LinkWeight int
Code, CodeBackground ui.Color
CodeSize, BlockSpacing, ItemSpacing, ListIndent float32
Headings [6]HeadingStyle
QuoteBar, QuoteText ui.Color
QuoteBarWidth float32
Alerts [5]ui.Color
Rule ui.Color
CodeBlockBackground, CodeBlockBorder ui.Color
CodeBlockRadius, CodeBlockPadding float32
CodeColors *editor.Theme
TableBorder, TableHeader, TableStripe ui.Color
TableCellPadding [2]float32
TableMaxColumn float32
Mark, Checkbox ui.Color
}
type VirtualMetrics ¶
type VirtualSnapshot ¶
type VirtualState ¶
type VirtualState struct {
List ui.ListState
Scroll ui.ScrollState
MeasurementKey string
// contains filtered or unexported fields
}
VirtualState owns Markstream's block-level virtual document viewport. Its cache and anchors are independent from the low-level syntax parser.
func (*VirtualState) Capture ¶
func (v *VirtualState) Capture() VirtualSnapshot
func (*VirtualState) Metrics ¶
func (v *VirtualState) Metrics() VirtualMetrics
func (*VirtualState) Reset ¶
func (v *VirtualState) Reset()
func (*VirtualState) Restore ¶
func (v *VirtualState) Restore(s VirtualSnapshot)
func (*VirtualState) ScrollToEnd ¶
func (v *VirtualState) ScrollToEnd()
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
demo
command
Demo is a native MyGo app.
|
Demo is a native MyGo app. |
|
Package rich provides bundled, offline renderers for Mermaid, KaTeX, D2, AntV Infographic and sanitized HTML.
|
Package rich provides bundled, offline renderers for Mermaid, KaTeX, D2, AntV Infographic and sanitized HTML. |
