Implement wires module in React

New project to rewrite this in React.
This commit is contained in:
Daniel Sinn
2019-11-25 08:35:03 -05:00
parent ada083c346
commit 28a4d8c4f8
20 changed files with 13938 additions and 150 deletions
Executable
+346
View File
@@ -0,0 +1,346 @@
body {
background-color: white;
color: black;
font-family: monospace;
}
section {
border-top: 1px solid black;
clear: both;
padding: 1em;
}
h2 {
margin-top: 0;
}
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 0.2em 0.5em;
}
ul {
list-style-type: none;
}
button {
border-width: 1px;
}
.instruction {
background-color: #eee;
padding: 0.5em;
}
.button {
padding: 0.2em;
}
.red {
background-color: red;
color: white;
}
.yellow {
background-color: yellow;
color: black;
}
.blue {
background-color: blue;
color: white;
}
.green {
background-color: green;
color: white;
}
.white {
background-color: white;
border-color: black;
color: black;
}
.black {
background-color: black;
color: white;
}
.litIndicator {
color: white;
border: 1px outset red;
text-shadow: 0px 0px 3px yellow,0px 0px 3px yellow;
background: black;
padding: 0 3px 3px;
}
.litIndicator:before {
content: '\2022\a0';
}
.button.white {
border: 1px solid black;
}
section .active { /* ugh, specificity */
opacity: 1;
}
.inactive {
opacity: 0.3;
}
h2 {
cursor: pointer;
}
.collapsed {
padding: 0;
}
.collapsed * {
display: none;
}
.collapsed h2 {
display: block;
font-size: small;
margin: 0;
}
.jsResetSection {
display: block;
}
nav {
background-color: white;
border-left: 1px solid black;
border-top: 1px solid black;
position: fixed;
bottom: 0;
right: 0;
}
#navList {
line-height: 150%;
list-style-type: none;
margin: 0;
padding: 0.1em 0.5em;
}
#sectionButton {
line-height: 150%;
}
#sectionButton div {
margin-bottom: 1em;
}
#sectionButton .buttonWhite {
border-style: solid;
border-width: 1px;
}
#sectionKeypads ul {
display: inline-block;
list-style-type: none;
margin-right: 2em;
padding-left: 0;
}
#sectionKeypads li {
border: 1px solid black;
border-bottom: 0;
cursor: pointer;
line-height: 0;
}
#sectionKeypads li:last-child {
border-bottom: 1px solid black;
}
#sectionKeypads .selected {
background-color: #ff6;
}
#sectionKeypads ul[data-count='4'] .selected {
background-color: lightgreen;
}
#simonInputs {
float: left;
margin-right: 5em;
}
.collapsed #simonBoard {
display: none;
}
#simonBoard {
display: inline-block;
padding-bottom: 40px; /* Compensate for height increase as a result of rotation */
position: relative;
transform: rotate(45deg);
}
#simonBoard > div > div {
border: 2px solid black;
display: inline-block;
height: 64px;
width: 64px;
}
#simonBoard > .simonRow:first-child > div {
border-top-width: 4px;
}
#simonBoard > .simonRow:first-child + div > div {
border-bottom-width: 4px;
}
#simonBoard > .simonRow > div:first-child {
border-left-width: 4px;
}
#simonBoard > .simonRow > div:last-child {
border-right-width: 4px;
}
.simonRed {
background: radial-gradient(#fb9a9a, #fc7373, red);
}
.simonYellow {
background: radial-gradient(#fbfb9a, #fcfc73, yellow);
}
.simonBlue {
background: radial-gradient(#9a9afb, #7373fc, blue);
}
.simonGreen {
background: radial-gradient(#98c998, #72b772, green);
}
.arrow {
background-color: black;
height: 10px;
width: 50px;
opacity: 0;
position: absolute;
}
.arrow::after {
content: '';
border-top: 10px solid transparent;
border-left: 20px solid black;
border-bottom: 10px solid transparent;
height: 0;
width: 0;
margin-left: 50px;
position: absolute;
top: -5px;
}
#arrowRB {
top: 70px;
left: 10px;
transform: rotate(-90deg);
}
#arrowBR {
top: 60px;
left: 10px;
transform: rotate(90deg);
}
#arrowBY {
top: 30px;
left: 45px;
}
#arrowYB {
top: 30px;
left: 45px;
transform: rotate(180deg);
}
#arrowYG {
top: 60px;
left: 80px;
transform: rotate(90deg);
}
#arrowGY {
top: 70px;
left: 80px;
transform: rotate(-90deg);
}
#arrowGR {
top: 100px;
left: 45px;
transform: rotate(180deg);
}
#arrowRG {
top: 100px;
left: 45px;
}
#arrowRY {
top: 66px;
left: 44px;
transform: rotate(-45deg);
}
#arrowYR {
top: 66px;
left: 44px;
transform: rotate(135deg);
}
#arrowBG {
top: 64px;
left: 44px;
transform: rotate(45deg);
}
#arrowGB {
top: 64px;
left: 44px;
transform: rotate(-135deg);
}
#sectionWof {
white-space: nowrap;
}
#sectionWof dl, #sectionWof table {
display: inline-block;
margin-bottom: 1em;
}
#sectionWof.collapsed dl, #sectionWof.collapsed table {
display: none;
}
#sectionWof dl {
margin-right: 4em;
}
#sectionWof dt {
background-color: black;
clear: left;
color: white;
margin-right: 1em;
text-align: center;
width: 6em;
}
#sectionWof dd {
margin-bottom: 0.4em;
margin-left: 0;
}
#sectionWof dt, #sectionWof dd {
display: inline-block;
float: left;
}
#sectionWof dt.inactive + dd {
opacity: 0;
}
#sectionWof table {
margin-left: 0.5em;
}
#sectionWof th {
border: 1px solid black;
}
#sectionMemory table {
margin-top: 1em;
}
#sectionMemory td {
text-align: right;
}
#sectionMemory input {
text-align: center;
width: 5em;
}
#sectionMorse table {
float: left;
margin-bottom: 1em;
margin-right: 1em;
}
#sectionSequence button {
cursor: pointer;
width: 2em;
}
#sequenceOptions {
padding-left: 0;
width: 9.5em;
}
#sequenceOptions li {
display: inline-block;
}
#sequenceInstruction {
list-style-type: decimal;
}
#sequenceInstruction button {
margin-right: 0.2em;
}
#sectionVenn2 td {
height: 1.5em;
width: 1em;
}
+17
View File
@@ -0,0 +1,17 @@
import React from 'react';
import './App.css';
import WiresModule from "./components/WiresModule";
function App() {
return (
<div className="App">
<header>
<h1>Keep Talking and Nobody Explodes</h1>
</header>
<WiresModule id='sectionWires' />
</div>
);
}
export default App;
+9
View File
@@ -0,0 +1,9 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
+38
View File
@@ -0,0 +1,38 @@
import PropTypes from "prop-types";
import React, {Component} from "react";
class KtaneModule extends Component {
constructor(props) {
super(props);
this.resetState();
}
getTitle() {
throw new Error("getTitle() not implemented.");
}
mainRender() {
throw new Error("mainRender() not implemented.");
}
render() {
return (
<section id={this.props.id}>
<h2>{this.getTitle()}</h2>
{this.mainRender()}
</section>
);
}
resetState() {
throw new Error("mainRender() not implemented.");
}
}
KtaneModule.propTypes = {
id: PropTypes.string
};
export default KtaneModule;
+194
View File
@@ -0,0 +1,194 @@
import KtaneModule from "./KtaneModule";
import React from "react";
import "../css/WiresModule.css";
export default class WiresModule extends KtaneModule {
constructor(props) {
super(props);
this.addWire = this.addWire.bind(this);
this.deleteWires = this.deleteWires.bind(this);
this.classNameEven = "even";
this.classNameOdd = "odd";
this.colourRed = "red";
this.colourYellow = "yellow";
this.colourBlue = "blue";
this.colourWhite = "white";
this.colourBlack = "black";
this.allColours = [this.colourRed, this.colourYellow, this.colourBlue, this.colourWhite, this.colourBlack];
}
addWire(event) {
const colour = event.target.dataset.colour;
this.setState(state => {
state.counts[colour]++;
return {
counts: state.counts,
wires: this.computeWiresToCut(state.counts, [...state.wires, {
colour,
cutFlags: [],
shouldCut: false
}])
};
});
}
computeWiresToCut(counts, wires) {
this.resetWiresToCut(wires);
const lastColour = wires.slice(-1).colour;
switch (wires.length) {
case 3: {
if (!counts.red) {
this.flagWireForCutting(wires, 2);
} else if (lastColour === this.colourWhite) {
this.flagWireForCutting(wires, wires.length);
} else if (counts.blue > 1) {
this.flagWireForCutting(wires, this.getLastIndexOfColour(wires, this.colourBlue));
} else {
this.flagWireForCutting(wires, wires.length);
}
break;
}
case 4: {
const isOddPossible = counts.red > 1;
if (isOddPossible) {
this.flagWireForCutting(wires, this.getLastIndexOfColour(wires, this.colourRed), this.classNameOdd);
}
if ((lastColour === this.colourYellow && counts.red) || counts.blue === 1) {
this.flagWireForCutting(wires, 1, isOddPossible ? this.classNameEven : null);
} else if (counts.yellow > 1) {
this.flagWireForCutting(wires, wires.length, isOddPossible ? this.classNameEven : null);
} else {
this.flagWireForCutting(wires, 2, isOddPossible ? this.classNameEven : null);
}
break;
}
case 5: {
const isOddPossible = lastColour === 'black';
if (isOddPossible) {
this.flagWireForCutting(wires, 4, this.classNameOdd);
}
if (counts.red === 1 && counts.yellow > 1) {
this.flagWireForCutting(wires, 1, isOddPossible ? this.classNameEven : null);
} else if (!counts.black) {
this.flagWireForCutting(wires, 2, isOddPossible ? this.classNameEven : null);
} else {
this.flagWireForCutting(wires, 1, isOddPossible ? this.classNameEven : null);
}
break;
}
case 6: {
const isOddPossible = !counts.yellow;
if (isOddPossible) {
this.flagWireForCutting(wires, 3, this.classNameOdd);
}
if (counts.yellow === 1 && counts.white > 1) {
this.flagWireForCutting(wires, 4, isOddPossible ? this.classNameEven : null);
} else if (!counts.red) {
this.flagWireForCutting(wires, wires.length, isOddPossible ? this.classNameEven : null);
} else {
this.flagWireForCutting(wires, 4, isOddPossible ? this.classNameEven : null);
}
break;
}
default: {
break;
}
}
return wires;
}
deleteWires(event) {
const wireIndex = parseInt(event.target.dataset.index, 10);
this.setState(state => {
state.wires.splice(wireIndex).forEach(wire => {
state.counts[wire.colour]--;
});
return {
counts: state.counts,
wires: this.computeWiresToCut(state.counts, state.wires)
};
});
}
flagWireForCutting(wires, oneIndex, extraFlag) {
const zeroIndex = oneIndex - 1;
wires[zeroIndex].shouldCut = true;
if (extraFlag) {
wires[zeroIndex].cutFlags.push(extraFlag);
}
}
getLastIndexOfColour(wires, colour) {
for (let i = wires.length - 1; i >= 0; i--) {
if (wires[i].colour === colour) {
return i + 1;
}
}
return -1;
}
getTitle() {
return "Wires";
}
mainRender() {
return (
<>
<ul>
{
this.allColours.map(colour => (
<li key={`option_${colour}`}>
<button className={`button ${colour}`} data-colour={colour} onClick={this.addWire} />
</li>
))
}
</ul>
<ul id="wireList">
{
this.state.wires.map((wire, index) => (
<li className={`${wire.shouldCut ? "wireToCut" : ""} ${wire.cutFlags.join(" ")}`} key={index}>
<button className={`button ${wire.colour}`} data-index={index} onClick={this.deleteWires} />
</li>
))
}
</ul>
</>
)
}
resetState() {
this.state = {
// @TODO Convert this.allColours to a constant that is available here, i.e., before the constructor's super call
counts: ["red", "yellow", "blue", "white", "black"].reduce((counts, colour) => {
counts[colour] = 0;
return counts;
}, {}),
wires: []
};
}
resetWiresToCut(wires) {
wires.forEach(wire => {
wire.cutFlags = [];
wire.shouldCut = false;
});
}
}
+24
View File
@@ -0,0 +1,24 @@
#sectionWires button {
border-color: black;
cursor: pointer;
width: 2em;
height: 2em;
}
#wireOptions li {
display: inline-block;
}
#wireList {
list-style-type: decimal;
}
.wireToCut:after {
color: green;
}
.wireToCut:after, .wireToCut.odd.even:after {
content: '\27fd';
}
.wireToCut.odd:after {
content: '\27fd\a0 odd';
}
.wireToCut.even:after {
content: '\27fd\a0 even';
}
+13
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;
}
+12
View File
@@ -0,0 +1,12 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, 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();
+135
View File
@@ -0,0 +1,135 @@
// 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();
});
}
}