// Package chatmarkdown renders a small Markdown vocabulary without raw HTML. package chatmarkdown import ( "bytes" "html" "html/template" "net/url" "regexp" "strings" "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/util" ) // Labels are the words of a paste box, from the app's copy: its Copy // button, the button once it has copied, what is announced when the // clipboard is refused and the text is selected instead, and the labels // of a prompt, a text and a command box. CopyIcon and CopiedIcon are the // app's own icons (fixed, aria-hidden markup, never input) beside Copy's // word: one shown before a copy, the other, a tick, after. type Labels struct { Copy, Copied, Selected, Prompt, Text, Command string CopyIcon, CopiedIcon template.HTML } // Render renders a finished message. func (l Labels) Render(body string) template.HTML { return render(body, false, l) } // RenderDraft renders a reply that is still arriving with the same rules, // leaving out only what the next characters could still change (see // draft.go). The draft of a whole reply is the reply's Render, unless the // reply itself ends on an unclosed opener or a bare list marker. func (l Labels) RenderDraft(body string) template.HTML { return render(body, true, l) } func render(body string, draft bool, l Labels) template.HTML { var hide spans if draft { body = steady(body) } source := []byte(body) root, seen := parse(source) if draft { hide = unclosed(root, source, seen) } var out bytes.Buffer escape := func(b []byte) { out.WriteString(html.EscapeString(string(b))) } var node func(ast.Node) children := func(n ast.Node) { for c := n.FirstChild(); c != nil; c = c.NextSibling() { node(c) } } node = func(n ast.Node) { wrap := func(open, close string) { out.WriteString(open); children(n); out.WriteString(close) } switch v := n.(type) { case *ast.Document: children(n) case *ast.Paragraph, *ast.Heading: wrap("

", "

\n") case *ast.TextBlock: children(n) case *ast.Text: escape(util.ResolveEntityNames(util.ResolveNumericReferences(util.UnescapePunctuations(hide.value(source, v.Segment))))) if v.HardLineBreak() { out.WriteString("
\n") } else if v.SoftLineBreak() { out.WriteByte('\n') } case *ast.String: escape(v.Value) case *ast.Emphasis: if v.Level == 2 { wrap("", "") } else { wrap("", "") } case *ast.CodeSpan: out.WriteString("") for c := n.FirstChild(); c != nil; c = c.NextSibling() { escape(c.(*ast.Text).Segment.Value(source)) } out.WriteString("") case *ast.FencedCodeBlock: // Copy waits while a draft's fence is still open. l.box(&out, v, source, draft && !seen.closed(v)) case *ast.CodeBlock: out.WriteString("
")
			for i := 0; i < n.Lines().Len(); i++ {
				line := n.Lines().At(i)
				escape(line.Value(source))
			}
			out.WriteString("
\n") case *ast.List: if v.IsOrdered() { wrap("
    ", "
\n") } else { wrap("\n") } case *ast.ListItem: wrap("
  • ", "
  • \n") case *ast.Link: dest := linkEntities(string(v.Destination)) u, err := url.Parse(dest) // Absolute web and mail links, and on this site only a task's // or a project's own page (the coordinator links tasks by title). if err == nil && (u.Scheme == "https" || u.Scheme == "http" || u.Scheme == "mailto" || u.Scheme == "" && sitePage.MatchString(dest)) { wrap(``, "") } else { children(n) } case *ast.RawHTML: for i := 0; i < v.Segments.Len(); i++ { seg := v.Segments.At(i) escape(seg.Value(source)) } case *ast.HTMLBlock: for i := 0; i < v.Lines().Len(); i++ { seg := v.Lines().At(i) escape(seg.Value(source)) } if v.HasClosure() { escape(v.ClosureLine.Value(source)) } default: children(n) } } node(root) return template.HTML(out.String()) // Every text leaf is escaped; tags above are fixed. } // A destination may contain proper HTML entities, but query parameters such // as ×tamp and ®ion are not entities. Decode exactly once and require // the complete name, so an unknown ¬arealentity; also remains unchanged. var properEntity = regexp.MustCompile(`&(?:#[xX][0-9A-Fa-f]+|#[0-9]+|[A-Za-z][A-Za-z0-9]*);`) func linkEntities(value string) string { return properEntity.ReplaceAllStringFunc(value, func(entity string) string { if entity[1] == '#' { return html.UnescapeString(entity) } if named, ok := util.LookUpHTML5EntityByName(entity[1 : len(entity)-1]); ok { return string(named.Characters) } return entity }) } // sitePage is a same-origin link the chat may render: a task or a project. var sitePage = regexp.MustCompile(`^/(tasks/tk[a-z0-9]{1,32}|projects/p_[a-z0-9]{1,40})$`) // box is a fenced block as a paste box: a bar with its label, quietly, // when the fence names a safe language, and a Copy button, then the // text in a selectable //
    , which is what the button copies (paste.js reads the code's
    // text, so entities are the characters they stand for). A prompt or text
    // block is prose and wraps; anything else is code and scrolls. While a
    // draft's fence is open the button is there but aria-disabled, so a
    // half-streamed command is never copied, and the box does not move when
    // it closes: only the button's attribute changes.
    func (l Labels) box(out *bytes.Buffer, v *ast.FencedCodeBlock, source []byte, open bool) {
    	lang := string(v.Language(source))
    	if !language.MatchString(lang) {
    		lang = ""
    	}
    	kind := "code"
    	if prose[strings.ToLower(lang)] {
    		kind = "prose"
    	}
    	out.WriteString(`
    `) if label := l.label(lang); label != "" { out.WriteString(`` + html.EscapeString(label) + ``) } out.WriteString(`
    `)
    	for i := 0; i < v.Lines().Len(); i++ {
    		line := v.Lines().At(i)
    		out.WriteString(html.EscapeString(string(line.Value(source))))
    	}
    	out.WriteString("
    \n") } // language is a fence's label that may show: a short word of letters, // digits and the marks language names use (c++, c#, objective-c, .env). var language = regexp.MustCompile(`^\.?[A-Za-z0-9][A-Za-z0-9_+#.-]{0,23}$`) // prose are the labels of text a person reads and pastes whole: it wraps. var prose = map[string]bool{"prompt": true, "text": true} // shells are the fence labels of a command typed into a terminal. var shells = map[string]bool{"bash": true, "sh": true, "zsh": true, "shell": true, "console": true} // label is what a box's bar says it holds: Prompt, Text or Command in // the app's words, otherwise the fence's language as written ("" for // none). func (l Labels) label(lang string) string { word := "" switch lower := strings.ToLower(lang); { case lower == "prompt": word = l.Prompt case lower == "text": word = l.Text case shells[lower]: word = l.Command } if word == "" { return lang } return word }