From 0d5f254bf4a6f00debcbfc09868ad5e03523df6e Mon Sep 17 00:00:00 2001 From: Wei Wang Date: Thu, 19 Nov 2026 16:39:28 -0500 Subject: [PATCH 1/2] Read the clipboard at paste time, and empty it when its file closes A Cut or a Copy now keeps which entries it took, and a paste asks their document for them as they are then, the way the Data Explorer in MATLAB resolves its clipboard. An edit made between a Cut and its paste used to be lost: the paste wrote the value from the moment of the Cut and then removed the edited original. - Each document registers a reader beside its source deleter (registers.registerSourceReader). It finds each taken entry again by its origin token (a MAT-file variable), its uuid (a dictionary entry, through a rename), or its name in its section, and takes it again as a copy does (clipboardAction.readTaken). A cut's delete then names the entry as it is now, so a renamed original moves under its new name. - An entry no longer there is skipped and named: "Not pasted: ..." when others landed (also a warning), "Nothing to paste: ..." when none did, which empties the clipboard (transfer.goneMessage). - Closing a document's last table empties a clipboard taken from it, Copy or Cut, and tells every table (registers.closeSource). A cut no longer pastes after its source closed and leaves the original behind. - A MAT-file reload carries each uniquely named variable's token to the variable of that name, so a Copy made before an outside change still finds it. - A drag is unchanged: nothing can edit between its start and its drop. --- dist/model/edit/binaryView.js | 9 +- dist/model/edit/clipboardAction.d.ts | 37 ++++- dist/model/edit/clipboardAction.js | 85 +++++++++-- dist/model/edit/jsonView.js | 13 +- dist/model/edit/matEngine.d.ts | 14 +- dist/model/edit/matEngine.js | 76 +++++++++- dist/model/edit/registers.d.ts | 31 +++- dist/model/edit/registers.js | 23 ++- dist/model/edit/transfer.d.ts | 22 ++- dist/model/edit/transfer.js | 55 +++++++- dist/model/index.d.ts | 4 +- dist/model/index.js | 2 +- src/model/edit/binaryView.ts | 11 +- src/model/edit/clipboardAction.ts | 96 +++++++++++-- src/model/edit/jsonView.ts | 15 +- src/model/edit/matEngine.ts | 79 ++++++++++- src/model/edit/registers.ts | 59 +++++++- src/model/edit/transfer.ts | 70 +++++++-- src/model/index.ts | 3 + test/binaryEngine/clipboard.test.ts | 15 +- test/binaryEngine/lateCopy.test.ts | 126 +++++++++++++++++ test/jsonEngine/clipboard.test.ts | 50 +++---- test/jsonEngine/lateCopy.test.ts | 100 +++++++++++++ test/lateClipboard.test.ts | 203 +++++++++++++++++++++++++++ test/matEngine/clipboard.test.ts | 42 +++--- test/matEngine/lateCopy.test.ts | 122 ++++++++++++++++ test/matEngine/workspace.test.ts | 17 ++- test/shell/harness.ts | 10 +- test/shell/log.test.ts | 16 ++- test/shell/toasts.test.ts | 13 +- test/shell/undo.test.ts | 22 ++- 31 files changed, 1270 insertions(+), 170 deletions(-) create mode 100644 test/binaryEngine/lateCopy.test.ts create mode 100644 test/jsonEngine/lateCopy.test.ts create mode 100644 test/lateClipboard.test.ts create mode 100644 test/matEngine/lateCopy.test.ts diff --git a/dist/model/edit/binaryView.js b/dist/model/edit/binaryView.js index f5b72c1d..6eeba727 100644 --- a/dist/model/edit/binaryView.js +++ b/dist/model/edit/binaryView.js @@ -22,7 +22,7 @@ import { sourceWarnings, warningBanner } from '../rows/parseWarnings.js'; import { buildEntryRows, COLUMNS, COLUMN_GROUPS, COLUMN_LABELS } from '../rows/rowBuilder.js'; import { rowPlannerFor } from '../rows/rowPlanner.js'; import { SourceClosed, } from '../source/tableSource.js'; -import { copyEntriesToClipboard, dragEntries } from './clipboardAction.js'; +import { copyEntriesToClipboard, dragEntries, entriesUnder, readTaken } from './clipboardAction.js'; import { clipMarkChange, clipMarkOfDoc } from './clipMarks.js'; import { sectionTarget } from './dictionaryTarget.js'; import { answerEditTextRequest } from './editText.js'; @@ -84,6 +84,8 @@ export class BinaryView { drag: (descriptor) => this.emit({ kind: 'drag', descriptor }), }); registers.registerSourceDeleter(doc.uri, (targets) => this.deleteMoved(targets)); + // And so that a paste of what a Copy or a Cut took from it reads the entries as they are now. + registers.registerSourceReader(doc.uri, (items) => readTaken(items, { session: this.session, entries: () => entriesUnder(this.doc.liveModel()), describe: (m) => this.doc.describe(m) })); doc.views.add(this); } get session() { @@ -817,9 +819,10 @@ export class BinaryView { registers.clearDrag(); registers.broadcastDragState(); } - // Only once the LAST view of the document closes: both are the document's. + // Only once the LAST view of the document closes: both are the document's. A clipboard taken + // from it goes too (closeSource): there is nothing left to read it back from. if (this.doc.views.size === 0) { - registers.unregisterSourceDeleter(this.doc.uri); + registers.closeSource(this.doc.uri); this.doc.baseline.clear(); } } diff --git a/dist/model/edit/clipboardAction.d.ts b/dist/model/edit/clipboardAction.d.ts index 16170a70..768dc361 100644 --- a/dist/model/edit/clipboardAction.d.ts +++ b/dist/model/edit/clipboardAction.d.ts @@ -1,6 +1,6 @@ import { type Session } from 'data-explorer-core'; import type { ClipboardMode } from '../source/wire.js'; -import type { ClipboardItem, DragRegisterItem, Registers } from './registers.js'; +import type { ClipboardItem, DragRegisterItem, Registers, SourceRead } from './registers.js'; /** The part of core's session a snapshot asks. */ export type SnapshotSession = Pick; export interface CopyDeps { @@ -49,6 +49,11 @@ export declare class CopyRefused extends Error { * document. A detached entry, or one whose section has no name, is '' as it always was. */ export declare function sourceSectionOf(session: Pick, entry: any): string; +/** + * The entries of the document under `root`: the first nodes down each branch that are one (a + * MAT-file's children, a dictionary's sections' children). Nothing below an entry is one. + */ +export declare function entriesUnder(root: any): any[]; /** * Snapshot the rows a drag started on into the drag-register shape: the same walk, dedupe and * refusal as a copy, so "if you can cut/copy you can drag". Each item keeps its OWN source @@ -60,14 +65,42 @@ export declare function buildDragSnapshot(session: SnapshotSession, rowIds: unkn }; /** * Snapshot the rows a copy/cut acts on into the clipboard shape: the same walk and the same - * dedupe as buildDragSnapshot. Each item keeps its OWN source section: a cut is lazy, so the + * dedupe as buildDragSnapshot. What a paste lands is this snapshot read back from its document at + * paste time (readTaken), by who each entry was. Each item keeps its OWN source section: a cut is lazy, so the * source deletion at paste time must find each entry where it actually lives. */ export declare function buildClipboardSnapshot(session: SnapshotSession, rowIds: unknown, findNode: (rowId: string) => any, originOf?: (entry: any) => object | undefined): ClipboardItem[]; +/** What a document's reader needs of it to read back what a Copy or a Cut took (readTaken). */ +export interface ReadDeps { + /** Core's session, which the entries are asked of (copyRefusal) and resolved in. */ + session: SnapshotSession; + /** + * The document's entries as they are now, its model first brought up to date with its live + * content (a JSON dictionary re-parses its text): once per paste, however many entries it reads. + */ + entries: () => Iterable; + /** The token its document tells an entry by (CopyDeps.originOf), where its selectors cannot. */ + originOf?: (entry: any) => object | undefined; + /** Core's message in this document's words (a srcId said as the file's name). Default: as it is. */ + describe?: (message: string) => string; +} +/** + * The entries `held` took from this document, as they are now (registers.ts's SourceReader): each + * found again by who it was, then taken again as a copy takes it, so the paste lands what the user + * sees and a cut's delete names the entry as it is now. Who an entry was is its origin token where + * it was taken with one (a MAT-file's variable: through edits and a rename, the same node), else + * its uuid (a dictionary entry's, which a rename keeps), else its name in the section it was taken + * from. One found nowhere, deleted since, is named in `gone`. A refusal (an entry that can no + * longer travel, a model that no longer reads) throws TransferRefused, in this document's words. + */ +export declare function readTaken(held: readonly ClipboardItem[], deps: ReadDeps): SourceRead; /** * Snapshot every entry the rows resolve to onto the clipboard in `mode`. * * Rows are deduped by owning entry, so selecting a bus and two of its elements copies ONE bus. + * Copy and Cut alike are read back from their document when they are pasted (readTaken): the + * snapshot says which entries, and the paste lands them as they are then. + * * `uriString` is recorded with the payloads because a cut is LAZY — the source delete is deferred * to paste time, and the paste may land in a different document, so the clipboard must remember * which document to delete from. diff --git a/dist/model/edit/clipboardAction.js b/dist/model/edit/clipboardAction.js index 123ed3f5..8fcb26d5 100644 --- a/dist/model/edit/clipboardAction.js +++ b/dist/model/edit/clipboardAction.js @@ -13,7 +13,7 @@ // Everything format-specific is injected: `refresh` (bring the model up to date with the live // content) and `findNode` (resolve a row id against it) are the ONLY real difference between the // formats here, never what copying a row means. -import { entrySelectorOf, owningEntryOf } from 'data-explorer-core'; +import { TransferRefused, entrySelectorOf, owningEntryOf } from 'data-explorer-core'; import { dropFactsOf } from '../actions/dropFacts.js'; import { WHOLE_FILE_SECTION } from '../ids/sectionRowId.js'; import { sharedNameRefusal } from './transfer.js'; @@ -116,21 +116,29 @@ function entriesSharingAName(entries) { } return shared; } -// How many entries of the document under `root` answer to each name: its entries are the -// first nodes down each branch that are one (a MAT-file's children, a dictionary's sections' -// children). Nothing below an entry is one. +// How many entries of the document under `root` answer to each name. function entryNameCounts(root) { const counts = new Map(); + for (const entry of entriesUnder(root)) + counts.set(entry.name, (counts.get(entry.name) ?? 0) + 1); + return counts; +} +/** + * The entries of the document under `root`: the first nodes down each branch that are one (a + * MAT-file's children, a dictionary's sections' children). Nothing below an entry is one. + */ +export function entriesUnder(root) { + const entries = []; const visit = (node) => { for (const child of (node?.children ?? [])) { if (child?.isEntry) - counts.set(child.name, (counts.get(child.name) ?? 0) + 1); + entries.push(child); else visit(child); } }; visit(root); - return counts; + return entries; } /** * Each row's owning entry as a register item: what to paste, the section it came from, the @@ -139,7 +147,10 @@ function entryNameCounts(root) { * by. The one build behind both registers, after the one refusal they share. */ function registerItemsOf(session, rowIds, findNode, originOf) { - const entries = owningEntriesOf(rowIds, findNode); + return itemsOfEntries(session, owningEntriesOf(rowIds, findNode), originOf); +} +// The register items of `entries`, as a copy, a cut and a drag take them, after the refusal they share. +function itemsOfEntries(session, entries, originOf) { refuseUncopyable(session, entries); const shared = entriesSharingAName(entries); return entries.map((entry) => { @@ -164,16 +175,74 @@ export function buildDragSnapshot(session, rowIds, findNode, originOf) { } /** * Snapshot the rows a copy/cut acts on into the clipboard shape: the same walk and the same - * dedupe as buildDragSnapshot. Each item keeps its OWN source section: a cut is lazy, so the + * dedupe as buildDragSnapshot. What a paste lands is this snapshot read back from its document at + * paste time (readTaken), by who each entry was. Each item keeps its OWN source section: a cut is lazy, so the * source deletion at paste time must find each entry where it actually lives. */ export function buildClipboardSnapshot(session, rowIds, findNode, originOf) { return registerItemsOf(session, rowIds, findNode, originOf); } +/** + * The entries `held` took from this document, as they are now (registers.ts's SourceReader): each + * found again by who it was, then taken again as a copy takes it, so the paste lands what the user + * sees and a cut's delete names the entry as it is now. Who an entry was is its origin token where + * it was taken with one (a MAT-file's variable: through edits and a rename, the same node), else + * its uuid (a dictionary entry's, which a rename keeps), else its name in the section it was taken + * from. One found nowhere, deleted since, is named in `gone`. A refusal (an entry that can no + * longer travel, a model that no longer reads) throws TransferRefused, in this document's words. + */ +export function readTaken(held, deps) { + const said = (message) => (deps.describe ? deps.describe(message) : message); + let live; + try { + live = [...deps.entries()]; + } + catch (err) { + throw new TransferRefused(said(`Could not read the copied entries again: ${err?.message || String(err)}`)); + } + const byOrigin = new Map(); + const byUuid = new Map(); + for (const entry of live) { + const origin = deps.originOf?.(entry); + if (origin) + byOrigin.set(origin, entry); + const { uuid } = entrySelectorOf(entry); + if (uuid) + byUuid.set(uuid, [...(byUuid.get(uuid) ?? []), entry]); + } + const sameAsTaken = (it, entry) => entry.name === it.payload.name && sourceSectionOf(deps.session, entry) === it.sourceSection; + const found = []; + const gone = []; + for (const it of held) { + const { uuid } = entrySelectorOf(it.payload); + let entry; + if (it.origin) + entry = byOrigin.get(it.origin); + else if (uuid) { + const withUuid = byUuid.get(uuid) ?? []; + entry = withUuid.length === 1 ? withUuid[0] : withUuid.find((e) => sameAsTaken(it, e)); + } + else + entry = live.find((e) => sameAsTaken(it, e)); + if (!entry) + gone.push(String(it.payload.name ?? '')); + else if (!found.includes(entry)) + found.push(entry); + } + try { + return { items: itemsOfEntries(deps.session, found, deps.originOf), gone }; + } + catch (err) { + throw new TransferRefused(said(err instanceof CopyRefused ? err.message : `Failed to paste: ${err?.message || String(err)}`)); + } +} /** * Snapshot every entry the rows resolve to onto the clipboard in `mode`. * * Rows are deduped by owning entry, so selecting a bus and two of its elements copies ONE bus. + * Copy and Cut alike are read back from their document when they are pasted (readTaken): the + * snapshot says which entries, and the paste lands them as they are then. + * * `uriString` is recorded with the payloads because a cut is LAZY — the source delete is deferred * to paste time, and the paste may land in a different document, so the clipboard must remember * which document to delete from. diff --git a/dist/model/edit/jsonView.js b/dist/model/edit/jsonView.js index 130b4831..03e6aeb0 100644 --- a/dist/model/edit/jsonView.js +++ b/dist/model/edit/jsonView.js @@ -27,7 +27,7 @@ import { buildEntryRows, COLUMNS, COLUMN_GROUPS, COLUMN_LABELS } from '../rows/r import { rowPlannerFor } from '../rows/rowPlanner.js'; import { SourceClosed, } from '../source/tableSource.js'; import { parseDetached } from '../workspace/SlddModel.js'; -import { copyEntriesToClipboard, dragEntries } from './clipboardAction.js'; +import { copyEntriesToClipboard, dragEntries, entriesUnder, readTaken } from './clipboardAction.js'; import { clipMarkChange, clipMarkOfDoc } from './clipMarks.js'; import { sectionTarget } from './dictionaryTarget.js'; import { answerEditTextRequest } from './editText.js'; @@ -132,6 +132,9 @@ export class JsonView { drag: (descriptor) => this.emit({ kind: 'drag', descriptor }), })); registers.registerSourceDeleter(this.uri, (targets) => doc.writes.enqueue(() => this.deleteFromSourceDocument(targets))); + // And so that a paste of what a Copy or a Cut took from it reads the entries from the text as + // it stands then, whichever writer last changed it. + registers.registerSourceReader(this.uri, (items) => readTaken(items, { session: this.session, entries: () => entriesUnder(this.liveModel()), describe: (m) => this.doc.describe(m) })); // Every tab of this document repaints wide when the baseline moves (repaintAll). this.docState.repaints.add(this.repaintThis); // Repaint on ANY change to the text: this table's edits, a text view's, undo and redo. @@ -982,7 +985,8 @@ export class JsonView { copyEntriesToClipboard(rowIds, 'copy', this.uri, this.copyDeps(() => this.doc.options.registers.broadcastClipboardState())); } // Cut is LAZY: it only marks the entry on the clipboard and writes nothing. The source is removed - // at PASTE time, so a same-document move is a single write (one undo step). + // at PASTE time, so a same-document move is a single write (one undo step), and what moves is + // the entry as the text holds it then (the registered reader). cut(rowIds) { if (this.disposed) return; @@ -1554,9 +1558,10 @@ export class JsonView { done?.(true); // Per table, paired with the open: the last one drops the tree it held. this.doc.registry.releaseSourceView(this.uri); - // Only once the LAST table of this document closes. + // Only once the LAST table of this document closes, and a clipboard taken from it with it + // (closeSource): there is nothing left to read it back from. if (this.doc.closeView(this.docState)) { - registers.unregisterSourceDeleter(this.uri); + registers.closeSource(this.uri); this.doc.baseline.clear(); } } diff --git a/dist/model/edit/matEngine.d.ts b/dist/model/edit/matEngine.d.ts index 6d0bc9d1..b2df40ea 100644 --- a/dist/model/edit/matEngine.d.ts +++ b/dist/model/edit/matEngine.d.ts @@ -204,11 +204,18 @@ export declare class MatEngine { * the answer. */ private deleteMoved; + /** + * The variables a Copy or a Cut took from this file, as they are now, for a paste of them (the + * registers' source reader): each found by the token it was taken with (`originOf`), among the + * nodes `deleteMoved` would take it from, so the paste and a cut's delete find the same one. + */ + private readTaken; /** * The token a cut or a drag of `variable` carries (TransferItem.origin), which `deleteMoved` * tells the original by: one object for as long as the variable is the same node — through - * edits of it, a rename, and the undo of its delete, which puts the node itself back. A variable - * made since (an Add, a paste, a reload of the file) is another node, with another token. + * edits of it, a rename, and the undo of its delete, which puts the node itself back — and, + * through a reload of the file, for the variable the file still holds under its name + * (`carryTokens`). A variable made since (an Add, a paste) is another node, with another token. */ private originOf; private readonly origins; @@ -226,6 +233,9 @@ export declare class MatEngine { * every view is painted from it. */ replace(bytes: ArrayBuffer): Promise; + private uniquelyNamed; + private tokensByName; + private carryTokens; /** A table of the document: an EditableTableSource, until its `dispose()`. */ view(): EditableTableSource & { dispose(): void; diff --git a/dist/model/edit/matEngine.js b/dist/model/edit/matEngine.js index 841d3489..58c71dc6 100644 --- a/dist/model/edit/matEngine.js +++ b/dist/model/edit/matEngine.js @@ -51,7 +51,7 @@ import { refuseIfUnreadable, sourceWarnings, warningBanner } from '../rows/parse import { COLUMNS, COLUMN_GROUPS, COLUMN_LABELS } from '../rows/rowBuilder.js'; import { rowPlannerFor } from '../rows/rowPlanner.js'; import { SourceClosed, } from '../source/tableSource.js'; -import { copyEntriesToClipboard, dragEntries } from './clipboardAction.js'; +import { copyEntriesToClipboard, dragEntries, readTaken } from './clipboardAction.js'; import { clipMarkChange, clipMarkOfDoc } from './clipMarks.js'; import { answerEditTextRequest } from './editText.js'; import { addChildRefusal, addEntryRefusal, deleteRefusal, describeSource, refusedChange } from './refusal.js'; @@ -220,6 +220,7 @@ export class MatEngine { record: (label, run, touched) => this.record(label, run, touched), originOf: (variable) => this.originOf(variable), deleteMoved: (targets) => this.deleteMoved(targets), + readTaken: (items) => this.readTaken(items), notify: (level, message, ms) => this.notify(level, message, ms), }; } @@ -526,11 +527,25 @@ export class MatEngine { return { removed: false, reason: this.describe(observed.error) }; return { removed: false, reason: 'the file did not let it be removed' }; } + /** + * The variables a Copy or a Cut took from this file, as they are now, for a paste of them (the + * registers' source reader): each found by the token it was taken with (`originOf`), among the + * nodes `deleteMoved` would take it from, so the paste and a cut's delete find the same one. + */ + readTaken(items) { + return readTaken(items, { + session: this.session, + entries: () => [...this.model().children, ...(this.file.movedOut?.(this.root()) ?? [])], + originOf: (variable) => this.originOf(variable), + describe: (message) => this.describe(message), + }); + } /** * The token a cut or a drag of `variable` carries (TransferItem.origin), which `deleteMoved` * tells the original by: one object for as long as the variable is the same node — through - * edits of it, a rename, and the undo of its delete, which puts the node itself back. A variable - * made since (an Add, a paste, a reload of the file) is another node, with another token. + * edits of it, a rename, and the undo of its delete, which puts the node itself back — and, + * through a reload of the file, for the variable the file still holds under its name + * (`carryTokens`). A variable made since (an Add, a paste) is another node, with another token. */ originOf(variable) { let token = this.origins.get(variable); @@ -619,6 +634,7 @@ export class MatEngine { * every view is painted from it. */ replace(bytes) { + const held = this.loaded && !('error' in this.loaded) ? this.tokensByName() : null; this.session.removeDataSource(this.srcId); this.bytes = bytes; this.loaded = null; @@ -629,12 +645,56 @@ export class MatEngine { // tree. A file that no longer reads says so at the paint. try { this.model(); + if (held) + this.carryTokens(held); } catch { /* reported by the paint */ } return this.repaintAll(); } + // The variables (and the nodes beside them) a reload makes again, each list's by name: only a + // name one node answers to in the list, since two of one name cannot be told apart. + uniquelyNamed() { + const lists = [this.model().children, [...(this.file.movedOut?.(this.root()) ?? [])]]; + return lists.map((nodes) => { + const byName = new Map(); + const twice = new Set(); + for (const node of nodes) { + if (byName.has(node.name)) + twice.add(node.name); + byName.set(node.name, node); + } + for (const name of twice) + byName.delete(name); + return byName; + }); + } + // The tokens the uniquely-named nodes carry before a reload, by name. + tokensByName() { + return this.uniquelyNamed().map((byName) => { + const tokens = new Map(); + for (const [name, node] of byName) { + const token = this.origins.get(node); + if (token) + tokens.set(name, token); + } + return tokens; + }); + } + // A reload reads the file's variables again as new nodes: each takes the token the one of its + // name had (`originOf`), so a Copy or a Cut made before an outside change still finds the + // variable of that name in the file as it is now. A name two nodes answer to, before or after, + // takes none. + carryTokens(held) { + this.uniquelyNamed().forEach((byName, i) => { + for (const [name, token] of held[i] ?? []) { + const node = byName.get(name); + if (node) + this.origins.set(node, token); + } + }); + } /** A table of the document: an EditableTableSource, until its `dispose()`. */ view() { return new MatView(this.document); @@ -703,8 +763,11 @@ class MatView { }, drag: (descriptor) => this.emit({ kind: 'drag', descriptor }), }); - if (doc.views.size === 0) + if (doc.views.size === 0) { registers.registerSourceDeleter(doc.uri, (targets) => doc.deleteMoved(targets)); + // And reads back, at a paste, the variables a Copy or a Cut took from it, as they are then. + registers.registerSourceReader(doc.uri, (items) => doc.readTaken(items)); + } doc.views.add(this); } get session() { @@ -1441,8 +1504,9 @@ class MatView { registers.clearDrag(); registers.broadcastDragState(); } - // The deleter is the document's, so it stays while any view of it does. + // The deleter and the reader are the document's, so they stay while any view of it does, and a + // clipboard taken from it goes with the last (closeSource): nothing is left to read it from. if (this.doc.views.size === 0) - registers.unregisterSourceDeleter(this.doc.uri); + registers.closeSource(this.doc.uri); } } diff --git a/dist/model/edit/registers.d.ts b/dist/model/edit/registers.d.ts index 8834c9a0..28b316c6 100644 --- a/dist/model/edit/registers.d.ts +++ b/dist/model/edit/registers.d.ts @@ -40,6 +40,22 @@ export type DeleteTarget = string | SourceSelector; * (transfer.ts) reports the answer on its own view, which is the one where the gesture happened. */ export type SourceDeleter = (targets: DeleteTarget[]) => Promise | SourceDeleteResult; +/** What a document's reader found of the entries a Copy or a Cut took from it. */ +export interface SourceRead { + /** Each entry still there, as it is now, in the order taken. */ + items: ClipboardItem[]; + /** The names of the entries no longer there, as they were taken. */ + gone: string[]; +} +/** + * How one open document reads back the entries a Copy or a Cut took from it, as they are NOW: the + * paste's half of a lazy clipboard. Each item is found again by who it was (its uuid, its origin + * token, or its name in its section) and taken again as a copy takes it, so a paste lands the + * value the user sees, and a cut's delete names the entry as it is now. Synchronous, because a + * paste reads its register before it changes anything. Throws TransferRefused for an entry that + * cannot travel any more, in the words a copy would refuse it in. + */ +export type SourceReader = (items: readonly ClipboardItem[]) => SourceRead; /** * A deleter's reason when nothing in its document answers to the names it was given any more: * renamed or deleted since the cut. One spelling for every format, because it is one fact. @@ -110,12 +126,21 @@ export interface Registers { /** How the document `uriString` removes entries from itself, for a move out of it. */ registerSourceDeleter(uriString: string, fn: SourceDeleter): void; unregisterSourceDeleter(uriString: string): void; + /** How the document `uriString` reads back the entries a Copy or a Cut took from it (SourceReader). */ + registerSourceReader(uriString: string, fn: SourceReader): void; + /** + * The document `uriString` closed (its last table did): its deleter and its reader go, and a + * clipboard taken from it, Copy or Cut, is emptied, and every table told. Nothing is left to + * read the entries from, and a cut's original can no longer be taken out, as the Data Explorer + * in MATLAB empties its clipboard when its source closes. + */ + closeSource(uriString: string): void; /** * Complete the source-delete half of a cross-document move, and say whether it happened. * - * During a drag the source view is open (closing it ends the drag), so its deleter is here. A - * CUT is different: it is lazy, so its source may have been closed between the cut and the - * paste, and then there is no deleter — and no format-appropriate way to edit the file — so the + * During a drag the source view is open (closing it ends the drag), and a cut's source is open + * too: closing it empties the clipboard the cut is on (closeSource). A document that never + * registered a deleter has none, and no format-appropriate way to edit the file, so the * original stays where it is: an answer the caller reports. * * A deleter that throws still throws: the caller (transfer.ts) turns that into the same report. diff --git a/dist/model/edit/registers.js b/dist/model/edit/registers.js index 9dcbbff0..843ba503 100644 --- a/dist/model/edit/registers.js +++ b/dist/model/edit/registers.js @@ -24,6 +24,7 @@ export function createRegisters() { let clipboard = null; let drag = null; const sourceDeleters = new Map(); + const sourceReaders = new Map(); const listeners = new Set(); const getClipboard = () => clipboard; const clearClipboard = () => { @@ -98,9 +99,18 @@ export function createRegisters() { let held = null; return { kind: 'clipboard', + // As the entries are now, where their document reads them back (SourceReader); as they + // were taken where none does, which no open document is without. read() { held = getClipboard(); - return held && { items: held.items, sourceDocUri: held.sourceDocUri, move: held.mode === 'cut' }; + if (!held) + return null; + const move = held.mode === 'cut'; + const reader = held.sourceDocUri === undefined ? undefined : sourceReaders.get(held.sourceDocUri); + if (!reader) + return { items: held.items, sourceDocUri: held.sourceDocUri, move }; + const now = reader(held.items); + return { items: now.items, sourceDocUri: held.sourceDocUri, move, gone: now.gone }; }, clear() { if (held && getClipboard() === held) @@ -129,6 +139,17 @@ export function createRegisters() { unregisterSourceDeleter(uriString) { sourceDeleters.delete(uriString); }, + registerSourceReader(uriString, fn) { + sourceReaders.set(uriString, fn); + }, + closeSource(uriString) { + sourceDeleters.delete(uriString); + sourceReaders.delete(uriString); + if (clipboard?.sourceDocUri !== uriString) + return; + clearClipboard(); + broadcastClipboardState(); + }, async deleteFromSource(uriString, targets) { const fn = sourceDeleters.get(uriString); if (!fn) diff --git a/dist/model/edit/transfer.d.ts b/dist/model/edit/transfer.d.ts index 892c41be..e47da2d6 100644 --- a/dist/model/edit/transfer.d.ts +++ b/dist/model/edit/transfer.d.ts @@ -32,6 +32,11 @@ export interface TransferContents { sourceDocUri: string | undefined; /** The source is to lose them: a cut, or a drop in move mode. */ move: boolean; + /** + * The names of the entries taken that their document no longer holds, by the time a paste read + * them back (registers.ts's SourceReader): skipped, and named to the user. Absent: none. + */ + gone?: readonly string[]; } /** * Where a transfer's items come from, and how it lets go of them. @@ -181,10 +186,19 @@ export type TransferOutcome = { kind: 'failed'; error: unknown; } -/** Landed. `sourceKept` is the message reported when a move's source delete did not happen. */ +/** Every entry the clipboard took is gone from its document: nothing pasted, and `message` said. */ + | { + kind: 'gone'; + message: string; +} +/** + * Landed. `sourceKept` is the message reported when a move's source delete did not happen, and + * `skipped` the one naming the entries no longer there to paste (TransferContents.gone). + */ | { kind: 'done'; sourceKept?: string; + skipped?: string; }; /** * Whether moving `contents` onto `sectionName` of `docUri` would change nothing: every item @@ -209,6 +223,12 @@ export declare function runTransfer(req: TransferReque * same words, because it is the same rule. */ export declare function sharedNameRefusal(verb: 'cut' | 'move', name: string, sourceDocUri: string | undefined): string; +/** + * 'Not pasted: "x" is no longer in a.sldd.' — the entries a Copy or a Cut took that their document + * no longer holds by the paste (TransferContents.gone), the first five by name. `nothingLeft` + * when no other entry was pasted either: 'Nothing to paste: "x" and "y" are no longer in a.sldd.' + */ +export declare function goneMessage(names: readonly string[], sourceDocUri: string | undefined, nothingLeft: boolean): string; /** * "Pasted here, but the original in a.sldd could not be removed: . Remove it there by * hand." — accurate about both halves: the paste DID land, and nothing was rolled back. Or, where diff --git a/dist/model/edit/transfer.js b/dist/model/edit/transfer.js index 57783a21..59c1d094 100644 --- a/dist/model/edit/transfer.js +++ b/dist/model/edit/transfer.js @@ -86,11 +86,28 @@ async function transfer(req, register, adapter, deps) { const isPaste = register.kind === 'clipboard'; if (adapter.guard && !adapter.guard()) return { kind: 'guarded' }; - const contents = register.read(); + let contents; + try { + // A paste's register reads its entries back from their document here, which can refuse one. + contents = register.read(); + } + catch (err) { + return refusedOrFailed(err, adapter); + } + const gone = contents?.gone ?? []; + if (contents && contents.items.length === 0 && gone.length > 0) { + // Nothing the clipboard took is left to paste, now or on another try. + const message = goneMessage(gone, contents.sourceDocUri, true); + adapter.report(message); + register.clear(); + register.broadcast(); + return { kind: 'gone', message }; + } if (!contents || contents.items.length === 0) { adapter.report(isPaste ? 'Nothing to paste — the clipboard is empty.' : 'Nothing to drop.'); return { kind: 'empty' }; } + const skipped = gone.length > 0 ? goneMessage(gone, contents.sourceDocUri, false) : undefined; const replacing = req.replacing ?? []; let target; try { @@ -143,10 +160,21 @@ async function transfer(req, register, adapter, deps) { catch (err) { return refusedOrFailed(err, adapter); } - // Landed. Everything below is the source's half of a cross-document move, and none of it - // may undo or repaint what just happened here. + // Landed. Said where it landed, and where it stays until dismissed: the paste's repaint clears + // a banner, and an entry the user expected that never came is the outcome this is for. + if (skipped) { + adapter.report(skipped); + deps.warn?.(skipped); + } + const done = (sourceKept) => ({ + kind: 'done', + ...(sourceKept ? { sourceKept } : {}), + ...(skipped ? { skipped } : {}), + }); + // Everything below is the source's half of a cross-document move, and none of it may undo or + // repaint what just happened here. if (!contents.move) - return { kind: 'done' }; + return done(); // Consumed by the paste that just landed, whatever the source delete does next: a cut left // live would paste the same entries a second time. Cleared BEFORE the delete is awaited, so // a second Paste arriving meanwhile finds nothing to paste rather than this cut again. @@ -154,14 +182,14 @@ async function transfer(req, register, adapter, deps) { register.clear(); try { if (sameDoc || selectors.length === 0) - return { kind: 'done' }; + return done(); const result = await sourceDelete(contents.sourceDocUri, selectors, deps); if (result.removed) - return { kind: 'done' }; + return done(); const message = sourceKeptMessage(isPaste, contents.sourceDocUri, selectors.length, result.reason, result.gone === true); adapter.report(message); deps.warn?.(message); - return { kind: 'done', sourceKept: message }; + return done(message); } finally { if (isPaste) @@ -198,6 +226,19 @@ export function sharedNameRefusal(verb, name, sourceDocUri) { const where = sourceDocUri ? fileNameOf(sourceDocUri) : 'its file'; return `Cannot ${verb} "${name}": ${where} holds more than one "${name}", and a move takes its original out by name. Copy it instead.`; } +/** + * 'Not pasted: "x" is no longer in a.sldd.' — the entries a Copy or a Cut took that their document + * no longer holds by the paste (TransferContents.gone), the first five by name. `nothingLeft` + * when no other entry was pasted either: 'Nothing to paste: "x" and "y" are no longer in a.sldd.' + */ +export function goneMessage(names, sourceDocUri, nothingLeft) { + const shown = names.slice(0, 5).map((n) => `"${n}"`); + const more = names.length - shown.length; + const listed = more > 0 ? `${shown.join(', ')} and ${more} more` : shown.length > 1 ? `${shown.slice(0, -1).join(', ')} and ${shown.at(-1)}` : shown[0]; + const where = sourceDocUri ? fileNameOf(sourceDocUri) : 'their file'; + const lead = nothingLeft ? 'Nothing to paste' : 'Not pasted'; + return `${lead}: ${listed} ${names.length === 1 ? 'is' : 'are'} no longer in ${where}.`; +} /** * "Pasted here, but the original in a.sldd could not be removed: . Remove it there by * hand." — accurate about both halves: the paste DID land, and nothing was rolled back. Or, where diff --git a/dist/model/index.d.ts b/dist/model/index.d.ts index 4e149850..aba2df1e 100644 --- a/dist/model/index.d.ts +++ b/dist/model/index.d.ts @@ -105,8 +105,8 @@ export type { MessageSourceOptions } from './source/messageSource.js'; export type { AddChildMessage, AddEntryMessage, BeginRenameMessage, ChildRowsMessage, ClipboardMode, ClipboardStateMessage, CopyMessage, CutMessage, DeleteMessage, DragDescriptor, DragEndMessage, DragStartMessage, DragStateMessage, DropMessage, EditMessage, EditTextMessage, EmptyMessage, ErrorMessage, FolderAnswerMessage, FolderAsk, FolderChangedMessage, FolderClientMessage, FolderHostMessage, FolderRequestMessage, InsertEntryRowsMessage, MatrixCellsMessage, PasteMessage, ReadyMessage, RefusedMessage, RequestChildrenMessage, RequestEditTextMessage, SetActiveConfigSetMessage, RequestMatrixMessage, SectionRulesMessage, SelectMessage, SelectRowsMessage, SetRowsMessage, ShowPropsMessage, TableClientMessage, TableEditClientMessage, TableEditHostMessage, TableHostMessage, TablePort, UndoRedoMessage, UpdateEntryRowsMessage, ValidationErrorMessage, } from './source/wire.js'; export type { Notice, Notify } from './edit/hooks.js'; export { NOT_FOUND_REASON, createRegisters } from './edit/registers.js'; -export type { ClipboardBroadcast, ClipboardEntry, ClipboardItem, DeleteTarget, DragEntry, DragRegisterItem, RegisterListener, Registers, SourceDeleter, } from './edit/registers.js'; -export { TransferRefused, isNoopMove as isNoopTransfer, runTransfer, sharedNameRefusal, sourceKeptMessage, } from './edit/transfer.js'; +export type { ClipboardBroadcast, ClipboardEntry, ClipboardItem, DeleteTarget, DragEntry, DragRegisterItem, RegisterListener, Registers, SourceDeleter, SourceRead, SourceReader, } from './edit/registers.js'; +export { TransferRefused, goneMessage, isNoopMove as isNoopTransfer, runTransfer, sharedNameRefusal, sourceKeptMessage, } from './edit/transfer.js'; export type { SourceDeleteResult, SourceSelector, TransferAdapter, TransferCommit, TransferContents, TransferDeps, TransferItem, TransferLabel, TransferOutcome, TransferRegister, TransferRequest, TransferTarget, } from './edit/transfer.js'; export { REFUSAL_TITLES, addChildRefusal, addEntryRefusal, deleteRefusal, describeSource, refusedChange } from './edit/refusal.js'; export type { RefusalSession, RefusedGesture } from './edit/refusal.js'; diff --git a/dist/model/index.js b/dist/model/index.js index 8f107fd7..ed9ee130 100644 --- a/dist/model/index.js +++ b/dist/model/index.js @@ -111,7 +111,7 @@ export { inspectorFeed, messageSource } from './source/messageSource.js'; export { NOT_FOUND_REASON, createRegisters } from './edit/registers.js'; // transfer.ts's isNoopMove, the host's half of the rule the drop predictor's isNoopMove answers // (above), under a name of its own. -export { TransferRefused, isNoopMove as isNoopTransfer, runTransfer, sharedNameRefusal, sourceKeptMessage, } from './edit/transfer.js'; +export { TransferRefused, goneMessage, isNoopMove as isNoopTransfer, runTransfer, sharedNameRefusal, sourceKeptMessage, } from './edit/transfer.js'; export { REFUSAL_TITLES, addChildRefusal, addEntryRefusal, deleteRefusal, describeSource, refusedChange } from './edit/refusal.js'; export { answerEditTextRequest } from './edit/editText.js'; // A folder across a message channel, for a hierarchy where its files are not: the page's end diff --git a/src/model/edit/binaryView.ts b/src/model/edit/binaryView.ts index 6ec75647..f51f4213 100644 --- a/src/model/edit/binaryView.ts +++ b/src/model/edit/binaryView.ts @@ -72,7 +72,7 @@ import { type TableView, } from '../source/tableSource.js'; import type { BinaryDocument, ModelSource } from './binaryEngine.js'; -import { copyEntriesToClipboard, dragEntries, type CopyDeps } from './clipboardAction.js'; +import { copyEntriesToClipboard, dragEntries, entriesUnder, readTaken, type CopyDeps } from './clipboardAction.js'; import { clipMarkChange, clipMarkOfDoc } from './clipMarks.js'; import { sectionTarget, type SectionTarget } from './dictionaryTarget.js'; import { answerEditTextRequest } from './editText.js'; @@ -135,6 +135,10 @@ export class BinaryView implements EditableTableSource { drag: (descriptor) => this.emit({ kind: 'drag', descriptor }), }); registers.registerSourceDeleter(doc.uri, (targets) => this.deleteMoved(targets)); + // And so that a paste of what a Copy or a Cut took from it reads the entries as they are now. + registers.registerSourceReader(doc.uri, (items) => + readTaken(items, { session: this.session, entries: () => entriesUnder(this.doc.liveModel()), describe: (m) => this.doc.describe(m) }), + ); doc.views.add(this); } @@ -889,9 +893,10 @@ export class BinaryView implements EditableTableSource { registers.clearDrag(); registers.broadcastDragState(); } - // Only once the LAST view of the document closes: both are the document's. + // Only once the LAST view of the document closes: both are the document's. A clipboard taken + // from it goes too (closeSource): there is nothing left to read it back from. if (this.doc.views.size === 0) { - registers.unregisterSourceDeleter(this.doc.uri); + registers.closeSource(this.doc.uri); this.doc.baseline.clear(); } } diff --git a/src/model/edit/clipboardAction.ts b/src/model/edit/clipboardAction.ts index 24cf0764..de3d45b8 100644 --- a/src/model/edit/clipboardAction.ts +++ b/src/model/edit/clipboardAction.ts @@ -13,11 +13,11 @@ // Everything format-specific is injected: `refresh` (bring the model up to date with the live // content) and `findNode` (resolve a row id against it) are the ONLY real difference between the // formats here, never what copying a row means. -import { entrySelectorOf, owningEntryOf, type Session } from 'data-explorer-core'; +import { TransferRefused, entrySelectorOf, owningEntryOf, type Session } from 'data-explorer-core'; import { dropFactsOf } from '../actions/dropFacts.js'; import { WHOLE_FILE_SECTION } from '../ids/sectionRowId.js'; import type { ClipboardMode } from '../source/wire.js'; -import type { ClipboardItem, DragRegisterItem, Registers } from './registers.js'; +import type { ClipboardItem, DragRegisterItem, Registers, SourceRead } from './registers.js'; import { sharedNameRefusal } from './transfer.js'; /** The part of core's session a snapshot asks. */ @@ -142,19 +142,27 @@ function entriesSharingAName(entries: readonly any[]): Set { return shared; } -// How many entries of the document under `root` answer to each name: its entries are the -// first nodes down each branch that are one (a MAT-file's children, a dictionary's sections' -// children). Nothing below an entry is one. +// How many entries of the document under `root` answer to each name. function entryNameCounts(root: any): Map { const counts = new Map(); + for (const entry of entriesUnder(root)) counts.set(entry.name, (counts.get(entry.name) ?? 0) + 1); + return counts; +} + +/** + * The entries of the document under `root`: the first nodes down each branch that are one (a + * MAT-file's children, a dictionary's sections' children). Nothing below an entry is one. + */ +export function entriesUnder(root: any): any[] { + const entries: any[] = []; const visit = (node: any) => { for (const child of (node?.children ?? []) as any[]) { - if (child?.isEntry) counts.set(child.name, (counts.get(child.name) ?? 0) + 1); + if (child?.isEntry) entries.push(child); else visit(child); } }; visit(root); - return counts; + return entries; } /** @@ -169,7 +177,11 @@ function registerItemsOf( findNode: (rowId: string) => any, originOf?: (entry: any) => object | undefined, ): ClipboardItem[] { - const entries = owningEntriesOf(rowIds, findNode); + return itemsOfEntries(session, owningEntriesOf(rowIds, findNode), originOf); +} + +// The register items of `entries`, as a copy, a cut and a drag take them, after the refusal they share. +function itemsOfEntries(session: SnapshotSession, entries: readonly any[], originOf?: (entry: any) => object | undefined): ClipboardItem[] { refuseUncopyable(session, entries); const shared = entriesSharingAName(entries); return entries.map((entry): ClipboardItem => { @@ -199,7 +211,8 @@ export function buildDragSnapshot( /** * Snapshot the rows a copy/cut acts on into the clipboard shape: the same walk and the same - * dedupe as buildDragSnapshot. Each item keeps its OWN source section: a cut is lazy, so the + * dedupe as buildDragSnapshot. What a paste lands is this snapshot read back from its document at + * paste time (readTaken), by who each entry was. Each item keeps its OWN source section: a cut is lazy, so the * source deletion at paste time must find each entry where it actually lives. */ export function buildClipboardSnapshot( @@ -211,10 +224,75 @@ export function buildClipboardSnapshot( return registerItemsOf(session, rowIds, findNode, originOf); } +/** What a document's reader needs of it to read back what a Copy or a Cut took (readTaken). */ +export interface ReadDeps { + /** Core's session, which the entries are asked of (copyRefusal) and resolved in. */ + session: SnapshotSession; + /** + * The document's entries as they are now, its model first brought up to date with its live + * content (a JSON dictionary re-parses its text): once per paste, however many entries it reads. + */ + entries: () => Iterable; + /** The token its document tells an entry by (CopyDeps.originOf), where its selectors cannot. */ + originOf?: (entry: any) => object | undefined; + /** Core's message in this document's words (a srcId said as the file's name). Default: as it is. */ + describe?: (message: string) => string; +} + +/** + * The entries `held` took from this document, as they are now (registers.ts's SourceReader): each + * found again by who it was, then taken again as a copy takes it, so the paste lands what the user + * sees and a cut's delete names the entry as it is now. Who an entry was is its origin token where + * it was taken with one (a MAT-file's variable: through edits and a rename, the same node), else + * its uuid (a dictionary entry's, which a rename keeps), else its name in the section it was taken + * from. One found nowhere, deleted since, is named in `gone`. A refusal (an entry that can no + * longer travel, a model that no longer reads) throws TransferRefused, in this document's words. + */ +export function readTaken(held: readonly ClipboardItem[], deps: ReadDeps): SourceRead { + const said = (message: string) => (deps.describe ? deps.describe(message) : message); + let live: any[]; + try { + live = [...deps.entries()]; + } catch (err) { + throw new TransferRefused(said(`Could not read the copied entries again: ${(err as Error)?.message || String(err)}`)); + } + const byOrigin = new Map(); + const byUuid = new Map(); + for (const entry of live) { + const origin = deps.originOf?.(entry); + if (origin) byOrigin.set(origin, entry); + const { uuid } = entrySelectorOf(entry); + if (uuid) byUuid.set(uuid, [...(byUuid.get(uuid) ?? []), entry]); + } + const sameAsTaken = (it: ClipboardItem, entry: any) => + entry.name === it.payload.name && sourceSectionOf(deps.session, entry) === it.sourceSection; + const found: any[] = []; + const gone: string[] = []; + for (const it of held) { + const { uuid } = entrySelectorOf(it.payload); + let entry: any; + if (it.origin) entry = byOrigin.get(it.origin); + else if (uuid) { + const withUuid = byUuid.get(uuid) ?? []; + entry = withUuid.length === 1 ? withUuid[0] : withUuid.find((e) => sameAsTaken(it, e)); + } else entry = live.find((e) => sameAsTaken(it, e)); + if (!entry) gone.push(String(it.payload.name ?? '')); + else if (!found.includes(entry)) found.push(entry); + } + try { + return { items: itemsOfEntries(deps.session, found, deps.originOf), gone }; + } catch (err) { + throw new TransferRefused(said(err instanceof CopyRefused ? err.message : `Failed to paste: ${(err as Error)?.message || String(err)}`)); + } +} + /** * Snapshot every entry the rows resolve to onto the clipboard in `mode`. * * Rows are deduped by owning entry, so selecting a bus and two of its elements copies ONE bus. + * Copy and Cut alike are read back from their document when they are pasted (readTaken): the + * snapshot says which entries, and the paste lands them as they are then. + * * `uriString` is recorded with the payloads because a cut is LAZY — the source delete is deferred * to paste time, and the paste may land in a different document, so the clipboard must remember * which document to delete from. diff --git a/src/model/edit/jsonView.ts b/src/model/edit/jsonView.ts index 9d0b72be..b6736559 100644 --- a/src/model/edit/jsonView.ts +++ b/src/model/edit/jsonView.ts @@ -92,7 +92,7 @@ import { type TableView, } from '../source/tableSource.js'; import { parseDetached } from '../workspace/SlddModel.js'; -import { copyEntriesToClipboard, dragEntries, type CopyDeps } from './clipboardAction.js'; +import { copyEntriesToClipboard, dragEntries, entriesUnder, readTaken, type CopyDeps } from './clipboardAction.js'; import { clipMarkChange, clipMarkOfDoc } from './clipMarks.js'; import { sectionTarget, type SectionTarget } from './dictionaryTarget.js'; import { answerEditTextRequest } from './editText.js'; @@ -211,6 +211,11 @@ export class JsonView implements EditableTableSource { }), ); registers.registerSourceDeleter(this.uri, (targets) => doc.writes.enqueue(() => this.deleteFromSourceDocument(targets))); + // And so that a paste of what a Copy or a Cut took from it reads the entries from the text as + // it stands then, whichever writer last changed it. + registers.registerSourceReader(this.uri, (items) => + readTaken(items, { session: this.session, entries: () => entriesUnder(this.liveModel()), describe: (m) => this.doc.describe(m) }), + ); // Every tab of this document repaints wide when the baseline moves (repaintAll). this.docState.repaints.add(this.repaintThis); // Repaint on ANY change to the text: this table's edits, a text view's, undo and redo. @@ -1054,7 +1059,8 @@ export class JsonView implements EditableTableSource { } // Cut is LAZY: it only marks the entry on the clipboard and writes nothing. The source is removed - // at PASTE time, so a same-document move is a single write (one undo step). + // at PASTE time, so a same-document move is a single write (one undo step), and what moves is + // the entry as the text holds it then (the registered reader). cut(rowIds: readonly string[]): void { if (this.disposed) return; copyEntriesToClipboard(rowIds, 'cut', this.uri, this.copyDeps(() => this.doc.options.registers.broadcastClipboardState())); @@ -1625,9 +1631,10 @@ export class JsonView implements EditableTableSource { for (const { done } of this.awaiting.splice(0)) done?.(true); // Per table, paired with the open: the last one drops the tree it held. this.doc.registry.releaseSourceView(this.uri); - // Only once the LAST table of this document closes. + // Only once the LAST table of this document closes, and a clipboard taken from it with it + // (closeSource): there is nothing left to read it back from. if (this.doc.closeView(this.docState)) { - registers.unregisterSourceDeleter(this.uri); + registers.closeSource(this.uri); this.doc.baseline.clear(); } } diff --git a/src/model/edit/matEngine.ts b/src/model/edit/matEngine.ts index 7c99e792..a53adbce 100644 --- a/src/model/edit/matEngine.ts +++ b/src/model/edit/matEngine.ts @@ -65,12 +65,12 @@ import { type TableChange, type TableView, } from '../source/tableSource.js'; -import { copyEntriesToClipboard, dragEntries, type CopyDeps } from './clipboardAction.js'; +import { copyEntriesToClipboard, dragEntries, readTaken, type CopyDeps } from './clipboardAction.js'; import { clipMarkChange, clipMarkOfDoc } from './clipMarks.js'; import { answerEditTextRequest } from './editText.js'; import type { EditIndex, EditSink, Notify } from './hooks.js'; import { addChildRefusal, addEntryRefusal, deleteRefusal, describeSource, refusedChange, type RefusedGesture } from './refusal.js'; -import { NOT_FOUND_REASON, reach, type DeleteTarget, type Registers } from './registers.js'; +import { NOT_FOUND_REASON, reach, type ClipboardItem, type DeleteTarget, type Registers, type SourceRead } from './registers.js'; import { MAT_FILE, type EngineFile } from './engineFile.js'; import { replacementsIn, SaveMarks, type SaveMark, type SaveSnapshot } from './saveMarks.js'; import { replacingOrRefuse } from './replacing.js'; @@ -192,6 +192,7 @@ interface MatDocument { record(label: string, run: (mat: any) => void, touched?: () => Iterable): Observed; originOf(variable: any): object; deleteMoved(targets: readonly DeleteTarget[]): SourceDeleteResult; + readTaken(items: readonly ClipboardItem[]): SourceRead; notify(level: 'warning' | 'error' | 'status', message: string, ms?: number): void; } @@ -388,6 +389,7 @@ export class MatEngine { record: (label, run, touched) => this.record(label, run, touched), originOf: (variable) => this.originOf(variable), deleteMoved: (targets) => this.deleteMoved(targets), + readTaken: (items) => this.readTaken(items), notify: (level, message, ms) => this.notify(level, message, ms), }; } @@ -698,11 +700,26 @@ export class MatEngine { return { removed: false, reason: 'the file did not let it be removed' }; } + /** + * The variables a Copy or a Cut took from this file, as they are now, for a paste of them (the + * registers' source reader): each found by the token it was taken with (`originOf`), among the + * nodes `deleteMoved` would take it from, so the paste and a cut's delete find the same one. + */ + private readTaken(items: readonly ClipboardItem[]): SourceRead { + return readTaken(items, { + session: this.session, + entries: () => [...(this.model().children as any[]), ...(this.file.movedOut?.(this.root()) ?? [])], + originOf: (variable) => this.originOf(variable), + describe: (message) => this.describe(message), + }); + } + /** * The token a cut or a drag of `variable` carries (TransferItem.origin), which `deleteMoved` * tells the original by: one object for as long as the variable is the same node — through - * edits of it, a rename, and the undo of its delete, which puts the node itself back. A variable - * made since (an Add, a paste, a reload of the file) is another node, with another token. + * edits of it, a rename, and the undo of its delete, which puts the node itself back — and, + * through a reload of the file, for the variable the file still holds under its name + * (`carryTokens`). A variable made since (an Add, a paste) is another node, with another token. */ private originOf(variable: any): object { let token = this.origins.get(variable); @@ -787,6 +804,7 @@ export class MatEngine { * every view is painted from it. */ replace(bytes: ArrayBuffer): Promise { + const held = this.loaded && !('error' in this.loaded) ? this.tokensByName() : null; this.session.removeDataSource(this.srcId); this.bytes = bytes; this.loaded = null; @@ -797,12 +815,54 @@ export class MatEngine { // tree. A file that no longer reads says so at the paint. try { this.model(); + if (held) this.carryTokens(held); } catch { /* reported by the paint */ } return this.repaintAll(); } + // The variables (and the nodes beside them) a reload makes again, each list's by name: only a + // name one node answers to in the list, since two of one name cannot be told apart. + private uniquelyNamed(): Map[] { + const lists = [this.model().children as any[], [...(this.file.movedOut?.(this.root()) ?? [])]]; + return lists.map((nodes) => { + const byName = new Map(); + const twice = new Set(); + for (const node of nodes) { + if (byName.has(node.name)) twice.add(node.name); + byName.set(node.name, node); + } + for (const name of twice) byName.delete(name); + return byName; + }); + } + + // The tokens the uniquely-named nodes carry before a reload, by name. + private tokensByName(): Map[] { + return this.uniquelyNamed().map((byName) => { + const tokens = new Map(); + for (const [name, node] of byName) { + const token = this.origins.get(node); + if (token) tokens.set(name, token); + } + return tokens; + }); + } + + // A reload reads the file's variables again as new nodes: each takes the token the one of its + // name had (`originOf`), so a Copy or a Cut made before an outside change still finds the + // variable of that name in the file as it is now. A name two nodes answer to, before or after, + // takes none. + private carryTokens(held: Map[]): void { + this.uniquelyNamed().forEach((byName, i) => { + for (const [name, token] of held[i] ?? []) { + const node = byName.get(name); + if (node) this.origins.set(node, token); + } + }); + } + /** A table of the document: an EditableTableSource, until its `dispose()`. */ view(): EditableTableSource & { dispose(): void; repaintAll(): Promise; opened(view?: TableView): void } { return new MatView(this.document); @@ -869,7 +929,11 @@ class MatView implements EditableTableSource { }, drag: (descriptor) => this.emit({ kind: 'drag', descriptor }), }); - if (doc.views.size === 0) registers.registerSourceDeleter(doc.uri, (targets) => doc.deleteMoved(targets)); + if (doc.views.size === 0) { + registers.registerSourceDeleter(doc.uri, (targets) => doc.deleteMoved(targets)); + // And reads back, at a paste, the variables a Copy or a Cut took from it, as they are then. + registers.registerSourceReader(doc.uri, (items) => doc.readTaken(items)); + } doc.views.add(this); } @@ -1628,7 +1692,8 @@ class MatView implements EditableTableSource { registers.clearDrag(); registers.broadcastDragState(); } - // The deleter is the document's, so it stays while any view of it does. - if (this.doc.views.size === 0) registers.unregisterSourceDeleter(this.doc.uri); + // The deleter and the reader are the document's, so they stay while any view of it does, and a + // clipboard taken from it goes with the last (closeSource): nothing is left to read it from. + if (this.doc.views.size === 0) registers.closeSource(this.doc.uri); } } diff --git a/src/model/edit/registers.ts b/src/model/edit/registers.ts index 7f747e58..e451c412 100644 --- a/src/model/edit/registers.ts +++ b/src/model/edit/registers.ts @@ -19,7 +19,11 @@ // cut is LAZY — the source deletion is deferred to paste time, so each item has to say where it // must be deleted FROM. One shared section would delete the wrong entry, or none. Each item is a // structural snapshot of a serialized node ({name, metadata, value}) captured at copy/cut time — -// independent of the live model, so later mutations don't alias it. +// independent of the live model, so later mutations don't alias it — and it is what the paste +// asks the entry's document for again: a paste reads the entries as they are THEN (the source's +// reader, as the Data Explorer in MATLAB resolves its clipboard at paste time), so an edit made +// between a Copy or a Cut and its paste is what lands. That is also why closing the +// document empties a clipboard taken from it (closeSource): there is nothing left to read. // // THE DRAG REGISTER exists because a drag's dataTransfer does not reliably cross a frame (a // webview's iframe): on drag start the host snapshots the dragged entries here, and on drop the @@ -91,6 +95,24 @@ export type DeleteTarget = string | SourceSelector; */ export type SourceDeleter = (targets: DeleteTarget[]) => Promise | SourceDeleteResult; +/** What a document's reader found of the entries a Copy or a Cut took from it. */ +export interface SourceRead { + /** Each entry still there, as it is now, in the order taken. */ + items: ClipboardItem[]; + /** The names of the entries no longer there, as they were taken. */ + gone: string[]; +} + +/** + * How one open document reads back the entries a Copy or a Cut took from it, as they are NOW: the + * paste's half of a lazy clipboard. Each item is found again by who it was (its uuid, its origin + * token, or its name in its section) and taken again as a copy takes it, so a paste lands the + * value the user sees, and a cut's delete names the entry as it is now. Synchronous, because a + * paste reads its register before it changes anything. Throws TransferRefused for an entry that + * cannot travel any more, in the words a copy would refuse it in. + */ +export type SourceReader = (items: readonly ClipboardItem[]) => SourceRead; + /** * A deleter's reason when nothing in its document answers to the names it was given any more: * renamed or deleted since the cut. One spelling for every format, because it is one fact. @@ -165,12 +187,21 @@ export interface Registers { /** How the document `uriString` removes entries from itself, for a move out of it. */ registerSourceDeleter(uriString: string, fn: SourceDeleter): void; unregisterSourceDeleter(uriString: string): void; + /** How the document `uriString` reads back the entries a Copy or a Cut took from it (SourceReader). */ + registerSourceReader(uriString: string, fn: SourceReader): void; + /** + * The document `uriString` closed (its last table did): its deleter and its reader go, and a + * clipboard taken from it, Copy or Cut, is emptied, and every table told. Nothing is left to + * read the entries from, and a cut's original can no longer be taken out, as the Data Explorer + * in MATLAB empties its clipboard when its source closes. + */ + closeSource(uriString: string): void; /** * Complete the source-delete half of a cross-document move, and say whether it happened. * - * During a drag the source view is open (closing it ends the drag), so its deleter is here. A - * CUT is different: it is lazy, so its source may have been closed between the cut and the - * paste, and then there is no deleter — and no format-appropriate way to edit the file — so the + * During a drag the source view is open (closing it ends the drag), and a cut's source is open + * too: closing it empties the clipboard the cut is on (closeSource). A document that never + * registered a deleter has none, and no format-appropriate way to edit the file, so the * original stays where it is: an answer the caller reports. * * A deleter that throws still throws: the caller (transfer.ts) turns that into the same report. @@ -210,6 +241,7 @@ export function createRegisters(): Registers { let clipboard: ClipboardEntry | null = null; let drag: DragEntry | null = null; const sourceDeleters = new Map(); + const sourceReaders = new Map(); const listeners = new Set(); const getClipboard = (): ClipboardEntry | null => clipboard; @@ -288,9 +320,16 @@ export function createRegisters(): Registers { let held: ClipboardEntry | null = null; return { kind: 'clipboard', + // As the entries are now, where their document reads them back (SourceReader); as they + // were taken where none does, which no open document is without. read(): TransferContents | null { held = getClipboard(); - return held && { items: held.items, sourceDocUri: held.sourceDocUri, move: held.mode === 'cut' }; + if (!held) return null; + const move = held.mode === 'cut'; + const reader = held.sourceDocUri === undefined ? undefined : sourceReaders.get(held.sourceDocUri); + if (!reader) return { items: held.items, sourceDocUri: held.sourceDocUri, move }; + const now = reader(held.items); + return { items: now.items, sourceDocUri: held.sourceDocUri, move, gone: now.gone }; }, clear(): void { if (held && getClipboard() === held) clearClipboard(); @@ -318,6 +357,16 @@ export function createRegisters(): Registers { unregisterSourceDeleter(uriString) { sourceDeleters.delete(uriString); }, + registerSourceReader(uriString, fn) { + sourceReaders.set(uriString, fn); + }, + closeSource(uriString) { + sourceDeleters.delete(uriString); + sourceReaders.delete(uriString); + if (clipboard?.sourceDocUri !== uriString) return; + clearClipboard(); + broadcastClipboardState(); + }, async deleteFromSource(uriString, targets) { const fn = sourceDeleters.get(uriString); if (!fn) return { removed: false, reason: 'its table is no longer open' }; diff --git a/src/model/edit/transfer.ts b/src/model/edit/transfer.ts index 11b992de..20ce2567 100644 --- a/src/model/edit/transfer.ts +++ b/src/model/edit/transfer.ts @@ -76,6 +76,11 @@ export interface TransferContents { sourceDocUri: string | undefined; /** The source is to lose them: a cut, or a drop in move mode. */ move: boolean; + /** + * The names of the entries taken that their document no longer holds, by the time a paste read + * them back (registers.ts's SourceReader): skipped, and named to the user. Absent: none. + */ + gone?: readonly string[]; } /** @@ -227,8 +232,13 @@ export type TransferOutcome = | { kind: 'noop' } | { kind: 'refused'; message: string } | { kind: 'failed'; error: unknown } - /** Landed. `sourceKept` is the message reported when a move's source delete did not happen. */ - | { kind: 'done'; sourceKept?: string }; + /** Every entry the clipboard took is gone from its document: nothing pasted, and `message` said. */ + | { kind: 'gone'; message: string } + /** + * Landed. `sourceKept` is the message reported when a move's source delete did not happen, and + * `skipped` the one naming the entries no longer there to paste (TransferContents.gone). + */ + | { kind: 'done'; sourceKept?: string; skipped?: string }; /** * Whether moving `contents` onto `sectionName` of `docUri` would change nothing: every item @@ -279,11 +289,27 @@ async function transfer( ): Promise { const isPaste = register.kind === 'clipboard'; if (adapter.guard && !adapter.guard()) return { kind: 'guarded' }; - const contents = register.read(); + let contents: TransferContents | null; + try { + // A paste's register reads its entries back from their document here, which can refuse one. + contents = register.read(); + } catch (err) { + return refusedOrFailed(err, adapter); + } + const gone = contents?.gone ?? []; + if (contents && contents.items.length === 0 && gone.length > 0) { + // Nothing the clipboard took is left to paste, now or on another try. + const message = goneMessage(gone, contents.sourceDocUri, true); + adapter.report(message); + register.clear(); + register.broadcast(); + return { kind: 'gone', message }; + } if (!contents || contents.items.length === 0) { adapter.report(isPaste ? 'Nothing to paste — the clipboard is empty.' : 'Nothing to drop.'); return { kind: 'empty' }; } + const skipped = gone.length > 0 ? goneMessage(gone, contents.sourceDocUri, false) : undefined; const replacing = req.replacing ?? []; let target: T | null; @@ -337,21 +363,32 @@ async function transfer( return refusedOrFailed(err, adapter); } - // Landed. Everything below is the source's half of a cross-document move, and none of it - // may undo or repaint what just happened here. - if (!contents.move) return { kind: 'done' }; + // Landed. Said where it landed, and where it stays until dismissed: the paste's repaint clears + // a banner, and an entry the user expected that never came is the outcome this is for. + if (skipped) { + adapter.report(skipped); + deps.warn?.(skipped); + } + const done = (sourceKept?: string): TransferOutcome => ({ + kind: 'done', + ...(sourceKept ? { sourceKept } : {}), + ...(skipped ? { skipped } : {}), + }); + // Everything below is the source's half of a cross-document move, and none of it may undo or + // repaint what just happened here. + if (!contents.move) return done(); // Consumed by the paste that just landed, whatever the source delete does next: a cut left // live would paste the same entries a second time. Cleared BEFORE the delete is awaited, so // a second Paste arriving meanwhile finds nothing to paste rather than this cut again. if (isPaste) register.clear(); try { - if (sameDoc || selectors.length === 0) return { kind: 'done' }; + if (sameDoc || selectors.length === 0) return done(); const result = await sourceDelete(contents.sourceDocUri, selectors, deps); - if (result.removed) return { kind: 'done' }; + if (result.removed) return done(); const message = sourceKeptMessage(isPaste, contents.sourceDocUri, selectors.length, result.reason, result.gone === true); adapter.report(message); deps.warn?.(message); - return { kind: 'done', sourceKept: message }; + return done(message); } finally { if (isPaste) register.broadcast(); } @@ -392,6 +429,21 @@ export function sharedNameRefusal(verb: 'cut' | 'move', name: string, sourceDocU return `Cannot ${verb} "${name}": ${where} holds more than one "${name}", and a move takes its original out by name. Copy it instead.`; } +/** + * 'Not pasted: "x" is no longer in a.sldd.' — the entries a Copy or a Cut took that their document + * no longer holds by the paste (TransferContents.gone), the first five by name. `nothingLeft` + * when no other entry was pasted either: 'Nothing to paste: "x" and "y" are no longer in a.sldd.' + */ +export function goneMessage(names: readonly string[], sourceDocUri: string | undefined, nothingLeft: boolean): string { + const shown = names.slice(0, 5).map((n) => `"${n}"`); + const more = names.length - shown.length; + const listed = + more > 0 ? `${shown.join(', ')} and ${more} more` : shown.length > 1 ? `${shown.slice(0, -1).join(', ')} and ${shown.at(-1)}` : shown[0]; + const where = sourceDocUri ? fileNameOf(sourceDocUri) : 'their file'; + const lead = nothingLeft ? 'Nothing to paste' : 'Not pasted'; + return `${lead}: ${listed} ${names.length === 1 ? 'is' : 'are'} no longer in ${where}.`; +} + /** * "Pasted here, but the original in a.sldd could not be removed: . Remove it there by * hand." — accurate about both halves: the paste DID land, and nothing was rolled back. Or, where diff --git a/src/model/index.ts b/src/model/index.ts index 68a631c7..8c898c4a 100644 --- a/src/model/index.ts +++ b/src/model/index.ts @@ -265,11 +265,14 @@ export type { RegisterListener, Registers, SourceDeleter, + SourceRead, + SourceReader, } from './edit/registers.js'; // transfer.ts's isNoopMove, the host's half of the rule the drop predictor's isNoopMove answers // (above), under a name of its own. export { TransferRefused, + goneMessage, isNoopMove as isNoopTransfer, runTransfer, sharedNameRefusal, diff --git a/test/binaryEngine/clipboard.test.ts b/test/binaryEngine/clipboard.test.ts index 7f860116..823b15d1 100644 --- a/test/binaryEngine/clipboard.test.ts +++ b/test/binaryEngine/clipboard.test.ts @@ -293,7 +293,8 @@ async function cutAndPaste(w: ReturnType, source: Opened, close target.view.posts.length = 0; target.view.send({ type: 'paste', rowId: 'section:design' }); await waitFor('the paste to land or be refused', () => target.events.length > edits || errorsIn(target.view.posts).length > 0); - // The source delete runs after the paste's write, and its report after that. + // The source delete runs after the paste's write, and its report after that. (A closed source + // emptied the clipboard already.) await waitFor('the move to finish', () => w.registers.getClipboard() === null); await quiet(); return { @@ -313,17 +314,13 @@ describe('A cut from a compressed-binary .sldd, pasted into another dictionary', assert.ok(!run.sourceHolds, 'and left the source'); }); - it('says the original could not be removed when its tab was closed after the cut, and loses nothing', async () => { + it('pastes nothing when its tab was closed after the cut, and loses nothing: the close took the cut with it', async () => { const w = windowOf(); const source = await w.bin('xdoc_src_closed_bin.sldd'); const run = await cutAndPaste(w, source, true, 'xdoc_dst_closed_bin.sldd'); - assert.deepStrictEqual( - run.errors, - ['Pasted here, but the original in xdoc_src_closed_bin.sldd could not be removed: its table is no longer open. Remove it there by hand.'], - 'the target view says what is left to do', - ); - assert.ok(run.targetHas, `${MOVED} landed in the target`); - assert.ok(run.sourceHolds, 'and is still in the source: two copies, neither lost'); + assert.deepStrictEqual(run.errors, ['Nothing to paste — the clipboard is empty.']); + assert.ok(!run.targetHas, `${MOVED} did not land in the target`); + assert.ok(run.sourceHolds, 'and is still in the source'); }); }); diff --git a/test/binaryEngine/lateCopy.test.ts b/test/binaryEngine/lateCopy.test.ts new file mode 100644 index 00000000..c8774d38 --- /dev/null +++ b/test/binaryEngine/lateCopy.test.ts @@ -0,0 +1,126 @@ +// Copyright 2026 The MathWorks, Inc. +// +// A compressed-binary dictionary's clipboard is read at paste time (registers.ts's SourceReader): +// what a Cut or a Copy took is pasted as it is when the paste lands, so an edit made in between is +// what moves or is copied, as the Data Explorer in MATLAB resolves its clipboard. An entry deleted +// in between is not pasted and is named, and closing the dictionary empties a clipboard taken from +// it. The bug behind it: a Cut, an edit of the cut entry, a paste — the paste wrote the value from +// the moment of the Cut and removed the edited original, so the edit was in neither place. +import * as assert from 'node:assert'; +import { createSession } from 'data-explorer-core'; +import { describe, it } from 'vitest'; +import { createRegisters } from '../../src/model/index.js'; +import { entryOf, entryRow, errorsIn, open, waitFor, type Opened } from './harness.js'; + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +/** The edit bash's MATLAB-written binary dictionary: somewhere a paste can land, holding no gravity. */ +const VALUES = 'test-integration/fixtures/editbash/values_binary.sldd'; + +/** A window: one session and one set of registers for every document a case opens. */ +function windowOf() { + const registers = createRegisters(); + const session = createSession(); + return { + registers, + source: () => open('test-integration/fixtures/sldd/params_binary.sldd', undefined, { as: 'late_src.sldd', registers, session }), + target: () => open(VALUES, undefined, { as: 'late_dst.sldd', registers, session }), + }; +} + +/** Send a gesture to a view and wait for its edit, or its word. */ +async function gesture(tab: Opened, msg: Record): Promise { + const edits = tab.events.length; + tab.view.posts.length = 0; + tab.view.send(msg); + await waitFor(`the ${String(msg.type)} to land or be refused`, () => tab.events.length > edits || errorsIn(tab.view.posts).length > 0); + return errorsIn(tab.view.posts); +} + +/** The Value cell of the document's entry `name`, as its table shows it. */ +function valueOf(tab: Opened, name: string): string { + const entry = entryOf(tab.model(), name); + assert.ok(entry, `${name} is in the document`); + const cell = entry.toRow().Value; + return String(cell && typeof cell === 'object' ? (cell.text ?? '') : cell); +} + +const editValue = (tab: Opened, name: string, oldValue: string, newValue: string) => + gesture(tab, { type: 'edit', rowId: entryRow(tab.view.posts, name).ID, columnId: 'Value', oldValue, newValue }); + +const rename = (tab: Opened, name: string, newValue: string) => + gesture(tab, { type: 'edit', rowId: entryRow(tab.view.posts, name).ID, columnId: 'Name', oldValue: name, newValue }); + +/** Paste into the target's Design Data, and wait for a cut's move to finish. */ +async function pasteInto(w: ReturnType, target: Opened): Promise { + const said = await gesture(target, { type: 'paste', rowId: 'section:design' }); + await new Promise((resolve) => setTimeout(resolve, 20)); + return said; +} + +describe('a binary dictionary clipboard, read at paste time', () => { + it('a Cut, an edit of the cut entry, then a paste moves the edited value', async () => { + const w = windowOf(); + const source = await w.source(); + source.view.send({ type: 'cut', rowIds: [entryRow(source.view.posts, 'gravity').ID] }); + assert.deepStrictEqual(await editValue(source, 'gravity', '9.81', '9.8'), []); + const target = await w.target(); + assert.deepStrictEqual(await pasteInto(w, target), []); + assert.strictEqual(valueOf(target, 'gravity'), '9.8', 'the value typed after the Cut is the one pasted'); + await waitFor('the original to leave the source', () => !source.names().includes('gravity')); + assert.strictEqual(w.registers.getClipboard(), null, 'the cut is spent'); + }); + + it('a Copy, an edit, then a paste copies the edited value, and the source keeps it', async () => { + const w = windowOf(); + const source = await w.source(); + source.view.send({ type: 'copy', rowIds: [entryRow(source.view.posts, 'gravity').ID] }); + await editValue(source, 'gravity', '9.81', '9.8'); + const target = await w.target(); + assert.deepStrictEqual(await pasteInto(w, target), []); + assert.strictEqual(valueOf(target, 'gravity'), '9.8'); + assert.strictEqual(valueOf(source, 'gravity'), '9.8'); + assert.strictEqual(w.registers.getClipboard()?.mode, 'copy', 'a copy stays for the next paste'); + }); + + it('an entry renamed after the Cut moves under its new name', async () => { + const w = windowOf(); + const source = await w.source(); + source.view.send({ type: 'cut', rowIds: [entryRow(source.view.posts, 'gravity').ID] }); + assert.deepStrictEqual(await rename(source, 'gravity', 'g0'), []); + const target = await w.target(); + assert.deepStrictEqual(await pasteInto(w, target), []); + assert.strictEqual(valueOf(target, 'g0'), '9.81'); + assert.ok(!entryOf(target.model(), 'gravity'), 'nothing lands under the old name'); + await waitFor('the renamed original to leave the source', () => !source.names().includes('g0')); + }); + + it('an entry deleted after the Copy is not pasted, and the paste says so', async () => { + const w = windowOf(); + const source = await w.source(); + source.view.send({ type: 'copy', rowIds: [entryRow(source.view.posts, 'gravity').ID] }); + await gesture(source, { type: 'delete', rowIds: [entryRow(source.view.posts, 'gravity').ID] }); + const target = await w.target(); + const before = target.events.length; + assert.deepStrictEqual(await pasteInto(w, target), ['Nothing to paste: "gravity" is no longer in late_src.sldd.']); + assert.strictEqual(target.events.length, before, 'nothing was pasted'); + assert.ok(!entryOf(target.model(), 'gravity')); + assert.strictEqual(w.registers.getClipboard(), null, 'nothing is left on the clipboard'); + }); + + it('closing the dictionary empties a clipboard taken from it, Copy or Cut', async () => { + for (const mode of ['copy', 'cut']) { + const w = windowOf(); + const source = await w.source(); + source.view.send({ type: mode, rowIds: [entryRow(source.view.posts, 'gravity').ID] }); + assert.strictEqual(w.registers.getClipboard()?.mode, mode); + source.view.close(); + assert.strictEqual(w.registers.getClipboard(), null, `the ${mode} went with the dictionary`); + const target = await w.target(); + const before = target.events.length; + assert.deepStrictEqual(await pasteInto(w, target), ['Nothing to paste — the clipboard is empty.']); + assert.strictEqual(target.events.length, before); + assert.ok(source.names().includes('gravity'), 'and the source keeps its entry'); + } + }); +}); diff --git a/test/jsonEngine/clipboard.test.ts b/test/jsonEngine/clipboard.test.ts index 381a6121..c07761bb 100644 --- a/test/jsonEngine/clipboard.test.ts +++ b/test/jsonEngine/clipboard.test.ts @@ -445,17 +445,13 @@ for (const [format, openSource] of [ assert.ok(!run.sourceHolds, 'and left the source'); }); - it('says the original could not be removed when its tab was closed after the cut, and loses nothing', async () => { + it('pastes nothing when its tab was closed after the cut, and loses nothing: the close took the cut with it', async () => { const w = windowOf(); const source = await openSource(w, `xdoc_src_closed_${tag}.sldd`); const run = await cutAndPaste(w, source, true, `xdoc_dst_closed_${tag}.sldd`); - assert.deepStrictEqual( - run.errors, - [`Pasted here, but the original in xdoc_src_closed_${tag}.sldd could not be removed: its table is no longer open. Remove it there by hand.`], - 'the target view says what is left to do', - ); - assert.ok(run.targetHas, `${MOVED} landed in the target`); - assert.ok(run.sourceHolds, 'and is still in the source: two copies, neither lost'); + assert.deepStrictEqual(run.errors, ['Nothing to paste — the clipboard is empty.']); + assert.ok(!run.targetHas, `${MOVED} did not land in the target`); + assert.ok(run.sourceHolds, 'and is still in the source'); }); }); } @@ -926,22 +922,19 @@ describe('MAT-file pastes and drops refused, with a JSON dictionary on the other assert.ok(j.names().includes('charStr'), 'the refused move left its source alone'); }); - it('a move whose original became one of two of its name is pasted, and the original kept, said', async () => { + it('a cut whose original became one of two of its name is not pasted: which one it was cannot be told', async () => { const w = windowOf(); const a = await w.mat('back.mat', matFixture('pv_basic.mat')); const j = await w.json('target.sldd'); a.view.send({ type: 'cut', rowIds: [variableRow(a.view.posts, 'x').ID] }); // The file is read again holding two x (an outside change, with no unsaved edit): the cut's - // original is now one of two. + // original is now one of two, and the paste reads it back from the file as it is now. await a.engine.replace(buffer(twiceNamedMat())); await waitFor('the reload', () => namesOf(a).join() === 'x,str,x'); await onJson(j, { type: 'paste', rowId: 'section:design' }); - await moveDone(w); - await waitFor('the report', () => errorsIn(j.view.posts).length > 0); - assert.deepStrictEqual(errorsIn(j.view.posts), [ - 'Pasted here, but the original in back.mat could not be removed: it holds more than one "x", and a move takes its original out by name. Remove it there by hand.', - ]); - assert.ok(j.names().includes('x'), 'the paste landed'); + assert.deepStrictEqual(errorsIn(j.view.posts), ['Nothing to paste: "x" is no longer in back.mat.']); + assert.strictEqual(w.registers.getClipboard(), null, 'nothing is left to paste'); + assert.ok(!j.names().includes('x'), 'nothing landed'); assert.deepStrictEqual(namesOf(a), ['x', 'str', 'x'], 'and nothing was guessed at in the MAT-file'); assert.strictEqual(a.events.length, 0); }); @@ -975,7 +968,7 @@ describe('MAT-file pastes and drops refused, with a JSON dictionary on the other // A cut is lazy and a MAT-file's variable is told by name alone, so between the cut and the // paste the original can be deleted and another variable given its name. The cut carries who - // the original was (originOf), and the move takes out only that one. + // the original was (originOf): the paste reads back only that one, and the move takes out only it. const giveNameX = async (a: MatOpened, from: string) => { // A variable of the name `x` that is not the one cut: an Add, renamed. await onMat(a, { type: 'addEntry', section: '', className: 'MatlabVariable', rename: false }); @@ -984,7 +977,7 @@ describe('MAT-file pastes and drops refused, with a JSON dictionary on the other assert.ok(namesOf(a).includes('x'), 'another variable now holds the name'); }; - it('a cut whose variable was deleted and its name given to another: the paste lands, and the other is left alone', async () => { + it('a cut whose variable was deleted and its name given to another: nothing is pasted, it is said, and the other is left alone', async () => { const w = windowOf(); const a = await w.mat('cut.mat', matFixture('pv_basic.mat')); const j = await w.json('target.sldd'); @@ -994,30 +987,27 @@ describe('MAT-file pastes and drops refused, with a JSON dictionary on the other const other = variableOf(a, 'x'); const edits = a.events.length; await onJson(j, { type: 'paste', rowId: 'section:design' }); - await moveDone(w); - await waitFor('the report', () => errorsIn(j.view.posts).length > 0); - assert.deepStrictEqual(errorsIn(j.view.posts), [ - 'Pasted here; the original in cut.mat is no longer there to remove: the "x" it holds now is another variable, which was left as it is.', - ]); - assert.ok(j.names().includes('x'), 'the paste landed'); + assert.deepStrictEqual(errorsIn(j.view.posts), ['Nothing to paste: "x" is no longer in cut.mat.']); + assert.strictEqual(w.registers.getClipboard(), null, 'nothing is left to paste'); + assert.ok(!j.names().includes('x'), 'the other variable was not pasted in its place'); assert.strictEqual(variableOf(a, 'x'), other, 'and the variable that holds the name now was not taken out'); assert.strictEqual(a.events.length, edits, 'no edit in the MAT-file'); }); - it('a cut whose variable was renamed and its name given to another: nothing is taken out, and the renamed one is named', async () => { + it('a cut whose variable was renamed and its name given to another moves the renamed one, and leaves the other alone', async () => { const w = windowOf(); const a = await w.mat('renamed.mat', matFixture('pv_basic.mat')); const j = await w.json('target.sldd'); a.view.send({ type: 'cut', rowIds: [variableRow(a.view.posts, 'x').ID] }); await onMat(a, { type: 'edit', rowId: variableOf(a, 'x').id, columnId: 'Name', oldValue: 'x', newValue: 'y' }); await giveNameX(a, namesOf(a).join()); + const other = variableOf(a, 'x'); await onJson(j, { type: 'paste', rowId: 'section:design' }); await moveDone(w); - await waitFor('the report', () => errorsIn(j.view.posts).length > 0); - assert.deepStrictEqual(errorsIn(j.view.posts), [ - 'Pasted here, but the original in renamed.mat could not be removed: the "x" it holds now is another variable, and the one taken is now "y". Remove it there by hand.', - ]); - assert.ok(namesOf(a).includes('x') && namesOf(a).includes('y'), 'both are where they were'); + await waitFor('the renamed original to move out', () => !namesOf(a).includes('y')); + assert.deepStrictEqual(errorsIn(j.view.posts), []); + assert.ok(j.names().includes('y') && !j.names().includes('x'), 'the variable the cut took, under the name it has now'); + assert.strictEqual(variableOf(a, 'x'), other, 'and the one that holds its old name stays'); }); it('a cut whose variable was edited, or deleted and the delete undone, is still the one taken, and moves', async () => { diff --git a/test/jsonEngine/lateCopy.test.ts b/test/jsonEngine/lateCopy.test.ts new file mode 100644 index 00000000..4930a9d6 --- /dev/null +++ b/test/jsonEngine/lateCopy.test.ts @@ -0,0 +1,100 @@ +// Copyright 2026 The MathWorks, Inc. +// +// A JSON dictionary's clipboard is read at paste time (registers.ts's SourceReader), from the text +// as it stands then: an edit made between a Cut or a Copy and its paste is what lands, whether it +// was made in the table or in a text view of the file, as the Data Explorer in MATLAB resolves its +// clipboard. An entry deleted in between is named and not pasted, and closing the +// dictionary empties a clipboard taken from it. +import * as assert from 'node:assert'; +import { createSession } from 'data-explorer-core'; +import { describe, it } from 'vitest'; +import { createRegisters } from '../../src/model/index.js'; +import { DocumentRegistry } from '../../src/model/workspace/SlddModel.js'; +import { WORKSPACE_DATA, WORKSPACE_PARAMS, chunkOf, entryRow, errorsIn, file, open, settle, waitFor, type Opened } from './harness.js'; + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +function windowOf() { + const registers = createRegisters(); + const registry = new DocumentRegistry(createSession()); + return { + registers, + source: () => open(WORKSPACE_PARAMS, file(WORKSPACE_PARAMS), { as: 'late_src.sldd', registers, registry }), + target: () => open(WORKSPACE_DATA, file(WORKSPACE_DATA), { as: 'late_dst.sldd', registers, registry }), + }; +} + +/** Send a gesture to a view, and wait for the text to move or the view to say why not. */ +async function gesture(tab: Opened, msg: Record): Promise { + const version = tab.text.version; + tab.view.posts.length = 0; + tab.view.send(msg); + await waitFor(`the ${String(msg.type)} to land or be refused`, () => tab.text.version !== version || errorsIn(tab.view.posts).length > 0); + await settle(); + return errorsIn(tab.view.posts); +} + +/** The entry `name` the text holds, as a value of the chunk. */ +function entryIn(tab: Opened, name: string): any { + return ((chunkOf(tab.text.text).entries ?? []) as any[]).find((e) => e.name === name); +} + +const description = (tab: Opened, name: string): string => entryIn(tab, name)?.value?._elements?.[0]?._properties?.Description; + +describe('a JSON dictionary clipboard, read at paste time', () => { + it('a Cut, an edit of the cut entry in its table, then a paste moves the edited entry', async () => { + const w = windowOf(); + const source = await w.source(); + source.view.send({ type: 'cut', rowIds: [entryRow(source.view.posts, 'gravity').ID] }); + const row = entryRow(source.view.posts, 'gravity'); + assert.deepStrictEqual( + await gesture(source, { type: 'edit', rowId: row.ID, columnId: 'Description', oldValue: 'gravity accel', newValue: 'typed after the cut' }), + [], + ); + const target = await w.target(); + assert.deepStrictEqual(await gesture(target, { type: 'paste', rowId: 'section:design' }), []); + assert.strictEqual(description(target, 'gravity'), 'typed after the cut', 'the edit made after the Cut is the one pasted'); + await waitFor('the original to leave the source', () => !source.names().includes('gravity')); + }); + + it('a Copy, an edit in a text view of the file, then a paste copies the text as it is now', async () => { + const w = windowOf(); + const source = await w.source(); + source.view.send({ type: 'copy', rowIds: [entryRow(source.view.posts, 'gravity').ID] }); + const at = source.text.text.indexOf('"gravity accel"'); + assert.ok(at > 0, 'the fixture spells the description'); + assert.ok(await source.type(at, '"gravity accel"'.length, '"typed in the text"'), 'the text view edit landed'); + await settle(); + const target = await w.target(); + assert.deepStrictEqual(await gesture(target, { type: 'paste', rowId: 'section:design' }), []); + assert.strictEqual(description(target, 'gravity'), 'typed in the text'); + }); + + it('an entry deleted after the Copy is not pasted, and the paste says so', async () => { + const w = windowOf(); + const source = await w.source(); + source.view.send({ type: 'copy', rowIds: [entryRow(source.view.posts, 'gravity').ID] }); + await gesture(source, { type: 'delete', rowIds: [entryRow(source.view.posts, 'gravity').ID] }); + const target = await w.target(); + const version = target.text.version; + assert.deepStrictEqual(await gesture(target, { type: 'paste', rowId: 'section:design' }), [ + 'Nothing to paste: "gravity" is no longer in late_src.sldd.', + ]); + assert.strictEqual(target.text.version, version, 'nothing was pasted'); + assert.strictEqual(w.registers.getClipboard(), null); + }); + + it('closing the dictionary empties a clipboard taken from it, Copy or Cut', async () => { + for (const mode of ['copy', 'cut']) { + const w = windowOf(); + const source = await w.source(); + source.view.send({ type: mode, rowIds: [entryRow(source.view.posts, 'gravity').ID] }); + assert.strictEqual(w.registers.getClipboard()?.mode, mode); + source.view.close(); + assert.strictEqual(w.registers.getClipboard(), null, `the ${mode} went with the dictionary`); + const target = await w.target(); + assert.deepStrictEqual(await gesture(target, { type: 'paste', rowId: 'section:design' }), ['Nothing to paste — the clipboard is empty.']); + assert.ok(!target.names().includes('gravity')); + } + }); +}); diff --git a/test/lateClipboard.test.ts b/test/lateClipboard.test.ts new file mode 100644 index 00000000..cd7af352 --- /dev/null +++ b/test/lateClipboard.test.ts @@ -0,0 +1,203 @@ +// Copyright 2026 The MathWorks, Inc. +// +// The clipboard read at paste time, as the Data Explorer in MATLAB reads its own: a Cut or a +// Copy keeps which entries it took, and a paste asks their document for them as they are NOW, so +// an edit made between the two is what lands. Closing the document empties a clipboard taken +// from it, and an entry gone by the time of the paste is skipped and named. +// +// The registers' half (the reader each document registers, closeSource) and the transfer's half +// (what a paste does with what the reader answered), with a fake document; each engine's own +// reader is pinned in its clipboard tests. +import { describe, expect, it } from 'vitest'; +import { + createRegisters, + goneMessage, + runTransfer, + TransferRefused, + type ClipboardItem, + type TransferAdapter, + type TransferCommit, + type TransferDeps, + type TransferTarget, +} from '../src/model/index.js'; + +const A = 'file:///work/a.sldd'; +const B = 'file:///work/b.sldd'; + +function item(name: string, value: unknown = 1, sourceSection = 'design'): ClipboardItem { + return { + payload: { name, metadata: { uuid: `u-${name}` }, value }, + sourceSection, + className: 'double', + arrayClass: 'double', + kind: 'Variable', + isMatlabVariable: true, + isScalarNumeric: true, + }; +} + +function fakeAdapter(docUri = B) { + const log = { commits: [] as TransferCommit[], reports: [] as string[], failures: [] as unknown[] }; + const adapter: TransferAdapter = { + docUri, + resolveTarget: () => ({ sectionName: 'design' }), + commit: (plan) => void log.commits.push(plan), + onFailure: (err) => void log.failures.push(err), + report: (message) => void log.reports.push(message), + }; + return { adapter, log }; +} + +function fakeDeps() { + const deletes: { uri: string; selectors: unknown[] }[] = []; + const warnings: string[] = []; + const deps: TransferDeps = { + deleteFromSource: async (uri, selectors) => { + deletes.push({ uri, selectors }); + return { removed: true }; + }, + warn: (message) => void warnings.push(message), + }; + return { deps, deletes, warnings }; +} + +describe('a paste reads the clipboard from its document at paste time', () => { + it('hands the reader what was taken, and pastes what it answers', async () => { + const r = createRegisters(); + const asked: (readonly ClipboardItem[])[] = []; + r.registerSourceReader(A, (items) => { + asked.push(items); + return { items: [item('x', 555)], gone: [] }; + }); + const taken = [item('x', -100000)]; + r.setClipboard(taken, 'copy', A); + const { adapter, log } = fakeAdapter(); + const out = await runTransfer({ rowId: 'r' }, r.clipboardRegister(() => {}), adapter, fakeDeps().deps); + expect(out).toEqual({ kind: 'done' }); + expect(asked).toEqual([taken]); + expect(log.commits.map((c) => c.payloads)).toEqual([[item('x', 555).payload]]); + }); + + it('a cut moves the entry as it is now: the fresh name is the one deleted from its document', async () => { + const r = createRegisters(); + r.registerSourceReader(A, () => ({ items: [item('renamed', 2)], gone: [] })); + r.setClipboard([item('x')], 'cut', A); + const { adapter, log } = fakeAdapter(); + const { deps, deletes } = fakeDeps(); + const out = await runTransfer({ rowId: 'r' }, r.clipboardRegister(() => {}), adapter, deps); + expect(out).toEqual({ kind: 'done' }); + expect(log.commits[0]!.payloads).toEqual([item('renamed', 2).payload]); + expect(deletes).toEqual([{ uri: A, selectors: [{ name: 'renamed', uuid: 'u-renamed' }] }]); + expect(r.getClipboard()).toBeNull(); + }); + + it('pastes what is left, and names what is no longer there', async () => { + const r = createRegisters(); + r.registerSourceReader(A, () => ({ items: [item('y')], gone: ['x'] })); + r.setClipboard([item('x'), item('y')], 'copy', A); + const { adapter, log } = fakeAdapter(); + const { deps, warnings } = fakeDeps(); + const out = await runTransfer({ rowId: 'r' }, r.clipboardRegister(() => {}), adapter, deps); + const message = 'Not pasted: "x" is no longer in a.sldd.'; + expect(out).toEqual({ kind: 'done', skipped: message }); + expect(log.commits.map((c) => c.payloads.map((p) => p.name))).toEqual([['y']]); + expect(log.reports).toEqual([message]); + expect(warnings).toEqual([message]); + expect(r.getClipboard()?.mode, 'a copy stays on the clipboard').toBe('copy'); + }); + + it('pastes nothing when every entry is gone, says so, and empties the clipboard', async () => { + const r = createRegisters(); + r.registerSourceReader(A, () => ({ items: [], gone: ['x', 'y'] })); + r.setClipboard([item('x'), item('y')], 'cut', A); + let broadcasts = 0; + const { adapter, log } = fakeAdapter(); + const { deps, deletes } = fakeDeps(); + const out = await runTransfer({ rowId: 'r' }, r.clipboardRegister(() => void broadcasts++), adapter, deps); + const message = 'Nothing to paste: "x" and "y" are no longer in a.sldd.'; + expect(out).toEqual({ kind: 'gone', message }); + expect(log.reports).toEqual([message]); + expect(log.commits).toEqual([]); + expect(deletes).toEqual([]); + expect(r.getClipboard()).toBeNull(); + expect(broadcasts).toBe(1); + }); + + it('a reader that refuses is said as it is, and changes nothing', async () => { + const r = createRegisters(); + r.registerSourceReader(A, () => { + throw new TransferRefused('Cannot copy "x": it is too big.'); + }); + r.setClipboard([item('x')], 'cut', A); + const { adapter, log } = fakeAdapter(); + const out = await runTransfer({ rowId: 'r' }, r.clipboardRegister(() => {}), adapter, fakeDeps().deps); + expect(out).toEqual({ kind: 'refused', message: 'Cannot copy "x": it is too big.' }); + expect(log.reports).toEqual(['Cannot copy "x": it is too big.']); + expect(log.commits).toEqual([]); + expect(r.getClipboard()?.mode, 'the cut stays for another try').toBe('cut'); + }); + + it('a drop is not re-read: a drag has no time between its start and its drop', async () => { + const r = createRegisters(); + let asked = 0; + r.registerSourceReader(A, () => { + asked++; + return { items: [], gone: ['x'] }; + }); + r.setDrag(A, [item('x')]); + const { adapter, log } = fakeAdapter(); + await runTransfer({ rowId: 'r' }, r.dragRegister('copy', () => {}), adapter, fakeDeps().deps); + expect(asked).toBe(0); + expect(log.commits.map((c) => c.payloads.map((p) => p.name))).toEqual([['x']]); + }); +}); + +describe('closing a document', () => { + it('empties a clipboard taken from it, Copy or Cut, and tells every table', () => { + for (const mode of ['copy', 'cut'] as const) { + const r = createRegisters(); + const heard: unknown[] = []; + r.listen({ clipboard: (state) => void heard.push(state.canPaste) }); + r.setClipboard([item('x')], mode, A); + r.closeSource(A); + expect(r.getClipboard(), mode).toBeNull(); + expect(heard, mode).toEqual([false]); + } + }); + + it('leaves a clipboard taken from another document alone', () => { + const r = createRegisters(); + const heard: unknown[] = []; + r.listen({ clipboard: (state) => void heard.push(state.canPaste) }); + r.setClipboard([item('x')], 'cut', A); + r.closeSource(B); + expect(r.getClipboard()?.sourceDocUri).toBe(A); + expect(heard).toEqual([]); + }); + + it('drops its deleter and its reader', async () => { + const r = createRegisters(); + let read = 0; + r.registerSourceDeleter(A, () => ({ removed: true })); + r.registerSourceReader(A, (items) => { + read++; + return { items: [...items], gone: [] }; + }); + r.closeSource(A); + expect(await r.deleteFromSource(A, ['x'])).toEqual({ removed: false, reason: 'its table is no longer open' }); + r.setClipboard([item('x')], 'copy', A); + r.clipboardRegister(() => {}).read(); + expect(read).toBe(0); + }); +}); + +describe('goneMessage', () => { + it('names each entry, and says whether anything was pasted', () => { + expect(goneMessage(['x'], A, true)).toBe('Nothing to paste: "x" is no longer in a.sldd.'); + expect(goneMessage(['x'], A, false)).toBe('Not pasted: "x" is no longer in a.sldd.'); + expect(goneMessage(['x', 'y', 'z'], A, false)).toBe('Not pasted: "x", "y" and "z" are no longer in a.sldd.'); + expect(goneMessage(['a', 'b', 'c', 'd', 'e', 'f', 'g'], undefined, false)).toBe( + 'Not pasted: "a", "b", "c", "d", "e" and 2 more are no longer in their file.', + ); + }); +}); diff --git a/test/matEngine/clipboard.test.ts b/test/matEngine/clipboard.test.ts index a42ee9f3..8eda757b 100644 --- a/test/matEngine/clipboard.test.ts +++ b/test/matEngine/clipboard.test.ts @@ -429,25 +429,19 @@ describe('MAT-file engine: pastes and drops refused', () => { assert.deepStrictEqual(w.registers.getClipboard()?.items.map((i) => i.payload.name), ['str']); }); - it('a move whose original became one of two of its name is pasted, and the original kept, said', async () => { + it('a cut whose original became one of two of its name is not pasted: which one it was cannot be told', async () => { const w = windowOf(); const a = await w.open('back.mat', fixture('pv_basic.mat')); const t = await w.open('target.mat', emptyMat()); - const warnings: string[] = []; a.view.send({ type: 'cut', rowIds: [variableRow(a.view.posts, 'x').ID] }); // The file is read again holding two x (an outside change, with no unsaved edit): the cut's - // original is now one of two. + // original is now one of two, and the paste reads it back from the file as it is now. await a.engine.replace(buffer(twiceNamedMat())); assert.deepStrictEqual(namesOf(a), ['x', 'str', 'x']); await onMat(t, { type: 'paste', rowId: '' }); - await waitFor('the cut to be spent', () => w.registers.getClipboard() === null); - await waitFor('the report', () => errorsIn(t.view.posts).length > 0); - const said = - 'Pasted here, but the original in back.mat could not be removed: it holds more than one "x", and a move takes its original out by name. Remove it there by hand.'; - assert.deepStrictEqual(errorsIn(t.view.posts), [said]); - for (const n of t.notices) warnings.push(n.message); - assert.deepStrictEqual(warnings, [said], 'said where it stays, too'); - assert.ok(namesOf(t).includes('x'), 'the paste landed'); + assert.deepStrictEqual(errorsIn(t.view.posts), ['Nothing to paste: "x" is no longer in back.mat.']); + assert.strictEqual(w.registers.getClipboard(), null, 'nothing is left to paste'); + assert.deepStrictEqual(namesOf(t), [], 'nothing landed'); assert.deepStrictEqual(namesOf(a), ['x', 'str', 'x'], 'and nothing was guessed at in the source'); assert.strictEqual(a.events.length, 0); }); @@ -480,7 +474,7 @@ describe('MAT-file engine: pastes and drops refused', () => { // A cut is lazy and a MAT-file's variable is told by name alone, so between the cut and the // paste the original can be deleted and another variable given its name. The cut carries who - // the original was (originOf), and the move takes out only that one. + // the original was (originOf): the paste reads back only that one, and the move takes out only it. const giveNameX = async (a: Opened, from: string) => { await onMat(a, { type: 'addEntry', section: '', className: 'MatlabVariable', rename: false }); const added = namesOf(a).find((n) => !from.split(',').includes(n))!; @@ -488,7 +482,7 @@ describe('MAT-file engine: pastes and drops refused', () => { assert.ok(namesOf(a).includes('x'), 'another variable now holds the name'); }; - it('a cut whose variable was deleted and its name given to another: the paste lands, and the other is left alone', async () => { + it('a cut whose variable was deleted and its name given to another: nothing is pasted, it is said, and the other is left alone', async () => { const w = windowOf(); const a = await w.open('cut.mat', fixture('pv_basic.mat')); const t = await w.open('target.mat', emptyMat()); @@ -498,30 +492,27 @@ describe('MAT-file engine: pastes and drops refused', () => { const other = variableOf(a, 'x'); const edits = a.events.length; await onMat(t, { type: 'paste', rowId: '' }); - await waitFor('the cut to be spent', () => w.registers.getClipboard() === null); - await waitFor('the report', () => errorsIn(t.view.posts).length > 0); - assert.deepStrictEqual(errorsIn(t.view.posts), [ - 'Pasted here; the original in cut.mat is no longer there to remove: the "x" it holds now is another variable, which was left as it is.', - ]); - assert.ok(namesOf(t).includes('x'), 'the paste landed'); + assert.deepStrictEqual(errorsIn(t.view.posts), ['Nothing to paste: "x" is no longer in cut.mat.']); + assert.strictEqual(w.registers.getClipboard(), null, 'nothing is left to paste'); + assert.deepStrictEqual(namesOf(t), [], 'the other variable was not pasted in its place'); assert.strictEqual(variableOf(a, 'x'), other, 'and the variable that holds the name now was not taken out'); assert.strictEqual(a.events.length, edits, 'no edit in the source'); }); - it('a cut whose variable was renamed and its name given to another: nothing is taken out, and the renamed one is named', async () => { + it('a cut whose variable was renamed and its name given to another moves the renamed one, and leaves the other alone', async () => { const w = windowOf(); const a = await w.open('renamed.mat', fixture('pv_basic.mat')); const t = await w.open('target.mat', emptyMat()); a.view.send({ type: 'cut', rowIds: [variableRow(a.view.posts, 'x').ID] }); await onMat(a, { type: 'edit', rowId: variableOf(a, 'x').id, columnId: 'Name', oldValue: 'x', newValue: 'y' }); await giveNameX(a, namesOf(a).join()); + const other = variableOf(a, 'x'); await onMat(t, { type: 'paste', rowId: '' }); await waitFor('the cut to be spent', () => w.registers.getClipboard() === null); - await waitFor('the report', () => errorsIn(t.view.posts).length > 0); - assert.deepStrictEqual(errorsIn(t.view.posts), [ - 'Pasted here, but the original in renamed.mat could not be removed: the "x" it holds now is another variable, and the one taken is now "y". Remove it there by hand.', - ]); - assert.ok(namesOf(a).includes('x') && namesOf(a).includes('y'), 'both are where they were'); + await waitFor('the renamed original to move out', () => !namesOf(a).includes('y')); + assert.deepStrictEqual(errorsIn(t.view.posts), []); + assert.deepStrictEqual(namesOf(t), ['y'], 'the variable the cut took, under the name it has now'); + assert.strictEqual(variableOf(a, 'x'), other, 'and the one that holds its old name stays'); }); it('a cut whose variable was edited, or deleted and the delete undone, is still the one taken, and moves', async () => { @@ -534,6 +525,7 @@ describe('MAT-file engine: pastes and drops refused', () => { await waitFor('the cut to be spent', () => w.registers.getClipboard() === null); await waitFor('the original moved out', () => !namesOf(a).includes('x')); assert.deepStrictEqual(errorsIn(t.view.posts), []); + assert.strictEqual(shownCells(variableOf(t, 'x'))['.']!.Value, '[4 5]', 'the value it was edited to after the cut'); a.view.send({ type: 'cut', rowIds: [variableRow(a.view.posts, 'p').ID] }); await onMat(a, { type: 'delete', rowIds: [variableOf(a, 'p').id] }); diff --git a/test/matEngine/lateCopy.test.ts b/test/matEngine/lateCopy.test.ts new file mode 100644 index 00000000..b87b5de8 --- /dev/null +++ b/test/matEngine/lateCopy.test.ts @@ -0,0 +1,122 @@ +// Copyright 2026 The MathWorks, Inc. +// +// A MAT-file's clipboard is read at paste time (registers.ts's SourceReader): each variable a Cut +// or a Copy took is found again by its origin token — the same node through edits and a rename — +// and pasted as it is then, as the Data Explorer in MATLAB resolves its clipboard. A +// variable deleted in between is named and not pasted, and closing the file empties a clipboard +// taken from it. +import * as assert from 'node:assert'; +import { createSession } from 'data-explorer-core'; +import { describe, it } from 'vitest'; +import { createRegisters } from '../../src/model/index.js'; +import { buffer, emptyMat, errorsIn, fixture, namesOf, open, shownCells, tableOf, variableOf, waitFor, type Opened } from './harness.js'; + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +function windowOf() { + const registers = createRegisters(); + const session = createSession(); + return { + registers, + source: () => open('gains.mat', fixture('pv_basic.mat'), { as: 'gains.mat', registers, session }), + target: () => open('other.mat', emptyMat(), { as: 'other.mat', registers, session }), + }; +} + +const rowOf = (tab: Opened, name: string): any => { + const row = tableOf(tab.view.posts).find((r) => r.parent == null && r.Name?.label === name); + assert.ok(row, `the table has a row for "${name}"`); + return row; +}; + +/** Send a gesture and wait for its edit, or its word. */ +async function gesture(tab: Opened, msg: Record): Promise { + const edits = tab.events.length; + tab.view.posts.length = 0; + tab.view.send(msg); + await waitFor(`the ${String(msg.type)} to land or be refused`, () => tab.events.length > edits || errorsIn(tab.view.posts).length > 0); + return errorsIn(tab.view.posts); +} + +/** A value edit or a rename of the variable `name`, as the table sends one. */ +const editOf = (tab: Opened, name: string, columnId: string, newValue: string) => ({ + type: 'edit', + rowId: rowOf(tab, name).ID, + columnId, + oldValue: '', + newValue, +}); + +const valueOf = (tab: Opened, name: string): string => { + const variable = variableOf(tab, name); + assert.ok(variable, `${name} is in the file`); + return shownCells(variable)['.']!.Value!; +}; + +describe('a MAT-file clipboard, read at paste time', () => { + it('a Cut, an edit of the cut variable, then a paste moves the edited value', async () => { + const w = windowOf(); + const source = await w.source(); + source.view.send({ type: 'cut', rowIds: [rowOf(source, 'x').ID] }); + assert.deepStrictEqual(await gesture(source, editOf(source, 'x', 'Value', '42')), []); + const target = await w.target(); + assert.deepStrictEqual(await gesture(target, { type: 'paste', rowId: '' }), []); + assert.strictEqual(valueOf(target, 'x'), '42', 'the value typed after the Cut is the one pasted'); + await waitFor('the original to leave the source', () => !namesOf(source).includes('x')); + }); + + it('a variable renamed after the Copy is pasted under its new name', async () => { + const w = windowOf(); + const source = await w.source(); + const before = valueOf(source, 'x'); + source.view.send({ type: 'copy', rowIds: [rowOf(source, 'x').ID] }); + assert.deepStrictEqual(await gesture(source, editOf(source, 'x', 'Name', 'x0')), []); + const target = await w.target(); + assert.deepStrictEqual(await gesture(target, { type: 'paste', rowId: '' }), []); + assert.deepStrictEqual(namesOf(target), ['x0']); + assert.strictEqual(valueOf(target, 'x0'), before); + }); + + it('a variable deleted after the Copy is not pasted, and the paste says so', async () => { + const w = windowOf(); + const source = await w.source(); + source.view.send({ type: 'copy', rowIds: [rowOf(source, 'x').ID] }); + await gesture(source, { type: 'delete', rowIds: [rowOf(source, 'x').ID] }); + const target = await w.target(); + const edits = target.events.length; + assert.deepStrictEqual(await gesture(target, { type: 'paste', rowId: '' }), ['Nothing to paste: "x" is no longer in gains.mat.']); + assert.strictEqual(target.events.length, edits); + assert.deepStrictEqual(namesOf(target), []); + }); + + it('a Copy, then the file read again from disk, then a paste reads the variable from the file as it is now', async () => { + const w = windowOf(); + const source = await w.source(); + // What the disk holds after an outside writer (MATLAB) set x to 42 and saved. + const outside = await open('gains.mat', fixture('pv_basic.mat'), { as: 'outside.mat' }); + await gesture(outside, editOf(outside, 'x', 'Value', '42')); + const written = outside.save(); + for (const mode of ['copy', 'cut']) { + source.view.send({ type: mode, rowIds: [rowOf(source, 'x').ID] }); + await source.engine.replace(buffer(written)); + const target = await w.target(); + assert.deepStrictEqual(await gesture(target, { type: 'paste', rowId: '' }), [], mode); + assert.strictEqual(valueOf(target, 'x'), '42', `${mode}: the variable as the file holds it now`); + } + await waitFor('the cut to take x out of the source', () => !namesOf(source).includes('x')); + }); + + it('closing the file empties a clipboard taken from it, Copy or Cut', async () => { + for (const mode of ['copy', 'cut']) { + const w = windowOf(); + const source = await w.source(); + source.view.send({ type: mode, rowIds: [rowOf(source, 'x').ID] }); + assert.strictEqual(w.registers.getClipboard()?.mode, mode); + source.view.close(); + assert.strictEqual(w.registers.getClipboard(), null, `the ${mode} went with the file`); + const target = await w.target(); + assert.deepStrictEqual(await gesture(target, { type: 'paste', rowId: '' }), ['Nothing to paste — the clipboard is empty.']); + assert.deepStrictEqual(namesOf(target), []); + } + }); +}); diff --git a/test/matEngine/workspace.test.ts b/test/matEngine/workspace.test.ts index 64a65fcc..eb3024a0 100644 --- a/test/matEngine/workspace.test.ts +++ b/test/matEngine/workspace.test.ts @@ -184,16 +184,15 @@ describe('createWorkspace({editing}): a MAT-file edited in the page', () => { const ws = workspace(true, notices); const doc = await ws.open(fixture('cases.mat'), 'cases.mat'); await doc.table.open(); - const cut = await ws.open(fixture('pv_basic.mat'), 'twin.mat'); - await cut.table.open(); - // A cut whose source no longer has a table open: the paste lands, and the source keeps it. - (cut.table as any).cut([variableId(cut, 'x')]); - cut.dispose(); + const twin = await ws.open(fixture('pv_basic.mat'), 'twin.mat'); + await twin.table.open(); + // A copy of two variables, one of them deleted before the paste: the other lands, and the + // paste says which one it could not paste. + (twin.table as any).copy([variableId(twin, 'x'), variableId(twin, 'p')]); + (twin.table as any).delete([variableId(twin, 'x')]); + await settle(); (doc.table as any).paste(''); await settle(); - assert.deepStrictEqual( - notices.map((n) => [n.level, n.message]), - [['warning', 'Pasted here, but the original in twin.mat could not be removed: its table is no longer open. Remove it there by hand.']], - ); + assert.deepStrictEqual(notices.map((n) => [n.level, n.message]), [['warning', 'Not pasted: "x" is no longer in twin.mat.']]); }); }); diff --git a/test/shell/harness.ts b/test/shell/harness.ts index fd8626e2..51c79cb4 100644 --- a/test/shell/harness.ts +++ b/test/shell/harness.ts @@ -344,9 +344,13 @@ export async function valueIn(bytes: Uint8Array, file: string, row: string): Pro /** The last bytes saved to `name`. */ export const savedTo = (main: Main, name: string) => main.saves.filter((s) => s.path === at(name)).at(-1)?.bytes; -/** The items the shared context menu shows when row `row` of `name` is right-clicked (none: no menu). */ -export async function menuOn(name: string, row: string): Promise<{ id: string; label: string; disabled?: boolean }[]> { +/** + * The items the shared context menu shows when row `row` of `name` is right-clicked (none: no menu), + * with the rows `alsoSelected` selected beside it, as a ctrl-click selects them first. + */ +export async function menuOn(name: string, row: string, alsoSelected: string[] = []): Promise<{ id: string; label: string; disabled?: boolean }[]> { const r = await rowOf(name, row); + const others = await Promise.all(alsoSelected.map((other) => rowOf(name, other))); const table = tableOf(name)!; const menu = document.querySelector('dex-context-menu')!; let shown: { id: string; label: string; disabled?: boolean }[] = []; @@ -355,7 +359,7 @@ export async function menuOn(name: string, row: string): Promise<{ id: string; l shown = items.filter((i) => !i.separator).map((i) => ({ id: i.id, label: i.label, disabled: i.disabled })); show(x, y, items); }; - table.selectedRowIds = [r.ID]; + table.selectedRowIds = [r.ID, ...others.map((o) => o.ID)]; table.dispatchEvent(new CustomEvent('dex-table-context-menu', { detail: { x: 0, y: 0, rowId: r.ID }, bubbles: true, composed: true })); menu.show = show; return shown; diff --git a/test/shell/log.test.ts b/test/shell/log.test.ts index ce6bd4a1..4fec5dfa 100644 --- a/test/shell/log.test.ts +++ b/test/shell/log.test.ts @@ -12,7 +12,7 @@ import { afterEach, describe, expect, it } from 'vitest'; import { portFromMessagePort } from '../../src/model/source/ports.js'; import { serveFolder, type FolderReads } from '../../src/serve/index.js'; import type { LogEntry } from '../../src/widgets/app-shell/modules/dex-log-panel.js'; -import { at, changedOutside, choose, commandWindow, dirtyTabs, edit, folderReads, logPanel, menuOn, open, rowOf, serveFolderTo, startPage, tempFolder, until, type Page } from './harness.js'; +import { at, changedOutside, choose, commandWindow, dirtyTabs, edit, folderReads, logPanel, menuOn, open, rowOf, serveFolderTo, startPage, tableOf, tempFolder, until, type Page } from './harness.js'; let stop: (() => void)[] = []; afterEach(() => { @@ -68,15 +68,17 @@ describe('the Log view', () => { await edit('params.sldd', 'Kp', 'Ki', 'Name'); await until(() => lines.length >= 1); expect(lines[0]).toMatch(/^warning .*Ki/); - // A cut whose original was renamed before the paste: the workspace's warning. + // A copy of two entries, one of them deleted before the paste: the workspace's warning. + await menuOn('params.sldd', 'Uo', ['Kp']); + choose('copy'); await menuOn('params.sldd', 'Uo'); - choose('cut'); - await edit('params.sldd', 'Uo', 'Uo2', 'Name'); - await rowOf('params.sldd', 'Uo2'); + choose('delete'); + await until(() => !tableOf('params.sldd')!.rows.some((r) => r.Name?.label === 'Uo')); await menuOn('ParamMat.mat', 'ParamMat'); choose('paste'); - await until(() => lines.some((l) => l.includes('the original in params.sldd could not be removed'))); - expect(lines.find((l) => l.includes('could not be removed'))!.startsWith('warning ')).toBe(true); + const skipped = 'Not pasted: "Uo" is no longer in params.sldd.'; + await until(() => lines.some((l) => l.includes(skipped))); + expect(lines.find((l) => l.includes(skipped))!.startsWith('warning ')).toBe(true); }); it('says a gesture the document refused, and a copy that did not reach the clipboard', async () => { diff --git a/test/shell/toasts.test.ts b/test/shell/toasts.test.ts index ba745f5e..e310b73f 100644 --- a/test/shell/toasts.test.ts +++ b/test/shell/toasts.test.ts @@ -7,7 +7,7 @@ // activeConfig.test.ts read the workspace's warnings there now. import { describe, expect, it, vi } from 'vitest'; import type { Toast } from '../../src/widgets/app-shell/dex-toast-host.js'; -import { at, choose, dirtyTabs, edit, menuOn, open, rowOf, startPage, tabNames, toastHost, toastTexts, until } from './harness.js'; +import { at, choose, dirtyTabs, edit, menuOn, open, rowOf, startPage, tableOf, tabNames, toastHost, toastTexts, until } from './harness.js'; const FILES = { 'params.sldd': 'params.sldd', 'ParamMat.mat': 'ParamMat.mat' }; @@ -43,17 +43,18 @@ describe('toasts', () => { expect(shown[0]).toEqual({ level: 'info', message: 'Saved copy.sldd', ms: 2000 }); }); - it("the workspace's notices come as they are: a cut whose original stayed is a warning that stays", async () => { + it("the workspace's notices come as they are: an entry a paste could not paste is a warning", async () => { const page = startPage(FILES); const shown = shownToasts(); await open(page, 'params.sldd', 'ParamMat.mat'); + await menuOn('params.sldd', 'Uo', ['Kp']); + choose('copy'); await menuOn('params.sldd', 'Uo'); - choose('cut'); - await edit('params.sldd', 'Uo', 'Uo2', 'Name'); - await rowOf('params.sldd', 'Uo2'); + choose('delete'); + await until(() => !tableOf('params.sldd')!.rows.some((r) => r.Name?.label === 'Uo')); await menuOn('ParamMat.mat', 'ParamMat'); choose('paste'); await until(() => shown.some((t) => t.level === 'warning')); - expect(shown.find((t) => t.level === 'warning')!.message).toContain('the original in params.sldd could not be removed'); + expect(shown.find((t) => t.level === 'warning')!.message).toBe('Not pasted: "Uo" is no longer in params.sldd.'); }); }); diff --git a/test/shell/undo.test.ts b/test/shell/undo.test.ts index 6a4035eb..7055a9ec 100644 --- a/test/shell/undo.test.ts +++ b/test/shell/undo.test.ts @@ -133,7 +133,7 @@ describe('between tabs', () => { expect(await valueIn(savedTo(page.main, 'params.sldd')!, 'params.sldd', 'Uo')).toBe(''); }); - it('a cut whose original was renamed before the paste says, in a toast that stays, that the original stayed', async () => { + it('a cut whose original was renamed before the paste moves it, under the name it has now', async () => { const page = startPage(FILES); await open(page, 'params.sldd', 'ParamMat.mat'); await menuOn('params.sldd', 'Uo'); @@ -142,10 +142,24 @@ describe('between tabs', () => { await rowOf('params.sldd', 'Uo2'); await menuOn('ParamMat.mat', 'ParamMat'); choose('paste'); - const toast = () => toastHost().shadowRoot?.querySelector('.toast'); + await rowOf('ParamMat.mat', 'Uo2'); + await until(() => !tableOf('params.sldd')!.rows.some((r) => r.Name?.label === 'Uo2')); + expect(tableOf('ParamMat.mat')!.rows.some((r) => r.Name?.label === 'Uo')).toBe(false); + }); + + it('an entry deleted between its copy and the paste is said in a toast that stays', async () => { + const page = startPage(FILES); + await open(page, 'params.sldd', 'ParamMat.mat'); + await menuOn('params.sldd', 'Uo', ['Kp']); + choose('copy'); + await menuOn('params.sldd', 'Uo'); + choose('delete'); + await until(() => !tableOf('params.sldd')!.rows.some((r) => r.Name?.label === 'Uo')); + await menuOn('ParamMat.mat', 'ParamMat'); + choose('paste'); + const toast = () => toastHost().shadowRoot?.querySelector('.toast.warning'); await until(() => !!toast()); - expect(toast()!.classList.contains('warning')).toBe(true); - expect(toast()!.textContent).toContain('the original in params.sldd could not be removed'); + expect(toast()!.textContent).toContain('Not pasted: "Uo" is no longer in params.sldd.'); toast()!.querySelector('.dismiss')!.click(); await until(() => !toast()); }); From 941e21b7242e46ee28cae7cfb1ca9793d3ed30a0 Mon Sep 17 00:00:00 2001 From: Wei Wang Date: Thu, 19 Nov 2026 16:40:00 -0500 Subject: [PATCH 2/2] Bump to 1.11.0 --- README.md | 2 +- dist/model/version.js | 2 +- package-lock.json | 4 ++-- package.json | 2 +- src/model/version.ts | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index a50e5735..ad36677b 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ release notes before you move the pin. ```json "dependencies": { - "data-explorer-view": "github:mathworks/data-explorer-view#v1.10.1", + "data-explorer-view": "github:mathworks/data-explorer-view#v1.11.0", "data-explorer-core": "github:mathworks/data-explorer-core#v1.59.0", "lit": "^3.2.0" } diff --git a/dist/model/version.js b/dist/model/version.js index b1436c1e..691c7296 100644 --- a/dist/model/version.js +++ b/dist/model/version.js @@ -1,4 +1,4 @@ // Copyright 2026 The MathWorks, Inc. // GENERATED by scripts/gen-version.mjs from package.json. Do not edit. /** This package's version, as its package.json says: what an app's About shows for data-explorer-view. */ -export const VIEW_VERSION = '1.10.1'; +export const VIEW_VERSION = '1.11.0'; diff --git a/package-lock.json b/package-lock.json index e69f2903..b39da3d4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "data-explorer-view", - "version": "1.10.1", + "version": "1.11.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "data-explorer-view", - "version": "1.10.1", + "version": "1.11.0", "license": "BSD-3-Clause", "devDependencies": { "@custom-elements-manifest/analyzer": "^0.11.0", diff --git a/package.json b/package.json index 3bb504c4..d67cc345 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "data-explorer-view", - "version": "1.10.1", + "version": "1.11.0", "description": "Widgets and view model for Simulink data files, built on data-explorer-core", "license": "BSD-3-Clause", "type": "module", diff --git a/src/model/version.ts b/src/model/version.ts index 9d5ce7e3..c6d055dc 100644 --- a/src/model/version.ts +++ b/src/model/version.ts @@ -2,4 +2,4 @@ // GENERATED by scripts/gen-version.mjs from package.json. Do not edit. /** This package's version, as its package.json says: what an app's About shows for data-explorer-view. */ -export const VIEW_VERSION: string = '1.10.1'; +export const VIEW_VERSION: string = '1.11.0';