feat(app): use components from nextjs branch

This commit is contained in:
Pihkaal
2024-05-30 15:16:52 +02:00
parent 4d1c3d958b
commit e21d337d53
24 changed files with 3078 additions and 2810 deletions

View File

@@ -15,7 +15,6 @@
"music-metadata-browser": "^2.5.10",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-dom-curse": "file:../react-dom-curse",
"react-router-dom": "^6.21.3",
"tailwind-merge": "^2.2.1",
"vite-tsconfig-paths": "^4.3.1",
@@ -49,5 +48,5 @@
"ct3aMetadata": {
"initVersion": "7.25.1"
},
"packageManager": "pnpm@8.14.1"
"packageManager": "pnpm@9.1.2"
}

4594
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

View File

@@ -1,38 +1,35 @@
import { BrowserRouter } from "react-router-dom";
import { Kitty } from "./components/Kitty";
import { AppContextProvider } from "./context/AppContext";
import { Waybar } from "./components/Waybar/Waybar";
import { useState } from "react";
import { Music } from "./components/Music/Music";
import { Kitty } from "./components/Kitty";
import { AppProvider } from "./context/AppContext";
import { Music } from "./components/Music";
// import { Nvim } from "./components/Nvim";
function App() {
const [clicked, setClicked] = useState(false);
export default function App() {
const [loggedIn, setLoggedIn] = useState(false);
return (
<AppContextProvider>
<BrowserRouter>
{clicked ? (
<main
className={
"insets-0 fixed flex h-screen w-screen flex-col gap-3 bg-[url(/wallpaper.jpg)] bg-cover p-3 font-body leading-[26px]"
}
>
<Waybar />
<AppProvider>
<main className="h-screen w-screen overflow-hidden bg-[url(/wallpaper.jpg)] bg-cover">
{loggedIn ? (
<div className="flex h-full w-full flex-col">
<Kitty className="w-full flex-1 pb-1 pl-2 pr-2 pt-2">
{/* <Nvim /> */}
</Kitty>
<Kitty className="flex-1"></Kitty>
<div className="flex h-[142px] gap-3">
<Music />{" "}
<Music />
</div>
</main>
) : (
<main className="flex h-screen items-center justify-center">
<button onClick={() => setClicked(true)}>Login</button>
</main>
<div className="flex h-full items-center justify-center">
<button
className="rounded-md border border-black px-2 py-1 hover:border-2 hover:font-bold"
onClick={() => setLoggedIn(true)}
>
Log in
</button>
</div>
)}
</BrowserRouter>
</AppContextProvider>
</main>
</AppProvider>
);
}
export default App;

View File

@@ -1,15 +1,97 @@
import { type ReactNode } from "react";
import clsx from "clsx";
import { Terminal } from "react-dom-curse";
import {
type ReactNode,
useEffect,
useRef,
useState,
useCallback,
useId,
} from "react";
import { KittyContext, type KittyContextProps } from "../context/KittyContext";
import { useApp } from "../context/AppContext";
export const Kitty = (props: { children?: ReactNode; className?: string }) => (
export const CHAR_WIDTH = 12;
export const CHAR_HEIGHT = 26;
const PADDING_RIGHT = CHAR_WIDTH / 2;
export const Kitty = (props: {
children?: ReactNode;
rows?: number;
cols?: number;
className?: string;
}) => {
const container = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState<`${number}px` | "auto">(
props.cols ? `${props.cols * CHAR_WIDTH}px` : "auto",
);
const [height, setHeight] = useState<`${number}px` | "auto">(
props.rows ? `${props.rows * CHAR_HEIGHT}px` : "auto",
);
const [context, setContext] = useState<KittyContextProps | undefined>(
undefined,
);
const id = useId();
const { activeKitty, setActiveKitty } = useApp();
const handleMouseEnter = useCallback(() => {
setActiveKitty(id);
}, [id, setActiveKitty]);
const snapToCharacter = useCallback(() => {
if (!container.current) return;
const cols = Math.round(
(container.current.clientWidth - PADDING_RIGHT) / CHAR_WIDTH,
);
const rows = Math.round(container.current.clientHeight / CHAR_HEIGHT);
const width = cols * CHAR_WIDTH;
const height = rows * CHAR_HEIGHT;
setWidth(`${width}px`);
setHeight(`${height}px`);
setContext((ctx) => ({ ...(ctx ?? { active: false }), rows, cols }));
}, []);
useEffect(() => {
if (!container.current) return;
snapToCharacter();
window.addEventListener("resize", snapToCharacter);
return () => {
window.removeEventListener("resize", snapToCharacter);
};
}, [snapToCharacter]);
return (
<div className={props.className} onMouseEnter={handleMouseEnter}>
<div
className={clsx(
"overflow-hidden whitespace-pre rounded-lg border-2 border-borderInactive bg-background bg-opacity-80 text-lg text-color7 text-foreground shadow-window transition-colors duration-[500ms] ease-out hover:border-borderActive hover:duration-[200ms]",
props.className,
)}
style={{ backdropFilter: "blur(2px)" }}
className={
"h-full w-full overflow-hidden rounded-lg border-2 border-borderInactive bg-background bg-opacity-80 px-[1px] text-lg text-color7 text-foreground shadow-window transition-colors duration-[500ms] ease-out"
}
style={{
lineHeight: `${CHAR_HEIGHT}px`,
...(activeKitty === id
? {
borderColor: "#cdd6f4",
animationDuration: "200ms",
}
: {}),
}}
ref={container}
>
<Terminal font="20px JetbrainsMono">{props.children}</Terminal>
<div
className="whitespace-pre"
style={{ backdropFilter: "blur(2px)", width, height }}
>
<KittyContext.Provider value={context}>
{props.children}
</KittyContext.Provider>
</div>
</div>
</div>
);
};

View File

@@ -1,46 +1,83 @@
import { Fragment, useRef, useEffect, useState } from "react";
import { ProgressBar, Group, useFrame, useTerminal } from "react-dom-curse";
import { theme } from "~/utils/theme";
import {
type RefObject,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { type InnerKittyProps, useKitty } from "../../context/KittyContext";
import { CHAR_WIDTH } from "../Kitty";
export const Cava = () => {
const { width } = useTerminal();
export const Cava = (props: { audio: RefObject<HTMLAudioElement> }) => {
const kitty = useKitty();
const audioContext = useRef(new AudioContext());
const analyser = useRef(audioContext.current.createAnalyser());
const bufferLength = useRef(analyser.current.frequencyBinCount);
const dataArray = useRef(new Uint8Array(bufferLength.current));
return (
<div
className="grid select-none text-[#b2b9d7]"
style={{
gap: `${CHAR_WIDTH}px`,
gridTemplateColumns: `repeat(auto-fill, ${CHAR_WIDTH * 2}px)`,
gridTemplateRows: `1fr`,
}}
>
{kitty && <InnerCava {...props} {...kitty} />}
</div>
);
};
const FrequencyBar = (props: {
value: number;
max: number;
height: number;
}) => {
const WIDTH = 2;
const GRADIENT = "▁▂▃▄▅▆▇█";
const FULL_BLOCK = "█";
const fraction = props.value / props.max;
const totalCharacters = props.height * GRADIENT.length;
const filledCharacters = fraction * totalCharacters;
const fullBlocksCount = Math.floor(filledCharacters / GRADIENT.length);
const remainderIndex = Math.floor(filledCharacters % GRADIENT.length);
let bar = "";
const emptyBlocksCount =
props.height - fullBlocksCount - (remainderIndex > 0 ? 1 : 0);
bar += `${" ".repeat(WIDTH)}\n`.repeat(Math.max(emptyBlocksCount, 0));
if (remainderIndex > 0) {
bar += `${GRADIENT[remainderIndex]!.repeat(WIDTH)}\n`;
}
bar += `${FULL_BLOCK.repeat(WIDTH)}\n`.repeat(fullBlocksCount);
return <span>{bar}</span>;
};
const InnerCava = (props: InnerKittyProps<typeof Cava>) => {
const sourceRef = useRef<MediaElementAudioSourceNode | null>(null);
const analyserRef = useRef<AnalyserNode | null>(null);
const audioContextRef = useRef<AudioContext | null>(null);
const [barHeights, setBarHeights] = useState(
new Array<number>(Math.round(width / 3)).fill(0),
new Array<number>(Math.round(props.cols / 3)).fill(0),
);
useEffect(() => {
const audioElement = document.querySelector("audio");
if (!audioElement) return;
const requestRef = useRef<number>();
const calculateBarHeights = useCallback(() => {
if (!analyserRef.current) return;
const audioSource =
audioContext.current.createMediaElementSource(audioElement);
audioSource.connect(analyser.current);
analyser.current.connect(audioContext.current.destination);
void audioElement.play();
const bufferLength = analyserRef.current.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
analyserRef.current.getByteFrequencyData(dataArray);
const analyzerElement = analyser.current;
return () => {
audioSource.disconnect();
analyzerElement.disconnect();
};
}, []);
useFrame(() => {
analyser.current.getByteFrequencyData(dataArray.current);
const barCount = Math.floor(width / 3);
const barCount = Math.round(props.cols / 3);
const newBarHeights = [];
for (let i = 0; i < barCount; i++) {
const startIndex = Math.floor((i / barCount) * bufferLength.current);
const endIndex = Math.floor(((i + 1) / barCount) * bufferLength.current);
const slice = dataArray.current.slice(startIndex, endIndex);
const startIndex = Math.floor((i / barCount) * bufferLength);
const endIndex = Math.floor(((i + 1) / barCount) * bufferLength);
const slice = dataArray.slice(startIndex, endIndex);
const sum = slice.reduce((acc, val) => acc + val, 0);
const average = sum / slice.length;
newBarHeights.push(average);
@@ -52,45 +89,46 @@ export const Cava = () => {
: barHeights;
const smoothedBarHeights = newBarHeights.map((height, i) => {
const smoothingFactor = 0.1;
const smoothingFactor = 1;
return (
stateBarHeights[i] + (height - stateBarHeights[i]) * smoothingFactor
stateBarHeights[i]! + (height - stateBarHeights[i]!) * smoothingFactor
);
});
setBarHeights(smoothedBarHeights);
});
return (
<Group
x={0}
y={0}
width={width}
height={5}
style={{ foreground: theme.white }}
>
{barHeights.map((height, x) => (
<Fragment key={x}>
<ProgressBar
x={x * 3}
y={4}
size={5}
min={0}
max={255}
value={height}
orientation="top"
/>
<ProgressBar
x={x * 3 + 1}
y={4}
size={5}
min={0}
max={255}
value={height}
orientation="top"
/>
</Fragment>
))}
</Group>
);
requestRef.current = requestAnimationFrame(calculateBarHeights);
}, [props.cols, barHeights]);
useEffect(() => {
const audioElement = props.audio.current;
if (!audioElement) return;
const audioContext = new AudioContext();
audioContextRef.current = audioContext;
const analyser = audioContext.createAnalyser();
analyser.fftSize = 256;
console.log("ok");
void audioElement.play().then(() => void audioContext.resume());
if (!sourceRef.current) {
const source = audioContext.createMediaElementSource(audioElement);
source.connect(analyser);
analyser.connect(audioContext.destination);
sourceRef.current = source;
analyserRef.current = analyser;
}
requestRef.current = requestAnimationFrame(calculateBarHeights);
return () => {
if (requestRef.current) cancelAnimationFrame(requestRef.current);
};
}, [props.cols, props.audio]);
return barHeights.map((value, i) => (
<FrequencyBar key={i} value={value} max={255 / 2} height={props.rows} />
));
};

View File

@@ -1,49 +0,0 @@
import { useEffect, useRef, useState } from "react";
import { parseBlob, type IAudioMetadata } from "music-metadata-browser";
import song from "/audio/colorful-flowers.mp3";
import { Kitty } from "../Kitty";
import { Cava } from "./Cava";
import { SpotifyPlayer } from "./SpotifyPlayer";
export const Music = () => {
const [metadata, setMetadata] = useState<IAudioMetadata>();
const [currentTime, setCurrentTime] = useState(0);
const audio = useRef<HTMLAudioElement>(null);
const handleTimeUpdate = () => {
setCurrentTime(audio.current?.currentTime ?? 0);
};
useEffect(() => {
if (metadata) return;
void fetch(song)
.then(r => r.blob())
.then(b => parseBlob(b))
.then(setMetadata);
}, [metadata]);
return (
<>
<audio ref={audio} src={song} onTimeUpdate={handleTimeUpdate} loop />
{metadata && audio.current && (
<>
<Kitty className="flex-1 select-none">
<SpotifyPlayer
title={metadata.common.title ?? "Unknown"}
artist={metadata.common.artist ?? "Unknown"}
album={metadata.common.album ?? "Unknown"}
played={currentTime}
duration={audio.current.duration}
/>
</Kitty>
<Kitty className="flex-1">
<Cava />
</Kitty>
</>
)}
</>
);
};

View File

@@ -1,79 +1,108 @@
import { useEffect } from "react";
import { Bar, Frame, Group, Text, useTerminal } from "react-dom-curse";
import { theme } from "~/utils/theme";
const formatDurationMSS = (duration: number) => {
duration = Math.floor(duration);
const minutes = Math.floor(duration / 60);
const seconds = duration % 60;
return `${minutes}:${seconds.toString().padStart(2, "0")}`;
};
import { useState } from "react";
import { formatMMSS } from "../../utils/time";
import { CharArray } from "../../utils/string";
import { CHAR_HEIGHT, CHAR_WIDTH } from "../Kitty";
import { type InnerKittyProps, useKitty } from "../../context/KittyContext";
export const SpotifyPlayer = (props: {
title: string;
artist: string;
album: string;
played: number;
duration: number;
played: number;
onTogglePause: (state: boolean) => void;
}) => {
const { width } = useTerminal();
const time = `${formatDurationMSS(props.played)}/${formatDurationMSS(
props.duration,
)}`;
const kitty = useKitty();
return (
<Group
x={0}
y={0}
width={width}
height={5}
style={{ foreground: theme.white }}
<div
className="grid select-none"
style={{
gridTemplateColumns: `${CHAR_WIDTH}px ${CHAR_WIDTH * 8}px 1fr ${CHAR_WIDTH}px`,
gridTemplateRows: `${CHAR_HEIGHT}px ${CHAR_HEIGHT * 3}px ${CHAR_HEIGHT}px`,
}}
>
<Frame x={0} y={0} width={width} height={5} border="single">
<Text x={0} y={0} style={{ foreground: theme.cyan, bold: true }}>
{props.title} · {props.artist}
</Text>
<Text x={0} y={1} style={{ foreground: theme.yellow }}>
{props.album}
</Text>
<Group x={0} y={2} width={width} height={1}>
<Bar
x={0}
y={0}
style={{
foreground: theme.green,
background: "#55576d",
bold: true,
}}
char=" "
size={width}
direction="right"
/>
<Bar
x={0}
y={0}
style={{
foreground: "#55576d",
background: theme.green,
bold: true,
}}
char=" "
size={width * (props.played / props.duration)}
direction="right"
/>
<Text x={Math.floor(width / 2 - time.length / 2 - 1)} y={0}>
{time}
</Text>
</Group>
</Frame>
<Text x={1} y={0} style={{ foreground: theme.magenta }}>
{"Playback".substring(0, Math.min(8, width - 2))}
</Text>
</Group>
{kitty && <InnerSpotifyPlayer {...props} {...kitty} />}
</div>
);
};
const InnerSpotifyPlayer = (props: InnerKittyProps<typeof SpotifyPlayer>) => {
const [paused, setPaused] = useState(false);
const fillSize = Math.round(
(props.played / props.duration) * (props.cols - 2),
);
const emptySize = props.cols - 2 - fillSize;
const timeString = `${formatMMSS(props.played)}/${formatMMSS(props.duration)}`;
const timeStringLeft = Math.round(
(props.cols - 2) / 2 - timeString.length / 2,
);
const fill = new CharArray(" ", fillSize)
.write(timeStringLeft, timeString)
.toString();
const empty = new CharArray(" ", emptySize)
.write(timeStringLeft - fillSize, timeString)
.toString();
const handleTogglePause = () => {
setPaused(!paused);
props.onTogglePause(!paused);
};
return (
<>
{/* title */}
<span
className="font-bold text-color5"
style={{ gridArea: "1 / 2 / 2 / 3" }}
>
Playback
</span>
{/* border right */}
<span style={{ gridArea: "1 / 4 / 2 / 5" }}></span>
<span style={{ gridArea: "2 / 4 / 3 / 4" }}>
{"│\n".repeat(props.rows - 2)}
</span>
<span style={{ gridArea: "3 / 4 / 4 / 5" }}></span>
{/* borer left */}
<span style={{ gridArea: "1 / 1 / 2 / 2" }}></span>
<span style={{ gridArea: "2 / 1 / 3 / 1" }}>
{"│\n".repeat(props.rows - 2)}
</span>
<span style={{ gridArea: "3 / 1 / 4 / 2" }}></span>
{/* border top */}
<span className="overflow-hidden" style={{ gridArea: "1 / 3 / 2 / 4" }}>
{"─".repeat(props.cols - 2 - 8)}
</span>
{/* border bottom */}
<span className="overflow-hidden" style={{ gridArea: "3 / 2 / 4 / 4" }}>
{"─".repeat(props.cols - 2)}
</span>
{/* body */}
<div className="overflow-hidden" style={{ gridArea: "2 / 2 / 3 / 4" }}>
<span className="font-bold text-color6">
<span onClick={handleTogglePause}>
{paused ? "\udb81\udc0a " : "\udb80\udfe4 "}
</span>
{props.title} · {props.artist}
</span>
<br />
<span className="text-color3">{props.album}</span>
<br />
<div className="relative font-bold">
<span className="bg-color2 text-color8">{fill}</span>
<span className="bg-color8 text-color2">{empty}</span>
</div>
<br />
</div>
</>
);
};

View File

@@ -0,0 +1,71 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { type IAudioMetadata, parseBlob } from "music-metadata-browser";
import { Kitty } from "../Kitty";
import { SpotifyPlayer } from "./SpotifyPlayer";
import { Cava } from "./Cava";
const song = "/audio/asinine-vivement-quoi.mp3";
export const Music = () => {
const audio = useRef<HTMLAudioElement>(null);
const [metadata, setMetadata] = useState<IAudioMetadata>();
const [currentTime, setCurrentTime] = useState(0);
const handleTimeUpdate = useCallback(() => {
setCurrentTime(audio.current?.currentTime ?? 0);
}, []);
const handleTogglePause = useCallback((paused: boolean) => {
if (!audio.current) return;
if (paused) {
void audio.current.pause();
} else {
void audio.current.play();
}
}, []);
useEffect(() => {
if (metadata) return;
void fetch(song)
.then((r) => r.blob())
.then((b) => parseBlob(b))
.then((m) => {
if (!audio.current) return;
setMetadata(m);
audio.current.volume = 0.01;
});
}, [metadata]);
return (
<div className="flex flex-row">
<audio ref={audio} src={song} onTimeUpdate={handleTimeUpdate} loop />
{audio.current && metadata ? (
<>
<Kitty className="h-full w-1/2 pb-2 pl-2 pr-1 pt-1" rows={5}>
<SpotifyPlayer
title={metadata.common.title ?? "Unknown"}
artist={metadata.common.artist ?? "Unknown"}
album={metadata.common.album ?? "Unknown"}
played={currentTime}
onTogglePause={handleTogglePause}
duration={audio.current.duration}
/>
</Kitty>
<Kitty className="h-full w-1/2 pb-2 pl-1 pr-2 pt-1" rows={5}>
<Cava audio={audio} />
</Kitty>
</>
) : (
<>
<Kitty className="h-full w-1/2 pb-2 pl-2 pr-1 pt-1" rows={5} />
<Kitty className="h-full w-1/2 pb-2 pl-1 pr-2 pt-1" rows={5} />
</>
)}
</div>
);
};

View File

@@ -1,76 +0,0 @@
import { useApp } from "~/context/AppContext";
import { NvimStatusBar } from "./NvimStatusBar";
import { NvimTree } from "./NvimTree";
import { buildFileTree } from "~/utils/filesystem";
import { useEffect, useState } from "react";
import axios from "axios";
import { useLocation, useNavigate } from "react-router-dom";
import { NvimEditor } from "./NvimEditor";
const fetchData = async (
branch: string,
repo: string,
file: string,
): Promise<string | null> => {
return `Displaying ${repo}/${file} on branch ${branch}`;
try {
const response = await axios.get<string>(
`https://raw.githubusercontent.com/pihkaal/${repo}/${branch}/${file}`,
);
return response.data;
} catch {
return null;
}
};
export const Nvim = () => {
const manifest = useApp();
const [data, setData] = useState<string | null>(null);
const location = useLocation();
const navigate = useNavigate();
useEffect(() => {
const params = new URLSearchParams(location.search);
const view = params.get("view");
if (!view) {
navigate("?view=README.md");
return;
}
const path = view.split("/");
if (path.length === 1) {
path.splice(0, 0, "pihkaal");
}
const repo = path[0]!;
const file = path[1]!;
void (async () => {
const data =
(await fetchData("main", repo, file)) ??
(await fetchData("dev", repo, file));
if (!data) {
navigate("?view=README.md");
return;
}
setData(data);
})();
}, [location, navigate]);
return (
<div className="flex flex-col">
<div className="flex flex-1 flex-row">
<div className="w-fit">
<NvimTree files={buildFileTree(manifest)} />
</div>
<div className="flex-1">
<NvimEditor content={data} />
</div>
</div>
<div className="h-fit bg-[#29293c]">
<NvimStatusBar label="NORMAL" fileName="README.md" />
</div>
</div>
);
};

View File

@@ -1,16 +0,0 @@
import { useTerminal } from "~/context/TerminalContext";
import { TerminalRenderer } from "~/utils/terminal/renderer";
export const NvimEditor = (props: { content: string | null }) => {
const { cols: width, rows: height } = useTerminal();
const canvas = new TerminalRenderer(width * 0.8, height - 2);
if (props.content) {
props.content.split("\n").forEach((line, y) => {
canvas.write(0, y, line);
});
}
return canvas.render();
};

View File

@@ -1,31 +0,0 @@
import { useTerminal } from "~/context/TerminalContext";
import { TerminalRenderer } from "~/utils/terminal/renderer";
import { theme } from "~/utils/terminal/theme";
export const NvimStatusBar = (props: { label: string; fileName: string }) => {
const { cols: width } = useTerminal();
const canvas = new TerminalRenderer(width, 1);
canvas.write(0, 0, ` ${props.label} `, {
background: theme.blue,
foreground: "#000",
});
canvas.write(props.label.length + 2, 0, "\ue0ba", {
background: theme.blue,
foreground: "#474353",
});
canvas.write(props.label.length + 3, 0, "\ue0ba", {
background: "#474353",
foreground: "#373040",
});
canvas.write(props.label.length + 4, 0, ` ${props.fileName} `, {
background: "#373040",
foreground: theme.white,
});
canvas.write(props.label.length + 6 + props.fileName.length, 0, "\ue0ba", {
background: "#373040",
foreground: "#29293c",
});
return <p>{canvas.render()}</p>;
};

View File

@@ -1,133 +0,0 @@
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useTerminal } from "~/context/TerminalContext";
import {
DEFAULT_FILE_STYLE,
FILE_STYLES,
getExtension,
type File,
} from "~/utils/filesystem";
import { type Cell } from "~/utils/terminal/cell";
import { TerminalRenderer } from "~/utils/terminal/renderer";
import { theme } from "~/utils/terminal/theme";
const PATH_FOLDED: Cell = {
char: "",
foreground: theme.grey,
};
const PATH_UNFOLDED: Cell = {
char: "",
foreground: theme.blue,
};
export const NvimTree = (props: { files: Array<File> }) => {
const [selected, setSelected] = useState(0);
const [files, setFiles] = useState(props.files);
const navigate = useNavigate();
const { cols: width, rows: height } = useTerminal();
const canvas = new TerminalRenderer(width * 0.2, height - 2, {
background: "#0000001a",
});
const tree = new TerminalRenderer(canvas.width - 3, height - 1);
tree.write(0, selected, " ".repeat(tree.width), { background: "#504651" });
let y = 0;
let indent = 0;
const renderTree = (files: Array<File>) => {
files.forEach(file => {
if (file.type === "directory") {
tree.apply(2 + indent * 2, y, {
char: file.folded ? "\ue6ad" : "\ueaf6",
foreground: theme.blue,
});
tree.apply(indent * 2, y, file.folded ? PATH_FOLDED : PATH_UNFOLDED);
tree.write(4 + indent * 2, y, file.name, {
foreground: theme.blue,
});
y++;
if (!file.folded) {
indent++;
renderTree(file.children);
indent--;
}
} else {
const style =
FILE_STYLES[getExtension(file.name)] ?? DEFAULT_FILE_STYLE;
tree.apply(2 + indent * 2, y, style);
if (file.name === "README.md") {
tree.write(4 + indent * 2, y, file.name, {
foreground: theme.yellow,
fontWeight: 800,
});
} else {
tree.write(4 + indent * 2, y, file.name);
}
y++;
}
});
};
useEffect(() => {
const onScroll = (event: KeyboardEvent) => {
switch (event.key) {
case "ArrowUp":
setSelected(x => Math.max(0, x - 1));
break;
case "ArrowDown":
setSelected(x => Math.min(y - 1, x + 1));
break;
case "Enter":
let y = 0;
const findFile = (files: Array<File>): File | null => {
for (const f of files) {
if (y === selected) {
return f;
}
y++;
if (f.type === "directory" && !f.folded) {
const found = findFile(f.children);
if (found) return found;
}
}
return null;
};
const current = findFile(files);
if (!current) {
setSelected(0);
return;
}
if (current.type === "directory") {
current.folded = !current.folded;
setFiles([...files]);
} else {
//document.location.href = `?view=${current.path}`
navigate(`?view=${current.path}`);
}
break;
}
};
window.addEventListener("keydown", onScroll);
return () => {
window.removeEventListener("keydown", onScroll);
};
});
renderTree(files);
canvas.writeElement(tree, 2, 1);
return <p>{canvas.render()}</p>;
};

View File

@@ -1,54 +1,22 @@
/* eslint-disable react-refresh/only-export-components */
import {
createContext,
useEffect,
useContext,
useState,
type ReactNode,
} from "react";
import axios from "axios";
import { type Manifest } from "~/utils/types";
import { type ReactNode, createContext, useContext, useState } from "react";
const AppContext = createContext<Manifest | null>(null);
export const AppContext = createContext<
{ activeKitty: string; setActiveKitty: (value: string) => void } | undefined
>(undefined);
export const AppContextProvider = (props: {
children: Array<ReactNode> | ReactNode;
}) => {
const [manifest, setManifest] = useState<Manifest | null>({
projects: [
{
name: "tlock",
files: ["README.md"],
},
{
name: "pihkaal",
files: ["README.md", "pubkey.asc"],
},
],
});
export const useApp = () => {
const app = useContext(AppContext);
if (!app) throw new Error("`useApp` used outside AppContext");
useEffect(() => {
return;
void axios
.get<Manifest>(
"https://raw.githubusercontent.com/pihkaal/pihkaal/main/manifest.json",
)
.then(x => {
setManifest(x.data);
console.log(x.data);
});
}, []);
return app;
};
export const AppProvider = (props: { children?: ReactNode }) => {
const [activeKitty, setActiveKitty] = useState(":r0:");
return (
<AppContext.Provider value={manifest}>
{manifest && props.children}
<AppContext.Provider value={{ activeKitty, setActiveKitty }}>
{props.children}
</AppContext.Provider>
);
};
export const useApp = () => {
const context = useContext(AppContext);
if (!context) throw new Error("useApp must be used inside the app lol");
return context;
};

View File

@@ -0,0 +1,20 @@
import { createContext, useContext } from "react";
export const KittyContext = createContext<KittyContextProps | undefined>(
undefined,
);
export const useKitty = () => useContext(KittyContext);
export type KittyContextProps = {
rows: number;
cols: number;
active: boolean;
};
type Prettify<T> = NonNullable<{ [K in keyof T]: T[K] }>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type InnerKittyProps<T extends (...args: any[]) => any> = Prettify<
Parameters<T>[0] & KittyContextProps
>;

View File

@@ -15,6 +15,7 @@
body {
margin: 0;
font-family: "JetBrainsMono";
}
@font-face {

View File

@@ -1,80 +0,0 @@
import { type Cell } from "./terminal/cell";
import { theme } from "./terminal/theme";
import { type Manifest } from "./types";
export const getExtension = (path: string) => {
const parts = path.split(".");
return parts[Math.max(0, parts.length - 1)] ?? "";
};
export const DEFAULT_FILE_STYLE: Cell = {
char: "F",
foreground: theme.white,
};
export const FILE_STYLES: Record<string, Cell> = {
md: {
char: "\ue73e",
foreground: theme.blue,
},
asc: {
char: "\uf43d",
foreground: theme.yellow,
},
};
export type File = {
name: string;
path: string;
} & (
| {
type: "file";
}
| {
type: "directory";
children: Array<File>;
folded: boolean;
}
);
const sortFiles = (files: Array<File>) =>
files
.sort((a, b) => a.name.localeCompare(b.name))
.sort((a, b) =>
a.type === "directory" && b.type !== "directory"
? -1
: a.type !== "directory" && b.type === "directory"
? 1
: 0,
);
export const buildFileTree = (manifest: Manifest): Array<File> => {
const files: Array<File> = [];
manifest.projects.forEach(project => {
if (project.name === "pihkaal") {
project.files.forEach(file => {
files.push({
name: file,
path: file,
type: "file",
});
});
} else {
files.push({
name: project.name,
path: project.name,
type: "directory",
folded: true,
children: sortFiles(
project.files.map(file => ({
name: file,
path: `${project.name}/${file}`,
type: "file",
})),
),
});
}
});
return sortFiles(files);
};

View File

@@ -1,17 +0,0 @@
export const clamp = (v: number, min: number, max: number): number =>
Math.min(Math.max(min, v), max);
export const clamp01 = (v: number): number => clamp(v, 0, 1);
export const clamp0 = (v: number): number => clamp(v, 0, v);
export const floorAll = (...xs: Array<number>): Array<number> =>
xs.map(Math.floor);
/**
* Random int in [min, max[
*/
export const randomMinMax = (min: number, max: number): number =>
Math.round(Math.random() * (max - min - 1) + min);
export const randomSign = (): number => Math.sign(randomMinMax(0, 2) - 1);

View File

@@ -1,4 +0,0 @@
import clsx, { type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export const cn = (...values: Array<ClassValue>) => twMerge(clsx(...values));

26
src/utils/string.ts Normal file
View File

@@ -0,0 +1,26 @@
export class CharArray {
private readonly chars: string[];
constructor(fill: string, size: number) {
this.chars = fill.repeat(size).split("");
}
set(i: number, char: string | undefined) {
if (char === undefined || i < 0 || i >= this.chars.length) return;
this.chars[i] = char;
return this;
}
write(i: number, str: string) {
for (let oi = 0; oi < str.length; oi++) {
this.set(i + oi, str[oi]);
}
return this;
}
toString() {
return this.chars.join("");
}
}

View File

@@ -1,12 +0,0 @@
export const theme = {
black: "#45475a",
red: "#f38ba8",
green: "#a6e3a1",
yellow: "#f9e2af",
blue: "#89bafa",
magenta: "#f5c2e7",
cyan: "#94e2d5",
white: "#bac2de",
grey: "#585B70",
lightGrey: "#a6adc8",
};

9
src/utils/time.ts Normal file
View File

@@ -0,0 +1,9 @@
export const formatMMSS = (time: number) => {
const minutes = Math.floor(time / 60);
const seconds = Math.floor(time % 60);
const minutesString = minutes.toString().padStart(2, "0");
const secondsString = seconds.toString().padStart(2, "0");
return `${minutesString}:${secondsString}`;
};

View File

@@ -1,6 +0,0 @@
export type Manifest = {
projects: Array<{
name: string;
files: Array<string>;
}>;
};