richtext

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: Apache-2.0, MIT Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package richtext renders, cleans, and measures rich text for Sight fields and public pages. One Renderer holds a field's configuration: storage mode (GFM Markdown or semantic HTML), enabled features, and the classes each element gets at display time.

Content is stored without classes. Clean turns submitted HTML into the canonical classless form; Render sanitizes stored content again, runs app transforms, and adds the configured classes, so the admin preview and the public page render the same markup. The editor bundle reads the same configuration from ClientConfig.

The package does not import github.com/fletchhq/sight; a public site can render content without linking the admin panel.

Index

Constants

View Source
const DefaultMaxBytes = 1 << 20

DefaultMaxBytes is the default input size limit.

Variables

View Source
var (
	// ErrTooLarge is returned for input over the size limit.
	ErrTooLarge = errors.New("richtext: input exceeds the size limit")
	// ErrTooDeep is returned for markup nested deeper than the HTML parser
	// accepts.
	ErrTooDeep = errors.New("richtext: content nests too deeply")
)
View Source
var ErrTooComplex = errors.New("richtext: markdown has too much emphasis markup in one block")

ErrTooComplex is returned for Markdown whose emphasis markup would make rendering slow.

Functions

This section is empty.

Types

type Align

type Align struct{ Left, Center, Right string }

Align maps GFM column alignment to classes. No style or align attribute reaches rendered output.

type Classes

type Classes map[Element]string

Classes maps elements to space-separated class names. A token may hold any printable non-space character except quotes, <, >, and backtick, so Tailwind tokens such as md:text-[1.1rem] work. Content never stores these classes: Render adds them.

type Element

type Element string

Element names a content element for class mapping.

const (
	H1           Element = "h1"
	H2           Element = "h2"
	H3           Element = "h3"
	H4           Element = "h4"
	H5           Element = "h5"
	H6           Element = "h6"
	P            Element = "p"
	UL           Element = "ul"
	OL           Element = "ol"
	LI           Element = "li"
	Blockquote   Element = "blockquote"
	HR           Element = "hr"
	Pre          Element = "pre"
	PreCode      Element = "pre>code"
	Code         Element = "code"
	A            Element = "a"
	Img          Element = "img"
	Table        Element = "table"
	THead        Element = "thead"
	TBody        Element = "tbody"
	TR           Element = "tr"
	TH           Element = "th"
	TD           Element = "td"
	Strong       Element = "strong"
	Em           Element = "em"
	Del          Element = "del"
	U            Element = "u"
	TaskList     Element = "ul.task"
	TaskItem     Element = "li.task"
	TaskCheckbox Element = "input.task"
)

The elements content may hold. PreCode is the code element of a fenced block and Code is inline code. TaskList, TaskItem, and TaskCheckbox are the ul, li, and input of a GFM task list; their classes are added to the UL, LI, and checkbox classes.

type ExternalLinks struct {
	// Target is "" or "_blank".
	Target string
	// Rel defaults to "noopener noreferrer nofollow". With Target "_blank",
	// noopener is always added.
	Rel string
}

ExternalLinks holds the attributes Render adds to external links.

type Feature

type Feature string

Feature names an editing feature. A disabled feature's markup is dropped on save and render, keeping its text.

const (
	Bold           Feature = "bold"
	Italic         Feature = "italic"
	Underline      Feature = "underline"
	Strike         Feature = "strike"
	InlineCode     Feature = "code"
	Link           Feature = "link"
	Image          Feature = "image"
	Heading        Feature = "heading"
	BulletList     Feature = "bulletList"
	OrderedList    Feature = "orderedList"
	Tasks          Feature = "taskList"
	Quote          Feature = "blockquote"
	CodeBlock      Feature = "codeBlock"
	HorizontalRule Feature = "hr"
	Tables         Feature = "table"
	HardBreak      Feature = "hardBreak"
)

The features. Their values are the names the editor's JSON config uses.

type Images

type Images struct {
	// Hosts lists the absolute hosts allowed in src. Relative paths are
	// always allowed; an absolute or protocol-relative src on another host
	// removes the image.
	Hosts []string
	// Lazy adds loading="lazy" decoding="async". It is on when WithImages
	// is not used; a value passed to WithImages is taken as given.
	Lazy bool
}

Images configures image URLs.

type Links struct {
	// Schemes lists the allowed URL schemes. Default: http, https, mailto,
	// tel. Relative URLs are always allowed.
	Schemes []string
	// SiteHosts lists hosts treated as internal, besides relative URLs.
	SiteHosts []string
	// External sets the attributes of links to other hosts.
	External ExternalLinks
}

Links configures link URLs and the attributes of external links.

type Mode

type Mode uint8

Mode is the storage format of a field.

const (
	// Markdown stores GFM text.
	Markdown Mode = iota + 1
	// HTML stores canonical, classless, sanitized semantic HTML.
	HTML
)

func (Mode) String

func (m Mode) String() string

type Option

type Option func(*settings)

Option configures a Renderer.

func WithAlign

func WithAlign(a Align) Option

WithAlign sets the classes for left, center, and right table columns.

func WithClasses

func WithClasses(c Classes) Option

WithClasses sets the classes Render adds to each element.

func WithFeatures

func WithFeatures(fs ...Feature) Option

WithFeatures limits the features. The default is every feature valid for the mode.

func WithHeadingIDs

func WithHeadingIDs(prefix string) Option

WithHeadingIDs makes Render give headings ids built from their text. Every id starts with prefix, so content cannot clobber page globals.

func WithHeadings

func WithHeadings(levels ...int) Option

WithHeadings limits heading levels; the default is 1 to 6. Other levels become the nearest deeper allowed level, or the deepest allowed one.

func WithImages

func WithImages(i Images) Option

WithImages configures image hosts and lazy loading.

func WithLinks(l Links) Option

WithLinks configures link schemes, internal hosts, and external links.

func WithMaxBytes

func WithMaxBytes(n int) Option

WithMaxBytes sets the input size limit; the default is DefaultMaxBytes.

func WithRawHTML

func WithRawHTML() Option

WithRawHTML lets Markdown carry raw HTML. It then goes through the same sanitizer as everything else. Markdown mode only.

func WithTransform

func WithTransform(fn func(root *html.Node) error) Option

WithTransform adds a trusted hook that Render runs on the sanitized tree, before classes are added. root is a document node whose children are the content. A hook may add elements; the final check still rejects scripts, event handlers, inline styles, and unsafe URLs.

type Renderer

type Renderer struct {
	// contains filtered or unexported fields
}

Renderer renders and cleans rich text for one field configuration. It is immutable and safe for concurrent use.

func MustNew

func MustNew(mode Mode, opts ...Option) *Renderer

MustNew is New that panics on a configuration error, for package-level renderers.

func New

func New(mode Mode, opts ...Option) (*Renderer, error)

New returns a Renderer for mode. Every configuration error is reported, joined into one error.

func (*Renderer) Clean

func (r *Renderer) Clean(src string) (string, error)

Clean is the save path. HTML mode returns canonical, classless, sanitized HTML. Markdown mode normalizes line endings and invalid UTF-8 and checks that the text renders; it is otherwise stored as written, since rendering sanitizes it.

func (*Renderer) ClientConfig

func (r *Renderer) ClientConfig() []byte

ClientConfig returns the JSON the editor reads from data-config.

func (*Renderer) Features

func (r *Renderer) Features() []Feature

Features returns the enabled features in a stable order.

func (*Renderer) Has

func (r *Renderer) Has(f Feature) bool

Has reports whether f is enabled.

func (*Renderer) Headings

func (r *Renderer) Headings() []int

Headings returns the allowed heading levels.

func (*Renderer) Images

func (r *Renderer) Images() Images

Images returns the effective image configuration, defaults applied.

func (r *Renderer) Links() Links

Links returns the effective link configuration, defaults applied.

func (*Renderer) MaxBytes

func (r *Renderer) MaxBytes() int

MaxBytes returns the input size limit.

func (*Renderer) Mode

func (r *Renderer) Mode() Mode

Mode returns the storage mode.

func (*Renderer) Render

func (r *Renderer) Render(_ context.Context, src string) (crest.Component, error)

Render produces display HTML: sanitize, run transforms, add classes and link and image attributes. Its signature matches sight.WithMarkdown.

func (*Renderer) RenderString

func (r *Renderer) RenderString(src string) (string, error)

RenderString is Render returning a string.

func (*Renderer) Text

func (r *Renderer) Text(src string) string

Text returns the visible text: block boundaries become newlines and runs of spaces collapse. It suits excerpts, search, and length limits. Input that fails to render yields "".

Directories

Path Synopsis
Package editor is the WYSIWYG rich text widget for Sight string fields.
Package editor is the WYSIWYG rich text widget for Sight string fields.

Jump to

Keyboard shortcuts

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