ippon-slides 0.1.0 → 0.1.2

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.
@@ -0,0 +1,227 @@
1
+ // Markdown → スライドの <section> 群
2
+ //
3
+ // --- スライドの区切り
4
+ // ::center:: 1 行目に置くとスライドの指示(center / title / wide / bg=xxx / size=1.5)
5
+ // ::right:: ここから右カラム
6
+ // ::note:: 発表者ノート(この行以降は本番に出ず発表者ビューだけに出る)
7
+ // -# 注釈 小さい注釈
8
+ // ```hcl コード(hcl / console / sh / json / js / ts)
9
+ // !! 行 コードの行を強調(行頭の "!! " は消える)
10
+ import { esc, highlight } from './highlight.js';
11
+ export const BG = {
12
+ blue: '#0d76bc',
13
+ orange: '#ff6a00',
14
+ purple: '#5c2d91',
15
+ red: '#c0392b',
16
+ green: '#188038',
17
+ black: '#000000',
18
+ white: '#fafafa',
19
+ };
20
+ const DIRECTIVES = /^(center|title|wide|bg=.+|size=.+)$/;
21
+ // ---------------------------------------------------------------
22
+ // inline
23
+ // ---------------------------------------------------------------
24
+ export function inline(text) {
25
+ const codes = [];
26
+ let s = text.replace(/`([^`]+)`/g, (_, c) => {
27
+ codes.push(`<code>${esc(c)}</code>`);
28
+ return `\u0000${codes.length - 1}\u0000`;
29
+ });
30
+ s = esc(s);
31
+ s = s.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+&quot;([^&]*)&quot;)?\)/g, (_, alt, src, title) => `<img src="${src}" alt="${alt}">` + (title ? `<span class="img-caption">${title}</span>` : ''));
32
+ s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
33
+ s = s.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
34
+ s = s.replace(/(^|[^*])\*([^*\s][^*]*?)\*/g, '$1<em>$2</em>');
35
+ s = s.replace(/→/g, '<span class="arrow">→</span>');
36
+ return s.replace(/\u0000(\d+)\u0000/g, (_, i) => codes[Number(i)]);
37
+ }
38
+ function list(items) {
39
+ const base = items[0].indent;
40
+ const tag = items[0].ordered ? 'ol' : 'ul';
41
+ let html = `<${tag}>`;
42
+ let i = 0;
43
+ while (i < items.length) {
44
+ const item = items[i++];
45
+ const children = [];
46
+ while (i < items.length && items[i].indent > base)
47
+ children.push(items[i++]);
48
+ html += `<li>${inline(item.text)}${children.length ? list(children) : ''}</li>`;
49
+ }
50
+ return html + `</${tag}>`;
51
+ }
52
+ function table(rows) {
53
+ // `\|` はセルの区切りではなく文字としての |
54
+ const cells = (r) => r
55
+ .trim()
56
+ .replace(/^\||\|$/g, '')
57
+ .split(/(?<!\\)\|/)
58
+ .map((c) => c.trim().replace(/\\\|/g, '|'));
59
+ const head = cells(rows[0]);
60
+ const align = cells(rows[1]).map((c) => (/:$/.test(c) ? ' class="num"' : ''));
61
+ let html = '<table><thead><tr>';
62
+ head.forEach((c, i) => (html += `<th${align[i] || ''}>${inline(c)}</th>`));
63
+ html += '</tr></thead><tbody>';
64
+ for (const r of rows.slice(2)) {
65
+ html += '<tr>';
66
+ cells(r).forEach((c, i) => (html += `<td${align[i] || ''}>${inline(c)}</td>`));
67
+ html += '</tr>';
68
+ }
69
+ return html + '</tbody></table>';
70
+ }
71
+ const LIST_ITEM = /^(\s*)([-*]|\d+\.)\s+(.*)$/;
72
+ export function blocks(src) {
73
+ const lines = src.split('\n');
74
+ let html = '';
75
+ let para = [];
76
+ const flush = () => {
77
+ if (!para.length)
78
+ return;
79
+ const text = para.join('\n');
80
+ para = [];
81
+ if (text.startsWith('-# '))
82
+ html += `<p class="note">${inline(text.slice(3)).replace(/\n/g, '<br>')}</p>`;
83
+ else
84
+ html += `<p>${inline(text).replace(/\n/g, '<br>')}</p>`;
85
+ };
86
+ for (let i = 0; i < lines.length; i++) {
87
+ const line = lines[i];
88
+ const fence = line.match(/^```([\w-]*)\s*$/);
89
+ if (fence) {
90
+ flush();
91
+ const lang = fence[1];
92
+ const body = [];
93
+ while (++i < lines.length && !/^```\s*$/.test(lines[i]))
94
+ body.push(lines[i]);
95
+ const attr = lang && lang !== 'console' ? ` data-lang="${esc(lang)}"` : '';
96
+ html += `<pre${attr}><code>${highlight(body.join('\n'), lang)}</code></pre>`;
97
+ continue;
98
+ }
99
+ if (!line.trim()) {
100
+ flush();
101
+ continue;
102
+ }
103
+ const h = line.match(/^(#{1,3})\s+(.*)$/);
104
+ if (h) {
105
+ flush();
106
+ const level = h[1].length;
107
+ html += `<h${level}>${inline(h[2])}</h${level}>`;
108
+ continue;
109
+ }
110
+ if (LIST_ITEM.test(line) && !line.startsWith('-# ')) {
111
+ flush();
112
+ const items = [];
113
+ let m;
114
+ while (i < lines.length && (m = lines[i].match(LIST_ITEM))) {
115
+ items.push({ indent: m[1].length, ordered: /\d/.test(m[2]), text: m[3] });
116
+ i++;
117
+ }
118
+ i--;
119
+ html += list(items);
120
+ continue;
121
+ }
122
+ if (line.startsWith('|') && /^\|?\s*:?-+/.test(lines[i + 1] || '')) {
123
+ flush();
124
+ const rows = [];
125
+ while (i < lines.length && lines[i].startsWith('|'))
126
+ rows.push(lines[i++]);
127
+ i--;
128
+ html += table(rows);
129
+ continue;
130
+ }
131
+ if (line.startsWith('> ')) {
132
+ flush();
133
+ const q = [];
134
+ while (i < lines.length && lines[i].startsWith('> '))
135
+ q.push(lines[i++].slice(2));
136
+ i--;
137
+ html += `<blockquote>${blocks(q.join('\n'))}</blockquote>`;
138
+ continue;
139
+ }
140
+ para.push(line);
141
+ }
142
+ flush();
143
+ return html;
144
+ }
145
+ // ---------------------------------------------------------------
146
+ // slide
147
+ // ---------------------------------------------------------------
148
+ export function splitSlides(md) {
149
+ const slides = [];
150
+ let cur = [];
151
+ let inFence = false;
152
+ for (const line of md.split('\n')) {
153
+ if (/^```/.test(line))
154
+ inFence = !inFence;
155
+ if (!inFence && /^---\s*$/.test(line)) {
156
+ slides.push(cur.join('\n'));
157
+ cur = [];
158
+ }
159
+ else
160
+ cur.push(line);
161
+ }
162
+ slides.push(cur.join('\n'));
163
+ return slides.filter((s) => s.trim());
164
+ }
165
+ export function slide(src) {
166
+ const classes = ['slide'];
167
+ let style = '';
168
+ let body = src.replace(/^\s+/, '');
169
+ // 発表者ノート(::note:: 以降。本番スライドには出さない)
170
+ let notes = '';
171
+ const noteParts = body.split(/^::note::[ \t]*$/m);
172
+ if (noteParts.length > 1) {
173
+ body = noteParts[0];
174
+ notes = blocks(noteParts.slice(1).join('\n').trim());
175
+ }
176
+ const d = body.match(/^::([^:]+)::[ \t]*(\n|$)/);
177
+ const tokens = d ? d[1].trim().split(/\s+/) : [];
178
+ if (d && tokens.every((t) => DIRECTIVES.test(t))) {
179
+ for (const tok of tokens) {
180
+ const bg = tok.match(/^bg=(.+)$/);
181
+ const size = tok.match(/^size=(.+)$/);
182
+ if (bg) {
183
+ const name = bg[1];
184
+ style += `background:${esc(BG[name] || name)};`;
185
+ if (name === 'white')
186
+ classes.push('light');
187
+ }
188
+ else if (size)
189
+ style += `--slide-size:${esc(size[1])};`;
190
+ else
191
+ classes.push(tok);
192
+ }
193
+ body = body.slice(d[0].length);
194
+ }
195
+ let html;
196
+ const parts = body.split(/^::right::[ \t]*$/m);
197
+ if (parts.length === 2) {
198
+ const [first, right] = parts;
199
+ // 先頭の見出しはカラムの外(上)に出す
200
+ const head = first.match(/^\s*(#{1,3} .*)\n/);
201
+ const left = head ? first.replace(head[0], '') : first;
202
+ html =
203
+ (head ? blocks(head[1]) : '') +
204
+ `<div class="cols"><div>${blocks(left)}</div><div>${blocks(right)}</div></div>`;
205
+ }
206
+ else {
207
+ html = blocks(body);
208
+ }
209
+ return `<section class="${classes.join(' ')}"${style ? ` style="${style}"` : ''}>${html}${notes ? `<aside class="notes">${notes}</aside>` : ''}</section>`;
210
+ }
211
+ export function frontmatter(md) {
212
+ const m = md.replace(/^\uFEFF/, '').match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);
213
+ if (!m)
214
+ return [{}, md];
215
+ const meta = {};
216
+ for (const line of m[1].split(/\r?\n/)) {
217
+ const kv = line.match(/^(\w+):\s*(.*?)\s*$/);
218
+ if (kv)
219
+ meta[kv[1]] = kv[2].replace(/^(["'])(.*)\1$/, '$2');
220
+ }
221
+ return [meta, md.slice(m[0].length)];
222
+ }
223
+ /** Markdown 全体 → { meta, sections } */
224
+ export function parse(md) {
225
+ const [meta, body] = frontmatter(md.replace(/\r\n/g, '\n'));
226
+ return { meta, sections: splitSlides(body).map(slide) };
227
+ }
package/dist/pdf.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /** --browser-path → CHROME_PATH → よくある場所 の順に探す */
2
+ export declare function findBrowser(explicit?: string): string | null;
3
+ export interface PdfOptions {
4
+ /** 使うブラウザ。省略すると CHROME_PATH → よくある場所 の順に探す */
5
+ browserPath?: string;
6
+ }
7
+ /**
8
+ * @param html file:// URL の画像で組み立てた HTML
9
+ * @param out 出力する PDF のパス
10
+ */
11
+ export declare function toPdf(html: string, out: string, { browserPath }?: PdfOptions): Promise<void>;
package/dist/pdf.js ADDED
@@ -0,0 +1,83 @@
1
+ // PDF 出力。ローカルの Chrome / Chromium / Edge をヘッドレスで起動して印刷する。
2
+ // 依存パッケージなし(puppeteer も使わない)。
3
+ import { spawn } from 'node:child_process';
4
+ import { existsSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { delimiter, join } from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+ const CANDIDATES = {
9
+ darwin: [
10
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
11
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
12
+ '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
13
+ '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
14
+ ],
15
+ linux: ['google-chrome-stable', 'google-chrome', 'chromium', 'chromium-browser', 'microsoft-edge', 'brave-browser'],
16
+ win32: [
17
+ join(process.env['PROGRAMFILES'] || 'C:\\Program Files', 'Google\\Chrome\\Application\\chrome.exe'),
18
+ join(process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)', 'Google\\Chrome\\Application\\chrome.exe'),
19
+ join(process.env['LOCALAPPDATA'] || '', 'Google\\Chrome\\Application\\chrome.exe'),
20
+ join(process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)', 'Microsoft\\Edge\\Application\\msedge.exe'),
21
+ ],
22
+ };
23
+ function which(cmd) {
24
+ for (const dir of (process.env.PATH || '').split(delimiter)) {
25
+ const p = join(dir, cmd);
26
+ if (existsSync(p))
27
+ return p;
28
+ }
29
+ return null;
30
+ }
31
+ /** --browser-path → CHROME_PATH → よくある場所 の順に探す */
32
+ export function findBrowser(explicit) {
33
+ if (explicit)
34
+ return existsSync(explicit) ? explicit : null;
35
+ if (process.env.CHROME_PATH && existsSync(process.env.CHROME_PATH))
36
+ return process.env.CHROME_PATH;
37
+ for (const c of CANDIDATES[process.platform] || []) {
38
+ const p = c.includes('/') || c.includes('\\') ? (existsSync(c) ? c : null) : which(c);
39
+ if (p)
40
+ return p;
41
+ }
42
+ return null;
43
+ }
44
+ /**
45
+ * @param html file:// URL の画像で組み立てた HTML
46
+ * @param out 出力する PDF のパス
47
+ */
48
+ export async function toPdf(html, out, { browserPath } = {}) {
49
+ const browser = findBrowser(browserPath);
50
+ if (!browser) {
51
+ throw new Error('PDF の出力には Chrome / Chromium / Edge が必要です。--browser-path か環境変数 CHROME_PATH で場所を指定してください。');
52
+ }
53
+ const dir = mkdtempSync(join(tmpdir(), 'ippon-'));
54
+ const src = join(dir, 'slide.html');
55
+ writeFileSync(src, html);
56
+ rmSync(out, { force: true });
57
+ try {
58
+ const args = [
59
+ '--headless=new',
60
+ '--disable-gpu',
61
+ '--no-first-run',
62
+ '--no-default-browser-check',
63
+ `--user-data-dir=${join(dir, 'profile')}`,
64
+ '--no-pdf-header-footer',
65
+ '--virtual-time-budget=3000', // Web フォントの読み込みを待つ
66
+ `--print-to-pdf=${out}`,
67
+ pathToFileURL(src).href,
68
+ ];
69
+ const stderr = await new Promise((ok, ng) => {
70
+ const p = spawn(browser, args, { stdio: ['ignore', 'ignore', 'pipe'] });
71
+ let err = '';
72
+ p.stderr.on('data', (d) => (err += d));
73
+ p.on('error', ng);
74
+ p.on('close', () => ok(err));
75
+ });
76
+ if (!existsSync(out) || statSync(out).size === 0) {
77
+ throw new Error(`PDF の出力に失敗しました(${browser})\n${stderr.trim()}`);
78
+ }
79
+ }
80
+ finally {
81
+ rmSync(dir, { recursive: true, force: true });
82
+ }
83
+ }
@@ -0,0 +1,14 @@
1
+ export interface RenderOptions {
2
+ /** 画像の相対パスの基準(= Markdown のあるディレクトリ) */
3
+ baseDir: string;
4
+ /** 出力先ディレクトリ。省略すると画像は file:// URL になる */
5
+ outDir?: string;
6
+ /** 追加の CSS(--css) */
7
+ css?: string;
8
+ }
9
+ export interface RenderResult {
10
+ html: string;
11
+ /** スライドの枚数 */
12
+ count: number;
13
+ }
14
+ export declare function render(md: string, { baseDir, outDir, css }: RenderOptions): RenderResult;
package/dist/render.js ADDED
@@ -0,0 +1,52 @@
1
+ // スライドの HTML を 1 ファイルに組み立てる(CSS / JS も全部埋め込む)
2
+ import { readFileSync } from 'node:fs';
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ import { esc } from './highlight.js';
6
+ import { parse } from './markdown.js';
7
+ const assets = join(dirname(fileURLToPath(import.meta.url)), '..', 'assets');
8
+ const EXTERNAL = /^(?:[a-z][a-z0-9+.-]*:|\/\/|#|\/)/i;
9
+ /**
10
+ * 相対パスの画像を、出力先から見たパスに書き換える。
11
+ * - outDir を渡す → 出力先からの相対パス(HTML 用)
12
+ * - outDir なし → file:// の絶対 URL(PDF の一時ファイル用)
13
+ */
14
+ function rewriteImages(html, baseDir, outDir) {
15
+ return html.replace(/(<img src=")([^"]+)(")/g, (all, pre, src, post) => {
16
+ if (EXTERNAL.test(src) || isAbsolute(src))
17
+ return all;
18
+ const abs = resolve(baseDir, decodeURI(src));
19
+ const url = outDir ? encodeURI(relative(outDir, abs).split(sep).join('/')) : pathToFileURL(abs).href;
20
+ return pre + url + post;
21
+ });
22
+ }
23
+ export function render(md, { baseDir, outDir, css = '' }) {
24
+ const { meta, sections } = parse(md);
25
+ const style = readFileSync(join(assets, 'style.css'), 'utf8') + (css ? `\n/* --css */\n${css}` : '');
26
+ const script = readFileSync(join(assets, 'deck.js'), 'utf8');
27
+ const body = rewriteImages(sections.join('\n'), baseDir, outDir);
28
+ const html = `<!doctype html>
29
+ <html lang="${esc(meta.lang || 'ja')}">
30
+ <head>
31
+ <meta charset="utf-8">
32
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
33
+ <title>${esc(meta.title || 'slides')}</title>
34
+ ${meta.description ? `<meta name="description" content="${esc(meta.description)}">\n` : ''}${meta.author ? `<meta name="author" content="${esc(meta.author)}">\n` : ''}<meta name="generator" content="ippon-slides">
35
+ <style>${style}</style>
36
+ </head>
37
+ <body>
38
+ <div id="deck">
39
+ ${body}
40
+ </div>
41
+ <div id="overview"></div>
42
+ <div id="presenter"></div>
43
+ <div id="progress"></div>
44
+ <div id="timer"></div>
45
+ <div id="counter"></div>
46
+ <div id="hint">← → 移動 ・ f フルスクリーン ・ o 一覧 ・ p 発表者</div>
47
+ <script>${script}</script>
48
+ </body>
49
+ </html>
50
+ `;
51
+ return { html, count: sections.length };
52
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ippon-slides",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "1 枚 1 メッセージのスライドを Markdown から作る CLI。HTML 1 ファイルと PDF を出力",
5
5
  "keywords": [
6
6
  "slides",
@@ -25,17 +25,28 @@
25
25
  "ippon": "bin/ippon.js"
26
26
  },
27
27
  "exports": {
28
- ".": "./src/index.js"
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "import": "./dist/index.js"
31
+ }
29
32
  },
33
+ "types": "./dist/index.d.ts",
30
34
  "files": [
31
35
  "bin",
32
- "src",
36
+ "dist",
33
37
  "assets"
34
38
  ],
35
39
  "engines": {
36
40
  "node": ">=18.17"
37
41
  },
38
42
  "scripts": {
39
- "test": "node --test"
43
+ "build": "tsc -p tsconfig.build.json && tsc -p src/client",
44
+ "typecheck": "tsc && tsc -p src/client --noEmit",
45
+ "test": "npm run build && node --test test/*.test.ts",
46
+ "prepack": "npm run build"
47
+ },
48
+ "devDependencies": {
49
+ "@types/node": "^22.20.5",
50
+ "typescript": "^7.0.2"
40
51
  }
41
52
  }
package/src/cli.js DELETED
@@ -1,236 +0,0 @@
1
- import { existsSync, mkdirSync, readFileSync, statSync, watch, writeFileSync } from 'node:fs'
2
- import { basename, dirname, extname, join, resolve } from 'node:path'
3
- import { fileURLToPath } from 'node:url'
4
- import { toPdf } from './pdf.js'
5
- import { render } from './render.js'
6
-
7
- const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8'))
8
-
9
- const HELP = `ippon v${pkg.version} — 1 枚 1 メッセージのスライドを Markdown から作る
10
-
11
- 使い方:
12
- ippon build <input.md> [options] スライドをビルドする
13
- ippon <input.md> [options] build の省略形
14
- ippon init [file] サンプルの Markdown を作る(デフォルト: slide.md)
15
-
16
- build のオプション:
17
- --html HTML を出力する(--pdf がなければデフォルト)
18
- --pdf PDF を出力する(Chrome / Chromium / Edge が必要)
19
- -o, --output <path> 出力先。--html と --pdf を両方指定したときは拡張子だけ差し替える
20
- ディレクトリを指定するとその中に <input>.html / .pdf を作る
21
- -w, --watch Markdown と --css の変更を監視して再ビルドする
22
- --css <file> 追加の CSS(色やフォントの上書きなど)
23
- --browser-path <path> PDF に使うブラウザ(環境変数 CHROME_PATH でも可)
24
-
25
- -h, --help ヘルプ
26
- -v, --version バージョン
27
-
28
- 例:
29
- ippon build slide.md --html
30
- ippon build slide.md --pdf -o dist/
31
- ippon build slide.md --html --pdf -o dist/talk
32
- ippon build slide.md --html -w
33
- `
34
-
35
- // ---------------------------------------------------------------
36
- // args
37
- // ---------------------------------------------------------------
38
-
39
- const FLAGS = { '--html': 'html', '--pdf': 'pdf', '-w': 'watch', '--watch': 'watch', '-h': 'help', '--help': 'help', '-v': 'version', '--version': 'version' }
40
- const VALUES = { '-o': 'output', '--output': 'output', '--css': 'css', '--browser-path': 'browserPath' }
41
-
42
- export function parseArgs(argv) {
43
- const opts = { _: [] }
44
- for (let i = 0; i < argv.length; i++) {
45
- let a = argv[i]
46
- let v
47
- const eq = a.match(/^(--[^=]+)=(.*)$/)
48
- if (eq) [, a, v] = eq
49
- if (FLAGS[a]) opts[FLAGS[a]] = true
50
- else if (VALUES[a]) {
51
- if (v === undefined) v = argv[++i]
52
- if (v === undefined) throw new Error(`${a} には値が必要です`)
53
- opts[VALUES[a]] = v
54
- } else if (a.startsWith('-') && a !== '-') throw new Error(`不明なオプション: ${a}`)
55
- else opts._.push(a)
56
- }
57
- return opts
58
- }
59
-
60
- /** 出力先を決める */
61
- export function outputs(input, { html, pdf, output }) {
62
- const formats = []
63
- if (html || !pdf) formats.push('html')
64
- if (pdf) formats.push('pdf')
65
-
66
- const name = basename(input, extname(input))
67
- let base // 拡張子なしのパス
68
- let exact = null // 1 形式だけのときに -o をそのまま使う
69
-
70
- if (!output) base = join(dirname(input), name)
71
- else if (output.endsWith('/') || output.endsWith('\\') || (existsSync(output) && statSync(output).isDirectory()))
72
- base = join(output, name)
73
- else if (formats.length === 1 && extname(output)) exact = output
74
- else base = extname(output) ? output.slice(0, -extname(output).length) : output
75
-
76
- return formats.map((f) => ({ format: f, path: resolve(exact || `${base}.${f}`) }))
77
- }
78
-
79
- // ---------------------------------------------------------------
80
- // build
81
- // ---------------------------------------------------------------
82
-
83
- const time = () => new Date().toLocaleTimeString()
84
-
85
- async function build(input, opts) {
86
- const md = readFileSync(input, 'utf8')
87
- const css = opts.css ? readFileSync(opts.css, 'utf8') : ''
88
- const baseDir = dirname(resolve(input))
89
-
90
- for (const { format, path } of outputs(input, opts)) {
91
- mkdirSync(dirname(path), { recursive: true })
92
- if (format === 'html') {
93
- const { html, count } = render(md, { baseDir, outDir: dirname(path), css })
94
- writeFileSync(path, html)
95
- console.log(`${time()} ✓ ${count} slides → ${path}`)
96
- } else {
97
- const { html, count } = render(md, { baseDir, css })
98
- await toPdf(html, path, { browserPath: opts.browserPath })
99
- console.log(`${time()} ✓ ${count} slides → ${path}`)
100
- }
101
- }
102
- }
103
-
104
- function watchBuild(input, opts) {
105
- let timer = null
106
- let running = Promise.resolve()
107
- const rebuild = () => {
108
- clearTimeout(timer)
109
- timer = setTimeout(() => {
110
- running = running.then(() => build(input, opts)).catch((e) => console.error(`${time()} ✗ ${e.message}`))
111
- }, 80)
112
- }
113
- // エディタによってはファイルを置き換えて保存するので、ディレクトリごと監視する
114
- const files = [input, opts.css].filter(Boolean).map((f) => resolve(f))
115
- for (const dir of new Set(files.map(dirname))) {
116
- watch(dir, (_, file) => {
117
- if (file && files.includes(join(dir, file.toString()))) rebuild()
118
- })
119
- }
120
- console.log(`watching ${files.join(', ')} ...`)
121
- }
122
-
123
- // ---------------------------------------------------------------
124
- // init
125
- // ---------------------------------------------------------------
126
-
127
- const SAMPLE = `---
128
- title: はじめての ippon
129
- author: あなたの名前
130
- ---
131
-
132
- ::title::
133
-
134
- # はじめての ippon
135
-
136
- サブタイトル
137
-
138
- あなたの名前 ・ 2026-01-01
139
-
140
- ---
141
-
142
- ::center::
143
-
144
- 1 枚に
145
-
146
- 1 メッセージ
147
-
148
- ---
149
-
150
- ::center size=2::
151
-
152
- **大きく**
153
-
154
- ---
155
-
156
- ::center bg=blue::
157
-
158
- 背景色も変えられる
159
-
160
- -# blue / orange / purple / red / green / black / white、または #rrggbb
161
-
162
- ---
163
-
164
- ::center size=1.5 bg=white::
165
-
166
- セクション
167
-
168
- ---
169
-
170
- ## 箇条書き
171
-
172
- - **太字** はアクセントカラーになる
173
- - \`inline code\` も書ける
174
- - ネストもできる
175
- - 矢印 → は少し薄くなる
176
-
177
- ---
178
-
179
- ## 2 カラム
180
-
181
- - 左に説明
182
- - 右にコード
183
-
184
- ::right::
185
-
186
- \`\`\`ts
187
- const app = new Hono()
188
- !! app.get('/', (c) => c.text('Hello!'))
189
- \`\`\`
190
-
191
- -# 行頭に "!! " を付けるとその行が強調される
192
-
193
- ---
194
-
195
- \`\`\`console
196
- $ npx ippon-slides build slide.md --html --pdf
197
- ✓ 9 slides → slide.html
198
- ✓ 9 slides → slide.pdf
199
- \`\`\`
200
-
201
- ---
202
-
203
- ::title::
204
-
205
- # ありがとうございました
206
-
207
- あなたの名前
208
- `
209
-
210
- function init(file = 'slide.md') {
211
- if (existsSync(file)) throw new Error(`${file} はすでにあります`)
212
- writeFileSync(file, SAMPLE)
213
- console.log(`✓ ${file} を作りました → ippon build ${file} --html -w`)
214
- }
215
-
216
- // ---------------------------------------------------------------
217
- // main
218
- // ---------------------------------------------------------------
219
-
220
- export async function main(argv) {
221
- const opts = parseArgs(argv)
222
- if (opts.version) return console.log(pkg.version)
223
- if (opts.help || opts._.length === 0) return console.log(HELP)
224
-
225
- let [cmd, ...rest] = opts._
226
- if (cmd === 'init') return init(rest[0])
227
- if (cmd !== 'build') rest = [cmd, ...rest] // `ippon slide.md` は build の省略形
228
-
229
- const input = rest[0]
230
- if (!input) throw new Error('入力の Markdown を指定してください(例: ippon build slide.md --html)')
231
- if (rest.length > 1) throw new Error(`入力は 1 つだけ指定してください: ${rest.join(' ')}`)
232
- if (!existsSync(input)) throw new Error(`${input} が見つかりません`)
233
-
234
- await build(input, opts)
235
- if (opts.watch) watchBuild(input, opts)
236
- }