Skip to content
This repository has been archived by the owner on Dec 7, 2019. It is now read-only.

Домашнее задание 1 #8

Merged
merged 4 commits into from
May 19, 2019
Merged

Домашнее задание 1 #8

merged 4 commits into from
May 19, 2019

Conversation

denisstasyev
Copy link
Owner

  1. При выполнении дз возник ряд вопросов с созданием спрайта для картинок. Не получается настроить css-sprite-loader. В configs/webpack.config.js в rules: я должен вставить шаблон для css файлов, но там уже стоит на cssRegex обработчик. Да и в коде я указываю background: url(...) из javascript (так как думаю, что изменять одно место лучше, чем писать 1000 css- классов (если отдельно под каждый эмодзи создавать класс со своим background)) и понятно, что css-sprite-loader надо как-то отдельно настраивать, как? Или что-то вместо него использовать?

  2. В src/components/MessageList/Message/Message.js возник вопрос как аккуратно обрабатывать XSS угрозу, когда любой html можно отправить, тем самым можно поломать всё теоретически.

Copy link
Collaborator

@chexex chexex left a comment

Choose a reason for hiding this comment

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

css спрайты нужны :)

return updateObject(state, {user: state.concat(
{name: state.name, isAuthorized: state.isAuthorized})});
}*/
return state;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Предлагаю убрать лишние строки (закомментированные)

src/App.js Outdated
<Switch>
<Route exact path="/" component={ChatList} />
<Route path="/chat/:id" component={Chat} />
{/* <Route path="/register" component={Register} /> */}
Copy link
Collaborator

Choose a reason for hiding this comment

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

Лишнее?

const result = Object.keys(this.state.loginForm).reduce((res, key) => {
res[key] = this.state.loginForm[key].value;
return res;
}, {});
Copy link
Collaborator

Choose a reason for hiding this comment

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

Предложу рассмотреть метод entries у Object

const result = Object
  .entires(this.state.loginForm)
  .reduce((acc, [key, value]) => {
    acc[key] = value.value
    return acc
  }, {})

if (rule.minLength) {
isValid = value.trim().length >= rule.minLength && isValid;
}
return isValid;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Хочу обратить внимание, что такой checkValidity подойдет для понимания, как происходит валидация форм, однако в промышленной разработке необходимо будет предусмотреть больше параметров для валидации ввода (вне зависимости от того, будет ли использована сторонняя библиотека, например, formik или функционал формы будет реализован самостоятельно):

  • тип данных для ввода
  • разрешенные символы
  • длина ввода
  • управление пробелами

inputData.value = event.target.value;
inputData.valid = this.checkValidity(inputData.value, inputData.validation);

const invalid = Object.keys(newFormData).some(key => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Здесь тоже предложу entries

}

const mapStateToProps = state => {
return {
Copy link
Collaborator

Choose a reason for hiding this comment

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

... state => ({ ... })

import ImageFileButton from "../../../../static/Chat/MessageForm/FileButton/paperclip.svg";
import * as actionTypes from "../../../../../store/actionTypes/actionTypes";

import ImageFileButton from "../../../../../static/Chat/MessageForm/FileButton/paperclip.svg";
Copy link
Collaborator

Choose a reason for hiding this comment

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

@martinkomitsky dothell выглядит так :)

Copy link
Owner Author

@denisstasyev denisstasyev May 11, 2019

Choose a reason for hiding this comment

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

@chexex Лучше абсолютные пути? Или лучше просто в components для каждого компонента создать папку? Не начнётся ли ад, так что вообще будет непонятно что с чем как взаимодействует?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Лично я предпочитаю абсолютные пути. Для этого в .env файле нужно добавить строку

NODE_PATH=src/,

а в модулях делать так:

import * as actionTypes from "store/actionTypes/actionTypes"

}

function success(position) {
var text = `My location: (${position.coords.latitude}, ${
Copy link
Collaborator

Choose a reason for hiding this comment

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

Возможно, будет лучше, если в рамках одного модуля не мешать старые и новые типы переменных (var, let, const)
А в рамках одной строки не использовать сигнатурные вещи es5 (тип var) и es6 (литеральные строки) :))

alert("Unable to retrieve your location!");
}

navigator.geolocation.getCurrentPosition(success.bind(this), error);
Copy link
Collaborator

Choose a reason for hiding this comment

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

В модулях выше методы класса были определены через константные переменные, можно и в этом компоненте поступить так же :)

Copy link
Owner Author

Choose a reason for hiding this comment

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

@chexex Тот самый комментарий

Copy link
Collaborator

Choose a reason for hiding this comment

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

Здесь я имел ввиду определение методов класса через константы (стрелочные функции), мне, почему-то, казалось, что они везде так были определены.

https://reactjs.org/docs/faq-functions.html

После просмотра всего кода понял, что мне казалось. Комментарий не актуален. Однако статья может быть полезной :)

@@ -0,0 +1,41 @@
import React from "react";
Copy link
Collaborator

Choose a reason for hiding this comment

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

Позже продолжу отсюда

Copy link
Owner Author

Choose a reason for hiding this comment

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

Вот в этом компоненте как раз непонятно, как src в CSS вынести для css-sprite-loader

@denisstasyev
Copy link
Owner Author

Спасибо, буду исправлять, Auth пока до ума не доводил

".png?sprite=sprite-reactions")}
alt={"Reaction " + this.props.name}
/>
);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Что если вместо img использовать span для отображения бэкграунда?

Например, у нас может определен список изображений (смайлов в нашем случае). Тогда мы сможем в css файле определить их бэкграунд по имени изображения, а в компоненте динамически подставить имя класса.

// list with images file
export default [
  'one',
  'two',
  'three',
  'four',
  ...
]
// some.css file
:root {
  --basic-bg-size: 24px 24px;
}
one {
  background: url("some-url-one?sprite");
  background-size: var(--basic-bg-size);
}
two {
  background: url("some-url-two?sprite");
  background-size: var(--basic-bg-size);
}
three {
  background: url("some-url-three?sprite");
  background-size: var(--basic-bg-size);
}
...

// in jsx
render () {
  const images = importedImages
    .map((image, idx) => (
      <span
        className={image}
        key={`${image}_${idx}`}
        onClick={...}
        onDoubleClick={...}
      >
      </span>
    ))
  return (
    <div className="someContainerClass">
      {images}
    </div>   
  )
}

Copy link
Owner Author

Choose a reason for hiding this comment

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

@chexex хорошо, переделаю так, просто изначально посчитал, что писать так CSS слишком избыточно и не особо красиво

}

const mapDispatchToProps = dispatch => {
return {
Copy link
Collaborator

Choose a reason for hiding this comment

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

const mapDispatchToProps = dispatch => ({...})

);
}
}

export default SendButton;
const mapStateToProps = state => {
return {
Copy link
Collaborator

Choose a reason for hiding this comment

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

... state => ({...})

};

const mapDispatchToProps = dispatch => {
return {
Copy link
Collaborator

Choose a reason for hiding this comment

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

... dispatch => ({ ... })

@@ -1,79 +1,141 @@
/* eslint-disable jsx-a11y/img-redundant-alt */
import React from "react";
import "./Message.css";
// import "../../ReactionTypes/ReactionTypes.css";
Copy link
Collaborator

Choose a reason for hiding this comment

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

Больше не нужно?

'" style="max-width:100%;" alt="Reaction template" />'.replace(
"template",
reaction.name
);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Ввиду коммента выше, не думаю, что здесь подойдет img элемент. Однако, обращу внимание, что строковые литералы позволят избежать replace для подстановки в строку нужных переменных

resutl = `<img src="${src} style="max-width: 100%;" alt="Reaction ${reaction.name}" />`

reaction.name
);
}
while (result.indexOf(reaction.text) !== -1) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Почему здесь этот цикл, для чего он? :)

<li className={"message " + (this.props.isMy ? "my" : "alien")}>
<div className={"text--" + (this.props.isMy ? "my" : "alien")}>
{text}
</div>
Copy link
Collaborator

Choose a reason for hiding this comment

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

Много повторяющегося кода

}

onDragOver(event) {
handleDragAndDrop(event) {
event.preventDefault();
var files = Array.from(event.dataTransfer.files);

files.forEach(function(file) {
var reader = new FileReader();
Copy link
Collaborator

Choose a reason for hiding this comment

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

От var необходимо избавиться

@@ -0,0 +1,64 @@
const reactionTypesList = [
Copy link
Collaborator

Choose a reason for hiding this comment

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

А вот и список с картинками. :) Для них можно завести правила в css, а в jsx подставлять только className соответсвтующий имени картинки

@chexex
Copy link
Collaborator

chexex commented May 11, 2019

  1. При выполнении дз возник ряд вопросов с созданием спрайта для картинок. Не получается настроить css-sprite-loader. В configs/webpack.config.js в rules: я должен вставить шаблон для css файлов, но там уже стоит на cssRegex обработчик. Да и в коде я указываю background: url(...) из javascript (так как думаю, что изменять одно место лучше, чем писать 1000 css- классов (если отдельно под каждый эмодзи создавать класс со своим background)) и понятно, что css-sprite-loader надо как-то отдельно настраивать, как? Или что-то вместо него использовать?
  2. В src/components/MessageList/Message/Message.js возник вопрос как аккуратно обрабатывать XSS угрозу, когда любой html можно отправить, тем самым можно поломать всё теоретически.

Спасибо за проделанную работу. Я постарался ответить на поставленные вопросы по ходу ревью.
Если остались непонятные моменты, пожалуйста, задавай вопросы.

@denisstasyev
Copy link
Owner Author

denisstasyev commented May 13, 2019

@chexex

  • Исправил большинство замечаний, кроме одного комментария (отметил его) (Auth пока не трогал, далее им займусь как раз).

  • Никак не получается отображение через span сделать в Message в handleReaction(text) . В чём моя ошибка?

  • В config/webpack.config.js не знаю как аккуратно добавить строки для css-sprite-loader, так как там есть cssRegex и насколько я понимаю красиво было бы css-sprite-loader сюда же добавить, пробовал в use: ["css-sprite-loader", getStyleLoaders(...)], но ругается. --- сделано

@denisstasyev
Copy link
Owner Author

denisstasyev commented May 14, 2019

@chexex Добавил css-sprite-loader, но отображает он неверно иконки. Мне кажется, что
background-size: contain;
background-clip: initial;
могли бы исправить ситуацию, но их css-sprite-loader не поддерживает тут issue

`<span className="${[
styles["reaction-inline"],
styles[reaction.name]
].join(" ")}" />`
Copy link
Collaborator

Choose a reason for hiding this comment

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

Здесь не получается отобразить?

Если честно, меня по-прежнему смущает этот алгоритм замены текстового представления смайлика :).
Я бы следовал одному из пути, указанному здесь:
https://stackoverflow.com/a/55334886

Теперь, чтобы наверняка понять, почему не работает, я прошу показать, как выглядит готовый кусок html кода. Возможно @martinkomitsky с ходу назовет проблему, но я в любом случае рекомендую приложить html/скрин

Copy link
Owner Author

Choose a reason for hiding this comment

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

Screenshot from 2019-05-15 19-47-46
@chexex Вот тут плохо в ExtrasPanel отображаются

Copy link
Owner Author

@denisstasyev denisstasyev May 15, 2019

Choose a reason for hiding this comment

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

Screenshot from 2019-05-15 19-48-49
При отправке только смайла (то есть текста ": alien :" без пробелов)

Copy link
Owner Author

Choose a reason for hiding this comment

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

Screenshot from 2019-05-15 19-49-57
при отправке :alien :123

alert("Unable to retrieve your location!");
}

navigator.geolocation.getCurrentPosition(success.bind(this), error);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Здесь я имел ввиду определение методов класса через константы (стрелочные функции), мне, почему-то, казалось, что они везде так были определены.

https://reactjs.org/docs/faq-functions.html

После просмотра всего кода понял, что мне казалось. Комментарий не актуален. Однако статья может быть полезной :)

@chexex
Copy link
Collaborator

chexex commented May 15, 2019

На будущее попрошу действия, подобные eject (автоматически генерирующие файлы, которые должны версионироваться), делать отдельным коммитом, иначе сложно ревьюить.

В общем и целом, я не вижу проблем в том, чтобы принять работу, жду следующие задания.

@denisstasyev
Copy link
Owner Author

@chexex Есть ещё вопрос как сделать, чтобы чат автоматически скролился вниз ?

Ну и по сдаче: вы можете тогда замержить (Мартин обычно сам делал это) или мне самому?

Screenshot from 2019-05-15 19-58-28

@martinkomitsky
Copy link
Collaborator

Коммент от Леши: мерж и 6 баллов.
@chexex Есть ещё вопрос как сделать, чтобы чат автоматически скролился вниз ?

@martinkomitsky martinkomitsky merged commit 76f68b8 into master May 19, 2019
@martinkomitsky martinkomitsky deleted the sem2-hw1 branch May 19, 2019 07:44
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants