@r_masseater/tako 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,87 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 masseater
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ @tanstack/eslint-plugin-start
26
+
27
+ MIT License
28
+
29
+ Copyright (c) 2021-present Tanner Linsley
30
+
31
+ Permission is hereby granted, free of charge, to any person obtaining a copy
32
+ of this software and associated documentation files (the "Software"), to deal
33
+ in the Software without restriction, including without limitation the rights
34
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
35
+ copies of the Software, and to permit persons to whom the Software is
36
+ furnished to do so, subject to the following conditions:
37
+
38
+ The above copyright notice and this permission notice shall be included in all
39
+ copies or substantial portions of the Software.
40
+
41
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
42
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
43
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
44
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
45
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
46
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
47
+ SOFTWARE.
48
+
49
+ ---
50
+
51
+ @typescript-eslint/utils
52
+
53
+ MIT License
54
+
55
+ Copyright (c) 2019 typescript-eslint and other contributors
56
+
57
+ Permission is hereby granted, free of charge, to any person obtaining a copy
58
+ of this software and associated documentation files (the "Software"), to deal
59
+ in the Software without restriction, including without limitation the rights
60
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
61
+ copies of the Software, and to permit persons to whom the Software is
62
+ furnished to do so, subject to the following conditions:
63
+
64
+ The above copyright notice and this permission notice shall be included in all
65
+ copies or substantial portions of the Software.
66
+
67
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
68
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
69
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
70
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
71
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
72
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
73
+ SOFTWARE.
74
+
75
+ ---
76
+
77
+ globals
78
+
79
+ MIT License
80
+
81
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
82
+
83
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
84
+
85
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
86
+
87
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,70 @@
1
1
  # @r_masseater/tako
2
2
 
3
- This version only reserves the name. Releases come from CI.
3
+ Draws infographics from a few lines of Typst. You write what the figure says, and the parts decide the layout, the spacing, the colors and the shapes.
4
+
5
+ It requires Node.js 26 or later.
6
+
7
+ ```sh
8
+ bun add @r_masseater/tako
9
+ ```
10
+
11
+ ## Write a figure
12
+
13
+ ```typst
14
+ #import "/.tako/tako.typ": *
15
+ #show: figure
16
+
17
+ #flow(
18
+ hero: (big: [about \$13], caption: [per day]),
19
+ nodes: (
20
+ (kind: "outside", icon: "forum", body: [Discord], note: [1M messages]),
21
+ (kind: "system", icon: "smart_toy", body: [Gateway]),
22
+ (kind: "data", icon: "database", body: [Durable Object], note: [14.8 rows each]),
23
+ ),
24
+ )
25
+ ```
26
+
27
+ `kind` is one of `person`, `system`, `data`, `amount`, `condition` and `outside`. `icon` is the name of a Material Symbols icon. The hero number hangs from the last node by default. Pass `to` with a node index to hang it from another node.
28
+
29
+ ```typst
30
+ #bars(
31
+ unit: "$",
32
+ rows: ((label: [now], value: 13), (label: [fewer indexes], value: 9)),
33
+ limit: (value: 0.1, label: [limit \$0.1]),
34
+ )
35
+ ```
36
+
37
+ ## More parts
38
+
39
+ - `cycle(nodes: (...), hero: (...))` puts the nodes on a ring with arrows between them and an optional hero number in the middle.
40
+ - `tree(root: (kind: ..., body: [...], children: (...)))` lays a tree out top down.
41
+ - `timeline(events: ((when: [...], kind: ..., body: [...], note: [...]), ...))` alternates events above and below an axis.
42
+ - `nested(root: (kind: ..., body: [...], children: (...)))` draws boxes inside boxes.
43
+ - `fork(before: (...), decide: (...), yes: (...), no: (...), yes-label: [...], no-label: [...])` splits a flow at a condition into two branches.
44
+
45
+ ## Render
46
+
47
+ ```sh
48
+ tako render figure.typ
49
+ tako render figure.typ --theme dark --format pdf
50
+ ```
51
+
52
+ Without `--theme`, it writes `figure.light.svg` and `figure.dark.svg` next to the source. `--format` is `svg` or `pdf`.
53
+
54
+ From code, `renderFigure` returns the bytes.
55
+
56
+ ```ts
57
+ import { renderFigure } from "@r_masseater/tako";
58
+
59
+ const svg = await renderFigure({ file: "figure.typ", theme: "light", format: "svg" });
60
+ ```
61
+
62
+ An SVG draws its text as outlines. Use `pdf` where the text must stay searchable. A figure with Japanese text needs a Japanese font installed, and Noto Sans CJK JP is the first choice.
63
+
64
+ ## Agent skills
65
+
66
+ The package ships an agent skill in `skills/`. Add `permissions: { "@r_masseater/tako": { skills: true } }` to `pnpm-workspace.yaml` and `vp install` links it into the skill directories of your agents.
67
+
68
+ ## License
69
+
70
+ [MIT](LICENSE)
@@ -0,0 +1,70 @@
1
+ import { n as RenderError, r as failWith, t as renderFigure } from "./render-y19FJtYB.mjs";
2
+ import { layer } from "@effect/platform-node/NodeServices";
3
+ import { Array, Console, Effect, FileSystem, Option, Path, Schema } from "effect";
4
+ import { parseArgs } from "node:util";
5
+ import { runMain } from "@effect/platform-node/NodeRuntime";
6
+ // src/entities/figure/model/request.ts
7
+ const ThemeSchema = Schema.Literals(["light", "dark"]);
8
+ const FormatSchema = Schema.Literals(["svg", "pdf"]);
9
+ // src/app/cli.ts
10
+ const ARGUMENTS_START = 2;
11
+ const FILE_POSITION = 1;
12
+ const SUBCOMMAND = "render";
13
+ const DEFAULT_FORMAT = "svg";
14
+ const SEQUENTIAL = { concurrency: 1 };
15
+ const ALL_THEMES = ["light", "dark"];
16
+ const USAGE = "usage: tako render <file.typ> [--theme light|dark] [--format svg|pdf]";
17
+ const Flags = Schema.Struct({
18
+ theme: Schema.optional(ThemeSchema),
19
+ format: Schema.optional(FormatSchema)
20
+ });
21
+ const usageFailure = (reason) => RenderError.make({ message: `${reason}\n${USAGE}` });
22
+ const parseFlags = (argv) => Effect.try({
23
+ try: () => parseArgs({
24
+ args: [...argv],
25
+ allowPositionals: true,
26
+ options: {
27
+ theme: { type: "string" },
28
+ format: { type: "string" }
29
+ }
30
+ }),
31
+ catch: failWith
32
+ }).pipe(Effect.flatMap(({ positionals, values }) => Schema.decodeUnknownEffect(Flags)(values).pipe(Effect.mapBoth({
33
+ onSuccess: (flags) => ({
34
+ positionals,
35
+ flags
36
+ }),
37
+ onFailure: () => usageFailure("theme is light or dark and format is svg or pdf")
38
+ }))));
39
+ const program = Effect.gen(function* runProgram() {
40
+ const path = yield* Path.Path;
41
+ const fileSystem = yield* FileSystem.FileSystem;
42
+ const { positionals, flags } = yield* parseFlags(process.argv.slice(ARGUMENTS_START));
43
+ const file = yield* Array.get(positionals, FILE_POSITION).pipe(Effect.fromOption, Effect.mapError(() => usageFailure("missing file")));
44
+ yield* Effect.filterOrFail(Effect.succeed(Array.head(positionals)), Option.contains(SUBCOMMAND), () => usageFailure("unknown command"));
45
+ const format = Option.getOrElse(Option.fromNullishOr(flags.format), () => DEFAULT_FORMAT);
46
+ const themes = Option.match(Option.fromNullishOr(flags.theme), {
47
+ onNone: () => ALL_THEMES,
48
+ onSome: (theme) => [theme]
49
+ });
50
+ const stem = path.join(path.dirname(file), path.basename(file, path.extname(file)));
51
+ yield* Effect.forEach(themes, (theme) => Effect.gen(function* writeFigure() {
52
+ const output = yield* Effect.tryPromise({
53
+ try: () => renderFigure({
54
+ file,
55
+ theme,
56
+ format
57
+ }),
58
+ catch: failWith
59
+ });
60
+ const target = `${stem}.${theme}.${format}`;
61
+ yield* fileSystem.writeFile(target, output);
62
+ yield* Console.log(target);
63
+ }), SEQUENTIAL);
64
+ }).pipe(Effect.catchTag("RenderError", (failure) => Console.error(failure.message)));
65
+ const runCli = () => {
66
+ runMain(program.pipe(Effect.provide(layer)));
67
+ };
68
+ export { runCli };
69
+
70
+ //# sourceMappingURL=cli-CSX4cCgd.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli-CSX4cCgd.mjs","names":["Arr","nodeServices"],"sources":["../src/entities/figure/model/request.ts","../src/app/cli.ts"],"sourcesContent":["import { Schema } from \"effect\";\n\nexport const ThemeSchema = Schema.Literals([\"light\", \"dark\"]);\n\nexport const FormatSchema = Schema.Literals([\"svg\", \"pdf\"]);\n\nexport type Theme = typeof ThemeSchema.Type;\n\nexport type Format = typeof FormatSchema.Type;\n\nexport type Rendered = Uint8Array;\n\nexport interface RenderRequest {\n readonly file: string;\n readonly theme: Theme;\n readonly format: Format;\n}\n","import { parseArgs } from \"node:util\";\n\nimport { runMain } from \"@effect/platform-node/NodeRuntime\";\nimport { layer as nodeServices } from \"@effect/platform-node/NodeServices\";\nimport { Array as Arr, Console, Effect, FileSystem, Option, Path, Schema } from \"effect\";\n\nimport { FormatSchema, ThemeSchema } from \"#/entities/figure/index.ts\";\nimport type { Format, Theme } from \"#/entities/figure/index.ts\";\nimport { RenderError, failWith } from \"#/shared/lib/errors.ts\";\n\nimport { renderFigure } from \"./render.ts\";\n\nconst ARGUMENTS_START = 2;\nconst FILE_POSITION = 1;\nconst SUBCOMMAND = \"render\";\nconst DEFAULT_FORMAT: Format = \"svg\";\nconst SEQUENTIAL = { concurrency: 1 } as const;\nconst ALL_THEMES: readonly Theme[] = [\"light\", \"dark\"];\nconst USAGE = \"usage: tako render <file.typ> [--theme light|dark] [--format svg|pdf]\";\n\nconst Flags = Schema.Struct({\n theme: Schema.optional(ThemeSchema),\n format: Schema.optional(FormatSchema),\n});\n\nconst usageFailure = (reason: string): RenderError =>\n RenderError.make({ message: `${reason}\\n${USAGE}` });\n\nconst parseFlags = (\n argv: readonly string[],\n): Effect.Effect<\n { readonly positionals: readonly string[]; readonly flags: typeof Flags.Type },\n RenderError\n> =>\n Effect.try({\n try: () =>\n parseArgs({\n args: [...argv],\n allowPositionals: true,\n options: { theme: { type: \"string\" }, format: { type: \"string\" } },\n }),\n catch: failWith,\n }).pipe(\n Effect.flatMap(({ positionals, values }) =>\n Schema.decodeUnknownEffect(Flags)(values).pipe(\n Effect.mapBoth({\n onSuccess: (flags) => ({ positionals, flags }),\n onFailure: () => usageFailure(\"theme is light or dark and format is svg or pdf\"),\n }),\n ),\n ),\n );\n\nconst program = Effect.gen(function* runProgram() {\n const path = yield* Path.Path;\n const fileSystem = yield* FileSystem.FileSystem;\n const { positionals, flags } = yield* parseFlags(process.argv.slice(ARGUMENTS_START));\n const file = yield* Arr.get(positionals, FILE_POSITION).pipe(\n Effect.fromOption,\n Effect.mapError(() => usageFailure(\"missing file\")),\n );\n yield* Effect.filterOrFail(\n Effect.succeed(Arr.head(positionals)),\n Option.contains(SUBCOMMAND),\n () => usageFailure(\"unknown command\"),\n );\n const format = Option.getOrElse(Option.fromNullishOr(flags.format), () => DEFAULT_FORMAT);\n const themes = Option.match(Option.fromNullishOr(flags.theme), {\n onNone: () => ALL_THEMES,\n onSome: (theme) => [theme],\n });\n const stem = path.join(path.dirname(file), path.basename(file, path.extname(file)));\n yield* Effect.forEach(\n themes,\n (theme) =>\n Effect.gen(function* writeFigure() {\n const output = yield* Effect.tryPromise({\n try: () => renderFigure({ file, theme, format }),\n catch: failWith,\n });\n const target = `${stem}.${theme}.${format}`;\n yield* fileSystem.writeFile(target, output);\n yield* Console.log(target);\n }),\n SEQUENTIAL,\n );\n}).pipe(Effect.catchTag(\"RenderError\", (failure) => Console.error(failure.message)));\n\nexport const runCli = (): void => {\n runMain(program.pipe(Effect.provide(nodeServices)));\n};\n"],"mappings":";;;;;;AAEA,MAAa,cAAc,OAAO,SAAS,CAAC,SAAS,MAAM,CAAC;AAE5D,MAAa,eAAe,OAAO,SAAS,CAAC,OAAO,KAAK,CAAC;;ACQ1D,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,aAAa;AACnB,MAAM,iBAAyB;AAC/B,MAAM,aAAa,EAAE,aAAa,EAAE;AACpC,MAAM,aAA+B,CAAC,SAAS,MAAM;AACrD,MAAM,QAAQ;AAEd,MAAM,QAAQ,OAAO,OAAO;CAC1B,OAAO,OAAO,SAAS,WAAW;CAClC,QAAQ,OAAO,SAAS,YAAY;AACtC,CAAC;AAED,MAAM,gBAAgB,WACpB,YAAY,KAAK,EAAE,SAAS,GAAG,OAAO,IAAI,QAAQ,CAAC;AAErD,MAAM,cACJ,SAKA,OAAO,IAAI;CACT,WACE,UAAU;EACR,MAAM,CAAC,GAAG,IAAI;EACd,kBAAkB;EAClB,SAAS;GAAE,OAAO,EAAE,MAAM,SAAS;GAAG,QAAQ,EAAE,MAAM,SAAS;EAAE;CACnE,CAAC;CACH,OAAO;AACT,CAAC,CAAC,CAAC,KACD,OAAO,SAAS,EAAE,aAAa,aAC7B,OAAO,oBAAoB,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,KACxC,OAAO,QAAQ;CACb,YAAY,WAAW;EAAE;EAAa;CAAM;CAC5C,iBAAiB,aAAa,iDAAiD;AACjF,CAAC,CACH,CACF,CACF;AAEF,MAAM,UAAU,OAAO,IAAI,UAAU,aAAa;CAChD,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,aAAa,OAAO,WAAW;CACrC,MAAM,EAAE,aAAa,UAAU,OAAO,WAAW,QAAQ,KAAK,MAAM,eAAe,CAAC;CACpF,MAAM,OAAO,OAAOA,MAAI,IAAI,aAAa,aAAa,CAAC,CAAC,KACtD,OAAO,YACP,OAAO,eAAe,aAAa,cAAc,CAAC,CACpD;CACA,OAAO,OAAO,aACZ,OAAO,QAAQA,MAAI,KAAK,WAAW,CAAC,GACpC,OAAO,SAAS,UAAU,SACpB,aAAa,iBAAiB,CACtC;CACA,MAAM,SAAS,OAAO,UAAU,OAAO,cAAc,MAAM,MAAM,SAAS,cAAc;CACxF,MAAM,SAAS,OAAO,MAAM,OAAO,cAAc,MAAM,KAAK,GAAG;EAC7D,cAAc;EACd,SAAS,UAAU,CAAC,KAAK;CAC3B,CAAC;CACD,MAAM,OAAO,KAAK,KAAK,KAAK,QAAQ,IAAI,GAAG,KAAK,SAAS,MAAM,KAAK,QAAQ,IAAI,CAAC,CAAC;CAClF,OAAO,OAAO,QACZ,SACC,UACC,OAAO,IAAI,UAAU,cAAc;EACjC,MAAM,SAAS,OAAO,OAAO,WAAW;GACtC,WAAW,aAAa;IAAE;IAAM;IAAO;GAAO,CAAC;GAC/C,OAAO;EACT,CAAC;EACD,MAAM,SAAS,GAAG,KAAK,GAAG,MAAM,GAAG;EACnC,OAAO,WAAW,UAAU,QAAQ,MAAM;EAC1C,OAAO,QAAQ,IAAI,MAAM;CAC3B,CAAC,GACH,UACF;AACF,CAAC,CAAC,CAAC,KAAK,OAAO,SAAS,gBAAgB,YAAY,QAAQ,MAAM,QAAQ,OAAO,CAAC,CAAC;AAEnF,MAAa,eAAqB;CAChC,QAAQ,QAAQ,KAAK,OAAO,QAAQC,KAAY,CAAC,CAAC;AACpD"}
package/dist/cli.d.mts ADDED
@@ -0,0 +1 @@
1
+ export {}
package/dist/cli.mjs ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { enableCompileCache } from "node:module";
3
+ // bin/tako.ts
4
+ enableCompileCache();
5
+ const { runCli } = await import("./cli-CSX4cCgd.mjs");
6
+ runCli();
7
+ export {};
8
+
9
+ //# sourceMappingURL=cli.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.mjs","names":[],"sources":["../bin/tako.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { enableCompileCache } from \"node:module\";\n\nenableCompileCache();\n\nconst { runCli } = await import(\"#/app/cli.ts\");\n\nrunCli();\n"],"mappings":";;;AAGA,mBAAmB;AAEnB,MAAM,EAAE,WAAW,MAAM,OAAO;AAEhC,OAAO"}
@@ -0,0 +1,20 @@
1
+ import { Schema } from "effect";
2
+ declare const ThemeSchema: Schema.Literals<readonly ["light", "dark"]>;
3
+ declare const FormatSchema: Schema.Literals<readonly ["svg", "pdf"]>;
4
+ type Theme = typeof ThemeSchema.Type;
5
+ type Format = typeof FormatSchema.Type;
6
+ type Rendered = Uint8Array;
7
+ interface RenderRequest {
8
+ readonly file: string;
9
+ readonly theme: Theme;
10
+ readonly format: Format;
11
+ }
12
+ export declare const renderFigure: (request: RenderRequest) => Promise<Rendered>;
13
+ declare const RenderError_base: Schema.Class<RenderError, Schema.TaggedStruct<"RenderError", {
14
+ readonly message: Schema.String;
15
+ }>, import("effect/Cause").YieldableError & {
16
+ readonly brand: unique symbol;
17
+ }>;
18
+ export declare class RenderError extends RenderError_base {}
19
+ export type { Format, RenderRequest, Rendered, Theme };
20
+ //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ export { n as RenderError, t as renderFigure } from "./render-y19FJtYB.mjs";
@@ -0,0 +1,105 @@
1
+ import { layer } from "@effect/platform-node/NodeServices";
2
+ import { Array, Effect, FileSystem, Match, Option, Path, Predicate, Result, Schema, String as String$1, pipe } from "effect";
3
+ import { NodeCompiler } from "@myriaddreamin/typst-ts-node-compiler";
4
+ // src/shared/lib/errors.ts
5
+ const taggedError = Schema.TaggedError;
6
+ var RenderError = class extends taggedError()("RenderError", { message: Schema.String }) {};
7
+ const messageOf = (cause) => Match.value(cause).pipe(Match.when(Predicate.isError, (failure) => failure.message), Match.orElse(String));
8
+ const failWith = (cause) => RenderError.make({ message: messageOf(cause) });
9
+ // src/features/render-figure/model/render.ts
10
+ const encoder = new TextEncoder();
11
+ const SEQUENTIAL$1 = { concurrency: 1 };
12
+ const Diagnostics = Schema.Array(Schema.Struct({
13
+ path: Schema.String,
14
+ message: Schema.String
15
+ }));
16
+ const renderers = {
17
+ svg: (compiler, document) => encoder.encode(compiler.svg(document)),
18
+ pdf: (compiler, document) => compiler.pdf(document)
19
+ };
20
+ const describeFailure = (raw) => pipe(Schema.decodeUnknownOption(Diagnostics)(raw), Option.getOrElse(() => []), Array.map((diagnostic) => `${diagnostic.path}: ${diagnostic.message}`), Array.join("\n"));
21
+ const diagnosticsOf = (compiler, compiled) => pipe(Option.fromNullishOr(compiled.takeDiagnostics()), Option.map((error) => compiler.fetchDiagnostics(error)), Option.match({
22
+ onNone: () => "",
23
+ onSome: describeFailure
24
+ }));
25
+ const mapShadows = (compiler, mounted) => Effect.forEach(mounted, (item) => Effect.try({
26
+ try: () => {
27
+ compiler.mapShadow(item.path, Buffer.from(item.content));
28
+ },
29
+ catch: failWith
30
+ }), SEQUENTIAL$1).pipe(Effect.asVoid);
31
+ const compileFigure = (request) => Effect.gen(function* compileDocument() {
32
+ const compiler = yield* Effect.try({
33
+ try: () => NodeCompiler.create({
34
+ workspace: request.root,
35
+ inputs: { theme: request.theme }
36
+ }),
37
+ catch: failWith
38
+ });
39
+ yield* mapShadows(compiler, request.mounted);
40
+ const compiled = yield* Effect.try({
41
+ try: () => compiler.compile({ mainFilePath: request.file }),
42
+ catch: failWith
43
+ });
44
+ const document = yield* Effect.fromOption(Option.fromNullishOr(compiled.result)).pipe(Effect.mapError(() => RenderError.make({ message: diagnosticsOf(compiler, compiled) })));
45
+ return yield* Effect.try({
46
+ try: () => renderers[request.format](compiler, document),
47
+ catch: failWith
48
+ });
49
+ });
50
+ // src/app/render.ts
51
+ const ICON_FOLDER = "outlined";
52
+ const PARTS_MOUNT = ".tako";
53
+ const ICONS_MOUNT = "icons";
54
+ const PARTS_EXTENSION = ".typ";
55
+ const WORD_GROUP = "word";
56
+ const QUOTED_WORD = /"(?<word>[a-z0-9_]+)"/gv;
57
+ const SEQUENTIAL = { concurrency: 1 };
58
+ const folderContaining = (resolved) => Effect.gen(function* resolveFolder() {
59
+ const path = yield* Path.Path;
60
+ const file = yield* path.fromFileUrl(new URL(resolved));
61
+ return path.dirname(file);
62
+ }).pipe(Effect.mapError(failWith));
63
+ const quotedWords = (source) => pipe(Array.fromIterable(String$1.matchAll(QUOTED_WORD)(source)), Array.filterMap((match) => pipe(Option.fromNullishOr(match.groups), Option.flatMap((groups) => Option.fromNullishOr(groups[WORD_GROUP])), Option.match({
64
+ onNone: () => Result.fail(match),
65
+ onSome: Result.succeed
66
+ }))), Array.dedupe);
67
+ const readInto = (from, to) => FileSystem.FileSystem.pipe(Effect.flatMap((fileSystem) => fileSystem.readFile(from)), Effect.mapBoth({
68
+ onSuccess: (content) => ({
69
+ path: to,
70
+ content
71
+ }),
72
+ onFailure: failWith
73
+ }));
74
+ const mountParts = (root) => Effect.gen(function* mountPartFiles() {
75
+ const fileSystem = yield* FileSystem.FileSystem;
76
+ const path = yield* Path.Path;
77
+ const partsFolder = yield* folderContaining(import.meta.resolve("@r_masseater/tako/typ/theme.typ"));
78
+ const names = yield* fileSystem.readDirectory(partsFolder).pipe(Effect.mapError(failWith));
79
+ return yield* Effect.forEach(pipe(names, Array.filter((name) => String$1.endsWith(PARTS_EXTENSION)(name))), (name) => readInto(path.join(partsFolder, name), path.join(root, PARTS_MOUNT, name)), SEQUENTIAL);
80
+ });
81
+ const mountIcons = (source, root) => Effect.gen(function* mountIconFiles() {
82
+ const path = yield* Path.Path;
83
+ const packageFolder = yield* folderContaining(import.meta.resolve("@material-symbols/svg-400/package.json"));
84
+ const found = yield* Effect.forEach(quotedWords(source), (word) => readInto(path.join(packageFolder, ICON_FOLDER, `${word}.svg`), path.join(root, PARTS_MOUNT, ICONS_MOUNT, `${word}.svg`)).pipe(Effect.option), SEQUENTIAL);
85
+ return Array.getSomes(found);
86
+ });
87
+ const renderWithServices = (request) => Effect.gen(function* renderInApp() {
88
+ const fileSystem = yield* FileSystem.FileSystem;
89
+ const path = yield* Path.Path;
90
+ const file = path.resolve(request.file);
91
+ const root = path.dirname(file);
92
+ const source = yield* fileSystem.readFileString(file).pipe(Effect.mapError(failWith));
93
+ const parts = yield* mountParts(root);
94
+ const icons = yield* mountIcons(source, root);
95
+ return yield* compileFigure({
96
+ ...request,
97
+ file,
98
+ root,
99
+ mounted: Array.appendAll(parts, icons)
100
+ });
101
+ });
102
+ const renderFigure = (request) => Effect.runPromise(renderWithServices(request).pipe(Effect.provide(layer)));
103
+ export { RenderError as n, failWith as r, renderFigure as t };
104
+
105
+ //# sourceMappingURL=render-y19FJtYB.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-y19FJtYB.mjs","names":["SEQUENTIAL","Arr","Arr","Str","nodeServices"],"sources":["../src/shared/lib/errors.ts","../src/features/render-figure/model/render.ts","../src/app/render.ts"],"sourcesContent":["import { Match, Predicate, Schema } from \"effect\";\n\nconst taggedError = Schema.TaggedError;\n\nexport class RenderError extends taggedError<RenderError, { readonly brand: unique symbol }>()(\n \"RenderError\",\n { message: Schema.String },\n) {}\n\nconst messageOf = (cause: unknown): string =>\n Match.value(cause).pipe(\n Match.when(Predicate.isError, (failure): string => failure.message),\n Match.orElse(String),\n );\n\nexport const failWith = (cause: unknown): RenderError =>\n RenderError.make({ message: messageOf(cause) });\n","import { NodeCompiler } from \"@myriaddreamin/typst-ts-node-compiler\";\nimport type {\n NodeTypstCompileResult,\n NodeTypstDocument,\n} from \"@myriaddreamin/typst-ts-node-compiler\";\nimport { Array as Arr, Effect, Option, Schema, pipe } from \"effect\";\n\nimport type { Format, Rendered, Theme } from \"#/entities/figure/index.ts\";\nimport { RenderError, failWith } from \"#/shared/lib/errors.ts\";\n\nconst encoder = new TextEncoder();\nconst SEQUENTIAL = { concurrency: 1 } as const;\n\nexport interface Mounted {\n readonly path: string;\n readonly content: Uint8Array;\n}\n\nexport interface CompileRequest {\n readonly file: string;\n readonly root: string;\n readonly theme: Theme;\n readonly format: Format;\n readonly mounted: readonly Mounted[];\n}\n\nconst Diagnostics = Schema.Array(Schema.Struct({ path: Schema.String, message: Schema.String }));\n\nconst renderers: Readonly<\n Record<Format, (compiler: NodeCompiler, document: NodeTypstDocument) => Rendered>\n> = {\n svg: (compiler, document) => encoder.encode(compiler.svg(document)),\n pdf: (compiler, document) => compiler.pdf(document),\n};\n\nconst describeFailure = (raw: readonly unknown[]): string =>\n pipe(\n Schema.decodeUnknownOption(Diagnostics)(raw),\n Option.getOrElse(() => []),\n Arr.map((diagnostic) => `${diagnostic.path}: ${diagnostic.message}`),\n Arr.join(\"\\n\"),\n );\n\nconst diagnosticsOf = (compiler: NodeCompiler, compiled: NodeTypstCompileResult): string =>\n pipe(\n Option.fromNullishOr(compiled.takeDiagnostics()),\n Option.map((error): readonly unknown[] => compiler.fetchDiagnostics(error)),\n Option.match({ onNone: () => \"\", onSome: describeFailure }),\n );\n\nconst mapShadows = (\n compiler: NodeCompiler,\n mounted: readonly Mounted[],\n): Effect.Effect<void, RenderError> =>\n Effect.forEach(\n mounted,\n (item) =>\n Effect.try({\n try: () => {\n compiler.mapShadow(item.path, Buffer.from(item.content));\n },\n catch: failWith,\n }),\n SEQUENTIAL,\n ).pipe(Effect.asVoid);\n\nexport const compileFigure = (request: CompileRequest): Effect.Effect<Rendered, RenderError> =>\n Effect.gen(function* compileDocument() {\n const compiler = yield* Effect.try({\n try: () => NodeCompiler.create({ workspace: request.root, inputs: { theme: request.theme } }),\n catch: failWith,\n });\n yield* mapShadows(compiler, request.mounted);\n const compiled = yield* Effect.try({\n try: () => compiler.compile({ mainFilePath: request.file }),\n catch: failWith,\n });\n const document = yield* Effect.fromOption(Option.fromNullishOr(compiled.result)).pipe(\n Effect.mapError(() => RenderError.make({ message: diagnosticsOf(compiler, compiled) })),\n );\n return yield* Effect.try({\n try: () => renderers[request.format](compiler, document),\n catch: failWith,\n });\n });\n","import { layer as nodeServices } from \"@effect/platform-node/NodeServices\";\nimport {\n Array as Arr,\n Effect,\n FileSystem,\n Option,\n Path,\n Result,\n String as Str,\n pipe,\n} from \"effect\";\n\nimport type { Rendered, RenderRequest } from \"#/entities/figure/index.ts\";\nimport { compileFigure } from \"#/features/render-figure/index.ts\";\nimport type { Mounted } from \"#/features/render-figure/index.ts\";\nimport type { RenderError } from \"#/shared/lib/errors.ts\";\nimport { failWith } from \"#/shared/lib/errors.ts\";\n\nconst ICON_FOLDER = \"outlined\";\nconst PARTS_MOUNT = \".tako\";\nconst ICONS_MOUNT = \"icons\";\nconst PARTS_EXTENSION = \".typ\";\nconst WORD_GROUP = \"word\";\nconst QUOTED_WORD = /\"(?<word>[a-z0-9_]+)\"/gv;\nconst SEQUENTIAL = { concurrency: 1 } as const;\n\ntype Services = FileSystem.FileSystem | Path.Path;\n\nconst folderContaining = (resolved: string): Effect.Effect<string, RenderError, Path.Path> =>\n Effect.gen(function* resolveFolder() {\n const path = yield* Path.Path;\n const file = yield* path.fromFileUrl(new URL(resolved));\n return path.dirname(file);\n }).pipe(Effect.mapError(failWith));\n\nconst quotedWords = (source: string): readonly string[] =>\n pipe(\n Arr.fromIterable(Str.matchAll(QUOTED_WORD)(source)),\n Arr.filterMap((match) =>\n pipe(\n Option.fromNullishOr(match.groups),\n Option.flatMap((groups) => Option.fromNullishOr(groups[WORD_GROUP])),\n Option.match({ onNone: () => Result.fail(match), onSome: Result.succeed }),\n ),\n ),\n Arr.dedupe,\n );\n\nconst readInto = (\n from: string,\n to: string,\n): Effect.Effect<Mounted, RenderError, FileSystem.FileSystem> =>\n FileSystem.FileSystem.pipe(\n Effect.flatMap((fileSystem) => fileSystem.readFile(from)),\n Effect.mapBoth({ onSuccess: (content) => ({ path: to, content }), onFailure: failWith }),\n );\n\nconst mountParts = (root: string): Effect.Effect<readonly Mounted[], RenderError, Services> =>\n Effect.gen(function* mountPartFiles() {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const partsFolder = yield* folderContaining(\n import.meta.resolve(\"@r_masseater/tako/typ/theme.typ\"),\n );\n const names = yield* fileSystem.readDirectory(partsFolder).pipe(Effect.mapError(failWith));\n return yield* Effect.forEach(\n pipe(\n names,\n Arr.filter((name): boolean => Str.endsWith(PARTS_EXTENSION)(name)),\n ),\n (name) => readInto(path.join(partsFolder, name), path.join(root, PARTS_MOUNT, name)),\n SEQUENTIAL,\n );\n });\n\nconst mountIcons = (\n source: string,\n root: string,\n): Effect.Effect<readonly Mounted[], RenderError, Services> =>\n Effect.gen(function* mountIconFiles() {\n const path = yield* Path.Path;\n const packageFolder = yield* folderContaining(\n import.meta.resolve(\"@material-symbols/svg-400/package.json\"),\n );\n const found = yield* Effect.forEach(\n quotedWords(source),\n (word) =>\n readInto(\n path.join(packageFolder, ICON_FOLDER, `${word}.svg`),\n path.join(root, PARTS_MOUNT, ICONS_MOUNT, `${word}.svg`),\n ).pipe(Effect.option),\n SEQUENTIAL,\n );\n return Arr.getSomes(found);\n });\n\nconst renderWithServices = (\n request: RenderRequest,\n): Effect.Effect<Rendered, RenderError, Services> =>\n Effect.gen(function* renderInApp() {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const file = path.resolve(request.file);\n const root = path.dirname(file);\n const source = yield* fileSystem.readFileString(file).pipe(Effect.mapError(failWith));\n const parts = yield* mountParts(root);\n const icons = yield* mountIcons(source, root);\n return yield* compileFigure({ ...request, file, root, mounted: Arr.appendAll(parts, icons) });\n });\n\nexport const renderFigure = (request: RenderRequest): Promise<Rendered> =>\n Effect.runPromise(renderWithServices(request).pipe(Effect.provide(nodeServices)));\n"],"mappings":"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"}
package/package.json CHANGED
@@ -1,15 +1,65 @@
1
1
  {
2
2
  "name": "@r_masseater/tako",
3
- "version": "0.0.0",
4
- "description": "Reserves the name until the first release from CI.",
3
+ "version": "0.1.0",
4
+ "description": "Draws infographics from a few lines of Typst: parts for the six kinds of element, flows, a hero number and bars, laid out automatically in light and dark.",
5
+ "keywords": [
6
+ "diagram",
7
+ "infographic",
8
+ "tanstack-intent",
9
+ "typst"
10
+ ],
11
+ "homepage": "https://github.com/masseater/ecosystems/tree/main/libs/tako#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/masseater/ecosystems/issues"
14
+ },
5
15
  "license": "MIT",
6
16
  "repository": {
7
17
  "type": "git",
8
18
  "url": "git+https://github.com/masseater/ecosystems.git",
9
19
  "directory": "libs/tako"
10
20
  },
11
- "homepage": "https://github.com/masseater/ecosystems/tree/main/libs/tako#readme",
12
- "bugs": {
13
- "url": "https://github.com/masseater/ecosystems/issues"
14
- }
21
+ "bin": {
22
+ "tako": "./dist/cli.mjs"
23
+ },
24
+ "files": [
25
+ "LICENSE",
26
+ "dist",
27
+ "skills/draw-infographic",
28
+ "typ"
29
+ ],
30
+ "type": "module",
31
+ "sideEffects": false,
32
+ "imports": {
33
+ "#/*": "./src/*"
34
+ },
35
+ "exports": {
36
+ ".": {
37
+ "types": "./dist/index.d.mts",
38
+ "default": "./dist/index.mjs"
39
+ },
40
+ "./package.json": "./package.json",
41
+ "./typ/*": "./typ/*"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public",
45
+ "provenance": true
46
+ },
47
+ "dependencies": {
48
+ "@effect/platform-node": "^4.1.5",
49
+ "@material-symbols/svg-400": "^0.49.0",
50
+ "@myriaddreamin/typst-ts-node-compiler": "^0.7.0"
51
+ },
52
+ "devDependencies": {
53
+ "@effect/vitest": "4.1.5",
54
+ "@types/node": "26.6.10",
55
+ "effect": "4.1.5",
56
+ "vite-plus": "1.8.0"
57
+ },
58
+ "peerDependencies": {
59
+ "effect": "^4.1.0"
60
+ },
61
+ "engines": {
62
+ "node": ">=26.13.1"
63
+ },
64
+ "scripts": {}
15
65
  }
@@ -0,0 +1,56 @@
1
+ ---
2
+ name: draw-infographic
3
+ description: >
4
+ Use when an infographic, a flow with a hero number, or a bar chart with a limit line is wanted
5
+ as a figure: write a few lines of Typst with the tako parts and tako render lays it out and
6
+ writes light and dark SVG or PDF.
7
+ metadata:
8
+ type: core
9
+ library: "@r_masseater/tako"
10
+ library_version: 0.1.0
11
+ sources:
12
+ - typ/**
13
+ - README.md
14
+ ---
15
+
16
+ # draw-infographic
17
+
18
+ A figure drawn by hand needs coordinates and spacing chosen again for every figure. The tako parts choose the layout from the content, so the figure says what it means and nothing else.
19
+
20
+ ## Setup
21
+
22
+ ```sh
23
+ bun add @r_masseater/tako
24
+ ```
25
+
26
+ A Japanese figure needs a Japanese font such as Noto Sans CJK JP installed.
27
+
28
+ ## Write a figure
29
+
30
+ ```typst
31
+ #import "/.tako/tako.typ": *
32
+ #show: figure
33
+
34
+ #flow(
35
+ hero: (big: [about \$13], caption: [per day]),
36
+ nodes: (
37
+ (kind: "outside", icon: "forum", body: [Discord]),
38
+ (kind: "system", icon: "smart_toy", body: [Gateway]),
39
+ (kind: "data", icon: "database", body: [Durable Object], note: [14.8 rows each]),
40
+ ),
41
+ )
42
+ ```
43
+
44
+ Give each node the kind that matches what happens to it: `person` acts, `system` processes, `data` stays, `amount` is measured, `condition` splits, `outside` is not yours. The kind sets the color and the shape. `icon` is a Material Symbols name.
45
+
46
+ `bars(rows: (...), limit: (...))` draws bars in the amount color and a dashed limit line in the condition color.
47
+
48
+ Pick the part by what the figure shows: `flow` for steps, `fork` for a split at a condition, `cycle` for a repeat, `tree` for parent and child, `nested` for inside and outside, `timeline` for dates, `bars` for a size against a limit. The README lists their arguments.
49
+
50
+ ## Render
51
+
52
+ ```sh
53
+ bunx tako render figure.typ
54
+ ```
55
+
56
+ It writes `figure.light.svg` and `figure.dark.svg`. Pass `--format pdf` where the text must stay searchable, because an SVG draws its text as outlines.
package/typ/cycle.typ ADDED
@@ -0,0 +1,33 @@
1
+ #import "theme.typ": tokens, kinds
2
+ #import "node.typ": *
3
+
4
+ #let cycle(nodes: (), hero: none, label: none) = context {
5
+ let u = uniform(nodes)
6
+ let count = nodes.len()
7
+ let h = u.height
8
+ let total = u.widths.sum()
9
+ let wmax = calc.max(..u.widths)
10
+ let big = if hero == none { none } else { hero-box(hero) }
11
+ let rx = calc.max(total / 3, if big == none { 0pt } else { big.width / 2 + wmax / 2 + 36pt }, 150pt)
12
+ let ry = calc.max(rx * 0.62, if big == none { 0pt } else { big.height / 2 + h / 2 + 30pt })
13
+ let cx = rx + wmax / 2
14
+ let cy = ry + h / 2
15
+ let centers = range(count).map(i => {
16
+ let angle = -90deg + 360deg * i / count
17
+ (cx + rx * calc.cos(angle), cy + ry * calc.sin(angle))
18
+ })
19
+ box(width: 2 * rx + wmax, height: 2 * ry + h, {
20
+ for i in range(count) {
21
+ let j = calc.rem(i + 1, count)
22
+ let from = edge-point(centers.at(i), u.widths.at(i) + 8pt, h + 8pt, centers.at(j))
23
+ let to = edge-point(centers.at(j), u.widths.at(j) + 14pt, h + 14pt, centers.at(i))
24
+ link(from, to, bend: 16pt)
25
+ }
26
+ for (i, node) in nodes.enumerate() {
27
+ at-center(centers.at(i), u.widths.at(i), h, build(node, h, u.widths.at(i)))
28
+ }
29
+ if big != none {
30
+ at-center((cx, cy), big.width, big.height, big.content)
31
+ }
32
+ })
33
+ }
package/typ/fork.typ ADDED
@@ -0,0 +1,48 @@
1
+ #import "theme.typ": tokens, kinds
2
+ #import "node.typ": *
3
+
4
+ #let fork(before: (), decide: (), yes: (), no: (), yes-label: [], no-label: [], gap: 56pt) = context {
5
+ let everyone = before + (decide,) + yes + no
6
+ let u = uniform(everyone)
7
+ let h = u.height
8
+ let rows-gap = h + 52pt
9
+ let widths = u.widths
10
+ let x-of(index-list) = {
11
+ let xs = ()
12
+ let x = 0pt
13
+ for i in index-list {
14
+ xs.push(x)
15
+ x += widths.at(i) + gap
16
+ }
17
+ xs
18
+ }
19
+ let before-idx = range(before.len())
20
+ let decide-idx = before.len()
21
+ let yes-idx = range(decide-idx + 1, decide-idx + 1 + yes.len())
22
+ let no-idx = range(decide-idx + 1 + yes.len(), everyone.len())
23
+ let main-xs = x-of(before-idx + (decide-idx,))
24
+ let after-x = main-xs.last() + widths.at(decide-idx) + gap
25
+ let yes-xs = x-of(yes-idx).map(x => x + after-x)
26
+ let no-xs = x-of(no-idx).map(x => x + after-x)
27
+ let row-end(xs, idx) = if xs.len() == 0 { 0pt } else { xs.last() + widths.at(idx.last()) }
28
+ let total = calc.max(row-end(main-xs, before-idx + (decide-idx,)), row-end(yes-xs, yes-idx), row-end(no-xs, no-idx))
29
+ let place-row(indexes, xs, y) = {
30
+ for (k, i) in indexes.enumerate() {
31
+ place(top + left, dx: xs.at(k), dy: y, build(everyone.at(i), h, widths.at(i)))
32
+ }
33
+ for k in range(indexes.len() - 1) {
34
+ link((xs.at(k) + widths.at(indexes.at(k)), y + h / 2), (xs.at(k + 1), y + h / 2), bend: 14pt)
35
+ }
36
+ }
37
+ box(width: total, height: 3 * h + 2 * (rows-gap - h), {
38
+ place-row(before-idx + (decide-idx,), main-xs, rows-gap)
39
+ place-row(yes-idx, yes-xs, 0pt)
40
+ place-row(no-idx, no-xs, 2 * rows-gap)
41
+ let from = (main-xs.last() + widths.at(decide-idx) * 0.8, rows-gap + h * 0.1)
42
+ let start = (main-xs.last() + widths.at(decide-idx) * 0.85, rows-gap + 2pt)
43
+ let bottom = (main-xs.last() + widths.at(decide-idx) * 0.85, rows-gap + h - 2pt)
44
+ let magenta = kinds.condition.stroke
45
+ link(start, (yes-xs.first(), h / 2), color: magenta, dashed: true, bend: 24pt, label: yes-label)
46
+ link(bottom, (no-xs.first(), 2 * rows-gap + h / 2), color: magenta, dashed: true, bend: -24pt, label: no-label)
47
+ })
48
+ }
package/typ/nested.typ ADDED
@@ -0,0 +1,23 @@
1
+ #import "theme.typ": tokens, kinds
2
+ #import "shapes.typ": outer-width
3
+ #import "node.typ": *
4
+
5
+ #let nested-part(spec, depth) = {
6
+ let kids = spec.at("children", default: ())
7
+ if kids.len() == 0 {
8
+ let sized = natural(spec)
9
+ build(spec, sized.height, outer-width(spec.kind, sized.inner, sized.height))
10
+ } else {
11
+ let tone = kinds.at(spec.kind)
12
+ let fill = if depth == 0 { tone.fill } else { tokens.bg }
13
+ let title = content-of(spec.kind, spec.at("icon", default: none), spec.body)
14
+ box(inset: 16pt, radius: 22pt, fill: fill, stroke: if spec.kind == "outside" { (paint: tone.stroke, thickness: 2pt, dash: (6pt, 5pt)) } else { 2pt + tone.stroke }, stack(
15
+ dir: ttb,
16
+ spacing: 14pt,
17
+ align(left, title),
18
+ grid(columns: kids.len(), column-gutter: 14pt, row-gutter: 14pt, align: horizon, ..kids.map(kid => nested-part(kid, depth + 1))),
19
+ ))
20
+ }
21
+ }
22
+
23
+ #let nested(root: ()) = context { nested-part(root, 0) }
package/typ/node.typ ADDED
@@ -0,0 +1,80 @@
1
+ #import "theme.typ": tokens, kinds
2
+ #import "shapes.typ": shape, outer-width
3
+
4
+ #let icon-of(name, color, size) = image(
5
+ bytes(read("/.tako/icons/" + name + ".svg").replace("<path ", "<path fill=\"" + color.to-hex() + "\" ")),
6
+ format: "svg",
7
+ width: size,
8
+ )
9
+
10
+ #let content-of(kind, icon, body) = grid(
11
+ columns: if icon == none { 1 } else { 2 },
12
+ column-gutter: 8pt,
13
+ align: horizon,
14
+ ..if icon == none { () } else { (icon-of(icon, kinds.at(kind).stroke, 22pt),) },
15
+ text(size: 18pt, weight: "bold", fill: tokens.ink, body),
16
+ )
17
+
18
+ #let natural(node) = {
19
+ let c = content-of(node.kind, node.at("icon", default: none), node.body)
20
+ let m = measure(c)
21
+ (inner: m.width, height: calc.max(m.height + 24pt, 52pt), content: c)
22
+ }
23
+
24
+ #let build(node, h, w) = box(width: w, height: h, {
25
+ shape(node.kind, w, h)
26
+ place(center + horizon, content-of(node.kind, node.at("icon", default: none), node.body))
27
+ })
28
+
29
+ #let uniform(nodes) = {
30
+ let sized = nodes.map(natural)
31
+ let h = calc.max(..sized.map(s => s.height))
32
+ let widths = nodes.zip(sized).map(p => outer-width(p.at(0).kind, p.at(1).inner, h))
33
+ (height: h, widths: widths)
34
+ }
35
+
36
+ #let arrow-head(tip, from, color) = {
37
+ let angle = calc.atan2((tip.at(0) - from.at(0)) / 1pt, (tip.at(1) - from.at(1)) / 1pt)
38
+ let size = 9pt
39
+ let back(a) = (tip.at(0) - size * calc.cos(angle + a), tip.at(1) - size * calc.sin(angle + a))
40
+ curve(fill: color, stroke: none, curve.move(tip), curve.line(back(25deg)), curve.line(back(-25deg)), curve.close())
41
+ }
42
+
43
+ #let link(a, b, color: tokens.sub, dashed: false, bend: 22pt, thickness: 2.5pt, label: none) = {
44
+ let dx = (b.at(0) - a.at(0)) / 1pt
45
+ let dy = (b.at(1) - a.at(1)) / 1pt
46
+ let length = calc.max(calc.sqrt(dx * dx + dy * dy), 1)
47
+ let mid = ((a.at(0) + b.at(0)) / 2 + bend * dy / length, (a.at(1) + b.at(1)) / 2 - bend * dx / length)
48
+ let line = if dashed { (paint: color, thickness: thickness, dash: (7pt, 6pt)) } else { thickness + color }
49
+ place(top + left, curve(stroke: line, curve.move(a), curve.quad(mid, b)))
50
+ place(top + left, arrow-head(b, mid, color))
51
+ if label != none {
52
+ let at = ((a.at(0) + b.at(0)) / 4 + mid.at(0) / 2, (a.at(1) + b.at(1)) / 4 + mid.at(1) / 2)
53
+ place(top + left, dx: at.at(0), dy: at.at(1), place(center + horizon, box(fill: tokens.bg, inset: (x: 4pt, y: 2pt), text(size: 14pt, fill: tokens.ink, label))))
54
+ }
55
+ }
56
+
57
+ #let edge-point(center, w, h, toward) = {
58
+ let dx = (toward.at(0) - center.at(0)) / 1pt
59
+ let dy = (toward.at(1) - center.at(1)) / 1pt
60
+ let tx = if calc.abs(dx) < 0.001 { 1e9 } else { (w / 2 / 1pt) / calc.abs(dx) }
61
+ let ty = if calc.abs(dy) < 0.001 { 1e9 } else { (h / 2 / 1pt) / calc.abs(dy) }
62
+ let t = calc.min(tx, ty)
63
+ (center.at(0) + dx * t * 1pt, center.at(1) + dy * t * 1pt)
64
+ }
65
+
66
+ #let at-center(center, w, h, body) = place(top + left, dx: center.at(0) - w / 2, dy: center.at(1) - h / 2, body)
67
+
68
+ #let hero-box(hero) = {
69
+ let big = text(size: 58pt, weight: "bold", fill: tokens.ink, hero.big)
70
+ let cap = text(size: 16pt, fill: tokens.sub, hero.caption)
71
+ let inner = stack(spacing: 12pt, align(center, big), align(center, cap))
72
+ let m = measure(inner)
73
+ let h = m.height / 0.55
74
+ let w = outer-width("amount", m.width + 24pt, 0pt)
75
+ (width: w, height: h, content: box(width: w, height: h, {
76
+ shape("amount", w, h)
77
+ place(center + horizon, inner)
78
+ }))
79
+ }
80
+
package/typ/shapes.typ ADDED
@@ -0,0 +1,73 @@
1
+ #import "theme.typ": kinds, stroke-width
2
+
3
+ #let scaled(w, h, point) = (point.at(0) / 200 * w, point.at(1) / 80 * h)
4
+
5
+ #let cubic(w, h, a, b, c) = curve.cubic(scaled(w, h, a), scaled(w, h, b), scaled(w, h, c))
6
+
7
+ #let page-parts(w, h) = (
8
+ curve.move(scaled(w, h, (0, 14))),
9
+ cubic(w, h, (0, 6), (6, 0), (14, 0)),
10
+ curve.line(scaled(w, h, (186, 0))),
11
+ cubic(w, h, (194, 0), (200, 6), (200, 14)),
12
+ curve.line(scaled(w, h, (200, 69))),
13
+ cubic(w, h, (164, 87), (136, 60), (100, 69)),
14
+ cubic(w, h, (64, 87), (36, 60), (0, 69)),
15
+ curve.close(mode: "straight"),
16
+ )
17
+
18
+ #let lens-parts(w, h) = (
19
+ curve.move(scaled(w, h, (0, 40))),
20
+ cubic(w, h, (44, -6.4), (156, -6.4), (200, 40)),
21
+ cubic(w, h, (156, 86.4), (44, 86.4), (0, 40)),
22
+ curve.close(mode: "straight"),
23
+ )
24
+
25
+ #let cloud-segments = (
26
+ ((118.6, 0), (139.5, 4.7), (155.8, 9.3)),
27
+ ((172.2, 13.8), (192, 20.2), (198, 27.3)),
28
+ ((203.9, 34.4), (197.4, 44.1), (191.3, 51.9)),
29
+ ((185.2, 59.6), (176.3, 69.3), (161.1, 73.7)),
30
+ ((145.9, 78), (120.2, 78.1), (100, 78)),
31
+ ((79.8, 77.9), (55.3, 77.4), (40, 73)),
32
+ ((24.8, 68.7), (15, 59.5), (8.7, 51.9)),
33
+ ((2.4, 44.2), (-3.9, 34.4), (2, 27.3)),
34
+ ((8, 20.2), (27.8, 13.8), (44.2, 9.3)),
35
+ ((60.5, 4.7), (81.4, 0), (100, 0)),
36
+ )
37
+
38
+ #let cloud-parts(w, h) = (
39
+ curve.move(scaled(w, h, (100, 0))),
40
+ ..cloud-segments.map(s => cubic(w, h, ..s)),
41
+ curve.close(mode: "straight"),
42
+ )
43
+
44
+ #let inner-width(kind, outer, h) = {
45
+ if kind == "person" { outer - h * 0.55 }
46
+ else if kind == "amount" { outer * 0.74 }
47
+ else if kind == "condition" { outer * 0.6 }
48
+ else if kind == "outside" { outer * 0.82 }
49
+ else { outer - 28pt }
50
+ }
51
+
52
+ #let outer-width(kind, inner, h) = {
53
+ if kind == "person" { inner + h * 0.55 }
54
+ else if kind == "amount" { inner / 0.74 }
55
+ else if kind == "condition" { inner / 0.6 }
56
+ else if kind == "outside" { inner / 0.82 }
57
+ else { inner + 28pt }
58
+ }
59
+
60
+ #let shape(kind, w, h) = {
61
+ let spec = kinds.at(kind)
62
+ let line = stroke-width + spec.stroke
63
+ let fill = spec.fill
64
+ if kind == "person" { rect(width: w, height: h, radius: h / 2, fill: fill, stroke: line) }
65
+ else if kind == "system" { rect(width: w, height: h, radius: 18pt, fill: fill, stroke: line) }
66
+ else if kind == "amount" { ellipse(width: w, height: h, fill: fill, stroke: line) }
67
+ else if kind == "data" { box(width: w, height: h, curve(fill: fill, stroke: line, ..page-parts(w, h))) }
68
+ else if kind == "condition" { box(width: w, height: h, curve(fill: fill, stroke: line, ..lens-parts(w, h))) }
69
+ else {
70
+ let dashed = (paint: spec.stroke, thickness: stroke-width, dash: (6pt, 5pt))
71
+ box(width: w, height: h, curve(fill: fill, stroke: dashed, ..cloud-parts(w, h)))
72
+ }
73
+ }
package/typ/tako.typ ADDED
@@ -0,0 +1,71 @@
1
+ #import "theme.typ": tokens, kinds
2
+ #import "shapes.typ": shape, outer-width
3
+ #import "node.typ": *
4
+
5
+ #let flow(nodes: (), gap: 64pt, hero: none) = context {
6
+ let sized = nodes.map(natural)
7
+ let h = calc.max(..sized.map(s => s.height))
8
+ let widths = nodes.zip(sized).map(p => outer-width(p.at(0).kind, p.at(1).inner, h))
9
+ let xs = ()
10
+ let x = 0pt
11
+ for w in widths {
12
+ xs.push(x)
13
+ x += w + gap
14
+ }
15
+ let total = x - gap
16
+ let big = if hero == none { none } else { hero-box(hero) }
17
+ let target = if hero == none { 0 } else { hero.at("to", default: nodes.len() - 1) }
18
+ let cx = xs.at(target) + widths.at(target) / 2
19
+ let lead = if big == none { 0pt } else { calc.max(0pt, big.width / 2 - cx) }
20
+ let span = if big == none { total } else { calc.max(total, cx + big.width / 2) } + lead
21
+ let rise = if big == none { 0pt } else { big.height + 56pt }
22
+ box(width: span, height: rise + h + 40pt, {
23
+ for (i, n) in nodes.enumerate() {
24
+ place(top + left, dx: lead + xs.at(i), dy: rise, build(n, h, widths.at(i)))
25
+ if n.at("note", default: none) != none {
26
+ place(top + left, dx: lead + xs.at(i), dy: rise + h + 8pt, box(width: widths.at(i), align(center, text(size: 15pt, fill: tokens.sub, n.note))))
27
+ }
28
+ }
29
+ for i in range(nodes.len() - 1) {
30
+ link((lead + xs.at(i) + widths.at(i), rise + h / 2), (lead + xs.at(i + 1), rise + h / 2))
31
+ }
32
+ if big != none {
33
+ place(top + left, dx: lead + cx - big.width / 2, dy: 0pt, big.content)
34
+ link((lead + cx, big.height), (lead + cx, rise), color: kinds.condition.stroke, dashed: true, bend: -26pt)
35
+ }
36
+ })
37
+ }
38
+
39
+ #let figure(body) = {
40
+ set page(width: auto, height: auto, margin: 24pt, fill: tokens.bg)
41
+ set text(font: ("Noto Sans CJK JP", "Noto Sans JP", "Hiragino Sans"), fill: tokens.ink)
42
+ body
43
+ }
44
+
45
+ #let bars(rows: (), limit: none, unit: "", max: auto, width: 520pt) = context {
46
+ let scale = if max == auto { calc.max(..rows.map(r => r.value), if limit == none { 0 } else { limit.value }) } else { max }
47
+ let labels = rows.map(r => measure(text(size: 17pt, r.label)).width)
48
+ let label-width = calc.max(..labels) + 16pt
49
+ let row-height = 52pt
50
+ let spec = kinds.amount
51
+ box(width: label-width + width + 110pt, height: row-height * rows.len() + 40pt, {
52
+ for (i, r) in rows.enumerate() {
53
+ let y = 32pt + row-height * i
54
+ place(top + left, dy: y - 12pt, box(width: label-width - 12pt, align(right, text(size: 17pt, fill: tokens.ink, r.label))))
55
+ let w = calc.max(r.value / scale * width, 10pt)
56
+ place(top + left, dx: label-width, dy: y - 16pt, rect(width: w, height: 32pt, radius: (right: 16pt, left: 4pt), fill: spec.fill, stroke: 2pt + spec.stroke))
57
+ place(top + left, dx: label-width + w + 10pt, dy: y - 13pt, text(size: 20pt, weight: "bold", fill: tokens.ink, unit + str(r.value)))
58
+ }
59
+ if limit != none {
60
+ let x = label-width + limit.value / scale * width
61
+ place(top + left, curve(stroke: (paint: kinds.condition.stroke, thickness: 2.5pt, dash: (7pt, 6pt)), curve.move((x, 16pt)), curve.line((x, 40pt + row-height * rows.len() - 20pt))))
62
+ place(top + left, dx: x + 8pt, dy: 0pt, text(size: 16pt, fill: tokens.ink, limit.label))
63
+ }
64
+ })
65
+ }
66
+
67
+ #import "cycle.typ": cycle
68
+ #import "tree.typ": tree
69
+ #import "timeline.typ": timeline
70
+ #import "nested.typ": nested
71
+ #import "fork.typ": fork
package/typ/theme.typ ADDED
@@ -0,0 +1,39 @@
1
+ #let dark = sys.inputs.at("theme", default: "light") == "dark"
2
+
3
+ #let pick(light, dark-value) = if dark { dark-value } else { light }
4
+
5
+ #let tokens = (
6
+ bg: pick(rgb("#ffffff"), rgb("#14181c")),
7
+ ink: pick(rgb("#1f2933"), rgb("#e8ecef")),
8
+ sub: pick(rgb("#5b6672"), rgb("#a3adb8")),
9
+ line: pick(rgb("#c7d0d9"), rgb("#3a444e")),
10
+ )
11
+
12
+ #let kinds = (
13
+ person: (
14
+ stroke: pick(rgb("#2151af"), rgb("#3769ca")),
15
+ fill: pick(rgb("#d9e1f1"), rgb("#1d2e4b")),
16
+ ),
17
+ system: (
18
+ stroke: pick(rgb("#966cd7"), rgb("#ae84f2")),
19
+ fill: pick(rgb("#ede6f8"), rgb("#3e3556")),
20
+ ),
21
+ data: (
22
+ stroke: pick(rgb("#179a8e"), rgb("#2da79b")),
23
+ fill: pick(rgb("#d8eeec"), rgb("#1b3f3e")),
24
+ ),
25
+ amount: (
26
+ stroke: pick(rgb("#d16022"), rgb("#ed7940")),
27
+ fill: pick(rgb("#f7e4d9"), rgb("#4f3226")),
28
+ ),
29
+ condition: (
30
+ stroke: pick(rgb("#942464"), rgb("#af3e7c")),
31
+ fill: pick(rgb("#eddae5"), rgb("#3e2236")),
32
+ ),
33
+ outside: (
34
+ stroke: pick(rgb("#6b7785"), rgb("#8d99a6")),
35
+ fill: pick(rgb("#f2f3f5"), rgb("#24292f")),
36
+ ),
37
+ )
38
+
39
+ #let stroke-width = 2pt
@@ -0,0 +1,30 @@
1
+ #import "theme.typ": tokens, kinds
2
+ #import "node.typ": *
3
+
4
+ #let timeline(events: (), gap: 36pt) = context {
5
+ let u = uniform(events)
6
+ let h = u.height
7
+ let step = calc.max(..u.widths) + gap
8
+ let stem = 44pt
9
+ let total = step * (events.len() - 1) + calc.max(..u.widths)
10
+ let axis-y = h + stem + 26pt
11
+ box(width: total, height: 2 * axis-y, {
12
+ place(top + left, curve(stroke: 3pt + tokens.line, curve.move((0pt, axis-y)), curve.line((total, axis-y))))
13
+ for (i, event) in events.enumerate() {
14
+ let x = calc.max(..u.widths) / 2 + step * i
15
+ let above = calc.rem(i, 2) == 0
16
+ let spec = kinds.at(event.kind)
17
+ let node-y = if above { h / 2 } else { axis-y + 26pt + stem + h / 2 }
18
+ let stem-from = if above { h } else { axis-y + 26pt + stem }
19
+ place(top + left, curve(stroke: 2.5pt + spec.stroke, curve.move((x, stem-from)), curve.line((x, axis-y))))
20
+ place(top + left, dx: x - 7pt, dy: axis-y - 7pt, circle(radius: 7pt, fill: spec.stroke))
21
+ let date-y = if above { axis-y + 12pt } else { axis-y - 36pt }
22
+ place(top + left, dx: x - 60pt, dy: date-y, box(width: 120pt, align(center, text(size: 15pt, weight: "bold", fill: tokens.ink, event.when))))
23
+ at-center((x, node-y), u.widths.at(i), h, build(event, h, u.widths.at(i)))
24
+ if event.at("note", default: none) != none {
25
+ let note-y = if above { 0pt - 24pt } else { node-y + h / 2 + 6pt }
26
+ place(top + left, dx: x - 90pt, dy: note-y, box(width: 180pt, align(center, text(size: 14pt, fill: tokens.sub, event.note))))
27
+ }
28
+ }
29
+ })
30
+ }
package/typ/tree.typ ADDED
@@ -0,0 +1,56 @@
1
+ #import "theme.typ": tokens, kinds
2
+ #import "shapes.typ": outer-width
3
+ #import "node.typ": *
4
+
5
+ #let flat(n) = (n,) + n.at("children", default: ()).map(flat).flatten()
6
+
7
+ #let tree(root: (), gap-x: 28pt, gap-y: 64pt) = context {
8
+ let everyone = flat(root)
9
+ let sized = everyone.map(natural)
10
+ let h = calc.max(..sized.map(s => s.height))
11
+ let own(n) = outer-width(n.kind, natural(n).inner, h)
12
+ let span(n) = {
13
+ let kids = n.at("children", default: ())
14
+ if kids.len() == 0 { own(n) } else {
15
+ calc.max(own(n), kids.map(span).sum() + gap-x * (kids.len() - 1))
16
+ }
17
+ }
18
+ let lay(n, left, depth) = {
19
+ let kids = n.at("children", default: ())
20
+ let width = span(n)
21
+ let cy = depth * (h + gap-y) + h / 2
22
+ if kids.len() == 0 {
23
+ (items: ((node: n, cx: left + width / 2, cy: cy, w: own(n)),), edges: ())
24
+ } else {
25
+ let block = kids.map(span).sum() + gap-x * (kids.len() - 1)
26
+ let cursor = left + (width - block) / 2
27
+ let items = ()
28
+ let edges = ()
29
+ let centers = ()
30
+ for kid in kids {
31
+ let sub = lay(kid, cursor, depth + 1)
32
+ items += sub.items
33
+ edges += sub.edges
34
+ centers.push(sub.items.first().cx)
35
+ cursor += span(kid) + gap-x
36
+ }
37
+ let cx = (centers.first() + centers.last()) / 2
38
+ for kid-center in centers {
39
+ edges.push((from: (cx, cy + h / 2), to: (kid-center, cy + h + gap-y - h / 2 - 0pt)))
40
+ }
41
+ items.insert(0, (node: n, cx: cx, cy: cy, w: own(n)))
42
+ (items: items, edges: edges)
43
+ }
44
+ }
45
+ let placed = lay(root, 0pt, 0)
46
+ let depth = calc.max(..placed.items.map(i => i.cy)) + h / 2
47
+ box(width: span(root), height: depth, {
48
+ for e in placed.edges {
49
+ let mid = (e.from.at(1) + e.to.at(1)) / 2
50
+ place(top + left, curve(stroke: 2.5pt + tokens.sub, curve.move(e.from), curve.cubic((e.from.at(0), mid), (e.to.at(0), mid), e.to)))
51
+ }
52
+ for item in placed.items {
53
+ at-center((item.cx, item.cy), item.w, h, build(item.node, h, item.w))
54
+ }
55
+ })
56
+ }