diff --git a/.github/skills/accessibility-aria-expert/SKILL.md b/.github/skills/accessibility-aria-expert/SKILL.md index 6c54a7d46..7ce7a3cb5 100644 --- a/.github/skills/accessibility-aria-expert/SKILL.md +++ b/.github/skills/accessibility-aria-expert/SKILL.md @@ -321,6 +321,16 @@ import { Announcer } from '/components/accessibility'; - **Condition resets automatically** - when `when` goes back to `false`, it's ready for the next announcement - **Prefer 'assertive'** for user-initiated actions, 'polite' for background updates +## Known VS Code-Owned Behavior + +**F6 / Shift+F6 stays inside a webview tab (#769).** This is a VS Code 1.147 workbench +defect, not ours: the webview overlay can lose its link to the editor area +(`data-parent-flow-to-element-id=""`), so F6 refocuses the same webview. It reproduces with +the built-in Markdown Preview, and switching tabs repairs it. Do not add an F6 handler, force +focus, or remove the Monaco focus-trap bumper for it. See +`docs/ai-and-plans/features/accessibility/iterations/02-f6-webview-trap-investigation.md` +and decision 0013. + ## Quick Checklist - [ ] Icon-only buttons have `aria-label` diff --git a/build/verification/README.md b/build/verification/README.md index 5c87bfe9f..8c8a090c3 100644 --- a/build/verification/README.md +++ b/build/verification/README.md @@ -363,7 +363,8 @@ The serve-only [Vite plugin](../vite/webview-scenarios.mjs) lists every No scenario or helper URL uses query strings, which remote port forwarding mangles. Nothing is added to production bundles or the packaged-VSIX L2 gate. -[Scenarios](./browser/scenarios.ts) import all six L2 fixtures as `default`, plus nine Local Quick +[Scenarios](./browser/scenarios.ts) import all six L2 fixtures as `default`, add `add` and `view` +Document View focus scenarios, plus nine Local Quick Start states: `introduction`, `configure`, `provisioning`, `success`, `failed-port-in-use`, `failed-timeout`, and `docker-missing-windows`, `docker-missing-mac`, `docker-missing-linux`; and nineteen connection diagnosis states beside its connected `default`: `running` (rows 1–3 diff --git a/build/verification/browser/contrast-matrix-bootstrap.mjs b/build/verification/browser/contrast-matrix-bootstrap.mjs new file mode 100644 index 000000000..a5c9c57d8 --- /dev/null +++ b/build/verification/browser/contrast-matrix-bootstrap.mjs @@ -0,0 +1,17 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { FluentProvider } from '@fluentui/react-components'; +import '@vitejs/plugin-react/preamble'; +import React from 'react'; +/* eslint-disable import/no-internal-modules -- This dev-only bootstrap imports the exact implementation and styles under evaluation. */ +import 'react-data-grid/lib/styles.css'; +import { createRoot } from 'react-dom/client'; +import { MetricCard } from '../../../packages/vscode-ext-webview-fluentui/src/components/MetricGrid/MetricCard.tsx'; +import { createVSCodeFluentTheme } from '../../../packages/vscode-ext-webview-fluentui/src/theme/core/createVSCodeFluentTheme.ts'; +import { TypedValueCell } from '../../../src/webviews/documentdb/collectionView/components/resultsTab/TypedValueCell.tsx'; +import '../../../src/webviews/documentdb/collectionView/components/resultsTab/dataGridTheme.scss'; + +export { createRoot, createVSCodeFluentTheme, FluentProvider, MetricCard, React, TypedValueCell }; diff --git a/build/verification/browser/scenarios.test.ts b/build/verification/browser/scenarios.test.ts index 0c6da60c5..7678390e2 100644 --- a/build/verification/browser/scenarios.test.ts +++ b/build/verification/browser/scenarios.test.ts @@ -578,8 +578,8 @@ describe('L2-dev manifest and routes', (): void => { it('round-trips every scenario and theme, without duplicate routes', (): void => { const routes = scenarioRoutes(); - expect(routes).toHaveLength(222); - expect(new Set(routes.map((route): string => route.path)).size).toBe(222); + expect(routes).toHaveLength(228); + expect(new Set(routes.map((route): string => route.path)).size).toBe(228); for (const route of routes) expect(parseScenarioRoute(route.path)).toEqual(route); }); @@ -678,13 +678,28 @@ describe('L2-dev manifest and routes', (): void => { expect(notFound).toContain('high-contrast'); }); + it.each(['add', 'view'] as const)('covers Document %s initial focus in every theme', (mode): void => { + const routes = scenarioRoutes().filter( + (route): boolean => route.view === 'documentView' && route.scenario === mode, + ); + expect(routes.map((route) => route.theme)).toEqual(['dark', 'light', 'high-contrast']); + expect(scenarios.documentView[mode].config.mode).toBe(mode); + expect(scenarios.documentView[mode].assertions).toContainEqual( + expect.objectContaining({ + kind: 'attribute', + attribute: 'data-fui-focus-visible', + expected: '', + }), + ); + }); + it('escapes diagnostic HTML and lists all routes', (): void => { expect(scenarioIndex('')).not.toContain(' + + + +
+

DocumentDB Table contrast matrix

+

+ First-pass comparison for #775, #382, #771 and the focused Table-row text in #778. Every theme panel + uses CSS variables captured from an installed VS Code 1.147.0 webview. Ratios are calculated from those + theme definitions and this branch's styles, compositing alpha before WCAG luminance; they are not + measured in an installed Collection View. +

+

+ Probe basis: Light 2026, Dark 2026, Default High Contrast and Default High Contrast Light; no + workbench.colorCustomizations. The focus samples use the branch's + dataGridTheme.scss plus react-data-grid 7.0.0-beta.64 CSS. Hover is intentionally absent. + HC panels are not forced-colors emulation. +

+
+

Explore opacity and focus-ring weight

+

+ Adjust a slider to update every theme panel and its calculated ratios. These controls are only for + exploring the captured theme definitions; they do not change VS Code settings or product code. +

+
+
+
+ + 40% +
+ + Pre-change value: 40% (now 80%, decision 0012). The solid candidate inherits the row foreground. +
+
+
+ + 60% +
+ + + Pre-change value: 60% (now solid descriptionForeground, decision 0011). Compare a + solid Fluent token and a solid VS Code descriptionForeground token. + +
+
+
+ + 2px +
+ + + Contrast ratio does not change with width. Two-tone remains 1px + 1px to compare the VS Code + and Fluent colors at the current Fluent-like 2px total weight. + +
+
+ +

+
+
+

What the guidelines require

+
+
+ + + WCAG 2.2 SC 1.4.3 · text + + — 4.5:1 + +

+ Normal-size text must reach 4.5:1; only large text gets 3:1. The small + Ab marker and literal { } type glyph are treated as text here, so + use 4.5:1. +

+ + WCAG says not to round before deciding pass/fail; the matrix compares full precision and + rounds only the displayed ratio. + +
+
+ + + WCAG 2.2 SC 1.4.11 · non-text + + — 3:1 + +

+ Meaningful icons and visual component/state indicators need 3:1 against adjacent colors. + This is the basis for the info icon and focus-indicator target. +

+
+
+ + + WCAG 2.2 SC 2.4.13 · focus appearance (AAA) + + +

+ In addition to 3:1 focused-vs-unfocused contrast on the same pixels, the visible indicator + needs area at least equal to a 2 CSS-pixel perimeter. Width alone does not prove a pass. + Fluent's + createFocusOutlineStyle uses a 2px border with colorStrokeFocus2; + its forced-colors rule uses the system Highlight color, which this page does + not emulate. +

+
+
+
+
+

What the issues and closeout notes asked to verify

+
+
+ #775 · Table focus outline +

+ Original report: about 1.948:1 in Light 2026 and 1.857:1 in Dark 2026; expected at least + 3:1. It suggests a contrasting 2px+ outline or outline plus shadow. +

+ + Closeout asks for the actual keyboard indicator against adjacent colors on header/body cells + and selected rows, pointer away from hover, plus an installed Windows contrast theme. Keep + measured values/screenshots; a keyboard journey or forced-colors emulation alone is not + enough. This is parked until the grid update lands. + +
+
+ #382 · “Ab” marker text +

+ Original report: 2.8479:1 against a 4.5:1 expectation. The request is to retest the actual + type-marker text at 4.5:1, including focused/selected states where relevant. +

+ + The closeout notes that announcing the type does not fix visual contrast; a badge is parked, + and no new tooltip or unique CodeWithScope symbol is needed for this criterion. + +
+
+ #771 · Info and { } glyphs +

+ The info icon indicates tooltip availability and is expected to reach 3:1. The issue also + flags the Table { } icon as a similar symptom. +

+ + Closeout asks to keep both non-text checks (3:1) in Light/Dark 2026 without assuming one + root cause. #382 separately owns the Ab text check at 4.5:1. + +
+
+ #778 · Focused Table-row text symptom +

+ The original issue is primarily the native Connection String Quick Pick (reported around + 3.44:1 Light / 3.20:1 Dark). Separately, it notes focused Table-row text below 4.5:1 in Dark + 2026. +

+ + Closeout keeps the Quick Pick with upstream VS Code (microsoft/vscode#325289) and requests an independent installed-Table retest against the real focused-row + background after the grid update. This row-text symptom is distinct from #775's outline. + +
+
+
+
+

Loading captured themes and branch styles…

+
+

+ Green/red status is accompanied by an explicit ratio and threshold. Single-color focus previews use the + width slider; “two-tone” stays 1px VS Code focusBorder plus 1px Fluent focus2. The query icon and Fluent + focus tokens come from the extension's actual Fluent theme factory. Hover and Windows forced-colors are + not simulated. +

+
+ + + diff --git a/docs/ai-and-plans/features/accessibility/theme-captures/probe-extension/extension.js b/docs/ai-and-plans/features/accessibility/theme-captures/probe-extension/extension.js new file mode 100644 index 000000000..a3eca51ef --- /dev/null +++ b/docs/ai-and-plans/features/accessibility/theme-captures/probe-extension/extension.js @@ -0,0 +1,74 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// Development-only probe. It opens one webview and writes the `--vscode-*` CSS variables that +// VS Code injects into that webview, together with the theme kind and the media-query flags, +// to `$PROBE_OUT/.json`, then writes `.done`. +// It is loaded with `--extensionDevelopmentPath` by `../capture-themes.mjs`; it is never packaged. + +const vscode = require('vscode'); +const fs = require('fs'); +const path = require('path'); + +function html() { + return `

probe

`; +} + +exports.activate = function activate(context) { + const outDir = process.env.PROBE_OUT; + const label = process.env.PROBE_LABEL; + if (!outDir || !label) { + throw new Error('PROBE_OUT and PROBE_LABEL must be set (see capture-themes.mjs).'); + } + + const panel = vscode.window.createWebviewPanel('a11yThemeProbe', 'probe', vscode.ViewColumn.One, { + enableScripts: true, + }); + panel.webview.html = html(); + panel.webview.onDidReceiveMessage((msg) => { + const wb = vscode.workspace.getConfiguration('workbench'); + const win = vscode.workspace.getConfiguration('window'); + const out = { + label, + vscodeVersion: vscode.version, + appName: vscode.env.appName, + configuredTheme: wb.get('colorTheme'), + preferredLight: wb.get('preferredLightColorTheme'), + preferredDark: wb.get('preferredDarkColorTheme'), + activeColorThemeKind: vscode.window.activeColorTheme.kind, + colorCustomizations: wb.inspect('colorCustomizations'), + iconTheme: wb.get('iconTheme'), + autoDetectColorScheme: win.get('autoDetectColorScheme'), + autoDetectHighContrast: win.get('autoDetectHighContrast'), + ...msg, + }; + fs.writeFileSync(path.join(outDir, `${label}.json`), JSON.stringify(out, null, 2)); + fs.writeFileSync(path.join(outDir, `${label}.done`), 'ok'); + }); + context.subscriptions.push(panel); +}; diff --git a/docs/ai-and-plans/features/accessibility/theme-captures/probe-extension/package.json b/docs/ai-and-plans/features/accessibility/theme-captures/probe-extension/package.json new file mode 100644 index 000000000..8067d8397 --- /dev/null +++ b/docs/ai-and-plans/features/accessibility/theme-captures/probe-extension/package.json @@ -0,0 +1,14 @@ +{ + "name": "documentdb-a11y-theme-probe", + "displayName": "DocumentDB a11y theme probe (development only)", + "publisher": "local", + "version": "0.0.1", + "private": true, + "engines": { + "vscode": "^1.100.0" + }, + "main": "./extension.js", + "activationEvents": [ + "onStartupFinished" + ] +} diff --git a/docs/ai-and-plans/features/accessibility/theme-captures/type-marker-proposals.html b/docs/ai-and-plans/features/accessibility/theme-captures/type-marker-proposals.html new file mode 100644 index 000000000..30b47bf81 --- /dev/null +++ b/docs/ai-and-plans/features/accessibility/theme-captures/type-marker-proposals.html @@ -0,0 +1,515 @@ + + + + + + DocumentDB Table type-marker proposals + + + + +
+

Table type-marker proposals

+

+ Covers the Ab marker (#382) and the { } glyph (#771). Both are the same + TypedValueCell span, at font-size: smaller; its opacity was 0.4 and + is 0.8 since decision 0012. Each column below sets its own opacity. + Ratios are calculated from theme definitions (VS Code 1.147.0 captures, no color + customizations) and this branch's real component; they are not measured in an installed VS Code. +

+
+

+ Target: 4.5:1, WCAG 2.2 SC 1.4.3. The marker is small text that tells the user the + value's type, so the large-text and incidental exceptions do not apply. The target holds in every + row state, hover included. +

+

+ Already settled: Table focus ring = Fluent colorStrokeFocus2, 2px. Query Insights info + icon = descriptionForeground. Opacity is composited over the row background before the + ratio is computed. Hover is shown as a static preview. +

+
+
+
+ + + 80% +
+

Updates the “Your value” column and its summary row.

+
+
+

Worst case across all four themes and row states

+
+
+

Loading captured themes…

+

+ Forced colors is not emulated. With any opacity below 1, Windows forced colors still dims the system + text color, as it does today at 40%. +

+
+ + + diff --git a/docs/ai-and-plans/features/data-grid/README.md b/docs/ai-and-plans/features/data-grid/README.md index d92a5822d..601d628f6 100644 --- a/docs/ai-and-plans/features/data-grid/README.md +++ b/docs/ai-and-plans/features/data-grid/README.md @@ -32,6 +32,8 @@ released extension version or completion of the remaining handover gates. arbitrary-depth document model rather than using RDG's `TreeDataGrid`. - Mouse Back inside a nested Table result steps up one embedded-object level, like Level Up. It does not change result pages; root-level, other views and other mouse buttons are unchanged. +- Plain Backspace on a nested Table cell or header also steps up one level. From a cell, focus + returns to the same document's object cell when available; from a header, it stays on the header row. - Results Tree and Indexes share `ExpandCollapseButton`, a compact Fluent-tree-style rotating chevron. Tree keeps cell-owned keyboard focus; Indexes keeps a normally tabbable button. - Each Tree depth adds Fluent's `spacingHorizontalXXL` (24 px), independent of the font; leaves diff --git a/docs/ai-and-plans/features/data-grid/decisions.md b/docs/ai-and-plans/features/data-grid/decisions.md index c7a4087ec..c1f4403f7 100644 --- a/docs/ai-and-plans/features/data-grid/decisions.md +++ b/docs/ai-and-plans/features/data-grid/decisions.md @@ -20,6 +20,7 @@ implementation remains subject to the planned work items and later gates. | 0006 | UX review: sizing gate, previews, copy and hover | Accepted | Sizing accepted; native platform Copy clarified | 2026-11-30 | #1142 | | 0007 | Column-width hold release and width scope | Accepted | Remount by scope rejected; frozen widths deferred | 2026-12-01 | #1142 | | 0008 | Position-based Tree node keys | Accepted | Replaces document-identity-based Tree keys | 2026-12-01 | #1142 | +| 0009 | Header-menu column sizing without dragging | Accepted | Fit uses RDG's double-click; Tree keeps auto sizing | 2026-12-02 | #1147 | ## 0001 - React Data Grid, beta candidate and document tree @@ -325,3 +326,53 @@ field/path order, preorder, and the array expansion bound remain unchanged. This approval is recorded as WI-R1/C4 option A in the [Copilot PR review triage table](./iterations/08-copilot-pr-review-triage.md#operator-decisions-2026-12-01). + +## 0009 - Header-menu column sizing without dragging + +**Status:** Accepted · **Date:** 2026-12-02 + +### Question + +[#776](https://github.com/microsoft/vscode-documentdb/issues/776) needs column resizing in +Table and Tree with a single pointer, without dragging or a physical keyboard. How should +**Size Column to Fit** measure the content, and how much of Table's width policy should Tree +share? + +### Decision + +- **Native header menu.** **Set Column Width…** and **Size Column to Fit** are host commands + under `webview/context`. Each header gets its scoped `data-vscode-context` in a capture-phase + `contextmenu` listener, because RDG virtualizes headers. Collection View's context-menu + suppression exempts stamped headers, since VS Code ignores a prevented `contextmenu` event. +- **Set Column Width…** uses a VS Code input box prefilled with the rendered width. It accepts + the column minimum up to 2000 px and stores `{ type: 'resized', width }` for that column only. +- **Size Column to Fit uses RDG's own fit.** It sends a synthetic `dblclick` to the header's + `.rdg-resize-handle`, so RDG fits the column to `max-content` and reports a `resized` width. + It fits **rendered rows only**. The operator chose this for minimal code and accepted the + dependence on scroll position. +- **Tree keeps RDG's automatic sizing.** Tree has three columns and holds only explicit + overrides in a plain `columnWidths` map. It does not use Table's 320 px cap, fill or holds. +- **Focus.** After a command, and when the webview regains focus after the menu closed with + `body` active, focus returns to the invoking header. A later click on a data cell may need + a second click; the operator accepted this. + +Rejected alternatives: + +- **Measuring every loaded row ourselves** with canvas text metrics. It included offscreen + rows, but added measurement code that had to mirror cell fonts, padding and type glyphs. +- **Deleting the width override to refit,** as Cosmos DB's Query Editor does. That is reset to + automatic, which belongs to [#1161](https://github.com/microsoft/vscode-documentdb/issues/1161), + and the result is not fixed when the pane resizes. +- **A Fluent menu and dialog in the webview.** Decision 0002 requires native menus. +- **Sharing `useStableColumnWidths` with Tree.** It imposed Table's automatic-width policy. + +Recheck the synthetic double-click and the header DOM on any RDG upgrade; see +[#1151](https://github.com/microsoft/vscode-documentdb/issues/1151#issuecomment-7349846705). + +### Evidence + +- `DataViewPanelTable.test.tsx` and `DataViewPanelTree.test.tsx` cover exact width, Cancel, + one handle `dblclick` per fit, stable neighbors, pane-resize stability, menu context on a + 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. diff --git a/docs/ai-and-plans/features/data-grid/design.md b/docs/ai-and-plans/features/data-grid/design.md index f96d1558e..95d70cd5b 100644 --- a/docs/ai-and-plans/features/data-grid/design.md +++ b/docs/ai-and-plans/features/data-grid/design.md @@ -64,7 +64,7 @@ the successful response matching the current query, request, and destination pat once, after the Table page is committed, to column 0—the same row's root `_id` cell—using its `rowKey`, not its previous column or numeric index. It does not select the row. -The pending focus restoration is permanently cancelled if focus leaves the initiating results +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 @@ -77,6 +77,12 @@ the current field path is nested. Capture-phase handling keeps that gesture out mouse handlers; its matching release and auxiliary click are consumed even after reaching root. Other mouse buttons, result paging, other views and input outside the results area are unchanged. +Plain Backspace from a focused cell or column header in a nested Table invokes Level Up once per +press. Key repeats, modified keys, editing, and keys already handled by a popup do not navigate. +On the matching parent page, a cell returns to the exited object on the same row, then falls back +to that row's `_id`, the first row's `_id`, or a header if there are no rows. A header stays in +the header row. Focus is not restored if the user moved it while the page was loading. + Long cell values ellipsize independently of the BSON type indicator; the full value text remains in the DOM, with no additional per-cell Tab stop. For defined values, visually hidden text puts the full BSON type before the value in the focused cell's accessible name, for example diff --git a/docs/ai-and-plans/features/query-playground/README.md b/docs/ai-and-plans/features/query-playground/README.md index a51e8e95c..ef75eb70d 100644 --- a/docs/ai-and-plans/features/query-playground/README.md +++ b/docs/ai-and-plans/features/query-playground/README.md @@ -31,10 +31,14 @@ sibling areas [interactive-shell](../interactive-shell/README.md) and - `src/documentdb/playground/**` — the playground service, evaluation, result rendering, type definitions, and the TypeScript server plugin - `src/commands/playground/**` — commands, including the Connect picker +- Playground result lifecycle is shared by the run commands, with `documentDB.playground.afterRun` + resolved separately for screen-reader shortcut invocations and other entry points. ## User docs - [docs/user-manual/query-playground.md](../../../user-manual/query-playground.md) +- [docs/user-manual/accessibility.md](../../../user-manual/accessibility.md) — keyboard entry + points, focus commands, and the after-run setting - [docs/user-manual/query-runtime.md](../../../user-manual/query-runtime.md) — including "Running Several Sessions at Once", which is the source of truth for the per-cluster worker behavior that [multi-connection-behavior.md](./multi-connection-behavior.md) used to hold @@ -55,6 +59,10 @@ sibling areas [interactive-shell](../interactive-shell/README.md) and and well formatted instead of ad-hoc. - **The name is "Query Playground".** "Scrapbook" and "scratchpad" were removed everywhere, including command ids, language ids, folder names, and webpack entry points. +- **Accessibility actions use standard VS Code surfaces.** CodeLens remains available for mouse + users; palette, title, overflow and context-menu entry points do not require new default + shortcuts. The after-run behavior is defined by + [accessibility decision 0004](../accessibility/decisions.md#0004--after-a-run-focus-moves-to-the-result-only-in-screen-reader-mode). ## Timeline @@ -80,6 +88,9 @@ the constraints and design forks behind connection persistence are in ## Open gaps +- **Result navigation after first save or Save As** ([#1172](https://github.com/microsoft/vscode-documentdb/issues/1172), + `wontfix`): an open result keeps its original source URI. Rerun from the saved Playground to + restore both focus commands for that file. Ordinary saves to the same URI are unaffected. - [future-work.md](./future-work.md) — deferred playground enhancements - [future-work-aggregation-pipeline.md](./future-work-aggregation-pipeline.md) — the aggregation pipeline editor and its completion provider, scoped as a separate work item diff --git a/docs/index.md b/docs/index.md index 0a2f4ef79..6fae58758 100644 --- a/docs/index.md +++ b/docs/index.md @@ -81,6 +81,10 @@ The User Manual provides guidance on using the extension. It contains detailed d - [AI Performance Insights: Model and Billing](./user-manual/ai-utility-model) +### Accessibility + +- [Accessibility](./user-manual/accessibility) + ## Release Notes Explore the history of updates and improvements to the extension. Each release brings new features, enhancements, and fixes to improve your experience. diff --git a/docs/user-manual/accessibility.md b/docs/user-manual/accessibility.md new file mode 100644 index 000000000..f43c17897 --- /dev/null +++ b/docs/user-manual/accessibility.md @@ -0,0 +1,112 @@ +--- +title: 'Accessibility' +parent: 'User Manual' +nav_order: 5 +--- + +# Accessibility + +This page collects accessibility behavior and related settings available in the DocumentDB extension for Visual Studio Code. +Screen-reader output can vary by screen reader and VS Code configuration. + +## Keyboard access + +The [Query Playground](./query-playground) keeps its CodeLens actions for mouse users and also +exposes them through standard VS Code surfaces: + +| Action | Command Palette | Editor title or overflow menu | Editor context menu | +| ----------------------------- | --------------- | ----------------------------- | ------------------- | +| Connect or change connection | Yes | **Playground Connection…** | No | +| Run All | Yes | Yes, in the title | No | +| Run Block | Yes | Yes, in the overflow menu | Yes | +| Open Block in Shell | Yes | Yes, in the overflow menu | Yes | +| Open Block in Collection View | Yes | Yes, in the overflow menu | Yes | +| Focus Result | Yes | No | No | + +Open the Command Palette and search for **Query Playground**. Open the editor context menu with +`Shift+F10` or the Menu key. Block actions use the block containing the cursor; on a blank line, +they fall back to the nearest preceding block. **Open Block in Shell** and **Open Block in +Collection View** require a connected playground and a block containing code. The title +overflow lists both actions and checks those requirements when you invoke them. A collection +can only be inferred from compatible code. + +The existing run shortcuts remain `Ctrl+Enter` for Run Block and `Ctrl+Shift+Enter` for Run All; +use `Cmd` instead of `Ctrl` on macOS. There are no default shortcuts for Connect, Shell, +Collection View, or the focus commands. You can assign your own VS Code keybindings. + +The palette commands **Query Playground: Focus Result** and **Query Playground: Focus Playground** +move between an open result and its source playground. They are available without a default +keybinding. + +After saving an untitled Playground for the first time or using **Save As**, rerun the query +from the saved file to open a result tab linked to it. The original result tab stays open +but is not relinked. An ordinary save keeps the existing result association. + +## Screen readers + +`documentDB.playground.afterRun` controls what happens after a successful Query Playground run. +Its default is `auto`. + +| Value | Run from the screen-reader shortcut contribution | Any other run | +| ---------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `auto` (default) | Move focus to the result | Stay in the playground | +| `stay` | Stay in the playground | Stay in the playground | +| `focusResult` | Move focus to the result | Move focus to the result | +| `notify` | Stay in the playground and show a completion notification with a **Focus Result** button | Stay in the playground and show a completion notification with a **Focus Result** button | + +Automatic screen-reader focus applies only to the `Ctrl/Cmd+Enter` and +`Ctrl/Cmd+Shift+Enter` contributions while VS Code's `accessibilityModeEnabled` context is active. +Runs from ordinary shortcuts, CodeLens, the Command Palette, the editor title, or the editor +context menu do not carry the screen-reader flag. An explicit `stay`, `focusResult`, or `notify` +value overrides `auto` for every entry point. + +Each successful run has exactly one after-run outcome. `notify` describes the result count or type +(or that there is no return value) plus **Focus Result**; it does not also move focus +automatically. Errors keep the existing error notification. Cancelled runs do not show a completion +notification. + +Status announcements are used for Query Insights actions, index-management refreshes, and +connection-diagnostics progress and results. In the Document editor and Collection View's JSON +editor, `Escape` leaves the embedded editor when no suggestion or snippet session is handling the +key. This is not a blanket Escape behavior for every editor or webview. + +The Documents tree item exposes the visible **Documents** label as its accessibility label while +retaining its hover tooltip. + +## Interactive Shell + +Set `documentDB.shell.display.colorSupport` to `false` for plain shell syntax and result output +without ANSI colors. The default is `true`. Shell action links are underlined even when color +support is off, so they do not rely on color alone. + +This is not a claim that the terminal is fully accessible. In particular, the broader Interactive +Shell terminal accessibility pass is still tracked by +[#941](https://github.com/microsoft/vscode-documentdb/issues/941). + +## Settings reference + +| Setting | Default | Effect | +| ------------------------------------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `documentDB.playground.afterRun` | `auto` | Controls focus or notification behavior after a successful playground run as described above. | +| `documentDB.shell.display.colorSupport` | `true` | Enables ANSI syntax and result colors in the Interactive Shell. Set it to `false` for plain output. | +| `documentDB.accessibility.hideCountPrefix` | `false` | Removes the two-dot visual separator before database, collection, index, and Kubernetes namespace counts. The counts remain visible. | + +## Known limitations and reporting + +- See [Collection View navigation](./collection-view-querying#navigating-nested-results) + for Table and Tree keyboard controls, including **Enter** to step into an object + and **Backspace** to step out in Table. The grid and contrast changes in + [#1147](https://github.com/microsoft/vscode-documentdb/pull/1147) await accessibility-tester verification. +- If **F6** or **Shift+F6** stays in a webview instead of moving to another VS Code + area, **switch to another editor tab and back**, then retry. This VS Code behavior + also occurs in the built-in Markdown Preview; the extension does not override F6. + See the [reproduction and explanation on #769](https://github.com/microsoft/vscode-documentdb/issues/769#issuecomment-7361365705). +- The native Quick Pick contrast symptoms in + [#767](https://github.com/microsoft/vscode-documentdb/issues/767) and + [#778](https://github.com/microsoft/vscode-documentdb/issues/778) are tracked upstream in + VS Code. + +Report accessibility problems in the +[DocumentDB extension issue tracker](https://github.com/microsoft/vscode-documentdb/issues). +When a report assigns closure to TCS/C+AI accessibility testers, source changes and automated +checks do not close it; those testers retain closure ownership. diff --git a/docs/user-manual/collection-view-querying.md b/docs/user-manual/collection-view-querying.md index 0bc7451e9..0feef05c8 100644 --- a/docs/user-manual/collection-view-querying.md +++ b/docs/user-manual/collection-view-querying.md @@ -243,10 +243,12 @@ This is a significant improvement over earlier versions of the extension, which In **Table View**, focus an object cell and press **Enter**, or double-click the cell, to step into that field. After **Enter**, focus moves to the same document row's `_id` cell, so you can continue -with the arrow keys or press **Space** to select that row. Mouse step-in is unchanged. Use -**Level Up** to return one level, activate an ancestor breadcrumb to jump back to it, or choose -**Root Level** to return to the document root. The help beside the navigation controls describes -these actions. +with the arrow keys or press **Space** to select that row. To return one level, press +**Backspace** on a cell or column header in a nested table, or use **Level Up**. After +**Backspace** from a cell, focus returns to the object cell in the same document if available, +or to another cell in the grid. From a column header, focus stays in the header row. Activate an +ancestor breadcrumb to jump back to it, or choose **Root Level** to return to the document root. +The help beside the navigation controls describes the breadcrumb and Level Up actions. In **Tree View**, focus an expandable **Field** cell and press **Enter** to expand or collapse it. The chevron button beside the field also toggles expansion. New results start collapsed. If a @@ -277,17 +279,31 @@ To suppress row hover highlights in Table and Tree, enable `documentDB.accessibility.disableHighlightOnHover` and reopen Collection View. Reduced motion also suppresses these highlights, even when the setting is off. Focus and selection remain visible. -### Table Column Widths +### Results Column Widths -Drag a column header edge to choose its width. Neighboring columns stay still during the drag; -automatic columns can reflow when the pane changes width, while manually resized columns stay -fixed. Spare space is shared among automatic columns when they fit. An all-manual layout may -leave unused space. +In Table and Tree, drag a column header edge to choose its width. With a header focused, you can +also use **Ctrl+Arrow Left** or **Ctrl+Arrow Right** (**Cmd+Arrow** on macOS), or double-click the +resize handle to fit the visible content. -Manual widths are remembered for each inspected Table path while Collection View stays open, -including across pages and Tree/JSON view switches. Returning to a path restores its manual -widths. Running a different query or closing the panel clears them; automatic widths are -measured again for the available pane. +For a single-pointer or keyboard-only alternative, open the focused column header's context menu +with a pointer, the **Context Menu** key, or **Shift+F10**, then choose: + +- **Set Column Width…** to enter an exact width in pixels: 50–2000 in Table, 100–2000 in Tree. + The prompt starts with the column's current rendered width. Cancel leaves the layout unchanged. +- **Size Column to Fit** to fit the header and the values currently rendered in that column, like + double-clicking the column edge. This uses no new database query and is not limited to Table's + 320 px automatic width. + +Both menu actions apply only to the selected column and store an explicit width. Automatic columns +can reflow when the pane changes width, while explicitly resized or content-fitted columns stay +fixed. In Table, neighboring columns stay still during pointer resizing, spare space is shared +among automatic columns when they fit, and an all-manual layout may leave unused space. Tree +automatic columns keep normal automatic sizing. + +Table manual widths are remembered for each inspected Table path while Collection View stays open, +including across pages and Table/Tree/JSON view switches. Running a different query or closing the +panel clears them; automatic widths are measured again for the available pane. Tree manual widths +last while the Tree view stays open and are not remembered across view switches. ## Navigating to Other Features diff --git a/docs/user-manual/interactive-shell.md b/docs/user-manual/interactive-shell.md index 09ca684ab..cbfe35af9 100644 --- a/docs/user-manual/interactive-shell.md +++ b/docs/user-manual/interactive-shell.md @@ -33,7 +33,10 @@ There are several ways to open an Interactive Shell session: 1. **From the tree view**: Right-click a cluster, database, or collection node in the Connections, Discovery, or Azure views, then select **Open Interactive Shell**. 2. **From the inline button**: Click the terminal icon (rightmost icon) next to a database or collection node in the tree view. 3. **From the Collection View**: Use the **Open in Shell** toolbar button to export your current find query into a new shell session. -4. **From the Query Playground**: Use a CodeLens link to launch a shell for the same connection. +4. **From the Query Playground**: Use a CodeLens link, the Command Palette, the editor title + overflow, or the editor context menu to run **Open Block in Shell**. The playground must be + connected and the block at the cursor (or nearest preceding block on a blank line) must contain + code. See [Accessibility](./accessibility) for the complete keyboard workflow.

Inline action buttons on a collection node: Open Collection View, New Query Playground, Open Interactive Shell

@@ -152,7 +155,9 @@ The shell colorizes your input in real time as you type: | Gray | Comments | | Red | Regex literals (and unterminated string errors) | -Syntax highlighting can be disabled via the `documentDB.shell.display.colorSupport` setting for accessibility (screen readers) or piped output. +Set `documentDB.shell.display.colorSupport` to `false` for plain output. Shell links stay +underlined when colors are disabled. See [Accessibility](./accessibility#interactive-shell) for the +documented accessibility behavior and caveats. ## Cursor Iteration @@ -213,7 +218,9 @@ The Interactive Shell is connected to the other query surfaces in the extension: - **To Collection View**: Click the `↗ Collection View` link that appears after query results. - **To Query Playground**: Click the `↗ Query Playground` link that appears after query results to open a playground for the same collection. - **From the Collection View**: The Collection View toolbar has an **Open in Shell** button that pre-feeds your current find query into a new shell session. -- **From the Query Playground**: CodeLens links let you launch a shell from within your script. +- **From the Query Playground**: CodeLens or the keyboard-reachable **Open Block in Shell** + command launches a shell from the block at the cursor, with the preceding-block fallback on a + blank line. For more details on the Query Playground, see the [Query Playground](./query-playground) documentation. @@ -223,14 +230,14 @@ Open VS Code Settings and expand **Extensions** > **DocumentDB**. The display an options are under **Interactive Shell**. The shared connection timeout is under **Connections & Discovery**, and the shared batch size is under **Queries & Results**. You can also search for a setting ID from the table. -| Setting | Default | Description | -| ----------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------ | -| `documentDB.connectionTimeout` | `30` | Maximum time (in seconds) to wait for the shell to connect and authenticate (shared with Query Playground) | -| `documentDB.shell.display.colorSupport` | `true` | Enable ANSI color support for syntax highlighting and formatted output. Disable for screen readers or piped output | -| `documentDB.shell.display.autocompletion` | `true` | Tab completion, the candidate list, and the dim inline suggestions at the cursor | -| `documentDB.shell.display.inlineHints` | `true` | The informational hints marked with 🛈, which are never inserted into your input | -| `documentDB.shell.multiLinePasteBehavior` | `ask` | Controls how multi-line text is handled when pasted into the shell | -| `documentDB.batchSize` | `50` | Number of documents to display per cursor iteration (shared with Query Playground) | +| Setting | Default | Description | +| ----------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------ | +| `documentDB.connectionTimeout` | `30` | Maximum time (in seconds) to wait for the shell to connect and authenticate (shared with Query Playground) | +| `documentDB.shell.display.colorSupport` | `true` | Controls ANSI colors and plain shell output; see [Accessibility](./accessibility#interactive-shell) for the supported behavior | +| `documentDB.shell.display.autocompletion` | `true` | Tab completion, the candidate list, and the dim inline suggestions at the cursor | +| `documentDB.shell.display.inlineHints` | `true` | The informational hints marked with 🛈, which are never inserted into your input | +| `documentDB.shell.multiLinePasteBehavior` | `ask` | Controls how multi-line text is handled when pasted into the shell | +| `documentDB.batchSize` | `50` | Number of documents to display per cursor iteration (shared with Query Playground) | The connection timeout applies when connecting and authenticating, not while running queries. Queries have no extension-side time limit. Press **Ctrl+C** to cancel, or use `.maxTimeMS()` on a supported query @@ -246,7 +253,8 @@ The help output also prints the full Settings search query for manual access. - **Use variables for iteration**: Store intermediate results in variables and refine your queries step by step. - **Switch databases with `use`**: No need to open a new shell. Just type `use otherDatabase` and the prompt updates. - **Copy queries to the playground**: If an ad-hoc query grows complex, use the navigation links to move it to a playground file where you can save and refine it. -- **Disable colors for accessibility**: If you use a screen reader, set `documentDB.shell.display.colorSupport` to `false` for clean, unformatted output. +- **Disable colors for accessibility**: See [Accessibility](./accessibility#interactive-shell) + for the `documentDB.shell.display.colorSupport` setting and its limitations. --- diff --git a/docs/user-manual/query-playground.md b/docs/user-manual/query-playground.md index a5bd3c7d4..b3498eafb 100644 --- a/docs/user-manual/query-playground.md +++ b/docs/user-manual/query-playground.md @@ -77,18 +77,25 @@ Because the playground uses a full JavaScript runtime, you can write queries the ## Running Code -The playground provides two execution modes, each triggered through CodeLens buttons that appear above your code: +The playground provides two execution modes. You can use CodeLens, the Command Palette, or the +editor title toolbar and overflow menu:

Query Playground showing Run All at the top, and Run, Collection View, Shell CodeLens links on each block

-| Mode | Trigger | Behavior | -| ------------- | -------------------------------------------------------------------------------- | ----------------------------------------- | -| **Run Block** | Click the **Run** button above a specific block, or press `Ctrl+Enter` | Executes the block at the cursor position | -| **Run All** | Click the **Run All** button at the top of the file, or press `Ctrl+Shift+Enter` | Executes the entire file, top to bottom | +| Mode | Trigger | Behavior | +| ------------- | -------------------------------------------------------------------------------------- | ----------------------------------------- | +| **Run Block** | CodeLens, Command Palette, editor title overflow, or editor context menu; `Ctrl+Enter` | Executes the block at the cursor position | +| **Run All** | CodeLens, Command Palette, or editor title; `Ctrl+Shift+Enter` | Executes the entire file, top to bottom | -Each block also shows **Collection View** and **Shell** CodeLens links. These open the same query in the Collection View or the Interactive Shell, so you can switch tools without copy-pasting. Some scripts (e.g., loops, aggregations, or multi-statement blocks) may not be convertible to the Collection View. +Each block also shows **Collection View** and **Shell** CodeLens links. The corresponding +**Query Playground: Open Block in Collection View** and **Query Playground: Open Block in Shell** +commands are available from the Command Palette, editor title overflow, and editor context menu. +They require a connection and code in the target block. The Shell opens with the block text ready +for execution. Some scripts (for example, loops, aggregations, or multi-statement blocks) may not +be convertible to the Collection View. -When you press `Ctrl+Enter` and the cursor is on a blank line between blocks, the playground runs the nearest preceding block. +When a block action has no arguments, it uses the block at the cursor. If the cursor is on a blank +line, it falls back to the nearest preceding block. Each execution reuses the connection you established when you connected to the cluster. There is no need to authenticate again or provide credentials separately. @@ -157,12 +164,13 @@ You can also trigger this manually at any time through the Command Palette: run ## Connections and Multiple Files -Each playground file is permanently bound to the cluster and database it was created for. This means: +Each playground file is bound to a cluster and database, and the connection can be changed for the +active file: - **Multiple playgrounds, multiple connections**: You can have several `.documentdb.js` files open at the same time, each connected to a different server or database. - **Status bar indicator**: The VS Code status bar shows the active playground's connection details when the file is focused. -- **CodeLens header**: The first line of each file displays a CodeLens showing the connection status. Click it to see connection details. -- **No "switch connection" workflow**: To query a different database, create a new playground from that database's tree node. +- **Connection actions**: Use **Playground Connection…** in the editor title to connect or show the current connection and switch databases. The Command Palette lists **Query Playground: Connect to Database** or **Query Playground: Change Connection**, depending on the active playground. The CodeLens header and status bar expose the same connection flow. +- **Run with no saved connection**: A playground prompts for a connection when you run it without one. ## Keyboard Shortcuts @@ -171,12 +179,16 @@ Each playground file is permanently bound to the cluster and database it was cre | `Ctrl+Enter` | Run the current block | | `Ctrl+Shift+Enter` | Run the entire file | +Use `Cmd` on macOS. Connect, Shell, Collection View, and the focus commands have no default +shortcuts. See [Accessibility](./accessibility) for the keyboard-reachable surfaces and +screen-reader after-run behavior. + ## Navigating to Other Features The playground is connected to the other query surfaces in the extension: -- **Open in Collection View**: A CodeLens link lets you open the collection referenced in your script directly in the Collection View, where you can browse results visually. -- **Open in Interactive Shell**: A CodeLens link lets you launch an Interactive Shell session for the same connection, pre-filled with your code. +- **Open in Collection View**: A CodeLens link or the keyboard-reachable **Open Block in Collection View** command opens the collection referenced in your script in the Collection View, where you can browse results visually. +- **Open in Interactive Shell**: A CodeLens link or the keyboard-reachable **Open Block in Shell** command launches an Interactive Shell session for the same connection, pre-filled with your code. - **From the Collection View**: The Collection View toolbar has an **Open in Playground** button that exports your current find query (filter, project, sort) into a new playground file. For more details on the Interactive Shell, see the [Interactive Shell](./interactive-shell) documentation. @@ -187,11 +199,12 @@ Open VS Code Settings and expand **Extensions** > **DocumentDB**. The Run All co is under **Query Playground**. The shared batch size is under **Queries & Results**, and the shared connection timeout is under **Connections & Discovery**. You can also search for a setting ID from the table. -| Setting | Default | Description | -| ------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------- | -| `documentDB.playground.confirmRunAll` | `true` | Show a confirmation dialog before running the entire playground file with Run All | -| `documentDB.batchSize` | `50` | Number of documents to display per cursor iteration in the Query Playground and Interactive Shell | -| `documentDB.connectionTimeout` | `30` | Maximum time (in seconds) to wait for the playground to connect and authenticate (shared with Interactive Shell) | +| Setting | Default | Description | +| ------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| `documentDB.playground.confirmRunAll` | `true` | Show a confirmation dialog before running the entire playground file with Run All | +| `documentDB.batchSize` | `50` | Number of documents to display per cursor iteration in the Query Playground and Interactive Shell | +| `documentDB.connectionTimeout` | `30` | Maximum time (in seconds) to wait for the playground to connect and authenticate (shared with Interactive Shell) | +| `documentDB.playground.afterRun` | `auto` | Controls focus or notification behavior after a successful run; see the [Accessibility behavior table](./accessibility#screen-readers) | The connection timeout does not limit query execution. Use **Cancel** to stop a long-running query, or use `.maxTimeMS()` on a supported query to set a server-side limit. diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 7a8731cf8..896451723 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -468,6 +468,7 @@ "Architecture": "Architecture", "Are you sure you want to run all code?": "Are you sure you want to run all code?", "Are you sure?": "Are you sure?", + "Array ({0} elements)": "Array ({0} elements)", "As requested": "As requested", "ascending": "ascending", "Ascending (1)": "Ascending (1)", @@ -1008,6 +1009,7 @@ "Credentials rejected by the cluster": "Credentials rejected by the cluster", "Credentials updated successfully.": "Credentials updated successfully.", "Credentials updated. New connections will use them. Open shells for '{cluster}' keep their current connection until you close them.": "Credentials updated. New connections will use them. Open shells for '{cluster}' keep their current connection until you close them.", + "Cursor ({0} documents)": "Cursor ({0} documents)", "Custom cloud": "Custom cloud", "Custom tag": "Custom tag", "Daemon architecture": "Daemon architecture", @@ -1267,6 +1269,9 @@ "Enter a whole number from 1000 to 100000.": "Enter a whole number from 1000 to 100000.", "Enter a whole number from 2 to 100.": "Enter a whole number from 2 to 100.", "Enter a whole number from 20 to 2048.": "Enter a whole number from 20 to 2048.", + "Enter a whole number of pixels.": "Enter a whole number of pixels.", + "Enter a width between {0} and {1} pixels.": "Enter a width between {0} and {1} pixels.", + "Enter a width in pixels for {0}.": "Enter a width in pixels for {0}.", "Enter an initial collection name for the new database.": "Enter an initial collection name for the new database.", "Enter both a username and a password, or leave both blank to auto-generate.": "Enter both a username and a password, or leave both blank to auto-generate.", "Enter details": "Enter details", @@ -1479,6 +1484,7 @@ "Failed to unhide index.": "Failed to unhide index.", "Failed to update connection: {0}": "Failed to update connection: {0}", "Failed to update connection: connection not found in storage or missing connection string.": "Failed to update connection: connection not found in storage or missing connection string.", + "Failed to update Query Playground context: {0}": "Failed to update Query Playground context: {0}", "Failed to update the connection.": "Failed to update the connection.", "Failed to validate source collection: {0}": "Failed to validate source collection: {0}", "Failed to view kubeconfig: {0}": "Failed to view kubeconfig: {0}", @@ -1510,6 +1516,7 @@ "Finished at": "Finished at", "Finished importing": "Finished importing", "Fix the highlighted values in Advanced settings to continue.": "Fix the highlighted values in Advanced settings to continue.", + "Focus Result": "Focus Result", "Folder": "Folder", "Folder name cannot be empty": "Folder name cannot be empty", "For example, {0}": "For example, {0}", @@ -2073,6 +2080,8 @@ "No projects available": "No projects available", "No projects available for these credentials": "No projects available for these credentials", "No public connectivity": "No public connectivity", + "No Query Playground is available to focus.": "No Query Playground is available to focus.", + "No Query Playground result is open.": "No Query Playground result is open.", "No reachable service address": "No reachable service address", "No ready pods behind the service": "No ready pods behind the service", "No ready pods found backing service \"{0}\" in namespace \"{1}\". Check that the service has running pods.": "No ready pods found backing service \"{0}\" in namespace \"{1}\". Check that the service has running pods.", @@ -2373,6 +2382,8 @@ "Query": "Query", "Query completed in {0}ms.\n\nThis is acceptable for most use cases, though optimization could improve responsiveness.": "Query completed in {0}ms.\n\nThis is acceptable for most use cases, though optimization could improve responsiveness.", "Query completed in {0}ms.\n\nThis is excellent performance and provides a responsive user experience.": "Query completed in {0}ms.\n\nThis is excellent performance and provides a responsive user experience.", + "Query completed without a return value.": "Query completed without a return value.", + "Query completed: {0}": "Query completed: {0}", "Query copied to clipboard": "Query copied to clipboard", "Query Efficiency Analysis": "Query Efficiency Analysis", "Query execution failed": "Query execution failed", @@ -2679,6 +2690,7 @@ "Session ID is required": "Session ID is required", "sessionId is required for query optimization": "sessionId is required for query optimization", "Set a display name for \"{0}\". The kubeconfig file is not modified. Leave empty to clear the alias.": "Set a display name for \"{0}\". The kubeconfig file is not modified. Leave empty to clear the alias.", + "Set Column Width": "Set Column Width", "Set microsoft-sovereign-cloud.environment to the cluster cloud, then connect again.": "Set microsoft-sovereign-cloud.environment to the cluster cloud, then connect again.", "Set the KUBECONFIG environment variable or create a kubeconfig at the default path, then try again.": "Set the KUBECONFIG environment variable or create a kubeconfig at the default path, then try again.", "Set up": "Set up", @@ -3421,6 +3433,7 @@ "Use existing": "Use existing", "Use Level Up to return one level, or activate an ancestor breadcrumb to jump to it.": "Use Level Up to return one level, or activate an ancestor breadcrumb to jump to it.", "Use native DocumentDB authentication or managed identity on an Azure VM, and report this on GitHub.": "Use native DocumentDB authentication or managed identity on an Azure VM, and report this on GitHub.", + "Use the Command Palette (Query Playground) or the editor context menu for all actions.": "Use the Command Palette (Query Playground) or the editor context menu for all actions.", "Use the host name covered by the certificate, or ask your administrator to correct the certificate.": "Use the host name covered by the certificate, or ask your administrator to correct the certificate.", "Use the identity assigned to this machine": "Use the identity assigned to this machine", "Use the single SRV host name supplied for the cluster.": "Use the single SRV host name supplied for the cluster.", diff --git a/package-lock.json b/package-lock.json index 8e82121a6..36dafe777 100644 --- a/package-lock.json +++ b/package-lock.json @@ -51,6 +51,7 @@ "bson": "^7.2.0", "denque": "~2.1.0", "es-toolkit": "~1.45.1", + "keyborg": "~3.498.0", "monaco-editor": "~0.52.2", "mongodb": "^7.1.0", "mongodb-connection-string-url": "~3.0.2", diff --git a/package.json b/package.json index 2225f3883..e030e927d 100644 --- a/package.json +++ b/package.json @@ -193,6 +193,7 @@ "bson": "^7.2.0", "denque": "~2.1.0", "es-toolkit": "~1.45.1", + "keyborg": "~3.498.0", "monaco-editor": "~0.52.2", "mongodb": "^7.1.0", "mongodb-connection-string-url": "~3.0.2", @@ -813,6 +814,14 @@ "command": "vscode-documentdb.command.clusterDashboard.context.deleteCollection", "title": "Delete Collection" }, + { + "command": "vscode-documentdb.command.collectionView.column.resize", + "title": "Set Column Width…" + }, + { + "command": "vscode-documentdb.command.collectionView.column.resizeByContent", + "title": "Size Column to Fit" + }, { "//": "Open Container View", "category": "DocumentDB", @@ -888,7 +897,9 @@ "//": "[Query Playground] Show Connection Info", "category": "DocumentDB", "command": "vscode-documentdb.command.playground.showConnectionInfo", - "title": "Query Playground: Show Connection Info" + "title": "Query Playground: Change Connection", + "shortTitle": "%playground.connectionShortTitle%", + "icon": "$(plug)" }, { "//": "[Query Playground] Connect / Reconnect", @@ -905,12 +916,36 @@ "icon": "$(run-all)" }, { - "//": "[Query Playground] Run Selected / Current Block", + "//": "[Query Playground] Run Current Block", "category": "DocumentDB", "command": "vscode-documentdb.command.playground.runSelected", - "title": "Query Playground: Run Selected", + "title": "Query Playground: Run Block", "icon": "$(play)" }, + { + "//": "[Query Playground] Open Block in Shell", + "category": "DocumentDB", + "command": "vscode-documentdb.command.playground.openQueryInShell", + "title": "%playground.openBlockInShell%", + "icon": "$(terminal)" + }, + { + "category": "DocumentDB", + "command": "vscode-documentdb.command.playground.focusResult", + "title": "%playground.focusResult%" + }, + { + "category": "DocumentDB", + "command": "vscode-documentdb.command.playground.focusPlayground", + "title": "%playground.focusPlayground%" + }, + { + "//": "[Query Playground] Open Block in Collection View", + "category": "DocumentDB", + "command": "vscode-documentdb.command.playground.openQueryInCollectionView", + "title": "%playground.openBlockInCollectionView%", + "icon": "$(screen-full)" + }, { "//": "[Query Playground] Scan Collection Schema for field completions", "category": "DocumentDB", @@ -970,9 +1005,61 @@ "group": "navigation@5" } ], - "editor/context": [], - "editor/title": [], + "editor/context": [ + { + "command": "vscode-documentdb.command.playground.runSelected", + "when": "editorLangId == 'documentdb-playground'", + "group": "1_documentdb@1" + }, + { + "command": "vscode-documentdb.command.playground.openQueryInShell", + "when": "editorLangId == 'documentdb-playground' && documentdbPlaygroundConnected && documentdbPlaygroundBlockHasCode", + "group": "1_documentdb@2" + }, + { + "command": "vscode-documentdb.command.playground.openQueryInCollectionView", + "when": "editorLangId == 'documentdb-playground' && documentdbPlaygroundConnected && documentdbPlaygroundBlockHasCode", + "group": "1_documentdb@3" + } + ], + "editor/title": [ + { + "command": "vscode-documentdb.command.playground.showConnectionInfo", + "when": "resourceLangId == 'documentdb-playground'", + "group": "navigation@1" + }, + { + "command": "vscode-documentdb.command.playground.runAll", + "when": "resourceLangId == 'documentdb-playground'", + "group": "navigation@2" + }, + { + "command": "vscode-documentdb.command.playground.runSelected", + "when": "resourceLangId == 'documentdb-playground'", + "group": "2_playground@1" + }, + { + "command": "vscode-documentdb.command.playground.openQueryInShell", + "when": "resourceLangId == 'documentdb-playground'", + "group": "2_playground@2" + }, + { + "command": "vscode-documentdb.command.playground.openQueryInCollectionView", + "when": "resourceLangId == 'documentdb-playground'", + "group": "2_playground@3" + } + ], "webview/context": [ + { + "command": "vscode-documentdb.command.collectionView.column.resize", + "when": "webviewId == 'vscode-documentdb-collection-view' && collectionViewColumnHeader", + "group": "1_resize@1" + }, + { + "command": "vscode-documentdb.command.collectionView.column.resizeByContent", + "when": "webviewId == 'vscode-documentdb-collection-view' && collectionViewColumnHeader", + "group": "1_resize@2" + }, { "command": "vscode-documentdb.command.clusterDashboard.context.viewCollections", "when": "webviewId == 'vscode-documentdb-cluster-dashboard' && clusterDashboardNamespace == database", @@ -1643,6 +1730,14 @@ "command": "vscode-documentdb.command.clusterDashboard.context.deleteCollection", "when": "never" }, + { + "command": "vscode-documentdb.command.collectionView.column.resize", + "when": "never" + }, + { + "command": "vscode-documentdb.command.collectionView.column.resizeByContent", + "when": "never" + }, { "command": "vscode-documentdb.command.refresh", "when": "never" @@ -1886,19 +1981,35 @@ }, { "command": "vscode-documentdb.command.playground.showConnectionInfo", - "when": "never" + "when": "editorLangId == 'documentdb-playground' && documentdbPlaygroundConnected" }, { "command": "vscode-documentdb.command.playground.connect", - "when": "editorLangId == 'documentdb-playground'" + "when": "editorLangId == 'documentdb-playground' && !documentdbPlaygroundConnected" }, { "command": "vscode-documentdb.command.playground.runAll", - "when": "never" + "when": "editorLangId == 'documentdb-playground'" }, { "command": "vscode-documentdb.command.playground.runSelected", - "when": "never" + "when": "editorLangId == 'documentdb-playground'" + }, + { + "command": "vscode-documentdb.command.playground.openQueryInShell", + "when": "editorLangId == 'documentdb-playground' && documentdbPlaygroundConnected && documentdbPlaygroundBlockHasCode" + }, + { + "command": "vscode-documentdb.command.playground.openQueryInCollectionView", + "when": "editorLangId == 'documentdb-playground' && documentdbPlaygroundConnected && documentdbPlaygroundBlockHasCode" + }, + { + "command": "vscode-documentdb.command.playground.focusResult", + "when": "editorLangId == 'documentdb-playground'" + }, + { + "command": "vscode-documentdb.command.playground.focusPlayground", + "when": "resourceScheme == 'documentdb-playground-result'" } ] }, @@ -1914,6 +2025,24 @@ "key": "ctrl+enter", "mac": "cmd+enter", "when": "editorLangId == 'documentdb-playground' && editorTextFocus" + }, + { + "command": "vscode-documentdb.command.playground.runAll", + "key": "ctrl+shift+enter", + "mac": "cmd+shift+enter", + "when": "editorLangId == 'documentdb-playground' && editorTextFocus && accessibilityModeEnabled", + "args": { + "screenReaderMode": true + } + }, + { + "command": "vscode-documentdb.command.playground.runSelected", + "key": "ctrl+enter", + "mac": "cmd+enter", + "when": "editorLangId == 'documentdb-playground' && editorTextFocus && accessibilityModeEnabled", + "args": { + "screenReaderMode": true + } } ], "configuration": [ @@ -2062,6 +2191,24 @@ "type": "boolean", "default": true, "description": "Show a confirmation dialog before running the entire playground file with Run All." + }, + "documentDB.playground.afterRun": { + "order": 2, + "type": "string", + "default": "auto", + "enum": [ + "auto", + "stay", + "focusResult", + "notify" + ], + "description": "%playground.afterRun.description%", + "enumDescriptions": [ + "%playground.afterRun.auto%", + "%playground.afterRun.stay%", + "%playground.afterRun.focusResult%", + "%playground.afterRun.notify%" + ] } } }, diff --git a/package.nls.json b/package.nls.json index 88f95c3c7..000ac6cf7 100644 --- a/package.nls.json +++ b/package.nls.json @@ -2,5 +2,15 @@ "survey.containerTitle": "DocumentDB Feedback", "survey.viewTitle": "Share Your Experience", "survey.giveFeedbackTitle": "Give Feedback", + "playground.connectionShortTitle": "Playground Connection…", + "playground.openBlockInShell": "Query Playground: Open Block in Shell", + "playground.openBlockInCollectionView": "Query Playground: Open Block in Collection View", + "playground.focusResult": "Query Playground: Focus Result", + "playground.focusPlayground": "Query Playground: Focus Playground", + "playground.afterRun.description": "What happens after a successful Query Playground run.", + "playground.afterRun.auto": "Focus the result when a run shortcut passes screen-reader mode; otherwise stay in the playground.", + "playground.afterRun.stay": "Stay in the playground after every run.", + "playground.afterRun.focusResult": "Focus the result after every run.", + "playground.afterRun.notify": "Stay in the playground and show a completion notification with a Focus Result action after every run.", "translation.placeholder": "Translation placeholder…" } diff --git a/packages/vscode-ext-webview-fluentui/CHANGELOG.md b/packages/vscode-ext-webview-fluentui/CHANGELOG.md index a1d1e9cf1..b46cdd980 100644 --- a/packages/vscode-ext-webview-fluentui/CHANGELOG.md +++ b/packages/vscode-ext-webview-fluentui/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased + +- `MetricCard`'s info glyph is now solid `descriptionForeground` instead of the label color at 60% opacity, which fell under the 3:1 non-text contrast minimum in light themes ([#771](https://github.com/microsoft/vscode-documentdb/issues/771)). Outside VS Code it falls back to `colorNeutralForeground4`. + ## 1.3.0 - The `@fluentui/react-components` peer accepts both 9.74.x and 9.75.1 through 9.75.x. diff --git a/packages/vscode-ext-webview-fluentui/src/components/MetricGrid/MetricCard.tsx b/packages/vscode-ext-webview-fluentui/src/components/MetricGrid/MetricCard.tsx index b913a4d98..5b3242a76 100644 --- a/packages/vscode-ext-webview-fluentui/src/components/MetricGrid/MetricCard.tsx +++ b/packages/vscode-ext-webview-fluentui/src/components/MetricGrid/MetricCard.tsx @@ -40,7 +40,13 @@ const useStyles = makeStyles({ textOverflow: 'ellipsis', }, labelWithGlyph: { display: 'inline-flex', alignItems: 'center' }, - glyph: { fontSize: '12px', opacity: 0.6, marginLeft: '4px' }, + // A solid theme color rather than a faded label color: at 60% opacity the glyph fell under the + // 3:1 non-text contrast minimum in Light themes. + glyph: { + fontSize: '12px', + marginLeft: '4px', + color: `var(--vscode-descriptionForeground, ${tokens.colorNeutralForeground4})`, + }, // The slot is what stops the skeleton to value swap from shifting everything below it, so its // height is reserved rather than derived from the content. value: { @@ -54,7 +60,9 @@ const useStyles = makeStyles({ }, valueLarge: { fontSize: '28px', lineHeight: '32px', minHeight: '32px' }, valueSmall: { fontSize: '14px', lineHeight: '20px', minHeight: '20px' }, - unavailable: { opacity: 0.5, color: tokens.colorNeutralForegroundDisabled }, + // "N/A" is content, not a disabled control, so it needs 4.5:1. The disabled color at half + // opacity fell to about 1.4:1, and opacity also survives forced-colors mode. + unavailable: { color: `var(--vscode-descriptionForeground, ${tokens.colorNeutralForeground3})` }, tooltip: { padding: '8px' }, tooltipTitle: { fontWeight: 600, fontSize: '16px', marginBottom: '12px' }, tooltipBody: { whiteSpace: 'pre-line' }, diff --git a/src/commands/playground/connectDatabase.ts b/src/commands/playground/connectDatabase.ts index 81988aaf6..9b23c0989 100644 --- a/src/commands/playground/connectDatabase.ts +++ b/src/commands/playground/connectDatabase.ts @@ -6,7 +6,6 @@ import { type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; -import { PLAYGROUND_LANGUAGE_ID } from '../../documentdb/playground/constants'; import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; import { type PlaygroundConnection } from '../../documentdb/playground/types'; import { DocumentDBConnectionString } from '../../documentdb/utils/DocumentDBConnectionString'; @@ -16,6 +15,7 @@ import { DatabaseItem } from '../../tree/documentdb/DatabaseItem'; import { type BaseClusterModel, type TreeCluster } from '../../tree/models/BaseClusterModel'; import { type TreeElement } from '../../tree/TreeElement'; import { pickTreeNode } from '../../utils/pickItem/pickTreeNode'; +import { parsePlaygroundInvocation, resolvePlaygroundEditor } from './playgroundInvocation'; /** * Context-value token marking a database node in the Connections tree. @@ -32,9 +32,12 @@ const DATABASE_CONTEXT_VALUE = 'treeItem_database'; * replaced once a new database is actually selected, so cancelling the picker * leaves the current connection intact. */ -export async function showConnectionInfo(context: IActionContext): Promise { - const editor = vscode.window.activeTextEditor; - if (!editor || editor.document.languageId !== PLAYGROUND_LANGUAGE_ID) { +export async function showConnectionInfo(context: IActionContext, ...args: unknown[]): Promise { + const invocation = parsePlaygroundInvocation(args); + context.telemetry.properties.activationSource = invocation.activationSource; + + const editor = resolvePlaygroundEditor(invocation.uri); + if (!editor) { return; } @@ -73,9 +76,12 @@ export async function showConnectionInfo(context: IActionContext): Promise * * Invoked from the "Not connected" CodeLens / StatusBar affordance. */ -export async function connectPlayground(context: IActionContext): Promise { - const editor = vscode.window.activeTextEditor; - if (!editor || editor.document.languageId !== PLAYGROUND_LANGUAGE_ID) { +export async function connectPlayground(context: IActionContext, ...args: unknown[]): Promise { + const invocation = parsePlaygroundInvocation(args); + context.telemetry.properties.activationSource = invocation.activationSource; + + const editor = resolvePlaygroundEditor(invocation.uri); + if (!editor) { return; } await promptAndConnectPlayground(context, editor.document.uri, 'playground.connect'); diff --git a/src/commands/playground/executePlaygroundCode.test.ts b/src/commands/playground/executePlaygroundCode.test.ts new file mode 100644 index 000000000..b1591d22d --- /dev/null +++ b/src/commands/playground/executePlaygroundCode.test.ts @@ -0,0 +1,343 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { type ExecutionResult, type PlaygroundConnection } from '../../documentdb/playground/types'; +import { disposeEvaluators, executePlaygroundCode } from './executePlaygroundCode'; + +const mocks = vi.hoisted(() => ({ + evaluate: vi.fn<() => Promise>(), + killWorker: vi.fn(), + consoleOutputCount: 0, + provider: { showResult: vi.fn(), focusResult: vi.fn<() => Promise>() }, + service: { getConnection: vi.fn(), isExecuting: vi.fn(), setExecuting: vi.fn() }, + recordSurveyActivity: vi.fn(), + notificationChoice: vi.fn<() => Promise>(), + errors: [] as { event: string; error: unknown }[], + tasks: [] as Promise[], +})); + +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ + ...(await importOriginal()), + callWithTelemetryAndErrorHandling: ( + event: string, + callback: (context: IActionContext) => Promise, + ): Promise => { + const context = { telemetry: { properties: {}, measurements: {} }, errorHandling: {} } as IActionContext; + const task = (async (): Promise => { + try { + return await callback(context); + } catch (error) { + mocks.errors.push({ event, error }); + return undefined; + } + })(); + mocks.tasks.push(task); + return task; + }, +})); +vi.mock('../../documentdb/ClustersClient', () => ({ ClustersClient: { getExistingClient: vi.fn() } })); +vi.mock('../../documentdb/CredentialCache', () => ({ CredentialCache: { getCredentials: vi.fn() } })); +vi.mock('../../documentdb/feedResultToSchemaStore', () => ({ feedResultToSchemaStore: vi.fn() })); +vi.mock('../../documentdb/playground/PlaygroundEvaluator', () => ({ + PlaygroundEvaluator: class { + readonly evaluate = mocks.evaluate; + readonly killWorker = mocks.killWorker; + readonly sessionEvalCount = 1; + readonly lastInitDurationMs = 0; + get lastEvalConsoleOutputCount(): number { + return mocks.consoleOutputCount; + } + dispose(): void {} + }, +})); +vi.mock('../../documentdb/playground/PlaygroundService', () => ({ + PlaygroundService: { getInstance: (): typeof mocks.service => mocks.service }, +})); +vi.mock('../../documentdb/utils/getClusterMetadata', () => ({ addDomainInfoToProperties: vi.fn() })); +vi.mock('../../documentdb/utils/connectionStringHelpers', () => ({ getHostsFromConnectionString: vi.fn() })); +vi.mock('../../extensionVariables', () => ({ ext: { playgroundResultProvider: mocks.provider } })); +vi.mock('../../services/errorExplanationService', () => ({ + ErrorExplanationService: { explain: vi.fn().mockResolvedValue(undefined) }, +})); +vi.mock('../../services/survey/SurveyService', () => ({ recordSurveyActivity: mocks.recordSurveyActivity })); +vi.mock('./connectDatabase', () => ({ promptAndConnectPlayground: vi.fn() })); + +describe('executePlaygroundCode after-run behavior', () => { + const sourceUri = vscode.Uri.file('/query.documentdb.js'); + const connection: PlaygroundConnection = { + clusterId: 'cluster', + clusterDisplayName: 'Cluster', + databaseName: 'db', + }; + const result: ExecutionResult = { type: 'Cursor', printable: [{ _id: 1 }, { _id: 2 }], durationMs: 5 }; + let cancellation: vscode.EventEmitter; + let progressFinished: boolean; + let token: vscode.CancellationToken; + + beforeEach(() => { + mocks.errors.length = 0; + mocks.tasks.length = 0; + mocks.consoleOutputCount = 0; + mocks.evaluate.mockResolvedValue(result); + mocks.provider.showResult.mockResolvedValue(undefined); + mocks.provider.focusResult.mockResolvedValue(true); + mocks.service.getConnection.mockReturnValue(connection); + mocks.service.isExecuting.mockReturnValue(false); + mocks.notificationChoice.mockResolvedValue(undefined); + cancellation = new vscode.EventEmitter(); + token = { isCancellationRequested: false, onCancellationRequested: cancellation.event }; + progressFinished = false; + vi.spyOn(vscode.window, 'showInformationMessage').mockImplementation( + async ( + _message: string, + ...items: (T | vscode.MessageOptions)[] + ): Promise => { + const choice = await mocks.notificationChoice(); + return items.find((item): item is T => { + if (typeof item === 'string') { + return item === choice; + } + return typeof item === 'object' && 'title' in item && item.title === choice; + }); + }, + ); + vi.spyOn(vscode.window, 'showErrorMessage').mockResolvedValue(undefined); + vi.spyOn(vscode.window, 'withProgress').mockImplementation( + async ( + _options: vscode.ProgressOptions, + task: ( + progress: vscode.Progress<{ message?: string; increment?: number }>, + token: vscode.CancellationToken, + ) => Thenable, + ): Promise => { + try { + return await task({ report: vi.fn() }, token); + } finally { + progressFinished = true; + } + }, + ); + }); + + afterEach(() => { + cancellation.dispose(); + disposeEvaluators(); + vi.restoreAllMocks(); + vi.clearAllMocks(); + }); + + it.each([undefined, 'stay', 'focusResult', 'notify'] as const)( + 'performs only the %s success outcome', + async (afterRun) => { + await executePlaygroundCode( + 'db.test.find()', + 'runSelected', + sourceUri, + afterRun ? { afterRun } : undefined, + ); + + expect(mocks.provider.showResult).toHaveBeenCalledExactlyOnceWith( + sourceUri, + expect.stringContaining('// Result: Cursor (2 documents)'), + { focus: afterRun === 'focusResult' }, + ); + if (afterRun === 'notify') { + expect(vscode.window.showInformationMessage).toHaveBeenCalledExactlyOnceWith( + 'Query completed: Cursor (2 documents)', + 'Focus Result', + ); + } else { + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + } + expect(mocks.provider.focusResult).not.toHaveBeenCalled(); + expect(mocks.recordSurveyActivity).toHaveBeenCalledWith('queryPlayground'); + expect(mocks.service.setExecuting.mock.calls).toEqual([ + ['cluster', true], + ['cluster', false], + ]); + expect(progressFinished).toBe(true); + }, + ); + + it('uses the approved no-return message only when the worker proves the printable was undefined', async () => { + mocks.evaluate.mockResolvedValue({ + type: null, + printable: undefined, + printableIsUndefined: true, + durationMs: 5, + }); + + await executePlaygroundCode('const a = 1', 'runAll', sourceUri, { afterRun: 'notify' }); + + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( + 'Query completed without a return value.', + 'Focus Result', + ); + }); + + it.each([ + [null, 'null'], + [42, 'number'], + ] as const)( + 'truthfully announces an untyped printable %j instead of claiming no return value', + async (printable, description) => { + mocks.evaluate.mockResolvedValue({ type: null, printable, durationMs: 5 }); + + await executePlaygroundCode('db.test.findOne()', 'runAll', sourceUri, { afterRun: 'notify' }); + + expect(vscode.window.showInformationMessage).toHaveBeenCalledExactlyOnceWith( + `Query completed: ${description}`, + 'Focus Result', + ); + expect(mocks.provider.showResult).toHaveBeenCalledExactlyOnceWith(sourceUri, expect.any(String), { + focus: false, + }); + }, + ); + + it.each([undefined, 'Focus Result'])( + 'finishes progress and unlocks execution before the notification choice %s', + async (choice) => { + let choose: ((value: string | undefined) => void) | undefined; + const notification = new Promise((resolve) => { + choose = resolve; + }); + mocks.notificationChoice.mockReturnValueOnce(notification); + + await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'notify' }); + + expect(progressFinished).toBe(true); + expect(mocks.service.setExecuting).toHaveBeenLastCalledWith('cluster', false); + expect(mocks.provider.focusResult).not.toHaveBeenCalled(); + choose?.(choice); + await Promise.all(mocks.tasks); + if (choice) { + expect(mocks.provider.focusResult).toHaveBeenCalledExactlyOnceWith(sourceUri); + } else { + expect(mocks.provider.focusResult).not.toHaveBeenCalled(); + } + expect(mocks.errors).toEqual([]); + }, + ); + + it('reports a result closed before the notification action is chosen', async () => { + mocks.notificationChoice.mockResolvedValueOnce('Focus Result'); + mocks.provider.focusResult.mockResolvedValue(false); + + await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'notify' }); + await Promise.all(mocks.tasks); + + expect(vscode.window.showInformationMessage).toHaveBeenLastCalledWith('No Query Playground result is open.'); + }); + + it.each(['notification', 'focus'])( + 'handles a failed fire-and-forget %s through the telemetry/error wrapper', + async (failure) => { + const error = new Error('Action failed'); + if (failure === 'notification') { + mocks.notificationChoice.mockRejectedValueOnce(error); + } else { + mocks.notificationChoice.mockResolvedValueOnce('Focus Result'); + mocks.provider.focusResult.mockRejectedValue(error); + } + + await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'notify' }); + await Promise.all(mocks.tasks); + + expect(mocks.errors).toEqual([{ event: 'playground.afterRun.notify', error }]); + expect(progressFinished).toBe(true); + }, + ); + + it.each(['stay', 'focusResult', 'notify'] as const)( + 'preserves the existing error result and notification for %s', + async (afterRun) => { + const error = new Error('Query failed'); + mocks.evaluate.mockRejectedValue(error); + + await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun }); + + expect(mocks.provider.showResult).toHaveBeenCalledExactlyOnceWith( + sourceUri, + expect.stringContaining('Query failed'), + ); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'Query playground execution failed: Query failed', + ); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(mocks.provider.focusResult).not.toHaveBeenCalled(); + expect(mocks.recordSurveyActivity).not.toHaveBeenCalled(); + expect(mocks.errors).toEqual([{ event: 'playground.execute', error }]); + expect(mocks.service.setExecuting).toHaveBeenLastCalledWith('cluster', false); + }, + ); + + it.each(['focusResult', 'notify'] as const)( + 'keeps focus and skips completion when a cancelled evaluation still succeeds (%s)', + async (afterRun) => { + mocks.evaluate.mockImplementation(async () => { + cancellation.fire(); + return result; + }); + + await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun }); + + expect(mocks.killWorker).toHaveBeenCalledOnce(); + expect(mocks.provider.showResult).toHaveBeenCalledExactlyOnceWith(sourceUri, expect.any(String), { + focus: false, + }); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(mocks.recordSurveyActivity).not.toHaveBeenCalled(); + }, + ); + + it('keeps focus and suppresses error/success UI when worker cancellation rejects', async () => { + mocks.evaluate.mockImplementation(async () => { + cancellation.fire(); + throw new Error('Worker killed'); + }); + + await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'notify' }); + + expect(mocks.provider.showResult).not.toHaveBeenCalled(); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(mocks.errors).toEqual([ + { + event: 'playground.execute', + error: expect.objectContaining({ stepName: 'playground.execute', _isUserCancelledError: true }), + }, + ]); + expect(mocks.service.setExecuting).toHaveBeenLastCalledWith('cluster', false); + }); + + it('does not focus or notify when progress was cancelled before its callback', async () => { + token = { ...token, isCancellationRequested: true }; + + await executePlaygroundCode('db.test.find()', 'runAll', sourceUri, { afterRun: 'focusResult' }); + + expect(mocks.provider.showResult).toHaveBeenCalledWith(sourceUri, expect.any(String), { focus: false }); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(mocks.recordSurveyActivity).not.toHaveBeenCalled(); + }); + + it('retains the existing console output hint in the result', async () => { + mocks.consoleOutputCount = 1; + + await executePlaygroundCode('print(1)', 'runAll', sourceUri); + + expect(mocks.provider.showResult).toHaveBeenCalledWith( + sourceUri, + expect.stringContaining( + '\n\n// Note: Output was printed to the "DocumentDB Query Playground Output" channel', + ), + { focus: false }, + ); + }); +}); diff --git a/src/commands/playground/executePlaygroundCode.ts b/src/commands/playground/executePlaygroundCode.ts index 807b7dd9f..d6e7ea71d 100644 --- a/src/commands/playground/executePlaygroundCode.ts +++ b/src/commands/playground/executePlaygroundCode.ts @@ -13,9 +13,10 @@ import * as vscode from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { feedResultToSchemaStore } from '../../documentdb/feedResultToSchemaStore'; +import { type PlaygroundAfterRunOutcome } from '../../documentdb/playground/afterRun'; import { PlaygroundEvaluator } from '../../documentdb/playground/PlaygroundEvaluator'; import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; -import { formatError, formatResult } from '../../documentdb/playground/resultFormatter'; +import { describeCompletion, formatError, formatResult } from '../../documentdb/playground/resultFormatter'; import { type PlaygroundConnection } from '../../documentdb/playground/types'; import { extractErrorCode } from '../../documentdb/shell/ShellOutputFormatter'; import { getHostsFromConnectionString } from '../../documentdb/utils/connectionStringHelpers'; @@ -91,10 +92,15 @@ export function getPlaygroundEvaluators(): ReadonlyMap { const service = PlaygroundService.getInstance(); let connection = service.getConnection(documentUri); @@ -182,7 +188,7 @@ export async function executePlaygroundCode( cancellable: true, }, async (progress, token) => { - let cancelled = false; + let cancelled = token.isCancellationRequested; token.onCancellationRequested(() => { cancelled = true; @@ -218,11 +224,31 @@ export async function executePlaygroundCode( } if (sourceUri) { - await ext.playgroundResultProvider.showResult(sourceUri, formattedOutput); + await ext.playgroundResultProvider.showResult(sourceUri, formattedOutput, { + focus: !cancelled && options?.afterRun === 'focusResult', + }); } if (!cancelled) { recordSurveyActivity('queryPlayground'); + if (options?.afterRun === 'notify') { + const description = describeCompletion(result); + const message = description + ? l10n.t('Query completed: {0}', description) + : l10n.t('Query completed without a return value.'); + // The notification choice must not keep execution progress open. + void callWithTelemetryAndErrorHandling('playground.afterRun.notify', async () => { + const focusResult = l10n.t('Focus Result'); + const choice = await vscode.window.showInformationMessage(message, focusResult); + if (choice === focusResult) { + if (!(await ext.playgroundResultProvider.focusResult(sourceUri))) { + await vscode.window.showInformationMessage( + l10n.t('No Query Playground result is open.'), + ); + } + } + }); + } } // result: 'Succeeded' is set automatically by the framework } catch (error: unknown) { diff --git a/src/commands/playground/focusPlaygroundResult.test.ts b/src/commands/playground/focusPlaygroundResult.test.ts new file mode 100644 index 000000000..e030c3692 --- /dev/null +++ b/src/commands/playground/focusPlaygroundResult.test.ts @@ -0,0 +1,199 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { PlaygroundResultProvider } from '../../documentdb/playground/PlaygroundResultProvider'; +import { ext } from '../../extensionVariables'; +import { focusPlayground, focusPlaygroundResult } from './focusPlaygroundResult'; + +vi.mock('../../extensionVariables', () => ({ ext: { playgroundResultProvider: undefined } })); + +function makeEditor(uri: vscode.Uri, languageId: string, viewColumn: vscode.ViewColumn): vscode.TextEditor { + return { document: { uri, languageId }, viewColumn } as vscode.TextEditor; +} + +describe('playground focus commands', () => { + const sourceUri = vscode.Uri.file('/target.documentdb.js'); + const context = {} as IActionContext; + let provider: PlaygroundResultProvider; + let activeEditor: vscode.TextEditor | undefined; + let visibleEditors: vscode.TextEditor[]; + let documents: vscode.TextDocument[]; + + beforeEach(() => { + activeEditor = undefined; + visibleEditors = []; + documents = []; + vi.spyOn(vscode.workspace, 'textDocuments', 'get').mockImplementation(() => documents); + vi.spyOn(vscode.window, 'activeTextEditor', 'get').mockImplementation(() => activeEditor); + vi.spyOn(vscode.window, 'visibleTextEditors', 'get').mockImplementation(() => visibleEditors); + vi.spyOn(vscode.window, 'showInformationMessage').mockResolvedValue(undefined); + vi.spyOn(vscode.window, 'showTextDocument').mockResolvedValue({} as vscode.TextEditor); + vi.spyOn(vscode.workspace, 'openTextDocument').mockResolvedValue({ uri: sourceUri } as vscode.TextDocument); + vi.spyOn(vscode.workspace, 'onDidCloseTextDocument').mockReturnValue({ dispose: vi.fn() }); + provider = new PlaygroundResultProvider(); + ext.playgroundResultProvider = provider; + vi.spyOn(provider, 'focusResult').mockResolvedValue(true); + }); + + afterEach(() => { + provider.dispose(); + vi.restoreAllMocks(); + vi.clearAllMocks(); + }); + + it.each(['documentdb-playground', 'documentdb-playground-result'])( + 'focuses the source-specific result from %s', + async (languageId) => { + activeEditor = makeEditor( + languageId === 'documentdb-playground' ? sourceUri : provider.getResultUri(sourceUri), + languageId, + vscode.ViewColumn.One, + ); + + await focusPlaygroundResult(context); + + expect(provider.focusResult).toHaveBeenCalledOnce(); + expect(vi.mocked(provider.focusResult).mock.calls[0][0].toString()).toBe(sourceUri.toString()); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(vscode.workspace.openTextDocument).not.toHaveBeenCalled(); + }, + ); + + it('reports when the active playground has no open result', async () => { + activeEditor = makeEditor(sourceUri, 'documentdb-playground', vscode.ViewColumn.One); + vi.mocked(provider.focusResult).mockResolvedValue(false); + + await focusPlaygroundResult(context); + + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith('No Query Playground result is open.'); + }); + + it.each([undefined, 'javascript'])('reports no result without a target (%s)', async (languageId) => { + activeEditor = languageId ? makeEditor(sourceUri, languageId, vscode.ViewColumn.One) : undefined; + + await focusPlaygroundResult(context); + + expect(provider.focusResult).not.toHaveBeenCalled(); + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith('No Query Playground result is open.'); + }); + + it('returns to the exact source in its existing editor group rather than another playground', async () => { + activeEditor = makeEditor( + provider.getResultUri(sourceUri), + 'documentdb-playground-result', + vscode.ViewColumn.Two, + ); + const target = makeEditor(sourceUri, 'documentdb-playground', vscode.ViewColumn.Three); + visibleEditors = [ + makeEditor(vscode.Uri.file('/other.documentdb.js'), 'documentdb-playground', vscode.ViewColumn.One), + target, + activeEditor, + ]; + + await focusPlayground(context); + + expect(vscode.window.showTextDocument).toHaveBeenCalledExactlyOnceWith(target.document, { + viewColumn: vscode.ViewColumn.Three, + preserveFocus: false, + }); + expect(vscode.workspace.openTextDocument).not.toHaveBeenCalled(); + }); + + it('opens a source not currently visible without running or connecting', async () => { + activeEditor = makeEditor( + provider.getResultUri(sourceUri), + 'documentdb-playground-result', + vscode.ViewColumn.Two, + ); + + await focusPlayground(context); + + expect(vscode.workspace.openTextDocument).toHaveBeenCalledOnce(); + expect(vi.mocked(vscode.workspace.openTextDocument).mock.calls[0][0]).toEqual( + expect.objectContaining({ scheme: sourceUri.scheme, path: sourceUri.path }), + ); + expect(vscode.window.showTextDocument).toHaveBeenCalledWith(expect.objectContaining({ uri: sourceUri }), { + viewColumn: vscode.ViewColumn.Active, + preserveFocus: false, + }); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + }); + + it.each([undefined, 'documentdb-playground'])( + 'reports no playground without an active result (%s)', + async (languageId) => { + activeEditor = languageId ? makeEditor(sourceUri, languageId, vscode.ViewColumn.One) : undefined; + + await focusPlayground(context); + + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith( + 'No Query Playground is available to focus.', + ); + expect(vscode.window.showTextDocument).not.toHaveBeenCalled(); + }, + ); + + it('reports when the result source can no longer be opened', async () => { + activeEditor = makeEditor( + provider.getResultUri(sourceUri), + 'documentdb-playground-result', + vscode.ViewColumn.Two, + ); + vi.mocked(vscode.workspace.openTextDocument).mockRejectedValue(new Error('File not found')); + + await focusPlayground(context); + + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith('No Query Playground is available to focus.'); + expect(vscode.window.showTextDocument).not.toHaveBeenCalled(); + }); + + it('does not recreate a closed untitled playground or a stale pre-Save As source', async () => { + const untitledUri = vscode.Uri.parse('untitled:Query-1.documentdb.js'); + activeEditor = makeEditor( + provider.getResultUri(untitledUri), + 'documentdb-playground-result', + vscode.ViewColumn.Two, + ); + const savedEditor = makeEditor( + vscode.Uri.file('/saved.documentdb.js'), + 'documentdb-playground', + vscode.ViewColumn.One, + ); + documents = [savedEditor.document]; + visibleEditors = [savedEditor, activeEditor]; + + await focusPlayground(context); + + expect(vscode.workspace.openTextDocument).not.toHaveBeenCalled(); + expect(vscode.window.showTextDocument).not.toHaveBeenCalled(); + expect(vscode.window.showInformationMessage).toHaveBeenCalledExactlyOnceWith( + 'No Query Playground is available to focus.', + ); + }); + + it('reveals an already-open but hidden untitled playground without creating another document', async () => { + const untitledUri = vscode.Uri.parse('untitled:Query-1.documentdb.js'); + activeEditor = makeEditor( + provider.getResultUri(untitledUri), + 'documentdb-playground-result', + vscode.ViewColumn.Two, + ); + const source = makeEditor(untitledUri, 'documentdb-playground', vscode.ViewColumn.One); + documents = [source.document, activeEditor.document]; + visibleEditors = [activeEditor]; + + await focusPlayground(context); + + expect(vscode.workspace.openTextDocument).not.toHaveBeenCalled(); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(vscode.window.showTextDocument).toHaveBeenCalledExactlyOnceWith(source.document, { + viewColumn: vscode.ViewColumn.Active, + preserveFocus: false, + }); + }); +}); diff --git a/src/commands/playground/focusPlaygroundResult.ts b/src/commands/playground/focusPlaygroundResult.ts new file mode 100644 index 000000000..e062156a3 --- /dev/null +++ b/src/commands/playground/focusPlaygroundResult.ts @@ -0,0 +1,52 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import * as l10n from '@vscode/l10n'; +import * as vscode from 'vscode'; +import { PLAYGROUND_LANGUAGE_ID } from '../../documentdb/playground/constants'; +import { ext } from '../../extensionVariables'; + +export async function focusPlaygroundResult(_context: IActionContext): Promise { + const document = vscode.window.activeTextEditor?.document; + const sourceUri = + document?.languageId === PLAYGROUND_LANGUAGE_ID + ? document.uri + : document && ext.playgroundResultProvider.getSourceUri(document.uri); + if (!sourceUri || !(await ext.playgroundResultProvider.focusResult(sourceUri))) { + await vscode.window.showInformationMessage(l10n.t('No Query Playground result is open.')); + } +} + +export async function focusPlayground(_context: IActionContext): Promise { + const resultUri = vscode.window.activeTextEditor?.document.uri; + const sourceUri = resultUri && ext.playgroundResultProvider.getSourceUri(resultUri); + if (!sourceUri) { + await vscode.window.showInformationMessage(l10n.t('No Query Playground is available to focus.')); + return; + } + const editor = vscode.window.visibleTextEditors.find( + (candidate) => candidate.document.uri.toString() === sourceUri.toString(), + ); + let document = + editor?.document ?? + vscode.workspace.textDocuments.find((candidate) => candidate.uri.toString() === sourceUri.toString()); + if (!document && sourceUri.scheme === 'untitled') { + await vscode.window.showInformationMessage(l10n.t('No Query Playground is available to focus.')); + return; + } + if (!document) { + try { + document = await vscode.workspace.openTextDocument(sourceUri); + } catch { + await vscode.window.showInformationMessage(l10n.t('No Query Playground is available to focus.')); + return; + } + } + await vscode.window.showTextDocument(document, { + viewColumn: editor?.viewColumn ?? vscode.ViewColumn.Active, + preserveFocus: false, + }); +} diff --git a/src/commands/playground/newPlayground.test.ts b/src/commands/playground/newPlayground.test.ts index df7710c7f..32a6573a2 100644 --- a/src/commands/playground/newPlayground.test.ts +++ b/src/commands/playground/newPlayground.test.ts @@ -3,11 +3,23 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; -import type * as vscode from 'vscode'; +import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import * as vscode from 'vscode'; +import { modifierKey } from '../../constants'; +import { type DatabaseItemModel } from '../../documentdb/ClustersClient'; import { PLAYGROUND_LANGUAGE_ID } from '../../documentdb/playground/constants'; -import { createPlaygroundFileName } from './newPlayground'; +import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; +import { DocumentDBExperience } from '../../DocumentDBExperiences'; +import { DatabaseItem } from '../../tree/documentdb/DatabaseItem'; +import { type BaseClusterModel, type TreeCluster } from '../../tree/models/BaseClusterModel'; +import { + buildPlaygroundHeader, + createPlaygroundFileName, + newPlayground, + newPlaygroundWithContent, +} from './newPlayground'; function playgroundDocument(fileName: string): vscode.TextDocument { return { @@ -97,3 +109,69 @@ describe('createPlaygroundFileName', () => { expect(fileName).toBe('playground-2.documentdb.js'); }); }); + +describe('buildPlaygroundHeader', () => { + let service: PlaygroundService | undefined; + + afterEach(() => { + service?.dispose(); + vi.restoreAllMocks(); + }); + + it('preserves shortcut guidance and adds palette and context-menu discovery', () => { + expect(buildPlaygroundHeader('my-cluster')).toEqual([ + '// Query Playground: my-cluster', + '//', + `// Use ${modifierKey}+Enter to run the current block or ${modifierKey}+Shift+Enter to run the entire file`, + '// Use the Command Palette (Query Playground) or the editor context menu for all actions.', + '// Note: when running multiple statements, only the last result is displayed', + '', + ]); + }); + + it('uses the shared header for tree-node and provided-content playgrounds', async () => { + const insertedContent: string[] = []; + vi.spyOn(vscode.WorkspaceEdit.prototype, 'insert').mockImplementation( + (_uri: vscode.Uri, _position: vscode.Position, content: string): void => { + insertedContent.push(content); + }, + ); + vi.spyOn(vscode.workspace, 'applyEdit').mockResolvedValue(true); + vi.spyOn(vscode.workspace, 'openTextDocument').mockResolvedValue({ + uri: vscode.Uri.file('playground.documentdb.js'), + } as vscode.TextDocument); + vi.spyOn(vscode.window, 'showTextDocument').mockResolvedValue({} as vscode.TextEditor); + service = PlaygroundService.getInstance(); + const setConnection = vi.spyOn(service, 'setConnection').mockImplementation(() => undefined); + + const context = { + telemetry: { properties: {}, measurements: {} }, + } as IActionContext; + const cluster: TreeCluster = { + clusterId: 'cluster-id', + dbExperience: DocumentDBExperience, + name: 'tree-cluster', + treeId: 'cluster-id', + viewId: 'connections', + }; + const databaseInfo: DatabaseItemModel = { name: 'database' }; + const treeNode = new DatabaseItem(cluster, databaseInfo); + + await newPlayground(context, treeNode); + await newPlaygroundWithContent(context, { + clusterId: 'cluster-id', + clusterDisplayName: 'content-cluster', + databaseName: 'database', + content: 'db.users.find({})', + }); + + expect(insertedContent).toHaveLength(2); + expect(setConnection).toHaveBeenCalledTimes(2); + expect(insertedContent[0]).toBe( + [...buildPlaygroundHeader('tree-cluster'), "db.getCollection('collectionName').find({ })", ''].join('\n'), + ); + expect(insertedContent[1]).toBe( + [...buildPlaygroundHeader('content-cluster'), 'db.users.find({})', ''].join('\n'), + ); + }); +}); diff --git a/src/commands/playground/newPlayground.ts b/src/commands/playground/newPlayground.ts index a133eb182..3a9e34d14 100644 --- a/src/commands/playground/newPlayground.ts +++ b/src/commands/playground/newPlayground.ts @@ -21,6 +21,17 @@ interface PlaygroundFileNameContext { readonly databaseOrCollectionName: string; } +export function buildPlaygroundHeader(clusterName: string): string[] { + return [ + `// Query Playground: ${clusterName}`, + '//', + `// Use ${modifierKey}+Enter to run the current block or ${modifierKey}+Shift+Enter to run the entire file`, + `// ${l10n.t('Use the Command Palette (Query Playground) or the editor context menu for all actions.')}`, + '// Note: when running multiple statements, only the last result is displayed', + '', + ]; +} + /** * Creates a new Query Playground file. * @@ -45,14 +56,9 @@ export async function newPlayground(context: IActionContext, node?: DatabaseItem // Build template — customize when launched from a collection node const collectionName = isCollectionItem(node) ? escapeJsString(node.collectionInfo.name) : 'collectionName'; - const headerComment = `// Query Playground: ${node.cluster.name}`; const template = [ - headerComment, - '//', - `// Use ${modifierKey}+Enter to run the current block or ${modifierKey}+Shift+Enter to run the entire file`, - '// Note: when running multiple statements, only the last result is displayed', - '', + ...buildPlaygroundHeader(node.cluster.name), `db.getCollection('${collectionName}').find({ })`, '', ].join('\n'); @@ -99,15 +105,7 @@ export async function newPlaygroundWithContent( // ── Telemetry: cross-feature activation ────────────────────────── context.telemetry.properties.activationSource = 'crossFeature'; - const template = [ - `// Query Playground: ${params.clusterDisplayName}`, - '//', - `// Use ${modifierKey}+Enter to run the current block or ${modifierKey}+Shift+Enter to run the entire file`, - '// Note: when running multiple statements, only the last result is displayed', - '', - params.content, - '', - ].join('\n'); + const template = [...buildPlaygroundHeader(params.clusterDisplayName), params.content, ''].join('\n'); await createPlaygroundWithContent(template, { clusterId: params.clusterId, diff --git a/src/commands/playground/playground.packageJson.test.ts b/src/commands/playground/playground.packageJson.test.ts new file mode 100644 index 000000000..4487c15ec --- /dev/null +++ b/src/commands/playground/playground.packageJson.test.ts @@ -0,0 +1,264 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { beforeAll, describe, expect, it } from 'vitest'; + +import * as fs from 'fs'; +import * as path from 'path'; + +interface MenuContribution { + readonly command: string; + readonly when: string; + readonly group?: string; +} + +interface CommandContribution { + readonly command: string; + readonly title: string; + readonly shortTitle?: string; + readonly icon?: string; +} + +interface KeybindingContribution { + readonly command: string; + readonly key: string; + readonly mac: string; + readonly when: string; + readonly args?: { readonly screenReaderMode: boolean }; +} + +interface ConfigurationContribution { + readonly title: string; + readonly properties: Record< + string, + { + readonly type: string; + readonly default: unknown; + readonly enum?: readonly string[]; + readonly description: string; + readonly enumDescriptions?: readonly string[]; + } + >; +} + +interface PackageContributions { + readonly commands: readonly CommandContribution[]; + readonly keybindings: readonly KeybindingContribution[]; + readonly configuration: readonly ConfigurationContribution[]; + readonly menus: { + readonly 'editor/context': readonly MenuContribution[]; + readonly 'editor/title': readonly MenuContribution[]; + readonly commandPalette: readonly MenuContribution[]; + }; +} + +describe('query playground command contributions', () => { + let contributes: PackageContributions; + + beforeAll(() => { + const packageJson = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../../../package.json'), 'utf8')) as { + contributes: PackageContributions; + }; + contributes = packageJson.contributes; + }); + + it('contributes keyboard-reachable Open Block commands with their icons', () => { + expect(contributes.commands).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + command: 'vscode-documentdb.command.playground.openQueryInShell', + title: '%playground.openBlockInShell%', + icon: '$(terminal)', + }), + expect.objectContaining({ + command: 'vscode-documentdb.command.playground.openQueryInCollectionView', + title: '%playground.openBlockInCollectionView%', + icon: '$(screen-full)', + }), + ]), + ); + }); + + it.each(['vscode-documentdb.command.playground.runAll', 'vscode-documentdb.command.playground.runSelected'])( + 'exposes %s in the palette for playground editors', + (command) => { + expect(contributes.menus.commandPalette).toContainEqual( + expect.objectContaining({ command, when: "editorLangId == 'documentdb-playground'" }), + ); + }, + ); + + it.each([ + 'vscode-documentdb.command.playground.openQueryInShell', + 'vscode-documentdb.command.playground.openQueryInCollectionView', + ])('gates %s on connection and current-block code in the palette and editor context menu', (command) => { + for (const menu of [contributes.menus.commandPalette, contributes.menus['editor/context']]) { + const entry = menu.find((candidate) => candidate.command === command); + expect(entry?.when).toBe( + "editorLangId == 'documentdb-playground' && documentdbPlaygroundConnected && documentdbPlaygroundBlockHasCode", + ); + } + }); + + it('puts only connection and Run All actions inline in the editor title', () => { + expect(contributes.menus['editor/title']).toEqual([ + { + command: 'vscode-documentdb.command.playground.showConnectionInfo', + when: "resourceLangId == 'documentdb-playground'", + group: 'navigation@1', + }, + { + command: 'vscode-documentdb.command.playground.runAll', + when: "resourceLangId == 'documentdb-playground'", + group: 'navigation@2', + }, + { + command: 'vscode-documentdb.command.playground.runSelected', + when: "resourceLangId == 'documentdb-playground'", + group: '2_playground@1', + }, + { + command: 'vscode-documentdb.command.playground.openQueryInShell', + when: "resourceLangId == 'documentdb-playground'", + group: '2_playground@2', + }, + { + command: 'vscode-documentdb.command.playground.openQueryInCollectionView', + when: "resourceLangId == 'documentdb-playground'", + group: '2_playground@3', + }, + ]); + }); + + it('uses a localized state-neutral short title without changing the full connection command labels', () => { + expect(contributes.commands).toContainEqual( + expect.objectContaining({ + command: 'vscode-documentdb.command.playground.showConnectionInfo', + title: 'Query Playground: Change Connection', + shortTitle: '%playground.connectionShortTitle%', + }), + ); + expect(contributes.commands).toContainEqual( + expect.objectContaining({ + command: 'vscode-documentdb.command.playground.connect', + title: 'Query Playground: Connect to Database', + }), + ); + const localized = JSON.parse( + fs.readFileSync(path.resolve(__dirname, '../../../package.nls.json'), 'utf8'), + ) as Record; + expect(localized['playground.connectionShortTitle']).toBe('Playground Connection…'); + }); + + it('uses state-specific connection commands in the palette', () => { + expect(contributes.menus.commandPalette).toContainEqual( + expect.objectContaining({ + command: 'vscode-documentdb.command.playground.connect', + when: "editorLangId == 'documentdb-playground' && !documentdbPlaygroundConnected", + }), + ); + expect(contributes.menus.commandPalette).toContainEqual( + expect.objectContaining({ + command: 'vscode-documentdb.command.playground.showConnectionInfo', + when: "editorLangId == 'documentdb-playground' && documentdbPlaygroundConnected", + }), + ); + }); + + it.each([ + [ + 'editor/context', + 'vscode-documentdb.command.playground.runSelected', + "editorLangId == 'documentdb-playground'", + ], + [ + 'editor/title', + 'vscode-documentdb.command.playground.runSelected', + "resourceLangId == 'documentdb-playground'", + ], + ])('contributes Run Block to %s for playground editors', (menu, command, when) => { + const entries = contributes.menus[menu as 'editor/context' | 'editor/title']; + expect(entries).toContainEqual(expect.objectContaining({ command, when })); + }); + + it('gates each inline editor-title action on its group language', () => { + const title = contributes.menus['editor/title']; + expect(title).toContainEqual( + expect.objectContaining({ + command: 'vscode-documentdb.command.playground.runAll', + when: "resourceLangId == 'documentdb-playground'", + group: 'navigation@2', + }), + ); + expect(title).toContainEqual( + expect.objectContaining({ + command: 'vscode-documentdb.command.playground.showConnectionInfo', + when: "resourceLangId == 'documentdb-playground'", + group: 'navigation@1', + }), + ); + }); + + it('preserves the original shortcuts and appends their screen-reader variants without new combinations', () => { + const originals = [ + { + command: 'vscode-documentdb.command.playground.runAll', + key: 'ctrl+shift+enter', + mac: 'cmd+shift+enter', + when: "editorLangId == 'documentdb-playground' && editorTextFocus", + }, + { + command: 'vscode-documentdb.command.playground.runSelected', + key: 'ctrl+enter', + mac: 'cmd+enter', + when: "editorLangId == 'documentdb-playground' && editorTextFocus", + }, + ]; + expect(contributes.keybindings).toEqual([ + ...originals, + ...originals.map((entry) => ({ + ...entry, + when: `${entry.when} && accessibilityModeEnabled`, + args: { screenReaderMode: true }, + })), + ]); + }); + + it('contributes the after-run setting and all localized enum descriptions in Query Playground', () => { + const settings = contributes.configuration.find((entry) => entry.title === 'Query Playground'); + expect(settings?.properties['documentDB.playground.afterRun']).toMatchObject({ + type: 'string', + default: 'auto', + enum: ['auto', 'stay', 'focusResult', 'notify'], + description: '%playground.afterRun.description%', + enumDescriptions: [ + '%playground.afterRun.auto%', + '%playground.afterRun.stay%', + '%playground.afterRun.focusResult%', + '%playground.afterRun.notify%', + ], + }); + const localized = JSON.parse( + fs.readFileSync(path.resolve(__dirname, '../../../package.nls.json'), 'utf8'), + ) as Record; + for (const key of settings?.properties['documentDB.playground.afterRun'].enumDescriptions ?? []) { + expect(localized[key.slice(1, -1)]).toBeTruthy(); + } + }); + + it.each([ + ['focusResult', "editorLangId == 'documentdb-playground'", 'Query Playground: Focus Result'], + ['focusPlayground', "resourceScheme == 'documentdb-playground-result'", 'Query Playground: Focus Playground'], + ])('contributes the localized %s palette command without a shortcut', (id, when, title) => { + const command = `vscode-documentdb.command.playground.${id}`; + expect(contributes.commands).toContainEqual(expect.objectContaining({ command, title: `%playground.${id}%` })); + expect(contributes.menus.commandPalette).toContainEqual({ command, when }); + expect(contributes.keybindings.some((entry) => entry.command === command)).toBe(false); + const localized = JSON.parse( + fs.readFileSync(path.resolve(__dirname, '../../../package.nls.json'), 'utf8'), + ) as Record; + expect(localized[`playground.${id}`]).toBe(title); + }); +}); diff --git a/src/commands/playground/playgroundCommands.test.ts b/src/commands/playground/playgroundCommands.test.ts new file mode 100644 index 000000000..7a62657e2 --- /dev/null +++ b/src/commands/playground/playgroundCommands.test.ts @@ -0,0 +1,423 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import * as vscode from 'vscode'; +import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; +import { ShellCommandIds } from '../../documentdb/shell/constants'; +import { settingsKeys } from '../../settingsKeys'; +import { executePlaygroundCode } from './executePlaygroundCode'; +import { playgroundOpenQueryInCollectionView } from './playgroundOpenInCollectionView'; +import { playgroundOpenQueryInShell } from './playgroundOpenInShell'; +import { runAll } from './runAll'; +import { runSelected } from './runSelected'; + +vi.mock('./executePlaygroundCode', () => ({ + executePlaygroundCode: vi.fn(), +})); + +function makeEditor(uri: vscode.Uri, text: string, line: number): vscode.TextEditor { + const lines = text.split('\n'); + const document = { + uri, + languageId: 'documentdb-playground', + lineCount: lines.length, + lineAt(index: number) { + return { text: lines[index] ?? '' }; + }, + getText(range?: vscode.Range) { + if (!range) { + return text; + } + const start = + lines.slice(0, range.start.line).reduce((total, value) => total + value.length + 1, 0) + + range.start.character; + const end = + lines.slice(0, range.end.line).reduce((total, value) => total + value.length + 1, 0) + + range.end.character; + return text.substring(start, end); + }, + } as unknown as vscode.TextDocument; + return { + document, + selection: { active: new vscode.Position(line, 0) }, + } as unknown as vscode.TextEditor; +} + +function makeContext(): { + telemetry: { properties: Record; measurements: Record }; +} { + return { + telemetry: { properties: {}, measurements: {} }, + }; +} + +describe('playground commands', () => { + let activeEditor: vscode.TextEditor | undefined; + let visibleEditors: vscode.TextEditor[]; + let service: PlaygroundService; + + beforeEach(() => { + visibleEditors = []; + vi.spyOn(vscode.window, 'activeTextEditor', 'get').mockImplementation(() => activeEditor); + vi.spyOn(vscode.window, 'visibleTextEditors', 'get').mockImplementation(() => visibleEditors); + vi.spyOn(vscode.window, 'showInformationMessage').mockResolvedValue(undefined); + vi.spyOn(vscode.window, 'showWarningMessage').mockResolvedValue(undefined); + vi.spyOn(vscode.commands, 'executeCommand').mockResolvedValue(undefined); + vi.spyOn(vscode.workspace, 'getConfiguration').mockReturnValue({ + get: () => false, + } as unknown as vscode.WorkspaceConfiguration); + service = PlaygroundService.getInstance(); + }); + + afterEach(() => { + service.dispose(); + vi.restoreAllMocks(); + vi.clearAllMocks(); + }); + + it('runs the cursor block without arguments and preserves cursor telemetry', async () => { + const editor = makeEditor( + vscode.Uri.file('/active.documentdb.js'), + 'db.users.find({});\n\ndb.orders.find({});', + 0, + ); + activeEditor = editor; + visibleEditors = [editor]; + const context = makeContext(); + + await runSelected(context as never); + + expect(executePlaygroundCode).toHaveBeenCalledWith('db.users.find({});', 'runSelected', editor.document.uri, { + afterRun: 'stay', + }); + expect(context.telemetry.properties).toMatchObject({ + activationSource: 'playgroundOther', + selectionSource: 'cursor', + }); + expect(context.telemetry.measurements.blockCount).toBe(2); + }); + + it('runs the preceding block from a blank line and preserves fallback telemetry', async () => { + const editor = makeEditor( + vscode.Uri.file('/active.documentdb.js'), + 'db.users.find({});\n\ndb.orders.find({});', + 1, + ); + activeEditor = editor; + visibleEditors = [editor]; + const context = makeContext(); + + await runSelected(context as never); + + expect(executePlaygroundCode).toHaveBeenCalledWith('db.users.find({});', 'runSelected', editor.document.uri, { + afterRun: 'stay', + }); + expect(context.telemetry.properties.selectionSource).toBe('fallback'); + }); + + it('preserves explicit Run Block CodeLens ranges', async () => { + const editor = makeEditor( + vscode.Uri.file('/active.documentdb.js'), + 'db.users.find({});\n\ndb.orders.find({});', + 0, + ); + activeEditor = editor; + visibleEditors = [editor]; + const context = makeContext(); + + await runSelected(context as never, 2, 2); + + expect(executePlaygroundCode).toHaveBeenCalledWith('db.orders.find({});', 'runSelected', editor.document.uri, { + afterRun: 'stay', + }); + expect(context.telemetry.properties).toMatchObject({ + activationSource: 'playgroundCodeLens', + selectionSource: 'codeLens', + }); + }); + + it('targets an inactive editor group when an editor-menu URI is supplied', async () => { + const active = makeEditor(vscode.Uri.file('/active.documentdb.js'), 'db.active.find({});', 0); + const target = makeEditor(vscode.Uri.file('/target.documentdb.js'), 'db.target.find({});', 0); + activeEditor = active; + visibleEditors = [active, target]; + const context = makeContext(); + + await runSelected(context as never, target.document.uri); + + expect(executePlaygroundCode).toHaveBeenCalledWith('db.target.find({});', 'runSelected', target.document.uri, { + afterRun: 'stay', + }); + expect(context.telemetry.properties.activationSource).toBe('playgroundEditorMenu'); + }); + + it('targets the clicked inactive playground when editor-title context is supplied', async () => { + const active = makeEditor(vscode.Uri.file('/active.documentdb.js'), 'db.active.find({});', 0); + const target = makeEditor(vscode.Uri.file('/target.documentdb.js'), 'db.target.find({});', 0); + activeEditor = active; + visibleEditors = [active, target]; + const context = makeContext(); + + await runSelected(context as never, target.document.uri, { groupId: 2, editorIndex: 0 }); + + expect(executePlaygroundCode).toHaveBeenCalledWith('db.target.find({});', 'runSelected', target.document.uri, { + afterRun: 'stay', + }); + expect(context.telemetry.properties.activationSource).toBe('playgroundEditorMenu'); + }); + + it('opens the no-argument current block in Shell using the visible editor connection', async () => { + const editor = makeEditor(vscode.Uri.file('/active.documentdb.js'), '// heading\n\ndb.users.find({});', 2); + activeEditor = editor; + visibleEditors = [editor]; + service.setConnection(editor.document.uri, { + clusterId: 'cluster', + clusterDisplayName: 'Cluster', + databaseName: 'database', + }); + const context = makeContext(); + + await playgroundOpenQueryInShell(context as never); + + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + ShellCommandIds.openWithInput, + expect.objectContaining({ initialInput: 'db.users.find({});' }), + ); + expect(context.telemetry.properties.activationSource).toBe('playgroundOther'); + }); + + it('preserves explicit Open CodeLens ranges and targets their editor', async () => { + const active = makeEditor(vscode.Uri.file('/active.documentdb.js'), 'db.active.find({});', 0); + const target = makeEditor( + vscode.Uri.file('/target.documentdb.js'), + 'db.target.find({});\n\ndb.orders.find({});', + 0, + ); + activeEditor = active; + visibleEditors = [active, target]; + service.setConnection(target.document.uri, { + clusterId: 'cluster', + clusterDisplayName: 'Cluster', + databaseName: 'database', + }); + const context = makeContext(); + + await playgroundOpenQueryInShell(context as never, target.document.uri, 2, 2); + + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + ShellCommandIds.openWithInput, + expect.objectContaining({ initialInput: 'db.orders.find({});' }), + ); + expect(context.telemetry.properties.activationSource).toBe('playgroundCodeLens'); + }); + + it('opens the no-argument current block in Collection View', async () => { + const editor = makeEditor(vscode.Uri.file('/active.documentdb.js'), 'db.users.find({ active: true });', 0); + activeEditor = editor; + visibleEditors = [editor]; + service.setConnection(editor.document.uri, { + clusterId: 'cluster', + clusterDisplayName: 'Cluster', + databaseName: 'database', + }); + const context = makeContext(); + + await playgroundOpenQueryInCollectionView(context as never); + + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + 'vscode-documentdb.command.internal.containerView.open', + expect.objectContaining({ + collectionName: 'users', + databaseName: 'database', + }), + ); + }); + + describe.each([ + ['Shell', playgroundOpenQueryInShell, ShellCommandIds.openWithInput, { initialInput: 'db.target.find({});' }], + [ + 'Collection View', + playgroundOpenQueryInCollectionView, + 'vscode-documentdb.command.internal.containerView.open', + { collectionName: 'target' }, + ], + ] as const)('Open Block in %s target validation', (_label, command, destination, expectedPayload) => { + it.each(['// db.target.find({});', '/*\ndb.target.find({});\n*/', ' \n\t'])( + 'rejects a URI-targeted block containing no code: %j', + async (text) => { + const active = makeEditor(vscode.Uri.file('/active.documentdb.js'), 'db.active.find({});', 0); + const target = makeEditor(vscode.Uri.file('/target.documentdb.js'), text, 0); + activeEditor = active; + visibleEditors = [active, target]; + service.setConnection(active.document.uri, { + clusterId: 'active-cluster', + clusterDisplayName: 'Active Cluster', + databaseName: 'active-database', + }); + service.setConnection(target.document.uri, { + clusterId: 'target-cluster', + clusterDisplayName: 'Target Cluster', + databaseName: 'target-database', + }); + const context = makeContext(); + + await command(context as never, target.document.uri); + + expect(vscode.window.showInformationMessage).toHaveBeenCalledExactlyOnceWith( + 'No code to run. Place the cursor in a code block.', + ); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + expect(context.telemetry.properties.activationSource).toBe('playgroundEditorMenu'); + }, + ); + + it('rejects a disconnected URI target even when the active playground is connected', async () => { + const active = makeEditor(vscode.Uri.file('/active.documentdb.js'), 'db.active.find({});', 0); + const target = makeEditor(vscode.Uri.file('/target.documentdb.js'), 'db.target.find({});', 0); + activeEditor = active; + visibleEditors = [active, target]; + service.setConnection(active.document.uri, { + clusterId: 'active-cluster', + clusterDisplayName: 'Active Cluster', + databaseName: 'active-database', + }); + + await command(makeContext() as never, target.document.uri); + + expect(vscode.window.showWarningMessage).toHaveBeenCalledExactlyOnceWith( + 'This playground has no connection.', + ); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); + + it.each([ + ['editor menu', undefined, 'playgroundEditorMenu'], + ['CodeLens', [2, 2], 'playgroundCodeLens'], + ] as const)( + 'preserves the valid URI target and connection from %s', + async (_source, range, activationSource) => { + const active = makeEditor(vscode.Uri.file('/active.documentdb.js'), 'db.active.find({});', 0); + const target = makeEditor( + vscode.Uri.file('/target.documentdb.js'), + 'db.first.find({});\n\ndb.target.find({});', + range ? 0 : 2, + ); + activeEditor = active; + visibleEditors = [active, target]; + service.setConnection(active.document.uri, { + clusterId: 'active-cluster', + clusterDisplayName: 'Active Cluster', + databaseName: 'active-database', + }); + service.setConnection(target.document.uri, { + clusterId: 'target-cluster', + clusterDisplayName: 'Target Cluster', + databaseName: 'target-database', + }); + const context = makeContext(); + + await command(context as never, target.document.uri, ...(range ?? [])); + + expect(vscode.commands.executeCommand).toHaveBeenCalledExactlyOnceWith( + destination, + expect.objectContaining({ + clusterId: 'target-cluster', + clusterDisplayName: 'Target Cluster', + databaseName: 'target-database', + ...expectedPayload, + }), + ); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + expect(context.telemetry.properties.activationSource).toBe(activationSource); + }, + ); + }); + + it('attributes the explicit Run All CodeLens marker once', async () => { + const editor = makeEditor(vscode.Uri.file('/active.documentdb.js'), 'db.users.find({});', 0); + activeEditor = editor; + visibleEditors = [editor]; + const context = makeContext(); + + await runAll(context as never, { activationSource: 'playgroundCodeLens' }); + + expect(context.telemetry.properties.activationSource).toBe('playgroundCodeLens'); + expect(executePlaygroundCode).toHaveBeenCalledWith('db.users.find({});', 'runAll', editor.document.uri, { + afterRun: 'stay', + }); + }); + + describe.each([ + ['Run All', runAll, 'runAll'], + ['Run Block', runSelected, 'runSelected'], + ] as const)('%s after-run behavior', (_label, command, runMode) => { + it.each([ + ['auto', false, 'stay'], + ['auto', true, 'focusResult'], + ['stay', true, 'stay'], + ['focusResult', false, 'focusResult'], + ['notify', true, 'notify'], + ] as const)( + 'resolves %s with screenReaderMode=%s at invocation', + async (setting, screenReaderMode, afterRun) => { + const editor = makeEditor(vscode.Uri.file('/active.documentdb.js'), 'db.users.find({});', 0); + activeEditor = editor; + visibleEditors = [editor]; + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: (key: string): unknown => (key === settingsKeys.playgroundAfterRun ? setting : false), + } as vscode.WorkspaceConfiguration); + const context = makeContext(); + + await command(context as never, ...(screenReaderMode ? [{ screenReaderMode: true }] : [])); + + expect(executePlaygroundCode).toHaveBeenCalledWith('db.users.find({});', runMode, editor.document.uri, { + afterRun, + }); + expect(context.telemetry.properties).toMatchObject({ + afterRun, + screenReaderMode: screenReaderMode ? 'true' : 'false', + activationSource: screenReaderMode ? 'playgroundScreenReaderKeybinding' : 'playgroundOther', + }); + }, + ); + + it.each(['stay', 'focusResult', 'notify'] as const)( + 'applies explicit %s to CodeLens and menu invocation', + async (afterRun) => { + const editor = makeEditor(vscode.Uri.file('/active.documentdb.js'), 'db.users.find({});', 0); + activeEditor = editor; + visibleEditors = [editor]; + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: (key: string): unknown => (key === settingsKeys.playgroundAfterRun ? afterRun : false), + } as vscode.WorkspaceConfiguration); + const args = runMode === 'runAll' ? [{ activationSource: 'playgroundCodeLens' }] : [0, 0]; + + await command(makeContext() as never, ...args); + await command(makeContext() as never, editor.document.uri); + + expect(executePlaygroundCode).toHaveBeenCalledTimes(2); + expect(executePlaygroundCode).toHaveBeenNthCalledWith( + 1, + 'db.users.find({});', + runMode, + editor.document.uri, + { afterRun }, + ); + expect(executePlaygroundCode).toHaveBeenNthCalledWith( + 2, + 'db.users.find({});', + runMode, + editor.document.uri, + { afterRun }, + ); + }, + ); + }); +}); diff --git a/src/commands/playground/playgroundInvocation.test.ts b/src/commands/playground/playgroundInvocation.test.ts new file mode 100644 index 000000000..ee285c7bd --- /dev/null +++ b/src/commands/playground/playgroundInvocation.test.ts @@ -0,0 +1,102 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import * as vscode from 'vscode'; +import { PLAYGROUND_LANGUAGE_ID } from '../../documentdb/playground/constants'; +import { parsePlaygroundInvocation, resolvePlaygroundEditor } from './playgroundInvocation'; + +function makeEditor(uri: vscode.Uri, languageId = PLAYGROUND_LANGUAGE_ID): vscode.TextEditor { + return { document: { uri, languageId } } as unknown as vscode.TextEditor; +} + +describe('parsePlaygroundInvocation', () => { + it('recognizes the existing Run Block CodeLens range', () => { + expect(parsePlaygroundInvocation([2, 4])).toEqual({ + activationSource: 'playgroundCodeLens', + range: { startLine: 2, endLine: 4 }, + screenReaderMode: false, + }); + }); + + it('recognizes the existing Open CodeLens arguments', () => { + const uri = vscode.Uri.file('/playground.documentdb.js'); + expect(parsePlaygroundInvocation([uri, 2, 4])).toEqual({ + activationSource: 'playgroundCodeLens', + uri, + range: { startLine: 2, endLine: 4 }, + screenReaderMode: false, + }); + }); + + it('recognizes editor-menu URIs and the bounded Run All marker', () => { + const uri = vscode.Uri.file('/playground.documentdb.js'); + expect(parsePlaygroundInvocation([uri])).toMatchObject({ + activationSource: 'playgroundEditorMenu', + uri, + }); + expect(parsePlaygroundInvocation([{ activationSource: 'playgroundCodeLens' }])).toMatchObject({ + activationSource: 'playgroundCodeLens', + }); + expect( + parsePlaygroundInvocation([{ activationSource: 'playgroundCodeLens', extra: true }]).activationSource, + ).toBe('playgroundOther'); + }); + + it('preserves the URI from editor-title invocation context', () => { + const uri = vscode.Uri.file('/playground.documentdb.js'); + expect(parsePlaygroundInvocation([uri, { groupId: 2, editorIndex: 0 }])).toEqual({ + activationSource: 'playgroundEditorMenu', + uri, + screenReaderMode: false, + }); + }); + + it('recognizes only supported screen-reader objects', () => { + expect(parsePlaygroundInvocation([{ screenReaderMode: true }])).toEqual({ + activationSource: 'playgroundScreenReaderKeybinding', + screenReaderMode: true, + }); + expect(parsePlaygroundInvocation([{ screenReaderMode: false }]).activationSource).toBe('playgroundOther'); + }); + + it.each([['playgroundEditorMenu'], ['playgroundScreenReaderKeybinding'], ['unbounded-source']])( + 'does not accept a caller-supplied telemetry string %s', + (activationSource) => { + expect(parsePlaygroundInvocation([{ activationSource }]).activationSource).toBe('playgroundOther'); + expect(parsePlaygroundInvocation([activationSource]).activationSource).toBe('playgroundOther'); + }, + ); +}); + +describe('resolvePlaygroundEditor', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('uses the active playground when no URI is supplied', () => { + const active = makeEditor(vscode.Uri.file('/active.documentdb.js')); + vi.spyOn(vscode.window, 'activeTextEditor', 'get').mockReturnValue(active); + expect(resolvePlaygroundEditor(undefined)).toBe(active); + }); + + it('targets a matching inactive visible editor group instead of another active playground', () => { + const active = makeEditor(vscode.Uri.file('/active.documentdb.js')); + const target = makeEditor(vscode.Uri.file('/target.documentdb.js')); + vi.spyOn(vscode.window, 'activeTextEditor', 'get').mockReturnValue(active); + vi.spyOn(vscode.window, 'visibleTextEditors', 'get').mockReturnValue([active, target]); + + expect(resolvePlaygroundEditor(target.document.uri)).toBe(target); + }); + + it('does not use another active playground when the requested URI is not visible', () => { + const active = makeEditor(vscode.Uri.file('/active.documentdb.js')); + vi.spyOn(vscode.window, 'activeTextEditor', 'get').mockReturnValue(active); + vi.spyOn(vscode.window, 'visibleTextEditors', 'get').mockReturnValue([active]); + + expect(resolvePlaygroundEditor(vscode.Uri.file('/missing.documentdb.js'))).toBeUndefined(); + }); +}); diff --git a/src/commands/playground/playgroundInvocation.ts b/src/commands/playground/playgroundInvocation.ts new file mode 100644 index 000000000..23c85b74a --- /dev/null +++ b/src/commands/playground/playgroundInvocation.ts @@ -0,0 +1,102 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as vscode from 'vscode'; +import { PLAYGROUND_LANGUAGE_ID } from '../../documentdb/playground/constants'; + +export type PlaygroundActivationSource = + | 'playgroundCodeLens' + | 'playgroundEditorMenu' + | 'playgroundScreenReaderKeybinding' + | 'playgroundOther'; + +export interface PlaygroundInvocation { + readonly activationSource: PlaygroundActivationSource; + readonly uri?: vscode.Uri; + readonly range?: { readonly startLine: number; readonly endLine: number }; + readonly screenReaderMode: boolean; +} + +function isUri(value: unknown): value is vscode.Uri { + return ( + value instanceof vscode.Uri || + (value !== null && + typeof value === 'object' && + 'scheme' in value && + typeof value.scheme === 'string' && + 'path' in value && + typeof value.path === 'string' && + 'toString' in value && + typeof value.toString === 'function') + ); +} + +export function parsePlaygroundInvocation(args: readonly unknown[]): PlaygroundInvocation { + if (args.length === 2 && typeof args[0] === 'number' && typeof args[1] === 'number') { + return { + activationSource: 'playgroundCodeLens', + range: { startLine: args[0], endLine: args[1] }, + screenReaderMode: false, + }; + } + + if (args.length === 3 && isUri(args[0]) && typeof args[1] === 'number' && typeof args[2] === 'number') { + return { + activationSource: 'playgroundCodeLens', + uri: args[0], + range: { startLine: args[1], endLine: args[2] }, + screenReaderMode: false, + }; + } + + if (isUri(args[0])) { + return { + activationSource: 'playgroundEditorMenu', + uri: args[0], + screenReaderMode: false, + }; + } + + const first = args[0]; + if (args.length === 1 && first && typeof first === 'object') { + if ('screenReaderMode' in first && first.screenReaderMode === true) { + return { + activationSource: 'playgroundScreenReaderKeybinding', + screenReaderMode: true, + }; + } + if ( + Object.keys(first).length === 1 && + 'activationSource' in first && + first.activationSource === 'playgroundCodeLens' + ) { + return { + activationSource: 'playgroundCodeLens', + screenReaderMode: false, + }; + } + } + + return { + activationSource: 'playgroundOther', + screenReaderMode: false, + }; +} + +export function resolvePlaygroundEditor(uri: vscode.Uri | undefined): vscode.TextEditor | undefined { + const active = vscode.window.activeTextEditor; + if (!uri) { + return active?.document.languageId === PLAYGROUND_LANGUAGE_ID ? active : undefined; + } + + if (active?.document.languageId === PLAYGROUND_LANGUAGE_ID && active.document.uri.toString() === uri.toString()) { + return active; + } + + return vscode.window.visibleTextEditors.find( + (editor) => + editor.document.languageId === PLAYGROUND_LANGUAGE_ID && editor.document.uri.toString() === uri.toString(), + ); +} diff --git a/src/commands/playground/playgroundOpenInCollectionView.ts b/src/commands/playground/playgroundOpenInCollectionView.ts index 1ec14d1ab..136474323 100644 --- a/src/commands/playground/playgroundOpenInCollectionView.ts +++ b/src/commands/playground/playgroundOpenInCollectionView.ts @@ -9,7 +9,9 @@ import * as vscode from 'vscode'; import { extractCollectionName } from '../../documentdb/playground/extractCollectionName'; import { parseFindExpression } from '../../documentdb/playground/parseFindExpression'; import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; +import { blockContainsCode, detectBlocks, resolveBlockAtLine } from '../../documentdb/playground/statementDetector'; import { Views } from '../../documentdb/Views'; +import { parsePlaygroundInvocation, resolvePlaygroundEditor } from './playgroundInvocation'; /** * Opens the current playground code block in Collection View. @@ -19,26 +21,31 @@ import { Views } from '../../documentdb/Views'; * * Arguments: [uri: vscode.Uri, startLine: number, endLine: number] */ -export async function playgroundOpenQueryInCollectionView( - context: IActionContext, - uri?: vscode.Uri, - startLine?: number, - endLine?: number, -): Promise { - if (!uri || startLine === undefined || endLine === undefined) { +export async function playgroundOpenQueryInCollectionView(context: IActionContext, ...args: unknown[]): Promise { + const invocation = parsePlaygroundInvocation(args); + context.telemetry.properties.activationSource = invocation.activationSource; + + const editor = resolvePlaygroundEditor(invocation.uri); + if (!editor) { + void vscode.window.showInformationMessage(l10n.t('No code to run. Place the cursor in a code block.')); return; } const service = PlaygroundService.getInstance(); - const connection = service.getConnection(uri); + const connection = service.getConnection(editor.document.uri); if (!connection) { void vscode.window.showWarningMessage(l10n.t('This playground has no connection.')); return; } - const document = await vscode.workspace.openTextDocument(uri); - const blockText = document.getText(new vscode.Range(startLine, 0, endLine + 1, 0)); + const range = + invocation.range ?? resolveBlockAtLine(detectBlocks(editor.document), editor.selection.active.line)?.block; + if (!range || (!invocation.range && !blockContainsCode(editor.document, range))) { + void vscode.window.showInformationMessage(l10n.t('No code to run. Place the cursor in a code block.')); + return; + } + const blockText = editor.document.getText(new vscode.Range(range.startLine, 0, range.endLine + 1, 0)); const collectionName = extractCollectionName(blockText); if (!collectionName) { @@ -49,8 +56,6 @@ export async function playgroundOpenQueryInCollectionView( // Try to extract filter/project/sort from the code block for a richer handoff const parsed = parseFindExpression(blockText); - // ── Telemetry: cross-feature navigation context ────────────────── - context.telemetry.properties.activationSource = 'playgroundCodeLens'; context.telemetry.properties.hasFilter = parsed.filter ? 'true' : 'false'; try { diff --git a/src/commands/playground/playgroundOpenInShell.ts b/src/commands/playground/playgroundOpenInShell.ts index e20640b6a..558b371e0 100644 --- a/src/commands/playground/playgroundOpenInShell.ts +++ b/src/commands/playground/playgroundOpenInShell.ts @@ -7,7 +7,9 @@ import { type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; +import { blockContainsCode, detectBlocks, resolveBlockAtLine } from '../../documentdb/playground/statementDetector'; import { ShellCommandIds } from '../../documentdb/shell/constants'; +import { parsePlaygroundInvocation, resolvePlaygroundEditor } from './playgroundInvocation'; /** * Opens the current playground code block in an Interactive Shell. @@ -17,34 +19,37 @@ import { ShellCommandIds } from '../../documentdb/shell/constants'; * * Arguments: [uri: vscode.Uri, startLine: number, endLine: number] */ -export async function playgroundOpenQueryInShell( - context: IActionContext, - uri?: vscode.Uri, - startLine?: number, - endLine?: number, -): Promise { - if (!uri || startLine === undefined || endLine === undefined) { +export async function playgroundOpenQueryInShell(context: IActionContext, ...args: unknown[]): Promise { + const invocation = parsePlaygroundInvocation(args); + context.telemetry.properties.activationSource = invocation.activationSource; + + const editor = resolvePlaygroundEditor(invocation.uri); + if (!editor) { + void vscode.window.showInformationMessage(l10n.t('No code to run. Place the cursor in a code block.')); return; } const service = PlaygroundService.getInstance(); - const connection = service.getConnection(uri); + const connection = service.getConnection(editor.document.uri); if (!connection) { void vscode.window.showWarningMessage(l10n.t('This playground has no connection.')); return; } - const document = await vscode.workspace.openTextDocument(uri); - const blockText = document.getText(new vscode.Range(startLine, 0, endLine + 1, 0)).trim(); + const range = + invocation.range ?? resolveBlockAtLine(detectBlocks(editor.document), editor.selection.active.line)?.block; + if (!range || (!invocation.range && !blockContainsCode(editor.document, range))) { + void vscode.window.showInformationMessage(l10n.t('No code to run. Place the cursor in a code block.')); + return; + } + const blockText = editor.document.getText(new vscode.Range(range.startLine, 0, range.endLine + 1, 0)).trim(); if (!blockText) { + void vscode.window.showInformationMessage(l10n.t('No code to run. Place the cursor in a code block.')); return; } - // ── Telemetry: cross-feature navigation ────────────────────────── - context.telemetry.properties.activationSource = 'playgroundCodeLens'; - await vscode.commands.executeCommand(ShellCommandIds.openWithInput, { clusterId: connection.clusterId, clusterDisplayName: connection.clusterDisplayName, diff --git a/src/commands/playground/runAll.ts b/src/commands/playground/runAll.ts index d2d6a7086..aaeacba25 100644 --- a/src/commands/playground/runAll.ts +++ b/src/commands/playground/runAll.ts @@ -6,16 +6,26 @@ import { type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; -import { PLAYGROUND_LANGUAGE_ID } from '../../documentdb/playground/constants'; +import { resolveAfterRunOutcome } from '../../documentdb/playground/afterRun'; import { settingsKeys } from '../../settingsKeys'; import { executePlaygroundCode } from './executePlaygroundCode'; +import { parsePlaygroundInvocation, resolvePlaygroundEditor } from './playgroundInvocation'; /** * Runs the entire content of the active query playground file. */ -export async function runAll(_context: IActionContext): Promise { - const editor = vscode.window.activeTextEditor; - if (!editor || editor.document.languageId !== PLAYGROUND_LANGUAGE_ID) { +export async function runAll(context: IActionContext, ...args: unknown[]): Promise { + const invocation = parsePlaygroundInvocation(args); + context.telemetry.properties.activationSource = invocation.activationSource; + const afterRun = resolveAfterRunOutcome( + vscode.workspace.getConfiguration().get(settingsKeys.playgroundAfterRun), + invocation.screenReaderMode, + ); + context.telemetry.properties.afterRun = afterRun; + context.telemetry.properties.screenReaderMode = invocation.screenReaderMode ? 'true' : 'false'; + + const editor = resolvePlaygroundEditor(invocation.uri); + if (!editor) { return; } @@ -44,13 +54,13 @@ export async function runAll(_context: IActionContext): Promise { ); if (!confirmed) { - _context.telemetry.properties.runAllDialogConfirmed = 'false'; + context.telemetry.properties.runAllDialogConfirmed = 'false'; return; } - _context.telemetry.properties.runAllDialogConfirmed = 'true'; + context.telemetry.properties.runAllDialogConfirmed = 'true'; } else { - _context.telemetry.properties.runAllDialogConfirmed = 'skipped'; + context.telemetry.properties.runAllDialogConfirmed = 'skipped'; } - await executePlaygroundCode(code, 'runAll', editor.document.uri); + await executePlaygroundCode(code, 'runAll', editor.document.uri, { afterRun }); } diff --git a/src/commands/playground/runSelected.ts b/src/commands/playground/runSelected.ts index d1ccd7793..43ba6e049 100644 --- a/src/commands/playground/runSelected.ts +++ b/src/commands/playground/runSelected.ts @@ -6,9 +6,11 @@ import { type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; -import { PLAYGROUND_LANGUAGE_ID } from '../../documentdb/playground/constants'; -import { detectBlocks, detectCurrentBlock } from '../../documentdb/playground/statementDetector'; +import { resolveAfterRunOutcome } from '../../documentdb/playground/afterRun'; +import { detectBlocks, getBlockText, resolveBlockAtLine } from '../../documentdb/playground/statementDetector'; +import { settingsKeys } from '../../settingsKeys'; import { executePlaygroundCode } from './executePlaygroundCode'; +import { parsePlaygroundInvocation, resolvePlaygroundEditor } from './playgroundInvocation'; /** * Runs the block specified by CodeLens arguments or the current block @@ -18,55 +20,45 @@ import { executePlaygroundCode } from './executePlaygroundCode'; * CodeLens passes `[startLine, endLine]` as arguments so clicking * a per-block "▶ Run" lens executes exactly that block. */ -export async function runSelected(_context: IActionContext, startLine?: number, endLine?: number): Promise { - const editor = vscode.window.activeTextEditor; - if (!editor || editor.document.languageId !== PLAYGROUND_LANGUAGE_ID) { +export async function runSelected(context: IActionContext, ...args: unknown[]): Promise { + const invocation = parsePlaygroundInvocation(args); + context.telemetry.properties.activationSource = invocation.activationSource; + const afterRun = resolveAfterRunOutcome( + vscode.workspace.getConfiguration().get(settingsKeys.playgroundAfterRun), + invocation.screenReaderMode, + ); + context.telemetry.properties.afterRun = afterRun; + context.telemetry.properties.screenReaderMode = invocation.screenReaderMode ? 'true' : 'false'; + + const editor = resolvePlaygroundEditor(invocation.uri); + if (!editor) { return; } let codeToRun: string; let selectionSource: string; - if (startLine !== undefined && endLine !== undefined) { + if (invocation.range) { // Invoked from CodeLens with explicit block range selectionSource = 'codeLens'; - const range = new vscode.Range(startLine, 0, endLine, editor.document.lineAt(endLine).text.length); - codeToRun = editor.document.getText(range); + codeToRun = getBlockText(editor.document, invocation.range); } else { // Run current block at cursor, fall back to preceding block. // Any active selection (e.g. from autocomplete) is intentionally // ignored so we always execute the full block. - selectionSource = 'cursor'; - codeToRun = detectCurrentBlock(editor.document, editor.selection.active); - if (!codeToRun.trim()) { - // Cursor is on a blank line — fall back to the nearest preceding block - // (same behavior as CodeLens resolveActiveBlock) - selectionSource = 'fallback'; - const blocks = detectBlocks(editor.document); - const cursorLine = editor.selection.active.line; - for (let i = blocks.length - 1; i >= 0; i--) { - if (blocks[i].endLine < cursorLine) { - const range = new vscode.Range( - blocks[i].startLine, - 0, - blocks[i].endLine, - editor.document.lineAt(blocks[i].endLine).text.length, - ); - codeToRun = editor.document.getText(range); - break; - } - } - } + const resolved = resolveBlockAtLine(detectBlocks(editor.document), editor.selection.active.line); + selectionSource = resolved?.match === 'preceding' ? 'fallback' : 'cursor'; + codeToRun = resolved ? getBlockText(editor.document, resolved.block) : ''; } - _context.telemetry.properties.selectionSource = selectionSource; + context.telemetry.properties.selectionSource = selectionSource; const blocks = detectBlocks(editor.document); - _context.telemetry.measurements.blockCount = blocks.length; + context.telemetry.measurements.blockCount = blocks.length; if (!codeToRun.trim()) { void vscode.window.showInformationMessage(l10n.t('No code to run. Place the cursor in a code block.')); return; } - await executePlaygroundCode(codeToRun, 'runSelected', editor.document.uri); + await executePlaygroundCode(codeToRun, 'runSelected', editor.document.uri, { afterRun }); } diff --git a/src/documentdb/ClustersExtension.ts b/src/documentdb/ClustersExtension.ts index adde5809d..ca92f92b0 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -72,6 +72,7 @@ import { pasteCollection } from '../commands/pasteCollection/pasteCollection'; import { pasteIndexes } from '../commands/pasteIndexes/pasteIndexes'; import { connectPlayground, showConnectionInfo } from '../commands/playground/connectDatabase'; import { disposeEvaluators, shutdownOrphanedEvaluators } from '../commands/playground/executePlaygroundCode'; +import { focusPlayground, focusPlaygroundResult } from '../commands/playground/focusPlaygroundResult'; import { newPlayground, newPlaygroundWithContent } from '../commands/playground/newPlayground'; import { playgroundOpenQueryInCollectionView } from '../commands/playground/playgroundOpenInCollectionView'; import { playgroundOpenQueryInShell } from '../commands/playground/playgroundOpenInShell'; @@ -142,10 +143,12 @@ import { } from '../utils/commandErrorHandling'; import { withCommandCorrelation, withTreeNodeCommandCorrelation } from '../utils/commandTelemetry'; import { registerClusterDashboardContextMenuCommands } from '../webviews/documentdb/clusterDashboard/clusterDashboardController'; +import { registerCollectionViewColumnContextMenuCommands } from '../webviews/documentdb/collectionView/collectionViewController'; import { EntraErrorExplainer } from './auth/entraErrors/EntraErrorExplainer'; import { PLAYGROUND_FILE_EXTENSION, PLAYGROUND_LANGUAGE_ID, PlaygroundCommandIds } from './playground/constants'; import { PlaygroundBlockHighlighter } from './playground/PlaygroundBlockHighlighter'; import { PlaygroundCodeLensProvider } from './playground/PlaygroundCodeLensProvider'; +import { PlaygroundContextKeyTracker } from './playground/PlaygroundContextKeys'; import { PlaygroundService } from './playground/PlaygroundService'; import { ensureTsPluginStub } from './playground/tsPluginStub'; import { CollectionNameCache } from './query-language/playground-completions/CollectionNameCache'; @@ -288,6 +291,7 @@ export class ClustersExtension implements vscode.Disposable { this.registerDiscoveryTree(activateContext); this.registerHelpAndFeedbackTree(activateContext); registerClusterDashboardContextMenuCommands(ext.context); + registerCollectionViewColumnContextMenuCommands(ext.context); // Initialize TaskService and TaskProgressReportingService TaskProgressReportingService.attach(TaskService); @@ -360,6 +364,7 @@ export class ClustersExtension implements vscode.Disposable { ext.context.subscriptions.push( vscode.languages.registerCodeLensProvider({ language: PLAYGROUND_LANGUAGE_ID }, codeLensProvider), ); + ext.context.subscriptions.push(new PlaygroundContextKeyTracker()); // Register block highlighter for query playground files const blockHighlighter = new PlaygroundBlockHighlighter(ext.context.extensionPath); @@ -573,6 +578,10 @@ export class ClustersExtension implements vscode.Disposable { registerCommand(PlaygroundCommandIds.runSelected, withCommandCorrelation(runSelected)); + registerCommand(PlaygroundCommandIds.focusResult, withCommandCorrelation(focusPlaygroundResult)); + + registerCommand(PlaygroundCommandIds.focusPlayground, withCommandCorrelation(focusPlayground)); + // Register scan schema command (triggered by "Discover Fields" completion item) registerCommand( PlaygroundCommandIds.scanCollectionSchema, diff --git a/src/documentdb/playground/PlaygroundCodeLensProvider.test.ts b/src/documentdb/playground/PlaygroundCodeLensProvider.test.ts index 8533bd27e..5ffacb067 100644 --- a/src/documentdb/playground/PlaygroundCodeLensProvider.test.ts +++ b/src/documentdb/playground/PlaygroundCodeLensProvider.test.ts @@ -74,6 +74,7 @@ describe('PlaygroundCodeLensProvider', () => { const runAllLens = lenses[1]; expect(runAllLens.command?.command).toBe(PlaygroundCommandIds.runAll); expect(runAllLens.command?.title).toContain('Run All'); + expect(runAllLens.command?.arguments).toEqual([{ activationSource: 'playgroundCodeLens' }]); expect(runAllLens.range.start.line).toBe(0); }); diff --git a/src/documentdb/playground/PlaygroundCodeLensProvider.ts b/src/documentdb/playground/PlaygroundCodeLensProvider.ts index 86b5b53a0..d9d8aa85b 100644 --- a/src/documentdb/playground/PlaygroundCodeLensProvider.ts +++ b/src/documentdb/playground/PlaygroundCodeLensProvider.ts @@ -8,7 +8,7 @@ import * as vscode from 'vscode'; import { modifierKey } from '../../constants'; import { PLAYGROUND_LANGUAGE_ID, PlaygroundCommandIds } from './constants'; import { PlaygroundService } from './PlaygroundService'; -import { detectBlocks, findBlockAtLine } from './statementDetector'; +import { blockContainsCode, detectBlocks, resolveBlockAtLine } from './statementDetector'; /** * Provides CodeLens actions for Query Playground files: @@ -49,7 +49,7 @@ export class PlaygroundCodeLensProvider implements vscode.CodeLensProvider, vsco } const cursorLine = e.selections[0].active.line; const blocks = detectBlocks(e.textEditor.document); - const newStart = this.resolveActiveBlock(blocks, cursorLine)?.startLine; + const newStart = resolveBlockAtLine(blocks, cursorLine)?.block.startLine; if (newStart !== this._lastActiveBlockStart) { this._lastActiveBlockStart = newStart; @@ -59,28 +59,6 @@ export class PlaygroundCodeLensProvider implements vscode.CodeLensProvider, vsco ); } - /** - * Find the block at the cursor line. If the cursor is on a blank line - * between blocks, fall back to the nearest preceding block to avoid - * CodeLens flickering. - */ - private resolveActiveBlock( - blocks: ReturnType, - cursorLine: number, - ): ReturnType { - const direct = findBlockAtLine(blocks, cursorLine); - if (direct) { - return direct; - } - // Fall back: find the last block that ends before the cursor - for (let i = blocks.length - 1; i >= 0; i--) { - if (blocks[i].endLine < cursorLine) { - return blocks[i]; - } - } - return undefined; - } - provideCodeLenses(document: vscode.TextDocument): vscode.CodeLens[] { const lenses: vscode.CodeLens[] = []; const service = PlaygroundService.getInstance(); @@ -116,6 +94,7 @@ export class PlaygroundCodeLensProvider implements vscode.CodeLensProvider, vsco new vscode.CodeLens(topRange, { title: runAllTitle, command: PlaygroundCommandIds.runAll, + arguments: [{ activationSource: 'playgroundCodeLens' }], tooltip: runAllTooltip, }), ); @@ -126,7 +105,7 @@ export class PlaygroundCodeLensProvider implements vscode.CodeLensProvider, vsco if (editor && editor.document === document) { const cursorLine = editor.selection.active.line; const blocks = detectBlocks(document); - const activeBlock = this.resolveActiveBlock(blocks, cursorLine); + const activeBlock = resolveBlockAtLine(blocks, cursorLine)?.block; if (activeBlock) { const blockRange = new vscode.Range(activeBlock.startLine, 0, activeBlock.startLine, 0); @@ -145,7 +124,7 @@ export class PlaygroundCodeLensProvider implements vscode.CodeLensProvider, vsco // Navigation CodeLens — open this block in other surfaces // Only show for blocks that contain actual code (not comment-only blocks) - if (displayName && this.blockContainsCode(document, activeBlock)) { + if (displayName && blockContainsCode(document, activeBlock)) { lenses.push( new vscode.CodeLens(blockRange, { title: `$(screen-full) ${l10n.t('Collection View')}`, @@ -167,47 +146,6 @@ export class PlaygroundCodeLensProvider implements vscode.CodeLensProvider, vsco return lenses; } - /** - * Returns true if the block contains at least one line that is not a comment. - * Comment-only blocks (e.g., the header block) should not get navigation lenses. - */ - private blockContainsCode(document: vscode.TextDocument, block: { startLine: number; endLine: number }): boolean { - let inBlockComment = false; - for (let i = block.startLine; i <= block.endLine; i++) { - const trimmed = document.lineAt(i).text.trim(); - if (inBlockComment) { - const closeIdx = trimmed.indexOf('*/'); - if (closeIdx !== -1) { - inBlockComment = false; - // Check if there's code after the closing */ - const afterComment = trimmed.substring(closeIdx + 2).trim(); - if (afterComment.length > 0 && !afterComment.startsWith('//')) { - return true; - } - } - continue; - } - if (trimmed.startsWith('/*')) { - const closeIdx = trimmed.indexOf('*/', 2); - if (closeIdx === -1) { - inBlockComment = true; - continue; - } - // Inline block comment — check if there's code after */ - const afterComment = trimmed.substring(closeIdx + 2).trim(); - if (afterComment.length > 0 && !afterComment.startsWith('//')) { - return true; - } - continue; - } - if (trimmed.startsWith('//') || trimmed.length === 0) { - continue; - } - return true; - } - return false; - } - dispose(): void { this._onDidChangeCodeLenses.dispose(); for (const d of this._disposables) { diff --git a/src/documentdb/playground/PlaygroundContextKeys.test.ts b/src/documentdb/playground/PlaygroundContextKeys.test.ts new file mode 100644 index 000000000..c60068a4d --- /dev/null +++ b/src/documentdb/playground/PlaygroundContextKeys.test.ts @@ -0,0 +1,185 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import * as vscode from 'vscode'; +import { ext } from '../../extensionVariables'; +import { PlaygroundContextKeyTracker, PlaygroundContextKeys } from './PlaygroundContextKeys'; +import { type PlaygroundService } from './PlaygroundService'; +import { PLAYGROUND_LANGUAGE_ID } from './constants'; + +vi.mock('../../extensionVariables', () => ({ + ext: { outputChannel: { error: vi.fn() } }, +})); + +interface MockDocument extends vscode.TextDocument { + lines: string[]; +} + +function makeEditor( + uri: vscode.Uri, + lines: string[], + line: number, +): { + editor: vscode.TextEditor; + document: MockDocument; +} { + const document = { + uri, + languageId: PLAYGROUND_LANGUAGE_ID, + lineCount: lines.length, + lines, + lineAt: (index: number) => ({ text: lines[index] ?? '' }), + } as unknown as MockDocument; + return { + document, + editor: { + document, + selection: { active: new vscode.Position(line, 0) }, + } as unknown as vscode.TextEditor, + }; +} + +describe('PlaygroundContextKeyTracker', () => { + let activeEditor: vscode.TextEditor | undefined; + let stateEvent: vscode.EventEmitter; + let activeEditorListener: ((editor: vscode.TextEditor | undefined) => void) | undefined; + let selectionListener: ((event: vscode.TextEditorSelectionChangeEvent) => void) | undefined; + let documentListener: ((event: vscode.TextDocumentChangeEvent) => void) | undefined; + let connected: boolean; + let tracker: PlaygroundContextKeyTracker; + let disposables: vscode.Disposable[]; + + beforeEach(() => { + connected = true; + stateEvent = new vscode.EventEmitter(); + disposables = []; + vi.spyOn(vscode.window, 'activeTextEditor', 'get').mockImplementation(() => activeEditor); + vi.spyOn(vscode.window, 'onDidChangeActiveTextEditor').mockImplementation((listener) => { + activeEditorListener = listener; + const disposable = { dispose: vi.fn() }; + disposables.push(disposable); + return disposable; + }); + vi.spyOn(vscode.window, 'onDidChangeTextEditorSelection').mockImplementation((listener) => { + selectionListener = listener; + const disposable = { dispose: vi.fn() }; + disposables.push(disposable); + return disposable; + }); + vi.spyOn(vscode.workspace, 'onDidChangeTextDocument').mockImplementation((listener) => { + documentListener = listener; + const disposable = { dispose: vi.fn() }; + disposables.push(disposable); + return disposable; + }); + vi.spyOn(vscode.commands, 'executeCommand').mockResolvedValue(undefined); + }); + + afterEach(() => { + tracker?.dispose(); + stateEvent.dispose(); + vi.restoreAllMocks(); + vi.clearAllMocks(); + }); + + function start(lines = ['db.users.find({});']): { editor: vscode.TextEditor; document: MockDocument } { + const target = makeEditor(vscode.Uri.file('/playground.documentdb.js'), lines, 0); + activeEditor = target.editor; + const service = { + onDidChangeState: stateEvent.event, + isConnected: vi.fn(() => connected), + } as unknown as PlaygroundService; + tracker = new PlaygroundContextKeyTracker(service); + return target; + } + + it('tracks connected and current-block-code state without duplicate context writes', () => { + const target = start(['db.users.find({});', '', '// heading']); + + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + 'setContext', + PlaygroundContextKeys.connected, + true, + ); + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + 'setContext', + PlaygroundContextKeys.blockHasCode, + true, + ); + + vi.mocked(vscode.commands.executeCommand).mockClear(); + tracker.refresh(); + selectionListener?.({ + textEditor: target.editor, + selections: [], + kind: undefined, + }); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); + + it('updates for connection, selection and document changes and is false outside a playground', () => { + const target = start(['// heading', '', 'db.users.find({});']); + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + 'setContext', + PlaygroundContextKeys.blockHasCode, + false, + ); + vi.mocked(vscode.commands.executeCommand).mockClear(); + + target.document.lines[0] = 'db.users.find({});'; + const documentChange: vscode.TextDocumentChangeEvent = { + document: target.document, + contentChanges: [], + reason: undefined, + }; + documentListener?.(documentChange); + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + 'setContext', + PlaygroundContextKeys.blockHasCode, + true, + ); + + target.editor.selection = { + ...target.editor.selection, + active: new vscode.Position(2, 0), + } as vscode.Selection; + vi.mocked(vscode.commands.executeCommand).mockClear(); + selectionListener?.({ textEditor: target.editor } as vscode.TextEditorSelectionChangeEvent); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + + connected = false; + stateEvent.fire(); + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + 'setContext', + PlaygroundContextKeys.connected, + false, + ); + + activeEditor = { document: { languageId: 'plaintext' } } as vscode.TextEditor; + activeEditorListener?.(activeEditor); + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + 'setContext', + PlaygroundContextKeys.blockHasCode, + false, + ); + }); + + it('disposes all scoped listeners', () => { + start(); + tracker.dispose(); + for (const disposable of disposables) { + expect(disposable.dispose).toHaveBeenCalled(); + } + }); + + it('reports rejected context updates', async () => { + vi.mocked(vscode.commands.executeCommand).mockRejectedValueOnce(new Error('context failed')); + start(); + await Promise.resolve(); + expect(ext.outputChannel.error).toHaveBeenCalledWith(expect.stringContaining('context failed')); + }); +}); diff --git a/src/documentdb/playground/PlaygroundContextKeys.ts b/src/documentdb/playground/PlaygroundContextKeys.ts new file mode 100644 index 000000000..163e35609 --- /dev/null +++ b/src/documentdb/playground/PlaygroundContextKeys.ts @@ -0,0 +1,77 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as vscode from 'vscode'; +import { ext } from '../../extensionVariables'; +import { PLAYGROUND_LANGUAGE_ID } from './constants'; +import { PlaygroundService } from './PlaygroundService'; +import { blockContainsCode, detectBlocks, resolveBlockAtLine } from './statementDetector'; + +export const PlaygroundContextKeys = { + connected: 'documentdbPlaygroundConnected', + blockHasCode: 'documentdbPlaygroundBlockHasCode', +} as const; + +export class PlaygroundContextKeyTracker implements vscode.Disposable { + private readonly _service: PlaygroundService; + private readonly _disposables: vscode.Disposable[] = []; + private _connected: boolean | undefined; + private _blockHasCode: boolean | undefined; + + constructor(service: PlaygroundService = PlaygroundService.getInstance()) { + this._service = service; + this._disposables.push( + this._service.onDidChangeState(() => this.refresh()), + vscode.window.onDidChangeActiveTextEditor(() => this.refresh()), + vscode.window.onDidChangeTextEditorSelection((event) => { + if (event.textEditor === vscode.window.activeTextEditor) { + this.refresh(); + } + }), + vscode.workspace.onDidChangeTextDocument((event) => { + if (event.document === vscode.window.activeTextEditor?.document) { + this.refresh(); + } + }), + ); + this.refresh(); + } + + refresh(): void { + const editor = vscode.window.activeTextEditor; + let connected = false; + let blockHasCode = false; + + if (editor?.document.languageId === PLAYGROUND_LANGUAGE_ID) { + connected = this._service.isConnected(editor.document.uri); + const block = resolveBlockAtLine(detectBlocks(editor.document), editor.selection.active.line)?.block; + blockHasCode = block ? blockContainsCode(editor.document, block) : false; + } + + this.updateContextKey(PlaygroundContextKeys.connected, connected, '_connected'); + this.updateContextKey(PlaygroundContextKeys.blockHasCode, blockHasCode, '_blockHasCode'); + } + + dispose(): void { + for (const disposable of this._disposables) { + disposable.dispose(); + } + } + + private updateContextKey(key: string, value: boolean, property: '_connected' | '_blockHasCode'): void { + if (this[property] === value) { + return; + } + this[property] = value; + + void vscode.commands.executeCommand('setContext', key, value).then( + (): void => undefined, + (error: unknown): void => { + const errorMessage = error instanceof Error ? error.message : String(error); + ext.outputChannel.error(vscode.l10n.t('Failed to update Query Playground context: {0}', errorMessage)); + }, + ); + } +} diff --git a/src/documentdb/playground/PlaygroundEvaluator.test.ts b/src/documentdb/playground/PlaygroundEvaluator.test.ts index f86ba3983..8acfe4746 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.test.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.test.ts @@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; import { type callWithTelemetryAndErrorHandling, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { Int32 } from 'bson'; import * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; import { type AuthTraceContext } from '../../utils/authTrace'; @@ -25,7 +26,7 @@ import { type getManagedIdentityAccessToken } from '../auth/managedIdentityToken import { type CachedClusterCredentials } from '../CredentialCache'; import { PlaygroundEvaluator } from './PlaygroundEvaluator'; import { type WorkerSessionCallbacks } from './WorkerSessionManager'; -import { type MainToWorkerMessage, type WorkerToMainMessage } from './workerTypes'; +import { type MainToWorkerMessage, type SerializableExecutionResult, type WorkerToMainMessage } from './workerTypes'; type InitMessage = Extract; type TokenRequest = Extract; @@ -47,6 +48,7 @@ const mocks = vi.hoisted(() => ({ callbacks: undefined as WorkerSessionCallbacks | undefined, initMessage: undefined as InitMessage | undefined, clusterId: undefined as string | undefined, + sendEval: vi.fn<() => Promise<{ result: SerializableExecutionResult }>>(), })); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ @@ -106,7 +108,7 @@ vi.mock('./WorkerSessionManager', () => ({ get workerClusterId(): string | undefined { return mocks.clusterId; }, - sendEval: vi.fn().mockResolvedValue({ result: { type: 'number', printable: '1', durationMs: 0 } }), + sendEval: mocks.sendEval, dispose: vi.fn(), }; }), @@ -137,6 +139,7 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { mocks.callbacks = undefined; mocks.initMessage = undefined; mocks.clusterId = undefined; + mocks.sendEval.mockResolvedValue({ result: { type: 'number', printable: '1', durationMs: 0 } }); customSuffix = undefined; vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ get: vi.fn((_key: string, defaultValue: unknown): unknown => defaultValue), @@ -404,3 +407,48 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { }, ); }); + +describe('PlaygroundEvaluator result deserialization', () => { + const clusterId = 'playground-cluster'; + let evaluator: PlaygroundEvaluator; + + beforeEach(() => { + vi.clearAllMocks(); + mocks.getCredentials.mockReturnValue({ + clusterId, + connectionString: 'mongodb://localhost:27017/', + authMechanism: AuthMethodId.NativeAuth, + }); + mocks.getConnectionStringWithPassword.mockReturnValue('mongodb://localhost:27017/'); + vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({ + get: (_key: string, defaultValue: unknown): unknown => defaultValue, + } as vscode.WorkspaceConfiguration); + evaluator = new PlaygroundEvaluator(); + }); + + afterEach(() => { + evaluator.dispose(); + }); + + it.each([ + [{ type: null, printable: 'null', printableIsUndefined: true, durationMs: 10 }, null, true], + [{ type: null, printable: 'null', durationMs: 10 }, null, undefined], + [{ type: null, printable: '42', durationMs: 10 }, new Int32(42), undefined], + [{ type: null, printable: '"value"', printableIsUndefined: false, durationMs: 10 }, 'value', false], + ] satisfies readonly (readonly [SerializableExecutionResult, unknown, boolean | undefined])[])( + 'copies the worker undefined flag without changing printable for %j', + async (serialized, printable, printableIsUndefined) => { + mocks.sendEval.mockResolvedValue({ result: serialized }); + + const result = await evaluator.evaluate( + { clusterId, clusterDisplayName: 'Test Cluster', databaseName: 'test' }, + '1', + ); + + expect(result.printableIsUndefined).toBe(printableIsUndefined); + expect(result.printable).toEqual(printable); + expect(result.type).toBe(serialized.type); + expect(result.durationMs).toBe(serialized.durationMs); + }, + ); +}); diff --git a/src/documentdb/playground/PlaygroundEvaluator.ts b/src/documentdb/playground/PlaygroundEvaluator.ts index 605db229f..f3b2cd9a2 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.ts @@ -349,6 +349,7 @@ export class PlaygroundEvaluator implements vscode.Disposable { printable: string; durationMs: number; cursorHasMore?: boolean; + printableIsUndefined?: boolean; source?: { namespace?: { db: string; collection: string } }; }): ExecutionResult { let printable: unknown; @@ -370,6 +371,7 @@ export class PlaygroundEvaluator implements vscode.Disposable { printable, durationMs: serResult.durationMs, cursorHasMore: serResult.cursorHasMore, + printableIsUndefined: serResult.printableIsUndefined, source: serResult.source, }; } diff --git a/src/documentdb/playground/PlaygroundResultProvider.test.ts b/src/documentdb/playground/PlaygroundResultProvider.test.ts new file mode 100644 index 000000000..67ac79f05 --- /dev/null +++ b/src/documentdb/playground/PlaygroundResultProvider.test.ts @@ -0,0 +1,148 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { PlaygroundResultProvider } from './PlaygroundResultProvider'; + +function makeDocument(uri: vscode.Uri): vscode.TextDocument { + return { uri } as vscode.TextDocument; +} + +function makeEditor(document: vscode.TextDocument, viewColumn: vscode.ViewColumn): vscode.TextEditor { + return { document, viewColumn } as vscode.TextEditor; +} + +describe('PlaygroundResultProvider', () => { + const sourceUri = vscode.Uri.file('/queries/a query.documentdb.js'); + let provider: PlaygroundResultProvider; + let documents: vscode.TextDocument[]; + let editors: vscode.TextEditor[]; + + beforeEach(() => { + documents = []; + editors = []; + vi.spyOn(vscode.workspace, 'textDocuments', 'get').mockImplementation(() => documents); + vi.spyOn(vscode.window, 'visibleTextEditors', 'get').mockImplementation(() => editors); + vi.spyOn(vscode.window, 'showTextDocument').mockResolvedValue({} as vscode.TextEditor); + vi.spyOn(vscode.workspace, 'openTextDocument').mockImplementation(async () => { + const resultUri = provider.getResultUri(sourceUri); + resultUri.toString(); + return makeDocument(resultUri); + }); + vi.spyOn(vscode.languages, 'setTextDocumentLanguage').mockImplementation(async (doc) => doc); + vi.spyOn(vscode.workspace, 'onDidCloseTextDocument').mockReturnValue({ dispose: vi.fn() }); + provider = new PlaygroundResultProvider(); + }); + + afterEach(() => { + provider.dispose(); + vi.restoreAllMocks(); + vi.clearAllMocks(); + }); + + it('round-trips the existing result URI source including escaped query characters', () => { + const source = sourceUri.with({ query: 'value=a&b=+#' }); + const resultUri = provider.getResultUri(source); + expect(provider.getSourceUri(resultUri)?.toString()).toBe(source.toString()); + expect(provider.getSourceUri(resultUri.with({ scheme: 'file' }))).toBeUndefined(); + expect(provider.getSourceUri(resultUri.with({ query: '' }))).toBeUndefined(); + expect(provider.getSourceUri(resultUri.with({ query: 'source=' }))).toBeUndefined(); + }); + + it('returns no source for an invalid encoded URI', () => { + const resultUri = provider.getResultUri(sourceUri); + vi.spyOn(vscode.Uri, 'parse').mockImplementationOnce(() => { + throw new Error('Invalid URI'); + }); + expect(provider.getSourceUri(resultUri)).toBeUndefined(); + }); + + it.each([undefined, false, true])( + 'opens a new result with focus=%s and preserves content and language', + async (focus) => { + const resultUri = provider.getResultUri(sourceUri); + resultUri.toString(); + const changes: vscode.Uri[] = []; + const subscription = provider.onDidChange((uri) => changes.push(uri)); + + await provider.showResult(sourceUri, 'result bytes', focus === undefined ? undefined : { focus }); + + expect(vscode.workspace.openTextDocument).toHaveBeenCalledWith(resultUri); + expect(vscode.window.showTextDocument).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ uri: resultUri }), + { viewColumn: vscode.ViewColumn.Beside, preserveFocus: focus !== true, preview: false }, + ); + expect(vscode.languages.setTextDocumentLanguage).toHaveBeenCalledWith( + expect.objectContaining({ uri: resultUri }), + 'documentdb-playground-result', + ); + expect(provider.provideTextDocumentContent(resultUri)).toBe('result bytes'); + expect(changes).toEqual([resultUri]); + subscription.dispose(); + }, + ); + + it.each([undefined, false, true])( + 'updates a visible result with focus=%s without duplicate reveals', + async (focus) => { + const doc = makeDocument(provider.getResultUri(sourceUri)); + documents = [doc]; + editors = [makeEditor(doc, vscode.ViewColumn.Three)]; + + await provider.showResult(sourceUri, 'updated', focus === undefined ? undefined : { focus }); + + expect(vscode.workspace.openTextDocument).not.toHaveBeenCalled(); + expect(provider.provideTextDocumentContent(doc.uri)).toBe('updated'); + if (focus) { + expect(vscode.window.showTextDocument).toHaveBeenCalledExactlyOnceWith(doc, { + viewColumn: vscode.ViewColumn.Three, + preserveFocus: false, + preview: false, + }); + } else { + expect(vscode.window.showTextDocument).not.toHaveBeenCalled(); + } + }, + ); + + it.each([false, true])('reveals a hidden open result with focus=%s', async (focus) => { + const doc = makeDocument(provider.getResultUri(sourceUri)); + documents = [doc]; + + await provider.showResult(sourceUri, 'updated', { focus }); + + expect(vscode.workspace.openTextDocument).not.toHaveBeenCalled(); + expect(vscode.window.showTextDocument).toHaveBeenCalledExactlyOnceWith(doc, { + viewColumn: vscode.ViewColumn.Beside, + preserveFocus: !focus, + preview: false, + }); + }); + + it('does not create a result when explicitly focusing a source without an open result', async () => { + documents = [makeDocument(provider.getResultUri(vscode.Uri.file('/another.documentdb.js')))]; + expect(await provider.focusResult(sourceUri)).toBe(false); + expect(vscode.workspace.openTextDocument).not.toHaveBeenCalled(); + expect(vscode.window.showTextDocument).not.toHaveBeenCalled(); + }); + + it.each([false, true])( + 'focuses the actual open result (visible=%s) in its existing group when visible', + async (visible) => { + const doc = makeDocument(provider.getResultUri(sourceUri)); + documents = [doc]; + editors = visible ? [makeEditor(doc, vscode.ViewColumn.Two)] : []; + + expect(await provider.focusResult(sourceUri)).toBe(true); + expect(vscode.window.showTextDocument).toHaveBeenCalledExactlyOnceWith(doc, { + viewColumn: visible ? vscode.ViewColumn.Two : vscode.ViewColumn.Beside, + preserveFocus: false, + preview: false, + }); + expect(vscode.workspace.openTextDocument).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/src/documentdb/playground/PlaygroundResultProvider.ts b/src/documentdb/playground/PlaygroundResultProvider.ts index 0efd2843c..b9b97ceb9 100644 --- a/src/documentdb/playground/PlaygroundResultProvider.ts +++ b/src/documentdb/playground/PlaygroundResultProvider.ts @@ -66,6 +66,36 @@ export class PlaygroundResultProvider implements vscode.TextDocumentContentProvi }); } + getSourceUri(resultUri: vscode.Uri): vscode.Uri | undefined { + if (resultUri.scheme !== PLAYGROUND_RESULT_SCHEME) { + return undefined; + } + const source = new URLSearchParams(resultUri.query).get('source'); + if (!source) { + return undefined; + } + try { + return vscode.Uri.parse(source, true); + } catch { + return undefined; + } + } + + async focusResult(sourceUri: vscode.Uri): Promise { + const resultUri = this.getResultUri(sourceUri); + const doc = vscode.workspace.textDocuments.find((d) => d.uri.toString() === resultUri.toString()); + if (!doc) { + return false; + } + const editor = vscode.window.visibleTextEditors.find((e) => e.document.uri.toString() === resultUri.toString()); + await vscode.window.showTextDocument(doc, { + viewColumn: editor?.viewColumn ?? vscode.ViewColumn.Beside, + preserveFocus: false, + preview: false, + }); + return true; + } + /** * Update (or set) the content for a result URI and notify VS Code to re-read it. */ @@ -82,7 +112,7 @@ export class PlaygroundResultProvider implements vscode.TextDocumentContentProvi * delegates syntax highlighting to JSONC via its TextMate grammar while * keeping the custom DocumentDB icon on the tab. */ - async showResult(sourceUri: vscode.Uri, content: string): Promise { + async showResult(sourceUri: vscode.Uri, content: string, options?: { readonly focus?: boolean }): Promise { const resultUri = this.getResultUri(sourceUri); this.updateContent(resultUri, content); @@ -94,7 +124,7 @@ export class PlaygroundResultProvider implements vscode.TextDocumentContentProvi const doc = await vscode.workspace.openTextDocument(resultUri); await vscode.window.showTextDocument(doc, { viewColumn: vscode.ViewColumn.Beside, - preserveFocus: true, + preserveFocus: !options?.focus, preview: false, }); // Set our language so VS Code uses our icon and JSONC-delegating grammar. @@ -106,10 +136,10 @@ export class PlaygroundResultProvider implements vscode.TextDocumentContentProvi const visibleEditor = vscode.window.visibleTextEditors.find( (e) => e.document.uri.toString() === resultUri.toString(), ); - if (!visibleEditor) { + if (!visibleEditor || options?.focus) { await vscode.window.showTextDocument(existingDoc, { - viewColumn: vscode.ViewColumn.Beside, - preserveFocus: true, + viewColumn: visibleEditor?.viewColumn ?? vscode.ViewColumn.Beside, + preserveFocus: !options?.focus, preview: false, }); } diff --git a/src/documentdb/playground/afterRun.test.ts b/src/documentdb/playground/afterRun.test.ts new file mode 100644 index 000000000..db12a93ad --- /dev/null +++ b/src/documentdb/playground/afterRun.test.ts @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { describe, expect, it } from 'vitest'; +import { resolveAfterRunOutcome } from './afterRun'; + +describe('resolveAfterRunOutcome', () => { + it.each([ + ['auto', false, 'stay'], + ['auto', true, 'focusResult'], + ['stay', false, 'stay'], + ['stay', true, 'stay'], + ['focusResult', false, 'focusResult'], + ['focusResult', true, 'focusResult'], + ['notify', false, 'notify'], + ['notify', true, 'notify'], + ] as const)('resolves %s with screenReaderMode=%s to %s', (setting, screenReaderMode, expected) => { + expect(resolveAfterRunOutcome(setting, screenReaderMode)).toBe(expected); + }); + + it.each([undefined, null, 'invalid', false, 42, {}])('uses auto for an unset or unknown value %j', (setting) => { + expect(resolveAfterRunOutcome(setting, false)).toBe('stay'); + expect(resolveAfterRunOutcome(setting, true)).toBe('focusResult'); + }); +}); diff --git a/src/documentdb/playground/afterRun.ts b/src/documentdb/playground/afterRun.ts new file mode 100644 index 000000000..cf4dec705 --- /dev/null +++ b/src/documentdb/playground/afterRun.ts @@ -0,0 +1,14 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export type PlaygroundAfterRunSetting = 'auto' | 'stay' | 'focusResult' | 'notify'; +export type PlaygroundAfterRunOutcome = 'stay' | 'focusResult' | 'notify'; + +export function resolveAfterRunOutcome(setting: unknown, screenReaderMode: boolean): PlaygroundAfterRunOutcome { + if (setting === 'stay' || setting === 'focusResult' || setting === 'notify') { + return setting; + } + return screenReaderMode ? 'focusResult' : 'stay'; +} diff --git a/src/documentdb/playground/constants.ts b/src/documentdb/playground/constants.ts index 03ff86532..361b0ce99 100644 --- a/src/documentdb/playground/constants.ts +++ b/src/documentdb/playground/constants.ts @@ -31,6 +31,8 @@ export const PlaygroundCommandIds = { runAll: 'vscode-documentdb.command.playground.runAll', /** Run the selection or the statement at the cursor */ runSelected: 'vscode-documentdb.command.playground.runSelected', + focusResult: 'vscode-documentdb.command.playground.focusResult', + focusPlayground: 'vscode-documentdb.command.playground.focusPlayground', /** Sample documents from a collection to discover field names */ scanCollectionSchema: 'vscode-documentdb.command.playground.scanCollectionSchema', /** Open the current code block in Collection View */ diff --git a/src/documentdb/playground/resultFormatter.test.ts b/src/documentdb/playground/resultFormatter.test.ts index 6ba8dbc26..e0f2606ab 100644 --- a/src/documentdb/playground/resultFormatter.test.ts +++ b/src/documentdb/playground/resultFormatter.test.ts @@ -3,10 +3,17 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; -import { formatError, formatResult } from './resultFormatter'; -import { type PlaygroundConnection } from './types'; +import * as l10n from '@vscode/l10n'; +import { Decimal128, Double, EJSON, Int32, Long } from 'bson'; +import { describeCompletion, describeResult, formatError, formatResult } from './resultFormatter'; +import { type ExecutionResult, type PlaygroundConnection } from './types'; + +vi.mock('@vscode/l10n', async (importOriginal) => { + const original = await importOriginal(); + return { ...original, t: vi.fn(original.t) }; +}); const connection: PlaygroundConnection = { clusterId: 'test-cluster', @@ -16,6 +23,178 @@ const connection: PlaygroundConnection = { }; describe('resultFormatter', () => { + it.each([ + [{ type: 'Cursor', printable: [{ _id: 1 }, { _id: 2 }], durationMs: 10 }, 'Cursor (2 documents)'], + [{ type: 'Cursor', printable: { cursorHasMore: true, documents: [] }, durationMs: 10 }, 'Cursor (0 documents)'], + [{ type: 'Document', printable: { documents: [] }, durationMs: 10 }, 'Document'], + [{ type: 'string', printable: 'secret value', durationMs: 10 }, 'string'], + [{ type: null, printable: [1, 2, 3], durationMs: 10 }, 'Array (3 elements)'], + [{ type: null, printable: undefined, durationMs: 10 }, undefined], + ] satisfies readonly (readonly [ExecutionResult, string | undefined])[])( + 'describes only existing count/type metadata for %j', + (result, expected) => { + expect(describeResult(result)).toBe(expected); + }, + ); + + it.each([ + [{ type: null, printable: null, printableIsUndefined: true, durationMs: 10 }, undefined], + [{ type: 'string', printable: 'serialized value', printableIsUndefined: true, durationMs: 10 }, undefined], + [{ type: null, printable: null, durationMs: 10 }, 'null'], + [{ type: null, printable: null, printableIsUndefined: false, durationMs: 10 }, 'null'], + [{ type: null, printable: 42, durationMs: 10 }, 'number'], + [{ type: null, printable: { _id: 1 }, durationMs: 10 }, 'object'], + [{ type: null, printable: 'private value', durationMs: 10 }, 'string'], + [{ type: null, printable: undefined, durationMs: 10 }, 'undefined'], + [{ type: 'Document', printable: { _id: 1 }, durationMs: 10 }, 'Document'], + [ + { type: 'Cursor', printable: { cursorHasMore: true, documents: [{ _id: 1 }] }, durationMs: 10 }, + 'Cursor (1 documents)', + ], + [{ type: null, printable: [1, 2], durationMs: 10 }, 'Array (2 elements)'], + ] satisfies readonly (readonly [ExecutionResult, string | undefined])[])( + 'describes completion without guessing absence for %j', + (result, expected) => { + expect(describeCompletion(result)).toBe(expected); + }, + ); + + it.each([ + { type: null, printable: null, durationMs: 10 }, + { type: null, printable: 42, durationMs: 10 }, + { type: 'Document', printable: { _id: 1 }, durationMs: 10 }, + ] satisfies readonly ExecutionResult[])( + 'keeps every formatted byte unchanged regardless of the undefined flag for %j', + (result) => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-11-27T12:00:00Z')); + try { + const unchanged = formatResult(result, 'db.test.findOne()', connection); + expect(formatResult({ ...result, printableIsUndefined: true }, 'db.test.findOne()', connection)).toBe( + unchanged, + ); + expect(formatResult({ ...result, printableIsUndefined: false }, 'db.test.findOne()', connection)).toBe( + unchanged, + ); + if (result.type === null) { + expect(unchanged).not.toContain('// Result:'); + } + } finally { + vi.useRealTimers(); + } + }, + ); + + it.each([new Int32(42), new Double(42.5), Long.fromString('9223372036854775807'), Decimal128.fromString('42.5')])( + 'describes canonical EJSON numeric wrappers as numbers', + (value) => { + const printable = EJSON.parse(EJSON.stringify(value, undefined, undefined, { relaxed: false }), { + relaxed: false, + }); + expect(describeCompletion({ type: null, printable, durationMs: 10 })).toBe('number'); + }, + ); + + it.each([ + ['ordinary object', { _id: 1 }], + ['nested object', { metadata: { enabled: true }, value: 42 }], + ] satisfies readonly (readonly [string, Record])[])( + 'keeps canonical EJSON %s classified as an object', + (_label, value) => { + const printable = EJSON.parse(EJSON.stringify(value, undefined, undefined, { relaxed: false }), { + relaxed: false, + }); + expect(describeCompletion({ type: null, printable, durationMs: 10 })).toBe('object'); + }, + ); + + it('does not classify an object with a BSON type tag as a numeric wrapper', () => { + expect( + describeCompletion({ + type: null, + printable: { _bsontype: 'Int32', value: 42 }, + durationMs: 10, + }), + ).toBe('object'); + }); + + it.each([ + [ + { type: 'Cursor', printable: [{ _id: 1 }, { _id: 2 }], durationMs: 10 }, + 'Result: Cursor ({0} documents)', + 2, + '2 documents — résultat du curseur', + ], + [ + { type: null, printable: [1, 2, 3], durationMs: 10 }, + 'Result: Array ({0} elements)', + 3, + '3 éléments — résultat du tableau', + ], + [{ type: 'Document', printable: { _id: 1 }, durationMs: 10 }, 'Result: {0}', 'Document', 'Document — résultat'], + ] satisfies readonly (readonly [ExecutionResult, string, number | string, string])[])( + 'uses the original complete translation key for %j and argument order', + (result, key, argument, translated) => { + const translator = vi + .mocked(l10n.t) + .mockReset() + .mockImplementation((message: unknown, ...args: unknown[]): string => + message === key && args[0] === argument ? translated : 'autre traduction', + ); + try { + const output = formatResult(result, 'db.test.find()', connection); + + expect(translator).toHaveBeenCalledWith(key, argument); + expect(output.split('\n')).toContain(`// ${translated}`); + const usedKeys = translator.mock.calls.map(([message]) => message); + expect(usedKeys).not.toContain('Cursor ({0} documents)'); + expect(usedKeys).not.toContain('Array ({0} elements)'); + } finally { + translator.mockReset(); + } + }, + ); + + it.each([ + [ + { type: 'Cursor', printable: [{ _id: 1 }], durationMs: 10 }, + 'Result: Cursor (1 documents)', + '[\n {\n "_id": 1\n }\n]', + ], + [ + { type: 'Cursor', printable: { cursorHasMore: false, documents: [] }, durationMs: 10 }, + 'Result: Cursor (0 documents)', + '[]', + ], + [{ type: 'Document', printable: { _id: 1 }, durationMs: 10 }, 'Result: Document', '{\n "_id": 1\n}'], + [{ type: 'string', printable: 'hello', durationMs: 10 }, 'Result: string', 'hello'], + [{ type: null, printable: [1], durationMs: 10 }, 'Result: Array (1 elements)', '[\n 1\n]'], + [{ type: null, printable: undefined, durationMs: 10 }, undefined, 'undefined'], + ] satisfies readonly (readonly [ExecutionResult, string | undefined, string])[])( + 'preserves every formatted byte for %j', + (result, header, value) => { + const date = new Date('2026-11-27T12:00:00Z'); + vi.useFakeTimers(); + vi.setSystemTime(date); + try { + const lines = [ + '// Test Cluster / testDb', + `// ${date.toLocaleString()}`, + '//', + '// ▶ db.test.find()', + ...(header ? [`// ${header}`] : []), + '// Executed in 10ms', + '// ─────────────────────────', + '', + value, + ]; + expect(formatResult(result, 'db.test.find()', connection)).toBe(lines.join('\n')); + } finally { + vi.useRealTimers(); + } + }, + ); + describe('formatError', () => { it('strips ANSI color codes from error messages', () => { const error = new Error('\x1b[31mSyntaxError\x1b[0m: \x1b[1mMissing semicolon\x1b[0m'); diff --git a/src/documentdb/playground/resultFormatter.ts b/src/documentdb/playground/resultFormatter.ts index 9865cdb93..8a65c4b59 100644 --- a/src/documentdb/playground/resultFormatter.ts +++ b/src/documentdb/playground/resultFormatter.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import * as l10n from '@vscode/l10n'; -import { EJSON } from 'bson'; +import { Decimal128, Double, EJSON, Int32, Long } from 'bson'; import { SettingsHintError } from '../shell/SettingsHintError'; import { extractErrorCode } from '../shell/ShellOutputFormatter'; import { type ExecutionResult, type PlaygroundConnection } from './types'; @@ -28,6 +28,39 @@ function isMaxTimeMSError(error: unknown): boolean { return error instanceof Error && 'code' in error && (error as { code: unknown }).code === 50; } +export function describeResult(result: ExecutionResult): string | undefined { + const unwrapped = unwrapCursorResult(result.printable); + if (result.type === 'Cursor' && Array.isArray(unwrapped)) { + return l10n.t('Cursor ({0} documents)', unwrapped.length); + } + if (result.type) { + return result.type; + } + if (Array.isArray(unwrapped)) { + return l10n.t('Array ({0} elements)', unwrapped.length); + } + return undefined; +} + +export function describeCompletion(result: ExecutionResult): string | undefined { + if (result.printableIsUndefined === true) { + return undefined; + } + const summary = describeResult(result); + if (summary !== undefined) { + return summary; + } + if ( + result.printable instanceof Int32 || + result.printable instanceof Double || + result.printable instanceof Long || + result.printable instanceof Decimal128 + ) { + return 'number'; + } + return result.printable === null ? 'null' : typeof result.printable; +} + /** * Formats a query playground execution result for display in a read-only output panel. * diff --git a/src/documentdb/playground/statementDetector.test.ts b/src/documentdb/playground/statementDetector.test.ts index 140397bbc..0914b3302 100644 --- a/src/documentdb/playground/statementDetector.test.ts +++ b/src/documentdb/playground/statementDetector.test.ts @@ -6,7 +6,15 @@ import { describe, expect, it } from 'vitest'; import * as vscode from 'vscode'; -import { detectBlocks, detectCurrentBlock, findBlockAtLine, type CodeBlock } from './statementDetector'; +import { + blockContainsCode, + detectBlocks, + detectCurrentBlock, + findBlockAtLine, + getBlockText, + resolveBlockAtLine, + type CodeBlock, +} from './statementDetector'; /** * Helper to create a mock TextDocument from a multiline string. @@ -148,4 +156,50 @@ describe('statementDetector', () => { expect(result).toBe(''); }); }); + + describe('resolveBlockAtLine', () => { + const blocks: CodeBlock[] = [ + { startLine: 1, endLine: 2 }, + { startLine: 5, endLine: 6 }, + ]; + + it('identifies a block containing the cursor', () => { + expect(resolveBlockAtLine(blocks, 2)).toEqual({ + block: { startLine: 1, endLine: 2 }, + match: 'cursor', + }); + }); + + it('falls back to the nearest preceding block on a blank line', () => { + expect(resolveBlockAtLine(blocks, 4)).toEqual({ + block: { startLine: 1, endLine: 2 }, + match: 'preceding', + }); + }); + + it('returns undefined before the first block and for an empty list', () => { + expect(resolveBlockAtLine(blocks, 0)).toBeUndefined(); + expect(resolveBlockAtLine([], 0)).toBeUndefined(); + }); + }); + + describe('block text and code detection', () => { + it('extracts a block through the last line character', () => { + const doc = mockDocument('db.users.find({});\n\n db.orders.find({});'); + expect(getBlockText(doc, { startLine: 2, endLine: 2 })).toBe(' db.orders.find({});'); + }); + + it.each(['// heading', '/* heading */', '/*\n * heading\n */'])( + 'does not treat a comment-only block as code: %s', + (text) => { + const doc = mockDocument(text); + expect(blockContainsCode(doc, { startLine: 0, endLine: doc.lineCount - 1 })).toBe(false); + }, + ); + + it('finds code following a block comment', () => { + const doc = mockDocument('/* heading */ db.users.find({});'); + expect(blockContainsCode(doc, { startLine: 0, endLine: 0 })).toBe(true); + }); + }); }); diff --git a/src/documentdb/playground/statementDetector.ts b/src/documentdb/playground/statementDetector.ts index 46f1a37d2..b2b85e64e 100644 --- a/src/documentdb/playground/statementDetector.ts +++ b/src/documentdb/playground/statementDetector.ts @@ -17,6 +17,11 @@ export interface CodeBlock { readonly endLine: number; } +export interface ResolvedBlock { + readonly block: CodeBlock; + readonly match: 'cursor' | 'preceding'; +} + /** * Detects code blocks in a query playground document using blank-line separation. * @@ -82,3 +87,58 @@ export function detectCurrentBlock(document: vscode.TextDocument, position: vsco export function findBlockAtLine(blocks: CodeBlock[], line: number): CodeBlock | undefined { return blocks.find((b) => line >= b.startLine && line <= b.endLine); } + +export function resolveBlockAtLine(blocks: readonly CodeBlock[], line: number): ResolvedBlock | undefined { + const direct = blocks.find((block) => line >= block.startLine && line <= block.endLine); + if (direct) { + return { block: direct, match: 'cursor' }; + } + + for (let i = blocks.length - 1; i >= 0; i--) { + if (blocks[i].endLine < line) { + return { block: blocks[i], match: 'preceding' }; + } + } + + return undefined; +} + +export function getBlockText(document: vscode.TextDocument, block: CodeBlock): string { + const range = new vscode.Range(block.startLine, 0, block.endLine, document.lineAt(block.endLine).text.length); + return document.getText(range); +} + +export function blockContainsCode(document: vscode.TextDocument, block: CodeBlock): boolean { + let inBlockComment = false; + for (let i = block.startLine; i <= block.endLine; i++) { + const trimmed = document.lineAt(i).text.trim(); + if (inBlockComment) { + const closeIdx = trimmed.indexOf('*/'); + if (closeIdx !== -1) { + inBlockComment = false; + const afterComment = trimmed.substring(closeIdx + 2).trim(); + if (afterComment.length > 0 && !afterComment.startsWith('//')) { + return true; + } + } + continue; + } + if (trimmed.startsWith('/*')) { + const closeIdx = trimmed.indexOf('*/', 2); + if (closeIdx === -1) { + inBlockComment = true; + continue; + } + const afterComment = trimmed.substring(closeIdx + 2).trim(); + if (afterComment.length > 0 && !afterComment.startsWith('//')) { + return true; + } + continue; + } + if (trimmed.startsWith('//') || trimmed.length === 0) { + continue; + } + return true; + } + return false; +} diff --git a/src/documentdb/playground/types.ts b/src/documentdb/playground/types.ts index 359246db6..1f2b95fbb 100644 --- a/src/documentdb/playground/types.ts +++ b/src/documentdb/playground/types.ts @@ -30,6 +30,8 @@ export interface ExecutionResult { readonly type: string | null; /** The printable result value — already iterated for cursors. */ readonly printable: unknown; + /** True when the original printable value was undefined before EJSON serialization. */ + readonly printableIsUndefined?: boolean; /** Execution duration in milliseconds. */ readonly durationMs: number; /** Whether the cursor has more documents beyond the returned batch (Cursor results only). */ diff --git a/src/settingsKeys.ts b/src/settingsKeys.ts index 5e9ef4476..7b40d5f22 100644 --- a/src/settingsKeys.ts +++ b/src/settingsKeys.ts @@ -34,6 +34,7 @@ export namespace settingsKeys { // Query Playground export const playgroundConfirmRunAll = 'documentDB.playground.confirmRunAll'; + export const playgroundAfterRun = 'documentDB.playground.afterRun'; // Interactive Shell export const shellMultiLinePasteBehavior = 'documentDB.shell.multiLinePasteBehavior'; diff --git a/src/tree/documentdb/DocumentsItem.test.ts b/src/tree/documentdb/DocumentsItem.test.ts new file mode 100644 index 000000000..6e8326725 --- /dev/null +++ b/src/tree/documentdb/DocumentsItem.test.ts @@ -0,0 +1,52 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { describe, expect, it, vi } from 'vitest'; + +import { type CollectionItemModel, type DatabaseItemModel } from '../../documentdb/ClustersClient'; +import { DocumentDBExperience } from '../../DocumentDBExperiences'; +import { type BaseClusterModel, type TreeCluster } from '../models/BaseClusterModel'; +import { type CollectionItem } from './CollectionItem'; +import { DocumentsItem } from './DocumentsItem'; + +vi.mock('@microsoft/vscode-azext-utils', () => ({ + createContextValue: (values: string[]) => values.join(';'), +})); + +vi.mock('@vscode/l10n', () => ({ + t: (message: string): string => message, +})); + +vi.mock('vscode', () => ({ + ThemeIcon: class ThemeIcon { + constructor(public readonly id: string) {} + }, +})); + +const cluster = { + treeId: 'cluster-tree-id', + clusterId: 'cluster-id', + name: 'Cluster', + viewId: 'connectionsView', + dbExperience: DocumentDBExperience, +} as TreeCluster; +const databaseInfo: DatabaseItemModel = { name: 'database' }; +const collectionInfo: CollectionItemModel = { name: 'collection' }; +const parentCollectionNode = {} as CollectionItem; + +describe('DocumentsItem accessibility', () => { + it('includes the visible label in its accessible name', () => { + const treeItem = new DocumentsItem(cluster, databaseInfo, collectionInfo, parentCollectionNode).getTreeItem(); + + expect(treeItem.label).toBe('Documents'); + expect(treeItem.accessibilityInformation?.label).toContain(treeItem.label as string); + }); + + it('retains the hover tooltip', () => { + const treeItem = new DocumentsItem(cluster, databaseInfo, collectionInfo, parentCollectionNode).getTreeItem(); + + expect(treeItem.tooltip).toBe('Click to open the collection view'); + }); +}); diff --git a/src/tree/documentdb/DocumentsItem.ts b/src/tree/documentdb/DocumentsItem.ts index 56166182f..58eb4dc9b 100644 --- a/src/tree/documentdb/DocumentsItem.ts +++ b/src/tree/documentdb/DocumentsItem.ts @@ -53,6 +53,7 @@ export class DocumentsItem implements TreeElement, TreeElementWithExperience, Tr id: this.id, contextValue: this.contextValue, label: l10n.t('Documents'), + accessibilityInformation: { label: l10n.t('Documents') }, tooltip: l10n.t('Click to open the collection view'), command: { title: l10n.t('Open Collection'), // unused, but required by TreeItem diff --git a/src/tree/documentdb/IndexesItem.test.ts b/src/tree/documentdb/IndexesItem.test.ts index 350f0625a..10975db16 100644 --- a/src/tree/documentdb/IndexesItem.test.ts +++ b/src/tree/documentdb/IndexesItem.test.ts @@ -131,6 +131,13 @@ describe('IndexesItem - async index loading', () => { return new Promise((resolve) => setImmediate(resolve)); } + it('uses the visible Indexes label without a plain-string tooltip', () => { + const treeItem = new IndexesItem(cluster, databaseInfo, collectionInfo).getTreeItem(); + + expect(treeItem.label).toBe('Indexes'); + expect(treeItem.tooltip).toBeUndefined(); + }); + it('loadIndexCount fetches indexes once and exposes the count via description', async () => { const item = new IndexesItem(cluster, databaseInfo, collectionInfo); diff --git a/src/webviews/components/accessibility/focusWithVisibleIndicator.test.tsx b/src/webviews/components/accessibility/focusWithVisibleIndicator.test.tsx new file mode 100644 index 000000000..96a5aef9b --- /dev/null +++ b/src/webviews/components/accessibility/focusWithVisibleIndicator.test.tsx @@ -0,0 +1,84 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// @vitest-environment jsdom + +import { Button, FluentProvider, webLightTheme } from '@fluentui/react-components'; +import { createKeyborg, disposeKeyborg } from 'keyborg'; +import { act } from 'react'; +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 { focusWithVisibleIndicator } from './focusWithVisibleIndicator'; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +describe('focusWithVisibleIndicator', (): void => { + let host: HTMLElement; + let root: Root; + + beforeEach((): void => { + host = document.createElement('div'); + document.body.appendChild(host); + root = createRoot(host); + }); + + afterEach((): void => { + act(() => root.unmount()); + host.remove(); + vi.restoreAllMocks(); + }); + + it('skips unavailable candidates and returns the focused eligible element', async (): Promise => { + await act(async () => { + root.render( + + + + + , + ); + }); + const buttons = host.querySelectorAll('button'); + const disconnected = document.createElement('button'); + + const focused = focusWithVisibleIndicator([null, disconnected, buttons[0], buttons[1], buttons[2]]); + + expect(focused).toBe(buttons[2]); + expect(document.activeElement).toBe(buttons[2]); + expect(buttons[2]?.hasAttribute('data-fui-focus-visible')).toBe(true); + }); + + it('keeps the shared keyborg keyboard state and subscription alive', async (): Promise => { + await act(async () => { + root.render( + + + , + ); + }); + const persistent = createKeyborg(window); + const onChange = vi.fn(); + persistent.subscribe(onChange); + const button = host.querySelector('button'); + + try { + focusWithVisibleIndicator([button]); + + expect(persistent.isNavigatingWithKeyboard()).toBe(true); + expect(onChange).toHaveBeenCalledWith(true); + expect(button?.hasAttribute('data-fui-focus-visible')).toBe(true); + } finally { + persistent.unsubscribe(onChange); + disposeKeyborg(persistent); + } + }); + + it('returns undefined when no candidate can receive focus', (): void => { + const disconnected = document.createElement('button'); + disconnected.setAttribute('aria-disabled', 'true'); + + expect(focusWithVisibleIndicator([null, disconnected])).toBeUndefined(); + }); +}); diff --git a/src/webviews/components/accessibility/focusWithVisibleIndicator.ts b/src/webviews/components/accessibility/focusWithVisibleIndicator.ts new file mode 100644 index 000000000..6645bc95a --- /dev/null +++ b/src/webviews/components/accessibility/focusWithVisibleIndicator.ts @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { createKeyborg, disposeKeyborg } from 'keyborg'; + +export function focusWithVisibleIndicator( + candidates: ReadonlyArray, +): HTMLElement | undefined { + for (const candidate of candidates) { + if ( + !candidate?.isConnected || + candidate.matches(':disabled') || + candidate.getAttribute('aria-disabled') === 'true' + ) { + continue; + } + + candidate.focus(); + if (candidate.ownerDocument.activeElement !== candidate) { + continue; + } + + const targetWindow = candidate.ownerDocument.defaultView; + if (targetWindow) { + const keyborg = createKeyborg(targetWindow); + try { + keyborg.setVal(true); + } finally { + disposeKeyborg(keyborg); + } + } + return candidate; + } + + return undefined; +} diff --git a/src/webviews/components/accessibility/index.ts b/src/webviews/components/accessibility/index.ts index 3326bd7dc..e1dab464b 100644 --- a/src/webviews/components/accessibility/index.ts +++ b/src/webviews/components/accessibility/index.ts @@ -4,3 +4,4 @@ *--------------------------------------------------------------------------------------------*/ export { Announcer, type AnnouncerProps } from './Announcer'; +export { focusWithVisibleIndicator } from './focusWithVisibleIndicator'; diff --git a/src/webviews/components/expandCollapseButton.scss b/src/webviews/components/expandCollapseButton.scss index f7607ecdf..fbe1276cd 100644 --- a/src/webviews/components/expandCollapseButton.scss +++ b/src/webviews/components/expandCollapseButton.scss @@ -29,9 +29,11 @@ color: var(--colorNeutralForeground3Pressed, currentColor); } + // Fluent's 2px focus ring, as on the rest of the extension. `--vscode-focusBorder` is + // semi-transparent in some themes and fell under 3:1 on a hovered row. &:focus-visible { - outline: 1px solid var(--vscode-focusBorder); - outline-offset: -1px; + outline: var(--strokeWidthThick, 2px) solid var(--colorStrokeFocus2, var(--vscode-focusBorder)); + outline-offset: calc(-1 * var(--strokeWidthThick, 2px)); } .expandCollapseButtonIcon { diff --git a/src/webviews/components/useSelectiveContextMenuPrevention.ts b/src/webviews/components/useSelectiveContextMenuPrevention.ts index 7b72bca7b..5f1311fa9 100644 --- a/src/webviews/components/useSelectiveContextMenuPrevention.ts +++ b/src/webviews/components/useSelectiveContextMenuPrevention.ts @@ -7,9 +7,10 @@ import { useEffect } from 'react'; /** * Custom hook that selectively prevents context menus based on element selectors. - * Currently allows context menus in Monaco editor elements while preventing them elsewhere. - * This preserves editor functionality (copy/paste/formatting) while preventing unwanted - * context menus in data tables and other UI elements. + * 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. * * Additional editor selectors can be added to the allowlist as needed. */ @@ -36,7 +37,9 @@ export const useSelectiveContextMenuPrevention = (): void => { // Check if target is within any allowed element const isInAllowedElement = allowedSelectors.some((selector) => target.closest(selector) !== null); - if (!isInAllowedElement) { + const hasNativeWebviewMenu = target.closest('[role="columnheader"][data-vscode-context]') !== null; + + if (!isInAllowedElement && !hasNativeWebviewMenu) { e.preventDefault(); } }; diff --git a/src/webviews/documentdb/collectionView/CollectionView.test.tsx b/src/webviews/documentdb/collectionView/CollectionView.test.tsx index 351275594..70ef688f6 100644 --- a/src/webviews/documentdb/collectionView/CollectionView.test.tsx +++ b/src/webviews/documentdb/collectionView/CollectionView.test.tsx @@ -12,7 +12,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { fieldColumnKey, ROOT_ID_COLUMN_KEY, type ColumnKey, type TablePage } from '../../../utils/documentGrid/types'; import { CollectionView } from './CollectionView'; import { Views } from './collectionViewContext'; -import { type DataViewPanelTableFocusRequest } from './components/resultsTab/DataViewPanelTable'; +import type * as DataViewPanelTableModule from './components/resultsTab/DataViewPanelTable'; import { type ColumnWidthCache, type ColumnWidthScope } from './components/resultsTab/useStableColumnWidths'; (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -25,7 +25,7 @@ interface DeferredTableRequest { interface TableHostProps { readonly page: TablePage | undefined; - readonly focusRequest?: DataViewPanelTableFocusRequest; + readonly focusRequest?: DataViewPanelTableModule.DataViewPanelTableFocusRequest; readonly selectedRowKeys: readonly string[]; readonly onSelectedRowKeysChange: (rowKeys: readonly string[]) => void; readonly onStepIn: (rowKey: string, columnKey: ColumnKey, gesture: 'keyboard' | 'pointer') => void; @@ -66,6 +66,7 @@ const nestedPage: TablePage = { }; const boundaries = vi.hoisted(() => ({ + useRealTable: false, latestTableProps: undefined as TableHostProps | undefined, announcerMounts: [] as { readonly message: string; @@ -177,9 +178,13 @@ vi.mock('../../query-language-support', () => ({ setCompletionContext: vi.fn() } vi.mock('@fluentui/react-icons', () => ({ EmojiRegular: (): null => null })); vi.mock('@fluentui/react-components', () => ({ Button: ({ children }: { readonly children?: ReactNode }): React.JSX.Element => , + makeStyles: () => (): Record => ({}), ProgressBar: (): React.JSX.Element =>
, + Skeleton: ({ children }: { readonly children?: ReactNode }): React.JSX.Element =>
{children}
, + SkeletonItem: (): null => null, Tab: ({ children }: { readonly children?: ReactNode }): React.JSX.Element => , TabList: ({ children }: { readonly children?: ReactNode }): React.JSX.Element =>
{children}
, + Tooltip: ({ children }: { readonly children: React.JSX.Element }): React.JSX.Element => children, })); vi.mock('./components/queryEditor/QueryEditor', () => ({ QueryEditor: ({ onExecuteRequest }: { readonly onExecuteRequest: () => void }): React.JSX.Element => ( @@ -188,13 +193,17 @@ vi.mock('./components/queryEditor/QueryEditor', () => ({ ), })); -vi.mock('./components/resultsTab/DataViewPanelTable', async () => { +vi.mock('./components/resultsTab/DataViewPanelTable', async (importOriginal) => { const { useContext } = await import('react'); const { CollectionViewContext: ActualContext } = await import('./collectionViewContext'); + const { DataViewPanelTable } = await importOriginal(); return { - DataViewPanelTable: (props: TableHostProps): React.JSX.Element => { + DataViewPanelTable: (props: Parameters[0]): React.JSX.Element => { boundaries.latestTableProps = props; const [, setContext] = useContext(ActualContext); + if (boundaries.useRealTable) { + return ; + } return (
+ ))} +
+ {leafColumns.map((column) => ( +
+ ))} + {props.rows.slice(0, 20).map((row, rowIdx) => { const children = leafColumns.map((column, columnIdx) => ( + ); + })} +
+ {props.columns.map((column) => { + if (!('key' in column)) { + throw new Error('Unexpected column group in DataViewPanelTree'); + } + return
; + })} + {props.rows.slice(0, 20).map((row, rowIdx) => (
{props.columns.map((column, columnIdx) => { if (!('key' in column)) { @@ -77,7 +107,39 @@ let root: Root; async function render(nodes: readonly TreeNode[]): Promise { await act(async () => { - root.render(); + root.render(); + }); +} + +function header(label: string): HTMLElement { + const result = [...host.querySelectorAll('[role="columnheader"]')].find( + (candidate) => candidate.textContent === label, + ); + if (!result) { + throw new Error(`Missing column header: ${label}`); + } + return result; +} + +async function sendResizeMessage(data: object): Promise { + await act(async () => { + window.dispatchEvent(new MessageEvent('message', { data })); + await Promise.resolve(); + }); +} + +function focusOutsideGrid(): HTMLButtonElement { + const outside = document.createElement('button'); + outside.type = 'button'; + document.body.appendChild(outside); + outside.focus(); + expect(document.activeElement).toBe(outside); + return outside; +} + +function reportColumnWidths(widths: ReadonlyMap): void { + act(() => { + rdg.onColumnWidthsChange?.(widths); }); } @@ -121,11 +183,15 @@ beforeEach(() => { document.body.appendChild(host); root = createRoot(host); rdg.onCellCopy = undefined; + rdg.onColumnWidthsChange = undefined; + rdg.columnWidths = undefined; + rdg.columns = undefined; }); afterEach(async () => { await act(async () => root.unmount()); host.remove(); + document.body.replaceChildren(); }); describe('DataViewPanelTree copy', (): void => { @@ -208,3 +274,220 @@ describe('DataViewPanelTree copy', (): void => { 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]); + + const value = rdg.columns?.find((column) => 'key' in column && column.key === 'value'); + expect(value).toBeDefined(); + expect(value).not.toHaveProperty('maxWidth'); + expect(value).not.toHaveProperty('width'); + expect(rdg.columnWidths?.size).toBe(0); + }); + + it('applies an exact width only to the invoking Tree column and returns focus to its header', async (): Promise => { + await render([nestedNode]); + reportColumnWidths( + new Map([ + ['field', { type: 'resized', width: 140 }], + ['value', { type: 'measured', width: 180 }], + ['type', { type: 'measured', width: 100 }], + ]), + ); + const valueHeader = header('Value'); + focusOutsideGrid(); + + await sendResizeMessage({ + type: 'collectionView.columnResize', + action: 'resize', + view: 'tree', + columnKey: 'value', + width: 275, + }); + + expect(rdg.columnWidths?.get('field')).toEqual({ type: 'resized', width: 140 }); + expect(rdg.columnWidths?.get('value')).toEqual({ type: 'resized', width: 275 }); + expect(rdg.columnWidths?.get('type')).toEqual({ type: 'measured', width: 100 }); + expect(document.activeElement).toBe(valueHeader); + }); + + it('leaves the width unchanged when Resize is cancelled and returns focus to the header', async (): Promise => { + await render([nestedNode]); + await sendResizeMessage({ + type: 'collectionView.columnResize', + action: 'resize', + view: 'tree', + columnKey: 'value', + width: 275, + }); + const valueHeader = header('Value'); + focusOutsideGrid(); + + await sendResizeMessage({ + type: 'collectionView.columnResize', + action: 'resize', + view: 'tree', + columnKey: 'value', + }); + + expect(rdg.columnWidths?.get('value')).toEqual({ type: 'resized', width: 275 }); + expect(rdg.columnWidths?.has('field')).toBe(false); + expect(document.activeElement).toBe(valueHeader); + }); + + it('fits by content through the Value header resize handle and returns focus to that header', async (): Promise => { + await render([nestedNode]); + reportColumnWidths( + new Map([ + ['field', { type: 'measured', width: 110 }], + ['value', { type: 'measured', width: 184.5 }], + ['type', { type: 'measured', width: 100 }], + ]), + ); + const doubleClicks = new Map(); + for (const label of ['Field', 'Value', 'Type']) { + const handle = header(label).querySelector('.rdg-resize-handle'); + if (!handle) { + throw new Error(`Missing resize handle: ${label}`); + } + doubleClicks.set(label, 0); + handle.addEventListener('dblclick', (): void => { + doubleClicks.set(label, (doubleClicks.get(label) ?? 0) + 1); + }); + } + const valueHeader = header('Value'); + vi.spyOn(valueHeader, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 184.5, 20)); + focusOutsideGrid(); + + await sendResizeMessage({ + type: 'collectionView.columnResize', + action: 'resizeByContent', + view: 'tree', + columnKey: 'value', + }); + + expect(Object.fromEntries(doubleClicks)).toEqual({ Field: 0, Value: 1, Type: 0 }); + expect(document.activeElement).toBe(valueHeader); + const fitted = rdg.columnWidths?.get('value'); + expect(fitted).toEqual({ type: 'resized', width: 184.5 }); + if (!fitted) { + throw new Error('Missing fitted width'); + } + + reportColumnWidths( + new Map([ + ['field', { type: 'measured', width: 130 }], + ['value', fitted], + ['type', { type: 'measured', width: 120 }], + ]), + ); + + expect(rdg.columnWidths?.get('value')).toEqual({ type: 'resized', width: 184.5 }); + expect(rdg.columnWidths?.get('field')).toEqual({ type: 'measured', width: 130 }); + expect(rdg.columnWidths?.get('type')).toEqual({ type: 'measured', width: 120 }); + }); + + it('keeps an RDG-reported fractional fit instead of the stale rendered Tree width', async (): Promise => { + await render([nestedNode]); + reportColumnWidths( + new Map([ + ['field', { type: 'measured', width: 110 }], + ['value', { type: 'measured', width: 150 }], + ['type', { type: 'measured', width: 100 }], + ]), + ); + const valueHeader = header('Value'); + vi.spyOn(valueHeader, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 150.5, 20)); + const handle = valueHeader.querySelector('.rdg-resize-handle'); + if (!handle) { + throw new Error('Missing Value resize handle'); + } + handle.addEventListener('dblclick', (): void => { + rdg.onColumnWidthsChange?.( + new Map([ + ['field', { type: 'measured', width: 110 }], + ['value', { type: 'resized', width: 420.25 }], + ['type', { type: 'measured', width: 100 }], + ]), + ); + }); + + await sendResizeMessage({ + type: 'collectionView.columnResize', + action: 'resizeByContent', + view: 'tree', + columnKey: 'value', + }); + + expect(rdg.columnWidths?.get('value')).toEqual({ type: 'resized', width: 420.25 }); + expect(rdg.columnWidths?.get('field')).toEqual({ type: 'measured', width: 110 }); + expect(rdg.columnWidths?.get('type')).toEqual({ type: 'measured', width: 100 }); + }); + + it('does not replace a previously explicit Tree width with the rendered fallback', async (): Promise => { + await render([nestedNode]); + reportColumnWidths(new Map([['value', { type: 'resized', width: 275 }]])); + vi.spyOn(header('Value'), 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 184.5, 20)); + + await sendResizeMessage({ + type: 'collectionView.columnResize', + action: 'resizeByContent', + view: 'tree', + columnKey: 'value', + }); + + expect(rdg.columnWidths?.get('value')).toEqual({ type: 'resized', width: 275 }); + }); + + it('keeps an explicit width when RDG re-measures neighboring automatic columns', async (): Promise => { + await render([nestedNode]); + reportColumnWidths( + new Map([ + ['field', { type: 'measured', width: 110 }], + ['value', { type: 'measured', width: 150 }], + ['type', { type: 'measured', width: 100 }], + ]), + ); + await sendResizeMessage({ + type: 'collectionView.columnResize', + action: 'resize', + view: 'tree', + columnKey: 'value', + width: 420, + }); + const resized = rdg.columnWidths?.get('value'); + expect(resized).toEqual({ type: 'resized', width: 420 }); + if (!resized) { + throw new Error('Missing resized width'); + } + + reportColumnWidths( + new Map([ + ['field', { type: 'measured', width: 130 }], + ['value', resized], + ['type', { type: 'measured', width: 120 }], + ]), + ); + + expect(rdg.columnWidths?.get('value')).toEqual({ type: 'resized', width: 420 }); + expect(rdg.columnWidths?.get('field')).toEqual({ type: 'measured', width: 130 }); + expect(rdg.columnWidths?.get('type')).toEqual({ type: 'measured', width: 120 }); + }); + it('publishes scoped native menu context for Tree headers', async (): Promise => { + await render([nestedNode]); + const fieldHeader = header('Field'); + fieldHeader.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true })); + + const context = JSON.parse(fieldHeader.dataset.vscodeContext ?? '{}') as Record; + expect(context).toMatchObject({ + preventDefaultContextMenuItems: true, + collectionViewColumnHeader: true, + collectionViewSessionId: 'session-tree', + collectionViewColumnView: 'tree', + collectionViewColumnKey: 'field', + collectionViewColumnLabel: 'Field', + }); + expect(typeof context.collectionViewColumnWidth).toBe('number'); + }); +}); diff --git a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.tsx b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.tsx index b63f07574..2fbe1caa8 100644 --- a/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.tsx +++ b/src/webviews/documentdb/collectionView/components/resultsTab/DataViewPanelTree.tsx @@ -5,19 +5,21 @@ import * as l10n from '@vscode/l10n'; import * as React from 'react'; -import { Cell, DataGrid, Row, type Column, type DataGridHandle } from 'react-data-grid'; +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 { 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 { useTreeRows } from './useTreeRows'; interface DataViewPanelTreeProps { readonly nodes: readonly TreeNode[]; + readonly columnResizeSessionId: string; } interface TreeFocusRecord { @@ -39,12 +41,33 @@ function treeCellText(row: TreeNode, key: Column['key']): string { } } -export const DataViewPanelTree = ({ nodes }: DataViewPanelTreeProps): React.JSX.Element => { +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 => { const gridRef = React.useRef(null); useColumnResizeKeyboardGuard(gridRef); const focusedCellRef = React.useRef(undefined); const previousNodesRef = React.useRef(nodes); const { rows, expandedKeys, setExpanded } = useTreeRows(nodes); + const [columnWidths, setColumnWidths] = React.useState(() => new Map()); + const resizeColumn = React.useCallback((columnKey: string, width: number): void => { + if (!TREE_COLUMN_KEYS.has(columnKey) || !Number.isSafeInteger(width) || width <= 0) { + return; + } + setColumnWidths((previous) => new Map(previous).set(columnKey, { type: 'resized', width })); + }, []); + const commitFittedWidth = React.useCallback((columnKey: string, width: number): void => { + if (!TREE_COLUMN_KEYS.has(columnKey) || !Number.isFinite(width) || width <= 0) { + return; + } + setColumnWidths((previous) => + previous.get(columnKey)?.type === 'resized' + ? previous + : new Map(previous).set(columnKey, { type: 'resized', width }), + ); + }, []); const columns = React.useMemo[]>( (): readonly Column[] => [ { @@ -95,6 +118,22 @@ export const DataViewPanelTree = ({ nodes }: DataViewPanelTreeProps): React.JSX. ], [expandedKeys], ); + 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 }, + ], + [], + ); + useCollectionViewColumnHeaderActions({ + gridRef, + sessionId: columnResizeSessionId, + view: 'tree', + columns: headerActions, + resizeColumn, + commitFittedWidth, + }); const focusedCellText = React.useCallback( (rowIdx: number, columnIdx: number): string | undefined => { const row = rows[rowIdx]; @@ -185,6 +224,8 @@ export const DataViewPanelTree = ({ nodes }: DataViewPanelTreeProps): React.JSX. aria-label={l10n.t('Tree View')} className="documentDataGrid" columns={columns} + columnWidths={columnWidths} + onColumnWidthsChange={setColumnWidths} rows={rows} getRowKey={(row): string => row.key} defaultColumnOptions={{ minWidth: 100, resizable: true }} diff --git a/src/webviews/documentdb/collectionView/components/resultsTab/TypedValueCell.tsx b/src/webviews/documentdb/collectionView/components/resultsTab/TypedValueCell.tsx index b0e6c6b2a..a5db28248 100644 --- a/src/webviews/documentdb/collectionView/components/resultsTab/TypedValueCell.tsx +++ b/src/webviews/documentdb/collectionView/components/resultsTab/TypedValueCell.tsx @@ -59,7 +59,9 @@ const useStyles = makeStyles({ marginInlineStart: 'auto', paddingInlineStart: '3px', fontSize: 'smaller', - opacity: 0.4, + // Inherits the row color, so it follows selection and theme overrides. Below about 0.67 + // the marker drops under 4.5:1 on hovered and selected rows in Dark 2026 (#382, #771). + opacity: 0.8, }, srOnly: { position: 'absolute', diff --git a/src/webviews/documentdb/collectionView/components/resultsTab/collectionViewColumnContextMenu.ts b/src/webviews/documentdb/collectionView/components/resultsTab/collectionViewColumnContextMenu.ts new file mode 100644 index 000000000..51ca9ed12 --- /dev/null +++ b/src/webviews/documentdb/collectionView/components/resultsTab/collectionViewColumnContextMenu.ts @@ -0,0 +1,52 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export const COLLECTION_VIEW_COLUMN_CONTEXT_MENU_COMMANDS = { + resize: 'vscode-documentdb.command.collectionView.column.resize', + resizeByContent: 'vscode-documentdb.command.collectionView.column.resizeByContent', +} as const; + +export type CollectionViewColumnContextMenuCommandId = + (typeof COLLECTION_VIEW_COLUMN_CONTEXT_MENU_COMMANDS)[keyof typeof COLLECTION_VIEW_COLUMN_CONTEXT_MENU_COMMANDS]; + +export type CollectionViewColumnView = 'table' | 'tree'; + +/** Upper bound for exact and content-fitted column widths, in CSS pixels. */ +export const MAX_COLUMN_WIDTH = 2000; + +/** The `data-vscode-context` payload on a Results column header. */ +export interface CollectionViewColumnContextMenuContext { + readonly preventDefaultContextMenuItems: true; + readonly collectionViewColumnHeader: true; + readonly collectionViewSessionId: string; + readonly collectionViewColumnView: CollectionViewColumnView; + readonly collectionViewColumnKey: string; + readonly collectionViewColumnLabel: string; + readonly collectionViewColumnWidth: number; +} + +export interface CollectionViewColumnResizeMessage { + readonly type: 'collectionView.columnResize'; + readonly action: 'resize' | 'resizeByContent'; + readonly columnKey: string; + readonly view: CollectionViewColumnView; + /** `undefined` means the exact-width prompt was cancelled. */ + readonly width?: number; +} + +export function isCollectionViewColumnResizeMessage(value: unknown): value is CollectionViewColumnResizeMessage { + if (typeof value !== 'object' || value === null) { + return false; + } + + const message = value as Partial; + return ( + message.type === 'collectionView.columnResize' && + (message.action === 'resize' || message.action === 'resizeByContent') && + typeof message.columnKey === 'string' && + (message.view === 'table' || message.view === 'tree') && + (message.width === undefined || typeof message.width === 'number') + ); +} diff --git a/src/webviews/documentdb/collectionView/components/resultsTab/dataGridTheme.scss b/src/webviews/documentdb/collectionView/components/resultsTab/dataGridTheme.scss index 5e5335fde..93d3e3188 100644 --- a/src/webviews/documentdb/collectionView/components/resultsTab/dataGridTheme.scss +++ b/src/webviews/documentdb/collectionView/components/resultsTab/dataGridTheme.scss @@ -90,8 +90,10 @@ --vscode-list-activeSelectionForeground, var(--vscode-list-inactiveSelectionForeground, var(--vscode-editor-foreground)) ); - --rdg-selection-color: var(--vscode-focusBorder); - --rdg-checkbox-focus-color: var(--vscode-focusBorder); + // Fluent's focus color, as on the extension's other Fluent controls. focusBorder is under + // 3:1 on Dark 2026 rows (#775). RDG already draws the ring at Fluent's 2px. + --rdg-selection-color: var(--colorStrokeFocus2, var(--vscode-focusBorder)); + --rdg-checkbox-focus-color: var(--colorStrokeFocus2, var(--vscode-focusBorder)); :is(.disableHighlightOnHover, body.vscode-reduce-motion) & { --rdg-row-hover-background-color: var(--rdg-background-color); diff --git a/src/webviews/documentdb/collectionView/components/resultsTab/useCollectionViewColumnHeaderActions.ts b/src/webviews/documentdb/collectionView/components/resultsTab/useCollectionViewColumnHeaderActions.ts new file mode 100644 index 000000000..1a44f4f97 --- /dev/null +++ b/src/webviews/documentdb/collectionView/components/resultsTab/useCollectionViewColumnHeaderActions.ts @@ -0,0 +1,185 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as React from 'react'; +import { type DataGridHandle } from 'react-data-grid'; +import { + type CollectionViewColumnContextMenuContext, + type CollectionViewColumnView, + isCollectionViewColumnResizeMessage, + MAX_COLUMN_WIDTH, +} from './collectionViewColumnContextMenu'; + +export interface CollectionViewColumnHeader { + readonly key: string; + readonly label: string; + readonly minWidth: number; +} + +interface UseCollectionViewColumnHeaderActionsOptions { + readonly gridRef: React.RefObject; + readonly sessionId: string; + readonly view: CollectionViewColumnView; + readonly columns: readonly CollectionViewColumnHeader[]; + readonly resizeColumn: (columnKey: string, width: number) => void; + readonly commitFittedWidth: (columnKey: string, width: number) => void; +} + +function columnIndexOf(element: Element): number { + return Number(element.getAttribute('aria-colindex')) - 1; +} + +function findHeader(grid: HTMLElement, columnIndex: number): HTMLElement | undefined { + return [...grid.querySelectorAll('[role="columnheader"]')].find( + (header) => columnIndexOf(header) === columnIndex, + ); +} + +export function useCollectionViewColumnHeaderActions({ + gridRef, + sessionId, + view, + columns, + resizeColumn, + commitFittedWidth, +}: UseCollectionViewColumnHeaderActionsOptions): void { + const latestRef = React.useRef({ sessionId, view, columns }); + React.useLayoutEffect(() => { + latestRef.current = { sessionId, view, columns }; + }, [columns, sessionId, view]); + + // RDG virtualizes headers, so the menu context is stamped lazily on the header that receives + // `contextmenu` (pointer or keyboard). Capture phase runs before VS Code's own listener reads it. + const listenerRef = React.useRef<{ readonly grid: HTMLElement; readonly dispose: () => void } | undefined>( + undefined, + ); + const menuColumnIndexRef = React.useRef(undefined); + React.useEffect(() => { + const grid = gridRef.current?.element ?? undefined; + if (listenerRef.current?.grid === grid) { + return; + } + listenerRef.current?.dispose(); + listenerRef.current = undefined; + if (!grid) { + return; + } + + const handleContextMenu = (event: MouseEvent): void => { + const target = event.target; + if (!(target instanceof Element)) { + return; + } + const header = target.closest('[role="columnheader"]'); + if (!header || !grid.contains(header)) { + return; + } + const latest = latestRef.current; + const column = latest.columns[columnIndexOf(header)]; + if (!column) { + delete header.dataset.vscodeContext; + delete header.dataset.collectionViewColumnKey; + return; + } + const context: CollectionViewColumnContextMenuContext = { + preventDefaultContextMenuItems: true, + collectionViewColumnHeader: true, + collectionViewSessionId: latest.sessionId, + collectionViewColumnView: latest.view, + collectionViewColumnKey: column.key, + collectionViewColumnLabel: column.label, + collectionViewColumnWidth: header.getBoundingClientRect().width, + }; + header.dataset.collectionViewColumnKey = column.key; + header.dataset.vscodeContext = JSON.stringify(context); + menuColumnIndexRef.current = columnIndexOf(header); + }; + + grid.addEventListener('contextmenu', handleContextMenu, true); + listenerRef.current = { + grid, + dispose: (): void => grid.removeEventListener('contextmenu', handleContextMenu, true), + }; + }); + React.useEffect( + () => (): void => { + listenerRef.current?.dispose(); + listenerRef.current = undefined; + }, + [], + ); + + // Closing the native menu with Escape refocuses the webview with `body` active, so the + // invoking header is restored unless focus has already moved to another element. + React.useEffect(() => { + let timer: ReturnType | undefined; + const handleWindowFocus = (): void => { + const columnIndex = menuColumnIndexRef.current; + menuColumnIndexRef.current = undefined; + if (columnIndex === undefined) { + return; + } + clearTimeout(timer); + timer = setTimeout(() => { + const grid = gridRef.current?.element; + const active = document.activeElement; + if (grid && (active === null || active === document.body || active === document.documentElement)) { + findHeader(grid, columnIndex)?.focus({ preventScroll: true }); + } + }, 0); + }; + + window.addEventListener('focus', handleWindowFocus); + return () => { + clearTimeout(timer); + window.removeEventListener('focus', handleWindowFocus); + }; + }, [gridRef]); + + React.useEffect(() => { + const handleMessage = (event: MessageEvent): void => { + if (!isCollectionViewColumnResizeMessage(event.data) || event.data.view !== view) { + return; + } + const message = event.data; + const columnIndex = columns.findIndex((column) => column.key === message.columnKey); + const column = columns[columnIndex]; + const grid = gridRef.current?.element; + if (columnIndex === -1 || !column || !grid) { + return; + } + + if (message.action === 'resize') { + if ( + message.width !== undefined && + Number.isSafeInteger(message.width) && + message.width >= column.minWidth && + message.width <= MAX_COLUMN_WIDTH + ) { + resizeColumn(column.key, message.width); + } + } else { + const header = findHeader(grid, columnIndex); + const resizeHandle = header?.querySelector('.rdg-resize-handle'); + if (header && resizeHandle) { + resizeHandle.dispatchEvent( + new MouseEvent('dblclick', { bubbles: true, cancelable: true, button: 0 }), + ); + // RDG reports only changed fits; pin the rendered width when it leaves the column automatic. + commitFittedWidth(column.key, header.getBoundingClientRect().width); + } + } + queueMicrotask(() => { + const currentGrid = gridRef.current?.element; + if (currentGrid) { + findHeader(currentGrid, columnIndex)?.focus(); + } + }); + }; + + window.addEventListener('message', handleMessage); + return () => window.removeEventListener('message', handleMessage); + }, [columns, commitFittedWidth, gridRef, resizeColumn, view]); +} diff --git a/src/webviews/documentdb/collectionView/components/resultsTab/useStableColumnWidths.ts b/src/webviews/documentdb/collectionView/components/resultsTab/useStableColumnWidths.ts index 35fcd6653..2235286ed 100644 --- a/src/webviews/documentdb/collectionView/components/resultsTab/useStableColumnWidths.ts +++ b/src/webviews/documentdb/collectionView/components/resultsTab/useStableColumnWidths.ts @@ -24,6 +24,8 @@ export interface ColumnWidthScope { export interface StableColumnWidths { readonly columnWidths: ColumnWidths; readonly onColumnWidthsChange: (widths: ColumnWidths) => void; + readonly resizeColumn: (columnKey: string, width: number) => void; + readonly commitFittedWidth: (columnKey: string, width: number) => void; readonly overrideFor: (columnKey: string) => { readonly width?: number; readonly minWidth?: number; @@ -269,6 +271,41 @@ export function useStableColumnWidths( [columnWidths, fill, hold], ); + const resizeColumn = React.useCallback( + (columnKey: string, width: number): void => { + if (!columnKeySet.has(columnKey) || !Number.isSafeInteger(width) || width <= 0) { + return; + } + setState((current) => { + const previous = current.widths.get(columnKey); + if (previous?.type === 'resized' && previous.width === width) { + return current; + } + const widths = new Map(current.widths); + widths.set(columnKey, { type: 'resized', width }); + return { ...current, widths }; + }); + }, + [columnKeySet], + ); + + const commitFittedWidth = React.useCallback( + (columnKey: string, width: number): void => { + if (!columnKeySet.has(columnKey) || !Number.isFinite(width) || width <= 0) { + return; + } + setState((current) => { + if (current.widths.get(columnKey)?.type === 'resized') { + return current; + } + const widths = new Map(current.widths); + widths.set(columnKey, { type: 'resized', width }); + return { ...current, widths }; + }); + }, + [columnKeySet], + ); + React.useEffect(() => { if (cache.queryKey !== state.queryKey) { return; @@ -420,5 +457,5 @@ export function useStableColumnWidths( return () => observer.disconnect(); }, [attached, gridRef]); - return { columnWidths, onColumnWidthsChange, overrideFor }; + return { columnWidths, onColumnWidthsChange, resizeColumn, commitFittedWidth, overrideFor }; } diff --git a/src/webviews/documentdb/collectionView/indexesTab/indexesTab.scss b/src/webviews/documentdb/collectionView/indexesTab/indexesTab.scss index d5e0305ad..36781b1b9 100644 --- a/src/webviews/documentdb/collectionView/indexesTab/indexesTab.scss +++ b/src/webviews/documentdb/collectionView/indexesTab/indexesTab.scss @@ -352,9 +352,10 @@ font-family: var(--fontFamilyMonospace); } + // Full badge color: the tinted badge leaves no contrast headroom for opacity, and the + // direction is sometimes a word (text, hashed, 2dsphere). .keyBadgeDir { margin-left: 6px; - opacity: 0.8; } // Present-only facts list (definition list). diff --git a/src/webviews/documentdb/collectionView/queryInsightsTab/components/optimizationCards/ImprovementCard.test.tsx b/src/webviews/documentdb/collectionView/queryInsightsTab/components/optimizationCards/ImprovementCard.test.tsx new file mode 100644 index 000000000..d3335f47c --- /dev/null +++ b/src/webviews/documentdb/collectionView/queryInsightsTab/components/optimizationCards/ImprovementCard.test.tsx @@ -0,0 +1,181 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// @vitest-environment jsdom + +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; // eslint-disable-line import/no-internal-modules +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { type ImprovementCard as ImprovementCardConfig } from '../../../types/queryInsights'; +import { ImprovementCard } from './ImprovementCard'; + +vi.mock('@vscode/l10n', () => ({ + t: (message: string, ...args: unknown[]): string => + args.reduce((result, arg, index) => result.replace(`{${index}}`, String(arg)), message), +})); + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +interface ActionResult { + success: boolean; + message?: string; +} + +interface Deferred { + promise: Promise; + resolve: (result: ActionResult) => void; +} + +const mounted: { host: HTMLElement; root: Root }[] = []; + +function deferred(): Deferred { + let resolve: (result: ActionResult) => void = () => undefined; + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise; + }); + return { promise, resolve }; +} + +async function renderCard( + primaryAction?: (actionId: string, payload: unknown) => Promise, + secondaryAction?: (actionId: string, payload: unknown) => Promise, +): Promise { + const config: ImprovementCardConfig = { + type: 'improvement', + cardId: 'card-1', + title: 'Create an index', + priority: 'high', + description: 'An index can improve this query.', + recommendedIndex: '{ field: 1 }', + indexName: 'field_1', + recommendedIndexDetails: 'Indexes the field in ascending order.', + details: 'Check the index build cost.', + shellCommand: 'db.collection.createIndex({ field: 1 })', + primaryButton: { + label: 'Primary action', + actionId: 'primaryAction', + payload: { source: 'primary' }, + }, + secondaryButton: { + label: 'Secondary action', + actionId: 'secondaryAction', + payload: { source: 'secondary' }, + }, + }; + const host = document.createElement('div'); + document.body.appendChild(host); + const root = createRoot(host); + mounted.push({ host, root }); + await act(async () => { + root.render( + , + ); + }); + return host; +} + +function buttonWithLabel(host: HTMLElement, label: string): HTMLButtonElement { + const button = Array.from(host.querySelectorAll('button')).find( + (candidate) => candidate.textContent?.trim() === label, + ); + if (!button) { + throw new Error(`Missing button: ${label}`); + } + return button; +} + +afterEach(async () => { + for (const { host, root } of mounted.splice(0)) { + await act(async () => root.unmount()); + host.remove(); + } + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +describe('ImprovementCard action announcements', () => { + it.each(['primary', 'secondary'] as const)( + 'keeps focus and announces %s success without allowing duplicate clicks', + async (actionKind) => { + vi.useFakeTimers(); + const pending = deferred(); + const action = vi.fn((_actionId: string, _payload: unknown) => pending.promise); + const host = actionKind === 'primary' ? await renderCard(action) : await renderCard(undefined, action); + const regions = Array.from(host.querySelectorAll('[role="status"]')); + const politeRegions = Array.from(host.querySelectorAll('[aria-live="polite"]')); + const successRegion = politeRegions[actionKind === 'primary' ? 0 : 1]; + const button = buttonWithLabel(host, actionKind === 'primary' ? 'Primary action' : 'Secondary action'); + + expect(regions).toHaveLength(4); + expect(regions.every((region) => region.textContent === '')).toBe(true); + button.focus(); + + await act(async () => button.click()); + expect(button.getAttribute('aria-disabled')).toBe('true'); + expect(button.hasAttribute('disabled')).toBe(false); + expect(document.activeElement).toBe(button); + + await act(async () => button.click()); + expect(action).toHaveBeenCalledTimes(1); + + await act(async () => { + pending.resolve({ success: true, message: `${actionKind} completed` }); + await pending.promise; + }); + expect(document.activeElement).toBe(button); + + await act(async () => vi.advanceTimersByTimeAsync(100)); + const currentSuccessRegion = Array.from(host.querySelectorAll('[aria-live="polite"]'))[ + actionKind === 'primary' ? 0 : 1 + ]; + expect(currentSuccessRegion).toBe(successRegion); + expect(successRegion.textContent).toBe(`${actionKind} completed`); + expect(document.activeElement).toBe(button); + + await act(async () => button.click()); + expect(action).toHaveBeenCalledTimes(1); + }, + ); + + it.each(['primary', 'secondary'] as const)( + 'announces repeated %s failures as assertive retry messages', + async (actionKind) => { + vi.useFakeTimers(); + const first = deferred(); + const second = deferred(); + const action = vi + .fn((_actionId: string, _payload: unknown) => first.promise) + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise); + const host = actionKind === 'primary' ? await renderCard(action) : await renderCard(undefined, action); + const errorRegion = Array.from(host.querySelectorAll('[aria-live="assertive"]'))[ + actionKind === 'primary' ? 0 : 1 + ]; + const button = buttonWithLabel(host, actionKind === 'primary' ? 'Primary action' : 'Secondary action'); + + await act(async () => button.click()); + await act(async () => { + first.resolve({ success: false, message: 'Try again' }); + await first.promise; + }); + await act(async () => vi.advanceTimersByTimeAsync(100)); + expect(errorRegion.textContent).toBe('Error: Try again'); + expect(button.textContent?.trim()).toBe('Retry'); + + await act(async () => button.click()); + await act(async () => vi.advanceTimersByTimeAsync(0)); + expect(errorRegion.textContent).toBe(''); + + await act(async () => { + second.resolve({ success: false, message: 'Try again' }); + await second.promise; + }); + await act(async () => vi.advanceTimersByTimeAsync(100)); + expect(errorRegion.textContent).toBe('Error: Try again'); + expect(action).toHaveBeenCalledTimes(2); + }, + ); +}); diff --git a/src/webviews/documentdb/collectionView/queryInsightsTab/components/optimizationCards/ImprovementCard.tsx b/src/webviews/documentdb/collectionView/queryInsightsTab/components/optimizationCards/ImprovementCard.tsx index 09e00e8d6..a96e4e5e9 100644 --- a/src/webviews/documentdb/collectionView/queryInsightsTab/components/optimizationCards/ImprovementCard.tsx +++ b/src/webviews/documentdb/collectionView/queryInsightsTab/components/optimizationCards/ImprovementCard.tsx @@ -21,6 +21,7 @@ import { ArrowTrendingSparkleRegular } from '@fluentui/react-icons'; // import { CopyRegular } from '@fluentui/react-icons'; import * as l10n from '@vscode/l10n'; import { useState } from 'react'; +import { Announcer } from '../../../../../components/accessibility'; import { type ImprovementCard as ImprovementCardConfig } from '../../../types/queryInsights'; import './baseOptimizationCard.scss'; @@ -277,13 +278,29 @@ export function ImprovementCard({ )} + + + + + {/* Action Buttons */}
{config.primaryButton && (