From bec217417773b04081b2b32640ba07642e049fb9 Mon Sep 17 00:00:00 2001 From: tnaum-ms <171359267+tnaum-ms@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:27:59 +0000 Subject: [PATCH 1/7] Initial plan From b5f6021d4e7f4670fc199d06f64326ea43511d3a Mon Sep 17 00:00:00 2001 From: tnaum-ms <171359267+tnaum-ms@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:31:55 +0000 Subject: [PATCH 2/7] Use executed projection for Table columns Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- src/documentdb/ClusterSession.test.ts | 53 +++++++++++++++++++ src/documentdb/ClusterSession.ts | 52 ++++++++++++------- src/utils/documentGrid/toTablePage.ts | 75 +++++++++++++++------------ 3 files changed, 126 insertions(+), 54 deletions(-) create mode 100644 src/documentdb/ClusterSession.test.ts diff --git a/src/documentdb/ClusterSession.test.ts b/src/documentdb/ClusterSession.test.ts new file mode 100644 index 000000000..ac5c1c3b4 --- /dev/null +++ b/src/documentdb/ClusterSession.test.ts @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { fieldColumnKey, getCell } from '../utils/documentGrid/types'; +import { ClusterSession } from './ClusterSession'; + +const runFindQuery = vi.hoisted(() => vi.fn()); +vi.mock('./ClustersClient', () => ({ + ClustersClient: { getClient: () => Promise.resolve({ runFindQuery }) }, +})); +vi.mock('../extensionVariables', () => ({ ext: { outputChannel: { trace: vi.fn() } } })); + +describe('ClusterSession Table pages', () => { + let sessionId: string; + let session: ClusterSession; + + beforeEach(async () => { + runFindQuery.mockReset(); + sessionId = await ClusterSession.initNewSession('table-test'); + session = ClusterSession.getSession(sessionId); + }); + + afterEach(() => ClusterSession.closeSession(sessionId)); + + it('uses only executed projection fields without clearing the shared schema', async () => { + runFindQuery + .mockResolvedValueOnce([{ _id: 1, title: 'a', rating: 5, secret: 'wide' }]) + .mockResolvedValueOnce([{ title: 'a' }, { rating: 0 }]) + .mockResolvedValueOnce([]) + .mockResolvedValueOnce([{ _id: 2, title: 'b' }]); + + await session.runFindQueryWithCache('db', 'projection', {}, 1, 50); + const headers = (): readonly string[] => session.getCurrentPageAsTable([]).columns.map(({ label }) => label); + expect(headers()).toEqual(expect.arrayContaining(['_id', 'title', 'rating', 'secret'])); + + const project = '{ title: 1, rating: 1, _id: 0 }'; + await session.runFindQueryWithCache('db', 'projection', { project }, 1, 50); + const projected = session.getCurrentPageAsTable([]); + expect(projected.columns.map(({ label }) => label)).toEqual(['title', 'rating']); + expect(getCell(projected.rows[0], fieldColumnKey('rating'))).toBeUndefined(); + expect(getCell(projected.rows[1], fieldColumnKey('rating'))?.display).toBe('0'); + expect(session.getKnownFields()).toEqual(expect.arrayContaining([expect.objectContaining({ path: 'secret' })])); + + await session.runFindQueryWithCache('db', 'projection', { filter: '{ rating: 99 }', project }, 1, 50); + expect(headers()).toEqual([]); + + await session.runFindQueryWithCache('db', 'projection', { project: '{ }' }, 1, 50); + expect(headers()).toEqual(expect.arrayContaining(['_id', 'title', 'rating', 'secret'])); + }); +}); diff --git a/src/documentdb/ClusterSession.ts b/src/documentdb/ClusterSession.ts index 3514dd414..9c5959000 100644 --- a/src/documentdb/ClusterSession.ts +++ b/src/documentdb/ClusterSession.ts @@ -92,6 +92,7 @@ export class ClusterSession { */ private _currentRawDocuments: WithId[] = []; private _currentPageIdentityTrusted = false; + private _currentPageProjected = false; /** * Query Insights caching @@ -231,6 +232,23 @@ export class ClusterSession { pageSize: number, executionIntent: 'initial' | 'refresh' | 'pagination' = 'pagination', ): Promise { + let projected = false; + let identityTrusted = true; + if (queryParams.project && queryParams.project.trim() !== '{}') { + try { + const projection: unknown = parseShellBSON(queryParams.project, { mode: ParseMode.Loose }); + if (projection !== null && typeof projection === 'object' && !Array.isArray(projection)) { + projected = Object.keys(projection).length > 0; + identityTrusted = isIdentityTrustedForProjection(projection as Document); + } else { + identityTrusted = false; + } + } catch { + // The query execution retains its existing projection-error reporting. + identityTrusted = false; + } + } + const querySkip = queryParams.skip ?? 0; const queryLimit = queryParams.limit ?? 0; @@ -246,6 +264,7 @@ export class ClusterSession { // We're trying to page beyond the query's limit - return empty results this._currentRawDocuments = []; this._currentPageIdentityTrusted = false; + this._currentPageProjected = projected; return 0; } @@ -277,21 +296,6 @@ export class ClusterSession { limit: dbLimit, }; - let identityTrusted = true; - if (paginatedQueryParams.project && paginatedQueryParams.project.trim() !== '{}') { - try { - const projection: unknown = parseShellBSON(paginatedQueryParams.project, { mode: ParseMode.Loose }); - identityTrusted = - projection !== null && - typeof projection === 'object' && - !Array.isArray(projection) && - isIdentityTrustedForProjection(projection as Document); - } catch { - // The query execution retains its existing projection-error reporting. - identityTrusted = false; - } - } - // Track execution time for query insights const startTime = performance.now(); const documents: WithId[] = await this._client.runFindQuery( @@ -304,6 +308,7 @@ export class ClusterSession { // Update current page documents (always replace, not accumulate) this._currentRawDocuments = documents; this._currentPageIdentityTrusted = identityTrusted; + this._currentPageProjected = projected; // Store database/collection context for schema operations this._databaseName = databaseName; @@ -350,11 +355,18 @@ export class ClusterSession { } public getCurrentPageAsTable(path: string[]): TablePage { - const store = SchemaStore.getInstance(); - const headers = - this._databaseName && this._collectionName - ? store.getPropertyNamesAtLevel(this._clusterId, this._databaseName, this._collectionName, path) - : []; + let headers: readonly string[] | undefined; + if (!this._currentPageProjected) { + headers = + this._databaseName && this._collectionName + ? SchemaStore.getInstance().getPropertyNamesAtLevel( + this._clusterId, + this._databaseName, + this._collectionName, + path, + ) + : []; + } return toTablePage(this._currentRawDocuments, path, headers, this._currentPageIdentityTrusted); } diff --git a/src/utils/documentGrid/toTablePage.ts b/src/utils/documentGrid/toTablePage.ts index f6a0a35f1..9cf5f5f4b 100644 --- a/src/utils/documentGrid/toTablePage.ts +++ b/src/utils/documentGrid/toTablePage.ts @@ -94,50 +94,57 @@ export function toGridCellValue(value: unknown): GridCellValue { export function toTablePage( documents: readonly Document[], path: readonly string[], - headers: readonly string[], + schemaHeaders: readonly string[] | undefined, identityTrusted: boolean, ): TablePage { const identities = assignRowIdentities(documents, identityTrusted); - return { - path: [...path], - columns: [ - { key: ROOT_ID_COLUMN_KEY, label: '_id' }, - ...headers - .filter((field) => field !== '_id') - .map((field) => ({ key: fieldColumnKey(field), label: field })), - ], - rows: documents.map((document, index) => { - const cells: Partial> = {}; - if (Object.prototype.hasOwnProperty.call(document, '_id')) { - cells[ROOT_ID_COLUMN_KEY] = toGridCellValue(document._id); - } - - let subdocument: unknown = document; - for (const field of path) { - if ( - subdocument !== null && - typeof subdocument === 'object' && - Object.prototype.hasOwnProperty.call(subdocument, field) - ) { - subdocument = (subdocument as Document)[field] as unknown; - } else { - subdocument = undefined; - break; - } - } + // A projected page has no schema headers; discover fields from all returned rows instead. + const projectedFields = new Set(); + let hasRootId = schemaHeaders !== undefined; + const rows = documents.map((document, index) => { + const cells: Partial> = {}; + if (Object.prototype.hasOwnProperty.call(document, '_id')) { + hasRootId = true; + cells[ROOT_ID_COLUMN_KEY] = toGridCellValue(document._id); + } + let subdocument: unknown = document; + for (const field of path) { if ( subdocument !== null && typeof subdocument === 'object' && - (BSONTypes.inferType(subdocument) === BSONTypes.Object || Array.isArray(subdocument)) + Object.prototype.hasOwnProperty.call(subdocument, field) ) { - for (const [field, value] of Object.entries(subdocument)) { - if (field !== '_id') { - cells[fieldColumnKey(field)] = toGridCellValue(value); + subdocument = (subdocument as Document)[field] as unknown; + } else { + subdocument = undefined; + break; + } + } + + if ( + subdocument !== null && + typeof subdocument === 'object' && + (BSONTypes.inferType(subdocument) === BSONTypes.Object || Array.isArray(subdocument)) + ) { + for (const [field, value] of Object.entries(subdocument)) { + if (field !== '_id' || (schemaHeaders === undefined && path.length > 0)) { + cells[fieldColumnKey(field)] = toGridCellValue(value); + if (schemaHeaders === undefined) { + projectedFields.add(field); } } } - return { ...identities[index], cells }; - }), + } + return { ...identities[index], cells }; + }); + const fields = schemaHeaders?.filter((field) => field !== '_id') ?? [...projectedFields]; + return { + path: [...path], + columns: [ + ...(hasRootId ? [{ key: ROOT_ID_COLUMN_KEY, label: '_id' } as const] : []), + ...fields.map((field) => ({ key: fieldColumnKey(field), label: field })), + ], + rows, }; } From c726e326bd6a699b53a8e5858071585c6ebdf7be Mon Sep 17 00:00:00 2001 From: tnaum-ms <171359267+tnaum-ms@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:38:40 +0000 Subject: [PATCH 3/7] Add native full-value copy for Table cells Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../browser/collectionViewFixtures.ts | 4 + build/verification/browser/scenarios.ts | 12 ++ .../ai-and-plans/features/data-grid/README.md | 7 +- .../ai-and-plans/features/data-grid/design.md | 18 ++- docs/user-manual/collection-view-querying.md | 8 ++ package.json | 13 +++ package.nls.json | 1 + src/documentdb/ClusterSession.test.ts | 103 +++++++++++++++++- src/documentdb/ClusterSession.ts | 67 +++++++++++- src/documentdb/ClustersClient.ts | 2 + src/documentdb/ClustersExtension.ts | 2 + src/utils/documentGrid/toTablePage.ts | 27 ++--- src/utils/documentGrid/types.ts | 12 +- .../useSelectiveContextMenuPrevention.ts | 13 ++- .../collectionView/CollectionView.tsx | 38 ++++++- .../collectionView/collectionViewRouter.ts | 7 +- .../resultsTab/DataViewPanelTable.tsx | 84 +++++++++++--- .../collectionView/tableCellClipboard.ts | 46 ++++++++ 18 files changed, 409 insertions(+), 55 deletions(-) create mode 100644 src/webviews/documentdb/collectionView/tableCellClipboard.ts diff --git a/build/verification/browser/collectionViewFixtures.ts b/build/verification/browser/collectionViewFixtures.ts index 926f2abf0..388a872c2 100644 --- a/build/verification/browser/collectionViewFixtures.ts +++ b/build/verification/browser/collectionViewFixtures.ts @@ -371,6 +371,7 @@ const emptyPage: TablePageOutput = { }; const noIdPage: TablePageOutput = { + copyPageId: '4bf66698-74a7-4547-ad4c-607bc11a0f73', path: [], columns: [ { key: ROOT_ID_COLUMN_KEY, label: '_id' }, @@ -380,6 +381,7 @@ const noIdPage: TablePageOutput = { rows: [ { rowKey: 'pos:0', + copyRowIndex: 0, cells: { [fieldColumnKey('name')]: { display: 'Browse only', type: 'string' }, [fieldColumnKey('details')]: { display: '{...}', type: 'object' }, @@ -387,6 +389,7 @@ const noIdPage: TablePageOutput = { }, { rowKey: 'id:"ordinary-target"', + copyRowIndex: 1, documentId: '"ordinary-target"', cells: { [ROOT_ID_COLUMN_KEY]: { display: 'ordinary-target', type: 'string' }, @@ -667,6 +670,7 @@ export const collectionViewFixtures = { results: [noIdPage], cases: [{ input: ['details'], results: [noIdNestedPage] }], }, + 'mongoClusters.collectionView.copyTableCellValue': { type: 'mutation', results: [null] }, }, }, 'first-load': { diff --git a/build/verification/browser/scenarios.ts b/build/verification/browser/scenarios.ts index 8dc97bf81..80e0a93d9 100644 --- a/build/verification/browser/scenarios.ts +++ b/build/verification/browser/scenarios.ts @@ -1056,6 +1056,18 @@ export const collectionViewContracts = { }, ], 'no-id': [ + { + kind: 'calls', + name: 'Full-value shortcut targets the focused object cell without a document ID', + requiresGrid: 'grid', + path: 'mongoClusters.collectionView.copyTableCellValue', + input: { pageId: '4bf66698-74a7-4547-ad4c-607bc11a0f73', rowIndex: 0, columnIndex: 2 }, + count: 1, + steps: [ + { action: 'focus', role: 'gridcell', name: '{...}' }, + { action: 'press', key: 'Alt+Shift+C' }, + ], + }, { kind: 'attribute', name: 'TDD: K1 no-ID rows remain selectable for browsing', diff --git a/docs/ai-and-plans/features/data-grid/README.md b/docs/ai-and-plans/features/data-grid/README.md index d92a5822d..109bb4fbf 100644 --- a/docs/ai-and-plans/features/data-grid/README.md +++ b/docs/ai-and-plans/features/data-grid/README.md @@ -39,8 +39,10 @@ released extension version or completion of the remaining handover gates. - Tree Field content is vertically centered with the other columns and uses Fluent's 2 px label padding after the chevron slot. The whole expandable Field cell is a pointer target; Value/Type cells and leaves do not toggle expansion. -- After keyboard step-in, focus moves to the same root row's `_id` cell after the matching Table +- After keyboard step-in, focus moves to the same row's first column after the matching Table page is applied. Pointer step-in is unchanged. +- Projected Table pages show only fields returned on the page, including the union across + heterogeneous rows. The shared completion schema is not cleared or used as projected headers. - Long Table values ellipsize without hiding the BSON type indicator or adding per-cell Tab stops. Defined values expose their full BSON type before the value in the accessible cell name; the visual glyph is decorative and there is no BSON type hover tooltip. @@ -63,7 +65,8 @@ released extension version or completion of the remaining handover gates. - Embedded Table objects preview their first two fields without expanding nested values; Table arrays retain `array[N]`. Tree containers show direct field/element counts. - Native platform Copy copies the active cell's display text, including a preview, without - type decorations. Read-only cells do not offer substring selection; typed copy is future work. + type decorations. Table **Copy Cell Value** is a separate native command and keyboard shortcut + that copies the full underlying value from the executed page without a document ID or refetch. - The hover opt-out setting or effective reduced motion suppresses Table/Tree hover highlights, retaining focus and selection. A polite Escape hint is frozen once per confirmed grid entry. diff --git a/docs/ai-and-plans/features/data-grid/design.md b/docs/ai-and-plans/features/data-grid/design.md index f96d1558e..32d44f595 100644 --- a/docs/ai-and-plans/features/data-grid/design.md +++ b/docs/ai-and-plans/features/data-grid/design.md @@ -20,8 +20,11 @@ The Table and Tree use the exact-pinned `react-data-grid@7.0.0-beta.64` dependen shapes fetched documents into the grid-neutral types in `src/utils/documentGrid/`; the React components consume `TablePage` and `TreeNode` data rather than raw database documents. -`TablePage` contains the root `_id` column, the fields at the active nested path, and rows in -server order. Each cell has separate display text and BSON type metadata. `toTreeNodes` creates hierarchical nodes from documents; `useTreeRows` sorts siblings by field +`TablePage` contains the fields at the active nested path and rows in server order. A projected +page derives columns from all returned rows and shows the root `_id` only if returned. An +unprojected page keeps the root `_id` column and its collection-schema headers; projection +does not clear the shared completion schema. Each cell has separate display text and BSON type +metadata. `toTreeNodes` creates hierarchical nodes from documents; `useTreeRows` sorts siblings by field name and exposes only roots and descendants whose ancestors are expanded. Its node keys are `JSON.stringify([index, ...segments])`, with a zero-based page index and typed string/number path segments. The keys do not contain or depend on `_id`. The tree is application-owned rather @@ -61,13 +64,13 @@ Plain click selects one row; Ctrl/Cmd-click toggles it; Shift-click extends the toggles the focused row and Shift+Space extends from the selection anchor. Enter on a focused object cell, or double-clicking that cell, steps into that field. For a valid keyboard step-in, the successful response matching the current query, request, and destination path restores focus -once, after the Table page is committed, to column 0—the same row's root `_id` cell—using its +once, after the Table page is committed, to the same row's first column using its `rowKey`, not its previous column or numeric index. It does not select the row. The pending focus restoration is permanently cancelled if focus leaves the initiating results grid, the query or navigation supersedes the request, the load fails, the row disappears, or the view unmounts. A stale intent cannot fire on a later load. Pointer step-in has no new focus -behavior. The handler rejects stale pages, the root `_id` column, `_id` fields, and non-object +behavior. The handler rejects stale pages, the root `_id` column, and non-object values before changing the nested path. Level Up returns one level. The ancestor breadcrumb jumps to that level, and Root Level returns to @@ -101,6 +104,13 @@ already-handled events are excluded. In-grid events still use RDG. The fallback the current Table page or visible Tree rows, not DOM text containing type decorations. Its ARIA index mapping assumes the existing single header row and no summary rows. +Table **Copy Cell Value** uses a native VS Code context menu on populated cells and +Alt+Shift+C (Option+Shift+C on macOS) on the focused cell. Both routes use the same host +clipboard writer. The address contains the rendered page ID, original row index, and column +index. The host resolves the column against the rendered path and the row against that page's +cached documents, without parsing previews or refetching. Replaced pages and deleted rows are +unresolvable. Strings and ObjectIds copy as plain text; structured values use Extended JSON. + In Table and Tree headers, Ctrl/Cmd+Left/Right Arrow resizes the focused column only when no other modifiers are held. Shift, Alt, or holding both Ctrl and Cmd suppresses RDG's resize handler without cancelling the native shortcut or starting a Table width hold. diff --git a/docs/user-manual/collection-view-querying.md b/docs/user-manual/collection-view-querying.md index 0bc7451e9..4d57b4d9d 100644 --- a/docs/user-manual/collection-view-querying.md +++ b/docs/user-manual/collection-view-querying.md @@ -99,6 +99,14 @@ The project editor controls which fields appear in the results. Use `1` to inclu > **Note:** You cannot mix inclusion and exclusion in the same projection, except for the `_id` field which can always be explicitly excluded. +In Table View, the columns show the fields actually returned on the current projected page, including fields missing from some rows. If the projection returns no documents, the Table shows no columns. Clear the projection and run the query again to restore normal column discovery. + +### Copy a Table cell + +Right-click a populated cell and choose **Copy Cell Value**, or focus the cell and press **Alt+Shift+C** (**Option+Shift+C** on macOS). This copies one full value, including all fields of an object or all elements of an array, even when the projection excludes `_id`. Structured values use Extended JSON; strings and ObjectId hex values are copied as plain text. + +Ordinary **Ctrl+C** (**Cmd+C** on macOS) still copies the cell's display text, such as an object preview or array count. Neither action copies the entire document. + ## Writing Sort Expressions The sort editor controls the order of returned documents. Use `1` for ascending and `-1` for descending: diff --git a/package.json b/package.json index 2225f3883..fc88c1a6b 100644 --- a/package.json +++ b/package.json @@ -777,6 +777,10 @@ "command": "vscode-documentdb.command.clusterDashboard.context.manageIndexes", "title": "Manage Indexes" }, + { + "command": "vscode-documentdb.command.collectionView.context.copyCellValue", + "title": "%collectionView.copyCellValue%" + }, { "command": "vscode-documentdb.command.clusterDashboard.context.copyReference", "title": "Copy Reference" @@ -973,6 +977,11 @@ "editor/context": [], "editor/title": [], "webview/context": [ + { + "command": "vscode-documentdb.command.collectionView.context.copyCellValue", + "when": "webviewId == 'vscode-documentdb-collection-view' && collectionViewTableCell", + "group": "1_copy" + }, { "command": "vscode-documentdb.command.clusterDashboard.context.viewCollections", "when": "webviewId == 'vscode-documentdb-cluster-dashboard' && clusterDashboardNamespace == database", @@ -1579,6 +1588,10 @@ ], "explorer/context": [], "commandPalette": [ + { + "command": "vscode-documentdb.command.collectionView.context.copyCellValue", + "when": "never" + }, { "command": "vscode-documentdb.debug.survey.showInvitation", "when": "documentdb-development-mode" diff --git a/package.nls.json b/package.nls.json index 88f95c3c7..e6b8a02eb 100644 --- a/package.nls.json +++ b/package.nls.json @@ -1,4 +1,5 @@ { + "collectionView.copyCellValue": "Copy Cell Value", "survey.containerTitle": "DocumentDB Feedback", "survey.viewTitle": "Share Your Experience", "survey.giveFeedbackTitle": "Give Feedback", diff --git a/src/documentdb/ClusterSession.test.ts b/src/documentdb/ClusterSession.test.ts index ac5c1c3b4..1fe28e77a 100644 --- a/src/documentdb/ClusterSession.test.ts +++ b/src/documentdb/ClusterSession.test.ts @@ -3,13 +3,22 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { BSONRegExp, Long } from 'bson'; +import { type Document } from 'mongodb'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; import { fieldColumnKey, getCell } from '../utils/documentGrid/types'; +import { registerTableCellClipboardCommand } from '../webviews/documentdb/collectionView/tableCellClipboard'; import { ClusterSession } from './ClusterSession'; -const runFindQuery = vi.hoisted(() => vi.fn()); +const { runFindQuery, writeText } = vi.hoisted(() => ({ runFindQuery: vi.fn(), writeText: vi.fn() })); +vi.mock('vscode', async (importOriginal) => { + const original = await importOriginal(); + return { ...original, env: { ...original.env, clipboard: { writeText } } }; +}); + vi.mock('./ClustersClient', () => ({ - ClustersClient: { getClient: () => Promise.resolve({ runFindQuery }) }, + ClustersClient: { getClient: () => Promise.resolve({ runFindQuery, deleteDocuments: () => Promise.resolve(true) }) }, })); vi.mock('../extensionVariables', () => ({ ext: { outputChannel: { trace: vi.fn() } } })); @@ -23,7 +32,11 @@ describe('ClusterSession Table pages', () => { session = ClusterSession.getSession(sessionId); }); - afterEach(() => ClusterSession.closeSession(sessionId)); + afterEach(() => { + ClusterSession.closeSession(sessionId); + vi.restoreAllMocks(); + writeText.mockClear(); + }); it('uses only executed projection fields without clearing the shared schema', async () => { runFindQuery @@ -50,4 +63,88 @@ describe('ClusterSession Table pages', () => { await session.runFindQueryWithCache('db', 'projection', { project: '{ }' }, 1, 50); expect(headers()).toEqual(expect.arrayContaining(['_id', 'title', 'rating', 'secret'])); }); + + it('resolves full values from the same projected page, including its nested path', async () => { + const longText = 'a'.repeat(500); + runFindQuery.mockResolvedValueOnce([ + { nested: { 'field.with.dots': { first: longText, second: false, third: new BSONRegExp('a.b', 's') } } }, + { nested: { 'field.with.dots': [longText, Long.fromString('9007199254740993')], extra: null } }, + ]); + await session.runFindQueryWithCache('db', 'copy', { project: '{ nested: 1, _id: 0 }' }, 1, 50); + const root = session.getCurrentPageAsTable([]); + const nested = session.getCurrentPageAsTable(['nested']); + const address = { pageId: nested.copyPageId, rowIndex: 0, columnIndex: 0 }; + expect(nested.rows[0].documentId).toBeUndefined(); + expect(session.getTableCellCopyText(address)).toBe( + JSON.stringify({ + first: longText, + second: false, + third: { $regularExpression: { pattern: 'a.b', options: 's' } }, + }), + ); + expect(session.getTableCellCopyText({ ...address, rowIndex: 1 })).toBe( + JSON.stringify([longText, { $numberLong: '9007199254740993' }]), + ); + expect(session.getTableCellCopyText({ ...address, columnIndex: 1 })).toBeUndefined(); + expect(session.getTableCellCopyText({ ...address, rowIndex: 1, columnIndex: 1 })).toBe('null'); + expect(session.getTableCellCopyText({ ...address, pageId: root.copyPageId })).toBeUndefined(); + expect(runFindQuery).toHaveBeenCalledTimes(1); + + runFindQuery.mockResolvedValueOnce([{ nested: { 'field.with.dots': 'replacement' } }]); + await session.runFindQueryWithCache('db', 'copy', { project: '{ nested: 1, _id: 0 }' }, 2, 50); + const replacement = session.getCurrentPageAsTable(['nested']); + expect(session.getTableCellCopyText(address)).toBeUndefined(); + expect(session.getTableCellCopyText({ ...address, pageId: replacement.copyPageId })).toBe('replacement'); + }); + + it('writes only the clicked cell through the native command and rejects a stale or invalid context', async () => { + runFindQuery.mockResolvedValue([{ item: ['a', 'b'] }]); + await session.runFindQueryWithCache('db', 'copy', { project: '{ item: 1, _id: 0 }' }, 1, 50); + const page = session.getCurrentPageAsTable([]); + const registerCommand = vi.spyOn(vscode.commands, 'registerCommand'); + registerTableCellClipboardCommand({ subscriptions: [] } as unknown as vscode.ExtensionContext); + const [command, run] = registerCommand.mock.calls[0]; + expect(command).toBe('vscode-documentdb.command.collectionView.context.copyCellValue'); + const context = { + preventDefaultContextMenuItems: true, + collectionViewTableCell: true, + collectionViewSessionId: sessionId, + pageId: page.copyPageId, + rowIndex: 0, + columnIndex: 0, + }; + await run({ ...context, rowIndex: -1 }); + await run({ ...context, collectionViewTableCell: false }); + expect(writeText).not.toHaveBeenCalled(); + await run(context); + expect(writeText).toHaveBeenCalledExactlyOnceWith('["a","b"]'); + await session.runFindQueryWithCache('db', 'copy', { project: '{ item: 1, _id: 0 }' }, 2, 50); + await run(context); + expect(writeText).toHaveBeenCalledTimes(1); + }); + + it('keeps surviving cell addresses stable after deleting an earlier row', async () => { + runFindQuery.mockResolvedValue([{ _id: 'first', name: 'first' }, { _id: 'second', name: 'second' }]); + await session.runFindQueryWithCache('db', 'delete', {}, 1, 50); + const page = session.getCurrentPageAsTable([]); + const address = { pageId: page.copyPageId, columnIndex: 1 }; + expect(page.rows.map((row) => row.copyRowIndex)).toEqual([0, 1]); + await session.deleteDocuments('db', 'delete', ['"first"']); + expect(session.getTableCellCopyText({ ...address, rowIndex: 0 })).toBeUndefined(); + expect(session.getTableCellCopyText({ ...address, rowIndex: 1 })).toBe('second'); + }); + + it('keeps a newer page copyable when an older query finishes late', async () => { + let resolveOlder!: (documents: Document[]) => void; + const older = new Promise((resolve) => { + resolveOlder = resolve; + }); + runFindQuery.mockReturnValueOnce(older).mockResolvedValueOnce([{ item: 'current' }]); + const oldRun = session.runFindQueryWithCache('db', 'copy', {}, 1, 50); + await session.runFindQueryWithCache('db', 'copy', { project: '{ item: 1, _id: 0 }' }, 1, 50); + const page = session.getCurrentPageAsTable([]); + resolveOlder([{ _id: 1, item: 'old' }]); + await oldRun; + expect(session.getTableCellCopyText({ pageId: page.copyPageId, rowIndex: 0, columnIndex: 0 })).toBe('current'); + }); }); diff --git a/src/documentdb/ClusterSession.ts b/src/documentdb/ClusterSession.ts index 9c5959000..f0a122a55 100644 --- a/src/documentdb/ClusterSession.ts +++ b/src/documentdb/ClusterSession.ts @@ -6,13 +6,20 @@ import { type FieldEntry } from '@documentdb-js/schema-analyzer'; import { ParseMode, parse as parseShellBSON } from '@mongodb-js/shell-bson-parser'; import * as l10n from '@vscode/l10n'; -import { EJSON } from 'bson'; +import { EJSON, ObjectId } from 'bson'; import { type Document, type Filter, type WithId } from 'mongodb'; +import { randomUUID } from 'node:crypto'; import { ext } from '../extensionVariables'; import { isIdentityTrustedForProjection } from '../utils/documentGrid/documentIdentity'; -import { toTablePage } from '../utils/documentGrid/toTablePage'; +import { getOwnValueAtPath, toTablePage } from '../utils/documentGrid/toTablePage'; import { toTreeNodes } from '../utils/documentGrid/toTreeNodes'; -import { type TablePage, type TreeNode } from '../utils/documentGrid/types'; +import { + fieldFromColumnKey, + getCell, + type TableCellAddress, + type TablePage, + type TreeNode, +} from '../utils/documentGrid/types'; import { type QueryInsightsStage2Response } from '../webviews/documentdb/collectionView/types/queryInsights'; import { ClustersClient, type FindQueryParams } from './ClustersClient'; import { SchemaStore } from './SchemaStore'; @@ -93,6 +100,8 @@ export class ClusterSession { private _currentRawDocuments: WithId[] = []; private _currentPageIdentityTrusted = false; private _currentPageProjected = false; + private _queryGeneration = 0; + private _currentTablePage: { page: TablePage; documents: (Document | undefined)[] } | undefined; /** * Query Insights caching @@ -232,6 +241,8 @@ export class ClusterSession { pageSize: number, executionIntent: 'initial' | 'refresh' | 'pagination' = 'pagination', ): Promise { + const generation = ++this._queryGeneration; + this._currentTablePage = undefined; let projected = false; let identityTrusted = true; if (queryParams.project && queryParams.project.trim() !== '{}') { @@ -303,9 +314,13 @@ export class ClusterSession { collectionName, paginatedQueryParams, ); + if (generation !== this._queryGeneration) { + return documents.length; + } this._lastExecutionTimeMs = performance.now() - startTime; // Update current page documents (always replace, not accumulate) + this._currentTablePage = undefined; this._currentRawDocuments = documents; this._currentPageIdentityTrusted = identityTrusted; this._currentPageProjected = projected; @@ -339,8 +354,9 @@ export class ClusterSession { const acknowledged = await this._client.deleteDocuments(databaseName, collectionName, documentIds); if (acknowledged) { + const removed = new Set(); this._currentRawDocuments = this._currentRawDocuments.filter((doc) => { - return !documentIds.some((id) => { + const deleted = documentIds.some((id) => { const parsedId = parseDocumentId(id); const docIdStr = EJSON.stringify(doc._id, { relaxed: false }, 0); @@ -348,13 +364,22 @@ export class ClusterSession { return docIdStr === parsedIdStr; }); + if (deleted) { + removed.add(doc); + } + return !deleted; }); + const table = this._currentTablePage; + if (table) { + // The webview also removes rows locally. Keep the remaining original copy indexes stable. + table.documents = table.documents.map((doc) => (doc && removed.has(doc) ? undefined : doc)); + } } return acknowledged; } - public getCurrentPageAsTable(path: string[]): TablePage { + public getCurrentPageAsTable(path: string[]): TablePage & { readonly copyPageId: string } { let headers: readonly string[] | undefined; if (!this._currentPageProjected) { headers = @@ -367,7 +392,37 @@ export class ClusterSession { ) : []; } - return toTablePage(this._currentRawDocuments, path, headers, this._currentPageIdentityTrusted); + const page = { + ...toTablePage(this._currentRawDocuments, path, headers, this._currentPageIdentityTrusted), + copyPageId: randomUUID(), + }; + this._currentTablePage = { page, documents: [...this._currentRawDocuments] }; + return page; + } + + public getTableCellCopyText({ pageId, rowIndex, columnIndex }: TableCellAddress): string | undefined { + const table = this._currentTablePage; + if (!table || table.page.copyPageId !== pageId) { + return undefined; + } + const { page, documents } = table; + const column = page.columns[columnIndex]; + const row = page.rows[rowIndex]; + const document = documents[rowIndex]; + if (!column || !row || !document || !getCell(row, column.key)) { + return undefined; + } + + const field = fieldFromColumnKey(column.key); + const path = field === undefined ? ['_id'] : [...page.path, field]; + const value = getOwnValueAtPath(document, path); + if (value instanceof ObjectId) { + return value.toHexString(); + } + if (value === null || typeof value !== 'object') { + return Object.is(value, -0) ? '-0' : String(value); + } + return EJSON.stringify(value, { relaxed: false }); } /** diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index e95dc632a..4de07d1ec 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -957,6 +957,8 @@ export class ClustersClient { const options: FindOptions = { skip: queryParams.skip ?? 0, limit: queryParams.limit ?? 0, + // Preserve BSON regex options for full-value copy instead of decoding them as JS flags. + bsonRegExp: true, }; // Parse and add projection if provided diff --git a/src/documentdb/ClustersExtension.ts b/src/documentdb/ClustersExtension.ts index adde5809d..26cbf0c44 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -142,6 +142,7 @@ import { } from '../utils/commandErrorHandling'; import { withCommandCorrelation, withTreeNodeCommandCorrelation } from '../utils/commandTelemetry'; import { registerClusterDashboardContextMenuCommands } from '../webviews/documentdb/clusterDashboard/clusterDashboardController'; +import { registerTableCellClipboardCommand } from '../webviews/documentdb/collectionView/tableCellClipboard'; import { EntraErrorExplainer } from './auth/entraErrors/EntraErrorExplainer'; import { PLAYGROUND_FILE_EXTENSION, PLAYGROUND_LANGUAGE_ID, PlaygroundCommandIds } from './playground/constants'; import { PlaygroundBlockHighlighter } from './playground/PlaygroundBlockHighlighter'; @@ -288,6 +289,7 @@ export class ClustersExtension implements vscode.Disposable { this.registerDiscoveryTree(activateContext); this.registerHelpAndFeedbackTree(activateContext); registerClusterDashboardContextMenuCommands(ext.context); + registerTableCellClipboardCommand(ext.context); // Initialize TaskService and TaskProgressReportingService TaskProgressReportingService.attach(TaskService); diff --git a/src/utils/documentGrid/toTablePage.ts b/src/utils/documentGrid/toTablePage.ts index 9cf5f5f4b..4f8f7fcce 100644 --- a/src/utils/documentGrid/toTablePage.ts +++ b/src/utils/documentGrid/toTablePage.ts @@ -91,6 +91,16 @@ export function toGridCellValue(value: unknown): GridCellValue { } } +export function getOwnValueAtPath(value: unknown, path: readonly string[]): unknown { + for (const field of path) { + if (value === null || typeof value !== 'object' || !Object.hasOwn(value, field)) { + return undefined; + } + value = (value as Record)[field]; + } + return value; +} + export function toTablePage( documents: readonly Document[], path: readonly string[], @@ -108,20 +118,7 @@ export function toTablePage( cells[ROOT_ID_COLUMN_KEY] = toGridCellValue(document._id); } - let subdocument: unknown = document; - for (const field of path) { - if ( - subdocument !== null && - typeof subdocument === 'object' && - Object.prototype.hasOwnProperty.call(subdocument, field) - ) { - subdocument = (subdocument as Document)[field] as unknown; - } else { - subdocument = undefined; - break; - } - } - + const subdocument = getOwnValueAtPath(document, path); if ( subdocument !== null && typeof subdocument === 'object' && @@ -136,7 +133,7 @@ export function toTablePage( } } } - return { ...identities[index], cells }; + return { ...identities[index], copyRowIndex: index, cells }; }); const fields = schemaHeaders?.filter((field) => field !== '_id') ?? [...projectedFields]; return { diff --git a/src/utils/documentGrid/types.ts b/src/utils/documentGrid/types.ts index cac6f18db..80d0cff96 100644 --- a/src/utils/documentGrid/types.ts +++ b/src/utils/documentGrid/types.ts @@ -33,16 +33,26 @@ export interface TableRow { readonly rowKey: string; /** Canonical EJSON of the root _id. Absent means browsable but not actionable. */ readonly documentId?: string; + /** Original result index, unchanged if another row is deleted locally. */ + readonly copyRowIndex?: number; /** Missing key means missing field. BSON null is { display: 'null', type: 'null' }. */ readonly cells: Readonly>>; } export interface TablePage { readonly path: readonly string[]; - /** Root ID column first, then field columns at path. */ + /** Root ID column first when shown, then field columns at path. */ readonly columns: readonly TableColumn[]; /** Server order. */ readonly rows: readonly TableRow[]; + /** Opaque handle for resolving a cell against this rendered page on the host. */ + readonly copyPageId?: string; +} + +export interface TableCellAddress { + readonly pageId: string; + readonly rowIndex: number; + readonly columnIndex: number; } export interface TreeNode { diff --git a/src/webviews/components/useSelectiveContextMenuPrevention.ts b/src/webviews/components/useSelectiveContextMenuPrevention.ts index 7b72bca7b..0bce231b3 100644 --- a/src/webviews/components/useSelectiveContextMenuPrevention.ts +++ b/src/webviews/components/useSelectiveContextMenuPrevention.ts @@ -7,7 +7,7 @@ import { useEffect } from 'react'; /** * Custom hook that selectively prevents context menus based on element selectors. - * Currently allows context menus in Monaco editor elements while preventing them elsewhere. + * Allows context menus in Monaco and an optional caller-provided native menu target. * This preserves editor functionality (copy/paste/formatting) while preventing unwanted * context menus in data tables and other UI elements. * @@ -26,15 +26,16 @@ const ALLOWED_SELECTORS = [ // Add other editor selectors here as needed ]; -export const useSelectiveContextMenuPrevention = (): void => { +export const useSelectiveContextMenuPrevention = (nativeMenuSelector?: string): void => { useEffect(() => { - const allowedSelectors = ALLOWED_SELECTORS; + const allowedSelectors = nativeMenuSelector ? [...ALLOWED_SELECTORS, nativeMenuSelector] : ALLOWED_SELECTORS; const handleContextMenu = (e: MouseEvent): void => { - const target = e.target as HTMLElement; + const target = e.target; // Check if target is within any allowed element - const isInAllowedElement = allowedSelectors.some((selector) => target.closest(selector) !== null); + const isInAllowedElement = + target instanceof Element && allowedSelectors.some((selector) => target.closest(selector) !== null); if (!isInAllowedElement) { e.preventDefault(); @@ -46,5 +47,5 @@ export const useSelectiveContextMenuPrevention = (): void => { return () => { document.removeEventListener('contextmenu', handleContextMenu); }; - }, []); + }, [nativeMenuSelector]); }; diff --git a/src/webviews/documentdb/collectionView/CollectionView.tsx b/src/webviews/documentdb/collectionView/CollectionView.tsx index e406a6fcb..8088c0e57 100644 --- a/src/webviews/documentdb/collectionView/CollectionView.tsx +++ b/src/webviews/documentdb/collectionView/CollectionView.tsx @@ -21,6 +21,7 @@ import { type ColumnKey, fieldFromColumnKey, getCell, + type TableCellAddress, type TablePage, type TreeNode, } from '../../../utils/documentGrid/types'; @@ -62,6 +63,7 @@ import { extractErrorCode } from './utils/errorCodeExtractor'; interface QueryResults { tablePage?: TablePage; + tablePageQuery?: CollectionViewContextType['activeQuery']; /** The executed query and path that `tablePage` was loaded for; column widths are remembered per scope. */ tableWidthScope?: ColumnWidthScope; treeNodes?: TreeNode[]; @@ -150,7 +152,7 @@ export const CollectionView = (): JSX.Element => { resetColumnWidthCache(columnWidthCacheRef.current, activeColumnWidthQueryKey); }, [activeColumnWidthQueryKey]); - useSelectiveContextMenuPrevention(); + useSelectiveContextMenuPrevention('.dataViewPanelTable [role="gridcell"][data-vscode-context]'); // Apply initial query from cross-feature navigation (e.g., Playground → Collection View) useEffect(() => { @@ -460,11 +462,13 @@ export const CollectionView = (): JSX.Element => { currentQueryResultsRef.current = { ...currentQueryResultsRef.current, tablePage: result, + tablePageQuery: requestQuery, tableWidthScope, }; setCurrentQueryResults((prev) => ({ ...prev, tablePage: result, + tablePageQuery: requestQuery, tableWidthScope, })); if (completesFocusRequest && claimedFocusIntent !== undefined) { @@ -777,6 +781,24 @@ export const CollectionView = (): JSX.Element => { }); } + async function handleCopyCellValue(address: TableCellAddress): Promise { + if ( + !isCurrentTablePage(currentContextRef.current) || + currentQueryResultsRef.current?.tablePage?.copyPageId !== address.pageId + ) { + return; + } + try { + await trpcClient.mongoClusters.collectionView.copyTableCellValue.mutate(address); + } catch { + void trpcClient.common.displayErrorMessage.mutate({ + message: l10n.t('An unexpected error occurred'), + modal: false, + cause: '', + }); + } + } + function handleStepInRequest(rowKey: string, columnKey: ColumnKey, gesture: 'keyboard' | 'pointer'): void { const page = currentQueryResultsRef.current?.tablePage; const context = currentContextRef.current; @@ -788,8 +810,6 @@ export const CollectionView = (): JSX.Element => { !row || !isCurrentTablePage(context) || field === undefined || - // O1 keeps nested _id fields hidden; only the root ID column is shown. - field === '_id' || getCell(row, columnKey)?.type !== 'object' ) { return; @@ -1144,6 +1164,18 @@ export const CollectionView = (): JSX.Element => { columnWidthCache={columnWidthCacheRef.current} widthScope={currentQueryResults?.tableWidthScope} focusRequest={tableFocusRequest} + copyCell={ + !currentContext.isLoading && + currentQueryResults?.tablePageQuery === currentContext.activeQuery && + currentQueryResults.tableWidthScope?.pathKey === + JSON.stringify(currentContext.currentViewState?.currentPath ?? []) + ? { + sessionId: configuration.sessionId, + copyValue: (address): void => + void handleCopyCellValue(address), + } + : undefined + } /> ), 'Tree View': , diff --git a/src/webviews/documentdb/collectionView/collectionViewRouter.ts b/src/webviews/documentdb/collectionView/collectionViewRouter.ts index 965b0e4dc..81d8db992 100644 --- a/src/webviews/documentdb/collectionView/collectionViewRouter.ts +++ b/src/webviews/documentdb/collectionView/collectionViewRouter.ts @@ -19,6 +19,7 @@ import { type QueryGenerationContext, } from '../../../commands/llmEnhancedCommands/queryGenerationCommands'; import { showConfirmationAsInSettings } from '../../../utils/dialogs/showConfirmation'; +import { type TablePage } from '../../../utils/documentGrid/types'; import { parseFindExpression } from '../../../documentdb/playground/parseFindExpression'; import { Views } from '../../../documentdb/Views'; @@ -37,6 +38,7 @@ import { toFieldCompletionItems } from '../../../utils/json/data-api/autocomplet import { readOnlyJsonDocumentProvider } from '../../../utils/readOnlyJsonDocumentProvider'; import { type BaseRouterContext } from '../../_integration/appRouter'; import { queryInsightsRouter } from './queryInsights/queryInsightsRouter'; +import { copyTableCellValue, tableCellAddressSchema } from './tableCellClipboard'; export type RouterContext = BaseRouterContext & { sessionId: string; @@ -281,7 +283,7 @@ export const collectionsViewRouter = router({ // parameters .input(z.array(z.string())) // procedure type - .query(({ input, ctx }) => { + .query(({ input, ctx }): TablePage => { const myCtx = ctx as RouterContext; const session: ClusterSession = ClusterSession.getSession(myCtx.sessionId); @@ -289,6 +291,9 @@ export const collectionsViewRouter = router({ return tablePage; }), + copyTableCellValue: publicProcedureWithTelemetry.input(tableCellAddressSchema).mutation(async ({ input, ctx }) => { + await copyTableCellValue((ctx as RouterContext).sessionId, input); + }), getCurrentPageAsTree: publicProcedureWithTelemetry // procedure type .query(({ ctx }) => { diff --git a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.tsx b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.tsx index b103cba27..bebda8ffc 100644 --- a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.tsx +++ b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.tsx @@ -8,7 +8,13 @@ import * as React from 'react'; import { Cell, DataGrid, Row, type Column, type DataGridHandle, type DefaultColumnOptions } from 'react-data-grid'; // eslint-disable-next-line import/no-internal-modules -- beta.64 explicitly exports this public stylesheet subpath. import 'react-data-grid/lib/styles.css'; -import { getCell, type ColumnKey, type TablePage, type TableRow } from '../../../../../utils/documentGrid/types'; +import { + getCell, + type ColumnKey, + type TableCellAddress, + type TablePage, + type TableRow, +} from '../../../../../utils/documentGrid/types'; import { CollectionViewContext } from '../../collectionViewContext'; import './dataGridTheme.scss'; import './dataViewPanelTable.scss'; @@ -27,6 +33,10 @@ interface DataViewPanelTableProps { /** Decided when the page was accepted; without it, widths are neither restored nor remembered. */ readonly widthScope?: ColumnWidthScope; readonly focusRequest?: DataViewPanelTableFocusRequest; + readonly copyCell?: { + readonly sessionId: string; + readonly copyValue: (address: TableCellAddress) => void; + }; } export interface DataViewPanelTableFocusRequest { @@ -50,6 +60,7 @@ export function DataViewPanelTable({ columnWidthCache, widthScope, focusRequest, + copyCell, }: DataViewPanelTableProps): React.JSX.Element { const [currentContext] = React.useContext(CollectionViewContext); const gridRef = React.useRef(null); @@ -77,7 +88,8 @@ export function DataViewPanelTable({ if ( focusRequest === undefined || handledFocusRequestRef.current === focusRequest || - focusRequest.page !== page + focusRequest.page !== page || + page.columns.length === 0 ) { return; } @@ -231,19 +243,63 @@ export function DataViewPanelTable({ event.clipboardData.setData('text/plain', tableCellText(row, columnKey)); }} renderers={{ - renderCell: (key, props): React.JSX.Element => ( - { - props.onFocusCapture?.(event); - if (!event.defaultPrevented && event.target === event.currentTarget) { - // Native Tab exit uses the remembered position, not the focused DOM cell. - props.setActivePosition({ rowIdx: props.rowIdx, idx: props.column.idx }); + renderCell: (key, props): React.JSX.Element => { + const columnKey = page?.columns[props.column.idx]?.key; + const rowIndex = props.row.copyRowIndex; + const address: TableCellAddress | undefined = + copyCell && + page?.copyPageId && + rowIndex !== undefined && + columnKey !== undefined && + getCell(props.row, columnKey) + ? { pageId: page.copyPageId, rowIndex, columnIndex: props.column.idx } + : undefined; + return ( + - ), + aria-keyshortcuts={address ? 'Alt+Shift+C' : undefined} + onKeyDown={(event): void => { + props.onKeyDown?.(event); + if ( + !copyCell || + !address || + event.defaultPrevented || + event.target !== event.currentTarget || + !event.altKey || + !event.shiftKey || + event.ctrlKey || + event.metaKey || + (event.code !== 'KeyC' && event.key.toLowerCase() !== 'c') + ) { + return; + } + event.preventDefault(); + event.stopPropagation(); + if (!event.repeat) { + copyCell.copyValue(address); + } + }} + onFocusCapture={(event): void => { + props.onFocusCapture?.(event); + if (!event.defaultPrevented && event.target === event.currentTarget) { + // Native Tab exit uses the remembered position, not the focused DOM cell. + props.setActivePosition({ rowIdx: props.rowIdx, idx: props.column.idx }); + } + }} + /> + ); + }, renderRow: (key, props): React.JSX.Element => ( handleRowKeyDown(props.row, event)} /> ), diff --git a/src/webviews/documentdb/collectionView/tableCellClipboard.ts b/src/webviews/documentdb/collectionView/tableCellClipboard.ts new file mode 100644 index 000000000..4bd1f0950 --- /dev/null +++ b/src/webviews/documentdb/collectionView/tableCellClipboard.ts @@ -0,0 +1,46 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as vscode from 'vscode'; +import { z } from 'zod'; +import { ClusterSession } from '../../../documentdb/ClusterSession'; +import { type TableCellAddress } from '../../../utils/documentGrid/types'; + +export const tableCellAddressSchema = z.object({ + pageId: z.string().uuid(), + rowIndex: z.number().int().nonnegative(), + columnIndex: z.number().int().nonnegative(), +}); + +const menuContextSchema = tableCellAddressSchema.extend({ + collectionViewTableCell: z.literal(true), + collectionViewSessionId: z.string(), +}); + +export async function copyTableCellValue(sessionId: string, address: TableCellAddress): Promise { + try { + const text = ClusterSession._sessions.get(sessionId)?.getTableCellCopyText(address); + if (text !== undefined) { + await vscode.env.clipboard.writeText(text); + } + } catch { + // A serialization or clipboard error must not expose document contents. + void vscode.window.showErrorMessage(vscode.l10n.t('An unexpected error occurred')); + } +} + +export function registerTableCellClipboardCommand(context: vscode.ExtensionContext): void { + context.subscriptions.push( + vscode.commands.registerCommand( + 'vscode-documentdb.command.collectionView.context.copyCellValue', + async (menuContext: unknown): Promise => { + const parsed = menuContextSchema.safeParse(menuContext); + if (parsed.success) { + await copyTableCellValue(parsed.data.collectionViewSessionId, parsed.data); + } + }, + ), + ); +} From 70ddfc42ba136063212c93ea9c9bb9c6fe2da31c Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 3 Dec 2026 19:22:39 +0100 Subject: [PATCH 4/7] Keep selected projection columns visible in Table View Merge projection header hints with returned fields without adding synthetic rows or affecting the shared schema. Document the table shaper parameters and cover missing and empty results. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../ai-and-plans/features/data-grid/README.md | 6 +- .../features/data-grid/decisions.md | 27 +++++ .../ai-and-plans/features/data-grid/design.md | 14 ++- docs/user-manual/collection-view-querying.md | 2 +- src/documentdb/ClusterSession.test.ts | 113 +++++++++++++++++- src/documentdb/ClusterSession.ts | 85 +++++++++++-- src/utils/documentGrid/toTablePage.test.ts | 33 +++++ src/utils/documentGrid/toTablePage.ts | 46 ++++++- .../collectionView/CollectionView.tsx | 1 + .../collectionView/tableCellClipboard.ts | 2 + 10 files changed, 307 insertions(+), 22 deletions(-) diff --git a/docs/ai-and-plans/features/data-grid/README.md b/docs/ai-and-plans/features/data-grid/README.md index 109bb4fbf..95c062ba0 100644 --- a/docs/ai-and-plans/features/data-grid/README.md +++ b/docs/ai-and-plans/features/data-grid/README.md @@ -41,8 +41,10 @@ released extension version or completion of the remaining handover gates. Value/Type cells and leaves do not toggle expansion. - After keyboard step-in, focus moves to the same row's first column after the matching Table page is applied. Pointer step-in is unchanged. -- Projected Table pages show only fields returned on the page, including the union across - heterogeneous rows. The shared completion schema is not cleared or used as projected headers. +- Projected Table pages merge executed-projection header hints with the union of fields returned + across rows. Selected headers remain even when every row lacks the field or the page is empty; + hints never create values or hide returned fields. The shared completion schema is not cleared, + seeded by hints or used as projected headers. See [decision 0009](./decisions.md#0009---additive-projection-header-hints). - Long Table values ellipsize without hiding the BSON type indicator or adding per-cell Tab stops. Defined values expose their full BSON type before the value in the accessible cell name; the visual glyph is decorative and there is no BSON type hover tooltip. diff --git a/docs/ai-and-plans/features/data-grid/decisions.md b/docs/ai-and-plans/features/data-grid/decisions.md index c7a4087ec..00231a6dc 100644 --- a/docs/ai-and-plans/features/data-grid/decisions.md +++ b/docs/ai-and-plans/features/data-grid/decisions.md @@ -20,6 +20,7 @@ implementation remains subject to the planned work items and later gates. | 0006 | UX review: sizing gate, previews, copy and hover | Accepted | Sizing accepted; native platform Copy clarified | 2026-11-30 | #1142 | | 0007 | Column-width hold release and width scope | Accepted | Remount by scope rejected; frozen widths deferred | 2026-12-01 | #1142 | | 0008 | Position-based Tree node keys | Accepted | Replaces document-identity-based Tree keys | 2026-12-01 | #1142 | +| 0009 | Additive projection header hints | Accepted | Selected headers remain on empty projected pages | 2026-12-03 | #1171 | ## 0001 - React Data Grid, beta candidate and document tree @@ -325,3 +326,29 @@ field/path order, preorder, and the array expansion bound remain unchanged. This approval is recorded as WI-R1/C4 option A in the [Copilot PR review triage table](./iterations/08-copilot-pr-review-triage.md#operator-decisions-2026-12-01). + +## 0009 - Additive projection header hints + +**Status:** Accepted · **Date:** 2026-12-03 · **PR:** #1171 + +### Decision + +Merge header hints from the executed projection with columns discovered from the current page. +Hints retain selected columns even when every returned document lacks the field or the result +is empty. They never hide fields returned by the data or manufacture rows, cell values, +document identities or shared completion-schema knowledge. + +Root `_id` remains first when returned or hinted. Other hinted columns follow projection order, +then additional returned columns follow discovery order. Positive selections and computed +outputs contribute hints at the active nested path; exclusions do not. Inclusion projections +retain their implicit root `_id` unless explicitly excluded. + +### Rationale and alternatives + +The operator approved additive hints because "it's just a hint and fields in data will still +show up." This replaces the draft's result-only discovery and its no-columns-on-empty-result +behavior, while retaining real data as the source of cell values. + +A dummy document was considered and rejected in favor of explicit column metadata: hints do +not need synthetic result rows and cannot contaminate row identity, copy addresses or schema +inference. diff --git a/docs/ai-and-plans/features/data-grid/design.md b/docs/ai-and-plans/features/data-grid/design.md index 32d44f595..1ee7e9523 100644 --- a/docs/ai-and-plans/features/data-grid/design.md +++ b/docs/ai-and-plans/features/data-grid/design.md @@ -21,9 +21,17 @@ shapes fetched documents into the grid-neutral types in `src/utils/documentGrid/ components consume `TablePage` and `TreeNode` data rather than raw database documents. `TablePage` contains the fields at the active nested path and rows in server order. A projected -page derives columns from all returned rows and shows the root `_id` only if returned. An -unprojected page keeps the root `_id` column and its collection-schema headers; projection -does not clear the shared completion schema. Each cell has separate display text and BSON type +page merges header hints from the executed projection with columns discovered in all returned +rows. Root `_id` stays first, followed by hinted columns in projection order and additional +returned fields in discovery order, deduplicated by column key. Positive selections, computed +outputs and the implicit `_id` of an inclusion projection supply hints; exclusions do not. +Dotted and nested selections supply hints at the active path without interpreting expression +arguments as output paths. Selected headers remain on empty pages, but hints never create rows, +cell values or document identities. Root and nested `_id` columns retain distinct keys. +An unprojected page keeps the root `_id` column and its collection-schema headers; projection +does not clear the shared completion schema, and hints never seed it. +See [decision 0009](./decisions.md#0009---additive-projection-header-hints). +Each cell has separate display text and BSON type metadata. `toTreeNodes` creates hierarchical nodes from documents; `useTreeRows` sorts siblings by field name and exposes only roots and descendants whose ancestors are expanded. Its node keys are `JSON.stringify([index, ...segments])`, with a zero-based page index and typed string/number diff --git a/docs/user-manual/collection-view-querying.md b/docs/user-manual/collection-view-querying.md index 4d57b4d9d..e4efd2dd5 100644 --- a/docs/user-manual/collection-view-querying.md +++ b/docs/user-manual/collection-view-querying.md @@ -99,7 +99,7 @@ The project editor controls which fields appear in the results. Use `1` to inclu > **Note:** You cannot mix inclusion and exclusion in the same projection, except for the `_id` field which can always be explicitly excluded. -In Table View, the columns show the fields actually returned on the current projected page, including fields missing from some rows. If the projection returns no documents, the Table shows no columns. Clear the projection and run the query again to restore normal column discovery. +In Table View, selected projection fields remain as columns even when no returned document contains them or the query returns no documents. Missing values are shown as unset, not as `null`. Fields actually returned on the current page also appear, including fields missing from some rows. Root `_id` stays first when returned or included by the projection. Exclusion-only projections discover columns from returned documents. Clear the projection and run the query again to restore normal column discovery. ### Copy a Table cell diff --git a/src/documentdb/ClusterSession.test.ts b/src/documentdb/ClusterSession.test.ts index 1fe28e77a..5db1f435e 100644 --- a/src/documentdb/ClusterSession.test.ts +++ b/src/documentdb/ClusterSession.test.ts @@ -7,7 +7,7 @@ import { BSONRegExp, Long } from 'bson'; import { type Document } from 'mongodb'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; -import { fieldColumnKey, getCell } from '../utils/documentGrid/types'; +import { fieldColumnKey, getCell, ROOT_ID_COLUMN_KEY } from '../utils/documentGrid/types'; import { registerTableCellClipboardCommand } from '../webviews/documentdb/collectionView/tableCellClipboard'; import { ClusterSession } from './ClusterSession'; @@ -58,12 +58,121 @@ describe('ClusterSession Table pages', () => { expect(session.getKnownFields()).toEqual(expect.arrayContaining([expect.objectContaining({ path: 'secret' })])); await session.runFindQueryWithCache('db', 'projection', { filter: '{ rating: 99 }', project }, 1, 50); - expect(headers()).toEqual([]); + expect(headers()).toEqual(['title', 'rating']); await session.runFindQueryWithCache('db', 'projection', { project: '{ }' }, 1, 50); expect(headers()).toEqual(expect.arrayContaining(['_id', 'title', 'rating', 'secret'])); }); + it.each([ + { + name: 'explicit root ID and missing field', + project: '{ _id: 1, address: 1 }', + path: [], + keys: [ROOT_ID_COLUMN_KEY, fieldColumnKey('address')], + }, + { + name: 'implicit root ID', + project: '{ address: 1 }', + path: [], + keys: [ROOT_ID_COLUMN_KEY, fieldColumnKey('address')], + }, + { + name: 'boolean inclusion and ID exclusion', + project: '{ address: true, _id: false }', + path: [], + keys: [fieldColumnKey('address')], + }, + { + name: 'computed outputs without expression-argument columns', + project: '{ alias: "$name", address: { $literal: { city: "Paris" } }, _id: 0 }', + path: [], + keys: [fieldColumnKey('alias'), fieldColumnKey('address')], + }, + { + name: 'root of dotted selections', + project: '{ "address.city": 1, "address.zip": 1, _id: 0 }', + path: [], + keys: [fieldColumnKey('address')], + }, + { + name: 'nested dotted selections', + project: '{ "address.city": 1, "address.zip": 1, _id: 0 }', + path: ['address'], + keys: [fieldColumnKey('city'), fieldColumnKey('zip')], + }, + { + name: 'nested projection syntax', + project: '{ address: { city: 1, zip: true }, _id: 0 }', + path: ['address'], + keys: [fieldColumnKey('city'), fieldColumnKey('zip')], + }, + { + name: 'distinct root and nested ID columns', + project: '{ "address._id": 1, "address.city": 1 }', + path: ['address'], + keys: [ROOT_ID_COLUMN_KEY, fieldColumnKey('_id'), fieldColumnKey('city')], + }, + { + name: 'exclusion-only projection', + project: '{ secret: 0 }', + path: [], + keys: [], + }, + { + name: 'nested exclusions', + project: '{ address: { city: 0 }, _id: 0 }', + path: [], + keys: [], + }, + { + name: 'unknown children of a selected whole object', + project: '{ address: 1, _id: 0 }', + path: ['address'], + keys: [], + }, + { + name: 'computed object children are not projection paths', + project: '{ address: { $literal: { city: "Paris" } }, _id: 0 }', + path: ['address'], + keys: [], + }, + ])('retains the correct empty-page hints for $name', async ({ project, path, keys }): Promise => { + runFindQuery.mockResolvedValueOnce([]); + + await session.runFindQueryWithCache('db', 'hints', { project }, 1, 50); + const page = session.getCurrentPageAsTable(path); + + expect(page.columns.map(({ key }) => key)).toEqual(keys); + expect(page.rows).toEqual([]); + }); + + it('keeps hints out of shared schema and copying while retaining additional returned fields', async (): Promise => { + runFindQuery.mockResolvedValueOnce([{ _id: 'root', extra: 'returned' }]); + await session.runFindQueryWithCache('db', 'hint-isolation', { project: '{ _id: 1, address: 1 }' }, 1, 50); + const page = session.getCurrentPageAsTable([]); + + expect(page.columns.map(({ label }) => label)).toEqual(['_id', 'address', 'extra']); + expect(session.getKnownFields().some(({ path }) => path === 'address')).toBe(false); + expect(session.getTableCellCopyText({ pageId: page.copyPageId, rowIndex: 0, columnIndex: 1 })).toBeUndefined(); + expect(session.getTableCellCopyText({ pageId: page.copyPageId, rowIndex: 0, columnIndex: 2 })).toBe('returned'); + }); + + it('updates hints for a page beyond the query limit without querying the database', async (): Promise => { + runFindQuery.mockResolvedValueOnce([{ old: 'previous' }]); + await session.runFindQueryWithCache('db', 'hint-limit', { project: '{ old: 1, _id: 0 }' }, 1, 1); + await session.runFindQueryWithCache( + 'db', + 'hint-limit', + { project: '{ address: 1, _id: 0 }', limit: 1 }, + 2, + 1, + ); + + expect(session.getCurrentPageAsTable([]).columns.map(({ label }) => label)).toEqual(['address']); + expect(runFindQuery).toHaveBeenCalledTimes(1); + }); + it('resolves full values from the same projected page, including its nested path', async () => { const longText = 'a'.repeat(500); runFindQuery.mockResolvedValueOnce([ diff --git a/src/documentdb/ClusterSession.ts b/src/documentdb/ClusterSession.ts index f0a122a55..4fdc74154 100644 --- a/src/documentdb/ClusterSession.ts +++ b/src/documentdb/ClusterSession.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type FieldEntry } from '@documentdb-js/schema-analyzer'; +import { BSONTypes, type FieldEntry } from '@documentdb-js/schema-analyzer'; import { ParseMode, parse as parseShellBSON } from '@mongodb-js/shell-bson-parser'; import * as l10n from '@vscode/l10n'; import { EJSON, ObjectId } from 'bson'; @@ -14,9 +14,13 @@ import { isIdentityTrustedForProjection } from '../utils/documentGrid/documentId import { getOwnValueAtPath, toTablePage } from '../utils/documentGrid/toTablePage'; import { toTreeNodes } from '../utils/documentGrid/toTreeNodes'; import { + fieldColumnKey, fieldFromColumnKey, getCell, + ROOT_ID_COLUMN_KEY, + type ColumnKey, type TableCellAddress, + type TableColumn, type TablePage, type TreeNode, } from '../utils/documentGrid/types'; @@ -99,7 +103,7 @@ export class ClusterSession { */ private _currentRawDocuments: WithId[] = []; private _currentPageIdentityTrusted = false; - private _currentPageProjected = false; + private _currentPageProjection: Document | undefined; private _queryGeneration = 0; private _currentTablePage: { page: TablePage; documents: (Document | undefined)[] } | undefined; @@ -169,6 +173,7 @@ export class ClusterSession { this._currentPageSize = null; this._currentRawDocuments = []; this._currentPageIdentityTrusted = false; + this._currentPageProjection = undefined; this._lastExecutionTimeMs = undefined; // Clear query insights caches @@ -243,14 +248,16 @@ export class ClusterSession { ): Promise { const generation = ++this._queryGeneration; this._currentTablePage = undefined; - let projected = false; + let projection: Document | undefined; let identityTrusted = true; if (queryParams.project && queryParams.project.trim() !== '{}') { try { - const projection: unknown = parseShellBSON(queryParams.project, { mode: ParseMode.Loose }); - if (projection !== null && typeof projection === 'object' && !Array.isArray(projection)) { - projected = Object.keys(projection).length > 0; - identityTrusted = isIdentityTrustedForProjection(projection as Document); + const parsed: unknown = parseShellBSON(queryParams.project, { mode: ParseMode.Loose }); + if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { + if (Object.keys(parsed).length > 0) { + projection = parsed as Document; + } + identityTrusted = isIdentityTrustedForProjection(projection); } else { identityTrusted = false; } @@ -275,7 +282,7 @@ export class ClusterSession { // We're trying to page beyond the query's limit - return empty results this._currentRawDocuments = []; this._currentPageIdentityTrusted = false; - this._currentPageProjected = projected; + this._currentPageProjection = projection; return 0; } @@ -323,7 +330,7 @@ export class ClusterSession { this._currentTablePage = undefined; this._currentRawDocuments = documents; this._currentPageIdentityTrusted = identityTrusted; - this._currentPageProjected = projected; + this._currentPageProjection = projection; // Store database/collection context for schema operations this._databaseName = databaseName; @@ -379,9 +386,58 @@ export class ClusterSession { return acknowledged; } + /** + * Converts positive selections in the executed projection into additive headers at the current path. + * Exclusions supply no hints; expression arguments are not treated as selected field paths. + */ + private getTableHeadersHint(path: readonly string[]): TableColumn[] { + const projection = this._currentPageProjection; + if (!projection) { + return []; + } + const selectedPaths: string[][] = []; + + /** Flattens dotted and nested selections while keeping computed expressions as output leaves. */ + function collectSelectedPaths(document: Document, prefix: readonly string[]): void { + for (const [field, value] of Object.entries(document)) { + if (value === 0 || value === false) { + continue; + } + const segments = [...prefix, ...field.split('.')]; + if ( + BSONTypes.inferType(value) === BSONTypes.Object && + !Object.keys(value as Document).some((key) => key.startsWith('$')) + ) { + collectSelectedPaths(value as Document, segments); + } else { + selectedPaths.push(segments); + } + } + } + + collectSelectedPaths(projection, []); + const hints = new Map(); + if (selectedPaths.length > 0 && projection._id !== 0 && projection._id !== false) { + hints.set(ROOT_ID_COLUMN_KEY, { key: ROOT_ID_COLUMN_KEY, label: '_id' }); + } + for (const segments of selectedPaths) { + if (!path.every((segment, index) => segment === segments[index])) { + continue; + } + const field = segments[path.length]; + if (field === undefined || field === '$') { + continue; + } + const key = path.length === 0 && field === '_id' ? ROOT_ID_COLUMN_KEY : fieldColumnKey(field); + hints.set(key, { key, label: field }); + } + return [...hints.values()]; + } + + /** Shapes the current results with executed-projection hints and replaces the full-value copy handle. */ public getCurrentPageAsTable(path: string[]): TablePage & { readonly copyPageId: string } { let headers: readonly string[] | undefined; - if (!this._currentPageProjected) { + if (!this._currentPageProjection) { headers = this._databaseName && this._collectionName ? SchemaStore.getInstance().getPropertyNamesAtLevel( @@ -393,13 +449,20 @@ export class ClusterSession { : []; } const page = { - ...toTablePage(this._currentRawDocuments, path, headers, this._currentPageIdentityTrusted), + ...toTablePage( + this._currentRawDocuments, + path, + headers, + this._currentPageIdentityTrusted, + this.getTableHeadersHint(path), + ), copyPageId: randomUUID(), }; this._currentTablePage = { page, documents: [...this._currentRawDocuments] }; return page; } + /** Resolves a populated cell's full value from the rendered page; stale or missing cells are not copyable. */ public getTableCellCopyText({ pageId, rowIndex, columnIndex }: TableCellAddress): string | undefined { const table = this._currentTablePage; if (!table || table.page.copyPageId !== pageId) { diff --git a/src/utils/documentGrid/toTablePage.test.ts b/src/utils/documentGrid/toTablePage.test.ts index cb0870ce4..8c2971dc5 100644 --- a/src/utils/documentGrid/toTablePage.test.ts +++ b/src/utils/documentGrid/toTablePage.test.ts @@ -119,6 +119,39 @@ describe('toTablePage', () => { expect(page.rows.every((row) => row.documentId !== undefined)).toBe(true); }); + it('merges header hints with returned fields without adding rows, values or identities', (): void => { + const page = toTablePage([{ _id: 'root', extra: 0 }, {}], [], undefined, true, [ + { key: fieldColumnKey('address'), label: 'address' }, + { key: ROOT_ID_COLUMN_KEY, label: '_id' }, + { key: fieldColumnKey('address'), label: 'address' }, + ]); + + expect(page.columns.map(({ key }) => key)).toEqual([ + ROOT_ID_COLUMN_KEY, + fieldColumnKey('address'), + fieldColumnKey('extra'), + ]); + expect(page.rows).toHaveLength(2); + expect(page.rows[0].documentId).toBe('"root"'); + expect(page.rows[1].documentId).toBeUndefined(); + expect(getCell(page.rows[0], fieldColumnKey('address'))).toBeUndefined(); + expect(getCell(page.rows[1], ROOT_ID_COLUMN_KEY)).toBeUndefined(); + expect(getCell(page.rows[0], fieldColumnKey('extra'))?.display).toBe('0'); + }); + + it('keeps root and nested _id hints distinct even when a projected page is empty', (): void => { + const headersHint = [ + { key: ROOT_ID_COLUMN_KEY, label: '_id' }, + { key: fieldColumnKey('_id'), label: '_id' }, + { key: fieldColumnKey('city'), label: 'city' }, + ] as const; + const page = toTablePage([], ['address'], undefined, false, headersHint); + + expect(page.columns).toEqual(headersHint); + expect(page.rows).toEqual([]); + expect(toTablePage([], [], undefined, false).columns).toEqual([]); + }); + it('previews two own fields with distinct shallow values and placeholders', () => { const nested = { toJSON: vi.fn(() => { diff --git a/src/utils/documentGrid/toTablePage.ts b/src/utils/documentGrid/toTablePage.ts index 4f8f7fcce..7ec401b97 100644 --- a/src/utils/documentGrid/toTablePage.ts +++ b/src/utils/documentGrid/toTablePage.ts @@ -7,7 +7,14 @@ import { BSONTypes, valueToDisplayString } from '@documentdb-js/schema-analyzer' import { type Document } from 'mongodb'; import { ext } from '../../extensionVariables'; import { assignRowIdentities } from './documentIdentity'; -import { fieldColumnKey, ROOT_ID_COLUMN_KEY, type ColumnKey, type GridCellValue, type TablePage } from './types'; +import { + fieldColumnKey, + ROOT_ID_COLUMN_KEY, + type ColumnKey, + type GridCellValue, + type TableColumn, + type TablePage, +} from './types'; const OBJECT_PREVIEW_FIELD_LIMIT = 2; const OBJECT_PREVIEW_KEY_LENGTH = 24; @@ -91,6 +98,7 @@ export function toGridCellValue(value: unknown): GridCellValue { } } +/** Resolves literal path segments through own properties only, without interpreting dots in field names. */ export function getOwnValueAtPath(value: unknown, path: readonly string[]): unknown { for (const field of path) { if (value === null || typeof value !== 'object' || !Object.hasOwn(value, field)) { @@ -101,11 +109,34 @@ export function getOwnValueAtPath(value: unknown, path: readonly string[]): unkn return value; } +/** + * Shapes real documents into a table, using schema headers or page-local discovery. + * Header hints add columns only; they never create rows, cell values or document identities. + * + * @param documents - The current result page in server order, e.g. `[{ _id: 'p1', address: { city: 'Paris' } }]`. + * @param path - The field segments of the table's current level: `[]` for the root or `['address']` for its children. + * @param schemaHeaders - Known field names at that level, e.g. `['city', 'zip']` inside `address`. + * Pass `undefined` to discover columns from the returned rows instead; `[]` keeps only the root `_id` and any hints. + * @param identityTrusted - Whether the query preserves the original root `_id`. Use `false` for a computed + * or partial `_id` so the row can still be displayed without allowing document actions. + * @param headersHint - Additional columns to display even when absent from every row, e.g. + * `[{ key: fieldColumnKey('zip'), label: 'zip' }]`. Defaults to no hints. + * + * @example + * ```ts + * // Inside address, discover city from the data and keep the requested zip column unset. + * const page = toTablePage([{ _id: 'p1', address: { city: 'Paris' } }], ['address'], undefined, true, [ + * { key: fieldColumnKey('zip'), label: 'zip' }, + * ]); + * // Columns: _id, zip, city + * ``` + */ export function toTablePage( documents: readonly Document[], path: readonly string[], schemaHeaders: readonly string[] | undefined, identityTrusted: boolean, + headersHint: readonly TableColumn[] = [], ): TablePage { const identities = assignRowIdentities(documents, identityTrusted); // A projected page has no schema headers; discover fields from all returned rows instead. @@ -136,11 +167,20 @@ export function toTablePage( return { ...identities[index], copyRowIndex: index, cells }; }); const fields = schemaHeaders?.filter((field) => field !== '_id') ?? [...projectedFields]; + const columns = new Map(headersHint.map((column) => [column.key, column])); + if (hasRootId) { + columns.set(ROOT_ID_COLUMN_KEY, { key: ROOT_ID_COLUMN_KEY, label: '_id' }); + } + for (const field of fields) { + const key = fieldColumnKey(field); + columns.set(key, { key, label: field }); + } + const rootIdColumn = columns.get(ROOT_ID_COLUMN_KEY); return { path: [...path], columns: [ - ...(hasRootId ? [{ key: ROOT_ID_COLUMN_KEY, label: '_id' } as const] : []), - ...fields.map((field) => ({ key: fieldColumnKey(field), label: field })), + ...(rootIdColumn ? [rootIdColumn] : []), + ...[...columns.values()].filter(({ key }) => key !== ROOT_ID_COLUMN_KEY), ], rows, }; diff --git a/src/webviews/documentdb/collectionView/CollectionView.tsx b/src/webviews/documentdb/collectionView/CollectionView.tsx index 8088c0e57..bf4da0abf 100644 --- a/src/webviews/documentdb/collectionView/CollectionView.tsx +++ b/src/webviews/documentdb/collectionView/CollectionView.tsx @@ -781,6 +781,7 @@ export const CollectionView = (): JSX.Element => { }); } + /** Requests full-value copy only while the addressed table page is still current. */ async function handleCopyCellValue(address: TableCellAddress): Promise { if ( !isCurrentTablePage(currentContextRef.current) || diff --git a/src/webviews/documentdb/collectionView/tableCellClipboard.ts b/src/webviews/documentdb/collectionView/tableCellClipboard.ts index 4bd1f0950..1cf108a00 100644 --- a/src/webviews/documentdb/collectionView/tableCellClipboard.ts +++ b/src/webviews/documentdb/collectionView/tableCellClipboard.ts @@ -19,6 +19,7 @@ const menuContextSchema = tableCellAddressSchema.extend({ collectionViewSessionId: z.string(), }); +/** Copies one cached cell value without refetching; unresolvable addresses leave the clipboard unchanged. */ export async function copyTableCellValue(sessionId: string, address: TableCellAddress): Promise { try { const text = ClusterSession._sessions.get(sessionId)?.getTableCellCopyText(address); @@ -31,6 +32,7 @@ export async function copyTableCellValue(sessionId: string, address: TableCellAd } } +/** Registers the native cell menu action, validating its webview-supplied address before copying. */ export function registerTableCellClipboardCommand(context: vscode.ExtensionContext): void { context.subscriptions.push( vscode.commands.registerCommand( From 5ad49839d3103b6adeade85c96856782cdcfde3c Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Thu, 3 Dec 2026 20:42:35 +0100 Subject: [PATCH 5/7] Unify Copy in Collection View Table and Tree Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../browser/collectionViewFixtures.ts | 17 +- build/verification/browser/scenarios.ts | 4 +- .../ai-and-plans/features/data-grid/README.md | 10 +- .../features/data-grid/decisions.md | 3 + .../ai-and-plans/features/data-grid/design.md | 46 +++-- docs/user-manual/collection-view-querying.md | 16 +- package.json | 90 ++++++++- package.nls.json | 7 + src/documentdb/ClusterSession.test.ts | 152 +++++++++++---- src/documentdb/ClusterSession.ts | 84 +++++--- src/documentdb/ClustersExtension.ts | 4 +- src/documentdb/utils/toFilterQuery.ts | 82 +++++++- src/utils/documentGrid/formatGridValue.ts | 133 +++++++++++++ src/utils/documentGrid/toTablePage.ts | 2 +- .../utils/documentGrid/typeToDisplayString.ts | 7 + src/utils/documentGrid/types.ts | 19 ++ .../collectionView/CollectionView.test.tsx | 31 ++- .../collectionView/CollectionView.tsx | 53 +++--- .../collectionView/collectionViewRouter.ts | 6 +- .../resultsTab/DataViewPanelTable.test.tsx | 179 +++++------------- .../resultsTab/DataViewPanelTable.tsx | 84 ++------ .../DataViewPanelTree.focus.test.tsx | 68 +++++++ .../resultsTab/DataViewPanelTree.test.tsx | 121 +----------- .../resultsTab/DataViewPanelTree.tsx | 163 +++++++++------- .../components/resultsTab/TypedValueCell.tsx | 2 +- .../resultsTab/useFocusedCellCopyFallback.ts | 122 +++++++++--- .../collectionView/tableCellClipboard.ts | 78 ++++++-- .../documentdbQueryValidator.ts | 2 + 28 files changed, 1020 insertions(+), 565 deletions(-) create mode 100644 src/utils/documentGrid/formatGridValue.ts rename src/{webviews => }/utils/documentGrid/typeToDisplayString.ts (82%) diff --git a/build/verification/browser/collectionViewFixtures.ts b/build/verification/browser/collectionViewFixtures.ts index deaa87f27..5b8b44aa6 100644 --- a/build/verification/browser/collectionViewFixtures.ts +++ b/build/verification/browser/collectionViewFixtures.ts @@ -17,7 +17,12 @@ import { type FixtureOutputs, type TypedRpcFixtures } from './core/fixtures'; type CollectionOutputs = FixtureOutputs['mongoClusters']['collectionView']; type TablePageOutput = Exclude; -type TreeNodesOutput = Exclude; +type TreePageOutput = Exclude; +type TreeNodesOutput = TreePageOutput['nodes']; + +function treePage(nodes: TreeNodesOutput): TreePageOutput { + return { nodes, copyPageId: '51e26865-14ba-42ba-bedd-521816106bb5' }; +} type CollectionViewFixture = { readonly config?: Partial; readonly rpc: TypedRpcFixtures; @@ -603,7 +608,7 @@ export const collectionViewFixtures = { 'mongoClusters.collectionView.runFindQuery': { type: 'query', results: [{ documentCount: 2 }] }, 'mongoClusters.collectionView.getCurrentPageAsTree': { type: 'query', - results: [deepNestingNodes], + results: [treePage(deepNestingNodes)], }, }, }, @@ -614,7 +619,7 @@ export const collectionViewFixtures = { 'mongoClusters.collectionView.runFindQuery': { type: 'query', results: [{ documentCount: 1 }] }, 'mongoClusters.collectionView.getCurrentPageAsTree': { type: 'query', - results: [arrayNodes], + results: [treePage(arrayNodes)], }, 'mongoClusters.collectionView.getCurrentPageAsTable': { type: 'query', results: [arrayTablePage] }, 'mongoClusters.collectionView.getCurrentPageAsJson': { @@ -672,7 +677,7 @@ export const collectionViewFixtures = { results: [noIdPage], cases: [{ input: ['details'], results: [noIdNestedPage] }], }, - 'mongoClusters.collectionView.copyTableCellValue': { type: 'mutation', results: [null] }, + 'mongoClusters.collectionView.copyGridCell': { type: 'mutation', results: [null] }, }, }, 'first-load': { @@ -699,7 +704,7 @@ export const collectionViewFixtures = { rpc: { 'mongoClusters.collectionView.runFindQuery': { type: 'query', results: [{ documentCount: 3 }] }, 'mongoClusters.collectionView.getCurrentPageAsTable': { type: 'query', results: [heterogeneousPage] }, - 'mongoClusters.collectionView.getCurrentPageAsTree': { type: 'query', results: [heterogeneousTreeNodes] }, + 'mongoClusters.collectionView.getCurrentPageAsTree': { type: 'query', results: [treePage(heterogeneousTreeNodes)] }, }, }, identity: { @@ -749,7 +754,7 @@ export const collectionViewFixtures = { rpc: { 'mongoClusters.collectionView.runFindQuery': { type: 'query', results: [{ documentCount: 3 }] }, 'mongoClusters.collectionView.getCurrentPageAsTable': { type: 'query', results: [heterogeneousPage] }, - 'mongoClusters.collectionView.getCurrentPageAsTree': { type: 'query', results: [heterogeneousTreeNodes] }, + 'mongoClusters.collectionView.getCurrentPageAsTree': { type: 'query', results: [treePage(heterogeneousTreeNodes)] }, }, }, } as const satisfies Readonly< diff --git a/build/verification/browser/scenarios.ts b/build/verification/browser/scenarios.ts index 09caf0c21..66f7eec10 100644 --- a/build/verification/browser/scenarios.ts +++ b/build/verification/browser/scenarios.ts @@ -1072,8 +1072,8 @@ export const collectionViewContracts = { kind: 'calls', name: 'Full-value shortcut targets the focused object cell without a document ID', requiresGrid: 'grid', - path: 'mongoClusters.collectionView.copyTableCellValue', - input: { pageId: '4bf66698-74a7-4547-ad4c-607bc11a0f73', rowIndex: 0, columnIndex: 2 }, + path: 'mongoClusters.collectionView.copyGridCell', + input: { view: 'table', pageId: '4bf66698-74a7-4547-ad4c-607bc11a0f73', rowIndex: 0, columnIndex: 2 }, count: 1, steps: [ { action: 'focus', role: 'gridcell', name: '{...}' }, diff --git a/docs/ai-and-plans/features/data-grid/README.md b/docs/ai-and-plans/features/data-grid/README.md index cc3484158..0c09f64a5 100644 --- a/docs/ai-and-plans/features/data-grid/README.md +++ b/docs/ai-and-plans/features/data-grid/README.md @@ -25,7 +25,7 @@ released extension version or completion of the remaining handover gates. - `react-data-grid@7.0.0-beta.64` renders the Table and the application-owned document Tree. The independent JSON view remains separate. -- `src/utils/documentGrid/` defines grid-neutral `TablePage` and `TreeNode` shapes, BSON display +- `src/utils/documentGrid/` defines grid-neutral `TablePage`, `TreePage`, and `TreeNode` shapes, BSON display values, and the identity helpers used by host shaping. `ClusterSession` creates those shapes; React components do not depend on database documents directly. - The Table supports nested-object step-in. The Tree flattens visible descendants from an @@ -68,9 +68,9 @@ released extension version or completion of the remaining handover gates. or both Ctrl and Cmd does not resize a column. - Embedded Table objects preview their first two fields without expanding nested values; Table arrays retain `array[N]`. Tree containers show direct field/element counts. -- Native platform Copy copies the active cell's display text, including a preview, without - type decorations. Table **Copy Cell Value** is a separate native command and keyboard shortcut - that copies the full underlying value from the executed page without a document ID or refetch. +- Native platform Copy copies the focused header, Tree Field, or Tree Type label, or a full Table + or Tree value as a shell literal. The native context menu targets the clicked cell and offers + **Copy As** on values. Value copy resolves the rendered page's cache without an ID or refetch. - The hover opt-out setting or effective reduced motion suppresses Table/Tree hover highlights, retaining focus and selection. A polite Escape hint is frozen once per confirmed grid entry. @@ -146,7 +146,7 @@ Operator workbench feedback on 2026-11-30 accepted the hover checks and NVDA ent hints. Narrator was not reported. Actual-host Ctrl+C initially retained the previous clipboard contents because body-targeted Copy events bypassed RDG's grid-root handler. The focused-cell document fallback in `e62dfff69` resolved this: the operator passed -all listed Table/Tree Copy, header-exclusion and JSON Copy checks. The correction's +all listed Table/Tree Copy, then-current header-exclusion and JSON Copy checks. The correction's Case 1 build and 51 focused tests passed; temporary tracing was removed before commit. R3's packaged checks are now earned from diff --git a/docs/ai-and-plans/features/data-grid/decisions.md b/docs/ai-and-plans/features/data-grid/decisions.md index 888944327..568af2c0f 100644 --- a/docs/ai-and-plans/features/data-grid/decisions.md +++ b/docs/ai-and-plans/features/data-grid/decisions.md @@ -273,6 +273,9 @@ and platform copy shortcuts such as Ctrl+Insert, rather than restricting the implementation to a remembered Ctrl/Cmd+C keydown. This clarifies O3's input route; typed copy and range selection remain out of scope. +The display-only restriction was superseded on the unified Table/Tree Copy branch. See +[the current design](./design.md) for native label and value Copy. Range selection remains out of scope. + ## 0007 - Column-width hold release and width scope **Status:** Accepted · **Date:** 2026-12-01 diff --git a/docs/ai-and-plans/features/data-grid/design.md b/docs/ai-and-plans/features/data-grid/design.md index aed27621f..1717e193f 100644 --- a/docs/ai-and-plans/features/data-grid/design.md +++ b/docs/ai-and-plans/features/data-grid/design.md @@ -106,24 +106,30 @@ Embedded objects use a bounded, shallow preview of the first two own enumerable Nested objects and arrays use placeholders rather than recursive formatting; a third field adds an omission marker without reading its value. Table arrays retain `array[N]`. -Native platform Copy, including Ctrl/Cmd+C, copies the active body cell's full display string, -not the type glyph, accessible type label or selected rows. A missing field copies empty text. -Preview copy is not typed BSON/EJSON export. Read-only Table/Tree cells disable native substring -selection and the text cursor. Tree Copy shares the Field/Value/Type rendering text. - -A document-level native Copy fallback covers desktop-host events targeted at the -document body, which do not reach RDG's grid-root handler. It acts only while an actual -body gridcell in the current grid has focus; headers, editors, outside focus and -already-handled events are excluded. In-grid events still use RDG. The fallback resolves -the current Table page or visible Tree rows, not DOM text containing type decorations. -Its ARIA index mapping assumes the existing single header row and no summary rows. - -Table **Copy Cell Value** uses a native VS Code context menu on populated cells and -Alt+Shift+C (Option+Shift+C on macOS) on the focused cell. Both routes use the same host -clipboard writer. The address contains the rendered page ID, original row index, and column -index. The host resolves the column against the rendered path and the row against that page's -cached documents, without parsing previews or refetching. Replaced pages and deleted rows are -unresolvable. Strings and ObjectIds copy as plain text; structured values use Extended JSON. +Native platform Copy targets the focused Table or Tree cell. Column headers (even with no rows), +Tree Field cells, and Tree Type cells copy their visible labels. Table data and Tree Value cells +copy the full returned value as a shell literal by default, including collapsed containers and +the whole returned document at a Tree root. Alt+Shift+C (Option+Shift+C on macOS) is an alias +for default value copy. Missing and stale values leave the clipboard unchanged. + +A single native document-level Copy listener covers both grid-origin events and desktop-host +events targeted at the document body. It resolves the actual focused header or cell and never +copies from Monaco, JSON View, inputs, or focus outside the grid. It uses model text rather than +DOM text with decorations. The ARIA index mapping assumes one header row and no summary rows. + +The native context menu targets the clicked cell independently of grid focus or row selection. +Header resize actions remain alongside **Copy Column Name**. Field and type labels offer only +their label action. Populated values offer **Copy Cell Value** and **Copy As**: **Shell Literal**, +**Display Text**, and **Extended JSON (Canonical)**. Value copy shares a host formatter across +menu and keyboard, using display text only when explicitly requested. Canonical Extended JSON +preserves the driver-returned BSON type information, not types already promoted by the driver. + +Menu metadata carries opaque addresses, not document contents. Table addresses use the rendered +page ID, original row index, and column index. Tree addresses use the rendered page ID and a node +index in the complete Tree, not its visible row index. The host resolves that node's typed path +segments against the cached documents, preserving literal dots in field names. Neither view +requires an `_id` or refetches values. Display-only native Copy and header exclusion are superseded; +copy remains a single target, not a row or range export. In Table and Tree headers, Ctrl/Cmd+Left/Right Arrow resizes the focused column only when no other modifiers are held. Shift, Alt, or holding both Ctrl and Cmd suppresses @@ -206,8 +212,8 @@ chosen from the entry view/selection and stays frozen during cell moves or selec so delayed delivery is not cancelled. A known focus destination outside the grid rearms it; null focus targets, including window/webview switching, do not. Re-entry gets a fresh keyed Announcer. Existing selection-first Escape and popup precedence are unchanged. -The operator passed NVDA entry-hint delivery and, after the document-Copy correction, -the listed Table/Tree/header/JSON host clipboard checks. Narrator remains unreported. +The operator passed NVDA entry-hint delivery and the previous Table/Tree/header/JSON clipboard +contract after the document-Copy correction. Narrator remains unreported. ## Verification and limits diff --git a/docs/user-manual/collection-view-querying.md b/docs/user-manual/collection-view-querying.md index 2ce7f5edb..5b6669d94 100644 --- a/docs/user-manual/collection-view-querying.md +++ b/docs/user-manual/collection-view-querying.md @@ -101,11 +101,21 @@ The project editor controls which fields appear in the results. Use `1` to inclu In Table View, selected projection fields remain as columns even when no returned document contains them or the query returns no documents. Missing values are shown as unset, not as `null`. Fields actually returned on the current page also appear, including fields missing from some rows. Root `_id` stays first when returned or included by the projection. Exclusion-only projections discover columns from returned documents. Clear the projection and run the query again to restore normal column discovery. -### Copy a Table cell +### Copy a Table or Tree cell -Right-click a populated cell and choose **Copy Cell Value**, or focus the cell and press **Alt+Shift+C** (**Option+Shift+C** on macOS). This copies one full value, including all fields of an object or all elements of an array, even when the projection excludes `_id`. Structured values use Extended JSON; strings and ObjectId hex values are copied as plain text. +Press **Ctrl+C** (**Cmd+C** on macOS) to copy the focused cell, or right-click a cell to copy that cell regardless of focus or row selection. -Ordinary **Ctrl+C** (**Cmd+C** on macOS) still copies the cell's display text, such as an object preview or array count. Neither action copies the entire document. +- A column header copies its name, even on an empty results page. Choose **Copy Column Name** from the header menu. +- Tree **Field** and **Type** cells copy their displayed labels. Choose **Copy Field Name** or **Copy Type Name** from the cell menu. +- Table cells and Tree **Value** cells copy the full returned value by default. Choose **Copy Cell Value**, or press **Alt+Shift+C** (**Option+Shift+C** on macOS) on the focused value. Collapsed objects and arrays copy all their contents. A Tree root **Value** copies the entire returned document, as limited by the projection. No `_id` is required. + +Value cells also offer **Copy As**: + +- **Shell Literal**: The default, ready to paste into a filter or shell expression. A string is quoted and escaped; an ObjectId is copied as `ObjectId("...")`. +- **Display Text**: The text shown in the grid, including a preview or count when applicable, without icons or accessibility labels. +- **Extended JSON (Canonical)**: The full value with the BSON type information available from the driver. It cannot recover numeric subtypes the driver already converted. + +A missing field or stale result leaves the clipboard unchanged. In **Shell Literal** format, a null value copies as `null` and an empty string as `""`. ## Writing Sort Expressions diff --git a/package.json b/package.json index e9d643a12..ee6863f64 100644 --- a/package.json +++ b/package.json @@ -789,6 +789,30 @@ "command": "vscode-documentdb.command.collectionView.context.copyCellValue", "title": "%collectionView.copyCellValue%" }, + { + "command": "vscode-documentdb.command.collectionView.context.copyColumnName", + "title": "%collectionView.copyColumnName%" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyFieldName", + "title": "%collectionView.copyFieldName%" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyTypeName", + "title": "%collectionView.copyTypeName%" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyShellLiteral", + "title": "%collectionView.copyShellLiteral%" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyDisplayText", + "title": "%collectionView.copyDisplayText%" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyCanonicalExtendedJson", + "title": "%collectionView.copyCanonicalExtendedJson%" + }, { "command": "vscode-documentdb.command.clusterDashboard.context.copyReference", "title": "Copy Reference" @@ -978,6 +1002,12 @@ "title": "Show Shell and Playground Sessions" } ], + "submenus": [ + { + "id": "documentdb-collection-view-copy-as", + "label": "%collectionView.copyAs%" + } + ], "menus": { "view/title": [ { @@ -1053,7 +1083,27 @@ "webview/context": [ { "command": "vscode-documentdb.command.collectionView.context.copyCellValue", - "when": "webviewId == 'vscode-documentdb-collection-view' && collectionViewTableCell", + "when": "webviewId == 'vscode-documentdb-collection-view' && collectionViewCopyKind == 'value'", + "group": "1_copy@1" + }, + { + "submenu": "documentdb-collection-view-copy-as", + "when": "webviewId == 'vscode-documentdb-collection-view' && collectionViewCopyKind == 'value'", + "group": "1_copy@2" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyColumnName", + "when": "webviewId == 'vscode-documentdb-collection-view' && collectionViewColumnHeader", + "group": "1_copy" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyFieldName", + "when": "webviewId == 'vscode-documentdb-collection-view' && collectionViewCopyKind == 'field'", + "group": "1_copy" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyTypeName", + "when": "webviewId == 'vscode-documentdb-collection-view' && collectionViewCopyKind == 'type'", "group": "1_copy" }, { @@ -1665,12 +1715,50 @@ "group": "yheAlmostLastGroup@1" } ], + "documentdb-collection-view-copy-as": [ + { + "command": "vscode-documentdb.command.collectionView.context.copyShellLiteral", + "group": "copy@1" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyDisplayText", + "group": "copy@2" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyCanonicalExtendedJson", + "group": "copy@3" + } + ], "explorer/context": [], "commandPalette": [ { "command": "vscode-documentdb.command.collectionView.context.copyCellValue", "when": "never" }, + { + "command": "vscode-documentdb.command.collectionView.context.copyColumnName", + "when": "never" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyFieldName", + "when": "never" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyTypeName", + "when": "never" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyShellLiteral", + "when": "never" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyDisplayText", + "when": "never" + }, + { + "command": "vscode-documentdb.command.collectionView.context.copyCanonicalExtendedJson", + "when": "never" + }, { "command": "vscode-documentdb.command.disconnect", "when": "false" diff --git a/package.nls.json b/package.nls.json index 7ab3b3a28..201fbd918 100644 --- a/package.nls.json +++ b/package.nls.json @@ -1,5 +1,12 @@ { "collectionView.copyCellValue": "Copy Cell Value", + "collectionView.copyColumnName": "Copy Column Name", + "collectionView.copyFieldName": "Copy Field Name", + "collectionView.copyTypeName": "Copy Type Name", + "collectionView.copyAs": "Copy As", + "collectionView.copyShellLiteral": "Shell Literal", + "collectionView.copyDisplayText": "Display Text", + "collectionView.copyCanonicalExtendedJson": "Extended JSON (Canonical)", "connections.disconnect": "Disconnect", "diagnostics.showConnectionStats": "Show Connection Client Sessions", "survey.containerTitle": "DocumentDB Feedback", diff --git a/src/documentdb/ClusterSession.test.ts b/src/documentdb/ClusterSession.test.ts index 0712fd6c2..fc2cd05de 100644 --- a/src/documentdb/ClusterSession.test.ts +++ b/src/documentdb/ClusterSession.test.ts @@ -3,13 +3,14 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { BSONRegExp, Long } from 'bson'; +import { BSONRegExp, BSONSymbol, EJSON, Int32, Long, ObjectId } from 'bson'; import { type Document } from 'mongodb'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; -import { fieldColumnKey, getCell, ROOT_ID_COLUMN_KEY } from '../utils/documentGrid/types'; -import { registerTableCellClipboardCommand } from '../webviews/documentdb/collectionView/tableCellClipboard'; +import { fieldColumnKey, getCell, ROOT_ID_COLUMN_KEY, type TreeColumnKey } from '../utils/documentGrid/types'; +import { copyGridCell, registerGridClipboardCommands } from '../webviews/documentdb/collectionView/tableCellClipboard'; import { ClusterSession } from './ClusterSession'; +import { toFilterQueryObj } from './utils/toFilterQuery'; const { binding, runFindQuery, writeText } = vi.hoisted(() => ({ binding: { clusterId: 'table-test', fingerprint: 'table-test', generation: 1 }, @@ -169,8 +170,9 @@ describe('ClusterSession Table pages', () => { expect(page.columns.map(({ label }) => label)).toEqual(['_id', 'address', 'extra']); expect(session.getKnownFields().some(({ path }) => path === 'address')).toBe(false); - expect(session.getTableCellCopyText({ pageId: page.copyPageId, rowIndex: 0, columnIndex: 1 })).toBeUndefined(); - expect(session.getTableCellCopyText({ pageId: page.copyPageId, rowIndex: 0, columnIndex: 2 })).toBe('returned'); + const address = { view: 'table', pageId: page.copyPageId, rowIndex: 0 } as const; + expect(session.getGridCellCopyText({ ...address, columnIndex: 1 })).toBeUndefined(); + expect(session.getGridCellCopyText({ ...address, columnIndex: 2 })).toBe('"returned"'); }); it('updates hints for a page beyond the query limit without querying the database', async (): Promise => { @@ -197,65 +199,147 @@ describe('ClusterSession Table pages', () => { await session.runFindQueryWithCache('db', 'copy', { project: '{ nested: 1, _id: 0 }' }, 1, 50); const root = session.getCurrentPageAsTable([]); const nested = session.getCurrentPageAsTable(['nested']); - const address = { pageId: nested.copyPageId, rowIndex: 0, columnIndex: 0 }; + const address = { view: 'table', pageId: nested.copyPageId, rowIndex: 0, columnIndex: 0 } as const; expect(nested.rows[0].documentId).toBeUndefined(); - expect(session.getTableCellCopyText(address)).toBe( + expect(session.getGridCellCopyText(address, 'canonical')).toBe( JSON.stringify({ first: longText, second: false, third: { $regularExpression: { pattern: 'a.b', options: 's' } }, }), ); - expect(session.getTableCellCopyText({ ...address, rowIndex: 1 })).toBe( + expect(session.getGridCellCopyText({ ...address, rowIndex: 1 }, 'canonical')).toBe( JSON.stringify([longText, { $numberLong: '9007199254740993' }]), ); - expect(session.getTableCellCopyText({ ...address, columnIndex: 1 })).toBeUndefined(); - expect(session.getTableCellCopyText({ ...address, rowIndex: 1, columnIndex: 1 })).toBe('null'); - expect(session.getTableCellCopyText({ ...address, pageId: root.copyPageId })).toBeUndefined(); + expect(session.getGridCellCopyText({ ...address, columnIndex: 1 })).toBeUndefined(); + expect(session.getGridCellCopyText({ ...address, rowIndex: 1, columnIndex: 1 })).toBe('null'); + expect(session.getGridCellCopyText({ ...address, pageId: root.copyPageId })).toBeUndefined(); expect(runFindQuery).toHaveBeenCalledTimes(1); runFindQuery.mockResolvedValueOnce([{ nested: { 'field.with.dots': 'replacement' } }]); await session.runFindQueryWithCache('db', 'copy', { project: '{ nested: 1, _id: 0 }' }, 2, 50); const replacement = session.getCurrentPageAsTable(['nested']); - expect(session.getTableCellCopyText(address)).toBeUndefined(); - expect(session.getTableCellCopyText({ ...address, pageId: replacement.copyPageId })).toBe('replacement'); + expect(session.getGridCellCopyText(address)).toBeUndefined(); + expect(session.getGridCellCopyText({ ...address, pageId: replacement.copyPageId })).toBe('"replacement"'); }); - it('writes only the clicked cell through the native command and rejects a stale or invalid context', async () => { - runFindQuery.mockResolvedValue([{ item: ['a', 'b'] }]); + function registerCopyMenu(): (command: string, context: object) => Promise { + const registerCommand = vi.spyOn(vscode.commands, 'registerCommand'); + registerGridClipboardCommands({ subscriptions: [] } as unknown as vscode.ExtensionContext); + return async (command, context) => { + const handler = registerCommand.mock.calls.find( + ([id]) => id === `vscode-documentdb.command.collectionView.context.${command}`, + )?.[1]; + if (!handler) { + throw new Error(`Missing context-menu command ${command}`); + } + await handler({ collectionViewSessionId: sessionId, ...context }); + }; + } + + it('writes the clicked value in each native menu format and skips stale or invalid addresses', async () => { + runFindQuery.mockResolvedValue([{ item: ['a', 'b'] }, { item: [new Int32(7), { _bsontype: 'data' }] }]); await session.runFindQueryWithCache('db', 'copy', { project: '{ item: 1, _id: 0 }' }, 1, 50); const page = session.getCurrentPageAsTable([]); - const registerCommand = vi.spyOn(vscode.commands, 'registerCommand'); - registerTableCellClipboardCommand({ subscriptions: [] } as unknown as vscode.ExtensionContext); - const [command, run] = registerCommand.mock.calls[0]; - expect(command).toBe('vscode-documentdb.command.collectionView.context.copyCellValue'); + const run = registerCopyMenu(); const context = { - preventDefaultContextMenuItems: true, - collectionViewTableCell: true, - collectionViewSessionId: sessionId, + view: 'table', pageId: page.copyPageId, - rowIndex: 0, + rowIndex: 1, columnIndex: 0, }; - await run({ ...context, rowIndex: -1 }); - await run({ ...context, collectionViewTableCell: false }); + await run('copyCellValue', { ...context, rowIndex: -1 }); + await run('copyFieldName', context); expect(writeText).not.toHaveBeenCalled(); - await run(context); - expect(writeText).toHaveBeenCalledExactlyOnceWith('["a","b"]'); + await run('copyCellValue', context); + await run('copyShellLiteral', context); + await run('copyDisplayText', context); + await run('copyCanonicalExtendedJson', context); + expect(writeText.mock.calls).toEqual([ + ['[NumberInt(7), {"_bsontype": "data"}]'], + ['[NumberInt(7), {"_bsontype": "data"}]'], + ['array[2]'], + ['[{"$numberInt":"7"},{"_bsontype":"data"}]'], + ]); await session.runFindQueryWithCache('db', 'copy', { project: '{ item: 1, _id: 0 }' }, 2, 50); - await run(context); - expect(writeText).toHaveBeenCalledTimes(1); + await run('copyCellValue', context); + expect(writeText).toHaveBeenCalledTimes(4); + }); + + it('writes distinct strings for ObjectId, a look-alike, null and empty, but leaves missing alone', async () => { + const hex = '507f1f77bcf86cd799439011'; + runFindQuery.mockResolvedValueOnce([{ item: new ObjectId(hex) }, { item: hex }, { item: null }, {}, { item: '' }]); + await session.runFindQueryWithCache('db', 'copy', { project: '{ item: 1, _id: 0 }' }, 1, 50); + const { copyPageId: pageId } = session.getCurrentPageAsTable([]); + for (const rowIndex of [0, 1, 2, 3, 4]) { + await copyGridCell(sessionId, { view: 'table', pageId, rowIndex, columnIndex: 0 }); + } + expect(writeText.mock.calls).toEqual([[`ObjectId("${hex}")`], [`"${hex}"`], ['null'], ['""']]); + }); + + it('copies native Tree names, types, and full projected values at literal paths without fetching again', async () => { + runFindQuery.mockResolvedValueOnce([{ _id: 'root', 'a.b': [new Int32(7), 'item'], a: { b: 'nested' } }]); + await session.runFindQueryWithCache('db', 'copy', { project: '{ a: 1 }' }, 1, 50); + const page = session.getCurrentPageAsTree(); + const run = registerCopyMenu(); + const address = (key: string, column: TreeColumnKey): object => ({ + view: 'tree', + pageId: page.copyPageId, + nodeIndex: page.nodes.findIndex((node) => node.key === key), + column, + }); + await run('copyColumnName', { collectionViewColumnHeader: true, collectionViewColumnLabel: 'Value' }); + await run('copyFieldName', address('[0]', 'field')); + await run('copyFieldName', address('[0,"a.b",0]', 'field')); + await run('copyTypeName', address('[0,"a.b",0]', 'type')); + await run('copyTypeName', address('[0]', 'type')); + await run('copyCellValue', address('[0,"a.b"]', 'value')); + await run('copyDisplayText', address('[0,"a.b"]', 'value')); + await run('copyCellValue', address('[0,"a","b"]', 'value')); + await run('copyCellValue', address('[0]', 'value')); + expect(writeText.mock.calls).toEqual([ + ['Value'], + ['"root"'], + ['a.b[0]'], + ['Int32'], + ['Document'], + ['[NumberInt(7), "item"]'], + ['[ 2 elements ]'], + ['"nested"'], + ['{"_id": "root", "a.b": [NumberInt(7), "item"], "a": {"b": "nested"}}'], + ]); + session.getCurrentPageAsTable([]); + await run('copyCellValue', address('[0]', 'value')); + expect(writeText).toHaveBeenCalledTimes(9); + expect(runFindQuery).toHaveBeenCalledOnce(); + }); + + it('copies a literal that round-trips through the Collection View filter parser', async () => { + const item = { + ['__proto__']: { escaped: 'a"\\\n\u2028' }, + array: ['BSONRegExp("not a call")', new BSONRegExp('a.b', 'sx'), new BSONSymbol('symbol')], + }; + runFindQuery.mockResolvedValueOnce([{ item }]); + await session.runFindQueryWithCache('db', 'copy', { project: '{ item: 1, _id: 0 }' }, 1, 50); + const { copyPageId: pageId } = session.getCurrentPageAsTable([]); + await copyGridCell(sessionId, { view: 'table', pageId, rowIndex: 0, columnIndex: 0 }); + const literal = writeText.mock.lastCall?.[0]; + expect(literal).toBe( + '{["__proto__"]: {"escaped": "a\\"\\\\\\n\\u2028"}, "array": ["BSONRegExp(\\"not a call\\")", BSONRegExp("a.b", "sx"), BSONSymbol("symbol")]}', + ); + const parsed = toFilterQueryObj(`{ item: ${literal} }`); + expect(EJSON.stringify(parsed, { relaxed: false })).toBe(EJSON.stringify({ item }, { relaxed: false })); }); it('keeps surviving cell addresses stable after deleting an earlier row', async () => { runFindQuery.mockResolvedValue([{ _id: 'first', name: 'first' }, { _id: 'second', name: 'second' }]); await session.runFindQueryWithCache('db', 'delete', {}, 1, 50); const page = session.getCurrentPageAsTable([]); - const address = { pageId: page.copyPageId, columnIndex: 1 }; + const address = { view: 'table', pageId: page.copyPageId, columnIndex: 1 } as const; expect(page.rows.map((row) => row.copyRowIndex)).toEqual([0, 1]); await session.deleteDocuments('db', 'delete', ['"first"']); - expect(session.getTableCellCopyText({ ...address, rowIndex: 0 })).toBeUndefined(); - expect(session.getTableCellCopyText({ ...address, rowIndex: 1 })).toBe('second'); + expect(session.getGridCellCopyText({ ...address, rowIndex: 0 })).toBeUndefined(); + expect(session.getGridCellCopyText({ ...address, rowIndex: 1 })).toBe('"second"'); }); it('keeps a newer page copyable when an older query finishes late', async () => { @@ -269,6 +353,8 @@ describe('ClusterSession Table pages', () => { const page = session.getCurrentPageAsTable([]); resolveOlder([{ _id: 1, item: 'old' }]); await oldRun; - expect(session.getTableCellCopyText({ pageId: page.copyPageId, rowIndex: 0, columnIndex: 0 })).toBe('current'); + expect(session.getGridCellCopyText({ view: 'table', pageId: page.copyPageId, rowIndex: 0, columnIndex: 0 })).toBe( + '"current"', + ); }); }); diff --git a/src/documentdb/ClusterSession.ts b/src/documentdb/ClusterSession.ts index f3c606816..f657ff9ef 100644 --- a/src/documentdb/ClusterSession.ts +++ b/src/documentdb/ClusterSession.ts @@ -7,23 +7,27 @@ import { BSONTypes, type FieldEntry } from '@documentdb-js/schema-analyzer'; import { UserCancelledError } from '@microsoft/vscode-azext-utils'; import { ParseMode, parse as parseShellBSON } from '@mongodb-js/shell-bson-parser'; import * as l10n from '@vscode/l10n'; -import { EJSON, ObjectId } from 'bson'; +import { EJSON } from 'bson'; import { type Document, type Filter, type WithId } from 'mongodb'; import { randomUUID } from 'node:crypto'; import { ext } from '../extensionVariables'; import { isIdentityTrustedForProjection } from '../utils/documentGrid/documentIdentity'; +import { formatGridValue } from '../utils/documentGrid/formatGridValue'; import { getOwnValueAtPath, toTablePage } from '../utils/documentGrid/toTablePage'; import { toTreeNodes } from '../utils/documentGrid/toTreeNodes'; +import { treeTypeText } from '../utils/documentGrid/typeToDisplayString'; import { fieldColumnKey, fieldFromColumnKey, getCell, ROOT_ID_COLUMN_KEY, type ColumnKey, + type GridCellAddress, + type GridValueCopyFormat, type TableCellAddress, type TableColumn, type TablePage, - type TreeNode, + type TreePage, } from '../utils/documentGrid/types'; import { type QueryInsightsStage2Response } from '../webviews/documentdb/collectionView/types/queryInsights'; import { ClustersClient, type ConnectionBinding, type FindQueryParams } from './ClustersClient'; @@ -162,7 +166,10 @@ export class ClusterSession { private _currentPageIdentityTrusted = false; private _currentPageProjection: Document | undefined; private _queryGeneration = 0; - private _currentTablePage: { page: TablePage; documents: (Document | undefined)[] } | undefined; + private _currentGridPage: + | { view: 'table'; page: TablePage; documents: (Document | undefined)[] } + | { view: 'tree'; page: TreePage; documents: readonly Document[] } + | undefined; /** * Query Insights caching @@ -304,7 +311,7 @@ export class ClusterSession { signal?: AbortSignal, ): Promise { const generation = ++this._queryGeneration; - this._currentTablePage = undefined; + this._currentGridPage = undefined; let projection: Document | undefined; let identityTrusted = true; if (queryParams.project && queryParams.project.trim() !== '{}') { @@ -409,7 +416,7 @@ export class ClusterSession { this._lastExecutionTimeMs = executionTimeMs; // Update current page documents (always replace, not accumulate) - this._currentTablePage = undefined; + this._currentGridPage = undefined; this._currentRawDocuments = documents; this._currentPageIdentityTrusted = identityTrusted; this._currentPageProjection = projection; @@ -433,11 +440,15 @@ export class ClusterSession { } public getCurrentPageAsJson(): string[] { + this._currentGridPage = undefined; return this._currentRawDocuments.map((doc) => JSON.stringify(doc, null, 4)); } - public getCurrentPageAsTree(): TreeNode[] { - return toTreeNodes(this._currentRawDocuments); + public getCurrentPageAsTree(): TreePage { + const documents = this._currentRawDocuments; + const page = { nodes: toTreeNodes(documents), copyPageId: randomUUID() }; + this._currentGridPage = { view: 'tree', page, documents }; + return page; } public async deleteDocuments( @@ -468,10 +479,12 @@ export class ClusterSession { } return !deleted; }); - const table = this._currentTablePage; - if (table) { + const grid = this._currentGridPage; + if (grid?.view === 'table') { // The webview also removes rows locally. Keep the remaining original copy indexes stable. - table.documents = table.documents.map((doc) => (doc && removed.has(doc) ? undefined : doc)); + grid.documents = grid.documents.map((doc) => (doc && removed.has(doc) ? undefined : doc)); + } else if (removed.size > 0) { + this._currentGridPage = undefined; } } @@ -550,34 +563,59 @@ export class ClusterSession { ), copyPageId: randomUUID(), }; - this._currentTablePage = { page, documents: [...this._currentRawDocuments] }; + this._currentGridPage = { view: 'table', page, documents: [...this._currentRawDocuments] }; return page; } + public getGridCellCopyText(address: GridCellAddress, format: GridValueCopyFormat = 'shell'): string | undefined { + if (address.view === 'table') { + return this.getTableCellCopyText(address, format); + } + + const tree = this._currentGridPage; + if (tree?.view !== 'tree' || tree.page.copyPageId !== address.pageId) { + return undefined; + } + const node = tree.page.nodes[address.nodeIndex]; + if (!node) { + return undefined; + } + if (address.column === 'field') { + return node.field; + } + if (address.column === 'type') { + return treeTypeText(node); + } + + // Only keys created by toTreeNodes are decoded; the webview sends an opaque node index. + const [index, ...path] = JSON.parse(node.key) as [number, ...(string | number)[]]; + const document = tree.documents[index]; + return document === undefined + ? undefined + : formatGridValue(getOwnValueAtPath(document, path), node.value.display, format); + } + /** Resolves a populated cell's full value from the rendered page; stale or missing cells are not copyable. */ - public getTableCellCopyText({ pageId, rowIndex, columnIndex }: TableCellAddress): string | undefined { - const table = this._currentTablePage; - if (!table || table.page.copyPageId !== pageId) { + private getTableCellCopyText( + { pageId, rowIndex, columnIndex }: TableCellAddress, + format: GridValueCopyFormat, + ): string | undefined { + const table = this._currentGridPage; + if (table?.view !== 'table' || table.page.copyPageId !== pageId) { return undefined; } const { page, documents } = table; const column = page.columns[columnIndex]; const row = page.rows[rowIndex]; const document = documents[rowIndex]; - if (!column || !row || !document || !getCell(row, column.key)) { + const cell = column && row && getCell(row, column.key); + if (!column || !document || !cell) { return undefined; } const field = fieldFromColumnKey(column.key); const path = field === undefined ? ['_id'] : [...page.path, field]; - const value = getOwnValueAtPath(document, path); - if (value instanceof ObjectId) { - return value.toHexString(); - } - if (value === null || typeof value !== 'object') { - return Object.is(value, -0) ? '-0' : String(value); - } - return EJSON.stringify(value, { relaxed: false }); + return formatGridValue(getOwnValueAtPath(document, path), cell.display, format); } /** diff --git a/src/documentdb/ClustersExtension.ts b/src/documentdb/ClustersExtension.ts index 3f4d5489b..894035763 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -145,7 +145,7 @@ import { import { withCommandCorrelation, withTreeNodeCommandCorrelation } from '../utils/commandTelemetry'; import { registerClusterDashboardContextMenuCommands } from '../webviews/documentdb/clusterDashboard/clusterDashboardController'; import { registerCollectionViewColumnContextMenuCommands } from '../webviews/documentdb/collectionView/collectionViewController'; -import { registerTableCellClipboardCommand } from '../webviews/documentdb/collectionView/tableCellClipboard'; +import { registerGridClipboardCommands } from '../webviews/documentdb/collectionView/tableCellClipboard'; import { EntraErrorExplainer } from './auth/entraErrors/EntraErrorExplainer'; import { EntraSignInRequiredErrorExplainer } from './auth/entraErrors/EntraSignInRequiredErrorExplainer'; import { PLAYGROUND_FILE_EXTENSION, PLAYGROUND_LANGUAGE_ID, PlaygroundCommandIds } from './playground/constants'; @@ -295,7 +295,7 @@ export class ClustersExtension implements vscode.Disposable { this.registerDiscoveryTree(activateContext); this.registerHelpAndFeedbackTree(activateContext); registerClusterDashboardContextMenuCommands(ext.context); - registerTableCellClipboardCommand(ext.context); + registerGridClipboardCommands(ext.context); registerCollectionViewColumnContextMenuCommands(ext.context); // Initialize TaskService and TaskProgressReportingService diff --git a/src/documentdb/utils/toFilterQuery.ts b/src/documentdb/utils/toFilterQuery.ts index 1cbb67a15..539987523 100644 --- a/src/documentdb/utils/toFilterQuery.ts +++ b/src/documentdb/utils/toFilterQuery.ts @@ -4,7 +4,11 @@ *--------------------------------------------------------------------------------------------*/ import { ParseMode, parse as parseShellBSON } from '@mongodb-js/shell-bson-parser'; +import { parseExpressionAt } from 'acorn'; +import { simple } from 'acorn-walk'; +import { BSONRegExp, BSONSymbol, Code, DBRef } from 'bson'; import { type Document, type Filter } from 'mongodb'; +import { randomUUID } from 'node:crypto'; import * as vscode from 'vscode'; import { QueryError } from '../errors/QueryError'; @@ -25,7 +29,7 @@ export function toFilterQueryObj(queryString: string): Filter { if (queryString.trim().length === 0) { return {} as Filter; } - return parseShellBSON(queryString, { mode: ParseMode.Loose }) as Filter; + return parseFilterWithShellLiterals(queryString) as Filter; } catch (error) { const cause = error instanceof Error ? error : new Error(String(error)); throw new QueryError( @@ -37,4 +41,80 @@ export function toFilterQueryObj(queryString: string): Filter { cause, ); } + + function parseFilterWithShellLiterals(source: string): unknown { + const parse = (input: string): unknown => parseShellBSON(input, { mode: ParseMode.Loose }); + if (!/\b(?:BSONRegExp|BSONSymbol|__proto__)\b/.test(source)) { + return parse(source); + } + + // The filter parser does not expose these two shell constructors or accept computed keys. + // Rewrite only literal syntax by AST range, then let its existing allowlist parse the filter. + const replacements: { start: number; end: number; text: string }[] = []; + const values = new Map(); + simple(parseExpressionAt(source, 0, { ecmaVersion: 2020 }), { + Property(node) { + if (node.computed && node.key.type === 'Literal' && node.key.value === '__proto__') { + const key = /^\[\s*(['"])__proto__\1\s*\]/.exec(source.slice(node.start)); + if (key) { + replacements.push({ start: node.start, end: node.start + key[0].length, text: '"__proto__"' }); + } + } + }, + CallExpression(node) { + if (node.callee.type !== 'Identifier') { + return; + } + const name = node.callee.name; + const [first, second] = node.arguments; + if ( + (name !== 'BSONRegExp' && name !== 'BSONSymbol') || + first?.type !== 'Literal' || + typeof first.value !== 'string' || + node.arguments.length > (name === 'BSONRegExp' ? 2 : 1) || + (second && (second.type !== 'Literal' || typeof second.value !== 'string')) + ) { + return; + } + const value = + name === 'BSONRegExp' + ? new BSONRegExp(first.value, typeof second?.value === 'string' ? second.value : undefined) + : new BSONSymbol(first.value); + const key = randomUUID(); + values.set(key, value); + replacements.push({ start: node.start, end: node.end, text: `Symbol("${key}")` }); + }, + }); + + let rewritten = source; + for (const { start, end, text } of replacements.sort((a, b) => b.start - a.start)) { + rewritten = rewritten.slice(0, start) + text + rewritten.slice(end); + } + const result = parse(rewritten); + return values.size === 0 ? result : restoreShellLiterals(result, values); + } + + function restoreShellLiterals(value: unknown, literals: ReadonlyMap): unknown { + if (value instanceof BSONSymbol) { + return literals.get(value.value) ?? value; + } + if (Array.isArray(value)) { + return value.map((item) => restoreShellLiterals(item, literals)); + } + if (value instanceof Map) { + for (const [key, child] of value) { + value.set(key, restoreShellLiterals(child, literals)); + } + } else if ( + value !== null && + typeof value === 'object' && + (value instanceof Code || value instanceof DBRef || Object.getPrototypeOf(value) === Object.prototype) + ) { + const document = value as Record; + for (const key of Object.keys(document)) { + document[key] = restoreShellLiterals(document[key], literals); + } + } + return value; + } } diff --git a/src/utils/documentGrid/formatGridValue.ts b/src/utils/documentGrid/formatGridValue.ts new file mode 100644 index 000000000..1dafba6c2 --- /dev/null +++ b/src/utils/documentGrid/formatGridValue.ts @@ -0,0 +1,133 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { + Binary, + BSONRegExp, + BSONSymbol, + Code, + DBRef, + Decimal128, + Double, + EJSON, + Int32, + Long, + MaxKey, + MinKey, + ObjectId, + Timestamp, +} from 'bson'; +import { type GridValueCopyFormat } from './types'; + +function quote(text: string): string { + return JSON.stringify(text).replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); +} + +function numberText(value: number): string { + return Object.is(value, -0) ? '-0' : String(value); +} + +function isPlainDocument(value: unknown): value is Record { + if (value === null || typeof value !== 'object') { + return false; + } + const prototype: unknown = Object.getPrototypeOf(value); + return prototype === null || prototype === Object.prototype; +} + +function toShellLiteral(value: unknown): string { + if (typeof value === 'string') { + return quote(value); + } + if (typeof value === 'number') { + return numberText(value); + } + if (typeof value === 'bigint') { + return `NumberLong(${quote(String(value))})`; + } + if (value === null || value === undefined || typeof value === 'boolean') { + return String(value); + } + if (Array.isArray(value)) { + return `[${Array.from(value, toShellLiteral).join(', ')}]`; + } + if (value instanceof ObjectId) { + return `ObjectId(${quote(value.toHexString())})`; + } + if (value instanceof Date) { + return `new Date(${numberText(value.getTime())})`; + } + if (value instanceof Int32) { + return `NumberInt(${value.value})`; + } + if (value instanceof Double) { + return `Double(${numberText(value.value)})`; + } + if (value instanceof Decimal128) { + return `NumberDecimal(${quote(value.toString())})`; + } + if (value instanceof Timestamp) { + return `Timestamp(${value.getHighBitsUnsigned()}, ${value.getLowBitsUnsigned()})`; + } + if (value instanceof Long) { + return `NumberLong(${quote(value.toString())})`; + } + if (value instanceof Binary) { + return `BinData(${value.sub_type}, ${quote(value.toString('base64'))})`; + } + if (value instanceof BSONRegExp) { + return `BSONRegExp(${quote(value.pattern)}, ${quote(value.options)})`; + } + if (value instanceof RegExp) { + return `RegExp(${quote(value.source)}, ${quote(value.flags)})`; + } + if (value instanceof BSONSymbol) { + return `BSONSymbol(${quote(value.value)})`; + } + if (value instanceof Code) { + return `Code(${quote(value.code)}${value.scope ? `, ${toShellLiteral(value.scope)}` : ''})`; + } + if (value instanceof DBRef) { + return `DBRef(${quote(value.collection)}, ${toShellLiteral(value.oid)}, ${toShellLiteral(value.db)}, ${toShellLiteral(value.fields)})`; + } + if (value instanceof MinKey || value instanceof MaxKey) { + return `${value._bsontype}()`; + } + if (isPlainDocument(value)) { + const fields = Object.entries(value).map(([key, child]) => { + // A plain "__proto__" property in a JavaScript literal sets the prototype instead. + const name = key === '__proto__' ? `[${quote(key)}]` : quote(key); + return `${name}: ${toShellLiteral(child)}`; + }); + return `{${fields.join(', ')}}`; + } + throw new TypeError('Unsupported grid value'); +} + +function toCanonicalExtendedJson(value: unknown): string { + if (Array.isArray(value)) { + return `[${Array.from(value, toCanonicalExtendedJson).join(',')}]`; + } + if (isPlainDocument(value)) { + // A stored field named "_bsontype" is data, but EJSON treats it as an internal tag + // when handed the whole object. Serialize the document fields and delegate BSON leaves. + const fields = Object.entries(value).map( + ([key, child]) => `${JSON.stringify(key)}:${toCanonicalExtendedJson(child)}`, + ); + return `{${fields.join(',')}}`; + } + return EJSON.stringify(value, { relaxed: false }); +} + +export function formatGridValue(value: unknown, display: string, format: GridValueCopyFormat): string { + switch (format) { + case 'display': + return display; + case 'canonical': + return toCanonicalExtendedJson(value); + case 'shell': + return toShellLiteral(value); + } +} diff --git a/src/utils/documentGrid/toTablePage.ts b/src/utils/documentGrid/toTablePage.ts index 7ec401b97..55a4f0153 100644 --- a/src/utils/documentGrid/toTablePage.ts +++ b/src/utils/documentGrid/toTablePage.ts @@ -99,7 +99,7 @@ export function toGridCellValue(value: unknown): GridCellValue { } /** Resolves literal path segments through own properties only, without interpreting dots in field names. */ -export function getOwnValueAtPath(value: unknown, path: readonly string[]): unknown { +export function getOwnValueAtPath(value: unknown, path: readonly (string | number)[]): unknown { for (const field of path) { if (value === null || typeof value !== 'object' || !Object.hasOwn(value, field)) { return undefined; diff --git a/src/webviews/utils/documentGrid/typeToDisplayString.ts b/src/utils/documentGrid/typeToDisplayString.ts similarity index 82% rename from src/webviews/utils/documentGrid/typeToDisplayString.ts rename to src/utils/documentGrid/typeToDisplayString.ts index fa07c9bb2..eeba2daea 100644 --- a/src/webviews/utils/documentGrid/typeToDisplayString.ts +++ b/src/utils/documentGrid/typeToDisplayString.ts @@ -3,6 +3,9 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import * as l10n from '@vscode/l10n'; +import { type TreeNode } from './types'; + const bsonToDisplayStringMap: Record = { string: 'String', number: 'Number', @@ -35,3 +38,7 @@ const bsonToDisplayStringMap: Record = { export function bsonStringToDisplayString(type: string): string { return bsonToDisplayStringMap[type] || 'Unknown'; } + +export function treeTypeText(node: TreeNode): string { + return node.depth === 0 ? l10n.t('Document') : bsonStringToDisplayString(node.value.type); +} diff --git a/src/utils/documentGrid/types.ts b/src/utils/documentGrid/types.ts index 80d0cff96..3b6f347df 100644 --- a/src/utils/documentGrid/types.ts +++ b/src/utils/documentGrid/types.ts @@ -50,11 +50,30 @@ export interface TablePage { } export interface TableCellAddress { + readonly view: 'table'; readonly pageId: string; readonly rowIndex: number; readonly columnIndex: number; } +export interface TreePage { + readonly nodes: readonly TreeNode[]; + readonly copyPageId: string; +} + +export type TreeColumnKey = 'field' | 'value' | 'type'; + +export interface TreeCellAddress { + readonly view: 'tree'; + readonly pageId: string; + /** Index in the complete page, not the flattened list of visible nodes. */ + readonly nodeIndex: number; + readonly column: TreeColumnKey; +} + +export type GridCellAddress = TableCellAddress | TreeCellAddress; +export type GridValueCopyFormat = 'shell' | 'display' | 'canonical'; + export interface TreeNode { /** JSON.stringify([index, ...segments]); index is zero-based page position; segments retain string/number types. */ readonly key: string; diff --git a/src/webviews/documentdb/collectionView/CollectionView.test.tsx b/src/webviews/documentdb/collectionView/CollectionView.test.tsx index eab242e7d..d3a939767 100644 --- a/src/webviews/documentdb/collectionView/CollectionView.test.tsx +++ b/src/webviews/documentdb/collectionView/CollectionView.test.tsx @@ -13,8 +13,9 @@ import { fieldColumnKey, ROOT_ID_COLUMN_KEY, type ColumnKey, - type TableCellAddress, + type GridCellAddress, type TablePage, + type TreePage, } from '../../../utils/documentGrid/types'; import { CollectionView } from './CollectionView'; import { Views } from './collectionViewContext'; @@ -37,10 +38,7 @@ interface TableHostProps { readonly onStepIn: (rowKey: string, columnKey: ColumnKey, gesture: 'keyboard' | 'pointer') => void; readonly columnWidthCache: ColumnWidthCache; readonly widthScope?: ColumnWidthScope; - readonly copyCell?: { - readonly sessionId: string; - readonly copyValue: (address: TableCellAddress) => void; - }; + readonly copyValue?: (address: GridCellAddress) => void; } const rootPage: TablePage = { @@ -104,7 +102,7 @@ const client = vi.hoisted(() => { mongoClusters: { collectionView: { addDocument: mutation(), - copyTableCellValue: mutation(), + copyGridCell: mutation(), deleteDocumentsById: { mutate: vi.fn(async (): Promise => true) }, editDocumentById: mutation(), getCurrentPageAsJson: { query: vi.fn(async (): Promise => []) }, @@ -119,7 +117,9 @@ const client = vi.hoisted(() => { }); }), }, - getCurrentPageAsTree: { query: vi.fn(async (): Promise<[]> => []) }, + getCurrentPageAsTree: { + query: vi.fn(async (): Promise => ({ nodes: [], copyPageId: 'tree-page' })), + }, getFieldCompletionData: { query: vi.fn(async (): Promise<[]> => []) }, queryInsights: { getQueryInsightsStage1: { @@ -796,23 +796,22 @@ describe('CollectionView mouse Back step-up', (): void => { it('wires full-value copy to the displayed Table and rejects its address after navigation', async (): Promise => { const copyPageId = 'c0f1e4f0-d5f8-4a46-8896-b09f8fcded5a'; await render({ ...rootPage, copyPageId }); - const copyCell = boundaries.latestTableProps?.copyCell; - if (!copyCell) { + const copyValue = boundaries.latestTableProps?.copyValue; + if (!copyValue) { throw new Error('Missing Table cell copy handler'); } - expect(copyCell.sessionId).toBe('session'); - const address = { pageId: copyPageId, rowIndex: 0, columnIndex: 1 }; - await act(async () => copyCell.copyValue(address)); + const address = { view: 'table', pageId: copyPageId, rowIndex: 0, columnIndex: 1 } as const; + await act(async () => copyValue(address)); await flush(); - expect(client.trpc.mongoClusters.collectionView.copyTableCellValue.mutate).toHaveBeenCalledExactlyOnceWith( + expect(client.trpc.mongoClusters.collectionView.copyGridCell.mutate).toHaveBeenCalledExactlyOnceWith( address, ); await keyboardStepIn(); - expect(boundaries.latestTableProps?.copyCell).toBeUndefined(); - await act(async () => copyCell.copyValue(address)); + expect(boundaries.latestTableProps?.copyValue).toBeUndefined(); + await act(async () => copyValue(address)); await flush(); - expect(client.trpc.mongoClusters.collectionView.copyTableCellValue.mutate).toHaveBeenCalledOnce(); + expect(client.trpc.mongoClusters.collectionView.copyGridCell.mutate).toHaveBeenCalledOnce(); }); describe('CollectionView column width cache', (): void => { diff --git a/src/webviews/documentdb/collectionView/CollectionView.tsx b/src/webviews/documentdb/collectionView/CollectionView.tsx index 5afa15f8f..6ab43c812 100644 --- a/src/webviews/documentdb/collectionView/CollectionView.tsx +++ b/src/webviews/documentdb/collectionView/CollectionView.tsx @@ -22,9 +22,9 @@ import { fieldColumnKey, fieldFromColumnKey, getCell, - type TableCellAddress, + type GridCellAddress, type TablePage, - type TreeNode, + type TreePage, } from '../../../utils/documentGrid/types'; import { isConnectionUnavailableMessage, @@ -73,7 +73,7 @@ interface QueryResults { tablePageQuery?: CollectionViewContextType['activeQuery']; /** The executed query and path that `tablePage` was loaded for; column widths are remembered per scope. */ tableWidthScope?: ColumnWidthScope; - treeNodes?: TreeNode[]; + treePage?: TreePage; jsonDocuments?: string[]; /** Number of documents returned by the query (for screen reader announcements) */ @@ -159,7 +159,7 @@ export const CollectionView = (): JSX.Element => { resetColumnWidthCache(columnWidthCacheRef.current, activeColumnWidthQueryKey); }, [activeColumnWidthQueryKey]); - useSelectiveContextMenuPrevention('.dataViewPanelTable [role="gridcell"][data-vscode-context]'); + useSelectiveContextMenuPrevention('.documentDataGrid [role="gridcell"][data-vscode-context]'); // Apply initial query from cross-feature navigation (e.g., Playground → Collection View) useEffect(() => { @@ -233,7 +233,7 @@ export const CollectionView = (): JSX.Element => { const currentContextRef = useRef(currentContext); const dataRequestRef = useRef(0); const cachedQueryRef = useRef(undefined); - const tablePageRequestRef = useRef(undefined); + const gridPageRequestRef = useRef(undefined); currentQueryResultsRef.current = currentQueryResults; currentContextRef.current = currentContext; const queryRequestRef = useRef(0); @@ -311,7 +311,7 @@ export const CollectionView = (): JSX.Element => { !context.isLoading && context.currentView === Views.TABLE && page !== undefined && - tablePageRequestRef.current === dataRequestRef.current && + gridPageRequestRef.current === dataRequestRef.current && JSON.stringify(page.path) === JSON.stringify(context.currentViewState?.currentPath ?? []) ); }, []); @@ -539,7 +539,7 @@ export const CollectionView = (): JSX.Element => { if (claimedFocusIntent?.request === request) { disposePendingTableFocusIntent(); } - tablePageRequestRef.current = request; + gridPageRequestRef.current = request; const tableWidthScope = columnWidthScope(requestQuery, result.path); currentQueryResultsRef.current = { ...currentQueryResultsRef.current, @@ -586,9 +586,11 @@ export const CollectionView = (): JSX.Element => { showUnavailable(result.unavailable); return; } + gridPageRequestRef.current = request; + currentQueryResultsRef.current = { ...currentQueryResultsRef.current, treePage: result }; setCurrentQueryResults((prev) => ({ ...prev, - treeNodes: result, + treePage: result, })); settleFirstLoad(firstLoadDocumentCountRef.current === 0 ? 'empty' : 'dataShown'); }) @@ -979,16 +981,21 @@ export const CollectionView = (): JSX.Element => { } } - /** Requests full-value copy only while the addressed table page is still current. */ - async function handleCopyCellValue(address: TableCellAddress): Promise { - if ( - !isCurrentTablePage(currentContextRef.current) || - currentQueryResultsRef.current?.tablePage?.copyPageId !== address.pageId - ) { + async function handleCopyCellValue(address: GridCellAddress): Promise { + const context = currentContextRef.current; + const results = currentQueryResultsRef.current; + const isCurrent = + address.view === 'table' + ? isCurrentTablePage(context) && results?.tablePage?.copyPageId === address.pageId + : !context.isLoading && + context.currentView === Views.TREE && + gridPageRequestRef.current === dataRequestRef.current && + results?.treePage?.copyPageId === address.pageId; + if (!isCurrent) { return; } try { - await trpcClient.mongoClusters.collectionView.copyTableCellValue.mutate(address); + await trpcClient.mongoClusters.collectionView.copyGridCell.mutate(address); } catch { void trpcClient.common.displayErrorMessage.mutate({ message: l10n.t('An unexpected error occurred'), @@ -1411,24 +1418,26 @@ export const CollectionView = (): JSX.Element => { columnWidthCache={columnWidthCacheRef.current} widthScope={currentQueryResults?.tableWidthScope} focusRequest={tableFocusRequest} - copyCell={ + copyValue={ !currentContext.isLoading && currentQueryResults?.tablePageQuery === currentContext.activeQuery && currentQueryResults.tableWidthScope?.pathKey === JSON.stringify(currentContext.currentViewState?.currentPath ?? []) - ? { - sessionId: configuration.sessionId, - copyValue: (address): void => - void handleCopyCellValue(address), - } + ? (address): void => void handleCopyCellValue(address) : undefined } /> ), 'Tree View': ( void handleCopyCellValue(address) + } /> ), 'JSON View': ( diff --git a/src/webviews/documentdb/collectionView/collectionViewRouter.ts b/src/webviews/documentdb/collectionView/collectionViewRouter.ts index 04be47dba..c10c1302b 100644 --- a/src/webviews/documentdb/collectionView/collectionViewRouter.ts +++ b/src/webviews/documentdb/collectionView/collectionViewRouter.ts @@ -49,7 +49,7 @@ import { readOnlyJsonDocumentProvider } from '../../../utils/readOnlyJsonDocumen import { type BaseRouterContext } from '../../_integration/appRouter'; import { type ConnectionUnavailableResponse } from '../../_integration/connectionUnavailable'; import { queryInsightsRouter } from './queryInsights/queryInsightsRouter'; -import { copyTableCellValue, tableCellAddressSchema } from './tableCellClipboard'; +import { copyGridCell, gridCellAddressSchema } from './tableCellClipboard'; export type RouterContext = BaseRouterContext & { sessionId: string; @@ -348,8 +348,8 @@ export const collectionsViewRouter = router({ return session.getCurrentPageAsTable(input); }); }), - copyTableCellValue: publicProcedureWithTelemetry.input(tableCellAddressSchema).mutation(async ({ input, ctx }) => { - await copyTableCellValue((ctx as RouterContext).sessionId, input); + copyGridCell: publicProcedureWithTelemetry.input(gridCellAddressSchema).mutation(async ({ input, ctx }) => { + await copyGridCell((ctx as RouterContext).sessionId, input); }), getCurrentPageAsTree: publicProcedureWithTelemetry // procedure type diff --git a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.test.tsx b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.test.tsx index 6cf9cca7f..715eaf451 100644 --- a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.test.tsx +++ b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.test.tsx @@ -5,12 +5,7 @@ // @vitest-environment jsdom -import { - act, - type ClipboardEvent as ReactClipboardEvent, - type KeyboardEvent as ReactKeyboardEvent, - type ReactNode, -} from 'react'; +import { act, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from 'react'; import { type Column, type ColumnWidth, @@ -48,7 +43,6 @@ import { const rdg = vi.hoisted(() => ({ setActivePosition: vi.fn(), - onCellCopy: undefined as DataGridProps['onCellCopy'], onColumnWidthsChange: undefined as DataGridProps['onColumnWidthsChange'], columnWidths: undefined as DataGridProps['columnWidths'], })); @@ -73,7 +67,6 @@ vi.mock('react-data-grid', async () => { const DataGrid = React.forwardRef>(function MockDataGrid(props, ref) { React.useLayoutEffect(() => { - rdg.onCellCopy = props.onCellCopy; rdg.onColumnWidthsChange = props.onColumnWidthsChange; rdg.columnWidths = props.columnWidths; }); @@ -177,6 +170,7 @@ const positionalRow: TableRow = { let host: HTMLDivElement; let root: Root; let columnWidthCache: ColumnWidthCache; +const copyValue = vi.fn(); let resizeObservers: Array<{ readonly callback: ResizeObserverCallback; readonly targets: Set; @@ -209,6 +203,7 @@ async function render( columnWidthCache={columnWidthCache} widthScope={widthScope} focusRequest={focusRequest} + copyValue={copyValue} /> , ); @@ -303,30 +298,6 @@ function notifyPaneResize(inlineSize: number): void { }); } -function copyCell( - row: TableRow, - columnIdx: number, -): { readonly preventDefault: ReturnType; readonly setData: ReturnType } { - const handler = rdg.onCellCopy; - if (!handler) { - throw new Error('Missing onCellCopy handler'); - } - const preventDefault = vi.fn(); - const setData = vi.fn(); - const event = { - preventDefault, - clipboardData: { setData }, - } as unknown as ReactClipboardEvent; - handler( - { - row, - column: { idx: columnIdx } as Parameters[0]['column'], - }, - event, - ); - return { preventDefault, setData }; -} - function copyFrom(target: Node): { readonly event: Event; readonly setData: ReturnType; @@ -343,7 +314,7 @@ beforeEach(() => { document.body.appendChild(host); root = createRoot(host); rdg.setActivePosition.mockReset(); - rdg.onCellCopy = undefined; + copyValue.mockClear(); rdg.onColumnWidthsChange = undefined; rdg.columnWidths = undefined; columnWidthCache = createColumnWidthCache(); @@ -431,28 +402,56 @@ describe('TDD: DataViewPanelTable keyboard step-in focus', (): void => { }); describe('DataViewPanelTable copy', (): void => { - it('copies the focused display cell when the host retargets Copy to the body', async (): Promise => { - await render(page([firstRow])); - gridCell('{...}').focus(); + it.each([{ rows: [], name: 'empty' }, { rows: [firstRow], name: 'populated' }])( + 'copies the exact header label on a $name page', + async ({ rows }): Promise => { + await render(page(rows)); + const column = header('details'); + column.focus(); + + for (const target of [document.body, column]) { + const { event, setData } = copyFrom(target); + expect(event.defaultPrevented).toBe(true); + expect(setData).toHaveBeenCalledExactlyOnceWith('text/plain', 'details'); + } + }, + ); - const { event, setData } = copyFrom(document.body); + it('routes native Copy and the value shortcut to the same focused address, once per event', async (): Promise => { + const copyPageId = 'c0f1e4f0-d5f8-4a46-8896-b09f8fcded5a'; + await render({ ...page([{ ...firstRow, copyRowIndex: 5 }]), copyPageId }); + const focused = gridCell('{...}'); + focused.focus(); - expect(event.defaultPrevented).toBe(true); - expect(setData).toHaveBeenCalledWith('text/plain', '{...}'); + for (const target of [document.body, gridCell('first')]) { + const { event, setData } = copyFrom(target); + expect(event.defaultPrevented).toBe(false); + expect(setData).not.toHaveBeenCalled(); + } + focused.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'C', + code: 'KeyC', + shiftKey: true, + altKey: true, + bubbles: true, + cancelable: true, + }), + ); + const expected = { view: 'table', pageId: copyPageId, rowIndex: 5, columnIndex: 1 }; + expect(copyValue.mock.calls).toEqual([[expected], [expected], [expected]]); }); - it('copies empty text for a missing focused field', async (): Promise => { - await render(page([positionalRow])); + it('leaves the clipboard alone for missing fields, prevented events, and editors or focus outside the grid', async (): Promise => { + await render({ + ...page([{ ...positionalRow, copyRowIndex: 0 }]), + copyPageId: 'c0f1e4f0-d5f8-4a46-8896-b09f8fcded5a', + }); gridCell('').focus(); + const missing = copyFrom(document.body); + expect(missing.event.defaultPrevented).toBe(false); + expect(missing.setData).not.toHaveBeenCalled(); - const { event, setData } = copyFrom(document.body); - - expect(event.defaultPrevented).toBe(true); - expect(setData).toHaveBeenCalledWith('text/plain', ''); - }); - - it('ignores prevented, grid-origin, header, editor and outside Copy targets', async (): Promise => { - await render(page([firstRow])); const cell = gridCell('{...}'); cell.focus(); @@ -464,91 +463,15 @@ describe('DataViewPanelTable copy', (): void => { expect(prevented.defaultPrevented).toBe(true); expect(preventedSetData).not.toHaveBeenCalled(); - const gridOrigin = copyFrom(cell); - expect(gridOrigin.event.defaultPrevented).toBe(false); - expect(gridOrigin.setData).not.toHaveBeenCalled(); - - const grid = host.querySelector('[role="grid"]'); - if (!grid) { - throw new Error('Missing grid'); - } - const header = document.createElement('div'); - header.setAttribute('role', 'columnheader'); - header.tabIndex = -1; - grid.append(header); - header.focus(); - expect(copyFrom(document.body).setData).not.toHaveBeenCalled(); - const editor = document.createElement('input'); cell.append(editor); + expect(copyFrom(editor).setData).not.toHaveBeenCalled(); editor.focus(); expect(copyFrom(document.body).setData).not.toHaveBeenCalled(); - const outside = document.createElement('button'); - document.body.append(outside); - outside.focus(); + focusElsewhere(); expect(copyFrom(document.body).setData).not.toHaveBeenCalled(); - }); - - it('uses the latest rendered page for body-targeted Copy', async (): Promise => { - await render(page([firstRow])); - const replacement: TableRow = { - rowKey: 'id:"second"', - cells: { - [ROOT_ID_COLUMN_KEY]: { display: 'second', type: 'string' }, - [detailsColumn.key]: { display: '{ fresh: true }', type: 'object' }, - }, - }; - await render(page([replacement])); - gridCell('{ fresh: true }').focus(); - - const { setData } = copyFrom(document.body); - - expect(setData).toHaveBeenCalledWith('text/plain', '{ fresh: true }'); - }); - - it('copies the display string for a populated cell', async (): Promise => { - await render(page([firstRow])); - - const event = copyCell(firstRow, 0); - - expect(event.preventDefault).toHaveBeenCalledTimes(1); - expect(event.setData).toHaveBeenCalledWith('text/plain', firstRow.cells[ROOT_ID_COLUMN_KEY]?.display); - }); - - it('copies an object preview as stored without truncating the display string', async (): Promise => { - const preview = '{ name: "Ada", profile: {...}, totals: [ 3 elements ] }'; - const row: TableRow = { - ...firstRow, - cells: { - ...firstRow.cells, - [detailsColumn.key]: { display: preview, type: 'object' }, - }, - }; - await render(page([row])); - - const event = copyCell(row, 1); - - expect(event.preventDefault).toHaveBeenCalledTimes(1); - expect(event.setData).toHaveBeenCalledWith('text/plain', preview); - }); - - it('copies empty text for a missing cell', async (): Promise => { - await render(page([positionalRow])); - - const event = copyCell(positionalRow, 0); - - expect(event.preventDefault).toHaveBeenCalledTimes(1); - expect(event.setData).toHaveBeenCalledWith('text/plain', ''); - }); - - it('leaves the default copy untouched when the column key cannot be resolved', async (): Promise => { - await render(page([firstRow])); - - const event = copyCell(firstRow, 2); - - expect(event.preventDefault).not.toHaveBeenCalled(); - expect(event.setData).not.toHaveBeenCalled(); + expect(copyValue).not.toHaveBeenCalled(); }); }); diff --git a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.tsx b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.tsx index 5b4703e5b..449719263 100644 --- a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.tsx +++ b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.tsx @@ -11,6 +11,7 @@ import 'react-data-grid/lib/styles.css'; import { getCell, type ColumnKey, + type GridCellAddress, type TableCellAddress, type TablePage, type TableRow, @@ -22,7 +23,7 @@ import { LoadingAnimationTable } from './LoadingAnimationTable'; import { TypedValueCell } from './TypedValueCell'; import { useCollectionViewColumnHeaderActions } from './useCollectionViewColumnHeaderActions'; import { useColumnResizeKeyboardGuard } from './useColumnResizeKeyboardGuard'; -import { useFocusedCellCopyFallback } from './useFocusedCellCopyFallback'; +import { gridCellCopyContext, useFocusedCellCopy } from './useFocusedCellCopyFallback'; import { useStableColumnWidths, type ColumnWidthCache, type ColumnWidthScope } from './useStableColumnWidths'; interface DataViewPanelTableProps { @@ -35,10 +36,7 @@ interface DataViewPanelTableProps { /** Decided when the page was accepted; without it, widths are neither restored nor remembered. */ readonly widthScope?: ColumnWidthScope; readonly focusRequest?: DataViewPanelTableFocusRequest; - readonly copyCell?: { - readonly sessionId: string; - readonly copyValue: (address: TableCellAddress) => void; - }; + readonly copyValue?: (address: GridCellAddress) => void; } export interface DataViewPanelTableFocusRequest { @@ -51,8 +49,11 @@ const defaultColumnOptions: DefaultColumnOptions = { resizable: true, }; -function tableCellText(row: TableRow, key: ColumnKey): string { - return getCell(row, key)?.display ?? ''; +function tableCellAddress(page: TablePage | undefined, row: TableRow, columnIndex: number): TableCellAddress | undefined { + const column = page?.columns[columnIndex]; + return page?.copyPageId && row.copyRowIndex !== undefined && column && getCell(row, column.key) + ? { view: 'table', pageId: page.copyPageId, rowIndex: row.copyRowIndex, columnIndex } + : undefined; } export function DataViewPanelTable({ @@ -64,7 +65,7 @@ export function DataViewPanelTable({ columnWidthCache, widthScope, focusRequest, - copyCell, + copyValue, }: DataViewPanelTableProps): React.JSX.Element { const [currentContext] = React.useContext(CollectionViewContext); const gridRef = React.useRef(null); @@ -236,15 +237,19 @@ export function DataViewPanelTable({ ), [page?.columns, overrideFor], ); - const focusedCellText = React.useCallback( - (rowIdx: number, columnIdx: number): string | undefined => { + useFocusedCellCopy( + gridRef, + (rowIdx, columnIdx) => { + if (rowIdx === -1) { + const column = page?.columns[columnIdx]; + return column && { label: column.label }; + } const row = page?.rows[rowIdx]; - const key = page?.columns[columnIdx]?.key; - return row === undefined || key === undefined ? undefined : tableCellText(row, key); + const address = copyValue && row && tableCellAddress(page, row, columnIdx); + return address && { address }; }, - [page], + copyValue, ); - useFocusedCellCopyFallback(gridRef, focusedCellText); if (currentContext.isFirstTimeLoad) { return ; @@ -282,62 +287,15 @@ export function DataViewPanelTable({ onStepIn(row.rowKey, columnKey, 'pointer'); } }} - onCellCopy={({ column, row }, event): void => { - const columnKey = page?.columns[column.idx]?.key; - if (columnKey === undefined) { - return; - } - event.preventDefault(); - event.clipboardData.setData('text/plain', tableCellText(row, columnKey)); - }} renderers={{ renderCell: (key, props): React.JSX.Element => { - const columnKey = page?.columns[props.column.idx]?.key; - const rowIndex = props.row.copyRowIndex; - const address: TableCellAddress | undefined = - copyCell && - page?.copyPageId && - rowIndex !== undefined && - columnKey !== undefined && - getCell(props.row, columnKey) - ? { pageId: page.copyPageId, rowIndex, columnIndex: props.column.idx } - : undefined; + const address = copyValue && tableCellAddress(page, props.row, props.column.idx); return ( { - props.onKeyDown?.(event); - if ( - !copyCell || - !address || - event.defaultPrevented || - event.target !== event.currentTarget || - !event.altKey || - !event.shiftKey || - event.ctrlKey || - event.metaKey || - (event.code !== 'KeyC' && event.key.toLowerCase() !== 'c') - ) { - return; - } - event.preventDefault(); - event.stopPropagation(); - if (!event.repeat) { - copyCell.copyValue(address); - } - }} onFocusCapture={(event): void => { props.onFocusCapture?.(event); if (!event.defaultPrevented && event.target === event.currentTarget) { diff --git a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.focus.test.tsx b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.focus.test.tsx index 2b639dd4b..2b719e624 100644 --- a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.focus.test.tsx +++ b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.focus.test.tsx @@ -55,6 +55,14 @@ function gridCell(rowIndex: number, columnIndex: number): HTMLElement { return cell; } +function copyFrom(target: HTMLElement): ReturnType { + const setData = vi.fn(); + const event = new Event('copy', { bubbles: true, cancelable: true }); + Object.defineProperty(event, 'clipboardData', { value: { setData } }); + target.dispatchEvent(event); + return setData; +} + beforeEach((): void => { vi.stubGlobal('CSS', { escape: (value: string): string => value }); const querySelector = Element.prototype.querySelector; @@ -114,6 +122,66 @@ describe('DataViewPanelTree disclosure', (): void => { expect(host.querySelectorAll('[role="gridcell"]')).toHaveLength(9); }); + describe('DataViewPanelTree native Copy', (): void => { + it.each([{ rows: [], name: 'empty' }, { rows: nodes, name: 'populated' }])( + 'copies exact header labels on a $name page', + async ({ rows }): Promise => { + await act(async () => root.render()); + for (const [index, label] of ['Field', 'Value', 'Type'].entries()) { + const header = host.querySelector(`[role="columnheader"][aria-colindex="${index + 1}"]`); + if (!header) { + throw new Error(`Missing header ${label}`); + } + await act(async () => header.focus()); + expect(copyFrom(document.body)).toHaveBeenCalledExactlyOnceWith('text/plain', label); + } + }, + ); + + it('copies focused Field and Type labels, but addresses Value copy and right clicks by node, not visible row', async (): Promise => { + const pageId = 'c0f1e4f0-d5f8-4a46-8896-b09f8fcded5a'; + const copyValue = vi.fn(); + await act(async () => + root.render( + , + ), + ); + const rootField = gridCell(3, 1); + const focused = gridCell(3, 2); + await act(async () => rootField.focus()); + expect(copyFrom(document.body)).toHaveBeenCalledExactlyOnceWith('text/plain', '"zulu"'); + await act(async () => focused.focus()); + expect(copyFrom(document.body)).not.toHaveBeenCalled(); + expect(copyValue).toHaveBeenCalledExactlyOnceWith({ view: 'tree', pageId, nodeIndex: 0, column: 'value' }); + + await act(async () => rootField.click()); + const type = gridCell(4, 3); + await act(async () => type.focus()); + expect(copyFrom(type)).toHaveBeenCalledExactlyOnceWith('text/plain', 'Int32'); + + await act(async () => focused.focus()); + const clicked = gridCell(4, 2); + clicked.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, button: 2 })); + expect(document.activeElement).toBe(focused); + expect(JSON.parse(clicked.dataset.vscodeContext ?? '{}')).toEqual({ + view: 'tree', + pageId, + nodeIndex: 1, + column: 'value', + preventDefaultContextMenuItems: true, + collectionViewCopyKind: 'value', + collectionViewSessionId: 'session-tree', + }); + await act(async () => rootField.click()); + expect(clicked.isConnected).toBe(false); + }); + }); + it('uses the shared button without adding a Tab stop and keeps Enter expansion on the Field cell', async (): Promise => { await act(async () => root.render()); const fieldCell = gridCell(3, 1); diff --git a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.test.tsx b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.test.tsx index 92b0cd226..cb0c144b6 100644 --- a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.test.tsx +++ b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.test.tsx @@ -5,7 +5,7 @@ // @vitest-environment jsdom -import { act, type JSX, type ClipboardEvent as ReactClipboardEvent, type ReactNode } from 'react'; +import { act, type JSX, type ReactNode } from 'react'; import { type ColumnWidth, type DataGridHandle, type DataGridProps } from 'react-data-grid'; import { createRoot, type Root } from 'react-dom/client'; // eslint-disable-line import/no-internal-modules import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -15,7 +15,6 @@ import { DataViewPanelTree } from './DataViewPanelTree'; (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; const rdg = vi.hoisted(() => ({ - onCellCopy: undefined as DataGridProps['onCellCopy'], onColumnWidthsChange: undefined as DataGridProps['onColumnWidthsChange'], columnWidths: undefined as DataGridProps['columnWidths'], columns: undefined as DataGridProps['columns'] | undefined, @@ -30,7 +29,6 @@ vi.mock('react-data-grid', async () => { const DataGrid = React.forwardRef>( function MockDataGrid(props, ref): React.JSX.Element { React.useLayoutEffect(() => { - rdg.onCellCopy = props.onCellCopy; rdg.onColumnWidthsChange = props.onColumnWidthsChange; rdg.columnWidths = props.columnWidths; rdg.columns = props.columns; @@ -143,46 +141,10 @@ function reportColumnWidths(widths: ReadonlyMap): void { }); } -function copyCell( - row: TreeNode, - key: string, -): { readonly preventDefault: ReturnType; readonly setData: ReturnType } { - const handler = rdg.onCellCopy; - if (!handler) { - throw new Error('Missing onCellCopy handler'); - } - const preventDefault = vi.fn(); - const setData = vi.fn(); - const event = { - preventDefault, - clipboardData: { setData }, - } as unknown as ReactClipboardEvent; - handler( - { - row, - column: { key } as Parameters[0]['column'], - }, - event, - ); - return { preventDefault, setData }; -} - -function copyFromBody(): { - readonly event: Event; - readonly setData: ReturnType; -} { - const setData = vi.fn(); - const event = new Event('copy', { bubbles: true, cancelable: true }); - Object.defineProperty(event, 'clipboardData', { value: { setData } }); - document.body.dispatchEvent(event); - return { event, setData }; -} - beforeEach(() => { host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host); - rdg.onCellCopy = undefined; rdg.onColumnWidthsChange = undefined; rdg.columnWidths = undefined; rdg.columns = undefined; @@ -194,87 +156,6 @@ afterEach(async () => { document.body.replaceChildren(); }); -describe('DataViewPanelTree copy', (): void => { - it('copies the focused display cell when the host retargets Copy to the body', async (): Promise => { - await render([nestedNode]); - const valueCell = host.querySelector( - '[role="row"][aria-rowindex="2"] [role="gridcell"][aria-colindex="2"]', - ); - if (!valueCell) { - throw new Error('Missing Tree value grid cell'); - } - valueCell.focus(); - - const { event, setData } = copyFromBody(); - - expect(event.defaultPrevented).toBe(true); - expect(setData).toHaveBeenCalledWith('text/plain', '42'); - }); - - it('uses the latest visible Tree node for body-targeted Copy', async (): Promise => { - await render([nestedNode]); - const replacement: TreeNode = { - ...nestedNode, - key: '["id","answer","replacement"]', - value: { display: '99', type: 'int32' }, - }; - await render([replacement]); - const valueCell = host.querySelector( - '[role="row"][aria-rowindex="2"] [role="gridcell"][aria-colindex="2"]', - ); - if (!valueCell) { - throw new Error('Missing Tree value grid cell'); - } - valueCell.focus(); - - const { setData } = copyFromBody(); - - expect(setData).toHaveBeenCalledWith('text/plain', '99'); - }); - - it('copies the field without indentation or expander content', async (): Promise => { - await render([nestedNode]); - - const event = copyCell(nestedNode, 'field'); - - expect(event.preventDefault).toHaveBeenCalledTimes(1); - expect(event.setData).toHaveBeenCalledWith('text/plain', 'answer'); - }); - - it('copies the value display text without type content', async (): Promise => { - await render([nestedNode]); - - const event = copyCell(nestedNode, 'value'); - - expect(event.preventDefault).toHaveBeenCalledTimes(1); - expect(event.setData).toHaveBeenCalledWith('text/plain', '42'); - }); - - it('copies the displayed BSON type name for nested values', async (): Promise => { - await render([nestedNode]); - - const event = copyCell(nestedNode, 'type'); - - expect(event.preventDefault).toHaveBeenCalledTimes(1); - expect(event.setData).toHaveBeenCalledWith('text/plain', 'Int32'); - }); - - it('copies Document for a root type cell', async (): Promise => { - const documentNode: TreeNode = { - ...nestedNode, - depth: 0, - field: '0', - value: { display: '{ 2 fields }', type: 'object' }, - }; - await render([documentNode]); - - const event = copyCell(documentNode, 'type'); - - expect(event.preventDefault).toHaveBeenCalledTimes(1); - expect(event.setData).toHaveBeenCalledWith('text/plain', 'Document'); - }); -}); - describe('DataViewPanelTree column widths', (): void => { it('keeps automatic Tree columns uncapped and uncontrolled until a width is set', async (): Promise => { await render([nestedNode]); diff --git a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.tsx b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.tsx index 2fbe1caa8..debaeef30 100644 --- a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.tsx +++ b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.tsx @@ -8,18 +8,25 @@ import * as React from 'react'; import { Cell, DataGrid, Row, type Column, type ColumnWidths, type DataGridHandle } from 'react-data-grid'; // eslint-disable-next-line import/no-internal-modules -- beta.64 explicitly exports this public stylesheet subpath. import 'react-data-grid/lib/styles.css'; -import { type TreeNode } from '../../../../../utils/documentGrid/types'; +import { treeTypeText } from '../../../../../utils/documentGrid/typeToDisplayString'; +import { + type GridCellAddress, + type TreeCellAddress, + type TreeColumnKey, + type TreeNode, +} from '../../../../../utils/documentGrid/types'; import { ExpandCollapseButton } from '../../../../components/ExpandCollapseButton'; -import { bsonStringToDisplayString } from '../../../../utils/documentGrid/typeToDisplayString'; import './dataGridTheme.scss'; import { useCollectionViewColumnHeaderActions } from './useCollectionViewColumnHeaderActions'; import { useColumnResizeKeyboardGuard } from './useColumnResizeKeyboardGuard'; -import { useFocusedCellCopyFallback } from './useFocusedCellCopyFallback'; +import { gridCellCopyContext, useFocusedCellCopy } from './useFocusedCellCopyFallback'; import { useTreeRows } from './useTreeRows'; interface DataViewPanelTreeProps { readonly nodes: readonly TreeNode[]; readonly columnResizeSessionId: string; + readonly copyPageId?: string; + readonly copyValue?: (address: GridCellAddress) => void; } interface TreeFocusRecord { @@ -28,24 +35,16 @@ interface TreeFocusRecord { readonly rowIdx: number; } -function treeCellText(row: TreeNode, key: Column['key']): string { - switch (key) { - case 'field': - return row.field; - case 'value': - return row.value.display; - case 'type': - return row.depth === 0 ? l10n.t('Document') : bsonStringToDisplayString(row.value.type); - default: - return ''; - } -} - const TREE_COLUMN_MIN_WIDTH = 100; const TREE_COLUMN_KEYS: ReadonlySet = new Set(['field', 'value', 'type']); -export const DataViewPanelTree = ({ nodes, columnResizeSessionId }: DataViewPanelTreeProps): React.JSX.Element => { +export const DataViewPanelTree = ({ + nodes, + columnResizeSessionId, + copyPageId, + copyValue, +}: DataViewPanelTreeProps): React.JSX.Element => { const gridRef = React.useRef(null); useColumnResizeKeyboardGuard(gridRef); const focusedCellRef = React.useRef(undefined); @@ -68,11 +67,19 @@ export const DataViewPanelTree = ({ nodes, columnResizeSessionId }: DataViewPane : new Map(previous).set(columnKey, { type: 'resized', width }), ); }, []); + const headerActions = React.useMemo( + () => [ + { key: 'field', label: l10n.t('Field'), minWidth: TREE_COLUMN_MIN_WIDTH }, + { key: 'value', label: l10n.t('Value'), minWidth: TREE_COLUMN_MIN_WIDTH }, + { key: 'type', label: l10n.t('Type'), minWidth: TREE_COLUMN_MIN_WIDTH }, + ] as const, + [], + ); const columns = React.useMemo[]>( - (): readonly Column[] => [ + () => [ { - key: 'field', - name: l10n.t('Field'), + key: headerActions[0].key, + name: headerActions[0].label, cellClass: (row): string => (row.expandable ? 'treeFieldCell treeExpandableCell' : 'treeFieldCell'), renderCell: ({ row }): React.ReactNode => ( <> @@ -101,30 +108,22 @@ export const DataViewPanelTree = ({ nodes, columnResizeSessionId }: DataViewPane ) : (