| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "html/template" |
| 5 | "math" |
| 6 | "strconv" |
| 7 | "strings" |
| 8 | |
| 9 | "amadan.net/oficina/mapa/internal/mapa/markup" |
| 10 | ) |
| 11 | |
| 12 | // The history diff (level-up spec §4.5): block by block, aligned as the |
| 13 | // merge aligns them, then word by word inside a block that changed. A |
| 14 | // [[link]] is one word. Everything a person typed is escaped; a changed |
| 15 | // block is drawn as its kind with its text, never through the renderer. |
| 16 | |
| 17 | // Kinds of block change. |
| 18 | const ( |
| 19 | blockSame = "same" |
| 20 | blockAdded = "added" |
| 21 | blockRemoved = "removed" |
| 22 | blockChanged = "changed" |
| 23 | ) |
| 24 | |
| 25 | // blockChange is one step from the version before to this one. From and |
| 26 | // To are block indices, -1 where the side has none. At is where the step |
| 27 | // falls in this version: To, or for a removal the block after it. |
| 28 | type blockChange struct { |
| 29 | Kind string |
| 30 | From, To, At int |
| 31 | } |
| 32 | |
| 33 | // diffBlocks is the steps from one version's blocks to the next's. |
| 34 | // Unmatched blocks between two matches pair up in order as changed |
| 35 | // blocks when their words are alike; the rest are removed, then added. |
| 36 | // Past the alignment's bound (matchBlocks), nothing pairs: the changed |
| 37 | // middle is all removed, then all added. |
| 38 | func diffBlocks(from, to []markup.Block) []blockChange { |
| 39 | matched, coarse := matchBlocks(from, to) |
| 40 | alike := func(was, now int) bool { |
| 41 | return !coarse && similar(tokensOf(from[was]), tokensOf(to[now])) |
| 42 | } |
| 43 | var changes, removed []blockChange |
| 44 | next := 0 |
| 45 | for index, target := range matched { |
| 46 | if target < 0 { |
| 47 | removed = append(removed, blockChange{Kind: blockRemoved, |
| 48 | From: index, To: -1}) |
| 49 | continue |
| 50 | } |
| 51 | changes = append(changes, stretch(removed, next, target, alike)...) |
| 52 | changes = append(changes, blockChange{Kind: blockSame, From: index, |
| 53 | To: target, At: target}) |
| 54 | removed, next = nil, target+1 |
| 55 | } |
| 56 | return append(changes, stretch(removed, next, len(to), alike)...) |
| 57 | } |
| 58 | |
| 59 | // stretch settles the blocks between two matches: removed from the |
| 60 | // version before, and to's blocks start up to end. Each removed block is |
| 61 | // paired, in order, with the next added one alike enough to diff word |
| 62 | // by word (a changed block). Between pairs, the rest are drawn removed, |
| 63 | // then added; a removal falls At the block drawn after it. |
| 64 | func stretch(removed []blockChange, start, end int, |
| 65 | alike func(was, now int) bool) []blockChange { |
| 66 | pairs := append(pairUp(removed, start, end, alike), |
| 67 | blockPair{From: math.MaxInt, To: end}) |
| 68 | var out []blockChange |
| 69 | gone, cursor := 0, start |
| 70 | for _, pair := range pairs { |
| 71 | for ; gone < len(removed) && removed[gone].From < pair.From; gone++ { |
| 72 | change := removed[gone] |
| 73 | change.At = cursor |
| 74 | out = append(out, change) |
| 75 | } |
| 76 | for ; cursor < pair.To; cursor++ { |
| 77 | out = append(out, blockChange{Kind: blockAdded, From: -1, |
| 78 | To: cursor, At: cursor}) |
| 79 | } |
| 80 | if pair.To < end { |
| 81 | out = append(out, blockChange{Kind: blockChanged, |
| 82 | From: pair.From, To: pair.To, At: pair.To}) |
| 83 | gone, cursor = gone+1, cursor+1 |
| 84 | } |
| 85 | } |
| 86 | return out |
| 87 | } |
| 88 | |
| 89 | // blockPair is a removed block, From, that changed into an added one. |
| 90 | type blockPair struct{ From, To int } |
| 91 | |
| 92 | // maxPairings bounds how many block pairs one stretch compares. |
| 93 | const maxPairings = 2000 |
| 94 | |
| 95 | // pairUp is the removed blocks that changed into added ones in start up |
| 96 | // to end, in order: greedily, in order on both sides, so a pairing |
| 97 | // never crosses another. |
| 98 | func pairUp(removed []blockChange, start, end int, |
| 99 | alike func(was, now int) bool) []blockPair { |
| 100 | var pairs []blockPair |
| 101 | cursor, tries := start, 0 |
| 102 | for _, gone := range removed { |
| 103 | for candidate := cursor; candidate < end; candidate++ { |
| 104 | if tries++; tries > maxPairings { |
| 105 | return pairs |
| 106 | } |
| 107 | if alike(gone.From, candidate) { |
| 108 | pairs = append(pairs, blockPair{From: gone.From, |
| 109 | To: candidate}) |
| 110 | cursor = candidate + 1 |
| 111 | break |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | return pairs |
| 116 | } |
| 117 | |
| 118 | // maxBlockCells bounds the block alignment's table, as maxWordCells |
| 119 | // bounds the word diff's: 4 MB of it. The blocks the two versions share |
| 120 | // at either end are matched first and cost nothing; past the bound, the |
| 121 | // middle between them is not aligned at all (coarse). |
| 122 | const maxBlockCells = 1 << 20 |
| 123 | |
| 124 | // matchBlocks maps each block of from to its match in to, by a longest |
| 125 | // common subsequence of block sources, or -1 where it has none: the |
| 126 | // merge's alignment (markup's align), kept here so history needs |
| 127 | // nothing new from markup. coarse reports a middle too large to align, |
| 128 | // whose blocks are all -1. |
| 129 | func matchBlocks(from, to []markup.Block) (matched []int, coarse bool) { |
| 130 | head, tail := sharedEnds(from, to) |
| 131 | rows, columns := len(from)-head-tail, len(to)-head-tail |
| 132 | matched = make([]int, len(from)) |
| 133 | for index := range matched { |
| 134 | switch { |
| 135 | case index < head: |
| 136 | matched[index] = index |
| 137 | case index >= head+rows: |
| 138 | matched[index] = index + len(to) - len(from) |
| 139 | default: |
| 140 | matched[index] = -1 |
| 141 | } |
| 142 | } |
| 143 | if rows*columns > maxBlockCells { |
| 144 | return matched, true |
| 145 | } |
| 146 | middle := lcs(rows, columns, func(row, column int) bool { |
| 147 | return from[head+row].Source == to[head+column].Source |
| 148 | }) |
| 149 | for row, column := range middle { |
| 150 | if column >= 0 { |
| 151 | matched[head+row] = head + column |
| 152 | } |
| 153 | } |
| 154 | return matched, false |
| 155 | } |
| 156 | |
| 157 | // sharedEnds is how many blocks the two versions share at the start, |
| 158 | // and then at the end of what is left. |
| 159 | func sharedEnds(from, to []markup.Block) (head, tail int) { |
| 160 | shorter := min(len(from), len(to)) |
| 161 | for head < shorter && from[head].Source == to[head].Source { |
| 162 | head++ |
| 163 | } |
| 164 | for tail < shorter-head && from[len(from)-1-tail].Source == |
| 165 | to[len(to)-1-tail].Source { |
| 166 | tail++ |
| 167 | } |
| 168 | return head, tail |
| 169 | } |
| 170 | |
| 171 | // lcs maps each of rows items to its match among columns, or -1, by a |
| 172 | // longest common subsequence under same. |
| 173 | func lcs(rows, columns int, same func(row, column int) bool) []int { |
| 174 | lengths := make([][]int32, rows+1) |
| 175 | for row := range lengths { |
| 176 | lengths[row] = make([]int32, columns+1) |
| 177 | } |
| 178 | for row := rows - 1; row >= 0; row-- { |
| 179 | for column := columns - 1; column >= 0; column-- { |
| 180 | if same(row, column) { |
| 181 | lengths[row][column] = lengths[row+1][column+1] + 1 |
| 182 | } else { |
| 183 | lengths[row][column] = max(lengths[row+1][column], |
| 184 | lengths[row][column+1]) |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | matched := make([]int, rows) |
| 189 | row, column := 0, 0 |
| 190 | for row < rows { |
| 191 | switch { |
| 192 | case column < columns && same(row, column): |
| 193 | matched[row] = column |
| 194 | row, column = row+1, column+1 |
| 195 | case column < columns && |
| 196 | lengths[row][column+1] >= lengths[row+1][column]: |
| 197 | column++ |
| 198 | default: |
| 199 | matched[row] = -1 |
| 200 | row++ |
| 201 | } |
| 202 | } |
| 203 | return matched |
| 204 | } |
| 205 | |
| 206 | // drawRun draws a run of a version's blocks as the page draws them, in |
| 207 | // the viewer's scope (markup.Render), with no empty paragraph after. |
| 208 | type drawRun func(blocks []markup.Block) (template.HTML, error) |
| 209 | |
| 210 | // diffHTML draws this version, to, with what changed from the version |
| 211 | // before it marked. Runs of unchanged blocks go through draw; changed |
| 212 | // blocks are drawn here. The editor's empty paragraph comes once, at the |
| 213 | // end, as the page's renderer decides it (pageEnd). |
| 214 | func diffHTML(from, to []markup.Block, draw drawRun) (template.HTML, |
| 215 | error) { |
| 216 | // Fences are left out: History's diff draws a page's blocks one |
| 217 | // after another, not in their columns (columns and icons spec, |
| 218 | // build note C5), and a fence alone draws nothing worth marking. |
| 219 | from, to = withoutFences(from), withoutFences(to) |
| 220 | var out strings.Builder |
| 221 | var kept []markup.Block |
| 222 | var last *markup.Block |
| 223 | flush := func() error { |
| 224 | if len(kept) == 0 { |
| 225 | return nil |
| 226 | } |
| 227 | drawn, err := draw(kept) |
| 228 | out.WriteString(continued(string(drawn), last, kept[0])) |
| 229 | last, kept = &kept[len(kept)-1], nil |
| 230 | return err |
| 231 | } |
| 232 | for _, change := range diffBlocks(from, to) { |
| 233 | if change.Kind == blockSame { |
| 234 | kept = append(kept, to[change.To]) |
| 235 | continue |
| 236 | } |
| 237 | if err := flush(); err != nil { |
| 238 | return "", err |
| 239 | } |
| 240 | block := blockOf(change, from, to) |
| 241 | out.WriteString(changedBlock(change, block, from)) |
| 242 | last = &block |
| 243 | } |
| 244 | err := flush() |
| 245 | return template.HTML(out.String() + pageEnd(last)), err |
| 246 | } |
| 247 | |
| 248 | // continued is a kept run, drawn, that goes on with a numbered list a |
| 249 | // change interrupted: its list starts at its first item's own number, |
| 250 | // not at 1. |
| 251 | func continued(drawn string, last *markup.Block, first markup.Block) string { |
| 252 | if last == nil || last.Kind != markup.Item || first.Kind != |
| 253 | markup.Item || !first.Ordered { |
| 254 | return drawn |
| 255 | } |
| 256 | rest, found := strings.CutPrefix(drawn, "<ol>") |
| 257 | if !found { |
| 258 | return drawn |
| 259 | } |
| 260 | return `<ol start="` + itemNumber(first) + `">` + rest |
| 261 | } |
| 262 | |
| 263 | // pageEnd is the editor's empty paragraph after the last block drawn, |
| 264 | // when it is not a paragraph, as markup.RenderPage ends a body. With |
| 265 | // nothing drawn there is none, so the version reads as empty. |
| 266 | func pageEnd(last *markup.Block) string { |
| 267 | if last == nil || last.Kind == markup.Paragraph { |
| 268 | return "" |
| 269 | } |
| 270 | return markup.EmptyParagraph |
| 271 | } |
| 272 | |
| 273 | // drawPage is a whole body drawn as its page, with its end. |
| 274 | func drawPage(body string, draw drawRun) (template.HTML, error) { |
| 275 | blocks := markup.Parse(body) |
| 276 | if len(blocks) == 0 { |
| 277 | return "", nil |
| 278 | } |
| 279 | drawn, err := draw(blocks) |
| 280 | return drawn + template.HTML(pageEnd(&blocks[len(blocks)-1])), err |
| 281 | } |
| 282 | |
| 283 | // blockOf is the block a change draws: the one removed, or this |
| 284 | // version's. |
| 285 | func blockOf(change blockChange, from, to []markup.Block) markup.Block { |
| 286 | if change.Kind == blockRemoved { |
| 287 | return from[change.From] |
| 288 | } |
| 289 | return to[change.To] |
| 290 | } |
| 291 | |
| 292 | // changedBlock is one added, removed or changed block, as its kind. |
| 293 | func changedBlock(change blockChange, block markup.Block, |
| 294 | from []markup.Block) string { |
| 295 | var inner string |
| 296 | switch change.Kind { |
| 297 | case blockAdded: |
| 298 | inner = drawRuns([]wordRun{{Tag: "ins", Tokens: tokensOf(block)}}) |
| 299 | case blockRemoved: |
| 300 | inner = drawRuns([]wordRun{{Tag: "del", Tokens: tokensOf(block)}}) |
| 301 | default: |
| 302 | inner = drawRuns(diffWords(tokensOf(from[change.From]), |
| 303 | tokensOf(block))) |
| 304 | } |
| 305 | return `<div mapa-diff="` + change.Kind + `">` + asKind(block, inner) + |
| 306 | "</div>\n" |
| 307 | } |
| 308 | |
| 309 | // asKind wraps a block's drawn text in its kind's element. |
| 310 | func asKind(block markup.Block, inner string) string { |
| 311 | switch block.Kind { |
| 312 | case markup.Heading: |
| 313 | level := strconv.Itoa(min(block.Level+1, 6)) |
| 314 | return "<h" + level + ">" + inner + "</h" + level + ">" |
| 315 | case markup.Item: |
| 316 | return asItem(block, inner) |
| 317 | case markup.Quote: |
| 318 | return "<blockquote><p>" + inner + "</p></blockquote>" |
| 319 | case markup.Code: |
| 320 | return "<pre><code>" + inner + "</code></pre>" |
| 321 | case markup.Rule: |
| 322 | return "<hr>" |
| 323 | } |
| 324 | return "<p>" + inner + "</p>" |
| 325 | } |
| 326 | |
| 327 | // asItem is one list item as a list of its own, at its depth; a numbered |
| 328 | // item keeps its number. |
| 329 | func asItem(block markup.Block, inner string) string { |
| 330 | open := "<ul" |
| 331 | tag := "ul" |
| 332 | if block.Ordered { |
| 333 | tag = "ol" |
| 334 | open = `<ol start="` + itemNumber(block) + `"` |
| 335 | } |
| 336 | return open + ` mapa-diff-level="` + strconv.Itoa(min(block.Level, 3)) + |
| 337 | `"><li>` + inner + "</li></" + tag + ">" |
| 338 | } |
| 339 | |
| 340 | // itemNumber is a numbered item's own number, as typed. |
| 341 | func itemNumber(block markup.Block) string { |
| 342 | digits := strings.TrimLeft(block.Source, " \t") |
| 343 | end := strings.IndexFunc(digits, func(char rune) bool { |
| 344 | return char < '0' || char > '9' |
| 345 | }) |
| 346 | return digits[:max(end, 0)] |
| 347 | } |
| 348 | |