@lcars-gui/core 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 aarondnas
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,19 @@
1
- # Temporary Holding Version
1
+ # @lcars-gui/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Gemeinsame Basis der lcars-gui-Fraktionspakete. Normalerweise brauchst du dieses Paket nicht direkt –
4
+ es wird von [`@lcars-gui/federation`](https://www.npmjs.com/package/@lcars-gui/federation) und
5
+ [`@lcars-gui/romulus`](https://www.npmjs.com/package/@lcars-gui/romulus) mitinstalliert.
6
+
7
+ ## Inhalt
8
+
9
+ | Export | Zweck |
10
+ |-----------------------------|---------------------------------------------------------------------------|
11
+ | `createLcarsSound()` | Synthetisierte Bedien-Töne über die Web Audio API (keine Audiodateien) |
12
+ | `initBehaviors()` | Verhalten für reines HTML/JS: Toggles, Tabs, Keypads, Töne |
13
+ | `seededRandom()`, `cx()` | Kleine Hilfsfunktionen |
14
+ | `@lcars-gui/core/react` | `SoundProvider`, `useLcarsSound` – ein Sound-Kontext für alle Fraktionen |
15
+ | `@lcars-gui/core/build` | `buildCss()` – erzeugt das CSS einer Fraktion aus Tokens und Komponenten-CSS |
16
+
17
+ ## Lizenz
18
+
19
+ MIT
package/build/css.js ADDED
@@ -0,0 +1,123 @@
1
+ // Erzeugt das CSS eines Fraktionspakets aus dessen Tokens und Komponenten-Styles.
2
+ // Erwartete Ordnerstruktur (relativ zu `root`):
3
+ //
4
+ // tokens/base.json Maße, Schriftgrößen, Grundfarben … → :root-Variablen
5
+ // tokens/themes/<name>.json Farbpalette pro Theme → [data-theme="<name>"]
6
+ // tokens/alerts/<name>.json Farbpalette pro Alarmstufe → [data-alert="<name>"]
7
+ // css/*.css Komponenten-Styles (nach Dateiname sortiert)
8
+ // themes/<name>/theme.css Theme-Extras (optional) → dist/themes/<name>.css
9
+ // fonts/ Schriften (optional) → dist/fonts/
10
+ //
11
+ // Ergebnis: dist/ui.css (+ dist/themes/*.css, dist/fonts/).
12
+ import fs from "fs";
13
+ import path from "path";
14
+
15
+ // Helper function: camelCase → kebab-case
16
+ const kebab = (str) =>
17
+ str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
18
+
19
+ const readJson = (file) => JSON.parse(fs.readFileSync(file, "utf8"));
20
+
21
+ // Alle JSON-Dateien eines Ordners als { name: inhalt }
22
+ function readJsonDir(dir) {
23
+ if (!fs.existsSync(dir)) return {};
24
+ return Object.fromEntries(
25
+ fs
26
+ .readdirSync(dir)
27
+ .filter((file) => file.endsWith(".json"))
28
+ .sort()
29
+ .map((file) => [path.basename(file, ".json"), readJson(path.join(dir, file))])
30
+ );
31
+ }
32
+
33
+ // Generate css-variables from all base tokens
34
+ function generateCssVars(baseTokens, vars) {
35
+ let css = "";
36
+ for (const [group, values] of Object.entries(baseTokens)) {
37
+ for (const [key, value] of Object.entries(values)) {
38
+ css += ` --${vars}${group}-${kebab(key)}: ${value};\n`;
39
+ }
40
+ }
41
+ return css;
42
+ }
43
+
44
+ // Palette → --colors-* Variablen. Fehlende Hover-Farben werden abgeleitet.
45
+ function generatePalette(palette, vars) {
46
+ let css = "";
47
+ for (const [key, value] of Object.entries(palette)) {
48
+ if (key.endsWith("hover")) continue;
49
+ const hover = palette[`${key}hover`] ?? `color-mix(in srgb, ${value} 65%, white)`;
50
+ css += ` --${vars}colors-${key}: ${value};\n`;
51
+ css += ` --${vars}colors-${key}hover: ${hover};\n`;
52
+ }
53
+ return css;
54
+ }
55
+
56
+ // Colors: data-color="n" sets --<prefix>-bg / --<prefix>-bg-hover (inherited by children)
57
+ function generateColorStyles(palette, prefix, vars) {
58
+ let css = "/* Colors */\n";
59
+ for (let i = 1; palette[`color${i}`]; i++) {
60
+ css += `[data-color="${i}"] { --${prefix}-bg: var(--${vars}colors-color${i}); --${prefix}-bg-hover: var(--${vars}colors-color${i}hover); }\n`;
61
+ }
62
+ return css + "\n";
63
+ }
64
+
65
+ function generatePaletteBlocks(palettes, attribute, vars) {
66
+ return Object.entries(palettes)
67
+ .map(([name, palette]) => `[${attribute}="${name}"] {\n${generatePalette(palette, vars)}}\n`)
68
+ .join("");
69
+ }
70
+
71
+ // Component styles: css/*.css in file name order
72
+ function readComponentStyles(cssDir) {
73
+ return fs
74
+ .readdirSync(cssDir)
75
+ .filter((file) => file.endsWith(".css"))
76
+ .sort()
77
+ .map((file) => `/* ==================== ${file} ==================== */\n\n` + fs.readFileSync(path.join(cssDir, file), "utf8"))
78
+ .join("\n");
79
+ }
80
+
81
+ /**
82
+ * @param {object} options
83
+ * @param {string} options.root Paketordner der Fraktion
84
+ * @param {string} options.defaultTheme Theme, dessen Palette auf :root liegt
85
+ * @param {string} [options.prefix] Präfix der CSS-Klassen/-Variablen (z. B. "lcar")
86
+ * @param {string} [options.varPrefix] Präfix der Token-Variablen (z. B. "rom-" → --rom-colors-color1),
87
+ * damit mehrere Fraktionen auf einer Seite nicht kollidieren
88
+ */
89
+ export function buildCss({ root, defaultTheme, prefix = "lcar", varPrefix = "" }) {
90
+ const distDir = path.join(root, "dist");
91
+ const base = readJson(path.join(root, "tokens/base.json"));
92
+ const themes = readJsonDir(path.join(root, "tokens/themes"));
93
+ const alerts = readJsonDir(path.join(root, "tokens/alerts"));
94
+
95
+ const defaultPalette = themes[defaultTheme];
96
+ if (!defaultPalette) throw new Error(`Theme "${defaultTheme}" fehlt in tokens/themes/`);
97
+
98
+ const finalCss =
99
+ "/* AUTO-GENERATED FROM tokens/ + css/*.css — DO NOT EDIT */\n\n" +
100
+ `:root {\n${generateCssVars(base, varPrefix)}${generatePalette(defaultPalette, varPrefix)}}\n\n` +
101
+ generateColorStyles(defaultPalette, prefix, varPrefix) +
102
+ "/* Themes */\n" + generatePaletteBlocks(themes, "data-theme", varPrefix) + "\n" +
103
+ "/* Alert palettes */\n" + generatePaletteBlocks(alerts, "data-alert", varPrefix) + "\n" +
104
+ readComponentStyles(path.join(root, "css"));
105
+
106
+ fs.mkdirSync(distDir, { recursive: true });
107
+ fs.writeFileSync(path.join(distDir, "ui.css"), finalCss);
108
+
109
+ // Theme-Extras
110
+ const themesDir = path.join(root, "themes");
111
+ if (fs.existsSync(themesDir)) {
112
+ fs.mkdirSync(path.join(distDir, "themes"), { recursive: true });
113
+ for (const name of fs.readdirSync(themesDir)) {
114
+ const file = path.join(themesDir, name, "theme.css");
115
+ if (fs.existsSync(file)) fs.copyFileSync(file, path.join(distDir, "themes", `${name}.css`));
116
+ }
117
+ }
118
+
119
+ const fontsDir = path.join(root, "fonts");
120
+ if (fs.existsSync(fontsDir)) {
121
+ fs.cpSync(fontsDir, path.join(distDir, "fonts"), { recursive: true });
122
+ }
123
+ }
@@ -0,0 +1,56 @@
1
+ type LcarsSoundKind = "beep" | "confirm" | "deny" | "alert";
2
+ /** [Frequenz in Hz, Dauer in ms] je Ton einer Folge */
3
+ type LcarsSoundPatterns = Record<LcarsSoundKind, [number, number][]>;
4
+ interface LcarsSoundOptions {
5
+ /** Tonfolgen je Art (Standard: Föderations-Töne) */
6
+ patterns?: LcarsSoundPatterns;
7
+ /** Wellenform des Oszillators (Standard: "sine") */
8
+ wave?: OscillatorType;
9
+ }
10
+ interface LcarsSound {
11
+ play(kind?: LcarsSoundKind): void;
12
+ }
13
+ declare function createLcarsSound(volume?: number, { patterns, wave }?: LcarsSoundOptions): LcarsSound;
14
+
15
+ interface BehaviorSelectors {
16
+ /** Elemente, die beim Klicken einen Ton spielen (Buttons, Tabs) */
17
+ control: string;
18
+ /** Keypad-Container */
19
+ keypad: string;
20
+ /** Taste innerhalb eines Keypads */
21
+ keypadKey: string;
22
+ /** Anzeige innerhalb eines Keypads */
23
+ keypadDisplay: string;
24
+ }
25
+ interface InitBehaviorsOptions {
26
+ /** Bereich, in dem verdrahtet wird (Standard: document) */
27
+ root?: Document | HTMLElement;
28
+ /** Bedien-Töne von Anfang an an (später: setSound) */
29
+ sound?: boolean;
30
+ volume?: number;
31
+ /** Prüft den Code eines Keypads; ohne Angabe wird mit data-code verglichen */
32
+ onKeypadSubmit?: (code: string, keypad: HTMLElement) => boolean | void;
33
+ }
34
+ interface LcarsController {
35
+ play(kind?: LcarsSoundKind): void;
36
+ setSound(enabled: boolean): void;
37
+ destroy(): void;
38
+ }
39
+ /** Event, das ein Toggle nach jedem Umschalten auslöst (detail.pressed). */
40
+ declare const pressedChangeEvent = "lcar:pressedchange";
41
+ /**
42
+ * Macht statisches Markup interaktiv.
43
+ * Der zurückgegebene Controller spielt Töne und entfernt die Listener wieder.
44
+ */
45
+ declare function initBehaviors(selectors: BehaviorSelectors, { root, sound, volume, onKeypadSubmit }?: InitBehaviorsOptions, soundOptions?: LcarsSoundOptions): LcarsController;
46
+
47
+ declare const cx: (base: string, extra?: string) => string;
48
+
49
+ /**
50
+ * Zufallszahlen 0–1, aber reproduzierbar (mulberry32):
51
+ * gleicher Seed → gleiche Folge, wichtig für Server-Rendering.
52
+ */
53
+ declare function seededRandom(seed?: number): () => number;
54
+
55
+ export { createLcarsSound, cx, initBehaviors, pressedChangeEvent, seededRandom };
56
+ export type { BehaviorSelectors, InitBehaviorsOptions, LcarsController, LcarsSound, LcarsSoundKind, LcarsSoundOptions, LcarsSoundPatterns };
package/dist/index.js ADDED
@@ -0,0 +1,131 @@
1
+ // src/sound.ts
2
+ var defaultPatterns = {
3
+ beep: [[1320, 70]],
4
+ confirm: [[880, 70], [1320, 110]],
5
+ deny: [[440, 110], [330, 180]],
6
+ alert: [[620, 220], [880, 220], [620, 220], [880, 220]]
7
+ };
8
+ function createLcarsSound(volume = 0.12, { patterns = defaultPatterns, wave = "sine" } = {}) {
9
+ let ctx;
10
+ return {
11
+ play(kind = "beep") {
12
+ if (typeof AudioContext === "undefined") return;
13
+ ctx ?? (ctx = new AudioContext());
14
+ let t = ctx.currentTime;
15
+ for (const [freq, ms] of patterns[kind]) {
16
+ const osc = ctx.createOscillator();
17
+ const gain = ctx.createGain();
18
+ const end = t + ms / 1e3;
19
+ osc.type = wave;
20
+ osc.frequency.value = freq;
21
+ gain.gain.setValueAtTime(volume, t);
22
+ gain.gain.exponentialRampToValueAtTime(1e-4, end);
23
+ osc.connect(gain).connect(ctx.destination);
24
+ osc.start(t);
25
+ osc.stop(end);
26
+ t = end + 0.02;
27
+ }
28
+ }
29
+ };
30
+ }
31
+
32
+ // src/behaviors.ts
33
+ var pressedChangeEvent = "lcar:pressedchange";
34
+ function initBehaviors(selectors, { root = document, sound = false, volume, onKeypadSubmit } = {}, soundOptions) {
35
+ const player = createLcarsSound(volume, soundOptions);
36
+ let soundOn = sound;
37
+ const play = (kind) => soundOn && player.play(kind);
38
+ const onClick = (e) => {
39
+ const target = e.target;
40
+ const control = target.closest(selectors.control);
41
+ if (control && control.dataset.sound !== "none") play(control.dataset.sound || "beep");
42
+ const toggle = target.closest("[aria-pressed]");
43
+ if (toggle) {
44
+ const pressed = toggle.getAttribute("aria-pressed") !== "true";
45
+ toggle.setAttribute("aria-pressed", String(pressed));
46
+ toggle.dispatchEvent(new CustomEvent(pressedChangeEvent, { bubbles: true, detail: { pressed } }));
47
+ }
48
+ const tab = target.closest('[role="tab"]');
49
+ if (tab) selectTab(tab);
50
+ const key = target.closest(`${selectors.keypad} ${selectors.keypadKey}`);
51
+ if (key) pressKey(key.closest(selectors.keypad), key.textContent.trim());
52
+ };
53
+ const onKeyDown = (e) => {
54
+ const { key, target } = e;
55
+ const step = key === "ArrowRight" ? 1 : key === "ArrowLeft" ? -1 : 0;
56
+ const tab = target.closest('[role="tab"]');
57
+ if (!step || !tab) return;
58
+ const list = tabsOf(tab);
59
+ const next = list[(list.indexOf(tab) + step + list.length) % list.length];
60
+ selectTab(next);
61
+ play("beep");
62
+ next.focus();
63
+ };
64
+ const codes = /* @__PURE__ */ new WeakMap();
65
+ const pressKey = (pad, key) => {
66
+ const display = pad.querySelector(selectors.keypadDisplay);
67
+ const length = Number(pad.dataset.length) || 6;
68
+ let code = codes.get(pad) ?? "";
69
+ const show = (text, state) => {
70
+ if (!display) return;
71
+ display.textContent = text || "\u2013".repeat(length);
72
+ if (state) display.dataset.state = state;
73
+ else delete display.dataset.state;
74
+ };
75
+ if (key === "ENT") {
76
+ const accepted = onKeypadSubmit ? onKeypadSubmit(code, pad) : code === pad.dataset.code;
77
+ codes.set(pad, "");
78
+ if (accepted === void 0) return play("confirm");
79
+ play(accepted ? "confirm" : "deny");
80
+ return show(accepted ? "OK" : "Denied", accepted ? "ok" : "error");
81
+ }
82
+ if (key === "CLR") code = "";
83
+ else if (code.length < length) code += key;
84
+ codes.set(pad, code);
85
+ show(pad.dataset.mask === void 0 ? code : "\u2022".repeat(code.length));
86
+ };
87
+ root.addEventListener("click", onClick);
88
+ root.addEventListener("keydown", onKeyDown);
89
+ return {
90
+ play: (kind) => player.play(kind),
91
+ setSound: (enabled) => soundOn = enabled,
92
+ destroy() {
93
+ root.removeEventListener("click", onClick);
94
+ root.removeEventListener("keydown", onKeyDown);
95
+ }
96
+ };
97
+ }
98
+ function tabsOf(tab) {
99
+ return [...tab.closest('[role="tablist"]')?.querySelectorAll('[role="tab"]') ?? []];
100
+ }
101
+ function selectTab(tab) {
102
+ for (const t of tabsOf(tab)) {
103
+ const on = t === tab;
104
+ t.setAttribute("aria-selected", String(on));
105
+ t.tabIndex = on ? 0 : -1;
106
+ const panel = document.getElementById(t.getAttribute("aria-controls") ?? "");
107
+ if (panel) panel.hidden = !on;
108
+ }
109
+ }
110
+
111
+ // src/cx.ts
112
+ var cx = (base, extra) => extra ? `${base} ${extra}` : base;
113
+
114
+ // src/random.ts
115
+ function seededRandom(seed = 47) {
116
+ let state = seed >>> 0;
117
+ return () => {
118
+ state = state + 1831565813 >>> 0;
119
+ let t = state;
120
+ t = Math.imul(t ^ t >>> 15, t | 1);
121
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
122
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
123
+ };
124
+ }
125
+ export {
126
+ createLcarsSound,
127
+ cx,
128
+ initBehaviors,
129
+ pressedChangeEvent,
130
+ seededRandom
131
+ };
@@ -0,0 +1,22 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+
4
+ type LcarsSoundKind = "beep" | "confirm" | "deny" | "alert";
5
+ /** [Frequenz in Hz, Dauer in ms] je Ton einer Folge */
6
+ type LcarsSoundPatterns = Record<LcarsSoundKind, [number, number][]>;
7
+
8
+ interface SoundProviderProps {
9
+ enabled?: boolean;
10
+ volume?: number;
11
+ /** Eigene Tonfolgen (z. B. die einer Fraktion) */
12
+ patterns?: LcarsSoundPatterns;
13
+ wave?: OscillatorType;
14
+ children?: ReactNode;
15
+ }
16
+ /** Aktiviert die Bedien-Töne für alle Komponenten darunter. */
17
+ declare function SoundProvider({ enabled, volume, patterns, wave, children }: SoundProviderProps): react.JSX.Element;
18
+ /** Liefert play(kind); ohne SoundProvider (oder deaktiviert) passiert nichts. */
19
+ declare function useLcarsSound(): (kind?: LcarsSoundKind) => void | undefined;
20
+
21
+ export { SoundProvider, useLcarsSound };
22
+ export type { SoundProviderProps };
@@ -0,0 +1,56 @@
1
+ "use client";
2
+
3
+ // src/react/Sound.tsx
4
+ import {
5
+ createContext,
6
+ useCallback,
7
+ useContext,
8
+ useMemo
9
+ } from "react";
10
+
11
+ // src/sound.ts
12
+ var defaultPatterns = {
13
+ beep: [[1320, 70]],
14
+ confirm: [[880, 70], [1320, 110]],
15
+ deny: [[440, 110], [330, 180]],
16
+ alert: [[620, 220], [880, 220], [620, 220], [880, 220]]
17
+ };
18
+ function createLcarsSound(volume = 0.12, { patterns = defaultPatterns, wave = "sine" } = {}) {
19
+ let ctx;
20
+ return {
21
+ play(kind = "beep") {
22
+ if (typeof AudioContext === "undefined") return;
23
+ ctx ?? (ctx = new AudioContext());
24
+ let t = ctx.currentTime;
25
+ for (const [freq, ms] of patterns[kind]) {
26
+ const osc = ctx.createOscillator();
27
+ const gain = ctx.createGain();
28
+ const end = t + ms / 1e3;
29
+ osc.type = wave;
30
+ osc.frequency.value = freq;
31
+ gain.gain.setValueAtTime(volume, t);
32
+ gain.gain.exponentialRampToValueAtTime(1e-4, end);
33
+ osc.connect(gain).connect(ctx.destination);
34
+ osc.start(t);
35
+ osc.stop(end);
36
+ t = end + 0.02;
37
+ }
38
+ }
39
+ };
40
+ }
41
+
42
+ // src/react/Sound.tsx
43
+ import { jsx } from "react/jsx-runtime";
44
+ var SoundContext = createContext(null);
45
+ function SoundProvider({ enabled = true, volume, patterns, wave, children }) {
46
+ const sound = useMemo(() => createLcarsSound(volume, { patterns, wave }), [volume, patterns, wave]);
47
+ return /* @__PURE__ */ jsx(SoundContext.Provider, { value: enabled ? sound : null, children });
48
+ }
49
+ function useLcarsSound() {
50
+ const sound = useContext(SoundContext);
51
+ return useCallback((kind) => sound?.play(kind), [sound]);
52
+ }
53
+ export {
54
+ SoundProvider,
55
+ useLcarsSound
56
+ };
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@lcars-gui/core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Gemeinsame Basis für alle lcars-gui-Fraktionen: Sound-Engine, Verhalten für HTML/JS, CSS-Build",
5
+ "keywords": [
6
+ "lcars",
7
+ "star-trek",
8
+ "ui",
9
+ "sound"
10
+ ],
11
+ "license": "MIT",
12
+ "author": "aarondnas",
13
+ "homepage": "https://aarondnas.github.io/lcars-gui/",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/aarondnas/lcars-gui.git",
17
+ "directory": "packages/core"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/aarondnas/lcars-gui/issues"
21
+ },
22
+ "type": "module",
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ },
30
+ "./react": {
31
+ "types": "./dist/react/index.d.ts",
32
+ "import": "./dist/react/index.js"
33
+ },
34
+ "./build": "./build/css.js"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "build"
39
+ ],
40
+ "sideEffects": false,
41
+ "scripts": {
42
+ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsup",
43
+ "dev": "tsup --watch"
44
+ },
45
+ "peerDependencies": {
46
+ "react": ">=18"
47
+ },
48
+ "peerDependenciesMeta": {
49
+ "react": {
50
+ "optional": true
51
+ }
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ }
56
+ }