diff --git a/desktop/internal/webpreview/assets/markdown.js b/desktop/internal/webpreview/assets/markdown.js
index 56b7d5be79..d47393df46 100644
--- a/desktop/internal/webpreview/assets/markdown.js
+++ b/desktop/internal/webpreview/assets/markdown.js
@@ -1,12 +1,14 @@
// The rendered page of a Markdown file. The host sends Core's sanitized HTML; the page lays it out,
// renders math, code and diagrams, and keeps its scroll position in step with the editor by source
// line. It reaches nothing but its own origin: images are requested as res/, and the host
-// answers with what Core resolves the src to.
+// answers with what Core resolves the src to. While the host's Contents button is on, the page's
+// outline floats at its top right: the headings as a tree that folds, with the section at the
+// page's top marked.
//
// Host to page: {type: 'setup', strings, theme}, {type: 'render', revision, html},
-// {type: 'scroll', line}, {type: 'theme', theme}.
+// {type: 'scroll', line}, {type: 'theme', theme}, {type: 'outline', open}.
// Page to host: {type: 'ready'}, {type: 'rendered', revision, headings}, {type: 'scrolled', line},
-// {type: 'link', href}.
+// {type: 'link', href}, {type: 'outline', open} when the user closed the outline in the page.
(() => {
'use strict';
@@ -15,8 +17,13 @@
const viewer = document.getElementById('image-viewer');
const fullImage = document.getElementById('image-full');
const imageClose = document.getElementById('image-close');
+ const outline = document.getElementById('outline');
+ const outlineTitle = document.getElementById('outline-title');
+ const outlineTree = document.getElementById('outline-tree');
+ const outlineRows = document.getElementById('outline-rows');
const XLINK = 'http://www.w3.org/1999/xlink';
+ const SVG = 'http://www.w3.org/2000/svg';
// Blocks whose source lines map the page to the editor. Inline elements share their block's lines.
const BLOCKS = 'p, h1, h2, h3, h4, h5, h6, li, pre, blockquote, table, tr, hr, ul, ol, dl, dt, dd, details, figure, section, div';
// Code blocks that are drawn rather than highlighted.
@@ -25,6 +32,15 @@
const HIGHLIGHT_ENTRIES = 256;
// Auto-detecting the language of a long block on each keystroke costs more than it shows.
const AUTO_DETECT_LIMIT = 20000;
+ // The outline's rows are OUTLINE_ROW high, as .outline-item is, and each level is indented
+ // OUTLINE_INDENT more. OUTLINE_OVERSCAN rows past each edge of its view are laid out too;
+ // OUTLINE_PAD is the tree's padding.
+ const OUTLINE_ROW = 28;
+ const OUTLINE_INDENT = 16;
+ const OUTLINE_OVERSCAN = 8;
+ const OUTLINE_PAD = 6;
+ // A heading counts as the section at the page's top this many lines before it reaches the top.
+ const SECTION_LEAD = 0.5;
let strings = {};
let theme = 'light';
@@ -93,6 +109,7 @@
content.dataset.empty = strings.empty || '';
viewer.setAttribute('aria-label', strings.imagePreview || '');
imageClose.setAttribute('aria-label', strings.closeImage || '');
+ outlineTitle.textContent = strings.outline || '';
}
// Resources ---------------------------------------------------------------------------------
@@ -351,8 +368,10 @@
content.replaceChildren(root);
renderMarkmaps();
points = null;
+ const list = headings();
+ setOutline(list);
placeLine(topLine);
- post({ type: 'rendered', revision, headings: headings() });
+ post({ type: 'rendered', revision, headings: list });
}
function sourceLines(element) {
@@ -431,6 +450,7 @@
function placeLine(line) {
window.scrollTo(0, Math.max(0, yOfLine(line) - margin));
expectedY = window.scrollY;
+ markSection();
}
function onScroll() {
@@ -442,6 +462,7 @@
function report() {
reportFrame = 0;
topLine = lineOfY(window.scrollY + margin);
+ markSection();
post({ type: 'scrolled', line: topLine });
}
@@ -453,6 +474,321 @@
placeLine(topLine);
}
+ // Outline ---------------------------------------------------------------------------------------
+
+ // entries are the page's headings in order, as a tree: depth is how many headings it is under,
+ // parent the entry it is under (-1 for none), position its place among its siblings (from 1)
+ // and siblings how many they are, key what names it through a new rendering, and children
+ // whether headings are under it. A heading is under the nearest heading before it of a higher
+ // level, so a skipped level indents once.
+ let entries = [];
+ // folded holds the keys of the entries whose headings are hidden.
+ const folded = new Set();
+ // visible are the entries in the tree's rows, those not under a folded entry; rowOf is the row
+ // of each entry, -1 for one hidden.
+ let visible = [];
+ let rowOf = new Int32Array(0);
+ // drawn holds the row elements laid out, by row: only the rows in the tree's view and
+ // OUTLINE_OVERSCAN past each edge exist.
+ const drawn = new Map();
+ let outlineOpen = false;
+ // section is the entry of the section at the page's top, -1 before the first heading; focused
+ // is the entry the keys move from, -1 for none.
+ let section = -1;
+ let focused = -1;
+
+ function setOutline(list) {
+ const focusedKey = focused >= 0 ? entries[focused].key : null;
+ entries = [];
+ const stack = [];
+ const seen = new Map();
+ const counts = new Map();
+ for (const heading of list) {
+ while (stack.length > 0 && entries[stack[stack.length - 1]].level >= heading.level) stack.pop();
+ const parent = stack.length > 0 ? stack[stack.length - 1] : -1;
+ // Siblings of the same level and text are told apart by their order.
+ const name = (parent >= 0 ? entries[parent].key : '') + '\n' + heading.level + ' ' + heading.text;
+ const nth = seen.get(name) || 0;
+ seen.set(name, nth + 1);
+ const position = (counts.get(parent) || 0) + 1;
+ counts.set(parent, position);
+ if (parent >= 0) entries[parent].children = true;
+ stack.push(entries.length);
+ entries.push({
+ level: heading.level,
+ text: heading.text,
+ line: heading.line,
+ depth: stack.length - 1,
+ parent,
+ position,
+ siblings: 0,
+ key: name + '\n' + nth,
+ children: false
+ });
+ }
+ const keys = new Set();
+ for (const entry of entries) {
+ entry.siblings = counts.get(entry.parent);
+ keys.add(entry.key);
+ }
+ for (const key of folded) {
+ if (!keys.has(key)) folded.delete(key);
+ }
+ focused = focusedKey === null ? -1 : entries.findIndex(entry => entry.key === focusedKey);
+ section = -1;
+ showOutline();
+ }
+
+ // showOutline shows the outline while it is open and the page has headings, its rows laid out
+ // again. Opened, it scrolls to the section.
+ function showOutline() {
+ const hidden = !outlineOpen || entries.length === 0;
+ const opening = outline.hidden && !hidden;
+ outline.hidden = hidden;
+ layoutOutline();
+ if (opening) reveal(sectionRow());
+ }
+
+ function layoutOutline() {
+ visible = [];
+ rowOf = new Int32Array(entries.length).fill(-1);
+ let under = -1;
+ for (const [index, entry] of entries.entries()) {
+ if (under >= 0 && entry.depth > under) continue;
+ under = entry.children && folded.has(entry.key) ? entry.depth : -1;
+ rowOf[index] = visible.length;
+ visible.push(index);
+ }
+ if (focused >= 0 && rowOf[focused] < 0) focused = -1;
+ for (const element of drawn.values()) element.remove();
+ drawn.clear();
+ outlineRows.style.height = visible.length * OUTLINE_ROW + 'px';
+ updateActiveDescendant();
+ paintOutline();
+ }
+
+ // paintOutline lays out the rows in the tree's view and drops the rows that left it.
+ function paintOutline() {
+ if (outline.hidden) return;
+ const top = outlineTree.scrollTop - OUTLINE_PAD;
+ const first = Math.max(0, Math.floor(top / OUTLINE_ROW) - OUTLINE_OVERSCAN);
+ const last = Math.min(visible.length, Math.ceil((top + outlineTree.clientHeight) / OUTLINE_ROW) + OUTLINE_OVERSCAN);
+ for (const [row, element] of drawn) {
+ if (row < first || row >= last) {
+ element.remove();
+ drawn.delete(row);
+ }
+ }
+ const marked = shownSection();
+ for (let row = first; row < last; row++) {
+ let element = drawn.get(row);
+ if (!element) {
+ element = outlineRow(row);
+ drawn.set(row, element);
+ outlineRows.append(element);
+ }
+ const index = visible[row];
+ element.classList.toggle('active', index === marked);
+ element.classList.toggle('focused', index === focused);
+ element.setAttribute('aria-selected', String(index === marked));
+ }
+ }
+
+ function outlineRow(row) {
+ const index = visible[row];
+ const entry = entries[index];
+ const element = document.createElement('div');
+ element.className = 'outline-item';
+ element.id = 'outline-entry-' + index;
+ element.dataset.entry = String(index);
+ element.setAttribute('role', 'treeitem');
+ element.setAttribute('aria-level', String(entry.depth + 1));
+ element.setAttribute('aria-posinset', String(entry.position));
+ element.setAttribute('aria-setsize', String(entry.siblings));
+ element.style.top = row * OUTLINE_ROW + 'px';
+ element.style.paddingLeft = 4 + entry.depth * OUTLINE_INDENT + 'px';
+ element.title = entry.text;
+ const toggle = document.createElement('span');
+ toggle.className = 'outline-toggle';
+ if (entry.children) {
+ element.setAttribute('aria-expanded', String(!folded.has(entry.key)));
+ toggle.append(chevron());
+ }
+ const text = document.createElement('span');
+ text.className = 'outline-text';
+ text.textContent = entry.text;
+ element.append(toggle, text);
+ return element;
+ }
+
+ function chevron() {
+ const svg = document.createElementNS(SVG, 'svg');
+ svg.setAttribute('viewBox', '0 0 10 10');
+ svg.setAttribute('aria-hidden', 'true');
+ const path = document.createElementNS(SVG, 'path');
+ path.setAttribute('d', 'M3.5 1.5 7 5 3.5 8.5');
+ path.setAttribute('fill', 'none');
+ path.setAttribute('stroke', 'currentColor');
+ path.setAttribute('stroke-width', '1.5');
+ path.setAttribute('stroke-linecap', 'round');
+ path.setAttribute('stroke-linejoin', 'round');
+ svg.append(path);
+ return svg;
+ }
+
+ // reveal scrolls the tree as little as it takes to show row.
+ function reveal(row) {
+ if (row < 0 || outline.hidden) return;
+ const top = row * OUTLINE_ROW;
+ const bottom = top + OUTLINE_ROW + 2 * OUTLINE_PAD;
+ if (top < outlineTree.scrollTop) outlineTree.scrollTop = top;
+ else if (bottom > outlineTree.scrollTop + outlineTree.clientHeight) outlineTree.scrollTop = bottom - outlineTree.clientHeight;
+ paintOutline();
+ }
+
+ // sectionAt is the entry of the last heading at or above source line, -1 before the first.
+ function sectionAt(line) {
+ let low = 0;
+ let high = entries.length - 1;
+ let found = -1;
+ while (low <= high) {
+ const mid = (low + high) >> 1;
+ if (entries[mid].line <= line + SECTION_LEAD) {
+ found = mid;
+ low = mid + 1;
+ } else {
+ high = mid - 1;
+ }
+ }
+ return found;
+ }
+
+ // shownSection is the entry the section is marked on: its heading, or the nearest heading
+ // above it that is shown while it is folded away.
+ function shownSection() {
+ let index = section;
+ while (index >= 0 && rowOf[index] < 0) index = entries[index].parent;
+ return index;
+ }
+
+ function sectionRow() {
+ const index = shownSection();
+ return index >= 0 ? rowOf[index] : -1;
+ }
+
+ // markSection marks the section at the page's top and, while the pointer is not over the
+ // outline, scrolls the tree to it.
+ function markSection() {
+ const index = sectionAt(topLine);
+ if (index === section) return;
+ section = index;
+ if (outline.hidden) return;
+ paintOutline();
+ if (!outline.matches(':hover')) reveal(sectionRow());
+ }
+
+ function setFolded(index, closed) {
+ const entry = entries[index];
+ if (!entry.children || folded.has(entry.key) === closed) return;
+ if (closed) folded.add(entry.key);
+ else folded.delete(entry.key);
+ layoutOutline();
+ }
+
+ // goTo puts entry index's heading at the page's top and tells the host, which moves the source.
+ function goTo(index) {
+ topLine = entries[index].line;
+ placeLine(topLine);
+ post({ type: 'scrolled', line: topLine });
+ }
+
+ function focusEntry(index) {
+ if (index < 0 || index >= entries.length || rowOf[index] < 0) return;
+ focused = index;
+ updateActiveDescendant();
+ reveal(rowOf[index]);
+ paintOutline();
+ }
+
+ function updateActiveDescendant() {
+ if (focused >= 0 && rowOf[focused] >= 0) outlineTree.setAttribute('aria-activedescendant', 'outline-entry-' + focused);
+ else outlineTree.removeAttribute('aria-activedescendant');
+ }
+
+ function closeOutline() {
+ outlineOpen = false;
+ showOutline();
+ post({ type: 'outline', open: false });
+ }
+
+ function onOutlineKey(event) {
+ if (event.altKey || event.ctrlKey || event.metaKey || visible.length === 0) return;
+ const row = focused >= 0 ? rowOf[focused] : -1;
+ const start = row >= 0 ? row : Math.max(sectionRow(), 0);
+ const page = Math.max(1, Math.floor(outlineTree.clientHeight / OUTLINE_ROW) - 1);
+ const entry = row >= 0 ? entries[focused] : null;
+ let target = -1;
+ switch (event.key) {
+ case 'ArrowDown':
+ target = row >= 0 ? Math.min(row + 1, visible.length - 1) : start;
+ break;
+ case 'ArrowUp':
+ target = row >= 0 ? Math.max(row - 1, 0) : start;
+ break;
+ case 'PageDown':
+ target = Math.min(start + page, visible.length - 1);
+ break;
+ case 'PageUp':
+ target = Math.max(start - page, 0);
+ break;
+ case 'Home':
+ target = 0;
+ break;
+ case 'End':
+ target = visible.length - 1;
+ break;
+ case 'ArrowRight':
+ if (!entry) target = start;
+ else if (entry.children && folded.has(entry.key)) setFolded(focused, false);
+ else if (entry.children) target = row + 1;
+ break;
+ case 'ArrowLeft':
+ if (!entry) target = start;
+ else if (entry.children && !folded.has(entry.key)) setFolded(focused, true);
+ else if (entry.parent >= 0) target = rowOf[entry.parent];
+ break;
+ case 'Enter':
+ case ' ':
+ if (entry) goTo(focused);
+ else target = start;
+ break;
+ default:
+ return;
+ }
+ event.preventDefault();
+ if (target >= 0) focusEntry(visible[target]);
+ }
+
+ outlineTree.addEventListener('click', event => {
+ const row = event.target instanceof Element ? event.target.closest('.outline-item') : null;
+ if (!row) return;
+ const index = Number(row.dataset.entry);
+ focused = index;
+ updateActiveDescendant();
+ if (entries[index].children && event.target.closest('.outline-toggle')) {
+ setFolded(index, !folded.has(entries[index].key));
+ } else {
+ paintOutline();
+ goTo(index);
+ }
+ });
+ outlineTree.addEventListener('focus', () => {
+ if (focused < 0 || rowOf[focused] < 0) focusEntry(visible[Math.max(sectionRow(), 0)] ?? -1);
+ });
+ outlineTree.addEventListener('keydown', onOutlineKey);
+ outlineTree.addEventListener('scroll', paintOutline, { passive: true });
+ window.addEventListener('resize', paintOutline);
+
// Links and images ------------------------------------------------------------------------------
function jumpTo(fragment) {
@@ -511,7 +847,9 @@
if (event.target instanceof Element && event.target.closest('a')) event.preventDefault();
});
document.addEventListener('keydown', event => {
- if (event.key === 'Escape' && !viewer.hidden) closeImage();
+ if (event.key !== 'Escape') return;
+ if (!viewer.hidden) closeImage();
+ else if (!outline.hidden) closeOutline();
});
window.addEventListener('scroll', onScroll, { passive: true });
new ResizeObserver(onResize).observe(content);
@@ -544,6 +882,10 @@
topLine = Math.max(1, Number(message.line) || 1);
placeLine(topLine);
break;
+ case 'outline':
+ outlineOpen = message.open === true;
+ showOutline();
+ break;
}
};
}
diff --git a/desktop/internal/webpreview/webpreview.go b/desktop/internal/webpreview/webpreview.go
index bbf10d656e..704c95a3af 100644
--- a/desktop/internal/webpreview/webpreview.go
+++ b/desktop/internal/webpreview/webpreview.go
@@ -86,6 +86,8 @@ type Heading struct {
// - "rendered" (Markdown): Revision was laid out, with its Headings.
// - "scrolled" (Markdown): the user scrolled the page to source Line, fractional.
// - "link" (Markdown): the user followed Href, which is not an anchor of the page.
+// - "outline" (Markdown): the user opened or closed the page's outline in the page, as Open
+// says.
// - "scale" (image): the image is shown at Scale, Fit is its fitted scale and Width and Height
// its own size.
// - "failed" (image): the image could not be loaded.
@@ -95,6 +97,7 @@ type Message struct {
Headings []Heading `json:"headings"`
Line float64 `json:"line"`
Href string `json:"href"`
+ Open bool `json:"open"`
Scale float64 `json:"scale"`
Fit float64 `json:"fit"`
Width int `json:"width"`
diff --git a/desktop/internal/workbench/markdown_preview.go b/desktop/internal/workbench/markdown_preview.go
index 245ecdd550..b4d32c9f4c 100644
--- a/desktop/internal/workbench/markdown_preview.go
+++ b/desktop/internal/workbench/markdown_preview.go
@@ -40,6 +40,10 @@ const (
// markdownContentsMax is the most the heading list grows to before it scrolls.
markdownContentsMax = 400
markdownContentsWidth = 280
+ // markdownContentsInset is the space at each end of a row of the heading list, and
+ // markdownContentsIndent how much further in each deeper level starts.
+ markdownContentsInset = 8
+ markdownContentsIndent = 12
)
// pageMode is how the tab of a file with a page shows it, a Markdown file or an SVG file
@@ -308,8 +312,12 @@ func (a *App) markdownPage(c ui.C, p *project, d *document) {
}
// markdownContentsButton declares, in the tab strip before the mode switch, the Contents button
-// of d's page and, while it is open, the list of headings under it. It is not shown with the
-// source alone or while the page has no headings.
+// of d's page, which looks pressed while the contents are shown. It is not shown with the source
+// alone or while the page has no headings.
+//
+// A web page draws its contents itself, as an outline over its top right that stays while the
+// user goes from heading to heading (markdown.js); the button turns it on and off. The page Viva
+// draws shows them as a list under the button, which closes once a heading is chosen.
func (a *App) markdownContentsButton(c ui.C, p *project, d *document) {
if d.pageMode == pageSource {
return
@@ -320,22 +328,46 @@ func (a *App) markdownContentsButton(c ui.C, p *project, d *document) {
s.sync(d)
}
if s.too || len(s.headings) == 0 {
- s.contentsOpen = false
+ s.showContents(false)
return
}
title := i18n.Shared(a.language(), "desktop.markdown.contents")
- jump := -1
- button := ui.Button(c.Part("contents"), title).Icon(icons.ListTree).IconOnly().Ghost().
- Size(shellHideSize, shellHideSize).Shrink(0).Tooltip(title)
+ on := s.contentsOpen
+ k := c.Part("contents")
+ button := ui.Row(k).Size(shellHideSize, shellHideSize).Shrink(0).Center().Radius(a.theme.Metrics.RadiusItem()).
+ HitWith(ui.ID(k), title, gfx.HitOptions{Role: gfx.RoleButton, Expandable: true, Expanded: on, Cursor: gfx.PointerCursorHand}).
+ Pressed(ui.Look{}.Background(a.colors.Active))
+ icon := a.colors.Subtle
+ if on {
+ button = button.Background(a.colors.Active)
+ icon = a.colors.Text
+ } else {
+ button = button.Hover(ui.Look{}.Background(a.colors.Hover))
+ }
+ button.Tooltip(title).Children(func() {
+ ui.Icon(k, icons.ListTree).Size(shellIconSize, shellIconSize).Color(icon).
+ StateFrom(button).Hover(ui.Look{}.Color(a.colors.Text))
+ })
if button.Clicked() {
- s.contentsOpen = !s.contentsOpen
+ s.showContents(!on)
+ }
+ if s.web != nil {
+ return
+ }
+ jump := -1
+ // Each heading is indented by how much deeper it is than the shallowest heading, so a page
+ // whose headings start at the second level is not indented throughout.
+ top := s.headings[0].level
+ for _, h := range s.headings {
+ top = min(top, h.level)
}
spec := ui.PopoverSpec{Align: ui.End, Width: markdownContentsWidth, ConsumeOutsidePress: true, Title: title}
ui.PopoverWith(c, button, spec, &s.contentsOpen, func() {
height := min(float32(len(s.headings))*markdownContentsRow, markdownContentsMax)
ui.List(c, &s.contents, len(s.headings), func(row ui.ListRow) {
h := s.headings[row.Index]
- row.Element.FillWidth().Height(markdownContentsRow).PadSides(8+float32(max(h.level-1, 0))*12, 0, 8, 0).Items(ui.Center).
+ indent := markdownContentsInset + float32(h.level-top)*markdownContentsIndent
+ row.Element.FillWidth().Height(markdownContentsRow).PadSides(0, markdownContentsInset, 0, indent).Items(ui.Center).
Radius(a.theme.Metrics.RadiusItem()).Hover(ui.Look{}.Background(a.colors.Hover)).Children(func() {
ui.Text(row.C, h.text).FontSize(12.5).Color(a.colors.Text).Ellipsis().Shrink(1)
})
@@ -353,6 +385,17 @@ func (a *App) markdownContentsButton(c ui.C, p *project, d *document) {
}
}
+// showContents shows or hides the page's contents, telling a web page, which draws them.
+func (s *markdownPreviewState) showContents(open bool) {
+ if s.contentsOpen == open {
+ return
+ }
+ s.contentsOpen = open
+ if w := s.web; w != nil {
+ w.entry.view.Send(markdownPageOutline{Type: "outline", Open: open})
+ }
+}
+
// jump puts heading index at the top of d's page and, beside the source, the editor at its line.
func (s *markdownPreviewState) jump(d *document, index int) {
heading := s.headings[index]
diff --git a/desktop/internal/workbench/markdown_preview_test.go b/desktop/internal/workbench/markdown_preview_test.go
index 5060044f9a..9558b70b17 100644
--- a/desktop/internal/workbench/markdown_preview_test.go
+++ b/desktop/internal/workbench/markdown_preview_test.go
@@ -157,6 +157,55 @@ func TestMarkdownContentsJumpsToHeading(t *testing.T) {
}
}
+// TestMarkdownContentsIndentsHeadingsByLevel: the Contents list of the page Viva draws shows each
+// heading on a row of its own, indented by how much deeper it is than the shallowest heading.
+func TestMarkdownContentsIndentsHeadingsByLevel(t *testing.T) {
+ h := newHarness(t, &testKernel{Client: core.NewClient()})
+ openMarkdown(t, h, "## Intro\n\nText.\n\n### Setup\n\n#### Keys\n\n## Usage\n")
+ title := i18n.Shared(h.app.language(), "desktop.markdown.contents")
+ h.click(center(h.hitLabeled(title)))
+ rows := map[string]gfx.Rect{}
+ expanded := false
+ for _, label := range h.driver.Snapshot().Labels {
+ if label.FontSize == 12.5 {
+ rows[label.Value] = label.Bounds
+ }
+ }
+ var list gfx.Rect
+ for _, hit := range h.driver.Snapshot().Hits {
+ switch {
+ case hit.Label != title || hit.IsLabel:
+ case hit.Role == gfx.RoleButton:
+ expanded = hit.Expanded
+ case hit.Role == gfx.RoleListBox:
+ list = hit.Bounds
+ }
+ }
+ order := []string{"Intro", "Setup", "Keys", "Usage"}
+ for _, name := range order {
+ if rows[name].Width == 0 {
+ t.Fatalf("the list does not show %q: %v", name, rows)
+ }
+ }
+ if !expanded {
+ t.Fatal("the Contents button does not say the list is open")
+ }
+ for i := 1; i < len(order); i++ {
+ above, below := rows[order[i-1]], rows[order[i]]
+ if below.Y < above.Y+above.Height {
+ t.Fatalf("%q at %v overlaps %q at %v", order[i], below, order[i-1], above)
+ }
+ }
+ intro, setup, keys, usage := rows["Intro"].X, rows["Setup"].X, rows["Keys"].X, rows["Usage"].X
+ if setup-intro != markdownContentsIndent || keys-setup != markdownContentsIndent || usage != intro {
+ t.Fatalf("the headings start at %v, %v, %v and %v, want each level %d further in", intro, setup, keys, usage, markdownContentsIndent)
+ }
+ // The shallowest headings are not indented: the page's headings start at the second level.
+ if list.Width == 0 || intro-list.X != markdownContentsInset {
+ t.Fatalf("the shallowest heading starts at %v in the list at %v, want %d in", intro, list, markdownContentsInset)
+ }
+}
+
// editorTopLine is the line most of whose first row is at the top of d's editor.
func editorTopLine(d *document) int {
v := d.view
diff --git a/desktop/internal/workbench/markdown_web.go b/desktop/internal/workbench/markdown_web.go
index a325e63bca..53014fdf6e 100644
--- a/desktop/internal/workbench/markdown_web.go
+++ b/desktop/internal/workbench/markdown_web.go
@@ -22,6 +22,11 @@ import (
// the editor scrolls, each without echoing the other's move. Links come back to the host, which
// follows them as Core resolves them (followMarkdownLink), and the page's images are served as
// Core resolves them. The source is rendered again after each change, one rendering at a time.
+//
+// The page draws its contents itself, as an outline of its headings at its top right. The
+// Contents button in the tab strip tells the page to show or hide it; the page tells the host
+// when the user closed it there, and leads the source to a heading chosen in it as it does when
+// the user scrolls it.
// markdownRenderTimeout bounds Core's rendering of one revision.
const markdownRenderTimeout = 10 * time.Second
@@ -57,6 +62,10 @@ type (
Type string `json:"type"`
Line float64 `json:"line"`
}
+ markdownPageOutline struct {
+ Type string `json:"type"`
+ Open bool `json:"open"`
+ }
)
// markdownWebPage is the web page of d, opened the first time it is shown and again after it was
@@ -185,6 +194,7 @@ func (a *App) markdownWebMessage(p *project, d *document, s *markdownPreviewStat
_, s.editorScroll = d.view.ScrollOffset()
}
w.entry.view.Send(markdownPageScroll{Type: "scroll", Line: w.line})
+ w.entry.view.Send(markdownPageOutline{Type: "outline", Open: s.contentsOpen})
case "rendered":
s.headings = s.headings[:0]
for _, heading := range message.Headings {
@@ -195,6 +205,9 @@ func (a *App) markdownWebMessage(p *project, d *document, s *markdownPreviewStat
s.leadEditor(d)
case "link":
a.followMarkdownLink(p, d, s, message.Href)
+ case "outline":
+ // The page shows or hides the outline itself; it is not told again.
+ s.contentsOpen = message.Open
}
a.invalidator.Invalidate()
}
@@ -210,6 +223,7 @@ func (a *App) markdownWebSetup(w *markdownWeb) {
"mermaidFailed": i18n.Shared(language, "desktop.markdown.mermaidFailed"),
"markmap": i18n.Shared(language, "desktop.markdown.markmap"),
"markmapFailed": i18n.Shared(language, "desktop.markdown.markmapFailed"),
+ "outline": i18n.Shared(language, "desktop.markdown.contents"),
}})
}
diff --git a/desktop/internal/workbench/markdown_web_test.go b/desktop/internal/workbench/markdown_web_test.go
index 0fca04050f..2124a5a796 100644
--- a/desktop/internal/workbench/markdown_web_test.go
+++ b/desktop/internal/workbench/markdown_web_test.go
@@ -85,10 +85,10 @@ func longMarkdownHeadings() []webpreview.Heading {
}
// TestMarkdownWebPageRendersCoreHTMLAndScrollsWithTheSource: a Markdown file's page is a web page
-// given Core's HTML once it loads, with the line at the editor's top; the Contents list jumps to a
-// heading the page reported, the source and the page lead each other without either echoing the
-// other, an edit is rendered again, and the page coming back after the source was shown alone
-// takes up the source's line.
+// given Core's HTML once it loads, with the line at the editor's top; the Contents button turns
+// the page's own outline on and off, a heading chosen there leads the source, the source and the
+// page lead each other without either echoing the other, an edit is rendered again, and the page
+// coming back after the source was shown alone takes up the source's line.
func TestMarkdownWebPageRendersCoreHTMLAndScrollsWithTheSource(t *testing.T) {
h := newHarness(t, &testKernel{Client: core.NewClient()})
pages := fakePreviews(h)
@@ -117,27 +117,40 @@ func TestMarkdownWebPageRendersCoreHTMLAndScrollsWithTheSource(t *testing.T) {
t.Fatalf("the loaded page was scrolled %+v, want to line 1", scrolls)
}
+ if outlines := sentOf[markdownPageOutline](page); len(outlines) != 1 || outlines[0].Open {
+ t.Fatalf("the loaded page was told its outline is %+v, want closed", outlines)
+ }
+
+ // The page draws its contents itself: the button turns its outline on, and the host draws no
+ // list of its own.
page.config.OnMessage(webpreview.Message{Type: "rendered", Revision: d.view.Revision(), Headings: longMarkdownHeadings()})
h.settle()
h.click(center(h.hitLabeled(i18n.Shared(h.app.language(), "desktop.markdown.contents"))))
- var entry gfx.Rect
+ h.settle()
+ if outlines := sentOf[markdownPageOutline](page); !s.contentsOpen || len(outlines) != 2 || !outlines[1].Open {
+ t.Fatalf("Contents told the page %+v, want its outline shown", outlines)
+ }
for _, label := range h.driver.Snapshot().Labels {
- if label.Value == "Part 12" && label.FontSize == 12.5 {
- entry = label.Bounds
+ if label.Value == "Part 12" {
+ t.Fatalf("the host drew the headings over the web page at %v", label.Bounds)
}
}
- if !s.contentsOpen || entry.Width == 0 {
- t.Fatalf("Contents does not list the page's headings: %v", h.driver.Snapshot().Labels)
- }
- h.click(center(entry))
+ // Part 12 chosen in the outline, the page scrolls itself there and leads the source.
+ page.config.OnMessage(webpreview.Message{Type: "scrolled", Line: 56})
h.settle()
- scrolls := sentOf[markdownPageScroll](page)
- if s.contentsOpen || len(scrolls) != 2 || scrolls[1].Line != 56 {
- t.Fatalf("choosing Part 12 scrolled the page %+v, want once more to line 56", scrolls)
- }
if line := editorTopLine(d); line != 55 {
t.Fatalf("the source's top line is %d, want the heading's line 55", line)
}
+ if scrolls := sentOf[markdownPageScroll](page); len(scrolls) != 1 {
+ t.Fatalf("the page was scrolled back after a heading was chosen in it: %+v", scrolls)
+ }
+ // Closed in the page, the outline is not shown when the button is drawn again, and the page
+ // is not told what it did itself.
+ page.config.OnMessage(webpreview.Message{Type: "outline", Open: false})
+ h.settle()
+ if outlines := sentOf[markdownPageOutline](page); s.contentsOpen || len(outlines) != 2 {
+ t.Fatalf("the page closed its outline, the host has it open %v and told the page %+v", s.contentsOpen, outlines)
+ }
source := editorRect(h, d)
lineHeight := d.view.LineHeight()
@@ -145,8 +158,8 @@ func TestMarkdownWebPageRendersCoreHTMLAndScrollsWithTheSource(t *testing.T) {
t.Fatal(err)
}
h.settle()
- scrolls = sentOf[markdownPageScroll](page)
- if editorTopLine(d) != 95 || len(scrolls) != 3 || math.Abs(scrolls[2].Line-96) > 0.01 {
+ scrolls := sentOf[markdownPageScroll](page)
+ if editorTopLine(d) != 95 || len(scrolls) != 2 || math.Abs(scrolls[1].Line-96) > 0.01 {
t.Fatalf("the source at line %d scrolled the page %+v, want to line 96", editorTopLine(d), scrolls)
}
@@ -156,7 +169,7 @@ func TestMarkdownWebPageRendersCoreHTMLAndScrollsWithTheSource(t *testing.T) {
if line := editorTopLine(d); line != 45 {
t.Fatalf("the source's top line is %d after the page scrolled, want 45", line)
}
- if got := len(sentOf[markdownPageScroll](page)); got != 3 {
+ if got := len(sentOf[markdownPageScroll](page)); got != 2 {
t.Fatalf("the page was scrolled back after it led the source: %d scrolls", got)
}
diff --git a/shared/platform-feature-matrix/features/markdown-preview-outline.json b/shared/platform-feature-matrix/features/markdown-preview-outline.json
index 2915c09e47..07c88a9857 100644
--- a/shared/platform-feature-matrix/features/markdown-preview-outline.json
+++ b/shared/platform-feature-matrix/features/markdown-preview-outline.json
@@ -2,13 +2,19 @@
"id": "markdown-preview-outline",
"area": "编辑器",
"group": "Markdown",
- "capability": "Markdown 预览目录默认展开、全高滚动与标题跳转",
+ "capability": "Markdown 预览目录:右上角浮动大纲,按层级缩进与折叠,跟随当前章节并跳转到标题",
"macos": {
"implementationStatus": "implemented",
"verificationStatus": "pending",
"evidence": [
"desktop/internal/workbench/markdown_preview.go",
- "desktop/internal/workbench/markdown_preview_test.go"
+ "desktop/internal/workbench/markdown_web.go",
+ "desktop/internal/webpreview/webpreview.go",
+ "desktop/internal/webpreview/assets/markdown.html",
+ "desktop/internal/webpreview/assets/markdown.js",
+ "desktop/internal/webpreview/assets/markdown.css",
+ "desktop/internal/workbench/markdown_preview_test.go",
+ "desktop/internal/workbench/markdown_web_test.go"
]
},
"windows": {
@@ -16,11 +22,17 @@
"verificationStatus": "pending",
"evidence": [
"desktop/internal/workbench/markdown_preview.go",
- "desktop/internal/workbench/markdown_preview_test.go"
+ "desktop/internal/workbench/markdown_web.go",
+ "desktop/internal/webpreview/webpreview.go",
+ "desktop/internal/webpreview/assets/markdown.html",
+ "desktop/internal/webpreview/assets/markdown.js",
+ "desktop/internal/webpreview/assets/markdown.css",
+ "desktop/internal/workbench/markdown_preview_test.go",
+ "desktop/internal/workbench/markdown_web_test.go"
]
},
"owner": "Editor",
- "verification": "在 macOS 原生 Lithe 打开含 60 节标题的 Markdown,验证默认展开、全高目录独立滚动、末尾标题跳转后保持展开、按钮与 Escape 收起;分栏中编辑保存及外部刷新保留折叠选择,删除全部标题隐藏目录,恢复标题保留展开偏好;检查短文档与无标题文档、宽预览正文避让和窄预览可收起。Viva 新桌面端:打开含 40 节标题的 Markdown,点目录选末尾标题后源码与渲染页同时滚到该标题;编辑新增标题后目录更新(scripts/desktop/desktop-go.sh test ./internal/workbench -run TestMarkdown -count=1)。 补充无标题时按 Escape 关闭图片后恢复标题的展开偏好验证。",
+ "verification": "在 macOS 原生 Lithe 打开含 60 节标题的 Markdown,验证默认展开、全高目录独立滚动、末尾标题跳转后保持展开、按钮与 Escape 收起;分栏中编辑保存及外部刷新保留折叠选择,删除全部标题隐藏目录,恢复标题保留展开偏好;检查短文档与无标题文档、宽预览正文避让和窄预览可收起。补充无标题时按 Escape 关闭图片后恢复标题的展开偏好验证。Viva 新桌面端(web view 页):在深浅主题打开含多级标题与 80 节以上标题的 Markdown,点“目录”按钮在页面右上角显示大纲面板:标题栏与分隔线、每深一级多缩进一档、有子标题的行带折叠箭头且折叠只改大纲不滚动页面、超长标题省略;点行或用方向键与回车选标题后源码与渲染页一起滚到该标题,当前章节高亮随页面滚动更新、折叠时落在可见的上级;编辑后重新渲染保留折叠;面板内只排版视口附近的行;按 Escape 或再点按钮关闭面板并同步按钮状态;无标题时隐藏面板与按钮。Viva 原生页(Linux 无 web 引擎):弹出标题列表按级别缩进且行不重叠。自动回归:scripts/desktop/desktop-go.sh test ./internal/workbench ./internal/webpreview -run 'Markdown|Preview|Serves|EveryPage' -count=1;页面交互用无头 Chrome 驱动 markdown.js 断言折叠、跳转、键盘、虚拟化与当前章节高亮。",
"legacy": {
"revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36",
"macos": {
@@ -39,5 +51,5 @@
"verificationStatus": "not-applicable"
}
},
- "notes": "Viva:标签栏模式切换前的“目录”按钮(web view 页与原生页共用)打开标题列表弹窗,标题由源码派生、随编辑更新,按级别缩进,列表最高 400 点、可独立滚动;点击或回车关闭弹窗并把源码与渲染页一起滚到该标题。无标题时不显示按钮。"
+ "notes": "Viva:标签栏模式切换前的“目录”按钮(可展开样式,打开时高亮)。有系统 web 引擎(macOS WKWebView、Windows WebView2)时,大纲画在 web view 页内:页面从渲染结果的标题(带源码行)建树,右上角浮动面板,固定行高虚拟化,只创建视口附近的行;折叠状态按父级、层级、文本和同名序号组成的稳定键保存,重新渲染后保留;当前章节随页面顶行高亮。宿主用 outline{open} 消息打开或关闭面板,页面内按 Escape 关闭时回报 outline{open:false} 同步按钮。Linux 没有 web 引擎时仍用 Viva 原生弹出列表,按级别缩进,点击或回车跳转并关闭。无标题时不显示按钮。"
}