Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Victoria Sawchuk -- Carets #25

Open
wants to merge 38 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
3a6cd61
Load all trips in a table when user clicks 'All Trips' link
vsawchuk Nov 28, 2017
7cc1e20
Show trip details from trip link
vsawchuk Nov 28, 2017
10750eb
Dynamically add form when user clicks 'Add trip' link
vsawchuk Nov 28, 2017
23fe9bb
User can add trips via a form
vsawchuk Nov 28, 2017
a190df7
Use backbone to listen for updates to the trip list
vsawchuk Nov 29, 2017
82228d6
Add form for trip reservations
vsawchuk Nov 29, 2017
7c18102
Add trip id to reservation form
vsawchuk Nov 29, 2017
15b75b4
Add fetchTrips to prevent list of trips from loading automatically
vsawchuk Nov 29, 2017
ec6dd6e
Add client side validation for adding a trip
vsawchuk Nov 30, 2017
7b14979
Remove extraneous parameter
vsawchuk Nov 30, 2017
7ffc290
Modify listener for clearMessages to clear any time the user exits th…
vsawchuk Nov 30, 2017
a499b80
add saveReservation method and client side reservation validation
vsawchuk Nov 30, 2017
dd03754
Allow user to submit a reservation, redirect back to the individual t…
vsawchuk Nov 30, 2017
e74036d
Add sorting capability on trips table with styling to indicate sort c…
vsawchuk Dec 1, 2017
5620f51
Add dynamic form for filtering input that is only visible when approp…
vsawchuk Dec 1, 2017
0ee18fe
Add ability to filter by text fields
vsawchuk Dec 1, 2017
82d963b
Add filtering capability by numeric values for weeks and cost
vsawchuk Dec 1, 2017
266e7b2
Squash bug: all trips not loading from any other page when the tripLi…
vsawchuk Dec 1, 2017
63cd21c
Change trigger to function call
vsawchuk Dec 1, 2017
777f945
Split screen when click on anything that is not all trips
vsawchuk Dec 1, 2017
e941cbd
Highlight current selected trip in all trips table
vsawchuk Dec 1, 2017
99850a4
Get filter form onto left half of screen
vsawchuk Dec 1, 2017
237bc43
Give appropriate height to status messges
vsawchuk Dec 1, 2017
b8db86a
Add header to reservation form
vsawchuk Dec 1, 2017
17e8c82
Make table of all trips scrollable, separate from the right half of t…
vsawchuk Dec 1, 2017
f110f04
Make trip details scrollable separate from table
vsawchuk Dec 1, 2017
936a87e
Change trip details scroll to only scroll the about paragraph
vsawchuk Dec 1, 2017
f16cbd8
Display cost as money in table
vsawchuk Dec 1, 2017
2711296
display cost as money in trip description
vsawchuk Dec 1, 2017
9ebb6e0
Make add trip a modal that shows errors appropriately
vsawchuk Dec 2, 2017
5da855f
Change width from 5 columns to 6 for split screen elements
vsawchuk Dec 2, 2017
1da9f10
Change table cell overflow
vsawchuk Dec 2, 2017
3a39956
Refactor form error display
vsawchuk Dec 4, 2017
ae3dd73
Refactor display of status messages
vsawchuk Dec 4, 2017
9c5896b
Group handlers for click event on #load-trips
vsawchuk Dec 4, 2017
3507b04
Refactored functions to increase readability, added url to reservatio…
vsawchuk Dec 4, 2017
af702eb
Remove extraneous line
vsawchuk Dec 4, 2017
298a87b
Chain adding and removing classes
vsawchuk Dec 4, 2017
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 70 additions & 2 deletions dist/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,81 @@
<meta charset="utf-8">
<title>My JavaScript App</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
</head>
<body>
<header>

<h1 class='columns small-6'>BackTREK</h1>
<span id='buttons' class='float-right'>
<a id='load-trips' class='button' href='#'>All Trips</a>
<a id='add-trip' class='button' href="#add-trip-modal" rel="modal:open">Add Trip</a>
</span>
</header>
<main>
<main class='row clear'>
<section id="status-messages">
<button class="clear float-right">[x]</button>
<ul></ul>
</section>

<section>
<div id='filter-container' class='columns small-12'>
<form id='filter' class='columns small-5'>
<select id='filter-select' class='width35'>
<script type="text/template" id="filter-trips-template">
<option value='<%- item %>'><%- capitalized %></option>
</script>
</select>
<input type='text' id='filter-input' class='width55'/>
</form>
</div>
<table class='left-half'>
<thead class='table'>
<tr id='trip-headers'>
<script type="text/template" id="trip-headers-template">
<th class='sort <%- header %>'><a><%- header %></a><span class='sortorder'></span></th>
</script>
</tr>
</thead>
<tbody id='all-trips'>
<script type="text/template" id="all-trips-template">
<tr>
<td><a id=<%- id %> class='trip' href='#'><%- name %></a></td>
<td><%- category %></td>
<td><%- continent %></td>
<td><%- weeks %></td>
<td>$<%- cost.toFixed(2) %></td>
</tr>
</script>
</tbody>
</table>
</section>


<section id='show-trip' class='content right-half'>
<script type="text/template" id="show-trip-template">
<h3><%- name %></h3>
<a id='reserve' tripid=<%- id %> href='#'>Reserve</a>
<h5><%- weeks %> week<%- plural %></h5>
<h5>$<%- cost.toFixed(2) %></h5>
<p class='scrollable'><%- about %></p>
</script>
</section>
<section>
<h2 id='reserve-trip-header' class='content right-half'></h2>
<form id='reserve-trip-form' class='content right-half'>
</form>
</section>
<section class='modal' id='add-trip-modal'>
<h2 id='add-trip-header' class='content'></h2>
<form id='add-trip-form' class='content'>
<script type="text/template" id="form-template">
<section>
<label><%- field %><span id=<%- `label-${field}` %>></span></label>
<input type='text' id=<%- field %> name=<%- field %> />
</section>
</script>
</form>
</section>
</main>
<footer>

Expand Down
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"dependencies": {
"backbone": "^1.3.3",
"jquery": "^3.2.1",
"jquery-modal": "^0.9.1",
"underscore": "^1.8.3"
}
}
249 changes: 247 additions & 2 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,258 @@
// Vendor Modules
import $ from 'jquery';
import _ from 'underscore';
import 'jquery-modal';

// CSS
import './css/foundation.css';
import './css/style.css';

console.log('it loaded!');
// Models and Collections
import Trip from './app/models/trip';
import TripList from './app/collections/trip_list';
import Reservation from './app/models/reservation';

const tripList = new TripList();
let referenceList = new TripList();
let allTripsTemplate;
let tripHeadersTemplate;
let showTripTemplate;
let formTemplate;
let filterTemplate;
let filterCategory;

const url = 'https://ada-backtrek-api.herokuapp.com/trips';
const tableFields = ['name', 'category', 'continent', 'weeks', 'cost'];
const addTripFields = ['name', 'category', 'continent', 'weeks', 'cost', 'about'];
const reservationFields = ['name', 'age', 'email'];

const fetchTrips = function fetchTrips() {
tripList.fetch();
}

const syncReferenceList = function syncReferenceList() {
referenceList.add(tripList.models);
loadTripsTable(referenceList);
}

const renderTrips = function renderTrips(list) {
$('#all-trips').empty();
list.forEach((trip) => $('#all-trips').append(allTripsTemplate(trip.attributes)));
};

const loadTripsTable = function loadTripsTable(list) {
$('#trip-headers').html('');
clearContent();
tableFields.forEach((field) => $('#trip-headers').append(tripHeadersTemplate({header: field})));
renderTrips(list);
loadFilters();
};

const loadFilters = function loadFilters() {
$('#filter-select').empty();
$('#filter').show();
tableFields.forEach((filter) => {
const capitalFilter = filter.charAt(0).toUpperCase() + filter.slice(1);
$('#filter-select').append(filterTemplate({item: filter, capitalized: capitalFilter}))
});
$('#filter-select').prop('selectedIndex', -1);
};

const setFilterCategory = function setFilterCategory() {
const capital = $('#filter-select').find(':selected').text();
filterCategory = capital.charAt(0).toLowerCase() + capital.slice(1);
};

const filterTrips = function filterTrips(event) {
let filterInput = event.currentTarget.value;
let filteredTrips = [];
switch (filterCategory) {
case 'name':
case 'category':
case 'continent':
filterInput = filterInput.toLowerCase();
filteredTrips = tripList.models.filter(trip => trip.attributes[filterCategory].toLowerCase().includes(filterInput));
referenceList.reset(filteredTrips);
renderTrips(referenceList);
break;
case 'weeks':
case 'cost':
filterInput = parseFloat(filterInput);
filteredTrips = tripList.models.filter(trip => trip.attributes[filterCategory] <= filterInput);
referenceList.reset(filteredTrips);
renderTrips(referenceList);
break;
default:
break;
}
};

const splitScreen = function splitScreen() {
$('.left-half').addClass('columns small-6 float-left');
$('.right-half').addClass('columns small-6 float-right');
};

const unSplitScreen = function unSplitScreen() {
$('.left-half, .right-half').removeClass('columns small-6 float-left');
$('#filter-input').val('');
}

const highlightCurrentTrip = function highlightCurrentTrip(event) {
const currentRow = $(event.currentTarget).parent().parents('tr:first').children();
$('#all-trips tr td').removeClass('current-trip');
$(currentRow).addClass('current-trip');
};

const showTrip = function showTrip(event) {
$('#show-trip').addClass('show-right').siblings().removeClass('show-right');
highlightCurrentTrip(event);
clearContent();
splitScreen();
const tripUrl = `${url}/${event.currentTarget.id}`;
$.get(tripUrl, (response) => {
response.plural = (response.weeks === 1) ? '' : 's';
$('#show-trip').append(showTripTemplate(response));
})
};

const clearContent = function clearContent() {
$('.content').empty();
};

const clearMessages = function clearMessages() {
$('#status-messages ul').empty();
$('#status-messages').hide();
};

const loadFormFields = function loadFormFields(formId, formFieldsArray) {
clearContent();
formFieldsArray.forEach((item) => {
$(`#${formId}`).append(formTemplate({field: item}));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a very clever method to generate the form you need. The downside is that you can't create controls like select which keep a user from entering an invalid choice. Similarly you can't have inputs of type number.

How could you adapt this method to improve the UX?

});
$(`#${formId}`).append('<section><button type="submit" class="button">Submit</button></section>');
}

const addTripForm = function addTripForm() {
loadFormFields('add-trip-form', addTripFields);
$('#add-trip-header').append('Add Trip');
}

const saveTrip = function saveTrip(event) {
event.preventDefault();
const data = {};
addTripFields.forEach((field) => data[field] = $(`#add-trip-form input[name=${field}]`).val());
const trip = new Trip(data);
if (trip.isValid()) {
trip.save({}, {
success: successfulTripSave,
error: failedTripSave,
})
} else {
displayFormErrors('add-trip-form', trip.validationError)
}
}

const displayFormErrors = function displayFormErrors(formId, errors) {
$(`#${formId} input`).removeClass('input-error');
$(`#${formId} label span`).empty();
for (let error in errors) {
errors[error].forEach((message) => {
$(`#${formId} label span#label-${error}`).append(`: ${message}`);
});
$(`#${formId} input#${error}`).addClass('input-error');
}
}

const displayStatusMessages = function displayStatusMessages(model) {
$('#status-messages ul').empty();
$('#status-messages ul').append(`<li>${model.get('name')} added!</li>`);
$('#status-messages').show();
};

const successfulTripSave = function successfulTripSave(trip) {
$.modal.close();
tripList.add(trip);
referenceList.add(trip);
addTripFields.forEach((field) => {
$(`#add-trip-form input[name=${field}]`).val('');
});
displayStatusMessages(trip);
}

const failedTripSave = function failedTripSave(model, response) {
model.destroy
displayFormErrors('add-trip-form', response.responseJSON.errors);
}

const reserveForm = function reserveForm(event) {
loadFormFields('reserve-trip-form', reservationFields);
$('#reserve-trip-header').append('Reserve');
$('#reserve-trip-form').attr('tripid', $(event.currentTarget.attributes.tripid).val());
};

const saveReservation = function saveReservation(event) {
event.preventDefault();
const tripId = $(event.currentTarget.attributes.tripid).val();
const data = {};
reservationFields.forEach((field) => data[field] = $(`#reserve-trip-form input[name=${field}]`).val());
const reservation = new Reservation(data, {trip: tripId});
if (reservation.isValid()) {
reservation.save({}, {
success: successfulReservationSave,
error: failedReservationSave,
})
} else {
displayFormErrors('reserve-trip-form', reservation.validationError);
}
}

const successfulReservationSave = function successfulReservationSave(reservation, response) {
reservationFields.forEach((field) => $(`#reserve-trip-form input[name=${field}]`).val(''));
displayStatusMessages(reservation);
const fakeEvent = {currentTarget: {id: response.trip_id}};
showTrip(fakeEvent);
}

const failedReservationSave = function failedReservationSave(model, response) {
model.destroy
displayFormErrors('reserve-trip-form', response.responseJSON.errors);
}

const sortTrips = function sortTrips() {
const classes = $(this).attr('class').split(/\s+/);
referenceList.comparator = classes.find(thisClass => tableFields.includes(thisClass));
$('.sortorder').empty();
if (classes.includes('desc')) {
renderTrips(referenceList.models.reverse());
$(this).removeClass('desc');
} else {
renderTrips(referenceList.sort());
$(this).addClass('desc').siblings().removeClass('desc');
}
$(`.${referenceList.comparator} .sortorder`).html($(this).hasClass('desc') ? '&#x25BC': '&#x25B2');
$(this).addClass('current-sort-field').siblings().removeClass('current-sort-field');
}

$(document).ready( () => {
$('main').html('<h1>Hello World!</h1>');
allTripsTemplate = _.template($('#all-trips-template').html());
tripHeadersTemplate = _.template($('#trip-headers-template').html());
showTripTemplate = _.template($('#show-trip-template').html());
formTemplate = _.template($('#form-template').html());
filterTemplate = _.template($('#filter-trips-template').html());
$('#load-trips').on('click', function() {
unSplitScreen();
fetchTrips();
loadTripsTable(referenceList);
});
tripList.on('update', syncReferenceList);
referenceList.on('update', loadTripsTable, referenceList);
$('#filter-select').on('change', setFilterCategory);
$('#filter-input').on('input', filterTrips);
$('#all-trips').on('click', '.trip', showTrip);
$('thead').on('click', '.sort', sortTrips);
$('#add-trip').on('click', addTripForm);
$('#add-trip-form').on('submit', saveTrip);
$('#show-trip').on('click', '#reserve', reserveForm);
$('#reserve-trip-form').on('submit', saveReservation);
$('.clear, #load-trips, #add-trip').on('click', clearMessages);
});
9 changes: 9 additions & 0 deletions src/app/collections/trip_list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import Backbone from 'backbone';
import Trip from '../models/trip';

const TripList = Backbone.Collection.extend({
model: Trip,
url: 'https://ada-backtrek-api.herokuapp.com/trips',
})

export default TripList;
Loading