We code better now

This commit is contained in:
Daniel Kluge 2022-06-12 14:22:15 +02:00
parent 929519225a
commit 0a0020b5c0
12 changed files with 230 additions and 166 deletions

View File

@ -1,69 +1,48 @@
import type { NextPage } from "next";
import { useEffect, useRef, useState } from "react";
import { useContext, useEffect, useRef, useState } from "react";
import asciidoctor from "asciidoctor";
import styles from "../styles/ProjectModal.module.css";
import type { Project, Diary } from "../lib/projects/types";
import type { Project, Diary } from "../lib/content/types";
import { useCommands } from "./contexts/CommandInterface";
import { generateContent, projectEmpty } from "../lib/content/generate";
import { useModalFunctions } from "./contexts/ModalFunctions";
//import Link from "next/link";
interface ModalInput {
project: Project|Diary|undefined;
projectType: "project"|"diary";
visible: boolean;
setVisible: CallableFunction;
}
const ProjectModal: NextPage = () => {
const [visible, setVisible] = useState<boolean>(false);
const [diaryPages, setDiaryPages] = useState<string[]>([]);
const [content, setContent] = useState<string>(projectEmpty);
const ad = asciidoctor();
const setModalContent = async (content: Project|Diary, selectedPage?: number) => {
if (content.type === "diary") setDiaryPages(content.entries.map(entry => entry.title));
setContent(await generateContent(content, selectedPage));
};
const { updateCallbacks: updateCmdCallbacks } = useCommands();
const { updateCallbacks: updateModalCallbacks } = useModalFunctions();
updateCmdCallbacks({ setModalVisible: setVisible, setModalContent});
updateModalCallbacks({ setVisible, setContent: setModalContent, setHtml: setContent });
const ProjectModal: NextPage<ModalInput> = ({ project, projectType, visible, setVisible }) => {
const projectEmpty = "<div>Kein Projekt ausgewählt.</div>";
const [projectData, setProjectData] = useState<string>(projectEmpty);
const containerRef = useRef<HTMLDivElement>(null);
const projectNotFoundHtml = `<div class="${"error"}">Sorry! There is no data for this project. Please check back later to see if that changed!</div>`;
const projectServerErrorHtml = `<div class="${"error"}">Sorry! A server error happend when the project data was fetched!</div>`;
const generateFooter = (project: string, lastUpdate: string) => `<hr>
<div id="footer">
<div id="footer-text">
Last updated: ${lastUpdate} | <a href="https://git.c0ntroller.de/c0ntroller/frontpage-projects/src/branch/senpai/${project}.adoc">Document source</a>
</div>
</div>
`;
useEffect(() => {
if (project && project.name) {
// TODO
// set Spinner
setProjectData("Loading...");
fetch(`/api/${projectType === "diary" ? "diaries" : "projects"}/${project.name}`).then((res) => {
if (res.status === 404) setProjectData(projectNotFoundHtml);
if (res.status !== 200) setProjectData(projectServerErrorHtml);
res.text().then(data => {
try {
const adDoc = ad.load(data, { attributes: { showtitle: true } });
setProjectData(adDoc.convert(adDoc).toString() + generateFooter(project.name, adDoc.getAttribute("docdatetime")));
} catch {
setProjectData(projectServerErrorHtml);
if (content && containerRef.current) {
containerRef.current.innerHTML = content;
}
});
});
} else if (typeof project === "undefined") setProjectData(projectEmpty);
}, [project, projectType, projectEmpty, projectNotFoundHtml, projectServerErrorHtml]);
useEffect(() => {
if (projectData && containerRef.current && projectData !== "") {
containerRef.current.innerHTML = projectData;
}
}, [projectData, visible]);
}, [content]);
if (!visible) return <></>;
return <div className={styles.modal}>
<a href="javascript:void(0);" onClick={() => setVisible(false)}>
<a onClick={() => setVisible(false)}>
<div className={styles.modalClose}><div className={styles.modalCloseAlign}>X</div></div>
</a>
<div className={styles.modalContainer}>
{
// TODO
// If diaryPages
// Show page selector
}
<div className={`${styles.modalText} asciidoc`} ref={containerRef}>
</div>

View File

@ -1,6 +1,6 @@
import { NextPage } from "next";
import Link from "next/link";
import { BaseSyntheticEvent, MutableRefObject, useEffect, useRef } from "react";
import type { BaseSyntheticEvent, MutableRefObject } from "react";
import styles from "../../styles/REPL/REPLHistory.module.css";
interface REPLHistoryParams {

View File

@ -1,27 +1,17 @@
import type { NextPage } from "next";
import useSWR from "swr";
import { MutableRefObject, useState, createRef, useEffect } from "react";
import { MutableRefObject, useState, createRef } from "react";
import { CommandInterface } from "../../lib/commands";
import styles from "../../styles/REPL/REPLInput.module.css";
import type { ProjectList } from "../../lib/projects/types";
import { useCommands } from "../contexts/CommandInterface";
import { useModalFunctions } from "../contexts/ModalFunctions";
interface REPLInputParams {
historyCallback: CallableFunction;
historyClear: CallableFunction;
inputRef: MutableRefObject<HTMLInputElement|null>;
modalManipulation: {
setModalVisible: CallableFunction;
setModalProject: CallableFunction;
setModalProjectType: CallableFunction;
}
}
async function fetchProjects(endpoint: string): Promise<ProjectList> {
const res = await fetch(endpoint);
return res.json();
}
const REPLInput: NextPage<REPLInputParams> = ({historyCallback, historyClear, inputRef, modalManipulation}) => {
const REPLInput: NextPage<REPLInputParams> = ({historyCallback, historyClear, inputRef}) => {
const typed = createRef<HTMLSpanElement>();
const completion = createRef<HTMLSpanElement>();
const [currentCmd, setCurrentCmd] = useState<string[]>([]);
@ -29,8 +19,8 @@ const REPLInput: NextPage<REPLInputParams> = ({historyCallback, historyClear, in
const [inCmdHistory, setInCmdHistory] = useState<number>(-1);
const [cmdHistory, setCmdHistory] = useState<string[]>([]);
const [usrInputTmp, setUsrInputTmp] = useState<string>("");
const [cmdIf, setCmdIf] = useState<CommandInterface>(new CommandInterface(modalManipulation, {projects: [], diaries: []}));
const { data: projects, error: projectsError } = useSWR("/api/projects?swr=1", fetchProjects);
const {cmdContext: cmdIf} = useCommands();
const { modalFunctions } = useModalFunctions();
const setInput = (inputRef: HTMLInputElement, input: string) => {
const nativeSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set;
@ -38,8 +28,8 @@ const REPLInput: NextPage<REPLInputParams> = ({historyCallback, historyClear, in
nativeSetter.call(inputRef, input);
//if(typed.current) typed.current.innerHTML = input;
//if(completion.current) completion.current.innerHTML = "";
const event = new Event("input", { bubbles: true });
inputRef.dispatchEvent(event);
inputRef.dispatchEvent(new Event("input", { bubbles: true }));
inputRef.dispatchEvent(new Event("change", { bubbles: true }));
};
const clearInput = (inputRef: HTMLInputElement) => {
@ -83,7 +73,8 @@ const REPLInput: NextPage<REPLInputParams> = ({historyCallback, historyClear, in
return false;
} else setJustTabbed(0);
if (e.key === "Enter") {
switch (true) {
case e.key === "Enter": {
e.preventDefault();
const command = (e.target as HTMLInputElement).value.trim();
if (cmdHistory.at(-1) !== command) setCmdHistory(cmdHistory.concat([command]).splice(0, 100));
@ -98,29 +89,25 @@ const REPLInput: NextPage<REPLInputParams> = ({historyCallback, historyClear, in
historyCallback(result);
return false;
}
if (e.key === "d" && e.ctrlKey) {
case e.key === "d" && e.ctrlKey: {
e.preventDefault();
const result = cmdIf.executeCommand("exit");
clearInput(input);
historyCallback(result);
return false;
}
if (e.key === "l" && e.ctrlKey) {
case e.key === "l" && e.ctrlKey: {
e.preventDefault();
clearInput(input);
historyClear();
return false;
}
if ((e.key === "c" || e.key === "u") && e.ctrlKey) {
case (e.key === "c" || e.key === "u") && e.ctrlKey: {
e.preventDefault();
clearInput(input);
return false;
}
if (e.key === "ArrowUp") {
case e.key === "ArrowUp": {
e.preventDefault();
const idx = inCmdHistory + 1;
if (idx < cmdHistory.length) {
@ -130,9 +117,9 @@ const REPLInput: NextPage<REPLInputParams> = ({historyCallback, historyClear, in
setInput(input, cmd);
setInCmdHistory(idx);
}
return false;
}
if (e.key === "ArrowDown") {
case e.key === "ArrowDown": {
e.preventDefault();
const idx = inCmdHistory - 1;
if (0 <= idx) {
@ -143,14 +130,11 @@ const REPLInput: NextPage<REPLInputParams> = ({historyCallback, historyClear, in
setInput(input, usrInputTmp);
setInCmdHistory(-1);
}
return false;
}
}
};
useEffect(() => {
if (!projectsError && projects) setCmdIf(new CommandInterface(modalManipulation, projects));
// In any other case we just don't create another interface.
}, [projects, projectsError, modalManipulation]);
return <div className={styles.wrapperwrapper}>
<span className={styles.inputstart}>$&nbsp;</span>
<div className={styles.wrapper}>

View File

@ -6,14 +6,9 @@ import type { NextPage } from "next";
interface IREPLProps {
inputRef: MutableRefObject<HTMLInputElement|null>;
modalManipulation: {
setModalVisible: CallableFunction;
setModalProject: CallableFunction;
setModalProjectType: CallableFunction;
}
}
const REPL: NextPage<IREPLProps> = ({ inputRef, modalManipulation }) => {
const REPL: NextPage<IREPLProps> = ({ inputRef }) => {
const date = new Date();
const [history, manipulateHistory] = useState<string[]>([`cer0 0S - ${date.toLocaleDateString()}`]);
const containerRef = useRef<HTMLDivElement>(null);
@ -30,7 +25,7 @@ const REPL: NextPage<IREPLProps> = ({ inputRef, modalManipulation }) => {
return (<div className={styles.container} ref={containerRef}>
<REPLHistory history={history} inputRef={inputRef} />
<REPLInput historyCallback={onCommandExecuted} historyClear={onClearHistory} inputRef={inputRef} modalManipulation={modalManipulation} />
<REPLInput historyCallback={onCommandExecuted} historyClear={onClearHistory} inputRef={inputRef} />
<div style={{flexGrow: 2}} onClick={focusInput}></div>
</div>);
};

View File

@ -0,0 +1,18 @@
import { createContext, useContext } from "react";
import type { PropsWithChildren } from "react";
import { CommandInterface } from "../../lib/commands";
import type { Diary, Project, ContentList } from "../../lib/content/types";
interface CommandInterfaceCallbacks {
setModalVisible?: (visible: boolean) => void;
setModalContent?: (content: Project | Diary, selectedPage?: number) => void;
}
const commandInterface = new CommandInterface();
const CommandContext = createContext(commandInterface);
const setCommandCallbacks = (callbacks: CommandInterfaceCallbacks) => commandInterface.callbacks = {...commandInterface.callbacks, ...callbacks};
const setContents = (content: ContentList) => commandInterface.content = content;
const useCommands = () => ({cmdContext: useContext(CommandContext), updateCallbacks: setCommandCallbacks, setContents});
const CommandsProvider = (props: PropsWithChildren<{}>) => <CommandContext.Provider value={commandInterface} {...props} />;
export { CommandsProvider, useCommands };

View File

@ -0,0 +1,17 @@
import { createContext, useContext } from "react";
import type { PropsWithChildren } from "react";
import type { Project, Diary } from "../../lib/content/types";
interface ModalFunctions {
setVisible?: CallableFunction;
setContent?: (content: Project| Diary) => void;
setHtml?: (html: string) => void;
}
const modalFunctions: ModalFunctions = {};
const ModalContext = createContext(modalFunctions);
const updateCallbacks = (callbacks: ModalFunctions) => Object.assign(modalFunctions, callbacks);
const useModalFunctions = () => ({modalFunctions: useContext(ModalContext), updateCallbacks});
const ModalFunctionProvider = (props: PropsWithChildren<{}>) => <ModalContext.Provider value={modalFunctions} {...props} />;
export { ModalFunctionProvider, useModalFunctions };

View File

@ -1,3 +1,4 @@
import type { Diary, Project } from "../content/types";
import type { Command, Flag } from "./types";
function getCommandByName(name: string): Command|undefined {
@ -146,9 +147,16 @@ const project: Command = {
execute: (flags, args, _raw, cmdIf) => {
if (project.flags && checkFlagInclude(flags, project.flags.list)) {
const result = ["Found the following projects:"];
cmdIf.projects.projects.forEach(project => result.push(`\t${project.name}\t${project.short_desc}`));
const projects = cmdIf.content.filter(p => p.type === "project");
if(projects.length === 0) result.push("\tNo projects found.");
else projects.forEach(project => result.push(`\t${project.name}\t${project.short_desc}`));
result.push("And the following diaries:");
cmdIf.projects.diaries.forEach(diary => result.push(`\t${diary.name}\t${diary.short_desc}`));
const diaries = cmdIf.content.filter(p => p.type === "diary");
if(diaries.length === 0) result.push("\tNo diaries found.");
else diaries.forEach(diary => result.push(`\t${diary.name}\t${diary.short_desc}`));
return result;
}
@ -156,8 +164,7 @@ const project: Command = {
if (args[0] === "this") args[0] = "homepage";
let [pjt, ptype] = [cmdIf.projects.projects.find(p => p.name === args[0]), "project"];
if (!pjt) [pjt, ptype] = [cmdIf.projects.diaries.find(p => p.name === args[0]), "diary"];
let [pjt] = [cmdIf.content.find(p => p.name === args[0]) as Project|Diary|undefined];
if (!pjt) return [
`Cannot find project ${args[0]}!`,
"You can see available projects using 'project -l'."
@ -173,9 +180,8 @@ const project: Command = {
}
if (project.flags && checkFlagInclude(flags, project.flags.minimal)) return pjt.desc;
cmdIf.callbacks.setModalProjectType(ptype);
cmdIf.callbacks.setModalProject(pjt);
cmdIf.callbacks.setModalVisible(true);
if (cmdIf.callbacks?.setModalContent) cmdIf.callbacks.setModalContent(pjt);
if (cmdIf.callbacks?.setModalVisible) cmdIf.callbacks.setModalVisible(true);
return [];
}
};
@ -203,4 +209,4 @@ const clear: Command = {
execute: () => []
};
export const commandList = [about, help, man, project, exitCmd, clear];
export const commandList = [about, help, man, project, exitCmd, clear].sort((a, b) => a.name.localeCompare(b.name));

View File

@ -1,19 +1,18 @@
import type { ProjectList } from "../projects/types";
import type { ContentList } from "../content/types";
import { printSyntax, commandList } from "./definitions";
interface CommandInterfaceCallbacks {
setModalVisible: CallableFunction;
setModalProject: CallableFunction;
setModalProjectType: CallableFunction;
setModalVisible?: CallableFunction;
setModalContent?: CallableFunction;
}
export class CommandInterface {
callbacks: CommandInterfaceCallbacks;
projects: ProjectList;
callbacks?: CommandInterfaceCallbacks;
content: ContentList = [];
constructor(callbacks: CommandInterfaceCallbacks, projects: ProjectList) {
constructor(callbacks?: CommandInterfaceCallbacks, content?: ContentList) {
this.callbacks = callbacks;
this.projects = projects;
this.content = content || [];
}
static commandCompletion(input: string): string[] {

44
lib/content/generate.ts Normal file
View File

@ -0,0 +1,44 @@
import type { Project, Diary } from "./types";
import asciidoctor from "asciidoctor";
export const projectEmpty = "<div>Kein Projekt ausgewählt.</div>";
const projectNotFoundHtml = `<div class="${"error"}">Sorry! There is no data for this project. Please check back later to see if that changed!</div>`;
const projectServerErrorHtml = `<div class="${"error"}">Sorry! A server error happend when the project data was fetched!</div>`;
const ad = asciidoctor();
export async function generateContent(content: Project|Diary, selectedPage?: number): Promise<string> {
if(!content) return projectEmpty;
switch (content.type) {
case "project": return await generateProjectHTML(content);
case "diary": return await generateDiaryHTML(content, selectedPage);
default: return projectNotFoundHtml;
}
}
async function generateProjectHTML(project: Project): Promise<string> {
const resp = await fetch(`/content/projects/${project.name}.adoc`);
if (resp.status !== 200) return projectServerErrorHtml;
const adDoc = ad.load(await resp.text(), { attributes: { showtitle: true } });
return `${adDoc.convert(adDoc).toString()}
<hr>
<div id="footer">
<div id="footer-text">
Last updated: ${adDoc.getAttribute("docdatetime")} | <a href="https://git.c0ntroller.de/c0ntroller/frontpage-content/src/branch/senpai/projects/${project.name}.adoc">Document source</a>
</div>
</div>`;
}
async function generateDiaryHTML(diary: Diary, selectedPage?: number): Promise<string> {
const resp = selectedPage === undefined ? await fetch(`/content/diaries/${diary.name}.adoc`) : await fetch(`/content/diaries/${diary.name}/${diary.entries[selectedPage].filename}.adoc`);
if (resp.status !== 200) return projectServerErrorHtml;
const adDoc = ad.load(await resp.text(), { attributes: { showtitle: true } });
const gitfile = selectedPage === undefined ? `${diary.name}.adoc` : `${diary.name}/${diary.entries[selectedPage].filename}.adoc`;
return `${adDoc.convert(adDoc).toString()}
<hr>
<div id="footer">
<div id="footer-text">
Last updated: ${adDoc.getAttribute("docdatetime")} | <a href="https://git.c0ntroller.de/c0ntroller/frontpage-content/src/branch/senpai/diaries/${gitfile}">Document source</a>
</div>
</div>`;
}

View File

@ -1,9 +1,9 @@
export interface ProjectList {
projects: Project[];
diaries: Diary[];
}
export type ContentList = (Project|Diary)[];
export type ContentType = "project" | "diary";
export interface Project {
type: "project";
name: string;
desc: string[];
short_desc: string;
@ -12,6 +12,7 @@ export interface Project {
}
export interface Diary {
type: "diary";
name: string;
desc: string[];
short_desc: string;
@ -19,6 +20,6 @@ export interface Diary {
repo?: string;
entries: {
title: string;
path: string;
filename: string;
}[];
}

View File

@ -2,6 +2,8 @@ import type { AppProps } from "next/app";
import Head from "next/head";
import "../styles/globals.css";
import "../styles/customAsciidoc.scss";
import { CommandsProvider } from "../components/contexts/CommandInterface";
import { ModalFunctionProvider } from "../components/contexts/ModalFunctions";
function MyApp({ Component, pageProps }: AppProps) {
return <>
@ -32,7 +34,11 @@ function MyApp({ Component, pageProps }: AppProps) {
<meta name="msapplication-TileImage" content="/mstile-310x310.png" />
<meta name="theme-color" content="#444444" />
</Head>
<CommandsProvider>
<ModalFunctionProvider>
<Component {...pageProps} />
</ModalFunctionProvider>
</CommandsProvider>
</>;
}

View File

@ -1,32 +1,47 @@
import type { NextPage } from "next";
import Head from "next/head";
import { GithubLogo, InstagramLogo, DiscordLogo, GameController } from "phosphor-react";
import { useRef, useState } from "react";
import { useEffect, useRef,useCallback } from "react";
import { useCommands } from "../components/contexts/CommandInterface";
import { useModalFunctions } from "../components/contexts/ModalFunctions";
import ProjectModal from "../components/ProjectModal";
import REPL from "../components/REPL";
import type { Project, Diary } from "../lib/projects/types";
import styles from "../styles/Home.module.css";
const Home: NextPage = () => {
const inputRef = useRef<HTMLInputElement>(null);
const [modalVisible, setModalVisible] = useState<boolean>(false);
const [modalProject, setModalProject] = useState<Project|Diary|undefined>(undefined);
const [modalProjectType, setModalProjectType] = useState<"project"|"diary">("project");
const { modalFunctions } = useModalFunctions();
const { setContents } = useCommands();
const updateProjects = useCallback(async () => {
try {
const res = await fetch("/content/list.json");
const projects = await res.json();
setContents(projects);
} catch {}
}, [setContents]);
updateProjects();
const focusInput = () => { if (inputRef.current) inputRef.current.focus(); };
const hideModalOnEsc = (e: React.KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
setModalVisible(false);
if(modalFunctions.setVisible) modalFunctions.setVisible(false);
}
};
useEffect(() => {
const interval = setInterval(updateProjects, 30 * 1000);
return () => clearInterval(interval);
}, [updateProjects]);
return (<main onKeyDown={hideModalOnEsc} tabIndex={-1}>
<Head>
<title>c0ntroller.de</title>
</Head>
<ProjectModal visible={modalVisible} project={modalProject} projectType={modalProjectType} setVisible={setModalVisible}/>
<ProjectModal />
<div className={styles.container}>
<div className={styles.header}>
<span className={styles.spacer} onClick={focusInput}>&nbsp;</span>
@ -49,7 +64,7 @@ const Home: NextPage = () => {
</span>
</a><span className={styles.spacer} onClick={focusInput}>&nbsp;</span>
</div>
<REPL inputRef={inputRef} modalManipulation={{setModalVisible, setModalProject, setModalProjectType}}/>
<REPL inputRef={inputRef} />
</div>
</main>);
};