Skip to content

Commit ca46ae8

Browse files
authored
Merge branch 'main' into fix/dock-safe-area-on-anchor
2 parents 2447a2f + c47fdea commit ca46ae8

9 files changed

Lines changed: 564 additions & 15 deletions

File tree

‎packages/devframe/src/utils/serve-static.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,10 @@ async function startH3(dir: string, options?: ServeStaticOptions): Promise<Fixtu
2828
return {
2929
dir,
3030
baseUrl: `http://127.0.0.1:${port}`,
31-
close: () => new Promise<void>(r => server.close(() => r())),
31+
close: () => new Promise<void>((r) => {
32+
server.closeAllConnections()
33+
server.close(() => r())
34+
}),
3235
}
3336
}
3437

@@ -49,7 +52,10 @@ async function startMw(
4952
return {
5053
dir,
5154
baseUrl: `http://127.0.0.1:${port}`,
52-
close: () => new Promise<void>(r => server.close(() => r())),
55+
close: () => new Promise<void>((r) => {
56+
server.closeAllConnections()
57+
server.close(() => r())
58+
}),
5359
}
5460
}
5561

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import type { DocksContext } from '@devframes/hub/client'
2+
import { CLIENT_CONTEXT_KEY } from '@devframes/hub/client'
3+
import { afterEach, expect, it, vi } from 'vitest'
4+
import { isInsideHub } from '../embedded/is-inside-hub'
5+
import { closeDockPopup, requestDockPopupOpen, useIsDockPopupOpen } from './popup'
6+
7+
vi.mock('./branding', () => ({
8+
applyDocumentHead: vi.fn(),
9+
applyPrimaryColor: vi.fn(),
10+
useBranding: () => ({ value: {} }),
11+
}))
12+
vi.mock('./color-mode', async () => {
13+
const { ref } = await import('vue')
14+
return {
15+
isDark: ref(false),
16+
}
17+
})
18+
19+
const { onMount } = vi.hoisted(() => ({
20+
onMount: vi.fn(),
21+
}))
22+
vi.mock('../components/DockStandalone', () => ({
23+
DockStandalone: class {
24+
constructor() { onMount() }
25+
remove() {}
26+
},
27+
}))
28+
29+
afterEach(() => {
30+
closeDockPopup()
31+
vi.unstubAllGlobals()
32+
vi.clearAllMocks()
33+
})
34+
35+
it('identifies the popup as a Hub before mounting its iframe views', async () => {
36+
const element = () => ({
37+
appendChild: vi.fn(),
38+
style: {
39+
setProperty: vi.fn(),
40+
},
41+
})
42+
const popup = {
43+
document: {
44+
createElement: element,
45+
documentElement: element(),
46+
head: element(),
47+
body: {
48+
...element(),
49+
textContent: '',
50+
},
51+
},
52+
addEventListener: vi.fn(),
53+
removeEventListener: vi.fn(),
54+
close: vi.fn(),
55+
}
56+
// The fixture supplies only the context fields used by popup initialization.
57+
// eslint-disable-next-line slop/no-chained-type-assertions
58+
const context = {
59+
panel: {
60+
store: { width: 80, height: 80 },
61+
},
62+
rpc: { connectionMeta: {} },
63+
docks: {
64+
switchEntry: vi.fn(),
65+
},
66+
} as unknown as DocksContext
67+
vi.stubGlobal('window', {
68+
innerWidth: 1000,
69+
innerHeight: 800,
70+
documentPictureInPicture: {
71+
requestWindow: async () => popup,
72+
},
73+
})
74+
let insideHubAtMount: boolean | undefined
75+
onMount.mockImplementation(() => {
76+
insideHubAtMount = isInsideHub({ parent: popup })
77+
})
78+
79+
requestDockPopupOpen(context)
80+
await vi.waitFor(() => expect(useIsDockPopupOpen().value).toBe(true))
81+
expect(insideHubAtMount).toBe(true)
82+
expect(Reflect.get(popup, CLIENT_CONTEXT_KEY)).toBe(context)
83+
})

‎packages/hub-ui/src/client/state/popup.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { DocksContext } from '@devframes/hub/client'
2+
import { CLIENT_CONTEXT_KEY } from '@devframes/hub/client'
23
import { createEventEmitter } from 'devframe/utils/events'
34
import { shallowRef, watch } from 'vue'
45
import { applyDocumentHead, applyPrimaryColor, useBranding } from './branding'
@@ -125,6 +126,9 @@ async function mountStandaloneApp(context: DocksContext, popup: Window) {
125126
;(popup as Window & { [DEVFRAME_CONNECTION_META_KEY]?: unknown })[DEVFRAME_CONNECTION_META_KEY]
126127
= (globalThis as Record<string, unknown>)[DEVFRAME_CONNECTION_META_KEY] ?? context.rpc.connectionMeta
127128

129+
// Let iframe bootstraps recognize the Hub before its views mount.
130+
;(popup as Window & { [CLIENT_CONTEXT_KEY]?: DocksContext })[CLIENT_CONTEXT_KEY] = context
131+
128132
const appRoot = popup.document.createElement('div')
129133
appRoot.id = 'devframes-popup-root'
130134
popup.document.body.appendChild(appRoot)

‎plugins/data-inspector/app/App.vue‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,8 @@ function saveCurrent(input: { title?: string, description?: string, scope: Saved
8989
<Pane class="min-w-0">
9090
<ResultViewer
9191
:result="wb.result.value"
92+
:observation="wb.observation.value"
93+
:observation-notices="wb.observationNotices.value"
9294
:has-result="wb.hasResult.value"
9395
:stats="wb.stats.value"
9496
:stats-stale="wb.statsStale.value"

‎plugins/data-inspector/app/components/ResultViewer.vue‎

Lines changed: 57 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,23 @@
11
<script setup lang="ts">
22
import type { NodePath, QueryStats } from '@devframes/plugin-data-inspector/engine'
3+
import type { QueryObservation } from '../composables/query-observation'
34
import ActionIconButton from '@antfu/design/components/Action/ActionIconButton.vue'
45
import DisplayBadge from '@antfu/design/components/Display/DisplayBadge.vue'
56
import DisplayBytes from '@antfu/design/components/Display/DisplayBytes.vue'
67
import DisplayDate from '@antfu/design/components/Display/DisplayDate.vue'
78
import DisplayDuration from '@antfu/design/components/Display/DisplayDuration.vue'
8-
import { computed, shallowRef, watch } from 'vue'
9+
import FormTextarea from '@antfu/design/components/Form/FormTextarea.vue'
10+
import OverlayModal from '@antfu/design/components/Overlay/OverlayModal.vue'
11+
import { computed, onUnmounted, shallowRef, watch } from 'vue'
912
import { useDiscoveryViewer } from '../composables/discovery'
1013
import { prepareForDisplay } from '../composables/display-transform'
14+
import { observationMarkdown } from '../composables/query-observation'
1115
import { colorScheme } from '../composables/scheme'
1216
import EditPanel from './EditPanel.vue'
1317
1418
const props = defineProps<{
19+
observation: QueryObservation | null
20+
observationNotices: string[]
1521
result: unknown
1622
hasResult: boolean
1723
stats: (QueryStats & { rpcMs: number }) | null
@@ -72,16 +78,38 @@ const lockTooltip = computed(() => {
7278
return ''
7379
})
7480
75-
const copied = shallowRef(false)
81+
const copied = shallowRef<'json' | 'markdown' | null>(null)
82+
const copying = shallowRef(false)
83+
const manualCopyOpen = shallowRef(false)
84+
const manualCopyText = shallowRef('')
85+
const copyError = shallowRef('')
7686
let copiedTimer: ReturnType<typeof setTimeout> | undefined
77-
function copyResult(): void {
87+
onUnmounted(() => clearTimeout(copiedTimer))
88+
89+
async function copyResult(format: 'json' | 'markdown'): Promise<void> {
90+
if (!props.hasResult || !props.observation || copying.value)
91+
return
92+
// Serialize at the click, before a refresh can replace the observation.
93+
const text = format === 'markdown'
94+
? observationMarkdown(props.observation, props.observationNotices)
95+
: JSON.stringify(props.observation.result, null, 2) ?? 'null'
96+
copying.value = true
97+
copied.value = null
98+
copyError.value = ''
99+
clearTimeout(copiedTimer)
78100
try {
79-
void navigator.clipboard.writeText(JSON.stringify(props.result, null, 2))
80-
copied.value = true
81-
clearTimeout(copiedTimer)
82-
copiedTimer = setTimeout(() => (copied.value = false), 1200)
101+
await navigator.clipboard.writeText(text)
102+
copied.value = format
103+
copiedTimer = setTimeout(() => (copied.value = null), 1200)
104+
}
105+
catch {
106+
copyError.value = 'Clipboard write failed. Select and copy the complete text below.'
107+
manualCopyText.value = text
108+
manualCopyOpen.value = true
109+
}
110+
finally {
111+
copying.value = false
83112
}
84-
catch {}
85113
}
86114
</script>
87115

@@ -138,13 +166,22 @@ function copyResult(): void {
138166
@click="viewer.setExpanded(1)"
139167
/>
140168
<ActionIconButton
141-
v-if="hasResult"
142169
class="text-sm"
143-
:icon="copied ? 'i-ph:check' : 'i-ph:copy-duotone'"
170+
:disabled="!hasResult || copying"
171+
:icon="copied === 'json' ? 'i-ph:check' : 'i-ph:copy-duotone'"
144172
label="Copy result as JSON"
145173
tooltip="Copy the result as JSON"
146-
@click="copyResult"
174+
@click="copyResult('json')"
147175
/>
176+
<ActionIconButton
177+
class="text-sm"
178+
:disabled="!hasResult || copying"
179+
:icon="copied === 'markdown' ? 'i-ph:check' : 'i-ph:file-text-duotone'"
180+
label="Copy result with context"
181+
tooltip="Copy result with context"
182+
@click="copyResult('markdown')"
183+
/>
184+
<span class="sr-only" role="status">{{ copied ? 'Copied to clipboard' : '' }}</span>
148185
<ActionIconButton
149186
class="text-sm"
150187
:icon="running ? 'i-ph:arrows-clockwise animate-spin' : 'i-ph:arrows-clockwise'"
@@ -155,6 +192,14 @@ function copyResult(): void {
155192
/>
156193
</div>
157194

195+
<div v-if="hasResult && observationNotices.length" class="px-3 py-2 text-xs color-muted border-b border-base" role="status">
196+
<p v-for="notice in observationNotices" :key="notice">
197+
{{ notice }}
198+
</p>
199+
</div>
200+
<OverlayModal v-model:open="manualCopyOpen" title="Copy manually" :description="copyError">
201+
<FormTextarea v-model="manualCopyText" readonly :rows="14" class="font-mono text-xs" aria-label="Complete copy text" @focus="($event.target as HTMLTextAreaElement).select()" />
202+
</OverlayModal>
158203
<div
159204
v-if="error"
160205
class="mx-3 mt-2 px-3 py-2 font-mono text-xs whitespace-pre-wrap rounded-lg border border-red-600/40 bg-red-500:8 color-red-700 dark:(border-red-400/40 color-red-300)"
@@ -173,7 +218,7 @@ function copyResult(): void {
173218
<div v-if="!hasResult" class="flex-1 grid place-items-center select-none">
174219
<div class="flex flex-col items-center gap-2 color-faint">
175220
<span class="i-ph:tree-structure-duotone text-3xl" />
176-
<span class="text-sm">Results render here, start typing a query</span>
221+
<span class="text-sm">Run a successful query to view and copy its result</span>
177222
</div>
178223
</div>
179224
</div>
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import type { FilterOptions, QueryStats } from '@devframes/plugin-data-inspector/engine'
2+
3+
/** One successful response and the conditions that produced it. */
4+
export interface QueryObservation {
5+
source: { id: string, title: string }
6+
query: string
7+
filters: Required<FilterOptions>
8+
receivedAt: number
9+
result: unknown
10+
normalize: QueryStats['normalize']
11+
}
12+
13+
function fenced(text: string, language = ''): string {
14+
const runs = text.match(/`+/g) ?? []
15+
const fence = '`'.repeat(runs.reduce((length, run) => Math.max(length, run.length + 1), 3))
16+
return `${fence}${language}\n${text}\n${fence}`
17+
}
18+
19+
export function observationMarkdown(observation: QueryObservation, notices: string[]): string {
20+
const { source, query, filters, receivedAt, result, normalize } = observation
21+
return [
22+
'# Data Inspector query result',
23+
'## Source and time',
24+
fenced(`Name: ${source.title}\nID: ${source.id}`),
25+
`Browser received this result at ${new Date(receivedAt).toISOString()} (UTC). This is not the time when the data was sampled on the node side.`,
26+
...notices,
27+
'## Executed query',
28+
fenced(query, 'jora'),
29+
'Filters:',
30+
...Object.entries(filters).map(([key, value]) => `- ${key}: ${value}`),
31+
'## Result',
32+
fenced(JSON.stringify(result, null, 2) ?? 'null', 'json'),
33+
'## Data scope and limits',
34+
'This is one successful response after Data Inspector conversion and filtering, not a lossless copy of the original object.',
35+
`Reported truncation: depth=${normalize.truncatedDepth}, entries=${normalize.truncatedEntries}, properties=${normalize.truncatedProps}.`,
36+
'No reported truncation does not prove completeness. Later node expansions are not included. The source name and ID do not identify a machine or deployment.',
37+
].join('\n\n')
38+
}

‎plugins/data-inspector/app/composables/workbench.ts‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import type { DataSourceMeta, FilterOptions, NodePath, QueryOutcome, QueryStats,
88
* An empty query runs `$` (the root), so every source lands on a full view.
99
*/
1010
import type { InjectionKey } from 'vue'
11+
import type { QueryObservation } from './query-observation'
1112
import jora from 'jora'
1213
import { computed, inject, reactive, ref, shallowRef, watch } from 'vue'
1314
import { backend, connection } from './rpc'
@@ -178,6 +179,22 @@ export function useWorkbench() {
178179
const statsStale = ref(false)
179180
const result = shallowRef<unknown>()
180181
const hasResult = ref(false)
182+
const observation = shallowRef<QueryObservation | null>(null)
183+
const observationNotices = computed(() => {
184+
const saved = observation.value
185+
if (!saved)
186+
return []
187+
const notices: string[] = []
188+
if (saved.query !== (query.value.trim() || '$') || FILTER_KEYS.some(key => saved.filters[key] !== settings[key]))
189+
notices.push('Query conditions changed. This result uses the earlier conditions shown in the copy.')
190+
if (running.value)
191+
notices.push('A new query is pending. This is the previous successful result.')
192+
if (serverError.value)
193+
notices.push('The latest query failed. This is an earlier successful result.')
194+
if (syntax.value.kind !== 'ok')
195+
notices.push('The current query has incomplete or invalid syntax and was not executed.')
196+
return notices
197+
})
181198
/** When the last successful query landed, driving the "ran … ago" label. */
182199
const lastRunAt = ref<number | null>(null)
183200

@@ -270,12 +287,17 @@ export function useWorkbench() {
270287
syntax.value = { kind: 'ok' }
271288
}
272289

290+
const request = {
291+
source: { id: sourceId.value, title: activeSource.value?.title ?? sourceId.value },
292+
query: text,
293+
filters: { ...settings },
294+
}
273295
const seq = ++runSeq
274296
running.value = true
275297
const started = performance.now()
276298
let outcome: QueryOutcome
277299
try {
278-
outcome = await backend().query(sourceId.value, text, { ...settings })
300+
outcome = await backend().query(request.source.id, request.query, request.filters)
279301
}
280302
catch (error) {
281303
if (seq === runSeq) {
@@ -305,6 +327,12 @@ export function useWorkbench() {
305327
result.value = outcome.result
306328
hasResult.value = true
307329
lastRunAt.value = Date.now()
330+
observation.value = {
331+
...request,
332+
receivedAt: lastRunAt.value,
333+
result: outcome.result,
334+
normalize: { ...outcome.stats.normalize },
335+
}
308336
}
309337

310338
function scheduleRun(): void {
@@ -499,6 +527,17 @@ export function useWorkbench() {
499527
}
500528
scheduleRun()
501529
})
530+
watch(sourceId, () => {
531+
++runSeq
532+
running.value = false
533+
result.value = undefined
534+
hasResult.value = false
535+
observation.value = null
536+
lastRunAt.value = null
537+
stats.value = null
538+
statsStale.value = false
539+
serverError.value = null
540+
}, { flush: 'sync' })
502541
watch(sourceId, () => {
503542
suggestions.value = []
504543
restoreDraft()
@@ -569,6 +608,8 @@ export function useWorkbench() {
569608
statsStale,
570609
result,
571610
hasResult,
611+
observation,
612+
observationNotices,
572613
lastRunAt,
573614
suggestions,
574615
skeleton,

0 commit comments

Comments
 (0)