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

@@ -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 }) => (
<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)" }}
>
<Terminal font="20px JetbrainsMono">{props.children}</Terminal>
</div>
);
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={
"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}
>
<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>;
};