Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

textPaste.ts

74 lines2.6 KB

1export const PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES = 32 * 1024;
2​
3const textEncoder = new TextEncoder();
4​
5export type PastedTextDisposition = "attachment" | "inline";
6​
7export function isPasteAsTextShortcut(
8 event: Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
9 macPlatform: boolean,
10): boolean {
11 return (
12 event.key.toLowerCase() === "v" &&
13 event.shiftKey &&
14 !event.altKey &&
15 (macPlatform ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey)
16 );
18​
19/**
20 * The threshold is byte-based: character counts substantially understate the
21 * context cost of some Unicode-heavy clipboard contents.
22 */
23export function pastedTextDisposition(input: {
24 readonly text: string;
25 readonly canAttach: boolean;
26 readonly bypassAutoAttachment?: boolean;
27 readonly wouldExceedInputLimit?: boolean;
28}): PastedTextDisposition {
29 if (input.bypassAutoAttachment || !input.canAttach || input.text.length === 0) {
30 return "inline";
31 }
32 return input.wouldExceedInputLimit ||
33 input.text.length >= PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES ||
34 textEncoder.encode(input.text).byteLength >= PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES
35 ? "attachment"
36 : "inline";
38​
39export function nextPastedTextFileName(existingNames: ReadonlyArray<string>): string {
40 const names = new Set(existingNames.map((name) => name.toLowerCase()));
41 if (!names.has("pasted-text.txt")) {
42 return "pasted-text.txt";
43 }
44 for (let sequence = 2; ; sequence += 1) {
45 const candidate = `pasted-text-${sequence}.txt`;
46 if (!names.has(candidate)) {
47 return candidate;
48 }
49 }
51​
52export function replaceTextSelection(input: {
53 readonly value: string;
54 readonly selection: { readonly start: number; readonly end: number };
55 readonly text: string;
56}): { readonly value: string; readonly cursor: number } {
57 const start = Math.max(0, Math.min(input.value.length, input.selection.start));
58 const end = Math.max(start, Math.min(input.value.length, input.selection.end));
59 return {
60 value: `${input.value.slice(0, start)}${input.text}${input.value.slice(end)}`,
61 cursor: start + input.text.length,
62 };
64​
65export function wouldTextPasteExceedLimit(input: {
66 readonly valueLength: number;
67 readonly selection: { readonly start: number; readonly end: number };
68 readonly textLength: number;
69 readonly maxLength: number;
70}): boolean {
71 const start = Math.max(0, Math.min(input.valueLength, input.selection.start));
72 const end = Math.max(start, Math.min(input.valueLength, input.selection.end));
73 return input.valueLength - (end - start) + input.textLength > input.maxLength;