Use TypeScript (#99)

Co-authored-by: Ian C. Anderson <ian@iancanderson.com>
This commit is contained in:
Katherine Peterson
2022-01-26 20:44:10 -08:00
committed by GitHub
parent b5fc1de3bf
commit 6e54f867aa
15 changed files with 17055 additions and 98 deletions

3
images.d.ts vendored Normal file
View File

@@ -0,0 +1,3 @@
declare module '*.svg'
declare module '*.png'
declare module '*.jpg'

16875
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -8,11 +8,17 @@
"@testing-library/jest-dom": "^5.16.1",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.4.0",
"@types/node": "^17.0.12",
"@types/react": "^17.0.38",
"@types/react-dom": "^17.0.11",
"@types/react-modal": "^3.13.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-modal": "^3.14.4",
"react-scripts": "5.0.0-next.58",
"tailwindcss-neumorphism": "^0.1.0",
"typescript": "^4.5.5",
"web-vitals": "^2.1.2"
},
"scripts": {

View File

@@ -2,14 +2,14 @@ import { letters, status } from './constants'
import { useEffect, useState } from 'react'
import { EndGameModal } from './components/EndGameModal'
import { ReactComponent as Info } from './data/Info.svg'
import { InfoModal } from './components/InfoModal'
import { Keyboard } from './components/Keyboard'
import { ReactComponent as Settings } from './data/Settings.svg'
import { SettingsModal } from './components/SettingsModal'
import answers from './data/answers'
import { useLocalStorage } from './hooks/useLocalStorage'
import words from './data/words'
import { ReactComponent as Info } from './data/Info.svg'
import { ReactComponent as Settings } from './data/Settings.svg'
const words = require('./data/words').default as { [key: string]: boolean }
const state = {
playing: 'playing',
@@ -28,8 +28,19 @@ const getRandomAnswer = () => {
return answers[randomIndex].toUpperCase()
}
type State = {
answer: () => string
gameState: string
board: string[][]
cellStatuses: string[][]
currentRow: number
currentCol: number
letterStatuses: () => { [key: string]: string }
submittedInvalidWord: boolean
}
function App() {
const initialStates = {
const initialStates: State = {
answer: () => getRandomAnswer(),
gameState: state.playing,
board: [
@@ -44,7 +55,7 @@ function App() {
currentRow: 0,
currentCol: 0,
letterStatuses: () => {
const letterStatuses = {}
const letterStatuses: { [key: string]: string } = {}
letters.forEach((letter) => {
letterStatuses[letter] = status.unguessed
})
@@ -82,12 +93,13 @@ function App() {
if (difficultyLevel === difficulty.easy) {
return 'Guess any 5 letters'
} else if (difficultyLevel === difficulty.hard) {
return 'Guess any valid word using all the hints you\'ve been given'
return "Guess any valid word using all the hints you've been given"
} else {
return 'Guess any valid word'
}
}
const [exactGuesses, setExactGuesses] = useLocalStorage('exact-guesses', {})
const eg: { [key: number]: string } = {}
const [exactGuesses, setExactGuesses] = useLocalStorage('exact-guesses', eg)
const openModal = () => setIsOpen(true)
const closeModal = () => setIsOpen(false)
@@ -97,7 +109,7 @@ function App() {
}
const [darkMode, setDarkMode] = useLocalStorage('dark-mode', false)
const toggleDarkMode = () => setDarkMode((prev) => !prev)
const toggleDarkMode = () => setDarkMode((prev: boolean) => !prev)
useEffect(() => {
if (gameState !== state.playing) {
@@ -107,7 +119,7 @@ function App() {
}
}, [gameState])
const getCellStyles = (rowNumber, colNumber, letter) => {
const getCellStyles = (rowNumber: number, colNumber: number, letter: string) => {
if (rowNumber === currentRow) {
if (letter) {
return `nm-inset-background dark:nm-inset-background-dark text-primary dark:text-primary-dark ${
@@ -129,9 +141,9 @@ function App() {
}
}
const addLetter = (letter) => {
const addLetter = (letter: string) => {
setSubmittedInvalidWord(false)
setBoard((prev) => {
setBoard((prev: string[][]) => {
if (currentCol > 4) {
return prev
}
@@ -140,14 +152,15 @@ function App() {
return newBoard
})
if (currentCol < 5) {
setCurrentCol((prev) => prev + 1)
setCurrentCol((prev: number) => prev + 1)
}
}
// returns an array with a boolean of if the word is valid and an error message if it is not
const isValidWord = (word) => {
const isValidWord = (word: string): [boolean] | [boolean, string] => {
if (word.length < 5) return [false, `please enter a 5 letter word`]
if (difficultyLevel === difficulty.easy) return [true]
debugger
if (!words[word.toLowerCase()]) return [false, `${word} is not a valid word. Please try again.`]
if (difficultyLevel === difficulty.normal) return [true]
const guessedLetters = Object.entries(letterStatuses).filter(([letter, letterStatus]) =>
@@ -155,7 +168,7 @@ function App() {
)
const yellowsUsed = guessedLetters.every(([letter, _]) => word.includes(letter))
const greensUsed = Object.entries(exactGuesses).every(
([position, letter]) => word[position] === letter
([position, letter]) => word[parseInt(position)] === letter
)
if (!yellowsUsed || !greensUsed)
return [false, `In hard mode, you must use all the hints you've been given.`]
@@ -164,10 +177,11 @@ function App() {
const onEnterPress = () => {
const word = board[currentRow].join('')
const [valid, err] = isValidWord(word)
const [valid, _err] = isValidWord(word)
if (!valid) {
console.log({ valid, _err })
setSubmittedInvalidWord(true)
// alert(err)
// alert(_err)
return
}
@@ -175,7 +189,7 @@ function App() {
updateCellStatuses(word, currentRow)
updateLetterStatuses(word)
setCurrentRow((prev) => prev + 1)
setCurrentRow((prev: number) => prev + 1)
setCurrentCol(0)
}
@@ -183,22 +197,22 @@ function App() {
setSubmittedInvalidWord(false)
if (currentCol === 0) return
setBoard((prev) => {
setBoard((prev: any) => {
const newBoard = [...prev]
newBoard[currentRow][currentCol - 1] = ''
return newBoard
})
setCurrentCol((prev) => prev - 1)
setCurrentCol((prev: number) => prev - 1)
}
const updateCellStatuses = (word, rowNumber) => {
const fixedLetters = {}
setCellStatuses((prev) => {
const updateCellStatuses = (word: string, rowNumber: number) => {
const fixedLetters: { [key: number]: string } = {}
setCellStatuses((prev: any) => {
const newCellStatuses = [...prev]
newCellStatuses[rowNumber] = [...prev[rowNumber]]
const wordLength = word.length
const answerLetters = answer.split('')
const answerLetters: string[] = answer.split('')
// set all to gray
for (let i = 0; i < wordLength; i++) {
@@ -224,11 +238,11 @@ function App() {
return newCellStatuses
})
setExactGuesses(prev => ({...prev, ...fixedLetters}))
setExactGuesses((prev: { [key: number]: string }) => ({ ...prev, ...fixedLetters }))
}
const isRowAllGreen = (row) => {
return row.every((cell) => cell === status.green)
const isRowAllGreen = (row: string[]) => {
return row.every((cell: string) => cell === status.green)
}
// every time cellStatuses updates, check if the game is won or lost
@@ -244,7 +258,7 @@ function App() {
var streak = currentStreak + 1
setCurrentStreak(streak)
setLongestStreak((prev) => (streak > prev ? streak : prev))
setLongestStreak((prev: number) => (streak > prev ? streak : prev))
} else if (gameState === state.playing && currentRow === 6) {
setGameState(state.lost)
setCurrentStreak(0)
@@ -259,8 +273,8 @@ function App() {
setLongestStreak,
])
const updateLetterStatuses = (word) => {
setLetterStatuses((prev) => {
const updateLetterStatuses = (word: string) => {
setLetterStatuses((prev: { [key: string]: string }) => {
const newLetterStatuses = { ...prev }
const wordLength = word.length
for (let i = 0; i < wordLength; i++) {
@@ -349,8 +363,8 @@ function App() {
<div className="flex items-center flex-col py-3 flex-1 justify-center relative">
<div className="relative">
<div className="grid grid-cols-5 grid-flow-row gap-4">
{board.map((row, rowNumber) =>
row.map((letter, colNumber) => (
{board.map((row: string[], rowNumber: number) =>
row.map((letter: string, colNumber: number) => (
<span
key={colNumber}
className={`${getCellStyles(

View File

@@ -5,6 +5,19 @@ import Fail from '../data/Cross.png'
Modal.setAppElement('#root')
type Props = {
isOpen: boolean
handleClose: () => void
styles: any
darkMode: boolean
gameState: any
state: any
currentStreak: any
longestStreak: any
answer: any
playAgain: any
}
export const EndGameModal = ({
isOpen,
handleClose,
@@ -16,7 +29,7 @@ export const EndGameModal = ({
longestStreak,
answer,
playAgain,
}) => {
}: Props) => {
const PlayAgainButton = () => {
return (
<div className={darkMode ? 'dark' : ''}>
@@ -40,12 +53,12 @@ export const EndGameModal = ({
>
<div className={darkMode ? 'dark' : ''}>
<div className="h-full flex flex-col items-center justify-center max-w-[300px] mx-auto text-primary dark:text-primary-dark">
<button
className="absolute top-4 right-4 rounded-full nm-flat-background dark:nm-flat-background-dark text-primary dark:text-primary-dark p-1 w-6 h-6 sm:p-2 sm:h-8 sm:w-8 hover:nm-inset-background dark:hover:nm-inset-background-dark"
onClick={handleClose}
>
<Close />
</button>
<button
className="absolute top-4 right-4 rounded-full nm-flat-background dark:nm-flat-background-dark text-primary dark:text-primary-dark p-1 w-6 h-6 sm:p-2 sm:h-8 sm:w-8 hover:nm-inset-background dark:hover:nm-inset-background-dark"
onClick={handleClose}
>
<Close />
</button>
{gameState === state.won && (
<>
<img src={Success} alt="success" height="auto" width="auto" />

View File

@@ -1,10 +1,17 @@
import Modal from 'react-modal'
import { ReactComponent as Github } from '../data/Github.svg'
import { ReactComponent as Close } from '../data/Close.svg'
import Modal from 'react-modal'
Modal.setAppElement('#root')
export const InfoModal = ({ isOpen, handleClose, darkMode, styles }) => (
type Props = {
isOpen: boolean
handleClose: () => void
darkMode: boolean
styles: any
}
export const InfoModal = ({ isOpen, handleClose, darkMode, styles }: Props) => (
<Modal isOpen={isOpen} onRequestClose={handleClose} style={styles} contentLabel="Game Info Modal">
<div className={`h-full ${darkMode ? 'dark' : ''}`}>
<button

View File

@@ -1,8 +1,22 @@
import { keyboardLetters, status, letters } from '../constants'
import { useEffect, useCallback } from 'react'
const Keyboard = ({ letterStatuses, addLetter, onEnterPress, onDeletePress, gameDisabled }) => {
const getKeyStyle = (letter) => {
type Props = {
letterStatuses: { [key: string]: string }
gameDisabled: boolean
onDeletePress: () => void
onEnterPress: () => void
addLetter: any
}
const Keyboard = ({
letterStatuses,
addLetter,
onEnterPress,
onDeletePress,
gameDisabled,
}: Props) => {
const getKeyStyle = (letter: string) => {
switch (letterStatuses[letter]) {
case status.green:
return 'bg-n-green text-gray-50'
@@ -15,7 +29,7 @@ const Keyboard = ({ letterStatuses, addLetter, onEnterPress, onDeletePress, game
}
}
const onKeyButtonPress = (letter) => {
const onKeyButtonPress = (letter: string) => {
letter = letter.toLowerCase()
window.dispatchEvent(
new KeyboardEvent('keydown', {

View File

@@ -1,12 +1,32 @@
import { RadioGroup, Switch } from '@headlessui/react'
import { ReactComponent as Close } from '../data/Close.svg'
import Modal from 'react-modal'
import { difficulty } from '../App'
import { ReactComponent as Close } from '../data/Close.svg'
Modal.setAppElement('#root')
export const SettingsModal = ({ isOpen, handleClose, styles, darkMode, toggleDarkMode, difficultyLevel, setDifficultyLevel, levelInstructions }) => {
type Props = {
isOpen: boolean
handleClose: () => void
styles: any
darkMode: boolean
toggleDarkMode: () => void
difficultyLevel: string
setDifficultyLevel: any
levelInstructions: string
}
export const SettingsModal = ({
isOpen,
handleClose,
styles,
darkMode,
toggleDarkMode,
difficultyLevel,
setDifficultyLevel,
levelInstructions,
}: Props) => {
return (
<Modal
isOpen={isOpen}
@@ -70,7 +90,7 @@ export const SettingsModal = ({ isOpen, handleClose, styles, darkMode, toggleDar
))}
</div>
</RadioGroup>
<p className="text-center w-10/12 mx-auto font-medium">{levelInstructions}</p>
<p className="text-center w-10/12 mx-auto font-medium">{levelInstructions}</p>
</div>
<div className="flex flex-col items-center">
<div className="mb-4">

View File

@@ -1,4 +1,4 @@
const words = {
const words: { [key: string]: boolean } = {
aahed: true,
aalii: true,
aargh: true,

View File

@@ -1,6 +1,6 @@
import { useState } from 'react'
export const useLocalStorage = (key, initialValue) => {
export const useLocalStorage = <Type,>(key: string, initialValue: Type): [Type, any] => {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key)
@@ -10,7 +10,7 @@ export const useLocalStorage = (key, initialValue) => {
return initialValue
}
})
const setValue = (value) => {
const setValue = (value: any) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value
setStoredValue(valueToStore)

View File

@@ -2,7 +2,7 @@ const defaultTheme = require('tailwindcss/defaultTheme')
module.exports = {
darkMode: 'class',
content: ['./src/**/*.{js,jsx}'],
content: ['./src/**/*.{js,jsx,ts,tsx}'],
theme: {
screens: {
xxs: '321px',

101
tsconfig.json Normal file
View File

@@ -0,0 +1,101 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
"jsx": "react-jsx" /* Specify what JSX code is generated. */,
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
/* Modules */
"module": "commonjs" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "resolveJsonModule": true, /* Enable importing .json files */
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
// "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}