mirror of
https://activitypub.software/TransFem-org/sfm-js
synced 2024-11-22 05:55:13 +00:00
inspect API accept a single node.
This commit is contained in:
parent
391fcbfe90
commit
be39aab80d
3 changed files with 31 additions and 7 deletions
18
src/api.ts
18
src/api.ts
|
@ -1,6 +1,6 @@
|
|||
import peg from 'pegjs';
|
||||
import { MfmNode, MfmPlainNode } from './node';
|
||||
import { stringifyNode, stringifyTree } from './util';
|
||||
import { MfmNode, MfmPlainNode, TEXT } from './node';
|
||||
import { stringifyNode, stringifyTree, inspectOne } from './util';
|
||||
|
||||
const parser: peg.Parser = require('./parser');
|
||||
|
||||
|
@ -37,13 +37,17 @@ export function toString(node: MfmNode | MfmNode[]): string {
|
|||
/**
|
||||
* Inspects the MfmNode tree.
|
||||
*/
|
||||
export function inspect(nodes: MfmNode[], action: (node: MfmNode) => void): void {
|
||||
for (const node of nodes) {
|
||||
action(node);
|
||||
if (node.children != null) {
|
||||
inspect(node.children, action);
|
||||
export function inspect(node: MfmNode, action: (node: MfmNode) => void): void
|
||||
export function inspect(nodes: MfmNode[], action: (node: MfmNode) => void): void
|
||||
export function inspect(node: (MfmNode | MfmNode[]), action: (node: MfmNode) => void): void {
|
||||
if (Array.isArray(node)) {
|
||||
for (const n of node) {
|
||||
inspectOne(n, action);
|
||||
}
|
||||
}
|
||||
else {
|
||||
inspectOne(node, action);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -147,6 +147,15 @@ export function stringifyTree(nodes: MfmNode[]): string {
|
|||
return dest.map(n => stringifyNode(n)).join('');
|
||||
}
|
||||
|
||||
export function inspectOne(node: MfmNode, action: (node: MfmNode) => void) {
|
||||
action(node);
|
||||
if (node.children != null) {
|
||||
for (const child of node.children) {
|
||||
inspectOne(child, action);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// dynamic consuming
|
||||
//
|
||||
|
|
11
test/api.ts
11
test/api.ts
|
@ -32,6 +32,17 @@ after`;
|
|||
});
|
||||
assert.strictEqual(mfm.toString(result), 'hello [tada everynyan!]');
|
||||
});
|
||||
|
||||
it('replace text (one item)', () => {
|
||||
const input = 'good morning [tada everyone!]';
|
||||
const result = mfm.parse(input);
|
||||
mfm.inspect(result[1], node => {
|
||||
if (node.type == 'text') {
|
||||
node.props.text = node.props.text.replace(/one/g, 'nyan');
|
||||
}
|
||||
});
|
||||
assert.strictEqual(mfm.toString(result), 'good morning [tada everynyan!]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('extract', () => {
|
||||
|
|
Loading…
Reference in a new issue