Deleted old TodoApp example.

This commit is contained in:
Martin Sosic 2020-10-30 15:58:30 +01:00
parent 0c4ae72495
commit ecc1740bcc
36 changed files with 0 additions and 16415 deletions

View File

@ -1,5 +0,0 @@
{
"projects": {
"default": "wasp-lang-examples"
}
}

67
examples/.gitignore vendored
View File

@ -1,67 +0,0 @@
/dist/
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
firebase-debug.log*
# Firebase cache
.firebase/
# Firebase config
# Uncomment this if you'd like others to create their own Firebase project.
# For a team working on the same Firebase project(s), it is recommended to leave
# it commented so all members can deploy to the same project(s) in .firebaserc.
# .firebaserc
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env

View File

@ -1,12 +0,0 @@
.PHONY: buildTodoApp
buildTodoApp:
cd todoApp/out && npm install && npm run-script build
.PHONY: deploy
deploy: buildTodoApp
# NOTE: Right now we copy todoApp directly to dist, but in the future we will probably
# want to copy it to dist/todoApp, so we can have other examples next to it, all hosted together.
rm -r dist
cp -R todoApp/out/build dist
firebase deploy

View File

@ -1,9 +0,0 @@
Each example has `src/` and `out/` directory, where `out/` is code generated by `waspc` from `src/`.
Examples are deployed to https://examples.wasp-lang.dev.
NOTE: Right now, only todoApp/ is deployed, and it is deployed directly to https://examples.wasp-lang.dev.
Plan is, when we will have more examples, to deploy them next to each other, each in its own directory, so they would be accessed as https://examples.wasp-lang.dev/todoApp and so on.
But, for that we need support in Wasp for the scenario where frontend is not hosted at server root, which we don't support yet.
Check `Makefile` for build / deploy commands.

View File

@ -1,10 +0,0 @@
{
"hosting": {
"public": "dist",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}

View File

@ -1,9 +0,0 @@
In this example we use Wasp to implement a simple Todo app, inspired by http://todomvc.com.
NOTE: This is an old example, made with old version of Wasp and will not work with the current version.
Code in [src/](src/) (todoApp.wasp + [src/src](src/src)) is compiled by `waspc`, generating code in [out/](out/), which is frontend only web app. There was no manual intervention in the generated code, it is as generated by `waspc`.
Command used: `waspc src/todoApp.wasp out/`.
You can check out deployed generated app at https://examples.wasp-lang.dev.

View File

@ -1,23 +0,0 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@ -1 +0,0 @@
Generated on 2020-03-10 18:22:45.230191331 UTC by waspc version "0.1.0.0" .

View File

@ -1,68 +0,0 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br>
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br>
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.<br>
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br>
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `npm run build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

File diff suppressed because it is too large Load Diff

View File

@ -1,38 +0,0 @@
{
"name": "todoApp",
"version": "0.0.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.9.1",
"@reduxjs/toolkit": "^1.2.3",
"lodash": "^4.17.15",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-redux": "^7.1.3",
"react-router-dom": "^5.1.2",
"react-scripts": "3.4.0",
"redux": "^4.0.5",
"uuid": "^3.4.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

View File

@ -1,52 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta
name="viewport"
content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<!--
This is the font that Material-UI requires.
-->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>ToDo App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

View File

@ -1,14 +0,0 @@
{
"name": "todoApp",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -1,31 +0,0 @@
import React, { Component } from 'react'
import { connect } from 'react-redux'
import Todo from "./ext-src/Todo.js"
import * as taskState from './entities/task/state.js'
import * as taskActions from './entities/task/actions.js'
import Task from './entities/task/Task.js'
import NewTaskForm from './entities/task/components/NewTaskForm.js'
import TaskList from './entities/task/components/TaskList.js'
import './ext-src/Main.css'
export class Main extends Component {
// TODO: Add propTypes.
render() {
return (
<Todo/>
)
}
}
export default connect(state => ({
taskList: taskState.selectors.all(state)
}), {
addTask: taskActions.add,
updateTask: taskActions.update,
removeTask: taskActions.remove
})(Main)

View File

@ -1,30 +0,0 @@
import React from 'react'
import { connect } from 'react-redux'
import Button from '@material-ui/core/Button'
import { deleteDoneAction } from '../entities/task/actions.js'
export class DeleteDoneButton extends React.Component {
// TODO: Add propTypes.
onClick = () => {
this.props.deleteDoneAction()
}
render() {
return (
<Button {...this.props}
onClick={this.onClick}
>
Delete completed
</Button>
)
}
}
export default connect(state => ({
// Selectors
}), {
// Actions
deleteDoneAction
})(DeleteDoneButton)

View File

@ -1,30 +0,0 @@
import React from 'react'
import { connect } from 'react-redux'
import Button from '@material-ui/core/Button'
import { toggleIsDoneAction } from '../entities/task/actions.js'
export class ToggleIsDoneButton extends React.Component {
// TODO: Add propTypes.
onClick = () => {
this.props.toggleIsDoneAction()
}
render() {
return (
<Button {...this.props}
onClick={this.onClick}
>
</Button>
)
}
}
export default connect(state => ({
// Selectors
}), {
// Actions
toggleIsDoneAction
})(ToggleIsDoneButton)

View File

@ -1,28 +0,0 @@
import uuidv4 from 'uuid/v4'
export default class Task {
_data = {}
constructor (data = {}) {
this._data = {
id: data.id || uuidv4(),
isDone: data.isDone,
description: data.description,
}
}
get id () {
return this._data.id
}
get isDone () {
return this._data.isDone
}
get description () {
return this._data.description
}
toData () {
return this._data
}
}

View File

@ -1,4 +0,0 @@
export const ADD = 'entities/task/ADD'
export const SET = 'entities/task/SET'
export const UPDATE = 'entities/task/UPDATE'
export const REMOVE = 'entities/task/REMOVE'

View File

@ -1,56 +0,0 @@
import * as types from './actionTypes'
import Task from './Task'
import { selectors } from './state'
/**
* @param {Task} task
*/
export const add = (task) => ({
type: types.ADD,
data: task.toData()
})
/**
* @param {Task[]} tasks
*/
export const set = (tasks) => ({
type: types.SET,
tasks: tasks.map(t => t.toData())
})
/**
* @param {String} id
* @param {Object} data - Partial data that will be merged with existing task.
*/
export const update = (id, data) => ({
type: types.UPDATE,
id,
data
})
/**
* @param {String} id
*/
export const remove = (id) => ({
type: types.REMOVE,
id
})
export const toggleIsDoneAction = () => (dispatch, getState) => {
const tasks = selectors.all(getState())
const updateFn = tasks => {
const areAllDone = tasks.every(t => t.isDone)
return tasks.map(t => ({ ...t, isDone: !areAllDone }))
}
const newTasks = updateFn(tasks.map(t => t.toData())).map(t => new Task(t))
dispatch(set(newTasks))
}
export const deleteDoneAction = () => (dispatch, getState) => {
const tasks = selectors.all(getState())
const updateFn = tasks => tasks.filter(t => !t.isDone)
const newTasks = updateFn(tasks.map(t => t.toData())).map(t => new Task(t))
dispatch(set(newTasks))
}

View File

@ -1,73 +0,0 @@
import _ from 'lodash'
import React from 'react'
import PropTypes from 'prop-types'
import FormControlLabel from '@material-ui/core/FormControlLabel'
import Switch from '@material-ui/core/Switch'
import Button from '@material-ui/core/Button'
import TextField from '@material-ui/core/TextField'
import Task from '../Task'
export default class NewTaskForm extends React.Component {
static propTypes = {
onCreate: PropTypes.func,
submitButtonLabel: PropTypes.string
}
state = {
fields: {
isDone: false,
description: '',
}
}
setField = (name, valueOrFn) => {
this.setState(prevState => ({
fields: {
...prevState.fields,
[name]: _.isFunction(valueOrFn) ? valueOrFn(prevState) : valueOrFn
}
}))
}
resetAllFields = () => {
this.setField('isDone', false)
this.setField('description', '')
}
toggleField = (name) => {
this.setField(name, prevState => !prevState.fields[name])
}
getField = (name) => {
return this.state.fields[name]
}
handleSubmit = () => {
this.props.onCreate(new Task(this.state.fields))
this.resetAllFields()
}
render() {
return (
<div className={this.props.className}>
<form noValidate onSubmit={this.handleSubmit} action="javascript:void(0);">
<div>
<TextField
placeholder="What needs to be done?"
value={this.getField('description')}
onChange={event => this.setField('description', event.target.value)}
margin="normal"
fullWidth
InputLabelProps={{
shrink: true
}}
/>
</div>
</form>
</div>
)
}
}

View File

@ -1,136 +0,0 @@
import _ from 'lodash'
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import Paper from '@material-ui/core/Paper'
import Table from '@material-ui/core/Table'
import TableBody from '@material-ui/core/TableBody'
import TableCell from '@material-ui/core/TableCell'
import TableHead from '@material-ui/core/TableHead'
import TableRow from '@material-ui/core/TableRow'
import Checkbox from '@material-ui/core/Checkbox'
import TextField from '@material-ui/core/TextField'
import ClickAwayListener from '@material-ui/core/ClickAwayListener'
import Select from '@material-ui/core/Select'
import MenuItem from '@material-ui/core/MenuItem'
import * as taskState from '../state'
import * as taskActions from '../actions'
import Task from '../Task'
export class TaskList extends React.Component {
static propTypes = {
editable: PropTypes.bool
}
state = {
taskBeingEdited: null,
filterName: 'all'
}
setAsBeingEdited = task => this.setState({
taskBeingEdited: task.id
})
isBeingEdited = task =>
task.id === this.state.taskBeingEdited
finishEditing = task => {
if (task.id === this.state.taskBeingEdited)
this.setState({ taskBeingEdited: null })
}
renderTaskDescription =
(task) => task.isDone ? <s>{task.description}</s> : task.description
handleFilterChange = event => {
this.setState({ filterName: event.target.value })
}
filters = {
'completed': task => task.isDone,
'active': task => !task.isDone,
}
render() {
const taskListToShow = this.state.filterName !== 'all' ?
this.props.taskList.filter(this.filters[this.state.filterName]) :
this.props.taskList
return (
<div className={this.props.className}>
Filter:&nbsp;
<Select
value={this.state.filterName}
onChange={this.handleFilterChange}
>
<MenuItem value="all">all</MenuItem>
<MenuItem value="completed">completed</MenuItem>
<MenuItem value="active">active</MenuItem>
</Select>
<Paper>
<Table>
<TableHead style={{display: 'none'}}>
<TableRow>
<TableCell width="50%">isDone</TableCell>
<TableCell width="50%">description</TableCell>
</TableRow>
</TableHead>
<TableBody>
{taskListToShow.map((task) => (
<TableRow key={task.id}>
<TableCell>
<Checkbox
checked={task.isDone}
color="default"
inputProps={{
'aria-label': 'checkbox'
}}
disabled={!this.props.editable}
onChange={e => this.props.updateTask(
task.id, { 'isDone': e.target.checked }
)}
/>
</TableCell>
<ClickAwayListener
onClickAway={() => this.finishEditing(task) }>
<TableCell
onDoubleClick={() => this.setAsBeingEdited(task)}
>
{this.props.editable && this.isBeingEdited(task) ? (
<TextField
value={task.description}
onChange={e => this.props.updateTask(
task.id, { 'description': e.target.value }
)}
/>
) : (
this.renderTaskDescription(task)
)}
</TableCell>
</ClickAwayListener>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
</div>
)
}
}
export default connect(state => ({
// Selectors
taskList: taskState.selectors.all(state)
}), {
// Actions
updateTask: taskActions.update
})(TaskList)

View File

@ -1,65 +0,0 @@
import { createSelector } from 'reselect'
import Task from './Task'
import * as types from './actionTypes'
// We assume that root reducer of the app will put this reducer under
// key ROOT_REDUCER_KEY.
const ROOT_REDUCER_KEY = 'entities/Task'
const initialState = {
all: []
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case types.ADD:
return {
...state,
all: [ ...state.all, action.data ]
}
case types.SET:
return {
...state,
all: action.tasks
}
case types.UPDATE:
return {
...state,
all: state.all.map(
task =>
task.id === action.id
? { ...task, ...action.data }
: task
)
}
case types.REMOVE:
return {
...state,
all: state.all.filter(
task => task.id !== action.id
)
}
default:
return state
}
}
let selectors = {}
selectors.root = (state) => state[ROOT_REDUCER_KEY]
/**
* @returns {Task[]}
*/
selectors.all = createSelector(selectors.root, (state) => {
return state.all.map(data => new Task(data))
})
export { reducer, initialState, selectors, ROOT_REDUCER_KEY }

View File

@ -1,60 +0,0 @@
div {
color: green;
}
button.selected {
border: 1px solid black;
}
.hidden {
visibility: hidden;
}
.todos {
display: flex;
flex-direction: column;
align-items: center;
}
.todos h1 {
text-align: center;
}
.todos__container {
width: 450px;
}
.todos__toggleAndInput {
display: flex;
align-items: flex-end;
margin-bottom: 10px;
}
.todos__toggleButton {
height: 40px;
margin-bottom: 8px;
margin-left: 20px;
background-color: white;
border: none;
display: inline-block;
font-size: 24px !important;
cursor: pointer;
}
.todos__newTaskForm {
width: 100%;
margin-left: 10px;
}
.todos__footer {
width: 100%;
margin-top: 10px;
display: flex;
justify-content: space-between;
}
.todos__footer__filters .filter:not(:last-child) {
margin-right: 10px;
}

View File

@ -1,68 +0,0 @@
// As seen here, we can import npm packages used in code generated by Wasp, which will be clearly defined.
// In the future, we will of course also be able to specify additional packages as dependencies.
import React from 'react'
import { connect } from 'react-redux'
// As seen here, we can import specific components/code generated by Wasp.
// These will have well defined and documented APIs and paths.
// Note that Task, NewTaskForm and TaskList are generated based on the declarations
// we made in todoApp.wasp file.
import NewTaskForm from '../entities/task/components/NewTaskForm'
import TaskList from '../entities/task/components/TaskList'
import * as taskState from '../entities/task/state.js'
import * as taskActions from '../entities/task/actions.js'
import ToggleIsDoneButton from '../components/ToggleIsDoneButton'
import DeleteDoneButton from '../components/DeleteDoneButton'
class Todo extends React.Component {
// TODO: prop types.
isAnyTaskCompleted = () => this.props.taskList.some(t => t.isDone)
isThereAnyTask = () => this.props.taskList.length > 0
render = () => {
return (
<div className="todos">
<div className="todos__container">
<h1> Todos </h1>
<div className="todos__toggleAndInput">
<ToggleIsDoneButton
disabled={!this.isThereAnyTask()}
className="todos__toggleButton"
/>
<NewTaskForm
className="todos__newTaskForm"
onCreate={task => this.props.addTask(task)}
submitButtonLabel={'Create new task'}
/>
</div>
{ this.isThereAnyTask() && (<>
<TaskList editable />
<div className="todos__footer">
<div className="todos__footer__itemsLeft">
{ this.props.taskList.filter(task => !task.isDone).length } items left
</div>
<div className="todos__footer__clearCompleted">
<DeleteDoneButton
className={this.isAnyTaskCompleted() ? '' : 'hidden' }
/>
</div>
</div>
</>)}
</div>
</div>
)
}
}
export default connect(state => ({
taskList: taskState.selectors.all(state)
}), {
addTask: taskActions.add
})(Todo)

View File

@ -1,14 +0,0 @@
body {
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
}

View File

@ -1,25 +0,0 @@
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import router from './router'
import { configureStore } from './store'
import { rootReducer } from './reducers'
import * as serviceWorker from './serviceWorker'
import './index.css'
const store = configureStore(rootReducer)
ReactDOM.render(
<Provider store={store}>
{ router }
</Provider>,
document.getElementById('root')
)
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

Binary file not shown.

Before

Width:  |  Height:  |  Size: 818 B

View File

@ -1,18 +0,0 @@
import { combineReducers } from 'redux'
import * as taskState from './entities/task/state.js'
const states = [
taskState,
]
const keyToReducer = states.reduce((acc, state) => {
// We set the reducers here by using their ROOT_REDUCER_KEY, because their
// internal state implementations assume so.
return { ...acc, [state.ROOT_REDUCER_KEY]: state.reducer }
}, {})
export const rootReducer = combineReducers({
...keyToReducer
})

View File

@ -1,15 +0,0 @@
import React from 'react'
import { Route, BrowserRouter as Router } from 'react-router-dom'
import Main from './Main'
const router = (
<Router>
<div>
<Route exact path="/" component={ Main }/>
</div>
</Router>
)
export default router

View File

@ -1,135 +0,0 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}

View File

@ -1,26 +0,0 @@
import * as RTK from '@reduxjs/toolkit'
import loggerMiddleware from './middleware/logger'
/**
* @param {Function} reducer - Redux reducer to be used for this store.
* @param {Object} [preloadedState] - State that this store will be initialized with.
* @returns {Object} Redux store, configured to suit our needs.
*/
export const configureStore = (reducer, preloadedState) => {
const middleware = [
...RTK.getDefaultMiddleware(),
loggerMiddleware
]
const enhancers = []
const store = RTK.configureStore({
reducer,
preloadedState,
middleware,
enhancers
})
return store
}

View File

@ -1,13 +0,0 @@
const logger = store => next => action => {
console.group(action.type)
console.info('dispatching', action)
let result = next(action)
console.log('next state', store.getState())
console.groupEnd()
return result
}
export default logger

View File

@ -1,60 +0,0 @@
div {
color: green;
}
button.selected {
border: 1px solid black;
}
.hidden {
visibility: hidden;
}
.todos {
display: flex;
flex-direction: column;
align-items: center;
}
.todos h1 {
text-align: center;
}
.todos__container {
width: 450px;
}
.todos__toggleAndInput {
display: flex;
align-items: flex-end;
margin-bottom: 10px;
}
.todos__toggleButton {
height: 40px;
margin-bottom: 8px;
margin-left: 20px;
background-color: white;
border: none;
display: inline-block;
font-size: 24px !important;
cursor: pointer;
}
.todos__newTaskForm {
width: 100%;
margin-left: 10px;
}
.todos__footer {
width: 100%;
margin-top: 10px;
display: flex;
justify-content: space-between;
}
.todos__footer__filters .filter:not(:last-child) {
margin-right: 10px;
}

View File

@ -1,68 +0,0 @@
// As seen here, we can import npm packages used in code generated by Wasp, which will be clearly defined.
// In the future, we will of course also be able to specify additional packages as dependencies.
import React from 'react'
import { connect } from 'react-redux'
// As seen here, we can import specific components/code generated by Wasp.
// These will have well defined and documented APIs and paths.
// Note that Task, NewTaskForm and TaskList are generated based on the declarations
// we made in todoApp.wasp file.
import NewTaskForm from '@wasp/entities/task/components/NewTaskForm'
import TaskList from '@wasp/entities/task/components/TaskList'
import * as taskState from '@wasp/entities/task/state.js'
import * as taskActions from '@wasp/entities/task/actions.js'
import ToggleIsDoneButton from '@wasp/components/ToggleIsDoneButton'
import DeleteDoneButton from '@wasp/components/DeleteDoneButton'
class Todo extends React.Component {
// TODO: prop types.
isAnyTaskCompleted = () => this.props.taskList.some(t => t.isDone)
isThereAnyTask = () => this.props.taskList.length > 0
render = () => {
return (
<div className="todos">
<div className="todos__container">
<h1> Todos </h1>
<div className="todos__toggleAndInput">
<ToggleIsDoneButton
disabled={!this.isThereAnyTask()}
className="todos__toggleButton"
/>
<NewTaskForm
className="todos__newTaskForm"
onCreate={task => this.props.addTask(task)}
submitButtonLabel={'Create new task'}
/>
</div>
{ this.isThereAnyTask() && (<>
<TaskList editable />
<div className="todos__footer">
<div className="todos__footer__itemsLeft">
{ this.props.taskList.filter(task => !task.isDone).length } items left
</div>
<div className="todos__footer__clearCompleted">
<DeleteDoneButton
className={this.isAnyTaskCompleted() ? '' : 'hidden' }
/>
</div>
</div>
</>)}
</div>
</div>
)
}
}
export default connect(state => ({
taskList: taskState.selectors.all(state)
}), {
addTask: taskActions.add
})(Todo)

View File

@ -1,76 +0,0 @@
import Todo from "@ext/Todo.js" // Imports non-wasp code from external code dir (ext/).
entity Task {
isDone :: boolean,
description :: string
}
app todoApp {
title: "ToDo App"
}
page Main {
route: "/",
style: "@ext/Main.css",
// TODO: We need to make this nicer / more explicit, it is not clear where is this coming from (these props).
// Also, this wiring is not elegant.
// Here we use Todo React component that we imported at the beginning of this file.
content: {=jsx <Todo/> jsx=}
}
entity-form<Task> NewTaskForm {
fields: {
description: {
show: true,
label: none,
placeholder: "What needs to be done?"
},
isDone: {
show: false,
defaultValue: false
}
},
submit: {
onEnter: true,
button: { show: false }
}
}
entity-list<Task> TaskList {
showHeader: false,
fields: {
description: {
// The contract for render is that user must provide a function that:
// - Receives a task as an input.
// - Returns a React Node or something that can be rendered by JSX.
// - Does not depend on any outer context.
render: {=js (task) => task.isDone ? <s>{task.description}</s> : task.description js=}
}
},
mutuallyExclusiveFilters: {
completed: {=js task => task.isDone js=},
active: {=js task => !task.isDone js=}
}
}
button ToggleIsDoneButton {
label: "✓",
onClick: toggleIsDoneAction
}
button DeleteDoneButton {
label: "Delete completed",
onClick: deleteDoneAction
}
action<Task> toggleIsDoneAction {=js
tasks => {
const areAllDone = tasks.every(t => t.isDone)
return tasks.map(t => ({ ...t, isDone: !areAllDone }))
}
js=}
action<Task> deleteDoneAction {=js
tasks => tasks.filter(t => !t.isDone)
js=}