// refpop.go is the preview half of RFC 0011 §14: the shared popover's
// card fragments, and the two chat rows — the reply-quote and the
// backlink line — that are references without being prose.
//
// A reference anchor carries one attribute — data-ref, the canonical
// token — wherever it is minted. The behaviour is armed once, on the
// layout's container, and reaches every anchor by delegation, so every
// surface previews the same way without any surface paying per link.
package web
import (
"fmt"
"html/template"
"net/http"
"net/url"
"strconv"
"strings"
)
// refAnchorName is the one CSS anchor name the shared popover binds
// to. One name, moved from link to link, because there is one popover:
// a name per reference would be a stylesheet per page.
const refAnchorName = "--qrefpop"
// refAttr is the whole per-anchor cost of a preview: the canonical
// token, and nothing else. The rows this file draws — the reply-quote
// and the backlink line — are references without being prose, so they
// carry the same one attribute a reference in prose does and are armed
// by the same delegated handlers.
func refAttr(token string) string {
if token == "" {
return ""
}
return fmt.Sprintf(` data-ref="%s"`, template.HTMLEscapeString(token))
}
// The preview is armed by one script (assets/refpop.js), which listens
// on the document and so reaches every reference on the page by
// delegation; an anchor carries only its token. The script fetches on
// hover intent, shows a card only once its own content is ready, caches
// per ref, and drops out-of-order responses. <body> still carries
// data-ref-repo, the page's own repository, against which the fragment
// route reads a token (a cross-repository token has its own `repo:`
// prefix inside data-ref).
//
// refDelegation is what the layout adds to <body> for it: nothing. It is
// kept as the one name the layout and its tests agree on.
const refDelegation = ``
// refCard is ref.resolve's answer, as the page reads it.
type refCard struct {
Kind string `json:"kind"`
ID string `json:"id"`
Repo string `json:"repo"`
Title string `json:"title"`
Summary string `json:"summary"`
State string `json:"state"`
Href string `json:"href"`
Expired bool `json:"expired"`
Author string `json:"author"`
At string `json:"at"`
// Number is a landing's !N.
Number int `json:"number"`
}
// refCardHTML draws one card: what it is, one to three facts, and the
// way in. Every kind uses the same three slots rather than seven
// bespoke layouts — a reader glancing at a preview is reading a shape,
// not a form, and seven shapes is six too many.
func refCardHTML(c refCard) template.HTML {
var b strings.Builder
fmt.Fprintf(&b, `<div class="refcard" data-kind="%s"`, template.HTMLEscapeString(c.Kind))
if c.Expired {
b.WriteString(` data-expired`)
}
if c.State != "" {
fmt.Fprintf(&b, ` data-state="%s"`, template.HTMLEscapeString(c.State))
}
if c.Number > 0 {
fmt.Fprintf(&b, ` data-number="%d"`, c.Number)
}
b.WriteString(">")
if c.Kind == "person" {
b.WriteString(string(identicon(c.Title)))
}
if c.Title != "" {
fmt.Fprintf(&b, `<b class="refcard-title">%s</b>`, template.HTMLEscapeString(c.Title))
}
if c.State != "" {
fmt.Fprintf(&b, ` <span class="refcard-state">%s</span>`, template.HTMLEscapeString(c.State))
}
if c.Summary != "" {
fmt.Fprintf(&b, `<br><span class="refcard-sum">%s</span>`, template.HTMLEscapeString(c.Summary))
}
if c.Author != "" || c.At != "" {
b.WriteString(`<br><small class="tl-meta-inline">`)
if c.Author != "" {
b.WriteString(template.HTMLEscapeString(c.Author))
}
if c.At != "" {
b.WriteString(" " + string(ago(c.At)))
}
b.WriteString(`</small>`)
}
if c.Expired {
b.WriteString(`<br><span class="refcard-sum">aged out of the chat window</span>`)
}
fmt.Fprintf(&b, `<br><a class="refcard-open" href="%s">open</a></div>`,
template.HTMLEscapeString(c.Href))
return template.HTML(b.String())
}
// refPopHTML wraps a card as the shared popover's whole content: the
// fragment REPLACES #refpop, so the popover attribute has to come back
// with it or the element stops being a popover after the first preview.
func refPopHTML(inner template.HTML) string {
return `<div id="refpop" popover>` + string(inner) + `</div>`
}
// chatQuoteHTML is the reply-quote block: who is being answered and the
// first line of what they said, above the reply's own text. It is a
// link to the permalink and carries the same preview hooks a reference
// in prose does, because it IS one.
func (h *handlerHooks) chatQuoteHTML(m ChatMessage, repo string) template.HTML {
if m.Ref == 0 || m.RefUser == "" {
return ""
}
return h.chatQuoteBlock(m.Ref, m.RefUser, m.RefLine, repo)
}
// chatQuoteBlock is the quote itself, spelled once: a reply's quote and
// the quote an inline #seq earns are the same block, so they cannot
// come to look like two different things.
func (h *handlerHooks) chatQuoteBlock(seq uint64, user, line, repo string) template.HTML {
n := strconv.FormatUint(seq, 10)
href := "/r/" + url.PathEscape(repo) + "/chat/" + n
return template.HTML(fmt.Sprintf(
`<a class="chat-quote" data-quote-seq="%d" href="%s"%s>%s<b>%s</b> · %s · %s</a>`,
seq, href, refAttr("#"+n), string(h.userIcon(user)),
template.HTMLEscapeString(user), msgNum(seq),
template.HTMLEscapeString(quoteLine(line))))
}
// msgNum names a message in the page's own labels the way a message
// reference names it in prose (markup's chat icon): the bubble and the
// number, since "#" names a ticket (#309).
func msgNum(seq uint64) string {
return fmt.Sprintf(`<span class="msg-num ref-nw" data-hook="msg-num" data-seq="%d" role="img" aria-label="message %d" title="message %d">`+
`<svg class="ic ref-ic" aria-hidden="true"><use href="#i-comment"/></svg>%d</span>`, seq, seq, seq, seq)
}
// quoteLine is the quoted message's first line, bounded: a quote is a
// reminder of what is being answered, not a second copy of it.
func quoteLine(s string) string {
const limit = 120
if len(s) <= limit {
return s
}
cut := limit
for cut > 0 && s[cut]&0xC0 == 0x80 {
cut--
}
return strings.TrimSpace(s[:cut]) + "…"
}
// patchElements writes one Datastar element patch — the same two-line
// SSE frame the caps preview fragment writes, spelled once here so the
// reference fragments and it cannot drift.
func patchElements(w http.ResponseWriter, body string) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, "event: datastar-patch-elements\n")
sseElements(w, body)
}
// trailingMention reads the @handle a composer is part-way through
// typing: the token at the very end of the text, and nothing else. A
// mention finished three words ago is not what the reader is asking to
// complete.
func trailingMention(text string) (string, bool) {
i := strings.LastIndexAny(text, " \t\n")
last := text[i+1:]
if !strings.HasPrefix(last, "@") {
return "", false
}
q := last[1:]
for _, c := range q {
if !isHandleRune(c) {
return "", false
}
}
return q, true
}
func isHandleRune(c rune) bool {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' ||
c == '.' || c == '_' || c == '-'
}
// chatRefsRow is ref-counting's page half: how often the CURRENT chat
// window named this artifact, and the latest message to land on.
type chatRefsRow struct {
Count int `json:"count"`
Seq uint64 `json:"seq"`
At string `json:"at"`
}
// chatRefsHTML draws the "chat" row that sits beside an artifact's
// durable MentionRef rows. It is visibly its own row and says it is
// window-bounded, because a count that silently shrinks reads as data
// loss to anyone who thought it was an index fact (RFC 0011 §14).
func chatRefsHTML(c chatRefsRow, repo string) template.HTML {
if c.Count == 0 || c.Seq == 0 {
return ""
}
href := "/r/" + url.PathEscape(repo) + "/chat/" + strconv.FormatUint(c.Seq, 10)
var b strings.Builder
fmt.Fprintf(&b, `<p class="chatrefs" data-chat-refs data-count="%d" data-seq="%d">`, c.Count, c.Seq)
fmt.Fprintf(&b, `<a href="%s"%s>%d chat %s</a>`, href,
refAttr("#"+strconv.FormatUint(c.Seq, 10)),
c.Count, map[bool]string{true: "message", false: "messages"}[c.Count == 1])
if c.At != "" {
b.WriteString(` <small class="tl-meta-inline">last ` + string(ago(c.At)) + `</small>`)
}
b.WriteString(` <small class="tl-meta-inline">· within the chat window</small></p>`)
return template.HTML(b.String())
}
// chatRefsOf lifts the chat row out of any op answer that carries one,
// so four page handlers share one spelling of "did chat mention this".
func chatRefsOf(out any) chatRefsRow {
var v struct {
ChatRefs chatRefsRow `json:"chatRefs"`
}
remarshal(out, &v)
return v.ChatRefs
}