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
+198
@@ -0,0 +1,198 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// longText returns n paragraphs of formatted text: a heading every
|
||||
// fiftieth, items of lists, and runs of bold, italic and links.
|
||||
func longText(n int) Text {
|
||||
paras := make([]Paragraph, n)
|
||||
for i := range paras {
|
||||
st := ParagraphStyle{}
|
||||
switch {
|
||||
case i%50 == 0:
|
||||
st.Heading = 2
|
||||
case i%7 == 3:
|
||||
st.List = Bullets
|
||||
}
|
||||
paras[i] = Paragraph{Style: st, Runs: []Run{
|
||||
{Text: fmt.Sprintf("Paragraph %d has ", i)},
|
||||
{Text: "bold words", Attributes: Attributes{Weight: 700}},
|
||||
{Text: ", an "},
|
||||
{Text: "italic one", Attributes: Attributes{Italic: true}},
|
||||
{Text: " and "},
|
||||
{Text: "a link", Attributes: Attributes{Link: "https://example.com"}},
|
||||
{Text: " in a line long enough to wrap in a narrow window."},
|
||||
}}
|
||||
}
|
||||
return TextOf(paras...)
|
||||
}
|
||||
|
||||
// benchParagraphs are the sizes of the documents of the benchmarks.
|
||||
var benchParagraphs = []int{1000, 10000, 100000}
|
||||
|
||||
// BenchmarkTypeFrame types a character in the middle of a document and
|
||||
// draws the frame that shows it, as typing does.
|
||||
func BenchmarkTypeFrame(b *testing.B) {
|
||||
for _, n := range benchParagraphs {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
doc := NewDocument(longText(n))
|
||||
tt := ui.NewTester(func(c *ui.Context) { Editor(c, doc).Fill() }, 1000, 800)
|
||||
tt.Press(500, 400)
|
||||
tt.Release(500, 400)
|
||||
mid := doc.Text().Len() / 2
|
||||
doc.SetSelection(mid, mid)
|
||||
tt.Frame()
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
tt.Type("x")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkReplace replaces a rune in the middle of a document's text,
|
||||
// the edit a keystroke makes, without drawing.
|
||||
func BenchmarkReplace(b *testing.B) {
|
||||
for _, n := range benchParagraphs {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
t := longText(n)
|
||||
mid := t.Len() / 2
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
t = t.ReplaceString(mid, mid+1, "y", Attributes{Weight: 700})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkFormat makes a thousand runes bold in the middle of a document.
|
||||
func BenchmarkFormat(b *testing.B) {
|
||||
for _, n := range benchParagraphs {
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
t := longText(n)
|
||||
mid := t.Len() / 2
|
||||
on := false
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
on = !on
|
||||
t = t.Format(mid, mid+1000, func(a *Attributes) { a.Italic = on })
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkScrollFrame scrolls a long document by a wheel's step a frame.
|
||||
func BenchmarkScrollFrame(b *testing.B) {
|
||||
doc := NewDocument(longText(100000))
|
||||
tt := ui.NewTester(func(c *ui.Context) { Editor(c, doc).Fill() }, 1000, 800)
|
||||
tt.Frame()
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
tt.Scroll(500, 400, 0, 120)
|
||||
}
|
||||
}
|
||||
|
||||
// shortParagraphs returns n short paragraphs, as a note's lines or a
|
||||
// list's items are, many to a chunk of the text: their words run plain,
|
||||
// bold and plain, with a multi-byte rune in each.
|
||||
func shortParagraphs(n int) Text {
|
||||
paras := make([]Paragraph, n)
|
||||
for i := range paras {
|
||||
paras[i] = Paragraph{Runs: []Run{
|
||||
{Text: fmt.Sprintf("Line %d — ", i)},
|
||||
{Text: "bold", Attributes: Attributes{Weight: 700}},
|
||||
{Text: "."},
|
||||
}}
|
||||
}
|
||||
return TextOf(paras...)
|
||||
}
|
||||
|
||||
// benchShort are the sizes of the documents of short paragraphs.
|
||||
var benchShort = []int{100, 300, 1000, 3000}
|
||||
|
||||
// BenchmarkParagraphs walks the paragraphs of a document of short ones,
|
||||
// as saving or searching it does.
|
||||
func BenchmarkParagraphs(b *testing.B) {
|
||||
for _, n := range benchShort {
|
||||
t := shortParagraphs(n)
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
for range t.Paragraphs() {
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkRuns walks the runs of the whole of a document of short
|
||||
// paragraphs, as copying it does.
|
||||
func BenchmarkRuns(b *testing.B) {
|
||||
for _, n := range benchShort {
|
||||
t := shortParagraphs(n)
|
||||
b.Run(fmt.Sprint(n), func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
for range t.Runs(0, t.Len()) {
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// readsAsRuns returns a paragraph with every mark Markdown writes.
|
||||
func readsAsRuns() []Run {
|
||||
bold := Attributes{Weight: 700}
|
||||
italic := Attributes{Italic: true}
|
||||
underlined := Attributes{Underline: true}
|
||||
strike := Attributes{Strikethrough: true}
|
||||
code := Attributes{Code: true}
|
||||
linked := Attributes{Link: "https://example.com"}
|
||||
attachment := &Attachment{Name: "a cat", URL: "cat.png"}
|
||||
var runs []Run
|
||||
for repeat := 0; repeat < 32; repeat++ {
|
||||
runs = append(runs,
|
||||
Run{Text: "a é "},
|
||||
Run{Text: "bold", Attributes: bold},
|
||||
Run{Text: " "},
|
||||
Run{Text: "italic", Attributes: italic},
|
||||
Run{Text: " "},
|
||||
Run{Text: "under", Attributes: underlined},
|
||||
Run{Text: " "},
|
||||
Run{Text: "strike", Attributes: strike},
|
||||
Run{Text: " "},
|
||||
Run{Text: "code", Attributes: code},
|
||||
Run{Text: " "},
|
||||
Run{Text: "link", Attributes: linked},
|
||||
Run{Text: " "},
|
||||
Run{Text: string(ObjectReplacement), Attributes: Attributes{Attachment: attachment}},
|
||||
Run{Text: " "},
|
||||
)
|
||||
}
|
||||
runs = append(runs, Run{Text: " "})
|
||||
return runs
|
||||
}
|
||||
|
||||
// BenchmarkReadsAs measures reading a written paragraph back, which
|
||||
// compares every rune and its marks.
|
||||
func BenchmarkReadsAs(bench *testing.B) {
|
||||
runs := readsAsRuns()
|
||||
var builder strings.Builder
|
||||
writeMarkdownRuns(&builder, runs)
|
||||
markdown := builder.String()
|
||||
if !readsAs(markdown, runs) {
|
||||
bench.Fatal("Markdown does not read back")
|
||||
}
|
||||
bench.ReportAllocs()
|
||||
for bench.Loop() {
|
||||
if !readsAs(markdown, runs) {
|
||||
bench.Fatal("Markdown does not read back")
|
||||
}
|
||||
}
|
||||
}
|
||||
+260
@@ -0,0 +1,260 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/egoist/mygo/transfer"
|
||||
)
|
||||
|
||||
// Format is the clipboard's format of attributed text copied from an
|
||||
// Editor: its paragraphs, styles and runs as JSON, which other MyGo apps
|
||||
// paste whole, as Lexical and Slate copy a format of their own first.
|
||||
const Format transfer.Format = "application/x-mygo-rich-text"
|
||||
|
||||
// RTF is the format of Rich Text Format, which macOS apps (TextEdit,
|
||||
// Notes, Pages) copy.
|
||||
const RTF transfer.Format = "text/rtf"
|
||||
|
||||
// clipText is the JSON of the format, for paragraphs of a Text.
|
||||
type clipText struct {
|
||||
// Copy names the copy within the process that made it, whose text,
|
||||
// attachments included, pastes as it was.
|
||||
Copy string `json:"copy,omitempty"`
|
||||
Paragraphs []clipParagraph `json:"paragraphs"`
|
||||
}
|
||||
|
||||
type clipParagraph struct {
|
||||
Style ParagraphStyle `json:"style"`
|
||||
Runs []clipRun `json:"runs,omitempty"`
|
||||
}
|
||||
|
||||
type clipRun struct {
|
||||
Text string `json:"text"`
|
||||
Attributes clipAttributes `json:"attributes"`
|
||||
Attachment *clipAttachment `json:"attachment,omitempty"`
|
||||
}
|
||||
|
||||
// clipAttributes are the Attributes of a run but its attachment, which
|
||||
// clipAttachment describes.
|
||||
type clipAttributes struct {
|
||||
Font string `json:"font,omitempty"`
|
||||
Size float32 `json:"size,omitempty"`
|
||||
Weight int `json:"weight,omitempty"`
|
||||
Italic bool `json:"italic,omitempty"`
|
||||
Underline bool `json:"underline,omitempty"`
|
||||
Strikethrough bool `json:"strikethrough,omitempty"`
|
||||
Color string `json:"color,omitempty"`
|
||||
Background string `json:"background,omitempty"`
|
||||
Code bool `json:"code,omitempty"`
|
||||
Link string `json:"link,omitempty"`
|
||||
Tag string `json:"tag,omitempty"`
|
||||
}
|
||||
|
||||
type clipAttachment struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Width float32 `json:"width,omitempty"`
|
||||
Height float32 `json:"height,omitempty"`
|
||||
}
|
||||
|
||||
// copies keeps the last text copied in this process, by the name its
|
||||
// format carries, so that pasting it keeps its attachments. Names start
|
||||
// with one random to the process, so that no other app's copy has one.
|
||||
var (
|
||||
copies sync.Map // string → Text
|
||||
copyName atomic.Uint64
|
||||
lastCopy atomic.Value // string
|
||||
process = rand.Text()
|
||||
)
|
||||
|
||||
// encodeClip returns t in the clipboard's format.
|
||||
func encodeClip(t Text) []byte {
|
||||
name := process + "-" + strconv.FormatUint(copyName.Add(1), 36)
|
||||
if old, ok := lastCopy.Load().(string); ok {
|
||||
copies.Delete(old)
|
||||
}
|
||||
copies.Store(name, t)
|
||||
lastCopy.Store(name)
|
||||
c := clipOf(t)
|
||||
c.Copy = name
|
||||
for i := range c.Paragraphs {
|
||||
// IDs are the app's, of paragraphs where they are: a paste
|
||||
// makes new ones (Text.Replace).
|
||||
c.Paragraphs[i].Style.ID = ""
|
||||
}
|
||||
b, _ := json.Marshal(c)
|
||||
return b
|
||||
}
|
||||
|
||||
// MarshalJSON writes t as JSON, as the clipboard's Format holds it, to
|
||||
// save it: paragraphs of a style each, of runs of text and attributes.
|
||||
// Attachments keep their names, URLs and sizes; images and drawings are
|
||||
// the app's to save.
|
||||
func (t Text) MarshalJSON() ([]byte, error) { return json.Marshal(clipOf(t)) }
|
||||
|
||||
// UnmarshalJSON reads what MarshalJSON wrote.
|
||||
func (t *Text) UnmarshalJSON(b []byte) error {
|
||||
var c clipText
|
||||
if err := json.Unmarshal(b, &c); err != nil {
|
||||
return err
|
||||
}
|
||||
*t = c.text()
|
||||
return nil
|
||||
}
|
||||
|
||||
// clipOf returns the JSON form of t.
|
||||
func clipOf(t Text) clipText {
|
||||
var c clipText
|
||||
for _, p := range t.Paragraphs() {
|
||||
cp := clipParagraph{Style: p.Style}
|
||||
for _, r := range p.Runs {
|
||||
a := r.Attributes
|
||||
cr := clipRun{Text: r.Text, Attributes: clipAttributes{
|
||||
Font: a.Font, Size: a.Size, Weight: a.Weight, Italic: a.Italic, Underline: a.Underline,
|
||||
Strikethrough: a.Strikethrough, Code: a.Code, Link: a.Link, Tag: a.Tag,
|
||||
}}
|
||||
if a.Color.A > 0 {
|
||||
cr.Attributes.Color = cssColor(a.Color)
|
||||
}
|
||||
if a.Background.A > 0 {
|
||||
cr.Attributes.Background = cssColor(a.Background)
|
||||
}
|
||||
if at := a.Attachment; at != nil {
|
||||
w, h := at.size()
|
||||
cr.Attachment = &clipAttachment{Name: at.Name, URL: at.URL, Width: w, Height: h}
|
||||
}
|
||||
cp.Runs = append(cp.Runs, cr)
|
||||
}
|
||||
c.Paragraphs = append(c.Paragraphs, cp)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// decodeClip returns the text of the clipboard's format.
|
||||
func decodeClip(b []byte) (Text, bool) {
|
||||
var c clipText
|
||||
if json.Unmarshal(b, &c) != nil {
|
||||
return Text{}, false
|
||||
}
|
||||
if c.Copy != "" {
|
||||
if t, ok := copies.Load(c.Copy); ok {
|
||||
return t.(Text), true
|
||||
}
|
||||
}
|
||||
if len(c.Paragraphs) == 0 {
|
||||
return Text{}, false
|
||||
}
|
||||
return c.text(), true
|
||||
}
|
||||
|
||||
// text returns the text of the JSON form.
|
||||
func (c clipText) text() Text {
|
||||
var paras []Paragraph
|
||||
for _, cp := range c.Paragraphs {
|
||||
p := Paragraph{Style: cp.Style}
|
||||
for _, cr := range cp.Runs {
|
||||
a := Attributes{
|
||||
Font: cr.Attributes.Font, Size: cr.Attributes.Size, Weight: cr.Attributes.Weight, Italic: cr.Attributes.Italic,
|
||||
Underline: cr.Attributes.Underline, Strikethrough: cr.Attributes.Strikethrough, Code: cr.Attributes.Code,
|
||||
Link: safeLink(cr.Attributes.Link), Tag: cr.Attributes.Tag,
|
||||
}
|
||||
a.Color, _ = parseCSSColor(cr.Attributes.Color)
|
||||
a.Background, _ = parseCSSColor(cr.Attributes.Background)
|
||||
if at := cr.Attachment; at != nil {
|
||||
a.Attachment = &Attachment{Name: at.Name, URL: at.URL, Width: side(at.Width), Height: side(at.Height)}
|
||||
}
|
||||
p.Runs = append(p.Runs, Run{Text: cr.Text, Attributes: a})
|
||||
}
|
||||
paras = append(paras, p)
|
||||
}
|
||||
if len(paras) == 0 {
|
||||
return Text{}
|
||||
}
|
||||
return TextOf(paras...)
|
||||
}
|
||||
|
||||
// PlainText returns t as plain text, its attachments left out.
|
||||
func (t Text) PlainText() string {
|
||||
return strings.ReplaceAll(t.String(), string(ObjectReplacement), "")
|
||||
}
|
||||
|
||||
// clipboardData returns t as the clipboard takes it: in the format of
|
||||
// the editor, as HTML and as plain text.
|
||||
func clipboardData(t Text) transfer.Data {
|
||||
return transfer.New(transfer.NewItem(
|
||||
transfer.Bytes(Format, encodeClip(t)),
|
||||
transfer.Bytes(transfer.HTML, []byte(t.HTML())),
|
||||
transfer.Bytes(transfer.Text, []byte(t.PlainText())),
|
||||
))
|
||||
}
|
||||
|
||||
// copySelection puts the selection on the clipboard.
|
||||
func (v *view) copySelection() {
|
||||
a, z := v.selection()
|
||||
if a == z {
|
||||
return
|
||||
}
|
||||
v.services.WriteClipboardData(clipboardData(v.shown.Slice(a, z)))
|
||||
}
|
||||
|
||||
// paste replaces the selection with what the clipboard holds: the richest
|
||||
// format the editor reads, or its plain text in the typing attributes when
|
||||
// matching the style.
|
||||
func (v *view) paste(matchStyle bool) {
|
||||
var t Text
|
||||
ok := false
|
||||
if !matchStyle {
|
||||
d := v.services.ReadClipboardData(Format, transfer.HTML, RTF, transfer.Markdown, transfer.Text)
|
||||
if b, err := d.Read(Format); err == nil {
|
||||
t, ok = decodeClip(b)
|
||||
}
|
||||
if !ok {
|
||||
if b, err := d.Read(transfer.HTML); err == nil && len(b) > 0 {
|
||||
t, ok = ParseHTML(string(b)), true
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
// TextEdit, Pages and WordPad copy RTF without HTML.
|
||||
if b, err := d.Read(RTF); err == nil && len(b) > 0 {
|
||||
t, ok = ParseRTF(b), true
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
// Markdown apps and Markdown views copy it.
|
||||
if b, err := d.Read(transfer.Markdown); err == nil && len(b) > 0 {
|
||||
t, ok = ParseMarkdown(string(b)), true
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
if b, err := d.Read(transfer.Text); err == nil && len(b) > 0 {
|
||||
v.insert(string(b))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
s := v.services.ReadClipboard()
|
||||
if s != "" {
|
||||
v.insert(s)
|
||||
}
|
||||
return
|
||||
}
|
||||
v.record(false)
|
||||
d := v.doc
|
||||
d.lock()
|
||||
v.lockedSync()
|
||||
a, z := v.selection() // as the sync moved it
|
||||
v.lockedPublish()
|
||||
v.lockedEdit(func(e *Edit) { e.Replace(a, z, t) })
|
||||
caret := a + t.Len()
|
||||
v.selAnchor, v.caret = caret, caret
|
||||
d.anchor, d.caret = caret, caret
|
||||
d.mu.Unlock()
|
||||
v.mode, v.coalesce = newStep, false
|
||||
v.reveal = true
|
||||
}
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/transfer"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// sample is a text of every kind of paragraph and run.
|
||||
func sample() Text {
|
||||
bold := Attributes{Weight: 700}
|
||||
return TextOf(
|
||||
Paragraph{Style: ParagraphStyle{Heading: 1}, Runs: []Run{{Text: "Trip"}}},
|
||||
Paragraph{Runs: []Run{{Text: "Land at "}, {Text: "10:40", Attributes: bold}, {Text: " near the "},
|
||||
{Text: "castle", Attributes: Attributes{Link: "https://x.org/a"}}, {Text: ", "}, {Text: "slowly", Attributes: Attributes{Italic: true}}, {Text: "."}}},
|
||||
Paragraph{Style: ParagraphStyle{List: Tasks, Checked: true}, Runs: []Run{{Text: "Passport"}}},
|
||||
Paragraph{Style: ParagraphStyle{List: Tasks}, Runs: []Run{{Text: "Adapter"}}},
|
||||
Paragraph{Style: ParagraphStyle{List: Numbers}, Runs: []Run{{Text: "One"}}},
|
||||
Paragraph{Style: ParagraphStyle{List: Numbers, Indent: 1}, Runs: []Run{{Text: "Inner"}}},
|
||||
Paragraph{Style: ParagraphStyle{List: Numbers}, Runs: []Run{{Text: "Two"}}},
|
||||
Paragraph{Style: ParagraphStyle{Quote: true}, Runs: []Run{{Text: "A quote"}}},
|
||||
Paragraph{Style: ParagraphStyle{CodeBlock: true}, Runs: []Run{{Text: "a := 1"}}},
|
||||
Paragraph{Style: ParagraphStyle{CodeBlock: true}, Runs: []Run{{Text: "b := 2"}}},
|
||||
Paragraph{Style: ParagraphStyle{Align: ui.Center}, Runs: []Run{{Text: "mid", Attributes: Attributes{Underline: true, Strikethrough: true}}, {Text: " and "}, {Text: "x()", Attributes: Attributes{Code: true}}}},
|
||||
)
|
||||
}
|
||||
|
||||
func TestMarkdown(t *testing.T) {
|
||||
want := strings.Join([]string{
|
||||
"# Trip",
|
||||
"",
|
||||
"Land at **10:40** near the [castle](https://x.org/a), *slowly*.",
|
||||
"",
|
||||
"- [x] Passport",
|
||||
"- [ ] Adapter",
|
||||
"1. One",
|
||||
" 1. Inner",
|
||||
"2. Two",
|
||||
"",
|
||||
"> A quote",
|
||||
"",
|
||||
"```",
|
||||
"a := 1",
|
||||
"b := 2",
|
||||
"```",
|
||||
"",
|
||||
"~~<u>mid</u>~~ and `x()`",
|
||||
}, "\n")
|
||||
if got := sample().Markdown(); got != want {
|
||||
t.Fatalf("Markdown:\n%s\nwant:\n%s", got, want)
|
||||
}
|
||||
// What Markdown would read as a block is escaped in a body paragraph.
|
||||
if got := NewText("# not a heading").Markdown(); got != `\# not a heading` {
|
||||
t.Fatalf("%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTMLRoundTrip(t *testing.T) {
|
||||
in := sample()
|
||||
html := in.HTML()
|
||||
out := ParseHTML(html)
|
||||
if out.String() != in.String() {
|
||||
t.Fatalf("text %q, want %q\nHTML %s", out.String(), in.String(), html)
|
||||
}
|
||||
if got, want := runsOf(out), runsOf(in); got != want {
|
||||
t.Fatalf("runs %q, want %q", got, want)
|
||||
}
|
||||
for start, p := range in.Paragraphs() {
|
||||
if got := out.ParagraphStyleAt(start); got != p.Style {
|
||||
t.Fatalf("paragraph at %d: %+v, want %+v", start, got, p.Style)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseForeignHTML(t *testing.T) {
|
||||
// As Google Docs copies: a bold wrapper made normal, spans styled.
|
||||
gdocs := `<meta charset="utf-8"><b style="font-weight:normal;" id="docs-internal-guid-1"><p dir="ltr"><span style="font-size:11pt;font-family:Arial;font-weight:700;">Bold</span><span style="font-size:11pt;"> and </span><span style="font-style:italic;">italic</span></p><ul><li><p><span>item</span></p></li></ul></b>`
|
||||
got := ParseHTML(gdocs)
|
||||
if s := got.String(); s != "Bold and italic\nitem" {
|
||||
t.Fatalf("text %q", s)
|
||||
}
|
||||
if r := runsOf(got.Slice(0, 15)); r != "*Bold*| and |_italic_" {
|
||||
t.Fatalf("runs %q", r)
|
||||
}
|
||||
if got.ParagraphStyleAt(17).List != Bullets {
|
||||
t.Fatalf("not a list: %+v", got.ParagraphStyleAt(17))
|
||||
}
|
||||
// Whitespace collapses; scripts and styles are left out.
|
||||
got = ParseHTML("<style>p{}</style><p> a \n b </p><script>x()</script><p>c<br>d</p>")
|
||||
if s := got.String(); s != "a b\nc\nd" {
|
||||
t.Fatalf("text %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyPaste(t *testing.T) {
|
||||
doc := NewDocument(sample())
|
||||
tt, _ := richTester(t, doc)
|
||||
doc.SetSelection(5, 18) // "Land at 10:40"
|
||||
tt.Frame()
|
||||
tt.Key(ui.Cmd, ui.KeyC)
|
||||
d := tt.ClipboardData()
|
||||
for _, f := range []transfer.Format{Format, transfer.HTML, transfer.Text} {
|
||||
if _, err := d.Read(f); err != nil {
|
||||
t.Fatalf("no %s copied", f)
|
||||
}
|
||||
}
|
||||
if text, _ := d.Read(transfer.Text); string(text) != "Land at 10:40" {
|
||||
t.Fatalf("plain text %q", text)
|
||||
}
|
||||
doc.SetSelection(0, 0)
|
||||
tt.Frame()
|
||||
tt.Key(ui.Cmd, ui.KeyV)
|
||||
if got := doc.Text().Slice(0, 13); runsOf(got) != "Land at |*10:40*" {
|
||||
t.Fatalf("pasted %q", runsOf(got))
|
||||
}
|
||||
// One step of undo takes the paste back.
|
||||
tt.Key(ui.Cmd, ui.KeyZ)
|
||||
if !doc.Text().Equal(sample()) {
|
||||
t.Fatalf("undo made %q", doc.Text().String())
|
||||
}
|
||||
// HTML from another app pastes its formats; Paste and Match Style
|
||||
// pastes its text in the typing attributes.
|
||||
tt.SetClipboardData(transfer.New(transfer.NewItem(transfer.Bytes(transfer.HTML, []byte("<b>hi</b>")), transfer.Bytes(transfer.Text, []byte("hi")))))
|
||||
doc.SetSelection(0, 0)
|
||||
tt.Frame()
|
||||
tt.Key(ui.Cmd, ui.KeyV)
|
||||
if got := runsOf(doc.Text().Slice(0, 2)); got != "*hi*" {
|
||||
t.Fatalf("pasted HTML %q", got)
|
||||
}
|
||||
tt.Command("pasteAndMatchStyle")
|
||||
if got := runsOf(doc.Text().Slice(0, 4)); got != "*hihi*" {
|
||||
t.Fatalf("pasted matching the style %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSON(t *testing.T) {
|
||||
in := sample()
|
||||
b, err := in.MarshalJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out Text
|
||||
if err := out.UnmarshalJSON(b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !out.Equal(in) {
|
||||
t.Fatalf("%q, want %q", runsOf(out), runsOf(in))
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRTF(t *testing.T) {
|
||||
// As TextEdit copies: a font table, bold, italic, a link, a list.
|
||||
rtf := `{\rtf1\ansi\ansicpg1252\cocoartf2822
|
||||
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
|
||||
{\colortbl;\red255\green255\blue255;}
|
||||
\pard\tx560\pardirnatural\partightenfactor0
|
||||
\f0\fs24 \cf0 Plain \b bold\b0 and \i italic\i0 , caf\'e9 \u8364 ? {\field{\*\fldinst{HYPERLINK "https://go.dev"}}{\fldrslt site}} end.\
|
||||
\pard\qc centered\
|
||||
\pard\tx220\li720\fi-720\pardirnatural\partightenfactor0
|
||||
\ls1\ilvl0{\listtext \uc0舦 }one\
|
||||
{\listtext \uc0舦 }two\
|
||||
}`
|
||||
got := ParseRTF([]byte(rtf))
|
||||
if s := got.String(); s != "Plain bold and italic, café € site end.\ncentered\none\ntwo" {
|
||||
t.Fatalf("text %q", s)
|
||||
}
|
||||
first, _ := got.ParagraphRange(0)
|
||||
if r := runsOf(got.Slice(first, 39)); r != "Plain |*bold*| and |_italic_|, café € |[site]| end." {
|
||||
t.Fatalf("runs %q", r)
|
||||
}
|
||||
if st := got.ParagraphStyleAt(45); st.Align != ui.Center {
|
||||
t.Fatalf("centered: %+v", st)
|
||||
}
|
||||
if st := got.ParagraphStyleAt(got.Len()); st.List != Bullets {
|
||||
t.Fatalf("list: %+v", st)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMarkdownEscapes checks that what Markdown would read as more than
|
||||
// text stays text: block starts in items and headings, a heading's
|
||||
// closing #s, indentation, entities, images and backticks in code.
|
||||
func TestMarkdownEscapes(t *testing.T) {
|
||||
para := func(st ParagraphStyle, runs ...Run) Paragraph { return Paragraph{Style: st, Runs: runs} }
|
||||
for _, c := range []struct {
|
||||
text Text
|
||||
want string
|
||||
}{
|
||||
{TextOf(para(ParagraphStyle{List: Bullets}, Run{Text: "# not a heading"})), `- \# not a heading`},
|
||||
{TextOf(para(ParagraphStyle{List: Numbers}, Run{Text: "> x"})), `1. \> x`},
|
||||
{TextOf(para(ParagraphStyle{Heading: 2}, Run{Text: "Issue #"})), `## Issue \#`},
|
||||
{NewText("---"), `\---`},
|
||||
{NewText("-"), `\-`},
|
||||
{NewText(" indented"), `    indented`},
|
||||
{NewText("Tom & Jerry & co"), `Tom \& Jerry & co`},
|
||||
{TextOf(para(ParagraphStyle{}, Run{Text: "x!"}, Run{Text: "y", Attributes: Attributes{Link: "http://e"}})), `x\`},
|
||||
{TextOf(para(ParagraphStyle{}, Run{Text: "a``b", Attributes: Attributes{Code: true}})), "```a``b```"},
|
||||
{TextOf(para(ParagraphStyle{}, Run{Text: "`x", Attributes: Attributes{Code: true}})), "`` `x ``"},
|
||||
// Delimiters that cannot open or close where they are.
|
||||
{TextOf(para(ParagraphStyle{}, Run{Text: "foo.", Attributes: Attributes{Weight: 700}}, Run{Text: "bar"})), "<strong>foo.</strong>bar"},
|
||||
{TextOf(para(ParagraphStyle{}, Run{Text: "x"}, Run{Text: "(y)", Attributes: Attributes{Italic: true}})), "x<em>(y)</em>"},
|
||||
{TextOf(para(ParagraphStyle{}, Run{Text: "foo.", Attributes: Attributes{Weight: 700}}, Run{Text: " bar"})), "**foo.** bar"},
|
||||
} {
|
||||
if got := c.text.Markdown(); got != c.want {
|
||||
t.Errorf("%q: got %q, want %q", c.text.String(), got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestCodecsSanitize checks what pasted documents may not bring: styles
|
||||
// out of range, links that run scripts, sizes that aren't, pictures too
|
||||
// large to decode, and another app's copy taken for this one's.
|
||||
func TestCodecsSanitize(t *testing.T) {
|
||||
at, ok := decodeClip([]byte(`{"paragraphs":[{"style":{"list":1,"indent":-1,"heading":99},"runs":[{"text":"x","attributes":{"link":" javascript:alert(1)"}}]}]}`))
|
||||
if !ok {
|
||||
t.Fatal("not decoded")
|
||||
}
|
||||
if st := at.ParagraphStyleAt(0); st.Indent != 0 || st.Heading != 6 {
|
||||
t.Errorf("style %+v", st)
|
||||
}
|
||||
_ = at.HTML()
|
||||
_ = at.Markdown()
|
||||
for _, src := range []string{`<a href=" javascript:alert(1)">x</a>`, "<a href=\"java\tscript:alert(1)\">x</a>", `<a href="VBScript:x">x</a>`} {
|
||||
if l := ParseHTML(src).AttributesAt(0).Link; l != "" {
|
||||
t.Errorf("%s: link %q", src, l)
|
||||
}
|
||||
}
|
||||
if l := ParseRTF([]byte(`{\rtf1{\field{\*\fldinst HYPERLINK "javascript:alert(1)"}{\fldrslt x}}}`)).AttributesAt(0).Link; l != "" {
|
||||
t.Errorf("RTF link %q", l)
|
||||
}
|
||||
if h := TextOf(Paragraph{Runs: []Run{{Text: "x", Attributes: Attributes{Link: "javascript:alert(1)"}}}}).HTML(); strings.Contains(h, "javascript") {
|
||||
t.Errorf("HTML %s", h)
|
||||
}
|
||||
img := ParseHTML(`<img src="x.png" width="NaN" height="-Inf">`)
|
||||
if a := img.AttributesAt(0).Attachment; a == nil || a.Width != 0 || a.Height != 0 {
|
||||
t.Errorf("attachment %+v", a)
|
||||
} else if _, err := img.MarshalJSON(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
// Another app's copy with the name of this one's is its own text.
|
||||
encodeClip(NewText("my old copy"))
|
||||
if got, _ := decodeClip([]byte(`{"copy":"1","paragraphs":[{"runs":[{"text":"theirs"}]}]}`)); got.String() != "theirs" {
|
||||
t.Errorf("pasted %q", got.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestHTMLQuotes checks that quoted lists, headings and code stay quoted
|
||||
// through HTML.
|
||||
func TestHTMLQuotes(t *testing.T) {
|
||||
in := TextOf(
|
||||
Paragraph{Style: ParagraphStyle{Quote: true, Heading: 2}, Runs: []Run{{Text: "QH"}}},
|
||||
Paragraph{Style: ParagraphStyle{Quote: true, List: Bullets}, Runs: []Run{{Text: "item"}}},
|
||||
Paragraph{Style: ParagraphStyle{Quote: true, CodeBlock: true}, Runs: []Run{{Text: "code"}}},
|
||||
Paragraph{Runs: []Run{{Text: "after"}}},
|
||||
)
|
||||
out := ParseHTML(in.HTML())
|
||||
i := 0
|
||||
for _, p := range out.Paragraphs() {
|
||||
want := i < 3
|
||||
i++
|
||||
if p.Style.Quote != want {
|
||||
t.Errorf("paragraph %d %v: quote %v (%s)", i, p.Runs, p.Style.Quote, in.HTML())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRTFWordPad checks what WordPad and Word write: lists of \pntext,
|
||||
// table cells, hidden text, non-breaking hyphens and links to bookmarks.
|
||||
func TestRTFWordPad(t *testing.T) {
|
||||
at := ParseRTF([]byte(`{\rtf1{\pntext\f1\'B7\tab}{\*\pn\pnlvlblt{\pntxtb\'B7}}one\par{\pntext 1.\tab}{\*\pn\pnlvlbody}first\par
|
||||
e\_mail vis{\v hid}ible\par alpha\cell beta\cell\row {\field{\*\fldinst HYPERLINK \\l "top"}{\fldrslt up}}\par}`))
|
||||
var got []string
|
||||
for _, p := range at.Paragraphs() {
|
||||
got = append(got, fmt.Sprintf("%d:%s", p.Style.List, plainOf(p)))
|
||||
}
|
||||
want := []string{"1:one", "2:first", "0:e‑mail visible", "0:alpha\tbeta\t", "0:up"}
|
||||
if strings.Join(got, "|") != strings.Join(want, "|") {
|
||||
t.Errorf("got %q, want %q", got, want)
|
||||
}
|
||||
if l := at.AttributesAt(at.Len() - 1).Link; l != "#top" {
|
||||
t.Errorf("link %q", l)
|
||||
}
|
||||
}
|
||||
+365
@@ -0,0 +1,365 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// FormatState is whether a format holds for a selection: all of it, none,
|
||||
// or some of it, as a toolbar's button shows it.
|
||||
type FormatState uint8
|
||||
|
||||
const (
|
||||
FormatOff FormatState = iota
|
||||
FormatOn
|
||||
FormatMixed
|
||||
)
|
||||
|
||||
// Formatting describes the formats of a document's selection, as
|
||||
// a toolbar and a Format menu show them: of the runes selected, or of the
|
||||
// typing attributes at a caret.
|
||||
type Formatting struct {
|
||||
// Attributes are those of the first rune selected, or the typing
|
||||
// attributes at a caret.
|
||||
Attributes Attributes
|
||||
Bold, Italic, Underline, Strikethrough, Code FormatState
|
||||
// Link is the link all of the selection is in, "" when none is.
|
||||
Link string
|
||||
// Paragraph is the style of the first paragraph selected, and
|
||||
// ParagraphsMixed whether others differ from it.
|
||||
Paragraph ParagraphStyle
|
||||
ParagraphsMixed bool
|
||||
}
|
||||
|
||||
// Formatting returns the formats of the selection.
|
||||
func (d *Document) Formatting() Formatting {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
return d.formatting()
|
||||
}
|
||||
|
||||
func (d *Document) formatting() Formatting {
|
||||
a, z := d.span()
|
||||
f := Formatting{Attributes: d.typingAttributes()}
|
||||
if a < z {
|
||||
// From the first rune that takes a format, not a newline.
|
||||
for _, r := range d.text.Runs(a, z) {
|
||||
if r.Text != "\n" {
|
||||
f.Attributes = r.Attributes
|
||||
f.Attributes.Attachment = nil
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
state := func(on bool) FormatState {
|
||||
if on {
|
||||
return FormatOn
|
||||
}
|
||||
return FormatOff
|
||||
}
|
||||
at := f.Attributes
|
||||
f.Bold, f.Italic, f.Underline, f.Strikethrough, f.Code = state(at.Bold()), state(at.Italic), state(at.Underline), state(at.Strikethrough), state(at.Code)
|
||||
f.Link = at.Link
|
||||
if a < z {
|
||||
mix := func(s *FormatState, on bool) {
|
||||
if (*s == FormatOn) != on {
|
||||
*s = FormatMixed
|
||||
}
|
||||
}
|
||||
for _, r := range d.text.Runs(a, z) {
|
||||
if r.Text == "\n" {
|
||||
continue // a newline selected takes no format
|
||||
}
|
||||
x := r.Attributes
|
||||
mix(&f.Bold, x.Bold())
|
||||
mix(&f.Italic, x.Italic)
|
||||
mix(&f.Underline, x.Underline)
|
||||
mix(&f.Strikethrough, x.Strikethrough)
|
||||
mix(&f.Code, x.Code)
|
||||
if x.Link != f.Link {
|
||||
f.Link = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
pa, pz := d.text.paragraphSpan(a, z)
|
||||
seqEach(d.text.seq(), pa, func(i int, p *richPara) bool {
|
||||
st := p.style
|
||||
if i == pa {
|
||||
f.Paragraph = st
|
||||
} else if st.ID = f.Paragraph.ID; st != f.Paragraph {
|
||||
// Paragraphs of other IDs look the same.
|
||||
f.ParagraphsMixed = true
|
||||
}
|
||||
return i < pz
|
||||
})
|
||||
return f
|
||||
}
|
||||
|
||||
// Format changes the attributes of the selection with fn, as one step of
|
||||
// undo, or the typing attributes at a caret.
|
||||
func (d *Document) Format(fn func(a *Attributes)) {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
d.format(fn)
|
||||
}
|
||||
|
||||
func (d *Document) format(fn func(a *Attributes)) {
|
||||
a, z := d.span()
|
||||
if a == z {
|
||||
t := d.typingAttributes()
|
||||
fn(&t)
|
||||
t.Attachment = nil
|
||||
d.typing = &t
|
||||
return
|
||||
}
|
||||
anchor, caret := d.anchor, d.caret
|
||||
d.edit(false, func(e *Edit) { e.Format(a, z, fn) })
|
||||
d.anchor, d.caret = anchor, caret
|
||||
}
|
||||
|
||||
// toggle turns a format on for the selection unless all of it has it, then
|
||||
// off.
|
||||
func (d *Document) toggle(state func(f Formatting) FormatState, set func(a *Attributes, on bool)) {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
on := state(d.formatting()) != FormatOn
|
||||
d.format(func(a *Attributes) { set(a, on) })
|
||||
}
|
||||
|
||||
// ToggleBold makes the selection bold, or not when all of it is, as ⌘B
|
||||
// does.
|
||||
func (d *Document) ToggleBold() {
|
||||
d.toggle(func(f Formatting) FormatState { return f.Bold }, func(a *Attributes, on bool) {
|
||||
if on {
|
||||
a.Weight = 700
|
||||
} else {
|
||||
a.Weight = 0
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ToggleItalic, ToggleUnderline, ToggleStrikethrough and ToggleCode turn
|
||||
// those formats on for the selection, or off when all of it has them.
|
||||
func (d *Document) ToggleItalic() {
|
||||
d.toggle(func(f Formatting) FormatState { return f.Italic }, func(a *Attributes, on bool) { a.Italic = on })
|
||||
}
|
||||
|
||||
func (d *Document) ToggleUnderline() {
|
||||
d.toggle(func(f Formatting) FormatState { return f.Underline }, func(a *Attributes, on bool) { a.Underline = on })
|
||||
}
|
||||
|
||||
func (d *Document) ToggleStrikethrough() {
|
||||
d.toggle(func(f Formatting) FormatState { return f.Strikethrough }, func(a *Attributes, on bool) { a.Strikethrough = on })
|
||||
}
|
||||
|
||||
func (d *Document) ToggleCode() {
|
||||
d.toggle(func(f Formatting) FormatState { return f.Code }, func(a *Attributes, on bool) { a.Code = on })
|
||||
}
|
||||
|
||||
// linkRange returns the runes around i that link to the same URL as the
|
||||
// rune at i, or i, i.
|
||||
func (t Text) linkRange(i int) (int, int) {
|
||||
url := t.AttributesAt(i).Link
|
||||
if url == "" || i >= t.Len() {
|
||||
return i, i
|
||||
}
|
||||
ps, pe := t.ParagraphRange(i)
|
||||
a, z := i, i
|
||||
for a > ps && t.AttributesAt(a-1).Link == url {
|
||||
a--
|
||||
}
|
||||
for z < pe && t.AttributesAt(z).Link == url {
|
||||
z++
|
||||
}
|
||||
return a, z
|
||||
}
|
||||
|
||||
// SetLink links the selection to url, or takes its link away for "". At a
|
||||
// caret inside a link, it changes or takes away that link; elsewhere it
|
||||
// inserts url, linked to itself.
|
||||
func (d *Document) SetLink(url string) {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
a, z := d.span()
|
||||
if a == z {
|
||||
la, lz := d.text.linkRange(a)
|
||||
if la == lz && a > 0 {
|
||||
la, lz = d.text.linkRange(a - 1)
|
||||
if lz != a {
|
||||
la, lz = a, a
|
||||
}
|
||||
}
|
||||
if la == lz {
|
||||
if url != "" {
|
||||
attrs := d.typingAttributes()
|
||||
attrs.Link = url
|
||||
d.edit(false, func(e *Edit) { e.ReplaceString(a, a, url, attrs) })
|
||||
}
|
||||
return
|
||||
}
|
||||
a, z = la, lz
|
||||
}
|
||||
anchor, caret := d.anchor, d.caret
|
||||
d.edit(false, func(e *Edit) { e.Format(a, z, func(x *Attributes) { x.Link = url }) })
|
||||
d.anchor, d.caret = anchor, caret
|
||||
}
|
||||
|
||||
// FormatParagraphs changes the styles of the paragraphs selected with fn,
|
||||
// as one step of undo.
|
||||
func (d *Document) FormatParagraphs(fn func(p *ParagraphStyle)) {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
d.formatParagraphs(fn)
|
||||
}
|
||||
|
||||
func (d *Document) formatParagraphs(fn func(p *ParagraphStyle)) {
|
||||
a, z := d.span()
|
||||
anchor, caret, typing := d.anchor, d.caret, d.typing
|
||||
d.edit(false, func(e *Edit) { e.FormatParagraphs(a, z, fn) })
|
||||
d.anchor, d.caret, d.typing = anchor, caret, typing
|
||||
}
|
||||
|
||||
// paragraphsAll reports whether every paragraph selected satisfies fn.
|
||||
func (d *Document) paragraphsAll(fn func(p ParagraphStyle) bool) bool {
|
||||
a, z := d.span()
|
||||
pa, pz := d.text.paragraphSpan(a, z)
|
||||
all := true
|
||||
seqEach(d.text.seq(), pa, func(i int, p *richPara) bool {
|
||||
all = fn(p.style)
|
||||
return all && i < pz
|
||||
})
|
||||
return all
|
||||
}
|
||||
|
||||
// SetHeading makes the paragraphs selected headings of level, from 1, or
|
||||
// body paragraphs for 0.
|
||||
func (d *Document) SetHeading(level int) {
|
||||
d.FormatParagraphs(func(p *ParagraphStyle) {
|
||||
p.Heading = max(0, min(level, 6))
|
||||
if p.Heading > 0 {
|
||||
p.List, p.Checked, p.CodeBlock = NoList, false, false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ToggleList makes the paragraphs selected items of a list of kind, or
|
||||
// takes them out of it when all of them are.
|
||||
func (d *Document) ToggleList(kind ListKind) {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
off := d.paragraphsAll(func(p ParagraphStyle) bool { return p.List == kind })
|
||||
d.formatParagraphs(func(p *ParagraphStyle) {
|
||||
if off {
|
||||
p.List, p.Checked = NoList, false
|
||||
return
|
||||
}
|
||||
p.List, p.Heading, p.CodeBlock = kind, 0, false
|
||||
if kind != Tasks {
|
||||
p.Checked = false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ToggleQuote and ToggleCodeBlock make the paragraphs selected a quotation
|
||||
// or a block of code, or not when all of them are.
|
||||
func (d *Document) ToggleQuote() {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
off := d.paragraphsAll(func(p ParagraphStyle) bool { return p.Quote })
|
||||
d.formatParagraphs(func(p *ParagraphStyle) {
|
||||
if off || !p.Quote {
|
||||
p.QuoteDepth = 0
|
||||
}
|
||||
p.Quote = !off
|
||||
})
|
||||
}
|
||||
|
||||
func (d *Document) ToggleCodeBlock() {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
off := d.paragraphsAll(func(p ParagraphStyle) bool { return p.CodeBlock })
|
||||
d.formatParagraphs(func(p *ParagraphStyle) {
|
||||
p.CodeBlock = !off
|
||||
if p.CodeBlock {
|
||||
p.Heading, p.List, p.Checked = 0, NoList, false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// maxIndent is the deepest a paragraph indents.
|
||||
const maxIndent = 8
|
||||
|
||||
// Indent indents the paragraphs selected by levels, or outdents them for
|
||||
// a negative count, as Tab and Shift-Tab do in a list.
|
||||
func (d *Document) Indent(levels int) {
|
||||
d.FormatParagraphs(func(p *ParagraphStyle) { p.Indent = max(0, min(p.Indent+levels, maxIndent)) })
|
||||
}
|
||||
|
||||
// SetAlign aligns the lines of the paragraphs selected.
|
||||
func (d *Document) SetAlign(a ui.Align) {
|
||||
d.FormatParagraphs(func(p *ParagraphStyle) { p.Align = a })
|
||||
}
|
||||
|
||||
// ToggleChecked checks the task holding rune i, or unchecks it.
|
||||
func (d *Document) ToggleChecked(i int) {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
anchor, caret, typing := d.anchor, d.caret, d.typing
|
||||
d.edit(false, func(e *Edit) {
|
||||
e.FormatParagraphs(i, i, func(p *ParagraphStyle) {
|
||||
if p.List == Tasks {
|
||||
p.Checked = !p.Checked
|
||||
}
|
||||
})
|
||||
})
|
||||
d.anchor, d.caret, d.typing = anchor, caret, typing
|
||||
}
|
||||
|
||||
// InsertText replaces the selection with s, in the typing attributes, as
|
||||
// typing does but as a step of undo of its own.
|
||||
func (d *Document) InsertText(s string) {
|
||||
s = normalizeNewlines(s)
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
a, z := d.span()
|
||||
attrs := d.typingAttributes()
|
||||
d.edit(false, func(e *Edit) {
|
||||
n := e.Text().Len()
|
||||
e.ReplaceString(a, z, s, attrs)
|
||||
end := z + e.Text().Len() - n
|
||||
e.Select(end, end)
|
||||
})
|
||||
}
|
||||
|
||||
// Insert replaces the selection with text, as a paste does.
|
||||
func (d *Document) Insert(text Text) {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
a, z := d.span()
|
||||
d.edit(false, func(e *Edit) {
|
||||
e.Replace(a, z, text)
|
||||
e.Select(a+text.Len(), a+text.Len())
|
||||
})
|
||||
}
|
||||
|
||||
// InsertAttachment replaces the selection with an attachment.
|
||||
func (d *Document) InsertAttachment(a *Attachment) {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
s, z := d.span()
|
||||
attrs := d.typingAttributes().extending()
|
||||
attrs.Attachment = a
|
||||
d.edit(false, func(e *Edit) {
|
||||
e.ReplaceString(s, z, string(ObjectReplacement), attrs)
|
||||
e.Select(s+1, s+1)
|
||||
})
|
||||
}
|
||||
|
||||
// normalizeNewlines turns the newlines of other systems into "\n".
|
||||
func normalizeNewlines(s string) string {
|
||||
if !strings.ContainsAny(s, "\r\u2029") {
|
||||
return s
|
||||
}
|
||||
return strings.NewReplacer("\r\n", "\n", "\r", "\n", "
", "\n").Replace(s)
|
||||
}
|
||||
+536
@@ -0,0 +1,536 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
"weak"
|
||||
)
|
||||
|
||||
// Document is what an Editor edits: a Text, its
|
||||
// selection with the attributes typing gets there, and the history of
|
||||
// undo, which the app keeps from frame to frame, as it keeps a TextBuffer.
|
||||
// Its methods are safe from any goroutine: a toolbar, a menu or a timer
|
||||
// formats and edits it while the editor shows it, and the editor follows
|
||||
// what changed at its next frame (schedule changes from other goroutines
|
||||
// with Window.Update, so that a frame comes).
|
||||
//
|
||||
// Commands act on the selection as the editor's shortcuts do: on a range
|
||||
// they change its runs or paragraphs, as one step of undo; on a caret,
|
||||
// character formats change only the typing attributes, which the next
|
||||
// typed text gets and the next move of the caret forgets, as ⌘B does in
|
||||
// NSTextView.
|
||||
type Document struct {
|
||||
mu sync.Mutex
|
||||
text Text
|
||||
anchor int
|
||||
caret int
|
||||
typing *Attributes // nil: derived from the text at the caret
|
||||
version uint64
|
||||
// selVersion counts changes of the selection made by the document's
|
||||
// methods, which the editor then takes.
|
||||
selVersion uint64
|
||||
undo, redo []undoStep
|
||||
lastEdit time.Time
|
||||
coalesce bool // typing may join the last step
|
||||
// log is what changed since the versions the editor last saw, for it
|
||||
// to lay out only the paragraphs that changed.
|
||||
log []change
|
||||
// newID names the paragraphs edits make (IdentifyParagraphs).
|
||||
newID func() string
|
||||
// shownIn is the editor built last that shows the document, for
|
||||
// VisibleParagraphs and CaretRect: an app that shows it in two
|
||||
// editors reads each one's right after building it. What was read is
|
||||
// kept in that editor, for its next paint to tell whether it moved
|
||||
// what was read; readNone is set when the app read them with no
|
||||
// editor yet, for the first to paint to ask for another frame.
|
||||
shownIn weak.Pointer[view]
|
||||
readNone bool
|
||||
}
|
||||
|
||||
// change is a change of a document: the runes from start to oldEnd
|
||||
// became those from start to newEnd, at version.
|
||||
type change struct {
|
||||
version uint64
|
||||
start, oldEnd, newEnd int
|
||||
}
|
||||
|
||||
// undoStep is a step of undo: the texts before and after it, which share
|
||||
// all they did not change, the selections, and the region it changed.
|
||||
type undoStep struct {
|
||||
before, after Text
|
||||
selBefore, selAfter [2]int
|
||||
start, oldEnd, newEnd int
|
||||
// parts are its replacements in the order they were made, each in the
|
||||
// text the ones before it left, for undo and redo to tell the editor
|
||||
// of one by one, as the edit did; nil past maxUndoParts (typing a
|
||||
// while), for them to tell it of the region.
|
||||
parts []change
|
||||
}
|
||||
|
||||
// maxUndoParts is how many replacements a step of undo keeps: more than
|
||||
// the edits that move text need (a move is two), and well under the 128
|
||||
// changes the log keeps for the editor, past which it lays the whole text
|
||||
// out again. A longer step, as typing a while, is one region.
|
||||
const maxUndoParts = 16
|
||||
|
||||
// NewDocument returns a document of text, its caret at the end.
|
||||
func NewDocument(text Text) *Document {
|
||||
n := text.Len()
|
||||
return &Document{text: text, anchor: n, caret: n, version: 1}
|
||||
}
|
||||
|
||||
func (d *Document) lock() {
|
||||
d.mu.Lock()
|
||||
if d.version == 0 {
|
||||
d.version = 1 // the zero value is an empty document
|
||||
}
|
||||
}
|
||||
|
||||
// Text returns the text of the document, which later edits leave as it is.
|
||||
func (d *Document) Text() Text {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
return d.text
|
||||
}
|
||||
|
||||
// Version counts the changes of the document's text.
|
||||
func (d *Document) Version() uint64 {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
return d.version
|
||||
}
|
||||
|
||||
// SetText replaces the text, as when the app opens another note: it is not
|
||||
// a step of undo, and clears the history. The selection goes to the end.
|
||||
func (d *Document) SetText(text Text) {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
old := d.text.Len()
|
||||
d.text = d.identify(text, 0, text.ParagraphCount()-1)
|
||||
d.undo, d.redo = nil, nil
|
||||
d.coalesce = false
|
||||
d.changed(0, old, text.Len())
|
||||
n := text.Len()
|
||||
d.setSelection(n, n)
|
||||
}
|
||||
|
||||
// Selection returns the selection: anchor is where it started, caret where
|
||||
// it ends and the caret is, equal for a caret.
|
||||
func (d *Document) Selection() (anchor, caret int) {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
return d.anchor, d.caret
|
||||
}
|
||||
|
||||
// SetSelection selects the runes between anchor and caret, or puts the
|
||||
// caret at caret when they are equal; the editor scrolls it into view.
|
||||
func (d *Document) SetSelection(anchor, caret int) {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
d.setSelection(anchor, caret)
|
||||
}
|
||||
|
||||
func (d *Document) setSelection(anchor, caret int) {
|
||||
n := d.text.Len()
|
||||
d.anchor, d.caret = max(0, min(anchor, n)), max(0, min(caret, n))
|
||||
d.typing = nil
|
||||
d.coalesce = false
|
||||
d.selVersion++
|
||||
}
|
||||
|
||||
func (d *Document) span() (int, int) {
|
||||
return min(d.anchor, d.caret), max(d.anchor, d.caret)
|
||||
}
|
||||
|
||||
// TypingAttributes returns the attributes typing gets at the caret: those
|
||||
// a command set at the caret, else those of the character before it (after
|
||||
// it at the start of a paragraph), or of the first selected character,
|
||||
// without a link, code or tag at their edges, as NSTextView derives them.
|
||||
func (d *Document) TypingAttributes() Attributes {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
return d.typingAttributes()
|
||||
}
|
||||
|
||||
func (d *Document) typingAttributes() Attributes {
|
||||
if d.typing != nil {
|
||||
return *d.typing
|
||||
}
|
||||
a, z := d.span()
|
||||
return typingAttributes(d.text, a, z)
|
||||
}
|
||||
|
||||
// typingAttributes returns the attributes typing gets in place of the runes
|
||||
// from start to end of t.
|
||||
func typingAttributes(t Text, start, end int) Attributes {
|
||||
if start < end {
|
||||
a := t.AttributesAt(start)
|
||||
a.Attachment = nil
|
||||
return a
|
||||
}
|
||||
ps, _ := t.ParagraphRange(start)
|
||||
if start == ps {
|
||||
return t.AttributesAt(start).extending()
|
||||
}
|
||||
before, after := t.AttributesAt(start-1), t.AttributesAt(start)
|
||||
if _, pe := t.ParagraphRange(start); start == pe {
|
||||
// The newline: a link or code ends with the line, as a selection
|
||||
// of whole lines formats newlines too.
|
||||
after = Attributes{}
|
||||
}
|
||||
a := before.extending()
|
||||
// What does not extend holds inside: between two runes of a link.
|
||||
if before.Link == after.Link {
|
||||
a.Link = before.Link
|
||||
}
|
||||
if before.Code && after.Code {
|
||||
a.Code = true
|
||||
}
|
||||
if before.Tag == after.Tag {
|
||||
a.Tag = before.Tag
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// SetTypingAttributes sets the attributes the next typed text gets, until
|
||||
// the caret moves.
|
||||
func (d *Document) SetTypingAttributes(a Attributes) {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
a.Attachment = nil
|
||||
d.typing = &a
|
||||
}
|
||||
|
||||
// changed notes that the runes from start to oldEnd became those from start
|
||||
// to newEnd.
|
||||
func (d *Document) changed(start, oldEnd, newEnd int) {
|
||||
d.version++
|
||||
d.log = append(d.log, change{d.version, start, oldEnd, newEnd})
|
||||
if len(d.log) > 256 {
|
||||
// The editor reloads a text it is too far behind.
|
||||
d.log = append(d.log[:0], d.log[len(d.log)-128:]...)
|
||||
}
|
||||
}
|
||||
|
||||
// since returns the change from version v to the document's, as one
|
||||
// region, the changes it is made of in the order they were made, and
|
||||
// whether the log holds all of it. The changes are the log's, which the
|
||||
// next change of the document reuses.
|
||||
func (d *Document) since(v uint64) (change, []change, bool) {
|
||||
if v == d.version {
|
||||
return change{version: v}, nil, true
|
||||
}
|
||||
var c change
|
||||
from := -1
|
||||
for i, l := range d.log {
|
||||
if l.version <= v {
|
||||
continue
|
||||
}
|
||||
if from < 0 {
|
||||
if l.version != v+1 {
|
||||
return change{}, nil, false
|
||||
}
|
||||
c, from = l, i
|
||||
continue
|
||||
}
|
||||
c = composeChanges(c, l)
|
||||
}
|
||||
if from < 0 || c.version != d.version {
|
||||
return change{}, nil, false
|
||||
}
|
||||
return c, d.log[from:], true
|
||||
}
|
||||
|
||||
// composeChanges returns the change a then b make together.
|
||||
func composeChanges(a, b change) change {
|
||||
// Map a's new end through b, and b's old end back through a.
|
||||
end := a.newEnd
|
||||
switch {
|
||||
case end > b.start && end < b.oldEnd:
|
||||
end = b.newEnd
|
||||
case end >= b.oldEnd:
|
||||
end += b.newEnd - b.oldEnd
|
||||
}
|
||||
old := b.oldEnd
|
||||
switch {
|
||||
case old > a.start && old < a.newEnd:
|
||||
old = a.oldEnd
|
||||
case old >= a.newEnd:
|
||||
old -= a.newEnd - a.oldEnd
|
||||
}
|
||||
return change{
|
||||
version: b.version,
|
||||
start: min(a.start, b.start),
|
||||
oldEnd: max(a.oldEnd, old),
|
||||
newEnd: max(end, b.newEnd),
|
||||
}
|
||||
}
|
||||
|
||||
// Edit changes a document as one step of undo, in
|
||||
// Document.Edit. Offsets are into the text as the edit's changes
|
||||
// so far left it, and the selection follows them.
|
||||
type Edit struct {
|
||||
d *Document
|
||||
step *undoStep
|
||||
}
|
||||
|
||||
// Text returns the text as the edit's changes so far left it.
|
||||
func (e *Edit) Text() Text { return e.d.text }
|
||||
|
||||
// Selection returns the selection as the edit's changes so far moved it.
|
||||
func (e *Edit) Selection() (anchor, caret int) { return e.d.anchor, e.d.caret }
|
||||
|
||||
// Select selects the runes between anchor and caret.
|
||||
func (e *Edit) Select(anchor, caret int) { e.d.setSelection(anchor, caret) }
|
||||
|
||||
// Replace replaces the runes from start to end with text.
|
||||
func (e *Edit) Replace(start, end int, text Text) {
|
||||
n := e.d.text.Len()
|
||||
start, end = max(0, min(start, end, n)), max(0, min(max(start, end), n))
|
||||
e.d.apply(e.step, start, end-start, text.Len(), e.d.text.Replace(start, end, text))
|
||||
}
|
||||
|
||||
// ReplaceString replaces the runes from start to end with s, which takes
|
||||
// attributes a.
|
||||
func (e *Edit) ReplaceString(start, end int, s string, a Attributes) {
|
||||
n := e.d.text.Len()
|
||||
start, end = max(0, min(start, end, n)), max(0, min(max(start, end), n))
|
||||
t := e.d.text.ReplaceString(start, end, s, a)
|
||||
e.d.apply(e.step, start, end-start, t.Len()-n+end-start, t)
|
||||
}
|
||||
|
||||
// Format changes the attributes of the runes from start to end.
|
||||
func (e *Edit) Format(start, end int, fn func(a *Attributes)) {
|
||||
n := e.d.text.Len()
|
||||
start, end = max(0, min(start, end, n)), max(0, min(max(start, end), n))
|
||||
t := e.d.text.Format(start, end, fn)
|
||||
if !t.Same(e.d.text) {
|
||||
e.d.apply(e.step, start, end-start, end-start, t)
|
||||
}
|
||||
}
|
||||
|
||||
// FormatParagraphs changes the styles of the paragraphs from the one
|
||||
// holding start to the one holding end (see Text.FormatParagraphs).
|
||||
func (e *Edit) FormatParagraphs(start, end int, fn func(p *ParagraphStyle)) {
|
||||
t := e.d.text
|
||||
pa, pz := t.paragraphSpan(start, end)
|
||||
a := t.paraStart(pa)
|
||||
z := t.paraStart(pz) + seqAt(t.seq(), pz).n
|
||||
if f := t.FormatParagraphs(start, end, fn); !f.Same(t) {
|
||||
e.d.apply(e.step, a, z-a, z-a, f)
|
||||
}
|
||||
}
|
||||
|
||||
// apply makes t, in which the runes from start to start+removed of the text
|
||||
// are now start to start+inserted, the document's text, as part of step.
|
||||
func (d *Document) apply(step *undoStep, start, removed, inserted int, t Text) {
|
||||
t = d.identify(t, t.paraAt(start), t.paraAt(start+inserted))
|
||||
formatted := t.text == d.text.text // the text is the same: only formats changed
|
||||
d.text = t
|
||||
if step != nil {
|
||||
part := change{start: start, oldEnd: start + removed, newEnd: start + inserted}
|
||||
if step.start < 0 {
|
||||
step.start, step.oldEnd, step.newEnd = part.start, part.oldEnd, part.newEnd
|
||||
step.parts = []change{part}
|
||||
} else {
|
||||
c := composeChanges(change{start: step.start, oldEnd: step.oldEnd, newEnd: step.newEnd}, part)
|
||||
step.start, step.oldEnd, step.newEnd = c.start, c.oldEnd, c.newEnd
|
||||
if step.parts != nil && len(step.parts) < maxUndoParts {
|
||||
step.parts = append(step.parts, part)
|
||||
} else {
|
||||
step.parts = nil
|
||||
}
|
||||
}
|
||||
step.after = t
|
||||
}
|
||||
d.changed(start, start+removed, start+inserted)
|
||||
if formatted {
|
||||
return
|
||||
}
|
||||
a, z := d.span()
|
||||
if a == z {
|
||||
a = mapPosition(a, start, removed, inserted, false)
|
||||
z = a
|
||||
} else {
|
||||
a, z = mapPosition(a, start, removed, inserted, false), mapPosition(z, start, removed, inserted, true)
|
||||
}
|
||||
if d.caret >= d.anchor {
|
||||
d.anchor, d.caret = a, z
|
||||
} else {
|
||||
d.anchor, d.caret = z, a
|
||||
}
|
||||
d.typing = nil
|
||||
}
|
||||
|
||||
// mapPosition returns where p goes as the runes from start to
|
||||
// start+removed become inserted others, as AttributedString tracks indices:
|
||||
// a caret or the start of a range where text is inserted goes after it,
|
||||
// the end of a range does not grow, and what was replaced collapses to
|
||||
// its edges.
|
||||
func mapPosition(p, start, removed, inserted int, upper bool) int {
|
||||
end := start + removed
|
||||
switch {
|
||||
case p < start:
|
||||
return p
|
||||
case removed == 0 && p == start:
|
||||
if upper {
|
||||
return p
|
||||
}
|
||||
return p + inserted
|
||||
case p < end:
|
||||
if upper {
|
||||
return start + inserted
|
||||
}
|
||||
return start
|
||||
}
|
||||
return p + inserted - removed
|
||||
}
|
||||
|
||||
// Edit changes the document with fn, as one step of undo, which undoing
|
||||
// takes back whole with the selection before it:
|
||||
//
|
||||
// doc.Edit(func(e *richtext.Edit) {
|
||||
// e.ReplaceString(0, 0, "Dear Ann,\n", richtext.Attributes{})
|
||||
// e.Format(0, 8, func(a *richtext.Attributes) { a.Italic = true })
|
||||
// })
|
||||
func (d *Document) Edit(fn func(e *Edit)) {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
d.edit(false, fn)
|
||||
}
|
||||
|
||||
// edit runs fn as a step of undo, joined to the last one when join is set
|
||||
// and the last edit was typing a moment ago.
|
||||
func (d *Document) edit(join bool, fn func(e *Edit)) {
|
||||
now := time.Now()
|
||||
var step *undoStep
|
||||
if join && d.coalesce && now.Sub(d.lastEdit) < time.Second && len(d.undo) > 0 {
|
||||
step = &d.undo[len(d.undo)-1]
|
||||
} else {
|
||||
d.undo = append(d.undo, undoStep{before: d.text, after: d.text, selBefore: [2]int{d.anchor, d.caret}, start: -1})
|
||||
step = &d.undo[len(d.undo)-1]
|
||||
}
|
||||
fn(&Edit{d: d, step: step})
|
||||
if step.start < 0 {
|
||||
// Nothing changed.
|
||||
d.undo = d.undo[:len(d.undo)-1]
|
||||
return
|
||||
}
|
||||
if len(d.undo) > 200 {
|
||||
d.undo[0] = undoStep{}
|
||||
d.undo = d.undo[1:]
|
||||
}
|
||||
step.selAfter = [2]int{d.anchor, d.caret}
|
||||
clear(d.redo)
|
||||
d.redo = d.redo[:0]
|
||||
d.coalesce = join
|
||||
d.lastEdit = now
|
||||
}
|
||||
|
||||
// IdentifyParagraphs has newID give an ID (ParagraphStyle.ID) to each
|
||||
// paragraph without one: those of the text now and of SetText, and those
|
||||
// edits make, as a paragraph split or text pasted, in the step of undo
|
||||
// that makes them, so that undo and redo bring them back with their IDs,
|
||||
// and the app finds every paragraph by its ID when it saves:
|
||||
//
|
||||
// doc := richtext.NewDocument(chapter)
|
||||
// doc.IdentifyParagraphs(func() string { return rand.Text() })
|
||||
//
|
||||
// Call it before the document is edited: the steps of undo before it keep
|
||||
// their texts. newID runs with the document locked, so it must not call
|
||||
// the document's methods. nil stops naming paragraphs.
|
||||
func (d *Document) IdentifyParagraphs(newID func() string) {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
d.newID = newID
|
||||
if t := d.identify(d.text, 0, d.text.ParagraphCount()-1); !t.Same(d.text) {
|
||||
d.text = t
|
||||
n := t.Len()
|
||||
d.changed(0, n, n)
|
||||
}
|
||||
}
|
||||
|
||||
// identify returns t with the paragraphs from pa to pz that have no ID
|
||||
// given one, when the document names paragraphs.
|
||||
func (d *Document) identify(t Text, pa, pz int) Text {
|
||||
if d.newID == nil {
|
||||
return t
|
||||
}
|
||||
return t.formatParas(pa, pz, func(p *ParagraphStyle) {
|
||||
if p.ID == "" {
|
||||
p.ID = d.newID()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// CanUndo and CanRedo report whether there is a step to undo or redo.
|
||||
func (d *Document) CanUndo() bool {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
return len(d.undo) > 0
|
||||
}
|
||||
|
||||
func (d *Document) CanRedo() bool {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
return len(d.redo) > 0
|
||||
}
|
||||
|
||||
// Undo takes back the last step of undo, and Redo the last step undone,
|
||||
// restoring the text, its attributes and the selection.
|
||||
func (d *Document) Undo() {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
d.takeBack(false)
|
||||
}
|
||||
|
||||
func (d *Document) Redo() {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
d.takeBack(true)
|
||||
}
|
||||
|
||||
func (d *Document) takeBack(redo bool) {
|
||||
from, to := &d.undo, &d.redo
|
||||
if redo {
|
||||
from, to = to, from
|
||||
}
|
||||
n := len(*from)
|
||||
if n == 0 {
|
||||
return
|
||||
}
|
||||
s := (*from)[n-1]
|
||||
(*from)[n-1] = undoStep{}
|
||||
*from = (*from)[:n-1]
|
||||
switch {
|
||||
case redo:
|
||||
d.text = s.after
|
||||
for _, p := range s.parts {
|
||||
d.changed(p.start, p.oldEnd, p.newEnd)
|
||||
}
|
||||
if s.parts == nil {
|
||||
d.changed(s.start, s.oldEnd, s.newEnd)
|
||||
}
|
||||
d.setSelection(s.selAfter[0], s.selAfter[1])
|
||||
default:
|
||||
// The parts taken back from the last.
|
||||
d.text = s.before
|
||||
for i := len(s.parts) - 1; i >= 0; i-- {
|
||||
p := s.parts[i]
|
||||
d.changed(p.start, p.newEnd, p.oldEnd)
|
||||
}
|
||||
if s.parts == nil {
|
||||
d.changed(s.start, s.newEnd, s.oldEnd)
|
||||
}
|
||||
d.setSelection(s.selBefore[0], s.selBefore[1])
|
||||
}
|
||||
*to = append(*to, s)
|
||||
}
|
||||
|
||||
// BreakUndoCoalescing ends the step typing adds to, as at a save, so that
|
||||
// what is typed next undoes on its own.
|
||||
func (d *Document) BreakUndoCoalescing() {
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
d.coalesce = false
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package richtext
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestDocumentLinkEndsWithLine checks that typing at the end of a line
|
||||
// linked whole, its newline too, doesn't continue the link.
|
||||
func TestDocumentLinkEndsWithLine(t *testing.T) {
|
||||
d := NewDocument(NewText("abc\nxyz"))
|
||||
d.SetSelection(0, 4)
|
||||
d.SetLink("u")
|
||||
d.SetSelection(3, 3)
|
||||
if l := d.TypingAttributes().Link; l != "" {
|
||||
t.Fatalf("typing link %q", l)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDocumentFormattingFromNewline checks the formats of a selection
|
||||
// that starts at a newline: those of the runes after it.
|
||||
func TestDocumentFormattingFromNewline(t *testing.T) {
|
||||
d := NewDocument(TextOf(Paragraph{Runs: []Run{{Text: "plain"}}}, Paragraph{Runs: []Run{{Text: "BOLD", Attributes: Attributes{Weight: 700}}}}))
|
||||
d.SetSelection(5, 10)
|
||||
if f := d.Formatting(); f.Bold != FormatOn {
|
||||
t.Fatalf("bold %v", f.Bold)
|
||||
}
|
||||
d.ToggleBold()
|
||||
if d.Text().AttributesAt(7).Bold() {
|
||||
t.Fatal("⌘B didn't take bold off")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDocumentInsertLeavesCaret checks that inserting over a selection
|
||||
// leaves the caret after what was inserted, as typing and pasting do.
|
||||
func TestDocumentInsertLeavesCaret(t *testing.T) {
|
||||
d := NewDocument(NewText("hello world"))
|
||||
d.SetSelection(6, 11)
|
||||
d.InsertText("there")
|
||||
if a, c := d.Selection(); a != 11 || c != 11 {
|
||||
t.Fatalf("InsertText: selection %d, %d", a, c)
|
||||
}
|
||||
d.SetSelection(0, 1)
|
||||
d.Insert(NewText("A\nB"))
|
||||
if a, c := d.Selection(); a != 3 || c != 3 {
|
||||
t.Fatalf("Insert: selection %d, %d", a, c)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDocumentFormatToEnd checks that formatting to the end of the text
|
||||
// formats what typing gets in a last empty paragraph.
|
||||
func TestDocumentFormatToEnd(t *testing.T) {
|
||||
d := NewDocument(NewText("abc\n"))
|
||||
d.SetSelection(0, 4)
|
||||
d.ToggleBold()
|
||||
d.SetSelection(4, 4)
|
||||
if !d.TypingAttributes().Bold() {
|
||||
t.Fatal("typing at the end isn't bold")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDocumentNoOpSteps checks that commands changing nothing make no
|
||||
// step of undo, and that a full history keeps its steps through them.
|
||||
func TestDocumentNoOpSteps(t *testing.T) {
|
||||
d := NewDocument(NewText("abc"))
|
||||
d.SetSelection(0, 3)
|
||||
v := d.Version()
|
||||
d.SetLink("")
|
||||
d.ToggleChecked(0)
|
||||
if d.Version() != v || d.CanUndo() {
|
||||
t.Fatalf("version %d → %d, can undo %v", v, d.Version(), d.CanUndo())
|
||||
}
|
||||
for range 200 {
|
||||
d.InsertText("x")
|
||||
}
|
||||
n := len(d.undo)
|
||||
d.Edit(func(*Edit) {})
|
||||
if len(d.undo) != n {
|
||||
t.Fatalf("undo steps %d → %d", n, len(d.undo))
|
||||
}
|
||||
}
|
||||
|
||||
// TestDocumentInsertTextCRLF checks that InsertText takes the newlines of
|
||||
// other systems as typing does.
|
||||
func TestDocumentInsertTextCRLF(t *testing.T) {
|
||||
d := NewDocument(NewText("ab"))
|
||||
d.InsertText("c\r\nd\re")
|
||||
if got := d.Text().String(); got != "abc\nd\ne" {
|
||||
t.Fatalf("text %q", got)
|
||||
}
|
||||
if _, c := d.Selection(); c != 7 {
|
||||
t.Fatalf("caret at %d, want 7", c)
|
||||
}
|
||||
}
|
||||
Vendored
+478
@@ -0,0 +1,478 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// Every edit of the editor goes through its document, as one of its steps
|
||||
// of undo, so that undoing it brings its attributes back with its text.
|
||||
|
||||
// lockedPublish gives the document the editor's selection; the caller
|
||||
// holds its lock. A selection moved forgets the typing attributes set at
|
||||
// the caret, as in NSTextView.
|
||||
func (v *view) lockedPublish() {
|
||||
d := v.doc
|
||||
if d.anchor != v.selAnchor || d.caret != v.caret {
|
||||
d.anchor, d.caret = v.selAnchor, v.caret
|
||||
d.typing = nil
|
||||
d.coalesce = false
|
||||
}
|
||||
}
|
||||
|
||||
// publish gives the document the editor's selection.
|
||||
func (v *view) publish() {
|
||||
v.doc.lock()
|
||||
defer v.doc.mu.Unlock()
|
||||
v.lockedPublish()
|
||||
}
|
||||
|
||||
// record starts an action of the editor: typing joins the step typing
|
||||
// made last, anything else starts a step of its own.
|
||||
func (v *view) record(typing bool) {
|
||||
if typing && v.coalesce {
|
||||
v.mode = typingStep
|
||||
} else {
|
||||
v.mode = newStep
|
||||
}
|
||||
v.coalesce = typing
|
||||
}
|
||||
|
||||
// replace replaces the runes from start to end with s in the typing
|
||||
// attributes, as part of the action's step of undo, and puts the caret
|
||||
// after it.
|
||||
func (v *view) replace(start, end int, s string) {
|
||||
d := v.doc
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
if c, ok := v.lockedSync(); ok {
|
||||
start = mapPosition(start, c.start, c.oldEnd-c.start, c.newEnd-c.start, false)
|
||||
end = mapPosition(end, c.start, c.oldEnd-c.start, c.newEnd-c.start, true)
|
||||
}
|
||||
v.lockedPublish()
|
||||
attrs := typingAttributes(d.text, start, end)
|
||||
if d.typing != nil {
|
||||
attrs = *d.typing
|
||||
}
|
||||
v.lockedEdit(func(e *Edit) { e.ReplaceString(start, end, s, attrs) })
|
||||
caret := start + utf8.RuneCountInString(s)
|
||||
v.selAnchor, v.caret = caret, caret
|
||||
d.anchor, d.caret = caret, caret
|
||||
if s == "" && start < end {
|
||||
// Typing again where text was deleted gets its attributes, until
|
||||
// the caret moves, as in NSTextView.
|
||||
keep := attrs
|
||||
d.typing = &keep
|
||||
}
|
||||
v.affinity = ui.TextDownstream
|
||||
v.hasDesired = false
|
||||
v.reveal = true
|
||||
}
|
||||
|
||||
// lockedEdit runs fn as an edit of the document in the action's step, and
|
||||
// takes what it changed; the caller holds the lock.
|
||||
func (v *view) lockedEdit(fn func(e *Edit)) {
|
||||
d := v.doc
|
||||
before := d.version
|
||||
switch v.mode {
|
||||
case sameStep:
|
||||
if len(d.undo) > 0 {
|
||||
s := &d.undo[len(d.undo)-1]
|
||||
fn(&Edit{d: d, step: s})
|
||||
s.selAfter = [2]int{d.anchor, d.caret}
|
||||
clear(d.redo)
|
||||
d.redo = d.redo[:0]
|
||||
break
|
||||
}
|
||||
d.edit(false, fn)
|
||||
default:
|
||||
d.edit(v.mode == typingStep, fn)
|
||||
// Typing that starts a step lets the typing after it join it.
|
||||
d.coalesce = v.coalesce
|
||||
}
|
||||
v.mode = sameStep
|
||||
if d.version != before {
|
||||
v.changed = true
|
||||
v.lockedSync()
|
||||
}
|
||||
}
|
||||
|
||||
// edit runs fn as a step of undo of its own, as a shortcut's conversion
|
||||
// does.
|
||||
func (v *view) edit(fn func(e *Edit)) {
|
||||
d := v.doc
|
||||
d.lock()
|
||||
defer d.mu.Unlock()
|
||||
v.lockedSync()
|
||||
v.lockedPublish()
|
||||
v.mode = newStep
|
||||
v.lockedEdit(fn)
|
||||
v.mode = newStep
|
||||
v.coalesce = false
|
||||
v.selAnchor, v.caret = d.anchor, d.caret
|
||||
v.selVersion = d.selVersion
|
||||
v.reveal = true
|
||||
}
|
||||
|
||||
// command runs a command of the document on the editor's selection.
|
||||
func (v *view) command(fn func(d *Document)) {
|
||||
v.publish()
|
||||
before := v.doc.Version()
|
||||
fn(v.doc)
|
||||
if v.doc.Version() != before {
|
||||
v.changed = true
|
||||
}
|
||||
v.sync()
|
||||
v.mode, v.coalesce = newStep, false
|
||||
}
|
||||
|
||||
// takeBack undoes the document's last step, or redoes the last undone.
|
||||
func (v *view) takeBack(redo bool) {
|
||||
v.command(func(d *Document) {
|
||||
if redo {
|
||||
d.Redo()
|
||||
} else {
|
||||
d.Undo()
|
||||
}
|
||||
})
|
||||
v.reveal = true
|
||||
}
|
||||
|
||||
// insert replaces the selection with s, as typing does.
|
||||
func (v *view) insert(s string) {
|
||||
if v.opts.ReadOnly {
|
||||
return
|
||||
}
|
||||
s = normalizeNewlines(s)
|
||||
a, z := v.selection()
|
||||
v.record(a == z && utf8.RuneCountInString(s) == 1 && s != "\n")
|
||||
v.replace(a, z, s)
|
||||
}
|
||||
|
||||
// deleteRange deletes the runes from a to z.
|
||||
func (v *view) deleteRange(a, z int, typing bool) {
|
||||
if a == z || v.opts.ReadOnly {
|
||||
return
|
||||
}
|
||||
v.record(typing)
|
||||
v.replace(min(a, z), max(a, z), "")
|
||||
}
|
||||
|
||||
// joinStep makes the next edit join the step of the edit before it, unless
|
||||
// the action started a step no edit made yet: a composition at a caret
|
||||
// starts one that its commit makes.
|
||||
func (v *view) joinStep() {
|
||||
if v.mode != newStep {
|
||||
v.mode = sameStep
|
||||
}
|
||||
}
|
||||
|
||||
// commitCompose puts the composition into the text, in the typing
|
||||
// attributes, as part of the step its start made.
|
||||
func (v *view) commitCompose() {
|
||||
if v.compose != "" {
|
||||
s := normalizeNewlines(v.compose)
|
||||
v.compose = ""
|
||||
v.joinStep()
|
||||
v.replace(v.caret, v.caret, s)
|
||||
}
|
||||
v.composeCaret, v.composeSelected = 0, ui.TextInputRange{}
|
||||
v.composing = false
|
||||
}
|
||||
|
||||
// special reports whether a paragraph of style st is more than a body
|
||||
// paragraph, which Backspace at its start makes it before joining.
|
||||
func special(st ParagraphStyle) bool {
|
||||
return st.List != NoList || st.Heading > 0 || st.Quote || st.CodeBlock || st.Indent > 0
|
||||
}
|
||||
|
||||
// unstyle takes away what Backspace at the start of a paragraph of style
|
||||
// st takes first: a level of indentation of a list's item, the list, a
|
||||
// heading, a quotation, a block of code.
|
||||
func unstyle(s *ParagraphStyle) {
|
||||
switch {
|
||||
case s.List != NoList && s.Indent > 0:
|
||||
s.Indent--
|
||||
case s.List != NoList:
|
||||
s.List, s.Checked = NoList, false
|
||||
case s.Heading > 0:
|
||||
s.Heading = 0
|
||||
case s.Quote:
|
||||
s.Quote, s.QuoteDepth = false, 0
|
||||
case s.CodeBlock:
|
||||
s.CodeBlock = false
|
||||
case s.Indent > 0:
|
||||
s.Indent--
|
||||
}
|
||||
}
|
||||
|
||||
// enter breaks the paragraph at the selection: a list's item continues the
|
||||
// list and an empty one leaves it, a heading ends at its end, and "```"
|
||||
// starts a block of code.
|
||||
func (v *view) enter() {
|
||||
a, z := v.selection()
|
||||
p := v.shown.paraAt(v.caret)
|
||||
st := v.para(p).style
|
||||
ps := v.shown.paraStart(p)
|
||||
pe := ps + v.para(p).n
|
||||
if a == z && ps == pe {
|
||||
exit := func(s *ParagraphStyle) bool {
|
||||
switch {
|
||||
case s.List != NoList && s.Indent > 0:
|
||||
s.Indent--
|
||||
case s.List != NoList:
|
||||
s.List, s.Checked = NoList, false
|
||||
case s.Quote:
|
||||
s.Quote, s.QuoteDepth = false, 0
|
||||
case s.CodeBlock && p > 0 && v.para(p-1).style.CodeBlock:
|
||||
s.CodeBlock = false
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
probe := st
|
||||
if exit(&probe) {
|
||||
v.command(func(d *Document) { d.FormatParagraphs(func(s *ParagraphStyle) { exit(s) }) })
|
||||
return
|
||||
}
|
||||
}
|
||||
if !v.opts.NoMarkdown && a == z && v.caret == pe && !st.CodeBlock {
|
||||
if line := v.lineOf(p); strings.HasPrefix(line, "```") && !strings.Contains(line[3:], "`") {
|
||||
v.edit(func(e *Edit) {
|
||||
e.ReplaceString(ps, pe, "", Attributes{})
|
||||
e.FormatParagraphs(ps, ps, func(s *ParagraphStyle) { *s = ParagraphStyle{CodeBlock: true, Indent: s.Indent, ID: s.ID} })
|
||||
e.Select(ps, ps)
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
atEnd := v.caret == pe && a == z
|
||||
atStart := a == z && a == ps && ps < pe
|
||||
v.doc.lock()
|
||||
v.lockedPublish()
|
||||
attrs := v.doc.typingAttributes()
|
||||
v.doc.mu.Unlock()
|
||||
v.record(false)
|
||||
v.replace(a, z, "\n")
|
||||
d := v.doc
|
||||
d.lock()
|
||||
v.lockedEdit(func(e *Edit) {
|
||||
// The new paragraph: after the caret's, or before it at its start,
|
||||
// as Notes keeps the item it moves down checked.
|
||||
at := v.caret
|
||||
if atStart {
|
||||
at = v.caret - 1
|
||||
}
|
||||
e.FormatParagraphs(at, at, func(s *ParagraphStyle) {
|
||||
if atEnd && s.Heading > 0 {
|
||||
s.Heading = 0
|
||||
}
|
||||
s.Checked = false
|
||||
})
|
||||
})
|
||||
d.anchor, d.caret = v.caret, v.caret
|
||||
keep := attrs
|
||||
d.typing = &keep
|
||||
d.mu.Unlock()
|
||||
v.coalesce = false
|
||||
}
|
||||
|
||||
// typed runs the Markdown shortcuts after s was typed at the caret.
|
||||
func (v *view) typed(s string) {
|
||||
if v.opts.NoMarkdown || v.opts.ReadOnly || utf8.RuneCountInString(s) != 1 {
|
||||
return
|
||||
}
|
||||
p := v.shown.paraAt(v.caret)
|
||||
ps := v.shown.paraStart(p)
|
||||
if v.para(p).style.CodeBlock {
|
||||
return
|
||||
}
|
||||
before := []rune(v.shown.Slice(ps, v.caret).String())
|
||||
if len(before) == 0 {
|
||||
return
|
||||
}
|
||||
if s == " " {
|
||||
v.blockShortcut(ps, string(before[:len(before)-1]))
|
||||
return
|
||||
}
|
||||
switch s {
|
||||
case "*", "_", "`", "~":
|
||||
v.inlineShortcut(ps, before)
|
||||
}
|
||||
}
|
||||
|
||||
// blockShortcut turns what was typed before a space at the start of a
|
||||
// paragraph into its style: "# " a heading, "- " a list, "> " a quotation.
|
||||
func (v *view) blockShortcut(ps int, prefix string) {
|
||||
var set func(s *ParagraphStyle)
|
||||
switch {
|
||||
case prefix != "" && strings.Trim(prefix, "#") == "" && len(prefix) <= 6:
|
||||
level := len(prefix)
|
||||
set = func(s *ParagraphStyle) { s.Heading, s.List, s.Checked = level, NoList, false }
|
||||
case prefix == "-" || prefix == "*" || prefix == "+":
|
||||
set = func(s *ParagraphStyle) { s.List, s.Heading = Bullets, 0 }
|
||||
case prefix == "[]" || prefix == "[ ]" || prefix == "- [ ]" || prefix == "-[ ]":
|
||||
set = func(s *ParagraphStyle) { s.List, s.Heading, s.Checked = Tasks, 0, false }
|
||||
case prefix == "[x]" || prefix == "- [x]" || prefix == "[X]":
|
||||
set = func(s *ParagraphStyle) { s.List, s.Heading, s.Checked = Tasks, 0, true }
|
||||
case prefix == ">":
|
||||
set = func(s *ParagraphStyle) { s.Quote = true }
|
||||
case len(prefix) >= 2 && (prefix[len(prefix)-1] == '.' || prefix[len(prefix)-1] == ')') && strings.Trim(prefix[:len(prefix)-1], "0123456789") == "":
|
||||
set = func(s *ParagraphStyle) { s.List, s.Heading = Numbers, 0 }
|
||||
}
|
||||
if set == nil {
|
||||
return
|
||||
}
|
||||
n := utf8.RuneCountInString(prefix) + 1
|
||||
v.edit(func(e *Edit) {
|
||||
e.ReplaceString(ps, ps+n, "", Attributes{})
|
||||
e.FormatParagraphs(ps, ps, set)
|
||||
e.Select(ps, ps)
|
||||
})
|
||||
}
|
||||
|
||||
// inlineShortcut formats what a pair of marks typed around words holds:
|
||||
// **bold**, *italic*, _italic_, `code` and ~~strikethrough~~.
|
||||
func (v *view) inlineShortcut(ps int, before []rune) {
|
||||
n := len(before)
|
||||
last := before[n-1]
|
||||
mark := string(last)
|
||||
if (last == '*' || last == '~' || last == '_') && n >= 2 && before[n-2] == last {
|
||||
mark += mark
|
||||
}
|
||||
if last == '~' && len(mark) == 1 {
|
||||
return
|
||||
}
|
||||
m := len([]rune(mark))
|
||||
closeAt := n - m
|
||||
if closeAt <= 0 || unicode.IsSpace(before[closeAt-1]) {
|
||||
return
|
||||
}
|
||||
open := -1
|
||||
for i := closeAt - 1; i >= 0; i-- {
|
||||
if string(before[i:min(i+m, n)]) == mark && i+m < closeAt {
|
||||
// Not the inside of a longer mark, and words right after it.
|
||||
if (i > 0 && before[i-1] == last) || before[i+m] == last || unicode.IsSpace(before[i+m]) {
|
||||
continue
|
||||
}
|
||||
// An underscore inside a word, as snake_case, is no mark.
|
||||
if last == '_' && i > 0 && (unicode.IsLetter(before[i-1]) || unicode.IsDigit(before[i-1])) {
|
||||
continue
|
||||
}
|
||||
open = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if open < 0 {
|
||||
return
|
||||
}
|
||||
set := func(a *Attributes) {
|
||||
switch mark {
|
||||
case "**", "__":
|
||||
a.Weight = 700
|
||||
case "*", "_":
|
||||
a.Italic = true
|
||||
case "`":
|
||||
a.Code = true
|
||||
case "~~":
|
||||
a.Strikethrough = true
|
||||
}
|
||||
}
|
||||
start, end := ps+open, ps+closeAt
|
||||
v.edit(func(e *Edit) {
|
||||
e.ReplaceString(end, end+m, "", Attributes{})
|
||||
e.ReplaceString(start, start+m, "", Attributes{})
|
||||
e.Format(start, end-m, set)
|
||||
e.Select(end-m, end-m)
|
||||
})
|
||||
// What is typed next is outside the format, as after a closing mark.
|
||||
v.doc.lock()
|
||||
plain := Attributes{}
|
||||
if start > ps {
|
||||
plain = v.doc.text.AttributesAt(start - 1).extending()
|
||||
}
|
||||
v.doc.typing = &plain
|
||||
v.doc.mu.Unlock()
|
||||
}
|
||||
|
||||
// looksLikeURL reports whether s is a URL, as ⌘K links one to itself.
|
||||
func looksLikeURL(s string) bool {
|
||||
if strings.ContainsAny(s, " \n\t") {
|
||||
return false
|
||||
}
|
||||
for _, prefix := range []string{"http://", "https://", "mailto:", "www."} {
|
||||
if strings.HasPrefix(s, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// run runs a command of the Format menu or of a shortcut, and reports
|
||||
// whether there is one of that name.
|
||||
func (v *view) run(cmd string) bool {
|
||||
var fn func(d *Document)
|
||||
switch cmd {
|
||||
case "bold":
|
||||
fn = (*Document).ToggleBold
|
||||
case "italic":
|
||||
fn = (*Document).ToggleItalic
|
||||
case "underline":
|
||||
fn = (*Document).ToggleUnderline
|
||||
case "strikethrough":
|
||||
fn = (*Document).ToggleStrikethrough
|
||||
case "code":
|
||||
fn = (*Document).ToggleCode
|
||||
case "bullets":
|
||||
fn = func(d *Document) { d.ToggleList(Bullets) }
|
||||
case "numbers":
|
||||
fn = func(d *Document) { d.ToggleList(Numbers) }
|
||||
case "tasks":
|
||||
fn = func(d *Document) { d.ToggleList(Tasks) }
|
||||
case "indent":
|
||||
fn = func(d *Document) { d.Indent(1) }
|
||||
case "outdent":
|
||||
fn = func(d *Document) { d.Indent(-1) }
|
||||
case "alignLeft":
|
||||
fn = func(d *Document) { d.SetAlign(ui.Start) }
|
||||
case "alignCenter":
|
||||
fn = func(d *Document) { d.SetAlign(ui.Center) }
|
||||
case "alignRight":
|
||||
fn = func(d *Document) { d.SetAlign(ui.End) }
|
||||
case "quote":
|
||||
fn = (*Document).ToggleQuote
|
||||
case "codeBlock":
|
||||
fn = (*Document).ToggleCodeBlock
|
||||
case "link":
|
||||
if v.opts.ReadOnly {
|
||||
return false
|
||||
}
|
||||
if v.opts.OnLinkCommand != nil {
|
||||
v.publish()
|
||||
v.opts.OnLinkCommand()
|
||||
return true
|
||||
}
|
||||
a, z := v.selection()
|
||||
url := strings.TrimSpace(v.shown.Slice(a, z).String())
|
||||
if a == z || !looksLikeURL(url) {
|
||||
return true
|
||||
}
|
||||
fn = func(d *Document) { d.SetLink(url) }
|
||||
default:
|
||||
if level, ok := strings.CutPrefix(cmd, "heading"); ok && len(level) == 1 && level[0] >= '0' && level[0] <= '6' {
|
||||
fn = func(d *Document) { d.SetHeading(int(level[0] - '0')) }
|
||||
}
|
||||
}
|
||||
if fn == nil {
|
||||
return false
|
||||
}
|
||||
if v.opts.ReadOnly {
|
||||
return true
|
||||
}
|
||||
v.command(fn)
|
||||
return true
|
||||
}
|
||||
+1505
File diff suppressed because it is too large.
Load diff
+86
@@ -0,0 +1,86 @@
|
||||
package richtext
|
||||
|
||||
import "math/bits"
|
||||
|
||||
// heights sums the heights of the paragraphs of an editor, measured as
|
||||
// they are laid out and estimated for the others, in two Fenwick trees:
|
||||
// the heights measured, and how many are not, which the estimate
|
||||
// multiplies. The top of a paragraph, and the paragraph at a height, take
|
||||
// O(log n) whatever the estimate, as a text area's do.
|
||||
type heights struct {
|
||||
measured []float64 // 1-based
|
||||
unknown []int32
|
||||
est float64
|
||||
}
|
||||
|
||||
// reset sums the heights hs, 0 for those not measured.
|
||||
func (h *heights) reset(hs []float32) {
|
||||
n := len(hs)
|
||||
if cap(h.measured) > 4*(n+1) {
|
||||
h.measured, h.unknown = nil, nil
|
||||
}
|
||||
h.measured = append(h.measured[:0], make([]float64, n+1)...)
|
||||
h.unknown = append(h.unknown[:0], make([]int32, n+1)...)
|
||||
for i, x := range hs {
|
||||
if x > 0 {
|
||||
h.measured[i+1] = float64(x)
|
||||
} else {
|
||||
h.unknown[i+1] = 1
|
||||
}
|
||||
}
|
||||
for i := 1; i <= n; i++ {
|
||||
if j := i + i&-i; j <= n {
|
||||
h.measured[j] += h.measured[i]
|
||||
h.unknown[j] += h.unknown[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// add changes the height measured of paragraph p by dm, and the count of
|
||||
// those not measured by du.
|
||||
func (h *heights) add(p int, dm float64, du int32) {
|
||||
for i := p + 1; i < len(h.measured); i += i & -i {
|
||||
h.measured[i] += dm
|
||||
h.unknown[i] += du
|
||||
}
|
||||
}
|
||||
|
||||
// top returns the top of paragraph p: the height of those before it.
|
||||
func (h *heights) top(p int) float64 {
|
||||
var m float64
|
||||
var u int32
|
||||
for i := min(p, len(h.measured)-1); i > 0; i -= i & -i {
|
||||
m += h.measured[i]
|
||||
u += h.unknown[i]
|
||||
}
|
||||
return m + float64(u)*h.est
|
||||
}
|
||||
|
||||
// at returns the paragraph at y, the last for y past the end.
|
||||
func (h *heights) at(y float64) int {
|
||||
n := len(h.measured) - 1
|
||||
if n <= 0 {
|
||||
return 0
|
||||
}
|
||||
pos := 0
|
||||
var sum float64
|
||||
for step := 1 << (bits.Len(uint(n)) - 1); step > 0; step >>= 1 {
|
||||
if next := pos + step; next <= n {
|
||||
if s := sum + h.measured[next] + float64(h.unknown[next])*h.est; s <= y {
|
||||
pos, sum = next, s
|
||||
}
|
||||
}
|
||||
}
|
||||
return min(pos, n-1)
|
||||
}
|
||||
|
||||
// totals returns the sum of the heights measured and how many are not.
|
||||
func (h *heights) totals() (float64, int) {
|
||||
var m float64
|
||||
var u int32
|
||||
for i := len(h.measured) - 1; i > 0; i -= i & -i {
|
||||
m += h.measured[i]
|
||||
u += h.unknown[i]
|
||||
}
|
||||
return m, int(u)
|
||||
}
|
||||
Vendored
+635
@@ -0,0 +1,635 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"html"
|
||||
"image"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
xhtml "golang.org/x/net/html"
|
||||
"golang.org/x/net/html/atom"
|
||||
)
|
||||
|
||||
// HTML returns t as HTML: paragraphs, headings, lists (task lists with
|
||||
// check boxes), quotations and blocks of code, and runs in the tags and
|
||||
// styles of their attributes, as browsers, mail and word processors paste
|
||||
// it.
|
||||
func (t Text) HTML() string {
|
||||
var b strings.Builder
|
||||
b.WriteString(`<meta charset="utf-8">`)
|
||||
var paras []Paragraph
|
||||
for _, p := range t.Paragraphs() {
|
||||
paras = append(paras, p)
|
||||
}
|
||||
writeBlocks(&b, paras)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// writeBlocks writes paragraphs as HTML blocks; those of a quotation in a
|
||||
// blockquote, whatever they are.
|
||||
func writeBlocks(b *strings.Builder, paras []Paragraph) {
|
||||
// open is the stack of lists open: their tags.
|
||||
var open []string
|
||||
closeLists := func(depth int) {
|
||||
for len(open) > depth {
|
||||
b.WriteString("</li></" + open[len(open)-1] + ">")
|
||||
open = open[:len(open)-1]
|
||||
}
|
||||
}
|
||||
for i := 0; i < len(paras); i++ {
|
||||
p := paras[i]
|
||||
st := p.Style
|
||||
if st.List == NoList || st.Quote {
|
||||
closeLists(0)
|
||||
}
|
||||
align := ""
|
||||
switch st.Align {
|
||||
case ui.Center:
|
||||
align = ` style="text-align:center"`
|
||||
case ui.End:
|
||||
align = ` style="text-align:right"`
|
||||
}
|
||||
switch {
|
||||
case st.Quote:
|
||||
j := i
|
||||
var quoted []Paragraph
|
||||
for ; j < len(paras) && paras[j].Style.Quote; j++ {
|
||||
q := paras[j]
|
||||
q.Style.QuoteDepth = q.Style.quoteDepth() - 1
|
||||
q.Style.Quote = q.Style.QuoteDepth > 0
|
||||
quoted = append(quoted, q)
|
||||
}
|
||||
b.WriteString("<blockquote>")
|
||||
writeBlocks(b, quoted)
|
||||
b.WriteString("</blockquote>")
|
||||
i = j - 1
|
||||
case st.List != NoList:
|
||||
tag := "ul"
|
||||
if st.List == Numbers {
|
||||
tag = "ol"
|
||||
}
|
||||
depth := st.Indent + 1
|
||||
if len(open) >= depth && open[depth-1] != tag {
|
||||
closeLists(depth - 1)
|
||||
}
|
||||
switch {
|
||||
case len(open) >= depth:
|
||||
closeLists(depth)
|
||||
b.WriteString("</li>")
|
||||
default:
|
||||
for len(open) < depth {
|
||||
b.WriteString("<" + tag + ">")
|
||||
open = append(open, tag)
|
||||
if len(open) < depth {
|
||||
b.WriteString("<li>")
|
||||
}
|
||||
}
|
||||
}
|
||||
b.WriteString("<li" + align + ">")
|
||||
if st.List == Tasks {
|
||||
if st.Checked {
|
||||
b.WriteString(`<input type="checkbox" checked disabled> `)
|
||||
} else {
|
||||
b.WriteString(`<input type="checkbox" disabled> `)
|
||||
}
|
||||
}
|
||||
writeRuns(b, p.Runs)
|
||||
case st.CodeBlock:
|
||||
b.WriteString("<pre><code>")
|
||||
for ; i < len(paras) && paras[i].Style.CodeBlock; i++ {
|
||||
for _, r := range paras[i].Runs {
|
||||
b.WriteString(html.EscapeString(r.Text))
|
||||
}
|
||||
if i+1 < len(paras) && paras[i+1].Style.CodeBlock {
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
}
|
||||
i--
|
||||
b.WriteString("</code></pre>")
|
||||
default:
|
||||
tag := blockTag(st)
|
||||
b.WriteString("<" + tag + align + ">")
|
||||
if len(p.Runs) == 0 {
|
||||
b.WriteString("<br>")
|
||||
}
|
||||
writeRuns(b, p.Runs)
|
||||
b.WriteString("</" + tag + ">")
|
||||
}
|
||||
}
|
||||
closeLists(0)
|
||||
}
|
||||
|
||||
// imageSide returns the width or height an img's attribute gives, or 0.
|
||||
func imageSide(s string) float32 {
|
||||
v, err := strconv.ParseFloat(strings.TrimSuffix(strings.TrimSpace(s), "px"), 32)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return side(float32(v))
|
||||
}
|
||||
|
||||
// side returns v as an attachment's width or height: 0, for its picture's,
|
||||
// unless it is a size, not negative, infinite or not a number.
|
||||
func side(v float32) float32 {
|
||||
if !(v > 0) || v > 1e5 {
|
||||
return 0
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// maxImagePixels is how many pixels a pasted picture may have, so a small
|
||||
// file that claims a huge size takes no gigabytes to decode.
|
||||
const maxImagePixels = 1 << 25
|
||||
|
||||
// smallImage reports whether the picture of data is small enough to decode.
|
||||
func smallImage(data []byte) bool {
|
||||
c, _, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
return err == nil && c.Width > 0 && c.Height > 0 && int64(c.Width)*int64(c.Height) <= maxImagePixels
|
||||
}
|
||||
|
||||
// safeLink returns a link's URL, or "" for one that runs a script where a
|
||||
// browser opens it: javascript:, vbscript: and data:, written as browsers
|
||||
// read them, with spaces before and tabs or newlines within.
|
||||
func safeLink(s string) string {
|
||||
s = strings.TrimFunc(s, func(r rune) bool { return r <= ' ' })
|
||||
scheme := strings.Map(func(r rune) rune {
|
||||
if r == '\t' || r == '\n' || r == '\r' {
|
||||
return -1
|
||||
}
|
||||
return unicode.ToLower(r)
|
||||
}, s)
|
||||
for _, bad := range []string{"javascript:", "vbscript:", "data:"} {
|
||||
if strings.HasPrefix(scheme, bad) {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// blockTag returns the tag of a paragraph of style st: p, or h1 to h6.
|
||||
func blockTag(st ParagraphStyle) string {
|
||||
if st.Heading > 0 {
|
||||
return "h" + strconv.Itoa(min(st.Heading, 6))
|
||||
}
|
||||
return "p"
|
||||
}
|
||||
|
||||
// writeRuns writes runs as HTML: a link around the tags of the formats,
|
||||
// and a span with the styles of fonts and colors.
|
||||
func writeRuns(b *strings.Builder, runs []Run) {
|
||||
for i := 0; i < len(runs); i++ {
|
||||
r := runs[i]
|
||||
a := r.Attributes
|
||||
if link := safeLink(a.Link); link != "" {
|
||||
b.WriteString(`<a href="` + html.EscapeString(link) + `">`)
|
||||
for ; i < len(runs) && runs[i].Attributes.Link == a.Link; i++ {
|
||||
writeRun(b, runs[i])
|
||||
}
|
||||
i--
|
||||
b.WriteString("</a>")
|
||||
continue
|
||||
}
|
||||
writeRun(b, r)
|
||||
}
|
||||
}
|
||||
|
||||
func writeRun(b *strings.Builder, r Run) {
|
||||
a := r.Attributes
|
||||
if at := a.Attachment; at != nil {
|
||||
src := at.URL
|
||||
w, h := at.size()
|
||||
fmt.Fprintf(b, `<img src="%s" alt="%s" width="%d" height="%d">`, html.EscapeString(src), html.EscapeString(at.Name), int(w+0.5), int(h+0.5))
|
||||
return
|
||||
}
|
||||
var style []string
|
||||
if a.Font != "" {
|
||||
style = append(style, "font-family:"+cssFamily(a.Font))
|
||||
}
|
||||
if a.Size > 0 {
|
||||
style = append(style, "font-size:"+strconv.FormatFloat(float64(a.Size), 'g', 4, 32)+"px")
|
||||
}
|
||||
if a.Color.A > 0 {
|
||||
style = append(style, "color:"+cssColor(a.Color))
|
||||
}
|
||||
if a.Background.A > 0 {
|
||||
style = append(style, "background-color:"+cssColor(a.Background))
|
||||
}
|
||||
if a.Weight > 0 && a.Weight != 400 && a.Weight != 700 {
|
||||
style = append(style, "font-weight:"+strconv.Itoa(a.Weight))
|
||||
}
|
||||
var tags []string
|
||||
if a.Weight == 700 {
|
||||
tags = append(tags, "b")
|
||||
}
|
||||
if a.Italic {
|
||||
tags = append(tags, "i")
|
||||
}
|
||||
if a.Underline {
|
||||
tags = append(tags, "u")
|
||||
}
|
||||
if a.Strikethrough {
|
||||
tags = append(tags, "s")
|
||||
}
|
||||
if a.Code {
|
||||
tags = append(tags, "code")
|
||||
}
|
||||
if len(style) > 0 {
|
||||
b.WriteString(`<span style="` + html.EscapeString(strings.Join(style, ";")) + `">`)
|
||||
}
|
||||
for _, t := range tags {
|
||||
b.WriteString("<" + t + ">")
|
||||
}
|
||||
b.WriteString(html.EscapeString(r.Text))
|
||||
for k := len(tags) - 1; k >= 0; k-- {
|
||||
b.WriteString("</" + tags[k] + ">")
|
||||
}
|
||||
if len(style) > 0 {
|
||||
b.WriteString("</span>")
|
||||
}
|
||||
}
|
||||
|
||||
// cssColor returns c as CSS.
|
||||
func cssColor(c ui.Color) string {
|
||||
if c.A == 255 {
|
||||
return fmt.Sprintf("#%02x%02x%02x", c.R, c.G, c.B)
|
||||
}
|
||||
return fmt.Sprintf("rgba(%d,%d,%d,%.3g)", c.R, c.G, c.B, float32(c.A)/255)
|
||||
}
|
||||
|
||||
// cssFamily returns a family as CSS, quoted when it has a space.
|
||||
func cssFamily(f string) string {
|
||||
if strings.ContainsAny(f, " ,") && !strings.ContainsAny(f, `"'`) {
|
||||
return `'` + f + `'`
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// parseCSSColor reads a CSS color: #rgb, #rrggbb, rgb() and rgba().
|
||||
func parseCSSColor(s string) (ui.Color, bool) {
|
||||
s = strings.TrimSpace(strings.ToLower(s))
|
||||
if s == "" || s == "transparent" || s == "inherit" || s == "initial" {
|
||||
return ui.Color{}, false
|
||||
}
|
||||
if strings.HasPrefix(s, "#") {
|
||||
h := s[1:]
|
||||
if len(h) == 3 {
|
||||
h = string([]byte{h[0], h[0], h[1], h[1], h[2], h[2]})
|
||||
}
|
||||
if len(h) != 6 && len(h) != 8 {
|
||||
return ui.Color{}, false
|
||||
}
|
||||
v, err := strconv.ParseUint(h, 16, 32)
|
||||
if err != nil {
|
||||
return ui.Color{}, false
|
||||
}
|
||||
if len(h) == 8 {
|
||||
return ui.Color{R: uint8(v >> 24), G: uint8(v >> 16), B: uint8(v >> 8), A: uint8(v)}, true
|
||||
}
|
||||
return ui.RGB(uint8(v>>16), uint8(v>>8), uint8(v)), true
|
||||
}
|
||||
if inner, ok := strings.CutPrefix(s, "rgba("); ok {
|
||||
s = "rgb(" + inner
|
||||
}
|
||||
if inner, ok := strings.CutPrefix(s, "rgb("); ok {
|
||||
inner = strings.TrimSuffix(inner, ")")
|
||||
parts := strings.FieldsFunc(inner, func(r rune) bool { return r == ',' || r == ' ' || r == '/' })
|
||||
if len(parts) < 3 {
|
||||
return ui.Color{}, false
|
||||
}
|
||||
var c [4]float64
|
||||
c[3] = 1
|
||||
for i, p := range parts[:min(len(parts), 4)] {
|
||||
f, err := strconv.ParseFloat(strings.TrimSuffix(p, "%"), 64)
|
||||
if err != nil {
|
||||
return ui.Color{}, false
|
||||
}
|
||||
if strings.HasSuffix(p, "%") {
|
||||
f = f / 100 * 255
|
||||
if i == 3 {
|
||||
f /= 255
|
||||
}
|
||||
}
|
||||
c[i] = f
|
||||
}
|
||||
if c[3] <= 0 {
|
||||
return ui.Color{}, false
|
||||
}
|
||||
return ui.RGBA(uint8(min(c[0], 255)), uint8(min(c[1], 255)), uint8(min(c[2], 255)), float32(min(c[3], 1))), true
|
||||
}
|
||||
return ui.Color{}, false
|
||||
}
|
||||
|
||||
// htmlBuilder builds a Text from the nodes of an HTML document.
|
||||
type htmlBuilder struct {
|
||||
paras []Paragraph
|
||||
// cur is the paragraph being built, and started whether it has begun.
|
||||
cur Paragraph
|
||||
started bool
|
||||
// space is set after whitespace, which collapses into one space.
|
||||
space bool
|
||||
// lists are the lists open: their kinds.
|
||||
lists []ListKind
|
||||
style ParagraphStyle
|
||||
pre int
|
||||
}
|
||||
|
||||
// ParseHTML returns the attributed text of an HTML document or fragment,
|
||||
// as a paste from a browser, mail or a word processor brings: paragraphs,
|
||||
// headings, lists, task lists, quotations, blocks of code, alignment,
|
||||
// bold, italic, underline, strikethrough, code and links. Fonts, sizes and
|
||||
// colors are left out, as in Notes, so that what is pasted takes the
|
||||
// editor's.
|
||||
func ParseHTML(s string) Text {
|
||||
root, err := xhtml.Parse(strings.NewReader(s))
|
||||
if err != nil {
|
||||
return NewText(s)
|
||||
}
|
||||
b := htmlBuilder{space: true}
|
||||
b.node(root, Attributes{})
|
||||
b.flush()
|
||||
if len(b.paras) == 0 {
|
||||
return Text{}
|
||||
}
|
||||
// Leading and trailing empty paragraphs are the document's margins.
|
||||
paras := b.paras
|
||||
for len(paras) > 1 && len(paras[len(paras)-1].Runs) == 0 {
|
||||
paras = paras[:len(paras)-1]
|
||||
}
|
||||
return TextOf(paras...)
|
||||
}
|
||||
|
||||
// flush ends the paragraph being built.
|
||||
func (b *htmlBuilder) flush() {
|
||||
if !b.started {
|
||||
return
|
||||
}
|
||||
p := b.cur
|
||||
// Trailing whitespace of a paragraph is not shown.
|
||||
if n := len(p.Runs); n > 0 && b.pre == 0 {
|
||||
p.Runs[n-1].Text = strings.TrimRight(p.Runs[n-1].Text, " ")
|
||||
if p.Runs[n-1].Text == "" {
|
||||
p.Runs = p.Runs[:n-1]
|
||||
}
|
||||
}
|
||||
b.paras = append(b.paras, p)
|
||||
b.cur, b.started, b.space = Paragraph{}, false, true
|
||||
}
|
||||
|
||||
// begin starts a paragraph of style, unless one is being built.
|
||||
func (b *htmlBuilder) begin() {
|
||||
if !b.started {
|
||||
b.cur = Paragraph{Style: b.style}
|
||||
b.started = true
|
||||
}
|
||||
}
|
||||
|
||||
// text adds text in attributes a.
|
||||
func (b *htmlBuilder) text(s string, a Attributes) {
|
||||
if b.pre > 0 {
|
||||
for i, line := range strings.Split(s, "\n") {
|
||||
if i > 0 {
|
||||
b.begin()
|
||||
b.flush()
|
||||
}
|
||||
if line != "" {
|
||||
b.begin()
|
||||
b.cur.Runs = append(b.cur.Runs, Run{Text: line, Attributes: a})
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
var out strings.Builder
|
||||
for _, r := range s {
|
||||
if r == ' ' || r == '\n' || r == '\t' || r == '\r' || r == '\f' {
|
||||
if !b.space {
|
||||
out.WriteByte(' ')
|
||||
b.space = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if r == ' ' {
|
||||
r = ' '
|
||||
}
|
||||
out.WriteRune(r)
|
||||
b.space = false
|
||||
}
|
||||
if out.Len() == 0 {
|
||||
return
|
||||
}
|
||||
b.begin()
|
||||
t := out.String()
|
||||
if len(b.cur.Runs) == 0 {
|
||||
t = strings.TrimLeft(t, " ")
|
||||
if t == "" {
|
||||
return
|
||||
}
|
||||
}
|
||||
b.cur.Runs = append(b.cur.Runs, Run{Text: t, Attributes: a})
|
||||
}
|
||||
|
||||
// node adds n and what it holds, in attributes a.
|
||||
func (b *htmlBuilder) node(n *xhtml.Node, a Attributes) {
|
||||
switch n.Type {
|
||||
case xhtml.TextNode:
|
||||
b.text(n.Data, a)
|
||||
return
|
||||
case xhtml.ElementNode:
|
||||
default:
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
b.node(c, a)
|
||||
}
|
||||
return
|
||||
}
|
||||
saved := b.style
|
||||
block := false
|
||||
switch n.DataAtom {
|
||||
case atom.Script, atom.Style, atom.Head, atom.Title, atom.Template, atom.Noscript:
|
||||
return
|
||||
case atom.Br:
|
||||
b.begin()
|
||||
b.flush()
|
||||
return
|
||||
case atom.Img:
|
||||
src, alt := attr(n, "src"), attr(n, "alt")
|
||||
at := &Attachment{Name: alt, URL: src}
|
||||
at.Width, at.Height = imageSide(attr(n, "width")), imageSide(attr(n, "height"))
|
||||
if data, ok := strings.CutPrefix(src, "data:"); ok {
|
||||
if _, enc, ok := strings.Cut(data, ";base64,"); ok {
|
||||
if raw, err := base64.StdEncoding.DecodeString(enc); err == nil && smallImage(raw) {
|
||||
if bm, err := ui.DecodeBitmap(raw); err == nil {
|
||||
at.Image = bm
|
||||
at.URL = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
b.begin()
|
||||
x := a.extending()
|
||||
x.Attachment = at
|
||||
b.cur.Runs = append(b.cur.Runs, Run{Text: string(ObjectReplacement), Attributes: x})
|
||||
b.space = false
|
||||
return
|
||||
case atom.Input:
|
||||
if strings.EqualFold(attr(n, "type"), "checkbox") {
|
||||
b.begin()
|
||||
b.cur.Style.List = Tasks
|
||||
_, checked := hasAttr(n, "checked")
|
||||
b.cur.Style.Checked = checked
|
||||
b.space = true
|
||||
}
|
||||
return
|
||||
case atom.B, atom.Strong:
|
||||
a.Weight = 700
|
||||
case atom.I, atom.Em, atom.Cite, atom.Dfn:
|
||||
a.Italic = true
|
||||
case atom.U, atom.Ins:
|
||||
a.Underline = true
|
||||
case atom.S, atom.Strike, atom.Del:
|
||||
a.Strikethrough = true
|
||||
case atom.Code, atom.Kbd, atom.Samp, atom.Tt:
|
||||
if b.pre == 0 {
|
||||
a.Code = true
|
||||
}
|
||||
case atom.A:
|
||||
a.Link = safeLink(attr(n, "href"))
|
||||
case atom.Ul, atom.Ol:
|
||||
b.flush()
|
||||
kind := Bullets
|
||||
if n.DataAtom == atom.Ol {
|
||||
kind = Numbers
|
||||
}
|
||||
b.lists = append(b.lists, kind)
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
b.node(c, a)
|
||||
}
|
||||
b.lists = b.lists[:len(b.lists)-1]
|
||||
b.flush()
|
||||
b.style = saved
|
||||
return
|
||||
case atom.Li:
|
||||
b.flush()
|
||||
kind := Bullets
|
||||
if k := len(b.lists); k > 0 {
|
||||
kind = b.lists[k-1]
|
||||
}
|
||||
b.style = ParagraphStyle{List: kind, Indent: max(len(b.lists)-1, 0), Align: saved.Align, Quote: saved.Quote, QuoteDepth: saved.QuoteDepth}
|
||||
block = true
|
||||
case atom.P, atom.Div, atom.Section, atom.Article, atom.Header, atom.Footer, atom.Main, atom.Aside, atom.Nav,
|
||||
atom.Figure, atom.Figcaption, atom.Tr, atom.Dt, atom.Dd, atom.Address, atom.Center:
|
||||
b.flush()
|
||||
block = true
|
||||
case atom.H1, atom.H2, atom.H3, atom.H4, atom.H5, atom.H6:
|
||||
b.flush()
|
||||
b.style = ParagraphStyle{Heading: int(n.Data[1] - '0'), Align: saved.Align, Quote: saved.Quote, QuoteDepth: saved.QuoteDepth}
|
||||
block = true
|
||||
case atom.Blockquote:
|
||||
b.flush()
|
||||
if b.style.Quote {
|
||||
b.style.QuoteDepth = b.style.quoteDepth() + 1
|
||||
}
|
||||
b.style.Quote = true
|
||||
block = true
|
||||
case atom.Pre:
|
||||
b.flush()
|
||||
b.style = ParagraphStyle{CodeBlock: true, Indent: saved.Indent, Quote: saved.Quote, QuoteDepth: saved.QuoteDepth}
|
||||
b.pre++
|
||||
defer func() { b.pre-- }()
|
||||
block = true
|
||||
case atom.Td, atom.Th:
|
||||
b.text(" ", a)
|
||||
}
|
||||
if style := attr(n, "style"); style != "" {
|
||||
a = applyCSS(style, a, &b.style, block)
|
||||
}
|
||||
if block {
|
||||
switch strings.ToLower(attr(n, "align")) {
|
||||
case "center":
|
||||
b.style.Align = ui.Center
|
||||
case "right":
|
||||
b.style.Align = ui.End
|
||||
}
|
||||
}
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
b.node(c, a)
|
||||
}
|
||||
if block {
|
||||
if n.DataAtom == atom.P && !b.started && b.pre == 0 {
|
||||
// An empty paragraph shows as one.
|
||||
b.begin()
|
||||
}
|
||||
b.flush()
|
||||
b.style = saved
|
||||
}
|
||||
}
|
||||
|
||||
// applyCSS applies the declarations of a style attribute to a run's
|
||||
// attributes and, for a block, its paragraph's style: weights, italics,
|
||||
// lines and alignment; fonts, sizes and colors are left out.
|
||||
func applyCSS(style string, a Attributes, ps *ParagraphStyle, block bool) Attributes {
|
||||
for _, decl := range strings.Split(style, ";") {
|
||||
name, value, ok := strings.Cut(decl, ":")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
name = strings.TrimSpace(strings.ToLower(name))
|
||||
value = strings.TrimSpace(strings.ToLower(value))
|
||||
value = strings.TrimSuffix(strings.TrimSpace(strings.TrimSuffix(value, "!important")), ";")
|
||||
switch name {
|
||||
case "font-weight":
|
||||
switch value {
|
||||
case "bold", "bolder":
|
||||
a.Weight = 700
|
||||
case "normal", "lighter":
|
||||
a.Weight = 0
|
||||
default:
|
||||
if w, err := strconv.Atoi(value); err == nil {
|
||||
if w >= 600 {
|
||||
a.Weight = 700
|
||||
} else {
|
||||
a.Weight = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
case "font-style":
|
||||
a.Italic = value == "italic" || value == "oblique"
|
||||
case "text-decoration", "text-decoration-line":
|
||||
a.Underline = a.Underline || strings.Contains(value, "underline")
|
||||
a.Strikethrough = a.Strikethrough || strings.Contains(value, "line-through")
|
||||
if value == "none" {
|
||||
a.Underline, a.Strikethrough = false, false
|
||||
}
|
||||
case "text-align":
|
||||
if block {
|
||||
switch value {
|
||||
case "center":
|
||||
ps.Align = ui.Center
|
||||
case "right", "end":
|
||||
ps.Align = ui.End
|
||||
case "left", "start", "justify":
|
||||
ps.Align = ui.Start
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// attr returns the attribute key of n.
|
||||
func attr(n *xhtml.Node, key string) string {
|
||||
v, _ := hasAttr(n, key)
|
||||
return v
|
||||
}
|
||||
|
||||
func hasAttr(n *xhtml.Node, key string) (string, bool) {
|
||||
for _, a := range n.Attr {
|
||||
if strings.EqualFold(a.Key, key) {
|
||||
return a.Val, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
Vendored
+249
@@ -0,0 +1,249 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf16"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/egoist/mygo/internal/rope"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// The editor is the client of the system's input methods: they read the
|
||||
// text around the caret and compose there, in UTF-16 units of the text
|
||||
// with the composition, which is a virtual insertion at the caret until it
|
||||
// is committed, as one step of undo with its start.
|
||||
|
||||
var _ ui.TextInputClient = (*view)(nil)
|
||||
|
||||
// units returns the UTF-16 offset of rune i of the text shown.
|
||||
func (v *view) units(i int) int {
|
||||
return rope.Prefix(v.shown.text, rope.ByteOfRune(v.shown.text, max(0, min(i, v.shown.Len())))).Units
|
||||
}
|
||||
|
||||
// runeOfUnits returns the rune holding UTF-16 unit u, or after it.
|
||||
func (v *view) runeOfUnits(u int) int {
|
||||
return rope.RuneOfUnit(v.shown.text, max(0, u))
|
||||
}
|
||||
|
||||
func countUnits(s string) int {
|
||||
n := 0
|
||||
for _, r := range s {
|
||||
n += utf16.RuneLen(r)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// virtualRune returns the rune of the text with the composition at UTF-16
|
||||
// unit u of it.
|
||||
func (v *view) virtualRune(u int) int {
|
||||
start, n := v.units(v.caret), countUnits(v.compose)
|
||||
if u <= start || v.compose == "" {
|
||||
return v.runeOfUnits(u)
|
||||
}
|
||||
if u <= start+n {
|
||||
return v.caret + utf8.RuneCountInString(v.compose[:ui.UTF16ByteOffset(v.compose, u-start)])
|
||||
}
|
||||
return v.runeOfUnits(u-n) + utf8.RuneCountInString(v.compose)
|
||||
}
|
||||
|
||||
// virtualUnits returns the UTF-16 offset of rune i of the text with the
|
||||
// composition.
|
||||
func (v *view) virtualUnits(i int) int {
|
||||
n := utf8.RuneCountInString(v.compose)
|
||||
if i <= v.caret || n == 0 {
|
||||
return v.units(i)
|
||||
}
|
||||
if i <= v.caret+n {
|
||||
return v.units(v.caret) + countUnits(string([]rune(v.compose)[:i-v.caret]))
|
||||
}
|
||||
return v.units(i-n) + countUnits(v.compose)
|
||||
}
|
||||
|
||||
func (v *view) TextForRange(r ui.TextInputRange) (string, ui.TextInputRange) {
|
||||
v.sync()
|
||||
if r.Start > r.End {
|
||||
r.Start, r.End = r.End, r.Start
|
||||
}
|
||||
a, z := v.virtualRune(r.Start), v.virtualRune(r.End)
|
||||
actual := ui.TextInputRange{Start: v.virtualUnits(a), End: v.virtualUnits(z)}
|
||||
n := utf8.RuneCountInString(v.compose)
|
||||
if n == 0 {
|
||||
return v.shown.Slice(a, z).String(), actual
|
||||
}
|
||||
var out strings.Builder
|
||||
if a < v.caret {
|
||||
out.WriteString(v.shown.Slice(a, min(z, v.caret)).String())
|
||||
}
|
||||
if a < v.caret+n && z > v.caret {
|
||||
cr := []rune(v.compose)
|
||||
out.WriteString(string(cr[max(0, a-v.caret):min(n, z-v.caret)]))
|
||||
}
|
||||
if z > v.caret+n {
|
||||
out.WriteString(v.shown.Slice(max(a-n, v.caret), z-n).String())
|
||||
}
|
||||
return out.String(), actual
|
||||
}
|
||||
|
||||
func (v *view) Selection() ui.TextInputSelection {
|
||||
v.sync()
|
||||
if v.compose != "" {
|
||||
start := v.units(v.caret)
|
||||
return ui.TextInputSelection{Range: ui.TextInputRange{Start: start + v.composeSelected.Start, End: start + v.composeSelected.End}}
|
||||
}
|
||||
a, z := v.selection()
|
||||
return ui.TextInputSelection{Range: ui.TextInputRange{Start: v.units(a), End: v.units(z)}, Reversed: v.caret == a && a != z}
|
||||
}
|
||||
|
||||
func (v *view) MarkedRange() (ui.TextInputRange, bool) {
|
||||
if v.compose == "" {
|
||||
return ui.TextInputRange{}, false
|
||||
}
|
||||
start := v.units(v.caret)
|
||||
return ui.TextInputRange{Start: start, End: start + countUnits(v.compose)}, true
|
||||
}
|
||||
|
||||
func (v *view) ReplaceText(r *ui.TextInputRange, s string) {
|
||||
v.sync()
|
||||
if v.opts.ReadOnly {
|
||||
return
|
||||
}
|
||||
// As typed text goes in.
|
||||
s = normalizeNewlines(s)
|
||||
switch {
|
||||
case r == nil && (v.compose != "" || v.composing):
|
||||
v.compose = ""
|
||||
v.joinStep()
|
||||
v.replace(v.caret, v.caret, s)
|
||||
case r == nil:
|
||||
v.insert(s)
|
||||
v.typed(s)
|
||||
default:
|
||||
a, z := v.virtualRune(r.Start), v.virtualRune(r.End)
|
||||
if a > z {
|
||||
a, z = z, a
|
||||
}
|
||||
transaction := v.composing
|
||||
v.commitCompose()
|
||||
if !transaction {
|
||||
v.record(false)
|
||||
} else {
|
||||
v.joinStep()
|
||||
}
|
||||
v.replace(a, z, s)
|
||||
}
|
||||
v.compose, v.composing = "", false
|
||||
v.composeCaret, v.composeSelected = 0, ui.TextInputRange{}
|
||||
v.reveal = true
|
||||
v.publish()
|
||||
}
|
||||
|
||||
func (v *view) SetMarkedText(r *ui.TextInputRange, s string, selected ui.TextInputRange) {
|
||||
v.sync()
|
||||
if v.opts.ReadOnly {
|
||||
return
|
||||
}
|
||||
if s == "" && r == nil && v.compose == "" && !v.composing {
|
||||
return
|
||||
}
|
||||
if v.compose == "" || r != nil {
|
||||
a, z := v.selection()
|
||||
if r != nil {
|
||||
a, z = v.virtualRune(r.Start), v.virtualRune(r.End)
|
||||
if a > z {
|
||||
a, z = z, a
|
||||
}
|
||||
}
|
||||
transaction := v.composing && v.compose != ""
|
||||
v.commitCompose()
|
||||
if !transaction {
|
||||
v.record(false)
|
||||
} else {
|
||||
v.joinStep()
|
||||
}
|
||||
v.composing = true
|
||||
if a != z {
|
||||
v.replace(a, z, "")
|
||||
}
|
||||
}
|
||||
if selected.Start > selected.End {
|
||||
selected.Start, selected.End = selected.End, selected.Start
|
||||
}
|
||||
n := countUnits(s)
|
||||
selected.Start, selected.End = min(selected.Start, n), min(selected.End, n)
|
||||
selected.Start = countUnits(s[:ui.UTF16ByteOffset(s, selected.Start)])
|
||||
selected.End = countUnits(s[:ui.UTF16ByteOffset(s, selected.End)])
|
||||
v.compose, v.composeSelected = s, selected
|
||||
v.composeCaret = utf8.RuneCountInString(s[:ui.UTF16ByteOffset(s, selected.End)])
|
||||
v.reveal = true
|
||||
v.publish()
|
||||
}
|
||||
|
||||
func (v *view) UnmarkText() {
|
||||
transaction := v.composing
|
||||
v.commitCompose()
|
||||
// GTK and IMM32 can end the composition before committing their
|
||||
// replacement, which shares its step of undo.
|
||||
v.composing = transaction
|
||||
v.publish()
|
||||
}
|
||||
|
||||
func (v *view) BoundsForRange(r ui.TextInputRange) (ui.Rect, ui.TextInputRange, bool) {
|
||||
v.sync()
|
||||
if len(v.paras) == 0 || v.width <= 0 {
|
||||
return ui.Rect{}, ui.TextInputRange{}, false
|
||||
}
|
||||
start, end := v.virtualRune(min(r.Start, r.End)), v.virtualRune(max(r.Start, r.End))
|
||||
aff := ui.TextDownstream
|
||||
if end == start && start == v.caret && v.compose == "" {
|
||||
aff = v.affinity
|
||||
}
|
||||
base, extra := v.virtualCaret(start)
|
||||
x, y, h := v.caretAt(base, extra, aff)
|
||||
b := ui.Rect{X: v.padX + x, Y: v.padY + float32(y-v.scroll), W: 1, H: h}
|
||||
u := v.virtualUnits(start)
|
||||
actual := ui.TextInputRange{Start: u, End: u}
|
||||
if end > start {
|
||||
eb, ee := v.virtualCaret(end)
|
||||
if x2, y2, _ := v.caretAt(eb, ee, ui.TextUpstream); y2 == y {
|
||||
b.W = max(1, x2-x)
|
||||
actual.End = v.virtualUnits(end)
|
||||
}
|
||||
}
|
||||
visible := b.Y+b.H > 0 && b.Y < v.rect.H
|
||||
return b, actual, visible
|
||||
}
|
||||
|
||||
// virtualCaret maps a virtual rune index (including any active composition)
|
||||
// to a document rune and an extra rune offset within the composition.
|
||||
func (v *view) virtualCaret(i int) (int, int) {
|
||||
n := utf8.RuneCountInString(v.compose)
|
||||
switch {
|
||||
case i <= v.caret || n == 0:
|
||||
return i, 0
|
||||
case i <= v.caret+n:
|
||||
return v.caret, i - v.caret
|
||||
default:
|
||||
return i - n, 0
|
||||
}
|
||||
}
|
||||
|
||||
func (v *view) IndexForPoint(p ui.Point) (int, bool) {
|
||||
v.sync()
|
||||
if v.width <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
x, y := v.contentPoint(p.X, p.Y)
|
||||
para, l, _ := v.layoutPositionAt(x, y)
|
||||
n := utf8.RuneCountInString(v.compose)
|
||||
// The rune of the text with the composition: the layout of the
|
||||
// caret's paragraph holds it, those after it are past it.
|
||||
i := v.shown.Len() + n
|
||||
if para >= 0 {
|
||||
i = v.shown.paraStart(para) + l
|
||||
if cp := v.shown.paraAt(v.caret); n > 0 && para > cp {
|
||||
i += n
|
||||
}
|
||||
}
|
||||
return v.virtualUnits(i), true
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
func TestBoundsForRangePlain(t *testing.T) {
|
||||
doc := NewDocument(NewText("hello world"))
|
||||
richTester(t, doc)
|
||||
v := doc.shownIn.Value()
|
||||
|
||||
one, _, ok := v.BoundsForRange(ui.TextInputRange{Start: 0, End: 1})
|
||||
if !ok {
|
||||
t.Fatal("single-rune bounds not visible")
|
||||
}
|
||||
endCaret, _, _ := v.BoundsForRange(ui.TextInputRange{Start: 5, End: 5})
|
||||
multi, actual, ok := v.BoundsForRange(ui.TextInputRange{Start: 0, End: 5})
|
||||
if !ok || actual != (ui.TextInputRange{Start: 0, End: 5}) {
|
||||
t.Fatalf("multi-rune bounds: rect=%+v actual=%+v ok=%v", multi, actual, ok)
|
||||
}
|
||||
if wantW := endCaret.X - one.X; multi.W != wantW || multi.W <= one.W {
|
||||
t.Fatalf("multi-rune rect=%+v, want W=%v (> %v)", multi, wantW, one.W)
|
||||
}
|
||||
rev, revActual, ok := v.BoundsForRange(ui.TextInputRange{Start: 5, End: 0})
|
||||
if !ok || revActual != actual || rev != multi {
|
||||
t.Fatalf("reversed range: rect=%+v actual=%+v, want rect=%+v actual=%+v", rev, revActual, multi, actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBoundsForRangeComposition(t *testing.T) {
|
||||
doc := NewDocument(NewText("ab"))
|
||||
tt, _ := richTester(t, doc)
|
||||
doc.SetSelection(1, 1)
|
||||
tt.Frame()
|
||||
|
||||
v := doc.shownIn.Value()
|
||||
v.SetMarkedText(nil, "nihao", ui.TextInputRange{Start: 5, End: 5})
|
||||
|
||||
// Virtual text is "anihaob"; query subrange "iha" inside the composition.
|
||||
startCaret, _, _ := v.BoundsForRange(ui.TextInputRange{Start: 2, End: 2})
|
||||
endCaret, _, _ := v.BoundsForRange(ui.TextInputRange{Start: 5, End: 5})
|
||||
b, actual, ok := v.BoundsForRange(ui.TextInputRange{Start: 2, End: 5})
|
||||
if !ok || actual != (ui.TextInputRange{Start: 2, End: 5}) {
|
||||
t.Fatalf("composition bounds: rect=%+v actual=%+v ok=%v", b, actual, ok)
|
||||
}
|
||||
if wantW := endCaret.X - startCaret.X; b.X != startCaret.X || b.W != wantW || b.W <= 1 {
|
||||
t.Fatalf("composition rect=%+v, want X=%v W=%v", b, startCaret.X, wantW)
|
||||
}
|
||||
full, fullActual, ok := v.BoundsForRange(ui.TextInputRange{Start: 0, End: 7})
|
||||
if !ok || fullActual != (ui.TextInputRange{Start: 0, End: 7}) || full.W <= b.W {
|
||||
t.Fatalf("full range with composition: rect=%+v actual=%+v ok=%v (innerW=%v)", full, fullActual, ok, b.W)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBoundsForRangeLineBreak(t *testing.T) {
|
||||
doc := NewDocument(NewText("hi\nhello world"))
|
||||
richTester(t, doc)
|
||||
v := doc.shownIn.Value()
|
||||
|
||||
startCaret, _, _ := v.BoundsForRange(ui.TextInputRange{Start: 1, End: 1})
|
||||
cross, actual, ok := v.BoundsForRange(ui.TextInputRange{Start: 1, End: 10})
|
||||
if !ok || actual != (ui.TextInputRange{Start: 1, End: 1}) || cross != startCaret {
|
||||
t.Fatalf("newline cross: rect=%+v actual=%+v ok=%v, want rect=%+v", cross, actual, ok, startCaret)
|
||||
}
|
||||
|
||||
const wrapped = "aa bbbbbb"
|
||||
wrapDoc := NewDocument(NewText(wrapped))
|
||||
tt := ui.NewTester(func(c *ui.Context) {
|
||||
Editor(c, wrapDoc).Width(80).Height(200)
|
||||
}, 100, 220)
|
||||
tt.Press(10, 10)
|
||||
tt.Release(10, 10)
|
||||
wv := wrapDoc.shownIn.Value()
|
||||
|
||||
line0, _, _ := wv.BoundsForRange(ui.TextInputRange{Start: 0, End: 0})
|
||||
wrapAt := -1
|
||||
for i := 1; i <= len(wrapped); i++ {
|
||||
if c, _, _ := wv.BoundsForRange(ui.TextInputRange{Start: i, End: i}); c.Y > line0.Y {
|
||||
wrapAt = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if wrapAt <= 0 {
|
||||
t.Fatal("text did not soft-wrap")
|
||||
}
|
||||
|
||||
firstLine, firstActual, ok := wv.BoundsForRange(ui.TextInputRange{Start: 0, End: wrapAt})
|
||||
if !ok || firstActual != (ui.TextInputRange{Start: 0, End: wrapAt}) || firstLine.Y != line0.Y || firstLine.W <= 1 {
|
||||
t.Fatalf("first wrapped line: rect=%+v actual=%+v ok=%v (line0Y=%v)", firstLine, firstActual, ok, line0.Y)
|
||||
}
|
||||
crossWrap, crossActual, ok := wv.BoundsForRange(ui.TextInputRange{Start: 0, End: len(wrapped)})
|
||||
if !ok || crossActual != (ui.TextInputRange{Start: 0, End: 0}) || crossWrap != line0 {
|
||||
t.Fatalf("cross wrap: rect=%+v actual=%+v ok=%v, want rect=%+v", crossWrap, crossActual, ok, line0)
|
||||
}
|
||||
|
||||
wv.caret = wrapAt
|
||||
wv.affinity = ui.TextUpstream
|
||||
secondLine, secondActual, ok := wv.BoundsForRange(ui.TextInputRange{Start: wrapAt, End: len(wrapped)})
|
||||
if !ok || secondActual != (ui.TextInputRange{Start: wrapAt, End: len(wrapped)}) || secondLine.Y <= line0.Y || secondLine.W <= 1 {
|
||||
t.Fatalf("second wrapped line: rect=%+v actual=%+v ok=%v (line0Y=%v)", secondLine, secondActual, ok, line0.Y)
|
||||
}
|
||||
atWrapCaret, _, _ := wv.BoundsForRange(ui.TextInputRange{Start: wrapAt, End: wrapAt})
|
||||
if atWrapCaret.Y != line0.Y || atWrapCaret.W != 1 {
|
||||
t.Fatalf("collapsed caret at wrap with upstream affinity: rect=%+v, want on line 0 (Y=%v)", atWrapCaret, line0.Y)
|
||||
}
|
||||
}
|
||||
+780
@@ -0,0 +1,780 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
|
||||
"github.com/egoist/mygo/internal/rope"
|
||||
"github.com/egoist/mygo/internal/text"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
const scrollbarWidth = 10
|
||||
|
||||
// input takes the editor's input as it comes: keys, text, edit commands,
|
||||
// the pointer and the wheel.
|
||||
func (v *view) input(ev ui.InputEvent) bool {
|
||||
// The app is asked first, before the editor takes the document's state
|
||||
// and gives its own back: what the app does to the document is kept.
|
||||
if ev.Kind == ui.InputKeyDown && v.opts.OnKey != nil && v.opts.OnKey(ev.Key, ev.Mods) {
|
||||
return true
|
||||
}
|
||||
if ev.Kind == ui.InputCommand && v.opts.OnCommand != nil && v.opts.OnCommand(ev.Text) {
|
||||
return true
|
||||
}
|
||||
v.sync()
|
||||
defer v.publish()
|
||||
switch ev.Kind {
|
||||
case ui.InputKeyDown:
|
||||
if v.key(ev.Key, ev.Mods) {
|
||||
v.blinkStart = ev.Time
|
||||
return true
|
||||
}
|
||||
return false
|
||||
case ui.InputText:
|
||||
if v.opts.ReadOnly || ev.Text == "" {
|
||||
return false
|
||||
}
|
||||
v.compose = ""
|
||||
v.insert(ev.Text)
|
||||
v.typed(ev.Text)
|
||||
v.blinkStart = ev.Time
|
||||
return true
|
||||
case ui.InputCommand:
|
||||
return v.editCommand(ev.Text)
|
||||
case ui.InputPointerDown:
|
||||
return v.press(ev)
|
||||
case ui.InputPointerMove:
|
||||
return v.move(ev)
|
||||
case ui.InputPointerUp:
|
||||
return v.release(ev)
|
||||
case ui.InputSelect:
|
||||
n := v.shown.Len()
|
||||
v.selAnchor, v.caret = max(0, min(ev.Start, n)), max(0, min(ev.End, n))
|
||||
v.affinity = ui.TextDownstream
|
||||
v.reveal = true
|
||||
return true
|
||||
case ui.InputScroll:
|
||||
// At an end, the wheel goes on to the containers around.
|
||||
return v.scrollTo(v.scroll + float64(ev.DY))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// moveTo puts the caret at i, extending the selection or not.
|
||||
func (v *view) moveTo(i int, affinity ui.TextAffinity, extend bool) {
|
||||
i = max(0, min(i, v.shown.Len()))
|
||||
v.caret, v.affinity = i, affinity
|
||||
if !extend {
|
||||
v.selAnchor = i
|
||||
}
|
||||
v.coalesce = false
|
||||
v.reveal = true
|
||||
}
|
||||
|
||||
// runeAt returns rune i of the text shown.
|
||||
func (v *view) runeAt(i int) rune {
|
||||
r, _ := rope.TextOf(v.shown.text).RuneAt(rope.ByteOfRune(v.shown.text, i))
|
||||
return r
|
||||
}
|
||||
|
||||
// nextWord returns the end of the word after i; prevWord the start of the
|
||||
// word before it. Each ideograph and kana is a word, as
|
||||
// text.WordBoundary has it.
|
||||
func (v *view) nextWord(i int) int {
|
||||
n, word, prev := v.shown.Len(), false, rune(0)
|
||||
for ; i < n; i++ {
|
||||
r := v.runeAt(i)
|
||||
if word && text.WordBoundary(prev, r) {
|
||||
break
|
||||
}
|
||||
word, prev = word || text.IsWordRune(r), r
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
func (v *view) prevWord(i int) int {
|
||||
word, next := false, rune(0)
|
||||
for ; i > 0; i-- {
|
||||
r := v.runeAt(i - 1)
|
||||
if word && text.WordBoundary(r, next) {
|
||||
break
|
||||
}
|
||||
word, next = word || text.IsWordRune(r), r
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
// wordAt returns the word, or the run of other runes, around i, within its
|
||||
// paragraph: an ideograph or a kana is a word alone.
|
||||
func (v *view) wordAt(i int) (int, int) {
|
||||
n := v.shown.Len()
|
||||
if n == 0 {
|
||||
return 0, 0
|
||||
}
|
||||
i = max(0, min(i, n-1))
|
||||
at := v.runeAt(i)
|
||||
a, z := i, i
|
||||
for next := at; a > 0; a-- {
|
||||
r := v.runeAt(a - 1)
|
||||
if r == '\n' || text.WordBoundary(r, next) {
|
||||
break
|
||||
}
|
||||
next = r
|
||||
}
|
||||
for prev := at; z < n; z++ {
|
||||
r := v.runeAt(z)
|
||||
if r == '\n' || z > i && text.WordBoundary(prev, r) {
|
||||
break
|
||||
}
|
||||
prev = r
|
||||
}
|
||||
return a, z
|
||||
}
|
||||
|
||||
// grapheme returns the edge of the grapheme before i (dir < 0) or after
|
||||
// it: a newline is one.
|
||||
func (v *view) grapheme(i, dir int) int {
|
||||
n := v.shown.Len()
|
||||
p := v.shown.paraAt(i)
|
||||
ps := v.shown.paraStart(p)
|
||||
pe := ps + v.para(p).n
|
||||
if dir < 0 && i == ps {
|
||||
return max(i-1, 0)
|
||||
}
|
||||
if dir > 0 && i >= pe {
|
||||
return min(i+1, n)
|
||||
}
|
||||
pv := v.paraLayout(p)
|
||||
u := pv.units[min(v.local(p, i), len(pv.units)-1)]
|
||||
if dir < 0 {
|
||||
u = pv.layout.PreviousBoundary(u)
|
||||
} else {
|
||||
u = pv.layout.NextBoundary(u)
|
||||
}
|
||||
return v.global(p, pv.runeOfUnit(u))
|
||||
}
|
||||
|
||||
// visual returns the caret one grapheme left (dir < 0) or right on screen,
|
||||
// across bidi runs, and to the next paragraph at the edge of one. An
|
||||
// offset can have two places, the edge of a span's PaddingX (outside the
|
||||
// span and in it) or a line wrapped within a word (the end of one line and
|
||||
// the start of the next), and a step between them is a move.
|
||||
func (v *view) visual(dir int) (int, ui.TextAffinity) {
|
||||
p := v.shown.paraAt(v.caret)
|
||||
pv := v.paraLayout(p)
|
||||
l := min(v.local(p, v.caret), len(pv.units)-1)
|
||||
pos := ui.TextCaretPosition{Index: pv.units[l], Affinity: v.affinity}
|
||||
next := pv.layout.MoveCaret(pos, dir)
|
||||
if next == pos {
|
||||
if dir < 0 {
|
||||
return max(v.shown.paraStart(p)-1, 0), ui.TextDownstream
|
||||
}
|
||||
return min(v.shown.paraStart(p)+v.para(p).n+1, v.shown.Len()), ui.TextDownstream
|
||||
}
|
||||
return v.global(p, pv.runeOfUnit(next.Index)), next.Affinity
|
||||
}
|
||||
|
||||
// vertical moves the caret up or down lines, keeping its x.
|
||||
func (v *view) vertical(lines int, extend bool) {
|
||||
// A plain move collapses a non-empty selection to its end in the
|
||||
// direction of travel — the start for up, the end for down — before
|
||||
// stepping vertically, matching KeyLeft/KeyRight and ui/editor.
|
||||
if !extend {
|
||||
if a, z := v.selection(); a != z {
|
||||
edge := z
|
||||
if lines < 0 {
|
||||
edge = a
|
||||
}
|
||||
aff := ui.TextDownstream
|
||||
if edge == v.caret {
|
||||
aff = v.affinity
|
||||
}
|
||||
v.moveTo(edge, aff, false)
|
||||
v.hasDesired = false
|
||||
}
|
||||
}
|
||||
x, y, h := v.caretAt(v.caret, 0, v.affinity)
|
||||
if !v.hasDesired {
|
||||
v.desiredX, v.hasDesired = x, true
|
||||
}
|
||||
target := y + float64(h)/2 + float64(lines)*float64(h)
|
||||
switch {
|
||||
case target < 0:
|
||||
v.moveTo(0, ui.TextDownstream, extend)
|
||||
case target > v.hs.top(len(v.paras)):
|
||||
v.moveTo(v.shown.Len(), ui.TextDownstream, extend)
|
||||
default:
|
||||
i, a := v.positionAt(v.desiredX, target)
|
||||
if _, ny, _ := v.caretAt(i, 0, a); ny == y {
|
||||
// Still on the caret's line: the room to the next line
|
||||
// that way, a heading's margin or Space, is over half a
|
||||
// line. Past it, to the last line of the paragraph before
|
||||
// or the first of the one after; at the text's start or
|
||||
// end, there.
|
||||
p := v.shown.paraAt(v.caret)
|
||||
switch {
|
||||
case lines < 0 && p > 0:
|
||||
i, a = v.positionAt(v.desiredX, v.hs.top(p)-1)
|
||||
case lines < 0:
|
||||
i, a = 0, ui.TextDownstream
|
||||
case p+1 < len(v.paras):
|
||||
i, a = v.positionAt(v.desiredX, v.hs.top(p+1)+1)
|
||||
default:
|
||||
i, a = v.shown.Len(), ui.TextDownstream
|
||||
}
|
||||
}
|
||||
v.moveTo(i, a, extend)
|
||||
}
|
||||
v.hasDesired = true
|
||||
}
|
||||
|
||||
// emacsKeys are the Control keys of macOS text views that act as other
|
||||
// keys.
|
||||
var emacsKeys = map[ui.Key]ui.Key{ui.KeyB: ui.KeyLeft, ui.KeyF: ui.KeyRight, ui.KeyP: ui.KeyUp, ui.KeyN: ui.KeyDown, ui.KeyH: ui.KeyBackspace, ui.KeyD: ui.KeyDelete}
|
||||
|
||||
// key handles a key pressed, and reports whether it took it.
|
||||
func (v *view) key(key ui.Key, mods ui.Modifiers) bool {
|
||||
if cmd, ok := shortcut(key, mods); ok {
|
||||
return v.run(cmd)
|
||||
}
|
||||
mac := runtime.GOOS == "darwin"
|
||||
shift := mods&ui.Shift != 0
|
||||
m := mods &^ ui.Shift
|
||||
if mac && m == ui.Ctrl {
|
||||
if to, ok := emacsKeys[key]; ok {
|
||||
key, m = to, 0
|
||||
} else {
|
||||
p := v.shown.paraAt(v.caret)
|
||||
ps := v.shown.paraStart(p)
|
||||
pe := ps + v.para(p).n
|
||||
switch key {
|
||||
case ui.KeyA:
|
||||
v.moveTo(ps, ui.TextDownstream, shift)
|
||||
return true
|
||||
case ui.KeyE:
|
||||
v.moveTo(pe, ui.TextDownstream, shift)
|
||||
return true
|
||||
case ui.KeyK:
|
||||
if v.opts.ReadOnly {
|
||||
return true
|
||||
}
|
||||
if pe == v.caret && pe < v.shown.Len() {
|
||||
pe++
|
||||
}
|
||||
v.deleteRange(v.caret, pe, false)
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
word := (!mac && m == ui.Ctrl) || (mac && m == ui.Alt)
|
||||
readOnly := v.opts.ReadOnly
|
||||
if key == ui.KeyV && shift && (m == ui.Cmd || m == ui.Cmd|ui.Alt) {
|
||||
// Paste and Match Style: ⇧⌥⌘V, and ⇧⌘V as Notes has it.
|
||||
return v.editCommand("pasteAndMatchStyle")
|
||||
}
|
||||
a, z := v.selection()
|
||||
n := v.shown.Len()
|
||||
switch key {
|
||||
case ui.KeyLeft, ui.KeyRight:
|
||||
left := key == ui.KeyLeft
|
||||
switch {
|
||||
case m == ui.Alt && !mac:
|
||||
return false // back and forward
|
||||
case mac && m == ui.Super:
|
||||
s, e := v.lineEdges(v.caret)
|
||||
if left {
|
||||
v.moveTo(s, ui.TextDownstream, shift)
|
||||
} else {
|
||||
v.moveTo(e, ui.TextUpstream, shift)
|
||||
}
|
||||
case word && left:
|
||||
v.moveTo(v.prevWord(v.caret), ui.TextDownstream, shift)
|
||||
case word:
|
||||
v.moveTo(v.nextWord(v.caret), ui.TextDownstream, shift)
|
||||
case a != z && !shift && left:
|
||||
v.moveTo(a, ui.TextDownstream, false)
|
||||
case a != z && !shift:
|
||||
v.moveTo(z, ui.TextDownstream, false)
|
||||
case left:
|
||||
i, aff := v.visual(-1)
|
||||
v.moveTo(i, aff, shift)
|
||||
default:
|
||||
i, aff := v.visual(1)
|
||||
v.moveTo(i, aff, shift)
|
||||
}
|
||||
v.hasDesired = false
|
||||
return true
|
||||
case ui.KeyUp, ui.KeyDown:
|
||||
if mac && m == ui.Super {
|
||||
if key == ui.KeyUp {
|
||||
v.moveTo(0, ui.TextDownstream, shift)
|
||||
} else {
|
||||
v.moveTo(n, ui.TextDownstream, shift)
|
||||
}
|
||||
return true
|
||||
}
|
||||
if mac && m == ui.Alt || !mac && m == ui.Ctrl {
|
||||
// By paragraphs: up to the start of this one or the one
|
||||
// before; down to the end of this one or the next on macOS,
|
||||
// as NSTextView, to the start of the next elsewhere, as
|
||||
// WordPad and GTK.
|
||||
a, z := v.shown.ParagraphRange(v.caret)
|
||||
switch {
|
||||
case key == ui.KeyUp && v.caret == a && a > 0:
|
||||
a, _ = v.shown.ParagraphRange(a - 1)
|
||||
v.moveTo(a, ui.TextDownstream, shift)
|
||||
case key == ui.KeyUp:
|
||||
v.moveTo(a, ui.TextDownstream, shift)
|
||||
case mac && v.caret == z && z < n:
|
||||
_, z = v.shown.ParagraphRange(z + 1)
|
||||
v.moveTo(z, ui.TextUpstream, shift)
|
||||
case mac:
|
||||
v.moveTo(z, ui.TextUpstream, shift)
|
||||
default:
|
||||
v.moveTo(min(z+1, n), ui.TextDownstream, shift)
|
||||
}
|
||||
v.hasDesired = false
|
||||
return true
|
||||
}
|
||||
if m != 0 {
|
||||
return false
|
||||
}
|
||||
d := 1
|
||||
if key == ui.KeyUp {
|
||||
d = -1
|
||||
}
|
||||
v.vertical(d, shift)
|
||||
return true
|
||||
case ui.KeyPageUp, ui.KeyPageDown:
|
||||
lines := max(int(v.viewH/(v.look.size*1.3))-1, 1)
|
||||
if key == ui.KeyPageUp {
|
||||
lines = -lines
|
||||
}
|
||||
v.vertical(lines, shift)
|
||||
return true
|
||||
case ui.KeyHome, ui.KeyEnd:
|
||||
if m == ui.Ctrl {
|
||||
if key == ui.KeyHome {
|
||||
v.moveTo(0, ui.TextDownstream, shift)
|
||||
} else {
|
||||
v.moveTo(n, ui.TextDownstream, shift)
|
||||
}
|
||||
return true
|
||||
}
|
||||
s, e := v.lineEdges(v.caret)
|
||||
if key == ui.KeyHome {
|
||||
v.moveTo(s, ui.TextDownstream, shift)
|
||||
} else {
|
||||
v.moveTo(e, ui.TextUpstream, shift)
|
||||
}
|
||||
return true
|
||||
case ui.KeyA:
|
||||
if m == ui.Cmd {
|
||||
v.selAnchor, v.caret = 0, n
|
||||
return true
|
||||
}
|
||||
case ui.KeyC, ui.KeyX, ui.KeyV, ui.KeyZ, ui.KeyY:
|
||||
if m != ui.Cmd {
|
||||
break
|
||||
}
|
||||
switch key {
|
||||
case ui.KeyC:
|
||||
return v.editCommand("copy")
|
||||
case ui.KeyX:
|
||||
return v.editCommand("cut")
|
||||
case ui.KeyV:
|
||||
return v.editCommand("paste")
|
||||
case ui.KeyZ:
|
||||
if shift {
|
||||
return v.editCommand("redo")
|
||||
}
|
||||
return v.editCommand("undo")
|
||||
case ui.KeyY:
|
||||
return v.editCommand("redo")
|
||||
}
|
||||
}
|
||||
if readOnly {
|
||||
return false
|
||||
}
|
||||
p := v.shown.paraAt(v.caret)
|
||||
st := v.para(p).style
|
||||
ps := v.shown.paraStart(p)
|
||||
switch key {
|
||||
case ui.KeyBackspace:
|
||||
switch {
|
||||
case a != z:
|
||||
v.deleteRange(a, z, false)
|
||||
case m == 0 && v.caret == ps && special(st):
|
||||
// At the start of a list's item, a heading, a quotation or a
|
||||
// block of code, Backspace takes the style away before joining.
|
||||
v.command(func(d *Document) { d.FormatParagraphs(unstyle) })
|
||||
case mac && m == ui.Super:
|
||||
s, _ := v.lineEdges(v.caret)
|
||||
v.deleteRange(s, v.caret, false)
|
||||
case word:
|
||||
v.deleteRange(v.prevWord(v.caret), v.caret, false)
|
||||
case v.caret > ps && text.IsCombiningMark(v.runeAt(v.caret-1)):
|
||||
v.deleteRange(v.caret-1, v.caret, true)
|
||||
case v.caret > 0:
|
||||
v.deleteRange(v.grapheme(v.caret, -1), v.caret, true)
|
||||
}
|
||||
return true
|
||||
case ui.KeyDelete:
|
||||
switch {
|
||||
case a != z:
|
||||
v.deleteRange(a, z, false)
|
||||
case word:
|
||||
v.deleteRange(v.caret, v.nextWord(v.caret), false)
|
||||
case v.caret < n:
|
||||
v.deleteRange(v.caret, v.grapheme(v.caret, 1), false)
|
||||
}
|
||||
return true
|
||||
case ui.KeyEnter:
|
||||
if m != 0 {
|
||||
return false
|
||||
}
|
||||
v.enter()
|
||||
return true
|
||||
case ui.KeyTab:
|
||||
switch {
|
||||
case m != 0:
|
||||
return false
|
||||
case st.List != NoList:
|
||||
if shift {
|
||||
return v.run("outdent")
|
||||
}
|
||||
return v.run("indent")
|
||||
case st.CodeBlock && !shift:
|
||||
v.insert("\t")
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// shortcut returns the command a key with mods runs: ⌘B, ⌘I, ⌘U, ⇧⌘X, ⌘E,
|
||||
// ⌘K, ⇧⌘7, ⇧⌘8, ⇧⌘L, ⌘], ⌘[, ⌘{, ⌘|, ⌘} and ⌥⌘0–6 on macOS, as Pages,
|
||||
// Notes and Google Docs have them, with Control in place of Command
|
||||
// elsewhere, where Ctrl+L, Ctrl+E, Ctrl+R align, as in Word.
|
||||
func shortcut(key ui.Key, mods ui.Modifiers) (string, bool) {
|
||||
mac := runtime.GOOS == "darwin"
|
||||
switch mods {
|
||||
case ui.Cmd:
|
||||
switch key {
|
||||
case ui.KeyB:
|
||||
return "bold", true
|
||||
case ui.KeyI:
|
||||
return "italic", true
|
||||
case ui.KeyU:
|
||||
return "underline", true
|
||||
case ui.KeyK:
|
||||
return "link", true
|
||||
case ui.KeyBracketRight:
|
||||
return "indent", true
|
||||
case ui.KeyBracketLeft:
|
||||
return "outdent", true
|
||||
case ui.KeyE:
|
||||
if mac {
|
||||
return "code", true
|
||||
}
|
||||
return "alignCenter", true
|
||||
case ui.KeyL:
|
||||
if !mac {
|
||||
return "alignLeft", true
|
||||
}
|
||||
case ui.KeyR:
|
||||
if !mac {
|
||||
return "alignRight", true
|
||||
}
|
||||
}
|
||||
case ui.Cmd | ui.Shift:
|
||||
switch key {
|
||||
case ui.KeyX:
|
||||
return "strikethrough", true
|
||||
case ui.Key7:
|
||||
return "numbers", true
|
||||
case ui.Key8:
|
||||
return "bullets", true
|
||||
case ui.KeyL:
|
||||
return "tasks", true
|
||||
case ui.KeyBracketLeft:
|
||||
if mac {
|
||||
return "alignLeft", true
|
||||
}
|
||||
case ui.KeyBracketRight:
|
||||
if mac {
|
||||
return "alignRight", true
|
||||
}
|
||||
case ui.KeyBackslash:
|
||||
if mac {
|
||||
return "alignCenter", true
|
||||
}
|
||||
case ui.KeyE:
|
||||
if !mac {
|
||||
return "code", true
|
||||
}
|
||||
}
|
||||
case ui.Cmd | ui.Alt:
|
||||
if key >= ui.Key0 && key <= ui.Key6 {
|
||||
return "heading" + string(rune('0'+int(key-ui.Key0))), true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// editCommand performs an edit command of a menu or a shortcut.
|
||||
func (v *view) editCommand(name string) bool {
|
||||
a, z := v.selection()
|
||||
switch name {
|
||||
case "copy":
|
||||
if a != z {
|
||||
v.copySelection()
|
||||
}
|
||||
return true
|
||||
case "cut":
|
||||
if a != z && !v.opts.ReadOnly {
|
||||
v.copySelection()
|
||||
v.deleteRange(a, z, false)
|
||||
}
|
||||
return true
|
||||
case "paste", "pasteAndMatchStyle":
|
||||
if !v.opts.ReadOnly {
|
||||
v.paste(name == "pasteAndMatchStyle")
|
||||
}
|
||||
return true
|
||||
case "selectAll":
|
||||
v.selAnchor, v.caret = 0, v.shown.Len()
|
||||
return true
|
||||
case "delete":
|
||||
if a != z && !v.opts.ReadOnly {
|
||||
v.deleteRange(a, z, false)
|
||||
}
|
||||
return true
|
||||
case "undo", "redo":
|
||||
if !v.opts.ReadOnly {
|
||||
v.commitCompose()
|
||||
v.takeBack(name == "redo")
|
||||
}
|
||||
return true
|
||||
}
|
||||
return v.run(name)
|
||||
}
|
||||
|
||||
// press handles a press of the pointer.
|
||||
func (v *view) press(ev ui.InputEvent) bool {
|
||||
if ev.Button == 1 && !v.overScrollbar(ev.X) {
|
||||
// A right-click outside the selection puts the caret where it
|
||||
// is, as in a TextArea, so that the context menu acts there; the
|
||||
// press goes on to open the menu.
|
||||
x, y := v.contentPoint(ev.X, ev.Y)
|
||||
i, aff := v.positionAt(x, y)
|
||||
if a, b := min(v.selAnchor, v.caret), max(v.selAnchor, v.caret); a == b || i < a || i > b {
|
||||
v.commitCompose()
|
||||
v.hasDesired = false
|
||||
v.moveTo(i, aff, false)
|
||||
}
|
||||
return false
|
||||
}
|
||||
if ev.Button != 0 {
|
||||
return false
|
||||
}
|
||||
v.pressMods = ev.Mods
|
||||
v.pressLink = ""
|
||||
if v.overScrollbar(ev.X) {
|
||||
v.thumb = true
|
||||
top, size := v.thumbBox()
|
||||
if ev.Y >= top && ev.Y < top+size {
|
||||
v.thumbGrab = ev.Y - top
|
||||
} else {
|
||||
v.thumbGrab = size / 2
|
||||
v.dragThumb(ev.Y)
|
||||
}
|
||||
return true
|
||||
}
|
||||
v.commitCompose()
|
||||
x, y := v.contentPoint(ev.X, ev.Y)
|
||||
if p, ok := v.taskBox(x, y); ok && ev.Clicks == 1 && !v.opts.ReadOnly {
|
||||
start := v.shown.paraStart(p)
|
||||
v.command(func(d *Document) { d.ToggleChecked(start) })
|
||||
return true
|
||||
}
|
||||
i, aff := v.positionAt(x, y)
|
||||
v.pressPoint = ui.Point{X: ev.X, Y: ev.Y}
|
||||
if ev.Clicks == 1 && ev.Mods&ui.Shift == 0 {
|
||||
v.pressLink = v.linkAt(x, y)
|
||||
}
|
||||
v.dragging = true
|
||||
v.hasDesired = false
|
||||
v.dragUnit = min(max(ev.Clicks, 1), 3)
|
||||
switch v.dragUnit {
|
||||
case 1:
|
||||
v.moveTo(i, aff, ev.Mods&ui.Shift != 0)
|
||||
case 2:
|
||||
v.selAnchor, v.caret = v.wordAt(i)
|
||||
default:
|
||||
a, z := v.shown.ParagraphRange(i)
|
||||
v.selAnchor, v.caret = a, min(z+1, v.shown.Len())
|
||||
}
|
||||
v.dragStart = [2]int{v.selAnchor, v.caret}
|
||||
v.coalesce = false
|
||||
return true
|
||||
}
|
||||
|
||||
// move handles the pointer moving: a drag extends the selection.
|
||||
func (v *view) move(ev ui.InputEvent) bool {
|
||||
if v.thumb {
|
||||
v.dragThumb(ev.Y)
|
||||
return true
|
||||
}
|
||||
x, y := v.contentPoint(ev.X, ev.Y)
|
||||
if !v.dragging {
|
||||
cursor := ui.CursorText
|
||||
if _, box := v.taskBox(x, y); box || v.overScrollbar(ev.X) {
|
||||
cursor = ui.CursorDefault
|
||||
} else if v.linkAt(x, y) != "" {
|
||||
cursor = ui.CursorPointer
|
||||
}
|
||||
if cursor != v.cursor {
|
||||
v.cursor = cursor
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
// Near the edges, a drag scrolls.
|
||||
if ev.Y < v.padY {
|
||||
v.setScroll(max(0, v.scroll-float64(v.padY-ev.Y)))
|
||||
} else if ev.Y > v.padY+v.viewH {
|
||||
v.setScroll(v.scroll + float64(ev.Y-v.padY-v.viewH))
|
||||
}
|
||||
i, aff := v.positionAt(x, y)
|
||||
switch v.dragUnit {
|
||||
case 2:
|
||||
s, e := v.wordAt(i)
|
||||
if i < v.dragStart[0] {
|
||||
v.selAnchor, v.caret = v.dragStart[1], s
|
||||
} else {
|
||||
v.selAnchor, v.caret = v.dragStart[0], max(e, v.dragStart[1])
|
||||
}
|
||||
case 3:
|
||||
a, z := v.shown.ParagraphRange(i)
|
||||
if i < v.dragStart[0] {
|
||||
v.selAnchor, v.caret = v.dragStart[1], a
|
||||
} else {
|
||||
v.selAnchor, v.caret = v.dragStart[0], min(z+1, v.shown.Len())
|
||||
}
|
||||
default:
|
||||
v.caret, v.affinity = i, aff
|
||||
}
|
||||
dx, dy := ev.X-v.pressPoint.X, ev.Y-v.pressPoint.Y
|
||||
if i != v.dragStart[0] || v.dragUnit != 1 || dx*dx+dy*dy >= 16 {
|
||||
v.pressLink = ""
|
||||
}
|
||||
v.reveal = true
|
||||
return true
|
||||
}
|
||||
|
||||
// release ends a drag, and opens the link a click began on.
|
||||
func (v *view) release(ev ui.InputEvent) bool {
|
||||
if v.thumb {
|
||||
v.thumb = false
|
||||
return true
|
||||
}
|
||||
if !v.dragging {
|
||||
return false
|
||||
}
|
||||
v.dragging = false
|
||||
link := v.pressLink
|
||||
v.pressLink = ""
|
||||
// A press the system took opens no link.
|
||||
x, y := v.contentPoint(ev.X, ev.Y)
|
||||
dx, dy := ev.X-v.pressPoint.X, ev.Y-v.pressPoint.Y
|
||||
if link != "" && v.caret == v.selAnchor && !ev.Canceled && dx*dx+dy*dy < 16 && v.linkAt(x, y) == link {
|
||||
if v.opts.OnLink != nil {
|
||||
v.opts.OnLink(link)
|
||||
} else if ui.SafeToOpen(link) {
|
||||
v.services.OpenURL(link)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Attachments occupy one rune, but either half of their drawn box opens
|
||||
// the link. Keep nearest-caret hit testing for selection alone.
|
||||
func (v *view) linkAt(x float32, y float64) string {
|
||||
p, l, _ := v.layoutPositionAt(x, y)
|
||||
if p < 0 {
|
||||
return ""
|
||||
}
|
||||
pv := v.paraLayout(p)
|
||||
ox, oy := v.origin(p)
|
||||
for _, object := range pv.layout.Objects() {
|
||||
if object.Rect.Contains(x-ox, float32(y-oy)) {
|
||||
at := pv.runeOfUnit(object.Index)
|
||||
start := v.caret - v.shown.paraStart(p)
|
||||
if v.compose != "" && v.shown.paraAt(v.caret) == p && at >= start && at < start+len([]rune(v.compose)) {
|
||||
return ""
|
||||
}
|
||||
return v.shown.AttributesAt(v.global(p, at)).Link
|
||||
}
|
||||
}
|
||||
i := v.global(p, l)
|
||||
if i < v.shown.Len() {
|
||||
a := v.shown.AttributesAt(i)
|
||||
if a.Attachment == nil {
|
||||
return a.Link
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// taskBox reports whether (x, y), in the content, is on the check box of
|
||||
// a task, and which paragraph's.
|
||||
func (v *view) taskBox(x float32, y float64) (int, bool) {
|
||||
if len(v.paras) == 0 {
|
||||
return 0, false
|
||||
}
|
||||
p := v.hs.at(y)
|
||||
st := v.para(p).style
|
||||
if st.List != Tasks {
|
||||
return 0, false
|
||||
}
|
||||
left, _ := v.insets(st)
|
||||
if x < left-v.look.indent || x >= left-2 {
|
||||
return p, false
|
||||
}
|
||||
// Beside the first line, where the box is.
|
||||
_, top, h := v.caretAt(v.shown.paraStart(p), 0, ui.TextDownstream)
|
||||
return p, y >= top && y < top+float64(h)
|
||||
}
|
||||
|
||||
// overScrollbar reports whether x of the element is on the scroll bar.
|
||||
func (v *view) overScrollbar(x float32) bool {
|
||||
if v.opts.NoScrollbar {
|
||||
return false
|
||||
}
|
||||
width := v.barStyle.TrackWidth
|
||||
if width <= 0 {
|
||||
width = scrollbarWidth
|
||||
}
|
||||
return v.hs.top(len(v.paras)) > float64(v.viewH) && x >= v.rect.W-width
|
||||
}
|
||||
|
||||
// bar returns the scroll bar, in the element.
|
||||
func (v *view) bar() ui.Scrollbar {
|
||||
return ui.Scrollbar{Box: ui.Rect{W: v.rect.W, H: v.rect.H}, View: v.viewH, Content: float32(v.hs.top(len(v.paras))), Offset: float32(v.scroll), Style: v.barStyle}
|
||||
}
|
||||
|
||||
// thumbBox returns the top and the height of the scroll bar's thumb, in
|
||||
// the element.
|
||||
func (v *view) thumbBox() (top, size float32) { return v.bar().Thumb() }
|
||||
|
||||
// dragThumb scrolls as the thumb is dragged to y.
|
||||
func (v *view) dragThumb(y float32) {
|
||||
v.setScroll(float64(v.bar().OffsetAt(y - v.thumbGrab)))
|
||||
}
|
||||
|
||||
// menu builds the editor's context menu.
|
||||
func (v *view) menu(m *ui.Menu) {
|
||||
m.EditItems()
|
||||
}
|
||||
+496
@@ -0,0 +1,496 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Markdown returns t as CommonMark with GitHub's extensions: headings,
|
||||
// lists and task lists, quotations, fenced blocks of code, **bold**,
|
||||
// *italic*, ~~strikethrough~~, `code`, links and images; underlines are
|
||||
// HTML's <u>, which Markdown keeps. Body paragraphs are apart by a blank
|
||||
// line, so that they stay paragraphs; alignment, fonts and colors have no
|
||||
// Markdown and are left out.
|
||||
func (t Text) Markdown() string {
|
||||
var b strings.Builder
|
||||
var paras []Paragraph
|
||||
for _, p := range t.Paragraphs() {
|
||||
paras = append(paras, p)
|
||||
}
|
||||
// numbers counts the items of the numbered lists open, by level.
|
||||
var numbers []int
|
||||
prevList := false
|
||||
for i := 0; i < len(paras); i++ {
|
||||
p := paras[i]
|
||||
st := p.Style
|
||||
if i > 0 && !(st.List != NoList && prevList) {
|
||||
b.WriteString("\n\n")
|
||||
} else if i > 0 {
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
prevList = st.List != NoList
|
||||
if st.List == NoList {
|
||||
numbers = numbers[:0]
|
||||
}
|
||||
quote := ""
|
||||
if st.Quote {
|
||||
quote = strings.Repeat("> ", st.quoteDepth())
|
||||
}
|
||||
switch {
|
||||
case st.CodeBlock:
|
||||
fence := "```"
|
||||
for k := i; k < len(paras) && paras[k].Style.CodeBlock; k++ {
|
||||
for strings.Contains(plainOf(paras[k]), fence) {
|
||||
fence += "`"
|
||||
}
|
||||
}
|
||||
b.WriteString(quote + fence + "\n")
|
||||
for ; i < len(paras) && paras[i].Style.CodeBlock; i++ {
|
||||
b.WriteString(quote + plainOf(paras[i]) + "\n")
|
||||
}
|
||||
i--
|
||||
b.WriteString(quote + fence)
|
||||
continue
|
||||
case st.Heading > 0:
|
||||
b.WriteString(quote + strings.Repeat("#", min(st.Heading, 6)) + " ")
|
||||
case st.List != NoList:
|
||||
level := st.Indent
|
||||
for len(numbers) <= level {
|
||||
numbers = append(numbers, 0)
|
||||
}
|
||||
numbers = numbers[:level+1]
|
||||
b.WriteString(quote + strings.Repeat(" ", level))
|
||||
switch st.List {
|
||||
case Numbers:
|
||||
numbers[level]++
|
||||
b.WriteString(strconv.Itoa(numbers[level]) + ". ")
|
||||
case Tasks:
|
||||
if st.Checked {
|
||||
b.WriteString("- [x] ")
|
||||
} else {
|
||||
b.WriteString("- [ ] ")
|
||||
}
|
||||
numbers[level] = 0
|
||||
default:
|
||||
b.WriteString("- ")
|
||||
numbers[level] = 0
|
||||
}
|
||||
default:
|
||||
b.WriteString(quote)
|
||||
}
|
||||
if st.Heading > 0 {
|
||||
// A heading's closing #s are not its text: escape them.
|
||||
var h strings.Builder
|
||||
writeMarkdownRuns(&h, p.Runs)
|
||||
s := h.String()
|
||||
if k := len(strings.TrimRight(s, "#")); k < len(s) {
|
||||
s = s[:k] + "\\" + s[k:]
|
||||
}
|
||||
b.WriteString(s)
|
||||
continue
|
||||
}
|
||||
writeMarkdownRuns(&b, p.Runs)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// plainOf returns the text of a paragraph.
|
||||
func plainOf(p Paragraph) string {
|
||||
var b strings.Builder
|
||||
for _, r := range p.Runs {
|
||||
b.WriteString(r.Text)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// mark is a Markdown mark around runs: a link (by its URL), bold, italic,
|
||||
// strikethrough or underline, from the outside in. Code is a span of each
|
||||
// run, fenced as its backticks need.
|
||||
type mark struct {
|
||||
kind byte // 'a', 'b', 'i', 's', 'u'
|
||||
url string
|
||||
}
|
||||
|
||||
func marksOf(a Attributes) []mark {
|
||||
var m []mark
|
||||
if a.Link != "" {
|
||||
m = append(m, mark{kind: 'a', url: a.Link})
|
||||
}
|
||||
if a.Bold() {
|
||||
m = append(m, mark{kind: 'b'})
|
||||
}
|
||||
if a.Italic {
|
||||
m = append(m, mark{kind: 'i'})
|
||||
}
|
||||
if a.Strikethrough {
|
||||
m = append(m, mark{kind: 's'})
|
||||
}
|
||||
if a.Underline {
|
||||
m = append(m, mark{kind: 'u'})
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// open returns the mark's opening, as HTML when html: what Markdown
|
||||
// cannot open or close where it is, as bold "foo." before "bar".
|
||||
func (m mark) open(html bool) string {
|
||||
switch m.kind {
|
||||
case 'a':
|
||||
return "["
|
||||
case 'b':
|
||||
if html {
|
||||
return "<strong>"
|
||||
}
|
||||
return "**"
|
||||
case 'i':
|
||||
if html {
|
||||
return "<em>"
|
||||
}
|
||||
return "*"
|
||||
case 's':
|
||||
if html {
|
||||
return "<del>"
|
||||
}
|
||||
return "~~"
|
||||
case 'u':
|
||||
return "<u>"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m mark) close(html bool) string {
|
||||
switch m.kind {
|
||||
case 'a':
|
||||
return "](" + markdownURL(m.url) + ")"
|
||||
case 'u':
|
||||
return "</u>"
|
||||
}
|
||||
if html {
|
||||
return "</" + m.open(true)[1:]
|
||||
}
|
||||
return m.open(false)
|
||||
}
|
||||
|
||||
// writeMarkdownRuns writes runs with their marks, opening and closing
|
||||
// them as they change, whitespace outside them so that they flank words
|
||||
// as CommonMark wants. Where a delimiter cannot open or close (bold
|
||||
// "foo." right before "bar" is not **foo.**bar), its mark is written as
|
||||
// HTML, which Markdown keeps: the runs written are read back to check,
|
||||
// and those still read otherwise are written in HTML whole. What would
|
||||
// start a block at the start of the paragraph is escaped, as the text
|
||||
// of an item or a heading too.
|
||||
func writeMarkdownRuns(b *strings.Builder, runs []Run) {
|
||||
s, delims := renderRuns(runs, nil)
|
||||
if len(delims) > 0 && !readsAs(s, runs) {
|
||||
html := map[delimKey]bool{}
|
||||
for _, d := range delims {
|
||||
if !d.flanks(s) {
|
||||
html[d.key] = true
|
||||
}
|
||||
}
|
||||
if len(html) > 0 {
|
||||
s2, _ := renderRuns(runs, html)
|
||||
if readsAs(s2, runs) {
|
||||
b.WriteString(s2)
|
||||
return
|
||||
}
|
||||
}
|
||||
for _, d := range delims {
|
||||
html[d.key] = true
|
||||
}
|
||||
s, _ = renderRuns(runs, html)
|
||||
}
|
||||
b.WriteString(s)
|
||||
}
|
||||
|
||||
// delimKey names a mark written in Markdown: the run it opens at and its
|
||||
// kind.
|
||||
type delimKey struct {
|
||||
run int
|
||||
kind byte
|
||||
}
|
||||
|
||||
// delim is where a mark's delimiters are in what renderRuns wrote.
|
||||
type delim struct {
|
||||
key delimKey
|
||||
char byte
|
||||
open, close, length int
|
||||
}
|
||||
|
||||
// flanks reports whether the delimiters can open and close where they
|
||||
// are, as CommonMark's rules of flanking say, the runs of the same
|
||||
// character around them taken together.
|
||||
func (d delim) flanks(s string) bool {
|
||||
return canFlank(s, d.open, d.length, d.char, true) && canFlank(s, d.close, d.length, d.char, false)
|
||||
}
|
||||
|
||||
func canFlank(s string, at, n int, c byte, left bool) bool {
|
||||
from, to := at, at+n
|
||||
for from > 0 && s[from-1] == c {
|
||||
from--
|
||||
}
|
||||
for to < len(s) && s[to] == c {
|
||||
to++
|
||||
}
|
||||
before, after := ' ', ' '
|
||||
if from > 0 {
|
||||
before, _ = utf8.DecodeLastRuneInString(s[:from])
|
||||
}
|
||||
if to < len(s) {
|
||||
after, _ = utf8.DecodeRuneInString(s[to:])
|
||||
}
|
||||
if !left {
|
||||
before, after = after, before
|
||||
}
|
||||
// Left-flanking: not before whitespace, and not before punctuation
|
||||
// unless after whitespace or punctuation; right-flanking mirrored.
|
||||
return !unicode.IsSpace(after) && (!isMarkdownPunct(after) || unicode.IsSpace(before) || isMarkdownPunct(before))
|
||||
}
|
||||
|
||||
func isMarkdownPunct(r rune) bool { return unicode.IsPunct(r) || unicode.IsSymbol(r) }
|
||||
|
||||
// renderRuns writes runs, the marks of html in HTML, and returns where
|
||||
// the delimiters of the others are.
|
||||
func renderRuns(runs []Run, html map[delimKey]bool) (string, []delim) {
|
||||
var b strings.Builder
|
||||
type opened struct {
|
||||
mark
|
||||
key delimKey
|
||||
at int
|
||||
}
|
||||
var open []opened
|
||||
var delims []delim
|
||||
pending := ""
|
||||
first := true
|
||||
closeTo := func(n int) {
|
||||
for len(open) > n {
|
||||
o := open[len(open)-1]
|
||||
h := html[o.key]
|
||||
if c := o.close(h); !h && (o.kind == 'b' || o.kind == 'i' || o.kind == 's') {
|
||||
delims = append(delims, delim{key: o.key, char: c[0], open: o.at, close: b.Len(), length: len(c)})
|
||||
}
|
||||
b.WriteString(o.close(h))
|
||||
open = open[:len(open)-1]
|
||||
}
|
||||
}
|
||||
for i, r := range runs {
|
||||
if at := r.Attributes.Attachment; at != nil {
|
||||
closeTo(0)
|
||||
b.WriteString(pending)
|
||||
pending = ""
|
||||
b.WriteString(" + ")")
|
||||
first = false
|
||||
continue
|
||||
}
|
||||
core := strings.TrimFunc(r.Text, unicode.IsSpace)
|
||||
if core == "" {
|
||||
pending += r.Text
|
||||
continue
|
||||
}
|
||||
lead := r.Text[:strings.Index(r.Text, core)]
|
||||
trail := r.Text[len(lead)+len(core):]
|
||||
want := marksOf(r.Attributes)
|
||||
k := 0
|
||||
for k < len(open) && k < len(want) && open[k].mark == want[k] {
|
||||
k++
|
||||
}
|
||||
closeTo(k)
|
||||
if first {
|
||||
// Spaces at the start would make a block of code.
|
||||
lead = strings.NewReplacer(" ", " ", "\t", "	").Replace(pending + lead)
|
||||
pending = ""
|
||||
}
|
||||
b.WriteString(pending + lead)
|
||||
for _, m := range want[k:] {
|
||||
key := delimKey{i, m.kind}
|
||||
open = append(open, opened{m, key, b.Len()})
|
||||
b.WriteString(m.open(html[key]))
|
||||
}
|
||||
if r.Attributes.Code {
|
||||
b.WriteString(codeSpan(core))
|
||||
} else {
|
||||
s := escapeMarkdown(core)
|
||||
if first {
|
||||
s = escapeBlockStart(s)
|
||||
}
|
||||
if strings.HasSuffix(s, "!") {
|
||||
// Not an image with a link after it.
|
||||
s = s[:len(s)-1] + "\\!"
|
||||
}
|
||||
b.WriteString(s)
|
||||
}
|
||||
first = false
|
||||
pending = trail
|
||||
}
|
||||
closeTo(0)
|
||||
b.WriteString(pending)
|
||||
return b.String(), delims
|
||||
}
|
||||
|
||||
// readsAs reports whether s reads back as runs, as far as Markdown keeps
|
||||
// them: their text, and the marks of all but whitespace.
|
||||
func readsAs(s string, runs []Run) bool {
|
||||
var got []Run
|
||||
for _, p := range ParseMarkdown(s).Paragraphs() {
|
||||
if got != nil {
|
||||
return false
|
||||
}
|
||||
got = append(p.Runs, Run{})[:len(p.Runs)]
|
||||
}
|
||||
return sameMarkRuns(got, runs)
|
||||
}
|
||||
|
||||
// runMarks are the marks of a character that Markdown keeps.
|
||||
type runMarks struct {
|
||||
bold, italic, strike, under, code bool
|
||||
link, atName, atURL string
|
||||
}
|
||||
|
||||
// markScanner walks the runes of runs and the marks Markdown keeps for
|
||||
// each, skipping trailing spaces outside code.
|
||||
type markScanner struct {
|
||||
runs []Run
|
||||
ri int
|
||||
bi int
|
||||
rem int
|
||||
cur runMarks
|
||||
}
|
||||
|
||||
// newMarkScanner counts the bytes of runs, less the trailing spaces outside
|
||||
// code that Markdown does not keep.
|
||||
func newMarkScanner(runs []Run) markScanner {
|
||||
rem := 0
|
||||
for _, r := range runs {
|
||||
rem += len(r.Text)
|
||||
}
|
||||
for i := len(runs) - 1; i >= 0; i-- {
|
||||
text := runs[i].Text
|
||||
if text == "" {
|
||||
continue
|
||||
}
|
||||
if runs[i].Attributes.Code {
|
||||
break
|
||||
}
|
||||
j := len(text)
|
||||
for j > 0 && text[j-1] == ' ' {
|
||||
j--
|
||||
rem--
|
||||
}
|
||||
if j > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return markScanner{runs: runs, rem: rem}
|
||||
}
|
||||
|
||||
// next returns the next rune and its effective Markdown marks, or false at
|
||||
// the end of the scanned prefix.
|
||||
func (s *markScanner) next() (rune, runMarks, bool) {
|
||||
for s.rem > 0 && s.ri < len(s.runs) {
|
||||
r := &s.runs[s.ri]
|
||||
if s.bi >= len(r.Text) {
|
||||
s.ri++
|
||||
s.bi = 0
|
||||
continue
|
||||
}
|
||||
if s.bi == 0 {
|
||||
a := r.Attributes
|
||||
s.cur = runMarks{bold: a.Bold(), italic: a.Italic, strike: a.Strikethrough, under: a.Underline, code: a.Code, link: a.Link}
|
||||
if a.Attachment != nil {
|
||||
s.cur.atName, s.cur.atURL = a.Attachment.Name, a.Attachment.URL
|
||||
}
|
||||
}
|
||||
c, size := utf8.DecodeRuneInString(r.Text[s.bi:])
|
||||
s.bi += size
|
||||
s.rem -= size
|
||||
m := s.cur
|
||||
if unicode.IsSpace(c) && !m.code {
|
||||
m = runMarks{}
|
||||
}
|
||||
return c, m, true
|
||||
}
|
||||
return 0, runMarks{}, false
|
||||
}
|
||||
|
||||
// sameMarkRuns reports whether a and b have the same runes and Markdown
|
||||
// marks, without allocating per-rune slices.
|
||||
func sameMarkRuns(a, b []Run) bool {
|
||||
sa, sb := newMarkScanner(a), newMarkScanner(b)
|
||||
for {
|
||||
ca, ma, oka := sa.next()
|
||||
cb, mb, okb := sb.next()
|
||||
if oka != okb {
|
||||
return false
|
||||
}
|
||||
if !oka {
|
||||
return true
|
||||
}
|
||||
if ca != cb || ma != mb {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// codeSpan returns s as a code span, fenced by more backticks than any
|
||||
// run of them in it.
|
||||
func codeSpan(s string) string {
|
||||
longest, n := 0, 0
|
||||
for _, r := range s {
|
||||
if r == '`' {
|
||||
n++
|
||||
longest = max(longest, n)
|
||||
} else {
|
||||
n = 0
|
||||
}
|
||||
}
|
||||
fence := strings.Repeat("`", longest+1)
|
||||
if strings.HasPrefix(s, "`") || strings.HasSuffix(s, "`") {
|
||||
s = " " + s + " "
|
||||
}
|
||||
return fence + s + fence
|
||||
}
|
||||
|
||||
// escapeMarkdown escapes what Markdown would read as marks.
|
||||
func escapeMarkdown(s string) string {
|
||||
var b strings.Builder
|
||||
for i, r := range s {
|
||||
switch r {
|
||||
case '\\', '*', '_', '`', '[', ']', '<', '~':
|
||||
b.WriteByte('\\')
|
||||
case '&':
|
||||
// Not the start of an entity, as & or &.
|
||||
if i+1 < len(s) && (s[i+1] == '#' || unicode.IsLetter(rune(s[i+1]))) {
|
||||
b.WriteByte('\\')
|
||||
}
|
||||
}
|
||||
b.WriteRune(r)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// escapeBlockStart escapes the start of a body paragraph that Markdown
|
||||
// would read as a heading, a list, a quotation or a rule.
|
||||
func escapeBlockStart(s string) string {
|
||||
switch {
|
||||
case strings.HasPrefix(s, "#"), strings.HasPrefix(s, ">"), strings.HasPrefix(s, "-"), strings.HasPrefix(s, "+"), strings.HasPrefix(s, "="):
|
||||
return "\\" + s
|
||||
}
|
||||
i := 0
|
||||
for i < len(s) && s[i] >= '0' && s[i] <= '9' {
|
||||
i++
|
||||
}
|
||||
if i > 0 && i < len(s) && (s[i] == '.' || s[i] == ')') {
|
||||
return s[:i] + "\\" + s[i:]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// markdownURL returns a URL as the destination of a link.
|
||||
func markdownURL(u string) string {
|
||||
if strings.ContainsAny(u, " ()<>") {
|
||||
return "<" + strings.NewReplacer("<", "%3C", ">", "%3E").Replace(u) + ">"
|
||||
}
|
||||
return u
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSameMarkRuns(test *testing.T) {
|
||||
bold := Attributes{Weight: 700}
|
||||
underlined := Attributes{Underline: true}
|
||||
strike := Attributes{Strikethrough: true}
|
||||
code := Attributes{Code: true}
|
||||
linked := Attributes{Link: "https://example.com"}
|
||||
attachmentAttributes := func(name, url string) Attributes {
|
||||
return Attributes{Attachment: &Attachment{Name: name, URL: url}}
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
left, right []Run
|
||||
want bool
|
||||
}{
|
||||
{"empty", nil, nil, true},
|
||||
{"empty runs", []Run{{}, {Text: " "}}, nil, true},
|
||||
{"trailing spaces", []Run{{Text: "a"}, {Text: " "}}, []Run{{Text: "a"}}, true},
|
||||
{"trailing spaces across runs", []Run{{Text: "a"}, {Text: " "}, {Text: "b "}}, []Run{{Text: "a b"}}, true},
|
||||
{"trailing spaces in code", []Run{{Text: "a"}, {Text: " ", Attributes: code}}, []Run{{Text: "a"}}, false},
|
||||
{"trailing spaces after code", []Run{{Text: "a"}, {Text: " ", Attributes: code}, {Text: " "}}, []Run{{Text: "a"}, {Text: " ", Attributes: code}}, true},
|
||||
{"code run after trailing spaces", []Run{{Text: "a "}, {Text: " ", Attributes: code}}, []Run{{Text: "a "}, {Text: " ", Attributes: code}}, true},
|
||||
{"code run after stripped spaces", []Run{{Text: "a "}, {Text: " ", Attributes: code}}, []Run{{Text: "a"}, {Text: " ", Attributes: code}}, false},
|
||||
{"empty code run between trailing spaces", []Run{{Text: "a "}, {Text: "", Attributes: code}, {Text: " "}}, []Run{{Text: "a"}}, true},
|
||||
{"trailing tab", []Run{{Text: "a"}, {Text: " \t "}}, []Run{{Text: "a"}, {Text: " \t"}}, true},
|
||||
{"trailing tab with marks", []Run{{Text: "a"}, {Text: " \t ", Attributes: bold}}, []Run{{Text: "a"}, {Text: " \t", Attributes: bold}}, true},
|
||||
{"whitespace marks ignored", []Run{{Text: "a"}, {Text: " ", Attributes: bold}, {Text: "b"}}, []Run{{Text: "a b"}}, true},
|
||||
{"code whitespace marks kept", []Run{{Text: "a"}, {Text: " ", Attributes: code}, {Text: "b"}}, []Run{{Text: "a b"}}, false},
|
||||
{"attachment name", []Run{{Text: string(ObjectReplacement), Attributes: attachmentAttributes("cat", "cat.png")}}, []Run{{Text: string(ObjectReplacement), Attributes: attachmentAttributes("dog", "cat.png")}}, false},
|
||||
{"attachment URL", []Run{{Text: string(ObjectReplacement), Attributes: attachmentAttributes("cat", "cat.png")}}, []Run{{Text: string(ObjectReplacement), Attributes: attachmentAttributes("cat", "dog.png")}}, false},
|
||||
{"attachment equal", []Run{{Text: string(ObjectReplacement), Attributes: attachmentAttributes("cat", "cat.png")}}, []Run{{Text: string(ObjectReplacement), Attributes: attachmentAttributes("cat", "cat.png")}}, true},
|
||||
{"run boundary", []Run{{Text: "a", Attributes: bold}, {Text: "b", Attributes: bold}}, []Run{{Text: "ab", Attributes: bold}}, true},
|
||||
{"mark changes at run boundary", []Run{{Text: "a", Attributes: bold}, {Text: "b"}}, []Run{{Text: "ab", Attributes: bold}}, false},
|
||||
{"split rune", []Run{{Text: "\xc3"}, {Text: "\xa9"}}, []Run{{Text: "é"}}, false},
|
||||
{"replacement rune encodings", []Run{{Text: "\ufffd"}}, []Run{{Text: "\xff"}}, true},
|
||||
{"rune mismatch", []Run{{Text: "a"}}, []Run{{Text: "b"}}, false},
|
||||
{"length mismatch", []Run{{Text: "a"}}, []Run{{Text: "a"}, {Text: "b"}}, false},
|
||||
{"mark mismatch", []Run{{Text: "a", Attributes: bold}}, []Run{{Text: "a"}}, false},
|
||||
{"link mismatch", []Run{{Text: "a", Attributes: linked}}, []Run{{Text: "a", Attributes: Attributes{Link: "https://other.example"}}}, false},
|
||||
{"code mismatch", []Run{{Text: "a", Attributes: code}}, []Run{{Text: "a"}}, false},
|
||||
{"all marks", []Run{
|
||||
{Text: "a ", Attributes: underlined},
|
||||
{Text: "bold", Attributes: Attributes{Weight: 700, Italic: true, Underline: true, Strikethrough: true, Link: "https://example.com"}},
|
||||
{Text: " "},
|
||||
{Text: "code", Attributes: code},
|
||||
{Text: " "},
|
||||
{Text: string(ObjectReplacement), Attributes: attachmentAttributes("cat", "cat.png")},
|
||||
}, []Run{
|
||||
{Text: "a ", Attributes: strike},
|
||||
{Text: "bold", Attributes: Attributes{Weight: 700, Italic: true, Underline: true, Strikethrough: true, Link: "https://example.com"}},
|
||||
{Text: " "},
|
||||
{Text: "code", Attributes: code},
|
||||
{Text: " "},
|
||||
{Text: string(ObjectReplacement), Attributes: attachmentAttributes("cat", "cat.png")},
|
||||
}, false},
|
||||
}
|
||||
for _, testCase := range tests {
|
||||
test.Run(testCase.name, func(test *testing.T) {
|
||||
if got := sameMarkRuns(testCase.left, testCase.right); got != testCase.want {
|
||||
test.Errorf("sameMarkRuns = %v, want %v", got, testCase.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkdownReadsAs(test *testing.T) {
|
||||
bold := Attributes{Weight: 700}
|
||||
tests := []struct {
|
||||
name string
|
||||
source string
|
||||
runs []Run
|
||||
want bool
|
||||
}{
|
||||
{"bold", "**a**", []Run{{Text: "a", Attributes: bold}}, true},
|
||||
{"bold with trailing spaces", "**a** ", []Run{{Text: "a", Attributes: bold}}, true},
|
||||
{"plain", "**a**", []Run{{Text: "a"}}, false},
|
||||
{"multiple paragraphs", "a\n\nb", []Run{{Text: "a"}, {Text: "b"}}, false},
|
||||
{"empty", "", nil, true},
|
||||
}
|
||||
for _, testCase := range tests {
|
||||
test.Run(testCase.name, func(test *testing.T) {
|
||||
if got := readsAs(testCase.source, testCase.runs); got != testCase.want {
|
||||
test.Errorf("readsAs = %v, want %v", got, testCase.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameMarkRunsAllocs(test *testing.T) {
|
||||
left := readsAsRuns()
|
||||
right := readsAsRuns()
|
||||
var equal bool
|
||||
allocs := testing.AllocsPerRun(100, func() {
|
||||
equal = sameMarkRuns(left, right)
|
||||
})
|
||||
if !equal {
|
||||
test.Fatal("runs with the same marks compare unequal")
|
||||
}
|
||||
if allocs != 0 {
|
||||
test.Errorf("got %v allocations, want 0", allocs)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkSameMarkRuns(bench *testing.B) {
|
||||
left := readsAsRuns()
|
||||
right := readsAsRuns()
|
||||
if !sameMarkRuns(left, right) {
|
||||
bench.Fatal("runs with the same marks compare unequal")
|
||||
}
|
||||
bench.ReportAllocs()
|
||||
for bench.Loop() {
|
||||
if !sameMarkRuns(left, right) {
|
||||
bench.Fatal("runs with the same marks compare unequal")
|
||||
}
|
||||
}
|
||||
}
|
||||
+282
@@ -0,0 +1,282 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/egoist/mygo/ui/markdown/parser"
|
||||
)
|
||||
|
||||
// ParseMarkdown returns the attributed text of Markdown, CommonMark with
|
||||
// GitHub's extensions and footnotes, as Markdown writes it: headings,
|
||||
// lists and task lists, quotations, blocks of code, bold, italic,
|
||||
// strikethrough, code, links, images, and the HTML tags of these marks
|
||||
// and of underlines, <u>. A list item's paragraphs after its first are
|
||||
// indented under it; a table's rows are paragraphs of their cells apart
|
||||
// by tabs, the header's bold. Math, which the editor does not show, stays
|
||||
// as written: \[ is an escaped bracket, as everywhere but in math.
|
||||
func ParseMarkdown(s string) Text {
|
||||
d := parser.New(parser.GFM | parser.ExtFootnotes)
|
||||
d.Set(s)
|
||||
m := mdReader{d: d}
|
||||
m.blocks(0, ParagraphStyle{}, -1)
|
||||
if len(m.paras) == 0 {
|
||||
return Text{}
|
||||
}
|
||||
return TextOf(m.paras...)
|
||||
}
|
||||
|
||||
// mdReader reads the blocks and inlines of a Markdown document into
|
||||
// paragraphs.
|
||||
type mdReader struct {
|
||||
d *parser.Document
|
||||
paras []Paragraph
|
||||
// html counts the inline HTML tags open, by the attribute they turn
|
||||
// on: <u>, <s>, <b> and <i> and their synonyms.
|
||||
html [4]int
|
||||
}
|
||||
|
||||
// blocks adds the children of block i in style st; depth is the level of
|
||||
// the list they are in, -1 outside lists.
|
||||
func (m *mdReader) blocks(i int, st ParagraphStyle, depth int) {
|
||||
for k := range m.d.Children(i) {
|
||||
m.block(k, st, depth)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *mdReader) block(i int, st ParagraphStyle, depth int) {
|
||||
b := m.d.Block(i)
|
||||
switch b.Kind {
|
||||
case parser.Paragraph:
|
||||
m.inlinePara(st, m.d.Inlines(i), Attributes{})
|
||||
case parser.Heading:
|
||||
st.Heading = b.Level
|
||||
m.inlinePara(st, m.d.Inlines(i), Attributes{})
|
||||
case parser.CodeBlock:
|
||||
st.CodeBlock, st.Heading = true, 0
|
||||
n := m.d.LineCount(i)
|
||||
for k := range n {
|
||||
line, _ := m.d.Line(i, k)
|
||||
p := Paragraph{Style: st}
|
||||
if line != "" {
|
||||
p.Runs = []Run{{Text: line}}
|
||||
}
|
||||
m.paras = append(m.paras, p)
|
||||
}
|
||||
if n == 0 {
|
||||
m.paras = append(m.paras, Paragraph{Style: st})
|
||||
}
|
||||
case parser.HTMLBlock:
|
||||
for _, p := range ParseHTML(m.d.Lines(i)).Paragraphs() {
|
||||
depth := p.Style.quoteDepth() + st.quoteDepth()
|
||||
p.Style.Quote = depth > 0
|
||||
if depth > 1 {
|
||||
p.Style.QuoteDepth = depth
|
||||
}
|
||||
p.Style.Indent += st.Indent
|
||||
m.paras = append(m.paras, p)
|
||||
}
|
||||
case parser.Quote:
|
||||
if st.Quote {
|
||||
st.QuoteDepth = st.quoteDepth() + 1
|
||||
}
|
||||
st.Quote = true
|
||||
m.blocks(i, st, depth)
|
||||
case parser.List:
|
||||
kind := Bullets
|
||||
if b.Ordered {
|
||||
kind = Numbers
|
||||
}
|
||||
for it := range m.d.Children(i) {
|
||||
ist := ParagraphStyle{List: kind, Indent: depth + 1, Quote: st.Quote, QuoteDepth: st.QuoteDepth}
|
||||
if task := m.d.Block(it).Task; task != parser.NoTask {
|
||||
ist.List, ist.Checked = Tasks, task == parser.Checked
|
||||
}
|
||||
m.item(it, ist, depth+1)
|
||||
}
|
||||
case parser.Table:
|
||||
for row := range m.d.Children(i) {
|
||||
p := Paragraph{Style: st}
|
||||
var a Attributes
|
||||
if m.d.Block(row).Header {
|
||||
a.Weight = 700
|
||||
}
|
||||
first := true
|
||||
for cell := range m.d.Children(row) {
|
||||
if !first {
|
||||
p.Runs = addMDRun(p.Runs, Run{Text: "\t", Attributes: a})
|
||||
}
|
||||
first = false
|
||||
for _, r := range m.runs(m.d.Inlines(cell), a) {
|
||||
p.Runs = addMDRun(p.Runs, r)
|
||||
}
|
||||
}
|
||||
m.paras = append(m.paras, p)
|
||||
}
|
||||
case parser.FootnoteDefinition:
|
||||
from := len(m.paras)
|
||||
m.blocks(i, st, depth)
|
||||
if from < len(m.paras) {
|
||||
p := &m.paras[from]
|
||||
p.Runs = append([]Run{{Text: "[" + b.Label() + "] "}}, p.Runs...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// item adds a list item: its first paragraph in the item's style ist, and
|
||||
// what follows indented under it.
|
||||
func (m *mdReader) item(i int, ist ParagraphStyle, depth int) {
|
||||
under := ParagraphStyle{Indent: depth + 1, Quote: ist.Quote, QuoteDepth: ist.QuoteDepth}
|
||||
first := true
|
||||
for k := range m.d.Children(i) {
|
||||
b := m.d.Block(k)
|
||||
if first {
|
||||
first = false
|
||||
if b.Kind == parser.Paragraph || b.Kind == parser.Heading {
|
||||
m.block(k, ist, depth)
|
||||
continue
|
||||
}
|
||||
// An item starting with code or a list has an empty line of
|
||||
// its own, as it shows.
|
||||
m.paras = append(m.paras, Paragraph{Style: ist})
|
||||
}
|
||||
m.block(k, under, depth)
|
||||
}
|
||||
if first {
|
||||
m.paras = append(m.paras, Paragraph{Style: ist})
|
||||
}
|
||||
}
|
||||
|
||||
// inlinePara adds a paragraph of inlines in style st; a hard line break
|
||||
// starts another, indented under a list item rather than an item of its
|
||||
// own.
|
||||
func (m *mdReader) inlinePara(st ParagraphStyle, in []parser.Inline, a Attributes) {
|
||||
runs := m.runs(in, a)
|
||||
p := Paragraph{Style: st}
|
||||
for _, r := range runs {
|
||||
for {
|
||||
line, rest, br := strings.Cut(r.Text, "\n")
|
||||
if line != "" {
|
||||
p.Runs = append(p.Runs, Run{Text: line, Attributes: r.Attributes})
|
||||
}
|
||||
if !br {
|
||||
break
|
||||
}
|
||||
m.paras = append(m.paras, p)
|
||||
if st.List != NoList {
|
||||
st = ParagraphStyle{Indent: st.Indent + 1, Quote: st.Quote, QuoteDepth: st.QuoteDepth}
|
||||
}
|
||||
p = Paragraph{Style: st}
|
||||
r.Text = rest
|
||||
}
|
||||
}
|
||||
m.paras = append(m.paras, p)
|
||||
}
|
||||
|
||||
// runs returns the runs of inlines, in attributes a; hard line breaks
|
||||
// are newlines.
|
||||
func (m *mdReader) runs(in []parser.Inline, a Attributes) []Run {
|
||||
var out []Run
|
||||
m.html = [4]int{}
|
||||
m.inlines(&out, in, 0, len(in), a)
|
||||
return out
|
||||
}
|
||||
|
||||
func (m *mdReader) inlines(out *[]Run, in []parser.Inline, from, to int, a Attributes) {
|
||||
add := func(s string, a Attributes) {
|
||||
if m.html[0] > 0 {
|
||||
a.Underline = true
|
||||
}
|
||||
if m.html[1] > 0 {
|
||||
a.Strikethrough = true
|
||||
}
|
||||
if m.html[2] > 0 {
|
||||
a.Weight = 700
|
||||
}
|
||||
if m.html[3] > 0 {
|
||||
a.Italic = true
|
||||
}
|
||||
*out = addMDRun(*out, Run{Text: s, Attributes: a})
|
||||
}
|
||||
for k := from; k < to; k = in[k].Next {
|
||||
n := &in[k]
|
||||
x := a
|
||||
switch n.Kind {
|
||||
case parser.Text:
|
||||
add(n.Text, a)
|
||||
case parser.SoftBreak:
|
||||
add(" ", a)
|
||||
case parser.LineBreak:
|
||||
add("\n", a)
|
||||
case parser.Code:
|
||||
x.Code = true
|
||||
add(n.Text, x)
|
||||
case parser.Emphasis:
|
||||
x.Italic = true
|
||||
m.inlines(out, in, k+1, n.Next, x)
|
||||
case parser.Strong:
|
||||
x.Weight = 700
|
||||
m.inlines(out, in, k+1, n.Next, x)
|
||||
case parser.Strikethrough:
|
||||
x.Strikethrough = true
|
||||
m.inlines(out, in, k+1, n.Next, x)
|
||||
case parser.Link:
|
||||
x.Link = safeLink(n.Dest)
|
||||
m.inlines(out, in, k+1, n.Next, x)
|
||||
case parser.Image:
|
||||
x = a.extending()
|
||||
x.Attachment = &Attachment{Name: parser.PlainText(in[k+1 : n.Next]), URL: safeLink(n.Dest)}
|
||||
*out = append(*out, Run{Text: string(ObjectReplacement), Attributes: x})
|
||||
case parser.HTML:
|
||||
m.tag(n.Text, out, a)
|
||||
case parser.FootnoteRef:
|
||||
add("["+n.Text+"]", a)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tag applies an inline HTML tag: the opening and closing tags of
|
||||
// underlines, strikethrough, bold and italic, and line breaks. Other
|
||||
// tags are left out, as a browser shows none.
|
||||
func (m *mdReader) tag(s string, out *[]Run, a Attributes) {
|
||||
s = strings.ToLower(strings.TrimSpace(s))
|
||||
if !strings.HasPrefix(s, "<") || !strings.HasSuffix(s, ">") {
|
||||
return
|
||||
}
|
||||
s = strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(s, "<"), ">"))
|
||||
closing := strings.HasPrefix(s, "/")
|
||||
s = strings.TrimPrefix(s, "/")
|
||||
s = strings.TrimSuffix(s, "/")
|
||||
name, _, _ := strings.Cut(strings.TrimSpace(s), " ")
|
||||
which := -1
|
||||
switch name {
|
||||
case "br":
|
||||
*out = append(*out, Run{Text: "\n", Attributes: a})
|
||||
return
|
||||
case "u", "ins":
|
||||
which = 0
|
||||
case "s", "strike", "del":
|
||||
which = 1
|
||||
case "b", "strong":
|
||||
which = 2
|
||||
case "i", "em":
|
||||
which = 3
|
||||
}
|
||||
if which < 0 {
|
||||
return
|
||||
}
|
||||
if closing {
|
||||
m.html[which] = max(m.html[which]-1, 0)
|
||||
} else {
|
||||
m.html[which]++
|
||||
}
|
||||
}
|
||||
|
||||
// addMDRun appends r to runs, joined to the last when their attributes
|
||||
// are the same.
|
||||
func addMDRun(runs []Run, r Run) []Run {
|
||||
if n := len(runs); n > 0 && runs[n-1].Attributes == r.Attributes && r.Attributes.Attachment == nil {
|
||||
runs[n-1].Text += r.Text
|
||||
return runs
|
||||
}
|
||||
return append(runs, r)
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/transfer"
|
||||
"github.com/egoist/mygo/ui"
|
||||
"github.com/egoist/mygo/ui/markdown"
|
||||
)
|
||||
|
||||
// dump writes the paragraphs of t, their styles and runs, to compare.
|
||||
func dump(t Text) string {
|
||||
var b strings.Builder
|
||||
for _, p := range t.Paragraphs() {
|
||||
fmt.Fprintf(&b, "%+v:", p.Style)
|
||||
for _, r := range p.Runs {
|
||||
a := r.Attributes
|
||||
at := a.Attachment
|
||||
a.Attachment = nil
|
||||
fmt.Fprintf(&b, " %q%+v", r.Text, a)
|
||||
if at != nil {
|
||||
fmt.Fprintf(&b, "[%q %q]", at.Name, at.URL)
|
||||
}
|
||||
}
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func TestParseMarkdown(t *testing.T) {
|
||||
want := sample()
|
||||
// Markdown has no alignment.
|
||||
var paras []Paragraph
|
||||
for _, p := range want.Paragraphs() {
|
||||
p.Style.Align = ui.Start
|
||||
paras = append(paras, p)
|
||||
}
|
||||
want = TextOf(paras...)
|
||||
if got := ParseMarkdown(sample().Markdown()); dump(got) != dump(want) {
|
||||
t.Errorf("got\n%s\nwant\n%s", dump(got), dump(want))
|
||||
}
|
||||
|
||||
para := func(st ParagraphStyle, runs ...Run) Paragraph { return Paragraph{Style: st, Runs: runs} }
|
||||
bold := Attributes{Weight: 700}
|
||||
for _, c := range []struct {
|
||||
src string
|
||||
want Text
|
||||
}{
|
||||
{"- item\n\n more\n\n code\n- next", TextOf(
|
||||
para(ParagraphStyle{List: Bullets}, Run{Text: "item"}),
|
||||
para(ParagraphStyle{Indent: 1}, Run{Text: "more"}),
|
||||
para(ParagraphStyle{Indent: 1, CodeBlock: true}, Run{Text: "code"}),
|
||||
para(ParagraphStyle{List: Bullets}, Run{Text: "next"}),
|
||||
)},
|
||||
{"> - [x] done\n> - nested", TextOf(
|
||||
para(ParagraphStyle{List: Tasks, Checked: true, Quote: true}, Run{Text: "done"}),
|
||||
para(ParagraphStyle{List: Bullets, Indent: 1, Quote: true}, Run{Text: "nested"}),
|
||||
)},
|
||||
{"a \nb", TextOf(para(ParagraphStyle{}, Run{Text: "a"}), para(ParagraphStyle{}, Run{Text: "b"}))},
|
||||
{"1. a\\\n b", TextOf(para(ParagraphStyle{List: Numbers}, Run{Text: "a"}), para(ParagraphStyle{Indent: 1}, Run{Text: "b"}))},
|
||||
{"| a | b |\n|---|---|\n| 1 | **2** |", TextOf(
|
||||
para(ParagraphStyle{}, Run{Text: "a\tb", Attributes: bold}),
|
||||
para(ParagraphStyle{}, Run{Text: "1\t"}, Run{Text: "2", Attributes: bold}),
|
||||
)},
|
||||
{"x <u>under *it*</u> <b>b</b>", TextOf(para(ParagraphStyle{}, Run{Text: "x "}, Run{Text: "under ", Attributes: Attributes{Underline: true}},
|
||||
Run{Text: "it", Attributes: Attributes{Underline: true, Italic: true}}, Run{Text: " "}, Run{Text: "b", Attributes: bold}))},
|
||||
{" [x](javascript:alert(1))", TextOf(para(ParagraphStyle{},
|
||||
Run{Text: string(ObjectReplacement), Attributes: Attributes{Attachment: &Attachment{Name: "a cat", URL: "cat.png"}}},
|
||||
Run{Text: " x"}))},
|
||||
{"see $$x^2$$, \\[a\\] and[^1]\n\n[^1]: The note.", TextOf(
|
||||
para(ParagraphStyle{}, Run{Text: "see $$x^2$$, [a] and[1]"}),
|
||||
para(ParagraphStyle{}, Run{Text: "[1] The note."}),
|
||||
)},
|
||||
{"", Text{}},
|
||||
} {
|
||||
if got := ParseMarkdown(c.src); dump(got) != dump(c.want) {
|
||||
t.Errorf("%q:\ngot\n%s\nwant\n%s", c.src, dump(got), dump(c.want))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMarkdownRoundTrip writes random texts as Markdown and reads them
|
||||
// back: what Markdown keeps comes back the same.
|
||||
func TestMarkdownRoundTrip(t *testing.T) {
|
||||
rng := rand.New(rand.NewPCG(1, 2))
|
||||
words := []string{"foo", "bar", "a", "x1", ".", ",", "!", "?", "(", ")", "-", "#", "*", "_", "`", "~", "[", "]", "<", ">", "&", "\\", "1.", "é", "\"", "'", ":", "/"}
|
||||
pick := func() Attributes {
|
||||
var a Attributes
|
||||
if rng.IntN(3) == 0 {
|
||||
a.Weight = 700
|
||||
}
|
||||
if rng.IntN(3) == 0 {
|
||||
a.Italic = true
|
||||
}
|
||||
if rng.IntN(5) == 0 {
|
||||
a.Strikethrough = true
|
||||
}
|
||||
if rng.IntN(6) == 0 {
|
||||
a.Underline = true
|
||||
}
|
||||
if rng.IntN(6) == 0 {
|
||||
a.Link = "https://e.org/" + fmt.Sprint(rng.IntN(3))
|
||||
}
|
||||
if rng.IntN(7) == 0 {
|
||||
a = Attributes{Code: true}
|
||||
}
|
||||
return a
|
||||
}
|
||||
failures := 0
|
||||
for range 3000 {
|
||||
var runs []Run
|
||||
for range 1 + rng.IntN(5) {
|
||||
var s strings.Builder
|
||||
for k := range 1 + rng.IntN(3) {
|
||||
if k > 0 && rng.IntN(2) == 0 {
|
||||
s.WriteByte(' ')
|
||||
}
|
||||
s.WriteString(words[rng.IntN(len(words))])
|
||||
}
|
||||
runs = append(runs, Run{Text: s.String(), Attributes: pick()})
|
||||
}
|
||||
// Only what shows the same: spaces at the ends of a paragraph are
|
||||
// not shown, and a code span's are its own.
|
||||
want := TextOf(Paragraph{Runs: runs})
|
||||
want = TextOf(normalize(want)...)
|
||||
md := want.Markdown()
|
||||
if got := ParseMarkdown(md); dump(got) != dump(want) {
|
||||
failures++
|
||||
if failures <= 10 {
|
||||
t.Errorf("%q as Markdown %q reads\n%s want\n%s", want.String(), md, dump(got), dump(want))
|
||||
}
|
||||
}
|
||||
}
|
||||
if failures > 0 {
|
||||
t.Errorf("%d of 3000 failed", failures)
|
||||
}
|
||||
}
|
||||
|
||||
// normalize returns the paragraphs of t as Markdown can keep them: no
|
||||
// spaces at their ends, and none at the ends of code, which a code span
|
||||
// takes as its padding.
|
||||
func normalize(t Text) []Paragraph {
|
||||
var out []Paragraph
|
||||
for _, p := range t.Paragraphs() {
|
||||
var runs []Run
|
||||
for i, r := range p.Runs {
|
||||
if i == 0 {
|
||||
r.Text = strings.TrimLeft(r.Text, " ")
|
||||
}
|
||||
if i == len(p.Runs)-1 {
|
||||
r.Text = strings.TrimRight(r.Text, " ")
|
||||
}
|
||||
if r.Attributes.Code {
|
||||
r.Text = strings.Trim(r.Text, " ")
|
||||
}
|
||||
if r.Text == "" {
|
||||
continue
|
||||
}
|
||||
if n := len(runs); n > 0 && runs[n-1].Attributes == r.Attributes {
|
||||
runs[n-1].Text += r.Text
|
||||
continue
|
||||
}
|
||||
runs = append(runs, r)
|
||||
}
|
||||
p.Runs = runs
|
||||
out = append(out, p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TestPasteFromMarkdownView copies a Markdown view's selection and pastes
|
||||
// it into the editor with its formatting, through HTML, and pastes the
|
||||
// Markdown that Markdown apps copy.
|
||||
func TestPasteFromMarkdownView(t *testing.T) {
|
||||
src := "## Plan\n\nSome **bold** and `code`.\n\n- [x] done\n"
|
||||
view := ui.NewTester(func(c *ui.Context) { markdown.View(c, src, nil) }, 500, 300)
|
||||
view.Click("Plan")
|
||||
view.Key(ui.Cmd, ui.KeyA)
|
||||
view.Key(ui.Cmd, ui.KeyC)
|
||||
data := view.ClipboardData()
|
||||
for _, f := range []transfer.Format{transfer.Text, transfer.HTML, transfer.Markdown} {
|
||||
if _, err := data.Read(f); err != nil {
|
||||
t.Fatalf("no %s copied", f)
|
||||
}
|
||||
}
|
||||
want := TextOf(
|
||||
Paragraph{Style: ParagraphStyle{Heading: 2}, Runs: []Run{{Text: "Plan"}}},
|
||||
Paragraph{Runs: []Run{{Text: "Some "}, {Text: "bold", Attributes: Attributes{Weight: 700}}, {Text: " and "}, {Text: "code", Attributes: Attributes{Code: true}}, {Text: "."}}},
|
||||
Paragraph{Style: ParagraphStyle{List: Tasks, Checked: true}, Runs: []Run{{Text: "done"}}},
|
||||
)
|
||||
for _, only := range []transfer.Format{transfer.HTML, transfer.Markdown} {
|
||||
b, _ := data.Read(only)
|
||||
doc := NewDocument(Text{})
|
||||
tt, _ := richTester(t, doc)
|
||||
tt.SetClipboardData(transfer.New(transfer.NewItem(transfer.Bytes(only, b), transfer.Bytes(transfer.Text, []byte("plain")))))
|
||||
tt.Key(ui.Cmd, ui.KeyV)
|
||||
if dump(doc.Text()) != dump(want) {
|
||||
t.Errorf("pasted from %s %q:\n%s\nwant\n%s", only, b, dump(doc.Text()), dump(want))
|
||||
}
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// about reports whether two lengths in DIPs are the same within a pixel's
|
||||
// rounding.
|
||||
func about(a, b float32) bool { return math.Abs(float64(a-b)) < 0.6 }
|
||||
|
||||
// A heading's LineHeight sets the height of its lines in ems of its size,
|
||||
// on each line it wraps to; without it a heading takes the text's. The
|
||||
// multiples are above any platform's own spacing (Segoe UI's ascent and
|
||||
// descent are 1.33 ems), as a line is never shorter than its font's
|
||||
// ascent and descent.
|
||||
func TestHeadingLineHeight(t *testing.T) {
|
||||
doc := NewDocument(TextOf(
|
||||
Paragraph{Style: ParagraphStyle{Heading: 1}, Runs: []Run{{Text: "Title"}}},
|
||||
Paragraph{Style: ParagraphStyle{Heading: 2}, Runs: []Run{{Text: "wraps wraps wraps wraps wraps wraps wraps wraps wraps"}}},
|
||||
Paragraph{Style: ParagraphStyle{Heading: 3}, Runs: []Run{{Text: "Text's"}}},
|
||||
Paragraph{Runs: []Run{{Text: "body"}}},
|
||||
))
|
||||
th := &Theme{Headings: [6]HeadingStyle{
|
||||
{Size: 24.0 / 15, LineHeight: 1.5},
|
||||
{Size: 20.0 / 15, LineHeight: 1.5},
|
||||
{Size: 16.0 / 15},
|
||||
}}
|
||||
tt := ui.NewTester(func(c *ui.Context) {
|
||||
EditorBase(c, doc, EditorOptions{Font: ui.Font{Size: 15, LineHeight: 1.6}, Theme: th}).Fill()
|
||||
}, 300, 400)
|
||||
tt.Frame()
|
||||
boxes := doc.VisibleParagraphs()
|
||||
if len(boxes) != 4 {
|
||||
t.Fatalf("paragraphs in view: %+v", boxes)
|
||||
}
|
||||
if h := boxes[0].Height; !about(h, 36) {
|
||||
t.Errorf("a heading of 24 with lines of 36: %v high", h)
|
||||
}
|
||||
// How many lines the second wraps to depends on the platform's font.
|
||||
lines := len(doc.shownIn.Value().paras[1].layout.Lines())
|
||||
if lines < 2 {
|
||||
t.Errorf("the second heading is on %d lines, want it to wrap", lines)
|
||||
}
|
||||
if h := boxes[1].Height; !about(h, float32(lines)*30) {
|
||||
t.Errorf("a heading of 20 with lines of 30, on %d lines: %v high", lines, h)
|
||||
}
|
||||
if h := boxes[2].Height; !about(h, 16*1.6) {
|
||||
t.Errorf("a heading without LineHeight takes the text's, %v: %v high", 16*1.6, h)
|
||||
}
|
||||
if h := boxes[3].Height; !about(h, 24) {
|
||||
t.Errorf("body text %v high", h)
|
||||
}
|
||||
}
|
||||
|
||||
// Space less than zero takes room away from the theme's, down to none:
|
||||
// a paragraph never runs into the one above.
|
||||
func TestSpaceTakesAway(t *testing.T) {
|
||||
doc := NewDocument(NewText("one\ntwo\nthree"))
|
||||
var room float32
|
||||
tt := ui.NewTester(func(c *ui.Context) {
|
||||
EditorBase(c, doc, EditorOptions{Font: ui.Font{Size: 15, LineHeight: 22.0 / 15}, Theme: &Theme{ParagraphSpacing: 8.0 / 15},
|
||||
Space: func(p int) float32 {
|
||||
if p == 1 {
|
||||
return room
|
||||
}
|
||||
return 0
|
||||
}}).Fill()
|
||||
}, 300, 200)
|
||||
gap := func() float32 {
|
||||
tt.Frame()
|
||||
tt.Frame()
|
||||
b := doc.VisibleParagraphs()
|
||||
return b[1].Top - (b[0].Top + b[0].Height)
|
||||
}
|
||||
for _, c := range []struct{ room, want float32 }{{0, 8}, {12, 20}, {-3, 5}, {-8, 0}, {-40, 0}} {
|
||||
room = c.room
|
||||
if g := gap(); !about(g, c.want) {
|
||||
t.Errorf("Space %v: %v between the paragraphs, want %v", c.room, g, c.want)
|
||||
}
|
||||
}
|
||||
b := doc.VisibleParagraphs()
|
||||
if g := b[2].Top - (b[1].Top + b[1].Height); !about(g, 8) {
|
||||
t.Errorf("the paragraph after: %v above it", g)
|
||||
}
|
||||
}
|
||||
|
||||
// Above a block of code, Space less than zero takes room away from the
|
||||
// block's padding at its top, inside its background, down to none.
|
||||
func TestSpaceTakesAwayCodePadding(t *testing.T) {
|
||||
doc := NewDocument(TextOf(
|
||||
para("before"),
|
||||
Paragraph{Style: ParagraphStyle{CodeBlock: true}, Runs: []Run{{Text: "code"}}},
|
||||
))
|
||||
var room float32
|
||||
tt := ui.NewTester(func(c *ui.Context) {
|
||||
EditorBase(c, doc, EditorOptions{Font: ui.Font{Size: 15, LineHeight: 22.0 / 15}, Theme: &Theme{CodeBlockPadding: [2]float32{12.0 / 15, 10.0 / 15}},
|
||||
Space: func(p int) float32 {
|
||||
if p == 1 {
|
||||
return room
|
||||
}
|
||||
return 0
|
||||
}}).Fill()
|
||||
}, 300, 200)
|
||||
gap := func() float32 {
|
||||
tt.Frame()
|
||||
tt.Frame()
|
||||
b := doc.VisibleParagraphs()
|
||||
return b[1].Top - (b[0].Top + b[0].Height)
|
||||
}
|
||||
for _, c := range []struct{ room, want float32 }{{0, 10}, {-4, 6}, {-10, 0}, {-30, 0}} {
|
||||
room = c.room
|
||||
if g := gap(); !about(g, c.want) {
|
||||
t.Errorf("Space %v above a block of code: %v between the paragraphs, want %v", c.room, g, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// paint lays out the paragraphs in view of the box r, and paints them:
|
||||
// their decorations, the selection, their text, the markers of lists, the
|
||||
// composition, the caret and the scroll bar.
|
||||
func (v *view) paint(p *ui.Painter, r ui.Rect) {
|
||||
v.rect = r
|
||||
w, h := max(r.W-2*v.padX, 1), max(r.H-2*v.padY, 1)
|
||||
// What of the text the clip shows, with a screen more above and below
|
||||
// it, laid out ahead of a scroll.
|
||||
if vis := p.Visible(); vis.H < h {
|
||||
top := vis.Y - (r.Y + v.padY)
|
||||
v.clip, v.clipped = [2]float32{top - vis.H, top + 2*vis.H}, true
|
||||
} else {
|
||||
v.clipped = false
|
||||
}
|
||||
v.layout(w, h)
|
||||
ox, oy := r.X+v.padX, r.Y+v.padY
|
||||
look := &v.look
|
||||
if v.shown.Len() == 0 && v.compose == "" && v.opts.Placeholder != "" {
|
||||
// where the text would start: past a list's marker, a task's box or a quote's bar, not under them
|
||||
px, py := v.origin(0)
|
||||
pl := ui.ShapeRichTextWith([]ui.Span{{Text: v.opts.Placeholder}}, v.paraFont(v.para(0).style), ui.TextShape{Width: max(w-px, 1)})
|
||||
p.TextLayout(pl, ox+px, oy+float32(py-v.scroll), look.Muted)
|
||||
}
|
||||
a, z := v.selection()
|
||||
focused := v.focused
|
||||
// Only the paragraphs the painter's clip shows are painted: an editor as
|
||||
// tall as its text, in a scroll container, has all of them in its box.
|
||||
// Each one's start is counted on from the one before it; found from the
|
||||
// start of the text, it cost as much as the text is long, for each one.
|
||||
vis := p.Visible()
|
||||
compose := -1
|
||||
if v.compose != "" {
|
||||
compose = v.shown.paraAt(v.caret)
|
||||
}
|
||||
ps := v.shown.paraStart(v.first)
|
||||
for i := v.first; i <= v.last && i < len(v.paras); i, ps = i+1, ps+v.para(i).n+1 {
|
||||
top := oy + float32(v.hs.top(i)-v.scroll)
|
||||
if bottom := oy + float32(v.hs.top(i+1)-v.scroll); bottom < vis.Y || top > vis.Y+vis.H {
|
||||
continue
|
||||
}
|
||||
pv := v.paraLayout(i)
|
||||
st := v.para(i).style
|
||||
px, py := v.origin(i)
|
||||
x, y := ox+px, oy+float32(py-v.scroll)
|
||||
v.paintBlock(p, i, st, ox, top, pv.h, w)
|
||||
pe := ps + v.para(i).n
|
||||
if a != z && a <= pe && z >= ps && (focused || v.opts.ReadOnly) {
|
||||
from, to := v.local(i, max(a, ps)), v.local(i, min(z, pe))
|
||||
color := look.Selection
|
||||
for _, s := range pv.layout.SelectionRects(ui.TextInputRange{Start: pv.units[from], End: pv.units[to]}) {
|
||||
p.Fill(ui.Rect{X: x + s.X, Y: y + s.Y, W: s.W, H: s.H}, color, 0)
|
||||
}
|
||||
if z > pe && i < len(v.paras)-1 {
|
||||
// The newline selected, as a space after the line.
|
||||
c := pv.layout.CaretAt(ui.TextCaretPosition{Index: pv.units[len(pv.units)-1], Affinity: ui.TextUpstream})
|
||||
p.Fill(ui.Rect{X: x + c.X, Y: y + c.Y, W: look.size * 0.35, H: c.H}, color, 0)
|
||||
}
|
||||
}
|
||||
p.TextLayout(pv.layout, x, y, look.Text)
|
||||
v.paintAttachments(p, i, pv, x, y)
|
||||
v.paintMarker(p, i, st, pv, x, y)
|
||||
if compose == i {
|
||||
c := v.local(i, v.caret)
|
||||
n := len([]rune(v.compose))
|
||||
for _, s := range pv.layout.SelectionRects(ui.TextInputRange{Start: pv.units[c], End: pv.units[min(c+n, len(pv.units)-1)]}) {
|
||||
p.Fill(ui.Rect{X: x + s.X, Y: y + s.Y + s.H - 2, W: s.W, H: 1}, look.Text, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
if focused && !v.opts.ReadOnly && a == z {
|
||||
const blink = 530 * time.Millisecond
|
||||
if phase := p.Now().Sub(v.blinkStart); (phase/blink)%2 == 0 || phase < 0 {
|
||||
cx, cy, ch := v.caretAt(v.caret, v.composeCaret, v.affinity)
|
||||
scale := p.Scale()
|
||||
p.Fill(ui.Rect{X: ox + cx, Y: oy + float32(cy-v.scroll), W: max(1/scale, 1), H: ch}, look.Caret, 0)
|
||||
}
|
||||
}
|
||||
// The scroll bar while the pointer is over the editor or drags its
|
||||
// thumb, as a scroll container's.
|
||||
if !v.opts.NoScrollbar && (v.inView || v.thumb) {
|
||||
v.barStyle = ui.ScrollbarStyle{}.Resolve(p.Theme())
|
||||
bar := v.bar()
|
||||
bar.Box.X, bar.Box.Y = r.X, r.Y
|
||||
p.Scrollbar(bar, ui.ScrollbarState{Hovered: v.inView, Dragging: v.thumb})
|
||||
}
|
||||
v.moved()
|
||||
}
|
||||
|
||||
// paintBlock paints what a paragraph of style st shows behind its text:
|
||||
// the background of a block of code, the bar of a quotation.
|
||||
func (v *view) paintBlock(p *ui.Painter, i int, st ParagraphStyle, x, top, height, width float32) {
|
||||
look := &v.look
|
||||
indent := float32(st.Indent) * look.indent
|
||||
if st.CodeBlock {
|
||||
// One block for the paragraphs of code next to each other, rounded
|
||||
// at its ends.
|
||||
radius := look.size * look.CodeBlockRadius
|
||||
first := i == 0 || !v.para(i-1).style.CodeBlock
|
||||
last := i+1 >= len(v.paras) || !v.para(i+1).style.CodeBlock
|
||||
if first && v.opts.Space != nil {
|
||||
// The room an app leaves above the block, as a place opened
|
||||
// for an item dragged, is outside it.
|
||||
room := max(0, v.opts.Space(i))
|
||||
top, height = top+room, height-room
|
||||
}
|
||||
box := ui.Rect{X: x + indent, Y: top, W: width - indent, H: height}
|
||||
fill := box
|
||||
if !first {
|
||||
fill.Y, fill.H = fill.Y-2*radius, fill.H+2*radius
|
||||
}
|
||||
if !last {
|
||||
fill.H += 2 * radius
|
||||
}
|
||||
p.Clip(box, 0, func() { p.Fill(fill, look.CodeBlockBackground, radius) })
|
||||
}
|
||||
if st.Quote {
|
||||
if i == 0 || !v.para(i-1).style.Quote {
|
||||
// The spacing above the first paragraph of a quotation is
|
||||
// outside it. A heading that starts one keeps outside only
|
||||
// Space's room and the spacing a body paragraph would take
|
||||
// there, the rest of its room inside, so that the room
|
||||
// above the quotation matches the spacing below it.
|
||||
above, _ := v.space(i, st)
|
||||
if st.Heading > 0 {
|
||||
var room, gap float32
|
||||
if v.opts.Space != nil {
|
||||
room = max(0, v.opts.Space(i))
|
||||
}
|
||||
if look.ParagraphSpacing > 0 && i > 0 && body(v.para(i-1).style) {
|
||||
gap = look.size * look.ParagraphSpacing
|
||||
}
|
||||
above = room + min(above-room, gap)
|
||||
}
|
||||
top, height = top+above, height-above
|
||||
}
|
||||
// A bar is rounded only at the ends of its quotation: where the
|
||||
// paragraph above or below goes on at its level, the bars join
|
||||
// square, as one.
|
||||
w := look.QuoteBarWidth
|
||||
var above, below int
|
||||
if i > 0 {
|
||||
above = v.para(i - 1).style.quoteDepth()
|
||||
}
|
||||
if i+1 < len(v.paras) {
|
||||
below = v.para(i + 1).style.quoteDepth()
|
||||
}
|
||||
for level := range st.quoteDepth() {
|
||||
r := [4]float32{w / 2, w / 2, w / 2, w / 2}
|
||||
if above > level {
|
||||
r[0], r[1] = 0, 0
|
||||
}
|
||||
if below > level {
|
||||
r[2], r[3] = 0, 0
|
||||
}
|
||||
p.FillRadii(ui.Rect{X: x + indent + float32(level)*look.indent*0.75, Y: top, W: w, H: height}, r, look.QuoteBar)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// paintMarker paints the marker of an item of a list: its bullet, its
|
||||
// number, or its check box.
|
||||
func (v *view) paintMarker(p *ui.Painter, i int, st ParagraphStyle, pv *paraView, x, y float32) {
|
||||
if st.List == NoList {
|
||||
return
|
||||
}
|
||||
look := &v.look
|
||||
line := pv.layout.CaretAt(ui.TextCaretPosition{})
|
||||
font := v.paraFont(st)
|
||||
if st.List == Tasks {
|
||||
box := font.Size * 0.95
|
||||
bx := x - look.indent + (look.indent-box)/2 - look.indent*0.1
|
||||
by := y + line.Y + (line.H-box)/2
|
||||
if st.Checked {
|
||||
p.Fill(ui.Rect{X: bx, Y: by, W: box, H: box}, look.Checkbox, box*0.25)
|
||||
var path ui.Path
|
||||
path.MoveTo(bx+box*0.25, by+box*0.52).LineTo(bx+box*0.43, by+box*0.7).LineTo(bx+box*0.76, by+box*0.32)
|
||||
p.StrokePath(&path, max(1.5, box*0.12), look.Checkmark)
|
||||
} else {
|
||||
p.Stroke(ui.Rect{X: bx, Y: by, W: box, H: box}, look.Muted, box*0.25, 1.25)
|
||||
}
|
||||
return
|
||||
}
|
||||
mark := v.marker(i, st)
|
||||
if pv.markerLayout == nil || pv.marker != mark {
|
||||
pv.marker, pv.markerLayout = mark, ui.ShapeText(mark, font, 0)
|
||||
}
|
||||
ml := pv.markerLayout
|
||||
mw, _ := ml.Size()
|
||||
mx := x - mw - look.indent*0.25
|
||||
if st.List == Bullets {
|
||||
mx = x - look.indent*0.5 - mw/2
|
||||
}
|
||||
p.TextLayout(ml, mx, y+line.Y, look.Marker)
|
||||
}
|
||||
|
||||
// listNumber returns the number of the item of a numbered list that
|
||||
// paragraph p is: one more than the item of the same level before it, the
|
||||
// deeper ones between them skipped, from 1 for the first.
|
||||
func (v *view) listNumber(p int) int {
|
||||
if !v.numbersOf.Same(v.shown) {
|
||||
clear(v.numbers)
|
||||
v.numbersOf = v.shown
|
||||
}
|
||||
if v.numbers == nil {
|
||||
v.numbers = map[int]int{}
|
||||
}
|
||||
if n, ok := v.numbers[p]; ok {
|
||||
return n
|
||||
}
|
||||
st := v.para(p).style
|
||||
n := 1
|
||||
for q := p - 1; q >= 0; q-- {
|
||||
qs := v.para(q).style
|
||||
if qs.List == NoList || qs.Indent < st.Indent {
|
||||
break
|
||||
}
|
||||
if qs.Indent > st.Indent {
|
||||
continue
|
||||
}
|
||||
if qs.List == Numbers {
|
||||
n = v.listNumber(q) + 1
|
||||
}
|
||||
break
|
||||
}
|
||||
v.numbers[p] = n
|
||||
return n
|
||||
}
|
||||
|
||||
// marker returns what marks item p of a list: a bullet for its level, or
|
||||
// its number, in digits, letters or Roman numerals by level.
|
||||
func (v *view) marker(p int, st ParagraphStyle) string {
|
||||
switch st.List {
|
||||
case Bullets:
|
||||
return []string{"•", "◦", "▪"}[st.Indent%3]
|
||||
case Numbers:
|
||||
n := v.listNumber(p)
|
||||
switch st.Indent % 3 {
|
||||
case 1:
|
||||
return alphaNumber(n) + "."
|
||||
case 2:
|
||||
return romanNumber(n) + "."
|
||||
}
|
||||
return strconv.Itoa(n) + "."
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// alphaNumber returns n as letters: a, b, … z, aa.
|
||||
func alphaNumber(n int) string {
|
||||
var b []byte
|
||||
for ; n > 0; n = (n - 1) / 26 {
|
||||
b = append([]byte{byte('a' + (n-1)%26)}, b...)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// romanNumber returns n in lowercase Roman numerals.
|
||||
func romanNumber(n int) string {
|
||||
if n <= 0 || n >= 4000 {
|
||||
return strconv.Itoa(n)
|
||||
}
|
||||
vals := []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
|
||||
syms := []string{"m", "cm", "d", "cd", "c", "xc", "l", "xl", "x", "ix", "v", "iv", "i"}
|
||||
var b []byte
|
||||
for i, val := range vals {
|
||||
for n >= val {
|
||||
b = append(b, syms[i]...)
|
||||
n -= val
|
||||
}
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// paintAttachments draws the attachments of paragraph p in the boxes its
|
||||
// layout, at (x, y), keeps for them: an image, the app's drawing, or a
|
||||
// box with the attachment's name.
|
||||
func (v *view) paintAttachments(p *ui.Painter, i int, pv *paraView, x, y float32) {
|
||||
objects := pv.layout.Objects()
|
||||
if len(objects) == 0 {
|
||||
return
|
||||
}
|
||||
ps := v.shown.paraStart(i)
|
||||
for _, o := range objects {
|
||||
l := pv.runeOfUnit(o.Index)
|
||||
if v.compose != "" && v.shown.paraAt(v.caret) == i && l >= v.caret-ps && l < v.caret-ps+len([]rune(v.compose)) {
|
||||
continue
|
||||
}
|
||||
at := v.shown.AttributesAt(v.global(i, l)).Attachment
|
||||
r := ui.Rect{X: x + o.Rect.X, Y: y + o.Rect.Y, W: o.Rect.W, H: o.Rect.H}
|
||||
switch {
|
||||
case at == nil:
|
||||
case at.Draw != nil:
|
||||
at.Draw(p, r)
|
||||
case at.Image != nil:
|
||||
p.Image(at.Image, r, ui.Contain)
|
||||
default:
|
||||
// Not loaded: a box with its name.
|
||||
p.Fill(r, v.look.CodeBlockBackground, 4)
|
||||
p.Stroke(r, v.look.border, 4, 1)
|
||||
if at.Name != "" {
|
||||
l := ui.ShapeText(at.Name, ui.Font{Size: v.look.size * 0.85}, max(r.W-8, 1))
|
||||
_, lh := l.Size()
|
||||
p.Clip(r, 4, func() { p.TextLayout(l, r.X+4, r.Y+(r.H-lh)/2, v.look.Muted) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+775
@@ -0,0 +1,775 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/transfer"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// proseTester builds an EditorBase of doc, 10 DIPs an em in theme th,
|
||||
// filling a window 300 wide and h high, focused. Its view reads the
|
||||
// paragraphs in view as it builds, as an app's gutter does, into the
|
||||
// boxes returned.
|
||||
func proseTester(t *testing.T, doc *Document, th *Theme, h int) (*ui.Tester, *[]ParagraphBox) {
|
||||
t.Helper()
|
||||
boxes := new([]ParagraphBox)
|
||||
tt := openTester(t, func(c *ui.Context) {
|
||||
*boxes = doc.VisibleParagraphs()
|
||||
EditorBase(c, doc, EditorOptions{Font: ui.Font{Size: 10}, Theme: th}).Fill()
|
||||
}, 300, h)
|
||||
tt.Press(150, float32(h)-2)
|
||||
tt.Release(150, float32(h)-2)
|
||||
return tt, boxes
|
||||
}
|
||||
|
||||
// caretAt puts the caret at i and returns where the editor shows it.
|
||||
func caretAt(t *testing.T, tt *ui.Tester, doc *Document, i int) ui.Rect {
|
||||
t.Helper()
|
||||
doc.SetSelection(i, i)
|
||||
tt.Frame()
|
||||
r, ok := tt.TextCaret()
|
||||
if !ok {
|
||||
t.Fatal("no caret")
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// para returns a body paragraph of text s.
|
||||
func para(s string) Paragraph { return Paragraph{Runs: []Run{{Text: s}}} }
|
||||
|
||||
// starts returns the rune each paragraph of t starts at.
|
||||
func starts(t Text) []int {
|
||||
var out []int
|
||||
for start := range t.Paragraphs() {
|
||||
out = append(out, start)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TestFirstLineIndent checks which paragraphs Theme.FirstLineIndent
|
||||
// indents: a body paragraph after another, not the first after a
|
||||
// heading, a centered paragraph, an empty one, a list or the start of a
|
||||
// quotation, and that the caret shows where the text is painted.
|
||||
func TestFirstLineIndent(t *testing.T) {
|
||||
text := TextOf(
|
||||
Paragraph{Style: ParagraphStyle{Heading: 2}, Runs: []Run{{Text: "Title"}}},
|
||||
para("After the heading"), // 1
|
||||
para("Indented"), // 2
|
||||
Paragraph{Style: ParagraphStyle{Align: ui.Center}, Runs: []Run{{Text: "* * *"}}},
|
||||
para("After the break"), // 4
|
||||
para(""), // 5
|
||||
para("After an empty line"), // 6
|
||||
Paragraph{Style: ParagraphStyle{Quote: true}, Runs: []Run{{Text: "Quoted"}}}, // 7
|
||||
Paragraph{Style: ParagraphStyle{Quote: true}, Runs: []Run{{Text: "Quoted again"}}}, // 8
|
||||
Paragraph{Style: ParagraphStyle{List: Bullets}, Runs: []Run{{Text: "An item"}}}, // 9
|
||||
para("After the list"), // 10
|
||||
Paragraph{Style: ParagraphStyle{Align: ui.End}, Runs: []Run{{Text: "Signed"}}}, // 11
|
||||
para("Indented too?"), // 12
|
||||
para("Indented again"), // 13
|
||||
)
|
||||
indented := map[int]bool{2: true, 5: true, 8: true, 13: true}
|
||||
doc := NewDocument(text)
|
||||
tt, _ := proseTester(t, doc, &Theme{FirstLineIndent: 2}, 400)
|
||||
plain := NewDocument(text)
|
||||
pt, _ := proseTester(t, plain, nil, 400)
|
||||
for p, s := range starts(text) {
|
||||
if st := text.ParagraphStyleAt(s); st.Align != ui.Start || st.Heading > 0 {
|
||||
continue
|
||||
}
|
||||
got, want := caretAt(t, tt, doc, s), caretAt(t, pt, plain, s)
|
||||
if got.Y != want.Y || got.H != want.H {
|
||||
t.Errorf("paragraph %d: caret %+v, %+v without the indent: the indent changed its line", p, got, want)
|
||||
}
|
||||
shift := got.X - want.X
|
||||
switch {
|
||||
case indented[p] && shift != 20:
|
||||
t.Errorf("paragraph %d starts %v right of its unindented start, want 20", p, shift)
|
||||
case !indented[p] && shift != 0:
|
||||
t.Errorf("paragraph %d is indented by %v", p, shift)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFirstLineIndentEditing moves the caret, clicks and types around the
|
||||
// indent of a paragraph: the indent is no character.
|
||||
func TestFirstLineIndentEditing(t *testing.T) {
|
||||
long := strings.Repeat("word ", 30)
|
||||
doc := NewDocument(TextOf(para("One"), para(long), para("Three")))
|
||||
tt, _ := proseTester(t, doc, &Theme{FirstLineIndent: 2}, 400)
|
||||
start := 4
|
||||
first := caretAt(t, tt, doc, start)
|
||||
// The second line of the paragraph wraps back to the edge.
|
||||
tt.Key(0, ui.KeyDown)
|
||||
if _, c := doc.Selection(); c <= start {
|
||||
t.Fatalf("down from the start went to %d", c)
|
||||
}
|
||||
tt.Key(0, ui.KeyHome)
|
||||
second, _ := tt.TextCaret()
|
||||
if first.X-second.X != 20 || second.Y <= first.Y {
|
||||
t.Errorf("first line at %+v, second at %+v: want the first 20 right", first, second)
|
||||
}
|
||||
// Left at the start goes to the end of the paragraph before, and
|
||||
// right comes back.
|
||||
caretAt(t, tt, doc, start)
|
||||
tt.Key(0, ui.KeyLeft)
|
||||
if _, c := doc.Selection(); c != 3 {
|
||||
t.Fatalf("left from the start went to %d, want 3", c)
|
||||
}
|
||||
tt.Key(0, ui.KeyRight)
|
||||
if _, c := doc.Selection(); c != start {
|
||||
t.Fatalf("right went to %d, want %d", c, start)
|
||||
}
|
||||
tt.Key(0, ui.KeyRight)
|
||||
if _, c := doc.Selection(); c != start+1 {
|
||||
t.Fatalf("right went to %d, want %d", c, start+1)
|
||||
}
|
||||
// A click in the indent puts the caret at the start.
|
||||
tt.ClickAt(5, first.Y+first.H/2)
|
||||
if a, c := doc.Selection(); a != start || c != start {
|
||||
t.Fatalf("a click in the indent selected %d–%d, want %d", a, c, start)
|
||||
}
|
||||
// Selecting the line from its end to Home selects from the start.
|
||||
tt.ClickAt(first.X+3, first.Y+first.H/2)
|
||||
tt.Key(ui.Shift, ui.KeyHome)
|
||||
if a, c := doc.Selection(); min(a, c) != start {
|
||||
t.Fatalf("shift-home selected %d–%d, want from %d", a, c, start)
|
||||
}
|
||||
// Typing at the start goes before the paragraph's text, after the
|
||||
// indent.
|
||||
caretAt(t, tt, doc, start)
|
||||
tt.Type("A")
|
||||
if got := doc.Text().String(); !strings.HasPrefix(got, "One\nAword") {
|
||||
t.Fatalf("typed into %q", got)
|
||||
}
|
||||
if r, _ := tt.TextCaret(); r.X <= first.X {
|
||||
t.Errorf("caret at %v after typing, the start at %v", r.X, first.X)
|
||||
}
|
||||
// An input method composes after the indent, its caret in the
|
||||
// composition.
|
||||
caretAt(t, tt, doc, start)
|
||||
tt.Compose("ni", 2)
|
||||
if r, _ := tt.TextCaret(); r.X <= first.X || r.Y != first.Y {
|
||||
t.Errorf("composing, the caret at %+v, the start at %+v", r, first)
|
||||
}
|
||||
tt.Compose("", 0)
|
||||
tt.Type("你")
|
||||
if got := doc.Text().String(); !strings.HasPrefix(got, "One\n你Aword") {
|
||||
t.Fatalf("composed into %q", got)
|
||||
}
|
||||
// Backspace at the start joins the paragraphs, as without an indent.
|
||||
caretAt(t, tt, doc, start)
|
||||
tt.Key(0, ui.KeyBackspace)
|
||||
if got := doc.Text().String(); !strings.HasPrefix(got, "One你Aword") {
|
||||
t.Fatalf("backspace left %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFirstLineIndentAttachment checks that an attachment starting an
|
||||
// indented paragraph is drawn after the indent, not in it.
|
||||
func TestFirstLineIndentAttachment(t *testing.T) {
|
||||
var drawn []ui.Rect
|
||||
at := &Attachment{Width: 30, Height: 8, Draw: func(p *ui.Painter, r ui.Rect) { drawn = append(drawn, r) }}
|
||||
text := TextOf(para("One"), Paragraph{Runs: []Run{{Text: string(ObjectReplacement), Attributes: Attributes{Attachment: at}}, {Text: " two"}}})
|
||||
doc := NewDocument(text)
|
||||
tt, _ := proseTester(t, doc, &Theme{FirstLineIndent: 2}, 200)
|
||||
drawn = nil
|
||||
tt.Frame()
|
||||
tt.Advance(600 * time.Millisecond) // a blink, which paints again
|
||||
if len(drawn) == 0 {
|
||||
t.Fatal("the attachment was not drawn")
|
||||
}
|
||||
for _, r := range drawn {
|
||||
if r.X != 20 || r.W != 30 {
|
||||
t.Fatalf("attachment drawn at %+v, want at x 20, 30 wide", r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestParagraphSpacing checks that Theme.ParagraphSpacing goes between
|
||||
// body paragraphs only, and that the caret and the paragraphs' boxes
|
||||
// stay with the text painted.
|
||||
func TestParagraphSpacing(t *testing.T) {
|
||||
text := TextOf(
|
||||
para("One"),
|
||||
para("Two"), // spaced
|
||||
Paragraph{Style: ParagraphStyle{Heading: 2}, Runs: []Run{{Text: "Heading"}}},
|
||||
para("Three"),
|
||||
Paragraph{Style: ParagraphStyle{List: Bullets}, Runs: []Run{{Text: "Item"}}},
|
||||
Paragraph{Style: ParagraphStyle{List: Bullets}, Runs: []Run{{Text: "Item"}}},
|
||||
para("Four"),
|
||||
Paragraph{Style: ParagraphStyle{Align: ui.Center}, Runs: []Run{{Text: "* * *"}}}, // spaced
|
||||
Paragraph{Style: ParagraphStyle{Quote: true}, Runs: []Run{{Text: "Quoted"}}}, // spaced
|
||||
Paragraph{Style: ParagraphStyle{CodeBlock: true}, Runs: []Run{{Text: "code"}}},
|
||||
para("Five"),
|
||||
)
|
||||
spaced := map[int]bool{1: true, 7: true, 8: true}
|
||||
doc := NewDocument(text)
|
||||
tt, boxes := proseTester(t, doc, &Theme{ParagraphSpacing: 1}, 400)
|
||||
plain := NewDocument(text)
|
||||
_, plainBoxes := proseTester(t, plain, nil, 400)
|
||||
if len(*boxes) != len(starts(text)) || len(*plainBoxes) != len(*boxes) {
|
||||
t.Fatalf("%d and %d paragraphs in view, want %d", len(*boxes), len(*plainBoxes), len(starts(text)))
|
||||
}
|
||||
added := float32(0)
|
||||
for p, b := range *boxes {
|
||||
pb := (*plainBoxes)[p]
|
||||
if spaced[p] {
|
||||
added += 10
|
||||
}
|
||||
if math.Abs(float64(b.Top-pb.Top-added)) > 0.01 || b.Height != pb.Height {
|
||||
t.Errorf("paragraph %d at %v, %v high, and %v, %v high without spacing: want %v lower", p, b.Top, b.Height, pb.Top, pb.Height, added)
|
||||
}
|
||||
if c := caretAt(t, tt, doc, b.Start); c.Y != b.Top {
|
||||
t.Errorf("paragraph %d: caret at %v, its box at %v", p, c.Y, b.Top)
|
||||
}
|
||||
}
|
||||
// A click in the space above a paragraph goes into it.
|
||||
two := (*boxes)[1]
|
||||
tt.ClickAt(100, two.Top-4)
|
||||
if _, c := doc.Selection(); c < two.Start || c > two.Start+3 {
|
||||
t.Errorf("a click above the second paragraph put the caret at %d", c)
|
||||
}
|
||||
}
|
||||
|
||||
// TestParagraphSpacingQuoteBar checks that the bar of a quotation starts
|
||||
// at its text, below the spacing above it.
|
||||
func TestParagraphSpacingQuoteBar(t *testing.T) {
|
||||
bar := ui.RGB(255, 0, 0)
|
||||
text := TextOf(para("One"),
|
||||
Paragraph{Style: ParagraphStyle{Quote: true}, Runs: []Run{{Text: "Quoted"}}},
|
||||
Paragraph{Style: ParagraphStyle{Quote: true}, Runs: []Run{{Text: "Quoted again"}}})
|
||||
doc := NewDocument(text)
|
||||
tt, boxes := proseTester(t, doc, &Theme{ParagraphSpacing: 2, QuoteBar: bar, QuoteBarWidth: 4}, 200)
|
||||
img := tt.Image()
|
||||
red := func(y float32) bool {
|
||||
c := img.RGBAAt(2, int(y))
|
||||
return c.R > 200 && c.G < 50 && c.B < 50
|
||||
}
|
||||
q1, q2 := (*boxes)[1], (*boxes)[2]
|
||||
if red(q1.Top - 10) {
|
||||
t.Error("the quotation's bar goes up into the spacing above it")
|
||||
}
|
||||
if !red(q1.Top+q1.Height/2) || !red(q2.Top-10) || !red(q2.Top+q2.Height/2) {
|
||||
t.Error("the quotation's bar is not along its paragraphs and the spacing between them")
|
||||
}
|
||||
}
|
||||
|
||||
// TestVisibleParagraphs checks that the paragraphs in view, as an app's
|
||||
// view reads them while it builds, are where the editor paints them, as
|
||||
// it scrolls, edits and resizes.
|
||||
func TestVisibleParagraphs(t *testing.T) {
|
||||
paras := make([]Paragraph, 200)
|
||||
for i := range paras {
|
||||
paras[i] = para(fmt.Sprintf("Paragraph %d, long enough to wrap in a window this narrow at times.", i))
|
||||
}
|
||||
doc := NewDocument(TextOf(paras...))
|
||||
tt, boxes := proseTester(t, doc, &Theme{ParagraphSpacing: 0.5, FirstLineIndent: 1.5}, 400)
|
||||
doc.SetSelection(0, 0)
|
||||
tt.Frame()
|
||||
painted := func() []ParagraphBox {
|
||||
t.Helper()
|
||||
v := doc.shownIn.Value()
|
||||
if v == nil {
|
||||
t.Fatal("no editor shows the document")
|
||||
}
|
||||
return v.boxes(nil)
|
||||
}
|
||||
height := float32(400)
|
||||
check := func(what string) {
|
||||
t.Helper()
|
||||
got, want := *boxes, painted()
|
||||
if len(got) == 0 || !slices.Equal(got, want) {
|
||||
t.Fatalf("%s: the view read %v, the editor painted %v", what, got, want)
|
||||
}
|
||||
// The first box may start below the top by the spacing above it.
|
||||
if got[0].Top > 5 || got[len(got)-1].Top+got[len(got)-1].Height < height {
|
||||
t.Fatalf("%s: %v does not cover the view", what, got)
|
||||
}
|
||||
text := doc.Text()
|
||||
for k, b := range got {
|
||||
if s, _ := text.ParagraphRange(b.Start); s != b.Start || text.paraAt(b.Start) != b.Index {
|
||||
t.Fatalf("%s: box %+v starts no paragraph", what, b)
|
||||
}
|
||||
if k > 0 && (b.Index != got[k-1].Index+1 || b.Top < got[k-1].Top+got[k-1].Height) {
|
||||
t.Fatalf("%s: boxes %+v and %+v out of order", what, got[k-1], b)
|
||||
}
|
||||
}
|
||||
}
|
||||
check("first frame")
|
||||
if (*boxes)[0].Index != 0 || (*boxes)[0].Top != 0 {
|
||||
t.Fatalf("the first box %+v, want paragraph 0 at the top", (*boxes)[0])
|
||||
}
|
||||
// The caret's line is at the box's top.
|
||||
if c := caretAt(t, tt, doc, (*boxes)[2].Start); c.Y != (*boxes)[2].Top {
|
||||
t.Errorf("caret at %v, its paragraph's box at %v", c.Y, (*boxes)[2].Top)
|
||||
}
|
||||
before := slices.Clone(*boxes)
|
||||
tt.Scroll(150, 200, 0, 1000)
|
||||
check("scrolled")
|
||||
if (*boxes)[0].Index == before[0].Index {
|
||||
t.Fatalf("scrolled, the first paragraph in view is still %d", before[0].Index)
|
||||
}
|
||||
// The app moves the caret far down: the editor reveals it as it lays
|
||||
// out, and the view reads where.
|
||||
end := doc.Text().Len()
|
||||
doc.SetSelection(end, end)
|
||||
tt.Frame()
|
||||
check("revealed")
|
||||
if last := (*boxes)[len(*boxes)-1]; last.Index != 199 {
|
||||
t.Fatalf("revealing the end, the last paragraph in view is %d", last.Index)
|
||||
}
|
||||
// An edit above, in the editor that has the keyboard, keeps the
|
||||
// caret's line where it is: the paragraphs from the edit's down to the
|
||||
// caret's stay, and those above them move up.
|
||||
first := (*boxes)[1]
|
||||
doc.Edit(func(e *Edit) { e.ReplaceString(first.Start, first.Start, "New\n", Attributes{}) })
|
||||
tt.Frame()
|
||||
check("edited")
|
||||
moved := slices.IndexFunc(*boxes, func(b ParagraphBox) bool { return b.Start == first.Start+4 })
|
||||
if moved < 0 || math.Abs(float64((*boxes)[moved].Top-first.Top)) > 0.01 {
|
||||
t.Fatalf("after a paragraph inserted at %d at %v, boxes %v", first.Start, first.Top, (*boxes)[:3])
|
||||
}
|
||||
if moved > 0 && (*boxes)[moved-1].Start != first.Start {
|
||||
t.Fatalf("after a paragraph inserted at %d, the box above the paragraph it moved is %+v", first.Start, (*boxes)[moved-1])
|
||||
}
|
||||
// Another width wraps the paragraphs otherwise: the frame that paints
|
||||
// them builds another, for the view to follow.
|
||||
tt.SetSize(200, 400)
|
||||
check("narrower")
|
||||
height = 250
|
||||
tt.SetSize(300, 250)
|
||||
check("shorter")
|
||||
}
|
||||
|
||||
// TestVisibleParagraphsBeforeEditor checks the first frames: the view
|
||||
// reads nothing before the editor showed the document, then the
|
||||
// paragraphs in view, with no help from the app.
|
||||
func TestVisibleParagraphsBeforeEditor(t *testing.T) {
|
||||
doc := NewDocument(TextOf(para("One"), para("Two")))
|
||||
if b := doc.VisibleParagraphs(); b != nil {
|
||||
t.Fatalf("no editor yet, and %v", b)
|
||||
}
|
||||
var reads [][]ParagraphBox
|
||||
tt := ui.NewTester(func(c *ui.Context) {
|
||||
reads = append(reads, doc.VisibleParagraphs())
|
||||
EditorBase(c, doc, EditorOptions{Font: ui.Font{Size: 10}}).Fill()
|
||||
}, 300, 200)
|
||||
if len(reads) < 2 || reads[0] != nil {
|
||||
t.Fatalf("reads %v, want nil then the paragraphs", reads)
|
||||
}
|
||||
if got := reads[len(reads)-1]; len(got) != 2 || got[0].Top != 0 || got[1].Top != got[0].Height {
|
||||
t.Fatalf("read %v", got)
|
||||
}
|
||||
// Frames that change nothing ask for none more.
|
||||
n := len(reads)
|
||||
tt.Frame()
|
||||
if len(reads) != n+1 || tt.FramePending() {
|
||||
t.Fatalf("%d frames for one", len(reads)-n)
|
||||
}
|
||||
}
|
||||
|
||||
// ids returns the IDs of the paragraphs of t.
|
||||
func ids(t Text) []string {
|
||||
var out []string
|
||||
for _, p := range t.Paragraphs() {
|
||||
out = append(out, p.Style.ID)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TestParagraphIDEdits checks where IDs go as paragraphs are split and
|
||||
// joined, by the editor's keys, and that undo and redo bring them back.
|
||||
func TestParagraphIDEdits(t *testing.T) {
|
||||
text := TextOf(
|
||||
Paragraph{Style: ParagraphStyle{ID: "a"}, Runs: []Run{{Text: "alpha"}}},
|
||||
Paragraph{Style: ParagraphStyle{ID: "b"}, Runs: []Run{{Text: "beta"}}},
|
||||
Paragraph{Style: ParagraphStyle{ID: "c", Heading: 2}, Runs: []Run{{Text: "gamma"}}},
|
||||
)
|
||||
steps := []struct {
|
||||
what string
|
||||
caret int
|
||||
key ui.Key
|
||||
text string
|
||||
ids []string
|
||||
strung string
|
||||
}{
|
||||
{"Enter in the middle", 2, ui.KeyEnter, "", []string{"a", "", "b", "c"}, "al\npha\nbeta\ngamma"},
|
||||
{"Enter at the start", 7, ui.KeyEnter, "", []string{"a", "", "", "b", "c"}, "al\npha\n\nbeta\ngamma"},
|
||||
{"Enter at the end", 13, ui.KeyEnter, "", []string{"a", "", "", "b", "", "c"}, "al\npha\n\nbeta\n\ngamma"},
|
||||
{"Backspace joining", 3, ui.KeyBackspace, "", []string{"a", "", "b", "", "c"}, "alpha\n\nbeta\n\ngamma"},
|
||||
{"Backspace after an empty paragraph", 7, ui.KeyBackspace, "", []string{"a", "b", "", "c"}, "alpha\nbeta\n\ngamma"},
|
||||
{"Delete joining", 10, ui.KeyDelete, "", []string{"a", "b", "c"}, "alpha\nbeta\ngamma"},
|
||||
}
|
||||
doc := NewDocument(text)
|
||||
tt, _ := richTester(t, doc)
|
||||
var versions []Text
|
||||
for _, s := range steps {
|
||||
versions = append(versions, doc.Text())
|
||||
doc.SetSelection(s.caret, s.caret)
|
||||
tt.Frame()
|
||||
tt.Key(0, s.key)
|
||||
if got := doc.Text().String(); got != s.strung {
|
||||
t.Fatalf("%s: text %q, want %q", s.what, got, s.strung)
|
||||
}
|
||||
if got := ids(doc.Text()); !slices.Equal(got, s.ids) {
|
||||
t.Fatalf("%s: IDs %q, want %q", s.what, got, s.ids)
|
||||
}
|
||||
}
|
||||
for k := len(steps) - 1; k >= 0; k-- {
|
||||
tt.Key(ui.Cmd, ui.KeyZ)
|
||||
if !doc.Text().Equal(versions[k]) {
|
||||
t.Fatalf("undoing %s: IDs %q, want %q", steps[k].what, ids(doc.Text()), ids(versions[k]))
|
||||
}
|
||||
}
|
||||
for _, s := range steps {
|
||||
tt.Key(ui.Cmd|ui.Shift, ui.KeyZ)
|
||||
if got := ids(doc.Text()); !slices.Equal(got, s.ids) {
|
||||
t.Fatalf("redoing %s: IDs %q, want %q", s.what, got, s.ids)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestParagraphIDText checks IDs in texts: a newline in a run, a
|
||||
// replacement whose text has IDs, JSON, formats and the clipboard.
|
||||
func TestParagraphIDText(t *testing.T) {
|
||||
text := TextOf(
|
||||
Paragraph{Style: ParagraphStyle{ID: "a"}, Runs: []Run{{Text: "one\ntwo"}}},
|
||||
Paragraph{Style: ParagraphStyle{ID: "b"}, Runs: []Run{{Text: "three"}}},
|
||||
)
|
||||
if got := ids(text); !slices.Equal(got, []string{"a", "", "b"}) {
|
||||
t.Fatalf("TextOf made IDs %q", got)
|
||||
}
|
||||
// Text inserted, IDs and all, brings none.
|
||||
in := text.Replace(4, 4, text.Slice(0, text.Len()))
|
||||
if got := ids(in); !slices.Equal(got, []string{"a", "", "", "", "b"}) {
|
||||
t.Fatalf("inserting a copy made IDs %q", got)
|
||||
}
|
||||
// JSON keeps them.
|
||||
b, err := json.Marshal(text)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var back Text
|
||||
if err := json.Unmarshal(b, &back); err != nil || !back.Equal(text) {
|
||||
t.Fatalf("JSON %s read back as %q", b, ids(back))
|
||||
}
|
||||
// The clipboard does not, in its format or in HTML.
|
||||
clip := clipboardData(text)
|
||||
for _, f := range []transfer.Format{Format, transfer.HTML} {
|
||||
if data, _ := clip.Read(f); strings.Contains(string(data), `"a"`) || strings.Contains(string(data), `id=`) {
|
||||
t.Errorf("the clipboard's %s holds the IDs: %s", f, data)
|
||||
}
|
||||
}
|
||||
// Paragraphs alike but for their IDs are no mix of styles.
|
||||
doc := NewDocument(text)
|
||||
doc.SetSelection(0, text.Len())
|
||||
if f := doc.Formatting(); f.ParagraphsMixed || f.Paragraph.ID != "a" {
|
||||
t.Errorf("formatting %+v", f)
|
||||
}
|
||||
}
|
||||
|
||||
// TestParagraphIDCopyPaste copies paragraphs with IDs and pastes them:
|
||||
// the copies have none, and the paragraphs copied keep theirs.
|
||||
func TestParagraphIDCopyPaste(t *testing.T) {
|
||||
doc := NewDocument(TextOf(
|
||||
Paragraph{Style: ParagraphStyle{ID: "a"}, Runs: []Run{{Text: "one"}}},
|
||||
Paragraph{Style: ParagraphStyle{ID: "b"}, Runs: []Run{{Text: "two"}}},
|
||||
))
|
||||
tt, _ := richTester(t, doc)
|
||||
doc.SetSelection(0, 7)
|
||||
tt.Frame()
|
||||
tt.Key(ui.Cmd, ui.KeyC)
|
||||
end := doc.Text().Len()
|
||||
doc.SetSelection(end, end)
|
||||
tt.Frame()
|
||||
tt.Key(0, ui.KeyEnter)
|
||||
tt.Key(ui.Cmd, ui.KeyV)
|
||||
if got := doc.Text().String(); got != "one\ntwo\none\ntwo" {
|
||||
t.Fatalf("pasted into %q", got)
|
||||
}
|
||||
if got := ids(doc.Text()); !slices.Equal(got, []string{"a", "b", "", ""}) {
|
||||
t.Fatalf("IDs %q after the paste", got)
|
||||
}
|
||||
// Cut and paste back: the text pasted is new.
|
||||
doc.SetSelection(0, 4)
|
||||
tt.Frame()
|
||||
tt.Key(ui.Cmd, ui.KeyX)
|
||||
tt.Key(ui.Cmd, ui.KeyV)
|
||||
if got := ids(doc.Text()); got[0] != "" || !slices.Contains(got, "b") {
|
||||
t.Fatalf("IDs %q after cutting and pasting", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIdentifyParagraphs checks that a document naming paragraphs names
|
||||
// those it has and those edits make, as part of their steps of undo.
|
||||
func TestIdentifyParagraphs(t *testing.T) {
|
||||
doc := NewDocument(TextOf(Paragraph{Style: ParagraphStyle{ID: "keep"}, Runs: []Run{{Text: "one"}}}, para("two")))
|
||||
n := 0
|
||||
doc.IdentifyParagraphs(func() string { n++; return fmt.Sprint("n", n) })
|
||||
if got := ids(doc.Text()); !slices.Equal(got, []string{"keep", "n1"}) {
|
||||
t.Fatalf("IDs %q", got)
|
||||
}
|
||||
tt, _ := richTester(t, doc)
|
||||
doc.SetSelection(1, 1)
|
||||
tt.Frame()
|
||||
tt.Key(0, ui.KeyEnter)
|
||||
after := ids(doc.Text())
|
||||
if !slices.Equal(after, []string{"keep", "n2", "n1"}) {
|
||||
t.Fatalf("IDs %q after Enter", after)
|
||||
}
|
||||
tt.Key(ui.Cmd, ui.KeyZ)
|
||||
if got := ids(doc.Text()); !slices.Equal(got, []string{"keep", "n1"}) {
|
||||
t.Fatalf("IDs %q after undo", got)
|
||||
}
|
||||
doc.Redo()
|
||||
if got := ids(doc.Text()); !slices.Equal(got, after) {
|
||||
t.Fatalf("IDs %q after redo, want %q", got, after)
|
||||
}
|
||||
// Pasted paragraphs get new IDs, and a paragraph whose ID the app
|
||||
// takes away gets one too.
|
||||
doc.SetSelection(0, 0)
|
||||
doc.Insert(TextOf(Paragraph{Style: ParagraphStyle{ID: "keep"}, Runs: []Run{{Text: "x\ny\n"}}}))
|
||||
doc.Edit(func(e *Edit) { e.FormatParagraphs(0, 0, func(p *ParagraphStyle) { p.ID = "" }) })
|
||||
got := ids(doc.Text())
|
||||
seen := map[string]bool{}
|
||||
for _, id := range got {
|
||||
if id == "" || seen[id] {
|
||||
t.Fatalf("IDs %q: one missing or twice", got)
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
doc.SetText(TextOf(para("new"), para("text")))
|
||||
if got := ids(doc.Text()); slices.Contains(got, "") {
|
||||
t.Fatalf("IDs %q of a text set", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVisibleParagraphsGutter lines up a gutter beside an Editor, as the
|
||||
// guide shows it: its marks are at the paragraphs' first lines, padding
|
||||
// and scrolling included.
|
||||
func TestVisibleParagraphsGutter(t *testing.T) {
|
||||
paras := make([]Paragraph, 60)
|
||||
for i := range paras {
|
||||
paras[i] = para(fmt.Sprintf("Paragraph %d", i))
|
||||
}
|
||||
doc := NewDocument(TextOf(paras...))
|
||||
var boxes []ParagraphBox
|
||||
var marks []ui.Rect
|
||||
tt := ui.NewTester(func(c *ui.Context) {
|
||||
boxes = doc.VisibleParagraphs()
|
||||
ui.Row(c).Fill().AlignItems(ui.Stretch).Children(func() {
|
||||
ui.Box(c).Width(40).Clip().Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
marks = marks[:0]
|
||||
for _, b := range boxes {
|
||||
mark := ui.Rect{X: r.X + 16, Y: r.Y + b.Top, W: 8, H: b.Height}
|
||||
marks = append(marks, mark)
|
||||
p.Fill(mark, ui.RGB(0, 0, 0), 2)
|
||||
}
|
||||
})
|
||||
Editor(c, doc, EditorOptions{Theme: &Theme{ParagraphSpacing: 1}}).Grow(1)
|
||||
})
|
||||
}, 400, 300)
|
||||
tt.ClickAt(200, 150)
|
||||
for _, scroll := range []float32{0, 230} {
|
||||
tt.Scroll(200, 150, 0, scroll)
|
||||
if len(marks) < 3 || len(marks) != len(boxes) {
|
||||
t.Fatalf("scrolled %v: marks %v of boxes %v", scroll, marks, boxes)
|
||||
}
|
||||
// Paragraphs whole in view, so that the caret does not scroll.
|
||||
for k := 1; k < 3; k++ {
|
||||
b, m := boxes[k], marks[k]
|
||||
doc.SetSelection(b.Start, b.Start)
|
||||
tt.Frame()
|
||||
if r, _ := tt.TextCaret(); r.Y != m.Y || marks[k] != m {
|
||||
t.Errorf("scrolled %v: paragraph %d's caret at %v, its mark at %v", scroll, b.Index, r.Y, m.Y)
|
||||
}
|
||||
}
|
||||
}
|
||||
if boxes[0].Index == 0 {
|
||||
t.Error("the editor did not scroll")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCaretRect checks that the caret, as an app's view reads it while it
|
||||
// builds to place a popup under it, is where the editor paints it and
|
||||
// tells the input method, as the user types, the app moves it, the editor
|
||||
// scrolls and its width changes, with no frames more than those.
|
||||
func TestCaretRect(t *testing.T) {
|
||||
paras := make([]Paragraph, 60)
|
||||
for i := range paras {
|
||||
paras[i] = para(fmt.Sprintf("Paragraph %d, long enough to wrap in a window this narrow.", i))
|
||||
}
|
||||
doc := NewDocument(TextOf(paras...))
|
||||
if _, ok := doc.CaretRect(); ok {
|
||||
t.Fatal("no editor shows the document, and a caret")
|
||||
}
|
||||
var read ui.Rect
|
||||
var readOK bool
|
||||
builds := 0
|
||||
tt := ui.NewTester(func(c *ui.Context) {
|
||||
builds++
|
||||
read, readOK = doc.CaretRect()
|
||||
EditorBase(c, doc, EditorOptions{Font: ui.Font{Size: 10}}).Fill()
|
||||
}, 300, 200)
|
||||
// The first frame reads nothing, before the editor showed the
|
||||
// document; the next, with no help from the app, the caret.
|
||||
if !readOK || builds < 2 {
|
||||
t.Fatalf("after %d frames the view read %v %v", builds, read, readOK)
|
||||
}
|
||||
tt.Press(150, 5)
|
||||
tt.Release(150, 5)
|
||||
check := func(what string, inView bool) {
|
||||
t.Helper()
|
||||
v := doc.shownIn.Value()
|
||||
if v == nil {
|
||||
t.Fatalf("%s: no editor shows the document", what)
|
||||
}
|
||||
want, wantOK := v.caretRect()
|
||||
if read != want || readOK != wantOK || readOK != inView {
|
||||
t.Fatalf("%s: the view read %v %v, the editor paints %v %v, want in view %v", what, read, readOK, want, wantOK, inView)
|
||||
}
|
||||
if !inView {
|
||||
return
|
||||
}
|
||||
if c, ok := tt.TextCaret(); !ok || c.X != read.X || c.Y != read.Y || c.H != read.H {
|
||||
t.Fatalf("%s: the view read %v, the input method has %v %v", what, read, c, ok)
|
||||
}
|
||||
}
|
||||
check("focused", true)
|
||||
// The view reads where the app put the caret in the frame that shows
|
||||
// it, not a frame late.
|
||||
moveTo := func(what string, i int) {
|
||||
t.Helper()
|
||||
n := builds
|
||||
doc.SetSelection(i, i)
|
||||
tt.Frame()
|
||||
check(what, true)
|
||||
if builds != n+1 {
|
||||
t.Fatalf("%s: %d frames for one", what, builds-n)
|
||||
}
|
||||
}
|
||||
moveTo("moved by the app", 0)
|
||||
start := read
|
||||
tt.Type("abc")
|
||||
check("typed", true)
|
||||
if read.X <= start.X || read.Y != start.Y {
|
||||
t.Fatalf("typed from %v, the caret read at %v", start, read)
|
||||
}
|
||||
// The end is far below: the editor scrolls to reveal it, and the view
|
||||
// reads where.
|
||||
moveTo("revealed", doc.Text().Len())
|
||||
if read.Y < 100 {
|
||||
t.Fatalf("at the end, the caret read at %v", read)
|
||||
}
|
||||
tt.Scroll(150, 100, 0, -100000)
|
||||
check("scrolled out of view", false)
|
||||
moveTo("moved back into view", 40)
|
||||
tt.SetSize(160, 200)
|
||||
check("narrower", true)
|
||||
// Frames that change nothing ask for none more.
|
||||
n := builds
|
||||
tt.Frame()
|
||||
if builds != n+1 || tt.FramePending() {
|
||||
t.Fatalf("%d frames for one", builds-n)
|
||||
}
|
||||
}
|
||||
|
||||
// The room Space leaves above a block of code is outside the block: its
|
||||
// background starts below it, and fills the block from there.
|
||||
func TestCodeBlockSpaceOutside(t *testing.T) {
|
||||
doc := NewDocument(TextOf(
|
||||
para("Before"),
|
||||
Paragraph{Style: ParagraphStyle{CodeBlock: true}, Runs: []Run{{Text: "code"}}},
|
||||
para("After"),
|
||||
))
|
||||
red := ui.RGB(255, 0, 0)
|
||||
boxes := new([]ParagraphBox)
|
||||
tt := openTester(t, func(c *ui.Context) {
|
||||
*boxes = doc.VisibleParagraphs()
|
||||
EditorBase(c, doc, EditorOptions{Font: ui.Font{Size: 10}, Theme: &Theme{CodeBlockBackground: red},
|
||||
Space: func(p int) float32 { return map[int]float32{1: 40}[p] }}).Fill()
|
||||
}, 300, 200)
|
||||
tt.Frame()
|
||||
if len(*boxes) != 3 {
|
||||
t.Fatalf("%d paragraphs in view, want 3", len(*boxes))
|
||||
}
|
||||
code := (*boxes)[1]
|
||||
img := tt.Image()
|
||||
s := float32(img.Bounds().Dx()) / 300
|
||||
isRed := func(y float32) bool {
|
||||
c := img.RGBAAt(int(250*s), int(y*s))
|
||||
return c.R > 200 && c.G < 60 && c.B < 60
|
||||
}
|
||||
// The block's padding above its line is 0.5 em: 5 DIPs.
|
||||
if room := code.Top - 5 - 20; isRed(room) {
|
||||
t.Errorf("the room above the block, at %v, has the block's background", room)
|
||||
}
|
||||
if line := code.Top + code.Height/2; !isRed(line) {
|
||||
t.Errorf("the block's line, at %v, has no background", line)
|
||||
}
|
||||
}
|
||||
|
||||
// A quotation that starts with a heading is as far from the paragraph
|
||||
// before it as from the paragraph after it: the heading's room beyond the
|
||||
// spacing between body paragraphs is inside the quotation's bar.
|
||||
func TestQuotationHeadingRoomInside(t *testing.T) {
|
||||
doc := NewDocument(TextOf(
|
||||
para("Before"),
|
||||
Paragraph{Style: ParagraphStyle{Quote: true, Heading: 1}, Runs: []Run{{Text: "Title"}}},
|
||||
Paragraph{Style: ParagraphStyle{Quote: true}, Runs: []Run{{Text: "Quoted"}}},
|
||||
para("After"),
|
||||
))
|
||||
red := ui.RGB(255, 0, 0)
|
||||
boxes := new([]ParagraphBox)
|
||||
tt := openTester(t, func(c *ui.Context) {
|
||||
*boxes = doc.VisibleParagraphs()
|
||||
// The spacing is 5 DIPs; the heading's room, 0.6 of its 18, is 10.8.
|
||||
EditorBase(c, doc, EditorOptions{Font: ui.Font{Size: 10},
|
||||
Theme: &Theme{QuoteBar: red, QuoteBarWidth: 4, ParagraphSpacing: 0.5}}).Fill()
|
||||
}, 300, 200)
|
||||
tt.Frame()
|
||||
if len(*boxes) != 4 {
|
||||
t.Fatalf("%d paragraphs in view, want 4", len(*boxes))
|
||||
}
|
||||
before, quoted, after := (*boxes)[0], (*boxes)[2], (*boxes)[3]
|
||||
img := tt.Image()
|
||||
s := float32(img.Bounds().Dx()) / 300
|
||||
isRed := func(x, y int) bool {
|
||||
c := img.RGBAAt(x, y)
|
||||
return c.R > 200 && c.G < 60 && c.B < 60
|
||||
}
|
||||
// The bar's middle, on the quoted line.
|
||||
row := int((quoted.Top + quoted.Height/2) * s)
|
||||
first, last := -1, -1
|
||||
for x := 0; x < img.Bounds().Dx()/2; x++ {
|
||||
if isRed(x, row) {
|
||||
if first < 0 {
|
||||
first = x
|
||||
}
|
||||
last = x
|
||||
}
|
||||
}
|
||||
if first < 0 {
|
||||
t.Fatal("no bar beside the quoted line")
|
||||
}
|
||||
x := (first + last) / 2
|
||||
top, bottom := row, row
|
||||
for top > 0 && isRed(x, top-1) {
|
||||
top--
|
||||
}
|
||||
for bottom+1 < img.Bounds().Dy() && isRed(x, bottom+1) {
|
||||
bottom++
|
||||
}
|
||||
above := float32(top)/s - (before.Top + before.Height)
|
||||
below := after.Top - float32(bottom+1)/s
|
||||
if d := above - below; d > 1 || d < -1 {
|
||||
t.Errorf("the bar is %v DIPs under the paragraph before and %v over the paragraph after, want them equal", above, below)
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"encoding/json/v2"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
func TestNestedQuoteListKeepsBothDepths(t *testing.T) {
|
||||
const src = `<blockquote><blockquote><ul><li>first<ul><li>second</li></ul></li></ul><blockquote><p>third</p></blockquote></blockquote></blockquote>`
|
||||
text := ParseHTML(src)
|
||||
assert := func(t *testing.T, text Text) {
|
||||
t.Helper()
|
||||
wantQuotes := []int{2, 2, 3}
|
||||
wantLists := []int{0, 1, 0}
|
||||
i := 0
|
||||
for _, p := range text.Paragraphs() {
|
||||
if i >= len(wantQuotes) {
|
||||
t.Fatal("extra paragraph")
|
||||
}
|
||||
if p.Style.quoteDepth() != wantQuotes[i] || p.Style.Indent != wantLists[i] {
|
||||
t.Errorf("paragraph %d: %+v", i, p.Style)
|
||||
}
|
||||
i++
|
||||
}
|
||||
if i != 3 {
|
||||
t.Fatalf("paragraphs=%d", i)
|
||||
}
|
||||
}
|
||||
assert(t, text)
|
||||
assert(t, ParseHTML(text.HTML()))
|
||||
assert(t, ParseMarkdown(text.Markdown()))
|
||||
data, err := json.Marshal(text)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var decoded Text
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assert(t, decoded)
|
||||
}
|
||||
|
||||
func TestQuoteDepthSurvivesSplitJoinAndUndo(t *testing.T) {
|
||||
for _, at := range []int{0, 2, 4} {
|
||||
t.Run(string(rune('0'+at)), func(t *testing.T) {
|
||||
d := NewDocument(TextOf(Paragraph{Style: ParagraphStyle{Quote: true, QuoteDepth: 3, List: Bullets, Indent: 1}, Runs: []Run{{Text: "abcd"}}}))
|
||||
d.SetSelection(at, at)
|
||||
d.InsertText("\n")
|
||||
for _, p := range d.Text().Paragraphs() {
|
||||
if p.Style.quoteDepth() != 3 || p.Style.Indent != 1 || p.Style.List != Bullets {
|
||||
t.Fatalf("split style=%+v", p.Style)
|
||||
}
|
||||
}
|
||||
d.Undo()
|
||||
if got := d.Text().String(); got != "abcd" {
|
||||
t.Fatalf("undo=%q", got)
|
||||
}
|
||||
d.Redo()
|
||||
d.SetSelection(at, at+1)
|
||||
d.InsertText("")
|
||||
if d.Text().ParagraphCount() != 1 || d.Text().ParagraphStyleAt(0).quoteDepth() != 3 {
|
||||
t.Fatal("join lost quote depth")
|
||||
}
|
||||
d.ToggleList(Numbers)
|
||||
if d.Text().ParagraphStyleAt(0).quoteDepth() != 3 {
|
||||
t.Fatal("list formatting changed quote depth")
|
||||
}
|
||||
d.ToggleQuote()
|
||||
if p := d.Text().ParagraphStyleAt(0); p.Quote || p.QuoteDepth != 0 {
|
||||
t.Fatalf("quote off=%+v", p)
|
||||
}
|
||||
d.Undo()
|
||||
if d.Text().ParagraphStyleAt(0).quoteDepth() != 3 {
|
||||
t.Fatal("undo lost quote depth")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuoteDepthIsIndependentOfListIndentInLayout(t *testing.T) {
|
||||
v := &view{}
|
||||
v.look.indent = 20
|
||||
shallow := ParagraphStyle{Quote: true, List: Bullets, Indent: 2}
|
||||
deep := shallow
|
||||
deep.QuoteDepth = 3
|
||||
a, _ := v.insets(shallow)
|
||||
b, _ := v.insets(deep)
|
||||
if b-a != 30 {
|
||||
t.Fatalf("quote inset delta=%v", b-a)
|
||||
}
|
||||
if count := strings.Count(TextOf(Paragraph{Style: deep, Runs: []Run{{Text: "x"}}}).HTML(), "<blockquote>"); count != 3 {
|
||||
t.Fatalf("quote count=%d", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeavingANestedQuoteClearsItsDepth(t *testing.T) {
|
||||
for _, key := range []ui.Key{ui.KeyBackspace, ui.KeyEnter} {
|
||||
doc := NewDocument(TextOf(Paragraph{Style: ParagraphStyle{Quote: true, QuoteDepth: 3}}))
|
||||
tt, _ := richTester(t, doc)
|
||||
tt.Key(0, key)
|
||||
if st := doc.Text().ParagraphStyleAt(0); st.Quote || st.QuoteDepth != 0 {
|
||||
t.Fatalf("key %v left style %+v", key, st)
|
||||
}
|
||||
doc.ToggleQuote()
|
||||
if st := doc.Text().ParagraphStyleAt(0); st.quoteDepth() != 1 {
|
||||
t.Fatalf("new quotation restored old depth: %+v", st)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuoteDepthKeepsLegacyQuotes(t *testing.T) {
|
||||
legacy := TextOf(Paragraph{Style: ParagraphStyle{Quote: true}, Runs: []Run{{Text: "quoted"}}})
|
||||
for _, depth := range []int{-1, 0, 1} {
|
||||
text := TextOf(Paragraph{Style: ParagraphStyle{Quote: true, QuoteDepth: depth}, Runs: []Run{{Text: "quoted"}}})
|
||||
if text.HTML() != legacy.HTML() || text.Markdown() != legacy.Markdown() {
|
||||
t.Fatalf("depth %d changed the legacy quotation", depth)
|
||||
}
|
||||
}
|
||||
const src = "> > first\n>\n> second\n>\n> > <blockquote><p>third</p></blockquote>"
|
||||
text := ParseMarkdown(src)
|
||||
for _, roundtrip := range []Text{text, ParseHTML(text.HTML()), ParseMarkdown(text.Markdown())} {
|
||||
i := 0
|
||||
for _, p := range roundtrip.Paragraphs() {
|
||||
if i >= 3 || p.Style.quoteDepth() != []int{2, 1, 3}[i] {
|
||||
t.Fatalf("paragraph %d: %+v", i, p.Style)
|
||||
}
|
||||
i++
|
||||
}
|
||||
if i != 3 {
|
||||
t.Fatalf("paragraph count=%d", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// The bars of a quotation's paragraphs join as one: rounded at the
|
||||
// quotation's ends only, so that no notch shows where two paragraphs
|
||||
// meet, even at the bar's outer edges.
|
||||
func TestQuoteBarsJoin(t *testing.T) {
|
||||
doc := NewDocument(TextOf(
|
||||
para("Before"),
|
||||
Paragraph{Style: ParagraphStyle{Quote: true}, Runs: []Run{{Text: "One"}}},
|
||||
Paragraph{Style: ParagraphStyle{Quote: true}, Runs: []Run{{Text: "Two"}}},
|
||||
para("After"),
|
||||
))
|
||||
red := ui.RGB(255, 0, 0)
|
||||
boxes := new([]ParagraphBox)
|
||||
tt := openTester(t, func(c *ui.Context) {
|
||||
*boxes = doc.VisibleParagraphs()
|
||||
EditorBase(c, doc, EditorOptions{Font: ui.Font{Size: 10},
|
||||
Theme: &Theme{QuoteBar: red, QuoteBarWidth: 6, ParagraphSpacing: 0.8}}).Fill()
|
||||
}, 300, 200)
|
||||
tt.Frame()
|
||||
if len(*boxes) != 4 {
|
||||
t.Fatalf("%d paragraphs in view, want 4", len(*boxes))
|
||||
}
|
||||
one, two := (*boxes)[1], (*boxes)[2]
|
||||
img := tt.Image()
|
||||
s := float32(img.Bounds().Dx()) / 300
|
||||
isRed := func(x, y int) bool {
|
||||
c := img.RGBAAt(x, y)
|
||||
return c.R > 200 && c.G < 60 && c.B < 60
|
||||
}
|
||||
row := int((one.Top + one.Height/2) * s)
|
||||
first, last := -1, -1
|
||||
for x := 0; x < img.Bounds().Dx()/2; x++ {
|
||||
if isRed(x, row) {
|
||||
if first < 0 {
|
||||
first = x
|
||||
}
|
||||
last = x
|
||||
}
|
||||
}
|
||||
if first < 0 {
|
||||
t.Fatal("no bar beside the first quoted line")
|
||||
}
|
||||
// The bar's outermost columns, where rounded ends would leave a notch,
|
||||
// are red all the way from the middle of one line to the next.
|
||||
for _, x := range []int{first, last} {
|
||||
for y := row; y < int((two.Top+two.Height/2)*s); y++ {
|
||||
if !isRed(x, y) {
|
||||
t.Fatalf("the bar has a notch at x %d, y %d (DIP %v), between the paragraphs at %v and %v", x, y, float32(y)/s, one.Top, two.Top)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Its ends stay round: the corner pixel at the top of the quotation is
|
||||
// not filled.
|
||||
top := row
|
||||
for top > 0 && isRed((first+last)/2, top-1) {
|
||||
top--
|
||||
}
|
||||
if isRed(first, top) {
|
||||
t.Error("the quotation's first bar is square at its top end")
|
||||
}
|
||||
}
|
||||
Vendored
+363
@@ -0,0 +1,363 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// ParseRTF returns the attributed text of a document in Rich Text Format,
|
||||
// as macOS apps (TextEdit, Pages) and WordPad copy it: paragraphs, their
|
||||
// alignment and lists, bold, italic, underline, strikethrough and links.
|
||||
// Fonts, sizes and colors are left out, as ParseHTML leaves them.
|
||||
func ParseRTF(data []byte) Text {
|
||||
r := rtfReader{s: strings.TrimRight(string(data), "\x00"), uc: 1}
|
||||
r.state = rtfState{uc: 1}
|
||||
r.read()
|
||||
r.endParagraph(false)
|
||||
for len(r.paras) > 1 && len(r.paras[len(r.paras)-1].Runs) == 0 {
|
||||
r.paras = r.paras[:len(r.paras)-1]
|
||||
}
|
||||
if len(r.paras) == 0 {
|
||||
return Text{}
|
||||
}
|
||||
return TextOf(r.paras...)
|
||||
}
|
||||
|
||||
// rtfState is what a group of RTF sets: the formats of characters, the
|
||||
// style of the paragraph, and what the group holds.
|
||||
type rtfState struct {
|
||||
a Attributes
|
||||
para ParagraphStyle
|
||||
skip bool // a destination whose text is not the document's
|
||||
field string // "inst" in a field's instruction, "result" in its result
|
||||
link string // the URL of the field the group is in
|
||||
list bool // a paragraph's list text, which says its marker
|
||||
hide bool // hidden text, \v
|
||||
uc int // how many characters follow a \u as its fallback
|
||||
}
|
||||
|
||||
type rtfReader struct {
|
||||
s string
|
||||
i int
|
||||
uc int
|
||||
state rtfState
|
||||
stack []rtfState
|
||||
paras []Paragraph
|
||||
cur Paragraph
|
||||
text strings.Builder // the run being read
|
||||
runA Attributes
|
||||
// inst is a field's instruction; marker is a paragraph's list text.
|
||||
inst string
|
||||
marker strings.Builder
|
||||
listed bool
|
||||
level int
|
||||
}
|
||||
|
||||
// flush ends the run being read.
|
||||
func (r *rtfReader) flush() {
|
||||
if r.text.Len() > 0 {
|
||||
r.cur.Runs = append(r.cur.Runs, Run{Text: r.text.String(), Attributes: r.runA})
|
||||
r.text.Reset()
|
||||
}
|
||||
}
|
||||
|
||||
// emit adds text in the current attributes.
|
||||
func (r *rtfReader) emit(s string) {
|
||||
st := &r.state
|
||||
switch {
|
||||
case st.list:
|
||||
r.marker.WriteString(s)
|
||||
return
|
||||
case st.field == "inst":
|
||||
r.inst += s
|
||||
return
|
||||
case st.skip, st.hide:
|
||||
return
|
||||
}
|
||||
a := st.a
|
||||
if st.field == "result" && st.link != "" {
|
||||
a.Link = st.link
|
||||
}
|
||||
if a != r.runA {
|
||||
r.flush()
|
||||
r.runA = a
|
||||
}
|
||||
r.text.WriteString(s)
|
||||
}
|
||||
|
||||
// endParagraph ends the paragraph being read, in the style of the group.
|
||||
func (r *rtfReader) endParagraph(always bool) {
|
||||
r.flush()
|
||||
if !always && len(r.cur.Runs) == 0 && !r.listed {
|
||||
return
|
||||
}
|
||||
p := r.cur
|
||||
p.Style.Align = r.state.para.Align
|
||||
if r.listed {
|
||||
m := strings.TrimSpace(r.marker.String())
|
||||
p.Style.List = Bullets
|
||||
if m != "" && (m[0] >= '0' && m[0] <= '9' || len(m) > 1 && strings.HasSuffix(m, ".")) {
|
||||
p.Style.List = Numbers
|
||||
}
|
||||
p.Style.Indent = r.level
|
||||
}
|
||||
r.paras = append(r.paras, p)
|
||||
r.cur = Paragraph{}
|
||||
r.marker.Reset()
|
||||
r.listed, r.level = false, 0
|
||||
}
|
||||
|
||||
// read reads the document's groups, control words and text.
|
||||
func (r *rtfReader) read() {
|
||||
s := r.s
|
||||
pendingSkip := false // after \* : the group is a destination to skip
|
||||
for r.i < len(s) {
|
||||
c := s[r.i]
|
||||
switch c {
|
||||
case '{':
|
||||
r.stack = append(r.stack, r.state)
|
||||
r.i++
|
||||
case '}':
|
||||
wasInst := r.state.field == "inst"
|
||||
if n := len(r.stack); n > 0 {
|
||||
r.state = r.stack[n-1]
|
||||
r.stack = r.stack[:n-1]
|
||||
}
|
||||
if wasInst && r.state.field != "inst" {
|
||||
// The field's group: its result links to the URL of its
|
||||
// instruction.
|
||||
r.state.link = safeLink(hyperlink(r.inst))
|
||||
r.inst = ""
|
||||
}
|
||||
r.i++
|
||||
case '\\':
|
||||
r.i++
|
||||
if r.i >= len(s) {
|
||||
return
|
||||
}
|
||||
c = s[r.i]
|
||||
switch {
|
||||
case c == '\'' && r.i+2 < len(s):
|
||||
// A character of the code page, as Windows-1252.
|
||||
if v, err := strconv.ParseUint(s[r.i+1:r.i+3], 16, 8); err == nil {
|
||||
r.emit(string(cp1252(byte(v))))
|
||||
}
|
||||
r.i += 3
|
||||
case c == '*':
|
||||
pendingSkip = true
|
||||
r.i++
|
||||
case c == '\\' || c == '{' || c == '}':
|
||||
r.emit(string(c))
|
||||
r.i++
|
||||
case c == '~':
|
||||
r.emit(" ")
|
||||
r.i++
|
||||
case c == '_':
|
||||
r.emit("\u2011") // a hyphen lines don't break at
|
||||
r.i++
|
||||
case c == '\n' || c == '\r':
|
||||
// \ and a newline is a \par.
|
||||
r.endParagraph(true)
|
||||
r.i++
|
||||
case isLetter(c):
|
||||
word, num, hasNum := r.word()
|
||||
if pendingSkip {
|
||||
pendingSkip = false
|
||||
if word != "fldinst" {
|
||||
r.state.skip = true
|
||||
}
|
||||
}
|
||||
r.control(word, num, hasNum)
|
||||
default:
|
||||
r.i++
|
||||
}
|
||||
case '\r', '\n':
|
||||
r.i++
|
||||
default:
|
||||
// Text up to the next special character.
|
||||
j := r.i
|
||||
for j < len(s) && s[j] != '\\' && s[j] != '{' && s[j] != '}' && s[j] != '\r' && s[j] != '\n' {
|
||||
j++
|
||||
}
|
||||
r.emit(s[r.i:j])
|
||||
r.i = j
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isLetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' }
|
||||
|
||||
// word reads a control word and its number, and the space ending them.
|
||||
func (r *rtfReader) word() (string, int, bool) {
|
||||
s := r.s
|
||||
start := r.i
|
||||
for r.i < len(s) && isLetter(s[r.i]) {
|
||||
r.i++
|
||||
}
|
||||
word := s[start:r.i]
|
||||
numStart := r.i
|
||||
if r.i < len(s) && s[r.i] == '-' {
|
||||
r.i++
|
||||
}
|
||||
for r.i < len(s) && s[r.i] >= '0' && s[r.i] <= '9' {
|
||||
r.i++
|
||||
}
|
||||
num, err := strconv.Atoi(s[numStart:r.i])
|
||||
if r.i < len(s) && s[r.i] == ' ' {
|
||||
r.i++
|
||||
}
|
||||
return word, num, err == nil
|
||||
}
|
||||
|
||||
// control applies a control word.
|
||||
func (r *rtfReader) control(word string, num int, hasNum bool) {
|
||||
st := &r.state
|
||||
on := !hasNum || num != 0
|
||||
switch word {
|
||||
case "fonttbl", "colortbl", "stylesheet", "info", "pict", "header", "footer", "footnote",
|
||||
"listtable", "listoverridetable", "expandedcolortbl", "themedata", "colorschememapping", "latentstyles",
|
||||
"datastore", "xmlnstbl", "rsidtbl", "generator", "object", "shppict", "nonshppict":
|
||||
st.skip = true
|
||||
case "field":
|
||||
st.field, st.link = "", ""
|
||||
case "fldinst":
|
||||
st.field = "inst"
|
||||
st.skip = false
|
||||
case "fldrslt":
|
||||
st.field = "result"
|
||||
case "listtext", "pntext":
|
||||
// The marker of a list's item, as Word and WordPad write it.
|
||||
st.list = true
|
||||
r.listed = true
|
||||
case "ls":
|
||||
r.listed = true
|
||||
case "ilvl":
|
||||
r.level = max(0, num)
|
||||
case "par", "line", "sect", "page":
|
||||
if !st.skip && !st.list && st.field != "inst" {
|
||||
r.endParagraph(true)
|
||||
}
|
||||
case "pard":
|
||||
st.para = ParagraphStyle{}
|
||||
case "ql", "qj":
|
||||
st.para.Align = ui.Start
|
||||
case "qc":
|
||||
st.para.Align = ui.Center
|
||||
case "qr":
|
||||
st.para.Align = ui.End
|
||||
case "plain":
|
||||
st.a, st.hide = Attributes{}, false
|
||||
case "b":
|
||||
if on {
|
||||
st.a.Weight = 700
|
||||
} else {
|
||||
st.a.Weight = 0
|
||||
}
|
||||
case "i":
|
||||
st.a.Italic = on
|
||||
case "ul", "uld", "uldb", "ulw", "ulth":
|
||||
st.a.Underline = on
|
||||
case "ulnone":
|
||||
st.a.Underline = false
|
||||
case "strike", "striked":
|
||||
st.a.Strikethrough = on
|
||||
case "tab", "cell":
|
||||
r.emit("\t")
|
||||
case "row":
|
||||
if !st.skip && !st.list && st.field != "inst" {
|
||||
r.endParagraph(true)
|
||||
}
|
||||
case "v":
|
||||
st.hide = on
|
||||
case "emdash":
|
||||
r.emit("—")
|
||||
case "endash":
|
||||
r.emit("–")
|
||||
case "bullet":
|
||||
r.emit("•")
|
||||
case "lquote":
|
||||
r.emit("‘")
|
||||
case "rquote":
|
||||
r.emit("’")
|
||||
case "ldblquote":
|
||||
r.emit("“")
|
||||
case "rdblquote":
|
||||
r.emit("”")
|
||||
case "uc":
|
||||
st.uc = num
|
||||
r.uc = num
|
||||
case "u":
|
||||
if num < 0 {
|
||||
num += 65536
|
||||
}
|
||||
rn := rune(num)
|
||||
// A surrogate pair comes as two \u.
|
||||
if rn >= 0xD800 && rn <= 0xDBFF {
|
||||
r.skipFallback()
|
||||
if strings.HasPrefix(r.s[r.i:], "\\u") {
|
||||
r.i++
|
||||
_, low, _ := r.word()
|
||||
if low < 0 {
|
||||
low += 65536
|
||||
}
|
||||
rn = 0x10000 + (rn-0xD800)<<10 + (rune(low) - 0xDC00)
|
||||
}
|
||||
}
|
||||
if utf8.ValidRune(rn) {
|
||||
r.emit(string(rn))
|
||||
}
|
||||
r.skipFallback()
|
||||
}
|
||||
}
|
||||
|
||||
// skipFallback skips the characters after a \u that stand for it where
|
||||
// Unicode is not read.
|
||||
func (r *rtfReader) skipFallback() {
|
||||
for n := r.state.uc; n > 0 && r.i < len(r.s); n-- {
|
||||
switch {
|
||||
case r.s[r.i] == '\\' && r.i+3 < len(r.s) && r.s[r.i+1] == '\'':
|
||||
r.i += 4
|
||||
case r.s[r.i] == '\\' || r.s[r.i] == '{' || r.s[r.i] == '}':
|
||||
return
|
||||
default:
|
||||
r.i++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// hyperlink returns the URL of a field's instruction, HYPERLINK "url".
|
||||
func hyperlink(inst string) string {
|
||||
inst = strings.TrimSpace(inst)
|
||||
rest, ok := strings.CutPrefix(inst, "HYPERLINK")
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
rest = strings.TrimSpace(rest)
|
||||
// \l "name" links to a bookmark of the document.
|
||||
if after, ok := strings.CutPrefix(rest, "\\l"); ok {
|
||||
if u := hyperlink("HYPERLINK " + strings.TrimSpace(after)); u != "" {
|
||||
return "#" + u
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if strings.HasPrefix(rest, "\"") {
|
||||
if end := strings.Index(rest[1:], "\""); end >= 0 {
|
||||
return rest[1 : end+1]
|
||||
}
|
||||
}
|
||||
if f := strings.Fields(rest); len(f) > 0 {
|
||||
return f[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// cp1252 returns the rune of a byte of Windows-1252.
|
||||
func cp1252(b byte) rune {
|
||||
if b >= 0x80 && b < 0xA0 {
|
||||
return []rune("€\u0081‚ƒ„…†‡ˆ‰Š‹Œ\u008dŽ\u008f\u0090‘’“”•–—˜™š›œ\u009džŸ")[b-0x80]
|
||||
}
|
||||
return rune(b)
|
||||
}
|
||||
+566
@@ -0,0 +1,566 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// longDoc returns a document of n paragraphs, each long enough to wrap in
|
||||
// a narrow editor.
|
||||
func longDoc(n int) *Document {
|
||||
paras := make([]Paragraph, n)
|
||||
for i := range paras {
|
||||
paras[i] = para(fmt.Sprintf("Paragraph %d, long enough to wrap in a window this narrow at times.", i))
|
||||
}
|
||||
return NewDocument(TextOf(paras...))
|
||||
}
|
||||
|
||||
// boxOf returns the box of paragraph i among boxes.
|
||||
func boxOf(t *testing.T, boxes []ParagraphBox, i int) ParagraphBox {
|
||||
t.Helper()
|
||||
for _, b := range boxes {
|
||||
if b.Index == i {
|
||||
return b
|
||||
}
|
||||
}
|
||||
t.Fatalf("paragraph %d is not in view: %v", i, boxes)
|
||||
return ParagraphBox{}
|
||||
}
|
||||
|
||||
// near reports whether a and b are the same to a hundredth of a DIP.
|
||||
func near(a, b float32) bool { return math.Abs(float64(a-b)) < 0.01 }
|
||||
|
||||
// openTester is ui.NewTester for a test that reads the document after its
|
||||
// last frame (CaretRect, VisibleParagraphs): the window stays open until
|
||||
// the test ends, as an app's does while it shows the editor. A document
|
||||
// holds its editor weakly, so that it doesn't keep a closed window's
|
||||
// alive, and once nothing uses the Tester the collector may take the
|
||||
// editor, after which the document reads as shown in none.
|
||||
func openTester(t *testing.T, view func(c *ui.Context), width, height int) *ui.Tester {
|
||||
t.Helper()
|
||||
tt := ui.NewTester(view, width, height)
|
||||
t.Cleanup(func() { runtime.KeepAlive(tt) })
|
||||
return tt
|
||||
}
|
||||
|
||||
// ScrollBy scrolls the editor by as much as asked, as far as its text
|
||||
// goes, and reports whether it moved; before an editor showed the
|
||||
// document, it does nothing.
|
||||
func TestScrollBy(t *testing.T) {
|
||||
doc := longDoc(200)
|
||||
if doc.ScrollBy(100) {
|
||||
t.Fatal("no editor shows the document, and it scrolled")
|
||||
}
|
||||
tt, boxes := proseTester(t, doc, &Theme{ParagraphSpacing: 0.5}, 400)
|
||||
doc.SetSelection(0, 0)
|
||||
tt.Frame()
|
||||
if (*boxes)[0].Index != 0 || (*boxes)[0].Top != 0 {
|
||||
t.Fatalf("the first frame shows %v", (*boxes)[0])
|
||||
}
|
||||
// A paragraph that stays in view moves up by as much.
|
||||
b := (*boxes)[len(*boxes)/2]
|
||||
if !doc.ScrollBy(b.Top / 2) {
|
||||
t.Fatal("ScrollBy did not scroll")
|
||||
}
|
||||
if !tt.FramePending() {
|
||||
t.Fatal("ScrollBy asked for no frame")
|
||||
}
|
||||
tt.Frame()
|
||||
if got := boxOf(t, *boxes, b.Index); !near(got.Top, b.Top/2) {
|
||||
t.Fatalf("scrolled by %v, paragraph %d went from %v to %v", b.Top/2, b.Index, b.Top, got.Top)
|
||||
}
|
||||
// The wheel goes as far as the text does, and so does ScrollBy.
|
||||
if !doc.ScrollBy(1e9) {
|
||||
t.Fatal("ScrollBy to the end did not scroll")
|
||||
}
|
||||
tt.Frame()
|
||||
last := (*boxes)[len(*boxes)-1]
|
||||
if last.Index != 199 || !near(last.Top+last.Height, 400) {
|
||||
t.Fatalf("at the end, the last box is %+v", last)
|
||||
}
|
||||
if doc.ScrollBy(10) {
|
||||
t.Fatal("ScrollBy scrolled past the end")
|
||||
}
|
||||
if !doc.ScrollBy(-1e9) {
|
||||
t.Fatal("ScrollBy to the start did not scroll")
|
||||
}
|
||||
tt.Frame()
|
||||
if first := (*boxes)[0]; first.Index != 0 || first.Top != 0 {
|
||||
t.Fatalf("at the start, the first box is %+v", first)
|
||||
}
|
||||
if doc.ScrollBy(-10) {
|
||||
t.Fatal("ScrollBy scrolled past the start")
|
||||
}
|
||||
// Frames that change nothing ask for none more.
|
||||
tt.Frame()
|
||||
if tt.FramePending() {
|
||||
t.Fatal("the frames do not settle")
|
||||
}
|
||||
}
|
||||
|
||||
// ScrollToParagraph lines a paragraph's lines up with the editor's top,
|
||||
// middle or bottom, or scrolls as little as shows them, as far as the
|
||||
// text goes.
|
||||
func TestScrollToParagraph(t *testing.T) {
|
||||
doc := longDoc(200)
|
||||
doc.ScrollToParagraph(100, ui.ScrollStart) // no editor yet: nothing
|
||||
tt, boxes := proseTester(t, doc, &Theme{ParagraphSpacing: 0.5}, 400)
|
||||
doc.SetSelection(0, 0)
|
||||
tt.Frame()
|
||||
to := func(i int, align ui.ScrollAlign) ParagraphBox {
|
||||
t.Helper()
|
||||
doc.ScrollToParagraph(i, align)
|
||||
tt.Frame()
|
||||
return boxOf(t, *boxes, i)
|
||||
}
|
||||
if b := to(100, ui.ScrollStart); !near(b.Top, 0) {
|
||||
t.Fatalf("paragraph 100 at the start: %+v", b)
|
||||
}
|
||||
if b := to(150, ui.ScrollCenter); !near(b.Top+b.Height/2, 200) {
|
||||
t.Fatalf("paragraph 150 in the middle: %+v", b)
|
||||
}
|
||||
if b := to(60, ui.ScrollEnd); !near(b.Top+b.Height, 400) {
|
||||
t.Fatalf("paragraph 60 at the end: %+v", b)
|
||||
}
|
||||
// Nearest: in view, nothing moves; below, it comes up to the bottom;
|
||||
// above, down to the top.
|
||||
in := (*boxes)[len(*boxes)/2]
|
||||
if b := to(in.Index, ui.ScrollNearest); b != in {
|
||||
t.Fatalf("paragraph %d in view went from %+v to %+v", in.Index, in, b)
|
||||
}
|
||||
if b := to(90, ui.ScrollNearest); !near(b.Top+b.Height, 400) {
|
||||
t.Fatalf("paragraph 90 below, nearest: %+v", b)
|
||||
}
|
||||
if b := to(20, ui.ScrollNearest); !near(b.Top, 0) {
|
||||
t.Fatalf("paragraph 20 above, nearest: %+v", b)
|
||||
}
|
||||
// Past the ends: the first and the last paragraphs, as far as the text
|
||||
// goes.
|
||||
doc.ScrollToParagraph(-5, ui.ScrollStart)
|
||||
tt.Frame()
|
||||
if b := (*boxes)[0]; b.Index != 0 || b.Top != 0 {
|
||||
t.Fatalf("paragraph -5: %+v", b)
|
||||
}
|
||||
doc.ScrollToParagraph(1000, ui.ScrollStart)
|
||||
tt.Frame()
|
||||
if b := (*boxes)[len(*boxes)-1]; b.Index != 199 || !near(b.Top+b.Height, 400) {
|
||||
t.Fatalf("paragraph 1000: %+v", b)
|
||||
}
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Error("an alignment out of range did not panic")
|
||||
}
|
||||
}()
|
||||
doc.ScrollToParagraph(0, ui.ScrollAlign(9))
|
||||
}
|
||||
|
||||
// anchorTester builds an EditorBase of doc 300×400 that leaves room
|
||||
// above paragraph *at of *room DIPs, the boxes it reads as it builds, and
|
||||
// whether to focus it. It scrolls to paragraph 50 and puts the caret at
|
||||
// the start of the paragraph in the middle of the view.
|
||||
func anchorTester(t *testing.T, doc *Document, focus bool) (tt *ui.Tester, boxes *[]ParagraphBox, at *int, room *float32) {
|
||||
t.Helper()
|
||||
boxes, at, room = new([]ParagraphBox), new(int), new(float32)
|
||||
tt = openTester(t, func(c *ui.Context) {
|
||||
*boxes = doc.VisibleParagraphs()
|
||||
EditorBase(c, doc, EditorOptions{Font: ui.Font{Size: 10}, Space: func(p int) float32 {
|
||||
if p == *at {
|
||||
return *room
|
||||
}
|
||||
return 0
|
||||
}}).Fill()
|
||||
}, 300, 400)
|
||||
if focus {
|
||||
tt.ClickAt(150, 5)
|
||||
if !tt.Focused("Rich text") {
|
||||
t.Fatal("the editor did not take the focus")
|
||||
}
|
||||
}
|
||||
doc.ScrollToParagraph(50, ui.ScrollStart)
|
||||
tt.Frame()
|
||||
mid := (*boxes)[len(*boxes)/2]
|
||||
doc.SetSelection(mid.Start, mid.Start)
|
||||
tt.Frame()
|
||||
if (*boxes)[0].Index != 50 {
|
||||
t.Fatalf("the view starts at paragraph %d", (*boxes)[0].Index)
|
||||
}
|
||||
return tt, boxes, at, room
|
||||
}
|
||||
|
||||
// caretRect returns where the editor shows the caret, which is in view.
|
||||
func caretRect(t *testing.T, doc *Document) ui.Rect {
|
||||
t.Helper()
|
||||
r, ok := doc.CaretRect()
|
||||
if !ok {
|
||||
t.Fatal("the caret is out of view")
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// While the editor has the keyboard, what grows between the top of the
|
||||
// view and the caret moves the text above it up, and the line being typed
|
||||
// stays, as browsers keep the focused editable element in place.
|
||||
func TestScrollAnchorCaret(t *testing.T) {
|
||||
doc := longDoc(200)
|
||||
tt, boxes, at, room := anchorTester(t, doc, true)
|
||||
caret := caretRect(t, doc)
|
||||
first, second := (*boxes)[0], (*boxes)[1]
|
||||
_, at0 := doc.Selection()
|
||||
cp := doc.Text().paraAt(at0)
|
||||
|
||||
// Room opens above a paragraph between the top of the view and the
|
||||
// caret's.
|
||||
*at, *room = first.Index+2, 40
|
||||
tt.Frame()
|
||||
if got := caretRect(t, doc); got != caret {
|
||||
t.Fatalf("room above paragraph %d moved the caret from %v to %v", *at, caret, got)
|
||||
}
|
||||
if got := boxOf(t, *boxes, second.Index); !near(got.Top, second.Top-40) {
|
||||
t.Fatalf("room above paragraph %d: paragraph %d went from %v to %v, want 40 up", *at, second.Index, second.Top, got.Top)
|
||||
}
|
||||
// It grows, and goes.
|
||||
*room = 90
|
||||
tt.Frame()
|
||||
if got := caretRect(t, doc); got != caret {
|
||||
t.Fatalf("more room moved the caret from %v to %v", caret, got)
|
||||
}
|
||||
*room = 0
|
||||
tt.Frame()
|
||||
if got := caretRect(t, doc); got != caret {
|
||||
t.Fatalf("the room gone moved the caret from %v to %v", caret, got)
|
||||
}
|
||||
// Room above the caret's own paragraph keeps its line too.
|
||||
*at, *room = cp, 30
|
||||
tt.Frame()
|
||||
if got := caretRect(t, doc); got != caret {
|
||||
t.Fatalf("room above the caret's paragraph moved the caret from %v to %v", caret, got)
|
||||
}
|
||||
// Room below the caret moves nothing above it.
|
||||
*at = cp + 2
|
||||
tt.Frame()
|
||||
if got := caretRect(t, doc); got != caret {
|
||||
t.Fatalf("room below the caret moved it from %v to %v", caret, got)
|
||||
}
|
||||
// Typing keeps its line, and so does an edit above it in view.
|
||||
tt.Type("abc")
|
||||
typed := caretRect(t, doc)
|
||||
if typed.Y != caret.Y || typed.X <= caret.X {
|
||||
t.Fatalf("typed from %v, the caret is at %v", caret, typed)
|
||||
}
|
||||
start := (*boxes)[1].Start
|
||||
doc.Edit(func(e *Edit) { e.ReplaceString(start, start, "Inserted\n", Attributes{}) })
|
||||
tt.Frame()
|
||||
if got := caretRect(t, doc); got.Y != typed.Y {
|
||||
t.Fatalf("a paragraph inserted above moved the caret from %v to %v", typed, got)
|
||||
}
|
||||
// Joining the caret's paragraph to the one above keeps the view.
|
||||
before := (*boxes)[0]
|
||||
tt.Key(ui.Cmd, ui.KeyLeft)
|
||||
tt.Key(0, ui.KeyBackspace)
|
||||
if got := boxOf(t, *boxes, before.Index); got.Top != before.Top {
|
||||
t.Fatalf("joining paragraphs moved the first in view from %+v to %+v", before, got)
|
||||
}
|
||||
// Frames that change nothing ask for none more.
|
||||
tt.Frame()
|
||||
if tt.FramePending() {
|
||||
t.Fatal("the frames do not settle")
|
||||
}
|
||||
}
|
||||
|
||||
// Without the keyboard, the editor keeps its place by the first paragraph
|
||||
// in view, as before: what grows above the caret moves the caret down.
|
||||
func TestScrollAnchorUnfocused(t *testing.T) {
|
||||
doc := longDoc(200)
|
||||
tt, boxes, at, room := anchorTester(t, doc, false)
|
||||
if tt.Focused("Rich text") {
|
||||
t.Fatal("the editor has the focus")
|
||||
}
|
||||
caret := caretRect(t, doc)
|
||||
first := (*boxes)[0]
|
||||
*at, *room = first.Index+2, 40
|
||||
tt.Frame()
|
||||
if got := caretRect(t, doc); !near(got.Y, caret.Y+40) {
|
||||
t.Fatalf("room above paragraph %d moved the caret from %v to %v, want 40 down", *at, caret.Y, got.Y)
|
||||
}
|
||||
if got := (*boxes)[0]; got != first {
|
||||
t.Fatalf("the first paragraph in view went from %+v to %+v", first, got)
|
||||
}
|
||||
}
|
||||
|
||||
// An editor scrolled to its top stays there while focused, as one that
|
||||
// shows all of its text does: room above the caret moves it down.
|
||||
func TestScrollAnchorAtTop(t *testing.T) {
|
||||
doc := longDoc(200)
|
||||
var boxes []ParagraphBox
|
||||
var room float32
|
||||
tt := openTester(t, func(c *ui.Context) {
|
||||
boxes = doc.VisibleParagraphs()
|
||||
EditorBase(c, doc, EditorOptions{Font: ui.Font{Size: 10}, Space: func(p int) float32 {
|
||||
if p == 1 {
|
||||
return room
|
||||
}
|
||||
return 0
|
||||
}}).Fill()
|
||||
}, 300, 400)
|
||||
doc.SetSelection(0, 0)
|
||||
tt.Frame()
|
||||
tt.ClickAt(150, 200)
|
||||
if !tt.Focused("Rich text") {
|
||||
t.Fatal("the editor did not take the focus")
|
||||
}
|
||||
caret := caretRect(t, doc)
|
||||
room = 40
|
||||
tt.Frame()
|
||||
if got := caretRect(t, doc); !near(got.Y, caret.Y+40) {
|
||||
t.Fatalf("at the top, room above the caret moved it from %v to %v, want 40 down", caret.Y, got.Y)
|
||||
}
|
||||
if first := boxes[0]; first.Index != 0 || first.Top != 0 {
|
||||
t.Fatalf("at the top, the first box is %+v", first)
|
||||
}
|
||||
}
|
||||
|
||||
// An edit that moves a paragraph across the top of the view in one step
|
||||
// of undo, as a block editor's drag by a handle does, keeps the view: the
|
||||
// paragraphs in view that did not move stay where they were, and the one
|
||||
// moved goes where it was put. The editor follows the edit's replacements
|
||||
// one by one, as undo and redo do, rather than one region from the first
|
||||
// to the last, which held the first paragraph in view and sent the view to
|
||||
// the region's start (#1723). With the keyboard, the caret's line stays.
|
||||
func TestAMoveAcrossTheTopOfTheViewKeepsIt(t *testing.T) {
|
||||
for _, focus := range []bool{false, true} {
|
||||
for _, kind := range []string{"into the view", "into the view from just above it", "out to above it"} {
|
||||
into := kind != "out to above it"
|
||||
name := kind
|
||||
if focus {
|
||||
name += ", focused"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
doc := longDoc(200)
|
||||
tt, boxes, _, _ := anchorTester(t, doc, focus)
|
||||
doc.ScrollBy(13) // the first paragraph in view partly out
|
||||
tt.Frame()
|
||||
before := placed(doc, *boxes)
|
||||
caret := caretRect(t, doc)
|
||||
|
||||
// Into the view: paragraph 10, or the one right above the
|
||||
// view, goes before the one next to last in view, below the
|
||||
// caret's. Out of it: the second in view goes before
|
||||
// paragraph 10.
|
||||
from, to := 10, (*boxes)[len(*boxes)-2].Index
|
||||
switch kind {
|
||||
case "into the view from just above it":
|
||||
from = (*boxes)[0].Index - 1
|
||||
case "out to above it":
|
||||
from, to = (*boxes)[1].Index, 10
|
||||
}
|
||||
moving := paraName(from)
|
||||
text := doc.Text()
|
||||
fs, fe := text.paraStart(from), text.paraStart(from+1)
|
||||
moved := text.Slice(fs, fe)
|
||||
ts := text.paraStart(to)
|
||||
doc.Edit(func(e *Edit) {
|
||||
e.Replace(fs, fe, Text{})
|
||||
if ts > fs {
|
||||
ts -= fe - fs
|
||||
}
|
||||
e.Replace(ts, ts, moved)
|
||||
})
|
||||
tt.Frame()
|
||||
after := placed(doc, *boxes)
|
||||
|
||||
switch {
|
||||
case focus:
|
||||
if got := caretRect(t, doc); got != caret {
|
||||
t.Fatalf("the move took the caret from %v to %v", caret, got)
|
||||
}
|
||||
case into:
|
||||
// What's above where it went stays, and it goes where
|
||||
// the paragraph it went before was.
|
||||
for p, top := range before {
|
||||
if num(p) < to && !near(after[p], top) {
|
||||
t.Errorf("the move took %s, above it, from %v to %v", p, top, after[p])
|
||||
}
|
||||
}
|
||||
if !near(after[moving], before[paraName(to)]) {
|
||||
t.Errorf("%s landed at %v; %s, which it went before, was at %v", moving, after[moving], paraName(to), before[paraName(to)])
|
||||
}
|
||||
default:
|
||||
// What's above where it was stays, and what was below
|
||||
// it moves up into its place.
|
||||
for p, top := range before {
|
||||
if num(p) < from && !near(after[p], top) {
|
||||
t.Errorf("the move took %s, above it, from %v to %v", p, top, after[p])
|
||||
}
|
||||
}
|
||||
if _, ok := after[moving]; ok {
|
||||
t.Errorf("%s is still in view", moving)
|
||||
}
|
||||
if !near(after[paraName(from+1)], before[moving]) {
|
||||
t.Errorf("%s went to %v, not up to %v where %s was", paraName(from+1), after[paraName(from+1)], before[moving], moving)
|
||||
}
|
||||
}
|
||||
|
||||
// Undo puts the view back as it was, and redo as the move
|
||||
// left it.
|
||||
doc.Undo()
|
||||
tt.Frame()
|
||||
samePlaces(t, "undone", before, placed(doc, *boxes))
|
||||
doc.Redo()
|
||||
tt.Frame()
|
||||
samePlaces(t, "redone", after, placed(doc, *boxes))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// placed returns where the paragraphs in view are, by their names
|
||||
// ("Paragraph 12").
|
||||
func placed(doc *Document, boxes []ParagraphBox) map[string]float32 {
|
||||
text := doc.Text()
|
||||
out := map[string]float32{}
|
||||
for _, b := range boxes {
|
||||
s := text.Slice(b.Start, text.paraStart(b.Index+1)).String()
|
||||
out[strings.SplitN(s, ",", 2)[0]] = b.Top
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// paraName returns the name of longDoc's paragraph i, and num the number
|
||||
// in a name.
|
||||
func paraName(i int) string { return fmt.Sprintf("Paragraph %d", i) }
|
||||
|
||||
func num(name string) int {
|
||||
n, _ := strconv.Atoi(strings.TrimPrefix(name, "Paragraph "))
|
||||
return n
|
||||
}
|
||||
|
||||
// samePlaces fails unless the same paragraphs are in view, at the same
|
||||
// places.
|
||||
func samePlaces(t *testing.T, what string, want, got map[string]float32) {
|
||||
t.Helper()
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("%s: %d paragraphs in view, want %d: %v, want %v", what, len(got), len(want), got, want)
|
||||
}
|
||||
for p, top := range want {
|
||||
if g, ok := got[p]; !ok || !near(g, top) {
|
||||
t.Fatalf("%s: %s is at %v (in view: %v), want %v", what, p, g, ok, top)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An edit of one replacement that puts a paragraph right where the first
|
||||
// paragraph in view starts shows it at the top of the view, as it always
|
||||
// has. One of several, as a paragraph moved there from above, puts it
|
||||
// above the view: what's in view stays, as undoing such a move needs. At
|
||||
// the start of the caret's paragraph, a Return moves the line being typed
|
||||
// down.
|
||||
func TestWhatIsPutAtTheStartOfTheAnchor(t *testing.T) {
|
||||
t.Run("one replacement", func(t *testing.T) {
|
||||
doc := longDoc(200)
|
||||
tt, boxes, _, _ := anchorTester(t, doc, false)
|
||||
doc.ScrollBy(13)
|
||||
tt.Frame()
|
||||
first := (*boxes)[0]
|
||||
before := placed(doc, *boxes)
|
||||
doc.Edit(func(e *Edit) {
|
||||
e.ReplaceString(first.Start, first.Start, "Inserted, long enough to wrap in a window this narrow, and then some more.\n", Attributes{})
|
||||
})
|
||||
tt.Frame()
|
||||
after := placed(doc, *boxes)
|
||||
if top, ok := after["Inserted"]; !ok || !near(top, first.Top) {
|
||||
t.Errorf("the paragraph put there is at %v (in view: %v), want %v, where %s was", top, ok, first.Top, paraName(first.Index))
|
||||
}
|
||||
if p := paraName(first.Index); after[p] <= before[p] {
|
||||
t.Errorf("%s stayed at %v", p, after[p])
|
||||
}
|
||||
})
|
||||
t.Run("several replacements", func(t *testing.T) {
|
||||
doc := longDoc(200)
|
||||
tt, boxes, _, _ := anchorTester(t, doc, false)
|
||||
doc.ScrollBy(13)
|
||||
tt.Frame()
|
||||
before := placed(doc, *boxes)
|
||||
text := doc.Text()
|
||||
fs, fe := text.paraStart(10), text.paraStart(11)
|
||||
moved := text.Slice(fs, fe)
|
||||
at := (*boxes)[0].Start
|
||||
doc.Edit(func(e *Edit) {
|
||||
e.Replace(fs, fe, Text{})
|
||||
e.Replace(at-(fe-fs), at-(fe-fs), moved)
|
||||
})
|
||||
tt.Frame()
|
||||
samePlaces(t, "a paragraph moved to its start", before, placed(doc, *boxes))
|
||||
})
|
||||
t.Run("the caret's paragraph", func(t *testing.T) {
|
||||
doc := longDoc(200)
|
||||
tt, boxes, _, _ := anchorTester(t, doc, true)
|
||||
first := (*boxes)[0]
|
||||
caret := caretRect(t, doc)
|
||||
tt.Key(0, ui.KeyEnter)
|
||||
if got := caretRect(t, doc); got.Y <= caret.Y {
|
||||
t.Fatalf("a Return at the start of the caret's line left it at %v from %v", got.Y, caret.Y)
|
||||
}
|
||||
if got := (*boxes)[0]; got != first {
|
||||
t.Fatalf("a Return moved the first paragraph in view from %+v to %+v", first, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A step of undo keeps up to maxUndoParts replacements, and its undo
|
||||
// follows them, as the move's: the view comes back. Undoing a longer one
|
||||
// tells the editor of one region, from its first replacement to its last,
|
||||
// as every undo did before: the view goes to the region's start, then to
|
||||
// the caret the undo puts back.
|
||||
func TestALongStepUndoesAsARegion(t *testing.T) {
|
||||
for _, parts := range []int{maxUndoParts, maxUndoParts + 1} {
|
||||
t.Run(fmt.Sprint(parts, " replacements"), func(t *testing.T) {
|
||||
doc := longDoc(200)
|
||||
tt, boxes, _, _ := anchorTester(t, doc, false)
|
||||
doc.ScrollBy(13)
|
||||
tt.Frame()
|
||||
before := placed(doc, *boxes)
|
||||
text := doc.Text()
|
||||
fs, fe := text.paraStart(10), text.paraStart(11)
|
||||
moved := text.Slice(fs, fe)
|
||||
to := text.paraStart((*boxes)[len(*boxes)-2].Index)
|
||||
s5 := text.paraStart(5)
|
||||
doc.Edit(func(e *Edit) {
|
||||
// A letter of paragraph 5 replaced by itself, then the
|
||||
// move's two replacements.
|
||||
for range parts - 2 {
|
||||
e.ReplaceString(s5, s5+1, "P", Attributes{})
|
||||
}
|
||||
e.Replace(fs, fe, Text{})
|
||||
e.Replace(to-(fe-fs), to-(fe-fs), moved)
|
||||
})
|
||||
tt.Frame()
|
||||
if got := placed(doc, *boxes)[paraName(50)]; !near(got, before[paraName(50)]) {
|
||||
t.Fatalf("the edit, followed one by one, moved Paragraph 50 from %v to %v", before[paraName(50)], got)
|
||||
}
|
||||
doc.Undo()
|
||||
tt.Frame()
|
||||
if doc.Text().String() != text.String() {
|
||||
t.Fatal("undo didn't bring the text back")
|
||||
}
|
||||
back := placed(doc, *boxes)
|
||||
came := len(back) == len(before)
|
||||
for p, top := range before {
|
||||
if g, ok := back[p]; !ok || !near(g, top) {
|
||||
came = false
|
||||
}
|
||||
}
|
||||
if want := parts <= maxUndoParts; came != want {
|
||||
t.Errorf("undone, the view came back: %v, want %v (%d replacements, %d kept)", came, want, parts, maxUndoParts)
|
||||
}
|
||||
if _, ok := doc.CaretRect(); !ok {
|
||||
t.Error("the caret undo put back is out of view")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Vendored
+178
@@ -0,0 +1,178 @@
|
||||
package richtext
|
||||
|
||||
// seq is a persistent sequence: an AVL tree whose leaves hold up to
|
||||
// seqChunk items each, as internal/rope's leaves hold text, and whose
|
||||
// nodes count the items below them. Replacing items copies the leaves it
|
||||
// touches and the path to them and shares the rest with the sequence
|
||||
// before it, so a version is a pointer, kept as long as wanted. An
|
||||
// Text keeps its paragraphs in one, aligned with the lines of
|
||||
// its text.
|
||||
type seq[T any] struct {
|
||||
left, right *seq[T]
|
||||
items []T // only leaves hold items
|
||||
n, height int
|
||||
}
|
||||
|
||||
const seqChunk = 32
|
||||
|
||||
func seqLen[T any](s *seq[T]) int {
|
||||
if s == nil {
|
||||
return 0
|
||||
}
|
||||
return s.n
|
||||
}
|
||||
|
||||
func seqHeight[T any](s *seq[T]) int {
|
||||
if s == nil {
|
||||
return 0
|
||||
}
|
||||
return s.height
|
||||
}
|
||||
|
||||
func seqLeaf[T any](items []T) *seq[T] {
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &seq[T]{items: items, n: len(items), height: 1}
|
||||
}
|
||||
|
||||
func seqBranch[T any](a, b *seq[T]) *seq[T] {
|
||||
if a == nil {
|
||||
return b
|
||||
}
|
||||
if b == nil {
|
||||
return a
|
||||
}
|
||||
return &seq[T]{left: a, right: b, n: a.n + b.n, height: 1 + max(a.height, b.height)}
|
||||
}
|
||||
|
||||
func seqBalance[T any](s *seq[T]) *seq[T] {
|
||||
if seqHeight(s.left)-seqHeight(s.right) > 1 {
|
||||
a := s.left
|
||||
if seqHeight(a.left) < seqHeight(a.right) {
|
||||
b := a.right
|
||||
a = seqBranch(seqBranch(a.left, b.left), b.right)
|
||||
}
|
||||
return seqBranch(a.left, seqBranch(a.right, s.right))
|
||||
}
|
||||
if seqHeight(s.right)-seqHeight(s.left) > 1 {
|
||||
b := s.right
|
||||
if seqHeight(b.right) < seqHeight(b.left) {
|
||||
a := b.left
|
||||
b = seqBranch(a.left, seqBranch(a.right, b.right))
|
||||
}
|
||||
return seqBranch(seqBranch(s.left, b.left), b.right)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// seqJoin returns the items of a followed by those of b.
|
||||
func seqJoin[T any](a, b *seq[T]) *seq[T] {
|
||||
if a == nil {
|
||||
return b
|
||||
}
|
||||
if b == nil {
|
||||
return a
|
||||
}
|
||||
if a.left == nil && b.left == nil && a.n+b.n <= seqChunk {
|
||||
items := make([]T, 0, a.n+b.n)
|
||||
return seqLeaf(append(append(items, a.items...), b.items...))
|
||||
}
|
||||
if a.height > b.height+1 {
|
||||
return seqBalance(seqBranch(a.left, seqJoin(a.right, b)))
|
||||
}
|
||||
if b.height > a.height+1 {
|
||||
return seqBalance(seqBranch(seqJoin(a, b.left), b.right))
|
||||
}
|
||||
return seqBranch(a, b)
|
||||
}
|
||||
|
||||
// seqBuild returns a sequence of items, which it keeps.
|
||||
func seqBuild[T any](items []T) *seq[T] {
|
||||
if len(items) <= seqChunk {
|
||||
return seqLeaf(items)
|
||||
}
|
||||
m := len(items) / 2
|
||||
return seqBranch(seqBuild(items[:m:m]), seqBuild(items[m:]))
|
||||
}
|
||||
|
||||
// seqSplit returns the items before index at and those from it.
|
||||
func seqSplit[T any](s *seq[T], at int) (*seq[T], *seq[T]) {
|
||||
if s == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if at <= 0 {
|
||||
return nil, s
|
||||
}
|
||||
if at >= s.n {
|
||||
return s, nil
|
||||
}
|
||||
if s.left == nil {
|
||||
return seqLeaf(s.items[:at:at]), seqLeaf(s.items[at:])
|
||||
}
|
||||
if at < s.left.n {
|
||||
a, b := seqSplit(s.left, at)
|
||||
return a, seqJoin(b, s.right)
|
||||
}
|
||||
a, b := seqSplit(s.right, at-s.left.n)
|
||||
return seqJoin(s.left, a), b
|
||||
}
|
||||
|
||||
// seqReplace returns s with items i up to j replaced by items, which it
|
||||
// keeps.
|
||||
func seqReplace[T any](s *seq[T], i, j int, items []T) *seq[T] {
|
||||
left, rest := seqSplit(s, i)
|
||||
_, right := seqSplit(rest, j-i)
|
||||
return seqJoin(seqJoin(left, seqBuild(items)), right)
|
||||
}
|
||||
|
||||
// seqAt returns item i.
|
||||
func seqAt[T any](s *seq[T], i int) *T {
|
||||
for s.left != nil {
|
||||
if i < s.left.n {
|
||||
s = s.left
|
||||
} else {
|
||||
i -= s.left.n
|
||||
s = s.right
|
||||
}
|
||||
}
|
||||
return &s.items[i]
|
||||
}
|
||||
|
||||
// seqSet returns s with item i replaced by v.
|
||||
func seqSet[T any](s *seq[T], i int, v T) *seq[T] {
|
||||
if s.left == nil {
|
||||
items := make([]T, len(s.items))
|
||||
copy(items, s.items)
|
||||
items[i] = v
|
||||
return &seq[T]{items: items, n: s.n, height: 1}
|
||||
}
|
||||
if i < s.left.n {
|
||||
return &seq[T]{left: seqSet(s.left, i, v), right: s.right, n: s.n, height: s.height}
|
||||
}
|
||||
return &seq[T]{left: s.left, right: seqSet(s.right, i-s.left.n, v), n: s.n, height: s.height}
|
||||
}
|
||||
|
||||
// seqEach calls fn with the items from index from on, and their indices,
|
||||
// until it returns false.
|
||||
func seqEach[T any](s *seq[T], from int, fn func(i int, v *T) bool) bool {
|
||||
return seqWalk(s, from, 0, fn)
|
||||
}
|
||||
|
||||
func seqWalk[T any](s *seq[T], from, base int, fn func(i int, v *T) bool) bool {
|
||||
if s == nil || from >= s.n {
|
||||
return true
|
||||
}
|
||||
if s.left == nil {
|
||||
for k := max(from, 0); k < len(s.items); k++ {
|
||||
if !fn(base+k, &s.items[k]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
if from < s.left.n && !seqWalk(s.left, from, base, fn) {
|
||||
return false
|
||||
}
|
||||
return seqWalk(s.right, from-s.left.n, base+s.left.n, fn)
|
||||
}
|
||||
Vendored
+739
@@ -0,0 +1,739 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo/ui"
|
||||
"iter"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/egoist/mygo/internal/rope"
|
||||
)
|
||||
|
||||
// Text is text whose runs have attributes of their own, in
|
||||
// paragraphs that have a style of their own: what an Editor edits,
|
||||
// as Foundation's AttributedString is what SwiftUI's TextEditor edits. It
|
||||
// is a value: methods return a new text and leave the one they are called
|
||||
// on as it was, sharing what did not change with it, so that keeping a
|
||||
// version (for undo, to save it later, to compare) costs a pointer, and a
|
||||
// version can be read from any goroutine while others are made. The zero
|
||||
// value is the empty text.
|
||||
//
|
||||
// Offsets count runes, newlines included, as Element.TextSelection does.
|
||||
// Paragraphs end at newlines; the style of a paragraph and the attributes
|
||||
// of its newline belong to it, as in word processors, so that an empty
|
||||
// paragraph remembers the attributes typing gets there. Runs are kept as
|
||||
// long as they can be: neighbors with the same attributes are one run.
|
||||
type Text struct {
|
||||
text *rope.Node
|
||||
paras *seq[richPara]
|
||||
}
|
||||
|
||||
// Attributes are the attributes of a run of an Text. What
|
||||
// they leave zero takes the style of the editor showing the text (its
|
||||
// font, size and color), and Italic, Underline, Strikethrough and Code only
|
||||
// turn those on. They are comparable: runs with equal attributes are one.
|
||||
type Attributes struct {
|
||||
// Font is a family, as for Element.Font.
|
||||
Font string
|
||||
// Size is in DIPs.
|
||||
Size float32
|
||||
// Weight goes from 100 (thin) to 900 (black): 700 is bold.
|
||||
Weight int
|
||||
Italic bool
|
||||
Underline bool
|
||||
Strikethrough bool
|
||||
// Color colors the text, Background highlights it.
|
||||
Color, Background ui.Color
|
||||
// Code shows inline code, in the editor's monospaced font. Typing at
|
||||
// its edges does not continue it.
|
||||
Code bool
|
||||
// Link is a URL the run links to. Typing at its edges does not
|
||||
// continue it, as in NSTextView.
|
||||
Link string
|
||||
// Tag is the app's own mark over the run, as a mention or a comment's
|
||||
// ID: typing at its edges does not continue it, and the app styles it
|
||||
// with EditorOptions.TagStyle.
|
||||
Tag string
|
||||
// Attachment is what an object replacement character (U+FFFC) shows:
|
||||
// an image, or a drawing of the app's, inside the line. Only that
|
||||
// character takes it.
|
||||
Attachment *Attachment
|
||||
}
|
||||
|
||||
// Bold reports whether the run is bold: its weight is 600 or more.
|
||||
func (a Attributes) Bold() bool { return a.Weight >= 600 }
|
||||
|
||||
// extends reports whether typing right after a run with the attributes
|
||||
// continues it. Links, code and tags hold only what they hold, as
|
||||
// NSTextView and the expand rules of Peritext and Loro leave them; every
|
||||
// other attribute carries on to what is typed after it.
|
||||
func (a Attributes) extending() Attributes {
|
||||
a.Link, a.Code, a.Tag, a.Attachment = "", false, "", nil
|
||||
return a
|
||||
}
|
||||
|
||||
// Attachment is an object inside an Text, as an image in a note:
|
||||
// one object replacement character (U+FFFC) whose Attributes hold it,
|
||||
// which the editor lays out as a box of its size inside the line, on the
|
||||
// baseline, and selects, copies and deletes as one character.
|
||||
type Attachment struct {
|
||||
// Image is drawn in the box, unless Draw draws it.
|
||||
Image ui.ImageSource
|
||||
// Width and Height are the size of the box in DIPs; zero takes the
|
||||
// image's size. A box wider than the editor is scaled down to fit.
|
||||
Width, Height float32
|
||||
// Name describes the attachment to assistive technology, and stands
|
||||
// for it in plain text: an image's alternative text, a file's name.
|
||||
Name string
|
||||
// URL is where the attachment comes from, as a file's or an image's,
|
||||
// which HTML and Markdown write for it.
|
||||
URL string
|
||||
// Draw draws the attachment in r, instead of Image, as an app's chip
|
||||
// for a mention or a file.
|
||||
Draw func(p *ui.Painter, r ui.Rect)
|
||||
// Data is the app's.
|
||||
Data any
|
||||
}
|
||||
|
||||
// size returns the size of the box of the attachment.
|
||||
func (a *Attachment) size() (w, h float32) {
|
||||
w, h = a.Width, a.Height
|
||||
if a.Image != nil && (w <= 0 || h <= 0) {
|
||||
iw, ih := ui.ImageSize(a.Image)
|
||||
switch {
|
||||
case w <= 0 && h <= 0:
|
||||
w, h = iw, ih
|
||||
case w <= 0 && ih > 0:
|
||||
w = h * iw / ih
|
||||
case h <= 0 && iw > 0:
|
||||
h = w * ih / iw
|
||||
}
|
||||
}
|
||||
return max(w, 1), max(h, 1)
|
||||
}
|
||||
|
||||
// ObjectReplacement is the character an Attachment takes in a text.
|
||||
const ObjectReplacement = ''
|
||||
|
||||
// ListKind is what a paragraph is an item of.
|
||||
type ListKind uint8
|
||||
|
||||
const (
|
||||
NoList ListKind = iota
|
||||
// Bullets is an unordered list.
|
||||
Bullets
|
||||
// Numbers is an ordered list, numbered from 1 among the items of one
|
||||
// level next to each other.
|
||||
Numbers
|
||||
// Tasks is a checklist, whose items are Checked or not.
|
||||
Tasks
|
||||
)
|
||||
|
||||
// normalized returns the style with its levels in range, as text pasted
|
||||
// or loaded may have any.
|
||||
func (s ParagraphStyle) normalized() ParagraphStyle {
|
||||
s.Heading = max(0, min(s.Heading, 6))
|
||||
s.Indent = max(0, min(s.Indent, maxIndent))
|
||||
if s.List > Tasks {
|
||||
s.List = NoList
|
||||
}
|
||||
if s.List != Tasks {
|
||||
s.Checked = false
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ParagraphStyle is the style of a paragraph of an Text: what it
|
||||
// is (a heading, an item of a list, a quote, a block of code) and how its
|
||||
// lines align. Lists are flat, as in Quill and Automerge: an item's Indent
|
||||
// is its level, and items next to each other make a list.
|
||||
type ParagraphStyle struct {
|
||||
// Heading is the level of a heading, from 1, or 0 for a body
|
||||
// paragraph.
|
||||
Heading int `json:"heading,omitempty"`
|
||||
List ListKind `json:"list,omitempty"`
|
||||
// Checked marks a task done.
|
||||
Checked bool `json:"checked,omitempty"`
|
||||
// Indent is how many levels the paragraph is indented: the level of a
|
||||
// list's item, from 0.
|
||||
Indent int `json:"indent,omitempty"`
|
||||
// Align aligns its lines: Start (the default), Center or End.
|
||||
Align ui.Align `json:"align,omitempty"`
|
||||
// Quote and CodeBlock show the paragraph as a quotation, or as code in
|
||||
// the monospaced font, its spaces kept.
|
||||
Quote bool `json:"quote,omitempty"`
|
||||
// QuoteDepth is the number of nested quotations when Quote is true.
|
||||
// Zero and one both mean one quotation, for existing documents. It is
|
||||
// independent of Indent, which remains the nesting level of a list item.
|
||||
QuoteDepth int `json:"quoteDepth,omitempty"`
|
||||
CodeBlock bool `json:"codeBlock,omitempty"`
|
||||
// ID is the app's name for the paragraph, the key of what it keeps
|
||||
// about it, which the editor does not show. It stays with the
|
||||
// paragraph's text as it is edited (see Text.Replace): a paragraph
|
||||
// split keeps it in its first half (the second when split at its
|
||||
// start), paragraphs joined keep the first's, and the paragraphs an
|
||||
// edit makes have none, unless the document names them
|
||||
// (Document.IdentifyParagraphs). Undo brings it
|
||||
// back with the text, JSON saves it, and the clipboard, Markdown,
|
||||
// HTML and RTF leave it out.
|
||||
ID string `json:"id,omitempty"`
|
||||
}
|
||||
|
||||
// quoteDepth is the effective quotation nesting of a paragraph.
|
||||
func (s ParagraphStyle) quoteDepth() int {
|
||||
if !s.Quote {
|
||||
return 0
|
||||
}
|
||||
return max(1, s.QuoteDepth)
|
||||
}
|
||||
|
||||
// Run is a run of text with its attributes.
|
||||
type Run struct {
|
||||
Text string
|
||||
Attributes Attributes
|
||||
}
|
||||
|
||||
// Paragraph is a paragraph of an Text: its style and its runs,
|
||||
// without its newline.
|
||||
type Paragraph struct {
|
||||
Style ParagraphStyle
|
||||
Runs []Run
|
||||
}
|
||||
|
||||
// richPara is a paragraph of an Text. Its runs hold its runes
|
||||
// and, last, its end: its newline, or for the last paragraph the end of the
|
||||
// text, whose attributes are those typing gets in an empty paragraph. They
|
||||
// are as long as they can be, none empty: n+1 runes in all.
|
||||
type richPara struct {
|
||||
id uint64
|
||||
style ParagraphStyle
|
||||
n int // runes, without the end
|
||||
runs []attrRun
|
||||
}
|
||||
|
||||
type attrRun struct {
|
||||
n int
|
||||
a Attributes
|
||||
}
|
||||
|
||||
// paraIDs numbers the paragraphs of every text, so that a paragraph keeps
|
||||
// its identity as the text changes around it, for layouts and, one day,
|
||||
// collaboration.
|
||||
var paraIDs atomic.Uint64
|
||||
|
||||
func newPara(style ParagraphStyle, runs []attrRun) richPara {
|
||||
p := richPara{id: paraIDs.Add(1), style: style.normalized(), runs: runs}
|
||||
for _, r := range runs {
|
||||
p.n += r.n
|
||||
}
|
||||
p.n--
|
||||
return p
|
||||
}
|
||||
|
||||
// emptyParas is the paragraph of the empty text.
|
||||
var emptyParas = seqLeaf([]richPara{{runs: []attrRun{{n: 1}}}})
|
||||
|
||||
func (t Text) seq() *seq[richPara] {
|
||||
if t.paras == nil {
|
||||
return emptyParas
|
||||
}
|
||||
return t.paras
|
||||
}
|
||||
|
||||
// NewText returns s as an Text, without attributes.
|
||||
func NewText(s string) Text {
|
||||
return TextOf(Paragraph{Runs: []Run{{Text: s}}})
|
||||
}
|
||||
|
||||
// TextOf returns an Text of paragraphs. A newline in a
|
||||
// run starts another paragraph of the same style, without its ID.
|
||||
//
|
||||
// ui.TextOf(
|
||||
// ui.Paragraph{Style: ui.ParagraphStyle{Heading: 1}, Runs: []ui.Run{{Text: "Groceries"}}},
|
||||
// ui.Paragraph{Style: ui.ParagraphStyle{List: ui.Tasks}, Runs: []ui.Run{{Text: "Milk"}}},
|
||||
// )
|
||||
func TextOf(paragraphs ...Paragraph) Text {
|
||||
if len(paragraphs) == 0 {
|
||||
return Text{}
|
||||
}
|
||||
var lines []string
|
||||
var paras []richPara
|
||||
for _, p := range paragraphs {
|
||||
var line strings.Builder
|
||||
var runs []attrRun
|
||||
var last Attributes
|
||||
for _, r := range p.Runs {
|
||||
last = r.Attributes
|
||||
rest := r.Text
|
||||
for {
|
||||
part, after, more := strings.Cut(rest, "\n")
|
||||
line.WriteString(part)
|
||||
runs = appendRuns(runs, part, r.Attributes)
|
||||
if !more {
|
||||
break
|
||||
}
|
||||
lines = append(lines, line.String())
|
||||
paras = append(paras, newPara(p.Style, appendRun(runs, attrRun{1, r.Attributes.extending()})))
|
||||
line.Reset()
|
||||
runs = nil
|
||||
rest = after
|
||||
p.Style.ID = ""
|
||||
}
|
||||
}
|
||||
lines = append(lines, line.String())
|
||||
paras = append(paras, newPara(p.Style, appendRun(runs, attrRun{1, last.extending()})))
|
||||
}
|
||||
return Text{text: rope.Build(strings.Join(lines, "\n")), paras: seqBuild(paras)}
|
||||
}
|
||||
|
||||
// appendRuns appends the runs of s with attributes a: an object
|
||||
// replacement character is a run of its own, where a holds an attachment,
|
||||
// which no other rune takes.
|
||||
func appendRuns(runs []attrRun, s string, a Attributes) []attrRun {
|
||||
if s == "" {
|
||||
return runs
|
||||
}
|
||||
if a.Attachment == nil {
|
||||
return appendRun(runs, attrRun{utf8.RuneCountInString(s), a})
|
||||
}
|
||||
plain := a
|
||||
plain.Attachment = nil
|
||||
for _, r := range s {
|
||||
if r == ObjectReplacement {
|
||||
runs = appendRun(runs, attrRun{1, a})
|
||||
} else {
|
||||
runs = appendRun(runs, attrRun{1, plain})
|
||||
}
|
||||
}
|
||||
return runs
|
||||
}
|
||||
|
||||
// appendRun appends r, joining it to the last run when they have the same
|
||||
// attributes: runs holding an attachment are never joined.
|
||||
func appendRun(runs []attrRun, r attrRun) []attrRun {
|
||||
if r.n <= 0 {
|
||||
return runs
|
||||
}
|
||||
if k := len(runs) - 1; k >= 0 && runs[k].a == r.a && r.a.Attachment == nil {
|
||||
runs[k].n += r.n
|
||||
return runs
|
||||
}
|
||||
return append(runs, r)
|
||||
}
|
||||
|
||||
// cutRuns returns the runs from rune from up to rune to of runs, appended
|
||||
// to dst.
|
||||
func cutRuns(dst, runs []attrRun, from, to int) []attrRun {
|
||||
at := 0
|
||||
for _, r := range runs {
|
||||
a, z := max(at, from), min(at+r.n, to)
|
||||
if a < z {
|
||||
dst = appendRun(dst, attrRun{z - a, r.a})
|
||||
}
|
||||
at += r.n
|
||||
if at >= to {
|
||||
break
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
// Len returns the number of runes of the text, newlines included.
|
||||
func (t Text) Len() int { return rope.Sum(t.text).Runes }
|
||||
|
||||
// String returns the text without its attributes.
|
||||
func (t Text) String() string { return rope.TextOf(t.text).String() }
|
||||
|
||||
// ParagraphCount returns the number of paragraphs: one more than the
|
||||
// newlines.
|
||||
func (t Text) ParagraphCount() int { return rope.Sum(t.text).Lines + 1 }
|
||||
|
||||
// Same reports whether t and u are the same version of a text, without
|
||||
// comparing them: a text is the same as what it was copied from.
|
||||
func (t Text) Same(u Text) bool { return t.text == u.text && t.paras == u.paras }
|
||||
|
||||
// Equal reports whether t and u hold the same text with the same
|
||||
// attributes and paragraph styles.
|
||||
func (t Text) Equal(u Text) bool {
|
||||
if t.Same(u) {
|
||||
return true
|
||||
}
|
||||
if t.Len() != u.Len() || t.ParagraphCount() != u.ParagraphCount() || t.String() != u.String() {
|
||||
return false
|
||||
}
|
||||
equal := true
|
||||
us := u.seq()
|
||||
seqEach(t.seq(), 0, func(i int, p *richPara) bool {
|
||||
q := seqAt(us, i)
|
||||
equal = p.style == q.style && slices.Equal(p.runs, q.runs)
|
||||
return equal
|
||||
})
|
||||
return equal
|
||||
}
|
||||
|
||||
// paraAt returns the paragraph holding rune i, whose newline is its.
|
||||
func (t Text) paraAt(i int) int {
|
||||
i = max(0, min(i, t.Len()))
|
||||
return rope.Prefix(t.text, rope.ByteOfRune(t.text, i)).Lines
|
||||
}
|
||||
|
||||
// paraStart returns the rune paragraph p starts at.
|
||||
func (t Text) paraStart(p int) int {
|
||||
if p <= 0 {
|
||||
return 0
|
||||
}
|
||||
return rope.Prefix(t.text, rope.LineStart(t.text, p)).Runes
|
||||
}
|
||||
|
||||
// ParagraphRange returns where the paragraph holding rune i starts and
|
||||
// ends, before its newline.
|
||||
func (t Text) ParagraphRange(i int) (start, end int) {
|
||||
p := t.paraAt(i)
|
||||
start = t.paraStart(p)
|
||||
return start, start + seqAt(t.seq(), p).n
|
||||
}
|
||||
|
||||
// AttributesAt returns the attributes of rune i, or those of the end of
|
||||
// the text for its length.
|
||||
func (t Text) AttributesAt(i int) Attributes {
|
||||
p := t.paraAt(i)
|
||||
return seqAt(t.seq(), p).attributesAt(i - t.paraStart(p))
|
||||
}
|
||||
|
||||
// attributesAt returns the attributes of rune i of the paragraph, its end
|
||||
// for its length.
|
||||
func (p *richPara) attributesAt(i int) Attributes {
|
||||
at := 0
|
||||
for _, r := range p.runs {
|
||||
at += r.n
|
||||
if i < at {
|
||||
return r.a
|
||||
}
|
||||
}
|
||||
return p.runs[len(p.runs)-1].a
|
||||
}
|
||||
|
||||
// ParagraphStyleAt returns the style of the paragraph holding rune i.
|
||||
func (t Text) ParagraphStyleAt(i int) ParagraphStyle {
|
||||
return seqAt(t.seq(), t.paraAt(i)).style
|
||||
}
|
||||
|
||||
// Paragraphs returns the paragraphs of the text, with the rune each starts
|
||||
// at.
|
||||
func (t Text) Paragraphs() iter.Seq2[int, Paragraph] {
|
||||
return func(yield func(int, Paragraph) bool) {
|
||||
start := 0
|
||||
tx := rope.TextOf(t.text)
|
||||
// Each line starts after the newline of the one before: the walk
|
||||
// carries the byte it starts at on, rather than finding each line
|
||||
// in the tree, which reads its chunk from the start every time.
|
||||
lineAt := 0
|
||||
seqEach(t.seq(), 0, func(_ int, p *richPara) bool {
|
||||
lineEnd := rope.ByteAfterRunes(t.text, lineAt, p.n)
|
||||
line := tx.Slice(lineAt, lineEnd)
|
||||
lineAt = lineEnd + 1
|
||||
par := Paragraph{Style: p.style}
|
||||
off := 0
|
||||
for _, r := range p.runs {
|
||||
if off >= len(line) {
|
||||
break
|
||||
}
|
||||
end := off
|
||||
for k := 0; k < r.n && end < len(line); k++ {
|
||||
_, size := utf8.DecodeRuneInString(line[end:])
|
||||
end += size
|
||||
}
|
||||
par.Runs = append(par.Runs, Run{Text: line[off:end], Attributes: r.a})
|
||||
off = end
|
||||
}
|
||||
if !yield(start, par) {
|
||||
return false
|
||||
}
|
||||
start += p.n + 1
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Runs returns the runs of the text from rune start to rune end, with the
|
||||
// rune each starts at: the newline ending a paragraph is a run of its own,
|
||||
// or ends the paragraph's last run when it has the same attributes.
|
||||
func (t Text) Runs(start, end int) iter.Seq2[int, Run] {
|
||||
return func(yield func(int, Run) bool) {
|
||||
n := t.Len()
|
||||
start, end = max(0, min(start, n)), max(0, min(end, n))
|
||||
if start >= end {
|
||||
return
|
||||
}
|
||||
tx := rope.TextOf(t.text)
|
||||
pa := t.paraAt(start)
|
||||
at := t.paraStart(pa)
|
||||
// The byte rune at starts at: found in the tree for the first run,
|
||||
// then carried on from one run to the next, each run's end read on
|
||||
// from its start.
|
||||
off := -1
|
||||
seqEach(t.seq(), pa, func(_ int, p *richPara) bool {
|
||||
for _, r := range p.runs {
|
||||
if at+r.n <= start {
|
||||
at += r.n
|
||||
continue
|
||||
}
|
||||
a, z := max(at, start), min(at+r.n, end, n)
|
||||
if off < 0 {
|
||||
off = rope.ByteOfRune(t.text, a)
|
||||
}
|
||||
bz := rope.ByteAfterRunes(t.text, off, z-a)
|
||||
if !yield(a, Run{Text: tx.Slice(off, bz), Attributes: r.a}) {
|
||||
return false
|
||||
}
|
||||
// A run cut short by end or the end of the text is the last.
|
||||
off = bz
|
||||
at += r.n
|
||||
if at >= end {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Slice returns the runes from start to end with their attributes and the
|
||||
// styles of their paragraphs.
|
||||
func (t Text) Slice(start, end int) Text {
|
||||
n := t.Len()
|
||||
start, end = max(0, min(start, n)), max(0, min(end, n))
|
||||
if start >= end {
|
||||
return Text{}
|
||||
}
|
||||
pa, pz := t.paraAt(start), t.paraAt(end)
|
||||
sa, sz := t.paraStart(pa), t.paraStart(pz)
|
||||
paras := make([]richPara, 0, pz-pa+1)
|
||||
seqEach(t.seq(), pa, func(i int, p *richPara) bool {
|
||||
from, to := 0, p.n+1
|
||||
if i == pa {
|
||||
from = start - sa
|
||||
}
|
||||
last := i == pz
|
||||
if last {
|
||||
to = end - sz
|
||||
}
|
||||
runs := cutRuns(nil, p.runs, from, to)
|
||||
n := to - from - 1
|
||||
if last {
|
||||
runs = appendRun(runs, attrRun{1, p.runs[len(p.runs)-1].a})
|
||||
n++
|
||||
}
|
||||
paras = append(paras, richPara{id: p.id, style: p.style, n: n, runs: runs})
|
||||
return !last
|
||||
})
|
||||
_, rest := rope.Split(t.text, rope.ByteOfRune(t.text, start))
|
||||
mid, _ := rope.Split(rest, rope.ByteOfRune(rest, end-start))
|
||||
return Text{text: mid, paras: seqBuild(paras)}
|
||||
}
|
||||
|
||||
// Replace returns the text with the runes from start to end replaced by
|
||||
// with. Paragraphs joined or split take the style of the one their first
|
||||
// rune comes from, as AppKit fixes paragraph styles: deleting the newline
|
||||
// after a heading keeps the heading, and text put at the start of a
|
||||
// paragraph brings its own paragraph's style.
|
||||
//
|
||||
// The IDs of paragraphs follow their text instead, and never come from
|
||||
// with, so that no two paragraphs get one ID: a paragraph split keeps its
|
||||
// ID in the first half, or in the second when split at its start, as
|
||||
// Enter there moves the paragraph down; the new paragraphs have none; and
|
||||
// paragraphs joined keep the first's, unless nothing of it is left.
|
||||
func (t Text) Replace(start, end int, with Text) Text {
|
||||
n := t.Len()
|
||||
start, end = max(0, min(start, end, n)), max(0, min(max(start, end), n))
|
||||
pa, pz := t.paraAt(start), t.paraAt(end)
|
||||
sa, sz := t.paraStart(pa), t.paraStart(pz)
|
||||
s := t.seq()
|
||||
first, last := seqAt(s, pa), seqAt(s, pz)
|
||||
head := cutRuns(nil, first.runs, 0, start-sa)
|
||||
tail := cutRuns(nil, last.runs, end-sz, last.n+1)
|
||||
headN, tailN := start-sa, last.n-(end-sz)
|
||||
|
||||
var frag []richPara
|
||||
seqEach(with.seq(), 0, func(_ int, p *richPara) bool {
|
||||
frag = append(frag, *p)
|
||||
return true
|
||||
})
|
||||
out := make([]richPara, 0, len(frag))
|
||||
if len(frag) == 1 {
|
||||
f := frag[0]
|
||||
runs := cutRuns(head, f.runs, 0, f.n)
|
||||
runs = cutRuns(runs, tail, 0, tailN+1)
|
||||
style := last.style
|
||||
switch {
|
||||
case headN > 0:
|
||||
style = first.style
|
||||
case f.n > 0:
|
||||
style = f.style
|
||||
}
|
||||
style.ID = last.style.ID
|
||||
if headN > 0 || f.n > 0 {
|
||||
style.ID = first.style.ID
|
||||
}
|
||||
out = append(out, richPara{id: first.id, style: style, n: headN + f.n + tailN, runs: runs})
|
||||
} else {
|
||||
// Split at its start, the paragraph's text goes to the last part,
|
||||
// with its ID.
|
||||
moved := pa == pz && headN == 0
|
||||
f := frag[0]
|
||||
style := f.style
|
||||
if headN > 0 {
|
||||
style = first.style
|
||||
}
|
||||
style.ID = first.style.ID
|
||||
if moved {
|
||||
style.ID = ""
|
||||
}
|
||||
out = append(out, richPara{id: first.id, style: style, n: headN + f.n, runs: cutRuns(head, f.runs, 0, f.n+1)})
|
||||
for _, f := range frag[1 : len(frag)-1] {
|
||||
f.id = paraIDs.Add(1)
|
||||
f.style.ID = ""
|
||||
out = append(out, f)
|
||||
}
|
||||
f = frag[len(frag)-1]
|
||||
style, id := last.style, paraIDs.Add(1)
|
||||
if f.n > 0 {
|
||||
style = f.style
|
||||
}
|
||||
style.ID = ""
|
||||
switch {
|
||||
case pz != pa:
|
||||
id = last.id
|
||||
style.ID = last.style.ID
|
||||
case moved:
|
||||
style.ID = first.style.ID
|
||||
}
|
||||
runs := cutRuns(nil, f.runs, 0, f.n)
|
||||
runs = cutRuns(runs, tail, 0, tailN+1)
|
||||
out = append(out, richPara{id: id, style: style, n: f.n + tailN, runs: runs})
|
||||
}
|
||||
left, rest := rope.Split(t.text, rope.ByteOfRune(t.text, start))
|
||||
_, right := rope.Split(rest, rope.ByteOfRune(rest, end-start))
|
||||
return Text{
|
||||
text: rope.Join(rope.Join(left, with.text), right),
|
||||
paras: seqReplace(s, pa, pz+1, out),
|
||||
}
|
||||
}
|
||||
|
||||
// ReplaceString returns the text with the runes from start to end replaced
|
||||
// by s, which takes attributes a and, for the paragraphs it adds, the style
|
||||
// of the paragraph holding start.
|
||||
func (t Text) ReplaceString(start, end int, s string, a Attributes) Text {
|
||||
style := t.ParagraphStyleAt(start)
|
||||
var frag []richPara
|
||||
for rest := s; ; {
|
||||
line, after, more := strings.Cut(rest, "\n")
|
||||
runs := appendRuns(nil, line, a)
|
||||
frag = append(frag, richPara{style: style, n: utf8.RuneCountInString(line), runs: appendRun(runs, attrRun{1, a.extending()})})
|
||||
if !more {
|
||||
break
|
||||
}
|
||||
rest = after
|
||||
}
|
||||
return t.Replace(start, end, Text{text: rope.Build(s), paras: seqBuild(frag)})
|
||||
}
|
||||
|
||||
// Insert returns the text with with inserted at rune i.
|
||||
func (t Text) Insert(i int, with Text) Text { return t.Replace(i, i, with) }
|
||||
|
||||
// Delete returns the text without the runes from start to end.
|
||||
func (t Text) Delete(start, end int) Text {
|
||||
return t.Replace(start, end, Text{})
|
||||
}
|
||||
|
||||
// Append returns the text followed by s with attributes a.
|
||||
func (t Text) Append(s string, a Attributes) Text {
|
||||
n := t.Len()
|
||||
return t.ReplaceString(n, n, s, a)
|
||||
}
|
||||
|
||||
// Format returns the text with fn changing the attributes of the runes
|
||||
// from start to end, newlines included. fn cannot add or take away an
|
||||
// attachment, which only an object replacement character has.
|
||||
func (t Text) Format(start, end int, fn func(a *Attributes)) Text {
|
||||
n := t.Len()
|
||||
start, end = max(0, min(start, n)), max(0, min(end, n))
|
||||
if start >= end {
|
||||
return t
|
||||
}
|
||||
pa, pz := t.paraAt(start), t.paraAt(end)
|
||||
if end == t.paraStart(pz) && pz > pa && end < n {
|
||||
pz-- // up to the newline ending the paragraph before
|
||||
}
|
||||
at := t.paraStart(pa)
|
||||
out := make([]richPara, 0, pz-pa+1)
|
||||
changed := false
|
||||
seqEach(t.seq(), pa, func(i int, p *richPara) bool {
|
||||
from, to := max(start-at, 0), min(end-at, p.n+1)
|
||||
if end == n && i == pz {
|
||||
// To the end of the text: what typing gets there too.
|
||||
to = p.n + 1
|
||||
}
|
||||
runs := cutRuns(nil, p.runs, 0, from)
|
||||
mid := cutRuns(nil, p.runs, from, to)
|
||||
for _, r := range mid {
|
||||
b := r.a
|
||||
fn(&b)
|
||||
b.Attachment = r.a.Attachment
|
||||
changed = changed || b != r.a
|
||||
runs = appendRun(runs, attrRun{r.n, b})
|
||||
}
|
||||
runs = cutRuns(runs, p.runs, to, p.n+1)
|
||||
q := *p
|
||||
q.runs = runs
|
||||
out = append(out, q)
|
||||
at += p.n + 1
|
||||
return i < pz
|
||||
})
|
||||
if !changed {
|
||||
return t
|
||||
}
|
||||
return Text{text: t.text, paras: seqReplace(t.seq(), pa, pz+1, out)}
|
||||
}
|
||||
|
||||
// FormatParagraphs returns the text with fn changing the styles of the
|
||||
// paragraphs from the one holding start to the one holding end, but for a
|
||||
// paragraph end only starts, after a selection of whole paragraphs.
|
||||
func (t Text) FormatParagraphs(start, end int, fn func(p *ParagraphStyle)) Text {
|
||||
pa, pz := t.paragraphSpan(start, end)
|
||||
return t.formatParas(pa, pz, fn)
|
||||
}
|
||||
|
||||
// formatParas returns the text with fn changing the styles of paragraphs
|
||||
// pa to pz.
|
||||
func (t Text) formatParas(pa, pz int, fn func(p *ParagraphStyle)) Text {
|
||||
out := make([]richPara, 0, pz-pa+1)
|
||||
changed := false
|
||||
seqEach(t.seq(), pa, func(i int, p *richPara) bool {
|
||||
q := *p
|
||||
fn(&q.style)
|
||||
q.style = q.style.normalized()
|
||||
changed = changed || q.style != p.style
|
||||
out = append(out, q)
|
||||
return i < pz
|
||||
})
|
||||
if !changed {
|
||||
return t
|
||||
}
|
||||
return Text{text: t.text, paras: seqReplace(t.seq(), pa, pz+1, out)}
|
||||
}
|
||||
|
||||
// paragraphSpan returns the paragraphs a selection from start to end
|
||||
// formats: those it touches, but for the one after a selection ending at
|
||||
// its start.
|
||||
func (t Text) paragraphSpan(start, end int) (int, int) {
|
||||
n := t.Len()
|
||||
start, end = max(0, min(start, end, n)), max(0, min(max(start, end), n))
|
||||
pa, pz := t.paraAt(start), t.paraAt(end)
|
||||
if end > start && pz > pa && end == t.paraStart(pz) {
|
||||
pz--
|
||||
}
|
||||
return pa, pz
|
||||
}
|
||||
+365
@@ -0,0 +1,365 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo/ui"
|
||||
"math/rand/v2"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// cell is a rune of a naive attributed text: its attributes and the style
|
||||
// of the paragraph it came from.
|
||||
type cell struct {
|
||||
r rune
|
||||
a Attributes
|
||||
style ParagraphStyle
|
||||
}
|
||||
|
||||
// naive is an attributed text as a cell per rune, and a last one for the
|
||||
// end of the text.
|
||||
type naive []cell
|
||||
|
||||
func naiveOf(t Text) naive {
|
||||
var out naive
|
||||
for _, p := range t.Paragraphs() {
|
||||
_ = p
|
||||
}
|
||||
i := 0
|
||||
for start, p := range t.Paragraphs() {
|
||||
_ = start
|
||||
for _, r := range p.Runs {
|
||||
for _, c := range r.Text {
|
||||
out = append(out, cell{c, r.Attributes, p.Style})
|
||||
i++
|
||||
}
|
||||
}
|
||||
end := t.AttributesAt(i)
|
||||
r := '\n'
|
||||
if i == t.Len() {
|
||||
r = 0
|
||||
}
|
||||
out = append(out, cell{r, end, p.Style})
|
||||
i++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// normalize gives every cell of a paragraph the style of its first, as
|
||||
// Text keeps one style a paragraph.
|
||||
func (n naive) normalize() naive {
|
||||
start := 0
|
||||
for i, c := range n {
|
||||
if c.r == '\n' || c.r == 0 {
|
||||
for k := start; k <= i; k++ {
|
||||
n[k].style = n[start].style
|
||||
}
|
||||
start = i + 1
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (n naive) String() string {
|
||||
var b strings.Builder
|
||||
for _, c := range n[:len(n)-1] {
|
||||
b.WriteRune(c.r)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func checkInvariants(t *testing.T, at Text) {
|
||||
t.Helper()
|
||||
s := at.String()
|
||||
lines := strings.Split(s, "\n")
|
||||
if at.ParagraphCount() != len(lines) || seqLen(at.seq()) != len(lines) {
|
||||
t.Fatalf("%d paragraphs, %d in the sequence, %d lines", at.ParagraphCount(), seqLen(at.seq()), len(lines))
|
||||
}
|
||||
seqEach(at.seq(), 0, func(i int, p *richPara) bool {
|
||||
sum := 0
|
||||
for k, r := range p.runs {
|
||||
if r.n <= 0 {
|
||||
t.Fatalf("paragraph %d: empty run", i)
|
||||
}
|
||||
if k > 0 && p.runs[k-1].a == r.a && r.a.Attachment == nil {
|
||||
t.Fatalf("paragraph %d: runs %d and %d not joined", i, k-1, k)
|
||||
}
|
||||
sum += r.n
|
||||
}
|
||||
if want := len([]rune(lines[i])); p.n != want || sum != want+1 {
|
||||
t.Fatalf("paragraph %d: n %d, runs %d, line %q", i, p.n, sum, lines[i])
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func compareNaive(t *testing.T, at Text, want naive) {
|
||||
t.Helper()
|
||||
checkInvariants(t, at)
|
||||
got := naiveOf(at)
|
||||
if got.String() != want.String() {
|
||||
t.Fatalf("text %q, want %q", got.String(), want.String())
|
||||
}
|
||||
for i := range got {
|
||||
if got[i].a != want[i].a {
|
||||
t.Fatalf("rune %d of %q: attributes %+v, want %+v", i, got.String(), got[i].a, want[i].a)
|
||||
}
|
||||
if got[i].style != want[i].style {
|
||||
t.Fatalf("rune %d of %q: style %+v, want %+v", i, got.String(), got[i].style, want[i].style)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var testAttrs = []Attributes{{}, {Weight: 700}, {Italic: true}, {Link: "https://a"}, {Weight: 700, Italic: true}, {Color: ui.RGB(200, 0, 0)}}
|
||||
var testStyles = []ParagraphStyle{{}, {Heading: 1}, {List: Bullets}, {List: Numbers, Indent: 1}, {Align: ui.Center}}
|
||||
|
||||
func randomText(rnd *rand.Rand) Text {
|
||||
var paras []Paragraph
|
||||
for range 1 + rnd.IntN(4) {
|
||||
p := Paragraph{Style: testStyles[rnd.IntN(len(testStyles))]}
|
||||
for range rnd.IntN(4) {
|
||||
words := []string{"a", "bc", "déf", "ghij", " ", "😀"}
|
||||
p.Runs = append(p.Runs, Run{Text: words[rnd.IntN(len(words))], Attributes: testAttrs[rnd.IntN(len(testAttrs))]})
|
||||
}
|
||||
paras = append(paras, p)
|
||||
}
|
||||
return TextOf(paras...)
|
||||
}
|
||||
|
||||
func TestAttributedTextOf(t *testing.T) {
|
||||
at := TextOf(
|
||||
Paragraph{Style: ParagraphStyle{Heading: 1}, Runs: []Run{{Text: "Title"}}},
|
||||
Paragraph{Runs: []Run{{Text: "Hello "}, {Text: "bold", Attributes: Attributes{Weight: 700}}, {Text: " and"}, {Text: " more"}}},
|
||||
Paragraph{},
|
||||
)
|
||||
checkInvariants(t, at)
|
||||
if got := at.String(); got != "Title\nHello bold and more\n" {
|
||||
t.Fatalf("text %q", got)
|
||||
}
|
||||
if at.ParagraphStyleAt(2).Heading != 1 || at.ParagraphStyleAt(8).Heading != 0 {
|
||||
t.Fatal("paragraph styles")
|
||||
}
|
||||
var runs []string
|
||||
for _, r := range at.Runs(6, 25) {
|
||||
runs = append(runs, r.Text)
|
||||
}
|
||||
if got := strings.Join(runs, "|"); got != "Hello |bold| and more" {
|
||||
t.Fatalf("runs %q", got)
|
||||
}
|
||||
if !at.AttributesAt(12).Bold() || at.AttributesAt(16).Bold() {
|
||||
t.Fatal("attributes")
|
||||
}
|
||||
if (Text{}).Len() != 0 || (Text{}).ParagraphCount() != 1 {
|
||||
t.Fatal("the zero text")
|
||||
}
|
||||
if !TextOf(Paragraph{Runs: []Run{{Text: "a\nb"}}}).Equal(NewText("a\nb")) {
|
||||
t.Fatal("a newline in a run starts a paragraph")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttributedTextJoinParagraphs(t *testing.T) {
|
||||
at := TextOf(
|
||||
Paragraph{Style: ParagraphStyle{Heading: 1}, Runs: []Run{{Text: "Title"}}},
|
||||
Paragraph{Runs: []Run{{Text: "body"}}},
|
||||
)
|
||||
// Deleting the newline after a heading keeps the heading.
|
||||
joined := at.Delete(5, 6)
|
||||
if joined.String() != "Titlebody" || joined.ParagraphStyleAt(0).Heading != 1 {
|
||||
t.Fatalf("%q %+v", joined.String(), joined.ParagraphStyleAt(0))
|
||||
}
|
||||
// Deleting the heading whole, newline and all, leaves the body.
|
||||
gone := at.Delete(0, 6)
|
||||
if gone.String() != "body" || gone.ParagraphStyleAt(0).Heading != 0 {
|
||||
t.Fatalf("%q %+v", gone.String(), gone.ParagraphStyleAt(0))
|
||||
}
|
||||
// Enter at the end of the heading: both paragraphs are headings, until
|
||||
// the editor makes the new one a body paragraph.
|
||||
split := at.ReplaceString(5, 5, "\n", Attributes{})
|
||||
if split.String() != "Title\n\nbody" || split.ParagraphStyleAt(6).Heading != 1 || split.ParagraphStyleAt(7).Heading != 0 {
|
||||
t.Fatalf("%q", split.String())
|
||||
}
|
||||
if at.String() != "Title\nbody" {
|
||||
t.Fatal("the text changed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttributedTextAttachments(t *testing.T) {
|
||||
img := &Attachment{Name: "photo", Width: 20, Height: 10}
|
||||
at := NewText("ab").ReplaceString(1, 1, "x", Attributes{Attachment: img})
|
||||
checkInvariants(t, at)
|
||||
if at.AttributesAt(1).Attachment != img || at.AttributesAt(2).Attachment != img || at.AttributesAt(3).Attachment != nil {
|
||||
t.Fatal("only object replacement characters hold the attachment")
|
||||
}
|
||||
f := at.Format(0, at.Len(), func(a *Attributes) { a.Weight = 700; a.Attachment = nil })
|
||||
if f.AttributesAt(1).Attachment != img || !f.AttributesAt(1).Bold() {
|
||||
t.Fatal("Format keeps attachments")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAttributedTextLongWalks walks the paragraphs and the runs of a text
|
||||
// of many chunks, of short paragraphs and some longer than a chunk, with
|
||||
// multi-byte runes, and checks them rune by rune against what it was made
|
||||
// of.
|
||||
func TestAttributedTextLongWalks(t *testing.T) {
|
||||
rnd := rand.New(rand.NewPCG(3, 11))
|
||||
words := []string{"a", "bc", "déf", "ghij", " ", "😀", "世界"}
|
||||
var paras []Paragraph
|
||||
var runes []rune
|
||||
var attrs []Attributes
|
||||
for i := range 3000 {
|
||||
p := Paragraph{Style: testStyles[rnd.IntN(len(testStyles))]}
|
||||
k := rnd.IntN(4)
|
||||
if i%97 == 0 {
|
||||
k = 1500
|
||||
}
|
||||
var last Attributes
|
||||
for range k {
|
||||
r := Run{Text: words[rnd.IntN(len(words))], Attributes: testAttrs[rnd.IntN(len(testAttrs))]}
|
||||
p.Runs = append(p.Runs, r)
|
||||
for _, c := range r.Text {
|
||||
runes, attrs = append(runes, c), append(attrs, r.Attributes)
|
||||
}
|
||||
last = r.Attributes
|
||||
}
|
||||
paras = append(paras, p)
|
||||
runes, attrs = append(runes, '\n'), append(attrs, last.extending())
|
||||
}
|
||||
runes = runes[:len(runes)-1]
|
||||
at := TextOf(paras...)
|
||||
checkInvariants(t, at)
|
||||
if at.Len() != len(runes) || at.Len() < 20*1024 {
|
||||
t.Fatalf("%d runes, made of %d", at.Len(), len(runes))
|
||||
}
|
||||
|
||||
i, k := 0, 0
|
||||
for start, p := range at.Paragraphs() {
|
||||
if start != i || p.Style != paras[k].Style.normalized() {
|
||||
t.Fatalf("paragraph %d: starts at %d, want %d; style %+v", k, start, i, p.Style)
|
||||
}
|
||||
for _, r := range p.Runs {
|
||||
for _, c := range r.Text {
|
||||
if runes[i] != c || attrs[i] != r.Attributes {
|
||||
t.Fatalf("paragraph %d, rune %d: %q %+v, want %q %+v", k, i, c, r.Attributes, runes[i], attrs[i])
|
||||
}
|
||||
i++
|
||||
}
|
||||
}
|
||||
if i < len(runes) && runes[i] != '\n' {
|
||||
t.Fatalf("paragraph %d ends at rune %d, before %q", k, i, runes[i])
|
||||
}
|
||||
i, k = i+1, k+1
|
||||
}
|
||||
if k != len(paras) {
|
||||
t.Fatalf("%d paragraphs, want %d", k, len(paras))
|
||||
}
|
||||
|
||||
walk := func(a, z int) {
|
||||
t.Helper()
|
||||
next := a
|
||||
for s, r := range at.Runs(a, z) {
|
||||
if s != next || r.Text == "" {
|
||||
t.Fatalf("Runs(%d, %d): a run of %q at %d, want one at %d", a, z, r.Text, s, next)
|
||||
}
|
||||
for _, c := range r.Text {
|
||||
if runes[next] != c || attrs[next] != r.Attributes {
|
||||
t.Fatalf("Runs(%d, %d), rune %d: %q %+v, want %q %+v", a, z, next, c, r.Attributes, runes[next], attrs[next])
|
||||
}
|
||||
next++
|
||||
}
|
||||
}
|
||||
if next != z {
|
||||
t.Fatalf("Runs(%d, %d) ends at %d", a, z, next)
|
||||
}
|
||||
}
|
||||
walk(0, at.Len())
|
||||
for range 300 {
|
||||
a := rnd.IntN(at.Len() + 1)
|
||||
walk(a, a+rnd.IntN(min(at.Len()-a, 9000)+1))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttributedTextRandom(t *testing.T) {
|
||||
for seed := range uint64(300) {
|
||||
rnd := rand.New(rand.NewPCG(seed, 7))
|
||||
at := randomText(rnd)
|
||||
model := naiveOf(at)
|
||||
compareNaive(t, at, model)
|
||||
for step := range 30 {
|
||||
n := at.Len()
|
||||
a := rnd.IntN(n + 1)
|
||||
z := a + rnd.IntN(n-a+1)
|
||||
switch rnd.IntN(4) {
|
||||
case 0, 1:
|
||||
with := randomText(rnd)
|
||||
if rnd.IntN(3) == 0 {
|
||||
// A piece of the text itself, as a paste.
|
||||
b := rnd.IntN(n + 1)
|
||||
with = at.Slice(b, b+rnd.IntN(n-b+1))
|
||||
}
|
||||
wm := naiveOf(with)
|
||||
next := append(append(append(naive{}, model[:a]...), wm[:len(wm)-1]...), model[z:]...)
|
||||
at, model = at.Replace(a, z, with), next.normalize()
|
||||
case 2:
|
||||
attrs := testAttrs[rnd.IntN(len(testAttrs))]
|
||||
at = at.Format(a, z, func(x *Attributes) { *x = attrs })
|
||||
if z == n && a < z {
|
||||
z++ // to the end of the text, what typing gets there
|
||||
}
|
||||
for i := a; i < z; i++ {
|
||||
model[i].a = attrs
|
||||
model[i].a.Attachment = nil
|
||||
}
|
||||
case 3:
|
||||
style := testStyles[rnd.IntN(len(testStyles))]
|
||||
pa, pz := at.paragraphSpan(a, z)
|
||||
at = at.FormatParagraphs(a, z, func(p *ParagraphStyle) { *p = style })
|
||||
para := 0
|
||||
for i := range model {
|
||||
if para >= pa && para <= pz {
|
||||
model[i].style = style
|
||||
}
|
||||
if model[i].r == '\n' {
|
||||
para++
|
||||
}
|
||||
}
|
||||
}
|
||||
t.Run("", func(t *testing.T) {
|
||||
defer func() {
|
||||
if t.Failed() {
|
||||
t.Logf("seed %d step %d", seed, step)
|
||||
}
|
||||
}()
|
||||
compareNaive(t, at, model)
|
||||
})
|
||||
if t.Failed() {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttributedTextSliceReplace(t *testing.T) {
|
||||
for seed := range uint64(200) {
|
||||
rnd := rand.New(rand.NewPCG(seed, 9))
|
||||
at := randomText(rnd)
|
||||
n := at.Len()
|
||||
a := rnd.IntN(n + 1)
|
||||
z := a + rnd.IntN(n-a+1)
|
||||
// Putting a slice back where it came from changes nothing.
|
||||
if got := at.Replace(a, z, at.Slice(a, z)); got.String() != at.String() || !runsEqual(got, at) {
|
||||
t.Fatalf("seed %d: %q [%d, %d)", seed, at.String(), a, z)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func runsEqual(a, b Text) bool {
|
||||
ma, mb := naiveOf(a), naiveOf(b)
|
||||
if len(ma) != len(mb) {
|
||||
return false
|
||||
}
|
||||
for i := range ma {
|
||||
if ma[i].a != mb[i].a {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
package richtext
|
||||
|
||||
import "github.com/egoist/mygo/ui"
|
||||
|
||||
// Theme is how the editor's text looks: its colors, the font of code, the
|
||||
// styles of headings, and the room of paragraphs, lists, quotations and
|
||||
// blocks of code. What it leaves zero takes the value of DefaultTheme for
|
||||
// the window's theme, so that a theme sets only what it changes:
|
||||
//
|
||||
// richtext.Editor(c, doc, richtext.EditorOptions{Theme: &richtext.Theme{Link: ui.Hex("#7c3aed")}})
|
||||
//
|
||||
// Lengths in ems are times the editor's font size (EditorOptions.Font).
|
||||
type Theme struct {
|
||||
// Text colors text, Muted the placeholder, the text of tasks done and
|
||||
// the boxes of those to do, and Link links.
|
||||
Text, Muted, Link ui.Color
|
||||
// Caret colors the caret, and Selection is behind the text selected.
|
||||
Caret, Selection ui.Color
|
||||
|
||||
// CodeFont is the family of code, the system's monospaced font when
|
||||
// empty, and CodeSize its size in ems: 0.92. Code colors code, within
|
||||
// text and in blocks, the Text color by default.
|
||||
CodeFont string
|
||||
CodeSize float32
|
||||
Code ui.Color
|
||||
// CodeBackground is behind code within text, which it hugs with
|
||||
// rounded corners.
|
||||
CodeBackground ui.Color
|
||||
// CodeBlockBackground fills blocks of code, with corners of
|
||||
// CodeBlockRadius ems (0.3) and CodeBlockPadding ems of room inside:
|
||||
// 0.7 across, and 0.5 at their top and bottom.
|
||||
CodeBlockBackground ui.Color
|
||||
CodeBlockRadius float32
|
||||
CodeBlockPadding [2]float32
|
||||
|
||||
// Headings are the styles of headings of levels 1 to 6.
|
||||
Headings [6]HeadingStyle
|
||||
|
||||
// FirstLineIndent indents the first line of a body paragraph by that
|
||||
// many ems, as printed prose sets paragraphs apart, but for the first
|
||||
// after a heading, a list, a block of code, a paragraph aligned
|
||||
// otherwise (a centered scene break) or an empty one, or the first of
|
||||
// a quotation, which nothing needs to set apart: 0, none. Only
|
||||
// paragraphs aligned at the start take it.
|
||||
FirstLineIndent float32
|
||||
// ParagraphSpacing is the room between two body paragraphs, in ems, as
|
||||
// prose on screens sets paragraphs apart instead: 0, none. A body
|
||||
// paragraph is one that is not a heading, an item of a list or code.
|
||||
ParagraphSpacing float32
|
||||
|
||||
// Indent is how far a level of a list or of indentation goes, in ems,
|
||||
// a list's markers in that room: 1.7.
|
||||
Indent float32
|
||||
// Marker colors the bullets and numbers of lists, the Text color by
|
||||
// default. Checkbox fills the boxes of tasks done, and Checkmark draws
|
||||
// their checks: white.
|
||||
Marker, Checkbox, Checkmark ui.Color
|
||||
// QuoteBar colors the bar along quotations, QuoteBarWidth DIPs wide
|
||||
// (3), and QuoteText their text, the Muted color by default.
|
||||
QuoteBar, QuoteText ui.Color
|
||||
QuoteBarWidth float32
|
||||
|
||||
// Padding is the room around the text of an Editor, in DIPs across
|
||||
// and down: the window theme's Space(3) and Space(2.5). An EditorBase
|
||||
// has none, its room the app's.
|
||||
Padding [2]float32
|
||||
}
|
||||
|
||||
// HeadingStyle is how headings of one level look.
|
||||
type HeadingStyle struct {
|
||||
// Size is their size in ems, and Weight their weight: 700.
|
||||
Size float32
|
||||
Weight int
|
||||
// Color colors them, the Text color by default.
|
||||
Color ui.Color
|
||||
// Top is the room above them in ems of their size, unless they start
|
||||
// the text: 0.6. Bottom is that below them in ems of the text: 0.25.
|
||||
Top, Bottom float32
|
||||
// LineHeight is the height of their lines in ems of their size, as a
|
||||
// type scale gives a heading tighter leading than the text's; zero
|
||||
// takes the text's (EditorOptions.Font.LineHeight). A line is never
|
||||
// shorter than its font's ascent and descent, which differ from one
|
||||
// platform's font to another's (Segoe UI's are 1.33 ems).
|
||||
LineHeight float32
|
||||
}
|
||||
|
||||
// headingSizes are the default sizes of headings, in ems.
|
||||
var headingSizes = [6]float32{1.8, 1.45, 1.2, 1.1, 1, 0.9}
|
||||
|
||||
// DefaultTheme returns the editor's theme in a window's theme: its text,
|
||||
// muted, accent, selection and border colors, code tinted with its text
|
||||
// color, and headings from 1.8 times the text down to 0.9.
|
||||
func DefaultTheme(t *ui.Theme) *Theme {
|
||||
th := defaultTheme(t)
|
||||
return &th
|
||||
}
|
||||
|
||||
func defaultTheme(t *ui.Theme) Theme {
|
||||
th := Theme{
|
||||
Text: t.Text,
|
||||
Muted: t.TextMuted,
|
||||
Link: t.Accent,
|
||||
Caret: t.Accent,
|
||||
Selection: t.Selection,
|
||||
CodeFont: "monospace",
|
||||
CodeSize: 0.92,
|
||||
Code: t.Text,
|
||||
CodeBackground: t.Text.Alpha(0.07),
|
||||
CodeBlockBackground: t.Text.Alpha(0.07),
|
||||
CodeBlockRadius: 0.3,
|
||||
CodeBlockPadding: [2]float32{0.7, 0.5},
|
||||
Indent: 1.7,
|
||||
Marker: t.Text,
|
||||
Checkbox: t.Accent,
|
||||
Checkmark: ui.RGB(255, 255, 255),
|
||||
QuoteBar: t.Border,
|
||||
QuoteText: t.TextMuted,
|
||||
QuoteBarWidth: 3,
|
||||
Padding: [2]float32{t.Space(3), t.Space(2.5)},
|
||||
}
|
||||
for i, size := range headingSizes {
|
||||
th.Headings[i] = HeadingStyle{Size: size, Weight: 700, Color: t.Text, Top: 0.6, Bottom: 0.25}
|
||||
}
|
||||
return th
|
||||
}
|
||||
|
||||
// resolve returns th with what it leaves zero taken from def; the colors
|
||||
// that default to others of th take those. FirstLineIndent and
|
||||
// ParagraphSpacing are none by default, as zero.
|
||||
func resolve(th *Theme, def *Theme) Theme {
|
||||
if th == nil {
|
||||
return *def
|
||||
}
|
||||
out := *th
|
||||
f := func(v *float32, d float32) {
|
||||
if *v == 0 {
|
||||
*v = d
|
||||
}
|
||||
}
|
||||
c := func(v *ui.Color, d ui.Color) {
|
||||
if *v == (ui.Color{}) {
|
||||
*v = d
|
||||
}
|
||||
}
|
||||
c(&out.Text, def.Text)
|
||||
c(&out.Muted, def.Muted)
|
||||
c(&out.Link, def.Link)
|
||||
c(&out.Caret, def.Caret)
|
||||
c(&out.Selection, def.Selection)
|
||||
if out.CodeFont == "" {
|
||||
out.CodeFont = def.CodeFont
|
||||
}
|
||||
f(&out.CodeSize, def.CodeSize)
|
||||
c(&out.Code, out.Text)
|
||||
c(&out.CodeBackground, def.CodeBackground)
|
||||
c(&out.CodeBlockBackground, def.CodeBlockBackground)
|
||||
f(&out.CodeBlockRadius, def.CodeBlockRadius)
|
||||
f(&out.CodeBlockPadding[0], def.CodeBlockPadding[0])
|
||||
f(&out.CodeBlockPadding[1], def.CodeBlockPadding[1])
|
||||
for i := range out.Headings {
|
||||
h, d := &out.Headings[i], def.Headings[i]
|
||||
f(&h.Size, d.Size)
|
||||
if h.Weight == 0 {
|
||||
h.Weight = d.Weight
|
||||
}
|
||||
c(&h.Color, out.Text)
|
||||
f(&h.Top, d.Top)
|
||||
f(&h.Bottom, d.Bottom)
|
||||
}
|
||||
f(&out.Indent, def.Indent)
|
||||
c(&out.Marker, out.Text)
|
||||
c(&out.Checkbox, def.Checkbox)
|
||||
c(&out.Checkmark, def.Checkmark)
|
||||
c(&out.QuoteBar, def.QuoteBar)
|
||||
c(&out.QuoteText, out.Muted)
|
||||
f(&out.QuoteBarWidth, def.QuoteBarWidth)
|
||||
f(&out.Padding[0], def.Padding[0])
|
||||
f(&out.Padding[1], def.Padding[1])
|
||||
return out
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package richtext
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// TestThemeResolve checks that what a theme leaves zero takes the
|
||||
// default, and the colors that follow others follow the theme's.
|
||||
func TestThemeResolve(t *testing.T) {
|
||||
def := DefaultTheme(ui.LightTheme())
|
||||
red := ui.RGB(200, 0, 0)
|
||||
th := resolve(&Theme{Text: red, CodeSize: 0.8, Headings: [6]HeadingStyle{{Size: 2.5}}}, def)
|
||||
if th.Headings[0].Size != 2.5 || th.Headings[0].Weight != 700 || th.Headings[1].Size != def.Headings[1].Size {
|
||||
t.Errorf("headings %+v", th.Headings[:2])
|
||||
}
|
||||
if th.Headings[0].Color != red || th.Marker != red || th.Code != red {
|
||||
t.Errorf("heading %v and marker %v don't follow the text %v", th.Headings[0].Color, th.Marker, red)
|
||||
}
|
||||
if th.CodeSize != 0.8 || th.Indent != def.Indent || th.Link != def.Link || th.QuoteText != def.Muted {
|
||||
t.Errorf("resolved %+v", th)
|
||||
}
|
||||
if got := resolve(nil, def); got != *def {
|
||||
t.Errorf("nil theme %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestThemeLook checks that the theme reaches the spans, fonts and room
|
||||
// of paragraphs.
|
||||
func TestThemeLook(t *testing.T) {
|
||||
link, code, heading := ui.RGB(124, 58, 237), ui.RGB(0, 120, 0), ui.RGB(0, 0, 200)
|
||||
th := &Theme{Link: link, CodeBackground: code, Code: code, CodeFont: "Menlo", CodeSize: 0.8, Indent: 2,
|
||||
CodeBlockPadding: [2]float32{1, 2}, Headings: [6]HeadingStyle{{Size: 3, Weight: 800, Color: heading, Top: 1, Bottom: 0.5}}}
|
||||
v := &view{opts: EditorOptions{Theme: th, Font: ui.Font{Size: 10}}}
|
||||
v.setLook(ui.LightTheme(), false)
|
||||
look := &v.look
|
||||
if s := look.span("x", Attributes{Link: "https://x"}, ParagraphStyle{}); s.Color != link {
|
||||
t.Errorf("link %v", s.Color)
|
||||
}
|
||||
if s := look.span("x", Attributes{Code: true}, ParagraphStyle{}); s.Background != code || s.Font != "Menlo" || s.Size != 8 {
|
||||
t.Errorf("code %+v", s)
|
||||
}
|
||||
if s := look.span("x", Attributes{}, ParagraphStyle{CodeBlock: true}); s.Color != code {
|
||||
t.Errorf("code block text %v", s.Color)
|
||||
}
|
||||
if s := look.span("x", Attributes{}, ParagraphStyle{Heading: 1}); s.Color != heading {
|
||||
t.Errorf("heading color %v", s.Color)
|
||||
}
|
||||
if f := v.paraFont(ParagraphStyle{Heading: 1}); f.Size != 30 || f.Weight != 800 {
|
||||
t.Errorf("heading font %+v", f)
|
||||
}
|
||||
if f := v.paraFont(ParagraphStyle{CodeBlock: true}); f.Family != "Menlo" || f.Size != 8 {
|
||||
t.Errorf("code block font %+v", f)
|
||||
}
|
||||
if left, right := v.insets(ParagraphStyle{CodeBlock: true, Indent: 1}); left != 30 || right != 10 {
|
||||
t.Errorf("code block insets %v %v", left, right)
|
||||
}
|
||||
v.opts.Theme = &Theme{Padding: [2]float32{20, 0}}
|
||||
v.setLook(ui.LightTheme(), true)
|
||||
if v.padX != 20 || v.padY != ui.LightTheme().Space(2.5) {
|
||||
t.Errorf("padding %v %v", v.padX, v.padY)
|
||||
}
|
||||
v.setLook(ui.LightTheme(), false)
|
||||
if v.padX != 0 || v.padY != 0 {
|
||||
t.Errorf("an EditorBase's padding %v %v", v.padX, v.padY)
|
||||
}
|
||||
}
|
||||
|
||||
// TestThemeChangeLaysOut changes the theme between frames: the text is
|
||||
// laid out again in it.
|
||||
func TestThemeChangeLaysOut(t *testing.T) {
|
||||
doc := NewDocument(ParseMarkdown("# Title\n\nSome `code` and a [link](https://x)."))
|
||||
var th *Theme
|
||||
tt := ui.NewTester(func(c *ui.Context) { Editor(c, doc, EditorOptions{Theme: th}).Fill() }, 400, 200)
|
||||
shot := func() []byte {
|
||||
tt.Frame()
|
||||
return bytes.Clone(tt.Image().Pix)
|
||||
}
|
||||
before := shot()
|
||||
th = &Theme{Headings: [6]HeadingStyle{{Size: 2.4}}, Link: ui.RGB(200, 0, 0)}
|
||||
if bytes.Equal(shot(), before) {
|
||||
t.Error("the theme changed, the text did not")
|
||||
}
|
||||
th = nil
|
||||
if !bytes.Equal(shot(), before) {
|
||||
t.Error("back to the default theme, the text shows otherwise")
|
||||
}
|
||||
}
|
||||
Vendored
+1388
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user