Browse Source

sum types with button color states (#1)

sum types with button color states

Co-authored-by: ken <piq9117@gmail.com>
Reviewed-on: https://taezos.org/piq9117/notes-examples/pulls/1
master
piq9117 2 years ago
parent
commit
4eb76e9ab2
38 changed files with 37571 additions and 0 deletions
  1. +40
    -0
      button-sum-types/.gitignore
  2. +1
    -0
      button-sum-types/ps/.psc-ide-port
  3. +23
    -0
      button-sum-types/ps/Makefile
  4. +18
    -0
      button-sum-types/ps/assets/index.html
  5. +20
    -0
      button-sum-types/ps/assets/index.js
  6. +7071
    -0
      button-sum-types/ps/package-lock.json
  7. +14
    -0
      button-sum-types/ps/package.json
  8. +128
    -0
      button-sum-types/ps/packages.dhall
  9. +19
    -0
      button-sum-types/ps/spago.dhall
  10. +41
    -0
      button-sum-types/ps/src/Component/Button.purs
  11. +17
    -0
      button-sum-types/ps/src/Component/Title.purs
  12. +62
    -0
      button-sum-types/ps/src/Main.purs
  13. +10
    -0
      button-sum-types/ps/test/Main.purs
  14. +44
    -0
      button-sum-types/ts/README.md
  15. +17
    -0
      button-sum-types/ts/default.nix
  16. +542
    -0
      button-sum-types/ts/node-env.nix
  17. +14990
    -0
      button-sum-types/ts/node-packages.nix
  18. +13993
    -0
      button-sum-types/ts/package-lock.json
  19. +40
    -0
      button-sum-types/ts/package.json
  20. +11
    -0
      button-sum-types/ts/pinned.nix
  21. BIN
      button-sum-types/ts/public/favicon.ico
  22. +44
    -0
      button-sum-types/ts/public/index.html
  23. BIN
      button-sum-types/ts/public/logo192.png
  24. BIN
      button-sum-types/ts/public/logo512.png
  25. +25
    -0
      button-sum-types/ts/public/manifest.json
  26. +3
    -0
      button-sum-types/ts/public/robots.txt
  27. +12
    -0
      button-sum-types/ts/shell.nix
  28. +38
    -0
      button-sum-types/ts/src/App.css
  29. +9
    -0
      button-sum-types/ts/src/App.test.tsx
  30. +61
    -0
      button-sum-types/ts/src/App.tsx
  31. +61
    -0
      button-sum-types/ts/src/Button.tsx
  32. +13
    -0
      button-sum-types/ts/src/index.css
  33. +17
    -0
      button-sum-types/ts/src/index.tsx
  34. +7
    -0
      button-sum-types/ts/src/logo.svg
  35. +1
    -0
      button-sum-types/ts/src/react-app-env.d.ts
  36. +149
    -0
      button-sum-types/ts/src/serviceWorker.ts
  37. +5
    -0
      button-sum-types/ts/src/setupTests.ts
  38. +25
    -0
      button-sum-types/ts/tsconfig.json

+ 40
- 0
button-sum-types/.gitignore View File

@@ -0,0 +1,40 @@
# 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*

# spago
**/output
data
test/spago-test
.stack-work/
*.cabal
*~
**/__pycache__
templates/docs-search-app.js
templates/purescript-docs-search
.envrc
curator.log
.DS_Store
**/.spago
**/.cache
**/dist

+ 1
- 0
button-sum-types/ps/.psc-ide-port View File

@@ -0,0 +1 @@
15749

+ 23
- 0
button-sum-types/ps/Makefile View File

@@ -0,0 +1,23 @@
build-all:
spago build && npm install

build:
spago build

build-watch:
spago build --watch

bundle:
spago bundle-app --main Main --to dist/app.js && ./node_modules/.bin/parcel build assets/index.html

bundle-watch:
spago bundle-app --main Main --to dist/app.js --watch

clean:
rm -rf .cache .spago node_modules .psci_modules output dist

start:
./node_modules/.bin/parcel assets/index.html

bundle-start:
make bundle && make start

+ 18
- 0
button-sum-types/ps/assets/index.html View File

@@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.0/css/bulma.min.css">
<title>React App</title>
</head>
<body>
<div id="app"></div>
<script src="./index.js"></script>
</body>
</html>

+ 20
- 0
button-sum-types/ps/assets/index.js View File

@@ -0,0 +1,20 @@
import React from "react";
import ReactDOM from "react-dom";

import Main from "../output/Main";

function main () {
const component = React.createElement(Main.mainJSX, { label: "MainComponent" });

ReactDOM.render(component, document.getElementById("app"));
}

if ( module.hot ) {
module.hot.accept(function () {
console.log("[INFO]: Running main...");
main();
})
}

console.log("[INFO]: Starting...");
main();

+ 7071
- 0
button-sum-types/ps/package-lock.json
File diff suppressed because it is too large
View File


+ 14
- 0
button-sum-types/ps/package.json View File

@@ -0,0 +1,14 @@
{
"name": "my-react-basic-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"parcel-bundler": "^1.12.4",
"react": "^16.12.0",
"react-dom": "^16.12.0"
}
}

+ 128
- 0
button-sum-types/ps/packages.dhall View File

@@ -0,0 +1,128 @@
{-
Welcome to your new Dhall package-set!

Below are instructions for how to edit this file for most use
cases, so that you don't need to know Dhall to use it.

## Warning: Don't Move This Top-Level Comment!

Due to how `dhall format` currently works, this comment's
instructions cannot appear near corresponding sections below
because `dhall format` will delete the comment. However,
it will not delete a top-level comment like this one.

## Use Cases

Most will want to do one or both of these options:
1. Override/Patch a package's dependency
2. Add a package not already in the default package set

This file will continue to work whether you use one or both options.
Instructions for each option are explained below.

### Overriding/Patching a package

Purpose:
- Change a package's dependency to a newer/older release than the
default package set's release
- Use your own modified version of some dependency that may
include new API, changed API, removed API by
using your custom git repo of the library rather than
the package set's repo

Syntax:
Replace the overrides' "{=}" (an empty record) with the following idea
The "//" means "merge these two records and
when they have the same value, use the one on the right:"
-------------------------------
let override =
{ packageName =
upstream.packageName // { updateEntity1 = "new value", updateEntity2 = "new value" }
, packageName =
upstream.packageName // { version = "v4.0.0" }
, packageName =
upstream.packageName // { repo = "https://www.example.com/path/to/new/repo.git" }
}
-------------------------------

Example:
-------------------------------
let overrides =
{ halogen =
upstream.halogen // { version = "master" }
, halogen-vdom =
upstream.halogen-vdom // { version = "v4.0.0" }
}
-------------------------------

### Additions

Purpose:
- Add packages that aren't already included in the default package set

Syntax:
Replace the additions' "{=}" (an empty record) with the following idea:
-------------------------------
let additions =
{ package-name =
{ dependencies =
[ "dependency1"
, "dependency2"
]
, repo =
"https://example.com/path/to/git/repo.git"
, version =
"tag ('v4.0.0') or branch ('master')"
}
, package-name =
{ dependencies =
[ "dependency1"
, "dependency2"
]
, repo =
"https://example.com/path/to/git/repo.git"
, version =
"tag ('v4.0.0') or branch ('master')"
}
, etc.
}
-------------------------------

Example:
-------------------------------
let additions =
{ benchotron =
{ dependencies =
[ "arrays"
, "exists"
, "profunctor"
, "strings"
, "quickcheck"
, "lcg"
, "transformers"
, "foldable-traversable"
, "exceptions"
, "node-fs"
, "node-buffer"
, "node-readline"
, "datetime"
, "now"
]
, repo =
"https://github.com/hdgarrood/purescript-benchotron.git"
, version =
"v7.0.0"
}
}
-------------------------------
-}


let upstream =
https://github.com/purescript/package-sets/releases/download/psc-0.13.6-20200226/packages.dhall sha256:3a52562e05b31a7b51d12d5b228ccbe567c527781a88e9028ab42374ab55c0f1

let overrides = {=}

let additions = {=}

in upstream // overrides // additions

+ 19
- 0
button-sum-types/ps/spago.dhall View File

@@ -0,0 +1,19 @@
{-
Welcome to a Spago project!
You can edit this file as you like.
-}
{ name = "my-react-basic-project"
, dependencies =
[ "console"
, "effect"
, "exceptions"
, "psci-support"
, "react-basic"
, "react-basic-hooks"
, "web-dom"
, "web-html"
, "generics-rep"
]
, packages = ./packages.dhall
, sources = [ "src/**/*.purs", "test/**/*.purs" ]
}

+ 41
- 0
button-sum-types/ps/src/Component/Button.purs View File

@@ -0,0 +1,41 @@
module Component.Button
( mkButton
, ButtonColor(..)
) where

import Prelude
import Data.Generic.Rep ( class Generic )
import Data.Generic.Rep.Show ( genericShow )
-- effect
import Effect ( Effect )
-- react
import React.Basic.DOM as R
import React.Basic.Hooks ( ReactComponent, component )

type Props = { color :: ButtonColor }

data ButtonColor
= Blue
| Red
| Yellow

derive instance genericButtonColor :: Generic ButtonColor _
derive instance eqButtonColor :: Eq ButtonColor

instance showButtonColor :: Show ButtonColor where
show = genericShow

colorToClassName :: ButtonColor -> String
colorToClassName = case _ of
Blue -> "is-info"
Red -> "is-danger"
Yellow -> "is-warning"

mkButton :: Effect ( ReactComponent Props )
mkButton = do
component "Button" $ \props -> React.do
pure
$ R.button
{ children: [ R.text "Hello" ]
, className: "button " <> colorToClassName props.color
}

+ 17
- 0
button-sum-types/ps/src/Component/Title.purs View File

@@ -0,0 +1,17 @@
module Component.Title
( mkTitle
) where

import Prelude ( ($), pure )
import React.Basic.DOM as R
import React.Basic.Hooks ( ReactComponent, component )
import Effect ( Effect )

type Props = { text :: String }

mkTitle :: Effect ( ReactComponent Props )
mkTitle = do
component "Title" $ \props -> React.do
pure $
R.h1_
[ R.text props.text ]

+ 62
- 0
button-sum-types/ps/src/Main.purs View File

@@ -0,0 +1,62 @@
module Main where

import Prelude ( Unit, bind, map, ($), (=<<), const, pure )
import Data.Maybe ( Maybe(..) )
-- internal component
import Component.Button
-- web
import Web.DOM.NonElementParentNode ( getElementById )
import Web.HTML.HTMLDocument ( toNonElementParentNode )
import Web.HTML.Window ( document )
import Web.HTML ( window )
-- effect
import Effect ( Effect )
import Effect.Exception ( throw )
-- react
import React.Basic.Hooks ( element, ReactComponent, component, JSX )
import React.Basic.DOM as R

data Response
= Success
| Error
| Warning

type Props = { response :: Response }

responseToColor :: Response -> ButtonColor
responseToColor = case _ of
Success -> Blue
Error -> Red
Warning -> Yellow

mkMainComponent :: Effect ( ReactComponent Props )
mkMainComponent = do
button <- mkButton
component "Main" $ \props -> React.do
pure $
R.div
{ className: "container"
, children:
[ R.div
{ className: "section"
, children:
[ element button { color: responseToColor props.response }
]
}
]
}

-- This is separated so it can be called in the hot reload function.
mainJSX :: Effect JSX
mainJSX = do
mainComp <- mkMainComponent
pure $ element mainComp { response: Error }

main :: Effect Unit
main = do
mApp <- getElementById "app" =<< ( map toNonElementParentNode $ document =<< window )
case mApp of
Nothing -> throw "App element not found."
Just app -> do
mainComponent <- mainJSX
R.render mainComponent app

+ 10
- 0
button-sum-types/ps/test/Main.purs View File

@@ -0,0 +1,10 @@
module Test.Main where

import Prelude
-- Effect
import Effect (Effect)
import Effect.Class.Console (log)

main :: Effect Unit
main = do
log "You should add some tests."

+ 44
- 0
button-sum-types/ts/README.md View File

@@ -0,0 +1,44 @@
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 can’t go back!**

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.

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.

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.

## 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/).

+ 17
- 0
button-sum-types/ts/default.nix View File

@@ -0,0 +1,17 @@
# This file has been generated by node2nix 1.8.0. Do not edit!

{pkgs ? import <nixpkgs> {
inherit system;
}, system ? builtins.currentSystem, nodejs ? pkgs."nodejs-12_x"}:

let
nodeEnv = import ./node-env.nix {
inherit (pkgs) stdenv python2 utillinux runCommand writeTextFile;
inherit nodejs;
libtool = if pkgs.stdenv.isDarwin then pkgs.darwin.cctools else null;
};
in
import ./node-packages.nix {
inherit (pkgs) fetchurl fetchgit;
inherit nodeEnv;
}

+ 542
- 0
button-sum-types/ts/node-env.nix View File

@@ -0,0 +1,542 @@
# This file originates from node2nix

{stdenv, nodejs, python2, utillinux, libtool, runCommand, writeTextFile}:

let
python = if nodejs ? python then nodejs.python else python2;

# Create a tar wrapper that filters all the 'Ignoring unknown extended header keyword' noise
tarWrapper = runCommand "tarWrapper" {} ''
mkdir -p $out/bin

cat > $out/bin/tar <<EOF
#! ${stdenv.shell} -e
$(type -p tar) "\$@" --warning=no-unknown-keyword --delay-directory-restore
EOF

chmod +x $out/bin/tar
'';

# Function that generates a TGZ file from a NPM project
buildNodeSourceDist =
{ name, version, src, ... }:

stdenv.mkDerivation {
name = "node-tarball-${name}-${version}";
inherit src;
buildInputs = [ nodejs ];
buildPhase = ''
export HOME=$TMPDIR
tgzFile=$(npm pack | tail -n 1) # Hooks to the pack command will add output (https://docs.npmjs.com/misc/scripts)
'';
installPhase = ''
mkdir -p $out/tarballs
mv $tgzFile $out/tarballs
mkdir -p $out/nix-support
echo "file source-dist $out/tarballs/$tgzFile" >> $out/nix-support/hydra-build-products
'';
};

includeDependencies = {dependencies}:
stdenv.lib.optionalString (dependencies != [])
(stdenv.lib.concatMapStrings (dependency:
''
# Bundle the dependencies of the package
mkdir -p node_modules
cd node_modules

# Only include dependencies if they don't exist. They may also be bundled in the package.
if [ ! -e "${dependency.name}" ]
then
${composePackage dependency}
fi

cd ..
''
) dependencies);

# Recursively composes the dependencies of a package
composePackage = { name, packageName, src, dependencies ? [], ... }@args:
builtins.addErrorContext "while evaluating node package '${packageName}'" ''
DIR=$(pwd)
cd $TMPDIR

unpackFile ${src}

# Make the base dir in which the target dependency resides first
mkdir -p "$(dirname "$DIR/${packageName}")"

if [ -f "${src}" ]
then
# Figure out what directory has been unpacked
packageDir="$(find . -maxdepth 1 -type d | tail -1)"

# Restore write permissions to make building work
find "$packageDir" -type d -exec chmod u+x {} \;
chmod -R u+w "$packageDir"

# Move the extracted tarball into the output folder
mv "$packageDir" "$DIR/${packageName}"
elif [ -d "${src}" ]
then
# Get a stripped name (without hash) of the source directory.
# On old nixpkgs it's already set internally.
if [ -z "$strippedName" ]
then
strippedName="$(stripHash ${src})"
fi

# Restore write permissions to make building work
chmod -R u+w "$strippedName"

# Move the extracted directory into the output folder
mv "$strippedName" "$DIR/${packageName}"
fi

# Unset the stripped name to not confuse the next unpack step
unset strippedName

# Include the dependencies of the package
cd "$DIR/${packageName}"
${includeDependencies { inherit dependencies; }}
cd ..
${stdenv.lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."}
'';

pinpointDependencies = {dependencies, production}:
let
pinpointDependenciesFromPackageJSON = writeTextFile {
name = "pinpointDependencies.js";
text = ''
var fs = require('fs');
var path = require('path');

function resolveDependencyVersion(location, name) {
if(location == process.env['NIX_STORE']) {
return null;
} else {
var dependencyPackageJSON = path.join(location, "node_modules", name, "package.json");

if(fs.existsSync(dependencyPackageJSON)) {
var dependencyPackageObj = JSON.parse(fs.readFileSync(dependencyPackageJSON));

if(dependencyPackageObj.name == name) {
return dependencyPackageObj.version;
}
} else {
return resolveDependencyVersion(path.resolve(location, ".."), name);
}
}
}

function replaceDependencies(dependencies) {
if(typeof dependencies == "object" && dependencies !== null) {
for(var dependency in dependencies) {
var resolvedVersion = resolveDependencyVersion(process.cwd(), dependency);

if(resolvedVersion === null) {
process.stderr.write("WARNING: cannot pinpoint dependency: "+dependency+", context: "+process.cwd()+"\n");
} else {
dependencies[dependency] = resolvedVersion;
}
}
}
}

/* Read the package.json configuration */
var packageObj = JSON.parse(fs.readFileSync('./package.json'));

/* Pinpoint all dependencies */
replaceDependencies(packageObj.dependencies);
if(process.argv[2] == "development") {
replaceDependencies(packageObj.devDependencies);
}
replaceDependencies(packageObj.optionalDependencies);

/* Write the fixed package.json file */
fs.writeFileSync("package.json", JSON.stringify(packageObj, null, 2));
'';
};
in
''
node ${pinpointDependenciesFromPackageJSON} ${if production then "production" else "development"}

${stdenv.lib.optionalString (dependencies != [])
''
if [ -d node_modules ]
then
cd node_modules
${stdenv.lib.concatMapStrings (dependency: pinpointDependenciesOfPackage dependency) dependencies}
cd ..
fi
''}
'';

# Recursively traverses all dependencies of a package and pinpoints all
# dependencies in the package.json file to the versions that are actually
# being used.

pinpointDependenciesOfPackage = { packageName, dependencies ? [], production ? true, ... }@args:
''
if [ -d "${packageName}" ]
then
cd "${packageName}"
${pinpointDependencies { inherit dependencies production; }}
cd ..
${stdenv.lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."}
fi
'';

# Extract the Node.js source code which is used to compile packages with
# native bindings
nodeSources = runCommand "node-sources" {} ''
tar --no-same-owner --no-same-permissions -xf ${nodejs.src}
mv node-* $out
'';

# Script that adds _integrity fields to all package.json files to prevent NPM from consulting the cache (that is empty)
addIntegrityFieldsScript = writeTextFile {
name = "addintegrityfields.js";
text = ''
var fs = require('fs');
var path = require('path');

function augmentDependencies(baseDir, dependencies) {
for(var dependencyName in dependencies) {
var dependency = dependencies[dependencyName];

// Open package.json and augment metadata fields
var packageJSONDir = path.join(baseDir, "node_modules", dependencyName);
var packageJSONPath = path.join(packageJSONDir, "package.json");

if(fs.existsSync(packageJSONPath)) { // Only augment packages that exist. Sometimes we may have production installs in which development dependencies can be ignored
console.log("Adding metadata fields to: "+packageJSONPath);
var packageObj = JSON.parse(fs.readFileSync(packageJSONPath));

if(dependency.integrity) {
packageObj["_integrity"] = dependency.integrity;
} else {
packageObj["_integrity"] = "sha1-000000000000000000000000000="; // When no _integrity string has been provided (e.g. by Git dependencies), add a dummy one. It does not seem to harm and it bypasses downloads.
}

if(dependency.resolved) {
packageObj["_resolved"] = dependency.resolved; // Adopt the resolved property if one has been provided
} else {
packageObj["_resolved"] = dependency.version; // Set the resolved version to the version identifier. This prevents NPM from cloning Git repositories.
}

if(dependency.from !== undefined) { // Adopt from property if one has been provided
packageObj["_from"] = dependency.from;
}

fs.writeFileSync(packageJSONPath, JSON.stringify(packageObj, null, 2));
}

// Augment transitive dependencies
if(dependency.dependencies !== undefined) {
augmentDependencies(packageJSONDir, dependency.dependencies);
}
}
}

if(fs.existsSync("./package-lock.json")) {
var packageLock = JSON.parse(fs.readFileSync("./package-lock.json"));

if(packageLock.lockfileVersion !== 1) {
process.stderr.write("Sorry, I only understand lock file version 1!\n");
process.exit(1);
}

if(packageLock.dependencies !== undefined) {
augmentDependencies(".", packageLock.dependencies);
}
}
'';
};

# Reconstructs a package-lock file from the node_modules/ folder structure and package.json files with dummy sha1 hashes
reconstructPackageLock = writeTextFile {
name = "addintegrityfields.js";
text = ''
var fs = require('fs');
var path = require('path');

var packageObj = JSON.parse(fs.readFileSync("package.json"));

var lockObj = {
name: packageObj.name,
version: packageObj.version,
lockfileVersion: 1,
requires: true,
dependencies: {}
};

function augmentPackageJSON(filePath, dependencies) {
var packageJSON = path.join(filePath, "package.json");
if(fs.existsSync(packageJSON)) {
var packageObj = JSON.parse(fs.readFileSync(packageJSON));
dependencies[packageObj.name] = {
version: packageObj.version,
integrity: "sha1-000000000000000000000000000=",
dependencies: {}
};
processDependencies(path.join(filePath, "node_modules"), dependencies[packageObj.name].dependencies);
}
}

function processDependencies(dir, dependencies) {
if(fs.existsSync(dir)) {
var files = fs.readdirSync(dir);

files.forEach(function(entry) {
var filePath = path.join(dir, entry);
var stats = fs.statSync(filePath);

if(stats.isDirectory()) {
if(entry.substr(0, 1) == "@") {
// When we encounter a namespace folder, augment all packages belonging to the scope
var pkgFiles = fs.readdirSync(filePath);

pkgFiles.forEach(function(entry) {
if(stats.isDirectory()) {
var pkgFilePath = path.join(filePath, entry);
augmentPackageJSON(pkgFilePath, dependencies);
}
});
} else {
augmentPackageJSON(filePath, dependencies);
}
}
});
}
}

processDependencies("node_modules", lockObj.dependencies);

fs.writeFileSync("package-lock.json", JSON.stringify(lockObj, null, 2));
'';
};

prepareAndInvokeNPM = {packageName, bypassCache, reconstructLock, npmFlags, production}:
let
forceOfflineFlag = if bypassCache then "--offline" else "--registry http://www.example.com";
in
''
# Pinpoint the versions of all dependencies to the ones that are actually being used
echo "pinpointing versions of dependencies..."
source $pinpointDependenciesScriptPath

# Patch the shebangs of the bundled modules to prevent them from
# calling executables outside the Nix store as much as possible
patchShebangs .

# Deploy the Node.js package by running npm install. Since the
# dependencies have been provided already by ourselves, it should not
# attempt to install them again, which is good, because we want to make
# it Nix's responsibility. If it needs to install any dependencies
# anyway (e.g. because the dependency parameters are
# incomplete/incorrect), it fails.
#
# The other responsibilities of NPM are kept -- version checks, build
# steps, postprocessing etc.

export HOME=$TMPDIR
cd "${packageName}"
runHook preRebuild

${stdenv.lib.optionalString bypassCache ''
${stdenv.lib.optionalString reconstructLock ''
if [ -f package-lock.json ]
then
echo "WARNING: Reconstruct lock option enabled, but a lock file already exists!"
echo "This will most likely result in version mismatches! We will remove the lock file and regenerate it!"
rm package-lock.json
else
echo "No package-lock.json file found, reconstructing..."
fi

node ${reconstructPackageLock}
''}

node ${addIntegrityFieldsScript}
''}

npm ${forceOfflineFlag} --nodedir=${nodeSources} ${npmFlags} ${stdenv.lib.optionalString production "--production"} rebuild

if [ "''${dontNpmInstall-}" != "1" ]
then
# NPM tries to download packages even when they already exist if npm-shrinkwrap is used.
rm -f npm-shrinkwrap.json

npm ${forceOfflineFlag} --nodedir=${nodeSources} ${npmFlags} ${stdenv.lib.optionalString production "--production"} install
fi
'';

# Builds and composes an NPM package including all its dependencies
buildNodePackage =
{ name
, packageName
, version
, dependencies ? []
, buildInputs ? []
, production ? true
, npmFlags ? ""
, dontNpmInstall ? false
, bypassCache ? false
, reconstructLock ? false
, preRebuild ? ""
, dontStrip ? true
, unpackPhase ? "true"
, buildPhase ? "true"
, ... }@args:

let
extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" "dontStrip" "dontNpmInstall" "preRebuild" "unpackPhase" "buildPhase" ];
in
stdenv.mkDerivation ({
name = "node_${name}-${version}";
buildInputs = [ tarWrapper python nodejs ]
++ stdenv.lib.optional (stdenv.isLinux) utillinux
++ stdenv.lib.optional (stdenv.isDarwin) libtool
++ buildInputs;

inherit nodejs;

inherit dontStrip; # Stripping may fail a build for some package deployments
inherit dontNpmInstall preRebuild unpackPhase buildPhase;

compositionScript = composePackage args;
pinpointDependenciesScript = pinpointDependenciesOfPackage args;

passAsFile = [ "compositionScript" "pinpointDependenciesScript" ];

installPhase = ''
# Create and enter a root node_modules/ folder
mkdir -p $out/lib/node_modules
cd $out/lib/node_modules

# Compose the package and all its dependencies
source $compositionScriptPath

${prepareAndInvokeNPM { inherit packageName bypassCache reconstructLock npmFlags production; }}

# Create symlink to the deployed executable folder, if applicable
if [ -d "$out/lib/node_modules/.bin" ]
then
ln -s $out/lib/node_modules/.bin $out/bin
fi

# Create symlinks to the deployed manual page folders, if applicable
if [ -d "$out/lib/node_modules/${packageName}/man" ]
then
mkdir -p $out/share
for dir in "$out/lib/node_modules/${packageName}/man/"*
do
mkdir -p $out/share/man/$(basename "$dir")
for page in "$dir"/*
do
ln -s $page $out/share/man/$(basename "$dir")
done
done
fi

# Run post install hook, if provided
runHook postInstall
'';
} // extraArgs);

# Builds a development shell
buildNodeShell =
{ name
, packageName
, version
, src
, dependencies ? []
, buildInputs ? []
, production ? true
, npmFlags ? ""
, dontNpmInstall ? false
, bypassCache ? false
, reconstructLock ? false
, dontStrip ? true
, unpackPhase ? "true"
, buildPhase ? "true"
, ... }@args:

let
extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" ];

nodeDependencies = stdenv.mkDerivation ({
name = "node-dependencies-${name}-${version}";

buildInputs = [ tarWrapper python nodejs ]
++ stdenv.lib.optional (stdenv.isLinux) utillinux
++ stdenv.lib.optional (stdenv.isDarwin) libtool
++ buildInputs;

inherit dontStrip; # Stripping may fail a build for some package deployments
inherit dontNpmInstall unpackPhase buildPhase;

includeScript = includeDependencies { inherit dependencies; };
pinpointDependenciesScript = pinpointDependenciesOfPackage args;

passAsFile = [ "includeScript" "pinpointDependenciesScript" ];

installPhase = ''
mkdir -p $out/${packageName}
cd $out/${packageName}

source $includeScriptPath

# Create fake package.json to make the npm commands work properly
cp ${src}/package.json .
chmod 644 package.json
${stdenv.lib.optionalString bypassCache ''
if [ -f ${src}/package-lock.json ]
then
cp ${src}/package-lock.json .
fi
''}

# Go to the parent folder to make sure that all packages are pinpointed
cd ..
${stdenv.lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."}

${prepareAndInvokeNPM { inherit packageName bypassCache reconstructLock npmFlags production; }}

# Expose the executables that were installed
cd ..
${stdenv.lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."}

mv ${packageName} lib
ln -s $out/lib/node_modules/.bin $out/bin
'';
} // extraArgs);
in
stdenv.mkDerivation {
name = "node-shell-${name}-${version}";

buildInputs = [ python nodejs ] ++ stdenv.lib.optional (stdenv.isLinux) utillinux ++ buildInputs;
buildCommand = ''
mkdir -p $out/bin
cat > $out/bin/shell <<EOF
#! ${stdenv.shell} -e
$shellHook
exec ${stdenv.shell}
EOF
chmod +x $out/bin/shell
'';

# Provide the dependencies in a development shell through the NODE_PATH environment variable
inherit nodeDependencies;
shellHook = stdenv.lib.optionalString (dependencies != []) ''
export NODE_PATH=${nodeDependencies}/lib/node_modules
export PATH="${nodeDependencies}/bin:$PATH"
'';
};
in
{
buildNodeSourceDist = stdenv.lib.makeOverridable buildNodeSourceDist;
buildNodePackage = stdenv.lib.makeOverridable buildNodePackage;
buildNodeShell = stdenv.lib.makeOverridable buildNodeShell;
}

+ 14990
- 0
button-sum-types/ts/node-packages.nix
File diff suppressed because it is too large
View File


+ 13993
- 0
button-sum-types/ts/package-lock.json
File diff suppressed because it is too large
View File


+ 40
- 0
button-sum-types/ts/package.json View File

@@ -0,0 +1,40 @@
{
"name": "button-sum-types",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"@types/jest": "^24.9.1",
"@types/node": "^12.12.47",
"@types/react": "^16.9.38",
"@types/react-dom": "^16.9.8",
"fp-ts": "^2.6.6",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1",
"typescript": "^3.7.5"
},
"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"
]
}
}

+ 11
- 0
button-sum-types/ts/pinned.nix View File

@@ -0,0 +1,11 @@
let
pkgs = import <nixpkgs> {};
in
import (
pkgs.fetchFromGitHub {
owner = "nixos";
repo = "nixpkgs";
rev = "e2e76d54f817bccd8b68f58b8a6c00d179453820";
sha256 = "03f335qdxx64wzvxmz41d2g8dagm99f5bpssmdlpk64bmragihm7";
}
)

BIN
button-sum-types/ts/public/favicon.ico View File

Before After

+ 44
- 0
button-sum-types/ts/public/index.html View File

@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.0/css/bulma.min.css">
<!--
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>React 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>

BIN
button-sum-types/ts/public/logo192.png View File

Before After
Width: 192  |  Height: 192  |  Size: 5.2 KiB

BIN
button-sum-types/ts/public/logo512.png View File

Before After
Width: 512  |  Height: 512  |  Size: 9.4 KiB

+ 25
- 0
button-sum-types/ts/public/manifest.json View File

@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

+ 3
- 0
button-sum-types/ts/public/robots.txt View File

@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

+ 12
- 0
button-sum-types/ts/shell.nix View File

@@ -0,0 +1,12 @@
{ nixpkgs ? import ./pinned.nix {} }:
let
inherit (nixpkgs) pkgs;
inherit (pkgs) nodePackages;
in
pkgs.mkShell rec {
name = "button-sum-types";
buildInputs = with pkgs; [
pkgs.nodejs
nodePackages.npm
];
}

+ 38
- 0
button-sum-types/ts/src/App.css View File

@@ -0,0 +1,38 @@
.App {
text-align: center;
}

.App-logo {
height: 40vmin;
pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}

.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}

.App-link {
color: #61dafb;
}

@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

+ 9
- 0
button-sum-types/ts/src/App.test.tsx View File

@@ -0,0 +1,9 @@
import React from 'react';
import { render } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
const { getByText } = render(<App />);
const linkElement = getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

+ 61
- 0
button-sum-types/ts/src/App.tsx View File

@@ -0,0 +1,61 @@
import React from 'react';
import './App.css';
import {
Button, blue, red, yellow, noColor, ButtonColor, Blue, Red, Yellow
} from "./Button";
import { pipe } from "fp-ts/lib/function";
import { fromNullable, getOrElse, map } from "fp-ts/lib/Option";

interface Success {
tag: "success";
color: Blue;
}

interface Error {
tag: "error";
color: Red;
}

interface Warning {
tag: "warning";
color: Yellow;
}

type Response
= Success
| Error
| Warning

interface Responses {
success: Success;
error: Error;
warning: Warning;
}

export const success: Success = ({ tag: "success", color: blue });
export const error: Error = ({ tag: "error", color: red });
export const warning: Warning = ({ tag: "warning", color: yellow });

const responses: Responses = {
success,
error,
warning
}

const responseToColor = (res: Response): ButtonColor =>
pipe(
fromNullable(responses[res.tag]),
map((r: Response) => r.color),
getOrElse(() => noColor as ButtonColor) // have to tell typescript noColor is a member of ButtonColor
);

export function App() {
let httpResponse = error;
return (
<div className="container">
<div className="section">
<Button color={responseToColor(httpResponse)} />
</div>
</div>
);
}

+ 61
- 0
button-sum-types/ts/src/Button.tsx View File

@@ -0,0 +1,61 @@
import React from "react";
import { pipe } from "fp-ts/lib/function";
import { fromNullable, map, getOrElse } from "fp-ts/lib/Option";

export interface Red {
tag: "red";
className: string;
}

export interface Blue {
tag: "blue";
className: string;
}

export interface Yellow {
tag: "yellow";
className: string;
}

export interface NoColor {
tag: "noColor";
className: string;
}


export type ButtonColor
= Red
| Blue
| Yellow
| NoColor;

interface Colors {
blue: Blue;
red: Red;
yellow: Yellow;
noColor: NoColor;
}

const toClassName = (b: ButtonColor): string =>
// pattern matching
pipe(
fromNullable(colors[b.tag]),
map((c: ButtonColor) => c.className),
getOrElse(() => noColor.className)
);

export const blue: Blue = ({ tag: "blue", className: "is-info" });
export const red: Red = ({ tag: "red", className: "is-danger" });
export const yellow: Yellow = ({ tag: "yellow", className: "is-warning" });
export const noColor: NoColor = ({ tag: "noColor", className: "" });

const colors: Colors = {
blue,
red,
yellow,
noColor
};

export function Button (props: { color: ButtonColor }) {
return ( <button className={ "button " + toClassName(props.color) }>Hello</button> );
}

+ 13
- 0
button-sum-types/ts/src/index.css View File

@@ -0,0 +1,13 @@
body {
margin: 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;
}

+ 17
- 0
button-sum-types/ts/src/index.tsx View File

@@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { App } from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
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();

+ 7
- 0
button-sum-types/ts/src/logo.svg View File

@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
<g fill="#61DAFB">
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
<circle cx="420.9" cy="296.5" r="45.7"/>
<path d="M520.5 78.1z"/>
</g>
</svg>

+ 1
- 0
button-sum-types/ts/src/react-app-env.d.ts View File

@@ -0,0 +1 @@
/// <reference types="react-scripts" />

+ 149
- 0
button-sum-types/ts/src/serviceWorker.ts View File

@@ -0,0 +1,149 @@
// 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.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);

type Config = {
onSuccess?: (registration: ServiceWorkerRegistration) => void;
onUpdate?: (registration: ServiceWorkerRegistration) => void;
};

export function register(config?: 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: string, config?: 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: string, config?: Config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' }
})
.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();
})
.catch(error => {
console.error(error.message);
});
}
}

+ 5
- 0
button-sum-types/ts/src/setupTests.ts View File

@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect';

+ 25
- 0
button-sum-types/ts/tsconfig.json View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}

Loading…
Cancel
Save