This commit is contained in:
@ -1,14 +1,17 @@
|
|||||||
import { useState, useEffect, useRef } from "preact/hooks";
|
import { useState, useEffect, useRef } from "preact/hooks";
|
||||||
import type { JSX } from "preact";
|
import type { JSX } from "preact";
|
||||||
import type { Command } from "../lib/terminal/types";
|
import type { Command } from "../utils/terminal/types";
|
||||||
import { buildFileSystem } from "../lib/terminal/fileSystem";
|
import { buildFileSystem } from "../utils/terminal/fs";
|
||||||
import { executeCommand, type CommandContext } from "../lib/terminal/commands";
|
import {
|
||||||
|
executeCommand,
|
||||||
|
type CommandContext,
|
||||||
|
} from "../utils/terminal/commands";
|
||||||
import {
|
import {
|
||||||
getCompletions,
|
getCompletions,
|
||||||
formatOutput,
|
formatOutput,
|
||||||
saveCommandToHistory,
|
saveCommandToHistory,
|
||||||
loadCommandHistory,
|
loadCommandHistory,
|
||||||
} from "../lib/terminal/utils";
|
} from "../utils/terminal/utils";
|
||||||
|
|
||||||
const Terminal = () => {
|
const Terminal = () => {
|
||||||
const [currentPath, setCurrentPath] = useState("/");
|
const [currentPath, setCurrentPath] = useState("/");
|
||||||
@ -145,7 +148,7 @@ const Terminal = () => {
|
|||||||
<div
|
<div
|
||||||
ref={terminalRef}
|
ref={terminalRef}
|
||||||
className={`flex-1 p-4 overflow-y-auto scrollbar-thin scrollbar-thumb-base-300 scrollbar-track-base-100 relative ${
|
className={`flex-1 p-4 overflow-y-auto scrollbar-thin scrollbar-thumb-base-300 scrollbar-track-base-100 relative ${
|
||||||
isTrainRunning ? 'opacity-0' : 'opacity-100'
|
isTrainRunning ? "opacity-0" : "opacity-100"
|
||||||
}`}
|
}`}
|
||||||
onClick={() => !isTrainRunning && inputRef.current?.focus()}
|
onClick={() => !isTrainRunning && inputRef.current?.focus()}
|
||||||
>
|
>
|
||||||
@ -198,7 +201,6 @@ const Terminal = () => {
|
|||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Train animation overlay - positioned over the content area but outside the opacity div */}
|
{/* Train animation overlay - positioned over the content area but outside the opacity div */}
|
||||||
|
@ -1,40 +1,48 @@
|
|||||||
import type { APIRoute } from 'astro';
|
import type { APIRoute } from "astro";
|
||||||
|
import {
|
||||||
|
getSpotifyCredentials,
|
||||||
|
isSpotifyConfigured,
|
||||||
|
} from "../../../utils/spotify";
|
||||||
|
|
||||||
export const GET: APIRoute = async () => {
|
export const GET: APIRoute = async () => {
|
||||||
try {
|
try {
|
||||||
// Only check environment variables at runtime, not build time
|
const isConfigured = isSpotifyConfigured();
|
||||||
const clientId = process.env.SPOTIFY_CLIENT_ID;
|
|
||||||
const clientSecret = process.env.SPOTIFY_CLIENT_SECRET;
|
|
||||||
const refreshToken = process.env.SPOTIFY_REFRESH_TOKEN;
|
|
||||||
|
|
||||||
const isConfigured = !!(clientId && clientSecret && refreshToken);
|
|
||||||
|
|
||||||
if (!isConfigured) {
|
if (!isConfigured) {
|
||||||
console.log('Spotify integration disabled - missing environment variables:', {
|
const credentials = getSpotifyCredentials();
|
||||||
hasClientId: !!clientId,
|
console.log(
|
||||||
hasClientSecret: !!clientSecret,
|
"Spotify integration disabled - missing environment variables:",
|
||||||
hasRefreshToken: !!refreshToken
|
{
|
||||||
});
|
hasClientId: !!credentials?.clientId,
|
||||||
|
hasClientSecret: !!credentials?.clientSecret,
|
||||||
|
hasRefreshToken: !!credentials?.refreshToken,
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Response(JSON.stringify({
|
return new Response(
|
||||||
configured: isConfigured
|
JSON.stringify({
|
||||||
}), {
|
configured: isConfigured,
|
||||||
status: 200,
|
}),
|
||||||
headers: {
|
{
|
||||||
'Content-Type': 'application/json',
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error checking Spotify configuration:', error);
|
console.error("Error checking Spotify configuration:", error);
|
||||||
return new Response(JSON.stringify({
|
return new Response(
|
||||||
configured: false
|
JSON.stringify({
|
||||||
}), {
|
configured: false,
|
||||||
status: 200,
|
}),
|
||||||
headers: {
|
{
|
||||||
'Content-Type': 'application/json',
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -1,62 +1,74 @@
|
|||||||
import type { APIRoute } from 'astro';
|
import type { APIRoute } from "astro";
|
||||||
|
import { getSpotifyCredentials } from "../../../utils/spotify";
|
||||||
|
|
||||||
// Helper function to refresh the access token
|
// Refresh the access token
|
||||||
async function refreshSpotifyToken(refreshToken: string, clientId: string, clientSecret: string) {
|
async function refreshSpotifyToken(
|
||||||
const response = await fetch('https://accounts.spotify.com/api/token', {
|
refreshToken: string,
|
||||||
method: 'POST',
|
clientId: string,
|
||||||
|
clientSecret: string,
|
||||||
|
) {
|
||||||
|
const response = await fetch("https://accounts.spotify.com/api/token", {
|
||||||
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/x-www-form-urlencoded',
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
'Authorization': `Basic ${btoa(`${clientId}:${clientSecret}`)}`,
|
Authorization: `Basic ${btoa(`${clientId}:${clientSecret}`)}`,
|
||||||
},
|
},
|
||||||
body: new URLSearchParams({
|
body: new URLSearchParams({
|
||||||
grant_type: 'refresh_token',
|
grant_type: "refresh_token",
|
||||||
refresh_token: refreshToken,
|
refresh_token: refreshToken,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error('Failed to refresh token');
|
throw new Error("Failed to refresh token");
|
||||||
}
|
}
|
||||||
|
|
||||||
return await response.json();
|
return await response.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Function to fetch current track from Spotify
|
// Function to fetch current track from Spotify
|
||||||
async function fetchCurrentTrack() {
|
async function fetchCurrentTrack(
|
||||||
|
clientId: string,
|
||||||
|
clientSecret: string,
|
||||||
|
refreshToken: string,
|
||||||
|
accessToken?: string,
|
||||||
|
) {
|
||||||
try {
|
try {
|
||||||
// Use runtime env vars instead of build-time
|
let currentAccessToken = accessToken;
|
||||||
const clientId = process.env.SPOTIFY_CLIENT_ID;
|
|
||||||
const clientSecret = process.env.SPOTIFY_CLIENT_SECRET;
|
|
||||||
let accessToken = process.env.SPOTIFY_ACCESS_TOKEN;
|
|
||||||
const refreshToken = process.env.SPOTIFY_REFRESH_TOKEN;
|
|
||||||
|
|
||||||
if (!clientId || !clientSecret || !refreshToken) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to fetch current track with existing token
|
// Try to fetch current track with existing token
|
||||||
let spotifyResponse = await fetch('https://api.spotify.com/v1/me/player/currently-playing', {
|
let spotifyResponse = await fetch(
|
||||||
headers: {
|
"https://api.spotify.com/v1/me/player/currently-playing",
|
||||||
'Authorization': `Bearer ${accessToken}`,
|
{
|
||||||
'Content-Type': 'application/json',
|
headers: {
|
||||||
|
Authorization: `Bearer ${currentAccessToken}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
);
|
||||||
|
|
||||||
// If token is expired (401), refresh it
|
// If token is expired (401), refresh it
|
||||||
if (spotifyResponse.status === 401) {
|
if (spotifyResponse.status === 401) {
|
||||||
try {
|
try {
|
||||||
const tokenData = await refreshSpotifyToken(refreshToken, clientId, clientSecret);
|
const tokenData = await refreshSpotifyToken(
|
||||||
accessToken = tokenData.access_token;
|
refreshToken,
|
||||||
|
clientId,
|
||||||
|
clientSecret,
|
||||||
|
);
|
||||||
|
currentAccessToken = tokenData.access_token;
|
||||||
|
|
||||||
// Retry the request with new token
|
// Retry the request with new token
|
||||||
spotifyResponse = await fetch('https://api.spotify.com/v1/me/player/currently-playing', {
|
spotifyResponse = await fetch(
|
||||||
headers: {
|
"https://api.spotify.com/v1/me/player/currently-playing",
|
||||||
'Authorization': `Bearer ${accessToken}`,
|
{
|
||||||
'Content-Type': 'application/json',
|
headers: {
|
||||||
|
Authorization: `Bearer ${currentAccessToken}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
);
|
||||||
} catch (refreshError) {
|
} catch (refreshError) {
|
||||||
console.error('Failed to refresh token:', refreshError);
|
console.error("Failed to refresh token:", refreshError);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -65,7 +77,7 @@ async function fetchCurrentTrack() {
|
|||||||
// Nothing is currently playing
|
// Nothing is currently playing
|
||||||
return {
|
return {
|
||||||
is_playing: false,
|
is_playing: false,
|
||||||
item: null
|
item: null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -74,118 +86,160 @@ async function fetchCurrentTrack() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const data = await spotifyResponse.json();
|
const data = await spotifyResponse.json();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
is_playing: data.is_playing,
|
is_playing: data.is_playing,
|
||||||
item: data.item ? {
|
item: data.item
|
||||||
name: data.item.name,
|
? {
|
||||||
artists: data.item.artists,
|
name: data.item.name,
|
||||||
is_playing: data.is_playing,
|
artists: data.item.artists,
|
||||||
external_urls: data.item.external_urls
|
is_playing: data.is_playing,
|
||||||
} : null
|
external_urls: data.item.external_urls,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Spotify API Error:', error);
|
console.error("Spotify API Error:", error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const GET: APIRoute = async ({ request }) => {
|
export const GET: APIRoute = async ({ request }) => {
|
||||||
// Set up Server-Sent Events
|
try {
|
||||||
const encoder = new TextEncoder();
|
// Get Spotify credentials
|
||||||
let controller: ReadableStreamDefaultController<Uint8Array>;
|
const credentials = getSpotifyCredentials();
|
||||||
let isClosed = false;
|
|
||||||
let pollInterval: NodeJS.Timeout | null = null;
|
|
||||||
|
|
||||||
const stream = new ReadableStream({
|
|
||||||
start(ctrl) {
|
|
||||||
controller = ctrl;
|
|
||||||
},
|
|
||||||
cancel() {
|
|
||||||
// Client disconnected
|
|
||||||
console.log('SSE stream cancelled by client');
|
|
||||||
isClosed = true;
|
|
||||||
if (pollInterval) {
|
|
||||||
clearInterval(pollInterval);
|
|
||||||
pollInterval = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Function to send SSE message
|
if (!credentials) {
|
||||||
const sendMessage = (data: any) => {
|
console.log(
|
||||||
if (isClosed) {
|
"Spotify SSE stream disabled - missing environment variables",
|
||||||
return; // Don't try to send if stream is closed
|
);
|
||||||
|
return new Response(JSON.stringify({ error: "Spotify not configured" }), {
|
||||||
|
status: 503,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
const { clientId, clientSecret, refreshToken, accessToken } = credentials;
|
||||||
const message = `data: ${JSON.stringify(data)}\n\n`;
|
|
||||||
controller.enqueue(encoder.encode(message));
|
// Set up Server-Sent Events
|
||||||
} catch (error) {
|
const encoder = new TextEncoder();
|
||||||
if (error instanceof TypeError && error.message.includes('Controller is already closed')) {
|
let controller: ReadableStreamDefaultController<Uint8Array>;
|
||||||
console.log('SSE controller is closed, stopping polling');
|
let isClosed = false;
|
||||||
|
let pollInterval: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
const stream = new ReadableStream({
|
||||||
|
start(ctrl) {
|
||||||
|
controller = ctrl;
|
||||||
|
},
|
||||||
|
cancel() {
|
||||||
|
// Client disconnected
|
||||||
|
console.log("SSE stream cancelled by client");
|
||||||
isClosed = true;
|
isClosed = true;
|
||||||
if (pollInterval) {
|
if (pollInterval) {
|
||||||
clearInterval(pollInterval);
|
clearInterval(pollInterval);
|
||||||
pollInterval = null;
|
pollInterval = null;
|
||||||
}
|
}
|
||||||
} else {
|
},
|
||||||
console.error('Error sending SSE message:', error);
|
});
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Start polling and sending updates
|
// Function to send SSE message
|
||||||
let lastTrackData: any = null;
|
const sendMessage = (data: any) => {
|
||||||
|
if (isClosed) {
|
||||||
const poll = async () => {
|
return; // Don't try to send if stream is closed
|
||||||
if (isClosed) {
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const message = `data: ${JSON.stringify(data)}\n\n`;
|
||||||
|
controller.enqueue(encoder.encode(message));
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
error instanceof TypeError &&
|
||||||
|
error.message.includes("Controller is already closed")
|
||||||
|
) {
|
||||||
|
console.log("SSE controller is closed, stopping polling");
|
||||||
|
isClosed = true;
|
||||||
|
if (pollInterval) {
|
||||||
|
clearInterval(pollInterval);
|
||||||
|
pollInterval = null;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error("Error sending SSE message:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Start polling and sending updates
|
||||||
|
let lastTrackData: any = null;
|
||||||
|
|
||||||
|
const poll = async () => {
|
||||||
|
if (isClosed) {
|
||||||
|
if (pollInterval) {
|
||||||
|
clearInterval(pollInterval);
|
||||||
|
pollInterval = null;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const currentTrack = await fetchCurrentTrack(
|
||||||
|
clientId,
|
||||||
|
clientSecret,
|
||||||
|
refreshToken,
|
||||||
|
accessToken,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Only send if data has changed and stream is still open
|
||||||
|
if (
|
||||||
|
!isClosed &&
|
||||||
|
JSON.stringify(currentTrack) !== JSON.stringify(lastTrackData)
|
||||||
|
) {
|
||||||
|
lastTrackData = currentTrack;
|
||||||
|
sendMessage(currentTrack || { is_playing: false, item: null });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (!isClosed) {
|
||||||
|
console.error("Polling error:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Send initial data
|
||||||
|
poll();
|
||||||
|
|
||||||
|
// Poll every 3 seconds
|
||||||
|
pollInterval = setInterval(poll, 3000);
|
||||||
|
|
||||||
|
// Clean up when client disconnects (abort signal)
|
||||||
|
request.signal.addEventListener("abort", () => {
|
||||||
|
console.log("SSE request aborted");
|
||||||
|
isClosed = true;
|
||||||
if (pollInterval) {
|
if (pollInterval) {
|
||||||
clearInterval(pollInterval);
|
clearInterval(pollInterval);
|
||||||
pollInterval = null;
|
pollInterval = null;
|
||||||
}
|
}
|
||||||
return;
|
});
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
return new Response(stream, {
|
||||||
const currentTrack = await fetchCurrentTrack();
|
headers: {
|
||||||
|
"Content-Type": "text/event-stream",
|
||||||
// Only send if data has changed and stream is still open
|
"Cache-Control": "no-cache",
|
||||||
if (!isClosed && JSON.stringify(currentTrack) !== JSON.stringify(lastTrackData)) {
|
Connection: "keep-alive",
|
||||||
lastTrackData = currentTrack;
|
"Access-Control-Allow-Origin": "*",
|
||||||
sendMessage(currentTrack || { is_playing: false, item: null });
|
"Access-Control-Allow-Headers": "Cache-Control",
|
||||||
}
|
},
|
||||||
} catch (error) {
|
});
|
||||||
if (!isClosed) {
|
} catch (error) {
|
||||||
console.error('Polling error:', error);
|
console.error("Error setting up Spotify SSE stream:", error);
|
||||||
}
|
return new Response(
|
||||||
}
|
JSON.stringify({ error: "Failed to initialize stream" }),
|
||||||
};
|
{
|
||||||
|
status: 500,
|
||||||
// Send initial data
|
headers: {
|
||||||
poll();
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
// Poll every 3 seconds
|
},
|
||||||
pollInterval = setInterval(poll, 3000);
|
);
|
||||||
|
}
|
||||||
// Clean up when client disconnects (abort signal)
|
};
|
||||||
request.signal.addEventListener('abort', () => {
|
|
||||||
console.log('SSE request aborted');
|
|
||||||
isClosed = true;
|
|
||||||
if (pollInterval) {
|
|
||||||
clearInterval(pollInterval);
|
|
||||||
pollInterval = null;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return new Response(stream, {
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'text/event-stream',
|
|
||||||
'Cache-Control': 'no-cache',
|
|
||||||
'Connection': 'keep-alive',
|
|
||||||
'Access-Control-Allow-Origin': '*',
|
|
||||||
'Access-Control-Allow-Headers': 'Cache-Control',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
41
src/utils/spotify.ts
Normal file
41
src/utils/spotify.ts
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
interface SpotifyCredentials {
|
||||||
|
clientId: string;
|
||||||
|
clientSecret: string;
|
||||||
|
refreshToken: string;
|
||||||
|
accessToken?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get Spotify credentials from environment variables
|
||||||
|
* Checks both process.env and import.meta.env for compatibility
|
||||||
|
*/
|
||||||
|
export function getSpotifyCredentials(): SpotifyCredentials | null {
|
||||||
|
const clientId =
|
||||||
|
process.env.SPOTIFY_CLIENT_ID || import.meta.env.SPOTIFY_CLIENT_ID;
|
||||||
|
const clientSecret =
|
||||||
|
process.env.SPOTIFY_CLIENT_SECRET ||
|
||||||
|
import.meta.env.SPOTIFY_CLIENT_SECRET;
|
||||||
|
const refreshToken =
|
||||||
|
process.env.SPOTIFY_REFRESH_TOKEN ||
|
||||||
|
import.meta.env.SPOTIFY_REFRESH_TOKEN;
|
||||||
|
const accessToken =
|
||||||
|
process.env.SPOTIFY_ACCESS_TOKEN || import.meta.env.SPOTIFY_ACCESS_TOKEN;
|
||||||
|
|
||||||
|
if (!clientId || !clientSecret || !refreshToken) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
clientId,
|
||||||
|
clientSecret,
|
||||||
|
refreshToken,
|
||||||
|
accessToken,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if Spotify integration is properly configured
|
||||||
|
*/
|
||||||
|
export function isSpotifyConfigured(): boolean {
|
||||||
|
return getSpotifyCredentials() !== null;
|
||||||
|
}
|
@ -1,5 +1,5 @@
|
|||||||
import type { FileSystemNode } from './types';
|
import type { FileSystemNode } from "./types";
|
||||||
import { getCurrentDirectory, resolvePath } from './fileSystem';
|
import { getCurrentDirectory, resolvePath } from "./fs";
|
||||||
|
|
||||||
export interface CommandContext {
|
export interface CommandContext {
|
||||||
currentPath: string;
|
currentPath: string;
|
||||||
@ -11,30 +11,30 @@ export interface CommandContext {
|
|||||||
|
|
||||||
export function executeCommand(input: string, context: CommandContext): string {
|
export function executeCommand(input: string, context: CommandContext): string {
|
||||||
const trimmedInput = input.trim();
|
const trimmedInput = input.trim();
|
||||||
if (!trimmedInput) return '';
|
if (!trimmedInput) return "";
|
||||||
|
|
||||||
const [command, ...args] = trimmedInput.split(' ');
|
const [command, ...args] = trimmedInput.split(" ");
|
||||||
|
|
||||||
switch (command.toLowerCase()) {
|
switch (command.toLowerCase()) {
|
||||||
case 'help':
|
case "help":
|
||||||
return handleHelp();
|
return handleHelp();
|
||||||
case 'ls':
|
case "ls":
|
||||||
return handleLs(args, context);
|
return handleLs(args, context);
|
||||||
case 'cd':
|
case "cd":
|
||||||
return handleCd(args, context);
|
return handleCd(args, context);
|
||||||
case 'pwd':
|
case "pwd":
|
||||||
return handlePwd(context);
|
return handlePwd(context);
|
||||||
case 'cat':
|
case "cat":
|
||||||
return handleCat(args, context);
|
return handleCat(args, context);
|
||||||
case 'tree':
|
case "tree":
|
||||||
return handleTree(context);
|
return handleTree(context);
|
||||||
case 'clear':
|
case "clear":
|
||||||
return '';
|
return "";
|
||||||
case 'whoami':
|
case "whoami":
|
||||||
return handleWhoami();
|
return handleWhoami();
|
||||||
case 'open':
|
case "open":
|
||||||
return handleOpen(args);
|
return handleOpen(args);
|
||||||
case 'sl':
|
case "sl":
|
||||||
return handleSl(context);
|
return handleSl(context);
|
||||||
default:
|
default:
|
||||||
return `${command}: command not found. Type 'help' for available commands.`;
|
return `${command}: command not found. Type 'help' for available commands.`;
|
||||||
@ -73,162 +73,178 @@ function handleHelp(): string {
|
|||||||
function handleLs(args: string[], context: CommandContext): string {
|
function handleLs(args: string[], context: CommandContext): string {
|
||||||
const { currentPath, fileSystem } = context;
|
const { currentPath, fileSystem } = context;
|
||||||
const targetPath = args[0] ? resolvePath(currentPath, args[0]) : currentPath;
|
const targetPath = args[0] ? resolvePath(currentPath, args[0]) : currentPath;
|
||||||
const pathParts = targetPath.split('/').filter((part: string) => part !== '');
|
const pathParts = targetPath.split("/").filter((part: string) => part !== "");
|
||||||
let target = fileSystem['/'];
|
let target = fileSystem["/"];
|
||||||
|
|
||||||
for (const part of pathParts) {
|
for (const part of pathParts) {
|
||||||
if (target?.children && target.children[part] && target.children[part].type === 'directory') {
|
if (
|
||||||
|
target?.children &&
|
||||||
|
target.children[part] &&
|
||||||
|
target.children[part].type === "directory"
|
||||||
|
) {
|
||||||
target = target.children[part];
|
target = target.children[part];
|
||||||
} else if (pathParts.length > 0) {
|
} else if (pathParts.length > 0) {
|
||||||
return `ls: cannot access '${targetPath}': No such file or directory`;
|
return `ls: cannot access '${targetPath}': No such file or directory`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!target?.children) {
|
if (!target?.children) {
|
||||||
return `ls: cannot access '${targetPath}': Not a directory`;
|
return `ls: cannot access '${targetPath}': Not a directory`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const items = Object.values(target.children)
|
const items = Object.values(target.children)
|
||||||
.map(item => {
|
.map((item) => {
|
||||||
const color = item.type === 'directory' ? '\x1b[34m' : '\x1b[0m';
|
const color = item.type === "directory" ? "\x1b[34m" : "\x1b[0m";
|
||||||
const suffix = item.type === 'directory' ? '/' : '';
|
const suffix = item.type === "directory" ? "/" : "";
|
||||||
return `${color}${item.name}${suffix}\x1b[0m`;
|
return `${color}${item.name}${suffix}\x1b[0m`;
|
||||||
})
|
})
|
||||||
.join(' ');
|
.join(" ");
|
||||||
|
|
||||||
return items || 'Directory is empty';
|
return items || "Directory is empty";
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleCd(args: string[], context: CommandContext): string {
|
function handleCd(args: string[], context: CommandContext): string {
|
||||||
const { currentPath, fileSystem, setCurrentPath } = context;
|
const { currentPath, fileSystem, setCurrentPath } = context;
|
||||||
const targetPath = args[0] ? resolvePath(currentPath, args[0]) : '/';
|
const targetPath = args[0] ? resolvePath(currentPath, args[0]) : "/";
|
||||||
const pathParts = targetPath.split('/').filter((part: string) => part !== '');
|
const pathParts = targetPath.split("/").filter((part: string) => part !== "");
|
||||||
let current = fileSystem['/'];
|
let current = fileSystem["/"];
|
||||||
|
|
||||||
for (const part of pathParts) {
|
for (const part of pathParts) {
|
||||||
if (current?.children && current.children[part] && current.children[part].type === 'directory') {
|
if (
|
||||||
|
current?.children &&
|
||||||
|
current.children[part] &&
|
||||||
|
current.children[part].type === "directory"
|
||||||
|
) {
|
||||||
current = current.children[part];
|
current = current.children[part];
|
||||||
} else {
|
} else {
|
||||||
return `cd: no such file or directory: ${targetPath}`;
|
return `cd: no such file or directory: ${targetPath}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
setCurrentPath(targetPath || '/');
|
setCurrentPath(targetPath || "/");
|
||||||
return '';
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
function handlePwd(context: CommandContext): string {
|
function handlePwd(context: CommandContext): string {
|
||||||
return context.currentPath || '/';
|
return context.currentPath || "/";
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleCat(args: string[], context: CommandContext): string {
|
function handleCat(args: string[], context: CommandContext): string {
|
||||||
const { currentPath, fileSystem } = context;
|
const { currentPath, fileSystem } = context;
|
||||||
|
|
||||||
if (!args[0]) {
|
if (!args[0]) {
|
||||||
return 'cat: missing file argument';
|
return "cat: missing file argument";
|
||||||
}
|
}
|
||||||
|
|
||||||
const filePath = resolvePath(currentPath, args[0]);
|
const filePath = resolvePath(currentPath, args[0]);
|
||||||
const pathParts = filePath.split('/').filter((part: string) => part !== '');
|
const pathParts = filePath.split("/").filter((part: string) => part !== "");
|
||||||
const fileName = pathParts.pop();
|
const fileName = pathParts.pop();
|
||||||
|
|
||||||
let current = fileSystem['/'];
|
let current = fileSystem["/"];
|
||||||
for (const part of pathParts) {
|
for (const part of pathParts) {
|
||||||
if (current?.children && current.children[part] && current.children[part].type === 'directory') {
|
if (
|
||||||
|
current?.children &&
|
||||||
|
current.children[part] &&
|
||||||
|
current.children[part].type === "directory"
|
||||||
|
) {
|
||||||
current = current.children[part];
|
current = current.children[part];
|
||||||
} else {
|
} else {
|
||||||
return `cat: ${filePath}: No such file or directory`;
|
return `cat: ${filePath}: No such file or directory`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!fileName || !current?.children || !current.children[fileName]) {
|
if (!fileName || !current?.children || !current.children[fileName]) {
|
||||||
return `cat: ${filePath}: No such file or directory`;
|
return `cat: ${filePath}: No such file or directory`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const file = current.children[fileName];
|
const file = current.children[fileName];
|
||||||
if (file.type !== 'file') {
|
if (file.type !== "file") {
|
||||||
return `cat: ${filePath}: Is a directory`;
|
return `cat: ${filePath}: Is a directory`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return file.content || '';
|
return file.content || "";
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleTree(context: CommandContext): string {
|
function handleTree(context: CommandContext): string {
|
||||||
const { fileSystem } = context;
|
const { fileSystem } = context;
|
||||||
|
|
||||||
const buildTree = (node: FileSystemNode, prefix: string = '', isLast: boolean = true): string => {
|
const buildTree = (
|
||||||
let result = '';
|
node: FileSystemNode,
|
||||||
|
prefix: string = "",
|
||||||
|
isLast: boolean = true,
|
||||||
|
): string => {
|
||||||
|
let result = "";
|
||||||
if (!node.children) return result;
|
if (!node.children) return result;
|
||||||
|
|
||||||
const entries = Object.entries(node.children);
|
const entries = Object.entries(node.children);
|
||||||
entries.forEach(([name, child], index) => {
|
entries.forEach(([name, child], index) => {
|
||||||
const isLastChild = index === entries.length - 1;
|
const isLastChild = index === entries.length - 1;
|
||||||
const connector = isLastChild ? '└── ' : '├── ';
|
const connector = isLastChild ? "└── " : "├── ";
|
||||||
const color = child.type === 'directory' ? '\x1b[34m' : '\x1b[0m';
|
const color = child.type === "directory" ? "\x1b[34m" : "\x1b[0m";
|
||||||
const suffix = child.type === 'directory' ? '/' : '';
|
const suffix = child.type === "directory" ? "/" : "";
|
||||||
|
|
||||||
result += `${prefix}${connector}${color}${name}${suffix}\x1b[0m\n`;
|
result += `${prefix}${connector}${color}${name}${suffix}\x1b[0m\n`;
|
||||||
|
|
||||||
if (child.type === 'directory') {
|
if (child.type === "directory") {
|
||||||
const newPrefix = prefix + (isLastChild ? ' ' : '│ ');
|
const newPrefix = prefix + (isLastChild ? " " : "│ ");
|
||||||
result += buildTree(child, newPrefix, isLastChild);
|
result += buildTree(child, newPrefix, isLastChild);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
|
|
||||||
return '.\n' + buildTree(fileSystem['/']);
|
return ".\n" + buildTree(fileSystem["/"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleWhoami(): string {
|
function handleWhoami(): string {
|
||||||
return 'guest@atri.dad';
|
return "guest@atri.dad";
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleOpen(args: string[]): string {
|
function handleOpen(args: string[]): string {
|
||||||
const path = args[0];
|
const path = args[0];
|
||||||
if (!path) {
|
if (!path) {
|
||||||
return 'open: missing path argument';
|
return "open: missing path argument";
|
||||||
}
|
}
|
||||||
|
|
||||||
let url = '';
|
let url = "";
|
||||||
if (path === '/resume' || path.startsWith('/resume')) {
|
if (path === "/resume" || path.startsWith("/resume")) {
|
||||||
url = '/resume';
|
url = "/resume";
|
||||||
} else if (path === '/projects' || path.startsWith('/projects')) {
|
} else if (path === "/projects" || path.startsWith("/projects")) {
|
||||||
url = '/projects';
|
url = "/projects";
|
||||||
} else if (path === '/posts' || path.startsWith('/posts')) {
|
} else if (path === "/posts" || path.startsWith("/posts")) {
|
||||||
url = '/posts';
|
url = "/posts";
|
||||||
} else if (path === '/talks' || path.startsWith('/talks')) {
|
} else if (path === "/talks" || path.startsWith("/talks")) {
|
||||||
url = '/talks';
|
url = "/talks";
|
||||||
} else if (path === '/' || path === '/about.txt') {
|
} else if (path === "/" || path === "/about.txt") {
|
||||||
url = '/';
|
url = "/";
|
||||||
} else {
|
} else {
|
||||||
return `open: cannot open '${path}': No associated page`;
|
return `open: cannot open '${path}': No associated page`;
|
||||||
}
|
}
|
||||||
|
|
||||||
window.open(url, '_blank');
|
window.open(url, "_blank");
|
||||||
return `Opening ${url} in new tab...`;
|
return `Opening ${url} in new tab...`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleSl(context: CommandContext): string {
|
function handleSl(context: CommandContext): string {
|
||||||
const { setIsTrainRunning, setTrainPosition } = context;
|
const { setIsTrainRunning, setTrainPosition } = context;
|
||||||
|
|
||||||
setIsTrainRunning(true);
|
setIsTrainRunning(true);
|
||||||
setTrainPosition(100);
|
setTrainPosition(100);
|
||||||
|
|
||||||
const animateTrain = () => {
|
const animateTrain = () => {
|
||||||
let position = 100;
|
let position = 100;
|
||||||
const interval = setInterval(() => {
|
const interval = setInterval(() => {
|
||||||
position -= 1.5;
|
position -= 1.5;
|
||||||
setTrainPosition(position);
|
setTrainPosition(position);
|
||||||
|
|
||||||
if (position < -50) {
|
if (position < -50) {
|
||||||
clearInterval(interval);
|
clearInterval(interval);
|
||||||
setIsTrainRunning(false);
|
setIsTrainRunning(false);
|
||||||
}
|
}
|
||||||
}, 60);
|
}, 60);
|
||||||
};
|
};
|
||||||
|
|
||||||
setTimeout(animateTrain, 100);
|
setTimeout(animateTrain, 100);
|
||||||
return '';
|
return "";
|
||||||
}
|
}
|
@ -1,98 +1,108 @@
|
|||||||
import type { FileSystemNode } from './types';
|
import type { FileSystemNode } from "./types";
|
||||||
import { resolvePath } from './fileSystem';
|
import { resolvePath } from "./fs";
|
||||||
|
|
||||||
export function getCompletions(
|
export function getCompletions(
|
||||||
input: string,
|
input: string,
|
||||||
currentPath: string,
|
currentPath: string,
|
||||||
fileSystem: { [key: string]: FileSystemNode }
|
fileSystem: { [key: string]: FileSystemNode },
|
||||||
): { completion: string | null, replaceFrom: number } {
|
): { completion: string | null; replaceFrom: number } {
|
||||||
const parts = input.trim().split(' ');
|
const parts = input.trim().split(" ");
|
||||||
const command = parts[0];
|
const command = parts[0];
|
||||||
const partialPath = parts[parts.length - 1] || '';
|
const partialPath = parts[parts.length - 1] || "";
|
||||||
|
|
||||||
// Only complete paths for these commands
|
// Only complete paths for these commands
|
||||||
if (parts.length > 1 && ['ls', 'cd', 'cat', 'open'].includes(command)) {
|
if (parts.length > 1 && ["ls", "cd", "cat", "open"].includes(command)) {
|
||||||
// Path completion
|
// Path completion
|
||||||
const isAbsolute = partialPath.startsWith('/');
|
const isAbsolute = partialPath.startsWith("/");
|
||||||
const pathToComplete = isAbsolute ? partialPath : resolvePath(currentPath, partialPath);
|
const pathToComplete = isAbsolute
|
||||||
|
? partialPath
|
||||||
|
: resolvePath(currentPath, partialPath);
|
||||||
|
|
||||||
// Find the directory to search in and the prefix to match
|
// Find the directory to search in and the prefix to match
|
||||||
let dirPath: string;
|
let dirPath: string;
|
||||||
let searchPrefix: string;
|
let searchPrefix: string;
|
||||||
|
|
||||||
if (pathToComplete.endsWith('/')) {
|
if (pathToComplete.endsWith("/")) {
|
||||||
// Path ends with slash - complete inside this directory
|
// Path ends with slash - complete inside this directory
|
||||||
dirPath = pathToComplete;
|
dirPath = pathToComplete;
|
||||||
searchPrefix = '';
|
searchPrefix = "";
|
||||||
} else {
|
} else {
|
||||||
// Base case - find directory and prefix
|
// Base case - find directory and prefix
|
||||||
const lastSlash = pathToComplete.lastIndexOf('/');
|
const lastSlash = pathToComplete.lastIndexOf("/");
|
||||||
if (lastSlash >= 0) {
|
if (lastSlash >= 0) {
|
||||||
dirPath = pathToComplete.substring(0, lastSlash + 1);
|
dirPath = pathToComplete.substring(0, lastSlash + 1);
|
||||||
searchPrefix = pathToComplete.substring(lastSlash + 1);
|
searchPrefix = pathToComplete.substring(lastSlash + 1);
|
||||||
} else {
|
} else {
|
||||||
dirPath = currentPath.endsWith('/') ? currentPath : currentPath + '/';
|
dirPath = currentPath.endsWith("/") ? currentPath : currentPath + "/";
|
||||||
searchPrefix = pathToComplete;
|
searchPrefix = pathToComplete;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate where to start replacement in the original input
|
// Calculate where to start replacement in the original input
|
||||||
const spaceBeforeArg = input.lastIndexOf(' ');
|
const spaceBeforeArg = input.lastIndexOf(" ");
|
||||||
const replaceFrom = spaceBeforeArg >= 0 ? spaceBeforeArg + 1 : 0;
|
const replaceFrom = spaceBeforeArg >= 0 ? spaceBeforeArg + 1 : 0;
|
||||||
|
|
||||||
// Navigate to the directory
|
// Navigate to the directory
|
||||||
const dirParts = dirPath.split('/').filter((part: string) => part !== '');
|
const dirParts = dirPath.split("/").filter((part: string) => part !== "");
|
||||||
let current = fileSystem['/'];
|
let current = fileSystem["/"];
|
||||||
|
|
||||||
for (const part of dirParts) {
|
for (const part of dirParts) {
|
||||||
if (current?.children && current.children[part] && current.children[part].type === 'directory') {
|
if (
|
||||||
|
current?.children &&
|
||||||
|
current.children[part] &&
|
||||||
|
current.children[part].type === "directory"
|
||||||
|
) {
|
||||||
current = current.children[part];
|
current = current.children[part];
|
||||||
} else {
|
} else {
|
||||||
return { completion: null, replaceFrom };
|
return { completion: null, replaceFrom };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!current?.children) {
|
if (!current?.children) {
|
||||||
return { completion: null, replaceFrom };
|
return { completion: null, replaceFrom };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get first matching item
|
// Get first matching item
|
||||||
const match = Object.keys(current.children)
|
const match = Object.keys(current.children).find((name) =>
|
||||||
.find(name => name.startsWith(searchPrefix));
|
name.startsWith(searchPrefix),
|
||||||
|
);
|
||||||
|
|
||||||
if (match) {
|
if (match) {
|
||||||
const item = current.children[match];
|
const item = current.children[match];
|
||||||
const completion = item.type === 'directory' ? `${match}/` : match;
|
const completion = item.type === "directory" ? `${match}/` : match;
|
||||||
return { completion, replaceFrom };
|
return { completion, replaceFrom };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { completion: null, replaceFrom: input.length };
|
return { completion: null, replaceFrom: input.length };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatOutput(text: string): string {
|
export function formatOutput(text: string): string {
|
||||||
return text
|
return text
|
||||||
.replace(/\x1b\[34m/g, '<span class="text-primary">')
|
.replace(/\x1b\[34m/g, '<span class="text-primary">')
|
||||||
.replace(/\x1b\[0m/g, '</span>');
|
.replace(/\x1b\[0m/g, "</span>");
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveCommandToHistory(command: string, persistentHistory: string[]): string[] {
|
export function saveCommandToHistory(
|
||||||
|
command: string,
|
||||||
|
persistentHistory: string[],
|
||||||
|
): string[] {
|
||||||
if (command.trim()) {
|
if (command.trim()) {
|
||||||
const updatedHistory = [...persistentHistory, command].slice(-100); // Keep last 100 commands
|
const updatedHistory = [...persistentHistory, command].slice(-100); // Keep last 100 commands
|
||||||
localStorage.setItem('terminal-history', JSON.stringify(updatedHistory));
|
localStorage.setItem("terminal-history", JSON.stringify(updatedHistory));
|
||||||
return updatedHistory;
|
return updatedHistory;
|
||||||
}
|
}
|
||||||
return persistentHistory;
|
return persistentHistory;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function loadCommandHistory(): string[] {
|
export function loadCommandHistory(): string[] {
|
||||||
const savedHistory = localStorage.getItem('terminal-history');
|
const savedHistory = localStorage.getItem("terminal-history");
|
||||||
if (savedHistory) {
|
if (savedHistory) {
|
||||||
try {
|
try {
|
||||||
return JSON.parse(savedHistory);
|
return JSON.parse(savedHistory);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error loading command history:', error);
|
console.error("Error loading command history:", error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
Reference in New Issue
Block a user