Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Shell-alike UI/UX #43

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
</head>
<body class="bg-solarized-base3 dark:bg-solarized-base03">
<body class="bg-neutral-800 font-mono text-neutral-300">
<div id="root" />
<script type="module" src="./src/main.tsx"></script>
</body>
Expand Down
144 changes: 92 additions & 52 deletions src/app/App.tsx
Original file line number Diff line number Diff line change
@@ -1,76 +1,116 @@
import { useEffect, useState } from "react";
import { getWorkingDirectory } from "../support/nana";
import { useEffect, useRef, useState } from "react";

import { Prompt } from "./Prompt";
import { IResult } from "./Result";

import { Card, ICard, CardPropTypes } from "./Card";
import { ansiFormat } from "../support/formatting";
import { getWorkingDirectory } from "../support/nana";
import { ResultList } from "./ResultList";

export default () => {
const promptRef = useRef<HTMLDivElement>(null);
const [history, setHistory] = useState<string[]>([]);
const [cards, setCards] = useState<ICard[]>([]);
const [activeHistoryIndex, setActiveHistoryIndex] = useState(-1);
const [input, setInput] = useState("");
const [results, setResults] = useState<IResult[]>([]);

const [workingDir, setWorkingDir] = useState("");

const resetActiveHistoryIndex = () => {
setActiveHistoryIndex(history.length);
};

// reset the active history index when the history changes
useEffect(resetActiveHistoryIndex, [history.length]);

// auto-scroll to the prompt whenever a new result is added/removed
useEffect(() => {
if (cards.length === 0) addEmptyCard();
}, [cards.length]);
promptRef.current?.scrollIntoView({ block: "start" });
}, [results.length]);

const addEmptyCard = async () => {
addCard({
workingDir: await getWorkingDirectory(),
});
// get working directory/bind global key presses on mount
useEffect(() => {
refreshWorkingDir();
window.addEventListener("keydown", handleGlobalKeyDown);
() => {
window.removeEventListener("keydown", handleGlobalKeyDown);
};
}, []);

const handleGlobalKeyDown = (e: KeyboardEvent) => {
if (e.ctrlKey && e.key == "l") {
// ctrl + l
e.preventDefault();
setResults([]);
}
};

const addCard = (props: CardPropTypes) => {
setCards((cards) => [...cards, { id: cards.length, ...props }]);
const refreshWorkingDir = async () => {
setWorkingDir(await getWorkingDirectory());
};

const addToHistory = (input?: string) => {
if (!input) return;
const handleResult = async (output: string, duration: number) => {
if (history.indexOf(input) === -1) {
setHistory((history) => [...history, input]);
setHistory((history) => [...history.slice(-25), input]);
}
};

const removeCard = (cardId: number) => {
setCards((cards) => cards.filter(({ id }) => id !== cardId));
setResults((results) => [
...results.slice(-10),
{
id: results.length,
workingDir,
input,
duration,
output: JSON.parse(output),
},
]);
refreshWorkingDir();
resetActiveHistoryIndex();
setInput("");
};

const updateCard = (cardId: number, props: CardPropTypes) => {
return setCards((cards) =>
cards.map((orig) => {
if (orig.id === cardId) {
return { ...orig, ...props };
}
return orig;
})
);
const handleError = async (output: string) => {
setResults((results) => [
...results,
{
id: results.length,
workingDir,
input,
output: ansiFormat(output),
},
]);
refreshWorkingDir();
setInput("");
};

const handleSubmit = async (
cardId: number,
props: CardPropTypes,
isError: boolean
) => {
const card = cards.find(({ id }) => id === cardId);
const alreadySubmitted = card && card.input !== undefined;
updateCard(cardId, props);
if (!isError && !alreadySubmitted) addEmptyCard();

addToHistory(props.input);
const handleHistory = (delta: number) => {
const index = activeHistoryIndex + delta;
if (index >= 0 && index < history.length) {
setInput(history[index]);
setActiveHistoryIndex(index);
}
};

return (
<main>
{cards.map((card) => (
<Card
key={card.id}
{...card}
history={history}
onClose={() => {
removeCard(card.id);
}}
onSubmit={(props: CardPropTypes, isError) => {
handleSubmit(card.id, props, isError);
}}
/>
))}
<main className="px-8 py-4 space-y-6">
<ResultList results={results} />

<Prompt
ref={promptRef}
input={input}
onSubmit={handleResult}
onSubmitError={handleError}
workingDir={workingDir}
onHistoryUp={() => {
handleHistory(1);
}}
onHistoryDown={() => {
handleHistory(-1);
}}
onChangeInput={(value) => {
setInput(value);
}}
/>
</main>
);
};
109 changes: 0 additions & 109 deletions src/app/Card.tsx

This file was deleted.

72 changes: 72 additions & 0 deletions src/app/CompletionList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import classNames from "classnames";
import { useEffect, useRef } from "react";

export type ICompletion = {
completion: string;
start: number;
};

const CompletionItem = ({
active,
completion,
...props
}: {
active: boolean;
completion: ICompletion;
}) => {
const ref = useRef<HTMLLIElement>(null);

useEffect(() => {
if (active) {
ref.current?.scrollIntoView({
block: "nearest",
// behavior: "smooth",
});
}
}, [active]);

return (
<li
{...props}
ref={ref}
className={classNames("scroll-mt-0 px-2 py-1", {
"bg-neutral-700": active,
})}
>
{completion.completion}
</li>
);
};

export const CompletionList = ({
completions,
activeIndex,
positionUp,
}: {
activeIndex: number;
completions: ICompletion[];
positionUp: boolean;
}) => {
const ref = useRef<HTMLUListElement>(null);

return (
<ul
ref={ref}
className={classNames(
"absolute left-0 z-50 max-h-64 divide-y divide-neutral-600 overflow-hidden overflow-y-auto rounded border border-neutral-600 bg-neutral-800 shadow",
{
"bottom-full": positionUp,
"top-full": !positionUp,
}
)}
>
{completions.map((completion, index) => (
<CompletionItem
key={completion.completion}
active={activeIndex === index}
completion={completion}
/>
))}
</ul>
);
};
Loading