mirror of
https://github.com/microsoft/frontend-bootcamp.git
synced 2026-01-26 14:56:42 +08:00
playground using codesandbox
This commit is contained in:
@@ -1,6 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<style>
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<iframe
|
||||
src="https://codesandbox.io/embed/jp590043k3?fontsize=14"
|
||||
style="width:100%; height:100vh; border:0; border-radius: 4px; overflow:hidden;"
|
||||
sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
|
||||
></iframe>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import { action, GenericActionTypes, GenericAction, GenericActionLookup } from '../redux-utils/action';
|
||||
import { Dispatch } from 'redux';
|
||||
import { Store } from '../store';
|
||||
import uuid from 'uuid/v4';
|
||||
import * as todosService from '../service/todosService';
|
||||
|
||||
export const actions = {
|
||||
add: (label: string) => action('add', { id: uuid(), label }),
|
||||
remove: (id: string) => action('remove', { id }),
|
||||
edit: (id: string, label: string) => action('edit', { id, label }),
|
||||
complete: (id: string) => action('complete', { id }),
|
||||
clear: () => action('clear'),
|
||||
setFilter: (filter: string) => action('setFilter', { filter })
|
||||
};
|
||||
|
||||
export const actionsWithService = {
|
||||
add: (label: string) => {
|
||||
return async (dispatch: Dispatch<TodoAction>, getState: () => Store) => {
|
||||
const addAction = actions.add(label);
|
||||
const id = addAction.id;
|
||||
dispatch(addAction);
|
||||
await todosService.add(id, getState().todos[id]);
|
||||
};
|
||||
},
|
||||
|
||||
edit: (id: string, label: string) => {
|
||||
return async (dispatch: Dispatch<TodoAction>, getState: () => Store) => {
|
||||
dispatch(actions.edit(id, label));
|
||||
await todosService.edit(id, getState().todos[id]);
|
||||
};
|
||||
},
|
||||
|
||||
remove: (id: string) => {
|
||||
return async (dispatch: Dispatch<TodoAction>, getState: () => Store) => {
|
||||
dispatch(actions.remove(id));
|
||||
await todosService.remove(id);
|
||||
};
|
||||
},
|
||||
|
||||
complete: (id: string) => {
|
||||
return async (dispatch: Dispatch<TodoAction>, getState: () => Store) => {
|
||||
dispatch(actions.complete(id));
|
||||
await todosService.edit(id, getState().todos[id]);
|
||||
};
|
||||
},
|
||||
|
||||
clear: () => {
|
||||
return async (dispatch: Dispatch<TodoAction>, getState: () => Store) => {
|
||||
dispatch(actions.clear());
|
||||
await todosService.editBulk(getState().todos);
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export type ActionTypes = GenericActionTypes<typeof actions>;
|
||||
export type TodoAction = GenericAction<typeof actions>;
|
||||
export type TodoActionWithService = GenericAction<typeof actionsWithService>;
|
||||
export type TodoActionLookup = GenericActionLookup<typeof actions>;
|
||||
@@ -1,15 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Stack } from 'office-ui-fabric-react';
|
||||
import { TodoFooter } from './TodoFooter';
|
||||
import { TodoHeader } from './TodoHeader';
|
||||
import { TodoList } from './TodoList';
|
||||
|
||||
export const TodoApp = (props: {}) => (
|
||||
<Stack horizontalAlign="center">
|
||||
<Stack style={{ width: 400 }} gap={25}>
|
||||
<TodoHeader />
|
||||
<TodoList />
|
||||
<TodoFooter />
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
@@ -1,38 +0,0 @@
|
||||
import React from 'react';
|
||||
|
||||
import { Store } from '../store';
|
||||
import { DefaultButton, Stack, Text } from 'office-ui-fabric-react';
|
||||
import { actionsWithService } from '../actions';
|
||||
import { connect } from 'react-redux';
|
||||
|
||||
// Redux Container
|
||||
export function mapStateToProps({ todos, filter }: Store) {
|
||||
return {
|
||||
todos,
|
||||
filter
|
||||
};
|
||||
}
|
||||
|
||||
export function mapDispatchToProps(dispatch: any) {
|
||||
return {
|
||||
clear: () => dispatch(actionsWithService.clear())
|
||||
};
|
||||
}
|
||||
|
||||
type TodoFooterProps = ReturnType<typeof mapStateToProps> & ReturnType<typeof mapDispatchToProps>;
|
||||
|
||||
export const TodoFooter = connect(
|
||||
mapStateToProps,
|
||||
mapDispatchToProps
|
||||
)((props: TodoFooterProps) => {
|
||||
const itemCount = Object.keys(props.todos).filter(id => !props.todos[id].completed).length;
|
||||
|
||||
return (
|
||||
<Stack horizontal horizontalAlign="space-between">
|
||||
<Text>
|
||||
{itemCount} item{itemCount === 1 ? '' : 's'} left
|
||||
</Text>
|
||||
<DefaultButton onClick={() => props.clear()}>Clear Completed</DefaultButton>
|
||||
</Stack>
|
||||
);
|
||||
});
|
||||
@@ -1,79 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Pivot, PivotItem, TextField, Stack, Text } from 'office-ui-fabric-react';
|
||||
import { FilterTypes, Store } from '../store';
|
||||
import { actionsWithService, actions } from '../actions';
|
||||
import { connect } from 'react-redux';
|
||||
|
||||
function mapStateToProps({ todos, filter }: Store) {
|
||||
return {
|
||||
todos,
|
||||
filter
|
||||
};
|
||||
}
|
||||
|
||||
function mapDispatchToProps(dispatch: any) {
|
||||
return {
|
||||
add: (label: string) => dispatch(actionsWithService.add(label)),
|
||||
remove: (id: string) => dispatch(actionsWithService.remove(id)),
|
||||
setFilter: (filter: FilterTypes) => dispatch(actions.setFilter(filter))
|
||||
};
|
||||
}
|
||||
|
||||
type TodoHeaderProps = ReturnType<typeof mapStateToProps> & ReturnType<typeof mapDispatchToProps>;
|
||||
|
||||
interface TodoHeaderState {
|
||||
labelInput: string;
|
||||
}
|
||||
|
||||
class TodoHeader extends React.Component<TodoHeaderProps, TodoHeaderState> {
|
||||
constructor(props: TodoHeaderProps) {
|
||||
super(props);
|
||||
this.state = { labelInput: undefined };
|
||||
}
|
||||
|
||||
onKeyPress = (evt: React.KeyboardEvent) => {
|
||||
if (evt.charCode === 13) {
|
||||
this.props.add(this.state.labelInput);
|
||||
this.setState({ labelInput: undefined });
|
||||
}
|
||||
};
|
||||
|
||||
onChange = (evt: React.FormEvent<HTMLInputElement>, newValue: string) => {
|
||||
this.setState({ labelInput: newValue });
|
||||
};
|
||||
|
||||
onFilter = (item: PivotItem) => {
|
||||
this.props.setFilter(item.props.headerText as FilterTypes);
|
||||
};
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Stack>
|
||||
<Stack horizontal horizontalAlign="center">
|
||||
<Text variant="xxLarge">todos</Text>
|
||||
</Stack>
|
||||
|
||||
<TextField
|
||||
placeholder="What needs to be done?"
|
||||
value={this.state.labelInput}
|
||||
onChange={this.onChange}
|
||||
onKeyPress={this.onKeyPress}
|
||||
/>
|
||||
|
||||
<Pivot onLinkClick={this.onFilter}>
|
||||
<PivotItem headerText="all" />
|
||||
<PivotItem headerText="active" />
|
||||
<PivotItem headerText="completed" />
|
||||
</Pivot>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Hook up the Redux state and dispatches
|
||||
const component = connect(
|
||||
mapStateToProps,
|
||||
mapDispatchToProps
|
||||
)(TodoHeader);
|
||||
|
||||
export { component as TodoHeader };
|
||||
@@ -1,40 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Stack } from 'office-ui-fabric-react';
|
||||
import { TodoListItem } from './TodoListItem';
|
||||
import { Store } from '../store';
|
||||
import { connect } from 'react-redux';
|
||||
|
||||
function mapStateToProps({ todos, filter }: Store) {
|
||||
return {
|
||||
todos,
|
||||
filter
|
||||
};
|
||||
}
|
||||
|
||||
function mapDispatchToProps(dispatch: any) {}
|
||||
|
||||
type TodoListProps = ReturnType<typeof mapStateToProps> & ReturnType<typeof mapDispatchToProps>;
|
||||
|
||||
class TodoList extends React.Component<TodoListProps> {
|
||||
render() {
|
||||
const { filter, todos } = this.props;
|
||||
const filteredTodos = Object.keys(todos).filter(id => {
|
||||
return filter === 'all' || (filter === 'completed' && todos[id].completed) || (filter === 'active' && !todos[id].completed);
|
||||
});
|
||||
|
||||
return (
|
||||
<Stack gap={10}>
|
||||
{filteredTodos.map(id => (
|
||||
<TodoListItem key={id} id={id} />
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const component = connect(
|
||||
mapStateToProps,
|
||||
mapDispatchToProps
|
||||
)(TodoList);
|
||||
|
||||
export { component as TodoList };
|
||||
@@ -1,104 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Stack, Checkbox, IconButton, TextField } from 'office-ui-fabric-react';
|
||||
import { mergeStyles } from '@uifabric/styling';
|
||||
import { Store } from '../store';
|
||||
import { actionsWithService } from '../actions';
|
||||
import { connect } from 'react-redux';
|
||||
|
||||
function mapStateToProps({ todos }: Store) {
|
||||
return {
|
||||
todos
|
||||
};
|
||||
}
|
||||
|
||||
function mapDispatchToProps(dispatch: any) {
|
||||
return {
|
||||
remove: (id: string) => dispatch(actionsWithService.remove(id)),
|
||||
complete: (id: string) => dispatch(actionsWithService.complete(id)),
|
||||
edit: (id: string, label: string) => dispatch(actionsWithService.edit(id, label))
|
||||
};
|
||||
}
|
||||
|
||||
type TodoListItemProps = { id: string } & ReturnType<typeof mapDispatchToProps> & ReturnType<typeof mapStateToProps>;
|
||||
|
||||
interface TodoListItemState {
|
||||
editing: boolean;
|
||||
editLabel: string;
|
||||
}
|
||||
|
||||
const className = mergeStyles({
|
||||
selectors: {
|
||||
'.clearButton': {
|
||||
visibility: 'hidden'
|
||||
},
|
||||
'&:hover .clearButton': {
|
||||
visibility: 'visible'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
class TodoListItem extends React.Component<TodoListItemProps, TodoListItemState> {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
constructor(props: TodoListItemProps) {
|
||||
super(props);
|
||||
this.state = { editing: false, editLabel: undefined };
|
||||
}
|
||||
|
||||
onEdit = () => {
|
||||
const { todos, id } = this.props;
|
||||
const { label } = todos[id];
|
||||
|
||||
this.setState(prevState => ({
|
||||
editing: true,
|
||||
editLabel: prevState.editLabel || label
|
||||
}));
|
||||
};
|
||||
|
||||
onDoneEdit = () => {
|
||||
this.props.edit(this.props.id, this.state.editLabel);
|
||||
this.setState(prevState => ({
|
||||
editing: false,
|
||||
editLabel: undefined
|
||||
}));
|
||||
};
|
||||
|
||||
onKeyDown = (evt: React.KeyboardEvent) => {
|
||||
if (evt.which === 13) {
|
||||
this.onDoneEdit();
|
||||
}
|
||||
};
|
||||
|
||||
onChange = (evt: React.FormEvent<HTMLInputElement>, newValue: string) => {
|
||||
this.setState({ editLabel: newValue });
|
||||
};
|
||||
|
||||
render() {
|
||||
const { todos, id, complete, remove } = this.props;
|
||||
const item = todos[id];
|
||||
|
||||
return (
|
||||
<Stack horizontal className={className} verticalAlign="center" horizontalAlign="space-between">
|
||||
{!this.state.editing && (
|
||||
<>
|
||||
<Checkbox label={item.label} checked={item.completed} onChange={() => complete(id)} />
|
||||
<div>
|
||||
<IconButton iconProps={{ iconName: 'Edit' }} className="clearButton" onClick={this.onEdit} />
|
||||
<IconButton iconProps={{ iconName: 'Cancel' }} className="clearButton" onClick={() => remove(id)} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{this.state.editing && <TextField value={this.state.editLabel} onChange={this.onChange} onKeyPress={this.onKeyDown} />}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const component = connect(
|
||||
mapStateToProps,
|
||||
mapDispatchToProps
|
||||
)(TodoListItem);
|
||||
|
||||
export { component as TodoListItem };
|
||||
@@ -1,36 +0,0 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { createStore, applyMiddleware, compose } from 'redux';
|
||||
import { Provider } from 'react-redux';
|
||||
import { reducer } from './reducers';
|
||||
import { TodoApp } from './components/TodoApp';
|
||||
import { initializeIcons } from '@uifabric/icons';
|
||||
import thunk from 'redux-thunk';
|
||||
import * as todosService from './service/todosService';
|
||||
import { FilterTypes } from './store';
|
||||
|
||||
declare var window: any;
|
||||
|
||||
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
|
||||
|
||||
// For preloading store
|
||||
initializeIcons();
|
||||
|
||||
(async () => {
|
||||
const preloadStore = {
|
||||
todos: await todosService.getAll(),
|
||||
filter: 'all' as FilterTypes
|
||||
};
|
||||
|
||||
const store = createStore(reducer, preloadStore, composeEnhancers(applyMiddleware(thunk)));
|
||||
|
||||
ReactDOM.render(
|
||||
<Provider store={store}>
|
||||
<TodoApp />
|
||||
</Provider>,
|
||||
document.getElementById('app')
|
||||
);
|
||||
})();
|
||||
|
||||
// For Synchronous Case
|
||||
// const store = createStore(reducer, { todos: {}, filter: 'all' }, composeEnhancers(applyMiddleware(thunk)));
|
||||
@@ -1,10 +0,0 @@
|
||||
import { reducer } from '../index';
|
||||
|
||||
describe('reducers', () => {
|
||||
it('should add item to the list', () => {
|
||||
const newStore = reducer({ todos: {}, filter: 'all' }, { type: 'add', label: 'hello' });
|
||||
const keys = Object.keys(newStore.todos);
|
||||
expect(keys.length).toBe(1);
|
||||
expect(newStore.todos[keys[0]].label).toBe('hello');
|
||||
});
|
||||
});
|
||||
@@ -1,10 +0,0 @@
|
||||
import { ActionTypes, TodoActionLookup, actions } from '../actions';
|
||||
import { createGenericReducer, HandlerMap, ImmerReducer } from '../redux-utils/reducer';
|
||||
import { Reducer } from 'redux';
|
||||
|
||||
export function createReducer<T, AM extends ActionTypes | never = never>(
|
||||
initialState: T,
|
||||
handlerOrMap: HandlerMap<T, typeof actions> | ImmerReducer<T, TodoActionLookup[AM]>
|
||||
): Reducer<T> {
|
||||
return createGenericReducer<T, typeof actions, AM>(initialState, handlerOrMap);
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import { createReducer } from './createReducer';
|
||||
import { Store, FilterTypes } from '../store';
|
||||
import { combineReducers } from 'redux';
|
||||
|
||||
export const reducer = combineReducers<Store>({
|
||||
todos: createReducer<Store['todos']>(
|
||||
{},
|
||||
{
|
||||
add(draft, action) {
|
||||
draft[action.id] = { label: action.label, completed: false };
|
||||
return draft;
|
||||
},
|
||||
|
||||
remove(draft, action) {
|
||||
delete draft[action.id];
|
||||
return draft;
|
||||
},
|
||||
|
||||
complete(draft, action) {
|
||||
draft[action.id].completed = !draft[action.id].completed;
|
||||
return draft;
|
||||
},
|
||||
|
||||
clear(draft) {
|
||||
Object.keys(draft).forEach(id => {
|
||||
if (draft[id].completed) {
|
||||
delete draft[id];
|
||||
}
|
||||
});
|
||||
return draft;
|
||||
},
|
||||
|
||||
edit(draft, action) {
|
||||
draft[action.id].label = action.label;
|
||||
return draft;
|
||||
}
|
||||
}
|
||||
),
|
||||
filter: createReducer<Store['filter'], 'setFilter'>('all', (draft, action) => {
|
||||
return action.filter as FilterTypes;
|
||||
})
|
||||
});
|
||||
@@ -1,14 +0,0 @@
|
||||
import { Action } from 'redux';
|
||||
|
||||
type ActionWithPayload<T, P> = Action<T> & P;
|
||||
|
||||
export function action<T extends string>(type: T): Action<T>;
|
||||
export function action<T extends string, P>(type: T, payload: P): ActionWithPayload<T, P>;
|
||||
export function action<T extends string, P>(type: T, payload?: P) {
|
||||
return { type, ...payload };
|
||||
}
|
||||
|
||||
export type GenericActionMapping<A> = { [somekey in keyof A]: (...args: any) => Action<any> | ActionWithPayload<any, any> };
|
||||
export type GenericActionTypes<A extends GenericActionMapping<A>> = ReturnType<A[keyof A]>['type'];
|
||||
export type GenericAction<A extends GenericActionMapping<A>> = ReturnType<A[GenericActionTypes<A>]>;
|
||||
export type GenericActionLookup<A extends GenericActionMapping<A>> = { [a in GenericActionTypes<A>]: ReturnType<A[a]> };
|
||||
@@ -1,34 +0,0 @@
|
||||
import { Reducer } from 'redux';
|
||||
import { Draft, produce } from 'immer';
|
||||
import { GenericActionLookup, GenericActionMapping } from './action';
|
||||
|
||||
export type ImmerReducer<T, A> = (state: Draft<T>, action?: A) => T;
|
||||
export type HandlerMap<T, A extends GenericActionMapping<A>> = {
|
||||
[actionType in keyof A]?: ImmerReducer<T, GenericActionLookup<A>[actionType]>
|
||||
};
|
||||
|
||||
function isHandlerFunction<T, A extends GenericActionMapping<A>>(
|
||||
handlerOrMap: HandlerMap<T, A> | ImmerReducer<T, A>
|
||||
): handlerOrMap is ImmerReducer<T, A> {
|
||||
if (typeof handlerOrMap === 'function') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function createGenericReducer<T, A extends GenericActionMapping<A>, AM = keyof GenericActionMapping<A>>(
|
||||
initialState: T,
|
||||
handlerOrMap: HandlerMap<T, A> | ImmerReducer<T, GenericActionLookup<A>[AM]>
|
||||
): Reducer<T> {
|
||||
return function reducer(state = initialState, action: GenericActionLookup<A>[AM]): T {
|
||||
if (isHandlerFunction(handlerOrMap)) {
|
||||
return produce(state, draft => handlerOrMap(draft, action as GenericActionLookup<A>[AM]));
|
||||
} else if (handlerOrMap.hasOwnProperty(action.type)) {
|
||||
const handler = (handlerOrMap as any)[action.type] as ImmerReducer<T, GenericActionLookup<A>[AM]>;
|
||||
return produce(state, draft => handler(draft, action));
|
||||
} else {
|
||||
return state;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { TodoItem, Store } from '../store';
|
||||
const HOST = 'http://localhost:3000';
|
||||
|
||||
export async function add(id: string, todo: TodoItem) {
|
||||
const response = await fetch(`${HOST}/todos/${id}`, {
|
||||
method: 'post',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(todo)
|
||||
});
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export async function edit(id: string, todo: TodoItem) {
|
||||
const response = await fetch(`${HOST}/todos/${id}`, {
|
||||
method: 'put',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(todo)
|
||||
});
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export async function remove(id: string) {
|
||||
const response = await fetch(`${HOST}/todos/${id}`, {
|
||||
method: 'delete'
|
||||
});
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export async function getAll() {
|
||||
const response = await fetch(`${HOST}/todos`, {
|
||||
method: 'get'
|
||||
});
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
export async function editBulk(todos: Store['todos']) {
|
||||
const response = await fetch(`${HOST}/todos`, {
|
||||
method: 'post',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(todos)
|
||||
});
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
export type FilterTypes = 'all' | 'active' | 'completed';
|
||||
|
||||
export interface TodoItem {
|
||||
label: string;
|
||||
completed: boolean;
|
||||
}
|
||||
|
||||
export interface Store {
|
||||
todos: {
|
||||
[id: string]: TodoItem;
|
||||
};
|
||||
|
||||
filter: FilterTypes;
|
||||
}
|
||||
Reference in New Issue
Block a user