princess-python-editor 0.1.0 → 0.1.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.
- package/README.html +1013 -0
- package/README.md +142 -35
- package/dist/PythonEditor.vue.d.ts +27 -0
- package/dist/index.cjs.js +131 -5
- package/dist/index.d.ts +10 -1
- package/dist/index.es.js +1053 -591
- package/dist/runtime/PyodideRunner.d.ts +9 -1
- package/dist/runtime/usePyodide.d.ts +9 -2
- package/dist/style.css +1 -1
- package/dist/types.d.ts +41 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -12,7 +12,11 @@ Vue 3 + TypeScript 的 Python 代码编辑器组件:基于 CodeMirror 6 的编
|
|
|
12
12
|
- **实时语法检查**:停止输入后自动检查 Python 语法,可配置防抖时间或关闭
|
|
13
13
|
- **多文件 Tab**:新建、打开本地文件、下载、复制、清空、切换、关闭,文件名可编辑
|
|
14
14
|
- **多语言编辑**:Python、SQL、JavaScript、JSON 的语法高亮与补全
|
|
15
|
-
- **输出面板**:stdout / stderr
|
|
15
|
+
- **输出面板**:stdout / stderr 分色展示,运行时异常输出完整 traceback,自动滚动,可清空
|
|
16
|
+
- **预置输入**:通过 `stdin` 属性按行提供 `input()` 数据
|
|
17
|
+
- **虚拟文件系统**:运行前自动同步 Python Tab,可在代码中 `import` 其他 Tab;内置虚拟文件面板可下载 Python 生成的文件
|
|
18
|
+
- **草稿持久化**:传入 `storage-key` 后自动把全部 Tab 与当前选中项保存到 localStorage,刷新页面不丢失
|
|
19
|
+
- **预置包**:通过 `preload-packages` 在 Pyodide 就绪后自动安装常用包(如 `sqlite3`)
|
|
16
20
|
- **主题与只读**:浅色 / 深色主题,只读模式,工具栏与输出面板均可按需显示
|
|
17
21
|
- **第三方包安装**:优先使用 Pyodide 内置 wheel,缺失时回退 micropip
|
|
18
22
|
- **可中断执行**:运行长时间计算时可停止,Worker 自动重建
|
|
@@ -116,6 +120,10 @@ function onRunError(error: PyError) {
|
|
|
116
120
|
| `pyodideUrl` | `string` | 见下文 | 自定义 Pyodide `indexURL`,必须以 `/` 结尾 |
|
|
117
121
|
| `fileName` | `string` | `'main.py'` | 初始文件名,支持 `v-model:file-name` |
|
|
118
122
|
| `language` | `EditorLanguage` | `'python'` | 初始语法类型,支持 `v-model:language` |
|
|
123
|
+
| `stdin` | `string` | `''` | 按行提供给 `input()` / `sys.stdin` 的预置输入 |
|
|
124
|
+
| `syncFilesOnRun` | `boolean` | `true` | 运行前把 Python Tab 写入虚拟文件系统,便于跨文件 import |
|
|
125
|
+
| `storageKey` | `string` | `''` | localStorage key;非空时启用草稿持久化 |
|
|
126
|
+
| `preloadPackages` | `string[]` | `[]` | Pyodide 就绪后自动安装的包;非空时挂载后自动加载 Pyodide |
|
|
119
127
|
|
|
120
128
|
## 事件
|
|
121
129
|
|
|
@@ -134,6 +142,7 @@ function onRunError(error: PyError) {
|
|
|
134
142
|
| `copy` | `string` | 复制代码成功 |
|
|
135
143
|
| `download` | `string` | 下载文件,参数为最终文件名 |
|
|
136
144
|
| `file-open` | `FileOpenEvent` | 打开本地文件 |
|
|
145
|
+
| `fs-download` | `FsDownloadEvent` | 下载虚拟文件系统中的文件 |
|
|
137
146
|
| `update:modelValue` | `string` | 代码内容变化 |
|
|
138
147
|
| `update:fileName` | `string` | 文件名变化 |
|
|
139
148
|
| `update:language` | `EditorLanguage` | 语法类型变化 |
|
|
@@ -162,26 +171,31 @@ async function runAndInstall() {
|
|
|
162
171
|
</template>
|
|
163
172
|
```
|
|
164
173
|
|
|
165
|
-
| 方法
|
|
166
|
-
|
|
|
167
|
-
| `run()`
|
|
168
|
-
| `stop()`
|
|
169
|
-
| `clearOutput()`
|
|
170
|
-
| `clearCode()`
|
|
171
|
-
| `newFile()`
|
|
172
|
-
| `switchFile(id)`
|
|
173
|
-
| `closeFile(id)`
|
|
174
|
-
| `copyCode()`
|
|
175
|
-
| `download()`
|
|
176
|
-
| `openFile()`
|
|
177
|
-
| `focus()`
|
|
178
|
-
| `install(packages)`
|
|
179
|
-
| `checkSyntax()`
|
|
180
|
-
| `getEditorView()`
|
|
181
|
-
| `getCode()`
|
|
182
|
-
| `setCode(code)`
|
|
183
|
-
| `getFiles()`
|
|
184
|
-
| `getActiveFile()`
|
|
174
|
+
| 方法 | 返回值 | 说明 |
|
|
175
|
+
| -------------------------- | ------------------------------ | ------------------------------------------------------ |
|
|
176
|
+
| `run()` | `void` | 运行当前 Python 文件 |
|
|
177
|
+
| `stop()` | `void` | 中断执行(终止并重建 Worker,Python 运行时状态会丢失) |
|
|
178
|
+
| `clearOutput()` | `void` | 清空输出面板 |
|
|
179
|
+
| `clearCode()` | `void` | 清空当前文件内容(保留输出) |
|
|
180
|
+
| `newFile()` | `void` | 新建文件并切换过去 |
|
|
181
|
+
| `switchFile(id)` | `void` | 切换到指定文件 |
|
|
182
|
+
| `closeFile(id)` | `void` | 关闭指定文件(至少保留一个) |
|
|
183
|
+
| `copyCode()` | `Promise<boolean>` | 复制当前代码到剪贴板 |
|
|
184
|
+
| `download()` | `string` | 下载当前文件,返回最终文件名 |
|
|
185
|
+
| `openFile()` | `void` | 打开本地文件选择框 |
|
|
186
|
+
| `focus()` | `void` | 聚焦编辑器 |
|
|
187
|
+
| `install(packages)` | `Promise<InstallResult>` | 安装第三方包 |
|
|
188
|
+
| `checkSyntax()` | `Promise<SyntaxIssue \| null>` | 检查当前内容语法,未就绪时返回 `null` |
|
|
189
|
+
| `getEditorView()` | `EditorView \| null` | 获取 CodeMirror `EditorView` 实例 |
|
|
190
|
+
| `getCode()` | `string` | 获取当前代码 |
|
|
191
|
+
| `setCode(code)` | `void` | 替换当前代码(保留撤销历史) |
|
|
192
|
+
| `getFiles()` | `EditorFile[]` | 获取全部文件快照 |
|
|
193
|
+
| `getActiveFile()` | `EditorFile` | 获取当前文件快照 |
|
|
194
|
+
| `writeFile(path, content)` | `Promise<FsWriteResult>` | 写入虚拟文件系统(UTF-8 文本) |
|
|
195
|
+
| `readFile(path)` | `Promise<FsReadResult>` | 读取虚拟文件系统中的文本文件 |
|
|
196
|
+
| `listFiles(path?)` | `Promise<FsListResult>` | 列出虚拟文件目录(递归,默认当前目录) |
|
|
197
|
+
| `downloadFile(path)` | `Promise<string \| null>` | 下载虚拟文件,返回下载使用的文件名 |
|
|
198
|
+
| `clearPersistedState()` | `void` | 清除 localStorage 中的本地草稿(保留当前编辑内容) |
|
|
185
199
|
|
|
186
200
|
## 语言与执行说明
|
|
187
201
|
|
|
@@ -189,6 +203,62 @@ async function runAndInstall() {
|
|
|
189
203
|
|
|
190
204
|
**只有 Python 文件可以执行。** 切换到 SQL / JavaScript / JSON 后,运行按钮会被禁用,`Ctrl+Enter` 也只会在输出面板提示“仅支持执行 Python 代码”。这些语言目前是纯编辑模式,不具备运行时。
|
|
191
205
|
|
|
206
|
+
## 文件与输入
|
|
207
|
+
|
|
208
|
+
### 虚拟文件系统
|
|
209
|
+
|
|
210
|
+
Python 运行在 Pyodide 的浏览器内存文件系统中,默认工作目录为 `/home/pyodide`:
|
|
211
|
+
|
|
212
|
+
- `open()`、`os`、`pathlib`、`csv`、`json`、`zipfile`、`tempfile` 等均可正常使用,支持文本与二进制读写。
|
|
213
|
+
- 运行前会自动把全部 Python Tab 写入虚拟文件系统(可用 `:sync-files-on-run="false"` 关闭)。因此 `main.py` 可以直接 `import utils`,只要 `utils.py` 是另一个 Python Tab。
|
|
214
|
+
- Python 会缓存已导入的模块。修改被导入的 Tab 后,需要在代码中 `importlib.reload(utils)`,或点击“停止”重建 Worker 后再运行。
|
|
215
|
+
- 同一 Worker 内,变量会在多次运行之间保留;点击“停止”、刷新页面或调用 `interrupt()` 后全部重置。
|
|
216
|
+
- 虚拟文件只存在于当前 Worker 内存中:点击“停止”、刷新页面或调用 `interrupt()` 后全部丢失。
|
|
217
|
+
- “打开本地文件”只是把文本载入编辑器 Tab,不会进入虚拟文件系统。需要预置数据文件时,使用实例方法 `writeFile(path, content)` 写入。
|
|
218
|
+
- Python 生成的文件可通过工具栏“虚拟文件”面板下载,也可以调用 `listFiles()`、`readFile()`、`downloadFile(path)` 自行处理。
|
|
219
|
+
- 面板下载仅支持 UTF-8 文本;二进制文件可以在 Python 内部读写,但无法通过面板下载。
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
await editorRef.value?.writeFile('data.csv', 'name,score\n张三,95\n')
|
|
223
|
+
const listed = await editorRef.value?.listFiles()
|
|
224
|
+
const read = await editorRef.value?.readFile('output.txt')
|
|
225
|
+
await editorRef.value?.downloadFile('output.txt')
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
### 交互输入 input()
|
|
229
|
+
|
|
230
|
+
通过 `stdin` 属性按行提供输入,`input()` 会依次读取;读取完毕后再次调用会抛出 `EOFError`:
|
|
231
|
+
|
|
232
|
+
```vue
|
|
233
|
+
<PythonEditor v-model="code" :stdin="'张三\n95'" />
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
```python
|
|
237
|
+
name = input('姓名:')
|
|
238
|
+
score = int(input('成绩:'))
|
|
239
|
+
print(name, score)
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
不支持运行中途暂停等待键盘输入。如果需要动态收集输入,请在每次运行前更新 `stdin`。
|
|
243
|
+
|
|
244
|
+
### 运行时异常
|
|
245
|
+
|
|
246
|
+
执行出错时,输出面板会展示完整 traceback,同时保持错误行高亮;宿主也可以通过 `run-error` 事件拿到 `PyError.traceback`。
|
|
247
|
+
|
|
248
|
+
## 草稿持久化
|
|
249
|
+
|
|
250
|
+
传入 `storageKey` 后,组件会把全部 Tab(文件名、语言、代码)和当前选中项保存到 localStorage,编辑后防抖 400ms 写入,组件卸载时再保存一次:
|
|
251
|
+
|
|
252
|
+
```vue
|
|
253
|
+
<PythonEditor v-model="code" storage-key="my-python-draft" />
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
- 挂载时若存在同 key 的草稿,会在创建编辑器前恢复,并通过 `update:modelValue`、`update:fileName`、`update:language` 同步给宿主。
|
|
257
|
+
- 存储结构带版本号;版本不兼容或内容损坏时自动忽略,不影响组件启动。
|
|
258
|
+
- 调用 `editorRef.value?.clearPersistedState()` 可清除草稿,仅删除存储,不改动当前编辑内容;之后继续编辑会重新写入。
|
|
259
|
+
- 不传 `storageKey` 时完全关闭该能力,不产生任何读写。
|
|
260
|
+
- 草稿只保存编辑内容,不包含虚拟文件系统与运行状态。
|
|
261
|
+
|
|
192
262
|
## Pyodide 配置
|
|
193
263
|
|
|
194
264
|
### 默认 CDN
|
|
@@ -218,6 +288,16 @@ const result = await editorRef.value?.install(['numpy', 'pandas'])
|
|
|
218
288
|
|
|
219
289
|
优先使用 Pyodide 内置 wheel,未内置的包会回退到 micropip 从 PyPI 下载。
|
|
220
290
|
|
|
291
|
+
### 预置包
|
|
292
|
+
|
|
293
|
+
`preloadPackages` 会在组件挂载后自动开始加载 Pyodide,就绪后安装指定包,安装日志输出到输出面板:
|
|
294
|
+
|
|
295
|
+
```vue
|
|
296
|
+
<PythonEditor v-model="code" :preload-packages="['sqlite3']" />
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
常用可预置的 Pyodide 内置包有 `sqlite3`、`numpy`、`pandas`、`matplotlib` 等。`sqlite3` 不会随 Pyodide 默认加载,必须安装后才能 `import sqlite3`。安装期间运行器状态为 `running`,运行按钮暂不可用;安装完成后即可正常导入。
|
|
300
|
+
|
|
221
301
|
### CSP 提示
|
|
222
302
|
|
|
223
303
|
组件通过 Blob URL 创建 Worker,并在 Worker 中加载 Pyodide。使用严格 CSP 时需要允许:
|
|
@@ -227,31 +307,53 @@ const result = await editorRef.value?.install(['numpy', 'pandas'])
|
|
|
227
307
|
|
|
228
308
|
## 无编辑器使用 Python
|
|
229
309
|
|
|
230
|
-
`usePyodide` 与编辑器共享同一个 Pyodide
|
|
310
|
+
`usePyodide` 与编辑器共享同一个 Pyodide 实例,支持 `pyodideUrl`、`preload` 与 `preloadPackages` 选项:
|
|
231
311
|
|
|
232
312
|
```ts
|
|
233
313
|
import { usePyodide } from 'princess-python-editor'
|
|
234
314
|
|
|
235
|
-
const {
|
|
236
|
-
|
|
315
|
+
const {
|
|
316
|
+
status,
|
|
317
|
+
version,
|
|
318
|
+
outputs,
|
|
319
|
+
runPython,
|
|
320
|
+
install,
|
|
321
|
+
checkSyntax,
|
|
322
|
+
interrupt,
|
|
323
|
+
clearOutputs,
|
|
324
|
+
writeFile,
|
|
325
|
+
readFile,
|
|
326
|
+
listFiles,
|
|
327
|
+
} = usePyodide({ preload: true })
|
|
237
328
|
|
|
238
329
|
const result = await runPython('print(1 + 1)')
|
|
239
330
|
console.log(result.ok, result.value, result.durationMs)
|
|
331
|
+
|
|
332
|
+
// 提供 input() 输入
|
|
333
|
+
await runPython('name = input()\nprint(name)', { stdin: '张三\n' })
|
|
334
|
+
|
|
335
|
+
// 虚拟文件系统
|
|
336
|
+
await writeFile('data.txt', 'hello')
|
|
337
|
+
const read = await readFile('data.txt')
|
|
338
|
+
const listed = await listFiles()
|
|
240
339
|
```
|
|
241
340
|
|
|
242
341
|
返回内容包括:
|
|
243
342
|
|
|
244
|
-
| 字段
|
|
245
|
-
|
|
|
246
|
-
| `status`
|
|
247
|
-
| `version`
|
|
248
|
-
| `outputs`
|
|
249
|
-
| `runPython(code)`
|
|
250
|
-
| `install(packages)`
|
|
251
|
-
| `checkSyntax(code)`
|
|
252
|
-
| `interrupt()`
|
|
253
|
-
| `clearOutputs()`
|
|
254
|
-
| `
|
|
343
|
+
| 字段 | 类型 | 说明 |
|
|
344
|
+
| --------------------------- | ------------------------------ | ---------------------------------- |
|
|
345
|
+
| `status` | `Ref<PyodideStatus>` | 运行器状态 |
|
|
346
|
+
| `version` | `Ref<string>` | Pyodide 版本 |
|
|
347
|
+
| `outputs` | `Ref<OutputLine[]>` | 输出行(失败时包含完整 traceback) |
|
|
348
|
+
| `runPython(code, options?)` | `Promise<RunResult>` | 执行代码,`options.stdin` 提供输入 |
|
|
349
|
+
| `install(packages)` | `Promise<InstallResult>` | 安装包 |
|
|
350
|
+
| `checkSyntax(code)` | `Promise<SyntaxIssue \| null>` | 语法检查 |
|
|
351
|
+
| `interrupt()` | `void` | 中断执行 |
|
|
352
|
+
| `clearOutputs()` | `void` | 清空输出 |
|
|
353
|
+
| `writeFile(path, content)` | `Promise<FsWriteResult>` | 写入虚拟文件系统 |
|
|
354
|
+
| `readFile(path)` | `Promise<FsReadResult>` | 读取虚拟文件 |
|
|
355
|
+
| `listFiles(path?)` | `Promise<FsListResult>` | 列出虚拟文件目录 |
|
|
356
|
+
| `ready()` | `Promise<void>` | 等待就绪 |
|
|
255
357
|
|
|
256
358
|
## 主题定制
|
|
257
359
|
|
|
@@ -285,6 +387,11 @@ import type {
|
|
|
285
387
|
InstallResult,
|
|
286
388
|
RunOutputEvent,
|
|
287
389
|
FileOpenEvent,
|
|
390
|
+
FsEntry,
|
|
391
|
+
FsWriteResult,
|
|
392
|
+
FsReadResult,
|
|
393
|
+
FsListResult,
|
|
394
|
+
FsDownloadEvent,
|
|
288
395
|
PythonEditorProps,
|
|
289
396
|
} from 'princess-python-editor'
|
|
290
397
|
```
|
|
@@ -35,7 +35,17 @@ export interface Props {
|
|
|
35
35
|
fileName?: string;
|
|
36
36
|
/** 初始语法类型(支持 v-model:language) */
|
|
37
37
|
language?: EditorLanguage;
|
|
38
|
+
/** 提供给 input() / sys.stdin 的预置文本,按行切分;留空则读取时立即 EOF */
|
|
39
|
+
stdin?: string;
|
|
40
|
+
/** 运行前把 Python Tab 写入虚拟文件系统,便于跨文件 import;默认开启 */
|
|
41
|
+
syncFilesOnRun?: boolean;
|
|
42
|
+
/** 非空时启用草稿持久化(localStorage key),保存全部 Tab 与当前选中项 */
|
|
43
|
+
storageKey?: string;
|
|
44
|
+
/** Pyodide 就绪后自动安装的包列表;非空时挂载后自动开始加载 Pyodide */
|
|
45
|
+
preloadPackages?: string[];
|
|
38
46
|
}
|
|
47
|
+
/** 清除本地草稿(不影响当前编辑内容) */
|
|
48
|
+
declare function clearPersistedState(): void;
|
|
39
49
|
/** 读取当前编辑器内容 */
|
|
40
50
|
declare function getCode(): string;
|
|
41
51
|
/** 替换编辑器内容(保留撤销历史) */
|
|
@@ -58,6 +68,14 @@ declare function clearCode(): void;
|
|
|
58
68
|
declare function copyCode(): Promise<boolean>;
|
|
59
69
|
/** 下载当前文件 */
|
|
60
70
|
declare function download(): string;
|
|
71
|
+
/** 下载虚拟文件系统中的文本文件,返回下载文件名 */
|
|
72
|
+
declare function downloadFile(path: string): Promise<string | null>;
|
|
73
|
+
/** 写入虚拟文件系统(供宿主预置数据文件) */
|
|
74
|
+
declare function writeFile(path: string, content: string): Promise<import('./types').FsWriteResult>;
|
|
75
|
+
/** 读取虚拟文件系统中的文本文件 */
|
|
76
|
+
declare function readFile(path: string): Promise<import('./types').FsReadResult>;
|
|
77
|
+
/** 列出虚拟文件系统目录 */
|
|
78
|
+
declare function listFiles(path?: string): Promise<import('./types').FsListResult>;
|
|
61
79
|
/** 打开本地文件选择框 */
|
|
62
80
|
declare function openFile(): void;
|
|
63
81
|
/** 聚焦编辑器 */
|
|
@@ -97,6 +115,11 @@ declare const _default: import('vue').DefineComponent<Props, {
|
|
|
97
115
|
setCode: typeof setCode;
|
|
98
116
|
getFiles: typeof getFiles;
|
|
99
117
|
getActiveFile: typeof getActiveFile;
|
|
118
|
+
writeFile: typeof writeFile;
|
|
119
|
+
readFile: typeof readFile;
|
|
120
|
+
listFiles: typeof listFiles;
|
|
121
|
+
downloadFile: typeof downloadFile;
|
|
122
|
+
clearPersistedState: typeof clearPersistedState;
|
|
100
123
|
}, {}, {}, {}, import('vue').ComponentOptionsMixin, import('vue').ComponentOptionsMixin, {
|
|
101
124
|
[x: string]: any;
|
|
102
125
|
} & {
|
|
@@ -105,6 +128,7 @@ declare const _default: import('vue').DefineComponent<Props, {
|
|
|
105
128
|
[x: `on${Capitalize<any>}`]: ((...args: any) => any) | undefined;
|
|
106
129
|
}>, {
|
|
107
130
|
height: number | string;
|
|
131
|
+
stdin: string;
|
|
108
132
|
pyodideUrl: string;
|
|
109
133
|
modelValue: string;
|
|
110
134
|
theme: "light" | "dark";
|
|
@@ -121,6 +145,9 @@ declare const _default: import('vue').DefineComponent<Props, {
|
|
|
121
145
|
preload: boolean;
|
|
122
146
|
fileName: string;
|
|
123
147
|
language: EditorLanguage;
|
|
148
|
+
syncFilesOnRun: boolean;
|
|
149
|
+
storageKey: string;
|
|
150
|
+
preloadPackages: string[];
|
|
124
151
|
}, {}, {}, {}, string, import('vue').ComponentProvideOptions, false, {
|
|
125
152
|
tabsEl: HTMLDivElement;
|
|
126
153
|
fileInputEl: HTMLInputElement;
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
var INDEX_URL = ${JSON.stringify(
|
|
3
|
-
var CHECK_SOURCE = ${JSON.stringify(
|
|
1
|
+
"use strict";var xt=Object.defineProperty;var Ft=(u,a,o)=>a in u?xt(u,a,{enumerable:!0,configurable:!0,writable:!0,value:o}):u[a]=o;var N=(u,a,o)=>Ft(u,typeof a!="symbol"?a+"":a,o);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const t=require("vue"),B=require("@codemirror/state"),k=require("@codemirror/view"),fe=require("@codemirror/theme-one-dark"),_e=require("@codemirror/lint"),ce=require("@codemirror/autocomplete"),ee=require("@codemirror/commands"),Ie=require("@codemirror/language"),je=require("@codemirror/lang-python"),Nt=require("@codemirror/lang-javascript"),Ct=require("@codemirror/lang-json"),Vt=require("@codemirror/lang-sql"),Ue="'JetBrains Mono', 'Fira Code', 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace",me=B.StateEffect.define();function Pt(u,a){const o=u.filter(i=>Number.isFinite(i)&&i>=1&&i<=a.lines).sort((i,s)=>i-s);return k.Decoration.set(o.map(i=>k.Decoration.line({class:"vpe-error-line"}).range(a.line(i).from)))}const Ot=B.StateField.define({create:()=>k.Decoration.none,update:(u,a)=>{let o=u;for(const i of a.effects)i.is(me)&&(o=Pt(i.value,a.state.doc));return a.docChanged&&(o=o.map(a.changes)),o},provide:u=>k.EditorView.decorations.from(u)}),Bt=k.EditorView.theme({"&":{height:"100%",fontSize:"13px"},".cm-scroller":{fontFamily:Ue,lineHeight:"1.65"},".cm-content":{padding:"10px 0 14px"},".cm-gutters":{borderRight:"none",backgroundColor:"transparent",paddingLeft:"2px",opacity:"0.8"},"&.cm-focused":{outline:"none"}});function qe(u,a){const o=k.EditorView.updateListener.of(S=>{S.docChanged&&a.onDocChange(S.state.doc.toString())}),i=k.keymap.of([{key:"Mod-Enter",preventDefault:!0,run:()=>(a.onRunShortcut(),!0)}]),s=B.EditorState.create({doc:a.value,extensions:[Bt,k.lineNumbers(),k.highlightActiveLineGutter(),k.highlightActiveLine(),k.drawSelection(),ee.history(),Ie.indentUnit.of(" "),a.language??je.python(),ce.autocompletion(),ce.closeBrackets(),Ie.bracketMatching(),k.EditorView.lineWrapping,k.placeholder(a.placeholderText),Ot,i,k.keymap.of([...ce.closeBracketsKeymap,...ee.defaultKeymap,...ee.historyKeymap,ee.indentWithTab]),...a.dark?[fe.oneDark]:[],...a.extensions,o]});return new k.EditorView({state:s,parent:u})}function ze(u,a=600){return _e.linter(async o=>{const i=o.state.doc.toString();if(!i.trim())return[];let s=null;try{s=await u.checkSyntax(i)}catch{return[]}if(!s)return[];const S=Math.min(Math.max(Math.round(s.line)||1,1),o.state.doc.lines),b=o.state.doc.line(S),C=Math.min(Math.max(Math.round(s.column)||1,1),b.length+1),O=b.from+C-1,x=Math.min(O+1,b.to);return[{from:O,to:x,severity:"error",message:s.message,source:"python-syntax"}]},{delay:a})}const Lt=["import ast, json","def _pye_check(src):"," try:"," ast.parse(src)"," return json.dumps({'ok': True})"," except SyntaxError as e:"," return json.dumps({'ok': False, 'line': int(e.lineno or 1), 'column': int(e.offset or 1), 'message': str(e.msg or 'invalid syntax')})"];function $t(u){const a=u.endsWith("/")?u:u+"/";return`
|
|
2
|
+
var INDEX_URL = ${JSON.stringify(a)};
|
|
3
|
+
var CHECK_SOURCE = ${JSON.stringify(Lt.join(`
|
|
4
4
|
`))};
|
|
5
5
|
var pyodide = null;
|
|
6
6
|
var checkFn = null;
|
|
@@ -22,6 +22,85 @@ function parseError(e) {
|
|
|
22
22
|
return { type: type, message: detail, line: line, traceback: msg };
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
function fsError(e) {
|
|
26
|
+
return {
|
|
27
|
+
type: String((e && e.name) || 'OSError'),
|
|
28
|
+
message: String((e && e.message) || e),
|
|
29
|
+
traceback: ''
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 将相对路径解析为虚拟文件系统中的绝对路径(默认基于 /home/pyodide) */
|
|
34
|
+
function normPath(p) {
|
|
35
|
+
var raw = String(p == null ? '' : p);
|
|
36
|
+
if (!raw) return pyodide.FS.cwd();
|
|
37
|
+
var full = raw.charAt(0) === '/' ? raw : pyodide.FS.cwd() + '/' + raw;
|
|
38
|
+
var parts = full.split('/');
|
|
39
|
+
var out = [];
|
|
40
|
+
for (var i = 0; i < parts.length; i++) {
|
|
41
|
+
var seg = parts[i];
|
|
42
|
+
if (!seg || seg === '.') continue;
|
|
43
|
+
if (seg === '..') {
|
|
44
|
+
if (out.length) out.pop();
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
out.push(seg);
|
|
48
|
+
}
|
|
49
|
+
return '/' + out.join('/');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 将预置文本按行切分,逐行提供给 input();text 为 null 时立即 EOF */
|
|
53
|
+
function makeStdin(text) {
|
|
54
|
+
var lines = null;
|
|
55
|
+
if (text !== undefined && text !== null) {
|
|
56
|
+
lines = String(text).split(/\\r\\n|\\n|\\r/);
|
|
57
|
+
if (lines.length && lines[lines.length - 1] === '') lines.pop();
|
|
58
|
+
}
|
|
59
|
+
var index = 0;
|
|
60
|
+
return function () {
|
|
61
|
+
if (!lines || index >= lines.length) return null;
|
|
62
|
+
var line = lines[index];
|
|
63
|
+
index += 1;
|
|
64
|
+
return line + '\\n';
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 递归列出虚拟文件;跳过缓存目录并限制深度与条目数,避免大目录阻塞 */
|
|
69
|
+
function listFs(path, recursive) {
|
|
70
|
+
var entries = [];
|
|
71
|
+
function walk(dir, depth) {
|
|
72
|
+
var names = pyodide.FS.readdir(dir);
|
|
73
|
+
for (var i = 0; i < names.length; i++) {
|
|
74
|
+
var name = names[i];
|
|
75
|
+
if (name === '.' || name === '..') continue;
|
|
76
|
+
if (name === '__pycache__' || name === '.cache') continue;
|
|
77
|
+
var full = dir === '/' ? '/' + name : dir + '/' + name;
|
|
78
|
+
var stat;
|
|
79
|
+
try {
|
|
80
|
+
stat = pyodide.FS.stat(full);
|
|
81
|
+
} catch (e) {
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
var isDir = pyodide.FS.isDir(stat.mode);
|
|
85
|
+
entries.push({
|
|
86
|
+
name: name,
|
|
87
|
+
path: full,
|
|
88
|
+
isDirectory: isDir,
|
|
89
|
+
size: isDir ? 0 : stat.size
|
|
90
|
+
});
|
|
91
|
+
if (isDir && recursive && depth < 4 && entries.length < 500) {
|
|
92
|
+
walk(full, depth + 1);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
walk(path, 0);
|
|
97
|
+
entries.sort(function (a, b) {
|
|
98
|
+
if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;
|
|
99
|
+
return a.path < b.path ? -1 : a.path > b.path ? 1 : 0;
|
|
100
|
+
});
|
|
101
|
+
return entries;
|
|
102
|
+
}
|
|
103
|
+
|
|
25
104
|
async function init() {
|
|
26
105
|
try {
|
|
27
106
|
self.importScripts(INDEX_URL + 'pyodide.js');
|
|
@@ -54,6 +133,7 @@ self.onmessage = async function (ev) {
|
|
|
54
133
|
return;
|
|
55
134
|
}
|
|
56
135
|
try {
|
|
136
|
+
pyodide.setStdin({ stdin: makeStdin(msg.stdin) });
|
|
57
137
|
var result = await pyodide.runPythonAsync(msg.code);
|
|
58
138
|
var value;
|
|
59
139
|
if (result !== undefined && result !== null) {
|
|
@@ -96,7 +176,53 @@ self.onmessage = async function (ev) {
|
|
|
96
176
|
}
|
|
97
177
|
}
|
|
98
178
|
currentId = 0;
|
|
179
|
+
|
|
180
|
+
} else if (msg.kind === 'fs-write') {
|
|
181
|
+
if (!pyodide) {
|
|
182
|
+
post({ kind: 'fs-written', id: msg.id, ok: false, error: { type: 'RuntimeError', message: 'Pyodide 未初始化', traceback: '' } });
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
try {
|
|
186
|
+
var writePath = normPath(msg.path);
|
|
187
|
+
var slash = writePath.lastIndexOf('/');
|
|
188
|
+
var dir = slash <= 0 ? '/' : writePath.slice(0, slash);
|
|
189
|
+
try {
|
|
190
|
+
pyodide.FS.mkdirTree(dir);
|
|
191
|
+
} catch (e0) {
|
|
192
|
+
// 目录已存在时忽略
|
|
193
|
+
}
|
|
194
|
+
pyodide.FS.writeFile(writePath, String(msg.content == null ? '' : msg.content), { encoding: 'utf8' });
|
|
195
|
+
post({ kind: 'fs-written', id: msg.id, ok: true, path: writePath });
|
|
196
|
+
} catch (e) {
|
|
197
|
+
post({ kind: 'fs-written', id: msg.id, ok: false, error: fsError(e) });
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
} else if (msg.kind === 'fs-read') {
|
|
201
|
+
if (!pyodide) {
|
|
202
|
+
post({ kind: 'fs-read', id: msg.id, ok: false, error: { type: 'RuntimeError', message: 'Pyodide 未初始化', traceback: '' } });
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
try {
|
|
206
|
+
var readPath = normPath(msg.path);
|
|
207
|
+
var content = pyodide.FS.readFile(readPath, { encoding: 'utf8' });
|
|
208
|
+
post({ kind: 'fs-read', id: msg.id, ok: true, path: readPath, content: content });
|
|
209
|
+
} catch (e) {
|
|
210
|
+
post({ kind: 'fs-read', id: msg.id, ok: false, error: fsError(e) });
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
} else if (msg.kind === 'fs-list') {
|
|
214
|
+
if (!pyodide) {
|
|
215
|
+
post({ kind: 'fs-list', id: msg.id, ok: false, error: { type: 'RuntimeError', message: 'Pyodide 未初始化', traceback: '' } });
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
try {
|
|
219
|
+
var listPath = normPath(msg.path);
|
|
220
|
+
var entries = listFs(listPath, msg.recursive !== false);
|
|
221
|
+
post({ kind: 'fs-list', id: msg.id, ok: true, path: listPath, entries: entries });
|
|
222
|
+
} catch (e) {
|
|
223
|
+
post({ kind: 'fs-list', id: msg.id, ok: false, error: fsError(e) });
|
|
224
|
+
}
|
|
99
225
|
}
|
|
100
226
|
};
|
|
101
|
-
`}const re="https://cdn.jsdelivr.net/pyodide/v0.27.2/full/";class Ve{constructor(r={}){x(this,"status","idle");x(this,"version","");x(this,"pyodideUrl");x(this,"worker",null);x(this,"pending",new Map);x(this,"seq",1);x(this,"chain",Promise.resolve());x(this,"generation",0);x(this,"statusHandlers",new Set);x(this,"outputHandlers",new Set);x(this,"initErrorHandlers",new Set);this.pyodideUrl=r.pyodideUrl||re}on(r,o){if(r==="status"){const s=o;return this.statusHandlers.add(s),()=>this.statusHandlers.delete(s)}if(r==="output"){const s=o;return this.outputHandlers.add(s),()=>this.outputHandlers.delete(s)}const i=o;return this.initErrorHandlers.add(i),()=>this.initErrorHandlers.delete(i)}waitReady(r=18e4){const o=this.generation;return this.ensureWorker(),this.status==="ready"||this.status==="running"?Promise.resolve():new Promise((i,s)=>{let k=()=>{},b=()=>{};const S=()=>{clearTimeout(O),k(),b()},O=setTimeout(()=>{S(),s(new Error("Pyodide 加载超时"))},r);k=this.on("status",E=>{if(this.generation!==o){S(),s(new Error("执行已被中断"));return}E==="ready"&&(S(),i())}),b=this.on("initError",E=>{S(),s(new Error(E))})})}async run(r,o){await this.waitReady();const i=performance.now();this.setStatus("running");const s=await this.send({kind:"run",id:this.seq++,code:r},o==null?void 0:o.onOutput);return this.status==="running"&&this.setStatus("ready"),{ok:s.ok,value:s.value,error:s.error,interrupted:s.interrupted,durationMs:performance.now()-i}}async checkSyntax(r){if(this.status!=="ready"||!r.trim())return null;const o=await this.send({kind:"check",id:this.seq++,code:r});return o.ok?null:{line:o.line??1,column:o.column??1,message:o.message??"语法错误"}}async loadPackages(r,o){await this.waitReady();const i=performance.now();this.setStatus("running");const s=await this.send({kind:"install",id:this.seq++,packages:r},o==null?void 0:o.onOutput);return this.status==="running"&&this.setStatus("ready"),{ok:s.ok,error:s.error,durationMs:performance.now()-i}}interrupt(){if(!this.worker)return;this.generation+=1,this.worker.terminate(),this.worker=null;const r={ok:!1,interrupted:!0,error:{type:"KeyboardInterrupt",message:"执行已被用户中断",traceback:""}};this.pending.forEach(o=>o.resolve(r)),this.pending.clear(),this.chain=Promise.resolve(),this.setStatus("idle")}ensureWorker(){if(this.worker)return this.worker;const r=new Blob([rt(this.pyodideUrl)],{type:"text/javascript"}),o=new Worker(URL.createObjectURL(r));return o.onmessage=i=>this.handleMessage(i.data),this.worker=o,this.setStatus("loading"),o}handleMessage(r){switch(r.kind){case"ready":this.version=r.version,this.setStatus("ready");break;case"init-error":this.setStatus("idle"),this.initErrorHandlers.forEach(o=>o(r.message));break;case"output":{const o=r.runId?this.pending.get(r.runId):void 0;o!=null&&o.onOutput?o.onOutput(r.stream,r.text):this.outputHandlers.forEach(i=>i(r.stream,r.text));break}case"result":{const o=this.pending.get(r.id);o&&(this.pending.delete(r.id),o.resolve({ok:r.ok,value:r.value,error:r.error}));break}case"checked":{const o=this.pending.get(r.id);o&&(this.pending.delete(r.id),o.resolve({ok:r.ok,line:r.line,column:r.column,message:r.message}));break}case"installed":{const o=this.pending.get(r.id);o&&(this.pending.delete(r.id),o.resolve({ok:r.ok,error:r.error}));break}}}send(r,o){const i=this.ensureWorker(),s=this.chain.then(()=>new Promise(k=>{this.pending.set(r.id,{resolve:k,onOutput:o}),i.postMessage(r)}));return this.chain=s.then(()=>{},()=>{}),s}setStatus(r){this.status!==r&&(this.status=r,this.statusHandlers.forEach(o=>o(r,this.version)))}}let Y=null;function ae(l){return Y?l!=null&&l.pyodideUrl&&l.pyodideUrl!==re&&console.warn("[princess-python-editor] Pyodide 运行器已初始化,后续传入的 pyodideUrl 将被忽略。"):Y=new Ve(l),Y}const te=[{value:"python",label:"Python",extension:"py"},{value:"sql",label:"SQL",extension:"sql"},{value:"javascript",label:"JavaScript",extension:"js"},{value:"json",label:"JSON",extension:"json"}];function z(l){return te.find(r=>r.value===l)??te[0]}function Q(l){switch(l){case"sql":return Ye.sql();case"javascript":return Ge.javascript();case"json":return Xe.json();case"python":default:return xe.python()}}function at(l){const r=l.lastIndexOf(".");if(r<0)return"python";switch(l.slice(r+1).toLowerCase()){case"sql":return"sql";case"js":case"mjs":case"cjs":case"jsx":case"ts":return"javascript";case"json":return"json";default:return"python"}}function C(l){const r=Array.isArray(l)?l:[l];return()=>e.h("svg",{viewBox:"0 0 24 24",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true"},r.map(o=>e.h("path",{d:o})))}const ot=C("M8 5.14v13.72a1 1 0 0 0 1.54.84l10.3-6.86a1 1 0 0 0 0-1.68L9.54 4.3A1 1 0 0 0 8 5.14Z"),it=C("M6 6h12v12H6Z"),Ee=C("M9 3h6a1 1 0 0 1 1 1v1h4a1 1 0 1 1 0 2h-1.06l-.87 12.13A2 2 0 0 1 16.08 21H7.92a2 2 0 0 1-1.99-1.87L5.06 7H4a1 1 0 0 1 0-2h4V4a1 1 0 0 1 1-1Zm1 2h4V5h-4v0Zm-2.92 2h9.84l-.85 12.07a.5.5 0 0 1-.5.43H7.93a.5.5 0 0 1-.5-.43Z"),st=C("M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 14h-3v3h-2v-3H8v-2h3v-3h2v3h3v2zm-3-7V3.5L18.5 9H13z"),lt=C("M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"),ut=C("M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z"),ct=C("M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"),dt=C("M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"),pt=C("M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"),ft=C("M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7A1 1 0 0 0 5.7 7.11L10.59 12 5.7 16.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 0 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4Z"),ht=C("M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6V5z"),mt={key:0,class:"vpe-toolbar"},yt=["title","disabled"],gt=["disabled"],vt=["disabled"],kt=["title","aria-label"],bt=["disabled"],Et={class:"vpe-file",title:"当前文件名(下载时使用)"},wt=["value","disabled"],xt=["value"],St=["aria-selected","data-file-id","title","onClick","onKeydown"],Ct={class:"vpe-tab-name"},Nt=["title","aria-label","disabled","onClick"],Vt=["disabled"],Ot={class:"vpe-output-head"},Lt={key:1,class:"vpe-empty"},Oe=e.defineComponent({__name:"PythonEditor",props:{modelValue:{default:""},theme:{default:"light"},height:{default:520},outputHeight:{default:180},placeholder:{default:""},readOnly:{type:Boolean,default:!1},autofocus:{type:Boolean,default:!1},showToolbar:{type:Boolean,default:!0},showTabs:{type:Boolean,default:!0},showOutput:{type:Boolean,default:!0},clearOutputOnRun:{type:Boolean,default:!0},lintDelay:{default:600},disableLint:{type:Boolean,default:!1},preload:{type:Boolean,default:!1},pyodideUrl:{default:""},fileName:{default:"main.py"},language:{default:"python"}},emits:["update:modelValue","ready","statusChange","runStart","runOutput","runError","runFinish","loadError","update:fileName","update:language","newFile","fileClose","fileSwitch","copy","download","fileOpen"],setup(l,{expose:r,emit:o}){const i=l,s=o,k=e.ref(),b=e.ref(),S=e.ref(),O=e.ref(),E=e.ref([]),N=e.ref("idle"),F=e.ref(!1);let d=null,oe=0,w=0,h=null,V=null,_;function A(t,n,a){return{id:++w,name:t,language:n,code:a}}const f=e.ref([A(i.fileName,i.language,i.modelValue)]),I=e.ref(f.value[0].id),p=e.computed(()=>f.value.find(t=>t.id===I.value)??f.value[0]),M=e.computed({get:()=>p.value.name,set:t=>{const n=p.value;n.name!==t&&(n.name=t,s("update:fileName",t))}}),ie=new B.Compartment,se=new B.Compartment,K=new B.Compartment,J=new B.Compartment,L=ae(i.pyodideUrl?{pyodideUrl:i.pyodideUrl}:void 0),Le=e.computed(()=>({height:typeof i.height=="number"?`${i.height}px`:i.height})),Be=e.computed(()=>typeof i.outputHeight=="number"?`${i.outputHeight}px`:i.outputHeight),Fe=e.computed(()=>({idle:"未加载",loading:"正在加载 Pyodide…",ready:"就绪",running:"运行中"})[N.value]);function P(t){return{...t}}function W(t,n){E.value.push({id:++oe,stream:t,text:n})}function y(t){W("system",t)}function R(t){if(!d)return;const n=t?[t]:[];d.dispatch({effects:ne.of(n)})}function Me(){const t=i.modelValue;if(d){t!==d.state.doc.toString()&&d.dispatch({changes:{from:0,to:d.state.doc.length,insert:t}});return}const n=p.value;n.code!==t&&(n.code=t)}function T(){return d?d.state.doc.toString():p.value.code}function Z(t){if(d){t!==d.state.doc.toString()&&d.dispatch({changes:{from:0,to:d.state.doc.length,insert:t}});return}const n=p.value;n.code=t,t!==i.modelValue&&s("update:modelValue",t)}function G(t){return i.disableLint||t!=="python"?[]:Ne(L,i.lintDelay)}function le(t){const n=p.value;if(n.language!==t){if(n.language=t,R(void 0),d==null||d.dispatch({effects:[K.reconfigure(Q(t)),J.reconfigure(G(t))]}),/^untitled(-\d+)?\.[^.]+$/.test(n.name)){const u=`${n.name.slice(0,n.name.lastIndexOf("."))}.${z(t).extension}`;f.value.some(c=>c.id!==n.id&&c.name===u)||(n.name=u,s("update:fileName",u))}s("update:language",t)}}function ue(t,n){const u=t.trim().replace(/[\\/:*?"<>|]+/g,"_").replace(/\.+$/,"")||"untitled";return/\.[^.\\/]+$/.test(u)?u:`${u}.${z(n).extension}`}function He(t){const n=z(t).extension,a=new Set(f.value.map(v=>v.name));let u=`untitled.${n}`,c=2;for(;a.has(u);)u=`untitled-${c}.${n}`,c+=1;return u}function Ie(t){if(!f.value.some(m=>m.name===t))return t;const n=t.lastIndexOf("."),a=n>0?t.slice(0,n):t,u=n>0?t.slice(n):"";let c=2,v=`${a}-${c}${u}`;for(;f.value.some(m=>m.name===v);)c+=1,v=`${a}-${c}${u}`;return v}let $=0;async function ce(){var c,v;if(N.value==="loading"||N.value==="running")return;const t=p.value.language;if(t!=="python"){y(`当前文件为 ${z(t).label},仅支持执行 Python 代码`);return}$+=1;const n=$,a=p.value.id;R(void 0),i.clearOutputOnRun&&(E.value=[]),y("开始执行"),s("runStart");const u=T();try{const m=await L.run(u,{onOutput:(j,D)=>{W(j,D),s("runOutput",{stream:j,text:D})}});if(n!==$)return;m.interrupted?y("执行已中断"):m.ok?y(`执行完成,耗时 ${(m.durationMs/1e3).toFixed(2)}s`):(y(`执行出错:${((c=m.error)==null?void 0:c.type)??"未知错误"}`),p.value.id===a&&R((v=m.error)==null?void 0:v.line),m.error&&s("runError",m.error)),s("runFinish",m)}catch(m){if(n!==$)return;const j=m instanceof Error?m.message:String(m);y(`执行失败:${j}`);const D={type:"RuntimeError",message:j,traceback:""};s("runError",D),s("runFinish",{ok:!1,durationMs:0,error:D})}}e.onMounted(()=>{const t=k.value;if(!t)return;const n=[ie.of(i.theme==="dark"?[ee.oneDark]:[]),se.of([B.EditorState.readOnly.of(i.readOnly),g.EditorView.editable.of(!i.readOnly)]),J.of(G(p.value.language))];try{d=Ce(t,{value:p.value.code,dark:i.theme==="dark",placeholderText:i.placeholder,language:K.of(Q(p.value.language)),extensions:n,onDocChange:a=>{p.value.code=a,a!==i.modelValue&&s("update:modelValue",a)},onRunShortcut:ce})}catch(a){const u=a instanceof Error?a.message:String(a);console.error("[princess-python-editor] 编辑器初始化失败",a),y(`编辑器初始化失败:${u}`),t.innerHTML="";const c=document.createElement("div");c.className="vpe-init-error",c.textContent=`编辑器初始化失败:${u}`,t.appendChild(c);return}i.autofocus&&d.focus(),h=L.on("status",(a,u)=>{N.value=a,a==="ready"&&(u&&y(`Pyodide ${u} 就绪`),s("ready"),d&&!i.disableLint&&p.value.language==="python"&&we.forceLinting(d)),s("statusChange",a)}),V=L.on("initError",a=>{y(`Pyodide 加载失败:${a}`),s("loadError",a)}),N.value=L.status,i.preload&&L.waitReady().catch(a=>y(a.message))}),e.onBeforeUnmount(()=>{h==null||h(),V==null||V(),window.clearTimeout(_),d==null||d.destroy(),d=null}),e.watch(()=>i.modelValue,()=>Me()),e.watch(()=>i.fileName,t=>{t&&t!==p.value.name&&(M.value=t)}),e.watch(()=>i.language,t=>{t!==p.value.language&&le(t)}),e.watch(()=>i.theme,t=>{d==null||d.dispatch({effects:ie.reconfigure(t==="dark"?[ee.oneDark]:[])})}),e.watch(()=>i.readOnly,t=>{d==null||d.dispatch({effects:se.reconfigure([B.EditorState.readOnly.of(t),g.EditorView.editable.of(!t)])})}),e.watch(()=>E.value.length,async()=>{await e.nextTick();const t=b.value;t&&(t.scrollTop=t.scrollHeight)});function de(){ce()}function pe(){N.value==="running"&&($+=1,L.interrupt(),y("执行已中断"))}function fe(){E.value=[]}function X(){if(i.readOnly)return;const t=p.value.language,n=A(He(t),t,"");f.value.push(n),H(n.id),s("newFile",P(n))}function H(t){if(t===I.value){U();return}const n=f.value.find(a=>a.id===t);n&&(I.value=t,me(n))}function he(t){if(f.value.length<=1)return;const n=f.value.findIndex(c=>c.id===t);if(n===-1)return;const a=f.value.splice(n,1)[0];if(!a||(s("fileClose",P(a)),t!==I.value))return;const u=f.value[Math.min(n,f.value.length-1)];u&&(I.value=u.id,me(u))}function me(t){R(void 0),Z(t.code),d==null||d.dispatch({effects:[K.reconfigure(Q(t.language)),J.reconfigure(G(t.language))]}),s("update:fileName",t.name),s("update:language",t.language),s("fileSwitch",P(t)),U()}function ye(){i.readOnly||(R(void 0),Z(""),U())}async function ge(){var a;const t=T();let n=!1;try{(a=navigator.clipboard)!=null&&a.writeText&&(await navigator.clipboard.writeText(t),n=!0)}catch{n=!1}return n||(n=Pe(t)),n?(F.value=!0,window.clearTimeout(_),_=window.setTimeout(()=>{F.value=!1},1600),s("copy",t),!0):(y("复制失败,请手动选择代码复制"),!1)}function Pe(t){const n=document.createElement("textarea");n.value=t,n.setAttribute("readonly",""),n.style.position="fixed",n.style.top="0",n.style.left="-9999px",n.style.opacity="0",document.body.appendChild(n),n.select(),n.setSelectionRange(0,n.value.length);let a=!1;try{a=document.execCommand("copy")}catch{a=!1}return n.remove(),a}function ve(){const t=p.value,n=ue(t.name,t.language);M.value=n;const a=new Blob([T()],{type:t.language==="python"?"text/x-python;charset=utf-8":"text/plain;charset=utf-8"}),u=URL.createObjectURL(a),c=document.createElement("a");return c.href=u,c.download=n,c.style.display="none",document.body.appendChild(c),c.click(),c.remove(),window.setTimeout(()=>URL.revokeObjectURL(u),1e3),s("download",n),n}function ke(){var t;(t=O.value)==null||t.click()}async function Re(t){var u;const n=t.target,a=(u=n.files)==null?void 0:u[0];if(n.value="",!!a){if(a.size>2*1024*1024){y(`文件过大:${(a.size/1024/1024).toFixed(1)} MB(最多 2 MB)`);return}try{const c=await a.text(),v=at(a.name),m=A(Ie(a.name),v,c);f.value.push(m),H(m.id),y(`已打开文件:${m.name}`),s("fileOpen",{name:m.name,code:c,language:v})}catch(c){const v=c instanceof Error?c.message:String(c);y(`读取文件失败:${v}`)}}}function Te(){M.value=ue(M.value,p.value.language)}function $e(t){t.key==="Enter"&&(t.preventDefault(),t.target.blur())}function je(t){le(t.target.value)}async function be(t){var n,a;await e.nextTick(),(a=(n=S.value)==null?void 0:n.querySelector(`[data-file-id="${t}"]`))==null||a.focus()}function De(t,n){if(t.target!==t.currentTarget)return;if(t.key==="Enter"||t.key===" "){t.preventDefault(),H(n.id),be(n.id);return}if(t.key!=="ArrowLeft"&&t.key!=="ArrowRight")return;t.preventDefault();const a=f.value.findIndex(v=>v.id===n.id);if(a<0)return;const u=t.key==="ArrowLeft"?-1:1,c=f.value[(a+u+f.value.length)%f.value.length];c&&(H(c.id),be(c.id))}function U(){d==null||d.focus()}async function Ue(t){var a;y(`正在安装:${t.join(", ")}`);let n;try{n=await L.loadPackages(t,{onOutput:(u,c)=>W(u,c)})}catch(u){const c=u instanceof Error?u.message:String(u);return y(`安装失败:${c}`),{ok:!1,durationMs:0,error:{type:"RuntimeError",message:c}}}return y(n.ok?"安装完成":`安装失败:${((a=n.error)==null?void 0:a.message)??"未知错误"}`),n}function qe(){return L.checkSyntax(T())}function ze(){return d}function _e(){return f.value.map(P)}function Ae(){return P(p.value)}return r({run:de,stop:pe,clearOutput:fe,clearCode:ye,newFile:X,switchFile:H,closeFile:he,copyCode:ge,download:ve,openFile:ke,focus:U,install:Ue,checkSyntax:qe,getEditorView:ze,getCode:T,setCode:Z,getFiles:_e,getActiveFile:Ae}),(t,n)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["vpe-root",{"vpe-dark":l.theme==="dark"}]),style:e.normalizeStyle(Le.value)},[l.showToolbar?(e.openBlock(),e.createElementBlock("div",mt,[N.value!=="running"?(e.openBlock(),e.createElementBlock("button",{key:0,class:"vpe-btn vpe-btn--primary",type:"button",title:p.value.language==="python"?"运行 (Ctrl+Enter)":"仅支持执行 Python 文件",disabled:N.value==="loading"||p.value.language!=="python",onClick:de},[e.createVNode(e.unref(ot)),n[1]||(n[1]=e.createElementVNode("span",null,"运行",-1))],8,yt)):(e.openBlock(),e.createElementBlock("button",{key:1,class:"vpe-btn vpe-btn--stop",type:"button",title:"中断执行",onClick:pe},[e.createVNode(e.unref(it)),n[2]||(n[2]=e.createElementVNode("span",null,"停止",-1))])),n[4]||(n[4]=e.createElementVNode("span",{class:"vpe-divider","aria-hidden":"true"},null,-1)),e.createElementVNode("button",{class:"vpe-btn",type:"button",title:"新建文件","aria-label":"新建文件",disabled:l.readOnly,onClick:X},[e.createVNode(e.unref(st))],8,gt),e.createElementVNode("button",{class:"vpe-btn",type:"button",title:"打开本地文件","aria-label":"打开本地文件",disabled:l.readOnly,onClick:ke},[e.createVNode(e.unref(lt))],8,vt),e.createElementVNode("button",{class:"vpe-btn",type:"button",title:"下载当前文件","aria-label":"下载当前文件",onClick:ve},[e.createVNode(e.unref(ct))]),e.createElementVNode("button",{class:e.normalizeClass(["vpe-btn",{"vpe-btn--copied":F.value}]),type:"button",title:F.value?"已复制":"复制代码","aria-label":F.value?"已复制":"复制代码",onClick:ge},[F.value?(e.openBlock(),e.createBlock(e.unref(pt),{key:0})):(e.openBlock(),e.createBlock(e.unref(dt),{key:1}))],10,kt),e.createElementVNode("button",{class:"vpe-btn",type:"button",title:"清空当前文件","aria-label":"清空当前文件",disabled:l.readOnly,onClick:ye},[e.createVNode(e.unref(Ee))],8,bt),n[5]||(n[5]=e.createElementVNode("span",{class:"vpe-divider","aria-hidden":"true"},null,-1)),e.createElementVNode("label",Et,[e.createVNode(e.unref(ut)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":n[0]||(n[0]=a=>M.value=a),class:"vpe-file-input",type:"text",spellcheck:"false","aria-label":"文件名",onBlur:Te,onKeydown:$e},null,544),[[e.vModelText,M.value]])]),n[6]||(n[6]=e.createElementVNode("span",{class:"vpe-spacer","aria-hidden":"true"},null,-1)),e.createElementVNode("span",{class:e.normalizeClass(["vpe-status",`vpe-status--${N.value}`])},[n[3]||(n[3]=e.createElementVNode("span",{class:"vpe-status-dot","aria-hidden":"true"},null,-1)),e.createElementVNode("span",null,e.toDisplayString(Fe.value),1)],2),e.createElementVNode("select",{class:"vpe-lang",value:p.value.language,title:"编辑器语言","aria-label":"编辑器语言",disabled:l.readOnly,onChange:je},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(te),a=>(e.openBlock(),e.createElementBlock("option",{key:a.value,value:a.value},e.toDisplayString(a.label),9,xt))),128))],40,wt)])):e.createCommentVNode("",!0),l.showTabs?(e.openBlock(),e.createElementBlock("div",{key:1,ref_key:"tabsEl",ref:S,class:"vpe-tabs",role:"tablist","aria-label":"文件"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(f.value,a=>(e.openBlock(),e.createElementBlock("div",{key:a.id,class:e.normalizeClass(["vpe-tab",{"vpe-tab--active":a.id===p.value.id}]),role:"tab",tabindex:"0","aria-selected":a.id===p.value.id,"data-file-id":a.id,title:a.name,onClick:u=>H(a.id),onKeydown:u=>De(u,a)},[e.createElementVNode("span",{class:e.normalizeClass(["vpe-tab-dot",`vpe-tab-dot--${a.language}`]),"aria-hidden":"true"},null,2),e.createElementVNode("span",Ct,e.toDisplayString(a.name),1),f.value.length>1?(e.openBlock(),e.createElementBlock("button",{key:0,class:"vpe-tab-close",type:"button",title:`关闭 ${a.name}`,"aria-label":`关闭 ${a.name}`,disabled:l.readOnly,onClick:e.withModifiers(u=>he(a.id),["stop"])},[e.createVNode(e.unref(ft))],8,Nt)):e.createCommentVNode("",!0)],42,St))),128)),e.createElementVNode("button",{class:"vpe-tabs-add",type:"button",title:"新建文件","aria-label":"新建文件",disabled:l.readOnly,onClick:X},[e.createVNode(e.unref(ht))],8,Vt)],512)):e.createCommentVNode("",!0),e.createElementVNode("input",{ref_key:"fileInputEl",ref:O,class:"vpe-file-hidden",type:"file",accept:".py,.pyw,.sql,.js,.mjs,.cjs,.jsx,.ts,.json,.txt,text/x-python,text/plain,application/json",onChange:Re},null,544),e.createElementVNode("div",{ref_key:"editorEl",ref:k,class:"vpe-editor"},null,512),l.showOutput?(e.openBlock(),e.createElementBlock("div",{key:2,class:"vpe-output",style:e.normalizeStyle({height:Be.value})},[e.createElementVNode("div",Ot,[n[7]||(n[7]=e.createElementVNode("span",null,"输出",-1)),e.createElementVNode("button",{class:"vpe-btn vpe-btn--sm",type:"button",title:"清空输出",onClick:fe},[e.createVNode(e.unref(Ee))])]),e.createElementVNode("pre",{ref_key:"outputEl",ref:b,class:"vpe-output-body"},[E.value.length?(e.openBlock(!0),e.createElementBlock(e.Fragment,{key:0},e.renderList(E.value,a=>(e.openBlock(),e.createElementBlock("span",{key:a.id,class:e.normalizeClass(["vpe-line",`vpe-line--${a.stream}`])},e.toDisplayString(a.text)+`
|
|
102
|
-
`,3))),128)):(
|
|
227
|
+
`}const he="https://cdn.jsdelivr.net/pyodide/v0.27.2/full/";class Ae{constructor(a={}){N(this,"status","idle");N(this,"version","");N(this,"pyodideUrl");N(this,"worker",null);N(this,"pending",new Map);N(this,"seq",1);N(this,"chain",Promise.resolve());N(this,"generation",0);N(this,"statusHandlers",new Set);N(this,"outputHandlers",new Set);N(this,"initErrorHandlers",new Set);this.pyodideUrl=a.pyodideUrl||he}on(a,o){if(a==="status"){const s=o;return this.statusHandlers.add(s),()=>this.statusHandlers.delete(s)}if(a==="output"){const s=o;return this.outputHandlers.add(s),()=>this.outputHandlers.delete(s)}const i=o;return this.initErrorHandlers.add(i),()=>this.initErrorHandlers.delete(i)}waitReady(a=18e4){const o=this.generation;return this.ensureWorker(),this.status==="ready"||this.status==="running"?Promise.resolve():new Promise((i,s)=>{let S=()=>{},b=()=>{};const C=()=>{clearTimeout(O),S(),b()},O=setTimeout(()=>{C(),s(new Error("Pyodide 加载超时"))},a);S=this.on("status",x=>{if(this.generation!==o){C(),s(new Error("执行已被中断"));return}x==="ready"&&(C(),i())}),b=this.on("initError",x=>{C(),s(new Error(x))})})}async run(a,o){await this.waitReady();const i=performance.now();this.setStatus("running");const s=await this.send({kind:"run",id:this.seq++,code:a,stdin:o==null?void 0:o.stdin},o==null?void 0:o.onOutput);return this.status==="running"&&this.setStatus("ready"),{ok:s.ok,value:s.value,error:s.error,interrupted:s.interrupted,durationMs:performance.now()-i}}async checkSyntax(a){if(this.status!=="ready"||!a.trim())return null;const o=await this.send({kind:"check",id:this.seq++,code:a});return o.ok?null:{line:o.line??1,column:o.column??1,message:o.message??"语法错误"}}async writeFile(a,o){await this.waitReady();const i=await this.send({kind:"fs-write",id:this.seq++,path:a,content:o});return{ok:i.ok,path:i.path,error:i.error}}async readFile(a){await this.waitReady();const o=await this.send({kind:"fs-read",id:this.seq++,path:a});return{ok:o.ok,path:o.path,content:o.content,error:o.error}}async listFiles(a="."){await this.waitReady();const o=await this.send({kind:"fs-list",id:this.seq++,path:a,recursive:!0});return{ok:o.ok,path:o.path,entries:o.entries,error:o.error}}async loadPackages(a,o){await this.waitReady();const i=performance.now();this.setStatus("running");const s=await this.send({kind:"install",id:this.seq++,packages:a},o==null?void 0:o.onOutput);return this.status==="running"&&this.setStatus("ready"),{ok:s.ok,error:s.error,durationMs:performance.now()-i}}interrupt(){if(!this.worker)return;this.generation+=1,this.worker.terminate(),this.worker=null;const a={ok:!1,interrupted:!0,error:{type:"KeyboardInterrupt",message:"执行已被用户中断",traceback:""}};this.pending.forEach(o=>o.resolve(a)),this.pending.clear(),this.chain=Promise.resolve(),this.setStatus("idle")}ensureWorker(){if(this.worker)return this.worker;const a=new Blob([$t(this.pyodideUrl)],{type:"text/javascript"}),o=new Worker(URL.createObjectURL(a));return o.onmessage=i=>this.handleMessage(i.data),this.worker=o,this.setStatus("loading"),o}handleMessage(a){switch(a.kind){case"ready":this.version=a.version,this.setStatus("ready");break;case"init-error":this.setStatus("idle"),this.initErrorHandlers.forEach(o=>o(a.message));break;case"output":{const o=a.runId?this.pending.get(a.runId):void 0;o!=null&&o.onOutput?o.onOutput(a.stream,a.text):this.outputHandlers.forEach(i=>i(a.stream,a.text));break}case"result":{const o=this.pending.get(a.id);o&&(this.pending.delete(a.id),o.resolve({ok:a.ok,value:a.value,error:a.error}));break}case"checked":{const o=this.pending.get(a.id);o&&(this.pending.delete(a.id),o.resolve({ok:a.ok,line:a.line,column:a.column,message:a.message}));break}case"installed":{const o=this.pending.get(a.id);o&&(this.pending.delete(a.id),o.resolve({ok:a.ok,error:a.error}));break}case"fs-written":{const o=this.pending.get(a.id);o&&(this.pending.delete(a.id),o.resolve({ok:a.ok,path:a.path,error:a.error}));break}case"fs-read":{const o=this.pending.get(a.id);o&&(this.pending.delete(a.id),o.resolve({ok:a.ok,path:a.path,content:a.content,error:a.error}));break}case"fs-list":{const o=this.pending.get(a.id);o&&(this.pending.delete(a.id),o.resolve({ok:a.ok,path:a.path,entries:a.entries,error:a.error}));break}}}send(a,o){const i=this.ensureWorker(),s=this.chain.then(()=>new Promise(S=>{this.pending.set(a.id,{resolve:S,onOutput:o}),i.postMessage(a)}));return this.chain=s.then(()=>{},()=>{}),s}setStatus(a){this.status!==a&&(this.status=a,this.statusHandlers.forEach(o=>o(a,this.version)))}}let ue=null;function ye(u){return ue?u!=null&&u.pyodideUrl&&u.pyodideUrl!==he&&console.warn("[princess-python-editor] Pyodide 运行器已初始化,后续传入的 pyodideUrl 将被忽略。"):ue=new Ae(u),ue}const ne=[{value:"python",label:"Python",extension:"py"},{value:"sql",label:"SQL",extension:"sql"},{value:"javascript",label:"JavaScript",extension:"js"},{value:"json",label:"JSON",extension:"json"}];function te(u){return ne.find(a=>a.value===u)??ne[0]}function de(u){switch(u){case"sql":return Vt.sql();case"javascript":return Nt.javascript();case"json":return Ct.json();case"python":default:return je.python()}}function Mt(u){const a=u.lastIndexOf(".");if(a<0)return"python";switch(u.slice(a+1).toLowerCase()){case"sql":return"sql";case"js":case"mjs":case"cjs":case"jsx":case"ts":return"javascript";case"json":return"json";default:return"python"}}function P(u){const a=Array.isArray(u)?u:[u];return()=>t.h("svg",{viewBox:"0 0 24 24",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true"},a.map(o=>t.h("path",{d:o})))}const It=P("M8 5.14v13.72a1 1 0 0 0 1.54.84l10.3-6.86a1 1 0 0 0 0-1.68L9.54 4.3A1 1 0 0 0 8 5.14Z"),Rt=P("M6 6h12v12H6Z"),Re=P("M9 3h6a1 1 0 0 1 1 1v1h4a1 1 0 1 1 0 2h-1.06l-.87 12.13A2 2 0 0 1 16.08 21H7.92a2 2 0 0 1-1.99-1.87L5.06 7H4a1 1 0 0 1 0-2h4V4a1 1 0 0 1 1-1Zm1 2h4V5h-4v0Zm-2.92 2h9.84l-.85 12.07a.5.5 0 0 1-.5.43H7.93a.5.5 0 0 1-.5-.43Z"),Dt=P("M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 14h-3v3h-2v-3H8v-2h3v-3h2v3h3v2zm-3-7V3.5L18.5 9H13z"),Tt=P("M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"),De=P("M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z"),Te=P("M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"),Ht=P("M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"),_t=P("M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"),He=P("M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7A1 1 0 0 0 5.7 7.11L10.59 12 5.7 16.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 0 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4Z"),jt=P("M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6V5z"),Ut={key:0,class:"vpe-toolbar"},qt=["title","disabled"],zt=["disabled"],At=["disabled"],Kt=["title","aria-label"],Jt=["disabled"],Wt={class:"vpe-file",title:"当前文件名(下载时使用)"},Zt=["value","disabled"],Gt=["value"],Xt=["aria-selected","data-file-id","title","onClick","onKeydown"],Yt={class:"vpe-tab-name"},Qt=["title","aria-label","disabled","onClick"],en=["disabled"],tn={class:"vpe-output-head"},nn={key:1,class:"vpe-empty"},rn={key:3,class:"vpe-fs-panel",role:"dialog","aria-label":"虚拟文件"},an={class:"vpe-fs-head"},on=["disabled"],sn={class:"vpe-fs-body"},ln={key:0,class:"vpe-fs-empty"},cn={key:0,class:"vpe-fs-empty"},un=["title"],dn={class:"vpe-fs-size"},pn=["title","aria-label","onClick"],pe=1,Ke=t.defineComponent({__name:"PythonEditor",props:{modelValue:{default:""},theme:{default:"light"},height:{default:520},outputHeight:{default:180},placeholder:{default:""},readOnly:{type:Boolean,default:!1},autofocus:{type:Boolean,default:!1},showToolbar:{type:Boolean,default:!0},showTabs:{type:Boolean,default:!0},showOutput:{type:Boolean,default:!0},clearOutputOnRun:{type:Boolean,default:!0},lintDelay:{default:600},disableLint:{type:Boolean,default:!1},preload:{type:Boolean,default:!1},pyodideUrl:{default:""},fileName:{default:"main.py"},language:{default:"python"},stdin:{default:""},syncFilesOnRun:{type:Boolean,default:!0},storageKey:{default:""},preloadPackages:{default:()=>[]}},emits:["update:modelValue","ready","statusChange","runStart","runOutput","runError","runFinish","loadError","update:fileName","update:language","newFile","fileClose","fileSwitch","copy","download","fileOpen","fsDownload"],setup(u,{expose:a,emit:o}){const i=u,s=o,S=t.ref(),b=t.ref(),C=t.ref(),O=t.ref(),x=t.ref([]),V=t.ref("idle"),L=t.ref(!1),R=t.ref(!1),$=t.ref(!1),M=t.ref([]);let _=!1,j,re=!1,X=!1,U=!1,l=null,m=0,w=0,F=null,D=null,q;function Y(e,n,r){return{id:++w,name:e,language:n,code:r}}const f=t.ref([Y(i.fileName,i.language,i.modelValue)]),I=t.ref(f.value[0].id),y=t.computed(()=>f.value.find(e=>e.id===I.value)??f.value[0]),T=t.computed({get:()=>y.value.name,set:e=>{const n=y.value;n.name!==e&&(n.name=e,s("update:fileName",e))}}),ge=new B.Compartment,ve=new B.Compartment,ae=new B.Compartment,oe=new B.Compartment,v=ye(i.pyodideUrl?{pyodideUrl:i.pyodideUrl}:void 0),Je=t.computed(()=>({height:typeof i.height=="number"?`${i.height}px`:i.height})),We=t.computed(()=>typeof i.outputHeight=="number"?`${i.outputHeight}px`:i.outputHeight),Ze=t.computed(()=>({idle:"未加载",loading:"正在加载 Pyodide…",ready:"就绪",running:"运行中"})[V.value]);function z(e){return{...e}}function A(e,n){x.value.push({id:++m,stream:e,text:n})}function p(e){A("system",e)}function Ge(e){return ne.some(n=>n.value===e)}function Xe(){if(!i.storageKey||typeof window>"u")return null;try{const e=window.localStorage.getItem(i.storageKey);if(!e)return null;const n=JSON.parse(e);if(n.version!==pe||!Array.isArray(n.files))return null;const r=[];for(const h of n.files){if(!h||typeof h.name!="string"||typeof h.code!="string"||!h.name.trim())continue;const g=Ge(h.language)?h.language:"python";r.push({name:h.name,language:g,code:h.code})}if(!r.length)return null;const c=typeof n.activeIndex=="number"?n.activeIndex:0,d=Math.min(Math.max(Math.trunc(c)||0,0),r.length-1);return{version:pe,files:r,activeIndex:d}}catch{return null}}function Ye(){const e=Xe();if(!e)return;f.value=e.files.map(r=>Y(r.name,r.language,r.code));const n=f.value[e.activeIndex]??f.value[0];I.value=n.id,p(`已恢复上次编辑内容(${f.value.length} 个文件)`),s("update:modelValue",n.code),s("update:fileName",n.name),s("update:language",n.language)}function ke(){if(!(!_||X||!i.storageKey||typeof window>"u"))try{const e={version:pe,files:f.value.map(n=>({name:n.name,language:n.language,code:n.code})),activeIndex:Math.max(f.value.findIndex(n=>n.id===I.value),0)};window.localStorage.setItem(i.storageKey,JSON.stringify(e))}catch(e){re||(re=!0,p(`本地草稿保存失败:${e instanceof Error?e.message:String(e)}`))}}function Qe(){!_||!i.storageKey||typeof window>"u"||(X=!1,window.clearTimeout(j),j=window.setTimeout(ke,400))}function et(){if(!(!i.storageKey||typeof window>"u")){window.clearTimeout(j);try{window.localStorage.removeItem(i.storageKey),X=!0,p("已清除本地草稿")}catch(e){p(`清除本地草稿失败:${e instanceof Error?e.message:String(e)}`)}}}function K(e){if(!l)return;const n=e?[e]:[];l.dispatch({effects:me.of(n)})}function tt(){const e=i.modelValue;if(l){e!==l.state.doc.toString()&&l.dispatch({changes:{from:0,to:l.state.doc.length,insert:e}});return}const n=y.value;n.code!==e&&(n.code=e)}function J(){return l?l.state.doc.toString():y.value.code}function ie(e){if(l){e!==l.state.doc.toString()&&l.dispatch({changes:{from:0,to:l.state.doc.length,insert:e}});return}const n=y.value;n.code=e,e!==i.modelValue&&s("update:modelValue",e)}function se(e){return i.disableLint||e!=="python"?[]:ze(v,i.lintDelay)}function be(e){const n=y.value;if(n.language!==e){if(n.language=e,K(void 0),l==null||l.dispatch({effects:[ae.reconfigure(de(e)),oe.reconfigure(se(e))]}),/^untitled(-\d+)?\.[^.]+$/.test(n.name)){const c=`${n.name.slice(0,n.name.lastIndexOf("."))}.${te(e).extension}`;f.value.some(d=>d.id!==n.id&&d.name===c)||(n.name=c,s("update:fileName",c))}s("update:language",e)}}function we(e,n){const c=e.trim().replace(/[\\/:*?"<>|]+/g,"_").replace(/\.+$/,"")||"untitled";return/\.[^.\\/]+$/.test(c)?c:`${c}.${te(n).extension}`}function nt(e){const n=te(e).extension,r=new Set(f.value.map(h=>h.name));let c=`untitled.${n}`,d=2;for(;r.has(c);)c=`untitled-${d}.${n}`,d+=1;return c}function rt(e){if(!f.value.some(g=>g.name===e))return e;const n=e.lastIndexOf("."),r=n>0?e.slice(0,n):e,c=n>0?e.slice(n):"";let d=2,h=`${r}-${d}${c}`;for(;f.value.some(g=>g.name===h);)d+=1,h=`${r}-${d}${c}`;return h}let W=0;function at(e){return!!e&&e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")}async function ot(){var n;if(!i.syncFilesOnRun)return;const e=f.value.filter(r=>r.language==="python");for(const r of e){if(!at(r.name)){p(`跳过同步文件:${r.name}(文件名不能包含路径分隔符)`);continue}const c=await v.writeFile(r.name,r.code);c.ok||p(`同步文件失败:${r.name}(${((n=c.error)==null?void 0:n.message)??"未知错误"})`)}}async function Ee(){var d,h,g;if(V.value==="loading"||V.value==="running")return;const e=y.value.language;if(e!=="python"){p(`当前文件为 ${te(e).label},仅支持执行 Python 代码`);return}W+=1;const n=W,r=y.value.id;K(void 0),i.clearOutputOnRun&&(x.value=[]),p("开始执行"),s("runStart");const c=J();try{await ot();const E=await v.run(c,{stdin:i.stdin,onOutput:(Z,G)=>{A(Z,G),s("runOutput",{stream:Z,text:G})}});if(n!==W)return;E.interrupted?p("执行已中断"):E.ok?p(`执行完成,耗时 ${(E.durationMs/1e3).toFixed(2)}s`):(p(`执行出错:${((d=E.error)==null?void 0:d.type)??"未知错误"}`),(h=E.error)!=null&&h.traceback&&(A("stderr",E.error.traceback),s("runOutput",{stream:"stderr",text:E.error.traceback})),y.value.id===r&&K((g=E.error)==null?void 0:g.line),E.error&&s("runError",E.error)),s("runFinish",E)}catch(E){if(n!==W)return;const Z=E instanceof Error?E.message:String(E);p(`执行失败:${Z}`);const G={type:"RuntimeError",message:Z,traceback:""};s("runError",G),s("runFinish",{ok:!1,durationMs:0,error:G})}}async function it(){var n;if(U)return;const e=i.preloadPackages;if(e.length){U=!0,p(`正在安装预置包:${e.join(", ")}`);try{const r=await v.loadPackages(e,{onOutput:(c,d)=>A(c,d)});p(r.ok?`预置包安装完成(${(r.durationMs/1e3).toFixed(1)}s)`:`预置包安装失败:${((n=r.error)==null?void 0:n.message)??"未知错误"}`)}catch(r){p(`预置包安装失败:${r instanceof Error?r.message:String(r)}`)}}}t.onMounted(()=>{const e=S.value;if(!e)return;Ye(),_=!0;const n=[ge.of(i.theme==="dark"?[fe.oneDark]:[]),ve.of([B.EditorState.readOnly.of(i.readOnly),k.EditorView.editable.of(!i.readOnly)]),oe.of(se(y.value.language))];try{l=qe(e,{value:y.value.code,dark:i.theme==="dark",placeholderText:i.placeholder,language:ae.of(de(y.value.language)),extensions:n,onDocChange:r=>{y.value.code=r,r!==i.modelValue&&s("update:modelValue",r)},onRunShortcut:Ee})}catch(r){const c=r instanceof Error?r.message:String(r);console.error("[princess-python-editor] 编辑器初始化失败",r),p(`编辑器初始化失败:${c}`),e.innerHTML="";const d=document.createElement("div");d.className="vpe-init-error",d.textContent=`编辑器初始化失败:${c}`,e.appendChild(d);return}i.autofocus&&l.focus(),F=v.on("status",(r,c)=>{V.value=r,r==="ready"&&(c&&p(`Pyodide ${c} 就绪`),s("ready"),l&&!i.disableLint&&y.value.language==="python"&&_e.forceLinting(l)),s("statusChange",r)}),D=v.on("initError",r=>{p(`Pyodide 加载失败:${r}`),s("loadError",r)}),V.value=v.status,i.preloadPackages.length?v.waitReady().then(()=>it()).catch(r=>p(r.message)):i.preload&&v.waitReady().catch(r=>p(r.message))}),t.onBeforeUnmount(()=>{F==null||F(),D==null||D(),window.clearTimeout(q),window.clearTimeout(j),ke(),l==null||l.destroy(),l=null}),t.watch(()=>i.modelValue,()=>tt()),t.watch(()=>i.fileName,e=>{e&&e!==y.value.name&&(T.value=e)}),t.watch(()=>i.language,e=>{e!==y.value.language&&be(e)}),t.watch(()=>i.theme,e=>{l==null||l.dispatch({effects:ge.reconfigure(e==="dark"?[fe.oneDark]:[])})}),t.watch(()=>i.readOnly,e=>{l==null||l.dispatch({effects:ve.reconfigure([B.EditorState.readOnly.of(e),k.EditorView.editable.of(!e)])})}),t.watch(()=>x.value.length,async()=>{await t.nextTick();const e=b.value;e&&(e.scrollTop=e.scrollHeight)}),t.watch([f,I],()=>Qe(),{deep:!0});function Se(){Ee()}function xe(){V.value==="running"&&(W+=1,v.interrupt(),p("执行已中断"))}function Fe(){x.value=[]}function le(){if(i.readOnly)return;const e=y.value.language,n=Y(nt(e),e,"");f.value.push(n),H(n.id),s("newFile",z(n))}function H(e){if(e===I.value){Q();return}const n=f.value.find(r=>r.id===e);n&&(I.value=e,Ce(n))}function Ne(e){if(f.value.length<=1)return;const n=f.value.findIndex(d=>d.id===e);if(n===-1)return;const r=f.value.splice(n,1)[0];if(!r||(s("fileClose",z(r)),e!==I.value))return;const c=f.value[Math.min(n,f.value.length-1)];c&&(I.value=c.id,Ce(c))}function Ce(e){K(void 0),ie(e.code),l==null||l.dispatch({effects:[ae.reconfigure(de(e.language)),oe.reconfigure(se(e.language))]}),s("update:fileName",e.name),s("update:language",e.language),s("fileSwitch",z(e)),Q()}function Ve(){i.readOnly||(K(void 0),ie(""),Q())}async function Pe(){var r;const e=J();let n=!1;try{(r=navigator.clipboard)!=null&&r.writeText&&(await navigator.clipboard.writeText(e),n=!0)}catch{n=!1}return n||(n=st(e)),n?(L.value=!0,window.clearTimeout(q),q=window.setTimeout(()=>{L.value=!1},1600),s("copy",e),!0):(p("复制失败,请手动选择代码复制"),!1)}function st(e){const n=document.createElement("textarea");n.value=e,n.setAttribute("readonly",""),n.style.position="fixed",n.style.top="0",n.style.left="-9999px",n.style.opacity="0",document.body.appendChild(n),n.select(),n.setSelectionRange(0,n.value.length);let r=!1;try{r=document.execCommand("copy")}catch{r=!1}return n.remove(),r}function Oe(){const e=y.value,n=we(e.name,e.language);T.value=n;const r=new Blob([J()],{type:e.language==="python"?"text/x-python;charset=utf-8":"text/plain;charset=utf-8"}),c=URL.createObjectURL(r),d=document.createElement("a");return d.href=c,d.download=n,d.style.display="none",document.body.appendChild(d),d.click(),d.remove(),window.setTimeout(()=>URL.revokeObjectURL(c),1e3),s("download",n),n}function lt(){R.value=!R.value,R.value&&Be()}async function Be(){var e;if(!$.value){$.value=!0;try{const n=await v.listFiles(".");if(!n.ok){M.value=[],p(`读取虚拟文件失败:${((e=n.error)==null?void 0:e.message)??"未知错误"}`);return}M.value=n.entries??[]}catch(n){M.value=[],p(`读取虚拟文件失败:${n instanceof Error?n.message:String(n)}`)}finally{$.value=!1}}}function ct(e){switch(e.slice(e.lastIndexOf(".")+1).toLowerCase()){case"csv":return"text/csv";case"json":return"application/json";case"html":case"htm":return"text/html";case"md":return"text/markdown";case"py":return"text/x-python";default:return"text/plain"}}function ut(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(1)} MB`}async function Le(e){var n;try{const r=await v.readFile(e);if(!r.ok||r.content===void 0)return p(`下载失败:${e}(${((n=r.error)==null?void 0:n.message)??"未知错误"})`),null;const c=e.slice(e.lastIndexOf("/")+1)||"download.txt",d=new Blob([r.content],{type:`${ct(c)};charset=utf-8`}),h=URL.createObjectURL(d),g=document.createElement("a");return g.href=h,g.download=c,g.style.display="none",document.body.appendChild(g),g.click(),g.remove(),window.setTimeout(()=>URL.revokeObjectURL(h),1e3),s("fsDownload",{path:r.path??e,name:c}),p(`已下载虚拟文件:${c}`),c}catch(r){return p(`下载失败:${r instanceof Error?r.message:String(r)}`),null}}function dt(e,n){return v.writeFile(e,n)}function pt(e){return v.readFile(e)}function ft(e="."){return v.listFiles(e)}function $e(){var e;(e=O.value)==null||e.click()}async function mt(e){var c;const n=e.target,r=(c=n.files)==null?void 0:c[0];if(n.value="",!!r){if(r.size>2*1024*1024){p(`文件过大:${(r.size/1024/1024).toFixed(1)} MB(最多 2 MB)`);return}try{const d=await r.text(),h=Mt(r.name),g=Y(rt(r.name),h,d);f.value.push(g),H(g.id),p(`已打开文件:${g.name}`),s("fileOpen",{name:g.name,code:d,language:h})}catch(d){const h=d instanceof Error?d.message:String(d);p(`读取文件失败:${h}`)}}}function ht(){T.value=we(T.value,y.value.language)}function yt(e){e.key==="Enter"&&(e.preventDefault(),e.target.blur())}function gt(e){be(e.target.value)}async function Me(e){var n,r;await t.nextTick(),(r=(n=C.value)==null?void 0:n.querySelector(`[data-file-id="${e}"]`))==null||r.focus()}function vt(e,n){if(e.target!==e.currentTarget)return;if(e.key==="Enter"||e.key===" "){e.preventDefault(),H(n.id),Me(n.id);return}if(e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;e.preventDefault();const r=f.value.findIndex(h=>h.id===n.id);if(r<0)return;const c=e.key==="ArrowLeft"?-1:1,d=f.value[(r+c+f.value.length)%f.value.length];d&&(H(d.id),Me(d.id))}function Q(){l==null||l.focus()}async function kt(e){var r;p(`正在安装:${e.join(", ")}`);let n;try{n=await v.loadPackages(e,{onOutput:(c,d)=>A(c,d)})}catch(c){const d=c instanceof Error?c.message:String(c);return p(`安装失败:${d}`),{ok:!1,durationMs:0,error:{type:"RuntimeError",message:d}}}return p(n.ok?"安装完成":`安装失败:${((r=n.error)==null?void 0:r.message)??"未知错误"}`),n}function bt(){return v.checkSyntax(J())}function wt(){return l}function Et(){return f.value.map(z)}function St(){return z(y.value)}return a({run:Se,stop:xe,clearOutput:Fe,clearCode:Ve,newFile:le,switchFile:H,closeFile:Ne,copyCode:Pe,download:Oe,openFile:$e,focus:Q,install:kt,checkSyntax:bt,getEditorView:wt,getCode:J,setCode:ie,getFiles:Et,getActiveFile:St,writeFile:dt,readFile:pt,listFiles:ft,downloadFile:Le,clearPersistedState:et}),(e,n)=>(t.openBlock(),t.createElementBlock("div",{class:t.normalizeClass(["vpe-root",{"vpe-dark":u.theme==="dark"}]),style:t.normalizeStyle(Je.value)},[u.showToolbar?(t.openBlock(),t.createElementBlock("div",Ut,[V.value!=="running"?(t.openBlock(),t.createElementBlock("button",{key:0,class:"vpe-btn vpe-btn--primary",type:"button",title:y.value.language==="python"?"运行 (Ctrl+Enter)":"仅支持执行 Python 文件",disabled:V.value==="loading"||y.value.language!=="python",onClick:Se},[t.createVNode(t.unref(It)),n[2]||(n[2]=t.createElementVNode("span",null,"运行",-1))],8,qt)):(t.openBlock(),t.createElementBlock("button",{key:1,class:"vpe-btn vpe-btn--stop",type:"button",title:"中断执行",onClick:xe},[t.createVNode(t.unref(Rt)),n[3]||(n[3]=t.createElementVNode("span",null,"停止",-1))])),n[6]||(n[6]=t.createElementVNode("span",{class:"vpe-divider","aria-hidden":"true"},null,-1)),t.createElementVNode("button",{class:"vpe-btn",type:"button",title:"新建文件","aria-label":"新建文件",disabled:u.readOnly,onClick:le},[t.createVNode(t.unref(Dt))],8,zt),t.createElementVNode("button",{class:"vpe-btn",type:"button",title:"打开本地文件","aria-label":"打开本地文件",disabled:u.readOnly,onClick:$e},[t.createVNode(t.unref(Tt))],8,At),t.createElementVNode("button",{class:"vpe-btn",type:"button",title:"下载当前文件","aria-label":"下载当前文件",onClick:Oe},[t.createVNode(t.unref(Te))]),t.createElementVNode("button",{class:"vpe-btn",type:"button",title:"虚拟文件(下载 Python 生成的文件)","aria-label":"虚拟文件",onClick:lt},[t.createVNode(t.unref(De)),n[4]||(n[4]=t.createElementVNode("span",null,"虚拟文件",-1))]),t.createElementVNode("button",{class:t.normalizeClass(["vpe-btn",{"vpe-btn--copied":L.value}]),type:"button",title:L.value?"已复制":"复制代码","aria-label":L.value?"已复制":"复制代码",onClick:Pe},[L.value?(t.openBlock(),t.createBlock(t.unref(_t),{key:0})):(t.openBlock(),t.createBlock(t.unref(Ht),{key:1}))],10,Kt),t.createElementVNode("button",{class:"vpe-btn",type:"button",title:"清空当前文件","aria-label":"清空当前文件",disabled:u.readOnly,onClick:Ve},[t.createVNode(t.unref(Re))],8,Jt),n[7]||(n[7]=t.createElementVNode("span",{class:"vpe-divider","aria-hidden":"true"},null,-1)),t.createElementVNode("label",Wt,[t.createVNode(t.unref(De)),t.withDirectives(t.createElementVNode("input",{"onUpdate:modelValue":n[0]||(n[0]=r=>T.value=r),class:"vpe-file-input",type:"text",spellcheck:"false","aria-label":"文件名",onBlur:ht,onKeydown:yt},null,544),[[t.vModelText,T.value]])]),n[8]||(n[8]=t.createElementVNode("span",{class:"vpe-spacer","aria-hidden":"true"},null,-1)),t.createElementVNode("span",{class:t.normalizeClass(["vpe-status",`vpe-status--${V.value}`])},[n[5]||(n[5]=t.createElementVNode("span",{class:"vpe-status-dot","aria-hidden":"true"},null,-1)),t.createElementVNode("span",null,t.toDisplayString(Ze.value),1)],2),t.createElementVNode("select",{class:"vpe-lang",value:y.value.language,title:"编辑器语言","aria-label":"编辑器语言",disabled:u.readOnly,onChange:gt},[(t.openBlock(!0),t.createElementBlock(t.Fragment,null,t.renderList(t.unref(ne),r=>(t.openBlock(),t.createElementBlock("option",{key:r.value,value:r.value},t.toDisplayString(r.label),9,Gt))),128))],40,Zt)])):t.createCommentVNode("",!0),u.showTabs?(t.openBlock(),t.createElementBlock("div",{key:1,ref_key:"tabsEl",ref:C,class:"vpe-tabs",role:"tablist","aria-label":"文件"},[(t.openBlock(!0),t.createElementBlock(t.Fragment,null,t.renderList(f.value,r=>(t.openBlock(),t.createElementBlock("div",{key:r.id,class:t.normalizeClass(["vpe-tab",{"vpe-tab--active":r.id===y.value.id}]),role:"tab",tabindex:"0","aria-selected":r.id===y.value.id,"data-file-id":r.id,title:r.name,onClick:c=>H(r.id),onKeydown:c=>vt(c,r)},[t.createElementVNode("span",{class:t.normalizeClass(["vpe-tab-dot",`vpe-tab-dot--${r.language}`]),"aria-hidden":"true"},null,2),t.createElementVNode("span",Yt,t.toDisplayString(r.name),1),f.value.length>1?(t.openBlock(),t.createElementBlock("button",{key:0,class:"vpe-tab-close",type:"button",title:`关闭 ${r.name}`,"aria-label":`关闭 ${r.name}`,disabled:u.readOnly,onClick:t.withModifiers(c=>Ne(r.id),["stop"])},[t.createVNode(t.unref(He))],8,Qt)):t.createCommentVNode("",!0)],42,Xt))),128)),t.createElementVNode("button",{class:"vpe-tabs-add",type:"button",title:"新建文件","aria-label":"新建文件",disabled:u.readOnly,onClick:le},[t.createVNode(t.unref(jt))],8,en)],512)):t.createCommentVNode("",!0),t.createElementVNode("input",{ref_key:"fileInputEl",ref:O,class:"vpe-file-hidden",type:"file",accept:".py,.pyw,.sql,.js,.mjs,.cjs,.jsx,.ts,.json,.txt,text/x-python,text/plain,application/json",onChange:mt},null,544),t.createElementVNode("div",{ref_key:"editorEl",ref:S,class:"vpe-editor"},null,512),u.showOutput?(t.openBlock(),t.createElementBlock("div",{key:2,class:"vpe-output",style:t.normalizeStyle({height:We.value})},[t.createElementVNode("div",tn,[n[9]||(n[9]=t.createElementVNode("span",null,"输出",-1)),t.createElementVNode("button",{class:"vpe-btn vpe-btn--sm",type:"button",title:"清空输出",onClick:Fe},[t.createVNode(t.unref(Re))])]),t.createElementVNode("pre",{ref_key:"outputEl",ref:b,class:"vpe-output-body"},[x.value.length?(t.openBlock(!0),t.createElementBlock(t.Fragment,{key:0},t.renderList(x.value,r=>(t.openBlock(),t.createElementBlock("span",{key:r.id,class:t.normalizeClass(["vpe-line",`vpe-line--${r.stream}`])},t.toDisplayString(r.text)+`
|
|
228
|
+
`,3))),128)):(t.openBlock(),t.createElementBlock("span",nn,"暂无输出,点击“运行”或按 Ctrl+Enter 执行代码"))],512)],4)):t.createCommentVNode("",!0),R.value?(t.openBlock(),t.createElementBlock("div",rn,[t.createElementVNode("div",an,[n[10]||(n[10]=t.createElementVNode("span",{class:"vpe-fs-title"},"虚拟文件",-1)),n[11]||(n[11]=t.createElementVNode("span",{class:"vpe-spacer","aria-hidden":"true"},null,-1)),t.createElementVNode("button",{class:"vpe-btn vpe-btn--sm",type:"button",title:"刷新文件列表",disabled:$.value,onClick:Be}," 刷新 ",8,on),t.createElementVNode("button",{class:"vpe-btn vpe-btn--sm",type:"button",title:"关闭虚拟文件面板","aria-label":"关闭虚拟文件面板",onClick:n[1]||(n[1]=r=>R.value=!1)},[t.createVNode(t.unref(He))])]),t.createElementVNode("div",sn,[$.value?(t.openBlock(),t.createElementBlock("div",ln,"正在读取虚拟文件…")):(t.openBlock(),t.createElementBlock(t.Fragment,{key:1},[M.value.length?t.createCommentVNode("",!0):(t.openBlock(),t.createElementBlock("div",cn," 暂无文件。运行 Python 代码创建文件后再刷新。 ")),(t.openBlock(!0),t.createElementBlock(t.Fragment,null,t.renderList(M.value,r=>(t.openBlock(),t.createElementBlock("div",{key:r.path,class:t.normalizeClass(["vpe-fs-item",{"vpe-fs-item--dir":r.isDirectory}])},[t.createElementVNode("span",{class:"vpe-fs-name",title:r.path},t.toDisplayString(r.path),9,un),t.createElementVNode("span",dn,t.toDisplayString(r.isDirectory?"目录":ut(r.size)),1),r.isDirectory?t.createCommentVNode("",!0):(t.openBlock(),t.createElementBlock("button",{key:0,class:"vpe-btn vpe-btn--sm",type:"button",title:`下载 ${r.name}`,"aria-label":`下载 ${r.name}`,onClick:c=>Le(r.path)},[t.createVNode(t.unref(Te))],8,pn))],2))),128))],64))])])):t.createCommentVNode("",!0)],6))}});function fn(u={}){var U;const a=ye(u.pyodideUrl?{pyodideUrl:u.pyodideUrl}:void 0),o=t.ref(a.status),i=t.ref(""),s=t.ref([]);let S=0;const b=(l,m)=>{s.value.push({id:++S,stream:l,text:m})},C=a.on("status",(l,m)=>{o.value=l,m&&(i.value=m)}),O=a.on("initError",l=>{b("system",`[pyodide] 加载失败:${l}`)});t.onScopeDispose(()=>{C(),O()});const x=async(l,m={})=>{var w;try{const F=await a.run(l,{stdin:m.stdin,onOutput:(D,q)=>b(D,q)});return!F.ok&&((w=F.error)!=null&&w.traceback)&&b("stderr",F.error.traceback),F}catch(F){return{ok:!1,durationMs:0,error:{type:"RuntimeError",message:F instanceof Error?F.message:String(F),traceback:""}}}},V=async(l,m)=>{try{return await a.writeFile(l,m)}catch(w){return{ok:!1,error:{type:"RuntimeError",message:w instanceof Error?w.message:String(w),traceback:""}}}},L=async l=>{try{return await a.readFile(l)}catch(m){return{ok:!1,error:{type:"RuntimeError",message:m instanceof Error?m.message:String(m),traceback:""}}}},R=async(l=".")=>{try{return await a.listFiles(l)}catch(m){return{ok:!1,error:{type:"RuntimeError",message:m instanceof Error?m.message:String(m),traceback:""}}}},$=async l=>{try{return await a.loadPackages(l,{onOutput:(m,w)=>b(m,w)})}catch(m){return{ok:!1,durationMs:0,error:{type:"RuntimeError",message:m instanceof Error?m.message:String(m),traceback:""}}}};let M=!1;const _=async()=>{var w;if(M)return;const l=u.preloadPackages??[];if(!l.length)return;M=!0,b("system",`[pyodide] 正在安装预置包:${l.join(", ")}`);const m=await $(l);b("system",m.ok?`[pyodide] 预置包安装完成(${(m.durationMs/1e3).toFixed(1)}s)`:`[pyodide] 预置包安装失败:${((w=m.error)==null?void 0:w.message)??"未知错误"}`)};return(u.preload||(((U=u.preloadPackages)==null?void 0:U.length)??0)>0)&&a.waitReady().then(()=>_()).catch(()=>{}),{status:o,version:i,outputs:s,runPython:x,install:$,checkSyntax:l=>a.checkSyntax(l),interrupt:()=>a.interrupt(),clearOutputs:()=>{s.value=[]},writeFile:V,readFile:L,listFiles:R,ready:()=>a.waitReady()}}const mn=Ke;exports.DEFAULT_PYODIDE_URL=he;exports.MONO_FONT_STACK=Ue;exports.PyodideRunner=Ae;exports.PythonEditor=mn;exports.createEditor=qe;exports.default=Ke;exports.getRunner=ye;exports.makePythonLinter=ze;exports.setErrorLines=me;exports.usePyodide=fn;
|