Skip to content

Commit

Permalink
#34
Browse files Browse the repository at this point in the history
  • Loading branch information
marihachi committed Mar 27, 2021
1 parent ffa45ab commit 57e687e
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 5 deletions.
5 changes: 5 additions & 0 deletions src/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ export type MfmNode = MfmBlock | MfmInline;

export type MfmBlock = MfmQuote | MfmSearch | MfmCodeBlock | MfmMathBlock | MfmCenter;

const blockTypes: MfmNode['type'][] = [ 'quote', 'search', 'blockCode', 'mathBlock', 'center' ];
export function isMfmBlock(node: MfmNode): node is MfmBlock {
return blockTypes.includes(node.type);
}

export type MfmQuote = {
type: 'quote';
props?: { };
Expand Down
48 changes: 43 additions & 5 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MfmNode } from './node';
import { isMfmBlock, MfmNode } from './node';

export function createNode(type: string, props?: Record<string, any>, children?: MfmNode[]): MfmNode {
const node: any = { type };
Expand Down Expand Up @@ -45,7 +45,7 @@ export function stringifyNode(node: MfmNode): string {
switch(node.type) {
// block
case 'quote': {
return stringifyTree(node.children).split('\n').map(line => `>${line}`).join('\n');
return stringifyTree(node.children).split('\n').map(line => `> ${line}`).join('\n');
}
case 'search': {
return node.props.content;
Expand All @@ -57,7 +57,7 @@ export function stringifyNode(node: MfmNode): string {
return `\\[\n${ node.props.formula }\n\\]`;
}
case 'center': {
return `<center>${ stringifyTree(node.children) }</center>`;
return `<center>\n${ stringifyTree(node.children) }\n</center>`;
}
// inline
case 'emoji': {
Expand Down Expand Up @@ -122,8 +122,46 @@ export function stringifyNode(node: MfmNode): string {
throw new Error('unknown mfm node');
}

export function stringifyTree(tree: MfmNode[]): string {
return tree.map(n => stringifyNode(n)).join('');
enum stringifyState {
none = 0,
inline,
block
};

export function stringifyTree(nodes: MfmNode[]): string {
let dest: MfmNode[] = [];
let state: stringifyState = stringifyState.none;

for (const node of nodes) {
// 文脈に合わせて改行を追加する。
// none -> inline : No
// none -> block : No
// inline -> inline : No
// inline -> block : Yes
// block -> inline : Yes
// block -> block : Yes

let pushLf: boolean = true;
if (isMfmBlock(node)) {
if (state == stringifyState.none) {
pushLf = false;
}
state = stringifyState.block;
}
else {
if (state == stringifyState.none || state == stringifyState.inline) {
pushLf = false;
}
state = stringifyState.inline;
}
if (pushLf) {
dest.push(createNode('text', { text: '\n' }));
}

dest.push(node);
}

return dest.map(n => stringifyNode(n)).join('');
}

//
Expand Down

0 comments on commit 57e687e

Please sign in to comment.