Skip to content

Examples (list)

Bhsd edited this page Apr 17, 2026 · 6 revisions

Other Languages

增加列表项的缩进

展开

你可以在页面中增加定义列表的缩进。此示例演示了 ListToken 的用法。

// Increasing indentation of list items (main)
// 包含定义列表的页面内容
import type {ListToken} from 'wikiparser-node';
const content = `: Foo
:: Bar`,
	root = Parser.parse(content);
for (const list of root.querySelectorAll<ListToken>('list')) {
	if (!list.ul && !list.ol && !list.dt) {
		list.indent++;
	}
}
assert.equal(
	root,
	`::Foo
:::Bar`,
);

将定义项转换为章节标题

展开

你可以在页面中将定义项转换为章节标题。此示例演示了 Token.prototype.buildListsListToken 的用法。

// Converting definition terms to section headers (main)
// 包含定义项的页面内容
import type {ListToken, HeadingToken, DdToken} from 'wikiparser-node';
const content = `== Foo ==
; Bar
Baz`,
	root = Parser.parse(content);
root.buildLists();
const sections = root.sections();
for (const dt of root.querySelectorAll<ListToken>('root > list')) {
	const {nextSibling} = dt;
	if (
		dt.ul || dt.ol || dt.dl
		|| nextSibling?.type !== 'list-range'
		|| !nextSibling.text().trim()
		// 不是孤立的定义项
		|| nextSibling.nextSibling?.is<DdToken>('dd')
		|| nextSibling.nextSibling?.text() === '\n'
		&& nextSibling.nextSibling.nextSibling?.type === 'list'
	) {
		continue;
	}
	const level = sections.findLast(
		({childNodes}) => childNodes.includes(dt),
	)?.querySelector<HeadingToken>('heading')?.level;
	if (level) {
		const title = nextSibling.text().trim(),
			equals = '='.repeat(level + 1);
		nextSibling.remove();
		dt.replaceWith(`${equals} ${title} ${equals}`);
	}
}
assert.equal(
	root,
	`== Foo ==
=== Bar ===
Baz`,
);

Clone this wiki locally