Tips & Tricks

Claude Code के साथ API Usage Guide

Claude Code का उपयोग करके API usage guide सीखें। Practical tips और code examples शामिल हैं।

Clipboard API से User Experience बेहतर बनाएं

एक click में code copy करना, rich text paste करना — Clipboard API web app की usability को काफी बेहतर बना देता है। Claude Code का उपयोग करके, browser compatibility और security को ध्यान में रखते हुए जल्दी implementation किया जा सकता है।

Code Block का Copy Button

> Code block में copy button जोड़ो।
> Click के बाद "copied" feedback दिखाओ।
// 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) {
      // Fallback
      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 ? 'Copy हो गया' : 'Code copy करें'}
    >
      {copied ? '✓ Copy हो गया' : 'Copy'}
    </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);
}

Rich Text Copy

// 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: Table data copy करना
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);
}

Clipboard से Reading

// Paste करते समय image processing
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 से permission check
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;
  }
}

Share URL Copy Feature

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 ? 'Copy हो गया!' : 'URL Copy करें'}
      </button>
    </div>
  );
}

Security Considerations

// Sanitize processing के साथ paste
function sanitizePastedContent(html: string): string {
  const div = document.createElement('div');
  div.innerHTML = html;
  
  // Script tags हटाएं
  div.querySelectorAll('script, iframe, object, embed').forEach(el => el.remove());
  
  // Event handler attributes हटाएं
  div.querySelectorAll('*').forEach(el => {
    Array.from(el.attributes)
      .filter(attr => attr.name.startsWith('on'))
      .forEach(attr => el.removeAttribute(attr.name));
  });
  
  return div.innerHTML;
}

Summary

Clipboard API के उपयोग से, code block copy और sharing features जैसी UX में काफी सुधार किया जा सकता है। Claude Code का उपयोग करके, fallback processing और security measures सहित robust implementation संभव है। Web Share API के साथ मिलाकर और भी flexible sharing features प्रदान कर सकते हैं। Performance optimization के पहलू को भी ध्यान में रखें। विस्तृत specification के लिए MDN Web Docs देखें।

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