-
Notifications
You must be signed in to change notification settings - Fork 0
Conversation
There was a problem hiding this 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; |
There was a problem hiding this comment.
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} /> */} |
There was a problem hiding this comment.
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; | ||
}, {}); |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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 => { |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@martinkomitsky dothell выглядит так :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@chexex Лучше абсолютные пути? Или лучше просто в components для каждого компонента создать папку? Не начнётся ли ад, так что вообще будет непонятно что с чем как взаимодействует?
There was a problem hiding this comment.
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}, ${ |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В модулях выше методы класса были определены через константные переменные, можно и в этом компоненте поступить так же :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@chexex Тот самый комментарий
There was a problem hiding this comment.
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"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Позже продолжу отсюда
There was a problem hiding this comment.
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
Спасибо, буду исправлять, Auth пока до ума не доводил |
".png?sprite=sprite-reactions")} | ||
alt={"Reaction " + this.props.name} | ||
/> | ||
); |
There was a problem hiding this comment.
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>
)
}
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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"; |
There was a problem hiding this comment.
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 | ||
); |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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> |
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
От var
необходимо избавиться
src/components/Chat/ReactionTypes.js
Outdated
@@ -0,0 +1,64 @@ | |||
const reactionTypesList = [ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А вот и список с картинками. :) Для них можно завести правила в css, а в jsx подставлять только className
соответсвтующий имени картинки
Спасибо за проделанную работу. Я постарался ответить на поставленные вопросы по ходу ревью. |
|
`<span className="${[ | ||
styles["reaction-inline"], | ||
styles[reaction.name] | ||
].join(" ")}" />` |
There was a problem hiding this comment.
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/скрин
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@chexex Вот тут плохо в ExtrasPanel отображаются
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
alert("Unable to retrieve your location!"); | ||
} | ||
|
||
navigator.geolocation.getCurrentPosition(success.bind(this), error); |
There was a problem hiding this comment.
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 Есть ещё вопрос как сделать, чтобы чат автоматически скролился вниз ? Ну и по сдаче: вы можете тогда замержить (Мартин обычно сам делал это) или мне самому? |
Коммент от Леши: мерж и 6 баллов. |
При выполнении дз возник ряд вопросов с созданием спрайта для картинок. Не получается настроить css-sprite-loader. В configs/webpack.config.js в rules: я должен вставить шаблон для css файлов, но там уже стоит на cssRegex обработчик. Да и в коде я указываю background: url(...) из javascript (так как думаю, что изменять одно место лучше, чем писать 1000 css- классов (если отдельно под каждый эмодзи создавать класс со своим background)) и понятно, что css-sprite-loader надо как-то отдельно настраивать, как? Или что-то вместо него использовать?
В src/components/MessageList/Message/Message.js возник вопрос как аккуратно обрабатывать XSS угрозу, когда любой html можно отправить, тем самым можно поломать всё теоретически.