@prozilla-os/terminal 1.0.1

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.
Files changed (43) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +64 -0
  3. package/package.json +38 -0
  4. package/src/components/Ansi.tsx +174 -0
  5. package/src/components/InputLine.tsx +55 -0
  6. package/src/components/OutputLine.tsx +17 -0
  7. package/src/components/Terminal.module.css +126 -0
  8. package/src/components/Terminal.tsx +369 -0
  9. package/src/constants/terminal.const.ts +43 -0
  10. package/src/core/_utils/terminal.utils.ts +10 -0
  11. package/src/core/command.ts +95 -0
  12. package/src/core/commands/cat.ts +33 -0
  13. package/src/core/commands/cd.ts +20 -0
  14. package/src/core/commands/clear.ts +15 -0
  15. package/src/core/commands/cmatrix.ts +101 -0
  16. package/src/core/commands/compgen.ts +14 -0
  17. package/src/core/commands/cowsay.ts +108 -0
  18. package/src/core/commands/dir.ts +15 -0
  19. package/src/core/commands/echo.ts +10 -0
  20. package/src/core/commands/exit.ts +11 -0
  21. package/src/core/commands/fortune.ts +63 -0
  22. package/src/core/commands/help.ts +28 -0
  23. package/src/core/commands/hostname.ts +10 -0
  24. package/src/core/commands/lolcat.ts +54 -0
  25. package/src/core/commands/ls.ts +31 -0
  26. package/src/core/commands/make.ts +9 -0
  27. package/src/core/commands/man.ts +86 -0
  28. package/src/core/commands/mkdir.ts +17 -0
  29. package/src/core/commands/neofetch.ts +69 -0
  30. package/src/core/commands/pwd.ts +15 -0
  31. package/src/core/commands/reboot.ts +11 -0
  32. package/src/core/commands/reload.ts +11 -0
  33. package/src/core/commands/rev.ts +10 -0
  34. package/src/core/commands/rm.ts +21 -0
  35. package/src/core/commands/rmdir.ts +19 -0
  36. package/src/core/commands/sl.ts +220 -0
  37. package/src/core/commands/touch.ts +27 -0
  38. package/src/core/commands/uptime.ts +10 -0
  39. package/src/core/commands/whatis.ts +22 -0
  40. package/src/core/commands/whoami.ts +10 -0
  41. package/src/core/commands.ts +52 -0
  42. package/src/core/stream.ts +38 -0
  43. package/src/index.ts +7 -0
@@ -0,0 +1,369 @@
1
+ import { MouseEventHandler, MutableRefObject, useEffect, useRef, useState } from "react";
2
+ import styles from "./Terminal.module.css";
3
+ import { OutputLine } from "./OutputLine";
4
+ import { InputLine } from "./InputLine";
5
+ import { ANSI, App, clamp, removeFromArray, SettingsManager, useSettingsManager, useSystemManager, useVirtualRoot, VirtualFolder, WindowProps } from "@prozilla-os/core";
6
+ import { HOSTNAME, USERNAME, WELCOME_MESSAGE } from "../constants/terminal.const";
7
+ import { Stream } from "../core/stream";
8
+ import { CommandResponse } from "../core/command";
9
+ import { formatError } from "../core/_utils/terminal.utils";
10
+ import { CommandsManager } from "../core/commands";
11
+
12
+ interface TerminalProps extends WindowProps {
13
+ path: string;
14
+ input: string;
15
+ }
16
+
17
+ interface HistoryEntry {
18
+ text: string;
19
+ isInput: boolean;
20
+ value?: string;
21
+ clear?: boolean;
22
+ }
23
+
24
+ export function Terminal({ app, path: startPath, input, setTitle, close: exit, active, focus }: TerminalProps) {
25
+ const systemManager = useSystemManager();
26
+ const [inputKey, setInputKey] = useState(0);
27
+ const [inputValue, setInputValue] = useState(input ?? "");
28
+ const [history, setHistory] = useState<HistoryEntry[]>([{
29
+ text: app ? WELCOME_MESSAGE.replace("$APP_NAME", app.name) : WELCOME_MESSAGE,
30
+ isInput: false,
31
+ }]);
32
+ const virtualRoot = useVirtualRoot();
33
+ const [currentDirectory, setCurrentDirectory] = useState(virtualRoot?.navigate(startPath ?? "~"));
34
+ const inputRef = useRef(null);
35
+ const [historyIndex, setHistoryIndex] = useState(0);
36
+ const [stream, setStream] = useState<Stream | null>(null);
37
+ const [streamOutput, setStreamOutput] = useState<string | null>(null);
38
+ const ref = useRef(null);
39
+ const [streamFocused, setStreamFocused] = useState(false);
40
+ const settingsManager = useSettingsManager();
41
+
42
+ useEffect(() => {
43
+ if (currentDirectory != null)
44
+ setTitle?.(`${USERNAME}@${HOSTNAME}: ${currentDirectory.root ? "/" : currentDirectory.path}`);
45
+ }, [currentDirectory?.path, currentDirectory?.root, setTitle]);
46
+
47
+ useEffect(() => {
48
+ if (!inputRef.current || !active)
49
+ return;
50
+
51
+ (inputRef.current as unknown as HTMLInputElement).focus();
52
+ }, [inputRef, active]);
53
+
54
+ const scrollDown = () => {
55
+ (ref.current as unknown as HTMLDivElement).scrollTop = (ref.current as unknown as HTMLDivElement).scrollHeight;
56
+ };
57
+
58
+ useEffect(() => {
59
+ if (streamFocused || ref.current == null || streamOutput == null)
60
+ return;
61
+
62
+ scrollDown();
63
+ setStreamFocused(true);
64
+ }, [streamFocused, streamOutput, ref]);
65
+
66
+ useEffect(() => {
67
+ if (ref.current == null || stream != null)
68
+ return;
69
+
70
+ scrollDown();
71
+ }, [inputValue]);
72
+
73
+ const prefix = `${ANSI.fg.cyan + USERNAME}@${HOSTNAME + ANSI.reset}:`
74
+ + `${ANSI.fg.blue + ((currentDirectory?.root || currentDirectory == null) ? "/" : currentDirectory?.path) + ANSI.reset}$ `;
75
+
76
+ const updatedHistory = history;
77
+ const pushHistory = (entry: HistoryEntry) => {
78
+ updatedHistory.push(entry);
79
+ setHistory(updatedHistory);
80
+ };
81
+
82
+ const promptOutput = (text: string) => {
83
+ pushHistory({
84
+ text,
85
+ isInput: false
86
+ });
87
+ };
88
+
89
+ const connectStream = (stream: Stream, pipes: string[]) => {
90
+ setStream(stream);
91
+ setStreamFocused(false);
92
+
93
+ const onKeyDown = (event: KeyboardEvent) => {
94
+ if (active && (event.ctrlKey || event.metaKey) && event.key === "c") {
95
+ stream.stop();
96
+ }
97
+ };
98
+
99
+ let lastOutput: CommandResponse | null = null;
100
+
101
+ stream.on(Stream.EVENT_NAMES.new, (text) => {
102
+ void (async () => {
103
+ let output: CommandResponse = text as CommandResponse;
104
+
105
+ for (const pipe of pipes) {
106
+ if (output instanceof Stream)
107
+ continue;
108
+
109
+ // Output from the previous command gets added as an argument for the next command
110
+ output = await handleInput(output ? `${pipe} ${output as string}` : pipe);
111
+ }
112
+
113
+ if ((output as unknown) instanceof Stream) {
114
+ stream.stop();
115
+ promptOutput(ANSI.fg.red + "Stream failed");
116
+ return;
117
+ }
118
+
119
+ lastOutput = output;
120
+ setStreamOutput(output as string);
121
+ })();
122
+ });
123
+
124
+ stream.on(Stream.EVENT_NAMES.stop, () => {
125
+ document.removeEventListener("keydown", onKeyDown);
126
+
127
+ promptOutput(lastOutput as string);
128
+
129
+ setStream(null);
130
+ setStreamOutput(null);
131
+ });
132
+
133
+ document.addEventListener("keydown", onKeyDown);
134
+ };
135
+
136
+ const handleInput = async (value: string): Promise<CommandResponse> => {
137
+ const rawInputValueStart = value.indexOf(" ") + 1;
138
+ const rawInputValue = rawInputValueStart <= 0 ? "" : value.substr(rawInputValueStart);
139
+ const timestamp = Date.now();
140
+
141
+ value = value.trim();
142
+ if (value === "") return;
143
+
144
+ // Parse arguments
145
+ const args = value.match(/(?:[^\s"]+|"[^"]*")+/g);
146
+ if (args == null) return;
147
+ if (args[0].toLowerCase() === "sudo" && args.length >= 2) args.shift();
148
+
149
+ // Get command
150
+ const commandName = args.shift()?.toLowerCase();
151
+ if (commandName == null) return;
152
+ const command = CommandsManager.find(commandName);
153
+
154
+ if (!command) return formatError(commandName, "Command not found");
155
+
156
+ // Get options
157
+ const options: string[] = [];
158
+ const inputs: Record<string, string> = {};
159
+ args.filter((arg: string) => arg.startsWith("-")).forEach((option: string) => {
160
+ const addOption = (key: string) => {
161
+ if (options.includes(key))
162
+ return;
163
+
164
+ options.push(key);
165
+ const commandOption = command.getOption(options[options.length - 1]);
166
+
167
+ if (commandOption?.isInput) {
168
+ const optionInput = args[args.indexOf(option) + 1];
169
+ inputs[commandOption.short] = optionInput;
170
+ removeFromArray(optionInput, args);
171
+ }
172
+ };
173
+
174
+ if (option.startsWith("--")) {
175
+ const longOption = option.substring(2).toLowerCase();
176
+ addOption(longOption);
177
+ } else {
178
+ const shortOptions = option.substring(1).split("");
179
+ shortOptions.forEach((shortOption: string) => {
180
+ addOption(shortOption);
181
+ });
182
+ }
183
+
184
+ removeFromArray(option, args);
185
+ });
186
+
187
+ // Check usage
188
+ if (command.requireArgs && args.length === 0)
189
+ return formatError(commandName, `Incorrect usage: ${commandName} requires at least 1 argument`);
190
+
191
+ if (command.requireOptions && options.length === 0)
192
+ return formatError(commandName, `Incorrect usage: ${commandName} requires at least 1 option`);
193
+
194
+ // Execute command
195
+ let response: CommandResponse | null = null;
196
+
197
+ try {
198
+ response = await command.execute(args, {
199
+ promptOutput,
200
+ pushHistory,
201
+ virtualRoot,
202
+ currentDirectory: currentDirectory as VirtualFolder,
203
+ setCurrentDirectory,
204
+ username: USERNAME,
205
+ hostname: HOSTNAME,
206
+ rawInputValue,
207
+ options,
208
+ exit,
209
+ inputs,
210
+ timestamp,
211
+ settingsManager: settingsManager as SettingsManager,
212
+ systemManager,
213
+ app: app as App,
214
+ });
215
+
216
+ if (response == null)
217
+ return formatError(commandName, "Command failed");
218
+
219
+ if (!(response as { blank: boolean }).blank)
220
+ return response;
221
+ } catch (error) {
222
+ console.error(error);
223
+ return formatError(commandName, "Command failed");
224
+ }
225
+ };
226
+
227
+ const resetInput = () => {
228
+ setInputValue("");
229
+ setHistoryIndex(0);
230
+ };
231
+
232
+ const submitInput = async (value: string) => {
233
+ pushHistory({
234
+ text: prefix + value,
235
+ isInput: true,
236
+ value
237
+ });
238
+
239
+ // Piping is used to chain commands
240
+ let pipes = value.split(" | ");
241
+ const completedPipes: string[] = [];
242
+
243
+ let output: CommandResponse | null = null;
244
+ for (const pipe of pipes) {
245
+ if (output instanceof Stream)
246
+ continue;
247
+
248
+ // Output from the previous command gets added as an argument for the next command
249
+ output = await handleInput(output ? `${pipe} ${output as string}` : pipe);
250
+ completedPipes.push(pipe);
251
+ }
252
+
253
+ resetInput();
254
+
255
+ pipes = pipes.filter((pipe) => !completedPipes.includes(pipe));
256
+
257
+ if (output) {
258
+ if (output instanceof Stream) {
259
+ connectStream(output, pipes);
260
+ } else {
261
+ promptOutput(`${output as string}\n`);
262
+ }
263
+ }
264
+ };
265
+
266
+ const updateHistoryIndex = (delta: number) => {
267
+ const inputHistory = history.filter(({ isInput }) => isInput);
268
+ const index = clamp(historyIndex + delta, 0, inputHistory.length);
269
+
270
+ if (index === historyIndex) {
271
+ if (delta < 0) {
272
+ setInputValue("");
273
+ }
274
+
275
+ return;
276
+ }
277
+
278
+ if (index === 0) {
279
+ setInputValue("");
280
+ } else {
281
+ setInputValue(inputHistory[inputHistory.length - index].value ?? "");
282
+ }
283
+
284
+ setHistoryIndex(index);
285
+ };
286
+
287
+ const onKeyDown = (event: KeyboardEvent) => {
288
+ const value = (event.target as HTMLInputElement).value;
289
+ const { key } = event;
290
+
291
+ if (key === "Enter") {
292
+ void submitInput(value);
293
+ setInputKey((previousKey) => previousKey + 1);
294
+ } else if (key === "ArrowUp") {
295
+ event.preventDefault();
296
+ updateHistoryIndex(1);
297
+ } else if (key === "ArrowDown") {
298
+ event.preventDefault();
299
+ updateHistoryIndex(-1);
300
+ } else if (!stream && (event.ctrlKey || event.metaKey) && key === "c") {
301
+ setInputValue((value) => value + "^C");
302
+ }
303
+ };
304
+
305
+ const onChange = (event: KeyboardEvent) => {
306
+ const value = (event.target as HTMLInputElement).value;
307
+ return setInputValue(value);
308
+ };
309
+
310
+ const displayHistory = () => {
311
+ const visibleHistory = history.slice(-16);
312
+ let startIndex = 0;
313
+
314
+ visibleHistory.forEach((entry, index) => {
315
+ if (entry.clear)
316
+ startIndex = index + 1;
317
+ });
318
+
319
+ return visibleHistory.slice(startIndex).map(({ text }, index) => {
320
+ return <OutputLine text={text} key={index}/>;
321
+ });
322
+ };
323
+
324
+ const onMouseDown = (event: MouseEvent) => {
325
+ focus?.(event);
326
+
327
+ if (event.button === 2) {
328
+ event.preventDefault();
329
+
330
+ navigator.clipboard.readText?.().then((text) => {
331
+ setInputValue(inputValue + text);
332
+ }).catch((error) => {
333
+ console.error(error);
334
+ });
335
+ }
336
+ };
337
+
338
+ const onContextMenu = (event: Event) => {
339
+ event.preventDefault();
340
+ };
341
+
342
+ return (
343
+ <div
344
+ ref={ref}
345
+ className={styles.Terminal}
346
+ onMouseDown={onMouseDown as unknown as MouseEventHandler}
347
+ onContextMenu={onContextMenu as unknown as MouseEventHandler}
348
+ onClick={(event) => {
349
+ if (window.getSelection()?.toString() === "") {
350
+ event.preventDefault();
351
+ (inputRef.current as HTMLInputElement | null)?.focus();
352
+ }
353
+ }}
354
+ >
355
+ {displayHistory()}
356
+ {!stream
357
+ ? <InputLine
358
+ key={inputKey}
359
+ value={inputValue}
360
+ prefix={prefix}
361
+ onKeyDown={onKeyDown}
362
+ onChange={onChange}
363
+ inputRef={inputRef as unknown as MutableRefObject<HTMLInputElement>}
364
+ />
365
+ : <OutputLine text={streamOutput ?? ""}/>
366
+ }
367
+ </div>
368
+ );
369
+ }
@@ -0,0 +1,43 @@
1
+ import { ANSI } from "@prozilla-os/core";
2
+
3
+ export const USERNAME = "user";
4
+ export const HOSTNAME = "prozilla-os";
5
+ export const MAX_WIDTH = 50;
6
+
7
+ export const WELCOME_MESSAGE = `${ANSI.fg.cyan + ANSI.decoration.dim}$APP_NAME - Made by Prozilla${ANSI.reset}`
8
+ + `\n${ANSI.decoration.dim}Type 'help' for a list of commands.${ANSI.reset}\n`;
9
+
10
+ export const ASCII_LOGO = `
11
+ :.
12
+ -==.
13
+ .=====:
14
+ ---::..:=======-.
15
+ :===+=----------::..
16
+ =+=---------------:..
17
+ --------------------:.
18
+ .:-+=----*###*--*####=---.
19
+ :==+----#%+-+%#-##%*+----:.
20
+ .=----#%+-+%#-*+-%#+---:.
21
+ ==----*###*--*###*----.
22
+ ==+-------------------:.
23
+ ...::---------------:.
24
+ .::---------::..
25
+ ....::... `;
26
+
27
+ export const ANSI_LOGO_COLOR = ANSI.fg.cyan;
28
+ export const ANSI_ASCII_LOGO = `
29
+ :.
30
+ -==.
31
+ .=====:
32
+ ---::..:=======-.
33
+ :===+=----------::..
34
+ =+=---------------:..
35
+ --------------------:.
36
+ .:-+=----${ANSI.fg.white}*###*${ANSI_LOGO_COLOR}--${ANSI.fg.white}*####=${ANSI_LOGO_COLOR}---.
37
+ :==+----${ANSI.fg.white}#%+${ANSI_LOGO_COLOR}-${ANSI.fg.white}+%#${ANSI_LOGO_COLOR}-${ANSI.fg.white}##%*+${ANSI_LOGO_COLOR}----:.
38
+ .=----${ANSI.fg.white}#%+${ANSI_LOGO_COLOR}-${ANSI.fg.white}+%#${ANSI_LOGO_COLOR}-${ANSI.fg.white}*+${ANSI_LOGO_COLOR}-${ANSI.fg.white}%#+${ANSI_LOGO_COLOR}---:.
39
+ ==----${ANSI.fg.white}*###*${ANSI_LOGO_COLOR}--${ANSI.fg.white}*###*${ANSI_LOGO_COLOR}----.
40
+ ==+-------------------:.
41
+ ...::---------------:.
42
+ .::---------::..
43
+ ....::... `;
@@ -0,0 +1,10 @@
1
+ import { ANSI } from "@prozilla-os/core";
2
+
3
+ export function formatError(commandName: string, error: string): string {
4
+ return `${ANSI.fg.red}${commandName}: ${error}${ANSI.reset}`;
5
+ }
6
+
7
+ export function removeAnsi(string: string): string {
8
+ // eslint-disable-next-line no-control-regex
9
+ return string.replace(/\u001b\[([0-9]+)m/gm, "");
10
+ }
@@ -0,0 +1,95 @@
1
+ import { App, SettingsManager, SystemManager, VirtualFolder, VirtualRoot } from "@prozilla-os/core";
2
+ import { Stream } from "./stream";
3
+
4
+ type Option = {
5
+ long: string,
6
+ short: string,
7
+ isInput: boolean
8
+ };
9
+
10
+ export type CommandResponse = string | { blank: boolean } | void | Stream;
11
+ export type ExecuteParams = {
12
+ promptOutput?: Function,
13
+ pushHistory?: Function,
14
+ virtualRoot?: VirtualRoot,
15
+ currentDirectory: VirtualFolder,
16
+ setCurrentDirectory?: Function,
17
+ username?: string,
18
+ hostname?: string,
19
+ rawInputValue?: string,
20
+ options?: string[],
21
+ exit?: Function,
22
+ inputs?: Record<string, string>,
23
+ timestamp: number,
24
+ settingsManager: SettingsManager,
25
+ systemManager: SystemManager,
26
+ app: App,
27
+ };
28
+
29
+ type Execute = (args?: string[], params?: ExecuteParams) => CommandResponse | Promise<CommandResponse>;
30
+
31
+ type Manual = {
32
+ purpose?: string,
33
+ usage?: string,
34
+ description?: string,
35
+ options?: object
36
+ };
37
+
38
+ export class Command {
39
+ name: string = "command";
40
+ options: Option[] = [];
41
+ manual: Manual | undefined;
42
+ requireArgs: boolean | undefined;
43
+ requireOptions: boolean | undefined;
44
+
45
+ execute: Execute = () => {};
46
+
47
+ setName(name: string): Command {
48
+ this.name = name;
49
+
50
+ if (!this.manual?.usage) {
51
+ if (!this.manual)
52
+ this.manual = {};
53
+
54
+ this.manual.usage = name;
55
+ }
56
+
57
+ return this;
58
+ }
59
+
60
+ setExecute(execute: Execute): Command {
61
+ this.execute = execute;
62
+ return this;
63
+ }
64
+
65
+ setRequireArgs(value: boolean): Command {
66
+ this.requireArgs = value;
67
+ return this;
68
+ }
69
+
70
+ setRequireOptions(value: boolean): Command {
71
+ this.requireOptions = value;
72
+ return this;
73
+ }
74
+
75
+ setManual({ purpose, usage, description, options }: Manual): Command {
76
+ this.manual = { purpose, usage, description, options };
77
+ return this;
78
+ }
79
+
80
+ addOption({ short, long, isInput }: Option): Command {
81
+ this.options.push({ short, long, isInput });
82
+ return this;
83
+ }
84
+
85
+ getOption(key: string): Option | null {
86
+ let matchingOption: Option | null = null;
87
+
88
+ this.options.forEach((option) => {
89
+ if (option.short === key || option.long === key)
90
+ matchingOption = option;
91
+ });
92
+
93
+ return matchingOption;
94
+ }
95
+ }
@@ -0,0 +1,33 @@
1
+ import { VirtualFile } from "@prozilla-os/core";
2
+ import { formatError } from "../_utils/terminal.utils";
3
+ import { Command, ExecuteParams } from "../command";
4
+
5
+ export const cat = new Command()
6
+ .setRequireArgs(true)
7
+ .setManual({
8
+ purpose: "Concetenate files and display on the terminal screen",
9
+ usage: "cat [options] [files]",
10
+ description: "Concetenate files to standard output."
11
+ })
12
+ .setExecute(function(this: Command, args, params) {
13
+ const { currentDirectory, options } = params as ExecuteParams;
14
+ const fileId = (args as string[])[0];
15
+ const { name, extension } = VirtualFile.splitId(fileId);
16
+ const file = currentDirectory.findFile(name, extension);
17
+
18
+ if (!file)
19
+ return formatError(this.name, `${fileId}: No such file`);
20
+
21
+ if (file.content) {
22
+ if (!options?.includes("e")) {
23
+ return file.content;
24
+ } else {
25
+ // Append "$" at the end of every line
26
+ return file.content.split("\n").join("$\n") + "$";
27
+ }
28
+ } else if (file.source) {
29
+ return `Src: ${file.source}`;
30
+ } else {
31
+ return { blank: true };
32
+ }
33
+ });
@@ -0,0 +1,20 @@
1
+ import { formatError } from "../_utils/terminal.utils";
2
+ import { Command, ExecuteParams } from "../command";
3
+
4
+ export const cd = new Command()
5
+ .setManual({
6
+ purpose: "Change the current directory",
7
+ usage: "cd [PATH]",
8
+ description: "Change working directory to given path (the home directory by default)."
9
+ })
10
+ .setExecute(function(this: Command, args, params) {
11
+ const { currentDirectory, setCurrentDirectory } = params as ExecuteParams;
12
+ const path = (args as string[])[0] ?? "~";
13
+ const destination = currentDirectory.navigate(path);
14
+
15
+ if (!destination)
16
+ return formatError(this.name, `${(args as string[])[0]}: No such file or directory`);
17
+
18
+ setCurrentDirectory?.(destination);
19
+ return { blank: true };
20
+ });
@@ -0,0 +1,15 @@
1
+ import { Command, ExecuteParams } from "../command";
2
+
3
+ export const clear = new Command()
4
+ .setManual({
5
+ purpose: "Clear terminal screen",
6
+ })
7
+ .setExecute(function(args, params) {
8
+ const { pushHistory } = params as ExecuteParams;
9
+ pushHistory?.({
10
+ clear: true,
11
+ isInput: false
12
+ });
13
+
14
+ return { blank: true };
15
+ });
@@ -0,0 +1,101 @@
1
+ import { ANSI, randomFromArray, randomRange, removeFromArray, Vector2 } from "@prozilla-os/core";
2
+ import { Command } from "../command";
3
+ import { Stream } from "../stream";
4
+
5
+ const ANIMATION_SPEED = 1.25;
6
+ const SCREEN_WIDTH = 75;
7
+ const SCREEN_HEIGHT = 20;
8
+ const CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.*\\/()#@&$!?%°:<>[]";
9
+
10
+ const PARTICLES = {
11
+ framesBetweenSpawn: 30,
12
+ fallSpeed: 1,
13
+ minSize: 5,
14
+ maxSize: 25
15
+ };
16
+
17
+ type Particle = {
18
+ position: Vector2,
19
+ size: number;
20
+ };
21
+
22
+ function generateScreen(frame: number, screen: string[][], particles: Particle[]): string {
23
+ // Spawn new particles
24
+ if (frame % PARTICLES.framesBetweenSpawn) {
25
+ const newParticle: Particle = {
26
+ position: new Vector2(randomRange(0, SCREEN_WIDTH), SCREEN_HEIGHT).round(),
27
+ size: Math.round(randomRange(PARTICLES.minSize, PARTICLES.maxSize))
28
+ };
29
+ particles.push(newParticle);
30
+ }
31
+
32
+ // Move and render particles
33
+ particles.forEach((particle) => {
34
+ particle.position.y -= PARTICLES.fallSpeed;
35
+
36
+ // Clean previous render
37
+ for (let i = 0; i < PARTICLES.fallSpeed; i++) {
38
+ const positionX = particle.position.x;
39
+ const positionY = particle.position.y + i + particle.size;
40
+
41
+ if (positionY < SCREEN_HEIGHT && positionY >= 0)
42
+ screen[positionY][positionX] = " ";
43
+ }
44
+
45
+ // Remove offscreen particles
46
+ if (particle.position.y + particle.size <= 0 || particle.position.x >= SCREEN_WIDTH)
47
+ return removeFromArray(particle, particles);
48
+
49
+ for (let i = 0; i < particle.size; i++) {
50
+ const character = randomFromArray(CHARACTERS.split(""));
51
+ let color = i == 0 ? ANSI.fg.white : ANSI.fg.green;
52
+
53
+ if (i > particle.size / 2)
54
+ color = ANSI.fg.green + ANSI.decoration.dim;
55
+
56
+ const positionX = particle.position.x;
57
+ const positionY = particle.position.y + i;
58
+
59
+ if (positionX < SCREEN_WIDTH && positionY < SCREEN_HEIGHT && positionY >= 0) {
60
+ screen[positionY][positionX] = color + character + ANSI.reset;
61
+ }
62
+ }
63
+ });
64
+
65
+ return [...screen.map((row) => row.join(""))].reverse().join("\n");
66
+ }
67
+
68
+ export const cmatrix = new Command()
69
+ .setManual({
70
+ purpose: "Show a scrolling 'Matrix' like screen",
71
+ usage: "cmatrix",
72
+ })
73
+ .setExecute(function() {
74
+ const stream = new Stream();
75
+ const particles: Particle[] = [];
76
+
77
+ // Create screen
78
+ const screen: string[][] = [];
79
+ for (let y = 0; y < SCREEN_HEIGHT; y++) {
80
+ const row: string[] = [];
81
+ for (let x = 0; x < SCREEN_WIDTH; x++) {
82
+ row.push(" ");
83
+ }
84
+ screen.push(row);
85
+ }
86
+
87
+ let frame = 0;
88
+ const interval = setInterval(() => {
89
+ const text = generateScreen(frame, screen, particles);
90
+ stream.send(text);
91
+ frame++;
92
+ }, 100 / ANIMATION_SPEED);
93
+
94
+ stream.on(Stream.EVENT_NAMES.stop, () => {
95
+ clearInterval(interval);
96
+ });
97
+
98
+ stream.start();
99
+
100
+ return stream;
101
+ });
@@ -0,0 +1,14 @@
1
+ import { Command, ExecuteParams } from "../command";
2
+ import { CommandsManager } from "../commands";
3
+
4
+ export const compgen = new Command()
5
+ .setManual({
6
+ purpose: "Display a list of all commands"
7
+ })
8
+ .setRequireOptions(true)
9
+ .setExecute(function(args, params) {
10
+ const { options } = params as ExecuteParams;
11
+ if (options?.includes("c")) {
12
+ return CommandsManager.COMMANDS.map((command) => command.name).sort().join("\n");
13
+ }
14
+ });