path selecting element

This commit is contained in:
2025-07-22 13:55:15 -06:00
parent 01d137efcf
commit 67b67100c1
12 changed files with 338 additions and 54 deletions

View File

@@ -1,4 +1,5 @@
"use client";
import ButtonSelect from "@/components/ButtonSelect";
import { DayOfWeekInput } from "@/components/form/DayOfWeekInput";
import SelectInput from "@/components/form/SelectInput";
import { Spinner } from "@/components/Spinner";
@@ -37,7 +38,7 @@ const sampleCompose = `services:
- ~/projects/faculty/4850_AdvancedFE/2024-fall-alex/modules:/app/storage/advanced_frontend
`;
export default function NewCourseForm() {
export default function AddNewCourseToGlobalSettingsForm() {
const router = useRouter();
const today = useMemo(() => new Date(), []);
const { data: canvasTerms } = useCanvasTermsQuery(today);
@@ -61,12 +62,13 @@ export default function NewCourseForm() {
return (
<div>
<SelectInput
value={selectedTerm}
setValue={setSelectedTerm}
label={"Canvas Term"}
<ButtonSelect
options={canvasTerms}
getOptionName={(t) => t.name}
getOptionName={(t) => t?.name ?? ""}
setValue={setSelectedTerm}
value={selectedTerm}
label={"Canvas Term"}
center={true}
/>
<SuspenseAndErrorHandling>
{selectedTerm && (
@@ -184,12 +186,13 @@ function OtherSettings({
return (
<>
<SelectInput
<ButtonSelect
value={selectedCanvasCourse}
setValue={setSelectedCanvasCourse}
label={"Course"}
options={availableCourses}
getOptionName={(c) => c.name}
getOptionName={(c) => c?.name ?? ""}
center={true}
/>
<SelectInput
value={selectedDirectory}

View File

@@ -0,0 +1,40 @@
"use client";
import ClientOnly from "@/components/ClientOnly";
import { StoragePathSelector } from "@/components/form/StoragePathSelector";
import { SuspenseAndErrorHandling } from "@/components/SuspenseAndErrorHandling";
import { FC, useState } from "react";
export const AddExistingCourseToGlobalSettings = () => {
const [showForm, setShowForm] = useState(false);
return (
<div>
<div className="flex justify-center">
<button className="" onClick={() => setShowForm((i) => !i)}>
Add Existing Course
</button>
</div>
<div className={" collapsible " + (showForm && "expand")}>
<div className="border rounded-md p-3 m-3">
<SuspenseAndErrorHandling>
<ClientOnly>{showForm && <ExistingCourseForm />}</ClientOnly>
</SuspenseAndErrorHandling>
</div>
</div>
</div>
);
};
const ExistingCourseForm: FC<{}> = () => {
const [path, setPath] = useState("./");
return (
<div>
<h2>Add Existing Course</h2>
<StoragePathSelector
startingValue={path}
submitValue={setPath}
label={"Course Directory Path"}
/>
</div>
);
};

View File

@@ -1,16 +1,16 @@
"use client";
import React, { useState } from "react";
import { SuspenseAndErrorHandling } from "@/components/SuspenseAndErrorHandling";
import NewCourseForm from "./NewCourseForm";
import AddNewCourseToGlobalSettingsForm from "./AddCourseToGlobalSettingsForm";
import ClientOnly from "@/components/ClientOnly";
export default function AddNewCourse() {
export default function AddCourseToGlobalSettings() {
const [showForm, setShowForm] = useState(false);
return (
<div>
<div className="flex justify-center">
<button className="" onClick={() => setShowForm(true)}>
<button className="" onClick={() => setShowForm((i) => !i)}>
Add New Course
</button>
</div>
@@ -18,7 +18,9 @@ export default function AddNewCourse() {
<div className={" collapsible " + (showForm && "expand")}>
<div className="border rounded-md p-3 m-3">
<SuspenseAndErrorHandling>
<ClientOnly>{showForm && <NewCourseForm />}</ClientOnly>
<ClientOnly>
{showForm && <AddNewCourseToGlobalSettingsForm />}
</ClientOnly>
</SuspenseAndErrorHandling>
</div>
</div>

View File

@@ -153,9 +153,9 @@ export default function NewItemForm({
<div>
<ButtonSelect<"Assignment" | "Quiz" | "Page">
options={["Assignment", "Quiz", "Page"]}
getName={(o) => o?.toString() ?? ""}
setSelectedOption={(t) => setType(t ?? "Assignment")}
selectedOption={type}
getOptionName={(o) => o?.toString() ?? ""}
setValue={(t) => setType(t ?? "Assignment")}
value={type}
label="Type"
/>
</div>
@@ -166,9 +166,9 @@ export default function NewItemForm({
{type !== "Page" && (
<ButtonSelect
options={settings.assignmentGroups}
getName={(g) => g?.name ?? ""}
setSelectedOption={setAssignmentGroup}
selectedOption={assignmentGroup}
getOptionName={(g) => g?.name ?? ""}
setValue={setAssignmentGroup}
value={assignmentGroup}
label="Assignment Group"
/>
)}

View File

@@ -1,5 +1,6 @@
import CourseList from "./CourseList";
import AddNewCourse from "./newCourse/AddNewCourse";
import { AddExistingCourseToGlobalSettings } from "./addCourse/AddExistingCourseToGlobalSettings";
import AddCourseToGlobalSettings from "./addCourse/AddNewCourse";
import TodaysLectures from "./todaysLectures/TodaysLectures";
export default async function Home() {
@@ -18,7 +19,36 @@ export default async function Home() {
<TodaysLectures />
<br />
<br />
<AddNewCourse />
<AddCourseToGlobalSettings />
<AddExistingCourseToGlobalSettings />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
</div>
</main>
);

View File

@@ -2,34 +2,41 @@ import React from "react";
export default function ButtonSelect<T>({
options,
getName,
setSelectedOption,
selectedOption,
label
getOptionName,
setValue,
value,
label,
center = false,
}: {
options: T[];
getName: (value: T | undefined) => string;
setSelectedOption: (value: T | undefined) => void;
selectedOption: T | undefined;
getOptionName: (value: T | undefined) => string;
setValue: (value: T | undefined) => void;
value: T | undefined;
label: string;
center?: boolean;
}) {
return (
<div>
<div className={center ? "text-center" : ""}>
<label>{label}</label>
<div className="flex flex-row gap-3 flex-wrap">
{options.map((o) => (
<button
type="button"
key={getName(o)}
<div
className={
getName(o) === getName(selectedOption) ? " " : "unstyled btn-outline"
"flex flex-row gap-3 flex-wrap " + (center ? "justify-center" : "")
}
onClick={() => setSelectedOption(o)}
>
{getName(o)}
</button>
))}
>
{options.map((o) => (
<button
type="button"
key={getOptionName(o)}
className={
getOptionName(o) === getOptionName(value)
? " "
: "unstyled btn-outline"
}
onClick={() => setValue(o)}
>
{getOptionName(o)}
</button>
))}
</div>
</div>
);

View File

@@ -0,0 +1,165 @@
import { useDirectoryContentsQuery } from "@/hooks/localCourse/storageDirectoryHooks";
import { useState, useRef, useEffect } from "react";
import { createPortal } from "react-dom";
export function StoragePathSelector({
startingValue,
submitValue,
label,
className,
}: {
startingValue: string;
submitValue: (newValue: string) => void;
label: string;
className?: string;
}) {
const [path, setPath] = useState(startingValue);
const [lastCorrectPath, setLastCorrectPath] = useState(startingValue);
const { data: directoryContents } =
useDirectoryContentsQuery(lastCorrectPath);
const [isFocused, setIsFocused] = useState(false);
const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);
const [arrowUsed, setArrowUsed] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (!isFocused || filteredFolders.length === 0) return;
if (e.key === "ArrowDown") {
setHighlightedIndex((prev) => (prev + 1) % filteredFolders.length);
setArrowUsed(true);
e.preventDefault();
} else if (e.key === "ArrowUp") {
setHighlightedIndex(
(prev) => (prev - 1 + filteredFolders.length) % filteredFolders.length
);
setArrowUsed(true);
e.preventDefault();
} else if (e.key === "Tab") {
if (highlightedIndex >= 0) {
handleSelectFolder(filteredFolders[highlightedIndex], arrowUsed);
e.preventDefault();
} else {
handleSelectFolder(filteredFolders[1], arrowUsed);
e.preventDefault();
}
} else if (e.key === "Enter") {
if (highlightedIndex >= 0) {
handleSelectFolder(filteredFolders[highlightedIndex], arrowUsed);
e.preventDefault();
} else {
setIsFocused(false);
inputRef.current?.blur();
e.preventDefault();
}
} else if (e.key === "Escape") {
setIsFocused(false);
inputRef.current?.blur();
e.preventDefault();
}
};
// Calculate dropdown position style
const dropdownPositionStyle = (() => {
if (inputRef.current) {
const rect = inputRef.current.getBoundingClientRect();
return {
top: rect.bottom + window.scrollY,
left: rect.left + window.scrollX,
width: rect.width,
};
}
return {};
})();
// Get last part of the path
const lastPart = path.split("/")[path.split("/").length - 1] || "";
// Filter options to those whose name matches the last part of the path
const filteredFolders = (directoryContents?.folders ?? []).filter((option) =>
option.toLowerCase().includes(lastPart.toLowerCase())
);
// Handle folder selection
const handleSelectFolder = (option: string, shouldFocus: boolean = false) => {
let newPath = path.endsWith("/")
? path + option
: path.replace(/[^/]*$/, option);
if (!newPath.endsWith("/")) {
newPath += "/";
}
setPath(newPath);
setLastCorrectPath(newPath);
setArrowUsed(false);
setHighlightedIndex(-1);
if (shouldFocus) {
setTimeout(() => inputRef.current?.focus(), 0);
}
submitValue(newPath);
};
// Scroll highlighted option into view when it changes
useEffect(() => {
if (dropdownRef.current && highlightedIndex >= 0) {
const optionElements =
dropdownRef.current.querySelectorAll(".dropdown-option");
if (optionElements[highlightedIndex]) {
(optionElements[highlightedIndex] as HTMLElement).scrollIntoView({
block: "nearest",
});
}
}
}, [highlightedIndex]);
return (
<label className={"flex flex-col relative " + className}>
{label}
<br />
<input
ref={inputRef}
className="bg-slate-800 border border-slate-500 rounded-md w-full px-1"
value={path}
onChange={(e) => {
setPath(e.target.value);
if (e.target.value.endsWith("/")) {
setLastCorrectPath(e.target.value);
setTimeout(() => inputRef.current?.focus(), 0);
}
}}
onFocus={() => setIsFocused(true)}
onBlur={() => setTimeout(() => setIsFocused(false), 100)}
onKeyDown={handleKeyDown}
autoComplete="off"
/>
<div className="text-xs text-slate-400 mt-1">
Last valid path: {lastCorrectPath}
</div>
{isFocused &&
createPortal(
<div className=" ">
<div
ref={dropdownRef}
className={
" text-slate-300 border border-slate-500 " +
"absolute bg-slate-900 rounded-md mt-1 w-full max-h-96 overflow-y-auto pointer-events-auto"
}
style={dropdownPositionStyle}
>
{filteredFolders.map((option, idx) => (
<div
key={option}
className={`dropdown-option w-full px-2 py-1 cursor-pointer ${
highlightedIndex === idx ? "bg-blue-700 text-white" : ""
}`}
onMouseDown={() => handleSelectFolder(option)}
onMouseEnter={() => setHighlightedIndex(idx)}
>
{option}
</div>
))}
</div>
</div>,
document.body
)}
</label>
);
}

View File

@@ -1,5 +1,5 @@
import { useTRPC } from "@/services/serverFunctions/trpcClient";
import { useSuspenseQuery } from "@tanstack/react-query";
import { useQuery, useSuspenseQuery } from "@tanstack/react-query";
export const directoryKeys = {
emptyFolders: ["empty folders"] as const,
@@ -9,3 +9,10 @@ export const useEmptyDirectoriesQuery = () => {
const trpc = useTRPC();
return useSuspenseQuery(trpc.directories.getEmptyDirectories.queryOptions());
};
export const useDirectoryContentsQuery = (relativePath: string) => {
const trpc = useTRPC();
return useQuery(
trpc.directories.getDirectoryContents.queryOptions({ relativePath })
);
};

View File

@@ -52,4 +52,25 @@ export const fileStorageService = {
await fs.mkdir(courseDirectory, { recursive: true });
},
async getDirectoryContents(
relativePath: string
): Promise<{ files: string[]; folders: string[] }> {
const fullPath = path.join(basePath, relativePath);
if (!(await directoryOrFileExists(fullPath))) {
throw new Error(`Directory ${fullPath} does not exist`);
}
const contents = await fs.readdir(fullPath, { withFileTypes: true });
const files: string[] = [];
const folders: string[] = [];
for (const dirent of contents) {
if (dirent.isDirectory()) {
folders.push(dirent.name);
} else if (dirent.isFile()) {
files.push(dirent.name);
}
}
return { files, folders };
},
};

View File

@@ -1,3 +1,4 @@
import z from "zod";
import publicProcedure from "../procedures/public";
import { router } from "../trpcSetup";
import { fileStorageService } from "@/services/fileStorage/fileStorageService";
@@ -6,4 +7,13 @@ export const directoriesRouter = router({
getEmptyDirectories: publicProcedure.query(async () => {
return await fileStorageService.getEmptyDirectories();
}),
getDirectoryContents: publicProcedure
.input(
z.object({
relativePath: z.string(),
})
)
.query(async ({ input: { relativePath } }) => {
return await fileStorageService.getDirectoryContents(relativePath);
}),
});