logigate/tests/devices.test.ts

177 lines
7.5 KiB
TypeScript
Raw Normal View History

// The terminal and the keyboard: the text a terminal keeps, the codes keys
// type, and both running in the real editor, a button strobing them.
import * as vue from 'vue'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { compile } from '../app/lib/logic/compile'
import { DATA_KEYS, keyCode, putChar } from '../app/lib/logic/devices'
import { clampSize, displayPins, displaySize, ratioText } from '../app/lib/logic/displays'
import { createProject, lookup } from '../app/lib/logic/ops'
import { Simulator } from '../app/lib/logic/sim'
import { saveProject, setCurrentId } from '../app/lib/logic/storage'
import type { ComponentDef, Project } from '../app/lib/logic/types'
const type = (s: string, cols = 32) => [...s].reduce((lines, c) => putChar(lines, c.charCodeAt(0), cols), [''])
describe('terminal text', () => {
it('prints, breaks lines, goes back, clears', () => {
expect(type('Hi\nyou')).toEqual(['Hi', 'you'])
expect(type('abc\b\bX')).toEqual(['aX'])
expect(type('abcdef', 4)).toEqual(['abcd', 'ef'])
expect(type('a\tb')).toEqual(['a b'])
expect(type('one\rtwo')).toEqual(['two'])
expect(type('junk\fok')).toEqual(['ok'])
expect(type('\x01\x07x')).toEqual(['x'])
expect(putChar(['é'], 0xe9)).toEqual(['éé'])
})
it('keys type their codes', () => {
expect(keyCode({ key: 'a' })).toBe(97)
expect(keyCode({ key: 'Enter' })).toBe(10)
expect(keyCode({ key: 'Backspace' })).toBe(8)
expect(keyCode({ key: 'c', ctrlKey: true })).toBe(3)
expect(keyCode({ key: 'ArrowUp' })).toBeNull()
expect(keyCode({ key: '😀' })).toBeNull()
})
})
/** A keyboard wired straight to a terminal; button W writes the waiting key and takes it, C clears. */
function echoProject(): Project {
const p = createProject({ examples: false })
const def: ComponentDef = {
id: 'echo',
name: 'Echo',
symbol: 'box',
nodes: [
{ id: 'kb', kind: 'keyboard', x: 0, y: 0 },
{ id: 'tm', kind: 'terminal', x: 12, y: 0 },
{ id: 'w', kind: 'button', x: 0, y: 14, label: 'W' },
{ id: 'c', kind: 'button', x: 0, y: 16, label: 'C' },
],
wires: [
...DATA_KEYS.map(k => ({ id: `d-${k}`, from: { node: 'kb', pin: k }, to: { node: 'tm', pin: k } })),
{ id: 'wr', from: { node: 'w', pin: 'q' }, to: { node: 'tm', pin: 'wr' } },
{ id: 'nx', from: { node: 'w', pin: 'q' }, to: { node: 'kb', pin: 'next' } },
{ id: 'cl', from: { node: 'c', pin: 'q' }, to: { node: 'tm', pin: 'clr' } },
],
}
p.components.push(def)
p.openId = def.id
return p
}
let store: Map<string, string>
beforeEach(() => {
store = new Map()
vi.stubGlobal('localStorage', {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => void store.set(k, String(v)),
removeItem: (k: string) => void store.delete(k),
})
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] })
})
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
})
async function openEditor(p: Project) {
saveProject({ id: 'p1', name: p.name, updated: Date.now() }, p)
setCurrentId('p1')
const on = () => {}
vi.stubGlobal('window', { addEventListener: on })
vi.stubGlobal('document', { addEventListener: on, visibilityState: 'visible' })
vi.stubGlobal('location', { pathname: '/', origin: 'http://localhost' })
vi.stubGlobal('history', { state: null, replaceState() {} })
for (const k of ['ref', 'computed', 'reactive', 'shallowRef', 'toRaw', 'watch', 'nextTick'] as const) vi.stubGlobal(k, vue[k])
vi.resetModules()
const { useEditor } = await import('../app/composables/useEditor')
return useEditor()
}
describe('keyboard and terminal in the editor', () => {
it('a rising WR writes the waiting key; NEXT takes it; CLR clears', async () => {
const ed = await openEditor(echoProject())
vi.advanceTimersByTime(100)
const click = (label: string) => {
const n = ed.def.value.nodes.find(x => x.label === label)!
ed.press(n, true)
ed.step()
ed.press(n, false)
ed.step()
}
ed.typeInto('kb')
for (const c of 'Hi!') ed.typeKey(c.charCodeAt(0))
ed.typeKey(10)
ed.typeKey('o'.charCodeAt(0))
ed.sim.value!.run()
expect(ed.val('kb', 'rdy')).toBe(1)
for (let i = 0; i < 5; i++) click('W')
expect(ed.screens.value.get('tm')).toEqual(['Hi!', 'o'])
expect(ed.keyQueues.value.get('kb')).toEqual([])
expect(ed.val('kb', 'rdy')).toBe(0)
// Nothing waiting: a strobe writes code 0, which shows nothing.
click('W')
expect(ed.screens.value.get('tm')).toEqual(['Hi!', 'o'])
click('C')
expect(ed.screens.value.get('tm')).toEqual([''])
})
it('inside a component a keyboard gives 0 and a terminal does nothing', () => {
const p = echoProject()
p.components.push({ id: 'outer', name: 'Outer', symbol: 'box', nodes: [{ id: 'e', kind: 'chip', chip: 'echo', x: 0, y: 0 }], wires: [] })
const s = new Simulator(compile(lookup(p), 'outer'))
s.run()
expect(s.nl.sources.size).toBe(0)
})
})
describe('monitors', () => {
it('pins follow the size: as many X and Y bits as it needs; turning swaps them', () => {
const n = { id: 'm', kind: 'monitor' as const, x: 0, y: 0, dims: [64, 32] as [number, number] }
expect(displayPins(n).map(p => p.label)).toEqual(['X0', 'X1', 'X2', 'X3', 'X4', 'X5', 'Y0', 'Y1', 'Y2', 'Y3', 'Y4', 'D', 'WR', 'CLR'])
expect(displayPins({ ...n, kind: 'rgbmonitor', dims: [5, 3] }).map(p => p.label)).toEqual(['X0', 'X1', 'X2', 'Y0', 'Y1', 'R', 'G', 'B', 'WR', 'CLR'])
expect(ratioText(64, 32)).toBe('2:1')
expect(ratioText(1920, 1080)).toBe('16:9')
expect(ratioText(127, 3)).toBe('42.33:1')
expect(clampSize('monitor', 500, 0)).toEqual([128, 2])
// An old terminal (no size) keeps its 32 × 10 and its pins.
expect(displaySize({ id: 't', kind: 'terminal', x: 0, y: 0 })).toEqual([32, 10])
})
it('a rising WR sets the pixel at X, Y to D; CLR clears; resizing keeps what fits', async () => {
const p = createProject({ examples: false })
const sw = (id: string, y: number) => ({ id, kind: 'input' as const, x: 0, y, label: id.toUpperCase() })
p.components.push({
id: 'mon',
name: 'Mon',
symbol: 'box',
nodes: [sw('x0', 0), sw('x1', 2), sw('y0', 4), sw('y1', 6), sw('d', 8), { id: 'w', kind: 'button', x: 0, y: 10, label: 'W' }, { id: 'c', kind: 'button', x: 0, y: 12, label: 'C' }, { id: 'm', kind: 'monitor', x: 10, y: 0, dims: [4, 4] }],
wires: [...['x0', 'x1', 'y0', 'y1', 'd'].map(k => ({ id: `w${k}`, from: { node: k, pin: 'q' }, to: { node: 'm', pin: k } })), { id: 'ww', from: { node: 'w', pin: 'q' }, to: { node: 'm', pin: 'wr' } }, { id: 'wc', from: { node: 'c', pin: 'q' }, to: { node: 'm', pin: 'clr' } }],
})
p.openId = 'mon'
const ed = await openEditor(p)
vi.advanceTimersByTime(100)
const node = (id: string) => ed.def.value.nodes.find(n => n.id === id)!
const click = (id: string) => {
ed.press(node(id), true)
ed.step()
ed.press(node(id), false)
ed.step()
}
// x = 3, y = 2, d = 1
for (const k of ['x0', 'x1', 'y1', 'd']) ed.toggleInput(node(k))
click('w')
const px = () => [...ed.frames.value.get('m')!.px]
expect(px().indexOf(1)).toBe(2 * 4 + 3)
expect(px().filter(v => v).length).toBe(1)
ed.setDims('m', 8, 3)
expect(ed.frames.value.get('m')!.px.length).toBe(24)
expect(px().indexOf(1)).toBe(2 * 8 + 3)
click('c')
expect(px().some(v => v)).toBe(false)
ed.turnDisplay('m')
expect(node('m').dims).toEqual([3, 8])
})
})