diff --git a/build/verification/browser/collectionViewFixtures.ts b/build/verification/browser/collectionViewFixtures.ts index 795574bdc..85328e5e2 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; @@ -373,6 +378,7 @@ const emptyPage: TablePageOutput = { }; const noIdPage: TablePageOutput = { + copyPageId: '4bf66698-74a7-4547-ad4c-607bc11a0f73', path: [], columns: [ { key: ROOT_ID_COLUMN_KEY, label: '_id' }, @@ -382,6 +388,7 @@ const noIdPage: TablePageOutput = { rows: [ { rowKey: 'pos:0', + copyRowIndex: 0, cells: { [fieldColumnKey('name')]: { display: 'Browse only', type: 'string' }, [fieldColumnKey('details')]: { display: '{...}', type: 'object' }, @@ -389,6 +396,7 @@ const noIdPage: TablePageOutput = { }, { rowKey: 'id:"ordinary-target"', + copyRowIndex: 1, documentId: '"ordinary-target"', cells: { [ROOT_ID_COLUMN_KEY]: { display: 'ordinary-target', type: 'string' }, @@ -600,7 +608,7 @@ export const collectionViewFixtures = { 'mongoClusters.collectionView.runFindQuery': { type: 'query', results: [{ documentCount: 2 }] }, 'mongoClusters.collectionView.getCurrentPageAsTree': { type: 'query', - results: [deepNestingNodes], + results: [treePage(deepNestingNodes)], }, }, }, @@ -611,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': { @@ -669,6 +677,7 @@ export const collectionViewFixtures = { results: [noIdPage], cases: [{ input: ['details'], results: [noIdNestedPage] }], }, + 'mongoClusters.collectionView.copyGridCell': { type: 'mutation', results: [null] }, }, }, 'first-load': { @@ -695,7 +704,10 @@ 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: { @@ -745,7 +757,10 @@ 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 f7ed88f87..66f7eec10 100644 --- a/build/verification/browser/scenarios.ts +++ b/build/verification/browser/scenarios.ts @@ -1068,6 +1068,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.copyGridCell', + input: { view: 'table', 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 601d628f6..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 @@ -41,8 +41,12 @@ 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 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 0010](./decisions.md#0010---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. @@ -64,8 +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. Read-only cells do not offer substring selection; typed copy is future work. +- 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. @@ -141,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 c1f4403f7..568af2c0f 100644 --- a/docs/ai-and-plans/features/data-grid/decisions.md +++ b/docs/ai-and-plans/features/data-grid/decisions.md @@ -21,6 +21,7 @@ implementation remains subject to the planned work items and later gates. | 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 | Header-menu column sizing without dragging | Accepted | Fit uses RDG's double-click; Tree keeps auto sizing | 2026-12-02 | #1147 | +| 0010 | 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 @@ -272,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 @@ -376,3 +380,29 @@ Recheck the synthetic double-click and the header DOM on any RDG upgrade; see header rendered after mount, and focus return after focus moved elsewhere. - An operator F5 pass on 2026-12-02 confirmed both commands, pointer and keyboard menus, scrolled-in headers, Tree sizing and focus after Escape. + +## 0010 - 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 95d70cd5b..17990629a 100644 --- a/docs/ai-and-plans/features/data-grid/design.md +++ b/docs/ai-and-plans/features/data-grid/design.md @@ -20,8 +20,19 @@ 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 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 0010](./decisions.md#0010---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 path segments. The keys do not contain or depend on `_id`. The tree is application-owned rather @@ -61,13 +72,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 step-in 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 @@ -95,17 +106,34 @@ 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. +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. +Shift+F10 and the Context Menu key use the native menu bridge. For body cells the grid explicitly +dispatches the event on the focused cell because desktop VS Code does not always dispatch it there. +On menu close, restore the former grid focus only if the workbench leaves focus on the body +and the target still belongs to the current grid. +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 @@ -188,8 +216,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 0feef05c8..ecd7e5930 100644 --- a/docs/user-manual/collection-view-querying.md +++ b/docs/user-manual/collection-view-querying.md @@ -99,6 +99,24 @@ 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, 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 or Tree cell + +Press **Ctrl+C** (**Cmd+C** on macOS) to copy the focused cell. To open its menu, press **Shift+F10** or the **Context Menu** key. Right-clicking instead opens the menu for the clicked cell, regardless of focus or row selection. + +- 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 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 fdca8c040..ee6863f64 100644 --- a/package.json +++ b/package.json @@ -785,6 +785,34 @@ "command": "vscode-documentdb.command.clusterDashboard.context.manageIndexes", "title": "Manage Indexes" }, + { + "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" @@ -974,6 +1002,12 @@ "title": "Show Shell and Playground Sessions" } ], + "submenus": [ + { + "id": "documentdb-collection-view-copy-as", + "label": "%collectionView.copyAs%" + } + ], "menus": { "view/title": [ { @@ -1047,6 +1081,31 @@ } ], "webview/context": [ + { + "command": "vscode-documentdb.command.collectionView.context.copyCellValue", + "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" + }, { "command": "vscode-documentdb.command.collectionView.column.resize", "when": "webviewId == 'vscode-documentdb-collection-view' && collectionViewColumnHeader", @@ -1656,8 +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 0ec099292..201fbd918 100644 --- a/package.nls.json +++ b/package.nls.json @@ -1,4 +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 new file mode 100644 index 000000000..255c2493e --- /dev/null +++ b/src/documentdb/ClusterSession.test.ts @@ -0,0 +1,363 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +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, 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 }, + 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', () => { + const client = { binding, runFindQuery, deleteDocuments: () => Promise.resolve(true) }; + return { + ClustersClient: { + getClient: () => Promise.resolve(client), + resolveBoundClient: () => Promise.resolve(client), + getEpoch: () => 0, + getLatchReason: () => undefined, + getBinding: () => binding, + assertBindingActive: vi.fn(), + reportFailure: vi.fn(), + }, + }; +}); +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); + vi.restoreAllMocks(); + writeText.mockClear(); + }); + + 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(['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); + 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 => { + 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([ + { 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 = { view: 'table', pageId: nested.copyPageId, rowIndex: 0, columnIndex: 0 } as const; + expect(nested.rows[0].documentId).toBeUndefined(); + expect(session.getGridCellCopyText(address, 'canonical')).toBe( + JSON.stringify({ + first: longText, + second: false, + third: { $regularExpression: { pattern: 'a.b', options: 's' } }, + }), + ); + expect(session.getGridCellCopyText({ ...address, rowIndex: 1 }, 'canonical')).toBe( + JSON.stringify([longText, { $numberLong: '9007199254740993' }]), + ); + 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.getGridCellCopyText(address)).toBeUndefined(); + expect(session.getGridCellCopyText({ ...address, pageId: replacement.copyPageId })).toBe('"replacement"'); + }); + + 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 run = registerCopyMenu(); + const context = { + view: 'table', + pageId: page.copyPageId, + rowIndex: 1, + columnIndex: 0, + }; + await run('copyCellValue', { ...context, rowIndex: -1 }); + await run('copyFieldName', context); + expect(writeText).not.toHaveBeenCalled(); + 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('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 = { 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.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 () => { + 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.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 4498cac68..8ab10b78d 100644 --- a/src/documentdb/ClusterSession.ts +++ b/src/documentdb/ClusterSession.ts @@ -3,17 +3,32 @@ * 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 { 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 } 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 { formatGridValue } from '../utils/documentGrid/formatGridValue'; +import { getOwnValueAtPath, toTablePage } from '../utils/documentGrid/toTablePage'; import { toTreeNodes } from '../utils/documentGrid/toTreeNodes'; -import { type TablePage, type TreeNode } from '../utils/documentGrid/types'; +import { + fieldColumnKey, + fieldFromColumnKey, + getCell, + ROOT_ID_COLUMN_KEY, + type ColumnKey, + type GridCellAddress, + type GridValueCopyFormat, + type TableCellAddress, + type TableColumn, + type TablePage, + type TreePage, +} from '../utils/documentGrid/types'; +import { treeTypeText } from '../utils/documentGrid/typeToDisplayString'; import { type QueryInsightsStage2Response } from '../webviews/documentdb/collectionView/types/queryInsights'; import { ClustersClient, type ConnectionBinding, type FindQueryParams } from './ClustersClient'; import { getRetiredBindingReason, isRetiredConnectionBinding } from './connectionBindingRetirement'; @@ -149,6 +164,12 @@ export class ClusterSession { */ private _currentRawDocuments: WithId[] = []; private _currentPageIdentityTrusted = false; + private _currentPageProjection: Document | undefined; + private _queryGeneration = 0; + private _currentGridPage: + | { view: 'table'; page: TablePage; documents: (Document | undefined)[] } + | { view: 'tree'; page: TreePage; documents: readonly Document[] } + | undefined; /** * Query Insights caching @@ -215,6 +236,7 @@ export class ClusterSession { this._currentPageSize = null; this._currentRawDocuments = []; this._currentPageIdentityTrusted = false; + this._currentPageProjection = undefined; this._lastExecutionTimeMs = undefined; // Clear query insights caches @@ -288,6 +310,27 @@ export class ClusterSession { executionIntent: 'initial' | 'refresh' | 'pagination' = 'pagination', signal?: AbortSignal, ): Promise { + const generation = ++this._queryGeneration; + this._currentGridPage = undefined; + let projection: Document | undefined; + let identityTrusted = true; + if (queryParams.project && queryParams.project.trim() !== '{}') { + try { + 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; + } + } catch { + // The query execution retains its existing projection-error reporting. + identityTrusted = false; + } + } + const querySkip = queryParams.skip ?? 0; const queryLimit = queryParams.limit ?? 0; @@ -302,9 +345,13 @@ export class ClusterSession { if (queryLimit > 0 && pageOffset >= queryLimit) { return this.runWithClient((_client, epoch) => { this.assertCurrent(epoch, signal); + if (generation !== this._queryGeneration) { + return Promise.resolve(0); + } // We're trying to page beyond the query's limit - return empty results this._currentRawDocuments = []; this._currentPageIdentityTrusted = false; + this._currentPageProjection = projection; return Promise.resolve(0); }); } @@ -325,21 +372,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; - } - } - const epoch = this.getEpoch(); let ran: ConnectionBinding | undefined; let ranAuthMethod: ClustersClient['authMethod'] | undefined; @@ -373,6 +405,9 @@ export class ClusterSession { const { documents, executionTimeMs } = queryResult; this.assertCurrent(epoch, signal); + if (generation !== this._queryGeneration) { + return documents.length; + } this.resetCachesIfUserQueryChanged(queryParams); this.resetAccumulationIfPageSizeChanged(pageSize); if (executionIntent === 'initial' || executionIntent === 'refresh') { @@ -381,8 +416,10 @@ export class ClusterSession { this._lastExecutionTimeMs = executionTimeMs; // Update current page documents (always replace, not accumulate) + this._currentGridPage = undefined; this._currentRawDocuments = documents; this._currentPageIdentityTrusted = identityTrusted; + this._currentPageProjection = projection; // Store database/collection context for schema operations this._databaseName = databaseName; @@ -403,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( @@ -423,8 +464,9 @@ export class ClusterSession { // Acknowledge a completed write, but don't update the page from an old operation. if (acknowledged && this.isCurrent(epoch)) { + 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); @@ -432,19 +474,148 @@ export class ClusterSession { return docIdStr === parsedIdStr; }); + if (deleted) { + removed.add(doc); + } + return !deleted; }); + const grid = this._currentGridPage; + if (grid?.view === 'table') { + // The webview also removes rows locally. Keep the remaining original copy indexes stable. + grid.documents = grid.documents.map((doc) => (doc && removed.has(doc) ? undefined : doc)); + } else if (removed.size > 0) { + this._currentGridPage = undefined; + } } return acknowledged; } - public getCurrentPageAsTable(path: string[]): TablePage { - const store = SchemaStore.getInstance(); - const headers = - this._databaseName && this._collectionName - ? store.getPropertyNamesAtLevel(this.binding.clusterId, this._databaseName, this._collectionName, path) - : []; - return toTablePage(this._currentRawDocuments, path, headers, this._currentPageIdentityTrusted); + /** + * 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._currentPageProjection) { + headers = + this._databaseName && this._collectionName + ? SchemaStore.getInstance().getPropertyNamesAtLevel( + this.binding.clusterId, + this._databaseName, + this._collectionName, + path, + ) + : []; + } + const page = { + ...toTablePage( + this._currentRawDocuments, + path, + headers, + this._currentPageIdentityTrusted, + this.getTableHeadersHint(path), + ), + copyPageId: randomUUID(), + }; + 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. */ + 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]; + 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]; + return formatGridValue(getOwnValueAtPath(document, path), cell.display, format); } /** diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 07c8b9015..61a664e50 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -1590,6 +1590,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 477245c96..894035763 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -145,6 +145,7 @@ import { import { withCommandCorrelation, withTreeNodeCommandCorrelation } from '../utils/commandTelemetry'; import { registerClusterDashboardContextMenuCommands } from '../webviews/documentdb/clusterDashboard/clusterDashboardController'; import { registerCollectionViewColumnContextMenuCommands } from '../webviews/documentdb/collectionView/collectionViewController'; +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'; @@ -294,6 +295,7 @@ export class ClustersExtension implements vscode.Disposable { this.registerDiscoveryTree(activateContext); this.registerHelpAndFeedbackTree(activateContext); registerClusterDashboardContextMenuCommands(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..8f72672ee --- /dev/null +++ b/src/utils/documentGrid/formatGridValue.ts @@ -0,0 +1,135 @@ +/*--------------------------------------------------------------------------------------------- + * 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.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 f6a0a35f1..55a4f0153 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,53 +98,90 @@ 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 | number)[]): 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; +} + +/** + * 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[], - headers: readonly string[], + schemaHeaders: readonly string[] | undefined, identityTrusted: boolean, + headersHint: readonly TableColumn[] = [], ): 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); + } - 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') { - cells[fieldColumnKey(field)] = toGridCellValue(value); + const subdocument = getOwnValueAtPath(document, path); + 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], 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: [ + ...(rootIdColumn ? [rootIdColumn] : []), + ...[...columns.values()].filter(({ key }) => key !== ROOT_ID_COLUMN_KEY), + ], + rows, }; } 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 cac6f18db..3b6f347df 100644 --- a/src/utils/documentGrid/types.ts +++ b/src/utils/documentGrid/types.ts @@ -33,18 +33,47 @@ 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 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/components/useSelectiveContextMenuPrevention.ts b/src/webviews/components/useSelectiveContextMenuPrevention.ts index 5f1311fa9..7ab462484 100644 --- a/src/webviews/components/useSelectiveContextMenuPrevention.ts +++ b/src/webviews/components/useSelectiveContextMenuPrevention.ts @@ -7,10 +7,8 @@ import { useEffect } from 'react'; /** * Custom hook that selectively prevents context menus based on element selectors. - * Allows context menus in Monaco editor elements and on grid column headers that carry a - * `data-vscode-context` payload (stamped by a capture-phase listener before this bubble-phase - * listener runs), so VS Code can show its native webview menu there. Context menus are - * prevented everywhere else, including ordinary data cells and other UI elements. + * Allows context menus in Monaco, stamped grid column headers and an optional caller-provided + * native menu target. Context menus are prevented everywhere else. * * Additional editor selectors can be added to the allowlist as needed. */ @@ -27,17 +25,19 @@ 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); - const hasNativeWebviewMenu = target.closest('[role="columnheader"][data-vscode-context]') !== null; + const hasNativeWebviewMenu = + target instanceof Element && target.closest('[role="columnheader"][data-vscode-context]') !== null; if (!isInAllowedElement && !hasNativeWebviewMenu) { e.preventDefault(); @@ -49,5 +49,5 @@ export const useSelectiveContextMenuPrevention = (): void => { return () => { document.removeEventListener('contextmenu', handleContextMenu); }; - }, []); + }, [nativeMenuSelector]); }; diff --git a/src/webviews/documentdb/collectionView/CollectionView.test.tsx b/src/webviews/documentdb/collectionView/CollectionView.test.tsx index b9facf6f0..99d89f42f 100644 --- a/src/webviews/documentdb/collectionView/CollectionView.test.tsx +++ b/src/webviews/documentdb/collectionView/CollectionView.test.tsx @@ -9,7 +9,14 @@ import { act, type ReactNode, type Ref } from 'react'; import { type ColumnWidth } 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'; -import { fieldColumnKey, ROOT_ID_COLUMN_KEY, type ColumnKey, type TablePage } from '../../../utils/documentGrid/types'; +import { + fieldColumnKey, + ROOT_ID_COLUMN_KEY, + type ColumnKey, + type GridCellAddress, + type TablePage, + type TreePage, +} from '../../../utils/documentGrid/types'; import { CollectionView } from './CollectionView'; import { Views } from './collectionViewContext'; import type * as DataViewPanelTableModule from './components/resultsTab/DataViewPanelTable'; @@ -31,6 +38,7 @@ interface TableHostProps { readonly onStepIn: (rowKey: string, columnKey: ColumnKey, gesture: 'keyboard' | 'pointer') => void; readonly columnWidthCache: ColumnWidthCache; readonly widthScope?: ColumnWidthScope; + readonly copyValue?: (address: GridCellAddress) => void; } const rootPage: TablePage = { @@ -94,6 +102,7 @@ const client = vi.hoisted(() => { mongoClusters: { collectionView: { addDocument: mutation(), + copyGridCell: mutation(), deleteDocumentsById: { mutate: vi.fn(async (): Promise => true) }, editDocumentById: mutation(), getCurrentPageAsJson: { query: vi.fn(async (): Promise => []) }, @@ -108,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: { @@ -544,6 +555,42 @@ describe('CollectionView Backspace step-up', (): void => { await key(target, 'Enter'); } + it('sends Shift+F10 and the Context Menu key to the native menu bridge for the focused populated cell', async (): Promise => { + const pageId = 'c0f1e4f0-d5f8-4a46-8896-b09f8fcded5a'; + await render({ + ...rootWithTwoRows, + copyPageId: pageId, + rows: rootWithTwoRows.rows.map((row, copyRowIndex) => ({ ...row, copyRowIndex })), + }); + const target = cell(1, 1); + const events: MouseEvent[] = []; + const bridge = (event: MouseEvent): void => { + if (!event.defaultPrevented) { + events.push(event); + } + }; + window.addEventListener('contextmenu', bridge); + try { + await act(async () => target.focus()); + expect((await key(target, 'F10', { shiftKey: true })).defaultPrevented).toBe(true); + expect((await key(target, 'F10', { shiftKey: true, repeat: true })).defaultPrevented).toBe(true); + expect((await key(target, 'ContextMenu')).defaultPrevented).toBe(true); + expect((await key(target, 'F10')).defaultPrevented).toBe(false); + const missing = cell(1, 0); + await act(async () => missing.focus()); + expect((await key(missing, 'F10', { shiftKey: true })).defaultPrevented).toBe(false); + expect(events.map((event) => event.target)).toEqual([target, target]); + expect(JSON.parse(target.dataset.vscodeContext ?? '{}')).toMatchObject({ + view: 'table', + pageId, + rowIndex: 1, + columnIndex: 1, + }); + } finally { + window.removeEventListener('contextmenu', bridge); + } + }); + it.each([0, 1])( 'returns from nested column %i to the object cell in the same document and continues navigating', async (column) => { @@ -782,6 +829,25 @@ 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 copyValue = boundaries.latestTableProps?.copyValue; + if (!copyValue) { + throw new Error('Missing Table cell copy handler'); + } + const address = { view: 'table', pageId: copyPageId, rowIndex: 0, columnIndex: 1 } as const; + await act(async () => copyValue(address)); + await flush(); + expect(client.trpc.mongoClusters.collectionView.copyGridCell.mutate).toHaveBeenCalledExactlyOnceWith(address); + + await keyboardStepIn(); + expect(boundaries.latestTableProps?.copyValue).toBeUndefined(); + await act(async () => copyValue(address)); + await flush(); + expect(client.trpc.mongoClusters.collectionView.copyGridCell.mutate).toHaveBeenCalledOnce(); +}); + describe('CollectionView column width cache', (): void => { it('keeps one cache across paging, unexecuted edits and view switches', async (): Promise => { await render(); diff --git a/src/webviews/documentdb/collectionView/CollectionView.tsx b/src/webviews/documentdb/collectionView/CollectionView.tsx index 475e11a02..3ed969985 100644 --- a/src/webviews/documentdb/collectionView/CollectionView.tsx +++ b/src/webviews/documentdb/collectionView/CollectionView.tsx @@ -22,8 +22,9 @@ import { fieldColumnKey, fieldFromColumnKey, getCell, + type GridCellAddress, type TablePage, - type TreeNode, + type TreePage, } from '../../../utils/documentGrid/types'; import { isConnectionUnavailableMessage, @@ -69,9 +70,10 @@ 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[]; + treePage?: TreePage; jsonDocuments?: string[]; /** Number of documents returned by the query (for screen reader announcements) */ @@ -157,7 +159,7 @@ export const CollectionView = (): JSX.Element => { resetColumnWidthCache(columnWidthCacheRef.current, activeColumnWidthQueryKey); }, [activeColumnWidthQueryKey]); - useSelectiveContextMenuPrevention(); + useSelectiveContextMenuPrevention('.documentDataGrid [role="gridcell"][data-vscode-context]'); // Apply initial query from cross-feature navigation (e.g., Playground → Collection View) useEffect(() => { @@ -231,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); @@ -309,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 ?? []) ); }, []); @@ -537,16 +539,18 @@ 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, tablePage: result, + tablePageQuery: requestQuery, tableWidthScope, }; setCurrentQueryResults((prev) => ({ ...prev, tablePage: result, + tablePageQuery: requestQuery, tableWidthScope, })); if (completesFocusRequest && claimedFocusIntent !== undefined) { @@ -582,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'); }) @@ -975,6 +981,30 @@ export const CollectionView = (): JSX.Element => { } } + 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.copyGridCell.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; @@ -986,8 +1016,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; @@ -1390,12 +1418,29 @@ export const CollectionView = (): JSX.Element => { columnWidthCache={columnWidthCacheRef.current} widthScope={currentQueryResults?.tableWidthScope} focusRequest={tableFocusRequest} + copyValue={ + !currentContext.isLoading && + currentQueryResults?.tablePageQuery === + currentContext.activeQuery && + currentQueryResults.tableWidthScope?.pathKey === + JSON.stringify( + currentContext.currentViewState?.currentPath ?? [], + ) + ? (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 0c032c148..c10c1302b 100644 --- a/src/webviews/documentdb/collectionView/collectionViewRouter.ts +++ b/src/webviews/documentdb/collectionView/collectionViewRouter.ts @@ -25,6 +25,7 @@ import { } from '../../../commands/llmEnhancedCommands/queryGenerationCommands'; import { getBindingLifetimeSignal } from '../../../documentdb/connectionBindingRetirement'; import { showConfirmationAsInSettings } from '../../../utils/dialogs/showConfirmation'; +import { type TablePage } from '../../../utils/documentGrid/types'; import { ConnectionUnavailableError, @@ -48,6 +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 { copyGridCell, gridCellAddressSchema } from './tableCellClipboard'; export type RouterContext = BaseRouterContext & { sessionId: string; @@ -338,7 +340,7 @@ export const collectionsViewRouter = router({ // parameters .input(z.array(z.string())) // procedure type - .query(async ({ input, ctx }) => { + .query(async ({ input, ctx }): Promise => { const myCtx = ctx as RouterContext; return runCollectionViewOperation(myCtx, async () => { const session = ClusterSession.getSession(myCtx.sessionId); @@ -346,6 +348,9 @@ export const collectionsViewRouter = router({ return session.getCurrentPageAsTable(input); }); }), + copyGridCell: publicProcedureWithTelemetry.input(gridCellAddressSchema).mutation(async ({ input, ctx }) => { + await copyGridCell((ctx as RouterContext).sessionId, input); + }), getCurrentPageAsTree: publicProcedureWithTelemetry // procedure type .query(async ({ ctx }) => { diff --git a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.test.tsx b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.test.tsx index 6cf9cca7f..bd013315a 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 ad073e6b5..9f8248cb3 100644 --- a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.tsx +++ b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTable.tsx @@ -8,7 +8,14 @@ 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 GridCellAddress, + type TableCellAddress, + type TablePage, + type TableRow, +} from '../../../../../utils/documentGrid/types'; import { CollectionViewContext } from '../../collectionViewContext'; import './dataGridTheme.scss'; import './dataViewPanelTable.scss'; @@ -16,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 { @@ -29,6 +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 copyValue?: (address: GridCellAddress) => void; } export interface DataViewPanelTableFocusRequest { @@ -41,8 +49,15 @@ 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({ @@ -54,6 +69,7 @@ export function DataViewPanelTable({ columnWidthCache, widthScope, focusRequest, + copyValue, }: DataViewPanelTableProps): React.JSX.Element { const [currentContext] = React.useContext(CollectionViewContext); const gridRef = React.useRef(null); @@ -98,7 +114,8 @@ export function DataViewPanelTable({ if ( focusRequest === undefined || handledFocusRequestRef.current === focusRequest || - focusRequest.page !== page + focusRequest.page !== page || + page.columns.length === 0 ) { return; } @@ -224,15 +241,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 ; @@ -270,28 +291,25 @@ 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 => ( - { - 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 address = copyValue && tableCellAddress(page, props.row, props.column.idx); + return ( + { + 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/components/resultsTab/DataViewPanelTree.focus.test.tsx b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.focus.test.tsx index 2b639dd4b..deb982222 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,123 @@ 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', + }); + vi.useFakeTimers(); + try { + act(() => { + focused.blur(); + window.dispatchEvent(new FocusEvent('focus')); + vi.advanceTimersByTime(0); + }); + expect(document.activeElement).toBe(focused); + } finally { + vi.useRealTimers(); + } + await act(async () => rootField.click()); + expect(clicked.isConnected).toBe(false); + }); + + it('restores the keyboard menu cell only if the workbench leaves focus on the body', async (): Promise => { + await act(async () => + root.render( + , + ), + ); + const cell = gridCell(3, 2); + const openKeyboardMenu = (): void => { + cell.focus(); + cell.dispatchEvent( + new KeyboardEvent('keydown', { key: 'F10', shiftKey: true, bubbles: true, cancelable: true }), + ); + cell.blur(); + }; + const returnFromMenu = (): void => { + window.dispatchEvent(new FocusEvent('focus')); + vi.advanceTimersByTime(0); + }; + + vi.useFakeTimers(); + try { + act(() => { + openKeyboardMenu(); + expect(document.activeElement).toBe(document.body); + returnFromMenu(); + }); + expect(document.activeElement).toBe(cell); + + const outside = document.createElement('button'); + host.appendChild(outside); + act(() => { + openKeyboardMenu(); + outside.focus(); + returnFromMenu(); + }); + expect(document.activeElement).toBe(outside); + } finally { + vi.useRealTimers(); + } + }); + }); + 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..95bf0ebc5 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,20 @@ 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 +109,22 @@ export const DataViewPanelTree = ({ nodes, columnResizeSessionId }: DataViewPane ) : (