Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
931d248e4c | ||
|
|
b9922b3bdc | ||
|
|
4a1ddd0f98 | ||
|
|
8cb42f07a2 | ||
|
|
8682de7d17 | ||
|
|
50872d8951 | ||
|
|
68458be71f |
@@ -30,8 +30,8 @@
|
|||||||
"@tailwindcss/vite": "^4.1.16",
|
"@tailwindcss/vite": "^4.1.16",
|
||||||
"@types/node": "^24",
|
"@types/node": "^24",
|
||||||
"@vitest/browser": "^3.2.4",
|
"@vitest/browser": "^3.2.4",
|
||||||
"drizzle-kit": "^0.31.8",
|
"drizzle-kit": "^0.18.1",
|
||||||
"drizzle-orm": "^0.45.1",
|
"drizzle-orm": "^0.45.2",
|
||||||
"eslint": "^9.36.0",
|
"eslint": "^9.36.0",
|
||||||
"eslint-config-prettier": "^10.1.8",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"eslint-plugin-svelte": "^3.12.4",
|
"eslint-plugin-svelte": "^3.12.4",
|
||||||
@@ -52,6 +52,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@lucide/svelte": "^0.548.0",
|
"@lucide/svelte": "^0.548.0",
|
||||||
|
"animejs": "^4.5.0",
|
||||||
"gl-matrix": "^3.4.4",
|
"gl-matrix": "^3.4.4",
|
||||||
"zod": "^4.3.6"
|
"zod": "^4.3.6"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,18 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<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 charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
%sveltekit.head%
|
%sveltekit.head%
|
||||||
|
|||||||
|
After Width: | Height: | Size: 158 B |
|
After Width: | Height: | Size: 158 B |
|
After Width: | Height: | Size: 158 B |
|
After Width: | Height: | Size: 205 B |
|
After Width: | Height: | Size: 597 B |
|
After Width: | Height: | Size: 560 B |
|
After Width: | Height: | Size: 615 B |
|
After Width: | Height: | Size: 597 B |
|
After Width: | Height: | Size: 628 B |
|
After Width: | Height: | Size: 585 B |
|
After Width: | Height: | Size: 604 B |
|
After Width: | Height: | Size: 601 B |
|
After Width: | Height: | Size: 632 B |
|
After Width: | Height: | Size: 612 B |
|
After Width: | Height: | Size: 467 B |
|
After Width: | Height: | Size: 471 B |
|
After Width: | Height: | Size: 471 B |
|
After Width: | Height: | Size: 476 B |
|
After Width: | Height: | Size: 468 B |
|
After Width: | Height: | Size: 459 B |
|
After Width: | Height: | Size: 472 B |
|
After Width: | Height: | Size: 628 B |
|
After Width: | Height: | Size: 649 B |
|
After Width: | Height: | Size: 638 B |
|
After Width: | Height: | Size: 656 B |
|
After Width: | Height: | Size: 648 B |
|
After Width: | Height: | Size: 640 B |
|
After Width: | Height: | Size: 629 B |
|
After Width: | Height: | Size: 628 B |
|
After Width: | Height: | Size: 639 B |
|
After Width: | Height: | Size: 657 B |
|
After Width: | Height: | Size: 645 B |
|
After Width: | Height: | Size: 654 B |
|
Before Width: | Height: | Size: 668 B After Width: | Height: | Size: 668 B |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 695 B After Width: | Height: | Size: 695 B |
|
Before Width: | Height: | Size: 620 B After Width: | Height: | Size: 620 B |
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 506 B After Width: | Height: | Size: 506 B |
@@ -0,0 +1,573 @@
|
|||||||
|
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';
|
||||||
|
this.#node.classList.add('[Movable]');
|
||||||
|
|
||||||
|
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.setProperty('--x', this.state.x.toString());
|
||||||
|
this.#node.style.setProperty('--y', this.state.y.toString());
|
||||||
|
this.#node.style.setProperty('--w', this.state.width.toString());
|
||||||
|
this.#node.style.setProperty('--h', this.state.height.toString());
|
||||||
|
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 = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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';
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,10 +1,5 @@
|
|||||||
import { drizzle } from 'drizzle-orm/mysql2';
|
//if (!env.DATABASE_URL) throw new Error('DATABASE_URL is not set');
|
||||||
import mysql from 'mysql2/promise';
|
|
||||||
import * as schema from './schema';
|
|
||||||
import { env } from '$env/dynamic/private';
|
|
||||||
|
|
||||||
if (!env.DATABASE_URL) throw new Error('DATABASE_URL is not set');
|
//const client = mysql.createPool(env.DATABASE_URL);
|
||||||
|
|
||||||
const client = mysql.createPool(env.DATABASE_URL);
|
//export const db = drizzle(client, { schema, mode: 'default', logger: true });
|
||||||
|
|
||||||
export const db = drizzle(client, { schema, mode: 'default', logger: true });
|
|
||||||
|
|||||||
@@ -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', {
|
export const task = mysqlTable('task', {
|
||||||
id: serial('id').primaryKey(),
|
id: serial('id').primaryKey(),
|
||||||
@@ -6,10 +18,66 @@ export const task = mysqlTable('task', {
|
|||||||
priority: int('priority').notNull().default(1)
|
priority: int('priority').notNull().default(1)
|
||||||
});
|
});
|
||||||
|
|
||||||
export const settings = mysqlTable('settings', {
|
export const config = mysqlTable('config', {
|
||||||
var: text('var').notNull().unique(),
|
key: varchar('key', { length: 64 }).primaryKey(),
|
||||||
state: tinyint('state')
|
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;
|
||||||
|
|||||||
@@ -0,0 +1,382 @@
|
|||||||
|
|
||||||
|
// this file is generated — do not edit it
|
||||||
|
|
||||||
|
|
||||||
|
/// <reference types="@sveltejs/kit" />
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This module provides access to environment variables that are injected _statically_ into your bundle at build time and are limited to _private_ access.
|
||||||
|
*
|
||||||
|
* | | Runtime | Build time |
|
||||||
|
* | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
|
||||||
|
* | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) |
|
||||||
|
* | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) |
|
||||||
|
*
|
||||||
|
* Static environment variables are [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env` at build time and then statically injected into your bundle at build time, enabling optimisations like dead code elimination.
|
||||||
|
*
|
||||||
|
* **_Private_ access:**
|
||||||
|
*
|
||||||
|
* - This module cannot be imported into client-side code
|
||||||
|
* - This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://svelte.dev/docs/kit/configuration#env) (if configured)
|
||||||
|
*
|
||||||
|
* For example, given the following build time environment:
|
||||||
|
*
|
||||||
|
* ```env
|
||||||
|
* ENVIRONMENT=production
|
||||||
|
* PUBLIC_BASE_URL=http://site.com
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* With the default `publicPrefix` and `privatePrefix`:
|
||||||
|
*
|
||||||
|
* ```ts
|
||||||
|
* import { ENVIRONMENT, PUBLIC_BASE_URL } from '$env/static/private';
|
||||||
|
*
|
||||||
|
* console.log(ENVIRONMENT); // => "production"
|
||||||
|
* console.log(PUBLIC_BASE_URL); // => throws error during build
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* The above values will be the same _even if_ different values for `ENVIRONMENT` or `PUBLIC_BASE_URL` are set at runtime, as they are statically replaced in your code with their build time values.
|
||||||
|
*/
|
||||||
|
declare module '$env/static/private' {
|
||||||
|
export const APP2UNIT_SLICES: string;
|
||||||
|
export const CHROME_DESKTOP: string;
|
||||||
|
export const CLUTTER_BACKEND: string;
|
||||||
|
export const DBUS_SESSION_BUS_ADDRESS: string;
|
||||||
|
export const DEBUGINFOD_URLS: string;
|
||||||
|
export const DESKTOP_SESSION: string;
|
||||||
|
export const DISPLAY: string;
|
||||||
|
export const EDITOR: string;
|
||||||
|
export const ELECTRON_NO_ATTACH_CONSOLE: string;
|
||||||
|
export const ELECTRON_OZONE_PLATFORM_HINT: string;
|
||||||
|
export const FC_FONTATIONS: string;
|
||||||
|
export const GDK_BACKEND: string;
|
||||||
|
export const HL_INITIAL_WORKSPACE_TOKEN: string;
|
||||||
|
export const HOME: string;
|
||||||
|
export const HYPRLAND_CMD: string;
|
||||||
|
export const HYPRLAND_INSTANCE_SIGNATURE: string;
|
||||||
|
export const INVOCATION_ID: string;
|
||||||
|
export const JOURNAL_STREAM: string;
|
||||||
|
export const LANG: string;
|
||||||
|
export const LC_ADDRESS: string;
|
||||||
|
export const LC_IDENTIFICATION: string;
|
||||||
|
export const LC_MEASUREMENT: string;
|
||||||
|
export const LC_MONETARY: string;
|
||||||
|
export const LC_NAME: string;
|
||||||
|
export const LC_NUMERIC: string;
|
||||||
|
export const LC_PAPER: string;
|
||||||
|
export const LC_TELEPHONE: string;
|
||||||
|
export const LC_TIME: string;
|
||||||
|
export const LOGNAME: string;
|
||||||
|
export const MAIL: string;
|
||||||
|
export const MANAGERPID: string;
|
||||||
|
export const MANAGERPIDFDID: string;
|
||||||
|
export const MEMORY_PRESSURE_WATCH: string;
|
||||||
|
export const MEMORY_PRESSURE_WRITE: string;
|
||||||
|
export const MOTD_SHOWN: string;
|
||||||
|
export const MOZ_ENABLE_WAYLAND: string;
|
||||||
|
export const NOTIFY_SOCKET: string;
|
||||||
|
export const NO_AT_BRIDGE: string;
|
||||||
|
export const PATH: string;
|
||||||
|
export const PWD: string;
|
||||||
|
export const QS_ICON_THEME: string;
|
||||||
|
export const QT_AUTO_SCREEN_SCALE_FACTOR: string;
|
||||||
|
export const QT_QPA_PLATFORM: string;
|
||||||
|
export const QT_QPA_PLATFORMTHEME: string;
|
||||||
|
export const QT_WAYLAND_DISABLE_WINDOWDECORATION: string;
|
||||||
|
export const SDL_VIDEODRIVER: string;
|
||||||
|
export const SHELL: string;
|
||||||
|
export const SHLVL: string;
|
||||||
|
export const SYSTEMD_EXEC_PID: string;
|
||||||
|
export const USER: string;
|
||||||
|
export const UWSM_FINALIZE_VARNAMES: string;
|
||||||
|
export const UWSM_WAIT_VARNAMES: string;
|
||||||
|
export const VIRTUAL_ENV_DISABLE_PROMPT: string;
|
||||||
|
export const VSCODE_CLI: string;
|
||||||
|
export const VSCODE_CODE_CACHE_PATH: string;
|
||||||
|
export const VSCODE_CRASH_REPORTER_PROCESS_TYPE: string;
|
||||||
|
export const VSCODE_CWD: string;
|
||||||
|
export const VSCODE_ESM_ENTRYPOINT: string;
|
||||||
|
export const VSCODE_HANDLES_UNCAUGHT_ERRORS: string;
|
||||||
|
export const VSCODE_IPC_HOOK: string;
|
||||||
|
export const VSCODE_NLS_CONFIG: string;
|
||||||
|
export const VSCODE_PID: string;
|
||||||
|
export const VSSCRIPT_PATH: string;
|
||||||
|
export const WAYLAND_DISPLAY: string;
|
||||||
|
export const XCURSOR_SIZE: string;
|
||||||
|
export const XCURSOR_THEME: string;
|
||||||
|
export const XDG_BACKEND: string;
|
||||||
|
export const XDG_CACHE_HOME: string;
|
||||||
|
export const XDG_CONFIG_DIRS: string;
|
||||||
|
export const XDG_CONFIG_HOME: string;
|
||||||
|
export const XDG_CURRENT_DESKTOP: string;
|
||||||
|
export const XDG_DATA_DIRS: string;
|
||||||
|
export const XDG_DATA_HOME: string;
|
||||||
|
export const XDG_MENU_PREFIX: string;
|
||||||
|
export const XDG_RUNTIME_DIR: string;
|
||||||
|
export const XDG_SEAT: string;
|
||||||
|
export const XDG_SEAT_PATH: string;
|
||||||
|
export const XDG_SESSION_CLASS: string;
|
||||||
|
export const XDG_SESSION_DESKTOP: string;
|
||||||
|
export const XDG_SESSION_ID: string;
|
||||||
|
export const XDG_SESSION_PATH: string;
|
||||||
|
export const XDG_SESSION_TYPE: string;
|
||||||
|
export const XDG_STATE_HOME: string;
|
||||||
|
export const XDG_VTNR: string;
|
||||||
|
export const _: string;
|
||||||
|
export const _JAVA_AWT_WM_NONREPARENTING: string;
|
||||||
|
export const ELECTRON_RUN_AS_NODE: string;
|
||||||
|
export const VSCODE_L10N_BUNDLE_LOCATION: string;
|
||||||
|
export const VITEST_VSCODE_LOG: string;
|
||||||
|
export const VITEST_VSCODE: string;
|
||||||
|
export const TEST: string;
|
||||||
|
export const VITEST_WS_ADDRESS: string;
|
||||||
|
export const VITEST: string;
|
||||||
|
export const NODE_ENV: string;
|
||||||
|
export const FORCE_COLOR: string;
|
||||||
|
export const PROD: string;
|
||||||
|
export const DEV: string;
|
||||||
|
export const BASE_URL: string;
|
||||||
|
export const MODE: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This module provides access to environment variables that are injected _statically_ into your bundle at build time and are _publicly_ accessible.
|
||||||
|
*
|
||||||
|
* | | Runtime | Build time |
|
||||||
|
* | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
|
||||||
|
* | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) |
|
||||||
|
* | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) |
|
||||||
|
*
|
||||||
|
* Static environment variables are [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env` at build time and then statically injected into your bundle at build time, enabling optimisations like dead code elimination.
|
||||||
|
*
|
||||||
|
* **_Public_ access:**
|
||||||
|
*
|
||||||
|
* - This module _can_ be imported into client-side code
|
||||||
|
* - **Only** variables that begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) (which defaults to `PUBLIC_`) are included
|
||||||
|
*
|
||||||
|
* For example, given the following build time environment:
|
||||||
|
*
|
||||||
|
* ```env
|
||||||
|
* ENVIRONMENT=production
|
||||||
|
* PUBLIC_BASE_URL=http://site.com
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* With the default `publicPrefix` and `privatePrefix`:
|
||||||
|
*
|
||||||
|
* ```ts
|
||||||
|
* import { ENVIRONMENT, PUBLIC_BASE_URL } from '$env/static/public';
|
||||||
|
*
|
||||||
|
* console.log(ENVIRONMENT); // => throws error during build
|
||||||
|
* console.log(PUBLIC_BASE_URL); // => "http://site.com"
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* The above values will be the same _even if_ different values for `ENVIRONMENT` or `PUBLIC_BASE_URL` are set at runtime, as they are statically replaced in your code with their build time values.
|
||||||
|
*/
|
||||||
|
declare module '$env/static/public' {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This module provides access to environment variables set _dynamically_ at runtime and that are limited to _private_ access.
|
||||||
|
*
|
||||||
|
* | | Runtime | Build time |
|
||||||
|
* | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
|
||||||
|
* | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) |
|
||||||
|
* | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) |
|
||||||
|
*
|
||||||
|
* Dynamic environment variables are defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](https://svelte.dev/docs/kit/cli)), this is equivalent to `process.env`.
|
||||||
|
*
|
||||||
|
* **_Private_ access:**
|
||||||
|
*
|
||||||
|
* - This module cannot be imported into client-side code
|
||||||
|
* - This module includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://svelte.dev/docs/kit/configuration#env) (if configured)
|
||||||
|
*
|
||||||
|
* > [!NOTE] In `dev`, `$env/dynamic` includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter.
|
||||||
|
*
|
||||||
|
* > [!NOTE] To get correct types, environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed:
|
||||||
|
* >
|
||||||
|
* > ```env
|
||||||
|
* > MY_FEATURE_FLAG=
|
||||||
|
* > ```
|
||||||
|
* >
|
||||||
|
* > You can override `.env` values from the command line like so:
|
||||||
|
* >
|
||||||
|
* > ```sh
|
||||||
|
* > MY_FEATURE_FLAG="enabled" npm run dev
|
||||||
|
* > ```
|
||||||
|
*
|
||||||
|
* For example, given the following runtime environment:
|
||||||
|
*
|
||||||
|
* ```env
|
||||||
|
* ENVIRONMENT=production
|
||||||
|
* PUBLIC_BASE_URL=http://site.com
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* With the default `publicPrefix` and `privatePrefix`:
|
||||||
|
*
|
||||||
|
* ```ts
|
||||||
|
* import { env } from '$env/dynamic/private';
|
||||||
|
*
|
||||||
|
* console.log(env.ENVIRONMENT); // => "production"
|
||||||
|
* console.log(env.PUBLIC_BASE_URL); // => undefined
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
declare module '$env/dynamic/private' {
|
||||||
|
export const env: {
|
||||||
|
APP2UNIT_SLICES: string;
|
||||||
|
CHROME_DESKTOP: string;
|
||||||
|
CLUTTER_BACKEND: string;
|
||||||
|
DBUS_SESSION_BUS_ADDRESS: string;
|
||||||
|
DEBUGINFOD_URLS: string;
|
||||||
|
DESKTOP_SESSION: string;
|
||||||
|
DISPLAY: string;
|
||||||
|
EDITOR: string;
|
||||||
|
ELECTRON_NO_ATTACH_CONSOLE: string;
|
||||||
|
ELECTRON_OZONE_PLATFORM_HINT: string;
|
||||||
|
FC_FONTATIONS: string;
|
||||||
|
GDK_BACKEND: string;
|
||||||
|
HL_INITIAL_WORKSPACE_TOKEN: string;
|
||||||
|
HOME: string;
|
||||||
|
HYPRLAND_CMD: string;
|
||||||
|
HYPRLAND_INSTANCE_SIGNATURE: string;
|
||||||
|
INVOCATION_ID: string;
|
||||||
|
JOURNAL_STREAM: string;
|
||||||
|
LANG: string;
|
||||||
|
LC_ADDRESS: string;
|
||||||
|
LC_IDENTIFICATION: string;
|
||||||
|
LC_MEASUREMENT: string;
|
||||||
|
LC_MONETARY: string;
|
||||||
|
LC_NAME: string;
|
||||||
|
LC_NUMERIC: string;
|
||||||
|
LC_PAPER: string;
|
||||||
|
LC_TELEPHONE: string;
|
||||||
|
LC_TIME: string;
|
||||||
|
LOGNAME: string;
|
||||||
|
MAIL: string;
|
||||||
|
MANAGERPID: string;
|
||||||
|
MANAGERPIDFDID: string;
|
||||||
|
MEMORY_PRESSURE_WATCH: string;
|
||||||
|
MEMORY_PRESSURE_WRITE: string;
|
||||||
|
MOTD_SHOWN: string;
|
||||||
|
MOZ_ENABLE_WAYLAND: string;
|
||||||
|
NOTIFY_SOCKET: string;
|
||||||
|
NO_AT_BRIDGE: string;
|
||||||
|
PATH: string;
|
||||||
|
PWD: string;
|
||||||
|
QS_ICON_THEME: string;
|
||||||
|
QT_AUTO_SCREEN_SCALE_FACTOR: string;
|
||||||
|
QT_QPA_PLATFORM: string;
|
||||||
|
QT_QPA_PLATFORMTHEME: string;
|
||||||
|
QT_WAYLAND_DISABLE_WINDOWDECORATION: string;
|
||||||
|
SDL_VIDEODRIVER: string;
|
||||||
|
SHELL: string;
|
||||||
|
SHLVL: string;
|
||||||
|
SYSTEMD_EXEC_PID: string;
|
||||||
|
USER: string;
|
||||||
|
UWSM_FINALIZE_VARNAMES: string;
|
||||||
|
UWSM_WAIT_VARNAMES: string;
|
||||||
|
VIRTUAL_ENV_DISABLE_PROMPT: string;
|
||||||
|
VSCODE_CLI: string;
|
||||||
|
VSCODE_CODE_CACHE_PATH: string;
|
||||||
|
VSCODE_CRASH_REPORTER_PROCESS_TYPE: string;
|
||||||
|
VSCODE_CWD: string;
|
||||||
|
VSCODE_ESM_ENTRYPOINT: string;
|
||||||
|
VSCODE_HANDLES_UNCAUGHT_ERRORS: string;
|
||||||
|
VSCODE_IPC_HOOK: string;
|
||||||
|
VSCODE_NLS_CONFIG: string;
|
||||||
|
VSCODE_PID: string;
|
||||||
|
VSSCRIPT_PATH: string;
|
||||||
|
WAYLAND_DISPLAY: string;
|
||||||
|
XCURSOR_SIZE: string;
|
||||||
|
XCURSOR_THEME: string;
|
||||||
|
XDG_BACKEND: string;
|
||||||
|
XDG_CACHE_HOME: string;
|
||||||
|
XDG_CONFIG_DIRS: string;
|
||||||
|
XDG_CONFIG_HOME: string;
|
||||||
|
XDG_CURRENT_DESKTOP: string;
|
||||||
|
XDG_DATA_DIRS: string;
|
||||||
|
XDG_DATA_HOME: string;
|
||||||
|
XDG_MENU_PREFIX: string;
|
||||||
|
XDG_RUNTIME_DIR: string;
|
||||||
|
XDG_SEAT: string;
|
||||||
|
XDG_SEAT_PATH: string;
|
||||||
|
XDG_SESSION_CLASS: string;
|
||||||
|
XDG_SESSION_DESKTOP: string;
|
||||||
|
XDG_SESSION_ID: string;
|
||||||
|
XDG_SESSION_PATH: string;
|
||||||
|
XDG_SESSION_TYPE: string;
|
||||||
|
XDG_STATE_HOME: string;
|
||||||
|
XDG_VTNR: string;
|
||||||
|
_: string;
|
||||||
|
_JAVA_AWT_WM_NONREPARENTING: string;
|
||||||
|
ELECTRON_RUN_AS_NODE: string;
|
||||||
|
VSCODE_L10N_BUNDLE_LOCATION: string;
|
||||||
|
VITEST_VSCODE_LOG: string;
|
||||||
|
VITEST_VSCODE: string;
|
||||||
|
TEST: string;
|
||||||
|
VITEST_WS_ADDRESS: string;
|
||||||
|
VITEST: string;
|
||||||
|
NODE_ENV: string;
|
||||||
|
FORCE_COLOR: string;
|
||||||
|
PROD: string;
|
||||||
|
DEV: string;
|
||||||
|
BASE_URL: string;
|
||||||
|
MODE: string;
|
||||||
|
[key: `PUBLIC_${string}`]: undefined;
|
||||||
|
[key: `${string}`]: string | undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This module provides access to environment variables set _dynamically_ at runtime and that are _publicly_ accessible.
|
||||||
|
*
|
||||||
|
* | | Runtime | Build time |
|
||||||
|
* | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
|
||||||
|
* | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) |
|
||||||
|
* | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) |
|
||||||
|
*
|
||||||
|
* Dynamic environment variables are defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](https://svelte.dev/docs/kit/cli)), this is equivalent to `process.env`.
|
||||||
|
*
|
||||||
|
* **_Public_ access:**
|
||||||
|
*
|
||||||
|
* - This module _can_ be imported into client-side code
|
||||||
|
* - **Only** variables that begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) (which defaults to `PUBLIC_`) are included
|
||||||
|
*
|
||||||
|
* > [!NOTE] In `dev`, `$env/dynamic` includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter.
|
||||||
|
*
|
||||||
|
* > [!NOTE] To get correct types, environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed:
|
||||||
|
* >
|
||||||
|
* > ```env
|
||||||
|
* > MY_FEATURE_FLAG=
|
||||||
|
* > ```
|
||||||
|
* >
|
||||||
|
* > You can override `.env` values from the command line like so:
|
||||||
|
* >
|
||||||
|
* > ```sh
|
||||||
|
* > MY_FEATURE_FLAG="enabled" npm run dev
|
||||||
|
* > ```
|
||||||
|
*
|
||||||
|
* For example, given the following runtime environment:
|
||||||
|
*
|
||||||
|
* ```env
|
||||||
|
* ENVIRONMENT=production
|
||||||
|
* PUBLIC_BASE_URL=http://example.com
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* With the default `publicPrefix` and `privatePrefix`:
|
||||||
|
*
|
||||||
|
* ```ts
|
||||||
|
* import { env } from '$env/dynamic/public';
|
||||||
|
* console.log(env.ENVIRONMENT); // => undefined, not public
|
||||||
|
* console.log(env.PUBLIC_BASE_URL); // => "http://example.com"
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
declare module '$env/dynamic/public' {
|
||||||
|
export const env: {
|
||||||
|
[key: `PUBLIC_${string}`]: string | undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
export { matchers } from './matchers.js';
|
||||||
|
|
||||||
|
export const nodes = [
|
||||||
|
() => import('./nodes/0'),
|
||||||
|
() => import('./nodes/1')
|
||||||
|
];
|
||||||
|
|
||||||
|
export const server_loads = [];
|
||||||
|
|
||||||
|
export const dictionary = {
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
export const hooks = {
|
||||||
|
handleError: (({ error }) => { console.error(error) }),
|
||||||
|
|
||||||
|
reroute: (() => {}),
|
||||||
|
transport: {}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const decoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.decode]));
|
||||||
|
export const encoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.encode]));
|
||||||
|
|
||||||
|
export const hash = false;
|
||||||
|
|
||||||
|
export const decode = (type, value) => decoders[type](value);
|
||||||
|
|
||||||
|
export { default as root } from '../root.js';
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export const matchers = {};
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export { default as component } from "../../../../../../../node_modules/@sveltejs/kit/src/runtime/components/svelte-5/layout.svelte";
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export { default as component } from "../../../../../../../node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte";
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"paths": {
|
||||||
|
"$app/types": [
|
||||||
|
"./types/index.d.ts"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"rootDirs": [
|
||||||
|
"..",
|
||||||
|
"./types"
|
||||||
|
],
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"lib": [
|
||||||
|
"esnext",
|
||||||
|
"DOM",
|
||||||
|
"DOM.Iterable"
|
||||||
|
],
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"module": "esnext",
|
||||||
|
"noEmit": true,
|
||||||
|
"target": "esnext",
|
||||||
|
"types": [
|
||||||
|
"node"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"ambient.d.ts",
|
||||||
|
"non-ambient.d.ts",
|
||||||
|
"./types/**/$types.d.ts",
|
||||||
|
"../vite.config.js",
|
||||||
|
"../vite.config.ts",
|
||||||
|
"../src/**/*.js",
|
||||||
|
"../src/**/*.ts",
|
||||||
|
"../src/**/*.svelte",
|
||||||
|
"../test/**/*.js",
|
||||||
|
"../test/**/*.ts",
|
||||||
|
"../test/**/*.svelte",
|
||||||
|
"../tests/**/*.js",
|
||||||
|
"../tests/**/*.ts",
|
||||||
|
"../tests/**/*.svelte"
|
||||||
|
],
|
||||||
|
"exclude": [
|
||||||
|
"../node_modules/**",
|
||||||
|
"../src/service-worker.js",
|
||||||
|
"../src/service-worker/**/*.js",
|
||||||
|
"../src/service-worker.ts",
|
||||||
|
"../src/service-worker/**/*.ts",
|
||||||
|
"../src/service-worker.d.ts",
|
||||||
|
"../src/service-worker/**/*.d.ts"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,478 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import {
|
||||||
|
CharacterRenderer,
|
||||||
|
INTERACTION,
|
||||||
|
ImageCache,
|
||||||
|
KeyboardInput,
|
||||||
|
NeedsSimulator,
|
||||||
|
Physics,
|
||||||
|
PointerController,
|
||||||
|
SoundPlayer,
|
||||||
|
StateClock,
|
||||||
|
collectStateUrls,
|
||||||
|
loadSoundPacks,
|
||||||
|
resolveStateName,
|
||||||
|
type BubblePack,
|
||||||
|
type ChatterConfig,
|
||||||
|
type InteractionConfig,
|
||||||
|
type StatePack
|
||||||
|
} from './';
|
||||||
|
import { CHATTER } from './chatter';
|
||||||
|
import { NEEDS, type ChatterHooks, type NeedDef } from './needs';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
states: Record<string, StatePack>;
|
||||||
|
bubblePacks?: Record<string, BubblePack>;
|
||||||
|
needsConfig?: NeedDef[];
|
||||||
|
chatter?: ChatterConfig | null;
|
||||||
|
interactions?: InteractionConfig;
|
||||||
|
scale?: number;
|
||||||
|
maxSpeed?: number;
|
||||||
|
idleThreshold?: number;
|
||||||
|
runThreshold?: number;
|
||||||
|
acceleration?: number;
|
||||||
|
friction?: number;
|
||||||
|
startAt?: number;
|
||||||
|
floorHeight?: number;
|
||||||
|
floorColor?: string;
|
||||||
|
reflectionOpacity?: number;
|
||||||
|
reflectionFade?: number;
|
||||||
|
reflectionTint?: string;
|
||||||
|
wrapEdges?: boolean;
|
||||||
|
jumpVelocity?: number;
|
||||||
|
gravity?: number;
|
||||||
|
showShadow?: boolean;
|
||||||
|
bubbleAnchorX?: number;
|
||||||
|
bubbleAnchorY?: number;
|
||||||
|
muted?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
states,
|
||||||
|
bubblePacks,
|
||||||
|
needsConfig = NEEDS,
|
||||||
|
chatter = CHATTER,
|
||||||
|
interactions = INTERACTION,
|
||||||
|
scale = 4,
|
||||||
|
maxSpeed = 280,
|
||||||
|
idleThreshold = 10,
|
||||||
|
runThreshold = 190,
|
||||||
|
acceleration = 1600,
|
||||||
|
friction = 2400,
|
||||||
|
startAt = 0.5,
|
||||||
|
floorHeight = 90,
|
||||||
|
floorColor = '#242830',
|
||||||
|
reflectionOpacity = 0.45,
|
||||||
|
reflectionFade = 0.9,
|
||||||
|
reflectionTint = 'rgba(120, 160, 200, 0.3)',
|
||||||
|
wrapEdges = true,
|
||||||
|
jumpVelocity = 620,
|
||||||
|
gravity = 2400,
|
||||||
|
showShadow = true,
|
||||||
|
bubbleAnchorX = 0,
|
||||||
|
bubbleAnchorY = 4,
|
||||||
|
muted = false
|
||||||
|
}: Props = $props();
|
||||||
|
|
||||||
|
/* ---------- DOM ---------- */
|
||||||
|
let canvas = $state<HTMLCanvasElement>();
|
||||||
|
let ctx: CanvasRenderingContext2D | null = null;
|
||||||
|
let dpr = 1;
|
||||||
|
let viewW = 0;
|
||||||
|
let viewH = 0;
|
||||||
|
|
||||||
|
/* ---------- Subsystems ---------- */
|
||||||
|
const cache = new ImageCache();
|
||||||
|
const physics = new Physics();
|
||||||
|
const clock = new StateClock();
|
||||||
|
const input = new KeyboardInput();
|
||||||
|
const needs = new NeedsSimulator();
|
||||||
|
const renderer = new CharacterRenderer();
|
||||||
|
const pointer = new PointerController(INTERACTION);
|
||||||
|
|
||||||
|
let soundPlayer: SoundPlayer | null = null;
|
||||||
|
let audioCtx: AudioContext | null = null;
|
||||||
|
|
||||||
|
let ready = false;
|
||||||
|
let placed = false;
|
||||||
|
let heldAnchorSet = false;
|
||||||
|
let loadError = $state<string | null>(null);
|
||||||
|
|
||||||
|
// Last drawn body size — used for pointer hit-testing on the next frame.
|
||||||
|
let lastBodyW = 0;
|
||||||
|
let lastBodyH = 0;
|
||||||
|
|
||||||
|
/* ---------- Asset loading ---------- */
|
||||||
|
const urlKey = $derived(
|
||||||
|
[
|
||||||
|
...collectStateUrls(states),
|
||||||
|
...Object.values(bubblePacks ?? {}).flatMap((p) => p.frames)
|
||||||
|
].join('\n')
|
||||||
|
);
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
const key = urlKey;
|
||||||
|
ready = false;
|
||||||
|
loadError = null;
|
||||||
|
if (!key) {
|
||||||
|
loadError = 'No state frames found. Check $lib/assets/character/states/.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let cancelled = false;
|
||||||
|
|
||||||
|
cache
|
||||||
|
.load(key.split('\n'))
|
||||||
|
.then(() => {
|
||||||
|
if (cancelled) return;
|
||||||
|
rebound();
|
||||||
|
ready = true;
|
||||||
|
})
|
||||||
|
.catch((err: Error) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
loadError = err.message;
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ---------- Bounds ---------- */
|
||||||
|
function bounds() {
|
||||||
|
const { w } = cache.largestSize(collectStateUrls(states));
|
||||||
|
return { viewW, viewH, floorHeight, spriteW: w, scale };
|
||||||
|
}
|
||||||
|
|
||||||
|
function resize() {
|
||||||
|
if (!canvas || !ctx) return;
|
||||||
|
dpr = Math.min(window.devicePixelRatio || 1, 3);
|
||||||
|
const rect = canvas.getBoundingClientRect();
|
||||||
|
viewW = rect.width;
|
||||||
|
viewH = rect.height;
|
||||||
|
canvas.width = Math.max(1, Math.round(rect.width * dpr));
|
||||||
|
canvas.height = Math.max(1, Math.round(rect.height * dpr));
|
||||||
|
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||||
|
ctx.imageSmoothingEnabled = false;
|
||||||
|
if (!placed && viewW > 0) {
|
||||||
|
placed = true;
|
||||||
|
physics.place(viewW, startAt);
|
||||||
|
}
|
||||||
|
rebound();
|
||||||
|
}
|
||||||
|
|
||||||
|
function rebound() {
|
||||||
|
physics.rebound(
|
||||||
|
{ maxSpeed, acceleration, friction, jumpVelocity, gravity, wrapEdges },
|
||||||
|
bounds()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Audio ---------- */
|
||||||
|
const GESTURES = ['pointerdown', 'keydown', 'touchstart'] as const;
|
||||||
|
|
||||||
|
function unlockAudio() {
|
||||||
|
if (audioCtx) return;
|
||||||
|
try {
|
||||||
|
const Ctor = window.AudioContext ?? (window as any).webkitAudioContext;
|
||||||
|
if (!Ctor) return;
|
||||||
|
audioCtx = new Ctor();
|
||||||
|
void audioCtx.resume();
|
||||||
|
void loadSoundPacks(audioCtx).then((packs) => {
|
||||||
|
if (!audioCtx) return;
|
||||||
|
soundPlayer = new SoundPlayer(audioCtx, packs);
|
||||||
|
soundPlayer.setMuted(muted);
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[character] audio unavailable', err);
|
||||||
|
}
|
||||||
|
for (const g of GESTURES) window.removeEventListener(g, unlockAudio);
|
||||||
|
}
|
||||||
|
|
||||||
|
function installAudioUnlocker() {
|
||||||
|
for (const g of GESTURES) window.addEventListener(g, unlockAudio, { passive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
soundPlayer?.setMuted(muted);
|
||||||
|
});
|
||||||
|
|
||||||
|
function playSound(name: string, volume: number) {
|
||||||
|
soundPlayer?.play(name, volume);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- State resolution ---------- */
|
||||||
|
function activeStateName(): string {
|
||||||
|
const needAction =
|
||||||
|
needs.active?.actionState && needs.active.elapsed >= needs.active.actionStart
|
||||||
|
? needs.active.actionState.name
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return resolveStateName(
|
||||||
|
{
|
||||||
|
interaction: pointer.state,
|
||||||
|
grounded: physics.grounded,
|
||||||
|
speed: Math.abs(physics.vx),
|
||||||
|
needAction
|
||||||
|
},
|
||||||
|
{ idleThreshold, runThreshold },
|
||||||
|
states
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sideFor(pack: StatePack) {
|
||||||
|
return physics.facing === 'left' ? pack.left : pack.right;
|
||||||
|
}
|
||||||
|
|
||||||
|
function bodyFor(name: string): HTMLImageElement | null {
|
||||||
|
const pack = states[name];
|
||||||
|
if (!pack) return null;
|
||||||
|
const side = sideFor(pack);
|
||||||
|
if (!side.frames.length) return null;
|
||||||
|
const i = clock.frameIndex(pack, side);
|
||||||
|
return cache.get(side.frames[i]) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Bubble ---------- */
|
||||||
|
function currentBubble(): { img: HTMLImageElement; index: number } | null {
|
||||||
|
if (pointer.state === 'held' || pointer.state === 'petted') return null;
|
||||||
|
const a = needs.active;
|
||||||
|
if (!a?.bubblePack || !a.bubblePack.frames.length) return null;
|
||||||
|
if (a.elapsed >= a.bubbleDuration) return null;
|
||||||
|
const index = Math.min(
|
||||||
|
Math.floor(a.elapsed * a.bubblePack.fps),
|
||||||
|
a.bubblePack.frames.length - 1
|
||||||
|
);
|
||||||
|
const img = cache.get(a.bubblePack.frames[index]);
|
||||||
|
return img ? { img, index } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function currentCharsShown(): number {
|
||||||
|
const a = needs.active;
|
||||||
|
if (!a?.text || !chatter) return Infinity;
|
||||||
|
const speed = chatter.typeSpeed ?? 0;
|
||||||
|
if (speed <= 0) return Infinity;
|
||||||
|
const pack = a.bubblePack;
|
||||||
|
const textStart = pack ? (chatter.textFrame ?? 0) / pack.fps : 0;
|
||||||
|
const typingElapsed = a.elapsed - textStart;
|
||||||
|
if (typingElapsed <= 0) return 0;
|
||||||
|
return Math.min(a.text.length, Math.floor(typingElapsed * speed));
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildChatterHooks(c: ChatterConfig): ChatterHooks {
|
||||||
|
return {
|
||||||
|
pack: c.pack,
|
||||||
|
interval: c.interval,
|
||||||
|
lines: c.lines,
|
||||||
|
typeSpeed: c.typeSpeed,
|
||||||
|
typeSound: c.typeSound,
|
||||||
|
typeSoundEvery: c.typeSoundEvery,
|
||||||
|
typeSoundVolume: c.typeSoundVolume,
|
||||||
|
bubbleDuration: (line: string, pack: BubblePack) => {
|
||||||
|
const animDur = pack.frames.length / pack.fps;
|
||||||
|
const textStart = (c.textFrame ?? 0) / pack.fps;
|
||||||
|
const speed = c.typeSpeed ?? 0;
|
||||||
|
const typing = speed > 0 ? line.length / speed : 0;
|
||||||
|
return Math.max(animDur, textStart + typing) + (c.holdLast ?? 1.6);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Loop ---------- */
|
||||||
|
let raf = 0;
|
||||||
|
let last = 0;
|
||||||
|
|
||||||
|
function loop(now: number) {
|
||||||
|
raf = requestAnimationFrame(loop);
|
||||||
|
const dt = last ? Math.min((now - last) / 1000, 1 / 20) : 0;
|
||||||
|
last = now;
|
||||||
|
if (!ready || !ctx) return;
|
||||||
|
|
||||||
|
const locked = needs.isLocked || pointer.state === 'held';
|
||||||
|
|
||||||
|
/* --- physics or held --- */
|
||||||
|
if (pointer.state === 'held') {
|
||||||
|
if (!heldAnchorSet) {
|
||||||
|
pointer.setGrabAnchor(physics.x, physics.y);
|
||||||
|
heldAnchorSet = true;
|
||||||
|
}
|
||||||
|
const anchor = pointer.getHeldPosition();
|
||||||
|
if (anchor) {
|
||||||
|
physics.x = anchor.x;
|
||||||
|
physics.y = Math.max(0, anchor.y);
|
||||||
|
physics.vx = 0;
|
||||||
|
physics.vy = 0;
|
||||||
|
physics.grounded = false;
|
||||||
|
physics.squash = 0;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
heldAnchorSet = false;
|
||||||
|
physics.step(
|
||||||
|
dt,
|
||||||
|
{
|
||||||
|
direction: locked ? 0 : input.direction(),
|
||||||
|
jump: locked ? false : input.consumeJump()
|
||||||
|
},
|
||||||
|
{ maxSpeed, acceleration, friction, jumpVelocity, gravity, wrapEdges },
|
||||||
|
bounds()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- falling → landing --- */
|
||||||
|
if (pointer.state === 'falling' && physics.grounded) {
|
||||||
|
pointer.setState('landing');
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- pointer bounds, then tick the pointer --- */
|
||||||
|
if (lastBodyW > 0) {
|
||||||
|
const gy = physics.groundY(bounds());
|
||||||
|
pointer.setBounds({
|
||||||
|
left: physics.x - lastBodyW / 2,
|
||||||
|
top: gy - physics.y - lastBodyH,
|
||||||
|
width: lastBodyW,
|
||||||
|
height: lastBodyH
|
||||||
|
});
|
||||||
|
}
|
||||||
|
pointer.update(dt);
|
||||||
|
|
||||||
|
/* --- resolve state and advance its clock --- */
|
||||||
|
const name = activeStateName();
|
||||||
|
const pack = states[name];
|
||||||
|
clock.update(dt, name, pack, Math.abs(physics.vx));
|
||||||
|
|
||||||
|
/* --- body image --- */
|
||||||
|
const body = bodyFor(name);
|
||||||
|
if (body) {
|
||||||
|
lastBodyW = body.naturalWidth * scale;
|
||||||
|
lastBodyH = body.naturalHeight * scale;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- needs --- */
|
||||||
|
needs.step(dt, name, {
|
||||||
|
defs: needsConfig,
|
||||||
|
bubblePacks: bubblePacks ?? {},
|
||||||
|
states,
|
||||||
|
chatter: chatter ? buildChatterHooks(chatter) : null,
|
||||||
|
onSound: playSound
|
||||||
|
});
|
||||||
|
|
||||||
|
/* --- draw --- */
|
||||||
|
if (!body || !pack) return;
|
||||||
|
const side = sideFor(pack);
|
||||||
|
|
||||||
|
renderer.draw({
|
||||||
|
ctx,
|
||||||
|
viewW,
|
||||||
|
viewH,
|
||||||
|
groundY: physics.groundY(bounds()),
|
||||||
|
dpr,
|
||||||
|
body,
|
||||||
|
mirrored: side.mirrored,
|
||||||
|
x: physics.x,
|
||||||
|
y: physics.y,
|
||||||
|
squash: physics.squash,
|
||||||
|
bubble: currentBubble(),
|
||||||
|
bubbleText: needs.active?.text ?? null,
|
||||||
|
charsShown: currentCharsShown(),
|
||||||
|
bubbleTextFrame: chatter?.textFrame ?? 0,
|
||||||
|
scale,
|
||||||
|
showShadow,
|
||||||
|
reflectionOpacity,
|
||||||
|
reflectionFade,
|
||||||
|
reflectionTint,
|
||||||
|
bubbleAnchorX,
|
||||||
|
bubbleAnchorY,
|
||||||
|
chatter
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
if (!canvas) return;
|
||||||
|
ctx = canvas.getContext('2d');
|
||||||
|
if (!ctx) return;
|
||||||
|
|
||||||
|
pointer.onGrab = () => {
|
||||||
|
needs.active = null;
|
||||||
|
needs.queue.length = 0;
|
||||||
|
heldAnchorSet = false;
|
||||||
|
if (interactions.pickupSound) playSound(interactions.pickupSound, 1);
|
||||||
|
};
|
||||||
|
pointer.onRelease = () => {
|
||||||
|
const v = pointer.getThrowVelocity();
|
||||||
|
physics.vx = v.vx;
|
||||||
|
physics.vy = v.vy;
|
||||||
|
// If the throw is upward, lift the cat out of the grounded state.
|
||||||
|
if (physics.vy > 0) physics.grounded = false;
|
||||||
|
if (interactions.dropSound) playSound(interactions.dropSound, 0.8);
|
||||||
|
};
|
||||||
|
pointer.onLanding = () => {
|
||||||
|
if (interactions.landingSound) playSound(interactions.landingSound, 0.8);
|
||||||
|
};
|
||||||
|
pointer.onPetSound = () => {
|
||||||
|
if (interactions.purrSound) playSound(interactions.purrSound, interactions.purrVolume ?? 0.4);
|
||||||
|
};
|
||||||
|
|
||||||
|
resize();
|
||||||
|
const ro = new ResizeObserver(resize);
|
||||||
|
ro.observe(canvas);
|
||||||
|
|
||||||
|
input.attach(window);
|
||||||
|
pointer.attach(window);
|
||||||
|
installAudioUnlocker();
|
||||||
|
raf = requestAnimationFrame(loop);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelAnimationFrame(raf);
|
||||||
|
ro.disconnect();
|
||||||
|
input.detach(window);
|
||||||
|
pointer.detach(window);
|
||||||
|
for (const g of GESTURES) window.removeEventListener(g, unlockAudio);
|
||||||
|
void audioCtx?.close();
|
||||||
|
};
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:window />
|
||||||
|
|
||||||
|
<div class="layer">
|
||||||
|
<div class="floor" style:height="{floorHeight}px" style:background={floorColor}></div>
|
||||||
|
<canvas bind:this={canvas} aria-hidden="true"></canvas>
|
||||||
|
{#if loadError}
|
||||||
|
<p class="err">{loadError}</p>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.layer {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 50;
|
||||||
|
}
|
||||||
|
.floor {
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.06), rgba(0, 0, 0, 0.15));
|
||||||
|
background-blend-mode: overlay;
|
||||||
|
}
|
||||||
|
canvas {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
image-rendering: pixelated;
|
||||||
|
}
|
||||||
|
.err {
|
||||||
|
position: absolute;
|
||||||
|
bottom: 1rem;
|
||||||
|
left: 1rem;
|
||||||
|
margin: 0;
|
||||||
|
font:
|
||||||
|
12px/1.4 ui-monospace,
|
||||||
|
monospace;
|
||||||
|
color: #ff6b6b;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
const files = import.meta.glob('$lib/assets/character/bubbles/**/*.png', {
|
||||||
|
eager: true,
|
||||||
|
query: '?url',
|
||||||
|
import: 'default'
|
||||||
|
}) as Record<string, string>;
|
||||||
|
|
||||||
|
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
|
||||||
|
const BUBBLE_RE = /\/bubbles\/([^/]+)\/[^/]+\.png$/i;
|
||||||
|
|
||||||
|
export interface BubblePack {
|
||||||
|
name: string;
|
||||||
|
frames: string[];
|
||||||
|
fps: number;
|
||||||
|
duration: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BubblePackOptions {
|
||||||
|
fps?: number;
|
||||||
|
duration?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadBubblePacks(opts: BubblePackOptions = {}): Record<string, BubblePack> {
|
||||||
|
const { fps = 8, duration = 2.5 } = opts;
|
||||||
|
const groups = new Map<string, Array<[string, string]>>();
|
||||||
|
|
||||||
|
for (const [path, url] of Object.entries(files)) {
|
||||||
|
const m = BUBBLE_RE.exec(path);
|
||||||
|
if (!m) continue;
|
||||||
|
const name = m[1].toLowerCase();
|
||||||
|
if (!groups.has(name)) groups.set(name, []);
|
||||||
|
groups.get(name)!.push([path, url]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const out: Record<string, BubblePack> = {};
|
||||||
|
for (const [name, entries] of groups) {
|
||||||
|
const frames = entries.sort(([a], [b]) => collator.compare(a, b)).map(([, url]) => url);
|
||||||
|
out[name] = { name, frames, fps, duration };
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ImageCache {
|
||||||
|
private images = new Map<string, HTMLImageElement>();
|
||||||
|
|
||||||
|
async load(urls: string[]): Promise<void> {
|
||||||
|
const results = await Promise.all(
|
||||||
|
urls.map(
|
||||||
|
(url) =>
|
||||||
|
new Promise<[string, HTMLImageElement]>((resolve, reject) => {
|
||||||
|
const img = new Image();
|
||||||
|
img.onload = () => resolve([url, img]);
|
||||||
|
img.onerror = () => reject(new Error(`Could not load "${url}"`));
|
||||||
|
img.src = url;
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
this.images = new Map(results);
|
||||||
|
}
|
||||||
|
|
||||||
|
get(url: string): HTMLImageElement | undefined {
|
||||||
|
return this.images.get(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
largestSize(urls: string[]): { w: number; h: number } {
|
||||||
|
let w = 0;
|
||||||
|
let h = 0;
|
||||||
|
for (const url of urls) {
|
||||||
|
const img = this.images.get(url);
|
||||||
|
if (!img) continue;
|
||||||
|
w = Math.max(w, img.naturalWidth);
|
||||||
|
h = Math.max(h, img.naturalHeight);
|
||||||
|
}
|
||||||
|
return { w, h };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
export interface ChatterConfig {
|
||||||
|
pack: string;
|
||||||
|
interval: [number, number];
|
||||||
|
lines: string[];
|
||||||
|
fontFamily?: string;
|
||||||
|
fontSize?: number;
|
||||||
|
color?: string;
|
||||||
|
align?: 'center' | 'left';
|
||||||
|
padding?: { top?: number; right?: number; bottom?: number; left?: number };
|
||||||
|
/** Distance from bubble top to the top of the first line, in sprite px. */
|
||||||
|
textTop?: number;
|
||||||
|
lineHeight?: number;
|
||||||
|
/** Bubble frame index at which text appears. */
|
||||||
|
textFrame?: number;
|
||||||
|
/** Typewriter speed in characters per second. */
|
||||||
|
typeSpeed?: number;
|
||||||
|
/** Sound pack for typing clicks. */
|
||||||
|
typeSound?: string;
|
||||||
|
typeSoundEvery?: number;
|
||||||
|
typeSoundVolume?: number;
|
||||||
|
/** Seconds the last frame holds after typing completes. */
|
||||||
|
holdLast?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CHATTER: ChatterConfig = {
|
||||||
|
pack: 'chatter',
|
||||||
|
interval: [12, 28],
|
||||||
|
lines: [
|
||||||
|
'mrrrp?',
|
||||||
|
'i could go for a nap',
|
||||||
|
'nice day for it',
|
||||||
|
'...',
|
||||||
|
'you again',
|
||||||
|
'meow',
|
||||||
|
'did you see that bird',
|
||||||
|
'my bowl is looking empty',
|
||||||
|
'i meant to do that',
|
||||||
|
'five more minutes'
|
||||||
|
],
|
||||||
|
fontFamily: "'Micro 5', sans-serif",
|
||||||
|
fontSize: 11,
|
||||||
|
color: '#1a1a1a',
|
||||||
|
align: 'center',
|
||||||
|
padding: { top: 8, right: 8, bottom: 8, left: 8 },
|
||||||
|
textTop: 8,
|
||||||
|
lineHeight: 1.2,
|
||||||
|
textFrame: 1,
|
||||||
|
typeSpeed: 24,
|
||||||
|
typeSound: 'type',
|
||||||
|
typeSoundEvery: 2,
|
||||||
|
typeSoundVolume: 0.3,
|
||||||
|
holdLast: 1.6
|
||||||
|
};
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
export type { Facing, PhysicsInput } from './types';
|
||||||
|
|
||||||
|
export { collectStateUrls, loadStates, resolveStateName, STATE_CONFIG, StateClock } from './states';
|
||||||
|
export type {
|
||||||
|
InteractionState,
|
||||||
|
ResolverConfig,
|
||||||
|
StateConfig,
|
||||||
|
StateConfigMap,
|
||||||
|
StateContext,
|
||||||
|
StatePack,
|
||||||
|
StateSide
|
||||||
|
} from './states';
|
||||||
|
|
||||||
|
export { ImageCache, loadBubblePacks } from './assets';
|
||||||
|
export type { BubblePack, BubblePackOptions } from './assets';
|
||||||
|
|
||||||
|
export { clamp, Physics } from './physics';
|
||||||
|
export type { PhysicsBounds, PhysicsConfig } from './physics';
|
||||||
|
|
||||||
|
export { KeyboardInput } from './input';
|
||||||
|
|
||||||
|
export { NEEDS, NeedsSimulator } from './needs';
|
||||||
|
export type {
|
||||||
|
ActiveEvent,
|
||||||
|
ChatterHooks,
|
||||||
|
FiredEvent,
|
||||||
|
NeedBand,
|
||||||
|
NeedDef,
|
||||||
|
NeedsConfig,
|
||||||
|
NeedSideEffect
|
||||||
|
} from './needs';
|
||||||
|
|
||||||
|
export { CHATTER } from './chatter';
|
||||||
|
export type { ChatterConfig } from './chatter';
|
||||||
|
|
||||||
|
export { CharacterRenderer } from './render';
|
||||||
|
export type { RenderInput } from './render';
|
||||||
|
|
||||||
|
export { loadSoundPacks, SoundPlayer } from './sounds';
|
||||||
|
export type { SoundPack } from './sounds';
|
||||||
|
|
||||||
|
export { INTERACTION, PointerController } from './interactions';
|
||||||
|
export type { InteractionConfig, PointerBounds } from './interactions';
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
const JUMP_KEYS = new Set([' ', 'w', 'arrowup']);
|
||||||
|
const MOVE_KEYS = new Set(['arrowleft', 'arrowright', 'a', 'd']);
|
||||||
|
|
||||||
|
export class KeyboardInput {
|
||||||
|
private held = new Set<string>();
|
||||||
|
private jumpQueued = false;
|
||||||
|
private listeners: Array<[string, EventListener]> = [];
|
||||||
|
|
||||||
|
attach(target: Window): void {
|
||||||
|
const down: EventListener = (e) => this.onKeyDown(e as KeyboardEvent);
|
||||||
|
const up: EventListener = (e) => this.onKeyUp(e as KeyboardEvent);
|
||||||
|
const blur: EventListener = () => this.clear();
|
||||||
|
|
||||||
|
target.addEventListener('keydown', down);
|
||||||
|
target.addEventListener('keyup', up);
|
||||||
|
target.addEventListener('blur', blur);
|
||||||
|
|
||||||
|
this.listeners = [
|
||||||
|
['keydown', down],
|
||||||
|
['keyup', up],
|
||||||
|
['blur', blur]
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
detach(target: Window): void {
|
||||||
|
for (const [type, fn] of this.listeners) target.removeEventListener(type, fn);
|
||||||
|
this.listeners = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
direction(): -1 | 0 | 1 {
|
||||||
|
let d = 0;
|
||||||
|
if (this.held.has('arrowleft') || this.held.has('a')) d -= 1;
|
||||||
|
if (this.held.has('arrowright') || this.held.has('d')) d += 1;
|
||||||
|
return d as -1 | 0 | 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
consumeJump(): boolean {
|
||||||
|
const j = this.jumpQueued;
|
||||||
|
this.jumpQueued = false;
|
||||||
|
return j;
|
||||||
|
}
|
||||||
|
|
||||||
|
clear(): void {
|
||||||
|
this.held.clear();
|
||||||
|
this.jumpQueued = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private onKeyDown(e: KeyboardEvent): void {
|
||||||
|
const k = e.key.toLowerCase();
|
||||||
|
|
||||||
|
if (JUMP_KEYS.has(k)) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!this.held.has(k)) this.jumpQueued = true;
|
||||||
|
this.held.add(k);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (MOVE_KEYS.has(k)) {
|
||||||
|
e.preventDefault();
|
||||||
|
this.held.add(k);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private onKeyUp(e: KeyboardEvent): void {
|
||||||
|
this.held.delete(e.key.toLowerCase());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
import type { InteractionState } from './states';
|
||||||
|
|
||||||
|
export interface PointerBounds {
|
||||||
|
left: number;
|
||||||
|
top: number;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InteractionConfig {
|
||||||
|
enabled?: boolean;
|
||||||
|
landingDuration?: number;
|
||||||
|
petDelay?: number;
|
||||||
|
petLinger?: number;
|
||||||
|
petSoundInterval?: number;
|
||||||
|
pickupSound?: string;
|
||||||
|
dropSound?: string;
|
||||||
|
landingSound?: string;
|
||||||
|
purrSound?: string;
|
||||||
|
purrVolume?: number;
|
||||||
|
/** Hard cap on throw speed, px/s. Prevents a fast flick launching the cat off-screen. */
|
||||||
|
maxThrowVelocity?: number;
|
||||||
|
/** Cursor-velocity smoothing, 0–1. Higher = twitchier throws, lower = smoother. */
|
||||||
|
throwSmoothing?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const INTERACTION: InteractionConfig = {
|
||||||
|
enabled: true,
|
||||||
|
landingDuration: 0.5,
|
||||||
|
petDelay: 0.25,
|
||||||
|
petLinger: 0.3,
|
||||||
|
petSoundInterval: 0.9,
|
||||||
|
pickupSound: 'pickup',
|
||||||
|
dropSound: 'drop',
|
||||||
|
landingSound: 'landing',
|
||||||
|
purrSound: 'purr',
|
||||||
|
purrVolume: 0.35,
|
||||||
|
maxThrowVelocity: 1200,
|
||||||
|
throwSmoothing: 0.35
|
||||||
|
};
|
||||||
|
|
||||||
|
function clamp(v: number, lo: number, hi: number): number {
|
||||||
|
return Math.min(Math.max(v, lo), hi);
|
||||||
|
}
|
||||||
|
|
||||||
|
function lerp(a: number, b: number, t: number): number {
|
||||||
|
return a + (b - a) * t;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PointerController {
|
||||||
|
cursorX = 0;
|
||||||
|
cursorY = 0;
|
||||||
|
state: InteractionState = 'free';
|
||||||
|
timeInState = 0;
|
||||||
|
|
||||||
|
onGrab?: () => void;
|
||||||
|
onRelease?: () => void;
|
||||||
|
onLanding?: () => void;
|
||||||
|
onPetStart?: () => void;
|
||||||
|
onPetSound?: () => void;
|
||||||
|
|
||||||
|
private cfg: Required<
|
||||||
|
Pick<
|
||||||
|
InteractionConfig,
|
||||||
|
| 'landingDuration'
|
||||||
|
| 'petDelay'
|
||||||
|
| 'petLinger'
|
||||||
|
| 'petSoundInterval'
|
||||||
|
| 'maxThrowVelocity'
|
||||||
|
| 'throwSmoothing'
|
||||||
|
>
|
||||||
|
> & { enabled: boolean };
|
||||||
|
|
||||||
|
private bounds: PointerBounds | null = null;
|
||||||
|
private grabAnchor: { x: number; y: number } | null = null;
|
||||||
|
private grabPointer = { x: 0, y: 0 };
|
||||||
|
private hoverTime = 0;
|
||||||
|
private lingerTime = 0;
|
||||||
|
private purrTimer = 0;
|
||||||
|
private listeners: Array<[string, EventListener]> = [];
|
||||||
|
|
||||||
|
// Cursor velocity tracking (screen coordinates, px/s).
|
||||||
|
private prevCursorX = 0;
|
||||||
|
private prevCursorY = 0;
|
||||||
|
private prevCursorSet = false;
|
||||||
|
private smoothVX = 0;
|
||||||
|
private smoothVY = 0;
|
||||||
|
|
||||||
|
constructor(cfg: InteractionConfig) {
|
||||||
|
this.cfg = {
|
||||||
|
enabled: cfg.enabled ?? true,
|
||||||
|
landingDuration: cfg.landingDuration ?? 0.5,
|
||||||
|
petDelay: cfg.petDelay ?? 0.25,
|
||||||
|
petLinger: cfg.petLinger ?? 0.3,
|
||||||
|
petSoundInterval: cfg.petSoundInterval ?? 0.9,
|
||||||
|
maxThrowVelocity: cfg.maxThrowVelocity ?? 1200,
|
||||||
|
throwSmoothing: clamp(cfg.throwSmoothing ?? 0.35, 0.05, 1)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
attach(target: Window): void {
|
||||||
|
if (!this.cfg.enabled) return;
|
||||||
|
|
||||||
|
const down: EventListener = (e) => this.onPointerDown(e as PointerEvent);
|
||||||
|
const up: EventListener = () => this.onPointerUp();
|
||||||
|
const move: EventListener = (e) => this.onPointerMove(e as PointerEvent);
|
||||||
|
const leave: EventListener = () => this.onPointerLeave();
|
||||||
|
|
||||||
|
const pairs: Array<[string, EventListener]> = [
|
||||||
|
['pointerdown', down],
|
||||||
|
['pointerup', up],
|
||||||
|
['pointermove', move],
|
||||||
|
['pointerleave', leave]
|
||||||
|
];
|
||||||
|
for (const [type, fn] of pairs) target.addEventListener(type, fn);
|
||||||
|
this.listeners = pairs;
|
||||||
|
}
|
||||||
|
|
||||||
|
detach(target: Window): void {
|
||||||
|
for (const [type, fn] of this.listeners) target.removeEventListener(type, fn);
|
||||||
|
this.listeners = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
setBounds(b: PointerBounds): void {
|
||||||
|
this.bounds = b;
|
||||||
|
}
|
||||||
|
|
||||||
|
setGrabAnchor(x: number, y: number): void {
|
||||||
|
this.grabAnchor = { x, y };
|
||||||
|
}
|
||||||
|
|
||||||
|
getHeldPosition(): { x: number; y: number } | null {
|
||||||
|
if (this.state !== 'held' || !this.grabAnchor) return null;
|
||||||
|
const dx = this.cursorX - this.grabPointer.x;
|
||||||
|
const dy = this.cursorY - this.grabPointer.y;
|
||||||
|
return { x: this.grabAnchor.x + dx, y: this.grabAnchor.y - dy };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cursor velocity at the moment of release, converted to internal coordinates.
|
||||||
|
* `x` matches screen x; `y` is flipped because internal y grows upward.
|
||||||
|
*/
|
||||||
|
getThrowVelocity(): { vx: number; vy: number } {
|
||||||
|
const cap = this.cfg.maxThrowVelocity;
|
||||||
|
return {
|
||||||
|
vx: clamp(this.smoothVX, -cap, cap),
|
||||||
|
vy: clamp(-this.smoothVY, -cap, cap)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
setState(s: InteractionState): void {
|
||||||
|
if (this.state === s) return;
|
||||||
|
this.state = s;
|
||||||
|
this.timeInState = 0;
|
||||||
|
|
||||||
|
if (s === 'held') this.onGrab?.();
|
||||||
|
if (s === 'falling') this.onRelease?.();
|
||||||
|
if (s === 'landing') this.onLanding?.();
|
||||||
|
if (s === 'petted') {
|
||||||
|
this.purrTimer = 0;
|
||||||
|
this.onPetStart?.();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
update(dt: number): void {
|
||||||
|
this.timeInState += dt;
|
||||||
|
|
||||||
|
// Cursor velocity tracking. Only meaningful while held; otherwise decay
|
||||||
|
// to zero so a stale flick doesn't linger between grabs.
|
||||||
|
if (this.state === 'held' && this.prevCursorSet && dt > 0) {
|
||||||
|
const rawVX = (this.cursorX - this.prevCursorX) / dt;
|
||||||
|
const rawVY = (this.cursorY - this.prevCursorY) / dt;
|
||||||
|
const a = this.cfg.throwSmoothing;
|
||||||
|
this.smoothVX = lerp(this.smoothVX, rawVX, a);
|
||||||
|
this.smoothVY = lerp(this.smoothVY, rawVY, a);
|
||||||
|
} else if (this.state !== 'held') {
|
||||||
|
this.smoothVX = 0;
|
||||||
|
this.smoothVY = 0;
|
||||||
|
}
|
||||||
|
this.prevCursorX = this.cursorX;
|
||||||
|
this.prevCursorY = this.cursorY;
|
||||||
|
this.prevCursorSet = true;
|
||||||
|
|
||||||
|
if (this.state === 'landing' && this.timeInState >= this.cfg.landingDuration) {
|
||||||
|
this.setState('free');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.state === 'free') {
|
||||||
|
if (this.hoveringHead()) {
|
||||||
|
this.hoverTime += dt;
|
||||||
|
if (this.hoverTime >= this.cfg.petDelay) {
|
||||||
|
this.hoverTime = 0;
|
||||||
|
this.setState('petted');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.hoverTime = 0;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.hoverTime = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.state === 'petted') {
|
||||||
|
if (this.hoveringHead()) {
|
||||||
|
this.lingerTime = 0;
|
||||||
|
} else {
|
||||||
|
this.lingerTime += dt;
|
||||||
|
if (this.lingerTime >= this.cfg.petLinger) {
|
||||||
|
this.lingerTime = 0;
|
||||||
|
this.setState('free');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.purrTimer += dt;
|
||||||
|
if (this.purrTimer >= this.cfg.petSoundInterval) {
|
||||||
|
this.purrTimer = 0;
|
||||||
|
this.onPetSound?.();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private hoveringHead(): boolean {
|
||||||
|
const b = this.bounds;
|
||||||
|
if (!b) return false;
|
||||||
|
return (
|
||||||
|
this.cursorX >= b.left &&
|
||||||
|
this.cursorX <= b.left + b.width &&
|
||||||
|
this.cursorY >= b.top &&
|
||||||
|
this.cursorY <= b.top + b.height / 2
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private hoveringBody(): boolean {
|
||||||
|
const b = this.bounds;
|
||||||
|
if (!b) return false;
|
||||||
|
return (
|
||||||
|
this.cursorX >= b.left &&
|
||||||
|
this.cursorX <= b.left + b.width &&
|
||||||
|
this.cursorY >= b.top &&
|
||||||
|
this.cursorY <= b.top + b.height
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private onPointerDown(e: PointerEvent): void {
|
||||||
|
if (this.state !== 'free' && this.state !== 'petted') return;
|
||||||
|
this.cursorX = e.clientX;
|
||||||
|
this.cursorY = e.clientY;
|
||||||
|
if (!this.hoveringBody()) return;
|
||||||
|
|
||||||
|
e.preventDefault();
|
||||||
|
this.grabPointer = { x: this.cursorX, y: this.cursorY };
|
||||||
|
this.setState('held');
|
||||||
|
}
|
||||||
|
|
||||||
|
private onPointerUp(): void {
|
||||||
|
if (this.state === 'held') this.setState('falling');
|
||||||
|
}
|
||||||
|
|
||||||
|
private onPointerMove(e: PointerEvent): void {
|
||||||
|
this.cursorX = e.clientX;
|
||||||
|
this.cursorY = e.clientY;
|
||||||
|
}
|
||||||
|
|
||||||
|
private onPointerLeave(): void {
|
||||||
|
if (this.state === 'held') this.setState('falling');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,338 @@
|
|||||||
|
import type { BubblePack } from './assets';
|
||||||
|
import type { StatePack } from './states';
|
||||||
|
|
||||||
|
export interface NeedBand {
|
||||||
|
at: number;
|
||||||
|
bubble: string;
|
||||||
|
action?: string;
|
||||||
|
sound?: string;
|
||||||
|
soundVolume?: number;
|
||||||
|
bubbleDuration?: number;
|
||||||
|
/** Seconds after the bubble disappears that the action begins. */
|
||||||
|
actionDelay?: number;
|
||||||
|
satisfyDuration?: number;
|
||||||
|
priority?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NeedSideEffect {
|
||||||
|
need: string;
|
||||||
|
perSecond: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NeedDef {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
riseRate: number;
|
||||||
|
max: number;
|
||||||
|
/** Multipliers on `riseRate` keyed by state name (idle, walk, run, jump, ...). */
|
||||||
|
activityMultipliers: Record<string, number>;
|
||||||
|
curve?: number;
|
||||||
|
bands: NeedBand[];
|
||||||
|
resetBelow: number;
|
||||||
|
priority: number;
|
||||||
|
satisfyDuration: number;
|
||||||
|
satisfyTo: number;
|
||||||
|
satisfySideEffects?: NeedSideEffect[];
|
||||||
|
/** Default bubbleDuration for this need's bands. */
|
||||||
|
bubbleDuration?: number;
|
||||||
|
/** Default actionDelay for this need's bands. */
|
||||||
|
actionDelay?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const NEEDS: NeedDef[] = [
|
||||||
|
{
|
||||||
|
id: 'thirst',
|
||||||
|
label: 'Thirst',
|
||||||
|
riseRate: 0.9,
|
||||||
|
max: 100,
|
||||||
|
activityMultipliers: { idle: 1, walk: 1.3, run: 2.0, jump: 1.6 },
|
||||||
|
curve: 0.5,
|
||||||
|
bands: [
|
||||||
|
{
|
||||||
|
at: 85,
|
||||||
|
bubble: 'thirst_urgent',
|
||||||
|
action: 'drink',
|
||||||
|
sound: 'thirst_urgent',
|
||||||
|
soundVolume: 0.6,
|
||||||
|
bubbleDuration: 1.6,
|
||||||
|
actionDelay: 0.4,
|
||||||
|
satisfyDuration: 4
|
||||||
|
},
|
||||||
|
{ at: 50, bubble: 'thirst_mild', bubbleDuration: 2 }
|
||||||
|
],
|
||||||
|
resetBelow: 15,
|
||||||
|
priority: 2,
|
||||||
|
satisfyDuration: 3,
|
||||||
|
satisfyTo: 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'boredom',
|
||||||
|
label: 'Boredom',
|
||||||
|
riseRate: 1.4,
|
||||||
|
max: 100,
|
||||||
|
activityMultipliers: { idle: 1.8, walk: 0.6, run: 0.3, jump: 0.5 },
|
||||||
|
curve: 0.3,
|
||||||
|
bands: [
|
||||||
|
{
|
||||||
|
at: 80,
|
||||||
|
bubble: 'bored_urgent',
|
||||||
|
action: 'play',
|
||||||
|
bubbleDuration: 1.6,
|
||||||
|
actionDelay: 0.4,
|
||||||
|
satisfyDuration: 5
|
||||||
|
},
|
||||||
|
{ at: 40, bubble: 'bored_mild', bubbleDuration: 2 }
|
||||||
|
],
|
||||||
|
resetBelow: 10,
|
||||||
|
priority: 1,
|
||||||
|
satisfyDuration: 4,
|
||||||
|
satisfyTo: 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'sleepiness',
|
||||||
|
label: 'Sleepiness',
|
||||||
|
riseRate: 0.6,
|
||||||
|
max: 100,
|
||||||
|
activityMultipliers: { idle: 1, walk: 1.2, run: 1.5, jump: 1.3 },
|
||||||
|
curve: 0.4,
|
||||||
|
bands: [
|
||||||
|
{
|
||||||
|
at: 90,
|
||||||
|
bubble: 'sleepy_urgent',
|
||||||
|
action: 'sleep',
|
||||||
|
bubbleDuration: 1.6,
|
||||||
|
actionDelay: 0.4,
|
||||||
|
satisfyDuration: 8
|
||||||
|
},
|
||||||
|
{ at: 60, bubble: 'sleepy_mild', bubbleDuration: 2 }
|
||||||
|
],
|
||||||
|
resetBelow: 5,
|
||||||
|
priority: 3,
|
||||||
|
satisfyDuration: 6,
|
||||||
|
satisfyTo: 0,
|
||||||
|
satisfySideEffects: [{ need: 'thirst', perSecond: 0.4 }]
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
export interface FiredEvent {
|
||||||
|
needId: string | null;
|
||||||
|
def: NeedDef | null;
|
||||||
|
band: NeedBand;
|
||||||
|
priority: number;
|
||||||
|
text?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ActiveEvent {
|
||||||
|
needId: string | null;
|
||||||
|
def: NeedDef | null;
|
||||||
|
bubblePack: BubblePack | null;
|
||||||
|
actionState: StatePack | null;
|
||||||
|
elapsed: number;
|
||||||
|
totalDuration: number;
|
||||||
|
satisfyTo: number;
|
||||||
|
text?: string;
|
||||||
|
soundPack?: string | null;
|
||||||
|
soundVolume?: number;
|
||||||
|
lastCharsShown: number;
|
||||||
|
bubbleDuration: number;
|
||||||
|
actionDelay: number;
|
||||||
|
satisfyDuration: number;
|
||||||
|
actionStart: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChatterHooks {
|
||||||
|
pack: string;
|
||||||
|
interval: [number, number];
|
||||||
|
lines: string[];
|
||||||
|
typeSpeed?: number;
|
||||||
|
typeSound?: string;
|
||||||
|
typeSoundEvery?: number;
|
||||||
|
typeSoundVolume?: number;
|
||||||
|
/** Total seconds the bubble stays up, computed by the caller. */
|
||||||
|
bubbleDuration: (line: string, pack: BubblePack) => number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NeedsConfig {
|
||||||
|
defs: NeedDef[];
|
||||||
|
bubblePacks: Record<string, BubblePack>;
|
||||||
|
states: Record<string, StatePack>;
|
||||||
|
chatter: ChatterHooks | null;
|
||||||
|
onSound: (name: string, volume: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_QUEUE = 8;
|
||||||
|
|
||||||
|
export class NeedsSimulator {
|
||||||
|
values: Record<string, number> = {};
|
||||||
|
firedBands = new Set<string>();
|
||||||
|
queue: FiredEvent[] = [];
|
||||||
|
active: ActiveEvent | null = null;
|
||||||
|
chatterTimer = 0;
|
||||||
|
chatterTarget = -1;
|
||||||
|
private initialized = false;
|
||||||
|
|
||||||
|
get isLocked(): boolean {
|
||||||
|
return !!this.active?.actionState && this.active.elapsed >= this.active.actionStart;
|
||||||
|
}
|
||||||
|
|
||||||
|
step(dt: number, activity: string, cfg: NeedsConfig): void {
|
||||||
|
if (!cfg.defs.length) return;
|
||||||
|
|
||||||
|
if (!this.initialized) {
|
||||||
|
for (const d of cfg.defs) this.values[d.id] = 0;
|
||||||
|
this.initialized = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.rise(dt, activity, cfg);
|
||||||
|
this.applySideEffects(dt, cfg);
|
||||||
|
this.checkBands(cfg);
|
||||||
|
this.maybeChatter(dt, cfg);
|
||||||
|
this.drainQueue(cfg);
|
||||||
|
this.advance(dt, cfg);
|
||||||
|
}
|
||||||
|
|
||||||
|
private rise(dt: number, activity: string, cfg: NeedsConfig): void {
|
||||||
|
for (const def of cfg.defs) {
|
||||||
|
if (this.active?.needId === def.id) continue;
|
||||||
|
const v = this.values[def.id] ?? 0;
|
||||||
|
const mult = def.activityMultipliers[activity] ?? 1;
|
||||||
|
const curve = def.curve ? Math.pow(1 + v / def.max, def.curve) : 1;
|
||||||
|
this.values[def.id] = Math.min(def.max, v + def.riseRate * mult * curve * dt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private applySideEffects(dt: number, cfg: NeedsConfig): void {
|
||||||
|
const fx = this.active?.def?.satisfySideEffects;
|
||||||
|
if (!fx) return;
|
||||||
|
for (const e of fx) {
|
||||||
|
const other = cfg.defs.find((n) => n.id === e.need);
|
||||||
|
if (!other) continue;
|
||||||
|
const cur = this.values[other.id] ?? 0;
|
||||||
|
this.values[other.id] = Math.min(other.max, cur + e.perSecond * dt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private checkBands(cfg: NeedsConfig): void {
|
||||||
|
for (const def of cfg.defs) {
|
||||||
|
const v = this.values[def.id] ?? 0;
|
||||||
|
for (const band of def.bands) {
|
||||||
|
const key = `${def.id}:${band.at}`;
|
||||||
|
if (v >= band.at && !this.firedBands.has(key)) {
|
||||||
|
this.firedBands.add(key);
|
||||||
|
if (this.queue.length < MAX_QUEUE) {
|
||||||
|
this.queue.push({
|
||||||
|
needId: def.id,
|
||||||
|
def,
|
||||||
|
band,
|
||||||
|
priority: band.priority ?? def.priority
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else if (v < def.resetBelow && this.firedBands.has(key)) {
|
||||||
|
this.firedBands.delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private maybeChatter(dt: number, cfg: NeedsConfig): void {
|
||||||
|
const c = cfg.chatter;
|
||||||
|
if (!c || !c.lines.length) return;
|
||||||
|
const pack = cfg.bubblePacks[c.pack];
|
||||||
|
if (!pack) return;
|
||||||
|
|
||||||
|
if (this.chatterTarget < 0) this.chatterTarget = randBetween(...c.interval);
|
||||||
|
|
||||||
|
if (this.active || this.queue.length > 0) return;
|
||||||
|
|
||||||
|
this.chatterTimer += dt;
|
||||||
|
if (this.chatterTimer < this.chatterTarget) return;
|
||||||
|
|
||||||
|
this.chatterTimer = 0;
|
||||||
|
this.chatterTarget = randBetween(...c.interval);
|
||||||
|
|
||||||
|
const line = c.lines[Math.floor(Math.random() * c.lines.length)];
|
||||||
|
this.queue.push({
|
||||||
|
needId: null,
|
||||||
|
def: null,
|
||||||
|
band: {
|
||||||
|
at: 0,
|
||||||
|
bubble: c.pack,
|
||||||
|
bubbleDuration: c.bubbleDuration(line, pack)
|
||||||
|
},
|
||||||
|
priority: -1000,
|
||||||
|
text: line
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private drainQueue(cfg: NeedsConfig): void {
|
||||||
|
if (this.queue.length > 1) this.queue.sort((a, b) => b.priority - a.priority);
|
||||||
|
if (this.active || !this.queue.length) return;
|
||||||
|
|
||||||
|
const fired = this.queue.shift()!;
|
||||||
|
this.active = buildActiveEvent(fired, cfg);
|
||||||
|
|
||||||
|
if (this.active.soundPack) {
|
||||||
|
cfg.onSound(this.active.soundPack, this.active.soundVolume ?? 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private advance(dt: number, cfg: NeedsConfig): void {
|
||||||
|
const a = this.active;
|
||||||
|
if (!a) return;
|
||||||
|
|
||||||
|
a.elapsed += dt;
|
||||||
|
|
||||||
|
const c = cfg.chatter;
|
||||||
|
if (a.text && c?.typeSound && a.elapsed < a.bubbleDuration) {
|
||||||
|
const speed = c.typeSpeed ?? 0;
|
||||||
|
if (speed > 0) {
|
||||||
|
const charsShown = Math.min(a.text.length, Math.floor(a.elapsed * speed));
|
||||||
|
const every = Math.max(1, c.typeSoundEvery ?? 2);
|
||||||
|
const before = Math.floor(a.lastCharsShown / every);
|
||||||
|
const now = Math.floor(charsShown / every);
|
||||||
|
if (now > before) cfg.onSound(c.typeSound, c.typeSoundVolume ?? 0.3);
|
||||||
|
a.lastCharsShown = charsShown;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (a.elapsed >= a.totalDuration) {
|
||||||
|
if (a.needId && a.def) this.values[a.needId] = a.satisfyTo;
|
||||||
|
this.active = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildActiveEvent(fired: FiredEvent, cfg: NeedsConfig): ActiveEvent {
|
||||||
|
const bubblePack = fired.band.bubble ? (cfg.bubblePacks[fired.band.bubble] ?? null) : null;
|
||||||
|
const actionState = fired.band.action ? (cfg.states[fired.band.action] ?? null) : null;
|
||||||
|
|
||||||
|
const bubbleDuration =
|
||||||
|
fired.band.bubbleDuration ?? fired.def?.bubbleDuration ?? bubblePack?.duration ?? 2.5;
|
||||||
|
const satisfyDuration = fired.band.satisfyDuration ?? fired.def?.satisfyDuration ?? 0;
|
||||||
|
const actionDelay = actionState ? (fired.band.actionDelay ?? fired.def?.actionDelay ?? 0.4) : 0;
|
||||||
|
|
||||||
|
const actionStart = bubbleDuration + actionDelay;
|
||||||
|
const totalDuration = actionState ? actionStart + satisfyDuration : bubbleDuration;
|
||||||
|
|
||||||
|
return {
|
||||||
|
needId: fired.needId,
|
||||||
|
def: fired.def,
|
||||||
|
bubblePack,
|
||||||
|
actionState,
|
||||||
|
elapsed: 0,
|
||||||
|
totalDuration,
|
||||||
|
satisfyTo: fired.def?.satisfyTo ?? 0,
|
||||||
|
text: fired.text,
|
||||||
|
soundPack: fired.band.sound ?? null,
|
||||||
|
soundVolume: fired.band.soundVolume ?? 1,
|
||||||
|
lastCharsShown: 0,
|
||||||
|
bubbleDuration,
|
||||||
|
actionDelay,
|
||||||
|
satisfyDuration,
|
||||||
|
actionStart
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function randBetween(min: number, max: number): number {
|
||||||
|
return min + Math.random() * (max - min);
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import type { Facing, PhysicsInput } from './types';
|
||||||
|
|
||||||
|
export interface PhysicsConfig {
|
||||||
|
maxSpeed: number;
|
||||||
|
acceleration: number;
|
||||||
|
friction: number;
|
||||||
|
jumpVelocity: number;
|
||||||
|
gravity: number;
|
||||||
|
wrapEdges: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PhysicsBounds {
|
||||||
|
viewW: number;
|
||||||
|
viewH: number;
|
||||||
|
floorHeight: number;
|
||||||
|
spriteW: number;
|
||||||
|
scale: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clamp(v: number, lo: number, hi: number): number {
|
||||||
|
return Math.min(Math.max(v, lo), hi);
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Physics {
|
||||||
|
x = 0;
|
||||||
|
vx = 0;
|
||||||
|
y = 0;
|
||||||
|
vy = 0;
|
||||||
|
grounded = true;
|
||||||
|
squash = 0;
|
||||||
|
facing: Facing = 'right';
|
||||||
|
|
||||||
|
place(viewW: number, fraction: number): void {
|
||||||
|
this.x = viewW * fraction;
|
||||||
|
}
|
||||||
|
|
||||||
|
step(dt: number, input: PhysicsInput, cfg: PhysicsConfig, bounds: PhysicsBounds): void {
|
||||||
|
/* --- horizontal --- */
|
||||||
|
if (input.direction !== 0) {
|
||||||
|
this.vx = clamp(
|
||||||
|
this.vx + input.direction * cfg.acceleration * dt,
|
||||||
|
-cfg.maxSpeed,
|
||||||
|
cfg.maxSpeed
|
||||||
|
);
|
||||||
|
this.facing = input.direction > 0 ? 'right' : 'left';
|
||||||
|
} else if (this.vx !== 0) {
|
||||||
|
// Air drag is much lighter than ground friction, so a thrown cat
|
||||||
|
// carries its momentum instead of stopping in a body length.
|
||||||
|
const f = this.grounded ? cfg.friction : cfg.friction * 0.15;
|
||||||
|
const drop = f * dt;
|
||||||
|
this.vx = Math.abs(this.vx) <= drop ? 0 : this.vx - Math.sign(this.vx) * drop;
|
||||||
|
}
|
||||||
|
|
||||||
|
const target = this.x + this.vx * dt;
|
||||||
|
const bounded = this.boundX(target, cfg, bounds);
|
||||||
|
if (!cfg.wrapEdges && bounded !== target) this.vx = 0;
|
||||||
|
this.x = bounded;
|
||||||
|
|
||||||
|
/* --- vertical --- */
|
||||||
|
if (input.jump && this.grounded) {
|
||||||
|
this.vy = cfg.jumpVelocity;
|
||||||
|
this.grounded = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.grounded) {
|
||||||
|
this.vy -= cfg.gravity * dt;
|
||||||
|
this.y += this.vy * dt;
|
||||||
|
if (this.y <= 0) {
|
||||||
|
const impact = -this.vy;
|
||||||
|
this.y = 0;
|
||||||
|
this.vy = 0;
|
||||||
|
this.grounded = true;
|
||||||
|
this.squash = clamp(impact / 900, 0, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.squash > 0) this.squash = Math.max(0, this.squash - dt * 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
rebound(cfg: PhysicsConfig, bounds: PhysicsBounds): void {
|
||||||
|
this.x = this.boundX(this.x, cfg, bounds);
|
||||||
|
}
|
||||||
|
|
||||||
|
groundY(bounds: PhysicsBounds): number {
|
||||||
|
return bounds.viewH - bounds.floorHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boundX(value: number, cfg: PhysicsConfig, bounds: PhysicsBounds): number {
|
||||||
|
if (bounds.viewW <= 0) return value;
|
||||||
|
const half = (bounds.spriteW * bounds.scale) / 2;
|
||||||
|
|
||||||
|
if (cfg.wrapEdges) {
|
||||||
|
const wrapWidth = bounds.viewW + bounds.spriteW * bounds.scale;
|
||||||
|
return ((((value + half) % wrapWidth) + wrapWidth) % wrapWidth) - half;
|
||||||
|
}
|
||||||
|
|
||||||
|
const lo = half;
|
||||||
|
const hi = bounds.viewW - half;
|
||||||
|
if (hi <= lo) return bounds.viewW / 2;
|
||||||
|
return clamp(value, lo, hi);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
import type { ChatterConfig } from './chatter';
|
||||||
|
|
||||||
|
export interface RenderInput {
|
||||||
|
ctx: CanvasRenderingContext2D;
|
||||||
|
viewW: number;
|
||||||
|
viewH: number;
|
||||||
|
groundY: number;
|
||||||
|
dpr: number;
|
||||||
|
|
||||||
|
body: HTMLImageElement;
|
||||||
|
mirrored: boolean;
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
squash: number;
|
||||||
|
|
||||||
|
bubble: { img: HTMLImageElement; index: number } | null;
|
||||||
|
bubbleText: string | null;
|
||||||
|
charsShown: number;
|
||||||
|
bubbleTextFrame: number;
|
||||||
|
|
||||||
|
scale: number;
|
||||||
|
showShadow: boolean;
|
||||||
|
reflectionOpacity: number;
|
||||||
|
reflectionFade: number;
|
||||||
|
reflectionTint: string;
|
||||||
|
bubbleAnchorX: number;
|
||||||
|
bubbleAnchorY: number;
|
||||||
|
|
||||||
|
chatter: ChatterConfig | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CharacterRenderer {
|
||||||
|
private reflCanvas: HTMLCanvasElement | null = null;
|
||||||
|
private reflCtx: CanvasRenderingContext2D | null = null;
|
||||||
|
private reflW = 0;
|
||||||
|
private reflH = 0;
|
||||||
|
|
||||||
|
draw(input: RenderInput): void {
|
||||||
|
const { ctx, viewW, viewH } = input;
|
||||||
|
ctx.clearRect(0, 0, viewW, viewH);
|
||||||
|
|
||||||
|
const dw = input.body.naturalWidth * input.scale;
|
||||||
|
const dh = input.body.naturalHeight * input.scale;
|
||||||
|
const half = dw / 2;
|
||||||
|
|
||||||
|
if (input.x + half <= 0 || input.x - half >= viewW) return;
|
||||||
|
|
||||||
|
const leftX = Math.round(input.x - half);
|
||||||
|
const feetY = input.groundY - input.y;
|
||||||
|
const topY = feetY - dh;
|
||||||
|
|
||||||
|
this.drawShadow(input, half);
|
||||||
|
this.drawReflection(input, leftX, dw, dh);
|
||||||
|
this.drawBody(input, leftX, feetY, dw, dh, half);
|
||||||
|
this.drawBubble(input, topY);
|
||||||
|
}
|
||||||
|
|
||||||
|
private drawShadow(input: RenderInput, half: number): void {
|
||||||
|
if (!input.showShadow) return;
|
||||||
|
const { ctx, groundY, x, y } = input;
|
||||||
|
const t = Math.min(Math.max(y / 200, 0), 1);
|
||||||
|
const rx = half * 0.75 * (1 - t * 0.5);
|
||||||
|
const ry = Math.max(2, rx * 0.22);
|
||||||
|
ctx.save();
|
||||||
|
ctx.globalAlpha = 0.32 * (1 - t * 0.85);
|
||||||
|
ctx.fillStyle = '#000';
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.ellipse(x, groundY, rx, ry, 0, 0, Math.PI * 2);
|
||||||
|
ctx.fill();
|
||||||
|
ctx.restore();
|
||||||
|
}
|
||||||
|
|
||||||
|
private drawReflection(input: RenderInput, leftX: number, dw: number, dh: number): void {
|
||||||
|
const { y, reflectionOpacity, reflectionFade, reflectionTint, groundY, dpr } = input;
|
||||||
|
const heightFade = Math.max(0, 1 - y / (dh * 4));
|
||||||
|
const alpha = Math.min(Math.max(reflectionOpacity * heightFade, 0), 1);
|
||||||
|
if (alpha <= 0.01) return;
|
||||||
|
|
||||||
|
const rc = this.ensureRefl(dw, dh, dpr);
|
||||||
|
if (!rc) return;
|
||||||
|
|
||||||
|
const pw = this.reflW;
|
||||||
|
const ph = this.reflH;
|
||||||
|
|
||||||
|
rc.save();
|
||||||
|
rc.translate(input.mirrored ? pw : 0, ph);
|
||||||
|
rc.scale(input.mirrored ? -1 : 1, -1);
|
||||||
|
rc.drawImage(input.body, 0, 0, pw, ph);
|
||||||
|
rc.restore();
|
||||||
|
|
||||||
|
rc.globalCompositeOperation = 'source-atop';
|
||||||
|
rc.fillStyle = reflectionTint;
|
||||||
|
rc.fillRect(0, 0, pw, ph);
|
||||||
|
|
||||||
|
rc.globalCompositeOperation = 'destination-out';
|
||||||
|
const grad = rc.createLinearGradient(0, 0, 0, ph);
|
||||||
|
grad.addColorStop(0, 'rgba(0,0,0,0)');
|
||||||
|
grad.addColorStop(1, `rgba(0,0,0,${Math.min(Math.max(reflectionFade, 0), 1)})`);
|
||||||
|
rc.fillStyle = grad;
|
||||||
|
rc.fillRect(0, 0, pw, ph);
|
||||||
|
rc.globalCompositeOperation = 'source-over';
|
||||||
|
|
||||||
|
input.ctx.globalAlpha = alpha;
|
||||||
|
input.ctx.drawImage(this.reflCanvas!, leftX, Math.round(groundY + input.y), dw, dh);
|
||||||
|
input.ctx.globalAlpha = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private drawBody(
|
||||||
|
input: RenderInput,
|
||||||
|
leftX: number,
|
||||||
|
feetY: number,
|
||||||
|
dw: number,
|
||||||
|
dh: number,
|
||||||
|
half: number
|
||||||
|
): void {
|
||||||
|
const { ctx, mirrored, squash, body } = input;
|
||||||
|
const sx = 1 + squash * 0.22;
|
||||||
|
const sy = 1 - squash * 0.22;
|
||||||
|
ctx.save();
|
||||||
|
ctx.translate(leftX + half, feetY);
|
||||||
|
ctx.scale(mirrored ? -sx : sx, sy);
|
||||||
|
ctx.drawImage(body, -half, -dh, dw, dh);
|
||||||
|
ctx.restore();
|
||||||
|
}
|
||||||
|
|
||||||
|
private drawBubble(input: RenderInput, topY: number): void {
|
||||||
|
const bf = input.bubble;
|
||||||
|
if (!bf) return;
|
||||||
|
const { ctx, scale, bubbleAnchorX, bubbleAnchorY, x, chatter } = input;
|
||||||
|
|
||||||
|
const bw = bf.img.naturalWidth * scale;
|
||||||
|
const bh = bf.img.naturalHeight * scale;
|
||||||
|
const ax = x + bubbleAnchorX * scale;
|
||||||
|
const ay = topY - bubbleAnchorY * scale;
|
||||||
|
const bx = Math.round(ax - bw / 2);
|
||||||
|
const by = Math.round(ay - bh);
|
||||||
|
|
||||||
|
ctx.drawImage(bf.img, bx, by, bw, bh);
|
||||||
|
|
||||||
|
if (!input.bubbleText || !chatter) return;
|
||||||
|
if (bf.index < input.bubbleTextFrame) return;
|
||||||
|
drawBubbleText(ctx, input.bubbleText, bx, by, bw, bh, scale, input.charsShown, chatter);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensureRefl(wCss: number, hCss: number, dpr: number): CanvasRenderingContext2D | null {
|
||||||
|
const pw = Math.max(1, Math.round(wCss * dpr));
|
||||||
|
const ph = Math.max(1, Math.round(hCss * dpr));
|
||||||
|
if (!this.reflCanvas) {
|
||||||
|
this.reflCanvas = document.createElement('canvas');
|
||||||
|
this.reflCtx = this.reflCanvas.getContext('2d');
|
||||||
|
}
|
||||||
|
if (!this.reflCtx) return null;
|
||||||
|
if (this.reflW !== pw || this.reflH !== ph) {
|
||||||
|
this.reflCanvas.width = pw;
|
||||||
|
this.reflCanvas.height = ph;
|
||||||
|
this.reflW = pw;
|
||||||
|
this.reflH = ph;
|
||||||
|
}
|
||||||
|
this.reflCtx.setTransform(1, 0, 0, 1, 0, 0);
|
||||||
|
this.reflCtx.globalCompositeOperation = 'source-over';
|
||||||
|
this.reflCtx.globalAlpha = 1;
|
||||||
|
this.reflCtx.clearRect(0, 0, pw, ph);
|
||||||
|
this.reflCtx.imageSmoothingEnabled = false;
|
||||||
|
return this.reflCtx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function wrapText(c: CanvasRenderingContext2D, text: string, maxWidth: number): string[] {
|
||||||
|
const words = text.split(/\s+/).filter(Boolean);
|
||||||
|
const lines: string[] = [];
|
||||||
|
let line = '';
|
||||||
|
for (const word of words) {
|
||||||
|
const candidate = line ? `${line} ${word}` : word;
|
||||||
|
if (c.measureText(candidate).width <= maxWidth) line = candidate;
|
||||||
|
else {
|
||||||
|
if (line) lines.push(line);
|
||||||
|
line = word;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (line) lines.push(line);
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
function drawBubbleText(
|
||||||
|
c: CanvasRenderingContext2D,
|
||||||
|
text: string,
|
||||||
|
bx: number,
|
||||||
|
by: number,
|
||||||
|
bw: number,
|
||||||
|
bh: number,
|
||||||
|
scale: number,
|
||||||
|
charsShown: number,
|
||||||
|
chatter: ChatterConfig
|
||||||
|
): void {
|
||||||
|
const padLeft = (chatter.padding?.left ?? 8) * scale;
|
||||||
|
const padRight = (chatter.padding?.right ?? 8) * scale;
|
||||||
|
const padBottom = (chatter.padding?.bottom ?? 8) * scale;
|
||||||
|
const textTop = (chatter.textTop ?? chatter.padding?.top ?? 8) * scale;
|
||||||
|
|
||||||
|
const maxW = bw - padLeft - padRight;
|
||||||
|
const maxH = bh - textTop - padBottom;
|
||||||
|
if (maxW <= 0 || maxH <= 0) return;
|
||||||
|
|
||||||
|
const size = chatter.fontSize ?? 11;
|
||||||
|
const lineHeight = size * (chatter.lineHeight ?? 1.2);
|
||||||
|
|
||||||
|
c.save();
|
||||||
|
c.font = `${size}px ${chatter.fontFamily ?? 'monospace'}`;
|
||||||
|
c.textBaseline = 'top';
|
||||||
|
c.textAlign = chatter.align === 'left' ? 'left' : 'center';
|
||||||
|
c.fillStyle = chatter.color ?? '#1a1a1a';
|
||||||
|
|
||||||
|
const lines = wrapText(c, text, maxW);
|
||||||
|
const x = chatter.align === 'left' ? bx + padLeft : bx + bw / 2;
|
||||||
|
const y0 = by + textTop;
|
||||||
|
|
||||||
|
let cursor = 0;
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
const line = lines[i];
|
||||||
|
const visible = Math.max(0, Math.min(line.length, charsShown - cursor));
|
||||||
|
if (visible <= 0) break;
|
||||||
|
c.fillText(line.slice(0, visible), x, y0 + i * lineHeight);
|
||||||
|
cursor += line.length;
|
||||||
|
if (visible < line.length) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
c.restore();
|
||||||
|
}
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
import { WebG } from './renderer/web_g_engine';
|
|
||||||
|
|
||||||
export namespace Shimagic {
|
|
||||||
export class Shimeji {
|
|
||||||
private WebGEngine: WebG.Engine;
|
|
||||||
//private PhysisEngine: Physis.Engine;
|
|
||||||
private size!: number;
|
|
||||||
|
|
||||||
private AnimID: number | null = null;
|
|
||||||
private pDeltaT: number = 0;
|
|
||||||
|
|
||||||
constructor(webgengine: WebG.Engine /* physis: Physis.Engine */) {
|
|
||||||
this.WebGEngine = webgengine;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Factory method: Initializes all sub-systems like WebG & Physis aswell as initializes the Shimeji and starts its animation
|
|
||||||
* @async
|
|
||||||
* @public
|
|
||||||
* @param {ShimejiConfig} config - Shimeji configuration
|
|
||||||
* @returns {Promise<Shimeji>} that resolves when the Shimeji is done initializing
|
|
||||||
*/
|
|
||||||
public static async Initialize(config: ShimejiConfig): Promise<Shimeji> {
|
|
||||||
const webg = await WebG.Engine.Initialize(config.webG);
|
|
||||||
//const physis = await Physis.Engine.Initialize(config.physis);
|
|
||||||
|
|
||||||
const shimeji = new Shimeji(webg);
|
|
||||||
shimeji.size = config.size;
|
|
||||||
|
|
||||||
const AFrame = (delta: number) => {
|
|
||||||
shimeji.pDeltaT = delta;
|
|
||||||
shimeji.AnimID = requestAnimationFrame(shimeji._anim);
|
|
||||||
};
|
|
||||||
|
|
||||||
shimeji.AnimID = requestAnimationFrame(AFrame);
|
|
||||||
|
|
||||||
return shimeji;
|
|
||||||
}
|
|
||||||
|
|
||||||
private _anim(delta: number) {
|
|
||||||
let dt = (delta - this.pDeltaT) / 1000;
|
|
||||||
dt = Math.min(dt, 0.05 /* * this.Physis.TIMESCALE */);
|
|
||||||
this.pDeltaT = delta;
|
|
||||||
|
|
||||||
this.UpdatePhysics(dt);
|
|
||||||
this.UpdateFrame(dt);
|
|
||||||
|
|
||||||
this.AnimID = requestAnimationFrame(this._anim);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A function called automatically every "frame" where the code for calculating the next physics frame of the Shimeji is placed
|
|
||||||
* @param delta - Automatically passed in deltaT value;
|
|
||||||
*/
|
|
||||||
private UpdatePhysics(delta: number): void {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A function called automatically every "frame" where the code for drawing the next frame of the Shimeji is placed
|
|
||||||
* @param delta - Automatically passed in deltaT value;
|
|
||||||
*/
|
|
||||||
private UpdateFrame(delta: number): void {}
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ShimejiConfig {
|
|
||||||
sprite: string; //temp soultion to
|
|
||||||
size: number;
|
|
||||||
webG: WebG.EngineConfig;
|
|
||||||
//physis: Physis.EngineConfig;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
const SOUND_RE = /\/sounds\/([^/]+)\/[^/]+\.(wav|mp3|ogg)$/i;
|
||||||
|
|
||||||
|
const files = import.meta.glob('$lib/assets/character/sounds/**/*.{wav,mp3,ogg}', {
|
||||||
|
eager: true,
|
||||||
|
query: '?url',
|
||||||
|
import: 'default'
|
||||||
|
}) as Record<string, string>;
|
||||||
|
|
||||||
|
export interface SoundPack {
|
||||||
|
name: string;
|
||||||
|
buffers: AudioBuffer[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
|
||||||
|
|
||||||
|
function soundPackUrls(): Record<string, string[]> {
|
||||||
|
const groups: Record<string, [string, string][]> = {};
|
||||||
|
|
||||||
|
for (const [path, url] of Object.entries(files)) {
|
||||||
|
const m = SOUND_RE.exec(path);
|
||||||
|
if (!m) continue;
|
||||||
|
const name = m[1].toLowerCase();
|
||||||
|
(groups[name] ??= []).push([path, url]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const out: Record<string, string[]> = {};
|
||||||
|
for (const [name, entries] of Object.entries(groups)) {
|
||||||
|
out[name] = entries.sort(([a], [b]) => collator.compare(a, b)).map(([, url]) => url);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadSoundPacks(ctx: AudioContext): Promise<Record<string, SoundPack>> {
|
||||||
|
const urls = soundPackUrls();
|
||||||
|
const out: Record<string, SoundPack> = {};
|
||||||
|
|
||||||
|
await Promise.all(
|
||||||
|
Object.entries(urls).map(async ([name, list]) => {
|
||||||
|
const buffers: AudioBuffer[] = [];
|
||||||
|
for (const url of list) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(url);
|
||||||
|
const raw = await res.arrayBuffer();
|
||||||
|
buffers.push(await ctx.decodeAudioData(raw));
|
||||||
|
} catch (err) {
|
||||||
|
console.warn(`[sound] failed to load "${url}"`, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (buffers.length) out[name] = { name, buffers };
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SoundPlayer {
|
||||||
|
private cursor: Record<string, number> = {};
|
||||||
|
private muted = false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private ctx: AudioContext,
|
||||||
|
private packs: Record<string, SoundPack>
|
||||||
|
) {}
|
||||||
|
|
||||||
|
has(name: string): boolean {
|
||||||
|
return !!this.packs[name];
|
||||||
|
}
|
||||||
|
|
||||||
|
setMuted(muted: boolean) {
|
||||||
|
this.muted = muted;
|
||||||
|
}
|
||||||
|
|
||||||
|
isMuted(): boolean {
|
||||||
|
return this.muted;
|
||||||
|
}
|
||||||
|
|
||||||
|
play(name: string, volume = 1): void {
|
||||||
|
if (this.muted) return;
|
||||||
|
|
||||||
|
const pack = this.packs[name];
|
||||||
|
if (!pack || !pack.buffers.length) return;
|
||||||
|
|
||||||
|
if (this.ctx.state === 'suspended') void this.ctx.resume();
|
||||||
|
|
||||||
|
const i = (this.cursor[name] ?? 0) % pack.buffers.length;
|
||||||
|
this.cursor[name] = i + 1;
|
||||||
|
|
||||||
|
const src = this.ctx.createBufferSource();
|
||||||
|
src.buffer = pack.buffers[i];
|
||||||
|
|
||||||
|
const gain = this.ctx.createGain();
|
||||||
|
gain.gain.value = Math.max(0, Math.min(1, volume));
|
||||||
|
|
||||||
|
src.connect(gain).connect(this.ctx.destination);
|
||||||
|
src.start();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
import type { Facing } from './types';
|
||||||
|
|
||||||
|
export type { Facing };
|
||||||
|
|
||||||
|
const files = import.meta.glob('$lib/assets/character/states/**/*.png', {
|
||||||
|
eager: true,
|
||||||
|
query: '?url',
|
||||||
|
import: 'default'
|
||||||
|
}) as Record<string, string>;
|
||||||
|
|
||||||
|
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
|
||||||
|
|
||||||
|
/** Matches states/<name>/<file>.png OR states/<name>/<side>/<file>.png */
|
||||||
|
const STATE_RE = /\/states\/([^/]+)\/(?:(left|right)\/)?[^/]+\.png$/i;
|
||||||
|
|
||||||
|
export interface StateSide {
|
||||||
|
frames: string[];
|
||||||
|
/** True if these frames must be drawn flipped. */
|
||||||
|
mirrored: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StatePack {
|
||||||
|
name: string;
|
||||||
|
fps: number;
|
||||||
|
left: StateSide;
|
||||||
|
right: StateSide;
|
||||||
|
/** Reference speed in px/s. When set, playback scales with |vx| / speed. */
|
||||||
|
speed?: number;
|
||||||
|
/** If true, loops. If false, holds on the last frame after one pass. */
|
||||||
|
loop: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StateConfig {
|
||||||
|
fps?: number;
|
||||||
|
speed?: number;
|
||||||
|
loop?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type StateConfigMap = Record<string, StateConfig>;
|
||||||
|
|
||||||
|
export const STATE_CONFIG: StateConfigMap = {
|
||||||
|
idle: { fps: 6 },
|
||||||
|
walk: { fps: 8, speed: 120 },
|
||||||
|
run: { fps: 12, speed: 280 },
|
||||||
|
jump: { fps: 8, loop: false },
|
||||||
|
held: { fps: 8 },
|
||||||
|
falling: { fps: 8 },
|
||||||
|
landing: { fps: 8, loop: false },
|
||||||
|
love: { fps: 8 },
|
||||||
|
drink: { fps: 8, loop: false },
|
||||||
|
play: { fps: 8, loop: false },
|
||||||
|
sleep: { fps: 8, loop: false }
|
||||||
|
};
|
||||||
|
|
||||||
|
export function loadStates(config: StateConfigMap = {}): Record<string, StatePack> {
|
||||||
|
const merged: StateConfigMap = { ...STATE_CONFIG, ...config };
|
||||||
|
|
||||||
|
const grouped = new Map<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
left: Array<[string, string]>;
|
||||||
|
right: Array<[string, string]>;
|
||||||
|
flat: Array<[string, string]>;
|
||||||
|
}
|
||||||
|
>();
|
||||||
|
|
||||||
|
for (const [path, url] of Object.entries(files)) {
|
||||||
|
const m = STATE_RE.exec(path);
|
||||||
|
if (!m) continue;
|
||||||
|
const name = m[1].toLowerCase();
|
||||||
|
const side = m[2]?.toLowerCase();
|
||||||
|
|
||||||
|
let bucket = grouped.get(name);
|
||||||
|
if (!bucket) {
|
||||||
|
bucket = { left: [], right: [], flat: [] };
|
||||||
|
grouped.set(name, bucket);
|
||||||
|
}
|
||||||
|
if (side === 'left') bucket.left.push([path, url]);
|
||||||
|
else if (side === 'right') bucket.right.push([path, url]);
|
||||||
|
else bucket.flat.push([path, url]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const out: Record<string, StatePack> = {};
|
||||||
|
|
||||||
|
for (const [name, buckets] of grouped) {
|
||||||
|
const sortUrls = (arr: Array<[string, string]>) =>
|
||||||
|
arr.sort(([a], [b]) => collator.compare(a, b)).map(([, url]) => url);
|
||||||
|
|
||||||
|
const leftUrls = sortUrls(buckets.left);
|
||||||
|
const rightUrls = sortUrls(buckets.right);
|
||||||
|
const flatUrls = sortUrls(buckets.flat);
|
||||||
|
const cfg = merged[name] ?? {};
|
||||||
|
|
||||||
|
let left: StateSide;
|
||||||
|
let right: StateSide;
|
||||||
|
|
||||||
|
if (leftUrls.length || rightUrls.length) {
|
||||||
|
if (leftUrls.length && rightUrls.length) {
|
||||||
|
left = { frames: leftUrls, mirrored: false };
|
||||||
|
right = { frames: rightUrls, mirrored: false };
|
||||||
|
} else if (leftUrls.length) {
|
||||||
|
left = { frames: leftUrls, mirrored: false };
|
||||||
|
right = { frames: leftUrls, mirrored: true };
|
||||||
|
} else {
|
||||||
|
right = { frames: rightUrls, mirrored: false };
|
||||||
|
left = { frames: rightUrls, mirrored: true };
|
||||||
|
}
|
||||||
|
} else if (flatUrls.length) {
|
||||||
|
left = { frames: flatUrls, mirrored: true };
|
||||||
|
right = { frames: flatUrls, mirrored: false };
|
||||||
|
} else {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
out[name] = {
|
||||||
|
name,
|
||||||
|
fps: cfg.fps ?? 8,
|
||||||
|
left,
|
||||||
|
right,
|
||||||
|
speed: cfg.speed,
|
||||||
|
loop: cfg.loop ?? true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function collectStateUrls(packs: Record<string, StatePack>): string[] {
|
||||||
|
const out = new Set<string>();
|
||||||
|
for (const pack of Object.values(packs)) {
|
||||||
|
for (const url of pack.left.frames) out.add(url);
|
||||||
|
for (const url of pack.right.frames) out.add(url);
|
||||||
|
}
|
||||||
|
return [...out];
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* State resolution */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
export type InteractionState = 'free' | 'held' | 'falling' | 'landing' | 'petted';
|
||||||
|
|
||||||
|
export interface StateContext {
|
||||||
|
interaction: InteractionState;
|
||||||
|
grounded: boolean;
|
||||||
|
speed: number;
|
||||||
|
/** Active need-action state name (e.g. 'drink'), or null. */
|
||||||
|
needAction: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ResolverConfig {
|
||||||
|
idleThreshold: number;
|
||||||
|
runThreshold: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Interaction-state → state-pack-name overrides, in priority order. */
|
||||||
|
const INTERACTION_MAP: Array<[InteractionState, string]> = [
|
||||||
|
['held', 'held'],
|
||||||
|
['falling', 'falling'],
|
||||||
|
['landing', 'landing'],
|
||||||
|
['petted', 'love']
|
||||||
|
];
|
||||||
|
|
||||||
|
export function resolveStateName(
|
||||||
|
ctx: StateContext,
|
||||||
|
cfg: ResolverConfig,
|
||||||
|
packs: Record<string, StatePack>
|
||||||
|
): string {
|
||||||
|
for (const [interactionState, packName] of INTERACTION_MAP) {
|
||||||
|
if (ctx.interaction === interactionState && packs[packName]) return packName;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ctx.needAction && packs[ctx.needAction]) return ctx.needAction;
|
||||||
|
|
||||||
|
if (!ctx.grounded && packs.jump) return 'jump';
|
||||||
|
if (ctx.speed >= cfg.runThreshold && packs.run) return 'run';
|
||||||
|
if (ctx.speed >= cfg.idleThreshold && packs.walk) return 'walk';
|
||||||
|
return 'idle';
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Animation clock */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
export class StateClock {
|
||||||
|
private lastName = '';
|
||||||
|
private elapsed = 0;
|
||||||
|
|
||||||
|
update(dt: number, name: string, pack: StatePack | undefined, speed: number): void {
|
||||||
|
if (name !== this.lastName) {
|
||||||
|
this.lastName = name;
|
||||||
|
this.elapsed = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!pack) return;
|
||||||
|
|
||||||
|
const rate = pack.speed && pack.speed > 0 ? Math.min(Math.max(speed / pack.speed, 0.25), 3) : 1;
|
||||||
|
this.elapsed += dt * rate;
|
||||||
|
}
|
||||||
|
|
||||||
|
get time(): number {
|
||||||
|
return this.elapsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
frameIndex(pack: StatePack, side: StateSide): number {
|
||||||
|
const count = side.frames.length;
|
||||||
|
if (!count) return 0;
|
||||||
|
const raw = Math.floor(this.elapsed * pack.fps);
|
||||||
|
return pack.loop ? raw % count : Math.min(raw, count - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
export type Facing = 'left' | 'right';
|
||||||
|
export type AnimName = 'idle' | 'walk' | 'run' | 'jump';
|
||||||
|
|
||||||
|
export interface Clip {
|
||||||
|
frames: string[];
|
||||||
|
fps: number;
|
||||||
|
speed?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FacingClips {
|
||||||
|
mirrored: boolean;
|
||||||
|
idle: Clip;
|
||||||
|
walk: Clip;
|
||||||
|
run?: Clip;
|
||||||
|
jump?: Clip;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CharacterSprites = Record<Facing, FacingClips>;
|
||||||
|
|
||||||
|
export interface BubblePack {
|
||||||
|
name: string;
|
||||||
|
frames: string[];
|
||||||
|
fps: number;
|
||||||
|
duration: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ActionPack {
|
||||||
|
name: string;
|
||||||
|
frames: string[];
|
||||||
|
fps: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PhysicsInput {
|
||||||
|
direction: -1 | 0 | 1;
|
||||||
|
jump: boolean;
|
||||||
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { WebG } from '$lib/shimagic/renderer/web_g_engine';
|
|
||||||
import type { KeyBind } from '../terminal/keybindRegistry';
|
import type { KeyBind } from '../terminal/keybindRegistry';
|
||||||
import type { Bash, Result } from './bash';
|
import type { Bash, Result } from './bash';
|
||||||
import { cd } from './commands/cd';
|
import { cd } from './commands/cd';
|
||||||
@@ -32,8 +31,6 @@ export const COMMANDS = {
|
|||||||
testProcess
|
testProcess
|
||||||
} as const satisfies Record<string, ICommand>;
|
} as const satisfies Record<string, ICommand>;
|
||||||
|
|
||||||
|
|
||||||
WebG.
|
|
||||||
/* //export const commands {
|
/* //export const commands {
|
||||||
return: {
|
return: {
|
||||||
method: this.cmd_return,
|
method: this.cmd_return,
|
||||||
|
|||||||
@@ -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:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import type { Bash } from './bash';
|
import { FileSystem } from '$lib/termos/filesystem/filesystem';
|
||||||
import type { TreeNode } from './fs';
|
import type { TreeNode } from './fs';
|
||||||
import { Posix } from './posix';
|
|
||||||
|
|
||||||
export enum SortNodeBy {
|
export enum SortNodeBy {
|
||||||
NAME = 'name',
|
NAME = 'name',
|
||||||
@@ -15,11 +14,12 @@ export enum SortNodeBy {
|
|||||||
|
|
||||||
export class Sort {
|
export class Sort {
|
||||||
public static nodeArraySort(
|
public static nodeArraySort(
|
||||||
this: Bash,
|
|
||||||
nodes: TreeNode[] | number[],
|
nodes: TreeNode[] | number[],
|
||||||
reverse: boolean = false,
|
reverse: boolean = false,
|
||||||
sortBy: SortNodeBy = SortNodeBy.NAME
|
sortBy: SortNodeBy = SortNodeBy.NAME
|
||||||
): TreeNode[] {
|
): TreeNode[] {
|
||||||
|
const Fs = FileSystem.instance;
|
||||||
|
|
||||||
if (nodes.length === 0) {
|
if (nodes.length === 0) {
|
||||||
console.warn('Tried to sort an empty node array!');
|
console.warn('Tried to sort an empty node array!');
|
||||||
return [];
|
return [];
|
||||||
@@ -28,7 +28,7 @@ export class Sort {
|
|||||||
|
|
||||||
if (typeof nodes[0] === 'number') {
|
if (typeof nodes[0] === 'number') {
|
||||||
for (const inode of nodes as number[]) {
|
for (const inode of nodes as number[]) {
|
||||||
const node = this.getFs().getNodeByINode(inode);
|
const node = Fs.getNodeByInode(inode);
|
||||||
parsedNodes.push(node);
|
parsedNodes.push(node);
|
||||||
}
|
}
|
||||||
Sort.nodeQSort(parsedNodes, reverse, sortBy, 0, parsedNodes.length - 1);
|
Sort.nodeQSort(parsedNodes, reverse, sortBy, 0, parsedNodes.length - 1);
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
// $lib/stores/petals.ts
|
||||||
|
|
||||||
|
function mulberry32(seed: number): () => number {
|
||||||
|
let a = seed >>> 0;
|
||||||
|
return () => {
|
||||||
|
a = (a + 0x6d2b79f5) | 0;
|
||||||
|
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||||||
|
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||||
|
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function accelPosition(u: number, k: number): number {
|
||||||
|
if (k < 0.01) return u * u;
|
||||||
|
if (k > 50) return u;
|
||||||
|
const denom = k - 1 + Math.exp(-k);
|
||||||
|
return (k * u - 1 + Math.exp(-k * u)) / denom;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PetalsOptions {
|
||||||
|
duration?: number;
|
||||||
|
fallAccel?: number;
|
||||||
|
fallDistance?: number;
|
||||||
|
leadIn?: number;
|
||||||
|
swayAmp?: number;
|
||||||
|
swayCycles?: number;
|
||||||
|
windX?: number;
|
||||||
|
spin?: number;
|
||||||
|
maxKeyframes?: number;
|
||||||
|
seed?: number;
|
||||||
|
hideOriginals?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PetalsCleanup = () => void;
|
||||||
|
|
||||||
|
let callCounter = 0;
|
||||||
|
|
||||||
|
function viewportBottom(): number {
|
||||||
|
const vv = window.visualViewport;
|
||||||
|
if (vv) return vv.height + vv.offsetTop;
|
||||||
|
return Math.max(document.documentElement.clientHeight, window.innerHeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function petals(
|
||||||
|
node: HTMLElement,
|
||||||
|
{
|
||||||
|
duration = 15000,
|
||||||
|
fallAccel = 4,
|
||||||
|
fallDistance,
|
||||||
|
leadIn = 0.18,
|
||||||
|
swayAmp = 22,
|
||||||
|
swayCycles = 2.0,
|
||||||
|
windX = 60,
|
||||||
|
spin = 300,
|
||||||
|
maxKeyframes = 90,
|
||||||
|
seed,
|
||||||
|
hideOriginals = true
|
||||||
|
}: PetalsOptions = {}
|
||||||
|
): PetalsCleanup {
|
||||||
|
const chars = Array.from(node.querySelectorAll<HTMLElement>('.char')).filter(
|
||||||
|
(el) => el.textContent?.trim() !== ''
|
||||||
|
);
|
||||||
|
|
||||||
|
if (chars.length === 0) return () => {};
|
||||||
|
|
||||||
|
const effectiveSeed = seed ?? Date.now() ^ (callCounter++ * 0x9e3779b9);
|
||||||
|
|
||||||
|
const rect = node.getBoundingClientRect();
|
||||||
|
const vb = viewportBottom();
|
||||||
|
|
||||||
|
// ── Clone + fixed overlay ────────────────────────────────────────────
|
||||||
|
const clone = node.cloneNode(true) as HTMLElement;
|
||||||
|
clone.removeAttribute('id');
|
||||||
|
clone.querySelectorAll<HTMLElement>('[id]').forEach((n) => n.removeAttribute('id'));
|
||||||
|
|
||||||
|
clone.querySelectorAll<HTMLElement>('.prompt, .cursor').forEach((n) => {
|
||||||
|
n.style.visibility = 'hidden';
|
||||||
|
});
|
||||||
|
|
||||||
|
clone.style.cssText = `
|
||||||
|
position: fixed;
|
||||||
|
top: ${rect.top}px;
|
||||||
|
left: ${rect.left}px;
|
||||||
|
margin: 0;
|
||||||
|
overflow: visible;
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 9999;
|
||||||
|
contain: layout style;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const origFont = getComputedStyle(node);
|
||||||
|
clone.style.fontSize = origFont.fontSize;
|
||||||
|
clone.style.fontFamily = origFont.fontFamily;
|
||||||
|
clone.style.fontWeight = origFont.fontWeight;
|
||||||
|
clone.style.fontStyle = origFont.fontStyle;
|
||||||
|
clone.style.fontVariant = origFont.fontVariant;
|
||||||
|
clone.style.fontStretch = origFont.fontStretch;
|
||||||
|
clone.style.lineHeight = origFont.lineHeight;
|
||||||
|
clone.style.letterSpacing = origFont.letterSpacing;
|
||||||
|
clone.style.wordSpacing = origFont.wordSpacing;
|
||||||
|
clone.style.color = 'var(--color-text-primary)';
|
||||||
|
clone.style.transition = 'var(--transition-standard)';
|
||||||
|
|
||||||
|
document.body.appendChild(clone);
|
||||||
|
|
||||||
|
if (hideOriginals) {
|
||||||
|
chars.forEach((el) => {
|
||||||
|
el.style.visibility = 'hidden';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const cloneChars = Array.from(clone.querySelectorAll<HTMLElement>('.char'));
|
||||||
|
const petalRects: DOMRect[] = [];
|
||||||
|
for (let i = 0; i < cloneChars.length; i++) {
|
||||||
|
petalRects.push(cloneChars[i].getBoundingClientRect());
|
||||||
|
}
|
||||||
|
|
||||||
|
const anims: Animation[] = [];
|
||||||
|
|
||||||
|
cloneChars.forEach((el, i) => {
|
||||||
|
const rand = mulberry32(effectiveSeed + i * 100003);
|
||||||
|
|
||||||
|
const charDuration = duration * (1.85 + rand() * 1.43);
|
||||||
|
const charAccel = fallAccel * (0.9 + rand() * 0.2);
|
||||||
|
const charSwayCycles = swayCycles * (0.7 + rand() * 0.7);
|
||||||
|
const charLeadIn = leadIn * (0.85 + rand() * 0.3);
|
||||||
|
|
||||||
|
const phase = rand() * Math.PI * 2;
|
||||||
|
const dir: 1 | -1 = rand() < 0.5 ? -1 : 1;
|
||||||
|
const amp = swayAmp * (0.5 + rand() * 0.9);
|
||||||
|
const spinTotal = spin * (0.7 + rand() * 0.6) * dir;
|
||||||
|
const charWindX = windX * (0.5 + rand() * 1.0);
|
||||||
|
|
||||||
|
let charFall: number;
|
||||||
|
if (fallDistance != null) {
|
||||||
|
charFall = fallDistance * (0.95 + rand() * 0.15);
|
||||||
|
} else {
|
||||||
|
const petalRect = petalRects[i];
|
||||||
|
const neededFall = vb - petalRect.top + petalRect.height + 40;
|
||||||
|
charFall = neededFall * (1 + rand() * 0.35);
|
||||||
|
}
|
||||||
|
|
||||||
|
const N = Math.min(maxKeyframes, Math.max(40, Math.round(charDuration / 200)));
|
||||||
|
const frames: Keyframe[] = [];
|
||||||
|
|
||||||
|
for (let k = 0; k <= N; k++) {
|
||||||
|
const t = k / N;
|
||||||
|
const y = charFall * accelPosition(t, charAccel);
|
||||||
|
|
||||||
|
const lead = Math.min(1, t / charLeadIn);
|
||||||
|
const leadSmooth = lead * lead * (3 - 2 * lead);
|
||||||
|
|
||||||
|
const sway = amp * leadSmooth * Math.sin(2 * Math.PI * charSwayCycles * t + phase);
|
||||||
|
const wind = charWindX * t;
|
||||||
|
const x = sway + wind;
|
||||||
|
|
||||||
|
const r = spinTotal * t;
|
||||||
|
|
||||||
|
frames.push({
|
||||||
|
transform: `translate(${x.toFixed(2)}px, ${y.toFixed(2)}px) rotate(${r.toFixed(2)}deg)`,
|
||||||
|
offset: t
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
anims.push(
|
||||||
|
el.animate(frames, {
|
||||||
|
duration: charDuration,
|
||||||
|
delay: 0,
|
||||||
|
easing: 'linear',
|
||||||
|
fill: 'forwards'
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
let cleaned = false;
|
||||||
|
const doCleanup = (): void => {
|
||||||
|
if (cleaned) return;
|
||||||
|
cleaned = true;
|
||||||
|
for (const a of anims) a.cancel();
|
||||||
|
clone.remove();
|
||||||
|
if (hideOriginals) {
|
||||||
|
chars.forEach((el) => {
|
||||||
|
el.style.visibility = '';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
void Promise.allSettled(anims.map((a) => a.finished)).then(doCleanup);
|
||||||
|
|
||||||
|
return doCleanup;
|
||||||
|
}
|
||||||
@@ -1,336 +1,370 @@
|
|||||||
import Vector2 from "../vector";
|
|
||||||
|
|
||||||
export class Shimeji {
|
export class Shimeji {
|
||||||
private element: HTMLElement;
|
private element: HTMLElement;
|
||||||
private canvas: HTMLCanvasElement;
|
|
||||||
private rect: DOMRect;
|
|
||||||
|
|
||||||
private pos: Vector2 = Vector2.zero;
|
// Position and velocity
|
||||||
private vel: Vector2 = Vector2.zero;
|
private x: number = 0;
|
||||||
|
private y: number = 0;
|
||||||
|
private velocityX: number = 0;
|
||||||
|
private velocityY: number = 0;
|
||||||
|
|
||||||
private angle: number = 0; // radians
|
// Mouse tracking
|
||||||
private angularVelocity: number = 0; // rad/s
|
private mouseX: number = 0;
|
||||||
private inertia: number; // kg·m²
|
private mouseY: number = 0;
|
||||||
private localGrip: Vector2 = Vector2.zero; // offset from center (body‑fixed)
|
private mouseAccelX: number = 0;
|
||||||
|
private mouseAccelY: number = 0;
|
||||||
|
|
||||||
private mousePos: Vector2 = Vector2.zero;
|
// Throw detection - track mouse movement history
|
||||||
|
private mouseHistory: Array<{ x: number; y: number; time: number }> = [];
|
||||||
|
private readonly HISTORY_LENGTH: number = 5;
|
||||||
|
|
||||||
private pivot: Vector2 = Vector2.zero;
|
private isBeingDragged: boolean = false;
|
||||||
|
|
||||||
private isBeingDragged: boolean = false;
|
private rafId: number | null = null;
|
||||||
|
|
||||||
private rafId: number | null = null;
|
// Physics parameters
|
||||||
private prevDeltaTime: number = 0;
|
private readonly STIFFNESS: number = 0.85;
|
||||||
|
private readonly DAMPING: number = 0.6;
|
||||||
|
private readonly MASS: number = 1.0;
|
||||||
|
|
||||||
|
// Gravity (pixels per frame squared)
|
||||||
|
private gravity: number = 10;
|
||||||
|
|
||||||
private readonly RESTITUTION: number = 0.6;
|
// Bounce coefficients (energy retention - lower = less bounce)
|
||||||
private readonly STIFFNESS: number = 500;
|
private readonly WALL_BOUNCE: number = 0.5; // Walls lose 50% energy
|
||||||
private readonly DAMPING: number = 1;
|
private readonly FLOOR_BOUNCE: number = 0.6; // Floor loses 40% energy (realistic)
|
||||||
private readonly MASS: number = 10.0;
|
private readonly CEILING_BOUNCE: number = 0.4; // Ceiling loses 60% energy
|
||||||
private readonly FRICTION: number = 0.9;
|
|
||||||
private readonly GRAVITY: number = 10;
|
|
||||||
|
|
||||||
private bounds: { minX: number; minY: number; maxX: number; maxY: number };
|
// Minimum velocity to continue bouncing
|
||||||
|
private readonly MIN_BOUNCE_VELOCITY: number = 2;
|
||||||
|
|
||||||
constructor(element: HTMLElement, canvas: HTMLCanvasElement) {
|
// Boundaries
|
||||||
this.element = element;
|
private bounds: { minX: number; minY: number; maxX: number; maxY: number };
|
||||||
this.canvas= canvas;
|
|
||||||
this.rect = element.getBoundingClientRect();
|
|
||||||
|
|
||||||
this.bounds = {
|
// Optional forces
|
||||||
minX: 0,
|
private wind: number = 0;
|
||||||
minY: 0,
|
private friction: number = 0.98;
|
||||||
maxX: window.innerWidth,
|
|
||||||
maxY: window.innerHeight
|
|
||||||
};
|
|
||||||
|
|
||||||
this.inertia = (1 / 12) *
|
// Track if on ground for additional effects
|
||||||
this.MASS * (this.rect.width * this.rect.width + this.rect.height * this.rect.height);
|
private wasOnGround: boolean = false;
|
||||||
|
private bounceCount: number = 0;
|
||||||
|
|
||||||
this.pos.set(window.innerWidth / 2, window.innerHeight/ 2);
|
constructor(element: HTMLElement) {
|
||||||
|
this.element = element;
|
||||||
|
|
||||||
this.updateBounds();
|
// Initialize bounds (will update on resize)
|
||||||
window.addEventListener('resize', () => this.updateBounds());
|
this.bounds = {
|
||||||
|
minX: 0,
|
||||||
|
minY: 0,
|
||||||
|
maxX: window.innerWidth,
|
||||||
|
maxY: window.innerHeight
|
||||||
|
};
|
||||||
|
|
||||||
console.log(this.element.getBoundingClientRect());
|
// Start with element at center
|
||||||
|
this.x = window.innerWidth / 2;
|
||||||
|
this.y = window.innerHeight / 2;
|
||||||
|
|
||||||
this.setupDragEvents();
|
this.updateBounds();
|
||||||
}
|
window.addEventListener('resize', () => this.updateBounds());
|
||||||
|
|
||||||
private updateBounds(): void {
|
this.setupDragEvents();
|
||||||
this.bounds = {
|
}
|
||||||
minX: 0,
|
|
||||||
minY: 0,
|
|
||||||
maxX: window.innerWidth,
|
|
||||||
maxY: window.innerHeight
|
|
||||||
};
|
|
||||||
|
|
||||||
this.canvas.width = window.innerWidth;
|
private updateBounds(): void {
|
||||||
this.canvas.height = window.innerHeight;
|
this.bounds = {
|
||||||
}
|
minX: 0,
|
||||||
|
minY: 0,
|
||||||
|
maxX: window.innerWidth,
|
||||||
|
maxY: window.innerHeight
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
start(): void {
|
start(): void {
|
||||||
if (this.rafId !== null) return;
|
if (this.rafId !== null) return;
|
||||||
|
|
||||||
const firstFrame = (delta: number) => {
|
const animate = () => {
|
||||||
this.prevDeltaTime = delta;
|
this.updatePhysics();
|
||||||
this.rafId = requestAnimationFrame(animate);
|
this.applyBoundaries();
|
||||||
}
|
this.render();
|
||||||
|
this.rafId = requestAnimationFrame(animate);
|
||||||
|
};
|
||||||
|
|
||||||
const animate = (delta: number) => {
|
this.rafId = requestAnimationFrame(animate);
|
||||||
const dt: number = Math.min(delta - this.prevDeltaTime, 0.05);
|
}
|
||||||
this.prevDeltaTime = delta;
|
|
||||||
|
|
||||||
this.updatePhysics(dt);
|
stop(): void {
|
||||||
this.applyBoundaries();
|
if (this.rafId !== null) {
|
||||||
this.render();
|
cancelAnimationFrame(this.rafId);
|
||||||
this.rafId = requestAnimationFrame(animate);
|
this.rafId = null;
|
||||||
};
|
}
|
||||||
|
}
|
||||||
|
|
||||||
this.rafId = requestAnimationFrame(firstFrame);
|
private setupDragEvents(): void {
|
||||||
}
|
this.element.addEventListener('mousedown', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
this.isBeingDragged = true;
|
||||||
|
this.element.style.cursor = 'grabbing';
|
||||||
|
|
||||||
stop(): void {
|
// Clear mouse history on new drag
|
||||||
if (this.rafId !== null) {
|
this.mouseHistory = [];
|
||||||
cancelAnimationFrame(this.rafId);
|
});
|
||||||
this.rafId = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private getCornerWorld(lx: number, ly: number): Vector2 {
|
// Track mouse movement globally for better throw detection
|
||||||
// lx, ly are in local coordinates (relative to center, with rotation)
|
document.addEventListener('mousemove', (e) => {
|
||||||
const cos = Math.cos(this.angle);
|
if (this.isBeingDragged) {
|
||||||
const sin = Math.sin(this.angle);
|
this.mouseX = e.pageX;
|
||||||
return new Vector2(
|
this.mouseY = e.pageY;
|
||||||
this.pos.x + (lx * cos - ly * sin),
|
this.mouseAccelX = e.movementX;
|
||||||
this.pos.y + (lx * sin + ly * cos)
|
this.mouseAccelY = e.movementY;
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private setupDragEvents(): void {
|
// Store mouse position history for throw calculation
|
||||||
this.element.addEventListener('mousedown', (e) => {
|
this.mouseHistory.push({
|
||||||
e.preventDefault();
|
x: e.pageX,
|
||||||
this.isBeingDragged = true;
|
y: e.pageY,
|
||||||
this.element.style.cursor = 'grabbing';
|
time: Date.now()
|
||||||
|
});
|
||||||
|
|
||||||
const parent = this.element.parentElement;
|
// Keep only recent history
|
||||||
if(parent) parent.style.cursor = 'grabbing';
|
if (this.mouseHistory.length > this.HISTORY_LENGTH) {
|
||||||
|
this.mouseHistory.shift();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const clickWorld = new Vector2(e.pageX, e.pageY);
|
this.element.addEventListener('mouseup', (e) => {
|
||||||
const center = this.pos;
|
if (this.isBeingDragged) {
|
||||||
const offset = clickWorld.sub(center)
|
this.isBeingDragged = false;
|
||||||
const cos = Math.cos(-this.angle);
|
this.element.style.cursor = 'grab';
|
||||||
const sin = Math.sin(-this.angle);
|
|
||||||
|
|
||||||
this.localGrip = new Vector2(
|
// Calculate throw velocity based on mouse movement speed
|
||||||
offset.x * cos - offset.y * sin,
|
this.applyThrowVelocity();
|
||||||
offset.x * sin + offset.y * cos
|
|
||||||
);
|
|
||||||
|
|
||||||
this.pivot.x = e.offsetX - this.rect.width / 2;
|
// Reset mouse history
|
||||||
this.pivot.y = e.offsetY - this.rect.height / 2;
|
this.mouseHistory = [];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
});
|
this.element.addEventListener('dragstart', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
document.addEventListener('mousemove', (e) => {
|
private applyThrowVelocity(): void {
|
||||||
this.mousePos.x = e.pageX;
|
if (this.mouseHistory.length < 2) return;
|
||||||
this.mousePos.y = e.pageY;
|
|
||||||
});
|
|
||||||
|
|
||||||
document.addEventListener('mouseup', (e) => {
|
// Get oldest and newest mouse positions
|
||||||
if(this.isBeingDragged) {
|
const oldest = this.mouseHistory[0];
|
||||||
this.isBeingDragged = false;
|
const newest = this.mouseHistory[this.mouseHistory.length - 1];
|
||||||
this.element.style.cursor = 'grab';
|
|
||||||
|
|
||||||
const parent = this.element.parentElement;
|
// Calculate time delta in seconds
|
||||||
if(parent) parent.style.cursor = 'auto';
|
const timeDelta = (newest.time - oldest.time) / 1000;
|
||||||
|
if (timeDelta === 0) return;
|
||||||
|
|
||||||
this.pivot = Vector2.zero;
|
// Calculate velocity in pixels per second
|
||||||
}
|
let throwVelX = (newest.x - oldest.x) / timeDelta;
|
||||||
|
let throwVelY = (newest.y - oldest.y) / timeDelta;
|
||||||
|
|
||||||
this.canvas.getContext('2d')!.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
// Cap maximum throw velocity to prevent ridiculous speeds
|
||||||
});
|
const MAX_THROW_SPEED = 50;
|
||||||
|
throwVelX = Math.min(Math.max(throwVelX, -MAX_THROW_SPEED), MAX_THROW_SPEED);
|
||||||
|
throwVelY = Math.min(Math.max(throwVelY, -MAX_THROW_SPEED), MAX_THROW_SPEED);
|
||||||
|
|
||||||
this.element.addEventListener('dragstart', (e) => {
|
// Apply throw velocity (divide by ~60 to convert from per-second to per-frame)
|
||||||
e.preventDefault();
|
this.velocityX += throwVelX / 60;
|
||||||
});
|
this.velocityY += throwVelY / 60;
|
||||||
}
|
|
||||||
|
|
||||||
private updatePhysics(dt: number): void {
|
// Add a little extra oomph based on acceleration
|
||||||
|
if (Math.abs(this.mouseAccelX) > 5) {
|
||||||
|
this.velocityX += this.mouseAccelX / 30;
|
||||||
|
}
|
||||||
|
if (Math.abs(this.mouseAccelY) > 5) {
|
||||||
|
this.velocityY += this.mouseAccelY / 30;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const cos = Math.cos(this.angle);
|
private updatePhysics(): void {
|
||||||
const sin = Math.sin(this.angle);
|
// Apply spring force toward mouse when dragging
|
||||||
const gripWorld = new Vector2(
|
if (this.isBeingDragged) {
|
||||||
this.pos.x + (this.localGrip.x * cos - this.localGrip.y * sin),
|
const dx = this.mouseX - this.x;
|
||||||
this.pos.y + (this.localGrip.x * sin + this.localGrip.y * cos)
|
const dy = this.mouseY - this.y;
|
||||||
);
|
|
||||||
|
|
||||||
if (this.isBeingDragged) {
|
const forceX = dx * this.STIFFNESS;
|
||||||
const direction: Vector2 = this.mousePos.sub(gripWorld);
|
const forceY = dy * this.STIFFNESS;
|
||||||
|
|
||||||
const force: Vector2 = direction.mul(this.STIFFNESS);
|
// Apply force to acceleration (F = ma)
|
||||||
|
const accelerationX = (forceX + this.mouseAccelX) / this.MASS;
|
||||||
|
const accelerationY = (forceY + this.mouseAccelY) / this.MASS;
|
||||||
|
|
||||||
const acceleration: Vector2 = force.div(this.MASS).deadZone(0.001);
|
// Update velocity with acceleration
|
||||||
|
this.velocityX += accelerationX;
|
||||||
|
this.velocityY += accelerationY;
|
||||||
|
}
|
||||||
|
|
||||||
acceleration.mulEq(dt);
|
// Apply gravity (always present, but stronger when not dragging)
|
||||||
|
if (!this.isBeingDragged) {
|
||||||
|
this.velocityY += this.gravity;
|
||||||
|
} else {
|
||||||
|
// Slight gravity even when dragging for realism
|
||||||
|
this.velocityY += this.gravity * 0.3;
|
||||||
|
}
|
||||||
|
|
||||||
this.vel.addEq(acceleration);
|
// Apply wind (optional horizontal force)
|
||||||
this.vel.mulEq(0.8);
|
if (this.y > 10) this.velocityX += this.wind;
|
||||||
|
|
||||||
const r = gripWorld.sub(this.pos);
|
// Apply damping (air resistance)
|
||||||
const torque = r.cross(force);
|
this.velocityX *= this.DAMPING;
|
||||||
this.angularVelocity += (torque / this.inertia) * dt;
|
this.velocityY *= this.DAMPING;
|
||||||
}
|
|
||||||
|
|
||||||
this.vel.y += this.GRAVITY;
|
// Update position with velocity
|
||||||
this.vel.mulEq(this.DAMPING);
|
this.x += this.velocityX;
|
||||||
|
this.y += this.velocityY;
|
||||||
|
}
|
||||||
|
|
||||||
if (this.pos.y + this.rect.width >= this.bounds.maxY) {
|
private getElementHeight(): number {
|
||||||
this.vel.x *= this.FRICTION;
|
return this.element.offsetHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
const outVel = this.vel.mul(dt);
|
private getElementWidth(): number {
|
||||||
this.pos.addEq(outVel);
|
return this.element.offsetWidth;
|
||||||
|
}
|
||||||
|
|
||||||
this.angle += this.angularVelocity * dt;
|
private applyBoundaries(): void {
|
||||||
this.angle %= 2 * Math.PI;
|
const elementWidth = this.getElementWidth();
|
||||||
}
|
const elementHeight = this.getElementHeight();
|
||||||
|
|
||||||
private applyBoundaries(): void {
|
// X-axis boundaries with realistic bounce
|
||||||
const w = this.rect.width / 2;
|
const leftBound = elementWidth / 2;
|
||||||
const h = this.rect.height / 2;
|
const rightBound = this.bounds.maxX - elementWidth / 2;
|
||||||
|
|
||||||
// List of corners in local coordinates (four combinations)
|
if (this.x < leftBound) {
|
||||||
const corners = [
|
this.x = leftBound;
|
||||||
{ lx: w, ly: h }, // top‑right
|
// Bounce with energy loss
|
||||||
{ lx: w, ly: -h }, // bottom‑right
|
this.velocityX = -Math.abs(this.velocityX) * this.WALL_BOUNCE;
|
||||||
{ lx: -w, ly: h }, // top‑left
|
|
||||||
{ lx: -w, ly: -h } // bottom‑left
|
|
||||||
];
|
|
||||||
|
|
||||||
// Check each wall
|
// Stop if bounce is too small
|
||||||
// Left wall (x = leftBound)
|
if (Math.abs(this.velocityX) < this.MIN_BOUNCE_VELOCITY) {
|
||||||
const leftBound = w;
|
this.velocityX = 0;
|
||||||
for (const corner of corners) {
|
}
|
||||||
const world = this.getCornerWorld(corner.lx, corner.ly);
|
} else if (this.x > rightBound) {
|
||||||
if (world.x < leftBound) {
|
this.x = rightBound;
|
||||||
// Penetration depth (distance from wall to corner)
|
this.velocityX = -Math.abs(this.velocityX) * this.WALL_BOUNCE;
|
||||||
const penetration = leftBound - world.x;
|
|
||||||
// Normal points to the right (+x)
|
|
||||||
const normal = new Vector2(1, 0);
|
|
||||||
// Contact point is the wall at corner's y (or clamp to avoid escaping)
|
|
||||||
const contactY = Math.min(Math.max(world.y, this.bounds.minY + h), this.bounds.maxY - h);
|
|
||||||
const contactPoint = new Vector2(leftBound, contactY);
|
|
||||||
this.resolveCollision(normal, contactPoint);
|
|
||||||
// Reposition to avoid continuous penetration
|
|
||||||
this.pos.x = leftBound - w;
|
|
||||||
return; // after one correction, stop checking further walls to avoid multiple impulses
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Right wall (x = rightBound)
|
if (Math.abs(this.velocityX) < this.MIN_BOUNCE_VELOCITY) {
|
||||||
const rightBound = this.bounds.maxX - w;
|
this.velocityX = 0;
|
||||||
for (const corner of corners) {
|
}
|
||||||
const world = this.getCornerWorld(corner.lx, corner.ly);
|
}
|
||||||
if (world.x > rightBound) {
|
|
||||||
const penetration = world.x - rightBound;
|
|
||||||
const normal = new Vector2(-1, 0);
|
|
||||||
const contactY = Math.min(Math.max(world.y, this.bounds.minY + h), this.bounds.maxY - h);
|
|
||||||
const contactPoint = new Vector2(rightBound, contactY);
|
|
||||||
this.resolveCollision(normal, contactPoint);
|
|
||||||
this.pos.x = rightBound + w;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Top wall (y = topBound)
|
// Y-axis boundaries with realistic bounce
|
||||||
const topBound = h;
|
const topBound = elementHeight / 2;
|
||||||
for (const corner of corners) {
|
const bottomBound = this.bounds.maxY - elementHeight / 2;
|
||||||
const world = this.getCornerWorld(corner.lx, corner.ly);
|
|
||||||
if (world.y < topBound) {
|
|
||||||
const penetration = topBound - world.y;
|
|
||||||
const normal = new Vector2(0, 1);
|
|
||||||
const contactX = Math.min(Math.max(world.x, leftBound), rightBound);
|
|
||||||
const contactPoint = new Vector2(contactX, topBound);
|
|
||||||
this.resolveCollision(normal, contactPoint);
|
|
||||||
this.pos.y = topBound - h;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bottom wall (y = bottomBound)
|
// Ceiling collision
|
||||||
const bottomBound = this.bounds.maxY - h;
|
if (this.y < topBound) {
|
||||||
for (const corner of corners) {
|
this.y = topBound;
|
||||||
const world = this.getCornerWorld(corner.lx, corner.ly);
|
this.velocityY = -this.velocityY * this.CEILING_BOUNCE;
|
||||||
if (world.y > bottomBound) {
|
|
||||||
const penetration = world.y - bottomBound;
|
// Stop tiny bouncing on ceiling
|
||||||
const normal = new Vector2(0, -1);
|
if (Math.abs(this.velocityY) < this.MIN_BOUNCE_VELOCITY) {
|
||||||
const contactX = Math.min(Math.max(world.x, leftBound), rightBound);
|
this.velocityY = 0;
|
||||||
const contactPoint = new Vector2(contactX, bottomBound);
|
}
|
||||||
this.resolveCollision(normal, contactPoint);
|
}
|
||||||
this.pos.y = bottomBound + h;
|
// Floor collision
|
||||||
return;
|
else if (this.y > bottomBound) {
|
||||||
}
|
this.y = bottomBound;
|
||||||
}
|
|
||||||
}
|
const impactSpeed = Math.abs(this.velocityY);
|
||||||
|
|
||||||
private resolveCollision(normal: Vector2, contactPoint: Vector2): void {
|
// Only bounce if impact speed is significant
|
||||||
// Vector from center to contact point
|
if (impactSpeed > this.MIN_BOUNCE_VELOCITY) {
|
||||||
const r = contactPoint.sub(this.pos);
|
// Apply floor bounce with energy loss
|
||||||
|
this.velocityY = -this.velocityY * this.FLOOR_BOUNCE;
|
||||||
// Velocity of the contact point
|
|
||||||
const v_rel = this.vel.clone();
|
// Bounce gets smaller each time naturally due to energy loss
|
||||||
// Add tangential component from angular velocity: ω × r
|
this.bounceCount++;
|
||||||
v_rel.x -= this.angularVelocity * r.y;
|
|
||||||
v_rel.y += this.angularVelocity * r.x;
|
// Apply ground friction on bounce
|
||||||
|
this.velocityX *= this.groundFriction;
|
||||||
// Relative velocity along normal
|
|
||||||
const vn = v_rel.dot(normal);
|
// Optional: Visual feedback for bounce
|
||||||
if (vn > 0) return; // Already separating
|
// console.log(`Bounce ${this.bounceCount}: impact speed ${impactSpeed.toFixed(2)}, new velocity ${this.velocityY.toFixed(2)}`);
|
||||||
|
} else {
|
||||||
// Impulse numerator
|
// Stop bouncing when energy is too low
|
||||||
const numerator = -(1 + this.RESTITUTION) * vn;
|
this.velocityY = 0;
|
||||||
|
this.wasOnGround = true;
|
||||||
// Denominator: 1/m + (r × n)^2 / I
|
}
|
||||||
const r_cross_n = r.cross(normal);
|
} else {
|
||||||
const denominator = 1 / this.MASS + (r_cross_n * r_cross_n) / this.inertia;
|
this.wasOnGround = false;
|
||||||
|
// Reset bounce count when in air
|
||||||
const j = numerator / denominator;
|
if (!this.isBeingDragged && this.velocityY !== 0) {
|
||||||
const impulse = normal.mul(j);
|
this.bounceCount = 0;
|
||||||
|
}
|
||||||
// Apply impulse
|
}
|
||||||
this.vel.addEq(impulse.div(this.MASS));
|
}
|
||||||
this.angularVelocity += r.cross(impulse) / this.inertia;
|
|
||||||
}
|
private get groundFriction(): number {
|
||||||
|
// More friction when moving fast
|
||||||
private drawRay(pos1: {x: number, y: number}, pos2: {x: number, y: number}) {
|
const speed = Math.abs(this.velocityX);
|
||||||
const ctx = this.canvas.getContext("2d")!;
|
if (speed > 10) return this.friction * 0.9;
|
||||||
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
if (speed > 5) return this.friction * 0.95;
|
||||||
ctx.strokeStyle = "white";
|
return this.friction;
|
||||||
ctx.lineWidth = 0.1
|
}
|
||||||
ctx.beginPath();
|
|
||||||
ctx.moveTo(pos1.x, pos1.y);
|
private render(): void {
|
||||||
ctx.lineTo(pos2.x, pos2.y);
|
this.element.style.transform = `translate(${this.x}px, ${this.y}px) translateY(-50%)`;
|
||||||
ctx.stroke();
|
}
|
||||||
}
|
|
||||||
|
// Public methods to control physics
|
||||||
private render(): void {
|
setGravity(value: number): void {
|
||||||
this.element.style.transform = `translate(${this.pos.x}px, ${this.pos.y}px) rotate(${this.angle * 180 / Math.PI}deg)`;
|
this.gravity = value;
|
||||||
|
}
|
||||||
/* if(this.isBeingDragged) {
|
|
||||||
this.drawRay(
|
setWind(value: number): void {
|
||||||
{x: this.mousePos.x, y: this.mousePos.y},
|
this.wind = value;
|
||||||
{x: this.pos.x + this.pivot.x, y: this.pos.y + this.pivot.y}
|
}
|
||||||
)
|
|
||||||
} */
|
setPhysics(stiffness: number, damping: number, mass: number = 1.0): void {
|
||||||
}
|
(this as any).STIFFNESS = stiffness;
|
||||||
|
(this as any).DAMPING = damping;
|
||||||
addImpulse(x: number, y: number): void {
|
(this as any).MASS = mass;
|
||||||
this.vel.x += x;
|
}
|
||||||
this.vel.y += y;
|
|
||||||
}
|
setFriction(value: number): void {
|
||||||
|
this.friction = value;
|
||||||
moveTo(pos: number) {
|
}
|
||||||
|
|
||||||
}
|
// Configure bounce properties
|
||||||
|
setBounceProperties(wall: number, floor: number, ceiling: number = 0.4): void {
|
||||||
|
(this as any).WALL_BOUNCE = Math.min(Math.max(wall, 0), 1);
|
||||||
|
(this as any).FLOOR_BOUNCE = Math.min(Math.max(floor, 0), 1);
|
||||||
|
(this as any).CEILING_BOUNCE = Math.min(Math.max(ceiling, 0), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add impulse (like a jump)
|
||||||
|
addImpulse(x: number, y: number): void {
|
||||||
|
this.velocityX += x;
|
||||||
|
this.velocityY += y;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset position
|
||||||
|
resetPosition(x?: number, y?: number): void {
|
||||||
|
this.x = x ?? this.bounds.maxX / 2;
|
||||||
|
this.y = y ?? this.bounds.maxY / 2;
|
||||||
|
this.velocityX = 0;
|
||||||
|
this.velocityY = 0;
|
||||||
|
this.isBeingDragged = false;
|
||||||
|
this.bounceCount = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
getState() {
|
||||||
|
return {
|
||||||
|
x: this.x,
|
||||||
|
y: this.y,
|
||||||
|
velocityX: this.velocityX,
|
||||||
|
velocityY: this.velocityY,
|
||||||
|
mouseX: this.mouseX,
|
||||||
|
mouseY: this.mouseY,
|
||||||
|
isBeingDragged: this.isBeingDragged,
|
||||||
|
isOnGround: this.wasOnGround,
|
||||||
|
bounceCount: this.bounceCount
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -33,8 +33,6 @@ export type PageCallbacks = {
|
|||||||
getFontSize: () => number;
|
getFontSize: () => number;
|
||||||
};
|
};
|
||||||
|
|
||||||
TermOS.Shell;
|
|
||||||
|
|
||||||
export class Terminal {
|
export class Terminal {
|
||||||
private _bash: Bash;
|
private _bash: Bash;
|
||||||
private _callbacks: Partial<PageCallbacks> = {};
|
private _callbacks: Partial<PageCallbacks> = {};
|
||||||
|
|||||||
@@ -1,17 +1,30 @@
|
|||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store';
|
||||||
|
|
||||||
function getInitalTheme(): string {
|
function getInitialTheme(): string {
|
||||||
if (typeof window === 'undefined') return 'dark';
|
// On client, read from the data-theme attribute set by the blocking script
|
||||||
|
if (typeof document !== 'undefined') {
|
||||||
const savedTheme: string | null = localStorage.getItem('theme');
|
const theme = document.documentElement.getAttribute('data-theme');
|
||||||
if (savedTheme === 'dark' || savedTheme === 'light') return savedTheme;
|
if (theme === 'dark' || theme === 'light') return theme;
|
||||||
|
}
|
||||||
const sysPrefTheme = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
// Fallback (SSR or if script failed)
|
||||||
return sysPrefTheme ? 'dark' : 'light';
|
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) => {
|
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');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,109 +1,233 @@
|
|||||||
import type { User } from '../shell/shell';
|
import type { User } from '../shell/shell';
|
||||||
import { MD5 } from '../util/hash';
|
|
||||||
|
|
||||||
export class FileSystem {
|
export class FileSystem {
|
||||||
static #instance: FileSystem;
|
static #instance: FileSystem | null = null;
|
||||||
private _fs: Map<number, TreeNode>;
|
|
||||||
private _root: number;
|
|
||||||
|
|
||||||
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;
|
this._root = this._fs.values().next().value!.inode;
|
||||||
|
|
||||||
if (!this._root) throw new Error('First entry in the filesystem map empty!');
|
if (!this._root) throw new Error('First entry in the filesystem map empty!');
|
||||||
|
|
||||||
|
await this.loadProtectedNodesConfig();
|
||||||
|
this.applyLocalEdits();
|
||||||
|
this.applyLocalDeletions();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Init() {
|
private async loadProtectedNodesConfig(): Promise<void> {
|
||||||
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> {
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(path);
|
const response = await fetch(`/api/v1/config`);
|
||||||
if (!response.ok) {
|
if (!response.ok) return;
|
||||||
throw new Error(`HTTP error! status: ${response.status}`);
|
|
||||||
|
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 applyLocalEdits(): void {
|
||||||
|
const cache = localStorage.getItem(STORAGE_KEYS.edits);
|
||||||
|
if (!cache) return;
|
||||||
|
|
||||||
|
const edits: Record<number, TreeNode> = JSON.parse(cache);
|
||||||
|
|
||||||
|
for (const [inodeStr, node] of Object.entries(edits)) {
|
||||||
|
const inode = Number(inodeStr);
|
||||||
|
if (this._protectedNodes.has(inode)) continue;
|
||||||
|
|
||||||
|
this._fs.set(inode, node);
|
||||||
|
|
||||||
|
if (!node.parent && !this._fs.has(node.parent)) continue;
|
||||||
|
|
||||||
|
const parent = this._fs.get(node.parent)!;
|
||||||
|
|
||||||
|
if (parent.children.includes(inode)) {
|
||||||
|
parent.children.push(inode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.text();
|
if (node.parent && this._fs.has(node.parent)) {
|
||||||
return data.slice(0, 36); //32 characters of uuid + 4 dashes
|
const parent = this._fs.get(node.parent)!;
|
||||||
} catch (error) {
|
parent.children = parent.children.filter((child) => child !== inode);
|
||||||
console.error('Failed to fetch the file system signature', error);
|
}
|
||||||
|
|
||||||
|
this._fs.delete(inode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async fetchFsJson(sig: string): Promise<JSON> {
|
private static _cloneFs(source: Map<number, TreeNode>): Map<number, TreeNode> {
|
||||||
const signature: string | null = localStorage.getItem('signature');
|
const copy = new Map<number, TreeNode>();
|
||||||
|
|
||||||
if (signature !== sig || signature === null || localStorage.getItem('fs') === null) {
|
for (const [inode, node] of source) {
|
||||||
const fs: JSON = await this._fetchFileSystem('/src/lib/assets/fs/fs.json');
|
copy.set(inode, { ...node, children: [...node.children] });
|
||||||
localStorage.setItem('signature', sig);
|
|
||||||
localStorage.setItem('fs', JSON.stringify(fs));
|
|
||||||
|
|
||||||
console.info('FS fetched from file, new sinature:', sig);
|
|
||||||
|
|
||||||
return fs;
|
|
||||||
} else {
|
|
||||||
const fs: string | null = localStorage.getItem('fs');
|
|
||||||
if (fs === null) throw new Error('FS in LocalStorage is null!');
|
|
||||||
|
|
||||||
console.info('FS fetched from localStorage with signature:', sig);
|
|
||||||
|
|
||||||
return JSON.parse(fs);
|
|
||||||
}
|
}
|
||||||
|
return copy;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _jsonToNodeTable(data: JSON): Map<number, TreeNode> {
|
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 FsTable: Map<number, TreeNode> = new Map<number, TreeNode>();
|
||||||
const entryList = Object.entries(data);
|
const entryList = Object.entries(data);
|
||||||
|
|
||||||
for (let i = 0; i < entryList.length; i++) {
|
for (const [key, obj] of Object.entries(data)) {
|
||||||
const object: any = entryList[i][1];
|
const inode = Number(key);
|
||||||
|
|
||||||
const node: TreeNode = {
|
const node: TreeNode = {
|
||||||
inode: object.Inode,
|
inode: inode,
|
||||||
name: object.Name,
|
name: obj.Name,
|
||||||
type: object.Type,
|
type: obj.Type,
|
||||||
size: object.Size,
|
size: obj.Size,
|
||||||
interactible: object.Interactible,
|
interactible: obj.Interactible,
|
||||||
func: object.Func,
|
func: obj.Func,
|
||||||
children: object.Children,
|
children: Array.isArray(obj.Children) ? obj.Children : [],
|
||||||
content: object.Content,
|
content: obj.Content,
|
||||||
link: object.Target,
|
link: obj.Target,
|
||||||
permission: {
|
permission: {
|
||||||
user: {
|
user: {
|
||||||
r: object.Permission[0]?.Read,
|
r: obj.Permission[0]?.Read ?? false,
|
||||||
w: object.Permission[0]?.Write,
|
w: obj.Permission[0]?.Write ?? false,
|
||||||
x: object.Permission[0]?.Exec
|
x: obj.Permission[0]?.Exec ?? false
|
||||||
},
|
},
|
||||||
group: {
|
group: {
|
||||||
r: object.Permission[1]?.Read,
|
r: obj.Permission[1]?.Read ?? false,
|
||||||
w: object.Permission[1]?.Write,
|
w: obj.Permission[1]?.Write ?? false,
|
||||||
x: object.Permission[1]?.Exec
|
x: obj.Permission[1]?.Exec ?? false
|
||||||
},
|
},
|
||||||
other: {
|
other: {
|
||||||
r: object.Permission[2]?.Read,
|
r: obj.Permission[2]?.Read ?? false,
|
||||||
w: object.Permission[2]?.Write,
|
w: obj.Permission[2]?.Write ?? false,
|
||||||
x: object.Permission[2]?.Exec
|
x: obj.Permission[2]?.Exec ?? false
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
owner: object.Owner,
|
owner: obj.Owner,
|
||||||
group: object.Group,
|
group: obj.Group,
|
||||||
timestamps: {
|
timestamps: {
|
||||||
modified: new Date(object.TimeStamps.MTime),
|
modified: new Date(obj.TimeStamps.MTime),
|
||||||
changed: new Date(object.TimeStamps.CTime),
|
changed: new Date(obj.TimeStamps.CTime),
|
||||||
accessed: new Date(object.TimeStamps.ATime)
|
accessed: new Date(obj.TimeStamps.ATime)
|
||||||
},
|
},
|
||||||
parent: object.Parent
|
parent: obj.Parent
|
||||||
};
|
};
|
||||||
|
|
||||||
FsTable.set(object.Inode, node);
|
FsTable.set(inode, node);
|
||||||
}
|
}
|
||||||
|
|
||||||
return FsTable;
|
return FsTable;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,10 +274,31 @@ export class FileSystem {
|
|||||||
this._fs.set(this._fs.size + 1, node);
|
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);
|
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 {
|
private _iNodeToPathString(inode: number): string {
|
||||||
const currentNode = this._fs.get(inode);
|
const currentNode = this._fs.get(inode);
|
||||||
|
|
||||||
@@ -212,6 +357,8 @@ export class FileSystem {
|
|||||||
return typeof path === 'string' && path.startsWith('/');
|
return typeof path === 'string' && path.startsWith('/');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
public saveEdit(edit: TreeNode): void {}
|
||||||
|
|
||||||
public getPathByINode(inode: number): string {
|
public getPathByINode(inode: number): string {
|
||||||
return this._iNodeToPathString(inode);
|
return this._iNodeToPathString(inode);
|
||||||
}
|
}
|
||||||
@@ -224,10 +371,10 @@ export class FileSystem {
|
|||||||
public getNodeByInode(inode: number): TreeNode {
|
public getNodeByInode(inode: number): TreeNode {
|
||||||
const node: TreeNode | undefined = this._fs.get(inode);
|
const node: TreeNode | undefined = this._fs.get(inode);
|
||||||
if (!node) throw new Error(`No node exists under inode - ${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)!;
|
if (path === '/') return this._fs.get(this._root)!;
|
||||||
|
|
||||||
let parsedPath: string = path;
|
let parsedPath: string = path;
|
||||||
@@ -248,8 +395,8 @@ export class FileSystem {
|
|||||||
});
|
});
|
||||||
parsedPath = `${trail}/${path.replace('~', '')}`;
|
parsedPath = `${trail}/${path.replace('~', '')}`;
|
||||||
}
|
}
|
||||||
|
const node = this._pathStringToNode(parsedPath);
|
||||||
return this._pathStringToNode(parsedPath);
|
return structuredClone(node);
|
||||||
}
|
}
|
||||||
|
|
||||||
public recursiveTraversalPre(
|
public recursiveTraversalPre(
|
||||||
@@ -288,10 +435,10 @@ export class FileSystem {
|
|||||||
|
|
||||||
public static get instance(): FileSystem {
|
public static get instance(): FileSystem {
|
||||||
if (!FileSystem.#instance) {
|
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;
|
changed: Date;
|
||||||
accessed: 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
|
||||||
|
};
|
||||||
|
|||||||
@@ -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 readonly _help: string; //TODO: Dont know where to pull the help text from yet
|
||||||
public abstract result: CommandResult;
|
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 = {
|
export type CommandFlag = {
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import type { Stack } from '$lib/stores/stack';
|
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 {
|
export class Shell {
|
||||||
private readonly _fs: FileSystem;
|
|
||||||
|
|
||||||
private _passwd: User[];
|
private _passwd: User[];
|
||||||
private _group: Group[];
|
private _group: Group[];
|
||||||
|
|
||||||
@@ -14,9 +13,15 @@ export class Shell {
|
|||||||
private user: User;
|
private user: User;
|
||||||
private _process?: Process;
|
private _process?: Process;
|
||||||
|
|
||||||
constructor() {
|
constructor() {}
|
||||||
this._fs = new FileSystem();
|
|
||||||
}
|
public static Initialize(
|
||||||
|
username: string,
|
||||||
|
password: string,
|
||||||
|
commands: Map<string, Command>,
|
||||||
|
passwd: Map<number, User>,
|
||||||
|
group: Map<number, Group>
|
||||||
|
) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum ExitCode {
|
export enum ExitCode {
|
||||||
|
|||||||
@@ -1,11 +1,110 @@
|
|||||||
export class MD5 {
|
export class MD5 {
|
||||||
private static encoder: TextEncoder = new TextEncoder();
|
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) {
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 pad(input: Uint8Array) {
|
private static pad(input: Uint8Array): Uint8Array {
|
||||||
const inputBitLength: number = input.length * 8;
|
const inputBitLength: number = input.length * 8;
|
||||||
|
|
||||||
const out: Uint8Array = new Uint8Array([...input, 0x80]);
|
const out: Uint8Array = new Uint8Array([...input, 0x80]);
|
||||||
@@ -27,21 +126,21 @@ export class MD5 {
|
|||||||
(high >> 24) & 0xff
|
(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[][] = [];
|
const blocks: number[][] = [];
|
||||||
|
|
||||||
for (let i = 0; i < input.length; i += 64) {
|
for (let i = 0; i < input.length; i += 64) {
|
||||||
const block = input.slice(i, i + 64);
|
const block = input.slice(i, i + 64);
|
||||||
blocks.push(this.sliceToWords(block));
|
blocks.push(MD5.sliceToWords(block));
|
||||||
}
|
}
|
||||||
|
|
||||||
return blocks;
|
return blocks;
|
||||||
}
|
}
|
||||||
|
|
||||||
private sliceToWords(block: Uint8Array): number[] {
|
private static sliceToWords(block: Uint8Array): number[] {
|
||||||
const words: number[] = new Array<number>(16);
|
const words: number[] = new Array<number>(16);
|
||||||
|
|
||||||
for (let i = 0; i < 16; i++) {
|
for (let i = 0; i < 16; i++) {
|
||||||
@@ -57,4 +156,28 @@ export class MD5 {
|
|||||||
|
|
||||||
return words;
|
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('');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||