8 Commits
105 changed files with 5092 additions and 2006 deletions
+1030 -1175
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -5,6 +5,7 @@
"type": "module",
"scripts": {
"dev": "vite dev",
"dev-host": "vite dev --host",
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
@@ -30,8 +31,8 @@
"@tailwindcss/vite": "^4.1.16",
"@types/node": "^24",
"@vitest/browser": "^3.2.4",
"drizzle-kit": "^0.31.8",
"drizzle-orm": "^0.45.1",
"drizzle-kit": "^0.18.1",
"drizzle-orm": "^0.45.2",
"eslint": "^9.36.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.12.4",
Executable → Regular
View File
Vendored Executable → Regular
View File
Executable → Regular
+12
View File
@@ -1,6 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<script>
// Immediately apply saved or system theme – no flash
(function () {
const saved = localStorage.getItem('theme');
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const theme =
saved === 'dark' || saved === 'light' ? saved : prefersDark ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', theme);
// Optional: prevent transition on load
document.documentElement.style.setProperty('--initial-load', 'true');
})();
</script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
Executable → Regular
View File
Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 668 B

After

Width:  |  Height:  |  Size: 668 B

Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 695 B

After

Width:  |  Height:  |  Size: 695 B

Executable → Regular
View File
Executable → Regular
View File
Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 620 B

After

Width:  |  Height:  |  Size: 620 B

View File

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 506 B

After

Width:  |  Height:  |  Size: 506 B

Executable → Regular
View File
Executable → Regular
View File
+568
View File
@@ -0,0 +1,568 @@
import {
getWrapperManager,
MWIN_MANAGER,
resolveElement,
type MWinAPI,
type MWinNormalizedParams,
type MWinParams,
type MWinState,
type ResizeDirection
} from './mwin_util';
export function mwin_movable(node: HTMLElement, options: MWinParams) {
const controller = new MWinController(node, options);
const api: MWinAPI = {
state: controller.state,
minimize: () => controller.minimize(),
maximize: () => controller.maximize(),
close: () => controller.close()
};
options.onAPI?.(api);
return {
destroy: () => controller.destroy()
};
}
class MWinController {
#rafID: number | null = null;
#pendingApply = false;
#node: HTMLElement;
#wrapper: HTMLElement;
#opts: MWinNormalizedParams;
#savedTransition: string;
#savedStyles: string;
#wrapperObserver: ResizeObserver | null = null;
#wrapperWidth: number = 0;
#wrapperHeight: number = 0;
#wrapperLeft: number = 0;
#wrapperTop: number = 0;
#wrapperBorderLeft: number = 0;
#wrapperBorderTop: number = 0;
#dragOffsetX: number = 0;
#dragOffsetY: number = 0;
#resizeDirection: ResizeDirection = null;
#resizeStartRect = { x: 0, y: 0, width: 0, height: 0 };
#resizeStartPos = { x: 0, y: 0 };
#restoreRect: { x: number; y: number; width: number; height: number } | null = null;
state = $state<MWinState>({
x: 0,
y: 0,
width: 0,
height: 0,
minimized: false,
maximized: false,
moving: false,
resizing: false,
zIndex: 0
});
constructor(node: HTMLElement, options: MWinParams) {
this.#node = node;
const wrapper = resolveElement(options.wrapper, node);
if (!wrapper) throw new Error('[Movable] - Wrapper element not found!');
this.#wrapper = wrapper;
const wrapperStyle = getComputedStyle(this.#wrapper);
this.#wrapperBorderLeft = parseFloat(wrapperStyle.borderLeftWidth);
this.#wrapperBorderTop = parseFloat(wrapperStyle.borderTopWidth);
const resizableOpts = typeof options.resizable === 'object' ? options.resizable : {};
this.#opts = {
handle: resolveElement(options.handle, node),
initX: options.initX,
initY: options.initY,
initWidth: options.initWidth,
initHeight: options.initHeight,
baseZIndex: options.baseZIndex ?? 1,
resizeHandle: resolveElement(options.resizeHandle, node),
resizable: !!options.resizable,
threshold: resizableOpts.threshold ?? 8,
minWidth: resizableOpts.minWidth ?? 24, //MinWidth should be min-content
minHeight: resizableOpts.minHeight ?? 24, //MinHeight should be min-content
maxWidth: resizableOpts.maxWidth ?? Infinity,
maxHeight: resizableOpts.maxHeight ?? Infinity,
onClose: options.onClose,
onMinimize: options.onMinimize,
onMaximize: options.onMaximize
};
this.#savedStyles = this.#node.style.cssText;
this.#savedTransition = this.#node.style.transition;
this.#node.style.transition = 'none';
this.#node.style.willChange = 'transform';
this.#wrapper.style.position = 'relative';
this.#node.style.position = 'absolute';
const wRect = this.#wrapper.getBoundingClientRect();
const nRect = this.#node.getBoundingClientRect();
this.state.x = this.#opts.initX ?? nRect.left - wRect.left;
this.state.y = this.#opts.initY ?? nRect.top - wRect.top;
this.state.width = this.#opts.initWidth ?? nRect.width;
this.state.height = this.#opts.initHeight ?? nRect.height;
this.#node.style.left = '0';
this.#node.style.top = '0';
const mgr = getWrapperManager(this.#wrapper);
mgr.refCount++;
if (!node.hasAttribute('tabindex')) {
node.setAttribute('tabindex', '0');
}
node.setAttribute('role', 'region');
node.setAttribute('aria-label', 'Movable window');
this.#cacheWrapperRect();
node.addEventListener('pointerdown', this.#onPointerDown);
node.addEventListener('pointermove', this.#updateCursor);
node.addEventListener('pointerleave', this.#resetCursor);
this.#clampAndApply();
this.#bringToFront();
this.#wrapperObserver = new ResizeObserver(() => {
this.#wrapperWidth = this.#wrapper.clientWidth;
this.#wrapperHeight = this.#wrapper.clientHeight;
this.#onWrapperResize();
});
this.#wrapperObserver.observe(this.#wrapper);
}
#cacheWrapperRect() {
const wrapperRect = this.#wrapper.getBoundingClientRect();
this.#wrapperLeft = wrapperRect.left + this.#wrapperBorderLeft;
this.#wrapperTop = wrapperRect.top + this.#wrapperBorderTop;
this.#wrapperWidth = this.#wrapper.clientWidth;
this.#wrapperHeight = this.#wrapper.clientHeight;
}
#bringToFront() {
const mgr = getWrapperManager(this.#wrapper);
mgr.zCounter++;
this.state.zIndex = this.#opts.baseZIndex + mgr.zCounter;
this.#node.style.zIndex = String(this.state.zIndex);
}
#clampAndApply() {
this.#clampRect();
this.#apply();
}
#clampRect() {
const bw = this.#wrapperWidth;
const bh = this.#wrapperHeight;
let w = Math.min(this.state.width, bw, this.#opts.maxWidth);
w = Math.max(w, this.#opts.minWidth, 0);
let h = Math.min(this.state.height, bh, this.#opts.maxHeight);
h = Math.max(h, this.#opts.minHeight, 0);
this.state.width = w;
this.state.height = h;
const maxX = Math.max(0, bw - w);
const maxY = Math.max(0, bh - h);
this.state.x = Math.min(Math.max(this.state.x, 0), maxX);
this.state.y = Math.min(Math.max(this.state.y, 0), maxY);
}
#apply() {
this.#node.style.transform = `translate(${this.state.x}px, ${this.state.y}px)`;
this.#node.style.width = this.state.width + 'px';
this.#node.style.height = this.state.height + 'px';
}
#getCornerDirection(e: PointerEvent): ResizeDirection {
if (!this.#opts.resizable) return null;
const t = this.#opts.threshold;
let dirY: string = '';
if (e.clientY - this.state.y < t) dirY = 'n';
else if (this.state.y + this.state.height - e.clientY < t) dirY = 's';
let dirX: string = '';
if (e.clientX - this.state.x < t) dirX = 'w';
else if (this.state.x + this.state.width - e.clientX < t) dirX = 'e';
if (dirY && dirX) {
return (dirY + dirX) as ResizeDirection;
}
return null;
}
#onPointerCancel = () => this.#onPointerUp();
#onPointerDown = (e: PointerEvent): void => {
if (this.#isInteractive(e.target as HTMLElement)) return;
if (this.state.minimized) return;
if (this.state.maximized) {
const target = e.target as HTMLElement;
const canDrag = this.#opts.handle?.contains(target) || !this.#opts.handle;
if (canDrag) this.#unmaximizeAtCursor(e);
return;
}
if (this.#opts.resizeHandle?.contains(e.target as HTMLElement)) {
this.#startResize(e, 'se');
return;
}
const dir = this.#getCornerDirection(e);
if (dir) {
this.#startResize(e, dir);
return;
}
if (this.#opts.handle?.contains(e.target as HTMLElement)) {
this.#startMove(e);
return;
}
if (!this.#opts.handle) {
this.#startMove(e);
}
};
#startMove(e: PointerEvent, skipOffset = false): void {
e.preventDefault();
this.#bringToFront();
this.state.moving = true;
this.#node.style.cursor = 'grabbing';
this.#cacheWrapperRect();
if (!skipOffset) {
const rect = this.#node.getBoundingClientRect();
this.#dragOffsetX = e.clientX - rect.left;
this.#dragOffsetY = e.clientY - rect.top;
}
this.#prepareInteraction();
}
#startResize(e: PointerEvent, direction: ResizeDirection): void {
e.preventDefault();
e.stopPropagation();
this.#bringToFront();
this.state.resizing = true;
this.#cacheWrapperRect();
this.#resizeDirection = direction;
this.#resizeStartRect = {
x: this.state.x,
y: this.state.y,
width: this.state.width,
height: this.state.height
};
this.#resizeStartPos = { x: e.clientX - this.#wrapperLeft, y: e.clientY - this.#wrapperTop };
this.#prepareInteraction();
}
#unmaximizeAtCursor(e: PointerEvent): void {
this.#cacheWrapperRect();
const cursorX = e.clientX - this.#wrapperLeft;
const cursorY = e.clientY - this.#wrapperTop;
const fracX = this.#wrapperWidth > 0 ? cursorX / this.#wrapperWidth : 0;
const fracY = this.#wrapperHeight > 0 ? cursorY / this.#wrapperHeight : 0;
if (this.#restoreRect) {
this.state.width = this.#restoreRect.width;
this.state.height = this.#restoreRect.height;
this.state.maximized = false;
this.#restoreRect = null;
} else {
// fallback: no saved rect, just keep current size
this.state.maximized = false;
}
// Position so the same relative point stays under the cursor
let newX = cursorX - fracX * this.state.width;
let newY = cursorY - fracY * this.state.height;
// Clamp inside the boundary
const maxX = Math.max(0, this.#wrapperWidth - this.state.width);
const maxY = Math.max(0, this.#wrapperHeight - this.state.height);
newX = Math.min(Math.max(newX, 0), maxX);
newY = Math.min(Math.max(newY, 0), maxY);
this.state.x = newX;
this.state.y = newY;
this.#scheduleApply();
this.#dragOffsetX = cursorX - newX;
this.#dragOffsetY = cursorY - newY;
this.#bringToFront();
this.state.moving = true;
this.#node.style.cursor = 'grabbing';
this.#prepareInteraction();
return;
}
#prepareInteraction(): void {
document.body.style.userSelect = 'none';
this.#node.style.transition = 'none';
this.#node.style.willChange = 'transform, width, height';
this.#node.style.touchAction = 'none';
window.addEventListener('pointermove', this.#onPointerMove, { passive: true });
window.addEventListener('pointerup', this.#onPointerUp, { passive: true });
window.addEventListener('pointercancel', this.#onPointerCancel, { passive: true });
}
#onPointerMove = (e: PointerEvent): void => {
this.#cacheWrapperRect();
const events = e.getCoalescedEvents?.() ?? [e];
for (const event of events) {
if (this.state.moving) {
this.#updateMove(event);
} else if (this.state.resizing) {
this.#updateResize(event);
}
}
this.#scheduleApply();
};
#scheduleApply(): void {
if (!this.#pendingApply) {
this.#pendingApply = true;
this.#rafID = requestAnimationFrame(() => {
if (!this.state.moving && !this.state.resizing) {
this.#node.style.willChange = 'auto';
}
this.#rafID = null;
this.#pendingApply = false;
this.#apply();
});
}
}
#updateMove(e: PointerEvent): void {
let newX = e.clientX - this.#wrapperLeft - this.#dragOffsetX;
let newY = e.clientY - this.#wrapperTop - this.#dragOffsetY;
newX = Math.max(0, Math.min(newX, this.#wrapperWidth - this.state.width));
newY = Math.max(0, Math.min(newY, this.#wrapperHeight - this.state.height));
this.state.x = newX;
this.state.y = newY;
}
#updateResize(e: PointerEvent): void {
const dir = this.#resizeDirection!;
const start = this.#resizeStartRect;
const dx = e.clientX - this.#wrapperLeft - this.#resizeStartPos.x;
const dy = e.clientY - this.#wrapperTop - this.#resizeStartPos.y;
const anchorLeft = dir.includes('e') ? start.x : start.x + start.width;
const anchorTop = dir.includes('s') ? start.y : start.y + start.height;
let movingX = anchorLeft;
let movingY = anchorTop;
if (dir.includes('e')) movingX = start.x + start.width + dx;
else movingX = start.x + dx;
if (dir.includes('s')) movingY = start.y + start.height + dy;
else movingY = start.y + dy;
const minWidth = this.#opts.minWidth;
const minHeight = this.#opts.minHeight;
const maxWidth = Math.min(this.#opts.maxWidth, this.#wrapperWidth);
const maxHeight = Math.min(this.#opts.maxHeight, this.#wrapperHeight);
if (dir.includes('e')) {
movingX = Math.max(anchorLeft + minWidth, Math.min(movingX, anchorLeft + maxWidth));
movingX = Math.min(movingX, this.#wrapperWidth);
} else {
movingX = Math.min(anchorLeft - minWidth, Math.max(movingX, anchorLeft - maxWidth));
movingX = Math.max(movingX, 0);
}
if (dir.includes('s')) {
movingY = Math.max(anchorTop + minHeight, Math.min(movingY, anchorTop + maxHeight));
movingY = Math.min(movingY, this.#wrapperHeight);
} else {
movingY = Math.min(anchorTop - minHeight, Math.max(movingY, anchorTop - maxHeight));
movingY = Math.max(movingY, 0);
}
const newX = Math.min(anchorLeft, movingX);
const newY = Math.min(anchorTop, movingY);
const newWidth = Math.abs(movingX - anchorLeft);
const newHeight = Math.abs(movingY - anchorTop);
this.state.x = newX;
this.state.y = newY;
this.state.width = newWidth;
this.state.height = newHeight;
}
#onPointerUp = (): void => {
if (this.#rafID !== null) {
cancelAnimationFrame(this.#rafID);
this.#rafID = null;
this.#pendingApply = false;
}
this.state.moving = false;
this.state.resizing = false;
this.#resizeDirection = null;
document.body.style.userSelect = '';
this.#node.style.transition = this.#savedTransition;
this.#node.style.willChange = 'auto';
this.#node.style.touchAction = '';
this.#node.style.cursor = 'auto';
window.removeEventListener('pointermove', this.#onPointerMove);
window.removeEventListener('pointerup', this.#onPointerUp);
window.removeEventListener('pointercancel', this.#onPointerCancel);
this.#apply();
};
#onWrapperResize(): void {
const style = getComputedStyle(this.#wrapper);
this.#wrapperBorderLeft = parseFloat(style.borderLeftWidth);
this.#wrapperBorderTop = parseFloat(style.borderTopWidth);
if (this.state.maximized) {
this.state.width = this.#wrapperWidth;
this.state.height = this.#wrapperHeight;
this.state.x = 0;
this.state.y = 0;
} else {
this.#clampRect();
}
this.#apply();
}
#updateCursor = (e: PointerEvent): void => {
if (this.state.moving || this.state.resizing) return;
const target = e.target as HTMLElement;
if (this.#isInteractive(target)) {
this.#resetCursor();
return;
}
if (this.#opts.resizeHandle?.contains(target)) {
this.#node.style.cursor = 'se-resize';
return;
}
const dir = this.#getCornerDirection(e);
if (dir) {
this.#node.style.cursor = dir === 'nw' || dir === 'se' ? 'nwse-resize' : 'nesw-resize';
return;
}
if (this.#opts.handle) {
if (this.#opts.handle.contains(target)) {
this.#node.style.cursor = 'grab';
} else {
this.#node.style.cursor = '';
}
} else {
this.#node.style.cursor = '';
}
};
#resetCursor = (): void => {
this.#node.style.cursor = '';
};
#isInteractive(target: HTMLElement): boolean {
const tag = target.tagName;
if (['INPUT', 'BUTTON', 'TEXTAREA', 'SELECT', 'A'].includes(tag)) return true;
if (target.isContentEditable) return true;
return !!target.closest('[role="button"], [role="textbox"]');
}
minimize(): void {
this.state.minimized = !this.state.minimized;
this.#opts.onMinimize?.();
}
maximize(): void {
if (this.state.maximized) {
if (this.#restoreRect) {
Object.assign(this.state, this.#restoreRect);
this.#restoreRect = null;
}
this.state.maximized = false;
} else {
this.#restoreRect = {
x: this.state.x,
y: this.state.y,
width: this.state.width,
height: this.state.height
};
this.state.x = 0;
this.state.y = 0;
this.state.width = this.#wrapperWidth;
this.state.height = this.#wrapperHeight;
this.state.maximized = true;
}
this.#apply();
}
close(): void {
this.#opts.onClose?.();
}
destroy(): void {
if (this.#rafID !== null) {
cancelAnimationFrame(this.#rafID);
}
this.#node.removeEventListener('pointerdown', this.#onPointerDown);
this.#node.removeEventListener('pointermove', this.#updateCursor);
this.#node.removeEventListener('pointerleave', this.#resetCursor);
//this.#node.removeEventListener('keydown', this.#onKeyDown);
window.removeEventListener('pointermove', this.#onPointerMove);
window.removeEventListener('pointerup', this.#onPointerUp);
window.removeEventListener('pointercancel', this.#onPointerCancel);
if (this.#wrapperObserver) {
this.#wrapperObserver.disconnect();
}
const mgr = getWrapperManager(this.#wrapper);
mgr.refCount--;
if (mgr.refCount === 0) {
delete (this.#wrapper as any)[MWIN_MANAGER];
}
document.body.style.userSelect = '';
this.#node.style.cssText = this.#savedStyles;
this.#node.style.transition = this.#savedTransition;
this.#node.style.willChange = 'auto';
this.#node.style.touchAction = '';
}
}
+96
View File
@@ -0,0 +1,96 @@
export interface MWinParams {
wrapper: HTMLElement | (() => HTMLElement) | string; // changed
handle?: HTMLElement | (() => HTMLElement) | string;
initX?: number;
initY?: number;
initWidth?: number;
initHeight?: number;
baseZIndex?: number;
resizable?: boolean | MWinResizeParams;
resizeHandle?: HTMLElement | (() => HTMLElement) | string;
onClose?: () => void;
onMinimize?: () => void;
onMaximize?: () => void;
onAPI?: (api: MWinAPI) => void;
}
export interface MWinNormalizedParams {
handle: HTMLElement | null;
initX?: number;
initY?: number;
initWidth?: number;
initHeight?: number;
baseZIndex: number;
resizeHandle: HTMLElement | null;
resizable: boolean;
threshold: number;
minWidth: number;
minHeight: number;
maxWidth: number;
maxHeight: number;
onClose?: () => void;
onMinimize?: () => void;
onMaximize?: () => void;
}
export interface MWinResizeParams {
threshold?: number;
minWidth?: number;
minHeight?: number;
maxWidth?: number;
maxHeight?: number;
}
export interface MWinState {
x: number;
y: number;
width: number;
height: number;
minimized: boolean;
maximized: boolean;
moving: boolean;
resizing: boolean;
zIndex: number;
}
export interface MWinAPI {
state: MWinState;
minimize: () => void;
maximize: () => void;
close: () => void;
}
export class WrapperManager {
zCounter: number = 0;
refCount: number = 0;
}
export type ResizeDirection = 'ne' | 'se' | 'sw' | 'nw' | null;
export const MWIN_MANAGER = Symbol('mwinlib');
export function getWrapperManager(wrapper: HTMLElement): WrapperManager {
let mgr = (wrapper as any)[MWIN_MANAGER] as WrapperManager | undefined;
if (!mgr) {
mgr = { zCounter: 0, refCount: 0 };
(wrapper as any)[MWIN_MANAGER] = mgr;
}
return mgr;
}
export function resolveElement(
input: HTMLElement | (() => HTMLElement) | string | undefined,
relativeTo: HTMLElement
): HTMLElement | null {
if (!input) return null;
if (input instanceof HTMLElement) return input;
if (typeof input === 'function') return input();
if (typeof input === 'string') {
return relativeTo.closest(input) as HTMLElement | null;
}
return null;
}
+19
View File
@@ -0,0 +1,19 @@
import { customType } from 'drizzle-orm/mysql-core';
export const mediumblob = customType<{
data: Buffer;
driverData: Buffer;
}>({
dataType() {
return 'MEDIUMBLOB';
}
});
export const longblob = customType<{
data: Buffer;
driverData: Buffer;
}>({
dataType() {
return 'LONGBLOB';
}
});
+73 -5
View File
@@ -1,4 +1,16 @@
import { mysqlTable, serial, int, text, tinyint } from 'drizzle-orm/mysql-core';
import {
boolean,
char,
int,
longtext,
mysqlTable,
serial,
text,
timestamp,
tinyint,
varchar
} from 'drizzle-orm/mysql-core';
import { longblob, mediumblob } from './custom-types';
export const task = mysqlTable('task', {
id: serial('id').primaryKey(),
@@ -6,10 +18,66 @@ export const task = mysqlTable('task', {
priority: int('priority').notNull().default(1)
});
export const settings = mysqlTable('settings', {
var: text('var').notNull().unique(),
state: tinyint('state')
export const config = mysqlTable('config', {
key: varchar('key', { length: 64 }).primaryKey(),
value: longtext('value').notNull()
});
export type Setting = typeof settings.$inferSelect;
export const projects = mysqlTable('projects', {
id: tinyint('id').notNull().primaryKey().autoincrement(),
name: text('name').notNull(),
data: longtext('data', {}).notNull(),
enabled: tinyint('enabled').notNull()
});
export const locales = mysqlTable('locales', {
code: char('code').notNull().unique(),
name: char('name').notNull(),
dictionary: longtext().notNull(),
flag: longtext('').notNull(),
enabled: tinyint('enabled').notNull()
});
export const groups = mysqlTable('groups', {
gid: int('gid').primaryKey().autoincrement(),
name: varchar('name', { length: 32 }).notNull().unique()
});
export const users = mysqlTable('users', {
uid: int('uid').primaryKey().autoincrement(),
username: varchar('username', { length: 32 }).notNull().unique(),
password: varchar('password', { length: 128 }).notNull(),
home: int('home').notNull(),
gid: int('gid')
.notNull()
.references(() => groups.gid),
accessible: boolean('accessible').notNull(),
face: mediumblob('face')
});
export const filesystem = mysqlTable(
'filesystem',
{
id: int('id').primaryKey().default(1),
data: longtext('data').notNull(),
checksum: varchar('checksum', { length: 32 }).notNull(),
updatedAt: timestamp('updated_at').defaultNow().onUpdateNow()
} /* ,
{
// Ensures only one row can exist
singleRow: check('single_row_check', `id = 1`)
} */
);
export const fileContents = mysqlTable('file_contents', {
guid: varchar('guid', { length: 36 }).primaryKey(),
data: longblob('data').notNull(),
mimeType: varchar('mime_type', { length: 127 }).default('text/plain'),
checksum: varchar('checksum', { length: 32 }).notNull()
});
export const allowList = mysqlTable('allow_list', {
ip: int('ip').notNull()
});
export type Config = typeof config.$inferSelect;
Executable → Regular
View File
-3
View File
@@ -1,4 +1,3 @@
import { WebG } from '$lib/shimagic/renderer/web_g_engine';
import type { KeyBind } from '../terminal/keybindRegistry';
import type { Bash, Result } from './bash';
import { cd } from './commands/cd';
@@ -32,8 +31,6 @@ export const COMMANDS = {
testProcess
} as const satisfies Record<string, ICommand>;
WebG.
/* //export const commands {
return: {
method: this.cmd_return,
View File
View File
Executable → Regular
-217
View File
@@ -1,217 +0,0 @@
import type { User } from './etc/userData';
import type { Permission, TimeStamps } from './metadata';
export enum Type {
Directory = 16384,
File = 32768,
SymbolicLink = 40960
}
export type NodePermission = {
user: Permission;
group: Permission;
other: Permission;
};
export type FsInitArgs = {
fs: Map<number, TreeNode>;
user: User;
};
export type TreeNode = {
inode: number;
parent: number;
name: string;
type: Type;
size: number; //Size in Bytes
children: number[];
content: string; // GUID of the cache file that contains the file contents.
link: number; // Links
permission: NodePerms;
owner: number;
group: number;
timestamps: TimeStamps;
interactible: boolean;
func: any;
};
export class VirtualFS {
private FsTable: Map<number, TreeNode>;
private rootINode: number;
private user: User;
home: number;
cwd: number;
pwd: number;
constructor(args: FsInitArgs) {
this.FsTable = args.fs;
this.user = args.user;
this.rootINode = 1;
this.home = this._pathStringToINode(args.user.home);
this.cwd = args.user.cwd ? args.user.cwd! : this.home;
this.pwd = args.user.pwd ? args.user.pwd! : this.cwd;
console.log(this.home);
console.log(this.cwd);
console.log(this.pwd);
}
private _iNodeToPathString(inode: number): string {
const currentNode = this.FsTable.get(inode);
if (!currentNode)
throw new Error('could not find the node in the fs table - inodetopathstring');
if (!currentNode.parent || currentNode.inode === this.rootINode) {
return '/';
}
const parentPath: string = this._iNodeToPathString(currentNode.parent);
return parentPath === '/' ? `/${currentNode.name}` : `${parentPath}/${currentNode.name}`;
}
//TODO: Make all backend methods NOT throw errors. Just return null, and let more closely connected with bash functions call throwError() so user can see the error.
// this will save a lot of ass pain later.
private _pathStringToINode(path: string): number {
const normalizedPath = path.replace(/^\/+|\/+$/g, '');
const pathComponents = normalizedPath.split('/').filter((component) => component.length > 0);
console.log(path, 'pathstringtoinode');
if (pathComponents.length === 0) return this.rootINode;
let currentNode = this.FsTable.get(this.rootINode);
if (!currentNode) throw new Error('iNode does not exist,');
for (const component of pathComponents) {
const childINode = this._findChildNodeByName(currentNode, component);
if (childINode === null) throw new Error('this child iNode does not exist,');
const nextNode = this.FsTable.get(childINode);
if (!nextNode) throw new Error('iNode child does not exist,');
currentNode = nextNode;
}
console.log(path, currentNode.inode);
return currentNode.inode;
}
private _findChildNodeByName(node: TreeNode, name: string): number {
console.log(name, node);
for (const childINode of node.children) {
const child = this.FsTable.get(childINode);
if (child && child.name === name) {
return childINode;
}
}
throw new Error('could not find the specified child node');
}
private _isAbsolutePath = (path: string): boolean => {
return typeof path === 'string' && path.startsWith('/');
};
public getPathByInode(inode: number): string {
return this._iNodeToPathString(inode);
}
public formatPath(path: string): string {
console.log(path, 'formatPath');
const prefix = this._iNodeToPathString(this.home);
if (path.startsWith(prefix)) {
return path.replace(prefix, '~');
} else return path;
}
public resolvePath(path: string): TreeNode {
if (path === '/') return this.getNodeByINode(this.rootINode);
let parsedPath: string = path;
if (!this._isAbsolutePath(path)) {
const trail: string = this._iNodeToPathString(this.cwd);
parsedPath = `${trail}/${path}`;
console.log(parsedPath);
}
if (path.startsWith('~')) {
const trail: string = this._iNodeToPathString(this.home);
parsedPath = `${trail}/${path.replace('~', '')}`;
console.log(parsedPath);
}
const INode: number = this._pathStringToINode(parsedPath);
const Node: TreeNode = this.getNodeByINode(INode);
return Node;
}
public getNodeByINode(inode: number): TreeNode {
const node: TreeNode | undefined = this.FsTable.get(inode);
if (!node) throw new Error(`Could not get the node, no such inode exists - ${inode}`);
return node;
}
public recursiveTraversalPre(
node: TreeNode,
callback: (param: TreeNode) => void,
childIndex?: number[],
depthIndex?: number
): void {
if (!depthIndex) depthIndex = 0;
if (!childIndex) childIndex = [0];
if (node.type != Type.File && node.children[childIndex[depthIndex]]) {
node = this.getNodeByINode(node.children[childIndex[depthIndex]]);
depthIndex++;
if (!childIndex[depthIndex]) childIndex[depthIndex] = 0;
callback(node);
} else {
node = this.getNodeByINode(node.parent);
childIndex[depthIndex] = 0;
depthIndex--;
childIndex[depthIndex]++;
}
if (depthIndex < 0) return;
this.recursiveTraversalPre(node, callback, childIndex, depthIndex);
}
private _createNode(name: string, type: Type, path: number, user: number): void {
let children: null | number[];
const node: TreeNode = {
inode: this.FsTable.size + 1,
name: name,
type: type,
size: 4096, //TODO: Calculate the size from the content
children: [],
content: '',
link: -1,
permission: {
user: {
r: true,
w: true,
x: false
},
group: {
r: true,
w: false,
x: false
},
other: {
r: true,
w: false,
x: false
}
},
owner: user,
group:
}
}
}
Executable → Regular
+4 -4
View File
@@ -1,6 +1,5 @@
import type { Bash } from './bash';
import { FileSystem } from '$lib/termos/filesystem/filesystem';
import type { TreeNode } from './fs';
import { Posix } from './posix';
export enum SortNodeBy {
NAME = 'name',
@@ -15,11 +14,12 @@ export enum SortNodeBy {
export class Sort {
public static nodeArraySort(
this: Bash,
nodes: TreeNode[] | number[],
reverse: boolean = false,
sortBy: SortNodeBy = SortNodeBy.NAME
): TreeNode[] {
const Fs = FileSystem.instance;
if (nodes.length === 0) {
console.warn('Tried to sort an empty node array!');
return [];
@@ -28,7 +28,7 @@ export class Sort {
if (typeof nodes[0] === 'number') {
for (const inode of nodes as number[]) {
const node = this.getFs().getNodeByINode(inode);
const node = Fs.getNodeByInode(inode);
parsedNodes.push(node);
}
Sort.nodeQSort(parsedNodes, reverse, sortBy, 0, parsedNodes.length - 1);
Executable → Regular
View File
+31
View File
@@ -0,0 +1,31 @@
import { addToast } from '$lib/stores/toasts';
import { derived, writable } from 'svelte/store';
import type { GroupData } from '../../routes/admin/util';
export const groups = writable<GroupData[]>([]);
export const groupMap = derived(groups, ($groups) => {
const map = new Map<number, string>();
for (const group of $groups) {
map.set(group.gid, group.groupname);
}
return map;
});
export async function fetchGroups() {
try {
const res = await fetch('/api/groups');
if (res.ok) {
const data = await res.json();
const groupsData: GroupData[] = data.map((g: any) => ({
gid: g.gid,
groupname: g.name,
members: g.members || []
}));
groups.set(groupsData);
} else {
throw new Error('Failed to fetch groups');
}
} catch (error: any) {
addToast('error', 'Groups', 'Failed to load groups: ' + error.message);
}
}
Executable → Regular
View File
+348
View File
@@ -0,0 +1,348 @@
import { FileSystem } from '$lib/termos/filesystem/filesystem';
import type { GroupData, GroupFormData, UserData, UserFormData } from '../../routes/admin/util';
import { addToast } from './toasts';
let users: UserData[] = $state([]);
let groups: GroupData[] = $state([]);
let config: Record<string, string> = $state({});
let userSearch = $state('');
let groupSearch = $state('');
let checkedUsers: Set<number> = $state(new Set());
let checkedGroups: Set<number> = $state(new Set());
let focusedUid: number | null = $state(null);
let focusedGid: number | null = $state(null);
let panelMode: 'user' | 'group' | null = $state(null);
let editingId: number | null = $state(null);
let userFormCache: Map<number, UserFormData> = $state(new Map());
let groupFormCache: Map<number, GroupFormData> = $state(new Map());
// ---------- Getters ----------
export function getUsers() {
return users;
}
export function getGroups() {
return groups;
}
export function getConfig() {
return config;
}
export function getUserSearch() {
return userSearch;
}
export function getGroupSearch() {
return groupSearch;
}
export function getCheckedUsers() {
return checkedUsers;
}
export function getCheckedGroups() {
return checkedGroups;
}
export function getFocusedUid() {
return focusedUid;
}
export function getFocusedGid() {
return focusedGid;
}
export function getPanelMode() {
return panelMode;
}
export function getEditingId() {
return editingId;
}
export function getUserFormCache() {
return userFormCache;
}
export function getGroupFormCache() {
return groupFormCache;
}
export function getFilteredUsers() {
return filteredUsers;
}
export function getFilteredGroups() {
return filteredGroups;
}
export function getActiveUserForm() {
return activeUserForm;
}
export function getActiveGroupForm() {
return activeGroupForm;
}
/* prettier-ignore */
const filteredUsers = $derived(
users.filter(
(u) => !userSearch || u.username.toLowerCase().includes(userSearch.toLowerCase())
)
);
const filteredGroups = $derived(
groups.filter(
(g) => !groupSearch || g.groupname.toLowerCase().includes(groupSearch.toLowerCase())
)
);
const activeUserForm = $derived(
panelMode === 'user' && editingId !== null
? (userFormCache.get(editingId) ?? newUserForm(editingId))
: null
);
const activeGroupForm = $derived(
panelMode === 'group' && editingId !== null
? (groupFormCache.get(editingId) ?? newGroupForm(editingId))
: null
);
function newUserForm(uid: number): UserFormData {
const u = users.find((u) => u.uid === uid);
if (!u) throw new Error('Failed to create new form data - user not found');
return {
uid,
username: u.username,
password: '',
confirmPassword: '',
homeDir: u.homeDir,
gid: u.gid,
accessible: u.accessible,
avatarFile: undefined,
avatarUrl: u.avatarUrl,
supplementaryGroups: []
};
}
function newGroupForm(gid: number): GroupFormData {
const g = groups.find((g) => g.gid === gid);
if (!g) throw new Error('Failed to create new form data - group not found');
return {
gid: g.gid,
groupname: g.groupname,
members: g.members
};
}
export async function fetchAllData() {
try {
const groupsRes = await fetch(`/api/v1/groups`);
if (!groupsRes.ok) throw new Error('Failed to fetch groups');
const groupsData: any[] = await groupsRes.json();
groups = groupsData.map((g: any) => ({
gid: g.gid,
groupname: g.name,
members: g.members || []
}));
const usersRes = await fetch('/api/v1/users');
if (!usersRes.ok) throw new Error('Failed to fetch users');
const usersRaw: any[] = await usersRes.json();
users = usersRaw.map((u: any) => ({
uid: u.uid,
username: u.username,
homeDir: u.home,
homePath: FileSystem.instance.getPathByINode(u.home),
gid: u.gid,
group: groups.find((g) => g.gid === u.gid)?.groupname || 'unknown',
accessible: u.accessible,
avatarUrl: u.avatarUrl,
supplementaryGroups: [] // computed below
}));
for (const user of users) {
const supp = groups.filter((g) => g.members.includes(user.uid)).map((g) => g.groupname);
user.supplementaryGroups = supp;
}
const configRes = await fetch(`/api/v1/config`);
if (configRes.ok) {
config = await configRes.json();
}
} catch (err: any) {
throw new Error(err.message);
}
}
export function removeUserCheck(uid: number) {
if (checkedUsers.has(uid)) checkedUsers.delete(uid);
}
export function removeGroupCheck(gid: number) {
if (checkedUsers.has(gid)) checkedUsers.delete(gid);
}
export function addUserCheck(uid: number) {
if (!checkedUsers.has(uid)) checkedUsers.delete(uid);
}
export function addGroupCheck(gid: number) {
if (!checkedUsers.has(gid)) checkedGroups.delete(gid);
}
export function toggleUserCheck(uid: number) {
if (checkedUsers.has(uid)) checkedUsers.delete(uid);
else checkedUsers.add(uid);
}
export function toggleGroupCheck(gid: number) {
if (checkedGroups.has(gid)) checkedGroups.delete(gid);
else checkedGroups.add(gid);
}
export function clearUserChecks() {
checkedUsers.clear();
}
export function clearGroupChecks() {
checkedGroups.clear();
}
export function openEdit(id: number, type: 'user' | 'group') {
panelMode = type;
editingId = id;
}
export function closePanel() {
panelMode = null;
editingId = null;
}
export function updateUserFormCache(uid: number, form: UserFormData) {
userFormCache.set(uid, form);
}
export function updateGroupFormCache(gid: number, form: GroupFormData) {
groupFormCache.set(gid, form);
}
export function clearUserCache(uid: number) {
userFormCache.delete(uid);
}
export function clearGroupCache(gid: number) {
groupFormCache.delete(gid);
}
export async function saveUser(form: UserFormData) {
const formData = new FormData();
formData.append('uid', form.uid!.toString());
formData.append('username', form.username);
formData.append('password', form.password);
formData.append('home', form.homeDir.toString());
formData.append('gid', form.gid.toString());
formData.append('accessible', form.accessible ? '1' : '0');
if (form.avatarFile) formData.append('avatar', form.avatarFile);
const res = await fetch(`/api/v1/users`, { method: 'POST', body: formData });
if (!res.ok) {
const err = await res.text();
throw new Error(err);
}
let uid: number;
if (form.uid !== undefined) {
uid = form.uid;
} else {
const created = await res.json();
uid = created.uid;
}
const oldSuppGids = groups
.filter((g) => g.members.includes(uid) && g.gid !== form.gid)
.map((g) => g.gid);
const newSuppGids = form.supplementaryGroups ?? [];
const added = newSuppGids.filter((gid) => !oldSuppGids.includes(gid));
const removed = oldSuppGids.filter((gid) => !newSuppGids.includes(gid));
async function updateGroupMembers(gid: number, members: number[]) {
await fetch(`/api/v1/groups`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ gid, members })
});
}
for (const gid of added) {
const group = groups.find((g) => g.gid === gid);
if (group) {
const newMemebers = [...group.members, uid];
await updateGroupMembers(gid, newMemebers);
}
}
for (const gid of removed) {
const group = groups.find((g) => g.gid === gid);
if (group) {
const newMemebers = group.members.filter((m) => m !== uid);
await updateGroupMembers(gid, newMemebers);
}
}
if (form.uid !== undefined) clearUserCache(form.uid!);
await fetchAllData();
addToast('success', 'User', 'Saved successfully');
}
export async function deleteUser(uid: number) {
const res = await fetch(`/api/v1/users/${uid}`, { method: 'DELETE' });
if (!res.ok) {
addToast('error', 'Failed', `To delete user - ${users.find((u) => u.uid === uid)?.username}`);
throw new Error('Failed to delete user');
}
clearUserCache(uid);
await fetchAllData();
addToast('success', 'User', 'Deleted');
}
export async function saveGroup(form: GroupFormData) {
const body = JSON.stringify({
gid: form.gid,
name: form.groupname,
members: form.members // array of uids
});
const res = await fetch(`/api/v1/groups`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body
});
if (!res.ok) throw new Error('Failed to save group');
clearGroupCache(form.gid!);
await fetchAllData();
addToast('success', 'Group', 'Saved');
}
export async function deleteGroup(gid: number) {
const res = await fetch(`/api/v1/groups/${gid}`, { method: 'DELETE' });
if (!res.ok) throw new Error('Failed to delete group');
clearGroupCache(gid);
await fetchAllData();
addToast('success', 'Group', 'Deleted');
}
export async function setConfig(key: string, value: string) {
const oldValue = config[key];
config[key] = value;
try {
const res = await fetch(`/api/v1/config`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ [key]: value })
});
if (!res.ok) throw new Error('Config update failed');
} catch (err: any) {
config[key] = oldValue;
addToast('error', 'Config', err.message);
}
}
Executable → Regular
View File
View File
View File
-2
View File
@@ -33,8 +33,6 @@ export type PageCallbacks = {
getFontSize: () => number;
};
TermOS.Shell;
export class Terminal {
private _bash: Bash;
private _callbacks: Partial<PageCallbacks> = {};
Executable → Regular
+23 -10
View File
@@ -1,17 +1,30 @@
import { writable } from 'svelte/store';
function getInitalTheme(): string {
if (typeof window === 'undefined') return 'dark';
const savedTheme: string | null = localStorage.getItem('theme');
if (savedTheme === 'dark' || savedTheme === 'light') return savedTheme;
const sysPrefTheme = window.matchMedia('(prefers-color-scheme: dark)').matches;
return sysPrefTheme ? 'dark' : 'light';
function getInitialTheme(): string {
// On client, read from the data-theme attribute set by the blocking script
if (typeof document !== 'undefined') {
const theme = document.documentElement.getAttribute('data-theme');
if (theme === 'dark' || theme === 'light') return theme;
}
// Fallback (SSR or if script failed)
if (typeof window !== 'undefined') {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
return 'dark';
}
export const theme = writable(getInitalTheme());
export const theme = writable(getInitialTheme());
theme.subscribe((value) => {
if (typeof window !== 'undefined') localStorage.setItem('theme', value);
if (typeof document !== 'undefined') {
document.documentElement.setAttribute('data-theme', value);
localStorage.setItem('theme', value);
}
});
// Optional: listen to system preference changes
if (typeof window !== 'undefined') {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
theme.set(e.matches ? 'dark' : 'light');
});
}
+68
View File
@@ -0,0 +1,68 @@
import { Tween } from 'svelte/motion';
import { writable } from 'svelte/store';
import type { ToastMessage } from '../../routes/admin/util';
let toastId = 0;
export const toasts = writable<ToastMessage[]>([]);
export function addToast(
type: ToastMessage['type'],
title: string,
message: string,
duration?: number,
initial?: number,
target?: number,
hideProgress?: boolean,
hideDismiss?: boolean,
onClose?: (tm: ToastMessage) => void,
onClick?: (tm: ToastMessage) => void
) {
const id = ++toastId;
duration = duration ?? 3000;
initial = initial ?? 100;
target = target ?? 0;
hideProgress = hideProgress ?? false;
hideDismiss = hideDismiss ?? false;
let isPermament: boolean = duration === 0 || duration === Infinity;
if (hideDismiss) isPermament = false;
if (isPermament) hideProgress = true;
let tween: Tween<number> | undefined;
if (!isPermament) {
tween = new Tween(initial, { duration: duration });
tween.set(target).then(() => {
removeToast(id);
});
}
toasts.update((t) => [
...t,
{
id,
type,
title,
message,
duration,
tween,
initial,
target,
hideProgress,
hideDismiss,
onClose,
onClick
}
]);
}
export function removeToast(id: number) {
let closedToast: ToastMessage | undefined;
toasts.update((ts) => {
closedToast = ts.find((t) => t.id === id);
return ts.filter((t) => t.id !== id);
});
if (closedToast?.onClose) closedToast.onClose(closedToast);
}
+69
View File
@@ -0,0 +1,69 @@
// src/lib/stores/users.ts
import { addToast } from '$lib/stores/toasts';
import { FileSystem } from '$lib/termos/filesystem/filesystem';
import { derived, writable } from 'svelte/store';
import type { UserData } from '../../routes/admin/util';
import { groupMap } from './groups';
interface RawUser {
uid: number;
username: string;
homeDir: number;
gid: number;
avatarUrl: string;
accessible: boolean;
}
export const rawUsers = writable<RawUser[]>([]);
export const usersLoading = writable(false);
export const userDataMap = derived(
[rawUsers, groupMap],
([$rawUsers, $groupsMap]): Map<number, UserData> | null => {
try {
FileSystem.instance;
} catch {
return null; // FileSystem not initialized
}
const map = new Map<number, UserData>();
for (const u of $rawUsers) {
const resolvedPath = FileSystem.instance.getPathByINode(u.homeDir);
const group = $groupsMap.get(u.gid);
const groupName = group?.groupname || 'unknown';
map.set(u.uid, {
uid: u.uid,
username: u.username,
homeDir: u.homeDir,
homePath: resolvedPath,
gid: u.gid,
group: groupName,
accessible: u.accessible,
avatarUrl: u.avatarUrl
});
}
return map;
}
);
export const userList = derived(userDataMap, ($map) => {
if (!$map) return [];
return Array.from($map.values());
});
export async function fetchUsers() {
usersLoading.set(true);
try {
const res = await fetch('/api/users');
if (res.ok) {
const data = await res.json();
rawUsers.set(data as RawUser[]);
} else {
throw new Error('Failed to fetch users');
}
} catch (err: any) {
addToast('error', 'Users', 'Failed to load users: ' + err.message);
} finally {
usersLoading.set(false);
}
}
View File
+228 -74
View File
@@ -1,109 +1,233 @@
import type { User } from '../shell/shell';
import { MD5 } from '../util/hash';
export class FileSystem {
static #instance: FileSystem;
private _fs: Map<number, TreeNode>;
private _root: number;
static #instance: FileSystem | null = null;
private constructor() {
private _fs: Map<number, TreeNode> = new Map();
private _canon_fs: Map<number, TreeNode> = new Map();
private _protectedNodes: Set<number> = new Set();
private _root: number = 1;
private constructor() {}
//TODO: Add a public setNode method that uses the private methods to manage the map;
public static async init(): Promise<void> {
if (FileSystem.#instance) return;
const instance = new FileSystem();
await instance.initialize();
FileSystem.#instance = instance;
}
private async initialize(): Promise<void> {
const cacheETag = localStorage.getItem(STORAGE_KEYS.etag);
const cacheData = localStorage.getItem(STORAGE_KEYS.data);
const headers: HeadersInit = {};
if (cacheETag) {
headers['If-None-Match'] = cacheETag;
}
const response = await fetch(`/api/v1/fs`, { headers });
let jsonText: string;
if (response.status === 304 && cacheData) {
jsonText = cacheData;
} else if (response.ok) {
jsonText = await response.text();
const newETag = response.headers.get('ETag');
localStorage.setItem(STORAGE_KEYS.data, jsonText);
if (newETag) {
localStorage.setItem(STORAGE_KEYS.etag, newETag);
}
} else {
throw new Error(`Failed to load filesystem: ${response.status}`);
}
const parsed = JSON.parse(jsonText);
this._canon_fs = FileSystem._jsonToNodeTable(parsed);
this._fs = FileSystem._cloneFs(this._canon_fs);
this._root = this._fs.values().next().value!.inode;
if (!this._root) throw new Error('First entry in the filesystem map empty!');
await this.loadProtectedNodesConfig();
this.applyLocalEdits();
this.applyLocalDeletions();
}
public static async Init() {
const fsJson: JSON = await this._fetchFileSystem('/temp/path');
const checksum: any = MD5.hash(JSON.stringify(fsJson));
}
private static async _fetchFileSystem(path: string): Promise<JSON> {
const response = await fetch(path);
if (!response.ok) throw new Error('Failed to fetch the file system json');
return await response.json();
}
private async _fetchFsSignature(path: string): Promise<any> {
private async loadProtectedNodesConfig(): Promise<void> {
try {
const response = await fetch(path);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const response = await fetch(`/api/v1/config`);
if (!response.ok) return;
const data = await response.text();
return data.slice(0, 36); //32 characters of uuid + 4 dashes
} catch (error) {
console.error('Failed to fetch the file system signature', error);
const config = await response.json();
if (config.protected_inodes) {
const list: number[] = JSON.parse(config.protected_inodes);
this._protectedNodes = new Set(list);
}
} catch {
throw new Error(`The protected nodes config failed to load`);
}
}
private async fetchFsJson(sig: string): Promise<JSON> {
const signature: string | null = localStorage.getItem('signature');
private applyLocalEdits(): void {
const cache = localStorage.getItem(STORAGE_KEYS.edits);
if (!cache) return;
if (signature !== sig || signature === null || localStorage.getItem('fs') === null) {
const fs: JSON = await this._fetchFileSystem('/src/lib/assets/fs/fs.json');
localStorage.setItem('signature', sig);
localStorage.setItem('fs', JSON.stringify(fs));
const edits: Record<number, TreeNode> = JSON.parse(cache);
console.info('FS fetched from file, new sinature:', sig);
for (const [inodeStr, node] of Object.entries(edits)) {
const inode = Number(inodeStr);
if (this._protectedNodes.has(inode)) continue;
return fs;
} else {
const fs: string | null = localStorage.getItem('fs');
if (fs === null) throw new Error('FS in LocalStorage is null!');
this._fs.set(inode, node);
console.info('FS fetched from localStorage with signature:', sig);
if (!node.parent && !this._fs.has(node.parent)) continue;
return JSON.parse(fs);
const parent = this._fs.get(node.parent)!;
if (parent.children.includes(inode)) {
parent.children.push(inode);
}
}
}
private _jsonToNodeTable(data: JSON): Map<number, TreeNode> {
private applyLocalDeletions(): void {
const cache = localStorage.getItem(STORAGE_KEYS.deletions);
if (!cache) return;
const deletions: number[] = JSON.parse(cache);
while (deletions.length > 0) {
const inode = deletions.pop()!;
if (this._protectedNodes.has(inode)) continue;
const node = this._fs.get(inode);
if (!node) continue;
if (node.type === Type.Directory) {
deletions.push(...node.children);
}
if (node.parent && this._fs.has(node.parent)) {
const parent = this._fs.get(node.parent)!;
parent.children = parent.children.filter((child) => child !== inode);
}
this._fs.delete(inode);
}
}
private static _cloneFs(source: Map<number, TreeNode>): Map<number, TreeNode> {
const copy = new Map<number, TreeNode>();
for (const [inode, node] of source) {
copy.set(inode, { ...node, children: [...node.children] });
}
return copy;
}
private static _NodeTableToJson(table: Map<number, TreeNode>): string {
const obj: Record<string, any> = {};
const sortedInodes = [...table.keys()].sort((a, b) => a - b);
for (const inode of sortedInodes) {
const node = table.get(inode)!;
obj[inode.toString()] = {
Inode: node.inode,
Name: node.name,
Type: node.type,
Size: node.size,
Children: [...node.children].sort((a, b) => a - b),
Content: node.content,
Target: node.link,
Persmision: [
{
Read: node.permission.user.r,
Write: node.permission.user.w,
Exec: node.permission.user.x
},
{
Read: node.permission.group.r,
Write: node.permission.group.w,
Exec: node.permission.group.x
},
{
Read: node.permission.other.r,
Write: node.permission.other.w,
Exec: node.permission.other.x
}
],
Owner: node.owner,
Group: node.group,
TimeStamps: {
MTime: node.timestamps.modified.toISOString(),
CTime: node.timestamps.changed.toISOString(),
ATime: node.timestamps.accessed.toISOString()
},
Interactible: node.interactible,
Func: node.func,
Parent: node.parent
};
}
return JSON.stringify(obj);
}
private static _jsonToNodeTable(data: JSON): Map<number, TreeNode> {
const FsTable: Map<number, TreeNode> = new Map<number, TreeNode>();
const entryList = Object.entries(data);
for (let i = 0; i < entryList.length; i++) {
const object: any = entryList[i][1];
for (const [key, obj] of Object.entries(data)) {
const inode = Number(key);
const node: TreeNode = {
inode: object.Inode,
name: object.Name,
type: object.Type,
size: object.Size,
interactible: object.Interactible,
func: object.Func,
children: object.Children,
content: object.Content,
link: object.Target,
inode: inode,
name: obj.Name,
type: obj.Type,
size: obj.Size,
interactible: obj.Interactible,
func: obj.Func,
children: Array.isArray(obj.Children) ? obj.Children : [],
content: obj.Content,
link: obj.Target,
permission: {
user: {
r: object.Permission[0]?.Read,
w: object.Permission[0]?.Write,
x: object.Permission[0]?.Exec
r: obj.Permission[0]?.Read ?? false,
w: obj.Permission[0]?.Write ?? false,
x: obj.Permission[0]?.Exec ?? false
},
group: {
r: object.Permission[1]?.Read,
w: object.Permission[1]?.Write,
x: object.Permission[1]?.Exec
r: obj.Permission[1]?.Read ?? false,
w: obj.Permission[1]?.Write ?? false,
x: obj.Permission[1]?.Exec ?? false
},
other: {
r: object.Permission[2]?.Read,
w: object.Permission[2]?.Write,
x: object.Permission[2]?.Exec
r: obj.Permission[2]?.Read ?? false,
w: obj.Permission[2]?.Write ?? false,
x: obj.Permission[2]?.Exec ?? false
}
},
owner: object.Owner,
group: object.Group,
owner: obj.Owner,
group: obj.Group,
timestamps: {
modified: new Date(object.TimeStamps.MTime),
changed: new Date(object.TimeStamps.CTime),
accessed: new Date(object.TimeStamps.ATime)
modified: new Date(obj.TimeStamps.MTime),
changed: new Date(obj.TimeStamps.CTime),
accessed: new Date(obj.TimeStamps.ATime)
},
parent: object.Parent
parent: obj.Parent
};
FsTable.set(object.Inode, node);
FsTable.set(inode, node);
}
return FsTable;
}
@@ -150,10 +274,31 @@ export class FileSystem {
this._fs.set(this._fs.size + 1, node);
}
private _deleteNode(inode: number): void {
private applySingleDeletion(inode: number): void {
const node = this._fs.get(inode);
if (!node) return;
if (node.parent && this._fs.has(node.parent)) {
const parent = this._fs.get(node.parent)!;
parent.children = parent.children.filter((child) => child !== inode);
}
this._fs.delete(inode);
}
private removeLocalEdit(inode: number): void {
const edits = JSON.parse(localStorage.getItem(STORAGE_KEYS.edits) || '{}');
delete edits[inode];
localStorage.setItem(STORAGE_KEYS.edits, JSON.stringify(edits));
}
private removeLocalDeletion(inode: number): void {
const deletions: number[] = JSON.parse(localStorage.getItem(STORAGE_KEYS.deletions) || '[]');
const idx = deletions.indexOf(inode);
if (idx !== -1) {
deletions.splice(idx, 1);
localStorage.setItem(STORAGE_KEYS.deletions, JSON.stringify(deletions));
}
}
private _iNodeToPathString(inode: number): string {
const currentNode = this._fs.get(inode);
@@ -212,6 +357,8 @@ export class FileSystem {
return typeof path === 'string' && path.startsWith('/');
};
public saveEdit(edit: TreeNode): void {}
public getPathByINode(inode: number): string {
return this._iNodeToPathString(inode);
}
@@ -224,10 +371,10 @@ export class FileSystem {
public getNodeByInode(inode: number): TreeNode {
const node: TreeNode | undefined = this._fs.get(inode);
if (!node) throw new Error(`No node exists under inode - ${inode}`);
return node;
return structuredClone(node);
}
public resolvePath(path: string, user: User): TreeNode {
public getNodeByPathString(path: string, user: User): TreeNode {
if (path === '/') return this._fs.get(this._root)!;
let parsedPath: string = path;
@@ -248,8 +395,8 @@ export class FileSystem {
});
parsedPath = `${trail}/${path.replace('~', '')}`;
}
return this._pathStringToNode(parsedPath);
const node = this._pathStringToNode(parsedPath);
return structuredClone(node);
}
public recursiveTraversalPre(
@@ -288,10 +435,10 @@ export class FileSystem {
public static get instance(): FileSystem {
if (!FileSystem.#instance) {
FileSystem.#instance = new FileSystem();
throw new Error(`FileSystem was not initialized properly!`);
}
return FileSystem.instance;
return FileSystem.#instance;
}
}
@@ -335,3 +482,10 @@ export type TimeStamps = {
changed: Date;
accessed: Date;
};
const STORAGE_KEYS = {
data: 'fs_data', // JSON string of canonical filesystem
etag: 'fs_etag', // MD5 checksum from server
edits: 'fs_edits', // Record<number, TreeNode> of user modifications
deletions: 'fs_deletions' // number[] of inodes deleted by user
};
+1 -1
View File
@@ -5,7 +5,7 @@ export abstract class Command {
public abstract readonly _help: string; //TODO: Dont know where to pull the help text from yet
public abstract result: CommandResult;
public abstract Main(this: Shell, flags: CommandFlag[], args: string[]): void;
public abstract Main(flags: CommandFlag[], args: string[]): void;
}
export type CommandFlag = {
+11 -6
View File
@@ -1,9 +1,8 @@
import type { Stack } from '$lib/stores/stack';
import { FileSystem } from '../filesystem/filesystem';
import type { Command } from './command';
import type { Process } from './process';
export class Shell {
private readonly _fs: FileSystem;
private _passwd: User[];
private _group: Group[];
@@ -14,9 +13,15 @@ export class Shell {
private user: User;
private _process?: Process;
constructor() {
this._fs = new FileSystem();
}
constructor() {}
public static Initialize(
username: string,
password: string,
commands: Map<string, Command>,
passwd: Map<number, User>,
group: Map<number, Group>
) {}
}
export enum ExitCode {
@@ -0,0 +1,66 @@
export class KeybindListener {
#abortController: AbortController;
#eventStack: KeyboardEvent[] = [];
#bindTable: Map<Keybind, KeybindOptions> = new Map();
constructor(elem: HTMLElement) {
this.#abortController = new AbortController();
elem.addEventListener('keydown', (e) => this.#captureEvent(e), {
signal: this.#abortController.signal,
passive: true
});
}
#captureEvent(e: KeyboardEvent) {
if (e.altKey || e.shiftKey || e.ctrlKey) {
this.#eventStack.push(e);
}
this.#processEvent(e);
}
#processEvent(e: KeyboardEvent) {
const keybind: Keybind = {
key: e.key,
modifiers: this.#pushModifiers()
};
const value = this.#bindTable.get(keybind);
if (!value) return;
value?.function?.(e);
console.log(`[keybind-listener] - executed a function under a keybind: ${keybind}`);
}
#pushModifiers(): Modifier[] {
const mods: Modifier[] = [];
for (const event of this.#eventStack) {
mods.push(event.key as Modifier);
}
return mods;
}
registerKeybinds(keybinds: { keybind: Keybind; options: KeybindOptions }[]): void {
for (const value of keybinds) {
this.#bindTable.set(value.keybind, {
function: value.options.function,
no_inhibit: value.options.no_inhibit ?? false
});
console.log(`[keybind-listener] - keybind registered under the key: ${value.keybind}`);
}
}
}
export type Keybind = {
key: string;
modifiers?: Modifier[];
};
export type KeybindOptions = {
function: (e: KeyboardEvent) => void;
no_inhibit?: boolean;
};
export type Modifier = 'Control' | 'Alt' | 'Shift';
+129 -6
View File
@@ -1,11 +1,110 @@
export class MD5 {
private static encoder: TextEncoder = new TextEncoder();
// prettier-ignore
private static K: number[] = [
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
];
// prettier-ignore
private static S: number[] = [
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
];
public static hash(input: string) {
const uIntArr: Uint8Array<ArrayBuffer> = this.encoder.encode(input);
const inputArr: Uint8Array<ArrayBuffer> = this.encoder.encode(input);
const padded = MD5.pad(inputArr);
let A = 0x67452301;
let B = 0xefcdab89;
let C = 0x98badcfe;
let D = 0x10325476;
function processBlock(M: number[]) {
function F(b: number, c: number, d: number): number {
return (b & c) | (~b & d);
}
function H(b: number, c: number, d: number): number {
return b ^ c ^ d;
}
function I(b: number, c: number, d: number): number {
return c ^ (b | ~d);
}
function G(b: number, c: number, d: number): number {
return (b & d) | (c & ~d);
}
private pad(input: Uint8Array) {
let AA = A,
BB = B,
CC = C,
DD = D;
for (let i = 0; i < 64; i++) {
let f: number, g: number;
if (i < 16) {
f = F(B, C, D);
g = i;
} else if (i < 32) {
f = G(B, C, D);
g = (5 * i + 1) % 16;
} else if (i < 48) {
f = H(B, C, D);
g = (3 * i + 5) % 16;
} else {
f = I(B, C, D);
g = (7 * i) % 16;
}
const sum = MD5.add32(A, MD5.add32(f, MD5.add32(M[g], MD5.K[i])));
const temp = MD5.add32(B, MD5.leftRotate(sum, MD5.S[i]));
A = D;
D = C;
C = B;
B = temp;
}
A = MD5.add32(A, AA);
B = MD5.add32(B, BB);
C = MD5.add32(C, CC);
D = MD5.add32(D, DD);
}
for (let i = 0; i < padded.length; i += 64) {
const M = MD5.sliceToWords(padded.slice(i, i + 64));
processBlock(M); // modifies A, B, C, D directly
}
const hashBytes = new Uint8Array([
...MD5.wordToBytesLE(A),
...MD5.wordToBytesLE(B),
...MD5.wordToBytesLE(C),
...MD5.wordToBytesLE(D)
]);
return MD5.toHexString(hashBytes);
}
private static pad(input: Uint8Array): Uint8Array {
const inputBitLength: number = input.length * 8;
const out: Uint8Array = new Uint8Array([...input, 0x80]);
@@ -27,21 +126,21 @@ export class MD5 {
(high >> 24) & 0xff
]);
return new Int8Array([...out, ...zeroArray, ...lengthBytes]);
return new Uint8Array([...out, ...zeroArray, ...lengthBytes]);
}
private sliceToBlocks(input: Uint8Array): number[][] {
private static sliceToBlocks(input: Uint8Array): number[][] {
const blocks: number[][] = [];
for (let i = 0; i < input.length; i += 64) {
const block = input.slice(i, i + 64);
blocks.push(this.sliceToWords(block));
blocks.push(MD5.sliceToWords(block));
}
return blocks;
}
private sliceToWords(block: Uint8Array): number[] {
private static sliceToWords(block: Uint8Array): number[] {
const words: number[] = new Array<number>(16);
for (let i = 0; i < 16; i++) {
@@ -57,4 +156,28 @@ export class MD5 {
return words;
}
private static leftRotate(x: number, n: number): number {
x = x >>> 0;
return ((x << n) | (x >>> (32 - n))) >>> 0;
}
private static add32(a: number, b: number): number {
return ((a >>> 0) + (b >>> 0)) >>> 0;
}
private static wordToBytesLE(word: number): Uint8Array {
return new Uint8Array([
word & 0xff,
(word >>> 8) & 0xff,
(word >>> 16) & 0xff,
(word >>> 24) & 0xff
]);
}
private static toHexString(bytes: Uint8Array): string {
return Array.from(bytes)
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
}
+13
View File
@@ -0,0 +1,13 @@
import type { Keybind, KeybindOptions } from "../terminal/keybind_listenter";
export const SHELL_KEYBINDS: { keybind: Keybind; options: KeybindOptions }[] = [
{
keybind: {
key: 'c',
modifiers: ['Control']
}
options: {
function
}
}
]
+138
View File
@@ -1,3 +1,4 @@
import type { UserData } from '../../../routes/admin/util';
import { FileSystem, type TreeNode } from '../filesystem/filesystem';
export enum SortNodeBy {
@@ -11,7 +12,35 @@ export enum SortNodeBy {
CTIME = 'changed'
}
export enum SortUserBy {
UID = 'uid',
USERNAME = 'username',
HOME = 'homePath', // sort by home dir name
GROUP = 'group', // group name
ACCESSIBLE = 'accessible'
}
export enum SortGroupBy {
UID = 'uid',
NAME = 'groupname',
MEMBERS = 'members' // members ammount
}
export class Sort {
public static userArraySort(
array: UserData[],
reverse: boolean = false,
sortBy: SortUserBy = SortUserBy.USERNAME
): UserData[] {
if (array.length === 0) {
console.warn('Tried to sort an empty UserData array!');
return [];
}
Sort.userDataQSort(array, reverse, sortBy, 0, array.length - 1);
return array;
}
public static nodeArraySort(
nodes: TreeNode[] | number[],
reverse: boolean = false,
@@ -38,6 +67,20 @@ export class Sort {
}
}
private static userDataQSort(
array: UserData[],
reverse: boolean,
sortBy: SortUserBy,
start: number,
end: number
) {
if (end <= start) return;
let pivot: number = this.userPartition(array, reverse, sortBy, start, end);
this.userDataQSort(array, reverse, sortBy, start, pivot - 1);
this.userDataQSort(array, reverse, sortBy, pivot + 1, end);
}
private static nodeQSort(
array: TreeNode[],
reverse: boolean,
@@ -78,6 +121,32 @@ export class Sort {
return i;
}
private static userPartition(
part: UserData[],
reverse: boolean,
sortBy: SortUserBy,
start: number,
end: number
): number {
let pivot: UserData = part[end];
let i: number = start - 1;
for (let j = start; j <= end; j++) {
if (this.userCompareElements(part[j], pivot, sortBy, reverse) < 0) {
i++;
let temp = part[i];
part[i] = part[j];
part[j] = temp;
}
}
i++;
let temp = part[i];
part[i] = part[end];
part[end] = temp;
return i;
}
private static nodeCompareElements(
a: TreeNode,
b: TreeNode,
@@ -139,6 +208,75 @@ export class Sort {
throw new Error(`Sorting basis outside of the declared scope. - `);
}
}
private static userCompareElements(
a: UserData,
b: UserData,
sortBy: SortUserBy,
reverse: boolean
): number {
switch (sortBy) {
case SortUserBy.USERNAME: {
const nameA: string = a.username;
const nameB: string = b.username;
const minLength = Math.min(nameA.length, nameB.length);
for (let i = 0; i < minLength; i++) {
const charCodeA = Posix.GetCharWeight(nameA[i]);
const charCodeB = Posix.GetCharWeight(nameB[i]);
if (charCodeA !== charCodeB) {
return reverse ? charCodeB - charCodeA : charCodeA - charCodeB;
}
}
return reverse ? nameB.length - nameA.length : nameA.length - nameB.length;
}
case SortUserBy.UID: {
console.log(sortBy, 'sortby');
const uidA: number = a.uid;
const uidB: number = b.uid;
return reverse ? uidB - uidA : uidA - uidB;
}
case SortUserBy.HOME: {
const nameA: string = a.homePath.replaceAll('/', '');
const nameB: string = b.homePath.replaceAll('/', '');
const minLength = Math.min(nameA.length, nameB.length);
for (let i = 0; i < minLength; i++) {
const charCodeA = Posix.GetCharWeight(nameA[i]);
const charCodeB = Posix.GetCharWeight(nameB[i]);
if (charCodeA !== charCodeB) {
return reverse ? charCodeB - charCodeA : charCodeA - charCodeB;
}
}
return reverse ? nameB.length - nameA.length : nameA.length - nameB.length;
}
case SortUserBy.GROUP: {
const nameA: string = a.group;
const nameB: string = b.group;
const minLength = Math.min(nameA.length, nameB.length);
for (let i = 0; i < minLength; i++) {
const charCodeA = Posix.GetCharWeight(nameA[i]);
const charCodeB = Posix.GetCharWeight(nameB[i]);
if (charCodeA !== charCodeB) {
return reverse ? charCodeB - charCodeA : charCodeA - charCodeB;
}
}
return reverse ? nameB.length - nameA.length : nameA.length - nameB.length;
}
case SortUserBy.ACCESSIBLE: {
return reverse
? (b.accessible ? 1 : 0) - (a.accessible ? 1 : 0)
: (a.accessible ? 1 : 0) - (b.accessible ? 1 : 0);
}
default:
throw new Error(`Sorting basis outside of the declared scope. - `);
}
}
}
class Posix {
+10
View File
@@ -0,0 +1,10 @@
<script lang="ts">
let { children, class: className = '', ...restProps } = $props();
</script>
<button
{...restProps}
class=" cursor-pointer rounded-md p-2 transition-all duration-200 hover:brightness-110 active:translate-y-0.5 active:brightness-90 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:brightness-100 {className}"
>
{@render children()}
</button>
+69
View File
@@ -0,0 +1,69 @@
<script lang="ts">
let x: number = $state(0);
let y: number = $state(0);
let showContestMenu: boolean = $state(false);
let rootElement: HTMLElement | undefined;
let parentElement: HTMLElement | null = null;
let {
items = [],
onClose = () => {}
}: {
items: { label: string; action: () => void }[];
onClose: () => void;
} = $props();
function handleAction(item: { action: () => void }) {
item.action();
closeContextMenu();
}
function closeContextMenu() {
showContestMenu = false;
onClose();
}
function handleGlobalInteraction(e: MouseEvent) {
e.preventDefault();
showContestMenu = !showContestMenu;
x = e.x;
y = e.y;
}
function handleKeyDown(e: KeyboardEvent) {
if (e.key === 'Escape') {
closeContextMenu();
}
}
function initEventListener(node: HTMLElement) {
const parent = node.parentElement;
if (!parent) return;
parent.addEventListener('contextmenu', handleGlobalInteraction, true);
document.addEventListener('keydown', handleKeyDown);
return {
destroy() {
parent.removeEventListener('contextmenu', handleGlobalInteraction, true);
document.removeEventListener('keydown', handleKeyDown);
}
};
}
</script>
<div use:initEventListener>
{#if showContestMenu}
<div
id="context-menu"
class="fixed z-100 min-w-[150px] bg-bg-lighter-dark"
style="left: {x}px; top: {y}px;"
>
{#each items as item}
<button title={item.label} onclick={() => handleAction(item)}
><p class="w-full text-text-dark">{item.label}</p></button
>
{/each}
</div>
{/if}
</div>
Executable → Regular
View File
Executable → Regular
View File
+103 -49
View File
@@ -1,12 +1,10 @@
<script lang="ts">
import { enhance } from "$app/forms";
import { PASSWD } from "$lib/stores/bash/etc/userData";
import { ArrowRight, ChevronLeft, ChevronRight, CircleAlert, Lock } from "@lucide/svelte";
import type { effect } from "zod/v3";
import { enhance } from '$app/forms';
import { PASSWD } from '$lib/stores/bash/etc/userData';
import { ArrowRight, ChevronLeft, ChevronRight, Lock } from '@lucide/svelte';
let formElem: HTMLElement;
let {init, form}: { init: (formData: FormData) => void, form: any} = $props();
let { init, form }: { init: (formData: FormData) => void; form: any } = $props();
const USERS = PASSWD.filter((user) => user.accesible == true);
const basePath: string = '/src/lib/assets/login/';
@@ -15,61 +13,104 @@
let username: string = $state('gornodox');
function changeUser(direction: 0 | 1) {
if(direction === 0) userIndex--;
if (direction === 0) userIndex--;
else userIndex++;
if(userIndex >= USERS.length) userIndex = 0;
if(userIndex < 0) userIndex = USERS.length - 1;
if (userIndex >= USERS.length) userIndex = 0;
if (userIndex < 0) userIndex = USERS.length - 1;
const user = USERS[userIndex];
username = user.username;
}
//TODO: Prefetch the images of the users when hovering on top of user switch buttons
</script>
<div id="wrapper" class=" flex flex-col items-center" class:outro={form?.success}>
<img class="rounded-full mb-4 border-primary-dark border-2" src={`${basePath}${username}.png`} onerror={(event) => {(event.currentTarget as HTMLImageElement).src = `${basePath}default.png`; return false;}} alt="user avatar" width="80" height="80" />
<div id="name" class=" relative flex flex-row items-center text-text-muted-dark justify-center gap-4 w-1/2">
<button onclick={() => changeUser(0)}
class=" active:-translate-x-0.5 hover:text-primary-hover-dark"><ChevronLeft size={16} strokeWidth={2} /></button>
<img
class="mb-4 rounded-full border-2 border-border shadow-subtle"
src={`${basePath}${username}.png`}
onerror={(event) => {
(event.currentTarget as HTMLImageElement).src = `${basePath}default.png`;
return false;
}}
alt="user avatar"
width="80"
height="80"
/>
<div
id="name"
class=" text-text-muted-dark relative flex w-1/2 flex-row items-center justify-center gap-4"
>
<button
id="btn-left"
onclick={() => changeUser(0)}
class=" hover:text-primary-hover-dark active:-translate-x-0.5"
><ChevronLeft size={16} strokeWidth={2} /></button
>
<strong class=" mx-auto">{username}</strong>
<button onclick={() => changeUser(1)}
class=" active:translate-x-0.5 hover:text-primary-hover-dark"><ChevronRight size={16} strokeWidth={2} /></button>
<button
id="btn-right"
onclick={() => changeUser(1)}
class=" hover:text-primary-hover-dark active:translate-x-0.5"
><ChevronRight size={16} strokeWidth={2} /></button
>
</div>
<form bind:this={formElem} onanimationend={() => {formElem.classList.remove('invalid')}} use:enhance={({ formData }) =>
{
<form
bind:this={formElem}
onanimationend={() => {
formElem.classList.remove('invalid');
}}
use:enhance={({ formData }) => {
init(formData);
}
} method="POST" action="?/login" class:invalid={form?.error} name="login-form" autocomplete="off" class="mt-6 flex flex-row gap-1">
<input name="username" value={username} class=" hidden ">
<div class=" bg-bg-lighter-dark flex flex-row ml-4 items-center rounded outline-none border border-transparent text-sm p-1.5 w-2xs text-text-dark focus-within:bg-bg-light-dark focus-within:border-primary-dark {form?.error ? 'focus-within:border-warning-dark text-warning-dark' : ''}">
}}
method="POST"
action="?/login"
class:invalid={form?.error}
name="login-form"
autocomplete="off"
class="mt-6 flex flex-row gap-1"
>
<input name="username" value={username} class=" hidden" />
<div
class="flex w-2xs flex-row
items-center overflow-clip rounded-md border border-border bg-surface-1 pl-2 text-sm text-muted transition-colors duration-200 outline-none has-focus:border-focus-ring"
>
<Lock size={16} strokeWidth={2} />
<input autofocus name="password" type="password" autocomplete="off" placeholder="Password..." class=" placeholder-text-dark {form?.error ? 'placeholder-warning-dark' : ''} grow ml-2 appearance-none outline-none">
</div>
<button type="submit" class=" bg-bg-lighter-dark rounded p-1.5 hover:text-primary-hover-dark active:text-primary-dark active:bg-bg-light-dark">
<input
name="password"
type="password"
placeholder="Password..."
class=" ml-2 grow appearance-none px-3 py-2 outline-none"
/>
<button
type="submit"
class=" bg-bg-lighter-dark hover:text-primary-hover-dark active:text-primary-dark active:bg-bg-light-dark rounded p-1.5"
>
<ArrowRight size={20} strokeWidth={2} />
</button>
</div>
</form>
</div>
<style>
.invalid {
.invalid {
animation: var(--animate-error-shake);
}
}
#error {
animation: fadeIn 0.2s forwards cubic-bezier(.4,.7,0,.99);
}
#error {
animation: fadeIn 0.2s forwards cubic-bezier(0.4, 0.7, 0, 0.99);
}
.switchL {
animation: fadeSlideLeft .75s forwards cubic-bezier(.4,.7,0,.99);
}
.switchL {
animation: fadeSlideLeft 0.75s forwards cubic-bezier(0.4, 0.7, 0, 0.99);
}
.switchR {
animation: fadeSlideRight .75s forwards cubic-bezier(.4,.7,0,.99);
}
.switchR {
animation: fadeSlideRight 0.75s forwards cubic-bezier(0.4, 0.7, 0, 0.99);
}
@keyframes fadeSlideLeft {
@keyframes fadeSlideLeft {
25% {
transform: translateX(-1rem);
opacity: 0;
@@ -82,9 +123,9 @@
transform: none;
opacity: 1;
}
}
}
@keyframes fadeSlideRight {
@keyframes fadeSlideRight {
25% {
transform: translateX(1rem);
opacity: 0;
@@ -97,19 +138,19 @@
transform: none;
opacity: 1;
}
}
}
@keyframes fadeIn {
@keyframes fadeIn {
to {
opacity: 1;
}
}
.outro {
transition: opacity 0.5s cubic-bezier(.4,.7,0,.99) 1s;
.outro {
transition: opacity 0.5s cubic-bezier(0.4, 0.7, 0, 0.99) 1s;
opacity: 0;
form {
transition: opacity 0.2s cubic-bezier(.4,.7,0,.99);
transition: opacity 0.2s cubic-bezier(0.4, 0.7, 0, 0.99);
opacity: 0;
}
img {
@@ -119,11 +160,24 @@
#name {
transform: translateY(30px);
transition: transform 0.5s ease-out;
}
#error {
transition: opacity 0.2s cubic-bezier(.4,.7,0,.99);
#btn-left {
transform: translateX(100px);
transition:
transform 0.2s ease-in,
opacity 0.2s cubic-bezier(0.4, 0.7, 0, 0.99);
opacity: 0;
}
}
#btn-right {
transform: translateX(-100px);
transition:
transform 0.2s ease-in,
opacity 0.2s cubic-bezier(0.4, 0.7, 0, 0.99);
opacity: 0;
}
}
#error {
transition: opacity 0.2s cubic-bezier(0.4, 0.7, 0, 0.99);
opacity: 0;
}
}
</style>
Executable → Regular
View File
Executable → Regular
+40 -28
View File
@@ -1,12 +1,11 @@
<script lang="ts">
import { Languages, Settings2, SunMoon } from '@lucide/svelte';
import { theme } from '$lib/stores/theme';
import { locale } from '$lib/stores/lang';
import plFlag from '$lib/assets/plFlag.svg';
import enFlag from '$lib/assets/enFlag.svg';
import deFlag from '$lib/assets/deFlag.svg';
import enFlag from '$lib/assets/enFlag.svg';
import frFlag from '$lib/assets/frFlag.svg';
import jaFlag from '$lib/assets/jaFlag.svg';
import plFlag from '$lib/assets/plFlag.svg';
import { theme } from '$lib/stores/theme';
import { Languages, Settings2, SunMoon } from '@lucide/svelte';
function toggleSettings() {
const settingsMenu = window.document.getElementById('settings-menu');
@@ -20,66 +19,77 @@
langsMenu?.classList.toggle('hide');
}
function setLang(id: string) {
}
function setLang(id: string) {}
</script>
<div
id="options"
class=" z-100 absolute top-0 left-0 isolate mx-4 rounded-b-xl bg-bg-dark light:bg-bg-light"
>
<div id="options" class=" absolute top-0 left-0 isolate z-70 mx-4 rounded-b-xl bg-surface-1">
<section class="hide grid" id="settings-menu">
<div class="flex flex-col items-center justify-center gap-4 overflow-hidden">
<div class=" mt-4 flex items-center justify-center rounded-lg">
<button
class=" rounded-lg bg-bg-lighter-dark p-1.5 text-text-dark shadow-button duration-75 hover:text-primary-hover-dark active:translate-y-0.5 light:bg-bg-lighter-light light:text-text-muted-light light:hover:text-primary-hover-light"
class="rounded-lg bg-surface-3 p-1.5 text-text-primary shadow-button hover:text-primary active:button-click"
id="theme-btn"
onclick={() => {
$theme = $theme === 'dark' ? 'light' : 'dark';
}}
>
<SunMoon strokeWidth={1} size={32} />
<SunMoon strokeWidth={1} size={32} class="mb-0.5" />
</button>
</div>
<div class="flex flex-col content-center items-center">
<button
class="z-3 mb-4 rounded-lg bg-bg-lighter-dark p-1.5 text-text-dark duration-75 hover:text-primary-hover-dark active:translate-y-0.5 light:bg-bg-lighter-light light:text-text-muted-light light:hover:text-primary-hover-light"
class="z-3 mb-4 rounded-lg bg-surface-3 p-1.5 text-text-primary shadow-button hover:text-primary active:button-click"
id="langs-btn"
onclick={toggleLangs}
>
<Languages strokeWidth={1} size={32} />
<Languages strokeWidth={1} size={32} class="mb-0.5" />
</button>
<form id="langs-menu" class="hide grid">
<div class="z-2 mb-4 flex flex-col items-center gap-2 overflow-hidden">
<label
class="border-primary-dark duration-100 hover:ml-1 hover:pl-1 has-checked:border-l-3 has-checked:hover:m-0 has-checked:hover:p-0 light:border-primary-light"
class=" border-primary duration-50 hover:ml-1 hover:pl-1 has-checked:border-l-3 has-checked:hover:m-0 has-checked:hover:p-0"
>
<input name="langs" type="radio" class="lang hidden" id="pl-PL" autocomplete="off" onclick={() => {console.log($locale)}}/>
<input
name="langs"
type="radio"
class="lang hidden"
id="pl-PL"
autocomplete="off"
onclick={(e) => {
console.log((e.target as HTMLElement).id);
}}
/>
<img class="flags mx-2" src={plFlag} alt="PL" height="26" width="26" />
</label>
<label
class="border-primary-dark duration-100 hover:ml-1 hover:pl-1 has-checked:border-l-3 has-checked:hover:m-0 has-checked:hover:p-0 light:border-primary-light"
class="border-primary duration-50 hover:ml-1 hover:pl-1 has-checked:border-l-3 has-checked:hover:m-0 has-checked:hover:p-0"
>
<input name="langs" type="radio" class="lang hidden" id="en-US" autocomplete="off" onclick={(id) => {
console.log(id);
}}/>
<input
name="langs"
type="radio"
class="lang hidden"
id="en-US"
autocomplete="off"
onclick={(e) => {
console.log((e.target as HTMLElement).id);
}}
/>
<img class="flags mx-2" src={enFlag} alt="EN" height="26" width="26" />
</label>
<label
class="border-primary-dark duration-100 hover:ml-1 hover:pl-1 has-checked:border-l-3 has-checked:hover:m-0 has-checked:hover:p-0 light:border-primary-light"
class="border-primary duration-50 hover:ml-1 hover:pl-1 has-checked:border-l-3 has-checked:hover:m-0 has-checked:hover:p-0"
>
<input name="langs" type="radio" class="lang hidden" id="fr-FR" autocomplete="off" />
<img class="flags mx-2" src={deFlag} alt="DE" height="26" width="26" />
</label>
<label
class="border-primary-dark hover:ml-1 hover:pl-1 has-checked:border-l-3 has-checked:hover:m-0 has-checked:hover:p-0 light:border-primary-light"
class="border-primary duration-50 hover:ml-1 hover:pl-1 has-checked:border-l-3 has-checked:hover:m-0 has-checked:hover:p-0"
>
<input name="langs" type="radio" class="lang hidden" id="en" autocomplete="off" />
<img class="flags mx-2" src={jaFlag} alt="JA" height="26" width="26" />
</label>
<label
class="border-primary-dark transition-none duration-100 hover:ml-1 hover:pl-1 has-checked:border-l-3 has-checked:hover:m-0 has-checked:hover:p-0 light:border-primary-light"
class="border-primary duration-50 hover:ml-1 hover:pl-1 has-checked:border-l-3 has-checked:hover:m-0 has-checked:hover:p-0"
>
<input name="langs" type="radio" class="lang hidden" id="en" autocomplete="off" />
<img class="flags mx-2" src={frFlag} alt="FR" height="26" width="26" />
@@ -90,7 +100,7 @@
</div>
</section>
<button
class="rounded-b-xl border-t bg-bg-light-dark p-2 text-text-dark shadow-button hover:text-primary-dark light:bg-bg-lighter-light light:text-text-muted-light light:hover:text-primary-light"
class="rounded-b-xl border-t bg-surface-3 p-2 text-text-primary shadow-button duration-50 hover:text-primary active:brightness-90"
id="settings-btn"
onclick={toggleSettings}
>
@@ -100,16 +110,18 @@
<style>
#langs-menu {
transition: 0.2s ease-in;
transition: grid-template-rows 0.2s ease-in;
grid-template-rows: 1fr;
&.hide {
grid-template-rows: 0fr;
}
}
#settings-menu {
transition: 0.2s ease-in;
transition: grid-template-rows 0.2s ease-in;
grid-template-rows: 1fr;
&.hide {
grid-template-rows: 0fr;
}
+18
View File
@@ -0,0 +1,18 @@
<script lang="ts">
export let rows = 5;
export let cols = 4;
</script>
<table class="min-w-full divide-y divide-gray-700">
<tbody>
{#each Array(rows) as _}
<tr class="animate-pulse">
{#each Array(cols) as _}
<td class="px-4 py-2">
<div class="h-4 w-3/4 rounded bg-gray-600"></div>
</td>
{/each}
</tr>
{/each}
</tbody>
</table>
Executable → Regular
+49 -87
View File
@@ -1,29 +1,25 @@
<script lang="ts">
import { ExitCode } from '$lib/stores/bash/metadata';
import { initTerminal } from '$lib/stores/terminal/init.svelte';
import { clear, print } from '$lib/stores/terminal/stdio/io';
import { Terminal, type PrintData } from '$lib/stores/terminal/terminal';
import { mwin_movable } from '$lib/mwinlib/mwin_controller.svelte';
import type { MWinAPI } from '$lib/mwinlib/mwin_util';
import Input from './terminal/Input.svelte';
const clearTerminal = (): void => clear();
const printOutput = (e: HTMLElement, d: PrintData): void => print(e, d);
let { username }: { username: string } = $props();
export async function init(username: string, password: string) {
try {
terminal = await initTerminal({ username, password }, callbackInit, 'en_US');
updateTerminal();
//await initTerminal({ username, password }, callbackInit, 'en_US');
updateTerminal(); //Rename this
} catch (error) {
console.error('terminal init failed', error);
console.error('Failed to intialize the terminal', error);
}
runTerminal();
document.getElementById('terminal-window')?.classList.remove('hidden');
}
function updateTerminal() {
//isProcessActive = terminal.isProcessActive;
username = terminal!.getUser().username;
cwd = terminal!.getCwd();
//username = terminal!.getUser().username;
//cwd = terminal!.getCwd();
}
function getWidth() {
@@ -50,98 +46,64 @@
return ctx.measureText('M').width;
}
function inputHandler(event: KeyboardEvent) {
const terminalKeyInhibitor = terminal.getKeybindInhibitor();
terminalKeyInhibitor.processKeystroke(event);
const processKeyInhibitor = terminal.getProcessKeyInhibitor();
if (processKeyInhibitor != ExitCode.ERROR) {
processKeyInhibitor.processKeystroke(event);
}
console.log(processKeyInhibitor, terminalKeyInhibitor);
switch (event.key) {
case 'Enter': {
terminal.executeCommand(inputValue);
updateTerminal();
break;
}
case 'ArrowRight': {
//TODO: Move cursor visually
}
case 'ArrowLeft': {
//TODO: Move cursor visually
}
case 'ArrowUp': {
//TODO: Make a traverse history function with up/down args
}
case 'ArrowDown': {
//TODO: Make a traverse history function with up/down args
}
}
const elem = document.getElementById('cout');
if (!elem) {
throw new Error('cant scroll to bottom, element is null');
}
elem.scrollTop = elem.scrollHeight;
}
function runTerminal() {
document.getElementById('terminal-window')?.classList.remove('hidden');
}
//Callback initializer
const callbackInit = {
print: (data: any) => {
const e = document.getElementById('outputWrapper');
if (!e) return;
printOutput(e, data);
},
clear: clearTerminal,
getWidth: getWidth,
getFontSize: getFontSize
};
//Empty terminal variable where the terminal class instance will be stored
let terminal: Terminal;
let username: string = $state('');
let cwd: string = $state('');
const hostname = 'terminal'; //TODO: Change this to pull from config on db
//let isProcessActive = $state(false);
let inputValue = $state<string>('');
let mwin: MWinAPI;
let inputValue = $state('');
let inputComponent: any;
</script>
<label for="input" onkeydowncapture={(event) => inputHandler(event)} class="w-11/12">
<div
id="terminal-wrapper"
class=" relative flex h-screen w-full flex-col items-center justify-center"
>
<div
id="terminal"
class=" terminal-window shadow-() h-full w-full rounded-md shadow-bg transition-discrete"
class="absolute flex size-full h-256 w-512 flex-col rounded-md shadow-subtle transition-discrete will-change-auto"
use:mwin_movable={{
wrapper: '#terminal-wrapper',
handle: '#terminal-bar',
baseZIndex: 10,
resizable: { threshold: 24, minWidth: 500, minHeight: 300 },
onAPI: (api) => (mwin = api)
}}
>
<div
class="terminal-bar flex h-9 w-full flex-row items-center rounded-t-md bg-bg-dark text-center font-terminal text-sm font-bold text-primary-dark light:bg-bg-dark-light light:text-primary-light"
id="terminal-bar"
class=" flex h-9 w-full flex-row items-center rounded-t-md bg-surface-2 text-center font-terminal text-sm font-bold text-primary select-none"
>
<div class="dots-wrapper mx-2.5 flex h-full flex-row items-center justify-center gap-2.5">
<button class="size-2.5 cursor-pointer rounded-full p-0" title=""></button>
<button class="size-2.5 cursor-pointer rounded-full p-0" title=""></button>
<button class="size-2.5 cursor-pointer rounded-full p-0" title=""></button>
<div class="dots-wrapper mx-3 flex h-full flex-row items-center justify-center gap-3">
<button class="size-3 cursor-pointer rounded-full p-0" title="" onclick={() => mwin.close()}
></button>
<button
class="size-3 cursor-pointer rounded-full p-0"
title=""
onclick={() => mwin.maximize()}
></button>
<button
class="size-3 cursor-pointer rounded-full p-0"
title=""
onclick={() => mwin.minimize()}
></button>
</div>
<div class=" mr-2 flex grow">
<h5>{username}</h5>
<!-- prettier-ignore -->
<h5 class=" mr-2">@terminal: </h5>
<h5>{cwd}</h5>
<div class=" mr-2 flex grow text-sm">
<p>{username}@{hostname} {cwd}</p>
</div>
</div>
<div
class="inner-content scroll-hidden h-7/8 origin-top overflow-y-auto rounded-b-md bg-bg-light-dark p-4 text-text-dark shadow-subtle light:bg-bg-lighter-light light:text-text-light"
class="inner-content scroll-hidden grow origin-top overflow-y-auto rounded-b-md bg-surface-1 p-4 text-sm text-text-primary"
id="cout"
onclick={() => inputComponent?.focusInput()}
onkeydown={() => inputComponent?.focusInput()}
role="textbox"
tabindex="-1"
>
<div id="outputWrapper"></div>
<Input {cwd} bind:inputValue />
<Input bind:value={inputValue} blinkDelay={500} bind:this={inputComponent} />
</div>
</div>
</label>
</div>
<style>
* {
+69
View File
@@ -0,0 +1,69 @@
<script lang="ts">
import { removeToast, toasts } from '$lib/stores/toasts';
import { CircleCheckBig, CircleX, Info, TriangleAlert, X } from '@lucide/svelte';
import { onMount } from 'svelte';
import { fly } from 'svelte/transition';
onMount(() => {
toasts.set([]);
});
</script>
<div class="fixed top-4 right-4 z-50 flex h-full flex-col gap-2 overflow-visible">
{#each $toasts as toast (toast.id)}
<div
transition:fly={{ x: 20, y: 0, duration: 300 }}
id={`toast-${toast.id.toString()}`}
class="w-md overflow-hidden rounded-md bg-surface-2"
onclick={() => toast.onClick?.(toast)}
role="button"
tabindex={toast.onClick ? 0 : undefined}
onkeydown={toast.onClick
? (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toast.onClick?.(toast);
}
}
: undefined}
>
<div class="flex items-center justify-start">
<div class="mx-4 my-8">
{#if toast.type === 'info'}
<Info class=" text-info"></Info>
{:else if toast.type === 'error'}
<CircleX class="text-error"></CircleX>
{:else if toast.type === 'warn'}
<TriangleAlert class="text-warning"></TriangleAlert>
{:else}
<CircleCheckBig class="text-success"></CircleCheckBig>
{/if}
</div>
<div class="my-2 mr-auto mb-auto ml-2 flex flex-col items-start justify-start select-none">
<h5 class=" text- text-md text-text-dark font-bold">{toast.title}</h5>
<p class=" text-md mb-2 overflow-x-hidden overflow-y-scroll text-muted">
{toast.message}
</p>
</div>
<div class=" m-2 self-start">
<button
class:hidden={toast.hideDismiss}
onclick={(e) => {
e.stopPropagation();
removeToast(toast.id);
}}
>
<X
stroke-width={3}
size={18}
class=" transition-all duration-200 hover:text-muted active:scale-90"
></X>
</button>
</div>
</div>
{#if !toast.hideProgress && toast.tween}
<div style:padding-right={`${toast.tween.current}%`} class=" h-[2px] w-0 bg-primary"></div>
{/if}
</div>
{/each}
</div>
+20
View File
@@ -0,0 +1,20 @@
<script lang="ts">
let { id, state, onclick }: { id: string; state: boolean; onclick: (e: MouseEvent) => void } =
$props();
</script>
<label class="inline-flex cursor-pointer items-center gap-3 select-none for={id}">
<input
class="peer sr-only"
{id}
role="switch"
type="checkbox"
checked={state}
onclick={(e) => {
onclick(e);
}}
/>
<span
class="relative block h-6 w-11 rounded-full bg-border transition-colors peer-checked:bg-primary after:absolute after:top-0.5 after:left-0.5 after:h-5 after:w-5 after:rounded-full after:bg-white after:shadow after:transition-transform after:content-[''] peer-checked:after:translate-x-5"
></span>
</label>
+19
View File
@@ -0,0 +1,19 @@
<script lang="ts">
import type { Snippet } from 'svelte';
let { icon, callback, id }: { icon: Snippet; callback: () => void; id: string } = $props();
</script>
<div class=" m-2 flex w-auto flex-col items-center gap-2 rounded-md bg-bg-light-dark p-2">
{@render icon()}
<label
for={id}
class="relative block h-5 w-10 cursor-pointer rounded-full bg-bg-lighter-dark shadow-subtle"
>
<input type="button" onclick={callback} {id} class=" peer sr-only" />
<span
class=" absolute top-0.5 left-0.5 h-4/5 w-2/5 rounded-full bg-bg-dark peer-checked:left-5.5 peer-checked:bg-primary-dark"
>
</span>
</label>
</div>
+19
View File
@@ -0,0 +1,19 @@
<script lang="ts">
let { placeholder, value }: { placeholder: string; value: string } = $props();
</script>
<!-- svelte-ignore a11y_autofocus -->
<div
class="
flex flex-row items-center justify-between
overflow-clip rounded-md border border-border
bg-surface-1 has-focus:border-focus-ring
"
>
<input
type="text"
class="px-3 py-2 outline-none placeholder:text-muted"
{placeholder}
bind:value
/>
</div>
View File
+20
View File
@@ -0,0 +1,20 @@
<script lang="ts">
import { Type } from '$lib/termos/filesystem/filesystem';
import { File, Folder } from '@lucide/svelte';
let {
nodeName,
nodeType,
isProject = true
}: { nodeName: string; nodeType: Type; isProject: boolean } = $props();
</script>
<input type="radio" />
<div class=" flex flex-row items-center rounded-md bg-bg-lighter-dark p-2">
{#if nodeType == Type.Directory}
<Folder class="text-primary-dark" strokeWidth={1} />
{:else}
<File strokeWidth={1} />
{/if}
<h4 class={isProject ? 'text-primary-dark' : 'text-text-dark'}>{nodeName}</h4>
</div>
+1 -3
View File
@@ -1,13 +1,11 @@
<script lang="ts">
import { ChevronRight, Power, SquarePen } from '@lucide/svelte';
let { projectName, checked = true }: { projectName: string; checked: boolean } = $props();
</script>
<div
class=" flex items-center text-text-dark saturate-50 has-checked:saturate-100 light:text-text-light"
>
<div class=" flex w-full flex-col justify-center gap-1 rounded-lg bg-bg-mid-dark">
<div class=" flex w-48 flex-col justify-center gap-1 rounded-lg bg-bg-mid-dark">
<h5 class=" m-4 font-primary text-xl font-bold">{projectName}</h5>
<div class="flex items-center gap-2">
<label
+1 -1
View File
@@ -14,7 +14,7 @@
</script>
<label
class="m-0 flex size-12 items-center justify-center rounded-xl bg-bg-lighter-dark shadow-subtle hover:text-primary-hover-dark has-checked:text-primary-dark has-checked:hover:text-primary-hover-dark light:bg-bg-light-light light:hover:text-primary-hover-light light:has-checked:text-primary-light light:has-checked:hover:text-primary-hover-light"
class=" m-0 flex size-12 items-center justify-center rounded-xl bg-surface-2 shadow-subtle duration-100 transition-standard hover:text-primary has-checked:text-primary has-checked:hover:text-primary has-active:button-click"
>
<input
onclick={() => goto(path)}
+45
View File
@@ -0,0 +1,45 @@
<script lang="ts">
import type { Snippet } from 'svelte';
let {
icon,
checked = false,
onChange = (value: boolean) => {},
disabled = false,
busy = false,
id = ''
}: {
icon?: Snippet;
checked: boolean;
onChange: (value: boolean) => void;
disabled?: boolean;
busy?: boolean;
id?: string;
} = $props();
</script>
<div class=" bg-bg-dark m-2 flex max-w-fit flex-col items-center gap-2 rounded-md p-2">
{#if icon}
{@render icon()}
{/if}
<label for={id} class="relative block h-6 w-11 rounded-full bg-border">
<input
{id}
role="switch"
aria-busy={busy}
disabled={disabled || busy}
type="checkbox"
{checked}
onclick={(e) => {
if (!disabled && !busy) {
checked = !checked;
onChange(checked);
}
}}
class=" peer sr-only"
/>
<span
class=" absolute top-0.5 left-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform content-[''] peer-checked:translate-x-5 peer-checked:bg-primary"
></span>
</label>
</div>
+32
View File
@@ -0,0 +1,32 @@
<script lang="ts">
let {list}: {list: any[]} = $props();
function toggleAll() {
}
</script>
<table class=" max-h-44">
<thead class=" h-4">
<tr>
<th>
<input type="checkbox" onchange={toggleAll} />
</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody class=" overflow-y-auto">
{#each list as entry}
<tr class=" h-4">
<td><input type="checkbox" onchange={toggleAll} /></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
@@ -0,0 +1,25 @@
<script lang="ts">
import type { Snippet } from 'svelte';
let {
icon,
callback,
id,
sync
}: { icon: Snippet; callback: () => void; id: string; sync: boolean } = $props();
</script>
<div class=" bg-bg-light-dark m-2 flex w-auto flex-col items-center gap-2 rounded-md p-2">
{@render icon()}
<label
for={id}
class="bg-bg-lighter-dark relative block h-5 w-10 cursor-pointer rounded-full shadow-subtle"
>
<label class="inline-flex cursor-pointer items-center gap-3 select-none">
<input type="checkbox" class="peer sr-only" checked={sync} onclick={callback} {id} />
<span
class="relative block h-6 w-11 rounded-full bg-border peer-checked:bg-primary after:absolute after:top-0.5 after:left-0.5 after:h-5 after:w-5 after:rounded-full after:bg-white after:shadow after:transition-transform after:content-[''] peer-checked:after:translate-x-5"
></span>
</label>
</label>
</div>
@@ -0,0 +1,41 @@
<div>
<div class="grid grid-cols-[auto_auto_auto] gap-y-4">
<!-- Header row (now a subgrid) -->
<div class="col-span-full mb-0 grid grid-cols-subgrid rounded-md bg-bg-dark">
<div class="px-4 py-2 text-left">
<p>Accessible</p>
</div>
<div class="px-4 py-2 text-left">
<p>Username</p>
</div>
<div class="px-4 py-2 text-left">
<p>Group</p>
</div>
</div>
<!-- Data rows – all follow the same subgrid pattern -->
<div class="col-span-full grid grid-cols-subgrid rounded-md bg-bg-light-dark">
<div class="px-4 py-2 text-left">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
</div>
<div class="px-4 py-2 text-left">
<p>Username</p>
</div>
<div class="px-4 py-2 text-left">
<p>Group</p>
</div>
</div>
<div class="col-span-full grid grid-cols-subgrid rounded-md bg-bg-light-dark">
<div class="px-4 py-2 text-left">
<p>Accessible</p>
</div>
<div class="px-4 py-2 text-left">
<p>Username</p>
</div>
<div class="px-4 py-2 text-left">
<p>Group</p>
</div>
</div>
</div>
</div>
@@ -0,0 +1,91 @@
<script lang="ts">
import { TriangleAlert } from '@lucide/svelte';
import Button from '../../Button.svelte';
let showModal = $state(false);
let {
entityName = '',
entityType = 'item',
onConfirm = () => {},
onClose = () => {},
loading = false
}: {
entityName: string;
entityType?: string;
onConfirm: () => void;
onClose: () => void;
loading?: boolean;
} = $props();
function closeModal() {
showModal = false;
confirmText = '';
onClose();
}
function confirmModal() {
showModal = false;
onConfirm();
}
let confirmText = $state('');
let isValid = $derived(confirmText === entityName && confirmText.length > 0);
</script>
{#if showModal}
<!-- svelte-ignore a11y_autofocus -->
<div
onclick={(e) => {
if (e.target === e.currentTarget) closeModal();
}}
onkeydown={(e) => {
if (e.key === 'Escape') closeModal();
}}
role="textbox"
tabindex="0"
class=" fixed inset-0 z-100 flex items-center justify-center bg-black/55"
autofocus
>
<div class="flex flex-col items-center rounded-xl bg-bg-light-dark p-4">
<TriangleAlert size={48} strokeWidth={2} class=" mb-4 text-danger-dark"></TriangleAlert>
<h2 class=" mb-4 text-xl font-semibold text-text-dark">Delete {entityType}</h2>
<p class=" mb-6 w-3/4 text-center text-text-muted-dark">
Are you sure you want to delete <span class="font-bold text-text-dark">{entityName}</span
>?<br />
This action cannot be undone!
</p>
<div class="flex w-full flex-col items-center px-16">
<p class="mb-2 text-text-muted-dark">
Please type <span class="font-bold text-text-dark">{entityName}</span> to confirm
</p>
<!-- prettier-ignore -->
<input
type="text"
required
class="
mb-4 w-full rounded-md border border-transparent focus:border-primary-dark
bg-bg-lightest-dark px-3 py-2 shadow-subtle placeholder:text-text-muted-dark
outline-none
"
placeholder={entityName}
bind:value={confirmText}
/>
</div>
<div class=" flex justify-end gap-16">
<Button onclick={closeModal} class="bg-bg-lightest-dark">Cancel</Button>
<Button
onkeydown={(e: any) => {
if (e.key === 'Enter') confirmModal();
}}
disabled={!isValid}
onclick={confirmModal}
class=" bg-danger-dark"
>
Delete
</Button>
</div>
</div>
</div>
{/if}
+27
View File
@@ -0,0 +1,27 @@
<script lang="ts">
import { getConfig, getGroups, getUsers, setConfig } from '$lib/stores/panel-state.svelte';
import SwitchModule from '../SwitchModule.svelte';
let toggle = $state(false);
let log = () => {};
async function handleToggle(key: string, newValue: boolean) {
const value = newValue ? '1' : '0';
try {
await setConfig(key, value);
} catch (e) {
// error already handled in setConfig
}
}
$inspect(getUsers(), 'users');
$inspect(getGroups(), 'groups');
$inspect(getConfig(), 'config');
</script>
<div class="justify-betwee flex w-full items-center">
<SwitchModule
id="maintenance"
checked={getConfig()['maintenance'] === '1'}
onChange={(value) => handleToggle('maintenance', value)}
/>
</div>
@@ -0,0 +1,11 @@
<script>
import InputElemModule from '../InputElemModule.svelte';
let value123 = $state('');
$inspect(value123);
</script>
<div>
<InputElemModule placeholder={'Test'} value={value123}></InputElemModule>
</div>
+70
View File
@@ -0,0 +1,70 @@
<script lang="ts">
import { ChevronDown } from '@lucide/svelte';
import type { UserData } from '../../../routes/admin/util';
import Switch from '../../inputs/Switch.svelte';
import UserEditForm from './UserEditForm.svelte';
let { data }: { data: UserData } = $props();
let accessible = $derived(data.accessible);
let detailsToggle: boolean = $state(false);
</script>
<div
class="col-span-full grid grid-cols-subgrid items-center border-y border-b border-border bg-surface-1"
>
<div
class="relative flex h-full items-center px-4 py-4 text-center after:absolute after:top-0 after:left-0 after:h-full after:w-0.5 after:bg-primary after:opacity-0 after:transition-opacity after:content-[''] has-checked:after:opacity-100"
>
<input type="checkbox" />
</div>
<div class="items-center py-4 pr-4 text-left">
<p>{data.username}</p>
</div>
<div class="items-center py-4 pr-4 text-left">
<p>{data.uid}</p>
</div>
<div class="items-center py-4 pr-4 text-left">
<p>{data.homePath}</p>
</div>
<div class="items-center py-4 pr-4 text-left">
<p>{data.group}</p>
</div>
<div class="items-center py-4 pr-4 text-left">
<p>{data.gid}</p>
</div>
<div class="flex items-center py-4 pr-4">
<Switch
id={data.uid + '-user-toggle'}
state={accessible}
onclick={(e) => {
accessible = !accessible;
}}
></Switch>
</div>
<div class="flex items-center py-4 pr-4">
<button
type="button"
aria-label="details"
onclick={() => {
detailsToggle = !detailsToggle;
}}
>
<div
class:-rotate-180={detailsToggle}
class="transition-rotate duration-100 ease-in hover:translate-y-0.5"
>
<ChevronDown></ChevronDown>
</div>
</button>
</div>
</div>
<div
class=" col-span-full grid origin-top grid-rows-[0fr] overflow-clip border-0 border-border bg-surface-1 transition-all duration-150"
class:grid-rows-[1fr]={detailsToggle}
class:border-y={detailsToggle}
>
<div class="min-h-0">
<UserEditForm></UserEditForm>
</div>
</div>
+143
View File
@@ -0,0 +1,143 @@
<script lang="ts">
/*
User checkboxes are not getting updated with the checkedSet changes
remake proof of concept to full fledged frontend
add a edit button to entry
reversing sort makes ALL the ARROWS be reversed
(we only want to indicate the sort direction on the sort comparation value)
make delete action be on bottom of edit form on the right, and save button on the top right of edit form
make the accessible indicator with an icon instead
squish the table in width
make sort indicators with icons
make the table be a separate module thats reusable
make the user entry a reusable module
*/
import {
addUserCheck,
clearUserChecks,
getCheckedUsers,
getFilteredUsers,
getFocusedUid,
openEdit
} from '$lib/stores/panel-state.svelte';
import { SortUserBy } from '$lib/termos/util/sort';
import type { UserData } from '../../../routes/admin/util';
import UserRow from './UserRow.svelte';
import UsersTableColumn from './UsersTableColumn.svelte';
let users = $derived(getFilteredUsers());
let checkedSet = $derived(getCheckedUsers());
let focusedUid = $derived(getFocusedUid());
let sortBy: SortUserBy = $state(SortUserBy.UID);
let sortReverse: boolean = $state(false);
function handleEdit(user: UserData) {
openEdit(user.uid, 'user');
}
function toggleAll(e: Event) {
const target = e.target as HTMLInputElement;
if (target.checked) {
for (const u of users) {
if (!checkedSet.has(u.uid)) {
console.log('checked', u.username);
addUserCheck(u.uid);
}
}
} else {
clearUserChecks();
target.checked = false;
console.log(checkedSet, users);
}
}
function toggleSort(col: SortUserBy): void {
if (sortBy === col) {
sortReverse = !sortReverse;
} else {
sortBy = col;
sortReverse = false;
}
}
</script>
<div>
{#if checkedSet.size > 0}
<!-- Bulk -->
{:else}
<!-- Search -->
{/if}
<div>
<div
style="grid-template-columns: repeat(32, max-content)"
class=" grid w-min border-b border-border"
>
<div
class=" col-span-full grid grid-cols-subgrid items-center border-b border-border bg-surface-2"
>
<div class="flex items-center px-4 py-2 text-center">
<input
type="checkbox"
onchange={toggleAll}
checked={users.length > 0 && checkedSet.size === users.length}
/>
</div>
<UsersTableColumn
header="Username"
{sortBy}
sortParam={SortUserBy.USERNAME}
{sortReverse}
{toggleSort}
></UsersTableColumn>
<UsersTableColumn
header="UID"
{sortBy}
sortParam={SortUserBy.UID}
{sortReverse}
{toggleSort}
></UsersTableColumn>
<UsersTableColumn
header="Home"
{sortBy}
sortParam={SortUserBy.HOME}
{sortReverse}
{toggleSort}
></UsersTableColumn>
<UsersTableColumn
header="Group"
{sortBy}
sortParam={SortUserBy.GROUP}
{sortReverse}
{toggleSort}
></UsersTableColumn>
<UsersTableColumn
header="GID"
{sortBy}
sortParam={SortUserBy.GROUP}
{sortReverse}
{toggleSort}
></UsersTableColumn>
<UsersTableColumn
header="Accessible"
{sortBy}
sortParam={SortUserBy.ACCESSIBLE}
{sortReverse}
{toggleSort}
></UsersTableColumn>
</div>
{#each users as user}
<UserRow data={user}></UserRow>
{/each}
</div>
</div>
</div>
@@ -0,0 +1,30 @@
<script lang="ts">
import type { SortUserBy } from '$lib/termos/util/sort';
import { ChevronsUpDown } from '@lucide/svelte';
let {
header,
sortBy,
sortParam,
sortReverse,
toggleSort
}: {
header: string;
sortBy: SortUserBy;
sortParam: SortUserBy;
sortReverse: boolean;
toggleSort: (param: SortUserBy) => void;
} = $props();
</script>
<div>
<button
class="flex flex-row items-center gap-2 py-2 pr-2 text-left"
onclick={() => toggleSort(sortParam)}
>
<h4 class="font-medium">{header}</h4>
<div class="flex items-center self-center pr-2">
<ChevronsUpDown size={16} strokeWidth={2}></ChevronsUpDown>
</div>
</button>
</div>
+210 -39
View File
@@ -1,53 +1,224 @@
<script lang="ts">
import { KeybindListener } from '$lib/termos/terminal/keybind_listenter';
import { SHELL_KEYBINDS } from '$lib/termos/util/shell_keybinds';
import { onMount } from 'svelte';
let {
inputValue = $bindable(),
isFocused,
cwd
}: { inputValue: string; isFocused?: boolean; cwd: string } = $props();
value = $bindable(''),
blinkDelay = 250,
autofocus = true,
oninput = () => {}
}: {
value?: string;
blinkDelay?: number;
autofocus?: boolean;
oninput?: (value: string) => void;
} = $props();
function handleInput(event: Event) {
inputValue = (event.target as HTMLInputElement).value;
let container: HTMLElement | undefined;
let cursorPos: number = $derived(value.length);
let text: string = $state('');
let focused: boolean = $state(false);
let blinkPaused: boolean = $state(false);
let blinkTimer: ReturnType<typeof setTimeout> | null = null;
$effect(() => {
if (autofocus && container) {
container.focus();
}
});
$effect(() => {
return () => {
if (blinkTimer) {
clearTimeout(blinkTimer);
blinkTimer = null;
}
};
});
export function focusInput(): void {
container?.focus();
}
/* function moveCursor() {
function pauseBlink() {
blinkPaused = true;
if (blinkTimer) clearTimeout(blinkTimer);
blinkTimer = setTimeout(() => {
blinkPaused = false;
blinkTimer = null;
}, blinkDelay);
}
function keyDown(event: KeyboardEvent) {
switch(event.key) {
case 'Enter':
inputValue = ''
case 'ArrowRight':
document.getElementById('cursor')?.style.transform = 'translateX(8px)'
case 'ArrowLeft':
function handleFocus() {
console.log('focused');
focused = true;
blinkPaused = false; // start blinking immediately
}
} */
function handleBlur() {
console.log('blured');
focused = false;
if (blinkTimer) {
clearTimeout(blinkTimer);
blinkTimer = null;
}
blinkPaused = true;
}
function insertChar(char: string) {
text = text.slice(0, cursorPos) + char + text.slice(cursorPos);
cursorPos += char.length;
pauseBlink();
}
function deleteCharBefore() {
if (cursorPos > 0) {
text = text.slice(0, cursorPos - 1) + text.slice(cursorPos);
cursorPos--;
pauseBlink();
}
}
function deleteCharAfter() {
if (cursorPos < text.length) {
text = text.slice(0, cursorPos) + text.slice(cursorPos + 1);
pauseBlink();
}
}
function moveCursor(delta: number) {
const newPos = cursorPos + delta;
if (newPos >= 0 && newPos <= text.length) {
cursorPos = newPos;
pauseBlink();
}
}
function handleKeydown(e: KeyboardEvent) {
console.log(e.key);
if (e.ctrlKey) {
if (e.key === 'a' || e.key === 'A') {
e.preventDefault();
cursorPos = 0;
pauseBlink();
return;
}
if (e.key === 'e' || e.key === 'E') {
e.preventDefault();
cursorPos = text.length;
pauseBlink();
return;
}
if (e.key === 'd' || e.key === 'D') {
e.preventDefault();
deleteCharAfter();
return;
}
if (e.key === 'ArrowLeft') {
e.preventDefault();
cursorPos = 0;
pauseBlink();
return;
}
if (e.key === 'ArrowRight') {
e.preventDefault();
cursorPos = text.length;
pauseBlink();
return;
}
// ignore other Ctrl combos
return;
}
// Arrow keys
if (e.key === 'ArrowLeft') {
e.preventDefault();
moveCursor(-1);
return;
}
if (e.key === 'ArrowRight') {
e.preventDefault();
moveCursor(1);
return;
}
// Home / End
if (e.key === 'Home') {
e.preventDefault();
cursorPos = 0;
pauseBlink();
return;
}
if (e.key === 'End') {
e.preventDefault();
cursorPos = text.length;
pauseBlink();
return;
}
// Backspace / Delete
if (e.key === 'Backspace') {
e.preventDefault();
deleteCharBefore();
return;
}
if (e.key === 'Delete') {
e.preventDefault();
deleteCharAfter();
return;
}
// Printable characters (length === 1 and no modifier)
if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
e.preventDefault();
insertChar(e.key);
return;
}
// Everything else (Enter, Tab, etc.) is ignored.EEE
}
onMount(() => {
const keybindListener = new KeybindListener(container!);
keybindListener.registerKeybinds(SHELL_KEYBINDS);
if (autofocus && container) {
container.focus();
}
});
</script>
<div class=" relative">
<input
autofocus
bind:value={inputValue}
onkeydown={(e) => e.key === 'Enter' && (inputValue = '')}
oninput={handleInput}
onfocus={() => (isFocused = true)}
onblur={() => (isFocused = false)}
type="text"
autocapitalize="off"
autocomplete="off"
autocorrect="off"
class=" pointer-events-none absolute left-0 m-0 w-0 border-none p-0 opacity-0"
id="input"
/>
<p class="cwd" id="cwd">{cwd}</p>
<div class="w flex-column flex flex-row flex-wrap font-terminal">
<span class="pointer pr-2">$</span>
<!-- prettier-ignore -->
<div style="white-space: preserve;" class=" relative wrap-break-word">{inputValue}</div>
<span id="cursor" class={isFocused ? 'animate-cursor-blink' : ''}>_</span>
</div>
<div
id="terminal-input"
class=" relative inline-block font-terminal whitespace-nowrap outline-none select-none"
bind:this={container}
tabindex="0"
role="textbox"
aria-label="terminal input"
onblur={handleBlur}
onfocus={handleFocus}
onkeydown={handleKeydown}
style="--cursor-index: {cursorPos};"
>
<span class="prompt inline-block w-[1ch] text-center">$</span>
<span class="inline cursor-text" aria-hidden="true">
{#each text.split('') as char}
<span class="inline-block w-[1ch] text-center">{char}</span>
{/each}
</span>
<div
class="cursor absolute bottom-[0.2rem] h-px w-[1ch] bg-text-primary"
class:animate-cursor-blink={!blinkPaused}
></div>
</div>
<style>
.cursor {
left: calc(var(--cursor-index) * 1ch + 8.5px + 1ch);
}
</style>
View File
Executable → Regular
+6 -9
View File
@@ -1,10 +1,10 @@
<script lang="ts">
import '../app.css';
import favicon from '$lib/assets/favicon.svg';
import { onMount, type Snippet } from 'svelte';
import { theme } from '$lib/stores/theme';
import Loading from '../modules/Loading.svelte';
import Shimeji from '../modules/Shimeji.svelte';
import { onMount, type Snippet } from 'svelte';
import '../app.css';
//import Loading from '../modules/Loading.svelte';
//import Shimeji from '../modules/Shimeji.svelte';
let { children }: { children: Snippet } = $props();
@@ -40,18 +40,15 @@
</svelte:head>
<main
class="text-text m-auto flex min-h-dvh w-full flex-col items-center justify-center overflow-hidden bg-dots-bg bg-size-[20px_20px]"
class="text-text m-auto flex min-h-dvh w-full flex-col items-center justify-center overflow-hidden bg-bg-base"
class:dark={$theme === 'dark'}
class:light={$theme === 'light'}
>
<Shimeji />
{@render children()}
</main>
<style>
main {
transition:
--dots-bg-2 0.2s ease-in,
--dots-bg-1 0.2s ease-in;
transition: all 0.2s ease-in;
}
</style>
+24 -16
View File
@@ -1,30 +1,38 @@
import { db } from "$lib/server/db";
import { settings } from "$lib/server/db/schema";
import { PASSWD } from "$lib/stores/bash/etc/userData";
import { eq } from "drizzle-orm";
import type { Actions } from "./$types";
import type { PageServerLoad } from "./panel/projects/$types";
import { db } from '$lib/server/db';
import { config } from '$lib/server/db/schema';
import { PASSWD } from '$lib/stores/bash/etc/userData';
import { error } from '@sveltejs/kit';
import { eq } from 'drizzle-orm';
import type { Actions, PageServerLoad } from './$types';
export const actions = {
login: async ({request}) => {
const user = PASSWD.find((object) => object.username == "gornodox");
login: async ({ request }) => {
const user = PASSWD.find((object) => object.username == 'gornodox');
let data = await request.formData();
let out = data.get("password")?.toString();
let out = data.get('password')?.toString();
let error = false;
let success = true
let success = true;
if(out != user?.passwd || out == undefined) {
if (out != user?.passwd || out == undefined) {
error = true;
success = false;
}
return { error, success, data: out };
}
} satisfies Actions
} satisfies Actions;
export const load: PageServerLoad = async () => {
return {
settings: await db.select({setting: settings.state}).from(settings).where(eq(settings.var, 'maintenance')).limit(1)
};
try {
const rows = await db
.select({ value: config.value })
.from(config)
.where(eq(config.value, 'maintenance'))
.limit(1);
return { config: rows };
} catch (err) {
console.error('Full error:', err);
// Optionally, throw a user-friendly error
throw error(500, 'Database query failed');
}
};
Executable → Regular
+34 -31
View File
@@ -1,36 +1,32 @@
<script lang="ts">
import Settings from '../modules/Settings.svelte';
import { isInitializing } from '$lib/stores/terminal/init.svelte';
import Login from '../modules/Login.svelte';
import { mount } from 'svelte';
import Terminal from '../modules/Terminal.svelte';
import { CircleAlert } from '@lucide/svelte';
import Maintenence from '../modules/Maintenence.svelte';
import Settings from '../modules/Settings.svelte';
import Terminal from '../modules/Terminal.svelte';
let { form, data } = $props();
const MAINTENANCE = $derived(Boolean(data.settings[0].setting));
//export let isWelcomeSequence = false;
// svelte-ignore non_reactive_update
let terminalComponent: Terminal;
const MAINTENANCE = $derived(Boolean(data.config[0]));
let username = $state('');
function welcomeSequence() {
//isWelcomeSequence = true;
//TODO: do magic :)
}
function initializer(formData: FormData) {
console.log(formData);
if(form?.error) return;
const password = formData.get("password")?.toString();
const username = formData.get("username")?.toString();
if(!password || !username) throw new Error("password or username is null or undefined");
terminalComponent.init(username, password)
username = formData.get('username')?.toString() ?? 'foo';
if (form?.error) return;
/* const password = formData.get('password')?.toString();
const username = formData.get('username')?.toString();
if (!password || !username) throw new Error('password or username is null or undefined');
terminalComponent.init(username, password); */
}
let bound = $state<HTMLElement>();
</script>
{#if MAINTENANCE}
@@ -38,33 +34,40 @@
<Maintenence />
{:else}
<Settings></Settings>
<div id="main" class="h-dvh w-full p-24 relative flex justify-center items-center">
<div id="wrapper1" class=" absolute z-35 flex flex-col items-center {form?.success ? 'outro' : ''}">
<Login init={initializer} form={form}/>
<div
bind:this={bound}
id="main"
class="relative flex h-screen w-full items-center justify-center p-24"
>
<div
id="wrapper1"
class=" absolute z-35 flex flex-col items-center {form?.success ? 'outro' : ''}"
>
<Login init={initializer} {form} />
</div>
<div id="wrapper2" class=" opacity-0 size-4/5 absolute z-4 {form?.success ? 'intro' : ''}">
<Terminal bind:this={terminalComponent} />
<div id="wrapper2" class=" {form?.success ? 'intro' : ''}">
<Terminal {username} {bound}></Terminal>
</div>
</div>
{/if}
<style>
.intro {
animation: fadeIn 0.5s forwards cubic-bezier(.4,.7,0,.99) 1s;
}
.intro {
animation: fadeIn 0.5s forwards cubic-bezier(0.4, 0.7, 0, 0.99) 1s;
}
.outro {
animation: fadeOut 0.5s forwards cubic-bezier(.4,.7,0,.99) 1s;
}
.outro {
animation: fadeOut 0.5s forwards cubic-bezier(0.4, 0.7, 0, 0.99) 1s;
}
@keyframes fadeIn {
@keyframes fadeIn {
to {
opacity: 1;
display: block;
}
}
}
@keyframes fadeOut {
@keyframes fadeOut {
to {
opacity: 0;
display: none;
+95
View File
@@ -0,0 +1,95 @@
import type { Tween } from 'svelte/motion';
export interface UserData {
uid: number;
username: string;
homeDir: number;
homePath: string;
gid: number;
group: string;
accessible: boolean;
avatarUrl: string;
supplementaryGroups: string[];
}
export interface GroupData {
gid: number;
groupname: string;
members: number[];
}
export interface UserFormData {
uid?: number;
username: string;
password: string;
confirmPassword: string;
homeDir: number;
gid: number;
supplementaryGroups: number[];
accessible: boolean;
avatarFile?: File;
avatarUrl?: string;
}
export interface GroupFormData {
gid: number;
groupname: string;
members: number[];
}
export interface ToastMessage {
id: number;
type: 'success' | 'error' | 'info' | 'warn';
title: string;
message: string;
duration: number;
tween?: Tween<number>;
initial: number;
target: number;
hideProgress: boolean;
hideDismiss: boolean;
onClose?: (tm: ToastMessage) => void;
onClick?: (tm: ToastMessage) => void;
}
export interface Keybind {
action: string;
combo: string;
handler: () => void;
}
export function capitalize(word: string): string {
if (!word) '';
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}
export async function request(
endpoint: string,
options?: {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
body?: any;
headers?: Record<string, string>;
}
) {
const config: RequestInit = {
method: options?.method || 'GET',
headers: {
'Content-Type': 'application/json',
...options?.headers
}
};
if (options?.body) {
config.body = JSON.stringify(options.body);
}
const response = await fetch(`/api/v1/${endpoint}`, config);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Request failed: ${response.status} ${errorText}`);
}
const text = await response.text();
return text ? JSON.parse(text) : null;
}
+26
View File
@@ -0,0 +1,26 @@
import { db } from '$lib/server/db';
import { config } from '$lib/server/db/schema';
export async function GET() {
const rows = await db.select().from(config);
const result: Record<string, string> = {};
for (const row of rows) {
result[row.key] = row.value;
}
return new Response(JSON.stringify(result), {
headers: { 'Content-Type': 'application/json' }
});
}
export async function POST({ request, getClientAddress }) {
const body = await request.json();
for (const [key, value] of Object.entries(body)) {
await db
.insert(config)
.values({ key, value: String(value) })
.onDuplicateKeyUpdate({ set: { value: String(value) } });
}
return new Response(JSON.stringify({ success: true }), {
headers: { 'Content-Type': 'application/json' }
});
}
+25
View File
@@ -0,0 +1,25 @@
import { db } from '$lib/server/db';
import { fileContents } from '$lib/server/db/schema';
import type { RequestEvent } from '@sveltejs/kit';
import { eq } from 'drizzle-orm';
export async function GET(event: RequestEvent): Promise<Response> {
if (event.params.guid === undefined)
return new Response(`Bad request - no guid specified`, { status: 400 });
const row = await db
.select()
.from(fileContents)
.where(eq(fileContents.guid, event.params.guid))
.limit(1);
if (!row.length) {
return new Response(`File not found`, { status: 404 });
}
return new Response(new Uint8Array(row[0].data), {
headers: {
'Content-Type': row[0].mimeType || 'application/octet-stream',
'Cache-Control': 'public, max-age=86400'
}
});
}
+59
View File
@@ -0,0 +1,59 @@
import { db } from '$lib/server/db';
import { filesystem } from '$lib/server/db/schema';
import { MD5 } from '$lib/termos/util/hash';
import { eq } from 'drizzle-orm';
import type { RequestEvent } from './$types';
export async function GET(event: RequestEvent): Promise<Response> {
const row = await db
.select({
data: filesystem.data,
checksum: filesystem.checksum
})
.from(filesystem)
.where(eq(filesystem.id, 1))
.limit(1);
if (!row.length) {
return new Response('Filesystem is not initialized on the database', { status: 500 });
}
const { data, checksum } = row[0];
const clientETag = event.request.headers.get('if-none-match');
if (clientETag === `"${checksum}"`) {
return new Response(null, {
status: 304,
headers: { ETag: `"${checksum}"` }
});
}
return new Response(data, {
status: 200,
headers: {
'Content-Type': 'application/json',
ETag: `"${checksum}"`,
'Cache-Control': 'no-cache'
}
});
}
export async function POST(event: RequestEvent) {
const newData = await event.request.text();
try {
JSON.parse(newData);
//TODO: Schema validation
} catch {
//TODO: Change that to a proper http headers error
return new Response('Invalid JSON', {
status: 400
});
}
const checksum: string = MD5.hash(newData);
await db.update(filesystem).set({ data: newData, checksum }).where(eq(filesystem.id, 1));
return new Response(JSON.stringify({ success: true }), { status: 200 });
}
+14
View File
@@ -0,0 +1,14 @@
import { db } from '$lib/server/db';
import { groups } from '$lib/server/db/schema';
export async function GET() {
const rows = await db.select().from(groups);
if (!rows.length) {
return new Response('No groups stored on the database', { status: 500 });
}
return new Response(JSON.stringify(rows), {
headers: { 'Content-Type': 'application/json' }
});
}
+24
View File
@@ -0,0 +1,24 @@
import { db } from '$lib/server/db';
import { groups } from '$lib/server/db/schema';
import type { RequestEvent } from '@sveltejs/kit';
import { eq } from 'drizzle-orm';
export async function GET(event: RequestEvent): Promise<Response> {
if (event.params.gid === undefined)
return new Response(`Bad request - no gid specified`, { status: 400 });
const row = await db
.select()
.from(groups)
.where(eq(groups.gid, Number(event.params.gid)))
.limit(1);
if (!row.length) {
return new Response(`Group not found`, { status: 404 });
}
return new Response(JSON.stringify(row), {
headers: {
'Content-Type': 'application/json'
}
});
}
+90
View File
@@ -0,0 +1,90 @@
import { db } from '$lib/server/db';
import { users } from '$lib/server/db/schema';
import { json, type RequestEvent } from '@sveltejs/kit';
import { eq } from 'drizzle-orm';
export async function GET(): Promise<Response> {
const rows = await db
.select({
uid: users.uid,
username: users.username,
password: users.password,
home: users.home,
gid: users.gid,
accessible: users.accessible
})
.from(users);
if (!rows.length) {
return new Response('No users stored on the database', { status: 500 });
}
const result: {}[] = rows.map((u) => ({
...u,
avatarUrl: `/api/users/${u.uid}/avatar`
}));
return json(result);
}
export async function POST(event: RequestEvent) {
const formData = await event.request.formData();
const uid = formData.get('uid');
const username = formData.get('username')?.toString();
const password = formData.get('password')?.toString();
const home = Number(formData.get('home'));
const gid = Number(formData.get('gid'));
const accessible = Boolean(formData.get('accessible'));
const avatarFile = formData.get('avatar') as File | null;
if (!username || !password || !home || !gid || accessible === undefined) {
return new Response('Missing fields', { status: 400 });
}
let avatarBuffer: Buffer | null = null;
if (avatarFile && avatarFile.size > 0) {
avatarBuffer = Buffer.from(await avatarFile.arrayBuffer());
}
if (uid) {
// Update existing user
await db
.update(users)
.set({
username,
password,
home,
gid,
...(avatarBuffer && { avatar: avatarBuffer })
})
.where(eq(users.uid, Number(uid)));
} else {
// Create new user
await db.insert(users).values({
gid,
username,
password,
home,
accessible,
face: avatarBuffer
});
}
const targetUid = uid
? Number(uid)
: (
await db
.select({ uid: users.uid })
.from(users)
.where(eq(users.username, username!))
.limit(1)
)[0]?.uid;
if (!targetUid) {
return new Response('Failed to retrieve user after save', { status: 500 });
}
return new Response(JSON.stringify({ targetUid, success: true }), {
headers: { 'Content-Type': 'application/json' }
});
}
+37
View File
@@ -0,0 +1,37 @@
import { db } from '$lib/server/db';
import { users } from '$lib/server/db/schema';
import type { RequestEvent } from '@sveltejs/kit';
import { eq } from 'drizzle-orm';
export async function GET(event: RequestEvent): Promise<Response> {
const row = await db
.select({
uid: users.uid,
username: users.username,
password: users.password,
home: users.home,
gid: users.gid,
accessible: users.accessible
})
.from(users)
.where(eq(users.uid, Number(event.params.uid)))
.limit(1);
if (!row.length) {
return new Response(`User not found`, { status: 404 });
}
const user = row[0];
return new Response(
JSON.stringify({
...user,
avatarUrl: `/api/users/${user.uid}/avatar`
}),
{
headers: {
'Content-Type': 'application/json'
}
}
);
}
@@ -0,0 +1,26 @@
// src/routes/api/users/[uid]/avatar/+server.ts
import { db } from '$lib/server/db';
import { users } from '$lib/server/db/schema';
import type { RequestEvent } from '@sveltejs/kit';
import { eq } from 'drizzle-orm';
export async function GET(event: RequestEvent) {
const row = await db
.select({ avatar: users.face })
.from(users)
.where(eq(users.uid, Number(event.params.uid)))
.limit(1);
if (!row.length || !row[0].avatar) {
return new Response('Not found', { status: 404 });
}
const buffer = row[0].avatar;
return new Response(new Uint8Array(buffer), {
headers: {
'Content-Type': 'image/png',
'Cache-Control': 'public, max-age=3600'
}
});
}
View File
Executable → Regular
View File
Executable → Regular
+43 -22
View File
@@ -1,50 +1,71 @@
<script lang="ts">
import '../../app.css';
import { page } from '$app/state';
import favicon from '$lib/assets/favicon.svg';
import { getContext, setContext, type Snippet } from 'svelte';
import { BookA, ChartLine, ChartNoAxesColumn, Construction, FolderArchive, Plus } from '@lucide/svelte';
import { fetchAllData } from '$lib/stores/panel-state.svelte';
import { FileSystem } from '$lib/termos/filesystem/filesystem';
import {
BookA,
ChartLine,
ChartNoAxesColumn,
FolderArchive,
Plus,
Settings2,
UserRoundCog
} from '@lucide/svelte';
import { onMount, type Snippet } from 'svelte';
import '../../app.css';
import SidebarButton from '../../modules/panel/SidebarButton.svelte';
let { children, data}: { children: Snippet, data: any } = $props();
import ToastsModule from '../../modules/ToastsModule.svelte';
import { capitalize } from '../admin/util';
let { children, data }: { children: Snippet; data: any } = $props();
// Get last word of pathname (full url) filter if no empty array indexes exist and capitalize it
let site: string = $derived(capitalize(page.url.pathname.split('/').filter(Boolean).pop() ?? ''));
onMount(async () => {
await FileSystem.init();
await fetchAllData();
});
</script>
<svelte:head>
<link rel="icon" href={favicon} />
</svelte:head>
<div class="flex h-dvh w-full flex-row text-text-dark light:text-text-light">
<div class="flex h-full w-fit flex-col items-center bg-bg-dark light:bg-bg-light">
<ToastsModule></ToastsModule>
<div class="flex h-dvh w-full flex-row text-text-primary">
<div class="flex h-full w-fit flex-col items-center bg-surface-1">
<img class="m-3 mb-8" alt="Logo" src={favicon} height="32" width="32" />
<form class="flex h-full w-fit flex-col items-center gap-3">
<label
class="m-0 mb-4 flex size-12 items-center justify-center rounded-xl bg-bg-lighter-dark shadow-subtle hover:text-primary-hover-dark has-checked:text-primary-dark has-checked:hover:text-primary-hover-dark light:bg-bg-light-light light:hover:text-primary-hover-light light:has-checked:text-primary-light light:has-checked:hover:text-primary-hover-light"
class="m-0 mb-4 flex size-12 items-center justify-center rounded-xl bg-surface-2 shadow-subtle duration-100 transition-standard hover:text-primary has-checked:text-primary has-checked:hover:text-primary-variant has-active:button-click"
>
<input name="langs" type="radio" class="hidden" id="pl" autocomplete="off" />
<Plus strokeWidth={1} />
<Plus strokeWidth={1.25} />
</label>
<SidebarButton checked path="/panel/projects">
<FolderArchive strokeWidth={1} />
<!-- prettier-ignore -->
<SidebarButton /*checked*/ path="/panel/projects">
<FolderArchive strokeWidth={1.25} />
</SidebarButton>
<SidebarButton path="/panel/users">
<UserRoundCog strokeWidth={1.25} />
</SidebarButton>
<SidebarButton path="/panel/langs">
<BookA strokeWidth={1} />
<BookA strokeWidth={1.25} />
</SidebarButton>
<SidebarButton path="/panel/metrics">
<ChartLine strokeWidth={1} />
<ChartLine strokeWidth={1.25} />
</SidebarButton>
<SidebarButton path="/panel/stats">
<ChartNoAxesColumn strokeWidth={1} />
<ChartNoAxesColumn strokeWidth={1.25} />
</SidebarButton>
<SidebarButton path="/panel/global">
<Settings2 strokeWidth={1.25} />
</SidebarButton>
</form>
</div>
<div class="flex w-full grow">
<div class=" m-8 w-full">
<h2 class=" m-8 ml-0 font-primary text-3xl font-black text-primary">{site}</h2>
{@render children()}
</div>
</div>
<style>
main {
transition:
--dots-bg-2 0.2s ease-in,
--dots-bg-1 0.2s ease-in;
}
</style>
Executable → Regular
View File
+17
View File
@@ -0,0 +1,17 @@
import { db } from '$lib/server/db';
import { locales } from '$lib/server/db/schema';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async () => {
return {
locales: await db
.select({
code: locales.code,
name: locales.name,
dictionary: locales.dictionary,
flag: locales.flag,
enabled: locales.enabled
})
.from(locales)
};
};
+15 -9
View File
@@ -1,19 +1,25 @@
<script lang="ts">
import LangModule from '../../../modules/panel/LangModule.svelte';
import plFlag from '$lib/assets/plFlag.svg';
import enFlag from '$lib/assets/enFlag.svg';
import deFlag from '$lib/assets/deFlag.svg';
import frFlag from '$lib/assets/frFlag.svg';
import jaFlag from '$lib/assets/jaFlag.svg';
let { data }: { data: any } = $props();
</script>
<div>
<form name="langs" class="m-10 flex flex-col gap-4">
<LangModule checked langName="Polish" icon={plFlag} />
<form name="locales" class="m-10 flex flex-col gap-4">
{#each data.locales as locale}
<LangModule checked={locale.enabled} langName={locale.name} icon={locale.flag} />
{/each}
<!-- <LangModule checked langName="Polish" icon={plFlag} />
<LangModule checked langName="English" icon={enFlag} />
<LangModule checked langName="German" icon={deFlag} />
<LangModule langName="Japanese" icon={jaFlag} />
<LangModule langName="French" icon={frFlag} />
<LangModule langName="French" icon={frFlag} /> -->
</form>
<div></div>
<div>
<form>
<input type="file" />
<input type="image" alt="NaN" />
<input type="text" />
</form>
</div>
</div>
View File
+17 -5
View File
@@ -1,10 +1,22 @@
import { db } from "$lib/server/db";
import { settings } from "$lib/server/db/schema";
import { eq } from "drizzle-orm";
import type { PageServerLoad } from "./$types";
import { db } from '$lib/server/db';
import { config, projects } from '$lib/server/db/schema';
import { eq } from 'drizzle-orm';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async () => {
return {
settings: await db.select({setting: settings.state}).from(settings).where(eq(settings.var, 'maintenance')).limit(1)
settings: await db
.select({ value: config.value })
.from(config)
.where(eq(config.key, 'maintenance'))
.limit(1),
projects: await db
.select({
id: projects.id,
name: projects.name,
data: projects.data,
enabled: projects.enabled
})
.from(projects)
};
};
+61 -16
View File
@@ -1,12 +1,20 @@
<script lang="ts">
import { Construction } from '@lucide/svelte';
import { Construction, Eye, EyeOff } from '@lucide/svelte';
import NodeModule from '../../../modules/panel/NodeModule.svelte';
import ProjectModule from '../../../modules/panel/ProjectModule.svelte';
import ToggleSwitchModule from '../../../modules/panel/ToggleSwitchModule.svelte';
import { setMaintenanceState } from '../settings.remote';
let { data }: { data: any } = $props();
let maintenance = $state(Boolean(data.settings[0].setting));
console.log(maintenance);
let showHidden = $state(false);
console.log(data.projects[0].name);
function testModule() {
console.log('it works!');
}
function handleToggle() {
console.log(maintenance);
@@ -15,22 +23,59 @@
let result = setMaintenanceState(Number(maintenance) as 1 | 0);
console.log(result);
}
function toggleHidden() {
showHidden = !showHidden;
}
</script>
<div class=" m-10">
<ProjectModule projectName="ProjectName" checked={false} />
</div>
<div class=" mt-4">
<div class=" flex items-start">
<ToggleSwitchModule
callback={async () => await setMaintenanceState(Number(!maintenance))}
id="maintenence"
sync={maintenance}
>
{#snippet icon()}
<Construction strokeWidth={1} />
<label
for='maintenence'
class="relative m-2 ml-auto block h-5 w-10 cursor-pointer rounded-full bg-bg-lighter-dark shadow-subtle"
>
<input type="checkbox" checked={maintenance} onclick={async () => await setMaintenanceState(Number(!maintenance))} id='maintenence' class=" peer sr-only" />
<span
class=" absolute top-0.5 left-0.5 h-4/5 w-2/5 rounded-full bg-bg-dark peer-checked:left-5.5 peer-checked:bg-primary-dark"
>
</span>
{/snippet}
</ToggleSwitchModule>
</div>
<div
class=" grid-cols-[1.5fr, 1fr] grid w-full"
style="grid-template-areas:
'a b'; "
>
<div class=" m-10">
{#each data.projects as project}
<ProjectModule projectName={project.name} checked={project.enabled} />
{/each}
</div>
<div class="m-8 flex w-xl flex-col justify-self-end">
<div>
<button title="ButtonShowHidden" onclick={toggleHidden}>
{#if !showHidden}
<EyeOff stroke-width={1} class="text-text-muted-dark" />
{:else}
<Eye stroke-width={1} />
{/if}
</button>
</div>
<div class=" flex flex-col gap-1">
<form>
{#each data.nodes as node}
{#if showHidden}
<label>
<NodeModule nodeName={node.name} nodeType={node.type} isProject={false} />
</label>
{/if}
{#if !node.name.startsWith('.') && !showHidden}
<label>
<NodeModule nodeName={node.name} nodeType={node.type} isProject={false} />
</label>
{/if}
{/each}
</form>
</div>
</div>
</div>
+6 -8
View File
@@ -1,11 +1,9 @@
import { query } from "$app/server";
import { db } from "$lib/server/db";
import { settings } from "$lib/server/db/schema";
import { eq } from "drizzle-orm";
import z from "zod";
import { query } from '$app/server';
import { db } from '$lib/server/db';
import { settings } from '$lib/server/db/schema';
import { eq } from 'drizzle-orm';
import z from 'zod';
export const setMaintenanceState = query(z.number(), async (state) => {
await db.update(settings)
.set({ state })
.where(eq(settings.var, 'maintenance'));
await db.update(settings).set({ state }).where(eq(settings.var, 'maintenance'));
});
View File

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