# 代码语言切换

同一个示例提供两种编程语言，可复制当前显示的代码。

## 试一试

选择一种编程语言，复制示例，并对照下方的预期输出。

## 交互细节

两种语言的示例都统计已完成项目数。切换后，屏幕和剪贴板使用同一段代码。

## 适用场景

API 文档、开发指南和多语言教程。

## 实现要求

> 切换语言后更新代码，复制按钮只复制当前可见的示例，并报告结果。

## 来源与致谢

- [Stripe API 的 Node.js 示例](<https://docs.stripe.com/api/setup_attempts/list?lang=node>)
- [Stripe API 的 Python 示例](<https://docs.stripe.com/api/setup_attempts/list?lang=python>)

## 如何验证效果

在 JavaScript 和 Python 之间切换后，复制当前显示的计数示例代码。网页版会将所选编程语言保存在网址中，后退时应恢复上一个代码片段。如果浏览器无法访问剪贴板，示例会选中代码，方便手动复制。

## 独立 HTML 示例

将以下代码保存为 HTML 文件，用浏览器打开即可离线体验。

```html
<!doctype html>
<html lang="zh-Hans"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>代码语言切换 · UI Motion Lab</title>
<style>:root{color-scheme:light;--paper:#f5f3ec;--ink:#262820;--line:#c7c6b7;--accent:#98402b}
*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:15px/1.55 Arial,'Apple SD Gothic Neo','Malgun Gothic',sans-serif;overflow-wrap:anywhere}
main{width:min(810px,calc(100% - 36px));margin:clamp(20px,5vh,58px) auto}
main h1{margin:0;font-size:clamp(28px,4.1vw,47px);font-weight:700;line-height:1.15;letter-spacing:-.065em}
main>p{color:#56594e;margin:8px 0 22px;line-height:1.55}.panel{padding:clamp(15px,2.7vw,28px);background:#fffdf6;border:1px solid var(--line);border-radius:2px}
button,select,input,textarea{font:inherit}button,select{min-height:40px}button{cursor:pointer}button:disabled{cursor:default;opacity:.45}
button,select{background:#faf9f0;color:inherit;border:1px solid #a6a798;border-radius:3px;padding:5px 12px}
:focus-visible{outline:3px solid #945030;outline-offset:3px}button:enabled:hover,select:hover{border-color:var(--ink)}
[hidden]{display:none!important}.lab-embedded [data-lab-shell]{display:none!important}.lab-embedded main{margin:clamp(12px,2vh,25px) auto}
figure,fieldset{margin:0}p:last-child{margin-bottom:0}fieldset{min-width:0}
@media(max-width:460px){main{width:calc(100% - 24px);margin:16px auto}main>p{font-size:13px;margin:5px 0 14px}main h1{font-size:26px}.panel{padding:13px}}
@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation-duration:.01ms!important;transition-duration:.01ms!important;scroll-behavior:auto!important}}
.lab-reduce *,.lab-reduce *::before,.lab-reduce *::after{animation-duration:.01ms!important;transition-duration:.01ms!important;scroll-behavior:auto!important}
.panel{padding:0;background:#222924;color:#f1eddb;border-color:#2d362f;overflow:hidden}
.toolbar{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:10px 14px;background:#303a32;border-bottom:1px solid #576050}
.toolbar label{font-size:13px;color:#dedfd0}.toolbar select,.toolbar button{background:#fff9;border-color:#b4b7a3;color:#172019;font-size:13px;min-height:35px}.toolbar #copy{margin-left:auto;background:transparent;color:#fff9df;border-color:#76816e}
.editor{padding:clamp(13px,3vw,26px)}.filename{font:12px/1.4 monospace;color:#c1cbb5;margin-bottom:12px}pre{margin:0;overflow-x:auto;max-width:100%;padding-bottom:5px;tab-size:2}code{font:clamp(12px,1.7vw,16px)/1.9 ui-monospace,Consolas,monospace;white-space:pre}.syntax-string{color:#e7bd8b}.syntax-word{color:#b1d6c7}
.console{display:flex;align-items:baseline;gap:15px;padding:9px 16px;color:#eeefd8;background:#3b493a}.console span{font-size:12px}.console strong{font:italic 24px Georgia,serif}
#status{font-size:12px;margin:0;color:#d8dfcf}#status:not(:empty){padding:6px 16px}#manual{width:calc(100% - 24px);min-height:75px;margin:0 12px 10px}
</style>
<script>
const viewOptions=new URLSearchParams(location.search);
document.documentElement.classList.toggle('lab-embedded',viewOptions.get('embed')==='1');
document.documentElement.classList.toggle('lab-reduce',viewOptions.get('reduce')==='1');
</script>
</head>
<body class="lab-example">
<main><h1>代码语言切换</h1><p>选择一种语言，然后复制对应的示例代码，统计已完成的项目数。</p>
<section class="panel" aria-label="已完成项目计数示例">
 <div class="toolbar"><label for="language">代码语言</label><select id="language"><option value="js">JavaScript</option><option value="py">Python</option></select><button id="copy" type="button">复制代码</button></div>
 <div class="editor"><div class="filename"></div><pre tabindex="0" aria-label="所选语言的代码"><code id="code"></code></pre></div>
 <div class="console"><span>预期输出</span><strong>2 项</strong></div>
 <p role="status" id="status"></p><textarea id="manual" hidden readonly aria-label="手动复制以下代码"></textarea>
</section>
</main>
<script>

const snippets = {
  js: 'const orders = ["done", "open", "done"];\nconst finished = orders.filter(status => status === "done");\nconsole.log(finished.length);',
  py: 'orders = ["done", "open", "done"]\nfinished = [status for status in orders if status == "done"]\nprint(len(finished))'
};
const language = document.querySelector("#language");
const code = document.querySelector("#code");
const status = document.querySelector("#status");
const manual = document.querySelector("#manual");
let revision = 0;
function display() {
  revision++;
  code.replaceChildren();
  const sample=snippets[language.value];
  const token=/"[^"]*"|\b(?:const|for|in|if|print|console|filter|len)\b/g;
  let start=0;
  for(const match of sample.matchAll(token)){
    code.append(document.createTextNode(sample.slice(start,match.index)));
    const span=document.createElement('span');
    span.className=match[0].startsWith('"')?'syntax-string':'syntax-word';
    span.textContent=match[0];code.append(span);start=match.index+match[0].length;
  }
  code.append(document.createTextNode(sample.slice(start)));
  document.querySelector('.filename').textContent=language.value==='js'?'count-completed.js':'count_completed.py';
  manual.hidden = true;
  manual.value = "";
  status.textContent = "";
}
function restore() {
  const key = new URL(location.href).searchParams.get("lang");
  language.value = Object.hasOwn(snippets, key) ? key : "js";
  display();
}
language.addEventListener("change", () => {
  display();
  if (!/^https?:$/.test(location.protocol)) return;
  const url = new URL(location.href);
  url.searchParams.set("lang", language.value);
  history.pushState(null, "", url);
});
document.querySelector("#copy").addEventListener("click", async () => {
  const selected = code.textContent;
  const label = language.selectedOptions[0].text;
  const atClick = revision;
  try {
    await navigator.clipboard.writeText(selected);
    if (atClick === revision) status.textContent = label + " 代码已复制。";
  } catch {
    if (atClick !== revision) return;
    manual.hidden = false;
    manual.value = selected;
    manual.focus();
    manual.select();
    status.textContent = "请复制选中的代码。";
  }
});
window.addEventListener("popstate", restore);
restore();
</script>
</body></html>
```
