session.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. export default{
  2. workout: null,
  3. pastSessions: null,
  4. exerciseIndex: 0,
  5. currentSession: null,
  6. render: async function(workout){
  7. this.workout = workout;
  8. this.pastSessions = await this.getPastSessions(workout.id);
  9. this.createNewSession(workout);
  10. this.changeExercise(0);
  11. },
  12. getPastSessions: async function(id){
  13. const sessions = await fetch(`/session/${id}`, {
  14. method: "GET",
  15. headers: {
  16. "Content-Type": "application/json"
  17. }
  18. });
  19. if(sessions.error){
  20. notify("error", "ERROR: Unable to retrieve past workouts");
  21. return [];
  22. }
  23. return await sessions.json();
  24. },
  25. createNewSession: function(workout){
  26. this.currentSession = {
  27. workout: workout.id,
  28. start: new Date(),
  29. notes: "",
  30. exercises: []
  31. };
  32. localStorage.setItem(workout.id, JSON.stringify(this.currentSession));
  33. },
  34. changeExercise: function(num){
  35. this.exerciseIndex += num;
  36. let exercise = null;
  37. if(this.currentSession[this.exerciseIndex]){
  38. exercise = currentSession[this.exerciseIndex];
  39. }else{
  40. const workoutExercise = this.workout.exercises[this.exerciseIndex];
  41. exercise = {
  42. exerciseId: workoutExercise._id,
  43. name: workoutExercise.name,
  44. type: workoutExercise.type,
  45. notes: "",
  46. sets: this.getPastSets(workoutExercise._id)
  47. }
  48. this.currentSession.exercises.push(exercise);
  49. }
  50. document.getElementById("sessionExerciseName").textContent = exercise.name;
  51. switch(exercise.type){
  52. case "weights": this.displayWeightSets(exercise);
  53. }
  54. },
  55. displayWeightSets: function(exercise){
  56. const container = document.getElementById("sessionSets");
  57. const weightTemplate = document.getElementById("weightSet").content.children[0];
  58. for(let i = 0; i < exercise.sets.length; i++){
  59. const set = weightTemplate.cloneNode(true);
  60. set.querySelector("h3").textContent = `Set #${i+1}`;
  61. set.querySelector(".weightSetWeight").value = exercise.sets[i].weight;
  62. set.querySelector(".weightSetReps").value = exercise.sets[i].reps;
  63. container.appendChild(set);
  64. }
  65. },
  66. getPastSets: function(id){
  67. for(let i = 0; i < this.pastSessions.length; i++){
  68. for(let j = 0; j < this.pastSessions[i].exercises.length; j++){
  69. if(this.pastSessions[i].exercises[j].exerciseId === id){
  70. return this.pastSessions[i].exercises[j].sets;
  71. }
  72. }
  73. }
  74. return [{weight: 0, reps: 0}, {weight: 0, reps: 0}, {weight: 0, reps: 0}];
  75. }
  76. }