Squad.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import React, { useState } from 'react';
  2. import Member from './Member';
  3. import empty from '../../img/empty.svg';
  4. import Mech from '../../Mech';
  5. import MechObserver from '../../MechObserver';
  6. import { isEmptySlot } from '../../MechUtils';
  7. function instead<T>(array: T[], index: number, newItem: T): T[] {
  8. return array.map((item, i) => {
  9. if (i === index) {
  10. return newItem;
  11. } else {
  12. return item;
  13. }
  14. });
  15. }
  16. function hasFreeSlot(squad: Mech[]) {
  17. return squad.some(isEmptySlot)
  18. }
  19. function isSquadFull(squad: Mech[]) {
  20. return !hasFreeSlot(squad);
  21. }
  22. function Squad({pickObservers} : {pickObservers: {[key: string] : MechObserver}}) {
  23. const placeHolder: Mech = {id: -1, name: 'Empty slot', kind: '_', health: 0, move: 0, squad: '_', img: empty};
  24. const [squadMechs, setSquadMechs] = useState([placeHolder, placeHolder, placeHolder]);
  25. const [squadName, setSquadName] = useState('Custom squad');
  26. function putInFreeSlot(mech: Mech, squad: Mech[]): Mech[] {
  27. const freeSlotIndex = squad.findIndex(isEmptySlot);
  28. console.log('Next free slot : ', freeSlotIndex);
  29. return instead(squad, freeSlotIndex, mech);
  30. }
  31. function addToSquad(mech: Mech) {
  32. console.log("New mech to add :", mech)
  33. if (isSquadFull(squadMechs)) {
  34. console.log("Squad is full, sorry");
  35. return;
  36. }
  37. setSquadMechs(putInFreeSlot(mech, squadMechs));
  38. }
  39. function removeFromSquad(index: number) {
  40. setSquadMechs(instead(squadMechs, index, placeHolder));
  41. }
  42. pickObservers.addWhenPicked = addToSquad;
  43. return (
  44. <article className='custom-squad'>
  45. <h2>{squadName}</h2>
  46. <div className='mech-members'>
  47. {squadMechs.map((m, index) => (
  48. <Member key={index} mech={m} remover={() => removeFromSquad(index)}/>
  49. ))}
  50. </div>
  51. <div className='squad-description'>
  52. <label htmlFor='squad-name-field-id'>Squad name</label>
  53. <input id='squad-name-field-id' defaultValue='Custom squad' value={squadName} onChange={change => setSquadName(change.target.value)}/>
  54. <label htmlFor='squad-description-field-id'>Squad description</label>
  55. <textarea id='squad-description-field-id' defaultValue='A powerful squad.'/>
  56. </div>
  57. </article>
  58. )
  59. }
  60. export default Squad;