add prettier and reformat all files

This commit is contained in:
2022-07-11 12:23:43 +02:00
parent 35e4d96726
commit dfab85da65
72 changed files with 1065 additions and 823 deletions

7
.prettierrc.js Normal file
View File

@@ -0,0 +1,7 @@
module.exports = {
trailingComma: 'es5',
tabWidth: 4,
semi: false,
singleQuote: true,
endOfLine: 'auto',
}

View File

@@ -17,6 +17,7 @@
"@types/uuid": "^8.3.4",
"axios": "^0.27.2",
"gh-pages": "^4.0.0",
"prettier": "^2.7.1",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-redux": "^8.0.2",

View File

@@ -38,6 +38,5 @@
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
--></body>
</html>

View File

@@ -12,7 +12,6 @@ body {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
box-sizing: border-box;
}
code {
@@ -68,7 +67,6 @@ code {
--success: #16a34a;
--warning: #d97706;
--error: #dc2626;
}
html {

View File

@@ -3,16 +3,14 @@ import ReactDOM from 'react-dom/client'
import './index.css'
import App from './s1-main/App'
import reportWebVitals from './reportWebVitals'
import {Provider} from 'react-redux'
import { Provider } from 'react-redux'
import store from './s2-homeworks/hw10/bll/store'
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
)
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
root.render(
<React.StrictMode>
<Provider store={store}>
<App/>
<App />
</Provider>
</React.StrictMode>
)

View File

@@ -1,15 +1,17 @@
import { ReportHandler } from 'web-vitals';
import { ReportHandler } from 'web-vitals'
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
import('web-vitals').then(
({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry)
getFID(onPerfEntry)
getFCP(onPerfEntry)
getLCP(onPerfEntry)
getTTFB(onPerfEntry)
}
};
)
}
}
export default reportWebVitals;
export default reportWebVitals

View File

@@ -3,7 +3,6 @@
}
.hw {
}
.hwTitle {
@@ -25,5 +24,5 @@
hr {
border-top: 1px solid #d9d9d9;
margin: 0
margin: 0;
}

View File

@@ -25,7 +25,7 @@ const App = () => {
{/*<HW3/>*/}
{/*<HW4/>*/}
<HW5/>
<HW5 />
</div>
)
}

View File

@@ -4,38 +4,48 @@ import s from './Message.module.css'
// создать тип вместо any и отобразить приходящие данные
const FriendMessage = (props: any) => {
return (
<div id={'hw1-friend-message-' + props.message.id} className={s.friendMessage}>
<div
id={'hw1-friend-message-' + props.message.id}
className={s.friendMessage}
>
<div className={s.friendImageAndMessage}>
<img
id={'hw1-friend-avatar-' + props.message.id}
// создаёт студент
src={props.message.user.avatar}
width={'50px'} height={'50px'}
width={'50px'}
height={'50px'}
alt={'avatar'}
//
/>
<div className={s.friendMessageText}>
<div id={'hw1-friend-name-' + props.message.id} className={s.friendName}>
<div
id={'hw1-friend-name-' + props.message.id}
className={s.friendName}
>
{/*создаёт студент*/}
{props.message.user.name}
{/**/}
</div>
<div id={'hw1-friend-text-' + props.message.id} className={s.friendText}>
<div
id={'hw1-friend-text-' + props.message.id}
className={s.friendText}
>
{/*создаёт студент*/}
{props.message.message.text}
{/**/}
</div>
</div>
</div>
<div id={'hw1-friend-time-' + props.message.id} className={s.friendTime}>
<div
id={'hw1-friend-time-' + props.message.id}
className={s.friendTime}
>
{/*создаёт студент*/}
{props.message.message.time}
{/**/}
</div>
</div>
)
}

View File

@@ -32,7 +32,6 @@ export const friendMessage0: MessageType = {
},
}
const HW1 = () => {
return (
<div id={'hw1'} className={s2.hw}>
@@ -40,21 +39,20 @@ const HW1 = () => {
{/*можно убрать этот тег*/}
<div className={s2.hwTitle}>Homework #1</div>
<hr/>
<hr />
<div className={s2.hwContainer}>
{/*проверка отображения (не менять)*/}
<div>
<Message message={message0}/>
<Message message={message0} />
{/*не обязательно*/}
<FriendMessage message={friendMessage0}/>
<FriendMessage message={friendMessage0} />
</div>
{/*для автоматической проверки дз (не менять)*/}
<MessageSender M={Message}/>
<MessageSender M={Message} />
</div>
{/*<hr/>*/}
{/*можно убрать этот тег*/}
<hr />

View File

@@ -63,7 +63,8 @@
max-width: 70%;
height: 100%;
background-color: #06c;
box-shadow: 0 5px 20px rgba(29, 33, 38, 0.03), 0 1px 2px rgba(29, 33, 38, 0.1);
box-shadow: 0 5px 20px rgba(29, 33, 38, 0.03),
0 1px 2px rgba(29, 33, 38, 0.1);
display: flex;
flex-direction: column;
margin-right: 20px;
@@ -119,7 +120,8 @@
.textarea {
box-sizing: border-box;
background: #f5f7fb;
box-shadow: 0 5px 20px rgba(29, 33, 38, 0.03), 0 1px 2px rgba(29, 33, 38, 0.1);
box-shadow: 0 5px 20px rgba(29, 33, 38, 0.03),
0 1px 2px rgba(29, 33, 38, 0.1);
border-radius: 20px;
width: 100%;
border: none;
@@ -173,4 +175,3 @@ img {
width: 48px;
text-align: center;
}

View File

@@ -11,7 +11,6 @@ const Message = (props: MessagePropsType) => {
<div className={s.imageAndMessage}>
<img
id={'hw1-avatar-' + props.message.id}
// создаёт студент
src={props.message.user.avatar}
alt={'avatar'}
@@ -36,7 +35,6 @@ const Message = (props: MessagePropsType) => {
{/**/}
</div>
</div>
)
}

View File

@@ -9,33 +9,44 @@ const MessageSender = (props: any) => {
const [text, setText] = useState<any>('')
const addMessage = () => {
setMessages([...messages, {
setMessages([
...messages,
{
id: messages.length ? messages.length + 1 : 1,
user: message0.user,
message: {
text,
time: new Date().toTimeString().slice(0, 5),
},
}])
},
])
setTimeout(() => setText(''), 4)
}
return (
<>
{messages.map(m => <M key={'message' + m.id} message={m}/>)}
{messages.map((m) => (
<M key={'message' + m.id} message={m} />
))}
<div id={'hw1-send-message-form'} className={s.sendForm}>
<textarea
id={'hw1-textarea'}
value={text}
onChange={e => setText(e.currentTarget.value)}
onChange={(e) => setText(e.currentTarget.value)}
placeholder={'Type your message'}
onKeyDown={e => e.key === 'Enter' && e.shiftKey && addMessage()}
onKeyDown={(e) =>
e.key === 'Enter' && e.shiftKey && addMessage()
}
title={'Shift+Enter for send'}
className={s.textarea}
rows={1}
/>
<button id={'hw1-button'} onClick={addMessage} className={s.button}>
<button
id={'hw1-button'}
onClick={addMessage}
className={s.button}
>
{/*текст кнопки могут изменить студенты*/}
Send
{/**/}

View File

@@ -9,12 +9,17 @@ type AffairPropsType = {
}
function Affair(props: AffairPropsType) {
const deleteCallback = () => {props.deleteAffairCallback(props.affair._id)} // need to fix // создаёт студент
const deleteCallback = () => {
props.deleteAffairCallback(props.affair._id)
} // need to fix // создаёт студент
const priorityClass = s.item + ' ' + s[props.affair.priority]
return (
<div id={'hw2-affair-' + props.affair._id} className={s.affair + ' ' + s[props.affair.priority]}>
<div
id={'hw2-affair-' + props.affair._id}
className={s.affair + ' ' + s[props.affair.priority]}
>
<div id={'hw2-name-' + props.affair._id} className={priorityClass}>
{/*создаёт студент*/}
{props.affair.name}
@@ -33,9 +38,7 @@ function Affair(props: AffairPropsType) {
onClick={deleteCallback} // создаёт студент
className={priorityClass + ' ' + s.closeButton}
>
{/*текст кнопки могут изменить студенты*/}
X
{/**/}
{/*текст кнопки могут изменить студенты*/}X{/**/}
</button>
</div>
)

View File

@@ -69,7 +69,6 @@
display: flex;
gap: 24px;
margin-bottom: 32px;
}
.closeButton {

View File

@@ -3,7 +3,8 @@ import Affair from './Affair'
import { AffairType, FilterType } from './HW2'
import s from './Affairs.module.css'
type AffairsPropsType = { // need to fix any
type AffairsPropsType = {
// need to fix any
data: any // AffairType[]
setFilter: any // (filter: FilterType) => void
// setFilter: Dispatch<SetStateAction<FilterType>>
@@ -36,10 +37,22 @@ function Affairs(props: AffairsPropsType) {
// props.setFilter(e.currentTarget.value as FilterType)
// }
const cnAll = s.button + ' ' + s.all + ' ' + (props.filter === 'all' ? s.active : '')
const cnHigh = s.button + ' ' + s.high + ' ' + (props.filter === 'high' ? s.active : '')
const cnMiddle = s.button + ' ' + s.middle + ' ' + (props.filter === 'middle' ? s.active : '')
const cnLow = s.button + ' ' + s.low + ' ' + (props.filter === 'low' ? s.active : '')
const cnAll =
s.button + ' ' + s.all + ' ' + (props.filter === 'all' ? s.active : '')
const cnHigh =
s.button +
' ' +
s.high +
' ' +
(props.filter === 'high' ? s.active : '')
const cnMiddle =
s.button +
' ' +
s.middle +
' ' +
(props.filter === 'middle' ? s.active : '')
const cnLow =
s.button + ' ' + s.low + ' ' + (props.filter === 'low' ? s.active : '')
// const setClass = (filter: FilterType) => {
// return s.button + (props.filter === filter ? ' ' + s.active : '')
// }
@@ -47,14 +60,36 @@ function Affairs(props: AffairsPropsType) {
return (
<div className={s.container}>
<div className={s.buttonContainer}>
<button id={'hw2-button-all'} onClick={setAll} className={cnAll}>All</button>
<button id={'hw2-button-high'} onClick={setHigh} className={cnHigh}>High</button>
<button id={'hw2-button-middle'} onClick={setMiddle} className={cnMiddle}>Middle</button>
<button id={'hw2-button-low'} onClick={setLow} className={cnLow}>Low</button>
</div>
<div className={s.affairs}>
{mappedAffairs}
<button
id={'hw2-button-all'}
onClick={setAll}
className={cnAll}
>
All
</button>
<button
id={'hw2-button-high'}
onClick={setHigh}
className={cnHigh}
>
High
</button>
<button
id={'hw2-button-middle'}
onClick={setMiddle}
className={cnMiddle}
>
Middle
</button>
<button
id={'hw2-button-low'}
onClick={setLow}
className={cnLow}
>
Low
</button>
</div>
<div className={s.affairs}>{mappedAffairs}</div>
{/*<button onClick={set} className={setClass('all')} value={'all'}>All</button>*/}
{/*<button onClick={set} className={setClass('high')} value={'high'}>High</button>*/}
{/*<button onClick={set} className={setClass('middle')} value={'middle'}>Middle</button>*/}

View File

@@ -1,11 +1,7 @@
import React from 'react'
function AlternativeAffairs() {
return (
<div>
</div>
)
return <div></div>
}
export default AlternativeAffairs

View File

@@ -13,16 +13,18 @@ export type AffairType = {
export type FilterType = 'all' | AffairPriorityType
// constants
const defaultAffairs: any = [ // need to fix any // AffairType[]
{_id: 1, name: 'React', priority: 'high'}, // студенты могут изменить содержимое name и количество элементов в массиве, ...priority не менять!
{_id: 2, name: 'anime', priority: 'low'},
{_id: 3, name: 'games', priority: 'low'},
{_id: 4, name: 'work', priority: 'high'},
{_id: 5, name: 'html & css', priority: 'middle'},
const defaultAffairs: any = [
// need to fix any // AffairType[]
{ _id: 1, name: 'React', priority: 'high' }, // студенты могут изменить содержимое name и количество элементов в массиве, ...priority не менять!
{ _id: 2, name: 'anime', priority: 'low' },
{ _id: 3, name: 'games', priority: 'low' },
{ _id: 4, name: 'work', priority: 'high' },
{ _id: 5, name: 'html & css', priority: 'middle' },
]
// pure helper functions
export const filterAffairs = (affairs: any, filter: any): any => { // need to fix any // (affairs: AffairType[], filter: FilterType): AffairType[]
export const filterAffairs = (affairs: any, filter: any): any => {
// need to fix any // (affairs: AffairType[], filter: FilterType): AffairType[]
if (filter === 'all') return affairs // создаёт студент
// else if (filter === 'low') return affairs.filter(a => a.priority === 'low')
// else if (filter === 'middle') return affairs.filter(a => a.priority === 'middle')
@@ -32,7 +34,8 @@ export const filterAffairs = (affairs: any, filter: any): any => { // need to fi
// return []
else return affairs.filter((a: any) => a.priority === filter) // need to fix // создаёт студент
}
export const deleteAffair = (affairs: any, _id: any): any => { // need to fix any // (affairs: AffairType[], _id: number): AffairType[]
export const deleteAffair = (affairs: any, _id: any): any => {
// need to fix any // (affairs: AffairType[], _id: number): AffairType[]
return affairs.filter((a: any) => a._id !== _id) // need to fix // создаёт студент
}
@@ -41,15 +44,16 @@ function HW2() {
const [filter, setFilter] = useState<any>('all') // need to fix any // FilterType
const filteredAffairs = filterAffairs(affairs, filter)
const deleteAffairCallback = (_id: any) => setAffairs(deleteAffair(affairs, _id)) // need to fix any // number
const deleteAffairCallback = (_id: any) =>
setAffairs(deleteAffair(affairs, _id)) // need to fix any // number
return (
<div id={'hw2'} className={s2.hw} style={{marginTop: '39px'}}>
<div id={'hw2'} className={s2.hw} style={{ marginTop: '39px' }}>
{/*<hr/>*/}
{/*можно убрать этот тег*/}
<div className={s2.hwTitle}>Homework #2</div>
<hr/>
<hr />
{/*не менять*/}
<Affairs
@@ -61,7 +65,7 @@ function HW2() {
{/*<hr/>*/}
{/*можно убрать этот тег*/}
<hr/>
<hr />
{/*можно убрать этот тег*/}
</div>
)

View File

@@ -1,16 +1,16 @@
import React from 'react'
import {AffairType, deleteAffair} from '../HW2'
import { AffairType, deleteAffair } from '../HW2'
let initialState: AffairType[]
beforeEach(() => {
initialState = [
{_id: 1, name: 'React', priority: 'high'},
{_id: 2, name: 'anime', priority: 'low'},
{_id: 3, name: 'games', priority: 'low'},
{_id: 4, name: 'work', priority: 'high'},
{_id: 5, name: 'html & css', priority: 'middle'},
{_id: 6, name: 'porn', priority: 'low'},
{ _id: 1, name: 'React', priority: 'high' },
{ _id: 2, name: 'anime', priority: 'low' },
{ _id: 3, name: 'games', priority: 'low' },
{ _id: 4, name: 'work', priority: 'high' },
{ _id: 5, name: 'html & css', priority: 'middle' },
{ _id: 6, name: 'porn', priority: 'low' },
]
})

View File

@@ -1,16 +1,16 @@
import React from 'react'
import {AffairType, filterAffairs} from '../HW2'
import { AffairType, filterAffairs } from '../HW2'
let initialState: AffairType[]
beforeEach(() => {
initialState = [
{_id: 1, name: 'React', priority: 'high'},
{_id: 2, name: 'anime', priority: 'low'},
{_id: 3, name: 'games', priority: 'low'},
{_id: 4, name: 'work', priority: 'high'},
{_id: 5, name: 'html & css', priority: 'middle'},
{_id: 6, name: 'porn', priority: 'low'},
{ _id: 1, name: 'React', priority: 'high' },
{ _id: 2, name: 'anime', priority: 'low' },
{ _id: 3, name: 'games', priority: 'low' },
{ _id: 4, name: 'work', priority: 'high' },
{ _id: 5, name: 'html & css', priority: 'middle' },
{ _id: 6, name: 'porn', priority: 'low' },
]
})

View File

@@ -14,13 +14,24 @@ type GreetingPropsType = {
// презентационная компонента (для верстальщика)
const Greeting: React.FC<GreetingPropsType> = (
{name, setNameCallback, addUser, onEnter, error, totalUsers, lastUser, onBlur} // деструктуризация пропсов
{
name,
setNameCallback,
addUser,
onEnter,
error,
totalUsers,
lastUser,
onBlur,
} // деструктуризация пропсов
) => {
const inputClass = error ? `${s.input} ${s.errorInput}` : s.input // need to fix with (?:)
return (
<div id={'hw3-form'} className={s.greetingForm}>
<div id={'hw3-users-total'} className={s.count}>{totalUsers}</div>
<div id={'hw3-users-total'} className={s.count}>
{totalUsers}
</div>
<div className={s.inputAndButtonContainer}>
<div>
<input
@@ -31,18 +42,24 @@ const Greeting: React.FC<GreetingPropsType> = (
onKeyDown={onEnter}
onBlur={onBlur}
/>
<div id={'hw3-error'} className={s.error}>{error}</div>
<div id={'hw3-error'} className={s.error}>
{error}
</div>
</div>
<button id={'hw3-button'} onClick={addUser} className={s.button} disabled={!name}>add</button>
<button
id={'hw3-button'}
onClick={addUser}
className={s.button}
disabled={!name}
>
add
</button>
</div>
{lastUser && (
<div className={s.greeting}>
hello{' '}
<span id={'hw3-last-user'}>{lastUser}</span>
!
hello <span id={'hw3-last-user'}>{lastUser}</span>!
</div>
)}
</div>

View File

@@ -11,11 +11,16 @@ type GreetingContainerPropsType = {
// function GreetingContainer(props: GreetingPropsType) {
// более современный и удобный для про :)
const GreetingContainer: React.FC<GreetingContainerPropsType> = ({users, addUserCallback}) => { // деструктуризация пропсов
const GreetingContainer: React.FC<GreetingContainerPropsType> = ({
users,
addUserCallback,
}) => {
// деструктуризация пропсов
const [name, setName] = useState<string>('') // need to fix any
const [error, setError] = useState<string>('') // need to fix any
const setNameCallback = (e: ChangeEvent<HTMLInputElement>) => { // need to fix any // нельзя пробелы перед и после имени, можно в середине
const setNameCallback = (e: ChangeEvent<HTMLInputElement>) => {
// need to fix any // нельзя пробелы перед и после имени, можно в середине
setName(e.currentTarget.value) // need to fix
error && setError('')
}

View File

@@ -6,14 +6,15 @@ import GreetingContainer from './GreetingContainer'
// types
export type UserType = {
_id: string// need to fix any
_id: string // need to fix any
name: string // need to fix any
}
const HW3 = () => {
const [users, setUsers] = useState<UserType[]>([]) // need to fix any
const addUserCallback = (name: string) => { // need to fix any
const addUserCallback = (name: string) => {
// need to fix any
const user = {
_id: v1(),
name,
@@ -30,11 +31,13 @@ const HW3 = () => {
{/*для автоматической проверки дз (не менять)*/}
<hr/>
<hr />
{/*можно убрать этот тег*/}
<GreetingContainer users={users} addUserCallback={addUserCallback}/>
<hr/>
<GreetingContainer
users={users}
addUserCallback={addUserCallback}
/>
<hr />
{/*можно убрать этот тег*/}
</div>
)

View File

@@ -8,12 +8,12 @@ const HW4 = () => {
{/*можно убрать этот тег*/}
<div className={s2.hwTitle}>Homework #4</div>
<hr/>
<hr />
{/*проверка отображения*/}
{/*демонстрация возможностей компонент:*/}
<Stand/>
<Stand />
<hr/>
<hr />
{/*можно убрать этот тег*/}
{/*<hr/>*/}
{/*можно убрать этот тег*/}

View File

@@ -1,8 +1,8 @@
import React, {useState} from 'react'
import React, { useState } from 'react'
import s from './Stand.module.css'
import SuperInputText from './common/c1-SuperInputText/SuperInputText'
import SuperCheckbox from './common/c3-SuperCheckbox/SuperCheckbox'
import SuperButton from "./common/c2-SuperButton/SuperButton";
import SuperButton from './common/c2-SuperButton/SuperButton'
const Stand = () => {
const [stateForAllInputs, setValue] = useState('')
@@ -21,7 +21,11 @@ const Stand = () => {
onChangeText={setValue}
error={error}
onEnter={() => {
setError(stateForAllInputs.trim() ? undefined : 'some error')
setError(
stateForAllInputs.trim()
? undefined
: 'some error'
)
setValue('')
}}
/>
@@ -31,7 +35,7 @@ const Stand = () => {
<SuperInputText
id={'hw4-super-input-like-old'}
value={stateForAllInputs}
onChange={e => setValue(e.currentTarget.value)}
onChange={(e) => setValue(e.currentTarget.value)}
/>
</div>
</div>
@@ -39,17 +43,26 @@ const Stand = () => {
<div className={s.buttons}>
{/*обычная кнопка:*/}
<div>
<SuperButton id={'hw4-super-button-default'}>default</SuperButton>
<SuperButton id={'hw4-super-button-default'}>
default
</SuperButton>
</div>
{/*красная кнопка:*/}
<div>
<SuperButton id={'hw4-super-button-red'} xType={'red'}>red</SuperButton>
<SuperButton id={'hw4-super-button-red'} xType={'red'}>
red
</SuperButton>
</div>
{/*задизэйбленная кнопка:*/}
<div>
<SuperButton id={'hw4-super-button-disabled'} xType={'red'} disabled>disabled</SuperButton>
<SuperButton
id={'hw4-super-button-disabled'}
xType={'red'}
disabled
>
disabled
</SuperButton>
</div>
</div>
<div className={s.checkboxes}>
@@ -68,7 +81,7 @@ const Stand = () => {
<SuperCheckbox
id={'hw4-super-checkbox-like-old'}
checked={stateForAllCheckboxes}
onChange={e => setChecked(e.currentTarget.checked)}
onChange={(e) => setChecked(e.currentTarget.checked)}
/>
</div>
</div>

View File

@@ -1,29 +1,40 @@
import React, { ChangeEvent, DetailedHTMLProps, InputHTMLAttributes, KeyboardEvent, ReactNode } from 'react'
import React, {
ChangeEvent,
DetailedHTMLProps,
InputHTMLAttributes,
KeyboardEvent,
ReactNode,
} from 'react'
import s from './SuperInputText.module.css'
// тип пропсов обычного инпута
type DefaultInputPropsType = DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>
type DefaultInputPropsType = DetailedHTMLProps<
InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>
// здесь мы говорим что у нашего инпута будут такие же пропсы как у обычного инпута, кроме type
// (чтоб не писать value: string, onChange: ...; они уже все описаны в DefaultInputPropsType)
type SuperInputTextPropsType = Omit<DefaultInputPropsType, 'type'> & { // и + ещё пропсы которых нет в стандартном инпуте
type SuperInputTextPropsType = Omit<DefaultInputPropsType, 'type'> & {
// и + ещё пропсы которых нет в стандартном инпуте
onChangeText?: (value: string) => void
onEnter?: () => void
error?: ReactNode
spanClassName?: string
}
const SuperInputText: React.FC<SuperInputTextPropsType> = (
{
onChange, onChangeText,
onKeyPress, onEnter,
const SuperInputText: React.FC<SuperInputTextPropsType> = ({
onChange,
onChangeText,
onKeyPress,
onEnter,
error,
className, spanClassName,
className,
spanClassName,
id,
...restProps// все остальные пропсы попадут в объект restProps
}
) => {
...restProps // все остальные пропсы попадут в объект restProps
}) => {
const onChangeCallback = (e: ChangeEvent<HTMLInputElement>) => {
onChange?.(e) // если есть пропс onChange, то передать ему е (поскольку onChange не обязателен)
@@ -32,13 +43,17 @@ const SuperInputText: React.FC<SuperInputTextPropsType> = (
const onKeyPressCallback = (e: KeyboardEvent<HTMLInputElement>) => {
onKeyPress?.(e)
onEnter // если есть пропс onEnter
&& e.key === 'Enter' // и если нажата кнопка Enter
&& onEnter() // то вызвать его
onEnter && // если есть пропс onEnter
e.key === 'Enter' && // и если нажата кнопка Enter
onEnter() // то вызвать его
}
const finalSpanClassName = `${s.error} ${spanClassName ? spanClassName : ''}`
const finalInputClassName = `${s.input} ${error ? s.errorInput : s.superInput} ${className}` // задача на смешивание классов
const finalSpanClassName = `${s.error} ${
spanClassName ? spanClassName : ''
}`
const finalInputClassName = `${s.input} ${
error ? s.errorInput : s.superInput
} ${className}` // задача на смешивание классов
return (
<div className={s.inputWrapper}>
@@ -48,10 +63,14 @@ const SuperInputText: React.FC<SuperInputTextPropsType> = (
onChange={onChangeCallback}
onKeyPress={onKeyPressCallback}
className={finalInputClassName}
{...restProps} // отдаём инпуту остальные пропсы если они есть (value например там внутри)
/>
<span id={id ? id + '-span' : undefined} className={finalSpanClassName}>{error}</span>
<span
id={id ? id + '-span' : undefined}
className={finalSpanClassName}
>
{error}
</span>
</div>
)
}

View File

@@ -1,26 +1,24 @@
import React, {ButtonHTMLAttributes, DetailedHTMLProps} from 'react'
import React, { ButtonHTMLAttributes, DetailedHTMLProps } from 'react'
import s from './SuperButton.module.css'
// тип пропсов обычной кнопки, children в котором храниться название кнопки там уже описан
type DefaultButtonPropsType = DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
type DefaultButtonPropsType = DetailedHTMLProps<
ButtonHTMLAttributes<HTMLButtonElement>,
HTMLButtonElement
>
type SuperButtonPropsType = DefaultButtonPropsType & {
xType?: string
}
const SuperButton: React.FC<SuperButtonPropsType> = (
{
xType, className,
const SuperButton: React.FC<SuperButtonPropsType> = ({
xType,
className,
disabled,
...restProps// все остальные пропсы попадут в объект restProps, там же будет children
}
) => {
...restProps // все остальные пропсы попадут в объект restProps, там же будет children
}) => {
const finalClassName = `${s.button} ${
disabled
? s.disabled
: xType === 'red'
? s.red
: s.default
disabled ? s.disabled : xType === 'red' ? s.red : s.default
} ${className}` // задачка на смешивание классов
return (

View File

@@ -30,7 +30,7 @@
.checkbox:checked {
appearance: none;
background-image: url("checked.svg");
background-image: url('checked.svg');
/*background: #99ff99;*/
}

View File

@@ -1,25 +1,33 @@
import React, {ChangeEvent, DetailedHTMLProps, InputHTMLAttributes} from 'react'
import React, {
ChangeEvent,
DetailedHTMLProps,
InputHTMLAttributes,
} from 'react'
import s from './SuperCheckbox.module.css'
// тип пропсов обычного инпута
type DefaultInputPropsType = DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>
type DefaultInputPropsType = DetailedHTMLProps<
InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>
type SuperCheckboxPropsType = Omit<DefaultInputPropsType, 'type'> & {
onChangeChecked?: (checked: boolean) => void
spanClassName?: string
}
const SuperCheckbox: React.FC<SuperCheckboxPropsType> = (
{
onChange, onChangeChecked,
className, spanClassName,
const SuperCheckbox: React.FC<SuperCheckboxPropsType> = ({
onChange,
onChangeChecked,
className,
spanClassName,
children, // в эту переменную попадёт текст, типизировать не нужно так как он затипизирован в React.FC
id,
...restProps// все остальные пропсы попадут в объект restProps
}
) => {
const onChangeCallback = (e: ChangeEvent<HTMLInputElement>) => { // задачка на написание онченджа
...restProps // все остальные пропсы попадут в объект restProps
}) => {
const onChangeCallback = (e: ChangeEvent<HTMLInputElement>) => {
// задачка на написание онченджа
onChange?.(e)
onChangeChecked?.(e.currentTarget.checked)
@@ -34,10 +42,16 @@ const SuperCheckbox: React.FC<SuperCheckboxPropsType> = (
type={'checkbox'}
onChange={onChangeCallback}
className={finalInputClassName}
{...restProps} // отдаём инпуту остальные пропсы если они есть (checked например там внутри)
/>
{children && <span id={id ? id + '-span' : undefined} className={s.spanClassName}>{children}</span>}
{children && (
<span
id={id ? id + '-span' : undefined}
className={s.spanClassName}
>
{children}
</span>
)}
</label> // благодаря label нажатие на спан передастся в инпут
)
}

View File

@@ -8,7 +8,7 @@ function HW5() {
<HashRouter>
{/*в gh-pages лучше работает HashRouter*/}
<Layout>
<Pages/>
<Pages />
</Layout>
</HashRouter>
)

View File

@@ -1,5 +1,5 @@
import React from 'react'
import {Routes, Route, Navigate} from 'react-router-dom'
import { Routes, Route, Navigate } from 'react-router-dom'
import Error404 from './pages/Error404'
import PreJunior from './pages/PreJunior'
import Junior from './pages/Junior'
@@ -16,18 +16,16 @@ function Pages() {
<div>
{/*Routes выбирает первый подходящий роут*/}
<Routes>
{/*роутинг будут писать студенты*/}
{/*в начале мы попадаем на страницу '/' и переходим сразу на страницу PRE_JUNIOR*/}
<Route path={'/'} element={<Navigate to={PATH.PRE_JUNIOR}/>}/>
<Route path={'/'} element={<Navigate to={PATH.PRE_JUNIOR} />} />
<Route path={PATH.PRE_JUNIOR} element={<PreJunior/>}/>
<Route path={PATH.JUNIOR} element={<Junior/>}/>
<Route path={PATH.JUNIOR_PLUS} element={<JuniorPlus/>}/>
<Route path={PATH.PRE_JUNIOR} element={<PreJunior />} />
<Route path={PATH.JUNIOR} element={<Junior />} />
<Route path={PATH.JUNIOR_PLUS} element={<JuniorPlus />} />
{/*он отрисуется если пользователь захочет попасть на несуществующую страницу*/}
<Route path={'/*'} element={<Error404/>}/>
<Route path={'/*'} element={<Error404 />} />
</Routes>
</div>
)

View File

@@ -7,21 +7,19 @@ type PropsType = {
handleOpen: () => void
}
export const Header: FC<PropsType> = ({open, handleOpen}) => {
export const Header: FC<PropsType> = ({ open, handleOpen }) => {
// hw5-menu изначально отсутствует, при нажатии на бургер - появляется, при повторном нажатии исчезает
return (
<>
<div id={'hw5-header'} className={s.header}>
<img src={burgerIcon}
<img
src={burgerIcon}
id={'hw5-burger-menu'}
className={s.burgerMenuIcon}
onClick={handleOpen}
alt={'open menu'}/>
alt={'open menu'}
/>
</div>
</>
)
}

View File

@@ -6,7 +6,7 @@ type PropsType = {
children: ReactNode
}
export const Layout: FC<PropsType> = ({children}) => {
export const Layout: FC<PropsType> = ({ children }) => {
const [open, setOpen] = useState(false)
const handleClose = () => setOpen(false)
const handleOpen = () => setOpen(true)
@@ -17,11 +17,9 @@ export const Layout: FC<PropsType> = ({children}) => {
return (
<>
<Sidebar open={open} handleClose={handleClose}/>
<Header open={open} handleOpen={handleOpen}/>
<Sidebar open={open} handleClose={handleClose} />
<Header open={open} handleOpen={handleOpen} />
{children}
</>
)
}

View File

@@ -8,10 +8,10 @@ function Junior() {
return (
<div id={'hw5-page-junior'}>
junior page
<HW6/>
<HW7/>
<HW8/>
<HW9/>
<HW6 />
<HW7 />
<HW8 />
<HW9 />
</div>
)
}

View File

@@ -8,10 +8,10 @@ function JuniorPlus() {
return (
<div id={'hw5-page-junior-plus'}>
junior plus page
<HW10/>
<HW11/>
<HW12/>
<HW13/>
<HW10 />
<HW11 />
<HW12 />
<HW13 />
</div>
)
}

View File

@@ -8,10 +8,10 @@ function PreJunior() {
return (
<div id={'hw5-page-pre-junior'}>
{/*pre junior page*/}
<HW1/>
<HW2/>
<HW3/>
<HW4/>
<HW1 />
<HW2 />
<HW3 />
<HW4 />
</div>
)
}

View File

@@ -12,7 +12,8 @@
}
.sidebar.open {
box-shadow: 0 10px 40px rgba(29, 33, 38, 0.13), 0 1px 2px rgba(29, 33, 38, 0.1);
box-shadow: 0 10px 40px rgba(29, 33, 38, 0.13),
0 1px 2px rgba(29, 33, 38, 0.1);
left: 0;
position: fixed;
transition: 0.2s ease-out;

View File

@@ -9,28 +9,27 @@ type PropsType = {
handleClose: () => void
}
export const Sidebar: FC<PropsType> = ({open, handleClose}) => {
export const Sidebar: FC<PropsType> = ({ open, handleClose }) => {
return (
<>
{/*бэкграунд справа от открытого меню*/}
{open && <div className={s.background} onClick={handleClose}/>}
{open && <div className={s.background} onClick={handleClose} />}
<aside className={`${s.sidebar} ${open ? s.open : ''}`}>
<button className={s.close} onClick={handleClose}>
<img
src={closeIcon}
alt='close sidebar'
alt="close sidebar"
id={'hw5-menu-close'}
/>
</button>
<nav id={'hw5-menu'} className={s.nav}>
<NavLink
id={'hw5-pre-junior-link'}
to={PATH.PRE_JUNIOR}
onClick={handleClose}
className={({isActive}) => isActive ? s.active : ''} // делает студент
className={({ isActive }) => (isActive ? s.active : '')} // делает студент
>
Pre-junior
</NavLink>
@@ -38,7 +37,7 @@ export const Sidebar: FC<PropsType> = ({open, handleClose}) => {
id={'hw5-junior-link'}
to={PATH.JUNIOR}
onClick={handleClose}
className={({isActive}) => isActive ? s.active : ''} // делает студент
className={({ isActive }) => (isActive ? s.active : '')} // делает студент
>
Junior
</NavLink>
@@ -46,14 +45,12 @@ export const Sidebar: FC<PropsType> = ({open, handleClose}) => {
id={'hw5-junior-plus-link'}
to={PATH.JUNIOR_PLUS}
onClick={handleClose}
className={({isActive}) => isActive ? s.active : ''} // делает студент
className={({ isActive }) => (isActive ? s.active : '')} // делает студент
>
Junior+
</NavLink>
</nav>
</aside>
</>
)
}

View File

@@ -1,6 +1,6 @@
import React, {useState} from 'react'
import React, { useState } from 'react'
import SuperEditableSpan from './common/c4-SuperEditableSpan/SuperEditableSpan'
import {restoreState, saveState} from './localStorage/localStorage'
import { restoreState, saveState } from './localStorage/localStorage'
import s2 from '../../s1-main/App.module.css'
import SuperButton from '../hw04/common/c2-SuperButton/SuperButton'
@@ -10,13 +10,14 @@ const HW6 = () => {
const save = () => {
saveState<string>('hw6-editable-span-value', value)
}
const restore = () => { // делают студенты
const restore = () => {
// делают студенты
setValue(restoreState<string>('hw6-editable-span-value', ''))
}
return (
<div id={'hw6'} className={s2.hw}>
<hr/>
<hr />
{/*можно убрать этот тег*/}
<div className={s2.hwTitle}>homeworks 6</div>
@@ -27,15 +28,22 @@ const HW6 = () => {
id={'hw6-spanable-input'}
value={value}
onChangeText={setValue}
spanProps={{children: value ? undefined : 'enter text...', id: 'hw6-editable-span'}}
spanProps={{
children: value ? undefined : 'enter text...',
id: 'hw6-editable-span',
}}
/>
</div>
<SuperButton id={'hw6-save'} onClick={save}>save to ls</SuperButton>
<SuperButton id={'hw6-restore'} onClick={restore}>get from ls</SuperButton>
<SuperButton id={'hw6-save'} onClick={save}>
save to ls
</SuperButton>
<SuperButton id={'hw6-restore'} onClick={restore}>
get from ls
</SuperButton>
<hr/>
<hr />
{/*можно убрать этот тег*/}
<hr/>
<hr />
{/*можно убрать этот тег*/}
</div>
)

View File

@@ -1,15 +1,27 @@
import React, {DetailedHTMLProps, InputHTMLAttributes, HTMLAttributes, useState} from 'react'
import React, {
DetailedHTMLProps,
InputHTMLAttributes,
HTMLAttributes,
useState,
} from 'react'
import s from './SuperEditableSpan.module.css'
import SuperInputText from '../../../hw04/common/c1-SuperInputText/SuperInputText'
// тип пропсов обычного инпута
type DefaultInputPropsType = DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>
type DefaultInputPropsType = DetailedHTMLProps<
InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>
// тип пропсов обычного спана
type DefaultSpanPropsType = DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>
type DefaultSpanPropsType = DetailedHTMLProps<
HTMLAttributes<HTMLSpanElement>,
HTMLSpanElement
>
// здесь мы говорим что у нашего инпута будут такие же пропсы как у обычного инпута, кроме type
// (чтоб не писать value: string, onChange: ...; они уже все описаны в DefaultInputPropsType)
type SuperEditableSpanType = Omit<DefaultInputPropsType, 'type'> & { // и + ещё пропсы которых нет в стандартном инпуте
type SuperEditableSpanType = Omit<DefaultInputPropsType, 'type'> & {
// и + ещё пропсы которых нет в стандартном инпуте
onChangeText?: (value: string) => void
onEnter?: () => void
error?: string
@@ -17,18 +29,17 @@ type SuperEditableSpanType = Omit<DefaultInputPropsType, 'type'> & { // и + е
spanProps?: DefaultSpanPropsType // пропсы для спана
}
const SuperEditableSpan: React.FC<SuperEditableSpanType> = (
{
const SuperEditableSpan: React.FC<SuperEditableSpanType> = ({
autoFocus,
onBlur,
onEnter,
spanProps,
...restProps// все остальные пропсы попадут в объект restProps
}
) => {
...restProps // все остальные пропсы попадут в объект restProps
}) => {
const [editMode, setEditMode] = useState<boolean>(false)
const {children, onDoubleClick, className, ...restSpanProps} = spanProps || {}
const { children, onDoubleClick, className, ...restSpanProps } =
spanProps || {}
const onEnterCallback = () => {
setEditMode(false) // выключить editMode при нажатии Enter // делают студенты
@@ -40,7 +51,9 @@ const SuperEditableSpan: React.FC<SuperEditableSpanType> = (
onBlur?.(e)
}
const onDoubleClickCallBack = (e: React.MouseEvent<HTMLSpanElement, MouseEvent>) => {
const onDoubleClickCallBack = (
e: React.MouseEvent<HTMLSpanElement, MouseEvent>
) => {
setEditMode(true) // включить editMode при двойном клике // делают студенты
onDoubleClick?.(e)
@@ -50,27 +63,23 @@ const SuperEditableSpan: React.FC<SuperEditableSpanType> = (
return (
<>
{editMode
? (
{editMode ? (
<SuperInputText
autoFocus={autoFocus || true}
onBlur={onBlurCallback}
onEnter={onEnterCallback}
{...restProps} // отдаём инпуту остальные пропсы если они есть (value например там внутри)
/>
) : (
<span
onDoubleClick={onDoubleClickCallBack}
className={spanClassName}
{...restSpanProps}
>
{/*если нет захардкодженного текста для спана, то значение инпута*/}
{children || restProps.value}
</span>
)
}
)}
</>
)
}

View File

@@ -21,7 +21,7 @@ type StateType = {
}
// сохраняем объект типа StateType в ячейке 'test'
saveState<StateType>('test', {x: 'A', y: 1})
saveState<StateType>('test', { x: 'A', y: 1 })
// получем в переменную state объект из ячейки 'test' или дэфолтный объект если ячейка пуста
const state: StateType = restoreState<StateType>('test', {x: '', y: 0})
const state: StateType = restoreState<StateType>('test', { x: '', y: 0 })

View File

@@ -1,9 +1,13 @@
import React, {useState} from 'react'
import React, { useState } from 'react'
import SuperSelect from './common/c5-SuperSelect/SuperSelect'
import SuperRadio from './common/c6-SuperRadio/SuperRadio'
import s2 from '../../s1-main/App.module.css'
const arr = [{id: 1, value: 'x'}, {id: 2, value: 'y'}, {id: 3, value: 'z'}] // value может быть изменено
const arr = [
{ id: 1, value: 'x' },
{ id: 2, value: 'y' },
{ id: 3, value: 'z' },
] // value может быть изменено
const HW7 = () => {
const [value, onChangeOption] = useState(1) // селект и радио должны работать синхронно
@@ -11,7 +15,7 @@ const HW7 = () => {
return (
<div id={'hw7'} className={s2.hw}>
<hr/>
<hr />
{/*можно убрать этот тег*/}
<div className={s2.hwTitle}>homeworks 7</div>
@@ -35,9 +39,9 @@ const HW7 = () => {
/>
</div>
<hr/>
<hr />
{/*можно убрать этот тег*/}
<hr/>
<hr />
{/*можно убрать этот тег*/}
</div>
)

View File

@@ -1,37 +1,54 @@
import React, {SelectHTMLAttributes, DetailedHTMLProps, ChangeEvent} from 'react'
import React, {
SelectHTMLAttributes,
DetailedHTMLProps,
ChangeEvent,
} from 'react'
import s from './SuperSelect.module.css'
type DefaultSelectPropsType = DetailedHTMLProps<SelectHTMLAttributes<HTMLSelectElement>, HTMLSelectElement>
type DefaultSelectPropsType = DetailedHTMLProps<
SelectHTMLAttributes<HTMLSelectElement>,
HTMLSelectElement
>
type SuperSelectPropsType = DefaultSelectPropsType & {
options?: any[]
onChangeOption?: (option: any) => void
}
const SuperSelect: React.FC<SuperSelectPropsType> = (
{
options, className,
onChange, onChangeOption,
const SuperSelect: React.FC<SuperSelectPropsType> = ({
options,
className,
onChange,
onChangeOption,
...restProps
}
) => {
const mappedOptions: any[] = options ? options.map(o => (
<option id={'hw7-option-' + o.id} className={s.option} key={o.id} value={o.id}>{o.value}</option>
)) : [] // map options with key
}) => {
const mappedOptions: any[] = options
? options.map((o) => (
<option
id={'hw7-option-' + o.id}
className={s.option}
key={o.id}
value={o.id}
>
{o.value}
</option>
))
: [] // map options with key
const onChangeCallback = (e: ChangeEvent<HTMLSelectElement>) => { // делают студенты
const onChangeCallback = (e: ChangeEvent<HTMLSelectElement>) => {
// делают студенты
onChange?.(e)
onChangeOption?.(+e.currentTarget.value)
}
const finalSelectClassName = s.select + (
className
? ' ' + className
: ''
)
const finalSelectClassName = s.select + (className ? ' ' + className : '')
return (
<select className={finalSelectClassName} onChange={onChangeCallback} {...restProps}>
<select
className={finalSelectClassName}
onChange={onChangeCallback}
{...restProps}
>
{mappedOptions}
</select>
)

View File

@@ -1,9 +1,20 @@
import React, {ChangeEvent, InputHTMLAttributes, DetailedHTMLProps, HTMLAttributes} from 'react'
import React, {
ChangeEvent,
InputHTMLAttributes,
DetailedHTMLProps,
HTMLAttributes,
} from 'react'
import s from './SuperRadio.module.css'
type DefaultRadioPropsType = DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>
type DefaultRadioPropsType = DetailedHTMLProps<
InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>
// тип пропсов обычного спана
type DefaultSpanPropsType = DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>
type DefaultSpanPropsType = DetailedHTMLProps<
HTMLAttributes<HTMLSpanElement>,
HTMLSpanElement
>
type SuperRadioPropsType = Omit<DefaultRadioPropsType, 'type'> & {
options?: any[]
@@ -12,36 +23,38 @@ type SuperRadioPropsType = Omit<DefaultRadioPropsType, 'type'> & {
spanProps?: DefaultSpanPropsType // пропсы для спана
}
const SuperRadio: React.FC<SuperRadioPropsType> = (
{
const SuperRadio: React.FC<SuperRadioPropsType> = ({
id,
name, className,
options, value,
onChange, onChangeOption,
name,
className,
options,
value,
onChange,
onChangeOption,
spanProps,
...restProps
}
) => {
}) => {
const onChangeCallback = (e: ChangeEvent<HTMLInputElement>) => {
onChange?.(e)
onChangeOption?.(+e.currentTarget.value)
}
const finalRadioClassName = `${s.radio} ${className ? className : ''}`
const spanClassName = `${s.span} ${spanProps?.className ? spanProps.className : ''}`
const spanClassName = `${s.span} ${
spanProps?.className ? spanProps.className : ''
}`
const mappedOptions: any[] = options ? options.map(o => (
const mappedOptions: any[] = options
? options.map((o) => (
<label key={name + '-' + o.id} className={s.label}>
<input
id={id + '-input-' + o.id}
className={finalRadioClassName}
type={'radio'}
// name, checked, value делают студенты
name={name}
checked={o.id === value}
value={o.id}
onChange={onChangeCallback}
{...restProps}
/>
@@ -53,13 +66,10 @@ const SuperRadio: React.FC<SuperRadioPropsType> = (
{o.value}
</span>
</label>
)) : []
))
: []
return (
<>
{mappedOptions}
</>
)
return <>{mappedOptions}</>
}
export default SuperRadio

View File

@@ -1,55 +1,70 @@
import React, {useState} from 'react'
import {homeWorkReducer} from './bll/homeWorkReducer'
import React, { useState } from 'react'
import { homeWorkReducer } from './bll/homeWorkReducer'
import s from './HW8.module.css'
import s2 from '../../s1-main/App.module.css'
import SuperButton from '../hw04/common/c2-SuperButton/SuperButton'
import User from './User'
export type UserType = { // need to fix any
export type UserType = {
// need to fix any
_id: number
name: string
age: number
}
const initialPeople: UserType[] = [ // студенты могут поменять имя/возраст/количество объектов, _id должны быть целочисленные
{_id: 0, name: 'Кот', age: 3},
{_id: 1, name: 'Александр', age: 66},
{_id: 2, name: 'Коля', age: 16},
{_id: 3, name: 'Виктор', age: 44},
{_id: 4, name: 'Дмитрий', age: 40},
{_id: 5, name: 'Ирина', age: 55},
const initialPeople: UserType[] = [
// студенты могут поменять имя/возраст/количество объектов, _id должны быть целочисленные
{ _id: 0, name: 'Кот', age: 3 },
{ _id: 1, name: 'Александр', age: 66 },
{ _id: 2, name: 'Коля', age: 16 },
{ _id: 3, name: 'Виктор', age: 44 },
{ _id: 4, name: 'Дмитрий', age: 40 },
{ _id: 5, name: 'Ирина', age: 55 },
]
const HW8 = () => {
const [people, setPeople] = useState<UserType[]>(initialPeople) // need to fix any
// need to fix any
const finalPeople = people.map((u: UserType) => <User key={u._id} u={u}/>)
const finalPeople = people.map((u: UserType) => <User key={u._id} u={u} />)
const sortUp = () => setPeople(homeWorkReducer(initialPeople, {type: 'sort', payload: 'up'})) // в алфавитном порядке a.name > b.name
const sortDown = () => setPeople(homeWorkReducer(initialPeople, {type: 'sort', payload: 'down'})) // в обратном порядке a.name < b.name
const check18 = () => setPeople(homeWorkReducer(initialPeople, {type: 'check', payload: 18})) // совершеннолетние
const sortUp = () =>
setPeople(
homeWorkReducer(initialPeople, { type: 'sort', payload: 'up' })
) // в алфавитном порядке a.name > b.name
const sortDown = () =>
setPeople(
homeWorkReducer(initialPeople, { type: 'sort', payload: 'down' })
) // в обратном порядке a.name < b.name
const check18 = () =>
setPeople(
homeWorkReducer(initialPeople, { type: 'check', payload: 18 })
) // совершеннолетние
return (
<div id={'hw3'} className={s2.hw}>
<hr/>
<hr />
{/*можно убрать этот тег*/}
<div className={s2.hwTitle}>homeworks 8</div>
<div id={'hw8-users'}>
{finalPeople}
</div>
<div id={'hw8-users'}>{finalPeople}</div>
<div>
<SuperButton id={'hw8-button-up'} onClick={sortUp}>sort up</SuperButton>
<SuperButton id={'hw8-button-down'} onClick={sortDown}>sort down</SuperButton>
<SuperButton id={'hw8-button-18'} onClick={check18}>check 18</SuperButton>
<SuperButton id={'hw8-button-up'} onClick={sortUp}>
sort up
</SuperButton>
<SuperButton id={'hw8-button-down'} onClick={sortDown}>
sort down
</SuperButton>
<SuperButton id={'hw8-button-18'} onClick={check18}>
check 18
</SuperButton>
</div>
<hr/>
<hr />
{/*можно убрать этот тег*/}
<hr/>
<hr />
{/*можно убрать этот тег*/}
</div>
)

View File

@@ -1,5 +1,5 @@
import React from 'react'
import {UserType} from './HW8'
import { UserType } from './HW8'
import s from './HW8.module.css'
// types
@@ -7,8 +7,7 @@ type UserPropsType = {
u: UserType
}
const User: React.FC<UserPropsType> = ({u}) => {
const User: React.FC<UserPropsType> = ({ u }) => {
return (
<div id={'hw8-user-' + u._id + '-' + u.age} className={s.item}>
<span id={'hw8-user-name-' + u._id}>{u.name}</span>

View File

@@ -1,9 +1,17 @@
import {UserType} from '../HW8'
import { UserType } from '../HW8'
type ActionType = {type: 'sort', payload: 'up' | 'down'} | {type: 'check', payload: number}
type ActionType =
| { type: 'sort'; payload: 'up' | 'down' }
| { type: 'check'; payload: number }
export const homeWorkReducer = (state: UserType[], action: ActionType): UserType[] => { // need to fix any
switch (action.type) { // делают студенты
export const homeWorkReducer = (
state: UserType[],
action: ActionType
): UserType[] => {
// need to fix any
switch (
action.type // делают студенты
) {
case 'sort': {
const newState = [...state].sort((a, b) => {
if (a.name > b.name) return 1
@@ -14,8 +22,9 @@ export const homeWorkReducer = (state: UserType[], action: ActionType): UserType
return action.payload === 'up' ? newState : newState.reverse()
}
case 'check': {
return state.filter(a => a.age >= action.payload)
return state.filter((a) => a.age >= action.payload)
}
default: return state
default:
return state
}
}

View File

@@ -1,32 +1,41 @@
import React from 'react'
import {homeWorkReducer} from '../homeWorkReducer'
import {UserType} from '../../HW8'
import { homeWorkReducer } from '../homeWorkReducer'
import { UserType } from '../../HW8'
let initialState: UserType[] // need to fix any
beforeEach(() => {
initialState = [
{_id: 0, name: 'Кот', age: 3},
{_id: 1, name: 'Александр', age: 66},
{_id: 2, name: 'Коля', age: 16},
{_id: 3, name: 'Виктор', age: 44},
{_id: 4, name: 'Дмитрий', age: 40},
{_id: 5, name: 'Ирина', age: 55},
{ _id: 0, name: 'Кот', age: 3 },
{ _id: 1, name: 'Александр', age: 66 },
{ _id: 2, name: 'Коля', age: 16 },
{ _id: 3, name: 'Виктор', age: 44 },
{ _id: 4, name: 'Дмитрий', age: 40 },
{ _id: 5, name: 'Ирина', age: 55 },
]
})
test('sort name up', () => {
const newState = homeWorkReducer(initialState, {type: 'sort', payload: 'up'})
const newState = homeWorkReducer(initialState, {
type: 'sort',
payload: 'up',
})
expect(newState[0]._id).toBe(1)
})
test('sort name down', () => {
const newState = homeWorkReducer(initialState, {type: 'sort', payload: 'down'})
const newState = homeWorkReducer(initialState, {
type: 'sort',
payload: 'down',
})
expect(newState[0]._id).toBe(0)
})
test('check age 18', () => {
const newState = homeWorkReducer(initialState, {type: 'check', payload: 18})
const newState = homeWorkReducer(initialState, {
type: 'check',
payload: 18,
})
expect(newState.length).toBe(4)
})

View File

@@ -1,19 +1,23 @@
import React, {useState} from 'react'
import React, { useState } from 'react'
import SuperButton from '../hw04/common/c2-SuperButton/SuperButton'
import {restoreState} from '../hw06/localStorage/localStorage'
import { restoreState } from '../hw06/localStorage/localStorage'
function Clock() {
const [timerId, setTimerId] = useState<number | undefined>(undefined)
const [date, setDate] = useState<Date>(new Date(restoreState('hw9-date', 0))) // for autotests
const [date, setDate] = useState<Date>(
new Date(restoreState('hw9-date', 0))
) // for autotests
const [show, setShow] = useState<boolean>(false)
const stop = () => { // пишут студенты
const stop = () => {
// пишут студенты
if (timerId) {
clearInterval(timerId)
setTimerId(undefined)
}
}
const start = () => { // пишут студенты
const start = () => {
// пишут студенты
const id: number = +setInterval(() => {
setDate(new Date())
}, 1000)
@@ -28,11 +32,11 @@ function Clock() {
}
// логику напишет Андрей :) // |v| видел такое в реальных часах |v|
const stringTime = date?.toLocaleTimeString() || <br/> // часы24:минуты:секунды (01:02:03)/(23:02:03)/(24:00:00)/(00:00:01) // пишут студенты
const stringDate = date?.toLocaleDateString() || <br/> // день.месяц.год (01.02.2022) // пишут студенты, варианты 01.02.0123/01.02.-123/01.02.12345 не рассматриваем
const stringTime = date?.toLocaleTimeString() || <br /> // часы24:минуты:секунды (01:02:03)/(23:02:03)/(24:00:00)/(00:00:01) // пишут студенты
const stringDate = date?.toLocaleDateString() || <br /> // день.месяц.год (01.02.2022) // пишут студенты, варианты 01.02.0123/01.02.-123/01.02.12345 не рассматриваем
// день недели на английском, месяц на английском
const stringDay = 'Monday' || <br/> // пишут студенты
const stringMonth = 'May' || <br/> // пишут студенты
const stringDay = 'Monday' || <br /> // пишут студенты
const stringMonth = 'May' || <br /> // пишут студенты
return (
<div>
@@ -53,13 +57,12 @@ function Clock() {
</>
) : (
<>
<br/>
<br/>
<br />
<br />
</>
)}
</div>
<SuperButton
id={'hw9-button-start'}
disabled={!!timerId} // пишут студенты

View File

@@ -5,17 +5,17 @@ import s2 from '../../s1-main/App.module.css'
const HW9 = () => {
return (
<div id={'hw9'} className={s2.hw}>
<hr/>
<hr />
{/*можно убрать этот тег*/}
<div className={s2.hwTitle}>homeworks 9</div>
{/*should work (должно работать)*/}
<Clock/>
<Clock />
<hr/>
<hr />
{/*можно убрать этот тег*/}
<hr/>
<hr />
{/*можно убрать этот тег*/}
</div>
)

View File

@@ -1,13 +1,15 @@
import React from 'react'
import {useDispatch, useSelector} from 'react-redux'
import {AppStoreType} from './bll/store'
import {loadingAC} from './bll/loadingReducer'
import { useDispatch, useSelector } from 'react-redux'
import { AppStoreType } from './bll/store'
import { loadingAC } from './bll/loadingReducer'
import SuperButton from '../hw04/common/c2-SuperButton/SuperButton'
import s2 from '../../s1-main/App.module.css'
const HW10 = () => {
// useSelector, useDispatch
const isLoading = useSelector<AppStoreType, boolean>((state: any) => state.loading.isLoading)
const isLoading = useSelector<AppStoreType, boolean>(
(state: any) => state.loading.isLoading
)
const dispatch = useDispatch()
const setLoading = () => {
@@ -23,25 +25,28 @@ const HW10 = () => {
return (
<div id={'hw10'} className={s2.hw}>
<hr/>
<hr />
{/*можно убрать этот тег*/}
<div className={s2.hwTitle}>homeworks 10</div>
{/*should work (должно работать)*/}
{isLoading
? (
{isLoading ? (
<div id={'hw10-loading'}>крутилка...</div>
) : (
<div>
<SuperButton id={'hw10-button-start-loading'} onClick={setLoading}>set loading...</SuperButton>
<SuperButton
id={'hw10-button-start-loading'}
onClick={setLoading}
>
set loading...
</SuperButton>
</div>
)
}
)}
<hr/>
<hr />
{/*можно убрать этот тег*/}
<hr/>
<hr />
{/*можно убрать этот тег*/}
</div>
)

View File

@@ -1,16 +1,21 @@
const initState = {
isLoading: false
isLoading: false,
}
export const loadingReducer = (state = initState, action: LoadingActionType): typeof initState=> { // fix any
export const loadingReducer = (
state = initState,
action: LoadingActionType
): typeof initState => {
// fix any
switch (action.type) {
case 'CHANGE_LOADING': {
return {
...state,
isLoading: action.isLoading
isLoading: action.isLoading,
}
}
default: return state
default:
return state
}
}
@@ -19,4 +24,7 @@ type LoadingActionType = {
isLoading: boolean
}
export const loadingAC = (isLoading: boolean): LoadingActionType => ({type: 'CHANGE_LOADING', isLoading}) // fix any
export const loadingAC = (isLoading: boolean): LoadingActionType => ({
type: 'CHANGE_LOADING',
isLoading,
}) // fix any

View File

@@ -1,6 +1,6 @@
import {loadingReducer} from './loadingReducer'
import {combineReducers, legacy_createStore} from 'redux'
import {themeReducer} from '../../hw12/bll/themeReducer'
import { loadingReducer } from './loadingReducer'
import { combineReducers, legacy_createStore } from 'redux'
import { themeReducer } from '../../hw12/bll/themeReducer'
const reducers = combineReducers({
loading: loadingReducer, // hw10

View File

@@ -1,24 +1,31 @@
import React, {ChangeEvent, DetailedHTMLProps, InputHTMLAttributes} from 'react'
import React, {
ChangeEvent,
DetailedHTMLProps,
InputHTMLAttributes,
} from 'react'
import s from './SuperRange.module.css'
// тип пропсов обычного инпута
type DefaultInputPropsType = DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>
type DefaultInputPropsType = DetailedHTMLProps<
InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>
// здесь мы говорим что у нашего инпута будут такие же пропсы как у обычного инпута
// (чтоб не писать value: string, onChange: ...; они уже все описаны в DefaultInputPropsType)
type SuperRangePropsType = DefaultInputPropsType & { // и + ещё пропсы которых нет в стандартном инпуте
type SuperRangePropsType = DefaultInputPropsType & {
// и + ещё пропсы которых нет в стандартном инпуте
onChangeRange?: (value: number) => void
};
}
const SuperRange: React.FC<SuperRangePropsType> = (
{
const SuperRange: React.FC<SuperRangePropsType> = ({
type, // достаём и игнорируем чтоб нельзя было задать другой тип инпута
onChange, onChangeRange,
onChange,
onChangeRange,
className,
...restProps// все остальные пропсы попадут в объект restProps
}
) => {
...restProps // все остальные пропсы попадут в объект restProps
}) => {
const onChangeCallback = (e: ChangeEvent<HTMLInputElement>) => {
onChange && onChange(e) // сохраняем старую функциональность
@@ -35,7 +42,6 @@ const SuperRange: React.FC<SuperRangePropsType> = (
type={'range'}
onChange={onChangeCallback}
className={finalRangeClassName}
{...restProps} // отдаём инпуту остальные пропсы если они есть (value например там внутри)
/>
</>

View File

@@ -1,7 +1,10 @@
import React, {DetailedHTMLProps, InputHTMLAttributes} from 'react'
import React, { DetailedHTMLProps, InputHTMLAttributes } from 'react'
import SuperRange from '../c7-SuperRange/SuperRange'
type DefaultInputPropsType = DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>
type DefaultInputPropsType = DetailedHTMLProps<
InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>
type SuperDoubleRangePropsType = Omit<DefaultInputPropsType, 'value'> & {
onChangeRange?: (value: [number, number]) => void
@@ -9,13 +12,12 @@ type SuperDoubleRangePropsType = Omit<DefaultInputPropsType, 'value'> & {
// min, max, step, disable, ...
}
const SuperDoubleRange: React.FC<SuperDoubleRangePropsType> = (
{
onChangeRange, value,
const SuperDoubleRange: React.FC<SuperDoubleRangePropsType> = ({
onChangeRange,
value,
// min, max, step, disable, ...
...restProps
}
) => {
}) => {
// сделать самому, можно подключать библиотеки
const [value1, value2] = value || [-1, -1]
@@ -28,9 +30,26 @@ const SuperDoubleRange: React.FC<SuperDoubleRangePropsType> = (
// взять двойной ползунок из материал-юай и повесить на него ид
return (
<div id={'hw11-double-slider'} style={{position: "relative", display: "inline-block", width: 176}}>
<SuperRange style={{position: "absolute", top: -12}} value={value?.[0]} onChangeRange={change1} {...restProps}/>
<SuperRange style={{position: "absolute", top: -12}} value={value?.[1]} onChangeRange={change2} {...restProps}/>
<div
id={'hw11-double-slider'}
style={{
position: 'relative',
display: 'inline-block',
width: 176,
}}
>
<SuperRange
style={{ position: 'absolute', top: -12 }}
value={value?.[0]}
onChangeRange={change1}
{...restProps}
/>
<SuperRange
style={{ position: 'absolute', top: -12 }}
value={value?.[1]}
onChangeRange={change2}
{...restProps}
/>
</div>
)
}

View File

@@ -1,8 +1,9 @@
const initState = {
themeId: 1
themeId: 1,
}
export const themeReducer = (state = initState, action: any): any => { // fix any
export const themeReducer = (state = initState, action: any): any => {
// fix any
switch (action.type) {
case 'SET_THEME_ID': {
return {
@@ -10,8 +11,9 @@ export const themeReducer = (state = initState, action: any): any => { // fix an
themeId: action.id,
}
}
default: return state
default:
return state
}
}
export const changeThemeId = (id: number): any => ({type: 'SET_THEME_ID', id}) // fix any
export const changeThemeId = (id: number): any => ({ type: 'SET_THEME_ID', id }) // fix any

View File

@@ -2,4 +2,4 @@
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
import '@testing-library/jest-dom'

View File

@@ -1,11 +1,7 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
@@ -20,7 +16,5 @@
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
"include": ["src"]
}

View File

@@ -7358,6 +7358,11 @@ prelude-ls@~1.1.2:
resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54"
integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=
prettier@^2.7.1:
version "2.7.1"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.7.1.tgz#e235806850d057f97bb08368a4f7d899f7760c64"
integrity sha512-ujppO+MkdPqoVINuDFDRLClm7D78qbDt0/NR+wp5FqEZOoTNAjPHWj17QRhu7geIHJfcNhRk1XVQmF8Bp3ye+g==
pretty-bytes@^5.3.0, pretty-bytes@^5.4.1:
version "5.6.0"
resolved "https://registry.yarnpkg.com/pretty-bytes/-/pretty-bytes-5.6.0.tgz#356256f643804773c82f64723fe78c92c62beaeb"