scroll/src/common/search.ts
Timothy J. Warren 33f19ddec1
All checks were successful
timw4mail/scroll/pipeline/head This commit looks good
Basic number highlighting
2024-02-29 15:48:11 -05:00

68 lines
1.4 KiB
JavaScript

import { Position } from './types.ts';
import { KeyCommand } from './ansi.ts';
import Document from './document.ts';
enum SearchDirection {
Forward = 1,
Backward = -1,
}
export class Search {
private lastMatch: number = -1;
private current: number = -1;
private direction: SearchDirection = SearchDirection.Forward;
public parent: Document | null = null;
private parseInput(key: string) {
switch (key) {
case KeyCommand.ArrowRight:
case KeyCommand.ArrowDown:
this.direction = SearchDirection.Forward;
break;
case KeyCommand.ArrowLeft:
case KeyCommand.ArrowUp:
this.direction = SearchDirection.Backward;
break;
default:
this.lastMatch = -1;
this.direction = SearchDirection.Forward;
}
if (this.lastMatch === -1) {
this.direction = SearchDirection.Forward;
}
this.current = this.lastMatch;
}
private getNextRow(rowCount: number): number {
this.current += this.direction;
if (this.current === -1) {
this.current = rowCount - 1;
} else if (this.current === rowCount) {
this.current = 0;
}
return this.current;
}
public search(q: string, key: string): Position | null {
this.parseInput(key);
let i = 0;
for (; i < this.parent!.numRows; i++) {
const current = this.getNextRow(this.parent!.numRows);
const possible = this.parent!.row(current)!.find(q);
if (possible !== null) {
this.lastMatch = current;
return Position.at(possible, current);
}
}
return null;
}
}