Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP - add wizard reducer and use case examples #65

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
2 changes: 2 additions & 0 deletions client/src/BoardGame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import { Client, BoardProps } from 'boardgame.io/react';
import { Local } from 'boardgame.io/multiplayer';
import { OpenStarTerVillageType } from 'packages/game/src/types';
import Table from './features/Table/Table';
import ActionBoard from './features/ActionBoard/ActionBoard';
import Players from './Players/Players';
import DevActions from './DevActions/DevActions';

const Board: React.FC<BoardProps<OpenStarTerVillageType.State.Root>> = (props) => {
return (
<div className='Board'>
<ActionBoard {...props} />
<Table {...props} />
<Players {...props} />
<DevActions {...props} />
Expand Down
7 changes: 7 additions & 0 deletions client/src/app/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { useDispatch, useSelector } from 'react-redux'
import type { TypedUseSelectorHook } from 'react-redux'
import type { RootState, AppDispatch } from './store'

export const useAppDispatch: () => AppDispatch = useDispatch

export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
247 changes: 247 additions & 0 deletions client/src/app/reducers/wizardReducer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,247 @@
import { createReducer, createAction } from '@reduxjs/toolkit'

namespace WizardStep {
namespace Table {
type ActiveEventType = 'table--event';
type ActiveProjectType = 'table--active-project';
type ActiveJobType = 'table--active-job';
type ActiveMoveType = 'table--active-move';

export type TableType = ActiveEventType | ActiveProjectType | ActiveJobType | ActiveMoveType;
}

namespace Player {
namespace Hand {
type ProjectType = 'player--hand--project';
type ForceType = 'player--hand--force';

export type HandType = ProjectType | ForceType;
}

export type PlayerType = Hand.HandType
}

export type StepType = Table.TableType | Player.PlayerType
}

type Step = {
type: WizardStep.StepType;
value: any;
prevValue?: any;
}

type RequiredStep = {
type: WizardStep.StepType;
limit?: number; // exactly limit, default is 1
min?: number; // minimum limit, default is 0
max?: number; // maximum limit, default is Inf
}

type Page = {
isCancellable: boolean;
requiredSteps: Partial<Record<WizardStep.StepType, RequiredStep>>;
toggledSteps: Step[];
}

type WizardState = {
pages: Page[];
currentPage: number;
}

const initialState: WizardState = {
pages: [],
currentPage: -1,
}

const enum WizardActionTypes {
INIT_WIZARD = 'INIT_WIZARD',
CLEAR_WIZARD = 'CLEAR_WIZARD',
TOGGLE_ON_STEP = 'TOGGLE_ON_STEP',
TOGGLE_OFF_STEP = 'TOGGLE_OFF_STEP',
NEXT_PAGE = 'NEXT_PAGE',
PREV_PAGE = 'PREV_PAGE',
}

const WizardActions = {
init: createAction<Page[]>(WizardActionTypes.INIT_WIZARD),
clear: createAction(WizardActionTypes.CLEAR_WIZARD),
toggleOnStep: createAction<Step>(WizardActionTypes.TOGGLE_ON_STEP),
toggleOffStep: createAction<Step>(WizardActionTypes.TOGGLE_OFF_STEP),
nextPage: createAction(WizardActionTypes.NEXT_PAGE),
prevPage: createAction(WizardActionTypes.PREV_PAGE),
}

const getRequiredLimit = (required: RequiredStep) => {
if (required.limit) {
return {
min: required.limit,
max: required.limit,
}
}
if (required.min || required.max) {
return {
min: required.min || 0,
max: required.max || Infinity,
}
}
return {
min: 0,
max: Infinity,
}
}

export const wizardReducer = createReducer(initialState, (builder) => {
builder
.addCase(WizardActions.init, (state, action) => {
state.pages = action.payload;
state.currentPage = 0;
})
.addCase(WizardActions.clear, () => initialState)
.addCase(WizardActions.toggleOnStep, (state, action) => {
state.pages[state.currentPage].toggledSteps.push(action.payload);
})
.addCase(WizardActions.toggleOffStep, (state, action) => {
const idx = state.pages[state.currentPage].toggledSteps.findIndex((step) =>
action.payload.type === step.type
&& action.payload.value === step.value
&& action.payload.prevValue === step.prevValue);

if (idx >= 0) {
state.pages[state.currentPage].toggledSteps.splice(idx);
}
})
.addCase(WizardActions.nextPage, (state) => {
state.currentPage ++;
state.currentPage = Math.min(state.currentPage, state.pages.length);
})
.addCase(WizardActions.prevPage, (state) => {
state.currentPage --;
state.currentPage = Math.max(0, state.currentPage);
})
})

// Wizard Selector

export const isLegitPage = (state: WizardState): boolean => state.currentPage >= 0;

export const isPageCancellable = (state: WizardState): boolean => isLegitPage(state) && state.pages[state.currentPage].isCancellable;

export const hasNextPage = (state: WizardState): boolean => isLegitPage(state) && state.currentPage < state.pages.length;

export const hasPrevPage = (state: WizardState): boolean => state.currentPage > 1;

export const getCurrentPage = (state: WizardState): Page => state.pages[state.currentPage];

// Page Selector

export const isRequiredStep = (state: Page, stepType: WizardStep.StepType): boolean => !!state.requiredSteps[stepType];

export const isToggledStep = (state: Page, step: Step): boolean => {
const idx = state.toggledSteps.findIndex(toggled => step.type === toggled.type && step.value === toggled.value && step.prevValue === toggled.prevValue);
return idx >= 0;
}

export const isRequiredStepsFulfilled = (state: Page): boolean => {
return Object.values(state.requiredSteps)
.every((requiredStep) => {
const { min, max } = getRequiredLimit(requiredStep);
const toggled = state.toggledSteps.filter(step => step.type === requiredStep.type).length;

return min <= toggled && toggled <= max;
});
}

/**
* // ActionBoard.tsx
* onCreateProjectActionClick = () => {
* dispatch(WizardActions.init(getPagesByActionName('create-project')));
* }
*
* onConfirmBtnClick = () => {
* dispatch(WizardActions.nextPage());
* }
*
* onCancelBtnClick = () => {
* dispatch(WizardActions.prevPage());
* }
*
* onSubmitBtnClick = () => {
* dispatch(WizardActions.clear());
* }
*
* const showCancelBtn = isPageCancellable(state.wizard);
* const showConfirmBtn = hasNextPage(state.wizard);
* const showSubmitBtn = !hasNextPage(state.wizard);
*
* render (<>
* <Toolbar>
* {showCancelBtn && <Button onClick={onCancelBtnClick} label="Cancel" />}
* {showConfirmBtn && <Button onClick={onConfirmClick} label="Confirm" />}
* {showSubmitBtn && <Button onClick={onSubmitClick} label="Submit" />}
* </Toolbar
* </>)
*
* const getPagesByActionName = (name) => {
* switch (name) {
* case 'create-project':
* return [
* {
* isCancellable: true;
* requiredSteps: {
* 'player--hand--project': {
* type: 'player--hand--project',
* limit: 1,
* }
* };
* toggledSteps: [],
* },
* {
* isCancellable: true;
* requiredSteps: {
* 'table--active-job': {
* type: 'table--active-job',
* limit: 1,
* }
* };
* toggledSteps: [],
* },
* ];
* }
* }
*
*
* // Table.tsx
*
* const isActiveProjectSelectable = isRequiredStep(state.wizard, 'table--active-project');
* const isActiveJobSelectable = isRequiredStep(state.wizard, 'table--active-job');
* render(<>
* <ActiveProject isSelectable={isActiveProjectSelectable} />
* ......
* <ActiveJob isSelectable={isActiveJobSelectable} />
* </>)
*
* // ActiveProject.tsx
* // TBD: alternative seletable state injection
* const isSelectable = isRequiredStep(state.wizard, 'table--active-project');
*
* const onClick = () => {
* const step = { type: 'table-active-project', value: 'some-project-name' };
* const isToggled = isToggledStep(getCurrentPage(state.wizard), step);
* if (isToggled) {
* dispatch(WizardActions.toggleOffStep, step)
* } else {
* dispatch(WizardActions.toggleOnStep, step)
* }
* }
* render(
* <Box selectable={isActiveProjectSelectable} onClick={}>
* ......
* </Box>
*
*
* // ActiveJob.tsx
* // Similar to ActiveProject
*
* // Players.tsx
* // TBD
*/
9 changes: 9 additions & 0 deletions client/src/app/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { configureStore } from '@reduxjs/toolkit'

export const store = configureStore({
reducer: {},
})

export type RootState = ReturnType<typeof store.getState>

export type AppDispatch = typeof store.dispatch
28 changes: 28 additions & 0 deletions client/src/features/ActionBoard/ActionBoard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import * as React from 'react';
import { BoardProps } from 'boardgame.io/react';
import { OpenStarTerVillageType as Type } from 'packages/game/src/types';
import { Box, Heading, ButtonGroup, Button } from '@chakra-ui/react'

const ActionBoard: React.FC<BoardProps<Type.State.Root>> = (props) => {
const playerID = props.playerID;
const currentPlayer = props.ctx.currentPlayer;

return (
<>
<Box m="4" p="4" border="1px" borderRadius="lg" borderColor="gray.100">
<Heading size="xs">Current Player: {currentPlayer}</Heading>
</Box>
<Box m="4" p="4" border="1px" borderRadius="lg" borderColor="gray.100">
{playerID === currentPlayer && (
<ButtonGroup size='sm' spacing='6'>
<Button>Create Project</Button>
<Button disabled>Move 2</Button>
<Button disabled>Move 3</Button>
</ButtonGroup>
)}
</Box>
</>
);
};

export default ActionBoard;
18 changes: 18 additions & 0 deletions client/src/features/Job/ActiveJob.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Box, Text } from '@chakra-ui/react';
import { OpenStarTerVillageType as Type } from 'packages/game/src/types';

export interface IActiveJobProps {
job: Type.Card.Job;
}

const ActiveJob: React.FC<IActiveJobProps> = (props) => {
const { job } = props;

return (
<Box m="4" p="4" border="1px" borderRadius="lg" borderColor="gray.100">
<Text fontSize='sm'>{job.name}</Text>
</Box>
);
}

export default ActiveJob;
29 changes: 22 additions & 7 deletions client/src/features/Table/Table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,37 @@ import { BoardProps } from 'boardgame.io/react';
import { OpenStarTerVillageType as Type } from 'packages/game/src/types';
import { Box, Stack } from '@chakra-ui/react';
import ActiveProject from '../Project/ActiveProject';
import ActiveJob from '../Job/ActiveJob';

type Props = BoardProps<Type.State.Root>;

const Table: React.FC<Props> = (props) => {
const activeProjects = [...props.G.table.activeProjects, ...Array(6)].slice(0, 6);
const activeJobs = props.G.table.activeJobs;

return (
<Box>
<Stack direction={['column', 'column', 'row']} wrap="wrap" mt={2} spacing={0}>
{activeProjects.map((p, pIndex) => (
<Box key={`active-project-${pIndex}`} w={['100%', '100%', '50%', '50%', '33.3%']}>
<ActiveProject project={p} />
</Box>
))}
</Stack >
</Box >
<Box w={['100%', '100%', '80%']}>
<Stack direction={['column', 'column', 'row']} wrap="wrap" mt={2} spacing={0}>
{activeProjects.map((p, pIndex) => (
<Box key={`active-project-${pIndex}`} w={['100%', '100%', '100%', '50%', '50%']}>
<ActiveProject project={p} />
</Box>
))}
</Stack>
</Box>
<Box w={['100%', '100%', '20%']}>
<Stack direction={['column', 'column', 'row']} wrap="wrap" mt={2} spacing={0}>
{activeJobs.map((job, jobIndex) => (
<Box key={`active-job-${jobIndex}`} w={['100%', '100%', '100%', '100%', '50%']}>
<ActiveJob job={job} />
</Box>
))}
</Stack>
</Box>
</Stack>
</Box>
)
}

Expand Down
10 changes: 7 additions & 3 deletions client/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@ import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { store } from './app/store'
import { Provider as ReduxProvider } from 'react-redux'

ReactDOM.render(
<StrictMode>
<ChakraProvider>
<App />
</ChakraProvider>
<ReduxProvider store={store}>
<ChakraProvider>
<App />
</ChakraProvider>
</ReduxProvider>
</StrictMode>,
document.getElementById('root')
);
Expand Down
Loading
Loading