Terminal UI API Update

This commit is contained in:
2025-11-29 03:53:21 +00:00
parent 22e02eb97b
commit 82d896a38e
13 changed files with 952 additions and 256 deletions
+245
View File
@@ -0,0 +1,245 @@
/**
* Terminal API Factory
*
* Creates a reactive API for manipulating terminal content programmatically.
* Use this with TerminalTUI's bindable `terminal` prop.
*/
import type { TerminalLine, ParsedLine, DisplayedLine, TerminalAPI } from './types';
import { parseColorText, getPlainText } from './utils';
import type { ThemeColorMap } from './utils';
export interface TerminalState {
lines: TerminalLine[];
displayedLines: DisplayedLine[];
isTyping: boolean;
isComplete: boolean;
currentLineIndex: number;
selectedIndex: number;
skipRequested: boolean;
}
export interface TerminalAPIOptions {
getState: () => TerminalState;
setState: (updates: Partial<TerminalState>) => void;
getColorMap: () => ThemeColorMap;
getBodyElement: () => HTMLDivElement | undefined;
typeText: () => void;
}
/**
* Parse a single terminal line into segments
*/
export function parseLine(line: TerminalLine, colorMap: ThemeColorMap): ParsedLine {
const segments = parseColorText(line.content, colorMap);
return {
line,
segments,
plainText: getPlainText(segments)
};
}
/**
* Create a terminal API instance
*/
export function createTerminalAPI(options: TerminalAPIOptions): TerminalAPI {
const { getState, setState, getColorMap, getBodyElement, typeText } = options;
function refreshDisplayedLines() {
const state = getState();
const colorMap = getColorMap();
const displayedLines = state.lines.map((line, i) => {
const parsed = parseLine(line, colorMap);
return {
parsed,
charIndex: parsed.plainText.length,
complete: true,
showImage: state.displayedLines[i]?.showImage ?? (line.type === 'image')
};
});
setState({ displayedLines, lines: [...state.lines] });
}
function apiScrollToBottom() {
const bodyElement = getBodyElement();
if (!bodyElement) return;
bodyElement.scrollTo({
top: bodyElement.scrollHeight,
behavior: 'smooth'
});
}
function apiScrollToLine(index: number) {
const bodyElement = getBodyElement();
if (!bodyElement) return;
const lineElements = bodyElement.querySelectorAll('.tui-line');
const target = lineElements[index] as HTMLElement | undefined;
if (target) {
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
return {
clear: () => {
setState({
lines: [],
displayedLines: [],
isComplete: true,
isTyping: false
});
},
write: (line: TerminalLine) => {
const state = getState();
const colorMap = getColorMap();
const parsed = parseLine(line, colorMap);
setState({
lines: [...state.lines, line],
displayedLines: [...state.displayedLines, {
parsed,
charIndex: parsed.plainText.length,
complete: true,
showImage: line.type === 'image'
}]
});
setTimeout(apiScrollToBottom, 10);
},
writeLines: (newLines: TerminalLine[]) => {
const state = getState();
const colorMap = getColorMap();
const newDisplayed = newLines.map(line => {
const parsed = parseLine(line, colorMap);
return {
parsed,
charIndex: parsed.plainText.length,
complete: true,
showImage: line.type === 'image'
};
});
setState({
lines: [...state.lines, ...newLines],
displayedLines: [...state.displayedLines, ...newDisplayed]
});
setTimeout(apiScrollToBottom, 10);
},
update: (index: number, updates: Partial<TerminalLine>) => {
const state = getState();
if (index < 0 || index >= state.lines.length) return;
state.lines[index] = { ...state.lines[index], ...updates };
refreshDisplayedLines();
},
updateContent: (index: number, content: string) => {
const state = getState();
if (index < 0 || index >= state.lines.length) return;
state.lines[index] = { ...state.lines[index], content };
refreshDisplayedLines();
},
insert: (index: number, line: TerminalLine) => {
const state = getState();
const clampedIndex = Math.max(0, Math.min(index, state.lines.length));
setState({
lines: [...state.lines.slice(0, clampedIndex), line, ...state.lines.slice(clampedIndex)]
});
refreshDisplayedLines();
},
remove: (index: number) => {
const state = getState();
if (index < 0 || index >= state.lines.length) return;
setState({
lines: [...state.lines.slice(0, index), ...state.lines.slice(index + 1)]
});
refreshDisplayedLines();
},
removeRange: (startIndex: number, count: number) => {
const state = getState();
if (startIndex < 0 || startIndex >= state.lines.length) return;
setState({
lines: [...state.lines.slice(0, startIndex), ...state.lines.slice(startIndex + count)]
});
refreshDisplayedLines();
},
setLines: (newLines: TerminalLine[]) => {
setState({ lines: [...newLines] });
refreshDisplayedLines();
},
getLineCount: () => getState().lines.length,
getLine: (index: number) => getState().lines[index],
getLines: () => [...getState().lines],
findById: (id: string) => getState().lines.findIndex(line => line.id === id),
updateById: (id: string, updates: Partial<TerminalLine>) => {
const state = getState();
const index = state.lines.findIndex(line => line.id === id);
if (index !== -1) {
state.lines[index] = { ...state.lines[index], ...updates };
refreshDisplayedLines();
}
},
removeById: (id: string) => {
const state = getState();
const index = state.lines.findIndex(line => line.id === id);
if (index !== -1) {
setState({
lines: [...state.lines.slice(0, index), ...state.lines.slice(index + 1)]
});
refreshDisplayedLines();
}
},
scrollToBottom: apiScrollToBottom,
scrollToLine: apiScrollToLine,
isAnimating: () => getState().isTyping,
skip: () => {
const state = getState();
if (!state.isTyping) return;
const colorMap = getColorMap();
const displayedLines = state.lines.map(line => {
const parsed = parseLine(line, colorMap);
return {
parsed,
charIndex: parsed.plainText.length,
complete: true,
showImage: line.type === 'image'
};
});
setState({
skipRequested: true,
displayedLines,
isTyping: false,
isComplete: true,
currentLineIndex: state.lines.length - 1
});
apiScrollToBottom();
},
restart: () => {
setState({
displayedLines: [],
currentLineIndex: 0,
isTyping: false,
isComplete: false,
skipRequested: false,
selectedIndex: -1
});
typeText();
}
};
}
+148
View File
@@ -0,0 +1,148 @@
/**
* Terminal Keyboard Handler
*
* Handles keyboard navigation and interaction for the terminal.
*/
import type { DisplayedLine } from './types';
import { browser } from '$app/environment';
export interface KeyboardHandlerOptions {
getIsTyping: () => boolean;
getIsComplete: () => boolean;
getInteractive: () => boolean;
getButtonIndices: () => number[];
getSelectedIndex: () => number;
setSelectedIndex: (index: number) => void;
getDisplayedLines: () => DisplayedLine[];
getBodyElement: () => HTMLDivElement | undefined;
skipAnimation: () => void;
scrollMargin?: number;
}
/**
* Scroll selected button into view with margin for context
*/
export function scrollToSelected(
bodyElement: HTMLDivElement | undefined,
selectedIndex: number,
displayedLines: DisplayedLine[],
scrollMargin: number = 80
): void {
if (!bodyElement || selectedIndex < 0) return;
const buttons = bodyElement.querySelectorAll('.tui-button');
const btnIndices = displayedLines
.map((item, idx) => item.parsed.line.type === 'button' ? idx : -1)
.filter(idx => idx !== -1);
const selectedButton = Array.from(buttons).find((_, i) => {
return btnIndices[i] === selectedIndex;
}) as HTMLElement | undefined;
if (selectedButton && bodyElement) {
const containerRect = bodyElement.getBoundingClientRect();
const buttonRect = selectedButton.getBoundingClientRect();
if (buttonRect.top < containerRect.top + scrollMargin) {
const scrollAmount = buttonRect.top - containerRect.top - scrollMargin;
bodyElement.scrollBy({ top: scrollAmount, behavior: 'smooth' });
} else if (buttonRect.bottom > containerRect.bottom - scrollMargin) {
const scrollAmount = buttonRect.bottom - containerRect.bottom + scrollMargin;
bodyElement.scrollBy({ top: scrollAmount, behavior: 'smooth' });
}
}
}
/**
* Handle button/link click navigation
*/
export function handleNavigation(line: { action?: () => void; href?: string; external?: boolean } | undefined): void {
if (!line) return;
if (line.action) {
line.action();
} else if (line.href) {
const isExternal = line.external || line.href.startsWith('http://') || line.href.startsWith('https://');
if (isExternal) {
window.open(line.href, '_blank', 'noopener,noreferrer');
} else {
window.location.href = line.href;
}
}
}
/**
* Create a keyboard event handler for the terminal
*/
export function createKeyboardHandler(options: KeyboardHandlerOptions) {
const {
getIsTyping,
getIsComplete,
getInteractive,
getButtonIndices,
getSelectedIndex,
setSelectedIndex,
getDisplayedLines,
getBodyElement,
skipAnimation,
scrollMargin = 80
} = options;
return function handleKeydown(event: KeyboardEvent): void {
// Skip animation on Y key
if (getIsTyping() && (event.key === 'y' || event.key === 'Y')) {
event.preventDefault();
skipAnimation();
return;
}
if (!getInteractive() || !getIsComplete()) return;
const buttonIndices = getButtonIndices();
if (buttonIndices.length === 0) return;
const selectedIndex = getSelectedIndex();
const currentButtonIdx = buttonIndices.indexOf(selectedIndex);
const displayedLines = getDisplayedLines();
const bodyElement = getBodyElement();
if (event.key === 'ArrowDown' || event.key === 'j') {
event.preventDefault();
const nextIdx = (currentButtonIdx + 1) % buttonIndices.length;
const newSelectedIndex = buttonIndices[nextIdx];
setSelectedIndex(newSelectedIndex);
scrollToSelected(bodyElement, newSelectedIndex, displayedLines, scrollMargin);
} else if (event.key === 'ArrowUp' || event.key === 'k') {
event.preventDefault();
const prevIdx = (currentButtonIdx - 1 + buttonIndices.length) % buttonIndices.length;
const newSelectedIndex = buttonIndices[prevIdx];
setSelectedIndex(newSelectedIndex);
scrollToSelected(bodyElement, newSelectedIndex, displayedLines, scrollMargin);
} else if (event.key === 'Enter') {
event.preventDefault();
const selectedLine = displayedLines[selectedIndex]?.parsed.line;
handleNavigation(selectedLine);
}
};
}
/**
* Scroll to hash target (anchor link like #skills)
*/
export function scrollToHash(bodyElement: HTMLDivElement | undefined): void {
if (!browser || !bodyElement) return;
const hash = window.location.hash;
if (!hash) return;
const targetId = hash.slice(1); // Remove the #
const targetElement = bodyElement.querySelector(`#${CSS.escape(targetId)}`);
if (targetElement) {
// Small delay to ensure layout is complete
setTimeout(() => {
targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
}, 100);
}
}
+222
View File
@@ -0,0 +1,222 @@
/**
* Terminal Typing Animation Engine
*
* Handles the character-by-character typing animation for terminal lines.
*/
import type { ParsedLine, DisplayedLine } from './types';
import type { TerminalSettings } from '$lib/config';
import { calculateTypeSpeed } from '$lib';
export interface TypingState {
displayedLines: DisplayedLine[];
currentLineIndex: number;
isTyping: boolean;
isComplete: boolean;
skipRequested: boolean;
selectedIndex: number;
}
export interface TypingOptions {
parsedLines: ParsedLine[];
speedMultiplier: number;
terminalSettings: TerminalSettings;
buttonIndices: number[];
interactive: boolean;
autoscroll: boolean;
getBodyElement: () => HTMLDivElement | undefined;
getState: () => TypingState;
setState: (updates: Partial<TypingState>) => void;
onComplete?: () => void;
scrollToHash: () => void;
}
function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* Scroll terminal body to bottom
*/
function scrollToBottom(bodyElement: HTMLDivElement | undefined, autoscroll: boolean) {
if (!autoscroll || !bodyElement) return;
bodyElement.scrollTo({
top: bodyElement.scrollHeight,
behavior: 'smooth'
});
}
/**
* Run the typing animation for all lines
*/
export async function runTypingAnimation(options: TypingOptions): Promise<void> {
const {
parsedLines,
speedMultiplier,
terminalSettings,
buttonIndices,
interactive,
autoscroll,
getBodyElement,
getState,
setState,
onComplete,
scrollToHash
} = options;
if (parsedLines.length === 0) return;
setState({ isTyping: true });
// Apply speed multiplier to start delay
const startDelayMs = speedMultiplier === 0 ? 0 : terminalSettings.startDelay * speedMultiplier;
await sleep(startDelayMs);
if (getState().skipRequested) return;
for (let i = 0; i < parsedLines.length; i++) {
const state = getState();
if (state.skipRequested) return;
const parsed = parsedLines[i];
const line = parsed.line;
const plainLength = parsed.plainText.length;
// Add new line to displayed lines
const currentDisplayed = [...state.displayedLines, { parsed, charIndex: 0, complete: false, showImage: false }];
setState({ displayedLines: currentDisplayed, currentLineIndex: i });
if (line.delay && speedMultiplier > 0) {
await sleep(line.delay * speedMultiplier);
if (getState().skipRequested) return;
}
const bodyElement = getBodyElement();
// Handle different line types
if (line.type === 'image') {
await sleep(speedMultiplier === 0 ? 0 : 100 * speedMultiplier);
if (getState().skipRequested) return;
updateDisplayedLine(i, { parsed, charIndex: plainLength, complete: true, showImage: true }, getState, setState);
scrollToBottom(bodyElement, autoscroll);
} else if (line.type === 'blank' || line.type === 'divider') {
updateDisplayedLine(i, { parsed, charIndex: plainLength, complete: true, showImage: false }, getState, setState);
} else if (line.type === 'button') {
// Buttons appear instantly
updateDisplayedLine(i, { parsed, charIndex: plainLength, complete: true, showImage: false }, getState, setState);
scrollToBottom(bodyElement, autoscroll);
} else if (speedMultiplier === 0) {
// Instant mode - no typing animation
updateDisplayedLine(i, { parsed, charIndex: plainLength, complete: true, showImage: false }, getState, setState);
if (i % 5 === 0) scrollToBottom(bodyElement, autoscroll);
} else if (line.type === 'header') {
const typeSpeed = calculateTypeSpeed(plainLength, speedMultiplier * 0.25);
for (let j = 0; j <= plainLength; j++) {
if (getState().skipRequested) return;
updateDisplayedLine(i, {
parsed,
charIndex: j,
complete: j === plainLength,
showImage: false
}, getState, setState);
if (j < plainLength) await sleep(typeSpeed);
}
scrollToBottom(bodyElement, autoscroll);
} else {
const typeSpeed = calculateTypeSpeed(plainLength, speedMultiplier);
for (let j = 0; j <= plainLength; j++) {
if (getState().skipRequested) return;
updateDisplayedLine(i, {
parsed,
charIndex: j,
complete: j === plainLength,
showImage: false
}, getState, setState);
if (j % 10 === 0) scrollToBottom(bodyElement, autoscroll);
if (j < plainLength) {
await sleep(typeSpeed);
}
}
}
if (getState().skipRequested) return;
// Mark line as complete
const finalState = getState();
const updatedLines = [...finalState.displayedLines];
if (updatedLines[i]) {
updatedLines[i].complete = true;
setState({ displayedLines: updatedLines });
}
scrollToBottom(bodyElement, autoscroll);
if (i < parsedLines.length - 1 && speedMultiplier > 0) {
await sleep(terminalSettings.lineDelay * speedMultiplier);
}
}
setState({ isTyping: false, isComplete: true });
if (interactive && buttonIndices.length > 0) {
setState({ selectedIndex: buttonIndices[0] });
}
// Scroll to hash anchor if present in URL
scrollToHash();
onComplete?.();
}
/**
* Update a single displayed line at index
*/
function updateDisplayedLine(
index: number,
update: DisplayedLine,
getState: () => TypingState,
setState: (updates: Partial<TypingState>) => void
) {
const state = getState();
const updatedLines = [...state.displayedLines];
updatedLines[index] = update;
setState({ displayedLines: updatedLines });
}
/**
* Skip animation and show all content instantly
*/
export function skipTypingAnimation(
parsedLines: ParsedLine[],
buttonIndices: number[],
interactive: boolean,
getState: () => TypingState,
setState: (updates: Partial<TypingState>) => void,
getBodyElement: () => HTMLDivElement | undefined,
autoscroll: boolean,
onComplete?: () => void
): void {
const state = getState();
if (!state.isTyping) return;
const displayedLines = parsedLines.map(parsed => ({
parsed,
charIndex: parsed.plainText.length,
complete: true,
showImage: parsed.line.type === 'image'
}));
setState({
skipRequested: true,
displayedLines,
isTyping: false,
isComplete: true,
currentLineIndex: parsedLines.length - 1,
selectedIndex: interactive && buttonIndices.length > 0 ? buttonIndices[0] : -1
});
scrollToBottom(getBodyElement(), autoscroll);
onComplete?.();
}
+44
View File
@@ -15,6 +15,50 @@ export interface FormOption {
disabled?: boolean;
}
// Terminal API for reactive manipulation
export interface TerminalAPI {
/** Clear all lines from the terminal */
clear: () => void;
/** Write a new line to the terminal (appends) */
write: (line: TerminalLine) => void;
/** Write multiple lines to the terminal (appends) */
writeLines: (lines: TerminalLine[]) => void;
/** Update a specific line by index */
update: (index: number, line: Partial<TerminalLine>) => void;
/** Update a line's content by index */
updateContent: (index: number, content: string) => void;
/** Insert a line at a specific index */
insert: (index: number, line: TerminalLine) => void;
/** Remove a line by index */
remove: (index: number) => void;
/** Remove lines by range */
removeRange: (startIndex: number, count: number) => void;
/** Replace all lines */
setLines: (lines: TerminalLine[]) => void;
/** Get current line count */
getLineCount: () => number;
/** Get a line by index */
getLine: (index: number) => TerminalLine | undefined;
/** Get all lines */
getLines: () => TerminalLine[];
/** Find line index by id */
findById: (id: string) => number;
/** Update a line by its id */
updateById: (id: string, line: Partial<TerminalLine>) => void;
/** Remove a line by its id */
removeById: (id: string) => void;
/** Scroll to bottom */
scrollToBottom: () => void;
/** Scroll to a specific line index */
scrollToLine: (index: number) => void;
/** Check if terminal is currently animating */
isAnimating: () => boolean;
/** Skip current animation */
skip: () => void;
/** Restart the typing animation */
restart: () => void;
}
export interface TerminalLine {
type: LineType;
content: string;