Tips & Tricks

API Usage Guide:Claude Code 实战指南

了解api usage guide:Claude Code 实战. 包含实用技巧和代码示例。

クリップボードAPIで用户体験を向上

ワン点击でコードをコピーしたり、リッチテキストをペーストしたり、クリップボードAPIはWeb应用の使い勝手を大きく向上させます。借助 Claude Code,浏览器互換性や安全を考慮した实现を快速构建可以。

コードブロックのコピー按钮

> コードブロックにコピー按钮添加。
> 点击後に「コピー済み」フィードバックを显示して。
// components/CopyButton.tsx
import { useState, useCallback } from 'react';

interface CopyButtonProps {
  text: string;
}

export function CopyButton({ text }: CopyButtonProps) {
  const [copied, setCopied] = useState(false);

  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      // フォールバック
      fallbackCopy(text);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  }, [text]);

  return (
    <button
      onClick={handleCopy}
      className="absolute right-2 top-2 rounded bg-gray-700 px-2 py-1 text-xs text-white
        transition-colors hover:bg-gray-600"
      aria-label={copied ? 'コピー済み' : 'コードをコピー'}
    >
      {copied ? '✓ コピー済み' : 'コピー'}
    </button>
  );
}

function fallbackCopy(text: string): void {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  textarea.style.position = 'fixed';
  textarea.style.opacity = '0';
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
}

リッチテキストのコピー

// utils/clipboard.ts
export async function copyRichText(html: string, plainText: string): Promise<void> {
  if (!navigator.clipboard?.write) {
    fallbackCopy(plainText);
    return;
  }

  const htmlBlob = new Blob([html], { type: 'text/html' });
  const textBlob = new Blob([plainText], { type: 'text/plain' });

  const item = new ClipboardItem({
    'text/html': htmlBlob,
    'text/plain': textBlob,
  });

  await navigator.clipboard.write([item]);
}

// Usage example:表格数据のコピー
async function copyTableAsHtml(data: string[][]) {
  const html = `<table>${data.map(row =>
    `<tr>${row.map(cell => `<td>${cell}</td>`).join('')}</tr>`
  ).join('')}</table>`;
  
  const text = data.map(row => row.join('\t')).join('\n');
  await copyRichText(html, text);
}

クリップボードからの読み取り

// ペースト時の图片処理
async function handlePaste(e: ClipboardEvent): Promise<void> {
  const items = e.clipboardData?.items;
  if (!items) return;

  for (const item of items) {
    if (item.type.startsWith('image/')) {
      e.preventDefault();
      const blob = item.getAsFile();
      if (blob) {
        const url = URL.createObjectURL(blob);
        insertImage(url);
      }
    }
  }
}

// Permissions APIで権限チェック
async function checkClipboardPermission(): Promise<boolean> {
  try {
    const result = await navigator.permissions.query({
      name: 'clipboard-read' as PermissionName,
    });
    return result.state === 'granted' || result.state === 'prompt';
  } catch {
    return false;
  }
}

共有用URLのコピー機能

function ShareUrl({ url, title }: { url: string; title: string }) {
  const [copied, setCopied] = useState(false);

  const handleCopy = async () => {
    await navigator.clipboard.writeText(url);
    setCopied(true);
    setTimeout(() => setCopied(false), 3000);
  };

  return (
    <div className="flex items-center gap-2 rounded-lg border p-3">
      <input
        type="text"
        value={url}
        readOnly
        className="flex-1 bg-transparent text-sm outline-none"
      />
      <button
        onClick={handleCopy}
        className="rounded bg-blue-600 px-3 py-1 text-sm text-white hover:bg-blue-700"
      >
        {copied ? 'コピー済み!' : 'URLをコピー'}
      </button>
    </div>
  );
}

安全の考慮事項

// サニタイズ処理付きペースト
function sanitizePastedContent(html: string): string {
  const div = document.createElement('div');
  div.innerHTML = html;
  
  // スクリプトタグを除去
  div.querySelectorAll('script, iframe, object, embed').forEach(el => el.remove());
  
  // 事件处理程序属性を除去
  div.querySelectorAll('*').forEach(el => {
    Array.from(el.attributes)
      .filter(attr => attr.name.startsWith('on'))
      .forEach(attr => el.removeAttribute(attr.name));
  });
  
  return div.innerHTML;
}

总结

クリップボードAPIの活用で、コードブロックのコピーや共有機能などのUXを大幅に改善可以。借助 Claude Code,フォールバック処理や安全対策まで含めた堅牢な实现が是可能的。Web Share APIと組み合わせれば、进一步柔軟な共有機能を提供可以。性能优化の観点も忘れずに考慮吧。詳しい仕様はMDN Web Docs

#Claude Code #Clipboard API #JavaScript #UX #Web API