psrt

package
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 30, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package psrt defines data types for the PSRT linear document format (pages, text blocks, fonts, and named string constants). See docs/02-linguagem-psrt.md in the repository for the full grammar.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CleanEmptyTextBlockStyles

func CleanEmptyTextBlockStyles(doc *Document)

CleanEmptyTextBlockStyles removes useless typography/layout styles from empty text blocks.

func Configure

func Configure(opts FormatOptions)

Configure overrides process-wide formatting options. Call once during startup, before any FormatPSRT call — it is not safe to call concurrently with formatting.

func ConstsWithInteractive added in v1.4.0

func ConstsWithInteractive(consts map[string]string, iConst map[string]InteractiveConst) map[string]string

ConstsWithInteractive returns a substitution map combining plain consts with interactive ones flattened to their Render text (keyed by the `type:render` reference token). Feeding it to ExpandConsts collapses `@type:render@` to its base label in universal snapshots (SVG/HTML), dropping the interactive behaviour.

func ConvertLegacyCoords added in v1.3.0

func ConvertLegacyCoords(s string) (string, error)

ConvertLegacyCoords rewrites one legacy hyphen-separated coordinate quad (X-Y-Width-Height or X-Y-Width-TextSize) into the comma-separated form used by the current grammar. The legacy format never supported negative numbers — the hyphen doubled as field separator and minus sign, so a negative value was already inexpressible — meaning this is a plain re-join: split on "-", require exactly four numeric chunks, join on ",".

func ConvertLegacyDocument added in v1.3.0

func ConvertLegacyDocument(raw string) (string, error)

ConvertLegacyDocument rewrites every >>, ==, and ~~ header's coordinate quad in raw legacy PSRT text (hyphen-separated) to the comma-separated grammar parsed by Parse. Directives, text/path bodies, styles, and everything else in the document are left untouched. The result is meant to be fed straight into Parse/ParseString.

func ExpandConsts

func ExpandConsts(content string, consts map[string]string) string

ExpandConsts replaces @name@ placeholders in content using consts. Longer keys are substituted first so names that are prefixes of other names do not break.

func FixMisencodedUTF8

func FixMisencodedUTF8(s string) string

FixMisencodedUTF8 repairs text that was UTF-8 but interpreted as Latin-1 (e.g. "você" → "você").

func FormatConstMarkdown

func FormatConstMarkdown(name, value string) string

FormatConstMarkdown renders a named constant as Markdown.

func FormatConstPSRT

func FormatConstPSRT(name, value string) []byte

FormatConstPSRT writes one constant line suitable inside $CONSTS … $ENDCONSTS.

func FormatDocumentMarkdown

func FormatDocumentMarkdown(doc Document) string

FormatDocumentMarkdown renders the whole document as Markdown.

func FormatPSRT

func FormatPSRT(doc Document, compact bool) ([]byte, error)

FormatPSRT serialises a full document to PSRT syntax.

func FormatPageMarkdown

func FormatPageMarkdown(p *Page) string

FormatPageMarkdown renders one page as Markdown.

func FormatPagePSRT

func FormatPagePSRT(p *Page) ([]byte, error)

FormatPagePSRT writes a single page as a PSRT fragment ($START … $END).

func FormatTextMarkdown

func FormatTextMarkdown(t *Text) string

FormatTextMarkdown renders a single text block as Markdown.

func FormatTextPSRT

func FormatTextPSRT(t *Text) ([]byte, error)

FormatTextPSRT writes one text block (>> header + indented body).

func IsTextBlockEmpty

func IsTextBlockEmpty(content string) bool

IsTextBlockEmpty reports whether a text block has no non-whitespace content.

func LoadSource

func LoadSource(raw string, url string) (string, error)

LoadSource reads one embedded asset from the $SOURCE block of raw PSRT text.

func NormalizePathData

func NormalizePathData(content string) string

NormalizePathData collapses line breaks and runs of whitespace in a ~~ block body into single spaces — line breaks in the source file are a readability convention only and carry no syntactic meaning (RF-4).

func NormalizeTextContent

func NormalizeTextContent(content string) string

NormalizeTextContent trims spaces and tabs before the first character and after the last character of a text block body (per PSRT spec).

func ParseTolerant

func ParseTolerant(r io.Reader) (Document, []ParseError)

ParseTolerant parses a PSRT document like Parse, but never aborts on a malformed or unrecognized >>/==/~~ block inside an already-open page: the offending block is discarded and its error is accumulated instead. This is the opt-in counterpart to Parse's all-or-nothing contract, for readers that would rather show a partial document than fail entirely on a marker or block they don't understand (e.g. an older reader encountering ~~).

func PlainTextForLayout

func PlainTextForLayout(content string) string

PlainTextForLayout strips inline markup delimiters for line-width estimation.

func PromoteEmptyTextsToMasks

func PromoteEmptyTextsToMasks(doc *Document)

PromoteEmptyTextsToMasks converts empty >> blocks into == mask blocks before formatting.

func RenderInlineHTML

func RenderInlineHTML(content string) string

RenderInlineHTML converts PSRT inline markup to safe HTML. Newlines become <br/>.

func RoundCoord

func RoundCoord(v float64) float64

RoundCoord limits a coordinate to at most coordMaxDecimals decimal places.

func TextFontSizePx

func TextFontSizePx(textSizePct float64, canvasW, canvasH int) float64

TextFontSizePx converts text-size percent to pixels using TextSizeBasisPx.

func TextSizeBasisPx

func TextSizeBasisPx(canvasW, canvasH int) float64

TextSizeBasisPx is the reference length for text-size percentages: min(canvas width, canvas height).

func ToJSON

func ToJSON(doc Document) ([]byte, error)

ToJSON returns the canonical JSON encoding of doc.

Types

type BaseBlock

type BaseBlock struct {
	X float64 `json:"x"`

	Y float64 `json:"y"`

	Width float64 `json:"width"`

	Style Style `json:"style"`

	Index int `json:"index"`

	ImageRef string `json:"imageRef,omitempty"`
}

type BlockKind

type BlockKind int

BlockKind identifies a page block entry.

const (
	BlockText BlockKind = iota
	BlockMask
	BlockPathMask
)

type Document

type Document struct {
	Pages []Page `json:"pages"`

	Fonts []string `json:"fonts"`

	Consts map[string]string `json:"consts"`

	// IConst holds interactive $CONSTS entries (`@type:render | value`), keyed by the
	// reference token `type:render` used as `@type:render@` in bodies.
	IConst map[string]InteractiveConst `json:"iConst,omitempty"`

	// Sources maps original asset URLs/paths to embedded data: URIs ($SOURCE block).
	Sources map[string]string `json:"sources,omitempty"`
}

func Parse

func Parse(r io.Reader) (Document, error)

Parse reads a PSRT document line by line and returns its structured form.

func ParseFast

func ParseFast(r io.Reader) (Document, error)

ParseFast parses a PSRT document without loading embedded asset payloads from $SOURCE. Source keys are recorded with empty values; use LoadSource to fetch a payload on demand.

func ParseFastString

func ParseFastString(input string) (Document, error)

ParseFastString is ParseFast from a string.

func ParseJSON

func ParseJSON(b []byte) (Document, error)

ParseJSON decodes a Document from JSON (inverse of ToJSON).

func ParseString

func ParseString(input string) (Document, error)

ParseString parses a PSRT document from a string.

type FormatOptions

type FormatOptions struct {
	// PathCommandsPerLine caps how many SVG path commands are written per
	// line in a ~~ block body. Zero/negative falls back to the default.
	PathCommandsPerLine int `json:"pathCommandsPerLine"`
}

FormatOptions configures process-wide PSRT serialization behavior. It is set once via Configure during process startup — psrt formatting has no reload mechanism, mirroring how the JS SDK's initPsrt() boots the WASM core exactly once per process.

type InteractiveConst added in v1.4.0

type InteractiveConst struct {
	Type string `json:"type"`

	Render string `json:"render"`

	Value string `json:"value"`
}

InteractiveConst is a behavioural $CONSTS entry. Type selects a renderer/handler (e.g. link, desc); Render is the inline text shown in place; Value is the handler payload (URL, modal content, …). The core is agnostic to the meaning of Type and Value — only renderers interpret them, so new directives need no core change.

type Mask

type Mask struct {
	BaseBlock

	Height float64 `json:"height"`
}

func FindMaskByIndex

func FindMaskByIndex(p *Page, index int) (*Mask, int, error)

FindMaskByIndex returns the mask block with the given index on p.

func NewMask

func NewMask(x, y, width, height float64, index int, style Style, imageRef string) Mask

NewMask builds a mask block.

type Page

type Page struct {
	Name string `json:"name"`

	Style Style `json:"style"`

	ImageURL string `json:"imageUrl"`

	Texts []Text `json:"texts"`

	Masks []Mask `json:"masks,omitempty"`

	PathMasks []PathMask `json:"pathMasks,omitempty"`
}

type PageBlockEntry

type PageBlockEntry struct {
	Kind     BlockKind
	Text     *Text
	Mask     *Mask
	PathMask *PathMask
}

PageBlockEntry is a text, mask, or path mask block sorted by Index for emission/compile.

func FindBlockByIndex

func FindBlockByIndex(p *Page, index int) (PageBlockEntry, error)

FindBlockByIndex returns a text, mask, or path mask block by index.

func PageBlocksByIndex

func PageBlocksByIndex(p *Page) []PageBlockEntry

PageBlocksByIndex returns all blocks on p sorted by Index ascending.

type ParseError

type ParseError struct {
	Line    int
	Message string
}

ParseError is one discarded-block failure accumulated by ParseTolerant.

func (ParseError) Error

func (e ParseError) Error() string

type PathMask

type PathMask struct {
	BaseBlock

	Height float64 `json:"height"`

	Path string `json:"path"`
}

func FindPathMaskByIndex

func FindPathMaskByIndex(p *Page, index int) (*PathMask, int, error)

FindPathMaskByIndex returns the path mask block with the given index on p.

func NewPathMask

func NewPathMask(x, y, width, height float64, index int, style Style, imageRef, path string) PathMask

NewPathMask builds a path mask block.

type Style

type Style = json.RawMessage

func ExpandConstsInStyle

func ExpandConstsInStyle(style Style, consts map[string]string) (Style, error)

ExpandConstsInStyle applies @name@ placeholders to compacted style JSON per PSRT.md.

type Text

type Text struct {
	BaseBlock

	TextSize float64 `json:"textSize"`

	Content string `json:"content"`
}

func FindTextByIndex

func FindTextByIndex(p *Page, index int) (*Text, int, error)

FindTextByIndex returns the text block with the given index on p.

func NewText

func NewText(x, y, width, textSize float64, index int, style Style, content, imageRef string) Text

NewText builds a text block (convenience for tests and callers).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL