mirror of
https://github.com/microsoft/frontend-bootcamp.git
synced 2026-01-26 14:56:42 +08:00
2.7 code
This commit is contained in:
@@ -1,8 +1,51 @@
|
||||
import uuid from 'uuid/v4';
|
||||
import { Store } from '../store';
|
||||
import * as service from '../service';
|
||||
|
||||
export const actions = {
|
||||
addTodo: (label: string) => ({ type: 'addTodo', id: uuid(), label }),
|
||||
remove: (id: string) => ({ type: 'remove', id }),
|
||||
complete: (id: string) => ({ type: 'complete', id }),
|
||||
clear: () => ({ type: 'clear' })
|
||||
clear: () => ({ type: 'clear' }),
|
||||
setFilter: (filter: string) => ({ type: 'setFilter', filter }),
|
||||
edit: (id: string, label: string) => ({ type: 'edit', id, label })
|
||||
};
|
||||
|
||||
export const actionsWithService = {
|
||||
addTodo: (label: string) => {
|
||||
return async (dispatch: any, getState: () => Store) => {
|
||||
const addAction = actions.addTodo(label);
|
||||
const id = addAction.id;
|
||||
dispatch(addAction);
|
||||
await service.add(id, getState().todos[id]);
|
||||
};
|
||||
},
|
||||
|
||||
remove: (id: string) => {
|
||||
return async (dispatch: any, getState: () => Store) => {
|
||||
dispatch(actions.remove(id));
|
||||
await service.remove(id);
|
||||
};
|
||||
},
|
||||
|
||||
complete: (id: string) => {
|
||||
return async (dispatch: any, getState: () => Store) => {
|
||||
dispatch(actions.complete(id));
|
||||
await service.update(id, getState().todos[id]);
|
||||
};
|
||||
},
|
||||
|
||||
clear: () => {
|
||||
return async (dispatch: any, getState: () => Store) => {
|
||||
dispatch(actions.clear());
|
||||
await service.updateAll(getState().todos);
|
||||
};
|
||||
},
|
||||
|
||||
edit: (id: string, label: string) => {
|
||||
return async (dispatch: any, getState: () => Store) => {
|
||||
dispatch(actions.complete(id));
|
||||
await service.update(id, getState().todos[id]);
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,26 +1,17 @@
|
||||
import React from 'react';
|
||||
import { Stack, Customizer, mergeStyles, getTheme } from 'office-ui-fabric-react';
|
||||
import { Stack } from 'office-ui-fabric-react';
|
||||
import { TodoFooter } from './TodoFooter';
|
||||
import { TodoHeader } from './TodoHeader';
|
||||
import { TodoList } from './TodoList';
|
||||
import { Store } from '../store';
|
||||
import { FluentCustomizations } from '@uifabric/fluent-theme';
|
||||
|
||||
const className = mergeStyles({
|
||||
padding: 25,
|
||||
...getTheme().effects.elevation4
|
||||
});
|
||||
|
||||
export const TodoApp = () => {
|
||||
return (
|
||||
<Customizer {...FluentCustomizations}>
|
||||
<Stack horizontalAlign="center">
|
||||
<Stack style={{ width: 400 }} gap={25} className={className}>
|
||||
<TodoHeader />
|
||||
<TodoList />
|
||||
<TodoFooter />
|
||||
</Stack>
|
||||
<Stack horizontalAlign="center">
|
||||
<Stack style={{ width: 400 }} gap={25}>
|
||||
<TodoHeader />
|
||||
<TodoList />
|
||||
<TodoFooter />
|
||||
</Stack>
|
||||
</Customizer>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,41 +1,20 @@
|
||||
import React from 'react';
|
||||
import { Store } from '../store';
|
||||
import { Stack, Text, DefaultButton } from 'office-ui-fabric-react';
|
||||
import { connect } from 'react-redux';
|
||||
import { actions } from '../actions';
|
||||
import { DefaultButton, Stack, Text } from 'office-ui-fabric-react';
|
||||
import { actionsWithService } from '../actions';
|
||||
import { useMappedState, useDispatch } from 'redux-react-hook';
|
||||
|
||||
interface TodoFooterProps {
|
||||
clear: () => void;
|
||||
todos: Store['todos'];
|
||||
}
|
||||
export const TodoFooter = () => {
|
||||
const { todos } = useMappedState(state => state);
|
||||
const dispatch = useDispatch();
|
||||
|
||||
const TodoFooter = (props: TodoFooterProps) => {
|
||||
const { todos } = props;
|
||||
const itemCount = todos ? Object.keys(todos).filter(id => !props.todos[id].completed).length : 0;
|
||||
const itemCount = Object.keys(todos).filter(id => !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>
|
||||
<DefaultButton onClick={() => dispatch(actionsWithService.clear())}>Clear Completed</DefaultButton>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
function mapStateToProps(state: Store) {
|
||||
return { ...state };
|
||||
}
|
||||
|
||||
function mapDispatchToProps(dispatch: any) {
|
||||
return {
|
||||
clear: () => dispatch(actions.clear())
|
||||
};
|
||||
}
|
||||
|
||||
const component = connect(
|
||||
mapStateToProps,
|
||||
mapDispatchToProps
|
||||
)(TodoFooter);
|
||||
|
||||
export { component as TodoFooter };
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
import React from 'react';
|
||||
import { Text, Stack, TextField, PrimaryButton } from 'office-ui-fabric-react';
|
||||
import { Store } from '../store';
|
||||
import { connect } from 'react-redux';
|
||||
import { actions } from '../actions';
|
||||
|
||||
interface TodoHeaderProps {
|
||||
addTodo: (label: string) => void;
|
||||
}
|
||||
import { Stack, Text, Pivot, PivotItem, TextField, PrimaryButton } from 'office-ui-fabric-react';
|
||||
import { FilterTypes } from '../store';
|
||||
import { actionsWithService, actions } from '../actions';
|
||||
import { StoreContext } from 'redux-react-hook';
|
||||
|
||||
interface TodoHeaderState {
|
||||
labelInput: string;
|
||||
}
|
||||
|
||||
class TodoHeader extends React.Component<TodoHeaderProps, TodoHeaderState> {
|
||||
constructor(props: TodoHeaderProps) {
|
||||
export class TodoHeader extends React.Component<{}, TodoHeaderState> {
|
||||
constructor(props: {}) {
|
||||
super(props);
|
||||
this.state = { labelInput: undefined };
|
||||
}
|
||||
@@ -22,42 +18,48 @@ class TodoHeader extends React.Component<TodoHeaderProps, TodoHeaderState> {
|
||||
return (
|
||||
<Stack gap={10}>
|
||||
<Stack horizontal horizontalAlign="center">
|
||||
<Text variant="xxLarge">todos - step2-07 demo</Text>
|
||||
<Text variant="xxLarge">todos</Text>
|
||||
</Stack>
|
||||
|
||||
<Stack horizontal gap={10}>
|
||||
<Stack.Item grow>
|
||||
<TextField placeholder="What needs to be done?" value={this.state.labelInput} onChange={this.onChange} />
|
||||
<TextField
|
||||
placeholder="What needs to be done?"
|
||||
value={this.state.labelInput}
|
||||
onChange={this.onChange}
|
||||
styles={props => ({
|
||||
...(props.focused && {
|
||||
field: {
|
||||
backgroundColor: '#c7e0f4'
|
||||
}
|
||||
})
|
||||
})}
|
||||
/>
|
||||
</Stack.Item>
|
||||
<PrimaryButton onClick={this.onAdd}>Add</PrimaryButton>
|
||||
</Stack>
|
||||
|
||||
<Pivot onLinkClick={this.onFilter}>
|
||||
<PivotItem headerText="all" />
|
||||
<PivotItem headerText="active" />
|
||||
<PivotItem headerText="completed" />
|
||||
</Pivot>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
private onAdd = () => {
|
||||
this.props.addTodo(this.state.labelInput);
|
||||
this.context.dispatch(actionsWithService.addTodo(this.state.labelInput));
|
||||
this.setState({ labelInput: undefined });
|
||||
};
|
||||
|
||||
private onChange = (evt: React.FormEvent<HTMLInputElement>, newValue: string) => {
|
||||
this.setState({ labelInput: newValue });
|
||||
};
|
||||
}
|
||||
|
||||
function mapStateToProps(state: Store) {
|
||||
return { ...state };
|
||||
}
|
||||
|
||||
function mapDispatchToProps(dispatch: any) {
|
||||
return {
|
||||
addTodo: (label: string) => dispatch(actions.addTodo(label))
|
||||
private onFilter = (item: PivotItem) => {
|
||||
this.context.dispatch(actions.setFilter(item.props.headerText as FilterTypes));
|
||||
};
|
||||
}
|
||||
|
||||
const component = connect(
|
||||
mapStateToProps,
|
||||
mapDispatchToProps
|
||||
)(TodoHeader);
|
||||
|
||||
export { component as TodoHeader };
|
||||
TodoHeader.contextType = StoreContext;
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
import React from 'react';
|
||||
import { Stack } from 'office-ui-fabric-react';
|
||||
import { TodoListItem } from './TodoListItem';
|
||||
import { Store } from '../store';
|
||||
import { connect } from 'react-redux';
|
||||
import { useMappedState } from 'redux-react-hook';
|
||||
|
||||
interface TodoListProps {
|
||||
todos: Store['todos'];
|
||||
}
|
||||
|
||||
const TodoList = (props: TodoListProps) => {
|
||||
const { todos } = props;
|
||||
const filteredTodos = Object.keys(todos);
|
||||
export const TodoList = () => {
|
||||
const { filter, todos } = useMappedState(state => state);
|
||||
const filteredTodos = Object.keys(todos).filter(id => {
|
||||
return filter === 'all' || (filter === 'completed' && todos[id].completed) || (filter === 'active' && !todos[id].completed);
|
||||
});
|
||||
|
||||
return (
|
||||
<Stack gap={10}>
|
||||
@@ -20,18 +17,3 @@ const TodoList = (props: TodoListProps) => {
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
function mapStateToProps(state: Store) {
|
||||
return { ...state };
|
||||
}
|
||||
|
||||
function mapDispatchToProps(dispatch: any) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const component = connect(
|
||||
mapStateToProps,
|
||||
mapDispatchToProps
|
||||
)(TodoList);
|
||||
|
||||
export { component as TodoList };
|
||||
|
||||
@@ -1,48 +1,78 @@
|
||||
import React from 'react';
|
||||
import { Stack, Checkbox, IconButton } from 'office-ui-fabric-react';
|
||||
import { Store } from '../store';
|
||||
import { connect } from 'react-redux';
|
||||
import { actions } from '../actions';
|
||||
import { Stack, Checkbox, IconButton, TextField, DefaultButton } from 'office-ui-fabric-react';
|
||||
import { actionsWithService } from '../actions';
|
||||
import { StoreContext } from 'redux-react-hook';
|
||||
|
||||
interface TodoListItemProps {
|
||||
id: string;
|
||||
todos: Store['todos'];
|
||||
remove: (id: string) => void;
|
||||
complete: (id: string) => void;
|
||||
}
|
||||
|
||||
class TodoListItem extends React.Component<TodoListItemProps, {}> {
|
||||
interface TodoListItemState {
|
||||
editing: boolean;
|
||||
editLabel: string;
|
||||
}
|
||||
|
||||
export class TodoListItem extends React.Component<TodoListItemProps, TodoListItemState> {
|
||||
constructor(props: TodoListItemProps) {
|
||||
super(props);
|
||||
this.state = { editing: false, editLabel: undefined };
|
||||
}
|
||||
|
||||
render() {
|
||||
const { todos, id, complete, remove } = this.props;
|
||||
const { id } = this.props;
|
||||
const { todos } = this.context.getState();
|
||||
const dispatch = this.context.dispatch;
|
||||
|
||||
const item = todos[id];
|
||||
|
||||
return (
|
||||
<Stack horizontal verticalAlign="center" horizontalAlign="space-between">
|
||||
<Checkbox label={item.label} checked={item.completed} onChange={() => complete(id)} />
|
||||
<div>
|
||||
<IconButton iconProps={{ iconName: 'Cancel' }} onClick={() => remove(id)} />
|
||||
</div>
|
||||
{!this.state.editing && (
|
||||
<>
|
||||
<Checkbox label={item.label} checked={item.completed} onChange={() => dispatch(actionsWithService.complete(id))} />
|
||||
<div>
|
||||
<IconButton iconProps={{ iconName: 'Edit' }} onClick={this.onEdit} />
|
||||
<IconButton iconProps={{ iconName: 'Cancel' }} onClick={() => dispatch(actionsWithService.remove(id))} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{this.state.editing && (
|
||||
<Stack.Item grow>
|
||||
<Stack horizontal gap={10}>
|
||||
<Stack.Item grow>
|
||||
<TextField value={this.state.editLabel} onChange={this.onChange} />
|
||||
</Stack.Item>
|
||||
<DefaultButton onClick={this.onDoneEdit}>Save</DefaultButton>
|
||||
</Stack>
|
||||
</Stack.Item>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function mapStateToProps({ todos }: Store) {
|
||||
return {
|
||||
todos
|
||||
private onEdit = () => {
|
||||
const { id } = this.props;
|
||||
const { todos } = this.context.getState();
|
||||
const { label } = todos[id];
|
||||
|
||||
this.setState({
|
||||
editing: true,
|
||||
editLabel: this.state.editLabel || label
|
||||
});
|
||||
};
|
||||
|
||||
private onDoneEdit = () => {
|
||||
this.context.dispatch(actionsWithService.edit(this.props.id, this.state.editLabel));
|
||||
this.setState({
|
||||
editing: false,
|
||||
editLabel: undefined
|
||||
});
|
||||
};
|
||||
|
||||
private onChange = (evt: React.FormEvent<HTMLInputElement>, newValue: string) => {
|
||||
this.setState({ editLabel: newValue });
|
||||
};
|
||||
}
|
||||
|
||||
function mapDispatchToProps(dispatch: any) {
|
||||
return {
|
||||
remove: (id: string) => dispatch(actions.remove(id)),
|
||||
complete: (id: string) => dispatch(actions.complete(id))
|
||||
};
|
||||
}
|
||||
|
||||
const component = connect(
|
||||
mapStateToProps,
|
||||
mapDispatchToProps
|
||||
)(TodoListItem);
|
||||
|
||||
export { component as TodoListItem };
|
||||
TodoListItem.contextType = StoreContext;
|
||||
|
||||
@@ -1,23 +1,30 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { reducer } from './reducers';
|
||||
import { createStore } from 'redux';
|
||||
import { Provider } from 'react-redux';
|
||||
import { createStore, applyMiddleware } from 'redux';
|
||||
import { TodoApp } from './components/TodoApp';
|
||||
import { actions } from './actions';
|
||||
import { initializeIcons } from '@uifabric/icons';
|
||||
import { composeWithDevTools } from 'redux-devtools-extension';
|
||||
import { StoreContext } from 'redux-react-hook';
|
||||
import thunk from 'redux-thunk';
|
||||
import { FilterTypes } from './store';
|
||||
|
||||
const store = createStore(reducer, {}, composeWithDevTools());
|
||||
(async () => {
|
||||
// TODO: to make the store pre-populate with data from the service,
|
||||
// replace the todos value below with a call to "await service.getAll()"
|
||||
const preloadStore = {
|
||||
todos: {},
|
||||
filter: 'all' as FilterTypes
|
||||
};
|
||||
|
||||
store.dispatch(actions.addTodo('hello'));
|
||||
store.dispatch(actions.addTodo('world'));
|
||||
const store = createStore(reducer, preloadStore, composeWithDevTools(applyMiddleware(thunk)));
|
||||
|
||||
initializeIcons();
|
||||
initializeIcons();
|
||||
|
||||
ReactDOM.render(
|
||||
<Provider store={store}>
|
||||
<TodoApp />
|
||||
</Provider>,
|
||||
document.getElementById('app')
|
||||
);
|
||||
ReactDOM.render(
|
||||
<StoreContext.Provider value={store}>
|
||||
<TodoApp />
|
||||
</StoreContext.Provider>,
|
||||
document.getElementById('app')
|
||||
);
|
||||
})();
|
||||
|
||||
@@ -1,27 +1,43 @@
|
||||
import { Store } from '../store';
|
||||
import { addTodo, remove, complete, clear } from './pureFunctions';
|
||||
import { combineReducers } from 'redux';
|
||||
import { createReducer } from 'redux-starter-kit';
|
||||
|
||||
function todoReducer(state: Store['todos'] = {}, action: any): Store['todos'] {
|
||||
switch (action.type) {
|
||||
case 'addTodo':
|
||||
return addTodo(state, action.id, action.label);
|
||||
export const todosReducer = createReducer<Store['todos']>(
|
||||
{},
|
||||
{
|
||||
addTodo(state, action) {
|
||||
state[action.id] = { label: action.label, completed: false };
|
||||
},
|
||||
|
||||
case 'remove':
|
||||
return remove(state, action.id);
|
||||
remove(state, action) {
|
||||
delete state[action.id];
|
||||
},
|
||||
|
||||
case 'clear':
|
||||
return clear(state);
|
||||
clear(state, action) {
|
||||
Object.keys(state).forEach(key => {
|
||||
if (state[key].completed) {
|
||||
delete state[key];
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
case 'complete':
|
||||
return complete(state, action.id);
|
||||
complete(state, action) {
|
||||
state[action.id].completed = !state[action.id].completed;
|
||||
},
|
||||
|
||||
edit(state, action) {
|
||||
state[action.id].label = action.label;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return state;
|
||||
}
|
||||
export const filterReducer = createReducer<Store['filter']>('all', {
|
||||
setFilter(state, action) {
|
||||
return action.filter;
|
||||
}
|
||||
});
|
||||
|
||||
export function reducer(state: Store, action: any): Store {
|
||||
return {
|
||||
todos: todoReducer(state.todos, action),
|
||||
filter: 'all'
|
||||
};
|
||||
}
|
||||
export const reducer = combineReducers({
|
||||
todos: todosReducer,
|
||||
filter: filterReducer
|
||||
});
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { addTodo, complete } from './pureFunctions';
|
||||
import { Store } from '../store';
|
||||
|
||||
describe('TodoApp reducers', () => {
|
||||
it('can add an item', () => {
|
||||
const state = <Store['todos']>{};
|
||||
|
||||
const newState = addTodo(state, '0', 'item1');
|
||||
|
||||
const keys = Object.keys(newState);
|
||||
|
||||
expect(newState).not.toBe(state);
|
||||
expect(keys.length).toBe(1);
|
||||
expect(newState[keys[0]].label).toBe('item1');
|
||||
expect(newState[keys[0]].completed).toBeFalsy();
|
||||
});
|
||||
|
||||
it('can complete an item', () => {
|
||||
const state = <Store['todos']>{};
|
||||
|
||||
let newState = addTodo(state, '0', 'item1');
|
||||
|
||||
const key = Object.keys(newState)[0];
|
||||
|
||||
newState = complete(newState, key);
|
||||
|
||||
expect(newState[key].completed).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
import { Store, FilterTypes } from '../store';
|
||||
|
||||
export function addTodo(state: Store['todos'], id: string, label: string): Store['todos'] {
|
||||
return { ...state, [id]: { label, completed: false } };
|
||||
}
|
||||
|
||||
export function remove(state: Store['todos'], id: string) {
|
||||
const newTodos = { ...state };
|
||||
|
||||
delete newTodos[id];
|
||||
|
||||
return newTodos;
|
||||
}
|
||||
|
||||
export function complete(state: Store['todos'], id: string) {
|
||||
// Clone the todo, overriding
|
||||
const newTodo = { ...state[id], completed: !state[id].completed };
|
||||
return { ...state, [id]: newTodo };
|
||||
}
|
||||
|
||||
export function clear(state: Store['todos']) {
|
||||
const newTodos = { ...state };
|
||||
|
||||
Object.keys(state).forEach(key => {
|
||||
if (state[key].completed) {
|
||||
delete newTodos[key];
|
||||
}
|
||||
});
|
||||
|
||||
return newTodos;
|
||||
}
|
||||
|
||||
export function setFilter(state: Store['filter'], filter: FilterTypes) {
|
||||
return filter;
|
||||
}
|
||||
48
step2-07/demo/src/service/index.ts
Normal file
48
step2-07/demo/src/service/index.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
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 update(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 updateAll(todos: Store['todos']) {
|
||||
const response = await fetch(`${HOST}/todos`, {
|
||||
method: 'post',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(todos)
|
||||
});
|
||||
|
||||
return await response.json();
|
||||
}
|
||||
Reference in New Issue
Block a user