= (props) => {
);
const flowControl = props.flowButtons && (
- {props.flowButtons}
+
+ {props.flowButtons}
+
);
const editingWorkspaceControl = (
-
+
{props.editingWorkspaceButtons}
);
diff --git a/devserver/src/components/controlBar/ControlBarClearButton.tsx b/devserver/src/components/controlBar/ControlBarClearButton.tsx
index adb04e941..44ce463c1 100644
--- a/devserver/src/components/controlBar/ControlBarClearButton.tsx
+++ b/devserver/src/components/controlBar/ControlBarClearButton.tsx
@@ -3,13 +3,15 @@ import { IconNames } from '@blueprintjs/icons';
import ControlButton from '../ControlButton';
type Props = {
- onClick: () => void
+ onClick: () => void;
};
-export const ControlBarClearButton = (props: Props) =>
-
- ;
+export const ControlBarClearButton = (props: Props) => (
+
+
+
+);
diff --git a/devserver/src/components/controlBar/ControlBarRefreshButton.tsx b/devserver/src/components/controlBar/ControlBarRefreshButton.tsx
index f586b8744..5ee8edb2b 100644
--- a/devserver/src/components/controlBar/ControlBarRefreshButton.tsx
+++ b/devserver/src/components/controlBar/ControlBarRefreshButton.tsx
@@ -3,13 +3,15 @@ import { IconNames } from '@blueprintjs/icons';
import ControlButton from '../ControlButton';
type Props = {
- onClick: () => void
+ onClick: () => void;
};
-export const ControlBarRefreshButton = (props: Props) =>
-
- ;
+export const ControlBarRefreshButton = (props: Props) => (
+
+
+
+);
diff --git a/devserver/src/components/controlBar/ControlBarRunButton.tsx b/devserver/src/components/controlBar/ControlBarRunButton.tsx
index e07163fd1..5fc0fbdd8 100644
--- a/devserver/src/components/controlBar/ControlBarRunButton.tsx
+++ b/devserver/src/components/controlBar/ControlBarRunButton.tsx
@@ -16,7 +16,9 @@ type StateProps = {
type ControlButtonRunButtonProps = DispatchProps & StateProps;
-export const ControlBarRunButton: React.FC
= (props) => {
+export const ControlBarRunButton: React.FC = (
+ props
+) => {
const tooltipContent = 'Evaluate the program';
return (
diff --git a/devserver/src/components/editor/Editor.tsx b/devserver/src/components/editor/Editor.tsx
index 3bc31c9cc..ff183ae5a 100644
--- a/devserver/src/components/editor/Editor.tsx
+++ b/devserver/src/components/editor/Editor.tsx
@@ -1,7 +1,7 @@
-import { type Ace, require as acequire } from 'ace-builds';
+import { require as acequire, type Ace } from 'ace-builds';
+import 'ace-builds/esm-resolver';
import 'ace-builds/src-noconflict/ext-language_tools';
import 'ace-builds/src-noconflict/ext-searchbox';
-import 'ace-builds/esm-resolver';
import 'js-slang/dist/editors/ace/theme/source';
@@ -28,13 +28,15 @@ type DispatchProps = {
export type EditorStateProps = {
newCursorPosition?: Position;
- editorValue: string
- handleEditorValueChange: (newCode: string) => void
+ editorValue: string;
+ handleEditorValueChange: (newCode: string) => void;
};
export type EditorProps = DispatchProps & EditorStateProps;
-const makeCompleter = (handlePromptAutocomplete: DispatchProps['handlePromptAutocomplete']) => ({
+const makeCompleter = (
+ handlePromptAutocomplete: DispatchProps['handlePromptAutocomplete']
+) => ({
getCompletions(
_editor: Ace.Editor,
_session: Ace.EditSession,
@@ -66,10 +68,13 @@ const handlers = {
};
const Editor: React.FC = (props: EditorProps) => {
- const reactAceRef: React.MutableRefObject = React.useRef(null);
+ const reactAceRef: React.MutableRefObject =
+ React.useRef(null);
// Refs for things that technically shouldn't change... but just in case.
- const handlePromptAutocompleteRef = React.useRef(props.handlePromptAutocomplete);
+ const handlePromptAutocompleteRef = React.useRef(
+ props.handlePromptAutocomplete
+ );
const editor = reactAceRef.current?.editor;
@@ -91,10 +96,9 @@ const Editor: React.FC = (props: EditorProps) => {
// The () => ref.current() are designed to use the latest instance only.
// Start autocompletion
- acequire('ace/ext/language_tools')
- .setCompleters([
- makeCompleter((...args) => handlePromptAutocompleteRef.current(...args))
- ]);
+ acequire('ace/ext/language_tools').setCompleters([
+ makeCompleter((...args) => handlePromptAutocompleteRef.current(...args))
+ ]);
}, [editor]);
React.useLayoutEffect(() => {
diff --git a/devserver/src/components/repl/Repl.tsx b/devserver/src/components/repl/Repl.tsx
index 60e8b5f71..cd8320c29 100644
--- a/devserver/src/components/repl/Repl.tsx
+++ b/devserver/src/components/repl/Repl.tsx
@@ -19,7 +19,9 @@ const Output: React.FC = (props: OutputProps) => {
case 'running':
return (
- {props.output.consoleLogs.join('\n')}
+
+ {props.output.consoleLogs.join('\n')}
+
);
case 'result':
@@ -32,7 +34,9 @@ const Output: React.FC = (props: OutputProps) => {
}
return (
- {props.output.consoleLogs.join('\n')}
+
+ {props.output.consoleLogs.join('\n')}
+
{props.output.value}
);
@@ -41,13 +45,17 @@ const Output: React.FC = (props: OutputProps) => {
if (props.output.consoleLogs.length === 0) {
return (
- {parseError(props.output.errors)}
+
+ {parseError(props.output.errors)}
+
);
}
return (
- {props.output.consoleLogs.join('\n')}
+
+ {props.output.consoleLogs.join('\n')}
+
{parseError(props.output.errors)}
@@ -69,9 +77,7 @@ export type ReplProps = {
const Repl: React.FC = (props: ReplProps) => (
- {props.output === null
- ?
- : }
+ {props.output === null ? : }
{/* {cards.length > 0 ? cards : ( )} */}
diff --git a/devserver/src/components/sideContent/SideContent.tsx b/devserver/src/components/sideContent/SideContent.tsx
index 27125198f..645cd5754 100644
--- a/devserver/src/components/sideContent/SideContent.tsx
+++ b/devserver/src/components/sideContent/SideContent.tsx
@@ -1,4 +1,11 @@
-import { Card, Icon, Tab, type TabProps, Tabs, Tooltip } from '@blueprintjs/core';
+import {
+ Card,
+ Icon,
+ Tab,
+ Tabs,
+ Tooltip,
+ type TabProps
+} from '@blueprintjs/core';
import React from 'react';
import type { SideContentTab } from './types';
@@ -21,11 +28,11 @@ export type SideContentProps = {
renderActiveTabPanelOnly?: boolean;
editorWidth?: string;
sideContentHeight?: number;
- dynamicTabs: SideContentTab[]
+ dynamicTabs: SideContentTab[];
- selectedTabId: string
- alerts: string[]
- onChange?: (newId: string, oldId: string) => void
+ selectedTabId: string;
+ alerts: string[];
+ onChange?: (newId: string, oldId: string) => void;
};
const renderTab = (
@@ -37,7 +44,13 @@ const renderTab = (
const iconSize = 20;
const tabTitle = (
-
+
@@ -64,7 +77,9 @@ const renderTab = (
// }
// }
// : tab.body;
- const tabPanel: React.JSX.Element =
{tab.body}
;
+ const tabPanel: React.JSX.Element = (
+
{tab.body}
+ );
return
;
};
@@ -89,7 +104,14 @@ const SideContent: React.FC
= ({
if (onChange) onChange(newId, oldId);
}}
>
- {dynamicTabs.map((tab) => renderTab(tab, alerts.includes(tab.id), editorWidth, sideContentHeight))}
+ {dynamicTabs.map((tab) =>
+ renderTab(
+ tab,
+ alerts.includes(tab.id),
+ editorWidth,
+ sideContentHeight
+ )
+ )}
diff --git a/devserver/src/components/sideContent/TestTab.tsx b/devserver/src/components/sideContent/TestTab.tsx
index cc1fcd011..eb07aa435 100644
--- a/devserver/src/components/sideContent/TestTab.tsx
+++ b/devserver/src/components/sideContent/TestTab.tsx
@@ -1,26 +1,33 @@
import { IconNames } from '@blueprintjs/icons';
import type { SideContentTab } from './types';
-const TestTab = () =>
-
Source Academy Tab Development Server
-
- Run some code that imports modules in the editor on the left. You should see the corresponding module tab spawn.
- Whenever you make changes to the tab, the server should automatically reload and show the changes that you've made
- If that does not happen, you can click the refresh button to manually reload tabs
-
-
;
+const TestTab = () => (
+
+
Source Academy Tab Development Server
+
+ Run some code that imports modules in the editor on the left. You should
+ see the corresponding module tab spawn.
+
+ Whenever you make changes to the tab, the server should automatically
+ reload and show the changes that you've made
+ If that does not happen, you can click the refresh button to manually
+ reload tabs
+
+
+);
const testTabContent: SideContentTab = {
id: 'test',
label: 'Welcome to the tab development server!',
iconName: IconNames.LabTest,
- body:
+ body:
};
export default testTabContent;
diff --git a/devserver/src/components/sideContent/types.ts b/devserver/src/components/sideContent/types.ts
index c9108f5f3..b4891a7ce 100644
--- a/devserver/src/components/sideContent/types.ts
+++ b/devserver/src/components/sideContent/types.ts
@@ -3,19 +3,19 @@ import type { Context } from 'js-slang';
import type { JSX } from 'react';
export type DebuggerContext = {
- context: Context
+ context: Context;
};
export type SideContentTab = {
- id: string
- label: string
- iconName: IconName
- body: JSX.Element
+ id: string;
+ label: string;
+ iconName: IconName;
+ body: JSX.Element;
};
export type ModuleSideContent = {
label: string;
- iconName: IconName
- toSpawn?: (context: DebuggerContext) => boolean
- body: (context: DebuggerContext) => JSX.Element
+ iconName: IconName;
+ toSpawn?: (context: DebuggerContext) => boolean;
+ body: (context: DebuggerContext) => JSX.Element;
};
diff --git a/devserver/src/components/sideContent/utils.ts b/devserver/src/components/sideContent/utils.ts
index c6e5529fe..e521c38d0 100644
--- a/devserver/src/components/sideContent/utils.ts
+++ b/devserver/src/components/sideContent/utils.ts
@@ -5,17 +5,25 @@ import type { ModuleSideContent, SideContentTab } from './types';
const moduleManifest = manifest as Record;
export const getDynamicTabs = async (context: Context) => {
- const moduleSideContents = await Promise.all(Object.keys(context.moduleContexts)
- .flatMap((moduleName) => moduleManifest[moduleName].tabs.map(async (tabName) => {
- const { default: rawTab } = await import(`../../../../src/tabs/${tabName}/index.tsx`);
- return rawTab as ModuleSideContent;
- })));
+ const moduleSideContents = await Promise.all(
+ Object.keys(context.moduleContexts).flatMap((moduleName) =>
+ moduleManifest[moduleName].tabs.map(async (tabName) => {
+ const { default: rawTab } = await import(
+ `../../../../src/tabs/${tabName}/index.tsx`
+ );
+ return rawTab as ModuleSideContent;
+ })
+ )
+ );
- return moduleSideContents.filter(({ toSpawn }) => !toSpawn || toSpawn({ context }))
- .map((tab): SideContentTab => ({
- ...tab,
- // In the frontend, module tabs use their labels as IDs
- id: tab.label,
- body: tab.body({ context })
- }));
+ return moduleSideContents
+ .filter(({ toSpawn }) => !toSpawn || toSpawn({ context }))
+ .map(
+ (tab): SideContentTab => ({
+ ...tab,
+ // In the frontend, module tabs use their labels as IDs
+ id: tab.label,
+ body: tab.body({ context })
+ })
+ );
};
diff --git a/devserver/src/components/utils/AceHelper.ts b/devserver/src/components/utils/AceHelper.ts
index 770e07a92..8118dd531 100644
--- a/devserver/src/components/utils/AceHelper.ts
+++ b/devserver/src/components/utils/AceHelper.ts
@@ -1,9 +1,13 @@
/* eslint-disable new-cap */
-import { HighlightRulesSelector, ModeSelector } from 'js-slang/dist/editors/ace/modes/source';
+import {
+ HighlightRulesSelector,
+ ModeSelector
+} from 'js-slang/dist/editors/ace/modes/source';
import { Chapter, Variant } from 'js-slang/dist/types';
import ace from 'react-ace';
-export const getModeString = () => `source${Chapter.SOURCE_4}${Variant.DEFAULT}${''}`;
+export const getModeString = () =>
+ `source${Chapter.SOURCE_4}${Variant.DEFAULT}${''}`;
/**
* This _modifies global state_ and defines a new Ace mode globally, if it does not already exist.
@@ -16,10 +20,11 @@ export const selectMode = () => {
const library = '';
if (
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-expect-error
- typeof ace.define.modules[`ace/mode/${getModeString(chapter, variant, library)}`]?.Mode
- === 'function'
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+ // @ts-expect-error
+ typeof ace.define.modules[
+ `ace/mode/${getModeString(chapter, variant, library)}`
+ ]?.Mode === 'function'
) {
return;
}
diff --git a/devserver/src/components/utils/Hooks.ts b/devserver/src/components/utils/Hooks.ts
index 6e292e650..e14df68a7 100644
--- a/devserver/src/components/utils/Hooks.ts
+++ b/devserver/src/components/utils/Hooks.ts
@@ -7,21 +7,26 @@
import React, { type RefObject } from 'react';
-export const useDimensions = (ref: RefObject): [width: number, height: number] => {
+export const useDimensions = (
+ ref: RefObject
+): [width: number, height: number] => {
const [width, setWidth] = React.useState(0);
const [height, setHeight] = React.useState(0);
const resizeObserver = React.useMemo(
- () => new ResizeObserver((entries: ResizeObserverEntry[], _observer: ResizeObserver) => {
- if (entries.length !== 1) {
- throw new Error(
- 'Expected only a single HTML element to be observed by the ResizeObserver.'
- );
- }
- const contentRect = entries[0].contentRect;
- setWidth(contentRect.width);
- setHeight(contentRect.height);
- }),
+ () =>
+ new ResizeObserver(
+ (entries: ResizeObserverEntry[], _observer: ResizeObserver) => {
+ if (entries.length !== 1) {
+ throw new Error(
+ 'Expected only a single HTML element to be observed by the ResizeObserver.'
+ );
+ }
+ const contentRect = entries[0].contentRect;
+ setWidth(contentRect.width);
+ setHeight(contentRect.height);
+ }
+ ),
[]
);
diff --git a/devserver/src/main.tsx b/devserver/src/main.tsx
index 38c8f7044..26c718f89 100644
--- a/devserver/src/main.tsx
+++ b/devserver/src/main.tsx
@@ -1,13 +1,16 @@
import React from 'react';
import ReactDOM from 'react-dom';
-import './styles/index.scss';
import Playground from './components/Playground';
+import './styles/index.scss';
-ReactDOM.render(
-
-
-
+ReactDOM.render(
+
+
-
-, document.getElementById('root')!);
+ ,
+ document.getElementById('root')!
+);
diff --git a/devserver/src/styles/_application.scss b/devserver/src/styles/_application.scss
index b276c81e8..ba3fa1bc8 100644
--- a/devserver/src/styles/_application.scss
+++ b/devserver/src/styles/_application.scss
@@ -6,7 +6,7 @@
*/
html {
background-size: cover;
- background-image: url('#{$images-path}/academy_background.jpg');
+ background-image: url("#{$images-path}/academy_background.jpg");
background-repeat: no-repeat;
background-attachment: fixed;
::-webkit-scrollbar {
diff --git a/devserver/src/styles/_global.scss b/devserver/src/styles/_global.scss
index 5922a82b6..4b59affbc 100644
--- a/devserver/src/styles/_global.scss
+++ b/devserver/src/styles/_global.scss
@@ -5,8 +5,8 @@ $cadet-color-3: #34495e;
$cadet-color-4: #ced9e0;
$cadet-color-5: #ffffff;
-$images-path: '../assets';
-$achievement-assets: 'https://source-academy-assets.s3-ap-southeast-1.amazonaws.com/achievement';
+$images-path: "../assets";
+$achievement-assets: "https://source-academy-assets.s3-ap-southeast-1.amazonaws.com/achievement";
/*
Fixes height behaviour of nested flexboxes in the code editor and REPL,
diff --git a/devserver/src/styles/_workspace.scss b/devserver/src/styles/_workspace.scss
index f03004779..baa53645b 100644
--- a/devserver/src/styles/_workspace.scss
+++ b/devserver/src/styles/_workspace.scss
@@ -144,7 +144,7 @@ $code-color-error: #ff4444;
}
.ace_breakpoint:before {
- content: ' \25CF';
+ content: " \25CF";
margin-left: -10px;
color: red;
}
@@ -425,7 +425,10 @@ $code-color-error: #ff4444;
* output. Taken from react-ace
* sourcecode, font size modified.
*/
- font: 16px / normal 'Inconsolata', 'Consolas', monospace;
+ font:
+ 16px / normal "Inconsolata",
+ "Consolas",
+ monospace;
.canvas-container {
display: -webkit-box;
@@ -455,7 +458,7 @@ $code-color-error: #ff4444;
// Set colour of icons in blueprintjs tabs
color: #a7b6c2;
- &[aria-selected='true'] {
+ &[aria-selected="true"] {
.side-content-tooltip {
background-color: #495a6b;
@@ -468,7 +471,7 @@ $code-color-error: #ff4444;
}
}
- &[aria-disabled='true'] {
+ &[aria-disabled="true"] {
.side-content-tooltip {
// Set tooltip colour to always be the same as the background
background-color: inherit;
@@ -676,7 +679,10 @@ $code-color-error: #ff4444;
* output. Taken from react-ace
* sourcecode, font size modified.
*/
- font: 16px / normal 'Inconsolata', 'Consolas', monospace;
+ font:
+ 16px / normal "Inconsolata",
+ "Consolas",
+ monospace;
}
.code-output {
diff --git a/devserver/src/styles/index.scss b/devserver/src/styles/index.scss
index 49e5b163d..8bbc6474a 100644
--- a/devserver/src/styles/index.scss
+++ b/devserver/src/styles/index.scss
@@ -1,7 +1,7 @@
-@use 'sass:math';
+@use "sass:math";
-@import '@blueprintjs/core/lib/css/blueprint.css';
-@import '@blueprintjs/core/lib/scss/variables';
+@import "@blueprintjs/core/lib/css/blueprint.css";
+@import "@blueprintjs/core/lib/scss/variables";
// CSS styles for react-mde Markdown editor
// (currently this editor is only used for grading comments)
@@ -9,10 +9,10 @@
// styles in the preview tab of the editor, providing a more accurate
// depiction of what the actual comment will look like
-@import 'global';
+@import "global";
-@import 'application';
-@import 'commons';
-@import 'editorTabs';
-@import 'playground';
-@import 'workspace';
+@import "application";
+@import "commons";
+@import "editorTabs";
+@import "playground";
+@import "workspace";
diff --git a/devserver/src/types.ts b/devserver/src/types.ts
index dddd7cbb2..de976f026 100644
--- a/devserver/src/types.ts
+++ b/devserver/src/types.ts
@@ -44,4 +44,8 @@ export type ErrorOutput = {
consoleLogs: string[];
};
-export type InterpreterOutput = CodeOutput | ErrorOutput | ResultOutput | RunningOutput;
+export type InterpreterOutput =
+ | CodeOutput
+ | ErrorOutput
+ | ResultOutput
+ | RunningOutput;
From 98b3571d71d8ced0a806ca270452499c03a01475 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Tue, 26 Mar 2024 21:48:43 +0800
Subject: [PATCH 02/39] Reformat scripts with Prettier
---
scripts/jest.setup.ts | 33 ++-
scripts/scripts_manager.js | 2 +-
scripts/src/build/__tests__/buildAll.test.ts | 67 ++---
.../src/build/__tests__/buildUtils.test.ts | 91 ++++---
scripts/src/build/__tests__/testingUtils.ts | 35 ++-
scripts/src/build/docs/__mocks__/docsUtils.ts | 3 +-
scripts/src/build/docs/__tests__/docs.test.ts | 44 ++--
scripts/src/build/docs/__tests__/json.test.ts | 28 +-
scripts/src/build/docs/docsUtils.ts | 10 +-
scripts/src/build/docs/docsreadme.md | 9 +-
scripts/src/build/docs/drawdown.ts | 8 +-
scripts/src/build/docs/html.ts | 111 ++++----
scripts/src/build/docs/index.ts | 48 ++--
scripts/src/build/docs/json.ts | 74 ++++--
scripts/src/build/index.ts | 43 ++-
.../build/modules/__tests__/bundle.test.ts | 32 ++-
.../build/modules/__tests__/output.test.ts | 37 +--
.../build/modules/__tests__/streamMocker.ts | 2 +-
.../src/build/modules/__tests__/tab.test.ts | 29 +-
scripts/src/build/modules/bundles.ts | 71 +++--
scripts/src/build/modules/commons.ts | 26 +-
scripts/src/build/modules/index.ts | 15 +-
scripts/src/build/modules/tabs.ts | 70 +++--
scripts/src/build/prebuild/__mocks__/lint.ts | 15 +-
scripts/src/build/prebuild/__mocks__/tsc.ts | 15 +-
.../build/prebuild/__tests__/prebuild.test.ts | 62 ++---
scripts/src/build/prebuild/index.ts | 17 +-
scripts/src/build/prebuild/lint.ts | 108 +++++---
scripts/src/build/prebuild/tsc.ts | 153 +++++++----
scripts/src/build/prebuild/utils.ts | 19 +-
scripts/src/build/utils.ts | 249 ++++++++++++------
scripts/src/commandUtils.ts | 88 ++++---
scripts/src/manifest.ts | 5 +-
.../src/templates/__tests__/create.test.ts | 92 +++----
scripts/src/templates/__tests__/names.test.ts | 6 +-
scripts/src/templates/index.ts | 5 +-
scripts/src/templates/module.ts | 30 ++-
scripts/src/templates/print.ts | 11 +-
scripts/src/templates/tab.ts | 12 +-
scripts/src/templates/templates/__bundle__.ts | 1 -
scripts/src/templates/templates/__tab__.tsx | 6 +-
scripts/src/testing/__tests__/runner.test.ts | 16 +-
scripts/src/testing/index.ts | 40 +--
scripts/tsconfig.json | 2 +-
44 files changed, 1076 insertions(+), 764 deletions(-)
diff --git a/scripts/jest.setup.ts b/scripts/jest.setup.ts
index 94c883175..cdf79e6b5 100644
--- a/scripts/jest.setup.ts
+++ b/scripts/jest.setup.ts
@@ -2,9 +2,16 @@ const chalkFunction = new Proxy((x: string) => x, {
get: () => chalkFunction
});
-jest.mock('chalk', () => new Proxy({}, {
- get: () => chalkFunction
-}));
+jest.mock(
+ 'chalk',
+ () =>
+ new Proxy(
+ {},
+ {
+ get: () => chalkFunction
+ }
+ )
+);
jest.mock('fs/promises', () => ({
copyFile: jest.fn(() => Promise.resolve()),
@@ -14,15 +21,17 @@ jest.mock('fs/promises', () => ({
}));
jest.mock('./src/manifest', () => ({
- retrieveManifest: jest.fn(() => Promise.resolve({
- test0: {
- tabs: ['tab0']
- },
- test1: { tabs: [] },
- test2: {
- tabs: ['tab1']
- }
- }))
+ retrieveManifest: jest.fn(() =>
+ Promise.resolve({
+ test0: {
+ tabs: ['tab0']
+ },
+ test1: { tabs: [] },
+ test2: {
+ tabs: ['tab1']
+ }
+ })
+ )
}));
global.process.exit = jest.fn(code => {
diff --git a/scripts/scripts_manager.js b/scripts/scripts_manager.js
index 412c7e372..c807df7fd 100644
--- a/scripts/scripts_manager.js
+++ b/scripts/scripts_manager.js
@@ -3,9 +3,9 @@ import { build as esbuild } from 'esbuild'
import jest from 'jest'
import _ from 'lodash'
import pathlib from 'path'
+import { pathsToModuleNameMapper } from 'ts-jest'
import { fileURLToPath } from 'url'
import tsconfig from './tsconfig.json' with { type: 'json' }
-import { pathsToModuleNameMapper } from 'ts-jest'
function cjsDirname(url) {
return pathlib.join(pathlib.dirname(fileURLToPath(url)))
diff --git a/scripts/src/build/__tests__/buildAll.test.ts b/scripts/src/build/__tests__/buildAll.test.ts
index fc7ac69ed..c6affe8ab 100644
--- a/scripts/src/build/__tests__/buildAll.test.ts
+++ b/scripts/src/build/__tests__/buildAll.test.ts
@@ -12,8 +12,7 @@ jest.mock('../prebuild/lint');
jest.mock('../docs/docsUtils');
jest.mock('esbuild', () => ({
- build: jest.fn()
- .mockResolvedValue({ outputFiles: [] })
+ build: jest.fn().mockResolvedValue({ outputFiles: [] })
}));
jest.spyOn(jsonModule, 'buildJsons');
@@ -21,63 +20,55 @@ jest.spyOn(htmlModule, 'buildHtml');
jest.spyOn(tabsModule, 'bundleTabs');
jest.spyOn(bundleModule, 'bundleBundles');
-const asMock =
any>(func: T) => func as MockedFunction;
-const runCommand = (...args: string[]) => getBuildAllCommand()
- .parseAsync(args, { from: 'user' });
+const asMock = any>(func: T) =>
+ func as MockedFunction;
+const runCommand = (...args: string[]) =>
+ getBuildAllCommand().parseAsync(args, { from: 'user' });
describe('test build all command', () => {
- testBuildCommand(
- 'buildAll',
- getBuildAllCommand,
- [
- jsonModule.buildJsons,
- htmlModule.buildHtml,
- tabsModule.bundleTabs,
- bundleModule.bundleBundles
- ]
- );
+ testBuildCommand('buildAll', getBuildAllCommand, [
+ jsonModule.buildJsons,
+ htmlModule.buildHtml,
+ tabsModule.bundleTabs,
+ bundleModule.bundleBundles
+ ]);
it('should exit with code 1 if buildJsons returns with an error', async () => {
- asMock(jsonModule.buildJsons)
- .mockResolvedValueOnce({
- jsons: [{
+ asMock(jsonModule.buildJsons).mockResolvedValueOnce({
+ jsons: [
+ {
severity: 'error',
name: 'test0',
error: {}
- }]
- });
+ }
+ ]
+ });
try {
await runCommand();
} catch (error) {
- expect(error)
- .toEqual(new Error('process.exit called with 1'));
+ expect(error).toEqual(new Error('process.exit called with 1'));
}
- expect(process.exit)
- .toHaveBeenCalledWith(1);
+ expect(process.exit).toHaveBeenCalledWith(1);
});
it('should exit with code 1 if buildHtml returns with an error', async () => {
- asMock(htmlModule.buildHtml)
- .mockResolvedValueOnce({
- elapsed: 0,
- result: {
- severity: 'error',
- error: {}
- }
- });
+ asMock(htmlModule.buildHtml).mockResolvedValueOnce({
+ elapsed: 0,
+ result: {
+ severity: 'error',
+ error: {}
+ }
+ });
try {
await runCommand();
} catch (error) {
- expect(error)
- .toEqual(new Error('process.exit called with 1'));
+ expect(error).toEqual(new Error('process.exit called with 1'));
}
- expect(process.exit)
- .toHaveBeenCalledWith(1);
+ expect(process.exit).toHaveBeenCalledWith(1);
- expect(htmlModule.buildHtml)
- .toHaveBeenCalledTimes(1);
+ expect(htmlModule.buildHtml).toHaveBeenCalledTimes(1);
});
});
diff --git a/scripts/src/build/__tests__/buildUtils.test.ts b/scripts/src/build/__tests__/buildUtils.test.ts
index b60835847..83b7d1d54 100644
--- a/scripts/src/build/__tests__/buildUtils.test.ts
+++ b/scripts/src/build/__tests__/buildUtils.test.ts
@@ -1,9 +1,14 @@
import { retrieveBundlesAndTabs } from '@src/commandUtils';
-type TestCase = [desc: string, {
- bundles?: string[] | null
- tabs?: string[] | null
-}, boolean, Awaited>];
+type TestCase = [
+ desc: string,
+ {
+ bundles?: string[] | null;
+ tabs?: string[] | null;
+ },
+ boolean,
+ Awaited>
+];
const testCases: TestCase[] = [
[
@@ -105,41 +110,57 @@ const testCases: TestCase[] = [
];
describe('Test retrieveBundlesAndTabs', () => {
- test.each(testCases)('%#. %s:', async (_, inputs, shouldAddModuleTabs, expected) => {
- const outputs = await retrieveBundlesAndTabs({
- ...inputs,
- manifest: 'modules.json'
- }, shouldAddModuleTabs);
- expect(outputs)
- .toMatchObject(expected);
- });
+ test.each(testCases)(
+ '%#. %s:',
+ async (_, inputs, shouldAddModuleTabs, expected) => {
+ const outputs = await retrieveBundlesAndTabs(
+ {
+ ...inputs,
+ manifest: 'modules.json'
+ },
+ shouldAddModuleTabs
+ );
+ expect(outputs).toMatchObject(expected);
+ }
+ );
- it('should throw an exception when encountering unknown modules or tabs', () => Promise.all([
- expect(retrieveBundlesAndTabs({
- manifest: '',
- bundles: ['random'],
- tabs: null
- }, true)).rejects.toMatchObject(new Error('Unknown bundles: random')),
+ it('should throw an exception when encountering unknown modules or tabs', () =>
+ Promise.all([
+ expect(
+ retrieveBundlesAndTabs(
+ {
+ manifest: '',
+ bundles: ['random'],
+ tabs: null
+ },
+ true
+ )
+ ).rejects.toMatchObject(new Error('Unknown bundles: random')),
- expect(retrieveBundlesAndTabs({
- manifest: '',
- bundles: [],
- tabs: ['random1', 'random2']
- }, false)).rejects.toMatchObject(new Error('Unknown tabs: random1, random2'))
- ]));
+ expect(
+ retrieveBundlesAndTabs(
+ {
+ manifest: '',
+ bundles: [],
+ tabs: ['random1', 'random2']
+ },
+ false
+ )
+ ).rejects.toMatchObject(new Error('Unknown tabs: random1, random2'))
+ ]));
it('should always return unique modules and tabs', async () => {
- const result = await retrieveBundlesAndTabs({
- manifest: '',
- bundles: ['test0', 'test0'],
- tabs: ['tab0']
- }, false);
+ const result = await retrieveBundlesAndTabs(
+ {
+ manifest: '',
+ bundles: ['test0', 'test0'],
+ tabs: ['tab0']
+ },
+ false
+ );
- expect(result.bundles)
- .toEqual(['test0']);
- expect(result.modulesSpecified)
- .toBe(true);
- expect(result.tabs)
- .toEqual(['tab0']);
+ expect(result.bundles).toEqual(['test0']);
+ expect(result.modulesSpecified).toBe(true);
+ expect(result.tabs).toEqual(['tab0']);
});
});
diff --git a/scripts/src/build/__tests__/testingUtils.ts b/scripts/src/build/__tests__/testingUtils.ts
index d052dcd87..41aa64c52 100644
--- a/scripts/src/build/__tests__/testingUtils.ts
+++ b/scripts/src/build/__tests__/testingUtils.ts
@@ -17,13 +17,13 @@ export function testBuildCommand(
mockedFunctions: MockedFunction[]
) {
function expectToBeCalled(times: number) {
- mockedFunctions.forEach((func) => expect(func)
- .toHaveBeenCalledTimes(times));
+ mockedFunctions.forEach((func) =>
+ expect(func).toHaveBeenCalledTimes(times)
+ );
}
function runCommand(...args: string[]) {
- return commandGetter()
- .parseAsync(args, { from: 'user' });
+ return commandGetter().parseAsync(args, { from: 'user' });
}
test(`${commandName} should run tsc when --tsc is specified`, async () => {
@@ -36,8 +36,7 @@ export function testBuildCommand(
});
await runCommand('--tsc');
- expect(tsc.runTsc)
- .toHaveBeenCalledTimes(1);
+ expect(tsc.runTsc).toHaveBeenCalledTimes(1);
expectToBeCalled(1);
});
@@ -50,12 +49,11 @@ export function testBuildCommand(
}
});
- await expect(runCommand('--tsc'))
- .rejects
- .toMatchInlineSnapshot('[Error: process.exit called with 1]');
+ await expect(runCommand('--tsc')).rejects.toMatchInlineSnapshot(
+ '[Error: process.exit called with 1]'
+ );
- expect(tsc.runTsc)
- .toHaveBeenCalledTimes(1);
+ expect(tsc.runTsc).toHaveBeenCalledTimes(1);
expectToBeCalled(0);
});
@@ -68,8 +66,7 @@ export function testBuildCommand(
}
});
await runCommand('--lint');
- expect(lint.runEslint)
- .toHaveBeenCalledTimes(1);
+ expect(lint.runEslint).toHaveBeenCalledTimes(1);
expectToBeCalled(1);
});
@@ -82,19 +79,17 @@ export function testBuildCommand(
}
});
- await expect(runCommand('--lint'))
- .rejects
- .toMatchInlineSnapshot('[Error: process.exit called with 1]');
+ await expect(runCommand('--lint')).rejects.toMatchInlineSnapshot(
+ '[Error: process.exit called with 1]'
+ );
- expect(lint.runEslint)
- .toHaveBeenCalledTimes(1);
+ expect(lint.runEslint).toHaveBeenCalledTimes(1);
expectToBeCalled(0);
});
test(`${commandName} should copy the manifest if there are no errors`, async () => {
await runCommand();
expectToBeCalled(1);
- expect(fs.copyFile)
- .toHaveBeenCalledTimes(1);
+ expect(fs.copyFile).toHaveBeenCalledTimes(1);
});
}
diff --git a/scripts/src/build/docs/__mocks__/docsUtils.ts b/scripts/src/build/docs/__mocks__/docsUtils.ts
index 8532cf4da..e74da0b3d 100644
--- a/scripts/src/build/docs/__mocks__/docsUtils.ts
+++ b/scripts/src/build/docs/__mocks__/docsUtils.ts
@@ -7,8 +7,7 @@ export const initTypedoc = jest.fn(() => {
} as any;
const app = {
- convert: jest.fn()
- .mockReturnValue(proj),
+ convert: jest.fn().mockReturnValue(proj),
generateDocs: jest.fn(() => Promise.resolve())
};
diff --git a/scripts/src/build/docs/__tests__/docs.test.ts b/scripts/src/build/docs/__tests__/docs.test.ts
index 5af72a20c..7f905872b 100644
--- a/scripts/src/build/docs/__tests__/docs.test.ts
+++ b/scripts/src/build/docs/__tests__/docs.test.ts
@@ -9,42 +9,40 @@ jest.mock('../docsUtils');
jest.spyOn(json, 'buildJsons');
jest.spyOn(html, 'buildHtml');
-const asMock = any>(func: T) => func as MockedFunction;
+const asMock = any>(func: T) =>
+ func as MockedFunction;
const mockBuildJson = asMock(json.buildJsons);
-const runCommand = (...args: string[]) => getBuildDocsCommand()
- .parseAsync(args, { from: 'user' });
+const runCommand = (...args: string[]) =>
+ getBuildDocsCommand().parseAsync(args, { from: 'user' });
describe('test the docs command', () => {
- testBuildCommand(
- 'buildDocs',
- getBuildDocsCommand,
- [json.buildJsons, html.buildHtml]
- );
+ testBuildCommand('buildDocs', getBuildDocsCommand, [
+ json.buildJsons,
+ html.buildHtml
+ ]);
it('should only build the documentation for specified modules', async () => {
await runCommand('-b', 'test0', 'test1');
- expect(json.buildJsons)
- .toHaveBeenCalledTimes(1);
+ expect(json.buildJsons).toHaveBeenCalledTimes(1);
const buildJsonCall = mockBuildJson.mock.calls[0];
- expect(buildJsonCall[0])
- .toEqual({
- bundles: ['test0', 'test1'],
- tabs: [],
- modulesSpecified: true
- });
-
- expect(html.buildHtml)
- .toHaveBeenCalledTimes(1);
-
- expect(html.buildHtml)
- .toReturnWith(Promise.resolve({
+ expect(buildJsonCall[0]).toEqual({
+ bundles: ['test0', 'test1'],
+ tabs: [],
+ modulesSpecified: true
+ });
+
+ expect(html.buildHtml).toHaveBeenCalledTimes(1);
+
+ expect(html.buildHtml).toReturnWith(
+ Promise.resolve({
elapsed: 0,
result: {
severity: 'warn'
}
- }));
+ })
+ );
});
});
diff --git a/scripts/src/build/docs/__tests__/json.test.ts b/scripts/src/build/docs/__tests__/json.test.ts
index df85d1cc8..7565b2852 100644
--- a/scripts/src/build/docs/__tests__/json.test.ts
+++ b/scripts/src/build/docs/__tests__/json.test.ts
@@ -7,38 +7,30 @@ jest.spyOn(json, 'buildJsons');
jest.mock('../docsUtils');
const mockBuildJson = json.buildJsons as MockedFunction;
-const runCommand = (...args: string[]) => json.getBuildJsonsCommand()
- .parseAsync(args, { from: 'user' });
+const runCommand = (...args: string[]) =>
+ json.getBuildJsonsCommand().parseAsync(args, { from: 'user' });
// TODO Figure out why expect(json.buildJsons).toHaveBeenCalledTimes is always 0
describe.skip('test json command', () => {
- testBuildCommand(
- 'buildJsons',
- json.getBuildJsonsCommand,
- [json.buildJsons]
- );
+ testBuildCommand('buildJsons', json.getBuildJsonsCommand, [json.buildJsons]);
test('normal function', async () => {
await runCommand();
- expect(fs.mkdir)
- .toBeCalledWith('build/jsons', { recursive: true });
+ expect(fs.mkdir).toBeCalledWith('build/jsons', { recursive: true });
- expect(json.buildJsons)
- .toHaveBeenCalledTimes(1);
+ expect(json.buildJsons).toHaveBeenCalledTimes(1);
});
it('should only build the jsons for specified modules', async () => {
await runCommand('-b', 'test0', 'test1');
- expect(json.buildJsons)
- .toHaveBeenCalledTimes(1);
+ expect(json.buildJsons).toHaveBeenCalledTimes(1);
const buildJsonCall = mockBuildJson.mock.calls[0];
- expect(buildJsonCall[1])
- .toMatchObject({
- outDir: 'build',
- bundles: ['test0', 'test1']
- });
+ expect(buildJsonCall[1]).toMatchObject({
+ outDir: 'build',
+ bundles: ['test0', 'test1']
+ });
});
});
diff --git a/scripts/src/build/docs/docsUtils.ts b/scripts/src/build/docs/docsUtils.ts
index 9ecc6edc3..df222b961 100644
--- a/scripts/src/build/docs/docsUtils.ts
+++ b/scripts/src/build/docs/docsUtils.ts
@@ -1,7 +1,11 @@
import * as td from 'typedoc';
import { expandBundleNames } from '../utils';
-export async function initTypedoc(bundles: string[], srcDir: string, verbose: boolean) {
+export async function initTypedoc(
+ bundles: string[],
+ srcDir: string,
+ verbose: boolean
+) {
const app = await td.Application.bootstrap({
categorizeByGroup: true,
entryPoints: expandBundleNames(srcDir, bundles),
@@ -17,7 +21,9 @@ export async function initTypedoc(bundles: string[], srcDir: string, verbose: bo
app.options.addReader(new td.TSConfigReader());
const project = await app.convert();
if (!project) {
- throw new Error('Failed to initialize typedoc - Make sure to check that the source files have no compilation errors!');
+ throw new Error(
+ 'Failed to initialize typedoc - Make sure to check that the source files have no compilation errors!'
+ );
}
return [project, app] as [td.ProjectReflection, td.Application];
}
diff --git a/scripts/src/build/docs/docsreadme.md b/scripts/src/build/docs/docsreadme.md
index 0adf8f5be..79538a4fd 100644
--- a/scripts/src/build/docs/docsreadme.md
+++ b/scripts/src/build/docs/docsreadme.md
@@ -1,18 +1,23 @@
# Overview
The Source Academy allows programmers to import functions and constants from a module, using JavaScript's `import` directive. For example, the programmer may decide to import the function `thrice` from the module `repeat` by starting the program with
+
```
import { thrice } from "repeat";
```
-When evaluating such a directive, the Source Academy looks for a module with the matching name, here `repeat`, in a preconfigured modules site. The Source Academy at https://sourceacademy.org uses the default modules site (located at https://source-academy.github.io/modules).
+When evaluating such a directive, the Source Academy looks for a module with the matching name, here `repeat`, in a preconfigured modules site. The Source Academy at uses the default modules site (located at ).
After importing functions or constants from a module, they can be used as usual.
+
```
thrice(display)(8); // displays 8 three times
```
+
if `thrice` is declared in the module `repeat` as follows:
+
```
const thrice = f => x => f(f(f(x)));
```
-[List of modules](modules.html) available at the default modules site.
\ No newline at end of file
+
+[List of modules](modules.html) available at the default modules site.
diff --git a/scripts/src/build/docs/drawdown.ts b/scripts/src/build/docs/drawdown.ts
index 8fe5d5aaa..cb55d3afc 100644
--- a/scripts/src/build/docs/drawdown.ts
+++ b/scripts/src/build/docs/drawdown.ts
@@ -12,9 +12,11 @@ export default (src: string): string => {
var rx_escape = /\\([\\\|`*_{}\[\]()#+\-~])/g;
var rx_hr = /^([*\-=_] *){3,}$/gm;
var rx_blockquote = /\n *> *([^]*?)(?=(\n|$){2})/g;
- var rx_list = /\n( *)(?:[*\-+]|((\d+)|([a-z])|[A-Z])[.)]) +([^]*?)(?=(\n|$){2})/g;
+ var rx_list =
+ /\n( *)(?:[*\-+]|((\d+)|([a-z])|[A-Z])[.)]) +([^]*?)(?=(\n|$){2})/g;
var rx_listjoin = /<\/(ol|ul)>\n\n<\1>/g;
- var rx_highlight = /(^|[^A-Za-z\d\\])(([*_])|(~)|(\^)|(--)|(\+\+)|`)(\2?)([^<]*?)\2\8(?!\2)(?=\W|_|$)/g;
+ var rx_highlight =
+ /(^|[^A-Za-z\d\\])(([*_])|(~)|(\^)|(--)|(\+\+)|`)(\2?)([^<]*?)\2\8(?!\2)(?=\W|_|$)/g;
var rx_code = /\n((```|~~~).*\n?([^]*?)\n?\2|(( {4}.*?\n)+))/g;
var rx_link = /((!?)\[(.*?)\]\((.*?)( ".*")?\)|\\([\\`*_{}\[\]()#+\-.!~]))/g;
var rx_table = /\n(( *\|.*?\| *\n)+)/g;
@@ -187,4 +189,4 @@ export default (src: string): string => {
});
return src.trim();
-};
\ No newline at end of file
+};
diff --git a/scripts/src/build/docs/html.ts b/scripts/src/build/docs/html.ts
index fa4e8a336..4135f879c 100644
--- a/scripts/src/build/docs/html.ts
+++ b/scripts/src/build/docs/html.ts
@@ -1,61 +1,84 @@
import { Command } from '@commander-js/extra-typings';
import chalk from 'chalk';
-import { manifestOption, outDirOption, retrieveBundlesAndTabs, srcDirOption, wrapWithTimer } from '@src/commandUtils';
-import type { BuildInputs, AwaitedReturn } from '../utils';
+import {
+ manifestOption,
+ outDirOption,
+ retrieveBundlesAndTabs,
+ srcDirOption,
+ wrapWithTimer
+} from '@src/commandUtils';
+import type { AwaitedReturn, BuildInputs } from '../utils';
import { initTypedoc, type TypedocResult } from './docsUtils';
-export type HtmlResult = {
- severity: 'error' | 'warn'
- error: any
-} | {
- severity: 'success'
-};
-
-export const buildHtml = wrapWithTimer(async (
- inputs: BuildInputs,
- outDir: string,
- [project, app]: TypedocResult
-): Promise => {
- if (inputs.modulesSpecified) {
- return {
- severity: 'warn',
- error: 'Not all modules were built, skipping building HTML documentation'
- };
+export type HtmlResult =
+ | {
+ severity: 'error' | 'warn';
+ error: any;
}
+ | {
+ severity: 'success';
+ };
+
+export const buildHtml = wrapWithTimer(
+ async (
+ inputs: BuildInputs,
+ outDir: string,
+ [project, app]: TypedocResult
+ ): Promise => {
+ if (inputs.modulesSpecified) {
+ return {
+ severity: 'warn',
+ error:
+ 'Not all modules were built, skipping building HTML documentation'
+ };
+ }
- try {
- await app.generateDocs(project, `${outDir}/documentation`);
- return {
- severity: 'success'
- };
- } catch (error) {
- return {
- severity: 'error',
- error
- };
+ try {
+ await app.generateDocs(project, `${outDir}/documentation`);
+ return {
+ severity: 'success'
+ };
+ } catch (error) {
+ return {
+ severity: 'error',
+ error
+ };
+ }
}
-});
+);
-export function htmlLogger({ result, elapsed }: AwaitedReturn) {
+export function htmlLogger({
+ result,
+ elapsed
+}: AwaitedReturn) {
const timeStr = `${(elapsed / 1000).toFixed(2)}s`;
switch (result.severity) {
case 'success':
- return `${chalk.cyanBright('Built HTML documentation')} ${chalk.greenBright('successfully')} in ${timeStr}`;
+ return `${chalk.cyanBright(
+ 'Built HTML documentation'
+ )} ${chalk.greenBright('successfully')} in ${timeStr}`;
case 'warn':
return chalk.yellowBright(result.error);
case 'error':
- return `${chalk.redBright('Failed')} ${chalk.cyanBright('to build HTML documentation: ')} ${result.error}`;
+ return `${chalk.redBright('Failed')} ${chalk.cyanBright(
+ 'to build HTML documentation: '
+ )} ${result.error}`;
}
}
-export const getBuildHtmlCommand = () => new Command('html')
- .addOption(srcDirOption)
- .addOption(outDirOption)
- .addOption(manifestOption)
- .option('-v, --verbose')
- .action(async opts => {
- const inputs = await retrieveBundlesAndTabs({ ...opts, tabs: [] }, false);
- const tdResult = await initTypedoc(inputs.bundles, opts.srcDir, opts.verbose);
- const result = await buildHtml(inputs, opts.outDir, tdResult);
- console.log(htmlLogger(result));
- });
+export const getBuildHtmlCommand = () =>
+ new Command('html')
+ .addOption(srcDirOption)
+ .addOption(outDirOption)
+ .addOption(manifestOption)
+ .option('-v, --verbose')
+ .action(async opts => {
+ const inputs = await retrieveBundlesAndTabs({ ...opts, tabs: [] }, false);
+ const tdResult = await initTypedoc(
+ inputs.bundles,
+ opts.srcDir,
+ opts.verbose
+ );
+ const result = await buildHtml(inputs, opts.outDir, tdResult);
+ console.log(htmlLogger(result));
+ });
diff --git a/scripts/src/build/docs/index.ts b/scripts/src/build/docs/index.ts
index 007d23aa8..6f82da719 100644
--- a/scripts/src/build/docs/index.ts
+++ b/scripts/src/build/docs/index.ts
@@ -1,12 +1,21 @@
import { bundlesOption } from '@src/commandUtils';
-import { createBuildCommand, type BuildInputs, createBuildCommandHandler, type AwaitedReturn } from '../utils';
+import {
+ createBuildCommand,
+ createBuildCommandHandler,
+ type AwaitedReturn,
+ type BuildInputs
+} from '../utils';
import { initTypedoc, type TypedocResult } from './docsUtils';
import { buildHtml } from './html';
import { buildJsons } from './json';
-export async function buildDocs(inputs: BuildInputs, outDir: string, tdResult: TypedocResult): Promise<
+export async function buildDocs(
+ inputs: BuildInputs,
+ outDir: string,
+ tdResult: TypedocResult
+): Promise<
AwaitedReturn & { html: AwaitedReturn }
-> {
+ > {
const [jsonsResult, htmlResult] = await Promise.all([
buildJsons(inputs, outDir, tdResult[0]),
buildHtml(inputs, outDir, tdResult)
@@ -18,22 +27,25 @@ export async function buildDocs(inputs: BuildInputs, outDir: string, tdResult: T
};
}
-const docsCommandHandler = createBuildCommandHandler(async (inputs, { srcDir, outDir, verbose }) => {
- const tdResult = await initTypedoc(inputs.bundles, srcDir, verbose);
- return buildDocs(inputs, outDir, tdResult);
-}, false);
+const docsCommandHandler = createBuildCommandHandler(
+ async (inputs, { srcDir, outDir, verbose }) => {
+ const tdResult = await initTypedoc(inputs.bundles, srcDir, verbose);
+ return buildDocs(inputs, outDir, tdResult);
+ },
+ false
+);
-export const getBuildDocsCommand = () => createBuildCommand(
- 'docs',
- 'Build HTML and json documentation'
-)
- .addOption(bundlesOption)
- .action(opts => docsCommandHandler({
- ...opts,
- tabs: []
- }));
+export const getBuildDocsCommand = () =>
+ createBuildCommand('docs', 'Build HTML and json documentation')
+ .addOption(bundlesOption)
+ .action(opts =>
+ docsCommandHandler({
+ ...opts,
+ tabs: []
+ })
+ );
-export { getBuildJsonsCommand } from './json';
export { getBuildHtmlCommand } from './html';
+export { getBuildJsonsCommand } from './json';
-export { buildJsons, buildHtml };
+export { buildHtml, buildJsons };
diff --git a/scripts/src/build/docs/json.ts b/scripts/src/build/docs/json.ts
index 1bb64e2b2..12b506539 100644
--- a/scripts/src/build/docs/json.ts
+++ b/scripts/src/build/docs/json.ts
@@ -1,7 +1,12 @@
import fs from 'fs/promises';
import * as td from 'typedoc';
import { bundlesOption } from '@src/commandUtils';
-import { createBuildCommand, createBuildCommandHandler, type BuildInputs, type OperationResult } from '../utils';
+import {
+ createBuildCommand,
+ createBuildCommandHandler,
+ type BuildInputs,
+ type OperationResult
+} from '../utils';
import { initTypedoc } from './docsUtils';
import drawdown from './drawdown';
@@ -14,13 +19,16 @@ const parsers = {
let description: string;
if (signature.comment) {
- description = drawdown(signature.comment.summary.map(({ text }) => text)
- .join(''));
+ description = drawdown(
+ signature.comment.summary.map(({ text }) => text).join('')
+ );
} else {
description = 'No description available';
}
- const params = signature.parameters.map(({ type, name }) => [name, typeToName(type)] as [string, string]);
+ const params = signature.parameters.map(
+ ({ type, name }) => [name, typeToName(type)] as [string, string]
+ );
return {
kind: 'function',
@@ -33,8 +41,9 @@ const parsers = {
[td.ReflectionKind.Variable](obj) {
let description: string;
if (obj.comment) {
- description = drawdown(obj.comment.summary.map(({ text }) => text)
- .join(''));
+ description = drawdown(
+ obj.comment.summary.map(({ text }) => text).join('')
+ );
} else {
description = 'No description available';
}
@@ -46,21 +55,28 @@ const parsers = {
type: typeToName(obj.type)
};
}
-} satisfies Partial any>>;
-
-async function buildJson(name: string, reflection: td.DeclarationReflection, outDir: string): Promise {
+} satisfies Partial<
+ Record any>
+>;
+
+async function buildJson(
+ name: string,
+ reflection: td.DeclarationReflection,
+ outDir: string
+): Promise {
try {
const jsonData = reflection.children.reduce((res, element) => {
const parser = parsers[element.kind];
return {
...res,
- [element.name]: parser
- ? parser(element)
- : { kind: 'unknown' }
+ [element.name]: parser ? parser(element) : { kind: 'unknown' }
};
}, {});
- await fs.writeFile(`${outDir}/jsons/${name}.json`, JSON.stringify(jsonData, null, 2));
+ await fs.writeFile(
+ `${outDir}/jsons/${name}.json`,
+ JSON.stringify(jsonData, null, 2)
+ );
return {
name,
@@ -95,22 +111,30 @@ export async function buildJsons(
};
}
- const results = await Promise.all(bundles.map(bundle => buildJson(
- bundle,
- project.getChildByName(bundle) as td.DeclarationReflection,
- outDir
- )));
+ const results = await Promise.all(
+ bundles.map(bundle =>
+ buildJson(
+ bundle,
+ project.getChildByName(bundle) as td.DeclarationReflection,
+ outDir
+ )
+ )
+ );
return {
jsons: results
};
}
-const jsonCommandHandler = createBuildCommandHandler(async (inputs, { srcDir, outDir, verbose }) => {
- const [project] = await initTypedoc(inputs.bundles, srcDir, verbose);
- return buildJsons(inputs, outDir, project);
-}, false);
+const jsonCommandHandler = createBuildCommandHandler(
+ async (inputs, { srcDir, outDir, verbose }) => {
+ const [project] = await initTypedoc(inputs.bundles, srcDir, verbose);
+ return buildJsons(inputs, outDir, project);
+ },
+ false
+);
-export const getBuildJsonsCommand = () => createBuildCommand('jsons', 'Build json documentation')
- .addOption(bundlesOption)
- .action(opts => jsonCommandHandler({ ...opts, tabs: [] }));
+export const getBuildJsonsCommand = () =>
+ createBuildCommand('jsons', 'Build json documentation')
+ .addOption(bundlesOption)
+ .action(opts => jsonCommandHandler({ ...opts, tabs: [] }));
diff --git a/scripts/src/build/index.ts b/scripts/src/build/index.ts
index 9d9fe936c..727e49d82 100644
--- a/scripts/src/build/index.ts
+++ b/scripts/src/build/index.ts
@@ -1,9 +1,22 @@
import { Command } from '@commander-js/extra-typings';
import { bundlesOption, tabsOption } from '@src/commandUtils';
-import { buildDocs, getBuildDocsCommand, getBuildHtmlCommand, getBuildJsonsCommand } from './docs';
+import {
+ buildDocs,
+ getBuildDocsCommand,
+ getBuildHtmlCommand,
+ getBuildJsonsCommand
+} from './docs';
import { initTypedoc } from './docs/docsUtils';
-import { buildModules, getBuildBundlesCommand, getBuildTabsCommand } from './modules';
-import { createBuildCommand, type BuildTask, createBuildCommandHandler } from './utils';
+import {
+ buildModules,
+ getBuildBundlesCommand,
+ getBuildTabsCommand
+} from './modules';
+import {
+ createBuildCommand,
+ createBuildCommandHandler,
+ type BuildTask
+} from './utils';
const buildAll: BuildTask = async (inputs, opts) => {
const tdResult = await initTypedoc(inputs.bundles, opts.srcDir, opts.verbose);
@@ -20,17 +33,19 @@ const buildAll: BuildTask = async (inputs, opts) => {
};
const buildAllCommandHandler = createBuildCommandHandler(buildAll, true);
-const getBuildAllCommand = () => createBuildCommand('all', 'Build bundles and tabs and documentation')
- .addOption(bundlesOption)
- .addOption(tabsOption)
- .action(buildAllCommandHandler);
+const getBuildAllCommand = () =>
+ createBuildCommand('all', 'Build bundles and tabs and documentation')
+ .addOption(bundlesOption)
+ .addOption(tabsOption)
+ .action(buildAllCommandHandler);
-const getBuildCommand = () => new Command('build')
- .addCommand(getBuildAllCommand(), { isDefault: true })
- .addCommand(getBuildBundlesCommand())
- .addCommand(getBuildDocsCommand())
- .addCommand(getBuildHtmlCommand())
- .addCommand(getBuildJsonsCommand())
- .addCommand(getBuildTabsCommand());
+const getBuildCommand = () =>
+ new Command('build')
+ .addCommand(getBuildAllCommand(), { isDefault: true })
+ .addCommand(getBuildBundlesCommand())
+ .addCommand(getBuildDocsCommand())
+ .addCommand(getBuildHtmlCommand())
+ .addCommand(getBuildJsonsCommand())
+ .addCommand(getBuildTabsCommand());
export default getBuildCommand;
diff --git a/scripts/src/build/modules/__tests__/bundle.test.ts b/scripts/src/build/modules/__tests__/bundle.test.ts
index ea917ec23..dc0e0b643 100644
--- a/scripts/src/build/modules/__tests__/bundle.test.ts
+++ b/scripts/src/build/modules/__tests__/bundle.test.ts
@@ -5,28 +5,26 @@ import * as bundles from '../bundles';
jest.spyOn(bundles, 'bundleBundles');
jest.mock('esbuild', () => ({
- build: jest.fn()
- .mockResolvedValue({ outputFiles: [] })
+ build: jest.fn().mockResolvedValue({ outputFiles: [] })
}));
-testBuildCommand(
- 'buildBundles',
- bundles.getBuildBundlesCommand,
- [bundles.bundleBundles]
-);
+testBuildCommand('buildBundles', bundles.getBuildBundlesCommand, [
+ bundles.bundleBundles
+]);
test('Normal command', async () => {
- await bundles.getBuildBundlesCommand()
+ await bundles
+ .getBuildBundlesCommand()
.parseAsync(['-b', 'test0'], { from: 'user' });
- expect(bundles.bundleBundles)
- .toHaveBeenCalledTimes(1);
+ expect(bundles.bundleBundles).toHaveBeenCalledTimes(1);
- const [args] = (bundles.bundleBundles as MockedFunction).mock.calls[0];
- expect(args)
- .toMatchObject({
- bundles: ['test0'],
- tabs: ['tab0'],
- modulesSpecified: true
- });
+ const [args] = (
+ bundles.bundleBundles as MockedFunction
+ ).mock.calls[0];
+ expect(args).toMatchObject({
+ bundles: ['test0'],
+ tabs: ['tab0'],
+ modulesSpecified: true
+ });
});
diff --git a/scripts/src/build/modules/__tests__/output.test.ts b/scripts/src/build/modules/__tests__/output.test.ts
index 6849a7aba..1534924af 100644
--- a/scripts/src/build/modules/__tests__/output.test.ts
+++ b/scripts/src/build/modules/__tests__/output.test.ts
@@ -12,7 +12,9 @@ const testBundle = `
`;
test('building a bundle', async () => {
- const { outputFiles: [file] } = await esbuild({
+ const {
+ outputFiles: [file]
+ } = await esbuild({
...commonEsbuildOptions,
stdin: {
contents: testBundle
@@ -25,10 +27,11 @@ test('building a bundle', async () => {
const rawBundleTextPromise = mockStream();
const result = await outputBundleOrTab(file, 'build');
- expect(result.severity)
- .toEqual('success');
+ expect(result.severity).toEqual('success');
- const bundleText = (await rawBundleTextPromise).slice('export default'.length);
+ const bundleText = (await rawBundleTextPromise).slice(
+ 'export default'.length
+ );
const mockContext = {
moduleContexts: {
test0: {
@@ -36,17 +39,17 @@ test('building a bundle', async () => {
}
}
};
- const bundleFuncs = eval(bundleText)((x) => ({
- 'js-slang/context': mockContext
- }[x]));
- expect(bundleFuncs.foo())
- .toEqual('foo');
- expect(bundleFuncs.bar())
- .toEqual(undefined);
- expect(mockContext.moduleContexts)
- .toMatchObject({
- test0: {
- state: 'bar'
- }
- });
+ const bundleFuncs = eval(bundleText)(
+ (x) =>
+ ({
+ 'js-slang/context': mockContext
+ }[x])
+ );
+ expect(bundleFuncs.foo()).toEqual('foo');
+ expect(bundleFuncs.bar()).toEqual(undefined);
+ expect(mockContext.moduleContexts).toMatchObject({
+ test0: {
+ state: 'bar'
+ }
+ });
});
diff --git a/scripts/src/build/modules/__tests__/streamMocker.ts b/scripts/src/build/modules/__tests__/streamMocker.ts
index 6b2007557..6c4408ef0 100644
--- a/scripts/src/build/modules/__tests__/streamMocker.ts
+++ b/scripts/src/build/modules/__tests__/streamMocker.ts
@@ -2,7 +2,7 @@ import fs from 'fs/promises';
import { PassThrough } from 'stream';
import type { MockedFunction } from 'jest-mock';
-const mockedFsOpen = (fs.open as MockedFunction);
+const mockedFsOpen = fs.open as MockedFunction;
export function mockStream() {
const stream = new PassThrough();
diff --git a/scripts/src/build/modules/__tests__/tab.test.ts b/scripts/src/build/modules/__tests__/tab.test.ts
index 0d028f587..63aa00619 100644
--- a/scripts/src/build/modules/__tests__/tab.test.ts
+++ b/scripts/src/build/modules/__tests__/tab.test.ts
@@ -3,30 +3,23 @@ import type { MockedFunction } from 'jest-mock';
import * as tabs from '../tabs';
jest.mock('esbuild', () => ({
- build: jest.fn()
- .mockResolvedValue({ outputFiles: [] })
+ build: jest.fn().mockResolvedValue({ outputFiles: [] })
}));
jest.spyOn(tabs, 'bundleTabs');
-testBuildCommand(
- 'buildTabs',
- tabs.getBuildTabsCommand,
- [tabs.bundleTabs]
-);
+testBuildCommand('buildTabs', tabs.getBuildTabsCommand, [tabs.bundleTabs]);
test('Normal command', async () => {
- await tabs.getBuildTabsCommand()
- .parseAsync(['-t', 'tab0'], { from: 'user' });
+ await tabs.getBuildTabsCommand().parseAsync(['-t', 'tab0'], { from: 'user' });
- expect(tabs.bundleTabs)
- .toHaveBeenCalledTimes(1);
+ expect(tabs.bundleTabs).toHaveBeenCalledTimes(1);
- const [args] = (tabs.bundleTabs as MockedFunction).mock.calls[0];
- expect(args)
- .toMatchObject({
- bundles: [],
- tabs: ['tab0'],
- modulesSpecified: true
- });
+ const [args] = (tabs.bundleTabs as MockedFunction)
+ .mock.calls[0];
+ expect(args).toMatchObject({
+ bundles: [],
+ tabs: ['tab0'],
+ modulesSpecified: true
+ });
});
diff --git a/scripts/src/build/modules/bundles.ts b/scripts/src/build/modules/bundles.ts
index 85471b002..8d9fbc3c3 100644
--- a/scripts/src/build/modules/bundles.ts
+++ b/scripts/src/build/modules/bundles.ts
@@ -1,7 +1,12 @@
import fs from 'fs/promises';
import { build as esbuild, type Plugin as ESBuildPlugin } from 'esbuild';
import { bundlesOption, promiseAll } from '@src/commandUtils';
-import { expandBundleNames, type BuildTask, createBuildCommandHandler, createBuildCommand } from '../utils';
+import {
+ createBuildCommand,
+ createBuildCommandHandler,
+ expandBundleNames,
+ type BuildTask
+} from '../utils';
import { commonEsbuildOptions, outputBundleOrTab } from './commons';
export const assertPolyfillPlugin: ESBuildPlugin = {
@@ -13,11 +18,13 @@ export const assertPolyfillPlugin: ESBuildPlugin = {
namespace: 'bundleAssert'
}));
- build.onLoad({
- filter: /^assert/u,
- namespace: 'bundleAssert'
- }, () => ({
- contents: `
+ build.onLoad(
+ {
+ filter: /^assert/u,
+ namespace: 'bundleAssert'
+ },
+ () => ({
+ contents: `
export default function assert(condition, message) {
if (condition) return;
@@ -28,7 +35,8 @@ export const assertPolyfillPlugin: ESBuildPlugin = {
throw message;
}
`
- }));
+ })
+ );
}
};
@@ -59,28 +67,37 @@ export const assertPolyfillPlugin: ESBuildPlugin = {
// }
// }
-export const bundleBundles: BuildTask = async ({ bundles }, { srcDir, outDir }) => {
- const [{ outputFiles }] = await promiseAll(esbuild({
- ...commonEsbuildOptions,
- entryPoints: expandBundleNames(srcDir, bundles),
- outbase: outDir,
- outdir: outDir,
- plugins: [
- assertPolyfillPlugin
- // jsSlangExportCheckingPlugin,
- ],
- tsconfig: `${srcDir}/tsconfig.json`
- }), fs.mkdir(`${outDir}/bundles`, { recursive: true }));
+export const bundleBundles: BuildTask = async (
+ { bundles },
+ { srcDir, outDir }
+) => {
+ const [{ outputFiles }] = await promiseAll(
+ esbuild({
+ ...commonEsbuildOptions,
+ entryPoints: expandBundleNames(srcDir, bundles),
+ outbase: outDir,
+ outdir: outDir,
+ plugins: [
+ assertPolyfillPlugin
+ // jsSlangExportCheckingPlugin,
+ ],
+ tsconfig: `${srcDir}/tsconfig.json`
+ }),
+ fs.mkdir(`${outDir}/bundles`, { recursive: true })
+ );
- const results = await Promise.all(outputFiles.map(file => outputBundleOrTab(file, outDir)));
+ const results = await Promise.all(
+ outputFiles.map(file => outputBundleOrTab(file, outDir))
+ );
return { bundles: results };
};
-const bundlesCommandHandler = createBuildCommandHandler((...args) => bundleBundles(...args), true);
+const bundlesCommandHandler = createBuildCommandHandler(
+ (...args) => bundleBundles(...args),
+ true
+);
-export const getBuildBundlesCommand = () => createBuildCommand(
- 'bundles',
- 'Build bundles'
-)
- .addOption(bundlesOption)
- .action(opts => bundlesCommandHandler({ ...opts, tabs: [] }));
+export const getBuildBundlesCommand = () =>
+ createBuildCommand('bundles', 'Build bundles')
+ .addOption(bundlesOption)
+ .action(opts => bundlesCommandHandler({ ...opts, tabs: [] }));
diff --git a/scripts/src/build/modules/commons.ts b/scripts/src/build/modules/commons.ts
index 41105337a..4ee1e39a7 100644
--- a/scripts/src/build/modules/commons.ts
+++ b/scripts/src/build/modules/commons.ts
@@ -3,7 +3,13 @@ import pathlib from 'path';
import { parse } from 'acorn';
import { generate } from 'astring';
import type { BuildOptions as ESBuildOptions, OutputFile } from 'esbuild';
-import type { ArrowFunctionExpression, CallExpression, ExportDefaultDeclaration, Program, VariableDeclaration } from 'estree';
+import type {
+ ArrowFunctionExpression,
+ CallExpression,
+ ExportDefaultDeclaration,
+ Program,
+ VariableDeclaration
+} from 'estree';
import type { OperationResult } from '../utils';
export const commonEsbuildOptions: ESBuildOptions = {
@@ -23,9 +29,11 @@ export const commonEsbuildOptions: ESBuildOptions = {
write: false
};
-export async function outputBundleOrTab({ path, text }: OutputFile, outDir: string): Promise {
- const [type, name] = path.split(pathlib.sep)
- .slice(-3, -1);
+export async function outputBundleOrTab(
+ { path, text }: OutputFile,
+ outDir: string
+): Promise {
+ const [type, name] = path.split(pathlib.sep).slice(-3, -1);
let file: fs.FileHandle | null = null;
try {
const parsed = parse(text, { ecmaVersion: 6 }) as unknown as Program;
@@ -45,10 +53,12 @@ export async function outputBundleOrTab({ path, text }: OutputFile, outDir: stri
type: 'ExportDefaultDeclaration',
declaration: {
...moduleCode,
- params: [{
- type: 'Identifier',
- name: 'require'
- }]
+ params: [
+ {
+ type: 'Identifier',
+ name: 'require'
+ }
+ ]
}
};
diff --git a/scripts/src/build/modules/index.ts b/scripts/src/build/modules/index.ts
index a308d1443..d6484cb50 100644
--- a/scripts/src/build/modules/index.ts
+++ b/scripts/src/build/modules/index.ts
@@ -1,5 +1,9 @@
import { bundlesOption, tabsOption } from '@src/commandUtils';
-import { createBuildCommand, type BuildTask, createBuildCommandHandler } from '../utils';
+import {
+ createBuildCommand,
+ createBuildCommandHandler,
+ type BuildTask
+} from '../utils';
import { bundleBundles } from './bundles';
import { bundleTabs } from './tabs';
@@ -17,10 +21,11 @@ export const buildModules: BuildTask = async (inputs, opts) => {
const modulesCommandHandler = createBuildCommandHandler(buildModules, true);
-export const getBuildModulesCommand = () => createBuildCommand('modules', 'Build bundles and tabs')
- .addOption(bundlesOption)
- .addOption(tabsOption)
- .action(modulesCommandHandler);
+export const getBuildModulesCommand = () =>
+ createBuildCommand('modules', 'Build bundles and tabs')
+ .addOption(bundlesOption)
+ .addOption(tabsOption)
+ .action(modulesCommandHandler);
export { getBuildBundlesCommand } from './bundles';
export { getBuildTabsCommand } from './tabs';
diff --git a/scripts/src/build/modules/tabs.ts b/scripts/src/build/modules/tabs.ts
index 1ffebda2c..0f39b6867 100644
--- a/scripts/src/build/modules/tabs.ts
+++ b/scripts/src/build/modules/tabs.ts
@@ -1,45 +1,61 @@
import fs from 'fs/promises';
import { build as esbuild, type Plugin as ESBuildPlugin } from 'esbuild';
import { promiseAll, tabsOption } from '@src/commandUtils';
-import { expandTabNames, createBuildCommandHandler, type BuildTask, createBuildCommand } from '../utils';
+import {
+ createBuildCommand,
+ createBuildCommandHandler,
+ expandTabNames,
+ type BuildTask
+} from '../utils';
import { commonEsbuildOptions, outputBundleOrTab } from './commons';
export const tabContextPlugin: ESBuildPlugin = {
name: 'Tab Context',
setup(build) {
build.onResolve({ filter: /^js-slang\/context/u }, () => ({
- errors: [{
- text: 'If you see this message, it means that your tab code is importing js-slang/context directly or indirectly. Do not do this'
- }]
+ errors: [
+ {
+ text: 'If you see this message, it means that your tab code is importing js-slang/context directly or indirectly. Do not do this'
+ }
+ ]
}));
}
};
export const bundleTabs: BuildTask = async ({ tabs }, { srcDir, outDir }) => {
- const [{ outputFiles }] = await promiseAll(esbuild({
- ...commonEsbuildOptions,
- entryPoints: expandTabNames(srcDir, tabs),
- external: [
- ...commonEsbuildOptions.external,
- 'react',
- 'react-ace',
- 'react-dom',
- 'react/jsx-runtime',
- '@blueprintjs/*'
- // 'phaser',
- ],
- jsx: 'automatic',
- outbase: outDir,
- outdir: outDir,
- tsconfig: `${srcDir}/tsconfig.json`,
- plugins: [tabContextPlugin]
- }), fs.mkdir(`${outDir}/tabs`, { recursive: true }));
+ const [{ outputFiles }] = await promiseAll(
+ esbuild({
+ ...commonEsbuildOptions,
+ entryPoints: expandTabNames(srcDir, tabs),
+ external: [
+ ...commonEsbuildOptions.external,
+ 'react',
+ 'react-ace',
+ 'react-dom',
+ 'react/jsx-runtime',
+ '@blueprintjs/*'
+ // 'phaser',
+ ],
+ jsx: 'automatic',
+ outbase: outDir,
+ outdir: outDir,
+ tsconfig: `${srcDir}/tsconfig.json`,
+ plugins: [tabContextPlugin]
+ }),
+ fs.mkdir(`${outDir}/tabs`, { recursive: true })
+ );
- const results = await Promise.all(outputFiles.map(file => outputBundleOrTab(file, outDir)));
+ const results = await Promise.all(
+ outputFiles.map(file => outputBundleOrTab(file, outDir))
+ );
return { tabs: results };
};
-const tabCommandHandler = createBuildCommandHandler((...args) => bundleTabs(...args), false);
-export const getBuildTabsCommand = () => createBuildCommand('tabs', 'Build tabs')
- .addOption(tabsOption)
- .action(opts => tabCommandHandler({ ...opts, bundles: [] }));
+const tabCommandHandler = createBuildCommandHandler(
+ (...args) => bundleTabs(...args),
+ false
+);
+export const getBuildTabsCommand = () =>
+ createBuildCommand('tabs', 'Build tabs')
+ .addOption(tabsOption)
+ .action(opts => tabCommandHandler({ ...opts, bundles: [] }));
diff --git a/scripts/src/build/prebuild/__mocks__/lint.ts b/scripts/src/build/prebuild/__mocks__/lint.ts
index eac3ba04f..0ff31fee8 100644
--- a/scripts/src/build/prebuild/__mocks__/lint.ts
+++ b/scripts/src/build/prebuild/__mocks__/lint.ts
@@ -1,10 +1,9 @@
-export const runEslint = jest.fn()
- .mockImplementation(() => ({
- elapsed: 0,
- result: {
- formatted: '',
- severity: 'error'
- }
- }));
+export const runEslint = jest.fn().mockImplementation(() => ({
+ elapsed: 0,
+ result: {
+ formatted: '',
+ severity: 'error'
+ }
+}));
export const eslintResultsLogger = jest.fn(() => '');
diff --git a/scripts/src/build/prebuild/__mocks__/tsc.ts b/scripts/src/build/prebuild/__mocks__/tsc.ts
index 18f7fd9a6..c58f4175b 100644
--- a/scripts/src/build/prebuild/__mocks__/tsc.ts
+++ b/scripts/src/build/prebuild/__mocks__/tsc.ts
@@ -1,10 +1,9 @@
export const tscResultsLogger = jest.fn(() => '');
-export const runTsc = jest.fn()
- .mockResolvedValue({
- elapsed: 0,
- result: {
- severity: 'error',
- results: []
- }
- });
+export const runTsc = jest.fn().mockResolvedValue({
+ elapsed: 0,
+ result: {
+ severity: 'error',
+ results: []
+ }
+});
diff --git a/scripts/src/build/prebuild/__tests__/prebuild.test.ts b/scripts/src/build/prebuild/__tests__/prebuild.test.ts
index 934883a48..0c4328da8 100644
--- a/scripts/src/build/prebuild/__tests__/prebuild.test.ts
+++ b/scripts/src/build/prebuild/__tests__/prebuild.test.ts
@@ -6,14 +6,14 @@ import * as tscModule from '../tsc';
jest.spyOn(lintModule, 'runEslint');
jest.spyOn(tscModule, 'runTsc');
-const asMock = any>(func: T) => func as MockedFunction;
+const asMock = any>(func: T) =>
+ func as MockedFunction;
const mockedTsc = asMock(tscModule.runTsc);
const mockedEslint = asMock(lintModule.runEslint);
describe('test eslint command', () => {
const runCommand = async (...args: string[]) => {
- await lintModule.getLintCommand()
- .parseAsync(args, { from: 'user' });
+ await lintModule.getLintCommand().parseAsync(args, { from: 'user' });
};
test('regular command function', async () => {
@@ -27,8 +27,7 @@ describe('test eslint command', () => {
await runCommand();
- expect(lintModule.runEslint)
- .toHaveBeenCalledTimes(1);
+ expect(lintModule.runEslint).toHaveBeenCalledTimes(1);
});
it('should only lint specified bundles and tabs', async () => {
@@ -42,16 +41,14 @@ describe('test eslint command', () => {
await runCommand('-b', 'test0', '-t', 'tab0');
- expect(lintModule.runEslint)
- .toHaveBeenCalledTimes(1);
+ expect(lintModule.runEslint).toHaveBeenCalledTimes(1);
const [lintCall] = mockedEslint.mock.calls[0];
- expect(lintCall)
- .toMatchObject({
- bundles: ['test0'],
- tabs: ['tab0'],
- srcDir: 'src'
- });
+ expect(lintCall).toMatchObject({
+ bundles: ['test0'],
+ tabs: ['tab0'],
+ srcDir: 'src'
+ });
});
it('should exit with code 1 if there are linting errors', async () => {
@@ -66,20 +63,17 @@ describe('test eslint command', () => {
try {
await runCommand();
} catch (error) {
- expect(error)
- .toEqual(new Error('process.exit called with 1'));
+ expect(error).toEqual(new Error('process.exit called with 1'));
}
- expect(lintModule.runEslint)
- .toHaveBeenCalledTimes(1);
+ expect(lintModule.runEslint).toHaveBeenCalledTimes(1);
- expect(process.exit)
- .toHaveBeenCalledWith(1);
+ expect(process.exit).toHaveBeenCalledWith(1);
});
});
describe('test tsc command', () => {
- const runCommand = (...args: string[]) => tscModule.getTscCommand()
- .parseAsync(args, { from: 'user' });
+ const runCommand = (...args: string[]) =>
+ tscModule.getTscCommand().parseAsync(args, { from: 'user' });
test('regular command function', async () => {
mockedTsc.mockResolvedValueOnce({
@@ -92,8 +86,7 @@ describe('test tsc command', () => {
await runCommand();
- expect(tscModule.runTsc)
- .toHaveBeenCalledTimes(1);
+ expect(tscModule.runTsc).toHaveBeenCalledTimes(1);
});
it('should only typecheck specified bundles and tabs', async () => {
@@ -107,16 +100,14 @@ describe('test tsc command', () => {
await runCommand('-b', 'test0', '-t', 'tab0');
- expect(tscModule.runTsc)
- .toHaveBeenCalledTimes(1);
+ expect(tscModule.runTsc).toHaveBeenCalledTimes(1);
const [tscCall] = mockedTsc.mock.calls[0];
- expect(tscCall)
- .toMatchObject({
- bundles: ['test0'],
- tabs: ['tab0'],
- srcDir: 'src'
- });
+ expect(tscCall).toMatchObject({
+ bundles: ['test0'],
+ tabs: ['tab0'],
+ srcDir: 'src'
+ });
});
it('should exit with code 1 if there are type check errors', async () => {
@@ -131,14 +122,11 @@ describe('test tsc command', () => {
try {
await runCommand();
} catch (error) {
- expect(error)
- .toEqual(new Error('process.exit called with 1'));
+ expect(error).toEqual(new Error('process.exit called with 1'));
}
- expect(tscModule.runTsc)
- .toHaveBeenCalledTimes(1);
+ expect(tscModule.runTsc).toHaveBeenCalledTimes(1);
- expect(process.exit)
- .toHaveBeenCalledWith(1);
+ expect(process.exit).toHaveBeenCalledWith(1);
});
});
diff --git a/scripts/src/build/prebuild/index.ts b/scripts/src/build/prebuild/index.ts
index f050b0b72..7001517fd 100644
--- a/scripts/src/build/prebuild/index.ts
+++ b/scripts/src/build/prebuild/index.ts
@@ -1,12 +1,16 @@
-import { type Severity, findSeverity, type BuildOptions } from '@src/build/utils';
+import {
+ findSeverity,
+ type BuildOptions,
+ type Severity
+} from '@src/build/utils';
import { promiseAll } from '@src/commandUtils';
import { eslintResultsLogger, runEslint } from './lint';
import { runTsc, tscResultsLogger } from './tsc';
interface PrebuildResult {
- lint?: Awaited>
- tsc?: Awaited>
- severity: Severity
+ lint?: Awaited>;
+ tsc?: Awaited>;
+ severity: Severity;
}
export default async function prebuild(
@@ -34,7 +38,10 @@ export default async function prebuild(
runEslint(combinedOpts)
);
- const overallSev = findSeverity([tscResult, lintResult], ({ result: { severity } }) => severity);
+ const overallSev = findSeverity(
+ [tscResult, lintResult],
+ ({ result: { severity } }) => severity
+ );
return {
tsc: tscResult,
diff --git a/scripts/src/build/prebuild/lint.ts b/scripts/src/build/prebuild/lint.ts
index adcdd5f2d..519c9e341 100644
--- a/scripts/src/build/prebuild/lint.ts
+++ b/scripts/src/build/prebuild/lint.ts
@@ -7,66 +7,92 @@ import chalk from 'chalk';
*/
// @ts-expect-error 2305
import { loadESLint, type ESLint } from 'eslint';
-import { lintFixOption, retrieveBundlesAndTabs, wrapWithTimer } from '@src/commandUtils';
-import { findSeverity, divideAndRound, type Severity, type AwaitedReturn } from '../utils';
-import { createPrebuildCommand, createPrebuildCommandHandler, type PrebuildOptions } from './utils';
+import {
+ lintFixOption,
+ retrieveBundlesAndTabs,
+ wrapWithTimer
+} from '@src/commandUtils';
+import {
+ divideAndRound,
+ findSeverity,
+ type AwaitedReturn,
+ type Severity
+} from '../utils';
+import {
+ createPrebuildCommand,
+ createPrebuildCommandHandler,
+ type PrebuildOptions
+} from './utils';
-const severityFinder = (results: ESLint.LintResult[]) => findSeverity(results, ({ warningCount, fatalErrorCount }) => {
- if (fatalErrorCount > 0) return 'error';
- if (warningCount > 0) return 'warn';
- return 'success';
-});
+const severityFinder = (results: ESLint.LintResult[]) =>
+ findSeverity(results, ({ warningCount, fatalErrorCount }) => {
+ if (fatalErrorCount > 0) return 'error';
+ if (warningCount > 0) return 'warn';
+ return 'success';
+ });
interface LintResults {
- formatted: string
- severity: Severity
+ formatted: string;
+ severity: Severity;
}
interface LintOptions extends PrebuildOptions {
- fix?: boolean
+ fix?: boolean;
}
-export const runEslint = wrapWithTimer(async ({ bundles, tabs, srcDir, fix }: LintOptions): Promise => {
- const ESlint = await loadESLint({ useFlatConfig: true });
- const linter = new ESlint({ fix });
+export const runEslint = wrapWithTimer(
+ async ({ bundles, tabs, srcDir, fix }: LintOptions): Promise => {
+ const ESlint = await loadESLint({ useFlatConfig: true });
+ const linter = new ESlint({ fix });
- const fileNames = [
- ...bundles.map(bundleName => `${srcDir}/bundles/${bundleName}/**/*.ts`),
- ...tabs.map(tabName => `${srcDir}/tabs/${tabName}/**/*.ts*`)
- ];
+ const fileNames = [
+ ...bundles.map(bundleName => `${srcDir}/bundles/${bundleName}/**/*.ts`),
+ ...tabs.map(tabName => `${srcDir}/tabs/${tabName}/**/*.ts*`)
+ ];
- try {
- const linterResults = await linter.lintFiles(fileNames);
- if (fix) {
- await ESlint.outputFixes(linterResults);
- }
+ try {
+ const linterResults = await linter.lintFiles(fileNames);
+ if (fix) {
+ await ESlint.outputFixes(linterResults);
+ }
- const outputFormatter = await linter.loadFormatter('stylish');
- const formatted = await outputFormatter.format(linterResults);
- const severity = severityFinder(linterResults);
- return {
- formatted,
- severity
- };
- } catch (error) {
- return {
- severity: 'error',
- formatted: error.toString()
- };
+ const outputFormatter = await linter.loadFormatter('stylish');
+ const formatted = await outputFormatter.format(linterResults);
+ const severity = severityFinder(linterResults);
+ return {
+ formatted,
+ severity
+ };
+ } catch (error) {
+ return {
+ severity: 'error',
+ formatted: error.toString()
+ };
+ }
}
-});
+);
-export function eslintResultsLogger({ elapsed, result: { formatted, severity } }: AwaitedReturn) {
+export function eslintResultsLogger({
+ elapsed,
+ result: { formatted, severity }
+}: AwaitedReturn) {
let errStr: string;
- if (severity === 'error') errStr = chalk.cyanBright('with ') + chalk.redBright('errors');
- else if (severity === 'warn') errStr = chalk.cyanBright('with ') + chalk.yellowBright('warnings');
+ if (severity === 'error')
+ errStr = chalk.cyanBright('with ') + chalk.redBright('errors');
+ else if (severity === 'warn')
+ errStr = chalk.cyanBright('with ') + chalk.yellowBright('warnings');
else errStr = chalk.greenBright('successfully');
- return `${chalk.cyanBright(`Linting completed in ${divideAndRound(elapsed, 1000)}s ${errStr}:`)}\n${formatted}`;
+ return `${chalk.cyanBright(
+ `Linting completed in ${divideAndRound(elapsed, 1000)}s ${errStr}:`
+ )}\n${formatted}`;
}
-const lintCommandHandler = createPrebuildCommandHandler((...args) => runEslint(...args), eslintResultsLogger);
+const lintCommandHandler = createPrebuildCommandHandler(
+ (...args) => runEslint(...args),
+ eslintResultsLogger
+);
export function getLintCommand() {
return createPrebuildCommand('lint', 'Run eslint')
diff --git a/scripts/src/build/prebuild/tsc.ts b/scripts/src/build/prebuild/tsc.ts
index 24b24ced0..6b6f47109 100644
--- a/scripts/src/build/prebuild/tsc.ts
+++ b/scripts/src/build/prebuild/tsc.ts
@@ -3,26 +3,39 @@ import pathlib from 'path';
import chalk from 'chalk';
import ts from 'typescript';
import { retrieveBundlesAndTabs, wrapWithTimer } from '@src/commandUtils';
-import { expandBundleNames, expandTabNames, divideAndRound, type AwaitedReturn } from '../utils';
-import { createPrebuildCommand, createPrebuildCommandHandler, type PrebuildOptions } from './utils';
-
-type TsconfigResult = {
- severity: 'error',
- results?: ts.Diagnostic[]
- error?: any
-} | {
- severity: 'success',
- results: ts.CompilerOptions
-};
-
-type TscResult = {
- severity: 'error'
- results?: ts.Diagnostic[]
- error?: any
-} | {
- severity: 'success',
- results: ts.Diagnostic[]
-};
+import {
+ divideAndRound,
+ expandBundleNames,
+ expandTabNames,
+ type AwaitedReturn
+} from '../utils';
+import {
+ createPrebuildCommand,
+ createPrebuildCommandHandler,
+ type PrebuildOptions
+} from './utils';
+
+type TsconfigResult =
+ | {
+ severity: 'error';
+ results?: ts.Diagnostic[];
+ error?: any;
+ }
+ | {
+ severity: 'success';
+ results: ts.CompilerOptions;
+ };
+
+type TscResult =
+ | {
+ severity: 'error';
+ results?: ts.Diagnostic[];
+ error?: any;
+ }
+ | {
+ severity: 'success';
+ results: ts.Diagnostic[];
+ };
async function getTsconfig(srcDir: string): Promise {
// Step 1: Read the text from tsconfig.json
@@ -31,7 +44,8 @@ async function getTsconfig(srcDir: string): Promise {
const configText = await fs.readFile(tsconfigLocation, 'utf-8');
// Step 2: Parse the raw text into a json object
- const { error: configJsonError, config: configJson } = ts.parseConfigFileTextToJson(tsconfigLocation, configText);
+ const { error: configJsonError, config: configJson } =
+ ts.parseConfigFileTextToJson(tsconfigLocation, configText);
if (configJsonError) {
return {
severity: 'error',
@@ -40,7 +54,8 @@ async function getTsconfig(srcDir: string): Promise {
}
// Step 3: Parse the json object into a config object for use by tsc
- const { errors: parseErrors, options: tsconfig } = ts.parseJsonConfigFileContent(configJson, ts.sys, srcDir);
+ const { errors: parseErrors, options: tsconfig } =
+ ts.parseJsonConfigFileContent(configJson, ts.sys, srcDir);
if (parseErrors.length > 0) {
return {
severity: 'error',
@@ -60,45 +75,56 @@ async function getTsconfig(srcDir: string): Promise {
}
}
-export const runTsc = wrapWithTimer(async ({ bundles, tabs, srcDir }: PrebuildOptions): Promise => {
- const tsconfigRes = await getTsconfig(srcDir);
- if (tsconfigRes.severity === 'error') {
- return tsconfigRes;
- }
+export const runTsc = wrapWithTimer(
+ async ({ bundles, tabs, srcDir }: PrebuildOptions): Promise => {
+ const tsconfigRes = await getTsconfig(srcDir);
+ if (tsconfigRes.severity === 'error') {
+ return tsconfigRes;
+ }
- const fileNames: string[] = [];
+ const fileNames: string[] = [];
- if (bundles.length > 0) {
- expandBundleNames(srcDir, bundles)
- .forEach(name => fileNames.push(name));
- }
+ if (bundles.length > 0) {
+ expandBundleNames(srcDir, bundles).forEach(name =>
+ fileNames.push(name)
+ );
+ }
- if (tabs.length > 0) {
- expandTabNames(srcDir, tabs)
- .forEach(name => fileNames.push(name));
- }
+ if (tabs.length > 0) {
+ expandTabNames(srcDir, tabs).forEach(name => fileNames.push(name));
+ }
- try {
- const tsc = ts.createProgram(fileNames, tsconfigRes.results);
- const results = tsc.emit();
- const diagnostics = ts.getPreEmitDiagnostics(tsc)
- .concat(results.diagnostics);
+ try {
+ const tsc = ts.createProgram(fileNames, tsconfigRes.results);
+ const results = tsc.emit();
+ const diagnostics = ts
+ .getPreEmitDiagnostics(tsc)
+ .concat(results.diagnostics);
- return {
- severity: diagnostics.length > 0 ? 'error' : 'success',
- results: diagnostics
- };
- } catch (error) {
- return {
- severity: 'error',
- error
- };
+ return {
+ severity: diagnostics.length > 0 ? 'error' : 'success',
+ results: diagnostics
+ };
+ } catch (error) {
+ return {
+ severity: 'error',
+ error
+ };
+ }
}
-});
+);
-export function tscResultsLogger({ elapsed, result: tscResult }: AwaitedReturn) {
+export function tscResultsLogger({
+ elapsed,
+ result: tscResult
+}: AwaitedReturn) {
if (tscResult.severity === 'error' && tscResult.error) {
- return `${chalk.cyanBright(`tsc finished with ${chalk.redBright('errors')} in ${divideAndRound(elapsed, 1000)}s: ${tscResult.error}`)}`;
+ return `${chalk.cyanBright(
+ `tsc finished with ${chalk.redBright('errors')} in ${divideAndRound(
+ elapsed,
+ 1000
+ )}s: ${tscResult.error}`
+ )}`;
}
const diagStr = ts.formatDiagnosticsWithColorAndContext(tscResult.results, {
@@ -108,9 +134,19 @@ export function tscResultsLogger({ elapsed, result: tscResult }: AwaitedReturn createPrebuildCommand('tsc', 'Run the typescript compiler to perform type checking')
- .action(async opts => {
+export const getTscCommand = () =>
+ createPrebuildCommand(
+ 'tsc',
+ 'Run the typescript compiler to perform type checking'
+ ).action(async opts => {
const inputs = await retrieveBundlesAndTabs(opts, false);
await tscCommandHandler({ ...opts, ...inputs });
});
diff --git a/scripts/src/build/prebuild/utils.ts b/scripts/src/build/prebuild/utils.ts
index c80369b9e..549b3d10a 100644
--- a/scripts/src/build/prebuild/utils.ts
+++ b/scripts/src/build/prebuild/utils.ts
@@ -1,15 +1,22 @@
import { Command } from '@commander-js/extra-typings';
-import { bundlesOption, manifestOption, srcDirOption, tabsOption, type TimedResult } from '@src/commandUtils';
+import {
+ bundlesOption,
+ manifestOption,
+ srcDirOption,
+ tabsOption,
+ type TimedResult
+} from '@src/commandUtils';
import { logInputs, type Severity } from '../utils';
export interface PrebuildOptions {
- srcDir: string
- manifest: string
- bundles: string[]
- tabs: string[]
+ srcDir: string;
+ manifest: string;
+ bundles: string[];
+ tabs: string[];
}
-export interface PrebuildResult extends TimedResult {}
+export interface PrebuildResult
+ extends TimedResult {}
export function createPrebuildCommand(
commandName: string,
diff --git a/scripts/src/build/utils.ts b/scripts/src/build/utils.ts
index d62ae2827..251383aa1 100644
--- a/scripts/src/build/utils.ts
+++ b/scripts/src/build/utils.ts
@@ -2,50 +2,63 @@ import { copyFile } from 'fs/promises';
import { Command } from '@commander-js/extra-typings';
import chalk from 'chalk';
import { Table } from 'console-table-printer';
-import { lintFixOption, lintOption, manifestOption, objectEntries, outDirOption, retrieveBundlesAndTabs, srcDirOption } from '@src/commandUtils';
+import {
+ lintFixOption,
+ lintOption,
+ manifestOption,
+ objectEntries,
+ outDirOption,
+ retrieveBundlesAndTabs,
+ srcDirOption
+} from '@src/commandUtils';
import { htmlLogger, type buildHtml } from './docs/html';
import prebuild, { formatPrebuildResults } from './prebuild';
export interface BuildInputs {
- bundles?: string[] | null
- tabs?: string[] | null
- modulesSpecified?: boolean
+ bundles?: string[] | null;
+ tabs?: string[] | null;
+ modulesSpecified?: boolean;
}
export interface BuildOptions {
- srcDir: string
- outDir: string
- manifest: string
- lint?: boolean
- fix?: boolean
- tsc?: boolean
- verbose?: boolean
+ srcDir: string;
+ outDir: string;
+ manifest: string;
+ lint?: boolean;
+ fix?: boolean;
+ tsc?: boolean;
+ verbose?: boolean;
}
export interface SuccessResult {
- name: string
- severity: 'success',
+ name: string;
+ severity: 'success';
}
export interface WarnResult {
- name: string,
- severity: 'warn',
- error: any
+ name: string;
+ severity: 'warn';
+ error: any;
}
export interface ErrorResult {
- name: string,
- severity: 'error',
- error: any
+ name: string;
+ severity: 'error';
+ error: any;
}
export type OperationResult = ErrorResult | SuccessResult | WarnResult;
export type Severity = OperationResult['severity'];
-export const isSuccessResult = (obj: OperationResult): obj is SuccessResult => obj.severity === 'success';
-export const isWarnResult = (obj: OperationResult): obj is WarnResult => obj.severity === 'warn';
+export const isSuccessResult = (obj: OperationResult): obj is SuccessResult =>
+ obj.severity === 'success';
+export const isWarnResult = (obj: OperationResult): obj is WarnResult =>
+ obj.severity === 'warn';
-export function findSeverity(results: T[], mapper?: (item: T) => Severity): Severity {
+export function findSeverity(
+ results: T[],
+ mapper?: (item: T) => Severity
+): Severity {
let overallSev: Severity = 'success';
for (const result of results) {
@@ -53,7 +66,10 @@ export function findSeverity(results: T[], mapper?: (item: T)
if ('severity' in result) {
severity = result.severity as Severity;
} else {
- if (!mapper) throw new Error(`Mapping function required to convert ${result} to severity`);
+ if (!mapper)
+ throw new Error(
+ `Mapping function required to convert ${result} to severity`
+ );
severity = mapper(result);
}
@@ -66,26 +82,38 @@ export function findSeverity(results: T[], mapper?: (item: T)
return overallSev;
}
-export const expandBundleNames = (srcDir: string, bundles: string[]) => bundles.map(bundle => `${srcDir}/bundles/${bundle}/index.ts`);
-export const expandTabNames = (srcDir: string, tabNames: string[]) => tabNames.map(tabName => `${srcDir}/tabs/${tabName}/index.tsx`);
+export const expandBundleNames = (srcDir: string, bundles: string[]) =>
+ bundles.map(bundle => `${srcDir}/bundles/${bundle}/index.ts`);
+export const expandTabNames = (srcDir: string, tabNames: string[]) =>
+ tabNames.map(tabName => `${srcDir}/tabs/${tabName}/index.tsx`);
-export type AwaitedReturn = T extends (...args: any) => Promise ? U : never;
+export type AwaitedReturn = T extends (...args: any) => Promise
+ ? U
+ : never;
-export const divideAndRound = (n: number, divisor: number) => (n / divisor).toFixed(2);
+export const divideAndRound = (n: number, divisor: number) =>
+ (n / divisor).toFixed(2);
type AssetType = 'bundles' | 'jsons' | 'tabs';
-type LogType = Partial & { html: Awaited> }>;
+type LogType = Partial<
+ Record & {
+ html: Awaited>;
+ }
+>;
-export type BuildTask = (inputs: BuildInputs, opts: BuildOptions) => Promise;
+export type BuildTask = (
+ inputs: BuildInputs,
+ opts: BuildOptions
+) => Promise;
-function processResults(
- results: LogType,
- verbose: boolean
-) {
- const notSuccessFilter = (result: OperationResult): result is Exclude => result.severity !== 'success';
+function processResults(results: LogType, verbose: boolean) {
+ const notSuccessFilter = (
+ result: OperationResult
+ ): result is Exclude =>
+ result.severity !== 'success';
- const logs = objectEntries(results)
- .map(([label, results]): [Severity, string] => {
+ const logs = objectEntries(results).map(
+ ([label, results]): [Severity, string] => {
if (label === 'html') {
return [results.result.severity, htmlLogger(results)];
}
@@ -94,68 +122,117 @@ function processResults(
const upperCaseLabel = label[0].toUpperCase() + label.slice(1);
if (!verbose) {
if (overallSev === 'success') {
- return ['success', `${chalk.cyanBright(`${upperCaseLabel} built`)} ${chalk.greenBright('successfully')}\n`];
+ return [
+ 'success',
+ `${chalk.cyanBright(`${upperCaseLabel} built`)} ${chalk.greenBright(
+ 'successfully'
+ )}\n`
+ ];
}
if (overallSev === 'warn') {
- return ['warn', chalk.cyanBright(`${upperCaseLabel} built with ${chalk.yellowBright('warnings')}:\n${results
- .filter(isWarnResult)
- .map(({ name: bundle, error }, i) => chalk.yellowBright(`${i + 1}. ${bundle}: ${error}`))
- .join('\n')}\n`)];
+ return [
+ 'warn',
+ chalk.cyanBright(
+ `${upperCaseLabel} built with ${chalk.yellowBright(
+ 'warnings'
+ )}:\n${results
+ .filter(isWarnResult)
+ .map(({ name: bundle, error }, i) =>
+ chalk.yellowBright(`${i + 1}. ${bundle}: ${error}`)
+ )
+ .join('\n')}\n`
+ )
+ ];
}
- return ['error', chalk.cyanBright(`${upperCaseLabel} build ${chalk.redBright('failed')} with errors:\n${results
- .filter(notSuccessFilter)
- .map(({ name: bundle, error, severity }, i) => (severity === 'error'
- ? chalk.redBright(`${i + 1}. Error ${bundle}: ${error}`)
- : chalk.yellowBright(`${i + 1}. Warning ${bundle}: ${error}`)))
- .join('\n')}\n`)];
+ return [
+ 'error',
+ chalk.cyanBright(
+ `${upperCaseLabel} build ${chalk.redBright(
+ 'failed'
+ )} with errors:\n${results
+ .filter(notSuccessFilter)
+ .map(({ name: bundle, error, severity }, i) =>
+ severity === 'error'
+ ? chalk.redBright(`${i + 1}. Error ${bundle}: ${error}`)
+ : chalk.yellowBright(`${i + 1}. Warning ${bundle}: ${error}`)
+ )
+ .join('\n')}\n`
+ )
+ ];
}
const outputTable = new Table({
- columns: [{
- name: 'name',
- title: upperCaseLabel
- },
- {
- name: 'severity',
- title: 'Status'
- },
- {
- name: 'error',
- title: 'Errors'
- }]
+ columns: [
+ {
+ name: 'name',
+ title: upperCaseLabel
+ },
+ {
+ name: 'severity',
+ title: 'Status'
+ },
+ {
+ name: 'error',
+ title: 'Errors'
+ }
+ ]
});
results.forEach(result => {
if (isWarnResult(result)) {
- outputTable.addRow({
- ...result,
- severity: 'Warning'
- }, { color: 'yellow' });
+ outputTable.addRow(
+ {
+ ...result,
+ severity: 'Warning'
+ },
+ { color: 'yellow' }
+ );
} else if (isSuccessResult(result)) {
- outputTable.addRow({
- ...result,
- error: '-',
- severity: 'Success'
- }, { color: 'green' });
+ outputTable.addRow(
+ {
+ ...result,
+ error: '-',
+ severity: 'Success'
+ },
+ { color: 'green' }
+ );
} else {
- outputTable.addRow({
- ...result,
- severity: 'Error'
- }, { color: 'red' });
+ outputTable.addRow(
+ {
+ ...result,
+ severity: 'Error'
+ },
+ { color: 'red' }
+ );
}
});
if (overallSev === 'success') {
- return ['success', `${chalk.cyanBright(`${upperCaseLabel} built`)} ${chalk.greenBright('successfully')}:\n${outputTable.render()}\n`];
+ return [
+ 'success',
+ `${chalk.cyanBright(`${upperCaseLabel} built`)} ${chalk.greenBright(
+ 'successfully'
+ )}:\n${outputTable.render()}\n`
+ ];
}
if (overallSev === 'warn') {
- return ['warn', `${chalk.cyanBright(`${upperCaseLabel} built`)} with ${chalk.yellowBright('warnings')}:\n${outputTable.render()}\n`];
+ return [
+ 'warn',
+ `${chalk.cyanBright(
+ `${upperCaseLabel} built`
+ )} with ${chalk.yellowBright('warnings')}:\n${outputTable.render()}\n`
+ ];
}
- return ['error', `${chalk.cyanBright(`${upperCaseLabel} build ${chalk.redBright('failed')} with errors`)}:\n${outputTable.render()}\n`];
- });
+ return [
+ 'error',
+ `${chalk.cyanBright(
+ `${upperCaseLabel} build ${chalk.redBright('failed')} with errors`
+ )}:\n${outputTable.render()}\n`
+ ];
+ }
+ );
- console.log(logs.map(x => x[1])
- .join('\n'));
+ console.log(logs.map(x => x[1]).join('\n'));
const overallOverallSev = findSeverity(logs, ([sev]) => sev);
if (overallOverallSev === 'error') {
@@ -163,10 +240,15 @@ function processResults(
}
}
-export function logInputs({ bundles, tabs }: BuildInputs, { tsc, lint }: Partial>) {
+export function logInputs(
+ { bundles, tabs }: BuildInputs,
+ { tsc, lint }: Partial>
+) {
const output: string[] = [];
if (tsc) {
- output.push(chalk.yellowBright('--tsc specified, will run typescript checker'));
+ output.push(
+ chalk.yellowBright('--tsc specified, will run typescript checker')
+ );
}
if (lint) {
@@ -191,7 +273,7 @@ export function createBuildCommandHandler(
shouldAddModuleTabs: boolean
) {
return async (
- opts: BuildOptions & { bundles: string[] | null, tabs: string[] | null }
+ opts: BuildOptions & { bundles: string[] | null; tabs: string[] | null }
) => {
const inputs = await retrieveBundlesAndTabs(opts, shouldAddModuleTabs);
@@ -211,10 +293,7 @@ export function createBuildCommandHandler(
};
}
-export function createBuildCommand(
- commandName: string,
- description: string
-) {
+export function createBuildCommand(commandName: string, description: string) {
return new Command(commandName)
.description(description)
.addOption(srcDirOption)
diff --git a/scripts/src/commandUtils.ts b/scripts/src/commandUtils.ts
index a24eb8118..487f16dc1 100644
--- a/scripts/src/commandUtils.ts
+++ b/scripts/src/commandUtils.ts
@@ -9,47 +9,65 @@ class OptionNew<
CoerceT = undefined,
Mandatory extends boolean = false,
ChoicesT = undefined
->
- extends Option {
- default(value: T, description?: string): Option {
+> extends Option {
+ default(
+ value: T,
+ description?: string
+ ): Option {
return super.default(value, description);
}
}
-export const srcDirOption = new OptionNew('--srcDir ', 'Location of the source files')
- .default('src');
+export const srcDirOption = new OptionNew(
+ '--srcDir ',
+ 'Location of the source files'
+).default('src');
-export const outDirOption = new OptionNew('--outDir ', 'Location of output directory')
- .default('build');
+export const outDirOption = new OptionNew(
+ '--outDir ',
+ 'Location of output directory'
+).default('build');
-export const manifestOption = new OptionNew('--manifest ', 'Location of manifest')
- .default('modules.json');
+export const manifestOption = new OptionNew(
+ '--manifest ',
+ 'Location of manifest'
+).default('modules.json');
export const lintOption = new OptionNew('--lint', 'Run ESLint');
-export const lintFixOption = new OptionNew('--fix', 'Fix automatically fixable linting errors')
- .implies({ lint: true });
+export const lintFixOption = new OptionNew(
+ '--fix',
+ 'Fix automatically fixable linting errors'
+).implies({ lint: true });
-export const bundlesOption = new OptionNew('-b, --bundles ', 'Manually specify which bundles')
- .default(null);
+export const bundlesOption = new OptionNew(
+ '-b, --bundles ',
+ 'Manually specify which bundles'
+).default(null);
-export const tabsOption = new OptionNew('-t, --tabs ', 'Manually specify which tabs')
- .default(null);
+export const tabsOption = new OptionNew(
+ '-t, --tabs ',
+ 'Manually specify which tabs'
+).default(null);
export async function retrieveBundlesAndTabs(
- { bundles, tabs, manifest: manifestFile }: {
- bundles?: string[] | null,
- tabs?: string[] | null,
- manifest: string
- }, shouldAddModuleTabs: boolean
+ {
+ bundles,
+ tabs,
+ manifest: manifestFile
+ }: {
+ bundles?: string[] | null;
+ tabs?: string[] | null;
+ manifest: string;
+ },
+ shouldAddModuleTabs: boolean
) {
const manifest = await retrieveManifest(manifestFile);
const knownBundles = Object.keys(manifest);
- const knownTabs = Object
- .values(manifest)
- .flatMap(x => x.tabs);
+ const knownTabs = Object.values(manifest).flatMap(x => x.tabs);
- const isUndefinedOrNull = (x: any): x is null | undefined => x === undefined || x === null;
+ const isUndefinedOrNull = (x: any): x is null | undefined =>
+ x === undefined || x === null;
let bundlesOutput: string[];
let tabsOutput: string[];
@@ -58,7 +76,9 @@ export async function retrieveBundlesAndTabs(
// User did not specify any bundles, select all
bundlesOutput = knownBundles;
} else {
- const unknownBundles = bundles.filter(bundleName => !knownBundles.includes(bundleName));
+ const unknownBundles = bundles.filter(
+ bundleName => !knownBundles.includes(bundleName)
+ );
if (unknownBundles.length > 0) {
throw new Error(`Unknown bundles: ${unknownBundles.join(', ')}`);
}
@@ -95,17 +115,23 @@ export async function retrieveBundlesAndTabs(
};
}
-export function promiseAll[]>(...args: T): Promise<{ [K in keyof T]: Awaited }> {
+export function promiseAll[]>(
+ ...args: T
+): Promise<{ [K in keyof T]: Awaited }> {
return Promise.all(args);
}
export interface TimedResult {
- result: T
- elapsed: number
+ result: T;
+ elapsed: number;
}
-export function wrapWithTimer Promise>(func: T) {
- return async (...args: Parameters): Promise>> => {
+export function wrapWithTimer Promise>(
+ func: T
+) {
+ return async (
+ ...args: Parameters
+ ): Promise>> => {
const startTime = performance.now();
const result = await func(...args);
return {
@@ -118,7 +144,7 @@ export function wrapWithTimer Promise>(func: T
type ValuesOfRecord = T extends Record ? U : never;
export type EntriesOfRecord> = ValuesOfRecord<{
- [K in keyof T]: [K, T[K]]
+ [K in keyof T]: [K, T[K]];
}>;
export function objectEntries>(obj: T) {
diff --git a/scripts/src/manifest.ts b/scripts/src/manifest.ts
index 53b38a02c..e8f798dc0 100644
--- a/scripts/src/manifest.ts
+++ b/scripts/src/manifest.ts
@@ -1,13 +1,14 @@
import fs from 'fs/promises';
-export type ModuleManifest = Record;
+export type ModuleManifest = Record;
export async function retrieveManifest(manifest: string) {
try {
const rawManifest = await fs.readFile(manifest, 'utf-8');
return JSON.parse(rawManifest) as ModuleManifest;
} catch (error) {
- if (error.code === 'ENOENT') throw new Error(`Could not locate manifest file at ${manifest}`);
+ if (error.code === 'ENOENT')
+ throw new Error(`Could not locate manifest file at ${manifest}`);
throw error;
}
}
diff --git a/scripts/src/templates/__tests__/create.test.ts b/scripts/src/templates/__tests__/create.test.ts
index a0ea05cbc..dc7c7457f 100644
--- a/scripts/src/templates/__tests__/create.test.ts
+++ b/scripts/src/templates/__tests__/create.test.ts
@@ -21,33 +21,31 @@ jest.mock('../print', () => ({
}
}));
-const asMock = any>(func: T) => func as MockedFunction;
+const asMock = any>(func: T) =>
+ func as MockedFunction;
const mockedAskQuestion = asMock(askQuestion);
function runCommand(...args: string[]) {
- return getCreateCommand()
- .parseAsync(args, { from: 'user' });
+ return getCreateCommand().parseAsync(args, { from: 'user' });
}
-function expectCall any>(
+function expectCall any>(
func: T,
- ...expected: Parameters[]) {
+ ...expected: Parameters[]
+) {
const mocked = asMock(func);
- expect(func)
- .toHaveBeenCalledTimes(expected.length);
+ expect(func).toHaveBeenCalledTimes(expected.length);
mocked.mock.calls.forEach((actual, i) => {
- expect(actual)
- .toEqual(expected[i]);
+ expect(actual).toEqual(expected[i]);
});
}
async function expectCommandFailure(snapshot: string) {
await expect(runCommand())
- .rejects
- // eslint-disable-next-line jest/no-interpolation-in-snapshots
+ .rejects // eslint-disable-next-line jest/no-interpolation-in-snapshots
.toMatchInlineSnapshot(`[Error: ERROR: ${snapshot}]`);
expect(fs.writeFile).not.toHaveBeenCalled();
@@ -62,7 +60,9 @@ describe('Test adding new module', () => {
it('should require camel case for module names', async () => {
mockedAskQuestion.mockResolvedValueOnce('pascalCase');
- await expectCommandFailure('Module names must be in snake case. (eg. binary_tree)');
+ await expectCommandFailure(
+ 'Module names must be in snake case. (eg. binary_tree)'
+ );
});
it('should check for existing modules', async () => {
@@ -74,29 +74,21 @@ describe('Test adding new module', () => {
mockedAskQuestion.mockResolvedValueOnce('new_module');
await runCommand();
- expectCall(
- fs.mkdir,
- ['src/bundles/new_module', { recursive: true }]
- );
+ expectCall(fs.mkdir, ['src/bundles/new_module', { recursive: true }]);
- expectCall(
- fs.copyFile,
- [
- './scripts/src/templates/templates/__bundle__.ts',
- 'src/bundles/new_module/index.ts'
- ]
- );
+ expectCall(fs.copyFile, [
+ './scripts/src/templates/templates/__bundle__.ts',
+ 'src/bundles/new_module/index.ts'
+ ]);
const oldManifest = await retrieveManifest('modules.json');
const [[manifestPath, newManifest]] = asMock(fs.writeFile).mock.calls;
- expect(manifestPath)
- .toEqual('modules.json');
-
- expect(JSON.parse(newManifest as string))
- .toMatchObject({
- ...oldManifest,
- new_module: { tabs: [] }
- });
+ expect(manifestPath).toEqual('modules.json');
+
+ expect(JSON.parse(newManifest as string)).toMatchObject({
+ ...oldManifest,
+ new_module: { tabs: [] }
+ });
});
});
@@ -108,7 +100,9 @@ describe('Test adding new tab', () => {
it('should require pascal case for tab names', async () => {
mockedAskQuestion.mockResolvedValueOnce('test0');
mockedAskQuestion.mockResolvedValueOnce('unknown_tab');
- await expectCommandFailure('Tab names must be in pascal case. (eg. BinaryTree)');
+ await expectCommandFailure(
+ 'Tab names must be in pascal case. (eg. BinaryTree)'
+ );
});
it('should check if the given tab already exists', async () => {
@@ -128,30 +122,22 @@ describe('Test adding new tab', () => {
await runCommand();
- expectCall(
- fs.mkdir,
- ['src/tabs/TabNew', { recursive: true }]
- );
+ expectCall(fs.mkdir, ['src/tabs/TabNew', { recursive: true }]);
- expectCall(
- fs.copyFile,
- [
- './scripts/src/templates/templates/__tab__.tsx',
- 'src/tabs/TabNew/index.tsx'
- ]
- );
+ expectCall(fs.copyFile, [
+ './scripts/src/templates/templates/__tab__.tsx',
+ 'src/tabs/TabNew/index.tsx'
+ ]);
const oldManifest = await retrieveManifest('modules.json');
const [[manifestPath, newManifest]] = asMock(fs.writeFile).mock.calls;
- expect(manifestPath)
- .toEqual('modules.json');
-
- expect(JSON.parse(newManifest as string))
- .toMatchObject({
- ...oldManifest,
- test0: {
- tabs: ['tab0', 'TabNew']
- }
- });
+ expect(manifestPath).toEqual('modules.json');
+
+ expect(JSON.parse(newManifest as string)).toMatchObject({
+ ...oldManifest,
+ test0: {
+ tabs: ['tab0', 'TabNew']
+ }
+ });
});
});
diff --git a/scripts/src/templates/__tests__/names.test.ts b/scripts/src/templates/__tests__/names.test.ts
index eaf0b6ce6..f4a90b8cf 100644
--- a/scripts/src/templates/__tests__/names.test.ts
+++ b/scripts/src/templates/__tests__/names.test.ts
@@ -4,8 +4,10 @@ function testFunction(
func: (value: string) => boolean,
tcs: [string, boolean][]
) {
- describe(`Testing ${func.name}`, () => test.each(tcs)('%#: %s', (value, valid) => expect(func(value))
- .toEqual(valid)));
+ describe(`Testing ${func.name}`, () =>
+ test.each(tcs)('%#: %s', (value, valid) =>
+ expect(func(value)).toEqual(valid)
+ ));
}
testFunction(isPascalCase, [
diff --git a/scripts/src/templates/index.ts b/scripts/src/templates/index.ts
index 7db181a61..1659e2bae 100644
--- a/scripts/src/templates/index.ts
+++ b/scripts/src/templates/index.ts
@@ -9,7 +9,10 @@ import { addNew as addNewTab } from './tab';
async function askMode(rl: Interface) {
while (true) {
// eslint-disable-next-line no-await-in-loop
- const mode = await askQuestion('What would you like to create? (module/tab)', rl);
+ const mode = await askQuestion(
+ 'What would you like to create? (module/tab)',
+ rl
+ );
if (mode !== 'module' && mode !== 'tab') {
warn("Please answer with only 'module' or 'tab'.");
} else {
diff --git a/scripts/src/templates/module.ts b/scripts/src/templates/module.ts
index 815ef1939..94a1df2fb 100644
--- a/scripts/src/templates/module.ts
+++ b/scripts/src/templates/module.ts
@@ -1,18 +1,21 @@
import fs from 'fs/promises';
import type { Interface } from 'readline/promises';
-import { type ModuleManifest, retrieveManifest } from '@src/manifest';
+import { retrieveManifest, type ModuleManifest } from '@src/manifest';
import { askQuestion, success, warn } from './print';
-import { type Options, isSnakeCase } from './utilities';
+import { isSnakeCase, type Options } from './utilities';
-export const check = (manifest: ModuleManifest, name: string) => Object.keys(manifest)
- .includes(name);
+export const check = (manifest: ModuleManifest, name: string) =>
+ Object.keys(manifest).includes(name);
async function askModuleName(manifest: ModuleManifest, rl: Interface) {
while (true) {
// eslint-disable-next-line no-await-in-loop
- const name = await askQuestion('What is the name of your new module? (eg. binary_tree)', rl);
+ const name = await askQuestion(
+ 'What is the name of your new module? (eg. binary_tree)',
+ rl
+ );
if (isSnakeCase(name) === false) {
warn('Module names must be in snake case. (eg. binary_tree)');
} else if (check(manifest, name)) {
@@ -23,7 +26,10 @@ async function askModuleName(manifest: ModuleManifest, rl: Interface) {
}
}
-export async function addNew({ srcDir, manifest: manifestFile }: Options, rl: Interface) {
+export async function addNew(
+ { srcDir, manifest: manifestFile }: Options,
+ rl: Interface
+) {
const manifest = await retrieveManifest(manifestFile);
const moduleName = await askModuleName(manifest, rl);
@@ -35,10 +41,14 @@ export async function addNew({ srcDir, manifest: manifestFile }: Options, rl: In
);
await fs.writeFile(
manifestFile,
- JSON.stringify({
- ...manifest,
- [moduleName]: { tabs: [] }
- }, null, 2)
+ JSON.stringify(
+ {
+ ...manifest,
+ [moduleName]: { tabs: [] }
+ },
+ null,
+ 2
+ )
);
success(`Bundle for module ${moduleName} created at ${bundleDestination}.`);
}
diff --git a/scripts/src/templates/print.ts b/scripts/src/templates/print.ts
index f358a2fc6..e2f106b5b 100644
--- a/scripts/src/templates/print.ts
+++ b/scripts/src/templates/print.ts
@@ -1,10 +1,11 @@
-import { type Interface, createInterface } from 'readline/promises';
+import { createInterface, type Interface } from 'readline/promises';
import chalk from 'chalk';
-export const getRl = () => createInterface({
- input: process.stdin,
- output: process.stdout
-});
+export const getRl = () =>
+ createInterface({
+ input: process.stdin,
+ output: process.stdout
+ });
export function info(...args: any[]) {
return console.log(...args.map(string => chalk.grey(string)));
diff --git a/scripts/src/templates/tab.ts b/scripts/src/templates/tab.ts
index 4bd1737d4..a34e1fb4f 100644
--- a/scripts/src/templates/tab.ts
+++ b/scripts/src/templates/tab.ts
@@ -2,11 +2,11 @@
import fs from 'fs/promises';
import type { Interface } from 'readline/promises';
-import { type ModuleManifest, retrieveManifest } from '@src/manifest';
+import { retrieveManifest, type ModuleManifest } from '@src/manifest';
import { check as _check } from './module';
import { askQuestion, success, warn } from './print';
-import { type Options, isPascalCase } from './utilities';
+import { isPascalCase, type Options } from './utilities';
export function check(manifest: ModuleManifest, tabName: string) {
return Object.values(manifest)
@@ -28,7 +28,8 @@ async function askModuleName(manifest: ModuleManifest, rl: Interface) {
async function askTabName(manifest: ModuleManifest, rl: Interface) {
while (true) {
const name = await askQuestion(
- 'What is the name of your new tab? (eg. BinaryTree)', rl
+ 'What is the name of your new tab? (eg. BinaryTree)',
+ rl
);
if (check(manifest, name)) {
warn('A tab with the same name already exists.');
@@ -40,7 +41,10 @@ async function askTabName(manifest: ModuleManifest, rl: Interface) {
}
}
-export async function addNew({ manifest: manifestFile, srcDir }: Options, rl: Interface) {
+export async function addNew(
+ { manifest: manifestFile, srcDir }: Options,
+ rl: Interface
+) {
const manifest = await retrieveManifest(manifestFile);
const moduleName = await askModuleName(manifest, rl);
diff --git a/scripts/src/templates/templates/__bundle__.ts b/scripts/src/templates/templates/__bundle__.ts
index a3deb9ec0..cfd6f218f 100644
--- a/scripts/src/templates/templates/__bundle__.ts
+++ b/scripts/src/templates/templates/__bundle__.ts
@@ -12,7 +12,6 @@
To access things like the context or module state you can just import the context
using the import below
*/
-import context from 'js-slang/context';
/**
* Sample function. Increments a number by 1.
diff --git a/scripts/src/templates/templates/__tab__.tsx b/scripts/src/templates/templates/__tab__.tsx
index 34eb95b09..1eed1299b 100644
--- a/scripts/src/templates/templates/__tab__.tsx
+++ b/scripts/src/templates/templates/__tab__.tsx
@@ -29,7 +29,7 @@ class Repeat extends React.Component {
constructor(props) {
super(props);
this.state = {
- counter: 0,
+ counter: 0
};
}
@@ -67,5 +67,5 @@ export default {
* displayed in the side contents panel.
* @see https://blueprintjs.com/docs/#icons
*/
- iconName: 'build',
-};
\ No newline at end of file
+ iconName: 'build'
+};
diff --git a/scripts/src/testing/__tests__/runner.test.ts b/scripts/src/testing/__tests__/runner.test.ts
index e6d93c3cf..47f25beb6 100644
--- a/scripts/src/testing/__tests__/runner.test.ts
+++ b/scripts/src/testing/__tests__/runner.test.ts
@@ -2,27 +2,23 @@ import type { MockedFunction } from 'jest-mock';
import getTestCommand from '..';
import * as runner from '../runner';
-jest.spyOn(runner, 'runJest')
- .mockImplementation(jest.fn());
+jest.spyOn(runner, 'runJest').mockImplementation(jest.fn());
-const runCommand = (...args: string[]) => getTestCommand()
- .parseAsync(args, { from: 'user' });
+const runCommand = (...args: string[]) =>
+ getTestCommand().parseAsync(args, { from: 'user' });
const mockRunJest = runner.runJest as MockedFunction;
test('Check that the test command properly passes options to jest', async () => {
await runCommand('-u', '-w', '--srcDir', 'gg', './src/folder');
const [call] = mockRunJest.mock.calls;
- expect(call[0])
- .toEqual(['-u', '-w', './src/folder']);
- expect(call[1])
- .toEqual('gg');
+ expect(call[0]).toEqual(['-u', '-w', './src/folder']);
+ expect(call[1]).toEqual('gg');
});
test('Check that the test command handles windows paths as posix paths', async () => {
await runCommand('.\\src\\folder');
const [call] = mockRunJest.mock.calls;
- expect(call[0])
- .toEqual(['./src/folder']);
+ expect(call[0]).toEqual(['./src/folder']);
});
diff --git a/scripts/src/testing/index.ts b/scripts/src/testing/index.ts
index b6c606ee4..8592e9356 100644
--- a/scripts/src/testing/index.ts
+++ b/scripts/src/testing/index.ts
@@ -6,26 +6,32 @@ import { srcDirOption } from '@src/commandUtils';
import { runJest } from './runner';
export type TestCommandOptions = {
- srcDir: string
+ srcDir: string;
};
-const getTestCommand = () => new Command('test')
- .description('Run jest')
- .addOption(srcDirOption)
- .allowUnknownOption()
- .action(({ srcDir }, command) => {
- const [args, filePatterns] = lodash.partition(command.args, arg => arg.startsWith('-'));
+const getTestCommand = () =>
+ new Command('test')
+ .description('Run jest')
+ .addOption(srcDirOption)
+ .allowUnknownOption()
+ .action(({ srcDir }, command) => {
+ const [args, filePatterns] = lodash.partition(command.args, arg =>
+ arg.startsWith('-')
+ );
- // command.args automatically includes the source directory option
- // which is not supported by Jest, so we need to remove it
- const toRemove = args.findIndex(arg => arg.startsWith('--srcDir'));
- if (toRemove !== -1) {
- args.splice(toRemove, 1);
- }
+ // command.args automatically includes the source directory option
+ // which is not supported by Jest, so we need to remove it
+ const toRemove = args.findIndex(arg => arg.startsWith('--srcDir'));
+ if (toRemove !== -1) {
+ args.splice(toRemove, 1);
+ }
- const jestArgs = args.concat(filePatterns.map(pattern => pattern.split(pathlib.win32.sep)
- .join(pathlib.posix.sep)));
- return runJest(jestArgs, srcDir);
- });
+ const jestArgs = args.concat(
+ filePatterns.map(pattern =>
+ pattern.split(pathlib.win32.sep).join(pathlib.posix.sep)
+ )
+ );
+ return runJest(jestArgs, srcDir);
+ });
export default getTestCommand;
diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json
index 897b90573..71e5118ef 100644
--- a/scripts/tsconfig.json
+++ b/scripts/tsconfig.json
@@ -11,4 +11,4 @@
},
"include": ["./src", "jest.setup.ts"],
"exclude": ["./src/templates/templates/**"]
-}
\ No newline at end of file
+}
From 246ad1391dd6669a6433d6a2edcde5916198ef2d Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Tue, 26 Mar 2024 21:51:04 +0800
Subject: [PATCH 03/39] Reformat tabs with Prettier
---
src/tabs/ArcadeTwod/index.tsx | 8 +-
src/tabs/CopyGc/index.tsx | 126 +++++------
src/tabs/CopyGc/style.tsx | 2 +-
src/tabs/Csg/canvas_holder.tsx | 195 +++++++++--------
src/tabs/Csg/hover_control_hint.tsx | 43 ++--
src/tabs/Csg/index.tsx | 12 +-
src/tabs/Curve/__tests__/Curve.tsx | 30 ++-
src/tabs/Curve/animation_canvas_3d_curve.tsx | 208 +++++++++---------
src/tabs/Curve/canvas_3d_curve.tsx | 109 +++++-----
src/tabs/Curve/index.tsx | 49 +++--
src/tabs/Game/constants.ts | 2 +-
src/tabs/MarkSweep/index.tsx | 72 +++---
src/tabs/MarkSweep/style.tsx | 2 +-
src/tabs/Painter/index.tsx | 62 +++---
src/tabs/Pixnflix/index.tsx | 24 +-
src/tabs/Plotly/index.tsx | 62 +++---
src/tabs/Repl/index.tsx | 118 ++++++----
src/tabs/Rune/__tests__/Rune.tsx | 8 +-
src/tabs/Rune/index.tsx | 21 +-
src/tabs/Sound/index.tsx | 11 +-
src/tabs/SoundMatrix/index.tsx | 2 +-
src/tabs/StereoSound/index.tsx | 16 +-
src/tabs/UnityAcademy/index.tsx | 212 +++++++++++++-----
src/tabs/common/AnimationCanvas.tsx | 217 ++++++++++---------
src/tabs/common/AutoLoopSwitch.tsx | 26 ++-
src/tabs/common/ButtonComponent.tsx | 18 +-
src/tabs/common/ModalDiv.tsx | 22 +-
src/tabs/common/MultItemDisplay.tsx | 29 ++-
src/tabs/common/PlayButton.tsx | 26 ++-
src/tabs/common/WebglCanvas.tsx | 4 +-
src/tabs/common/testUtils.ts | 15 +-
src/tabs/physics_2d/DebugDrawCanvas.tsx | 40 ++--
src/tabs/physics_2d/index.tsx | 12 +-
33 files changed, 1018 insertions(+), 785 deletions(-)
diff --git a/src/tabs/ArcadeTwod/index.tsx b/src/tabs/ArcadeTwod/index.tsx
index b2e2e5103..24867c9e9 100644
--- a/src/tabs/ArcadeTwod/index.tsx
+++ b/src/tabs/ArcadeTwod/index.tsx
@@ -90,7 +90,11 @@ class GameTab extends React.Component {
componentDidMount() {
// Only mount the component when the Arcade2D tab is active
- if (document.querySelector('[id="bp4-tab-panel_side-content-tabs_Arcade2D Tab"]')?.ariaHidden === 'true') {
+ if (
+ document.querySelector(
+ '[id="bp4-tab-panel_side-content-tabs_Arcade2D Tab"]'
+ )?.ariaHidden === 'true'
+ ) {
return;
}
@@ -136,7 +140,7 @@ class GameTab extends React.Component {
}}
>
- this.toggleGamePause(p)} />
+ this.toggleGamePause(p)} />
);
}
diff --git a/src/tabs/CopyGc/index.tsx b/src/tabs/CopyGc/index.tsx
index 0ed587331..78bde832e 100644
--- a/src/tabs/CopyGc/index.tsx
+++ b/src/tabs/CopyGc/index.tsx
@@ -1,4 +1,4 @@
-import { Slider, Icon } from '@blueprintjs/core';
+import { Icon, Slider } from '@blueprintjs/core';
import React from 'react';
import { COMMAND } from '../../bundles/copy_gc/types';
import { ThemeColor } from './style';
@@ -57,9 +57,9 @@ class CopyGC extends React.Component {
componentDidMount() {
const { debuggerContext } = this.props;
if (
- debuggerContext
- && debuggerContext.result
- && debuggerContext.result.value
+ debuggerContext &&
+ debuggerContext.result &&
+ debuggerContext.result.value
) {
this.initialize_state();
}
@@ -187,12 +187,12 @@ class CopyGC extends React.Component {
return commandHeap.length;
};
- private isTag = (tag) => {
+ private isTag = tag => {
const { tags } = this.state;
return tags ? tags.includes(tag) : false;
};
- private getMemoryColor = (indexValue) => {
+ private getMemoryColor = indexValue => {
const { heap } = this.state;
const value = heap ? heap[indexValue] : 0;
@@ -209,7 +209,7 @@ class CopyGC extends React.Component {
return color;
};
- private getBackgroundColor = (indexValue) => {
+ private getBackgroundColor = indexValue => {
const { firstChild } = this.state;
const { lastChild } = this.state;
const { commandHeap, value } = this.state;
@@ -264,38 +264,34 @@ class CopyGC extends React.Component {
marginTop: 10
}}
>
- {state.leftDesc
- ? (
-
-
- {state.leftDesc}
-
- )
- : (
- false
- )}
- {state.rightDesc
- ? (
-
-
- {state.rightDesc}
-
- )
- : (
- false
- )}
+ {state.leftDesc ? (
+
+
+ {state.leftDesc}
+
+ ) : (
+ false
+ )}
+ {state.rightDesc ? (
+
+
+ {state.rightDesc}
+
+ ) : (
+ false
+ )}
@@ -323,17 +319,19 @@ class CopyGC extends React.Component {
{state.toSpace === 0 ? 'To Space' : 'From Space'}
- {toMemoryMatrix
- && toMemoryMatrix.length > 0
- && toMemoryMatrix.map((item, row) => (
-
+ {toMemoryMatrix &&
+ toMemoryMatrix.length > 0 &&
+ toMemoryMatrix.map((item, row) => (
+
{row * state.column}
- {item
- && item.length > 0
- && item.map((content) => {
+ {item &&
+ item.length > 0 &&
+ item.map(content => {
const color = this.getMemoryColor(content);
const bgColor = this.getBackgroundColor(content);
return (
@@ -360,18 +358,20 @@ class CopyGC extends React.Component
{
{state.toSpace > 0 ? 'To Space' : 'From Space'}
- {fromMemoryMatrix
- && fromMemoryMatrix.length > 0
- && fromMemoryMatrix.map((item, row) => (
-
+ {fromMemoryMatrix &&
+ fromMemoryMatrix.length > 0 &&
+ fromMemoryMatrix.map((item, row) => (
+
{row * state.column + state.memorySize / 2}
{item && item.length > 0
- ? item.map((content) => {
+ ? item.map(content => {
const color = this.getMemoryColor(content);
const bgColor = this.getBackgroundColor(content);
return (
@@ -397,11 +397,13 @@ class CopyGC extends React.Component
{
-
+
{
- private readonly canvasReference: React.RefObject = React.createRef();
+ private readonly canvasReference: React.RefObject =
+ React.createRef();
private statefulRenderer: StatefulRenderer | null = null;
@@ -32,9 +39,8 @@ export default class CanvasHolder extends React.Component<
const { current: canvas } = this.canvasReference;
if (canvas === null) return;
- const renderGroups: RenderGroup[] = Core
- .getRenderGroupManager()
- .getGroupsToRender();
+ const renderGroups: RenderGroup[] =
+ Core.getRenderGroupManager().getGroupsToRender();
const lastRenderGroup: RenderGroup = renderGroups.at(-1) as RenderGroup;
this.statefulRenderer = new StatefulRenderer(
@@ -59,105 +65,108 @@ export default class CanvasHolder extends React.Component<
// canvasReference via the ref attribute, for imperatively modifying the
// canvas
render() {
- return <>
-
+ return (
+ <>
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+ >
+
+
-
-
-
- WebGL Context Lost
-
-
-
- Your GPU is probably busy. Waiting for browser to re-establish connection...
-
-
- >;
+
+ WebGL Context Lost
+
+
+
+ Your GPU is probably busy. Waiting for browser to re-establish
+ connection...
+
+
+ >
+ );
}
}
diff --git a/src/tabs/Csg/hover_control_hint.tsx b/src/tabs/Csg/hover_control_hint.tsx
index 5fdf3c04b..180160858 100644
--- a/src/tabs/Csg/hover_control_hint.tsx
+++ b/src/tabs/Csg/hover_control_hint.tsx
@@ -1,32 +1,35 @@
/* [Imports] */
import { Icon, Tooltip } from '@blueprintjs/core';
import React from 'react';
-import { BP_ICON_COLOR, SA_TAB_BUTTON_WIDTH, SA_TAB_ICON_SIZE } from '../common/css_constants';
+import {
+ BP_ICON_COLOR,
+ SA_TAB_BUTTON_WIDTH,
+ SA_TAB_ICON_SIZE
+} from '../common/css_constants';
import type { HintProps } from './types';
/* [Main] */
export default class HoverControlHint extends React.Component
{
render() {
- return
-
-
-
-
;
+
+
+
+
+ );
}
}
diff --git a/src/tabs/Csg/index.tsx b/src/tabs/Csg/index.tsx
index 00a42cf4f..94ee2455f 100644
--- a/src/tabs/Csg/index.tsx
+++ b/src/tabs/Csg/index.tsx
@@ -10,21 +10,17 @@ import CanvasHolder from './canvas_holder';
export default {
// Called by the frontend to decide whether to spawn the CSG tab
toSpawn(debuggerContext: DebuggerContext): boolean {
- const moduleState: CsgModuleState = debuggerContext.context.moduleContexts.csg.state;
+ const moduleState: CsgModuleState =
+ debuggerContext.context.moduleContexts.csg.state;
// toSpawn() is checked before the frontend calls body() if needed, so we
// initialise Core for the first time over on the tabs' end here
Core.initialize(moduleState);
- return Core.getRenderGroupManager()
- .shouldRender();
+ return Core.getRenderGroupManager().shouldRender();
},
// Called by the frontend to know what to render in the CSG tab
body(_debuggerContext: DebuggerContext): ReactElement {
- return (
-
- );
+ return ;
},
// BlueprintJS icon name
diff --git a/src/tabs/Curve/__tests__/Curve.tsx b/src/tabs/Curve/__tests__/Curve.tsx
index d0d87089e..4358be5d7 100644
--- a/src/tabs/Curve/__tests__/Curve.tsx
+++ b/src/tabs/Curve/__tests__/Curve.tsx
@@ -1,18 +1,32 @@
import { CurveTab } from '..';
-import { animate_3D_curve, animate_curve, draw_3D_connected, draw_connected } from '../../../bundles/curve';
+import {
+ animate_3D_curve,
+ animate_curve,
+ draw_3D_connected,
+ draw_connected
+} from '../../../bundles/curve';
import type { CurveModuleState } from '../../../bundles/curve/types';
import { mockDebuggerContext } from '../../common/testUtils';
test('Curve animations error gracefully', () => {
const badAnimation = animate_curve(1, 60, draw_connected(200), t => 1 as any);
- const mockContext = mockDebuggerContext({ drawnCurves: [badAnimation] }, 'curve');
- expect( )
- .toMatchSnapshot();
+ const mockContext = mockDebuggerContext(
+ { drawnCurves: [badAnimation] },
+ 'curve'
+ );
+ expect( ).toMatchSnapshot();
});
test('Curve 3D animations error gracefully', () => {
- const badAnimation = animate_3D_curve(1, 60, draw_3D_connected(200), t => 1 as any);
- const mockContext = mockDebuggerContext({ drawnCurves: [badAnimation] }, 'curve');
- expect( )
- .toMatchSnapshot();
+ const badAnimation = animate_3D_curve(
+ 1,
+ 60,
+ draw_3D_connected(200),
+ t => 1 as any
+ );
+ const mockContext = mockDebuggerContext(
+ { drawnCurves: [badAnimation] },
+ 'curve'
+ );
+ expect( ).toMatchSnapshot();
});
diff --git a/src/tabs/Curve/animation_canvas_3d_curve.tsx b/src/tabs/Curve/animation_canvas_3d_curve.tsx
index e993efaf9..ece620f0c 100644
--- a/src/tabs/Curve/animation_canvas_3d_curve.tsx
+++ b/src/tabs/Curve/animation_canvas_3d_curve.tsx
@@ -6,7 +6,11 @@ import AutoLoopSwitch from '../common/AutoLoopSwitch';
import ButtonComponent from '../common/ButtonComponent';
import PlayButton from '../common/PlayButton';
import WebGLCanvas from '../common/WebglCanvas';
-import { BP_TAB_BUTTON_MARGIN, BP_TEXT_MARGIN, CANVAS_MAX_WIDTH } from '../common/css_constants';
+import {
+ BP_TAB_BUTTON_MARGIN,
+ BP_TEXT_MARGIN,
+ CANVAS_MAX_WIDTH
+} from '../common/css_constants';
type Props = {
animation: AnimatedCurve;
@@ -157,7 +161,7 @@ export default class AnimationCanvas3dCurve extends React.Component<
// Animation hasn't ended, so just draw the next frame
this.drawFrame();
this.setState(
- (prev) => ({
+ prev => ({
animTimestamp: prev.animTimestamp + currentFrame
}),
this.reqFrame
@@ -192,17 +196,14 @@ export default class AnimationCanvas3dCurve extends React.Component<
* Reset button click handler
*/
private onResetButtonClick = () => {
- this.setState(
- { animTimestamp: 0 },
- () => {
- if (this.state.isPlaying) {
- // Force stop
- this.onPlayButtonClick();
- }
-
- this.drawFrame();
+ this.setState({ animTimestamp: 0 }, () => {
+ if (this.state.isPlaying) {
+ // Force stop
+ this.onPlayButtonClick();
}
- );
+
+ this.drawFrame();
+ });
};
/**
@@ -212,7 +213,7 @@ export default class AnimationCanvas3dCurve extends React.Component<
private onTimeSliderChange = (newValue: number) => {
this.callbackTimestamp = null;
this.setState(
- (prev) => ({
+ prev => ({
wasPlaying: prev.isPlaying,
isPlaying: false,
animTimestamp: newValue
@@ -226,7 +227,7 @@ export default class AnimationCanvas3dCurve extends React.Component<
*/
private onTimeSliderRelease = () => {
this.setState(
- (prev) => ({
+ prev => ({
isPlaying: prev.wasPlaying
}),
() => {
@@ -256,139 +257,142 @@ export default class AnimationCanvas3dCurve extends React.Component<
* Auto loop switch onChange callback
*/
private onSwitchChange = () => {
- this.setState((prev) => ({
+ this.setState(prev => ({
isAutoLooping: !prev.isAutoLooping
}));
};
public render() {
- return
+ return (
-
-
-
-
-
-
-
-
+
+
+
+
+
-
+
+
+
+
+
-
-
-
- {this.state.errored
- ? (
-
-
+ {this.state.errored ? (
+
-
-
+
+ flexDirection: 'row',
+ alignItems: 'center'
+ }}
+ >
+
+
An error occurred while running your animation!
Here's the details:
-
+
{this.state.errored.toString()}
-
)
- : (
+
+ ) : (
{
+ ref={r => {
this.canvas = r;
}}
/>
)}
+
-
;
+ );
}
}
diff --git a/src/tabs/Curve/canvas_3d_curve.tsx b/src/tabs/Curve/canvas_3d_curve.tsx
index 318ace72c..603b3bd62 100644
--- a/src/tabs/Curve/canvas_3d_curve.tsx
+++ b/src/tabs/Curve/canvas_3d_curve.tsx
@@ -4,7 +4,11 @@ import type { CurveDrawn } from '../../bundles/curve/curves_webgl';
import { degreesToRadians } from '../../common/utilities';
import PlayButton from '../common/PlayButton';
import WebGLCanvas from '../common/WebglCanvas';
-import { BP_TAB_BUTTON_MARGIN, BP_TEXT_MARGIN, CANVAS_MAX_WIDTH } from '../common/css_constants';
+import {
+ BP_TAB_BUTTON_MARGIN,
+ BP_TEXT_MARGIN,
+ CANVAS_MAX_WIDTH
+} from '../common/css_constants';
type State = {
/**
@@ -72,7 +76,7 @@ export default class Canvas3dCurve extends React.Component
{
if (!this.canvas) return;
this.setState(
- (prevState) => ({
+ prevState => ({
isRotating: !prevState.isRotating
}),
() => {
@@ -89,7 +93,7 @@ export default class Canvas3dCurve extends React.Component {
private autoRotate = () => {
if (this.canvas && this.state.isRotating) {
this.setState(
- (prevState) => ({
+ prevState => ({
...prevState,
displayAngle:
prevState.displayAngle >= 360 ? 0 : prevState.displayAngle + 2
@@ -102,7 +106,7 @@ export default class Canvas3dCurve extends React.Component {
}
};
- private onTextBoxChange = (event) => {
+ private onTextBoxChange = event => {
const angle = parseFloat(event.target.value);
this.setState(
() => ({ displayAngle: angle }),
@@ -122,68 +126,69 @@ export default class Canvas3dCurve extends React.Component {
}
public render() {
- return
+ return (
+
-
-
-
-
{
+ this.canvas = r;
}}
- type="number"
- value={ this.state.displayAngle }
- min={ 0 }
- max={ 360 }
- step={ 1 }
- disabled={ this.state.isRotating }
- onChange={ this.onTextBoxChange }
/>
-
- {
- this.canvas = r;
- }}
- />
-
-
;
+ );
}
}
diff --git a/src/tabs/Curve/index.tsx b/src/tabs/Curve/index.tsx
index d37045dff..48c8b529d 100644
--- a/src/tabs/Curve/index.tsx
+++ b/src/tabs/Curve/index.tsx
@@ -1,6 +1,10 @@
import type { CurveModuleState } from '../../bundles/curve/types';
import { glAnimation } from '../../typings/anim_types';
-import { getModuleState, type DebuggerContext, type ModuleTab } from '../../typings/type_helpers';
+import {
+ getModuleState,
+ type DebuggerContext,
+ type ModuleTab
+} from '../../typings/type_helpers';
import AnimationCanvas from '../common/AnimationCanvas';
import MultiItemDisplay from '../common/MultItemDisplay';
import WebGLCanvas from '../common/WebglCanvas';
@@ -13,29 +17,25 @@ export const CurveTab: ModuleTab = ({ context }) => {
const elemKey = i.toString();
if (glAnimation.isAnimation(curve)) {
- return curve.is3D
- ? (
-
- )
- : (
-
- );
- }
- return curve.is3D()
- ? (
-
- )
- : (
- {
- if (r) {
- curve.init(r);
- curve.redraw(0);
- }
- }}
- key={elemKey}
- />
+ return curve.is3D ? (
+
+ ) : (
+
);
+ }
+ return curve.is3D() ? (
+
+ ) : (
+ {
+ if (r) {
+ curve.init(r);
+ curve.redraw(0);
+ }
+ }}
+ key={elemKey}
+ />
+ );
});
return ;
@@ -43,7 +43,8 @@ export const CurveTab: ModuleTab = ({ context }) => {
export default {
toSpawn(context: DebuggerContext) {
- const drawnCurves = context.context?.moduleContexts?.curve?.state?.drawnCurves;
+ const drawnCurves =
+ context.context?.moduleContexts?.curve?.state?.drawnCurves;
return drawnCurves.length > 0;
},
body(context: DebuggerContext) {
diff --git a/src/tabs/Game/constants.ts b/src/tabs/Game/constants.ts
index a6afdeac5..b925b3ade 100644
--- a/src/tabs/Game/constants.ts
+++ b/src/tabs/Game/constants.ts
@@ -1,5 +1,5 @@
export enum Links {
gameUserGuide = 'https://github.com/source-academy/modules/wiki/%5Bgame%5D-User-Guide',
gameDeveloperDocumentation = 'https://github.com/source-academy/modules/wiki/%5Bgame%5D-Developer-Documentation',
- gameAPIDocumentation = 'https://source-academy.github.io/modules/documentation/modules/game.html',
+ gameAPIDocumentation = 'https://source-academy.github.io/modules/documentation/modules/game.html'
}
diff --git a/src/tabs/MarkSweep/index.tsx b/src/tabs/MarkSweep/index.tsx
index 4e4217146..2a06d1824 100644
--- a/src/tabs/MarkSweep/index.tsx
+++ b/src/tabs/MarkSweep/index.tsx
@@ -1,4 +1,4 @@
-import { Slider, Icon } from '@blueprintjs/core';
+import { Icon, Slider } from '@blueprintjs/core';
import React from 'react';
import { ThemeColor } from './style';
@@ -57,9 +57,9 @@ class MarkSweep extends React.Component {
componentDidMount() {
const { debuggerContext } = this.props;
if (
- debuggerContext
- && debuggerContext.result
- && debuggerContext.result.value
+ debuggerContext &&
+ debuggerContext.result &&
+ debuggerContext.result.value
) {
this.initialize_state();
}
@@ -178,19 +178,19 @@ class MarkSweep extends React.Component {
private getlengthFunction = () => {
const { debuggerContext } = this.props;
- const commandHeap
- = debuggerContext && debuggerContext.result.value
+ const commandHeap =
+ debuggerContext && debuggerContext.result.value
? debuggerContext.result.value.get_command()
: [];
return commandHeap.length;
};
- private isTag = (tag) => {
+ private isTag = tag => {
const { tags } = this.state;
return tags ? tags.includes(tag) : false;
};
- private getMemoryColor = (indexValue) => {
+ private getMemoryColor = indexValue => {
const { heap, marked, unmarked, command } = this.state;
const { debuggerContext } = this.props;
const roots = debuggerContext.result.value
@@ -219,7 +219,7 @@ class MarkSweep extends React.Component {
return color;
};
- private getBackgroundColor = (indexValue) => {
+ private getBackgroundColor = indexValue => {
const { firstChild } = this.state;
const { lastChild } = this.state;
const { commandHeap, value, command } = this.state;
@@ -285,22 +285,20 @@ class MarkSweep extends React.Component {
{state.leftDesc}
)}
- {state.rightDesc
- ? (
-
-
- {state.rightDesc}
-
- )
- : (
- false
- )}
+ {state.rightDesc ? (
+
+
+ {state.rightDesc}
+
+ ) : (
+ false
+ )}
@@ -327,17 +325,19 @@ class MarkSweep extends React.Component {
- {memoryMatrix
- && memoryMatrix.length > 0
- && memoryMatrix.map((item, row) => (
-
+ {memoryMatrix &&
+ memoryMatrix.length > 0 &&
+ memoryMatrix.map((item, row) => (
+
{row * state.column}
- {item
- && item.length > 0
- && item.map((content) => {
+ {item &&
+ item.length > 0 &&
+ item.map(content => {
const color = this.getMemoryColor(content);
const bgColor = this.getBackgroundColor(content);
return (
@@ -365,7 +365,7 @@ class MarkSweep extends React.Component
{
Queue: [
- {state.queue.map((child) => (
+ {state.queue.map(child => (
{child},
))}
]
diff --git a/src/tabs/MarkSweep/style.tsx b/src/tabs/MarkSweep/style.tsx
index 8817fe1f3..c1fddd6f1 100644
--- a/src/tabs/MarkSweep/style.tsx
+++ b/src/tabs/MarkSweep/style.tsx
@@ -5,7 +5,7 @@ export enum ThemeColor {
GREEN = '#42a870',
YELLOW = '#f0d60e',
RED = 'red',
- BLACK = 'black',
+ BLACK = 'black'
}
export const FONT = {
diff --git a/src/tabs/Painter/index.tsx b/src/tabs/Painter/index.tsx
index 7e243bd1e..75bcf0a4f 100644
--- a/src/tabs/Painter/index.tsx
+++ b/src/tabs/Painter/index.tsx
@@ -4,14 +4,14 @@ import type { DebuggerContext } from '../../typings/type_helpers';
import Modal from '../common/ModalDiv';
type Props = {
- children?: never
- className?: string
- debuggerContext: any
+ children?: never;
+ className?: string;
+ debuggerContext: any;
};
type State = {
- modalOpen: boolean
- selectedPainter: any | null
+ modalOpen: boolean;
+ selectedPainter: any | null;
};
class Painter extends React.Component
{
@@ -31,7 +31,15 @@ class Painter extends React.Component {
};
public render() {
- const { context: { moduleContexts: { painter: { state: { drawnPainters } } } } } = this.props.debuggerContext;
+ const {
+ context: {
+ moduleContexts: {
+ painter: {
+ state: { drawnPainters }
+ }
+ }
+ }
+ } = this.props.debuggerContext;
return (
@@ -52,28 +60,25 @@ class Painter extends React.Component
{
height: '20rem',
width: '20rem'
}}
- >
-
+ >
- {
- drawnPainters.map((drawnPainter: any, id:number) => {
- const divId = `plotDiv${id}`;
- return (
- <>
- this.handleOpen(drawnPainter)}>Click here to open Modal
- {
- console.log(drawnPainter);
- drawnPainter.draw(divId);
- }}
- >
-
- >
- );
- })
- }
-
+ {drawnPainters.map((drawnPainter: any, id: number) => {
+ const divId = `plotDiv${id}`;
+ return (
+ <>
+ this.handleOpen(drawnPainter)}>
+ Click here to open Modal
+
+ {
+ console.log(drawnPainter);
+ drawnPainter.draw(divId);
+ }}
+ >
+ >
+ );
+ })}
);
}
@@ -81,7 +86,8 @@ class Painter extends React.Component
{
export default {
toSpawn(context: DebuggerContext) {
- const drawnPainters = context.context?.moduleContexts?.painter.state.drawnPainters;
+ const drawnPainters =
+ context.context?.moduleContexts?.painter.state.drawnPainters;
console.log(drawnPainters);
return drawnPainters.length > 0;
},
diff --git a/src/tabs/Pixnflix/index.tsx b/src/tabs/Pixnflix/index.tsx
index 9ca938509..6daf33c4b 100644
--- a/src/tabs/Pixnflix/index.tsx
+++ b/src/tabs/Pixnflix/index.tsx
@@ -15,9 +15,9 @@ import {
MIN_WIDTH
} from '../../bundles/pix_n_flix/constants';
import {
+ InputFeed,
type BundlePacket,
type ErrorLogger,
- InputFeed,
type TabsPacket
} from '../../bundles/pix_n_flix/types';
@@ -31,7 +31,7 @@ enum VideoMode {
Video,
Still,
Accepting,
- Image,
+ Image
}
type State = {
@@ -195,10 +195,10 @@ class PixNFlix extends React.Component {
public handleUpdateDimensions = (w: number, h: number) => {
if (
- w >= MIN_WIDTH
- && w <= MAX_WIDTH
- && h >= MIN_HEIGHT
- && h <= MAX_HEIGHT
+ w >= MIN_WIDTH &&
+ w <= MAX_WIDTH &&
+ h >= MIN_HEIGHT &&
+ h <= MAX_HEIGHT
) {
this.setState({
width: w,
@@ -264,9 +264,9 @@ class PixNFlix extends React.Component {
*/
private isPixNFlix() {
return (
- this.pixNFlix
- && this.pixNFlix.toReplString
- && this.pixNFlix.toReplString() === '[Pix N Flix]'
+ this.pixNFlix &&
+ this.pixNFlix.toReplString &&
+ this.pixNFlix.toReplString() === '[Pix N Flix]'
);
}
@@ -359,7 +359,7 @@ class PixNFlix extends React.Component {
{
+ ref={r => {
this.$image = r;
}}
width={DEFAULT_WIDTH}
@@ -367,7 +367,7 @@ class PixNFlix extends React.Component
{
style={{ display: 'none' }}
/>
{
+ ref={r => {
this.$video = r;
}}
autoPlay
@@ -376,7 +376,7 @@ class PixNFlix extends React.Component {
style={{ display: 'none' }}
/>
{
+ ref={r => {
this.$canvas = r;
}}
width={DEFAULT_WIDTH}
diff --git a/src/tabs/Plotly/index.tsx b/src/tabs/Plotly/index.tsx
index aa4fe0373..4b5cccdbc 100644
--- a/src/tabs/Plotly/index.tsx
+++ b/src/tabs/Plotly/index.tsx
@@ -4,14 +4,14 @@ import { type DebuggerContext } from '../../typings/type_helpers';
import Modal from '../common/ModalDiv';
type Props = {
- children?: never
- className?: string
- debuggerContext: any
+ children?: never;
+ className?: string;
+ debuggerContext: any;
};
type State = {
- modalOpen: boolean
- selectedPlot: any | null
+ modalOpen: boolean;
+ selectedPlot: any | null;
};
class Plotly extends React.Component {
@@ -31,7 +31,15 @@ class Plotly extends React.Component {
};
public render() {
- const { context: { moduleContexts: { plotly: { state: { drawnPlots } } } } } = this.props.debuggerContext;
+ const {
+ context: {
+ moduleContexts: {
+ plotly: {
+ state: { drawnPlots }
+ }
+ }
+ }
+ } = this.props.debuggerContext;
return (
@@ -49,31 +57,31 @@ class Plotly extends React.Component
{
}
}}
style={{ height: '80vh' }}
- >
-
+ >
- {
- drawnPlots.map((drawnPlot: any, id:number) => {
- const divId = `plotDiv${id}`;
- return (
-
{
+ const divId = `plotDiv${id}`;
+ return (
+
-
this.handleOpen(drawnPlot)}>Click here to open Modal
-
{
- drawnPlot.draw(divId);
- }}
- >
-
+ }}
+ key={divId}
+ >
+
this.handleOpen(drawnPlot)}>
+ Click here to open Modal
- );
- })
- }
-
+
{
+ drawnPlot.draw(divId);
+ }}
+ >
+
+ );
+ })}
);
}
diff --git a/src/tabs/Repl/index.tsx b/src/tabs/Repl/index.tsx
index 607472d0e..6ee9106f0 100644
--- a/src/tabs/Repl/index.tsx
+++ b/src/tabs/Repl/index.tsx
@@ -15,23 +15,23 @@ import type { DebuggerContext } from '../../typings/type_helpers';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const AceEditor = require('react-ace').default;
+import 'ace-builds/src-noconflict/ext-language_tools';
import 'ace-builds/src-noconflict/mode-javascript';
import 'ace-builds/src-noconflict/theme-twilight';
-import 'ace-builds/src-noconflict/ext-language_tools';
type Props = {
programmableReplInstance: ProgrammableRepl;
};
type State = {
- editorHeight: number,
- isDraggingDragBar: boolean,
+ editorHeight: number;
+ isDraggingDragBar: boolean;
};
const BOX_PADDING_VALUE = 4;
class ProgrammableReplGUI extends React.Component
{
- public replInstance : ProgrammableRepl;
+ public replInstance: ProgrammableRepl;
private editorAreaRect;
private editorInstance;
constructor(data: Props) {
@@ -43,19 +43,22 @@ class ProgrammableReplGUI extends React.Component {
isDraggingDragBar: false
};
}
- private dragBarOnMouseDown = (e) => {
+ private dragBarOnMouseDown = e => {
e.preventDefault();
this.setState({ isDraggingDragBar: true });
};
- private onMouseMove = (e) => {
+ private onMouseMove = e => {
if (this.state.isDraggingDragBar) {
- const height = Math.max(e.clientY - this.editorAreaRect.top - BOX_PADDING_VALUE * 2, MINIMUM_EDITOR_HEIGHT);
+ const height = Math.max(
+ e.clientY - this.editorAreaRect.top - BOX_PADDING_VALUE * 2,
+ MINIMUM_EDITOR_HEIGHT
+ );
this.replInstance.editorHeight = height;
this.setState({ editorHeight: height });
this.editorInstance.resize();
}
};
- private onMouseUp = (_e) => {
+ private onMouseUp = _e => {
this.setState({ isDraggingDragBar: false });
};
componentDidMount() {
@@ -68,27 +71,42 @@ class ProgrammableReplGUI extends React.Component {
}
public render() {
const { editorHeight } = this.state;
- const outputDivs : React.JSX.Element[] = [];
+ const outputDivs: React.JSX.Element[] = [];
const outputStringCount = this.replInstance.outputStrings.length;
for (let i = 0; i < outputStringCount; i++) {
const str = this.replInstance.outputStrings[i];
if (str.outputMethod === 'richtext') {
if (str.color === '') {
- outputDivs.push(
);
+ outputDivs.push(
+
+ );
} else {
- outputDivs.push(
);
+ outputDivs.push(
+
+ );
}
} else if (str.color === '') {
- outputDivs.push({ str.content }
);
+ outputDivs.push({str.content}
);
} else {
- outputDivs.push({ str.content }
-
);
+ outputDivs.push(
+
+ {str.content}
+
+ );
}
}
return (
@@ -97,50 +115,60 @@ class ProgrammableReplGUI extends React.Component {
className="programmable-repl-button"
icon={IconNames.PLAY}
active={true}
- onClick={() => this.replInstance.runCode()}// Note: Here if I directly use "this.replInstance.RunCode" instead using this lambda function, the "this" reference will become undefined and lead to a runtime error when user clicks the "Run" button
+ onClick={() => this.replInstance.runCode()} // Note: Here if I directly use "this.replInstance.RunCode" instead using this lambda function, the "this" reference will become undefined and lead to a runtime error when user clicks the "Run" button
text="Run"
/>
this.replInstance.saveEditorContent()}// Note: Here if I directly use "this.replInstance.RunCode" instead using this lambda function, the "this" reference will become undefined and lead to a runtime error when user clicks the "Run" button
+ onClick={() => this.replInstance.saveEditorContent()} // Note: Here if I directly use "this.replInstance.RunCode" instead using this lambda function, the "this" reference will become undefined and lead to a runtime error when user clicks the "Run" button
text="Save"
/>
- {
- this.editorAreaRect = e?.getBoundingClientRect();
- }} style={{
- padding: `${BOX_PADDING_VALUE}px`,
- border: '2px solid #6f8194'
- }}>
+
{
+ this.editorAreaRect = e?.getBoundingClientRect();
+ }}
+ style={{
+ padding: `${BOX_PADDING_VALUE}px`,
+ border: '2px solid #6f8194'
+ }}
+ >
{
+ ref={e => {
this.editorInstance = e?.editor;
this.replInstance.setEditorInstance(e?.editor);
}}
- style={ {
+ style={{
width: '100%',
height: `${editorHeight}px`,
- ...(this.replInstance.customizedEditorProps.backgroundImageUrl !== 'no-background-image' && {
+ ...(this.replInstance.customizedEditorProps.backgroundImageUrl !==
+ 'no-background-image' && {
backgroundImage: `url(${this.replInstance.customizedEditorProps.backgroundImageUrl})`,
backgroundColor: `rgba(20, 20, 20, ${this.replInstance.customizedEditorProps.backgroundColorAlpha})`,
backgroundSize: '100%',
backgroundRepeat: 'no-repeat'
})
- } }
- mode="javascript" theme="twilight"
- onChange={ (newValue) => this.replInstance.updateUserCode(newValue) }
+ }}
+ mode="javascript"
+ theme="twilight"
+ onChange={newValue => this.replInstance.updateUserCode(newValue)}
value={this.replInstance.userCodeInEditor.toString()}
/>
-
-
@@ -165,7 +193,11 @@ export default {
* @param {DebuggerContext} context
*/
body(context: DebuggerContext) {
- return
;
+ return (
+
+ );
},
/**
diff --git a/src/tabs/Rune/__tests__/Rune.tsx b/src/tabs/Rune/__tests__/Rune.tsx
index c352b49bf..308b48d5f 100644
--- a/src/tabs/Rune/__tests__/Rune.tsx
+++ b/src/tabs/Rune/__tests__/Rune.tsx
@@ -5,7 +5,9 @@ import { mockDebuggerContext } from '../../common/testUtils';
test('Ensure that rune animations error gracefully', () => {
const badAnimation = animate_rune(1, 60, t => 1 as any);
- const mockContext = mockDebuggerContext
({ drawnRunes: [badAnimation ]}, 'rune');
- expect( )
- .toMatchSnapshot();
+ const mockContext = mockDebuggerContext(
+ { drawnRunes: [badAnimation] },
+ 'rune'
+ );
+ expect( ).toMatchSnapshot();
});
diff --git a/src/tabs/Rune/index.tsx b/src/tabs/Rune/index.tsx
index c5585e92f..e5db4221a 100644
--- a/src/tabs/Rune/index.tsx
+++ b/src/tabs/Rune/index.tsx
@@ -1,6 +1,13 @@
-import { type RuneModuleState, isHollusionRune } from '../../bundles/rune/functions';
+import {
+ isHollusionRune,
+ type RuneModuleState
+} from '../../bundles/rune/functions';
import { glAnimation } from '../../typings/anim_types';
-import { getModuleState, type DebuggerContext, type ModuleTab } from '../../typings/type_helpers';
+import {
+ getModuleState,
+ type DebuggerContext,
+ type ModuleTab
+} from '../../typings/type_helpers';
import AnimationCanvas from '../common/AnimationCanvas';
import MultiItemDisplay from '../common/MultItemDisplay';
import WebGLCanvas from '../common/WebglCanvas';
@@ -12,18 +19,14 @@ export const RuneTab: ModuleTab = ({ context }) => {
const elemKey = i.toString();
if (glAnimation.isAnimation(rune)) {
- return (
-
- );
+ return ;
}
if (isHollusionRune(rune)) {
- return (
-
- );
+ return ;
}
return (
{
+ ref={r => {
if (r) {
rune.draw(r);
}
diff --git a/src/tabs/Sound/index.tsx b/src/tabs/Sound/index.tsx
index 8142d6897..0f3d98324 100644
--- a/src/tabs/Sound/index.tsx
+++ b/src/tabs/Sound/index.tsx
@@ -1,5 +1,9 @@
import type { SoundModuleState } from '../../bundles/sound/types';
-import { getModuleState, type DebuggerContext, type ModuleTab } from '../../typings/type_helpers';
+import {
+ getModuleState,
+ type DebuggerContext,
+ type ModuleTab
+} from '../../typings/type_helpers';
import MultiItemDisplay from '../common/MultItemDisplay';
/**
@@ -10,7 +14,7 @@ import MultiItemDisplay from '../common/MultItemDisplay';
const SoundTab: ModuleTab = ({ context }) => {
const { audioPlayed } = getModuleState(context, 'sound');
- const elements = audioPlayed.map((audio) => (
+ const elements = audioPlayed.map(audio => (
0;
},
/**
diff --git a/src/tabs/SoundMatrix/index.tsx b/src/tabs/SoundMatrix/index.tsx
index 6765de7ee..8addd61b6 100644
--- a/src/tabs/SoundMatrix/index.tsx
+++ b/src/tabs/SoundMatrix/index.tsx
@@ -74,7 +74,7 @@ class SoundMatrix extends React.Component {
{
+ ref={r => {
this.$container = r;
}}
/>
diff --git a/src/tabs/StereoSound/index.tsx b/src/tabs/StereoSound/index.tsx
index cfb65395d..ebabac2c5 100644
--- a/src/tabs/StereoSound/index.tsx
+++ b/src/tabs/StereoSound/index.tsx
@@ -1,5 +1,9 @@
import type { StereoSoundModuleState } from '../../bundles/stereo_sound/types';
-import { getModuleState, type DebuggerContext, type ModuleTab } from '../../typings/type_helpers';
+import {
+ getModuleState,
+ type DebuggerContext,
+ type ModuleTab
+} from '../../typings/type_helpers';
import MultiItemDisplay from '../common/MultItemDisplay';
/**
@@ -9,9 +13,12 @@ import MultiItemDisplay from '../common/MultItemDisplay';
*/
const SoundTab: ModuleTab = ({ context }) => {
- const { audioPlayed } = getModuleState
(context, 'sound');
+ const { audioPlayed } = getModuleState(
+ context,
+ 'sound'
+ );
- const elements = audioPlayed.map((audio) => (
+ const elements = audioPlayed.map(audio => (
0;
},
/**
diff --git a/src/tabs/UnityAcademy/index.tsx b/src/tabs/UnityAcademy/index.tsx
index 6a79a3ea5..cfbd1f94a 100644
--- a/src/tabs/UnityAcademy/index.tsx
+++ b/src/tabs/UnityAcademy/index.tsx
@@ -4,7 +4,7 @@
* @author Wang Zihan
*/
-import { Button, NumericInput, Checkbox } from '@blueprintjs/core';
+import { Button, Checkbox, NumericInput } from '@blueprintjs/core';
import { IconNames } from '@blueprintjs/icons';
import React from 'react';
import { getInstance } from '../../bundles/unity_academy/UnityAcademy';
@@ -14,33 +14,74 @@ import { type DebuggerContext } from '../../typings/type_helpers';
type Props = {};
class Unity3DTab extends React.Component {
- private userAgreementCheckboxChecked : boolean;
- constructor(props : Props) {
+ private userAgreementCheckboxChecked: boolean;
+ constructor(props: Props) {
super(props);
this.userAgreementCheckboxChecked = false;
}
render() {
let highFPSWarning;
- const currentTargetFrameRate = getInstance()
- .getTargetFrameRate();
+ const currentTargetFrameRate = getInstance().getTargetFrameRate();
if (currentTargetFrameRate > 30 && currentTargetFrameRate <= 60) {
- highFPSWarning = [Warning] You are using a target FPS higher than default value (30). Higher FPS will lead to more cost in your device's resources such as GPU, increace device temperature and battery usage and may even lead to browser not responding, crash the browser or even crash your operation system if your device really can not endure the high resource cost.
;
+ highFPSWarning = (
+
+ [Warning] You are using a target FPS higher than default value (30).
+ Higher FPS will lead to more cost in your device's resources such as
+ GPU, increace device temperature and battery usage and may even lead
+ to browser not responding, crash the browser or even crash your
+ operation system if your device really can not endure the high
+ resource cost.
+
+ );
} else if (currentTargetFrameRate > 60 && currentTargetFrameRate <= 120) {
- highFPSWarning = [!!WARNING!!] You are using a target FPS that is extremely high. This FPS may lead to large cost in your device's resources such as GPU, significantly increace device temperature and battery usage and have a large chance of making browser not responding, crash the browser or even crash your operation system if your device's performance is not enough. ***ARE YOU REALLY CONFIDENT ABOUT THE PERFORMANCE OF YOUR OWN DEVICE?***
;
+ highFPSWarning = (
+
+ [!!WARNING!!] You are using a target FPS that is extremely high. This
+ FPS may lead to large cost in your device's resources such as GPU,
+ significantly increace device temperature and battery usage and have a
+ large chance of making browser not responding, crash the browser or
+ even crash your operation system if your device's performance is not
+ enough.
+
+ ***ARE YOU REALLY CONFIDENT ABOUT THE PERFORMANCE OF YOUR OWN
+ DEVICE?***
+
+ );
} else {
- highFPSWarning =
;
+ highFPSWarning =
;
}
const dimensionMode = getInstance().dimensionMode;
return (
-
Click the button below to open the Unity Academy Window filling the page.
-
Current Mode: {dimensionMode === '3d' ? '3D' : '2D'}
-
-
Remember always terminate the Unity Academy application when you completely finish programming with this module to clean up the engine and free up memory.
-
Otherwise it may lead to a potential waste to your device's resources (such as RAM) and battery.
-
-
Note that you need to use a 'Native' variant of Source language in order to use this module. If any strange error happens when using this module, please check whether you are using the 'Native' variant of Source language or not.
-
+
+ Click the button below to open the Unity Academy Window filling the
+ page.
+
+
+ Current Mode: {dimensionMode === '3d' ? '3D' : '2D'}
+
+
+
+
+ Remember always terminate the Unity Academy application when you
+ completely finish programming with this module
+ {' '}
+ to clean up the engine and free up memory.
+
+
+ Otherwise it may lead to a potential waste to your device's resources
+ (such as RAM) and battery.
+
+
+
+
+ Note that you need to use a 'Native' variant of Source
+ language in order to use this module.
+ {' '}
+ If any strange error happens when using this module, please check
+ whether you are using the 'Native' variant of Source language or not.
+
+
{
}}
text="Open Unity Academy Embedded Frontend"
/>
-
-
- If the frame rate is low when you are using Unity Academy with the default resolution, try using Unity Academy with 50% resolution here:
- 50% resolution will display Unity Academy in a smaller area with lower quality and less detailed graphics but requires less device (especially GPU) performance than the default resolution.
+
+
+
+ If the frame rate is low when you are using Unity Academy with the
+ default resolution, try using Unity Academy with 50% resolution here:
+
+
+ 50% resolution will display Unity Academy in a smaller area with lower
+ quality and less detailed graphics but requires less device
+ (especially GPU) performance than the default resolution.
+
{
}}
text="Open with 50% resolution"
/>
-
-
+
+
Target (Maximum) Frame Rate (Frames Per Second):
{
value={currentTargetFrameRate}
max={120}
min={15}
- onValueChange={(x) => {
- getInstance()
- .setTargetFrameRate(x);
+ onValueChange={x => {
+ getInstance().setTargetFrameRate(x);
this.setState({});
}}
stepSize={1}
@@ -81,8 +128,7 @@ class Unity3DTab extends React.Component {
{
- getInstance()
- .setTargetFrameRate(30);
+ getInstance().setTargetFrameRate(30);
this.setState({});
}}
text="30"
@@ -90,9 +136,12 @@ class Unity3DTab extends React.Component {
{
- if (confirm('Set the target frame rate higher than the default recommended value (30) ?')) {
- getInstance()
- .setTargetFrameRate(60);
+ if (
+ confirm(
+ 'Set the target frame rate higher than the default recommended value (30) ?'
+ )
+ ) {
+ getInstance().setTargetFrameRate(60);
this.setState({});
}
}}
@@ -101,9 +150,12 @@ class Unity3DTab extends React.Component {
{
- if (confirm('Set the target frame rate higher than the default recommended value (30) ?')) {
- getInstance()
- .setTargetFrameRate(90);
+ if (
+ confirm(
+ 'Set the target frame rate higher than the default recommended value (30) ?'
+ )
+ ) {
+ getInstance().setTargetFrameRate(90);
this.setState({});
}
}}
@@ -112,9 +164,12 @@ class Unity3DTab extends React.Component {
{
- if (confirm('Set the target frame rate higher than the default recommended value (30) ?')) {
- getInstance()
- .setTargetFrameRate(120);
+ if (
+ confirm(
+ 'Set the target frame rate higher than the default recommended value (30) ?'
+ )
+ ) {
+ getInstance().setTargetFrameRate(120);
this.setState({});
}
}}
@@ -123,37 +178,78 @@ class Unity3DTab extends React.Component {
The actual frame rate depends on your device's performance.
{highFPSWarning}
-
-
- 3D Prefab Information:
Click Here {dimensionMode === '2d' && ' (You need 3D mode to use prefabs.)'}
-
- Please note that before using Unity Academy and this module, you must agree to our
User Agreement
-
- {getInstance()
- .getUserAgreementStatus() === 'new_user_agreement' && The User Agreement has updated.
}
- {
- if (e !== null) {
- e.checked = (getInstance()
- .getUserAgreementStatus() === 'agreed');
- this.userAgreementCheckboxChecked = e.checked;
- }
- }} onChange={(event : React.ChangeEvent) => {
- this.userAgreementCheckboxChecked = event.target.checked;
- getInstance()
- .setUserAgreementStatus(this.userAgreementCheckboxChecked);
- }} />
+
+
+
+ 3D Prefab Information:{' '}
+
+ Click Here
+
+ {dimensionMode === '2d' && ' (You need 3D mode to use prefabs.)'}
+
+
+
+ Please note that before using Unity Academy and this module, you must
+ agree to our{' '}
+
+ User Agreement
+
+
+
+ {getInstance().getUserAgreementStatus() === 'new_user_agreement' && (
+
+ The User Agreement has updated.
+
+
+ )}
+ {
+ if (e !== null) {
+ e.checked = getInstance().getUserAgreementStatus() === 'agreed';
+ this.userAgreementCheckboxChecked = e.checked;
+ }
+ }}
+ onChange={(event: React.ChangeEvent) => {
+ this.userAgreementCheckboxChecked = event.target.checked;
+ getInstance().setUserAgreementStatus(
+ this.userAgreementCheckboxChecked
+ );
+ }}
+ />
);
}
- openUnityWindow(resolution : number) : void {
+ openUnityWindow(resolution: number): void {
if (!this.userAgreementCheckboxChecked) {
- alert('You must agree to the our User Agreement before using Unity Academy and this module!');
+ alert(
+ 'You must agree to the our User Agreement before using Unity Academy and this module!'
+ );
return;
}
const INSTANCE = getInstance();
if (INSTANCE === undefined) {
- alert('No running Unity application found. Please rerun your code and try again.');
+ alert(
+ 'No running Unity application found. Please rerun your code and try again.'
+ );
return;
}
INSTANCE.setShowUnityComponent(resolution);
diff --git a/src/tabs/common/AnimationCanvas.tsx b/src/tabs/common/AnimationCanvas.tsx
index 8ff2dbe7a..1af2a9770 100644
--- a/src/tabs/common/AnimationCanvas.tsx
+++ b/src/tabs/common/AnimationCanvas.tsx
@@ -6,7 +6,11 @@ import AutoLoopSwitch from './AutoLoopSwitch';
import ButtonComponent from './ButtonComponent';
import PlayButton from './PlayButton';
import WebGLCanvas from './WebglCanvas';
-import { BP_TAB_BUTTON_MARGIN, BP_TEXT_MARGIN, CANVAS_MAX_WIDTH } from './css_constants';
+import {
+ BP_TAB_BUTTON_MARGIN,
+ BP_TEXT_MARGIN,
+ CANVAS_MAX_WIDTH
+} from './css_constants';
type AnimCanvasProps = {
animation: glAnimation;
@@ -104,21 +108,23 @@ export default class AnimationCanvas extends React.Component<
this.reqframeId = requestAnimationFrame(this.animationCallback);
};
- private startAnimation = () => this.setState(
- {
- isPlaying: true
- },
- this.reqFrame
- );
-
- private stopAnimation = () => this.setState(
- {
- isPlaying: false
- },
- () => {
- this.callbackTimestamp = null;
- }
- );
+ private startAnimation = () =>
+ this.setState(
+ {
+ isPlaying: true
+ },
+ this.reqFrame
+ );
+
+ private stopAnimation = () =>
+ this.setState(
+ {
+ isPlaying: false
+ },
+ () => {
+ this.callbackTimestamp = null;
+ }
+ );
/**
* Callback to use with `requestAnimationFrame`
@@ -159,7 +165,7 @@ export default class AnimationCanvas extends React.Component<
} else {
// Animation hasn't ended, so just draw the next frame
this.setState(
- (prev) => ({
+ prev => ({
animTimestamp: prev.animTimestamp + currentFrame
}),
() => {
@@ -182,17 +188,14 @@ export default class AnimationCanvas extends React.Component<
* Reset button click handler
*/
private onResetButtonClick = () => {
- this.setState(
- { animTimestamp: 0 },
- () => {
- if (this.state.isPlaying) {
- // Force stop
- this.onPlayButtonClick();
- }
-
- this.drawFrame();
+ this.setState({ animTimestamp: 0 }, () => {
+ if (this.state.isPlaying) {
+ // Force stop
+ this.onPlayButtonClick();
}
- );
+
+ this.drawFrame();
+ });
};
/**
@@ -202,7 +205,7 @@ export default class AnimationCanvas extends React.Component<
private onSliderChange = (newValue: number) => {
this.callbackTimestamp = null;
this.setState(
- (prev) => ({
+ prev => ({
wasPlaying: prev.isPlaying,
isPlaying: false,
animTimestamp: newValue
@@ -216,7 +219,7 @@ export default class AnimationCanvas extends React.Component<
*/
private onSliderRelease = () => {
this.setState(
- (prev) => ({
+ prev => ({
isPlaying: prev.wasPlaying
}),
() => {
@@ -233,115 +236,121 @@ export default class AnimationCanvas extends React.Component<
* Auto loop switch onChange callback
*/
private onSwitchChange = () => {
- this.setState((prev) => ({
+ this.setState(prev => ({
isAutoLooping: !prev.isAutoLooping
}));
};
public render() {
- return
+ return (
-
-
-
-
-
-
-
-
+ onClick={this.onPlayButtonClick}
+ />
+
+
+
+
+
+
+
+
-
-
- {this.state.errored
- ? (
-
-
+ {this.state.errored ? (
+
-
-
+
+ flexDirection: 'row',
+ alignItems: 'center'
+ }}
+ >
+
+
An error occurred while running your animation!
Here's the details:
-
+
{this.state.errored.toString()}
-
)
- : (
+
+ ) : (
{
+ ref={r => {
this.canvas = r;
}}
/>
)}
+
-
;
+ );
}
}
diff --git a/src/tabs/common/AutoLoopSwitch.tsx b/src/tabs/common/AutoLoopSwitch.tsx
index 13cec0379..75cd8f92d 100644
--- a/src/tabs/common/AutoLoopSwitch.tsx
+++ b/src/tabs/common/AutoLoopSwitch.tsx
@@ -3,23 +3,25 @@ import { Switch, type SwitchProps } from '@blueprintjs/core';
import React from 'react';
export type AutoLoopSwitchProps = Omit & {
- isAutoLooping: boolean,
+ isAutoLooping: boolean;
};
/* [Main] */
export default class AutoLoopSwitch extends React.Component {
render() {
- return ;
+ // Prevent label from wrapping at every letter when width is small
+ whiteSpace: 'nowrap'
+ }}
+ label="Auto Loop"
+ checked={this.props.isAutoLooping}
+ {...this.props}
+ />
+ );
}
}
diff --git a/src/tabs/common/ButtonComponent.tsx b/src/tabs/common/ButtonComponent.tsx
index 4eb3d68ab..50af4759c 100644
--- a/src/tabs/common/ButtonComponent.tsx
+++ b/src/tabs/common/ButtonComponent.tsx
@@ -10,9 +10,9 @@ const defaultOptions = {
};
type Props = {
- onClick?: MouseEventHandler,
- disabled?: boolean,
- children?: ReactNode,
+ onClick?: MouseEventHandler;
+ disabled?: boolean;
+ children?: ReactNode;
};
const ButtonComponent = (props: Props) => {
@@ -20,12 +20,10 @@ const ButtonComponent = (props: Props) => {
...defaultOptions,
...props
};
- return props.disabled
- ? (
-
- )
- : (
-
- );
+ return props.disabled ? (
+
+ ) : (
+
+ );
};
export default ButtonComponent;
diff --git a/src/tabs/common/ModalDiv.tsx b/src/tabs/common/ModalDiv.tsx
index 737dae2f0..27c3f0682 100644
--- a/src/tabs/common/ModalDiv.tsx
+++ b/src/tabs/common/ModalDiv.tsx
@@ -40,21 +40,23 @@ const backdropStyle = {
} as CSSProperties;
interface ModalProp {
- open: boolean
- height: string
- width: string
- handleClose: MouseEventHandler
- children: ReactElement
+ open: boolean;
+ height: string;
+ width: string;
+ handleClose: MouseEventHandler;
+ children: ReactElement;
}
const Modal = ({ open, height, width, children, handleClose }: ModalProp) => (
<>
{open && (
<>
-
+
diff --git a/src/tabs/common/MultItemDisplay.tsx b/src/tabs/common/MultItemDisplay.tsx
index cb114d5c5..57fd95027 100644
--- a/src/tabs/common/MultItemDisplay.tsx
+++ b/src/tabs/common/MultItemDisplay.tsx
@@ -4,7 +4,7 @@ import { clamp } from 'lodash';
import React from 'react';
type MultiItemDisplayProps = {
- elements: React.JSX.Element[]
+ elements: React.JSX.Element[];
};
const MultiItemDisplay = ({ elements }: MultiItemDisplayProps) => {
@@ -15,8 +15,10 @@ const MultiItemDisplay = ({ elements }: MultiItemDisplayProps) => {
const [stepEditorValue, setStepEditorValue] = React.useState('1');
const [stepEditorFocused, setStepEditorFocused] = React.useState(false);
- const resetStepEditor = () => setStepEditorValue((currentStep + 1).toString());
- const elementsDigitCount = Math.floor(Math.log10(Math.max(1, elements.length))) + 1;
+ const resetStepEditor = () =>
+ setStepEditorValue((currentStep + 1).toString());
+ const elementsDigitCount =
+ Math.floor(Math.log10(Math.max(1, elements.length))) + 1;
return (
{
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-around'
- }}>
+ }}
+ >
Call
{/* When the text box is focused, it shows a little up and down bar, which needs a little bit
- * more space to be shown
- */}
-
+ * more space to be shown
+ */}
+
{
+ onChange={newValue => {
// Disallow non numeric inputs
if (newValue && !/^[0-9]+$/u.test(newValue)) return;
@@ -79,7 +90,7 @@ const MultiItemDisplay = ({ elements }: MultiItemDisplayProps) => {
if (newValue.length > elementsDigitCount) return;
setStepEditorValue(newValue);
}}
- onConfirm={(value) => {
+ onConfirm={value => {
if (value) {
const newStep = Number.parseFloat(value);
const clampedStep = clamp(newStep, 1, elements.length);
diff --git a/src/tabs/common/PlayButton.tsx b/src/tabs/common/PlayButton.tsx
index c21f3bd0e..03d1e3b48 100644
--- a/src/tabs/common/PlayButton.tsx
+++ b/src/tabs/common/PlayButton.tsx
@@ -1,27 +1,29 @@
/* [Imports] */
-import { Icon, type ButtonProps, Tooltip } from '@blueprintjs/core';
+import { Icon, Tooltip, type ButtonProps } from '@blueprintjs/core';
import { IconNames } from '@blueprintjs/icons';
import React from 'react';
import ButtonComponent from './ButtonComponent';
/* [Exports] */
export type PlayButtonProps = ButtonProps & {
- isPlaying: boolean,
+ isPlaying: boolean;
// onClickCallback: () => void,
};
/* [Main] */
export default class PlayButton extends React.Component {
render() {
- return
-
-
-
- ;
+ return (
+
+
+
+
+
+ );
}
}
diff --git a/src/tabs/common/WebglCanvas.tsx b/src/tabs/common/WebglCanvas.tsx
index 072c74caf..a8ed7f80d 100644
--- a/src/tabs/common/WebglCanvas.tsx
+++ b/src/tabs/common/WebglCanvas.tsx
@@ -13,8 +13,8 @@ const defaultStyle = {
*/
const WebGLCanvas = React.forwardRef(
(props: any, ref) => {
- const style
- = props.style !== undefined
+ const style =
+ props.style !== undefined
? {
...defaultStyle,
...props.style
diff --git a/src/tabs/common/testUtils.ts b/src/tabs/common/testUtils.ts
index 6e6540f1a..17e7a7cf8 100644
--- a/src/tabs/common/testUtils.ts
+++ b/src/tabs/common/testUtils.ts
@@ -1,11 +1,12 @@
import type { DebuggerContext } from '../../typings/type_helpers';
-export const mockDebuggerContext = (state: T, moduleName: string) => ({
- context: {
- moduleContexts: {
- [moduleName]: {
- state
+export const mockDebuggerContext = (state: T, moduleName: string) =>
+ ({
+ context: {
+ moduleContexts: {
+ [moduleName]: {
+ state
+ }
}
}
- }
-}) as DebuggerContext;
+ } as DebuggerContext);
diff --git a/src/tabs/physics_2d/DebugDrawCanvas.tsx b/src/tabs/physics_2d/DebugDrawCanvas.tsx
index e70ab2566..fc55f714a 100644
--- a/src/tabs/physics_2d/DebugDrawCanvas.tsx
+++ b/src/tabs/physics_2d/DebugDrawCanvas.tsx
@@ -82,8 +82,8 @@ export default class DebugDrawCanvas extends React.Component<
private drawFrame = () => {
if (this.canvas) {
if (!this.debugDraw) {
- const ctx: CanvasRenderingContext2D | null
- = this.canvas.getContext('2d');
+ const ctx: CanvasRenderingContext2D | null =
+ this.canvas.getContext('2d');
if (ctx) {
this.debugDraw = new DebugDraw(ctx);
}
@@ -99,21 +99,23 @@ export default class DebugDrawCanvas extends React.Component<
private reqFrame = () => requestAnimationFrame(this.animationCallback);
- private startAnimation = () => this.setState(
- {
- isPlaying: true
- },
- this.reqFrame
- );
-
- private stopAnimation = () => this.setState(
- {
- isPlaying: false
- },
- () => {
- this.callbackTimestamp = null;
- }
- );
+ private startAnimation = () =>
+ this.setState(
+ {
+ isPlaying: true
+ },
+ this.reqFrame
+ );
+
+ private stopAnimation = () =>
+ this.setState(
+ {
+ isPlaying: false
+ },
+ () => {
+ this.callbackTimestamp = null;
+ }
+ );
/**
* Callback to use with `requestAnimationFrame`
@@ -139,7 +141,7 @@ export default class DebugDrawCanvas extends React.Component<
this.callbackTimestamp = timeInMs;
this.setState(
- (prev) => ({
+ prev => ({
animTimestamp: prev.animTimestamp + currentFrame
}),
() => {
@@ -278,7 +280,7 @@ export default class DebugDrawCanvas extends React.Component<
style={{
flexGrow: 1
}}
- ref={(r) => {
+ ref={r => {
this.canvas = r;
}}
/>
diff --git a/src/tabs/physics_2d/index.tsx b/src/tabs/physics_2d/index.tsx
index 841724779..1bbe5be80 100644
--- a/src/tabs/physics_2d/index.tsx
+++ b/src/tabs/physics_2d/index.tsx
@@ -22,11 +22,19 @@ export default {
* @param {DebuggerContext} context
*/
body(context: DebuggerContext) {
- const { context: { moduleContexts: { physics_2d: { state: { world } } } } } = context;
+ const {
+ context: {
+ moduleContexts: {
+ physics_2d: {
+ state: { world }
+ }
+ }
+ }
+ } = context;
return (
-
+
);
},
From d57c4c34fc956a1753844f1a754e46648c021a0c Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Tue, 26 Mar 2024 21:54:34 +0800
Subject: [PATCH 04/39] Reformat bundles with Prettier
---
src/bundles/arcade_2d/audio.ts | 14 +-
src/bundles/arcade_2d/constants.ts | 9 +-
src/bundles/arcade_2d/functions.ts | 248 ++++---
src/bundles/arcade_2d/gameobject.ts | 31 +-
src/bundles/arcade_2d/index.ts | 40 +-
src/bundles/arcade_2d/phaserScene.ts | 188 +++--
src/bundles/arcade_2d/types.ts | 5 +-
src/bundles/binary_tree/functions.ts | 71 +-
src/bundles/binary_tree/index.ts | 9 +-
src/bundles/communication/Communications.ts | 12 +-
.../communication/GlobalStateController.ts | 6 +-
src/bundles/communication/MqttController.ts | 6 +-
.../communication/MultiUserController.ts | 6 +-
src/bundles/communication/RpcController.ts | 10 +-
src/bundles/communication/__tests__/index.ts | 88 +--
src/bundles/communication/index.ts | 12 +-
src/bundles/copy_gc/index.ts | 30 +-
src/bundles/copy_gc/types.ts | 2 +-
src/bundles/csg/functions.ts | 33 +-
src/bundles/csg/index.ts | 79 +--
src/bundles/csg/input_tracker.ts | 20 +-
src/bundles/csg/jscad/renderer.ts | 31 +-
src/bundles/csg/jscad/types.ts | 10 +-
src/bundles/csg/types.ts | 8 +-
src/bundles/csg/utilities.ts | 19 +-
src/bundles/curve/__tests__/curve.ts | 29 +-
src/bundles/curve/curves_webgl.ts | 9 +-
src/bundles/curve/functions.ts | 17 +-
src/bundles/curve/samples/canvases.js | 14 +-
src/bundles/curve/samples/imports.js | 38 -
src/bundles/curve/types.ts | 4 +-
src/bundles/game/functions.ts | 94 +--
src/bundles/game/index.ts | 12 +-
src/bundles/game/types.ts | 12 +-
src/bundles/mark_sweep/index.ts | 30 +-
src/bundles/mark_sweep/types.ts | 2 +-
src/bundles/painter/functions.ts | 24 +-
src/bundles/painter/index.ts | 2 +-
src/bundles/physics_2d/PhysicsObject.ts | 30 +-
src/bundles/physics_2d/PhysicsWorld.ts | 23 +-
src/bundles/physics_2d/functions.ts | 22 +-
src/bundles/physics_2d/index.ts | 50 +-
src/bundles/pix_n_flix/functions.ts | 60 +-
src/bundles/pix_n_flix/index.ts | 24 +-
src/bundles/pix_n_flix/types.ts | 2 +-
src/bundles/plotly/curve_functions.ts | 2 +-
src/bundles/plotly/functions.ts | 4 +-
src/bundles/plotly/index.ts | 6 +-
src/bundles/plotly/plotly.ts | 3 +-
src/bundles/plotly/sound_functions.ts | 12 +-
src/bundles/repeat/__tests__/index.ts | 11 +-
src/bundles/repeat/index.ts | 2 +-
src/bundles/repl/functions.ts | 27 +-
src/bundles/repl/index.ts | 8 +-
src/bundles/repl/programmable_repl.ts | 217 ++++--
src/bundles/rune/display.ts | 12 +-
src/bundles/rune/functions.ts | 35 +-
src/bundles/rune/index.ts | 2 +-
src/bundles/rune/rune.ts | 22 +-
src/bundles/rune/runes_ops.ts | 7 +-
src/bundles/rune/ruomu_journal.md | 25 +-
src/bundles/rune_in_words/functions.ts | 24 +-
src/bundles/rune_in_words/index.ts | 2 +-
src/bundles/rune_in_words/runes_ops.ts | 2 +-
src/bundles/scrabble/__tests__/index.ts | 18 +-
src/bundles/scrabble/index.ts | 6 +-
src/bundles/sound/__tests__/sound.test.ts | 23 +-
src/bundles/sound/functions.ts | 88 +--
src/bundles/sound/index.ts | 2 +-
src/bundles/sound/riffwave.ts | 4 +-
src/bundles/sound/types.ts | 2 +-
src/bundles/sound_matrix/functions.ts | 2 +-
src/bundles/sound_matrix/index.ts | 6 +-
src/bundles/sound_matrix/list.ts | 18 +-
src/bundles/stereo_sound/functions.ts | 134 ++--
src/bundles/stereo_sound/index.ts | 54 +-
src/bundles/stereo_sound/riffwave.ts | 4 +-
src/bundles/unity_academy/UnityAcademy.tsx | 575 ++++++++++-----
.../unity_academy/UnityAcademyMaths.ts | 68 +-
src/bundles/unity_academy/config.ts | 3 +-
src/bundles/unity_academy/functions.ts | 663 ++++++++++++------
src/bundles/unity_academy/index.ts | 118 ++--
src/bundles/wasm/index.ts | 5 +-
83 files changed, 2229 insertions(+), 1472 deletions(-)
diff --git a/src/bundles/arcade_2d/audio.ts b/src/bundles/arcade_2d/audio.ts
index 28c22a918..3618edf22 100644
--- a/src/bundles/arcade_2d/audio.ts
+++ b/src/bundles/arcade_2d/audio.ts
@@ -9,7 +9,10 @@
export class AudioClip {
private static audioClipCount: number = 0;
// Stores AudioClip index with the URL as a unique key.
- private static audioClipsIndexMap: Map = new Map();
+ private static audioClipsIndexMap: Map = new Map<
+ string,
+ number
+ >();
// Stores all the created AudioClips
private static audioClipsArray: Array = [];
public readonly id: number;
@@ -18,10 +21,7 @@ export class AudioClip {
private shouldPlay: boolean = false;
private shouldLoop: boolean = false;
- private constructor(
- private url: string,
- private volumeLevel: number
- ) {
+ private constructor(private url: string, private volumeLevel: number) {
this.id = AudioClip.audioClipCount++;
AudioClip.audioClipsIndexMap.set(url, this.id);
AudioClip.audioClipsArray.push(this);
@@ -36,7 +36,9 @@ export class AudioClip {
throw new Error('AudioClip URL cannot be empty');
}
if (AudioClip.audioClipsIndexMap.has(url)) {
- return AudioClip.audioClipsArray[AudioClip.audioClipsIndexMap.get(url) as number];
+ return AudioClip.audioClipsArray[
+ AudioClip.audioClipsIndexMap.get(url) as number
+ ];
}
return new AudioClip(url, volumeLevel);
}
diff --git a/src/bundles/arcade_2d/constants.ts b/src/bundles/arcade_2d/constants.ts
index 636196541..856953c0c 100644
--- a/src/bundles/arcade_2d/constants.ts
+++ b/src/bundles/arcade_2d/constants.ts
@@ -1,6 +1,10 @@
// This file contains the default values of the game canvas and GameObjects.
-import { type InteractableProps, type RenderProps, type TransformProps } from './types';
+import {
+ type InteractableProps,
+ type RenderProps,
+ type TransformProps
+} from './types';
// Default values of game
export const DEFAULT_WIDTH: number = 600;
@@ -43,4 +47,5 @@ export const DEFAULT_INTERACTABLE_PROPS: InteractableProps = {
};
// Default values of Phaser scene
-export const DEFAULT_PATH_PREFIX: string = 'https://source-academy-assets.s3-ap-southeast-1.amazonaws.com/';
+export const DEFAULT_PATH_PREFIX: string =
+ 'https://source-academy-assets.s3-ap-southeast-1.amazonaws.com/';
diff --git a/src/bundles/arcade_2d/functions.ts b/src/bundles/arcade_2d/functions.ts
index 85ac7c094..a76acd0bf 100644
--- a/src/bundles/arcade_2d/functions.ts
+++ b/src/bundles/arcade_2d/functions.ts
@@ -11,52 +11,50 @@
import { AudioClip } from './audio';
import {
- DEFAULT_WIDTH,
+ DEFAULT_DEBUG_STATE,
+ DEFAULT_FPS,
DEFAULT_HEIGHT,
+ DEFAULT_INTERACTABLE_PROPS,
+ DEFAULT_RENDER_PROPS,
DEFAULT_SCALE,
- DEFAULT_FPS,
+ DEFAULT_TRANSFORM_PROPS,
+ DEFAULT_WIDTH,
+ MAX_FPS,
MAX_HEIGHT,
- MIN_HEIGHT,
- MAX_WIDTH,
- MIN_WIDTH,
MAX_SCALE,
- MIN_SCALE,
- MAX_FPS,
- MIN_FPS,
MAX_VOLUME,
+ MAX_WIDTH,
+ MIN_FPS,
+ MIN_HEIGHT,
+ MIN_SCALE,
MIN_VOLUME,
- DEFAULT_DEBUG_STATE,
- DEFAULT_TRANSFORM_PROPS,
- DEFAULT_RENDER_PROPS,
- DEFAULT_INTERACTABLE_PROPS
+ MIN_WIDTH
} from './constants';
import {
+ CircleGameObject,
GameObject,
+ InteractableGameObject,
+ RectangleGameObject,
RenderableGameObject,
- type ShapeGameObject,
SpriteGameObject,
TextGameObject,
- RectangleGameObject,
- CircleGameObject,
- TriangleGameObject, InteractableGameObject
+ TriangleGameObject,
+ type ShapeGameObject
} from './gameobject';
+import { PhaserScene, gameState } from './phaserScene';
import {
- PhaserScene,
- gameState
-} from './phaserScene';
-import {
- type DisplayText,
type BuildGame,
- type Sprite,
- type UpdateFunction,
- type RectangleProps,
type CircleProps,
- type TriangleProps,
+ type ColorRGBA,
+ type DimensionsXY,
+ type DisplayText,
type FlipXY,
- type ScaleXY,
type PositionXY,
- type DimensionsXY,
- type ColorRGBA
+ type RectangleProps,
+ type ScaleXY,
+ type Sprite,
+ type TriangleProps,
+ type UpdateFunction
} from './types';
// =============================================================================
@@ -89,12 +87,20 @@ export const config = {
* ```
* @category GameObject
*/
-export const create_rectangle: (width: number, height: number) => ShapeGameObject = (width: number, height: number) => {
+export const create_rectangle: (
+ width: number,
+ height: number
+) => ShapeGameObject = (width: number, height: number) => {
const rectangle = {
width,
height
} as RectangleProps;
- return new RectangleGameObject(DEFAULT_TRANSFORM_PROPS, DEFAULT_RENDER_PROPS, DEFAULT_INTERACTABLE_PROPS, rectangle);
+ return new RectangleGameObject(
+ DEFAULT_TRANSFORM_PROPS,
+ DEFAULT_RENDER_PROPS,
+ DEFAULT_INTERACTABLE_PROPS,
+ rectangle
+ );
};
/**
@@ -107,11 +113,18 @@ export const create_rectangle: (width: number, height: number) => ShapeGameObjec
* ```
* @category GameObject
*/
-export const create_circle: (radius: number) => ShapeGameObject = (radius: number) => {
+export const create_circle: (radius: number) => ShapeGameObject = (
+ radius: number
+) => {
const circle = {
radius
} as CircleProps;
- return new CircleGameObject(DEFAULT_TRANSFORM_PROPS, DEFAULT_RENDER_PROPS, DEFAULT_INTERACTABLE_PROPS, circle);
+ return new CircleGameObject(
+ DEFAULT_TRANSFORM_PROPS,
+ DEFAULT_RENDER_PROPS,
+ DEFAULT_INTERACTABLE_PROPS,
+ circle
+ );
};
/**
@@ -124,7 +137,10 @@ export const create_circle: (radius: number) => ShapeGameObject = (radius: numbe
* ```
* @category GameObject
*/
-export const create_triangle: (width: number, height: number) => ShapeGameObject = (width: number, height: number) => {
+export const create_triangle: (
+ width: number,
+ height: number
+) => ShapeGameObject = (width: number, height: number) => {
const triangle = {
x1: 0,
y1: 0,
@@ -133,7 +149,12 @@ export const create_triangle: (width: number, height: number) => ShapeGameObject
x3: width / 2,
y3: height
} as TriangleProps;
- return new TriangleGameObject(DEFAULT_TRANSFORM_PROPS, DEFAULT_RENDER_PROPS, DEFAULT_INTERACTABLE_PROPS, triangle);
+ return new TriangleGameObject(
+ DEFAULT_TRANSFORM_PROPS,
+ DEFAULT_RENDER_PROPS,
+ DEFAULT_INTERACTABLE_PROPS,
+ triangle
+ );
};
/**
@@ -150,7 +171,12 @@ export const create_text: (text: string) => TextGameObject = (text: string) => {
const displayText = {
text
} as DisplayText;
- return new TextGameObject(DEFAULT_TRANSFORM_PROPS, DEFAULT_RENDER_PROPS, DEFAULT_INTERACTABLE_PROPS, displayText);
+ return new TextGameObject(
+ DEFAULT_TRANSFORM_PROPS,
+ DEFAULT_RENDER_PROPS,
+ DEFAULT_INTERACTABLE_PROPS,
+ displayText
+ );
};
/**
@@ -170,7 +196,9 @@ export const create_text: (text: string) => TextGameObject = (text: string) => {
* ```
* @category GameObject
*/
-export const create_sprite: (image_url: string) => SpriteGameObject = (image_url: string) => {
+export const create_sprite: (image_url: string) => SpriteGameObject = (
+ image_url: string
+) => {
if (image_url === '') {
throw new Error('image_url cannot be empty');
}
@@ -180,7 +208,12 @@ export const create_sprite: (image_url: string) => SpriteGameObject = (image_url
const sprite: Sprite = {
imageUrl: image_url
} as Sprite;
- return new SpriteGameObject(DEFAULT_TRANSFORM_PROPS, DEFAULT_RENDER_PROPS, DEFAULT_INTERACTABLE_PROPS, sprite);
+ return new SpriteGameObject(
+ DEFAULT_TRANSFORM_PROPS,
+ DEFAULT_RENDER_PROPS,
+ DEFAULT_INTERACTABLE_PROPS,
+ sprite
+ );
};
// =============================================================================
@@ -199,8 +232,10 @@ export const create_sprite: (image_url: string) => SpriteGameObject = (image_url
* ```
* @category GameObject
*/
-export const update_position: (gameObject: GameObject, [x, y]: PositionXY) => GameObject
-= (gameObject: GameObject, [x, y]: PositionXY) => {
+export const update_position: (
+ gameObject: GameObject,
+ [x, y]: PositionXY
+) => GameObject = (gameObject: GameObject, [x, y]: PositionXY) => {
if (gameObject instanceof GameObject) {
gameObject.setTransform({
...gameObject.getTransform(),
@@ -223,8 +258,10 @@ export const update_position: (gameObject: GameObject, [x, y]: PositionXY) => Ga
* ```
* @category GameObject
*/
-export const update_scale: (gameObject: GameObject, [x, y]: ScaleXY) => GameObject
-= (gameObject: GameObject, [x, y]: ScaleXY) => {
+export const update_scale: (
+ gameObject: GameObject,
+ [x, y]: ScaleXY
+) => GameObject = (gameObject: GameObject, [x, y]: ScaleXY) => {
if (gameObject instanceof GameObject) {
gameObject.setTransform({
...gameObject.getTransform(),
@@ -247,8 +284,10 @@ export const update_scale: (gameObject: GameObject, [x, y]: ScaleXY) => GameObje
* ```
* @category GameObject
*/
-export const update_rotation: (gameObject: GameObject, radians: number) => GameObject
-= (gameObject: GameObject, radians: number) => {
+export const update_rotation: (
+ gameObject: GameObject,
+ radians: number
+) => GameObject = (gameObject: GameObject, radians: number) => {
if (gameObject instanceof GameObject) {
gameObject.setTransform({
...gameObject.getTransform(),
@@ -272,8 +311,10 @@ export const update_rotation: (gameObject: GameObject, radians: number) => GameO
* ```
* @category GameObject
*/
-export const update_color: (gameObject: GameObject, color: ColorRGBA) => GameObject
-= (gameObject: GameObject, color: ColorRGBA) => {
+export const update_color: (
+ gameObject: GameObject,
+ color: ColorRGBA
+) => GameObject = (gameObject: GameObject, color: ColorRGBA) => {
if (color.length !== 4) {
throw new Error('color must be a 4-element array');
}
@@ -299,8 +340,10 @@ export const update_color: (gameObject: GameObject, color: ColorRGBA) => GameObj
* ```
* @category GameObject
*/
-export const update_flip: (gameObject: GameObject, flip: FlipXY) => GameObject
-= (gameObject: GameObject, flip: FlipXY) => {
+export const update_flip: (
+ gameObject: GameObject,
+ flip: FlipXY
+) => GameObject = (gameObject: GameObject, flip: FlipXY) => {
if (flip.length !== 2) {
throw new Error('flip must be a 2-element array');
}
@@ -327,8 +370,10 @@ export const update_flip: (gameObject: GameObject, flip: FlipXY) => GameObject
* ```
* @category GameObject
*/
-export const update_text: (textGameObject: TextGameObject, text: string) => GameObject
-= (textGameObject: TextGameObject, text: string) => {
+export const update_text: (
+ textGameObject: TextGameObject,
+ text: string
+) => GameObject = (textGameObject: TextGameObject, text: string) => {
if (textGameObject instanceof TextGameObject) {
textGameObject.setText({
text
@@ -348,8 +393,9 @@ export const update_text: (textGameObject: TextGameObject, text: string) => Game
* ```
* @category GameObject
*/
-export const update_to_top: (gameObject: GameObject) => GameObject
-= (gameObject: GameObject) => {
+export const update_to_top: (gameObject: GameObject) => GameObject = (
+ gameObject: GameObject
+) => {
if (gameObject instanceof RenderableGameObject) {
gameObject.setBringToTopFlag();
return gameObject;
@@ -376,7 +422,9 @@ export const update_to_top: (gameObject: GameObject) => GameObject
* ```
* @category GameObject
*/
-export const query_id: (gameObject: GameObject) => number = (gameObject: GameObject) => {
+export const query_id: (gameObject: GameObject) => number = (
+ gameObject: GameObject
+) => {
if (gameObject instanceof GameObject) {
return gameObject.id;
}
@@ -395,8 +443,9 @@ export const query_id: (gameObject: GameObject) => number = (gameObject: GameObj
* ```
* @category GameObject
*/
-export const query_position: (gameObject: GameObject) => PositionXY
-= (gameObject: GameObject) => {
+export const query_position: (gameObject: GameObject) => PositionXY = (
+ gameObject: GameObject
+) => {
if (gameObject instanceof GameObject) {
return [...gameObject.getTransform().position];
}
@@ -415,8 +464,9 @@ export const query_position: (gameObject: GameObject) => PositionXY
* ```
* @category GameObject
*/
-export const query_rotation: (gameObject: GameObject) => number
-= (gameObject: GameObject) => {
+export const query_rotation: (gameObject: GameObject) => number = (
+ gameObject: GameObject
+) => {
if (gameObject instanceof GameObject) {
return gameObject.getTransform().rotation;
}
@@ -435,8 +485,9 @@ export const query_rotation: (gameObject: GameObject) => number
* ```
* @category GameObject
*/
-export const query_scale: (gameObject: GameObject) => ScaleXY
-= (gameObject: GameObject) => {
+export const query_scale: (gameObject: GameObject) => ScaleXY = (
+ gameObject: GameObject
+) => {
if (gameObject instanceof GameObject) {
return [...gameObject.getTransform().scale];
}
@@ -455,8 +506,9 @@ export const query_scale: (gameObject: GameObject) => ScaleXY
* ```
* @category GameObject
*/
-export const query_color: (gameObject: RenderableGameObject) => ColorRGBA
-= (gameObject: RenderableGameObject) => {
+export const query_color: (gameObject: RenderableGameObject) => ColorRGBA = (
+ gameObject: RenderableGameObject
+) => {
if (gameObject instanceof RenderableGameObject) {
return [...gameObject.getColor()];
}
@@ -475,8 +527,9 @@ export const query_color: (gameObject: RenderableGameObject) => ColorRGBA
* ```
* @category GameObject
*/
-export const query_flip: (gameObject: RenderableGameObject) => FlipXY
-= (gameObject: RenderableGameObject) => {
+export const query_flip: (gameObject: RenderableGameObject) => FlipXY = (
+ gameObject: RenderableGameObject
+) => {
if (gameObject instanceof RenderableGameObject) {
return [...gameObject.getFlipState()];
}
@@ -496,8 +549,9 @@ export const query_flip: (gameObject: RenderableGameObject) => FlipXY
* ```
* @category GameObject
*/
-export const query_text: (textGameObject: TextGameObject) => string
-= (textGameObject: TextGameObject) => {
+export const query_text: (textGameObject: TextGameObject) => string = (
+ textGameObject: TextGameObject
+) => {
if (textGameObject instanceof TextGameObject) {
return textGameObject.getText().text;
}
@@ -515,8 +569,8 @@ export const query_text: (textGameObject: TextGameObject) => string
* position[1]; // y
* ```
*/
-export const query_pointer_position: () => PositionXY
-= () => gameState.pointerProps.pointerPosition;
+export const query_pointer_position: () => PositionXY = () =>
+ gameState.pointerProps.pointerPosition;
// =============================================================================
// Game configuration
@@ -531,8 +585,11 @@ export const query_pointer_position: () => PositionXY
* @returns a number within the interval
* @hidden
*/
-const withinRange: (num: number, min: number, max: number) => number
-= (num: number, min: number, max: number) => {
+const withinRange: (num: number, min: number, max: number) => number = (
+ num: number,
+ min: number,
+ max: number
+) => {
if (num > max) {
return max;
}
@@ -569,7 +626,9 @@ export const set_fps: (fps: number) => void = (fps: number) => {
* set_dimensions([500, 400]);
* ```
*/
-export const set_dimensions: (dimensions: DimensionsXY) => void = (dimensions: DimensionsXY) => {
+export const set_dimensions: (dimensions: DimensionsXY) => void = (
+ dimensions: DimensionsXY
+) => {
if (dimensions.length !== 2) {
throw new Error('dimensions must be a 2-element array');
}
@@ -651,7 +710,9 @@ export const debug_log: (info: string) => void = (info: string) => {
* ```
* @category Logic
*/
-export const input_key_down: (key_name: string) => boolean = (key_name: string) => gameState.inputKeysDown.has(key_name);
+export const input_key_down: (key_name: string) => boolean = (
+ key_name: string
+) => gameState.inputKeysDown.has(key_name);
/**
* Detects if the left mouse button is pressed down.
@@ -666,7 +727,8 @@ export const input_key_down: (key_name: string) => boolean = (key_name: string)
* ```
* @category Logic
*/
-export const input_left_mouse_down: () => boolean = () => gameState.pointerProps.isPointerPrimaryDown;
+export const input_left_mouse_down: () => boolean = () =>
+ gameState.pointerProps.isPointerPrimaryDown;
/**
* Detects if the right mouse button is pressed down.
@@ -681,7 +743,8 @@ export const input_left_mouse_down: () => boolean = () => gameState.pointerProps
* ```
* @category Logic
*/
-export const input_right_mouse_down: () => boolean = () => gameState.pointerProps.isPointerSecondaryDown;
+export const input_right_mouse_down: () => boolean = () =>
+ gameState.pointerProps.isPointerSecondaryDown;
/**
* Detects if the (mouse) pointer is over the gameobject.
@@ -724,9 +787,17 @@ export const pointer_over_gameobject = (gameObject: GameObject) => {
* ```
* @category Logic
*/
-export const gameobjects_overlap: (gameObject1: InteractableGameObject, gameObject2: InteractableGameObject) => boolean
-= (gameObject1: InteractableGameObject, gameObject2: InteractableGameObject) => {
- if (gameObject1 instanceof InteractableGameObject && gameObject2 instanceof InteractableGameObject) {
+export const gameobjects_overlap: (
+ gameObject1: InteractableGameObject,
+ gameObject2: InteractableGameObject
+) => boolean = (
+ gameObject1: InteractableGameObject,
+ gameObject2: InteractableGameObject
+) => {
+ if (
+ gameObject1 instanceof InteractableGameObject &&
+ gameObject2 instanceof InteractableGameObject
+ ) {
return gameObject1.isOverlapping(gameObject2);
}
throw new TypeError('Cannot check overlap of non-GameObject');
@@ -783,7 +854,9 @@ export const get_loop_count: () => number = () => gameState.loopCount;
* })
* ```
*/
-export const update_loop: (update_function: UpdateFunction) => void = (update_function: UpdateFunction) => {
+export const update_loop: (update_function: UpdateFunction) => void = (
+ update_function: UpdateFunction
+) => {
// Test for error in user update function
// This cannot not check for errors inside a block that is not run.
update_function([]);
@@ -861,15 +934,20 @@ export const build_game: () => BuildGame = () => {
* ```
* @category Audio
*/
-export const create_audio: (audio_url: string, volume_level: number) => AudioClip
-= (audio_url: string, volume_level: number) => {
+export const create_audio: (
+ audio_url: string,
+ volume_level: number
+) => AudioClip = (audio_url: string, volume_level: number) => {
if (typeof audio_url !== 'string') {
throw new Error('audio_url must be a string');
}
if (typeof volume_level !== 'number') {
throw new Error('volume_level must be a number');
}
- return AudioClip.of(audio_url, withinRange(volume_level, MIN_VOLUME, MAX_VOLUME));
+ return AudioClip.of(
+ audio_url,
+ withinRange(volume_level, MIN_VOLUME, MAX_VOLUME)
+ );
};
/**
@@ -884,7 +962,9 @@ export const create_audio: (audio_url: string, volume_level: number) => AudioCli
* ```
* @category Audio
*/
-export const loop_audio: (audio_clip: AudioClip) => AudioClip = (audio_clip: AudioClip) => {
+export const loop_audio: (audio_clip: AudioClip) => AudioClip = (
+ audio_clip: AudioClip
+) => {
if (audio_clip instanceof AudioClip) {
audio_clip.setShouldAudioClipLoop(true);
return audio_clip;
@@ -903,7 +983,9 @@ export const loop_audio: (audio_clip: AudioClip) => AudioClip = (audio_clip: Aud
* ```
* @category Audio
*/
-export const play_audio: (audio_clip: AudioClip) => AudioClip = (audio_clip: AudioClip) => {
+export const play_audio: (audio_clip: AudioClip) => AudioClip = (
+ audio_clip: AudioClip
+) => {
if (audio_clip instanceof AudioClip) {
audio_clip.setShouldAudioClipPlay(true);
return audio_clip;
@@ -922,7 +1004,9 @@ export const play_audio: (audio_clip: AudioClip) => AudioClip = (audio_clip: Aud
* ```
* @category Audio
*/
-export const stop_audio: (audio_clip: AudioClip) => AudioClip = (audio_clip: AudioClip) => {
+export const stop_audio: (audio_clip: AudioClip) => AudioClip = (
+ audio_clip: AudioClip
+) => {
if (audio_clip instanceof AudioClip) {
audio_clip.setShouldAudioClipPlay(false);
return audio_clip;
diff --git a/src/bundles/arcade_2d/gameobject.ts b/src/bundles/arcade_2d/gameobject.ts
index 8927d66fb..bad6eb7ff 100644
--- a/src/bundles/arcade_2d/gameobject.ts
+++ b/src/bundles/arcade_2d/gameobject.ts
@@ -2,7 +2,11 @@
* This file contains the bundle's representation of GameObjects.
*/
import type { ReplResult } from '../../typings/type_helpers';
-import { DEFAULT_INTERACTABLE_PROPS, DEFAULT_RENDER_PROPS, DEFAULT_TRANSFORM_PROPS } from './constants';
+import {
+ DEFAULT_INTERACTABLE_PROPS,
+ DEFAULT_RENDER_PROPS,
+ DEFAULT_TRANSFORM_PROPS
+} from './constants';
import type * as types from './types';
// =============================================================================
@@ -51,7 +55,9 @@ export abstract class GameObject implements Transformable, ReplResult {
/**
* Encapsulates the basic data-representation of a RenderableGameObject.
*/
-export abstract class RenderableGameObject extends GameObject implements Renderable {
+export abstract class RenderableGameObject
+ extends GameObject
+ implements Renderable {
protected isRenderUpdated: boolean = false;
private shouldBringToTop: boolean = false;
@@ -103,7 +109,9 @@ export abstract class RenderableGameObject extends GameObject implements Rendera
/**
* Encapsulates the basic data-representation of a InteractableGameObject.
*/
-export abstract class InteractableGameObject extends RenderableGameObject implements Interactable {
+export abstract class InteractableGameObject
+ extends RenderableGameObject
+ implements Interactable {
protected isHitboxUpdated: boolean = false;
protected phaserGameObject: types.PhaserGameObject | undefined;
@@ -132,7 +140,12 @@ export abstract class InteractableGameObject extends RenderableGameObject implem
* This stores the GameObject within the phaser game, which can only be set after the game has started.
* @param phaserGameObject The phaser GameObject reference.
*/
- setPhaserGameObject(phaserGameObject: Phaser.GameObjects.Shape | Phaser.GameObjects.Sprite | Phaser.GameObjects.Text) {
+ setPhaserGameObject(
+ phaserGameObject:
+ | Phaser.GameObjects.Shape
+ | Phaser.GameObjects.Sprite
+ | Phaser.GameObjects.Text
+ ) {
this.phaserGameObject = phaserGameObject;
}
/**
@@ -142,13 +155,19 @@ export abstract class InteractableGameObject extends RenderableGameObject implem
* @returns True, if both GameObjects overlap in the phaser game.
*/
isOverlapping(other: InteractableGameObject): boolean {
- if (this.phaserGameObject === undefined || other.phaserGameObject === undefined) {
+ if (
+ this.phaserGameObject === undefined ||
+ other.phaserGameObject === undefined
+ ) {
return false;
}
// Use getBounds to check if two objects overlap, checking the shape of the area before checking overlap.
// Since getBounds() returns a Rectangle, it will be unable to check the actual intersection of non-rectangular shapes.
// eslint-disable-next-line new-cap
- return Phaser.Geom.Intersects.RectangleToRectangle(this.phaserGameObject.getBounds(), other.phaserGameObject.getBounds());
+ return Phaser.Geom.Intersects.RectangleToRectangle(
+ this.phaserGameObject.getBounds(),
+ other.phaserGameObject.getBounds()
+ );
}
}
diff --git a/src/bundles/arcade_2d/index.ts b/src/bundles/arcade_2d/index.ts
index 894131aad..f5985c2e9 100644
--- a/src/bundles/arcade_2d/index.ts
+++ b/src/bundles/arcade_2d/index.ts
@@ -218,11 +218,24 @@ build_game();
*/
export {
+ build_game,
+ create_audio,
create_circle,
create_rectangle,
- create_triangle,
create_sprite,
create_text,
+ create_triangle,
+ debug_log,
+ enable_debug,
+ gameobjects_overlap,
+ get_game_time,
+ get_loop_count,
+ input_key_down,
+ input_left_mouse_down,
+ input_right_mouse_down,
+ loop_audio,
+ play_audio,
+ pointer_over_gameobject,
query_color,
query_flip,
query_id,
@@ -231,29 +244,16 @@ export {
query_rotation,
query_scale,
query_text,
+ set_dimensions,
+ set_fps,
+ set_scale,
+ stop_audio,
update_color,
update_flip,
+ update_loop,
update_position,
update_rotation,
update_scale,
update_text,
- update_to_top,
- set_fps,
- set_dimensions,
- set_scale,
- get_game_time,
- get_loop_count,
- enable_debug,
- debug_log,
- input_key_down,
- input_left_mouse_down,
- input_right_mouse_down,
- pointer_over_gameobject,
- gameobjects_overlap,
- update_loop,
- build_game,
- create_audio,
- loop_audio,
- stop_audio,
- play_audio
+ update_to_top
} from './functions';
diff --git a/src/bundles/arcade_2d/phaserScene.ts b/src/bundles/arcade_2d/phaserScene.ts
index 5e52cbd24..8a59019c6 100644
--- a/src/bundles/arcade_2d/phaserScene.ts
+++ b/src/bundles/arcade_2d/phaserScene.ts
@@ -1,24 +1,22 @@
import Phaser from 'phaser';
import { AudioClip } from './audio';
import { DEFAULT_PATH_PREFIX } from './constants';
-import {
- config
-} from './functions';
+import { config } from './functions';
import {
CircleGameObject,
GameObject,
- type InteractableGameObject,
RectangleGameObject,
ShapeGameObject,
SpriteGameObject,
TextGameObject,
- TriangleGameObject
+ TriangleGameObject,
+ type InteractableGameObject
} from './gameobject';
import {
- type TransformProps,
- type PositionXY,
type ExceptionError,
- type PhaserGameObject
+ type PhaserGameObject,
+ type PositionXY,
+ type TransformProps
} from './types';
// Game state information, that changes every frame.
@@ -53,7 +51,8 @@ export class PhaserScene extends Phaser.Scene {
constructor() {
super('PhaserScene');
}
- private sourceGameObjects: Array = GameObject.getGameObjectsArray();
+ private sourceGameObjects: Array =
+ GameObject.getGameObjectsArray();
private phaserGameObjects: Array = [];
private corsAssetsUrl: Set = new Set();
private sourceAudioClips: Array = AudioClip.getAudioClipsArray();
@@ -68,19 +67,19 @@ export class PhaserScene extends Phaser.Scene {
init() {
gameState.debugLogArray.length = 0;
// Disable context menu within the canvas
- this.game.canvas.oncontextmenu = (e) => e.preventDefault();
+ this.game.canvas.oncontextmenu = e => e.preventDefault();
}
preload() {
// Set the default path prefix
this.load.setPath(DEFAULT_PATH_PREFIX);
- this.sourceGameObjects.forEach((gameObject) => {
+ this.sourceGameObjects.forEach(gameObject => {
if (gameObject instanceof SpriteGameObject) {
this.corsAssetsUrl.add(gameObject.getSprite().imageUrl);
}
});
// Preload sprites (through Cross-Origin resource sharing (CORS))
- this.corsAssetsUrl.forEach((url) => {
+ this.corsAssetsUrl.forEach(url => {
this.load.image(url, url);
});
// Preload audio
@@ -104,15 +103,22 @@ export class PhaserScene extends Phaser.Scene {
gameState.inputKeysDown.add(event.key);
});
this.input.keyboard.on('keyup', (event: KeyboardEvent) => {
- this.delayedKeyUpEvents.add(() => gameState.inputKeysDown.delete(event.key));
+ this.delayedKeyUpEvents.add(() =>
+ gameState.inputKeysDown.delete(event.key)
+ );
});
// Handle debug info
if (!config.isDebugEnabled && !this.hasRuntimeError) {
gameState.debugLogArray.length = 0;
}
- this.debugLogText = this.add.text(0, 0, gameState.debugLogArray)
- .setWordWrapWidth(config.scale < 1 ? this.renderer.width * config.scale : this.renderer.width)
+ this.debugLogText = this.add
+ .text(0, 0, gameState.debugLogArray)
+ .setWordWrapWidth(
+ config.scale < 1
+ ? this.renderer.width * config.scale
+ : this.renderer.width
+ )
.setBackgroundColor('black')
.setAlpha(0.8)
.setScale(config.scale < 1 ? 1 / config.scale : 1);
@@ -126,7 +132,10 @@ export class PhaserScene extends Phaser.Scene {
// Set the pointer properties
gameState.pointerProps = {
...gameState.pointerProps,
- pointerPosition: [Math.trunc(this.input.activePointer.x), Math.trunc(this.input.activePointer.y)],
+ pointerPosition: [
+ Math.trunc(this.input.activePointer.x),
+ Math.trunc(this.input.activePointer.y)
+ ],
isPointerPrimaryDown: this.input.activePointer.primaryDown,
isPointerSecondaryDown: this.input.activePointer.rightButtonDown()
};
@@ -158,16 +167,18 @@ export class PhaserScene extends Phaser.Scene {
}
private createPhaserGameObjects() {
- this.sourceGameObjects.forEach((gameObject) => {
+ this.sourceGameObjects.forEach(gameObject => {
const transformProps = gameObject.getTransform();
// Create TextGameObject
if (gameObject instanceof TextGameObject) {
const text = gameObject.getText().text;
- this.phaserGameObjects.push(this.add.text(
- transformProps.position[0],
- transformProps.position[1],
- text
- ));
+ this.phaserGameObjects.push(
+ this.add.text(
+ transformProps.position[0],
+ transformProps.position[1],
+ text
+ )
+ );
this.phaserGameObjects[gameObject.id].setOrigin(0.5, 0.5);
if (gameObject.getHitboxState().isHitboxActive) {
this.phaserGameObjects[gameObject.id].setInteractive();
@@ -176,11 +187,13 @@ export class PhaserScene extends Phaser.Scene {
// Create SpriteGameObject
if (gameObject instanceof SpriteGameObject) {
const url = gameObject.getSprite().imageUrl;
- this.phaserGameObjects.push(this.add.sprite(
- transformProps.position[0],
- transformProps.position[1],
- url
- ));
+ this.phaserGameObjects.push(
+ this.add.sprite(
+ transformProps.position[0],
+ transformProps.position[1],
+ url
+ )
+ );
if (gameObject.getHitboxState().isHitboxActive) {
this.phaserGameObjects[gameObject.id].setInteractive();
}
@@ -189,45 +202,48 @@ export class PhaserScene extends Phaser.Scene {
if (gameObject instanceof ShapeGameObject) {
if (gameObject instanceof RectangleGameObject) {
const shape = gameObject.getShape();
- this.phaserGameObjects.push(this.add.rectangle(
- transformProps.position[0],
- transformProps.position[1],
- shape.width,
- shape.height
- ));
+ this.phaserGameObjects.push(
+ this.add.rectangle(
+ transformProps.position[0],
+ transformProps.position[1],
+ shape.width,
+ shape.height
+ )
+ );
if (gameObject.getHitboxState().isHitboxActive) {
this.phaserGameObjects[gameObject.id].setInteractive();
}
}
if (gameObject instanceof CircleGameObject) {
const shape = gameObject.getShape();
- this.phaserGameObjects.push(this.add.circle(
- transformProps.position[0],
- transformProps.position[1],
- shape.radius
- ));
+ this.phaserGameObjects.push(
+ this.add.circle(
+ transformProps.position[0],
+ transformProps.position[1],
+ shape.radius
+ )
+ );
if (gameObject.getHitboxState().isHitboxActive) {
this.phaserGameObjects[gameObject.id].setInteractive(
- new Phaser.Geom.Circle(
- shape.radius,
- shape.radius,
- shape.radius
- ), Phaser.Geom.Circle.Contains
+ new Phaser.Geom.Circle(shape.radius, shape.radius, shape.radius),
+ Phaser.Geom.Circle.Contains
);
}
}
if (gameObject instanceof TriangleGameObject) {
const shape = gameObject.getShape();
- this.phaserGameObjects.push(this.add.triangle(
- transformProps.position[0],
- transformProps.position[1],
- shape.x1,
- shape.y1,
- shape.x2,
- shape.y2,
- shape.x3,
- shape.y3
- ));
+ this.phaserGameObjects.push(
+ this.add.triangle(
+ transformProps.position[0],
+ transformProps.position[1],
+ shape.x1,
+ shape.y1,
+ shape.x2,
+ shape.y2,
+ shape.x3,
+ shape.y3
+ )
+ );
if (gameObject.getHitboxState().isHitboxActive) {
this.phaserGameObjects[gameObject.id].setInteractive(
new Phaser.Geom.Triangle(
@@ -237,7 +253,8 @@ export class PhaserScene extends Phaser.Scene {
shape.y2,
shape.x3,
shape.y3
- ), Phaser.Geom.Triangle.Contains
+ ),
+ Phaser.Geom.Triangle.Contains
);
}
}
@@ -265,10 +282,12 @@ export class PhaserScene extends Phaser.Scene {
private createAudioClips() {
try {
this.sourceAudioClips.forEach((audioClip: AudioClip) => {
- this.phaserAudioClips.push(this.sound.add(audioClip.getUrl(), {
- loop: audioClip.shouldAudioClipLoop(),
- volume: audioClip.getVolumeLevel()
- }));
+ this.phaserAudioClips.push(
+ this.sound.add(audioClip.getUrl(), {
+ loop: audioClip.shouldAudioClipLoop(),
+ volume: audioClip.getVolumeLevel()
+ })
+ );
});
} catch (error) {
this.hasRuntimeError = true;
@@ -303,17 +322,26 @@ export class PhaserScene extends Phaser.Scene {
/** Loop through each GameObject in the array and determine which needs to update. */
private handleGameObjectUpdates() {
this.sourceGameObjects.forEach((gameObject: InteractableGameObject) => {
- const phaserGameObject = this.phaserGameObjects[gameObject.id] as PhaserGameObject;
+ const phaserGameObject = this.phaserGameObjects[
+ gameObject.id
+ ] as PhaserGameObject;
if (phaserGameObject) {
// Update the transform of Phaser GameObject
- if (gameObject.hasTransformUpdates() || this.shouldRerenderGameObjects) {
+ if (
+ gameObject.hasTransformUpdates() ||
+ this.shouldRerenderGameObjects
+ ) {
const transformProps = gameObject.getTransform() as TransformProps;
- phaserGameObject.setPosition(transformProps.position[0], transformProps.position[1])
+ phaserGameObject
+ .setPosition(transformProps.position[0], transformProps.position[1])
.setRotation(transformProps.rotation)
.setScale(transformProps.scale[0], transformProps.scale[1]);
if (gameObject instanceof TriangleGameObject) {
// The only shape that requires flipping is the triangle, as the rest are symmetric about their origin.
- phaserGameObject.setRotation(transformProps.rotation + (gameObject.getFlipState()[1] ? Math.PI : 0));
+ phaserGameObject.setRotation(
+ transformProps.rotation +
+ (gameObject.getFlipState()[1] ? Math.PI : 0)
+ );
}
gameObject.setTransformUpdated();
}
@@ -322,22 +350,32 @@ export class PhaserScene extends Phaser.Scene {
if (gameObject.hasRenderUpdates() || this.shouldRerenderGameObjects) {
const color = gameObject.getColor();
// eslint-disable-next-line new-cap
- const intColor = Phaser.Display.Color.GetColor32(color[0], color[1], color[2], color[3]);
+ const intColor = Phaser.Display.Color.GetColor32(
+ color[0],
+ color[1],
+ color[2],
+ color[3]
+ );
const flip = gameObject.getFlipState();
if (gameObject instanceof TextGameObject) {
- (phaserGameObject as Phaser.GameObjects.Text).setTint(intColor)
+ (phaserGameObject as Phaser.GameObjects.Text)
+ .setTint(intColor)
.setAlpha(color[3] / 255)
.setFlip(flip[0], flip[1])
.setText(gameObject.getText().text);
} else if (gameObject instanceof SpriteGameObject) {
- (phaserGameObject as Phaser.GameObjects.Sprite).setTint(intColor)
+ (phaserGameObject as Phaser.GameObjects.Sprite)
+ .setTint(intColor)
.setAlpha(color[3] / 255)
.setFlip(flip[0], flip[1]);
} else if (gameObject instanceof ShapeGameObject) {
- (phaserGameObject as Phaser.GameObjects.Shape).setFillStyle(intColor, color[3] / 255)
- // Phaser.GameObjects.Shape does not have setFlip, so flipping is done with rotations.
- // The only shape that requires flipping is the triangle, as the rest are symmetric about their origin.
- .setRotation(gameObject.getTransform().rotation + (flip[1] ? Math.PI : 0));
+ (phaserGameObject as Phaser.GameObjects.Shape)
+ .setFillStyle(intColor, color[3] / 255)
+ // Phaser.GameObjects.Shape does not have setFlip, so flipping is done with rotations.
+ // The only shape that requires flipping is the triangle, as the rest are symmetric about their origin.
+ .setRotation(
+ gameObject.getTransform().rotation + (flip[1] ? Math.PI : 0)
+ );
}
// Update the z-index (rendering order), to the top.
if (gameObject.getShouldBringToTop()) {
@@ -347,7 +385,9 @@ export class PhaserScene extends Phaser.Scene {
}
} else {
this.hasRuntimeError = true;
- gameState.debugLogArray.push('RuntimeError: GameObject error in update_loop');
+ gameState.debugLogArray.push(
+ 'RuntimeError: GameObject error in update_loop'
+ );
}
});
}
@@ -355,7 +395,9 @@ export class PhaserScene extends Phaser.Scene {
private handleAudioUpdates() {
this.sourceAudioClips.forEach((audioClip: AudioClip) => {
if (audioClip.hasAudioClipUpdates()) {
- const phaserAudioClip = this.phaserAudioClips[audioClip.id] as Phaser.Sound.BaseSound;
+ const phaserAudioClip = this.phaserAudioClips[
+ audioClip.id
+ ] as Phaser.Sound.BaseSound;
if (phaserAudioClip) {
if (audioClip.shouldAudioClipPlay()) {
phaserAudioClip.play();
@@ -364,7 +406,9 @@ export class PhaserScene extends Phaser.Scene {
}
} else {
this.hasRuntimeError = true;
- gameState.debugLogArray.push('RuntimeError: Audio error in update_loop');
+ gameState.debugLogArray.push(
+ 'RuntimeError: Audio error in update_loop'
+ );
}
}
});
diff --git a/src/bundles/arcade_2d/types.ts b/src/bundles/arcade_2d/types.ts
index 875801d93..2928c2da0 100644
--- a/src/bundles/arcade_2d/types.ts
+++ b/src/bundles/arcade_2d/types.ts
@@ -125,4 +125,7 @@ export type ExceptionError = {
/**
* Represents the Phaser Game Object types that are used.
*/
-export type PhaserGameObject = Phaser.GameObjects.Shape | Phaser.GameObjects.Sprite | Phaser.GameObjects.Text;
+export type PhaserGameObject =
+ | Phaser.GameObjects.Shape
+ | Phaser.GameObjects.Sprite
+ | Phaser.GameObjects.Text;
diff --git a/src/bundles/binary_tree/functions.ts b/src/bundles/binary_tree/functions.ts
index b2d53b977..b86278925 100644
--- a/src/bundles/binary_tree/functions.ts
+++ b/src/bundles/binary_tree/functions.ts
@@ -44,18 +44,18 @@ export function make_tree(
* @param v Value to be tested
* @returns bool
*/
-export function is_tree(
- value: any
-): boolean {
- return value === null
- || (Array.isArray(value)
- && value.length === 2
- && Array.isArray(value[1])
- && value[1].length === 2
- && is_tree(value[1][0])
- && value[1][1].length === 2
- && is_tree(value[1][1][0])
- && value[1][1][1] === null);
+export function is_tree(value: any): boolean {
+ return (
+ value === null ||
+ (Array.isArray(value) &&
+ value.length === 2 &&
+ Array.isArray(value[1]) &&
+ value[1].length === 2 &&
+ is_tree(value[1][0]) &&
+ value[1][1].length === 2 &&
+ is_tree(value[1][1][0]) &&
+ value[1][1][1] === null)
+ );
}
/**
@@ -69,9 +69,7 @@ export function is_tree(
* @param v Value to be tested
* @returns bool
*/
-export function is_empty_tree(
- value: any
-): boolean {
+export function is_empty_tree(value: any): boolean {
return value === null;
}
@@ -85,15 +83,11 @@ export function is_empty_tree(
* @param t BinaryTree to be accessed
* @returns Value
*/
-export function entry(
- t: BinaryTree
-): boolean {
+export function entry(t: BinaryTree): boolean {
if (Array.isArray(t) && t.length === 2) {
return t[0];
}
- throw new Error(
- `function entry expects binary tree, received: ${t}`
- );
+ throw new Error(`function entry expects binary tree, received: ${t}`);
}
/**
@@ -106,16 +100,16 @@ export function entry(
* @param t BinaryTree to be accessed
* @returns BinaryTree
*/
-export function left_branch(
- t: BinaryTree
-): BinaryTree {
- if (Array.isArray(t) && t.length === 2
- && Array.isArray(t[1]) && t[1].length === 2) {
+export function left_branch(t: BinaryTree): BinaryTree {
+ if (
+ Array.isArray(t) &&
+ t.length === 2 &&
+ Array.isArray(t[1]) &&
+ t[1].length === 2
+ ) {
return t[1][0];
}
- throw new Error(
- `function left_branch expects binary tree, received: ${t}`
- );
+ throw new Error(`function left_branch expects binary tree, received: ${t}`);
}
/**
@@ -128,15 +122,16 @@ export function left_branch(
* @param t BinaryTree to be accessed
* @returns BinaryTree
*/
-export function right_branch(
- t: BinaryTree
-): BinaryTree {
- if (Array.isArray(t) && t.length === 2
- && Array.isArray(t[1]) && t[1].length === 2
- && Array.isArray(t[1][1]) && t[1][1].length === 2) {
+export function right_branch(t: BinaryTree): BinaryTree {
+ if (
+ Array.isArray(t) &&
+ t.length === 2 &&
+ Array.isArray(t[1]) &&
+ t[1].length === 2 &&
+ Array.isArray(t[1][1]) &&
+ t[1][1].length === 2
+ ) {
return t[1][1][0];
}
- throw new Error(
- `function right_branch expects binary tree, received: ${t}`
- );
+ throw new Error(`function right_branch expects binary tree, received: ${t}`);
}
diff --git a/src/bundles/binary_tree/index.ts b/src/bundles/binary_tree/index.ts
index 88c102ebe..b19399410 100644
--- a/src/bundles/binary_tree/index.ts
+++ b/src/bundles/binary_tree/index.ts
@@ -9,6 +9,11 @@
* @author Loh Xian Ze, Bryan
*/
export {
- entry, is_empty_tree, is_tree, left_branch,
- make_empty_tree, make_tree, right_branch
+ entry,
+ is_empty_tree,
+ is_tree,
+ left_branch,
+ make_empty_tree,
+ make_tree,
+ right_branch
} from './functions';
diff --git a/src/bundles/communication/Communications.ts b/src/bundles/communication/Communications.ts
index 6a960b2b5..f584ad855 100644
--- a/src/bundles/communication/Communications.ts
+++ b/src/bundles/communication/Communications.ts
@@ -28,7 +28,7 @@ export function initCommunications(
address: string,
port: number,
user: string,
- password: string,
+ password: string
) {
if (getModuleState() instanceof CommunicationModuleState) {
return;
@@ -37,7 +37,7 @@ export function initCommunications(
address,
port,
user,
- password,
+ password
);
context.moduleContexts.communication.state = newModuleState;
}
@@ -77,7 +77,7 @@ export function stopRunning() {
*/
export function initGlobalState(
topicHeader: string,
- callback: (state: any) => void,
+ callback: (state: any) => void
) {
const moduleState = getModuleState();
if (moduleState instanceof CommunicationModuleState) {
@@ -87,7 +87,7 @@ export function initGlobalState(
moduleState.globalState = new GlobalStateController(
topicHeader,
moduleState.multiUser,
- callback,
+ callback
);
return;
}
@@ -137,7 +137,7 @@ export function initRpc(topicHeader: string, userId?: string) {
moduleState.rpc = new RpcController(
topicHeader,
moduleState.multiUser,
- userId,
+ userId
);
return;
}
@@ -189,7 +189,7 @@ export function callFunction(
receiver: string,
name: string,
args: any[],
- callback: (args: any[]) => void,
+ callback: (args: any[]) => void
) {
const moduleState = getModuleState();
if (moduleState instanceof CommunicationModuleState) {
diff --git a/src/bundles/communication/GlobalStateController.ts b/src/bundles/communication/GlobalStateController.ts
index 03c86b1fb..571fb5d12 100644
--- a/src/bundles/communication/GlobalStateController.ts
+++ b/src/bundles/communication/GlobalStateController.ts
@@ -17,7 +17,7 @@ export class GlobalStateController {
constructor(
topicHeader: string,
multiUser: MultiUserController,
- callback: (state: any) => void,
+ callback: (state: any) => void
) {
this.topicHeader = topicHeader;
this.multiUser = multiUser;
@@ -34,7 +34,7 @@ export class GlobalStateController {
this.multiUser.addMessageCallback(this.topicHeader, (topic, message) => {
const shortenedTopic = topic.substring(
this.topicHeader.length,
- topic.length,
+ topic.length
);
this.parseGlobalStateMessage(shortenedTopic, message);
});
@@ -119,7 +119,7 @@ export class GlobalStateController {
this.multiUser.controller?.publish(
topic,
JSON.stringify(updatedState),
- false,
+ false
);
}
}
diff --git a/src/bundles/communication/MqttController.ts b/src/bundles/communication/MqttController.ts
index 6414b5db0..ff557ec83 100644
--- a/src/bundles/communication/MqttController.ts
+++ b/src/bundles/communication/MqttController.ts
@@ -26,7 +26,7 @@ export class MqttController {
constructor(
connectionCallback: (status: string) => void,
- messageCallback: (topic: string, message: string) => void,
+ messageCallback: (topic: string, message: string) => void
) {
this.connectionCallback = connectionCallback;
this.messageCallback = messageCallback;
@@ -85,11 +85,11 @@ export class MqttController {
topic: string,
message: string,
isRetain: boolean,
- qos: number = 1,
+ qos: number = 1
) {
this.client?.publish(topic, message, {
qos: qos,
- retain: isRetain,
+ retain: isRetain
});
}
diff --git a/src/bundles/communication/MultiUserController.ts b/src/bundles/communication/MultiUserController.ts
index 1d29f06a1..210092259 100644
--- a/src/bundles/communication/MultiUserController.ts
+++ b/src/bundles/communication/MultiUserController.ts
@@ -24,7 +24,7 @@ export class MultiUserController {
address: string,
port: number,
user: string,
- password: string,
+ password: string
) {
let currentController = this.controller;
if (currentController) {
@@ -38,7 +38,7 @@ export class MultiUserController {
},
(topic: string, message: string) => {
this.handleIncomingMessage(topic, message);
- },
+ }
);
this.controller = currentController;
}
@@ -75,7 +75,7 @@ export class MultiUserController {
*/
public addMessageCallback(
identifier: string,
- callback: (topic: string, message: string) => void,
+ callback: (topic: string, message: string) => void
) {
this.controller?.subscribe(`${identifier}/#`);
this.messageCallbacks.set(identifier, callback);
diff --git a/src/bundles/communication/RpcController.ts b/src/bundles/communication/RpcController.ts
index 673b0e845..e9e284c59 100644
--- a/src/bundles/communication/RpcController.ts
+++ b/src/bundles/communication/RpcController.ts
@@ -24,7 +24,7 @@ export class RpcController {
constructor(
topicHeader: string,
multiUser: MultiUserController,
- userId?: string,
+ userId?: string
) {
this.topicHeader = topicHeader;
this.multiUser = multiUser;
@@ -51,7 +51,7 @@ export class RpcController {
private returnResponse(sender: string, callId: string, result: any) {
const message = {
callId,
- result,
+ result
};
const topic = `${this.topicHeader}_return/${sender}`;
this.multiUser.controller?.publish(topic, JSON.stringify(message), false);
@@ -75,7 +75,7 @@ export class RpcController {
public expose(name: string, func: (...args: any[]) => any) {
const item = {
name,
- func,
+ func
};
this.functions.set(name, item);
const functionTopic = `${this.topicHeader}/${this.userId}/${name}`;
@@ -115,7 +115,7 @@ export class RpcController {
receiver: string,
name: string,
args: any[],
- callback: (args: any[]) => void,
+ callback: (args: any[]) => void
) {
const topic = `${this.topicHeader}/${receiver}/${name}`;
const callId = uniqid();
@@ -123,7 +123,7 @@ export class RpcController {
const messageJson = {
sender: this.userId,
callId,
- args,
+ args
};
const messageString = JSON.stringify(messageJson);
this.multiUser.controller?.publish(topic, messageString, false);
diff --git a/src/bundles/communication/__tests__/index.ts b/src/bundles/communication/__tests__/index.ts
index ff8b8cdb7..5edbff76e 100644
--- a/src/bundles/communication/__tests__/index.ts
+++ b/src/bundles/communication/__tests__/index.ts
@@ -6,7 +6,7 @@ multiUser.setupController('broker.hivemq.com', 8884, '', '');
const globalStateController = new GlobalStateController(
'test',
multiUser,
- (_) => {},
+ _ => {}
);
// Empty Root - Replace root.
@@ -15,18 +15,18 @@ test('Empty Root Set Null', () => {
globalStateController.globalState = undefined;
globalStateController.parseGlobalStateMessage('', JSON.stringify(null));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify(null),
+ JSON.stringify(null)
);
});
test('Empty Root Set Object', () => {
globalStateController.globalState = undefined;
const object = {
- a: 'b',
+ a: 'b'
};
globalStateController.parseGlobalStateMessage('', JSON.stringify(object));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify(object),
+ JSON.stringify(object)
);
});
@@ -34,36 +34,36 @@ test('Empty Root Set Object', () => {
test('Non-Empty Root Set Empty', () => {
const object = {
- a: 'b',
+ a: 'b'
};
globalStateController.globalState = object;
globalStateController.parseGlobalStateMessage('', JSON.stringify(undefined));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify(undefined),
+ JSON.stringify(undefined)
);
});
test('Non-Empty Root Set Null', () => {
const object = {
- a: 'b',
+ a: 'b'
};
globalStateController.globalState = object;
globalStateController.parseGlobalStateMessage('', JSON.stringify(null));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify(null),
+ JSON.stringify(null)
);
});
test('Non-Empty Root Set Object', () => {
globalStateController.globalState = {
- a: 'b',
+ a: 'b'
};
const object = {
- c: 'd',
+ c: 'd'
};
globalStateController.parseGlobalStateMessage('', JSON.stringify(object));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify(object),
+ JSON.stringify(object)
);
});
@@ -72,78 +72,78 @@ test('Non-Empty Root Set Object', () => {
test('Branch Value Set Empty', () => {
globalStateController.globalState = {
a: 'b',
- c: 'd',
+ c: 'd'
};
globalStateController.parseGlobalStateMessage('a', JSON.stringify(undefined));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify({ c: 'd' }),
+ JSON.stringify({ c: 'd' })
);
});
test('Nested Branch Value Set Empty', () => {
globalStateController.globalState = {
a: {
- b: 'c',
- },
+ b: 'c'
+ }
};
globalStateController.parseGlobalStateMessage(
'a/b',
- JSON.stringify(undefined),
+ JSON.stringify(undefined)
);
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify({ a: {} }),
+ JSON.stringify({ a: {} })
);
});
test('Branch Value Set Null', () => {
globalStateController.globalState = {
a: 'b',
- c: 'd',
+ c: 'd'
};
globalStateController.parseGlobalStateMessage('a', JSON.stringify(null));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify({ a: null, c: 'd' }),
+ JSON.stringify({ a: null, c: 'd' })
);
});
test('Nested Branch Value Set Null', () => {
globalStateController.globalState = {
a: {
- b: 'c',
- },
+ b: 'c'
+ }
};
globalStateController.parseGlobalStateMessage('a/b', JSON.stringify(null));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify({ a: { b: null } }),
+ JSON.stringify({ a: { b: null } })
);
});
test('Branch Value Set Object', () => {
globalStateController.globalState = {
a: 'b',
- c: 'd',
+ c: 'd'
};
const object = {
- b: 'e',
+ b: 'e'
};
globalStateController.parseGlobalStateMessage('a', JSON.stringify(object));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify({ a: object, c: 'd' }),
+ JSON.stringify({ a: object, c: 'd' })
);
});
test('Nested Branch Value Set Object', () => {
globalStateController.globalState = {
a: {
- b: 'c',
- },
+ b: 'c'
+ }
};
const object = {
- c: 'd',
+ c: 'd'
};
globalStateController.parseGlobalStateMessage('a/b', JSON.stringify(object));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify({ a: { b: object } }),
+ JSON.stringify({ a: { b: object } })
);
});
@@ -152,73 +152,73 @@ test('Nested Branch Value Set Object', () => {
test('Branch Object Set Empty', () => {
globalStateController.globalState = {
a: { b: 'c' },
- d: 'e',
+ d: 'e'
};
globalStateController.parseGlobalStateMessage('a', JSON.stringify(undefined));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify({ d: 'e' }),
+ JSON.stringify({ d: 'e' })
);
});
test('Nested Branch Object Set Empty', () => {
globalStateController.globalState = {
- a: { b: { c: 'd' }, e: 'f' },
+ a: { b: { c: 'd' }, e: 'f' }
};
globalStateController.parseGlobalStateMessage(
'a/b',
- JSON.stringify(undefined),
+ JSON.stringify(undefined)
);
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify({ a: { e: 'f' } }),
+ JSON.stringify({ a: { e: 'f' } })
);
});
test('Branch Object Set Null', () => {
globalStateController.globalState = {
a: { b: 'c' },
- d: 'e',
+ d: 'e'
};
globalStateController.parseGlobalStateMessage('a', JSON.stringify(null));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify({ a: null, d: 'e' }),
+ JSON.stringify({ a: null, d: 'e' })
);
});
test('Nested Branch Object Set Null', () => {
globalStateController.globalState = {
- a: { b: { c: 'd' }, e: 'f' },
+ a: { b: { c: 'd' }, e: 'f' }
};
globalStateController.parseGlobalStateMessage('a/b', JSON.stringify(null));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify({ a: { b: null, e: 'f' } }),
+ JSON.stringify({ a: { b: null, e: 'f' } })
);
});
test('Branch Object Set Object', () => {
globalStateController.globalState = {
a: { b: 'c', d: 'e' },
- f: 'g',
+ f: 'g'
};
const object = {
d: 'f',
- g: 'h',
+ g: 'h'
};
globalStateController.parseGlobalStateMessage('a', JSON.stringify(object));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify({ a: object, f: 'g' }),
+ JSON.stringify({ a: object, f: 'g' })
);
});
test('Nested Branch Object Set Null 2', () => {
globalStateController.globalState = {
- a: { b: { c: 'd' }, e: 'f' },
+ a: { b: { c: 'd' }, e: 'f' }
};
const object = {
c: 'g',
- h: 'i',
+ h: 'i'
};
globalStateController.parseGlobalStateMessage('a/b', JSON.stringify(object));
expect(JSON.stringify(globalStateController.globalState)).toBe(
- JSON.stringify({ a: { b: object, e: 'f' } }),
+ JSON.stringify({ a: { b: object, e: 'f' } })
);
});
diff --git a/src/bundles/communication/index.ts b/src/bundles/communication/index.ts
index 8971eb75d..e742904b1 100644
--- a/src/bundles/communication/index.ts
+++ b/src/bundles/communication/index.ts
@@ -13,18 +13,18 @@ export {
STATE_CONNECTED,
STATE_DISCONNECTED,
STATE_OFFLINE,
- STATE_RECONNECTING,
+ STATE_RECONNECTING
} from './MqttController';
export {
+ callFunction,
+ expose,
+ getGlobalState,
+ getUserId,
initCommunications,
initGlobalState,
- getGlobalState,
- updateGlobalState,
initRpc,
- getUserId,
- expose,
- callFunction,
keepRunning,
stopRunning,
+ updateGlobalState
} from './Communications';
diff --git a/src/bundles/copy_gc/index.ts b/src/bundles/copy_gc/index.ts
index 0c8d3c0a7..8b73b4280 100644
--- a/src/bundles/copy_gc/index.ts
+++ b/src/bundles/copy_gc/index.ts
@@ -1,4 +1,10 @@
-import { COMMAND, type CommandHeapObject, type Memory, type MemoryHeaps, type Tag } from './types';
+import {
+ COMMAND,
+ type CommandHeapObject,
+ type Memory,
+ type MemoryHeaps,
+ type Tag
+} from './types';
// Global Variables
let ROW: number = 10;
@@ -483,25 +489,25 @@ function init() {
}
export {
+ allHeap,
+ doneShowRoot,
+ endFlip,
+ generateMemory,
init,
// initialisation
initialize_memory,
initialize_tag,
- generateMemory,
- allHeap,
- updateSlotSegment,
- resetFromSpace,
+ newAssign,
newCommand,
newCopy,
- endFlip,
- newPush,
- newPop,
- newAssign,
newNew,
+ newPop,
+ newPush,
+ resetFromSpace,
+ resetRoots,
scanFlip,
+ showRoots,
startFlip,
updateRoots,
- resetRoots,
- showRoots,
- doneShowRoot
+ updateSlotSegment
};
diff --git a/src/bundles/copy_gc/types.ts b/src/bundles/copy_gc/types.ts
index 32ae5b243..d02270cc5 100644
--- a/src/bundles/copy_gc/types.ts
+++ b/src/bundles/copy_gc/types.ts
@@ -12,7 +12,7 @@ export enum COMMAND {
ASSIGN = 'Assign',
NEW = 'New',
SCAN = 'Scan',
- INIT = 'Initialize Memory',
+ INIT = 'Initialize Memory'
}
export type CommandHeapObject = {
diff --git a/src/bundles/csg/functions.ts b/src/bundles/csg/functions.ts
index f46034e09..9bf0dc141 100644
--- a/src/bundles/csg/functions.ts
+++ b/src/bundles/csg/functions.ts
@@ -1,7 +1,6 @@
/* [Imports] */
import { primitives } from '@jscad/modeling';
import { colorize as colorSolid } from '@jscad/modeling/src/colors';
-import { geom3 } from '@jscad/modeling/src/geometries';
import {
measureBoundingBox,
type BoundingBox
@@ -15,10 +14,10 @@ import { extrudeLinear } from '@jscad/modeling/src/operations/extrusions';
import { serialize } from '@jscad/stl-serializer';
import {
head,
+ is_list,
list,
tail,
- type List,
- is_list
+ type List
} from 'js-slang/dist/stdlib/list';
import save from 'save-file';
import { degreesToRadians } from '../../common/utilities';
@@ -27,10 +26,10 @@ import type { Solid } from './jscad/types';
import {
Group,
Shape,
+ centerPrimitive,
hexToColor,
type Operable,
- type RenderGroup,
- centerPrimitive
+ type RenderGroup
} from './utilities';
/* [Main] */
@@ -664,12 +663,12 @@ export function rgb(
blueValue: number
): string {
if (
- redValue < 0
- || redValue > 255
- || greenValue < 0
- || greenValue > 255
- || blueValue < 0
- || blueValue > 255
+ redValue < 0 ||
+ redValue > 255 ||
+ greenValue < 0 ||
+ greenValue > 255 ||
+ blueValue < 0 ||
+ blueValue > 255
) {
throw new Error('RGB values must be between 0 and 255 (inclusive)');
}
@@ -716,8 +715,7 @@ export function render(operable: Operable): RenderGroup {
// Trigger a new render group for use with subsequent renders.
// Render group is returned for REPL text only; do not document
- return Core.getRenderGroupManager()
- .nextRenderGroup();
+ return Core.getRenderGroupManager().nextRenderGroup();
}
/**
@@ -734,8 +732,7 @@ export function render_grid(operable: Operable): RenderGroup {
operable.store();
- return Core.getRenderGroupManager()
- .nextRenderGroup(true);
+ return Core.getRenderGroupManager().nextRenderGroup(true);
}
/**
@@ -752,8 +749,7 @@ export function render_axes(operable: Operable): RenderGroup {
operable.store();
- return Core.getRenderGroupManager()
- .nextRenderGroup(undefined, true);
+ return Core.getRenderGroupManager().nextRenderGroup(undefined, true);
}
/**
@@ -770,6 +766,5 @@ export function render_grid_axes(operable: Operable): RenderGroup {
operable.store();
- return Core.getRenderGroupManager()
- .nextRenderGroup(true, true);
+ return Core.getRenderGroupManager().nextRenderGroup(true, true);
}
diff --git a/src/bundles/csg/index.ts b/src/bundles/csg/index.ts
index 57c4e53eb..58732a22a 100644
--- a/src/bundles/csg/index.ts
+++ b/src/bundles/csg/index.ts
@@ -71,58 +71,53 @@ Core.initialize(moduleState);
export {
// Colors
black,
- navy,
- green,
- teal,
- crimson,
- purple,
- orange,
- silver,
- gray,
blue,
- lime,
+ bounding_box,
+ cone,
+ crimson,
+ cube,
cyan,
- rose,
- pink,
- yellow,
- white,
-
+ cylinder,
+ download_shape_stl,
// Primitives
empty_shape,
- cube,
+ geodesic_sphere,
+ gray,
+ green,
+ // Utilities
+ group,
+ intersect,
+ is_group,
+ is_shape,
+ lime,
+ navy,
+ orange,
+ pink,
+ prism,
+ purple,
+ pyramid,
+ // Rendering
+ render,
+ render_axes,
+ render_grid,
+ render_grid_axes,
+ rgb,
+ rose,
+ rotate,
rounded_cube,
- cylinder,
rounded_cylinder,
+ scale,
+ silver,
sphere,
- geodesic_sphere,
- pyramid,
- cone,
- prism,
star,
- torus,
-
- // Operations
- union,
subtract,
- intersect,
-
+ teal,
+ torus,
// Transformations
translate,
- rotate,
- scale,
-
- // Utilities
- group,
ungroup,
- is_shape,
- is_group,
- bounding_box,
- rgb,
- download_shape_stl,
-
- // Rendering
- render,
- render_grid,
- render_axes,
- render_grid_axes
+ // Operations
+ union,
+ white,
+ yellow
} from './functions';
diff --git a/src/bundles/csg/input_tracker.ts b/src/bundles/csg/input_tracker.ts
index 739453a99..7f5867d52 100644
--- a/src/bundles/csg/input_tracker.ts
+++ b/src/bundles/csg/input_tracker.ts
@@ -26,7 +26,7 @@ enum MousePointer {
FORWARD = 4,
NONE = -1,
- OTHER = 7050,
+ OTHER = 7050
}
/* [Exports] */
@@ -91,8 +91,8 @@ export default class InputTracker {
private isPointerPan(isShiftKey: boolean): boolean {
return (
- this.heldPointer === MousePointer.MIDDLE
- || (this.heldPointer === MousePointer.LEFT && isShiftKey)
+ this.heldPointer === MousePointer.MIDDLE ||
+ (this.heldPointer === MousePointer.LEFT && isShiftKey)
);
}
@@ -108,7 +108,9 @@ export default class InputTracker {
const canvasBounds: DOMRect = this.canvas.getBoundingClientRect();
const { devicePixelRatio } = window;
const newWidth: number = Math.floor(canvasBounds.width * devicePixelRatio);
- const newHeight: number = Math.floor(canvasBounds.height * devicePixelRatio);
+ const newHeight: number = Math.floor(
+ canvasBounds.height * devicePixelRatio
+ );
if (oldWidth === newWidth && oldHeight === newHeight) return;
this.frameDirty = true;
@@ -137,13 +139,13 @@ export default class InputTracker {
const scaledChange: number = currentTick * ZOOM_TICK_SCALE;
const potentialNewScale: number = this.controlsState.scale + scaledChange;
- const potentialNewDistance: number
- = vec3.distance(this.cameraState.position, this.cameraState.target)
- * potentialNewScale;
+ const potentialNewDistance: number =
+ vec3.distance(this.cameraState.position, this.cameraState.target) *
+ potentialNewScale;
if (
- potentialNewDistance > this.controlsState.limits.minDistance
- && potentialNewDistance < this.controlsState.limits.maxDistance
+ potentialNewDistance > this.controlsState.limits.minDistance &&
+ potentialNewDistance < this.controlsState.limits.maxDistance
) {
this.frameDirty = true;
this.controlsState.scale = potentialNewScale;
diff --git a/src/bundles/csg/jscad/renderer.ts b/src/bundles/csg/jscad/renderer.ts
index d82a6505f..6699838c3 100644
--- a/src/bundles/csg/jscad/renderer.ts
+++ b/src/bundles/csg/jscad/renderer.ts
@@ -7,7 +7,11 @@ import {
entitiesFromSolids,
prepareRender
} from '@jscad/regl-renderer';
-import { ACE_GUTTER_BACKGROUND_COLOR, ACE_GUTTER_TEXT_COLOR, BP_TEXT_COLOR } from '../../../tabs/common/css_constants';
+import {
+ ACE_GUTTER_BACKGROUND_COLOR,
+ ACE_GUTTER_TEXT_COLOR,
+ BP_TEXT_COLOR
+} from '../../../tabs/common/css_constants';
import {
DEFAULT_COLOR,
GRID_PADDING,
@@ -45,16 +49,13 @@ function solidsToGeometryEntities(solids: Solid[]): GeometryEntity[] {
const options: EntitiesFromSolidsOptions = {
color: hexToAlphaColor(DEFAULT_COLOR)
};
- return (entitiesFromSolids(
- options,
- ...solids
- ) as unknown) as GeometryEntity[];
+ return entitiesFromSolids(options, ...solids) as unknown as GeometryEntity[];
}
function neatGridDistance(rawDistance: number) {
const paddedDistance: number = rawDistance + GRID_PADDING;
- const roundedDistance: number
- = Math.ceil(paddedDistance / ROUND_UP_INTERVAL) * ROUND_UP_INTERVAL;
+ const roundedDistance: number =
+ Math.ceil(paddedDistance / ROUND_UP_INTERVAL) * ROUND_UP_INTERVAL;
return roundedDistance;
}
@@ -186,10 +187,10 @@ export function updateStates(
cameraState: PerspectiveCameraState,
controlsState: ControlsState
) {
- const states: UpdatedStates = (orbit.update({
+ const states: UpdatedStates = orbit.update({
camera: cameraState,
controls: controlsState
- }) as unknown) as UpdatedStates;
+ }) as unknown as UpdatedStates;
cameraState.position = states.camera.position;
cameraState.view = states.camera.view;
@@ -204,11 +205,11 @@ export function zoomToFit(
controlsState: ControlsState,
geometryEntities: GeometryEntity[]
) {
- const states: ZoomToFitStates = (orbit.zoomToFit({
+ const states: ZoomToFitStates = orbit.zoomToFit({
camera: cameraState,
controls: controlsState,
entities: geometryEntities as any
- }) as unknown) as ZoomToFitStates;
+ }) as unknown as ZoomToFitStates;
cameraState.target = states.camera.target;
@@ -221,14 +222,14 @@ export function rotate(
rotateX: number,
rotateY: number
) {
- const states: RotateStates = (orbit.rotate(
+ const states: RotateStates = orbit.rotate(
{
camera: cameraState,
controls: controlsState,
speed: ROTATION_SPEED
},
[rotateX, rotateY]
- ) as unknown) as RotateStates;
+ ) as unknown as RotateStates;
controlsState.thetaDelta = states.controls.thetaDelta;
controlsState.phiDelta = states.controls.phiDelta;
@@ -240,13 +241,13 @@ export function pan(
panX: number,
panY: number
) {
- const states: PanStates = (orbit.pan(
+ const states: PanStates = orbit.pan(
{
camera: cameraState,
controls: controlsState
},
[panX * X_FACTOR, panY * Y_FACTOR]
- ) as unknown) as PanStates;
+ ) as unknown as PanStates;
cameraState.position = states.camera.position;
cameraState.target = states.camera.target;
diff --git a/src/bundles/csg/jscad/types.ts b/src/bundles/csg/jscad/types.ts
index db0e9f13d..1fe7c2f00 100644
--- a/src/bundles/csg/jscad/types.ts
+++ b/src/bundles/csg/jscad/types.ts
@@ -1,7 +1,11 @@
/* [Import] */
import type { RGB, RGBA } from '@jscad/modeling/src/colors/types';
import type { Geom3 } from '@jscad/modeling/src/geometries/types';
-import { type cameras, type drawCommands, controls } from '@jscad/regl-renderer';
+import {
+ controls,
+ type cameras,
+ type drawCommands
+} from '@jscad/regl-renderer';
import type makeDrawMultiGrid from '@jscad/regl-renderer/types/rendering/commands/drawGrid/multi';
/* [Main] */
@@ -158,7 +162,7 @@ export type DrawCommandMakers = Record;
export type Mat4 = Float32Array;
export type PerspectiveCameraState = Omit<
typeof cameras.perspective.cameraState,
-'position' | 'target' | 'view'
+ 'position' | 'target' | 'view'
> & {
target: Coordinates;
@@ -209,7 +213,7 @@ export type WrappedRenderer = (data: WrappedRendererData) => void;
*/
export type ControlsState = Omit<
typeof orbit.controlsState,
-'phiDelta' | 'scale' | 'thetaDelta'
+ 'phiDelta' | 'scale' | 'thetaDelta'
> &
typeof orbit.controlsProps & {
scale: number;
diff --git a/src/bundles/csg/types.ts b/src/bundles/csg/types.ts
index 0668fbaa1..d09afda88 100644
--- a/src/bundles/csg/types.ts
+++ b/src/bundles/csg/types.ts
@@ -2,8 +2,8 @@
import type { RGB, RGBA } from '@jscad/modeling/src/colors';
import type { Geom3 } from '@jscad/modeling/src/geometries/types';
import {
- cameras,
controls as _controls,
+ cameras,
type drawCommands
} from '@jscad/regl-renderer';
import type makeDrawMultiGrid from '@jscad/regl-renderer/types/rendering/commands/drawGrid/multi';
@@ -34,7 +34,7 @@ export type OrthographicCamera = typeof orthographicCamera;
export type PerspectiveCameraState = Omit<
typeof perspectiveCamera.cameraState,
-'position' | 'target' | 'view'
+ 'position' | 'target' | 'view'
> & {
target: CoordinatesXYZ;
@@ -47,7 +47,7 @@ export type CameraState = OrthographicCameraState | PerspectiveCameraState;
// @jscad\regl-renderer\src\controls\orbitControls.js
export type Controls = Omit<
typeof controls,
-'pan' | 'rotate' | 'update' | 'zoomToFit'
+ 'pan' | 'rotate' | 'update' | 'zoomToFit'
> & {
update: ControlsUpdate.Function;
zoomToFit: ControlsZoomToFit.Function;
@@ -125,7 +125,7 @@ export type ControlsPan = (
export type ControlsState = Omit<
typeof controls.controlsState,
-'phiDelta' | 'scale' | 'thetaDelta'
+ 'phiDelta' | 'scale' | 'thetaDelta'
> &
typeof controls.controlsProps & {
scale: number;
diff --git a/src/bundles/csg/utilities.ts b/src/bundles/csg/utilities.ts
index af4e6e699..d9bb241fd 100644
--- a/src/bundles/csg/utilities.ts
+++ b/src/bundles/csg/utilities.ts
@@ -95,7 +95,9 @@ export class Group implements Operable, ReplResult {
ungroup(): Operable[] {
// Return all children, but we need to account for this Group's unresolved
// transforms by applying them to each child
- return this.children.map((child: Operable) => child.applyTransforms(this.transforms));
+ return this.children.map((child: Operable) =>
+ child.applyTransforms(this.transforms)
+ );
}
}
@@ -108,10 +110,9 @@ export class Shape implements Operable, ReplResult {
}
store(newTransforms: Mat4 = mat4.create()): void {
- Core.getRenderGroupManager()
- .storeShape(
- this.applyTransforms(newTransforms) as Shape
- );
+ Core.getRenderGroupManager().storeShape(
+ this.applyTransforms(newTransforms) as Shape
+ );
}
translate(offsets: [number, number, number]): Shape {
@@ -219,10 +220,10 @@ export function centerPrimitive(shape: Shape) {
}
export function hexToColor(hex: string): Color {
- const regex: RegExp
- = /^#?(?[\da-f]{2})(?[\da-f]{2})(?[\da-f]{2})$/iu;
- const potentialGroups: { [key: string]: string } | undefined
- = hex.match(regex)?.groups;
+ const regex: RegExp =
+ /^#?(?[\da-f]{2})(?[\da-f]{2})(?[\da-f]{2})$/iu;
+ const potentialGroups: { [key: string]: string } | undefined =
+ hex.match(regex)?.groups;
if (potentialGroups === undefined) return [0, 0, 0];
const groups: { [key: string]: string } = potentialGroups;
diff --git a/src/bundles/curve/__tests__/curve.ts b/src/bundles/curve/__tests__/curve.ts
index 4fc993db1..5565a2d14 100644
--- a/src/bundles/curve/__tests__/curve.ts
+++ b/src/bundles/curve/__tests__/curve.ts
@@ -1,21 +1,36 @@
import { generateCurve, type Curve } from '../curves_webgl';
-import { animate_3D_curve, animate_curve, draw_3D_connected, draw_connected, make_point } from '../functions';
+import {
+ animate_3D_curve,
+ animate_curve,
+ draw_3D_connected,
+ draw_connected,
+ make_point
+} from '../functions';
function evalCurve(curve: Curve, numPoints: number) {
generateCurve('none', 'points', numPoints, curve, '2D', false);
}
test('Ensure that invalid curves error gracefully', () => {
- expect(() => evalCurve((t) => 1 as any, 200))
- .toThrowErrorMatchingInlineSnapshot('"Expected curve to return a point, got \'1\' at t=0"');
+ expect(() =>
+ evalCurve(t => 1 as any, 200)
+ ).toThrowErrorMatchingInlineSnapshot(
+ '"Expected curve to return a point, got \'1\' at t=0"'
+ );
});
test('Using 3D render functions with animate_curve should throw errors', () => {
- expect(() => animate_curve(1, 60, draw_3D_connected(200), (t0) => (t1) => make_point(t0, t1)))
- .toThrowErrorMatchingInlineSnapshot('"animate_curve cannot be used with 3D draw function!"');
+ expect(() =>
+ animate_curve(1, 60, draw_3D_connected(200), t0 => t1 => make_point(t0, t1))
+ ).toThrowErrorMatchingInlineSnapshot(
+ '"animate_curve cannot be used with 3D draw function!"'
+ );
});
test('Using 2D render functions with animate_3D_curve should throw errors', () => {
- expect(() => animate_3D_curve(1, 60, draw_connected(200), (t0) => (t1) => make_point(t0, t1)))
- .toThrowErrorMatchingInlineSnapshot('"animate_3D_curve cannot be used with 2D draw function!"');
+ expect(() =>
+ animate_3D_curve(1, 60, draw_connected(200), t0 => t1 => make_point(t0, t1))
+ ).toThrowErrorMatchingInlineSnapshot(
+ '"animate_3D_curve cannot be used with 2D draw function!"'
+ );
});
diff --git a/src/bundles/curve/curves_webgl.ts b/src/bundles/curve/curves_webgl.ts
index ca81f9d0e..49609fd85 100644
--- a/src/bundles/curve/curves_webgl.ts
+++ b/src/bundles/curve/curves_webgl.ts
@@ -123,7 +123,8 @@ export class Point implements ReplResult {
public readonly color: Color
) {}
- public toReplString = () => `(${this.x}, ${this.y}, ${this.z}, Color: ${this.color})`;
+ public toReplString = () =>
+ `(${this.x}, ${this.y}, ${this.z}, Color: ${this.color})`;
}
/**
@@ -338,7 +339,11 @@ export function generateCurve(
const point = func(i / numPoints);
if (!(point instanceof Point)) {
- throw new Error(`Expected curve to return a point, got '${stringify(point)}' at t=${i / numPoints}`);
+ throw new Error(
+ `Expected curve to return a point, got '${stringify(point)}' at t=${
+ i / numPoints
+ }`
+ );
}
const x = point.x * 2 - 1;
diff --git a/src/bundles/curve/functions.ts b/src/bundles/curve/functions.ts
index 701d1c296..8267353a1 100644
--- a/src/bundles/curve/functions.ts
+++ b/src/bundles/curve/functions.ts
@@ -1,6 +1,11 @@
/* eslint-disable @typescript-eslint/naming-convention */
import context from 'js-slang/context';
-import { type Curve, type CurveDrawn, generateCurve, Point } from './curves_webgl';
+import {
+ Point,
+ generateCurve,
+ type Curve,
+ type CurveDrawn
+} from './curves_webgl';
import {
AnimatedCurve,
type CurveAnimation,
@@ -537,9 +542,9 @@ export function rotate_around_origin(
// 2 args
throw new Error('Expected 1 or 3 arguments, but received 2');
} else if (
- theta1 !== undefined
- && theta2 === undefined
- && theta3 === undefined
+ theta1 !== undefined &&
+ theta2 === undefined &&
+ theta3 === undefined
) {
// 1 args
const cth = Math.cos(theta1);
@@ -612,7 +617,7 @@ export function rotate_around_origin(
* @returns function that takes a Curve and returns a Curve
*/
export function scale(a: number, b: number, c: number): CurveTransformer {
- return (curve) => {
+ return curve => {
const transformation = (cf: Curve) => (t: number) => {
const ct = cf(t);
const a1 = a === undefined ? 1 : a;
@@ -684,7 +689,7 @@ export function put_in_standard_position(curve: Curve): Curve {
* @returns result Curve
*/
export function connect_rigidly(curve1: Curve, curve2: Curve): Curve {
- return (t) => (t < 1 / 2 ? curve1(2 * t) : curve2(2 * t - 1));
+ return t => (t < 1 / 2 ? curve1(2 * t) : curve2(2 * t - 1));
}
/**
diff --git a/src/bundles/curve/samples/canvases.js b/src/bundles/curve/samples/canvases.js
index cbac23d7c..56be0c033 100644
--- a/src/bundles/curve/samples/canvases.js
+++ b/src/bundles/curve/samples/canvases.js
@@ -5,6 +5,16 @@ draw_connected_full_view(20)(unit_circle);
draw_3D_connected(100)(t => make_3D_point(t, t * t, t));
-animate_curve(3, 30, draw_connected_full_view_proportional(100), s => t => make_point(t - s, t * s));
+animate_curve(
+ 3,
+ 30,
+ draw_connected_full_view_proportional(100),
+ s => t => make_point(t - s, t * s)
+);
-animate_3D_curve(3, 40, draw_3D_connected_full_view_proportional(100), s => t => make_3D_point(t - s, t - t * s, t * s));
+animate_3D_curve(
+ 3,
+ 40,
+ draw_3D_connected_full_view_proportional(100),
+ s => t => make_3D_point(t - s, t - t * s, t * s)
+);
diff --git a/src/bundles/curve/samples/imports.js b/src/bundles/curve/samples/imports.js
index b61fc316d..8b1378917 100644
--- a/src/bundles/curve/samples/imports.js
+++ b/src/bundles/curve/samples/imports.js
@@ -1,39 +1 @@
-import {
- animate_3D_curve,
- animate_curve,
- arc,
- b_of,
- connect_ends,
- connect_rigidly,
- draw_3D_connected,
- draw_3D_connected_full_view,
- draw_3D_connected_full_view_proportional,
- draw_3D_points,
- draw_3D_points_full_view,
- draw_3D_points_full_view_proportional,
- draw_connected,
- draw_connected_full_view,
- draw_connected_full_view_proportional,
- draw_points,
- draw_points_full_view,
- draw_points_full_view_proportional,
- g_of,
- invert,
- make_3D_color_point,
- make_3D_point,
- make_color_point,
- make_point,
- put_in_standard_position,
- r_of,
- rotate_around_origin,
- scale,
- scale_proportional,
- translate,
- unit_circle,
- unit_line,
- unit_line_at,
- x_of,
- y_of,
- z_of
-} from 'curve';
diff --git a/src/bundles/curve/types.ts b/src/bundles/curve/types.ts
index 9176542d8..facd6104f 100644
--- a/src/bundles/curve/types.ts
+++ b/src/bundles/curve/types.ts
@@ -3,7 +3,7 @@ import type { ReplResult } from '../../typings/type_helpers';
import type { Curve, CurveDrawn } from './curves_webgl';
export type CurveModuleState = {
- drawnCurves: (AnimatedCurve | CurveDrawn)[]
+ drawnCurves: (AnimatedCurve | CurveDrawn)[];
};
/** A function that takes in CurveFunction and returns a tranformed CurveFunction. */
@@ -23,7 +23,7 @@ export type CurveAnimation = (t: number) => Curve;
* a CurveFunction and returns a ShapeDrawn based on its specifications.
*/
export type RenderFunction = ((func: Curve) => CurveDrawn) & {
- is3D: boolean
+ is3D: boolean;
};
export class AnimatedCurve extends glAnimation implements ReplResult {
diff --git a/src/bundles/game/functions.ts b/src/bundles/game/functions.ts
index 9df32eafd..7da32b08c 100644
--- a/src/bundles/game/functions.ts
+++ b/src/bundles/game/functions.ts
@@ -17,16 +17,22 @@
/* eslint-disable consistent-return, @typescript-eslint/default-param-last, @typescript-eslint/no-shadow, @typescript-eslint/no-unused-vars */
import context from 'js-slang/context';
-import { type List, head, tail, is_pair, accumulate } from 'js-slang/dist/stdlib/list';
+import {
+ accumulate,
+ head,
+ is_pair,
+ tail,
+ type List
+} from 'js-slang/dist/stdlib/list';
import Phaser from 'phaser';
import {
+ defaultGameParams,
type GameObject,
type ObjectConfig,
type RawContainer,
type RawGameElement,
type RawGameObject,
- type RawInputObject,
- defaultGameParams
+ type RawInputObject
} from './types';
if (!context.moduleContexts.game.state) {
@@ -45,7 +51,7 @@ const {
// Listener ObjectTypes
enum ListenerTypes {
InputPlugin = 'input_plugin',
- KeyboardKeyType = 'keyboard_key',
+ KeyboardKeyType = 'keyboard_key'
}
const ListnerTypes = Object.values(ListenerTypes);
@@ -57,7 +63,7 @@ enum ObjectTypes {
RectType = 'rect',
EllipseType = 'ellipse',
ContainerType = 'container',
- AwardType = 'award',
+ AwardType = 'award'
}
const ObjTypes = Object.values(ObjectTypes);
@@ -71,7 +77,8 @@ const mandatory = (obj, errMsg: string) => {
return obj;
};
-const scene = () => mandatory(context.moduleContexts.game.state.scene, 'No scene found!');
+const scene = () =>
+ mandatory(context.moduleContexts.game.state.scene, 'No scene found!');
// =============================================================================
// Module's Private Functions
@@ -184,13 +191,17 @@ export function prepend_remote_url(asset_key: string): string {
*/
export function create_config(lst: List): ObjectConfig {
const config = {};
- accumulate((xs: [any, any], _) => {
- if (!is_pair(xs)) {
- throw_error('config element is not a pair!');
- }
- config[head(xs)] = tail(xs);
- return null;
- }, null, lst);
+ accumulate(
+ (xs: [any, any], _) => {
+ if (!is_pair(xs)) {
+ throw_error('config element is not a pair!');
+ }
+ config[head(xs)] = tail(xs);
+ return null;
+ },
+ null,
+ lst
+ );
return config;
}
@@ -619,10 +630,7 @@ export function create_image(
y: number,
asset_key: string
): GameObject | undefined {
- if (
- preloadImageMap.get(asset_key)
- || preloadSpritesheetMap.get(asset_key)
- ) {
+ if (preloadImageMap.get(asset_key) || preloadSpritesheetMap.get(asset_key)) {
const image = new Phaser.GameObjects.Sprite(scene(), x, y, asset_key);
return set_type(image, ObjectTypes.ImageType);
}
@@ -647,7 +655,11 @@ export function create_image(
* @param award_key key for award
* @returns award game object
*/
-export function create_award(x: number, y: number, award_key: string): GameObject {
+export function create_award(
+ x: number,
+ y: number,
+ award_key: string
+): GameObject {
return set_type(createAward(x, y, award_key), ObjectTypes.AwardType);
}
@@ -780,11 +792,10 @@ export function add_to_container(
obj: GameObject
): GameObject | undefined {
if (
- is_type(container, ObjectTypes.ContainerType)
- && is_any_type(obj, ObjTypes)
+ is_type(container, ObjectTypes.ContainerType) &&
+ is_any_type(obj, ObjTypes)
) {
- get_container(container)
- .add(get_game_obj(obj));
+ get_container(container).add(get_game_obj(obj));
return container;
}
throw_error(
@@ -803,8 +814,7 @@ export function add_to_container(
*/
export function destroy_obj(obj: GameObject) {
if (is_any_type(obj, ObjTypes)) {
- get_game_obj(obj)
- .destroy();
+ get_game_obj(obj).destroy();
} else {
throw_error(`${obj} is not of type ${ObjTypes}`);
}
@@ -825,8 +835,7 @@ export function set_display_size(
y: number
): GameObject | undefined {
if (is_any_type(obj, ObjTypes)) {
- get_game_obj(obj)
- .setDisplaySize(x, y);
+ get_game_obj(obj).setDisplaySize(x, y);
return obj;
}
throw_error(`${obj} is not of type ${ObjTypes}`);
@@ -840,10 +849,12 @@ export function set_display_size(
* @param alpha new alpha
* @returns game object itself
*/
-export function set_alpha(obj: GameObject, alpha: number): GameObject | undefined {
+export function set_alpha(
+ obj: GameObject,
+ alpha: number
+): GameObject | undefined {
if (is_any_type(obj, ObjTypes)) {
- get_game_obj(obj)
- .setAlpha(alpha);
+ get_game_obj(obj).setAlpha(alpha);
return obj;
}
throw_error(`${obj} is not of type ${ObjTypes}`);
@@ -865,8 +876,7 @@ export function set_interactive(
config: ObjectConfig = {}
): GameObject | undefined {
if (is_any_type(obj, ObjTypes)) {
- get_game_obj(obj)
- .setInteractive(config);
+ get_game_obj(obj).setInteractive(config);
return obj;
}
throw_error(`${obj} is not of type ${ObjTypes}`);
@@ -909,8 +919,7 @@ export function set_position(
y: number
): GameObject | undefined {
if (obj && is_any_type(obj, ObjTypes)) {
- get_game_obj(obj)
- .setPosition(x, y);
+ get_game_obj(obj).setPosition(x, y);
return obj;
}
throw_error(`${obj} is not of type ${ObjTypes}`);
@@ -931,8 +940,7 @@ export function set_scale(
y: number
): GameObject | undefined {
if (is_any_type(obj, ObjTypes)) {
- get_game_obj(obj)
- .setScale(x, y);
+ get_game_obj(obj).setScale(x, y);
return obj;
}
throw_error(`${obj} is not of type ${ObjTypes}`);
@@ -946,10 +954,12 @@ export function set_scale(
* @param rad the rotation, in radians
* @returns game object itself
*/
-export function set_rotation(obj: GameObject, rad: number): GameObject | undefined {
+export function set_rotation(
+ obj: GameObject,
+ rad: number
+): GameObject | undefined {
if (is_any_type(obj, ObjTypes)) {
- get_game_obj(obj)
- .setRotation(rad);
+ get_game_obj(obj).setRotation(rad);
return obj;
}
throw_error(`${obj} is not of type ${ObjTypes}`);
@@ -1020,8 +1030,7 @@ export function add_listener(
callback: Function
): GameObject | undefined {
if (is_any_type(obj, ObjTypes)) {
- const listener = get_game_obj(obj)
- .addListener(event, callback);
+ const listener = get_game_obj(obj).addListener(event, callback);
return set_type(listener, ListenerTypes.InputPlugin);
}
throw_error(`${obj} is not of type ${ObjTypes}`);
@@ -1061,8 +1070,7 @@ export function add_keyboard_listener(
*/
export function remove_listener(listener: GameObject): boolean {
if (is_any_type(listener, ListnerTypes)) {
- get_input_obj(listener)
- .removeAllListeners();
+ get_input_obj(listener).removeAllListeners();
return true;
}
return false;
@@ -1114,7 +1122,7 @@ const gameFunctions = [
// Inject minArgsNeeded to allow module varargs
// Remove if module varargs is fixed on js-slang side
-gameFunctions.forEach((fn) => {
+gameFunctions.forEach(fn => {
const dummy = fn as any;
dummy.minArgsNeeded = fn.length;
});
diff --git a/src/bundles/game/index.ts b/src/bundles/game/index.ts
index 17cf21529..797b81ac2 100644
--- a/src/bundles/game/index.ts
+++ b/src/bundles/game/index.ts
@@ -16,8 +16,8 @@
export {
add,
- add_listener,
add_keyboard_listener,
+ add_listener,
add_to_container,
add_tween,
create_anim,
@@ -31,16 +31,16 @@ export {
create_image,
create_interactive_config,
create_rect,
+ create_sound_config,
+ create_spritesheet_config,
create_text,
create_text_config,
create_tween_config,
- create_sound_config,
- create_spritesheet_config,
destroy_obj,
- get_screen_width,
- get_screen_height,
- get_screen_display_width,
get_screen_display_height,
+ get_screen_display_width,
+ get_screen_height,
+ get_screen_width,
load_image,
load_sound,
load_spritesheet,
diff --git a/src/bundles/game/types.ts b/src/bundles/game/types.ts
index 4ff97dcdc..3780fe911 100644
--- a/src/bundles/game/types.ts
+++ b/src/bundles/game/types.ts
@@ -7,7 +7,8 @@ export type RawGameElement =
| Phaser.GameObjects.Text;
export type RawGameShape =
- Phaser.GameObjects.Ellipse | Phaser.GameObjects.Rectangle;
+ | Phaser.GameObjects.Ellipse
+ | Phaser.GameObjects.Rectangle;
export type RawGameObject = RawGameElement | RawGameShape;
@@ -38,7 +39,8 @@ export type GameParams = {
createAward: (x: number, y: number, key: string) => Phaser.GameObjects.Sprite;
};
-export const sourceAcademyAssets = 'https://source-academy-assets.s3-ap-southeast-1.amazonaws.com';
+export const sourceAcademyAssets =
+ 'https://source-academy-assets.s3-ap-southeast-1.amazonaws.com';
// Scene needs to be set when available!
export const defaultGameParams: GameParams = {
@@ -52,10 +54,12 @@ export const defaultGameParams: GameParams = {
update() {}
},
renderPreview: false,
- remotePath: (path: string) => sourceAcademyAssets + (path[0] === '/' ? '' : '/') + path,
+ remotePath: (path: string) =>
+ sourceAcademyAssets + (path[0] === '/' ? '' : '/') + path,
screenSize: {
x: 1920,
y: 1080
},
- createAward: (x: number, y: number, key: string) => new Phaser.GameObjects.Sprite(defaultGameParams.scene!, x, y, key)
+ createAward: (x: number, y: number, key: string) =>
+ new Phaser.GameObjects.Sprite(defaultGameParams.scene!, x, y, key)
};
diff --git a/src/bundles/mark_sweep/index.ts b/src/bundles/mark_sweep/index.ts
index e0550db8d..a35234c41 100644
--- a/src/bundles/mark_sweep/index.ts
+++ b/src/bundles/mark_sweep/index.ts
@@ -1,4 +1,10 @@
-import { type MemoryHeaps, type Memory, type Tag, COMMAND, type CommandHeapObject } from './types';
+import {
+ COMMAND,
+ type CommandHeapObject,
+ type Memory,
+ type MemoryHeaps,
+ type Tag
+} from './types';
// Global Variables
let ROW: number = 10;
@@ -350,25 +356,25 @@ function init() {
}
export {
+ addRoots,
+ allHeap,
+ endGC,
+ generateMemory,
init,
// initialisation
initialize_memory,
initialize_tag,
- generateMemory,
- allHeap,
- updateSlotSegment,
+ newAssign,
newCommand,
+ newGC,
newMark,
- newPush,
- newPop,
- newAssign,
newNew,
- newGC,
+ newPop,
+ newPush,
newSweep,
- updateRoots,
newUpdateSweep,
+ showRoot,
showRoots,
- endGC,
- addRoots,
- showRoot
+ updateRoots,
+ updateSlotSegment
};
diff --git a/src/bundles/mark_sweep/types.ts b/src/bundles/mark_sweep/types.ts
index 56c71389d..7c5bcf36e 100644
--- a/src/bundles/mark_sweep/types.ts
+++ b/src/bundles/mark_sweep/types.ts
@@ -15,7 +15,7 @@ export enum COMMAND {
SHOW_MARKED = 'Marked Roots',
MARK = 'Mark',
SWEEP = 'Sweep',
- INIT = 'Initialize Memory',
+ INIT = 'Initialize Memory'
}
export type CommandHeapObject = {
diff --git a/src/bundles/painter/functions.ts b/src/bundles/painter/functions.ts
index e045328cb..2d61f5ba1 100644
--- a/src/bundles/painter/functions.ts
+++ b/src/bundles/painter/functions.ts
@@ -1,6 +1,6 @@
import context from 'js-slang/context';
import Plotly, { type Data, type Layout } from 'plotly.js-dist';
-import { type Frame, LinePlot } from './painter';
+import { LinePlot, type Frame } from './painter';
const drawnPainters: LinePlot[] = [];
context.moduleContexts.painter.state = {
@@ -50,16 +50,20 @@ export function display_painter(painter: (frame: Frame) => void) {
y: y_s
};
drawnPainters.push(
- new LinePlot(draw_new_painter, {
- ...data,
- mode: 'lines'
- } as Data, {
- xaxis: { visible: true },
- yaxis: {
- visible: true,
- scaleanchor: 'x'
+ new LinePlot(
+ draw_new_painter,
+ {
+ ...data,
+ mode: 'lines'
+ } as Data,
+ {
+ xaxis: { visible: true },
+ yaxis: {
+ visible: true,
+ scaleanchor: 'x'
+ }
}
- })
+ )
);
};
}
diff --git a/src/bundles/painter/index.ts b/src/bundles/painter/index.ts
index 3e6c83a66..6830409f6 100644
--- a/src/bundles/painter/index.ts
+++ b/src/bundles/painter/index.ts
@@ -4,4 +4,4 @@
* @author Sourabh Raj Jaiswal
*/
-export { draw_line, display_painter } from './functions';
+export { display_painter, draw_line } from './functions';
diff --git a/src/bundles/physics_2d/PhysicsObject.ts b/src/bundles/physics_2d/PhysicsObject.ts
index e5cbee63e..c5ab1cada 100644
--- a/src/bundles/physics_2d/PhysicsObject.ts
+++ b/src/bundles/physics_2d/PhysicsObject.ts
@@ -3,13 +3,13 @@
// follow the same guidelines as the rest of the codebase.
import {
- type b2Body,
- type b2Shape,
- type b2Fixture,
b2BodyType,
b2CircleShape,
b2PolygonShape,
- b2Vec2
+ b2Vec2,
+ type b2Body,
+ type b2Fixture,
+ type b2Shape
} from '@box2d/core';
import { type ReplResult } from '../../typings/type_helpers';
@@ -112,7 +112,8 @@ export class PhysicsObject implements ReplResult {
const resForce = this.forcesCentered
.filter((force: Force) => force.start_time < world_time)
.reduce(
- (res: b2Vec2, force: Force) => res.Add(force.direction.Scale(force.magnitude)),
+ (res: b2Vec2, force: Force) =>
+ res.Add(force.direction.Scale(force.magnitude)),
new b2Vec2()
);
@@ -121,10 +122,11 @@ export class PhysicsObject implements ReplResult {
private applyForcesAtAPoint(world_time: number) {
this.forcesAtAPoint = this.forcesAtAPoint.filter(
- (forceWithPos: ForceWithPos) => forceWithPos.force.start_time + forceWithPos.force.duration > world_time
+ (forceWithPos: ForceWithPos) =>
+ forceWithPos.force.start_time + forceWithPos.force.duration > world_time
);
- this.forcesAtAPoint.forEach((forceWithPos) => {
+ this.forcesAtAPoint.forEach(forceWithPos => {
const force = forceWithPos.force;
this.body.ApplyForce(
force.direction.Scale(force.magnitude),
@@ -150,8 +152,7 @@ export class PhysicsObject implements ReplResult {
}
public toReplString = () => `
- Mass: ${this.getMass()
- .toFixed(ACCURACY)}
+ Mass: ${this.getMass().toFixed(ACCURACY)}
Position: [${this.getPosition().x.toFixed(
ACCURACY
)},${this.getPosition().y.toFixed(ACCURACY)}]
@@ -159,10 +160,8 @@ export class PhysicsObject implements ReplResult {
ACCURACY
)},${this.getVelocity().y.toFixed(ACCURACY)}]
- Rotation: ${this.getRotation()
- .toFixed(ACCURACY)}
- AngularVelocity: [${this.getAngularVelocity()
- .toFixed(ACCURACY)}]`;
+ Rotation: ${this.getRotation().toFixed(ACCURACY)}
+ AngularVelocity: [${this.getAngularVelocity().toFixed(ACCURACY)}]`;
public scale_size(scale: number) {
if (this.shape instanceof b2CircleShape) {
@@ -170,7 +169,7 @@ export class PhysicsObject implements ReplResult {
} else if (this.shape instanceof b2PolygonShape) {
const centroid: b2Vec2 = this.shape.m_centroid;
const arr: b2Vec2[] = [];
- this.shape.m_vertices.forEach((vec) => {
+ this.shape.m_vertices.forEach(vec => {
arr.push(
new b2Vec2(
centroid.x + scale * (vec.x - centroid.x),
@@ -178,8 +177,7 @@ export class PhysicsObject implements ReplResult {
)
);
});
- this.shape = new b2PolygonShape()
- .Set(arr);
+ this.shape = new b2PolygonShape().Set(arr);
}
const f: b2Fixture = this.fixture;
this.body.DestroyFixture(this.fixture);
diff --git a/src/bundles/physics_2d/PhysicsWorld.ts b/src/bundles/physics_2d/PhysicsWorld.ts
index 04132ca47..39b659a97 100644
--- a/src/bundles/physics_2d/PhysicsWorld.ts
+++ b/src/bundles/physics_2d/PhysicsWorld.ts
@@ -3,16 +3,16 @@
// follow the same guidelines as the rest of the codebase.
import {
- type b2Body,
- type b2Fixture,
- type b2BodyDef,
b2BodyType,
+ b2ContactListener,
b2PolygonShape,
- type b2StepConfig,
b2Vec2,
b2World,
- b2ContactListener,
- type b2Contact
+ type b2Body,
+ type b2BodyDef,
+ type b2Contact,
+ type b2Fixture,
+ type b2StepConfig
} from '@box2d/core';
import { type PhysicsObject } from './PhysicsObject';
import { Timer } from './types';
@@ -73,11 +73,10 @@ export class PhysicsWorld {
type: b2BodyType.b2_staticBody,
position: new b2Vec2(0, height - 10)
});
- const groundShape: b2PolygonShape = new b2PolygonShape()
- .SetAsBox(
- 10000,
- 10
- );
+ const groundShape: b2PolygonShape = new b2PolygonShape().SetAsBox(
+ 10000,
+ 10
+ );
groundBody.CreateFixture({
shape: groundShape,
@@ -111,7 +110,7 @@ export class PhysicsWorld {
Objects:
`;
- this.physicsObjects.forEach((obj) => {
+ this.physicsObjects.forEach(obj => {
world_status += `
------------------------
${obj.toReplString()}
diff --git a/src/bundles/physics_2d/functions.ts b/src/bundles/physics_2d/functions.ts
index 83beb643f..d8e4496ad 100644
--- a/src/bundles/physics_2d/functions.ts
+++ b/src/bundles/physics_2d/functions.ts
@@ -13,7 +13,7 @@ import context from 'js-slang/context';
import { PhysicsObject } from './PhysicsObject';
import { PhysicsWorld } from './PhysicsWorld';
-import { type Force, Vector2 } from './types';
+import { Vector2, type Force } from './types';
// Global Variables
@@ -120,8 +120,7 @@ export function add_wall(pos: Vector2, rot: number, size: Vector2) {
new PhysicsObject(
pos,
rot,
- new b2PolygonShape()
- .SetAsBox(size.x / 2, size.y / 2),
+ new b2PolygonShape().SetAsBox(size.x / 2, size.y / 2),
true,
world
)
@@ -152,8 +151,7 @@ export function add_box_object(
const newObj: PhysicsObject = new PhysicsObject(
pos,
rot,
- new b2PolygonShape()
- .SetAsBox(size.x / 2, size.y / 2),
+ new b2PolygonShape().SetAsBox(size.x / 2, size.y / 2),
isStatic,
world
);
@@ -185,8 +183,7 @@ export function add_circle_object(
const newObj: PhysicsObject = new PhysicsObject(
pos,
rot,
- new b2CircleShape()
- .Set(new Vector2(), radius),
+ new b2CircleShape().Set(new Vector2(), radius),
isStatic,
world
);
@@ -220,12 +217,11 @@ export function add_triangle_object(
const newObj: PhysicsObject = new PhysicsObject(
pos,
rot,
- new b2PolygonShape()
- .Set([
- new Vector2(-base / 2, -height / 2),
- new Vector2(base / 2, -height / 2),
- new Vector2(0, height / 2)
- ]),
+ new b2PolygonShape().Set([
+ new Vector2(-base / 2, -height / 2),
+ new Vector2(base / 2, -height / 2),
+ new Vector2(0, height / 2)
+ ]),
isStatic,
world
);
diff --git a/src/bundles/physics_2d/index.ts b/src/bundles/physics_2d/index.ts
index e6efaaa6e..62f1a27d0 100644
--- a/src/bundles/physics_2d/index.ts
+++ b/src/bundles/physics_2d/index.ts
@@ -48,7 +48,7 @@
* The suggested time step is 1/60 (seconds).
*
* Visualization of the physics world can also be seen in the display tab.
-*
+ *
* The following example simulates a free fall of a circle object.
*
* ```
@@ -73,41 +73,33 @@
* @author Yu Jiali
*/
export {
- set_gravity,
- make_ground,
- add_wall,
-
- make_vector,
- make_force,
-
add_box_object,
add_circle_object,
add_triangle_object,
-
+ add_vector,
+ add_wall,
+ apply_force,
+ apply_force_to_center,
+ array_to_vector,
+ get_angular_velocity,
+ get_position,
+ get_rotation,
+ get_velocity,
+ impact_start_time,
+ is_touching,
+ make_force,
+ make_ground,
+ make_vector,
+ scale_size,
+ set_angular_velocity,
set_density,
set_friction,
- scale_size,
-
- get_position,
+ set_gravity,
set_position,
- get_rotation,
set_rotation,
- get_velocity,
set_velocity,
- get_angular_velocity,
- set_angular_velocity,
-
- apply_force,
- apply_force_to_center,
-
- is_touching,
- impact_start_time,
-
- update_world,
simulate_world,
-
- vector_to_array,
- array_to_vector,
- add_vector,
- subtract_vector
+ subtract_vector,
+ update_world,
+ vector_to_array
} from './functions';
diff --git a/src/bundles/pix_n_flix/functions.ts b/src/bundles/pix_n_flix/functions.ts
index 353cea7e2..c8e44bfcc 100644
--- a/src/bundles/pix_n_flix/functions.ts
+++ b/src/bundles/pix_n_flix/functions.ts
@@ -1,30 +1,30 @@
/* eslint-disable @typescript-eslint/no-shadow */
import {
- DEFAULT_WIDTH,
- DEFAULT_HEIGHT,
DEFAULT_FPS,
+ DEFAULT_HEIGHT,
+ DEFAULT_LOOP,
DEFAULT_VOLUME,
+ DEFAULT_WIDTH,
+ MAX_FPS,
MAX_HEIGHT,
- MIN_HEIGHT,
MAX_WIDTH,
- MIN_WIDTH,
- MAX_FPS,
MIN_FPS,
- DEFAULT_LOOP
+ MIN_HEIGHT,
+ MIN_WIDTH
} from './constants';
import {
+ InputFeed,
+ type BundlePacket,
type CanvasElement,
- type VideoElement,
type ErrorLogger,
- type StartPacket,
+ type Filter,
+ type ImageElement,
type Pixel,
type Pixels,
- type Filter,
type Queue,
+ type StartPacket,
type TabsPacket,
- type BundlePacket,
- InputFeed,
- type ImageElement
+ type VideoElement
} from './types';
// Global Variables
@@ -110,8 +110,8 @@ function writeToBuffer(buffer: Uint8ClampedArray, data: Pixels) {
}
if (!ok) {
- const warningMessage
- = 'You have invalid values for some pixels! Reseting them to default (0)';
+ const warningMessage =
+ 'You have invalid values for some pixels! Reseting them to default (0)';
console.warn(warningMessage);
errorLogger(warningMessage, false);
}
@@ -206,7 +206,7 @@ function playVideoElement() {
.then(() => {
videoIsPlaying = true;
})
- .catch((err) => {
+ .catch(err => {
console.warn(err);
});
}
@@ -263,15 +263,16 @@ function loadMedia(): void {
navigator.mediaDevices
.getUserMedia({ video: true })
- .then((stream) => {
+ .then(stream => {
videoElement.srcObject = stream;
- videoElement.onloadedmetadata = () => setAspectRatioDimensions(
- videoElement.videoWidth,
- videoElement.videoHeight
- );
+ videoElement.onloadedmetadata = () =>
+ setAspectRatioDimensions(
+ videoElement.videoWidth,
+ videoElement.videoHeight
+ );
toRunLateQueue = true;
})
- .catch((error) => {
+ .catch(error => {
const errorMessage = `${error.name}: ${error.message}`;
console.error(errorMessage);
errorLogger(errorMessage, false);
@@ -344,11 +345,11 @@ function updateFPS(fps: number): void {
function updateDimensions(w: number, h: number): void {
// ignore if no change or bad inputs
if (
- (w === WIDTH && h === HEIGHT)
- || w > MAX_WIDTH
- || w < MIN_WIDTH
- || h > MAX_HEIGHT
- || h < MIN_HEIGHT
+ (w === WIDTH && h === HEIGHT) ||
+ w > MAX_WIDTH ||
+ w < MIN_WIDTH ||
+ h > MAX_HEIGHT ||
+ h < MIN_HEIGHT
) {
return;
}
@@ -467,10 +468,9 @@ function deinit(): void {
if (!stream) {
return;
}
- stream.getTracks()
- .forEach((track) => {
- track.stop();
- });
+ stream.getTracks().forEach(track => {
+ track.stop();
+ });
}
// =============================================================================
diff --git a/src/bundles/pix_n_flix/index.ts b/src/bundles/pix_n_flix/index.ts
index 8d6776292..19eb42891 100644
--- a/src/bundles/pix_n_flix/index.ts
+++ b/src/bundles/pix_n_flix/index.ts
@@ -23,26 +23,26 @@
*/
export {
- start,
- red_of,
+ alpha_of,
blue_of,
+ compose_filter,
+ copy_image,
+ get_video_time,
green_of,
- alpha_of,
- set_rgba,
image_height,
image_width,
- copy_image,
install_filter,
- reset_filter,
- compose_filter,
+ keep_aspect_ratio,
pause_at,
+ red_of,
+ reset_filter,
set_dimensions,
set_fps,
+ set_loop_count,
+ set_rgba,
set_volume,
- use_local_file,
+ start,
use_image_url,
- use_video_url,
- get_video_time,
- keep_aspect_ratio,
- set_loop_count
+ use_local_file,
+ use_video_url
} from './functions';
diff --git a/src/bundles/pix_n_flix/types.ts b/src/bundles/pix_n_flix/types.ts
index 5f5495552..39cc98bb1 100644
--- a/src/bundles/pix_n_flix/types.ts
+++ b/src/bundles/pix_n_flix/types.ts
@@ -12,7 +12,7 @@ export enum InputFeed {
Camera,
ImageURL,
VideoURL,
- Local,
+ Local
}
export type BundlePacket = {
diff --git a/src/bundles/plotly/curve_functions.ts b/src/bundles/plotly/curve_functions.ts
index 26592a4e1..fe04f2122 100644
--- a/src/bundles/plotly/curve_functions.ts
+++ b/src/bundles/plotly/curve_functions.ts
@@ -1,5 +1,5 @@
import Plotly, { type Data, type Layout } from 'plotly.js-dist';
-import { type Curve, CurvePlot, type Point } from './plotly';
+import { CurvePlot, type Curve, type Point } from './plotly';
export function x_of(pt: Point): number {
return pt.x;
diff --git a/src/bundles/plotly/functions.ts b/src/bundles/plotly/functions.ts
index 130c4e097..96421fa00 100644
--- a/src/bundles/plotly/functions.ts
+++ b/src/bundles/plotly/functions.ts
@@ -8,10 +8,10 @@ import Plotly, { type Data, type Layout } from 'plotly.js-dist';
import { type Sound } from '../sound/types';
import { generatePlot } from './curve_functions';
import {
- type Curve,
CurvePlot,
- type CurvePlotFunction,
DrawnPlot,
+ type Curve,
+ type CurvePlotFunction,
type ListOfPairs
} from './plotly';
import { get_duration, get_wave, is_sound } from './sound_functions';
diff --git a/src/bundles/plotly/index.ts b/src/bundles/plotly/index.ts
index e588d53ad..19e984f70 100644
--- a/src/bundles/plotly/index.ts
+++ b/src/bundles/plotly/index.ts
@@ -4,11 +4,11 @@
*/
export {
- new_plot,
- new_plot_json,
draw_connected_2d,
draw_connected_3d,
draw_points_2d,
draw_points_3d,
- draw_sound_2d
+ draw_sound_2d,
+ new_plot,
+ new_plot_json
} from './functions';
diff --git a/src/bundles/plotly/plotly.ts b/src/bundles/plotly/plotly.ts
index ac76551ea..7958c96bc 100644
--- a/src/bundles/plotly/plotly.ts
+++ b/src/bundles/plotly/plotly.ts
@@ -55,7 +55,8 @@ export class Point implements ReplResult {
public readonly color: Color
) {}
- public toReplString = () => `(${this.x}, ${this.y}, ${this.z}, Color: ${this.color})`;
+ public toReplString = () =>
+ `(${this.x}, ${this.y}, ${this.z}, Color: ${this.color})`;
}
export type Wave = (...t: any) => number;
diff --git a/src/bundles/plotly/sound_functions.ts b/src/bundles/plotly/sound_functions.ts
index 42ad074af..6dc5dbaa3 100644
--- a/src/bundles/plotly/sound_functions.ts
+++ b/src/bundles/plotly/sound_functions.ts
@@ -1,14 +1,10 @@
-import {
- head,
- tail,
- is_pair
-} from 'js-slang/dist/stdlib/list';
+import { head, is_pair, tail } from 'js-slang/dist/stdlib/list';
import { type Sound, type Wave } from '../sound/types';
export function is_sound(x: any): x is Sound {
return (
- is_pair(x)
- && typeof get_wave(x) === 'function'
- && typeof get_duration(x) === 'number'
+ is_pair(x) &&
+ typeof get_wave(x) === 'function' &&
+ typeof get_duration(x) === 'number'
);
}
/**
diff --git a/src/bundles/repeat/__tests__/index.ts b/src/bundles/repeat/__tests__/index.ts
index e4e553763..89b34fc88 100644
--- a/src/bundles/repeat/__tests__/index.ts
+++ b/src/bundles/repeat/__tests__/index.ts
@@ -1,17 +1,14 @@
-import { repeat, twice, thrice } from '../functions';
+import { repeat, thrice, twice } from '../functions';
// Test functions
test('repeat works correctly and repeats function n times', () => {
- expect(repeat((x: number) => x + 1, 5)(1))
- .toBe(6);
+ expect(repeat((x: number) => x + 1, 5)(1)).toBe(6);
});
test('twice works correctly and repeats function twice', () => {
- expect(twice((x: number) => x + 1)(1))
- .toBe(3);
+ expect(twice((x: number) => x + 1)(1)).toBe(3);
});
test('thrice works correctly and repeats function thrice', () => {
- expect(thrice((x: number) => x + 1)(1))
- .toBe(4);
+ expect(thrice((x: number) => x + 1)(1)).toBe(4);
});
diff --git a/src/bundles/repeat/index.ts b/src/bundles/repeat/index.ts
index 8e1023ae4..2275398b9 100644
--- a/src/bundles/repeat/index.ts
+++ b/src/bundles/repeat/index.ts
@@ -4,4 +4,4 @@
* @author Tang Xin Kye, Marcus
*/
-export { repeat, twice, thrice } from './functions';
+export { repeat, thrice, twice } from './functions';
diff --git a/src/bundles/repl/functions.ts b/src/bundles/repl/functions.ts
index 948e3c8d1..18c0ceae8 100644
--- a/src/bundles/repl/functions.ts
+++ b/src/bundles/repl/functions.ts
@@ -25,8 +25,10 @@ context.moduleContexts.repl.state = INSTANCE;
*/
export function set_evaluator(evalFunc: Function) {
if (!(evalFunc instanceof Function)) {
- const typeName = typeof (evalFunc);
- throw new Error(`Wrong parameter type "${typeName}' in function "set_evaluator". It supposed to be a function and it's the entrance function of your metacircular evaulator.`);
+ const typeName = typeof evalFunc;
+ throw new Error(
+ `Wrong parameter type "${typeName}' in function "set_evaluator". It supposed to be a function and it's the entrance function of your metacircular evaulator.`
+ );
}
INSTANCE.evalFunction = evalFunc;
return {
@@ -72,9 +74,13 @@ export function set_evaluator(evalFunc: Function) {
* @param {content} the content you want to display
* @category Main
*/
-export function repl_display(content: any) : any {
+export function repl_display(content: any): any {
if (INSTANCE.richDisplayInternal(content) === 'not_rich_text_pair') {
- INSTANCE.pushOutputString(content.toString(), COLOR_REPL_DISPLAY_DEFAULT, 'plaintext');// students may set the value of the parameter "str" to types other than a string (for example "repl_display(1)" ). So here I need to first convert the parameter "str" into a string before preceding.
+ INSTANCE.pushOutputString(
+ content.toString(),
+ COLOR_REPL_DISPLAY_DEFAULT,
+ 'plaintext'
+ ); // students may set the value of the parameter "str" to types other than a string (for example "repl_display(1)" ). So here I need to first convert the parameter "str" into a string before preceding.
return content;
}
return undefined;
@@ -87,7 +93,10 @@ export function repl_display(content: any) : any {
*
* @category Main
*/
-export function set_background_image(img_url: string, background_color_alpha: number) : void {
+export function set_background_image(
+ img_url: string,
+ background_color_alpha: number
+): void {
INSTANCE.customizedEditorProps.backgroundImageUrl = img_url;
INSTANCE.customizedEditorProps.backgroundColorAlpha = background_color_alpha;
}
@@ -99,7 +108,7 @@ export function set_background_image(img_url: string, background_color_alpha: nu
* @category Main
*/
export function set_font_size(font_size_px: number) {
- INSTANCE.customizedEditorProps.fontSize = parseInt(font_size_px.toString());// The TypeScript type checker will throw an error as "parseInt" in TypeScript only accepts one string as parameter.
+ INSTANCE.customizedEditorProps.fontSize = parseInt(font_size_px.toString()); // The TypeScript type checker will throw an error as "parseInt" in TypeScript only accepts one string as parameter.
}
/**
@@ -109,8 +118,10 @@ export function set_font_size(font_size_px: number) {
*
* @category Main
*/
-export function default_js_slang(_program: string) : any {
- throw new Error('Invaild Call: Function "default_js_slang" can not be directly called by user\'s code in editor. You should use it as the parameter of the function "set_evaluator"');
+export function default_js_slang(_program: string): any {
+ throw new Error(
+ 'Invaild Call: Function "default_js_slang" can not be directly called by user\'s code in editor. You should use it as the parameter of the function "set_evaluator"'
+ );
// When the function is normally called by set_evaluator function, safeKey is set to "document.body", which has a type "Element".
// Students can not create objects and use HTML Elements in Source due to limitations and rules in Source, so they can't set the safeKey to a HTML Element, thus they can't use this function in Source.
}
diff --git a/src/bundles/repl/index.ts b/src/bundles/repl/index.ts
index 124c27694..02cab6333 100644
--- a/src/bundles/repl/index.ts
+++ b/src/bundles/repl/index.ts
@@ -35,12 +35,12 @@
*
* @module repl
* @author Wang Zihan
-*/
+ */
export {
- set_evaluator,
+ default_js_slang,
repl_display,
set_background_image,
- set_font_size,
- default_js_slang
+ set_evaluator,
+ set_font_size
} from './functions';
diff --git a/src/bundles/repl/programmable_repl.ts b/src/bundles/repl/programmable_repl.ts
index bcfa68649..3af63d956 100644
--- a/src/bundles/repl/programmable_repl.ts
+++ b/src/bundles/repl/programmable_repl.ts
@@ -6,7 +6,11 @@
import { runFilesInContext, type IOptions } from 'js-slang';
import context from 'js-slang/context';
-import { COLOR_RUN_CODE_RESULT, COLOR_ERROR_MESSAGE, DEFAULT_EDITOR_HEIGHT } from './config';
+import {
+ COLOR_ERROR_MESSAGE,
+ COLOR_RUN_CODE_RESULT,
+ DEFAULT_EDITOR_HEIGHT
+} from './config';
import { default_js_slang } from './functions';
export class ProgrammableRepl {
@@ -17,7 +21,7 @@ export class ProgrammableRepl {
private _tabReactComponent: any;
// I store editorHeight value separately in here although it is already stored in the module's Tab React component state because I need to keep the editor height
// when the Tab component is re-mounted due to the user drags the area between the module's Tab and Source Academy's original REPL to resize the module's Tab height.
- public editorHeight : number;
+ public editorHeight: number;
public customizedEditorProps = {
backgroundImageUrl: 'no-background-image',
@@ -26,10 +30,10 @@ export class ProgrammableRepl {
};
constructor() {
- this.evalFunction = (_placeholder) => this.easterEggFunction();
+ this.evalFunction = _placeholder => this.easterEggFunction();
this.userCodeInEditor = this.getSavedEditorContent();
this.outputStrings = [];
- this._editorInstance = null;// To be set when calling "SetEditorInstance" in the ProgrammableRepl Tab React Component render function.
+ this._editorInstance = null; // To be set when calling "SetEditorInstance" in the ProgrammableRepl Tab React Component render function.
this.editorHeight = DEFAULT_EDITOR_HEIGHT;
developmentLog(this);
}
@@ -50,15 +54,26 @@ export class ProgrammableRepl {
} catch (exception: any) {
developmentLog(exception);
// If the exception has a start line of -1 and an undefined error property, then this exception is most likely to be "incorrect number of arguments" caused by incorrect number of parameters in the evaluator entry function provided by students with set_evaluator.
- if (exception.location.start.line === -1 && exception.error === undefined) {
- this.pushOutputString('Error: Unable to use your evaluator to run the code. Does your evaluator entry function contain and only contain exactly one parameter?', COLOR_ERROR_MESSAGE);
+ if (
+ exception.location.start.line === -1 &&
+ exception.error === undefined
+ ) {
+ this.pushOutputString(
+ 'Error: Unable to use your evaluator to run the code. Does your evaluator entry function contain and only contain exactly one parameter?',
+ COLOR_ERROR_MESSAGE
+ );
} else {
- this.pushOutputString(`Line ${exception.location.start.line.toString()}: ${exception.error?.message}`, COLOR_ERROR_MESSAGE);
+ this.pushOutputString(
+ `Line ${exception.location.start.line.toString()}: ${
+ exception.error?.message
+ }`,
+ COLOR_ERROR_MESSAGE
+ );
}
this.reRenderTab();
return;
}
- if (typeof (retVal) === 'string') {
+ if (typeof retVal === 'string') {
retVal = `"${retVal}"`;
}
// Here must use plain text output mode because retVal contains strings from the users.
@@ -72,9 +87,18 @@ export class ProgrammableRepl {
}
// Rich text output method allow output strings to have html tags and css styles.
- pushOutputString(content : string, textColor : string, outputMethod : string = 'plaintext') {
+ pushOutputString(
+ content: string,
+ textColor: string,
+ outputMethod: string = 'plaintext'
+ ) {
const tmp = {
- content: content === undefined ? 'undefined' : content === null ? 'null' : content,
+ content:
+ content === undefined
+ ? 'undefined'
+ : content === null
+ ? 'null'
+ : content,
color: textColor,
outputMethod
};
@@ -84,46 +108,58 @@ export class ProgrammableRepl {
setEditorInstance(instance: any) {
if (instance === undefined) return; // It seems that when calling this function in gui->render->ref, the React internal calls this function for multiple times (at least two times) , and in at least one call the parameter 'instance' is set to 'undefined'. If I don't add this if statement, the program will throw a runtime error when rendering tab.
this._editorInstance = instance;
- this._editorInstance.on('guttermousedown', (e) => {
+ this._editorInstance.on('guttermousedown', e => {
const breakpointLine = e.getDocumentPosition().row;
developmentLog(breakpointLine);
});
- this._editorInstance.setOptions({ fontSize: `${this.customizedEditorProps.fontSize.toString()}pt` });
+ this._editorInstance.setOptions({
+ fontSize: `${this.customizedEditorProps.fontSize.toString()}pt`
+ });
}
richDisplayInternal(pair_rich_text) {
developmentLog(pair_rich_text);
- const head = (pair) => pair[0];
- const tail = (pair) => pair[1];
- const is_pair = (obj) => obj instanceof Array && obj.length === 2;
+ const head = pair => pair[0];
+ const tail = pair => pair[1];
+ const is_pair = obj => obj instanceof Array && obj.length === 2;
if (!is_pair(pair_rich_text)) return 'not_rich_text_pair';
- function checkColorStringValidity(htmlColor:string) {
+ function checkColorStringValidity(htmlColor: string) {
if (htmlColor.length !== 7) return false;
if (htmlColor[0] !== '#') return false;
for (let i = 1; i < 7; i++) {
const char = htmlColor[i];
developmentLog(` ${char}`);
- if (!((char >= '0' && char <= '9') || (char >= 'A' && char <= 'F') || (char >= 'a' && char <= 'f'))) {
+ if (
+ !(
+ (char >= '0' && char <= '9') ||
+ (char >= 'A' && char <= 'F') ||
+ (char >= 'a' && char <= 'f')
+ )
+ ) {
return false;
}
}
return true;
}
function recursiveHelper(thisInstance, param): string {
- if (typeof (param) === 'string') {
+ if (typeof param === 'string') {
// There MUST be a safe check on users' strings, because users may insert something that can be interpreted as executable JavaScript code when outputing rich text.
const safeCheckResult = thisInstance.userStringSafeCheck(param);
if (safeCheckResult !== 'safe') {
- throw new Error(`For safety matters, the character/word ${safeCheckResult} is not allowed in rich text output. Please remove it or use plain text output mode and try again.`);
+ throw new Error(
+ `For safety matters, the character/word ${safeCheckResult} is not allowed in rich text output. Please remove it or use plain text output mode and try again.`
+ );
}
developmentLog(head(param));
return `">${param}`;
}
if (!is_pair(param)) {
- throw new Error(`Unexpected data type ${typeof (param)} when processing rich text. It should be a pair.`);
+ throw new Error(
+ `Unexpected data type ${typeof param} when processing rich text. It should be a pair.`
+ );
} else {
- const pairStyleToCssStyle : { [pairStyle : string] : string } = {
+ const pairStyleToCssStyle: { [pairStyle: string]: string } = {
bold: 'font-weight:bold;',
italic: 'font-style:italic;',
small: 'font-size: 14px;',
@@ -132,40 +168,63 @@ export class ProgrammableRepl {
gigantic: 'font-size: 50px;',
underline: 'text-decoration: underline;'
};
- if (typeof (tail(param)) !== 'string') {
- throw new Error(`The tail in style pair should always be a string, but got ${typeof (tail(param))}.`);
+ if (typeof tail(param) !== 'string') {
+ throw new Error(
+ `The tail in style pair should always be a string, but got ${typeof tail(
+ param
+ )}.`
+ );
}
let style = '';
- if (tail(param)
- .substring(0, 3) === 'clr') {
+ if (tail(param).substring(0, 3) === 'clr') {
let prefix = '';
if (tail(param)[3] === 't') prefix = 'color:';
else if (tail(param)[3] === 'b') prefix = 'background-color:';
else throw new Error('Error when decoding rich text color data');
- const colorHex = tail(param)
- .substring(4);
+ const colorHex = tail(param).substring(4);
if (!checkColorStringValidity(colorHex)) {
- throw new Error(`Invalid html color string ${colorHex}. It should start with # and followed by 6 characters representing a hex number.`);
+ throw new Error(
+ `Invalid html color string ${colorHex}. It should start with # and followed by 6 characters representing a hex number.`
+ );
}
style = `${prefix + colorHex};`;
} else {
style = pairStyleToCssStyle[tail(param)];
if (style === undefined) {
- throw new Error(`Found undefined style ${tail(param)} during processing rich text.`);
+ throw new Error(
+ `Found undefined style ${tail(
+ param
+ )} during processing rich text.`
+ );
}
}
return style + recursiveHelper(thisInstance, head(param));
}
}
- this.pushOutputString(`', 'script', 'javascript', 'eval', 'document', 'window', 'console', 'location'];
+ const forbiddenWords = [
+ '\\',
+ '<',
+ '>',
+ 'script',
+ 'javascript',
+ 'eval',
+ 'document',
+ 'window',
+ 'console',
+ 'location'
+ ];
for (const word of forbiddenWords) {
if (tmp.indexOf(word) !== -1) {
return word;
@@ -181,7 +240,7 @@ export class ProgrammableRepl {
runInJsSlang(code: string): string {
developmentLog('js-slang context:');
// console.log(context);
- const options : Partial = {
+ const options: Partial = {
originalMaxExecTime: 1000,
scheduler: 'preemptive',
stepLimit: 1000,
@@ -190,54 +249,88 @@ export class ProgrammableRepl {
};
context.prelude = 'const display=(x)=>repl_display(x);';
context.errors = []; // Here if I don't manually clear the "errors" array in context, the remaining errors from the last evaluation will stop the function "preprocessFileImports" in preprocessor.ts of js-slang thus stop the whole evaluation.
- const sourceFile : Record = {
+ const sourceFile: Record = {
'/ReplModuleUserCode.js': code
};
- runFilesInContext(sourceFile, '/ReplModuleUserCode.js', context, options)
- .then((evalResult) => {
- if (evalResult.status === 'suspended' || evalResult.status === 'suspended-cse-eval') {
- throw new Error('This should not happen');
- }
- if (evalResult.status !== 'error') {
- this.pushOutputString('js-slang program finished with value:', COLOR_RUN_CODE_RESULT);
- // Here must use plain text output mode because evalResult.value contains strings from the users.
- this.pushOutputString(evalResult.value === undefined ? 'undefined' : evalResult.value.toString(), COLOR_RUN_CODE_RESULT);
- } else {
- const errors = context.errors;
- console.log(errors);
- const errorCount = errors.length;
- for (let i = 0; i < errorCount; i++) {
- const error = errors[i];
- if (error.explain()
- .indexOf('Name repl_display not declared.') !== -1) {
- this.pushOutputString('[Error] It seems that you haven\'t import the function "repl_display" correctly when calling "set_evaluator" in Source Academy\'s main editor.', COLOR_ERROR_MESSAGE);
- } else this.pushOutputString(`Line ${error.location.start.line}: ${error.type} Error: ${error.explain()} (${error.elaborate()})`, COLOR_ERROR_MESSAGE);
- }
+ runFilesInContext(
+ sourceFile,
+ '/ReplModuleUserCode.js',
+ context,
+ options
+ ).then(evalResult => {
+ if (
+ evalResult.status === 'suspended' ||
+ evalResult.status === 'suspended-cse-eval'
+ ) {
+ throw new Error('This should not happen');
+ }
+ if (evalResult.status !== 'error') {
+ this.pushOutputString(
+ 'js-slang program finished with value:',
+ COLOR_RUN_CODE_RESULT
+ );
+ // Here must use plain text output mode because evalResult.value contains strings from the users.
+ this.pushOutputString(
+ evalResult.value === undefined
+ ? 'undefined'
+ : evalResult.value.toString(),
+ COLOR_RUN_CODE_RESULT
+ );
+ } else {
+ const errors = context.errors;
+ console.log(errors);
+ const errorCount = errors.length;
+ for (let i = 0; i < errorCount; i++) {
+ const error = errors[i];
+ if (
+ error.explain().indexOf('Name repl_display not declared.') !== -1
+ ) {
+ this.pushOutputString(
+ '[Error] It seems that you haven\'t import the function "repl_display" correctly when calling "set_evaluator" in Source Academy\'s main editor.',
+ COLOR_ERROR_MESSAGE
+ );
+ } else
+ this.pushOutputString(
+ `Line ${error.location.start.line}: ${
+ error.type
+ } Error: ${error.explain()} (${error.elaborate()})`,
+ COLOR_ERROR_MESSAGE
+ );
}
- this.reRenderTab();
- });
+ }
+ this.reRenderTab();
+ });
return 'Async run in js-slang';
}
- setTabReactComponentInstance(tab : any) {
+ setTabReactComponentInstance(tab: any) {
this._tabReactComponent = tab;
}
private reRenderTab() {
- this._tabReactComponent.setState({});// Forces the tab React Component to re-render using setState
+ this._tabReactComponent.setState({}); // Forces the tab React Component to re-render using setState
}
saveEditorContent() {
- localStorage.setItem('programmable_repl_saved_editor_code', this.userCodeInEditor.toString());
+ localStorage.setItem(
+ 'programmable_repl_saved_editor_code',
+ this.userCodeInEditor.toString()
+ );
this.pushOutputString('Saved', 'lightgreen');
- this.pushOutputString('The saved code is stored locally in your browser. You may lose the saved code if you clear browser data or use another device. ', 'gray', 'richtext');
+ this.pushOutputString(
+ "The saved code is stored locally in your browser. You may lose the saved code if you clear browser data or use another device. ",
+ 'gray',
+ 'richtext'
+ );
this.reRenderTab();
}
private getSavedEditorContent() {
- const savedContent = localStorage.getItem('programmable_repl_saved_editor_code');
+ const savedContent = localStorage.getItem(
+ 'programmable_repl_saved_editor_code'
+ );
if (savedContent === null) return '';
return savedContent;
}
@@ -245,7 +338,7 @@ export class ProgrammableRepl {
private easterEggFunction() {
this.pushOutputString(' ', 'white', 'richtext');
this.pushOutputString(
- 'If you see this, please check whether you have called set_evaluator function with the correct parameter before using the Programmable Repl Tab.',
+ "If you see this, please check whether you have called set_evaluator function with the correct parameter before using the Programmable Repl Tab.",
'yellow',
'richtext'
);
diff --git a/src/bundles/rune/display.ts b/src/bundles/rune/display.ts
index c0416cd97..32a392771 100644
--- a/src/bundles/rune/display.ts
+++ b/src/bundles/rune/display.ts
@@ -1,6 +1,12 @@
import context from 'js-slang/context';
import { AnaglyphRune, HollusionRune } from './functions';
-import { type DrawnRune, AnimatedRune, type Rune, NormalRune, type RuneAnimation } from './rune';
+import {
+ AnimatedRune,
+ NormalRune,
+ type DrawnRune,
+ type Rune,
+ type RuneAnimation
+} from './rune';
import { throwIfNotRune } from './runes_ops';
// =============================================================================
@@ -81,7 +87,7 @@ export function animate_rune(
fps: number,
func: RuneAnimation
) {
- const anim = new AnimatedRune(duration, fps, (n) => {
+ const anim = new AnimatedRune(duration, fps, n => {
const rune = func(n);
throwIfNotRune(animate_rune.name, rune);
return new NormalRune(rune);
@@ -104,7 +110,7 @@ export function animate_anaglyph(
fps: number,
func: RuneAnimation
) {
- const anim = new AnimatedRune(duration, fps, (n) => {
+ const anim = new AnimatedRune(duration, fps, n => {
const rune = func(n);
throwIfNotRune(animate_anaglyph.name, rune);
return new AnaglyphRune(rune);
diff --git a/src/bundles/rune/functions.ts b/src/bundles/rune/functions.ts
index 6e85f95e4..83ba1a692 100644
--- a/src/bundles/rune/functions.ts
+++ b/src/bundles/rune/functions.ts
@@ -1,36 +1,36 @@
import { mat4, vec3 } from 'gl-matrix';
import {
- Rune,
DrawnRune,
+ Rune,
drawRunesToFrameBuffer,
type AnimatedRune
} from './rune';
import {
- getSquare,
+ addColorFromHex,
+ colorPalette,
getBlank,
- getRcross,
- getSail,
- getTriangle,
- getCorner,
- getNova,
getCircle,
+ getCorner,
getHeart,
+ getNova,
getPentagram,
+ getRcross,
getRibbon,
- throwIfNotRune,
- addColorFromHex,
- colorPalette,
- hexToColor
+ getSail,
+ getSquare,
+ getTriangle,
+ hexToColor,
+ throwIfNotRune
} from './runes_ops';
import {
- type FrameBufferWithTexture,
getWebGlFromCanvas,
initFramebufferObject,
- initShaderProgram
+ initShaderProgram,
+ type FrameBufferWithTexture
} from './runes_webgl';
export type RuneModuleState = {
- drawnRunes: (AnimatedRune | DrawnRune)[]
+ drawnRunes: (AnimatedRune | DrawnRune)[];
};
// =============================================================================
@@ -892,8 +892,8 @@ export class HollusionRune extends DrawnRune {
lastTime = timeInMs;
- const framePos
- = Math.floor(timeInMs / (period / frameCount)) % frameCount;
+ const framePos =
+ Math.floor(timeInMs / (period / frameCount)) % frameCount;
const fbObject = frameBuffer[framePos];
gl.clearColor(1.0, 1.0, 1.0, 1.0); // Set clear color to white, fully opaque
// eslint-disable-next-line no-bitwise
@@ -911,4 +911,5 @@ export class HollusionRune extends DrawnRune {
}
/** @hidden */
-export const isHollusionRune = (rune: DrawnRune): rune is HollusionRune => rune.isHollusion;
+export const isHollusionRune = (rune: DrawnRune): rune is HollusionRune =>
+ rune.isHollusion;
diff --git a/src/bundles/rune/index.ts b/src/bundles/rune/index.ts
index 693d91bc5..59f7bf162 100644
--- a/src/bundles/rune/index.ts
+++ b/src/bundles/rune/index.ts
@@ -42,8 +42,8 @@ export {
scale_independent,
square,
stack,
- stackn,
stack_frac,
+ stackn,
translate,
triangle,
turn_upside_down,
diff --git a/src/bundles/rune/rune.ts b/src/bundles/rune/rune.ts
index b08e12251..0731deda9 100644
--- a/src/bundles/rune/rune.ts
+++ b/src/bundles/rune/rune.ts
@@ -1,5 +1,5 @@
import { mat4 } from 'gl-matrix';
-import { type AnimFrame, glAnimation } from '../../typings/anim_types';
+import { glAnimation, type AnimFrame } from '../../typings/anim_types';
import type { ReplResult } from '../../typings/type_helpers';
import { getWebGlFromCanvas, initShaderProgram } from './runes_webgl';
@@ -67,14 +67,15 @@ export class Rune {
public hollusionDistance: number
) {}
- public copy = () => new Rune(
- this.vertices,
- this.colors,
- mat4.clone(this.transformMatrix),
- this.subRunes,
- this.texture,
- this.hollusionDistance
- );
+ public copy = () =>
+ new Rune(
+ this.vertices,
+ this.colors,
+ mat4.clone(this.transformMatrix),
+ this.subRunes,
+ this.texture,
+ this.hollusionDistance
+ );
/**
* Flatten the subrunes to return a list of runes
@@ -118,7 +119,8 @@ export class Rune {
hollusionDistance?: number;
} = {}
) => {
- const paramGetter = (name: string, defaultValue: () => any) => (params[name] === undefined ? defaultValue() : params[name]);
+ const paramGetter = (name: string, defaultValue: () => any) =>
+ params[name] === undefined ? defaultValue() : params[name];
return new Rune(
paramGetter('vertices', () => new Float32Array()),
diff --git a/src/bundles/rune/runes_ops.ts b/src/bundles/rune/runes_ops.ts
index 58fc1e378..56ae2cc2e 100644
--- a/src/bundles/rune/runes_ops.ts
+++ b/src/bundles/rune/runes_ops.ts
@@ -7,7 +7,7 @@ import { Rune } from './rune';
// Utility Functions
// =============================================================================
export function throwIfNotRune(name: string, ...runes: any) {
- runes.forEach((rune) => {
+ runes.forEach(rune => {
if (!(rune instanceof Rune)) {
throw Error(`${name} expects a rune as argument.`);
}
@@ -338,9 +338,8 @@ export const colorPalette = [
];
export function hexToColor(hex: string): number[] {
- const result = /^#?(?[a-f\d]{2})(?[a-f\d]{2})(?[a-f\d]{2})$/iu.exec(
- hex
- );
+ const result =
+ /^#?(?[a-f\d]{2})(?[a-f\d]{2})(?[a-f\d]{2})$/iu.exec(hex);
if (result === null || result.length < 4) {
return [0, 0, 0];
}
diff --git a/src/bundles/rune/ruomu_journal.md b/src/bundles/rune/ruomu_journal.md
index 0a98b91ef..95e217008 100644
--- a/src/bundles/rune/ruomu_journal.md
+++ b/src/bundles/rune/ruomu_journal.md
@@ -1,52 +1,69 @@
# Development journal for rune module
-## Todos:
-## Future directions:
+
+## Todos
+
+## Future directions
+
- improve efficiency by compress representation using index/programInfo/gl.TRIANGLE_FAN etc.
- improve efficiency by using texture cache
- improve efficiency by instance drawing, however, please keep it KISS
## Work Log
+
### 25 Jul 2021
+
- 2:00pm - 7:30pm : get familiar with Typescript, the project structure and webGL basics. tried to directly port Runes but failed. Propose to refactor the library to make everything clearer and coherent with the current coding style.
### 26 Jul 2021
+
- 9:30am - 12:30pm : implementing and porting
- 1:00pm - 7:00pm : finish porting the drawing and basic shapes
### 27 Jul 2021
+
- 10:00am - 12:30pm : write API documentation and check coding standard compliance
- 1:00pm - 1:30pm : check git workflow and create branches/pull request etc.
### 28 Jul 2021
+
- 9:00am - 9:40am : check webgl ANGLE instance drawing, decide to postpone it, because 1. it is not KISS; 2. it may not significant improve the performance; 3. it can be implemented orthorgonally with the current implementation
- 9:40am - 10:20am : implemented the color library
- 10:20am - 16:40pm : implement anaglyph and hollusion animation
- 16:40pm - 17:00pm : touch up the documentation and comments
### 31 Jul 2021
+
- 11:00am - 13:15pm : implementing the image rune feature
### 2 Aug 2021
+
- 12:00pm - 1:00pm : meeting
### 5 Aug 2021
+
- 14:30pm - 15:10pm : fix bugs
-###
+###
+
- 12:30pm - 1:00pm : working on #88
### 17 Aug 2021
+
- 18:00pm - 18:30pm : working on beside_frac and stack_frac definition
- 18:30pm - 19:00pm : fix the documentation of types #86
### 18 Aug 2021
+
- 21:50pm - 22:20pm : fix sail/triangle
### 19 Aug 2021
+
- 21:10pm - 23:20pm : fix the anaglyph/hollusion inverted problem #93, and improves CPU consumption of animation by limiting the framerate.
### 21 Aug 2021
+
- 18:00pm - 21:00pm : fix the memory leak / high memomry consumption by hollusion #95
### 5 Sep 2021
-- 12:30 - 13:30 : fix #97 #100
\ No newline at end of file
+
+- 12:30 - 13:30 : fix #97 #100
diff --git a/src/bundles/rune_in_words/functions.ts b/src/bundles/rune_in_words/functions.ts
index d40a90e84..90c84f9b5 100644
--- a/src/bundles/rune_in_words/functions.ts
+++ b/src/bundles/rune_in_words/functions.ts
@@ -1,16 +1,16 @@
import type { Rune } from './rune';
import {
- getSquare,
getBlank,
- getRcross,
- getSail,
- getTriangle,
- getCorner,
- getNova,
getCircle,
+ getCorner,
getHeart,
+ getNova,
getPentagram,
+ getRcross,
getRibbon,
+ getSail,
+ getSquare,
+ getTriangle,
throwIfNotRune
} from './runes_ops';
@@ -277,7 +277,11 @@ export function turn_upside_down(rune: string): string {
*
* @category Main
*/
-export function beside_frac(frac: number, rune1: string, rune2: string): string {
+export function beside_frac(
+ frac: number,
+ rune1: string,
+ rune2: string
+): string {
throwIfNotRune(beside_frac.name, rune1, rune2);
return `beside_frac(${frac}, ${rune1}, ${rune2})`;
@@ -378,7 +382,11 @@ export function repeat_pattern(
*
* @category Main
*/
-export function overlay_frac(frac: number, rune1: string, rune2: string): string {
+export function overlay_frac(
+ frac: number,
+ rune1: string,
+ rune2: string
+): string {
throwIfNotRune(overlay_frac.name, rune1);
throwIfNotRune(overlay_frac.name, rune2);
return `overlay_frac(${frac}, ${rune1}, ${rune2})`;
diff --git a/src/bundles/rune_in_words/index.ts b/src/bundles/rune_in_words/index.ts
index 1a65dffd4..676085565 100644
--- a/src/bundles/rune_in_words/index.ts
+++ b/src/bundles/rune_in_words/index.ts
@@ -45,8 +45,8 @@ export {
show,
square,
stack,
- stackn,
stack_frac,
+ stackn,
translate,
triangle,
turn_upside_down,
diff --git a/src/bundles/rune_in_words/runes_ops.ts b/src/bundles/rune_in_words/runes_ops.ts
index 51e31dac0..ccddab3a5 100644
--- a/src/bundles/rune_in_words/runes_ops.ts
+++ b/src/bundles/rune_in_words/runes_ops.ts
@@ -2,7 +2,7 @@
// Utility Functions
// =============================================================================
export function throwIfNotRune(name: string, ...runes: any) {
- runes.forEach((rune) => {
+ runes.forEach(rune => {
if (!(typeof rune === 'string')) {
throw Error(`${name} expects a rune (string) as argument.`);
}
diff --git a/src/bundles/scrabble/__tests__/index.ts b/src/bundles/scrabble/__tests__/index.ts
index 7d3dd7ba4..e0f20c16e 100644
--- a/src/bundles/scrabble/__tests__/index.ts
+++ b/src/bundles/scrabble/__tests__/index.ts
@@ -8,31 +8,25 @@ import {
// Test functions
test('get the word in the scrabble_words array at index 12', () => {
- expect(scrabble_words[12])
- .toBe('aardwolves');
+ expect(scrabble_words[12]).toBe('aardwolves');
});
test('get the word in the scrabble_letters array at index 100000', () => {
- expect(scrabble_letters[100000][0])
- .toBe('n');
+ expect(scrabble_letters[100000][0]).toBe('n');
});
test('scrabble_letters matches snapshot', () => {
- expect(scrabble_letters)
- .toMatchSnapshot();
+ expect(scrabble_letters).toMatchSnapshot();
});
test('scrabble_words matches snapshot', () => {
- expect(scrabble_words)
- .toMatchSnapshot();
+ expect(scrabble_words).toMatchSnapshot();
});
test('scrabble_letters_tiny matches snapshot', () => {
- expect(scrabble_letters_tiny)
- .toMatchSnapshot();
+ expect(scrabble_letters_tiny).toMatchSnapshot();
});
test('scrabble_words_tiny matches snapshot', () => {
- expect(scrabble_words_tiny)
- .toMatchSnapshot();
+ expect(scrabble_words_tiny).toMatchSnapshot();
});
diff --git a/src/bundles/scrabble/index.ts b/src/bundles/scrabble/index.ts
index 91d459a94..2a64a284d 100644
--- a/src/bundles/scrabble/index.ts
+++ b/src/bundles/scrabble/index.ts
@@ -3,8 +3,8 @@
* @author Martin Henz
*/
export {
- scrabble_words,
scrabble_letters,
- scrabble_words_tiny,
- scrabble_letters_tiny
+ scrabble_letters_tiny,
+ scrabble_words,
+ scrabble_words_tiny
} from './functions';
diff --git a/src/bundles/sound/__tests__/sound.test.ts b/src/bundles/sound/__tests__/sound.test.ts
index b304adc13..bca8d232a 100644
--- a/src/bundles/sound/__tests__/sound.test.ts
+++ b/src/bundles/sound/__tests__/sound.test.ts
@@ -2,8 +2,9 @@ import { make_sound, play, play_in_tab } from '../functions';
describe('Test make_sound', () => {
test('Should error gracefully when duration is negative', () => {
- expect(() => make_sound(() => 0, -1))
- .toThrowErrorMatchingInlineSnapshot('"Sound duration must be greater than or equal to 0"');
+ expect(() => make_sound(() => 0, -1)).toThrowErrorMatchingInlineSnapshot(
+ '"Sound duration must be greater than or equal to 0"'
+ );
});
test('Should not error when duration is zero', () => {
@@ -13,26 +14,28 @@ describe('Test make_sound', () => {
describe('Test play', () => {
test('Should error gracefully when duration is negative', () => {
- const sound = [(t) => 0, -1];
- expect(() => play(sound as any))
- .toThrowErrorMatchingInlineSnapshot('"play: duration of sound is negative"');
+ const sound = [t => 0, -1];
+ expect(() => play(sound as any)).toThrowErrorMatchingInlineSnapshot(
+ '"play: duration of sound is negative"'
+ );
});
test('Should not error when duration is zero', () => {
- const sound = make_sound((t) => 0, 0);
+ const sound = make_sound(t => 0, 0);
expect(() => play(sound)).not.toThrow();
});
});
describe('Test play_in_tab', () => {
test('Should error gracefully when duration is negative', () => {
- const sound = [(t) => 0, -1];
- expect(() => play_in_tab(sound as any))
- .toThrowErrorMatchingInlineSnapshot('"play_in_tab: duration of sound is negative"');
+ const sound = [t => 0, -1];
+ expect(() => play_in_tab(sound as any)).toThrowErrorMatchingInlineSnapshot(
+ '"play_in_tab: duration of sound is negative"'
+ );
});
test('Should not error when duration is zero', () => {
- const sound = make_sound((t) => 0, 0);
+ const sound = make_sound(t => 0, 0);
expect(() => play_in_tab(sound)).not.toThrow();
});
});
diff --git a/src/bundles/sound/functions.ts b/src/bundles/sound/functions.ts
index 33ae8a92d..6c87c70fa 100644
--- a/src/bundles/sound/functions.ts
+++ b/src/bundles/sound/functions.ts
@@ -1,23 +1,23 @@
/* eslint-disable new-cap, @typescript-eslint/naming-convention */
import context from 'js-slang/context';
import {
- pair,
+ accumulate,
head,
- tail,
- list,
- length,
is_null,
is_pair,
- accumulate,
+ length,
+ list,
+ pair,
+ tail,
type List
} from 'js-slang/dist/stdlib/list';
import { RIFFWAVE } from './riffwave';
import type {
- Wave,
+ AudioPlayed,
Sound,
SoundProducer,
SoundTransformer,
- AudioPlayed
+ Wave
} from './types';
// Global Constants and Variables
@@ -43,7 +43,7 @@ function init_audioCtx(): void {
// linear decay from 1 to 0 over decay_period
function linear_decay(decay_period: number): (t: number) => number {
- return (t) => {
+ return t => {
if (t > decay_period || t < 0) {
return 0;
}
@@ -89,7 +89,7 @@ function setPermissionToFalse() {
function start_recording(mediaRecorder: MediaRecorder) {
const data: any[] = [];
- mediaRecorder.ondataavailable = (e) => e.data.size && data.push(e.data);
+ mediaRecorder.ondataavailable = e => e.data.size && data.push(e.data);
mediaRecorder.start();
mediaRecorder.onstop = () => process(data);
}
@@ -110,21 +110,20 @@ function process(data) {
const blob = new Blob(data);
convertToArrayBuffer(blob)
- .then((arrayBuffer) => audioContext.decodeAudioData(arrayBuffer))
+ .then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer))
.then(save);
}
// Converts input microphone sound (blob) into array format.
function convertToArrayBuffer(blob: Blob): Promise {
const url = URL.createObjectURL(blob);
- return fetch(url)
- .then((response) => response.arrayBuffer());
+ return fetch(url).then(response => response.arrayBuffer());
}
function save(audioBuffer: AudioBuffer) {
const array = audioBuffer.getChannelData(0);
const duration = array.length / FS;
- recorded_sound = make_sound((t) => {
+ recorded_sound = make_sound(t => {
const index = t * FS;
const lowerIndex = Math.floor(index);
const upperIndex = lowerIndex + 1;
@@ -289,9 +288,9 @@ export function get_duration(sound: Sound): number {
*/
export function is_sound(x: any): x is Sound {
return (
- is_pair(x)
- && typeof get_wave(x) === 'function'
- && typeof get_duration(x) === 'number'
+ is_pair(x) &&
+ typeof get_wave(x) === 'function' &&
+ typeof get_duration(x) === 'number'
);
}
@@ -319,10 +318,14 @@ export function play_wave(wave: Wave, duration: number): Sound {
export function play_in_tab(sound: Sound): Sound {
// Type-check sound
if (!is_sound(sound)) {
- throw new Error(`${play_in_tab.name} is expecting sound, but encountered ${sound}`);
+ throw new Error(
+ `${play_in_tab.name} is expecting sound, but encountered ${sound}`
+ );
// If a sound is already playing, terminate execution.
} else if (isPlaying) {
- throw new Error(`${play_in_tab.name}: audio system still playing previous sound`);
+ throw new Error(
+ `${play_in_tab.name}: audio system still playing previous sound`
+ );
} else if (get_duration(sound) < 0) {
throw new Error(`${play_in_tab.name}: duration of sound is negative`);
} else if (get_duration(sound) === 0) {
@@ -468,7 +471,7 @@ export function stop(): void {
* @example noise_sound(5);
*/
export function noise_sound(duration: number): Sound {
- return make_sound((_t) => Math.random() * 2 - 1, duration);
+ return make_sound(_t => Math.random() * 2 - 1, duration);
}
/**
@@ -479,7 +482,7 @@ export function noise_sound(duration: number): Sound {
* @example silence_sound(5);
*/
export function silence_sound(duration: number): Sound {
- return make_sound((_t) => 0, duration);
+ return make_sound(_t => 0, duration);
}
/**
@@ -491,7 +494,7 @@ export function silence_sound(duration: number): Sound {
* @example sine_sound(440, 5);
*/
export function sine_sound(freq: number, duration: number): Sound {
- return make_sound((t) => Math.sin(2 * Math.PI * t * freq), duration);
+ return make_sound(t => Math.sin(2 * Math.PI * t * freq), duration);
}
/**
@@ -510,10 +513,7 @@ export function square_sound(f: number, duration: number): Sound {
}
return answer;
}
- return make_sound(
- (t) => (4 / Math.PI) * fourier_expansion_square(t),
- duration
- );
+ return make_sound(t => (4 / Math.PI) * fourier_expansion_square(t), duration);
}
/**
@@ -528,14 +528,14 @@ export function triangle_sound(freq: number, duration: number): Sound {
function fourier_expansion_triangle(t: number) {
let answer = 0;
for (let i = 0; i < fourier_expansion_level; i += 1) {
- answer
- += ((-1) ** i * Math.sin((2 * i + 1) * t * freq * Math.PI * 2))
- / (2 * i + 1) ** 2;
+ answer +=
+ ((-1) ** i * Math.sin((2 * i + 1) * t * freq * Math.PI * 2)) /
+ (2 * i + 1) ** 2;
}
return answer;
}
return make_sound(
- (t) => (8 / Math.PI / Math.PI) * fourier_expansion_triangle(t),
+ t => (8 / Math.PI / Math.PI) * fourier_expansion_triangle(t),
duration
);
}
@@ -557,7 +557,7 @@ export function sawtooth_sound(freq: number, duration: number): Sound {
return answer;
}
return make_sound(
- (t) => 1 / 2 - (1 / Math.PI) * fourier_expansion_sawtooth(t),
+ t => 1 / 2 - (1 / Math.PI) * fourier_expansion_sawtooth(t),
duration
);
}
@@ -638,30 +638,30 @@ export function adsr(
sustain_level: number,
release_ratio: number
): SoundTransformer {
- return (sound) => {
+ return sound => {
const wave = get_wave(sound);
const duration = get_duration(sound);
const attack_time = duration * attack_ratio;
const decay_time = duration * decay_ratio;
const release_time = duration * release_ratio;
- return make_sound((x) => {
+ return make_sound(x => {
if (x < attack_time) {
return wave(x) * (x / attack_time);
}
if (x < attack_time + decay_time) {
return (
- ((1 - sustain_level) * linear_decay(decay_time)(x - attack_time)
- + sustain_level)
- * wave(x)
+ ((1 - sustain_level) * linear_decay(decay_time)(x - attack_time) +
+ sustain_level) *
+ wave(x)
);
}
if (x < duration - release_time) {
return wave(x) * sustain_level;
}
return (
- wave(x)
- * sustain_level
- * linear_decay(release_time)(x - (duration - release_time))
+ wave(x) *
+ sustain_level *
+ linear_decay(release_time)(x - (duration - release_time))
);
}, duration);
};
@@ -698,7 +698,8 @@ export function stacking_adsr(
return simultaneously(
accumulate(
- (x: any, y: any) => pair(tail(x)(waveform(base_frequency * head(x), duration)), y),
+ (x: any, y: any) =>
+ pair(tail(x)(waveform(base_frequency * head(x), duration)), y),
null,
zip(envelopes, 1)
)
@@ -724,10 +725,11 @@ export function phase_mod(
duration: number,
amount: number
): SoundTransformer {
- return (modulator: Sound) => make_sound(
- (t) => Math.sin(2 * Math.PI * t * freq + amount * get_wave(modulator)(t)),
- duration
- );
+ return (modulator: Sound) =>
+ make_sound(
+ t => Math.sin(2 * Math.PI * t * freq + amount * get_wave(modulator)(t)),
+ duration
+ );
}
// MIDI conversion functions
diff --git a/src/bundles/sound/index.ts b/src/bundles/sound/index.ts
index cdb273294..c593ec447 100644
--- a/src/bundles/sound/index.ts
+++ b/src/bundles/sound/index.ts
@@ -45,9 +45,9 @@ export {
noise_sound,
phase_mod,
piano,
+ play,
// Play-related
play_in_tab,
- play,
play_wave,
record,
record_for,
diff --git a/src/bundles/sound/riffwave.ts b/src/bundles/sound/riffwave.ts
index 70a1af751..915c9d677 100644
--- a/src/bundles/sound/riffwave.ts
+++ b/src/bundles/sound/riffwave.ts
@@ -54,7 +54,7 @@ var FastBase64 = {
dst += '=';
}
return dst;
- }, // end Encode
+ } // end Encode
};
FastBase64.Init();
@@ -78,7 +78,7 @@ export function RIFFWAVE(this: any, data) {
blockAlign: 0, // 32 2 NumChannels*BitsPerSample/8
bitsPerSample: 8, // 34 2 8 bits = 8, 16 bits = 16
subChunk2Id: [0x64, 0x61, 0x74, 0x61], // 36 4 "data" = 0x64617461
- subChunk2Size: 0, // 40 4 data size = NumSamples*NumChannels*BitsPerSample/8
+ subChunk2Size: 0 // 40 4 data size = NumSamples*NumChannels*BitsPerSample/8
};
function u32ToArray(i) {
diff --git a/src/bundles/sound/types.ts b/src/bundles/sound/types.ts
index 5788c017c..0d1ec5998 100644
--- a/src/bundles/sound/types.ts
+++ b/src/bundles/sound/types.ts
@@ -14,5 +14,5 @@ export type AudioPlayed = {
};
export type SoundModuleState = {
- audioPlayed: AudioPlayed[]
+ audioPlayed: AudioPlayed[];
};
diff --git a/src/bundles/sound_matrix/functions.ts b/src/bundles/sound_matrix/functions.ts
index 4198d6460..eba896c98 100644
--- a/src/bundles/sound_matrix/functions.ts
+++ b/src/bundles/sound_matrix/functions.ts
@@ -219,7 +219,7 @@ ToneMatrix.initialise_matrix = initialise_matrix;
function bind_events_to_rect(c) {
c.addEventListener(
'click',
- (event) => {
+ event => {
// calculate the x, y coordinates of the click event
const rect = c.getBoundingClientRect();
const offset_top = rect.top + document.documentElement.scrollTop;
diff --git a/src/bundles/sound_matrix/index.ts b/src/bundles/sound_matrix/index.ts
index ad42ec791..95bc3e522 100644
--- a/src/bundles/sound_matrix/index.ts
+++ b/src/bundles/sound_matrix/index.ts
@@ -8,8 +8,8 @@
export {
// Constructor/Accessors/Typecheck
ToneMatrix,
- get_matrix,
+ clear_all_timeout,
clear_matrix,
- set_timeout,
- clear_all_timeout
+ get_matrix,
+ set_timeout
} from './functions';
diff --git a/src/bundles/sound_matrix/list.ts b/src/bundles/sound_matrix/list.ts
index 461fd31b9..4b0c22596 100644
--- a/src/bundles/sound_matrix/list.ts
+++ b/src/bundles/sound_matrix/list.ts
@@ -142,9 +142,9 @@ export function map(f, xs) {
export function build_list(n, fun) {
if (typeof n !== 'number' || n < 0 || Math.floor(n) !== n) {
throw new Error(
- 'build_list(n, fun) expects a positive integer as '
- + 'argument n, but encountered '
- + n
+ 'build_list(n, fun) expects a positive integer as ' +
+ 'argument n, but encountered ' +
+ n
);
}
@@ -296,14 +296,14 @@ export function filter(pred, xs) {
export function enum_list(start, end) {
if (typeof start !== 'number') {
throw new Error(
- 'enum_list(start, end) expects a number as argument start, but encountered '
- + start
+ 'enum_list(start, end) expects a number as argument start, but encountered ' +
+ start
);
}
if (typeof end !== 'number') {
throw new Error(
- 'enum_list(start, end) expects a number as argument start, but encountered '
- + end
+ 'enum_list(start, end) expects a number as argument start, but encountered ' +
+ end
);
}
if (start > end) {
@@ -317,8 +317,8 @@ export function enum_list(start, end) {
export function list_ref(xs, n) {
if (typeof n !== 'number' || n < 0 || Math.floor(n) !== n) {
throw new Error(
- 'list_ref(xs, n) expects a positive integer as argument n, but encountered '
- + n
+ 'list_ref(xs, n) expects a positive integer as argument n, but encountered ' +
+ n
);
}
for (; n > 0; --n) {
diff --git a/src/bundles/stereo_sound/functions.ts b/src/bundles/stereo_sound/functions.ts
index 42536c428..f510375e3 100644
--- a/src/bundles/stereo_sound/functions.ts
+++ b/src/bundles/stereo_sound/functions.ts
@@ -44,7 +44,7 @@ function init_audioCtx(): void {
// linear decay from 1 to 0 over decay_period
function linear_decay(decay_period: number): (t: number) => number {
- return (t) => {
+ return t => {
if (t > decay_period || t < 0) {
return 0;
}
@@ -90,7 +90,7 @@ function setPermissionToFalse() {
function start_recording(mediaRecorder: MediaRecorder) {
const data: any[] = [];
- mediaRecorder.ondataavailable = (e) => e.data.size && data.push(e.data);
+ mediaRecorder.ondataavailable = e => e.data.size && data.push(e.data);
mediaRecorder.start();
mediaRecorder.onstop = () => process(data);
}
@@ -109,21 +109,20 @@ function process(data: any[] | undefined) {
const blob = new Blob(data);
convertToArrayBuffer(blob)
- .then((arrayBuffer) => audioContext.decodeAudioData(arrayBuffer))
+ .then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer))
.then(save);
}
// Converts input microphone sound (blob) into array format.
function convertToArrayBuffer(blob: Blob): Promise {
const url = URL.createObjectURL(blob);
- return fetch(url)
- .then((response) => response.arrayBuffer());
+ return fetch(url).then(response => response.arrayBuffer());
}
function save(audioBuffer: AudioBuffer) {
const array = audioBuffer.getChannelData(0);
const duration = array.length / FS;
- recorded_sound = make_sound((t) => {
+ recorded_sound = make_sound(t => {
const index = t * FS;
const lowerIndex = Math.floor(index);
const upperIndex = lowerIndex + 1;
@@ -312,10 +311,10 @@ export function get_duration(sound: Sound): number {
*/
export function is_sound(x: any): boolean {
return (
- is_pair(x)
- && typeof get_left_wave(x) === 'function'
- && typeof get_right_wave(x) === 'function'
- && typeof get_duration(x) === 'number'
+ is_pair(x) &&
+ typeof get_left_wave(x) === 'function' &&
+ typeof get_right_wave(x) === 'function' &&
+ typeof get_duration(x) === 'number'
);
}
@@ -341,11 +340,7 @@ export function play_wave(wave: Wave, duration: number): Sound {
* @return the given Sound
* @example play_waves(t => math_sin(t * 3000), t => math_sin(t * 6000), 5);
*/
-export function play_waves(
- wave1: Wave,
- wave2: Wave,
- duration: number
-): Sound {
+export function play_waves(wave1: Wave, wave2: Wave, duration: number): Sound {
return play(make_stereo_sound(wave1, wave2, duration));
}
@@ -361,10 +356,14 @@ export function play_waves(
export function play_in_tab(sound: Sound): Sound {
// Type-check sound
if (!is_sound(sound)) {
- throw new Error(`${play_in_tab.name} is expecting sound, but encountered ${sound}`);
+ throw new Error(
+ `${play_in_tab.name} is expecting sound, but encountered ${sound}`
+ );
// If a sound is already playing, terminate execution.
} else if (isPlaying) {
- throw new Error(`${play_in_tab.name}: audio system still playing previous sound`);
+ throw new Error(
+ `${play_in_tab.name}: audio system still playing previous sound`
+ );
} else if (get_duration(sound) < 0) {
throw new Error(`${play_in_tab.name}: duration of sound is negative`);
} else if (get_duration(sound) === 0) {
@@ -398,8 +397,8 @@ export function play_in_tab(sound: Sound): Sound {
// smoothen out sudden cut-outs
if (
- channel[2 * i] === 0
- && Math.abs(channel[2 * i] - Lprev_value) > 0.01
+ channel[2 * i] === 0 &&
+ Math.abs(channel[2 * i] - Lprev_value) > 0.01
) {
channel[2 * i] = Lprev_value * 0.999;
}
@@ -418,8 +417,8 @@ export function play_in_tab(sound: Sound): Sound {
// smoothen out sudden cut-outs
if (
- channel[2 * i + 1] === 0
- && Math.abs(channel[2 * i] - Rprev_value) > 0.01
+ channel[2 * i + 1] === 0 &&
+ Math.abs(channel[2 * i] - Rprev_value) > 0.01
) {
channel[2 * i + 1] = Rprev_value * 0.999;
}
@@ -459,7 +458,9 @@ export function play_in_tab(sound: Sound): Sound {
export function play(sound: Sound): Sound {
// Type-check sound
if (!is_sound(sound)) {
- throw new Error(`${play.name} is expecting sound, but encountered ${sound}`);
+ throw new Error(
+ `${play.name} is expecting sound, but encountered ${sound}`
+ );
// If a sound is already playing, terminate execution.
} else if (isPlaying) {
throw new Error(`${play.name}: audio system still playing previous sound`);
@@ -496,8 +497,8 @@ export function play(sound: Sound): Sound {
// smoothen out sudden cut-outs
if (
- channel[2 * i] === 0
- && Math.abs(channel[2 * i] - Lprev_value) > 0.01
+ channel[2 * i] === 0 &&
+ Math.abs(channel[2 * i] - Lprev_value) > 0.01
) {
channel[2 * i] = Lprev_value * 0.999;
}
@@ -516,8 +517,8 @@ export function play(sound: Sound): Sound {
// smoothen out sudden cut-outs
if (
- channel[2 * i + 1] === 0
- && Math.abs(channel[2 * i] - Rprev_value) > 0.01
+ channel[2 * i + 1] === 0 &&
+ Math.abs(channel[2 * i] - Rprev_value) > 0.01
) {
channel[2 * i + 1] = Rprev_value * 0.999;
}
@@ -570,7 +571,7 @@ export function stop(): void {
export function squash(sound: Sound): Sound {
const left = get_left_wave(sound);
const right = get_right_wave(sound);
- return make_sound((t) => 0.5 * (left(t) + right(t)), get_duration(sound));
+ return make_sound(t => 0.5 * (left(t) + right(t)), get_duration(sound));
}
/**
@@ -582,7 +583,7 @@ export function squash(sound: Sound): Sound {
* @return a Sound Transformer that pans a Sound
*/
export function pan(amount: number): SoundTransformer {
- return (sound) => {
+ return sound => {
if (amount > 1) {
amount = 1;
}
@@ -591,8 +592,8 @@ export function pan(amount: number): SoundTransformer {
}
sound = squash(sound);
return make_stereo_sound(
- (t) => ((1 - amount) / 2) * get_left_wave(sound)(t),
- (t) => ((1 + amount) / 2) * get_right_wave(sound)(t),
+ t => ((1 - amount) / 2) * get_left_wave(sound)(t),
+ t => ((1 + amount) / 2) * get_right_wave(sound)(t),
get_duration(sound)
);
};
@@ -618,11 +619,11 @@ export function pan_mod(modulator: Sound): SoundTransformer {
}
return output;
};
- return (sound) => {
+ return sound => {
sound = squash(sound);
return make_stereo_sound(
- (t) => ((1 - amount(t)) / 2) * get_left_wave(sound)(t),
- (t) => ((1 + amount(t)) / 2) * get_right_wave(sound)(t),
+ t => ((1 - amount(t)) / 2) * get_left_wave(sound)(t),
+ t => ((1 + amount(t)) / 2) * get_right_wave(sound)(t),
get_duration(sound)
);
};
@@ -638,7 +639,7 @@ export function pan_mod(modulator: Sound): SoundTransformer {
* @example noise_sound(5);
*/
export function noise_sound(duration: number): Sound {
- return make_sound((_t) => Math.random() * 2 - 1, duration);
+ return make_sound(_t => Math.random() * 2 - 1, duration);
}
/**
@@ -649,7 +650,7 @@ export function noise_sound(duration: number): Sound {
* @example silence_sound(5);
*/
export function silence_sound(duration: number): Sound {
- return make_sound((_t) => 0, duration);
+ return make_sound(_t => 0, duration);
}
/**
@@ -661,7 +662,7 @@ export function silence_sound(duration: number): Sound {
* @example sine_sound(440, 5);
*/
export function sine_sound(freq: number, duration: number): Sound {
- return make_sound((t) => Math.sin(2 * Math.PI * t * freq), duration);
+ return make_sound(t => Math.sin(2 * Math.PI * t * freq), duration);
}
/**
@@ -680,10 +681,7 @@ export function square_sound(f: number, duration: number): Sound {
}
return answer;
}
- return make_sound(
- (t) => (4 / Math.PI) * fourier_expansion_square(t),
- duration
- );
+ return make_sound(t => (4 / Math.PI) * fourier_expansion_square(t), duration);
}
/**
@@ -698,14 +696,14 @@ export function triangle_sound(freq: number, duration: number): Sound {
function fourier_expansion_triangle(t: number) {
let answer = 0;
for (let i = 0; i < fourier_expansion_level; i += 1) {
- answer
- += ((-1) ** i * Math.sin((2 * i + 1) * t * freq * Math.PI * 2))
- / (2 * i + 1) ** 2;
+ answer +=
+ ((-1) ** i * Math.sin((2 * i + 1) * t * freq * Math.PI * 2)) /
+ (2 * i + 1) ** 2;
}
return answer;
}
return make_sound(
- (t) => (8 / Math.PI / Math.PI) * fourier_expansion_triangle(t),
+ t => (8 / Math.PI / Math.PI) * fourier_expansion_triangle(t),
duration
);
}
@@ -727,7 +725,7 @@ export function sawtooth_sound(freq: number, duration: number): Sound {
return answer;
}
return make_sound(
- (t) => 1 / 2 - (1 / Math.PI) * fourier_expansion_sawtooth(t),
+ t => 1 / 2 - (1 / Math.PI) * fourier_expansion_sawtooth(t),
duration
);
}
@@ -756,7 +754,11 @@ export function consecutively(list_of_sounds: List): Sound {
const new_right = (t: number) => (t < dur1 ? Rwave1(t) : Rwave2(t - dur1));
return make_stereo_sound(new_left, new_right, dur1 + dur2);
}
- return accumulate(stereo_cons_two, silence_sound(0), list_of_sounds);
+ return accumulate(
+ stereo_cons_two,
+ silence_sound(0),
+ list_of_sounds
+ );
}
/**
@@ -790,8 +792,10 @@ export function simultaneously(list_of_sounds: List): Sound {
list_of_sounds
);
const sounds_length = length(list_of_sounds);
- const normalised_left = (t: number) => head(head(unnormed))(t) / sounds_length;
- const normalised_right = (t: number) => tail(head(unnormed))(t) / sounds_length;
+ const normalised_left = (t: number) =>
+ head(head(unnormed))(t) / sounds_length;
+ const normalised_right = (t: number) =>
+ tail(head(unnormed))(t) / sounds_length;
const highest_duration = tail(unnormed);
return make_stereo_sound(normalised_left, normalised_right, highest_duration);
}
@@ -817,7 +821,7 @@ export function adsr(
sustain_level: number,
release_ratio: number
): SoundTransformer {
- return (sound) => {
+ return sound => {
const Lwave = get_left_wave(sound);
const Rwave = get_right_wave(sound);
const duration = get_duration(sound);
@@ -832,18 +836,18 @@ export function adsr(
}
if (x < attack_time + decay_time) {
return (
- ((1 - sustain_level) * linear_decay(decay_time)(x - attack_time)
- + sustain_level)
- * wave(x)
+ ((1 - sustain_level) * linear_decay(decay_time)(x - attack_time) +
+ sustain_level) *
+ wave(x)
);
}
if (x < duration - release_time) {
return wave(x) * sustain_level;
}
return (
- wave(x)
- * sustain_level
- * linear_decay(release_time)(x - (duration - release_time))
+ wave(x) *
+ sustain_level *
+ linear_decay(release_time)(x - (duration - release_time))
);
};
}
@@ -882,7 +886,8 @@ export function stacking_adsr(
return simultaneously(
accumulate(
- (x: any, y: any) => pair(tail(x)(waveform(base_frequency * head(x), duration)), y),
+ (x: any, y: any) =>
+ pair(tail(x)(waveform(base_frequency * head(x), duration)), y),
null,
zip(envelopes, 1)
)
@@ -908,13 +913,16 @@ export function phase_mod(
duration: number,
amount: number
): SoundTransformer {
- return (modulator: Sound) => make_stereo_sound(
- (t) => Math.sin(2 * Math.PI * t * freq + amount * get_left_wave(modulator)(t)),
- (t) => Math.sin(
- 2 * Math.PI * t * freq + amount * get_right_wave(modulator)(t)
- ),
- duration
- );
+ return (modulator: Sound) =>
+ make_stereo_sound(
+ t =>
+ Math.sin(2 * Math.PI * t * freq + amount * get_left_wave(modulator)(t)),
+ t =>
+ Math.sin(
+ 2 * Math.PI * t * freq + amount * get_right_wave(modulator)(t)
+ ),
+ duration
+ );
}
// MIDI conversion functions
diff --git a/src/bundles/stereo_sound/index.ts b/src/bundles/stereo_sound/index.ts
index 6633c5a90..1d63940e7 100644
--- a/src/bundles/stereo_sound/index.ts
+++ b/src/bundles/stereo_sound/index.ts
@@ -13,47 +13,47 @@
* @author Samyukta Sounderraman
*/
export {
- // Constructor/Accessors/Typecheck
- make_stereo_sound,
- make_sound,
+ adsr,
+ // Instruments
+ bell,
+ cello,
+ // Composition and Envelopes
+ consecutively,
+ get_duration,
get_left_wave,
get_right_wave,
- get_duration,
+ // Recording
+ init_record,
is_sound,
- squash,
+ letter_name_to_frequency,
+ // MIDI
+ letter_name_to_midi_note,
+ make_sound,
+ // Constructor/Accessors/Typecheck
+ make_stereo_sound,
+ midi_note_to_frequency,
+ // Basic waveforms
+ noise_sound,
pan,
pan_mod,
+ phase_mod,
+ piano,
+ play,
// Play-related
play_in_tab,
play_wave,
play_waves,
- play,
- stop,
- // Recording
- init_record,
record,
record_for,
- // Composition and Envelopes
- consecutively,
- simultaneously,
- phase_mod,
- adsr,
- stacking_adsr,
- // Basic waveforms
- noise_sound,
+ sawtooth_sound,
silence_sound,
+ simultaneously,
sine_sound,
- sawtooth_sound,
- triangle_sound,
square_sound,
- // MIDI
- letter_name_to_midi_note,
- midi_note_to_frequency,
- letter_name_to_frequency,
- // Instruments
- bell,
- cello,
- piano,
+ squash,
+ stacking_adsr,
+ stop,
+ triangle_sound,
trombone,
violin
} from './functions';
diff --git a/src/bundles/stereo_sound/riffwave.ts b/src/bundles/stereo_sound/riffwave.ts
index 70a1af751..915c9d677 100644
--- a/src/bundles/stereo_sound/riffwave.ts
+++ b/src/bundles/stereo_sound/riffwave.ts
@@ -54,7 +54,7 @@ var FastBase64 = {
dst += '=';
}
return dst;
- }, // end Encode
+ } // end Encode
};
FastBase64.Init();
@@ -78,7 +78,7 @@ export function RIFFWAVE(this: any, data) {
blockAlign: 0, // 32 2 NumChannels*BitsPerSample/8
bitsPerSample: 8, // 34 2 8 bits = 8, 16 bits = 16
subChunk2Id: [0x64, 0x61, 0x74, 0x61], // 36 4 "data" = 0x64617461
- subChunk2Size: 0, // 40 4 data size = NumSamples*NumChannels*BitsPerSample/8
+ subChunk2Size: 0 // 40 4 data size = NumSamples*NumChannels*BitsPerSample/8
};
function u32ToArray(i) {
diff --git a/src/bundles/unity_academy/UnityAcademy.tsx b/src/bundles/unity_academy/UnityAcademy.tsx
index 5b865858a..c0182b429 100644
--- a/src/bundles/unity_academy/UnityAcademy.tsx
+++ b/src/bundles/unity_academy/UnityAcademy.tsx
@@ -9,68 +9,75 @@ import { Button } from '@blueprintjs/core';
import { IconNames } from '@blueprintjs/icons';
import React from 'react';
import ReactDOM from 'react-dom';
-import { Vector3, normalizeVector, zeroVector, pointDistance } from './UnityAcademyMaths';
-import { UNITY_ACADEMY_BACKEND_URL, BUILD_NAME } from './config';
+import {
+ Vector3,
+ normalizeVector,
+ pointDistance,
+ zeroVector
+} from './UnityAcademyMaths';
+import { BUILD_NAME, UNITY_ACADEMY_BACKEND_URL } from './config';
type Transform = {
- position : Vector3;
- rotation : Vector3;
- scale : Vector3;
+ position: Vector3;
+ rotation: Vector3;
+ scale: Vector3;
};
type StudentGameObject = {
- startMethod : Function | null;
- updateMethod : Function | null;
- onCollisionEnterMethod : Function | null;
- onCollisionStayMethod : Function | null;
- onCollisionExitMethod : Function | null;
- transform : Transform;
- rigidbody : RigidbodyData | null;
- audioSource : AudioSourceData | null;
- customProperties : any;
- isDestroyed : boolean; // [set by interop]
+ startMethod: Function | null;
+ updateMethod: Function | null;
+ onCollisionEnterMethod: Function | null;
+ onCollisionStayMethod: Function | null;
+ onCollisionExitMethod: Function | null;
+ transform: Transform;
+ rigidbody: RigidbodyData | null;
+ audioSource: AudioSourceData | null;
+ customProperties: any;
+ isDestroyed: boolean; // [set by interop]
};
type InputData = {
- keyboardInputInfo : { [key : string] : number };
+ keyboardInputInfo: { [key: string]: number };
};
type RigidbodyData = {
- velocity : Vector3;
- angularVelocity : Vector3;
- mass : number;
- useGravity : boolean;
- drag : number;
- angularDrag : number;
+ velocity: Vector3;
+ angularVelocity: Vector3;
+ mass: number;
+ useGravity: boolean;
+ drag: number;
+ angularDrag: number;
};
type AudioSourceData = {
- audioClipIdentifier : AudioClipIdentifier;
- playSpeed : number;
- playProgress : number;
- volume : number;
- isLooping : boolean;
- isPlaying : boolean;
+ audioClipIdentifier: AudioClipIdentifier;
+ playSpeed: number;
+ playProgress: number;
+ volume: number;
+ isLooping: boolean;
+ isPlaying: boolean;
};
-declare const createUnityInstance : Function; // This function comes from {BUILD_NAME}.loader.js in Unity Academy Application (For Example: ua-frontend-prod.loader.js)
+declare const createUnityInstance: Function; // This function comes from {BUILD_NAME}.loader.js in Unity Academy Application (For Example: ua-frontend-prod.loader.js)
-export function getInstance() : UnityAcademyJsInteropContext {
+export function getInstance(): UnityAcademyJsInteropContext {
return (window as any).unityAcademyContext as UnityAcademyJsInteropContext;
}
type AudioClipInternalName = string;
-export class AudioClipIdentifier { // A wrapper class to store identifier string and prevent users from using arbitrary string for idenfitier
- audioClipInternalName : AudioClipInternalName;
- constructor(audioClipInternalName : string) {
+export class AudioClipIdentifier {
+ // A wrapper class to store identifier string and prevent users from using arbitrary string for idenfitier
+ audioClipInternalName: AudioClipInternalName;
+ constructor(audioClipInternalName: string) {
this.audioClipInternalName = audioClipInternalName;
}
}
-export class GameObjectIdentifier { // A wrapper class to store identifier string and prevent users from using arbitrary string for idenfitier
- gameObjectIdentifier : string;
- constructor(gameObjectIdentifier : string) {
+export class GameObjectIdentifier {
+ // A wrapper class to store identifier string and prevent users from using arbitrary string for idenfitier
+ gameObjectIdentifier: string;
+ constructor(gameObjectIdentifier: string) {
this.gameObjectIdentifier = gameObjectIdentifier;
}
}
@@ -88,44 +95,54 @@ class UnityComponent extends React.Component {
render() {
const moduleInstance = getInstance();
return (
- //
-
-
+
-
Preparing to load Unity Academy...
+ left: '0%',
+ top: '0%',
+ zIndex: '9999'
+ }}
+ >
+
+
+ Preparing to load Unity Academy...
-
-
+
{
moduleInstance.setShowUnityComponent(0);
- }}// Note: Here if I directly use "this.moduleInstance......" instead using this lambda function, the "this" reference will become undefined and lead to a runtime error when user clicks the "Run" button
+ }} // Note: Here if I directly use "this.moduleInstance......" instead using this lambda function, the "this" reference will become undefined and lead to a runtime error when user clicks the "Run" button
text="Hide Unity Academy Window"
style={{
position: 'absolute',
@@ -153,8 +170,7 @@ class UnityComponent extends React.Component {
}
componentDidMount() {
- getInstance()
- .firstTimeLoadUnityApplication();
+ getInstance().firstTimeLoadUnityApplication();
}
}
@@ -166,33 +182,38 @@ const UNITY_CONFIG = {
streamingAssetsUrl: `${UNITY_ACADEMY_BACKEND_URL}webgl_assetbundles`,
companyName: 'Wang Zihan @ NUS SoC 2026',
productName: 'Unity Academy (Source Academy Embedding Version)',
- productVersion: 'See \'About\' in the embedded frontend.'
+ productVersion: "See 'About' in the embedded frontend."
};
class UnityAcademyJsInteropContext {
// private unityConfig : any;
- public unityInstance : any;
- private unityContainerElement : HTMLElement | null;
- private studentGameObjectStorage : { [gameObjectIdentifier : string] : StudentGameObject }; // [get by interop]
+ public unityInstance: any;
+ private unityContainerElement: HTMLElement | null;
+ private studentGameObjectStorage: {
+ [gameObjectIdentifier: string]: StudentGameObject;
+ }; // [get by interop]
private prefabInfo: any;
private gameObjectIdentifierSerialCounter = 0;
- private studentActionQueue : any; // [get / clear by interop]
+ private studentActionQueue: any; // [get / clear by interop]
private deltaTime = 0; // [set by interop]
- private input : InputData; // [set by interop] 0 = key idle, 1 = on key down, 2 = holding key, 3 = on key up
- public gameObjectIdentifierWrapperClass : any; // [get by interop] For interop to create the class instance with the correct type when calling users' Start and Update functions. Only the object with this class type can pass checkGameObjectIdentifierParameter in functions.ts
- private targetFrameRate : number;
+ private input: InputData; // [set by interop] 0 = key idle, 1 = on key down, 2 = holding key, 3 = on key up
+ public gameObjectIdentifierWrapperClass: any; // [get by interop] For interop to create the class instance with the correct type when calling users' Start and Update functions. Only the object with this class type can pass checkGameObjectIdentifierParameter in functions.ts
+ private targetFrameRate: number;
private unityInstanceState; // [set by interop]
- private guiData : any[]; // [get / clear by interop]
+ private guiData: any[]; // [get / clear by interop]
public dimensionMode;
- private isShowingUnityAcademy : boolean; // [get by interop]
- private latestUserAgreementVersion : string;
- private audioClipStorage : AudioClipInternalName[];
+ private isShowingUnityAcademy: boolean; // [get by interop]
+ private latestUserAgreementVersion: string;
+ private audioClipStorage: AudioClipInternalName[];
private audioClipIdentifierSerialCounter = 0;
constructor() {
this.unityInstance = null;
this.unityContainerElement = document.getElementById('unity_container');
- if (this.unityContainerElement === undefined || this.unityContainerElement === null) {
+ if (
+ this.unityContainerElement === undefined ||
+ this.unityContainerElement === null
+ ) {
this.unityContainerElement = document.createElement('div');
this.unityContainerElement.id = 'unity_container';
}
@@ -245,14 +266,16 @@ class UnityAcademyJsInteropContext {
this.unityInstanceState = 'LoadingInstance';
const canvas = document.querySelector('#unity-canvas');
const unity_load_info = document.querySelector('#unity_load_info');
- createUnityInstance(canvas, UNITY_CONFIG, (progress) => {
- unity_load_info!.innerHTML = `Loading Unity Academy ( ${Math.floor(progress * 100)}% )`;
+ createUnityInstance(canvas, UNITY_CONFIG, progress => {
+ unity_load_info!.innerHTML = `Loading Unity Academy ( ${Math.floor(
+ progress * 100
+ )}% )`;
})
- .then((unityInstance) => {
+ .then(unityInstance => {
this.unityInstance = unityInstance;
unity_load_info!.innerHTML = '';
})
- .catch((message) => {
+ .catch(message => {
alert(message);
});
}
@@ -277,13 +300,19 @@ class UnityAcademyJsInteropContext {
if (toShow) {
(this.unityContainerElement as any).style.visibility = 'visible';
if (this.unityInstance !== null) {
- this.unityInstance[sendMessageFunctionName]('GameManager', 'WakeUpApplication');
+ this.unityInstance[sendMessageFunctionName](
+ 'GameManager',
+ 'WakeUpApplication'
+ );
}
} else {
(this.unityContainerElement as any).style.visibility = 'hidden';
// Make Unity Academy Application sleep to conserve resources (pause rendering, etc)
if (this.unityInstance !== null) {
- this.unityInstance[sendMessageFunctionName]('GameManager', 'DoApplicationSleep');
+ this.unityInstance[sendMessageFunctionName](
+ 'GameManager',
+ 'DoApplicationSleep'
+ );
}
}
const unityCanvas = document.getElementById('unity-canvas') as any;
@@ -297,7 +326,11 @@ class UnityAcademyJsInteropContext {
terminate() {
if (this.unityInstance === null) return;
- if (!confirm('Do you really hope to terminate the current Unity Academy instance? If so, everything need to reload when you use Unity Academy again.')) {
+ if (
+ !confirm(
+ 'Do you really hope to terminate the current Unity Academy instance? If so, everything need to reload when you use Unity Academy again.'
+ )
+ ) {
return;
}
const quitFunctionName = 'Quit';
@@ -305,10 +338,13 @@ class UnityAcademyJsInteropContext {
this.unityInstance = null;
this.resetModuleData();
this.setShowUnityComponent(0);
- const canvasContext = (document.querySelector('#unity-canvas') as HTMLCanvasElement)!.getContext('webgl2');
+ const canvasContext = (document.querySelector(
+ '#unity-canvas'
+ ) as HTMLCanvasElement)!.getContext('webgl2');
canvasContext!.clearColor(0, 0, 0, 0);
canvasContext!.clear(canvasContext!.COLOR_BUFFER_BIT);
- document.querySelector('#unity_load_info')!.innerHTML = 'Unity Academy app has been terminated. Please rerun your program with init_unity_academy_3d or init_unity_academy_2d for re-initialization.';
+ document.querySelector('#unity_load_info')!.innerHTML =
+ 'Unity Academy app has been terminated. Please rerun your program with init_unity_academy_3d or init_unity_academy_2d for re-initialization.';
}
reset() {
@@ -316,7 +352,10 @@ class UnityAcademyJsInteropContext {
if (this.unityInstance !== null) {
const sendMessageFunctionName = 'SendMessage';
// Reset Unity Academy app
- this.unityInstance[sendMessageFunctionName]('GameManager', 'ResetSession');
+ this.unityInstance[sendMessageFunctionName](
+ 'GameManager',
+ 'ResetSession'
+ );
}
}
@@ -335,7 +374,7 @@ class UnityAcademyJsInteropContext {
return this.unityInstanceState === 'Ready';
}
- private getLatestUserAgreementVersion() : void {
+ private getLatestUserAgreementVersion(): void {
const jsonUrl = `${UNITY_ACADEMY_BACKEND_URL}user_agreement.json`;
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
@@ -347,9 +386,15 @@ class UnityAcademyJsInteropContext {
xhr.send();
}
- getUserAgreementStatus() : string {
- const agreedUserAgreementVersion = localStorage.getItem('unity_academy_agreed_user_agreement_version');
- if (agreedUserAgreementVersion === null || agreedUserAgreementVersion === 'unagreed' || agreedUserAgreementVersion === 'unknown') {
+ getUserAgreementStatus(): string {
+ const agreedUserAgreementVersion = localStorage.getItem(
+ 'unity_academy_agreed_user_agreement_version'
+ );
+ if (
+ agreedUserAgreementVersion === null ||
+ agreedUserAgreementVersion === 'unagreed' ||
+ agreedUserAgreementVersion === 'unknown'
+ ) {
return 'unagreed';
}
if (this.latestUserAgreementVersion === 'unknown') {
@@ -361,15 +406,21 @@ class UnityAcademyJsInteropContext {
return 'agreed';
}
- setUserAgreementStatus(agree : boolean) : void {
+ setUserAgreementStatus(agree: boolean): void {
if (agree) {
- localStorage.setItem('unity_academy_agreed_user_agreement_version', this.latestUserAgreementVersion);
+ localStorage.setItem(
+ 'unity_academy_agreed_user_agreement_version',
+ this.latestUserAgreementVersion
+ );
} else {
- localStorage.setItem('unity_academy_agreed_user_agreement_version', 'unagreed');
+ localStorage.setItem(
+ 'unity_academy_agreed_user_agreement_version',
+ 'unagreed'
+ );
}
}
- instantiateInternal(prefabName : string) : GameObjectIdentifier {
+ instantiateInternal(prefabName: string): GameObjectIdentifier {
let prefabExists = false;
const len = this.prefabInfo.prefab_info.length;
for (let i = 0; i < len; i++) {
@@ -379,34 +430,42 @@ class UnityAcademyJsInteropContext {
}
}
if (!prefabExists) {
- throw new Error(`Unknown prefab name: '${prefabName}'. Please refer to this prefab list at [ ${UNITY_ACADEMY_BACKEND_URL}webgl_assetbundles/prefab_info.html ] for all available prefab names.`);
+ throw new Error(
+ `Unknown prefab name: '${prefabName}'. Please refer to this prefab list at [ ${UNITY_ACADEMY_BACKEND_URL}webgl_assetbundles/prefab_info.html ] for all available prefab names.`
+ );
}
const gameObjectIdentifier = `${prefabName}_${this.gameObjectIdentifierSerialCounter}`;
this.gameObjectIdentifierSerialCounter++;
this.makeGameObjectDataStorage(gameObjectIdentifier);
- this.dispatchStudentAction(`instantiate|${prefabName}|${gameObjectIdentifier}`);
+ this.dispatchStudentAction(
+ `instantiate|${prefabName}|${gameObjectIdentifier}`
+ );
return new GameObjectIdentifier(gameObjectIdentifier);
}
- instantiate2DSpriteUrlInternal(sourceImageUrl : string) : GameObjectIdentifier {
+ instantiate2DSpriteUrlInternal(sourceImageUrl: string): GameObjectIdentifier {
// Use percent-encoding "%7C" to replace all '|' characters as '|' is used as the data separator in student action strings in Unity Academy Embedded Frontend.
sourceImageUrl = sourceImageUrl.replaceAll('|', '%7C');
const gameObjectIdentifier = `2DSprite_${this.gameObjectIdentifierSerialCounter}`;
this.gameObjectIdentifierSerialCounter++;
this.makeGameObjectDataStorage(gameObjectIdentifier);
- this.dispatchStudentAction(`instantiate2DSpriteUrl|${sourceImageUrl}|${gameObjectIdentifier}`);
+ this.dispatchStudentAction(
+ `instantiate2DSpriteUrl|${sourceImageUrl}|${gameObjectIdentifier}`
+ );
return new GameObjectIdentifier(gameObjectIdentifier);
}
- instantiateEmptyGameObjectInternal() : GameObjectIdentifier {
+ instantiateEmptyGameObjectInternal(): GameObjectIdentifier {
const gameObjectIdentifier = `EmptyGameObject_${this.gameObjectIdentifierSerialCounter}`;
this.gameObjectIdentifierSerialCounter++;
this.makeGameObjectDataStorage(gameObjectIdentifier);
- this.dispatchStudentAction(`instantiateEmptyGameObject|${gameObjectIdentifier}`);
+ this.dispatchStudentAction(
+ `instantiateEmptyGameObject|${gameObjectIdentifier}`
+ );
return new GameObjectIdentifier(gameObjectIdentifier);
}
- instantiateAudioSourceInternal(audioClipIdentifier : AudioClipIdentifier) {
+ instantiateAudioSourceInternal(audioClipIdentifier: AudioClipIdentifier) {
const gameObjectIdentifier = `AudioSource_${this.gameObjectIdentifierSerialCounter}`;
this.gameObjectIdentifierSerialCounter++;
this.makeGameObjectDataStorage(gameObjectIdentifier);
@@ -418,15 +477,19 @@ class UnityAcademyJsInteropContext {
isLooping: false,
isPlaying: false
};
- this.dispatchStudentAction(`instantiateAudioSourceGameObject|${gameObjectIdentifier}|${audioClipIdentifier.audioClipInternalName}`);
+ this.dispatchStudentAction(
+ `instantiateAudioSourceGameObject|${gameObjectIdentifier}|${audioClipIdentifier.audioClipInternalName}`
+ );
return new GameObjectIdentifier(gameObjectIdentifier);
}
- destroyGameObjectInternal(gameObjectIdentifier : GameObjectIdentifier) : void {
- this.dispatchStudentAction(`destroyGameObject|${gameObjectIdentifier.gameObjectIdentifier}`);
+ destroyGameObjectInternal(gameObjectIdentifier: GameObjectIdentifier): void {
+ this.dispatchStudentAction(
+ `destroyGameObject|${gameObjectIdentifier.gameObjectIdentifier}`
+ );
}
- private makeGameObjectDataStorage(gameObjectIdentifier : string) {
+ private makeGameObjectDataStorage(gameObjectIdentifier: string) {
this.studentGameObjectStorage[gameObjectIdentifier] = {
startMethod: null,
updateMethod: null,
@@ -445,128 +508,211 @@ class UnityAcademyJsInteropContext {
};
}
- getStudentGameObject(gameObjectIdentifier : GameObjectIdentifier) : StudentGameObject {
- const retVal = this.studentGameObjectStorage[gameObjectIdentifier.gameObjectIdentifier];
+ getStudentGameObject(
+ gameObjectIdentifier: GameObjectIdentifier
+ ): StudentGameObject {
+ const retVal =
+ this.studentGameObjectStorage[gameObjectIdentifier.gameObjectIdentifier];
if (retVal === undefined) {
- throw new Error(`Could not find GameObject with identifier ${gameObjectIdentifier}`);
+ throw new Error(
+ `Could not find GameObject with identifier ${gameObjectIdentifier}`
+ );
}
return retVal;
}
- setStartInternal(gameObjectIdentifier : GameObjectIdentifier, startFunction : Function) : void {
+ setStartInternal(
+ gameObjectIdentifier: GameObjectIdentifier,
+ startFunction: Function
+ ): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.startMethod = startFunction;
}
- setUpdateInternal(gameObjectIdentifier : GameObjectIdentifier, updateFunction : Function) : void {
+ setUpdateInternal(
+ gameObjectIdentifier: GameObjectIdentifier,
+ updateFunction: Function
+ ): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.updateMethod = updateFunction;
}
- private dispatchStudentAction(action) : void {
+ private dispatchStudentAction(action): void {
this.studentActionQueue[this.studentActionQueue.length] = action;
}
- getGameObjectIdentifierForPrimitiveGameObject(name : string) : GameObjectIdentifier {
+ getGameObjectIdentifierForPrimitiveGameObject(
+ name: string
+ ): GameObjectIdentifier {
const propName = 'gameObjectIdentifierWrapperClass';
return new this[propName](name);
}
- getGameObjectTransformProp(propName : string, gameObjectIdentifier : GameObjectIdentifier) : Vector3 {
+ getGameObjectTransformProp(
+ propName: string,
+ gameObjectIdentifier: GameObjectIdentifier
+ ): Vector3 {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
- return new Vector3(gameObject.transform[propName].x, gameObject.transform[propName].y, gameObject.transform[propName].z);
+ return new Vector3(
+ gameObject.transform[propName].x,
+ gameObject.transform[propName].y,
+ gameObject.transform[propName].z
+ );
}
- setGameObjectTransformProp(propName : string, gameObjectIdentifier : GameObjectIdentifier, newValue : Vector3) : void {
+ setGameObjectTransformProp(
+ propName: string,
+ gameObjectIdentifier: GameObjectIdentifier,
+ newValue: Vector3
+ ): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.transform[propName].x = newValue.x;
gameObject.transform[propName].y = newValue.y;
gameObject.transform[propName].z = newValue.z;
}
- getDeltaTime() : number {
+ getDeltaTime(): number {
return this.deltaTime;
}
- translateWorldInternal(gameObjectIdentifier : GameObjectIdentifier, deltaPosition : Vector3) : void {
+ translateWorldInternal(
+ gameObjectIdentifier: GameObjectIdentifier,
+ deltaPosition: Vector3
+ ): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.transform.position.x += deltaPosition.x;
gameObject.transform.position.y += deltaPosition.y;
gameObject.transform.position.z += deltaPosition.z;
}
- translateLocalInternal(gameObjectIdentifier : GameObjectIdentifier, deltaPosition : Vector3) : void {
+ translateLocalInternal(
+ gameObjectIdentifier: GameObjectIdentifier,
+ deltaPosition: Vector3
+ ): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const rotation = gameObject.transform.rotation;
// Some methematical stuff here for calcuating the actual world position displacement from local translate vector and current Euler rotation.
- const rx = rotation.x * Math.PI / 180;
- const ry = rotation.y * Math.PI / 180;
- const rz = rotation.z * Math.PI / 180;
+ const rx = (rotation.x * Math.PI) / 180;
+ const ry = (rotation.y * Math.PI) / 180;
+ const rz = (rotation.z * Math.PI) / 180;
const cos = Math.cos;
const sin = Math.sin;
- const rotationMatrix
- = [[cos(ry) * cos(rz), -cos(ry) * sin(rz), sin(ry)],
- [cos(rx) * sin(rz) + sin(rx) * sin(ry) * cos(rz), cos(rx) * cos(rz) - sin(rx) * sin(ry) * sin(rz), -sin(rx) * cos(ry)],
- [sin(rx) * sin(rz) - cos(rx) * sin(ry) * cos(rz), cos(rx) * sin(ry) * sin(rz) + sin(rx) * cos(rz), cos(rx) * cos(ry)]];
+ const rotationMatrix = [
+ [cos(ry) * cos(rz), -cos(ry) * sin(rz), sin(ry)],
+ [
+ cos(rx) * sin(rz) + sin(rx) * sin(ry) * cos(rz),
+ cos(rx) * cos(rz) - sin(rx) * sin(ry) * sin(rz),
+ -sin(rx) * cos(ry)
+ ],
+ [
+ sin(rx) * sin(rz) - cos(rx) * sin(ry) * cos(rz),
+ cos(rx) * sin(ry) * sin(rz) + sin(rx) * cos(rz),
+ cos(rx) * cos(ry)
+ ]
+ ];
const finalWorldTranslateVector = [
- rotationMatrix[0][0] * deltaPosition.x + rotationMatrix[0][1] * deltaPosition.y + rotationMatrix[0][2] * deltaPosition.z,
- rotationMatrix[1][0] * deltaPosition.x + rotationMatrix[1][1] * deltaPosition.y + rotationMatrix[1][2] * deltaPosition.z,
- rotationMatrix[2][0] * deltaPosition.x + rotationMatrix[2][1] * deltaPosition.y + rotationMatrix[2][2] * deltaPosition.z
+ rotationMatrix[0][0] * deltaPosition.x +
+ rotationMatrix[0][1] * deltaPosition.y +
+ rotationMatrix[0][2] * deltaPosition.z,
+ rotationMatrix[1][0] * deltaPosition.x +
+ rotationMatrix[1][1] * deltaPosition.y +
+ rotationMatrix[1][2] * deltaPosition.z,
+ rotationMatrix[2][0] * deltaPosition.x +
+ rotationMatrix[2][1] * deltaPosition.y +
+ rotationMatrix[2][2] * deltaPosition.z
];
gameObject.transform.position.x += finalWorldTranslateVector[0];
gameObject.transform.position.y += finalWorldTranslateVector[1];
gameObject.transform.position.z += finalWorldTranslateVector[2];
}
- lookAtPositionInternal(gameObjectIdentifier : GameObjectIdentifier, position : Vector3) : void {
+ lookAtPositionInternal(
+ gameObjectIdentifier: GameObjectIdentifier,
+ position: Vector3
+ ): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
- const deltaVector = normalizeVector(new Vector3(position.x - gameObject.transform.position.x, position.y - gameObject.transform.position.y, position.z - gameObject.transform.position.z));
+ const deltaVector = normalizeVector(
+ new Vector3(
+ position.x - gameObject.transform.position.x,
+ position.y - gameObject.transform.position.y,
+ position.z - gameObject.transform.position.z
+ )
+ );
const eulerX = Math.asin(-deltaVector.y);
const eulerY = Math.atan2(deltaVector.x, deltaVector.z);
- gameObject.transform.rotation.x = eulerX * 180 / Math.PI;
- gameObject.transform.rotation.y = eulerY * 180 / Math.PI;
+ gameObject.transform.rotation.x = (eulerX * 180) / Math.PI;
+ gameObject.transform.rotation.y = (eulerY * 180) / Math.PI;
gameObject.transform.rotation.z = 0;
}
- gameObjectDistanceInternal(gameObjectIdentifier_A : GameObjectIdentifier, gameObjectIdentifier_B : GameObjectIdentifier) : number {
+ gameObjectDistanceInternal(
+ gameObjectIdentifier_A: GameObjectIdentifier,
+ gameObjectIdentifier_B: GameObjectIdentifier
+ ): number {
const gameObjectA = this.getStudentGameObject(gameObjectIdentifier_A);
const gameObjectB = this.getStudentGameObject(gameObjectIdentifier_B);
- return pointDistance(gameObjectA.transform.position, gameObjectB.transform.position);
+ return pointDistance(
+ gameObjectA.transform.position,
+ gameObjectB.transform.position
+ );
}
- rotateWorldInternal(gameObjectIdentifier : GameObjectIdentifier, angles : Vector3) : void {
+ rotateWorldInternal(
+ gameObjectIdentifier: GameObjectIdentifier,
+ angles: Vector3
+ ): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.transform.rotation.x += angles.x;
gameObject.transform.rotation.y += angles.y;
gameObject.transform.rotation.z += angles.z;
}
- copyTransformPropertiesInternal(propName : string, from : GameObjectIdentifier, to : GameObjectIdentifier, deltaValues : Vector3) : void {
+ copyTransformPropertiesInternal(
+ propName: string,
+ from: GameObjectIdentifier,
+ to: GameObjectIdentifier,
+ deltaValues: Vector3
+ ): void {
const fromGameObject = this.getStudentGameObject(from);
const toGameObject = this.getStudentGameObject(to);
const deltaX = deltaValues.x;
const deltaY = deltaValues.y;
const deltaZ = deltaValues.z;
- if (Math.abs(deltaX) !== 999999) toGameObject.transform[propName].x = fromGameObject.transform[propName].x + deltaX;
- if (Math.abs(deltaY) !== 999999) toGameObject.transform[propName].y = fromGameObject.transform[propName].y + deltaY;
- if (Math.abs(deltaZ) !== 999999) toGameObject.transform[propName].z = fromGameObject.transform[propName].z + deltaZ;
- }
-
- getKeyState(keyCode : string) : number {
+ if (Math.abs(deltaX) !== 999999)
+ toGameObject.transform[propName].x =
+ fromGameObject.transform[propName].x + deltaX;
+ if (Math.abs(deltaY) !== 999999)
+ toGameObject.transform[propName].y =
+ fromGameObject.transform[propName].y + deltaY;
+ if (Math.abs(deltaZ) !== 999999)
+ toGameObject.transform[propName].z =
+ fromGameObject.transform[propName].z + deltaZ;
+ }
+
+ getKeyState(keyCode: string): number {
return this.input.keyboardInputInfo[keyCode];
}
- playAnimatorStateInternal(gameObjectIdentifier : GameObjectIdentifier, animatorStateName : string) {
+ playAnimatorStateInternal(
+ gameObjectIdentifier: GameObjectIdentifier,
+ animatorStateName: string
+ ) {
this.getStudentGameObject(gameObjectIdentifier); // Just to check whether the game object identifier is valid or not.
- this.dispatchStudentAction(`playAnimatorState|${gameObjectIdentifier.gameObjectIdentifier}|${animatorStateName}`);
+ this.dispatchStudentAction(
+ `playAnimatorState|${gameObjectIdentifier.gameObjectIdentifier}|${animatorStateName}`
+ );
}
- applyRigidbodyInternal(gameObjectIdentifier : GameObjectIdentifier) {
- console.log(`Applying rigidbody to GameObject ${gameObjectIdentifier.gameObjectIdentifier}`);
+ applyRigidbodyInternal(gameObjectIdentifier: GameObjectIdentifier) {
+ console.log(
+ `Applying rigidbody to GameObject ${gameObjectIdentifier.gameObjectIdentifier}`
+ );
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
if (gameObject.rigidbody !== null) {
- throw new Error(`Trying to duplicately apply rigidbody on GameObject ${gameObjectIdentifier.gameObjectIdentifier}`);
+ throw new Error(
+ `Trying to duplicately apply rigidbody on GameObject ${gameObjectIdentifier.gameObjectIdentifier}`
+ );
}
gameObject.rigidbody = {
velocity: zeroVector(),
@@ -576,21 +722,37 @@ class UnityAcademyJsInteropContext {
drag: 0,
angularDrag: 0.05
};
- this.dispatchStudentAction(`applyRigidbody|${gameObjectIdentifier.gameObjectIdentifier}`);
+ this.dispatchStudentAction(
+ `applyRigidbody|${gameObjectIdentifier.gameObjectIdentifier}`
+ );
}
- private getRigidbody(gameObject: StudentGameObject) : RigidbodyData {
- if (gameObject.rigidbody === null) throw new Error('You must call apply_rigidbody on the game object before using this physics function!');
+ private getRigidbody(gameObject: StudentGameObject): RigidbodyData {
+ if (gameObject.rigidbody === null)
+ throw new Error(
+ 'You must call apply_rigidbody on the game object before using this physics function!'
+ );
return gameObject.rigidbody;
}
- getRigidbodyVelocityVector3Prop(propName : string, gameObjectIdentifier : GameObjectIdentifier) : Vector3 {
+ getRigidbodyVelocityVector3Prop(
+ propName: string,
+ gameObjectIdentifier: GameObjectIdentifier
+ ): Vector3 {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const rigidbody = this.getRigidbody(gameObject);
- return new Vector3(rigidbody[propName].x, rigidbody[propName].y, rigidbody[propName].z);
+ return new Vector3(
+ rigidbody[propName].x,
+ rigidbody[propName].y,
+ rigidbody[propName].z
+ );
}
- setRigidbodyVelocityVector3Prop(propName : string, gameObjectIdentifier : GameObjectIdentifier, newValue : Vector3) : void {
+ setRigidbodyVelocityVector3Prop(
+ propName: string,
+ gameObjectIdentifier: GameObjectIdentifier,
+ newValue: Vector3
+ ): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const rigidbody = this.getRigidbody(gameObject);
rigidbody[propName].x = newValue.x;
@@ -598,48 +760,78 @@ class UnityAcademyJsInteropContext {
rigidbody[propName].z = newValue.z;
}
- getRigidbodyNumericalProp(propName : string, gameObjectIdentifier : GameObjectIdentifier) : number {
+ getRigidbodyNumericalProp(
+ propName: string,
+ gameObjectIdentifier: GameObjectIdentifier
+ ): number {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const rigidbody = this.getRigidbody(gameObject);
return rigidbody[propName];
}
- setRigidbodyNumericalProp(propName : string, gameObjectIdentifier : GameObjectIdentifier, value : number) : void {
+ setRigidbodyNumericalProp(
+ propName: string,
+ gameObjectIdentifier: GameObjectIdentifier,
+ value: number
+ ): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const rigidbody = this.getRigidbody(gameObject);
rigidbody[propName] = value;
}
- setUseGravityInternal(gameObjectIdentifier : GameObjectIdentifier, useGravity : boolean) : void {
+ setUseGravityInternal(
+ gameObjectIdentifier: GameObjectIdentifier,
+ useGravity: boolean
+ ): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const rigidbody = this.getRigidbody(gameObject);
rigidbody.useGravity = useGravity;
}
- addImpulseForceInternal(gameObjectIdentifier : GameObjectIdentifier, force : Vector3) : void {
- this.dispatchStudentAction(`addImpulseForce|${gameObjectIdentifier.gameObjectIdentifier}|${force.x.toString()}|${force.y.toString()}|${force.z.toString()}`);
+ addImpulseForceInternal(
+ gameObjectIdentifier: GameObjectIdentifier,
+ force: Vector3
+ ): void {
+ this.dispatchStudentAction(
+ `addImpulseForce|${
+ gameObjectIdentifier.gameObjectIdentifier
+ }|${force.x.toString()}|${force.y.toString()}|${force.z.toString()}`
+ );
}
- removeColliderComponentsInternal(gameObjectIdentifier : GameObjectIdentifier) : void {
- this.dispatchStudentAction(`removeColliderComponents|${gameObjectIdentifier.gameObjectIdentifier}`);
+ removeColliderComponentsInternal(
+ gameObjectIdentifier: GameObjectIdentifier
+ ): void {
+ this.dispatchStudentAction(
+ `removeColliderComponents|${gameObjectIdentifier.gameObjectIdentifier}`
+ );
}
- setOnCollisionEnterInternal(gameObjectIdentifier : GameObjectIdentifier, eventFunction : Function) {
+ setOnCollisionEnterInternal(
+ gameObjectIdentifier: GameObjectIdentifier,
+ eventFunction: Function
+ ) {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.onCollisionEnterMethod = eventFunction;
}
- setOnCollisionStayInternal(gameObjectIdentifier : GameObjectIdentifier, eventFunction : Function) {
+ setOnCollisionStayInternal(
+ gameObjectIdentifier: GameObjectIdentifier,
+ eventFunction: Function
+ ) {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.onCollisionStayMethod = eventFunction;
}
- setOnCollisionExitInternal(gameObjectIdentifier : GameObjectIdentifier, eventFunction : Function) {
+ setOnCollisionExitInternal(
+ gameObjectIdentifier: GameObjectIdentifier,
+ eventFunction: Function
+ ) {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.onCollisionExitMethod = eventFunction;
}
- requestForMainCameraControlInternal() : GameObjectIdentifier {
+ requestForMainCameraControlInternal(): GameObjectIdentifier {
const name = 'MainCamera';
if (this.studentGameObjectStorage[name] !== undefined) {
return this.getGameObjectIdentifierForPrimitiveGameObject('MainCamera');
@@ -649,7 +841,7 @@ class UnityAcademyJsInteropContext {
return this.getGameObjectIdentifierForPrimitiveGameObject('MainCamera');
}
- onGUI_Label(content : string, x : number, y : number) : void {
+ onGUI_Label(content: string, x: number, y: number): void {
// Temporarily use "<%7C>" to replace all '|' characters as '|' is used as the data separator in GUI data in Unity Academy Embedded Frontend.
// In Unity Academy Embedded Frontend, "<%7C>" will be replaced back to '|' when displaying the text in GUI
content = content.replaceAll('|', '<%7C>');
@@ -662,7 +854,14 @@ class UnityAcademyJsInteropContext {
this.guiData.push(newLabel);
}
- onGUI_Button(text : string, x: number, y : number, width : number, height : number, onClick : Function) : void {
+ onGUI_Button(
+ text: string,
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ onClick: Function
+ ): void {
// Temporarily use "<%7C>" to replace all '|' characters as '|' is used as the data separator in GUI data in Unity Academy Embedded Frontend.
// In Unity Academy Embedded Frontend, "<%7C>" will be replaced back to '|' when displaying the text in GUI
text = text.replaceAll('|', '<%7C>');
@@ -678,15 +877,22 @@ class UnityAcademyJsInteropContext {
this.guiData.push(newButton);
}
- loadAudioClipInternal(audioClipUrl : string, audioType : string) : AudioClipIdentifier {
+ loadAudioClipInternal(
+ audioClipUrl: string,
+ audioType: string
+ ): AudioClipIdentifier {
const audioClipInternalName = `AudioClip_${this.audioClipIdentifierSerialCounter}`;
this.audioClipIdentifierSerialCounter++;
this.audioClipStorage[this.audioClipStorage.length] = audioClipInternalName;
- this.dispatchStudentAction(`loadAudioClip|${audioClipUrl}|${audioType}|${audioClipInternalName}`);
+ this.dispatchStudentAction(
+ `loadAudioClip|${audioClipUrl}|${audioType}|${audioClipInternalName}`
+ );
return new AudioClipIdentifier(audioClipInternalName);
}
- private getAudioSourceData(gameObjectIdentifier : GameObjectIdentifier) : AudioSourceData {
+ private getAudioSourceData(
+ gameObjectIdentifier: GameObjectIdentifier
+ ): AudioSourceData {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const retVal = gameObject.audioSource;
if (retVal === null) {
@@ -695,36 +901,47 @@ class UnityAcademyJsInteropContext {
return retVal;
}
- setAudioSourceProp(propName : string, audioSrc : GameObjectIdentifier, value : any) : void {
+ setAudioSourceProp(
+ propName: string,
+ audioSrc: GameObjectIdentifier,
+ value: any
+ ): void {
const audioSourceData = this.getAudioSourceData(audioSrc);
audioSourceData[propName] = value;
}
- getAudioSourceProp(propName : string, audioSrc : GameObjectIdentifier) : any {
+ getAudioSourceProp(propName: string, audioSrc: GameObjectIdentifier): any {
const audioSourceData = this.getAudioSourceData(audioSrc);
return audioSourceData[propName];
}
- studentLogger(contentStr : string, severity : string) {
+ studentLogger(contentStr: string, severity: string) {
// Temporarily use "<%7C>" to replace all '|' characters as '|' is used as the data separator in student action strings in Unity Academy Embedded Frontend.
// In Unity Academy Embedded Frontend, "<%7C>" will be replaced back to '|' when displaying the log message.
contentStr = contentStr.replaceAll('|', '<%7C>');
this.dispatchStudentAction(`studentLogger|${severity}|${contentStr}`);
}
- setTargetFrameRate(newTargetFrameRate : number) : void {
+ setTargetFrameRate(newTargetFrameRate: number): void {
newTargetFrameRate = Math.floor(newTargetFrameRate);
if (newTargetFrameRate < 15) return;
if (newTargetFrameRate > 120) return;
this.targetFrameRate = newTargetFrameRate;
}
- setCustomPropertyInternal(gameObjectIdentifier : GameObjectIdentifier, propName : string, value : any) : void {
+ setCustomPropertyInternal(
+ gameObjectIdentifier: GameObjectIdentifier,
+ propName: string,
+ value: any
+ ): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.customProperties[propName] = value;
}
- getCustomPropertyInternal(gameObjectIdentifier : GameObjectIdentifier, propName : string) : any {
+ getCustomPropertyInternal(
+ gameObjectIdentifier: GameObjectIdentifier,
+ propName: string
+ ): any {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
return gameObject.customProperties[propName];
}
@@ -734,11 +951,13 @@ class UnityAcademyJsInteropContext {
}
}
-export function initializeModule(dimensionMode : string) {
+export function initializeModule(dimensionMode: string) {
let instance = getInstance();
if (instance !== undefined) {
if (!instance.isUnityInstanceReady()) {
- throw new Error('Unity Academy Embedded Frontend is not ready to accept a new Source program now, please try again later. If you just successfully ran your code before but haven\'t open Unity Academy Embedded Frontend before running your code again, please try open the frontend first. If this error persists or you can not open Unity Academy Embedded Frontend, please try to refresh your browser\'s page.');
+ throw new Error(
+ "Unity Academy Embedded Frontend is not ready to accept a new Source program now, please try again later. If you just successfully ran your code before but haven't open Unity Academy Embedded Frontend before running your code again, please try open the frontend first. If this error persists or you can not open Unity Academy Embedded Frontend, please try to refresh your browser's page."
+ );
}
if (instance.unityInstance === null) {
instance.reloadUnityAcademyInstanceAfterTermination();
diff --git a/src/bundles/unity_academy/UnityAcademyMaths.ts b/src/bundles/unity_academy/UnityAcademyMaths.ts
index 84f09bf48..75d5a1285 100644
--- a/src/bundles/unity_academy/UnityAcademyMaths.ts
+++ b/src/bundles/unity_academy/UnityAcademyMaths.ts
@@ -19,53 +19,81 @@ export class Vector3 {
}
}
-export function checkVector3Parameter(parameter : any) : void {
- if (typeof (parameter) !== 'object') {
- throw new Error(`The given parameter is not a valid 3D vector! Wrong parameter type: ${typeof (parameter)}`);
+export function checkVector3Parameter(parameter: any): void {
+ if (typeof parameter !== 'object') {
+ throw new Error(
+ `The given parameter is not a valid 3D vector! Wrong parameter type: ${typeof parameter}`
+ );
}
- if (typeof (parameter.x) !== 'number' || typeof (parameter.y) !== 'number' || typeof (parameter.z) !== 'number') {
+ if (
+ typeof parameter.x !== 'number' ||
+ typeof parameter.y !== 'number' ||
+ typeof parameter.z !== 'number'
+ ) {
throw new Error('The given parameter is not a valid 3D vector!');
}
}
-export function makeVector3D(x : number, y : number, z : number) : Vector3 {
+export function makeVector3D(x: number, y: number, z: number): Vector3 {
return new Vector3(x, y, z);
}
-export function scaleVector(vector : Vector3, factor : number) : Vector3 {
+export function scaleVector(vector: Vector3, factor: number): Vector3 {
return new Vector3(vector.x * factor, vector.y * factor, vector.z * factor);
}
-export function addVectors(vectorA : Vector3, vectorB : Vector3) : Vector3 {
- return new Vector3(vectorA.x + vectorB.x, vectorA.y + vectorB.y, vectorA.z + vectorB.z);
+export function addVectors(vectorA: Vector3, vectorB: Vector3): Vector3 {
+ return new Vector3(
+ vectorA.x + vectorB.x,
+ vectorA.y + vectorB.y,
+ vectorA.z + vectorB.z
+ );
}
-export function vectorDifference(vectorA : Vector3, vectorB : Vector3) : Vector3 {
- return new Vector3(vectorA.x - vectorB.x, vectorA.y - vectorB.y, vectorA.z - vectorB.z);
+export function vectorDifference(vectorA: Vector3, vectorB: Vector3): Vector3 {
+ return new Vector3(
+ vectorA.x - vectorB.x,
+ vectorA.y - vectorB.y,
+ vectorA.z - vectorB.z
+ );
}
-export function dotProduct(vectorA : Vector3, vectorB : Vector3) : number {
+export function dotProduct(vectorA: Vector3, vectorB: Vector3): number {
return vectorA.x * vectorB.x + vectorA.y * vectorB.y + vectorA.z * vectorB.z;
}
-export function crossProduct(vectorA : Vector3, vectorB : Vector3) : Vector3 {
- return new Vector3(vectorA.y * vectorB.z - vectorB.y * vectorA.z, vectorB.x * vectorA.z - vectorA.x * vectorB.z, vectorA.x * vectorB.y - vectorB.x * vectorA.y);
+export function crossProduct(vectorA: Vector3, vectorB: Vector3): Vector3 {
+ return new Vector3(
+ vectorA.y * vectorB.z - vectorB.y * vectorA.z,
+ vectorB.x * vectorA.z - vectorA.x * vectorB.z,
+ vectorA.x * vectorB.y - vectorB.x * vectorA.y
+ );
}
-export function vectorMagnitude(vector : Vector3) : number {
- return Math.sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z);
+export function vectorMagnitude(vector: Vector3): number {
+ return Math.sqrt(
+ vector.x * vector.x + vector.y * vector.y + vector.z * vector.z
+ );
}
-export function normalizeVector(vector : Vector3) : Vector3 {
+export function normalizeVector(vector: Vector3): Vector3 {
const magnitude = vectorMagnitude(vector);
if (magnitude === 0) return new Vector3(0, 0, 0); // If the parameter is a zero vector, then return a new zero vector.
- return new Vector3(vector.x / magnitude, vector.y / magnitude, vector.z / magnitude);
+ return new Vector3(
+ vector.x / magnitude,
+ vector.y / magnitude,
+ vector.z / magnitude
+ );
}
-export function zeroVector() : Vector3 {
+export function zeroVector(): Vector3 {
return new Vector3(0, 0, 0);
}
-export function pointDistance(pointA : Vector3, pointB : Vector3) : number {
- return Math.sqrt((pointB.x - pointA.x) ** 2 + (pointB.y - pointA.y) ** 2 + (pointB.z - pointA.z) ** 2);
+export function pointDistance(pointA: Vector3, pointB: Vector3): number {
+ return Math.sqrt(
+ (pointB.x - pointA.x) ** 2 +
+ (pointB.y - pointA.y) ** 2 +
+ (pointB.z - pointA.z) ** 2
+ );
}
diff --git a/src/bundles/unity_academy/config.ts b/src/bundles/unity_academy/config.ts
index 12e4a2a2b..0cbaca37d 100644
--- a/src/bundles/unity_academy/config.ts
+++ b/src/bundles/unity_academy/config.ts
@@ -1,2 +1,3 @@
-export const UNITY_ACADEMY_BACKEND_URL = 'https://unity-academy.s3.ap-southeast-1.amazonaws.com/';
+export const UNITY_ACADEMY_BACKEND_URL =
+ 'https://unity-academy.s3.ap-southeast-1.amazonaws.com/';
export const BUILD_NAME = 'ua-frontend-prod';
diff --git a/src/bundles/unity_academy/functions.ts b/src/bundles/unity_academy/functions.ts
index 89250927e..34b8952c4 100644
--- a/src/bundles/unity_academy/functions.ts
+++ b/src/bundles/unity_academy/functions.ts
@@ -4,10 +4,25 @@
* @author Wang Zihan
*/
-import { initializeModule, getInstance, type GameObjectIdentifier, type AudioClipIdentifier } from './UnityAcademy';
import {
- type Vector3, checkVector3Parameter, makeVector3D, scaleVector, addVectors, vectorDifference, dotProduct,
- crossProduct, normalizeVector, vectorMagnitude, zeroVector, pointDistance
+ getInstance,
+ initializeModule,
+ type AudioClipIdentifier,
+ type GameObjectIdentifier
+} from './UnityAcademy';
+import {
+ addVectors,
+ checkVector3Parameter,
+ crossProduct,
+ dotProduct,
+ makeVector3D,
+ normalizeVector,
+ pointDistance,
+ scaleVector,
+ vectorDifference,
+ vectorMagnitude,
+ zeroVector,
+ type Vector3
} from './UnityAcademyMaths';
/**
@@ -18,7 +33,7 @@ import {
* @category Application Initialization
* @category Outside Lifecycle
*/
-export function init_unity_academy_2d() : void {
+export function init_unity_academy_2d(): void {
initializeModule('2d');
}
@@ -30,45 +45,68 @@ export function init_unity_academy_2d() : void {
* @category Application Initialization
* @category Outside Lifecycle
*/
-export function init_unity_academy_3d() : void {
+export function init_unity_academy_3d(): void {
initializeModule('3d');
}
function checkUnityAcademyExistence() {
if (getInstance() === undefined) {
- throw new Error('Unity module is not initialized, please call init_unity_academy_3d / init_unity_academy_2d first before calling this function');
+ throw new Error(
+ 'Unity module is not initialized, please call init_unity_academy_3d / init_unity_academy_2d first before calling this function'
+ );
}
}
-function checkIs2DMode() : void {
- if (getInstance().dimensionMode !== '2d') throw new Error('You are calling a "2D mode only" function in non-2d mode.');
+function checkIs2DMode(): void {
+ if (getInstance().dimensionMode !== '2d')
+ throw new Error(
+ 'You are calling a "2D mode only" function in non-2d mode.'
+ );
}
-function checkIs3DMode() : void {
- if (getInstance().dimensionMode !== '3d') throw new Error('You are calling a "3D mode only" function in non-3d mode.');
+function checkIs3DMode(): void {
+ if (getInstance().dimensionMode !== '3d')
+ throw new Error(
+ 'You are calling a "3D mode only" function in non-3d mode.'
+ );
}
-function checkGameObjectIdentifierParameter(gameObjectIdentifier : any) {
+function checkGameObjectIdentifierParameter(gameObjectIdentifier: any) {
// Here I can not just do "gameObjectIdentifier instanceof GameObjectIdentifier".
// Because if I do that, when students re-run their code on the same Unity instance, (gameObjectIdentifier instanceof GameObjectIdentifier) will always evaluate to false
// even when students provide the parameter with the correct type.
const instance = getInstance();
- if (!(gameObjectIdentifier instanceof instance.gameObjectIdentifierWrapperClass)) {
- throw new Error(`Type "${(typeof (gameObjectIdentifier)).toString()}" can not be used as game object identifier!`);
+ if (
+ !(gameObjectIdentifier instanceof instance.gameObjectIdentifierWrapperClass)
+ ) {
+ throw new Error(
+ `Type "${(typeof gameObjectIdentifier).toString()}" can not be used as game object identifier!`
+ );
}
if (instance.getStudentGameObject(gameObjectIdentifier).isDestroyed) {
throw new Error('Trying to use a GameObject that is already destroyed.');
}
}
-function checkParameterType(parameter : any, expectedType : string, numberAllowInfinity = false) {
- const actualType = typeof (parameter);
+function checkParameterType(
+ parameter: any,
+ expectedType: string,
+ numberAllowInfinity = false
+) {
+ const actualType = typeof parameter;
if (actualType !== expectedType) {
- throw new Error(`Wrong parameter type: expected ${expectedType}, but got ${actualType}`);
+ throw new Error(
+ `Wrong parameter type: expected ${expectedType}, but got ${actualType}`
+ );
}
if (actualType.toString() === 'number') {
- if (!numberAllowInfinity && (parameter === Infinity || parameter === -Infinity)) {
- throw new Error('Wrong parameter type: expected a finite number, but got Infinity or -Infinity');
+ if (
+ !numberAllowInfinity &&
+ (parameter === Infinity || parameter === -Infinity)
+ ) {
+ throw new Error(
+ 'Wrong parameter type: expected a finite number, but got Infinity or -Infinity'
+ );
}
}
}
@@ -81,10 +119,16 @@ function checkParameterType(parameter : any, expectedType : string, numberAllowI
* @return Returns true if the two GameObject identifiers refers to the same GameObject and false otherwise.
* @category Common
*/
-export function same_gameobject(first : GameObjectIdentifier, second : GameObjectIdentifier) : boolean {
+export function same_gameobject(
+ first: GameObjectIdentifier,
+ second: GameObjectIdentifier
+): boolean {
checkUnityAcademyExistence();
const instance = getInstance();
- if (!(first instanceof instance.gameObjectIdentifierWrapperClass) || !(second instanceof instance.gameObjectIdentifierWrapperClass)) {
+ if (
+ !(first instanceof instance.gameObjectIdentifierWrapperClass) ||
+ !(second instanceof instance.gameObjectIdentifierWrapperClass)
+ ) {
return false;
}
return first.gameObjectIdentifier === second.gameObjectIdentifier;
@@ -98,12 +142,14 @@ export function same_gameobject(first : GameObjectIdentifier, second : GameObjec
* @category Common
* @category Outside Lifecycle
*/
-export function set_start(gameObjectIdentifier : GameObjectIdentifier, startFunction : Function) : void {
+export function set_start(
+ gameObjectIdentifier: GameObjectIdentifier,
+ startFunction: Function
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(startFunction, 'function');
- getInstance()
- .setStartInternal(gameObjectIdentifier, startFunction);
+ getInstance().setStartInternal(gameObjectIdentifier, startFunction);
}
/**
@@ -115,12 +161,14 @@ export function set_start(gameObjectIdentifier : GameObjectIdentifier, startFunc
* @category Common
* @category Outside Lifecycle
*/
-export function set_update(gameObjectIdentifier : GameObjectIdentifier, updateFunction : Function) : void {
+export function set_update(
+ gameObjectIdentifier: GameObjectIdentifier,
+ updateFunction: Function
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(updateFunction, 'function');
- getInstance()
- .setUpdateInternal(gameObjectIdentifier, updateFunction);
+ getInstance().setUpdateInternal(gameObjectIdentifier, updateFunction);
}
/**
@@ -138,12 +186,11 @@ export function set_update(gameObjectIdentifier : GameObjectIdentifier, updateFu
* @category Common
* @category Outside Lifecycle
*/
-export function instantiate(prefab_name : string) : GameObjectIdentifier {
+export function instantiate(prefab_name: string): GameObjectIdentifier {
checkUnityAcademyExistence();
checkIs3DMode();
checkParameterType(prefab_name, 'string');
- return getInstance()
- .instantiateInternal(prefab_name);
+ return getInstance().instantiateInternal(prefab_name);
}
/**
@@ -161,12 +208,11 @@ export function instantiate(prefab_name : string) : GameObjectIdentifier {
* @category Common
* @category Outside Lifecycle
*/
-export function instantiate_sprite(sourceImageUrl : string) {
+export function instantiate_sprite(sourceImageUrl: string) {
checkUnityAcademyExistence();
checkIs2DMode();
checkParameterType(sourceImageUrl, 'string');
- return getInstance()
- .instantiate2DSpriteUrlInternal(sourceImageUrl);
+ return getInstance().instantiate2DSpriteUrlInternal(sourceImageUrl);
}
/**
@@ -181,10 +227,9 @@ export function instantiate_sprite(sourceImageUrl : string) {
* @category Common
* @category Outside Lifecycle
*/
-export function instantiate_empty() : GameObjectIdentifier {
+export function instantiate_empty(): GameObjectIdentifier {
checkUnityAcademyExistence();
- return getInstance()
- .instantiateEmptyGameObjectInternal();
+ return getInstance().instantiateEmptyGameObjectInternal();
}
/**
@@ -208,8 +253,7 @@ export function instantiate_empty() : GameObjectIdentifier {
*/
export function delta_time() {
checkUnityAcademyExistence();
- return getInstance()
- .getDeltaTime();
+ return getInstance().getDeltaTime();
}
/**
@@ -222,11 +266,10 @@ export function delta_time() {
* @param gameObjectIdentifier The identifier for the GameObject that you want to destroy.
* @category Common
*/
-export function destroy(gameObjectIdentifier : GameObjectIdentifier) : void {
+export function destroy(gameObjectIdentifier: GameObjectIdentifier): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
- getInstance()
- .destroyGameObjectInternal(gameObjectIdentifier);
+ getInstance().destroyGameObjectInternal(gameObjectIdentifier);
}
/**
@@ -236,11 +279,15 @@ export function destroy(gameObjectIdentifier : GameObjectIdentifier) : void {
*
* @category Transform
*/
-export function get_position(gameObjectIdentifier : GameObjectIdentifier) : Vector3 {
+export function get_position(
+ gameObjectIdentifier: GameObjectIdentifier
+): Vector3 {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
- return getInstance()
- .getGameObjectTransformProp('position', gameObjectIdentifier);
+ return getInstance().getGameObjectTransformProp(
+ 'position',
+ gameObjectIdentifier
+ );
}
/**
@@ -250,12 +297,18 @@ export function get_position(gameObjectIdentifier : GameObjectIdentifier) : Vect
*
* @category Transform
*/
-export function set_position(gameObjectIdentifier : GameObjectIdentifier, position : Vector3) : void {
+export function set_position(
+ gameObjectIdentifier: GameObjectIdentifier,
+ position: Vector3
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(position);
- return getInstance()
- .setGameObjectTransformProp('position', gameObjectIdentifier, position);
+ return getInstance().setGameObjectTransformProp(
+ 'position',
+ gameObjectIdentifier,
+ position
+ );
}
/**
@@ -265,11 +318,15 @@ export function set_position(gameObjectIdentifier : GameObjectIdentifier, positi
*
* @category Transform
*/
-export function get_rotation_euler(gameObjectIdentifier : GameObjectIdentifier) : Vector3 {
+export function get_rotation_euler(
+ gameObjectIdentifier: GameObjectIdentifier
+): Vector3 {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
- return getInstance()
- .getGameObjectTransformProp('rotation', gameObjectIdentifier);
+ return getInstance().getGameObjectTransformProp(
+ 'rotation',
+ gameObjectIdentifier
+ );
}
/**
@@ -279,12 +336,18 @@ export function get_rotation_euler(gameObjectIdentifier : GameObjectIdentifier)
*
* @category Transform
*/
-export function set_rotation_euler(gameObjectIdentifier : GameObjectIdentifier, rotation : Vector3) : void {
+export function set_rotation_euler(
+ gameObjectIdentifier: GameObjectIdentifier,
+ rotation: Vector3
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(rotation);
- return getInstance()
- .setGameObjectTransformProp('rotation', gameObjectIdentifier, rotation);
+ return getInstance().setGameObjectTransformProp(
+ 'rotation',
+ gameObjectIdentifier,
+ rotation
+ );
}
/**
@@ -296,11 +359,13 @@ export function set_rotation_euler(gameObjectIdentifier : GameObjectIdentifier,
*
* @category Transform
*/
-export function get_scale(gameObjectIdentifier : GameObjectIdentifier) : Vector3 {
+export function get_scale(gameObjectIdentifier: GameObjectIdentifier): Vector3 {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
- return getInstance()
- .getGameObjectTransformProp('scale', gameObjectIdentifier);
+ return getInstance().getGameObjectTransformProp(
+ 'scale',
+ gameObjectIdentifier
+ );
}
/**
@@ -315,12 +380,18 @@ export function get_scale(gameObjectIdentifier : GameObjectIdentifier) : Vector3
*
* @category Transform
*/
-export function set_scale(gameObjectIdentifier : GameObjectIdentifier, scale : Vector3) : void {
+export function set_scale(
+ gameObjectIdentifier: GameObjectIdentifier,
+ scale: Vector3
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(scale);
- return getInstance()
- .setGameObjectTransformProp('scale', gameObjectIdentifier, scale);
+ return getInstance().setGameObjectTransformProp(
+ 'scale',
+ gameObjectIdentifier,
+ scale
+ );
}
/**
@@ -331,12 +402,17 @@ export function set_scale(gameObjectIdentifier : GameObjectIdentifier, scale : V
*
* @category Transform
*/
-export function translate_world(gameObjectIdentifier : GameObjectIdentifier, deltaPosition : Vector3) : void {
+export function translate_world(
+ gameObjectIdentifier: GameObjectIdentifier,
+ deltaPosition: Vector3
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(deltaPosition);
- return getInstance()
- .translateWorldInternal(gameObjectIdentifier, deltaPosition);
+ return getInstance().translateWorldInternal(
+ gameObjectIdentifier,
+ deltaPosition
+ );
}
/**
@@ -351,12 +427,17 @@ export function translate_world(gameObjectIdentifier : GameObjectIdentifier, del
*
* @category Transform
*/
-export function translate_local(gameObjectIdentifier : GameObjectIdentifier, deltaPosition : Vector3) : void {
+export function translate_local(
+ gameObjectIdentifier: GameObjectIdentifier,
+ deltaPosition: Vector3
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(deltaPosition);
- return getInstance()
- .translateLocalInternal(gameObjectIdentifier, deltaPosition);
+ return getInstance().translateLocalInternal(
+ gameObjectIdentifier,
+ deltaPosition
+ );
}
/**
@@ -367,12 +448,14 @@ export function translate_local(gameObjectIdentifier : GameObjectIdentifier, del
*
* @category Transform
*/
-export function rotate_world(gameObjectIdentifier : GameObjectIdentifier, angles : Vector3) : void {
+export function rotate_world(
+ gameObjectIdentifier: GameObjectIdentifier,
+ angles: Vector3
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(angles);
- return getInstance()
- .rotateWorldInternal(gameObjectIdentifier, angles);
+ return getInstance().rotateWorldInternal(gameObjectIdentifier, angles);
}
/**
@@ -386,13 +469,21 @@ export function rotate_world(gameObjectIdentifier : GameObjectIdentifier, angles
*
* @category Transform
*/
-export function copy_position(from : GameObjectIdentifier, to : GameObjectIdentifier, deltaPosition : Vector3) : void {
+export function copy_position(
+ from: GameObjectIdentifier,
+ to: GameObjectIdentifier,
+ deltaPosition: Vector3
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(from);
checkGameObjectIdentifierParameter(to);
checkVector3Parameter(deltaPosition);
- return getInstance()
- .copyTransformPropertiesInternal('position', from, to, deltaPosition);
+ return getInstance().copyTransformPropertiesInternal(
+ 'position',
+ from,
+ to,
+ deltaPosition
+ );
}
/**
@@ -406,13 +497,21 @@ export function copy_position(from : GameObjectIdentifier, to : GameObjectIdenti
*
* @category Transform
*/
-export function copy_rotation(from : GameObjectIdentifier, to : GameObjectIdentifier, deltaRotation : Vector3) : void {
+export function copy_rotation(
+ from: GameObjectIdentifier,
+ to: GameObjectIdentifier,
+ deltaRotation: Vector3
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(from);
checkGameObjectIdentifierParameter(to);
checkVector3Parameter(deltaRotation);
- return getInstance()
- .copyTransformPropertiesInternal('rotation', from, to, deltaRotation);
+ return getInstance().copyTransformPropertiesInternal(
+ 'rotation',
+ from,
+ to,
+ deltaRotation
+ );
}
/**
@@ -426,13 +525,21 @@ export function copy_rotation(from : GameObjectIdentifier, to : GameObjectIdenti
*
* @category Transform
*/
-export function copy_scale(from : GameObjectIdentifier, to : GameObjectIdentifier, deltaScale : Vector3) : void {
+export function copy_scale(
+ from: GameObjectIdentifier,
+ to: GameObjectIdentifier,
+ deltaScale: Vector3
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(from);
checkGameObjectIdentifierParameter(to);
checkVector3Parameter(deltaScale);
- return getInstance()
- .copyTransformPropertiesInternal('scale', from, to, deltaScale);
+ return getInstance().copyTransformPropertiesInternal(
+ 'scale',
+ from,
+ to,
+ deltaScale
+ );
}
/**
@@ -447,12 +554,14 @@ export function copy_scale(from : GameObjectIdentifier, to : GameObjectIdentifie
*
* @category Transform
*/
-export function look_at(gameObjectIdentifier : GameObjectIdentifier, position : Vector3) : void {
+export function look_at(
+ gameObjectIdentifier: GameObjectIdentifier,
+ position: Vector3
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(position);
- getInstance()
- .lookAtPositionInternal(gameObjectIdentifier, position);
+ getInstance().lookAtPositionInternal(gameObjectIdentifier, position);
}
/**
@@ -464,22 +573,41 @@ export function look_at(gameObjectIdentifier : GameObjectIdentifier, position :
* @return The value of the distance between these two GameObjects
* @category Transform
*/
-export function gameobject_distance(gameObjectIdentifier_A : GameObjectIdentifier, gameObjectIdentifier_B : GameObjectIdentifier) : number {
+export function gameobject_distance(
+ gameObjectIdentifier_A: GameObjectIdentifier,
+ gameObjectIdentifier_B: GameObjectIdentifier
+): number {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier_A);
checkGameObjectIdentifierParameter(gameObjectIdentifier_B);
- return getInstance()
- .gameObjectDistanceInternal(gameObjectIdentifier_A, gameObjectIdentifier_B);
-}
-
-function checkKeyCodeValidityAndToLowerCase(keyCode : string) : string {
- if (typeof (keyCode) !== 'string') throw new Error(`Key code must be a string! Given type: ${typeof (keyCode)}`);
- if (keyCode === 'LeftMouseBtn' || keyCode === 'RightMouseBtn' || keyCode === 'MiddleMouseBtn' || keyCode === 'Space' || keyCode === 'LeftShift' || keyCode === 'RightShift') return keyCode;
+ return getInstance().gameObjectDistanceInternal(
+ gameObjectIdentifier_A,
+ gameObjectIdentifier_B
+ );
+}
+
+function checkKeyCodeValidityAndToLowerCase(keyCode: string): string {
+ if (typeof keyCode !== 'string')
+ throw new Error(`Key code must be a string! Given type: ${typeof keyCode}`);
+ if (
+ keyCode === 'LeftMouseBtn' ||
+ keyCode === 'RightMouseBtn' ||
+ keyCode === 'MiddleMouseBtn' ||
+ keyCode === 'Space' ||
+ keyCode === 'LeftShift' ||
+ keyCode === 'RightShift'
+ )
+ return keyCode;
keyCode = keyCode.toLowerCase();
- if (keyCode.length !== 1) throw new Error(`Key code must be either a string of length 1 or one among 'LeftMouseBtn', 'RightMouseBtn', 'MiddleMouseBtn', 'Space', 'LeftShift' or 'RightShift'! Given length: ${keyCode.length}`);
+ if (keyCode.length !== 1)
+ throw new Error(
+ `Key code must be either a string of length 1 or one among 'LeftMouseBtn', 'RightMouseBtn', 'MiddleMouseBtn', 'Space', 'LeftShift' or 'RightShift'! Given length: ${keyCode.length}`
+ );
const char = keyCode.charAt(0);
if (!((char >= 'a' && char <= 'z') || (char >= '0' && char <= '9'))) {
- throw new Error(`Key code must be either a letter between A-Z or a-z or 0-9 or one among 'LeftMouseBtn', 'RightMouseBtn', 'MiddleMouseBtn', 'Space', 'LeftShift' or 'RightShift'! Given: ${keyCode}`);
+ throw new Error(
+ `Key code must be either a letter between A-Z or a-z or 0-9 or one among 'LeftMouseBtn', 'RightMouseBtn', 'MiddleMouseBtn', 'Space', 'LeftShift' or 'RightShift'! Given: ${keyCode}`
+ );
}
return keyCode;
}
@@ -493,11 +621,10 @@ function checkKeyCodeValidityAndToLowerCase(keyCode : string) : string {
* @param keyCode The key to detact input for.
* @category Input
*/
-export function get_key_down(keyCode : string) : boolean {
+export function get_key_down(keyCode: string): boolean {
checkUnityAcademyExistence();
keyCode = checkKeyCodeValidityAndToLowerCase(keyCode);
- return getInstance()
- .getKeyState(keyCode) === 1;
+ return getInstance().getKeyState(keyCode) === 1;
}
/**
@@ -509,11 +636,10 @@ export function get_key_down(keyCode : string) : boolean {
* @param keyCode The key to detact input for.
* @category Input
*/
-export function get_key(keyCode : string) : boolean {
+export function get_key(keyCode: string): boolean {
checkUnityAcademyExistence();
keyCode = checkKeyCodeValidityAndToLowerCase(keyCode);
- const keyState = getInstance()
- .getKeyState(keyCode);
+ const keyState = getInstance().getKeyState(keyCode);
return keyState === 1 || keyState === 2 || keyState === 3;
}
@@ -526,11 +652,10 @@ export function get_key(keyCode : string) : boolean {
* @param keyCode The key to detact input for.
* @category Input
*/
-export function get_key_up(keyCode : string) : boolean {
+export function get_key_up(keyCode: string): boolean {
checkUnityAcademyExistence();
keyCode = checkKeyCodeValidityAndToLowerCase(keyCode);
- return getInstance()
- .getKeyState(keyCode) === 3;
+ return getInstance().getKeyState(keyCode) === 3;
}
/**
@@ -544,13 +669,18 @@ export function get_key_up(keyCode : string) : boolean {
* @param animatorStateName The name for the animator state to play.
* @category Common
*/
-export function play_animator_state(gameObjectIdentifier : GameObjectIdentifier, animatorStateName : string) : void {
+export function play_animator_state(
+ gameObjectIdentifier: GameObjectIdentifier,
+ animatorStateName: string
+): void {
checkUnityAcademyExistence();
checkIs3DMode();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(animatorStateName, 'string');
- getInstance()
- .playAnimatorStateInternal(gameObjectIdentifier, animatorStateName);
+ getInstance().playAnimatorStateInternal(
+ gameObjectIdentifier,
+ animatorStateName
+ );
}
/**
@@ -565,11 +695,12 @@ export function play_animator_state(gameObjectIdentifier : GameObjectIdentifier,
* @param gameObjectIdentifier The identifier for the GameObject that you want to apply rigidbody on.
* @category Physics - Rigidbody
*/
-export function apply_rigidbody(gameObjectIdentifier : GameObjectIdentifier) : void {
+export function apply_rigidbody(
+ gameObjectIdentifier: GameObjectIdentifier
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
- getInstance()
- .applyRigidbodyInternal(gameObjectIdentifier);
+ getInstance().applyRigidbodyInternal(gameObjectIdentifier);
}
/**
@@ -581,11 +712,10 @@ export function apply_rigidbody(gameObjectIdentifier : GameObjectIdentifier) : v
* @return The mass of the rigidbody attached on the GameObject
* @category Physics - Rigidbody
*/
-export function get_mass(gameObjectIdentifier : GameObjectIdentifier) : number {
+export function get_mass(gameObjectIdentifier: GameObjectIdentifier): number {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
- return getInstance()
- .getRigidbodyNumericalProp('mass', gameObjectIdentifier);
+ return getInstance().getRigidbodyNumericalProp('mass', gameObjectIdentifier);
}
/**
@@ -597,12 +727,14 @@ export function get_mass(gameObjectIdentifier : GameObjectIdentifier) : number {
* @param mass The value for the new mass.
* @category Physics - Rigidbody
*/
-export function set_mass(gameObjectIdentifier : GameObjectIdentifier, mass : number) : void {
+export function set_mass(
+ gameObjectIdentifier: GameObjectIdentifier,
+ mass: number
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(mass, 'number');
- getInstance()
- .setRigidbodyNumericalProp('mass', gameObjectIdentifier, mass);
+ getInstance().setRigidbodyNumericalProp('mass', gameObjectIdentifier, mass);
}
/**
@@ -614,11 +746,15 @@ export function set_mass(gameObjectIdentifier : GameObjectIdentifier, mass : num
* @return the velocity at this moment represented in a Vector3.
* @category Physics - Rigidbody
*/
-export function get_velocity(gameObjectIdentifier : GameObjectIdentifier) : Vector3 {
+export function get_velocity(
+ gameObjectIdentifier: GameObjectIdentifier
+): Vector3 {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
- return getInstance()
- .getRigidbodyVelocityVector3Prop('velocity', gameObjectIdentifier);
+ return getInstance().getRigidbodyVelocityVector3Prop(
+ 'velocity',
+ gameObjectIdentifier
+ );
}
/**
@@ -630,12 +766,18 @@ export function get_velocity(gameObjectIdentifier : GameObjectIdentifier) : Vect
* @param velocity The new velocity for the rigidbody attached on the GameObject.
* @category Physics - Rigidbody
*/
-export function set_velocity(gameObjectIdentifier : GameObjectIdentifier, velocity : Vector3) : void {
+export function set_velocity(
+ gameObjectIdentifier: GameObjectIdentifier,
+ velocity: Vector3
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(velocity);
- getInstance()
- .setRigidbodyVelocityVector3Prop('velocity', gameObjectIdentifier, velocity);
+ getInstance().setRigidbodyVelocityVector3Prop(
+ 'velocity',
+ gameObjectIdentifier,
+ velocity
+ );
}
/**
@@ -649,11 +791,15 @@ export function set_velocity(gameObjectIdentifier : GameObjectIdentifier, veloci
* @return the angular velocity at this moment represented in a Vector3.
* @category Physics - Rigidbody
*/
-export function get_angular_velocity(gameObjectIdentifier : GameObjectIdentifier) : Vector3 {
+export function get_angular_velocity(
+ gameObjectIdentifier: GameObjectIdentifier
+): Vector3 {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
- return getInstance()
- .getRigidbodyVelocityVector3Prop('angularVelocity', gameObjectIdentifier);
+ return getInstance().getRigidbodyVelocityVector3Prop(
+ 'angularVelocity',
+ gameObjectIdentifier
+ );
}
/**
@@ -667,12 +813,18 @@ export function get_angular_velocity(gameObjectIdentifier : GameObjectIdentifier
* @param angularVelocity The new angular velocity for the rigidbody attached on the GameObject.
* @category Physics - Rigidbody
*/
-export function set_angular_velocity(gameObjectIdentifier : GameObjectIdentifier, angularVelocity : Vector3) : void {
+export function set_angular_velocity(
+ gameObjectIdentifier: GameObjectIdentifier,
+ angularVelocity: Vector3
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(angularVelocity);
- getInstance()
- .setRigidbodyVelocityVector3Prop('angularVelocity', gameObjectIdentifier, angularVelocity);
+ getInstance().setRigidbodyVelocityVector3Prop(
+ 'angularVelocity',
+ gameObjectIdentifier,
+ angularVelocity
+ );
}
/**
@@ -686,12 +838,14 @@ export function set_angular_velocity(gameObjectIdentifier : GameObjectIdentifier
* @param value The value of the new drag.
* @category Physics - Rigidbody
*/
-export function set_drag(gameObjectIdentifier : GameObjectIdentifier, value: number) : void {
+export function set_drag(
+ gameObjectIdentifier: GameObjectIdentifier,
+ value: number
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(value, 'number');
- getInstance()
- .setRigidbodyNumericalProp('drag', gameObjectIdentifier, value);
+ getInstance().setRigidbodyNumericalProp('drag', gameObjectIdentifier, value);
}
/**
@@ -705,12 +859,18 @@ export function set_drag(gameObjectIdentifier : GameObjectIdentifier, value: num
* @param value The value of the new angular drag.
* @category Physics - Rigidbody
*/
-export function set_angular_drag(gameObjectIdentifier : GameObjectIdentifier, value: number) : void {
+export function set_angular_drag(
+ gameObjectIdentifier: GameObjectIdentifier,
+ value: number
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(value, 'number');
- getInstance()
- .setRigidbodyNumericalProp('angularDrag', gameObjectIdentifier, value);
+ getInstance().setRigidbodyNumericalProp(
+ 'angularDrag',
+ gameObjectIdentifier,
+ value
+ );
}
/**
@@ -722,12 +882,14 @@ export function set_angular_drag(gameObjectIdentifier : GameObjectIdentifier, va
* @param {useGravity} Set to true if you want gravity to be applied on this rigidbody, false otherwise.
* @category Physics - Rigidbody
*/
-export function set_use_gravity(gameObjectIdentifier : GameObjectIdentifier, useGravity : boolean) : void {
+export function set_use_gravity(
+ gameObjectIdentifier: GameObjectIdentifier,
+ useGravity: boolean
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(useGravity, 'boolean');
- getInstance()
- .setUseGravityInternal(gameObjectIdentifier, useGravity);
+ getInstance().setUseGravityInternal(gameObjectIdentifier, useGravity);
}
/**
@@ -739,12 +901,14 @@ export function set_use_gravity(gameObjectIdentifier : GameObjectIdentifier, use
* @param The force vector.
* @category Physics - Rigidbody
*/
-export function add_impulse_force(gameObjectIdentifier : GameObjectIdentifier, force : Vector3) : void {
+export function add_impulse_force(
+ gameObjectIdentifier: GameObjectIdentifier,
+ force: Vector3
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(force);
- getInstance()
- .addImpulseForceInternal(gameObjectIdentifier, force);
+ getInstance().addImpulseForceInternal(gameObjectIdentifier, force);
}
/**
@@ -757,11 +921,12 @@ export function add_impulse_force(gameObjectIdentifier : GameObjectIdentifier, f
* @param gameObjectIdentifier The identifier for the GameObject that you want to remove colliders for.
* @category Physics - Collision
*/
-export function remove_collider_components(gameObjectIdentifier : GameObjectIdentifier) : void {
+export function remove_collider_components(
+ gameObjectIdentifier: GameObjectIdentifier
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
- getInstance()
- .removeColliderComponentsInternal(gameObjectIdentifier);
+ getInstance().removeColliderComponentsInternal(gameObjectIdentifier);
}
/**
@@ -784,12 +949,17 @@ export function remove_collider_components(gameObjectIdentifier : GameObjectIden
* @category Physics - Collision
* @category Outside Lifecycle
*/
-export function on_collision_enter(gameObjectIdentifier : GameObjectIdentifier, eventFunction : Function) : void {
+export function on_collision_enter(
+ gameObjectIdentifier: GameObjectIdentifier,
+ eventFunction: Function
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(eventFunction, 'function');
- getInstance()
- .setOnCollisionEnterInternal(gameObjectIdentifier, eventFunction);
+ getInstance().setOnCollisionEnterInternal(
+ gameObjectIdentifier,
+ eventFunction
+ );
}
/**
@@ -812,12 +982,14 @@ export function on_collision_enter(gameObjectIdentifier : GameObjectIdentifier,
* @category Physics - Collision
* @category Outside Lifecycle
*/
-export function on_collision_stay(gameObjectIdentifier : GameObjectIdentifier, eventFunction : Function) : void {
+export function on_collision_stay(
+ gameObjectIdentifier: GameObjectIdentifier,
+ eventFunction: Function
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(eventFunction, 'function');
- getInstance()
- .setOnCollisionStayInternal(gameObjectIdentifier, eventFunction);
+ getInstance().setOnCollisionStayInternal(gameObjectIdentifier, eventFunction);
}
/**
@@ -840,12 +1012,14 @@ export function on_collision_stay(gameObjectIdentifier : GameObjectIdentifier, e
* @category Physics - Collision
* @category Outside Lifecycle
*/
-export function on_collision_exit(gameObjectIdentifier : GameObjectIdentifier, eventFunction : Function) : void {
+export function on_collision_exit(
+ gameObjectIdentifier: GameObjectIdentifier,
+ eventFunction: Function
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(eventFunction, 'function');
- getInstance()
- .setOnCollisionExitInternal(gameObjectIdentifier, eventFunction);
+ getInstance().setOnCollisionExitInternal(gameObjectIdentifier, eventFunction);
}
/**
@@ -862,13 +1036,12 @@ export function on_collision_exit(gameObjectIdentifier : GameObjectIdentifier, e
* @param y The y coordinate of the text (in screen position).
* @category Graphical User Interface
*/
-export function gui_label(text : string, x : number, y : number) : void {
+export function gui_label(text: string, x: number, y: number): void {
checkUnityAcademyExistence();
checkParameterType(text, 'string');
checkParameterType(x, 'number');
checkParameterType(y, 'number');
- getInstance()
- .onGUI_Label(text, x, y);
+ getInstance().onGUI_Label(text, x, y);
}
/**
@@ -910,7 +1083,14 @@ export function gui_label(text : string, x : number, y : number) : void {
* @param onClick The function that will be called when user clicks the button on screen.
* @category Graphical User Interface
*/
-export function gui_button(text : string, x: number, y : number, width : number, height : number, onClick : Function) : void {
+export function gui_button(
+ text: string,
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ onClick: Function
+): void {
checkUnityAcademyExistence();
checkParameterType(text, 'string');
checkParameterType(x, 'number');
@@ -918,8 +1098,7 @@ export function gui_button(text : string, x: number, y : number, width : number,
checkParameterType(width, 'number');
checkParameterType(height, 'number');
checkParameterType(onClick, 'function');
- getInstance()
- .onGUI_Button(text, x, y, width, height, onClick);
+ getInstance().onGUI_Button(text, x, y, width, height, onClick);
}
/**
@@ -935,10 +1114,11 @@ export function gui_button(text : string, x: number, y : number, width : number,
* @category Camera
* @category Outside Lifecycle
*/
-export function get_main_camera_following_target() : GameObjectIdentifier {
+export function get_main_camera_following_target(): GameObjectIdentifier {
checkUnityAcademyExistence();
- return getInstance()
- .getGameObjectIdentifierForPrimitiveGameObject('MainCameraFollowingTarget');
+ return getInstance().getGameObjectIdentifierForPrimitiveGameObject(
+ 'MainCameraFollowingTarget'
+ );
}
/**
@@ -952,10 +1132,9 @@ export function get_main_camera_following_target() : GameObjectIdentifier {
* @category Camera
* @category Outside Lifecycle
*/
-export function request_for_main_camera_control() : GameObjectIdentifier {
+export function request_for_main_camera_control(): GameObjectIdentifier {
checkUnityAcademyExistence();
- return getInstance()
- .requestForMainCameraControlInternal();
+ return getInstance().requestForMainCameraControlInternal();
}
/**
@@ -967,12 +1146,19 @@ export function request_for_main_camera_control() : GameObjectIdentifier {
*
* @category Common
*/
-export function set_custom_prop(gameObjectIdentifier : GameObjectIdentifier, propName : string, value : any) : void {
+export function set_custom_prop(
+ gameObjectIdentifier: GameObjectIdentifier,
+ propName: string,
+ value: any
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(propName, 'string');
- getInstance()
- .setCustomPropertyInternal(gameObjectIdentifier, propName, value);
+ getInstance().setCustomPropertyInternal(
+ gameObjectIdentifier,
+ propName,
+ value
+ );
}
/**
@@ -985,12 +1171,17 @@ export function set_custom_prop(gameObjectIdentifier : GameObjectIdentifier, pro
*
* @category Common
*/
-export function get_custom_prop(gameObjectIdentifier : GameObjectIdentifier, propName : string) : any {
+export function get_custom_prop(
+ gameObjectIdentifier: GameObjectIdentifier,
+ propName: string
+): any {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(propName, 'string');
- return getInstance()
- .getCustomPropertyInternal(gameObjectIdentifier, propName);
+ return getInstance().getCustomPropertyInternal(
+ gameObjectIdentifier,
+ propName
+ );
}
/**
@@ -1003,7 +1194,7 @@ export function get_custom_prop(gameObjectIdentifier : GameObjectIdentifier, pro
*
* @category Maths
*/
-export function vector3(x : number, y : number, z : number) : Vector3 {
+export function vector3(x: number, y: number, z: number): Vector3 {
checkParameterType(x, 'number');
checkParameterType(y, 'number');
checkParameterType(z, 'number');
@@ -1018,7 +1209,7 @@ export function vector3(x : number, y : number, z : number) : Vector3 {
*
* @category Maths
*/
-export function get_x(vector : Vector3) : number {
+export function get_x(vector: Vector3): number {
checkVector3Parameter(vector);
return vector.x;
}
@@ -1031,7 +1222,7 @@ export function get_x(vector : Vector3) : number {
*
* @category Maths
*/
-export function get_y(vector : Vector3) : number {
+export function get_y(vector: Vector3): number {
checkVector3Parameter(vector);
return vector.y;
}
@@ -1044,7 +1235,7 @@ export function get_y(vector : Vector3) : number {
*
* @category Maths
*/
-export function get_z(vector : Vector3) : number {
+export function get_z(vector: Vector3): number {
checkVector3Parameter(vector);
return vector.z;
}
@@ -1057,7 +1248,7 @@ export function get_z(vector : Vector3) : number {
*
* @category Maths
*/
-export function scale_vector(vector : Vector3, factor : number) : Vector3 {
+export function scale_vector(vector: Vector3, factor: number): Vector3 {
checkVector3Parameter(vector);
checkParameterType(factor, 'number');
return scaleVector(vector, factor);
@@ -1071,7 +1262,7 @@ export function scale_vector(vector : Vector3, factor : number) : Vector3 {
*
* @category Maths
*/
-export function add_vectors(vectorA : Vector3, vectorB : Vector3) : Vector3 {
+export function add_vectors(vectorA: Vector3, vectorB: Vector3): Vector3 {
checkVector3Parameter(vectorA);
checkVector3Parameter(vectorB);
return addVectors(vectorA, vectorB);
@@ -1085,7 +1276,7 @@ export function add_vectors(vectorA : Vector3, vectorB : Vector3) : Vector3 {
*
* @category Maths
*/
-export function vector_difference(vectorA : Vector3, vectorB : Vector3) : Vector3 {
+export function vector_difference(vectorA: Vector3, vectorB: Vector3): Vector3 {
checkVector3Parameter(vectorA);
checkVector3Parameter(vectorB);
return vectorDifference(vectorA, vectorB);
@@ -1099,7 +1290,7 @@ export function vector_difference(vectorA : Vector3, vectorB : Vector3) : Vector
*
* @category Maths
*/
-export function dot(vectorA : Vector3, vectorB : Vector3) : number {
+export function dot(vectorA: Vector3, vectorB: Vector3): number {
checkVector3Parameter(vectorA);
checkVector3Parameter(vectorB);
return dotProduct(vectorA, vectorB);
@@ -1113,7 +1304,7 @@ export function dot(vectorA : Vector3, vectorB : Vector3) : number {
*
* @category Maths
*/
-export function cross(vectorA : Vector3, vectorB : Vector3) : Vector3 {
+export function cross(vectorA: Vector3, vectorB: Vector3): Vector3 {
checkVector3Parameter(vectorA);
checkVector3Parameter(vectorB);
return crossProduct(vectorA, vectorB);
@@ -1126,7 +1317,7 @@ export function cross(vectorA : Vector3, vectorB : Vector3) : Vector3 {
*
* @category Maths
*/
-export function normalize(vector : Vector3) : Vector3 {
+export function normalize(vector: Vector3): Vector3 {
checkVector3Parameter(vector);
return normalizeVector(vector);
}
@@ -1138,7 +1329,7 @@ export function normalize(vector : Vector3) : Vector3 {
*
* @category Maths
*/
-export function magnitude(vector : Vector3) : number {
+export function magnitude(vector: Vector3): number {
checkVector3Parameter(vector);
return vectorMagnitude(vector);
}
@@ -1149,7 +1340,7 @@ export function magnitude(vector : Vector3) : number {
*
* @category Maths
*/
-export function zero_vector() : Vector3 {
+export function zero_vector(): Vector3 {
return zeroVector();
}
@@ -1163,7 +1354,7 @@ export function zero_vector() : Vector3 {
*
* @category Maths
*/
-export function point_distance(pointA : Vector3, pointB : Vector3) : number {
+export function point_distance(pointA: Vector3, pointB: Vector3): number {
checkVector3Parameter(pointA);
checkVector3Parameter(pointB);
return pointDistance(pointA, pointB);
@@ -1176,11 +1367,10 @@ export function point_distance(pointA : Vector3, pointB : Vector3) : number {
* @category Sound / Audio
* @category Outside Lifecycle
*/
-export function load_audio_clip_mp3(audioUrl: string) : AudioClipIdentifier {
+export function load_audio_clip_mp3(audioUrl: string): AudioClipIdentifier {
checkUnityAcademyExistence();
checkParameterType(audioUrl, 'string');
- return getInstance()
- .loadAudioClipInternal(audioUrl, 'mp3');
+ return getInstance().loadAudioClipInternal(audioUrl, 'mp3');
}
/**
@@ -1190,11 +1380,10 @@ export function load_audio_clip_mp3(audioUrl: string) : AudioClipIdentifier {
* @category Sound / Audio
* @category Outside Lifecycle
*/
-export function load_audio_clip_ogg(audioUrl: string) : AudioClipIdentifier {
+export function load_audio_clip_ogg(audioUrl: string): AudioClipIdentifier {
checkUnityAcademyExistence();
checkParameterType(audioUrl, 'string');
- return getInstance()
- .loadAudioClipInternal(audioUrl, 'ogg');
+ return getInstance().loadAudioClipInternal(audioUrl, 'ogg');
}
/**
@@ -1204,11 +1393,10 @@ export function load_audio_clip_ogg(audioUrl: string) : AudioClipIdentifier {
* @category Sound / Audio
* @category Outside Lifecycle
*/
-export function load_audio_clip_wav(audioUrl: string) : AudioClipIdentifier {
+export function load_audio_clip_wav(audioUrl: string): AudioClipIdentifier {
checkUnityAcademyExistence();
checkParameterType(audioUrl, 'string');
- return getInstance()
- .loadAudioClipInternal(audioUrl, 'wav');
+ return getInstance().loadAudioClipInternal(audioUrl, 'wav');
}
/**
@@ -1224,11 +1412,12 @@ export function load_audio_clip_wav(audioUrl: string) : AudioClipIdentifier {
* @category Sound / Audio
* @category Outside Lifecycle
*/
-export function instantiate_audio_source(audioClip : AudioClipIdentifier) : GameObjectIdentifier {
+export function instantiate_audio_source(
+ audioClip: AudioClipIdentifier
+): GameObjectIdentifier {
// todo: check audio clip identifier type
checkUnityAcademyExistence();
- return getInstance()
- .instantiateAudioSourceInternal(audioClip);
+ return getInstance().instantiateAudioSourceInternal(audioClip);
}
/**
@@ -1239,11 +1428,10 @@ export function instantiate_audio_source(audioClip : AudioClipIdentifier) : Game
*
* @category Sound / Audio
*/
-export function play_audio(audioSrc : GameObjectIdentifier) : void {
+export function play_audio(audioSrc: GameObjectIdentifier): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
- getInstance()
- .setAudioSourceProp('isPlaying', audioSrc, true);
+ getInstance().setAudioSourceProp('isPlaying', audioSrc, true);
}
/**
@@ -1254,11 +1442,10 @@ export function play_audio(audioSrc : GameObjectIdentifier) : void {
*
* @category Sound / Audio
*/
-export function pause_audio(audioSrc : GameObjectIdentifier) : void {
+export function pause_audio(audioSrc: GameObjectIdentifier): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
- getInstance()
- .setAudioSourceProp('isPlaying', audioSrc, false);
+ getInstance().setAudioSourceProp('isPlaying', audioSrc, false);
}
/**
@@ -1270,12 +1457,14 @@ export function pause_audio(audioSrc : GameObjectIdentifier) : void {
*
* @category Sound / Audio
*/
-export function set_audio_play_speed(audioSrc : GameObjectIdentifier, speed : number) : void {
+export function set_audio_play_speed(
+ audioSrc: GameObjectIdentifier,
+ speed: number
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
checkParameterType(speed, 'number');
- getInstance()
- .setAudioSourceProp('playSpeed', audioSrc, speed);
+ getInstance().setAudioSourceProp('playSpeed', audioSrc, speed);
}
/**
@@ -1287,11 +1476,12 @@ export function set_audio_play_speed(audioSrc : GameObjectIdentifier, speed : nu
*
* @category Sound / Audio
*/
-export function get_audio_play_progress(audioSrc : GameObjectIdentifier) : number {
+export function get_audio_play_progress(
+ audioSrc: GameObjectIdentifier
+): number {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
- return getInstance()
- .getAudioSourceProp('playProgress', audioSrc);
+ return getInstance().getAudioSourceProp('playProgress', audioSrc);
}
/**
@@ -1303,59 +1493,70 @@ export function get_audio_play_progress(audioSrc : GameObjectIdentifier) : numbe
*
* @category Sound / Audio
*/
-export function set_audio_play_progress(audioSrc : GameObjectIdentifier, progress : number) : void {
+export function set_audio_play_progress(
+ audioSrc: GameObjectIdentifier,
+ progress: number
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
checkParameterType(progress, 'number');
- getInstance()
- .setAudioSourceProp('playProgress', audioSrc, progress);
+ getInstance().setAudioSourceProp('playProgress', audioSrc, progress);
}
/**
*
* @category Sound / Audio
*/
-export function change_audio_clip(audioSrc : GameObjectIdentifier, newAudioClip : AudioClipIdentifier) : void {
+export function change_audio_clip(
+ audioSrc: GameObjectIdentifier,
+ newAudioClip: AudioClipIdentifier
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
// todo: check audio clip identifier type
- getInstance()
- .setAudioSourceProp('audioClipIdentifier', audioSrc, newAudioClip);
+ getInstance().setAudioSourceProp(
+ 'audioClipIdentifier',
+ audioSrc,
+ newAudioClip
+ );
}
/**
*
* @category Sound / Audio
*/
-export function set_audio_looping(audioSrc : GameObjectIdentifier, looping : boolean) : void {
+export function set_audio_looping(
+ audioSrc: GameObjectIdentifier,
+ looping: boolean
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
checkParameterType(looping, 'boolean');
- getInstance()
- .setAudioSourceProp('isLooping', audioSrc, looping);
+ getInstance().setAudioSourceProp('isLooping', audioSrc, looping);
}
/**
*
* @category Sound / Audio
*/
-export function set_audio_volume(audioSrc : GameObjectIdentifier, volume : number) : void {
+export function set_audio_volume(
+ audioSrc: GameObjectIdentifier,
+ volume: number
+): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
checkParameterType(volume, 'number');
- getInstance()
- .setAudioSourceProp('volume', audioSrc, volume);
+ getInstance().setAudioSourceProp('volume', audioSrc, volume);
}
/**
*
* @category Sound / Audio
*/
-export function is_audio_playing(audioSrc : GameObjectIdentifier) : boolean {
+export function is_audio_playing(audioSrc: GameObjectIdentifier): boolean {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
- return getInstance()
- .getAudioSourceProp('isPlaying', audioSrc);
+ return getInstance().getAudioSourceProp('isPlaying', audioSrc);
}
/**
@@ -1369,11 +1570,10 @@ export function is_audio_playing(audioSrc : GameObjectIdentifier) : boolean {
* @category Common
* @category Outside Lifecycle
*/
-export function debug_log(content : any) : void {
+export function debug_log(content: any): void {
checkUnityAcademyExistence();
const contentStr = content.toString();
- getInstance()
- .studentLogger(contentStr, 'log');
+ getInstance().studentLogger(contentStr, 'log');
}
/**
@@ -1387,11 +1587,10 @@ export function debug_log(content : any) : void {
* @category Common
* @category Outside Lifecycle
*/
-export function debug_logwarning(content : any) : void {
+export function debug_logwarning(content: any): void {
checkUnityAcademyExistence();
const contentStr = content.toString();
- getInstance()
- .studentLogger(contentStr, 'warning');
+ getInstance().studentLogger(contentStr, 'warning');
}
/**
@@ -1407,11 +1606,10 @@ export function debug_logwarning(content : any) : void {
* @category Common
* @category Outside Lifecycle
*/
-export function debug_logerror(content : any) : void {
+export function debug_logerror(content: any): void {
checkUnityAcademyExistence();
const contentStr = content.toString();
- getInstance()
- .studentLogger(contentStr, 'error');
+ getInstance().studentLogger(contentStr, 'error');
}
/**
@@ -1424,7 +1622,11 @@ export function debug_logerror(content : any) : void {
*
* @category Sound / Audio
*/
-export function set_audio_listener_position(positionX: number, positionY: number, positionZ: number) {
+export function set_audio_listener_position(
+ positionX: number,
+ positionY: number,
+ positionZ: number
+) {
// todo: check audio clip identifier type
checkUnityAcademyExistence();
checkParameterType(positionX, 'number');
@@ -1443,7 +1645,14 @@ export function set_audio_listener_position(positionX: number, positionY: number
*
* @category Sound / Audio
*/
-export function play_audio_clip_3d_sound(audioClip : AudioClipIdentifier, volume: number, loop: boolean, positionX: number, positionY: number, positionZ: number) {
+export function play_audio_clip_3d_sound(
+ audioClip: AudioClipIdentifier,
+ volume: number,
+ loop: boolean,
+ positionX: number,
+ positionY: number,
+ positionZ: number
+) {
// todo: check audio clip identifier type
checkUnityAcademyExistence();
checkParameterType(volume, 'number');
diff --git a/src/bundles/unity_academy/index.ts b/src/bundles/unity_academy/index.ts
index c10c51e05..0c403919e 100644
--- a/src/bundles/unity_academy/index.ts
+++ b/src/bundles/unity_academy/index.ts
@@ -91,68 +91,13 @@
*/
export {
- init_unity_academy_2d,
- init_unity_academy_3d,
- same_gameobject,
- set_start,
- set_update,
- instantiate,
- instantiate_sprite,
- instantiate_empty,
- destroy,
- delta_time,
- get_position,
- set_position,
- get_rotation_euler,
- set_rotation_euler,
- get_scale,
- set_scale,
- translate_world,
- translate_local,
- rotate_world,
+ add_impulse_force,
+ add_vectors,
+ apply_rigidbody,
copy_position,
copy_rotation,
copy_scale,
- look_at,
- gameobject_distance,
- get_key_down,
- get_key,
- get_key_up,
- play_animator_state,
- apply_rigidbody,
- get_mass,
- set_mass,
- set_drag,
- set_angular_drag,
- get_velocity,
- set_velocity,
- get_angular_velocity,
- set_angular_velocity,
- add_impulse_force,
- set_use_gravity,
- remove_collider_components,
- on_collision_enter,
- on_collision_stay,
- on_collision_exit,
- gui_label,
- gui_button,
- get_main_camera_following_target,
- request_for_main_camera_control,
- set_custom_prop,
- get_custom_prop,
- vector3,
- get_x,
- get_y,
- get_z,
- scale_vector,
- add_vectors,
- vector_difference,
- dot,
cross,
- normalize,
- magnitude,
- zero_vector,
- point_distance,
/* I will uncomment these audio functions when I totally finish audio support.
load_audio_clip_mp3,
load_audio_clip_ogg,
@@ -172,6 +117,61 @@ export {
play_audio_clip_3d_sound,
*/
debug_log,
+ debug_logerror,
debug_logwarning,
- debug_logerror
+ delta_time,
+ destroy,
+ dot,
+ gameobject_distance,
+ get_angular_velocity,
+ get_custom_prop,
+ get_key,
+ get_key_down,
+ get_key_up,
+ get_main_camera_following_target,
+ get_mass,
+ get_position,
+ get_rotation_euler,
+ get_scale,
+ get_velocity,
+ get_x,
+ get_y,
+ get_z,
+ gui_button,
+ gui_label,
+ init_unity_academy_2d,
+ init_unity_academy_3d,
+ instantiate,
+ instantiate_empty,
+ instantiate_sprite,
+ look_at,
+ magnitude,
+ normalize,
+ on_collision_enter,
+ on_collision_exit,
+ on_collision_stay,
+ play_animator_state,
+ point_distance,
+ remove_collider_components,
+ request_for_main_camera_control,
+ rotate_world,
+ same_gameobject,
+ scale_vector,
+ set_angular_drag,
+ set_angular_velocity,
+ set_custom_prop,
+ set_drag,
+ set_mass,
+ set_position,
+ set_rotation_euler,
+ set_scale,
+ set_start,
+ set_update,
+ set_use_gravity,
+ set_velocity,
+ translate_local,
+ translate_world,
+ vector3,
+ vector_difference,
+ zero_vector
} from './functions';
diff --git a/src/bundles/wasm/index.ts b/src/bundles/wasm/index.ts
index c7e8cf577..6051362ed 100644
--- a/src/bundles/wasm/index.ts
+++ b/src/bundles/wasm/index.ts
@@ -81,7 +81,4 @@
* @module wasm
* @author Kim Yongbeom
*/
-export {
- wcompile,
- wrun
-} from './wabt';
+export { wcompile, wrun } from './wabt';
From ed00f2c9e9743f8706d9743e013064f8cebb7a4e Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Tue, 26 Mar 2024 21:56:07 +0800
Subject: [PATCH 05/39] Reformat config files with Prettier
---
eslint.config.js | 43 ++++++++++++++++++++++++++-----------------
vite.config.ts | 14 ++++++++------
2 files changed, 34 insertions(+), 23 deletions(-)
diff --git a/eslint.config.js b/eslint.config.js
index 639c34dbc..62ea2977b 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -7,7 +7,12 @@ import globals from 'globals';
import tseslint from 'typescript-eslint';
const todoTreeKeywordsWarning = ['TODO', 'TODOS', 'TODO WIP', 'FIXME', 'WIP'];
-const todoTreeKeywordsAll = [...todoTreeKeywordsWarning, 'NOTE', 'NOTES', 'LIST'];
+const todoTreeKeywordsAll = [
+ ...todoTreeKeywordsWarning,
+ 'NOTE',
+ 'NOTES',
+ 'LIST'
+];
const OFF = 0;
const WARN = 1;
@@ -42,18 +47,25 @@ export default [
},
plugins: {
import: importPlugin,
- '@stylistic': stylePlugin,
+ '@stylistic': stylePlugin
},
rules: {
'import/no-duplicates': [WARN, { 'prefer-inline': false }],
'import/order': [
WARN,
{
- groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'],
+ groups: [
+ 'builtin',
+ 'external',
+ 'internal',
+ 'parent',
+ 'sibling',
+ 'index'
+ ],
alphabetize: {
order: 'asc',
orderImportKind: 'asc'
- },
+ }
}
],
@@ -70,7 +82,7 @@ export default [
WARN,
'always',
{ markers: todoTreeKeywordsAll }
- ],
+ ]
}
},
...tseslint.configs.recommended,
@@ -81,7 +93,7 @@ export default [
parser: tseslint.parser
},
plugins: {
- '@typescript-eslint': tseslint.plugin,
+ '@typescript-eslint': tseslint.plugin
},
rules: {
'no-unused-vars': OFF, // Use the typescript eslint rule instead
@@ -92,7 +104,7 @@ export default [
'@typescript-eslint/no-redundant-type-constituents': OFF, // Was ERROR
'@typescript-eslint/no-unused-vars': [WARN, { argsIgnorePattern: '^_' }], // Was ERROR
'@typescript-eslint/prefer-ts-expect-error': WARN,
- '@typescript-eslint/sort-type-constituents': WARN,
+ '@typescript-eslint/sort-type-constituents': WARN
}
},
{
@@ -107,16 +119,13 @@ export default [
'@stylistic/jsx-equals-spacing': [WARN, 'never'],
'@stylistic/jsx-indent': [WARN, 2],
'@stylistic/jsx-indent-props': [WARN, 2],
- '@stylistic/jsx-props-no-multi-spaces': WARN,
+ '@stylistic/jsx-props-no-multi-spaces': WARN
}
},
{
// Rules for bundles and tabs
files: ['src/**/*.ts*'],
- ignores: [
- '**/__tests__/**/*.ts*',
- '**/__mocks__/**/*.ts',
- ],
+ ignores: ['**/__tests__/**/*.ts*', '**/__mocks__/**/*.ts'],
languageOptions: {
globals: globals.browser,
parserOptions: {
@@ -128,8 +137,8 @@ export default [
'@typescript-eslint/no-namespace': OFF, // Was ERROR
'@typescript-eslint/no-var-requires': WARN, // Was ERROR
- '@typescript-eslint/switch-exhaustiveness-check': ERROR,
- },
+ '@typescript-eslint/switch-exhaustiveness-check': ERROR
+ }
},
{
// Rules for scripts
@@ -155,8 +164,8 @@ export default [
'@typescript-eslint/return-await': [ERROR, 'in-try-catch']
},
settings: {
- 'import/internal-regex': '^@src/',
- },
+ 'import/internal-regex': '^@src/'
+ }
},
{
// Rules for devserver,
@@ -170,7 +179,7 @@ export default [
...globals.browser,
...globals.node2020
}
- },
+ }
},
{
// Rules for tests
diff --git a/vite.config.ts b/vite.config.ts
index dcb950397..41b45e26a 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -7,12 +7,14 @@ export default defineConfig({
root: 'devserver',
resolve: {
preserveSymlinks: true,
- alias: [{
- find: /^js-slang\/context/,
- replacement: pathlib.resolve('./devserver/src/mockModuleContext')
- }]
+ alias: [
+ {
+ find: /^js-slang\/context/,
+ replacement: pathlib.resolve('./devserver/src/mockModuleContext')
+ }
+ ]
},
define: {
- 'process.env.NODE_ENV': 'development',
- },
+ 'process.env.NODE_ENV': 'development'
+ }
});
From e58323dbb446cfe32fc9f84324ed0db1aba8c5e5 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Tue, 9 Apr 2024 02:22:32 +0800
Subject: [PATCH 06/39] Report unused disable directives
---
eslint.config.js | 3 +++
1 file changed, 3 insertions(+)
diff --git a/eslint.config.js b/eslint.config.js
index 4ee15bbce..799ed359c 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -63,6 +63,9 @@ export default [
'always',
{ markers: todoTreeKeywordsAll }
],
+ },
+ linterOptions: {
+ reportUnusedDisableDirectives: 'error'
}
},
...tseslint.configs.recommended,
From f0adf32925f78600017d121cc66804087a46fe57 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Tue, 9 Apr 2024 02:50:32 +0800
Subject: [PATCH 07/39] Revert some Prettier devserver changes
---
.../components/sideContent/SideContent.tsx | 30 +++----------------
devserver/src/main.tsx | 2 +-
2 files changed, 5 insertions(+), 27 deletions(-)
diff --git a/devserver/src/components/sideContent/SideContent.tsx b/devserver/src/components/sideContent/SideContent.tsx
index 645cd5754..8f6741f57 100644
--- a/devserver/src/components/sideContent/SideContent.tsx
+++ b/devserver/src/components/sideContent/SideContent.tsx
@@ -1,11 +1,4 @@
-import {
- Card,
- Icon,
- Tab,
- Tabs,
- Tooltip,
- type TabProps
-} from '@blueprintjs/core';
+import { Card, Icon, Tab, type TabProps, Tabs, Tooltip } from '@blueprintjs/core';
import React from 'react';
import type { SideContentTab } from './types';
@@ -44,13 +37,7 @@ const renderTab = (
const iconSize = 20;
const tabTitle = (
-
+
@@ -77,9 +64,7 @@ const renderTab = (
// }
// }
// : tab.body;
- const tabPanel: React.JSX.Element = (
-
{tab.body}
- );
+ const tabPanel: React.JSX.Element =
{tab.body}
;
return
;
};
@@ -104,14 +89,7 @@ const SideContent: React.FC
= ({
if (onChange) onChange(newId, oldId);
}}
>
- {dynamicTabs.map((tab) =>
- renderTab(
- tab,
- alerts.includes(tab.id),
- editorWidth,
- sideContentHeight
- )
- )}
+ {dynamicTabs.map((tab) => renderTab(tab, alerts.includes(tab.id), editorWidth, sideContentHeight))}
diff --git a/devserver/src/main.tsx b/devserver/src/main.tsx
index 26c718f89..771c8bbb5 100644
--- a/devserver/src/main.tsx
+++ b/devserver/src/main.tsx
@@ -1,8 +1,8 @@
import React from 'react';
import ReactDOM from 'react-dom';
-import Playground from './components/Playground';
import './styles/index.scss';
+import Playground from './components/Playground';
ReactDOM.render(
From 0a1c106bdb7987af9345a54fd1bbce5623003426 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Fri, 12 Apr 2024 05:18:38 +0800
Subject: [PATCH 08/39] Revert some changes
---
devserver/src/components/ControlButton.tsx | 12 ++----------
devserver/src/styles/_application.scss | 2 +-
devserver/src/styles/_global.scss | 4 ++--
devserver/src/styles/_workspace.scss | 16 +++++-----------
devserver/src/styles/index.scss | 18 +++++++++---------
5 files changed, 19 insertions(+), 33 deletions(-)
diff --git a/devserver/src/components/ControlButton.tsx b/devserver/src/components/ControlButton.tsx
index 8ac2b8984..4b64f6ffe 100644
--- a/devserver/src/components/ControlButton.tsx
+++ b/devserver/src/components/ControlButton.tsx
@@ -1,10 +1,4 @@
-import {
- AnchorButton,
- Button,
- Icon,
- Intent,
- type IconName
-} from '@blueprintjs/core';
+import { AnchorButton, Button, Icon, type IconName, Intent } from '@blueprintjs/core';
import React from 'react';
type ButtonOptions = {
@@ -44,9 +38,7 @@ const ControlButton: React.FC = ({
...defaultOptions,
...options
};
- const iconElement = icon && (
-
- );
+ const iconElement = icon && ;
// Refer to #2417 and #2422 for why we conditionally
// set the button component. See also:
// https://blueprintjs.com/docs/#core/components/button
diff --git a/devserver/src/styles/_application.scss b/devserver/src/styles/_application.scss
index ba3fa1bc8..b276c81e8 100644
--- a/devserver/src/styles/_application.scss
+++ b/devserver/src/styles/_application.scss
@@ -6,7 +6,7 @@
*/
html {
background-size: cover;
- background-image: url("#{$images-path}/academy_background.jpg");
+ background-image: url('#{$images-path}/academy_background.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
::-webkit-scrollbar {
diff --git a/devserver/src/styles/_global.scss b/devserver/src/styles/_global.scss
index 4b59affbc..5922a82b6 100644
--- a/devserver/src/styles/_global.scss
+++ b/devserver/src/styles/_global.scss
@@ -5,8 +5,8 @@ $cadet-color-3: #34495e;
$cadet-color-4: #ced9e0;
$cadet-color-5: #ffffff;
-$images-path: "../assets";
-$achievement-assets: "https://source-academy-assets.s3-ap-southeast-1.amazonaws.com/achievement";
+$images-path: '../assets';
+$achievement-assets: 'https://source-academy-assets.s3-ap-southeast-1.amazonaws.com/achievement';
/*
Fixes height behaviour of nested flexboxes in the code editor and REPL,
diff --git a/devserver/src/styles/_workspace.scss b/devserver/src/styles/_workspace.scss
index baa53645b..f03004779 100644
--- a/devserver/src/styles/_workspace.scss
+++ b/devserver/src/styles/_workspace.scss
@@ -144,7 +144,7 @@ $code-color-error: #ff4444;
}
.ace_breakpoint:before {
- content: " \25CF";
+ content: ' \25CF';
margin-left: -10px;
color: red;
}
@@ -425,10 +425,7 @@ $code-color-error: #ff4444;
* output. Taken from react-ace
* sourcecode, font size modified.
*/
- font:
- 16px / normal "Inconsolata",
- "Consolas",
- monospace;
+ font: 16px / normal 'Inconsolata', 'Consolas', monospace;
.canvas-container {
display: -webkit-box;
@@ -458,7 +455,7 @@ $code-color-error: #ff4444;
// Set colour of icons in blueprintjs tabs
color: #a7b6c2;
- &[aria-selected="true"] {
+ &[aria-selected='true'] {
.side-content-tooltip {
background-color: #495a6b;
@@ -471,7 +468,7 @@ $code-color-error: #ff4444;
}
}
- &[aria-disabled="true"] {
+ &[aria-disabled='true'] {
.side-content-tooltip {
// Set tooltip colour to always be the same as the background
background-color: inherit;
@@ -679,10 +676,7 @@ $code-color-error: #ff4444;
* output. Taken from react-ace
* sourcecode, font size modified.
*/
- font:
- 16px / normal "Inconsolata",
- "Consolas",
- monospace;
+ font: 16px / normal 'Inconsolata', 'Consolas', monospace;
}
.code-output {
diff --git a/devserver/src/styles/index.scss b/devserver/src/styles/index.scss
index 8bbc6474a..49e5b163d 100644
--- a/devserver/src/styles/index.scss
+++ b/devserver/src/styles/index.scss
@@ -1,7 +1,7 @@
-@use "sass:math";
+@use 'sass:math';
-@import "@blueprintjs/core/lib/css/blueprint.css";
-@import "@blueprintjs/core/lib/scss/variables";
+@import '@blueprintjs/core/lib/css/blueprint.css';
+@import '@blueprintjs/core/lib/scss/variables';
// CSS styles for react-mde Markdown editor
// (currently this editor is only used for grading comments)
@@ -9,10 +9,10 @@
// styles in the preview tab of the editor, providing a more accurate
// depiction of what the actual comment will look like
-@import "global";
+@import 'global';
-@import "application";
-@import "commons";
-@import "editorTabs";
-@import "playground";
-@import "workspace";
+@import 'application';
+@import 'commons';
+@import 'editorTabs';
+@import 'playground';
+@import 'workspace';
From 790b2cb2495adbc83662b2b262e9b1495b6b4937 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Fri, 12 Apr 2024 05:23:34 +0800
Subject: [PATCH 09/39] Revert some changes
---
devserver/src/components/Playground.tsx | 121 ++++++++----------
devserver/src/components/Workspace.tsx | 18 +--
.../src/components/controlBar/ControlBar.tsx | 7 +-
.../controlBar/ControlBarRunButton.tsx | 4 +-
devserver/src/components/editor/Editor.tsx | 15 +--
devserver/src/components/repl/Repl.tsx | 12 +-
devserver/src/components/sideContent/utils.ts | 14 +-
devserver/src/components/utils/AceHelper.ts | 13 +-
devserver/src/components/utils/Hooks.ts | 27 ++--
devserver/src/types.ts | 6 +-
.../engine/Render/Renderer.ts | 2 +-
11 files changed, 92 insertions(+), 147 deletions(-)
diff --git a/devserver/src/components/Playground.tsx b/devserver/src/components/Playground.tsx
index 9aff5b75b..7049e3225 100644
--- a/devserver/src/components/Playground.tsx
+++ b/devserver/src/components/Playground.tsx
@@ -1,16 +1,6 @@
-import {
- Classes,
- Intent,
- OverlayToaster,
- type ToastProps
-} from '@blueprintjs/core';
+import { Classes, Intent, OverlayToaster, type ToastProps } from '@blueprintjs/core';
import classNames from 'classnames';
-import {
- SourceDocumentation,
- getNames,
- runInContext,
- type Context
-} from 'js-slang';
+import { SourceDocumentation, getNames, runInContext, type Context } from 'js-slang';
// Importing this straight from js-slang doesn't work for whatever reason
import createContext from 'js-slang/dist/createContext';
@@ -52,15 +42,9 @@ const createContextHelper = () => {
const Playground: React.FC<{}> = () => {
const [dynamicTabs, setDynamicTabs] = React.useState([]);
const [selectedTabId, setSelectedTab] = React.useState(testTabContent.id);
- const [codeContext, setCodeContext] = React.useState(
- createContextHelper()
- );
- const [editorValue, setEditorValue] = React.useState(
- localStorage.getItem('editorValue') ?? ''
- );
- const [replOutput, setReplOutput] = React.useState(
- null
- );
+ const [codeContext, setCodeContext] = React.useState(createContextHelper());
+ const [editorValue, setEditorValue] = React.useState(localStorage.getItem('editorValue') ?? '');
+ const [replOutput, setReplOutput] = React.useState(null);
const [alerts, setAlerts] = React.useState([]);
const toaster = React.useRef(null);
@@ -105,58 +89,56 @@ const Playground: React.FC<{}> = () => {
);
callback(null, [...builtinSuggestions, ...editorSuggestions]);
- }
- );
- },
- [editorValue, codeContext]
- );
+ });
+ }, [editorValue, codeContext]);
- const loadTabs = () =>
- getDynamicTabs(codeContext)
- .then((tabs) => {
- setDynamicTabs(tabs);
+ const loadTabs = () => getDynamicTabs(codeContext)
+ .then((tabs) => {
+ setDynamicTabs(tabs);
- const newIds = tabs.map(({ id }) => id);
- // If the currently selected tab no longer exists,
- // switch to the default test tab
- if (!newIds.includes(selectedTabId)) {
- setSelectedTab(testTabContent.id);
- }
- setAlerts(newIds);
- })
- .catch((error) => {
- showToast(errorToast);
- console.log(error);
- });
+ const newIds = tabs.map(({ id }) => id);
+ // If the currently selected tab no longer exists,
+ // switch to the default test tab
+ if (!newIds.includes(selectedTabId)) {
+ setSelectedTab(testTabContent.id);
+ }
+ setAlerts(newIds);
+ })
+ .catch((error) => {
+ showToast(errorToast);
+ console.log(error);
+ });
const evalCode = () => {
codeContext.errors = [];
// eslint-disable-next-line no-multi-assign
codeContext.moduleContexts = mockModuleContext.moduleContexts = {};
- runInContext(editorValue, codeContext).then((result) => {
- if (codeContext.errors.length > 0) {
- showToast(errorToast);
- } else {
- loadTabs().then(() => showToast(evalSuccessToast));
- }
+ runInContext(editorValue, codeContext)
+ .then((result) => {
+ if (codeContext.errors.length > 0) {
+ showToast(errorToast);
+ } else {
+ loadTabs()
+ .then(() => showToast(evalSuccessToast));
+ }
- // TODO: Add support for console.log?
- if (result.status === 'finished') {
- setReplOutput({
- type: 'result',
- // code: editorValue,
- consoleLogs: [],
- value: stringify(result.value)
- });
- } else if (result.status === 'error') {
- setReplOutput({
- type: 'errors',
- errors: codeContext.errors,
- consoleLogs: []
- });
- }
- });
+ // TODO: Add support for console.log?
+ if (result.status === 'finished') {
+ setReplOutput({
+ type: 'result',
+ // code: editorValue,
+ consoleLogs: [],
+ value: stringify(result.value)
+ });
+ } else if (result.status === 'error') {
+ setReplOutput({
+ type: 'errors',
+ errors: codeContext.errors,
+ consoleLogs: []
+ });
+ }
+ });
};
const resetEditor = () => {
@@ -195,13 +177,10 @@ const Playground: React.FC<{}> = () => {
sideContentProps: {
dynamicTabs: [testTabContent, ...dynamicTabs],
selectedTabId,
- onChange: useCallback(
- (newId: string) => {
- setSelectedTab(newId);
- setAlerts(alerts.filter((id) => id !== newId));
- },
- [alerts]
- ),
+ onChange: useCallback((newId: string) => {
+ setSelectedTab(newId);
+ setAlerts(alerts.filter((id) => id !== newId));
+ }, [alerts]),
alerts
}
};
diff --git a/devserver/src/components/Workspace.tsx b/devserver/src/components/Workspace.tsx
index 8d50b843b..4b34069a5 100644
--- a/devserver/src/components/Workspace.tsx
+++ b/devserver/src/components/Workspace.tsx
@@ -1,5 +1,5 @@
import { FocusStyleManager } from '@blueprintjs/core';
-import { Resizable, type Enable, type ResizeCallback } from 're-resizable';
+import { type Enable, Resizable, type ResizeCallback } from 're-resizable';
import React from 'react';
import ControlBar, { type ControlBarProps } from './controlBar/ControlBar';
@@ -40,9 +40,7 @@ const Workspace: React.FC = (props) => {
const [contentContainerWidth] = useDimensions(contentContainerDiv);
- const [sideContentHeight, setSideContentHeight] = React.useState<
- number | undefined
- >(undefined);
+ const [sideContentHeight, setSideContentHeight] = React.useState(undefined);
FocusStyleManager.onlyShowFocusOnTabs();
@@ -60,8 +58,8 @@ const Workspace: React.FC = (props) => {
const toggleEditorDividerDisplay: ResizeCallback = (_a, _b, ref) => {
const leftThreshold = 5;
const rightThreshold = 95;
- const editorWidthPercentage =
- ((ref as HTMLDivElement).clientWidth / contentContainerWidth) * 100;
+ const editorWidthPercentage
+ = ((ref as HTMLDivElement).clientWidth / contentContainerWidth) * 100;
// update resizable size
if (editorWidthPercentage > rightThreshold) {
leftParentResizable.current!.updateSize({
@@ -81,8 +79,8 @@ const Workspace: React.FC = (props) => {
* so that it's bottom border snaps flush with editor's bottom border
*/
const toggleDividerDisplay: ResizeCallback = (_a, _b, ref) => {
- maxDividerHeight.current =
- sideDividerDiv.current!.clientHeight > maxDividerHeight.current!
+ maxDividerHeight.current
+ = sideDividerDiv.current!.clientHeight > maxDividerHeight.current!
? sideDividerDiv.current!.clientHeight
: maxDividerHeight.current;
const resizableHeight = (ref as HTMLDivElement).clientHeight;
@@ -127,9 +125,7 @@ const Workspace: React.FC = (props) => {
className="resize-side-content"
enable={bottomResizeOnly}
onResize={toggleDividerDisplay}
- onResizeStop={(_a, _b, ref) =>
- setSideContentHeight(ref.clientHeight)
- }
+ onResizeStop={(_a, _b, ref) => setSideContentHeight(ref.clientHeight)}
>
= (props) => {
);
const editingWorkspaceControl = (
-
+
{props.editingWorkspaceButtons}
);
diff --git a/devserver/src/components/controlBar/ControlBarRunButton.tsx b/devserver/src/components/controlBar/ControlBarRunButton.tsx
index 5fc0fbdd8..e07163fd1 100644
--- a/devserver/src/components/controlBar/ControlBarRunButton.tsx
+++ b/devserver/src/components/controlBar/ControlBarRunButton.tsx
@@ -16,9 +16,7 @@ type StateProps = {
type ControlButtonRunButtonProps = DispatchProps & StateProps;
-export const ControlBarRunButton: React.FC
= (
- props
-) => {
+export const ControlBarRunButton: React.FC = (props) => {
const tooltipContent = 'Evaluate the program';
return (
diff --git a/devserver/src/components/editor/Editor.tsx b/devserver/src/components/editor/Editor.tsx
index ff183ae5a..860480ab3 100644
--- a/devserver/src/components/editor/Editor.tsx
+++ b/devserver/src/components/editor/Editor.tsx
@@ -1,7 +1,7 @@
-import { require as acequire, type Ace } from 'ace-builds';
-import 'ace-builds/esm-resolver';
+import { type Ace, require as acequire } from 'ace-builds';
import 'ace-builds/src-noconflict/ext-language_tools';
import 'ace-builds/src-noconflict/ext-searchbox';
+import 'ace-builds/esm-resolver';
import 'js-slang/dist/editors/ace/theme/source';
@@ -34,9 +34,7 @@ export type EditorStateProps = {
export type EditorProps = DispatchProps & EditorStateProps;
-const makeCompleter = (
- handlePromptAutocomplete: DispatchProps['handlePromptAutocomplete']
-) => ({
+const makeCompleter = (handlePromptAutocomplete: DispatchProps['handlePromptAutocomplete']) => ({
getCompletions(
_editor: Ace.Editor,
_session: Ace.EditSession,
@@ -68,13 +66,10 @@ const handlers = {
};
const Editor: React.FC = (props: EditorProps) => {
- const reactAceRef: React.MutableRefObject =
- React.useRef(null);
+ const reactAceRef: React.MutableRefObject = React.useRef(null);
// Refs for things that technically shouldn't change... but just in case.
- const handlePromptAutocompleteRef = React.useRef(
- props.handlePromptAutocomplete
- );
+ const handlePromptAutocompleteRef = React.useRef(props.handlePromptAutocomplete);
const editor = reactAceRef.current?.editor;
diff --git a/devserver/src/components/repl/Repl.tsx b/devserver/src/components/repl/Repl.tsx
index cd8320c29..c0118b44e 100644
--- a/devserver/src/components/repl/Repl.tsx
+++ b/devserver/src/components/repl/Repl.tsx
@@ -45,17 +45,13 @@ const Output: React.FC = (props: OutputProps) => {
if (props.output.consoleLogs.length === 0) {
return (
-
- {parseError(props.output.errors)}
-
+ {parseError(props.output.errors)}
);
}
return (
-
- {props.output.consoleLogs.join('\n')}
-
+ {props.output.consoleLogs.join('\n')}
{parseError(props.output.errors)}
@@ -77,7 +73,9 @@ export type ReplProps = {
const Repl: React.FC = (props: ReplProps) => (
- {props.output === null ? : }
+ {props.output === null
+ ?
+ : }
{/* {cards.length > 0 ? cards : ( )} */}
diff --git a/devserver/src/components/sideContent/utils.ts b/devserver/src/components/sideContent/utils.ts
index e521c38d0..54e7d4adb 100644
--- a/devserver/src/components/sideContent/utils.ts
+++ b/devserver/src/components/sideContent/utils.ts
@@ -18,12 +18,10 @@ export const getDynamicTabs = async (context: Context) => {
return moduleSideContents
.filter(({ toSpawn }) => !toSpawn || toSpawn({ context }))
- .map(
- (tab): SideContentTab => ({
- ...tab,
- // In the frontend, module tabs use their labels as IDs
- id: tab.label,
- body: tab.body({ context })
- })
- );
+ .map((tab): SideContentTab => ({
+ ...tab,
+ // In the frontend, module tabs use their labels as IDs
+ id: tab.label,
+ body: tab.body({ context })
+ }));
};
diff --git a/devserver/src/components/utils/AceHelper.ts b/devserver/src/components/utils/AceHelper.ts
index 8118dd531..336b2ba41 100644
--- a/devserver/src/components/utils/AceHelper.ts
+++ b/devserver/src/components/utils/AceHelper.ts
@@ -1,13 +1,9 @@
/* eslint-disable new-cap */
-import {
- HighlightRulesSelector,
- ModeSelector
-} from 'js-slang/dist/editors/ace/modes/source';
+import { HighlightRulesSelector, ModeSelector } from 'js-slang/dist/editors/ace/modes/source';
import { Chapter, Variant } from 'js-slang/dist/types';
import ace from 'react-ace';
-export const getModeString = () =>
- `source${Chapter.SOURCE_4}${Variant.DEFAULT}${''}`;
+export const getModeString = () => `source${Chapter.SOURCE_4}${Variant.DEFAULT}${''}`;
/**
* This _modifies global state_ and defines a new Ace mode globally, if it does not already exist.
@@ -22,9 +18,8 @@ export const selectMode = () => {
if (
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
- typeof ace.define.modules[
- `ace/mode/${getModeString(chapter, variant, library)}`
- ]?.Mode === 'function'
+ typeof ace.define.modules[`ace/mode/${getModeString(chapter, variant, library)}`]?.Mode
+ === 'function'
) {
return;
}
diff --git a/devserver/src/components/utils/Hooks.ts b/devserver/src/components/utils/Hooks.ts
index e14df68a7..6e292e650 100644
--- a/devserver/src/components/utils/Hooks.ts
+++ b/devserver/src/components/utils/Hooks.ts
@@ -7,26 +7,21 @@
import React, { type RefObject } from 'react';
-export const useDimensions = (
- ref: RefObject
-): [width: number, height: number] => {
+export const useDimensions = (ref: RefObject): [width: number, height: number] => {
const [width, setWidth] = React.useState(0);
const [height, setHeight] = React.useState(0);
const resizeObserver = React.useMemo(
- () =>
- new ResizeObserver(
- (entries: ResizeObserverEntry[], _observer: ResizeObserver) => {
- if (entries.length !== 1) {
- throw new Error(
- 'Expected only a single HTML element to be observed by the ResizeObserver.'
- );
- }
- const contentRect = entries[0].contentRect;
- setWidth(contentRect.width);
- setHeight(contentRect.height);
- }
- ),
+ () => new ResizeObserver((entries: ResizeObserverEntry[], _observer: ResizeObserver) => {
+ if (entries.length !== 1) {
+ throw new Error(
+ 'Expected only a single HTML element to be observed by the ResizeObserver.'
+ );
+ }
+ const contentRect = entries[0].contentRect;
+ setWidth(contentRect.width);
+ setHeight(contentRect.height);
+ }),
[]
);
diff --git a/devserver/src/types.ts b/devserver/src/types.ts
index de976f026..dddd7cbb2 100644
--- a/devserver/src/types.ts
+++ b/devserver/src/types.ts
@@ -44,8 +44,4 @@ export type ErrorOutput = {
consoleLogs: string[];
};
-export type InterpreterOutput =
- | CodeOutput
- | ErrorOutput
- | ResultOutput
- | RunningOutput;
+export type InterpreterOutput = CodeOutput | ErrorOutput | ResultOutput | RunningOutput;
diff --git a/src/bundles/robot_simulation/engine/Render/Renderer.ts b/src/bundles/robot_simulation/engine/Render/Renderer.ts
index fdee56c98..b22a0fa26 100644
--- a/src/bundles/robot_simulation/engine/Render/Renderer.ts
+++ b/src/bundles/robot_simulation/engine/Render/Renderer.ts
@@ -13,7 +13,7 @@ type ControlType = 'none' | 'orbit';
export type RenderConfig = {
width: number;
height: number;
- control: ControlType
+ control: ControlType;
};
export class Renderer {
From 74a8d9bd2998b5f4bcd3732dbf7b1ad4eee3b87e Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Fri, 12 Apr 2024 05:33:22 +0800
Subject: [PATCH 10/39] Update .gitignore
---
.gitignore | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/.gitignore b/.gitignore
index 9dc657cb0..bad059b58 100644
--- a/.gitignore
+++ b/.gitignore
@@ -47,3 +47,7 @@ scripts/bin.js
.Trashes
ehthumbs.db
Thumbs.db
+
+# IDE #
+#######
+.idea/
From b24ad8731371039859e201274f4565732c4a7796 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Fri, 12 Apr 2024 05:41:30 +0800
Subject: [PATCH 11/39] Revert some changes in scripts
---
scripts/jest.setup.ts | 33 ++++++----------
scripts/src/build/docs/drawdown.ts | 6 +--
.../build/modules/__tests__/bundle.test.ts | 4 +-
scripts/src/build/modules/index.ts | 15 +++-----
.../build/prebuild/__tests__/prebuild.test.ts | 3 +-
scripts/src/build/prebuild/index.ts | 11 +-----
scripts/src/build/prebuild/utils.ts | 11 +-----
scripts/src/manifest.ts | 3 +-
scripts/src/templates/index.ts | 5 +--
scripts/src/templates/print.ts | 11 +++---
scripts/src/templates/templates/__bundle__.ts | 1 +
scripts/src/testing/__tests__/runner.test.ts | 4 +-
scripts/src/testing/index.ts | 38 ++++++++-----------
13 files changed, 51 insertions(+), 94 deletions(-)
diff --git a/scripts/jest.setup.ts b/scripts/jest.setup.ts
index cdf79e6b5..94c883175 100644
--- a/scripts/jest.setup.ts
+++ b/scripts/jest.setup.ts
@@ -2,16 +2,9 @@ const chalkFunction = new Proxy((x: string) => x, {
get: () => chalkFunction
});
-jest.mock(
- 'chalk',
- () =>
- new Proxy(
- {},
- {
- get: () => chalkFunction
- }
- )
-);
+jest.mock('chalk', () => new Proxy({}, {
+ get: () => chalkFunction
+}));
jest.mock('fs/promises', () => ({
copyFile: jest.fn(() => Promise.resolve()),
@@ -21,17 +14,15 @@ jest.mock('fs/promises', () => ({
}));
jest.mock('./src/manifest', () => ({
- retrieveManifest: jest.fn(() =>
- Promise.resolve({
- test0: {
- tabs: ['tab0']
- },
- test1: { tabs: [] },
- test2: {
- tabs: ['tab1']
- }
- })
- )
+ retrieveManifest: jest.fn(() => Promise.resolve({
+ test0: {
+ tabs: ['tab0']
+ },
+ test1: { tabs: [] },
+ test2: {
+ tabs: ['tab1']
+ }
+ }))
}));
global.process.exit = jest.fn(code => {
diff --git a/scripts/src/build/docs/drawdown.ts b/scripts/src/build/docs/drawdown.ts
index cb55d3afc..4efeeaf67 100644
--- a/scripts/src/build/docs/drawdown.ts
+++ b/scripts/src/build/docs/drawdown.ts
@@ -12,11 +12,9 @@ export default (src: string): string => {
var rx_escape = /\\([\\\|`*_{}\[\]()#+\-~])/g;
var rx_hr = /^([*\-=_] *){3,}$/gm;
var rx_blockquote = /\n *> *([^]*?)(?=(\n|$){2})/g;
- var rx_list =
- /\n( *)(?:[*\-+]|((\d+)|([a-z])|[A-Z])[.)]) +([^]*?)(?=(\n|$){2})/g;
+ var rx_list = /\n( *)(?:[*\-+]|((\d+)|([a-z])|[A-Z])[.)]) +([^]*?)(?=(\n|$){2})/g;
var rx_listjoin = /<\/(ol|ul)>\n\n<\1>/g;
- var rx_highlight =
- /(^|[^A-Za-z\d\\])(([*_])|(~)|(\^)|(--)|(\+\+)|`)(\2?)([^<]*?)\2\8(?!\2)(?=\W|_|$)/g;
+ var rx_highlight = /(^|[^A-Za-z\d\\])(([*_])|(~)|(\^)|(--)|(\+\+)|`)(\2?)([^<]*?)\2\8(?!\2)(?=\W|_|$)/g;
var rx_code = /\n((```|~~~).*\n?([^]*?)\n?\2|(( {4}.*?\n)+))/g;
var rx_link = /((!?)\[(.*?)\]\((.*?)( ".*")?\)|\\([\\`*_{}\[\]()#+\-.!~]))/g;
var rx_table = /\n(( *\|.*?\| *\n)+)/g;
diff --git a/scripts/src/build/modules/__tests__/bundle.test.ts b/scripts/src/build/modules/__tests__/bundle.test.ts
index d84625a18..22a52031b 100644
--- a/scripts/src/build/modules/__tests__/bundle.test.ts
+++ b/scripts/src/build/modules/__tests__/bundle.test.ts
@@ -19,9 +19,7 @@ test('Normal command', async () => {
expect(bundles.bundleBundles).toHaveBeenCalledTimes(1);
- const [args] = (
- bundles.bundleBundles as MockedFunction
- ).mock.calls[0];
+ const [args] = (bundles.bundleBundles as MockedFunction).mock.calls[0];
expect(args).toMatchObject({
bundles: ['test0'],
tabs: ['tab0'],
diff --git a/scripts/src/build/modules/index.ts b/scripts/src/build/modules/index.ts
index 94d9cdb89..9df2e6429 100644
--- a/scripts/src/build/modules/index.ts
+++ b/scripts/src/build/modules/index.ts
@@ -1,9 +1,5 @@
import { bundlesOption, tabsOption } from '@src/commandUtils';
-import {
- createBuildCommand,
- createBuildCommandHandler,
- type BuildTask
-} from '../utils';
+import { createBuildCommand, type BuildTask, createBuildCommandHandler } from '../utils';
import { bundleBundles } from './bundles';
import { bundleTabs } from './tabs';
@@ -21,11 +17,10 @@ export const buildModules: BuildTask = async (inputs, opts) => {
const modulesCommandHandler = createBuildCommandHandler(buildModules);
-export const getBuildModulesCommand = () =>
- createBuildCommand('modules', 'Build bundles and tabs')
- .addOption(bundlesOption)
- .addOption(tabsOption)
- .action(modulesCommandHandler);
+export const getBuildModulesCommand = () => createBuildCommand('modules', 'Build bundles and tabs')
+ .addOption(bundlesOption)
+ .addOption(tabsOption)
+ .action(modulesCommandHandler);
export { getBuildBundlesCommand } from './bundles';
export { getBuildTabsCommand } from './tabs';
diff --git a/scripts/src/build/prebuild/__tests__/prebuild.test.ts b/scripts/src/build/prebuild/__tests__/prebuild.test.ts
index 0c4328da8..12076a0c7 100644
--- a/scripts/src/build/prebuild/__tests__/prebuild.test.ts
+++ b/scripts/src/build/prebuild/__tests__/prebuild.test.ts
@@ -6,8 +6,7 @@ import * as tscModule from '../tsc';
jest.spyOn(lintModule, 'runEslint');
jest.spyOn(tscModule, 'runTsc');
-const asMock = any>(func: T) =>
- func as MockedFunction;
+const asMock = any>(func: T) => func as MockedFunction;
const mockedTsc = asMock(tscModule.runTsc);
const mockedEslint = asMock(lintModule.runEslint);
diff --git a/scripts/src/build/prebuild/index.ts b/scripts/src/build/prebuild/index.ts
index 598b27617..3921bcae9 100644
--- a/scripts/src/build/prebuild/index.ts
+++ b/scripts/src/build/prebuild/index.ts
@@ -1,8 +1,4 @@
-import {
- findSeverity,
- type BuildOptions,
- type Severity
-} from '@src/build/utils';
+import { type Severity, findSeverity, type BuildOptions } from '@src/build/utils';
import { promiseAll } from '@src/commandUtils';
import { eslintResultsLogger, runEslint } from './lint';
import { runTsc, tscResultsLogger } from './tsc';
@@ -38,10 +34,7 @@ export default async function prebuild(
runEslint(combinedOpts)
);
- const overallSev = findSeverity(
- [tscResult, lintResult],
- ({ result: { severity } }) => severity
- );
+ const overallSev = findSeverity([tscResult, lintResult], ({ result: { severity } }) => severity);
return {
tsc: tscResult,
diff --git a/scripts/src/build/prebuild/utils.ts b/scripts/src/build/prebuild/utils.ts
index f3c604232..34084169a 100644
--- a/scripts/src/build/prebuild/utils.ts
+++ b/scripts/src/build/prebuild/utils.ts
@@ -1,11 +1,5 @@
import { Command } from '@commander-js/extra-typings';
-import {
- bundlesOption,
- manifestOption,
- srcDirOption,
- tabsOption,
- type TimedResult
-} from '@src/commandUtils';
+import { bundlesOption, manifestOption, srcDirOption, tabsOption, type TimedResult } from '@src/commandUtils';
import { logInputs, type Severity } from '../utils';
export interface PrebuildOptions {
@@ -15,8 +9,7 @@ export interface PrebuildOptions {
tabs: string[];
}
-export interface PrebuildResult
- extends TimedResult {}
+export interface PrebuildResult extends TimedResult {}
export function createPrebuildCommand(
commandName: string,
diff --git a/scripts/src/manifest.ts b/scripts/src/manifest.ts
index e8f798dc0..52c97c2b0 100644
--- a/scripts/src/manifest.ts
+++ b/scripts/src/manifest.ts
@@ -7,8 +7,7 @@ export async function retrieveManifest(manifest: string) {
const rawManifest = await fs.readFile(manifest, 'utf-8');
return JSON.parse(rawManifest) as ModuleManifest;
} catch (error) {
- if (error.code === 'ENOENT')
- throw new Error(`Could not locate manifest file at ${manifest}`);
+ if (error.code === 'ENOENT') throw new Error(`Could not locate manifest file at ${manifest}`);
throw error;
}
}
diff --git a/scripts/src/templates/index.ts b/scripts/src/templates/index.ts
index 153d20521..d971e56c7 100644
--- a/scripts/src/templates/index.ts
+++ b/scripts/src/templates/index.ts
@@ -9,10 +9,7 @@ import { addNew as addNewTab } from './tab';
async function askMode(rl: Interface) {
while (true) {
// eslint-disable-next-line no-await-in-loop
- const mode = await askQuestion(
- 'What would you like to create? (module/tab)',
- rl
- );
+ const mode = await askQuestion('What would you like to create? (module/tab)', rl);
if (mode !== 'module' && mode !== 'tab') {
warn("Please answer with only 'module' or 'tab'.");
} else {
diff --git a/scripts/src/templates/print.ts b/scripts/src/templates/print.ts
index e2f106b5b..f358a2fc6 100644
--- a/scripts/src/templates/print.ts
+++ b/scripts/src/templates/print.ts
@@ -1,11 +1,10 @@
-import { createInterface, type Interface } from 'readline/promises';
+import { type Interface, createInterface } from 'readline/promises';
import chalk from 'chalk';
-export const getRl = () =>
- createInterface({
- input: process.stdin,
- output: process.stdout
- });
+export const getRl = () => createInterface({
+ input: process.stdin,
+ output: process.stdout
+});
export function info(...args: any[]) {
return console.log(...args.map(string => chalk.grey(string)));
diff --git a/scripts/src/templates/templates/__bundle__.ts b/scripts/src/templates/templates/__bundle__.ts
index cfd6f218f..a3deb9ec0 100644
--- a/scripts/src/templates/templates/__bundle__.ts
+++ b/scripts/src/templates/templates/__bundle__.ts
@@ -12,6 +12,7 @@
To access things like the context or module state you can just import the context
using the import below
*/
+import context from 'js-slang/context';
/**
* Sample function. Increments a number by 1.
diff --git a/scripts/src/testing/__tests__/runner.test.ts b/scripts/src/testing/__tests__/runner.test.ts
index 47f25beb6..8c5decac2 100644
--- a/scripts/src/testing/__tests__/runner.test.ts
+++ b/scripts/src/testing/__tests__/runner.test.ts
@@ -4,8 +4,8 @@ import * as runner from '../runner';
jest.spyOn(runner, 'runJest').mockImplementation(jest.fn());
-const runCommand = (...args: string[]) =>
- getTestCommand().parseAsync(args, { from: 'user' });
+const runCommand = (...args: string[]) => getTestCommand()
+ .parseAsync(args, { from: 'user' });
const mockRunJest = runner.runJest as MockedFunction;
test('Check that the test command properly passes options to jest', async () => {
diff --git a/scripts/src/testing/index.ts b/scripts/src/testing/index.ts
index 8592e9356..e1619bdae 100644
--- a/scripts/src/testing/index.ts
+++ b/scripts/src/testing/index.ts
@@ -9,29 +9,23 @@ export type TestCommandOptions = {
srcDir: string;
};
-const getTestCommand = () =>
- new Command('test')
- .description('Run jest')
- .addOption(srcDirOption)
- .allowUnknownOption()
- .action(({ srcDir }, command) => {
- const [args, filePatterns] = lodash.partition(command.args, arg =>
- arg.startsWith('-')
- );
+const getTestCommand = () => new Command('test')
+ .description('Run jest')
+ .addOption(srcDirOption)
+ .allowUnknownOption()
+ .action(({ srcDir }, command) => {
+ const [args, filePatterns] = lodash.partition(command.args, arg => arg.startsWith('-'));
- // command.args automatically includes the source directory option
- // which is not supported by Jest, so we need to remove it
- const toRemove = args.findIndex(arg => arg.startsWith('--srcDir'));
- if (toRemove !== -1) {
- args.splice(toRemove, 1);
- }
+ // command.args automatically includes the source directory option
+ // which is not supported by Jest, so we need to remove it
+ const toRemove = args.findIndex(arg => arg.startsWith('--srcDir'));
+ if (toRemove !== -1) {
+ args.splice(toRemove, 1);
+ }
- const jestArgs = args.concat(
- filePatterns.map(pattern =>
- pattern.split(pathlib.win32.sep).join(pathlib.posix.sep)
- )
- );
- return runJest(jestArgs, srcDir);
- });
+ const jestArgs = args.concat(filePatterns.map(pattern => pattern.split(pathlib.win32.sep)
+ .join(pathlib.posix.sep)));
+ return runJest(jestArgs, srcDir);
+ });
export default getTestCommand;
From 77eaa1a82193fc2109c80e3aaf4092150abf1814 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Fri, 12 Apr 2024 05:43:54 +0800
Subject: [PATCH 12/39] Reformat ModalDiv
---
src/tabs/common/ModalDiv.tsx | 8 +-------
1 file changed, 1 insertion(+), 7 deletions(-)
diff --git a/src/tabs/common/ModalDiv.tsx b/src/tabs/common/ModalDiv.tsx
index 27c3f0682..1fc2009dc 100644
--- a/src/tabs/common/ModalDiv.tsx
+++ b/src/tabs/common/ModalDiv.tsx
@@ -50,13 +50,7 @@ const Modal = ({ open, height, width, children, handleClose }: ModalProp) => (
<>
{open && (
<>
-
+
From c4400626beda78eeffbda18424f8c3b1ea02adbf Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Fri, 12 Apr 2024 05:53:20 +0800
Subject: [PATCH 13/39] Revert some changes in tabs
---
src/tabs/ArcadeTwod/index.tsx | 6 +-----
src/tabs/CopyGc/style.tsx | 2 +-
src/tabs/Csg/canvas_holder.tsx | 11 ++---------
src/tabs/Csg/index.tsx | 3 +--
src/tabs/Curve/index.tsx | 9 ++-------
src/tabs/Painter/index.tsx | 13 ++-----------
src/tabs/Pixnflix/index.tsx | 18 +++++++++---------
src/tabs/Plotly/index.tsx | 10 +---------
src/tabs/Repl/index.tsx | 11 +++--------
src/tabs/Rune/__tests__/Rune.tsx | 5 +----
src/tabs/Rune/index.tsx | 11 ++---------
src/tabs/Sound/index.tsx | 9 ++-------
src/tabs/StereoSound/index.tsx | 14 +++-----------
src/tabs/UnityAcademy/index.tsx | 2 +-
src/tabs/common/MultItemDisplay.tsx | 20 +++++---------------
src/tabs/common/PlayButton.tsx | 2 +-
src/tabs/common/testUtils.ts | 15 +++++++--------
src/tabs/physics_2d/index.tsx | 10 +---------
18 files changed, 45 insertions(+), 126 deletions(-)
diff --git a/src/tabs/ArcadeTwod/index.tsx b/src/tabs/ArcadeTwod/index.tsx
index 24867c9e9..2f696acd8 100644
--- a/src/tabs/ArcadeTwod/index.tsx
+++ b/src/tabs/ArcadeTwod/index.tsx
@@ -90,11 +90,7 @@ class GameTab extends React.Component
{
componentDidMount() {
// Only mount the component when the Arcade2D tab is active
- if (
- document.querySelector(
- '[id="bp4-tab-panel_side-content-tabs_Arcade2D Tab"]'
- )?.ariaHidden === 'true'
- ) {
+ if (document.querySelector('[id="bp4-tab-panel_side-content-tabs_Arcade2D Tab"]')?.ariaHidden === 'true') {
return;
}
diff --git a/src/tabs/CopyGc/style.tsx b/src/tabs/CopyGc/style.tsx
index c1fddd6f1..8817fe1f3 100644
--- a/src/tabs/CopyGc/style.tsx
+++ b/src/tabs/CopyGc/style.tsx
@@ -5,7 +5,7 @@ export enum ThemeColor {
GREEN = '#42a870',
YELLOW = '#f0d60e',
RED = 'red',
- BLACK = 'black'
+ BLACK = 'black',
}
export const FONT = {
diff --git a/src/tabs/Csg/canvas_holder.tsx b/src/tabs/Csg/canvas_holder.tsx
index 8c4fea520..c16ee5bcc 100644
--- a/src/tabs/Csg/canvas_holder.tsx
+++ b/src/tabs/Csg/canvas_holder.tsx
@@ -5,13 +5,7 @@ import React from 'react';
import { Core } from '../../bundles/csg/core';
import StatefulRenderer from '../../bundles/csg/stateful_renderer';
import type { RenderGroup } from '../../bundles/csg/utilities';
-import {
- BP_CARD_BORDER_RADIUS,
- BP_TAB_BUTTON_MARGIN,
- BP_TAB_PANEL_MARGIN,
- BP_TEXT_MARGIN,
- CANVAS_MAX_WIDTH
-} from '../common/css_constants';
+import { BP_CARD_BORDER_RADIUS, BP_TAB_BUTTON_MARGIN, BP_TAB_PANEL_MARGIN, BP_TEXT_MARGIN, CANVAS_MAX_WIDTH } from '../common/css_constants';
import HoverControlHint from './hover_control_hint';
import type { CanvasHolderProps, CanvasHolderState } from './types';
@@ -20,8 +14,7 @@ export default class CanvasHolder extends React.Component<
CanvasHolderProps,
CanvasHolderState
> {
- private readonly canvasReference: React.RefObject =
- React.createRef();
+ private readonly canvasReference: React.RefObject = React.createRef();
private statefulRenderer: StatefulRenderer | null = null;
diff --git a/src/tabs/Csg/index.tsx b/src/tabs/Csg/index.tsx
index 94ee2455f..affb45142 100644
--- a/src/tabs/Csg/index.tsx
+++ b/src/tabs/Csg/index.tsx
@@ -10,8 +10,7 @@ import CanvasHolder from './canvas_holder';
export default {
// Called by the frontend to decide whether to spawn the CSG tab
toSpawn(debuggerContext: DebuggerContext): boolean {
- const moduleState: CsgModuleState =
- debuggerContext.context.moduleContexts.csg.state;
+ const moduleState: CsgModuleState = debuggerContext.context.moduleContexts.csg.state;
// toSpawn() is checked before the frontend calls body() if needed, so we
// initialise Core for the first time over on the tabs' end here
Core.initialize(moduleState);
diff --git a/src/tabs/Curve/index.tsx b/src/tabs/Curve/index.tsx
index 48c8b529d..3f1d59f9f 100644
--- a/src/tabs/Curve/index.tsx
+++ b/src/tabs/Curve/index.tsx
@@ -1,10 +1,6 @@
import type { CurveModuleState } from '../../bundles/curve/types';
import { glAnimation } from '../../typings/anim_types';
-import {
- getModuleState,
- type DebuggerContext,
- type ModuleTab
-} from '../../typings/type_helpers';
+import { getModuleState, type DebuggerContext, type ModuleTab } from '../../typings/type_helpers';
import AnimationCanvas from '../common/AnimationCanvas';
import MultiItemDisplay from '../common/MultItemDisplay';
import WebGLCanvas from '../common/WebglCanvas';
@@ -43,8 +39,7 @@ export const CurveTab: ModuleTab = ({ context }) => {
export default {
toSpawn(context: DebuggerContext) {
- const drawnCurves =
- context.context?.moduleContexts?.curve?.state?.drawnCurves;
+ const drawnCurves = context.context?.moduleContexts?.curve?.state?.drawnCurves;
return drawnCurves.length > 0;
},
body(context: DebuggerContext) {
diff --git a/src/tabs/Painter/index.tsx b/src/tabs/Painter/index.tsx
index 75bcf0a4f..b76984335 100644
--- a/src/tabs/Painter/index.tsx
+++ b/src/tabs/Painter/index.tsx
@@ -31,15 +31,7 @@ class Painter extends React.Component {
};
public render() {
- const {
- context: {
- moduleContexts: {
- painter: {
- state: { drawnPainters }
- }
- }
- }
- } = this.props.debuggerContext;
+ const { context: { moduleContexts: { painter: { state: { drawnPainters } } } } } = this.props.debuggerContext;
return (
@@ -86,8 +78,7 @@ class Painter extends React.Component
{
export default {
toSpawn(context: DebuggerContext) {
- const drawnPainters =
- context.context?.moduleContexts?.painter.state.drawnPainters;
+ const drawnPainters = context.context?.moduleContexts?.painter.state.drawnPainters;
console.log(drawnPainters);
return drawnPainters.length > 0;
},
diff --git a/src/tabs/Pixnflix/index.tsx b/src/tabs/Pixnflix/index.tsx
index 6daf33c4b..a4c3c0542 100644
--- a/src/tabs/Pixnflix/index.tsx
+++ b/src/tabs/Pixnflix/index.tsx
@@ -15,9 +15,9 @@ import {
MIN_WIDTH
} from '../../bundles/pix_n_flix/constants';
import {
- InputFeed,
type BundlePacket,
type ErrorLogger,
+ InputFeed,
type TabsPacket
} from '../../bundles/pix_n_flix/types';
@@ -31,7 +31,7 @@ enum VideoMode {
Video,
Still,
Accepting,
- Image
+ Image,
}
type State = {
@@ -195,10 +195,10 @@ class PixNFlix extends React.Component {
public handleUpdateDimensions = (w: number, h: number) => {
if (
- w >= MIN_WIDTH &&
- w <= MAX_WIDTH &&
- h >= MIN_HEIGHT &&
- h <= MAX_HEIGHT
+ w >= MIN_WIDTH
+ && w <= MAX_WIDTH
+ && h >= MIN_HEIGHT
+ && h <= MAX_HEIGHT
) {
this.setState({
width: w,
@@ -264,9 +264,9 @@ class PixNFlix extends React.Component {
*/
private isPixNFlix() {
return (
- this.pixNFlix &&
- this.pixNFlix.toReplString &&
- this.pixNFlix.toReplString() === '[Pix N Flix]'
+ this.pixNFlix
+ && this.pixNFlix.toReplString
+ && this.pixNFlix.toReplString() === '[Pix N Flix]'
);
}
diff --git a/src/tabs/Plotly/index.tsx b/src/tabs/Plotly/index.tsx
index 4b5cccdbc..ee24a7628 100644
--- a/src/tabs/Plotly/index.tsx
+++ b/src/tabs/Plotly/index.tsx
@@ -31,15 +31,7 @@ class Plotly extends React.Component {
};
public render() {
- const {
- context: {
- moduleContexts: {
- plotly: {
- state: { drawnPlots }
- }
- }
- }
- } = this.props.debuggerContext;
+ const { context: { moduleContexts: { plotly: { state: { drawnPlots } } } } } = this.props.debuggerContext;
return (
diff --git a/src/tabs/Repl/index.tsx b/src/tabs/Repl/index.tsx
index 42954a8d3..1abf49fca 100644
--- a/src/tabs/Repl/index.tsx
+++ b/src/tabs/Repl/index.tsx
@@ -13,9 +13,9 @@ import { FONT_MESSAGE, MINIMUM_EDITOR_HEIGHT } from '../../bundles/repl/config';
import type { ProgrammableRepl } from '../../bundles/repl/programmable_repl';
import type { DebuggerContext } from '../../typings/type_helpers';
-import 'ace-builds/src-noconflict/ext-language_tools';
import 'ace-builds/src-noconflict/mode-javascript';
import 'ace-builds/src-noconflict/theme-twilight';
+import 'ace-builds/src-noconflict/ext-language_tools';
type Props = {
programmableReplInstance: ProgrammableRepl;
@@ -140,8 +140,7 @@ class ProgrammableReplGUI extends React.Component
{
style={{
width: '100%',
height: `${editorHeight}px`,
- ...(this.replInstance.customizedEditorProps.backgroundImageUrl !==
- 'no-background-image' && {
+ ...(this.replInstance.customizedEditorProps.backgroundImageUrl !== 'no-background-image' && {
backgroundImage: `url(${this.replInstance.customizedEditorProps.backgroundImageUrl})`,
backgroundColor: `rgba(20, 20, 20, ${this.replInstance.customizedEditorProps.backgroundColorAlpha})`,
backgroundSize: '100%',
@@ -191,11 +190,7 @@ export default {
* @param {DebuggerContext} context
*/
body(context: DebuggerContext) {
- return (
-
- );
+ return ;
},
/**
diff --git a/src/tabs/Rune/__tests__/Rune.tsx b/src/tabs/Rune/__tests__/Rune.tsx
index 308b48d5f..84f7eaf05 100644
--- a/src/tabs/Rune/__tests__/Rune.tsx
+++ b/src/tabs/Rune/__tests__/Rune.tsx
@@ -5,9 +5,6 @@ import { mockDebuggerContext } from '../../common/testUtils';
test('Ensure that rune animations error gracefully', () => {
const badAnimation = animate_rune(1, 60, t => 1 as any);
- const mockContext = mockDebuggerContext(
- { drawnRunes: [badAnimation] },
- 'rune'
- );
+ const mockContext = mockDebuggerContext({ drawnRunes: [badAnimation] }, 'rune');
expect( ).toMatchSnapshot();
});
diff --git a/src/tabs/Rune/index.tsx b/src/tabs/Rune/index.tsx
index e5db4221a..a6a5aa967 100644
--- a/src/tabs/Rune/index.tsx
+++ b/src/tabs/Rune/index.tsx
@@ -1,13 +1,6 @@
-import {
- isHollusionRune,
- type RuneModuleState
-} from '../../bundles/rune/functions';
+import { type RuneModuleState, isHollusionRune } from '../../bundles/rune/functions';
import { glAnimation } from '../../typings/anim_types';
-import {
- getModuleState,
- type DebuggerContext,
- type ModuleTab
-} from '../../typings/type_helpers';
+import { getModuleState, type DebuggerContext, type ModuleTab } from '../../typings/type_helpers';
import AnimationCanvas from '../common/AnimationCanvas';
import MultiItemDisplay from '../common/MultItemDisplay';
import WebGLCanvas from '../common/WebglCanvas';
diff --git a/src/tabs/Sound/index.tsx b/src/tabs/Sound/index.tsx
index 0f3d98324..80d86342b 100644
--- a/src/tabs/Sound/index.tsx
+++ b/src/tabs/Sound/index.tsx
@@ -1,9 +1,5 @@
import type { SoundModuleState } from '../../bundles/sound/types';
-import {
- getModuleState,
- type DebuggerContext,
- type ModuleTab
-} from '../../typings/type_helpers';
+import { getModuleState, type DebuggerContext, type ModuleTab } from '../../typings/type_helpers';
import MultiItemDisplay from '../common/MultItemDisplay';
/**
@@ -44,8 +40,7 @@ export default {
* @returns {boolean}
*/
toSpawn(context: DebuggerContext) {
- const audioPlayed =
- context.context?.moduleContexts?.sound?.state?.audioPlayed;
+ const audioPlayed = context.context?.moduleContexts?.sound?.state?.audioPlayed;
return audioPlayed.length > 0;
},
/**
diff --git a/src/tabs/StereoSound/index.tsx b/src/tabs/StereoSound/index.tsx
index ebabac2c5..91e1e0d65 100644
--- a/src/tabs/StereoSound/index.tsx
+++ b/src/tabs/StereoSound/index.tsx
@@ -1,9 +1,5 @@
import type { StereoSoundModuleState } from '../../bundles/stereo_sound/types';
-import {
- getModuleState,
- type DebuggerContext,
- type ModuleTab
-} from '../../typings/type_helpers';
+import { getModuleState, type DebuggerContext, type ModuleTab } from '../../typings/type_helpers';
import MultiItemDisplay from '../common/MultItemDisplay';
/**
@@ -13,10 +9,7 @@ import MultiItemDisplay from '../common/MultItemDisplay';
*/
const SoundTab: ModuleTab = ({ context }) => {
- const { audioPlayed } = getModuleState(
- context,
- 'sound'
- );
+ const { audioPlayed } = getModuleState(context, 'sound');
const elements = audioPlayed.map(audio => (
0;
},
/**
diff --git a/src/tabs/UnityAcademy/index.tsx b/src/tabs/UnityAcademy/index.tsx
index cfbd1f94a..0893366fb 100644
--- a/src/tabs/UnityAcademy/index.tsx
+++ b/src/tabs/UnityAcademy/index.tsx
@@ -4,7 +4,7 @@
* @author Wang Zihan
*/
-import { Button, Checkbox, NumericInput } from '@blueprintjs/core';
+import { Button, NumericInput, Checkbox } from '@blueprintjs/core';
import { IconNames } from '@blueprintjs/icons';
import React from 'react';
import { getInstance } from '../../bundles/unity_academy/UnityAcademy';
diff --git a/src/tabs/common/MultItemDisplay.tsx b/src/tabs/common/MultItemDisplay.tsx
index 57fd95027..b019e110a 100644
--- a/src/tabs/common/MultItemDisplay.tsx
+++ b/src/tabs/common/MultItemDisplay.tsx
@@ -15,10 +15,8 @@ const MultiItemDisplay = ({ elements }: MultiItemDisplayProps) => {
const [stepEditorValue, setStepEditorValue] = React.useState('1');
const [stepEditorFocused, setStepEditorFocused] = React.useState(false);
- const resetStepEditor = () =>
- setStepEditorValue((currentStep + 1).toString());
- const elementsDigitCount =
- Math.floor(Math.log10(Math.max(1, elements.length))) + 1;
+ const resetStepEditor = () => setStepEditorValue((currentStep + 1).toString());
+ const elementsDigitCount = Math.floor(Math.log10(Math.max(1, elements.length))) + 1;
return (
{
>
Call
{/* When the text box is focused, it shows a little up and down bar, which needs a little bit
- * more space to be shown
- */}
-
+ * more space to be shown
+ */}
+
(state: T, moduleName: string) =>
- ({
- context: {
- moduleContexts: {
- [moduleName]: {
- state
- }
+export const mockDebuggerContext = (state: T, moduleName: string) => ({
+ context: {
+ moduleContexts: {
+ [moduleName]: {
+ state
}
}
- } as DebuggerContext);
+ }
+}) as DebuggerContext;
diff --git a/src/tabs/physics_2d/index.tsx b/src/tabs/physics_2d/index.tsx
index 1bbe5be80..f2ee2d9bd 100644
--- a/src/tabs/physics_2d/index.tsx
+++ b/src/tabs/physics_2d/index.tsx
@@ -22,15 +22,7 @@ export default {
* @param {DebuggerContext} context
*/
body(context: DebuggerContext) {
- const {
- context: {
- moduleContexts: {
- physics_2d: {
- state: { world }
- }
- }
- }
- } = context;
+ const { context: { moduleContexts: { physics_2d: { state: { world } } } } } = context;
return (
From 318441156a4d1e4d033cb1830ad3335c9cbee50b Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Fri, 12 Apr 2024 05:58:32 +0800
Subject: [PATCH 14/39] Revert some changes in tabs
---
src/tabs/CopyGc/index.tsx | 20 +++++------
src/tabs/Csg/hover_control_hint.tsx | 6 +---
src/tabs/Curve/__tests__/Curve.tsx | 24 +++----------
src/tabs/Curve/animation_canvas_3d_curve.tsx | 6 +---
src/tabs/Curve/canvas_3d_curve.tsx | 6 +---
src/tabs/Game/constants.ts | 2 +-
src/tabs/MarkSweep/index.tsx | 18 +++++-----
src/tabs/MarkSweep/style.tsx | 2 +-
src/tabs/common/AnimationCanvas.tsx | 38 +++++++++-----------
src/tabs/physics_2d/DebugDrawCanvas.tsx | 36 +++++++++----------
10 files changed, 61 insertions(+), 97 deletions(-)
diff --git a/src/tabs/CopyGc/index.tsx b/src/tabs/CopyGc/index.tsx
index 78bde832e..c73518048 100644
--- a/src/tabs/CopyGc/index.tsx
+++ b/src/tabs/CopyGc/index.tsx
@@ -1,4 +1,4 @@
-import { Icon, Slider } from '@blueprintjs/core';
+import { Slider, Icon } from '@blueprintjs/core';
import React from 'react';
import { COMMAND } from '../../bundles/copy_gc/types';
import { ThemeColor } from './style';
@@ -57,9 +57,9 @@ class CopyGC extends React.Component
{
componentDidMount() {
const { debuggerContext } = this.props;
if (
- debuggerContext &&
- debuggerContext.result &&
- debuggerContext.result.value
+ debuggerContext
+ && debuggerContext.result
+ && debuggerContext.result.value
) {
this.initialize_state();
}
@@ -329,9 +329,9 @@ class CopyGC extends React.Component {
}}
>
{row * state.column}
- {item &&
- item.length > 0 &&
- item.map(content => {
+ {item
+ && item.length > 0
+ && item.map(content => {
const color = this.getMemoryColor(content);
const bgColor = this.getBackgroundColor(content);
return (
@@ -358,9 +358,9 @@ class CopyGC extends React.Component {
{state.toSpace > 0 ? 'To Space' : 'From Space'}
- {fromMemoryMatrix &&
- fromMemoryMatrix.length > 0 &&
- fromMemoryMatrix.map((item, row) => (
+ {fromMemoryMatrix
+ && fromMemoryMatrix.length > 0
+ && fromMemoryMatrix.map((item, row) => (
{
const badAnimation = animate_curve(1, 60, draw_connected(200), t => 1 as any);
- const mockContext = mockDebuggerContext
(
- { drawnCurves: [badAnimation] },
- 'curve'
- );
+ const mockContext = mockDebuggerContext({ drawnCurves: [badAnimation] }, 'curve');
expect( ).toMatchSnapshot();
});
test('Curve 3D animations error gracefully', () => {
- const badAnimation = animate_3D_curve(
- 1,
- 60,
- draw_3D_connected(200),
- t => 1 as any
- );
- const mockContext = mockDebuggerContext(
- { drawnCurves: [badAnimation] },
- 'curve'
- );
+ const badAnimation = animate_3D_curve(1, 60, draw_3D_connected(200), t => 1 as any);
+ const mockContext = mockDebuggerContext({ drawnCurves: [badAnimation] }, 'curve');
expect( ).toMatchSnapshot();
});
diff --git a/src/tabs/Curve/animation_canvas_3d_curve.tsx b/src/tabs/Curve/animation_canvas_3d_curve.tsx
index ece620f0c..2ed97fb0a 100644
--- a/src/tabs/Curve/animation_canvas_3d_curve.tsx
+++ b/src/tabs/Curve/animation_canvas_3d_curve.tsx
@@ -6,11 +6,7 @@ import AutoLoopSwitch from '../common/AutoLoopSwitch';
import ButtonComponent from '../common/ButtonComponent';
import PlayButton from '../common/PlayButton';
import WebGLCanvas from '../common/WebglCanvas';
-import {
- BP_TAB_BUTTON_MARGIN,
- BP_TEXT_MARGIN,
- CANVAS_MAX_WIDTH
-} from '../common/css_constants';
+import { BP_TAB_BUTTON_MARGIN, BP_TEXT_MARGIN, CANVAS_MAX_WIDTH } from '../common/css_constants';
type Props = {
animation: AnimatedCurve;
diff --git a/src/tabs/Curve/canvas_3d_curve.tsx b/src/tabs/Curve/canvas_3d_curve.tsx
index 603b3bd62..c72dc0452 100644
--- a/src/tabs/Curve/canvas_3d_curve.tsx
+++ b/src/tabs/Curve/canvas_3d_curve.tsx
@@ -4,11 +4,7 @@ import type { CurveDrawn } from '../../bundles/curve/curves_webgl';
import { degreesToRadians } from '../../common/utilities';
import PlayButton from '../common/PlayButton';
import WebGLCanvas from '../common/WebglCanvas';
-import {
- BP_TAB_BUTTON_MARGIN,
- BP_TEXT_MARGIN,
- CANVAS_MAX_WIDTH
-} from '../common/css_constants';
+import { BP_TAB_BUTTON_MARGIN, BP_TEXT_MARGIN, CANVAS_MAX_WIDTH } from '../common/css_constants';
type State = {
/**
diff --git a/src/tabs/Game/constants.ts b/src/tabs/Game/constants.ts
index b925b3ade..a6afdeac5 100644
--- a/src/tabs/Game/constants.ts
+++ b/src/tabs/Game/constants.ts
@@ -1,5 +1,5 @@
export enum Links {
gameUserGuide = 'https://github.com/source-academy/modules/wiki/%5Bgame%5D-User-Guide',
gameDeveloperDocumentation = 'https://github.com/source-academy/modules/wiki/%5Bgame%5D-Developer-Documentation',
- gameAPIDocumentation = 'https://source-academy.github.io/modules/documentation/modules/game.html'
+ gameAPIDocumentation = 'https://source-academy.github.io/modules/documentation/modules/game.html',
}
diff --git a/src/tabs/MarkSweep/index.tsx b/src/tabs/MarkSweep/index.tsx
index 2a06d1824..af2d94cb1 100644
--- a/src/tabs/MarkSweep/index.tsx
+++ b/src/tabs/MarkSweep/index.tsx
@@ -1,4 +1,4 @@
-import { Icon, Slider } from '@blueprintjs/core';
+import { Slider, Icon } from '@blueprintjs/core';
import React from 'react';
import { ThemeColor } from './style';
@@ -57,9 +57,9 @@ class MarkSweep extends React.Component {
componentDidMount() {
const { debuggerContext } = this.props;
if (
- debuggerContext &&
- debuggerContext.result &&
- debuggerContext.result.value
+ debuggerContext
+ && debuggerContext.result
+ && debuggerContext.result.value
) {
this.initialize_state();
}
@@ -178,8 +178,8 @@ class MarkSweep extends React.Component {
private getlengthFunction = () => {
const { debuggerContext } = this.props;
- const commandHeap =
- debuggerContext && debuggerContext.result.value
+ const commandHeap
+ = debuggerContext && debuggerContext.result.value
? debuggerContext.result.value.get_command()
: [];
return commandHeap.length;
@@ -335,9 +335,9 @@ class MarkSweep extends React.Component {
}}
>
{row * state.column}
- {item &&
- item.length > 0 &&
- item.map(content => {
+ {item
+ && item.length > 0
+ && item.map(content => {
const color = this.getMemoryColor(content);
const bgColor = this.getBackgroundColor(content);
return (
diff --git a/src/tabs/MarkSweep/style.tsx b/src/tabs/MarkSweep/style.tsx
index c1fddd6f1..8817fe1f3 100644
--- a/src/tabs/MarkSweep/style.tsx
+++ b/src/tabs/MarkSweep/style.tsx
@@ -5,7 +5,7 @@ export enum ThemeColor {
GREEN = '#42a870',
YELLOW = '#f0d60e',
RED = 'red',
- BLACK = 'black'
+ BLACK = 'black',
}
export const FONT = {
diff --git a/src/tabs/common/AnimationCanvas.tsx b/src/tabs/common/AnimationCanvas.tsx
index 1af2a9770..ac27634e0 100644
--- a/src/tabs/common/AnimationCanvas.tsx
+++ b/src/tabs/common/AnimationCanvas.tsx
@@ -6,11 +6,7 @@ import AutoLoopSwitch from './AutoLoopSwitch';
import ButtonComponent from './ButtonComponent';
import PlayButton from './PlayButton';
import WebGLCanvas from './WebglCanvas';
-import {
- BP_TAB_BUTTON_MARGIN,
- BP_TEXT_MARGIN,
- CANVAS_MAX_WIDTH
-} from './css_constants';
+import { BP_TAB_BUTTON_MARGIN, BP_TEXT_MARGIN, CANVAS_MAX_WIDTH } from './css_constants';
type AnimCanvasProps = {
animation: glAnimation;
@@ -108,23 +104,21 @@ export default class AnimationCanvas extends React.Component<
this.reqframeId = requestAnimationFrame(this.animationCallback);
};
- private startAnimation = () =>
- this.setState(
- {
- isPlaying: true
- },
- this.reqFrame
- );
-
- private stopAnimation = () =>
- this.setState(
- {
- isPlaying: false
- },
- () => {
- this.callbackTimestamp = null;
- }
- );
+ private startAnimation = () => this.setState(
+ {
+ isPlaying: true
+ },
+ this.reqFrame
+ );
+
+ private stopAnimation = () => this.setState(
+ {
+ isPlaying: false
+ },
+ () => {
+ this.callbackTimestamp = null;
+ }
+ );
/**
* Callback to use with `requestAnimationFrame`
diff --git a/src/tabs/physics_2d/DebugDrawCanvas.tsx b/src/tabs/physics_2d/DebugDrawCanvas.tsx
index fc55f714a..3f7cd9d7d 100644
--- a/src/tabs/physics_2d/DebugDrawCanvas.tsx
+++ b/src/tabs/physics_2d/DebugDrawCanvas.tsx
@@ -82,8 +82,8 @@ export default class DebugDrawCanvas extends React.Component<
private drawFrame = () => {
if (this.canvas) {
if (!this.debugDraw) {
- const ctx: CanvasRenderingContext2D | null =
- this.canvas.getContext('2d');
+ const ctx: CanvasRenderingContext2D | null
+ = this.canvas.getContext('2d');
if (ctx) {
this.debugDraw = new DebugDraw(ctx);
}
@@ -99,23 +99,21 @@ export default class DebugDrawCanvas extends React.Component<
private reqFrame = () => requestAnimationFrame(this.animationCallback);
- private startAnimation = () =>
- this.setState(
- {
- isPlaying: true
- },
- this.reqFrame
- );
-
- private stopAnimation = () =>
- this.setState(
- {
- isPlaying: false
- },
- () => {
- this.callbackTimestamp = null;
- }
- );
+ private startAnimation = () => this.setState(
+ {
+ isPlaying: true
+ },
+ this.reqFrame
+ );
+
+ private stopAnimation = () => this.setState(
+ {
+ isPlaying: false
+ },
+ () => {
+ this.callbackTimestamp = null;
+ }
+ );
/**
* Callback to use with `requestAnimationFrame`
From b19b3f3891943cf41fd83710eb392bfdae953cf2 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Fri, 12 Apr 2024 06:10:18 +0800
Subject: [PATCH 15/39] Reformat some files manually
---
.../src/components/sideContent/TestTab.tsx | 2 +-
src/bundles/unity_academy/UnityAcademy.tsx | 8 +--
src/tabs/AugmentedReality/StartButton.tsx | 1 -
src/tabs/CopyGc/index.tsx | 72 +++++--------------
src/tabs/Csg/canvas_holder.tsx | 13 +---
src/tabs/Curve/animation_canvas_3d_curve.tsx | 31 ++------
src/tabs/Curve/canvas_3d_curve.tsx | 24 ++-----
src/tabs/MarkSweep/index.tsx | 62 ++++------------
src/tabs/Painter/index.tsx | 4 +-
src/tabs/Plotly/index.tsx | 12 +---
src/tabs/Repl/index.tsx | 17 +----
src/tabs/RobotSimulation/components/Modal.tsx | 9 +--
src/tabs/common/AnimationCanvas.tsx | 30 ++------
src/tabs/common/MultItemDisplay.tsx | 10 +--
src/tabs/physics_2d/DebugDrawCanvas.tsx | 6 +-
15 files changed, 64 insertions(+), 237 deletions(-)
diff --git a/devserver/src/components/sideContent/TestTab.tsx b/devserver/src/components/sideContent/TestTab.tsx
index eb07aa435..aa64ef6e8 100644
--- a/devserver/src/components/sideContent/TestTab.tsx
+++ b/devserver/src/components/sideContent/TestTab.tsx
@@ -11,7 +11,7 @@ const TestTab = () => (
}}
>
Source Academy Tab Development Server
-
+
Run some code that imports modules in the editor on the left. You should
see the corresponding module tab spawn.
diff --git a/src/bundles/unity_academy/UnityAcademy.tsx b/src/bundles/unity_academy/UnityAcademy.tsx
index c0182b429..c18488878 100644
--- a/src/bundles/unity_academy/UnityAcademy.tsx
+++ b/src/bundles/unity_academy/UnityAcademy.tsx
@@ -130,12 +130,8 @@ class UnityComponent extends React.Component {
+ style={{ width: '100%', height: '100%', position: 'absolute' }}
+ />
{
{state.command}
{state.description}
{state.leftDesc ? (
{state.leftDesc}
@@ -283,9 +277,7 @@ class CopyGC extends React.Component
{
{state.rightDesc}
@@ -322,12 +314,7 @@ class CopyGC extends React.Component {
{toMemoryMatrix &&
toMemoryMatrix.length > 0 &&
toMemoryMatrix.map((item, row) => (
-
+
{row * state.column}
{item
&& item.length > 0
@@ -336,17 +323,12 @@ class CopyGC extends React.Component
{
const bgColor = this.getBackgroundColor(content);
return (
);
@@ -358,40 +340,30 @@ class CopyGC extends React.Component {
{state.toSpace > 0 ? 'To Space' : 'From Space'}
- {fromMemoryMatrix
- && fromMemoryMatrix.length > 0
- && fromMemoryMatrix.map((item, row) => (
-
+ {fromMemoryMatrix &&
+ fromMemoryMatrix.length > 0 &&
+ fromMemoryMatrix.map((item, row) => (
+
{row * state.column + state.memorySize / 2}
- {item && item.length > 0
- ? item.map(content => {
+ {item && item.length > 0 ?
+ item.map(content => {
const color = this.getMemoryColor(content);
const bgColor = this.getBackgroundColor(content);
return (
);
- })
- : false}
+ }) :
+ false}
))}
@@ -408,9 +380,7 @@ class CopyGC extends React.Component
{
defined
@@ -418,9 +388,7 @@ class CopyGC extends React.Component
{
tag
@@ -428,9 +396,7 @@ class CopyGC extends React.Component {
empty or undefined
diff --git a/src/tabs/Csg/canvas_holder.tsx b/src/tabs/Csg/canvas_holder.tsx
index c16ee5bcc..30b48faa7 100644
--- a/src/tabs/Csg/canvas_holder.tsx
+++ b/src/tabs/Csg/canvas_holder.tsx
@@ -138,23 +138,14 @@ export default class CanvasHolder extends React.Component<
className="bp3-dark"
style={{
display: this.state.isContextLost ? 'block' : 'none',
-
textAlign: 'center'
}}
>
-
+
WebGL Context Lost
-
+
Your GPU is probably busy. Waiting for browser to re-establish
connection...
diff --git a/src/tabs/Curve/animation_canvas_3d_curve.tsx b/src/tabs/Curve/animation_canvas_3d_curve.tsx
index 2ed97fb0a..10357e625 100644
--- a/src/tabs/Curve/animation_canvas_3d_curve.tsx
+++ b/src/tabs/Curve/animation_canvas_3d_curve.tsx
@@ -260,17 +260,8 @@ export default class AnimationCanvas3dCurve extends React.Component<
public render() {
return (
-
-
+
+
@@ -335,12 +325,7 @@ export default class AnimationCanvas3dCurve extends React.Component<
/>
-
+
{this.state.errored ? (
Here's the details:
-
+
{this.state.errored.toString()}
) : (
{
this.canvas = r;
}}
diff --git a/src/tabs/Curve/canvas_3d_curve.tsx b/src/tabs/Curve/canvas_3d_curve.tsx
index c72dc0452..21ed3fa47 100644
--- a/src/tabs/Curve/canvas_3d_curve.tsx
+++ b/src/tabs/Curve/canvas_3d_curve.tsx
@@ -123,17 +123,8 @@ export default class Canvas3dCurve extends React.Component {
public render() {
return (
-
-
+
+
-
+
{
this.canvas = r;
diff --git a/src/tabs/MarkSweep/index.tsx b/src/tabs/MarkSweep/index.tsx
index af2d94cb1..0f48e1da7 100644
--- a/src/tabs/MarkSweep/index.tsx
+++ b/src/tabs/MarkSweep/index.tsx
@@ -267,20 +267,14 @@ class MarkSweep extends React.Component {
{state.command}
{state.description}
{state.leftDesc && (
{state.leftDesc}
@@ -290,9 +284,7 @@ class MarkSweep extends React.Component
{
{state.rightDesc}
@@ -328,12 +320,7 @@ class MarkSweep extends React.Component {
{memoryMatrix &&
memoryMatrix.length > 0 &&
memoryMatrix.map((item, row) => (
-
+
{row * state.column}
{item
&& item.length > 0
@@ -342,17 +329,12 @@ class MarkSweep extends React.Component
{
const bgColor = this.getBackgroundColor(content);
return (
);
@@ -374,19 +356,13 @@ class MarkSweep extends React.Component {
defined
@@ -394,9 +370,7 @@ class MarkSweep extends React.Component
{
tag
@@ -404,19 +378,13 @@ class MarkSweep extends React.Component {
empty or undefined
MARK_SLOT:
@@ -425,9 +393,7 @@ class MarkSweep extends React.Component
{
marked
@@ -435,9 +401,7 @@ class MarkSweep extends React.Component
{
unmarked
diff --git a/src/tabs/Painter/index.tsx b/src/tabs/Painter/index.tsx
index b76984335..9c421f170 100644
--- a/src/tabs/Painter/index.tsx
+++ b/src/tabs/Painter/index.tsx
@@ -52,7 +52,7 @@ class Painter extends React.Component
{
height: '20rem',
width: '20rem'
}}
- >
+ />
{drawnPainters.map((drawnPainter: any, id: number) => {
const divId = `plotDiv${id}`;
@@ -67,7 +67,7 @@ class Painter extends React.Component
{
console.log(drawnPainter);
drawnPainter.draw(divId);
}}
- >
+ />
>
);
})}
diff --git a/src/tabs/Plotly/index.tsx b/src/tabs/Plotly/index.tsx
index ee24a7628..185f29a66 100644
--- a/src/tabs/Plotly/index.tsx
+++ b/src/tabs/Plotly/index.tsx
@@ -49,18 +49,12 @@ class Plotly extends React.Component
{
}
}}
style={{ height: '80vh' }}
- >
+ />
{drawnPlots.map((drawnPlot: any, id: number) => {
const divId = `plotDiv${id}`;
return (
-
+
this.handleOpen(drawnPlot)}>
Click here to open Modal
@@ -70,7 +64,7 @@ class Plotly extends React.Component
{
ref={() => {
drawnPlot.draw(divId);
}}
- >
+ />
);
})}
diff --git a/src/tabs/Repl/index.tsx b/src/tabs/Repl/index.tsx
index 1abf49fca..044c6df89 100644
--- a/src/tabs/Repl/index.tsx
+++ b/src/tabs/Repl/index.tsx
@@ -84,10 +84,7 @@ class ProgrammableReplGUI extends React.Component {
} else {
outputDivs.push(
);
@@ -96,12 +93,7 @@ class ProgrammableReplGUI extends React.Component {
outputDivs.push({str.content}
);
} else {
outputDivs.push(
-
+
{str.content}
);
@@ -155,10 +147,7 @@ class ProgrammableReplGUI extends React.Component
{
= ({ children, isOpen, onClose }) => {
return (
-
-
+
+
x
diff --git a/src/tabs/common/AnimationCanvas.tsx b/src/tabs/common/AnimationCanvas.tsx
index ac27634e0..42d332e07 100644
--- a/src/tabs/common/AnimationCanvas.tsx
+++ b/src/tabs/common/AnimationCanvas.tsx
@@ -237,17 +237,8 @@ export default class AnimationCanvas extends React.Component<
public render() {
return (
-
-
+
-
+
{this.state.errored ? (
Here's the details:
-
+
{this.state.errored.toString()}
) : (
{
this.canvas = r;
}}
diff --git a/src/tabs/common/MultItemDisplay.tsx b/src/tabs/common/MultItemDisplay.tsx
index b019e110a..3c79cfa57 100644
--- a/src/tabs/common/MultItemDisplay.tsx
+++ b/src/tabs/common/MultItemDisplay.tsx
@@ -39,10 +39,7 @@ const MultiItemDisplay = ({ elements }: MultiItemDisplayProps) => {
}}
>
{
-
+
Date: Fri, 12 Apr 2024 06:27:00 +0800
Subject: [PATCH 16/39] Revert some changes in bundles
---
src/bundles/arcade_2d/audio.ts | 9 +--
src/bundles/arcade_2d/constants.ts | 9 +--
src/bundles/arcade_2d/gameobject.ts | 31 ++-------
src/bundles/arcade_2d/index.ts | 40 ++++++------
src/bundles/arcade_2d/types.ts | 5 +-
src/bundles/binary_tree/index.ts | 9 +--
src/bundles/communication/index.ts | 12 ++--
src/bundles/copy_gc/index.ts | 30 ++++-----
src/bundles/copy_gc/types.ts | 2 +-
src/bundles/csg/index.ts | 79 ++++++++++++-----------
src/bundles/csg/input_tracker.ts | 20 +++---
src/bundles/csg/jscad/types.ts | 6 +-
src/bundles/csg/types.ts | 2 +-
src/bundles/csg/utilities.ts | 12 ++--
src/bundles/curve/samples/canvases.js | 14 +---
src/bundles/curve/samples/imports.js | 38 +++++++++++
src/bundles/game/index.ts | 12 ++--
src/bundles/mark_sweep/index.ts | 30 ++++-----
src/bundles/painter/index.ts | 2 +-
src/bundles/physics_2d/index.ts | 48 ++++++++------
src/bundles/pix_n_flix/index.ts | 24 +++----
src/bundles/pix_n_flix/types.ts | 2 +-
src/bundles/plotly/curve_functions.ts | 2 +-
src/bundles/plotly/index.ts | 6 +-
src/bundles/repeat/__tests__/index.ts | 2 +-
src/bundles/repeat/index.ts | 2 +-
src/bundles/repl/index.ts | 6 +-
src/bundles/rune/index.ts | 2 +-
src/bundles/rune/rune.ts | 22 +++----
src/bundles/rune/runes_ops.ts | 3 +-
src/bundles/rune_in_words/functions.ts | 24 +++----
src/bundles/rune_in_words/index.ts | 2 +-
src/bundles/scrabble/index.ts | 6 +-
src/bundles/sound/__tests__/sound.test.ts | 23 +++----
src/bundles/sound/index.ts | 2 +-
src/bundles/sound_matrix/index.ts | 6 +-
src/bundles/stereo_sound/index.ts | 54 ++++++++--------
src/bundles/wasm/index.ts | 5 +-
38 files changed, 288 insertions(+), 315 deletions(-)
diff --git a/src/bundles/arcade_2d/audio.ts b/src/bundles/arcade_2d/audio.ts
index 3618edf22..1cf943a44 100644
--- a/src/bundles/arcade_2d/audio.ts
+++ b/src/bundles/arcade_2d/audio.ts
@@ -9,10 +9,7 @@
export class AudioClip {
private static audioClipCount: number = 0;
// Stores AudioClip index with the URL as a unique key.
- private static audioClipsIndexMap: Map = new Map<
- string,
- number
- >();
+ private static audioClipsIndexMap: Map = new Map();
// Stores all the created AudioClips
private static audioClipsArray: Array = [];
public readonly id: number;
@@ -36,9 +33,7 @@ export class AudioClip {
throw new Error('AudioClip URL cannot be empty');
}
if (AudioClip.audioClipsIndexMap.has(url)) {
- return AudioClip.audioClipsArray[
- AudioClip.audioClipsIndexMap.get(url) as number
- ];
+ return AudioClip.audioClipsArray[AudioClip.audioClipsIndexMap.get(url) as number];
}
return new AudioClip(url, volumeLevel);
}
diff --git a/src/bundles/arcade_2d/constants.ts b/src/bundles/arcade_2d/constants.ts
index 856953c0c..636196541 100644
--- a/src/bundles/arcade_2d/constants.ts
+++ b/src/bundles/arcade_2d/constants.ts
@@ -1,10 +1,6 @@
// This file contains the default values of the game canvas and GameObjects.
-import {
- type InteractableProps,
- type RenderProps,
- type TransformProps
-} from './types';
+import { type InteractableProps, type RenderProps, type TransformProps } from './types';
// Default values of game
export const DEFAULT_WIDTH: number = 600;
@@ -47,5 +43,4 @@ export const DEFAULT_INTERACTABLE_PROPS: InteractableProps = {
};
// Default values of Phaser scene
-export const DEFAULT_PATH_PREFIX: string =
- 'https://source-academy-assets.s3-ap-southeast-1.amazonaws.com/';
+export const DEFAULT_PATH_PREFIX: string = 'https://source-academy-assets.s3-ap-southeast-1.amazonaws.com/';
diff --git a/src/bundles/arcade_2d/gameobject.ts b/src/bundles/arcade_2d/gameobject.ts
index bad6eb7ff..8927d66fb 100644
--- a/src/bundles/arcade_2d/gameobject.ts
+++ b/src/bundles/arcade_2d/gameobject.ts
@@ -2,11 +2,7 @@
* This file contains the bundle's representation of GameObjects.
*/
import type { ReplResult } from '../../typings/type_helpers';
-import {
- DEFAULT_INTERACTABLE_PROPS,
- DEFAULT_RENDER_PROPS,
- DEFAULT_TRANSFORM_PROPS
-} from './constants';
+import { DEFAULT_INTERACTABLE_PROPS, DEFAULT_RENDER_PROPS, DEFAULT_TRANSFORM_PROPS } from './constants';
import type * as types from './types';
// =============================================================================
@@ -55,9 +51,7 @@ export abstract class GameObject implements Transformable, ReplResult {
/**
* Encapsulates the basic data-representation of a RenderableGameObject.
*/
-export abstract class RenderableGameObject
- extends GameObject
- implements Renderable {
+export abstract class RenderableGameObject extends GameObject implements Renderable {
protected isRenderUpdated: boolean = false;
private shouldBringToTop: boolean = false;
@@ -109,9 +103,7 @@ export abstract class RenderableGameObject
/**
* Encapsulates the basic data-representation of a InteractableGameObject.
*/
-export abstract class InteractableGameObject
- extends RenderableGameObject
- implements Interactable {
+export abstract class InteractableGameObject extends RenderableGameObject implements Interactable {
protected isHitboxUpdated: boolean = false;
protected phaserGameObject: types.PhaserGameObject | undefined;
@@ -140,12 +132,7 @@ export abstract class InteractableGameObject
* This stores the GameObject within the phaser game, which can only be set after the game has started.
* @param phaserGameObject The phaser GameObject reference.
*/
- setPhaserGameObject(
- phaserGameObject:
- | Phaser.GameObjects.Shape
- | Phaser.GameObjects.Sprite
- | Phaser.GameObjects.Text
- ) {
+ setPhaserGameObject(phaserGameObject: Phaser.GameObjects.Shape | Phaser.GameObjects.Sprite | Phaser.GameObjects.Text) {
this.phaserGameObject = phaserGameObject;
}
/**
@@ -155,19 +142,13 @@ export abstract class InteractableGameObject
* @returns True, if both GameObjects overlap in the phaser game.
*/
isOverlapping(other: InteractableGameObject): boolean {
- if (
- this.phaserGameObject === undefined ||
- other.phaserGameObject === undefined
- ) {
+ if (this.phaserGameObject === undefined || other.phaserGameObject === undefined) {
return false;
}
// Use getBounds to check if two objects overlap, checking the shape of the area before checking overlap.
// Since getBounds() returns a Rectangle, it will be unable to check the actual intersection of non-rectangular shapes.
// eslint-disable-next-line new-cap
- return Phaser.Geom.Intersects.RectangleToRectangle(
- this.phaserGameObject.getBounds(),
- other.phaserGameObject.getBounds()
- );
+ return Phaser.Geom.Intersects.RectangleToRectangle(this.phaserGameObject.getBounds(), other.phaserGameObject.getBounds());
}
}
diff --git a/src/bundles/arcade_2d/index.ts b/src/bundles/arcade_2d/index.ts
index f5985c2e9..894131aad 100644
--- a/src/bundles/arcade_2d/index.ts
+++ b/src/bundles/arcade_2d/index.ts
@@ -218,24 +218,11 @@ build_game();
*/
export {
- build_game,
- create_audio,
create_circle,
create_rectangle,
+ create_triangle,
create_sprite,
create_text,
- create_triangle,
- debug_log,
- enable_debug,
- gameobjects_overlap,
- get_game_time,
- get_loop_count,
- input_key_down,
- input_left_mouse_down,
- input_right_mouse_down,
- loop_audio,
- play_audio,
- pointer_over_gameobject,
query_color,
query_flip,
query_id,
@@ -244,16 +231,29 @@ export {
query_rotation,
query_scale,
query_text,
- set_dimensions,
- set_fps,
- set_scale,
- stop_audio,
update_color,
update_flip,
- update_loop,
update_position,
update_rotation,
update_scale,
update_text,
- update_to_top
+ update_to_top,
+ set_fps,
+ set_dimensions,
+ set_scale,
+ get_game_time,
+ get_loop_count,
+ enable_debug,
+ debug_log,
+ input_key_down,
+ input_left_mouse_down,
+ input_right_mouse_down,
+ pointer_over_gameobject,
+ gameobjects_overlap,
+ update_loop,
+ build_game,
+ create_audio,
+ loop_audio,
+ stop_audio,
+ play_audio
} from './functions';
diff --git a/src/bundles/arcade_2d/types.ts b/src/bundles/arcade_2d/types.ts
index 2928c2da0..875801d93 100644
--- a/src/bundles/arcade_2d/types.ts
+++ b/src/bundles/arcade_2d/types.ts
@@ -125,7 +125,4 @@ export type ExceptionError = {
/**
* Represents the Phaser Game Object types that are used.
*/
-export type PhaserGameObject =
- | Phaser.GameObjects.Shape
- | Phaser.GameObjects.Sprite
- | Phaser.GameObjects.Text;
+export type PhaserGameObject = Phaser.GameObjects.Shape | Phaser.GameObjects.Sprite | Phaser.GameObjects.Text;
diff --git a/src/bundles/binary_tree/index.ts b/src/bundles/binary_tree/index.ts
index b19399410..88c102ebe 100644
--- a/src/bundles/binary_tree/index.ts
+++ b/src/bundles/binary_tree/index.ts
@@ -9,11 +9,6 @@
* @author Loh Xian Ze, Bryan
*/
export {
- entry,
- is_empty_tree,
- is_tree,
- left_branch,
- make_empty_tree,
- make_tree,
- right_branch
+ entry, is_empty_tree, is_tree, left_branch,
+ make_empty_tree, make_tree, right_branch
} from './functions';
diff --git a/src/bundles/communication/index.ts b/src/bundles/communication/index.ts
index e742904b1..8971eb75d 100644
--- a/src/bundles/communication/index.ts
+++ b/src/bundles/communication/index.ts
@@ -13,18 +13,18 @@ export {
STATE_CONNECTED,
STATE_DISCONNECTED,
STATE_OFFLINE,
- STATE_RECONNECTING
+ STATE_RECONNECTING,
} from './MqttController';
export {
- callFunction,
- expose,
- getGlobalState,
- getUserId,
initCommunications,
initGlobalState,
+ getGlobalState,
+ updateGlobalState,
initRpc,
+ getUserId,
+ expose,
+ callFunction,
keepRunning,
stopRunning,
- updateGlobalState
} from './Communications';
diff --git a/src/bundles/copy_gc/index.ts b/src/bundles/copy_gc/index.ts
index 8b73b4280..0c8d3c0a7 100644
--- a/src/bundles/copy_gc/index.ts
+++ b/src/bundles/copy_gc/index.ts
@@ -1,10 +1,4 @@
-import {
- COMMAND,
- type CommandHeapObject,
- type Memory,
- type MemoryHeaps,
- type Tag
-} from './types';
+import { COMMAND, type CommandHeapObject, type Memory, type MemoryHeaps, type Tag } from './types';
// Global Variables
let ROW: number = 10;
@@ -489,25 +483,25 @@ function init() {
}
export {
- allHeap,
- doneShowRoot,
- endFlip,
- generateMemory,
init,
// initialisation
initialize_memory,
initialize_tag,
- newAssign,
+ generateMemory,
+ allHeap,
+ updateSlotSegment,
+ resetFromSpace,
newCommand,
newCopy,
- newNew,
- newPop,
+ endFlip,
newPush,
- resetFromSpace,
- resetRoots,
+ newPop,
+ newAssign,
+ newNew,
scanFlip,
- showRoots,
startFlip,
updateRoots,
- updateSlotSegment
+ resetRoots,
+ showRoots,
+ doneShowRoot
};
diff --git a/src/bundles/copy_gc/types.ts b/src/bundles/copy_gc/types.ts
index d02270cc5..32ae5b243 100644
--- a/src/bundles/copy_gc/types.ts
+++ b/src/bundles/copy_gc/types.ts
@@ -12,7 +12,7 @@ export enum COMMAND {
ASSIGN = 'Assign',
NEW = 'New',
SCAN = 'Scan',
- INIT = 'Initialize Memory'
+ INIT = 'Initialize Memory',
}
export type CommandHeapObject = {
diff --git a/src/bundles/csg/index.ts b/src/bundles/csg/index.ts
index 58732a22a..57c4e53eb 100644
--- a/src/bundles/csg/index.ts
+++ b/src/bundles/csg/index.ts
@@ -71,53 +71,58 @@ Core.initialize(moduleState);
export {
// Colors
black,
- blue,
- bounding_box,
- cone,
+ navy,
+ green,
+ teal,
crimson,
- cube,
- cyan,
- cylinder,
- download_shape_stl,
- // Primitives
- empty_shape,
- geodesic_sphere,
+ purple,
+ orange,
+ silver,
gray,
- green,
- // Utilities
- group,
- intersect,
- is_group,
- is_shape,
+ blue,
lime,
- navy,
- orange,
- pink,
- prism,
- purple,
- pyramid,
- // Rendering
- render,
- render_axes,
- render_grid,
- render_grid_axes,
- rgb,
+ cyan,
rose,
- rotate,
+ pink,
+ yellow,
+ white,
+
+ // Primitives
+ empty_shape,
+ cube,
rounded_cube,
+ cylinder,
rounded_cylinder,
- scale,
- silver,
sphere,
+ geodesic_sphere,
+ pyramid,
+ cone,
+ prism,
star,
- subtract,
- teal,
torus,
+
+ // Operations
+ union,
+ subtract,
+ intersect,
+
// Transformations
translate,
+ rotate,
+ scale,
+
+ // Utilities
+ group,
ungroup,
- // Operations
- union,
- white,
- yellow
+ is_shape,
+ is_group,
+ bounding_box,
+ rgb,
+ download_shape_stl,
+
+ // Rendering
+ render,
+ render_grid,
+ render_axes,
+ render_grid_axes
} from './functions';
diff --git a/src/bundles/csg/input_tracker.ts b/src/bundles/csg/input_tracker.ts
index 7f5867d52..739453a99 100644
--- a/src/bundles/csg/input_tracker.ts
+++ b/src/bundles/csg/input_tracker.ts
@@ -26,7 +26,7 @@ enum MousePointer {
FORWARD = 4,
NONE = -1,
- OTHER = 7050
+ OTHER = 7050,
}
/* [Exports] */
@@ -91,8 +91,8 @@ export default class InputTracker {
private isPointerPan(isShiftKey: boolean): boolean {
return (
- this.heldPointer === MousePointer.MIDDLE ||
- (this.heldPointer === MousePointer.LEFT && isShiftKey)
+ this.heldPointer === MousePointer.MIDDLE
+ || (this.heldPointer === MousePointer.LEFT && isShiftKey)
);
}
@@ -108,9 +108,7 @@ export default class InputTracker {
const canvasBounds: DOMRect = this.canvas.getBoundingClientRect();
const { devicePixelRatio } = window;
const newWidth: number = Math.floor(canvasBounds.width * devicePixelRatio);
- const newHeight: number = Math.floor(
- canvasBounds.height * devicePixelRatio
- );
+ const newHeight: number = Math.floor(canvasBounds.height * devicePixelRatio);
if (oldWidth === newWidth && oldHeight === newHeight) return;
this.frameDirty = true;
@@ -139,13 +137,13 @@ export default class InputTracker {
const scaledChange: number = currentTick * ZOOM_TICK_SCALE;
const potentialNewScale: number = this.controlsState.scale + scaledChange;
- const potentialNewDistance: number =
- vec3.distance(this.cameraState.position, this.cameraState.target) *
- potentialNewScale;
+ const potentialNewDistance: number
+ = vec3.distance(this.cameraState.position, this.cameraState.target)
+ * potentialNewScale;
if (
- potentialNewDistance > this.controlsState.limits.minDistance &&
- potentialNewDistance < this.controlsState.limits.maxDistance
+ potentialNewDistance > this.controlsState.limits.minDistance
+ && potentialNewDistance < this.controlsState.limits.maxDistance
) {
this.frameDirty = true;
this.controlsState.scale = potentialNewScale;
diff --git a/src/bundles/csg/jscad/types.ts b/src/bundles/csg/jscad/types.ts
index 1fe7c2f00..4051990ed 100644
--- a/src/bundles/csg/jscad/types.ts
+++ b/src/bundles/csg/jscad/types.ts
@@ -1,11 +1,7 @@
/* [Import] */
import type { RGB, RGBA } from '@jscad/modeling/src/colors/types';
import type { Geom3 } from '@jscad/modeling/src/geometries/types';
-import {
- controls,
- type cameras,
- type drawCommands
-} from '@jscad/regl-renderer';
+import { type cameras, type drawCommands, controls } from '@jscad/regl-renderer';
import type makeDrawMultiGrid from '@jscad/regl-renderer/types/rendering/commands/drawGrid/multi';
/* [Main] */
diff --git a/src/bundles/csg/types.ts b/src/bundles/csg/types.ts
index d09afda88..7901655bc 100644
--- a/src/bundles/csg/types.ts
+++ b/src/bundles/csg/types.ts
@@ -2,8 +2,8 @@
import type { RGB, RGBA } from '@jscad/modeling/src/colors';
import type { Geom3 } from '@jscad/modeling/src/geometries/types';
import {
- controls as _controls,
cameras,
+ controls as _controls,
type drawCommands
} from '@jscad/regl-renderer';
import type makeDrawMultiGrid from '@jscad/regl-renderer/types/rendering/commands/drawGrid/multi';
diff --git a/src/bundles/csg/utilities.ts b/src/bundles/csg/utilities.ts
index d9bb241fd..5d3bc03a0 100644
--- a/src/bundles/csg/utilities.ts
+++ b/src/bundles/csg/utilities.ts
@@ -95,9 +95,7 @@ export class Group implements Operable, ReplResult {
ungroup(): Operable[] {
// Return all children, but we need to account for this Group's unresolved
// transforms by applying them to each child
- return this.children.map((child: Operable) =>
- child.applyTransforms(this.transforms)
- );
+ return this.children.map((child: Operable) => child.applyTransforms(this.transforms));
}
}
@@ -220,10 +218,10 @@ export function centerPrimitive(shape: Shape) {
}
export function hexToColor(hex: string): Color {
- const regex: RegExp =
- /^#?(?[\da-f]{2})(?[\da-f]{2})(?[\da-f]{2})$/iu;
- const potentialGroups: { [key: string]: string } | undefined =
- hex.match(regex)?.groups;
+ const regex: RegExp
+ = /^#?(?[\da-f]{2})(?[\da-f]{2})(?[\da-f]{2})$/iu;
+ const potentialGroups: { [key: string]: string } | undefined
+ = hex.match(regex)?.groups;
if (potentialGroups === undefined) return [0, 0, 0];
const groups: { [key: string]: string } = potentialGroups;
diff --git a/src/bundles/curve/samples/canvases.js b/src/bundles/curve/samples/canvases.js
index 56be0c033..cbac23d7c 100644
--- a/src/bundles/curve/samples/canvases.js
+++ b/src/bundles/curve/samples/canvases.js
@@ -5,16 +5,6 @@ draw_connected_full_view(20)(unit_circle);
draw_3D_connected(100)(t => make_3D_point(t, t * t, t));
-animate_curve(
- 3,
- 30,
- draw_connected_full_view_proportional(100),
- s => t => make_point(t - s, t * s)
-);
+animate_curve(3, 30, draw_connected_full_view_proportional(100), s => t => make_point(t - s, t * s));
-animate_3D_curve(
- 3,
- 40,
- draw_3D_connected_full_view_proportional(100),
- s => t => make_3D_point(t - s, t - t * s, t * s)
-);
+animate_3D_curve(3, 40, draw_3D_connected_full_view_proportional(100), s => t => make_3D_point(t - s, t - t * s, t * s));
diff --git a/src/bundles/curve/samples/imports.js b/src/bundles/curve/samples/imports.js
index 8b1378917..b61fc316d 100644
--- a/src/bundles/curve/samples/imports.js
+++ b/src/bundles/curve/samples/imports.js
@@ -1 +1,39 @@
+import {
+ animate_3D_curve,
+ animate_curve,
+ arc,
+ b_of,
+ connect_ends,
+ connect_rigidly,
+ draw_3D_connected,
+ draw_3D_connected_full_view,
+ draw_3D_connected_full_view_proportional,
+ draw_3D_points,
+ draw_3D_points_full_view,
+ draw_3D_points_full_view_proportional,
+ draw_connected,
+ draw_connected_full_view,
+ draw_connected_full_view_proportional,
+ draw_points,
+ draw_points_full_view,
+ draw_points_full_view_proportional,
+ g_of,
+ invert,
+ make_3D_color_point,
+ make_3D_point,
+ make_color_point,
+ make_point,
+ put_in_standard_position,
+ r_of,
+ rotate_around_origin,
+ scale,
+ scale_proportional,
+ translate,
+ unit_circle,
+ unit_line,
+ unit_line_at,
+ x_of,
+ y_of,
+ z_of
+} from 'curve';
diff --git a/src/bundles/game/index.ts b/src/bundles/game/index.ts
index 797b81ac2..17cf21529 100644
--- a/src/bundles/game/index.ts
+++ b/src/bundles/game/index.ts
@@ -16,8 +16,8 @@
export {
add,
- add_keyboard_listener,
add_listener,
+ add_keyboard_listener,
add_to_container,
add_tween,
create_anim,
@@ -31,16 +31,16 @@ export {
create_image,
create_interactive_config,
create_rect,
- create_sound_config,
- create_spritesheet_config,
create_text,
create_text_config,
create_tween_config,
+ create_sound_config,
+ create_spritesheet_config,
destroy_obj,
- get_screen_display_height,
- get_screen_display_width,
- get_screen_height,
get_screen_width,
+ get_screen_height,
+ get_screen_display_width,
+ get_screen_display_height,
load_image,
load_sound,
load_spritesheet,
diff --git a/src/bundles/mark_sweep/index.ts b/src/bundles/mark_sweep/index.ts
index a35234c41..e0550db8d 100644
--- a/src/bundles/mark_sweep/index.ts
+++ b/src/bundles/mark_sweep/index.ts
@@ -1,10 +1,4 @@
-import {
- COMMAND,
- type CommandHeapObject,
- type Memory,
- type MemoryHeaps,
- type Tag
-} from './types';
+import { type MemoryHeaps, type Memory, type Tag, COMMAND, type CommandHeapObject } from './types';
// Global Variables
let ROW: number = 10;
@@ -356,25 +350,25 @@ function init() {
}
export {
- addRoots,
- allHeap,
- endGC,
- generateMemory,
init,
// initialisation
initialize_memory,
initialize_tag,
- newAssign,
+ generateMemory,
+ allHeap,
+ updateSlotSegment,
newCommand,
- newGC,
newMark,
- newNew,
- newPop,
newPush,
+ newPop,
+ newAssign,
+ newNew,
+ newGC,
newSweep,
+ updateRoots,
newUpdateSweep,
- showRoot,
showRoots,
- updateRoots,
- updateSlotSegment
+ endGC,
+ addRoots,
+ showRoot
};
diff --git a/src/bundles/painter/index.ts b/src/bundles/painter/index.ts
index 6830409f6..3e6c83a66 100644
--- a/src/bundles/painter/index.ts
+++ b/src/bundles/painter/index.ts
@@ -4,4 +4,4 @@
* @author Sourabh Raj Jaiswal
*/
-export { display_painter, draw_line } from './functions';
+export { draw_line, display_painter } from './functions';
diff --git a/src/bundles/physics_2d/index.ts b/src/bundles/physics_2d/index.ts
index 62f1a27d0..836afd7ed 100644
--- a/src/bundles/physics_2d/index.ts
+++ b/src/bundles/physics_2d/index.ts
@@ -73,33 +73,41 @@
* @author Yu Jiali
*/
export {
+ set_gravity,
+ make_ground,
+ add_wall,
+
+ make_vector,
+ make_force,
+
add_box_object,
add_circle_object,
add_triangle_object,
- add_vector,
- add_wall,
- apply_force,
- apply_force_to_center,
- array_to_vector,
- get_angular_velocity,
- get_position,
- get_rotation,
- get_velocity,
- impact_start_time,
- is_touching,
- make_force,
- make_ground,
- make_vector,
- scale_size,
- set_angular_velocity,
+
set_density,
set_friction,
- set_gravity,
+ scale_size,
+
+ get_position,
set_position,
+ get_rotation,
set_rotation,
+ get_velocity,
set_velocity,
- simulate_world,
- subtract_vector,
+ get_angular_velocity,
+ set_angular_velocity,
+
+ apply_force,
+ apply_force_to_center,
+
+ is_touching,
+ impact_start_time,
+
update_world,
- vector_to_array
+ simulate_world,
+
+ vector_to_array,
+ array_to_vector,
+ add_vector,
+ subtract_vector
} from './functions';
diff --git a/src/bundles/pix_n_flix/index.ts b/src/bundles/pix_n_flix/index.ts
index 19eb42891..8d6776292 100644
--- a/src/bundles/pix_n_flix/index.ts
+++ b/src/bundles/pix_n_flix/index.ts
@@ -23,26 +23,26 @@
*/
export {
- alpha_of,
+ start,
+ red_of,
blue_of,
- compose_filter,
- copy_image,
- get_video_time,
green_of,
+ alpha_of,
+ set_rgba,
image_height,
image_width,
+ copy_image,
install_filter,
- keep_aspect_ratio,
- pause_at,
- red_of,
reset_filter,
+ compose_filter,
+ pause_at,
set_dimensions,
set_fps,
- set_loop_count,
- set_rgba,
set_volume,
- start,
- use_image_url,
use_local_file,
- use_video_url
+ use_image_url,
+ use_video_url,
+ get_video_time,
+ keep_aspect_ratio,
+ set_loop_count
} from './functions';
diff --git a/src/bundles/pix_n_flix/types.ts b/src/bundles/pix_n_flix/types.ts
index 39cc98bb1..5f5495552 100644
--- a/src/bundles/pix_n_flix/types.ts
+++ b/src/bundles/pix_n_flix/types.ts
@@ -12,7 +12,7 @@ export enum InputFeed {
Camera,
ImageURL,
VideoURL,
- Local
+ Local,
}
export type BundlePacket = {
diff --git a/src/bundles/plotly/curve_functions.ts b/src/bundles/plotly/curve_functions.ts
index fe04f2122..26592a4e1 100644
--- a/src/bundles/plotly/curve_functions.ts
+++ b/src/bundles/plotly/curve_functions.ts
@@ -1,5 +1,5 @@
import Plotly, { type Data, type Layout } from 'plotly.js-dist';
-import { CurvePlot, type Curve, type Point } from './plotly';
+import { type Curve, CurvePlot, type Point } from './plotly';
export function x_of(pt: Point): number {
return pt.x;
diff --git a/src/bundles/plotly/index.ts b/src/bundles/plotly/index.ts
index 19e984f70..e588d53ad 100644
--- a/src/bundles/plotly/index.ts
+++ b/src/bundles/plotly/index.ts
@@ -4,11 +4,11 @@
*/
export {
+ new_plot,
+ new_plot_json,
draw_connected_2d,
draw_connected_3d,
draw_points_2d,
draw_points_3d,
- draw_sound_2d,
- new_plot,
- new_plot_json
+ draw_sound_2d
} from './functions';
diff --git a/src/bundles/repeat/__tests__/index.ts b/src/bundles/repeat/__tests__/index.ts
index 89b34fc88..603df598b 100644
--- a/src/bundles/repeat/__tests__/index.ts
+++ b/src/bundles/repeat/__tests__/index.ts
@@ -1,4 +1,4 @@
-import { repeat, thrice, twice } from '../functions';
+import { repeat, twice, thrice } from '../functions';
// Test functions
test('repeat works correctly and repeats function n times', () => {
diff --git a/src/bundles/repeat/index.ts b/src/bundles/repeat/index.ts
index 2275398b9..8e1023ae4 100644
--- a/src/bundles/repeat/index.ts
+++ b/src/bundles/repeat/index.ts
@@ -4,4 +4,4 @@
* @author Tang Xin Kye, Marcus
*/
-export { repeat, thrice, twice } from './functions';
+export { repeat, twice, thrice } from './functions';
diff --git a/src/bundles/repl/index.ts b/src/bundles/repl/index.ts
index 02cab6333..dd7586869 100644
--- a/src/bundles/repl/index.ts
+++ b/src/bundles/repl/index.ts
@@ -38,9 +38,9 @@
*/
export {
- default_js_slang,
+ set_evaluator,
repl_display,
set_background_image,
- set_evaluator,
- set_font_size
+ set_font_size,
+ default_js_slang
} from './functions';
diff --git a/src/bundles/rune/index.ts b/src/bundles/rune/index.ts
index 59f7bf162..693d91bc5 100644
--- a/src/bundles/rune/index.ts
+++ b/src/bundles/rune/index.ts
@@ -42,8 +42,8 @@ export {
scale_independent,
square,
stack,
- stack_frac,
stackn,
+ stack_frac,
translate,
triangle,
turn_upside_down,
diff --git a/src/bundles/rune/rune.ts b/src/bundles/rune/rune.ts
index 0731deda9..b08e12251 100644
--- a/src/bundles/rune/rune.ts
+++ b/src/bundles/rune/rune.ts
@@ -1,5 +1,5 @@
import { mat4 } from 'gl-matrix';
-import { glAnimation, type AnimFrame } from '../../typings/anim_types';
+import { type AnimFrame, glAnimation } from '../../typings/anim_types';
import type { ReplResult } from '../../typings/type_helpers';
import { getWebGlFromCanvas, initShaderProgram } from './runes_webgl';
@@ -67,15 +67,14 @@ export class Rune {
public hollusionDistance: number
) {}
- public copy = () =>
- new Rune(
- this.vertices,
- this.colors,
- mat4.clone(this.transformMatrix),
- this.subRunes,
- this.texture,
- this.hollusionDistance
- );
+ public copy = () => new Rune(
+ this.vertices,
+ this.colors,
+ mat4.clone(this.transformMatrix),
+ this.subRunes,
+ this.texture,
+ this.hollusionDistance
+ );
/**
* Flatten the subrunes to return a list of runes
@@ -119,8 +118,7 @@ export class Rune {
hollusionDistance?: number;
} = {}
) => {
- const paramGetter = (name: string, defaultValue: () => any) =>
- params[name] === undefined ? defaultValue() : params[name];
+ const paramGetter = (name: string, defaultValue: () => any) => (params[name] === undefined ? defaultValue() : params[name]);
return new Rune(
paramGetter('vertices', () => new Float32Array()),
diff --git a/src/bundles/rune/runes_ops.ts b/src/bundles/rune/runes_ops.ts
index 56ae2cc2e..e64c83124 100644
--- a/src/bundles/rune/runes_ops.ts
+++ b/src/bundles/rune/runes_ops.ts
@@ -338,8 +338,7 @@ export const colorPalette = [
];
export function hexToColor(hex: string): number[] {
- const result =
- /^#?(?[a-f\d]{2})(?[a-f\d]{2})(?[a-f\d]{2})$/iu.exec(hex);
+ const result = /^#?(?[a-f\d]{2})(?[a-f\d]{2})(?[a-f\d]{2})$/iu.exec(hex);
if (result === null || result.length < 4) {
return [0, 0, 0];
}
diff --git a/src/bundles/rune_in_words/functions.ts b/src/bundles/rune_in_words/functions.ts
index 90c84f9b5..d40a90e84 100644
--- a/src/bundles/rune_in_words/functions.ts
+++ b/src/bundles/rune_in_words/functions.ts
@@ -1,16 +1,16 @@
import type { Rune } from './rune';
import {
+ getSquare,
getBlank,
- getCircle,
+ getRcross,
+ getSail,
+ getTriangle,
getCorner,
- getHeart,
getNova,
+ getCircle,
+ getHeart,
getPentagram,
- getRcross,
getRibbon,
- getSail,
- getSquare,
- getTriangle,
throwIfNotRune
} from './runes_ops';
@@ -277,11 +277,7 @@ export function turn_upside_down(rune: string): string {
*
* @category Main
*/
-export function beside_frac(
- frac: number,
- rune1: string,
- rune2: string
-): string {
+export function beside_frac(frac: number, rune1: string, rune2: string): string {
throwIfNotRune(beside_frac.name, rune1, rune2);
return `beside_frac(${frac}, ${rune1}, ${rune2})`;
@@ -382,11 +378,7 @@ export function repeat_pattern(
*
* @category Main
*/
-export function overlay_frac(
- frac: number,
- rune1: string,
- rune2: string
-): string {
+export function overlay_frac(frac: number, rune1: string, rune2: string): string {
throwIfNotRune(overlay_frac.name, rune1);
throwIfNotRune(overlay_frac.name, rune2);
return `overlay_frac(${frac}, ${rune1}, ${rune2})`;
diff --git a/src/bundles/rune_in_words/index.ts b/src/bundles/rune_in_words/index.ts
index 676085565..1a65dffd4 100644
--- a/src/bundles/rune_in_words/index.ts
+++ b/src/bundles/rune_in_words/index.ts
@@ -45,8 +45,8 @@ export {
show,
square,
stack,
- stack_frac,
stackn,
+ stack_frac,
translate,
triangle,
turn_upside_down,
diff --git a/src/bundles/scrabble/index.ts b/src/bundles/scrabble/index.ts
index 2a64a284d..91d459a94 100644
--- a/src/bundles/scrabble/index.ts
+++ b/src/bundles/scrabble/index.ts
@@ -3,8 +3,8 @@
* @author Martin Henz
*/
export {
- scrabble_letters,
- scrabble_letters_tiny,
scrabble_words,
- scrabble_words_tiny
+ scrabble_letters,
+ scrabble_words_tiny,
+ scrabble_letters_tiny
} from './functions';
diff --git a/src/bundles/sound/__tests__/sound.test.ts b/src/bundles/sound/__tests__/sound.test.ts
index bca8d232a..b304adc13 100644
--- a/src/bundles/sound/__tests__/sound.test.ts
+++ b/src/bundles/sound/__tests__/sound.test.ts
@@ -2,9 +2,8 @@ import { make_sound, play, play_in_tab } from '../functions';
describe('Test make_sound', () => {
test('Should error gracefully when duration is negative', () => {
- expect(() => make_sound(() => 0, -1)).toThrowErrorMatchingInlineSnapshot(
- '"Sound duration must be greater than or equal to 0"'
- );
+ expect(() => make_sound(() => 0, -1))
+ .toThrowErrorMatchingInlineSnapshot('"Sound duration must be greater than or equal to 0"');
});
test('Should not error when duration is zero', () => {
@@ -14,28 +13,26 @@ describe('Test make_sound', () => {
describe('Test play', () => {
test('Should error gracefully when duration is negative', () => {
- const sound = [t => 0, -1];
- expect(() => play(sound as any)).toThrowErrorMatchingInlineSnapshot(
- '"play: duration of sound is negative"'
- );
+ const sound = [(t) => 0, -1];
+ expect(() => play(sound as any))
+ .toThrowErrorMatchingInlineSnapshot('"play: duration of sound is negative"');
});
test('Should not error when duration is zero', () => {
- const sound = make_sound(t => 0, 0);
+ const sound = make_sound((t) => 0, 0);
expect(() => play(sound)).not.toThrow();
});
});
describe('Test play_in_tab', () => {
test('Should error gracefully when duration is negative', () => {
- const sound = [t => 0, -1];
- expect(() => play_in_tab(sound as any)).toThrowErrorMatchingInlineSnapshot(
- '"play_in_tab: duration of sound is negative"'
- );
+ const sound = [(t) => 0, -1];
+ expect(() => play_in_tab(sound as any))
+ .toThrowErrorMatchingInlineSnapshot('"play_in_tab: duration of sound is negative"');
});
test('Should not error when duration is zero', () => {
- const sound = make_sound(t => 0, 0);
+ const sound = make_sound((t) => 0, 0);
expect(() => play_in_tab(sound)).not.toThrow();
});
});
diff --git a/src/bundles/sound/index.ts b/src/bundles/sound/index.ts
index c593ec447..cdb273294 100644
--- a/src/bundles/sound/index.ts
+++ b/src/bundles/sound/index.ts
@@ -45,9 +45,9 @@ export {
noise_sound,
phase_mod,
piano,
- play,
// Play-related
play_in_tab,
+ play,
play_wave,
record,
record_for,
diff --git a/src/bundles/sound_matrix/index.ts b/src/bundles/sound_matrix/index.ts
index 95bc3e522..ad42ec791 100644
--- a/src/bundles/sound_matrix/index.ts
+++ b/src/bundles/sound_matrix/index.ts
@@ -8,8 +8,8 @@
export {
// Constructor/Accessors/Typecheck
ToneMatrix,
- clear_all_timeout,
- clear_matrix,
get_matrix,
- set_timeout
+ clear_matrix,
+ set_timeout,
+ clear_all_timeout
} from './functions';
diff --git a/src/bundles/stereo_sound/index.ts b/src/bundles/stereo_sound/index.ts
index 1d63940e7..6633c5a90 100644
--- a/src/bundles/stereo_sound/index.ts
+++ b/src/bundles/stereo_sound/index.ts
@@ -13,47 +13,47 @@
* @author Samyukta Sounderraman
*/
export {
- adsr,
- // Instruments
- bell,
- cello,
- // Composition and Envelopes
- consecutively,
- get_duration,
+ // Constructor/Accessors/Typecheck
+ make_stereo_sound,
+ make_sound,
get_left_wave,
get_right_wave,
- // Recording
- init_record,
+ get_duration,
is_sound,
- letter_name_to_frequency,
- // MIDI
- letter_name_to_midi_note,
- make_sound,
- // Constructor/Accessors/Typecheck
- make_stereo_sound,
- midi_note_to_frequency,
- // Basic waveforms
- noise_sound,
+ squash,
pan,
pan_mod,
- phase_mod,
- piano,
- play,
// Play-related
play_in_tab,
play_wave,
play_waves,
+ play,
+ stop,
+ // Recording
+ init_record,
record,
record_for,
- sawtooth_sound,
- silence_sound,
+ // Composition and Envelopes
+ consecutively,
simultaneously,
- sine_sound,
- square_sound,
- squash,
+ phase_mod,
+ adsr,
stacking_adsr,
- stop,
+ // Basic waveforms
+ noise_sound,
+ silence_sound,
+ sine_sound,
+ sawtooth_sound,
triangle_sound,
+ square_sound,
+ // MIDI
+ letter_name_to_midi_note,
+ midi_note_to_frequency,
+ letter_name_to_frequency,
+ // Instruments
+ bell,
+ cello,
+ piano,
trombone,
violin
} from './functions';
diff --git a/src/bundles/wasm/index.ts b/src/bundles/wasm/index.ts
index 6051362ed..c7e8cf577 100644
--- a/src/bundles/wasm/index.ts
+++ b/src/bundles/wasm/index.ts
@@ -81,4 +81,7 @@
* @module wasm
* @author Kim Yongbeom
*/
-export { wcompile, wrun } from './wabt';
+export {
+ wcompile,
+ wrun
+} from './wabt';
From 1af78407a4be6ed346fcbb13d90c755fe23a3f04 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Fri, 12 Apr 2024 06:27:31 +0800
Subject: [PATCH 17/39] Reformat sound.test.ts
---
src/bundles/sound/__tests__/sound.test.ts | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/src/bundles/sound/__tests__/sound.test.ts b/src/bundles/sound/__tests__/sound.test.ts
index b304adc13..9879bcadf 100644
--- a/src/bundles/sound/__tests__/sound.test.ts
+++ b/src/bundles/sound/__tests__/sound.test.ts
@@ -13,26 +13,26 @@ describe('Test make_sound', () => {
describe('Test play', () => {
test('Should error gracefully when duration is negative', () => {
- const sound = [(t) => 0, -1];
+ const sound = [() => 0, -1];
expect(() => play(sound as any))
.toThrowErrorMatchingInlineSnapshot('"play: duration of sound is negative"');
});
test('Should not error when duration is zero', () => {
- const sound = make_sound((t) => 0, 0);
+ const sound = make_sound(() => 0, 0);
expect(() => play(sound)).not.toThrow();
});
});
describe('Test play_in_tab', () => {
test('Should error gracefully when duration is negative', () => {
- const sound = [(t) => 0, -1];
+ const sound = [() => 0, -1];
expect(() => play_in_tab(sound as any))
.toThrowErrorMatchingInlineSnapshot('"play_in_tab: duration of sound is negative"');
});
test('Should not error when duration is zero', () => {
- const sound = make_sound((t) => 0, 0);
+ const sound = make_sound(() => 0, 0);
expect(() => play_in_tab(sound)).not.toThrow();
});
});
From a2caec5f07759f4cd745deea29439f761e3e0c27 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Fri, 12 Apr 2024 06:33:43 +0800
Subject: [PATCH 18/39] Revert some changes in bundles
---
src/bundles/csg/functions.ts | 21 ++---
src/bundles/csg/jscad/renderer.ts | 10 +--
src/bundles/curve/curves_webgl.ts | 9 +-
src/bundles/curve/functions.ts | 13 +--
src/bundles/game/types.ts | 9 +-
src/bundles/mark_sweep/types.ts | 2 +-
src/bundles/painter/functions.ts | 2 +-
src/bundles/pix_n_flix/functions.ts | 37 ++++----
src/bundles/plotly/functions.ts | 4 +-
src/bundles/plotly/plotly.ts | 3 +-
src/bundles/plotly/sound_functions.ts | 6 +-
src/bundles/rune/display.ts | 8 +-
src/bundles/rune/functions.ts | 33 ++++---
src/bundles/sound/riffwave.ts | 4 +-
src/bundles/sound_matrix/list.ts | 18 ++--
src/bundles/unity_academy/config.ts | 3 +-
src/bundles/unity_academy/index.ts | 118 +++++++++++++-------------
17 files changed, 139 insertions(+), 161 deletions(-)
diff --git a/src/bundles/csg/functions.ts b/src/bundles/csg/functions.ts
index 9bf0dc141..3c96f4144 100644
--- a/src/bundles/csg/functions.ts
+++ b/src/bundles/csg/functions.ts
@@ -1,6 +1,7 @@
/* [Imports] */
import { primitives } from '@jscad/modeling';
import { colorize as colorSolid } from '@jscad/modeling/src/colors';
+import { geom3 } from '@jscad/modeling/src/geometries';
import {
measureBoundingBox,
type BoundingBox
@@ -14,10 +15,10 @@ import { extrudeLinear } from '@jscad/modeling/src/operations/extrusions';
import { serialize } from '@jscad/stl-serializer';
import {
head,
- is_list,
list,
tail,
- type List
+ type List,
+ is_list
} from 'js-slang/dist/stdlib/list';
import save from 'save-file';
import { degreesToRadians } from '../../common/utilities';
@@ -26,10 +27,10 @@ import type { Solid } from './jscad/types';
import {
Group,
Shape,
- centerPrimitive,
hexToColor,
type Operable,
- type RenderGroup
+ type RenderGroup,
+ centerPrimitive
} from './utilities';
/* [Main] */
@@ -663,12 +664,12 @@ export function rgb(
blueValue: number
): string {
if (
- redValue < 0 ||
- redValue > 255 ||
- greenValue < 0 ||
- greenValue > 255 ||
- blueValue < 0 ||
- blueValue > 255
+ redValue < 0
+ || redValue > 255
+ || greenValue < 0
+ || greenValue > 255
+ || blueValue < 0
+ || blueValue > 255
) {
throw new Error('RGB values must be between 0 and 255 (inclusive)');
}
diff --git a/src/bundles/csg/jscad/renderer.ts b/src/bundles/csg/jscad/renderer.ts
index 6699838c3..2df90d28d 100644
--- a/src/bundles/csg/jscad/renderer.ts
+++ b/src/bundles/csg/jscad/renderer.ts
@@ -7,11 +7,7 @@ import {
entitiesFromSolids,
prepareRender
} from '@jscad/regl-renderer';
-import {
- ACE_GUTTER_BACKGROUND_COLOR,
- ACE_GUTTER_TEXT_COLOR,
- BP_TEXT_COLOR
-} from '../../../tabs/common/css_constants';
+import { ACE_GUTTER_BACKGROUND_COLOR, ACE_GUTTER_TEXT_COLOR, BP_TEXT_COLOR } from '../../../tabs/common/css_constants';
import {
DEFAULT_COLOR,
GRID_PADDING,
@@ -54,8 +50,8 @@ function solidsToGeometryEntities(solids: Solid[]): GeometryEntity[] {
function neatGridDistance(rawDistance: number) {
const paddedDistance: number = rawDistance + GRID_PADDING;
- const roundedDistance: number =
- Math.ceil(paddedDistance / ROUND_UP_INTERVAL) * ROUND_UP_INTERVAL;
+ const roundedDistance: number
+ = Math.ceil(paddedDistance / ROUND_UP_INTERVAL) * ROUND_UP_INTERVAL;
return roundedDistance;
}
diff --git a/src/bundles/curve/curves_webgl.ts b/src/bundles/curve/curves_webgl.ts
index 49609fd85..ca81f9d0e 100644
--- a/src/bundles/curve/curves_webgl.ts
+++ b/src/bundles/curve/curves_webgl.ts
@@ -123,8 +123,7 @@ export class Point implements ReplResult {
public readonly color: Color
) {}
- public toReplString = () =>
- `(${this.x}, ${this.y}, ${this.z}, Color: ${this.color})`;
+ public toReplString = () => `(${this.x}, ${this.y}, ${this.z}, Color: ${this.color})`;
}
/**
@@ -339,11 +338,7 @@ export function generateCurve(
const point = func(i / numPoints);
if (!(point instanceof Point)) {
- throw new Error(
- `Expected curve to return a point, got '${stringify(point)}' at t=${
- i / numPoints
- }`
- );
+ throw new Error(`Expected curve to return a point, got '${stringify(point)}' at t=${i / numPoints}`);
}
const x = point.x * 2 - 1;
diff --git a/src/bundles/curve/functions.ts b/src/bundles/curve/functions.ts
index 8267353a1..b665169ab 100644
--- a/src/bundles/curve/functions.ts
+++ b/src/bundles/curve/functions.ts
@@ -1,11 +1,6 @@
/* eslint-disable @typescript-eslint/naming-convention */
import context from 'js-slang/context';
-import {
- Point,
- generateCurve,
- type Curve,
- type CurveDrawn
-} from './curves_webgl';
+import { type Curve, type CurveDrawn, generateCurve, Point } from './curves_webgl';
import {
AnimatedCurve,
type CurveAnimation,
@@ -542,9 +537,9 @@ export function rotate_around_origin(
// 2 args
throw new Error('Expected 1 or 3 arguments, but received 2');
} else if (
- theta1 !== undefined &&
- theta2 === undefined &&
- theta3 === undefined
+ theta1 !== undefined
+ && theta2 === undefined
+ && theta3 === undefined
) {
// 1 args
const cth = Math.cos(theta1);
diff --git a/src/bundles/game/types.ts b/src/bundles/game/types.ts
index 3780fe911..f912e7658 100644
--- a/src/bundles/game/types.ts
+++ b/src/bundles/game/types.ts
@@ -39,8 +39,7 @@ export type GameParams = {
createAward: (x: number, y: number, key: string) => Phaser.GameObjects.Sprite;
};
-export const sourceAcademyAssets =
- 'https://source-academy-assets.s3-ap-southeast-1.amazonaws.com';
+export const sourceAcademyAssets = 'https://source-academy-assets.s3-ap-southeast-1.amazonaws.com';
// Scene needs to be set when available!
export const defaultGameParams: GameParams = {
@@ -54,12 +53,10 @@ export const defaultGameParams: GameParams = {
update() {}
},
renderPreview: false,
- remotePath: (path: string) =>
- sourceAcademyAssets + (path[0] === '/' ? '' : '/') + path,
+ remotePath: (path: string) => sourceAcademyAssets + (path[0] === '/' ? '' : '/') + path,
screenSize: {
x: 1920,
y: 1080
},
- createAward: (x: number, y: number, key: string) =>
- new Phaser.GameObjects.Sprite(defaultGameParams.scene!, x, y, key)
+ createAward: (x: number, y: number, key: string) => new Phaser.GameObjects.Sprite(defaultGameParams.scene!, x, y, key)
};
diff --git a/src/bundles/mark_sweep/types.ts b/src/bundles/mark_sweep/types.ts
index 7c5bcf36e..56c71389d 100644
--- a/src/bundles/mark_sweep/types.ts
+++ b/src/bundles/mark_sweep/types.ts
@@ -15,7 +15,7 @@ export enum COMMAND {
SHOW_MARKED = 'Marked Roots',
MARK = 'Mark',
SWEEP = 'Sweep',
- INIT = 'Initialize Memory'
+ INIT = 'Initialize Memory',
}
export type CommandHeapObject = {
diff --git a/src/bundles/painter/functions.ts b/src/bundles/painter/functions.ts
index 2d61f5ba1..da8059a19 100644
--- a/src/bundles/painter/functions.ts
+++ b/src/bundles/painter/functions.ts
@@ -1,6 +1,6 @@
import context from 'js-slang/context';
import Plotly, { type Data, type Layout } from 'plotly.js-dist';
-import { LinePlot, type Frame } from './painter';
+import { type Frame, LinePlot } from './painter';
const drawnPainters: LinePlot[] = [];
context.moduleContexts.painter.state = {
diff --git a/src/bundles/pix_n_flix/functions.ts b/src/bundles/pix_n_flix/functions.ts
index c8e44bfcc..285027d60 100644
--- a/src/bundles/pix_n_flix/functions.ts
+++ b/src/bundles/pix_n_flix/functions.ts
@@ -1,30 +1,30 @@
/* eslint-disable @typescript-eslint/no-shadow */
import {
- DEFAULT_FPS,
+ DEFAULT_WIDTH,
DEFAULT_HEIGHT,
- DEFAULT_LOOP,
+ DEFAULT_FPS,
DEFAULT_VOLUME,
- DEFAULT_WIDTH,
- MAX_FPS,
MAX_HEIGHT,
+ MIN_HEIGHT,
MAX_WIDTH,
+ MIN_WIDTH,
+ MAX_FPS,
MIN_FPS,
- MIN_HEIGHT,
- MIN_WIDTH
+ DEFAULT_LOOP
} from './constants';
import {
- InputFeed,
- type BundlePacket,
type CanvasElement,
+ type VideoElement,
type ErrorLogger,
- type Filter,
- type ImageElement,
+ type StartPacket,
type Pixel,
type Pixels,
+ type Filter,
type Queue,
- type StartPacket,
type TabsPacket,
- type VideoElement
+ type BundlePacket,
+ InputFeed,
+ type ImageElement
} from './types';
// Global Variables
@@ -110,8 +110,8 @@ function writeToBuffer(buffer: Uint8ClampedArray, data: Pixels) {
}
if (!ok) {
- const warningMessage =
- 'You have invalid values for some pixels! Reseting them to default (0)';
+ const warningMessage
+ = 'You have invalid values for some pixels! Reseting them to default (0)';
console.warn(warningMessage);
errorLogger(warningMessage, false);
}
@@ -265,11 +265,10 @@ function loadMedia(): void {
.getUserMedia({ video: true })
.then(stream => {
videoElement.srcObject = stream;
- videoElement.onloadedmetadata = () =>
- setAspectRatioDimensions(
- videoElement.videoWidth,
- videoElement.videoHeight
- );
+ videoElement.onloadedmetadata = () => setAspectRatioDimensions(
+ videoElement.videoWidth,
+ videoElement.videoHeight
+ );
toRunLateQueue = true;
})
.catch(error => {
diff --git a/src/bundles/plotly/functions.ts b/src/bundles/plotly/functions.ts
index 96421fa00..130c4e097 100644
--- a/src/bundles/plotly/functions.ts
+++ b/src/bundles/plotly/functions.ts
@@ -8,10 +8,10 @@ import Plotly, { type Data, type Layout } from 'plotly.js-dist';
import { type Sound } from '../sound/types';
import { generatePlot } from './curve_functions';
import {
- CurvePlot,
- DrawnPlot,
type Curve,
+ CurvePlot,
type CurvePlotFunction,
+ DrawnPlot,
type ListOfPairs
} from './plotly';
import { get_duration, get_wave, is_sound } from './sound_functions';
diff --git a/src/bundles/plotly/plotly.ts b/src/bundles/plotly/plotly.ts
index 7958c96bc..ac76551ea 100644
--- a/src/bundles/plotly/plotly.ts
+++ b/src/bundles/plotly/plotly.ts
@@ -55,8 +55,7 @@ export class Point implements ReplResult {
public readonly color: Color
) {}
- public toReplString = () =>
- `(${this.x}, ${this.y}, ${this.z}, Color: ${this.color})`;
+ public toReplString = () => `(${this.x}, ${this.y}, ${this.z}, Color: ${this.color})`;
}
export type Wave = (...t: any) => number;
diff --git a/src/bundles/plotly/sound_functions.ts b/src/bundles/plotly/sound_functions.ts
index 6dc5dbaa3..b0fe55018 100644
--- a/src/bundles/plotly/sound_functions.ts
+++ b/src/bundles/plotly/sound_functions.ts
@@ -1,4 +1,8 @@
-import { head, is_pair, tail } from 'js-slang/dist/stdlib/list';
+import {
+ head,
+ tail,
+ is_pair
+} from 'js-slang/dist/stdlib/list';
import { type Sound, type Wave } from '../sound/types';
export function is_sound(x: any): x is Sound {
return (
diff --git a/src/bundles/rune/display.ts b/src/bundles/rune/display.ts
index 32a392771..2eabb95c7 100644
--- a/src/bundles/rune/display.ts
+++ b/src/bundles/rune/display.ts
@@ -1,12 +1,6 @@
import context from 'js-slang/context';
import { AnaglyphRune, HollusionRune } from './functions';
-import {
- AnimatedRune,
- NormalRune,
- type DrawnRune,
- type Rune,
- type RuneAnimation
-} from './rune';
+import { type DrawnRune, AnimatedRune, type Rune, NormalRune, type RuneAnimation } from './rune';
import { throwIfNotRune } from './runes_ops';
// =============================================================================
diff --git a/src/bundles/rune/functions.ts b/src/bundles/rune/functions.ts
index 83ba1a692..df25bc519 100644
--- a/src/bundles/rune/functions.ts
+++ b/src/bundles/rune/functions.ts
@@ -1,32 +1,32 @@
import { mat4, vec3 } from 'gl-matrix';
import {
- DrawnRune,
Rune,
+ DrawnRune,
drawRunesToFrameBuffer,
type AnimatedRune
} from './rune';
import {
- addColorFromHex,
- colorPalette,
+ getSquare,
getBlank,
- getCircle,
+ getRcross,
+ getSail,
+ getTriangle,
getCorner,
- getHeart,
getNova,
+ getCircle,
+ getHeart,
getPentagram,
- getRcross,
getRibbon,
- getSail,
- getSquare,
- getTriangle,
- hexToColor,
- throwIfNotRune
+ throwIfNotRune,
+ addColorFromHex,
+ colorPalette,
+ hexToColor
} from './runes_ops';
import {
+ type FrameBufferWithTexture,
getWebGlFromCanvas,
initFramebufferObject,
- initShaderProgram,
- type FrameBufferWithTexture
+ initShaderProgram
} from './runes_webgl';
export type RuneModuleState = {
@@ -892,8 +892,8 @@ export class HollusionRune extends DrawnRune {
lastTime = timeInMs;
- const framePos =
- Math.floor(timeInMs / (period / frameCount)) % frameCount;
+ const framePos
+ = Math.floor(timeInMs / (period / frameCount)) % frameCount;
const fbObject = frameBuffer[framePos];
gl.clearColor(1.0, 1.0, 1.0, 1.0); // Set clear color to white, fully opaque
// eslint-disable-next-line no-bitwise
@@ -911,5 +911,4 @@ export class HollusionRune extends DrawnRune {
}
/** @hidden */
-export const isHollusionRune = (rune: DrawnRune): rune is HollusionRune =>
- rune.isHollusion;
+export const isHollusionRune = (rune: DrawnRune): rune is HollusionRune => rune.isHollusion;
diff --git a/src/bundles/sound/riffwave.ts b/src/bundles/sound/riffwave.ts
index 915c9d677..70a1af751 100644
--- a/src/bundles/sound/riffwave.ts
+++ b/src/bundles/sound/riffwave.ts
@@ -54,7 +54,7 @@ var FastBase64 = {
dst += '=';
}
return dst;
- } // end Encode
+ }, // end Encode
};
FastBase64.Init();
@@ -78,7 +78,7 @@ export function RIFFWAVE(this: any, data) {
blockAlign: 0, // 32 2 NumChannels*BitsPerSample/8
bitsPerSample: 8, // 34 2 8 bits = 8, 16 bits = 16
subChunk2Id: [0x64, 0x61, 0x74, 0x61], // 36 4 "data" = 0x64617461
- subChunk2Size: 0 // 40 4 data size = NumSamples*NumChannels*BitsPerSample/8
+ subChunk2Size: 0, // 40 4 data size = NumSamples*NumChannels*BitsPerSample/8
};
function u32ToArray(i) {
diff --git a/src/bundles/sound_matrix/list.ts b/src/bundles/sound_matrix/list.ts
index 4b0c22596..461fd31b9 100644
--- a/src/bundles/sound_matrix/list.ts
+++ b/src/bundles/sound_matrix/list.ts
@@ -142,9 +142,9 @@ export function map(f, xs) {
export function build_list(n, fun) {
if (typeof n !== 'number' || n < 0 || Math.floor(n) !== n) {
throw new Error(
- 'build_list(n, fun) expects a positive integer as ' +
- 'argument n, but encountered ' +
- n
+ 'build_list(n, fun) expects a positive integer as '
+ + 'argument n, but encountered '
+ + n
);
}
@@ -296,14 +296,14 @@ export function filter(pred, xs) {
export function enum_list(start, end) {
if (typeof start !== 'number') {
throw new Error(
- 'enum_list(start, end) expects a number as argument start, but encountered ' +
- start
+ 'enum_list(start, end) expects a number as argument start, but encountered '
+ + start
);
}
if (typeof end !== 'number') {
throw new Error(
- 'enum_list(start, end) expects a number as argument start, but encountered ' +
- end
+ 'enum_list(start, end) expects a number as argument start, but encountered '
+ + end
);
}
if (start > end) {
@@ -317,8 +317,8 @@ export function enum_list(start, end) {
export function list_ref(xs, n) {
if (typeof n !== 'number' || n < 0 || Math.floor(n) !== n) {
throw new Error(
- 'list_ref(xs, n) expects a positive integer as argument n, but encountered ' +
- n
+ 'list_ref(xs, n) expects a positive integer as argument n, but encountered '
+ + n
);
}
for (; n > 0; --n) {
diff --git a/src/bundles/unity_academy/config.ts b/src/bundles/unity_academy/config.ts
index 0cbaca37d..12e4a2a2b 100644
--- a/src/bundles/unity_academy/config.ts
+++ b/src/bundles/unity_academy/config.ts
@@ -1,3 +1,2 @@
-export const UNITY_ACADEMY_BACKEND_URL =
- 'https://unity-academy.s3.ap-southeast-1.amazonaws.com/';
+export const UNITY_ACADEMY_BACKEND_URL = 'https://unity-academy.s3.ap-southeast-1.amazonaws.com/';
export const BUILD_NAME = 'ua-frontend-prod';
diff --git a/src/bundles/unity_academy/index.ts b/src/bundles/unity_academy/index.ts
index 0c403919e..c10c51e05 100644
--- a/src/bundles/unity_academy/index.ts
+++ b/src/bundles/unity_academy/index.ts
@@ -91,13 +91,68 @@
*/
export {
- add_impulse_force,
- add_vectors,
- apply_rigidbody,
+ init_unity_academy_2d,
+ init_unity_academy_3d,
+ same_gameobject,
+ set_start,
+ set_update,
+ instantiate,
+ instantiate_sprite,
+ instantiate_empty,
+ destroy,
+ delta_time,
+ get_position,
+ set_position,
+ get_rotation_euler,
+ set_rotation_euler,
+ get_scale,
+ set_scale,
+ translate_world,
+ translate_local,
+ rotate_world,
copy_position,
copy_rotation,
copy_scale,
+ look_at,
+ gameobject_distance,
+ get_key_down,
+ get_key,
+ get_key_up,
+ play_animator_state,
+ apply_rigidbody,
+ get_mass,
+ set_mass,
+ set_drag,
+ set_angular_drag,
+ get_velocity,
+ set_velocity,
+ get_angular_velocity,
+ set_angular_velocity,
+ add_impulse_force,
+ set_use_gravity,
+ remove_collider_components,
+ on_collision_enter,
+ on_collision_stay,
+ on_collision_exit,
+ gui_label,
+ gui_button,
+ get_main_camera_following_target,
+ request_for_main_camera_control,
+ set_custom_prop,
+ get_custom_prop,
+ vector3,
+ get_x,
+ get_y,
+ get_z,
+ scale_vector,
+ add_vectors,
+ vector_difference,
+ dot,
cross,
+ normalize,
+ magnitude,
+ zero_vector,
+ point_distance,
/* I will uncomment these audio functions when I totally finish audio support.
load_audio_clip_mp3,
load_audio_clip_ogg,
@@ -117,61 +172,6 @@ export {
play_audio_clip_3d_sound,
*/
debug_log,
- debug_logerror,
debug_logwarning,
- delta_time,
- destroy,
- dot,
- gameobject_distance,
- get_angular_velocity,
- get_custom_prop,
- get_key,
- get_key_down,
- get_key_up,
- get_main_camera_following_target,
- get_mass,
- get_position,
- get_rotation_euler,
- get_scale,
- get_velocity,
- get_x,
- get_y,
- get_z,
- gui_button,
- gui_label,
- init_unity_academy_2d,
- init_unity_academy_3d,
- instantiate,
- instantiate_empty,
- instantiate_sprite,
- look_at,
- magnitude,
- normalize,
- on_collision_enter,
- on_collision_exit,
- on_collision_stay,
- play_animator_state,
- point_distance,
- remove_collider_components,
- request_for_main_camera_control,
- rotate_world,
- same_gameobject,
- scale_vector,
- set_angular_drag,
- set_angular_velocity,
- set_custom_prop,
- set_drag,
- set_mass,
- set_position,
- set_rotation_euler,
- set_scale,
- set_start,
- set_update,
- set_use_gravity,
- set_velocity,
- translate_local,
- translate_world,
- vector3,
- vector_difference,
- zero_vector
+ debug_logerror
} from './functions';
From 63ed6ac4ed30e082d8334bafb45c0802aeb7ab91 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Fri, 12 Apr 2024 06:37:40 +0800
Subject: [PATCH 19/39] Downgrade unused disable directives severity
---
eslint.config.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/eslint.config.js b/eslint.config.js
index 799ed359c..fad4994f5 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -65,7 +65,7 @@ export default [
],
},
linterOptions: {
- reportUnusedDisableDirectives: 'error'
+ reportUnusedDisableDirectives: 'warn'
}
},
...tseslint.configs.recommended,
From 393d09566ea19d3c5075f5179e97a705839beddc Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Fri, 12 Apr 2024 06:47:54 +0800
Subject: [PATCH 20/39] Revert some changes in bundles
---
src/bundles/arcade_2d/functions.ts | 248 ++++++------------
src/bundles/arcade_2d/phaserScene.ts | 80 ++----
src/bundles/binary_tree/functions.ts | 55 ++--
src/bundles/communication/Communications.ts | 12 +-
.../communication/GlobalStateController.ts | 6 +-
src/bundles/communication/MqttController.ts | 6 +-
.../communication/MultiUserController.ts | 6 +-
src/bundles/communication/RpcController.ts | 10 +-
src/bundles/game/functions.ts | 57 ++--
src/bundles/physics_2d/PhysicsObject.ts | 16 +-
src/bundles/physics_2d/PhysicsWorld.ts | 21 +-
src/bundles/physics_2d/functions.ts | 2 +-
src/bundles/repl/functions.ts | 15 +-
src/bundles/sound/functions.ts | 60 ++---
src/bundles/stereo_sound/functions.ts | 94 +++----
src/bundles/stereo_sound/riffwave.ts | 4 +-
16 files changed, 264 insertions(+), 428 deletions(-)
diff --git a/src/bundles/arcade_2d/functions.ts b/src/bundles/arcade_2d/functions.ts
index a76acd0bf..85ac7c094 100644
--- a/src/bundles/arcade_2d/functions.ts
+++ b/src/bundles/arcade_2d/functions.ts
@@ -11,50 +11,52 @@
import { AudioClip } from './audio';
import {
- DEFAULT_DEBUG_STATE,
- DEFAULT_FPS,
+ DEFAULT_WIDTH,
DEFAULT_HEIGHT,
- DEFAULT_INTERACTABLE_PROPS,
- DEFAULT_RENDER_PROPS,
DEFAULT_SCALE,
- DEFAULT_TRANSFORM_PROPS,
- DEFAULT_WIDTH,
- MAX_FPS,
+ DEFAULT_FPS,
MAX_HEIGHT,
- MAX_SCALE,
- MAX_VOLUME,
- MAX_WIDTH,
- MIN_FPS,
MIN_HEIGHT,
+ MAX_WIDTH,
+ MIN_WIDTH,
+ MAX_SCALE,
MIN_SCALE,
+ MAX_FPS,
+ MIN_FPS,
+ MAX_VOLUME,
MIN_VOLUME,
- MIN_WIDTH
+ DEFAULT_DEBUG_STATE,
+ DEFAULT_TRANSFORM_PROPS,
+ DEFAULT_RENDER_PROPS,
+ DEFAULT_INTERACTABLE_PROPS
} from './constants';
import {
- CircleGameObject,
GameObject,
- InteractableGameObject,
- RectangleGameObject,
RenderableGameObject,
+ type ShapeGameObject,
SpriteGameObject,
TextGameObject,
- TriangleGameObject,
- type ShapeGameObject
+ RectangleGameObject,
+ CircleGameObject,
+ TriangleGameObject, InteractableGameObject
} from './gameobject';
-import { PhaserScene, gameState } from './phaserScene';
import {
+ PhaserScene,
+ gameState
+} from './phaserScene';
+import {
+ type DisplayText,
type BuildGame,
+ type Sprite,
+ type UpdateFunction,
+ type RectangleProps,
type CircleProps,
- type ColorRGBA,
- type DimensionsXY,
- type DisplayText,
+ type TriangleProps,
type FlipXY,
- type PositionXY,
- type RectangleProps,
type ScaleXY,
- type Sprite,
- type TriangleProps,
- type UpdateFunction
+ type PositionXY,
+ type DimensionsXY,
+ type ColorRGBA
} from './types';
// =============================================================================
@@ -87,20 +89,12 @@ export const config = {
* ```
* @category GameObject
*/
-export const create_rectangle: (
- width: number,
- height: number
-) => ShapeGameObject = (width: number, height: number) => {
+export const create_rectangle: (width: number, height: number) => ShapeGameObject = (width: number, height: number) => {
const rectangle = {
width,
height
} as RectangleProps;
- return new RectangleGameObject(
- DEFAULT_TRANSFORM_PROPS,
- DEFAULT_RENDER_PROPS,
- DEFAULT_INTERACTABLE_PROPS,
- rectangle
- );
+ return new RectangleGameObject(DEFAULT_TRANSFORM_PROPS, DEFAULT_RENDER_PROPS, DEFAULT_INTERACTABLE_PROPS, rectangle);
};
/**
@@ -113,18 +107,11 @@ export const create_rectangle: (
* ```
* @category GameObject
*/
-export const create_circle: (radius: number) => ShapeGameObject = (
- radius: number
-) => {
+export const create_circle: (radius: number) => ShapeGameObject = (radius: number) => {
const circle = {
radius
} as CircleProps;
- return new CircleGameObject(
- DEFAULT_TRANSFORM_PROPS,
- DEFAULT_RENDER_PROPS,
- DEFAULT_INTERACTABLE_PROPS,
- circle
- );
+ return new CircleGameObject(DEFAULT_TRANSFORM_PROPS, DEFAULT_RENDER_PROPS, DEFAULT_INTERACTABLE_PROPS, circle);
};
/**
@@ -137,10 +124,7 @@ export const create_circle: (radius: number) => ShapeGameObject = (
* ```
* @category GameObject
*/
-export const create_triangle: (
- width: number,
- height: number
-) => ShapeGameObject = (width: number, height: number) => {
+export const create_triangle: (width: number, height: number) => ShapeGameObject = (width: number, height: number) => {
const triangle = {
x1: 0,
y1: 0,
@@ -149,12 +133,7 @@ export const create_triangle: (
x3: width / 2,
y3: height
} as TriangleProps;
- return new TriangleGameObject(
- DEFAULT_TRANSFORM_PROPS,
- DEFAULT_RENDER_PROPS,
- DEFAULT_INTERACTABLE_PROPS,
- triangle
- );
+ return new TriangleGameObject(DEFAULT_TRANSFORM_PROPS, DEFAULT_RENDER_PROPS, DEFAULT_INTERACTABLE_PROPS, triangle);
};
/**
@@ -171,12 +150,7 @@ export const create_text: (text: string) => TextGameObject = (text: string) => {
const displayText = {
text
} as DisplayText;
- return new TextGameObject(
- DEFAULT_TRANSFORM_PROPS,
- DEFAULT_RENDER_PROPS,
- DEFAULT_INTERACTABLE_PROPS,
- displayText
- );
+ return new TextGameObject(DEFAULT_TRANSFORM_PROPS, DEFAULT_RENDER_PROPS, DEFAULT_INTERACTABLE_PROPS, displayText);
};
/**
@@ -196,9 +170,7 @@ export const create_text: (text: string) => TextGameObject = (text: string) => {
* ```
* @category GameObject
*/
-export const create_sprite: (image_url: string) => SpriteGameObject = (
- image_url: string
-) => {
+export const create_sprite: (image_url: string) => SpriteGameObject = (image_url: string) => {
if (image_url === '') {
throw new Error('image_url cannot be empty');
}
@@ -208,12 +180,7 @@ export const create_sprite: (image_url: string) => SpriteGameObject = (
const sprite: Sprite = {
imageUrl: image_url
} as Sprite;
- return new SpriteGameObject(
- DEFAULT_TRANSFORM_PROPS,
- DEFAULT_RENDER_PROPS,
- DEFAULT_INTERACTABLE_PROPS,
- sprite
- );
+ return new SpriteGameObject(DEFAULT_TRANSFORM_PROPS, DEFAULT_RENDER_PROPS, DEFAULT_INTERACTABLE_PROPS, sprite);
};
// =============================================================================
@@ -232,10 +199,8 @@ export const create_sprite: (image_url: string) => SpriteGameObject = (
* ```
* @category GameObject
*/
-export const update_position: (
- gameObject: GameObject,
- [x, y]: PositionXY
-) => GameObject = (gameObject: GameObject, [x, y]: PositionXY) => {
+export const update_position: (gameObject: GameObject, [x, y]: PositionXY) => GameObject
+= (gameObject: GameObject, [x, y]: PositionXY) => {
if (gameObject instanceof GameObject) {
gameObject.setTransform({
...gameObject.getTransform(),
@@ -258,10 +223,8 @@ export const update_position: (
* ```
* @category GameObject
*/
-export const update_scale: (
- gameObject: GameObject,
- [x, y]: ScaleXY
-) => GameObject = (gameObject: GameObject, [x, y]: ScaleXY) => {
+export const update_scale: (gameObject: GameObject, [x, y]: ScaleXY) => GameObject
+= (gameObject: GameObject, [x, y]: ScaleXY) => {
if (gameObject instanceof GameObject) {
gameObject.setTransform({
...gameObject.getTransform(),
@@ -284,10 +247,8 @@ export const update_scale: (
* ```
* @category GameObject
*/
-export const update_rotation: (
- gameObject: GameObject,
- radians: number
-) => GameObject = (gameObject: GameObject, radians: number) => {
+export const update_rotation: (gameObject: GameObject, radians: number) => GameObject
+= (gameObject: GameObject, radians: number) => {
if (gameObject instanceof GameObject) {
gameObject.setTransform({
...gameObject.getTransform(),
@@ -311,10 +272,8 @@ export const update_rotation: (
* ```
* @category GameObject
*/
-export const update_color: (
- gameObject: GameObject,
- color: ColorRGBA
-) => GameObject = (gameObject: GameObject, color: ColorRGBA) => {
+export const update_color: (gameObject: GameObject, color: ColorRGBA) => GameObject
+= (gameObject: GameObject, color: ColorRGBA) => {
if (color.length !== 4) {
throw new Error('color must be a 4-element array');
}
@@ -340,10 +299,8 @@ export const update_color: (
* ```
* @category GameObject
*/
-export const update_flip: (
- gameObject: GameObject,
- flip: FlipXY
-) => GameObject = (gameObject: GameObject, flip: FlipXY) => {
+export const update_flip: (gameObject: GameObject, flip: FlipXY) => GameObject
+= (gameObject: GameObject, flip: FlipXY) => {
if (flip.length !== 2) {
throw new Error('flip must be a 2-element array');
}
@@ -370,10 +327,8 @@ export const update_flip: (
* ```
* @category GameObject
*/
-export const update_text: (
- textGameObject: TextGameObject,
- text: string
-) => GameObject = (textGameObject: TextGameObject, text: string) => {
+export const update_text: (textGameObject: TextGameObject, text: string) => GameObject
+= (textGameObject: TextGameObject, text: string) => {
if (textGameObject instanceof TextGameObject) {
textGameObject.setText({
text
@@ -393,9 +348,8 @@ export const update_text: (
* ```
* @category GameObject
*/
-export const update_to_top: (gameObject: GameObject) => GameObject = (
- gameObject: GameObject
-) => {
+export const update_to_top: (gameObject: GameObject) => GameObject
+= (gameObject: GameObject) => {
if (gameObject instanceof RenderableGameObject) {
gameObject.setBringToTopFlag();
return gameObject;
@@ -422,9 +376,7 @@ export const update_to_top: (gameObject: GameObject) => GameObject = (
* ```
* @category GameObject
*/
-export const query_id: (gameObject: GameObject) => number = (
- gameObject: GameObject
-) => {
+export const query_id: (gameObject: GameObject) => number = (gameObject: GameObject) => {
if (gameObject instanceof GameObject) {
return gameObject.id;
}
@@ -443,9 +395,8 @@ export const query_id: (gameObject: GameObject) => number = (
* ```
* @category GameObject
*/
-export const query_position: (gameObject: GameObject) => PositionXY = (
- gameObject: GameObject
-) => {
+export const query_position: (gameObject: GameObject) => PositionXY
+= (gameObject: GameObject) => {
if (gameObject instanceof GameObject) {
return [...gameObject.getTransform().position];
}
@@ -464,9 +415,8 @@ export const query_position: (gameObject: GameObject) => PositionXY = (
* ```
* @category GameObject
*/
-export const query_rotation: (gameObject: GameObject) => number = (
- gameObject: GameObject
-) => {
+export const query_rotation: (gameObject: GameObject) => number
+= (gameObject: GameObject) => {
if (gameObject instanceof GameObject) {
return gameObject.getTransform().rotation;
}
@@ -485,9 +435,8 @@ export const query_rotation: (gameObject: GameObject) => number = (
* ```
* @category GameObject
*/
-export const query_scale: (gameObject: GameObject) => ScaleXY = (
- gameObject: GameObject
-) => {
+export const query_scale: (gameObject: GameObject) => ScaleXY
+= (gameObject: GameObject) => {
if (gameObject instanceof GameObject) {
return [...gameObject.getTransform().scale];
}
@@ -506,9 +455,8 @@ export const query_scale: (gameObject: GameObject) => ScaleXY = (
* ```
* @category GameObject
*/
-export const query_color: (gameObject: RenderableGameObject) => ColorRGBA = (
- gameObject: RenderableGameObject
-) => {
+export const query_color: (gameObject: RenderableGameObject) => ColorRGBA
+= (gameObject: RenderableGameObject) => {
if (gameObject instanceof RenderableGameObject) {
return [...gameObject.getColor()];
}
@@ -527,9 +475,8 @@ export const query_color: (gameObject: RenderableGameObject) => ColorRGBA = (
* ```
* @category GameObject
*/
-export const query_flip: (gameObject: RenderableGameObject) => FlipXY = (
- gameObject: RenderableGameObject
-) => {
+export const query_flip: (gameObject: RenderableGameObject) => FlipXY
+= (gameObject: RenderableGameObject) => {
if (gameObject instanceof RenderableGameObject) {
return [...gameObject.getFlipState()];
}
@@ -549,9 +496,8 @@ export const query_flip: (gameObject: RenderableGameObject) => FlipXY = (
* ```
* @category GameObject
*/
-export const query_text: (textGameObject: TextGameObject) => string = (
- textGameObject: TextGameObject
-) => {
+export const query_text: (textGameObject: TextGameObject) => string
+= (textGameObject: TextGameObject) => {
if (textGameObject instanceof TextGameObject) {
return textGameObject.getText().text;
}
@@ -569,8 +515,8 @@ export const query_text: (textGameObject: TextGameObject) => string = (
* position[1]; // y
* ```
*/
-export const query_pointer_position: () => PositionXY = () =>
- gameState.pointerProps.pointerPosition;
+export const query_pointer_position: () => PositionXY
+= () => gameState.pointerProps.pointerPosition;
// =============================================================================
// Game configuration
@@ -585,11 +531,8 @@ export const query_pointer_position: () => PositionXY = () =>
* @returns a number within the interval
* @hidden
*/
-const withinRange: (num: number, min: number, max: number) => number = (
- num: number,
- min: number,
- max: number
-) => {
+const withinRange: (num: number, min: number, max: number) => number
+= (num: number, min: number, max: number) => {
if (num > max) {
return max;
}
@@ -626,9 +569,7 @@ export const set_fps: (fps: number) => void = (fps: number) => {
* set_dimensions([500, 400]);
* ```
*/
-export const set_dimensions: (dimensions: DimensionsXY) => void = (
- dimensions: DimensionsXY
-) => {
+export const set_dimensions: (dimensions: DimensionsXY) => void = (dimensions: DimensionsXY) => {
if (dimensions.length !== 2) {
throw new Error('dimensions must be a 2-element array');
}
@@ -710,9 +651,7 @@ export const debug_log: (info: string) => void = (info: string) => {
* ```
* @category Logic
*/
-export const input_key_down: (key_name: string) => boolean = (
- key_name: string
-) => gameState.inputKeysDown.has(key_name);
+export const input_key_down: (key_name: string) => boolean = (key_name: string) => gameState.inputKeysDown.has(key_name);
/**
* Detects if the left mouse button is pressed down.
@@ -727,8 +666,7 @@ export const input_key_down: (key_name: string) => boolean = (
* ```
* @category Logic
*/
-export const input_left_mouse_down: () => boolean = () =>
- gameState.pointerProps.isPointerPrimaryDown;
+export const input_left_mouse_down: () => boolean = () => gameState.pointerProps.isPointerPrimaryDown;
/**
* Detects if the right mouse button is pressed down.
@@ -743,8 +681,7 @@ export const input_left_mouse_down: () => boolean = () =>
* ```
* @category Logic
*/
-export const input_right_mouse_down: () => boolean = () =>
- gameState.pointerProps.isPointerSecondaryDown;
+export const input_right_mouse_down: () => boolean = () => gameState.pointerProps.isPointerSecondaryDown;
/**
* Detects if the (mouse) pointer is over the gameobject.
@@ -787,17 +724,9 @@ export const pointer_over_gameobject = (gameObject: GameObject) => {
* ```
* @category Logic
*/
-export const gameobjects_overlap: (
- gameObject1: InteractableGameObject,
- gameObject2: InteractableGameObject
-) => boolean = (
- gameObject1: InteractableGameObject,
- gameObject2: InteractableGameObject
-) => {
- if (
- gameObject1 instanceof InteractableGameObject &&
- gameObject2 instanceof InteractableGameObject
- ) {
+export const gameobjects_overlap: (gameObject1: InteractableGameObject, gameObject2: InteractableGameObject) => boolean
+= (gameObject1: InteractableGameObject, gameObject2: InteractableGameObject) => {
+ if (gameObject1 instanceof InteractableGameObject && gameObject2 instanceof InteractableGameObject) {
return gameObject1.isOverlapping(gameObject2);
}
throw new TypeError('Cannot check overlap of non-GameObject');
@@ -854,9 +783,7 @@ export const get_loop_count: () => number = () => gameState.loopCount;
* })
* ```
*/
-export const update_loop: (update_function: UpdateFunction) => void = (
- update_function: UpdateFunction
-) => {
+export const update_loop: (update_function: UpdateFunction) => void = (update_function: UpdateFunction) => {
// Test for error in user update function
// This cannot not check for errors inside a block that is not run.
update_function([]);
@@ -934,20 +861,15 @@ export const build_game: () => BuildGame = () => {
* ```
* @category Audio
*/
-export const create_audio: (
- audio_url: string,
- volume_level: number
-) => AudioClip = (audio_url: string, volume_level: number) => {
+export const create_audio: (audio_url: string, volume_level: number) => AudioClip
+= (audio_url: string, volume_level: number) => {
if (typeof audio_url !== 'string') {
throw new Error('audio_url must be a string');
}
if (typeof volume_level !== 'number') {
throw new Error('volume_level must be a number');
}
- return AudioClip.of(
- audio_url,
- withinRange(volume_level, MIN_VOLUME, MAX_VOLUME)
- );
+ return AudioClip.of(audio_url, withinRange(volume_level, MIN_VOLUME, MAX_VOLUME));
};
/**
@@ -962,9 +884,7 @@ export const create_audio: (
* ```
* @category Audio
*/
-export const loop_audio: (audio_clip: AudioClip) => AudioClip = (
- audio_clip: AudioClip
-) => {
+export const loop_audio: (audio_clip: AudioClip) => AudioClip = (audio_clip: AudioClip) => {
if (audio_clip instanceof AudioClip) {
audio_clip.setShouldAudioClipLoop(true);
return audio_clip;
@@ -983,9 +903,7 @@ export const loop_audio: (audio_clip: AudioClip) => AudioClip = (
* ```
* @category Audio
*/
-export const play_audio: (audio_clip: AudioClip) => AudioClip = (
- audio_clip: AudioClip
-) => {
+export const play_audio: (audio_clip: AudioClip) => AudioClip = (audio_clip: AudioClip) => {
if (audio_clip instanceof AudioClip) {
audio_clip.setShouldAudioClipPlay(true);
return audio_clip;
@@ -1004,9 +922,7 @@ export const play_audio: (audio_clip: AudioClip) => AudioClip = (
* ```
* @category Audio
*/
-export const stop_audio: (audio_clip: AudioClip) => AudioClip = (
- audio_clip: AudioClip
-) => {
+export const stop_audio: (audio_clip: AudioClip) => AudioClip = (audio_clip: AudioClip) => {
if (audio_clip instanceof AudioClip) {
audio_clip.setShouldAudioClipPlay(false);
return audio_clip;
diff --git a/src/bundles/arcade_2d/phaserScene.ts b/src/bundles/arcade_2d/phaserScene.ts
index 8a59019c6..dffdd56bd 100644
--- a/src/bundles/arcade_2d/phaserScene.ts
+++ b/src/bundles/arcade_2d/phaserScene.ts
@@ -5,18 +5,18 @@ import { config } from './functions';
import {
CircleGameObject,
GameObject,
+ type InteractableGameObject,
RectangleGameObject,
ShapeGameObject,
SpriteGameObject,
TextGameObject,
- TriangleGameObject,
- type InteractableGameObject
+ TriangleGameObject
} from './gameobject';
import {
- type ExceptionError,
- type PhaserGameObject,
+ type TransformProps,
type PositionXY,
- type TransformProps
+ type ExceptionError,
+ type PhaserGameObject
} from './types';
// Game state information, that changes every frame.
@@ -51,8 +51,7 @@ export class PhaserScene extends Phaser.Scene {
constructor() {
super('PhaserScene');
}
- private sourceGameObjects: Array =
- GameObject.getGameObjectsArray();
+ private sourceGameObjects: Array = GameObject.getGameObjectsArray();
private phaserGameObjects: Array = [];
private corsAssetsUrl: Set = new Set();
private sourceAudioClips: Array = AudioClip.getAudioClipsArray();
@@ -103,9 +102,7 @@ export class PhaserScene extends Phaser.Scene {
gameState.inputKeysDown.add(event.key);
});
this.input.keyboard.on('keyup', (event: KeyboardEvent) => {
- this.delayedKeyUpEvents.add(() =>
- gameState.inputKeysDown.delete(event.key)
- );
+ this.delayedKeyUpEvents.add(() => gameState.inputKeysDown.delete(event.key));
});
// Handle debug info
@@ -282,12 +279,10 @@ export class PhaserScene extends Phaser.Scene {
private createAudioClips() {
try {
this.sourceAudioClips.forEach((audioClip: AudioClip) => {
- this.phaserAudioClips.push(
- this.sound.add(audioClip.getUrl(), {
- loop: audioClip.shouldAudioClipLoop(),
- volume: audioClip.getVolumeLevel()
- })
- );
+ this.phaserAudioClips.push(this.sound.add(audioClip.getUrl(), {
+ loop: audioClip.shouldAudioClipLoop(),
+ volume: audioClip.getVolumeLevel()
+ }));
});
} catch (error) {
this.hasRuntimeError = true;
@@ -322,26 +317,17 @@ export class PhaserScene extends Phaser.Scene {
/** Loop through each GameObject in the array and determine which needs to update. */
private handleGameObjectUpdates() {
this.sourceGameObjects.forEach((gameObject: InteractableGameObject) => {
- const phaserGameObject = this.phaserGameObjects[
- gameObject.id
- ] as PhaserGameObject;
+ const phaserGameObject = this.phaserGameObjects[gameObject.id] as PhaserGameObject;
if (phaserGameObject) {
// Update the transform of Phaser GameObject
- if (
- gameObject.hasTransformUpdates() ||
- this.shouldRerenderGameObjects
- ) {
+ if (gameObject.hasTransformUpdates() || this.shouldRerenderGameObjects) {
const transformProps = gameObject.getTransform() as TransformProps;
- phaserGameObject
- .setPosition(transformProps.position[0], transformProps.position[1])
+ phaserGameObject.setPosition(transformProps.position[0], transformProps.position[1])
.setRotation(transformProps.rotation)
.setScale(transformProps.scale[0], transformProps.scale[1]);
if (gameObject instanceof TriangleGameObject) {
// The only shape that requires flipping is the triangle, as the rest are symmetric about their origin.
- phaserGameObject.setRotation(
- transformProps.rotation +
- (gameObject.getFlipState()[1] ? Math.PI : 0)
- );
+ phaserGameObject.setRotation(transformProps.rotation + (gameObject.getFlipState()[1] ? Math.PI : 0));
}
gameObject.setTransformUpdated();
}
@@ -350,32 +336,22 @@ export class PhaserScene extends Phaser.Scene {
if (gameObject.hasRenderUpdates() || this.shouldRerenderGameObjects) {
const color = gameObject.getColor();
// eslint-disable-next-line new-cap
- const intColor = Phaser.Display.Color.GetColor32(
- color[0],
- color[1],
- color[2],
- color[3]
- );
+ const intColor = Phaser.Display.Color.GetColor32(color[0], color[1], color[2], color[3]);
const flip = gameObject.getFlipState();
if (gameObject instanceof TextGameObject) {
- (phaserGameObject as Phaser.GameObjects.Text)
- .setTint(intColor)
+ (phaserGameObject as Phaser.GameObjects.Text).setTint(intColor)
.setAlpha(color[3] / 255)
.setFlip(flip[0], flip[1])
.setText(gameObject.getText().text);
} else if (gameObject instanceof SpriteGameObject) {
- (phaserGameObject as Phaser.GameObjects.Sprite)
- .setTint(intColor)
+ (phaserGameObject as Phaser.GameObjects.Sprite).setTint(intColor)
.setAlpha(color[3] / 255)
.setFlip(flip[0], flip[1]);
} else if (gameObject instanceof ShapeGameObject) {
- (phaserGameObject as Phaser.GameObjects.Shape)
- .setFillStyle(intColor, color[3] / 255)
- // Phaser.GameObjects.Shape does not have setFlip, so flipping is done with rotations.
- // The only shape that requires flipping is the triangle, as the rest are symmetric about their origin.
- .setRotation(
- gameObject.getTransform().rotation + (flip[1] ? Math.PI : 0)
- );
+ (phaserGameObject as Phaser.GameObjects.Shape).setFillStyle(intColor, color[3] / 255)
+ // Phaser.GameObjects.Shape does not have setFlip, so flipping is done with rotations.
+ // The only shape that requires flipping is the triangle, as the rest are symmetric about their origin.
+ .setRotation(gameObject.getTransform().rotation + (flip[1] ? Math.PI : 0));
}
// Update the z-index (rendering order), to the top.
if (gameObject.getShouldBringToTop()) {
@@ -385,9 +361,7 @@ export class PhaserScene extends Phaser.Scene {
}
} else {
this.hasRuntimeError = true;
- gameState.debugLogArray.push(
- 'RuntimeError: GameObject error in update_loop'
- );
+ gameState.debugLogArray.push('RuntimeError: GameObject error in update_loop');
}
});
}
@@ -395,9 +369,7 @@ export class PhaserScene extends Phaser.Scene {
private handleAudioUpdates() {
this.sourceAudioClips.forEach((audioClip: AudioClip) => {
if (audioClip.hasAudioClipUpdates()) {
- const phaserAudioClip = this.phaserAudioClips[
- audioClip.id
- ] as Phaser.Sound.BaseSound;
+ const phaserAudioClip = this.phaserAudioClips[audioClip.id] as Phaser.Sound.BaseSound;
if (phaserAudioClip) {
if (audioClip.shouldAudioClipPlay()) {
phaserAudioClip.play();
@@ -406,9 +378,7 @@ export class PhaserScene extends Phaser.Scene {
}
} else {
this.hasRuntimeError = true;
- gameState.debugLogArray.push(
- 'RuntimeError: Audio error in update_loop'
- );
+ gameState.debugLogArray.push('RuntimeError: Audio error in update_loop');
}
}
});
diff --git a/src/bundles/binary_tree/functions.ts b/src/bundles/binary_tree/functions.ts
index b86278925..5d09af855 100644
--- a/src/bundles/binary_tree/functions.ts
+++ b/src/bundles/binary_tree/functions.ts
@@ -44,18 +44,18 @@ export function make_tree(
* @param v Value to be tested
* @returns bool
*/
-export function is_tree(value: any): boolean {
- return (
- value === null ||
- (Array.isArray(value) &&
- value.length === 2 &&
- Array.isArray(value[1]) &&
- value[1].length === 2 &&
- is_tree(value[1][0]) &&
- value[1][1].length === 2 &&
- is_tree(value[1][1][0]) &&
- value[1][1][1] === null)
- );
+export function is_tree(
+ value: any
+): boolean {
+ return value === null
+ || (Array.isArray(value)
+ && value.length === 2
+ && Array.isArray(value[1])
+ && value[1].length === 2
+ && is_tree(value[1][0])
+ && value[1][1].length === 2
+ && is_tree(value[1][1][0])
+ && value[1][1][1] === null);
}
/**
@@ -87,7 +87,9 @@ export function entry(t: BinaryTree): boolean {
if (Array.isArray(t) && t.length === 2) {
return t[0];
}
- throw new Error(`function entry expects binary tree, received: ${t}`);
+ throw new Error(
+ `function entry expects binary tree, received: ${t}`
+ );
}
/**
@@ -101,15 +103,13 @@ export function entry(t: BinaryTree): boolean {
* @returns BinaryTree
*/
export function left_branch(t: BinaryTree): BinaryTree {
- if (
- Array.isArray(t) &&
- t.length === 2 &&
- Array.isArray(t[1]) &&
- t[1].length === 2
- ) {
+ if (Array.isArray(t) && t.length === 2
+ && Array.isArray(t[1]) && t[1].length === 2) {
return t[1][0];
}
- throw new Error(`function left_branch expects binary tree, received: ${t}`);
+ throw new Error(
+ `function left_branch expects binary tree, received: ${t}`
+ );
}
/**
@@ -123,15 +123,12 @@ export function left_branch(t: BinaryTree): BinaryTree {
* @returns BinaryTree
*/
export function right_branch(t: BinaryTree): BinaryTree {
- if (
- Array.isArray(t) &&
- t.length === 2 &&
- Array.isArray(t[1]) &&
- t[1].length === 2 &&
- Array.isArray(t[1][1]) &&
- t[1][1].length === 2
- ) {
+ if (Array.isArray(t) && t.length === 2
+ && Array.isArray(t[1]) && t[1].length === 2
+ && Array.isArray(t[1][1]) && t[1][1].length === 2) {
return t[1][1][0];
}
- throw new Error(`function right_branch expects binary tree, received: ${t}`);
+ throw new Error(
+ `function right_branch expects binary tree, received: ${t}`
+ );
}
diff --git a/src/bundles/communication/Communications.ts b/src/bundles/communication/Communications.ts
index f584ad855..6a960b2b5 100644
--- a/src/bundles/communication/Communications.ts
+++ b/src/bundles/communication/Communications.ts
@@ -28,7 +28,7 @@ export function initCommunications(
address: string,
port: number,
user: string,
- password: string
+ password: string,
) {
if (getModuleState() instanceof CommunicationModuleState) {
return;
@@ -37,7 +37,7 @@ export function initCommunications(
address,
port,
user,
- password
+ password,
);
context.moduleContexts.communication.state = newModuleState;
}
@@ -77,7 +77,7 @@ export function stopRunning() {
*/
export function initGlobalState(
topicHeader: string,
- callback: (state: any) => void
+ callback: (state: any) => void,
) {
const moduleState = getModuleState();
if (moduleState instanceof CommunicationModuleState) {
@@ -87,7 +87,7 @@ export function initGlobalState(
moduleState.globalState = new GlobalStateController(
topicHeader,
moduleState.multiUser,
- callback
+ callback,
);
return;
}
@@ -137,7 +137,7 @@ export function initRpc(topicHeader: string, userId?: string) {
moduleState.rpc = new RpcController(
topicHeader,
moduleState.multiUser,
- userId
+ userId,
);
return;
}
@@ -189,7 +189,7 @@ export function callFunction(
receiver: string,
name: string,
args: any[],
- callback: (args: any[]) => void
+ callback: (args: any[]) => void,
) {
const moduleState = getModuleState();
if (moduleState instanceof CommunicationModuleState) {
diff --git a/src/bundles/communication/GlobalStateController.ts b/src/bundles/communication/GlobalStateController.ts
index 571fb5d12..03c86b1fb 100644
--- a/src/bundles/communication/GlobalStateController.ts
+++ b/src/bundles/communication/GlobalStateController.ts
@@ -17,7 +17,7 @@ export class GlobalStateController {
constructor(
topicHeader: string,
multiUser: MultiUserController,
- callback: (state: any) => void
+ callback: (state: any) => void,
) {
this.topicHeader = topicHeader;
this.multiUser = multiUser;
@@ -34,7 +34,7 @@ export class GlobalStateController {
this.multiUser.addMessageCallback(this.topicHeader, (topic, message) => {
const shortenedTopic = topic.substring(
this.topicHeader.length,
- topic.length
+ topic.length,
);
this.parseGlobalStateMessage(shortenedTopic, message);
});
@@ -119,7 +119,7 @@ export class GlobalStateController {
this.multiUser.controller?.publish(
topic,
JSON.stringify(updatedState),
- false
+ false,
);
}
}
diff --git a/src/bundles/communication/MqttController.ts b/src/bundles/communication/MqttController.ts
index ff557ec83..6414b5db0 100644
--- a/src/bundles/communication/MqttController.ts
+++ b/src/bundles/communication/MqttController.ts
@@ -26,7 +26,7 @@ export class MqttController {
constructor(
connectionCallback: (status: string) => void,
- messageCallback: (topic: string, message: string) => void
+ messageCallback: (topic: string, message: string) => void,
) {
this.connectionCallback = connectionCallback;
this.messageCallback = messageCallback;
@@ -85,11 +85,11 @@ export class MqttController {
topic: string,
message: string,
isRetain: boolean,
- qos: number = 1
+ qos: number = 1,
) {
this.client?.publish(topic, message, {
qos: qos,
- retain: isRetain
+ retain: isRetain,
});
}
diff --git a/src/bundles/communication/MultiUserController.ts b/src/bundles/communication/MultiUserController.ts
index 210092259..1d29f06a1 100644
--- a/src/bundles/communication/MultiUserController.ts
+++ b/src/bundles/communication/MultiUserController.ts
@@ -24,7 +24,7 @@ export class MultiUserController {
address: string,
port: number,
user: string,
- password: string
+ password: string,
) {
let currentController = this.controller;
if (currentController) {
@@ -38,7 +38,7 @@ export class MultiUserController {
},
(topic: string, message: string) => {
this.handleIncomingMessage(topic, message);
- }
+ },
);
this.controller = currentController;
}
@@ -75,7 +75,7 @@ export class MultiUserController {
*/
public addMessageCallback(
identifier: string,
- callback: (topic: string, message: string) => void
+ callback: (topic: string, message: string) => void,
) {
this.controller?.subscribe(`${identifier}/#`);
this.messageCallbacks.set(identifier, callback);
diff --git a/src/bundles/communication/RpcController.ts b/src/bundles/communication/RpcController.ts
index e9e284c59..673b0e845 100644
--- a/src/bundles/communication/RpcController.ts
+++ b/src/bundles/communication/RpcController.ts
@@ -24,7 +24,7 @@ export class RpcController {
constructor(
topicHeader: string,
multiUser: MultiUserController,
- userId?: string
+ userId?: string,
) {
this.topicHeader = topicHeader;
this.multiUser = multiUser;
@@ -51,7 +51,7 @@ export class RpcController {
private returnResponse(sender: string, callId: string, result: any) {
const message = {
callId,
- result
+ result,
};
const topic = `${this.topicHeader}_return/${sender}`;
this.multiUser.controller?.publish(topic, JSON.stringify(message), false);
@@ -75,7 +75,7 @@ export class RpcController {
public expose(name: string, func: (...args: any[]) => any) {
const item = {
name,
- func
+ func,
};
this.functions.set(name, item);
const functionTopic = `${this.topicHeader}/${this.userId}/${name}`;
@@ -115,7 +115,7 @@ export class RpcController {
receiver: string,
name: string,
args: any[],
- callback: (args: any[]) => void
+ callback: (args: any[]) => void,
) {
const topic = `${this.topicHeader}/${receiver}/${name}`;
const callId = uniqid();
@@ -123,7 +123,7 @@ export class RpcController {
const messageJson = {
sender: this.userId,
callId,
- args
+ args,
};
const messageString = JSON.stringify(messageJson);
this.multiUser.controller?.publish(topic, messageString, false);
diff --git a/src/bundles/game/functions.ts b/src/bundles/game/functions.ts
index 7da32b08c..933a2c2c9 100644
--- a/src/bundles/game/functions.ts
+++ b/src/bundles/game/functions.ts
@@ -17,22 +17,16 @@
/* eslint-disable consistent-return, @typescript-eslint/default-param-last, @typescript-eslint/no-shadow, @typescript-eslint/no-unused-vars */
import context from 'js-slang/context';
-import {
- accumulate,
- head,
- is_pair,
- tail,
- type List
-} from 'js-slang/dist/stdlib/list';
+import { type List, head, tail, is_pair, accumulate } from 'js-slang/dist/stdlib/list';
import Phaser from 'phaser';
import {
- defaultGameParams,
type GameObject,
type ObjectConfig,
type RawContainer,
type RawGameElement,
type RawGameObject,
- type RawInputObject
+ type RawInputObject,
+ defaultGameParams
} from './types';
if (!context.moduleContexts.game.state) {
@@ -51,7 +45,7 @@ const {
// Listener ObjectTypes
enum ListenerTypes {
InputPlugin = 'input_plugin',
- KeyboardKeyType = 'keyboard_key'
+ KeyboardKeyType = 'keyboard_key',
}
const ListnerTypes = Object.values(ListenerTypes);
@@ -63,7 +57,7 @@ enum ObjectTypes {
RectType = 'rect',
EllipseType = 'ellipse',
ContainerType = 'container',
- AwardType = 'award'
+ AwardType = 'award',
}
const ObjTypes = Object.values(ObjectTypes);
@@ -77,8 +71,7 @@ const mandatory = (obj, errMsg: string) => {
return obj;
};
-const scene = () =>
- mandatory(context.moduleContexts.game.state.scene, 'No scene found!');
+const scene = () => mandatory(context.moduleContexts.game.state.scene, 'No scene found!');
// =============================================================================
// Module's Private Functions
@@ -191,17 +184,13 @@ export function prepend_remote_url(asset_key: string): string {
*/
export function create_config(lst: List): ObjectConfig {
const config = {};
- accumulate(
- (xs: [any, any], _) => {
- if (!is_pair(xs)) {
- throw_error('config element is not a pair!');
- }
- config[head(xs)] = tail(xs);
- return null;
- },
- null,
- lst
- );
+ accumulate((xs: [any, any], _) => {
+ if (!is_pair(xs)) {
+ throw_error('config element is not a pair!');
+ }
+ config[head(xs)] = tail(xs);
+ return null;
+ }, null, lst);
return config;
}
@@ -655,11 +644,7 @@ export function create_image(
* @param award_key key for award
* @returns award game object
*/
-export function create_award(
- x: number,
- y: number,
- award_key: string
-): GameObject {
+export function create_award(x: number, y: number, award_key: string): GameObject {
return set_type(createAward(x, y, award_key), ObjectTypes.AwardType);
}
@@ -792,8 +777,8 @@ export function add_to_container(
obj: GameObject
): GameObject | undefined {
if (
- is_type(container, ObjectTypes.ContainerType) &&
- is_any_type(obj, ObjTypes)
+ is_type(container, ObjectTypes.ContainerType)
+ && is_any_type(obj, ObjTypes)
) {
get_container(container).add(get_game_obj(obj));
return container;
@@ -849,10 +834,7 @@ export function set_display_size(
* @param alpha new alpha
* @returns game object itself
*/
-export function set_alpha(
- obj: GameObject,
- alpha: number
-): GameObject | undefined {
+export function set_alpha(obj: GameObject, alpha: number): GameObject | undefined {
if (is_any_type(obj, ObjTypes)) {
get_game_obj(obj).setAlpha(alpha);
return obj;
@@ -954,10 +936,7 @@ export function set_scale(
* @param rad the rotation, in radians
* @returns game object itself
*/
-export function set_rotation(
- obj: GameObject,
- rad: number
-): GameObject | undefined {
+export function set_rotation(obj: GameObject, rad: number): GameObject | undefined {
if (is_any_type(obj, ObjTypes)) {
get_game_obj(obj).setRotation(rad);
return obj;
diff --git a/src/bundles/physics_2d/PhysicsObject.ts b/src/bundles/physics_2d/PhysicsObject.ts
index c5ab1cada..2162bb438 100644
--- a/src/bundles/physics_2d/PhysicsObject.ts
+++ b/src/bundles/physics_2d/PhysicsObject.ts
@@ -3,13 +3,13 @@
// follow the same guidelines as the rest of the codebase.
import {
+ type b2Body,
+ type b2Shape,
+ type b2Fixture,
b2BodyType,
b2CircleShape,
b2PolygonShape,
- b2Vec2,
- type b2Body,
- type b2Fixture,
- type b2Shape
+ b2Vec2
} from '@box2d/core';
import { type ReplResult } from '../../typings/type_helpers';
@@ -112,8 +112,7 @@ export class PhysicsObject implements ReplResult {
const resForce = this.forcesCentered
.filter((force: Force) => force.start_time < world_time)
.reduce(
- (res: b2Vec2, force: Force) =>
- res.Add(force.direction.Scale(force.magnitude)),
+ (res: b2Vec2, force: Force) => res.Add(force.direction.Scale(force.magnitude)),
new b2Vec2()
);
@@ -122,11 +121,10 @@ export class PhysicsObject implements ReplResult {
private applyForcesAtAPoint(world_time: number) {
this.forcesAtAPoint = this.forcesAtAPoint.filter(
- (forceWithPos: ForceWithPos) =>
- forceWithPos.force.start_time + forceWithPos.force.duration > world_time
+ (forceWithPos: ForceWithPos) => forceWithPos.force.start_time + forceWithPos.force.duration > world_time
);
- this.forcesAtAPoint.forEach(forceWithPos => {
+ this.forcesAtAPoint.forEach((forceWithPos) => {
const force = forceWithPos.force;
this.body.ApplyForce(
force.direction.Scale(force.magnitude),
diff --git a/src/bundles/physics_2d/PhysicsWorld.ts b/src/bundles/physics_2d/PhysicsWorld.ts
index 39b659a97..da87c17e9 100644
--- a/src/bundles/physics_2d/PhysicsWorld.ts
+++ b/src/bundles/physics_2d/PhysicsWorld.ts
@@ -3,16 +3,16 @@
// follow the same guidelines as the rest of the codebase.
import {
+ type b2Body,
+ type b2Fixture,
+ type b2BodyDef,
b2BodyType,
- b2ContactListener,
b2PolygonShape,
+ type b2StepConfig,
b2Vec2,
b2World,
- type b2Body,
- type b2BodyDef,
- type b2Contact,
- type b2Fixture,
- type b2StepConfig
+ b2ContactListener,
+ type b2Contact
} from '@box2d/core';
import { type PhysicsObject } from './PhysicsObject';
import { Timer } from './types';
@@ -73,10 +73,11 @@ export class PhysicsWorld {
type: b2BodyType.b2_staticBody,
position: new b2Vec2(0, height - 10)
});
- const groundShape: b2PolygonShape = new b2PolygonShape().SetAsBox(
- 10000,
- 10
- );
+ const groundShape: b2PolygonShape = new b2PolygonShape()
+ .SetAsBox(
+ 10000,
+ 10
+ );
groundBody.CreateFixture({
shape: groundShape,
diff --git a/src/bundles/physics_2d/functions.ts b/src/bundles/physics_2d/functions.ts
index d8e4496ad..9ebf42e56 100644
--- a/src/bundles/physics_2d/functions.ts
+++ b/src/bundles/physics_2d/functions.ts
@@ -13,7 +13,7 @@ import context from 'js-slang/context';
import { PhysicsObject } from './PhysicsObject';
import { PhysicsWorld } from './PhysicsWorld';
-import { Vector2, type Force } from './types';
+import { type Force, Vector2 } from './types';
// Global Variables
diff --git a/src/bundles/repl/functions.ts b/src/bundles/repl/functions.ts
index 18c0ceae8..15834e693 100644
--- a/src/bundles/repl/functions.ts
+++ b/src/bundles/repl/functions.ts
@@ -26,9 +26,7 @@ context.moduleContexts.repl.state = INSTANCE;
export function set_evaluator(evalFunc: Function) {
if (!(evalFunc instanceof Function)) {
const typeName = typeof evalFunc;
- throw new Error(
- `Wrong parameter type "${typeName}' in function "set_evaluator". It supposed to be a function and it's the entrance function of your metacircular evaulator.`
- );
+ throw new Error(`Wrong parameter type "${typeName}' in function "set_evaluator". It supposed to be a function and it's the entrance function of your metacircular evaulator.`);
}
INSTANCE.evalFunction = evalFunc;
return {
@@ -93,10 +91,7 @@ export function repl_display(content: any): any {
*
* @category Main
*/
-export function set_background_image(
- img_url: string,
- background_color_alpha: number
-): void {
+export function set_background_image(img_url: string, background_color_alpha: number): void {
INSTANCE.customizedEditorProps.backgroundImageUrl = img_url;
INSTANCE.customizedEditorProps.backgroundColorAlpha = background_color_alpha;
}
@@ -108,7 +103,7 @@ export function set_background_image(
* @category Main
*/
export function set_font_size(font_size_px: number) {
- INSTANCE.customizedEditorProps.fontSize = parseInt(font_size_px.toString()); // The TypeScript type checker will throw an error as "parseInt" in TypeScript only accepts one string as parameter.
+ INSTANCE.customizedEditorProps.fontSize = parseInt(font_size_px.toString());// The TypeScript type checker will throw an error as "parseInt" in TypeScript only accepts one string as parameter.
}
/**
@@ -119,9 +114,7 @@ export function set_font_size(font_size_px: number) {
* @category Main
*/
export function default_js_slang(_program: string): any {
- throw new Error(
- 'Invaild Call: Function "default_js_slang" can not be directly called by user\'s code in editor. You should use it as the parameter of the function "set_evaluator"'
- );
+ throw new Error('Invaild Call: Function "default_js_slang" can not be directly called by user\'s code in editor. You should use it as the parameter of the function "set_evaluator"');
// When the function is normally called by set_evaluator function, safeKey is set to "document.body", which has a type "Element".
// Students can not create objects and use HTML Elements in Source due to limitations and rules in Source, so they can't set the safeKey to a HTML Element, thus they can't use this function in Source.
}
diff --git a/src/bundles/sound/functions.ts b/src/bundles/sound/functions.ts
index 6c87c70fa..879127058 100644
--- a/src/bundles/sound/functions.ts
+++ b/src/bundles/sound/functions.ts
@@ -1,23 +1,23 @@
/* eslint-disable new-cap, @typescript-eslint/naming-convention */
import context from 'js-slang/context';
import {
- accumulate,
+ pair,
head,
+ tail,
+ list,
+ length,
is_null,
is_pair,
- length,
- list,
- pair,
- tail,
+ accumulate,
type List
} from 'js-slang/dist/stdlib/list';
import { RIFFWAVE } from './riffwave';
import type {
- AudioPlayed,
+ Wave,
Sound,
SoundProducer,
SoundTransformer,
- Wave
+ AudioPlayed
} from './types';
// Global Constants and Variables
@@ -288,9 +288,9 @@ export function get_duration(sound: Sound): number {
*/
export function is_sound(x: any): x is Sound {
return (
- is_pair(x) &&
- typeof get_wave(x) === 'function' &&
- typeof get_duration(x) === 'number'
+ is_pair(x)
+ && typeof get_wave(x) === 'function'
+ && typeof get_duration(x) === 'number'
);
}
@@ -318,14 +318,10 @@ export function play_wave(wave: Wave, duration: number): Sound {
export function play_in_tab(sound: Sound): Sound {
// Type-check sound
if (!is_sound(sound)) {
- throw new Error(
- `${play_in_tab.name} is expecting sound, but encountered ${sound}`
- );
+ throw new Error(`${play_in_tab.name} is expecting sound, but encountered ${sound}`);
// If a sound is already playing, terminate execution.
} else if (isPlaying) {
- throw new Error(
- `${play_in_tab.name}: audio system still playing previous sound`
- );
+ throw new Error(`${play_in_tab.name}: audio system still playing previous sound`);
} else if (get_duration(sound) < 0) {
throw new Error(`${play_in_tab.name}: duration of sound is negative`);
} else if (get_duration(sound) === 0) {
@@ -528,14 +524,14 @@ export function triangle_sound(freq: number, duration: number): Sound {
function fourier_expansion_triangle(t: number) {
let answer = 0;
for (let i = 0; i < fourier_expansion_level; i += 1) {
- answer +=
- ((-1) ** i * Math.sin((2 * i + 1) * t * freq * Math.PI * 2)) /
- (2 * i + 1) ** 2;
+ answer
+ += ((-1) ** i * Math.sin((2 * i + 1) * t * freq * Math.PI * 2))
+ / (2 * i + 1) ** 2;
}
return answer;
}
return make_sound(
- t => (8 / Math.PI / Math.PI) * fourier_expansion_triangle(t),
+ (t) => (8 / Math.PI / Math.PI) * fourier_expansion_triangle(t),
duration
);
}
@@ -650,18 +646,18 @@ export function adsr(
}
if (x < attack_time + decay_time) {
return (
- ((1 - sustain_level) * linear_decay(decay_time)(x - attack_time) +
- sustain_level) *
- wave(x)
+ ((1 - sustain_level) * linear_decay(decay_time)(x - attack_time)
+ + sustain_level)
+ * wave(x)
);
}
if (x < duration - release_time) {
return wave(x) * sustain_level;
}
return (
- wave(x) *
- sustain_level *
- linear_decay(release_time)(x - (duration - release_time))
+ wave(x)
+ * sustain_level
+ * linear_decay(release_time)(x - (duration - release_time))
);
}, duration);
};
@@ -698,8 +694,7 @@ export function stacking_adsr(
return simultaneously(
accumulate(
- (x: any, y: any) =>
- pair(tail(x)(waveform(base_frequency * head(x), duration)), y),
+ (x: any, y: any) => pair(tail(x)(waveform(base_frequency * head(x), duration)), y),
null,
zip(envelopes, 1)
)
@@ -725,11 +720,10 @@ export function phase_mod(
duration: number,
amount: number
): SoundTransformer {
- return (modulator: Sound) =>
- make_sound(
- t => Math.sin(2 * Math.PI * t * freq + amount * get_wave(modulator)(t)),
- duration
- );
+ return (modulator: Sound) => make_sound(
+ t => Math.sin(2 * Math.PI * t * freq + amount * get_wave(modulator)(t)),
+ duration
+ );
}
// MIDI conversion functions
diff --git a/src/bundles/stereo_sound/functions.ts b/src/bundles/stereo_sound/functions.ts
index f510375e3..f361fbb7c 100644
--- a/src/bundles/stereo_sound/functions.ts
+++ b/src/bundles/stereo_sound/functions.ts
@@ -311,10 +311,10 @@ export function get_duration(sound: Sound): number {
*/
export function is_sound(x: any): boolean {
return (
- is_pair(x) &&
- typeof get_left_wave(x) === 'function' &&
- typeof get_right_wave(x) === 'function' &&
- typeof get_duration(x) === 'number'
+ is_pair(x)
+ && typeof get_left_wave(x) === 'function'
+ && typeof get_right_wave(x) === 'function'
+ && typeof get_duration(x) === 'number'
);
}
@@ -340,7 +340,11 @@ export function play_wave(wave: Wave, duration: number): Sound {
* @return the given Sound
* @example play_waves(t => math_sin(t * 3000), t => math_sin(t * 6000), 5);
*/
-export function play_waves(wave1: Wave, wave2: Wave, duration: number): Sound {
+export function play_waves(
+ wave1: Wave,
+ wave2: Wave,
+ duration: number
+): Sound {
return play(make_stereo_sound(wave1, wave2, duration));
}
@@ -356,14 +360,10 @@ export function play_waves(wave1: Wave, wave2: Wave, duration: number): Sound {
export function play_in_tab(sound: Sound): Sound {
// Type-check sound
if (!is_sound(sound)) {
- throw new Error(
- `${play_in_tab.name} is expecting sound, but encountered ${sound}`
- );
+ throw new Error(`${play_in_tab.name} is expecting sound, but encountered ${sound}`);
// If a sound is already playing, terminate execution.
} else if (isPlaying) {
- throw new Error(
- `${play_in_tab.name}: audio system still playing previous sound`
- );
+ throw new Error(`${play_in_tab.name}: audio system still playing previous sound`);
} else if (get_duration(sound) < 0) {
throw new Error(`${play_in_tab.name}: duration of sound is negative`);
} else if (get_duration(sound) === 0) {
@@ -397,8 +397,8 @@ export function play_in_tab(sound: Sound): Sound {
// smoothen out sudden cut-outs
if (
- channel[2 * i] === 0 &&
- Math.abs(channel[2 * i] - Lprev_value) > 0.01
+ channel[2 * i] === 0
+ && Math.abs(channel[2 * i] - Lprev_value) > 0.01
) {
channel[2 * i] = Lprev_value * 0.999;
}
@@ -417,8 +417,8 @@ export function play_in_tab(sound: Sound): Sound {
// smoothen out sudden cut-outs
if (
- channel[2 * i + 1] === 0 &&
- Math.abs(channel[2 * i] - Rprev_value) > 0.01
+ channel[2 * i + 1] === 0
+ && Math.abs(channel[2 * i] - Rprev_value) > 0.01
) {
channel[2 * i + 1] = Rprev_value * 0.999;
}
@@ -458,9 +458,7 @@ export function play_in_tab(sound: Sound): Sound {
export function play(sound: Sound): Sound {
// Type-check sound
if (!is_sound(sound)) {
- throw new Error(
- `${play.name} is expecting sound, but encountered ${sound}`
- );
+ throw new Error(`${play.name} is expecting sound, but encountered ${sound}`);
// If a sound is already playing, terminate execution.
} else if (isPlaying) {
throw new Error(`${play.name}: audio system still playing previous sound`);
@@ -497,8 +495,8 @@ export function play(sound: Sound): Sound {
// smoothen out sudden cut-outs
if (
- channel[2 * i] === 0 &&
- Math.abs(channel[2 * i] - Lprev_value) > 0.01
+ channel[2 * i] === 0
+ && Math.abs(channel[2 * i] - Lprev_value) > 0.01
) {
channel[2 * i] = Lprev_value * 0.999;
}
@@ -517,8 +515,8 @@ export function play(sound: Sound): Sound {
// smoothen out sudden cut-outs
if (
- channel[2 * i + 1] === 0 &&
- Math.abs(channel[2 * i] - Rprev_value) > 0.01
+ channel[2 * i + 1] === 0
+ && Math.abs(channel[2 * i] - Rprev_value) > 0.01
) {
channel[2 * i + 1] = Rprev_value * 0.999;
}
@@ -696,14 +694,14 @@ export function triangle_sound(freq: number, duration: number): Sound {
function fourier_expansion_triangle(t: number) {
let answer = 0;
for (let i = 0; i < fourier_expansion_level; i += 1) {
- answer +=
- ((-1) ** i * Math.sin((2 * i + 1) * t * freq * Math.PI * 2)) /
- (2 * i + 1) ** 2;
+ answer
+ += ((-1) ** i * Math.sin((2 * i + 1) * t * freq * Math.PI * 2))
+ / (2 * i + 1) ** 2;
}
return answer;
}
return make_sound(
- t => (8 / Math.PI / Math.PI) * fourier_expansion_triangle(t),
+ (t) => (8 / Math.PI / Math.PI) * fourier_expansion_triangle(t),
duration
);
}
@@ -754,11 +752,7 @@ export function consecutively(list_of_sounds: List): Sound {
const new_right = (t: number) => (t < dur1 ? Rwave1(t) : Rwave2(t - dur1));
return make_stereo_sound(new_left, new_right, dur1 + dur2);
}
- return accumulate(
- stereo_cons_two,
- silence_sound(0),
- list_of_sounds
- );
+ return accumulate(stereo_cons_two, silence_sound(0), list_of_sounds);
}
/**
@@ -792,10 +786,8 @@ export function simultaneously(list_of_sounds: List): Sound {
list_of_sounds
);
const sounds_length = length(list_of_sounds);
- const normalised_left = (t: number) =>
- head(head(unnormed))(t) / sounds_length;
- const normalised_right = (t: number) =>
- tail(head(unnormed))(t) / sounds_length;
+ const normalised_left = (t: number) => head(head(unnormed))(t) / sounds_length;
+ const normalised_right = (t: number) => tail(head(unnormed))(t) / sounds_length;
const highest_duration = tail(unnormed);
return make_stereo_sound(normalised_left, normalised_right, highest_duration);
}
@@ -836,18 +828,18 @@ export function adsr(
}
if (x < attack_time + decay_time) {
return (
- ((1 - sustain_level) * linear_decay(decay_time)(x - attack_time) +
- sustain_level) *
- wave(x)
+ ((1 - sustain_level) * linear_decay(decay_time)(x - attack_time)
+ + sustain_level)
+ * wave(x)
);
}
if (x < duration - release_time) {
return wave(x) * sustain_level;
}
return (
- wave(x) *
- sustain_level *
- linear_decay(release_time)(x - (duration - release_time))
+ wave(x)
+ * sustain_level
+ * linear_decay(release_time)(x - (duration - release_time))
);
};
}
@@ -886,8 +878,7 @@ export function stacking_adsr(
return simultaneously(
accumulate(
- (x: any, y: any) =>
- pair(tail(x)(waveform(base_frequency * head(x), duration)), y),
+ (x: any, y: any) => pair(tail(x)(waveform(base_frequency * head(x), duration)), y),
null,
zip(envelopes, 1)
)
@@ -913,16 +904,13 @@ export function phase_mod(
duration: number,
amount: number
): SoundTransformer {
- return (modulator: Sound) =>
- make_stereo_sound(
- t =>
- Math.sin(2 * Math.PI * t * freq + amount * get_left_wave(modulator)(t)),
- t =>
- Math.sin(
- 2 * Math.PI * t * freq + amount * get_right_wave(modulator)(t)
- ),
- duration
- );
+ return (modulator: Sound) => make_stereo_sound(
+ t => Math.sin(2 * Math.PI * t * freq + amount * get_left_wave(modulator)(t)),
+ t => Math.sin(
+ 2 * Math.PI * t * freq + amount * get_right_wave(modulator)(t)
+ ),
+ duration
+ );
}
// MIDI conversion functions
diff --git a/src/bundles/stereo_sound/riffwave.ts b/src/bundles/stereo_sound/riffwave.ts
index 915c9d677..70a1af751 100644
--- a/src/bundles/stereo_sound/riffwave.ts
+++ b/src/bundles/stereo_sound/riffwave.ts
@@ -54,7 +54,7 @@ var FastBase64 = {
dst += '=';
}
return dst;
- } // end Encode
+ }, // end Encode
};
FastBase64.Init();
@@ -78,7 +78,7 @@ export function RIFFWAVE(this: any, data) {
blockAlign: 0, // 32 2 NumChannels*BitsPerSample/8
bitsPerSample: 8, // 34 2 8 bits = 8, 16 bits = 16
subChunk2Id: [0x64, 0x61, 0x74, 0x61], // 36 4 "data" = 0x64617461
- subChunk2Size: 0 // 40 4 data size = NumSamples*NumChannels*BitsPerSample/8
+ subChunk2Size: 0, // 40 4 data size = NumSamples*NumChannels*BitsPerSample/8
};
function u32ToArray(i) {
From 690e0c4b71b69c89bc427396269409bc538db29b Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Sat, 13 Apr 2024 08:23:35 +0800
Subject: [PATCH 21/39] Revert some changes in bundles
---
src/bundles/arcade_2d/phaserScene.ts | 10 +-
src/bundles/curve/__tests__/curve.ts | 8 +-
src/bundles/repl/programmable_repl.ts | 159 ++-----
src/bundles/unity_academy/UnityAcademy.tsx | 338 +++-----------
.../unity_academy/UnityAcademyMaths.ts | 16 +-
src/bundles/unity_academy/functions.ts | 427 ++++--------------
6 files changed, 199 insertions(+), 759 deletions(-)
diff --git a/src/bundles/arcade_2d/phaserScene.ts b/src/bundles/arcade_2d/phaserScene.ts
index dffdd56bd..d2242b221 100644
--- a/src/bundles/arcade_2d/phaserScene.ts
+++ b/src/bundles/arcade_2d/phaserScene.ts
@@ -279,10 +279,12 @@ export class PhaserScene extends Phaser.Scene {
private createAudioClips() {
try {
this.sourceAudioClips.forEach((audioClip: AudioClip) => {
- this.phaserAudioClips.push(this.sound.add(audioClip.getUrl(), {
- loop: audioClip.shouldAudioClipLoop(),
- volume: audioClip.getVolumeLevel()
- }));
+ this.phaserAudioClips.push(
+ this.sound.add(audioClip.getUrl(), {
+ loop: audioClip.shouldAudioClipLoop(),
+ volume: audioClip.getVolumeLevel()
+ })
+ );
});
} catch (error) {
this.hasRuntimeError = true;
diff --git a/src/bundles/curve/__tests__/curve.ts b/src/bundles/curve/__tests__/curve.ts
index 5565a2d14..51a8933c2 100644
--- a/src/bundles/curve/__tests__/curve.ts
+++ b/src/bundles/curve/__tests__/curve.ts
@@ -1,11 +1,5 @@
import { generateCurve, type Curve } from '../curves_webgl';
-import {
- animate_3D_curve,
- animate_curve,
- draw_3D_connected,
- draw_connected,
- make_point
-} from '../functions';
+import { animate_3D_curve, animate_curve, draw_3D_connected, draw_connected, make_point } from '../functions';
function evalCurve(curve: Curve, numPoints: number) {
generateCurve('none', 'points', numPoints, curve, '2D', false);
diff --git a/src/bundles/repl/programmable_repl.ts b/src/bundles/repl/programmable_repl.ts
index 3af63d956..84fc545f8 100644
--- a/src/bundles/repl/programmable_repl.ts
+++ b/src/bundles/repl/programmable_repl.ts
@@ -6,11 +6,7 @@
import { runFilesInContext, type IOptions } from 'js-slang';
import context from 'js-slang/context';
-import {
- COLOR_ERROR_MESSAGE,
- COLOR_RUN_CODE_RESULT,
- DEFAULT_EDITOR_HEIGHT
-} from './config';
+import { COLOR_RUN_CODE_RESULT, COLOR_ERROR_MESSAGE, DEFAULT_EDITOR_HEIGHT } from './config';
import { default_js_slang } from './functions';
export class ProgrammableRepl {
@@ -63,12 +59,7 @@ export class ProgrammableRepl {
COLOR_ERROR_MESSAGE
);
} else {
- this.pushOutputString(
- `Line ${exception.location.start.line.toString()}: ${
- exception.error?.message
- }`,
- COLOR_ERROR_MESSAGE
- );
+ this.pushOutputString(`Line ${exception.location.start.line.toString()}: ${exception.error?.message}`, COLOR_ERROR_MESSAGE);
}
this.reRenderTab();
return;
@@ -87,11 +78,7 @@ export class ProgrammableRepl {
}
// Rich text output method allow output strings to have html tags and css styles.
- pushOutputString(
- content: string,
- textColor: string,
- outputMethod: string = 'plaintext'
- ) {
+ pushOutputString(content: string, textColor: string, outputMethod: string = 'plaintext') {
const tmp = {
content:
content === undefined
@@ -113,9 +100,7 @@ export class ProgrammableRepl {
developmentLog(breakpointLine);
});
- this._editorInstance.setOptions({
- fontSize: `${this.customizedEditorProps.fontSize.toString()}pt`
- });
+ this._editorInstance.setOptions({ fontSize: `${this.customizedEditorProps.fontSize.toString()}pt` });
}
richDisplayInternal(pair_rich_text) {
@@ -130,13 +115,7 @@ export class ProgrammableRepl {
for (let i = 1; i < 7; i++) {
const char = htmlColor[i];
developmentLog(` ${char}`);
- if (
- !(
- (char >= '0' && char <= '9') ||
- (char >= 'A' && char <= 'F') ||
- (char >= 'a' && char <= 'f')
- )
- ) {
+ if (!((char >= '0' && char <= '9') || (char >= 'A' && char <= 'F') || (char >= 'a' && char <= 'f'))) {
return false;
}
}
@@ -147,17 +126,13 @@ export class ProgrammableRepl {
// There MUST be a safe check on users' strings, because users may insert something that can be interpreted as executable JavaScript code when outputing rich text.
const safeCheckResult = thisInstance.userStringSafeCheck(param);
if (safeCheckResult !== 'safe') {
- throw new Error(
- `For safety matters, the character/word ${safeCheckResult} is not allowed in rich text output. Please remove it or use plain text output mode and try again.`
- );
+ throw new Error(`For safety matters, the character/word ${safeCheckResult} is not allowed in rich text output. Please remove it or use plain text output mode and try again.`);
}
developmentLog(head(param));
return `">${param}`;
}
if (!is_pair(param)) {
- throw new Error(
- `Unexpected data type ${typeof param} when processing rich text. It should be a pair.`
- );
+ throw new Error(`Unexpected data type ${typeof (param)} when processing rich text. It should be a pair.`);
} else {
const pairStyleToCssStyle: { [pairStyle: string]: string } = {
bold: 'font-weight:bold;',
@@ -168,12 +143,8 @@ export class ProgrammableRepl {
gigantic: 'font-size: 50px;',
underline: 'text-decoration: underline;'
};
- if (typeof tail(param) !== 'string') {
- throw new Error(
- `The tail in style pair should always be a string, but got ${typeof tail(
- param
- )}.`
- );
+ if (typeof (tail(param)) !== 'string') {
+ throw new Error(`The tail in style pair should always be a string, but got ${typeof (tail(param))}.`);
}
let style = '';
if (tail(param).substring(0, 3) === 'clr') {
@@ -183,29 +154,19 @@ export class ProgrammableRepl {
else throw new Error('Error when decoding rich text color data');
const colorHex = tail(param).substring(4);
if (!checkColorStringValidity(colorHex)) {
- throw new Error(
- `Invalid html color string ${colorHex}. It should start with # and followed by 6 characters representing a hex number.`
- );
+ throw new Error(`Invalid html color string ${colorHex}. It should start with # and followed by 6 characters representing a hex number.`);
}
style = `${prefix + colorHex};`;
} else {
style = pairStyleToCssStyle[tail(param)];
if (style === undefined) {
- throw new Error(
- `Found undefined style ${tail(
- param
- )} during processing rich text.`
- );
+ throw new Error(`Found undefined style ${tail(param)} during processing rich text.`);
}
}
return style + recursiveHelper(thisInstance, head(param));
}
}
- this.pushOutputString(
- `',
- 'script',
- 'javascript',
- 'eval',
- 'document',
- 'window',
- 'console',
- 'location'
- ];
+ const forbiddenWords = ['\\', '<', '>', 'script', 'javascript', 'eval', 'document', 'window', 'console', 'location'];
for (const word of forbiddenWords) {
if (tmp.indexOf(word) !== -1) {
return word;
@@ -253,54 +203,28 @@ export class ProgrammableRepl {
'/ReplModuleUserCode.js': code
};
- runFilesInContext(
- sourceFile,
- '/ReplModuleUserCode.js',
- context,
- options
- ).then(evalResult => {
- if (
- evalResult.status === 'suspended' ||
- evalResult.status === 'suspended-cse-eval'
- ) {
- throw new Error('This should not happen');
- }
- if (evalResult.status !== 'error') {
- this.pushOutputString(
- 'js-slang program finished with value:',
- COLOR_RUN_CODE_RESULT
- );
- // Here must use plain text output mode because evalResult.value contains strings from the users.
- this.pushOutputString(
- evalResult.value === undefined
- ? 'undefined'
- : evalResult.value.toString(),
- COLOR_RUN_CODE_RESULT
- );
- } else {
- const errors = context.errors;
- console.log(errors);
- const errorCount = errors.length;
- for (let i = 0; i < errorCount; i++) {
- const error = errors[i];
- if (
- error.explain().indexOf('Name repl_display not declared.') !== -1
- ) {
- this.pushOutputString(
- '[Error] It seems that you haven\'t import the function "repl_display" correctly when calling "set_evaluator" in Source Academy\'s main editor.',
- COLOR_ERROR_MESSAGE
- );
- } else
- this.pushOutputString(
- `Line ${error.location.start.line}: ${
- error.type
- } Error: ${error.explain()} (${error.elaborate()})`,
- COLOR_ERROR_MESSAGE
- );
+ runFilesInContext(sourceFile, '/ReplModuleUserCode.js', context, options)
+ .then((evalResult) => {
+ if (evalResult.status === 'suspended' || evalResult.status === 'suspended-cse-eval') {
+ throw new Error('This should not happen');
}
- }
- this.reRenderTab();
- });
+ if (evalResult.status !== 'error') {
+ this.pushOutputString('js-slang program finished with value:', COLOR_RUN_CODE_RESULT);
+ // Here must use plain text output mode because evalResult.value contains strings from the users.
+ this.pushOutputString(evalResult.value === undefined ? 'undefined' : evalResult.value.toString(), COLOR_RUN_CODE_RESULT);
+ } else {
+ const errors = context.errors;
+ console.log(errors);
+ const errorCount = errors.length;
+ for (let i = 0; i < errorCount; i++) {
+ const error = errors[i];
+ if (error.explain().indexOf('Name repl_display not declared.') !== -1) {
+ this.pushOutputString('[Error] It seems that you haven\'t import the function "repl_display" correctly when calling "set_evaluator" in Source Academy\'s main editor.', COLOR_ERROR_MESSAGE);
+ } else this.pushOutputString(`Line ${error.location.start.line}: ${error.type} Error: ${error.explain()} (${error.elaborate()})`, COLOR_ERROR_MESSAGE);
+ }
+ }
+ this.reRenderTab();
+ });
return 'Async run in js-slang';
}
@@ -314,23 +238,14 @@ export class ProgrammableRepl {
}
saveEditorContent() {
- localStorage.setItem(
- 'programmable_repl_saved_editor_code',
- this.userCodeInEditor.toString()
- );
+ localStorage.setItem('programmable_repl_saved_editor_code', this.userCodeInEditor.toString());
this.pushOutputString('Saved', 'lightgreen');
- this.pushOutputString(
- "The saved code is stored locally in your browser. You may lose the saved code if you clear browser data or use another device. ",
- 'gray',
- 'richtext'
- );
+ this.pushOutputString('The saved code is stored locally in your browser. You may lose the saved code if you clear browser data or use another device. ', 'gray', 'richtext');
this.reRenderTab();
}
private getSavedEditorContent() {
- const savedContent = localStorage.getItem(
- 'programmable_repl_saved_editor_code'
- );
+ const savedContent = localStorage.getItem('programmable_repl_saved_editor_code');
if (savedContent === null) return '';
return savedContent;
}
diff --git a/src/bundles/unity_academy/UnityAcademy.tsx b/src/bundles/unity_academy/UnityAcademy.tsx
index c18488878..cdf4391da 100644
--- a/src/bundles/unity_academy/UnityAcademy.tsx
+++ b/src/bundles/unity_academy/UnityAcademy.tsx
@@ -9,13 +9,8 @@ import { Button } from '@blueprintjs/core';
import { IconNames } from '@blueprintjs/icons';
import React from 'react';
import ReactDOM from 'react-dom';
-import {
- Vector3,
- normalizeVector,
- pointDistance,
- zeroVector
-} from './UnityAcademyMaths';
-import { BUILD_NAME, UNITY_ACADEMY_BACKEND_URL } from './config';
+import { Vector3, normalizeVector, zeroVector, pointDistance } from './UnityAcademyMaths';
+import { UNITY_ACADEMY_BACKEND_URL, BUILD_NAME } from './config';
type Transform = {
position: Vector3;
@@ -185,9 +180,7 @@ class UnityAcademyJsInteropContext {
// private unityConfig : any;
public unityInstance: any;
private unityContainerElement: HTMLElement | null;
- private studentGameObjectStorage: {
- [gameObjectIdentifier: string]: StudentGameObject;
- }; // [get by interop]
+ private studentGameObjectStorage: { [gameObjectIdentifier: string]: StudentGameObject }; // [get by interop]
private prefabInfo: any;
private gameObjectIdentifierSerialCounter = 0;
private studentActionQueue: any; // [get / clear by interop]
@@ -206,10 +199,7 @@ class UnityAcademyJsInteropContext {
constructor() {
this.unityInstance = null;
this.unityContainerElement = document.getElementById('unity_container');
- if (
- this.unityContainerElement === undefined ||
- this.unityContainerElement === null
- ) {
+ if (this.unityContainerElement === undefined || this.unityContainerElement === null) {
this.unityContainerElement = document.createElement('div');
this.unityContainerElement.id = 'unity_container';
}
@@ -263,9 +253,7 @@ class UnityAcademyJsInteropContext {
const canvas = document.querySelector('#unity-canvas');
const unity_load_info = document.querySelector('#unity_load_info');
createUnityInstance(canvas, UNITY_CONFIG, progress => {
- unity_load_info!.innerHTML = `Loading Unity Academy ( ${Math.floor(
- progress * 100
- )}% )`;
+ unity_load_info!.innerHTML = `Loading Unity Academy ( ${Math.floor(progress * 100)}% )`;
})
.then(unityInstance => {
this.unityInstance = unityInstance;
@@ -296,19 +284,13 @@ class UnityAcademyJsInteropContext {
if (toShow) {
(this.unityContainerElement as any).style.visibility = 'visible';
if (this.unityInstance !== null) {
- this.unityInstance[sendMessageFunctionName](
- 'GameManager',
- 'WakeUpApplication'
- );
+ this.unityInstance[sendMessageFunctionName]('GameManager', 'WakeUpApplication');
}
} else {
(this.unityContainerElement as any).style.visibility = 'hidden';
// Make Unity Academy Application sleep to conserve resources (pause rendering, etc)
if (this.unityInstance !== null) {
- this.unityInstance[sendMessageFunctionName](
- 'GameManager',
- 'DoApplicationSleep'
- );
+ this.unityInstance[sendMessageFunctionName]('GameManager', 'DoApplicationSleep');
}
}
const unityCanvas = document.getElementById('unity-canvas') as any;
@@ -322,11 +304,7 @@ class UnityAcademyJsInteropContext {
terminate() {
if (this.unityInstance === null) return;
- if (
- !confirm(
- 'Do you really hope to terminate the current Unity Academy instance? If so, everything need to reload when you use Unity Academy again.'
- )
- ) {
+ if (!confirm('Do you really hope to terminate the current Unity Academy instance? If so, everything need to reload when you use Unity Academy again.')) {
return;
}
const quitFunctionName = 'Quit';
@@ -334,13 +312,10 @@ class UnityAcademyJsInteropContext {
this.unityInstance = null;
this.resetModuleData();
this.setShowUnityComponent(0);
- const canvasContext = (document.querySelector(
- '#unity-canvas'
- ) as HTMLCanvasElement)!.getContext('webgl2');
+ const canvasContext = (document.querySelector('#unity-canvas') as HTMLCanvasElement)!.getContext('webgl2');
canvasContext!.clearColor(0, 0, 0, 0);
canvasContext!.clear(canvasContext!.COLOR_BUFFER_BIT);
- document.querySelector('#unity_load_info')!.innerHTML =
- 'Unity Academy app has been terminated. Please rerun your program with init_unity_academy_3d or init_unity_academy_2d for re-initialization.';
+ document.querySelector('#unity_load_info')!.innerHTML = 'Unity Academy app has been terminated. Please rerun your program with init_unity_academy_3d or init_unity_academy_2d for re-initialization.';
}
reset() {
@@ -348,10 +323,7 @@ class UnityAcademyJsInteropContext {
if (this.unityInstance !== null) {
const sendMessageFunctionName = 'SendMessage';
// Reset Unity Academy app
- this.unityInstance[sendMessageFunctionName](
- 'GameManager',
- 'ResetSession'
- );
+ this.unityInstance[sendMessageFunctionName]('GameManager', 'ResetSession');
}
}
@@ -383,14 +355,8 @@ class UnityAcademyJsInteropContext {
}
getUserAgreementStatus(): string {
- const agreedUserAgreementVersion = localStorage.getItem(
- 'unity_academy_agreed_user_agreement_version'
- );
- if (
- agreedUserAgreementVersion === null ||
- agreedUserAgreementVersion === 'unagreed' ||
- agreedUserAgreementVersion === 'unknown'
- ) {
+ const agreedUserAgreementVersion = localStorage.getItem('unity_academy_agreed_user_agreement_version');
+ if (agreedUserAgreementVersion === null || agreedUserAgreementVersion === 'unagreed' || agreedUserAgreementVersion === 'unknown') {
return 'unagreed';
}
if (this.latestUserAgreementVersion === 'unknown') {
@@ -404,15 +370,9 @@ class UnityAcademyJsInteropContext {
setUserAgreementStatus(agree: boolean): void {
if (agree) {
- localStorage.setItem(
- 'unity_academy_agreed_user_agreement_version',
- this.latestUserAgreementVersion
- );
+ localStorage.setItem('unity_academy_agreed_user_agreement_version', this.latestUserAgreementVersion);
} else {
- localStorage.setItem(
- 'unity_academy_agreed_user_agreement_version',
- 'unagreed'
- );
+ localStorage.setItem('unity_academy_agreed_user_agreement_version', 'unagreed');
}
}
@@ -426,16 +386,12 @@ class UnityAcademyJsInteropContext {
}
}
if (!prefabExists) {
- throw new Error(
- `Unknown prefab name: '${prefabName}'. Please refer to this prefab list at [ ${UNITY_ACADEMY_BACKEND_URL}webgl_assetbundles/prefab_info.html ] for all available prefab names.`
- );
+ throw new Error(`Unknown prefab name: '${prefabName}'. Please refer to this prefab list at [ ${UNITY_ACADEMY_BACKEND_URL}webgl_assetbundles/prefab_info.html ] for all available prefab names.`);
}
const gameObjectIdentifier = `${prefabName}_${this.gameObjectIdentifierSerialCounter}`;
this.gameObjectIdentifierSerialCounter++;
this.makeGameObjectDataStorage(gameObjectIdentifier);
- this.dispatchStudentAction(
- `instantiate|${prefabName}|${gameObjectIdentifier}`
- );
+ this.dispatchStudentAction(`instantiate|${prefabName}|${gameObjectIdentifier}`);
return new GameObjectIdentifier(gameObjectIdentifier);
}
@@ -445,9 +401,7 @@ class UnityAcademyJsInteropContext {
const gameObjectIdentifier = `2DSprite_${this.gameObjectIdentifierSerialCounter}`;
this.gameObjectIdentifierSerialCounter++;
this.makeGameObjectDataStorage(gameObjectIdentifier);
- this.dispatchStudentAction(
- `instantiate2DSpriteUrl|${sourceImageUrl}|${gameObjectIdentifier}`
- );
+ this.dispatchStudentAction(`instantiate2DSpriteUrl|${sourceImageUrl}|${gameObjectIdentifier}`);
return new GameObjectIdentifier(gameObjectIdentifier);
}
@@ -455,9 +409,7 @@ class UnityAcademyJsInteropContext {
const gameObjectIdentifier = `EmptyGameObject_${this.gameObjectIdentifierSerialCounter}`;
this.gameObjectIdentifierSerialCounter++;
this.makeGameObjectDataStorage(gameObjectIdentifier);
- this.dispatchStudentAction(
- `instantiateEmptyGameObject|${gameObjectIdentifier}`
- );
+ this.dispatchStudentAction(`instantiateEmptyGameObject|${gameObjectIdentifier}`);
return new GameObjectIdentifier(gameObjectIdentifier);
}
@@ -473,16 +425,12 @@ class UnityAcademyJsInteropContext {
isLooping: false,
isPlaying: false
};
- this.dispatchStudentAction(
- `instantiateAudioSourceGameObject|${gameObjectIdentifier}|${audioClipIdentifier.audioClipInternalName}`
- );
+ this.dispatchStudentAction(`instantiateAudioSourceGameObject|${gameObjectIdentifier}|${audioClipIdentifier.audioClipInternalName}`);
return new GameObjectIdentifier(gameObjectIdentifier);
}
destroyGameObjectInternal(gameObjectIdentifier: GameObjectIdentifier): void {
- this.dispatchStudentAction(
- `destroyGameObject|${gameObjectIdentifier.gameObjectIdentifier}`
- );
+ this.dispatchStudentAction(`destroyGameObject|${gameObjectIdentifier.gameObjectIdentifier}`);
}
private makeGameObjectDataStorage(gameObjectIdentifier: string) {
@@ -504,31 +452,20 @@ class UnityAcademyJsInteropContext {
};
}
- getStudentGameObject(
- gameObjectIdentifier: GameObjectIdentifier
- ): StudentGameObject {
- const retVal =
- this.studentGameObjectStorage[gameObjectIdentifier.gameObjectIdentifier];
+ getStudentGameObject(gameObjectIdentifier: GameObjectIdentifier): StudentGameObject {
+ const retVal = this.studentGameObjectStorage[gameObjectIdentifier.gameObjectIdentifier];
if (retVal === undefined) {
- throw new Error(
- `Could not find GameObject with identifier ${gameObjectIdentifier}`
- );
+ throw new Error(`Could not find GameObject with identifier ${gameObjectIdentifier}`);
}
return retVal;
}
- setStartInternal(
- gameObjectIdentifier: GameObjectIdentifier,
- startFunction: Function
- ): void {
+ setStartInternal(gameObjectIdentifier: GameObjectIdentifier, startFunction: Function): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.startMethod = startFunction;
}
- setUpdateInternal(
- gameObjectIdentifier: GameObjectIdentifier,
- updateFunction: Function
- ): void {
+ setUpdateInternal(gameObjectIdentifier: GameObjectIdentifier, updateFunction: Function): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.updateMethod = updateFunction;
}
@@ -537,30 +474,17 @@ class UnityAcademyJsInteropContext {
this.studentActionQueue[this.studentActionQueue.length] = action;
}
- getGameObjectIdentifierForPrimitiveGameObject(
- name: string
- ): GameObjectIdentifier {
+ getGameObjectIdentifierForPrimitiveGameObject(name: string): GameObjectIdentifier {
const propName = 'gameObjectIdentifierWrapperClass';
return new this[propName](name);
}
- getGameObjectTransformProp(
- propName: string,
- gameObjectIdentifier: GameObjectIdentifier
- ): Vector3 {
+ getGameObjectTransformProp(propName: string, gameObjectIdentifier: GameObjectIdentifier): Vector3 {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
- return new Vector3(
- gameObject.transform[propName].x,
- gameObject.transform[propName].y,
- gameObject.transform[propName].z
- );
+ return new Vector3(gameObject.transform[propName].x, gameObject.transform[propName].y, gameObject.transform[propName].z);
}
- setGameObjectTransformProp(
- propName: string,
- gameObjectIdentifier: GameObjectIdentifier,
- newValue: Vector3
- ): void {
+ setGameObjectTransformProp(propName: string, gameObjectIdentifier: GameObjectIdentifier, newValue: Vector3): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.transform[propName].x = newValue.x;
gameObject.transform[propName].y = newValue.y;
@@ -571,20 +495,14 @@ class UnityAcademyJsInteropContext {
return this.deltaTime;
}
- translateWorldInternal(
- gameObjectIdentifier: GameObjectIdentifier,
- deltaPosition: Vector3
- ): void {
+ translateWorldInternal(gameObjectIdentifier: GameObjectIdentifier, deltaPosition: Vector3): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.transform.position.x += deltaPosition.x;
gameObject.transform.position.y += deltaPosition.y;
gameObject.transform.position.z += deltaPosition.z;
}
- translateLocalInternal(
- gameObjectIdentifier: GameObjectIdentifier,
- deltaPosition: Vector3
- ): void {
+ translateLocalInternal(gameObjectIdentifier: GameObjectIdentifier, deltaPosition: Vector3): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const rotation = gameObject.transform.rotation;
@@ -594,19 +512,10 @@ class UnityAcademyJsInteropContext {
const rz = (rotation.z * Math.PI) / 180;
const cos = Math.cos;
const sin = Math.sin;
- const rotationMatrix = [
- [cos(ry) * cos(rz), -cos(ry) * sin(rz), sin(ry)],
- [
- cos(rx) * sin(rz) + sin(rx) * sin(ry) * cos(rz),
- cos(rx) * cos(rz) - sin(rx) * sin(ry) * sin(rz),
- -sin(rx) * cos(ry)
- ],
- [
- sin(rx) * sin(rz) - cos(rx) * sin(ry) * cos(rz),
- cos(rx) * sin(ry) * sin(rz) + sin(rx) * cos(rz),
- cos(rx) * cos(ry)
- ]
- ];
+ const rotationMatrix
+ = [[cos(ry) * cos(rz), -cos(ry) * sin(rz), sin(ry)],
+ [cos(rx) * sin(rz) + sin(rx) * sin(ry) * cos(rz), cos(rx) * cos(rz) - sin(rx) * sin(ry) * sin(rz), -sin(rx) * cos(ry)],
+ [sin(rx) * sin(rz) - cos(rx) * sin(ry) * cos(rz), cos(rx) * sin(ry) * sin(rz) + sin(rx) * cos(rz), cos(rx) * cos(ry)]];
const finalWorldTranslateVector = [
rotationMatrix[0][0] * deltaPosition.x +
rotationMatrix[0][1] * deltaPosition.y +
@@ -623,10 +532,7 @@ class UnityAcademyJsInteropContext {
gameObject.transform.position.z += finalWorldTranslateVector[2];
}
- lookAtPositionInternal(
- gameObjectIdentifier: GameObjectIdentifier,
- position: Vector3
- ): void {
+ lookAtPositionInternal(gameObjectIdentifier: GameObjectIdentifier, position: Vector3): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const deltaVector = normalizeVector(
new Vector3(
@@ -642,73 +548,44 @@ class UnityAcademyJsInteropContext {
gameObject.transform.rotation.z = 0;
}
- gameObjectDistanceInternal(
- gameObjectIdentifier_A: GameObjectIdentifier,
- gameObjectIdentifier_B: GameObjectIdentifier
- ): number {
+ gameObjectDistanceInternal(gameObjectIdentifier_A: GameObjectIdentifier, gameObjectIdentifier_B: GameObjectIdentifier): number {
const gameObjectA = this.getStudentGameObject(gameObjectIdentifier_A);
const gameObjectB = this.getStudentGameObject(gameObjectIdentifier_B);
- return pointDistance(
- gameObjectA.transform.position,
- gameObjectB.transform.position
- );
+ return pointDistance(gameObjectA.transform.position, gameObjectB.transform.position);
}
- rotateWorldInternal(
- gameObjectIdentifier: GameObjectIdentifier,
- angles: Vector3
- ): void {
+ rotateWorldInternal(gameObjectIdentifier: GameObjectIdentifier, angles: Vector3): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.transform.rotation.x += angles.x;
gameObject.transform.rotation.y += angles.y;
gameObject.transform.rotation.z += angles.z;
}
- copyTransformPropertiesInternal(
- propName: string,
- from: GameObjectIdentifier,
- to: GameObjectIdentifier,
- deltaValues: Vector3
- ): void {
+ copyTransformPropertiesInternal(propName: string, from: GameObjectIdentifier, to: GameObjectIdentifier, deltaValues: Vector3): void {
const fromGameObject = this.getStudentGameObject(from);
const toGameObject = this.getStudentGameObject(to);
const deltaX = deltaValues.x;
const deltaY = deltaValues.y;
const deltaZ = deltaValues.z;
- if (Math.abs(deltaX) !== 999999)
- toGameObject.transform[propName].x =
- fromGameObject.transform[propName].x + deltaX;
- if (Math.abs(deltaY) !== 999999)
- toGameObject.transform[propName].y =
- fromGameObject.transform[propName].y + deltaY;
- if (Math.abs(deltaZ) !== 999999)
- toGameObject.transform[propName].z =
- fromGameObject.transform[propName].z + deltaZ;
+ if (Math.abs(deltaX) !== 999999) toGameObject.transform[propName].x = fromGameObject.transform[propName].x + deltaX;
+ if (Math.abs(deltaY) !== 999999) toGameObject.transform[propName].y = fromGameObject.transform[propName].y + deltaY;
+ if (Math.abs(deltaZ) !== 999999) toGameObject.transform[propName].z = fromGameObject.transform[propName].z + deltaZ;
}
getKeyState(keyCode: string): number {
return this.input.keyboardInputInfo[keyCode];
}
- playAnimatorStateInternal(
- gameObjectIdentifier: GameObjectIdentifier,
- animatorStateName: string
- ) {
+ playAnimatorStateInternal(gameObjectIdentifier: GameObjectIdentifier, animatorStateName: string) {
this.getStudentGameObject(gameObjectIdentifier); // Just to check whether the game object identifier is valid or not.
- this.dispatchStudentAction(
- `playAnimatorState|${gameObjectIdentifier.gameObjectIdentifier}|${animatorStateName}`
- );
+ this.dispatchStudentAction(`playAnimatorState|${gameObjectIdentifier.gameObjectIdentifier}|${animatorStateName}`);
}
applyRigidbodyInternal(gameObjectIdentifier: GameObjectIdentifier) {
- console.log(
- `Applying rigidbody to GameObject ${gameObjectIdentifier.gameObjectIdentifier}`
- );
+ console.log(`Applying rigidbody to GameObject ${gameObjectIdentifier.gameObjectIdentifier}`);
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
if (gameObject.rigidbody !== null) {
- throw new Error(
- `Trying to duplicately apply rigidbody on GameObject ${gameObjectIdentifier.gameObjectIdentifier}`
- );
+ throw new Error(`Trying to duplicately apply rigidbody on GameObject ${gameObjectIdentifier.gameObjectIdentifier}`);
}
gameObject.rigidbody = {
velocity: zeroVector(),
@@ -718,37 +595,21 @@ class UnityAcademyJsInteropContext {
drag: 0,
angularDrag: 0.05
};
- this.dispatchStudentAction(
- `applyRigidbody|${gameObjectIdentifier.gameObjectIdentifier}`
- );
+ this.dispatchStudentAction(`applyRigidbody|${gameObjectIdentifier.gameObjectIdentifier}`);
}
private getRigidbody(gameObject: StudentGameObject): RigidbodyData {
- if (gameObject.rigidbody === null)
- throw new Error(
- 'You must call apply_rigidbody on the game object before using this physics function!'
- );
+ if (gameObject.rigidbody === null) throw new Error('You must call apply_rigidbody on the game object before using this physics function!');
return gameObject.rigidbody;
}
- getRigidbodyVelocityVector3Prop(
- propName: string,
- gameObjectIdentifier: GameObjectIdentifier
- ): Vector3 {
+ getRigidbodyVelocityVector3Prop(propName: string, gameObjectIdentifier: GameObjectIdentifier): Vector3 {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const rigidbody = this.getRigidbody(gameObject);
- return new Vector3(
- rigidbody[propName].x,
- rigidbody[propName].y,
- rigidbody[propName].z
- );
+ return new Vector3(rigidbody[propName].x, rigidbody[propName].y, rigidbody[propName].z);
}
- setRigidbodyVelocityVector3Prop(
- propName: string,
- gameObjectIdentifier: GameObjectIdentifier,
- newValue: Vector3
- ): void {
+ setRigidbodyVelocityVector3Prop(propName: string, gameObjectIdentifier: GameObjectIdentifier, newValue: Vector3): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const rigidbody = this.getRigidbody(gameObject);
rigidbody[propName].x = newValue.x;
@@ -756,73 +617,43 @@ class UnityAcademyJsInteropContext {
rigidbody[propName].z = newValue.z;
}
- getRigidbodyNumericalProp(
- propName: string,
- gameObjectIdentifier: GameObjectIdentifier
- ): number {
+ getRigidbodyNumericalProp(propName: string, gameObjectIdentifier: GameObjectIdentifier): number {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const rigidbody = this.getRigidbody(gameObject);
return rigidbody[propName];
}
- setRigidbodyNumericalProp(
- propName: string,
- gameObjectIdentifier: GameObjectIdentifier,
- value: number
- ): void {
+ setRigidbodyNumericalProp(propName: string, gameObjectIdentifier: GameObjectIdentifier, value: number): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const rigidbody = this.getRigidbody(gameObject);
rigidbody[propName] = value;
}
- setUseGravityInternal(
- gameObjectIdentifier: GameObjectIdentifier,
- useGravity: boolean
- ): void {
+ setUseGravityInternal(gameObjectIdentifier: GameObjectIdentifier, useGravity: boolean): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const rigidbody = this.getRigidbody(gameObject);
rigidbody.useGravity = useGravity;
}
- addImpulseForceInternal(
- gameObjectIdentifier: GameObjectIdentifier,
- force: Vector3
- ): void {
- this.dispatchStudentAction(
- `addImpulseForce|${
- gameObjectIdentifier.gameObjectIdentifier
- }|${force.x.toString()}|${force.y.toString()}|${force.z.toString()}`
- );
+ addImpulseForceInternal(gameObjectIdentifier: GameObjectIdentifier, force: Vector3): void {
+ this.dispatchStudentAction(`addImpulseForce|${gameObjectIdentifier.gameObjectIdentifier}|${force.x.toString()}|${force.y.toString()}|${force.z.toString()}`);
}
- removeColliderComponentsInternal(
- gameObjectIdentifier: GameObjectIdentifier
- ): void {
- this.dispatchStudentAction(
- `removeColliderComponents|${gameObjectIdentifier.gameObjectIdentifier}`
- );
+ removeColliderComponentsInternal(gameObjectIdentifier: GameObjectIdentifier): void {
+ this.dispatchStudentAction(`removeColliderComponents|${gameObjectIdentifier.gameObjectIdentifier}`);
}
- setOnCollisionEnterInternal(
- gameObjectIdentifier: GameObjectIdentifier,
- eventFunction: Function
- ) {
+ setOnCollisionEnterInternal(gameObjectIdentifier: GameObjectIdentifier, eventFunction: Function) {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.onCollisionEnterMethod = eventFunction;
}
- setOnCollisionStayInternal(
- gameObjectIdentifier: GameObjectIdentifier,
- eventFunction: Function
- ) {
+ setOnCollisionStayInternal(gameObjectIdentifier: GameObjectIdentifier, eventFunction: Function) {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.onCollisionStayMethod = eventFunction;
}
- setOnCollisionExitInternal(
- gameObjectIdentifier: GameObjectIdentifier,
- eventFunction: Function
- ) {
+ setOnCollisionExitInternal(gameObjectIdentifier: GameObjectIdentifier, eventFunction: Function) {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.onCollisionExitMethod = eventFunction;
}
@@ -850,14 +681,7 @@ class UnityAcademyJsInteropContext {
this.guiData.push(newLabel);
}
- onGUI_Button(
- text: string,
- x: number,
- y: number,
- width: number,
- height: number,
- onClick: Function
- ): void {
+ onGUI_Button(text: string, x: number, y: number, width: number, height: number, onClick: Function): void {
// Temporarily use "<%7C>" to replace all '|' characters as '|' is used as the data separator in GUI data in Unity Academy Embedded Frontend.
// In Unity Academy Embedded Frontend, "<%7C>" will be replaced back to '|' when displaying the text in GUI
text = text.replaceAll('|', '<%7C>');
@@ -873,22 +697,15 @@ class UnityAcademyJsInteropContext {
this.guiData.push(newButton);
}
- loadAudioClipInternal(
- audioClipUrl: string,
- audioType: string
- ): AudioClipIdentifier {
+ loadAudioClipInternal(audioClipUrl: string, audioType: string): AudioClipIdentifier {
const audioClipInternalName = `AudioClip_${this.audioClipIdentifierSerialCounter}`;
this.audioClipIdentifierSerialCounter++;
this.audioClipStorage[this.audioClipStorage.length] = audioClipInternalName;
- this.dispatchStudentAction(
- `loadAudioClip|${audioClipUrl}|${audioType}|${audioClipInternalName}`
- );
+ this.dispatchStudentAction(`loadAudioClip|${audioClipUrl}|${audioType}|${audioClipInternalName}`);
return new AudioClipIdentifier(audioClipInternalName);
}
- private getAudioSourceData(
- gameObjectIdentifier: GameObjectIdentifier
- ): AudioSourceData {
+ private getAudioSourceData(gameObjectIdentifier: GameObjectIdentifier): AudioSourceData {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
const retVal = gameObject.audioSource;
if (retVal === null) {
@@ -897,11 +714,7 @@ class UnityAcademyJsInteropContext {
return retVal;
}
- setAudioSourceProp(
- propName: string,
- audioSrc: GameObjectIdentifier,
- value: any
- ): void {
+ setAudioSourceProp(propName: string, audioSrc: GameObjectIdentifier, value: any): void {
const audioSourceData = this.getAudioSourceData(audioSrc);
audioSourceData[propName] = value;
}
@@ -925,19 +738,12 @@ class UnityAcademyJsInteropContext {
this.targetFrameRate = newTargetFrameRate;
}
- setCustomPropertyInternal(
- gameObjectIdentifier: GameObjectIdentifier,
- propName: string,
- value: any
- ): void {
+ setCustomPropertyInternal(gameObjectIdentifier: GameObjectIdentifier, propName: string, value: any): void {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
gameObject.customProperties[propName] = value;
}
- getCustomPropertyInternal(
- gameObjectIdentifier: GameObjectIdentifier,
- propName: string
- ): any {
+ getCustomPropertyInternal(gameObjectIdentifier: GameObjectIdentifier, propName: string): any {
const gameObject = this.getStudentGameObject(gameObjectIdentifier);
return gameObject.customProperties[propName];
}
@@ -951,9 +757,7 @@ export function initializeModule(dimensionMode: string) {
let instance = getInstance();
if (instance !== undefined) {
if (!instance.isUnityInstanceReady()) {
- throw new Error(
- "Unity Academy Embedded Frontend is not ready to accept a new Source program now, please try again later. If you just successfully ran your code before but haven't open Unity Academy Embedded Frontend before running your code again, please try open the frontend first. If this error persists or you can not open Unity Academy Embedded Frontend, please try to refresh your browser's page."
- );
+ throw new Error('Unity Academy Embedded Frontend is not ready to accept a new Source program now, please try again later. If you just successfully ran your code before but haven\'t open Unity Academy Embedded Frontend before running your code again, please try open the frontend first. If this error persists or you can not open Unity Academy Embedded Frontend, please try to refresh your browser\'s page.');
}
if (instance.unityInstance === null) {
instance.reloadUnityAcademyInstanceAfterTermination();
diff --git a/src/bundles/unity_academy/UnityAcademyMaths.ts b/src/bundles/unity_academy/UnityAcademyMaths.ts
index 75d5a1285..17ff3d679 100644
--- a/src/bundles/unity_academy/UnityAcademyMaths.ts
+++ b/src/bundles/unity_academy/UnityAcademyMaths.ts
@@ -21,15 +21,9 @@ export class Vector3 {
export function checkVector3Parameter(parameter: any): void {
if (typeof parameter !== 'object') {
- throw new Error(
- `The given parameter is not a valid 3D vector! Wrong parameter type: ${typeof parameter}`
- );
+ throw new Error(`The given parameter is not a valid 3D vector! Wrong parameter type: ${typeof parameter}`);
}
- if (
- typeof parameter.x !== 'number' ||
- typeof parameter.y !== 'number' ||
- typeof parameter.z !== 'number'
- ) {
+ if (typeof parameter.x !== 'number' || typeof parameter.y !== 'number' || typeof parameter.z !== 'number') {
throw new Error('The given parameter is not a valid 3D vector!');
}
}
@@ -91,9 +85,5 @@ export function zeroVector(): Vector3 {
}
export function pointDistance(pointA: Vector3, pointB: Vector3): number {
- return Math.sqrt(
- (pointB.x - pointA.x) ** 2 +
- (pointB.y - pointA.y) ** 2 +
- (pointB.z - pointA.z) ** 2
- );
+ return Math.sqrt((pointB.x - pointA.x) ** 2 + (pointB.y - pointA.y) ** 2 + (pointB.z - pointA.z) ** 2);
}
diff --git a/src/bundles/unity_academy/functions.ts b/src/bundles/unity_academy/functions.ts
index 34b8952c4..3ae98c124 100644
--- a/src/bundles/unity_academy/functions.ts
+++ b/src/bundles/unity_academy/functions.ts
@@ -4,25 +4,10 @@
* @author Wang Zihan
*/
+import { initializeModule, getInstance, type GameObjectIdentifier, type AudioClipIdentifier } from './UnityAcademy';
import {
- getInstance,
- initializeModule,
- type AudioClipIdentifier,
- type GameObjectIdentifier
-} from './UnityAcademy';
-import {
- addVectors,
- checkVector3Parameter,
- crossProduct,
- dotProduct,
- makeVector3D,
- normalizeVector,
- pointDistance,
- scaleVector,
- vectorDifference,
- vectorMagnitude,
- zeroVector,
- type Vector3
+ type Vector3, checkVector3Parameter, makeVector3D, scaleVector, addVectors, vectorDifference, dotProduct,
+ crossProduct, normalizeVector, vectorMagnitude, zeroVector, pointDistance
} from './UnityAcademyMaths';
/**
@@ -51,24 +36,16 @@ export function init_unity_academy_3d(): void {
function checkUnityAcademyExistence() {
if (getInstance() === undefined) {
- throw new Error(
- 'Unity module is not initialized, please call init_unity_academy_3d / init_unity_academy_2d first before calling this function'
- );
+ throw new Error('Unity module is not initialized, please call init_unity_academy_3d / init_unity_academy_2d first before calling this function');
}
}
function checkIs2DMode(): void {
- if (getInstance().dimensionMode !== '2d')
- throw new Error(
- 'You are calling a "2D mode only" function in non-2d mode.'
- );
+ if (getInstance().dimensionMode !== '2d') throw new Error('You are calling a "2D mode only" function in non-2d mode.');
}
function checkIs3DMode(): void {
- if (getInstance().dimensionMode !== '3d')
- throw new Error(
- 'You are calling a "3D mode only" function in non-3d mode.'
- );
+ if (getInstance().dimensionMode !== '3d') throw new Error('You are calling a "3D mode only" function in non-3d mode.');
}
function checkGameObjectIdentifierParameter(gameObjectIdentifier: any) {
@@ -76,37 +53,22 @@ function checkGameObjectIdentifierParameter(gameObjectIdentifier: any) {
// Because if I do that, when students re-run their code on the same Unity instance, (gameObjectIdentifier instanceof GameObjectIdentifier) will always evaluate to false
// even when students provide the parameter with the correct type.
const instance = getInstance();
- if (
- !(gameObjectIdentifier instanceof instance.gameObjectIdentifierWrapperClass)
- ) {
- throw new Error(
- `Type "${(typeof gameObjectIdentifier).toString()}" can not be used as game object identifier!`
- );
+ if (!(gameObjectIdentifier instanceof instance.gameObjectIdentifierWrapperClass)) {
+ throw new Error(`Type "${(typeof (gameObjectIdentifier)).toString()}" can not be used as game object identifier!`);
}
if (instance.getStudentGameObject(gameObjectIdentifier).isDestroyed) {
throw new Error('Trying to use a GameObject that is already destroyed.');
}
}
-function checkParameterType(
- parameter: any,
- expectedType: string,
- numberAllowInfinity = false
-) {
+function checkParameterType(parameter: any, expectedType: string, numberAllowInfinity = false) {
const actualType = typeof parameter;
if (actualType !== expectedType) {
- throw new Error(
- `Wrong parameter type: expected ${expectedType}, but got ${actualType}`
- );
+ throw new Error(`Wrong parameter type: expected ${expectedType}, but got ${actualType}`);
}
if (actualType.toString() === 'number') {
- if (
- !numberAllowInfinity &&
- (parameter === Infinity || parameter === -Infinity)
- ) {
- throw new Error(
- 'Wrong parameter type: expected a finite number, but got Infinity or -Infinity'
- );
+ if (!numberAllowInfinity && (parameter === Infinity || parameter === -Infinity)) {
+ throw new Error('Wrong parameter type: expected a finite number, but got Infinity or -Infinity');
}
}
}
@@ -119,10 +81,7 @@ function checkParameterType(
* @return Returns true if the two GameObject identifiers refers to the same GameObject and false otherwise.
* @category Common
*/
-export function same_gameobject(
- first: GameObjectIdentifier,
- second: GameObjectIdentifier
-): boolean {
+export function same_gameobject(first: GameObjectIdentifier, second: GameObjectIdentifier): boolean {
checkUnityAcademyExistence();
const instance = getInstance();
if (
@@ -142,10 +101,7 @@ export function same_gameobject(
* @category Common
* @category Outside Lifecycle
*/
-export function set_start(
- gameObjectIdentifier: GameObjectIdentifier,
- startFunction: Function
-): void {
+export function set_start(gameObjectIdentifier: GameObjectIdentifier, startFunction: Function): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(startFunction, 'function');
@@ -161,10 +117,7 @@ export function set_start(
* @category Common
* @category Outside Lifecycle
*/
-export function set_update(
- gameObjectIdentifier: GameObjectIdentifier,
- updateFunction: Function
-): void {
+export function set_update(gameObjectIdentifier: GameObjectIdentifier, updateFunction: Function): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(updateFunction, 'function');
@@ -279,15 +232,10 @@ export function destroy(gameObjectIdentifier: GameObjectIdentifier): void {
*
* @category Transform
*/
-export function get_position(
- gameObjectIdentifier: GameObjectIdentifier
-): Vector3 {
+export function get_position(gameObjectIdentifier: GameObjectIdentifier): Vector3 {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
- return getInstance().getGameObjectTransformProp(
- 'position',
- gameObjectIdentifier
- );
+ return getInstance().getGameObjectTransformProp('position', gameObjectIdentifier);
}
/**
@@ -297,18 +245,11 @@ export function get_position(
*
* @category Transform
*/
-export function set_position(
- gameObjectIdentifier: GameObjectIdentifier,
- position: Vector3
-): void {
+export function set_position(gameObjectIdentifier: GameObjectIdentifier, position: Vector3): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(position);
- return getInstance().setGameObjectTransformProp(
- 'position',
- gameObjectIdentifier,
- position
- );
+ return getInstance().setGameObjectTransformProp('position', gameObjectIdentifier, position);
}
/**
@@ -318,9 +259,7 @@ export function set_position(
*
* @category Transform
*/
-export function get_rotation_euler(
- gameObjectIdentifier: GameObjectIdentifier
-): Vector3 {
+export function get_rotation_euler(gameObjectIdentifier: GameObjectIdentifier): Vector3 {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
return getInstance().getGameObjectTransformProp(
@@ -336,18 +275,11 @@ export function get_rotation_euler(
*
* @category Transform
*/
-export function set_rotation_euler(
- gameObjectIdentifier: GameObjectIdentifier,
- rotation: Vector3
-): void {
+export function set_rotation_euler(gameObjectIdentifier: GameObjectIdentifier, rotation: Vector3): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(rotation);
- return getInstance().setGameObjectTransformProp(
- 'rotation',
- gameObjectIdentifier,
- rotation
- );
+ return getInstance().setGameObjectTransformProp('rotation', gameObjectIdentifier, rotation);
}
/**
@@ -362,10 +294,7 @@ export function set_rotation_euler(
export function get_scale(gameObjectIdentifier: GameObjectIdentifier): Vector3 {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
- return getInstance().getGameObjectTransformProp(
- 'scale',
- gameObjectIdentifier
- );
+ return getInstance().getGameObjectTransformProp('scale', gameObjectIdentifier);
}
/**
@@ -380,18 +309,11 @@ export function get_scale(gameObjectIdentifier: GameObjectIdentifier): Vector3 {
*
* @category Transform
*/
-export function set_scale(
- gameObjectIdentifier: GameObjectIdentifier,
- scale: Vector3
-): void {
+export function set_scale(gameObjectIdentifier: GameObjectIdentifier, scale: Vector3): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(scale);
- return getInstance().setGameObjectTransformProp(
- 'scale',
- gameObjectIdentifier,
- scale
- );
+ return getInstance().setGameObjectTransformProp('scale', gameObjectIdentifier, scale);
}
/**
@@ -402,17 +324,11 @@ export function set_scale(
*
* @category Transform
*/
-export function translate_world(
- gameObjectIdentifier: GameObjectIdentifier,
- deltaPosition: Vector3
-): void {
+export function translate_world(gameObjectIdentifier: GameObjectIdentifier, deltaPosition: Vector3): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(deltaPosition);
- return getInstance().translateWorldInternal(
- gameObjectIdentifier,
- deltaPosition
- );
+ return getInstance().translateWorldInternal(gameObjectIdentifier, deltaPosition);
}
/**
@@ -427,17 +343,11 @@ export function translate_world(
*
* @category Transform
*/
-export function translate_local(
- gameObjectIdentifier: GameObjectIdentifier,
- deltaPosition: Vector3
-): void {
+export function translate_local(gameObjectIdentifier: GameObjectIdentifier, deltaPosition: Vector3): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(deltaPosition);
- return getInstance().translateLocalInternal(
- gameObjectIdentifier,
- deltaPosition
- );
+ return getInstance().translateLocalInternal(gameObjectIdentifier, deltaPosition);
}
/**
@@ -448,10 +358,7 @@ export function translate_local(
*
* @category Transform
*/
-export function rotate_world(
- gameObjectIdentifier: GameObjectIdentifier,
- angles: Vector3
-): void {
+export function rotate_world(gameObjectIdentifier: GameObjectIdentifier, angles: Vector3): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(angles);
@@ -469,21 +376,12 @@ export function rotate_world(
*
* @category Transform
*/
-export function copy_position(
- from: GameObjectIdentifier,
- to: GameObjectIdentifier,
- deltaPosition: Vector3
-): void {
+export function copy_position(from: GameObjectIdentifier, to: GameObjectIdentifier, deltaPosition: Vector3): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(from);
checkGameObjectIdentifierParameter(to);
checkVector3Parameter(deltaPosition);
- return getInstance().copyTransformPropertiesInternal(
- 'position',
- from,
- to,
- deltaPosition
- );
+ return getInstance().copyTransformPropertiesInternal('position', from, to, deltaPosition);
}
/**
@@ -497,21 +395,12 @@ export function copy_position(
*
* @category Transform
*/
-export function copy_rotation(
- from: GameObjectIdentifier,
- to: GameObjectIdentifier,
- deltaRotation: Vector3
-): void {
+export function copy_rotation(from: GameObjectIdentifier, to: GameObjectIdentifier, deltaRotation: Vector3): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(from);
checkGameObjectIdentifierParameter(to);
checkVector3Parameter(deltaRotation);
- return getInstance().copyTransformPropertiesInternal(
- 'rotation',
- from,
- to,
- deltaRotation
- );
+ return getInstance().copyTransformPropertiesInternal('rotation', from, to, deltaRotation);
}
/**
@@ -525,21 +414,12 @@ export function copy_rotation(
*
* @category Transform
*/
-export function copy_scale(
- from: GameObjectIdentifier,
- to: GameObjectIdentifier,
- deltaScale: Vector3
-): void {
+export function copy_scale(from: GameObjectIdentifier, to: GameObjectIdentifier, deltaScale: Vector3): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(from);
checkGameObjectIdentifierParameter(to);
checkVector3Parameter(deltaScale);
- return getInstance().copyTransformPropertiesInternal(
- 'scale',
- from,
- to,
- deltaScale
- );
+ return getInstance().copyTransformPropertiesInternal('scale', from, to, deltaScale);
}
/**
@@ -554,10 +434,7 @@ export function copy_scale(
*
* @category Transform
*/
-export function look_at(
- gameObjectIdentifier: GameObjectIdentifier,
- position: Vector3
-): void {
+export function look_at(gameObjectIdentifier: GameObjectIdentifier, position: Vector3): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(position);
@@ -573,41 +450,21 @@ export function look_at(
* @return The value of the distance between these two GameObjects
* @category Transform
*/
-export function gameobject_distance(
- gameObjectIdentifier_A: GameObjectIdentifier,
- gameObjectIdentifier_B: GameObjectIdentifier
-): number {
+export function gameobject_distance(gameObjectIdentifier_A: GameObjectIdentifier, gameObjectIdentifier_B: GameObjectIdentifier): number {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier_A);
checkGameObjectIdentifierParameter(gameObjectIdentifier_B);
- return getInstance().gameObjectDistanceInternal(
- gameObjectIdentifier_A,
- gameObjectIdentifier_B
- );
+ return getInstance().gameObjectDistanceInternal(gameObjectIdentifier_A, gameObjectIdentifier_B);
}
function checkKeyCodeValidityAndToLowerCase(keyCode: string): string {
- if (typeof keyCode !== 'string')
- throw new Error(`Key code must be a string! Given type: ${typeof keyCode}`);
- if (
- keyCode === 'LeftMouseBtn' ||
- keyCode === 'RightMouseBtn' ||
- keyCode === 'MiddleMouseBtn' ||
- keyCode === 'Space' ||
- keyCode === 'LeftShift' ||
- keyCode === 'RightShift'
- )
- return keyCode;
+ if (typeof (keyCode) !== 'string') throw new Error(`Key code must be a string! Given type: ${typeof (keyCode)}`);
+ if (keyCode === 'LeftMouseBtn' || keyCode === 'RightMouseBtn' || keyCode === 'MiddleMouseBtn' || keyCode === 'Space' || keyCode === 'LeftShift' || keyCode === 'RightShift') return keyCode;
keyCode = keyCode.toLowerCase();
- if (keyCode.length !== 1)
- throw new Error(
- `Key code must be either a string of length 1 or one among 'LeftMouseBtn', 'RightMouseBtn', 'MiddleMouseBtn', 'Space', 'LeftShift' or 'RightShift'! Given length: ${keyCode.length}`
- );
+ if (keyCode.length !== 1) throw new Error(`Key code must be either a string of length 1 or one among 'LeftMouseBtn', 'RightMouseBtn', 'MiddleMouseBtn', 'Space', 'LeftShift' or 'RightShift'! Given length: ${keyCode.length}`);
const char = keyCode.charAt(0);
if (!((char >= 'a' && char <= 'z') || (char >= '0' && char <= '9'))) {
- throw new Error(
- `Key code must be either a letter between A-Z or a-z or 0-9 or one among 'LeftMouseBtn', 'RightMouseBtn', 'MiddleMouseBtn', 'Space', 'LeftShift' or 'RightShift'! Given: ${keyCode}`
- );
+ throw new Error(`Key code must be either a letter between A-Z or a-z or 0-9 or one among 'LeftMouseBtn', 'RightMouseBtn', 'MiddleMouseBtn', 'Space', 'LeftShift' or 'RightShift'! Given: ${keyCode}`);
}
return keyCode;
}
@@ -669,18 +526,12 @@ export function get_key_up(keyCode: string): boolean {
* @param animatorStateName The name for the animator state to play.
* @category Common
*/
-export function play_animator_state(
- gameObjectIdentifier: GameObjectIdentifier,
- animatorStateName: string
-): void {
+export function play_animator_state(gameObjectIdentifier: GameObjectIdentifier, animatorStateName: string): void {
checkUnityAcademyExistence();
checkIs3DMode();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(animatorStateName, 'string');
- getInstance().playAnimatorStateInternal(
- gameObjectIdentifier,
- animatorStateName
- );
+ getInstance().playAnimatorStateInternal(gameObjectIdentifier, animatorStateName);
}
/**
@@ -695,9 +546,7 @@ export function play_animator_state(
* @param gameObjectIdentifier The identifier for the GameObject that you want to apply rigidbody on.
* @category Physics - Rigidbody
*/
-export function apply_rigidbody(
- gameObjectIdentifier: GameObjectIdentifier
-): void {
+export function apply_rigidbody(gameObjectIdentifier: GameObjectIdentifier): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
getInstance().applyRigidbodyInternal(gameObjectIdentifier);
@@ -727,10 +576,7 @@ export function get_mass(gameObjectIdentifier: GameObjectIdentifier): number {
* @param mass The value for the new mass.
* @category Physics - Rigidbody
*/
-export function set_mass(
- gameObjectIdentifier: GameObjectIdentifier,
- mass: number
-): void {
+export function set_mass(gameObjectIdentifier: GameObjectIdentifier, mass: number): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(mass, 'number');
@@ -746,15 +592,10 @@ export function set_mass(
* @return the velocity at this moment represented in a Vector3.
* @category Physics - Rigidbody
*/
-export function get_velocity(
- gameObjectIdentifier: GameObjectIdentifier
-): Vector3 {
+export function get_velocity(gameObjectIdentifier: GameObjectIdentifier): Vector3 {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
- return getInstance().getRigidbodyVelocityVector3Prop(
- 'velocity',
- gameObjectIdentifier
- );
+ return getInstance().getRigidbodyVelocityVector3Prop('velocity', gameObjectIdentifier);
}
/**
@@ -766,18 +607,11 @@ export function get_velocity(
* @param velocity The new velocity for the rigidbody attached on the GameObject.
* @category Physics - Rigidbody
*/
-export function set_velocity(
- gameObjectIdentifier: GameObjectIdentifier,
- velocity: Vector3
-): void {
+export function set_velocity(gameObjectIdentifier: GameObjectIdentifier, velocity: Vector3): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(velocity);
- getInstance().setRigidbodyVelocityVector3Prop(
- 'velocity',
- gameObjectIdentifier,
- velocity
- );
+ getInstance().setRigidbodyVelocityVector3Prop('velocity', gameObjectIdentifier, velocity);
}
/**
@@ -791,15 +625,10 @@ export function set_velocity(
* @return the angular velocity at this moment represented in a Vector3.
* @category Physics - Rigidbody
*/
-export function get_angular_velocity(
- gameObjectIdentifier: GameObjectIdentifier
-): Vector3 {
+export function get_angular_velocity(gameObjectIdentifier: GameObjectIdentifier): Vector3 {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
- return getInstance().getRigidbodyVelocityVector3Prop(
- 'angularVelocity',
- gameObjectIdentifier
- );
+ return getInstance().getRigidbodyVelocityVector3Prop('angularVelocity', gameObjectIdentifier);
}
/**
@@ -813,18 +642,11 @@ export function get_angular_velocity(
* @param angularVelocity The new angular velocity for the rigidbody attached on the GameObject.
* @category Physics - Rigidbody
*/
-export function set_angular_velocity(
- gameObjectIdentifier: GameObjectIdentifier,
- angularVelocity: Vector3
-): void {
+export function set_angular_velocity(gameObjectIdentifier: GameObjectIdentifier, angularVelocity: Vector3): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(angularVelocity);
- getInstance().setRigidbodyVelocityVector3Prop(
- 'angularVelocity',
- gameObjectIdentifier,
- angularVelocity
- );
+ getInstance().setRigidbodyVelocityVector3Prop('angularVelocity', gameObjectIdentifier, angularVelocity);
}
/**
@@ -838,10 +660,7 @@ export function set_angular_velocity(
* @param value The value of the new drag.
* @category Physics - Rigidbody
*/
-export function set_drag(
- gameObjectIdentifier: GameObjectIdentifier,
- value: number
-): void {
+export function set_drag(gameObjectIdentifier: GameObjectIdentifier, value: number): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(value, 'number');
@@ -859,18 +678,11 @@ export function set_drag(
* @param value The value of the new angular drag.
* @category Physics - Rigidbody
*/
-export function set_angular_drag(
- gameObjectIdentifier: GameObjectIdentifier,
- value: number
-): void {
+export function set_angular_drag(gameObjectIdentifier: GameObjectIdentifier, value: number): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(value, 'number');
- getInstance().setRigidbodyNumericalProp(
- 'angularDrag',
- gameObjectIdentifier,
- value
- );
+ getInstance().setRigidbodyNumericalProp('angularDrag', gameObjectIdentifier, value);
}
/**
@@ -882,10 +694,7 @@ export function set_angular_drag(
* @param {useGravity} Set to true if you want gravity to be applied on this rigidbody, false otherwise.
* @category Physics - Rigidbody
*/
-export function set_use_gravity(
- gameObjectIdentifier: GameObjectIdentifier,
- useGravity: boolean
-): void {
+export function set_use_gravity(gameObjectIdentifier: GameObjectIdentifier, useGravity: boolean): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(useGravity, 'boolean');
@@ -901,10 +710,7 @@ export function set_use_gravity(
* @param The force vector.
* @category Physics - Rigidbody
*/
-export function add_impulse_force(
- gameObjectIdentifier: GameObjectIdentifier,
- force: Vector3
-): void {
+export function add_impulse_force(gameObjectIdentifier: GameObjectIdentifier, force: Vector3): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkVector3Parameter(force);
@@ -921,9 +727,7 @@ export function add_impulse_force(
* @param gameObjectIdentifier The identifier for the GameObject that you want to remove colliders for.
* @category Physics - Collision
*/
-export function remove_collider_components(
- gameObjectIdentifier: GameObjectIdentifier
-): void {
+export function remove_collider_components(gameObjectIdentifier: GameObjectIdentifier): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
getInstance().removeColliderComponentsInternal(gameObjectIdentifier);
@@ -949,17 +753,11 @@ export function remove_collider_components(
* @category Physics - Collision
* @category Outside Lifecycle
*/
-export function on_collision_enter(
- gameObjectIdentifier: GameObjectIdentifier,
- eventFunction: Function
-): void {
+export function on_collision_enter(gameObjectIdentifier: GameObjectIdentifier, eventFunction: Function): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(eventFunction, 'function');
- getInstance().setOnCollisionEnterInternal(
- gameObjectIdentifier,
- eventFunction
- );
+ getInstance().setOnCollisionEnterInternal(gameObjectIdentifier, eventFunction);
}
/**
@@ -982,10 +780,7 @@ export function on_collision_enter(
* @category Physics - Collision
* @category Outside Lifecycle
*/
-export function on_collision_stay(
- gameObjectIdentifier: GameObjectIdentifier,
- eventFunction: Function
-): void {
+export function on_collision_stay(gameObjectIdentifier: GameObjectIdentifier, eventFunction: Function): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(eventFunction, 'function');
@@ -1012,10 +807,7 @@ export function on_collision_stay(
* @category Physics - Collision
* @category Outside Lifecycle
*/
-export function on_collision_exit(
- gameObjectIdentifier: GameObjectIdentifier,
- eventFunction: Function
-): void {
+export function on_collision_exit(gameObjectIdentifier: GameObjectIdentifier, eventFunction: Function): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(eventFunction, 'function');
@@ -1083,14 +875,7 @@ export function gui_label(text: string, x: number, y: number): void {
* @param onClick The function that will be called when user clicks the button on screen.
* @category Graphical User Interface
*/
-export function gui_button(
- text: string,
- x: number,
- y: number,
- width: number,
- height: number,
- onClick: Function
-): void {
+export function gui_button(text: string, x: number, y: number, width: number, height: number, onClick: Function): void {
checkUnityAcademyExistence();
checkParameterType(text, 'string');
checkParameterType(x, 'number');
@@ -1116,9 +901,7 @@ export function gui_button(
*/
export function get_main_camera_following_target(): GameObjectIdentifier {
checkUnityAcademyExistence();
- return getInstance().getGameObjectIdentifierForPrimitiveGameObject(
- 'MainCameraFollowingTarget'
- );
+ return getInstance().getGameObjectIdentifierForPrimitiveGameObject('MainCameraFollowingTarget');
}
/**
@@ -1146,19 +929,11 @@ export function request_for_main_camera_control(): GameObjectIdentifier {
*
* @category Common
*/
-export function set_custom_prop(
- gameObjectIdentifier: GameObjectIdentifier,
- propName: string,
- value: any
-): void {
+export function set_custom_prop(gameObjectIdentifier: GameObjectIdentifier, propName: string, value: any): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(propName, 'string');
- getInstance().setCustomPropertyInternal(
- gameObjectIdentifier,
- propName,
- value
- );
+ getInstance().setCustomPropertyInternal(gameObjectIdentifier, propName, value);
}
/**
@@ -1171,17 +946,11 @@ export function set_custom_prop(
*
* @category Common
*/
-export function get_custom_prop(
- gameObjectIdentifier: GameObjectIdentifier,
- propName: string
-): any {
+export function get_custom_prop(gameObjectIdentifier: GameObjectIdentifier, propName: string): any {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(gameObjectIdentifier);
checkParameterType(propName, 'string');
- return getInstance().getCustomPropertyInternal(
- gameObjectIdentifier,
- propName
- );
+ return getInstance().getCustomPropertyInternal(gameObjectIdentifier, propName);
}
/**
@@ -1412,9 +1181,7 @@ export function load_audio_clip_wav(audioUrl: string): AudioClipIdentifier {
* @category Sound / Audio
* @category Outside Lifecycle
*/
-export function instantiate_audio_source(
- audioClip: AudioClipIdentifier
-): GameObjectIdentifier {
+export function instantiate_audio_source(audioClip: AudioClipIdentifier): GameObjectIdentifier {
// todo: check audio clip identifier type
checkUnityAcademyExistence();
return getInstance().instantiateAudioSourceInternal(audioClip);
@@ -1457,10 +1224,7 @@ export function pause_audio(audioSrc: GameObjectIdentifier): void {
*
* @category Sound / Audio
*/
-export function set_audio_play_speed(
- audioSrc: GameObjectIdentifier,
- speed: number
-): void {
+export function set_audio_play_speed(audioSrc: GameObjectIdentifier, speed: number): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
checkParameterType(speed, 'number');
@@ -1476,9 +1240,7 @@ export function set_audio_play_speed(
*
* @category Sound / Audio
*/
-export function get_audio_play_progress(
- audioSrc: GameObjectIdentifier
-): number {
+export function get_audio_play_progress(audioSrc: GameObjectIdentifier): number {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
return getInstance().getAudioSourceProp('playProgress', audioSrc);
@@ -1493,10 +1255,7 @@ export function get_audio_play_progress(
*
* @category Sound / Audio
*/
-export function set_audio_play_progress(
- audioSrc: GameObjectIdentifier,
- progress: number
-): void {
+export function set_audio_play_progress(audioSrc: GameObjectIdentifier, progress: number): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
checkParameterType(progress, 'number');
@@ -1507,28 +1266,18 @@ export function set_audio_play_progress(
*
* @category Sound / Audio
*/
-export function change_audio_clip(
- audioSrc: GameObjectIdentifier,
- newAudioClip: AudioClipIdentifier
-): void {
+export function change_audio_clip(audioSrc: GameObjectIdentifier, newAudioClip: AudioClipIdentifier): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
// todo: check audio clip identifier type
- getInstance().setAudioSourceProp(
- 'audioClipIdentifier',
- audioSrc,
- newAudioClip
- );
+ getInstance().setAudioSourceProp('audioClipIdentifier', audioSrc, newAudioClip);
}
/**
*
* @category Sound / Audio
*/
-export function set_audio_looping(
- audioSrc: GameObjectIdentifier,
- looping: boolean
-): void {
+export function set_audio_looping(audioSrc: GameObjectIdentifier, looping: boolean): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
checkParameterType(looping, 'boolean');
@@ -1539,10 +1288,7 @@ export function set_audio_looping(
*
* @category Sound / Audio
*/
-export function set_audio_volume(
- audioSrc: GameObjectIdentifier,
- volume: number
-): void {
+export function set_audio_volume(audioSrc: GameObjectIdentifier, volume: number): void {
checkUnityAcademyExistence();
checkGameObjectIdentifierParameter(audioSrc);
checkParameterType(volume, 'number');
@@ -1622,11 +1368,7 @@ export function debug_logerror(content: any): void {
*
* @category Sound / Audio
*/
-export function set_audio_listener_position(
- positionX: number,
- positionY: number,
- positionZ: number
-) {
+export function set_audio_listener_position(positionX: number, positionY: number, positionZ: number) {
// todo: check audio clip identifier type
checkUnityAcademyExistence();
checkParameterType(positionX, 'number');
@@ -1645,14 +1387,7 @@ export function set_audio_listener_position(
*
* @category Sound / Audio
*/
-export function play_audio_clip_3d_sound(
- audioClip: AudioClipIdentifier,
- volume: number,
- loop: boolean,
- positionX: number,
- positionY: number,
- positionZ: number
-) {
+export function play_audio_clip_3d_sound(audioClip: AudioClipIdentifier, volume: number, loop: boolean, positionX: number, positionY: number, positionZ: number) {
// todo: check audio clip identifier type
checkUnityAcademyExistence();
checkParameterType(volume, 'number');
From 2708100caa6ca8bb4c8e2f57ba0a4464164ee91d Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Sat, 13 Apr 2024 08:37:06 +0800
Subject: [PATCH 22/39] Fix arrow parens lint
---
src/bundles/ar/AR.ts | 6 +++---
src/bundles/physics_2d/PhysicsObject.ts | 2 +-
src/bundles/repl/programmable_repl.ts | 2 +-
.../engine/Core/CallbackHandler.ts | 2 +-
.../robot_simulation/engine/Core/Controller.ts | 16 ++++++++--------
.../robot_simulation/engine/Core/Events.ts | 2 +-
.../engine/Render/helpers/GLTF.ts | 4 ++--
src/bundles/robot_simulation/engine/World.ts | 10 +++++-----
src/bundles/scrabble/functions.ts | 4 ++--
src/bundles/sound/functions.ts | 2 +-
src/bundles/stereo_sound/functions.ts | 2 +-
src/tabs/AugmentedReality/AugmentedContent.tsx | 16 ++++++++--------
12 files changed, 34 insertions(+), 34 deletions(-)
diff --git a/src/bundles/ar/AR.ts b/src/bundles/ar/AR.ts
index ba41fdcdc..7e2f1ec1f 100644
--- a/src/bundles/ar/AR.ts
+++ b/src/bundles/ar/AR.ts
@@ -127,7 +127,7 @@ export function createVector3(x: number, y: number, z: number): Vector3 {
export function addARObject(arObject: ARObject) {
const moduleState = getModuleState();
if (!moduleState) return;
- if (moduleState.arObjects.find((item) => item.id === arObject.id)) {
+ if (moduleState.arObjects.find(item => item.id === arObject.id)) {
return; // Already in array
}
if (arObject.onSelect) {
@@ -148,7 +148,7 @@ export function removeARObject(arObject: ARObject) {
const moduleState = getModuleState();
if (!moduleState) return;
moduleState.arObjects = moduleState.arObjects.filter(
- (item) => item.id !== arObject.id,
+ item => item.id !== arObject.id,
);
callARCallback();
}
@@ -266,7 +266,7 @@ export function getFrontObject() {
const moduleState = getModuleState();
if (!moduleState) return undefined;
return moduleState.arObjects.find(
- (arObject) => arObject.id === moduleState.selectedObjectId,
+ arObject => arObject.id === moduleState.selectedObjectId,
);
}
diff --git a/src/bundles/physics_2d/PhysicsObject.ts b/src/bundles/physics_2d/PhysicsObject.ts
index 2162bb438..78379fa53 100644
--- a/src/bundles/physics_2d/PhysicsObject.ts
+++ b/src/bundles/physics_2d/PhysicsObject.ts
@@ -124,7 +124,7 @@ export class PhysicsObject implements ReplResult {
(forceWithPos: ForceWithPos) => forceWithPos.force.start_time + forceWithPos.force.duration > world_time
);
- this.forcesAtAPoint.forEach((forceWithPos) => {
+ this.forcesAtAPoint.forEach(forceWithPos => {
const force = forceWithPos.force;
this.body.ApplyForce(
force.direction.Scale(force.magnitude),
diff --git a/src/bundles/repl/programmable_repl.ts b/src/bundles/repl/programmable_repl.ts
index 84fc545f8..6520a737d 100644
--- a/src/bundles/repl/programmable_repl.ts
+++ b/src/bundles/repl/programmable_repl.ts
@@ -204,7 +204,7 @@ export class ProgrammableRepl {
};
runFilesInContext(sourceFile, '/ReplModuleUserCode.js', context, options)
- .then((evalResult) => {
+ .then(evalResult => {
if (evalResult.status === 'suspended' || evalResult.status === 'suspended-cse-eval') {
throw new Error('This should not happen');
}
diff --git a/src/bundles/robot_simulation/engine/Core/CallbackHandler.ts b/src/bundles/robot_simulation/engine/Core/CallbackHandler.ts
index 76e1bae8d..77b51c56f 100644
--- a/src/bundles/robot_simulation/engine/Core/CallbackHandler.ts
+++ b/src/bundles/robot_simulation/engine/Core/CallbackHandler.ts
@@ -26,7 +26,7 @@ export class CallbackHandler {
this.currentStepCount = frameTimingInfo.stepCount;
- this.callbackStore = this.callbackStore.filter((callbackEntry) => {
+ this.callbackStore = this.callbackStore.filter(callbackEntry => {
callbackEntry.delay -= frameTimingInfo.timestep;
if (callbackEntry.delay <= 0) {
diff --git a/src/bundles/robot_simulation/engine/Core/Controller.ts b/src/bundles/robot_simulation/engine/Core/Controller.ts
index af3c50d2d..9f1eb88ef 100644
--- a/src/bundles/robot_simulation/engine/Core/Controller.ts
+++ b/src/bundles/robot_simulation/engine/Core/Controller.ts
@@ -26,7 +26,7 @@ implements Controller {
await this.callbacks?.start?.();
await Promise.all(
Object.values(this.map)
- .map(async (controller) => {
+ .map(async controller => {
await controller.start?.();
}),
);
@@ -35,7 +35,7 @@ implements Controller {
update(timingInfo: PhysicsTimingInfo): void {
this.callbacks?.update?.(timingInfo);
Object.values(this.map)
- .forEach((controller) => {
+ .forEach(controller => {
controller.update?.(timingInfo);
});
}
@@ -43,7 +43,7 @@ implements Controller {
fixedUpdate(timingInfo: PhysicsTimingInfo): void {
this.callbacks?.fixedUpdate?.(timingInfo);
Object.values(this.map)
- .forEach((controller) => {
+ .forEach(controller => {
controller.fixedUpdate?.(timingInfo);
});
}
@@ -51,7 +51,7 @@ implements Controller {
onDestroy(): void {
this.callbacks?.onDestroy?.();
Object.values(this.map)
- .forEach((controller) => {
+ .forEach(controller => {
controller.onDestroy?.();
});
}
@@ -66,26 +66,26 @@ export class ControllerGroup implements Controller {
async start?(): Promise {
await Promise.all(
- this.controllers.map(async (controller) => {
+ this.controllers.map(async controller => {
await controller.start?.();
}),
);
}
update(timingInfo: PhysicsTimingInfo): void {
- this.controllers.forEach((controller) => {
+ this.controllers.forEach(controller => {
controller.update?.(timingInfo);
});
}
fixedUpdate(timingInfo: PhysicsTimingInfo): void {
- this.controllers.forEach((controller) => {
+ this.controllers.forEach(controller => {
controller.fixedUpdate?.(timingInfo);
});
}
onDestroy(): void {
- this.controllers.forEach((controller) => {
+ this.controllers.forEach(controller => {
controller.onDestroy?.();
});
this.controllers = [];
diff --git a/src/bundles/robot_simulation/engine/Core/Events.ts b/src/bundles/robot_simulation/engine/Core/Events.ts
index 58402cdbd..ae01d6102 100644
--- a/src/bundles/robot_simulation/engine/Core/Events.ts
+++ b/src/bundles/robot_simulation/engine/Core/Events.ts
@@ -32,7 +32,7 @@ export class TypedEventTarget> {
): boolean {
const listeners = this.listeners[_type];
if (listeners) {
- listeners.forEach((listener) => {
+ listeners.forEach(listener => {
listener(event);
});
}
diff --git a/src/bundles/robot_simulation/engine/Render/helpers/GLTF.ts b/src/bundles/robot_simulation/engine/Render/helpers/GLTF.ts
index 10b86918e..9d7b46d3f 100644
--- a/src/bundles/robot_simulation/engine/Render/helpers/GLTF.ts
+++ b/src/bundles/robot_simulation/engine/Render/helpers/GLTF.ts
@@ -10,7 +10,7 @@ export function loadGLTF(url: string, dimension: GLTFLoaderOptions): Promise {
loader.load(
url,
- (data) => {
+ data => {
const box = new THREE.Box3()
.setFromObject(data.scene);
const meshSize = new THREE.Vector3();
@@ -25,7 +25,7 @@ export function loadGLTF(url: string, dimension: GLTFLoaderOptions): Promise reject(error),
+ error => reject(error),
);
});
}
diff --git a/src/bundles/robot_simulation/engine/World.ts b/src/bundles/robot_simulation/engine/World.ts
index 95239fcda..8e8ddfca9 100644
--- a/src/bundles/robot_simulation/engine/World.ts
+++ b/src/bundles/robot_simulation/engine/World.ts
@@ -44,19 +44,19 @@ export class World extends TypedEventTarget {
this.controllers.addController(...controllers);
this.addEventListener('worldStart', () => {
- controllers.forEach((controller) => {
+ controllers.forEach(controller => {
controller.start?.();
});
});
- this.addEventListener('beforeRender', (e) => {
- controllers.forEach((controller) => {
+ this.addEventListener('beforeRender', e => {
+ controllers.forEach(controller => {
controller.update?.(e.frameTimingInfo);
});
});
- this.physics.addEventListener('beforePhysicsUpdate', (e) => {
- controllers.forEach((controller) => {
+ this.physics.addEventListener('beforePhysicsUpdate', e => {
+ controllers.forEach(controller => {
controller.fixedUpdate?.(e.frameTimingInfo);
});
});
diff --git a/src/bundles/scrabble/functions.ts b/src/bundles/scrabble/functions.ts
index c21be3f32..fc0a5a0d7 100644
--- a/src/bundles/scrabble/functions.ts
+++ b/src/bundles/scrabble/functions.ts
@@ -172840,9 +172840,9 @@ export const scrabble_words = [
* order in which the letters appear in the word.
*/
-export const scrabble_letters = scrabble_words.map((w) => w.split(''));
+export const scrabble_letters = scrabble_words.map(w => w.split(''));
// Sample every 100 words to generate "tiny" dataset
export const scrabble_words_tiny = scrabble_words.filter((_, i) => i % 100 === 0);
-export const scrabble_letters_tiny = scrabble_words_tiny.map((w) => w.split(''));
+export const scrabble_letters_tiny = scrabble_words_tiny.map(w => w.split(''));
diff --git a/src/bundles/sound/functions.ts b/src/bundles/sound/functions.ts
index 879127058..3298439ec 100644
--- a/src/bundles/sound/functions.ts
+++ b/src/bundles/sound/functions.ts
@@ -531,7 +531,7 @@ export function triangle_sound(freq: number, duration: number): Sound {
return answer;
}
return make_sound(
- (t) => (8 / Math.PI / Math.PI) * fourier_expansion_triangle(t),
+ t => (8 / Math.PI / Math.PI) * fourier_expansion_triangle(t),
duration
);
}
diff --git a/src/bundles/stereo_sound/functions.ts b/src/bundles/stereo_sound/functions.ts
index f361fbb7c..8a99190ba 100644
--- a/src/bundles/stereo_sound/functions.ts
+++ b/src/bundles/stereo_sound/functions.ts
@@ -701,7 +701,7 @@ export function triangle_sound(freq: number, duration: number): Sound {
return answer;
}
return make_sound(
- (t) => (8 / Math.PI / Math.PI) * fourier_expansion_triangle(t),
+ t => (8 / Math.PI / Math.PI) * fourier_expansion_triangle(t),
duration
);
}
diff --git a/src/tabs/AugmentedReality/AugmentedContent.tsx b/src/tabs/AugmentedReality/AugmentedContent.tsx
index 8893a21d5..befc413a5 100644
--- a/src/tabs/AugmentedReality/AugmentedContent.tsx
+++ b/src/tabs/AugmentedReality/AugmentedContent.tsx
@@ -29,7 +29,7 @@ export function AugmentedContent(props: ARState) {
}
if (prev) {
const object = objectsRef.current?.find(
- (item) => item.uuid === prev.uuid,
+ item => item.uuid === prev.uuid,
);
if (object) {
object.isInFront = false;
@@ -37,7 +37,7 @@ export function AugmentedContent(props: ARState) {
}
if (current) {
const object = objectsRef.current?.find(
- (item) => item.uuid === current.uuid,
+ item => item.uuid === current.uuid,
);
if (object) {
object.isInFront = true;
@@ -69,13 +69,13 @@ export function AugmentedContent(props: ARState) {
function updateObjects(state: ARState) {
const newObjects: ARObject[] = [];
- state.arObjects.forEach((object) => {
+ state.arObjects.forEach(object => {
const newObject = ARObject.fromObject(object, getCurrentTime);
if (newObject) {
newObjects.push(newObject);
}
});
- newObjects.forEach((object) => {
+ newObjects.forEach(object => {
object.onSelect = () => {
const moduleState = getModuleState();
if (moduleState) {
@@ -158,13 +158,13 @@ export function AugmentedContent(props: ARState) {
useEffect(() => {
try {
fetch('https://worldtimeapi.org/api/timezone/Asia/Singapore')
- .then((response) => response.json())
- .then((data) => {
+ .then(response => response.json())
+ .then(data => {
const time = new Date(data.datetime).getTime();
const offset = time - new Date().getTime();
setTimeOffset(offset);
})
- .catch((error) => {
+ .catch(error => {
console.log(error);
});
} catch {
@@ -184,7 +184,7 @@ export function AugmentedContent(props: ARState) {
return (
- {objects.map((item) => item.getComponent(playArea.getCameraPosition))}
+ {objects.map(item => item.getComponent(playArea.getCameraPosition))}
);
}
From 7be4131ac4e3f7ee15843398ae7df510076277aa Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Sat, 13 Apr 2024 08:37:30 +0800
Subject: [PATCH 23/39] Enforce member delimiter style
---
eslint.config.js | 1 +
1 file changed, 1 insertion(+)
diff --git a/eslint.config.js b/eslint.config.js
index fad4994f5..436f0b6b2 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -58,6 +58,7 @@ export default [
'@stylistic/no-trailing-spaces': 'warn',
'@stylistic/quotes': ['warn', 'single', { avoidEscape: true }],
'@stylistic/semi': ['warn', 'always'],
+ '@stylistic/member-delimiter-style': 'error',
'@stylistic/spaced-comment': [
'warn',
'always',
From ff565927a2453bc3744099d954185984525ba8e2 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Sat, 13 Apr 2024 08:37:55 +0800
Subject: [PATCH 24/39] Make arrow-parens global
---
eslint.config.js | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/eslint.config.js b/eslint.config.js
index 436f0b6b2..f323bab5f 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -64,6 +64,7 @@ export default [
'always',
{ markers: todoTreeKeywordsAll }
],
+ '@stylistic/arrow-parens': ['warn', 'as-needed'],
},
linterOptions: {
reportUnusedDisableDirectives: 'warn'
@@ -137,8 +138,6 @@ export default [
'import/extensions': ['error', 'never', { json: 'always' }],
'no-constant-condition': 'off', // Was 'error',
- '@stylistic/arrow-parens': ['warn', 'as-needed'],
-
'@typescript-eslint/prefer-readonly': 'warn',
'@typescript-eslint/require-await': 'error',
'@typescript-eslint/return-await': ['error', 'in-try-catch']
From 409eb9b641e7426ffd34d11419268bfd73818c74 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Sat, 13 Apr 2024 08:44:18 +0800
Subject: [PATCH 25/39] Use React.FC typing
---
src/tabs/common/ButtonComponent.tsx | 2 +-
src/tabs/common/ModalDiv.tsx | 7 ++++---
2 files changed, 5 insertions(+), 4 deletions(-)
diff --git a/src/tabs/common/ButtonComponent.tsx b/src/tabs/common/ButtonComponent.tsx
index 50af4759c..eb35491d6 100644
--- a/src/tabs/common/ButtonComponent.tsx
+++ b/src/tabs/common/ButtonComponent.tsx
@@ -15,7 +15,7 @@ type Props = {
children?: ReactNode;
};
-const ButtonComponent = (props: Props) => {
+const ButtonComponent: React.FC = props => {
const buttonProps = {
...defaultOptions,
...props
diff --git a/src/tabs/common/ModalDiv.tsx b/src/tabs/common/ModalDiv.tsx
index 1fc2009dc..d9035b232 100644
--- a/src/tabs/common/ModalDiv.tsx
+++ b/src/tabs/common/ModalDiv.tsx
@@ -39,14 +39,15 @@ const backdropStyle = {
filter: 'blur(10px)'
} as CSSProperties;
-interface ModalProp {
+type Props = {
open: boolean;
height: string;
width: string;
handleClose: MouseEventHandler;
children: ReactElement;
-}
-const Modal = ({ open, height, width, children, handleClose }: ModalProp) => (
+};
+
+const Modal: React.FC = ({ open, height, width, children, handleClose }) => (
<>
{open && (
<>
From 089ce65e022af6b624936867957a1cd3a57090c7 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Sat, 13 Apr 2024 08:52:07 +0800
Subject: [PATCH 26/39] Reformat MarkSweep
---
src/tabs/MarkSweep/index.tsx | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/tabs/MarkSweep/index.tsx b/src/tabs/MarkSweep/index.tsx
index 0f48e1da7..c94a4d751 100644
--- a/src/tabs/MarkSweep/index.tsx
+++ b/src/tabs/MarkSweep/index.tsx
@@ -317,9 +317,9 @@ class MarkSweep extends React.Component {
- {memoryMatrix &&
- memoryMatrix.length > 0 &&
- memoryMatrix.map((item, row) => (
+ {memoryMatrix
+ && memoryMatrix.length > 0
+ && memoryMatrix.map((item, row) => (
{row * state.column}
{item
From f319466075db1294b74acc41abe6dbcd0c2051a7 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Sat, 13 Apr 2024 08:56:14 +0800
Subject: [PATCH 27/39] Standardize operator-linebreak to before
---
eslint.config.js | 1 +
.../communication/GlobalStateController.ts | 10 +++++-----
.../communication/MultiUserController.ts | 4 ++--
src/bundles/pix_n_flix/functions.ts | 10 +++++-----
src/bundles/plotly/sound_functions.ts | 6 +++---
src/bundles/repl/programmable_repl.ts | 4 ++--
src/bundles/unity_academy/functions.ts | 4 ++--
src/tabs/CopyGc/index.tsx | 20 +++++++++----------
src/tabs/Csg/canvas_holder.tsx | 4 ++--
src/tabs/RobotSimulation/index.tsx | 3 +--
10 files changed, 33 insertions(+), 33 deletions(-)
diff --git a/eslint.config.js b/eslint.config.js
index f323bab5f..c779b2987 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -65,6 +65,7 @@ export default [
{ markers: todoTreeKeywordsAll }
],
'@stylistic/arrow-parens': ['warn', 'as-needed'],
+ '@stylistic/operator-linebreak': ['warn', 'before'],
},
linterOptions: {
reportUnusedDisableDirectives: 'warn'
diff --git a/src/bundles/communication/GlobalStateController.ts b/src/bundles/communication/GlobalStateController.ts
index 03c86b1fb..d51cf7b29 100644
--- a/src/bundles/communication/GlobalStateController.ts
+++ b/src/bundles/communication/GlobalStateController.ts
@@ -63,8 +63,8 @@ export class GlobalStateController {
try {
let newGlobalState = { ...this.globalState };
if (
- this.globalState instanceof Array ||
- typeof this.globalState === 'string'
+ this.globalState instanceof Array
+ || typeof this.globalState === 'string'
) {
newGlobalState = {};
}
@@ -72,9 +72,9 @@ export class GlobalStateController {
for (let i = 1; i < splitTopic.length - 1; i++) {
const subTopic = splitTopic[i];
if (
- !(currentJson[subTopic] instanceof Object) ||
- currentJson[subTopic] instanceof Array ||
- typeof currentJson[subTopic] === 'string'
+ !(currentJson[subTopic] instanceof Object)
+ || currentJson[subTopic] instanceof Array
+ || typeof currentJson[subTopic] === 'string'
) {
currentJson[subTopic] = {};
}
diff --git a/src/bundles/communication/MultiUserController.ts b/src/bundles/communication/MultiUserController.ts
index 1d29f06a1..b2c23b0a6 100644
--- a/src/bundles/communication/MultiUserController.ts
+++ b/src/bundles/communication/MultiUserController.ts
@@ -7,8 +7,8 @@ import { MqttController, STATE_DISCONNECTED } from './MqttController';
export class MultiUserController {
controller: MqttController | null = null;
connectionState: string = STATE_DISCONNECTED;
- messageCallbacks: Map
void> =
- new Map();
+ messageCallbacks: Map void>
+ = new Map();
/**
* Sets up and connect to the MQTT link.
diff --git a/src/bundles/pix_n_flix/functions.ts b/src/bundles/pix_n_flix/functions.ts
index 285027d60..7943b9b86 100644
--- a/src/bundles/pix_n_flix/functions.ts
+++ b/src/bundles/pix_n_flix/functions.ts
@@ -344,11 +344,11 @@ function updateFPS(fps: number): void {
function updateDimensions(w: number, h: number): void {
// ignore if no change or bad inputs
if (
- (w === WIDTH && h === HEIGHT) ||
- w > MAX_WIDTH ||
- w < MIN_WIDTH ||
- h > MAX_HEIGHT ||
- h < MIN_HEIGHT
+ (w === WIDTH && h === HEIGHT)
+ || w > MAX_WIDTH
+ || w < MIN_WIDTH
+ || h > MAX_HEIGHT
+ || h < MIN_HEIGHT
) {
return;
}
diff --git a/src/bundles/plotly/sound_functions.ts b/src/bundles/plotly/sound_functions.ts
index b0fe55018..9f95d6c4f 100644
--- a/src/bundles/plotly/sound_functions.ts
+++ b/src/bundles/plotly/sound_functions.ts
@@ -6,9 +6,9 @@ import {
import { type Sound, type Wave } from '../sound/types';
export function is_sound(x: any): x is Sound {
return (
- is_pair(x) &&
- typeof get_wave(x) === 'function' &&
- typeof get_duration(x) === 'number'
+ is_pair(x)
+ && typeof get_wave(x) === 'function'
+ && typeof get_duration(x) === 'number'
);
}
/**
diff --git a/src/bundles/repl/programmable_repl.ts b/src/bundles/repl/programmable_repl.ts
index 6520a737d..7be62596e 100644
--- a/src/bundles/repl/programmable_repl.ts
+++ b/src/bundles/repl/programmable_repl.ts
@@ -51,8 +51,8 @@ export class ProgrammableRepl {
developmentLog(exception);
// If the exception has a start line of -1 and an undefined error property, then this exception is most likely to be "incorrect number of arguments" caused by incorrect number of parameters in the evaluator entry function provided by students with set_evaluator.
if (
- exception.location.start.line === -1 &&
- exception.error === undefined
+ exception.location.start.line === -1
+ && exception.error === undefined
) {
this.pushOutputString(
'Error: Unable to use your evaluator to run the code. Does your evaluator entry function contain and only contain exactly one parameter?',
diff --git a/src/bundles/unity_academy/functions.ts b/src/bundles/unity_academy/functions.ts
index 3ae98c124..62822f336 100644
--- a/src/bundles/unity_academy/functions.ts
+++ b/src/bundles/unity_academy/functions.ts
@@ -85,8 +85,8 @@ export function same_gameobject(first: GameObjectIdentifier, second: GameObjectI
checkUnityAcademyExistence();
const instance = getInstance();
if (
- !(first instanceof instance.gameObjectIdentifierWrapperClass) ||
- !(second instanceof instance.gameObjectIdentifierWrapperClass)
+ !(first instanceof instance.gameObjectIdentifierWrapperClass)
+ || !(second instanceof instance.gameObjectIdentifierWrapperClass)
) {
return false;
}
diff --git a/src/tabs/CopyGc/index.tsx b/src/tabs/CopyGc/index.tsx
index e3a46763d..a83683ad1 100644
--- a/src/tabs/CopyGc/index.tsx
+++ b/src/tabs/CopyGc/index.tsx
@@ -311,9 +311,9 @@ class CopyGC extends React.Component {
{state.toSpace === 0 ? 'To Space' : 'From Space'}
- {toMemoryMatrix &&
- toMemoryMatrix.length > 0 &&
- toMemoryMatrix.map((item, row) => (
+ {toMemoryMatrix
+ && toMemoryMatrix.length > 0
+ && toMemoryMatrix.map((item, row) => (
{row * state.column}
{item
@@ -340,15 +340,15 @@ class CopyGC extends React.Component
{
{state.toSpace > 0 ? 'To Space' : 'From Space'}
- {fromMemoryMatrix &&
- fromMemoryMatrix.length > 0 &&
- fromMemoryMatrix.map((item, row) => (
+ {fromMemoryMatrix
+ && fromMemoryMatrix.length > 0
+ && fromMemoryMatrix.map((item, row) => (
{row * state.column + state.memorySize / 2}
- {item && item.length > 0 ?
- item.map(content => {
+ {item && item.length > 0
+ ? item.map(content => {
const color = this.getMemoryColor(content);
const bgColor = this.getBackgroundColor(content);
return (
@@ -362,8 +362,8 @@ class CopyGC extends React.Component
{
/>
);
- }) :
- false}
+ })
+ : false}
))}
diff --git a/src/tabs/Csg/canvas_holder.tsx b/src/tabs/Csg/canvas_holder.tsx
index 30b48faa7..c79ee0998 100644
--- a/src/tabs/Csg/canvas_holder.tsx
+++ b/src/tabs/Csg/canvas_holder.tsx
@@ -32,8 +32,8 @@ export default class CanvasHolder extends React.Component<
const { current: canvas } = this.canvasReference;
if (canvas === null) return;
- const renderGroups: RenderGroup[] =
- Core.getRenderGroupManager().getGroupsToRender();
+ const renderGroups: RenderGroup[]
+ = Core.getRenderGroupManager().getGroupsToRender();
const lastRenderGroup: RenderGroup = renderGroups.at(-1) as RenderGroup;
this.statefulRenderer = new StatefulRenderer(
diff --git a/src/tabs/RobotSimulation/index.tsx b/src/tabs/RobotSimulation/index.tsx
index 96fd388df..fb2088239 100644
--- a/src/tabs/RobotSimulation/index.tsx
+++ b/src/tabs/RobotSimulation/index.tsx
@@ -14,8 +14,7 @@ export default {
* @returns {boolean}
*/
toSpawn(context: DebuggerContext) {
- const worldState =
- context.context.moduleContexts.robot_simulation.state?.world?.state;
+ const worldState = context.context.moduleContexts.robot_simulation.state?.world?.state;
return worldState !== undefined;
},
From 91aad7abb5dda5465e44977e656cde4927db87bb Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Sat, 13 Apr 2024 09:00:56 +0800
Subject: [PATCH 28/39] Reformat devserver
---
devserver/src/components/Playground.tsx | 11 +++++------
devserver/src/components/Workspace.tsx | 2 +-
devserver/src/components/controlBar/ControlBar.tsx | 2 +-
.../src/components/controlBar/ControlBarRunButton.tsx | 2 +-
devserver/src/components/sideContent/SideContent.tsx | 2 +-
devserver/src/components/sideContent/utils.ts | 7 +++----
6 files changed, 12 insertions(+), 14 deletions(-)
diff --git a/devserver/src/components/Playground.tsx b/devserver/src/components/Playground.tsx
index 7049e3225..1d7e2c646 100644
--- a/devserver/src/components/Playground.tsx
+++ b/devserver/src/components/Playground.tsx
@@ -75,8 +75,7 @@ const Playground: React.FC<{}> = () => {
name: undefined
}));
- const builtins: Record =
- SourceDocumentation.builtins[Chapter.SOURCE_4];
+ const builtins: Record = SourceDocumentation.builtins[Chapter.SOURCE_4];
const builtinSuggestions = Object.entries(builtins).map(
([builtin, thing]) => ({
...thing,
@@ -93,7 +92,7 @@ const Playground: React.FC<{}> = () => {
}, [editorValue, codeContext]);
const loadTabs = () => getDynamicTabs(codeContext)
- .then((tabs) => {
+ .then(tabs => {
setDynamicTabs(tabs);
const newIds = tabs.map(({ id }) => id);
@@ -104,7 +103,7 @@ const Playground: React.FC<{}> = () => {
}
setAlerts(newIds);
})
- .catch((error) => {
+ .catch(error => {
showToast(errorToast);
console.log(error);
});
@@ -115,7 +114,7 @@ const Playground: React.FC<{}> = () => {
codeContext.moduleContexts = mockModuleContext.moduleContexts = {};
runInContext(editorValue, codeContext)
- .then((result) => {
+ .then(result => {
if (codeContext.errors.length > 0) {
showToast(errorToast);
} else {
@@ -179,7 +178,7 @@ const Playground: React.FC<{}> = () => {
selectedTabId,
onChange: useCallback((newId: string) => {
setSelectedTab(newId);
- setAlerts(alerts.filter((id) => id !== newId));
+ setAlerts(alerts.filter(id => id !== newId));
}, [alerts]),
alerts
}
diff --git a/devserver/src/components/Workspace.tsx b/devserver/src/components/Workspace.tsx
index 4b34069a5..af18450cb 100644
--- a/devserver/src/components/Workspace.tsx
+++ b/devserver/src/components/Workspace.tsx
@@ -31,7 +31,7 @@ const bottomResizeOnly: Enable = { bottom: true };
export type WorkspaceProps = DispatchProps & StateProps;
-const Workspace: React.FC = (props) => {
+const Workspace: React.FC = props => {
const contentContainerDiv = React.useRef(null);
const editorDividerDiv = React.useRef(null);
const leftParentResizable = React.useRef(null);
diff --git a/devserver/src/components/controlBar/ControlBar.tsx b/devserver/src/components/controlBar/ControlBar.tsx
index e223fcdad..14c81360e 100644
--- a/devserver/src/components/controlBar/ControlBar.tsx
+++ b/devserver/src/components/controlBar/ControlBar.tsx
@@ -8,7 +8,7 @@ export type ControlBarProps = {
editingWorkspaceButtons?: Array;
};
-const ControlBar: React.FC = (props) => {
+const ControlBar: React.FC = props => {
const editorControl = (
{props.editorButtons}
diff --git a/devserver/src/components/controlBar/ControlBarRunButton.tsx b/devserver/src/components/controlBar/ControlBarRunButton.tsx
index e07163fd1..a3600c013 100644
--- a/devserver/src/components/controlBar/ControlBarRunButton.tsx
+++ b/devserver/src/components/controlBar/ControlBarRunButton.tsx
@@ -16,7 +16,7 @@ type StateProps = {
type ControlButtonRunButtonProps = DispatchProps & StateProps;
-export const ControlBarRunButton: React.FC = (props) => {
+export const ControlBarRunButton: React.FC = props => {
const tooltipContent = 'Evaluate the program';
return (
diff --git a/devserver/src/components/sideContent/SideContent.tsx b/devserver/src/components/sideContent/SideContent.tsx
index 8f6741f57..01acd221b 100644
--- a/devserver/src/components/sideContent/SideContent.tsx
+++ b/devserver/src/components/sideContent/SideContent.tsx
@@ -89,7 +89,7 @@ const SideContent: React.FC = ({
if (onChange) onChange(newId, oldId);
}}
>
- {dynamicTabs.map((tab) => renderTab(tab, alerts.includes(tab.id), editorWidth, sideContentHeight))}
+ {dynamicTabs.map(tab => renderTab(tab, alerts.includes(tab.id), editorWidth, sideContentHeight))}
diff --git a/devserver/src/components/sideContent/utils.ts b/devserver/src/components/sideContent/utils.ts
index 54e7d4adb..3bbee3193 100644
--- a/devserver/src/components/sideContent/utils.ts
+++ b/devserver/src/components/sideContent/utils.ts
@@ -6,14 +6,13 @@ const moduleManifest = manifest as Record;
export const getDynamicTabs = async (context: Context) => {
const moduleSideContents = await Promise.all(
- Object.keys(context.moduleContexts).flatMap((moduleName) =>
- moduleManifest[moduleName].tabs.map(async (tabName) => {
+ Object.keys(context.moduleContexts)
+ .flatMap(moduleName => moduleManifest[moduleName].tabs.map(async tabName => {
const { default: rawTab } = await import(
`../../../../src/tabs/${tabName}/index.tsx`
);
return rawTab as ModuleSideContent;
- })
- )
+ }))
);
return moduleSideContents
From a75a77f6e4f1f928978191bd3cd842d1af296a64 Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Sat, 13 Apr 2024 09:02:16 +0800
Subject: [PATCH 29/39] Reformat utils
---
devserver/src/components/sideContent/utils.ts | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/devserver/src/components/sideContent/utils.ts b/devserver/src/components/sideContent/utils.ts
index 3bbee3193..f561f3089 100644
--- a/devserver/src/components/sideContent/utils.ts
+++ b/devserver/src/components/sideContent/utils.ts
@@ -8,9 +8,7 @@ export const getDynamicTabs = async (context: Context) => {
const moduleSideContents = await Promise.all(
Object.keys(context.moduleContexts)
.flatMap(moduleName => moduleManifest[moduleName].tabs.map(async tabName => {
- const { default: rawTab } = await import(
- `../../../../src/tabs/${tabName}/index.tsx`
- );
+ const { default: rawTab } = await import(`../../../../src/tabs/${tabName}/index.tsx`);
return rawTab as ModuleSideContent;
}))
);
From 0facb84a8559a3e32648fc40dcfd40fa57aab4de Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Sat, 13 Apr 2024 09:04:45 +0800
Subject: [PATCH 30/39] Reformat MultiUserController
---
src/bundles/communication/MultiUserController.ts | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/src/bundles/communication/MultiUserController.ts b/src/bundles/communication/MultiUserController.ts
index b2c23b0a6..f2520f539 100644
--- a/src/bundles/communication/MultiUserController.ts
+++ b/src/bundles/communication/MultiUserController.ts
@@ -7,8 +7,7 @@ import { MqttController, STATE_DISCONNECTED } from './MqttController';
export class MultiUserController {
controller: MqttController | null = null;
connectionState: string = STATE_DISCONNECTED;
- messageCallbacks: Map void>
- = new Map();
+ messageCallbacks: Map void> = new Map();
/**
* Sets up and connect to the MQTT link.
From 15e7926f9181b51e1282b2aa7d0a05462a2b21ea Mon Sep 17 00:00:00 2001
From: Richard Dominick <34370238+RichDom2185@users.noreply.github.com>
Date: Sat, 13 Apr 2024 09:11:49 +0800
Subject: [PATCH 31/39] Reformat CopyGc
---
src/tabs/CopyGc/index.tsx | 12 +++---------
1 file changed, 3 insertions(+), 9 deletions(-)
diff --git a/src/tabs/CopyGc/index.tsx b/src/tabs/CopyGc/index.tsx
index a83683ad1..4709c2bc0 100644
--- a/src/tabs/CopyGc/index.tsx
+++ b/src/tabs/CopyGc/index.tsx
@@ -257,10 +257,8 @@ class CopyGC extends React.Component {
{state.command}
{state.description}
-