Files
supabase/apps/studio/components/interfaces/Settings/Logs/Logs.utils.test.ts
Ali Waseem 83992c55f7 feat(log-explorer): arrow key and deeper shortcuts for log explorer (#45989)
Closes
[FE-3378](https://linear.app/supabase/issue/FE-3378/featlogs-keyboard-shortcuts-for-function-logs-invocations-and-logs).

## Summary
Adds a shared shortcut registry for every `LogsPreviewer` surface —
Function Logs, Function Invocations, and the Logs Explorer — and brings
the grid keyboard model in line with the Auth Users / Table Editor
patterns.

## Shortcuts

| Key | Action |
| --- | --- |
| `↑` / `↓` | Move single-row selection; opens side panel |
| `Shift+Space` | Toggle current row in multi-select |
| `Mod+A` | Toggle all visible rows in multi-select |
| `Esc` | Staged: clear multi-select → close side panel |
| `Shift+R` | Refresh logs |
| `Shift+H` | Toggle histogram |
| `Shift+L` | Load older logs |
| `Shift+P` | Open time range picker |
| `Mod+Shift+J / M / C` | Copy selected rows as JSON / Markdown / CSV
(existing global handler) |

## Other changes
- `ShortcutTooltip` on search, refresh, histogram, load older, and
time-picker controls.
- `onSearchInputEscape` wired on the logs search bar (clear → blur).
- Visual row highlight (`rdg-row--focused`) when a row is
keyboard-focused or multi-selected.
- Multi-select copy dropdown gains a **Copy as CSV** entry and shows the
keybind on each item via `ShortcutBadge`.
- Manual arrow-nav (`navigate()`) updates `selectedRow` directly without
going through `onRowClick`, so multi-select checkmarks survive keyboard
navigation.

## Test plan
- [x] Function Logs and Function Invocations: all shortcuts above fire
while the page is mounted, no firing in other tabs.
- [x] Logs Explorer: same shortcuts work; copy keybinds still copy *all*
rows when nothing is multi-selected.
- [x] Arrow keys on first load select the first row even when the focus
sink is the active element.
- [x] Selecting rows via checkbox or `Shift+Space`, then pressing arrow
keys, preserves the checkmarks.
- [x] Escape on a populated search input clears it; Escape on an empty
input blurs it.
- [x] Esc with multi-select active clears the selection before closing
the side panel.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* CSV export for log selections (adds CSV alongside JSON and Markdown).
* New logs-preview keyboard shortcuts: search focus, refresh, chart
toggle, date picker, load older, navigation, and selection.

* **Improvements**
  * Shortcut badges and tooltip integration across the logs UI.
* Search input focus/ref support and controlled date-picker visibility.
  * Better no-results/error rendering and expanded copy dropdown sizing.

* **Tests**
  * Added CSV formatting tests covering RFC 4180 edge cases.

<!-- review_stack_entry_start -->

[![Review Change
Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/supabase/supabase/pull/45989)

<!-- review_stack_entry_end -->
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-05-19 15:25:47 +00:00

186 lines
6.2 KiB
TypeScript

import { describe, expect, test } from 'vitest'
import type { LogData } from './Logs.types'
import {
buildLogsPrompt,
extractEdgeFunctionName,
formatLogsAsCsv,
formatLogsAsJson,
formatLogsAsMarkdown,
} from './Logs.utils'
const createLog = (overrides: Partial<LogData> = {}): LogData => ({
id: 'test-id',
timestamp: 1621323232312,
event_message: 'test message',
...overrides,
})
describe('Logs.utils', () => {
describe('formatLogsAsJson', () => {
test('formats single log as JSON', () => {
const rows: LogData[] = [createLog({ id: '1', event_message: 'test message' })]
const result = formatLogsAsJson(rows)
expect(result).toContain('"id": "1"')
expect(result).toContain('"event_message": "test message"')
})
test('formats multiple logs as JSON array', () => {
const rows: LogData[] = [
createLog({ id: '1', event_message: 'first' }),
createLog({ id: '2', event_message: 'second' }),
]
const result = formatLogsAsJson(rows)
expect(result).toContain('"id": "1"')
expect(result).toContain('"id": "2"')
})
})
describe('formatLogsAsCsv', () => {
test('returns empty string for empty list', () => {
expect(formatLogsAsCsv([])).toBe('')
})
test('formats single row with header line', () => {
const rows: LogData[] = [createLog({ id: '1', event_message: 'hello' })]
const result = formatLogsAsCsv(rows)
const [header, row] = result.split('\r\n')
expect(header.split(',').sort()).toEqual(['event_message', 'id', 'timestamp'].sort())
expect(row).toContain('1')
expect(row).toContain('hello')
})
test('formats multiple rows', () => {
const rows: LogData[] = [
createLog({ id: '1', event_message: 'first' }),
createLog({ id: '2', event_message: 'second' }),
]
const lines = formatLogsAsCsv(rows).split('\r\n')
expect(lines).toHaveLength(3)
expect(lines[1]).toContain('first')
expect(lines[2]).toContain('second')
})
test('escapes commas, quotes, and newlines per RFC 4180', () => {
const rows: LogData[] = [
createLog({
id: 'a,b',
event_message: 'line1\nline2',
}),
createLog({
id: 'c"d',
event_message: 'has "quotes"',
}),
]
const result = formatLogsAsCsv(rows)
expect(result).toContain('"a,b"')
expect(result).toContain('"line1\nline2"')
expect(result).toContain('"c""d"')
expect(result).toContain('"has ""quotes"""')
})
test('emits columns based on the first row', () => {
const rows: LogData[] = [
{ id: '1', event_message: 'first', timestamp: 1 },
// Extra `status` key on later rows is dropped because headers
// come from the first row.
{ id: '2', event_message: 'second', timestamp: 2, status: '500' } as LogData,
]
const result = formatLogsAsCsv(rows)
expect(result).not.toContain('500')
expect(result.split('\r\n')[0]).toBe('id,event_message,timestamp')
})
test('renders null as the string "null" and undefined as empty', () => {
const rows: LogData[] = [
{ id: '1', event_message: null as unknown as string, timestamp: undefined as any },
]
const result = formatLogsAsCsv(rows)
const dataRow = result.split('\r\n')[1]
// Order matches first-row keys: id, event_message, timestamp
expect(dataRow).toBe('1,null,')
})
})
describe('formatLogsAsMarkdown', () => {
test('formats single log with timestamp', () => {
const rows: LogData[] = [
createLog({
id: '123',
timestamp: 1621323232312,
event_message: 'Test error',
status: '500',
}),
]
const result = formatLogsAsMarkdown(rows)
expect(result).toContain('## Log 1')
expect(result).toContain('**Timestamp:**')
expect(result).toContain('**Message:** Test error')
expect(result).toContain('**Details:**')
})
test('formats multiple logs with separators', () => {
const rows: LogData[] = [
createLog({ id: '1', event_message: 'first error' }),
createLog({ id: '2', event_message: 'second error' }),
]
const result = formatLogsAsMarkdown(rows)
expect(result).toContain('## Log 1')
expect(result).toContain('## Log 2')
expect(result).toContain('---')
})
})
describe('buildLogsPrompt', () => {
test('builds prompt with single log', () => {
const rows: LogData[] = [createLog({ id: '1', event_message: 'error occurred' })]
const result = buildLogsPrompt(rows)
expect(result).toContain('1 Supabase log entry')
expect(result).toContain('error occurred')
expect(result).toContain('What do these logs indicate')
})
test('builds prompt with multiple logs', () => {
const rows: LogData[] = [
createLog({ id: '1', event_message: 'error 1' }),
createLog({ id: '2', event_message: 'error 2' }),
]
const result = buildLogsPrompt(rows)
expect(result).toContain('2 Supabase log entries')
})
test('handles singular correctly', () => {
const rows: LogData[] = [createLog({ id: '1', event_message: 'single error' })]
const result = buildLogsPrompt(rows)
expect(result).toContain('1 Supabase log entry')
})
})
describe('extractEdgeFunctionName', () => {
test('extracts function name from full pathname', () => {
expect(extractEdgeFunctionName('/functions/v1/hello-world-1')).toBe('hello-world-1')
})
test('returns empty string for null', () => {
expect(extractEdgeFunctionName(null)).toBe('')
})
test('returns empty string for undefined', () => {
expect(extractEdgeFunctionName(undefined)).toBe('')
})
test('returns empty string for non-string values', () => {
expect(extractEdgeFunctionName(42)).toBe('')
expect(extractEdgeFunctionName({})).toBe('')
})
test('handles pathname with no slashes', () => {
expect(extractEdgeFunctionName('my-function')).toBe('my-function')
})
test('handles trailing slash', () => {
expect(extractEdgeFunctionName('/functions/v1/hello-world-1/')).toBe('hello-world-1')
})
})
})