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

@@ -17,16 +17,17 @@ services:
volumes: volumes:
- ./globalSettings.yml:/app/globalSettings.yml - ./globalSettings.yml:/app/globalSettings.yml
- .:/app - .:/app
- ~/projects/faculty/1810/2025-spring-alex/in-person:/app/storage/intro_to_web_old - ~/projects/faculty:/app/storage
- ~/projects/faculty/1810/2025-fall-alex/modules:/app/storage/intro_to_web # - ~/projects/faculty/1810/2025-spring-alex/in-person:/app/storage/intro_to_web_old
- ~/projects/faculty/4850_AdvancedFE/2025-fall-alex/modules:/app/storage/advanced_frontend # - ~/projects/faculty/1810/2025-fall-alex/modules:/app/storage/intro_to_web
- ~/projects/faculty/4850_AdvancedFE/2024-fall-alex/modules:/app/storage/advanced_frontend_old # - ~/projects/faculty/4850_AdvancedFE/2025-fall-alex/modules:/app/storage/advanced_frontend
- ~/projects/faculty/1430/2024-fall-alex/modules:/app/storage/ux_old # - ~/projects/faculty/4850_AdvancedFE/2024-fall-alex/modules:/app/storage/advanced_frontend_old
- ~/projects/faculty/1430/2025-fall-alex/modules:/app/storage/ux # - ~/projects/faculty/1430/2024-fall-alex/modules:/app/storage/ux_old
- ~/projects/faculty/1420/2024-fall/Modules:/app/storage/1420_old # - ~/projects/faculty/1430/2025-fall-alex/modules:/app/storage/ux
- ~/projects/faculty/1420/2025-fall-alex/modules:/app/storage/1420 # - ~/projects/faculty/1420/2024-fall/Modules:/app/storage/1420_old
- ~/projects/faculty/1425/2024-fall/Modules:/app/storage/1425_old # - ~/projects/faculty/1420/2025-fall-alex/modules:/app/storage/1420
- ~/projects/faculty/1425/2025-fall-alex/modules:/app/storage/1425 # - ~/projects/faculty/1425/2024-fall/Modules:/app/storage/1425_old
# - ~/projects/faculty/1425/2025-fall-alex/modules:/app/storage/1425
- ~/projects/facultyFiles:/app/public/images/facultyFiles - ~/projects/facultyFiles:/app/public/images/facultyFiles
redis: redis:

View File

@@ -1,3 +1 @@
courses: courses: []
- path: "./intro_to_web_old"
name: "Intro to Web (Old)"

View File

@@ -1,4 +1,5 @@
"use client"; "use client";
import ButtonSelect from "@/components/ButtonSelect";
import { DayOfWeekInput } from "@/components/form/DayOfWeekInput"; import { DayOfWeekInput } from "@/components/form/DayOfWeekInput";
import SelectInput from "@/components/form/SelectInput"; import SelectInput from "@/components/form/SelectInput";
import { Spinner } from "@/components/Spinner"; import { Spinner } from "@/components/Spinner";
@@ -37,7 +38,7 @@ const sampleCompose = `services:
- ~/projects/faculty/4850_AdvancedFE/2024-fall-alex/modules:/app/storage/advanced_frontend - ~/projects/faculty/4850_AdvancedFE/2024-fall-alex/modules:/app/storage/advanced_frontend
`; `;
export default function NewCourseForm() { export default function AddNewCourseToGlobalSettingsForm() {
const router = useRouter(); const router = useRouter();
const today = useMemo(() => new Date(), []); const today = useMemo(() => new Date(), []);
const { data: canvasTerms } = useCanvasTermsQuery(today); const { data: canvasTerms } = useCanvasTermsQuery(today);
@@ -61,12 +62,13 @@ export default function NewCourseForm() {
return ( return (
<div> <div>
<SelectInput <ButtonSelect
value={selectedTerm}
setValue={setSelectedTerm}
label={"Canvas Term"}
options={canvasTerms} options={canvasTerms}
getOptionName={(t) => t.name} getOptionName={(t) => t?.name ?? ""}
setValue={setSelectedTerm}
value={selectedTerm}
label={"Canvas Term"}
center={true}
/> />
<SuspenseAndErrorHandling> <SuspenseAndErrorHandling>
{selectedTerm && ( {selectedTerm && (
@@ -184,12 +186,13 @@ function OtherSettings({
return ( return (
<> <>
<SelectInput <ButtonSelect
value={selectedCanvasCourse} value={selectedCanvasCourse}
setValue={setSelectedCanvasCourse} setValue={setSelectedCanvasCourse}
label={"Course"} label={"Course"}
options={availableCourses} options={availableCourses}
getOptionName={(c) => c.name} getOptionName={(c) => c?.name ?? ""}
center={true}
/> />
<SelectInput <SelectInput
value={selectedDirectory} 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"; "use client";
import React, { useState } from "react"; import React, { useState } from "react";
import { SuspenseAndErrorHandling } from "@/components/SuspenseAndErrorHandling"; import { SuspenseAndErrorHandling } from "@/components/SuspenseAndErrorHandling";
import NewCourseForm from "./NewCourseForm"; import AddNewCourseToGlobalSettingsForm from "./AddCourseToGlobalSettingsForm";
import ClientOnly from "@/components/ClientOnly"; import ClientOnly from "@/components/ClientOnly";
export default function AddNewCourse() { export default function AddCourseToGlobalSettings() {
const [showForm, setShowForm] = useState(false); const [showForm, setShowForm] = useState(false);
return ( return (
<div> <div>
<div className="flex justify-center"> <div className="flex justify-center">
<button className="" onClick={() => setShowForm(true)}> <button className="" onClick={() => setShowForm((i) => !i)}>
Add New Course Add New Course
</button> </button>
</div> </div>
@@ -18,7 +18,9 @@ export default function AddNewCourse() {
<div className={" collapsible " + (showForm && "expand")}> <div className={" collapsible " + (showForm && "expand")}>
<div className="border rounded-md p-3 m-3"> <div className="border rounded-md p-3 m-3">
<SuspenseAndErrorHandling> <SuspenseAndErrorHandling>
<ClientOnly>{showForm && <NewCourseForm />}</ClientOnly> <ClientOnly>
{showForm && <AddNewCourseToGlobalSettingsForm />}
</ClientOnly>
</SuspenseAndErrorHandling> </SuspenseAndErrorHandling>
</div> </div>
</div> </div>

View File

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

View File

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

View File

@@ -2,32 +2,39 @@ import React from "react";
export default function ButtonSelect<T>({ export default function ButtonSelect<T>({
options, options,
getName, getOptionName,
setSelectedOption, setValue,
selectedOption, value,
label label,
center = false,
}: { }: {
options: T[]; options: T[];
getName: (value: T | undefined) => string; getOptionName: (value: T | undefined) => string;
setSelectedOption: (value: T | undefined) => void; setValue: (value: T | undefined) => void;
selectedOption: T | undefined; value: T | undefined;
label: string; label: string;
center?: boolean;
}) { }) {
return ( return (
<div> <div className={center ? "text-center" : ""}>
<label>{label}</label> <label>{label}</label>
<div className="flex flex-row gap-3 flex-wrap"> <div
className={
"flex flex-row gap-3 flex-wrap " + (center ? "justify-center" : "")
}
>
{options.map((o) => ( {options.map((o) => (
<button <button
type="button" type="button"
key={getName(o)} key={getOptionName(o)}
className={ className={
getName(o) === getName(selectedOption) ? " " : "unstyled btn-outline" getOptionName(o) === getOptionName(value)
? " "
: "unstyled btn-outline"
} }
onClick={() => setSelectedOption(o)} onClick={() => setValue(o)}
> >
{getName(o)} {getOptionName(o)}
</button> </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 { useTRPC } from "@/services/serverFunctions/trpcClient";
import { useSuspenseQuery } from "@tanstack/react-query"; import { useQuery, useSuspenseQuery } from "@tanstack/react-query";
export const directoryKeys = { export const directoryKeys = {
emptyFolders: ["empty folders"] as const, emptyFolders: ["empty folders"] as const,
@@ -9,3 +9,10 @@ export const useEmptyDirectoriesQuery = () => {
const trpc = useTRPC(); const trpc = useTRPC();
return useSuspenseQuery(trpc.directories.getEmptyDirectories.queryOptions()); 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 }); 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 publicProcedure from "../procedures/public";
import { router } from "../trpcSetup"; import { router } from "../trpcSetup";
import { fileStorageService } from "@/services/fileStorage/fileStorageService"; import { fileStorageService } from "@/services/fileStorage/fileStorageService";
@@ -6,4 +7,13 @@ export const directoriesRouter = router({
getEmptyDirectories: publicProcedure.query(async () => { getEmptyDirectories: publicProcedure.query(async () => {
return await fileStorageService.getEmptyDirectories(); return await fileStorageService.getEmptyDirectories();
}), }),
getDirectoryContents: publicProcedure
.input(
z.object({
relativePath: z.string(),
})
)
.query(async ({ input: { relativePath } }) => {
return await fileStorageService.getDirectoryContents(relativePath);
}),
}); });