25 Commits

Author SHA1 Message Date
c0ntroller bd7588b819 Change directory for deployment
Deploy Astro / Build and Deploy (push) Successful in 1m41s
Signed-off-by: Daniel Kluge <c0ntroller@noreply.git.c0ntroller.de>
2025-01-05 18:56:47 +01:00
c0ntroller 138ad075ea footer-nav ohne transition (fehleranfällig)
Deploy Astro / Build and Deploy (push) Successful in 27m28s
2024-03-03 16:26:46 +01:00
c0ntroller c2d70f0988 Astro audit
Deploy Astro / Build and Deploy (push) Has been cancelled
2024-03-03 16:06:35 +01:00
c0ntroller e339b21f66 Uniform icon size class 2024-03-03 15:58:24 +01:00
c0ntroller c40af33d1d Upgrade astro 2024-03-03 15:49:13 +01:00
c0ntroller dafbda9509 Upgrade astro-icons
Deploy Astro / Build and Deploy (push) Successful in 24m55s
2024-03-03 15:18:06 +01:00
c0ntroller 8a670bd0bb Add icons json
Deploy Astro / Build and Deploy (push) Failing after 23m8s
2024-03-03 12:13:17 +01:00
c0ntroller bd9c74d6f3 More styling
Deploy Astro / Build and Deploy (push) Failing after 24m25s
2024-03-02 21:04:14 +01:00
c0ntroller 5d5af62baf npm audit fix
Deploy Astro / Build and Deploy (push) Failing after 24m25s
2024-03-02 18:20:44 +01:00
c0ntroller d4396a5acc Terminal work
Deploy Astro / Build and Deploy (push) Has been cancelled
2024-03-02 18:13:28 +01:00
c0ntroller 0ebcf1d5a2 Add view transition 2024-03-02 17:52:29 +01:00
c0ntroller 78dc90de5e Terminal UI
Deploy Astro / Build and Deploy (push) Successful in 45s
2024-01-19 14:51:27 +01:00
c0ntroller bde27d0329 Prepare for dev release
Deploy Astro / Build and Deploy (push) Successful in 52s
2024-01-06 14:01:21 +01:00
c0ntroller 4e1c63ade5 Add first Terminal draft
Deploy Astro / Build and Deploy (push) Successful in 57s
2024-01-06 13:59:05 +01:00
c0ntroller 848ef71977 npm audit fix
Deploy Astro / Build and Deploy (push) Successful in 1m30s
2023-12-17 11:17:28 +01:00
c0ntroller 2c88ae7815 Add links to content pages
Deploy Astro / Build and Deploy (push) Failing after 44s
2023-12-17 11:15:40 +01:00
c0ntroller 38492baf96 Add document footer 2023-12-17 10:57:01 +01:00
c0ntroller c703096fca Fix styling 2023-12-17 10:55:43 +01:00
c0ntroller 54b4311b4d Making multiple theme switches possible 2023-12-17 00:28:24 +01:00
c0ntroller a7122a1e34 Add functionality to nav select 2023-12-17 00:23:57 +01:00
c0ntroller 6ebad3b068 Delete old files 2023-12-16 22:54:19 +01:00
c0ntroller e8dba73ea9 Markdown fertig 2023-12-16 22:53:49 +01:00
c0ntroller 592c83cfe2 Add gitea action
Deploy Astro / Build and Deploy (push) Failing after 51s
2023-12-16 12:41:17 +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
119 changed files with 12329 additions and 12309 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"
}
}
+31
View File
@@ -0,0 +1,31 @@
name: Deploy Astro
on:
push:
branches:
- dev
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: 21
- 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: /srv/website/dev
overwrite: true
strip_components: 1
+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).
+23
View File
@@ -0,0 +1,23 @@
import { defineConfig } from "astro/config";
import mdx from "@astrojs/mdx";
import a11yEmoji from "@fec/remark-a11y-emoji";
import wasmPack from 'vite-plugin-wasm-pack';
import icon from "astro-icon";
// https://astro.build/config
export default defineConfig({
prefetch: {
prefetchAll: true
},
integrations: [mdx(), icon()],
markdown: {
remarkPlugins: [a11yEmoji],
shikiConfig: {
theme: "one-dark-pro"
}
},
// Copy wasm-terminal to the build directory
vite: {
plugins: [wasmPack([], ['@c0ntroller/wasm-terminal'])]
}
});
-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;
},
};
+7760 -7682
View File
File diff suppressed because it is too large Load Diff
+21 -31
View File
@@ -1,39 +1,29 @@
{
"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.5.6",
"@astrojs/mdx": "^2.1.1",
"@c0ntroller/wasm-terminal": ">=0.1.0",
"astro": "^4.4.9",
"astro-icon": "^1.1.0",
"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",
"@iconify-json/mdi": "^1.1.64",
"@iconify-json/simple-icons": "^1.1.93",
"astro-themes": "^0.2.4",
"remark-code-extra": "^1.0.1",
"vite-plugin-wasm-pack": "0.1.11"
}
}
-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

+40
View File
@@ -0,0 +1,40 @@
---
interface Props {
title: string;
description: string;
published?: Date;
path: string;
slug: string;
}
const { title, description, /*published, */path, slug } = Astro.props;
---
<a href={path} class="nostyle">
<div class="card" transition:name={`markdown-border-${slug}`}>
<h3 transition:name={`markdown-title-${slug}`}>{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>
+105
View File
@@ -0,0 +1,105 @@
---
import { getCollection, getEntry, 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: 890px) {
& {
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>
+158
View File
@@ -0,0 +1,158 @@
---
import { getCollection, getEntry, 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>
<script>
const selectElements = document.querySelectorAll(".selectField");
selectElements.forEach((el) => {
el.addEventListener("change", (event) => {
window.location.pathname = (event.target as HTMLSelectElement)?.value;
});
});
</script>
<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: 890px) {
& {
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);
color: var(--blog_color);
}
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;
text-align: right;
}
.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/components";
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" loading="eager" />
</a>
<div class="navLink">
<a href="/" class="nostyle">
<span class="linkText">Projects</span>
<span class="linkIcon"
><Icon
name="mdi:home"
title="Home and Projects"
id="mdi_nav_home"
class="icon-2em"
/></span
>
</a>
</div>
<div class="navLink">
<a href="/me" class="nostyle">
<span class="linkText">About Me</span>
<span class="linkIcon"
><Icon
name="mdi:account"
class="icon-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"
class="icon-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,127 @@
---
import { Icon } from "astro-icon/components";
---
<div class="switch" transition:persist="theme-switch">
<Icon name="mdi:language-javascript" title="Theme switching needs JS to be enabled." data-theme-ph class="icon-15em" />
<Icon name="mdi:white-balance-sunny" title="Switch to dark theme" data-theme-sun class="icon-15em" />
<Icon name="mdi:weather-night" title="Switch to light theme" data-theme-moon class="icon-15em" />
</div>
<script>
// Get and delete placeholder (JS is enabled)
const placeHolder = document.querySelectorAll("[data-theme-ph]");
placeHolder.forEach(e => e.remove());
const moons = document.querySelectorAll("[data-theme-moon]");
const suns = document.querySelectorAll("[data-theme-sun]");
const current = document.documentElement.attributes.getNamedItem('data-theme')?.value ?? "dark";
if (current === "dark") {
moons.forEach(m => m.classList.add("selected"));
} else {
suns.forEach(s => s.classList.add("selected"));
}
const switchThemeDark = () => {
document.dispatchEvent(new CustomEvent('set-theme', { detail: 'dark' }));
moons.forEach(m => m.classList.remove("fadeOut", "fadeOutDone"));
moons.forEach(m => m.classList.add("fadeIn"));
setTimeout(() => moons.forEach(m => {
m.classList.add("fadeInDone");
m.classList.remove("fadeIn");
}), 250); // After 0.2s animation is completed
suns.forEach(s => s.classList.remove("fadeIn", "fadeInDone"));
suns.forEach(s => s.classList.add("fadeOut"));
setTimeout(() => suns.forEach(s => {
s.classList.add("fadeOutDone");
s.classList.remove("fadeOut");
}), 250); // After 0.2s animation is completed
}
const switchThemeLight = () => {
document.dispatchEvent(new CustomEvent('set-theme', { detail: 'light' }));
moons.forEach(m => m.classList.remove("fadeIn", "fadeInDone"));
moons.forEach(m => m.classList.add("fadeOut"));
setTimeout(() => moons.forEach(m => {
m.classList.add("fadeOutDone");
m.classList.remove("fadeOut");
}), 250); // After 0.2s animation is completed
suns.forEach(s => s.classList.remove("fadeOut", "fadeOutDone"));
suns.forEach(s => s.classList.add("fadeIn"));
setTimeout(() => suns.forEach(s => {
s.classList.add("fadeInDone");
s.classList.remove("fadeIn");
}), 250); // After 0.2s animation is completed
}
moons.forEach(m => m.addEventListener("click", switchThemeLight));
suns.forEach(s => s.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;
}
.fadeOutDone {
opacity: 0;
transform: translate(0, -100%);
}
.fadeIn {
animation: fadeIn 0.2s ease-in-out;
animation-fill-mode: forwards;
}
.fadeInDone {
opacity: 1;
transform: translate(0, 0);
}
.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

+218
View File
@@ -0,0 +1,218 @@
---
import { Icon } from "astro-icon/components";
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} class="icon-2em" />
</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} class="icon-1em" />
</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 {
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>
+51
View File
@@ -0,0 +1,51 @@
import { z, defineCollection } from 'astro:content';
// Schema for projects
const projectsCol = defineCollection({
type: "content",
schema: z.object({
title: z.string(),
site_title: z.string().optional(),
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(),
site_title: z.string().optional(),
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(),
site_title: z.string().optional(),
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,
};
+9
View File
@@ -0,0 +1,9 @@
---
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)."
relatedWebsite: https://doc.rust-lang.org/book/
---
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

+102
View File
@@ -0,0 +1,102 @@
---
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";
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/).
+77
View File
@@ -0,0 +1,77 @@
---
title: Overleaf Sync with Git
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
---
## 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
+40
View File
@@ -0,0 +1,40 @@
---
title: Google 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
---
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/infoscreen) and the [Simple Callback Server](/blog/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.
+29
View File
@@ -0,0 +1,29 @@
---
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
---
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.
+89
View File
@@ -0,0 +1,89 @@
---
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
---
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>
+27
View File
@@ -0,0 +1,27 @@
---
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
---
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/)
+48
View File
@@ -0,0 +1,48 @@
---
title: Hello world!
published: 2022-08-10T17:04:53+02:00
sorting: 0
slug: 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
+72
View File
@@ -0,0 +1,72 @@
---
title: Cargo
published: 2022-10-18T17:56:26+02:00
sorting: 1
slug: 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,252 @@
---
title: Erstes Spiel
published: 2022-10-18T17:56:26+02:00
sorting: 2
slug: higher-lower-game
---
[Link zum Buch](https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html)
## Projekt erstellen
Das Projekt wird wie in den vorherigen Einträgen beschrieben erstellt.
## Einen Input aufnehmen
```rust
use std::io;
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("Failed to read line");
println!("You guessed: {}", guess);
```
Ausgabe:
> 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:
```toml
[dependencies]
rand = "0.3.14"
```
Dependencies findet man auch auf [crates.io](https://crates.io).
Die crate `rand` kann jetzt im Code verwendet werden.
```rust
extern crate rand;
use rand::Rng;
let secret_number: u32 = rand::thread_rng().gen_range(1, 101);
println!("{}", secret_number);
```
Und schwubbs wird eine zufälle Zahl ausgegeben.
## Höher oder tiefer?
Vergleichen wir doch einfach mal…
Aber was ist das? Ein Fehler??
<div class="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!"),
}
```
</div>
Der Compiler sagt uns dann Folgendes:
```rust
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:
```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!
```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!"),
}
```
> Too big!
Wuuh!
## Nicht nur ein Versuch
Damit wir mehrmals raten können, brauchen wir eine Schleife.
```rust
let secret_number: u32 = rand::thread_rng().gen_range(1, 101);
loop {
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("Failed to read line");
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!"),
}
}
```
> 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 noch abbrechen.
```rust
let secret_number: u32 = rand::thread_rng().gen_range(1, 101);
loop {
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("Failed to read line");
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;
},
}
}
```
> 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:
```rust
loop {
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("Failed to read line");
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;
}
```
> 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".
+283
View File
@@ -0,0 +1,283 @@
---
title: Konzepte
published: 2022-10-18T17:56:26+02:00
sorting: 3
slug: konzepte
---
[Link zum Buch](https://doc.rust-lang.org/book/ch03-00-common-programming-concepts.html)
## 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:
<div class="notCompiling">
```rust
fn main() {
let x = "Hello world!";
// Das folgende funktioniert nicht, weil x nicht mutable ist!
x = "Hello Rust!";
}
```
</div>
Damit Variablen mutable sind, muss `mut` genutzt werden:
```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:
```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:
```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:
```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
```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:
```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:
```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:
```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:
```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:
```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).
```rust
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("{}", element);
}
}
```
+151
View File
@@ -0,0 +1,151 @@
---
title: Ownership
published: 2022-10-18T17:56:26+02:00
sorting: 4
slug: ownership
---
[Link zum Buch](https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html)
## 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:
```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
```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
<div class="notCompiling">
```rust
fn dangle() -> &String {
let s = String::from("hello");
&s // Referenz auf s returned
} // Hier fliegt s aus dem Scope
```
</div>
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.
```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).
+208
View File
@@ -0,0 +1,208 @@
---
title: Structs
published: 2022-08-10T17:04:53+02:00
sorting: 5
slug: structs
---
[Link zum Buch](https://doc.rust-lang.org/book/ch05-00-structs.html)
## 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
```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:
```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
```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
```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 OOP-ig.
Die folgenden Beispiele sollten relativ viel erklären:
```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!
<div class="notCompiling">
```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!
}
```
</div>
+150
View File
@@ -0,0 +1,150 @@
---
title: Enums & Matching
site_title: Enums und Pattern Matching
published: 2022-10-18T17:56:26+02:00
sorting: 6
slug: enums
---
[Link zum Buch](https://doc.rust-lang.org/book/ch06-00-enums.html)
## 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.
```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:
```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.
```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 [hier zu finden](https://doc.rust-lang.org/std/option/enum.Option.html) 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.
```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:
```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?!
}
```
+167
View File
@@ -0,0 +1,167 @@
---
title: Projektmanagement
published: 2022-10-18T17:56:26+02:00
sorting: 7
slug: projektmanagement
---
[Link zum Buch](https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html)
## 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 [Higher-Lower-Spiel](/blog/rust/higher-lower-game) 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:
<div class="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();
}
```
</div>
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:
```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:
```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.
+236
View File
@@ -0,0 +1,236 @@
---
title: Collections
published: 2022-10-18T17:56:27+02:00
sorting: 8
slug: collections
---
[Link zum Buch](https://doc.rust-lang.org/book/ch08-00-common-collections.html)
## `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:
```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 [Dokumentation zum Vector](https://doc.rust-lang.org/std/vec/struct.Vec.html) ist da wahrscheinlich sehr hilfreich.
## Strings
Strings eine Collection?
Klar, wie in C oder Python 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
> To summarize, strings are complicated.
Hier wieder eine Übersicht zur Nutzung:
```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.
```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:
```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
```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]);
}
```
+103
View File
@@ -0,0 +1,103 @@
---
title: Fehler und PANIK!
published: 2022-08-22T17:04:01+02:00
sorting: 9
slug: errors-and-panic
---
[Link zum Buch](https://doc.rust-lang.org/book/ch09-00-error-handling.html)
## `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:
```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`:
```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:
```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" />
+323
View File
@@ -0,0 +1,323 @@
---
import { ViewTransitions } from 'astro:transitions';
import Themes from "astro-themes";
import { Icon } from "astro-icon/components";
import Navbar from "../components/LayoutComponents/Navbar.astro";
import socials from "../data/socials.json";
interface Props {
title: string;
showAfterMain?: boolean;
mainTransitionName?: string;
}
const { title, showAfterMain, mainTransitionName } = Astro.props;
---
<!doctype html>
<html lang="en">
<head>
<Themes defaultTheme="dark" />
<ViewTransitions />
<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="true"></span>
<header transition:persist="nav">
<Navbar />
</header>
<main transition:name={ mainTransitionName || "main" }>
<slot />
</main>
{showAfterMain ? <div class="after-main">
<slot name="after-main" />
</div> : null
}
<footer id="bottom" transition:persist="footer">
<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} class="socialIcon" /></a>] :
[<a href={social.url} target="_blank" rel="noreferrer" class="socialIcon"><Icon name={social.icon} title={social.name} class="socialIcon" /></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);
}
.icon-1em {
height: 1em;
width: 1em;
}
.icon-15em {
height: 1.5em;
width: 1.5em;
}
.icon-2em {
height: 2em;
width: 2em;
}
</style>
+187
View File
@@ -0,0 +1,187 @@
---
import Layout from "./Layout.astro";
import { Icon } from "astro-icon/components";
interface Props {
title: string;
slug: string;
published?: Date;
srcPath?: string;
moreLinks?: {
icon: string;
href: string;
}[];
}
const { title, srcPath, published, moreLinks, slug } = Astro.props;
const gitUrl = `https://git.c0ntroller.de/c0ntroller/frontpage/src/branch/dev/src/content/${srcPath}`
---
<Layout title={title} showAfterMain={Astro.slots.has("footer-nav")} mainTransitionName={`markdown-border-${slug}`}>
{Astro.slots.has("main-nav") ?
<slot name="main-nav" /> :
null}
{ moreLinks && moreLinks.length !== 0 ?
<div class="more">
{ moreLinks.map(l => <a href={l.href} referrerpolicy="no-referrer" class="nostyle"><Icon name={l.icon} class="icon-2em" /></a>) }
</div>
: null}
<h1 transition:name={`markdown-title-${slug}`}>{title}</h1>
<slot />
{ published || srcPath ? <>
<hr />
<div class="contentFooter">
{ published ? <>Published on: <time datetime={published.toISOString()}>{published.toLocaleDateString("en-GB", {day: "2-digit", month: "long", year: "numeric", hour: "2-digit", minute: "2-digit", timeZone: "Europe/Berlin", hour12: false})}</time></> : null }
{ published && srcPath ? <> | </> : null}
{ srcPath ? <a href={gitUrl}>Document source</a> : null }
</div>
</>: null }
{Astro.slots.has("footer-nav") ?
<slot name="footer-nav" slot="after-main" /> :
null}
</Layout>
<style lang="scss" is:global>
main {
.contentFooter {
background-color: var(--blog_background-main);
clear: right;
border-radius: 1em;
margin-top: 10px;
padding: 14px 16px;
margin-bottom: -40px;
@media screen and (max-width: 890px) {
& {
margin-bottom: -10px;
}
}
}
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;
}
blockquote {
background: rgba(0, 0, 0, 0.2);
border-left: 3px solid var(--blog_content-border);
padding: .7em 1em;
margin-left: 1em;
p {
margin: 0;
}
}
/* 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;
}
}
}
.more {
float: right;
@media screen and (max-width: 890px) {
& {
float: none;
display: block;
width: max-content;
margin-left: auto;
margin-right: auto;
}
}
}
</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>
+50
View File
@@ -0,0 +1,50 @@
---
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();
const moreLinks = [];
if (diaryMain.data.relatedWebsite) {
moreLinks.push({
href: diaryMain.data.relatedWebsite,
icon: "mdi:web",
});
}
if (diaryMain.data.repository) {
moreLinks.push({
href: diaryMain.data.repository,
icon: "bi:git",
});
}
---
<MarkdownLayout title={diaryMain.data.site_title || diaryMain.data.title} slug={diaryMain.slug} srcPath={`diaryMainPages/${diaryMain.id}`} moreLinks={moreLinks}>
<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>
+34
View File
@@ -0,0 +1,34 @@
---
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 { diary } = Astro.params
const { entry } = Astro.props;
const { Content } = await entry.render();
---
<MarkdownLayout title={entry.data.site_title || entry.data.title} slug={entry.slug} srcPath={`${diary}/${entry.id}`} published={entry.data.published}>
<DiaryNavTop collectionName="rust" slot="main-nav" />
<Content />
<DiaryNavBar collectionName="rust" slot="footer-nav" />
</MarkdownLayout>
+40
View File
@@ -0,0 +1,40 @@
---
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();
const moreLinks = [];
if (entry.data.relatedWebsite) {
moreLinks.push({
href: entry.data.relatedWebsite,
icon: "mdi:web",
});
}
if (entry.data.repository) {
moreLinks.push({
href: entry.data.repository,
icon: "simple-icons:git",
});
}
---
<MarkdownLayout title={entry.data.site_title || entry.data.title} slug={entry.slug} srcPath={`projects/${entry.id}`} published={entry.data.published} moreLinks={moreLinks}>
<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}`} slug={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}`} slug={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/components";
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" loading="eager" />
</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"
aria-label={`Link to my ${social.name} profile`}
>
<Icon name={social.icon} class="icon-2em" />
</a>
))
}
</div>
<h2>Achievements</h2>
{achievements.map((achievement) => <div class="achievement">
<Icon name={achievement.icon} class="icon-2em" /><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>
+199
View File
@@ -0,0 +1,199 @@
---
import Layout from "../layouts/Layout.astro";
import wasmData from "@c0ntroller/wasm-terminal/package.json";
const date = new Date();
const screenVersion = `${date.getFullYear()}${date.getMonth()+1}${date.getDate()}${date.getHours()}${date.getMinutes()}`;
const wasmVersion = wasmData.version;
---
<Layout title="Terminal" showAfterMain>
<div class="screen" data-terminal-screen>
<div data-terminal-output>
<noscript><pre>You need to enable JavaScript to use this terminal.</pre></noscript>
<pre>cer0 0S V{wasmVersion} - UI V{screenVersion}</pre>
<pre class="logo">@@@@@@@@@@@
@@@@@@@@@@@@
@@@@@@@@@@@@
@@@@@@@@@@@@@
@@@@ @@@@@@@@@@@@
@@@@@ @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@ @@@@@@@@@
@@@@@@@@@@@@@@@W#MW@@@@@@@@@@@@@@@ @@@@@@@@@
@@@@@######## pkaMB@@@@@@@@mb@@@@@ @@@@@@@
@@@@@ pwdhoh@@@@@$OOOOOw ##@@@@ @ @@@@
@@@@@ dOOOOOOOOOO0OOOOOO #@@ @ @@@
@@@@ pOOOOOOOOOOOOOOZ# #@@ @
@@@@ oOOOOOOOOOOOOa #@
@@@@@ odwwpdda
@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@</pre>
</div>
<div class="input"><pre class="user">user@cer0</pre><pre>:</pre><pre class="pwd">/</pre><pre class="dollar">$&nbsp;</pre><input type="text" data-terminal-input /></div>
</div>
<template data-terminal-user-cmd>
<pre><pre class="user">user@cer0</pre><pre>:</pre><pre class="pwd"></pre><pre class="dollar">$&nbsp;</pre><pre class="user-cmd"></pre></pre>
</template>
<div slot="after-main" class="more">
Read more about the development of this terminal&nbsp;<a href="/blog/wasm-terminal" class="nocolor">here</a>.
</div>
</Layout>
<script>
(async () => {
const wasm = import("@c0ntroller/wasm-terminal");
const outputs = document.querySelectorAll("[data-terminal-output]") as NodeListOf<HTMLDivElement>;
const inputs = document.querySelectorAll("[data-terminal-input]") as NodeListOf<HTMLInputElement>;
const screens = document.querySelectorAll("[data-terminal-screen]") as NodeListOf<HTMLDivElement>;
const template = document.querySelector("[data-terminal-user-cmd]") as HTMLTemplateElement;
screens.forEach((s) => s.addEventListener("click", () => inputs[0]?.focus()));
screens.forEach((screen) => {
new MutationObserver((changes) => {
const totalNewHeight = changes.reduce((prev, change) => {
change.addedNodes.forEach(n => prev += (n as HTMLPreElement).clientHeight || 0);
return prev;
}, 0);
if (screen.scrollTop + screen.clientHeight >= screen.scrollHeight - totalNewHeight - 40) {
screen.scrollTo(0, screen.scrollHeight);
}
}).observe(screen, { childList: true, subtree: true });
});
const { default: init, Console } = await wasm;
await init();
const c = Console.new();
function updatePwd() {
document.querySelector(".input .pwd")!.textContent = c.get_pwd();
}
updatePwd();
inputs.forEach((input) => {
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
const prevPwd = c.get_pwd();
const cmd = input.value;
const inputLine = template.content.cloneNode(true) as HTMLPreElement;
inputLine.querySelector(".user-cmd")!.textContent = cmd;
inputLine.querySelector(".pwd")!.textContent = prevPwd;
outputs.forEach((output) => {
output.append(inputLine);
});
input.value = "";
if (cmd) {
const resp = c.execute(cmd);
if (resp) {
const outputLine = document.createElement("pre");
outputLine.textContent = resp
outputs.forEach((output) => {
output.append(outputLine);
});
}
}
updatePwd();
}
});
});
})()
</script>
<style lang="scss">
@font-face {
font-family: "Cascadia Code";
src: url("/fonts/CascadiaCode.woff2") format("woff2");
}
.screen {
width: 100%;
height: 30em;
background: #000;
border-radius: 0.2em;
box-shadow: 0 0 0.5em #000;
color: #fff;
padding: 10px;
display: flex;
flex-direction: column;
overflow-y: auto;
pre > pre {
display: inline-block;
}
.logo {
overflow-wrap: normal !important;
white-space: pre !important;
overflow-x: hidden;
font-size: min(2vw, 1em);
}
[data-terminal-output] {
display: flex;
flex-direction: column;
}
}
:global(pre) {
margin: 0;
padding: 0;
white-space: pre-wrap;
word-wrap: normal;
overflow-wrap: break-word;
font-family: "Cascadia Code", monospace;
&.user {
color: #0f0;
}
&.pwd {
color: #00f;
}
}
.input {
display: flex;
flex-direction: row;
input {
font-family: "Cascadia Code", monospace;
display: inline-block;
width: 100%;
flex-grow: 2;
font-size: 1rem;
padding: 0;
margin: 0;
border: none;
background: transparent;
appearance: none !important;
outline: none;
caret-shape: block;
color: #fff;
&::-moz-focus-outer, &::-moz-focus-inner, &:focus, &:focus *, &:-moz-focusring, &:-moz-focusring * {
border: none !important;
outline: none !important;
box-shadow: none !important;
}
}
}
.more {
display: flex;
justify-content: center;
align-items: center;
font-style: italic;
padding: 5px;
}
</style>
-171
View File
@@ -1,171 +0,0 @@
.personal {
p {
line-height: 1.5;
}
p:first-of-type {
font-size: 1.2em;
}
}
.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;
}
}
.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;
}
@media screen and (max-width: 500px) {
& {
float: none;
margin: 0 auto;
max-width: 100%;
border-radius: 1em;
margin-left: 0;
}
}
}
-79
View File
@@ -1,79 +0,0 @@
#blogBody {
background: var(--blog_back-background);
color: var(--blog_color);
padding-bottom: 20px;
min-height: 100vh;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
header {
position: sticky;
top: 10px;
z-index: 99;
}
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;
}
}
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: 1em;
}
}
}
h1 {
color: var(--blog_color-accent);
}
h2, h3, h4, h5, h6 {
color: var(--blog_color-accent-dark);
}
}

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