3 Commits

Author SHA1 Message Date
c0ntroller 8864d84d45 Add gitea action
Deploy Astro / Build and Deploy (push) Failing after 59s
2023-12-13 16:46:44 +01:00
c0ntroller 4f561a0abd Minimal bugfix 2023-12-11 23:49:06 +01:00
c0ntroller 4671378238 Initial astro commit 2023-12-11 23:41:48 +01:00
121 changed files with 15824 additions and 11477 deletions
-95
View File
@@ -1,95 +0,0 @@
kind: pipeline
type: docker
name: build
trigger:
event:
- push
steps:
- name: tag-commit-hash
image: alpine
commands:
- echo '${DRONE_COMMIT:0:8}' > .tags
- name: tag-dev
image: alpine
when:
branch:
- dev
commands:
- sed -i '$s/$/,dev/' .tags
- name: tag-latest
image: alpine
when:
branch:
- senpai
commands:
- sed -i '$s/$/,latest/' .tags
- name: build-image
image: plugins/docker
settings:
username:
from_secret: docker_user
password:
from_secret: docker_token
registry:
from_secret: registry_host
repo:
from_secret: local_repo
insecure: true
---
kind: pipeline
type: ssh
name: deploy
depends_on:
- build
trigger:
branch:
- senpai
- dev
event:
- push
server:
host:
from_secret: ssh_host
user:
from_secret: ssh_user
ssh_key:
from_secret: ssh_key
steps:
- name: deploy-dev
when:
branch:
- dev
environment:
DOCKER_USER:
from_secret: docker_user
DOCKER_PASS:
from_secret: docker_token
REGISTRY_HOST:
from_secret: registry_host
IMAGE: c0ntroller.de:dev
commands:
#- docker login -u $${DOCKER_USER} -p $${DOCKER_PASS}
- docker-compose -p website-dev -f docker-compose.dev.yml rm -s -v -f
- docker rmi $${REGISTRY_HOST}/$${IMAGE} || true
- docker rmi localhost:5000/$${IMAGE} || true
- docker pull $${REGISTRY_HOST}/$${IMAGE}
- docker-compose -p website-dev -f docker-compose.dev.yml up --no-build -d
- name: deploy-stable
when:
branch:
- senpai
environment:
DOCKER_USER:
from_secret: docker_user
DOCKER_PASS:
from_secret: docker_token
REGISTRY_HOST:
from_secret: registry_host
IMAGE: c0ntroller.de:latest
commands:
#- docker login -u $${DOCKER_USER} -p $${DOCKER_PASS}
- docker-compose -p website -f docker-compose.stable.yml rm -s -v -f
- docker rmi $${REGISTRY_HOST}/$${IMAGE} || true
- docker rmi localhost:5000/$${IMAGE} || true
- docker pull $${REGISTRY_HOST}/$${IMAGE}
- docker-compose -p website -f docker-compose.stable.yml up --no-build -d
-8
View File
@@ -1,8 +0,0 @@
{
"extends": "next/core-web-vitals",
"rules": {
"semi": ["warn", "always", { "omitLastInOneLineBlock": true }],
"quotes": ["warn", "double", { "avoidEscape": true }],
"eqeqeq": "error"
}
}
+29
View File
@@ -0,0 +1,29 @@
name: Deploy Astro
on:
push:
branches:
- astro
jobs:
build-and-deploy:
name: Build and Deploy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
name: Checkout code
- name: Setup node and npm
uses: actions/setup-node@v3
with:
node-version: lts
- name: Install dependencies
run: npm ci
- name: Check and build
run: npm run build
- name: Copy files via ssh
uses: https://github.com/appleboy/scp-action@v0.1.4
with:
host: c0ntroller.de
username: ${{ secrets.SSH_USERNAME }}
key: ${{ secrets.SSH_KEY }}
source: "dist/*"
target: /var/www/website/astro
+13 -31
View File
@@ -1,39 +1,21 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# build output
dist/
# generated types
.astro/
# dependencies
/node_modules
/.pnp
.pnp.js
node_modules/
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# environment variables
.env
.env.production
# vercel
.vercel
# typescript
*.tsbuildinfo
public/content/
# macOS-specific files
.DS_Store
+7
View File
@@ -0,0 +1,7 @@
{
"recommendations": [
"astro-build.astro-vscode",
"unifiedjs.vscode-mdx"
],
"unwantedRecommendations": []
}
+11
View File
@@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "./node_modules/.bin/astro dev",
"name": "Development server",
"request": "launch",
"type": "node-terminal"
}
]
}
-40
View File
@@ -1,40 +0,0 @@
# From https://nextjs.org/docs/deployment
# Rebuild the source code only when needed
FROM node:lts-alpine AS builder
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
ENV NEXT_TELEMETRY_DISABLED 1
RUN npm run build
# Production image, copy all the files and run next
FROM node:lts-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
# You only need to copy next.config.js if you are NOT using the default configuration
# COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
USER nextjs
EXPOSE 3000
ENV PORT 3000
# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry.
ENV NEXT_TELEMETRY_DISABLED 1
CMD ["node_modules/.bin/next", "start"]
+48 -9
View File
@@ -1,15 +1,54 @@
# Frontpage
# Astro Starter Kit: Basics
[![Read the blog entry at c0ntroller.de](https://c0ntroller.de/img/read-blog.svg)](https://c0ntroller.de/blog/project/terminal)
```sh
npm create astro@latest -- --template basics
```
| Stable | Dev
| ------ | ---
| [![Build Status](https://drone.c0ntroller.de/api/badges/c0ntroller/frontpage/status.svg)](https://drone.c0ntroller.de/c0ntroller/frontpage) | [![Build Status](https://drone.c0ntroller.de/api/badges/c0ntroller/frontpage/status.svg?ref=refs/heads/dev)](https://drone.c0ntroller.de/c0ntroller/frontpage)
[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/withastro/astro/tree/latest/examples/basics)
[![Open with CodeSandbox](https://assets.codesandbox.io/github/button-edit-lime.svg)](https://codesandbox.io/p/sandbox/github/withastro/astro/tree/latest/examples/basics)
[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/withastro/astro?devcontainer_path=.devcontainer/basics/devcontainer.json)
This repository contains my NextJS-based website.
> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!
When changes are made to `senpai` it will be deploy on https://c0ntroller.de
![just-the-basics](https://github.com/withastro/astro/assets/2244813/a0a5533c-a856-4198-8470-2d67b1d7c554)
When changes are made in the `dev` branch it will be deployed on https://dev.c0ntroller.de
## 🚀 Project Structure
AsciiDoc-files with projects descriptions are hosted in [c0ntroller/frontpage-content](https://git.c0ntroller.de/c0ntroller/frontpage-content)
Inside of your Astro project, you'll see the following folders and files:
```text
/
├── public/
│ └── favicon.svg
├── src/
│ ├── components/
│ │ └── Card.astro
│ ├── layouts/
│ │ └── Layout.astro
│ └── pages/
│ └── index.astro
└── package.json
```
Astro looks for `.astro` or `.md` files in the `src/pages/` directory. Each page is exposed as a route based on its file name.
There's nothing special about `src/components/`, but that's where we like to put any Astro/React/Vue/Svelte/Preact components.
Any static assets, like images, can be placed in the `public/` directory.
## 🧞 Commands
All commands are run from the root of the project, from a terminal:
| Command | Action |
| :------------------------ | :----------------------------------------------- |
| `npm install` | Installs dependencies |
| `npm run dev` | Starts local dev server at `localhost:4321` |
| `npm run build` | Build your production site to `./dist/` |
| `npm run preview` | Preview your build locally, before deploying |
| `npm run astro ...` | Run CLI commands like `astro add`, `astro check` |
| `npm run astro -- --help` | Get help using the Astro CLI |
## 👀 Want to learn more?
Feel free to check [our documentation](https://docs.astro.build) or jump into our [Discord server](https://astro.build/chat).
+17
View File
@@ -0,0 +1,17 @@
import { defineConfig } from 'astro/config';
import mdx from "@astrojs/mdx";
import a11yEmoji from "@fec/remark-a11y-emoji";
// https://astro.build/config
export default defineConfig({
integrations: [mdx()],
markdown: {
remarkPlugins: [
a11yEmoji
],
shikiConfig: {
theme: "one-dark-pro"
}
}
});
-22
View File
@@ -1,22 +0,0 @@
import type { NextPage } from "next";
import Link from "next/link";
import styles from "../../styles/Blog/Card.module.scss";
interface IContentCard {
name: string;
title: string;
description: string;
type: "project" | "diary";
}
const ContentCard: NextPage<IContentCard> = (content: IContentCard) => {
return <Link href={`/blog/${content.type}/${content.name}`}><a className="nostyle">
<div className={styles.card}>
<h3 className={styles.title}>{content.title}</h3>
<p className={styles.description}>{content.description}</p>
</div>
</a>
</Link>;
};
export default ContentCard;
-24
View File
@@ -1,24 +0,0 @@
import type { NextPage } from "next";
import { Git } from "@icons-pack/react-simple-icons";
import Icon from "@mdi/react";
import { mdiWeb } from "@mdi/js";
import type { ProjectRender, DiaryRender } from "../../lib/content/types";
import DiaryPageSelector from "./DiaryPageSelector";
import styles from "../../styles/Blog/Content.module.scss";
const ContentPage: NextPage<{ content: ProjectRender | DiaryRender }> = ({ content }) => {
return (<>
{content.type === "diary" ? <DiaryPageSelector title={content.title} pageSelected={content.pageSelected} name={content.name} pages={content.entries} /> : null}
<div className={styles.more}>
{content.more ? <a href={content.more} className="nostyle"><Icon path={mdiWeb} size="2em" title="More" id={`mdi_content_more_link_${content.name}`} /></a> : null}
{content.repo ? <a href={content.repo} className="nostyle"><Git size="2em" title="Repository" id={`mdi_content_repo_link_${content.name}`} /></a> : null}
</div>
<div className={styles.asciidoc} dangerouslySetInnerHTML={{ __html: content.html }}>
</div>
{content.type === "diary" ? <DiaryPageSelector title={content.title} pageSelected={content.pageSelected} name={content.name} pages={content.entries} bottom /> : null}
</>);
};
export default ContentPage;
-90
View File
@@ -1,90 +0,0 @@
import type { NextPage } from "next";
import Link from "next/link";
import { useRouter } from "next/router";
import type { ChangeEvent, ChangeEventHandler } from "react";
import { useEffect } from "react";
import type { DiaryEntry } from "../../lib/content/types";
import styles from "../../styles/Blog/DiaryPageSelector.module.scss";
interface IContent {
name: string;
title: string;
pageSelected: number
}
interface IContentNavBar extends IContent {
mobile?: boolean;
bottom?: boolean;
pages: string[];
}
interface IContentNav extends IContent {
bottom?: boolean;
pages: DiaryEntry[];
}
const PageSelectorBar: NextPage<IContentNavBar> = ({ pages, name, title, pageSelected, mobile, bottom }) => {
const router = useRouter();
// When we are on the main page no previous page exists, otherwise we need to check if the previous page is the main page
const prevLink = pageSelected === 0 ? null : pageSelected > 1 ? `/blog/diary/${name}/${pageSelected - 1}` : `/blog/diary/${name}`;
const nextLink = pageSelected < pages.length ? `/blog/diary/${name}/${pageSelected + 1}` : null;
useEffect(() => {
if (prevLink) router.prefetch(prevLink);
if (nextLink) router.prefetch(nextLink);
}, [nextLink, prevLink, router]);
const onSelection: ChangeEventHandler = async (e: ChangeEvent) => {
const selected = Number.parseInt((e.target as HTMLSelectElement).value) || 0;
const link = selected === 0 ? `/blog/diary/${name}` : `/blog/diary/${name}/${selected}`;
await router.push(link);
};
const prev = <span className={styles.leftSelectSpace}>{prevLink ? <Link href={prevLink}><a>&lt;<span className={styles.longLink}> {pageSelected - 1 === 0 ? "Main Page" : pages[pageSelected - 2]}</span><span className={styles.shortLink}>&lt;</span></a></Link> : null}</span>;
const next = <span className={styles.rightSelectSpace}>{nextLink ? <Link href={nextLink}><a><span className={styles.longLink}>{pages[pageSelected]} </span><span className={styles.shortLink}>&gt;</span>&gt;</a></Link> : null}</span>;
const select = (
<select onChange={onSelection} value={pageSelected}>
<option key={-1} value={0}>Main page</option>
{pages.map((entry, i) => <option key={i} value={i + 1}>{entry}</option>)}
</select>
);
const classNames = `${styles.barNav} ${mobile ? styles.mobile : ""} ${bottom ? styles.bottom : styles.top}`;
return (
<div className={classNames}>
<span></span> {/* Spacer */}
{prev}
<span style={{visibility: prevLink ? "visible" : "hidden"}}>&nbsp;&nbsp;|&nbsp;&nbsp;</span>
{select}
<span style={{visibility: nextLink ? "visible" : "hidden"}}>&nbsp;&nbsp;|&nbsp;&nbsp;</span>
{next}
<span></span> {/* Spacer */}
</div>
);
};
const PageSelector: NextPage<IContentNav> = (content) => {
const entries = content.pages.map(p => p.title);
if (content.bottom) return <PageSelectorBar pages={entries} name={content.name} title={content.title} pageSelected={content.pageSelected} bottom />;
return (
<div className={styles.nav}>
<PageSelectorBar pages={entries} name={content.name} title={content.title} pageSelected={content.pageSelected} mobile />
<aside className={`${styles.sideNav} ${styles.desktop}`}>
<Link href={`/blog/diary/${content.name}`}><a><h4 className={content.pageSelected === 0 ? styles.thisPage : undefined}>{content.title}</h4></a></Link>
<ol>
{entries.map((e, idx) => <li key={idx} className={content.pageSelected - 1 === idx ? styles.thisPage : undefined}><Link href={`/blog/diary/${content.name}/${idx + 1}`}><a>{e}</a></Link></li>)}
</ol>
</aside>
</div>
);
};
export default PageSelector;
-46
View File
@@ -1,46 +0,0 @@
import type { NextPage } from "next";
import Head from "next/head";
import Navigation from "./Navigation";
import styles from "../../styles/Blog/Blog.module.scss";
import socials from "../../data/socials";
import Link from "next/link";
interface ILayoutProps {
title?: string;
}
const Layout: NextPage<ILayoutProps> = ({ title, children }) => {
const socialLinks = socials("1.1em").map((social, i) => <a key={i} href={social.url} target="_blank" rel="noreferrer" className={styles.socialIcon}>{social.icon}</a>);
return <>
<Head>
<title>{title ?? "c0ntroller.de"}</title>
</Head>
<div id={styles.blogBody}>
<span id="top" aria-hidden></span>
<header>
<Navigation />
</header>
<main>
{ children }
</main>
<footer id="bottom">
<span style={{visibility: "hidden"}}></span>
<span className={styles.spacer}></span>
<span className={styles.footerContent}>
<span><Link href="/copyright"><a className="nocolor">Copyright</a></Link></span>
<span className={styles.divider}>|</span>
{socialLinks.flatMap((social, i) => i !== 0 ? [<span className={styles.divider} key={`d${i}`}>|</span>, social] : [social])}
<span className={styles.divider}>|</span>
<a className="nocolor" target="_blank" href="mailto:admin-website@c0ntroller.de" rel="noreferrer">Contact</a>
</span>
<span className={styles.spacer}></span>
<a className="nostyle" href="#top" title="Back to top"></a>
</footer>
</div>
</>;
};
export default Layout;
-41
View File
@@ -1,41 +0,0 @@
/* eslint-disable @next/next/no-img-element */
import type { NextPage } from "next";
import Link from "next/link";
import Image from "next/image";
import Icon from "@mdi/react";
import { mdiConsole, mdiAccount, mdiHome } from "@mdi/js";
import ThemeSwitch from "./ThemeSwitch";
import styles from "../../styles/Blog/Navigation.module.scss";
import logo from "../../public/img/icon.png";
const Navigation: NextPage<{}> = () => {
return <nav className={styles.navigation}>
<Link href="/">
<a className={`nostyle ${styles.imgContainer} ${styles.logo}`}>
<Image src={logo} alt="Logo" layout="fill" />
</a>
</Link>
<div className={styles.navLink}>
<Link href="/"><a className="nostyle">
<span className={styles.linkText}>Projects</span>
<span className={styles.linkIcon}><Icon path={mdiHome} size="2em" title="Home and Projects" id="mdi_nav_home" /></span>
</a></Link>
</div>
<div className={styles.navLink}>
<Link href="/me"><a className="nostyle">
<span className={styles.linkText}>About Me</span>
<span className={styles.linkIcon}><Icon path={mdiAccount} size="2em" title="About Me" id="mdi_nav_aboutme" /></span>
</a></Link>
</div>
<div className={styles.spacer}></div>
<div className={styles.navIcon}>
<Link href="/terminal"><a className="nostyle">
<Icon path={mdiConsole} size="2em" title="Terminal" id="mdi_nav_terminal" />
</a></Link>
</div>
<ThemeSwitch />
</nav>;
};
export default Navigation;
-53
View File
@@ -1,53 +0,0 @@
import type { NextPage } from "next";
import { useEffect, useState } from "react";
import { useTheme } from "next-themes";
import Icon from "@mdi/react";
import { mdiWhiteBalanceSunny, mdiWeatherNight, mdiLanguageJavascript } from "@mdi/js";
import styles from "../../styles/Blog/ThemeSwitch.module.scss";
interface FadeProperties {
sun?: string;
moon?: string;
}
const ThemeSwitch: NextPage<{ size?: string }> = ({ size }) => {
const [mounted, setMounted] = useState(false);
const [fadeProps, setFadeProps] = useState<FadeProperties>({});
const { resolvedTheme, setTheme } = useTheme();
// Will be run when the component is rendered.
useEffect(() => {
setMounted(true);
}, []);
const switchTheme = (theme: string) => {
if (theme === "dark") setFadeProps({
sun: styles.fadeIn,
moon: styles.fadeOut
});
else setFadeProps({
sun: styles.fadeOut,
moon: styles.fadeIn
});
setTheme(theme);
};
if (!mounted) {
return <div className={styles.switch} title="Theme switching needs JS to be enabled.">
<Icon path={mdiLanguageJavascript} size={size || "1.5em"} className={styles.placeHolder} id="mdi_themeswitch_noscript" />
</div>;
}
const sunClasses = fadeProps.sun || (resolvedTheme === "dark" ? styles.selected : undefined);
const moonClasses = fadeProps.moon || (resolvedTheme === "light" ? styles.selected : undefined);
return <div className={styles.switch}>
<div className={sunClasses} onClick={() => switchTheme("light")}><Icon path={mdiWhiteBalanceSunny} size={size || "1.5em"} title="Light theme" id="mdi_themeswitch_light" /></div>
<div className={moonClasses} onClick={() => switchTheme("dark")}><Icon path={mdiWeatherNight} size={size || "1.5em"} title="Dark theme" id="mdi_themeswitch_dark" /></div>
</div>;
};
export default ThemeSwitch;
-19
View File
@@ -1,19 +0,0 @@
import type { NextPage } from "next";
import styles from "../styles/Spinner.module.scss";
const Spinner: NextPage<{size: number, color?: string}> = ({ size, color }) => {
const diameterY = 300;
const padding = 25;
const rad = (angle: number) => angle * (Math.PI / 180);
const side = (diameterY / 2) / Math.sin(rad(60));
const x0 = side * Math.sin(rad(30));
const vbSizeX = (2 * x0) + side + (2 * padding);
const vbSizeY = diameterY + (2 * padding);
return <div style={{height: size, width: size}} className={styles.spinnerContainer}><svg height="100%" width="100%" viewBox={`-${padding} -${padding} ${vbSizeX} ${vbSizeY}`} className={styles.spinner}>
<polygon points={`${x0},${diameterY} 0,${diameterY/2} ${x0},0 ${x0+side},0 ${2*x0 + side},${diameterY/2} ${x0+side},${diameterY}`} className={styles.spinnerPath} style={{stroke: color}} />
</svg></div>;
};
export default Spinner;
-121
View File
@@ -1,121 +0,0 @@
import type { NextPage } from "next";
import { useEffect, useRef, useState, isValidElement, useCallback } from "react";
import { useRouter } from "next/router";
import styles from "../../styles/Terminal/ProjectModal.module.css";
import asciidocStyles from "../../styles/Terminal/customAsciidoc.module.scss";
import type { Project, Diary } from "../../lib/content/types";
import { useCommands } from "../../lib/commands/ContextProvider";
import { generateContent, projectEmpty } from "../../lib/content/generateBrowser";
import { useModalFunctions } from "./contexts/ModalFunctions";
import Spinner from "../Spinner";
import { renderToStaticMarkup } from "react-dom/server";
// Code Highlighting
import hljs from "highlight.js";
import rust from "highlight.js/lib/languages/rust";
import bash from "highlight.js/lib/languages/shell";
hljs.registerLanguage("rust", rust);
hljs.registerLanguage("bash", bash);
hljs.registerLanguage("console", bash);
hljs.registerLanguage("shell", bash);
const ProjectModal: NextPage = () => {
const [visible, _setVisible] = useState<boolean>(false);
const [currentContent, _setCurrentContent] = useState<Project | Diary | undefined>(undefined);
const [currentPage, setCurrentPage] = useState<number>(0);
const [HTMLContent, _setHTMLContent] = useState<string>(projectEmpty);
const router = useRouter();
const { updateCallbacks: updateCmdCallbacks, cmdContext } = useCommands();
const { updateCallbacks: updateModalCallbacks } = useModalFunctions();
const setHTMLContent = (html: any) => {
switch (true) {
case typeof html === "string": {
_setHTMLContent(html);
return;
}
case isValidElement(html): {
_setHTMLContent(renderToStaticMarkup(html));
return;
}
default: {
try {
_setHTMLContent(html.toString());
} catch {}
return;
}
}
};
const setModalContent = async (content: Project | Diary, selectedPage?: number) => {
_setCurrentContent(content);
router.replace("#", `#/${content.type}/${content.name}${content.type === "diary" && selectedPage ? `/${selectedPage}`: ""}`, {shallow: true});
if (content.type === "diary") setCurrentPage(selectedPage === undefined ? 0 : selectedPage);
setHTMLContent(<Spinner size={200} />);
setHTMLContent(await generateContent(content, selectedPage));
};
const setVisible = async (visible: boolean) => {
if (!visible) {
if (window) window.removeEventListener("hashchange", contentFromHash);
router.replace("#", undefined, {shallow: true});
} else {
if (window) window.addEventListener("hashchange", contentFromHash);
}
_setVisible(visible);
};
const contentFromHash = () => {
if (!window) return;
const selected = window.location.hash.split("/");
if (selected.length > 2) cmdContext.executeCommand(`project ${selected[2]}${selected[3] ? ` ${selected[3]}` : ""}`);
};
const onContentReady = () => {
contentFromHash();
};
updateCmdCallbacks({ setModalVisible: setVisible, setModalContent, setModalHTML: setHTMLContent });
updateModalCallbacks({ setVisible, setContent: setModalContent, setHtml: setHTMLContent, onContentReady });
useEffect(() => {
hljs.highlightAll();
}, [HTMLContent]);
const containerRef = useRef<HTMLDivElement>(null);
if (!visible) return <></>;
const nextPageSelector = (() => {
if (!currentContent || currentContent?.type !== "diary" || currentContent.entries.length === 0) return null;
const prev = <span className={styles.leftSelectSpace}>{currentPage > 0 ? <a className={styles.fakeLink} onClick={() => setModalContent(currentContent, currentPage - 1)}>&lt; {currentPage - 1 > 0 ? currentContent.entries[currentPage - 2].title : "Main page"}</a> : null}</span>;
const next = <span className={styles.rightSelectSpace}>{currentPage < currentContent.entries.length ? <a className={styles.fakeLink} onClick={() => setModalContent(currentContent, currentPage + 1)}>{currentContent.entries[currentPage].title} &gt;</a> : null}</span>;
const select = (
<select onChange={(e) => setModalContent(currentContent, Number.parseInt(e.target.value))} value={currentPage}>
<option key={-1} value={0}>Main page</option>
{currentContent.entries.map((entry, i) => <option key={i} value={i + 1}>{entry.title}</option>)}
</select>
);
return <div className={styles.pageSelector}>{prev}<span style={{visibility: currentPage > 0 ? "visible" : "hidden"}}>&nbsp;&nbsp;|&nbsp;&nbsp;</span>{select}<span style={{visibility: currentPage < currentContent.entries.length ? "visible" : "hidden"}}>&nbsp;&nbsp;|&nbsp;&nbsp;</span>{next}</div>;
})();
return <div className={styles.modal} onClick={() => setVisible(false)}>
<a onClick={() => setVisible(false)} className={styles.fakeLink}>
<div className={styles.modalClose}><div className={styles.modalCloseAlign}>X</div></div>
</a>
<div className={styles.modalContainer} onClick={(event) => event.stopPropagation()}>
{nextPageSelector}
<div className={`${styles.modalText} ${asciidocStyles.asciidoc}`} ref={containerRef} dangerouslySetInnerHTML={{ __html: HTMLContent ? HTMLContent : projectEmpty }}>
</div>
{nextPageSelector}
</div>
</div>;
};
export default ProjectModal;
-101
View File
@@ -1,101 +0,0 @@
import { NextPage } from "next";
import Link from "next/link";
import type { BaseSyntheticEvent, MutableRefObject } from "react";
import styles from "../../../styles/Terminal/REPL/REPLHistory.module.css";
interface REPLHistoryParams {
history: string[];
inputRef: MutableRefObject<HTMLInputElement|null>;
}
const REPLHistory: NextPage<REPLHistoryParams> = ({history, inputRef}) => {
const focusInput = () => {if (inputRef.current) inputRef.current.focus();};
const forceInput = (e: BaseSyntheticEvent) => {
const command = (e.target as HTMLSpanElement).innerHTML;
if (inputRef.current) {
inputRef.current.value = command;
// TODO
// Fix this as this currently doesn't work
inputRef.current.dispatchEvent(new KeyboardEvent("keydown", {
key: "Enter",
keyCode: 13,
}));
}
return true;
};
const makeLinks = (line: string) => {
let idxStart = line.indexOf("#{");
let idxSep = line.indexOf("|", idxStart);
let idxEnd = line.indexOf("}", idxSep);
if (idxStart === -1 || idxSep === -1 || idxEnd === -1) return [line];
const result = [];
while (idxStart !== -1 && idxSep !== -1 && idxEnd !== -1) {
const linkText = line.substring(idxStart+2, idxSep);
const linkHref = line.substring(idxSep+1, idxEnd);
const isLocal = linkHref.startsWith("https://c0ntroller.de") || linkHref.startsWith("/") || linkHref.startsWith("#");
result.push(line.substring(0, idxStart));
result.push(<Link href={linkHref} key={`${linkHref}${line.length}`}><a className={styles.link} target={isLocal ? "_self" : "_blank"} rel={isLocal ? "" : "noreferrer"}>{linkText}</a></Link>);
line = line.substring(idxEnd+1);
idxStart = line.indexOf("#{");
idxSep = line.indexOf("|", idxStart);
idxEnd = line.indexOf("}", idxSep);
}
// Its already cut off
result.push(line);
return result;
};
const makeCommands = (line: string|JSX.Element) => {
if (typeof line !== "string") return line;
let idxStart = line.indexOf("%{");
let idxEnd = line.indexOf("}", idxStart);
if (idxStart === -1 || idxEnd === -1) return line;
const result = [];
while (idxStart !== -1 && idxEnd !== -1) {
const cmdText = line.substring(idxStart+2, idxEnd);
result.push(line.substring(0, idxStart));
result.push(<span className={styles.cmd} onClick={forceInput} key={`${cmdText}${line.length}${cmdText}`}>{cmdText}</span>);
line = line.substring(idxEnd+1);
idxStart = line.indexOf("%{");
idxEnd = line.indexOf("}", idxStart);
}
// Its already cut off
result.push(line);
return result;
};
const parseLine = (line: string) => {
if (line === "") return "\u00A0";
const resultLinks = makeLinks(line);
const resultAll = resultLinks.map(makeCommands);
return resultAll.flat();
};
return <div className={styles.container} onClick={focusInput}>
{ history.map((value, idx) => <div className={styles.line} key={`${idx}${value}`}>
{parseLine(value)}
</div>)
}
{<noscript>
<div className={styles.line}>JavaScript must be enabled, else this site won&apos;t work.</div>
<div className={styles.line}>This site doesn&apos;t use any trackers, so please enable JS!</div>
</noscript>}
</div>;
};
export default REPLHistory;
-169
View File
@@ -1,169 +0,0 @@
import type { NextPage } from "next";
import { MutableRefObject, useState, createRef, useEffect } from "react";
import { CommandInterface } from "../../../lib/commands";
import styles from "../../../styles/Terminal/REPL/REPLInput.module.css";
import { useCommands } from "../../../lib/commands/ContextProvider";
//import { useModalFunctions } from "../contexts/ModalFunctions";
interface REPLInputParams {
historyCallback: CallableFunction;
historyClear: CallableFunction;
inputRef: MutableRefObject<HTMLInputElement|null>;
}
const REPLInput: NextPage<REPLInputParams> = ({historyCallback, historyClear, inputRef}) => {
const typed = createRef<HTMLSpanElement>();
const completion = createRef<HTMLSpanElement>();
const [currentCmd, setCurrentCmd] = useState<string[]>([]);
let [justTabbed, setJustTabbed] = useState<number>(0); // Because setters are not in sync but the events are too fast
const [inCmdHistory, setInCmdHistory] = useState<number>(-1);
const [cmdHistory, setCmdHistory] = useState<string[]>([]);
const [usrInputTmp, setUsrInputTmp] = useState<string>("");
const {cmdContext: cmdIf, updateCallbacks} = useCommands();
//const { modalFunctions } = useModalFunctions();
updateCallbacks({ getCmdHistory: () => cmdHistory });
const setInput = (inputRef: HTMLInputElement, input: string) => {
const nativeSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set;
if (!nativeSetter) return;
nativeSetter.call(inputRef, input);
//if(typed.current) typed.current.innerHTML = input;
//if(completion.current) completion.current.innerHTML = "";
inputRef.dispatchEvent(new Event("input", { bubbles: true }));
inputRef.dispatchEvent(new Event("change", { bubbles: true, }));
};
const clearInput = (inputRef: HTMLInputElement) => {
setInput(inputRef, "");
};
const replinOnChange = (e: React.FormEvent<HTMLInputElement>) => {
const input = (e.target as HTMLInputElement);
const currentInput = input.value.toLowerCase();
// Force lowercase
input.value = currentInput;
if (currentInput.trim() === "") input.value = "";
if (currentInput.includes(" ")) {
// Command already typed
input.maxLength = 524288; // Default value
if (typed.current) typed.current.innerHTML = "";
if (completion.current) completion.current.innerHTML = "";
setCurrentCmd([]);
return;
} else {
input.maxLength = 20;
if(justTabbed === 0) {
// Get completion hint
const suggest = CommandInterface.commandCompletion(currentInput);
setCurrentCmd(suggest);
if (suggest.length === 0) suggest.push("");
if (typed.current) typed.current.innerHTML = currentInput;
if (completion.current) completion.current.innerHTML = suggest[0].substring(currentInput.length);
} else {
if (typed.current) typed.current.innerHTML = "";
if (completion.current) completion.current.innerHTML = "";
}
}
};
const keyEvent = (e: React.KeyboardEvent<HTMLInputElement>) => {
const input = (e.target as HTMLInputElement);
if (e.key === "Tab") e.preventDefault();
if (e.key === "Tab" && currentCmd.length !== 0) {
const cmd = `${currentCmd[justTabbed % currentCmd.length]}${currentCmd.length === 1 ? " " : ""}`;
setJustTabbed(justTabbed + 1);
justTabbed += 1; // Because setters are not in sync but the events are too fast
setInput(input, cmd);
return false;
} else setJustTabbed(0);
switch (true) {
case e.key === "Enter": {
e.preventDefault();
const command = (e.target as HTMLInputElement).value.trim();
if (command.length === 0) {
historyCallback(["$"]);
return;
}
if (cmdHistory.at(-1) !== command) setCmdHistory(cmdHistory.concat([command]).splice(0, 100));
clearInput(input);
setInCmdHistory(-1);
setCurrentCmd([]);
if (command === "clear") {
historyClear();
return false;
}
const result = cmdIf.executeCommand(command);
historyCallback(result);
return false;
}
case e.key === "d" && e.ctrlKey: {
e.preventDefault();
const result = cmdIf.executeCommand("exit");
clearInput(input);
historyCallback(result);
return false;
}
case e.key === "l" && e.ctrlKey: {
e.preventDefault();
clearInput(input);
historyClear();
return false;
}
case (e.key === "c" || e.key === "u") && e.ctrlKey: {
e.preventDefault();
clearInput(input);
return false;
}
case e.key === "ArrowUp": {
e.preventDefault();
const idx = inCmdHistory + 1;
if (idx < cmdHistory.length) {
if (inCmdHistory === -1) setUsrInputTmp(input.value);
const cmd = cmdHistory[cmdHistory.length - idx - 1];
setInput(input, cmd);
setInCmdHistory(idx);
}
return false;
}
case e.key === "ArrowDown": {
e.preventDefault();
const idx = inCmdHistory - 1;
if (0 <= idx) {
const cmd = cmdHistory[cmdHistory.length - idx - 1];
setInput(input, cmd);
setInCmdHistory(idx);
} else if (idx === -1) {
setInput(input, usrInputTmp);
setInCmdHistory(-1);
}
return false;
}
}
};
useEffect(() => {
if (!window || !cmdIf) return;
const color = window.localStorage.getItem("color");
if(color) cmdIf.executeCommand(`color ${color}`);
const history = window.localStorage.getItem("history");
try {
if (history) setCmdHistory(JSON.parse(history));
} catch {}
}, [cmdIf]);
return <div className={styles.wrapperwrapper}>
<span className={styles.inputstart}>$&nbsp;</span>
<div className={styles.wrapper}>
<input ref={inputRef as MutableRefObject<HTMLInputElement>} className={styles.in} type="text" onChange={replinOnChange} onKeyDown={keyEvent} spellCheck="false" autoComplete="off" autoFocus maxLength={20} />
<span className={styles.completionWrapper}><span ref={typed} className={styles.typed}></span><span ref={completion} className={styles.completion}></span></span>
</div>
</div>;
};
export default REPLInput;
-34
View File
@@ -1,34 +0,0 @@
import { MutableRefObject, useEffect, useRef, useState } from "react";
import REPLInput from "./REPLInput";
import REPLHistory from "./REPLHistory";
import styles from "../../../styles/Terminal/REPL/REPLComplete.module.css";
import type { NextPage } from "next";
interface IREPLProps {
inputRef: MutableRefObject<HTMLInputElement|null>;
buildTime: string;
}
const REPL: NextPage<IREPLProps> = ({ inputRef, buildTime }) => {
const [history, manipulateHistory] = useState<string[]>([`cer0 0S - Build ${buildTime}`]);
const containerRef = useRef<HTMLDivElement>(null);
const onCommandExecuted = (result: string[]) => manipulateHistory(result.reverse().concat(history).slice(0, 1000));
const onClearHistory = () => manipulateHistory([]);
const focusInput = () => {
if (inputRef.current) inputRef.current.focus();
};
useEffect(() => {
if(containerRef && containerRef.current) containerRef.current.scrollTo(0, containerRef.current.scrollHeight);
}, [history]);
return (<div className={styles.container} ref={containerRef}>
<REPLHistory history={history} inputRef={inputRef} />
<REPLInput historyCallback={onCommandExecuted} historyClear={onClearHistory} inputRef={inputRef} />
<div style={{flexGrow: 2}} onClick={focusInput}></div>
</div>);
};
export default REPL;
@@ -1,18 +0,0 @@
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: any) => void;
onContentReady?: () => 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 };
-19
View File
@@ -1,19 +0,0 @@
import Icon from "@mdi/react";
import { mdiSeal, mdiRobotIndustrial } from "@mdi/js";
interface Achievement {
description: string;
icon: JSX.Element;
}
export const achievements = (size?: string): Achievement[] => [
{
"description": "Awarded with the Deutschlandstipendium",
"icon": <Icon path={mdiSeal} size={size || "2em"} id="mdi_achievement_stip" />
}, {
"description": "Developer of the official testbed for Digital Twins in Industry 4.0 of the TU Dresden",
"icon": <Icon path={mdiRobotIndustrial} size={size || "2em"} id="mdi_achievement_i40" />
}
];
export default achievements;
-216
View File
@@ -1,216 +0,0 @@
import Icon from "@mdi/react";
import { mdiBash, mdiLanguageCpp, mdiLanguageCsharp, mdiLanguageJava, mdiLanguageJavascript, mdiLanguagePhp, mdiLanguagePython, mdiLanguageRust, mdiLanguageTypescript, mdiReact, mdiTranslateVariant, mdiDatabaseSearch } from "@mdi/js";
import { Android, Arduino, CssThree, Espressif, Express, Html5, Linux, Sass, Springboot, Windows } from "@icons-pack/react-simple-icons";
export interface Skill {
name: string;
icon?: JSX.Element;
pct: number;
}
export interface AdditionalSkill {
name: string;
icon?: JSX.Element;
}
export interface CardColors {
background: string;
bars: string;
heading: string;
useDarkColor: boolean;
badges?: {
background: string;
useDarkColor: boolean;
}
}
export interface SkillCard {
title: string;
skillBars: Skill[];
additional?: AdditionalSkill[];
colors?: CardColors;
}
export interface SkillSet {
cards: SkillCard[];
additional?: AdditionalSkill[];
}
export const skills = (sizeCardIcons?: string, sizeBadgeIcons?: string): SkillSet => {
sizeCardIcons = sizeCardIcons || "2em";
sizeBadgeIcons = sizeBadgeIcons || "1em";
return {
cards: [{
title: "Programming Languages",
skillBars: [{
name: "TypeScript",
icon: <Icon path={mdiLanguageTypescript} size={sizeCardIcons} id="mdi_skills_prog_ts" />,
pct: 100
}, {
name: "JavaScript",
icon: <Icon path={mdiLanguageJavascript} size={sizeCardIcons} id="mdi_skills_prog_js" />,
pct: 100
}, {
name: "Java",
icon: <Icon path={mdiLanguageJava} size={sizeCardIcons} id="mdi_skills_prog_java" />,
pct: 80
}, {
name: "Python 3",
icon: <Icon path={mdiLanguagePython} size={sizeCardIcons} id="mdi_skills_prog_python" />,
pct: 95
}, {
name: "PHP",
icon: <Icon path={mdiLanguagePhp} size={sizeCardIcons} id="mdi_skills_prog_php" />,
pct: 50
}, {
name: "Bash",
icon: <Icon path={mdiBash} size={sizeCardIcons} id="mdi_skills_prog_bash" />,
pct: 60
}, {
name: "C/C++",
icon: <Icon path={mdiLanguageCpp} size={sizeCardIcons} id="mdi_skills_prog_c" />,
pct: 60
}, {
name: "Rust",
icon: <Icon path={mdiLanguageRust} size={sizeCardIcons} id="mdi_skills_prog_rust" />,
pct: 80
}, {
name: "C#",
icon: <Icon path={mdiLanguageCsharp} size={sizeCardIcons} id="mdi_skills_prog_cs" />,
pct: 70
}],
additional: [{
name: "SQL Languages",
icon: <Icon path={mdiDatabaseSearch} size={sizeBadgeIcons} id="mdi_skills_prog_sql" />
}],
colors: {
background: "#C3A3F7",
bars: "#8771AB",
heading: "#55476B",
useDarkColor: true,
badges: {
background: "#55476B",
useDarkColor: false,
}
}
}, {
title: "Web Technologies",
skillBars: [{
name: "TypeScript",
icon: <Icon path={mdiLanguageTypescript} size={sizeCardIcons} id="mdi_skills_web_ts" />,
pct: 100
}, {
name: "JavaScript",
icon: <Icon path={mdiLanguageJavascript} size={sizeCardIcons} id="mdi_skills_web_js" />,
pct: 100
}, {
name: "React",
icon: <Icon path={mdiReact} size={sizeCardIcons} id="mdi_skills_web_react" />,
pct: 80
}, {
name: "HTML5",
icon: <Html5 size={sizeCardIcons} id="mdi_skills_web_html" />,
pct: 80
}, {
name: "CSS3",
icon: <CssThree size={sizeCardIcons} id="mdi_skills_web_css" />,
pct: 90
}],
additional: [{
name: "Express",
icon: <Express size={sizeBadgeIcons} />
}, {
name: "Sass",
icon: <Sass size={sizeBadgeIcons} />
}, {
name: "Spring Boot",
icon: <Springboot size={sizeBadgeIcons} />
}],
colors: {
background: "#A4C7EA",
bars: "#706EB8",
heading: "#2A2885",
useDarkColor: true,
badges: {
background: "#2A2885",
useDarkColor: false,
}
}
}, {
title: "Embedded Programming",
skillBars: [{
name: "C/C++",
icon: <Icon path={mdiLanguageCpp} size={sizeCardIcons} id="mdi_skills_embedded_c" />,
pct: 60
}],
additional: [{
name: "Arduino",
icon: <Arduino size={sizeBadgeIcons} />
}, {
name: "ESP",
icon: <Espressif size={sizeBadgeIcons} />
}],
colors: {
background: "#EA8585",
bars: "#E53E3E",
heading: "#661C1C",
useDarkColor: true,
badges: {
background: "#661C1C",
useDarkColor: false,
}
}
}, {
title: "Operating Systems",
skillBars: [],
additional: [{
name: "Windows",
icon: <Windows size={sizeBadgeIcons} />
}, {
name: "Linux",
icon: <Linux size={sizeBadgeIcons} />
}, {
name: "Android",
icon: <Android size={sizeBadgeIcons} />
}],
colors: {
background: "#4DEB8C",
bars: "#38AB66",
heading: "#236B40",
useDarkColor: true,
badges: {
background: "#236B40",
useDarkColor: false
}
}
}, {
title: "Languages",
skillBars: [{
name: "German (native)",
icon: <Icon path={mdiTranslateVariant} size={sizeCardIcons} id="mdi_skills_lang_de" />,
pct: 100
}, {
name: "English (C1)",
icon: <Icon path={mdiTranslateVariant} size={sizeCardIcons} id="mdi_skills_lang_en" />,
pct: 90
}, {
name: "Russian (basics)",
icon: <Icon path={mdiTranslateVariant} size={sizeCardIcons} id="mdi_skills_lang_ru" />,
pct: 30
}],
colors: {
background: "#EB783F",
bars: "#AB582E",
heading: "#6B371D",
useDarkColor: true,
badges: {
background: "#6B371D",
useDarkColor: false,
}
}
}]
};
};
export default skills;
-43
View File
@@ -1,43 +0,0 @@
import { Github, Linkedin, Instagram, Discord, Steam } from "@icons-pack/react-simple-icons";
import Icon from "@mdi/react";
import { mdiEmailLock } from "@mdi/js";
interface Social {
name: string;
url: string;
icon: JSX.Element;
}
export const socials = (iconSize?: string, color?: string): Social[] => {
iconSize = iconSize || "1em";
return [
{
name: "GitHub",
url: "https://github.com/C0ntroller",
icon: <Github size={iconSize} title="GitHub" color={color} />,
}, {
name: "LinkedIn",
url: "https://www.linkedin.com/in/c0ntroller/",
icon: <Linkedin size={iconSize} title="Linked" color={color} />,
}, {
name: "Instagram",
url: "https://www.instagram.com/c0ntroller/",
icon: <Instagram size={iconSize} title="Instagram" color={color} />,
}, {
name: "Steam",
url: "https://steamcommunity.com/id/c0ntroller/",
icon: <Steam size={iconSize} title="Steam" color={color} />,
}, {
name: "Discord",
url: "https://discordapp.com/users/224208617820127233",
icon: <Discord size={iconSize} title="Discord" color={color} />
}, {
name: "PGP Key",
url: "/files/pubkey.pgp",
icon: <Icon path={mdiEmailLock} size={iconSize} title="PGP Key" color={color} />
}
];
};
export default socials;
-30
View File
@@ -1,30 +0,0 @@
version: '3'
services:
server:
image: localhost:5000/c0ntroller.de:dev
restart: always
volumes:
# Relative paths are located in the tmp folder where the project is cloned
- /srv/website-dev/content:/app/public/content:ro
- git_mask:/app/public/content/.git
networks:
- traefik
labels:
- "traefik.enable=true"
- "traefik.docker.network=traefik"
- "traefik.http.routers.website-dev.entrypoints=websecure"
- "traefik.http.routers.website-dev.rule=Host(`dev.c0ntroller.de`)"
- "traefik.http.routers.website-dev.middlewares=secHeaders@file"
- "traefik.http.routers.website-dev.tls=true"
- "traefik.http.routers.website-dev.tls.certresolver=le"
- "traefik.http.routers.website-dev.service=website-dev"
- "traefik.http.services.website-dev.loadbalancer.server.port=3000"
environment:
- IS_DEV_ENV=true
networks:
traefik:
external: true
volumes:
git_mask:
-30
View File
@@ -1,30 +0,0 @@
version: '3'
services:
server:
image: localhost:5000/c0ntroller.de:latest
restart: always
volumes:
# Relative paths are located in the tmp folder where the project is cloned
- /srv/website/content:/app/public/content:ro
- git_mask:/app/public/content/.git
networks:
- traefik
labels:
- "traefik.enable=true"
- "traefik.docker.network=traefik"
- "traefik.http.routers.website-stable.entrypoints=websecure"
- "traefik.http.routers.website-stable.rule=Host(`c0ntroller.de`) || Host(`www.c0ntroller.de`)"
- "traefik.http.routers.website-stable.middlewares=secHeaders@file"
- "traefik.http.routers.website-stable.tls=true"
- "traefik.http.routers.website-stable.tls.certresolver=le"
- "traefik.http.routers.website-stable.service=website-stable"
- "traefik.http.services.website-stable.loadbalancer.server.port=3000"
environment:
- IS_DEV_ENV=true
networks:
traefik:
external: true
volumes:
git_mask:
-40
View File
@@ -1,40 +0,0 @@
import Color from "color";
export function getColors() {
const replColor = window.document.documentElement.style.getPropertyValue("--repl_color") || window.getComputedStyle(document.documentElement).getPropertyValue("--repl_color") || "rgb(24, 138, 24)";
const linkColor = window.document.documentElement.style.getPropertyValue("--repl_color-link") || window.getComputedStyle(document.documentElement).getPropertyValue("--repl_color-link") || "rgb(31, 179, 31)";
const hintColor = window.document.documentElement.style.getPropertyValue("--repl_color-hint") || window.getComputedStyle(document.documentElement).getPropertyValue("--repl_color-hint") || "rgba(24, 138, 24, 0.3)";
return [replColor, linkColor, hintColor];
};
export function setColors(color: Color) {
window?.document.documentElement.style.setProperty("--repl_color", color.string());
window?.document.documentElement.style.setProperty("--repl_color-link", color.lighten(0.3).rgb().string());
window?.document.documentElement.style.setProperty("--repl_color-hint", color.fade(0.7).string());
};
export class Rainbow {
color: Color;
step: number = 5;
runner: any = undefined;
constructor() {
this.color = new Color("hsl(0, 100%, 50%)");
}
next() {;
this.color = this.color.rotate(this.step);
setColors(this.color);
}
start() {
this.runner = setInterval(() => this.next(), 100);
}
stop() {
clearInterval(this.runner);
this.runner = undefined;
}
}
export default new Rainbow();
-14
View File
@@ -1,14 +0,0 @@
import { createContext, useContext } from "react";
import type { PropsWithChildren } from "react";
import { CommandInterface } from ".";
import type { ContentList } from "../content/types";
import type { CommandInterfaceCallbacks } from "./types";
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 };
-415
View File
@@ -1,415 +0,0 @@
import type { Diary, Project } from "../content/types";
import type { Command, Flag } from "./types";
import Color from "color";
import { getColors, setColors } from "../colors";
import Rainbow from "../colors";
import styles from "../../styles/Terminal/Random.module.scss";
function getCommandByName(name: string): Command | undefined {
return commandList.find(cmd => cmd.name === name);
}
/*function illegalUse(raw: string, cmd: Command): string[] {
return [
"Syntax error!",
`Cannot parse "${raw}"`,
""
].concat(printSyntax(cmd));
}*/
/*function checkFlags(flags: string[], cmd: Command): boolean {
if (!flags || flags.length === 0) return true;
if (!cmd.flags) return false;
for (const flag of flags) {
const isLong = flag.substring(0, 2) === "--";
const flagObj = Object.values(cmd.flags).find(f => isLong ? f.long === flag.substring(2) : f.short === flag.substring(1));
if (!flagObj) return false;
}
return true;
}*/
/*function checkSubcmd(subcmds: string[], cmd: Command): boolean {
if (!subcmds || subcmds.length === 0) return true;
if (!cmd.subcommands) return false;
for (const sc of subcmds) {
const flagObj = Object.values(cmd.subcommands).find(s => s.name === sc);
if (!flagObj) return false;
}
return true;
}*/
function checkFlagInclude(flagsProvided: string[], flag: Flag): boolean {
if (!flag) return false;
return flagsProvided.includes(`-${flag.short}`) || flagsProvided.includes(`--${flag.long}`);
}
export function printSyntax(cmd: Command): string[] {
let flagsOption = "";
let flagsDesc = [];
if (cmd.flags && Object.keys(cmd.flags).length > 0) {
flagsOption = " [";
flagsDesc.push("");
flagsDesc.push("Flags:");
Object.values(cmd.flags).forEach((flag => {
flagsOption += `-${flag.short} `;
flagsDesc.push(`\t-${flag.short}\t--${flag.long}\t${flag.desc}`);
}));
flagsOption = flagsOption.substring(0, flagsOption.length - 1) + "]";
}
let subcmdOption = "";
let subcmdDesc = [];
if (cmd.subcommands && Object.keys(cmd.subcommands).length > 0) {
subcmdOption = " [";
subcmdDesc.push("");
subcmdDesc.push("Arguments:");
Object.values(cmd.subcommands).forEach((subcmd => {
subcmdOption += `${subcmd.name}|`;
subcmdDesc.push(`\t${subcmd.name}\t${subcmd.desc}`);
}));
subcmdOption = subcmdOption.substring(0, subcmdOption.length - 1) + "]";
}
return [`Usage: ${cmd.name}${flagsOption}${subcmdOption}`].concat(flagsDesc).concat(subcmdDesc);
}
const about: Command = {
name: "about",
desc: "Show information about this page.",
execute: () => {
return [
"Hello there wanderer.",
"So you want to know what this is about?",
"",
"Well, the answer is pretty unspectecular:",
"This site presents some stuff that me, a human, created.",
"If you look arround you can read about my various projects.",
"",
"The navigation is done via this console interface.",
"Even when you open a project page you don't need your mouse - just press Esc to close it.",
"",
"I hope you enjoy your stay here!",
"If you want to know more about the creation of this page, type %{project this}.",
"",
"If you are kind of lost what to do, type %{help --this}."
];
}
};
const help: Command = {
name: "help",
desc: "Shows helptext.",
flags: { more: { long: "this", short: "t", desc: "Show information about this site." } },
execute: (flags) => {
if (help.flags && checkFlagInclude(flags, help.flags.more)) {
return [
"Hello user!",
"What you see here should resemble a CLI. If you ever used Linux this should be pretty easy for you.",
"",
"Everyone else: Have no fear. It is pretty simple.",
"You just type in commands and the output is shown here or it does something on the webite.",
"To find out, which commands are available, you can type %{help}.",
"",
"When wanting to know how to use a command, type %{man <command>} or %{<command> --help}.",
"",
"Have fun!"
];
} else {
const available = ["Available commands:"];
commandList.filter(cmd => !cmd.hidden).forEach(cmd => available.push(`\t${cmd.name}\t${cmd.desc}`));
available.push("");
available.push("Need help about the general usage? Type %{help --this}!");
return available;
}
}
};
const man: Command = {
name: "man",
desc: "Provides a manual for a command.",
subcommands: {
command: { name: "command", desc: "Name of a command" }
},
execute: (_flags, args) => {
if (args.length !== 1) {
return printSyntax(man);
} else {
const cmd = getCommandByName(args[0]);
if (!cmd) return [`Cannot find command '${args[0]}'.`];
else return printSyntax(cmd);
}
}
};
const project: Command = {
name: "project",
desc: "Show information about a project.",
flags: {
minimal: { short: "m", long: "minimal", desc: "Only show minimal information." },
source: { short: "s", long: "source", desc: "Open git repository of project." },
list: { short: "l", long: "list", desc: "\tShow list of projects." }
},
subcommands: { name: { name: "name", desc: "Name of the project." }, page: {name: "page", desc: "Page of the diary (only for diaries; 0 is mainpage)."} },
execute: (flags, args, _raw, cmdIf) => {
if (project.flags && checkFlagInclude(flags, project.flags.list)) {
const result = ["Found the following projects:"];
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:");
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;
}
if (args.length < 1 || args.length > 2) return printSyntax(project);
if (args[0] === "this") args[0] = "terminal";
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'."
];
if (project.flags && checkFlagInclude(flags, project.flags.source)) {
try {
window && window.open(pjt.repo, "_blank");
return ["Opened repository in new tab."];
} catch {
return ["Sorry, no repository for this project."];
}
}
if (project.flags && checkFlagInclude(flags, project.flags.minimal)) return pjt.desc;
const result: string[] = [];
let selectedPage: number|undefined = Number.parseInt(args[1] || "");
if (args[1]) {
if(Number.isNaN(selectedPage)) {
result.push("Invalid page number, ignoring it.");
selectedPage = undefined;
} else {
if (pjt.type !== "diary") {
result.push("This is not a diary, ignoring page.");
selectedPage = undefined;
} else {
if (selectedPage < 0 || selectedPage > pjt.entries.length) {
result.push("Invalid page number, ignoring it.");
selectedPage = undefined;
}
}
}
} else {
selectedPage = undefined;
}
if (cmdIf.callbacks?.setModalContent) cmdIf.callbacks.setModalContent(pjt, selectedPage);
if (cmdIf.callbacks?.setModalVisible) cmdIf.callbacks.setModalVisible(true);
return result;
}
};
const exitCmd: Command = {
name: "exit",
desc: "Tries to close this tab.",
execute: () => {
if (typeof window !== undefined) {
window.opener = null;
window.open("", "_self");
window.close();
window.history.back();
}
return [];
}
};
const clear: Command = {
name: "clear",
desc: "Clears the output on screen.",
execute: () => []
};
const color: Command = {
name: "color",
desc: "Changes the color of the site.",
subcommands: {
reset: { name: "reset", desc: "Resets the color." },
value: { name: "value", desc: "Any valid (css) color value." },
},
execute: (_flags, args, _raw, cmdIf) => {
if (!window || !window.document) return [];
if (args.length === 0) {
const colors = getColors();
return [
"Current colors:",
`Text:\t\t${colors[0]}`,
`Links:\t\t${colors[1]}`,
`Completion:\t${colors[2]}`
];
}
if (args[0] === "reset") {
Rainbow.stop();
window.document.documentElement.style.removeProperty("--repl_color");
window.document.documentElement.style.removeProperty("--repl_color-link");
window.document.documentElement.style.removeProperty("--repl_color-hint");
return ["Color reset."];
} else {
let color: Color;
try {
color = Color(args.join(" ").trim());
} catch {
return ["Invalid color!"];
}
Rainbow.stop();
setColors(color);
switch(true) {
case color.hex().toLowerCase() === "#1f1e33": {
if (cmdIf.callbacks?.setModalHTML && cmdIf.callbacks?.setModalVisible) {
cmdIf.callbacks?.setModalHTML(`
<div class="${styles.modalVideoContainer}">
<iframe width="100%" height="100%" src="https://www.youtube-nocookie.com/embed/w4U9S5eX3eY" title="YouTube video player" frameborder="0" allow="autoplay; clipboard-write; encrypted-media; picture-in-picture" allowfullscreen></iframe>
</div>`);
cmdIf.callbacks?.setModalVisible(true);
}
break;
}
}
return ["Color set | #{Link|#} | %{help}"];
}
}
};
const save: Command = {
name: "save",
desc: "Saves the current color and command history to local storage.",
subcommands: {
clear: { name: "clear", desc: "Clear the saved data." },
confirm: { name: "confirm", desc: "You explicitly confirm, you allow saving to the local storage." },
},
flags: {
color: { short: "c", long: "color", desc: "Only save the color." },
history: { short: "h", long: "history", desc: "Only save the history." },
},
execute: (flags, args, _raw, cmdIf) => {
const defaultRet = [
"You can save the current color and command history to local storage.",
"To do so, use %{save confirm}.",
"By using this command above you agree on saving the non-functional data to local storage.",
"The data will never leave your computer!"
];
if (args.length === 0) {
return defaultRet;
} else if (args[0] === "clear") {
window.localStorage.clear();
return ["Colors and history removed from storage."];
} else if (args[0] === "confirm") {
const saveColor = save.flags && checkFlagInclude(flags, save.flags.color);
const saveHistory = save.flags && checkFlagInclude(flags, save.flags.history);
const saveAll = !saveColor && !saveHistory;
const result = [];
if (saveColor || saveAll) {
const currentColors = getColors();
const color = new Color(currentColors[0]);
if(color.contrast(new Color("#000")) < 1.1 || color.alpha() < 0.1) result.push("Skipping saving the color because it's too dark.");
else {
window.localStorage.setItem("color", currentColors[0]);
result.push("Color saved to local storage.");
}
}
if (saveHistory || saveAll) {
const history = cmdIf.callbacks?.getCmdHistory ? cmdIf.callbacks.getCmdHistory() : [];
window.localStorage.setItem("history", JSON.stringify(history));
result.push("History saved to storage.");
}
return result;
} else {
return printSyntax(save);
}
},
};
const pingi: Command = {
name: "pingi",
desc: "<3",
execute: (_flags, _args, _raw, cmdIf) => {
const pingiImg = [
"hJQFR4dpyyZskjmbAkvlnNYi",
"LjwTg8qftDGLDfYyNH5OMY6L",
"niaM6yPxKBQV8umkh0xpkbCH",
"7hcMiKlbn9QWNbwA3DFcpk6A",
"xFnQEWlO5jqvJ4lruK4C8zfq",
"CplNRTMYuwmSW8WH2UxCi5NU",
"oQ03IzrBkLwCwsUtdp3zn0nW",
"36zkZSuWmhAa89ErDR4myYW0",
"HZvdYHr4fqYRTkTn8zw4akjA",
"VdTAABUXCpo5Gom7aszQDw1c",
"zwIJwof4beiqDiy3PBkYmZYd"
];
if (cmdIf.callbacks?.setModalHTML && cmdIf.callbacks.setModalVisible) {
const img = pingiImg[Math.floor(Math.random()*pingiImg.length)];
cmdIf.callbacks.setModalHTML(`
<a href="https://labs.openai.com/s/${img}" target="_blank" rel="noreferrer" class="${styles.modalImageContainerSquare}">
<span class="${styles.imgLoading}">Loading cute image...</span>
<img src="https://openai-labs-public-images-prod.azureedge.net/user-jomUNcw4rd0bDGfcOQUAbYNO/generations/generation-${img}/image.webp" alt="Incredibly cute AI created image of a penguin and a rabbit." />
</a>
<small><i>Made with DALL-E</i></small>`);
cmdIf.callbacks.setModalVisible(true);
}
return ["<3"];
},
hidden: true
};
const blahaj: Command = {
name: "blahaj",
desc: "Blahaj is the best.",
execute: () => {
setColors(Color("#417988"));
return [" _________ . .",
"(.. \\_ , |\\ /|",
" \\ O \\ /| \\ \\/ / ",
" \\______ \\/ | \\ / ",
" vvvv\\ \\ | / |",
" \\^^^^ == \\_/ |",
" `\\_ === \\. |",
" / /\\_ \\ / |",
" |/ \\_ \\| /",
" \\________/" ];
},
hidden: true
};
const ping: Command = {
name: "ping",
desc: "Ping!",
execute: () => {
return ["Pong!"];
},
};
const jeb_: Command = {
name: "jeb_",
desc: "🐑🌈",
execute: () => {
Rainbow.start();
return [];
},
hidden: true
};
export const commandList = [about, help, man, project, exitCmd, clear, color, save, pingi, blahaj, ping, jeb_].sort((a, b) => a.name.localeCompare(b.name));
-41
View File
@@ -1,41 +0,0 @@
import type { ContentList } from "../content/types";
import { printSyntax, commandList } from "./definitions";
import { CommandInterfaceCallbacks } from "./types";
export class CommandInterface {
callbacks?: CommandInterfaceCallbacks;
content: ContentList = [];
constructor(callbacks?: CommandInterfaceCallbacks, content?: ContentList) {
this.callbacks = callbacks;
this.content = content || [];
}
static commandCompletion(input: string): string[] {
if (input === "") return [];
const candidates = commandList.filter(cmd => !cmd.hidden && cmd.name.startsWith(input)).map(cmd => cmd.name);
return candidates;
}
executeCommand(command: string): string[] {
if (!command) return [`$ ${command}`].concat(this.illegalCommand(command));
const args = command.split(" ");
const cmd = commandList.find(cmd => cmd.name === args[0]);
if (!cmd) return [`$ ${command}`].concat(this.illegalCommand(command));
const parsed = this.seperateFlags(args.splice(1));
const result = parsed.flags.includes("--help") || parsed.flags.includes("-?") ? printSyntax(cmd) : cmd.execute(parsed.flags, parsed.subcmds, command, this);
return [`$ ${command}`].concat(result);
}
private seperateFlags(args: string[]): {flags: string[], subcmds: string[]} {
const flags = args.filter(arg => arg.substring(0,1) === "-");
const subcmds = args.filter(arg => arg.substring(0,1) !== "-");
return {flags, subcmds};
}
private illegalCommand(command: string): string[] {
return [`Command '${command}' not found.`, "Type 'help' for help."];
}
}
-29
View File
@@ -1,29 +0,0 @@
import type { CommandInterface } from ".";
import type { Diary, Project } from "../content/types";
export interface Flag {
short: string;
long: string;
desc: string;
}
interface SubCommand {
name: string;
desc: string;
}
export interface Command {
name: string;
hidden?: boolean;
desc: string;
flags?: Record<string,Flag>;
subcommands?: Record<string,SubCommand>;
execute: (flags: string[], args: string[], raw: string, cmdIf: CommandInterface) => string[];
}
export interface CommandInterfaceCallbacks {
setModalVisible?: (visible: boolean) => void;
setModalContent?: (content: Project | Diary, selectedPage?: number) => void;
setModalHTML?: (html: any) => void;
getCmdHistory?: () => string[];
}
-174
View File
@@ -1,174 +0,0 @@
// This file is used to generate the HTML for the projects and diaries in the backend.
// We can use fs and stuff here.
import { Dirent, readdirSync } from "fs";
import { readFile } from "node:fs/promises";
import { resolve } from "path";
import { JSDOM } from "jsdom";
import type { Project, Diary } from "./types";
import asciidoctor from "asciidoctor";
// Code Highlighting
import hljs from "highlight.js";
import rust from "highlight.js/lib/languages/rust";
import bash from "highlight.js/lib/languages/shell";
hljs.registerLanguage("rust", rust);
hljs.registerLanguage("bash", bash);
hljs.registerLanguage("console", bash);
hljs.registerLanguage("shell", bash);
interface APISuccess {
type: "success";
html: string;
date: string;
repoUrl: string;
}
interface APIError {
type: "error";
html: string;
}
export type APIReturn = APISuccess | APIError;
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();
const listPath = resolve("./public", "content", "list.json");
const projectPath = resolve("./public", "content", "projects");
const diaryPath = resolve("./public", "content", "diaries");
// Error catching as this is evaluated at build time
let pf: Dirent[] = [];
let df: Dirent[] = [];
try { pf = readdirSync(projectPath, { withFileTypes: true }).filter((f) => f.isFile() && f.name.endsWith(".adoc")) }
catch {}
// As we need the diaries too, no filter here
try { df = readdirSync(diaryPath, { withFileTypes: true }) }
catch {}
const projectFiles = pf;
const diaryFiles = df;
export async function getContentList() {
try {
const list = await readFile(listPath, { encoding: "utf-8" });
return JSON.parse(list);
} catch (e) {
console.error(e);
return [];
}
}
export async function generateContent(content: Project|Diary, selectedPage?: number, api: boolean = false): Promise<string|APIReturn> {
if(!content) return api ? {type: "error", html: projectEmpty} : projectEmpty;
switch (content.type) {
case "project": return await generateProjectHTML(content, api);
case "diary": return await generateDiaryHTML(content, selectedPage, api);
default: return projectNotFoundHtml;
}
}
async function generateProjectHTML(project: Project, api: boolean = false): Promise<string|APIReturn> {
// First we test if the file exist
if(!projectFiles.find((f) => f.name === `${project.name}.adoc`)) return api ? { type: "error", html: projectNotFoundHtml } : projectNotFoundHtml;
// Resolve the path
const path = resolve(projectPath, `${project.name}.adoc`);
try {
// Read the file
const rawAd = await readFile(path, { encoding: "utf-8" });
// Correct the paths so that the images are loaded correctly
const pathsCorrected = rawAd.replace(/(image[:]+)(.*\.[a-zA-Z]+)\[/g, "$1/content/projects/$2[");
const adDoc = ad.load(pathsCorrected, { attributes: { showtitle: true } });
// Convert to HTML
const converted = adDoc.convert(adDoc).toString();
// For the API we want the HTML and the date only
if (api) return {
type: "success",
html: converted,
date: new Date(adDoc.getAttribute("docdatetime")).toISOString(),
repoUrl: `https://git.c0ntroller.de/c0ntroller/frontpage-content/src/branch/${process.env.IS_DEV ? "dev" : "senpai"}/projects/${project.name}.adoc`,
};
// Return and add the footer
return `${converted}
<hr>
<div id="footer">
<div id="footer-text">
Last updated: ${new Date(adDoc.getAttribute("docdatetime")).toLocaleString()} | <a href="https://git.c0ntroller.de/c0ntroller/frontpage-content/src/branch/${process.env.IS_DEV ? "dev" : "senpai"}/projects/${project.name}.adoc" target="_blank">Document source</a>
</div>
</div>`;
} catch (e) {
// Something gone wrong
console.error(e);
return api ? { type: "error", html: projectServerErrorHtml } : projectServerErrorHtml;
}
}
async function generateDiaryHTML(diary: Diary, selectedPage?: number, api: boolean = false): Promise<string|APIReturn> {
// First we test if the file exist
if(!diaryFiles.find((f) => f.isFile() && f.name === `${diary.name}.adoc`)) return api ? { type: "error", html: projectNotFoundHtml } : projectNotFoundHtml;
// First we need the page number and the path to load
const page: number = Number.parseInt(selectedPage?.toString() || "0") - 1;
// If the page number is not -1, a directory must exist
if (page !== -1 && !diaryFiles.find((f) => f.isDirectory() && f.name === diary.name)) return api ? { type: "error", html: projectNotFoundHtml } : projectNotFoundHtml;
// Next we load the correct path
const path = page === -1 ? resolve(diaryPath, `${diary.name}.adoc`) : resolve(diaryPath, diary.name, `${diary.entries[page].filename}.adoc`);
try {
// Read the file
const rawAd = await readFile(path, { encoding: "utf-8" });
// Correct the paths so that the images are loaded correctly
const pathsCorrected = rawAd.replace(/(image[:]{1,2})(.*\.[a-zA-Z]+)\[/g, "$1/content/diaries/$2[");
const adDoc = ad.load(pathsCorrected, { attributes: { showtitle: true } });
const gitfile = page === -1 ? `${diary.name}.adoc` : `${diary.name}/${diary.entries[page].filename}.adoc`;
// Convert to HTML
const converted = adDoc.convert(adDoc).toString();
// For the API we want the HTML and the date only
if (api) return {
type: "success",
html: converted,
date: new Date(adDoc.getAttribute("docdatetime")).toISOString(),
repoUrl: `https://git.c0ntroller.de/c0ntroller/frontpage-content/src/branch/${process.env.IS_DEV ? "dev" : "senpai"}/diaries/${gitfile}`,
};
// Return and add the footer
return `${converted}
<hr>
<div id="footer">
<div id="footer-text">
Last updated: ${new Date(adDoc.getAttribute("docdatetime")).toLocaleString()} | <a href="https://git.c0ntroller.de/c0ntroller/frontpage-content/src/branch/${process.env.IS_DEV ? "dev" : "senpai"}/diaries/${gitfile}" target="_blank">Document source</a>
</div>
</div>`;
} catch (e) {
// Something gone wrong
console.error(e);
return api ? { type: "error", html: projectServerErrorHtml } : projectServerErrorHtml;
}
}
export function prepareDOM(html: string) {
const dom = (new JSDOM(html)).window.document;
dom.querySelectorAll("pre code").forEach((block) => {
hljs.highlightElement(block as HTMLElement);
});
dom.querySelectorAll("a[href^='#']").forEach((link) => {
(link as HTMLAnchorElement).href = `/blog/${(link as HTMLAnchorElement).href.split("#")[1]}`;
});
return dom.body.innerHTML;
}
-54
View File
@@ -1,54 +0,0 @@
// This file is used for the generation of the static HTML files in the frontend.
// It is used by the terminal.
import type { Project, Diary } from "./types";
import type { APIReturn } from "./generateBackend";
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>`;
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(`/api/contentRendering?name=${project.name}`);
if (resp.status !== 200) return projectServerErrorHtml;
const response = await resp.json() as APIReturn;
if (!response || !response.type) return projectServerErrorHtml;
if (response.type === "error") return response.html;
else {
return `${response.html}
<hr>
<div id="footer">
<div id="footer-text">
Last updated: ${new Date(response.date).toLocaleString()} | <a href="${response.repoUrl}" target="_blank">Document source</a>
</div>
</div>`;
}
}
async function generateDiaryHTML(diary: Diary, selectedPage?: number): Promise<string> {
const url = `/api/contentRendering?name=${diary.name}${selectedPage ? `&page=${selectedPage}` : ""}`;
const resp = await fetch(url);
const response = await resp.json() as APIReturn;
if (!response || !response.type) return projectServerErrorHtml;
if (response.type === "error") return response.html;
return `${response.html}
<hr>
<div id="footer">
<div id="footer-text">
Last updated: ${new Date(response.date).toLocaleString()} | <a href="${response.repoUrl}" target="_blank">Document source</a>
</div>
</div>`;
}
-36
View File
@@ -1,36 +0,0 @@
export type ContentList = (Project | Diary)[];
export type ContentType = "project" | "diary";
interface Content {
type: "project" | "diary";
name: string;
desc: string[];
short_desc: string;
more?: string;
repo?: string;
title: string;
}
export interface Project extends Content {
type: "project";
}
export interface DiaryEntry {
title: string;
filename: string;
}
export interface Diary extends Content {
type: "diary";
entries: DiaryEntry[];
}
export interface ProjectRender extends Project {
html: string;
}
export interface DiaryRender extends Diary {
html: string;
pageSelected: number;
}
-5
View File
@@ -1,5 +0,0 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
-14
View File
@@ -1,14 +0,0 @@
/** @type {import('next').NextConfig} */
module.exports = {
reactStrictMode: true,
images: {
domains: ["openai-labs-public-images-prod.azureedge.net"]
},
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
config.module.rules.push({
test: /\.adoc$/i,
loader: "raw-loader",
});
return config;
},
};
+11151 -6929
View File
File diff suppressed because it is too large Load Diff
+17 -31
View File
@@ -1,39 +1,25 @@
{
"name": "c0ntroller.de",
"private": true,
"name": "website-astro",
"type": "module",
"version": "0.0.1",
"scripts": {
"dev": "npx next dev",
"build": "npx next build",
"start": "npx next start",
"lint": "npx next lint"
"dev": "astro dev",
"start": "astro dev",
"build": "astro check && astro build",
"preview": "astro preview",
"astro": "astro"
},
"dependencies": {
"@icons-pack/react-simple-icons": "^5.10.0",
"@mdi/js": "^7.0.96",
"@mdi/react": "^1.6.1",
"asciidoctor": "^2.2.5",
"color": "^4.2.3",
"highlight.js": "^11.5.1",
"jsdom": "^20.0.1",
"next": "12.1.0",
"next-themes": "^0.2.1",
"node-fetch": "^3.2.0",
"random-seed": "^0.3.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"sharp": "^0.31.1"
"@astrojs/check": "^0.3.1",
"@astrojs/mdx": "^1.1.5",
"astro": "^3.6.0",
"astro-icon": "^0.8.1",
"sass": "^1.69.5",
"typescript": "^5.3.2"
},
"devDependencies": {
"@types/color": "^3.0.3",
"@types/jsdom": "^20.0.0",
"@types/node": "16.11.11",
"@types/random-seed": "^0.3.3",
"@types/react": "17.0.37",
"@types/react-dom": "^18.0.5",
"eslint": "7.32.0",
"eslint-config-next": "12.0.4",
"raw-loader": "^4.0.2",
"sass": "^1.49.7",
"typescript": "4.5.2"
"@fec/remark-a11y-emoji": "^4.0.2",
"astro-themes": "^0.2.4",
"remark-code-extra": "^1.0.1"
}
}
-82
View File
@@ -1,82 +0,0 @@
import type { NextPage } from "next";
import Head from "next/head";
import Link from "next/link";
import styles from "../styles/Errorpage.module.css";
const svg = `
<svg viewBox="30 -20 450 280" x="0" y="0">
<!-- Box -->
<polygon points="100,70 170,0 370,50 370,180" style="fill:#b58747;" />
<defs>
<linearGradient id="shadow_grad1" x1="50%" y1="0%" x2="0%" y2="50%">
<stop offset="0%" style="stop-color:#876029;stop-opacity:1" />
<stop offset="100%" style="stop-color:#000000;stop-opacity:1" />
</linearGradient>
</defs>
<defs>
<linearGradient id="shadow_grad2" x1="0%" y1="0%" x2="50%" y2="100%">
<stop offset="0%" style="stop-color:#876029;stop-opacity:1" />
<stop offset="100%" style="stop-color:#000000;stop-opacity:1" />
</linearGradient>
</defs>
<polygon points="100,70 170,0 330,100 300,120" style="fill:#876029;fill:url(#shadow_grad1)" />
<polygon points="100,70 170,0 170,130 100,200, 100,70" style="fill:#876029;fill:url(#shadow_grad2)"/>
<line x1="170" y1="0" x2="370" y2="50" style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;"/>
<line x1="170" y1="0" x2="170" y2="130" style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;"/>
<!-- Katzenschweif -->
<path id="${styles.schweif}" d="M 280,120 C 250 100, 310 70, 320 20" style="fill:transparent;stroke:black;stroke-width:10;stroke-linecap:round" />
<!-- Box-linien -->
<polygon points="100,70 300,120 370,50 370,180 300,250 100,200" style="fill:#d19b4f;" />
<g style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;">
<line x1="100" y1="70" x2="100" y2="200" />
<line x1="100" y1="200" x2="300" y2="250" />
<line x1="300" y1="250" x2="300" y2="120" />
<line x1="100" y1="70" x2="300" y2="120" />
<line x1="300" y1="120" x2="370" y2="50" />
<line x1="300" y1="250" x2="370" y2="180" />
<line x1="370" y1="50" x2="370" y2="180" />
</g>
<!-- Lappen-rechts -->
<polygon points="300,120 350,150 420,80 370,50" style="fill:#b58747;" />
<g style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;">
<line x1="300" y1="120" x2="370" y2="50" />
<line x1="300" y1="120" x2="350" y2="150" />
<line x1="350" y1="150" x2="420" y2="80" />
<line x1="370" y1="50" x2="420" y2="80" />
</g>
<!-- Lappen-links -->
<polygon points="100,70 50,100 120,30 170,0" style="fill:#b58747;" />
<g style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;">
<line x1="100" y1="70" x2="170" y2="0" />
<line x1="100" y1="70" x2="50" y2="100" />
<line x1="50" y1="100" x2="120" y2="30" />
<line x1="170" y1="0" x2="120" y2="30" />
</g>
<!-- Text -->
<text x="120" y="120" style="font-size:4em;font-weight:bold;fill:#000000;transform:rotateX(40deg) rotateY(21deg);">404</text>
<!-- Killeraugen -->
<ellipse cx="275" cy="150" rx="32" ry="20" style="fill:#291e0f;transform:rotateZ(12deg)" />
<ellipse cx="266" cy="153" rx="7" ry="5" style="fill:#4a6b2a;transform:rotateZ(12deg)" />
<ellipse cx="266" cy="153" rx="2" ry="5" style="fill:#000000;transform:rotateZ(12deg)" />
<ellipse cx="285" cy="153" rx="7" ry="5" style="fill:#4a6b2a;transform:rotateZ(12deg)" />
<ellipse cx="285" cy="153" rx="2" ry="5" style="fill:#000000;transform:rotateZ(12deg)" />
<rect id="${styles.blinzeln}" width="40" height="22" x="255" y="139" style="fill:#291e0f;transform:rotateZ(12deg);" />
</svg>
`;
const Custom404: NextPage = () => {
return <>
<Head><title>Error 404 - c0ntroller.de</title></Head>
<div className={styles.container}>
<div id={styles.wrapper}>
<div id={styles.box} dangerouslySetInnerHTML={{__html: svg}}>
</div>
<div id={styles.errorText}>
The site you requested could not be found.<br/>
<Link href="/"><a>&gt; Back to the main page &lt;</a></Link>
</div>
</div>
</div></>;
};
export default Custom404;
-47
View File
@@ -1,47 +0,0 @@
import type { AppProps } from "next/app";
import Head from "next/head";
import { ThemeProvider } from "next-themes";
import "../styles/globals.scss";
import { CommandsProvider } from "../lib/commands/ContextProvider";
import { ModalFunctionProvider } from "../components/Terminal/contexts/ModalFunctions";
function MyApp({ Component, pageProps }: AppProps) {
return <>
<Head>
<meta charSet="utf-8" />
<meta name="description" content="This is the homepage of C0ntroller." />
<meta name="keyword" content="private, homepage, software, portfolio, development, cli, hacker, terminal, javascript, js, typescript, ts, nextjs, react, responsive" />
<meta name="author" content="C0ntroller" />
<meta name="copyright" content="C0ntroller" />
<meta name="robots" content="index,nofollow" />
<link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png" />
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png" />
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png" />
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png" />
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png" />
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png" />
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png" />
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png" />
<link rel="icon" type="image/png" sizes="192x192" href="/android-chrome-192x192.png" />
<link rel="icon" type="image/png" sizes="512x512" href="/android-chrome-512x512.png" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<link rel="manifest" href="/manifest.json" />
<meta name="msapplication-TileColor" content="#444444" />
<meta name="msapplication-TileImage" content="/mstile-310x310.png" />
<meta name="theme-color" content="#444444" />
</Head>
<ThemeProvider>
<CommandsProvider>
<ModalFunctionProvider>
<Component {...pageProps} />
</ModalFunctionProvider>
</CommandsProvider>
</ThemeProvider>
</>;
}
export default MyApp;
-13
View File
@@ -1,13 +0,0 @@
import { Html, Head, Main, NextScript } from "next/document";
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
-88
View File
@@ -1,88 +0,0 @@
import { NextPage, NextPageContext } from "next";
import Head from "next/head";
import Link from "next/link";
import styles from "../styles/Errorpage.module.css";
const Error: NextPage<{ statusCode?: number }> = ({ statusCode }) => {
const svg = `
<svg viewBox="30 -20 450 280" x="0" y="0">
<!-- Box -->
<polygon points="100,70 170,0 370,50 370,180" style="fill:#b58747;" />
<defs>
<linearGradient id="shadow_grad1" x1="50%" y1="0%" x2="0%" y2="50%">
<stop offset="0%" style="stop-color:#876029;stop-opacity:1" />
<stop offset="100%" style="stop-color:#000000;stop-opacity:1" />
</linearGradient>
</defs>
<defs>
<linearGradient id="shadow_grad2" x1="0%" y1="0%" x2="50%" y2="100%">
<stop offset="0%" style="stop-color:#876029;stop-opacity:1" />
<stop offset="100%" style="stop-color:#000000;stop-opacity:1" />
</linearGradient>
</defs>
<polygon points="100,70 170,0 330,100 300,120" style="fill:#876029;fill:url(#shadow_grad1)" />
<polygon points="100,70 170,0 170,130 100,200, 100,70" style="fill:#876029;fill:url(#shadow_grad2)"/>
<line x1="170" y1="0" x2="370" y2="50" style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;"/>
<line x1="170" y1="0" x2="170" y2="130" style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;"/>
<!-- Katzenschweif -->
<path id="${styles.schweif}" d="M 280,120 C 250 100, 310 70, 320 20" style="fill:transparent;stroke:black;stroke-width:10;stroke-linecap:round" />
<!-- Box-linien -->
<polygon points="100,70 300,120 370,50 370,180 300,250 100,200" style="fill:#d19b4f;" />
<g style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;">
<line x1="100" y1="70" x2="100" y2="200" />
<line x1="100" y1="200" x2="300" y2="250" />
<line x1="300" y1="250" x2="300" y2="120" />
<line x1="100" y1="70" x2="300" y2="120" />
<line x1="300" y1="120" x2="370" y2="50" />
<line x1="300" y1="250" x2="370" y2="180" />
<line x1="370" y1="50" x2="370" y2="180" />
</g>
<!-- Lappen-rechts -->
<polygon points="300,120 350,150 420,80 370,50" style="fill:#b58747;" />
<g style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;">
<line x1="300" y1="120" x2="370" y2="50" />
<line x1="300" y1="120" x2="350" y2="150" />
<line x1="350" y1="150" x2="420" y2="80" />
<line x1="370" y1="50" x2="420" y2="80" />
</g>
<!-- Lappen-links -->
<polygon points="100,70 50,100 120,30 170,0" style="fill:#b58747;" />
<g style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;">
<line x1="100" y1="70" x2="170" y2="0" />
<line x1="100" y1="70" x2="50" y2="100" />
<line x1="50" y1="100" x2="120" y2="30" />
<line x1="170" y1="0" x2="120" y2="30" />
</g>
<!-- Text -->
<text x="120" y="120" style="font-size:4em;font-weight:bold;fill:#000000;transform:rotateX(40deg) rotateY(21deg);">${statusCode ? statusCode : "???"}</text>
<!-- Killeraugen -->
<ellipse cx="275" cy="150" rx="32" ry="20" style="fill:#291e0f;transform:rotateZ(12deg)" />
<ellipse cx="266" cy="153" rx="7" ry="5" style="fill:#4a6b2a;transform:rotateZ(12deg)" />
<ellipse cx="266" cy="153" rx="2" ry="5" style="fill:#000000;transform:rotateZ(12deg)" />
<ellipse cx="285" cy="153" rx="7" ry="5" style="fill:#4a6b2a;transform:rotateZ(12deg)" />
<ellipse cx="285" cy="153" rx="2" ry="5" style="fill:#000000;transform:rotateZ(12deg)" />
<rect id="${styles.blinzeln}" width="40" height="22" x="255" y="139" style="fill:#291e0f;transform:rotateZ(12deg);" />
</svg>
`;
return <>
<Head><title>Error {statusCode} - c0ntroller.de</title></Head>
<div className={styles.container}>
<div id={styles.wrapper}>
<div id={styles.box} dangerouslySetInnerHTML={{ __html: svg }}>
</div>
<div id={styles.errorText}>
{ statusCode === 404 ? "The site you requested could not be found." : "An error occurred." }
<br />
<Link href="/"><a>&gt; Back to the main page &lt;</a></Link>
</div>
</div>
</div></>;
};
Error.getInitialProps = ({ res, err }: NextPageContext) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
return { statusCode };
};
export default Error;
-18
View File
@@ -1,18 +0,0 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { generateContent, getContentList } from "../../lib/content/generateBackend";
import type { APIReturn } from "../../lib/content/generateBackend";
import type { ContentList, Diary, Project } from "../../lib/content/types";
export default async function handler(req: NextApiRequest, res: NextApiResponse<string>) {
if (!req.query || !req.query.name) return res.status(400).end();
const list: ContentList = await getContentList();
if (!list) return res.status(500).end();
const content: Project | Diary | undefined = list.find((c) => c.name === req.query.name);
if (!content) return res.status(404).end();
const rendered = await generateContent(content, req.query.page ? parseInt(req.query.page as string) : undefined, true) as APIReturn;
res.status(200).json(JSON.stringify(rendered));
res.end();
}
-7
View File
@@ -1,7 +0,0 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
export default function handler(_req: NextApiRequest, res: NextApiResponse<string>) {
res.status(200).send("Pong!");
res.end();
}
-37
View File
@@ -1,37 +0,0 @@
import type { GetServerSideProps, NextPage } from "next";
import Layout from "../../../components/Blog/Layout";
import ContentPage from "../../../components/Blog/ContentPage";
import { generateContent, getContentList, prepareDOM } from "../../../lib/content/generateBackend";
import type { ContentList, DiaryRender, Diary } from "../../../lib/content/types";
const DiaryMain: NextPage<{ content: DiaryRender }> = ({ content }) => {
return <Layout title={`${content.title} - c0ntroller.de`}>
<ContentPage content={content} />
</Layout>;
};
export const getServerSideProps: GetServerSideProps = async (context) => {
const { did } = context.query;
const contentList = await getContentList();
const contentEntry: Diary | undefined = (contentList as ContentList).find((c) => c.name === did && c.type === "diary") as Diary | undefined;
if (!contentEntry) return { notFound: true };
const contentHtml = await generateContent(contentEntry) as string;
const contentPrepared = prepareDOM(contentHtml);
context.res.setHeader("Cache-Control", "public, s-maxage=3600, stale-while-revalidate=600");
return {
props: {
content: {
...contentEntry,
html: contentPrepared,
pageSelected: 0
}
}
};
};
export default DiaryMain;
-37
View File
@@ -1,37 +0,0 @@
import type { GetServerSideProps, NextPage } from "next";
import ContentPage from "../../../../components/Blog/ContentPage";
import Layout from "../../../../components/Blog/Layout";
import { generateContent, getContentList, prepareDOM } from "../../../../lib/content/generateBackend";
import type { ContentList, Diary, DiaryRender } from "../../../../lib/content/types";
const DiaryPage: NextPage<{ content: DiaryRender }> = ({ content }) => {
return <Layout title={`${content.entries[content.pageSelected - 1].title} - ${content.title} - c0ntroller.de`}>
<ContentPage content={content} />
</Layout>;
};
export const getServerSideProps: GetServerSideProps = async (context) => {
const { did, page } = context.query;
const contentList = await getContentList();
const contentEntry: Diary | undefined = (contentList as ContentList).find((c) => c.name === did && c.type === "diary") as Diary | undefined;
if (!contentEntry || !page || typeof page !== "string") return { notFound: true };
const contentHtml = await generateContent(contentEntry, Number.parseInt(page)) as string;
const contentPrepared = prepareDOM(contentHtml);
context.res.setHeader("Cache-Control", "public, s-maxage=3600, stale-while-revalidate=600");
return {
props: {
content: {
...contentEntry,
html: contentPrepared,
pageSelected: Number.parseInt(page)
}
}
};
};
export default DiaryPage;
-39
View File
@@ -1,39 +0,0 @@
import type { GetServerSideProps, NextPage } from "next";
import ContentPage from "../../../components/Blog/ContentPage";
import Layout from "../../../components/Blog/Layout";
import { generateContent, getContentList, prepareDOM } from "../../../lib/content/generateBackend";
import type { ContentList, ProjectRender } from "../../../lib/content/types";
const Post: NextPage<{ content: ProjectRender }> = ({ content }) => {
return <Layout title={`${content.title} - c0ntroller.de`}>
<ContentPage content={content} />
</Layout>;
};
export const getServerSideProps: GetServerSideProps = async (context) => {
const { pid } = context.query;
const contentList = await getContentList();
const contentEntry = (contentList as ContentList).find((c) => c.name === pid && c.type === "project");
if (!contentEntry) return { notFound: true };
const contentHtml = await generateContent(contentEntry) as string;
const contentPrepared = prepareDOM(contentHtml);
context.res.setHeader("Cache-Control", "public, s-maxage=3600, stale-while-revalidate=600");
return {
props: {
content: {
more: contentEntry.more || null,
repo: contentEntry.repo || null,
title: contentEntry.title,
html: contentPrepared,
}
}
};
};
export default Post;
-15
View File
@@ -1,15 +0,0 @@
import type { NextPage } from "next";
import Layout from "../components/Blog/Layout";
const Copyright: NextPage = () => {
return <Layout>
<h1>Copyright</h1>
<p>Unless otherwise stated, all content on this website is licensed under the <a className="nocolor" rel="noreferrer" target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> license.</p>
<p>The logo (the &quot;eye&quot;) and images of me are not licensed, all rights are reserved.</p>
<p>The <a className="nocolor" rel="noreferrer" target="_blank" href="https://materialdesignicons.com/">Material Design Icons</a> used on this website are licensed under the <a className="nocolor" rel="noreferrer" target="_blank" href="https://www.apache.org/licenses/LICENSE-2.0">Apache License 2.0</a>.</p>
<p>The <a className="nocolor" rel="noreferrer" target="_blank" href="">Simple Icons</a> used on this website are licensed under the <a className="nocolor" rel="noreferrer" target="_blank" href="https://creativecommons.org/publicdomain/zero/1.0/">CC0 1.0 Universal</a> license.</p>
<p>The <a className="nocolor" rel="noreferrer" target="_blank" href="https://sass-lang.com/">SASS Logo</a> used on this website is licensed under the <a className="nocolor" rel="noreferrer" target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/3.0/">CC BY-NC-SA 3.0</a> license.</p>
</Layout>;
};
export default Copyright;
-66
View File
@@ -1,66 +0,0 @@
import type { GetServerSideProps, NextPage } from "next";
import Link from "next/link";
import gen from "random-seed";
import Layout from "../components/Blog/Layout";
import type { ContentList, Project, Diary } from "../lib/content/types";
import ProjectCard from "../components/Blog/Card";
import { getContentList } from "../lib/content/generateBackend";
import styles from "../styles/Blog/Front.module.scss";
const Blog: NextPage<{ content: ContentList }> = ({content}) => {
const clearDescription = (description: string) => {
const linkRegex = /#%\{([a-z0-9 \.-\/:]*)\|([a-z0-9 \/:\.-]*)\}/ig;
const cmdRegex = /%\{([a-z0-9 \.-\/:]*)}/ig;
return description.replace(linkRegex, "$1").replace(cmdRegex, "\"$1\"");
};
const shuffleArray = (arr: any[]) => {
// We want shuffle but only between days
const date = new Date();
const generator = gen.create(`${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`);
// https://stackoverflow.com/a/6274381
for (let i = arr.length - 1; i > 0; i--) {
const j = generator.intBetween(0, i);
[arr[i], arr[j]] = [arr[j], arr[i]];
}
generator.done();
return arr;
};
const generateCards = (type: string) => {
return <div className={styles.contentList}>{
(shuffleArray(content.filter(p => p.type === type)) as (Project|Diary)[])
.map(p =>
<ProjectCard key={p.name} title={p.title} description={clearDescription(p.desc.join(" "))} type={p.type} name={p.name} />
)}
</div>;
};
return <Layout>
<h1>Hello there!</h1>
<p className={styles.frontText}>
Welcome to my website!<br/>
You can find here blog entries about some projects I did and some diaries where I document progress.<br/>
Interested in me? Visit the <Link href="/me"><a className="nocolor">About Me page</a></Link>, and you will find out more about me.<br/>
On the right of the navigation, you will find what used to be my website - a CLI you can play around with.<br/><br/>
Have fun!
</p>
<h2>Projects</h2>
{ generateCards("project") }
<h2>Diaries</h2>
{ generateCards("diary") }
</Layout>;
};
export const getServerSideProps: GetServerSideProps = async ({ res }) => {
res.setHeader("Cache-Control", "public, s-maxage=3600, stale-while-revalidate=600");
return { props: { content: await getContentList() } };
};
export default Blog;
-126
View File
@@ -1,126 +0,0 @@
import type { NextPage } from "next";
import Link from "next/link";
import Image from "next/image";
import { useEffect } from "react";
import { Discord, Github, Instagram, Steam, Linkedin } from "@icons-pack/react-simple-icons";
import Layout from "../components/Blog/Layout";
import styles from "../styles/Blog/AboutMe.module.scss";
import pic from "../public/img/me.png";
import skills, { AdditionalSkill, Skill, SkillCard } from "../data/skills";
import achievements from "../data/achievements";
import socials from "../data/socials";
const Badge: NextPage<{ additional: AdditionalSkill }> = ({ additional }) => {
return <div className={styles.badge}>
<span>{additional.icon || null}</span><span>{additional.name}</span>
</div>;
};
const SkillBar: NextPage<{ skill: Skill }> = ({ skill }) => {
return <div className={styles.skillBar}>
<div className={styles.barName}>{skill.icon || null}</div>
<div className={styles.percentBar} style={{"--barPct": skill.pct + "%"} as React.CSSProperties}>
<div className={`${styles.front} vpAnimated`}></div>
</div>
<div>{skill.name}</div>
</div>;
};
const SkillCard: NextPage<{ card: SkillCard }> = ({ card }) => {
const cardStyle = {
background: card.colors?.background,
"--ch-color": card.colors?.heading,
"--bar-color": card.colors?.bars,
color: card.colors?.useDarkColor === undefined ? undefined : (card.colors?.useDarkColor ? "#222" : "#ddd"),
"--badge-bg": card.colors?.badges?.background,
"--badge-color": card.colors?.badges?.useDarkColor === undefined ? undefined : (card.colors?.badges?.useDarkColor ? "#222" : "#ddd"),
} as React.CSSProperties;
return <div className={styles.skillCard} style={cardStyle}>
<h3>{card.title}</h3>
<div className={styles.skillBarsSet}>
{card.skillBars.sort((bar1, bar2) => bar2.pct - bar1.pct).map((skill, i) =>
<SkillBar key={i} skill={skill} />
)}
</div>
{card.additional && card.additional.length > 0 ? <div className={styles.badgeSet}>
{card.additional?.map((skill, i) => <Badge additional={skill} key={i} />)}
</div> : null}
</div>;
};
const Me: NextPage = () => {
useEffect(() => {
const handleScrollAnimation = () => {
document.querySelectorAll(".vpAnimated").forEach((element) => {
const rect = element.getBoundingClientRect();
const inVp = (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
if (inVp) (element as HTMLElement).style.animationPlayState = "running";
else (element as HTMLElement).style.animationPlayState = "paused";
});
};
handleScrollAnimation(); // First time so we don't _need_ scrolling
window.addEventListener("scroll", handleScrollAnimation);
}, []);
const age = new Date().getFullYear() - 1998 - (new Date().getMonth() <= 10 ? 1 : 0);
return <Layout>
<h1>This is me.</h1>
<div className={styles.photo}>
<Image src={pic} alt="Me" layout="responsive" placeholder="blur" />
</div>
<div className={styles.personal}>
<p className={styles.preText}>
My name is <strong>Daniel</strong> and I&apos;m a prospective <strong>automation engineer</strong>, <strong>hardware enthusiast</strong>, and <strong>software developer</strong> from Germany.<br/>
I&apos;m {age} years old and studying <strong>Information Systems Engineering</strong> at <strong>TU Dresden</strong>.
</p>
<p>
To be honest, I don&apos;t really know what to write here.
What could you - some visitor of my website - possibly want to know about me?
</p><p>
Maybe you are an employer and want to know what I can do for you?
Then see below - I tried to list all my skills and achievements.
If your company is doing anything related to software development (even low-level ones like embedded controllers), I&apos;m probably suited for it.
</p><p>
But maybe you are just another guy on the internet browsing through my website?
Well then have fun!
I hope you find what you are looking for.
If you haven&apos;t seen it already, you should check out the <Link href="/terminal"><a className="nocolor">command line</a></Link> I made.
Otherwise, have fun poking around in my <Link href="/"><a className="nocolor">projects</a></Link>.
</p><p>
Do you want to know more about my personal life?
Well, I like to play video games, and watch anime, I love cats and <a href="https://www.reddit.com/r/blahaj" target="_blank" rel="noreferrer" className="nocolor">sharks</a>.
So just your ordinary nerdy student.<br/>
If you want to be even more invested in my personal life, check out my socials below.
</p><p>
Any questions I did not cover, but you are interested in?
Just contact me <a className="nocolor" href="mailto:admin-website@c0ntroller.de" rel="noreferrer" target="_blank">via email</a> or any of the socials below!
</p>
</div>
<h2>Social Media</h2>
<div className={styles.socials}>
{socials("2em").filter((social) => social.name !== "PGP Key").map((social, i) =>
<a key={i} href={social.url} target="_blank" rel="noreferrer" className="nocolor">
{social.icon}
</a>
)}
</div>
<h2>Achievements</h2>
{achievements().map((achievement, i) => <div key={i} className={styles.achievement}>
<span>{achievement.icon}</span><span>{achievement.description}</span>
</div>)}
<h2>Skills</h2>
{skills().cards.map((card, i) => <SkillCard key={i} card={card} />)}
</Layout>;
};
export default Me;
-96
View File
@@ -1,96 +0,0 @@
import type { NextPage, GetStaticProps } from "next";
import Head from "next/head";
import Link from "next/link";
import Icon from "@mdi/react";
import { mdiEmail } from "@mdi/js";
import { useEffect, useRef,useCallback } from "react";
import { useCommands } from "../lib/commands/ContextProvider";
import { useModalFunctions } from "../components/Terminal/contexts/ModalFunctions";
import ProjectModal from "../components/Terminal/ProjectModal";
import REPL from "../components/Terminal/REPL";
import type { ContentList } from "../lib/content/types";
import { useRouter } from "next/router";
import Rainbow from "../lib/colors";
import styles from "../styles/Terminal/Terminal.module.css";
import socials from "../data/socials";
const Terminal: NextPage<{ buildTime: string }> = ({ buildTime }) => {
const inputRef = useRef<HTMLInputElement>(null);
const { modalFunctions } = useModalFunctions();
const { setContents } = useCommands();
const router = useRouter();
const updateProjects = useCallback(async () => {
try {
const res = await fetch("/content/list.json");
const projects: ContentList = await res.json();
projects.sort((a, b) => {
return a.name.localeCompare(b.name);
});
setContents(projects);
} catch {}
}, [setContents]);
const focusInput = () => { if (inputRef.current) inputRef.current.focus(); };
const hideModalOnEsc = (e: React.KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
if(modalFunctions.setVisible) modalFunctions.setVisible(false);
}
};
useEffect(() => {
updateProjects().then(() => { if (modalFunctions.onContentReady) modalFunctions.onContentReady(); });
const interval = setInterval(updateProjects, 30 * 1000);
return () => clearInterval(interval);
}, [updateProjects, modalFunctions]);
useEffect(() => {
if ("rainbow" in router.query) {
Rainbow.start();
}
}, [router]);
const iconSize = "1.3em";
const socialLinks = socials(iconSize, "var(--repl_color)").map((social, i) => <a key={i} href={social.url} target="_blank" rel="noreferrer" className={styles.iconLink}>{social.icon}</a>);
return (<main onKeyDown={hideModalOnEsc} tabIndex={-1}>
<Head>
<title>c0ntroller.de</title>
</Head>
<ProjectModal />
<div className={styles.container}>
<div className={styles.header}>
<span className={styles.spacer} onClick={focusInput}>&nbsp;</span>
<Link href="/"><a>Main page</a></Link>
<span className={styles.divider}>|</span>
<a href="https://github.com/C0ntroller/c0ntroller.de" target="_blank" rel="noreferrer">Source</a>
<span className={styles.divider}>|</span>
<a href="https://github.com/C0ntroller/c0ntroller.de/issues/new" target="_blank" rel="noreferrer">Bug?</a>
<span className={styles.divider}>|</span>
<a href="mailto:admin-website@c0ntroller.de" rel="noreferrer" target="_blank" className={styles.iconLink}><Icon path={mdiEmail} color="var(--repl_color)" size="1.5em" id="mdi_terminal_nav_email" title="Email" /></a>
<span className={styles.divider}>|</span>
{socialLinks.flatMap((social, i) => i !== 0 ? [<span className={styles.divider} key={`d${i}`}>|</span>, social] : [social])}
<span className={styles.spacer} onClick={focusInput}>&nbsp;</span>
</div>
<REPL inputRef={inputRef} buildTime={buildTime} />
</div>
</main>);
};
export const getStaticProps: GetStaticProps = async (_context) => {
const date = new Date();
const padD = (n: number) => n.toString().padStart(2, "0");
const buildTime = `${date.getUTCFullYear()}${padD(date.getUTCDate())}${padD(date.getUTCMonth() + 1)}-${padD(date.getUTCHours())}${padD(date.getUTCMinutes())}`;
return {
props: {
buildTime
}
};
};
export default Terminal;
+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 128 128">
<path d="M50.4 78.5a75.1 75.1 0 0 0-28.5 6.9l24.2-65.7c.7-2 1.9-3.2 3.4-3.2h29c1.5 0 2.7 1.2 3.4 3.2l24.2 65.7s-11.6-7-28.5-7L67 45.5c-.4-1.7-1.6-2.8-2.9-2.8-1.3 0-2.5 1.1-2.9 2.7L50.4 78.5Zm-1.1 28.2Zm-4.2-20.2c-2 6.6-.6 15.8 4.2 20.2a17.5 17.5 0 0 1 .2-.7 5.5 5.5 0 0 1 5.7-4.5c2.8.1 4.3 1.5 4.7 4.7.2 1.1.2 2.3.2 3.5v.4c0 2.7.7 5.2 2.2 7.4a13 13 0 0 0 5.7 4.9v-.3l-.2-.3c-1.8-5.6-.5-9.5 4.4-12.8l1.5-1a73 73 0 0 0 3.2-2.2 16 16 0 0 0 6.8-11.4c.3-2 .1-4-.6-6l-.8.6-1.6 1a37 37 0 0 1-22.4 2.7c-5-.7-9.7-2-13.2-6.2Z" />
<style>
path { fill: #000; }
@media (prefers-color-scheme: dark) {
path { fill: #FFF; }
}
</style>
</svg>

After

Width:  |  Height:  |  Size: 749 B

Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 3.5 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 384 B

After

Width:  |  Height:  |  Size: 384 B

+39
View File
@@ -0,0 +1,39 @@
---
interface Props {
title: string;
description: string;
published?: Date;
path: string;
}
const { title, description, published, path } = Astro.props;
---
<a href={path} class="nostyle">
<div class="card">
<h3>{title}</h3>
<p>{description}</p>
</div>
</a>
<style lang="scss">
.card {
border: 1px solid gray;
border-radius: 1em;
max-width: 350px;
margin: 1rem auto;
transition: box-shadow 0.1s ease-in-out;
cursor: pointer;
padding: 10px;
margin: 5px;
&:hover {
box-shadow: 0px 0px 10px var(--blog_color);
}
}
h3 {
font-size: 120%;
font-weight: bold;
}
</style>
+106
View File
@@ -0,0 +1,106 @@
---
import { getCollection, getEntry } from "astro:content";
import type { CollectionEntry } from "astro:content";
interface Props {
collectionName: CollectionEntry<"diaryMainPages">["slug"];
}
const { collectionName } = Astro.props;
const collectionTitle = (await getEntry("diaryMainPages", collectionName)).data
.title;
const collection = (await getCollection(collectionName)).sort(
(a, b) => a.data.sorting - b.data.sorting,
);
const collectionBasePath = `/blog/${collectionName}`;
const pageSelectedClass = (slug?: string) =>
`${collectionBasePath}${slug ? "/" + slug : ""}` === Astro.url.pathname
? "pageSelected"
: "";
---
<aside class="desktopOnly">
<a href={collectionBasePath}>
<h4 class={pageSelectedClass()}>
{collectionTitle}
</h4>
</a>
<ol>
{
collection.map((entry) => (
<li class={pageSelectedClass(entry.slug)}>
<a href={`${collectionBasePath}/${entry.slug}`}>
{entry.data.title}
</a>
</li>
))
}
</ol>
</aside>
<style lang="scss">
aside {
float: right;
background: transparent;
display: block;
/* 50px padding in main */
margin: -50px -50px 10px 10px;
padding: 20px;
border-bottom-left-radius: 1em;
border-top-right-radius: 1em;
border: none;
border-left: 1px solid var(--blog_content-border);
border-bottom: 1px solid var(--blog_content-border);
@media screen and (max-width: 900px) {
& {
display: none;
}
}
}
h4 {
margin: 0 0 10px 0;
}
ol {
list-style-type: "\1405\0020\0020";
list-style-position: inside;
margin: 0;
padding: 0;
}
li {
margin: 0;
padding: 0;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
width: 200px;
&:hover {
&::marker {
font-weight: bold;
}
}
}
a:link,
a:visited,
a:hover,
a:active {
color: inherit;
text-decoration: none;
}
li.pageSelected {
font-weight: bold;
}
h4.pageSelected,
h4:hover {
text-decoration: underline;
}
</style>
+147
View File
@@ -0,0 +1,147 @@
---
import { getCollection, getEntry } from "astro:content";
import type { CollectionEntry } from "astro:content";
interface Props {
collectionName: CollectionEntry<"diaryMainPages">["slug"];
isOnTop?: boolean;
}
const { collectionName, isOnTop } = Astro.props;
const collectionTitle = (await getEntry("diaryMainPages", collectionName)).data.title;
const collection = (await getCollection(collectionName)).sort((a, b) => a.data.sorting - b.data.sorting);
const collectionBasePath = `/blog/${collectionName}`;
const currentIndex = collection.findIndex(entry => `${collectionBasePath}/${entry.slug}` === Astro.url.pathname);
const previousEntry = collection[currentIndex - 1];
const nextEntry = collection[currentIndex + 1];
const previousEntryLink = previousEntry ?
{show: true, href: `${collectionBasePath}/${previousEntry.slug}`, title: previousEntry.data.title} :
{show: currentIndex !== -1, href: collectionBasePath, title: collectionTitle};
const nextEntryLink = nextEntry ?
{href: `${collectionBasePath}/${nextEntry.slug}`, title: nextEntry.data.title} :
null ;
---
<nav class={isOnTop ? "top" : "bottom"}>
<span></span>
<span class="leftSelectSpace">
{ previousEntryLink.show ?
<a href={previousEntryLink.href}>&lt;<span class="longLink"> {previousEntryLink.title}</span><span class="shortLink">&lt;</span></a> :
null
}
</span>
<span class="leftSelectSpaceSync">
{ nextEntryLink ?
<>&lt;<span class="longLink"> {nextEntryLink.title}</span><span class="shortLink">&lt;</span></>
: null}
</span>
<span style={{ visibility: previousEntryLink.show ? "visible" : "hidden" }}>&nbsp;&nbsp;|&nbsp;&nbsp;</span>
<select class="selectField">
<option value={ collectionBasePath }>{ collectionTitle }</option>
{ collection.map(entry => <option value={`${collectionBasePath}/${entry.slug}`} selected={`${collectionBasePath}/${entry.slug}` === Astro.url.pathname}>{ entry.data.title }</option> ) }
</select>
<span style={{ visibility: nextEntryLink ? "visible" : "hidden" }}>&nbsp;&nbsp;|&nbsp;&nbsp;</span>
<span class="rightSelectSpace">
{ nextEntryLink ?
<a href={nextEntryLink.href}><span class="longLink">{nextEntryLink.title} </span><span class="shortLink">&gt;</span>&gt;</a> :
null
}
</span>
<span class="rightSelectSpaceSync">
{ previousEntryLink.show ?
<><span class="longLink">{previousEntryLink.title} </span><span class="shortLink">&gt;</span>&gt;</> :
null
}
</span>
<span></span>
</nav>
<style lang="scss">
nav {
display: grid;
grid-template-columns: 1fr max-content max-content max-content max-content max-content 1fr;
align-items: center;
background: transparent;
padding: 10px;
&.top {
display: none;
margin: -50px -50px 20px;
border-bottom: 1px solid var(--blog_content-border);
@media screen and (max-width: 889px) {
& {
display: grid;
margin-top: -20px;
}
}
}
/*&.bottom {
margin: 40px -50px -50px;
border-top: 1px solid var(--blog_content-border);
}*/
}
select {
padding: 5px;
border-radius: 1em;
border: 1px solid var(--blog_content-border);
background: var(--blog_background-main);
}
a:link, a:visited, a:active {
color: inherit;
text-decoration: none;
font-weight: bold;
text-overflow: clip;
}
a:hover {
text-decoration: underline;
}
.longLink {
display: inline;
}
.shortLink {
display: none;
}
@media screen and (max-width: 599px) {
.longLink {
display: none;
}
.shortLink {
display: inline;
}
}
.leftSelectSpace {
grid-area: 1/2;
}
.leftSelectSpaceSync {
grid-area: 1/2;
visibility: hidden;
}
.rightSelectSpace {
grid-area: 1/6;
}
.rightSelectSpaceSync {
grid-area: 1/6;
visibility: hidden;
}
</style>
+14
View File
@@ -0,0 +1,14 @@
---
import DiaryNavAside from "./DiaryNavAside.astro";
import DiaryNavBar from "./DiaryNavBar.astro";
import type { CollectionEntry } from "astro:content";
interface Props {
collectionName: CollectionEntry<"diaryMainPages">["slug"];
}
const { collectionName } = Astro.props;
---
<DiaryNavBar collectionName={ collectionName } isOnTop={ true } />
<DiaryNavAside collectionName={ collectionName } />
@@ -0,0 +1,147 @@
---
import { Image } from "astro:assets";
import { Icon } from "astro-icon";
import ThemeSwitch from "./ThemeSwitch.astro";
import logo from "./logo.png";
---
<nav class="navigation">
<a href="/" class="nostyle imgContainer">
<Image src={logo} alt="Logo" class="logoImg" />
</a>
<div class="navLink">
<a href="/" class="nostyle">
<span class="linkText">Projects</span>
<span class="linkIcon"
><Icon
name="mdi:home"
size="2em"
title="Home and Projects"
id="mdi_nav_home"
/></span
>
</a>
</div>
<div class="navLink">
<a href="/me" class="nostyle">
<span class="linkText">About Me</span>
<span class="linkIcon"
><Icon
name="mdi:account"
size="2em"
title="About Me"
id="mdi_nav_aboutme"
/></span
>
</a>
</div>
<div class="spacer"></div>
<div class="navIcon">
<a href="/terminal" class="nostyle">
<Icon
name="mdi:console"
size="2em"
title="Terminal"
id="mdi_nav_terminal"
/>
</a>
</div>
<ThemeSwitch />
</nav>
<style lang="scss">
.navigation {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
align-items: center;
max-width: 1000px;
/*min-width: 300px;*/
position: relative;
height: calc(1em + 40px);
margin: 0 auto;
padding: 20px;
font-size: 120%;
/* height / 2 */
border-radius: calc((1em + 40px) / 2);
border: 1px solid var(--blog_nav-border);
background: var(--blog_nav-background);
backdrop-filter: blur(var(--blog_content-blur));
box-shadow: 0px 2px 5px gray;
.imgContainer {
align-self: flex-start;
margin-top: -10px;
position: relative;
cursor: pointer;
display: none;
height: calc(1em + 40px - 20px);
width: calc((501 / 204) * (1em + 40px - 20px));
}
.logoImg {
height: 100%;
width: 100%;
}
.navLink {
transition: text-decoration 0.3s ease-in-out;
display: block;
margin-right: 10px;
cursor: pointer;
&:hover {
text-decoration: underline;
}
}
.navIcon {
margin-right: 15px;
height: 1.8em;
display: block;
}
.navLink .linkIcon {
cursor: pointer;
height: 1.8em;
display: block;
}
.navLink {
.linkText {
display: none;
}
.linkIcon {
display: block;
}
}
@media screen and (min-width: 450px) {
.imgContainer {
display: block;
}
.navLink:nth-of-type(1) {
margin-left: 15px; /*calc((501 / 204) * (1em + 40px - 20px) + 15px);*/
}
}
@media screen and (min-width: 350px) {
.navLink {
.linkText {
display: inline;
}
.linkIcon {
display: none;
}
}
}
.spacer {
flex-grow: 2;
}
}
</style>
@@ -0,0 +1,101 @@
---
import { Icon } from "astro-icon";
---
<div class="switch">
<Icon name="mdi:language-javascript" class="placeHolder" title="Theme switching needs JS to be enabled."/>
<Icon name="mdi:white-balance-sunny" class="sun" title="Switch to dark theme" />
<Icon name="mdi:weather-night" class="moon" title="Switch to light theme" />
</div>
<script lang="ts">
// Get and delete placeholder (JS is enabled)
const placeHolder = document.querySelector(".placeHolder");
placeHolder.remove();
const moon = document.querySelector(".moon");
const sun = document.querySelector(".sun");
const current = document.documentElement.attributes.getNamedItem('data-theme')?.value ?? "dark";
if (current === "dark") {
moon.classList.add("selected");
} else {
sun.classList.add("selected");
}
const switchThemeDark = () => {
document.dispatchEvent(new CustomEvent('set-theme', { detail: 'dark' }));
moon.classList.remove("fadeOut");
moon.classList.add("fadeIn");
sun.classList.remove("fadeIn");
sun.classList.add("fadeOut");
}
const switchThemeLight = () => {
document.dispatchEvent(new CustomEvent('set-theme', { detail: 'light' }));
moon.classList.remove("fadeIn");
moon.classList.add("fadeOut");
sun.classList.remove("fadeOut");
sun.classList.add("fadeIn");
}
moon.addEventListener("click", switchThemeLight);
sun.addEventListener("click", switchThemeDark);
</script>
<style lang="scss">
.switch {
position: relative;
width: 1.5em;
height: 1.5em;
cursor: pointer;
& > * {
position: absolute;
opacity: 0;
transform: translate(0, 100%);
}
& > .selected {
opacity: 1;
transform: translate(0, 0);
}
.fadeOut {
animation: fadeOut 0.2s ease-in-out;
animation-fill-mode: forwards;
}
.fadeIn {
animation: fadeIn 0.2s ease-in-out;
animation-fill-mode: forwards;
}
.placeHolder {
opacity: 1 !important;
transform: translate(0, 0) !important;
}
}
@keyframes fadeOut {
from {
opacity: 1;
transform: translate(0, 0);
}
to {
opacity: 0;
transform: translate(0, -100%);
}
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translate(0, 100%);
}
to {
opacity: 1;
transform: translate(0, 0);
}
}
</style>

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 27 KiB

+219
View File
@@ -0,0 +1,219 @@
---
import { Icon } from "astro-icon";
import Skills from "../data/skills.json";
type Skill = (typeof Skills.cards)[number];
interface Props {
card: Skill;
}
const { card } = Astro.props;
const cardStyle = {
background: card.colors?.background,
"--ch-color": card.colors?.heading,
"--bar-color": card.colors?.bars,
color:
card.colors?.useDarkColor === undefined
? undefined
: card.colors?.useDarkColor
? "#222"
: "#ddd",
"--badge-bg": card.colors?.badges?.background,
"--badge-color":
card.colors?.badges?.useDarkColor === undefined
? undefined
: card.colors?.badges?.useDarkColor
? "#222"
: "#ddd",
};
---
<div class="skillCard" style={cardStyle}>
<h3>{card.title}</h3>
<div class="skillBarsSet">
{
card.skillBars
.sort((bar1, bar2) => bar2.pct - bar1.pct)
.map((skill) => (
<div class="skillBar">
<div class="barName">
<Icon name={skill.icon} />
</div>
<div
class="percentBar"
style={{ "--barPct": skill.pct + "%" }}
>
<div class="front vpAnimated" />
</div>
<div>{skill.name}</div>
</div>
))
}
</div>
{
card.additional && card.additional.length > 0 ? (
<div class="badgeSet">
{card.additional?.map((additional) => (
<>
<div class="badge">
<span>
<Icon name={additional.icon} />
</span>
<span>{additional.name}</span>
</div>
</>
))}
</div>
) : null
}
</div>
<script>
const handleScrollAnimation = () => {
document.querySelectorAll(".vpAnimated").forEach((element) => {
const rect = element.getBoundingClientRect();
const inVp =
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <=
(window.innerHeight ||
document.documentElement.clientHeight) &&
rect.right <=
(window.innerWidth || document.documentElement.clientWidth);
if (inVp)
(element as HTMLElement).style.animationPlayState = "running";
else (element as HTMLElement).style.animationPlayState = "paused";
});
};
handleScrollAnimation(); // First time so we don't _need_ scrolling
window.addEventListener("scroll", handleScrollAnimation);
</script>
<style lang="scss">
.percentBar {
position: relative;
height: 1em;
width: 100%;
border-radius: 0.5em;
border: 1px solid var(--blog_content-border);
background: transparent;
.front {
border-radius: 0.5em;
height: 100%;
position: absolute;
background: var(--bar-color, var(--blog_color-accent));
animation: barFill 2s ease-in-out;
animation-fill-mode: forwards;
}
}
.badgeSet {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.achievement {
display: grid;
grid-template-columns: 2em auto;
column-gap: 10px;
padding: 5px;
padding-left: 0;
& > span:first-of-type {
height: 2em;
}
}
.badge {
display: grid;
grid-template-columns: 1em auto;
column-gap: 5px;
border: 1px solid var(--blog_content-border);
border-radius: 0.5em;
padding: 5px;
background: var(--badge-bg, transparent);
color: var(--badge-color, inherit);
margin-right: 10px;
margin-top: 10px;
&:last-of-type {
margin-right: 0;
}
& > span {
align-self: center;
}
& > span:first-of-type {
height: 1em;
}
}
@keyframes barFill {
0% {
width: 1em;
}
100% {
width: var(--barPct);
}
}
.skillCard {
padding: 10px;
border: 1px solid var(--blog_content-border);
border-radius: 0.5em;
box-shadow: 2px 2px 5px 0px var(--blog_color);
margin-bottom: 20px;
h3 {
margin: 0;
color: var(--ch-color) !important;
}
&:last-of-type {
margin-bottom: 0;
}
&.useDarkColor {
color: #222;
}
&.useLightColor {
color: #ddd;
}
}
.skillBar {
display: grid;
grid-template-columns: 2em auto;
column-gap: 10px;
padding: 10px;
margin: 10px 0;
& > div {
align-self: center;
}
& > div:first-of-type {
height: 2em;
grid-row: 1/3;
}
& > div:nth-of-type(3) {
text-align: center;
margin-top: -2px;
font-size: small;
}
&:last-of-type {
margin-bottom: 0;
}
}
</style>
+232
View File
@@ -0,0 +1,232 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
+104
View File
@@ -0,0 +1,104 @@
[
{
"type": "project",
"name": "terminal",
"short_desc": "The terminal on my website.",
"desc": [
"This is part of my homepage.",
"What you see on the page resembles an CLI. You just type in commands and some output is shown or it does something on the website.",
"To find out which commands are available, you can just type %{help}.",
"",
"Everything is always in development. So if you come back in a few days/weeks/months/years something could have been changed!",
"You can also check out the #%{dev version|https://dev.c0ntroller.de} if you haven't already.",
"",
"Have fun!"
],
"repo": "https://git.c0ntroller.de/c0ntroller/frontpage",
"title": "Terminal"
},
{
"type": "project",
"name": "infoscreen",
"short_desc": "Screen that shows various information.",
"desc": [
"I had a screen left over and hooked a Raspberry Pi to it.",
"Then I created a webpage that fetches and shows various information.",
"Currently it includes time, weather, calendar, departures and more."
],
"repo": "https://git.c0ntroller.de/c0ntroller/infoscreen",
"title": "Infoscreen"
},
{
"type": "diary",
"name": "rust",
"short_desc": "Me learning Rust (German).",
"desc": [
"I documented my progress to learn the Rust programming language.",
"It follows the #%{Rust book|https://doc.rust-lang.org/book/} with my own annotations.",
"Everything is in German as these notes are mostly meant for me."
],
"entries": [
{ "title": "Hello World", "filename": "00 - Hello World"},
{ "title": "Cargo", "filename": "01 - Cargo"},
{ "title": "Higher-Lower-Game", "filename": "02 - Higher-Lower-Spiel"},
{ "title": "Basics", "filename": "03 - Concepts"},
{ "title": "Ownership", "filename": "04 - Ownership"},
{ "title": "Structs", "filename": "05 - Structs"},
{ "title": "Enums", "filename": "06 - Enums"},
{ "title": "Crates & Modules", "filename": "07 - Management"},
{ "title": "Collections", "filename": "08 - Collections"},
{ "title": "Errors und panic!", "filename": "09 - Errors und panic"}
],
"title": "Rust Diary"
},
{
"type": "project",
"name": "tufast",
"short_desc": "TUfast is a browser extension that is used by multiple thousand users of the TU Dresden.",
"desc": [
"TUfast is a browser extension that is used by multiple thousand users of the TU Dresden.",
"It provides autologin to the most used portals, shortcuts, redirects, and more.",
"I'm one of the developers."
],
"repo": "https://github.com/TUfast-TUD/TUfast_TUD",
"more": "https://tu-fast.de/",
"title": "TUfast TUD"
},
{
"type": "project",
"name": "ol-git",
"short_desc": "I created a script that pushes Overleaf projects to a git remote.",
"desc": [
"Overleaf is a LaTeX editor for the web and honestly great to use.",
"But there is no way to back up your project to a cloud drive or git without paying them money.",
"Even the self-hosted community version has no such functionality.",
"I decided that's BS and made my own script to sync a project to git."
],
"repo": "https://git.c0ntroller.de/c0ntroller/overleaf-git-sync",
"title": "Overleaf Git Sync"
},
{
"type": "project",
"name": "simple-cb",
"short_desc": "A simple callback server for OAuth2 applications.",
"desc": [
"Most times when using OAuth2 on an API like Google or Spotify I just need the refresh token on setup.",
"To get the initial tokens and the refresh token it is necessary to have a server that prints the POST body.",
"This application does this."
],
"repo": "https://git.c0ntroller.de/c0ntroller/simple-callback-server",
"title": "Simple Callback Server"
},
{
"type": "project",
"name": "photo-sync",
"short_desc": "A script that syncs a Google Photos album to your drive.",
"desc": [
"Giving random apps access to your Google Photos can be bad.",
"To still use an album as screensaver etc. I wrote this script.",
"It syncs all your photos to your drive while giving you maximum privacy."
],
"repo": "https://git.c0ntroller.de/c0ntroller/simple-callback-server",
"title": "Photo Sync"
}
]
+89
View File
@@ -0,0 +1,89 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://c0ntroller.de/content/list.schema.json",
"title": "Content List",
"description": "A list of projects and diaries for my homepage.",
"type": "array",
"items": {
"anyOf": [
{ "$ref": "#/$defs/project" },
{ "$ref": "#/$defs/diary" }
]
},
"$defs": {
"content": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["project", "diary"]
},
"name": {
"type": "string",
"pattern": "^[a-z0-9-_]+$"
},
"short_desc": {
"type": "string",
"maxLength": 100
},
"desc": {
"type": "array",
"items": {
"type": "string"
}
},
"more": {
"type": "string",
"format": "uri"
},
"repo": {
"type": "string",
"format": "uri"
},
"title": {
"type": "string",
"maxLength": 50
}
},
"required": ["type", "name", "short_desc", "desc", "title"]
},
"project": {
"type": "object",
"allOf": [
{ "$ref": "#/$defs/content" }
],
"properties": {
"type": {
"const": "project"
}
}
},
"diary": {
"type": "object",
"allOf": [
{ "$ref": "#/$defs/content" }
],
"properties": {
"type": {
"const": "diary"
},
"entries": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"filename": {
"type": "string"
}
},
"required": ["title", "filename"]
}
}
},
"required": ["entries"]
}
}
}
+48
View File
@@ -0,0 +1,48 @@
import { z, defineCollection } from 'astro:content';
// Schema for projects
const projectsCol = defineCollection({
type: "content",
schema: z.object({
title: z.string(),
description: z.string(),
descriptionShort: z.string(),
repository: z.string().url().optional(),
relatedWebsite: z.string().url().optional(),
published: z.date(),
tags: z.array(z.string()).optional(),
isDraft: z.boolean().optional(),
}),
});
const diaryMainPages = defineCollection({
type: "content",
schema: z.object({
title: z.string(),
description: z.string(),
descriptionShort: z.string(),
repository: z.string().url().optional(),
relatedWebsite: z.string().url().optional(),
lastUpdated: z.date(),
tags: z.array(z.string()).optional(),
isDraft: z.boolean().optional(),
}),
});
const diarySubPages = defineCollection({
type: "content",
schema: z.object({
title: z.string(),
repository: z.string().url().optional(),
relatedWebsite: z.string().url().optional(),
published: z.date().optional(),
isDraft: z.boolean().optional(),
sorting: z.number(),
}),
});
export const collections = {
"projects": projectsCol,
"rust": diarySubPages,
"diaryMainPages": diaryMainPages,
};
+10
View File
@@ -0,0 +1,10 @@
---
title: Learning Rust
lastUpdated: 2022-06-14T12:21:00.755Z
description: "I documented my progress to learn the Rust programming language. It follows the Rust book with my own annotations. Everything is in German as these notes are mostly meant for me."
descriptionShort: "Me learning Rust (German)."
---
# Learning Rust
In this diary I want to document my progress through the [Rust book](https://doc.rust-lang.org/book/) and documenting some stuff for myself.
Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

+104
View File
@@ -0,0 +1,104 @@
---
title: Infoscreen
description: "I had a screen left over and hooked a Raspberry Pi to it. Then I created a webpage that fetches and shows various information. Currently it includes time, weather, calendar, departures and more."
descriptionShort: Screen that shows various information.
repository: "https://git.c0ntroller.de/c0ntroller/infoscreen"
published: 2022-06-13T13:07:27.205Z
---
import { Image } from "astro:assets";
import screenshot from "./data_infoscreen/screenshot.jpg";
# Infoscreen
This document is about a screen that shows information.
Shocking, I know.
## Screenshot
<Image src={screenshot} alt="Screenshot of the Infoscreen" />
I obfuscated a few things to protect my personal information.
## How it Started
A few years ago I bought a new monitor for my PC.
That left me with a monitor I could use for anything I want.
So I decided to hook a Raspberry Pi to it and show some useful information like weather, calendar, and news.
The monitor then was placed in the kitchen.
## History
### The First Implementation
The first implementation for this was using vanilla JS (and of course HTML and CSS).
Even though I had not had too much experience in JS, I tried to use "good" software development practices, like class inheritance and [ES-Modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules).<br/>
I hosted it, using the default [PHP HTTP-Server](https://www.php.net/manual/en/features.commandline.webserver.php) locally and opened a Chromium browser on localhost.
If you are interested in the code, [here](https://github.com/C0ntroller/infoscreen-old) is the repository of the second version, which uses most of the code from version one.
### Phase Two
The second version of this project basically took all the code from the first version and bundle it as an Electron App.
I hoped that the performance would be increased by not using _the whole_ Chromium bloat.
It (well, who would have guessed) didn't.<br/>
The old code is still up, so if you're interested you can find it [in this repository](https://github.com/C0ntroller/infoscreen-old).
### Phase Three
When I started to learn React more, I realized that what I tried to achieve in the prior versions are just React components.
I rewrote what I had using React.
But I also had already learned about frameworks for React that provide static site generation like [Next.JS](https://nextjs.org/) and [Gatsby](https://www.gatsbyjs.com/).<br/>
Gatsby looked like a good choice so I just went for it.
It gets hosted in a Docker container on my own home server and the Pi just opens up a Chromium again.
This marks the end of the development history.
## So what's on the Screen?
Currently, the following info is shown:
- Time
- Weather and weather map
- two RSS news feeds
- a Google calendar
- departures on the nearest tram station
- Spotify or info from my plant sensors
Also, the background image is cycled through 20-ish images.
When it's getting late, a dark mode gets activated and the weather map is replaced by I cute gif of a sleeping Pikachu.
### Weather
For the weather, I used the [DarkSky API](https://darksky.net/).
Because Apple bought it and (of course) shut down the public API I had to switch to [Pirate Weather](https://pirateweather.net/). +
Sadly the data from Pirate Weather seems to not be accurate most times.
In the future, I probably want to switch to another API.
### RSS News
For news, I use the RSS feed of the [Tagesschau](https://www.tagesschau.de/), one of the earliest and biggest news channels in Germany.
I also put in a few topics from [Der Postillon](https://www.der-postillon.com/) a German satire news page.
It's available in [English too](https://www.the-postillon.com/).
### Google Calendar
It uses the [Google Calendar API](https://developers.google.com/calendar) and orders the event by a day.
### Departures
My local public transport company has an API available to fetch data for the stations.
It's quite simple to use actually!
### Spotify
This part shows which song is currently playing in the kitchen.
How it works is a project in itself.
A write-up will follow later.
If nothing is playing, information about a few plant sensors is shown.
### Plants
This just fetches and shows the current status of the plant sensors from my [Home Assistant](https://www.home-assistant.io/).
+79
View File
@@ -0,0 +1,79 @@
---
title: Overleaf Git Sync
description: "Overleaf is a LaTeX editor for the web and honestly great to use. But there is no way to back up your project to a cloud drive or git without paying them money. Even the self-hosted community version has no such functionality. I decided that's BS and made my own script to sync a project to git."
descriptionShort: "I created a script that pushes Overleaf projects to a git remote."
repository: "https://git.c0ntroller.de/c0ntroller/overleaf-git-sync"
published: 2022-10-18T17:56:27+02:00
---
# Overleaf Sync with Git
## The Problem
When I was writing some important stuff for uni I wanted as many backups as possible.
Because what would I do if a hard drive breaks?
Or what if I lose my laptop?
I wanted to use LaTeX for writing and I decided, the best way to have it in a central location where I have access from all my devices would be a self-hosted instance of [Overleaf](https://overleaf.com/).
Because it is only an editor for the web and uses project directories and files means there should be an easy way to back it up, right?
Wrong!
Not only is there no way to sync your projects to any cloud storage or git in the self-hosted community version.
But there _is_ a way for it in the central version hosted by them.
But **only if you pay them**.
And it's not like it's just a cheap little SaaS.
Even for students, it's 70€/year!
This is just major BS.
There has to be a way to do this myself.
## Where is my data?
After setting up the container stack for Overleaf I just created a small default project.
And now the files are somewhere stored on the disk so I can just copy them from there and work with them, right?
Wrong again.
Some files get stored on disk - but only images.
I would suspect they just pipe all the TeX stuff into the MongoDB the service uses.
Well, that didn't work.
Do they have an API?
If they do, it's not documented at all.
But using the browser Dev-Tools it seems like they indeed have some API routes.
Also [their repo includes a `router.js`](https://github.com/overleaf/overleaf/blob/main/services/web/app/src/router.js).
But how to use them?
## Access granted
I noticed the front end uses session IDs for user authentication.
You get an ID, you POST valid credentials (and a CSRF token) to `/login` and your session ID get's "verified".
Using their repository, it was easy to find other routes that are useable.
But I only needed one: downloading the whole project.
That was easy because after login you can use the same route the browser uses: `/project/{id}/download/zip`
Using a simple Python script I was able to make these calls with no problems.
## What to do with the zip?
Because I think it's unintuitive to run git commands in the Python `subprocess` library, I just wrote a bash script.
Not only one but two.
The first script prepares the git folder.
It clones the repository where we want to put our stuff and switches to the branch we want to use.
Then the zip file we downloaded earlier is unpacked in this folder.
The second bash script creates a git commit and pushes the changes to remote.
## Improvements for the Future
Everything was put together in a really short time, so I guess it's fairly flawed.
A few flaws I will maybe fix someday:
- Use environment variables or a `.env` file instead of a Python dictionary for settings
- Include other sync methods, like just extracting the zip in any directory so you can put it in your Drive/Dropbox/whatever
- (Probably never implemented) Implement login using OAuth
+42
View File
@@ -0,0 +1,42 @@
---
title: Photo Sync
description: "Giving random apps access to your Google Photos can be bad. To still use an album as screensaver etc. I wrote this script. It syncs all your photos to your drive while giving you maximum privacy."
descriptionShort: "A script that syncs a Google Photos album to your drive."
repository: https://git.c0ntroller.de/c0ntroller/google-photo-album-sync
published: 2022-08-08T12:19:20+02:00
---
# Google Photo Sync
Why give up privacy for a screensaver?
## Storytime
I recently got a new NVidia Shield with Android TV and after setting everything up I wanted to add a screen saver.
There are tons of them and some of them even can take a Google Photo album and make your TV a digital picture frame.
I thought it would be great because I already use Google Photos for sharing albums with other people.
So I tried to log in.
And I didn't do it.
The screensaver app did not only need access to my photos.
It also wanted my personal details, email address, contact list, and other details.
This was unacceptable.
Then I thought about it: These apps normally can use images stored on the device or a connected drive.
My NAS is already connected to the Shield so...
## The Solution
I already had some experience with the Google API from projects like the [Infoscreen](/blog/projects/infoscreen) and the [Simple Callback Server](/blog/projects/simple-cb).
I decided to make it easier for users who are not familiar with the API, so I created a CLI to set everything up.
I think the `README` is pretty good so no need to explain the setup process.
## What's left
My detection for images with similar names is bad (but it works and I can only think of one edge case where it doesn't).
I could use MD5s to make it better.
+31
View File
@@ -0,0 +1,31 @@
---
title: Simple Callback Server
description: "Most times when using OAuth2 on an API like Google or Spotify I just need the refresh token on setup. To get the initial tokens and the refresh token it is necessary to have a server that prints the POST body. This application does this."
descriptionShort: "A simple callback server for OAuth2 applications."
repository: "https://git.c0ntroller.de/c0ntroller/simple-callback-server"
published: 2022-10-18T17:56:27+02:00
---
# Simple Callback Server
This is probably my simplest project.
## What is this?
It's the simplest thing you could imagine: An `express` server that prints out all headers and the body or all query parameters.
Still, I needed it sometimes and I didn't want to rewrite it every time I use it.
## What can it be used for?
When creating a dev application on Google, Spotify, or other services you often have some heavy authentication flow to get access.
But normally I want to use the API for private projects and it's _my_ account that gets authenticated every time.
To make reauthentication easier these OAuth protocols often provide a "refresh token" which can be used to get a valid new token.
To get the initial authentication token and to get such a refresh token you provide a callback address where you get redirected after the user logs in.
The tokens and meta information normally are sent in a `POST` body.
And this is where this small application is necessary.
## This sounds overly complicated
It is. But this is necessary for OAuth2 to be safe.
+91
View File
@@ -0,0 +1,91 @@
---
title: Terminal
description: "This is part of my homepage. What you see on the page resembles an CLI. You just type in commands and some output is shown or it does something on the website. To find out which commands are available, you can just type help. Everything is always in development. So if you come back in a few days/weeks/months/years something could have been changed! You can also check out the dev version if you haven't already. Have fun!"
descriptionShort: "The terminal on my website."
repository: https://git.c0ntroller.de/c0ntroller/frontpage
published: 2022-10-18T17:56:27+02:00
---
# Terminal
Hello and welcome to my website. This documentation is for the [cli on my website](https://c0ntroller.de/terminal) so check it out if you haven't!
## Why did I do this?
Mainly because of boredom and because I like to code.
Also, a website is a fantastic way to show someone what you are capable of in programming skills.
Now I have my own space to try things out, present what I did and link all my socials.
## How did I do this?
### Frameworks
This website is entirely built in [Next.js](https://nextjs.org/), which is a JavaScript framework.
So the entire backend is in [Node.js](https://nodejs.org/).
The project files are written in ~~[AsciiDoc](https://projects.eclipse.org/projects/asciidoc.asciidoc-lang)~~ [MDX](https://mdxjs.com/).
Hosting the webserver is done in a [Docker](https://www.docker.com/) container on my personal server.
### The Process
#### Thinking About a Website
I always wanted my own website. One day, I thought about how cool a website would be, this is basically a console. +
It seemed not too hard to make, as it consists of an input field and a log/history.
But I wanted more. I wanted the code to be as modular as possible, so it's easy in the future to add commands, project logs, and components. Also, I wanted some appealing features like tab completion and shortcuts.
But as it is hard to show a CLI to friends who don't know computer science or an employer, I decided a "normal" frontend should be added.
#### Implementing all the Stuff
As you can imagine, it was not easy to implement all the features I had imagined. But I'm pretty confident I'm on the right track now. +
The commands are all contained in one file, and one can easily add or remove them, add flags and other attributes and change the function called when the command is requested. +
The project files are contained in a separate repository and folder on my server, which is just used as a Docker volume. This means they can be updated without rebuilding the entire project.
After the CLI website was done, it was my main homepage for a few months.
Then that I created the "normal" part which basically is a blog and my portfolio.
#### Autodeployment
I like automatization, so I use a CI/CD pipeline.
I use [Drone](https://www.drone.io/) for this job which is self-hosted too.
The Docker container is pushed and pulled in a self-hosted registry, so it should be safe if I ever want to include secrets and private data into the project.
The project files are first built with [Asciidoctor](https://asciidoctor.org/) to check their validity.
Then a script pulls them on the server.
As the projects git directory on the server is mounted in the docker container only a quick reload is necessary so the files are available on the server.
== The Future
What future features do I want to implement? +
I don't know.
It will probably be like the rest of this website:
One day I have a good thought (At least I _think_ it's good...) and add an issue or implement it immediately.
~~Probably I should start by adding a [JSON schema](https://json-schema.org/) for the project list.~~ Thats done!
## CLI Shortcuts
I talked about shortcuts before, but here's a list of which shortcuts are possible:
| Key | Effect |
|-----|--------|
| <kbd>Tab</kbd> | Inserts the current suggestions from autocompletion. |
| <kbd>&#9650;</kbd> / <kbd>&#9660;</kbd> | Scroll through last commands. |
| <kbd>Ctrl</kbd>+<kbd>L</kbd> | Clears the history. Similar to `clear`. |
| <kbd>Ctrl</kbd>+<kbd>D</kbd> | Exits the page. If that doesn't work ([JavaScript restriction](https://developer.mozilla.org/en-US/docs/Web/API/Window/close)) it goes back in page history. Similar to `exit`. |
| <kbd>Ctrl</kbd>+<kbd>U</kbd>/<kbd>Ctrl</kbd>+<kbd>C</kbd> | Removes the current input. |
| <kbd>Esc</kbd> | Close the dialog modal. |
## Some Stuff I'm Proud of
- Every line in the cli history window is parsed in a custom format.
* `%{command}` is parsed to a clickable command
* `#{link text|url}` is parsed to a link
- Project logs are loaded dynamically. They can be updated at any time.
* But they are rendered in the backend. For the main site no JS is necessary!
- There are lots of eastereggs. Some are for specific people, some for me and some for fun.
- I made some custom annotations for code blocks show faulty code (wrong syntax/will not compile/etc.).
<div class="notCompiling">
```rust
// This is how a faulty code block looks like
fn main() {
let x = 5;
x = 6;
}
```
</div>
+29
View File
@@ -0,0 +1,29 @@
---
title: TUfast TUD
description: "TUfast is a browser extension that is used by multiple thousand users of the TU Dresden. It provides autologin to the most used portals, shortcuts, redirects, and more. I'm one of the developers."
descriptionShort: "TUfast is a browser extension that is used by multiple thousand users of the TU Dresden."
repository: https://github.com/TUfast-TUD/TUfast_TUD
relatedWebsite: https://tu-fast.de/
published: 2022-06-23T12:53:07.207Z
---
# TUfast
My work on a browser extension that is used by multiple thousand students.
## What is TUfast?
TUfast is a browser extension made by some students of the TU Dresden.
The main feature is the injection of username and password on various login pages of portals of the TU. +
Other features are shortcuts, redirects from search engines, enhancement and more. +
It has multiple thousand users.
The project is open source and [hosted on Github](https://github.com/TUfast-TUD/TUfast_TUD).
## What did I do?
I am one of the first and one of the main contributors of the project.
At the time of writing this I rewrote the whole backend in TypeScript and prepared it to shift to the [Manifest V3](https://developer.chrome.com/docs/extensions/mv3/intro/).
## More information
- [Repository](https://github.com/TUfast-TUD/TUfast_TUD)
- [Website](https://tu-fast.de/)
+52
View File
@@ -0,0 +1,52 @@
---
title: Hello world!
published: 2022-08-10T17:04:53+02:00
sorting: 0
slug: hello-world
---
# Hello world!
_[Link zum Buch](https://doc.rust-lang.org/book/ch01-02-hello-world.html)_
## How to `println!`
Hello world ist relativ einfach. `println!` ist ein Makro (eine
spezielle Art Funktion?), die einfach auf stdout printed.
```rust
println!("Hello world!");
```
Output:
```
Hello world!
```
## Komplettes Programm
Rust hat ähnlich wie C eine `main`-Funktion, die zum Start ausgeführt
wird.
Ein komplettes Programm zum Kompilieren hätte also den folgenden Inhalt:
```rust
fn main() {
println!("Hello world!");
}
```
Kompiliert und ausgeführt wird es dann über folgende Befehle:
```bash
$ rustc main.rs
$ ./main
Hello world!
```
## Weitere Details
* `fn` -> Funktionsdeklaration
* 4 Leerzeichen zum Einrücken, kein Tab
* `;` am Ende der Zeile
+74
View File
@@ -0,0 +1,74 @@
---
title: Cargo
published: 2022-10-18T17:56:26+02:00
sorting: 1
slug: cargo
---
# Cargo
_[Link zum Buch](https://doc.rust-lang.org/book/ch01-03-hello-cargo.html)_
## Was ist Cargo?
Cargo ist Rusts package manager.<br/>
Um ein neues Cargo-Projekt zu erstellen, braucht es das folgende
Command:
```bash
$ cargo new projektname --bin
```
`--bin` sagt, dass wir ein neues Binary erstellen und keine
Bibliothek.<br/>
Es wird auch gleich `main.rs`, ein `.git`-Ordner (inkl. `.gitignore`)
und `Cargo.toml` erstellt.
## Angelegte Dateien
### Cargo.toml
Unangetastet sieht die Datei so aus:
```toml
[package]
name = "projektname"
version = "0.1.0"
authors = ["Your Name <you@example.com>"]
[dependencies]
```
Hier können also Meta-Infos wie Name und Dependencies gespeichert
werden.
So wie eine `package.json` in JavaScript.
### main.rs
Die Main-Datei ist mit ``Hello World'' gefüllt.
## Commands
### cargo build
```bash
$ cargo build
$ ./target/debug/projektname
```
Standardmäßig wird ein Debug-Build erzeugt. `cargo build --release`
erzeugt einen Release-Build.
### cargo run
Macht einen build und führt die Datei dann aus.
### cargo check
Checkt alles einmal durch.
### cargo update
Updatet alle Dependencies. Allerdings nur auf die letzte Subversion der
angegebenen Version. Will man eine neue Version, muss man das manuell
angeben.
@@ -0,0 +1,313 @@
:experimental:
:docdatetime: 2022-10-18T17:56:26+02:00
= Erstes Spiel
_https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html[Link zum Buch]_ | _Diese Seite ist aus einem https://jupyter.org/[Jupyter Notebook] exportiert_.
== Projekt erstellen
Das Projekt wird wie in Notebook 01 beschrieben erstellt.
== Einen Input aufnehmen
~*In[2]:*~
[source, rust]
----
:dep evcxr_input
// Das ^ ist für Jupyter
// Das v würde man wirklich benutzen
// use std::io;
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = evcxr_input::get_string("Number? ");
// Das ^ ist für Jupyter
// Das v würde man wirklich benutzen
//let mut guess = String::new();
//io::stdin().read_line(&mut guess)
// .expect("Failed to read line");
println!("You guessed: {}", guess);
----
~*Out[2]:*~
----
Guess the number!
Please input your guess.
Number? 42
You guessed: 42
----
== Was haben wir gemacht?
* `use std::io;` bindet die Standard-IO Bibliothek ein
* `let mut guess` legt eine Variable `guess` an
** `mut` bedeutet, dass sie ``mutable'' also veränderbar ist
* `String::new()` erstellt eine neue Instanz der `String`-Klasse
* `io::stdin()` legt ein `Stdin`-Objekt an - ein Handler für die
CLI-Eingabe
** ohne die ``use'' Anweisung oben, müsste es `std::io::stdin()` sein
* `.read_line(&mut guess)` ließt eine Zeile und speichert sie in guess
** `&` erstellt dabei eine Referenz (wie in C)
** Referenzen sind standardmäßig immutable - deshalb `&mut`
** `read_line()` gibt ein `Result`-Objekt zurück, dieser kann `Ok` oder
`Err` enthalten
* `.expect("Fehlermeldung")` entpackt das `Result`-Objekt
** Theoretisch ist das unnötig, sonst gibt es aber eine Warnung
** Sollte ein `Err` im Result sein, wird durch `expect()` eine Exception
auftreten
* `println!("Eingabe: {}", guess)` ist ein formatiertes print
== Eine random Zahl erstellen
Für eine random Zahl brauchen wir die erste Dependency. +
Also `Cargo.toml` bearbeiten:
[source, toml]
----
[dependencies]
rand = "0.3.14"
----
(In Jupyter müssen wir das anders lösen.)
Dependencies findet man auch auf https://crates.io[crates.io].
Die crate `rand` kann jetzt im Code verwendet werden.
~*In[3]:*~
[source, rust]
----
:dep rand = "0.3.15"
// Das ^ ist von Jupyter
extern crate rand;
use rand::Rng;
let secret_number: u32 = rand::thread_rng().gen_range(1, 101);
println!("{}", secret_number);
----
~*Out[3]:*~
----
37
----
== Höher oder tiefer?
Vergleichen wir doch einfach mal… +
Ein Fehler?
~*In[4]:*~
[source.notCompiling, rust]
----
use std::cmp::Ordering;
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
----
~*Out[4]:*~
----
match guess.cmp(&secret_number) {
^^^^^^^^^^^^^^ expected struct `String`, found `u32`
mismatched types
----
Unser `guess` ist ja ein `String`! Den kann man nicht einfach mit einem
`int` vergleichen (anscheinend). +
Wir müssen unser guess also umwandeln:
~*In[5]:*~
[source, rust]
----
let guess: u32 = guess.trim().parse().expect("Please type a number!");
----
`.strip()` entfernt Whitespace von beiden Seiten und `parse()` macht
eine Zahl draus.
`guess` als Variable ist schon vorhanden? Kein Problem! Rust erlaubt
``Shadowing'', damit man nicht mehrere Variablen unterschiedlicher
Datentypen für den selben Wert anlegen muss.
Jetzt sollte das Vergleichen auch klappen!
~*In[6]:*~
[source, rust]
----
use std::cmp::Ordering;
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
----
~*Out[6]:*~
----
Too big!
()
----
== Nicht nur ein Versuch
Damit wir mehrmals raten können, brauchen wir eine Schleife.
~*In[7]:*~
[source, rust]
----
let secret_number: u32 = rand::thread_rng().gen_range(1, 101);
loop {
let mut guess = evcxr_input::get_string("Number? ");
let guess: u32 = guess.trim().parse().expect("Please type a number!");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
}
----
~*Out[7]:*~
----
Number? 100
Too big!
Number? 50
Too big!
Number? 25
Too small!
Number? 30
Too small!
Number? 40
Too small!
Number? 42
Too small!
Number? 45
You win!
Number? 45
You win!
Number? 100
Too big!
Number? 45
You win!
Number?
...
----
Funktioniert, aber selbst nach dem Erraten passiert nichts und wir
sollen weiter raten. +
Offensichtlich müssen wir die Schleife dann abbrechen.
~*In[8]:*~
[source, rust]
----
let secret_number: u32 = rand::thread_rng().gen_range(1, 101);
loop {
let mut guess = evcxr_input::get_string("Number? ");
let guess: u32 = guess.trim().parse().expect("Please type a number!");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
},
}
}
----
~*Out[8]:*~
----
Number? 100
Too big!
Number? 50
Too big!
Number? 25
Too small!
Number? 42
Too big!
Number? 39
Too big!
Number? 37
Too big!
Number? 36
Too big!
Number? 33
Too big!
Number? 30
Too big!
Number? 29
You win!
()
----
== Error handling
Derzeit stirbt das Programm einfach mit einem Fehler, wenn man keine
Zahl eingibt. Das können wir auch relativ einfach fixen:
~*In[9]:*~
[source, rust]
----
loop {
let mut guess = evcxr_input::get_string("Number? ");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
// Wenn wir hier her kommen, haben wir eine gültige Zahl und beenden einfach.
break;
}
----
~*Out[9]:*~
----
Number? a
Number? b
Number? 🦀
Number? 5
()
----
Statt einem `expect()` haben wir nun eine `match`-Expression. Die Syntax
ist relativ einfach zu verstehen. Man kann auch mehrere `Ok(value)`
nutzen, wobei dann das richtige aufgerufen wird. `Err(_)` nutzt den
Unterstrich, um alle Fehler zu catchen, nicht nur einen speziellen.
Das `num` nach dem Pfeil ist ein implizites Return. Wenn eine Variable
am Ende eines Blocks steht, wird sie zurückgegeben.
== Fertig
Wir haben nun alle Elemente für das ``Higher-Lower-Game''.
+291
View File
@@ -0,0 +1,291 @@
:experimental:
:docdatetime: 2022-10-18T17:56:26+02:00
= Konzepte
https://doc.rust-lang.org/book/ch03-00-common-programming-concepts.html[Link zum Buch]
== Variablen
=== Mutability
Standardmäßig sind Variablen nicht mutable, also nicht veränderbar.
In anderen Sprachen ist das häufig `const` - in Rust gibt es aber auch `const`!
Das Folgende funktioniert also nicht:
[source.notCompiling, Rust]
----
fn main() {
let x = "Hello world!";
// Das folgende funktioniert nicht, weil x nicht mutable ist!
x = "Hello Rust!";
}
----
Damit Variablen mutable sind, muss `mut` genutzt werden:
[source, rust]
----
fn main() {
let mut x = "Hello world!";
// Hier funktioniert es.
x = "Hello Rust!";
}
----
=== Constants
Neben unveränderlichen Variablen gibt es auch noch Konstanten.
Diese sind sehr ähnlich zu ersteren, haben aber zwei relevante Unterschiede:
- Der Typ *muss* angegeben werden. Type inference funktioniert hier nicht.
- Konstanten können nur auf zu Compilezeit konstante Ausdrücke gesetzt werden, keine zu Runtime veränderlichen.
Die Konvention für Konstanten ist snake case all caps.
Ein Beispiel dafür ist folgendes:
[source, rust]
----
const MINUTES_IN_A_DAY: u32 = 24 * 60;
----
=== Shadowing
Shadowing wurde beim Higher-Lower-Game schon einmal erwähnt.
Anfangs habe ich es falsch verstanden: Ich dachte Shadowing wäre, dass eine Variable unter dem selben Namen in unterschiedlichen Datentypen vorhanden wäre.
Allerdings ist es mehr ein "Reuse" eines alten Namens.
Ein Beispiel:
[source, rust]
----
fn main() {
let x = 5;
let x = x + 5;
println!("{}", x);
}
----
Die Ausgabe des Programms ist dabei der letztere Wert, hier also 10.
Es ist also mehr eine neue Variable unter dem selben Namen wie die alte.
Sogar der Datentyp kann sich dabei ändern, man muss sich also nicht ständig neue Namen für Variablen ausdenken, nur weil man sie casted (Juchuu!).
Da Variablen immer Block-Scope-basiert (?) sind, kann dies natürlich auch in einem eingebetteten Block genutzt werden.
Der Unterschied zu mutable Variablen ist ganz einfach: neben einigen Unterschieden unter der Haube (oder?), haben mutable Variablen einen festen Datentyp, der nicht einfach geändert werden kann.
== Datentypen
=== Data Inference
Jede Variable hat einen festen Datentyp.
Der Compiler kann häufig selber herausfinden, was für einer das ist, das ist die "Type Inference".
Wenn das nicht geht, muss manuell ein Typ festgelegt werden.
Ein Beispiel:
[source, rust]
----
let guess: u32 = "42".parse().expect("Not a number!");
----
`"42"` ist offensichtlich ein String.
`parse()` kann verschiedene Ergebnisse-Datentypen erzeugen.
Das Ergebnis kann also verschiedene Typen haben, wir wollen ja aber wissen, was `guess` ist.
Hier muss also `guess: u32` angegeben werden, sonst gibt es einen Fehler vom Compiler.
=== Scalar Types
Skalar heißt: ein einziges Value.
Also eine Zahl (integer/float), Boolean oder ein einzelner Character.
==== Integer
Es signed und unsigned Integer und verschiedener Länge - 8, 16, 32, 64 und 128 Bit und "size".
"size" ist dabei architektur-abhängig, also zumeist 32 oder 64 Bit.
- signed sind im Zweierkomplement
- man kann den Datentyp direkt an eine Zahl anhängen (`5u32`)
- man kann in Dezimalschreibweise beliebig `_` einfügen für Lesbarkeit (z.B. `1_000`)
- außerdem schreibbar in hex (`0x...`), oct (`0o...`), bin (`0b...`) oder als Byte (`b'A'`)
- Division zweier Integer erzeugt einen Integer (abgerundet)
Overflows sind interessant: Wenn zu Debug compiled wird, gibt es ein panic und das Programm beendet mit einem Fehler (nicht auffangbar).
In Release ist es dann die "normale" Variante mit einem Wrap-around. +
Interessant ist, dass es zusätzliche Methoden für alles gibt (nicht nur `add`):
- `wrapping_add` ersetzt das normale Addieren und wrapt
- `checked_add` wirft einen abfangbaren Fehler bei Overflow
- `overflowing_add` gibt einen Boolean, ob ein Overflow auftritt
- `saturating_add` bleibt beim Maximum oder Minimum des verfügbaren Bereiches
[source, rust]
----
let number: u8 = 254;
println!("{}", number.wrapping_add(2));
----
Die Ausgabe des Programms ist 0.
==== Floats
Sind normale IEEE-754 floats mit 32 oder 64 Bit.
==== Boolean
Auch nichts besonders, `true` oder `false` halt.
==== Chars
Sind besonders.
Einzelne Character in Rust sind nicht einfach wie in C ein u8 unter anderem Namen, sondern wirklich ein Zeichen.
Jeder Unicode-Character ist ein Char, also auch `'🐧'`.
Chars werden mit single-quotes geschrieben (Strings mit doppelten quotes).
Allerdings scheint es noch ein wenig komplizierter zu sein, das kommt aber erst später.
=== Compound Types
Gruppierung von mehreren Werten in einem Typ.
==== Tupel
Tupel sind weird.
Sie haben eine feste Länge (wie C-Arrays), können aber verschiedene Datentypen beinhalten, also wie in Python.
Sie sind aber schreibbar, wenn `mut` zur Initialisierung genutzt wird, also nicht wie in Python.
Ein paar Beispiele als Code:
[source, rust]
----
let x: (f32, char, u8) = (1.0, '🐧', 3);
//_x.0 = 2.0; // geht nicht, da x nicht mut ist.
let mut x: (f32, char, u8) = x;
println!("{}", x.0); // x.0 == x[0] -> 1.0
// Dekonstruktur. Wie in JS wird einfach zugewiesen.
let (_a, b, _c) = x; // a = x.0 = 1.0, b = x.1 = 🐧, c = x.2 = 3
println!("{}", b); // b is 🐧
x.2 = 4; // x.2 ist schreibbar, wenn x mut ist.
println!("{}", x.2);
//x.2 = 1.0; // Das geht nicht, da x.2 ein u8 ist.
----
Falls eine Funktion in Rust nichts zurückgibt, gibt sie in leeres Tupel `()`, auch `unit type` genannt, zurück.
==== Arrays
Arrays sind wie C-Arrays, haben also eine feste Länge und nur einen Datentyp.
Für "Arrays" mit veränderbarer Länge gibt es Vektoren.
Wieder etwas Code:
[source, rust]
----
let x: [i32; 5] = [1, 2, 3, 4, 5];
// ^ so sieht der Datentyp aus
println!("{}", x[0]); // 1, so wie immer
let mut x = [15; 3]; // -> [15, 15, 15]
x[0] = 16; // x = [16, 15, 15]
----
Im Gegensatz zu C-Arrays wird allerdings vor dem Zugriff auf das Array ein Check durchgeführt.
Während C also auch außerhalb des Arrays Speicher lesen kann (mindestens theoretisch), kommt es in Rust dann zu einem Compilerfehler oder einer Runtime-Panic.
== Funktionen
Sind wie normale Funktionen in C auch. Keyword ist `fn`.
Beispiel:
[source, rust]
----
fn calculate_sum(a: i32, b: i32) -> i64 {
// Statements können natürlich normal genutzt werden
let c: i64 = a + b
// Wenn das letzte Statement kein ";" am Ende hat, ist es die Rückgabe
// Quasi "return c;"
// "let ...." returnt aber nichts
// Könnte aber auch einfach nur "a + b" sein.
c
}
----
== Kommentare
Schon häufiger in den Beispielen - einfach `//`.
Es gibt auch noch spezielle Docstrings, aber das kommt später.
== Kontrollfluss
=== `if`
- ohne runde Klammern um die Bedingung
- _immer_ geschweifte Klammern, zumindest kein Beispiel ohne
- Geht auch als short-if bei `let x = if condition { 5 } else { 6 }`
- Bedingung *muss* ein bool sein!
=== `loop`
- Basically ein `while (true)`
- `break` und `continue`
- Können labels haben. Dann kann `break 'label` genutzt werden
Beispiel für labels:
[source, rust]
----
fn main() {
'outer: loop {
let mut a = 1;
loop {
a += 1;
if a == 10 {
break 'outer;
}
}
}
}
----
==== Ergebnis aus der Loop
`break` mit Wert ist Rückgabe.
Einfaches Beispiel:
[source, rust]
----
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("{}", result); // 20
}
----
=== `while`
- nutzt auch keine runden Klammern
- sonst normal
=== `for`
Looped durch eine Collection (wie in Python).
[source, rust]
----
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("{}", element);
}
}
----
+151
View File
@@ -0,0 +1,151 @@
:experimental:
:docdatetime: 2022-10-18T17:56:26+02:00
= Ownership
https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html[Link zum Buch]
== Was ist das?
Jeder Wert hat eine Variable, die ihn "besitzt".
Jeder Wert kann zu einem Zeitpunkt nur von _einer_ Variable besessen werden.
Sollte die Variable aus dem Scope verschwinden, wird der Wert ungültig und aus dem Speicher entfernt.
== Warum?
Wenn ein Wert eine feste Länge hat, kann man sie ganz einfach auf den Stack packen.
Falls die Länge aber variabel ist, muss zu Laufzeit Speicher allokiert werden.
In C ist das dann der Aufruf `malloc`, der einen Pointer zu dem entsprechenden Bereich gibt.
Später muss dann `free` aufgerufen werden, um den Speicher wieder freizugeben, weil C keinen Garbage Collector hat, der sich alleine darum kümmert.
Es ist wenig verwunderlich, dass beim manuellen Aufruf von `malloc` und `free` allerhand schiefgehen kann.
Entweder kann Speicher zu früh (eventuell falsche Werte) oder zu spät (höherer Speicherverbrauch) freigegeben werden, oder auch zum Beispiel doppelt.
Rust nutzt deshalb (wenn man das nicht aktiv anders macht) einen anderen Ansatz, bei dem der Compiler selber `drop` (was in etwa `free` entspricht) einfügt, wenn eine Variable aus dem Scope verschwindet.
== Was das für den Code bedeutet
=== String Datentyp
Fangen wir mal mit einem Datentypen an, den das betrifft.
Neben String literals gibt es auch noch einen anderen String-Typen, Rust scheint da sich ein wenig an OOP zu orientieren.
Im Higher-Lower-Game wurde der auch schon benutzt, und User-Input mit `String::from(x)` in eine Variable gelegt.
Dieser String-Typ hat den Vorteil, dass er eine dynamische Länge hat und damit verändert werden kann.
Ein Beispiel:
[source, rust]
----
let mut x = String::from("Hello"); // Legt "dynamischen" String an
x.push_str(" world!"); // Konkatiniert an den String
println!("{}", x); // "Hello world!"
----
Das geht mit den normalen String-Literalen (`let mut x = "Hello";`) nicht, da diese eine immer eine feste Länge haben.
Theoretisch kann `x` natürlich dann überschrieben werden, mit einem String anderer Länge, aber anscheinend wird das von Rust überdeckt und wahrscheinlich ähnlich wie Shadowing gehandhabt.
=== Move
[source, rust]
----
let x = 5; // Int -> feste Größe und auf Stack
let y = x;
let s1 = String::from("Hello world"); // Dynamischer String auf Heap
let s2 = s1;
----
Hier trifft ähnliches zu, wie zum Beispiel in Python: primitive Datentypen, wie `int` oder `float`, werden einfach kopiert, wenn sie einer anderen Variable zugewiesen werden.
Bei Objekten auf dem Heap dagegen, wird auch kopiert, allerdings nur was wirklich in `s1` steht: die Referenz auf den Speicher (also ein Pointer), die Länge und andere "Metadaten".
In Sprachen mit Garbage Collector also Java oder Python haben `s1` und `s2` jetzt zu jeder Zeit den gleichen Wert.
Sollte eines verändert werden, wird das zweite auch verändert.
Sehr tückisch manchmal.
Rust löst es anders: Damit nicht zum Beispiel ein doppeltes `free` auftritt, wird hier `s1` invalidiert, nachdem es in eine andere Variable gegeben wurde.
Wie oben beschrieben: Der Wert von `s1` kann nur einen Besitzer haben und der wird mit der letzten Zeile gewechselt.
Sollte man nach dem Snipped ein print nutzen, gäbe es einen Compile-Fehler.
Natürlich gibt es auch Wege für ein "deep copy", allerdings ist das nie der Standard.
Die Methode dafür (muss natürlich implementiert sein) heißt `clone`.
Wir könnten also auch schreiben `let s2 = s1.clone()` und beide Variablen wären unabhängig voneinander und gültig.
Das kann aber sehr teuer für die Laufzeit sein!
=== Copy und Drop Annotation
Im Buch wird jetzt noch kurz angeschnitten, dass diese primitiven Datentypen kopiert werden, weil sie das `Copy` "trait" implementiert hätten.
An dem Punkt habe ich noch keine Ahnung, was das ist, aber ich denke es wird so ähnlich sein, wie Java Interfaces?
Wenn ein Datentyp den `Copy` trait hat, wird es auf jeden Fall einfach kopiert, statt gemoved.
Es gibt auch ein `Drop` trait, mit dem noch irgendwas ausgeführt werden kann, wenn ein Wert dieses Types gedropped wird. Dieser trait ist exklusiv zu `Copy`.
== In Funktionen
Sollte eine Funktion eine Variable übergeben bekommen, wird auch das Ownership der Variable dahin übergeben.
Nach Ausführen der Funktion ist die Variable ungültig.
Der Wert wird aber möglicherweise wieder zurückgegeben.
Das gilt natürlich nicht für die `Copy`-Datentypen.
Wie vorher schon erfahren, kann man auch Referenzen und mutable Referenzen übergeben, wodurch die Variable nur "geborgt" wird.
In C/C++ gibt es ja beim Aufruf von zum Beispiel Funktionen eines Structs oder Objekt, den Pfeil (`x->fun()`) der quasi auch nur ein hübsches `(*x).fun()` ist.
In Rust sag ich der Funktion, dass ein Argument eine Referenz auf einen Datentypen ist, und ich kann mit der Variable arbeiten, als wäre sie da.
Wenn ich den Wert der Referenz haben will, muss ich sie natürlich immer noch dereferenzieren.
Solange die Referenz nicht mutable ist, können davon unendlich viele existieren.
Mutable References werden noch wieder kritisch behandelt - es kann zu einem Zeitpunkt immer nur eine mutable Referenz geben (ähnlich Ownership also).
Noch krasser: Eine mutable Referenz kann nicht erstellt werden, solange eine immutable existiert.
"Existieren" bedeutet hier natürlich: Wenn die immutable Referenz nach Erstellen der mutable Referenz noch einmal genutzt wird.
Sonst kümmert sich der Compiler drum.
Das heißt natürlich auch, dass alle immutable Referenzen invalid werden, sobald eine mutable Referenz erstellt wird.
Damit werden (unter anderem) Race Conditions schon beim Compilen verhindert.
=== Dangling references
[source.notCompiling, rust]
----
fn dangle() -> &String {
let s = String::from("hello");
&s // Referenz auf s returned
} // Hier fliegt s aus dem Scope
----
Hier ist eine Funktion gebaut, die nur eine Referenz zurückgibt.
Allerdings wird `s` ja (da nach Funktion out of scope) nach der Funktion gedropped.
Der Compiler gibt uns dafür auch einen Fehler.
Das Tutorial sagt an diesem Punkt, dass man am besten keine Referenzen zurückgibt, die Fehlermeldung redet aber auch noch von "lifetimes" und dass `&'static String` ein möglicher Rückgabetyp wäre.
Das kommt wohl aber erst später...
== Der Slice-Datentyp
Wenn wir auf Arrays arbeiten, wäre es ja cool, an verschiedenen Stellen gleichzeitig zu arbeiten.
Nur so kann multithreading etc. funktionieren.
Dafür hat Rust den Slice-Datentyp.
Der funktioniert ähnlich wie Array-Ranges in Python.
[source, rust]
----
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
----
Rust kümmert sich dabei darum, dass wir jetzt keinen Unsinn mehr mit `s` machen.
Sollte man versuchen `s` zu mutaten und danach die Slice zu nutzen, gibt es einen Fehler, denn Slices sind genauso Referenzen.
Fun fact: String Literale sind auch Slices und damit Referenzen von Strings.
Noch mehr fun fact: Da dynamische String und String Literale damit quasi den selben Typ beschreiben, haben sie auch den gemeinsamen Typ `&str`.
Für Leseoperationen kann also im Allgemeinen dieser benutzt werden.
Slices können auch mutable sein, dafür muss aber das ursprüngliche Array mutable sein und es kann immer nur ein mutable Slice gleichzeitig existieren (also genauso wie beim Ownership).
+210
View File
@@ -0,0 +1,210 @@
:experimental:
:docdatetime: 2022-08-10T17:04:53+02:00
= Structs
https://doc.rust-lang.org/book/ch05-00-structs.html[Link zum Buch]
== Was sind Structs
Structs kennt man ja aus C/C++.
Man kann es (denke ich) auch mit JavaScript Objekten vergleichen.
In Structs gruppiert man zusammengehöriges Zeug und hat so eine Art Pseudo-OOP.
Man kann damit neue Datentypen machen.
== How to
=== "Normale" Structs
[source, rust]
----
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
fn main() {
let mut user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
println!("{}", user1.email);
user1.email = String::from("anotheremail@example.com");
}
----
Hinweis: Es können nicht einzelne Felder mutable sein, sondern wenn dann immer das ganze Struct.
==== Dinge wie in Javascript
Wenn die Variable heißt wie das Feld, kann man auch statt `email: email` einfach nur `email` schreiben.
Wenn man ein neues Struct aus einem alten mit Updates erstellen will, geht das auch mit einer Art Spread-Parameter:
[source, rust]
----
let user2 = User {
email: String::from("another@example.com"),
..user1
};
----
`..user1` *muss* als letztes kommen und füllt dann alle bisher nicht gesetzten Felder.
Außerdem ist das etwas tricky:
Wenn die Daten, die von `user1` zu `user2` übertragen werden, gemoved werden (sprich: keine primitiven Datentypen sind), dann ist `user1` danach ungültig.
Hätten wir jetzt auch noch einen neuen `username` gesetzt (auch ein String) und nur `active` und `sign_in_count` übertragen, wäre `user1` noch gültig.
=== Tupel Structs
[source, rust]
----
struct RGBColor(u8, u8, u8);
fn main() {
let black = Color(0, 0, 0)
}
----
Sind nutzbar wie Tupel (destrucuture und `.index` zum Zugriff auf Werte), allerdings eben ein eigener Typ.
=== Unit-Like Structs
[source, rust]
----
struct AlwaysEqual;
----
Ein Struct muss keine Felder haben.
Das Buch meint, man könnte für diesen Datentypen jetzt noch Traits implementieren, aber davon habe ich noch keine Ahnung.
Nur dann macht diese Art von Struct irgendwie Sinn.
== Ownership der Felder
Im ersten Beispiel wird `String` satt `&str` genutzt.
Wir wollen am besten im Struct keine Referenzen, oder es müssen "named lifetime parameter" sein, etwas das wir erst später lernen.
Der Compiler wird sonst streiken.
== Das erste Mal Traits
Im Buch folgt ein Beispielprogramm für ein Struct, das ein Rechteck abbildet.
Wir wollten das ganze printen (mit `{}` als Platzhalter), allerdings implementiert Das Rechteck nicht `std::fmt::Display`.
Das scheint eine Art `toString()` für Rust zu sein.
Es gibt aber noch eine andere Möglichkeit und das haben wir schonmal für Tupel genutzt:
`{:?}` als Platzhalter (bzw. `{:#?}` für pretty print).
Dafür brauchen wir aber das Trait `Debug`.
Zum Glück scheint das aber einfach zu implementieren sein, es muss nur implementiert werden.
Der Compiler schlägt uns zwei Varianten vor:
1. `#[derive(Debug)]` über der Definition des Structs
2. `impl Debug for Rectangle` manuell
Jetzt können wir Variablen dieses Typs printen und es zeigt uns Datentyp und Felder an.
Alternativ kann man auch das Makro `dbg!(...)` nutzen.
Das wird dann auf `stderr` geprintet.
Man kann sogar ein Statement da rein packen (also zum Beispiel `30 * x`) und bekommt das Statement mit dem Ergebnis geprintet, wobei das Ergebnis (als Wert, nicht Referenz) auch zurückgegeben wird.
== Funktionen in Structs
Unser Struct soll jetzt auch eine Funktion auf sich selbst aufrufen können.
Tatsächlich ist der sehr einfach und sehr OOPig.
Die folgenden Beispiele sollten relativ viel erklären:
[source, rust]
----
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
// Das ist eine Methode/"method"
// Erster Parameter ist &self (/&mut self) und wird aufgerufen wie folgt:
// var.area();
fn area(&self) -> u32 {
self.width * self.height
}
// Das ist eine "associated function"
// Kein &self und aufgerufen wie folgt:
// Rectangle::square(5);
fn square(size: u32) -> Rectangle {
Rectangle {
width: size,
height: size,
}
}
}
// Mehrere impl Blöcke sind erlaubt
impl Rectangle {
// var.has_same_area(&other);
fn has_same_area(&self, other: &Rectangle) -> bool {
self.area() == other.area()
}
// Rectangle::same_area(&first, &second);
fn same_area(first: &Rectangle, second: &Rectangle) -> bool {
first.area() == second.area()
}
// Methoden können auch wie Felder heißen
fn width(&self) -> bool {
self.width > 0
}
}
fn main() {
let rect1 = Rectangle {
width: 12,
height: 3,
};
let rect2 = Rectangle::square(6);
println!("{}", rect1.area()); // 36
println!("{}", rect2.area()); // 36
println!("{}", rect1.has_same_area(&rect2)); // true
println!("{}", rect2.has_same_area(&rect1)); // true
println!("{}", Rectangle::same_area(&rect1, &rect2)); // true
}
----
=== `&mut self`
Eine Methode kann auch `&mut self` als ersten Parameter haben.
Dann können auch Felder geschrieben werden. In diesem Fall werden Referenzen aber invalidiert!
[source, rust]
----
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn change_width(&mut self, width: u32) {
self.width = width;
}
}
fn main() {
let mut rect1 = Rectangle {
width: 12,
height: 3,
};
let ref1 = &rect1;
rect1.change_width(5);
println!("{}", ref1.width); // <- geht nicht!
}
----
+152
View File
@@ -0,0 +1,152 @@
:experimental:
:docdatetime: 2022-10-18T17:56:26+02:00
= Enums und Pattern Matching
https://doc.rust-lang.org/book/ch06-00-enums.html[Link zum Buch]
== Enums
Enumarations gibt's in vielen Programmiersprachen, in Rust scheinen sie aber eine große Rolle einzunehmen.
"Enumeration" stimmt eigentlich gar nicht, Enums haben hier nämlich nicht zwangsläufig was mit Zahlen zu tun.
Grundsätzlich ist ein "Enum" in Rust näher am "Union" würde ich denken.
Ein einfaches Beispiel für ist der Typ `Option<T>` (vergleichbar mit Python oder Java `Optional`).
Dieser ist entweder `None` oder `Some(value: T)` - es kann also ein Wert zusätzlich zur "Definition" beinhalten.
[source, rust]
----
enum Farbcode {
Hex,
Rgb,
}
let hexcolor = Farbcode::Hex;
----
`Farbcode` ist also ein im Code benutzbarer Datentyp, genauso wie `Farbcode::Hex`.
Wenn eine Funktion nun eine Variable mit Typ `Farbcode` erwartet, kann diese Variable sowohl `Hex` oder `Rgb` sein.
Die Funktion kann dann je nach Typ verschieden funktionieren.
Wie schon erwähnt, kann so ein Enum-Wert auch Werte beinhalten, um das zu machen, schreiben wir den Code einfach um:
[source, rust]
----
enum Farbcode {
Hex(String),
Rgb(u8, u8, u8),
}
// Alternativ:
struct Hex(String);
struct Rgb(u8, u8, u8);
enum Farbcode {
Hex,
Rgb
}
let hexcode = Farbcode::Hex(String::from("00affe"));
let rgbcode = Farbcode::Rgb(125, 255, 255);
----
Natürlich können die Structs jeder Art sein.
Enums sind aber auch selber eine Art Struct.
Also können wir für Enums auch Methoden definieren wie für Structs.
[source, rust]
----
impl Farbcode {
fn to_css_string(&self) {
// Methode, die für Hex und Rgb angewendet werden kann
}
}
let rgbcode = Farbcode::Rgb(125, 255, 255);
rgbcode.to_css_string();
----
Tatsächlich ist damit so etwas wie Vererbung implementierbar.
Es gibt zwar keine Attribute, aber da ja auch die internen Structs Methoden haben können, ist eine gewisse Hierarchie erstellbar.
=== `Option<T>`
Options hab ich oben schonmal kurz beschrieben.
In Rust ist dieser Datentyp sehr wichtig.
Die Dokumentation dazu ist https://doc.rust-lang.org/std/option/enum.Option.html[hier zu finden] und enthält sehr viel Wichtiges und Interessantes.
== `match`
`match` ist quasi das `switch` von Rust.
Nur kann es auch prüfen, ob eine Variable einem Enum-Typen angehört.
So wie Rust bis jetzt klang, kann wahrscheinlich jedem Datentypen ein "match-Trait" gegeben werden, der dann eine "Zugehörigkeit" (Gleichheit stimmt ja irgendwie nicht) prüfen kann.
Aber ganz einfach: Angenommen wir wollen die Methode `to_css_string` von oben implementieren.
Diese Methode muss ja, je nach Typ, völlig unterschiedlich funktionieren.
[source, rust]
----
enum Farbcode {
Hex(String),
Rgb(u8, u8, u8),
}
impl Farbcode {
fn to_css_string(&self) -> String {
match self {
// format! ist offensichtlich ein Pragma, dass Strings erstellt auf die selbe Weise wie println!
Farbcode::Hex(hex) => format!("#{}", hex),
Farbcode::Rgb(r, g, b) => format!("rgb({}, {}, {})", r, g, b),
}
}
}
fn main() {
let hexcode = Farbcode::Hex(String::from("affe00"));
let rgbcode = Farbcode::Rgb(125, 255, 255);
println!("{}", hexcode.to_css_string());
println!("{}", rgbcode.to_css_string());
}
----
Hier sieht man auch ganz gut, wie im Match dem "Inhalt" des Enums direkt Namen gegeben werden und Tuples auch dekonstruiert.
Im Beispiel ist auch deutlich, dass `match` einen Rückgabewert hat, nämlich das, was im Statement(-Block) des jeweiligen Matches zurückgegeben wird.
=== Vollständigkeit
Entweder muss ein `match` eines Enums jede mögliche Variante abgrasen oder es gibt zwei Alternativen.
`other` ist quasi das `default` von Rust.
Aber auch `\_` matched alles.
Der Unterschied ist, dass bei `other` noch der Inhalt genutzt werden kann, bei `_` wird er direkt ignoriert und ist nicht nutzbar.
=== `if let`
Dieses if-Konstrukt nutzt man am besten, wenn man nur auf eine einzelne Variante eines Enums prüfen möchte.
Letztendlich ist es ganz simpel:
[source, rust]
----
#[derive(Debug)]
enum Muenzwurf {
Kopf,
Zahl,
Seite
}
fn print_wurf(ergebnis: Muenzwurf) {
if let Muenzwurf::Seite = ergebnis {
println!("Das glaub ich nicht! Seite?!");
} else {
println!("Du hast {:?} geworfen.", ergebnis);
}
}
fn main() {
let ergebnis = Muenzwurf::Zahl;
print_wurf(ergebnis); // Du hast Zahl geworfen.
let ergebnis = Muenzwurf::Seite;
print_wurf(ergebnis); // Das glaub ich nicht! Seite?!
}
----
+166
View File
@@ -0,0 +1,166 @@
:experimental:
:docdatetime: 2022-10-18T17:56:26+02:00
= How to: Projektmanagement
https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html[Link zum Buch]
== Packages, Crates, Modules, was?
Rust hat ein sehr hierarchisches Konzept, was die Strukturierung von Projekten angeht.
Fangen wir mal von oben an:
=== Packages
Packages bestehen aus Crates.
Sie fassen diese also quasi zusammen und in `Cargo.toml` wird definiert, wie die Crates zu bauen sind.
Jedes Package, das wir bis jetzt erstellt haben, hatte standardmäßig eine "binary create" (dazu gleich mehr) im generierten Projekt.
Die Crates können (soweit wie ich das verstanden habe) in beliebigen Ordnern existieren, falls die Crate so heißen soll wie das Package, ist der Standardpfad `src/main.rs` (für binary) bzw. `src/lib.rs` (für library).
==== Warum mehrere Crates in einem Projekt?
Einfaches Beispiel: Man hat eine library crate, die Funktionen für einen Webserver bereitstellt.
Man kann dann einfach eine binary crate hinzufügen, die eine Referenz-Nutzung abbildet, also direkt ein Beispiel ist.
Dies hilft Nutzern direkt und gleichzeitig testet es direkt auch (wobei richtige Tests natürlich anders zu implementieren sind).
=== Crates
Creates sind die eigentlichen "Module".
Es gibt zwei Arten: binary und library.
==== Binary Crates
Diese Crates können zu einer ausführbaren Datei kompiliert werden.
Jedes der bisherigen Beispiele, z.B. auch das link:#/diary/rust/3[Higher-Lower-Spiel] sind eine solche binary crate.
Ihr Merkmal ist vor allem, dass eine `main`-Funktion existiert, die der Einstiegspunkt ist.
==== Library Crate
Wie der Name schon sagt, stellt diese Art Crate nur Funktionen zur Verfügung wie eine Bibliothek.
=== Modules
Innerhalb einer Crate können Module existieren.
Und hier ist auch schon wieder von OOP abgeschaut.
Es können nämlich Rusts `private` und `public` hier genutzt werden.
Im Hauptprogramm kann mit `mod modulname;` das Modul eingebunden werden. Gesucht wird das Modul dann in `./modulname.rs` oder in `./modulname/mod.rs`, wobei letzteres aber aussieht, als wäre es die veraltete Version.
Zusätzlich kann auch direkt inline ein Modul erstellt werden.
Ein Beispiel:
[source.notCompiling, rust]
----
mod testmodul {
mod nested_modul {
fn funktion() {
funktion2();
}
fn funktion2() {
println!("Hello World");
}
}
mod zweites_modul {
fn funktion() {}
}
}
fn main() {
// Hello world! Geht nicht...
crate::testmodul::nested_modul::funktion();
}
----
Das funktioniert noch *nicht*.
Denn standardmäßig ist alles private, was nicht explizit public ist.
Damit wir den obigen Aufruf machen können, muss der Code so aussehen:
[source, rust]
----
mod testmodul {
pub mod nested_modul {
pub fn funktion() {
funktion2();
}
fn funktion2() {
println!("Hello World");
}
}
mod zweites_modul {
fn funktion() {}
}
}
fn main() {
// Hello world!
crate::testmodul::nested_modul::funktion();
}
----
Nur so kann auf Submodule und Funktionen dieser Module zugegriffen werden.
Wie im "normalen" OOP, können aus diesen öffentlichen Funktionen aber dann auch private aufgerufen werden.
==== Von unten nach oben
Um aus einem inneren Modul auf das äußere zuzugreifen, kann übrigens `super::...` verwendet werden.
==== Structs und Enums
In Modulen können natürlich auch Structs und Enums verwendet werden.
Bei Structs ist die Besonderheit, dass die einzelnen Attribute auch wieder private oder public sein können.
So kann man folgendes machen:
[source, rust]
----
mod testmodul {
pub struct Teststruct {
pub oeffentlich: String,
privat: String,
}
impl Teststruct {
pub fn generator(wert: &str) -> Teststruct {
Teststruct {
oeffentlich: String::from(wert),
privat: String::from("Sehr geheimer Wert"),
}
}
}
}
fn main() {
let a = crate::testmodul::Teststruct::generator("Irgendein Wert");
// Geht
println!("Öffentlich: {}", a.oeffentlich);
// Geht nicht!
// println!("Privat: {}", a.privat);
}
----
Dagegen gilt für Enums: Wenn der Enum public ist, sind auch alle Varianten public.
==== Abkürzungen mit `use`
Angenommen, wir haben eine Mediathek mit Filmen, Serien, Spielen, etc. und brauchen immer lange Zugriffspfade (also z.B. `crate::medien::spiele::liste::add()`), obwohl wir nur Spiele brauchen, kann `use` benutzt werden.
Wenn wir also `use crate::medien::spiele;` in unseren Code einfügen, können alle diese Befehle verkürzt werden auf eben z.B. `spiele::liste::add()`.
Theoretisch können wir das bis hin zu einzelnen Funktionsnamen machen, `se crate::medien::spiele::liste:add;`, würde `add()` im Scope verfügbar machen.
Dabei gibt es zwei Hinweise:
1. Es funktioniert nur, wenn sich zwei Namespaces nicht überschneiden. Ein Zufügen von `use andere::mod::add;` geht also nicht!
2. Das ganze gilt nur in genau diesem Scope. Falls wir jetzt ein weiteres Modul definieren, können wir darin nicht die Pfade kürzen.
Und für beides gibt es Umwege:
1. Man kann `use andere::mod::add as modAdd;` benutzen.
2. Sollten wir `pub use ...` benutzen, kann tatsächlich diese Abkürzung benutzt werden.
`pub use` kann auch benutzt werden, alle möglichen Module in seiner Crate miteinander reden zu lassen, aber nach außen nur bestimmte Schnittstellen freizugeben.
+239
View File
@@ -0,0 +1,239 @@
:experimental:
:docdatetime: 2022-10-18T17:56:27+02:00
= Standard Collections
https://doc.rust-lang.org/book/ch08-00-common-collections.html[Link zum Buch]
== `Vec<T>` - Vektoren
Vektoren kennt man ja aus C++ als dynamische Alternative zu Arrays.
Es ist quasi eine Linked List, die beliebig erweiterbar bzw. manipulierbar ist.
Wie in der Überschrift zu sehen, sind sie typspezifisch, man kann also nur Daten eines einzigen Typs in diese Liste speichern.
Wie benutze ich jetzt so einen Vector?
Hier einfach mal eine Übersicht:
[source, rust]
----
// -- Erstellen --
// Mit dem vec!-Pragma
let v = vec![1, 2, 3];
let v = vec![0; 5]; // 5 Nullen
// Mit new() (mit mut, damit wir gleich etwas zufügen können)
let mut v: Vec<i32> = Vec::new();
// -- Updaten --
// Push
v.push(1);
v.push(2);
v.push(3);
v.push(4);
v.push(5);
// -> [1,2,3,4,5]
// Pop, returnt ein Optional<T>
v.pop(3);
v.pop(4);
// -> [1,2,3]
// Insert
v.insert(1, 9); // -> [1,9,2,3]
// Remove
v.remove(1); // -> [1,2,3]
// -- Lesen --
// Über Index
let second: &i32 = &v[1];
// Mit get() (gibt ein Option<&T>)
// Hat den Vorteil, dass es nicht einfach paniced.
match v.get(2) {
Some(value) => {...}
None => (),
}
// -- Drüber iterieren --
// mut natürlich nur, wenn wir es verändern wollen
// Wir brauchen hier aber * zum Dereferenzieren!
for i in &mut v {
*i += 50;
}
----
=== Achtung, Scope
Wenn ein Vector aus dem Scope fällt, wird er zusammen mit seinem Inhalt gedropped.
Blöd, wenn man Referenzen auf Elemente aus dem Vector hat.
=== Ownership
Wenn `push()` ausgeführt wird, findet ein mutable borrow statt und das kommt mit allen Eigenheiten wie vorher.
Alle Referenzen, die vorher über Index oder `get()` genommen wurden, sind dann ungültig.
Das liegt daran, dass es by `push()` passieren kann, dass neue Speicher reserviert und genutzt werden muss, falls die Elemente nicht mehr nebeneinander passen.
=== Lifehack: Enum für verschiedene Datentypen
Ein Vector kann nur einen Datentypen aufnehmen?
Der Datentyp kann aber auch ein Enum sein!
Also wenn mal ein String neben Zahlen gespeichert werden soll: Einfach einen Enum mit beiden Varianten anlegen.
=== Weiteres
Es gibt auch hier Slices und noch eine Menge Tricks.
Die https://doc.rust-lang.org/std/vec/struct.Vec.html[Dokumentation zum Vector] ist da wahrscheinlich sehr hilfreich.
== Strings
Strings eine Collection?
Klar, wie in C ja auch.
Es gibt im Core eigentlich nur `str`, also ein Slice.
Der `String`-Typ kommt aus der Standard-Lib und ist einfacher zu nutzen.
In den meisten Programmiersprachen kennt man ja `toString()`, hier ist es natürlich `to_string()` und für alle Typen definiert, die den Trait `Display` implementiert haben.
Das gilt zum Beispiel auch für String-Literale, man kann also `str` ganz einfach in einen `String` umwandeln, indem man `"text".to_string()` aufruft.
Natürlich funktioniert auch `String::from("text")`.
String sind UTF-8 encoded, also egal mit was man sie bewirft, es sollte klappen.
Allerdings ist das Handling deshalb etwas kompliziert.
Rust fasst das ganz gut am Ende der Seite zusammen mit
[quote]
To summarize, strings are complicated.
Hier wieder eine Übersicht zur Nutzung:
[source, rust]
----
// -- Erstellen --
// String::from()
// "Hello ".to_string() macht das selbe
let mut s = String::from("Hello ");
// -- Manipulieren --
// push_str()
// Hier wird kein Ownership übergeben!
// Sollte "world" in einer Variable stehen, ist sie danach weiter nutzbar.
s.push_str("world");
// -> Hello World
// push(), für einen einzelnen Character
s.push('!');
// +
// Ist etwas tricky. Der Methodenkopf sieht so aus:
// fn add(self, s: &str) -> String
// Also wird Ownership von s1 übergeben und s2 offensichtlich magisch von &String zu &str.
// Somit ist danach auch s1 nicht mehr gültig.
let s1 = String::from("Hello ");
let s2 = String::from("world!");
let s3 = s1 + &s2;
// Es geht auch mit noch mehr Elementen!
// Damit das aber nicht zu unübersichtlich wird, gibt es format!
let s1 = String::from("Schere");
let s2 = String::from("Stein");
let s3 = String::from("Papier");
let s4 = format!("{}, {}, {}", s1, s2, s3);
// Hier wird kein Ownership übergeben!
----
=== Indexing
Aus Python z.B. kennt man ja `"Hallo"[0] -> H`.
In Rust geht das nicht.
Das liegt am Aufbau der String, dass sie eben UTF-8 verwenden und `String` eigentlich nur ein `Vec<u8>` ist.
Das macht das ganze ordentlich schwierig.
=== Slicing
Ist immer eine schlechte Idee, außer man weiß exakt wie lang die einzelnen Zeichen (in Byte) des Strings sind.
Im Englischen ist es normalerweise 1 Byte pro Zeichen, Umlaute sind schon 2, und so weiter.
Sollte man aus Versehen ein Zeichen "durchschneiden" (also nur 1 Byte eines "ü" im Slice haben), gibt es eine Runtime Panic.
=== Iterieren
Über einem String iterieren geht ganz ok.
[source, rust]
----
for c in "hallo".chars() {
println!("{}", c);
}
// Ist für europäische Sprachen absolut geeignet.
// Bei Hindi wird es schon wieder eklig.
for b in "hallo".bytes() {
println!("{}", b);
}
// Wirft eben die einzelnen u8 raus.
----
Wenn wir "grapheme" haben wollen (Was anscheinend so etwas wie "volle Zeichen" sind, mehr als nur char), gibt es keine eingebaute Funktion aber crates, die das lösen.
== HashMaps
Der Erlöser der Programmierer und Lösung jeder Aufgabe bei der Bewerbung, die "O(n)" enthält.
Oder so ähnlich.
Nutzung:
[source, rust]
----
// Das hier ist für die "Abkürzungen"
use std::collections::HashMap;
// -- Erstellen --
// iter(), zip() und collect()
// collect() kann in alles mögliche wandeln, deshalb muss der Typ angegeben werden.
let woerter = vec![String::from("eins"), String::from("zwei"), String::from("drei")];
let zahlen = vec![1, 2, 3];
let mut zahlwort: HashMap<_, _> = woerter.into_iter().zip(zahlen.into_iter()).collect();
// Einfach normal
let mut zahlwort = HashMap::new();
// -- Nutzung --
// insert()
// Ownership wird bei den Strings übergeben
zahlwort.insert(String::from("eins"), 1);
zahlwort.insert(String::from("zwei"), 2);
zahlwort.insert(String::from("drei"), 5);
zahlwort.insert(String::from("drei"), 3); // Überschreibt vorheriges
// get()
// Hier wird kein Ownership übergeben
let testwort = String::from("eins");
let eins_oder_none = zahlwort.get(&testwort); // -> Optional
// entry()
// Checkt, ob etwas da ist und kann im Zweifel etwas einfügen
zahlwort.entry(String::from("vier")).or_insert(4);
// entry kann auch genutzt werden, um den bisherigen Eintrag upzudaten
let bisher = zahlwort.entry(String::from("vier")).or_insert(4); // &mut i32
*bisher += 1;
// Drüber Iterieren
for (key, value) in &zahlwort {
println!("{}: {}", key, value);
}
// Sehr selbsterklärend
----
=== Ownership
Falls Key oder Value kein Copy Trait haben, wird der Ownership übergeben. Strings sind also danach ungültig.
== Hausaufgaben
Das Buch gibt uns hier ein paar Aufgaben, die wir jetzt lösen können:
* Den Median aus einer Liste finden. Erst sortieren, dann den mittleren Wert.
* Wörter zu "pig-latin" machen. Wenn erster Buchstabe ein Vokal ist, wird "-hay" angehängt, wenn es ein Konsonant ist, wird er ans Ende angefügt (nach "-") und "ay" angehängt.
* Eine kleine Befehlszeile mit Befehlen wie "Add Name to Sales" und Ausgabe.
Vielleicht werde ich sie irgendwann mal lösen, dann landet der Code hier.
=== Aufgabe 1
[source, rust]
----
fn main() {
let mut list = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort();
let mid = list.len() / 2; // integer divide
println!("{}", list[mid]);
}
----
@@ -0,0 +1,104 @@
:experimental:
:docdatetime: 2022-08-22T17:04:01+02:00
= Errors und `panic!`
https://doc.rust-lang.org/book/ch09-00-error-handling.html[Link zum Buch]
== `panic!`
Dieses Makro it furchtbar simpel: Es macht Panik und das Programm stirbt mit einem Fehler.
Diesen Fehler kann man auch nicht catchen.
Wenn `RUST_BACKTRACE` als Umgebungsvariable gesetzt ist, wird auch noch ein langer Traceback angezeigt, allerdings nur, solange Debug-Symbole aktiviert sind (also bei `cargo run` oder `cargo build` ohne `--release`).
Will man gar kein Traceback und kein "unwinding" (das "hochgehen" durch den Funktionsstack und Aufräumen), kann man auch noch folgendes zu seiner `Cargo.toml` hinzufügen:
[source, toml]
----
[profile.release]
panic = 'abort'
----
== `Result<T, E>`
Der Result-Datentyp ist deutlich besser für mögliche Fehler geeignet, die das Programm abfangen und bearbeiten kann.
Falls zum Beispiel eine Datei auf dem Dateisystem nicht existiert, ist es ja manchmal gewünscht, dass diese Datei dann einfach angelegt wird.
Der `Result`-Typ ist ein Enum von `Ok<T>` und `Error<E>`.
Also kann dann mit `match` geprüft werden, was genau wir gerade bekommen haben.
Alternativ können auch Funktionen wie `unwrap_or_else(|error| {...})` genutzt werden.
`Ok<T>` verhält sich wie `Some<T>` und sollte zurückgegeben werden, wenn alles glatt läuft.
`Error<E>` beinhaltet einen Fehler.
Der genaue Fehler kann mit `error.kind()` erfahren werden; ein weiteres `match` ist dann eine "genauere" Fehlerbehandlung.
Ein volles Beispiel mit ganz viel `match`:
[source, rust]
----
use std::fs::File;
use std::io::ErrorKind;
fn main() {
let greeting_file_result = File::open("hello.txt");
let greeting_file = match greeting_file_result {
Ok(file) => file,
Err(error) => match error.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(fc) => fc,
Err(e) => panic!("Problem creating the file: {:?}", e),
},
other_error => {
panic!("Problem opening the file: {:?}", other_error);
}
},
};
}
----
=== `unwrap()` und `expect()`
Machen aus einem `Result<T, E>` entweder ein `T` oder eine `panic!`.
Bei `expect()` kann man noch die Fehlermeldung festlegen.
Warum man jemals `unwrap()` nehmen sollte, erschließt sich mir nicht ganz.
=== `?`
Oft schreibt man Funktionen so, dass Fehler weiter "hochgegeben" werden, falls man welche bekommt.
`?` macht genau das bei einem Result.
Codemäßig erklärt:
[source, rust]
----
let a = match result {
Ok(nummer) => nummer,
Err(e) => return Err(e),
};
// Ergibt das selbe wie
let a = result?;
----
Das `?` kann auch für zum Beispiel `Option` verwendet werden, dann returned es natürlich `None`.
=== Rückgaben von `main()`
Bis jetzt hat `main()` immer nichts, also implizit `()` zurückgegeben.
Manchmal wollen wir ja aber auch was anderes als "0" als return code haben.
Wir können Tatsächlich auch ein Result zurückgeben. Und zwar ein `Result<(), Box<dyn Error>>`.
Der zweite Typ dort, kann wohl als "irgendein Fehler" gelesen werden und wird später noch erklärt.
Allgemein kann aber jedes Objekt, dass `std::process::Termination`-Trait implementiert von main als Rückgabe genutzt werden.
== Wann `Result<T, E>`, wann `panic!`?
Der Artikel ist sehr sehr sehr lang, aber eigentlich sagt er:
"Panic nur wenn es eben nicht gerettet werden kann."
Und obviously in Tests.
Und man kann natürlich auch tolle eigene Fehlertypen für Result bauen.
+10
View File
@@ -0,0 +1,10 @@
[
{
"description": "Awarded with the Deutschlandstipendium",
"icon": "mdi:seal"
},
{
"description": "Developer of the official testbed for Digital Twins in Industry 4.0 of the TU Dresden",
"icon": "mdi:robot-industrial"
}
]

Before

Width:  |  Height:  |  Size: 488 KiB

After

Width:  |  Height:  |  Size: 488 KiB

+171
View File
@@ -0,0 +1,171 @@
{
"cards": [{
"title": "Programming Languages",
"skillBars": [{
"name": "TypeScript",
"icon": "mdi:language-typescript",
"pct": 100
}, {
"name": "JavaScript",
"icon": "mdi:language-javascript",
"pct": 100
}, {
"name": "Java",
"icon": "mdi:language-java",
"pct": 80
}, {
"name": "Python 3",
"icon": "mdi:language-python",
"pct": 95
}, {
"name": "PHP",
"icon": "mdi:language-php",
"pct": 50
}, {
"name": "Bash",
"icon": "mdi:bash",
"pct": 60
}, {
"name": "C/C++",
"icon": "mdi:language-cpp",
"pct": 60
}, {
"name": "Rust",
"icon": "mdi:language-rust",
"pct": 70
}, {
"name": "C#",
"icon": "mdi:language-csharp",
"pct": 90
}],
"additional": [{
"name": "SQL Languages",
"icon": "mdi:database-search"
}],
"colors": {
"background": "#C3A3F7",
"bars": "#8771AB",
"heading": "#55476B",
"useDarkColor": true,
"badges": {
"background": "#55476B",
"useDarkColor": false
}
}
}, {
"title": "Web Technologies",
"skillBars": [{
"name": "TypeScript",
"icon": "mdi:language-typescript",
"pct": 100
}, {
"name": "JavaScript",
"icon": "mdi:language-javascript",
"pct": 100
}, {
"name": "React",
"icon": "mdi:react",
"pct": 80
}, {
"name": "HTML5",
"icon": "simple-icons:html5",
"pct": 100
}, {
"name": "CSS3",
"icon": "simple-icons:css3",
"pct": 90
}],
"additional": [{
"name": "Express",
"icon": "simple-icons:express"
}, {
"name": "Sass",
"icon": "simple-icons:sass"
}, {
"name": "Spring Boot",
"icon": "simple-icons:springboot"
}],
"colors": {
"background": "#A4C7EA",
"bars": "#706EB8",
"heading": "#2A2885",
"useDarkColor": true,
"badges": {
"background": "#2A2885",
"useDarkColor": false
}
}
}, {
"title": "Embedded Programming",
"skillBars": [{
"name": "C/C++",
"icon": "mdi:language-cpp",
"pct": 60
}],
"additional": [{
"name": "Arduino",
"icon": "simple-icons:arduino"
}, {
"name": "ESP",
"icon": "simple-icons:espressif"
}],
"colors": {
"background": "#EA8585",
"bars": "#E53E3E",
"heading": "#661C1C",
"useDarkColor": true,
"badges": {
"background": "#661C1C",
"useDarkColor": false
}
}
}, {
"title": "Operating Systems",
"skillBars": [],
"additional": [{
"name": "Windows",
"icon": "simple-icons:windows"
}, {
"name": "Linux",
"icon": "simple-icons:linux"
}, {
"name": "Android",
"icon": "simple-icons:android"
}],
"colors": {
"background": "#4DEB8C",
"bars": "#38AB66",
"heading": "#236B40",
"useDarkColor": true,
"badges": {
"background": "#236B40",
"useDarkColor": false
}
}
}, {
"title": "Languages",
"skillBars": [{
"name": "German (native)",
"icon": "mdi:language",
"pct": 100
}, {
"name": "English (C1)",
"icon": "mdi:language",
"pct": 90
}, {
"name": "Russian (basics)",
"icon": "mdi:language",
"pct": 30
}],
"colors": {
"background": "#EB783F",
"bars": "#AB582E",
"heading": "#6B371D",
"useDarkColor": true,
"badges": {
"background": "#6B371D",
"useDarkColor": false
}
}
}]
}
+27
View File
@@ -0,0 +1,27 @@
[
{
"name": "GitHub",
"url": "https://github.com/C0ntroller",
"icon": "simple-icons:github"
}, {
"name": "LinkedIn",
"url": "https://www.linkedin.com/in/c0ntroller/",
"icon": "simple-icons:linkedin"
}, {
"name": "Instagram",
"url": "https://www.instagram.com/c0ntroller/",
"icon": "simple-icons:instagram"
}, {
"name": "Steam",
"url": "https://steamcommunity.com/id/c0ntroller/",
"icon": "simple-icons:steam"
}, {
"name": "Discord",
"url": "https://discordapp.com/users/224208617820127233",
"icon": "simple-icons:discord"
}, {
"name": "PGP Key",
"url": "/files/pubkey.pgp",
"icon": "mdi:email-lock"
}
]
+2
View File
@@ -0,0 +1,2 @@
/// <reference path="../.astro/types.d.ts" />
/// <reference types="astro/client" />
+304
View File
@@ -0,0 +1,304 @@
---
import Navbar from "../components/LayoutComponents/Navbar.astro";
import Themes from "astro-themes";
import Icon from "astro-icon";
import socials from "../data/socials.json";
interface Props {
title: string;
showAfterMain?: boolean;
}
const { title, showAfterMain } = Astro.props;
---
<!doctype html>
<html lang="en">
<head>
<Themes defaultTheme="dark" />
<meta charset="utf-8" />
<meta
name="description"
content="This is the homepage of C0ntroller."
/>
<meta
name="keyword"
content="private, homepage, software, portfolio, development, cli, hacker, terminal, javascript, js, typescript, ts, nextjs, react, responsive"
/>
<meta name="author" content="C0ntroller" />
<meta name="copyright" content="C0ntroller" />
<meta name="robots" content="index,nofollow" />
<link
rel="apple-touch-icon"
sizes="57x57"
href="/apple-icon-57x57.png"
/>
<link
rel="apple-touch-icon"
sizes="60x60"
href="/apple-icon-60x60.png"
/>
<link
rel="apple-touch-icon"
sizes="72x72"
href="/apple-icon-72x72.png"
/>
<link
rel="apple-touch-icon"
sizes="76x76"
href="/apple-icon-76x76.png"
/>
<link
rel="apple-touch-icon"
sizes="114x114"
href="/apple-icon-114x114.png"
/>
<link
rel="apple-touch-icon"
sizes="120x120"
href="/apple-icon-120x120.png"
/>
<link
rel="apple-touch-icon"
sizes="144x144"
href="/apple-icon-144x144.png"
/>
<link
rel="apple-touch-icon"
sizes="152x152"
href="/apple-icon-152x152.png"
/>
<link
rel="apple-touch-icon"
sizes="180x180"
href="/apple-icon-180x180.png"
/>
<link
rel="icon"
type="image/png"
sizes="192x192"
href="/android-chrome-192x192.png"
/>
<link
rel="icon"
type="image/png"
sizes="512x512"
href="/android-chrome-512x512.png"
/>
<link
rel="icon"
type="image/png"
sizes="32x32"
href="/favicon-32x32.png"
/>
<link
rel="icon"
type="image/png"
sizes="96x96"
href="/favicon-96x96.png"
/>
<link
rel="icon"
type="image/png"
sizes="16x16"
href="/favicon-16x16.png"
/>
<link rel="manifest" href="/manifest.json" />
<meta name="msapplication-TileColor" content="#444444" />
<meta name="msapplication-TileImage" content="/mstile-310x310.png" />
<meta name="theme-color" content="#444444" />
<meta name="viewport" content="width=device-width" />
<meta name="generator" content={Astro.generator} />
<title>{title}</title>
</head>
<body>
<span id="top" aria-hidden></span>
<header>
<Navbar />
</header>
<main>
<slot />
</main>
{showAfterMain ? <div class="after-main">
<slot name="after-main" />
</div> : null
}
<footer id="bottom">
<span style="visibility:hidden">▲</span>
<span class="spacer"></span>
<span class="footerContent">
<span><a class="nocolor" href="/copyright">Copyright</a></span>
<span class="divider">|</span>
{socials.flatMap((social, i) => (
i !== 0 ?
[<span class="divider">|</span>, <a href={social.url} target="_blank" rel="noreferrer" class="socialIcon"><Icon name={social.icon} title={social.name} /></a>] :
[<a href={social.url} target="_blank" rel="noreferrer" class="socialIcon"><Icon name={social.icon} title={social.name} /></a>]
))}
<span class="divider">|</span>
<a class="nocolor" target="_blank" href="mailto:admin-website@c0ntroller.de" rel="noreferrer">Contact</a>
</span>
<span class="spacer"></span>
<a class="nostyle" href="#top" title="Back to top">▲</a>
</footer>
</body>
</html>
<style is:global lang="scss">
* {
box-sizing: border-box !important;
}
:root {
--repl_color: #188a18;
--repl_color-link: rgb(31, 179, 31);
--repl_color-hint: rgba(24, 138, 24, 0.3);
--blog_nav-background: rgba(128, 128, 128, 0.3);
--blog_nav-border: #ccc;
/* https://doodad.dev/pattern-generator?share=stripes-8-247_250_252_1-229_62_62_1-0_0_0_1-57-45-3-8-0-0-0-0-0-0-0 */
--blog_back-background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='100%25' width='100%25'%3E%3Cdefs%3E%3Cpattern id='doodad' width='57' height='57' viewBox='0 0 40 40' patternUnits='userSpaceOnUse' patternTransform='rotate(45)'%3E%3Crect width='100%25' height='100%25' fill='rgba(32, 19, 19,1)'/%3E%3Ccircle cx='0' cy='20' r='1.5' fill='rgba(247, 250, 252,1)'/%3E%3Ccircle cx='40' cy='20' r='1.5' fill='rgba(247, 250, 252,1)'/%3E%3Cpath d='m 16 19.5 h8 v1 h-8z' fill='rgba(229, 62, 62,1)'/%3E%3C/pattern%3E%3C/defs%3E%3Crect fill='url(%23doodad)' height='200%25' width='200%25'/%3E%3C/svg%3E ");
--blog_background-main: rgba(32, 19, 19, 1);
--blog_content-background: rgba(40, 40, 40, 0.2);
--blog_content-border: rgba(
221,
221,
221,
0.25
); /* #ddd but less opacity */
--blog_content-blur: 10px;
--blog_color: #ddd;
--blog_light-el-display: none;
--blog_dark-el-display: initial;
--blog_color-accent: rgba(229, 62, 62, 1);
--blog_color-accent-dark: rgb(190, 54, 54);
}
:root[data-theme="light"] {
--blog_nav-background: rgba(192, 192, 192, 0.3);
--blog_nav-border: #ccc;
--blog_back-background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='100%25' width='100%25'%3E%3Cdefs%3E%3Cpattern id='doodad' width='57' height='57' viewBox='0 0 40 40' patternUnits='userSpaceOnUse' patternTransform='rotate(45)'%3E%3Crect width='100%25' height='100%25' fill='rgba(245, 179, 179,1)'/%3E%3Ccircle cx='0' cy='20' r='1.5' fill='rgba(247, 250, 252,1)'/%3E%3Ccircle cx='40' cy='20' r='1.5' fill='rgba(247, 250, 252,1)'/%3E%3Cpath d='m 16 19.5 h8 v1 h-8z' fill='rgba(229, 62, 62,1)'/%3E%3C/pattern%3E%3C/defs%3E%3Crect fill='url(%23doodad)' height='200%25' width='200%25'/%3E%3C/svg%3E ");
--blog_background-main: rgba(245, 179, 179, 1);
--blog_content-background: rgba(160, 160, 160, 0.15);
--blog_content-border: rgb(
34,
34,
34,
0.17
); /* #222 but less opacity */
--blog_content-blur: 5px;
--blog_color: #222;
--blog_light-el-display: initial;
--blog_dark-el-display: none;
}
body {
margin: 0;
padding: 0;
background: var(--blog_back-background);
color: var(--blog_color);
padding-bottom: 20px;
min-height: 100vh;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
a.nostyle {
text-decoration: inherit;
}
a.nocolor,
a.nostyle {
color: inherit;
}
header {
position: sticky;
top: 10px;
z-index: 99;
}
main,
.after-main,
footer {
max-width: 950px;
border: 1px solid var(--blog_content-border);
background: var(--blog_content-background);
backdrop-filter: blur(var(--blog_content-blur));
}
main {
margin: 40px auto 0;
padding: 50px;
border-top-left-radius: 1em;
border-top-right-radius: 1em;
h1 {
margin-top: 0;
}
@media screen and (max-width: 890px) {
& {
padding: 20px;
}
}
}
.after-main {
margin: 5px auto 0;
padding: 0px 50px;
}
footer {
margin: 5px auto 0;
padding: 20px;
border-bottom-left-radius: 1em;
border-bottom-right-radius: 1em;
display: flex;
flex-direction: row;
flex-wrap: nowrap;
align-items: center;
font-size: 1.1em;
.spacer {
flex-grow: 1;
}
.footerContent {
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: center;
justify-content: center;
margin: 0 10px;
.divider {
margin: 0 10px;
}
.socialIcon {
color: inherit;
text-decoration: none;
height: 1.1em;
width: 1.1em;
}
}
}
h1 {
color: var(--blog_color-accent);
}
h2,
h3,
h4,
h5,
h6 {
color: var(--blog_color-accent-dark);
}
</style>
+149
View File
@@ -0,0 +1,149 @@
---
import Layout from "./Layout.astro";
interface Props {
title: string;
}
const { title } = Astro.props;
---
<Layout title={title} showAfterMain={Astro.slots.has("footer-nav")}>
{Astro.slots.has("main-nav") ?
<slot name="main-nav" /> :
null}
<slot />
{Astro.slots.has("footer-nav") ?
<slot name="footer-nav" slot="after-main" /> :
null}
</Layout>
<style lang="scss" is:global>
main {
/*h1 {
color: var(--blog_color-accent);
font-size: 2em;
}
h2 {
font-size: 1.5em;
}
h3 {
font-size: 1.2em;
}
h4 {
font-size: 1.1em;
}
h2,
h3 {
font-weight: bold;
text-decoration: underline;
}
h2,
h3,
h4,
h5,
h6 {
color: var(--blog_color-accent-dark);
}*/
h1 + p:first-of-type {
font-style: italic;
font-size: 120%;
}
tbody > tr:nth-of-type(odd) {
background-color: var(--blog_background-main);
}
tbody > tr:hover {
background-color: rgba(0, 0, 0, 0.2);
}
pre {
background-color: #282c34;
border: 1px solid var(--blog_content-border);
padding: 1em;
color: #abb2bf;
clear: right;
}
:not(pre) > code,
kbd {
background-color: var(--blog_background-main);
color: inherit;
[data-theme="light"] & {
background-color: #d49a9a;
}
}
kbd {
border-radius: 3px;
border: 1px solid #b4b4b4;
box-shadow:
0 1px 1px rgba(0, 0, 0, 0.2),
0 2px 0 0 rgba(255, 255, 255, 0.7) inset;
display: inline-block;
font-size: 0.85em;
font-weight: 700;
line-height: 1;
padding: 2px 4px;
white-space: nowrap;
}
a:link,
a:visited,
a:active {
color: var(--blog_color-accent);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
img {
width: 80%;
height: auto;
}
/* A custom indicator that this code is in fact faulty */
.notCompiling code {
display: block;
position: relative;
/*
.content {
position: absolute;
}*/
&::before {
content: "!";
color: white;
background-color: #a30e0e;
border-radius: 50%;
position: absolute;
top: 1em;
right: 1em;
display: inline-block;
width: 1.3em;
height: 1.3em;
text-align: center;
font-weight: bolder;
padding: 1px 1px 1px 1px;
font-family: sans-serif;
font-size: 1rem;
}
&:hover::after {
content: "Code is faulty!";
font-weight: bold;
color: #a30e0e;
position: absolute;
right: 1em;
bottom: 1em;
}
}
}
</style>
+241
View File
@@ -0,0 +1,241 @@
---
import Layout from "../layouts/Layout.astro";
---
<Layout title="Not found">
<div id="wrapper">
<div id="box">
<svg viewBox="30 -20 450 280" x="0" y="0">
<!-- Box -->
<polygon
points="100,70 170,0 370,50 370,180"
style="fill:#b58747;"></polygon>
<defs>
<linearGradient
id="shadow_grad1"
x1="50%"
y1="0%"
x2="0%"
y2="50%"
>
<stop
offset="0%"
style="stop-color:#876029;stop-opacity:1"></stop>
<stop
offset="100%"
style="stop-color:#000000;stop-opacity:1"></stop>
</linearGradient>
</defs>
<defs>
<linearGradient
id="shadow_grad2"
x1="0%"
y1="0%"
x2="50%"
y2="100%"
>
<stop
offset="0%"
style="stop-color:#876029;stop-opacity:1"></stop>
<stop
offset="100%"
style="stop-color:#000000;stop-opacity:1"></stop>
</linearGradient>
</defs>
<polygon
points="100,70 170,0 330,100 300,120"
style="fill:#876029;fill:url(#shadow_grad1)"></polygon>
<polygon
points="100,70 170,0 170,130 100,200, 100,70"
style="fill:#876029;fill:url(#shadow_grad2)"></polygon>
<line
x1="170"
y1="0"
x2="370"
y2="50"
style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;"
></line>
<line
x1="170"
y1="0"
x2="170"
y2="130"
style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;"
></line>
<!-- Katzenschweif -->
<path
id="schweif"
d="M 280,120 C 250 100, 310 70, 320 20"
style="fill:transparent;stroke:black;stroke-width:10;stroke-linecap:round"
></path>
<!-- Box-linien -->
<polygon
points="100,70 300,120 370,50 370,180 300,250 100,200"
style="fill:#d19b4f;"></polygon>
<g style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;">
<line x1="100" y1="70" x2="100" y2="200"></line>
<line x1="100" y1="200" x2="300" y2="250"></line>
<line x1="300" y1="250" x2="300" y2="120"></line>
<line x1="100" y1="70" x2="300" y2="120"></line>
<line x1="300" y1="120" x2="370" y2="50"></line>
<line x1="300" y1="250" x2="370" y2="180"></line>
<line x1="370" y1="50" x2="370" y2="180"></line>
</g>
<!-- Lappen-rechts -->
<polygon
points="300,120 350,150 420,80 370,50"
style="fill:#b58747;"></polygon>
<g style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;">
<line x1="300" y1="120" x2="370" y2="50"></line>
<line x1="300" y1="120" x2="350" y2="150"></line>
<line x1="350" y1="150" x2="420" y2="80"></line>
<line x1="370" y1="50" x2="420" y2="80"></line>
</g>
<!-- Lappen-links -->
<polygon
points="100,70 50,100 120,30 170,0"
style="fill:#b58747;"></polygon>
<g style="stroke:#694f2c;stroke-width:5;stroke-linecap:round;">
<line x1="100" y1="70" x2="170" y2="0"></line>
<line x1="100" y1="70" x2="50" y2="100"></line>
<line x1="50" y1="100" x2="120" y2="30"></line>
<line x1="170" y1="0" x2="120" y2="30"></line>
</g>
<!-- Text -->
<text
x="120"
y="120"
style="font-size:4em;font-weight:bold;fill:#000000;transform:rotateX(40deg) rotateY(21deg);"
>404</text
>
<!-- Killeraugen -->
<ellipse
cx="275"
cy="150"
rx="32"
ry="20"
style="fill:#291e0f;transform:rotateZ(12deg)"></ellipse>
<ellipse
cx="266"
cy="153"
rx="7"
ry="5"
style="fill:#4a6b2a;transform:rotateZ(12deg)"></ellipse>
<ellipse
cx="266"
cy="153"
rx="2"
ry="5"
style="fill:#000000;transform:rotateZ(12deg)"></ellipse>
<ellipse
cx="285"
cy="153"
rx="7"
ry="5"
style="fill:#4a6b2a;transform:rotateZ(12deg)"></ellipse>
<ellipse
cx="285"
cy="153"
rx="2"
ry="5"
style="fill:#000000;transform:rotateZ(12deg)"></ellipse>
<rect
id="blinzeln"
width="40"
height="22"
x="255"
y="139"
style="fill:#291e0f;transform:rotateZ(12deg);"></rect>
</svg>
</div>
<div id="errorText">
The site you requested could not be found.<br />
<a href="/">&gt; Back to the main page &lt;</a>
</div>
</div>
</Layout>
<style>
/*.container {
background: #222222;
width: 100vw;
height: 100vh;
}*/
#errorText {
margin-top: 2vh;
color: #fff;
text-align: center;
font-family: Arial, Helvetica, sans-serif;
font-size: 150%;
}
#wrapper a:link,
#wrapper a:visited,
#wrapper a:hover,
#wrapper a:active {
color: #fff;
font-weight: bold;
text-decoration: none;
}
#wrapper {
margin: auto;
position: relative;
}
#box {
max-width: 800px;
margin: auto;
}
@keyframes schweif {
0% {
d: path("M 280,120 C 250 100, 310 70, 320 20");
}
12.5% {
d: path("M 280,120 C 260 100, 280 70, 310 20");
}
25% {
d: path("M 280,120 C 280 100, 260 70, 290 20");
}
37.5% {
d: path("M 280,120 C 280 100, 240 70, 270 20");
}
50% {
d: path("M 280,120 C 280 100, 240 70, 230 20");
}
62.5% {
d: path("M 280,120 C 270 100, 260 70, 250 20");
}
75% {
d: path("M 280,120 C 270 100, 280 70, 270 20");
}
87.5% {
d: path("M 280,120 C 250 100, 310 70, 290 20");
}
100% {
d: path("M 280,120 C 250 100, 310 70, 320 20");
}
}
#schweif {
animation-name: schweif;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
#box svg:hover > #schweif {
animation-duration: 1s;
}
#blinzeln {
fill-opacity: 1;
transition: fill-opacity 0.5s;
}
#box svg:hover > #blinzeln {
fill-opacity: 0;
}
</style>
+36
View File
@@ -0,0 +1,36 @@
---
import MarkdownLayout from "../../layouts/MarkdownLayout.astro";
import { getCollection, getEntry } from "astro:content";
import type { CollectionEntry } from "astro:content";
import DiaryNavBar from "../../components/DiaryNav/DiaryNavBar.astro";
export async function getStaticPaths() {
const collectionData = await getCollection("diaryMainPages");
return collectionData.map((entry) => ({
params: { diary: entry.slug },
}));
}
interface Props {
diary: CollectionEntry<"diaryMainPages">["slug"];
}
const { diary} = Astro.params;
const diaryMain = await getEntry("diaryMainPages", diary);
const collectionBasePath = `/blog/${diary}`;
const diaryPages = (await getCollection(diary)).sort((a, b) => a.data.sorting - b.data.sorting);
const { Content } = await diaryMain.render();
---
<MarkdownLayout title={diaryMain.data.title}>
<Content />
<h2>Pages</h2>
<ol>
{ diaryPages.map((page) => <li><a href={collectionBasePath + "/" + page.slug}>{page.data.title}</a></li>) }
</ol>
<DiaryNavBar collectionName={diary} slot="footer-nav" />
</MarkdownLayout>
+33
View File
@@ -0,0 +1,33 @@
---
import { getCollection } from "astro:content";
import MarkdownLayout from "../../../layouts/MarkdownLayout.astro";
import DiaryNavTop from "../../../components/DiaryNav/DiaryNavTop.astro";
import DiaryNavBar from "../../../components/DiaryNav/DiaryNavBar.astro";
export async function getStaticPaths() {
const pathsAvailable = [];
const availableCollections = await getCollection("diaryMainPages");
for (const collection of availableCollections) {
const collectionData = await getCollection(collection.slug);
for (const entry of collectionData) {
pathsAvailable.push({
params: { diary: collection.slug, entry: entry.slug },
props: { entry },
});
}
}
return pathsAvailable;
}
const { entry } = Astro.props;
const { Content } = await entry.render();
---
<MarkdownLayout title={entry.data.title}>
<DiaryNavTop collectionName="rust" slot="main-nav" />
<Content />
<DiaryNavBar collectionName="rust" slot="footer-nav" />
</MarkdownLayout>
+25
View File
@@ -0,0 +1,25 @@
---
import { getCollection } from "astro:content";
import MarkdownLayout from "../../layouts/MarkdownLayout.astro";
export async function getStaticPaths() {
const pathsAvailable = [];
const collectionData = await getCollection("projects");
for (const entry of collectionData) {
pathsAvailable.push({
params: { entry: entry.slug },
props: { entry },
});
}
return pathsAvailable;
}
const { entry } = Astro.props;
const { Content } = await entry.render();
---
<MarkdownLayout title={entry.data.title}>
<Content />
</MarkdownLayout>
+12
View File
@@ -0,0 +1,12 @@
---
import Layout from "../layouts/Layout.astro";
---
<Layout title="Copyright">
<h1>Copyright</h1>
<p>Unless otherwise stated, all content on this website is licensed under the <a class="nocolor" rel="noreferrer" target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> license.</p>
<p>The logo (the &quot;eye&quot;) and images of my person are not licensed, all rights are reserved.</p>
<p>The <a class="nocolor" rel="noreferrer" target="_blank" href="https://materialdesignicons.com/">Material Design Icons</a> used on this website are licensed under the <a class="nocolor" rel="noreferrer" target="_blank" href="https://www.apache.org/licenses/LICENSE-2.0">Apache License 2.0</a>.</p>
<p>The <a class="nocolor" rel="noreferrer" target="_blank" href="">Simple Icons</a> used on this website are licensed under the <a class="nocolor" rel="noreferrer" target="_blank" href="https://creativecommons.org/publicdomain/zero/1.0/">CC0 1.0 Universal</a> license.</p>
<p>The <a class="nocolor" rel="noreferrer" target="_blank" href="https://sass-lang.com/">SASS Logo</a> used on this website is licensed under the <a class="nocolor" rel="noreferrer" target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/3.0/">CC BY-NC-SA 3.0</a> license.</p>
</Layout>
+47
View File
@@ -0,0 +1,47 @@
---
import ContentCard from "../components/ContentCard.astro";
import Layout from "../layouts/Layout.astro";
import { getCollection } from "astro:content";
const projects = (await getCollection("projects")).sort((a, b) => a.data.published.getTime() - b.data.published.getTime());
const diaries = (await getCollection("diaryMainPages")).sort((a, b) => a.data.lastUpdated.getTime() - b.data.lastUpdated.getTime());;
---
<Layout title="c0ntroller.de">
<h1>Hello there!</h1>
<p class="frontText">
Welcome to my website!<br />
You can find here blog entries about some projects I did and some
diaries where I document progress.<br />
Interested in me? Visit the <a href="/me" class="nocolor"
>About Me page</a
>, and you will find out more about me.<br />
On the right of the navigation, you will find what used to be my
website - a CLI you can play around with.<br /><br />
Have fun!
</p>
<h2>Projects</h2>
<div class="contentList">
{ projects.map(p => <ContentCard title={p.data.title} description={p.data.description} path={`/blog/${p.slug}`} />) }
</div>
<h2>Diaries</h2>
<div class="contentList">
{ diaries.map(p => <ContentCard title={p.data.title} description={p.data.description} path={`/blog/${p.slug}`} />) }
</div>
</Layout>
<style>
.contentList {
display: flex;
align-items: center;
flex-wrap: wrap;
justify-content: space-evenly;
padding: 0;
}
.frontText {
font-size: 1.1em;
line-height: 1.5;
}
</style>
+158
View File
@@ -0,0 +1,158 @@
---
import { Image } from "astro:assets";
import { Icon } from "astro-icon";
import Layout from "../layouts/Layout.astro";
import SkillCard from "../components/SkillCard.astro";
import pic from "../data/me.png";
import socials from "../data/socials.json";
import skills from "../data/skills.json";
import achievements from "../data/achievements.json";
const age = new Date().getFullYear() - 1998 - (new Date().getMonth() <= 10 ? 1 : 0);
---
<Layout title="About me">
<h1>This is me.</h1>
<div class="photo">
<Image src={pic} alt="Me" />
</div>
<div class="personal">
<p class="preText">
My name is <strong>Daniel</strong> and I&apos;m a prospective <strong>automation engineer</strong>, <strong>hardware enthusiast</strong>, and <strong>software developer</strong> from Germany.<br />
I&apos;m {age} years old and studying <strong>Information Systems Engineering</strong> at <strong>TU Dresden</strong>.
</p>
<p>
To be honest, I don&apos;t really know what to write here. What could
you - some visitor of my website - possibly want to know about me?
</p><p>
Maybe you are an employer and want to know what I can do for you? Then
see below - I tried to list all my skills and achievements. If your
company is doing anything related to software development (even
low-level ones like embedded controllers), I&apos;m probably suited for
it.
</p><p>
But maybe you are just another guy on the internet browsing through my
website? Well then have fun! I hope you find what you are looking for.
If you haven&apos;t seen it already, you should check out the <a class="nocolor" href="/terminal">command line</a>
I made. Otherwise, have fun poking around in my <a class="nocolor" href="/">projects</a>.
</p><p>
Do you want to know more about my personal life? Well, I like to play
video games, and watch anime, I love cats and <a
href="https://www.reddit.com/r/blahaj"
target="_blank"
rel="noreferrer"
class="nocolor">sharks</a
>. So just your ordinary nerdy student.<br />
If you want to be even more invested in my personal life, check out my
socials below.
</p><p>
Any questions I did not cover, but you are interested in? Just contact
me <a
class="nocolor"
href="mailto:admin-website@c0ntroller.de"
rel="noreferrer"
target="_blank">via email</a
> or any of the socials below!
</p>
</div>
<h2>Social Media</h2>
<div class="socials">
{
socials
.filter((social) => social.name !== "PGP Key")
.map((social) => (
<a
href={social.url}
target="_blank"
rel="noreferrer"
class="nocolor"
style={{ width: "2em" }}
>
<Icon name={social.icon} />
</a>
))
}
</div>
<h2>Achievements</h2>
{achievements.map((achievement) => <div class="achievement">
<Icon name={achievement.icon} /><span>{achievement.description}</span>
</div>)}
<h2>Skills</h2>
{skills.cards.map((card) => <SkillCard card={card} />)}
<style lang="scss">
.personal {
p {
line-height: 1.5;
}
p:first-of-type {
font-size: 1.2em;
}
}
.achievement {
display: grid;
grid-template-columns: 2em auto;
column-gap: 10px;
padding: 5px;
padding-left: 0;
&:first-child {
height: 2em;
}
}
@keyframes barFill {
0% {
width: 1em;
}
100% {
width: var(--barPct);
}
}
.socials {
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: center;
& > * {
margin-right: 30px;
}
& > *:last-of-type {
margin-right: 0;
}
}
.photo {
float: right;
position: relative;
height: max-content;
width: 100%;
max-width: 250px;
border-radius: 1em;
margin-left: 20px;
margin-bottom: 20px;
& * {
border-radius: 1em;
width: 100%;
height: auto;
}
@media screen and (max-width: 500px) {
& {
float: none;
margin: 0 auto;
max-width: 100%;
border-radius: 1em;
margin-left: 0;
}
}
}
</style>

Some files were not shown because too many files have changed in this diff Show More