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

Шаблонизируй то #6

Merged
merged 5 commits into from
Sep 29, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
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
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
10 changes: 9 additions & 1 deletion src/main.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import ListPresenter from './presenter/list-presenter.js';
import {render} from './framework/render.js';

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';
import TripFiltersFormView from './view/trip-filters-form-view.js';
import { generateFilter } from './mock/filter.js';

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

const pointsTripModel = new PointsTripModel();
const offersTripModel = new OffersTripsModel();
Expand All @@ -18,6 +22,10 @@ const listPresenter = new ListPresenter({
offersTripModel,
});

const filters = generateFilter();

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

Copy link
Collaborator

Choose a reason for hiding this comment

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

Мне кажется лучше рендерить фильтры внутри ListPresenter, т.к. список точек маршрутра и фильтрация - это взаимосвязанные вещи

listPresenter.init();


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;
}
}
87 changes: 66 additions & 21 deletions src/presenter/list-presenter.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,52 @@
import { render, RenderPosition, replace } from '../framework/render.js';
import { MESSAGE } from '../const.js';
import { SortType } from '../const.js';
import { sortEventsByDay, sortEventsByTime, sortEventsByPrice } from '../utils/filter.js';

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

import SortButtonView from '../view/sort-view.js';
import SortButtonView from '../view/sort-button-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');


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.#renderList();
}


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

const destination = this.#destinations.getDestinationById(item);
Expand Down Expand Up @@ -114,31 +120,70 @@ export default class ListPresenter {

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

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

Choose a reason for hiding this comment

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

Лучше вынести из этого метода #renderSort(); и render(new SectionTripInfoView({allDestinations: this.#destinations , allPoints: this.#listPoints}), tripMain, RenderPosition.AFTERBEGIN); . В будущем могут возникнуть ситуации в которых нам надо перерендерить список, но не перерендеривать эти два элемента. В целом лучше разделять на разные методы рендеры разных кусков нашего приложения


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

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

}
/** Рендерим кнопки сортировки */
render(new SortButtonView(), this.#listContainer);
} else {
/** Если список событий не пуст, то отрисовываем события */

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

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


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

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

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];
}

this.#currentSortType = sortType;
}

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

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
6 changes: 3 additions & 3 deletions src/view/event-item-view.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {humanizeEventDate, getDuration} from '../utils.js';
import {humanizeEventDate, getDuration} from '../utils/utils.js';
import AbstractView from '../framework/view/abstract-view.js';

function createOffersTemplate(offers) {
Expand Down Expand Up @@ -67,8 +67,8 @@ function createEventItemTemplate(tripEventData) {

export default class EventItemView extends AbstractView {

#tripEventData;
#handleEditClick;
#tripEventData = null;
#handleEditClick = null;

constructor(tripEventData, {onEditClick}) {
super();
Expand Down
Loading
Loading