refactor: reached same app state using vite

This commit is contained in:
Pihkaal
2024-01-28 15:56:19 +01:00
parent 8446ee6c65
commit 5542dce881
27 changed files with 805 additions and 207 deletions

View File

@@ -1,42 +0,0 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

View File

@@ -1,31 +1,39 @@
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import "./App.css";
import { MusicPlayer } from "./components/MusicPlayer";
import { MusicVisualizer } from "./components/MusicVisualizer";
import { Nvim } from "./components/Nvim/Nvim";
import { Terminal } from "./components/Terminal";
import { AppContextProvider } from "./context/AppContext";
function App() {
const [count, setCount] = useState(0);
return (
<>
<div>
<a href="https://vitejs.dev" target="_blank"></a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount(count => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.tsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</>
<AppContextProvider>
<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]"
}
>
<nav className="border border-red-500">toolbar</nav>
<Terminal className="flex-1">
<Nvim />
</Terminal>
<div className="flex gap-3">
<Terminal className="flex-1 select-none">
<MusicPlayer
title="Last Tango in Kyoto"
artist="Floating Bits"
album="Last Tango in Kyoto"
duration={93}
/>
</Terminal>
<Terminal className="flex-1">
<MusicVisualizer />
</Terminal>
</div>
</main>
</AppContextProvider>
);
}

View File

@@ -0,0 +1,85 @@
import { useTerminal } from "~/context/TerminalContext";
import { TerminalRenderer } from "~/utils/terminal/renderer";
import { TerminalBoxElement } from "~/utils/terminal/elements/box";
import { useEffect, useState } from "react";
const theme = {
black: "#45475a",
red: "#f38ba8",
green: "#a6e3a1",
yellow: "#f9e2af",
blue: "#89bafa",
magenta: "#f5c2e7",
cyan: "#94e2d5",
white: "#bac2de",
grey: "#585B70",
lightGrey: "#a6adc8",
};
const formatDurationMSS = (duration: number) => {
const minutes = Math.floor(duration / 60);
const seconds = duration % 60;
return `${minutes}:${seconds.toString().padStart(2, "0")}`;
};
export const MusicPlayer = (props: {
title: string;
artist: string;
album: string;
duration: number;
}) => {
const { cols } = useTerminal();
const canvas = new TerminalRenderer(cols, 5);
const [played, setPlayed] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setPlayed(x => Math.min(props.duration, x + 1));
}, 1000);
return () => clearInterval(interval);
}, [setPlayed, props.duration]);
canvas.writeElement(
new TerminalBoxElement(canvas.width, canvas.height),
0,
0,
);
canvas.write(1, 0, "Playback".substring(0, Math.min(8, canvas.width - 2)), {
foreground: theme.magenta,
});
const inner = new TerminalRenderer(canvas.width - 2, canvas.height - 2);
// Title and Artist
inner.write(2, 0, `${props.title} · ${props.artist}`, {
foreground: theme.cyan,
fontWeight: 700,
});
inner.apply(0, 0, {
char: "\udb81\udc0a",
foreground: theme.cyan,
fontWeight: 800,
});
// Album
inner.write(0, 1, props.album, { foreground: theme.yellow });
// Bar
inner.write(0, 2, " ".repeat(inner.width), {
foreground: theme.green,
background: "#55576d",
});
inner.write(0, 2, " ".repeat((inner.width * played) / props.duration), {
foreground: "#55576d",
background: theme.green,
});
const time = `${formatDurationMSS(played)}/${formatDurationMSS(
props.duration,
)}`;
inner.write(inner.width / 2 - time.length / 2, 2, time, { fontWeight: 800 });
canvas.writeElement(inner, 1, 1);
return <p>{canvas.render()}</p>;
};

View File

@@ -0,0 +1,5 @@
import { type FunctionComponent } from "react";
export const MusicVisualizer: FunctionComponent = () => (
<div className="h-full w-full bg-red-500"></div>
);

View File

@@ -0,0 +1,19 @@
import { NvimStatusBar } from "./NvimStatusBar";
import { NvimTree } from "./NvimTree";
export const Nvim = () => {
return (
<div>
<div className="flex">
<div className="w-fit">
<NvimTree />
</div>
<div className="flex-1"></div>
</div>
<div className="h-fit bg-[#29293c]">
<NvimStatusBar label="NORMAL" fileName="README.md" />
</div>
</div>
);
};

View File

@@ -0,0 +1,31 @@
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

@@ -0,0 +1,158 @@
import { useState, useEffect } from "react";
import { useApp } from "~/context/AppContext";
import { useTerminal } from "~/context/TerminalContext";
import { FILE_STYLES, type File } from "~/utils/filesystem";
import { type Cell } from "~/utils/terminal/cell";
import { TerminalRenderer } from "~/utils/terminal/renderer";
import { theme } from "~/utils/terminal/theme";
import { type Manifest } from "~/utils/types";
const PATH_FOLDED: Cell = {
char: "",
foreground: theme.grey,
};
const PATH_UNFOLDED: Cell = {
char: "",
foreground: theme.blue,
};
const buildFileTree = (manifest: Manifest): Array<File> => {
if (manifest === undefined) return [];
const files: Array<File> = [];
manifest.projects.forEach(project => {
if (project.name === "pihkaal") {
project.files.forEach(file => {
files.push({
name: file,
type: "md",
});
});
} else {
files.push({
name: project.name,
type: "directory",
folded: true,
children: project.files.map(file => ({
name: file,
type: "md",
})),
});
}
});
return files;
};
export const NvimTree = () => {
const manifest = useApp();
const [selected, setSelected] = useState(0);
const [files, setFiles] = useState(buildFileTree(manifest));
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 => {
tree.apply(2 + indent * 2, y, FILE_STYLES[file.type]);
if (file.type === "directory") {
tree.apply(indent * 2, y, file.folded ? PATH_FOLDED : PATH_UNFOLDED);
tree.write(4 + indent * 2, y, file.name, {
foreground: FILE_STYLES.directory.foreground,
});
y++;
if (!file.folded) {
indent++;
renderTree(file.children);
indent--;
}
} else {
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]);
}
break;
}
};
window.addEventListener("keydown", onScroll);
return () => {
window.removeEventListener("keydown", onScroll);
};
});
renderTree(files);
canvas.writeElement(tree, 2, 1);
return <p>{canvas.render()}</p>;
};
/*
.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,
),
*/

View File

@@ -0,0 +1,64 @@
import { useRef, useState, useEffect, type ReactNode } from "react";
import clsx from "clsx";
import { TerminalContextProvider } from "~/context/TerminalContext";
export const Terminal = (props: {
children?: ReactNode;
className?: string;
}) => {
const terminalRef = useRef<HTMLDivElement>(null);
const [size, setSize] = useState<{ cols: number; rows: number }>();
useEffect(() => {
const precision = 300;
const calculateSize = () => {
if (!terminalRef.current) return;
const node = document.createElement("span");
node.style.color = "transparent";
node.style.position = "absolute";
node.textContent = "A".repeat(precision);
terminalRef.current.appendChild(node);
setSize({
cols: Math.floor(
(terminalRef.current.offsetWidth - 4) /
(node.offsetWidth / precision),
),
rows: Math.floor(
(terminalRef.current.offsetHeight - 4) / node.offsetHeight,
),
});
node.remove();
};
calculateSize();
setTimeout(() => calculateSize(), 1);
window.addEventListener("resize", calculateSize);
return () => {
window.removeEventListener("resize", calculateSize);
};
}, []);
return (
<TerminalContextProvider value={size}>
<div
ref={terminalRef}
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)" }}
>
{size && props.children}
</div>
</TerminalContextProvider>
);
};

View File

@@ -0,0 +1,42 @@
/* 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";
const AppContext = createContext<Manifest | null>(null);
export const AppContextProvider = (props: {
children: Array<ReactNode> | ReactNode;
}) => {
const [manifest, setManifest] = useState<Manifest | null>(null);
useEffect(() => {
void axios
.get<Manifest>(
"https://raw.githubusercontent.com/pihkaal/pihkaal/main/manifest.json",
)
.then(x => {
setManifest(x.data);
console.log(x.data);
});
}, []);
return (
<AppContext.Provider value={manifest}>
{manifest && 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,16 @@
/* eslint-disable react-refresh/only-export-components */
import { createContext, useContext } from "react";
const TerminalContext = createContext<
{ cols: number; rows: number } | undefined
>(undefined);
export const TerminalContextProvider = TerminalContext.Provider;
export const useTerminal = () => {
const context = useContext(TerminalContext);
if (!context)
throw new Error("useTerminal must be used inside a Terminal component");
return context;
};

View File

@@ -1,68 +0,0 @@
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

48
src/index.scss Normal file
View File

@@ -0,0 +1,48 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
font-family: mono;
line-height: 1.5;
font-weight: 400;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
margin: 0;
}
@font-face {
font-family: "JetBrainsMono";
src:
url("/fonts/JetBrainsMonoNFM-Bold.woff2") format("woff2"),
url("/fonts/JetBrainsMonoNFM-Bold.woff") format("woff");
font-weight: bold;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "JetBrainsMono";
src:
url("/fonts/JetBrainsMonoNFM-Regular.woff2") format("woff2"),
url("/fonts/JetBrainsMonoNFM-Regular.woff") format("woff");
font-weight: normal;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "JetBrainsMono";
src:
url("/fonts/JetBrainsMonoNFM-Medium.woff2") format("woff2"),
url("/fonts/JetBrainsMonoNFM-Medium.woff") format("woff");
font-weight: 500;
font-style: normal;
font-display: swap;
}

View File

@@ -1,7 +1,7 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import "./index.scss";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>

32
src/utils/filesystem.ts Normal file
View File

@@ -0,0 +1,32 @@
import { type Cell } from "./terminal/cell";
import { theme } from "./terminal/theme";
export const FILE_STYLES = {
directory: {
char: "\ue6ad", // \ue6ad ||| \ueaf6
foreground: theme.blue,
},
md: {
char: "\ue73e",
foreground: theme.blue,
},
asc: {
char: "\uf43d",
foreground: theme.yellow,
},
} as const satisfies Record<string, Cell>;
export type FileType = keyof typeof FILE_STYLES;
export type File = {
name: string;
} & (
| {
type: Exclude<FileType, "directory">;
}
| {
type: "directory";
children: Array<File>;
folded: boolean;
}
);

7
src/utils/math.ts Normal file
View File

@@ -0,0 +1,7 @@
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 floorAll = (...xs: Array<number>): Array<number> =>
xs.map(Math.floor);

View File

@@ -0,0 +1,9 @@
export type Cell = {
char: string;
} & CellStyle;
export type CellStyle = Partial<{
foreground: string;
background: string;
fontWeight: number;
}>;

View File

@@ -0,0 +1,7 @@
import { type Cell } from "./cell";
export interface TerminalElement {
readonly data: Array<Array<Cell>>;
readonly width: number;
readonly height: number;
}

View File

@@ -0,0 +1,38 @@
import { type Cell, type CellStyle } from "../cell";
import { TerminalRenderer } from "../renderer";
import { type TerminalElement } from "../element";
export class TerminalBoxElement implements TerminalElement {
public readonly data: Array<Array<Cell>>;
constructor(
public readonly width: number,
public readonly height: number,
style: CellStyle = {},
) {
const canvas = new TerminalRenderer(width, height, style);
if (width == 1 && height > 1) {
for (let y = 0; y < height - 1; y++) {
canvas.write(0, y, "│");
}
} else if (height == 1 && width > 1) {
canvas.write(0, 0, "─".repeat(width - 2));
} else {
canvas.write(0, 0, "┌");
canvas.write(width - 1, 0, "┐");
canvas.write(0, height - 1, "└");
canvas.write(width - 1, height - 1, "┘");
canvas.write(1, 0, "─".repeat(width - 2));
canvas.write(1, height - 1, "─".repeat(width - 2));
for (let y = 1; y < height - 1; y++) {
canvas.write(0, y, "│");
canvas.write(width - 1, y, "│");
}
}
this.data = canvas.data;
}
}

View File

@@ -0,0 +1,124 @@
import { type ReactNode } from "react";
import { floorAll } from "../math";
import { type CellStyle, type Cell } from "./cell";
import { type TerminalElement } from "./element";
export class TerminalRenderer implements TerminalElement {
public readonly data: Array<Array<Cell>>;
constructor(
public readonly width: number,
public readonly height: number,
public readonly defaultStyle: CellStyle = {},
) {
[this.width, this.height] = floorAll(this.width, this.height);
this.data = new Array(this.height).fill(0).map(() =>
new Array<Cell>(this.width).fill({
char: " ",
...defaultStyle,
}),
);
}
apply(x: number, y: number, cell: Partial<Cell>): void {
[x, y] = floorAll(x, y);
if (x < 0 || x >= this.width || y < 0 || y >= this.height) return;
this.data[y][x] = {
...this.data[y][x],
...cell,
};
}
write(x: number, y: number, text: string, style: CellStyle = {}): void {
[x, y] = floorAll(x, y);
for (let i = 0; i < text.length; i++) {
this.apply(x + i, y, {
char: text[i],
...style,
});
}
}
writeFilter(
x: number,
y: number,
text: string,
filter: (cell: Cell) => Cell,
): void {
[x, y] = floorAll(x, y);
for (let i = 0; i < text.length; i++) {
this.apply(x + i, y, {
...filter(this.data[y][x + i]),
char: text[i],
});
}
}
writeElement(canvas: TerminalElement, dx: number, dy: number): void {
[dx, dy] = floorAll(dx, dy);
for (let y = 0; y < canvas.height; y++) {
for (let x = 0; x < canvas.width; x++) {
this.apply(dx + x, dy + y, canvas.data[y][x]);
}
}
}
subCanvas(
x: number,
y: number,
width: number,
height: number,
): TerminalRenderer {
[x, y, width, height] = floorAll(x, y, width, height);
const canvas = new TerminalRenderer(width, height);
for (let cy = 0; cy < height; cy++) {
for (let cx = 0; cx < width; cx++) {
canvas.apply(cx, cy, this.data[y + cy][x + cx]);
}
}
return canvas;
}
render(): Array<ReactNode> {
const nodes: Array<ReactNode> = [];
for (let y = 0; y < this.height; y++) {
for (let x = 0; x < this.width; x++) {
const cell = this.data[y][x];
/*
const span = document.createElement("span");
span.innerHTML = cell.char;
span.style.color = cell.foreground ?? "unset";
span.style.background = cell.background ?? "unset";
span.style.fontWeight = String(cell.fontWeight ?? "unset");
target.appendChild(span);
*/
nodes.push(
<span
key={`${x}-${y}`}
style={{
color: cell.foreground,
background: cell.background,
fontWeight: cell.fontWeight,
}}
>
{cell.char}
</span>,
);
}
nodes.push(<br key={y} />);
}
return nodes;
}
}

View File

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

6
src/utils/types.ts Normal file
View File

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