Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript
19.8 KB
Raw Blame
import { describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
  DataTable,
  GroupedTableBody,
  RowActionMenu,
  TableHeaderCell,
  TableRow,
  TableStateRow,
  TableViewport,
  TruncatedText,
  stableSortRows,
} from '@clerum/frontend-components'

function cssRule(css: string, selector: string) {
  const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  const match = css.match(new RegExp(`${escaped}\\s*\\{([^}]*)\\}`, 'm'))
  expect(match, `Expected CSS rule for ${selector}`).not.toBeNull()
  return match?.[1] ?? ''
}

describe('shared frontend components', () => {
  it('controls independent accessible grouped table disclosures with semantic rows', () => {
    const onAlphaExpandedChange = vi.fn()
    const { rerender } = render(
      <DataTable>
        <GroupedTableBody
          colSpan={2}
          disclosureLabel={expanded => `${expanded ? 'Collapse' : 'Expand'} Alpha records`}
          expanded={false}
          groupId="alpha"
          onExpandedChange={onAlphaExpandedChange}
          summary="Alpha"
        >
          <tr>
            <td>Alpha child action</td>
            <td>
              <button type="button">Edit Alpha</button>
            </td>
          </tr>
        </GroupedTableBody>
        <GroupedTableBody
          colSpan={2}
          disclosureLabel={expanded => `${expanded ? 'Collapse' : 'Expand'} Beta records`}
          expanded={false}
          groupId="beta"
          onExpandedChange={vi.fn()}
          summary="Beta"
        >
          <tr>
            <td>Beta child</td>
            <td />
          </tr>
        </GroupedTableBody>
      </DataTable>
    )

    const alphaDisclosure = screen.getByRole('button', { name: 'Expand Alpha records' })
    expect(alphaDisclosure).toHaveAttribute('aria-expanded', 'false')
    expect(alphaDisclosure.getAttribute('aria-controls')).toMatch(/alpha-rows$/)
    expect(document.querySelectorAll('table > tbody > tr')).toHaveLength(2)
    expect(screen.queryByText('Alpha child action')).toBeNull()
    expect(screen.queryByText('Beta child')).toBeNull()

    fireEvent.click(alphaDisclosure)
    expect(onAlphaExpandedChange).toHaveBeenCalledWith(true)

    rerender(
      <DataTable>
        <GroupedTableBody
          colSpan={2}
          disclosureLabel={expanded => `${expanded ? 'Collapse' : 'Expand'} Alpha records`}
          expanded
          groupId="alpha"
          onExpandedChange={onAlphaExpandedChange}
          summary="Alpha"
        >
          <tr>
            <td>Alpha child action</td>
            <td>
              <button type="button">Edit Alpha</button>
            </td>
          </tr>
        </GroupedTableBody>
        <GroupedTableBody
          colSpan={2}
          disclosureLabel={expanded => `${expanded ? 'Collapse' : 'Expand'} Beta records`}
          expanded={false}
          groupId="beta"
          onExpandedChange={vi.fn()}
          summary="Beta"
        >
          <tr>
            <td>Beta child</td>
            <td />
          </tr>
        </GroupedTableBody>
      </DataTable>
    )

    expect(screen.getByRole('button', { name: 'Collapse Alpha records' })).toHaveAttribute(
      'aria-expanded',
      'true'
    )
    const alphaChildBody = screen.getByText('Alpha child action').closest('tr')?.parentElement
    const collapseAlpha = screen.getByRole('button', { name: 'Collapse Alpha records' })
    expect(alphaChildBody).toHaveAttribute('id', collapseAlpha.getAttribute('aria-controls'))
    expect(alphaChildBody).toHaveAttribute('aria-labelledby', collapseAlpha.id)
    expect(screen.queryByText('Beta child')).toBeNull()

    fireEvent.click(screen.getByRole('button', { name: 'Edit Alpha' }))
    expect(onAlphaExpandedChange).toHaveBeenCalledTimes(1)

    fireEvent.click(collapseAlpha)
    expect(onAlphaExpandedChange).toHaveBeenLastCalledWith(false)
  })

  it.each([
    { label: 'five columns', colSpan: 5, spans: [2, 1, 2] },
    { label: 'seven columns', colSpan: 7, spans: [1, 2, 1, 3] },
  ])(
    'aligns grouped summaries with arbitrary $label through native cells',
    ({ colSpan, spans }) => {
      const onExpandedChange = vi.fn()
      render(
        <DataTable>
          <thead>
            <tr>
              {spans.map((span, index) => (
                <TableHeaderCell
                  colSpan={span}
                  key={`header-${index}`}
                  label={`Header ${index + 1}`}
                />
              ))}
            </tr>
          </thead>
          <GroupedTableBody
            colSpan={colSpan}
            disclosureLabel={() => 'Expand provider records'}
            expanded={false}
            groupId={`provider-${colSpan}`}
            onExpandedChange={onExpandedChange}
            summaryCells={spans.map((span, index) => ({
              key: `cell-${index}`,
              colSpan: span,
              content:
                index === spans.length - 1 ? (
                  <button type="button">Inspect provider</button>
                ) : (
                  `Summary ${index + 1}`
                ),
            }))}
          >
            <tr>
              <td colSpan={colSpan}>Provider child</td>
            </tr>
          </GroupedTableBody>
        </DataTable>
      )

      const disclosure = screen.getByRole('button', { name: 'Expand provider records' })
      const summaryRow = disclosure.closest('tr')
      expect(summaryRow).not.toBeNull()
      expect(Array.from(summaryRow?.cells ?? []).map(cell => cell.colSpan)).toEqual(spans)

      fireEvent.click(screen.getByText('Summary 2'))
      expect(onExpandedChange).not.toHaveBeenCalled()

      fireEvent.click(disclosure)
      expect(onExpandedChange).toHaveBeenCalledOnce()
      expect(onExpandedChange).toHaveBeenLastCalledWith(true)

      fireEvent.click(screen.getByRole('button', { name: 'Inspect provider' }))
      expect(onExpandedChange).toHaveBeenCalledOnce()
    }
  )

  it('keeps grouped summary and nested child column schemas independent', () => {
    render(
      <DataTable variant="grouped">
        <thead>
          <tr>
            {['Provider', 'Models', 'Details', 'Actions'].map(label => (
              <TableHeaderCell key={label} label={label} />
            ))}
          </tr>
        </thead>
        <GroupedTableBody
          childHeader={
            <tr>
              {['Select', 'Model', 'Vendor', 'Context', 'Enabled', 'Actions'].map(label => (
                <TableHeaderCell key={label} label={label} />
              ))}
            </tr>
          }
          childTableClassName="test-child-table"
          colSpan={4}
          disclosureLabel={() => 'Collapse provider records'}
          expanded
          groupId="provider"
          nestedChildTable
          onExpandedChange={() => undefined}
          summaryCells={['Provider', 'Models', 'Details', 'Actions'].map(label => ({
            key: label,
            content: `${label} summary`,
          }))}
        >
          <tr>
            <td>Select value</td>
            <td>Model value</td>
            <td>Vendor value</td>
            <td>Context value</td>
            <td>Enabled value</td>
            <td>Action value</td>
          </tr>
        </GroupedTableBody>
      </DataTable>
    )

    const outerTable = document.querySelector<HTMLTableElement>('.eft-table--grouped')
    const childTable = document.querySelector<HTMLTableElement>('.test-child-table')
    expect(outerTable).not.toBeNull()
    expect(outerTable?.querySelectorAll(':scope > thead > tr > th')).toHaveLength(4)
    expect(childTable).not.toBeNull()
    expect(childTable).not.toBe(outerTable)
    expect(childTable?.querySelectorAll(':scope > thead > tr > th')).toHaveLength(6)
    expect(childTable?.querySelectorAll(':scope > tbody > tr > td')).toHaveLength(6)
    expect(childTable?.closest('.eft-table-group__child-cell')).toHaveAttribute('colspan', '4')
  })

  it('rejects grouped summary-cell spans that cannot match the table columns', () => {
    const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
    const preventReportedError = (event: ErrorEvent) => event.preventDefault()
    window.addEventListener('error', preventReportedError)
    try {
      expect(() =>
        render(
          <DataTable>
            <GroupedTableBody
              colSpan={4}
              disclosureLabel={() => 'Expand invalid records'}
              expanded={false}
              groupId="invalid"
              onExpandedChange={() => undefined}
              summaryCells={[
                { key: 'provider', content: 'Provider' },
                { key: 'details', colSpan: 2, content: 'Details' },
              ]}
            >
              <tr>
                <td colSpan={4}>Invalid child</td>
              </tr>
            </GroupedTableBody>
          </DataTable>
        )
      ).toThrow('GroupedTableBody summary cell spans (3) must equal colSpan (4).')
    } finally {
      window.removeEventListener('error', preventReportedError)
      errorSpy.mockRestore()
    }
  })

  it('uses unique, labelled rowgroup relationships across table instances', () => {
    render(
      <>
        {[1, 2].map(instance => (
          <DataTable key={instance}>
            <GroupedTableBody
              colSpan={1}
              disclosureLabel={() => 'Collapse Shared records'}
              expanded
              groupId="shared"
              onExpandedChange={() => undefined}
              summary={`Shared ${instance}`}
            >
              <tr>
                <td>Child {instance}</td>
              </tr>
            </GroupedTableBody>
          </DataTable>
        ))}
      </>
    )

    const disclosures = screen.getAllByRole('button', { name: 'Collapse Shared records' })
    const rowgroups = screen.getAllByRole('rowgroup', { name: 'Collapse Shared records' })
    const controlledIds = disclosures.map(disclosure => disclosure.getAttribute('aria-controls'))

    expect(new Set(controlledIds).size).toBe(2)
    expect(rowgroups).toHaveLength(2)
    disclosures.forEach((disclosure, index) => {
      expect(rowgroups[index]).toHaveAttribute('id', controlledIds[index])
      expect(rowgroups[index]).toHaveAttribute('aria-labelledby', disclosure.id)
    })
  })

  it('owns the canonical viewport class and preserves semantic modifiers', () => {
    render(
      <TableViewport aria-label="Embedded results" className="cu-table-wrap" embedded>
        Results
      </TableViewport>
    )

    expect(screen.getByLabelText('Embedded results')).toHaveClass(
      'eft-table-viewport',
      'eft-table-viewport--embedded',
      'cu-table-wrap'
    )
  })

  it('exposes sortable header state and a keyboard sort control', () => {
    const onSort = vi.fn()
    render(
      <DataTable>
        <thead>
          <tr>
            <TableHeaderCell activeDirection="asc" label="Name" onSort={onSort} />
          </tr>
        </thead>
      </DataTable>
    )

    expect(screen.getByRole('columnheader')).toHaveAttribute('aria-sort', 'ascending')
    fireEvent.click(screen.getByRole('button', { name: 'Sort by Name descending' }))
    expect(onSort).toHaveBeenCalledOnce()
  })

  it('uses stable explicit values and a deterministic identity tie-breaker', () => {
    const rows = [
      { id: 'b', name: 'Same' },
      { id: 'a', name: 'Same' },
      { id: 'c', name: null },
    ]

    expect(
      stableSortRows(
        rows,
        row => row.name,
        'asc',
        row => row.id
      ).map(row => row.id)
    ).toEqual(['a', 'b', 'c'])
    expect(
      stableSortRows(
        rows,
        row => row.name,
        'desc',
        row => row.id
      ).map(row => row.id)
    ).toEqual(['a', 'b', 'c'])
  })

  it('supports pointer and keyboard row navigation without hijacking child actions', () => {
    const onNavigate = vi.fn()
    const onChild = vi.fn()
    render(
      <DataTable>
        <tbody>
          <TableRow onNavigate={onNavigate}>
            <td>Record</td>
            <td>
              <button onClick={onChild}>Child action</button>
              <a href="/elsewhere">Child link</a>
              <input aria-label="Child selection" type="checkbox" />
            </td>
          </TableRow>
        </tbody>
      </DataTable>
    )

    const row = screen.getByRole('row')
    fireEvent.click(row)
    fireEvent.keyDown(row, { key: 'Enter' })
    expect(onNavigate).toHaveBeenCalledTimes(2)
    fireEvent.click(screen.getByRole('button', { name: 'Child action' }))
    expect(onChild).toHaveBeenCalledOnce()
    expect(onNavigate).toHaveBeenCalledTimes(2)

    for (const child of [
      screen.getByRole('button', { name: 'Child action' }),
      screen.getByRole('link', { name: 'Child link' }),
      screen.getByRole('checkbox', { name: 'Child selection' }),
    ]) {
      fireEvent.keyDown(child, { key: 'Enter' })
      fireEvent.keyDown(child, { key: ' ' })
    }
    expect(onNavigate).toHaveBeenCalledTimes(2)
  })

  it('defaults empty table copy and exposes full truncated text', () => {
    const longDescription =
      'This description is deliberately long enough to exceed the shared default bounded text length for table descriptions.'

    render(
      <DataTable>
        <tbody>
          <TableStateRow colSpan={2} />
          <tr>
            <td>
              <TruncatedText value={longDescription} />
            </td>
          </tr>
        </tbody>
      </DataTable>
    )

    expect(screen.getByText('No data')).toBeInTheDocument()
    expect(screen.getByText(/default bounde\.\.\./)).toBeInTheDocument()
    expect(screen.getByRole('tooltip')).toHaveTextContent(longDescription)
  })

  it('keeps table paint contracts compatible with supported browsers', async () => {
    const frontendStyles = readFileSync(
      resolve(process.cwd(), '../packages/frontend-components/styles.css'),
      'utf8'
    )
    const controlStyles = readFileSync(resolve(process.cwd(), 'app/globals.css'), 'utf8')
    const tableHeaderRule = cssRule(frontendStyles, '.eft-table thead th')
    const tableHeaderPaintRule = cssRule(frontendStyles, '.eft-table thead th::before')
    const disabledActionTriggerRule = cssRule(frontendStyles, '.eft-row-actions__trigger:disabled')
    const descriptionCellRule = cssRule(controlStyles, 'td.cu-registry-description')
    const groupedTableRule = cssRule(frontendStyles, '.eft-table--grouped')
    const groupedActionsRule = cssRule(
      frontendStyles,
      '.eft-table--grouped > thead > tr > th:last-child'
    )
    const groupedCountRule = cssRule(controlStyles, '.cu-llm-model-group__count')

    expect(frontendStyles).not.toContain(':has(')
    expect(tableHeaderRule).toContain('background-clip: border-box;')
    expect(tableHeaderRule).toContain('top: -1px;')
    expect(tableHeaderPaintRule).toContain('height: 2px;')
    expect(frontendStyles).toContain('.eft-row-actions__trigger:hover:not(:disabled)')
    expect(disabledActionTriggerRule).toContain('cursor: not-allowed;')
    expect(disabledActionTriggerRule).toContain('opacity: 0.5;')
    expect(descriptionCellRule).toContain('display: table-cell;')
    expect(descriptionCellRule).toContain('overflow: visible;')
    expect(descriptionCellRule).toContain('-webkit-line-clamp: unset;')
    expect(descriptionCellRule).toContain('line-clamp: unset;')
    expect(groupedTableRule).toContain('table-layout: fixed;')
    expect(groupedActionsRule).toContain('text-align: right;')
    expect(groupedActionsRule).toContain('width: var(--eft-table-group-actions-width, 8rem);')
    expect(groupedCountRule).toContain('margin-left: calc((var(--cu-space-2) + 1px) * -1);')

    const seamShadow = '0 -0.375rem 0 var(--eft-surface-muted), inset 0 -1px 0 var(--eft-border)'
    const { unmount } = render(
      <DataTable>
        <thead>
          <tr>
            <TableHeaderCell label="Unwrapped seam" />
          </tr>
        </thead>
      </DataTable>
    )

    expect(screen.getByRole('columnheader', { name: 'Unwrapped seam' })).not.toHaveStyle({
      boxShadow: seamShadow,
    })
    unmount()

    render(
      <TableViewport>
        <DataTable>
          <thead>
            <tr>
              <TableHeaderCell label="Paint seam" />
              <th>Raw seam</th>
            </tr>
          </thead>
        </DataTable>
      </TableViewport>
    )

    await waitFor(() => {
      expect(screen.getByRole('columnheader', { name: 'Paint seam' })).toHaveStyle({
        boxShadow: seamShadow,
      })
      expect(screen.getByRole('columnheader', { name: 'Raw seam' })).toHaveStyle({
        boxShadow: seamShadow,
      })
    })
  })

  it('opens one accessible action menu and executes its destructive action', () => {
    const onDelete = vi.fn()
    render(
      <RowActionMenu
        ariaLabel="Actions for Alpha"
        actions={[{ key: 'delete', label: 'Delete', danger: true, onSelect: onDelete }]}
      />
    )

    fireEvent.click(screen.getByRole('button', { name: 'Actions for Alpha' }))
    const menu = screen.getByRole('menu')
    fireEvent.click(within(menu).getByRole('menuitem', { name: 'Delete' }))
    expect(onDelete).toHaveBeenCalledOnce()
    expect(screen.queryByRole('menu')).not.toBeInTheDocument()
  })

  it('opens a class-A action menu from the whole cell without adding a tab stop', () => {
    const onNavigate = vi.fn()
    render(
      <table>
        <tbody>
          <tr onClick={onNavigate}>
            <td data-testid="action-cell">
              <RowActionMenu
                ariaLabel="Actions for Alpha"
                actions={[{ key: 'view', label: 'View', onSelect: vi.fn() }]}
              />
            </td>
          </tr>
        </tbody>
      </table>
    )

    const cell = screen.getByTestId('action-cell')
    expect(cell).not.toHaveAttribute('tabindex')
    fireEvent.click(cell)
    expect(screen.getByRole('menu')).toBeInTheDocument()
    expect(onNavigate).not.toHaveBeenCalled()
    expect(screen.getAllByRole('button')).toHaveLength(1)
  })

  it('does not widen a mixed-control action cell', () => {
    render(
      <table>
        <tbody>
          <tr>
            <td data-testid="mixed-cell">
              <button type="button">Pin</button>
              <RowActionMenu
                ariaLabel="Actions for Alpha"
                actions={[{ key: 'view', label: 'View', onSelect: vi.fn() }]}
              />
            </td>
          </tr>
        </tbody>
      </table>
    )
    fireEvent.click(screen.getByTestId('mixed-cell'))
    expect(screen.queryByRole('menu')).not.toBeInTheDocument()
  })

  it('disables the trigger when every row action is unavailable', () => {
    const onDelete = vi.fn()
    render(
      <RowActionMenu
        ariaLabel="Actions for Alpha"
        actions={[
          { key: 'delete', label: 'Delete', danger: true, disabled: true, onSelect: onDelete },
        ]}
      />
    )

    const trigger = screen.getByRole('button', { name: 'Actions for Alpha' })
    expect(trigger).toBeDisabled()
    fireEvent.click(trigger)
    expect(screen.queryByRole('menu')).not.toBeInTheDocument()
    expect(onDelete).not.toHaveBeenCalled()
  })

  it('keeps disabled action reasons reachable without running unavailable actions', () => {
    const onDelete = vi.fn()
    render(
      <RowActionMenu
        ariaLabel="Actions for Alpha"
        actions={[
          {
            key: 'delete',
            label: 'Delete',
            danger: true,
            disabled: true,
            disabledReason: 'Only owners can delete this record.',
            onSelect: onDelete,
          },
        ]}
      />
    )

    const trigger = screen.getByRole('button', { name: 'Actions for Alpha' })
    expect(trigger).not.toBeDisabled()
    fireEvent.click(trigger)
    const deleteAction = screen.getByRole('menuitem', { name: /Delete/ })
    expect(deleteAction).toHaveFocus()
    expect(deleteAction).toHaveAttribute('aria-disabled', 'true')
    expect(deleteAction).toHaveTextContent('Only owners can delete this record.')
    fireEvent.click(deleteAction)
    expect(onDelete).not.toHaveBeenCalled()
  })
})