Skip to content

Commit f62cd2f

Browse files
authored
Fix task list checkbox toggle to work with YAML front matter (#25184)
Fixes #25160. `data-source-position` of checkboxes in a task list was incorrect whenever there was YAML front matter. This would result in issue content or PR descriptions getting corrupted with random `x` or space characters when a user checked or unchecked a task.
1 parent 419804f commit f62cd2f

File tree

6 files changed

+66
-7
lines changed

6 files changed

+66
-7
lines changed

modules/markup/markdown/ast.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,8 @@ func IsSummary(node ast.Node) bool {
7676
// TaskCheckBoxListItem is a block that represents a list item of a markdown block with a checkbox
7777
type TaskCheckBoxListItem struct {
7878
*ast.ListItem
79-
IsChecked bool
79+
IsChecked bool
80+
SourcePosition int
8081
}
8182

8283
// KindTaskCheckBoxListItem is the NodeKind for TaskCheckBoxListItem
@@ -86,6 +87,7 @@ var KindTaskCheckBoxListItem = ast.NewNodeKind("TaskCheckBoxListItem")
8687
func (n *TaskCheckBoxListItem) Dump(source []byte, level int) {
8788
m := map[string]string{}
8889
m["IsChecked"] = strconv.FormatBool(n.IsChecked)
90+
m["SourcePosition"] = strconv.FormatInt(int64(n.SourcePosition), 10)
8991
ast.DumpHelper(n, source, level, m, nil)
9092
}
9193

modules/markup/markdown/goldmark.go

+6-6
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,11 @@ func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc pa
177177
newChild := NewTaskCheckBoxListItem(listItem)
178178
newChild.IsChecked = taskCheckBox.IsChecked
179179
newChild.SetAttributeString("class", []byte("task-list-item"))
180+
segments := newChild.FirstChild().Lines()
181+
if segments.Len() > 0 {
182+
segment := segments.At(0)
183+
newChild.SourcePosition = rc.metaLength + segment.Start
184+
}
180185
v.AppendChild(v, newChild)
181186
}
182187
}
@@ -457,12 +462,7 @@ func (r *HTMLRenderer) renderTaskCheckBoxListItem(w util.BufWriter, source []byt
457462
} else {
458463
_, _ = w.WriteString("<li>")
459464
}
460-
_, _ = w.WriteString(`<input type="checkbox" disabled=""`)
461-
segments := node.FirstChild().Lines()
462-
if segments.Len() > 0 {
463-
segment := segments.At(0)
464-
_, _ = w.WriteString(fmt.Sprintf(` data-source-position="%d"`, segment.Start))
465-
}
465+
fmt.Fprintf(w, `<input type="checkbox" disabled="" data-source-position="%d"`, n.SourcePosition)
466466
if n.IsChecked {
467467
_, _ = w.WriteString(` checked=""`)
468468
}

modules/markup/markdown/markdown.go

+9
Original file line numberDiff line numberDiff line change
@@ -178,13 +178,22 @@ func actualRender(ctx *markup.RenderContext, input io.Reader, output io.Writer)
178178
}
179179
buf = giteautil.NormalizeEOL(buf)
180180

181+
// Preserve original length.
182+
bufWithMetadataLength := len(buf)
183+
181184
rc := &RenderConfig{
182185
Meta: renderMetaModeFromString(string(ctx.RenderMetaAs)),
183186
Icon: "table",
184187
Lang: "",
185188
}
186189
buf, _ = ExtractMetadataBytes(buf, rc)
187190

191+
metaLength := bufWithMetadataLength - len(buf)
192+
if metaLength < 0 {
193+
metaLength = 0
194+
}
195+
rc.metaLength = metaLength
196+
188197
pc.Set(renderConfigKey, rc)
189198

190199
if err := converter.Convert(buf, lw, parser.WithContext(pc)); err != nil {

modules/markup/markdown/markdown_test.go

+37
Original file line numberDiff line numberDiff line change
@@ -520,3 +520,40 @@ func TestMathBlock(t *testing.T) {
520520

521521
}
522522
}
523+
524+
func TestTaskList(t *testing.T) {
525+
testcases := []struct {
526+
testcase string
527+
expected string
528+
}{
529+
{
530+
// data-source-position should take into account YAML frontmatter.
531+
`---
532+
foo: bar
533+
---
534+
- [ ] task 1`,
535+
`<details><summary><i class="icon table"></i></summary><table>
536+
<thead>
537+
<tr>
538+
<th>foo</th>
539+
</tr>
540+
</thead>
541+
<tbody>
542+
<tr>
543+
<td>bar</td>
544+
</tr>
545+
</tbody>
546+
</table>
547+
</details><ul>
548+
<li class="task-list-item"><input type="checkbox" disabled="" data-source-position="19"/>task 1</li>
549+
</ul>
550+
`,
551+
},
552+
}
553+
554+
for _, test := range testcases {
555+
res, err := RenderString(&markup.RenderContext{Ctx: git.DefaultContext}, test.testcase)
556+
assert.NoError(t, err, "Unexpected error in testcase: %q", test.testcase)
557+
assert.Equal(t, test.expected, res, "Unexpected result in testcase %q", test.testcase)
558+
}
559+
}

modules/markup/markdown/renderconfig.go

+3
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ type RenderConfig struct {
2020
TOC string // "false": hide, "side"/empty: in sidebar, "main"/"true": in main view
2121
Lang string
2222
yamlNode *yaml.Node
23+
24+
// Used internally. Cannot be controlled by frontmatter.
25+
metaLength int
2326
}
2427

2528
func renderMetaModeFromString(s string) markup.RenderMetaMode {

web_src/js/markup/tasklist.js

+8
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@ export function initMarkupTasklist() {
2929

3030
const encoder = new TextEncoder();
3131
const buffer = encoder.encode(oldContent);
32+
// Indexes may fall off the ends and return undefined.
33+
if (buffer[position - 1] !== '['.codePointAt(0) ||
34+
buffer[position] !== ' '.codePointAt(0) && buffer[position] !== 'x'.codePointAt(0) ||
35+
buffer[position + 1] !== ']'.codePointAt(0)) {
36+
// Position is probably wrong. Revert and don't allow change.
37+
checkbox.checked = !checkbox.checked;
38+
throw new Error(`Expected position to be space or x and surrounded by brackets, but it's not: position=${position}`);
39+
}
3240
buffer.set(encoder.encode(checkboxCharacter), position);
3341
const newContent = new TextDecoder().decode(buffer);
3442

0 commit comments

Comments
 (0)