import { describe, it, expect, afterEach } from 'vitest'
import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
import { useActiveMarkdownView } from '../App'
import { Workspace } from '../plugin/workspace'
import { MarkdownView } from '../plugin/views/markdown-view'
import { createTFile } from '../plugin/files'
function ActiveEditorProbe({
workspace,
firstView,
secondView,
}: {
workspace: Workspace
firstView: MarkdownView
secondView: MarkdownView
}) {
const view = useActiveMarkdownView(workspace)
const label = view === firstView ? 'first' : view === secondView ? 'second' : 'none'
return
{label}
}
describe('useActiveMarkdownView', () => {
afterEach(() => {
cleanup()
})
it('reacts when the active editor is replaced on the same leaf', async () => {
const workspace = new Workspace(document.createElement('div'))
const leaf = workspace.getLeaf()
const file = createTFile('same.md', null, { ctime: 0, mtime: 0, size: 0 })
const firstView = new MarkdownView(leaf)
const secondView = new MarkdownView(leaf)
leaf.file = file
firstView.file = file
secondView.file = file
await act(async () => {
await leaf.open(firstView)
})
workspace.setActiveLeaf(leaf)
render()
expect(screen.getByTestId('active-editor')).toHaveTextContent('first')
await act(async () => {
await leaf.open(secondView)
})
await waitFor(() => {
expect(screen.getByTestId('active-editor')).toHaveTextContent('second')
})
})
it('reacts when a failed open clears activeEditor without a layout change', async () => {
class FailingMarkdownView extends MarkdownView {
override async onOpen(): Promise {
throw new Error('view open failed')
}
}
const workspace = new Workspace(document.createElement('div'))
const leaf = workspace.getLeaf()
const file = createTFile('same.md', null, { ctime: 0, mtime: 0, size: 0 })
const firstView = new MarkdownView(leaf)
const failingView = new FailingMarkdownView(leaf)
leaf.file = file
firstView.file = file
failingView.file = file
await act(async () => {
await leaf.open(firstView)
})
workspace.setActiveLeaf(leaf)
workspace.registerViewType('failing-markdown', (targetLeaf) => {
const view = new FailingMarkdownView(targetLeaf)
view.file = file
return view
})
render()
expect(screen.getByTestId('active-editor')).toHaveTextContent('first')
let openError: unknown = null
await act(async () => {
try {
await leaf.setViewState({ type: 'failing-markdown' })
} catch (err) {
openError = err
}
})
expect(openError).toBeInstanceOf(Error)
expect((openError as Error).message).toBe('view open failed')
await waitFor(() => {
expect(screen.getByTestId('active-editor')).toHaveTextContent('none')
})
})
})