((r) => {
39 | try {
40 | _[uri].fetch(input, init).then(response => response.json()).then(flow(E.right, r));
41 | } catch (error) {
42 | r(E.left(makeFetchFailed(typeof input === 'string' ? input : input.url)(error)));
43 | }
44 |
45 | return (cb) => {
46 | cb(makeFetchFailed(typeof input === 'string' ? input : input.url)(""));
47 | };
48 | })
49 | );
50 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "todomvc-fp",
3 | "version": "0.1.0",
4 | "repository": "https://github.com/rjdestigter/todomvc-fp",
5 | "homepage": "http://rjdestigter.github.io/todomvc-fp",
6 | "private": true,
7 | "dependencies": {
8 | "@matechs/console": "^4.0.0-beta.4",
9 | "@matechs/effect": "^6.0.0-beta.1",
10 | "@matechs/prelude": "^1.0.0-beta.2",
11 | "@testing-library/jest-dom": "^5.5.0",
12 | "@testing-library/react": "^10.0.2",
13 | "@testing-library/user-event": "^10.0.2",
14 | "@types/jest": "^25.2.1",
15 | "@types/node": "^13.13.0",
16 | "@types/react": "^16.9.0",
17 | "@types/react-dom": "^16.9.0",
18 | "fp-ts": "^2.5.3",
19 | "fp-ts-contrib": "^0.1.15",
20 | "gh-pages": "^2.2.0",
21 | "io-ts": "^2.2.1",
22 | "react": "^16.13.1",
23 | "react-dom": "^16.13.1",
24 | "react-scripts": "3.4.1",
25 | "retry-ts": "^0.1.2",
26 | "sass": "^1.26.3",
27 | "todomvc-app-css": "^2.3.0",
28 | "todomvc-common": "^1.0.5",
29 | "typescript": "^3.8.3"
30 | },
31 | "scripts": {
32 | "start": "react-scripts start",
33 | "build": "react-scripts build",
34 | "test": "react-scripts test",
35 | "eject": "react-scripts eject",
36 | "predeploy": "npm run build",
37 | "deploy": "gh-pages -d build"
38 | },
39 | "eslintConfig": {
40 | "extends": "react-app"
41 | },
42 | "browserslist": {
43 | "production": [
44 | ">0.2%",
45 | "not dead",
46 | "not op_mini all"
47 | ],
48 | "development": [
49 | "last 1 chrome version",
50 | "last 1 firefox version",
51 | "last 1 safari version"
52 | ]
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | TodoMVC with @matechs/effect and fp-ts
7 |
8 |
9 |
10 |
11 |
12 |
16 |
17 |
24 |
25 |
43 |
44 |
52 |
53 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Codesansbox
2 |
3 | [](https://codesandbox.io/s/github/rjdestigter/todomvc-fp/tree/master/?fontsize=14&hidenavigation=1&theme=dark)
4 |
5 | ## TLDR;
6 | This is an experimental repository examplifiying pure functional programming UI interfaces without the help from libraries such as ReactJS or Vue **but** with _functional efffects_ using [@matechs/effects](https://github.com/Matechs-Garage/matechs-effect), [fp-ts](https://github.com/gcanti/fp-ts), and other functional programming libraries.
7 |
8 | ## Original README:
9 |
10 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) **but does not use React**
11 |
12 | ## Available Scripts
13 |
14 | In the project directory, you can run:
15 |
16 | ### `yarn start`
17 |
18 | Runs the app in the development mode.
19 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
20 |
21 | The page will reload if you make edits.
22 | You will also see any lint errors in the console.
23 |
24 | ### `yarn test`
25 |
26 | Launches the test runner in the interactive watch mode.
27 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
28 |
29 | ### `yarn build`
30 |
31 | Builds the app for production to the `build` folder.
32 | It correctly bundles React in production mode and optimizes the build for the best performance.
33 |
34 | The build is minified and the filenames include the hashes.
35 | Your app is ready to be deployed!
36 |
37 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
38 |
39 | ### `yarn eject`
40 |
41 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
42 |
43 | If you aren’t 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.
44 |
45 | 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 you’re on your own.
46 |
47 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
48 |
49 | ## Learn More
50 |
51 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
52 |
53 | To learn React, check out the [React documentation](https://reactjs.org/).
54 |
--------------------------------------------------------------------------------
/src/modules/emitter.ts:
--------------------------------------------------------------------------------
1 | import { effect as T, stream as S, managed as M } from "@matechs/effect";
2 | import { pipe } from "fp-ts/lib/pipeable";
3 | import { log } from "@matechs/console";
4 |
5 | export const uri = "@uri/emitter";
6 |
7 | export type EventFor = TEventType extends
8 | | "keypress"
9 | | "keyup"
10 | | "keydown"
11 | ? KeyboardEvent
12 | : TEventType extends "click" | "dblclick" | "mousemove" | "mousedown" | "mouseup"
13 | ? MouseEvent
14 | : Event;
15 |
16 | export type EventHandler = (
17 | evt: EventFor
18 | ) => void;
19 |
20 | export interface Emitter {
21 | [uri]: {
22 | fromEvent: (
23 | type: TEventType
24 | ) => (cb: EventHandler) => T.Effect;
25 | addEventListener: >(
26 | el: TElement
27 | ) => (
28 | type: TEventType
29 | ) => (cb: EventHandler) => T.Effect;
30 | };
31 | }
32 |
33 | // Events
34 | export const subscribe = (type: TEventType, ret?: any) => <
35 | TElement extends Pick
36 | >(
37 | el?: TElement
38 | ) => {
39 | return S.fromSource(
40 | M.managed.chain(
41 | M.bracket(
42 | T.accessM((_: Emitter) =>
43 | T.sync(() => {
44 | const { next, ops, hasCB } = S.su.queueUtils<
45 | never,
46 | EventFor
47 | >();
48 |
49 | const fn = el ? _[uri].addEventListener(el) : _[uri].fromEvent;
50 |
51 | return {
52 | unsubscribe: fn(type)(a => {
53 | next({ _tag: "offer", a })
54 | return ret
55 | }),
56 | ops,
57 | hasCB
58 | };
59 | })
60 | ),
61 | _ => _.unsubscribe
62 | ),
63 | ({ ops, hasCB }) => S.su.emitter(ops, hasCB)
64 | )
65 | );
66 | };
67 |
68 | export const makeEmitterLive = <
69 | TRoot extends Pick
70 | >(
71 | rootEl: TRoot
72 | ): Emitter => {
73 | return {
74 | [uri]: {
75 | fromEvent: (type: TEventType) => (
76 | cb: EventHandler
77 | ) => {
78 | const wrappedCb = (e: EventFor) => {
79 | e.stopPropagation();
80 | return cb(e);
81 | };
82 | rootEl.addEventListener(type, wrappedCb as any);
83 |
84 | return T.sync(() => rootEl.removeEventListener(type, cb as any));
85 | },
86 | addEventListener: >(el: TElement) => <
87 | TEventType extends string
88 | >(
89 | type: TEventType
90 | ) => (cb: EventHandler) => {
91 | const wrappedCb = (e: EventFor) => {
92 | e.stopPropagation();
93 | return cb(e);
94 | };
95 | el.addEventListener(type, wrappedCb as any);
96 |
97 | return T.sync(() => el.removeEventListener(type, cb as any));
98 | }
99 | }
100 | };
101 | };
102 |
103 | /**
104 | * waitForKeyPress :: number -> Effect NoEnv never void
105 | *
106 | * Given a keyCode returns an effect that resolves once the user
107 | * presses a key on the keyboard matching the key code.
108 | */
109 | export const waitForKeyPress = (...keyCodes: number[]) =>
110 | T.effect.chain(log("Waiting for ", ...keyCodes), () =>
111 | pipe(
112 | subscribe("keyup")(),
113 | S.filter(event => keyCodes.includes(event.keyCode)),
114 | S.take(1),
115 | S.collectArray,
116 | T.map(([evt]) => evt)
117 | )
118 | );
119 |
--------------------------------------------------------------------------------
/src/serviceWorker.ts:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | type Config = {
24 | onSuccess?: (registration: ServiceWorkerRegistration) => void;
25 | onUpdate?: (registration: ServiceWorkerRegistration) => void;
26 | };
27 |
28 | export function register(config?: Config) {
29 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
30 | // The URL constructor is available in all browsers that support SW.
31 | const publicUrl = new URL(
32 | process.env.PUBLIC_URL || '',
33 | window.location.href
34 | );
35 | if (publicUrl.origin !== window.location.origin) {
36 | // Our service worker won't work if PUBLIC_URL is on a different origin
37 | // from what our page is served on. This might happen if a CDN is used to
38 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
39 | return;
40 | }
41 |
42 | window.addEventListener('load', () => {
43 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
44 |
45 | if (isLocalhost) {
46 | // This is running on localhost. Let's check if a service worker still exists or not.
47 | checkValidServiceWorker(swUrl, config);
48 |
49 | // Add some additional logging to localhost, pointing developers to the
50 | // service worker/PWA documentation.
51 | navigator.serviceWorker.ready.then(() => {
52 | console.log(
53 | 'This web app is being served cache-first by a service ' +
54 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
55 | );
56 | });
57 | } else {
58 | // Is not localhost. Just register service worker
59 | registerValidSW(swUrl, config);
60 | }
61 | });
62 | }
63 | }
64 |
65 | function registerValidSW(swUrl: string, config?: Config) {
66 | navigator.serviceWorker
67 | .register(swUrl)
68 | .then(registration => {
69 | registration.onupdatefound = () => {
70 | const installingWorker = registration.installing;
71 | if (installingWorker == null) {
72 | return;
73 | }
74 | installingWorker.onstatechange = () => {
75 | if (installingWorker.state === 'installed') {
76 | if (navigator.serviceWorker.controller) {
77 | // At this point, the updated precached content has been fetched,
78 | // but the previous service worker will still serve the older
79 | // content until all client tabs are closed.
80 | console.log(
81 | 'New content is available and will be used when all ' +
82 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
83 | );
84 |
85 | // Execute callback
86 | if (config && config.onUpdate) {
87 | config.onUpdate(registration);
88 | }
89 | } else {
90 | // At this point, everything has been precached.
91 | // It's the perfect time to display a
92 | // "Content is cached for offline use." message.
93 | console.log('Content is cached for offline use.');
94 |
95 | // Execute callback
96 | if (config && config.onSuccess) {
97 | config.onSuccess(registration);
98 | }
99 | }
100 | }
101 | };
102 | };
103 | })
104 | .catch(error => {
105 | console.error('Error during service worker registration:', error);
106 | });
107 | }
108 |
109 | function checkValidServiceWorker(swUrl: string, config?: Config) {
110 | // Check if the service worker can be found. If it can't reload the page.
111 | fetch(swUrl, {
112 | headers: { 'Service-Worker': 'script' }
113 | })
114 | .then(response => {
115 | // Ensure service worker exists, and that we really are getting a JS file.
116 | const contentType = response.headers.get('content-type');
117 | if (
118 | response.status === 404 ||
119 | (contentType != null && contentType.indexOf('javascript') === -1)
120 | ) {
121 | // No service worker found. Probably a different app. Reload the page.
122 | navigator.serviceWorker.ready.then(registration => {
123 | registration.unregister().then(() => {
124 | window.location.reload();
125 | });
126 | });
127 | } else {
128 | // Service worker found. Proceed as normal.
129 | registerValidSW(swUrl, config);
130 | }
131 | })
132 | .catch(() => {
133 | console.log(
134 | 'No internet connection found. App is running in offline mode.'
135 | );
136 | });
137 | }
138 |
139 | export function unregister() {
140 | if ('serviceWorker' in navigator) {
141 | navigator.serviceWorker.ready
142 | .then(registration => {
143 | registration.unregister();
144 | })
145 | .catch(error => {
146 | console.error(error.message);
147 | });
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/src/modules/dom.ts:
--------------------------------------------------------------------------------
1 | import { effect as T, stream as S } from "@matechs/effect";
2 | import * as O from "fp-ts/lib/Option";
3 | import { pipe } from "fp-ts/lib/pipeable";
4 | import { constant, flow, identity } from "fp-ts/lib/function";
5 | import { subscribe, Emitter, EventFor } from "./emitter";
6 | import { DocumentEnv, getDocument } from "./document";
7 |
8 | /**
9 | * Environment
10 | */
11 | export const uri = "@uri/dom";
12 |
13 | export interface Dom {
14 | [uri]: {
15 | createElement(
16 | tagName: K,
17 | options?: ElementCreationOptions
18 | ): HTMLElementTagNameMap[K];
19 | createElement(
20 | tagName: string,
21 | options?: ElementCreationOptions
22 | ): HTMLElement;
23 | };
24 | }
25 |
26 | export const domLive: Dom = {
27 | [uri]: {
28 | createElement: (tagName: any, options?: ElementCreationOptions) =>
29 | document.createElement(tagName, options),
30 | },
31 | };
32 |
33 | export const provideDom = T.provide(domLive);
34 |
35 | /**
36 | * Errors
37 | */
38 | class ElementNotFound extends Error {
39 | constructor(selectors: string) {
40 | super(`$(${selectors}) did not return an element.`);
41 | this.name = "ElementNotFound";
42 | }
43 | }
44 |
45 | class ParentElementNotFound extends Error {
46 | constructor(child: string) {
47 | super(`Parent of node: ${child} not found.`);
48 | this.name = "ParentElementNotFound";
49 | }
50 | }
51 |
52 | export const makeElementNotFound = (selectors: string) =>
53 | new ElementNotFound(selectors);
54 |
55 | export const raiseElementNotFound = flow(makeElementNotFound, T.raiseError);
56 |
57 | export const makeParentElementNotFound = (element: HTMLElement) =>
58 | new ParentElementNotFound(element.toString());
59 |
60 | export const raiseParentElementNotFound = flow(
61 | makeParentElementNotFound,
62 | T.raiseError
63 | );
64 |
65 | /**
66 | * Utilities
67 | */
68 | interface CreateElement {
69 | (
70 | tagName: K,
71 | options?: ElementCreationOptions
72 | ): T.Effect;
73 | (tagName: string, options?: ElementCreationOptions): T.Effect<
74 | unknown,
75 | Dom,
76 | never,
77 | HTMLElement
78 | >;
79 | }
80 |
81 | export const createElement: CreateElement = (
82 | tagName: string,
83 | options?: ElementCreationOptions
84 | ) => T.accessM((_: Dom) => T.pure(_[uri].createElement(tagName, options)));
85 |
86 | /**
87 | * QuerySelector
88 | */
89 | interface QuerySelector {
90 | (selectors: K): <
91 | TNode extends ParentNode
92 | >(
93 | node: TNode
94 | ) => O.Option;
95 | (selectors: K): <
96 | TNode extends ParentNode
97 | >(
98 | node: TNode
99 | ) => O.Option;
100 | (selectors: string): (
101 | node: TNode
102 | ) => O.Option;
103 | }
104 |
105 | interface QuerySelectorT {
106 | (selectors: K): <
107 | TNode extends ParentNode
108 | >(
109 | node: O.Option
110 | ) => O.Option;
111 | (selectors: K): <
112 | TNode extends ParentNode
113 | >(
114 | node: O.Option
115 | ) => O.Option;
116 | (selectors: string): (
117 | node: O.Option
118 | ) => O.Option;
119 | }
120 |
121 | export const querySelector: QuerySelector = (selectors: string) => <
122 | TNode extends ParentNode
123 | >(
124 | el: TNode
125 | ) => O.fromNullable(el.querySelector(selectors));
126 |
127 | export const querySelectorO: QuerySelectorT = (selectors: string) => <
128 | TNode extends ParentNode
129 | >(
130 | nodeOT: O.Option
131 | ) =>
132 | pipe(
133 | nodeOT,
134 | O.map((el) => querySelector(selectors)(el))
135 | );
136 |
137 | /**
138 | * $
139 | */
140 | interface $ {
141 | (selectors: K): T.Effect<
142 | unknown,
143 | DocumentEnv,
144 | ElementNotFound,
145 | HTMLElementTagNameMap[K]
146 | >;
147 | (selectors: K): T.Effect<
148 | unknown,
149 | DocumentEnv,
150 | ElementNotFound,
151 | SVGElementTagNameMap[K]
152 | >;
153 | (selectors: string): T.Effect<
154 | unknown,
155 | DocumentEnv,
156 | ElementNotFound,
157 | E
158 | >;
159 | }
160 |
161 | export const $: $ = (selectors: string) =>
162 | pipe(
163 | getDocument,
164 | T.map(querySelector(selectors)),
165 | T.chain(T.fromOption(constant(makeElementNotFound(selectors))))
166 | );
167 |
168 | /**
169 | * ```hs
170 | * parentElement :: Node -> Option
171 | * ```
172 | */
173 | export const parentElement = (
174 | node: TNode
175 | ) => O.fromNullable(node.parentElement as TParentNode | null);
176 |
177 | export class EmptyOptionOfElement extends Error {
178 | constructor(message: string) {
179 | super(message);
180 | this.name = "EmptyOptionOfElement";
181 | }
182 | }
183 |
184 | export const raiseEmptyOptionOfElement = (message: string) =>
185 | T.raiseError(new EmptyOptionOfElement(message));
186 |
187 | export const makeEventStream = (
188 | eventType: TEventType
189 | ) => <
190 | R,
191 | E,
192 | A extends Pick
193 | >(
194 | elementT: T.Effect>
195 | ) =>
196 | pipe(
197 | elementT,
198 | T.map((elementO) =>
199 | pipe(
200 | elementO,
201 | O.map(subscribe(eventType)),
202 | (effect) => effect,
203 | O.fold<
204 | S.Stream>,
205 | S.Stream>
206 | >(
207 | constant(
208 | S.raised(
209 | new EmptyOptionOfElement(
210 | `Option does not contain some element to create ${eventType} event stream for`
211 | )
212 | )
213 | ),
214 | identity
215 | )
216 | )
217 | )
218 | );
219 |
220 | export const makeClickStream = makeEventStream("click");
221 |
--------------------------------------------------------------------------------
/src/modules/todo.ts:
--------------------------------------------------------------------------------
1 | import { effect as T, stream as S } from "@matechs/effect";
2 |
3 | import * as O from "fp-ts/lib/Option";
4 | import * as A from "fp-ts/lib/ReadonlyArray";
5 | import * as Eq from "fp-ts/lib/Eq";
6 | import { pipe } from "fp-ts/lib/pipeable";
7 | import {
8 | constant,
9 | identity,
10 | flow,
11 | constVoid,
12 | tuple,
13 | constTrue,
14 | } from "fp-ts/lib/function";
15 |
16 | import * as t from "io-ts";
17 | import { Do } from "fp-ts-contrib/lib/Do";
18 |
19 | import {
20 | createElement,
21 | querySelector,
22 | makeElementNotFound,
23 | $,
24 | parentElement,
25 | makeParentElementNotFound,
26 | Dom,
27 | } from "./dom";
28 | import * as Fetch from "./fetch";
29 | import { subscribe, Emitter } from "./emitter";
30 | import { store, Store } from "./store";
31 | import { log, Console } from "@matechs/console";
32 | import { memoize } from "./utils";
33 |
34 | /**
35 | * ```hs
36 | *
37 | * URL :: string
38 | *
39 | * ```
40 | *
41 | * API URL where a list of todo objects is requested from
42 | */
43 | const URL = "https://jsonplaceholder.typicode.com/todos";
44 |
45 | /**
46 | * ```hs
47 | *
48 | * Todo :: t.TypeC
49 | *
50 | * ```
51 | *
52 | * io-ts decoder for Todo
53 | */
54 | const todoDecoder = t.type(
55 | {
56 | id: t.number,
57 | userId: t.number,
58 | title: t.string,
59 | completed: t.boolean,
60 | },
61 | "Todo"
62 | );
63 |
64 | /**
65 | * ```hs
66 | *
67 | * Todos :: t.TypeC
68 | *
69 | * ```
70 | *
71 | * io-ts decoder for a list of [[Todo]]
72 | */
73 | const todosDecoder = t.readonlyArray(todoDecoder);
74 |
75 | // Types
76 | type Todo = t.TypeOf;
77 |
78 | type Todos = readonly Todo[];
79 |
80 | const eqTodoById = Eq.contramap((todo: Todo) => todo.id)(Eq.eqNumber);
81 |
82 | // Store (environment)
83 | const uri = "@uri/todo-store";
84 |
85 | interface TodosState {
86 | todos: Todos;
87 | filterBy: "all" | "active" | "completed";
88 | }
89 |
90 | type TodosStore = Store;
91 |
92 | interface TodoStoreEnv {
93 | [uri]: TodosStore;
94 | }
95 |
96 | // Functions
97 | const getFilteredTodos = memoize((filterBy: TodosState["filterBy"]) =>
98 | memoize((todos: Todos) =>
99 | filterBy === "all"
100 | ? todos
101 | : pipe(
102 | todos,
103 | A.filter((todo) =>
104 | filterBy === "completed" ? todo.completed : !todo.completed
105 | )
106 | )
107 | )
108 | );
109 |
110 | const takeTenTodos = memoize(A.takeLeft(10))
111 |
112 | /**
113 | * ```hs
114 | *
115 | * todosStore :: Effect unknown never (Store Todos)
116 | *
117 | * ```
118 | *
119 | * You can update the list of todos by passing a callback function to store.next
120 | * or subscribe to store changes using the store.subscribe stream.
121 | */
122 | const storeT = store({
123 | todos: [],
124 | filterBy: "all",
125 | });
126 |
127 | const provideTodoStore = T.provideM(
128 | pipe(
129 | storeT,
130 | T.map((store) => ({ [uri]: store }))
131 | )
132 | );
133 |
134 | const todoStore = pipe(T.access((_: TodoStoreEnv) => _[uri]));
135 |
136 | // APIS
137 | const fetchTodos = pipe(
138 | // Fetch list of todos from the server
139 | Fetch.fetch(URL),
140 | // Decode the response
141 | T.chain((response) => T.sync(() => todosDecoder.decode(response))),
142 | // From Effect to Effect
143 | T.chain(T.fromEither)
144 | );
145 |
146 | /**
147 | * ```hs
148 | *
149 | * html :: string
150 | *
151 | * ```
152 | *
153 | * HTML used to create a todo for
154 | */
155 | const html = `
156 |
157 |
158 |
159 |
160 |
161 |
162 | `;
163 |
164 | // TODO: Use environment to produce div
165 | const _div = createElement("div");
166 |
167 | /**
168 | * ```hs
169 | *
170 | * createDomNodeForTodo :: Effect
171 | *
172 | * ```
173 | *
174 | * Create a dom element for a todo
175 | */
176 | const createDomNodeForTodo = pipe(
177 | _div,
178 | T.chain((el) =>
179 | T.sync(() => {
180 | el.innerHTML = html;
181 | return querySelector("li")(el);
182 | })
183 | ),
184 | T.chain(
185 | T.fromOption(
186 | constant(
187 | makeElementNotFound("Unable to create DOM element for todo item.")
188 | )
189 | )
190 | )
191 | );
192 |
193 | /**
194 | * ```hs
195 | *
196 | * todosUl :: Effect
197 | *
198 | * ```
199 | *
200 | * Select the ul dom node that contains the list of li nodes that are todo items.
201 | */
202 | const todosUl = $(".todo-list");
203 |
204 | /**
205 | * ```hs
206 | *
207 | * updateDomNodeOfTodo :: Todo -> HTMLLIElement -> Effect
208 | *
209 | * ```
210 | *
211 | * Update a given todo dom li node with information from a [[Todo]] model
212 | */
213 | const updateDomNodeOfTodo = (todo: Todo) => (todoLi: HTMLLIElement) =>
214 | pipe(
215 | Do(O.option)
216 | // Select the input and label dom nodes that are inside the li node
217 | .bind("label", querySelector("label")(todoLi))
218 | .bind("checkbox", querySelector("input")(todoLi))
219 | .bind("input", querySelector("input.edit")(todoLi))
220 | .return(({ label, checkbox, input }) =>
221 | T.sync(() => {
222 | // Update title
223 | label.innerHTML = todo.title;
224 |
225 | // Add todo id as attribute
226 | todoLi.setAttribute("data-todo-id", "" + todo.id);
227 |
228 | // Mark as completed if so
229 | todo.completed
230 | ? todoLi.classList.add("completed")
231 | : todoLi.classList.remove("completed");
232 | checkbox.checked = todo.completed;
233 | input.value = todo.title;
234 |
235 | return todoLi;
236 | })
237 | ),
238 | // TODO: Handle if label or input aren't available
239 | T.fromOption(constant(Error(""))),
240 | T.chain(identity)
241 | );
242 |
243 | const clickedTodoId = (target: HTMLElement) =>
244 | pipe(
245 | parentElement(target),
246 | O.chain((div) => parentElement(div)),
247 | T.pure,
248 | T.chain(T.fromOption(constant(makeParentElementNotFound(target)))),
249 | T.map((parent) =>
250 | pipe(
251 | parent.getAttribute("data-todo-id"),
252 | O.fromNullable,
253 | O.map(Number),
254 | O.map((todoId) => tuple(todoId, parent))
255 | )
256 | ),
257 | T.chain(T.fromOption(constant(makeParentElementNotFound(target))))
258 | );
259 |
260 | /**
261 | * ```hs
262 | *
263 | * handleEvents :: Effect
264 | *
265 | * ```
266 | *
267 | * Handle click events that indicate the user wants to:
268 | * - Remove the todo
269 | * - Toggle the todo's completed status
270 | * - Edit the todo's title
271 | *
272 | */
273 | const handleEvents = pipe(
274 | // With the root dom node that is the list of items
275 | todosUl,
276 | S.encaseEffect,
277 | // Subscribe to clicking the list
278 | S.chain(pipe(subscribe("click"))),
279 | // Map the mouse event to the target (currentTarget would be the list, we want what the user actually clicked.)
280 | S.map((_) => _.target),
281 | S.map(O.fromNullable),
282 | S.chain(S.fromOption),
283 | S.chain((_) => {
284 | const target = _ as HTMLElement;
285 |
286 | const todoIdEffect = clickedTodoId(target);
287 |
288 | // Clicking the remove button (red x on hover)
289 | if (target.hasAttribute("data-remove")) {
290 | return pipe(
291 | todoIdEffect,
292 | T.zip(todoStore),
293 | T.chain(([[todoId], store]) =>
294 | store.next((state) => {
295 | return {
296 | ...state,
297 | todos: state.todos.filter((todo) => todo.id !== todoId),
298 | };
299 | })
300 | ),
301 | S.encaseEffect
302 | );
303 |
304 | // Clicking the toggle "completed" checkbox
305 | } else if (target.hasAttribute("data-toggle")) {
306 | return pipe(
307 | todoIdEffect,
308 | T.zip(todoStore),
309 | T.chain(([[todoId], store]) =>
310 | store.next((state) => {
311 | return {
312 | ...state,
313 | todos: state.todos.map((todo) =>
314 | todo.id === todoId
315 | ? { ...todo, completed: !todo.completed }
316 | : todo
317 | ),
318 | };
319 | })
320 | ),
321 | S.encaseEffect
322 | );
323 |
324 | // Clicking the label to edit the title
325 | } else if (target.hasAttribute("data-edit")) {
326 | return pipe(
327 | todoIdEffect,
328 | T.chain(([todoId, li]) => {
329 | // Makes the text input box visible
330 | const addClass = T.sync(() => {
331 | li.classList.add("editing");
332 | });
333 |
334 | // Hides the text input box
335 | const removeClass = T.sync(() => {
336 | li.classList.remove("editing");
337 | });
338 |
339 | const input = pipe(
340 | li,
341 | querySelector("input.edit"),
342 | T.fromOption(constant(makeElementNotFound("li>input"))),
343 | T.chain((input) => {
344 | // Gives the text input box focus and selects the text
345 | const setFocus = T.sync(() => {
346 | input.focus();
347 | input.select();
348 | });
349 |
350 | // Executes when the text input box looses focus
351 | // Will hide the text input box
352 | const handleBlur = pipe(
353 | input,
354 | subscribe("blur"),
355 | S.take(1),
356 | S.drain,
357 | T.zip(removeClass)
358 | );
359 |
360 | // Updates the store on every keystroke
361 | const handlTextInput = pipe(
362 | input,
363 | // Listen to the text input's "oninput" event
364 | subscribe("input"),
365 | S.chain(
366 | constant(
367 | pipe(
368 | todoStore,
369 | // Update the title of the todo in the store
370 | T.chain((store) =>
371 | store.next((state) => ({
372 | ...state,
373 | todos: state.todos.map((todo) =>
374 | todo.id === todoId
375 | ? { ...todo, title: input.value }
376 | : todo
377 | ),
378 | }))
379 | ),
380 | S.encaseEffect
381 | )
382 | )
383 | ),
384 | // Do this until the text input box looses focus
385 | S.takeUntil(handleBlur),
386 | S.drain
387 | );
388 |
389 | return pipe(setFocus, T.zip(handlTextInput));
390 | })
391 | );
392 |
393 | return pipe(addClass, T.zip(input));
394 | }),
395 | S.encaseEffect
396 | );
397 | }
398 |
399 | return S.encaseEffect(T.pure(constVoid()));
400 | }),
401 | S.drain
402 | );
403 |
404 | /**
405 | * ```hs
406 | *
407 | * replaceTodosInStore :: [Todo] => Effect
408 | *
409 | * ```
410 | */
411 | const replaceTodosInStore = (todos: Todos) =>
412 | pipe(
413 | todoStore,
414 | T.chain((store) => store.next((state) => ({ ...state, todos })))
415 | );
416 |
417 | /**
418 | * ```hs
419 | *
420 | * fetchAndStoreTodos :: Effect
421 | *
422 | * ```
423 | *
424 | * Fetch todo items from the server and replace the store with them.
425 | */
426 | const fetchAndStoreTodos = pipe(fetchTodos, T.chain(replaceTodosInStore));
427 |
428 | const logChanges = T.Do()
429 | .bind("store", todoStore)
430 | .bindL("subscription", ({ store }) => store.subscribe)
431 | .doL(({ subscription }) =>
432 | pipe(subscription, S.chain(flow(log, S.encaseEffect)), S.drain)
433 | )
434 | .return(constVoid);
435 |
436 | /**
437 | * ```hs
438 | *
439 | * emptyListOfTodos :: [Todo]
440 | *
441 | * ```
442 | *
443 | */
444 | const emptyListOfTodos: Todos = [];
445 |
446 | /**
447 | * ```hs
448 | *
449 | * getTodosDifference :: [Todo] -> [Todo] -> [Todo]
450 | *
451 | * ```
452 | *
453 | * Return todos from list a that are not in list b.
454 | * This is used to remove dom nodes of deleted todos
455 | *
456 | */
457 | const getTodosDifference = A.difference(eqTodoById);
458 |
459 | /**
460 | * ```hs
461 | *
462 | * removeTodosFromDom :: [Todo] -> Effect
463 | *
464 | * ```
465 | *
466 | * For each todo, remove it's related dom node if present.
467 | *
468 | */
469 | const removeTodosFromDom = (todos: Todos) =>
470 | pipe(
471 | todos,
472 | A.map((todo) =>
473 | pipe(
474 | // Find the dom node
475 | $(`[data-todo-id="${todo.id}"]`),
476 | // Remove it from the dom
477 | T.chain((li) => T.sync(li.remove.bind(li)))
478 | )
479 | ),
480 | A.readonlyArray.sequence(T.effect)
481 | );
482 |
483 | /**
484 | * ```hs
485 | *
486 | * optionOfPreviousTodoInDom :: Effect (Option HTMLLIElement)
487 | *
488 | * ```
489 | *
490 | * Initial "previous sibling". Used as the initial value when reducing a list of todos
491 | * into a single effect updating the dom
492 | *
493 | */
494 | const optionOfPreviousTodoInDom: T.Effect<
495 | unknown,
496 | Console & Dom,
497 | ReturnType | Error,
498 | O.Option
499 | > = T.pure(O.none);
500 |
501 | /**
502 | * ```hs
503 | *
504 | * createAndUpdateTodoNode :: HTMLUListElement -> Effect (Option HTMLLIElement) -> Effect HTMLLIElement
505 | *
506 | * ```
507 | *
508 | * Creates new dom nodes for todos that are not yet present in the dom
509 | * and updates dom nodes of other todos
510 | *
511 | */
512 | const createAndUpdateTodoNode = (ul: HTMLUListElement) => (
513 | domNodeOfPreviousTodoInList: O.Option
514 | ) => (todo: Todo) =>
515 | pipe(
516 | // Create a dom node
517 | createDomNodeForTodo,
518 | // Update it with information from the todo
519 | T.chain(updateDomNodeOfTodo(todo)),
520 | // Get the dom node it should attach itself to if available
521 | // With the new dom node and it's "previous sibling"
522 | T.chainTap((li) =>
523 | pipe(
524 | domNodeOfPreviousTodoInList,
525 | O.fold(
526 | // Prepend the dom node to the start of the list if no previous sibling is available
527 | constant(T.sync(() => ul.prepend(li))),
528 | // Other wise attach it after it's sibling
529 | (domNodeOfPreviousTodoInList) =>
530 | T.sync(() => domNodeOfPreviousTodoInList.after(li))
531 | )
532 | )
533 | )
534 | );
535 |
536 | /**
537 | * ```hs
538 | *
539 | * updateDomWithTodos :: HTMLUListElement -> [Todo] -> Effect
540 | *
541 | * ```
542 | *
543 | * Creates new dom nodes for todos that are not yet present in the dom
544 | * and updates dom nodes of other todos
545 | *
546 | */
547 | const updateDomWithTodos = (ul: HTMLUListElement) => (todos: Todos) =>
548 | pipe(
549 | todos,
550 | // Reduce the list of todos into a single effect
551 | A.reduce(optionOfPreviousTodoInDom, (acc, todo) =>
552 | pipe(
553 | // Chain over the previous effect
554 | acc,
555 | T.chain((optionOfSiblingTodoInDom) =>
556 | pipe(
557 | ul,
558 | querySelector(`[data-todo-id="${todo.id}"]`),
559 | O.fold(
560 | // Create a dom node for new todos
561 | // The accumulated effect is passed so that
562 | // new dom nodes can attach themselves after the previous one
563 | constant(
564 | createAndUpdateTodoNode(ul)(optionOfSiblingTodoInDom)(todo)
565 | ),
566 | // Or if a dom node was found, update it
567 | updateDomNodeOfTodo(todo)
568 | ),
569 | T.map(O.some)
570 | )
571 | )
572 | )
573 | )
574 | );
575 |
576 | /**
577 | * ```hs
578 | *
579 | * commitStoreUpdatesToDom :: Effect
580 | *
581 | * ```
582 | *
583 | * Subscribes to store changes and updates the dom.
584 | *
585 | */
586 | const commitStoreUpdatesToDom = T.Do()
587 | .bind("store", todoStore)
588 | .bindL("subscription", ({ store }) => store.subscribe)
589 | .bind("ul", todosUl)
590 | // With store subscription and root dom node do:
591 | .doL(({ subscription, ul }) =>
592 | pipe(
593 | subscription,
594 | S.map((state) =>
595 | state.filterBy === "all"
596 | ? state.todos
597 | : pipe(
598 | state.todos,
599 | A.filter((todo) =>
600 | state.filterBy === "completed"
601 | ? todo.completed
602 | : !todo.completed
603 | )
604 | )
605 | ),
606 | // Take 10 todo items at a time
607 | S.map(takeTenTodos),
608 | // Keep track of previous list to use for comparison
609 | S.scan(tuple(emptyListOfTodos, emptyListOfTodos), ([prev], next) =>
610 | tuple(next, prev)
611 | ),
612 | S.chain(([next, prev]) =>
613 | S.encaseEffect(
614 | pipe(
615 | // Remove todos that were in the previous list but not in the next
616 | removeTodosFromDom(getTodosDifference(prev, next)),
617 | // Add todos to the dom that are in the new list but weren't in the previous
618 | // or update nodes with new information
619 | T.zip(updateDomWithTodos(ul)(next))
620 | )
621 | )
622 | ),
623 | S.drain
624 | )
625 | )
626 | .return(constVoid);
627 |
628 | const updateCounter = pipe(
629 | todoStore,
630 | T.chain((store) => store.subscribe),
631 | S.encaseEffect,
632 | S.chain(identity),
633 | S.map((state) => state.todos),
634 | S.map((todos) =>
635 | pipe(
636 | todos,
637 | A.filter((todo) => !todo.completed)
638 | )
639 | ),
640 | S.map((todos) => todos.length),
641 | S.chain((itemsLeft) =>
642 | S.encaseEffect(
643 | pipe(
644 | $(".todo-count"),
645 | T.map(querySelector("strong")),
646 | T.chain(
647 | T.fromOption(constant(makeElementNotFound(".todo-count > strong")))
648 | ),
649 | T.chain((el) =>
650 | T.sync(() => {
651 | el.innerHTML = "" + itemsLeft;
652 | })
653 | )
654 | )
655 | )
656 | ),
657 | S.drain
658 | );
659 |
660 | const makeHandleFilter = (filterBy: "all" | "active" | "completed") =>
661 | pipe(
662 | $(`#btn-filter-${filterBy}`),
663 | S.encaseEffect,
664 | S.chain(subscribe("click")),
665 | S.chain(
666 | constant(
667 | S.encaseEffect(
668 | pipe(
669 | T.parSequenceT(
670 | $(`#btn-filter-all`),
671 | $(`#btn-filter-active`),
672 | $(`#btn-filter-completed`)
673 | ),
674 | T.chain((links) =>
675 | T.sync(() => {
676 | links.forEach((link) => link.classList.remove("selected"));
677 | })
678 | )
679 | )
680 | )
681 | )
682 | ),
683 | S.chain(
684 | constant(
685 | S.encaseEffect(
686 | pipe(
687 | todoStore,
688 | T.chain((store) => store.next((state) => ({ ...state, filterBy })))
689 | )
690 | )
691 | )
692 | ),
693 | S.chain(
694 | constant(
695 | S.encaseEffect(
696 | pipe(
697 | $(`#btn-filter-${filterBy}`),
698 | T.chain((link) =>
699 | T.sync(() => {
700 | link.classList.add("selected");
701 | })
702 | )
703 | )
704 | )
705 | )
706 | ),
707 | S.drain
708 | );
709 |
710 | const handleClearCompleted = pipe(
711 | $(`.clear-completed`),
712 | S.encaseEffect,
713 | S.chain(subscribe("click")),
714 | S.chain(
715 | constant(
716 | S.encaseEffect(
717 | pipe(
718 | todoStore,
719 | T.chain((store) =>
720 | store.next((state) => ({
721 | ...state,
722 | todos: pipe(
723 | state.todos,
724 | A.filter((todo) => !todo.completed)
725 | ),
726 | }))
727 | )
728 | )
729 | )
730 | )
731 | ),
732 | S.drain
733 | );
734 |
735 | const handleNewTodos = pipe(
736 | $(".new-todo"),
737 | S.encaseEffect,
738 | S.chain(subscribe("keyup")),
739 | S.filter((event) => event.key === "Enter"),
740 | S.map((event) => event.currentTarget as HTMLInputElement | null),
741 | S.map(O.fromNullable),
742 | S.chain(S.fromOption),
743 | S.filter((input) => !!input.value.trim()),
744 | S.chain((input) =>
745 | S.encaseEffect(
746 | pipe(
747 | todoStore,
748 | T.chain((store) =>
749 | store.next((state) => ({
750 | ...state,
751 | todos: [
752 | {
753 | id: Math.random(),
754 | title: input.value,
755 | completed: false,
756 | userId: Math.random(),
757 | },
758 | ...state.todos,
759 | ],
760 | }))
761 | ),
762 | T.chain(
763 | constant(
764 | T.sync(() => {
765 | input.value = "";
766 | })
767 | )
768 | )
769 | )
770 | )
771 | ),
772 | S.drain
773 | );
774 |
775 | const allTodosAreCompleted = (todos: Todos): boolean =>
776 | pipe(
777 | todos,
778 | A.foldLeft(
779 | constTrue,
780 | (todo, rest) => todo.completed && allTodosAreCompleted(rest)
781 | )
782 | );
783 |
784 | const handleMarkAllAsCompleted = pipe(
785 | $("#toggle-all"),
786 | T.zip(todoStore),
787 | T.chain(([input, store]) =>
788 | pipe(
789 | store.subscribe,
790 | T.map((susbscription) => tuple(input, store, susbscription))
791 | )
792 | ),
793 | S.encaseEffect,
794 | S.chain(([input, store, susbscription]) => {
795 | const stateS: S.AsyncR = pipe(
796 | susbscription,
797 | S.map((state) => getFilteredTodos(state.filterBy)(state.todos)),
798 | // Take 10 todo items at a time
799 | S.map(takeTenTodos),
800 | S.map((todos) => tuple(allTodosAreCompleted(todos), todos)),
801 | S.chain(([allCompleted, todos]) =>
802 | S.encaseEffect(
803 | T.sync(() => {
804 | input.checked = allCompleted;
805 | })
806 | )
807 | ),
808 | S.map(constVoid)
809 | );
810 |
811 | const clickS = pipe(
812 | subscribe("click")(input),
813 | S.chain(
814 | constant(
815 | S.encaseEffect(
816 | pipe(
817 | store.get,
818 | T.chain((stateO) =>
819 | pipe(
820 | stateO,
821 | O.map((state) => {
822 | const todosListed = pipe(
823 | getFilteredTodos(state.filterBy)(state.todos),
824 | takeTenTodos
825 | );
826 |
827 | const completed = !allTodosAreCompleted(todosListed);
828 |
829 | return store.next((state) => ({
830 | ...state,
831 | todos: state.todos.map((todo) =>
832 | pipe(
833 | todosListed,
834 | A.findFirstMap((listedTodo) =>
835 | listedTodo.id !== todo.id
836 | ? O.none
837 | : O.some({ ...todo, completed })
838 | ),
839 | O.fold(constant(todo), identity)
840 | )
841 | ),
842 | }));
843 | }),
844 | O.getOrElse>(constant(T.sync(constVoid)))
845 | )
846 | )
847 | )
848 | )
849 | )
850 | ),
851 | S.map(constVoid)
852 | );
853 |
854 | return S.mergeAll([stateS, clickS]);
855 | }),
856 | S.drain
857 | );
858 | /**
859 | * ```hs
860 | *
861 | * main :: Effect
862 | *
863 | * ```
864 | *
865 | * TodoMVC Program
866 | */
867 | export const main = pipe(
868 | T.parSequenceT(
869 | logChanges,
870 | fetchAndStoreTodos,
871 | handleEvents,
872 | commitStoreUpdatesToDom,
873 | updateCounter,
874 | makeHandleFilter("all"),
875 | makeHandleFilter("active"),
876 | makeHandleFilter("completed"),
877 | handleNewTodos,
878 | handleClearCompleted,
879 | handleMarkAllAsCompleted
880 | ),
881 | provideTodoStore
882 | );
883 |
--------------------------------------------------------------------------------