gui: native WebView host as nested module yetano.dev/yetano/core/gui
Extracted from prototypes/yetano-webview (AP1): packages assets, document, bridge and window (macOS Cocoa/WKWebView via cgo, Windows Win32/WebView2 pure Go). No local HTTP listener or port: assets go through the WebView's resource handler, app routes through the native message binding. Own go.mod and gui/vX.Y.Z tags keep cgo and the WebView dependencies out of the main core module. Adds backend-free tests for the window's dispatch/destroy guards and a yet-gui migration guide. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
90132e2d76
commit
8c63d42a27
27 files changed
+4849
-3
No files matched your search
@@ -0,0 +1,295 @@
|
||||
// Package document prepares HTML for display: every "/assets/..." and
|
||||
// "assets:..." reference in HTML attributes, <style> blocks, style="" and
|
||||
// referenced CSS (url(), @import) is resolved through the asset resolver and
|
||||
// replaced by a typed data: URL.
|
||||
//
|
||||
// HTML is processed with the golang.org/x/net/html tokenizer. Tokens that are
|
||||
// not changed are copied byte for byte (comments, entities, scripts, void
|
||||
// tags and formatting stay as written); only a changed start tag is
|
||||
// re-serialized.
|
||||
package document
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/net/html"
|
||||
|
||||
"yetano.dev/yetano/core/gui/assets"
|
||||
)
|
||||
|
||||
// DefaultMaxOutput bounds the prepared document. Data-URL navigation and
|
||||
// NavigateToString have backend limits (WebView2: 2 MB); large binaries such
|
||||
// as Go-WASM are meant to be fetched separately, not inlined.
|
||||
const DefaultMaxOutput = 1536 << 10
|
||||
|
||||
// Replacement records one rewritten reference (diagnostics).
|
||||
type Replacement struct {
|
||||
Ref string `json:"ref"`
|
||||
Asset string `json:"asset"`
|
||||
Source string `json:"source"`
|
||||
MIME string `json:"mime"`
|
||||
Size int `json:"size"`
|
||||
In string `json:"in"`
|
||||
}
|
||||
|
||||
// Result is a prepared HTML document or fragment.
|
||||
type Result struct {
|
||||
HTML []byte
|
||||
Replacements []Replacement
|
||||
}
|
||||
|
||||
// Options for Prepare.
|
||||
type Options struct {
|
||||
MaxOutput int // 0 = DefaultMaxOutput (inline mode only)
|
||||
// Link keeps resources as URLs instead of inlining them: "assets:x"
|
||||
// becomes "/assets/x", "/assets/x" stays, relative CSS references stay.
|
||||
// Every reference is still validated against the resolver. This is the
|
||||
// mode for the native resource handler, where the WebView loads each
|
||||
// resource itself.
|
||||
Link bool
|
||||
}
|
||||
|
||||
type preparer struct {
|
||||
link bool
|
||||
res *assets.Resolver
|
||||
entry string // virtual name of the HTML being prepared (diagnostics)
|
||||
cssStack []string
|
||||
repl []Replacement
|
||||
}
|
||||
|
||||
// Prepare rewrites an HTML document or fragment. entry names the source for
|
||||
// error messages (an asset path or e.g. "fragment:/fragment/card").
|
||||
func Prepare(ctx context.Context, res *assets.Resolver, entry string, src []byte, opt Options) (*Result, error) {
|
||||
r, err := prepare(ctx, res, entry, src, opt)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("prepare %s: %w", entry, err)
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func prepare(ctx context.Context, res *assets.Resolver, entry string, src []byte, opt Options) (*Result, error) {
|
||||
if opt.MaxOutput == 0 {
|
||||
opt.MaxOutput = DefaultMaxOutput
|
||||
}
|
||||
if opt.Link {
|
||||
opt.MaxOutput = 1 << 30
|
||||
}
|
||||
p := &preparer{res: res, entry: entry, link: opt.Link}
|
||||
var out bytes.Buffer
|
||||
z := html.NewTokenizer(bytes.NewReader(src))
|
||||
inStyle := false
|
||||
for {
|
||||
tt := z.Next()
|
||||
if tt == html.ErrorToken {
|
||||
if z.Err() == io.EOF {
|
||||
break
|
||||
}
|
||||
return nil, fmt.Errorf("html: %w", z.Err())
|
||||
}
|
||||
raw := z.Raw()
|
||||
switch tt {
|
||||
case html.StartTagToken, html.SelfClosingTagToken:
|
||||
tok := z.Token()
|
||||
changed, err := p.rewriteTag(ctx, &tok)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if changed {
|
||||
out.WriteString(tok.String())
|
||||
} else {
|
||||
out.Write(raw)
|
||||
}
|
||||
inStyle = tt == html.StartTagToken && tok.Data == "style"
|
||||
case html.TextToken:
|
||||
if inStyle {
|
||||
css, err := p.rewriteCSS(ctx, string(raw), "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.Contains(strings.ToLower(css), "</style") {
|
||||
return nil, fmt.Errorf("rewritten <style> would contain </style")
|
||||
}
|
||||
out.WriteString(css)
|
||||
} else {
|
||||
out.Write(raw)
|
||||
}
|
||||
case html.EndTagToken:
|
||||
inStyle = false
|
||||
out.Write(raw)
|
||||
default:
|
||||
out.Write(raw)
|
||||
}
|
||||
if out.Len() > opt.MaxOutput {
|
||||
return nil, fmt.Errorf("prepared document exceeds %d bytes; load large assets via fetch instead of inlining", opt.MaxOutput)
|
||||
}
|
||||
}
|
||||
return &Result{HTML: out.Bytes(), Replacements: p.repl}, nil
|
||||
}
|
||||
|
||||
func (p *preparer) rewriteTag(ctx context.Context, tok *html.Token) (bool, error) {
|
||||
changed := false
|
||||
rel := ""
|
||||
for _, a := range tok.Attr {
|
||||
if a.Namespace == "" && a.Key == "rel" {
|
||||
rel = " " + strings.ToLower(a.Val) + " "
|
||||
}
|
||||
}
|
||||
for i := range tok.Attr {
|
||||
a := &tok.Attr[i]
|
||||
if a.Namespace != "" {
|
||||
continue
|
||||
}
|
||||
var nv string
|
||||
var err error
|
||||
did := false
|
||||
switch {
|
||||
case a.Key == "style":
|
||||
nv, err = p.rewriteCSS(ctx, a.Val, "")
|
||||
did = nv != a.Val
|
||||
case a.Key == "srcset" && (tok.Data == "img" || tok.Data == "source"):
|
||||
nv, did, err = p.rewriteSrcset(ctx, a.Val)
|
||||
case assets.IsAssetRef(strings.TrimSpace(a.Val)) && urlAttr(tok.Data, a.Key):
|
||||
ref := strings.TrimSpace(a.Val)
|
||||
if tok.Data == "link" && a.Key == "href" && strings.Contains(rel, " stylesheet ") {
|
||||
nv, err = p.stylesheetURL(ctx, ref)
|
||||
} else {
|
||||
nv, err = p.refDataURL(ctx, ref)
|
||||
}
|
||||
did = true
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if did {
|
||||
a.Val = nv
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
// urlAttr lists the element/attribute pairs whose asset references load a
|
||||
// resource. Navigation targets (<a href>) are deliberately not inlined.
|
||||
func urlAttr(tag, key string) bool {
|
||||
switch key {
|
||||
case "src":
|
||||
switch tag {
|
||||
case "img", "script", "source", "audio", "video", "track", "input", "iframe", "embed":
|
||||
return true
|
||||
}
|
||||
case "href":
|
||||
return tag == "link" || tag == "image" || tag == "use"
|
||||
case "poster":
|
||||
return tag == "video"
|
||||
case "data":
|
||||
return tag == "object"
|
||||
case "xlink:href":
|
||||
return tag == "image" || tag == "use"
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *preparer) rewriteSrcset(ctx context.Context, v string) (string, bool, error) {
|
||||
parts := strings.Split(v, ",")
|
||||
changed := false
|
||||
for i, part := range parts {
|
||||
f := strings.Fields(part)
|
||||
if len(f) == 0 || !assets.IsAssetRef(f[0]) {
|
||||
continue
|
||||
}
|
||||
d, err := p.refDataURL(ctx, f[0])
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
f[0] = d
|
||||
parts[i] = strings.Join(f, " ")
|
||||
changed = true
|
||||
}
|
||||
return strings.Join(parts, ", "), changed, nil
|
||||
}
|
||||
|
||||
func (p *preparer) stylesheetURL(ctx context.Context, ref string) (string, error) {
|
||||
name, err := assets.FromRef(ref)
|
||||
if err != nil {
|
||||
return "", p.fail(p.entry, ref, err)
|
||||
}
|
||||
if p.link {
|
||||
return p.assetDataURL(ctx, name, p.entry)
|
||||
}
|
||||
css, err := p.loadCSS(ctx, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
p.repl = append(p.repl, Replacement{Ref: ref, Asset: name, MIME: "text/css", Size: len(css), In: p.entry})
|
||||
return dataURL("text/css;charset=utf-8", []byte(css)), nil
|
||||
}
|
||||
|
||||
func (p *preparer) refDataURL(ctx context.Context, ref string) (string, error) {
|
||||
name, err := assets.FromRef(ref)
|
||||
if err != nil {
|
||||
return "", p.fail(p.entry, ref, err)
|
||||
}
|
||||
if assets.BaseMIME(mimeOf(name)) == "text/css" {
|
||||
return p.stylesheetURL(ctx, ref)
|
||||
}
|
||||
return p.assetDataURL(ctx, name, p.entry)
|
||||
}
|
||||
|
||||
func (p *preparer) assetDataURL(ctx context.Context, name, in string) (string, error) {
|
||||
if in == "" {
|
||||
in = p.entry
|
||||
}
|
||||
r, err := p.resolve(ctx, name, in)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
p.repl = append(p.repl, Replacement{Ref: name, Asset: name, Source: r.Source, MIME: r.MIME, Size: len(r.Bytes), In: in})
|
||||
if p.link {
|
||||
return assets.PrefixSlash + name, nil
|
||||
}
|
||||
m := strings.ReplaceAll(r.MIME, " ", "")
|
||||
return dataURL(m, r.Bytes), nil
|
||||
}
|
||||
|
||||
func (p *preparer) resolve(ctx context.Context, name, in string) (*assets.Resource, error) {
|
||||
r, err := p.res.Resolve(ctx, name)
|
||||
if err != nil {
|
||||
if in != p.entry {
|
||||
return nil, fmt.Errorf("%s: %w", in, err)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (p *preparer) fail(in, ref string, err error) error {
|
||||
if in == "" || in == p.entry {
|
||||
return fmt.Errorf("reference %q: %w", ref, err)
|
||||
}
|
||||
return fmt.Errorf("%s: reference %q: %w", in, ref, err)
|
||||
}
|
||||
|
||||
// PrepareCSS rewrites a stylesheet asset served on its own (link mode for
|
||||
// the native resource handler, inline mode otherwise).
|
||||
func PrepareCSS(ctx context.Context, res *assets.Resolver, name string, css []byte, opt Options) ([]byte, error) {
|
||||
p := &preparer{res: res, entry: name, link: opt.Link}
|
||||
out, err := p.rewriteCSS(ctx, string(css), name)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("prepare %s: %w", name, err)
|
||||
}
|
||||
return []byte(out), nil
|
||||
}
|
||||
|
||||
func dataURL(mime string, data []byte) string {
|
||||
return "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(data)
|
||||
}
|
||||
|
||||
func mimeOf(name string) string {
|
||||
m, _ := assets.DetectMIME(name, nil)
|
||||
return m
|
||||
}
|
||||
Reference in new issue
Block a user