Merged PR 219: Refactor App and MainMenu so that App is the one handling the loading + refactor isLoaded into an enum

This commit is contained in:
Eric Nguyen 2022-11-04 12:56:29 +00:00
commit bab144d75a
11 changed files with 506 additions and 475 deletions

View file

@ -162,14 +162,14 @@
/** /**
* Hide the main menu to go to the application. * Hide the main menu to go to the application.
* SetEditor must be called first or the application will crash. * SetEditor must be called first or the application will crash.
* @param isLoaded * @param appState
* @param callback * @param callback
*/ */
public SetLoaded(isLoaded: boolean, callback?: (state: IEditorState) => void) { public SetAppState(appState: SVGLD.AppState, callback?: (state: IEditorState) => void) {
const eventType = 'setLoaded'; const eventType = 'setAppState';
this.app.AddEventListener(eventType, callback); this.app.AddEventListener(eventType, callback);
const component = this.GetAppComponent(); const component = this.GetAppComponent();
component.dispatchEvent(new CustomEvent(eventType, { detail: isLoaded })) component.dispatchEvent(new CustomEvent(eventType, { detail: appState }))
} }
/** /**

657
public/svgld.d.ts vendored
View file

@ -1,67 +1,106 @@
declare namespace SVGLD { declare namespace SVGLD {
/** export interface IMargin {
* Add method when creating a container left?: number;
* - Append will append to the last children in list bottom?: number;
* - Insert will always place it at the begining top?: number;
* - Replace will remove the selected container and insert a new one right?: number;
* (default: Append)
*/
export enum AddMethod {
Append = 0,
Insert = 1,
Replace = 2,
ReplaceParent = 3
} }
export enum MessageType { export interface IPoint {
Normal = 0, x: number;
Success = 1, y: number;
Warning = 2,
Error = 3
} }
export enum Orientation {
Horizontal = 0,
Vertical = 1
}
export enum Position {
Left = 0,
Down = 1,
Up = 2,
Right = 3
}
export enum PositionReference {
TopLeft = 0,
TopCenter = 1,
TopRight = 2,
CenterLeft = 3,
CenterCenter = 4,
CenterRight = 5,
BottomLeft = 6,
BottomCenter = 7,
BottomRight = 8
}
/** /**
* Describe the type of the property. * Model of available symbol to configure the application */
* Used for the assignation in the OnPropertyChange function export interface IAvailableSymbol {
* See ContainerOperations.ts's OnPropertyChange Name: string;
*/ Image: IImage;
export enum PropertyType { Width?: number;
Height?: number;
PositionReference?: PositionReference;
}
export interface IAPIConfiguration {
apiFetchUrl?: string;
apiSetContainerListUrl?: string;
apiGetFeedbackUrl?: string;
}
export interface ISymbolModel {
/** Identifier */
id: string;
/** Type */
type: string;
/** Configuration of the symbol */
config: IAvailableSymbol;
/** Horizontal offset */
x: number;
/** Width */
width: number;
/** Height */
height: number;
/** List of linked container id */
linkedContainers: Set<string>;
}
export interface IPattern {
/** /**
* Simple property: is not inside any object: id, x, width... (default) * Unique id for the pattern
*/ */
Simple = 0, id: string;
/** /**
* Style property: is inside the style object: stroke, fillOpacity... * Text to display in the sidebar
*/ */
Style = 1, text: string;
/** /**
* Margin property: is inside the margin property: left, bottom, top, right... * IAvailableContainer id used to wrap the children.
*/ */
Margin = 2 wrapper: string;
/**
* List of ids of Pattern or IAvailableContainer
* If a IAvailableContainer and a Pattern have the same id,
* IAvailableContainer will be prioritized
*/
children: string[];
}
export type ContainerOrPattern = IAvailableContainer | IPattern;
export function GetPattern(id: string, configs: Map<string, IAvailableContainer>, patterns: Map<string, IPattern>): ContainerOrPattern | undefined;
export function IsPattern(id: string, configs: Map<string, IAvailableContainer>, patterns: Map<string, IPattern>): boolean;
export interface IHistoryState {
/** Last editor action */
lastAction: string;
/** Reference to the main container */
mainContainer: string;
containers: Map<string, IContainerModel>;
/** Id of the selected container */
selectedContainerId: string;
/** Counter of type of container. Used for ids. */
typeCounters: Record<string, number>;
/** List of symbols */
symbols: Map<string, ISymbolModel>;
/** Selected symbols id */
selectedSymbolId: string;
}
export interface IGetFeedbackRequest {
/** Current application state */
ApplicationState: IHistoryState;
}
export interface IInputGroup {
key: string;
text: React.ReactNode;
value: string;
} }
@ -75,13 +114,176 @@ export interface IAction {
AddingBehavior: AddMethod; AddingBehavior: AddMethod;
} }
export interface IAPIConfiguration {
apiFetchUrl?: string;
apiSetContainerListUrl?: string; export interface ISetContainerListResponse {
apiGetFeedbackUrl?: string; Containers: IAvailableContainer[];
AddingBehavior?: AddMethod;
} }
export interface IContainerModel {
children: string[];
properties: IContainerProperties;
userData: Record<string, string | number>;
}
/**
* Macro for creating the interface
* Do not add methods since they will be lost during serialization
*/
export class ContainerModel implements IContainerModel {
children: string[];
properties: IContainerProperties;
userData: Record<string, string | number>;
constructor(properties: IContainerProperties, children?: string[], userData?: {});
}
/**
* A SizePointer is a pointer in a 1 dimensional array of width/space
* x being the address where the pointer is pointing
* width being the overall (un)allocated space affected to the address
*/
export interface ISizePointer {
x: number;
width: number;
}
export interface IGetFeedbackResponse {
messages: IMessage[];
}
/** Model of configuration for the application to configure it */
export interface IConfiguration {
AvailableContainers: IAvailableContainer[];
AvailableSymbols: IAvailableSymbol[];
Categories: ICategory[];
Patterns: IPattern[];
MainContainer: IAvailableContainer;
APIConfiguration?: IAPIConfiguration;
}
export interface ISetContainerListRequest {
/** Name of the action declared in the API */
Action: IAction;
/** Selected container */
Container: IContainerModel;
/** The previous sibling container */
PreviousContainer: IContainerModel | undefined;
/** The next sibling container */
NextContainer: IContainerModel | undefined;
/** Current application state */
ApplicationState: IHistoryState;
}
/**
* Properties of a container
*/
export interface IContainerProperties {
/** id of the container */
id: string;
/** type matching the configuration on construction */
type: string;
/** id of the parent container (null when there is no parent) */
parentId: string;
/** id of the linked symbol ('' when there is no parent) */
linkedSymbolId: string;
/** Text displayed in the container */
displayedText: string;
/** orientation */
orientation: Orientation;
/** horizontal offset */
x: number;
/** vertical offset */
y: number;
/** margin */
margin: IMargin;
/** width */
width: number;
/** height */
height: number;
/**
* Minimum width (min=1)
*/
minWidth: number;
/**
* Maximum width
*/
maxWidth: number;
/**
* Minimum height (min=1)
*/
minHeight: number;
/**
* Maximum height
*/
maxHeight: number;
/** true if anchor, false otherwise */
isAnchor: boolean;
/** true if flex, false otherwise */
isFlex: boolean;
/** Horizontal alignment, also determines the visual location of x {Left = 0, Center, Right } */
positionReference: PositionReference;
/** Hide the children in the treeview */
hideChildrenInTreeview: boolean;
/** if true, show the dimension of the container */
showSelfDimensions: Position[];
/** if true show the overall dimensions of its children */
showChildrenDimensions: Position[];
/**
* if true, allows a parent dimension borrower to borrow its x coordinate
* as a reference point for a dimension
*/
markPosition: Orientation[];
/**
* if true, show a dimension from the edge of the container to end
* and insert dimensions marks at lift up children (see liftDimensionToBorrower)
*/
showDimensionWithMarks: Position[];
/**
* Warnings of a container
*/
warning: string;
/**
* (optional)
* Replace a <rect> by a customized "SVG". It is not really an svg but it at least allows
* to draw some patterns that can be bind to the properties of the container
* Use {prop} to bind a property. Use {{ styleProp }} to use an object.
* Example :
* ```
* `<rect width="{width}" height="{height}" style="{style}"></rect>
* <rect width="{width}" height="{height}" stroke="black" fill-opacity="0"></rect>
* <line x1="0" y1="0" x2="{width}" y2="{height}" stroke="black" style='{{ "transform":"scaleY(0.5)"}}'></line>
* <line x1="{width}" y1="0" x2="0" y2="{height}" stroke="black" style='{userData.styleLine}'></line>
* `
* ```
*/
customSVG?: string;
/**
* (optional)
* Style of the <rect>
*/
style?: React.CSSProperties;
/**
* (optional)
* User data that can be used for data storage or custom SVG
*/
userData?: object;
}
@ -213,157 +415,13 @@ export interface IAvailableContainer {
* (optional) * (optional)
* User data that can be used for data storage or custom SVG * User data that can be used for data storage or custom SVG
*/ */
UserData?: IKeyValue[]; UserData?: object;
} }
export interface IMessage {
/** text: string;
* Model of available symbol to configure the application */ type: MessageType;
export interface IAvailableSymbol {
Name: string;
Image: IImage;
Width?: number;
Height?: number;
PositionReference?: PositionReference;
}
export interface ICategory {
Type: string;
DisplayedText?: string;
}
/** Model of configuration for the application to configure it */
export interface IConfiguration {
AvailableContainers: IAvailableContainer[];
AvailableSymbols: IAvailableSymbol[];
Categories: ICategory[];
Patterns: IPattern[];
MainContainer: IAvailableContainer;
APIConfiguration?: IAPIConfiguration;
}
export interface IContainerModel {
children: string[];
properties: IContainerProperties;
userData: Record<string, string | number>;
}
/**
* Macro for creating the interface
* Do not add methods since they will be lost during serialization
*/
export class ContainerModel implements IContainerModel {
children: string[];
properties: IContainerProperties;
userData: Record<string, string | number>;
constructor(properties: IContainerProperties, children?: string[], userData?: {});
}
/**
* Properties of a container
*/
export interface IContainerProperties {
/** id of the container */
id: string;
/** type matching the configuration on construction */
type: string;
/** id of the parent container (null when there is no parent) */
parentId: string;
/** id of the linked symbol ('' when there is no parent) */
linkedSymbolId: string;
/** Text displayed in the container */
displayedText: string;
/** orientation */
orientation: Orientation;
/** horizontal offset */
x: number;
/** vertical offset */
y: number;
/** margin */
margin: IMargin;
/** width */
width: number;
/** height */
height: number;
/**
* Minimum width (min=1)
*/
minWidth: number;
/**
* Maximum width
*/
maxWidth: number;
/**
* Minimum height (min=1)
*/
minHeight: number;
/**
* Maximum height
*/
maxHeight: number;
/** true if anchor, false otherwise */
isAnchor: boolean;
/** true if flex, false otherwise */
isFlex: boolean;
/** Horizontal alignment, also determines the visual location of x {Left = 0, Center, Right } */
positionReference: PositionReference;
/** Hide the children in the treeview */
hideChildrenInTreeview: boolean;
/** if true, show the dimension of the container */
showSelfDimensions: Position[];
/** if true show the overall dimensions of its children */
showChildrenDimensions: Position[];
/**
* if true, allows a parent dimension borrower to borrow its x coordinate
* as a reference point for a dimension
*/
markPosition: Orientation[];
/**
* if true, show a dimension from the edge of the container to end
* and insert dimensions marks at lift up children (see liftDimensionToBorrower)
*/
showDimensionWithMarks: Position[];
/**
* Warnings of a container
*/
warning: string;
/**
* (optional)
* Replace a <rect> by a customized "SVG". It is not really an svg but it at least allows
* to draw some patterns that can be bind to the properties of the container
* Use {prop} to bind a property. Use {{ styleProp }} to use an object.
* Example :
* ```
* `<rect width="{width}" height="{height}" style="{style}"></rect>
* <rect width="{width}" height="{height}" stroke="black" fill-opacity="0"></rect>
* <line x1="0" y1="0" x2="{width}" y2="{height}" stroke="black" style='{{ "transform":"scaleY(0.5)"}}'></line>
* <line x1="{width}" y1="0" x2="0" y2="{height}" stroke="black" style='{userData.styleLine}'></line>
* `
* ```
*/
customSVG?: string;
/**
* (optional)
* Style of the <rect>
*/
style?: React.CSSProperties;
/**
* (optional)
* User data that can be used for data storage or custom SVG
*/
userData?: IKeyValue[];
} }
@ -374,33 +432,9 @@ export interface IEditorState {
configuration: IConfiguration; configuration: IConfiguration;
} }
export interface ICategory {
export interface IGetFeedbackRequest { Type: string;
/** Current application state */ DisplayedText?: string;
ApplicationState: IHistoryState;
}
export interface IGetFeedbackResponse {
messages: IMessage[];
}
export interface IHistoryState {
/** Last editor action */
lastAction: string;
/** Reference to the main container */
mainContainer: string;
containers: Map<string, IContainerModel>;
/** Id of the selected container */
selectedContainerId: string;
/** Counter of type of container. Used for ids. */
typeCounters: Record<string, number>;
/** List of symbols */
symbols: Map<string, ISymbolModel>;
/** Selected symbols id */
selectedSymbolId: string;
} }
/** /**
@ -421,116 +455,75 @@ export interface IImage {
Svg?: string; Svg?: string;
} }
export enum MessageType {
export interface IInputGroup { Normal = 0,
key: string; Success = 1,
text: React.ReactNode; Warning = 2,
value: string; Error = 3
}
export interface IKeyValue {
Key: string;
Value: string;
}
export interface ILanguage {
language: string;
dictionary: Record<string, string>;
languageChange?: (selected: string) => void;
}
export interface IMargin {
left?: number;
bottom?: number;
top?: number;
right?: number;
}
export interface IMessage {
text: string;
type: MessageType;
}
export interface IPattern {
/**
* Unique id for the pattern
*/
id: string;
/**
* Text to display in the sidebar
*/
text: string;
/**
* IAvailableContainer id used to wrap the children.
*/
wrapper: string;
/**
* List of ids of Pattern or IAvailableContainer
* If a IAvailableContainer and a Pattern have the same id,
* IAvailableContainer will be prioritized
*/
children: string[];
}
export type ContainerOrPattern = IAvailableContainer | IPattern;
export function GetPattern(id: string, configs: Map<string, IAvailableContainer>, patterns: Map<string, IPattern>): ContainerOrPattern | undefined;
export function IsPattern(id: string, configs: Map<string, IAvailableContainer>, patterns: Map<string, IPattern>): boolean;
export interface IPoint {
x: number;
y: number;
}
export interface ISetContainerListRequest {
/** Name of the action declared in the API */
Action: IAction;
/** Selected container */
Container: IContainerModel;
/** The previous sibling container */
PreviousContainer: IContainerModel | undefined;
/** The next sibling container */
NextContainer: IContainerModel | undefined;
/** Current application state */
ApplicationState: IHistoryState;
}
export interface ISetContainerListResponse {
Containers: IAvailableContainer[];
AddingBehavior?: AddMethod;
} }
/** /**
* A SizePointer is a pointer in a 1 dimensional array of width/space * Add method when creating a container
* x being the address where the pointer is pointing * - Append will append to the last children in list
* width being the overall (un)allocated space affected to the address * - Insert will always place it at the begining
* - Replace will remove the selected container and insert a new one
* (default: Append)
*/ */
export interface ISizePointer { export enum AddMethod {
x: number; Append = 0,
width: number; Insert = 1,
Replace = 2,
ReplaceParent = 3
} }
/**
* Describe the type of the property.
* Used for the assignation in the OnPropertyChange function
* See ContainerOperations.ts's OnPropertyChange
*/
export enum PropertyType {
/**
* Simple property: is not inside any object: id, x, width... (default)
*/
Simple = 0,
/**
* Style property: is inside the style object: stroke, fillOpacity...
*/
Style = 1,
/**
* Margin property: is inside the margin property: left, bottom, top, right...
*/
Margin = 2
}
export interface ISymbolModel { export enum PositionReference {
/** Identifier */ TopLeft = 0,
id: string; TopCenter = 1,
/** Type */ TopRight = 2,
type: string; CenterLeft = 3,
/** Configuration of the symbol */ CenterCenter = 4,
config: IAvailableSymbol; CenterRight = 5,
/** Horizontal offset */ BottomLeft = 6,
x: number; BottomCenter = 7,
/** Width */ BottomRight = 8
width: number; }
/** Height */
height: number; export enum AppState {
/** List of linked container id */ MainMenu = 0,
linkedContainers: Set<string>; Loading = 1,
Loaded = 2
}
export enum Orientation {
Horizontal = 0,
Vertical = 1
}
export enum Position {
Left = 0,
Down = 1,
Up = 2,
Right = 3
} }
} }

View file

@ -1,13 +1,14 @@
import { Dispatch, SetStateAction } from 'react'; import { Dispatch, SetStateAction } from 'react';
import { AppState } from '../../../Enums/AppState';
import { IEditorState } from '../../../Interfaces/IEditorState'; import { IEditorState } from '../../../Interfaces/IEditorState';
import { Revive } from '../../../utils/saveload'; import { Revive } from '../../../utils/saveload';
export function LoadState( export function LoadState(
editorState: IEditorState, editorState: IEditorState,
setEditorState: Dispatch<SetStateAction<IEditorState>>, setEditorState: Dispatch<SetStateAction<IEditorState>>,
setLoaded: Dispatch<SetStateAction<boolean>> setAppState: Dispatch<SetStateAction<AppState>>
): void { ): void {
Revive(editorState); Revive(editorState);
setEditorState(editorState); setEditorState(editorState);
setLoaded(true); setAppState(AppState.Loaded);
} }

View file

@ -1,9 +1,10 @@
import { Dispatch, SetStateAction, useEffect } from 'react'; import { Dispatch, SetStateAction } from 'react';
import { IConfiguration } from '../../../Interfaces/IConfiguration'; import { IConfiguration } from '../../../Interfaces/IConfiguration';
import { FetchConfiguration } from '../../API/api'; import { FetchConfiguration } from '../../API/api';
import { IEditorState } from '../../../Interfaces/IEditorState'; import { IEditorState } from '../../../Interfaces/IEditorState';
import { LoadState } from './Load'; import { LoadState } from './Load';
import { DISABLE_API, GetDefaultEditorState } from '../../../utils/default'; import { DISABLE_API, GetDefaultEditorState } from '../../../utils/default';
import { AppState } from '../../../Enums/AppState';
export function NewEditor( export function NewEditor(
editorState: IEditorState, editorState: IEditorState,
@ -36,7 +37,7 @@ export function NewEditor(
export function LoadEditor( export function LoadEditor(
files: FileList | null, files: FileList | null,
setEditorState: Dispatch<SetStateAction<IEditorState>>, setEditorState: Dispatch<SetStateAction<IEditorState>>,
setLoaded: Dispatch<SetStateAction<boolean>> setAppState: Dispatch<SetStateAction<AppState>>
): void { ): void {
if (files === null) { if (files === null) {
return; return;
@ -47,7 +48,7 @@ export function LoadEditor(
const result = reader.result as string; const result = reader.result as string;
const editorState: IEditorState = JSON.parse(result); const editorState: IEditorState = JSON.parse(result);
LoadState(editorState, setEditorState, setLoaded); LoadState(editorState, setEditorState, setAppState);
}); });
reader.readAsText(file); reader.readAsText(file);
} }

View file

@ -6,7 +6,9 @@ import { Editor } from '../Editor/Editor';
import { IEditorState } from '../../Interfaces/IEditorState'; import { IEditorState } from '../../Interfaces/IEditorState';
import { LoadState } from './Actions/Load'; import { LoadState } from './Actions/Load';
import { LoadEditor, NewEditor } from './Actions/MenuActions'; import { LoadEditor, NewEditor } from './Actions/MenuActions';
import { DEFAULT_CONFIG, DEFAULT_MAINCONTAINER_PROPS } from '../../utils/default'; import { DEFAULT_CONFIG, DEFAULT_MAINCONTAINER_PROPS, FAST_BOOT } from '../../utils/default';
import { AppState } from '../../Enums/AppState';
import { Loader } from '../Loader/Loader';
import { LanguageContext } from '../LanguageProvider/LanguageProvider'; import { LanguageContext } from '../LanguageProvider/LanguageProvider';
// App will never have props // App will never have props
@ -16,9 +18,9 @@ interface IAppProps {
} }
function UseHTTPGETStatePreloading( function UseHTTPGETStatePreloading(
isLoaded: boolean, appState: AppState,
setEditorState: Dispatch<SetStateAction<IEditorState>>, setEditorState: Dispatch<SetStateAction<IEditorState>>,
setLoaded: Dispatch<SetStateAction<boolean>> setAppState: Dispatch<SetStateAction<AppState>>
): void { ): void {
useEffect(() => { useEffect(() => {
const queryString = window.location.search; const queryString = window.location.search;
@ -29,21 +31,21 @@ function UseHTTPGETStatePreloading(
return; return;
} }
if (!isLoaded) { if (appState !== AppState.Loaded) {
fetch(state) fetch(state)
.then( .then(
async(response) => await response.json(), async(response) => await response.json(),
(error) => { throw new Error(error); } (error) => { throw new Error(error); }
) )
.then((data: IEditorState) => { .then((data: IEditorState) => {
LoadState(data, setEditorState, setLoaded); LoadState(data, setEditorState, setAppState);
}, (error) => { throw new Error(error); }); }, (error) => { throw new Error(error); });
} }
}); });
}; };
export function App(props: IAppProps): JSX.Element { export function App(props: IAppProps): JSX.Element {
const [isLoaded, setLoaded] = useState<boolean>(false); const [appState, setAppState] = useState<AppState>(FAST_BOOT);
const appRef = useRef<HTMLDivElement>(null); const appRef = useRef<HTMLDivElement>(null);
const languageContext = useContext(LanguageContext); const languageContext = useContext(LanguageContext);
@ -72,48 +74,59 @@ export function App(props: IAppProps): JSX.Element {
appRef, appRef,
languageContext, languageContext,
setEditorState, setEditorState,
setLoaded setAppState
); );
UseHTTPGETStatePreloading(isLoaded, setEditorState, setLoaded); UseHTTPGETStatePreloading(appState, setEditorState, setAppState);
const enableLoaded = useCallback(() => { switch (appState) {
setLoaded(true); case AppState.Loaded:
}, []); return (
<div
if (isLoaded) { ref={appRef}
return ( className='App'
<div >
ref={appRef} <Editor
className='App' root={props.root}
> configuration={editorState.configuration}
<Editor history={editorState.history}
root={props.root} historyCurrentStep={editorState.historyCurrentStep}
configuration={editorState.configuration} />
history={editorState.history} </div>
historyCurrentStep={editorState.historyCurrentStep} );
/> case AppState.Loading:
</div> return (
); <div
ref={appRef}
className='App mainmenu-bg'
>
<div className='absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2'>
<Loader />
</div>
</div>
);
default:
return (
<div
ref={appRef}
className='App mainmenu-bg'
>
<MainMenu
newEditor={() => {
setAppState(AppState.Loading);
NewEditor(
editorState,
(newEditor) => setEditorState(newEditor),
() => setAppState(AppState.Loaded)
);
}}
loadEditor={(files: FileList | null) => LoadEditor(
files,
setEditorState,
setAppState
)}
/>
</div>
);
} }
return (
<div
ref={appRef}
className='App mainmenu-bg'
>
<MainMenu
newEditor={() => NewEditor(
editorState,
(newEditor) => setEditorState(newEditor),
enableLoaded
)}
loadEditor={(files: FileList | null) => LoadEditor(
files,
setEditorState,
setLoaded
)}
/>
</div>
);
}; };

View file

@ -1,6 +1,4 @@
import * as React from 'react'; import * as React from 'react';
import { FAST_BOOT } from '../../utils/default';
import { Loader } from '../Loader/Loader';
import { Text } from '../Text/Text'; import { Text } from '../Text/Text';
interface IMainMenuProps { interface IMainMenuProps {
@ -11,21 +9,11 @@ interface IMainMenuProps {
enum WindowState { enum WindowState {
Main, Main,
Load, Load,
Loading,
} }
export function MainMenu(props: IMainMenuProps): JSX.Element { export function MainMenu(props: IMainMenuProps): JSX.Element {
const [windowState, setWindowState] = React.useState(WindowState.Main); const [windowState, setWindowState] = React.useState(WindowState.Main);
if (FAST_BOOT) {
props.newEditor();
return (
<div className='absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2'>
<Loader />
</div>
);
}
switch (windowState) { switch (windowState) {
case WindowState.Load: case WindowState.Load:
return ( return (
@ -66,12 +54,6 @@ export function MainMenu(props: IMainMenuProps): JSX.Element {
</div> </div>
); );
case WindowState.Loading:
return (
<div className='absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2'>
<Loader />
</div>
);
default: default:
return ( return (
<div className='absolute bg-blue-50 p-12 <div className='absolute bg-blue-50 p-12
@ -81,7 +63,6 @@ export function MainMenu(props: IMainMenuProps): JSX.Element {
w-full sm:w-auto w-full sm:w-auto
sm:top-1/2 sm:left-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2'> sm:top-1/2 sm:left-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2'>
<button type="button" className='mainmenu-btn' onClick={() => { <button type="button" className='mainmenu-btn' onClick={() => {
setWindowState(WindowState.Loading);
props.newEditor(); props.newEditor();
}}> }}>
{Text({ textId: '@StartFromScratch' })} {Text({ textId: '@StartFromScratch' })}

5
src/Enums/AppState.ts Normal file
View file

@ -0,0 +1,5 @@
export enum AppState {
MainMenu,
Loading,
Loaded
}

View file

@ -1,4 +1,5 @@
import { useEffect } from 'react'; import { useEffect } from 'react';
import { AppState } from '../Enums/AppState';
import { IConfiguration } from '../Interfaces/IConfiguration'; import { IConfiguration } from '../Interfaces/IConfiguration';
import { IEditorState } from '../Interfaces/IEditorState'; import { IEditorState } from '../Interfaces/IEditorState';
import { IHistoryState } from '../Interfaces/IHistoryState'; import { IHistoryState } from '../Interfaces/IHistoryState';
@ -11,7 +12,7 @@ interface IAppEventParams {
root: Element | Document root: Element | Document
languageContext: ILanguage languageContext: ILanguage
setEditor: (newState: IEditorState) => void setEditor: (newState: IEditorState) => void
setLoaded: (loaded: boolean) => void setAppState: (appState: AppState) => void
eventInitDict?: CustomEventInit eventInitDict?: CustomEventInit
} }
@ -22,7 +23,7 @@ export interface IAppEvent {
export const events: IAppEvent[] = [ export const events: IAppEvent[] = [
{ name: 'setEditor', func: SetEditor }, { name: 'setEditor', func: SetEditor },
{ name: 'setLoaded', func: SetLoaded }, { name: 'setAppState', func: SetAppState },
{ name: 'reviveEditorState', func: ReviveEditorState }, { name: 'reviveEditorState', func: ReviveEditorState },
{ name: 'reviveHistory', func: ReviveHistory }, { name: 'reviveHistory', func: ReviveHistory },
{ name: 'getDefaultEditorState', func: GetDefaultEditorState }, { name: 'getDefaultEditorState', func: GetDefaultEditorState },
@ -36,7 +37,7 @@ export function UseCustomEvents(
appRef: React.RefObject<HTMLDivElement>, appRef: React.RefObject<HTMLDivElement>,
languageContext: ILanguage, languageContext: ILanguage,
setEditor: (newState: IEditorState) => void, setEditor: (newState: IEditorState) => void,
setLoaded: (loaded: boolean) => void setAppState: (appState: AppState) => void
): void { ): void {
useEffect(() => { useEffect(() => {
const funcs = new Map<string, () => void>(); const funcs = new Map<string, () => void>();
@ -46,7 +47,7 @@ export function UseCustomEvents(
root, root,
languageContext, languageContext,
setEditor, setEditor,
setLoaded, setAppState,
eventInitDict eventInitDict
}); });
} }
@ -68,20 +69,22 @@ export function UseCustomEvents(
function SetEditor({ function SetEditor({
root, root,
setEditor, setEditor,
setAppState,
eventInitDict eventInitDict
}: IAppEventParams): void { }: IAppEventParams): void {
const editor: IEditorState = eventInitDict?.detail; const editor: IEditorState = eventInitDict?.detail;
setEditor(editor); setEditor(editor);
setAppState(AppState.Loading);
const customEvent = new CustomEvent<IEditorState>('setEditor', { detail: editor }); const customEvent = new CustomEvent<IEditorState>('setEditor', { detail: editor });
root.dispatchEvent(customEvent); root.dispatchEvent(customEvent);
} }
function SetLoaded({ function SetAppState({
setLoaded, setAppState,
eventInitDict eventInitDict
}: IAppEventParams): void { }: IAppEventParams): void {
const isLoaded: boolean = eventInitDict?.detail; const appState: AppState = eventInitDict?.detail;
setLoaded(isLoaded); setAppState(appState);
} }
function ReviveEditorState({ function ReviveEditorState({

View file

@ -9,15 +9,15 @@ import { IHistoryState } from '../Interfaces/IHistoryState';
import { FindContainerById } from '../utils/itertools'; import { FindContainerById } from '../utils/itertools';
import { GetCircularReplacer } from '../utils/saveload'; import { GetCircularReplacer } from '../utils/saveload';
// TODO: set the params of func in an interface interface IEditorEventParams {
root: Element | Document
editorState: IEditorState
setNewHistory: (newHistory: IHistoryState[], historyCurrentStep?: number) => void
eventInitDict?: CustomEventInit
}
export interface IEditorEvent { export interface IEditorEvent {
name: string name: string
func: ( func: (params: IEditorEventParams) => void
root: Element | Document,
editorState: IEditorState,
setNewHistory: (newHistory: IHistoryState[], historyCurrentStep?: number) => void,
eventInitDict?: CustomEventInit
) => void
} }
export const events: IEditorEvent[] = [ export const events: IEditorEvent[] = [
@ -55,12 +55,12 @@ export function UseCustomEvents(
const funcs = new Map<string, () => void>(); const funcs = new Map<string, () => void>();
for (const event of events) { for (const event of events) {
function Func(eventInitDict?: CustomEventInit): void { function Func(eventInitDict?: CustomEventInit): void {
return event.func( return event.func({
root, root,
editorState, editorState,
setNewHistory, setNewHistory,
eventInitDict eventInitDict
); });
} }
editorRef.current?.addEventListener(event.name, Func); editorRef.current?.addEventListener(event.name, Func);
funcs.set(event.name, Func); funcs.set(event.name, Func);
@ -94,24 +94,30 @@ export function UseEditorListener(
}); });
} }
function GetEditorState(root: Element | Document, function GetEditorState({
editorState: IEditorState): void { root,
editorState
}: IEditorEventParams): void {
const customEvent = new CustomEvent<IEditorState>('getEditorState', { detail: structuredClone(editorState) }); const customEvent = new CustomEvent<IEditorState>('getEditorState', { detail: structuredClone(editorState) });
root.dispatchEvent(customEvent); root.dispatchEvent(customEvent);
} }
function GetEditorStateAsString(root: Element | Document, function GetEditorStateAsString({
editorState: IEditorState): void { root,
editorState
}: IEditorEventParams): void {
const spaces = import.meta.env.DEV ? 4 : 0; const spaces = import.meta.env.DEV ? 4 : 0;
const data = JSON.stringify(editorState, GetCircularReplacer(), spaces); const data = JSON.stringify(editorState, GetCircularReplacer(), spaces);
const customEvent = new CustomEvent<string>('getEditorStateAsString', { detail: data }); const customEvent = new CustomEvent<string>('getEditorStateAsString', { detail: data });
root.dispatchEvent(customEvent); root.dispatchEvent(customEvent);
} }
function SetHistory(root: Element | Document, function SetHistory({
editorState: IEditorState, root,
setNewHistory: (newHistory: IHistoryState[], historyCurrentStep?: number) => void, editorState,
eventInitDict?: CustomEventInit): void { setNewHistory,
eventInitDict
}: IEditorEventParams): void {
const history: IHistoryState[] = eventInitDict?.detail.history; const history: IHistoryState[] = eventInitDict?.detail.history;
const historyCurrentStep: number | undefined = eventInitDict?.detail.historyCurrentStep; const historyCurrentStep: number | undefined = eventInitDict?.detail.historyCurrentStep;
setNewHistory(history, historyCurrentStep); setNewHistory(history, historyCurrentStep);
@ -119,18 +125,22 @@ function SetHistory(root: Element | Document,
root.dispatchEvent(customEvent); root.dispatchEvent(customEvent);
} }
function GetCurrentHistoryState(root: Element | Document, function GetCurrentHistoryState({
editorState: IEditorState): void { root,
editorState
}: IEditorEventParams): void {
const customEvent = new CustomEvent<IHistoryState>( const customEvent = new CustomEvent<IHistoryState>(
'getCurrentHistoryState', 'getCurrentHistoryState',
{ detail: structuredClone(editorState.history[editorState.historyCurrentStep]) }); { detail: structuredClone(editorState.history[editorState.historyCurrentStep]) });
root.dispatchEvent(customEvent); root.dispatchEvent(customEvent);
} }
function AppendNewState(root: Element | Document, function AppendNewState({
editorState: IEditorState, root,
setNewHistory: (newHistory: IHistoryState[]) => void, editorState,
eventInitDict?: CustomEventInit): void { setNewHistory,
eventInitDict
}: IEditorEventParams): void {
const state: IHistoryState = eventInitDict?.detail.state; const state: IHistoryState = eventInitDict?.detail.state;
const history = GetCurrentHistory(editorState.history, editorState.historyCurrentStep); const history = GetCurrentHistory(editorState.history, editorState.historyCurrentStep);
@ -143,10 +153,12 @@ function AppendNewState(root: Element | Document,
root.dispatchEvent(customEvent); root.dispatchEvent(customEvent);
} }
function AddContainer(root: Element | Document, function AddContainer({
editorState: IEditorState, root,
setNewHistory: (newHistory: IHistoryState[]) => void, editorState,
eventInitDict?: CustomEventInit): void { setNewHistory,
eventInitDict
}: IEditorEventParams): void {
const { const {
index, index,
type, type,
@ -170,10 +182,12 @@ function AddContainer(root: Element | Document,
root.dispatchEvent(customEvent); root.dispatchEvent(customEvent);
} }
function AddContainerToSelectedContainer(root: Element | Document, function AddContainerToSelectedContainer({
editorState: IEditorState, root,
setNewHistory: (newHistory: IHistoryState[]) => void, editorState,
eventInitDict?: CustomEventInit): void { setNewHistory,
eventInitDict
}: IEditorEventParams): void {
const { const {
index, index,
type type
@ -198,10 +212,12 @@ function AddContainerToSelectedContainer(root: Element | Document,
root.dispatchEvent(customEvent); root.dispatchEvent(customEvent);
} }
function AppendContainer(root: Element | Document, function AppendContainer({
editorState: IEditorState, root,
setNewHistory: (newHistory: IHistoryState[]) => void, editorState,
eventInitDict?: CustomEventInit): void { setNewHistory,
eventInitDict
}: IEditorEventParams): void {
const { const {
type, type,
parentId parentId
@ -228,10 +244,12 @@ function AppendContainer(root: Element | Document,
root.dispatchEvent(customEvent); root.dispatchEvent(customEvent);
} }
function AppendContainerToSelectedContainer(root: Element | Document, function AppendContainerToSelectedContainer({
editorState: IEditorState, root,
setNewHistory: (newHistory: IHistoryState[]) => void, editorState,
eventInitDict?: CustomEventInit): void { setNewHistory,
eventInitDict
}: IEditorEventParams): void {
const { const {
type type
} = eventInitDict?.detail; } = eventInitDict?.detail;
@ -257,10 +275,12 @@ function AppendContainerToSelectedContainer(root: Element | Document,
root.dispatchEvent(customEvent); root.dispatchEvent(customEvent);
} }
function SelectContainer(root: Element | Document, function SelectContainer({
editorState: IEditorState, root,
setNewHistory: (newHistory: IHistoryState[]) => void, editorState,
eventInitDict?: CustomEventInit): void { setNewHistory,
eventInitDict
}: IEditorEventParams): void {
const { const {
containerId containerId
} = eventInitDict?.detail; } = eventInitDict?.detail;
@ -280,10 +300,12 @@ function SelectContainer(root: Element | Document,
root.dispatchEvent(customEvent); root.dispatchEvent(customEvent);
} }
function DeleteContainer(root: Element | Document, function DeleteContainer({
editorState: IEditorState, root,
setNewHistory: (newHistory: IHistoryState[]) => void, editorState,
eventInitDict?: CustomEventInit): void { setNewHistory,
eventInitDict
}: IEditorEventParams): void {
const { const {
containerId containerId
} = eventInitDict?.detail; } = eventInitDict?.detail;
@ -303,10 +325,12 @@ function DeleteContainer(root: Element | Document,
root.dispatchEvent(customEvent); root.dispatchEvent(customEvent);
} }
function AddSymbol(root: Element | Document, function AddSymbol({
editorState: IEditorState, root,
setNewHistory: (newHistory: IHistoryState[]) => void, editorState,
eventInitDict?: CustomEventInit): void { setNewHistory,
eventInitDict
}: IEditorEventParams): void {
const { const {
name name
} = eventInitDict?.detail; } = eventInitDict?.detail;
@ -327,10 +351,12 @@ function AddSymbol(root: Element | Document,
root.dispatchEvent(customEvent); root.dispatchEvent(customEvent);
} }
function SelectSymbol(root: Element | Document, function SelectSymbol({
editorState: IEditorState, root,
setNewHistory: (newHistory: IHistoryState[]) => void, editorState,
eventInitDict?: CustomEventInit): void { setNewHistory,
eventInitDict
}: IEditorEventParams): void {
const { const {
symbolId symbolId
} = eventInitDict?.detail; } = eventInitDict?.detail;
@ -350,10 +376,12 @@ function SelectSymbol(root: Element | Document,
root.dispatchEvent(customEvent); root.dispatchEvent(customEvent);
} }
function DeleteSymbol(root: Element | Document, function DeleteSymbol({
editorState: IEditorState, root,
setNewHistory: (newHistory: IHistoryState[]) => void, editorState,
eventInitDict?: CustomEventInit): void { setNewHistory,
eventInitDict
}: IEditorEventParams): void {
const { const {
symbolId symbolId
} = eventInitDict?.detail; } = eventInitDict?.detail;

6
src/dts/svgld.d.ts vendored
View file

@ -13,6 +13,12 @@ export enum AddMethod {
ReplaceParent = 3 ReplaceParent = 3
} }
export enum AppState {
MainMenu = 0,
Loading = 1,
Loaded = 2
}
export enum MessageType { export enum MessageType {
Normal = 0, Normal = 0,
Success = 1, Success = 1,

View file

@ -11,8 +11,8 @@ import { Position } from '../Enums/Position';
/// EDITOR DEFAULTS /// /// EDITOR DEFAULTS ///
/** Enable fast boot and disable main menu (default = false) */ /** Enable fast boot and disable main menu (0 = disabled, 1 = loading, 2 = loaded) */
export const FAST_BOOT = true; export const FAST_BOOT = import.meta.env.PROD ? 2 : 0;
/** Disable any call to the API (default = false) */ /** Disable any call to the API (default = false) */
export const DISABLE_API = false; export const DISABLE_API = false;