File size: 16,104 Bytes
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa1490a
cfd4ac1
 
bdac669
 
cfd4ac1
a83fcff
 
 
 
 
 
 
 
aa1490a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
cfd4ac1
 
 
 
 
 
 
 
 
 
 
bdac669
 
 
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
// ---------------------------------------------------------------------------------------------
// sheet/clipboardOps.ts β€” WHAT A COPY OUT OF THE SHEET IS MADE OF, LIFTED OUT OF `SheetGrid.tsx`.
//
// ⭐ WAVE 54 BASE KIT β€” a SEAM, not a redesign. The body below was moved verbatim out of
// `SheetGrid.tsx::heldFor`; the component keeps a one-line `useCallback` around it so both copy
// doors (the ribbon's button and glide's own native Ctrl+C) still share ONE builder and both
// dependency arrays are unchanged.
//
// ⭐⭐ AND `copySelection` HAS NOW FOLLOWED IT, WHICH THE NOTE ABOVE THIS ONE USED TO REFUSE. The
// refusal was right at the time and is worth keeping, because it names the trap: it closes over
// six pieces of component state (`viewRange`, `onNotice`, `heldFor`, `copiedRef`, `setCopyMarquee`
// and `clearSelection`), and `verify_grid_ux.py`'s copy-marquee leg asserted its marquee literal
// INSIDE `SheetGrid.tsx`, so moving it under a no-behaviour-change brief would have reddened a
// gate about a claim that was still true. Wave 54 re-aimed that leg to read THIS file instead: it
// asserts where the marquee is set FROM, which is a claim about the code, and the code moved. The
// six values are ARGUMENTS now, and the component keeps a `useCallback` whose dependency array is
// unchanged, exactly as it already does for `heldFor`.
//
// β›” AND `pasteCells` IS NOT HERE EITHER. It already lives in `sheetState.ts` and is imported from
// there by both paste doors; a second home for it would be a second answer to the same question.
// ---------------------------------------------------------------------------------------------

import type { CellRange } from "./sheetState";
// ⭐⭐ W54-T15: `rememberCopy` is the IN APP CLIPBOARD, and it lives in `sheetState.ts` beside
// the one paste engine that reads it. The import direction is this file -> `sheetState.ts`, which
// is the direction that already existed for `displayText`; the reverse would be a cycle.
import { editableText, pasteOptionsOf, rawDisplayText, rememberCopy, rememberCut } from "./sheetState";
import type { Cell, CellMap } from "./types";
import { formatCellText } from "./types";
import type { WholeAxis } from "./shortcuts";
import { wholeAxisOf } from "./shortcuts";

/** The three clipboard layers a paste command may apply. Normal is the full cell payload. */
export const PASTE_MODES = ["normal", "values", "formatting"] as const;
export type PasteMode = (typeof PASTE_MODES)[number];

/** Narrow a ribbon argument at the clipboard boundary; unknown arguments remain normal paste. */
export const pasteModeFrom = (value: unknown): PasteMode =>
  value === "values" || value === "formatting" ? value : "normal";

/** C8: every paste door names its layers through this one option list. */
export const PASTE_WHAT = [
  "all", "all-source-theme", "formulas", "all-except-borders", "values", "column-widths",
  "formats", "formulas-number-formats", "comments", "values-number-formats", "validation",
  "all-merging-cf", "keep-source-formatting", "values-source-formatting", "no-borders",
  "keep-source-column-widths",
] as const;
export const PASTE_OPERATIONS = ["none", "add", "subtract", "multiply", "divide"] as const;
export type PasteWhat = (typeof PASTE_WHAT)[number];
export type PasteOperation = (typeof PASTE_OPERATIONS)[number];
export type PasteOptions = {
  what: PasteWhat;
  operation?: PasteOperation;
  skipBlanks?: boolean;
  transpose?: boolean;
  link?: boolean;
};

/** Ribbon arguments retain the legacy aliases while accepting every C8 layer name. */
export const pasteOptionsFrom = (value: unknown): PasteOptions => {
  if (typeof value !== "string") return { what: "all" };
  if (PASTE_MODES.includes(value as PasteMode)) return pasteOptionsOf(value as PasteMode);
  return PASTE_WHAT.includes(value as PasteWhat) ? { what: value as PasteWhat } : { what: "all" };
};

export const MENU_PASTE_OPTIONS = {
  "paste": { what: "all" },
  "paste-values": { what: "values" },
  "paste-formulas": { what: "formulas" },
  "paste-formatting": { what: "formats" },
  "paste-transpose": { what: "all", transpose: true },
  "paste-link": { what: "all", link: true },
} satisfies Record<string, PasteOptions>;

export interface ClipboardPayload {
  text: string;
  values: string[][];
}

/** Prefer TSV; HTML-only clipboard tables retain their cell boundaries. */
export function parseClipboardPayload(text: string, html = ""): ClipboardPayload {
  if (!text && html) {
    const table = new DOMParser().parseFromString(html, "text/html").querySelector("table");
    if (table) {
      const values = Array.from(table.rows, (row) => Array.from(row.cells, (cell) => {
        // textContent works in the detached document; preserve explicit line breaks in a cell.
        cell.querySelectorAll("br").forEach((br) => br.replaceWith("\n"));
        return cell.textContent ?? "";
      }));
      if (values.length > 0) return { text: values.map((row) => row.join("\t")).join("\n"), values };
    }
  }
  return {
    text,
    values: text.replace(/\r\n/g, "\n").replace(/\n+$/, "")
      .split("\n").map((line) => line.split("\t")),
  };
}

/** The ribbon has no paste event, so read the same two formats from the browser. */
export async function readClipboardPayload(): Promise<ClipboardPayload> {
  if (navigator.clipboard.read) {
    try {
      const items = await navigator.clipboard.read();
      const plain = items.find((item) => item.types.includes("text/plain"));
      const text = plain ? await (await plain.getType("text/plain")).text() : "";
      if (text) return parseClipboardPayload(text);
      const rich = items.find((item) => item.types.includes("text/html"));
      return parseClipboardPayload(text, rich ? await (await rich.getType("text/html")).text() : "");
    } catch {
      // Some browsers expose read() but allow only readText().
    }
  }
  return parseClipboardPayload(await navigator.clipboard.readText());
}

/**
 * WHAT A COPY OF `range` PUTS ON THE CLIPBOARD, AND WHAT THE COMPONENT REMEMBERS ABOUT IT.
 *
 * ⭐ IT WRITES WHAT THE CELL READS, not what it stores: `formatCellText` over `displayText`, so
 * a currency cell arrives in Excel as the currency somebody chose. That is the same string
 * `displayData` carries, which is what makes glide's own Ctrl+C agree with the ribbon's button
 * β€” and it is why the two copy doors can share one builder at all.
 *
 * ⚠ THE FOUR DEPENDENCIES ARE ARGUMENTS RATHER THAN A CLOSURE, which is the whole of what this
 * extraction did. `cells` is the tab's map, `addrAt` is the ONE door from a view coordinate to an
 * A1 address, and `realCol`/`realRow` translate a VIEW index back to the sheet's own coordinates
 * β€” a hidden column would otherwise move the recorded top-left one column left with no error.
 *
 * ⭐⭐ W54-T15 β€” AND IT IS WHERE THE COPY IS REGISTERED, because it is the ONE builder BOTH copy
 * doors share. The ribbon's button goes through `runCopySelection`, but a NATIVE Ctrl+C is
 * answered by glide and reaches this component only as a DOM `copy` event, whose handler calls
 * this function and nothing else. Registering in `runCopySelection` therefore covered the button
 * alone, and a native copy pasted back with the destination's own formatting still on it.
 *
 * ⭐⭐ TWO KEYS, ONE BLOCK, AND BOTH ARE NEEDED. What goes on the OS clipboard is the FORMATTED
 * grid, because Excel must receive the currency somebody chose; but glide round trips its own
 * copy through a `text/html` payload carrying `getCellContent`'s `data`, which is
 * `editableText`. So the very same copy comes back as `1234.5` where it left as `$1,234.50`, and
 * a registry findable under only one of those two strings misses on exactly one of the two
 * doors. The EDITABLE grid is built here beside the formatted one, joined with the same tabs and
 * newlines, and {@link rememberCopy} files the block under both.
 *
 * ⚠ REGISTERING HERE MEANS A COPY IS REGISTERED EVEN IF THE CLIPBOARD WRITE LATER REFUSES. That
 * is deliberate and it is the native door's requirement: glide's own Ctrl+C hands this component
 * no promise to observe, so there is no later moment at which to register. The cost of being
 * wrong is one stale entry in a two entry registry that is only ever consulted by an exact text
 * match, which no other clipboard content can produce.
 */
export function buildCopyPayload(
  range: CellRange,
  cells: CellMap,
  addrAt: (col: number, row: number) => string,
  realCol: (view: number) => number,
  realRow: (view: number) => number,
  viewExtent?: { cols: number; rows: number },
): CopyPayload {
  const lines: string[] = [];
  // ⭐ W54-T15: the second key. `editableText` is what glide's own `data` round trip hands back.
  const editableLines: string[] = [];
  // ⭐ W51-T19: the CELLS are kept beside the text, so a bound cell pasted back into the sheet
  // can take its drag rules. See `copiedRef` for why the text alone cannot carry a binding.
  const block: (Cell | null)[][] = [];
  for (let r = Math.min(range.row0, range.row1); r <= Math.max(range.row0, range.row1); r += 1) {
    const line: string[] = [];
    const editLine: string[] = [];
    const row: (Cell | null)[] = [];
    for (let c = Math.min(range.col0, range.col1); c <= Math.max(range.col0, range.col1);
         c += 1) {
      const cell = cells[addrAt(c, r)] ?? null;
      // β›”β›” W54-T17: `rawDisplayText`, NEVER `displayText`. The IMPLICIT default number
      // format is a reading convenience on the canvas, not a value: a plain 1234.5 copied out
      // to Excel must arrive as 1234.5 and not as the rounded, grouped string a screen shows.
      // A format somebody EXPLICITLY chose still travels, because `formatCellText` applies it
      // here exactly as it always has.
      line.push(formatCellText(cell, rawDisplayText(cell)));
      editLine.push(editableText(cell));
      row.push(cell);
    }
    lines.push(line.join("\t"));
    editableLines.push(editLine.join("\t"));
    block.push(row);
  }
  const payload: CopyPayload = {
    text: lines.join("\n"),
    col: realCol(Math.min(range.col0, range.col1)),
    row: realRow(Math.min(range.row0, range.row1)),
    cells: block,
    editable: editableLines.join("\n"),
    wholeAxis: viewExtent ? wholeAxisOf(range, viewExtent) : null,
  };
  rememberCopy(payload);
  return payload;
}

/** What one copy out of the sheet is made of. `buildCopyPayload` returns exactly this shape. */
export interface CopyPayload {
  text: string;
  col: number;
  row: number;
  cells: (Cell | null)[][];
  /** W61-T09: both copy doors record this flag; paste reads it to choose the anchor.
   * The view extent matters: frozen/hidden bands must not turn a whole axis into a partial copy.
   */
  wholeAxis?: WholeAxis;
  /**
   * β›” W54-T15 β€” THE SECOND LOOKUP KEY, NEVER THE CLIPBOARD STRING. `text` stays the FORMATTED
   * grid: it is what is written to the OS clipboard for Excel, and it is what
   * `SheetGrid.tsx::copiedBlock` and `::isRecognizedCopy` compare against verbatim. This is the
   * same block rendered as `editableText`, which is the string glide's own `text/html` round trip
   * gives back to the paste door. Optional because only {@link buildCopyPayload} can build it.
   */
  editable?: string;
}

/** The copied rectangle, in the sheet's REAL coordinates: top left plus how many of each. */
export interface CopyMarquee {
  col: number;
  row: number;
  cols: number;
  rows: number;
}

/**
 * COPY, and CUT, which is a copy whose source goes away WHEN THE PASTE LANDS.
 *
 * β›” THE CLEAR ONLY HAPPENS IF THE COPY SUCCEEDED. A browser that refuses clipboard access on a
 * cut would otherwise delete a person's cells with nothing on the clipboard to paste back.
 *
 * ⭐⭐ W54-T16 β€” AND IT NO LONGER HAPPENS HERE AT ALL. Clearing at CUT time is the defect the
 * owner reported from both ends: the source cell was emptied of its value but kept its fill
 * colour, its borders and its database binding, so it still looked occupied; and a cut abandoned
 * with Escape had already destroyed the value with nothing pasted anywhere. The successful write
 * now ARMS the cut through `sheetState.ts::rememberCut`, and `sheetState.ts::pasteCells` removes
 * the source in the SAME edit set as the paste that completes it - one undo step, one save, and
 * an identity check on every source cell before a single one is removed.
 *
 * ⭐ WHAT IT PUTS ON THE CLIPBOARD IS `heldFor`'s, which glide's own Ctrl+C now records
 * through the same builder.
 *
 * ⚠ THE SIX DEPENDENCIES ARE ARGUMENTS RATHER THAN A CLOSURE, which is the whole of what the
 * wave-54 extraction did. `viewRange` is the selection as VIEW coordinates, `heldFor` is the one
 * copy builder both doors share, `copiedRef` is the component's memory of its own last copy,
 * `setCopyMarquee` paints it, `_clearSelection` used to be the cut's second half, and `onNotice`
 * is the one door every refusal in this feature speaks through.
 *
 * β›”β›” W54-T16 KEEPS THE SIXTH PARAMETER AND STOPS USING IT, WHICH IS DELIBERATE AND NOT A
 * LEFTOVER. `verify_grid_ux.py` pins the CALL SITE in `SheetGrid.tsx` as an exact string, and
 * that file belongs to another ticket this wave, so dropping the argument would redden a gate leg
 * from inside a file this one may not touch. `noUnusedParameters` is on, so the name carries a
 * leading underscore instead; the component keeps handing its selection clearer over, and the
 * next lane to touch that call site may retire both halves in one move.
 */
export function runCopySelection(
  cut: boolean,
  viewRange: () => CellRange | null,
  heldFor: (range: CellRange) => CopyPayload,
  copiedRef: { current: CopyPayload | null },
  setCopyMarquee: (rect: CopyMarquee | null) => void,
  _clearSelection: () => void,
  onNotice: (message: string) => void,
): void {
  const range = viewRange();
  if (!range) {
    onNotice(cut ? "Select a cell first, then cut it." : "Select a cell first, then copy it.");
    return;
  }
  // ⭐ W53-T03: the block and its text are built by `heldFor`, the ONE builder both copy doors
  // share, so a native Ctrl+C and this button can never record different things about the same
  // selection.
  const held = heldFor(range);
  const block = held.cells;
  const text = held.text;
  // β›” RECORDED ONLY ON A SUCCESSFUL WRITE, so the sheet never believes it holds a block the
  // clipboard does not. It is a SEPARATE `then` so that the cut stays the one line a
  // W51-T17 gate leg pins: a cut takes effect only after the copy landed, and folding
  // the two together would have moved that leg's anchor for no reason at all.
  navigator.clipboard.writeText(text)
    .then(() => {
      copiedRef.current = held;
      // ⭐⭐ W54-T15 / C2 β€” THE IN APP CLIPBOARD IS NOT REGISTERED HERE, AND THAT IS THE FIX
      // RATHER THAN AN OMISSION. `heldFor` is `buildCopyPayload`, which registers the block
      // itself under both of its keys, so this door is already covered; a second registration
      // from here would file the same block again through a parameter typed as the narrower
      // `CopyPayload`, and the de-duplication would then REPLACE the entry that carries the
      // editable key with one that may not. One registration, at the one shared builder.
      //
      // ⭐ W52-T07: a NEW copy/cut is the closest thing to "the clipboard changed" this app can
      // observe, so it replaces the marquee rather than requiring an Escape first.
      setCopyMarquee({ col: held.col, row: held.row, cols: block[0]?.length ?? 0,
                       rows: block.length });
    })
    // ⭐⭐ W54-T16: the cut is ARMED here and performed by the paste that completes it. On a
    // browser that refuses the write this `then` never runs, so nothing is armed, nothing is
    // deleted, and the catch below says so out loud.
    .then(() => { if (cut) rememberCut(held); })
    .catch(() => onNotice("This browser did not let the sheet write to the clipboard. "
                          + "Press Ctrl+C instead."));
}