30a95ef08a
A table that starts forming made stableMarkdownPrefix truncate every streaming frame at the table start, so the card froze and the whole table plus tail arrived in the single finalize frame (live: 5.2 KB dump after the answer had already finished upstream). Add the DINGTALK_CARD_WIDE_TABLE_GROUP=smooth mode: over-wide tables are grouped on every frame (as "on") and, while streaming, every table is grouped so no table block survives into a partial frame. The final frame keeps the real table whenever it lays out safely.
266 lines
7.2 KiB
Go
266 lines
7.2 KiB
Go
package dingtalk
|
||
|
||
import (
|
||
"strings"
|
||
"unicode"
|
||
)
|
||
|
||
// maxTableCellVisualWidth is the DingTalk-safe cell budget. CJK counts as 2
|
||
// display columns; a cell wider than this tends to collapse the column layout
|
||
// (one character per line) in the streaming card renderer.
|
||
const maxTableCellVisualWidth = 32
|
||
|
||
// tableNormalizeOptions controls how a final answer is adapted to the card
|
||
// renderer. The zero value keeps the historical behaviour.
|
||
type tableNormalizeOptions struct {
|
||
// groupWideTables rewrites tables containing over-wide cells into grouped
|
||
// lists (bold row heading + "- header:value" lines). Disable it when the
|
||
// client lays out wide tables itself, so the answer keeps its real table.
|
||
groupWideTables bool
|
||
// groupAllTables rewrites every table into a grouped list, compact ones
|
||
// included. Streaming frames use it so a table that is still forming never
|
||
// freezes the card; the final frame keeps the real table whenever it lays
|
||
// out safely.
|
||
groupAllTables bool
|
||
}
|
||
|
||
func defaultTableNormalizeOptions() tableNormalizeOptions {
|
||
return tableNormalizeOptions{groupWideTables: true}
|
||
}
|
||
|
||
// tableGroupingForMode maps the configured mode to the two frames the card
|
||
// renders. An unknown or empty mode keeps the historical behaviour (group on
|
||
// every frame), so an unset environment never changes rendering.
|
||
//
|
||
// ""/"on" group on every frame
|
||
// "off" never group: real tables everywhere
|
||
// "stream" group while streaming, real table on the final frame
|
||
// "smooth" group on every frame and group every table (compact ones too)
|
||
// while streaming, so a table forming mid-answer keeps the card
|
||
// growing instead of freezing it until the final frame
|
||
func tableGroupingForMode(mode string) (partial, final, allPartial bool) {
|
||
switch strings.ToLower(strings.TrimSpace(mode)) {
|
||
case "off", "0", "false", "no":
|
||
return false, false, false
|
||
case "stream", "streaming", "partial":
|
||
return true, false, false
|
||
case "smooth":
|
||
return true, true, true
|
||
default:
|
||
return true, true, false
|
||
}
|
||
}
|
||
|
||
// normalizeWideMarkdownTables makes final answers render reliably on DingTalk
|
||
// cards without changing the knowledge itself. It (1) replaces <br> inside
|
||
// table cells with a full-width separator, and (2) rewrites any table that
|
||
// still contains an over-wide cell into a grouped list — a bold row heading
|
||
// followed by one "- header:value" line per column. Compact tables pass
|
||
// through unchanged. Tables inside code fences are never touched.
|
||
func normalizeWideMarkdownTables(content string) string {
|
||
return normalizeMarkdownTables(content, defaultTableNormalizeOptions())
|
||
}
|
||
|
||
func normalizeMarkdownTables(content string, options tableNormalizeOptions) string {
|
||
if !strings.Contains(content, "|") {
|
||
return content
|
||
}
|
||
lines := splitMarkdownStreamLines(content)
|
||
out := make([]string, 0, len(lines))
|
||
for i := 0; i < len(lines); {
|
||
line := lines[i]
|
||
if line.inFence {
|
||
out = append(out, line.text)
|
||
i++
|
||
continue
|
||
}
|
||
if isTableHeaderCandidate(line.text) && i+1 < len(lines) &&
|
||
isCompleteTableDelimiter(lines[i+1].text) {
|
||
end := i + 1
|
||
for end+1 < len(lines) && !lines[end+1].inFence &&
|
||
strings.HasPrefix(strings.TrimSpace(lines[end+1].text), "|") {
|
||
end++
|
||
}
|
||
out = append(out, normalizeTableBlock(lines[i:end+1], options)...)
|
||
i = end + 1
|
||
continue
|
||
}
|
||
out = append(out, line.text)
|
||
i++
|
||
}
|
||
return strings.Join(out, "\n")
|
||
}
|
||
|
||
func normalizeTableBlock(rows []markdownStreamLine, options tableNormalizeOptions) []string {
|
||
cells := make([][]string, 0, len(rows))
|
||
for idx, row := range rows {
|
||
if idx == 1 { // delimiter row
|
||
continue
|
||
}
|
||
cells = append(cells, splitTableRow(row.text))
|
||
}
|
||
maxWidth := 0
|
||
for _, row := range cells {
|
||
for _, cell := range row {
|
||
if w := visualWidth(cell); w > maxWidth {
|
||
maxWidth = w
|
||
}
|
||
}
|
||
}
|
||
header := cells[0]
|
||
if !options.groupAllTables && (maxWidth <= maxTableCellVisualWidth || !options.groupWideTables) {
|
||
// Compact tables keep their exact original bytes unless a cell carries
|
||
// <br>, which the card renderer mishandles inside cells. The same path
|
||
// serves over-wide tables when grouping is disabled: the table stays a
|
||
// table and only <br> is replaced.
|
||
if !blockHasBreak(rows) {
|
||
rebuilt := make([]string, len(rows))
|
||
for i, row := range rows {
|
||
rebuilt[i] = row.text
|
||
}
|
||
return rebuilt
|
||
}
|
||
var rebuilt []string
|
||
for idx, row := range cells {
|
||
joined := "| " + strings.Join(row, " | ") + " |"
|
||
if idx == 0 {
|
||
rebuilt = append(rebuilt, joined)
|
||
delims := make([]string, len(row))
|
||
for c := range row {
|
||
delims[c] = "---"
|
||
}
|
||
rebuilt = append(rebuilt, "| "+strings.Join(delims, " | ")+" |")
|
||
} else {
|
||
rebuilt = append(rebuilt, joined)
|
||
}
|
||
}
|
||
return rebuilt
|
||
}
|
||
|
||
var out []string
|
||
for gi, row := range cells[1:] {
|
||
if gi > 0 {
|
||
out = append(out, "")
|
||
}
|
||
var title string
|
||
var rest []string
|
||
for c, cell := range row {
|
||
if c == 0 {
|
||
title = cell
|
||
continue
|
||
}
|
||
label := strings.TrimSpace(header[min(c, len(header)-1)])
|
||
if label == "" {
|
||
label = "第" + itoa(c+1) + "项"
|
||
}
|
||
if cell == "" {
|
||
continue
|
||
}
|
||
rest = append(rest, "- "+label+":"+cell)
|
||
}
|
||
if title == "" {
|
||
title = label2(row[0])
|
||
}
|
||
out = append(out, "**"+strings.Trim(title, "* ")+"**")
|
||
out = append(out, rest...)
|
||
}
|
||
return out
|
||
}
|
||
|
||
func blockHasBreak(rows []markdownStreamLine) bool {
|
||
for _, row := range rows {
|
||
lower := strings.ToLower(row.text)
|
||
if strings.Contains(lower, "<br") {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
func splitTableRow(line string) []string {
|
||
trimmed := strings.TrimSpace(line)
|
||
trimmed = strings.TrimPrefix(trimmed, "|")
|
||
trimmed = strings.TrimSuffix(trimmed, "|")
|
||
parts := splitEscaped(trimmed)
|
||
for i := range parts {
|
||
cell := strings.TrimSpace(parts[i])
|
||
cell = strings.ReplaceAll(cell, "<br>", ";")
|
||
cell = strings.ReplaceAll(cell, "<br/>", ";")
|
||
cell = strings.ReplaceAll(cell, "<br />", ";")
|
||
cell = strings.ReplaceAll(cell, "\\|", "|")
|
||
parts[i] = strings.TrimSpace(cell)
|
||
}
|
||
return parts
|
||
}
|
||
|
||
// splitEscaped splits on unescaped pipe separators.
|
||
func splitEscaped(s string) []string {
|
||
var parts []string
|
||
var b strings.Builder
|
||
for i := 0; i < len(s); i++ {
|
||
switch s[i] {
|
||
case '\\':
|
||
if i+1 < len(s) && s[i+1] == '|' {
|
||
b.WriteString("\\|")
|
||
i++
|
||
continue
|
||
}
|
||
b.WriteByte(s[i])
|
||
case '|':
|
||
parts = append(parts, b.String())
|
||
b.Reset()
|
||
default:
|
||
b.WriteByte(s[i])
|
||
}
|
||
}
|
||
parts = append(parts, b.String())
|
||
return parts
|
||
}
|
||
|
||
func label2(cell string) string { return strings.Trim(cell, "* ") }
|
||
func min(a, b int) int {
|
||
if a < b {
|
||
return a
|
||
}
|
||
return b
|
||
}
|
||
|
||
func itoa(n int) string {
|
||
if n == 0 {
|
||
return "0"
|
||
}
|
||
var d []byte
|
||
for n > 0 {
|
||
d = append([]byte{byte('0' + n%10)}, d...)
|
||
n /= 10
|
||
}
|
||
return string(d)
|
||
}
|
||
|
||
func visualWidth(s string) int {
|
||
w := 0
|
||
for _, r := range s {
|
||
if r == '\n' {
|
||
if w > 0 {
|
||
w++ // separator counted conservatively
|
||
}
|
||
continue
|
||
}
|
||
if unicode.Is(unicode.Han, r) || unicode.Is(unicode.Katakana, r) ||
|
||
unicode.Is(unicode.Hiragana, r) || fullwidthPunct(r) {
|
||
w += 2
|
||
continue
|
||
}
|
||
w++
|
||
}
|
||
return w
|
||
}
|
||
|
||
func fullwidthPunct(r rune) bool {
|
||
switch r {
|
||
case ',', '。', ':', ';', '(', ')', '、', '【', '】', '《', '》', '“', '”', '‘', '’', ' ':
|
||
return true
|
||
}
|
||
return false
|
||
}
|