repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
YourBrainEatsYou/adventofcode2021
src/challenges/day-13/challenge-25.ts
import Day13 from './day-13'; export default class Challenge25 extends Day13 { solve(): number { this.foldOrigami(this.instructions[0]); return this.origami.flat(1).reduce((a, b) => b ? a + 1 : a, 0); } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-10/challenge-19.ts
import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; const BRACKETS: { [key: string]: string } = { '(': ')', '[': ']', '{': '}', '<': '>', }; const POINTS: { [key: string]: number } = { ')': 3, ']': 57, '}': 1197, '>': 25137, }; export default class Challenge19 implements Challenge { readonly input: string[][] = new FileReader(10) .getFileAsArray() .filter((line) => line !== '') .map((line) => line.split('').filter((line) => line !== '')); getFirstIllegalCharacter(line: string[]): string | null { let closingStack: string[] = []; for (let brace of line) { if (BRACKETS.hasOwnProperty(brace)) { // is opening brace closingStack = [BRACKETS[brace], ...closingStack]; } else { // is closing, so the first element of the closingstack should match const predictedClosingItem = closingStack.shift(); if (predictedClosingItem !== brace) { return brace; } } } return null; } solve(): number { let illegalBrackets = []; for (let line of this.input) { const illegalBracket = this.getFirstIllegalCharacter(line); if (illegalBracket !== null) { illegalBrackets.push(illegalBracket); } } return illegalBrackets.map((bracket) => POINTS[bracket]).reduce((a, b) => a + b); } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-17/challenge-33.ts
import Day17 from './day-17'; export default class Challenge33 extends Day17 { solve(): number { return this.highestYCoordinateReached; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-04/day-04.ts
import { Challenge } from '../../utils/Challenge'; import { FileReader } from '../../utils'; export default abstract class Day04 implements Challenge { readonly numbers: Array<number> = []; readonly boards: Array<Array<Array<number>>> = []; boardsMarks: Array<Array<Array<boolean>>> = []; // track witch numbers were called private readonly input: Array<string> = new FileReader(4).getFileAsArray(); constructor() { // prepare input for (let index = 0; index < this.input.length; index += 1) { const line = this.input[index]; if (index === 0) { this.numbers = line.split(',').map((value) => parseInt(value, 10)); continue; } // its an empty line, so prepare next board if (line === '') { this.boards.push([]); this.boardsMarks.push([]); continue; } // add values to the current board const items: Array<number> = line.split(' ').filter((val) => val !== '').map((val) => parseInt(val, 10)); if (items.length) { this.boards[this.boards.length - 1].push(items); this.boardsMarks[this.boards.length - 1].push(Array(items.length).fill(false)); } } if (this.boards[this.boards.length - 1].length === 0) { this.boards.splice(this.boards.length - 1, 1); this.boardsMarks.splice(this.boardsMarks.length - 1, 1); } } markNumberOnCards(calledNumber: number) { // search number in the boards for (let boardIndex = 0; boardIndex < this.boards.length; boardIndex += 1) { this.markNumberOnCard(calledNumber, boardIndex); } } markNumberOnCard(calledNumber: number, boardIndex: number) { const board = this.boards[boardIndex]; for (let rowIndex = 0; rowIndex < board.length; rowIndex += 1) { const row = board[rowIndex]; // check if the called number exists in row const numberIndex = row.indexOf(calledNumber); if (numberIndex !== -1) { // number was found, so mark it on the dots board this.boardsMarks[boardIndex][rowIndex][numberIndex] = true; } } } getWinningBoard() { for (let boardIndex = 0; boardIndex < this.boardsMarks.length; boardIndex += 1) { if (this.checkIfBoardHasWon(boardIndex)) { return boardIndex; } } return null; } checkIfBoardHasWon(boardIndex: number): boolean { const board = this.boardsMarks[boardIndex]; // check Rows (easy part) & prepare cols Array for (let rowIndex = 0; rowIndex < board.length; rowIndex += 1) { const row = board[rowIndex]; // check row if (row.filter((value) => value === false).length === 0) { // found winning board return true; } // check colums with the same rowIndex const col: Array<boolean> = []; for (let colIndex = 0; colIndex < row.length; colIndex += 1) { col.push(board[colIndex][rowIndex]); } if (col.filter((value) => value === false).length === 0) { // found winning board return true; } } return false; } addUnmarkedNumbers(boardIndex: number) { let sum: number = 0; const board = this.boards[boardIndex]; const markings = this.boardsMarks[boardIndex]; for (let rowIndex = 0; rowIndex < markings.length; rowIndex += 1) { const row = markings[rowIndex]; for (let colIndex = 0; colIndex < row.length; colIndex += 1) { const col = row[colIndex]; if (col === false) { sum += board[rowIndex][colIndex]; } } } return sum; } abstract solve(): number; }
YourBrainEatsYou/adventofcode2021
src/challenges/day-14/challenge-27.ts
import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; export default class Challenge27 implements Challenge { private readonly input: string[] = new FileReader(14).getFileAsArray().filter((line) => line !== ''); private template: string[] = []; private insertionRules: { [key: string]: string } = {}; constructor() { for (let line of this.input) { if (line.includes(' -> ')) { // line is rule let rule: [string, string] = line.split(' -> ') as [string, string]; this.insertionRules[rule[0]] = rule[1]; } else { // line is template this.template = line.split(''); } } } calculateElements(elements: string[]): number { const counts = Object.values(elements.reduce((acc: { [key: string]: number }, value: string) => ({ ...acc, [value]: (acc[value] || 0) + 1, }), {})).sort((a, b) => a - b); const most = counts.pop(); const least = counts.shift(); return most - least; } solve(): number { const numOfSteps = 10; for (let step = 0; step < numOfSteps; step += 1) { this.template = this.template.reduce((prev: string[], current: string) => { if (prev.length > 0) { const ruleToFind = prev[prev.length - 1] + current; if (this.insertionRules.hasOwnProperty(ruleToFind)) { prev.push(this.insertionRules[ruleToFind]); } } prev.push(current); return prev; }, []); } return this.calculateElements(this.template); } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-09/challenge-18.ts
import Day09 from './day-09'; import Point from './interfaces/point'; export default class Challenge18 extends Day09 { pointToId(point: Point): string { return point.x.toString() + '-' + point.y.toString(); } idToPoint(id: string): Point { const idParts = id.split('-'); return { x: parseInt(idParts[0]), y: parseInt(idParts[1]), } as Point; } calculateBasinSize(point: Point): number { let sourcePoints: Array<Point> = [point]; let pointsWereSourcePoint: Array<string> = []; while (sourcePoints.length > 0) { const sourcePointsSnapshot = [...sourcePoints]; const newSourcePoints: Array<string> = []; for (let sourcePoint of sourcePointsSnapshot) { pointsWereSourcePoint.push(this.pointToId(sourcePoint)); // add new SourcePoints const up = this.up(sourcePoint.x, sourcePoint.y) !== null ? this.up(sourcePoint.x, sourcePoint.y) : 10; const down = this.down(sourcePoint.x, sourcePoint.y) !== null ? this.down(sourcePoint.x, sourcePoint.y) : 10; const left = this.left(sourcePoint.x, sourcePoint.y) !== null ? this.left(sourcePoint.x, sourcePoint.y) : 10; const right = this.right(sourcePoint.x, sourcePoint.y) !== null ? this.right(sourcePoint.x, sourcePoint.y) : 10; // up if (up < 9) { const upPoint = { x: sourcePoint.x, y: sourcePoint.y - 1 }; if (!pointsWereSourcePoint.includes(this.pointToId(upPoint))) { newSourcePoints.push(this.pointToId(upPoint)); } } // down if (down < 9) { const downPoint = { x: sourcePoint.x, y: sourcePoint.y + 1 }; if (!pointsWereSourcePoint.includes(this.pointToId(downPoint))) { newSourcePoints.push(this.pointToId(downPoint)); } } // left if (left < 9) { const leftPoint = { x: sourcePoint.x - 1, y: sourcePoint.y }; if (!pointsWereSourcePoint.includes(this.pointToId(leftPoint))) { newSourcePoints.push(this.pointToId(leftPoint)); } } // right if (right < 9) { const rightPoint = { x: sourcePoint.x + 1, y: sourcePoint.y }; if (!pointsWereSourcePoint.includes(this.pointToId(rightPoint))) { newSourcePoints.push(this.pointToId(rightPoint)); } } } sourcePoints = Array.from(new Set(newSourcePoints)).map((id) => this.idToPoint(id)); } return pointsWereSourcePoint.length; } solve(): number { const deepestPoints = this.getDeepestPointsCoords(); const basinSizes = []; for (let point of deepestPoints) { basinSizes.push(this.calculateBasinSize(point)); } basinSizes.sort((a, b) => a - b).reverse(); return basinSizes[0] * basinSizes[1] * basinSizes[2]; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-03/index.ts
<reponame>YourBrainEatsYou/adventofcode2021 import Challenge05 from './challenge-05'; import Challenge06 from './challenge-06'; export { Challenge05, Challenge06, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-16/challenge-31.ts
<filename>src/challenges/day-16/challenge-31.ts import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; export default class Challenge31 implements Challenge { readonly input: string = new FileReader(16) .getFileAsArray() .filter((line) => line !== '') .map((line) => line.split('') .map((char) => (parseInt(char, 16)).toString(2).padStart(4, '0')) .join(''), ) .shift(); transmission: string = this.input; versionTotal = 0; getPacketVersion(): number { return parseInt(this.transmission.slice(0, 3), 2); } getPacketType(): number { return parseInt(this.transmission.slice(3, 6), 2); } removeIdAndType() { this.transmission = this.transmission.slice(6); } parseLiteral(): number { let literal = ''; // remove packageVersion and Type this.removeIdAndType(); let hasMore = true; while (hasMore) { const literalByte = parseInt(this.transmission.slice(0, 5), 2); this.transmission = this.transmission.slice(5); literal += ((literalByte & 15)).toString(2).padStart(4, '0'); hasMore = !!(literalByte & 16); } return parseInt(literal, 2); } parseOperator() { this.removeIdAndType(); const length = this.transmission.slice(0, 1) === '0' ? 15 : 11; this.transmission = this.transmission.slice(1); this.transmission = this.transmission.slice(length); } parseNextPackage() { let packageVersion = this.getPacketVersion(); let packageType = this.getPacketType(); this.versionTotal += packageVersion; switch (packageType) { case 4: this.parseLiteral(); break; default: this.parseOperator(); break; } } solve(): number { while (this.transmission.includes('1')) { this.parseNextPackage(); } return this.versionTotal; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-13/index.ts
import Challenge25 from './challenge-25'; import Challenge26 from './challenge-26'; export { Challenge25, Challenge26, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-11/day-11.ts
import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; export default abstract class Day11 implements Challenge { input: number[][] = new FileReader(11) .getFileAsArray() .filter((line) => line !== '') .map((line) => line.split('') .filter((line) => line !== '') .map((item) => parseInt(item)), ); increaseAdjacentOctopuses(x: number, y: number) { const adjacentMap = [ [-1, -1], // top left [0, -1], // top [1, -1], // top right [-1, 0], // mid left [0, 0], // mid [1, 0], // mid right [-1, 1], // bottom left [0, 1], // bottom [1, 1], // bottom right ]; adjacentMap.forEach((modifier) => { if (typeof this.input[y + modifier[1]] !== 'undefined' && typeof this.input[y + modifier[1]][x + modifier[0]] !== 'undefined') { if (this.input[y + modifier[1]][x + modifier[0]] !== -1) { // has not flashed in this step this.input[y + modifier[1]][x + modifier[0]] += 1; } } }); } step(): number { let flashesInStep = 0; // increase all energy levels this.input.forEach((row, yIndex) => { row.forEach(((energyLevel, xIndex) => { this.input[yIndex][xIndex] = energyLevel + 1; })); }); let hasFlashed = false; do { hasFlashed = false; this.input.forEach((row, yIndex) => { row.forEach((energyLevel, xIndex) => { if (energyLevel > 9) { // flash octopus and increase adjacents this.increaseAdjacentOctopuses(xIndex, yIndex); this.input[yIndex][xIndex] = -1; flashesInStep += 1; hasFlashed = true; } }); }); } while (hasFlashed); // reset -1 to 0 this.input.forEach((row, yIndex) => { row.forEach(((energyLevel, xIndex) => { if (this.input[yIndex][xIndex] === -1) { this.input[yIndex][xIndex] = 0; } })); }); return flashesInStep; } abstract solve(): number; }
YourBrainEatsYou/adventofcode2021
src/challenges/day-08/challenge-16.ts
import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; interface IO { input: string[], output: string[], } export default class Challenge15 implements Challenge { private readonly input: Array<IO> = new FileReader(8) .getFileAsArray() .filter((line) => line !== '') .map((line) => { const partsResult = line.split('|'); return { input: partsResult[0].split(' ') .filter((item) => item !== '') .map((item) => item.split('').sort().join('')) .sort((a, b) => a.length - b.length), output: partsResult[1].split(' ') .filter((item) => item !== '') .map((item) => item.split('').sort().join('')), } as IO; }); /** * Normal map: * * aaaa * b c * b c * dddd * e f * e f * gggg * * possible lengths / numbers per length * length: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | * numbers: | - | 1 | 7 | 4 | 2,3,5 | 0,6,9 | 8 | * * Easy numbers: 1, 7, 4, 8 * * then: * * Semi easy Numbers: * 3 => length == 5 & has to include 1 * 9 => length == 6 & has to include 4 * * then: * * Hard numbers: * 0 => length == 6 & has to include 7 * 5 => length == 5 & is included in 9 * * then: * * 2 => last man standing with length === 5 * 6 => last man standing with length === 6 */ getSevenSegmentMap(inputValuesToDecode: Array<string>): Array<string> { const sevenSegmentMap = Array(10).fill('') as Array<string>; const lengthOf5Unsolved = []; const lengthOf6Unsolved = []; // set the easy numbers and prepare the semi and hard numbers array for (let inputValue of inputValuesToDecode) { switch (inputValue.length) { case 2: // 1 sevenSegmentMap[1] = inputValue; break; case 3: // 7 sevenSegmentMap[7] = inputValue; break; case 4: // 4 sevenSegmentMap[4] = inputValue; break; case 5: // 2,3,5 // solve 3 => length == 5 & has to include 1 if (this.isXIncludedInY(sevenSegmentMap[1], inputValue)) { sevenSegmentMap[3] = inputValue; } else { lengthOf5Unsolved.push(inputValue); } break; case 6: // 0,6,9 // solve 9 => length == 6 & has to include 4 if (this.isXIncludedInY(sevenSegmentMap[4], inputValue)) { sevenSegmentMap[9] = inputValue; } else { lengthOf6Unsolved.push(inputValue); } break; case 7: // 8 sevenSegmentMap[8] = inputValue; break; } } // solve 5 => length == 5 & is included in 9 for (let item of lengthOf5Unsolved) { if (this.isXIncludedInY(item, sevenSegmentMap[9])) { sevenSegmentMap[5] = item; lengthOf5Unsolved.splice(lengthOf5Unsolved.indexOf(item), 1); break; } } // solve 0 => length == 6 & has to include 7 for (let item of lengthOf6Unsolved) { if (this.isXIncludedInY(sevenSegmentMap[7], item)) { sevenSegmentMap[0] = item; lengthOf6Unsolved.splice(lengthOf6Unsolved.indexOf(item), 1); break; } } // they should only be one sting in each array remaining // solve 2 => last man standing with length === 5 if (lengthOf5Unsolved.length === 1) { sevenSegmentMap[2] = lengthOf5Unsolved.shift(); } // solve 6 => last man standing with length === 6 if (lengthOf6Unsolved.length === 1) { sevenSegmentMap[6] = lengthOf6Unsolved.shift(); } return sevenSegmentMap; } isXIncludedInY(x: string, y: string): boolean { const xArray = x.split(''); const yArray = y.split(''); return xArray.filter((item) => !yArray.includes(item)).length === 0; } decryptOutput(sevenSegmentMap: Array<string>, input: Array<string>): number { let outputString = ''; for (let number of input) { let index = sevenSegmentMap.indexOf(number); if (index !== -1) { outputString += index.toString(); } else { console.error('Now something is broken!'); } } return parseInt(outputString, 10); } solve(): number { let sumOfTotalNumbers = 0; for (let io of this.input) { sumOfTotalNumbers += this.decryptOutput(this.getSevenSegmentMap(io.input), io.output); } return sumOfTotalNumbers; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-09/challenge-17.ts
<reponame>YourBrainEatsYou/adventofcode2021<filename>src/challenges/day-09/challenge-17.ts import Day09 from './day-09'; export default class Challenge17 extends Day09 { solve(): number { const deepestPoints = this.getDeepestPointsCoords(); let sumOfLowPoints = 0; for (let point of deepestPoints) { sumOfLowPoints += this.input[point.y][point.x] + 1; } return sumOfLowPoints; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-11/challenge-22.ts
<gh_stars>1-10 import Day11 from './day-11'; export default class Challenge22 extends Day11 { solve(): number { const targetFlashes = this.input.flat(2).length; let stepFlashes = 0; let stepCount = 0; while (targetFlashes != stepFlashes) { stepCount += 1; stepFlashes = this.step(); } return stepCount; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-12/challenge-24.ts
<gh_stars>1-10 import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; import { Cave } from './interfaces/Cave'; export default class Challenge24 implements Challenge { START = 'start'; END = 'end'; private readonly input: [string, string][] = new FileReader(12) .getFileAsArray() .filter((line) => line !== '') .map((line) => line.split('-').filter((line) => line !== '') as [string, string]); private caves: { ids: string[], entities: Cave[] } = { ids: [], entities: [], }; private possiblePaths: string[][] = []; constructor() { // create Caves const uniqueInput = [...Array.from(new Set(this.input.flat(2)))]; for (let index = 0; index < uniqueInput.length; index += 1) { let id = uniqueInput[index]; let uppercaseId = id.toUpperCase(); let cave: Cave = { id, isBig: (id === uppercaseId), isStart: (id === this.START), isEnd: (id === this.END), connections: [], nextCaveIndexToExplore: 0, }; this.caves.ids.push(id); this.caves.entities.push(cave); } // add Cave Connections for (let index = 0; index < this.input.length; index += 1) { let [cave1, cave2] = this.input[index]; this.caves.entities[this.caves.ids.indexOf(cave1)].connections.push(cave2); this.caves.entities[this.caves.ids.indexOf(cave2)].connections.push(cave1); } } getDuplicates(array: string[]) { return array.filter((e, i, a) => a.indexOf(e) !== i); } canVisitCave(cave: Cave, exploredCaves: string[]) { if (!cave.isBig) { if (!exploredCaves.includes(cave.id)) { // is cave was never visited, visit the cave return true; } // the case was visited before, so check how many duplicates there are const smallCaves = exploredCaves.filter((cave) => cave.toLowerCase() === cave); if (this.getDuplicates(smallCaves).length > 0) { return false; } } return true; } getChildRoutes(cave: Cave, trace: string[]) { trace = [...trace, cave.id]; if (cave.id !== this.END) { const filteredConnections = cave.connections.filter((id) => id !== this.START); for (let id of filteredConnections) { const nextCave = this.caves.entities[this.caves.ids.indexOf(id)]; if (this.canVisitCave(nextCave, trace)) { this.getChildRoutes(nextCave, trace); } } } else { this.possiblePaths.push(trace); } } solve(): number { this.getChildRoutes(this.caves.entities[this.caves.ids.indexOf(this.START)], []); return this.possiblePaths.length; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-06/index.ts
import Challenge11 from './challenge-11'; import Challenge12 from './challenge-12'; export { Challenge11, Challenge12, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-11/index.ts
import Challenge21 from './challenge-21'; import Challenge22 from './challenge-22'; export { Challenge21, Challenge22, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-02/index.ts
<gh_stars>1-10 import Challenge03 from './challenge-03'; import Challenge04 from './challenge-04'; export { Challenge03, Challenge04, };
YourBrainEatsYou/adventofcode2021
src/index.ts
<reponame>YourBrainEatsYou/adventofcode2021<filename>src/index.ts<gh_stars>1-10 import { performance } from 'perf_hooks'; import { CliColors } from './utils/CliColors'; const selectedChallenge: string = (process.argv[2] || '1').padStart(2, '0'); const selectedChallengeInt: number = parseInt(selectedChallenge, 10); const dayInt = (selectedChallengeInt % 2 === 0) ? selectedChallengeInt / 2 : (selectedChallengeInt + 1) / 2; const paddedDay = dayInt.toString(10).padStart(2, '0'); import(`./challenges/day-${paddedDay}/challenge-${selectedChallenge}`).then(m => { const startTime = performance.now(); const answer = new m.default().solve(); const endTime = performance.now(); console.log(`${CliColors.FgCyan}The answer to challenge`, CliColors.FgMagenta + selectedChallenge, `${CliColors.FgCyan}is: `, CliColors.FgBlack + CliColors.BgGreen + ' ' + answer, `${CliColors.Reset + CliColors.FgBlue} and took`, `${CliColors.FgYellow}${(endTime - startTime).toFixed(3)}ms`, `${CliColors.FgBlue}to compute`, CliColors.Reset, ); }).catch((e) => { console.log(e); console.log(CliColors.FgRed + 'You have to write some code first!' + CliColors.Reset); });
YourBrainEatsYou/adventofcode2021
src/challenges/day-15/index.ts
import Challenge29 from './challenge-29'; import Challenge30 from './challenge-30'; export { Challenge29, Challenge30, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-01/challenge-01.ts
import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; export default class Challenge01 implements Challenge { private readonly input: number[] = new FileReader(1) .getFileAsArray() .filter((val) => val !== '') .map((value) => parseInt(value)); solve(): number { let countLargerMeasurements: number = 0; let lastMeasurement: number | null = null; for (let measurement of this.input) { if (lastMeasurement !== null && measurement > lastMeasurement) { countLargerMeasurements += 1; } lastMeasurement = measurement; } return countLargerMeasurements; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-14/index.ts
import Challenge27 from './challenge-27'; import Challenge28 from './challenge-28'; export { Challenge27, Challenge28, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-03/challenge-06.ts
<gh_stars>1-10 import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; export default class Challenge06 implements Challenge { private input: number[][] = new FileReader(3) .getFileAsArray() .filter((value) => value !== '') .map((value) => value.split('').map((val) => parseInt(val))); solve(): number { let oxygenGeneratorRatingArray = [...this.input]; let co2ScrubberRatingArray = [...this.input]; for (let position = 0; position < this.input[0].length; position += 1) { let oxyPositionCount = 0; let co2PositionCount = 0; if (oxygenGeneratorRatingArray.length > 1) { for (let item of oxygenGeneratorRatingArray) { oxyPositionCount += item[position]; } oxygenGeneratorRatingArray = oxygenGeneratorRatingArray.filter((item) => item[position] === +(oxyPositionCount >= (oxygenGeneratorRatingArray.length / 2))); } if (co2ScrubberRatingArray.length > 1) { for (let item of co2ScrubberRatingArray) { co2PositionCount += item[position]; } co2ScrubberRatingArray = co2ScrubberRatingArray.filter((item) => item[position] === +(co2PositionCount < (co2ScrubberRatingArray.length / 2))); } } const oxygenGeneratorRating = parseInt(oxygenGeneratorRatingArray[0].join(''), 2); const co2ScrubberRating = parseInt(co2ScrubberRatingArray[0].join(''), 2); return oxygenGeneratorRating * co2ScrubberRating; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-09/index.ts
<filename>src/challenges/day-09/index.ts import Challenge17 from './challenge-17'; import Challenge18 from './challenge-18'; export { Challenge17, Challenge18, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-04/challenge-08.ts
<filename>src/challenges/day-04/challenge-08.ts import Day04 from './day-04'; export default class Challenge08 extends Day04 { solve(): number { let boardWinningOrder: Array<number> = []; let boardsWithNoWin = this.boards.map(((value, index) => index)); let lastCalledNumber: number | null; // call the numbers for (let call of this.numbers) { const preNoWinBoards = [...boardsWithNoWin]; for (let noWinIndex = 0; noWinIndex < preNoWinBoards.length; noWinIndex += 1) { const boardIndex = preNoWinBoards[noWinIndex]; this.markNumberOnCard(call, boardIndex); if (this.checkIfBoardHasWon(boardIndex) && boardWinningOrder.indexOf(boardIndex) === -1) { boardWinningOrder.push(boardIndex); boardsWithNoWin.splice(boardsWithNoWin.indexOf(boardIndex), 1); } } lastCalledNumber = call; //check if all boards has won if (boardWinningOrder.length === this.boards.length) { // all boards has won, so get out of here. break; } } return this.addUnmarkedNumbers(boardWinningOrder[boardWinningOrder.length - 1]) * lastCalledNumber; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-13/day-13.ts
<gh_stars>1-10 import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; import { Instruction } from './interfaces/Instruction'; export default abstract class Day13 implements Challenge { origami: boolean[][] = []; readonly instructions: Instruction[] = []; private readonly input: string[] = new FileReader(13).getFileAsArray(); private points: number[][] = []; private maxY = 0; private maxX = 0; constructor() { // prepare origami and instructions for (let line of this.input) { line = line.replace('fold along ', ''); let point = line.split(','); let instruction = line.split('='); if (point.length == 2) { let coords = point.map((coord) => parseInt(coord, 10)); // console.log(coords); this.maxX = coords[0] > this.maxX ? coords[0] : this.maxX; this.maxY = coords[1] > this.maxY ? coords[1] : this.maxY; this.points.push(coords); } if (instruction.length == 2) { this.instructions.push({ direction: instruction[0], position: parseInt(instruction[1]), } as Instruction); } } // prepare origami for (let yIndex = 0; yIndex <= this.maxY; yIndex++) { this.origami.push(Array(this.maxX + 1).fill(false)); } // fill origami for (let point of this.points) { this.origami[point[1]][point[0]] = true; } } displayOrigami(origami: boolean[][], [set, unset]: [string, string] = ['#', '.']) { console.log(origami.map((line) => line.map((val) => val ? set : unset).join('')).join('\n')); } foldOrigami(instruction: Instruction) { switch (instruction.direction) { case 'x': // fold left this.foldLeft(instruction.position); break; case 'y': // fold up this.foldUp(instruction.position); break; } } foldLeft(atPosition: number) { let leftPart = this.origami.map((line) => line.slice(0, atPosition)); let rightPart = this.origami.map((line) => line.slice(atPosition + 1, line.length).reverse()); this.origami = this.execArrayCombination(leftPart, rightPart); } foldUp(atPosition: number) { let upperPart = this.origami.slice(0, atPosition); let lowerPart = this.origami.slice(atPosition + 1, this.origami.length).reverse(); this.origami = this.execArrayCombination(upperPart, lowerPart); } execArrayCombination(array1: boolean[][], array2: boolean[][]) { const resultArray = []; for (let yIndex = 0; yIndex < array1.length; yIndex += 1) { const row = array1[yIndex]; resultArray.push(Array(row.length).fill(false)); for (let xIndex = 0; xIndex < row.length; xIndex += 1) { const value1 = array1[yIndex][xIndex]; const value2 = array2[yIndex][xIndex]; if (value1 || value2) { resultArray[yIndex][xIndex] = true; } } } return resultArray; } abstract solve(): number; }
YourBrainEatsYou/adventofcode2021
src/challenges/day-11/challenge-21.ts
import Day11 from './day-11'; export default class Challenge21 extends Day11 { solve(): number { let totalFlashes = 0; const steps = 100; for (let iteration = 1; iteration <= steps; iteration += 1) { totalFlashes += this.step(); } return totalFlashes; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-12/interfaces/Cave.ts
<reponame>YourBrainEatsYou/adventofcode2021 export interface Cave { id: string, isBig: boolean, isStart: boolean, isEnd: boolean, connections: string[], nextCaveIndexToExplore: number, }
YourBrainEatsYou/adventofcode2021
src/challenges/day-17/challenge-34.ts
<reponame>YourBrainEatsYou/adventofcode2021 import Day17 from './day-17'; export default class Challenge34 extends Day17 { solve(): number { return this.possibleVelocities.length; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-08/index.ts
import Challenge15 from './challenge-15'; import Challenge16 from './challenge-16'; export { Challenge15, Challenge16, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-07/challenge-13.ts
import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; export default class Challenge13 implements Challenge { private readonly input: number[] = new FileReader(7, 'input.txt') .getFileAsArray() .filter((line) => line !== '') .map((line) => line.split(',').map((num) => parseInt(num, 10))) .flat(1) .sort((a, b) => a - b); solve(): number { let leastFuelConsumption = null; for (let index = 0; index <= this.input[this.input.length - 1]; index += 1) { let fuelForCurrentIndex = 0; for (let crab of this.input) { fuelForCurrentIndex += Math.abs(index - crab); } if (fuelForCurrentIndex < leastFuelConsumption || leastFuelConsumption === null) { leastFuelConsumption = fuelForCurrentIndex; } } return leastFuelConsumption; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-04/challenge-07.ts
import Day04 from './day-04'; export default class Challenge07 extends Day04 { solve(): number { // call the numbers for (let call of this.numbers) { this.markNumberOnCards(call); let winningBoardIndex = this.getWinningBoard(); if (winningBoardIndex !== null) { return this.addUnmarkedNumbers(winningBoardIndex) * call; } } return null; } }
YourBrainEatsYou/adventofcode2021
src/utils/FileReader.ts
import * as fs from 'fs'; import * as path from 'path'; export class FileReader { private dayString = ''; private fileName = ''; constructor( day: number, fileName: string = 'input.txt', ) { this.dayString = day.toString(10).padStart(2, '0'); this.fileName = fileName; } getFileAsString(): string { return fs.readFileSync(path.resolve(path.join(__dirname, `../challenges/day-${this.dayString}/${this.fileName}`)), 'utf8'); } getFileAsArray(): string[] { return this.getFileAsString().split('\n'); } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-06/challenge-11.ts
import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; export default class Challenge11 implements Challenge { private readonly input: number[] = new FileReader(6, 'test-input.txt') .getFileAsArray() .filter((line) => line !== '') .map((line) => line.split(',').map((num) => parseInt(num, 10))) .flat(1); lanternfishPopulation = [...this.input]; tick() { let newPopulation = []; for (let fish of this.lanternfishPopulation) { if (fish === 0) { newPopulation.push(6); // reset Fish to 6 newPopulation.push(8); // spawn new Fish } else { fish += -1; // decrease timer newPopulation.push(fish); } } this.lanternfishPopulation = [...newPopulation]; } solve(): number { const days = 80; for (let day = 0; day < days; day += 1) { this.tick(); } return this.lanternfishPopulation.length; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-06/challenge-12.ts
import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; export default class Challenge12 implements Challenge { lanternfishPopulation = Array(9).fill(0); private readonly input: number[] = new FileReader(6, 'input.txt') .getFileAsArray() .filter((line) => line !== '') .map((line) => line.split(',').map((num) => parseInt(num, 10))) .flat(1); constructor() { // prepare initial population for (let fish of this.input) { this.lanternfishPopulation[fish] += 1; } } tick() { // rotate Array const fishesToReset = this.lanternfishPopulation.shift(); this.lanternfishPopulation[8] = 0; this.lanternfishPopulation[6] += fishesToReset; this.lanternfishPopulation[8] += fishesToReset; } solve(): number { const days = 256; for (let day = 0; day < days; day += 1) { this.tick(); } return this.lanternfishPopulation.reduce((prev, curr) => prev + curr); } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-04/index.ts
import Challenge07 from './challenge-07'; import Challenge08 from './challenge-08'; export { Challenge07, Challenge08, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-17/day-17.ts
<filename>src/challenges/day-17/day-17.ts import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; import { Coordinates, TargetArea, Velocity } from './interfaces/interfaces'; const regex = /x=([-0-9]+)[.]+([-0-9]+).+y=([-0-9]+)[.]+([-0-9]+)/g; export default abstract class Day17 implements Challenge { readonly input: TargetArea = new FileReader(17) .getFileAsArray() .filter((line) => line !== '') .map((line) => { let matches = regex.exec(line); if (matches[1] && matches[2] && matches[3] && matches[4]) { return { x: { from: parseInt(matches[1]), to: parseInt(matches[2]), }, y: { from: parseInt(matches[4]), to: parseInt(matches[3]), }, } as TargetArea; } }) .shift(); possibleVelocities: Velocity[] = []; highestYCoordinateReached: number = -Infinity; constructor() { this.bruteForceVelocities(); } private static step(currentCoordinates: Coordinates, currentVelocity: Velocity): { newCoordinates: Coordinates, newVelocity: Velocity } { const newCoordinates: Coordinates = { x: currentCoordinates.x + currentVelocity.x, y: currentCoordinates.y + currentVelocity.y, }; let velocityX = currentVelocity.x; if (velocityX > 0) { velocityX -= 1; } else if (velocityX < 0) { velocityX += 0; } const newVelocity: Velocity = { x: velocityX, y: currentVelocity.y - 1, }; return { newCoordinates, newVelocity }; } abstract solve(): number; private isInTargetArea({ x, y }: Coordinates): boolean { return ((this.input.x.from <= x && x <= this.input.x.to) && (this.input.y.from >= y && y >= this.input.y.to)); } private canReachTarget({ x, y }: Coordinates): boolean { return (x <= this.input.x.to) && (y >= this.input.y.to); } private bruteForceVelocities() { for (let y = -500; y < 500; y += 1) { for (let x = -500; x < 500; x += 1) { let probe: Coordinates = { x: 0, y: 0 }; let initialVelocity: Velocity = { x, y }; let velocity: Velocity = { x, y }; let highestOfVelocity = -Infinity; while (this.canReachTarget(probe)) { highestOfVelocity = Math.max(...[highestOfVelocity, probe.y]); if (this.isInTargetArea(probe)) { this.possibleVelocities.push(initialVelocity); this.highestYCoordinateReached = Math.max(...[this.highestYCoordinateReached, highestOfVelocity]); break; } let stepResult = Day17.step(probe, velocity); probe = stepResult.newCoordinates; velocity = stepResult.newVelocity; } } } } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-16/challenge-32.ts
import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; interface Pointer{ index: number; value: number; } export default class Challenge32 implements Challenge { readonly input: string = new FileReader(16) .getFileAsArray() .filter((line) => line !== '') .map((line) => line.split('') .map((char) => (parseInt(char, 16)).toString(2).padStart(4, '0')) .join(''), ) .shift(); parseNextPackage(index: number): Pointer { const packageType = parseInt(this.input.slice(index + 3, index += 6),2); if(packageType === 4){ // is Literal return this.parseLiteral(index); } else { // is Operator return this.parseOperator(index, packageType); } } parseLiteral(index: number): Pointer { let hasMore = true; let literal = ''; while (hasMore) { const literalByte = parseInt(this.input.slice(index, index += 5), 2); literal += ((literalByte & 15)).toString(2).padStart(4, '0'); hasMore = !!(literalByte & 16); } return { index, value: parseInt(literal, 2), } } parseOperator(index: number, packageType: number): Pointer { const lengthId: 11 | 15 = this.input.slice(index, index += 1) === '0' ? 15 : 11; const lengthCounter = parseInt(this.input.slice(index, index += lengthId), 2); const values = []; let value: number = 0; if(lengthId === 15){ const endIndex = index + lengthCounter; while (index < endIndex){ let { index: newIndex, value} = this.parseNextPackage(index); index = newIndex; values.push(value); } } else { while(values.length < lengthCounter){ let { index: newIndex, value} = this.parseNextPackage(index); index = newIndex; values.push(value); } } // parse Operations switch (packageType) { case 0: // sum value = values.reduce((a, b) => a + b, 0); break; case 1: // product value = values.reduce((a, b) => a * b, 1); break; case 2: // min value = Math.min(...values); break; case 3: // max value = Math.max(...values); break; case 5: // greater than > value = +(values[0] > values[1]); break; case 6: // less than < value = +(values[0] < values[1]); break; case 7: // equal = value = +(values[0] === values[1]); break; } return { index, value }; } solve(): number { return this.parseNextPackage(0).value; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-05/challenge-10.ts
import Day05 from './day-05'; export default class Challenge10 extends Day05 { solve(): number { for (let coords of this.input) { this.drawLine(coords[0], coords[1], false); } return this.countOverlaps(); } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-13/interfaces/Instruction.ts
<reponame>YourBrainEatsYou/adventofcode2021 type Direction = 'x' | 'y' export interface Instruction { direction: Direction, position: number, }
YourBrainEatsYou/adventofcode2021
src/challenges/day-16/index.ts
<filename>src/challenges/day-16/index.ts import Challenge31 from './challenge-31'; import Challenge32 from './challenge-32'; export { Challenge31, Challenge32, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-17/index.ts
<reponame>YourBrainEatsYou/adventofcode2021 import Challenge33 from './challenge-33'; import Challenge34 from './challenge-34'; export { Challenge33, Challenge34, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-01/challenge-02.ts
import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; export default class Challenge02 implements Challenge { private readonly input: number[] = new FileReader(1) .getFileAsArray() .filter((val) => val !== '') .map((value) => parseInt(value)); solve(): number { const sumOfMeasurements: number[] = []; let countLargerMeasurements: number = 0; for (let index = 0; index < this.input.length; index += 1) { if (this.input[index + 1] && this.input[index + 2]) { sumOfMeasurements.push(this.input[index] + this.input[index + 1] + this.input[index + 2]); if (sumOfMeasurements.length > 1) { if (sumOfMeasurements[sumOfMeasurements.length - 1] > sumOfMeasurements[sumOfMeasurements.length - 2]) { countLargerMeasurements += 1; } } } } return countLargerMeasurements; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-17/interfaces/interfaces.ts
export interface Range { from: number; to: number; } export interface TargetArea { x: Range; y: Range; } export interface Coordinates { x: number; y: number; } export interface Velocity { x: number, y: number }
YourBrainEatsYou/adventofcode2021
src/challenges/day-12/index.ts
import Challenge23 from './challenge-23'; import Challenge24 from './challenge-24'; export { Challenge23, Challenge24, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-03/challenge-05.ts
<reponame>YourBrainEatsYou/adventofcode2021<gh_stars>1-10 import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; export default class Challenge05 implements Challenge { private readonly input: number[][] = new FileReader(3) .getFileAsArray() .filter((value) => value !== '') .map((value) => value.split('').map((val) => parseInt(val))); solve(): number { let result = Array(this.input[0].length).fill(0); let binaryString = ''; for (let binarySet of this.input) { for (let index = 0; index < binarySet.length; index += 1) { result[index] += binarySet[index]; } } for (let bit of result) { binaryString += (bit > (this.input.length / 2)) ? '1' : '0'; } // convert binary String to number let gammaRate = parseInt(binaryString, 2); let epsilonRate = (parseInt(''.padStart(this.input[0].length, '1'), 2) ^ parseInt(binaryString, 2)); return gammaRate * epsilonRate; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-08/challenge-15.ts
<gh_stars>1-10 import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; export default class Challenge15 implements Challenge { private readonly input: string[] = new FileReader(8, 'input.txt') .getFileAsArray() .filter((line) => line !== '') .map((line) => line.split('|')[1]) .map((line) => line.split(' ').filter((item) => item !== '')) .flat(1); solve(): number { let countEasyNumbers = 0; for (let number of this.input) { switch (number.length) { case 2: // 1 case 4: // 4 case 3: // 8 case 7: // 9 countEasyNumbers += 1; break; default: break; } } return countEasyNumbers; } }
YourBrainEatsYou/adventofcode2021
src/utils/Challenge.ts
<filename>src/utils/Challenge.ts export abstract class Challenge { abstract solve(): number; }
YourBrainEatsYou/adventofcode2021
src/challenges/day-01/index.ts
<gh_stars>1-10 import Challenge01 from './challenge-01'; import Challenge02 from './challenge-02'; export { Challenge01, Challenge02, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-09/day-09.ts
<reponame>YourBrainEatsYou/adventofcode2021 import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; import Point from './interfaces/point'; export default abstract class Day09 implements Challenge { readonly input: number[][] = new FileReader(9) .getFileAsArray() .filter((line) => line !== '') .map((line) => { return line.split('').map((height) => parseInt(height)); }); up(x: number, y: number): number | null { if (typeof this.input[y - 1] !== 'undefined') { return this.input[y - 1][x]; } return null; } down(x: number, y: number): number | null { if (typeof this.input[y + 1] !== 'undefined') { return this.input[y + 1][x]; } return null; } left(x: number, y: number): number | null { if (typeof this.input[y][x - 1] !== 'undefined') { return this.input[y][x - 1]; } return null; } right(x: number, y: number): number | null { if (typeof this.input[y][x + 1] !== 'undefined') { return this.input[y][x + 1]; } return null; } getDeepestPointsCoords(): Array<Point> { const points = []; for (let yIndex = 0; yIndex < this.input.length; yIndex += 1) { const row = this.input[yIndex]; for (let xIndex = 0; xIndex < row.length; xIndex += 1) { const heightOfPoint = this.input[yIndex][xIndex]; const up = this.up(xIndex, yIndex) !== null ? this.up(xIndex, yIndex) : 10; const down = this.down(xIndex, yIndex) !== null ? this.down(xIndex, yIndex) : 10; const left = this.left(xIndex, yIndex) !== null ? this.left(xIndex, yIndex) : 10; const right = this.right(xIndex, yIndex) !== null ? this.right(xIndex, yIndex) : 10; if (heightOfPoint < up && heightOfPoint < down && heightOfPoint < left && heightOfPoint < right ) { const point: Point = { x: xIndex, y: yIndex, }; points.push(point); } } } return points; } abstract solve(): number; }
YourBrainEatsYou/adventofcode2021
src/challenges/day-15/challenge-30.ts
import Day15 from './day-15'; import { Node } from './interfaces/Node'; export default class Challenge30 extends Day15 { createMap(): Node[][] { const repeat = 5; const map: Node[][] = []; for (let yMod = 0; yMod < repeat; yMod += 1) { for (let yIndex = 0; yIndex < this.input.length; yIndex += 1) { const y = yIndex + (this.input.length * yMod); let yDistance = y - this.input.length < 0 ? 0 : y - this.input.length; map[y] = []; for (let xMod = 0; xMod < repeat; xMod += 1) { for (let xIndex = 0; xIndex < this.input[0].length; xIndex += 1) { const x = xIndex + (this.input[0].length * xMod); let xDistance = x - this.input[0].length < 0 ? 0 : x - this.input[0].length; let distance: number; if (yMod === 0 && xMod === 0) { // first square distance = this.input[y][x]; } if (yMod > 0 && xMod === 0) { distance = map[yDistance][x].distance + 1; } if (yMod === 0 && xMod > 0) { distance = map[y][xDistance].distance + 1; } if (yMod > 0 && xMod > 0) { distance = map[y][xDistance].distance + 1; } if (distance > 9) { distance = 1; } map[y][x] = { id: x.toString() + '-' + y.toString(), position: { x: x, y: y, }, g: 0, h: 0, f: 0, distance, parent: null, }; } } } } map[0][0].distance = 0; return map; } solve(): number { return super.solve(); } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-05/index.ts
<reponame>YourBrainEatsYou/adventofcode2021 import Challenge09 from './challenge-09'; import Challenge10 from './challenge-10'; export { Challenge09, Challenge10, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-07/index.ts
<reponame>YourBrainEatsYou/adventofcode2021<filename>src/challenges/day-07/index.ts import Challenge13 from './challenge-13'; import Challenge14 from './challenge-14'; export { Challenge13, Challenge14, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-05/day-05.ts
<filename>src/challenges/day-05/day-05.ts import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; export default abstract class Day05 implements Challenge { readonly maxX: number = 0; // horizontal readonly maxY: number = 0; // vertical matrix: Array<Array<number>>; readonly input: [number, number][][] = new FileReader(5) .getFileAsArray() .filter((line) => line !== '') .map((line) => line.split(' -> ') .map((coordinates) => coordinates.split(',') .map((number) => parseInt(number, 10)) as [number, number], ), ); constructor() { // get square size for (let line of this.input) { for (let coords of line) { this.maxX = coords[0] > this.maxX ? coords[0] : this.maxX; this.maxY = coords[1] > this.maxY ? coords[1] : this.maxY; } } // create matrix this.matrix = []; for (let index = 0; index <= this.maxY; index += 1) { this.matrix.push(Array(this.maxX).fill(0)); } } drawLine([fromX, fromY]: [number, number], [toX, toY]: [number, number], ignoreDiagonal = true): void { if (fromX === toX || fromY === toY) { // straightLine this.drawStraightLine([fromX, fromY], [toX, toY]); } else if (!ignoreDiagonal) { this.drawDiagonalLine([fromX, fromY], [toX, toY]); } } countOverlaps(): number { let overlaps = 0; for (let row of this.matrix) { for (let col of row) { if (col > 1) { overlaps += 1; } } } return overlaps; } abstract solve(): number; private drawStraightLine([fromX, fromY]: [number, number], [toX, toY]: [number, number]) { const coordsArrayToDraw = []; if (fromX === toX && fromY === toY) { coordsArrayToDraw.push([fromX, fromY]); } else { if (fromX === toX) { if (fromY <= toY) { for (let yIndex = fromY; yIndex <= toY; yIndex += 1) { coordsArrayToDraw.push([fromX, yIndex]); } } else { for (let yIndex = toY; yIndex <= fromY; yIndex += 1) { coordsArrayToDraw.push([fromX, yIndex]); } } } if (fromY === toY) { if (fromX <= toX) { for (let xIndex = fromX; xIndex <= toX; xIndex += 1) { coordsArrayToDraw.push([xIndex, fromY]); } } else { for (let xIndex = toX; xIndex <= fromX; xIndex += 1) { coordsArrayToDraw.push([xIndex, fromY]); } } } } this.increaseOnMatrix(coordsArrayToDraw as Array<[number, number]>); } private drawDiagonalLine([fromX, fromY]: [number, number], [toX, toY]: [number, number]) { const coordsArrayToDraw = []; let currentCoords = [fromX, fromY]; coordsArrayToDraw.push([...currentCoords]); while (currentCoords[0] !== toX && currentCoords[1] !== toY) { currentCoords[0] += currentCoords[0] > toX ? -1 : 1; currentCoords[1] += currentCoords[1] > toY ? -1 : 1; coordsArrayToDraw.push([...currentCoords]); } this.increaseOnMatrix(coordsArrayToDraw as Array<[number, number]>); } private increaseOnMatrix(numbers: Array<[number, number]>): void { for (let coords of numbers) { this.matrix[coords[1]][coords[0]] += 1; } } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-15/day-15.ts
import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; import { Coordinates, Node } from './interfaces/Node'; const neighbourList = [ [0, -1], // top [1, 0], // right [0, 1], // bottom [-1, 0], // left ]; export default abstract class Day15 implements Challenge { readonly input: number[][] = new FileReader(15) .getFileAsArray() .filter((line) => line !== '') .map((line) => line.split('') .map((chitons) => parseInt(chitons, 10)), ); private map: Node[][] = []; constructor() { this.map = this.createMap(); } private static idToCoords(id: string): Coordinates { const coordArray = id.split('-'); return { x: parseInt(coordArray[0], 10), y: parseInt(coordArray[1], 10), }; } private static calculateManhattanDistance(start: Coordinates, end: Coordinates): number { return Math.abs(start.x - end.x) + Math.abs(start.y + end.y); } abstract createMap(): Node[][]; solve(): number { const start = this.map[0][0]; const end = this.map[this.map.length - 1][this.map[0].length - 1]; let winningNode: Node; let openList = [start.id]; let closedList: string[] = []; while (openList.length > 0) { let lowestIndex = 0; for (let index = 0; index < openList.length; index++) { if (this.getNodeWithId(openList[index]).f < this.getNodeWithId(openList[lowestIndex]).f) { lowestIndex = index; } } let currentNode = this.getNodeWithId(openList[lowestIndex]); // reached finish if (currentNode.id === end.id) { winningNode = currentNode; break; } // move currentNode from open to close and inspect its neighbours openList.splice(lowestIndex, 1); closedList.push(currentNode.id); // getNeighbours const neighbours = this.getNeighbours(currentNode); for (let nIndex = 0; nIndex < neighbours.length; nIndex += 1) { let neighbour = neighbours[nIndex]; if (closedList.includes(neighbour.id)) { continue; // this node was already observed } const gScore = currentNode.g + neighbour.distance; // add the current distance to the parents distance let bestGScore = false; if (!openList.includes(neighbour.id)) { // calculate heuristic score bestGScore = true; neighbour.h = Day15.calculateManhattanDistance(neighbour.position, end.position); openList.push(neighbour.id); } else if (gScore < neighbour.g) { bestGScore = true; } if (bestGScore) { neighbour.parent = currentNode; neighbour.g = gScore; neighbour.f = neighbour.g + neighbour.h; } } } let riskLevel = null; if (winningNode) { riskLevel = winningNode.g; } return riskLevel; } private getNodeWithId(id: string): Node { const coords = Day15.idToCoords(id); return this.map[coords.y][coords.x]; } private getNeighbours(node: Node): Node[] { const neighbours = []; for (let modifier of neighbourList) { if (this.map[node.position.y + modifier[1]] && this.map[node.position.y + modifier[1]][node.position.x + modifier[0]]) { neighbours.push(this.map[node.position.y + modifier[1]][node.position.x + modifier[0]]); } } return neighbours; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-02/interfaces/index.ts
export type CommandType = 'forward' | 'down' | 'up'; export interface Command { type: CommandType, times: number } export interface Position { horizontal: number, depth: number, aim?: number }
YourBrainEatsYou/adventofcode2021
src/challenges/day-02/challenge-03.ts
import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; import { Command, CommandType, Position } from './interfaces'; export default class Challenge03 implements Challenge { private input: Command[] = new FileReader(2) .getFileAsArray() .filter((value) => value !== '') .map((value) => { const [type, times] = value.split(' ') as [CommandType, string]; return { type, times: parseInt(times) }; }); private position: Position = { horizontal: 0, depth: 0, }; solve(): number { for (let command of this.input) { switch (command.type) { case 'forward': this.position.horizontal += command.times; break; case 'down': this.position.depth += command.times; break; case 'up': this.position.depth -= command.times; break; } } return this.position.horizontal * this.position.depth; } }
YourBrainEatsYou/adventofcode2021
src/challenges/index.ts
<reponame>YourBrainEatsYou/adventofcode2021<filename>src/challenges/index.ts import { Challenge01, Challenge02 } from './day-01'; import { Challenge03, Challenge04 } from './day-02'; import { Challenge05, Challenge06 } from './day-03'; import { Challenge07, Challenge08 } from './day-04'; import { Challenge09, Challenge10 } from './day-05'; import { Challenge11, Challenge12 } from './day-06'; import { Challenge13, Challenge14 } from './day-07'; import { Challenge15, Challenge16 } from './day-08'; import { Challenge17, Challenge18 } from './day-09'; import { Challenge19, Challenge20 } from './day-10'; import { Challenge21, Challenge22 } from './day-11'; import { Challenge23, Challenge24 } from './day-12'; import { Challenge25, Challenge26 } from './day-13'; import { Challenge27, Challenge28 } from './day-14'; import { Challenge29, Challenge30 } from './day-15'; import { Challenge31, Challenge32 } from './day-16'; import { Challenge33, Challenge34 } from './day-17'; export { Challenge01, Challenge02, Challenge03, Challenge04, Challenge05, Challenge06, Challenge07, Challenge08, Challenge09, Challenge10, Challenge11, Challenge12, Challenge13, Challenge14, Challenge15, Challenge16, Challenge17, Challenge18, Challenge19, Challenge20, Challenge21, Challenge22, Challenge23, Challenge24, Challenge25, Challenge26, Challenge27, Challenge28, Challenge29, Challenge30, Challenge31, Challenge32, Challenge33, Challenge34, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-15/interfaces/Node.ts
<filename>src/challenges/day-15/interfaces/Node.ts<gh_stars>1-10 export interface Coordinates { x: number; y: number; } export interface Node { id: string; // x + y position: Coordinates; g: number | null; // current costs to this node h: number | null; // heuristic | manhattan distance to final node f: number | null; // calculatedCosts g + h distance: number; // distance |how many chitons are on that node parent: Node | null; }
YourBrainEatsYou/adventofcode2021
src/challenges/day-10/challenge-20.ts
<reponame>YourBrainEatsYou/adventofcode2021 import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; const BRACKETS: { [key: string]: string } = { '(': ')', '[': ']', '{': '}', '<': '>', }; const POINTS: { [key: string]: number } = { ')': 1, ']': 2, '}': 3, '>': 4, }; export default class Challenge20 implements Challenge { readonly input: string[][] = new FileReader(10) .getFileAsArray() .filter((line) => line !== '') .map((line) => line.split('').filter((line) => line !== '')); getClosingStack(line: string[]): string[] { let closingStack: string[] = []; for (let brace of line) { if (BRACKETS.hasOwnProperty(brace)) { // is opening brace closingStack = [BRACKETS[brace], ...closingStack]; } else { // is closing, so the first element of the closingStack should match const predictedClosingItem = closingStack.shift(); if (predictedClosingItem !== brace) { // if the closing brace dont match its an corrupted line return null; } } } return closingStack; } solve(): number { let closingStacks = []; for (let line of this.input) { const closingStack = this.getClosingStack(line); if (closingStack !== null) { closingStacks.push(closingStack); } } let totals = []; for (let stack of closingStacks) { let stackTotal = 0; for (let brace of stack) { stackTotal = (stackTotal * 5) + POINTS[brace]; } totals.push(stackTotal); } totals.sort((a, b) => a - b); return totals[(totals.length - 1) / 2]; } }
YourBrainEatsYou/adventofcode2021
src/challenges/day-10/index.ts
<reponame>YourBrainEatsYou/adventofcode2021 import Challenge19 from './challenge-19'; import Challenge20 from './challenge-20'; export { Challenge19, Challenge20, };
YourBrainEatsYou/adventofcode2021
src/challenges/day-14/challenge-28.ts
import { FileReader } from '../../utils'; import { Challenge } from '../../utils/Challenge'; export default class Challenge28 implements Challenge { private readonly input: string[] = new FileReader(14).getFileAsArray().filter((line) => line !== ''); private template: string[] = []; private occurrences: { [key: string]: number } = {}; private insertionRules: { [key: string]: string } = {}; private charCount: { [key: string]: number } = {}; constructor() { for (let line of this.input) { if (line.includes(' -> ')) { // line is rule let rule: [string, string] = line.split(' -> ') as [string, string]; this.insertionRules[rule[0]] = rule[1]; this.occurrences[rule[0]] = 0; } else { // line is template this.template = line.split(''); } } // initialCharCount for (let char of this.template) { this.charCount[char] = (this.charCount[char] || 0) + 1; } this.parseTemplateAndAddToOcurrences(this.template); } parseTemplateAndAddToOcurrences(template: string[], multiplier: number = 1) { for (let index = 0; index < template.length - 1; index += 1) { const searchIndex = template[index] + template[index + 1]; this.occurrences[searchIndex] = (this.occurrences[searchIndex] || 0) + multiplier; } } executeRulesOntoPolymers(): void { const occurrences = Object.keys(this.occurrences).filter((item: string) => this.occurrences[item] > 0); const occurrencesCopy: { [key: string]: number } = { ...this.occurrences }; this.occurrences = {}; for (let occurrence of occurrences) { const insert = this.insertionRules[occurrence]; const newTempalte = [occurrence[0], insert, occurrence[1]]; const multiplier = occurrencesCopy[occurrence]; this.charCount[insert] = (this.charCount[insert] || 0) + multiplier; this.parseTemplateAndAddToOcurrences(newTempalte, multiplier); } } calculateElements(): number { const counts = Object.values(this.charCount).sort((a, b) => a - b); const most = counts.pop(); const least = counts.shift(); return most - least; } solve(): number { const numOfSteps = 40; for (let step = 0; step < numOfSteps; step += 1) { this.executeRulesOntoPolymers(); } return this.calculateElements(); } }
YourBrainEatsYou/adventofcode2021
src/utils/index.ts
<filename>src/utils/index.ts import { FileReader } from './FileReader'; export { FileReader, };
JKusiak/isshu
frontend/src/api/Board/GetBoard.tsx
<filename>frontend/src/api/Board/GetBoard.tsx import axios from "axios"; import { createContext, Dispatch, useReducer, useState } from "react"; import { useParams } from "react-router-dom"; import { useMountEffect } from "../../hooks/useMountEffect"; import BoardData from "../../pages/Project/Subpages/BoardPage"; import { Action, ActionTypes, boardContentReducer } from "../../reducers/BoardReducer"; import { NestedBoardTemplate } from "../../types/ModelContentTemplate"; // context for avoiding propagating function fetchBoard() for refreshing // the board content to child components export const BoardReducerContext = createContext<{ boardState: any, dispatch: Dispatch<Action> }>({ boardState: null, dispatch: () => null, }); const GetBoard = () => { const { boardId } = useParams<{ boardId: string }>(); const [isLoaded, setIsLoaded] = useState<boolean>(false); const [boardState, dispatch] = useReducer(boardContentReducer, NestedBoardTemplate) useMountEffect(fetchBoard); function fetchBoard() { axios.get(`/boards/getContent/${boardId}`) .then(resp => { dispatch({ type: ActionTypes.FetchData, payload: resp.data }); setIsLoaded(true); }).catch((err) => { console.log(err); }); } function changeColumn(newColumnId: string, issueId: string) { const issueChanges = { columnId: newColumnId, } axios.post(`/issues/update/${issueId}`, issueChanges) .catch((err) => { console.log(err); }); } return ( <> {isLoaded && <BoardReducerContext.Provider value={{ boardState, dispatch }}> <BoardData board={boardState} changeColumn={changeColumn} /> </BoardReducerContext.Provider> } </> ); } export default GetBoard;
JKusiak/isshu
frontend/src/pages/RegisterPage.tsx
import Container from '@material-ui/core/Container'; import CssBaseline from '@material-ui/core/CssBaseline'; import { createStyles, makeStyles, Theme } from '@material-ui/core/styles'; import Register from '../api/Authentication/Register'; const useStyles = makeStyles((theme: Theme) => createStyles({ paper: { marginTop: theme.spacing(9), display: 'flex', flexDirection: 'column', alignItems: 'center', }, })); const RegisterPage = () => { const classes = useStyles(); return ( <Container component="main" maxWidth="xs"> <CssBaseline /> <div className={classes.paper}> <Register /> </div> </Container> ); } export default RegisterPage;
JKusiak/isshu
frontend/src/layout/Footer.tsx
<reponame>JKusiak/isshu<filename>frontend/src/layout/Footer.tsx import { createStyles, Link, makeStyles, Theme } from "@material-ui/core"; import { useContext } from "react"; import { DarkModeContext } from "../App"; const useStyles = makeStyles((theme: Theme) => createStyles({ footerContainer: { marginTop: 'auto', display: 'flex', justifyContent: 'center', fontSize: '16px', color: theme.palette.secondary.main, padding: theme.spacing(2), }, link: { color: theme.palette.secondary.main, "&:hover": { textDecoration: 'none', fontWeight: 'bold', } } })); const Footer = () => { const classes = useStyles(); const { darkMode } = useContext(DarkModeContext); return ( <> <footer className={classes.footerContainer}> Made with {darkMode ? <span>&nbsp;🤍&nbsp;</span> : <span>&nbsp;🖤&nbsp;</span>} by <Link className={classes.link} href="https://www.linkedin.com/in/juliusz-kusiak-22992520a/"> &nbsp;<NAME> </Link> </footer> </> ) } export default Footer;
JKusiak/isshu
frontend/src/pages/Home/Subpages/MembersGalleryPage.tsx
import { Typography } from "@material-ui/core"; import { createStyles, makeStyles, Theme } from "@material-ui/core/styles"; import { Fragment, useContext } from "react"; import { FetchMembersContext } from "../../../api/Authentication/GetHomePage"; import ManageMembers from "../../../api/Organization/ManageMembers"; import ManageMemberCard from "../../../api/User/ManageMemberCard"; import { INestedUser } from "../../../types/ModelTypes"; const useStyles = makeStyles((theme: Theme) => createStyles({ header: { display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 'bold', fontSize: '28px', [theme.breakpoints.down('xs')]: { fontSize: '22px', }, color: theme.palette.secondary.main, marginBottom: theme.spacing(2), }, galleryGrid: { display: 'grid', justifyContent: 'center', gap: theme.spacing(4), gridTemplateColumns: 'repeat(auto-fill, 400px)', [theme.breakpoints.down('xs')]: { gridTemplateColumns: 'repeat(auto-fill, 250px)', }, marginRight: theme.spacing(8), marginLeft: theme.spacing(8), marginBottom: theme.spacing(4), }, }) ); const MembersGalleryPage = () => { const classes = useStyles(); const { members } = useContext(FetchMembersContext); function displayMembers() { if (members.length > 0) { return (members.map((member: INestedUser) => { return ( <Fragment key={member._id}> <ManageMemberCard member={member} /> </Fragment> ); })); } } return ( <> <Typography className={classes.header} component="h1" variant="h4"> Members </Typography> <ManageMembers /> <div className={classes.galleryGrid}> {displayMembers()} </div> </> ); } export default MembersGalleryPage;
JKusiak/isshu
frontend/src/api/Board/UpdateBoard.tsx
import axios from 'axios'; import { FC, useContext, useState } from 'react'; import { useParams } from 'react-router-dom'; import UpdateBoardNameButton from '../../components/Board/UpdateNameButton'; import { ActionTypes } from '../../reducers/BoardReducer'; import { BoardReducerContext } from './GetBoard'; interface UpdateBoardProps { boardName: string, } const UpdateBoard: FC<UpdateBoardProps> = (props) => { let { boardId } = useParams<{ boardId: string }>(); const [tempBoardName, setTempBoardName] = useState(props.boardName); const { dispatch } = useContext(BoardReducerContext); function onSubmit(e: React.SyntheticEvent) { e.preventDefault(); if (tempBoardName === '') return; const board = { name: tempBoardName, } axios.post(`/boards/update/${boardId}`, board); dispatch({ type: ActionTypes.UpdateBoard, payload: tempBoardName }); } return ( <> <UpdateBoardNameButton tempBoardName={tempBoardName} setTempBoardName={setTempBoardName} permBoardName={props.boardName} onSubmit={onSubmit} /> </> ); } export default UpdateBoard;
JKusiak/isshu
frontend/src/components/Column/AddColumnButton.tsx
import { ClickAwayListener, IconButton, InputBase } from '@material-ui/core'; import Card from '@material-ui/core/Card'; import { createStyles, makeStyles, Theme } from '@material-ui/core/styles'; import AddIcon from '@material-ui/icons/AddOutlined'; import { FC, SetStateAction, useState } from 'react'; const useStyles = makeStyles((theme: Theme) => createStyles({ card: { width: 'auto', margin: theme.spacing(1), backgroundColor: theme.palette.primary.light, }, form: { display: 'flex', width: '250px', justifyContent: 'center', alignItems: 'center', }, inputField: { flexShrink: 0, marginLeft: theme.spacing(1), color: theme.palette.secondary.main, }, icon: { transform: 'scale(1)', color: theme.palette.secondary.main, }, })); interface AddColumnButtonProps { onSubmit: (e: React.SyntheticEvent<Element, Event>) => void, setColumnName: React.Dispatch<SetStateAction<string>>, } const AddColumnButton: FC<AddColumnButtonProps> = (props) => { const classes = useStyles(); const [addMode, setAddMode] = useState<boolean>(false); function handleSubmit(e: any) { e.preventDefault(); setAddMode(false); props.onSubmit(e); } return ( <> <div onClick={() => setAddMode(true)}> <ClickAwayListener onClickAway={() => setAddMode(false)}> <Card className={classes.card}> {addMode && <form className={classes.form} onSubmit={handleSubmit} autoComplete="off"> <InputBase className={classes.inputField} required autoFocus name="columnName" id="columnName" placeholder="Column name" autoComplete="column-name" onChange={e => { props.setColumnName(e.target.value); }} /> <IconButton type="submit" aria-label='expandedAddColumnButton'> <AddIcon className={classes.icon} /> </IconButton> </form> } {!addMode && <IconButton aria-label='addColumnButton'> <AddIcon className={classes.icon} /> </IconButton> } </Card> </ClickAwayListener> </div> </> ); } export default AddColumnButton;
JKusiak/isshu
frontend/src/components/Authentication/RegisterForm.tsx
<reponame>JKusiak/isshu import Button from '@material-ui/core/Button'; import Grid from '@material-ui/core/Grid'; import Link from '@material-ui/core/Link'; import { createStyles, makeStyles, Theme } from '@material-ui/core/styles'; import Typography from '@material-ui/core/Typography'; import React, { FC, useEffect, useReducer } from 'react'; import { Link as RouterLink } from 'react-router-dom'; import { ActionTypes, registerReducer, UserToRegisterTemplate } from '../../reducers/RegisterReducer'; import RegisterField from './RegisterField'; const useStyles = makeStyles((theme: Theme) => createStyles({ header: { display: 'flex', justifyContent: 'center', marginBottom: theme.spacing(5), color: theme.palette.secondary.main, }, form: { width: '100%', }, submitButton: { margin: theme.spacing(3, 0, 3), borderRadius: '10px', textTransform: 'none', fontSize: '16px', color: theme.palette.secondary.main, backgroundColor: theme.palette.primary.light, transition: 'all .12s linear', boxShadow: theme.shadows[2], "&:hover": { cursor: 'pointer', boxShadow: theme.shadows[5], backgroundColor: theme.palette.primary.light, }, }, createdAccount: { color: "green", textAlign: "center", }, wrongInput: { color: "#C62828", textAlign: "center", }, toLogin: { [theme.breakpoints.down('xs')]: { marginBottom: theme.spacing(4), }, } })); const emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; const nameRegex = /^$|^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/; const passRegex = /^$|^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/; const anythingRegex = /^.*$/; interface RegisterProps { registerUser: (user: any) => void, isValid: boolean setIsValid: React.Dispatch<React.SetStateAction<boolean>>, isSent: boolean, setIsSent: React.Dispatch<React.SetStateAction<boolean>>, errorText: string, setErrorText: React.Dispatch<React.SetStateAction<string>>, } const RegisterForm: FC<RegisterProps> = (props) => { const classes = useStyles(); const [userReducer, dispatch] = useReducer(registerReducer, UserToRegisterTemplate); useEffect(() => { if (userReducer.repeatPassword === userReducer.password) { props.setIsValid(true); } else { props.setErrorText("Passwords must be the same"); props.setIsValid(false); }; }, [userReducer.password, userReducer.repeatPassword]); function onSubmit(e: React.SyntheticEvent) { e.preventDefault(); const { name, surname, email, password } = userReducer; const newUser = { name, surname, email, password }; if (props.isValid) { props.registerUser(newUser); } } return ( <> <Typography className={classes.header} component="h1" variant="h4"> Sign up </Typography> <form className={classes.form} onSubmit={onSubmit}> <Grid container spacing={3}> <Grid item xs={12} sm={6}> <RegisterField type='Name' inputType='text' setIsValid={props.setIsValid} regex={nameRegex} errorText='Name must only contain lower- and uppercase letters' setErrorText={props.setErrorText} setIsSent={props.setIsSent} dispatch={dispatch} actionType={ActionTypes.SetName} /> </Grid> <Grid item xs={12} sm={6}> <RegisterField type='Surname' inputType='text' setIsValid={props.setIsValid} regex={nameRegex} errorText='Surname must only contain lower- and uppercase letters' setErrorText={props.setErrorText} setIsSent={props.setIsSent} dispatch={dispatch} actionType={ActionTypes.SetSurname} /> </Grid> <Grid item xs={12}> <RegisterField type='Email' inputType='text' setIsValid={props.setIsValid} regex={emailRegex} errorText='Email must follow valid email format' setErrorText={props.setErrorText} setIsSent={props.setIsSent} dispatch={dispatch} actionType={ActionTypes.SetEmail} /> </Grid> <Grid item xs={12}> <RegisterField type='Password' inputType='password' setIsValid={props.setIsValid} regex={passRegex} errorText={'Password must contain \n minimum 8 characters,' + ' at least 1 uppercase letter, 1 lowercase letter,' + ' 1 number and 1 special character (@$!%*?&)'} setErrorText={props.setErrorText} setIsSent={props.setIsSent} dispatch={dispatch} actionType={ActionTypes.SetPassword} /> </Grid> <Grid item xs={12}> <RegisterField type='Confirm_password' inputType='password' setIsValid={props.setIsValid} regex={anythingRegex} errorText={''} setErrorText={props.setErrorText} setIsSent={props.setIsSent} dispatch={dispatch} actionType={ActionTypes.SetRepeatPassword} /> </Grid> </Grid> {props.isSent && <div className={classes.createdAccount}><p id='success_text'>Succesfully created account</p></div>} {!props.isValid && <div className={classes.wrongInput}><p id='error_text'>{props.errorText}</p></div>} <Button className={classes.submitButton} type="submit" fullWidth variant="contained" > Sign Up </Button> <Grid container justify="flex-end"> <Grid className={classes.toLogin} item> <Link component={RouterLink} to='/login' color='secondary'> {"Already have an account? Log in here"} </Link> </Grid> </Grid> </form> </> ); } export default RegisterForm;
JKusiak/isshu
frontend/src/components/User/MemberCard.tsx
<filename>frontend/src/components/User/MemberCard.tsx import { Card, CardActions, CardContent, CardMedia, Typography } from "@material-ui/core"; import { createStyles, makeStyles, Theme } from "@material-ui/core/styles"; import { FC, useContext } from "react"; import { Link } from 'react-router-dom'; import DeleteMember from "../../api/Organization/DeleteMember"; import { AuthUserContext } from "../../App"; import { INestedUser } from "../../types/ModelTypes"; const useStyles = makeStyles((theme: Theme) => createStyles({ cardContainer: { display: 'flex', height: 140, [theme.breakpoints.down('xs')]: { height: 100, }, width: 'auto', transition: 'all .12s linear', boxShadow: theme.shadows[2], backgroundColor: theme.palette.primary.light, "&:hover": { boxShadow: theme.shadows[5], }, }, cardContent: { display: 'flex', width: '100%', justifyContent: 'center', alignItems: 'center', textDecoration: 'none', color: theme.palette.secondary.main, maxWidth: '260px', }, name: { [theme.breakpoints.down('sm')]: { fontSize: '18px', }, overflow: 'hidden', color: theme.palette.secondary.main, }, description: { overflow: 'hidden', color: theme.palette.secondary.main, }, image: { flex: 'none', marginRight: 'auto', height: 140, width: 140, [theme.breakpoints.down('xs')]: { height: 100, width: 100, }, filter: 'blur(0.5px)' }, } )); interface MemberProps { member: INestedUser, imageExists: boolean, imageUrl: string, } const MemberCard: FC<MemberProps> = (props) => { const classes = useStyles(); const { loggedInUser } = useContext(AuthUserContext); return ( <> <Card className={classes.cardContainer}> <CardMedia className={classes.image} component={Link} to={`/user/${props.member._id}`} image={props.imageUrl} title="Member profile photo" /> <CardContent className={classes.cardContent} component={Link} to={`/user/${props.member._id}`}> <Typography className={classes.name} component="h5" variant="h5"> {props.member.name} {props.member.surname} </Typography> </CardContent> <CardActions> {loggedInUser._id !== props.member._id && <DeleteMember member={props.member} /> } </CardActions> </Card> </> ); } export default MemberCard;
JKusiak/isshu
frontend/src/components/Authentication/RegisterField.tsx
import { createStyles, makeStyles, TextField, Theme } from '@material-ui/core'; import { FC } from 'react'; import { Action, ActionTypes } from '../../reducers/RegisterReducer'; const useStyles = makeStyles((theme: Theme) => createStyles({ inputField: { "& .MuiOutlinedInput-root": { color: theme.palette.secondary.main, "& .MuiOutlinedInput-notchedOutline": { borderRadius: '10px', borderColor: theme.palette.secondary.light, }, "&.Mui-focused .MuiOutlinedInput-notchedOutline": { borderColor: theme.palette.secondary.light, borderWidth: "2px", } }, }, })); interface FieldProps { type: string, inputType: string, setIsValid: React.Dispatch<React.SetStateAction<boolean>>, regex: RegExp, errorText: string, setErrorText: React.Dispatch<React.SetStateAction<string>>, setIsSent: React.Dispatch<React.SetStateAction<boolean>>, dispatch: (value: Action) => void, actionType: ActionTypes, } const RegisterField: FC<FieldProps> = (props) => { const classes = useStyles(); return ( <TextField className={classes.inputField} required fullWidth type={props.inputType} variant="outlined" autoComplete="register" name={props.type} id={props.type} placeholder={props.type} onChange={e => { if (e.target.value.match(props.regex)) { props.dispatch({ type: props.actionType, payload: e.target.value }); props.setIsValid(true); } else { props.setErrorText(props.errorText); props.setIsValid(false); } props.setIsSent(false); }} /> ); } export default RegisterField; export { };
JKusiak/isshu
frontend/src/reducers/RegisterReducer.tsx
export enum ActionTypes { SetName = 'SET NAME', SetSurname = 'SET SURNAME', SetEmail = 'SET EMAIL', SetPassword = '<PASSWORD>', SetRepeatPassword = 'SET REPEAT PASSWORD', } interface UserToRegister { name: string, surname: string, email: string, password: string, repeatPassword: string, } export const UserToRegisterTemplate = { name: '', surname: '', email: '', password: '', repeatPassword: '', } export type Action = { type: ActionTypes, payload: any, } export const registerReducer = (state: UserToRegister, action: Action) => { const { type, payload } = action; switch (type) { case ActionTypes.SetName: return { ...state, name: payload, } case ActionTypes.SetSurname: return { ...state, surname: payload, } case ActionTypes.SetEmail: return { ...state, email: payload, } case ActionTypes.SetPassword: return { ...state, password: payload, } case ActionTypes.SetRepeatPassword: return { ...state, repeatPassword: payload, } default: return state } }
JKusiak/isshu
frontend/src/components/Board/UpdateNameButton.tsx
<filename>frontend/src/components/Board/UpdateNameButton.tsx import { ClickAwayListener, TextField } from '@material-ui/core'; import { createStyles, makeStyles, Theme } from '@material-ui/core/styles'; import React, { FC, useState } from 'react'; const useStyles = makeStyles((theme: Theme) => createStyles({ container: { width: '100%', }, form: { width: '100%', }, inputField: { width: '100%', "& .MuiOutlinedInput-root": { color: theme.palette.secondary.main, "& .MuiOutlinedInput-notchedOutline": { borderRadius: '10px', borderColor: theme.palette.secondary.light, }, "&.Mui-focused .MuiOutlinedInput-notchedOutline": { borderColor: theme.palette.secondary.light, borderWidth: "2px", } }, "& .MuiOutlinedInput-input": { fontSize: 30, padding: 10, fontWeight: 'bold', }, }, nameText: { textAlign: 'center', "&:hover": { cursor: 'pointer' } } })); interface UpdateNameProps { tempBoardName: string, setTempBoardName: React.Dispatch<React.SetStateAction<string>>, permBoardName: string, onSubmit: (e: any) => void, } const UpdateNameButton: FC<UpdateNameProps> = (props) => { const classes = useStyles(); const [updateMode, setUpdateMode] = useState<boolean>(false); function handleSubmit(e: any) { if (updateMode) { props.onSubmit(e); } setUpdateMode(false); } return ( <ClickAwayListener onClickAway={handleSubmit}> <div className={classes.container} onClick={() => setUpdateMode(true)}> {updateMode && <form className={classes.form} onSubmit={handleSubmit} autoComplete="off"> <TextField className={classes.inputField} required autoFocus variant='outlined' name="boardName" id="boardName" value={props.tempBoardName} autoComplete="board-name" onChange={e => { props.setTempBoardName(e.target.value); }} /> </form> } {!updateMode && <div className={classes.nameText}>{props.permBoardName}</div> } </div> </ClickAwayListener> ); } export default UpdateNameButton;
JKusiak/isshu
frontend/src/api/Tag/ManageTags.tsx
import axios from 'axios'; import React, { FC, useContext, useState } from 'react'; import { AuthUserContext } from '../../App'; import AllTagsGallery from '../../components/Tag/AllTagsGallery'; import { useMountEffect } from '../../hooks/useMountEffect'; import { TagTemplate } from '../../types/ModelContentTemplate'; import { INestedIssue, ITag } from '../../types/ModelTypes'; interface ManageTagsProps { issue: INestedIssue, isTagsModalOpen: boolean, setTagsModalOpen: React.Dispatch<React.SetStateAction<boolean>>, } const ManageTags: FC<ManageTagsProps> = (props) => { const [allTags, setAllTags] = useState<[ITag]>([TagTemplate]); const { loggedInUser } = useContext(AuthUserContext); useMountEffect(fetchAllTags); function updateIssueTags() { const tagsToId = props.issue.tags.map(tag => tag._id); const requestBody = { tags: tagsToId, } axios.post(`/issues/update/${props.issue._id}`, requestBody) .catch((err) => { console.log(err); }) } function fetchAllTags() { axios.get(`/tags/${loggedInUser.organizationId}`) .then((res) => { setAllTags(res.data); }) } function addTag(e: React.SyntheticEvent, newTagName: string) { e.preventDefault(); const requestBody = { name: newTagName, organizationId: loggedInUser.organizationId, } axios.post('/tags/add', requestBody) .then(() => { fetchAllTags(); }) } function deleteTag(e: React.SyntheticEvent, tagId: string) { e.preventDefault(); axios.delete(`/tags/delete/${tagId}`) .then(() => { fetchAllTags(); }) } return ( <> <AllTagsGallery issue={props.issue} updateIssueTags={updateIssueTags} allTags={allTags} deleteTag={deleteTag} addTag={addTag} /> </> ); } export default ManageTags;
JKusiak/isshu
frontend/src/api/User/GetLoggedInUser.tsx
<gh_stars>0 export function getLoggedInUser() { const token = localStorage.getItem('token') || ''; const base64Url = token.split('.')[1]; const base64 = base64Url.replace('-', '+').replace('_', '/'); return JSON.parse(atob(base64)) || null; } export function getUserLanguage() { if (navigator.languages !== undefined) return navigator.languages[0]; return navigator.language; }
JKusiak/isshu
frontend/src/components/Project/ProjectInfoBanner/NameForm.tsx
import { TextField } from '@material-ui/core'; import { createStyles, makeStyles, Theme } from "@material-ui/core/styles"; import React, { FC } from "react"; import { Action, ActionTypes } from "../../../reducers/ProjectReducer"; const useStyles = makeStyles((theme: Theme) => createStyles({ nameForm: { gridArea: 'projectName', justifySelf: 'stretch', alignSelf: 'stretch', }, nameStyle: { [theme.breakpoints.down('xs')]: { fontSize: '36px', }, [theme.breakpoints.up('sm')]: { fontSize: '48px', }, fontWeight: 600, }, fontColor: { "& .MuiInputBase-root.Mui-disabled": { color: '#fafafa', }, "& .MuiInputBase-root": { color: 'rgba(255, 255, 255, 0.6)', }, "& .MuiButtonBase-root.MuiIconButton-root.Mui-disabled": { color: '#fafafa', }, "& .MuiButtonBase-root.MuiIconButton-root": { color: 'rgba(255, 255, 255, 0.6)', }, }, })); interface DateFormProps { isEditing: boolean, value: string, dispatch: React.Dispatch<Action>, actionType: ActionTypes, onSubmit: (e: React.SyntheticEvent) => void, } const DateForm: FC<DateFormProps> = (props) => { const classes = useStyles(props); return ( <form className={classes.nameForm} noValidate autoComplete="off" onSubmit={props.onSubmit}> <TextField className={classes.fontColor} id="project-name" disabled={!props.isEditing} InputProps={{ disableUnderline: true, classes: { input: classes.nameStyle, }, }} inputProps={{ min: 0, style: { textAlign: 'center' } }} value={props.value || ''} onChange={e => { props.dispatch({ type: props.actionType, payload: e.target.value }) }} /> </form> ); } export default DateForm;
JKusiak/isshu
frontend/src/components/Issue/Name/UpdateNameButton.tsx
<filename>frontend/src/components/Issue/Name/UpdateNameButton.tsx import { ClickAwayListener, TextField } from '@material-ui/core'; import { createStyles, makeStyles, Theme } from '@material-ui/core/styles'; import { FC, useState } from 'react'; import { INestedIssue } from '../../../types/ModelTypes'; import NameText from './NameText'; const useStyles = makeStyles((theme: Theme) => createStyles({ nameContainer: { gridArea: 'header', justifySelf: 'start', width: '67%', paddingRight: theme.spacing(2), }, form: { width: '100%', marginBottom: theme.spacing(2), }, inputField: { width: '100%', height: '100%', "& .MuiOutlinedInput-root": { height: '100%', color: theme.palette.secondary.main, "& .MuiOutlinedInput-notchedOutline": { height: 'auto', borderRadius: '6px', borderColor: theme.palette.secondary.light, }, "&.Mui-focused .MuiOutlinedInput-notchedOutline": { height: 'auto', borderColor: theme.palette.secondary.light, borderWidth: "2px", }, }, "& .MuiOutlinedInput-input": { fontSize: 24, padding: 10, fontWeight: 'bold', }, }, })); interface UpdateNameButtonProps { issue: INestedIssue, tempName: string, setTempName: React.Dispatch<React.SetStateAction<string>>, permName: string, onSubmit: (e: any) => void, } const UpdateNameButton: FC<UpdateNameButtonProps> = (props) => { const classes = useStyles(); const [updateMode, setUpdateMode] = useState<boolean>(false); function handleSubmit(e: any) { if (updateMode) { props.onSubmit(e); } setUpdateMode(false); } return ( <ClickAwayListener onClickAway={handleSubmit}> <div className={classes.nameContainer} onClick={() => setUpdateMode(true)}> {updateMode && <form className={classes.form} onSubmit={handleSubmit} autoComplete="off"> <TextField className={classes.inputField} required autoFocus size="small" variant='outlined' name="issueName" id="issueName" value={props.tempName} autoComplete="issue-name" onChange={e => { props.setTempName(e.target.value); }} /> </form> } {!updateMode && <NameText issue={props.issue} permName={props.permName} /> } </div> </ClickAwayListener> ); } export default UpdateNameButton;
JKusiak/isshu
frontend/src/api/Column/UpdateColumn.tsx
import axios from 'axios'; import { FC, useContext, useState } from 'react'; import ColumnNameButton from '../../components/Column/ColumnNameButton'; import { ActionTypes } from '../../reducers/BoardReducer'; import { INestedColumn } from '../../types/ModelTypes'; import { BoardReducerContext } from '../Board/GetBoard'; interface UpdateColumnProps { column: INestedColumn, } const UpdateColumn: FC<UpdateColumnProps> = (props) => { const [tempColumnName, setTempColumnName] = useState(props.column.name); const { dispatch } = useContext(BoardReducerContext); function onSubmit(e: React.SyntheticEvent) { e.preventDefault(); if (tempColumnName === '') return; const column = { name: tempColumnName, } axios.post(`/columns/update/${props.column._id}`, column); const payload = { newName: tempColumnName, columnId: props.column._id, } dispatch({ type: ActionTypes.UpdateColumn, payload: payload }) } return ( <> <ColumnNameButton tempColumnName={tempColumnName} setTempColumnName={setTempColumnName} permColumnName={props.column.name} onSubmit={onSubmit} /> </> ); } export default UpdateColumn;
JKusiak/isshu
frontend/src/api/Authentication/Login.tsx
import axios from 'axios'; import { useContext, useState } from 'react'; import { useHistory } from 'react-router-dom'; import { AuthUserContext, IsLoggedInContext } from '../../App'; import LoginForm from '../../components/Authentication/LoginForm'; import { getLoggedInUser } from '../User/GetLoggedInUser'; const Login = () => { const [isValid, setIsValid] = useState<boolean>(true); const { setLoggedIn } = useContext(IsLoggedInContext); const { setLoggedInUser } = useContext(AuthUserContext); const history = useHistory(); function loginUser(credentials: any) { axios.post('/login', credentials) .then((res) => { localStorage.setItem('token', res.data.token); setLoggedIn(true); setLoggedInUser(getLoggedInUser()); history.push("/home/projects"); }).catch((err) => { console.log(err); setIsValid(false); }); } return ( <> <LoginForm loginUser={loginUser} isValid={isValid} setIsValid={setIsValid} /> </> ); } export default Login;
JKusiak/isshu
frontend/src/components/Issue/Step/IssueStepsGallery.tsx
<gh_stars>0 import { createStyles, makeStyles, Theme, Typography } from '@material-ui/core'; import LinearProgress from '@material-ui/core/LinearProgress'; import { FC, Fragment, useContext, useEffect, useState } from 'react'; import { DragDropContext, Droppable, DropResult } from 'react-beautiful-dnd'; import { BoardReducerContext } from '../../../api/Board/GetBoard'; import { ActionTypes } from '../../../reducers/BoardReducer'; import { INestedIssue, IStep } from '../../../types/ModelTypes'; import AddStepButton from './AddStepButton'; import IssueStepData from './IssueStepData'; const useStyles = makeStyles((theme: Theme) => createStyles({ headline: { fontSize: '16px', fontWeight: 'bold', color: theme.palette.secondary.main, }, progressContainer: { display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: theme.spacing(1), marginTop: theme.spacing(1), }, progressBar: { width: '100%', backgroundColor: theme.palette.primary.main, "& .MuiLinearProgress-barColorPrimary": { backgroundColor: theme.palette.secondary.main, } }, progress: { textAlign: 'center', minWidth: '35px', marginLeft: theme.spacing(1), color: theme.palette.secondary.main }, }) ); interface IssueStepsGalleryProps { issue: INestedIssue, updateSteps: () => void, } const IssueStepsGallery: FC<IssueStepsGalleryProps> = (props) => { const classes = useStyles(); const [progress, setProgress] = useState<number>(0); const { dispatch } = useContext(BoardReducerContext); useEffect(() => { const allSteps = props.issue.steps; const checkedSteps = allSteps.filter(step => step.isCompleted === true); const percentage = Math.floor((checkedSteps.length / allSteps.length) * 100); if (isNaN(percentage)) { setProgress(0); } else { setProgress(percentage); } }, [props.issue.steps]); function displaySteps() { return (props.issue.steps.map((step: IStep, index: number) => { return ( <Fragment key={index}> <IssueStepData issue={props.issue} step={step} index={index} updateSteps={props.updateSteps} /> </Fragment> ); })); } function displayProgress() { return ( <div className={classes.progressContainer}> <LinearProgress className={classes.progressBar} variant="determinate" value={progress} /> <Typography className={classes.progress} variant="body2"> {`${progress}%`} </Typography> </div> ) } function onDragEnd(result: DropResult) { const { source, destination } = result; if (!destination) return; if (source.droppableId === destination.droppableId) { const reorderedSteps = reorderSteps(props.issue.steps, source.index, destination.index); const payload = { columnId: props.issue.columnId, issueId: props.issue._id, modified: { steps: reorderedSteps, }, }; dispatch({ type: ActionTypes.UpdateIssue, payload: payload }); props.updateSteps(); } else { return; } } function reorderSteps(steps: [IStep], startIndex: number, endIndex: number) { const [removed] = steps.splice(startIndex, 1); steps.splice(endIndex, 0, removed); return steps; } return ( <> <Typography className={classes.headline} component="h5" variant="h5"> Steps </Typography> {displayProgress()} <DragDropContext onDragEnd={result => onDragEnd(result)}> <Droppable droppableId={props.issue._id}> {provided => { return ( <div {...provided.droppableProps} ref={provided.innerRef}> {displaySteps()} {provided.placeholder} </div> ); }} </Droppable> </DragDropContext> <AddStepButton updateSteps={props.updateSteps} issue={props.issue} /> </> ); } export default IssueStepsGallery;
JKusiak/isshu
frontend/src/components/Issue/Message/IssueMessagesGallery.tsx
<reponame>JKusiak/isshu<filename>frontend/src/components/Issue/Message/IssueMessagesGallery.tsx import { createStyles, makeStyles, Theme } from "@material-ui/core/styles"; import React, { FC, useContext } from "react"; import { BoardReducerContext } from "../../../api/Board/GetBoard"; import { AuthUserContext } from "../../../App"; import { ActionTypes } from "../../../reducers/BoardReducer"; import { INestedIssue } from "../../../types/ModelTypes"; import AddMessageButton from "./AddMessageButton"; import IssueMessagesText from "./IssueMessagesText"; const useStyles = makeStyles((theme: Theme) => createStyles({ messagesTitle: { fontWeight: 'bold', fontSize: '16px', color: theme.palette.secondary.main, marginBottom: theme.spacing(2), }, }) ); interface IssueMessagesGalleryProps { issue: INestedIssue, addMessage: () => void, deleteMessage: () => void, } const IssueMessagesGallery: FC<IssueMessagesGalleryProps> = (props) => { const classes = useStyles(); const { dispatch } = useContext(BoardReducerContext); const { loggedInUser } = useContext(AuthUserContext); function handleSubmit(e: React.SyntheticEvent, messageContent: string) { e.preventDefault(); if (messageContent !== '') { const newMessage = { content: messageContent, sender: { _id: loggedInUser._id, name: loggedInUser.name, surname: loggedInUser.surname, }, addTime: Date.now(), }; const updatedMessages = [...props.issue.messages, newMessage]; const payload = { columnId: props.issue.columnId, issueId: props.issue._id, modified: { messages: updatedMessages, }, }; dispatch({ type: ActionTypes.UpdateIssue, payload: payload }); props.addMessage(); } } return ( <> <div className={classes.messagesTitle}>Messages</div> <AddMessageButton handleSubmit={handleSubmit} /> <IssueMessagesText issue={props.issue} deleteMessage={props.deleteMessage} displayOnly={false} /> </> ); } export default IssueMessagesGallery;
JKusiak/isshu
frontend/src/components/User/UsersGallery.tsx
import CssBaseline from '@material-ui/core/CssBaseline'; import Divider from '@material-ui/core/Divider'; import Drawer from '@material-ui/core/Drawer'; import Hidden from '@material-ui/core/Hidden'; import IconButton from '@material-ui/core/IconButton'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction'; import ListItemText from '@material-ui/core/ListItemText'; import { createStyles, makeStyles, Theme, useTheme } from '@material-ui/core/styles'; import AddIcon from '@material-ui/icons/AddOutlined'; import DeleteIcon from '@material-ui/icons/ClearOutlined'; import { FC, forwardRef, Fragment, useContext } from 'react'; import { Link } from 'react-router-dom'; import { AuthUserContext } from '../../App'; import { IUser } from '../../types/ModelTypes'; const useStyles = makeStyles((theme: Theme) => createStyles({ container: { marginTop: theme.spacing(8.5), padding: 0, }, listSubtitle: { fontSize: '24px', textAlign: 'center', padding: theme.spacing(2), // marginBottom: theme.spacing(2), fontWeight: 600, color: theme.palette.secondary.main, }, drawerPaper: { zIndex: 1, width: '270px', backgroundColor: theme.palette.primary.main, boxShadow: theme.shadows[5], }, listItem: { '&:hover': { backgroundColor: theme.palette.primary.light, boxShadow: theme.shadows[5], } }, nameLink: { color: theme.palette.secondary.main, textDecoration: 'none', '&:hover': { '& *': { fontWeight: 600 } } }, listButton: { color: theme.palette.secondary.main, }, divider: { backgroundColor: theme.palette.secondary.light, opacity: 0.2, } }), ); interface UsersGalleryProps { contributors: [IUser], otherUsers: [IUser], mobileOpen: boolean, handleSidebarToggle: () => void, addProjectToUser: (userId: string) => void, removeProjectFromUser: (userId: string) => void, window?: () => Window, } const UsersGallery: FC<UsersGalleryProps> = forwardRef((props, ref) => { const classes = useStyles(); const theme = useTheme(); const { window } = props; const container = window !== undefined ? () => window().document.body : undefined; const { loggedInUser } = useContext(AuthUserContext); function displayUsers(userType: [IUser]) { if (userType.length > 0) { return (userType.map((user: IUser) => { const fullName = `${user.name} ${user.surname}`; if (userType === props.contributors) { return ( <Fragment key={user._id}> <ListItem className={classes.listItem}> <div> <Link className={classes.nameLink} to={`/user/${user._id}`}> <ListItemText primary={fullName} /> </Link> <ListItemSecondaryAction> {loggedInUser._id !== user._id && <IconButton className={classes.listButton} edge="end" aria-label="remove-user" onClick={() => props.removeProjectFromUser(user._id)} > <DeleteIcon /> </IconButton> } </ListItemSecondaryAction> </div> </ListItem> </Fragment> ); } else { return ( <Fragment key={user._id}> <ListItem className={classes.listItem}> <div> <Link className={classes.nameLink} to={`/user/${user._id}`}> <ListItemText primary={fullName} /> </Link> <ListItemSecondaryAction> <IconButton className={classes.listButton} edge="end" aria-label="add-user" onClick={() => props.addProjectToUser(user._id)} > <AddIcon /> </IconButton> </ListItemSecondaryAction> </div> </ListItem> </Fragment> ); } })); } } const sidebar = ( <div> <List className={classes.container}> <div className={classes.listSubtitle}>Contributors</div> {displayUsers(props.contributors)} <br /> <Divider className={classes.divider} /> <div className={classes.listSubtitle}>Others</div> {displayUsers(props.otherUsers)} </List> </div> ) return ( <div> <CssBaseline /> <nav> <Hidden xsDown implementation="css"> <Drawer classes={{ paper: classes.drawerPaper, }} variant="permanent" open > {sidebar} </Drawer> </Hidden> <Hidden smUp implementation="css"> <Drawer classes={{ paper: classes.drawerPaper, }} container={container} variant="temporary" anchor={theme.direction === "rtl" ? "right" : "left"} open={props.mobileOpen} onClose={props.handleSidebarToggle} ModalProps={{ keepMounted: true }} > {sidebar} </Drawer> </Hidden> </nav> </div> ); }); export default UsersGallery;
JKusiak/isshu
frontend/src/components/Project/AddProjectModal/AddProjectModal.tsx
import { Button, Grid, Typography } from '@material-ui/core'; import Backdrop from '@material-ui/core/Backdrop'; import Fade from '@material-ui/core/Fade'; import Modal from '@material-ui/core/Modal'; import { createStyles, makeStyles, Theme } from '@material-ui/core/styles'; import React, { FC } from 'react'; import { Action, ActionTypes } from '../../../reducers/ProjectReducer'; import { IProject } from '../../../types/ModelTypes'; import DateForm from './DateForm'; import DescriptionForm from './DescriptionForm'; import NameForm from './NameForm'; const useStyles = makeStyles((theme: Theme) => createStyles({ modal: { display: 'flex', alignItems: 'center', justifyContent: 'center', }, paper: { width: '35vw', minWidth: '430px', height: 'auto', backgroundColor: theme.palette.primary.main, border: '2px solid', borderColor: theme.palette.secondary.main, borderRadius: '10px', boxShadow: theme.shadows[2], padding: theme.spacing(2, 4, 3), }, header: { display: 'grid', justifyContent: 'center', marginBottom: theme.spacing(5), color: theme.palette.secondary.main, }, form: { width: '100%', }, submit: { margin: theme.spacing(3, 0, 3), borderRadius: '10px', color: theme.palette.secondary.main, backgroundColor: theme.palette.primary.light, transition: 'all .12s linear', boxShadow: theme.shadows[2], "&:hover": { cursor: 'pointer', boxShadow: theme.shadows[5], backgroundColor: theme.palette.primary.light, }, }, wrongInput: { color: "#C62828", textAlign: "center", } })); interface AddProjectProps { onSubmit: (e: React.SyntheticEvent) => void, projectState: IProject, dispatch: React.Dispatch<Action>, isOpen: boolean, setIsOpen: React.Dispatch<React.SetStateAction<boolean>>, isValid: boolean, setIsValid: React.Dispatch<React.SetStateAction<boolean>>, errorText: string, setErrorText: React.Dispatch<React.SetStateAction<string>>, } const AddProjectModal: FC<AddProjectProps> = (props) => { const classes = useStyles(); return ( <Modal className={classes.modal} aria-labelledby="transition-modal-title" aria-describedby="transition-modal-description" open={props.isOpen} onClose={() => props.setIsOpen(false)} closeAfterTransition BackdropComponent={Backdrop} BackdropProps={{ timeout: 500, }} > <Fade in={props.isOpen}> <div className={classes.paper}> <Typography className={classes.header} component="h1" variant="h4"> Create project </Typography> <form className={classes.form} onSubmit={props.onSubmit} autoComplete="off"> <Grid container spacing={3}> <Grid item xs={12}> <NameForm dispatch={props.dispatch} setErrorText={props.setErrorText} setIsValid={props.setIsValid} /> </Grid> <Grid item xs={12}> <DescriptionForm dispatch={props.dispatch} /> </Grid> <Grid item xs={6}> <DateForm dispatch={props.dispatch} setErrorText={props.setErrorText} setIsValid={props.setIsValid} value={props.projectState.dateStart} minDate={new Date('January 1, 1900')} helperText="Beginning date of the project" actionType={ActionTypes.UpdateDateStart} /> </Grid> <Grid item xs={6}> <DateForm dispatch={props.dispatch} setErrorText={props.setErrorText} setIsValid={props.setIsValid} value={props.projectState.dateEnd} minDate={props.projectState.dateStart} helperText="Ending date of the project" actionType={ActionTypes.UpdateDateEnd} /> </Grid> </Grid> {!props.isValid && <div className={classes.wrongInput}><p>{props.errorText}</p></div>} <Button className={classes.submit} fullWidth type="submit" variant="contained" color="primary" > Create </Button> </form> </div> </Fade> </Modal> ); } export default AddProjectModal;
JKusiak/isshu
frontend/src/pages/Project/Subpages/BoardsGalleryPage.tsx
import { Card, Typography } from "@material-ui/core"; import { createStyles, makeStyles, Theme } from "@material-ui/core/styles"; import IssueIcon from '@material-ui/icons/BeenhereOutlined'; import { FC, Fragment } from "react"; import { Link, useRouteMatch } from "react-router-dom"; import AddBoard from "../../../api/Board/AddBoard"; import GetProjectInfoBanner from "../../../api/Project/GetProjectInfoBanner"; import { INestedProject } from "../../../types/ModelTypes"; const useStyles = makeStyles((theme: Theme) => createStyles({ gridContainer: { display: 'grid', width: '75%', justifyContent: 'center', gap: theme.spacing(4), gridTemplateColumns: 'repeat(auto-fill, minMax(450px, 1fr))', [theme.breakpoints.down('xs')]: { gridTemplateColumns: 'repeat(auto-fill, minMax(200px, 1fr))', width: '90%', }, margin: theme.spacing(4), }, link: { textDecoration: 'none', color: theme.palette.secondary.main, }, boardCard: { display: 'grid', gridTemplateRows: '1fr 2fr 1fr', height: '300px', [theme.breakpoints.down('xs')]: { height: '180px', }, backgroundColor: theme.palette.primary.light, transition: 'all .12s linear', boxShadow: theme.shadows[2], "&:hover": { cursor: 'pointer', boxShadow: theme.shadows[5], } }, boardName: { gridRow: 2, justifySelf: 'center', alignSelf: 'center', color: theme.palette.secondary.main, }, progressCount: { gridRow: 3, height: '20px', width: 'auto', justifySelf: 'center', alignSelf: 'center', display: 'flex', justifyContent: 'center', alignItems: 'center', fontSize: '16px', color: theme.palette.secondary.light, }, issueIcon: { marginLeft: theme.spacing(1), color: theme.palette.secondary.light, opacity: 0.7 }, }) ); interface BoardsGalleryProps { project: INestedProject; fetchBoards: () => void; } const BoardsGalleryPage: FC<BoardsGalleryProps> = (props) => { const classes = useStyles(); const { url } = useRouteMatch(); function displayBoards() { if (props.project.boards) { return (props.project.boards.map((board: any) => { return ( <Fragment key={board._id}> <Link className={classes.link} to={`${url}/${board._id}`}> <Card className={classes.boardCard}> <Typography className={classes.boardName} component="h5" variant="h5"> {board.name} </Typography> <Typography className={classes.progressCount} component="h5" variant="h5"> {`${board.totalCompleted} / ${board.totalIssues}`} <IssueIcon className={classes.issueIcon} /> </Typography> </Card> </Link> </Fragment> ); })); } } return ( <> <GetProjectInfoBanner project={props.project} /> <div className={classes.gridContainer}> <AddBoard fetchBoards={props.fetchBoards}/> {displayBoards()} </div> </> ); } export default BoardsGalleryPage;
JKusiak/isshu
frontend/src/api/Issue/Contributor/ManageContributors.tsx
<gh_stars>0 import axios from 'axios'; import { FC, useState } from 'react'; import { useParams } from 'react-router-dom'; import IssueContributorsGallery from '../../../components/Issue/Contributor/IssueContributorsGallery'; import { useMountEffect } from '../../../hooks/useMountEffect'; import { UserTemplate } from '../../../types/ModelContentTemplate'; import { INestedIssue, IUser } from '../../../types/ModelTypes'; interface ManageContributorsProps { issue: INestedIssue, displayOnly: boolean, } const ManageContributors: FC<ManageContributorsProps> = (props) => { const { projectId } = useParams<{ projectId: string }>(); const [projectContributors, setProjectContributors] = useState<[IUser]>([UserTemplate]); useMountEffect(fetchContributors); function fetchContributors() { // necessary for displaying archived issue without contributors if(!props.displayOnly) { axios.get(`/users/getUsersByProject/${projectId}`) .then(resp => { setProjectContributors(resp.data); }).catch((err) => { console.log(err); });; } } function updateContributors() { const contributorsToId = props.issue.contributors.map(contributor => contributor._id); const requestBody = { contributors: contributorsToId, } axios.post(`/issues/update/${props.issue._id}`, requestBody) .catch((err) => { console.log(err); }) } return ( <IssueContributorsGallery projectContributors={projectContributors} issue={props.issue} updateContributors={updateContributors} /> ); } export default ManageContributors;
JKusiak/isshu
frontend/src/components/Project/AddProjectModal/DateForm.tsx
<gh_stars>0 import DateFnsUtils from '@date-io/date-fns'; import { createStyles, makeStyles, Theme } from "@material-ui/core/styles"; import { KeyboardDatePicker, MuiPickersUtilsProvider } from '@material-ui/pickers'; import React, { FC } from "react"; import { Action, ActionTypes } from "../../../reducers/ProjectReducer"; const useStyles = makeStyles((theme: Theme) => createStyles({ inputField: { "& .MuiOutlinedInput-root": { color: theme.palette.secondary.main, "& .MuiOutlinedInput-notchedOutline": { borderRadius: '10px', borderColor: theme.palette.secondary.light, }, "&.Mui-focused .MuiOutlinedInput-notchedOutline": { borderColor: theme.palette.secondary.light, borderWidth: "2px", } }, // necessary for styling date picker color "& .MuiInputBase-root": { color: theme.palette.secondary.main, "& .MuiIconButton-root": { color: theme.palette.secondary.main, }, }, "& .MuiFormHelperText-root": { color: theme.palette.secondary.main, }, }, })); interface DateFormProps { dispatch: React.Dispatch<Action>, setErrorText: React.Dispatch<React.SetStateAction<string>>, setIsValid: React.Dispatch<React.SetStateAction<boolean>>, value: Date, minDate: Date, helperText: string, actionType: ActionTypes, } const DateForm: FC<DateFormProps> = (props) => { const classes = useStyles(props); return ( <MuiPickersUtilsProvider utils={DateFnsUtils}> <KeyboardDatePicker className={classes.inputField} required fullWidth format='dd/MM/yyyy' variant="inline" helperText={props.helperText} value={props.value} minDate={props.minDate} onChange={newDate => { props.dispatch({ type: props.actionType, payload: newDate }) }} /> </MuiPickersUtilsProvider> ); } export default DateForm;
JKusiak/isshu
frontend/src/api/Issue/AddIssue.tsx
import axios from 'axios'; import { FC, useContext, useState } from 'react'; import { AuthUserContext } from '../../App'; import AddIssueButton from '../../components/Issue/AddIssueButton'; import { ActionTypes } from '../../reducers/BoardReducer'; import { IColumn } from '../../types/ModelTypes'; import { BoardReducerContext } from '../Board/GetBoard'; interface AddIssueProps { column: IColumn, } const AddIssue: FC<AddIssueProps> = (props) => { const [issueName, setIssueName] = useState<string>(''); const [addMode, setAddMode] = useState<boolean>(false); const { dispatch } = useContext(BoardReducerContext); const { loggedInUser } = useContext(AuthUserContext); function onSubmit(e: React.SyntheticEvent) { e.preventDefault(); if (issueName === '') { setAddMode(false); return; } const requestBody = { name: issueName, creator: loggedInUser._id, columnId: props.column._id, } axios.post('/issues/add', requestBody) .then((res) => { setAddMode(false); dispatch({ type: ActionTypes.AddIssue, payload: res.data }) }) } return ( <AddIssueButton onSubmit={onSubmit} addMode={addMode} setAddMode={setAddMode} setIssueName={setIssueName} /> ); } export default AddIssue;
JKusiak/isshu
frontend/src/components/Project/ProjectCard.tsx
<filename>frontend/src/components/Project/ProjectCard.tsx import { Card, CardContent, CardMedia, Typography } from "@material-ui/core"; import { createStyles, makeStyles, Theme } from "@material-ui/core/styles"; import { FC } from "react"; import { Link } from 'react-router-dom'; import { IProject } from "../../types/ModelTypes"; const useStyles = makeStyles((theme: Theme) => createStyles({ cardContainer: { display: 'flex', height: 140, [theme.breakpoints.down('xs')]: { height: 100, }, width: 'auto', transition: 'all .12s linear', boxShadow: theme.shadows[2], backgroundColor: theme.palette.primary.light, "&:hover": { boxShadow: theme.shadows[5], }, }, cardContent: { display: 'flex', flexDirection: 'column', justifyContent: 'center', width: '100%', maxWidth: '260px', textDecoration: 'none', [theme.breakpoints.down('xs')]: { maxWidth: '150px', }, }, name: { height: '30px', flexShrink: 0, color: theme.palette.secondary.main, overflow: 'hidden', marginBottom: theme.spacing(0.5), }, description: { overflow: 'hidden', color: theme.palette.secondary.main, }, image: { flex: 'none', marginLeft: 'auto', height: 140, width: 140, [theme.breakpoints.down('xs')]: { height: 100, width: 100, }, filter: 'blur(0.5px)' }, } )); interface ProjectCardProps { project: IProject, imageExists: boolean, imageUrl: string, } const ProjectCard: FC<ProjectCardProps> = (props) => { const classes = useStyles(); return ( <> <Card className={classes.cardContainer}> <CardContent className={classes.cardContent} component={Link} to={`/project/${props.project._id}`}> <Typography className={classes.name} component="h5" variant="h5"> {props.project.name} </Typography> <Typography className={classes.description} variant="subtitle1" color="textSecondary"> {props.project.description} </Typography> </CardContent> <CardMedia className={classes.image} image={props.imageUrl} component={Link} to={`/project/${props.project._id}`} title="Project cover" /> </Card> </> ); } export default ProjectCard;
JKusiak/isshu
frontend/src/components/Issue/IssueData.tsx
<reponame>JKusiak/isshu import { Card, Typography } from "@material-ui/core"; import { createStyles, makeStyles, Theme } from "@material-ui/core/styles"; import CheckIcon from '@material-ui/icons/Check'; import { FC, useState } from "react"; import { Draggable } from "react-beautiful-dnd"; import { INestedIssue } from "../../types/ModelTypes"; import IssueModal from "./IssueModal"; const useStyles = makeStyles((theme: Theme) => createStyles({ issueCard: { display: 'grid', gridRows: '1fr, 1fr', height: 'auto', minHeight: '70px', maxHeight: '250px', marginBottom: theme.spacing(2), backgroundColor: theme.palette.primary.light, boxShadow: theme.shadows[2], "&:hover": { cursor: 'pointer', boxShadow: theme.shadows[5], } }, name: { gridRow: 1, margin: theme.spacing(1), fontSize: '14px', overflow: 'hidden', color: theme.palette.secondary.main, }, checkIcon: { gridRow: 2, justifySelf: 'end', marginRight: theme.spacing(1), color: theme.palette.success.dark, } } )); interface IssueDataProps { issue: INestedIssue, index: number, } const IssueData: FC<IssueDataProps> = (props) => { const classes = useStyles(); const [isModalOpen, setIsModalOpen] = useState(false); return ( <> <Draggable draggableId={props.issue._id} index={props.index}> {(provided) => { return ( <> <Card className={classes.issueCard} onClick={() => setIsModalOpen(true)} ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} style={{ ...provided.draggableProps.style }} > <Typography className={classes.name} component='h6' variant='h6'> {props.issue.name} </Typography> {props.issue.isFinished && <CheckIcon className={classes.checkIcon} />} </Card> <IssueModal issue={props.issue} isIssueModalOpen={isModalOpen} setIssueModalOpen={setIsModalOpen} displayOnly={false} /> </> ); }} </Draggable> </> ); } export default IssueData;
JKusiak/isshu
frontend/src/App.tsx
import CssBaseline from '@material-ui/core/CssBaseline'; import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles'; import axios from 'axios'; import React, { createContext, useState } from 'react'; import { Helmet } from 'react-helmet'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import GetHomePage from './api/Authentication/GetHomePage'; import { getLoggedInUser } from './api/User/GetLoggedInUser'; import Navbar from './layout/Navbar'; import LoginPage from './pages/LoginPage'; import ProjectPage from './pages/Project/ProjectPage'; import RegisterPage from './pages/RegisterPage'; import TitlePage from './pages/TitlePage'; import UserPage from './pages/UserPage'; import { darkPalette, getAntiShadows, lightPalette, overrides } from './resources/theme'; import { JWTUserTemplate } from './types/ModelContentTemplate'; import { JWTTokenUser } from './types/ModelTypes'; export const DarkModeContext = createContext<{ darkMode: boolean, setDarkMode: React.Dispatch<React.SetStateAction<boolean>> }>({} as any); export const IsLoggedInContext = createContext<{ isLoggedIn: boolean, setLoggedIn: React.Dispatch<React.SetStateAction<boolean>> }>({} as any); export const AuthUserContext = createContext<{ loggedInUser: JWTTokenUser, setLoggedInUser: React.Dispatch<React.SetStateAction<JWTTokenUser>> }>({} as any); const App = () => { const [isLoggedIn, setLoggedIn] = useState<boolean>( localStorage.getItem('token') ? true : false ); const [darkMode, setDarkMode] = useState<boolean>( localStorage.getItem('darkMode') === 'true' ? true : false ); const [loggedInUser, setLoggedInUser] = useState<JWTTokenUser>( isLoggedIn ? getLoggedInUser() : JWTUserTemplate ); const defaultTheme = createMuiTheme(); const theme = createMuiTheme({ palette: darkMode ? darkPalette : lightPalette, shadows: darkMode ? getAntiShadows() : defaultTheme.shadows, overrides: darkMode ? overrides : undefined }); axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('token')}`; axios.defaults.baseURL = 'http://localhost:5000/'; return ( <ThemeProvider theme={theme}> <DarkModeContext.Provider value={{ darkMode, setDarkMode }}> <IsLoggedInContext.Provider value={{ isLoggedIn, setLoggedIn }}> <AuthUserContext.Provider value={{ loggedInUser, setLoggedInUser }}> <CssBaseline> <Helmet> <title>Isshu.</title> <meta name="description" content="Minimalistic bug tracking tool for small sized teams" /> <style>{`body { background-color: ${theme.palette.primary.main}; }`}</style> </Helmet> <Router> <Navbar /> <Switch> <Route path="/home"> <GetHomePage /> </Route> <Route path="/project/:projectId"> <ProjectPage /> </Route> <Route path="/login"> <LoginPage /> </Route> <Route path="/register"> <RegisterPage /> </Route> <Route path="/user/:userId"> <UserPage /> </Route> <Route path="/"> <TitlePage /> </Route> </Switch> </Router> </CssBaseline> </AuthUserContext.Provider> </IsLoggedInContext.Provider> </DarkModeContext.Provider> </ThemeProvider> ); } export default App;
JKusiak/isshu
frontend/src/components/Project/AddProjectModal/DescriptionForm.tsx
import { TextField } from '@material-ui/core'; import { createStyles, makeStyles, Theme } from "@material-ui/core/styles"; import React, { FC } from "react"; import { Action, ActionTypes } from "../../../reducers/ProjectReducer"; const useStyles = makeStyles((theme: Theme) => createStyles({ inputField: { "& .MuiOutlinedInput-root": { color: theme.palette.secondary.main, "& .MuiOutlinedInput-notchedOutline": { borderRadius: '10px', borderColor: theme.palette.secondary.light, }, "&.Mui-focused .MuiOutlinedInput-notchedOutline": { borderColor: theme.palette.secondary.light, borderWidth: "2px", } }, }, })); interface DescriptionProps { dispatch: React.Dispatch<Action>, } const DescriptionForm: FC<DescriptionProps> = (props) => { const classes = useStyles(props); return ( <TextField className={classes.inputField} required fullWidth variant="outlined" name="description" id="description" placeholder="Description" autoComplete="description" multiline={true} onChange={e => { props.dispatch({ type: ActionTypes.UpdateDescription, payload: e.target.value }) }} /> ); } export default DescriptionForm;
JKusiak/isshu
frontend/src/components/Column/DeleteColumnButton.tsx
<gh_stars>0 import { createStyles, IconButton, makeStyles, Theme } from "@material-ui/core"; import DeleteIcon from '@material-ui/icons/ClearOutlined'; import { FC, useContext, useState } from "react"; import { BoardReducerContext } from "../../api/Board/GetBoard"; import { ActionTypes } from "../../reducers/BoardReducer"; import { IColumn } from "../../types/ModelTypes"; import ConfirmationModal from "../Commons/ConfirmationModal"; const useStyles = makeStyles((theme: Theme) => createStyles({ button: { padding: theme.spacing(1), }, icon: { color: theme.palette.secondary.light, }, })) interface DeleteColumnButtonProps { column: IColumn, deleteColumn: () => void, } const DeleteColumnButton: FC<DeleteColumnButtonProps> = (props) => { const classes = useStyles(); const [openModal, setOpenModal] = useState(false); const { dispatch } = useContext(BoardReducerContext); function handleDelete() { dispatch({ type: ActionTypes.DeleteColumn, payload: props.column._id }); props.deleteColumn(); } return ( <> <IconButton className={classes.button} onClick={() => { setOpenModal(true) }}> <DeleteIcon className={classes.icon} /> </IconButton> <ConfirmationModal handleConfirm={handleDelete} open={openModal} setOpen={setOpenModal} /> </> ); } export default DeleteColumnButton
JKusiak/isshu
frontend/src/api/Column/AddColumn.tsx
<reponame>JKusiak/isshu import axios from 'axios'; import { useContext, useState } from 'react'; import { useParams } from 'react-router-dom'; import AddColumnButton from '../../components/Column/AddColumnButton'; import { ActionTypes } from '../../reducers/BoardReducer'; import { BoardReducerContext } from '../Board/GetBoard'; const AddColumn = () => { const { boardId } = useParams<{ boardId: string }>(); const [columnName, setColumnName] = useState<string>(''); const { dispatch } = useContext(BoardReducerContext); function onSubmit(e: React.SyntheticEvent) { // e.preventDefault(); const requestBody = { columnName: columnName, boardId: boardId, }; axios.post('/columns/add', requestBody) .then((resp) => { setColumnName(''); const payload = { ...resp.data, issues: [], } dispatch({ type: ActionTypes.AddColumn, payload: payload }) }) } return ( <> <AddColumnButton onSubmit={onSubmit} setColumnName={setColumnName} /> </> ); } export default AddColumn;
JKusiak/isshu
frontend/src/reducers/BoardReducer.tsx
<reponame>JKusiak/isshu import { INestedBoard } from "../types/ModelTypes"; // helper function for ensuring the find function result never equals undefined export function ensure<T>(argument: T | undefined | null, message: string = 'This value was promised to be there.'): T { if (argument === undefined || argument === null) { throw new TypeError(message); } return argument; } export enum ActionTypes { FetchData = 'FETCH DATA', UpdateBoard = 'UPDATE BOARD', AddColumn = 'ADD COLUMN', DeleteColumn = 'DELETE COLUMN', UpdateColumn = 'UPDATE COLUMN', AddIssue = 'ADD ISSUE', ArchiveIssue = 'ARCHIVE ISSUE', UpdateIssue = 'UPDATE ISSUE', ChangeColumns = 'REMOVE FROM COLUMN', ReorderColumn = 'REORDER COLUMN' } export type Action = { type: ActionTypes, payload: any, } export const boardContentReducer = (state: INestedBoard, action: Action) => { const { type, payload } = action; switch (type) { case ActionTypes.FetchData: return payload case ActionTypes.UpdateBoard: return { ...state, name: payload, } case ActionTypes.AddColumn: return { ...state, columns: [...state.columns, payload], } case ActionTypes.DeleteColumn: return { ...state, columns: state.columns.filter(column => column._id !== payload), } case ActionTypes.UpdateColumn: return { ...state, columns: state.columns.map(column => { if (column._id === payload.columnId) { column.name = payload.newName } return column; }) } case ActionTypes.AddIssue: return { ...state, columns: state.columns.map(column => { if (column._id === payload.columnId) { column.issues.push(payload) } return column; }) } case ActionTypes.ArchiveIssue: return { ...state, columns: state.columns.map(column => { if (column._id === payload.columnId) { const newIssues = column.issues.filter(issue => issue._id !== payload.issueId); return { ...column, issues: newIssues, } } return column; }) } case ActionTypes.UpdateIssue: return { ...state, columns: state.columns.map(column => { if (column._id === payload.columnId) { column.issues.map(issue => { if (issue._id === payload.issueId) { if (payload.modified.name) issue.name = payload.modified.name; if (payload.modified.description) issue.description = payload.modified.description; if (payload.modified.columnId) issue.columnId = payload.modified.columnId; if (payload.modified.steps) issue.steps = payload.modified.steps; if (payload.modified.messages) issue.messages = payload.modified.messages; if (payload.modified.tags) issue.tags = payload.modified.tags; if (payload.modified.contributors) issue.contributors = payload.modified.contributors; if (payload.modified.attachments) issue.attachments = payload.modified.attachments; if (typeof payload.modified.isFinished !== 'undefined') issue.isFinished = payload.modified.isFinished; } return issue; }) } return column; }) } case ActionTypes.ChangeColumns: const issueColumn = ensure(state.columns.find(column => column._id === payload.oldColumnId)); const movedIssue = ensure(issueColumn.issues.find(issue => issue._id === payload.issueId)); movedIssue.columnId = payload.newColumnId; return { ...state, columns: state.columns.map(column => { if (column._id === payload.oldColumnId) { const newIssues = column.issues.filter(issue => issue._id !== payload.issueId); return { ...column, issues: newIssues, } } else if (column._id === payload.newColumnId) { if (movedIssue !== undefined) { column.issues.push(movedIssue) } } return column; }) } case ActionTypes.ReorderColumn: return { ...state, columns: state.columns.map(column => { if (column._id === payload.columnId) { return { ...column, issues: payload.reorderedIssues } } return column; }) } default: return state } }
JKusiak/isshu
frontend/src/api/Project/ManageProjectCard.tsx
import axios from "axios"; import { FC, useContext, useEffect, useState } from "react"; import { AuthUserContext } from "../../App"; import ProjectCard from "../../components/Project/ProjectCard"; import { IProject } from "../../types/ModelTypes"; interface ManageGalleryProjectProps { project: IProject, } const ManageGalleryProject: FC<ManageGalleryProjectProps> = (props) => { const [imageExists, setImageExists] = useState<boolean>(false); const [imageUrl, setImageUrl] = useState<string>(''); const { loggedInUser } = useContext(AuthUserContext); // when props are loaded, fetches image from the server useEffect(() => { checkIfExists(); }, [props.project]); function checkIfExists() { // substitutes backslash (/) with %2f as the whole path is passed as one parameter const path = `uploads%2forganization-${loggedInUser.organizationId}%2fprojects-covers%2f${props.project._id}.jpg`; axios.get(`/uploads/get/${path}`) .then((resp) => { setImageExists(resp.data); if (resp.data) { const adjustedPath = path.replaceAll('%2f', '/'); setImageUrl(`http://localhost:5000/${adjustedPath}`); } }).catch((err) => { console.log(err); }) } return ( <> <ProjectCard project={props.project} imageExists={imageExists} imageUrl={imageUrl} /> </> ); } export default ManageGalleryProject;
JKusiak/isshu
frontend/src/api/Board/DeleteBoard.tsx
import axios from 'axios'; import { useHistory, useParams } from "react-router-dom"; import DeleteBoardButton from '../../components/Board/DeleteBoardButton'; const DeleteBoard = () => { const { boardId } = useParams<{ boardId: string }>(); const { projectId } = useParams<{ projectId: string }>(); let history = useHistory(); function deleteBoard() { axios.delete(`/boards/delete/${boardId}`) .catch((err) => { console.log(err); }); history.push(`/project/${projectId}`); } return ( <> <DeleteBoardButton deleteBoard={deleteBoard} /> </> ); } export default DeleteBoard;
JKusiak/isshu
frontend/src/components/Issue/ArchivedIssueCard.tsx
import { Card, CardContent, createStyles, makeStyles, Theme, Typography } from "@material-ui/core"; import { FC, useState } from "react"; import { INestedIssue } from "../../types/ModelTypes"; import IssueModal from "./IssueModal"; const useStyles = makeStyles((theme: Theme) => createStyles({ cardContainer: { display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: 140, [theme.breakpoints.down('xs')]: { height: 100, }, width: 'auto', transition: 'all .12s linear', boxShadow: theme.shadows[2], backgroundColor: theme.palette.primary.light, "&:hover": { boxShadow: theme.shadows[5], cursor: 'pointer', }, }, cardContent: { textAlign: 'center', width: '100%', maxWidth: '260px', overflow: 'hidden', }, cardName: { [theme.breakpoints.down('xs')]: { fontSize: '18px', }, color: theme.palette.secondary.main, }, cardDescription: { color: theme.palette.secondary.main, }, }) ); interface ArchivedIssueCardProps { issue: INestedIssue, } const ArchivedIssueCard: FC<ArchivedIssueCardProps> = (props) => { const classes = useStyles(); const [isModalOpen, setModalOpen] = useState(false); return ( <> <Card className={classes.cardContainer} onClick={() => setModalOpen(true)}> <CardContent className={classes.cardContent}> <Typography className={classes.cardName} component="h5" variant="h5"> {props.issue.name} </Typography> <Typography className={classes.cardDescription}> {props.issue.description} </Typography> </CardContent> </Card> <IssueModal issue={props.issue} isIssueModalOpen={isModalOpen} setIssueModalOpen={setModalOpen} displayOnly={true} /> </> ); } export default ArchivedIssueCard;
JKusiak/isshu
frontend/src/components/Organization/InvitationsGallery.tsx
import { Typography } from "@material-ui/core"; import { createStyles, makeStyles, Theme } from "@material-ui/core/styles"; import { FC, Fragment } from "react"; import ManageInvitation from "../../api/Organization/ManageInvitation"; const useStyles = makeStyles((theme: Theme) => createStyles({ header: { textAlign: 'center', fontSize: '20px', color: theme.palette.secondary.main, marginTop: theme.spacing(4), marginBottom: theme.spacing(2), }, buttons: { marginLeft: 'auto', } }) ); interface InvitationsGalleryProps { user: any, } const InvitationsGallery: FC<InvitationsGalleryProps> = (props) => { const classes = useStyles(); function displayInvitations() { if (props.user.invitations.length > 0) { return (props.user.invitations.map((invite: any, index: number) => { return ( <Fragment key={index}> <ManageInvitation invite={invite} user={props.user} /> </Fragment> ); })); } else { return ( <Typography className={classes.header}> You currently have no invitations to organizations </Typography> ) } } return ( <> <div > {displayInvitations()} </div> </> ); } export default InvitationsGallery;
JKusiak/isshu
frontend/src/components/Board/AddBoardButton.tsx
import { ClickAwayListener, IconButton, TextField } from '@material-ui/core'; import Card from '@material-ui/core/Card'; import { createStyles, makeStyles, Theme } from '@material-ui/core/styles'; import Typography from '@material-ui/core/Typography'; import AddIcon from '@material-ui/icons/AddOutlined'; import React, { FC, SetStateAction } from 'react'; const useStyles = makeStyles((theme: Theme) => createStyles({ boardCard: { display: 'flex', height: '300px', [theme.breakpoints.down('xs')]: { height: '180px', }, justifyContent: 'center', alignItems: 'center', transition: 'all .12s linear', backgroundColor: theme.palette.primary.light, boxShadow: theme.shadows[2], "&:hover": { boxShadow: theme.shadows[5], cursor: 'pointer', }, }, inputField: { "& .MuiOutlinedInput-root": { color: theme.palette.secondary.main, "& .MuiOutlinedInput-notchedOutline": { borderRadius: '10px', borderColor: theme.palette.secondary.light, }, "&.Mui-focused .MuiOutlinedInput-notchedOutline": { borderColor: theme.palette.secondary.light, borderWidth: "2px", } }, }, icon: { fontSize: '35px', color: theme.palette.secondary.main, }, })); interface AddBoardModalProps { onSubmit: (e: React.SyntheticEvent<Element, Event>) => void, addMode: boolean, setAddMode: React.Dispatch<SetStateAction<boolean>>, setBoardName: React.Dispatch<SetStateAction<string>>, } const AddBoardModal: FC<AddBoardModalProps> = (props) => { const classes = useStyles(); return ( <> <div onClick={() => props.setAddMode(true)}> <ClickAwayListener onClickAway={() => props.setAddMode(false)}> <Card className={classes.boardCard}> <Typography component="h5" variant="h5"> {props.addMode && <form onSubmit={props.onSubmit} autoComplete="off"> <TextField className={classes.inputField} required autoFocus variant='outlined' name="boardName" id="boardName" placeholder="Board name" autoComplete="board-name" onChange={e => { props.setBoardName(e.target.value); }} /> <IconButton type="submit"> <AddIcon className={classes.icon} /> </IconButton> </form> } {!props.addMode && <AddIcon className={classes.icon} /> } </Typography> </Card> </ClickAwayListener> </div> </> ); } export default AddBoardModal;
JKusiak/isshu
frontend/src/api/Board/GetBoardsGallery.tsx
<reponame>JKusiak/isshu import axios from "axios"; import { useState } from "react"; import { useParams } from "react-router-dom"; import { useMountEffect } from "../../hooks/useMountEffect"; import BoardsGallery from "../../pages/Project/Subpages/BoardsGalleryPage"; import { NestedProjectTemplate } from "../../types/ModelContentTemplate"; import { INestedProject } from "../../types/ModelTypes"; const GetBoardsGallery = () => { const { projectId } = useParams<{ projectId: string }>(); const [project, setProject] = useState<INestedProject>(NestedProjectTemplate); useMountEffect(fetchProject); function fetchProject() { axios.get(`/projects/getProgress/${projectId}`) .then((res) => { setProject(res.data); }).catch((err) => { console.log(err); }); } return ( <> <BoardsGallery project={project} fetchBoards={fetchProject} /> </> ); } export default GetBoardsGallery;