示例工程 33-clipboard-dnd-fs
33-clipboard-dnd-fs/app/.tsc/src/App.js
function escape(text) {
return text.replace(/[&<>"]/g, (char) => {
if (char === "&")
return "&";
if (char === "<")
return "<";
if (char === ">")
return ">";
return """;
});
}
function sizeText(size) {
if (size < 1024)
return `${size} B`;
return `${(size / 1024).toFixed(1)} KB`;
}
export function mountApp(root) {
root.innerHTML = `
<div class="app">
<header class="header">
<div class="brand">
<h1>剪贴板、拖放与文件系统工作台</h1>
<span class="pill" data-testid="platform">—</span>
<span class="pill" data-testid="format-count">0 种格式</span>
</div>
<div class="actions">
<button class="btn" data-testid="read-clipboard">读取剪贴板</button>
</div>
</header>
<main class="layout">
<div class="column">
<section class="card pad">
<div class="card-head">
<h2>剪贴板</h2>
<span class="muted small">显式读取,不自动监听</span>
</div>
<textarea class="input area" rows="4" data-testid="clip-input"></textarea>
<div class="actions wrap">
<button class="btn primary" data-testid="write-text">写入纯文本</button>
<button class="btn" data-testid="write-html">写入 HTML</button>
<button class="btn" data-testid="clear-input">清空输入</button>
</div>
<div class="formats" data-testid="formats"></div>
<div class="clip-preview" data-testid="clip-preview"></div>
</section>
<section class="card pad">
<div class="card-head">
<h2>拖放与文件</h2>
<span class="muted small">.md / .txt / .json / .log · ≤1MB</span>
</div>
<div class="dropzone" data-testid="dropzone">
把文本或文件拖到这里;文件路径经 <code>webUtils.getPathForFile</code>
取得,再由主进程校验。
</div>
<div class="drop-types" data-testid="drop-types"></div>
<div class="actions wrap">
<button class="btn" data-testid="pick-file">选择文件</button>
<button class="btn" data-testid="sample-notes">模拟拖入 notes.md</button>
<button class="btn" data-testid="sample-missing">模拟失效文件</button>
<button class="btn" data-testid="sample-wrong">错误扩展名</button>
<button class="btn" data-testid="sample-big">超 1MB 文件</button>
</div>
<div class="file-preview">
<strong data-testid="file-name">尚未打开文件</strong>
<div class="muted small" data-testid="file-meta"></div>
<div class="error" data-testid="file-error"></div>
<pre class="content" data-testid="file-content"></pre>
</div>
</section>
</div>
<div class="column">
<section class="card pad">
<div class="card-head">
<h2>最近打开</h2>
<div class="actions">
<button class="btn" data-testid="refresh-recent">刷新状态</button>
<button class="btn" data-testid="clear-recent">清空</button>
</div>
</div>
<ul class="recent" data-testid="recent"></ul>
</section>
<section class="card pad">
<div class="card-head">
<h2>安全边界</h2>
</div>
<ul class="notes muted small">
<li>剪贴板只在用户点击时读取,启动时不偷看。</li>
<li>拖放文件路径由 preload 的 <code>webUtils</code> 解析,渲染层不拼路径。</li>
<li>扩展名白名单 + 1MB 上限 + UTF-8 读取;二进制文件直接拒绝。</li>
<li>文件内容按纯文本展示,不执行、不渲染 HTML。</li>
<li>最近打开只存路径与元数据;每次刷新重新检查是否存在。</li>
</ul>
</section>
<p class="status muted small" data-testid="status">就绪</p>
</div>
</main>
</div>
`;
const clipInput = root.querySelector('[data-testid="clip-input"]');
const formatCount = root.querySelector('[data-testid="format-count"]');
const formatsEl = root.querySelector('[data-testid="formats"]');
const clipPreview = root.querySelector('[data-testid="clip-preview"]');
const dropTypes = root.querySelector('[data-testid="drop-types"]');
const fileName = root.querySelector('[data-testid="file-name"]');
const fileMeta = root.querySelector('[data-testid="file-meta"]');
const fileError = root.querySelector('[data-testid="file-error"]');
const fileContent = root.querySelector('[data-testid="file-content"]');
const recentEl = root.querySelector('[data-testid="recent"]');
const status = root.querySelector('[data-testid="status"]');
const platform = root.querySelector('[data-testid="platform"]');
let state = null;
let localDropText = "";
let localDropTypes = [];
function renderClipboard() {
if (!state)
return;
const info = state.clipboard;
if (platform)
platform.textContent = state.platform;
if (formatCount)
formatCount.textContent = `${info.formats.length} 种格式`;
if (formatsEl) {
formatsEl.innerHTML =
info.formats.length === 0
? `<span class="muted small">尚未读取</span>`
: info.formats
.map((format) => `<code class="format">${escape(format)}</code>`)
.join("");
}
if (clipPreview) {
const text = info.text.length > 240 ? `${info.text.slice(0, 240)}…` : info.text;
clipPreview.innerHTML = `
<div class="muted small">读取到 ${info.text.length} 字符文本 / ${info.html.length} 字符 HTML</div>
<div class="clip-text">${escape(text) || "<span class='muted'>(空)</span>"}</div>
<div class="muted small">HTML 前 120 字符:${escape(info.html.slice(0, 120)) || "—"}</div>`;
}
}
function renderFile(file) {
if (!fileName || !fileMeta || !fileError || !fileContent)
return;
if (!file) {
fileName.textContent = "尚未打开文件";
fileMeta.textContent = "";
fileError.textContent = "";
fileContent.textContent = "";
return;
}
fileName.textContent = file.name;
fileMeta.textContent = `${file.ext || "?"} · ${sizeText(file.size)} · ${file.ok ? "已读取" : "失败"}`;
fileError.textContent = file.ok ? "" : `错误:${file.error}`;
fileContent.textContent = file.ok ? file.content : "";
}
function renderRecent() {
if (!recentEl || !state)
return;
if (state.recent.length === 0) {
recentEl.innerHTML = `<li class="muted">暂无最近文件</li>`;
return;
}
recentEl.innerHTML = state.recent
.map((entry) => `
<li class="recent-item" data-testid="recent-item" data-path="${escape(entry.path)}">
<div>
<strong>${escape(entry.name)}</strong>
<span class="muted small">${escape(entry.ext)} · ${sizeText(entry.size)}</span>
</div>
${entry.exists
? `<span class="ok small">存在</span>`
: `<span class="missing small" data-testid="recent-missing">失效</span>`}
</li>`)
.join("");
}
function renderDrop() {
if (!dropTypes)
return;
const types = localDropTypes;
dropTypes.innerHTML =
types.length === 0
? `<span class="muted small">尚未拖入内容</span>`
: types
.map((type) => `<code class="format">${escape(type)}</code>`)
.join("");
if (localDropText) {
dropTypes.innerHTML += `<div class="drop-text">${escape(localDropText.slice(0, 200))}</div>`;
}
}
function apply(next) {
state = next;
renderClipboard();
renderFile(next.lastFile);
renderRecent();
renderDrop();
}
window.api.clipboard.get().then(apply);
root
.querySelector('[data-testid="write-text"]')
?.addEventListener("click", async () => {
apply(await window.api.clipboard.writeText(clipInput?.value ?? ""));
if (status)
status.textContent = "已写入纯文本";
});
root
.querySelector('[data-testid="write-html"]')
?.addEventListener("click", async () => {
const text = clipInput?.value ?? "";
apply(await window.api.clipboard.writeHtml(`<p>${escape(text)}</p>`));
if (status)
status.textContent = "已写入 HTML";
});
root
.querySelector('[data-testid="read-clipboard"]')
?.addEventListener("click", async () => {
apply(await window.api.clipboard.read());
if (status)
status.textContent = "已读取剪贴板";
});
root
.querySelector('[data-testid="clear-input"]')
?.addEventListener("click", () => {
if (clipInput)
clipInput.value = "";
});
const readSample = (path) => {
if (path)
void window.api.fs.readPath(path).then(apply);
};
root
.querySelector('[data-testid="sample-notes"]')
?.addEventListener("click", () => readSample(state?.samples.notes));
root
.querySelector('[data-testid="sample-missing"]')
?.addEventListener("click", () => readSample(state?.samples.missing));
root
.querySelector('[data-testid="sample-wrong"]')
?.addEventListener("click", () => readSample(state?.samples.wrong));
root
.querySelector('[data-testid="sample-big"]')
?.addEventListener("click", () => readSample(state?.samples.big));
root
.querySelector('[data-testid="pick-file"]')
?.addEventListener("click", async () => {
apply(await window.api.fs.pick());
});
root
.querySelector('[data-testid="refresh-recent"]')
?.addEventListener("click", async () => {
apply(await window.api.fs.refreshRecent());
if (status)
status.textContent = "已刷新最近文件状态";
});
root
.querySelector('[data-testid="clear-recent"]')
?.addEventListener("click", async () => {
apply(await window.api.fs.clearRecent());
if (status)
status.textContent = "已清空最近文件";
});
recentEl?.addEventListener("click", (event) => {
const target = event.target;
const item = target.closest("[data-testid='recent-item']");
const filePath = item?.dataset.path;
if (filePath)
readSample(filePath);
});
const zone = root.querySelector('[data-testid="dropzone"]');
zone?.addEventListener("dragover", (event) => event.preventDefault());
zone?.addEventListener("drop", async (event) => {
event.preventDefault();
localDropTypes = Array.from(event.dataTransfer?.types ?? []);
const file = event.dataTransfer?.files?.[0];
if (file) {
try {
const filePath = window.api.fs.pathForFile(file);
apply(await window.api.fs.readPath(filePath));
}
catch {
localDropText = "无法读取拖放文件路径";
renderDrop();
}
return;
}
localDropText = event.dataTransfer?.getData("text/plain") ?? "";
renderDrop();
});
window.__prepareShots = async (stage) => {
await window.api.fs.clearRecent();
if (stage === "clipboard") {
if (clipInput) {
clipInput.value =
"XWRT 剪贴板示例:~/work/project\n邮箱 dev@example.com";
}
await window.api.clipboard.writeText(clipInput?.value ?? "");
await window.api.clipboard.writeHtml("<p>XWRT <b>HTML</b> 示例</p>");
apply(await window.api.clipboard.read());
}
else if (stage === "file") {
const base = await window.api.clipboard.get();
await window.api.fs.readPath(base.samples.config);
apply(await window.api.fs.readPath(base.samples.notes));
}
else {
const base = await window.api.clipboard.get();
await window.api.fs.readPath(base.samples.notes);
apply(await window.api.fs.readPath(base.samples.missing));
}
};
window.__smoke = async () => {
const api = window.api;
const original = (await api.clipboard.get()).clipboard.text;
await api.clipboard.writeText("XWRT 剪贴板测试");
const written = await api.clipboard.read();
await api.clipboard.writeHtml("<p>html</p>");
const htmlState = await api.clipboard.read();
await api.clipboard.writeText(original);
const base = await api.clipboard.get();
const notes = await api.fs.readPath(base.samples.notes);
const missing = await api.fs.readPath(base.samples.missing);
const wrong = await api.fs.readPath(base.samples.wrong);
const big = await api.fs.readPath(base.samples.big);
const refreshed = await api.fs.refreshRecent();
const missingEntry = refreshed.recent.find((entry) => entry.path === base.samples.missing);
const recentBeforeClear = refreshed.recent.length;
const cleared = await api.fs.clearRecent();
apply(cleared);
return {
platform: base.platform,
clipboardText: written.clipboard.text,
formats: written.clipboard.formats,
formatsHasHtml: htmlState.clipboard.formats.includes("text/html"),
notesOk: notes.lastFile?.ok ?? false,
notesContent: notes.lastFile?.content ?? "",
missingError: missing.lastFile?.error ?? "",
wrongError: wrong.lastFile?.error ?? "",
bigError: big.lastFile?.error ?? "",
refreshedMissing: missingEntry?.exists === false,
recentBeforeClear,
cleared: cleared.recent.length === 0,
samples: base.samples,
};
};
}
//# sourceMappingURL=App.js.map