kintone-plugin-ide 0.0.0-stage → 0.3.1

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,94 @@
1
+ // IDE を組み立てる。各部品は ctx(共有の入れ物)に自分の関数を足していく
2
+ import { F } from '../config.js';
3
+ import { api } from '../kintone/api.js';
4
+ import { canInstall } from '../kintone/api.js';
5
+ import { loadSettings } from '../util/settings.js';
6
+ import { createState, readSources } from './state.js';
7
+ import { setupDialog } from './dialog.js';
8
+ import { setupLayout } from './layout.js';
9
+ import { setupTerminal } from './terminal.js';
10
+ import { setupTree } from './tree.js';
11
+ import { setupEditor } from './editor.js';
12
+ import { setupSave } from './actions/save.js';
13
+ import { setupRelease } from './actions/release.js';
14
+ import { setupZip } from './actions/zip.js';
15
+ import { setupNpm } from './actions/npm.js';
16
+ import { setupMisc } from './actions/misc.js';
17
+ import { setupCommands } from './commands.js';
18
+ import { SAMPLE } from './sample.js';
19
+
20
+ export async function openIDE() {
21
+ if (document.querySelector('.kpi-root')) return;
22
+ const appId = kintone.app.getId();
23
+ const recordId = kintone.app.record.getId();
24
+ const ctx = {
25
+ appId, recordId,
26
+ draftKey: `kintone-plugin-ide:draft:${location.host}:${appId}:${recordId}`,
27
+ settings: loadSettings(),
28
+ problems: { errors: 0, warnings: 0 },
29
+ savedOnce: false,
30
+ current: null,
31
+ // ターミナルができるまではコンソールに出す
32
+ log: Object.fromEntries(['info', 'ok', 'warn', 'error', 'plain'].map((k) => [k, (t) => console.log(`[IDE ${k}]`, t)])),
33
+ };
34
+ ctx.loadRecord = async () => (await api('/k/v1/record.json', 'GET', { app: appId, id: recordId })).record;
35
+ ctx.record = await ctx.loadRecord();
36
+ const sources = await readSources(ctx.record);
37
+ ctx.state = createState(sources);
38
+ ctx.testApp = () => Number(ctx.record[F.testApp] && ctx.record[F.testApp].value) || 0;
39
+ ctx.pluginIdValue = () => ctx.record[F.id] && ctx.record[F.id].value;
40
+ ctx.manifestInfo = () => { try { const m = JSON.parse(ctx.state.files.get('manifest.json')); return { name: m.name.ja || m.name.en, version: m.version }; } catch { return null; } };
41
+
42
+ setupLayout(ctx);
43
+ setupDialog(ctx);
44
+ setupCommands(ctx);
45
+ await setupTerminal(ctx);
46
+ await setupTree(ctx);
47
+ setupSave(ctx);
48
+ await setupEditor(ctx);
49
+ setupRelease(ctx);
50
+ setupZip(ctx);
51
+ setupNpm(ctx);
52
+ setupMisc(ctx);
53
+
54
+ // ---- 閉じる ----
55
+ const onKey = (e) => {
56
+ if (e.key === 'Escape' && !document.querySelector('.kpi-menu, .kpi-dialog') && !ctx.ui.termEl.contains(document.activeElement) && !ctx.isDiffOpen()) ctx.close();
57
+ };
58
+ const guard = (e) => { if (ctx.state.dirty().length) { e.preventDefault(); e.returnValue = ''; } };
59
+ ctx.close = async () => {
60
+ if (ctx.state.dirty().length && !(await ctx.confirm('保存していない変更があります', '閉じても、下書きはこのブラウザに残ります', { ok: '閉じる' }))) return;
61
+ ctx.disposeTerminal(); ctx.disposeEditor(); ctx.closeMenu();
62
+ ctx.tree.cleanUp?.();
63
+ window.removeEventListener('beforeunload', guard);
64
+ document.removeEventListener('keydown', onKey);
65
+ ctx.ui.root.remove();
66
+ document.body.style.overflow = '';
67
+ // URL に ide=1 が残っていると、読み込み直した時にまた開いてしまう
68
+ const clean = location.href.replace(/([?&#])ide=1(&|$)/, (_, a, b) => (b ? a : '')).replace(/[?&#]$/, '');
69
+ if (clean !== location.href) history.replaceState(history.state, '', clean);
70
+ // 保存した時だけ、詳細画面を新しい内容にするために読み込み直す
71
+ if (ctx.savedOnce) location.reload();
72
+ };
73
+ window.addEventListener('beforeunload', guard);
74
+ document.addEventListener('keydown', onKey);
75
+
76
+ // ---- 最初の表示 ----
77
+ const { files } = ctx.state;
78
+ if (!ctx.state.sourcePaths().length) {
79
+ ctx.log.info('ファイルがありません。サンプル(TypeScript + npm + 設定画面)を入れました。保存すると残ります');
80
+ ctx.addFiles(Object.entries(SAMPLE));
81
+ }
82
+ if (sources.from === 'legacy') ctx.log.warn('ソースは前の形式(サブテーブル)です。保存すると zip のフィールドに移ります');
83
+ await ctx.restoreDraft();
84
+ ctx.preloadModels();
85
+ ctx.refreshStatus();
86
+ ctx.openFile(['src/desktop.ts', 'src/desktop.js', 'manifest.json'].find((p) => files.has(p)) || ctx.state.sourcePaths()[0]);
87
+ ctx.log.ok('準備ができました。help でコマンド一覧。Ctrl/Cmd+S 保存 / Ctrl/Cmd+B ビルド / Ctrl/Cmd+Enter インストール');
88
+ if (!canInstall()) ctx.log.warn(`${location.hostname} は INSTALL_HOSTS に無いので、インストールはできません(パッケージとダウンロードはできます)`);
89
+ ctx.startRepl();
90
+ // package.json の通りに node_modules をそろえる(2回目からはブラウザのキャッシュから)
91
+ ctx.run(() => ctx.npmRestore({ quiet: true }));
92
+ window.__kintonePluginIDE = ctx;
93
+ return ctx;
94
+ }
@@ -0,0 +1,89 @@
1
+ // 画面の骨組み・大きさの調整・状態バー・処理の直列化
2
+ import { canInstall } from '../kintone/api.js';
3
+ import { el, downloadBlob } from '../util/dom.js';
4
+ import { saveSettings } from '../util/settings.js';
5
+ import { CSS, DIALOG_CSS } from './css.js';
6
+
7
+ export function setupLayout(ctx) {
8
+ const { log, settings, recordId } = ctx;
9
+ if (!document.getElementById('kpi-style')) document.head.append(el('style', { id: 'kpi-style', textContent: CSS + DIALOG_CSS }));
10
+
11
+ const btn = (label, title, onClick, cls = '') => { const b = el('button', { className: `kpi-btn ${cls}`, textContent: label, title }); b.onclick = onClick; return b; };
12
+ const sideBtn = (label, title, fn) => { const b = el('button', { textContent: label, title }); b.onclick = fn; return b; };
13
+ const titleEl = el('div', { className: 'kpi-title' });
14
+ const editorEl = el('div', { className: 'kpi-editor' }, el('div', { className: 'kpi-empty', innerHTML: '左のファイルを選んでください<br><small>zip をここにドロップすると取り込めます</small>' }));
15
+ const treeEl = el('div', { className: 'kpi-tree' });
16
+ const side = el('div', { className: 'kpi-side' },
17
+ el('div', { className: 'kpi-side-head' }, el('span', { textContent: 'エクスプローラー' }),
18
+ sideBtn('+', '新しいファイル', () => ctx.newFile('')),
19
+ sideBtn('⊞', '新しいフォルダ', () => ctx.newFolder('')),
20
+ sideBtn('⤒', 'ファイルをアップロード(画像など)', () => ctx.uploadFiles('')),
21
+ sideBtn('⇩', 'zip を取り込む', () => run(ctx.importZip)),
22
+ sideBtn('⇧', 'ソースを zip で書き出す', () => run(ctx.exportZip))),
23
+ treeEl);
24
+ const split = el('div', { className: 'kpi-split' });
25
+ const termEl = el('div', { className: 'kpi-term' });
26
+ const termSplit = el('div', { className: 'kpi-term-split' });
27
+ const termWrap = el('div', { className: 'kpi-term-wrap' }, termSplit, termEl);
28
+ const statusEl = el('div', { className: 'kpi-status' });
29
+ const buttons = {
30
+ save: btn('保存', 'Ctrl/Cmd+S', () => run(ctx.save)),
31
+ build: btn('ビルド', 'Ctrl/Cmd+B', () => run(() => ctx.buildOnly())),
32
+ zip: btn('ダウンロード', 'プラグインの zip をダウンロード', () => run(async () => { const r = await ctx.buildAndPack(); downloadBlob(r.plugin, r.zipName); })),
33
+ install: btn('インストール', 'Ctrl/Cmd+Enter: 保存 → ビルド → パッケージ → インストール → テスト用アプリに反映', () => run(ctx.buildAndInstall), 'primary'),
34
+ close: btn('閉じる', 'Esc', () => ctx.close()),
35
+ };
36
+ if (!canInstall()) buttons.install.style.display = 'none';
37
+ const root = el('div', { className: 'kpi-root' },
38
+ el('div', { className: 'kpi-bar' }, titleEl, ...Object.values(buttons)),
39
+ side, split, editorEl, termWrap, statusEl);
40
+ document.body.append(root);
41
+ document.body.style.overflow = 'hidden';
42
+
43
+ const drag = (handle, onMove) => {
44
+ handle.onpointerdown = (e) => {
45
+ handle.setPointerCapture(e.pointerId); handle.classList.add('on');
46
+ handle.onpointermove = (ev) => onMove(ev);
47
+ handle.onpointerup = () => { handle.onpointermove = null; handle.classList.remove('on'); };
48
+ };
49
+ };
50
+ drag(split, (ev) => root.style.setProperty('--kpi-side', `${Math.min(600, Math.max(140, ev.clientX))}px`));
51
+ drag(termSplit, (ev) => root.style.setProperty('--kpi-term', `${Math.min(innerHeight - 200, Math.max(80, innerHeight - 24 - ev.clientY))}px`));
52
+
53
+ // ---- 状態バー ----
54
+ const toggle = (key, label) => {
55
+ const b = el('button', { textContent: `${label}: ${settings[key] ? 'ON' : 'OFF'}`, title: `クリックで切り替え(${key})` });
56
+ b.onclick = () => { settings[key] = !settings[key]; saveSettings(settings); updateStatus(); };
57
+ return b;
58
+ };
59
+ function updateStatus() {
60
+ const m = ctx.manifestInfo();
61
+ const n = ctx.state.dirty().length;
62
+ titleEl.replaceChildren(m ? `${m.name} v${m.version}` : '(manifest.json なし)', el('small', { textContent: `レコード ${recordId}${n ? ` ・ 未保存 ${n}` : ''}` }));
63
+ const testApp = ctx.testApp();
64
+ const pid = ctx.pluginIdValue();
65
+ const probBtn = el('button', { textContent: `⨂ ${ctx.problems.errors} ⚠ ${ctx.problems.warnings}`, title: '型チェックの結果(クリックで一覧)' });
66
+ probBtn.onclick = () => run(() => ctx.command('check'));
67
+ statusEl.replaceChildren(
68
+ el('span', {}, ctx.current || ''),
69
+ probBtn,
70
+ el('span', { className: 'sp' }),
71
+ toggle('prod', '本番ビルド'), toggle('typecheck', '型チェック'), toggle('format', '保存時に整形'), toggle('watch', '保存でインストール'),
72
+ el('span', {}, 'テスト用アプリ: ', el('b', { textContent: testApp ? `#${testApp}` : '未設定' })),
73
+ el('span', {}, 'ID: ', el('b', { textContent: pid ? pid.slice(0, 8) + '…' : '未作成' })),
74
+ );
75
+ }
76
+
77
+ // ---- 重い処理を1つずつ ----
78
+ let busy = false;
79
+ async function run(fn) {
80
+ if (busy) { log.warn('ほかの処理が終わるまで待ってください'); return; }
81
+ busy = true;
82
+ Object.values(buttons).forEach((b) => { b.disabled = b !== buttons.close; });
83
+ try { await fn(); } catch (e) { console.error(e); log.error(e.message || String(e)); }
84
+ finally { busy = false; Object.values(buttons).forEach((b) => { b.disabled = false; }); }
85
+ }
86
+
87
+ ctx.ui = { root, editorEl, treeEl, termEl, statusEl, buttons };
88
+ Object.assign(ctx, { run, updateStatus });
89
+ }
@@ -0,0 +1,168 @@
1
+ // 最初に開いた時(ファイルが無い時)に入れるサンプル: TypeScript + npm + 複数ファイル + 設定画面 + CSS
2
+ import { BINARY_PREFIX } from '../config.js';
3
+ import { DEFAULT_TSCONFIG } from './workspace-fs.js';
4
+
5
+ const ICON = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAFklEQVR4nGMwnvmfJMQwqmFUw/DVAAA4MssQTFf6UAAAAABJRU5ErkJggg==';
6
+ export const SAMPLE = {
7
+ 'manifest.json': JSON.stringify({
8
+ manifest_version: 1, version: '0.1.0', type: 'APP',
9
+ name: { ja: 'サンプルプラグイン', en: 'Sample plugin' },
10
+ description: { ja: 'kintone Plugin IDE で作ったサンプル', en: 'Made with kintone Plugin IDE' },
11
+ homepage_url: { ja: 'https://cybozu.dev/ja/kintone/', en: 'https://kintone.dev/en/' },
12
+ icon: 'image/icon.png',
13
+ desktop: { js: ['js/desktop.js'], css: ['css/desktop.css'] },
14
+ config: { html: 'html/config.html', js: ['js/config.js'], css: [], required_params: ['message'] },
15
+ }, null, 2) + '\n',
16
+ 'package.json': JSON.stringify({ name: 'sample-plugin', version: '0.1.0', private: true, dependencies: { dayjs: '^1.11.0' } }, null, 2) + '\n',
17
+ 'src/desktop.ts': [
18
+ "import dayjs from 'dayjs';",
19
+ "import { banner } from './lib/banner';",
20
+ '',
21
+ '// kintone.$PLUGIN_ID は読み込まれた瞬間にしか取れないので、最初に受け取っておく',
22
+ 'const PLUGIN_ID = kintone.$PLUGIN_ID;',
23
+ '',
24
+ "kintone.events.on('app.record.index.show', (event) => {",
25
+ ' const { message = \'こんにちは\' } = kintone.plugin.app.getConfig(PLUGIN_ID);',
26
+ ' const space = kintone.app.getHeaderMenuSpaceElement();',
27
+ " if (space && !space.querySelector('.sample-banner')) {",
28
+ " space.append(banner(`${message}。いまは ${dayjs().format('YYYY/MM/DD HH:mm')} です`));",
29
+ ' }',
30
+ ' return event;',
31
+ '});',
32
+ '',
33
+ ].join('\n'),
34
+ 'src/lib/banner.ts': [
35
+ 'export function banner(text: string): HTMLElement {',
36
+ " const el = document.createElement('span');",
37
+ " el.className = 'sample-banner';",
38
+ ' el.textContent = text;',
39
+ ' return el;',
40
+ '}',
41
+ '',
42
+ ].join('\n'),
43
+ 'src/desktop.css': '.sample-banner {\n padding: 4px 10px;\n border-radius: 6px;\n background: #2b6cb0;\n color: #fff;\n font-weight: 600;\n}\n',
44
+ 'src/config.ts': [
45
+ 'const PLUGIN_ID = kintone.$PLUGIN_ID;',
46
+ '',
47
+ "const form = document.querySelector<HTMLFormElement>('#sample-config')!;",
48
+ "const input = form.querySelector<HTMLInputElement>('input[name=message]')!;",
49
+ "input.value = kintone.plugin.app.getConfig(PLUGIN_ID).message ?? 'こんにちは';",
50
+ '',
51
+ "form.addEventListener('submit', (e) => {",
52
+ ' e.preventDefault();',
53
+ ' kintone.plugin.app.setConfig({ message: input.value });',
54
+ '});',
55
+ "document.querySelector('#sample-cancel')!.addEventListener('click', () => history.back());",
56
+ '',
57
+ ].join('\n'),
58
+ 'html/config.html': [
59
+ '<form id="sample-config">',
60
+ ' <label>あいさつの言葉 <input name="message" class="kintoneplugin-input-text"></label>',
61
+ ' <p>',
62
+ ' <button type="submit" class="kintoneplugin-button-dialog-ok">保存</button>',
63
+ ' <button type="button" id="sample-cancel" class="kintoneplugin-button-dialog-cancel">キャンセル</button>',
64
+ ' </p>',
65
+ '</form>',
66
+ '',
67
+ ].join('\n'),
68
+ // kintone の型は @kintone/dts-gen を URL のまま読む(エディタの補完・型チェック用。ビルドには関係しない)
69
+ 'tsconfig.json': DEFAULT_TSCONFIG,
70
+ 'image/icon.png': BINARY_PREFIX + ICON,
71
+ };
72
+
73
+
74
+ // ---- フレームワークのサンプル(ターミナルの `sample svelte` / `sample vue`) ----
75
+ const manifestFor = (ja, en) => SAMPLE['manifest.json'].replace('サンプルプラグイン', ja).replace('Sample plugin', en);
76
+ const pkgFor = (name, deps) => JSON.stringify({ name, version: '0.1.0', private: true, dependencies: deps }, null, 2) + '\n';
77
+ const common = {
78
+ 'src/config.ts': SAMPLE['src/config.ts'],
79
+ 'html/config.html': SAMPLE['html/config.html'],
80
+ 'tsconfig.json': DEFAULT_TSCONFIG,
81
+ 'image/icon.png': SAMPLE['image/icon.png'],
82
+ };
83
+ const mountTs = (importLine, mountLine) => [
84
+ importLine,
85
+ '',
86
+ 'const PLUGIN_ID = kintone.$PLUGIN_ID;',
87
+ '',
88
+ "kintone.events.on('app.record.index.show', (event) => {",
89
+ ' const space = kintone.app.getHeaderMenuSpaceElement();',
90
+ " if (space && !space.querySelector('.sample-root')) {",
91
+ " const target = document.createElement('span');",
92
+ " target.className = 'sample-root';",
93
+ ' space.append(target);',
94
+ " const { message = 'こんにちは' } = kintone.plugin.app.getConfig(PLUGIN_ID);",
95
+ ` ${mountLine}`,
96
+ ' }',
97
+ ' return event;',
98
+ '});',
99
+ '',
100
+ ].join('\n');
101
+ const SCSS = [
102
+ '// css/desktop.css は src/desktop.scss から作られる(.css / .scss / .sass / .less のどれでもいい)',
103
+ '$accent: #2b6cb0;',
104
+ '',
105
+ '.sample-root {',
106
+ ' display: inline-flex;',
107
+ ' margin-left: 8px;',
108
+ ' button { border-color: $accent; }',
109
+ '}',
110
+ '',
111
+ ].join('\n');
112
+
113
+ export const SAMPLES = {
114
+ ts: SAMPLE,
115
+ svelte: {
116
+ 'manifest.json': manifestFor('Svelte サンプル', 'Svelte sample'),
117
+ 'package.json': pkgFor('svelte-sample', { svelte: '^5.0.0' }),
118
+ 'src/desktop.ts': mountTs("import { mount } from 'svelte';\nimport App from './App.svelte';", 'mount(App, { target, props: { message } });'),
119
+ 'src/App.svelte': [
120
+ '<script lang="ts">',
121
+ " import { clicks } from './clicks.svelte';",
122
+ '',
123
+ ' let { message }: { message: string } = $props();',
124
+ ' let count = $state(0);',
125
+ ' let doubled = $derived(count * 2);',
126
+ '</script>',
127
+ '',
128
+ '<button onclick={() => { count++; clicks.total++; }}>',
129
+ ' {message} ・ {count} 回(×2 = {doubled}、全体 {clicks.total})',
130
+ '</button>',
131
+ '',
132
+ '<style>',
133
+ ' /* このコンポーネントの中だけに効く */',
134
+ ' button { padding: 4px 12px; border-radius: 6px; background: #ff3e00; color: #fff; border: 2px solid; font-weight: 600; cursor: pointer; }',
135
+ '</style>',
136
+ '',
137
+ ].join('\n'),
138
+ 'src/clicks.svelte.ts': '// .svelte.ts ではルーン($state など)がコンポーネントの外でも使える\nexport const clicks = $state({ total: 0 });\n',
139
+ 'src/desktop.scss': SCSS,
140
+ ...common,
141
+ },
142
+ vue: {
143
+ 'manifest.json': manifestFor('Vue サンプル', 'Vue sample'),
144
+ 'package.json': pkgFor('vue-sample', { vue: '^3.5.0' }),
145
+ 'src/desktop.ts': mountTs("import { createApp } from 'vue';\nimport App from './App.vue';", 'createApp(App, { message }).mount(target);'),
146
+ 'src/App.vue': [
147
+ '<script setup lang="ts">',
148
+ "import { computed, ref } from 'vue';",
149
+ '',
150
+ 'const props = defineProps<{ message: string }>();',
151
+ 'const count = ref(0);',
152
+ 'const doubled = computed(() => count.value * 2);',
153
+ '</script>',
154
+ '',
155
+ '<template>',
156
+ ' <button @click="count++">{{ props.message }} ・ {{ count }} 回(×2 = {{ doubled }})</button>',
157
+ '</template>',
158
+ '',
159
+ '<style scoped lang="scss">',
160
+ '$green: #42b883;',
161
+ 'button { padding: 4px 12px; border-radius: 6px; background: $green; color: #fff; border: 2px solid; font-weight: 600; cursor: pointer; }',
162
+ '</style>',
163
+ '',
164
+ ].join('\n'),
165
+ 'src/desktop.scss': SCSS,
166
+ ...common,
167
+ },
168
+ };
@@ -0,0 +1,58 @@
1
+ // IDE が持つ状態。ファイルは path → text の Map(バイナリは "base64:...")
2
+ // レコードには、ソース一式を zip にして添付ファイルのフィールドに保存する。
3
+ import { F } from '../config.js';
4
+ import { zipSync, unzipSync } from 'fflate';
5
+ import { downloadFile } from '../kintone/api.js';
6
+ import { fromBytes, toBytes } from '../util/bytes.js';
7
+ import { normalize, isVendor } from '../util/path.js';
8
+
9
+ export async function readSources(record) {
10
+ const files = new Map(), dirs = new Set();
11
+ const f = record[F.source]?.value?.[0];
12
+ if (f) {
13
+ const entries = unzipSync(await downloadFile(f.fileKey));
14
+ for (const [raw, bytes] of Object.entries(entries)) {
15
+ const p = normalize(raw);
16
+ if (!p || isVendor(p)) continue;
17
+ if (raw.endsWith('/')) dirs.add(p); else files.set(p, fromBytes(bytes));
18
+ }
19
+ return { files, dirs, from: 'zip', name: f.name };
20
+ }
21
+ // 前の版(サブテーブル)からの引っ越し
22
+ const L = F.legacy;
23
+ for (const row of record[L?.files]?.value || []) {
24
+ const raw = row.value[L.path].value || '';
25
+ const p = normalize(raw);
26
+ if (!p || isVendor(p)) continue;
27
+ if (raw.endsWith('/')) dirs.add(p); else files.set(p, row.value[L.content].value || '');
28
+ }
29
+ return { files, dirs, from: files.size || dirs.size ? 'legacy' : 'empty' };
30
+ }
31
+
32
+ export function createState({ files: loaded, dirs: loadedDirs, from }) {
33
+ const files = new Map(loaded); // 今の内容(node_modules も含む)
34
+ const saved = from === 'legacy' ? new Map() : new Map(loaded); // 引っ越し前は「全部未保存」扱いにして、保存で zip に移す
35
+ const dirs = new Set(loadedDirs); // 空でも残すフォルダ(zip には "foo/" として入れる)
36
+ const savedDirs = new Set(from === 'legacy' ? [] : loadedDirs);
37
+ const sourcePaths = () => [...files.keys()].filter((p) => !isVendor(p));
38
+ const dirty = () => {
39
+ const changed = sourcePaths().filter((p) => files.get(p) !== saved.get(p));
40
+ const removed = [...saved.keys()].filter((p) => !files.has(p));
41
+ const dirChanged = [...dirs].filter((d) => !savedDirs.has(d)).concat([...savedDirs].filter((d) => !dirs.has(d))).map((d) => d + '/');
42
+ return changed.concat(removed, dirChanged);
43
+ };
44
+ // 中にファイルがあるフォルダは、わざわざ覚えておかなくていい
45
+ const pruneDirs = () => { for (const d of dirs) if ([...files.keys()].some((f) => f.startsWith(d + '/'))) dirs.delete(d); };
46
+ async function toZip() {
47
+ pruneDirs();
48
+ const entries = {};
49
+ for (const p of sourcePaths().sort()) entries[p] = toBytes(files.get(p));
50
+ for (const d of dirs) entries[d + '/'] = new Uint8Array(0);
51
+ return zipSync(entries, { level: 9 });
52
+ }
53
+ const markSaved = () => {
54
+ saved.clear(); for (const p of sourcePaths()) saved.set(p, files.get(p));
55
+ savedDirs.clear(); for (const d of dirs) savedDirs.add(d);
56
+ };
57
+ return { files, saved, dirs, from, sourcePaths, dirty, toZip, markSaved, pruneDirs };
58
+ }
@@ -0,0 +1,57 @@
1
+ // ターミナル(xterm + xterm-readline)。ログの出力先でもある
2
+ import { loadXterm } from '../deps.js';
3
+ import { el } from '../util/dom.js';
4
+ import { normalize } from '../util/path.js';
5
+
6
+ const COLOR = { info: '\x1b[90m', ok: '\x1b[32m', warn: '\x1b[33m', error: '\x1b[31m', plain: '' };
7
+
8
+ export async function setupTerminal(ctx) {
9
+ const { ui } = ctx;
10
+ const { Terminal, FitAddon, Readline, css } = await loadXterm();
11
+ if (!document.getElementById('kpi-xterm-css')) document.head.append(el('link', { id: 'kpi-xterm-css', rel: 'stylesheet', href: css }));
12
+ const term = new Terminal({
13
+ fontSize: 12, fontFamily: 'ui-monospace,SFMono-Regular,Menlo,Consolas,monospace', cursorBlink: true, convertEol: true, scrollback: 5000,
14
+ theme: { background: '#0e0e0e', foreground: '#dddddd', cursor: '#68d391', selectionBackground: '#2b6cb055' },
15
+ });
16
+ const fit = new FitAddon();
17
+ const rl = new Readline();
18
+ term.loadAddon(fit); term.loadAddon(rl);
19
+ term.open(ui.termEl);
20
+ const ro = new ResizeObserver(() => { try { fit.fit(); } catch {} });
21
+ ro.observe(ui.termEl);
22
+
23
+ // "src/foo.ts:12:3" をクリックするとエディタのその行に飛ぶ / "/k/12/" はアプリを開く
24
+ term.registerLinkProvider({
25
+ provideLinks(y, cb) {
26
+ const text = term.buffer.active.getLine(y - 1)?.translateToString(true) || '';
27
+ const links = [];
28
+ for (const m of text.matchAll(/([\w./@-]+\.(?:tsx?|mts|jsx?|mjs|json|css|html|md)):(\d+)(?::(\d+))?|(\/k\/\d+\/)/g)) {
29
+ const x = [...text.slice(0, m.index)].reduce((w, ch) => w + (ch.charCodeAt(0) > 0x2e80 ? 2 : 1), 0) + 1;
30
+ links.push({
31
+ range: { start: { x, y }, end: { x: x + [...m[0]].length - 1, y } }, text: m[0],
32
+ activate: () => (m[4] ? window.open(m[4], '_blank') : ctx.openFile(normalize(m[1]), +m[2], +(m[3] || 1))),
33
+ });
34
+ }
35
+ cb(links);
36
+ },
37
+ });
38
+
39
+ const log = ctx.log;
40
+ for (const level of Object.keys(COLOR)) {
41
+ log[level] = (text) => {
42
+ const time = `\x1b[2m${new Date().toLocaleTimeString()}\x1b[0m `;
43
+ rl.println(`${level === 'plain' ? '' : time}${COLOR[level]}${text}\x1b[0m`);
44
+ };
45
+ }
46
+
47
+ let alive = true;
48
+ const startRepl = () => (async () => {
49
+ while (alive) {
50
+ const line = await rl.read('\x1b[32m$\x1b[0m ');
51
+ if (!alive) break;
52
+ await ctx.run(() => ctx.command(line));
53
+ }
54
+ })();
55
+ const disposeTerminal = () => { alive = false; ro.disconnect(); term.dispose(); };
56
+ Object.assign(ctx, { term, rl, startRepl, disposeTerminal });
57
+ }