1
0
Fork 0
mirror of https://github.com/muerwre/vault-frontend.git synced 2025-04-24 20:36:40 +07:00

Добавили заметки в сайдбар (#126)

* added notes sidebar

* added note dropping and editing

* added sidebar navigation

* handling sidebarchanges over time

* using router back for closing sidebar

* fixed tripping inside single sidebar

* added superpowers toggle to sidebar

* user button opens sidebar now

* added profile cover for profile sidebar

* removed profile sidebar completely

* ran prettier over project

* added note not found error literal
This commit is contained in:
muerwre 2022-08-12 14:07:19 +07:00 committed by GitHub
parent fe3db608d6
commit 5d34090238
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
72 changed files with 1241 additions and 664 deletions

View file

@ -1,6 +1,6 @@
NEXT_PUBLIC_API_HOST=https://pig.staging.vault48.org/
NEXT_PUBLIC_REMOTE_CURRENT=https://pig.staging.vault48.org/static/
#NEXT_PUBLIC_API_HOST=http://localhost:8888/
#NEXT_PUBLIC_REMOTE_CURRENT=http://localhost:8888/static/
#NEXT_PUBLIC_API_HOST=https://pig.vault48.org/
#NEXT_PUBLIC_REMOTE_CURRENT=https://pig.vault48.org/static/
# NEXT_PUBLIC_API_HOST=http://localhost:8888/
# NEXT_PUBLIC_REMOTE_CURRENT=http://localhost:8888/static/
# NEXT_PUBLIC_API_HOST=https://pig.vault48.org/
# NEXT_PUBLIC_REMOTE_CURRENT=https://pig.vault48.org/static/

4
.gitignore vendored
View file

@ -6,4 +6,6 @@
/.next
/.vscode
/.history
.DS_Store
.DS_Store
/tsconfig.tsbuildinfo
.env.local

View file

@ -94,7 +94,7 @@
"husky": "^7.0.4",
"lint-staged": "^12.1.6",
"next-transpile-modules": "^9.0.0",
"prettier": "^1.18.2"
"prettier": "^2.7.1"
},
"lint-staged": {
"./**/*.{js,jsx,ts,tsx}": [

View file

@ -1,8 +1,31 @@
import { ApiGetNotesRequest, ApiGetNotesResponse } from '~/api/notes/types';
import { URLS } from '~/constants/urls';
import { api, cleanResult } from '~/utils/api';
import {
ApiGetNotesRequest as ApiListNotesRequest,
ApiGetNotesResponse,
ApiCreateNoteRequest,
ApiUpdateNoteResponse,
ApiUpdateNoteRequest,
} from "~/api/notes/types";
import { URLS } from "~/constants/urls";
import { api, cleanResult } from "~/utils/api";
export const apiGetNotes = ({ limit, offset, search }: ApiGetNotesRequest) =>
export const apiListNotes = ({ limit, offset, search }: ApiListNotesRequest) =>
api
.get<ApiGetNotesResponse>(URLS.NOTES, { params: { limit, offset, search } })
.then(cleanResult);
export const apiCreateNote = ({ text }: ApiCreateNoteRequest) =>
api
.post<ApiUpdateNoteResponse>(URLS.NOTES, {
text,
})
.then(cleanResult);
export const apiDeleteNote = (id: number) =>
api.delete(URLS.NOTE(id)).then(cleanResult);
export const apiUpdateNote = ({ id, text }: ApiUpdateNoteRequest) =>
api
.put<ApiUpdateNoteResponse>(URLS.NOTE(id), {
content: text,
})
.then(cleanResult);

View file

@ -1,4 +1,4 @@
import { Note } from '~/types/notes';
import { Note } from "~/types/notes";
export interface ApiGetNotesRequest {
limit: number;
@ -10,3 +10,14 @@ export interface ApiGetNotesResponse {
list: Note[];
totalCount: number;
}
export interface ApiCreateNoteRequest {
text: string;
}
export interface ApiUpdateNoteResponse extends Note {}
export interface ApiUpdateNoteRequest {
id: number;
text: string;
}

View file

@ -1,10 +1,10 @@
import { FC, memo, useCallback, useEffect, useRef, useState } from "react";
import { FC, memo, useCallback, useEffect, useRef, useState } from 'react';
import { debounce, throttle } from "throttle-debounce";
import { debounce, throttle } from 'throttle-debounce';
import { useWindowSize } from "~/hooks/dom/useWindowSize";
import { useWindowSize } from '~/hooks/dom/useWindowSize';
import styles from "./styles.module.scss";
import styles from './styles.module.scss';
interface LoginSceneProps {}
@ -17,31 +17,31 @@ interface Layer {
const layers: Layer[] = [
{
src: "/images/clouds__bg.svg",
src: '/images/clouds__bg.svg',
velocity: -0.3,
width: 3840,
height: 1080,
},
{
src: "/images/clouds__cube.svg",
src: '/images/clouds__cube.svg',
velocity: -0.1,
width: 3840,
height: 1080,
},
{
src: "/images/clouds__cloud.svg",
src: '/images/clouds__cloud.svg',
velocity: 0.2,
width: 3840,
height: 1080,
},
{
src: "/images/clouds__dudes.svg",
src: '/images/clouds__dudes.svg',
velocity: 0.5,
width: 3840,
height: 1080,
},
{
src: "/images/clouds__trash.svg",
src: '/images/clouds__trash.svg',
velocity: 0.8,
width: 3840,
height: 1080,
@ -52,7 +52,7 @@ const LoginScene: FC<LoginSceneProps> = memo(() => {
const containerRef = useRef<HTMLDivElement>(null);
const [loaded, setLoaded] = useState(false);
const imageRefs = useRef<Array<SVGImageElement | null>>([]);
const { isMobile } = useWindowSize();
const { isTablet } = useWindowSize();
const domRect = useRef<DOMRect>();
const onMouseMove = useCallback(
@ -84,11 +84,11 @@ const LoginScene: FC<LoginSceneProps> = memo(() => {
useEffect(() => {
const listener = throttle(100, onMouseMove);
document.addEventListener("mousemove", listener);
return () => document.removeEventListener("mousemove", listener);
document.addEventListener('mousemove', listener);
return () => document.removeEventListener('mousemove', listener);
}, []);
if (isMobile) {
if (isTablet) {
return null;
}
@ -103,16 +103,16 @@ const LoginScene: FC<LoginSceneProps> = memo(() => {
>
<defs>
<linearGradient id="fallbackGradient" x1={0} x2={0} y1={1} y2={0}>
<stop style={{ stopColor: "#ffccaa", stopOpacity: 1 }} offset="0" />
<stop style={{ stopColor: '#ffccaa', stopOpacity: 1 }} offset="0" />
<stop
style={{ stopColor: "#fff6d5", stopOpacity: 1 }}
style={{ stopColor: '#fff6d5', stopOpacity: 1 }}
offset="0.34655526"
/>
<stop
style={{ stopColor: "#afc6e9", stopOpacity: 1 }}
style={{ stopColor: '#afc6e9', stopOpacity: 1 }}
offset="0.765342"
/>
<stop style={{ stopColor: "#879fde", stopOpacity: 1 }} offset="1" />
<stop style={{ stopColor: '#879fde', stopOpacity: 1 }} offset="1" />
</linearGradient>
</defs>

View file

@ -1,15 +1,17 @@
import React, { FC } from 'react';
import { observer } from 'mobx-react-lite';
import { useAuth } from '~/hooks/auth/useAuth';
interface IProps {}
const Superpower: FC<IProps> = ({ children }) => {
const Superpower: FC<IProps> = observer(({ children }) => {
const { isTester } = useAuth();
if (!isTester) return null;
return <>{children}</>;
};
});
export { Superpower };

View file

@ -1,13 +1,21 @@
import React, { DetailedHTMLProps, FC, HTMLAttributes } from 'react';
import React, { DetailedHTMLProps, VFC, HTMLAttributes } from 'react';
import classNames from 'classnames';
import styles from '~/styles/common/markdown.module.scss';
import { formatText } from '~/utils/dom';
interface IProps extends DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement> {}
interface IProps
extends DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement> {
children?: string;
}
const Markdown: FC<IProps> = ({ className, ...props }) => (
<div className={classNames(styles.wrapper, className)} {...props} />
const Markdown: VFC<IProps> = ({ className, children = '', ...props }) => (
<div
className={classNames(styles.wrapper, className)}
{...props}
dangerouslySetInnerHTML={{ __html: formatText(children) }}
/>
);
export { Markdown };

View file

@ -1,22 +1,26 @@
import React, { FC } from "react";
import React, { FC } from 'react';
import classNames from "classnames";
import classNames from 'classnames';
import styles from "./styles.module.scss";
import styles from './styles.module.scss';
interface ZoneProps {
title?: string;
className?: string;
color?: "danger" | "normal";
color?: 'danger' | 'normal';
}
const Zone: FC<ZoneProps> = ({
title,
className,
children,
color = "normal",
color = 'normal',
}) => (
<div className={classNames(className, styles.pad, styles[color])}>
<div
className={classNames(className, styles.pad, styles[color], {
[styles.with_title]: !!title,
})}
>
{!!title && (
<div className={styles.title}>
<span>{title}</span>

View file

@ -8,7 +8,7 @@ $pad_usual: mix(white, $content_bg, 10%);
span {
position: absolute;
top: -5px;
top: -$gap;
left: $radius;
transform: translate(0, -100%);
background: $pad_usual;
@ -25,7 +25,7 @@ $pad_usual: mix(white, $content_bg, 10%);
}
.pad {
padding: $gap * 1.5 $gap $gap;
padding: $gap;
box-shadow: inset $pad_usual 0 0 0 2px;
border-radius: $radius;
position: relative;
@ -33,4 +33,8 @@ $pad_usual: mix(white, $content_bg, 10%);
&.danger {
box-shadow: inset $pad_danger 0 0 0 2px;
}
&.with_title {
padding-top: $gap * 2;
}
}

View file

@ -11,7 +11,7 @@ import { useNodeFormContext } from '~/hooks/node/useNodeFormFormik';
const EditorButtons: FC = () => {
const { values, handleChange, isSubmitting } = useNodeFormContext();
const { isMobile } = useWindowSize();
const { isTablet } = useWindowSize();
return (
<Padder style={{ position: 'relative' }}>
@ -23,14 +23,14 @@ const EditorButtons: FC = () => {
title="Название"
value={values.title}
handler={handleChange('title')}
autoFocus={!isMobile}
autoFocus={!isTablet}
maxLength={256}
disabled={isSubmitting}
/>
</Filler>
<Button
title={isMobile ? undefined : 'Сохранить'}
title={isTablet ? undefined : 'Сохранить'}
iconRight="check"
color={values.is_promoted ? 'primary' : 'lab'}
disabled={isSubmitting}

View file

@ -12,20 +12,20 @@ interface IProps {
}
const ImageGrid: FC<IProps> = ({ files, setFiles, locked }) => {
const { isMobile } = useWindowSize();
const { isTablet } = useWindowSize();
const onMove = useCallback(
(newFiles: IFile[]) => {
setFiles(newFiles.filter(it => it));
},
[setFiles, files]
[setFiles, files],
);
const onDrop = useCallback(
(id: IFile['id']) => {
setFiles(files.filter(file => file && file.id !== id));
},
[setFiles, files]
[setFiles, files],
);
return (
@ -34,7 +34,7 @@ const ImageGrid: FC<IProps> = ({ files, setFiles, locked }) => {
onSortEnd={onMove}
items={files}
locked={locked}
size={!isMobile ? 220 : (innerWidth - 60) / 2}
size={!isTablet ? 220 : (innerWidth - 60) / 2}
/>
);
};

View file

@ -39,10 +39,12 @@ const FlowCell: FC<Props> = ({
canEdit = false,
onChangeCellView,
}) => {
const { isMobile } = useWindowSize();
const { isTablet } = useWindowSize();
const withText =
((!!flow.display && flow.display !== 'single') || !image) && flow.show_description && !!text;
((!!flow.display && flow.display !== 'single') || !image) &&
flow.show_description &&
!!text;
const {
hasDescription,
setViewHorizontal,
@ -51,14 +53,19 @@ const FlowCell: FC<Props> = ({
setViewSingle,
toggleViewDescription,
} = useFlowCellControls(id, text, flow, onChangeCellView);
const { isActive: isMenuActive, activate, ref, deactivate } = useClickOutsideFocus();
const {
isActive: isMenuActive,
activate,
ref,
deactivate,
} = useClickOutsideFocus();
const shadeSize = useMemo(() => {
const min = isMobile ? 10 : 15;
const max = isMobile ? 20 : 40;
const min = isTablet ? 10 : 15;
const max = isTablet ? 20 : 40;
return withText ? min : max;
}, [withText, isMobile]);
}, [withText, isTablet]);
const shadeAngle = useMemo(() => {
if (flow.display === 'vertical') {
@ -73,7 +80,10 @@ const FlowCell: FC<Props> = ({
}, [flow.display]);
return (
<div className={classNames(styles.cell, styles[flow.display || 'single'])} ref={ref as any}>
<div
className={classNames(styles.cell, styles[flow.display || 'single'])}
ref={ref as any}
>
{canEdit && !isMenuActive && (
<div className={styles.menu}>
<MenuDots onClick={activate} />
@ -98,7 +108,10 @@ const FlowCell: FC<Props> = ({
<Anchor className={styles.link} href={to}>
{withText && (
<FlowCellText className={styles.text} heading={<h4 className={styles.title}>{title}</h4>}>
<FlowCellText
className={styles.text}
heading={<h4 className={styles.title}>{title}</h4>}
>
{text!}
</FlowCellText>
)}
@ -113,7 +126,12 @@ const FlowCell: FC<Props> = ({
)}
{!!title && (
<CellShade color={color} className={styles.shade} size={shadeSize} angle={shadeAngle} />
<CellShade
color={color}
className={styles.shade}
size={shadeSize}
angle={shadeAngle}
/>
)}
{!withText && (

View file

@ -8,7 +8,6 @@ import { DivProps } from '~/utils/types';
import styles from './styles.module.scss';
interface Props extends DivProps {
children: string;
heading: string | ReactElement;
@ -17,10 +16,7 @@ interface Props extends DivProps {
const FlowCellText: FC<Props> = ({ children, heading, ...rest }) => (
<div {...rest} className={classNames(styles.text, rest.className)}>
{heading && <div className={styles.heading}>{heading}</div>}
<Markdown
className={styles.description}
dangerouslySetInnerHTML={{ __html: formatText(children) }}
/>
<Markdown className={styles.description}>{formatText(children)}</Markdown>
</div>
);

View file

@ -34,14 +34,17 @@ const lazy = {
};
export const FlowSwiperHero: FC<Props> = ({ heroes }) => {
const { isMobile } = useWindowSize();
const { isTablet } = useWindowSize();
const { push } = useNavigation();
const [controlledSwiper, setControlledSwiper] = useState<SwiperClass | undefined>(undefined);
const [controlledSwiper, setControlledSwiper] = useState<
SwiperClass | undefined
>(undefined);
const [currentIndex, setCurrentIndex] = useState(heroes.length);
const preset = useMemo(() => (isMobile ? ImagePresets.cover : ImagePresets.small_hero), [
isMobile,
]);
const preset = useMemo(
() => (isTablet ? ImagePresets.cover : ImagePresets.small_hero),
[isTablet],
);
const onNext = useCallback(() => {
controlledSwiper?.slideNext(1);
@ -79,7 +82,7 @@ export const FlowSwiperHero: FC<Props> = ({ heroes }) => {
(sw: SwiperClass) => {
push(URLS.NODE_URL(heroes[sw.realIndex]?.id));
},
[push, heroes]
[push, heroes],
);
if (!heroes.length) {

View file

@ -20,11 +20,9 @@ const LabDescription: FC<INodeComponentProps> = ({ node, isLoading }) => {
<Paragraph />
</div>
) : (
<Markdown
className={styles.wrap}
dangerouslySetInnerHTML={{ __html: formatText(node.description) }}
onClick={onClick}
/>
<Markdown className={styles.wrap} onClick={onClick}>
{formatText(node.description)}
</Markdown>
);
};

View file

@ -10,9 +10,10 @@ import { path } from '~/utils/ramda';
import styles from './styles.module.scss';
const LabText: FC<INodeComponentProps> = ({ node, isLoading }) => {
const content = useMemo(() => formatTextParagraphs(path(['blocks', 0, 'text'], node) || ''), [
node,
]);
const content = useMemo(
() => formatTextParagraphs(path(['blocks', 0, 'text'], node) || ''),
[node],
);
const onClick = useGotoNode(node.id);
@ -21,11 +22,9 @@ const LabText: FC<INodeComponentProps> = ({ node, isLoading }) => {
<Paragraph lines={5} />
</div>
) : (
<Markdown
dangerouslySetInnerHTML={{ __html: content }}
className={styles.wrap}
onClick={onClick}
/>
<Markdown className={styles.wrap} onClick={onClick}>
{content}
</Markdown>
);
};

View file

@ -1,52 +1,35 @@
import React, { FC, useCallback } from 'react';
import { FC } from 'react';
import { Group } from '~/components/containers/Group';
import { Icon } from '~/components/input/Icon';
import { MenuButton, MenuItemWithIcon } from '~/components/menu';
import { ImagePresets } from '~/constants/urls';
import { IUser } from '~/types/auth';
import { IFile } from '~/types';
import { getURL } from '~/utils/dom';
import styles from './styles.module.scss';
interface IProps {
user: Partial<IUser>;
onLogout: () => void;
authOpenProfile: () => void;
username: string;
photo?: IFile;
onClick?: () => void;
}
const UserButton: FC<IProps> = ({ user: { username, photo }, authOpenProfile, onLogout }) => {
const onProfileOpen = useCallback(() => {
authOpenProfile();
}, [authOpenProfile]);
const onSettingsOpen = useCallback(() => {
authOpenProfile();
}, [authOpenProfile]);
const UserButton: FC<IProps> = ({ username, photo, onClick }) => {
return (
<div className={styles.wrap}>
<button className={styles.wrap} onClick={onClick}>
<Group horizontal className={styles.user_button}>
<div className={styles.username}>{username}</div>
<MenuButton
position="bottom"
translucent={false}
icon={
<div
className={styles.user_avatar}
style={{ backgroundImage: `url('${getURL(photo, ImagePresets.avatar)}')` }}
>
{(!photo || !photo.id) && <Icon icon="profile" />}
</div>
}
<div
className={styles.user_avatar}
style={{
backgroundImage: `url('${getURL(photo, ImagePresets.avatar)}')`,
}}
>
<MenuItemWithIcon onClick={onProfileOpen}>Профиль</MenuItemWithIcon>
<MenuItemWithIcon onClick={onSettingsOpen}>Настройки</MenuItemWithIcon>
<MenuItemWithIcon onClick={onLogout}>Выдох</MenuItemWithIcon>
</MenuButton>
{(!photo || !photo.id) && <Icon icon="profile" />}
</div>
</Group>
</div>
</button>
);
};

View file

@ -3,7 +3,6 @@ import React, { FC, useCallback } from 'react';
import { Avatar } from '~/components/common/Avatar';
import { useUserDescription } from '~/hooks/auth/useUserDescription';
import { INodeUser } from '~/types';
import { openUserProfile } from '~/utils/user';
import styles from './styles.module.scss';
@ -12,8 +11,6 @@ interface Props {
}
const NodeAuthorBlock: FC<Props> = ({ user }) => {
const onOpenProfile = useCallback(() => openUserProfile(user?.username), [user]);
const description = useUserDescription(user);
if (!user) {
@ -23,7 +20,7 @@ const NodeAuthorBlock: FC<Props> = ({ user }) => {
const { fullname, username, photo } = user;
return (
<div className={styles.block} onClick={onOpenProfile}>
<div className={styles.block}>
<Avatar username={username} url={photo?.url} className={styles.avatar} />
<div className={styles.info}>

View file

@ -30,16 +30,19 @@ const NodeEditMenu: VFC<NodeEditMenuProps> = ({
onLock,
onEdit,
}) => {
const { isMobile } = useWindowSize();
const { isTablet } = useWindowSize();
if (isMobile) {
if (isTablet) {
return (
<MenuButton
icon={<Icon icon="dots-vertical" className={styles.icon} size={24} />}
className={className}
>
{canStar && (
<MenuItemWithIcon icon={isHeroic ? 'star_full' : 'star'} onClick={onStar}>
<MenuItemWithIcon
icon={isHeroic ? 'star_full' : 'star'}
onClick={onStar}
>
{isHeroic ? 'Убрать с главной' : 'На главную'}
</MenuItemWithIcon>
)}
@ -48,7 +51,10 @@ const NodeEditMenu: VFC<NodeEditMenuProps> = ({
Редактировать
</MenuItemWithIcon>
<MenuItemWithIcon icon={isLocked ? 'locked' : 'unlocked'} onClick={onLock}>
<MenuItemWithIcon
icon={isLocked ? 'locked' : 'unlocked'}
onClick={onLock}
>
{isLocked ? 'Восстановить' : 'Удалить'}
</MenuItemWithIcon>
</MenuButton>

View file

@ -1,4 +1,4 @@
import React, { VFC } from 'react';
import React, { useCallback, useState, VFC } from 'react';
import { Card } from '~/components/containers/Card';
import { Markdown } from '~/components/containers/Markdown';
@ -6,22 +6,56 @@ import { Padder } from '~/components/containers/Padder';
import { NoteMenu } from '~/components/notes/NoteMenu';
import { formatText, getPrettyDate } from '~/utils/dom';
import { NoteCreationForm } from '../NoteCreationForm';
import styles from './styles.module.scss';
interface NoteCardProps {
content: string;
remove: () => Promise<void>;
update: (text: string, callback?: () => void) => Promise<void>;
createdAt: string;
}
const NoteCard: VFC<NoteCardProps> = ({ content, createdAt }) => (
<Card className={styles.note}>
<Padder>
<NoteMenu onEdit={console.log} onDelete={console.log} />
<Markdown className={styles.wrap} dangerouslySetInnerHTML={{ __html: formatText(content) }} />
</Padder>
const NoteCard: VFC<NoteCardProps> = ({
content,
createdAt,
remove,
update,
}) => {
const [editing, setEditing] = useState(false);
<Padder className={styles.footer}>{getPrettyDate(createdAt)}</Padder>
</Card>
);
const toggleEditing = useCallback(() => setEditing(v => !v), []);
const onUpdate = useCallback(
(text: string, callback?: () => void) =>
update(text, () => {
setEditing(false);
callback?.();
}),
[],
);
return (
<Card className={styles.note}>
{editing ? (
<NoteCreationForm
text={content}
onSubmit={onUpdate}
onCancel={toggleEditing}
/>
) : (
<>
<Padder>
<NoteMenu onEdit={toggleEditing} onDelete={remove} />
<Markdown className={styles.wrap}>{formatText(content)}</Markdown>
</Padder>
<Padder className={styles.footer}>{getPrettyDate(createdAt)}</Padder>
</>
)}
</Card>
);
};
export { NoteCard };

View file

@ -6,10 +6,6 @@
word-break: break-word;
padding: 0;
position: relative;
& > * {
@include row_shadow;
}
}
.footer {

View file

@ -0,0 +1,99 @@
import { FC, useCallback } from 'react';
import { FormikConfig, useFormik } from 'formik';
import { Asserts, object, string } from 'yup';
import { Card } from '~/components/containers/Card';
import { Filler } from '~/components/containers/Filler';
import { Group } from '~/components/containers/Group';
import { Button } from '~/components/input/Button';
import { Textarea } from '~/components/input/Textarea';
import { useRandomPhrase } from '~/constants/phrases';
import { getErrorMessage } from '~/utils/errors/getErrorMessage';
import { showErrorToast } from '~/utils/errors/showToast';
import styles from './styles.module.scss';
interface NoteCreationFormProps {
text?: string;
onSubmit: (text: string, callback: () => void) => void;
onCancel: () => void;
}
const validationSchema = object({
text: string().required('Напишите что-нибудь'),
});
type Values = Asserts<typeof validationSchema>;
const NoteCreationForm: FC<NoteCreationFormProps> = ({
text = '',
onSubmit,
onCancel,
}) => {
const placeholder = useRandomPhrase('SIMPLE');
const submit = useCallback<FormikConfig<Values>['onSubmit']>(
async (values, { resetForm, setSubmitting, setErrors }) => {
try {
await onSubmit(values.text, () => resetForm());
} catch (error) {
const message = getErrorMessage(error);
if (message) {
setErrors({ text: message });
return;
}
showErrorToast(error);
} finally {
setSubmitting(false);
}
},
[onSubmit],
);
const {
values,
errors,
handleChange,
handleSubmit,
touched,
handleBlur,
isSubmitting,
} = useFormik<Values>({
initialValues: { text },
validationSchema,
onSubmit: submit,
});
return (
<form onSubmit={handleSubmit}>
<Card className={styles.card}>
<div className={styles.row}>
<Textarea
handler={handleChange('text')}
value={values.text}
error={touched.text ? errors.text : undefined}
onBlur={handleBlur('text')}
placeholder={placeholder}
autoFocus
/>
</div>
<Group horizontal className={styles.row}>
<Filler />
<Button size="mini" type="button" color="link" onClick={onCancel}>
Отмена
</Button>
<Button size="mini" type="submit" color="gray" loading={isSubmitting}>
ОК
</Button>
</Group>
</Card>
</form>
);
};
export { NoteCreationForm };

View file

@ -0,0 +1,11 @@
@import "src/styles/variables";
.card {
padding: 0;
}
.row {
@include row_shadow;
padding: $gap / 2;
}

View file

@ -1,14 +1,14 @@
import { FC } from "react";
import { FC } from 'react';
import { Filler } from "~/components/containers/Filler";
import { Group } from "~/components/containers/Group";
import { Padder } from "~/components/containers/Padder";
import { Button } from "~/components/input/Button";
import { UserSettingsView } from "~/containers/settings/UserSettingsView";
import { Filler } from '~/components/containers/Filler';
import { Group } from '~/components/containers/Group';
import { Padder } from '~/components/containers/Padder';
import { Button } from '~/components/input/Button';
import { UserSettingsView } from '~/containers/settings/UserSettingsView';
import {
SettingsProvider,
useSettings,
} from "~/utils/providers/SettingsProvider";
} from '~/utils/providers/SettingsProvider';
const Form = ({ children }) => {
const { handleSubmit } = useSettings();

View file

@ -1,21 +1,22 @@
import React, { VFC } from 'react';
import { VFC } from 'react';
import { useStackContext } from '~/components/sidebar/SidebarStack';
import { SidebarStackCard } from '~/components/sidebar/SidebarStackCard';
import { SettingsNotes } from '~/containers/settings/SettingsNotes';
import styles from './styles.module.scss';
interface ProfileSidebarNotesProps {}
const ProfileSidebarNotes: VFC<ProfileSidebarNotesProps> = () => {
const { closeAllTabs } = useStackContext();
return (
<SidebarStackCard width={800} headerFeature="back" title="Заметки" onBackPress={closeAllTabs}>
<div className={styles.scroller}>
<SettingsNotes />
</div>
<SidebarStackCard
width={480}
headerFeature="back"
title="Заметки"
onBackPress={closeAllTabs}
>
<SettingsNotes />
</SidebarStackCard>
);
};

View file

@ -1,17 +1,17 @@
import React, { FC } from "react";
import React, { FC } from 'react';
import { Filler } from "~/components/containers/Filler";
import { Button } from "~/components/input/Button";
import { ProfileSettings } from "~/components/profile/ProfileSettings";
import { useStackContext } from "~/components/sidebar/SidebarStack";
import { SidebarStackCard } from "~/components/sidebar/SidebarStackCard";
import { UserSettingsView } from "~/containers/settings/UserSettingsView";
import { Filler } from '~/components/containers/Filler';
import { Button } from '~/components/input/Button';
import { ProfileSettings } from '~/components/profile/ProfileSettings';
import { useStackContext } from '~/components/sidebar/SidebarStack';
import { SidebarStackCard } from '~/components/sidebar/SidebarStackCard';
import { UserSettingsView } from '~/containers/settings/UserSettingsView';
import {
SettingsProvider,
useSettings,
} from "~/utils/providers/SettingsProvider";
} from '~/utils/providers/SettingsProvider';
import styles from "./styles.module.scss";
import styles from './styles.module.scss';
interface IProps {}

View file

@ -1,11 +1,21 @@
import React, { createContext, FC, PropsWithChildren, useCallback, useContext, useMemo, useState } from 'react';
import React, {
createContext,
FC,
PropsWithChildren,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import { isNil } from '~/utils/ramda';
import styles from './styles.module.scss';
interface SidebarStackProps extends PropsWithChildren<{}> {
initialTab?: number;
tab?: number;
onTabChange?: (index?: number) => void;
}
interface SidebarStackContextValue {
@ -38,12 +48,32 @@ const SidebarCards: FC = ({ children }) => {
return <div className={styles.card}>{nonEmptyChildren[activeTab]}</div>;
};
const SidebarStack = function({ children, initialTab }: SidebarStackProps) {
const [activeTab, setActiveTab] = useState<number | undefined>(initialTab);
const closeAllTabs = useCallback(() => setActiveTab(undefined), []);
const SidebarStack = function({
children,
tab,
onTabChange,
}: SidebarStackProps) {
const [activeTab, setActiveTab] = useState<number | undefined>(tab);
const closeAllTabs = useCallback(() => {
setActiveTab(undefined);
onTabChange?.(undefined);
}, []);
const onChangeTab = useCallback(
(index: number) => {
onTabChange?.(index);
setActiveTab(index);
},
[onTabChange],
);
useEffect(() => setActiveTab(tab), [tab]);
return (
<SidebarStackContext.Provider value={{ activeTab, setActiveTab, closeAllTabs }}>
<SidebarStackContext.Provider
value={{ activeTab, setActiveTab: onChangeTab, closeAllTabs }}
>
<div className={styles.stack}>{children}</div>
</SidebarStackContext.Provider>
);

View file

@ -43,6 +43,7 @@ export const ERRORS = {
MESSAGE_NOT_FOUND: 'MessageNotFound',
COMMENT_TOO_LONG: 'CommentTooLong',
NETWORK_ERROR: 'Network Error',
NOTE_NOT_FOUND: 'NoteNotFound',
};
export const ERROR_LITERAL = {
@ -74,9 +75,12 @@ export const ERROR_LITERAL = {
[ERRORS.INCORRECT_NODE_TYPE]: 'Ты пытаешься отправить пост неизвестного типа',
[ERRORS.UNEXPECTED_BEHAVIOR]: 'Что-то пошло не так. Напишите об этом Борису',
[ERRORS.FILES_IS_TOO_BIG]: 'Файл слишком большой',
[ERRORS.OAUTH_CODE_IS_EMPTY]: 'Мы не смогли получить код от социальной сети. Попробуй ещё раз.',
[ERRORS.OAUTH_UNKNOWN_PROVIDER]: 'Ты пытаешься войти с помощью неизвестной социальной сети',
[ERRORS.OAUTH_INVALID_DATA]: 'Социальная сеть вернула какую-то дичь. Попробуй ещё раз.',
[ERRORS.OAUTH_CODE_IS_EMPTY]:
'Мы не смогли получить код от социальной сети. Попробуй ещё раз.',
[ERRORS.OAUTH_UNKNOWN_PROVIDER]:
'Ты пытаешься войти с помощью неизвестной социальной сети',
[ERRORS.OAUTH_INVALID_DATA]:
'Социальная сеть вернула какую-то дичь. Попробуй ещё раз.',
[ERRORS.USERNAME_IS_SHORT]: 'Хотя бы 2 символа',
[ERRORS.USERNAME_CONTAINS_INVALID_CHARS]: 'Буквы, цифры и подчёркивание',
[ERRORS.PASSWORD_IS_SHORT]: 'Хотя бы 6 символов',
@ -91,4 +95,5 @@ export const ERROR_LITERAL = {
[ERRORS.MESSAGE_NOT_FOUND]: 'Сообщение не найдено',
[ERRORS.COMMENT_TOO_LONG]: 'Комментарий слишком длинный',
[ERRORS.NETWORK_ERROR]: 'Подключение не удалось',
[ERRORS.NOTE_NOT_FOUND]: 'Заметка не найдена',
};

View file

@ -1,5 +1,4 @@
export enum EventMessageType {
OpenProfile = 'open_profile',
OAuthLogin = 'oauth_login',
OAuthProcessed = 'oauth_processed',
OAuthError = 'oauth_error',

View file

@ -4,18 +4,15 @@ import { LoadingDialog } from '~/containers/dialogs/LoadingDialog';
import { LoginDialog } from '~/containers/dialogs/LoginDialog';
import { LoginSocialRegisterDialog } from '~/containers/dialogs/LoginSocialRegisterDialog';
import { PhotoSwipe } from '~/containers/dialogs/PhotoSwipe';
import { ProfileDialog } from '~/containers/dialogs/ProfileDialog';
import { RestorePasswordDialog } from '~/containers/dialogs/RestorePasswordDialog';
import { RestoreRequestDialog } from '~/containers/dialogs/RestoreRequestDialog';
import { TestDialog } from '~/containers/dialogs/TestDialog';
import { ProfileSidebar } from '~/containers/sidebars/ProfileSidebar';
import { TagSidebar } from '~/containers/sidebars/TagSidebar';
export enum Dialog {
Login = 'Login',
LoginSocialRegister = 'LoginSocialRegister',
Loading = 'Loading',
Profile = 'Profile',
RestoreRequest = 'RestoreRequest',
RestorePassword = 'RestorePassword',
Test = 'Test',
@ -23,7 +20,6 @@ export enum Dialog {
CreateNode = 'CreateNode',
EditNode = 'EditNode',
TagSidebar = 'TagNodes',
ProfileSidebar = 'ProfileSidebar',
}
export const DIALOG_CONTENT = {
@ -31,12 +27,10 @@ export const DIALOG_CONTENT = {
[Dialog.LoginSocialRegister]: LoginSocialRegisterDialog,
[Dialog.Loading]: LoadingDialog,
[Dialog.Test]: TestDialog,
[Dialog.Profile]: ProfileDialog,
[Dialog.RestoreRequest]: RestoreRequestDialog,
[Dialog.RestorePassword]: RestorePasswordDialog,
[Dialog.Photoswipe]: PhotoSwipe,
[Dialog.CreateNode]: EditorCreateDialog,
[Dialog.EditNode]: EditorEditDialog,
[Dialog.TagSidebar]: TagSidebar,
[Dialog.ProfileSidebar]: ProfileSidebar,
} as const;

View file

@ -0,0 +1,9 @@
import { ProfileSidebar } from "~/containers/sidebars/ProfileSidebar";
import { SidebarName } from "./index";
export const sidebarComponents = {
[SidebarName.Settings]: ProfileSidebar,
};
export type SidebarComponents = typeof sidebarComponents;

View file

@ -1,11 +1,5 @@
import { FC, ReactNode } from "react";
import { ProfileSidebar } from "~/containers/sidebars/ProfileSidebar";
export enum SidebarName {
Settings = 'settings'
Settings = "settings",
}
export const sidebarComponents = {
[SidebarName.Settings]: ProfileSidebar
}

View file

@ -1,48 +1,49 @@
import { FlowDisplayVariant, INode } from '~/types';
import { FlowDisplayVariant, INode } from "~/types";
export const URLS = {
BASE: '/',
LAB: '/lab',
BORIS: '/boris',
BASE: "/",
LAB: "/lab",
BORIS: "/boris",
AUTH: {
LOGIN: '/auth/login',
LOGIN: "/auth/login",
},
EXAMPLES: {
EDITOR: '/examples/edit',
IMAGE: '/examples/image',
EDITOR: "/examples/edit",
IMAGE: "/examples/image",
},
ERRORS: {
NOT_FOUND: '/lost',
BACKEND_DOWN: '/oopsie',
NOT_FOUND: "/lost",
BACKEND_DOWN: "/oopsie",
},
NODE_URL: (id: INode['id'] | string) => `/post${id}`,
NODE_URL: (id: INode["id"] | string) => `/post${id}`,
PROFILE_PAGE: (username: string) => `/profile/${username}`,
SETTINGS: {
BASE: '/settings',
NOTES: '/settings/notes',
TRASH: '/settings/trash',
BASE: "/settings",
NOTES: "/settings/notes",
TRASH: "/settings/trash",
},
NOTES: '/notes/',
NOTES: "/notes/",
NOTE: (id: number) => `/notes/${id}`,
};
export const ImagePresets = {
'1600': '1600',
'600': '600',
'300': '300',
cover: 'cover',
small_hero: 'small_hero',
avatar: 'avatar',
flow_square: 'flow_square',
flow_vertical: 'flow_vertical',
flow_horizontal: 'flow_horizontal',
"1600": "1600",
"600": "600",
"300": "300",
cover: "cover",
small_hero: "small_hero",
avatar: "avatar",
flow_square: "flow_square",
flow_vertical: "flow_vertical",
flow_horizontal: "flow_horizontal",
} as const;
export const flowDisplayToPreset: Record<
FlowDisplayVariant,
typeof ImagePresets[keyof typeof ImagePresets]
> = {
single: 'flow_square',
quadro: 'flow_square',
vertical: 'flow_vertical',
horizontal: 'flow_horizontal',
single: "flow_square",
quadro: "flow_square",
vertical: "flow_vertical",
horizontal: "flow_horizontal",
};

View file

@ -0,0 +1,22 @@
import { FC } from 'react';
import { observer } from 'mobx-react-lite';
import { BorisSuperpowers } from '~/components/boris/BorisSuperpowers';
import { useAuth } from '~/hooks/auth/useAuth';
import { useSuperPowers } from '~/hooks/auth/useSuperPowers';
interface SuperPowersToggleProps {}
const SuperPowersToggle: FC<SuperPowersToggleProps> = observer(() => {
const { isUser } = useAuth();
const { isTester, setIsTester } = useSuperPowers();
if (!isUser) {
return null;
}
return <BorisSuperpowers active={isTester} onChange={setIsTester} />;
});
export { SuperPowersToggle };

View file

@ -1,24 +1,22 @@
import React, { FC } from 'react';
import { FC } from 'react';
import { BorisContacts } from '~/components/boris/BorisContacts';
import { BorisStats } from '~/components/boris/BorisStats';
import { BorisSuperpowers } from '~/components/boris/BorisSuperpowers';
import { Group } from '~/components/containers/Group';
import { SuperPowersToggle } from '~/containers/auth/SuperPowersToggle';
import styles from '~/layouts/BorisLayout/styles.module.scss';
import { BorisUsageStats } from '~/types/boris';
interface Props {
isUser: boolean;
isTester: boolean;
stats: BorisUsageStats;
setBetaTester: (val: boolean) => void;
isLoading: boolean;
}
const BorisSidebar: FC<Props> = ({ isUser, stats, isLoading, isTester, setBetaTester }) => (
const BorisSidebar: FC<Props> = ({ isUser, stats, isLoading }) => (
<Group className={styles.stats__container}>
<div className={styles.super_powers}>
{isUser && <BorisSuperpowers active={isTester} onChange={setBetaTester} />}
<SuperPowersToggle />
</div>
<BorisContacts />

View file

@ -1,39 +1,18 @@
import { FC, useCallback } from 'react';
import { useRouter } from 'next/router';
import { FC } from 'react';
import { Group } from '~/components/containers/Group';
import { Button } from '~/components/input/Button';
import { SidebarName } from '~/constants/sidebar';
import { URLS } from '~/constants/urls';
import { useSidebar } from '~/utils/providers/SidebarProvider';
import styles from './styles.module.scss';
import { Markdown } from '~/components/containers/Markdown';
export interface BorisSuperpowersProps {}
const BorisSuperpowers: FC<BorisSuperpowersProps> = () => {
const { open } = useSidebar();
const openProfileSidebar = useCallback(() => {
open(SidebarName.Settings);
}, [open]);
const { push } = useRouter();
return (
<Group>
<h2>Штучи, находящиеся в разработке</h2>
<h2>Штучки, находящиеся в разработке</h2>
<div className={styles.grid}>
<Button size="mini" onClick={() => openProfileSidebar()}>
Открыть
</Button>
<div className={styles.label}>Профиль в сайдбаре</div>
<Button size="mini" onClick={() => push(URLS.SETTINGS.BASE)}>
Открыть
</Button>
<div className={styles.label}>Профиль на отдельной странице</div>
</div>
<Markdown>
{`> На данный момент в разработке нет вещей, которые можно показать.\n\n// Приходите завтра`}
</Markdown>
</Group>
);
};

View file

@ -1,22 +1,22 @@
import React, { FC, useCallback } from "react";
import React, { FC, useCallback } from 'react';
import { LoginDialogButtons } from "~/components/auth/login/LoginDialogButtons";
import { LoginScene } from "~/components/auth/login/LoginScene";
import { Group } from "~/components/containers/Group";
import { Padder } from "~/components/containers/Padder";
import { BetterScrollDialog } from "~/components/dialogs/BetterScrollDialog";
import { DialogTitle } from "~/components/dialogs/DialogTitle";
import { Button } from "~/components/input/Button";
import { InputText } from "~/components/input/InputText";
import { Dialog } from "~/constants/modal";
import { useCloseOnEscape } from "~/hooks";
import { useAuth } from "~/hooks/auth/useAuth";
import { useLoginForm } from "~/hooks/auth/useLoginForm";
import { useOAuth } from "~/hooks/auth/useOAuth";
import { useShowModal } from "~/hooks/modal/useShowModal";
import { DialogComponentProps } from "~/types/modal";
import { LoginDialogButtons } from '~/components/auth/login/LoginDialogButtons';
import { LoginScene } from '~/components/auth/login/LoginScene';
import { Group } from '~/components/containers/Group';
import { Padder } from '~/components/containers/Padder';
import { BetterScrollDialog } from '~/components/dialogs/BetterScrollDialog';
import { DialogTitle } from '~/components/dialogs/DialogTitle';
import { Button } from '~/components/input/Button';
import { InputText } from '~/components/input/InputText';
import { Dialog } from '~/constants/modal';
import { useCloseOnEscape } from '~/hooks';
import { useAuth } from '~/hooks/auth/useAuth';
import { useLoginForm } from '~/hooks/auth/useLoginForm';
import { useOAuth } from '~/hooks/auth/useOAuth';
import { useShowModal } from '~/hooks/modal/useShowModal';
import { DialogComponentProps } from '~/types/modal';
import styles from "./styles.module.scss";
import styles from './styles.module.scss';
type LoginDialogProps = DialogComponentProps & {};
@ -55,7 +55,7 @@ const LoginDialog: FC<LoginDialogProps> = ({ onRequestClose }) => {
<InputText
title="Логин"
handler={handleChange("username")}
handler={handleChange('username')}
value={values.username}
error={errors.username}
autoFocus
@ -63,7 +63,7 @@ const LoginDialog: FC<LoginDialogProps> = ({ onRequestClose }) => {
<InputText
title="Пароль"
handler={handleChange("password")}
handler={handleChange('password')}
value={values.password}
error={errors.password}
type="password"

View file

@ -22,7 +22,7 @@ export interface PhotoSwipeProps extends DialogComponentProps {
const PhotoSwipe: VFC<PhotoSwipeProps> = observer(({ index, items }) => {
let ref = useRef<HTMLDivElement>(null);
const { hideModal } = useModal();
const { isMobile } = useWindowSize();
const { isTablet } = useWindowSize();
useEffect(() => {
new Promise(async resolve => {
@ -34,7 +34,10 @@ const PhotoSwipe: VFC<PhotoSwipeProps> = observer(({ index, items }) => {
img.onload = () => {
resolveImage({
src: getURL(image, isMobile ? ImagePresets[900] : ImagePresets[1600]),
src: getURL(
image,
isTablet ? ImagePresets[900] : ImagePresets[1600],
),
h: img.naturalHeight,
w: img.naturalWidth,
});
@ -45,8 +48,8 @@ const PhotoSwipe: VFC<PhotoSwipeProps> = observer(({ index, items }) => {
};
img.src = getURL(image, ImagePresets[1600]);
})
)
}),
),
);
resolve(images);
@ -61,10 +64,16 @@ const PhotoSwipe: VFC<PhotoSwipeProps> = observer(({ index, items }) => {
ps.listen('destroy', hideModal);
ps.listen('close', hideModal);
});
}, [hideModal, items, index, isMobile]);
}, [hideModal, items, index, isTablet]);
return (
<div className="pswp" tabIndex={-1} role="dialog" aria-hidden="true" ref={ref}>
<div
className="pswp"
tabIndex={-1}
role="dialog"
aria-hidden="true"
ref={ref}
>
<div className={classNames('pswp__bg', styles.bg)} />
<div className={classNames('pswp__scroll-wrap', styles.wrap)}>
<div className="pswp__container">
@ -76,7 +85,10 @@ const PhotoSwipe: VFC<PhotoSwipeProps> = observer(({ index, items }) => {
<div className="pswp__ui pswp__ui--hidden">
<div className={classNames('pswp__top-bar', styles.bar)}>
<div className="pswp__counter" />
<button className="pswp__button pswp__button--close" title="Close (Esc)" />
<button
className="pswp__button pswp__button--close"
title="Close (Esc)"
/>
<div className="pswp__preloader">
<div className="pswp__preloader__icn">
@ -96,7 +108,10 @@ const PhotoSwipe: VFC<PhotoSwipeProps> = observer(({ index, items }) => {
title="Previous (arrow left)"
/>
<button className="pswp__button pswp__button--arrow--right" title="Next (arrow right)" />
<button
className="pswp__button pswp__button--arrow--right"
title="Next (arrow right)"
/>
<div className="pswp__caption">
<div className="pswp__caption__center" />

View file

@ -1,47 +0,0 @@
import React, { FC } from 'react';
import { CoverBackdrop } from '~/components/containers/CoverBackdrop';
import { Tabs } from '~/components/dialogs/Tabs';
import { ProfileDescription } from '~/components/profile/ProfileDescription';
import { ProfileSettings } from '~/components/profile/ProfileSettings';
import { ProfileAccounts } from '~/containers/profile/ProfileAccounts';
import { ProfileInfo } from '~/containers/profile/ProfileInfo';
import { ProfileMessages } from '~/containers/profile/ProfileMessages';
import { useUser } from '~/hooks/auth/useUser';
import { useGetProfile } from '~/hooks/profile/useGetProfile';
import { DialogComponentProps } from '~/types/modal';
import { ProfileProvider } from '~/utils/providers/ProfileProvider';
import { BetterScrollDialog } from '../../../components/dialogs/BetterScrollDialog';
export interface ProfileDialogProps extends DialogComponentProps {
username: string;
}
const ProfileDialog: FC<ProfileDialogProps> = ({ username, onRequestClose }) => {
const { isLoading, profile } = useGetProfile(username);
const {
user: { id },
} = useUser();
return (
<ProfileProvider username={username}>
<Tabs>
<BetterScrollDialog
header={<ProfileInfo isOwn={profile.id === id} isLoading={isLoading} />}
backdrop={<CoverBackdrop cover={profile.cover} />}
onClose={onRequestClose}
>
<Tabs.Content>
<ProfileDescription />
<ProfileMessages />
<ProfileSettings />
<ProfileAccounts />
</Tabs.Content>
</BetterScrollDialog>
</Tabs>
</ProfileProvider>
);
};
export { ProfileDialog };

View file

@ -1,5 +0,0 @@
@import "src/styles/variables";
.messages {
padding: $gap;
}

View file

@ -11,6 +11,7 @@ import { Button } from '~/components/input/Button';
import { Logo } from '~/components/main/Logo';
import { UserButton } from '~/components/main/UserButton';
import { Dialog } from '~/constants/modal';
import { SidebarName } from '~/constants/sidebar';
import { URLS } from '~/constants/urls';
import { useAuth } from '~/hooks/auth/useAuth';
import { useScrollTop } from '~/hooks/dom/useScrollTop';
@ -18,6 +19,7 @@ import { useFlow } from '~/hooks/flow/useFlow';
import { useGetLabStats } from '~/hooks/lab/useGetLabStats';
import { useModal } from '~/hooks/modal/useModal';
import { useUpdates } from '~/hooks/updates/useUpdates';
import { useSidebar } from '~/utils/providers/SidebarProvider';
import styles from './styles.module.scss';
@ -27,15 +29,15 @@ const Header: FC<HeaderProps> = observer(() => {
const labStats = useGetLabStats();
const [isScrolled, setIsScrolled] = useState(false);
const { logout } = useAuth();
const { showModal } = useModal();
const { isUser, user } = useAuth();
const { updates: flowUpdates } = useFlow();
const { borisCommentedAt } = useUpdates();
const { open } = useSidebar();
const openProfile = useCallback(() => {
showModal(Dialog.Profile, { username: user.username });
}, [user.username, showModal]);
const openProfileSidebar = useCallback(() => {
open(SidebarName.Settings, {});
}, [open]);
const onLogin = useCallback(() => showModal(Dialog.Login, {}), [showModal]);
@ -47,10 +49,12 @@ const Header: FC<HeaderProps> = observer(() => {
borisCommentedAt &&
(!user.last_seen_boris ||
isBefore(new Date(user.last_seen_boris), new Date(borisCommentedAt))),
[borisCommentedAt, isUser, user.last_seen_boris]
[borisCommentedAt, isUser, user.last_seen_boris],
);
const hasLabUpdates = useMemo(() => labStats.updates.length > 0, [labStats.updates]);
const hasLabUpdates = useMemo(() => labStats.updates.length > 0, [
labStats.updates,
]);
const hasFlowUpdates = useMemo(() => flowUpdates.length > 0, [flowUpdates]);
// Needed for SSR
@ -59,7 +63,9 @@ const Header: FC<HeaderProps> = observer(() => {
}, [top]);
return (
<header className={classNames(styles.wrap, { [styles.is_scrolled]: isScrolled })}>
<header
className={classNames(styles.wrap, { [styles.is_scrolled]: isScrolled })}
>
<div className={styles.container}>
<div className={styles.logo_wrapper}>
<Logo />
@ -98,10 +104,21 @@ const Header: FC<HeaderProps> = observer(() => {
</Authorized>
</nav>
{isUser && <UserButton user={user} onLogout={logout} authOpenProfile={openProfile} />}
{isUser && (
<UserButton
username={user.username}
photo={user.photo}
onClick={openProfileSidebar}
/>
)}
{!isUser && (
<Button className={styles.user_button} onClick={onLogin} round color="secondary">
<Button
className={styles.user_button}
onClick={onLogin}
round
color="secondary"
>
ВДОХ
</Button>
)}

View file

@ -26,17 +26,19 @@ const ProfilePageLeft: FC<IProps> = ({ username, profile, isLoading }) => {
/>
<div className={styles.region}>
<div className={styles.name}>{isLoading ? <Placeholder /> : profile?.fullname}</div>`
<div className={styles.name}>
{isLoading ? <Placeholder /> : profile?.fullname}
</div>
`
<div className={styles.username}>
{isLoading ? <Placeholder /> : `~${profile?.username}`}
</div>
</div>
{!!profile?.description && (
<Markdown
className={styles.description}
dangerouslySetInnerHTML={{ __html: formatText(profile.description) }}
/>
<Markdown className={styles.description}>
{formatText(profile.description)}
</Markdown>
)}
</div>
);

View file

@ -15,6 +15,7 @@ import { useAuth } from '~/hooks/auth/useAuth';
import markdown from '~/styles/common/markdown.module.scss';
import { ProfileSidebarLogoutButton } from '../ProfileSidebarLogoutButton';
import { ProfileToggles } from '../ProfileToggles';
import styles from './styles.module.scss';
@ -40,9 +41,19 @@ const ProfileSidebarMenu: VFC<ProfileSidebarMenuProps> = ({ onClose }) => {
<Filler className={classNames(markdown.wrapper, styles.text)}>
<Group>
<VerticalMenu className={styles.menu}>
<VerticalMenu.Item onClick={() => setActiveTab(0)}>Настройки</VerticalMenu.Item>
<VerticalMenu.Item onClick={() => setActiveTab(0)}>
Настройки
</VerticalMenu.Item>
<VerticalMenu.Item onClick={() => setActiveTab(1)}>
Заметки
</VerticalMenu.Item>
</VerticalMenu>
<div className={styles.toggles}>
<ProfileToggles />
</div>
<div className={styles.stats}>
<ProfileStats />
</div>
@ -51,7 +62,7 @@ const ProfileSidebarMenu: VFC<ProfileSidebarMenuProps> = ({ onClose }) => {
<Group className={styles.buttons} horizontal>
<Filler />
<ProfileSidebarLogoutButton onLogout={onLogout}/>
<ProfileSidebarLogoutButton onLogout={onLogout} />
</Group>
</div>
);

View file

@ -19,3 +19,7 @@
.stats {
display: none;
}
.toggles {
padding-top: $gap * 2;
}

View file

@ -0,0 +1,17 @@
import React, { FC } from 'react';
import { Group } from '~/components/containers/Group';
import { Zone } from '~/components/containers/Zone';
import { SuperPowersToggle } from '~/containers/auth/SuperPowersToggle';
interface ProfileTogglesProps {}
const ProfileToggles: FC<ProfileTogglesProps> = () => (
<Zone>
<Group>
<SuperPowersToggle />
</Group>
</Zone>
);
export { ProfileToggles };

View file

@ -1,56 +1,80 @@
import React, { useState, VFC } from 'react';
import { FC, useCallback, useState, VFC } from 'react';
import { Card } from '~/components/containers/Card';
import { Columns } from '~/components/containers/Columns';
import { Filler } from '~/components/containers/Filler';
import { Group } from '~/components/containers/Group';
import { Padder } from '~/components/containers/Padder';
import { Button } from '~/components/input/Button';
import { Icon } from '~/components/input/Icon';
import { InputText } from '~/components/input/InputText';
import { Textarea } from '~/components/input/Textarea';
import { HorizontalMenu } from '~/components/menu/HorizontalMenu';
import { NoteCard } from '~/components/notes/NoteCard';
import { useGetNotes } from '~/hooks/notes/useGetNotes';
import { NoteCreationForm } from '~/components/notes/NoteCreationForm';
import { useConfirmation } from '~/hooks/dom/useConfirmation';
import { NoteProvider, useNotesContext } from '~/utils/providers/NoteProvider';
import styles from './styles.module.scss';
interface SettingsNotesProps {}
const SettingsNotes: VFC<SettingsNotesProps> = () => {
const [text, setText] = useState('');
const { notes } = useGetNotes('');
const List = () => {
const { notes, remove, update } = useNotesContext();
const confirm = useConfirmation();
const onRemove = useCallback(
async (id: number) => {
confirm('Удалить? Это удалит заметку навсегда', () => remove(id));
},
[remove],
);
return (
<div>
<Padder>
<Group horizontal>
<HorizontalMenu>
<HorizontalMenu.Item active>Новые</HorizontalMenu.Item>
<HorizontalMenu.Item>Старые</HorizontalMenu.Item>
</HorizontalMenu>
<>
{notes.map(note => (
<NoteCard
remove={() => onRemove(note.id)}
update={(text, callback) => update(note.id, text, callback)}
key={note.id}
content={note.content}
createdAt={note.created_at}
/>
))}
</>
);
};
<Filler />
const Form: FC<{ onCancel: () => void }> = ({ onCancel }) => {
const { create: submit } = useNotesContext();
return <NoteCreationForm onSubmit={submit} onCancel={onCancel} />;
};
<InputText suffix={<Icon icon="search" size={24} />} />
</Group>
</Padder>
const SettingsNotes: VFC<SettingsNotesProps> = () => {
const [formIsShown, setFormIsShown] = useState(false);
<Columns>
<Card>
<Group>
<Textarea handler={setText} value={text} />
<Group horizontal>
return (
<NoteProvider>
<div className={styles.grid}>
<div className={styles.head}>
{formIsShown ? (
<Form onCancel={() => setFormIsShown(false)} />
) : (
<Group className={styles.showForm} horizontal>
<Filler />
<Button size="mini">Добавить</Button>
<Button
onClick={() => setFormIsShown(true)}
size="mini"
iconRight="plus"
color="secondary"
>
Добавить
</Button>
</Group>
)}
</div>
<div className={styles.list}>
<Group>
<Group>
<List />
</Group>
</Group>
</Card>
{notes.map(note => (
<NoteCard key={note.id} content={note.content} createdAt={note.created_at} />
))}
</Columns>
</div>
</div>
</div>
</NoteProvider>
);
};

View file

@ -0,0 +1,26 @@
@import "src/styles/variables";
.grid {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
z-index: 4;
height: 100%;
}
.head {
@include row_shadow;
width: 100%;
padding: $gap;
}
.list {
@include row_shadow;
overflow-y: auto;
flex: 1 1;
overflow: auto;
padding: 10px;
}

View file

@ -1,17 +1,18 @@
import { FC } from "react";
import { FC } from 'react';
import { Superpower } from "~/components/boris/Superpower";
import { Filler } from "~/components/containers/Filler";
import { Group } from "~/components/containers/Group";
import { Zone } from "~/components/containers/Zone";
import { InputText } from "~/components/input/InputText";
import { Textarea } from "~/components/input/Textarea";
import { ERROR_LITERAL } from "~/constants/errors";
import { ProfileAccounts } from "~/containers/profile/ProfileAccounts";
import { useSettings } from "~/utils/providers/SettingsProvider";
import { has } from "~/utils/ramda";
import { Superpower } from '~/components/boris/Superpower';
import { Filler } from '~/components/containers/Filler';
import { Group } from '~/components/containers/Group';
import { Zone } from '~/components/containers/Zone';
import { InputText } from '~/components/input/InputText';
import { Textarea } from '~/components/input/Textarea';
import { ERROR_LITERAL } from '~/constants/errors';
import { ProfileAccounts } from '~/containers/profile/ProfileAccounts';
import { useWindowSize } from '~/hooks/dom/useWindowSize';
import { useSettings } from '~/utils/providers/SettingsProvider';
import { has } from '~/utils/ramda';
import styles from "./styles.module.scss";
import styles from './styles.module.scss';
interface UserSettingsViewProps {}
@ -20,10 +21,11 @@ const getError = (error?: string) =>
const UserSettingsView: FC<UserSettingsViewProps> = () => {
const { values, handleChange, errors } = useSettings();
const { isPhone } = useWindowSize();
return (
<Group>
<Group horizontal className={styles.base_info}>
<Group horizontal={!isPhone} className={styles.base_info}>
<Superpower>
<Zone className={styles.avatar} title="Фото">
<small>
@ -33,18 +35,18 @@ const UserSettingsView: FC<UserSettingsViewProps> = () => {
</Zone>
</Superpower>
<Zone title="О себе">
<Zone title="О себе" className={styles.about}>
<Group>
<InputText
value={values.fullname}
handler={handleChange("fullname")}
handler={handleChange('fullname')}
title="Полное имя"
error={getError(errors.fullname)}
/>
<Textarea
value={values.description}
handler={handleChange("description")}
handler={handleChange('description')}
title="Описание"
/>
@ -75,21 +77,21 @@ const UserSettingsView: FC<UserSettingsViewProps> = () => {
<Group>
<InputText
value={values.username}
handler={handleChange("username")}
handler={handleChange('username')}
title="Логин"
error={getError(errors.username)}
/>
<InputText
value={values.email}
handler={handleChange("email")}
handler={handleChange('email')}
title="E-mail"
error={getError(errors.email)}
/>
<InputText
value={values.newPassword}
handler={handleChange("newPassword")}
handler={handleChange('newPassword')}
title="Новый пароль"
type="password"
error={getError(errors.newPassword)}
@ -97,7 +99,7 @@ const UserSettingsView: FC<UserSettingsViewProps> = () => {
<InputText
value={values.password}
handler={handleChange("password")}
handler={handleChange('password')}
title="Старый пароль"
type="password"
error={getError(errors.password)}

View file

@ -3,6 +3,10 @@
$pad_danger: mix($red, $content_bg, 70%);
$pad_usual: mix(white, $content_bg, 10%);
.about {
flex: 4;
}
.wrap {
padding: $gap;
z-index: 4;
@ -21,5 +25,5 @@ div.base_info.base_info {
}
.avatar {
flex: 0 0 150px;
}
flex: 1 0 90px;
}

View file

@ -1,22 +1,72 @@
import { VFC } from 'react';
import React, { useCallback, useEffect, useMemo, VFC } from 'react';
import { isNil } from 'ramda';
import { CoverBackdrop } from '~/components/containers/CoverBackdrop';
import { ProfileSidebarNotes } from '~/components/profile/ProfileSidebarNotes';
import { ProfileSidebarSettings } from '~/components/profile/ProfileSidebarSettings';
import { SidebarStack } from '~/components/sidebar/SidebarStack';
import { SidebarStackCard } from '~/components/sidebar/SidebarStackCard';
import { SidebarName } from '~/constants/sidebar';
import { ProfileSidebarMenu } from '~/containers/profile/ProfileSidebarMenu';
import { SidebarWrapper } from '~/containers/sidebars/SidebarWrapper';
import { DialogComponentProps } from '~/types/modal';
import { useAuth } from '~/hooks/auth/useAuth';
import { useUser } from '~/hooks/auth/useUser';
import type { SidebarComponentProps } from '~/types/sidebar';
interface ProfileSidebarProps extends DialogComponentProps {
page: string;
const tabs = ['profile', 'bookmarks'] as const;
type TabName = typeof tabs[number];
interface ProfileSidebarProps
extends SidebarComponentProps<SidebarName.Settings> {
page?: TabName;
}
const ProfileSidebar: VFC<ProfileSidebarProps> = ({ onRequestClose }) => {
const ProfileSidebar: VFC<ProfileSidebarProps> = ({
onRequestClose,
page,
openSidebar,
}) => {
const { isUser } = useAuth();
const {
user: { cover },
} = useUser();
const tab = useMemo(
() => (page ? Math.max(tabs.indexOf(page), 0) : undefined),
[page],
);
const onTabChange = useCallback(
(val: number | undefined) => {
openSidebar(SidebarName.Settings, {
page: !isNil(val) ? tabs[val] : undefined,
});
},
[open, onRequestClose],
);
useEffect(() => {
if (!isUser) {
onRequestClose();
}
}, [isUser]);
if (!isUser) {
return null;
}
return (
<SidebarWrapper onClose={onRequestClose}>
<SidebarStack>
<SidebarStackCard headerFeature="close" title="Профиль" onBackPress={onRequestClose}>
<SidebarWrapper
onClose={onRequestClose}
backdrop={cover && <CoverBackdrop cover={cover} />}
>
<SidebarStack tab={tab} onTabChange={onTabChange}>
<SidebarStackCard
headerFeature="close"
title="Профиль"
onBackPress={onRequestClose}
>
<ProfileSidebarMenu onClose={onRequestClose} />
</SidebarStackCard>

View file

@ -1,4 +1,4 @@
import React, { FC, useEffect, useRef } from 'react';
import React, { FC, ReactNode, useEffect, useRef } from 'react';
import { clearAllBodyScrollLocks, disableBodyScroll } from 'body-scroll-lock';
@ -9,9 +9,15 @@ import styles from './styles.module.scss';
interface IProps {
onClose?: () => void;
closeOnBackdropClick?: boolean;
backdrop?: ReactNode;
}
const SidebarWrapper: FC<IProps> = ({ children, onClose, closeOnBackdropClick = true }) => {
const SidebarWrapper: FC<IProps> = ({
children,
onClose,
closeOnBackdropClick = true,
backdrop,
}) => {
const ref = useRef<HTMLDivElement>(null);
useCloseOnEscape(onClose);
@ -25,7 +31,12 @@ const SidebarWrapper: FC<IProps> = ({ children, onClose, closeOnBackdropClick =
return (
<div className={styles.wrapper} ref={ref}>
{closeOnBackdropClick && <div className={styles.backdrop} onClick={onClose} />}
{(closeOnBackdropClick || backdrop) && (
<div className={styles.backdrop} onClick={onClose}>
{backdrop}
</div>
)}
{children}
</div>
);

View file

@ -1,4 +1,12 @@
import React, { ChangeEvent, FC, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import React, {
ChangeEvent,
FC,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { TagAutocomplete } from '~/components/tags/TagAutocomplete';
import { TagWrapper } from '~/components/tags/TagWrapper';
@ -15,7 +23,7 @@ const prepareInput = (input: string): string[] => {
title
.trim()
.substring(0, 64)
.toLowerCase()
.toLowerCase(),
)
.filter(el => el.length > 0);
};
@ -49,7 +57,7 @@ const TagInput: FC<IProps> = ({ exclude, onAppend, onClearTag, onSubmit }) => {
setInput(items[items.length - 1] || '');
},
[onAppend]
[onAppend],
);
const onKeyDown = useCallback(
@ -69,14 +77,13 @@ const TagInput: FC<IProps> = ({ exclude, onAppend, onClearTag, onSubmit }) => {
const created = prepareInput(input);
if (created.length) {
console.log('appending?!!')
onAppend(created);
}
setInput('');
}
},
[input, setInput, onClearTag, onAppend]
[input, setInput, onClearTag, onAppend],
);
const onFocus = useCallback(() => setFocused(true), []);
@ -99,7 +106,7 @@ const TagInput: FC<IProps> = ({ exclude, onAppend, onClearTag, onSubmit }) => {
onSubmit([]);
},
[input, setInput, onSubmit]
[input, setInput, onSubmit],
);
const onAutocompleteSelect = useCallback(
@ -109,13 +116,15 @@ const TagInput: FC<IProps> = ({ exclude, onAppend, onClearTag, onSubmit }) => {
if (!val.trim()) {
return;
}
onAppend([val]);
},
[onAppend, setInput]
[onAppend, setInput],
);
const feature = useMemo(() => (input?.substr(0, 1) === '/' ? 'green' : ''), [input]);
const feature = useMemo(() => (input?.substr(0, 1) === '/' ? 'green' : ''), [
input,
]);
useEffect(() => {
if (!focused) return;
@ -126,7 +135,11 @@ const TagInput: FC<IProps> = ({ exclude, onAppend, onClearTag, onSubmit }) => {
return (
<div className={styles.wrap} ref={wrapper}>
<TagWrapper title={input || placeholder} hasInput={true} feature={feature}>
<TagWrapper
title={input || placeholder}
hasInput={true}
feature={feature}
>
<input
type="text"
value={input}

View file

@ -35,14 +35,6 @@ export const useMessageEventReactions = () => {
void createSocialAccount(path(['data', 'payload', 'token'], event));
}
break;
case EventMessageType.OpenProfile:
const username: string | undefined = path(['data', 'username'], event);
if (!username) {
return;
}
showModal(Dialog.Profile, { username });
break;
default:
console.log('unknown message', event.data);
}

View file

@ -0,0 +1,9 @@
import { useMemo } from "react";
import { useAuth } from "~/hooks/auth/useAuth";
export const useSuperPowers = () => {
const { isTester, setIsTester } = useAuth();
return useMemo(() => ({ isTester, setIsTester }), [isTester, setIsTester]);
};

View file

@ -1,18 +1,16 @@
import { useCallback, useEffect } from 'react';
import { useCallback, useEffect } from "react";
import isBefore from 'date-fns/isBefore';
import isBefore from "date-fns/isBefore";
import { useRandomPhrase } from '~/constants/phrases';
import { useAuth } from '~/hooks/auth/useAuth';
import { useLastSeenBoris } from '~/hooks/auth/useLastSeenBoris';
import { useBorisStats } from '~/hooks/boris/useBorisStats';
import { IComment } from '~/types';
import { useRandomPhrase } from "~/constants/phrases";
import { useLastSeenBoris } from "~/hooks/auth/useLastSeenBoris";
import { useBorisStats } from "~/hooks/boris/useBorisStats";
import { IComment } from "~/types";
export const useBoris = (comments: IComment[]) => {
const title = useRandomPhrase('BORIS_TITLE');
const title = useRandomPhrase("BORIS_TITLE");
const { lastSeen, setLastSeen } = useLastSeenBoris();
const { isTester, setIsTester } = useAuth();
useEffect(() => {
const last_comment = comments[0];
@ -32,12 +30,5 @@ export const useBoris = (comments: IComment[]) => {
const { stats, isLoading: isLoadingStats } = useBorisStats();
const setIsBetaTester = useCallback(
(isTester: boolean) => {
setIsTester(isTester);
},
[setIsTester]
);
return { setIsBetaTester, isTester, stats, title, isLoadingStats };
return { stats, title, isLoadingStats };
};

View file

@ -0,0 +1,11 @@
import { useCallback } from "react";
export const useConfirmation = () =>
useCallback((prompt = "", onApprove: () => {}, onReject?: () => {}) => {
if (!window.confirm(prompt || "Уверен?")) {
onReject?.();
return;
}
onApprove();
}, []);

View file

@ -1,24 +1,30 @@
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useState } from "react";
export const useWindowSize = () => {
const [size, setSize] = useState({ innerWidth: 0, innerHeight: 0, isMobile: false });
const [size, setSize] = useState({
innerWidth: 0,
innerHeight: 0,
isTablet: false,
isPhone: false,
});
const onResize = useCallback(
() =>
setSize({
innerWidth: window.innerWidth,
innerHeight: window.innerHeight,
isMobile: window.innerWidth < 768,
isTablet: window.innerWidth < 768,
isPhone: window.innerWidth < 500,
}),
[]
[],
);
useEffect(() => {
onResize();
window.addEventListener('resize', onResize);
window.addEventListener("resize", onResize);
return () => window.removeEventListener('resize', onResize);
return () => window.removeEventListener("resize", onResize);
}, []);
return size;

View file

@ -1,55 +0,0 @@
import { useCallback, useMemo } from 'react';
import useSWRInfinite, { SWRInfiniteKeyLoader } from 'swr/infinite';
import { apiGetNotes } from '~/api/notes';
import { ApiGetNotesRequest } from '~/api/notes/types';
import { useAuth } from '~/hooks/auth/useAuth';
import { GetLabNodesRequest, ILabNode } from '~/types/lab';
import { flatten, uniqBy } from '~/utils/ramda';
const DEFAULT_COUNT = 20;
const getKey: (isUser: boolean, search: string) => SWRInfiniteKeyLoader = (isUser, search) => (
index,
prev: ILabNode[]
) => {
if (!isUser) return null;
if (index > 0 && (!prev?.length || prev.length < 20)) return null;
const props: GetLabNodesRequest = {
limit: DEFAULT_COUNT,
offset: index * DEFAULT_COUNT,
search: search || '',
};
return JSON.stringify(props);
};
const parseKey = (key: string): ApiGetNotesRequest => {
try {
return JSON.parse(key);
} catch (error) {
return { limit: DEFAULT_COUNT, offset: 0, search: '' };
}
};
export const useGetNotes = (search: string) => {
const { isUser } = useAuth();
const { data, isValidating, size, setSize, mutate } = useSWRInfinite(
getKey(isUser, search),
async (key: string) => {
const result = await apiGetNotes(parseKey(key));
return result.list;
},
{
dedupingInterval: 300,
}
);
const notes = useMemo(() => uniqBy(n => n.id, flatten(data || [])), [data]);
const hasMore = (data?.[size - 1]?.length || 0) >= 1;
const loadMore = useCallback(() => setSize(size + 1), [setSize, size]);
return { notes, hasMore, loadMore, isLoading: !data && isValidating };
};

113
src/hooks/notes/useNotes.ts Normal file
View file

@ -0,0 +1,113 @@
import { useCallback, useMemo } from "react";
import useSWRInfinite, { SWRInfiniteKeyLoader } from "swr/infinite";
import {
apiCreateNote,
apiDeleteNote,
apiListNotes,
apiUpdateNote,
} from "~/api/notes";
import { ApiGetNotesRequest } from "~/api/notes/types";
import { useAuth } from "~/hooks/auth/useAuth";
import { GetLabNodesRequest, ILabNode } from "~/types/lab";
import { Note } from "~/types/notes";
import { flatten, uniqBy } from "~/utils/ramda";
const DEFAULT_COUNT = 20;
const getKey: (isUser: boolean, search: string) => SWRInfiniteKeyLoader = (
isUser,
search,
) => (index, prev: ILabNode[]) => {
if (!isUser) return null;
if (index > 0 && (!prev?.length || prev.length < 20)) return null;
const props: GetLabNodesRequest = {
limit: DEFAULT_COUNT,
offset: index * DEFAULT_COUNT,
search: search || "",
};
return JSON.stringify(props);
};
const parseKey = (key: string): ApiGetNotesRequest => {
try {
return JSON.parse(key);
} catch (error) {
return { limit: DEFAULT_COUNT, offset: 0, search: "" };
}
};
export const useNotes = (search: string) => {
const { isUser } = useAuth();
const { data, isValidating, size, setSize, mutate } = useSWRInfinite(
getKey(isUser, search),
async (key: string) => {
const result = await apiListNotes(parseKey(key));
return result.list;
},
{
dedupingInterval: 300,
},
);
const create = useCallback(
async (text: string, onSuccess?: (note: Note) => void) => {
const result = await apiCreateNote({ text });
if (data) {
await mutate(
data?.map((it, index) => (index === 0 ? [result, ...it] : it)),
{ revalidate: false },
);
}
onSuccess?.(result);
},
[mutate, data],
);
const remove = useCallback(
async (id: number, onSuccess?: () => void) => {
await apiDeleteNote(id);
await mutate(
data?.map(page => page.filter(it => it.id !== id)),
{ revalidate: false },
);
onSuccess?.();
},
[mutate, data],
);
const update = useCallback(
async (id: number, text: string, onSuccess?: () => void) => {
const result = await apiUpdateNote({ id, text });
await mutate(
data?.map(page => page.map(it => (it.id === id ? result : it))),
{ revalidate: false },
);
onSuccess?.();
},
[mutate, data],
);
const notes = useMemo(() => uniqBy(n => n.id, flatten(data || [])), [data]);
const hasMore = (data?.[size - 1]?.length || 0) >= 1;
const loadMore = useCallback(() => setSize(size + 1), [setSize, size]);
return useMemo(
() => ({
notes,
hasMore,
loadMore,
isLoading: !data && isValidating,
create,
remove,
update,
}),
[notes, hasMore, loadMore, data, isValidating, create, remove],
);
};

View file

@ -3,12 +3,12 @@ import { FC, useMemo } from 'react';
import { observer } from 'mobx-react-lite';
import { BorisGraphicStats } from '~/components/boris/BorisGraphicStats';
import { BorisSidebar } from '~/components/boris/BorisSidebar';
import { Superpower } from '~/components/boris/Superpower';
import { Card } from '~/components/containers/Card';
import { Group } from '~/components/containers/Group';
import { Sticky } from '~/components/containers/Sticky';
import { BorisComments } from '~/containers/boris/BorisComments';
import { BorisSidebar } from '~/containers/boris/BorisSidebar';
import { BorisSuperPowersSSR } from '~/containers/boris/BorisSuperpowers/ssr';
import { Container } from '~/containers/main/Container';
import { SidebarRouter } from '~/containers/main/SidebarRouter';
@ -19,71 +19,69 @@ import styles from './styles.module.scss';
type IProps = {
title: string;
setIsBetaTester: (val: boolean) => void;
isTester: boolean;
stats: BorisUsageStats;
isLoadingStats: boolean;
};
const BorisLayout: FC<IProps> = observer(
({ title, setIsBetaTester, isTester, stats, isLoadingStats }) => {
const { isUser } = useAuthProvider();
const commentsByMonth = useMemo(() => stats.backend.comments.by_month?.slice(0, -1), [
stats.backend.comments.by_month,
]);
const nodesByMonth = useMemo(() => stats.backend.nodes.by_month?.slice(0, -1), [
stats.backend.comments.by_month,
]);
const BorisLayout: FC<IProps> = observer(({ title, stats, isLoadingStats }) => {
const { isUser } = useAuthProvider();
const commentsByMonth = useMemo(
() => stats.backend.comments.by_month?.slice(0, -1),
[stats.backend.comments.by_month],
);
const nodesByMonth = useMemo(
() => stats.backend.nodes.by_month?.slice(0, -1),
[stats.backend.comments.by_month],
);
return (
<Container>
<div className={styles.wrap}>
<div className={styles.cover} />
return (
<Container>
<div className={styles.wrap}>
<div className={styles.cover} />
<div className={styles.image}>
<div className={styles.caption}>
<div className={styles.caption_text}>{title}</div>
</div>
<img src="/images/boris_robot.svg" alt="Борис" />
<div className={styles.image}>
<div className={styles.caption}>
<div className={styles.caption_text}>{title}</div>
</div>
<div className={styles.container}>
<Card className={styles.content}>
<Group>
<img src="/images/boris_robot.svg" alt="Борис" />
</div>
<div className={styles.container}>
<Card className={styles.content}>
<Group>
<div>
<Superpower>
<BorisSuperPowersSSR />
</Superpower>
</div>
<BorisGraphicStats
totalComments={stats.backend.comments.total}
commentsByMonth={commentsByMonth}
totalNodes={stats.backend.nodes.total}
nodesByMonth={nodesByMonth}
/>
<BorisGraphicStats
totalComments={stats.backend.comments.total}
commentsByMonth={commentsByMonth}
totalNodes={stats.backend.nodes.total}
nodesByMonth={nodesByMonth}
/>
<BorisComments />
</Group>
</Card>
<Group className={styles.stats}>
<Sticky>
<BorisSidebar
isTester={isTester}
stats={stats}
setBetaTester={setIsBetaTester}
isUser={isUser}
isLoading={isLoadingStats}
/>
</Sticky>
<BorisComments />
</Group>
</div>
</div>
</Card>
<SidebarRouter prefix="/" />
</Container>
);
}
);
<Group className={styles.stats}>
<Sticky>
<BorisSidebar
stats={stats}
isUser={isUser}
isLoading={isLoadingStats}
/>
</Sticky>
</Group>
</div>
</div>
<SidebarRouter prefix="/" />
</Container>
);
});
export { BorisLayout };

View file

@ -25,7 +25,7 @@ const BorisPage: VFC = observer(() => {
isLoading: isLoadingComments,
isLoadingMore,
} = useNodeComments(696);
const { title, setIsBetaTester, isTester, stats, isLoadingStats } = useBoris(comments);
const { title, stats, isLoadingStats } = useBoris(comments);
return (
<NodeContextProvider node={node} isLoading={isLoading} update={update}>
@ -43,8 +43,6 @@ const BorisPage: VFC = observer(() => {
<BorisLayout
title={title}
setIsBetaTester={setIsBetaTester}
isTester={isTester}
stats={stats}
isLoadingStats={isLoadingStats}
/>

View file

@ -1,4 +1,4 @@
@import "src/styles/variables";
@import 'src/styles/variables';
@import 'photoswipe/dist/photoswipe';
@import 'photoswipe/dist/default-skin/default-skin';
@ -55,7 +55,8 @@ body {
color: #555555;
}
.todo, .done {
.todo,
.done {
color: #333333;
border-radius: 3px;
padding: 0 2px;
@ -76,12 +77,8 @@ h2 {
}
.username {
background: transparentize($color: #000000, $amount: 0.8);
padding: 2px 4px;
border-radius: 4px;
cursor: pointer;
color: $wisegreen;
font-weight: bold;
font-weight: 600;
}
a {
@ -129,12 +126,16 @@ button {
outline: none;
}
h3, h2, h1 {
h3,
h2,
h1 {
color: white;
font-weight: 800;
}
h6, h5, h4 {
h6,
h5,
h4 {
color: white;
font-weight: 600;
}
@ -177,4 +178,4 @@ p {
small {
font-size: 0.8em;
}
}

View file

@ -3,19 +3,87 @@
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
hgroup,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
margin: 0;
padding: 0;
border: 0;
@ -24,21 +92,34 @@ time, mark, audio, video {
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
ol,
ul {
list-style: none;
}
blockquote, q {
blockquote,
q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
blockquote:before,
blockquote:after,
q:before,
q:after {
content: '';
content: none;
}
@ -48,4 +129,5 @@ table {
}
button {
padding: 0;
color: inherit;
}

View file

@ -1,5 +1,7 @@
import { ERRORS } from '~/constants/errors';
import { IUser } from '~/types/auth';
import { Context } from "react";
import { ERRORS } from "~/constants/errors";
import { IUser } from "~/types/auth";
export interface ITag {
ID: number;
@ -16,10 +18,11 @@ export interface ITag {
export type IIcon = string;
export type ValueOf<T> = T[keyof T];
export type ContextValue<T> = T extends Context<infer U> ? U : never;
export type UUID = string;
export type IUploadType = 'image' | 'text' | 'audio' | 'video' | 'other';
export type IUploadType = "image" | "text" | "audio" | "video" | "other";
export interface IFile {
id: number;
@ -52,17 +55,21 @@ export interface IFile {
}
export interface IBlockText {
type: 'text';
type: "text";
text: string;
}
export interface IBlockEmbed {
type: 'video';
type: "video";
url: string;
}
export type IBlock = IBlockText | IBlockEmbed;
export type FlowDisplayVariant = 'single' | 'vertical' | 'horizontal' | 'quadro';
export type FlowDisplayVariant =
| "single"
| "vertical"
| "horizontal"
| "quadro";
export interface FlowDisplay {
display: FlowDisplayVariant;
show_description: boolean;
@ -102,7 +109,7 @@ export interface INode {
export type IFlowNode = Pick<
INode,
'id' | 'flow' | 'description' | 'title' | 'thumbnail' | 'created_at'
"id" | "flow" | "description" | "title" | "thumbnail" | "created_at"
>;
export interface IComment {
@ -116,7 +123,7 @@ export interface IComment {
deleted_at?: string;
}
export type IMessage = Omit<IComment, 'user' | 'node'> & {
export type IMessage = Omit<IComment, "user" | "node"> & {
from: IUser;
to: IUser;
};
@ -125,7 +132,7 @@ export interface ICommentGroup {
user: IUser;
comments: IComment[];
distancesInDays: number[];
ids: IComment['id'][];
ids: IComment["id"][];
hasNew: boolean;
}
@ -133,19 +140,19 @@ export type IUploadProgressHandler = (progress: ProgressEvent) => void;
export type IError = ValueOf<typeof ERRORS>;
export const NOTIFICATION_TYPES = {
message: 'message',
comment: 'comment',
node: 'node',
message: "message",
comment: "comment",
node: "node",
};
export type IMessageNotification = {
type: typeof NOTIFICATION_TYPES['message'];
type: typeof NOTIFICATION_TYPES["message"];
content: Partial<IMessage>;
created_at: string;
};
export type ICommentNotification = {
type: typeof NOTIFICATION_TYPES['comment'];
type: typeof NOTIFICATION_TYPES["comment"];
content: Partial<IComment>;
created_at: string;
};

View file

@ -0,0 +1,20 @@
import { FunctionComponent } from "react";
import type { SidebarComponents } from "~/constants/sidebar/components";
export type SidebarComponent = keyof SidebarComponents;
// TODO: use it to store props for sidebar
export type SidebarProps<
T extends SidebarComponent
> = SidebarComponents[T] extends FunctionComponent<infer U>
? U extends object
? U extends SidebarComponentProps<T>
? Omit<U, keyof SidebarComponentProps<T>>
: U
: U
: {};
export interface SidebarComponentProps<T extends SidebarComponent> {
onRequestClose: () => void;
openSidebar: (name: T, props: SidebarProps<T>) => void;
}

View file

@ -9,22 +9,20 @@ import { stripHTMLTags } from '~/utils/stripHTMLTags';
export const formatTextSanitizeYoutube = (text: string): string =>
text.replace(
/(https?:\/\/(www\.)?(youtube\.com|youtu\.be)\/(watch)?(\?v=)?[\w\-&=]+)/gim,
'\n$1\n'
'\n$1\n',
);
/**
* Removes HTML tags
*/
export const formatTextSanitizeTags = (text: string): string => stripHTMLTags(text);
export const formatTextSanitizeTags = (text: string): string =>
stripHTMLTags(text);
/**
* Returns clickable usernames
*/
export const formatTextClickableUsernames = (text: string): string =>
text.replace(
/~([\wа-яА-Я-]+)/giu,
`<span class="username" onClick="window.postMessage({ type: '${EventMessageType.OpenProfile}', username: '$1'});">~$1</span>`
);
text.replace(/~([\wа-яА-Я-]+)/giu, `<span class="username">~$1</span>`);
/**
* Makes gray comments
@ -41,10 +39,13 @@ export const formatTextComments = (text: string): string =>
*/
export const formatTextTodos = (text: string): string =>
text
.replace(/\/\/\s*(todo|туду):?\s*([^\n]+)/gim, '// <span class="todo">$1</span> $2')
.replace(
/\/\/\s*(todo|туду):?\s*([^\n]+)/gim,
'// <span class="todo">$1</span> $2',
)
.replace(
/\/\/\s*(done|сделано|сделал|готово|fixed|пофикшено|фиксед):?\s*([^\n]+)/gim,
'// <span class="done">$1</span> $2'
'// <span class="done">$1</span> $2',
);
/**
@ -56,7 +57,8 @@ export const formatExclamations = (text: string): string =>
/**
* Replaces -- with dash
*/
export const formatTextDash = (text: string): string => text.replace(' -- ', ' — ');
export const formatTextDash = (text: string): string =>
text.replace(' -- ', ' — ');
/**
* Formats with markdown

View file

@ -0,0 +1,21 @@
import { createContext, FC, useContext } from 'react';
import { useNotes } from '~/hooks/notes/useNotes';
const NoteContext = createContext<ReturnType<typeof useNotes>>({
notes: [],
hasMore: false,
loadMore: async () => Promise.resolve(undefined),
isLoading: false,
create: () => Promise.resolve(),
remove: () => Promise.resolve(),
update: (id: number, text: string) => Promise.resolve(),
});
export const NoteProvider: FC = ({ children }) => {
const notes = useNotes('');
return <NoteContext.Provider value={notes}>{children}</NoteContext.Provider>;
};
export const useNotesContext = () => useContext(NoteContext);

View file

@ -1,78 +1,98 @@
import { Context, createContext, createElement, FunctionComponent, PropsWithChildren, useCallback, useContext, useMemo } from 'react';
import {
Context,
createContext,
createElement,
PropsWithChildren,
useCallback,
useContext,
useMemo,
} from 'react';
import { useRouter } from 'next/router';
import { has } from 'ramda';
import { has, omit } from 'ramda';
import { ModalWrapper } from '~/components/dialogs/ModalWrapper';
import { sidebarComponents, SidebarName } from '~/constants/sidebar';
import { DialogComponentProps } from '~/types/modal';
import { SidebarName } from '~/constants/sidebar';
import { sidebarComponents } from '~/constants/sidebar/components';
import { SidebarComponent, SidebarProps } from '~/types/sidebar';
type ContextValue = typeof SidebarContext extends Context<infer U> ? U : never;
type Name = keyof typeof sidebarComponents;
// TODO: use it to store props for sidebar
type Props<T extends Name> = typeof sidebarComponents[T] extends FunctionComponent<infer U>
? U extends DialogComponentProps ? Omit<U, 'onRequestClose'> : U
: {};
const SidebarContext = createContext({
current: undefined as SidebarName | undefined,
open: <T extends Name>(name: T) => {},
close: () => {},
open: <T extends SidebarComponent>(name: T, props: SidebarProps<T>) => {},
close: () => {},
});
export const SidebarProvider = <T extends Name>({ children }: PropsWithChildren<{}>) => {
export const SidebarProvider = <T extends SidebarComponent>({
children,
}: PropsWithChildren<{}>) => {
const router = useRouter();
const current = useMemo(() => {
const val = router.query.sidebar as SidebarName | undefined
const val = router.query.sidebar as SidebarName | undefined;
return val && has(val, sidebarComponents) ? val : undefined;
}, [router]);
const open = useCallback(
<T extends Name>(name: T) => {
<T extends SidebarComponent>(name: T, props: SidebarProps<T>) => {
const [path] = router.asPath.split('?');
void router.push(path + '?sidebar=' + name, path + '?sidebar=' + name, {
const query = Object.entries(props as {})
.filter(([, val]) => val)
.map(([name, val]) => `${name}=${val}`)
.join('&');
const url = path + '?sidebar=' + name + (query && `&${query}`);
// don't store history inside the same sidebar
if (router.query?.sidebar === name) {
void router.replace(url, url, {
shallow: true,
scroll: false,
});
return;
}
void router.push(url, url, {
shallow: true,
scroll: false,
});
},
[router]
[router],
);
const close = useCallback(
() => {
const [path] = router.asPath.split('?');
const close = useCallback(() => {
const [path] = router.asPath.split('?');
console.log('trying to close');
void router.replace(path, path, {
shallow: true,
scroll: false,
});
}, [router]);
void router.replace(path, path, {
shallow: true,
scroll: false,
});
},
[router]
const value = useMemo<ContextValue>(
() => ({
current,
open,
close,
}),
[current, open, close],
);
const value = useMemo<ContextValue>(() => ({
current,
open,
close,
}), [current, open, close]);
return (
<SidebarContext.Provider value={value}>
{children}
{current &&
{current && (
<ModalWrapper onOverlayClick={close}>
{createElement(
sidebarComponents[current],
{ onRequestClose: close } as any
)}
{createElement(sidebarComponents[current], {
onRequestClose: close,
openSidebar: open,
...omit(['sidebar'], router.query),
} as any)}
</ModalWrapper>
}
)}
</SidebarContext.Provider>
);
}
};
export const useSidebar = () => useContext(SidebarContext);

View file

@ -1,9 +0,0 @@
import { EventMessageType } from '~/constants/events';
export const openUserProfile = (username?: string) => {
if (!username) {
return;
}
window.postMessage({ type: EventMessageType.OpenProfile, username }, '*');
};

File diff suppressed because one or more lines are too long

View file

@ -2260,10 +2260,10 @@ prelude-ls@^1.2.1:
resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396"
integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==
prettier@^1.18.2:
version "1.19.1"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.19.1.tgz#f7d7f5ff8a9cd872a7be4ca142095956a60797cb"
integrity sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==
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-format@^26.6.2:
version "26.6.2"