feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
@@ -0,0 +1,212 @@
|
||||
// Package frontend is what the updater shares with the windows that show
|
||||
// its sessions: package updater shows them in a web page, package native
|
||||
// in native UI.
|
||||
package frontend
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"sync"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/plugins/updater/internal/markdown"
|
||||
)
|
||||
|
||||
// Session is a check for updates and what follows it, as its window sees
|
||||
// it.
|
||||
type Session interface {
|
||||
// NewWindow creates the session's window, hidden, showing content, or
|
||||
// a web page when content is nil. The session resizes it for its
|
||||
// views and closes it when it ends.
|
||||
NewWindow(content mygo.Content) *mygo.Window
|
||||
// Current returns the view to show and a channel closed when it
|
||||
// changes.
|
||||
Current() (View, <-chan struct{})
|
||||
// Done is closed when the session ends or its window closes.
|
||||
Done() <-chan struct{}
|
||||
// Respond answers the prompt of a view with a button, and tells
|
||||
// whether updates may be installed automatically from now on. Only
|
||||
// the first response to a prompt counts.
|
||||
Respond(prompt int, a Action, automaticDownloads bool)
|
||||
// Fit gives the window the width its buttons need, when they need
|
||||
// more than the usual width, and a status view the height of its
|
||||
// content, in DIPs.
|
||||
Fit(width, height int)
|
||||
// Texts returns the texts of the window that views leave out.
|
||||
Texts() Texts
|
||||
// Icon returns the PNG image of the window, or nil.
|
||||
Icon() []byte
|
||||
// User reports whether the user asked for the check: the window shows
|
||||
// in front.
|
||||
User() bool
|
||||
}
|
||||
|
||||
// Open creates the window of a session and shows it, at once or once it
|
||||
// is ready to.
|
||||
type Open func(s Session)
|
||||
|
||||
// Plugin returns the updater plugin with opts, an updater.Options, whose
|
||||
// windows open creates. Package updater sets it.
|
||||
var Plugin func(opts any, open Open) mygo.Plugin
|
||||
|
||||
// Show shows win as Sparkle shows its update alert: in front, with the
|
||||
// keyboard, when the user asked for the check or the app is active. A check
|
||||
// in the background takes the keyboard from no other app: on macOS win
|
||||
// waits until the app becomes active, unless the app has no Dock icon and
|
||||
// so may never be, which comes to the front; elsewhere it shows without
|
||||
// the keyboard.
|
||||
func Show(win *mygo.Window, user bool) { show(win, user) }
|
||||
|
||||
// The app as Show sees it, which tests swap.
|
||||
var (
|
||||
goos = runtime.GOOS
|
||||
appActive = mygo.App.IsActive
|
||||
activationPolicy = mygo.App.ActivationPolicy
|
||||
focusApp = mygo.App.Focus
|
||||
onAppActive = mygo.App.OnDidBecomeActive
|
||||
)
|
||||
|
||||
// window is what Show does with a *mygo.Window.
|
||||
type window interface {
|
||||
Show()
|
||||
ShowInactive()
|
||||
Focus()
|
||||
IsVisible() bool
|
||||
OnClosed(fn func()) (off func())
|
||||
}
|
||||
|
||||
func show(win window, user bool) {
|
||||
switch {
|
||||
case user || appActive():
|
||||
case goos != "darwin":
|
||||
win.ShowInactive()
|
||||
return
|
||||
case activationPolicy() != mygo.ActivationPolicyRegular:
|
||||
focusApp()
|
||||
default:
|
||||
showWhenActive(win)
|
||||
return
|
||||
}
|
||||
win.Show()
|
||||
win.Focus()
|
||||
}
|
||||
|
||||
// showWhenActive shows win in front once the app becomes active, unless
|
||||
// it closed first or the user had it shown already.
|
||||
func showWhenActive(win window) {
|
||||
var mu sync.Mutex
|
||||
var offs []func()
|
||||
done := false
|
||||
// end stops waiting, and shows win when front is set. Only its first
|
||||
// call counts.
|
||||
end := func(front bool) {
|
||||
mu.Lock()
|
||||
if done {
|
||||
mu.Unlock()
|
||||
return
|
||||
}
|
||||
done = true
|
||||
for _, off := range offs {
|
||||
off()
|
||||
}
|
||||
mu.Unlock()
|
||||
if front && !win.IsVisible() {
|
||||
win.Show()
|
||||
win.Focus()
|
||||
}
|
||||
}
|
||||
mu.Lock()
|
||||
offs = append(offs, onAppActive(func() { end(true) }), win.OnClosed(func() { end(false) }))
|
||||
mu.Unlock()
|
||||
// The app may have become active before it was watched.
|
||||
if appActive() {
|
||||
end(true)
|
||||
}
|
||||
}
|
||||
|
||||
// Action is a button of the update window.
|
||||
type Action string
|
||||
|
||||
const (
|
||||
OK Action = "ok"
|
||||
Cancel Action = "cancel"
|
||||
Skip Action = "skip"
|
||||
Later Action = "later"
|
||||
Install Action = "install"
|
||||
Relaunch Action = "relaunch"
|
||||
// Close is the window closing, not a button.
|
||||
Close Action = "close"
|
||||
)
|
||||
|
||||
// View is what the update window shows.
|
||||
type View struct {
|
||||
// Prompt changes with the buttons: responses name the prompt they
|
||||
// answer, so that none answers a later one.
|
||||
Prompt int `json:"prompt"`
|
||||
// Release views show release notes, in a larger window.
|
||||
Release bool `json:"release,omitzero"`
|
||||
Title string `json:"title"`
|
||||
Message string `json:"message,omitzero"`
|
||||
// Detail is the error of a failure.
|
||||
Detail string `json:"detail,omitzero"`
|
||||
// Notes are the release notes.
|
||||
Notes []markdown.Block `json:"-"`
|
||||
// Bar shows a progress bar with Progress, between 0 and 1, or -1 when
|
||||
// the progress is unknown.
|
||||
Bar bool `json:"bar,omitzero"`
|
||||
Progress float64 `json:"progress,omitzero"`
|
||||
// Checkbox offers to download and install updates automatically,
|
||||
// Checked or not.
|
||||
Checkbox bool `json:"checkbox,omitzero"`
|
||||
Checked bool `json:"checked,omitzero"`
|
||||
Buttons []Button `json:"buttons"`
|
||||
}
|
||||
|
||||
// Button is a button of a view.
|
||||
type Button struct {
|
||||
Action Action `json:"action"`
|
||||
Label string `json:"label"`
|
||||
// Default is the button of Enter, Cancel the one of Escape.
|
||||
Default bool `json:"default,omitzero"`
|
||||
Cancel bool `json:"cancel,omitzero"`
|
||||
// Aside sets the button apart, on the left.
|
||||
Aside bool `json:"aside,omitzero"`
|
||||
Disabled bool `json:"disabled,omitzero"`
|
||||
}
|
||||
|
||||
// Texts are the texts of the window around its views, in the language of
|
||||
// the window.
|
||||
type Texts struct {
|
||||
// Title is the title of the window, ReleaseNotes the heading of the
|
||||
// notes and AutomaticDownloads the label of the checkbox.
|
||||
Title, ReleaseNotes, AutomaticDownloads string
|
||||
// Lang is the language, such as "zh-Hans", and RTL is set for those
|
||||
// written from right to left.
|
||||
Lang string
|
||||
RTL bool
|
||||
}
|
||||
|
||||
// The size of the update window's content, for status views and for views
|
||||
// with release notes.
|
||||
const (
|
||||
StatusWidth, StatusHeight = 480, 148
|
||||
ReleaseWidth, ReleaseHeight = 620, 440
|
||||
)
|
||||
|
||||
// Size returns the size of the window's content for a status view or a
|
||||
// release view.
|
||||
func Size(release bool) (width, height int) {
|
||||
if release {
|
||||
return ReleaseWidth, ReleaseHeight
|
||||
}
|
||||
return StatusWidth, StatusHeight
|
||||
}
|
||||
|
||||
// Background returns the light and dark colors of the update window: the
|
||||
// gray of dialogs on macOS, and white elsewhere, where the title bar above
|
||||
// it is light.
|
||||
func Background() (light, dark string) {
|
||||
if runtime.GOOS == "darwin" {
|
||||
return "#ececec", "#1e1e1e"
|
||||
}
|
||||
return "#fff", "#1e1e1e"
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package frontend
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
)
|
||||
|
||||
type fakeWindow struct {
|
||||
visible, focused, inactive bool
|
||||
closed []func()
|
||||
}
|
||||
|
||||
func (w *fakeWindow) Show() { w.visible = true }
|
||||
func (w *fakeWindow) ShowInactive() { w.visible, w.inactive = true, true }
|
||||
func (w *fakeWindow) Focus() { w.focused = true }
|
||||
func (w *fakeWindow) IsVisible() bool { return w.visible }
|
||||
func (w *fakeWindow) OnClosed(fn func()) func() {
|
||||
w.closed = append(w.closed, fn)
|
||||
return func() { w.closed = nil }
|
||||
}
|
||||
|
||||
// fakeApp is the app as Show sees it, on GOOS os, until the test ends.
|
||||
type fakeApp struct {
|
||||
active, focused bool
|
||||
policy mygo.ActivationPolicy
|
||||
listeners []func()
|
||||
}
|
||||
|
||||
func useApp(t *testing.T, os string) *fakeApp {
|
||||
a := &fakeApp{policy: mygo.ActivationPolicyRegular}
|
||||
prev := [...]any{goos, appActive, activationPolicy, focusApp, onAppActive}
|
||||
goos = os
|
||||
appActive = func() bool { return a.active }
|
||||
activationPolicy = func() mygo.ActivationPolicy { return a.policy }
|
||||
focusApp = func() { a.focused = true }
|
||||
onAppActive = func(fn func()) func() {
|
||||
a.listeners = append(a.listeners, fn)
|
||||
return func() { a.listeners = nil }
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
goos = prev[0].(string)
|
||||
appActive = prev[1].(func() bool)
|
||||
activationPolicy = prev[2].(func() mygo.ActivationPolicy)
|
||||
focusApp = prev[3].(func())
|
||||
onAppActive = prev[4].(func(func()) func())
|
||||
})
|
||||
return a
|
||||
}
|
||||
|
||||
func (a *fakeApp) activate() {
|
||||
a.active = true
|
||||
for _, fn := range a.listeners {
|
||||
fn()
|
||||
}
|
||||
}
|
||||
|
||||
// A background check while the app is active shows the window in front, with
|
||||
// the keyboard, as Sparkle does; it used to show it behind the app's window.
|
||||
func TestShowActiveApp(t *testing.T) {
|
||||
for _, os := range []string{"darwin", "windows", "linux"} {
|
||||
a := useApp(t, os)
|
||||
a.active = true
|
||||
w := &fakeWindow{}
|
||||
show(w, false)
|
||||
if !w.visible || !w.focused {
|
||||
t.Errorf("%s: visible %v, focused %v; want the window in front", os, w.visible, w.focused)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// On macOS a background check while another app is in front waits for the
|
||||
// app to become active, then shows the window in front, once.
|
||||
func TestShowWaitsForActivation(t *testing.T) {
|
||||
a := useApp(t, "darwin")
|
||||
w := &fakeWindow{}
|
||||
show(w, false)
|
||||
if w.visible {
|
||||
t.Fatal("the window showed while the app was in the background")
|
||||
}
|
||||
a.activate()
|
||||
if !w.visible || !w.focused || w.inactive {
|
||||
t.Fatalf("visible %v, focused %v, inactive %v once active; want it in front", w.visible, w.focused, w.inactive)
|
||||
}
|
||||
if len(a.listeners) != 0 || len(w.closed) != 0 {
|
||||
t.Error("still watching the app after showing the window")
|
||||
}
|
||||
}
|
||||
|
||||
// A window closed while it waits for the app, as when its session ends,
|
||||
// never shows.
|
||||
func TestShowClosedWhileWaiting(t *testing.T) {
|
||||
a := useApp(t, "darwin")
|
||||
w := &fakeWindow{}
|
||||
show(w, false)
|
||||
for _, fn := range w.closed {
|
||||
fn()
|
||||
}
|
||||
a.activate()
|
||||
if w.visible {
|
||||
t.Error("a closed window showed when the app became active")
|
||||
}
|
||||
}
|
||||
|
||||
// An app without a Dock icon may never become active by itself, so a
|
||||
// background check brings it to the front with the window, as Sparkle does.
|
||||
func TestShowAccessoryApp(t *testing.T) {
|
||||
a := useApp(t, "darwin")
|
||||
a.policy = mygo.ActivationPolicyAccessory
|
||||
w := &fakeWindow{}
|
||||
show(w, false)
|
||||
if !a.focused || !w.visible || !w.focused {
|
||||
t.Errorf("app focused %v, window visible %v, focused %v; want both in front", a.focused, w.visible, w.focused)
|
||||
}
|
||||
}
|
||||
|
||||
// Elsewhere a background check while another app is in front shows the
|
||||
// window without the keyboard.
|
||||
func TestShowInactiveElsewhere(t *testing.T) {
|
||||
useApp(t, "windows")
|
||||
w := &fakeWindow{}
|
||||
show(w, false)
|
||||
if !w.visible || w.focused {
|
||||
t.Errorf("visible %v, focused %v; want it shown without the keyboard", w.visible, w.focused)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,534 @@
|
||||
// Package markdown parses the release notes of the update window. It
|
||||
// knows what changelogs use: headings, paragraphs, nested lists, block
|
||||
// quotes, fenced code, rules, emphasis, code spans and links. Everything
|
||||
// else is text: raw HTML stays text, and links only go to http, https and
|
||||
// mailto URLs, so notes cannot run code in the window.
|
||||
package markdown
|
||||
|
||||
import (
|
||||
"html"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// BlockKind is what a Block is.
|
||||
type BlockKind uint8
|
||||
|
||||
const (
|
||||
Paragraph BlockKind = iota
|
||||
Heading
|
||||
List
|
||||
Quote
|
||||
Code
|
||||
Rule
|
||||
)
|
||||
|
||||
// Block is a block of release notes.
|
||||
type Block struct {
|
||||
Kind BlockKind
|
||||
// Level is the level of a heading, from 1 to 6.
|
||||
Level int
|
||||
// Inlines are the text of a paragraph or heading.
|
||||
Inlines []Inline
|
||||
// Text is the text of fenced code.
|
||||
Text string
|
||||
// Ordered is set for a numbered list, whose Items hold the blocks of
|
||||
// each item; Blocks are those of a quote.
|
||||
Ordered bool
|
||||
Items [][]Block
|
||||
Blocks []Block
|
||||
}
|
||||
|
||||
// InlineKind is what an Inline is.
|
||||
type InlineKind uint8
|
||||
|
||||
const (
|
||||
Text InlineKind = iota
|
||||
CodeSpan
|
||||
Emphasis
|
||||
Strong
|
||||
Link
|
||||
)
|
||||
|
||||
// Inline is a run of text in a paragraph or heading.
|
||||
type Inline struct {
|
||||
Kind InlineKind
|
||||
// Text is the text of a Text or CodeSpan.
|
||||
Text string
|
||||
// Children are the text of an Emphasis, Strong or Link.
|
||||
Children []Inline
|
||||
// URL is where a Link goes: an http, https or mailto URL.
|
||||
URL string
|
||||
}
|
||||
|
||||
// Parse parses release notes.
|
||||
func Parse(src string) []Block {
|
||||
src = strings.ReplaceAll(src, "\r\n", "\n")
|
||||
src = strings.ReplaceAll(src, "\t", " ")
|
||||
return parseBlocks(strings.Split(src, "\n"))
|
||||
}
|
||||
|
||||
// parseBlocks parses lines as blocks.
|
||||
func parseBlocks(lines []string) []Block {
|
||||
var blocks []Block
|
||||
var para []string
|
||||
flush := func() {
|
||||
if len(para) > 0 {
|
||||
blocks = append(blocks, Block{Kind: Paragraph, Inlines: parseInline(strings.Join(para, "\n"))})
|
||||
para = nil
|
||||
}
|
||||
}
|
||||
for i := 0; i < len(lines); {
|
||||
line := lines[i]
|
||||
trimmed := strings.TrimSpace(line)
|
||||
switch {
|
||||
case trimmed == "":
|
||||
flush()
|
||||
i++
|
||||
case isFence(trimmed):
|
||||
flush()
|
||||
fence := trimmed[:3]
|
||||
var code []string
|
||||
for i++; i < len(lines) && !strings.HasPrefix(strings.TrimSpace(lines[i]), fence); i++ {
|
||||
code = append(code, lines[i])
|
||||
}
|
||||
i++
|
||||
blocks = append(blocks, Block{Kind: Code, Text: strings.Join(code, "\n")})
|
||||
case heading(trimmed) > 0:
|
||||
flush()
|
||||
n := heading(trimmed)
|
||||
text := strings.TrimRight(strings.TrimSpace(trimmed[n:]), "#")
|
||||
blocks = append(blocks, Block{Kind: Heading, Level: n, Inlines: parseInline(strings.TrimSpace(text))})
|
||||
i++
|
||||
case isRule(trimmed):
|
||||
flush()
|
||||
blocks = append(blocks, Block{Kind: Rule})
|
||||
i++
|
||||
case strings.HasPrefix(trimmed, ">"):
|
||||
flush()
|
||||
var quote []string
|
||||
for ; i < len(lines) && strings.HasPrefix(strings.TrimSpace(lines[i]), ">"); i++ {
|
||||
q := strings.TrimPrefix(strings.TrimSpace(lines[i]), ">")
|
||||
quote = append(quote, strings.TrimPrefix(q, " "))
|
||||
}
|
||||
blocks = append(blocks, Block{Kind: Quote, Blocks: parseBlocks(quote)})
|
||||
default:
|
||||
if _, _, ok := listMarker(line); ok && (len(para) == 0 || startsList(line)) {
|
||||
flush()
|
||||
var list Block
|
||||
list, i = parseList(lines, i)
|
||||
blocks = append(blocks, list)
|
||||
continue
|
||||
}
|
||||
para = append(para, trimmed)
|
||||
i++
|
||||
}
|
||||
}
|
||||
flush()
|
||||
return blocks
|
||||
}
|
||||
|
||||
// parseList parses the list starting at lines[i] and returns it with the
|
||||
// index of the line after it.
|
||||
func parseList(lines []string, i int) (Block, int) {
|
||||
indent, ordered, _ := listMarker(lines[i])
|
||||
list := Block{Kind: List, Ordered: ordered}
|
||||
for i < len(lines) {
|
||||
ind, ord, ok := listMarker(lines[i])
|
||||
if !ok || ind != indent || ord != ordered {
|
||||
break
|
||||
}
|
||||
// The item holds the rest of its first line, the lines indented to
|
||||
// its content, lists nested less deep than that, and the lines
|
||||
// that continue its paragraph.
|
||||
width := markerWidth(lines[i])
|
||||
item := []string{lines[i][width:]}
|
||||
blank := false
|
||||
lines:
|
||||
for i++; i < len(lines); i++ {
|
||||
line := lines[i]
|
||||
if strings.TrimSpace(line) == "" {
|
||||
blank = true
|
||||
item = append(item, "")
|
||||
continue
|
||||
}
|
||||
ind := leadingSpaces(line)
|
||||
_, _, marker := listMarker(line)
|
||||
switch {
|
||||
case ind >= width:
|
||||
item = append(item, line[width:])
|
||||
case ind > indent && marker:
|
||||
item = append(item, line[ind:])
|
||||
case !blank && !marker && !isBlockStart(line):
|
||||
item = append(item, strings.TrimSpace(line))
|
||||
default:
|
||||
break lines
|
||||
}
|
||||
blank = false
|
||||
}
|
||||
for len(item) > 0 && item[len(item)-1] == "" {
|
||||
item = item[:len(item)-1]
|
||||
}
|
||||
list.Items = append(list.Items, parseBlocks(item))
|
||||
}
|
||||
return list, i
|
||||
}
|
||||
|
||||
// listMarker reports whether line starts a list item, with the indentation
|
||||
// of its marker and whether the list is ordered.
|
||||
func listMarker(line string) (indent int, ordered, ok bool) {
|
||||
indent = leadingSpaces(line)
|
||||
rest := line[indent:]
|
||||
if len(rest) >= 2 && strings.ContainsRune("-*+", rune(rest[0])) && rest[1] == ' ' {
|
||||
return indent, false, !isRule(strings.TrimSpace(rest))
|
||||
}
|
||||
n := 0
|
||||
for n < len(rest) && n < 9 && rest[n] >= '0' && rest[n] <= '9' {
|
||||
n++
|
||||
}
|
||||
if n > 0 && len(rest) > n+1 && (rest[n] == '.' || rest[n] == ')') && rest[n+1] == ' ' {
|
||||
return indent, true, true
|
||||
}
|
||||
return 0, false, false
|
||||
}
|
||||
|
||||
// markerWidth returns the column where the content of the list item that
|
||||
// line starts begins: after its marker and the space after it.
|
||||
func markerWidth(line string) int {
|
||||
w := leadingSpaces(line)
|
||||
for w < len(line) && line[w] != ' ' {
|
||||
w++
|
||||
}
|
||||
start := w
|
||||
for w < len(line) && line[w] == ' ' && w-start < 4 {
|
||||
w++
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// startsList reports whether line starts a list item that may interrupt a
|
||||
// paragraph: a bullet, or an ordered item numbered 1.
|
||||
func startsList(line string) bool {
|
||||
_, ordered, ok := listMarker(line)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
return !ordered || strings.HasPrefix(strings.TrimSpace(line), "1")
|
||||
}
|
||||
|
||||
func isBlockStart(line string) bool {
|
||||
t := strings.TrimSpace(line)
|
||||
return heading(t) > 0 || isFence(t) || isRule(t) || strings.HasPrefix(t, ">")
|
||||
}
|
||||
|
||||
func leadingSpaces(s string) int {
|
||||
n := 0
|
||||
for n < len(s) && s[n] == ' ' {
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func heading(t string) int {
|
||||
n := 0
|
||||
for n < len(t) && n < 7 && t[n] == '#' {
|
||||
n++
|
||||
}
|
||||
if n == 0 || n > 6 || (len(t) > n && t[n] != ' ') {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func isFence(t string) bool { return strings.HasPrefix(t, "```") || strings.HasPrefix(t, "~~~") }
|
||||
|
||||
func isRule(t string) bool {
|
||||
if len(t) < 3 || !strings.ContainsRune("-*_", rune(t[0])) {
|
||||
return false
|
||||
}
|
||||
n := 0
|
||||
for _, c := range t {
|
||||
switch {
|
||||
case c == rune(t[0]):
|
||||
n++
|
||||
case c != ' ':
|
||||
return false
|
||||
}
|
||||
}
|
||||
return n >= 3
|
||||
}
|
||||
|
||||
// inlines collects the inlines of a text, merging runs of text.
|
||||
type inlines []Inline
|
||||
|
||||
func (in *inlines) text(s string) {
|
||||
if n := len(*in); n > 0 && (*in)[n-1].Kind == Text {
|
||||
(*in)[n-1].Text += s
|
||||
return
|
||||
}
|
||||
*in = append(*in, Inline{Kind: Text, Text: s})
|
||||
}
|
||||
|
||||
// link adds children linked to href, or the children alone when the URL is
|
||||
// not one the window opens.
|
||||
func (in *inlines) link(href string, children []Inline) {
|
||||
if !SafeURL(href) {
|
||||
for _, c := range children {
|
||||
if c.Kind == Text {
|
||||
in.text(c.Text)
|
||||
} else {
|
||||
*in = append(*in, c)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
*in = append(*in, Inline{Kind: Link, URL: href, Children: children})
|
||||
}
|
||||
|
||||
// parseInline parses the text of a paragraph or heading.
|
||||
func parseInline(s string) []Inline {
|
||||
var in inlines
|
||||
for i := 0; i < len(s); {
|
||||
c := s[i]
|
||||
switch {
|
||||
case c == '\\' && i+1 < len(s) && isPunct(s[i+1]):
|
||||
in.text(s[i+1 : i+2])
|
||||
i += 2
|
||||
continue
|
||||
case c == '\n':
|
||||
in.text(" ")
|
||||
i++
|
||||
continue
|
||||
case c == '`':
|
||||
n := run(s[i:], '`')
|
||||
if end := strings.Index(s[i+n:], s[i:i+n]); end >= 0 {
|
||||
code := strings.TrimSpace(strings.ReplaceAll(s[i+n:i+n+end], "\n", " "))
|
||||
in = append(in, Inline{Kind: CodeSpan, Text: code})
|
||||
i += n + end + n
|
||||
continue
|
||||
}
|
||||
in.text(s[i : i+n])
|
||||
i += n
|
||||
continue
|
||||
case c == '[' || c == '!' && strings.HasPrefix(s[i:], "!["):
|
||||
image := c == '!'
|
||||
start := i
|
||||
if image {
|
||||
start++
|
||||
}
|
||||
if text, href, n, ok := parseLink(s[start:]); ok {
|
||||
var children []Inline
|
||||
if image {
|
||||
children = []Inline{{Kind: Text, Text: text}}
|
||||
} else {
|
||||
children = parseInline(text)
|
||||
}
|
||||
in.link(href, children)
|
||||
i = start + n
|
||||
continue
|
||||
}
|
||||
case c == '<':
|
||||
if end := strings.IndexByte(s[i:], '>'); end > 0 {
|
||||
if u := s[i+1 : i+end]; !strings.ContainsAny(u, " <") && SafeURL(u) {
|
||||
in.link(u, []Inline{{Kind: Text, Text: u}})
|
||||
i += end + 1
|
||||
continue
|
||||
}
|
||||
}
|
||||
case c == '*' || c == '_':
|
||||
n := min(run(s[i:], c), 2)
|
||||
if c == '_' && i > 0 && isWord(s[i-1]) {
|
||||
break
|
||||
}
|
||||
delim := s[i : i+n]
|
||||
rest := s[i+n:]
|
||||
if rest != "" && rest[0] != ' ' && rest[0] != '\n' {
|
||||
if end := closing(rest, delim); end > 0 {
|
||||
kind := Emphasis
|
||||
if n == 2 {
|
||||
kind = Strong
|
||||
}
|
||||
in = append(in, Inline{Kind: kind, Children: parseInline(rest[:end])})
|
||||
i += n + end + n
|
||||
continue
|
||||
}
|
||||
}
|
||||
in.text(delim)
|
||||
i += n
|
||||
continue
|
||||
case c == 'h' && (i == 0 || !isWord(s[i-1])) && (strings.HasPrefix(s[i:], "https://") || strings.HasPrefix(s[i:], "http://")):
|
||||
end := i
|
||||
for end < len(s) && s[end] > ' ' && s[end] != '<' {
|
||||
end++
|
||||
}
|
||||
u := strings.TrimRight(s[i:end], ".,:;!?\"')")
|
||||
if strings.Count(u, "(") > strings.Count(u, ")") && end > i+len(u) && s[i+len(u)] == ')' {
|
||||
u += ")"
|
||||
}
|
||||
in.link(u, []Inline{{Kind: Text, Text: u}})
|
||||
i += len(u)
|
||||
continue
|
||||
}
|
||||
_, size := utf8.DecodeRuneInString(s[i:])
|
||||
in.text(s[i : i+size])
|
||||
i += size
|
||||
}
|
||||
return in
|
||||
}
|
||||
|
||||
// parseLink parses "[text](url)" or `[text](url "title")` at the start of
|
||||
// s, returning the text, the URL and the length of the link.
|
||||
func parseLink(s string) (text, href string, n int, ok bool) {
|
||||
depth := 0
|
||||
end := -1
|
||||
for i := 0; i < len(s) && end < 0; i++ {
|
||||
switch s[i] {
|
||||
case '\\':
|
||||
i++
|
||||
case '[':
|
||||
depth++
|
||||
case ']':
|
||||
if depth--; depth == 0 {
|
||||
end = i
|
||||
}
|
||||
}
|
||||
}
|
||||
if end < 0 || !strings.HasPrefix(s[end+1:], "(") {
|
||||
return "", "", 0, false
|
||||
}
|
||||
close := strings.IndexByte(s[end+2:], ')')
|
||||
if close < 0 {
|
||||
return "", "", 0, false
|
||||
}
|
||||
dest := strings.TrimSpace(s[end+2 : end+2+close])
|
||||
if sp := strings.IndexAny(dest, " \n"); sp >= 0 {
|
||||
dest = dest[:sp] // drop the title
|
||||
}
|
||||
dest = strings.TrimSuffix(strings.TrimPrefix(dest, "<"), ">")
|
||||
return s[1:end], dest, end + 2 + close + 1, true
|
||||
}
|
||||
|
||||
// SafeURL reports whether u is a URL the window opens: http, https or
|
||||
// mailto.
|
||||
func SafeURL(u string) bool {
|
||||
l := strings.ToLower(u)
|
||||
return strings.HasPrefix(l, "https://") || strings.HasPrefix(l, "http://") || strings.HasPrefix(l, "mailto:")
|
||||
}
|
||||
|
||||
// closing returns the index of the delimiter closing an emphasis in s.
|
||||
func closing(s, delim string) int {
|
||||
for i := 1; i+len(delim) <= len(s); i++ {
|
||||
switch {
|
||||
case s[i] == '`':
|
||||
// Code spans take precedence.
|
||||
n := run(s[i:], '`')
|
||||
if end := strings.Index(s[i+n:], s[i:i+n]); end >= 0 {
|
||||
i += n + end + n - 1
|
||||
}
|
||||
case s[i] == '\\':
|
||||
i++
|
||||
case strings.HasPrefix(s[i:], delim) && s[i-1] != ' ' && s[i-1] != '\n':
|
||||
if len(delim) == 1 && i+1 < len(s) && s[i+1] == delim[0] {
|
||||
i++ // part of a strong delimiter
|
||||
continue
|
||||
}
|
||||
if delim[0] == '_' && i+len(delim) < len(s) && isWord(s[i+len(delim)]) {
|
||||
continue
|
||||
}
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func run(s string, c byte) int {
|
||||
n := 0
|
||||
for n < len(s) && s[n] == c {
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func isPunct(c byte) bool { return strings.IndexByte("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", c) >= 0 }
|
||||
|
||||
func isWord(c byte) bool {
|
||||
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c >= 0x80
|
||||
}
|
||||
|
||||
// HTML renders blocks as HTML, escaping all their text.
|
||||
func HTML(blocks []Block) string {
|
||||
var b strings.Builder
|
||||
writeBlocks(&b, blocks, false)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// writeBlocks renders blocks. tight renders paragraphs without <p>, apart
|
||||
// by <br>, as in the items of a list.
|
||||
func writeBlocks(b *strings.Builder, blocks []Block, tight bool) {
|
||||
paras := 0
|
||||
for _, bl := range blocks {
|
||||
switch bl.Kind {
|
||||
case Paragraph:
|
||||
if !tight {
|
||||
b.WriteString("<p>")
|
||||
writeInlines(b, bl.Inlines)
|
||||
b.WriteString("</p>")
|
||||
} else {
|
||||
if paras > 0 {
|
||||
b.WriteString("<br>")
|
||||
}
|
||||
writeInlines(b, bl.Inlines)
|
||||
}
|
||||
paras++
|
||||
case Heading:
|
||||
tag := "h" + strconv.Itoa(bl.Level)
|
||||
b.WriteString("<" + tag + ">")
|
||||
writeInlines(b, bl.Inlines)
|
||||
b.WriteString("</" + tag + ">")
|
||||
case List:
|
||||
tag := "ul"
|
||||
if bl.Ordered {
|
||||
tag = "ol"
|
||||
}
|
||||
b.WriteString("<" + tag + ">")
|
||||
for _, item := range bl.Items {
|
||||
b.WriteString("<li>")
|
||||
writeBlocks(b, item, true)
|
||||
b.WriteString("</li>")
|
||||
}
|
||||
b.WriteString("</" + tag + ">")
|
||||
case Quote:
|
||||
b.WriteString("<blockquote>")
|
||||
writeBlocks(b, bl.Blocks, false)
|
||||
b.WriteString("</blockquote>")
|
||||
case Code:
|
||||
b.WriteString("<pre><code>" + html.EscapeString(bl.Text) + "</code></pre>")
|
||||
case Rule:
|
||||
b.WriteString("<hr>")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeInlines(b *strings.Builder, inlines []Inline) {
|
||||
for _, in := range inlines {
|
||||
switch in.Kind {
|
||||
case Text:
|
||||
b.WriteString(html.EscapeString(in.Text))
|
||||
case CodeSpan:
|
||||
b.WriteString("<code>" + html.EscapeString(in.Text) + "</code>")
|
||||
case Emphasis, Strong:
|
||||
tag := "em"
|
||||
if in.Kind == Strong {
|
||||
tag = "strong"
|
||||
}
|
||||
b.WriteString("<" + tag + ">")
|
||||
writeInlines(b, in.Children)
|
||||
b.WriteString("</" + tag + ">")
|
||||
case Link:
|
||||
b.WriteString(`<a href="` + html.EscapeString(in.URL) + `">`)
|
||||
writeInlines(b, in.Children)
|
||||
b.WriteString("</a>")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package markdown
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHTML(t *testing.T) {
|
||||
for _, tc := range []struct{ in, want string }{
|
||||
{"", ""},
|
||||
{"Hello\nworld", "<p>Hello world</p>"},
|
||||
{"One\n\nTwo", "<p>One</p><p>Two</p>"},
|
||||
{"### Added\n\n- One\n- Two", "<h3>Added</h3><ul><li>One</li><li>Two</li></ul>"},
|
||||
{"## 1.2.0 ##", "<h2>1.2.0</h2>"},
|
||||
{"#hashtag", "<p>#hashtag</p>"},
|
||||
{"Fixes:\n- one\n- two", "<p>Fixes:</p><ul><li>one</li><li>two</li></ul>"},
|
||||
{"1. one\n2. two", "<ol><li>one</li><li>two</li></ol>"},
|
||||
{"We shipped\n2. things", "<p>We shipped 2. things</p>"},
|
||||
{"- a\n - b\n - c\n- d", "<ul><li>a<ul><li>b</li><li>c</li></ul></li><li>d</li></ul>"},
|
||||
{"1. a\n - b", "<ol><li>a<ul><li>b</li></ul></li></ol>"},
|
||||
{"- a long\nitem\n- b", "<ul><li>a long item</li><li>b</li></ul>"},
|
||||
{"- a\n\n more\n- b", "<ul><li>a<br>more</li><li>b</li></ul>"},
|
||||
{"- a\n\nAfter", "<ul><li>a</li></ul><p>After</p>"},
|
||||
{"- a\n* b", "<ul><li>a</li><li>b</li></ul>"},
|
||||
{"- a\n1. b", "<ul><li>a</li></ul><ol><li>b</li></ol>"},
|
||||
{"> quoted\n> text", "<blockquote><p>quoted text</p></blockquote>"},
|
||||
{"---", "<hr>"},
|
||||
{"- - -", "<hr>"},
|
||||
{"```\n<b>code</b>\n\n x\n```\nafter", "<pre><code><b>code</b>\n\n x</code></pre><p>after</p>"},
|
||||
{"**bold** and *em* and _em_ and __bold__", "<p><strong>bold</strong> and <em>em</em> and <em>em</em> and <strong>bold</strong></p>"},
|
||||
{"snake_case_name and 2 * 3 * 4", "<p>snake_case_name and 2 * 3 * 4</p>"},
|
||||
{"**bold *em* bold**", "<p><strong>bold <em>em</em> bold</strong></p>"},
|
||||
{"`a *b* <c>` and ``x ` y``", "<p><code>a *b* <c></code> and <code>x ` y</code></p>"},
|
||||
{`\*not em\*`, "<p>*not em*</p>"},
|
||||
{"[docs](https://example.com/a?b=1&c=2 \"Title\")", `<p><a href="https://example.com/a?b=1&c=2">docs</a></p>`},
|
||||
{"[**bold** link](https://example.com)", `<p><a href="https://example.com"><strong>bold</strong> link</a></p>`},
|
||||
{"[bad](javascript:alert(1))", "<p>bad)</p>"},
|
||||
{"[rel](/path)", "<p>rel</p>"},
|
||||
{"", `<p><a href="https://example.com/logo.png">logo</a></p>`},
|
||||
{"<https://example.com> <b>hi</b>", `<p><a href="https://example.com">https://example.com</a> <b>hi</b></p>`},
|
||||
{"See https://example.com/x_(y). Or (https://example.com).", `<p>See <a href="https://example.com/x_(y)">https://example.com/x_(y)</a>. Or (<a href="https://example.com">https://example.com</a>).</p>`},
|
||||
{"<script>alert(1)</script>", "<p><script>alert(1)</script></p>"},
|
||||
{`<img src=x onerror="alert(1)">`, "<p><img src=x onerror="alert(1)"></p>"},
|
||||
{"[x](https://a\"onmouseover=\"alert(1))", `<p><a href="https://a"onmouseover="alert(1">x</a>)</p>`},
|
||||
{"Café — ünïcode", "<p>Café — ünïcode</p>"},
|
||||
{"a\r\nb", "<p>a b</p>"},
|
||||
{"**unclosed", "<p>**unclosed</p>"},
|
||||
{"[unclosed](https://x", "<p>[unclosed](<a href=\"https://x\">https://x</a></p>"},
|
||||
} {
|
||||
if got := HTML(Parse(tc.in)); got != tc.want {
|
||||
t.Errorf("HTML(Parse(%q))\n got %s\nwant %s", tc.in, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
got := Parse("## Fixed\n\n- A **bold [link](https://example.com)** fix\n 1. nested\n\n> `code`")
|
||||
want := []Block{
|
||||
{Kind: Heading, Level: 2, Inlines: []Inline{{Kind: Text, Text: "Fixed"}}},
|
||||
{Kind: List, Items: [][]Block{{
|
||||
{Kind: Paragraph, Inlines: []Inline{
|
||||
{Kind: Text, Text: "A "},
|
||||
{Kind: Strong, Children: []Inline{
|
||||
{Kind: Text, Text: "bold "},
|
||||
{Kind: Link, URL: "https://example.com", Children: []Inline{{Kind: Text, Text: "link"}}},
|
||||
}},
|
||||
{Kind: Text, Text: " fix"},
|
||||
}},
|
||||
{Kind: List, Ordered: true, Items: [][]Block{{{Kind: Paragraph, Inlines: []Inline{{Kind: Text, Text: "nested"}}}}}},
|
||||
}}},
|
||||
{Kind: Quote, Blocks: []Block{{Kind: Paragraph, Inlines: []Inline{{Kind: CodeSpan, Text: "code"}}}}},
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Parse\n got %+v\nwant %+v", got, want)
|
||||
}
|
||||
if blocks := Parse(" \n\n"); len(blocks) != 0 {
|
||||
t.Errorf("Parse of blank notes = %+v, want none", blocks)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user