Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/main/store/settingsStore.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { readFileSync, writeFileSync, existsSync } from 'node:fs'
import { join } from 'node:path'
import { app } from 'electron'
import { DEFAULT_SETTINGS, type AppSettings } from '../../shared/types'
import { DEFAULT_SETTINGS, isValidResultViewSelection, type AppSettings } from '../../shared/types'

interface SettingsFile {
version: 1
Expand All @@ -17,6 +17,7 @@ function mergeSettings(stored?: Partial<AppSettings>): AppSettings {
return {
...DEFAULT_SETTINGS,
...stored,
enabledResultViews: isValidResultViewSelection(stored?.enabledResultViews) ? stored.enabledResultViews : DEFAULT_SETTINGS.enabledResultViews,
defaultExportDirectory: defaultExportDirectory(stored)
}
}
Expand Down Expand Up @@ -50,6 +51,9 @@ class SettingsStore {
}

update(patch: Partial<AppSettings>): AppSettings {
if ('enabledResultViews' in patch && !isValidResultViewSelection(patch.enabledResultViews)) {
throw new Error('Invalid result view selection.')
}
this.data.settings = { ...this.data.settings, ...patch }
this.persist()
return this.data.settings
Expand Down
31 changes: 19 additions & 12 deletions src/renderer/src/components/results/ResultPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { Braces, ChartColumn, Check, ChevronLeft, ChevronRight, Copy, LayoutGrid, Maximize2, Minimize2, Network, Pin, PinOff, SlidersHorizontal, Table, Table2 } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { QUERY_LIMITS, type JsonEncoding, type ResultExportFormat, type ShellResult } from '@shared/types'
import { useAppStore, getActiveTab, getActiveResult, type ResultView } from '@renderer/store/useAppStore'
import { QUERY_LIMITS, RESULT_VIEWS, type JsonEncoding, type ResultExportFormat, type ShellResult } from '@shared/types'
import { useAppStore, getActiveTab, getActiveResult } from '@renderer/store/useAppStore'
import type { ResultChartConfig } from '@renderer/lib/resultChart'
import { resultTabLabel, type ResultFoldView, type ResultTab } from '@renderer/lib/tabs'
import { RESULT_VIEW_LABELS, resultTabLabel, type ResultFoldView, type ResultTab } from '@renderer/lib/tabs'
import { formatQueryTime, formatRelativeQueryTime } from '@renderer/lib/queryTime'
import { resolveResultTimeZone } from '@renderer/lib/dateTimeZone'
import { docActionContext } from '@renderer/lib/docActions'
Expand Down Expand Up @@ -141,7 +141,9 @@ function ResultPanelContent({
if (!liveIds.has(id)) gridStates.current.delete(id)
}
}), [])
const view = active?.resultView ?? 'tree'
const enabledViews = useAppStore((s) => s.settings.enabledResultViews)
const views = enabledViews.filter((mode) => mode !== 'chart' || result?.kind === 'documents')
const view = active?.resultView && views.includes(active.resultView) ? active.resultView : views[0]
const fieldSort = useAppStore((s) => s.settings.resultFieldSort)
const fieldInfo = useResultFieldInfo(docs, view === 'table' || view === 'chart')
const displayFields = useMemo(() => {
Expand Down Expand Up @@ -245,7 +247,6 @@ function ResultPanelContent({
const switchable = !!result && result.kind !== 'error' && result.kind !== 'explain'
useEffect(() => {
if (!switchable || !isAppShortcutEnabled(keyboardShortcutsEnabled, disabledKeyboardShortcuts, 'resultView')) return
const views: ResultView[] = ['tree', 'json', 'table', 'grid']
const onKey = (e: KeyboardEvent): void => {
if (hasOpenShortcutLayer()) return
const index = primaryDigitIndex(e, isMacPlatform())
Expand All @@ -256,16 +257,16 @@ function ResultPanelContent({
chooseConsole(true)
return
}
const target = index == null ? undefined : views[index]
if (!target) return
const target = index == null ? undefined : RESULT_VIEWS[index]
if (!target || !enabledViews.includes(target)) return
e.preventDefault()
e.stopPropagation()
chooseConsole(false)
setView(target)
}
window.addEventListener('keydown', onKey, true)
return () => window.removeEventListener('keydown', onKey, true)
}, [switchable, hasOutput, active?.id, results, setView, disabledKeyboardShortcuts, keyboardShortcutsEnabled])
}, [switchable, enabledViews, hasOutput, active?.id, results, setView, disabledKeyboardShortcuts, keyboardShortcutsEnabled])

useEffect(() => {
if (!result && expanded) onExpandedChange(false)
Expand Down Expand Up @@ -359,8 +360,9 @@ function ResultPanelContent({
{strip}
<div className="result-bar flex-wrap">
<div className="view-switch sliding-selection shrink-0">
{(['tree', 'json', 'table', 'grid'] as ResultView[]).map((v, i) => {
const label = v === 'tree' ? 'Tree' : v === 'json' ? 'JSON' : v === 'table' ? 'Table' : 'Grid'
{RESULT_VIEWS.map((v, i) => {
if (v === 'chart' || !views.includes(v)) return null
const label = RESULT_VIEW_LABELS[v]
const Icon = v === 'tree' ? Network : v === 'json' ? Braces : v === 'table' ? Table : LayoutGrid
return (
<Tooltip key={v} content={`${label} (${primaryKey}${i + 1})`} disabled={!viewShortcutEnabled}>
Expand All @@ -382,7 +384,7 @@ function ResultPanelContent({
</Tooltip>
)
})}
{result.kind === 'documents' && (
{views.includes('chart') && (
<button
className={`group/result-view flex items-center justify-center ${!showConsole && view === 'chart' ? 'active is-selected' : ''}`}
aria-label={t('chart.title')}
Expand All @@ -392,6 +394,11 @@ function ResultPanelContent({
<span className="inline-flex items-center gap-1"><ChartColumn size={12} aria-hidden="true" />{t('chart.title')}</span>
</button>
)}
{!view && (
<button className={showConsole ? '' : 'active is-selected'} aria-pressed={!showConsole} onClick={() => chooseConsole(false)}>
{t('context.result')}
</button>
)}
{hasOutput && (
<Tooltip content={`Console (${primaryKey}5)`} disabled={!viewShortcutEnabled}>
<button
Expand Down Expand Up @@ -495,7 +502,7 @@ function ResultPanelContent({
docCtx={docCtx}
/>
)}
{view === 'json' && <JsonView folding={foldingFor('json')} value={docs} visibleFields={visibleFields} onSelectFields={openFieldModal} fontSize={dataFontSize} controlsContainer={foldControls} />}
{(!view || view === 'json') && <JsonView folding={foldingFor('json')} value={view ? docs : result.data} visibleFields={visibleFields} onSelectFields={openFieldModal} fontSize={dataFontSize} controlsContainer={foldControls} />}
{view === 'grid' && gridState && (
<GridView
key={active?.id}
Expand Down
24 changes: 24 additions & 0 deletions src/renderer/src/components/settings/SettingsWindow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ import {
HISTORY_LIMITS,
QUERY_LIMITS,
QUERY_TIMEOUTS_MS,
RESULT_VIEWS,
type CollectionSort,
type KeyboardShortcutId,
type Language,
type TableNestedDisplay,
type ThemeMode
} from '@shared/types'
import { setLanguage } from '@renderer/i18n'
import { RESULT_VIEW_LABELS } from '@renderer/lib/tabs'
import { matchesSettingsSearch } from '@renderer/lib/settingsSearch'
import { useAppStore } from '@renderer/store/useAppStore'
import { Button } from '@renderer/components/common/Button'
Expand Down Expand Up @@ -111,6 +113,9 @@ export function SettingsWindow({ onClose }: { onClose?: () => void }): React.JSX
t('settings.timeZone'),
t('settings.timeZoneSystem'),
t('settings.timeZoneHint'),
t('settings.enabledResultViews'),
...Object.values(RESULT_VIEW_LABELS),
t('chart.title'),
t('settings.resultFieldSort'),
t('settings.resultIdFirst'),
t('settings.tableNestedDisplay'),
Expand Down Expand Up @@ -436,6 +441,25 @@ export function SettingsWindow({ onClose }: { onClose?: () => void }): React.JSX
]}
/>
</Field>
<fieldset className="m-0 mb-4 border-0 p-0">
<legend className="mb-2 p-0 text-[11px] font-medium text-muted-foreground">{t('settings.enabledResultViews')}</legend>
<div className="flex flex-wrap gap-x-4 gap-y-2">
{RESULT_VIEWS.map((view) => {
const checked = settings.enabledResultViews.includes(view)
return (
<Checkbox
key={view}
label={view === 'chart' ? t('chart.title') : RESULT_VIEW_LABELS[view]}
checked={checked}
disabled={checked && settings.enabledResultViews.length === 1}
onCheckedChange={(enabled) => void updateSettings({
enabledResultViews: RESULT_VIEWS.filter((mode) => mode === view ? enabled : settings.enabledResultViews.includes(mode))
})}
/>
)
})}
</div>
</fieldset>
<Field label={t('settings.resultFieldSort')}>
<Select<CollectionSort>
value={settings.resultFieldSort}
Expand Down
2 changes: 1 addition & 1 deletion src/renderer/src/components/ui/Checkbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export function Checkbox({
return (
<BaseCheckbox.Root
className={cn(
'group m-0 inline-flex w-auto cursor-pointer items-center gap-2 border-0 bg-transparent p-0 text-left text-[13px] text-foreground/90 outline-none hover:bg-transparent focus-visible:shadow-none disabled:cursor-default disabled:opacity-55',
'group m-0 inline-flex w-auto cursor-pointer items-center gap-2 border-0 bg-transparent p-0 text-left text-[13px] text-foreground/90 outline-none hover:bg-transparent focus-visible:shadow-none data-[disabled]:cursor-default data-[disabled]:opacity-55',
className
)}
checked={checked}
Expand Down
3 changes: 2 additions & 1 deletion src/renderer/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
"sortNatural": "Natural (server order)",
"sortAlpha": "Name ascending",
"sortAlphaDesc": "Name descending",
"enabledResultViews": "Result views",
"resultFieldSort": "Query result field sort",
"resultIdFirst": "Show _id first",
"defaultExportDirectory": "Default export directory",
Expand Down Expand Up @@ -94,7 +95,7 @@
"shortcutTabs": "Switch Tabs (9: last)",
"shortcutQueryTabs": "Query",
"shortcutDataTabs": "Result",
"shortcutResultView": "Switch Tree / JSON / Table / Grid / Console",
"shortcutResultView": "Switch result view",
"shortcutOpenSettings": "Open Settings",
"shortcutClear": "Clear",
"shortcutRestore": "Restore",
Expand Down
3 changes: 2 additions & 1 deletion src/renderer/src/i18n/locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
"sortNatural": "自然顺序(服务器顺序)",
"sortAlpha": "名称升序",
"sortAlphaDesc": "名称降序",
"enabledResultViews": "结果视图",
"resultFieldSort": "查询结果字段排序",
"resultIdFirst": "_id 优先显示",
"defaultExportDirectory": "默认导出目录",
Expand Down Expand Up @@ -94,7 +95,7 @@
"shortcutTabs": "切换 Tab(9:末尾)",
"shortcutQueryTabs": "查询",
"shortcutDataTabs": "结果",
"shortcutResultView": "切换树形 / JSON / 表格 / Grid / Console",
"shortcutResultView": "切换结果视图",
"shortcutOpenSettings": "打开设置",
"shortcutClear": "清除",
"shortcutRestore": "恢复",
Expand Down
3 changes: 2 additions & 1 deletion src/renderer/src/i18n/locales/zh-TW.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
"sortNatural": "自然順序(伺服器順序)",
"sortAlpha": "名稱升冪",
"sortAlphaDesc": "名稱降冪",
"enabledResultViews": "結果檢視",
"resultFieldSort": "查詢結果欄位排序",
"resultIdFirst": "_id 優先顯示",
"defaultExportDirectory": "預設匯出目錄",
Expand Down Expand Up @@ -94,7 +95,7 @@
"shortcutTabs": "切換 Tab(9:末尾)",
"shortcutQueryTabs": "查詢",
"shortcutDataTabs": "結果",
"shortcutResultView": "切換樹狀 / JSON / 表格 / Grid / Console",
"shortcutResultView": "切換結果檢視",
"shortcutOpenSettings": "開啟設定",
"shortcutClear": "清除",
"shortcutRestore": "恢復",
Expand Down
5 changes: 3 additions & 2 deletions src/renderer/src/lib/tabs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
* outcomes can be compared side by side.
* Keeping the list/label logic here (no store, no React) makes it unit-testable.
*/
import type { ShellResult } from '@shared/types'
import type { ResultView, ShellResult } from '@shared/types'
import type { ResultChartConfig } from './resultChart'

export type ResultView = 'tree' | 'json' | 'table' | 'grid' | 'chart'
export type { ResultView }
export const RESULT_VIEW_LABELS = { tree: 'Tree', json: 'JSON', table: 'Table', grid: 'Grid' } as const
export type ResultFoldView = 'json' | 'console' | 'explain'

/** The query that produced a result (refresh / doc-edit target). */
Expand Down
10 changes: 10 additions & 0 deletions src/shared/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,14 @@ export type Language = 'system' | 'en' | 'zh-CN' | 'zh-TW'

export type KeyboardShortcutId =
'newConnection' | 'newQuery' | 'tabSearch' | 'quickSearch' | 'contextualTabs' | 'resultView' | 'openSettings'
export const RESULT_VIEWS = ['tree', 'json', 'table', 'grid', 'chart'] as const
export type ResultView = (typeof RESULT_VIEWS)[number]

export function isValidResultViewSelection(value: unknown): value is ResultView[] {
return Array.isArray(value) && value.length > 0 && value.length === new Set(value).size
&& value.every((view) => RESULT_VIEWS.includes(view))
}

export type TableNestedDisplay = 'inline' | 'grouped' | 'auto'
export type GridHeightMode = 'fixed' | 'expanded'

Expand All @@ -597,6 +605,7 @@ export interface AppSettings {
collectionSort: CollectionSort
resultFieldSort: CollectionSort
resultIdFirst: boolean
enabledResultViews: ResultView[]
/** 'system' = follow OS (default); 'light' = Stone; 'dark' = Stone Night. */
theme: ThemeMode
/** UI language. 'system' (default) follows the OS/app locale. */
Expand Down Expand Up @@ -679,6 +688,7 @@ export const DEFAULT_SETTINGS: AppSettings = {
collectionSort: 'alpha',
resultFieldSort: 'alpha',
resultIdFirst: true,
enabledResultViews: ['tree', 'json', 'table'],
theme: 'system',
language: 'system',
dateTimeZone: 'system',
Expand Down
2 changes: 2 additions & 0 deletions src/shared/webSettings.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
DEFAULT_SETTINGS,
HISTORY_LIMITS,
isValidResultViewSelection,
QUERY_LIMITS,
QUERY_TIMEOUTS_MS,
type AppSettings,
Expand Down Expand Up @@ -31,6 +32,7 @@ export function mergeWebSettings(
!next.connectionOrder.every((item) => typeof item === "string") ||
!["natural", "alpha", "alphaDesc"].includes(next.collectionSort) ||
!["natural", "alpha", "alphaDesc"].includes(next.resultFieldSort) ||
!isValidResultViewSelection(next.enabledResultViews) ||
typeof next.resultIdFirst !== "boolean" ||
!["light", "dark", "system"].includes(next.theme) ||
!["system", "en", "zh-CN", "zh-TW"].includes(next.language) ||
Expand Down
3 changes: 3 additions & 0 deletions test/e2e/charts.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import assert from 'node:assert/strict'
import { writeFile } from 'node:fs/promises'
import test from 'node:test'
import { clickElement, waitForExpression } from '../helpers/packagedElectron.mjs'
import { updateRendererSettings } from '../helpers/quickSearch.mjs'
import { runShellScenario } from '../helpers/shellUi.mjs'

test('Chart examples teach a configuration and map it to compatible result fields', { timeout: 120_000 }, () =>
runShellScenario('chart-examples', async ({ renderer, enterQuery, key, modifier, report }) => {
await updateRendererSettings(renderer, { enabledResultViews: ['tree', 'json', 'table', 'chart'] })
const dialog = 'document.querySelector("[role=dialog]")'
const button = (label, root = 'document') => `[...${root}.querySelectorAll('button')].find(button => (button.getAttribute('aria-label') || button.textContent.trim()) === ${JSON.stringify(label)})`
const option = (name) => `[...document.querySelectorAll('.amdm-field-select-popup [role=option]')].find(option => option.textContent.trim() === ${JSON.stringify(name)})`
Expand Down Expand Up @@ -79,6 +81,7 @@ test('Chart examples teach a configuration and map it to compatible result field

test('Query charts render BSON results and preserve configuration and page scope', { timeout: 120_000 }, () =>
runShellScenario('query-charts', async ({ renderer, main, mongo, enterQuery, key, modifier, report }) => {
await updateRendererSettings(renderer, { enabledResultViews: ['tree', 'json', 'table', 'chart'] })
await mongo.db('amdm_e2e').collection('chartSales').insertMany([
...Array.from({ length: 12 }, () => ({ status: 'paid' })),
...Array.from({ length: 3 }, () => ({ status: 'pending' })),
Expand Down
4 changes: 4 additions & 0 deletions test/e2e/grid.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import assert from 'node:assert/strict'
import test from 'node:test'
import { Long } from 'mongodb'
import { clickElement, waitForExpression } from '../helpers/packagedElectron.mjs'
import { updateRendererSettings } from '../helpers/quickSearch.mjs'
import { runShellScenario } from '../helpers/shellUi.mjs'

test('Grid edits a projected document while preserving stored fields and BSON types', { timeout: 120_000 }, () =>
runShellScenario('grid-edit-projection', async ({ renderer, enterQuery, key, modifier, mongo, report }) => {
await updateRendererSettings(renderer, { enabledResultViews: ['tree', 'json', 'table', 'grid'] })
const collection = mongo.db('amdm_e2e').collection('items')
const hidden = Long.fromNumber(42)
await collection.insertOne({ _id: 'projected', name: 'before', hidden })
Expand Down Expand Up @@ -37,6 +39,7 @@ test('Grid edits a projected document while preserving stored fields and BSON ty

test('Grid keeps rendering when a focused card is beyond the end of the next page', { timeout: 120_000 }, () =>
runShellScenario('grid-short-page', async ({ renderer, enterQuery, key, modifier, report }) => {
await updateRendererSettings(renderer, { enabledResultViews: ['tree', 'json', 'table', 'grid'] })
await enterQuery('db.pages.find({ n: { $lt: 51 } }).sort({ n: 1 })')
await key('Enter', 'Enter', 13, modifier)
await waitForExpression(renderer, "document.querySelector('.result-range')?.textContent === '1–50'")
Expand All @@ -54,6 +57,7 @@ test('Grid keeps rendering when a focused card is beyond the end of the next pag

test('Derived results with a stored document ID are read-only in every document view', { timeout: 120_000 }, () =>
runShellScenario('result-derived-id', async ({ renderer, enterQuery, key, modifier, mongo, report }) => {
await updateRendererSettings(renderer, { enabledResultViews: ['tree', 'json', 'table', 'grid'] })
const collection = mongo.db('amdm_e2e').collection('items')
await collection.insertMany([{ _id: 'input', bucket: 'stored' }, { _id: 'stored', name: 'separate record' }])
const queries = [
Expand Down
18 changes: 18 additions & 0 deletions test/e2e/shell.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -409,5 +409,23 @@ test('Settings opens in a separate Renderer with an isolated bridge', { timeout:
assert.equal(await settings.evaluate('typeof window.api'), 'object')
assert.equal(await settings.evaluate('typeof window.require'), 'undefined')
report.steps.push('Settings button opened a rendered, isolated Settings window')

const viewLabels = "[...document.querySelectorAll('.view-switch button')].map(button => button.getAttribute('aria-label'))"
assert.deepEqual(await renderer.evaluate(viewLabels), ['Tree', 'JSON', 'Table'])
await clickElement(settings, "[...document.querySelectorAll('nav button')].find(button => button.textContent === 'Data Display')", 1, false)
const checkbox = (label) => `[...document.querySelectorAll('fieldset [role=checkbox]')].find(box => box.textContent === '${label}')`
for (const mode of ['Chart', 'Grid']) {
assert.equal(await settings.evaluate(`${checkbox(mode)}.getAttribute('aria-checked')`), 'false')
await clickElement(settings, checkbox(mode), 1, false)
await waitForExpression(renderer, `${viewLabels}.includes('${mode}')`)
}
for (const mode of ['Tree', 'JSON', 'Table', 'Grid']) {
await clickElement(settings, checkbox(mode), 1, false)
await waitForExpression(renderer, `!${viewLabels}.includes('${mode}')`)
}
assert.equal(await settings.evaluate(`${checkbox('Chart')}.hasAttribute('data-disabled')`), true)
await waitForExpression(renderer, "!!document.querySelector('[data-chart-view]')")
assert.deepEqual(await settings.evaluate('window.api.settings.get().then(settings => settings.enabledResultViews)'), ['chart'])
report.steps.push('result views update in the workspace and the final selected mode stays checked')
}),
)
Loading