react-smart-copy 1.11.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,6 +28,7 @@ ID PLT-29018 [Copy]
28
28
  - **`react-smart-copy/table`**: copy rows that paste into Excel and Google Sheets as cells, and read pasted ranges back as typed records. Works with AG Grid, TanStack Table and any `<table>`
29
29
  - **`react-smart-copy/structured`**: copy your own objects and paste them back as the same typed, validated objects in another tab or app, the way design tools do. Versioned, with migrations, and works with Zod, Valibot or ArkType
30
30
  - **`react-smart-copy/markdown`**: paste from Google Docs, Word, Notion or any web page into a Markdown field and get clean Markdown, with undo intact: `<textarea onPaste={pasteAsMarkdown} />`
31
+ - **`react-smart-copy/code`**: copy code blocks the way developers expect (a terminal session copies as its commands, gutters and prompts stay behind, colours survive in Docs and Slack), paste code cleaned and indented, and catch Trojan Source, invisible identifiers and lookalike letters
31
32
  - **`react-smart-copy/capture`**: copy an `<svg>` or any piece of your UI as a PNG
32
33
  - Every failure is a typed, classified error. Nothing silently no-ops
33
34
  - Unstyled. Works with Tailwind, CSS modules, CSS-in-JS, shadcn, MUI, Ant Design
@@ -47,6 +48,7 @@ This package only promises what browsers actually support.
47
48
  | Several formats at once | ✅ | `kind: 'multi'`; each MIME type is checked with `ClipboardItem.supports()` first |
48
49
  | Your app's own data (typed) | ✅ | `react-smart-copy/structured`: a web custom format, a custom type and an HTML envelope, so every browser and paste path gets one |
49
50
  | Rich text as Markdown | ✅ paste | `react-smart-copy/markdown`: CommonMark + GFM from Docs, Word, web pages and mail; plain-text pastes stay untouched |
51
+ | Code (blocks, sessions, diffs) | ✅ | `react-smart-copy/code`: plain text plus monospaced, highlighted HTML; commands without prompts or output; Trojan Source checks on paste |
50
52
  | SVG (icons, charts, logos) | ✅ as PNG | `svgToPngBlob()` from `react-smart-copy/capture` rasterises natively, no dependency. Raw SVG is not a clipboard image format |
51
53
  | A section of your UI as an image | ✅ bring a rasteriser | Browsers have no "screenshot this element" API. `captureElement()` wraps one you choose (e.g. `modern-screenshot`) with limits and checks |
52
54
  | Files (PDF, DOCX, ZIP) | ❌ | Not writable to the system clipboard by any browser API |
@@ -675,6 +677,85 @@ documents with a CommonMark parser and compare the result character by character
675
677
  | `hardBreak` | `"backslash"` | `"spaces"` for two trailing spaces |
676
678
  | `codeAsText` (paste) | `true` | `false` turns code-only pastes into fenced code blocks |
677
679
 
680
+ ## Copy and paste code
681
+
682
+ `react-smart-copy/code` is for the copy button on every code block and for fields people
683
+ paste code into. It also catches code that reads differently from how it runs. No
684
+ dependencies, about 7.4 kB (`inspectCode` alone is about 2.5 kB).
685
+
686
+ ```tsx
687
+ import { useCopy } from "react-smart-copy";
688
+ import { codePayload } from "react-smart-copy/code";
689
+
690
+ const { copy, status } = useCopy();
691
+ <pre ref={preRef}>…</pre>
692
+ <button onClick={() => copy(() => codePayload(preRef.current!, { language: "tsx" }))}>Copy</button>
693
+ ```
694
+
695
+ What gets copied is the code the reader means to run:
696
+
697
+ - **A terminal or REPL session copies as its commands.** `$ npm test` followed by its output copies as `npm test`. Prompts from `bash`/`zsh` (`$`, `user@host:~$`, `(venv) $`), PowerShell, `cmd`, Python, IPython and Node are recognised. Continued commands stay whole: a trailing `\`, a heredoc or an open quote. `prompt: "auto"` (the default) only acts when the first line starts with a prompt
698
+ - **A highlighted block copies without its chrome.** Line-number gutters (Prism, highlight.js, Rouge, react-syntax-highlighter and others), `user-select: none` and `aria-hidden` parts, hidden parts, buttons and anything with `data-copy-ignore` are left out. `ignore` takes a CSS selector for more
699
+ - **It pastes well everywhere.** Plain text for editors and terminals, plus monospaced HTML with the block's syntax colours for Google Docs, Word, Slack, Teams and mail. Both flavours always hold the same code
700
+ - **Diffs, line numbers, indentation.** `diff: "after"` (or `"before"`) copies one side of a unified diff. `lineNumbers: true` removes typed line numbers when they count up on every line. Shared indentation, trailing whitespace and blank edges are removed, and line endings are normalised (`lineEnding: "crlf"` for Windows)
701
+
702
+ For a code field, `pasteAsCode` is a ready paste handler:
703
+
704
+ ```tsx
705
+ import { pasteAsCode } from "react-smart-copy/code";
706
+
707
+ <textarea onPaste={pasteAsCode} />
708
+ <textarea onPaste={(event) => pasteAsCode(event, { onPaste: (r) => !r.danger || confirm("Paste anyway?") })} />
709
+ ```
710
+
711
+ It fixes what chat apps and word processors do to code (curly quotes, `—` for `--`,
712
+ no-break spaces, zero-width characters) and dedents the paste. Each line after the first is
713
+ indented to the cursor line, as code editors do. The paste is one step on the browser's
714
+ undo stack. `onPaste` sees every finding first and can cancel. For CodeMirror, Monaco or
715
+ `usePaste`, `pasteToCode(result)` returns the same `{ code, findings, fixed, remaining, danger }`.
716
+
717
+ **Security: code that runs differently from how it reads.** `inspectCode` reports, with
718
+ line, column and a label such as `U+202E RIGHT-TO-LEFT OVERRIDE`:
719
+
720
+ | Kind | Severity | What it catches |
721
+ | ---- | -------- | --------------- |
722
+ | `bidi-control` | danger | Trojan Source ([CVE-2021-42574](https://trojansource.codes/)): overrides and isolates that reorder how code is shown. Implicit marks are a warning |
723
+ | `invisible` | danger / warning | Hangul fillers that make invisible identifiers, and tag characters that hide ASCII (including hidden instructions in prompts) are danger. Zero-width spaces, joiners outside words and emoji, and runs of variation selectors that smuggle data are warnings |
724
+ | `mixed-script` | danger / warning | A Cyrillic or Greek letter inside a Latin word (`аdmin` with a Cyrillic `а`). A Latin lookalike is danger; another letter is a warning |
725
+ | `control` | warning | Control characters other than tab, line feed, carriage return and form feed, and Unicode line separators |
726
+ | `unusual-space` | warning | No-break, em, ideographic and similar spaces |
727
+ | `confusable-punctuation` | warning | Curly quotes, dashes, `…`, the Greek question mark that looks like `;`, full-width punctuation outside CJK text |
728
+
729
+ Joiners inside Arabic, Persian or Indic words and emoji, a single emoji variation
730
+ selector, and full-width punctuation in CJK comments are left alone. `cleanCode` applies
731
+ the safe replacement of every finding. It runs until nothing fixable is left, because
732
+ removing a zero-width space can expose a mixed word. It never guesses a letter that has no
733
+ Latin lookalike; those stay in `remaining`. Copying doesn't clean by default
734
+ (`clean: true` turns it on). Pasting does (`clean: false` turns it off).
735
+
736
+ ```ts
737
+ import { cleanCode, inspectCode, normalizeCode } from "react-smart-copy/code";
738
+
739
+ inspectCode(source).danger; // true for Trojan Source, lookalikes, invisible identifiers
740
+ cleanCode("const s = “hi”;").code; // 'const s = "hi";'
741
+ normalizeCode("$ npm i\nadded 1 package"); // "npm i" (also works on the server)
742
+ ```
743
+
744
+ Pasted code is never cut: past `maxLength` (2,000,000 characters) `pasteToCode` throws a
745
+ `too-large` error, and `pasteAsCode` leaves the paste to the browser. HTML is parsed
746
+ inertly and only its text is used.
747
+
748
+ | Option | Default | |
749
+ | ------ | ------- | - |
750
+ | `prompt` | `"auto"` copy, `false` paste | a style (`"shell"`, `"powershell"`, `"cmd"`, `"python"`, `"ipython"`, `"node"`), `{ command, continuation }` regexes, or `false` |
751
+ | `diff` | `false` | `"after"` or `"before"` |
752
+ | `lineNumbers` | `false` | remove typed line numbers that count up |
753
+ | `dedent` / `trimTrailingWhitespace` / `trimBlankLines` | `true` | |
754
+ | `lineEnding` / `finalNewline` | `"lf"` / `false` | |
755
+ | `clean` | `false` copy, `true` paste | `true`, `false` or a list of kinds |
756
+ | `html` / `language` (copy) | `true` / none | add the HTML flavour; `class="language-…"` on `<code>` |
757
+ | `indentToCursor` / `onPaste` (`pasteAsCode`) | `true` / none | |
758
+
678
759
  ## Only one "Copied" at a time
679
760
 
680
761
  Wrap a table or list in `<CopyGroup>`. A new successful copy returns the previously copied
@@ -1123,7 +1204,8 @@ embedded webviews. Where a capability is missing you get a typed error, never a
1123
1204
  - ~~**1.8** `useDragCopy` / `registerDragCopy` — populate `DataTransfer` on drag-start; no Clipboard API needed~~ shipped
1124
1205
  - ~~**1.9** `react-smart-copy/table` — Excel- and Sheets-ready copy and paste, AG Grid and TanStack Table adapters, typed record import~~ shipped
1125
1206
  - ~~**1.10** `react-smart-copy/structured` — typed, versioned, validated application data on the clipboard~~ shipped
1126
- - **1.11** `react-smart-copy/markdown` — paste rich content as Markdown, with undo intact
1207
+ - ~~**1.11** `react-smart-copy/markdown` — paste rich content as Markdown, with undo intact~~ shipped
1208
+ - **1.12** `react-smart-copy/code` — copy code blocks and sessions cleanly, paste code safely, detect Trojan Source and homoglyphs
1127
1209
 
1128
1210
  Full history: [CHANGELOG.md](./CHANGELOG.md) or the [Releases page](https://suprabhat02.github.io/react-smart-copy/#releases).
1129
1211