# HtmlSandbox

> 在隔离的 iframe 中预览含 CSS、JavaScript 的 HTML，保留源码和显式运行控制。

网页来源：/components/html-sandbox

版本：@quirekit/ui 0.3.1；源码修订：d79a6b48d00e+worktree。此文档对应当前源码构建，接入方式以开始使用为准。

接入前置：[开始使用](/raw/components/getting-started.md)（Vue、样式、主题与图标 Provider）。

`QuireHtmlSandbox` 接收 HTML 字符串，默认点击“运行”后才执行。它使用 `@quirekit/html-sandbox` 内核，无需上传文件或为每份内容创建 URL。

## 预览与源码

`html` 保留原始内容，切换页签不会重新执行。源码更新后保留上次运行结果并提示更新，点击“重新运行”应用新内容；停止会释放页面，源码仍可查看和复制。

### 示例：html-sandbox/basic

文件：`basic.vue`

```vue
<script setup lang="ts">
import { QuireHtmlSandbox } from "@quirekit/ui/vue";
const html = `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><style>
body { margin:0; padding:32px; color:#153f36; background:#f3faf5; font:16px system-ui; }
h1 { font-size:24px; margin:0 0 12px; } p { color:#527068; }
button { padding:10px 20px; border:0; border-radius:8px; color:white; background:#22624f; cursor:pointer; font:inherit; }
</style></head><body><h1>今天的小进步</h1><p>这一块 HTML 有自己的样式和交互。</p>
<button onclick="this.textContent='已记录 '+(this.dataset.count=Number(this.dataset.count||0)+1)+' 次';console.log(this.textContent)">记录一次</button></body></html>`;
</script>
<template><div class="p-qk-surface" data-sandbox-basic><QuireHtmlSandbox :html="html" title="进步记录" :height="280" /></div></template>
```

独立组件可从 `@quirekit/ui/vue/html-sandbox` 按需导入。读取本地文件时由宿主调用 `await file.text()`，再把结果赋给 `html`。

## 流式内容

流式期间传 `complete=false`；宿主确认语法和生成均完成后改为 true。`config.execution='on-complete'` 会在完成边界运行一次。切换文档时更新 `identity`；停止后自动运行保持关闭，直到显式运行。

### 示例：html-sandbox/stream

文件：`stream.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import { defineHtmlSandboxConfig } from "@quirekit/html-sandbox";
import { QuireHtmlSandbox, QuireButton } from "@quirekit/ui/vue";
const html = ref('<h2>正在准备内容');
const complete = ref(false);
const config = defineHtmlSandboxConfig({ execution: "on-complete" });
/** The host declares completion only after syntax and generation have finished. */
function finish(): void { html.value = '<h2>内容已完整</h2><button onclick="this.textContent=\'已响应\'">试一下</button>'; complete.value = true; }
/** A new incomplete input does not silently replace the running snapshot. */
function restart(): void { complete.value = false; html.value = '<h2>正在准备下一版'; }
</script>
<template>
  <div class="p-qk-surface" data-sandbox-stream>
    <div class="flex gap-qk-inline mb-qk-surface-compact"><QuireButton :disabled="complete" @click="finish">提交完整内容</QuireButton><QuireButton @click="restart">开始下一版</QuireButton></div>
    <QuireHtmlSandbox :html="html" :complete="complete" :config="config" identity="stream-example" :height="220" />
  </div>
</template>
```

## 执行策略与尺寸

`config.execution='disabled'` 保留源码阅读。`height` 默认固定 320px，也可传 `{ min, max, initial }` 启用有界自动高度。页面状态只存在于当前运行，卸载后不保存。

### 示例：html-sandbox/states

文件：`states.vue`

```vue
<script setup lang="ts">
import { QuireHtmlSandbox } from "@quirekit/ui/vue";
</script>
<template>
  <div class="p-qk-surface grid gap-qk-surface" data-sandbox-states>
    <QuireHtmlSandbox html="<h2>仅查看源码</h2>" :config="{ execution: 'disabled' }" :height="160" title="禁用执行" />
    <QuireHtmlSandbox html="<button onclick=&quot;throw new Error('示例错误')&quot;>触发日志</button>" :height="{ min: 160, max: 400 }" title="有界自动高度" />
  </div>
</template>
```

内嵌资源模式支持内联 CSS、JavaScript 和 data 图片/字体；外部资源、相对路径、npm 导入不在支持范围。隔离限制宿主访问，不提供硬 CPU/内存配额或绝对断网保证。

## 编辑器与 Markdown

MSFE 和 Incremark 可显式安装 `createMsfeHtmlSandbox()`（`@quirekit/msfe-html-sandbox/vue`），只识别 `html-preview` 围栏。Block Editor 通过 extensions 安装 `createHtmlSandboxExtension()`（`@quirekit/extension-html-sandbox/vue`），使用 `insertHtmlSandbox` / `updateHtmlSandbox` 命令保存源码。

编辑器适配默认手动运行，只接受 manual/disabled，避免滚动重挂触发重复执行。源码编辑、保存和文档身份由编辑器拥有；`interactionGated` 可要求先点击“进入交互”，让外层仍能选块。静态 HTML 导出保留转义代码，不运行脚本。

MSFE 在 `mode: 'live'` 或 `'locked'` 中显示组件，source 模式保留围栏源码。阅读适配接收已提交的 Markdown 快照；流式自动执行使用上面的独立组件，并由宿主明确提供 `complete` 和 `identity`。

```ts
import { createMsfeHtmlSandbox } from '@quirekit/msfe-html-sandbox/vue'
import { writeHtmlSandboxFence } from '@quirekit/html-sandbox/markdown'

const options = {
  mode: 'live' as const,
  markdown: writeHtmlSandboxFence('<button onclick="this.textContent=1">点击</button>'),
  extensions: [createMsfeHtmlSandbox()],
}
// 传给 MsfeEditorContent 的 options；修改源码沿 editor.commands.updateAttributes。
```

## API

### QuireHtmlSandbox

#### Props

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| html | 是 | — | Exact HTML source; no document writeback occurs. |
| complete | 否 | true | True only after both syntax and upstream generation are complete. Defaults to true. |
| identity | 否 | — | Stable document/block identity; defaults to this component mount. |
| config | 否 | — | Trusted host policy; defaults to manual execution with embedded resources. |
| title | 否 | — | Accessible frame and section name. |
| height | 否 | — | Fixed CSS pixel height or bounded automatic height. Defaults to 320. |
| interactionGated | 否 | false | Require an explicit enter action before guest interaction, for editor selection. Defaults to false. |

**html**

```ts
string
```

**complete**

```ts
boolean | undefined
```

**identity**

```ts
string | undefined
```

```ts
undefined | string
```

**config**

```ts
HtmlSandboxConfig | undefined
```

```ts
undefined | {
  /** Defaults to srcdoc. */
  transport?: undefined | {
    kind: "srcdoc";
  } | {
    kind: "hosted";
    runnerUrl: string;
  };
  /** Embedded resources only; this is not a complete network-egress guarantee. */
  resources?: undefined | "embedded";
  /** Defaults to manual. */
  execution?: undefined | "disabled" | "manual" | "on-complete";
}
```

**title**

```ts
string | undefined
```

```ts
undefined | string
```

**height**

```ts
QuireKitHtmlSandboxHeight | undefined
```

```ts
undefined | number | {
  min?: undefined | number;
  max?: number | undefined;
  initial?: number | undefined;
}
```

**interactionGated**

```ts
boolean | undefined
```

#### Events

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| state-change | 否 | — |  |
| diagnostic | 否 | — |  |
| resize | 否 | — |  |

**state-change**

```ts
[state: HtmlSandboxState]
```

**diagnostic**

```ts
[diagnostic: HtmlSandboxDiagnostic]
```

**resize**

```ts
[height: number]
```

#### Slots

无。

#### 公开实例成员

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| run | 否 | — | Run the current complete snapshot. |
| stop | 否 | — | Stop the current or pending execution. |

**run**

```ts
() => Promise<boolean>
```

```ts
{ (): Promise<boolean>; }
```

**stop**

```ts
() => void
```

```ts
{ (): void; }
```
