session2.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. export default {
  2. workout: null,
  3. exerciseIndex: 0,
  4. pastSessions: null,
  5. previousExercise: null,
  6. render: async function(workout){
  7. this.workout = workout;
  8. this.pastSessions = await this.getPastSessions(workout.id);
  9. this.switchExercise(0);
  10. },
  11. getPastSessions: async function(id){
  12. const sessions = await fetch(`/session/${id}`, {
  13. method: "GET",
  14. headers: {
  15. "Content-Type": "application/json"
  16. }
  17. });
  18. if(sessions.error){
  19. notify("error", "ERROR: Unable to retrieve past workouts");
  20. return [];
  21. }
  22. return await sessions.json();
  23. },
  24. switchExercise: function(num){
  25. this.exerciseIndex += num;
  26. this.previousExercise = this.findPreviousExercise();
  27. this.renderPreviousSessionData();
  28. this.renderExercise();
  29. },
  30. findPreviousExercise: function(){
  31. for(let i = 0; i < this.pastSessions.length; i++){
  32. for(let j = 0; j < this.pastSessions[i].exercises.length; j++){
  33. const exercise = this.pastSessions[i].exercises[j];
  34. if(exercise.exerciseId === this.workout.exercises[this.exerciseIndex]){
  35. return exercise;
  36. }
  37. }
  38. }
  39. return null;
  40. },
  41. renderExercise: function(){
  42. const container = document.getElementById("sessionSets");
  43. const weightTemplate = document.getElementById("weightSet").content.children[0];
  44. let setCount = 0;
  45. const title = document.createElement("h1");
  46. title.textContent = this.workout.exercises[this.exerciseIndex].name;
  47. container.appendChild(title);
  48. if(this.previousExercise){
  49. setCount = this.previousExercise.sets.length;
  50. }else{
  51. setCount = 3;
  52. }
  53. for(let i = 0; i < setCount; i++){
  54. const weightSet = weightTemplate.cloneNode(true);
  55. weightSet.querySelector("h3").textContent = `Set #${i+1}`;
  56. if(this.previousExercise){
  57. weightSet.querySelector(".weightSetWeight").value = this.previousExercise.sets[i].weight;
  58. }
  59. weightSet.querySelector(".weightSetWeight").addEventListener("change", this.update.bind(this));
  60. container.appendChild(weightSet);
  61. }
  62. },
  63. renderPreviousSessionData: function(){
  64. const container = document.getElementById("previousSession");
  65. if(!this.previousExercise){
  66. const p = document.createElement("p");
  67. p.id = "noSessionText";
  68. p.textContent = "No previous workout data to display";
  69. container.appendChild(p);
  70. }else{
  71. console.log("not implemented");
  72. }
  73. },
  74. update: function(){
  75. console.log("something");
  76. }
  77. }