Skip to content

Commit

Permalink
Merge pull request #6 from licos87/module4-task2
Browse files Browse the repository at this point in the history
Шаблонизируй то
  • Loading branch information
AlSudar authored Sep 29, 2024
2 parents b825db1 + 9fee6d3 commit 3bff771
Show file tree
Hide file tree
Showing 17 changed files with 371 additions and 136 deletions.
35 changes: 33 additions & 2 deletions src/const.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,35 @@
const EVENT_TYPES = ['taxi', 'bus', 'train', 'ship', 'drive', 'flight', 'check-in', 'sightseeing', 'restaurant'];
const EVENT_TYPES = [
'taxi'
, 'bus'
, 'train'
, 'ship'
, 'drive'
, 'flight'
, 'check-in'
, 'sightseeing'
, 'restaurant'];

const MESSAGE = {
EMPTY: 'Click New Event to create your first point',
LOADING: 'Loading...',
FAILED_LOAD: 'Failed to load latest route information',
};

export {EVENT_TYPES};
const FilterType = {
EVERYTHING: 'everything',
FUTURE: 'future',
PRESENT: 'present',
PAST: 'past'
};

const SortType = {
DAY: 'day',
EVENT: 'event',
TIME: 'time',
PRICE: 'price',
OFFERS: 'offers',
};

const DisabledSortType = [SortType.EVENT, SortType.OFFERS];

export {EVENT_TYPES, MESSAGE, FilterType, SortType, DisabledSortType};
1 change: 1 addition & 0 deletions src/framework/view/abstract-view.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export default class AbstractView {
/** @type {HTMLElement|null} Элемент представления */
#element = null;


constructor() {
if (new.target === AbstractView) {
throw new Error('Can\'t instantiate AbstractView, only concrete one.');
Expand Down
1 change: 0 additions & 1 deletion src/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import ListPresenter from './presenter/list-presenter.js';

import PointsTripModel from './model/points-trip-model.js';
import OffersTripsModel from './model/offers-trip-model.js';
import DestinationsTripModel from './model/destinations-trip-model.js';
Expand Down
7 changes: 7 additions & 0 deletions src/mock/filter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { filter } from '../utils/filter.js';

function generateFilter() {
return Object.entries(filter).map(([filterType]) => ({type: filterType}));
}

export { generateFilter };
2 changes: 1 addition & 1 deletion src/model/points-trip-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export default class PointsTripModel {
this.#points = points;
}

get() {
get points() {
return this.#points;
}
}
34 changes: 34 additions & 0 deletions src/presenter/header-presenter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { render, RenderPosition } from '../framework/render.js';

import SectionTripInfoView from '../view/section-trip-info-view.js';
import NewEventButtonView from '../view/new-event-button-view.js';

const tripMain = document.querySelector('.trip-main');


export default class HeaderPresenter {

#pointsTrip = null;
#destinations = null;
#listPoints = [];

constructor({destinations, pointsTrip}) {
this.#pointsTrip = pointsTrip;
this.#destinations = destinations;
}

init() {
this.#listPoints = [...this.#pointsTrip];

this.#renderTripHeader();

}


/** Создание шапки сайта */
#renderTripHeader() {
render(new SectionTripInfoView({allDestinations: this.#destinations , allPoints: this.#listPoints}), tripMain, RenderPosition.AFTERBEGIN); // Заголовок, даты, общая цена

render(new NewEventButtonView(), tripMain); // Заголовок, кнопка добавить событие
}
}
137 changes: 101 additions & 36 deletions src/presenter/list-presenter.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,102 @@
import { render, RenderPosition, replace } from '../framework/render.js';
import { render, replace } from '../framework/render.js';
import { MESSAGE } from '../const.js';
import { SortType } from '../const.js';
import { sortEventsByDay, sortEventsByTime, sortEventsByPrice } from '../utils/filter.js';
import { generateFilter } from '../mock/filter.js';

import SectionTripInfoView from '../view/section-trip-info-view.js';
import NewEventButtonView from '../view/new-event-button-view.js';
import SortButtonView from '../view/sort-button-view.js';
import TripFiltersFormView from '../view/trip-filters-form-view.js';

import SortButtonView from '../view/sort-view.js';
import TripEventListView from '../view/trip-events-list-view.js';
import EventItemView from '../view/event-item-view.js';
// import AddNewPointView from '../view/add-new-point-view.js';
import EditPointView from '../view/edit-poit-view.js';
import TripEventsMessage from '../view/trip-events-message-view.js';

const tripMain = document.querySelector('.trip-main');
const tripControlsFilters = document.querySelector('.trip-controls__filters');
import HeaderPresenter from './header-presenter.js';

const tripFiltersElement = document.querySelector('.trip-controls__filters');


export default class ListPresenter {

#listContainer;
#pointsTrip;
#destinations;
#offers;
#listContainer = null;
#pointsTrip = null;
#destinations = null;
#offers = null;

#listComponent = new TripEventListView();

#listPoints = [];

#sourcedTripPoints = [];
#sortComponent = null;
#currentSortType = SortType.DAY;

constructor({ listContainer, pointsTripModel, destinationsTripModel, offersTripModel }) {
this.#listContainer = listContainer;
this.#pointsTrip = pointsTripModel.get();
this.#pointsTrip = pointsTripModel.points;
this.#destinations = destinationsTripModel;
this.#offers = offersTripModel;
}

init() {
this.#listPoints = [...this.#pointsTrip];

/** Отрисовка всех компонентов */
this.#sourcedTripPoints = [...this.#pointsTrip];


this.#headerPresenter({destinations:this.#destinations, pointsTrip: this.#pointsTrip});

/** Рендерим кнопки сортировки */
this.#renderSort();

/** Рендерим форму фильтрации */
this.#renderFilters();

/** Отрисовка всех компонентов путешествия */
this.#renderList();

}

#renderList() {

/** Рендерим список для новых событий */
render(this.#listComponent, this.#listContainer);

if (this.#listPoints.length === 0) {
/** Если список событий пуст, то отрисовываем сообщение */
render(new TripEventsMessage(MESSAGE.EMPTY), this.#listContainer);

} else {
/** Если список событий не пуст, то отрисовываем события */

/** Рендерим редактируемое событие */
this.#rederTripEvent(this.#listPoints[0]);

/** Рендерим список событий */
this.#renderAllTripEvents();
}


// Переделать логику отрисовки новой точки!
// render(new AddNewPointView({pointsTrip: this.#listPoints, offers: this.#offers}), this.#listContainer);
}

#headerPresenter({destinations, pointsTrip}) {
const headerPresenter = new HeaderPresenter({
destinations,
pointsTrip,
});

return headerPresenter.init();
}

#renderFilters() {
const filters = generateFilter();

render(new TripFiltersFormView({filters}), tripFiltersElement);
}

/** Елемент события путешествия */
#tripEventData(item) {

const destination = this.#destinations.getDestinationById(item);
Expand Down Expand Up @@ -112,33 +168,42 @@ export default class ListPresenter {
});
}

#renderList() {
/** Отрисовка шапки сайта */
render(new SectionTripInfoView({allDestinations: this.#destinations, allPoints: this.#listPoints}), tripMain, RenderPosition.AFTERBEGIN); // Заголовок, даты, общая цена
render(new NewEventButtonView(), tripMain); // Заголовок, кнопка добавить событие
render (new TripFiltersFormView(), tripControlsFilters); // Кнопки сортировки


/** Рендерим список для новых событий */
render(this.#listComponent, this.#listContainer);
/** Отрисовка cортировки событий путешествия */
#renderSort() {
this.#sortComponent = new SortButtonView({
onSortTypeChange: this.#handleSortTypeChange,
currentSortType: this.#currentSortType,
});

/** Если список событий пуст, то отрисовываем сообщение */
if (this.#listPoints.length === 0) {
render(new TripEventsMessage, this.#listContainer);
render(this.#sortComponent, this.#listContainer);
}

/** Сортировка событий путешествия */
#sortTripPoints(sortType) {

switch (sortType) {
case SortType.DAY:
this.#pointsTrip.sort(sortEventsByDay);
break;
case SortType.TIME:
this.#pointsTrip.sort(sortEventsByTime);
break;
case SortType.PRICE:
this.#pointsTrip.sort(sortEventsByPrice);
break;
default:
this.#pointsTrip = [...this.#sourcedTripPoints];
}
/** Рендерим кнопки сортировки */
render(new SortButtonView(), this.#listContainer);

/** Рендерим редактируемое событие */
this.#rederTripEvent(this.#listPoints[0]);

/** Рендерим список событий */
this.#renderAllTripEvents();
this.#currentSortType = sortType;
}

#handleSortTypeChange = (sortType) => {
if (this.#currentSortType === sortType) {
return;
}

// Переделать логику отрисовки новой точки!
// render(new AddNewPointView({pointsTrip: this.#listPoints, offers: this.#offers}), this.#listContainer);
}
this.#sortTripPoints(sortType);
};

}
53 changes: 53 additions & 0 deletions src/utils/filter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { FilterType } from '../const.js';
import dayjs from 'dayjs';

const filter = {
[FilterType.EVERYTHING]: (pointsTrip) => pointsTrip,
[FilterType.FUTURE]: (pointsTrip) => pointsTrip.filter((pointTrip) => new Date(pointTrip.date_from) > Date.now()),
[FilterType.PRESENT]: (pointsTrip) => pointsTrip.filter((pointTrip) => new Date(pointTrip.date_from) <= Date.now() && new Date(pointTrip.date_to) >= Date.now()),
[FilterType.PAST]: (pointsTrip) => pointsTrip.filter((pointTrip) => new Date(pointTrip.date_to) < Date.now()),
};


function sortEventsByDay (eventA, eventB) {

if (dayjs(eventA.date_from).diff(dayjs(eventB.date_from)) < 0) {
return -1;
}

if (dayjs(eventA.date_from).diff(dayjs(eventB.date_from)) > 0) {
return 1;
}

return 0;
}

function sortEventsByTime (eventA, eventB) {

if (dayjs(eventA.date_from).diff(dayjs(eventA.date_to)) <
dayjs(eventB.date_from).diff(dayjs(eventB.date_to))) {
return -1;
}

if (dayjs(eventA.date_from).diff(dayjs(eventA.date_to)) >
dayjs(eventB.date_from).diff(dayjs(eventB.date_to))) {
return 1;
}

return 0;
}

function sortEventsByPrice (eventA, eventB) {

if (eventA.base_price < eventB.base_price) {
return -1;
}

if (eventA.base_price > eventB.base_price) {
return 1;
}

return 0;
}

export { filter, sortEventsByDay, sortEventsByTime, sortEventsByPrice };
11 changes: 1 addition & 10 deletions src/utils.js → src/utils/utils.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
import dayjs from 'dayjs';

/**
* Returns a random element from the given array.
* @param {Array} items - Array of any type of elements.
* @returns {any} - Random element from the array.
*/
function getRandomArrayElement(items) {
return items[Math.floor(Math.random() * items.length)];
}

const FORMATS = {
'headerDate': 'DD MMM',
'date': 'MMM D',
Expand Down Expand Up @@ -62,4 +53,4 @@ function capitalizeFirstLetter(word) {
return word[0].toUpperCase() + word.slice(1);
}

export { getRandomArrayElement, humanizeEventDate, getDuration, capitalizeFirstLetter };
export { humanizeEventDate, getDuration, capitalizeFirstLetter };
4 changes: 2 additions & 2 deletions src/view/add-new-point-view.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,8 @@ function createAddNewPointTemplate() {

export default class AddNewPointView extends AbstractView {

#pointsTrip;
#offers;
#pointsTrip = null;
#offers = null;

constructor(pointsTrip, offers) {
super();
Expand Down
12 changes: 6 additions & 6 deletions src/view/edit-poit-view.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {EVENT_TYPES} from '../const.js';
import { humanizeEventDate, capitalizeFirstLetter } from '../utils.js';
import { humanizeEventDate, capitalizeFirstLetter } from '../utils/utils.js';
import AbstractView from '../framework/view/abstract-view.js';

function createOffersTemplate(tripEventData) {
Expand Down Expand Up @@ -154,12 +154,12 @@ function createEditPointTemplate(tripEventData, destinations, allDestinations) {

export default class EditPointView extends AbstractView {

#tripEventData;
#destinations;
#allDestinations;
#tripEventData = null;
#destinations = null;
#allDestinations = null;

#handleFormSubmit;
#handleCloseFormClick;
#handleFormSubmit = null;
#handleCloseFormClick = null;

constructor({tripEventData, destinations, allDestinations, onFormSubmit, onCloseFormClick}) {
super();
Expand Down
Loading

0 comments on commit 3bff771

Please sign in to comment.