Skip to content

Commit

Permalink
feat(hiccup-markdown): add table serializer & test, update deps
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Mar 22, 2020
1 parent 502594c commit 7cecf24
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/hiccup-markdown/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"@thi.ng/fsm": "^2.4.0",
"@thi.ng/hiccup": "^3.2.13",
"@thi.ng/strings": "^1.7.0",
"@thi.ng/text-canvas": "^0.2.1",
"@thi.ng/transducers": "^6.4.1",
"tslib": "^1.11.1"
},
Expand Down
49 changes: 48 additions & 1 deletion packages/hiccup-markdown/src/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { DEFAULT, defmulti, MultiFn3 } from "@thi.ng/defmulti";
import { illegalArgs } from "@thi.ng/errors";
import { normalize } from "@thi.ng/hiccup";
import { repeat, wrap } from "@thi.ng/strings";
import { Border, tableCanvas, toString } from "@thi.ng/text-canvas";
import { map } from "@thi.ng/transducers";

interface SerializeState {
indent: number;
Expand Down Expand Up @@ -156,5 +158,50 @@ serializeElement.addAll({

br: () => "\\\n",

hr: () => "\n---\n"
hr: () => "\n---\n",

table: (el, ctx) => {
let thead: any[] = [];
let tbody: any[] = [];
let colWidths: number[] = [];

const rows = (rows: any[]) =>
rows.map((x: any) =>
normalize(x)[2].map((td: any, i: number) => {
const cell = serialize(td, ctx);
colWidths[i] = Math.max(colWidths[i] || 3, cell.length);
return cell;
})
);

for (let child of el[2]) {
child = normalize(child);
switch (child[0]) {
case "thead":
thead = rows(child[2]);
break;
case "tbody":
tbody = rows(child[2]);
break;
}
}
return (
"\n" +
toString(
tableCanvas(
{
cols: [...map((width) => ({ width }), colWidths)],
padding: [1, 0],
border: Border.V
},
[
...thead,
[...map((w) => repeat("-", w), colWidths)],
...tbody
]
)
) +
"\n"
);
}
});
33 changes: 33 additions & 0 deletions packages/hiccup-markdown/test/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,33 @@ describe("hiccup-markdown", () => {
"baz"
],
["blockquote", "So long and thanks for all the fish."],
[
"table",
[
"thead",
[
"tr",
["th", "ID"],
["th", "Name"],
["th", "Comment"]
]
],
[
"tbody",
[
"tr",
["td", 1],
["td", ["code", "map()"]],
["td", "Transform"]
],
[
"tr",
["td", 2],
["td", ["code", "filter()"]],
["td", "Predicate"]
]
]
],
[
"p",
"More info ",
Expand Down Expand Up @@ -89,6 +116,12 @@ My magic number is: 42
> So long and thanks for all the fish.
| ID | Name | Comment |
| --- | ---------- | --------- |
| 1 | \`map()\` | Transform |
| 2 | \`filter()\` | Predicate |
More info [here](http://thi.ng/hiccup-markdown).
`
);
Expand Down

0 comments on commit 7cecf24

Please sign in to comment.