From 93ce8560fa19c3a91de99643fdbbe4f895a47b84 Mon Sep 17 00:00:00 2001 From: crupest Date: Thu, 11 Jun 2020 17:27:15 +0800 Subject: feat(front): Service worker is coming! --- Timeline/ClientApp/src/App.tsx | 84 ---- Timeline/ClientApp/src/about/About.tsx | 180 -------- Timeline/ClientApp/src/about/about.sass | 3 - Timeline/ClientApp/src/about/author-avatar.png | Bin 12038 -> 0 bytes Timeline/ClientApp/src/admin/Admin.tsx | 78 ---- Timeline/ClientApp/src/admin/UserAdmin.tsx | 463 --------------------- Timeline/ClientApp/src/app/App.tsx | 84 ++++ Timeline/ClientApp/src/app/about/About.tsx | 180 ++++++++ Timeline/ClientApp/src/app/about/about.sass | 3 + Timeline/ClientApp/src/app/about/author-avatar.png | Bin 0 -> 12038 bytes Timeline/ClientApp/src/app/admin/Admin.tsx | 78 ++++ Timeline/ClientApp/src/app/admin/UserAdmin.tsx | 463 +++++++++++++++++++++ Timeline/ClientApp/src/app/common.ts | 4 + Timeline/ClientApp/src/app/common/AlertHost.tsx | 75 ++++ Timeline/ClientApp/src/app/common/AppBar.tsx | 107 +++++ .../ClientApp/src/app/common/CollapseButton.tsx | 101 +++++ Timeline/ClientApp/src/app/common/FileInput.tsx | 41 ++ Timeline/ClientApp/src/app/common/ImageCropper.tsx | 306 ++++++++++++++ Timeline/ClientApp/src/app/common/LoadingPage.tsx | 12 + .../ClientApp/src/app/common/OperationDialog.tsx | 381 +++++++++++++++++ Timeline/ClientApp/src/app/common/SearchInput.tsx | 63 +++ Timeline/ClientApp/src/app/common/TimelineLogo.tsx | 26 ++ .../ClientApp/src/app/common/UserTimelineLogo.tsx | 26 ++ Timeline/ClientApp/src/app/common/alert-service.ts | 59 +++ Timeline/ClientApp/src/app/common/alert.sass | 15 + Timeline/ClientApp/src/app/common/common.sass | 33 ++ Timeline/ClientApp/src/app/config.ts | 1 + Timeline/ClientApp/src/app/data/base64.ts | 9 + Timeline/ClientApp/src/app/data/common.ts | 25 ++ Timeline/ClientApp/src/app/data/timeline.ts | 345 +++++++++++++++ Timeline/ClientApp/src/app/data/user.ts | 224 ++++++++++ Timeline/ClientApp/src/app/helper.ts | 35 ++ Timeline/ClientApp/src/app/home/Home.tsx | 155 +++++++ Timeline/ClientApp/src/app/home/TimelineBoard.tsx | 54 +++ .../src/app/home/TimelineBoardAreaWithUser.tsx | 36 ++ .../src/app/home/TimelineBoardAreaWithoutUser.tsx | 26 ++ .../src/app/home/TimelineCreateDialog.tsx | 60 +++ Timeline/ClientApp/src/app/home/home.sass | 13 + Timeline/ClientApp/src/app/i18n.ts | 79 ++++ Timeline/ClientApp/src/app/index.sass | 86 ++++ Timeline/ClientApp/src/app/index.tsx | 22 + .../ClientApp/src/app/locales/en/translation.ts | 183 ++++++++ Timeline/ClientApp/src/app/locales/scheme.ts | 167 ++++++++ .../ClientApp/src/app/locales/zh/translation.ts | 178 ++++++++ Timeline/ClientApp/src/app/settings/Settings.tsx | 253 +++++++++++ Timeline/ClientApp/src/app/timeline/Timeline.tsx | 99 +++++ .../src/app/timeline/TimelineDeleteDialog.tsx | 59 +++ .../src/app/timeline/TimelineInfoCard.tsx | 109 +++++ .../ClientApp/src/app/timeline/TimelineItem.tsx | 175 ++++++++ .../ClientApp/src/app/timeline/TimelineMember.tsx | 196 +++++++++ .../ClientApp/src/app/timeline/TimelinePage.tsx | 39 ++ .../src/app/timeline/TimelinePageTemplate.tsx | 275 ++++++++++++ .../src/app/timeline/TimelinePageTemplateUI.tsx | 212 ++++++++++ .../ClientApp/src/app/timeline/TimelinePageUI.tsx | 22 + .../src/app/timeline/TimelinePostEdit.tsx | 224 ++++++++++ .../app/timeline/TimelinePropertyChangeDialog.tsx | 70 ++++ .../ClientApp/src/app/timeline/timeline-ui.sass | 18 + Timeline/ClientApp/src/app/timeline/timeline.sass | 125 ++++++ Timeline/ClientApp/src/app/tsconfig.json | 13 + Timeline/ClientApp/src/app/type-utilities.ts | 1 + Timeline/ClientApp/src/app/typings.d.ts | 24 ++ .../ClientApp/src/app/user/ChangeAvatarDialog.tsx | 306 ++++++++++++++ .../src/app/user/ChangeNicknameDialog.tsx | 28 ++ Timeline/ClientApp/src/app/user/Login.tsx | 147 +++++++ Timeline/ClientApp/src/app/user/User.tsx | 79 ++++ Timeline/ClientApp/src/app/user/UserInfoCard.tsx | 116 ++++++ Timeline/ClientApp/src/app/user/UserPage.tsx | 20 + Timeline/ClientApp/src/app/user/api.ts | 79 ++++ Timeline/ClientApp/src/app/user/user-page.sass | 11 + Timeline/ClientApp/src/common.ts | 4 - Timeline/ClientApp/src/common/AlertHost.tsx | 75 ---- Timeline/ClientApp/src/common/AppBar.tsx | 107 ----- Timeline/ClientApp/src/common/CollapseButton.tsx | 101 ----- Timeline/ClientApp/src/common/FileInput.tsx | 41 -- Timeline/ClientApp/src/common/ImageCropper.tsx | 306 -------------- Timeline/ClientApp/src/common/LoadingPage.tsx | 12 - Timeline/ClientApp/src/common/OperationDialog.tsx | 381 ----------------- Timeline/ClientApp/src/common/SearchInput.tsx | 63 --- Timeline/ClientApp/src/common/TimelineLogo.tsx | 26 -- Timeline/ClientApp/src/common/UserTimelineLogo.tsx | 26 -- Timeline/ClientApp/src/common/alert-service.ts | 59 --- Timeline/ClientApp/src/common/alert.sass | 15 - Timeline/ClientApp/src/common/common.sass | 33 -- Timeline/ClientApp/src/config.ts | 1 - Timeline/ClientApp/src/data/base64.ts | 9 - Timeline/ClientApp/src/data/common.ts | 25 -- Timeline/ClientApp/src/data/timeline.ts | 345 --------------- Timeline/ClientApp/src/data/user.ts | 224 ---------- Timeline/ClientApp/src/helper.ts | 35 -- Timeline/ClientApp/src/home/Home.tsx | 155 ------- Timeline/ClientApp/src/home/TimelineBoard.tsx | 54 --- .../src/home/TimelineBoardAreaWithUser.tsx | 36 -- .../src/home/TimelineBoardAreaWithoutUser.tsx | 26 -- .../ClientApp/src/home/TimelineCreateDialog.tsx | 60 --- Timeline/ClientApp/src/home/home.sass | 13 - Timeline/ClientApp/src/i18n.ts | 79 ---- Timeline/ClientApp/src/index.sass | 86 ---- Timeline/ClientApp/src/index.tsx | 15 - Timeline/ClientApp/src/locales/en/translation.ts | 183 -------- Timeline/ClientApp/src/locales/scheme.ts | 167 -------- Timeline/ClientApp/src/locales/zh/translation.ts | 178 -------- Timeline/ClientApp/src/settings/Settings.tsx | 253 ----------- Timeline/ClientApp/src/sw/sw.ts | 22 + Timeline/ClientApp/src/sw/tsconfig.json | 12 + Timeline/ClientApp/src/timeline/Timeline.tsx | 99 ----- .../src/timeline/TimelineDeleteDialog.tsx | 59 --- .../ClientApp/src/timeline/TimelineInfoCard.tsx | 109 ----- Timeline/ClientApp/src/timeline/TimelineItem.tsx | 175 -------- Timeline/ClientApp/src/timeline/TimelineMember.tsx | 196 --------- Timeline/ClientApp/src/timeline/TimelinePage.tsx | 39 -- .../src/timeline/TimelinePageTemplate.tsx | 275 ------------ .../src/timeline/TimelinePageTemplateUI.tsx | 212 ---------- Timeline/ClientApp/src/timeline/TimelinePageUI.tsx | 22 - .../ClientApp/src/timeline/TimelinePostEdit.tsx | 224 ---------- .../src/timeline/TimelinePropertyChangeDialog.tsx | 70 ---- Timeline/ClientApp/src/timeline/timeline-ui.sass | 18 - Timeline/ClientApp/src/timeline/timeline.sass | 125 ------ Timeline/ClientApp/src/tsconfig.json | 17 + Timeline/ClientApp/src/type-utilities.ts | 1 - Timeline/ClientApp/src/typings.d.ts | 24 -- Timeline/ClientApp/src/user/ChangeAvatarDialog.tsx | 306 -------------- .../ClientApp/src/user/ChangeNicknameDialog.tsx | 28 -- Timeline/ClientApp/src/user/Login.tsx | 147 ------- Timeline/ClientApp/src/user/User.tsx | 79 ---- Timeline/ClientApp/src/user/UserInfoCard.tsx | 116 ------ Timeline/ClientApp/src/user/UserPage.tsx | 20 - Timeline/ClientApp/src/user/api.ts | 79 ---- Timeline/ClientApp/src/user/user-page.sass | 11 - 128 files changed, 6506 insertions(+), 6435 deletions(-) delete mode 100644 Timeline/ClientApp/src/App.tsx delete mode 100644 Timeline/ClientApp/src/about/About.tsx delete mode 100644 Timeline/ClientApp/src/about/about.sass delete mode 100644 Timeline/ClientApp/src/about/author-avatar.png delete mode 100644 Timeline/ClientApp/src/admin/Admin.tsx delete mode 100644 Timeline/ClientApp/src/admin/UserAdmin.tsx create mode 100644 Timeline/ClientApp/src/app/App.tsx create mode 100644 Timeline/ClientApp/src/app/about/About.tsx create mode 100644 Timeline/ClientApp/src/app/about/about.sass create mode 100644 Timeline/ClientApp/src/app/about/author-avatar.png create mode 100644 Timeline/ClientApp/src/app/admin/Admin.tsx create mode 100644 Timeline/ClientApp/src/app/admin/UserAdmin.tsx create mode 100644 Timeline/ClientApp/src/app/common.ts create mode 100644 Timeline/ClientApp/src/app/common/AlertHost.tsx create mode 100644 Timeline/ClientApp/src/app/common/AppBar.tsx create mode 100644 Timeline/ClientApp/src/app/common/CollapseButton.tsx create mode 100644 Timeline/ClientApp/src/app/common/FileInput.tsx create mode 100644 Timeline/ClientApp/src/app/common/ImageCropper.tsx create mode 100644 Timeline/ClientApp/src/app/common/LoadingPage.tsx create mode 100644 Timeline/ClientApp/src/app/common/OperationDialog.tsx create mode 100644 Timeline/ClientApp/src/app/common/SearchInput.tsx create mode 100644 Timeline/ClientApp/src/app/common/TimelineLogo.tsx create mode 100644 Timeline/ClientApp/src/app/common/UserTimelineLogo.tsx create mode 100644 Timeline/ClientApp/src/app/common/alert-service.ts create mode 100644 Timeline/ClientApp/src/app/common/alert.sass create mode 100644 Timeline/ClientApp/src/app/common/common.sass create mode 100644 Timeline/ClientApp/src/app/config.ts create mode 100644 Timeline/ClientApp/src/app/data/base64.ts create mode 100644 Timeline/ClientApp/src/app/data/common.ts create mode 100644 Timeline/ClientApp/src/app/data/timeline.ts create mode 100644 Timeline/ClientApp/src/app/data/user.ts create mode 100644 Timeline/ClientApp/src/app/helper.ts create mode 100644 Timeline/ClientApp/src/app/home/Home.tsx create mode 100644 Timeline/ClientApp/src/app/home/TimelineBoard.tsx create mode 100644 Timeline/ClientApp/src/app/home/TimelineBoardAreaWithUser.tsx create mode 100644 Timeline/ClientApp/src/app/home/TimelineBoardAreaWithoutUser.tsx create mode 100644 Timeline/ClientApp/src/app/home/TimelineCreateDialog.tsx create mode 100644 Timeline/ClientApp/src/app/home/home.sass create mode 100644 Timeline/ClientApp/src/app/i18n.ts create mode 100644 Timeline/ClientApp/src/app/index.sass create mode 100644 Timeline/ClientApp/src/app/index.tsx create mode 100644 Timeline/ClientApp/src/app/locales/en/translation.ts create mode 100644 Timeline/ClientApp/src/app/locales/scheme.ts create mode 100644 Timeline/ClientApp/src/app/locales/zh/translation.ts create mode 100644 Timeline/ClientApp/src/app/settings/Settings.tsx create mode 100644 Timeline/ClientApp/src/app/timeline/Timeline.tsx create mode 100644 Timeline/ClientApp/src/app/timeline/TimelineDeleteDialog.tsx create mode 100644 Timeline/ClientApp/src/app/timeline/TimelineInfoCard.tsx create mode 100644 Timeline/ClientApp/src/app/timeline/TimelineItem.tsx create mode 100644 Timeline/ClientApp/src/app/timeline/TimelineMember.tsx create mode 100644 Timeline/ClientApp/src/app/timeline/TimelinePage.tsx create mode 100644 Timeline/ClientApp/src/app/timeline/TimelinePageTemplate.tsx create mode 100644 Timeline/ClientApp/src/app/timeline/TimelinePageTemplateUI.tsx create mode 100644 Timeline/ClientApp/src/app/timeline/TimelinePageUI.tsx create mode 100644 Timeline/ClientApp/src/app/timeline/TimelinePostEdit.tsx create mode 100644 Timeline/ClientApp/src/app/timeline/TimelinePropertyChangeDialog.tsx create mode 100644 Timeline/ClientApp/src/app/timeline/timeline-ui.sass create mode 100644 Timeline/ClientApp/src/app/timeline/timeline.sass create mode 100644 Timeline/ClientApp/src/app/tsconfig.json create mode 100644 Timeline/ClientApp/src/app/type-utilities.ts create mode 100644 Timeline/ClientApp/src/app/typings.d.ts create mode 100644 Timeline/ClientApp/src/app/user/ChangeAvatarDialog.tsx create mode 100644 Timeline/ClientApp/src/app/user/ChangeNicknameDialog.tsx create mode 100644 Timeline/ClientApp/src/app/user/Login.tsx create mode 100644 Timeline/ClientApp/src/app/user/User.tsx create mode 100644 Timeline/ClientApp/src/app/user/UserInfoCard.tsx create mode 100644 Timeline/ClientApp/src/app/user/UserPage.tsx create mode 100644 Timeline/ClientApp/src/app/user/api.ts create mode 100644 Timeline/ClientApp/src/app/user/user-page.sass delete mode 100644 Timeline/ClientApp/src/common.ts delete mode 100644 Timeline/ClientApp/src/common/AlertHost.tsx delete mode 100644 Timeline/ClientApp/src/common/AppBar.tsx delete mode 100644 Timeline/ClientApp/src/common/CollapseButton.tsx delete mode 100644 Timeline/ClientApp/src/common/FileInput.tsx delete mode 100644 Timeline/ClientApp/src/common/ImageCropper.tsx delete mode 100644 Timeline/ClientApp/src/common/LoadingPage.tsx delete mode 100644 Timeline/ClientApp/src/common/OperationDialog.tsx delete mode 100644 Timeline/ClientApp/src/common/SearchInput.tsx delete mode 100644 Timeline/ClientApp/src/common/TimelineLogo.tsx delete mode 100644 Timeline/ClientApp/src/common/UserTimelineLogo.tsx delete mode 100644 Timeline/ClientApp/src/common/alert-service.ts delete mode 100644 Timeline/ClientApp/src/common/alert.sass delete mode 100644 Timeline/ClientApp/src/common/common.sass delete mode 100644 Timeline/ClientApp/src/config.ts delete mode 100644 Timeline/ClientApp/src/data/base64.ts delete mode 100644 Timeline/ClientApp/src/data/common.ts delete mode 100644 Timeline/ClientApp/src/data/timeline.ts delete mode 100644 Timeline/ClientApp/src/data/user.ts delete mode 100644 Timeline/ClientApp/src/helper.ts delete mode 100644 Timeline/ClientApp/src/home/Home.tsx delete mode 100644 Timeline/ClientApp/src/home/TimelineBoard.tsx delete mode 100644 Timeline/ClientApp/src/home/TimelineBoardAreaWithUser.tsx delete mode 100644 Timeline/ClientApp/src/home/TimelineBoardAreaWithoutUser.tsx delete mode 100644 Timeline/ClientApp/src/home/TimelineCreateDialog.tsx delete mode 100644 Timeline/ClientApp/src/home/home.sass delete mode 100644 Timeline/ClientApp/src/i18n.ts delete mode 100644 Timeline/ClientApp/src/index.sass delete mode 100644 Timeline/ClientApp/src/index.tsx delete mode 100644 Timeline/ClientApp/src/locales/en/translation.ts delete mode 100644 Timeline/ClientApp/src/locales/scheme.ts delete mode 100644 Timeline/ClientApp/src/locales/zh/translation.ts delete mode 100644 Timeline/ClientApp/src/settings/Settings.tsx create mode 100644 Timeline/ClientApp/src/sw/sw.ts create mode 100644 Timeline/ClientApp/src/sw/tsconfig.json delete mode 100644 Timeline/ClientApp/src/timeline/Timeline.tsx delete mode 100644 Timeline/ClientApp/src/timeline/TimelineDeleteDialog.tsx delete mode 100644 Timeline/ClientApp/src/timeline/TimelineInfoCard.tsx delete mode 100644 Timeline/ClientApp/src/timeline/TimelineItem.tsx delete mode 100644 Timeline/ClientApp/src/timeline/TimelineMember.tsx delete mode 100644 Timeline/ClientApp/src/timeline/TimelinePage.tsx delete mode 100644 Timeline/ClientApp/src/timeline/TimelinePageTemplate.tsx delete mode 100644 Timeline/ClientApp/src/timeline/TimelinePageTemplateUI.tsx delete mode 100644 Timeline/ClientApp/src/timeline/TimelinePageUI.tsx delete mode 100644 Timeline/ClientApp/src/timeline/TimelinePostEdit.tsx delete mode 100644 Timeline/ClientApp/src/timeline/TimelinePropertyChangeDialog.tsx delete mode 100644 Timeline/ClientApp/src/timeline/timeline-ui.sass delete mode 100644 Timeline/ClientApp/src/timeline/timeline.sass create mode 100644 Timeline/ClientApp/src/tsconfig.json delete mode 100644 Timeline/ClientApp/src/type-utilities.ts delete mode 100644 Timeline/ClientApp/src/typings.d.ts delete mode 100644 Timeline/ClientApp/src/user/ChangeAvatarDialog.tsx delete mode 100644 Timeline/ClientApp/src/user/ChangeNicknameDialog.tsx delete mode 100644 Timeline/ClientApp/src/user/Login.tsx delete mode 100644 Timeline/ClientApp/src/user/User.tsx delete mode 100644 Timeline/ClientApp/src/user/UserInfoCard.tsx delete mode 100644 Timeline/ClientApp/src/user/UserPage.tsx delete mode 100644 Timeline/ClientApp/src/user/api.ts delete mode 100644 Timeline/ClientApp/src/user/user-page.sass (limited to 'Timeline/ClientApp/src') diff --git a/Timeline/ClientApp/src/App.tsx b/Timeline/ClientApp/src/App.tsx deleted file mode 100644 index befa2a9c..00000000 --- a/Timeline/ClientApp/src/App.tsx +++ /dev/null @@ -1,84 +0,0 @@ -import React from 'react'; -import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; -import { hot } from 'react-hot-loader/root'; - -import AppBar from './common/AppBar'; -import LoadingPage from './common/LoadingPage'; -import Home from './home/Home'; -import Login from './user/Login'; -import Settings from './settings/Settings'; -import About from './about/About'; -import User from './user/User'; -import TimelinePage from './timeline/TimelinePage'; -import AlertHost from './common/AlertHost'; - -import { checkUserLoginState, useOptionalUser } from './data/user'; - -const NoMatch: React.FC = () => { - return ( - <> - -
-
Ah-oh, 404!
- - ); -}; - -const LazyAdmin = React.lazy(() => - import(/* webpackChunkName: "admin" */ './admin/Admin') -); - -const App: React.FC = () => { - const user = useOptionalUser(); - - React.useEffect(() => { - void checkUserLoginState(); - }, []); - - let body; - if (user === undefined) { - body = ; - } else { - body = ( - }> - - - - - - - - - - - - - - - - - - - - {user && user.administrator && ( - - - - )} - - - - - - ); - } - - return ( - <> - {body} - - - ); -}; - -export default hot(App); diff --git a/Timeline/ClientApp/src/about/About.tsx b/Timeline/ClientApp/src/about/About.tsx deleted file mode 100644 index 031c46cb..00000000 --- a/Timeline/ClientApp/src/about/About.tsx +++ /dev/null @@ -1,180 +0,0 @@ -import React from 'react'; -import { useTranslation, Trans } from 'react-i18next'; - -import authorAvatarUrl from './author-avatar.png'; - -import AppBar from '../common/AppBar'; - -const frontendCredits: { - name: string; - url: string; - icon?: string; -}[] = [ - { - name: 'reactjs', - url: 'https://reactjs.org', - icon: 'react', - }, - { - name: 'typescript', - url: 'https://www.typescriptlang.org', - }, - { - name: 'bootstrap', - url: 'https://getbootstrap.com', - icon: 'bootstrap', - }, - { - name: 'reactstrap', - url: 'https://reactstrap.github.io', - }, - { - name: 'babeljs', - url: 'https://babeljs.io', - }, - { - name: 'webpack', - url: 'https://webpack.js.org', - }, - { - name: 'sass', - url: 'https://sass-lang.com', - icon: 'sass', - }, - { - name: 'fontawesome', - url: 'https://fontawesome.com', - icon: 'font-awesome-flag', - }, - { - name: 'eslint', - url: 'https://eslint.org', - }, - { - name: 'prettier', - url: 'https://prettier.io', - }, - { - name: 'pepjs', - url: 'https://github.com/jquery/PEP', - }, -]; - -const backendCredits: { - name: string; - url: string; - icon?: string; -}[] = [ - { - name: 'ASP.NET Core', - url: 'https://dotnet.microsoft.com/learn/aspnet/what-is-aspnet-core', - }, - { name: 'sqlite', url: 'https://sqlite.org' }, - { - name: 'ImageSharp', - url: 'https://github.com/SixLabors/ImageSharp', - }, -]; - -const About: React.FC = () => { - const { t } = useTranslation(); - - return ( - <> - -
-
-

{t('about.author.title')}

-
-
- -
-

- {t('about.author.fullname')} - 杨宇千 -

-

- {t('about.author.nickname')} - crupest -

-

- {t('about.author.introduction')} - {t('about.author.introductionContent')} -

-
-
-

- {t('about.author.links')} - - - -

-
-
-
-

{t('about.site.title')}

-

- - 01234 - 56 - -

-

- - {t('about.site.repo')} - -

-
-
-

{t('about.credits.title')}

-

{t('about.credits.content')}

-

{t('about.credits.frontend')}

- -

{t('about.credits.backend')}

- -
-
- - ); -}; - -export default About; diff --git a/Timeline/ClientApp/src/about/about.sass b/Timeline/ClientApp/src/about/about.sass deleted file mode 100644 index 24af9dee..00000000 --- a/Timeline/ClientApp/src/about/about.sass +++ /dev/null @@ -1,3 +0,0 @@ -.about-link-icon - @extend .mx-2 - font-size: 1.2em diff --git a/Timeline/ClientApp/src/about/author-avatar.png b/Timeline/ClientApp/src/about/author-avatar.png deleted file mode 100644 index d890d8d0..00000000 Binary files a/Timeline/ClientApp/src/about/author-avatar.png and /dev/null differ diff --git a/Timeline/ClientApp/src/admin/Admin.tsx b/Timeline/ClientApp/src/admin/Admin.tsx deleted file mode 100644 index af07dd2b..00000000 --- a/Timeline/ClientApp/src/admin/Admin.tsx +++ /dev/null @@ -1,78 +0,0 @@ -import React, { Fragment } from 'react'; -import { Nav, NavItem, NavLink } from 'reactstrap'; -import { - Redirect, - Route, - Switch, - useRouteMatch, - useHistory -} from 'react-router'; -import classnames from 'classnames'; - -import AppBar from '../common/AppBar'; -import UserAdmin from './UserAdmin'; - -import { UserWithToken } from '../data/user'; - -interface AdminProps { - user: UserWithToken; -} - -const Admin: React.FC = props => { - const match = useRouteMatch(); - const history = useHistory(); - type TabNames = 'users' | 'more'; - - const tabName = history.location.pathname.replace(match.path + '/', ''); - - function toggle(newTab: TabNames): void { - history.push(`${match.url}/${newTab}`); - } - - const createRoute = ( - name: string, - body: React.ReactNode - ): React.ReactNode => { - return ( - - -
- - {body} - - ); - }; - - return ( - - - - {createRoute('users', )} - {createRoute('more',
More Page Works
)} -
-
- ); -}; - -export default Admin; diff --git a/Timeline/ClientApp/src/admin/UserAdmin.tsx b/Timeline/ClientApp/src/admin/UserAdmin.tsx deleted file mode 100644 index fc752011..00000000 --- a/Timeline/ClientApp/src/admin/UserAdmin.tsx +++ /dev/null @@ -1,463 +0,0 @@ -import React, { useState, useEffect } from 'react'; -import { - ListGroupItem, - Row, - Col, - UncontrolledDropdown, - DropdownToggle, - DropdownMenu, - DropdownItem, - Spinner, - Button, -} from 'reactstrap'; -import axios from 'axios'; - -import OperationDialog from '../common/OperationDialog'; - -import { User, UserWithToken } from '../data/user'; -import { apiBaseUrl } from '../config'; - -async function fetchUserList(_token: string): Promise { - const res = await axios.get(`${apiBaseUrl}/users`); - return res.data; -} - -interface CreateUserInfo { - username: string; - password: string; - administrator: boolean; -} - -async function createUser(user: CreateUserInfo, token: string): Promise { - const res = await axios.post( - `${apiBaseUrl}/userop/createuser?token=${token}`, - user - ); - return res.data; -} - -function deleteUser(username: string, token: string): Promise { - return axios.delete(`${apiBaseUrl}/users/${username}?token=${token}`); -} - -function changeUsername( - oldUsername: string, - newUsername: string, - token: string -): Promise { - return axios.patch(`${apiBaseUrl}/users/${oldUsername}?token=${token}`, { - username: newUsername, - }); -} - -function changePassword( - username: string, - newPassword: string, - token: string -): Promise { - return axios.patch(`${apiBaseUrl}/users/${username}?token=${token}`, { - password: newPassword, - }); -} - -function changePermission( - username: string, - newPermission: boolean, - token: string -): Promise { - return axios.patch(`${apiBaseUrl}/users/${username}?token=${token}`, { - administrator: newPermission, - }); -} - -const kChangeUsername = 'changeusername'; -const kChangePassword = 'changepassword'; -const kChangePermission = 'changepermission'; -const kDelete = 'delete'; - -type TChangeUsername = typeof kChangeUsername; -type TChangePassword = typeof kChangePassword; -type TChangePermission = typeof kChangePermission; -type TDelete = typeof kDelete; - -type ContextMenuItem = - | TChangeUsername - | TChangePassword - | TChangePermission - | TDelete; - -interface UserCardProps { - onContextMenu: (item: ContextMenuItem) => void; - user: User; -} - -const UserItem: React.FC = (props) => { - const user = props.user; - - const createClickCallback = (item: ContextMenuItem): (() => void) => { - return () => { - props.onContextMenu(item); - }; - }; - - return ( - - - -

{user.username}

- - {user.administrator ? 'administrator' : 'user'} - - - - - - Manage - - - - Change Username - - - Change Password - - - Change Permission - - - Delete - - - - -
-
- ); -}; - -interface DialogProps { - open: boolean; - close: () => void; -} - -interface CreateUserDialogProps extends DialogProps { - process: (user: CreateUserInfo) => Promise; -} - -const CreateUserDialog: React.FC = (props) => { - return ( - - props.process({ - username: username as string, - password: password as string, - administrator: administrator as boolean, - }) - } - close={props.close} - open={props.open} - /> - ); -}; - -const UsernameLabel: React.FC = (props) => { - return {props.children}; -}; - -interface UserDeleteDialogProps extends DialogProps { - username: string; - process: () => Promise; -} - -const UserDeleteDialog: React.FC = (props) => { - return ( - ( - <> - {'You are deleting user '} - {props.username} - {' !'} - - )} - onProcess={props.process} - /> - ); -}; - -interface UserModifyDialogProps extends DialogProps { - username: string; - process: (value: T) => Promise; -} - -const UserChangeUsernameDialog: React.FC> = ( - props -) => { - return ( - ( - <> - {'You are change the username of user '} - {props.username} - {' !'} - - )} - inputScheme={[{ type: 'text', label: 'New Username' }]} - onProcess={([newUsername]) => { - return props.process(newUsername as string); - }} - /> - ); -}; - -const UserChangePasswordDialog: React.FC> = ( - props -) => { - return ( - ( - <> - {'You are change the password of user '} - {props.username} - {' !'} - - )} - inputScheme={[{ type: 'text', label: 'New Password' }]} - onProcess={([newPassword]) => { - return props.process(newPassword as string); - }} - /> - ); -}; - -interface UserChangePermissionDialogProps extends DialogProps { - username: string; - newPermission: boolean; - process: () => Promise; -} - -const UserChangePermissionDialog: React.FC = ( - props -) => { - return ( - ( - <> - {'You are change user '} - {props.username} - {' to '} - - {props.newPermission ? 'administrator' : 'normal user'} - - {' !'} - - )} - onProcess={props.process} - /> - ); -}; - -interface UserAdminProps { - user: UserWithToken; -} - -const UserAdmin: React.FC = (props) => { - type DialogInfo = - | null - | { - type: 'create'; - } - | { type: TDelete; username: string } - | { - type: TChangeUsername; - username: string; - } - | { - type: TChangePassword; - username: string; - } - | { - type: TChangePermission; - username: string; - newPermission: boolean; - }; - - const [users, setUsers] = useState(null); - const [dialog, setDialog] = useState(null); - - const token = props.user.token; - - useEffect(() => { - let subscribe = true; - void fetchUserList(props.user.token).then((us) => { - if (subscribe) { - setUsers(us); - } - }); - return () => { - subscribe = false; - }; - }, [props.user]); - - let dialogNode: React.ReactNode; - if (dialog) - switch (dialog.type) { - case 'create': - dialogNode = ( - setDialog(null)} - process={async (user) => { - const u = await createUser(user, token); - setUsers((oldUsers) => [...(oldUsers ?? []), u]); - }} - /> - ); - break; - case 'delete': - dialogNode = ( - setDialog(null)} - username={dialog.username} - process={async () => { - await deleteUser(dialog.username, token); - setUsers((oldUsers) => - (oldUsers ?? []).filter((u) => u.username !== dialog.username) - ); - }} - /> - ); - break; - case kChangeUsername: - dialogNode = ( - setDialog(null)} - username={dialog.username} - process={async (newUsername) => { - await changeUsername(dialog.username, newUsername, token); - setUsers((oldUsers) => { - const users = (oldUsers ?? []).slice(); - const findedUser = users.find( - (u) => u.username === dialog.username - ); - if (findedUser) findedUser.username = newUsername; - return users; - }); - }} - /> - ); - break; - case kChangePassword: - dialogNode = ( - setDialog(null)} - username={dialog.username} - process={async (newPassword) => { - await changePassword(dialog.username, newPassword, token); - }} - /> - ); - break; - case kChangePermission: { - const newPermission = dialog.newPermission; - dialogNode = ( - setDialog(null)} - username={dialog.username} - newPermission={newPermission} - process={async () => { - await changePermission(dialog.username, newPermission, token); - setUsers((oldUsers) => { - const users = (oldUsers ?? []).slice(); - const findedUser = users.find( - (u) => u.username === dialog.username - ); - if (findedUser) findedUser.administrator = newPermission; - return users; - }); - }} - /> - ); - break; - } - } - - if (users) { - const userComponents = users.map((user) => { - return ( - { - setDialog( - item === kChangePermission - ? { - type: kChangePermission, - username: user.username, - newPermission: !user.administrator, - } - : { - type: item, - username: user.username, - } - ); - }} - /> - ); - }); - - return ( - <> - - {userComponents} - {dialogNode} - - ); - } else { - return ; - } -}; - -export default UserAdmin; diff --git a/Timeline/ClientApp/src/app/App.tsx b/Timeline/ClientApp/src/app/App.tsx new file mode 100644 index 00000000..befa2a9c --- /dev/null +++ b/Timeline/ClientApp/src/app/App.tsx @@ -0,0 +1,84 @@ +import React from 'react'; +import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; +import { hot } from 'react-hot-loader/root'; + +import AppBar from './common/AppBar'; +import LoadingPage from './common/LoadingPage'; +import Home from './home/Home'; +import Login from './user/Login'; +import Settings from './settings/Settings'; +import About from './about/About'; +import User from './user/User'; +import TimelinePage from './timeline/TimelinePage'; +import AlertHost from './common/AlertHost'; + +import { checkUserLoginState, useOptionalUser } from './data/user'; + +const NoMatch: React.FC = () => { + return ( + <> + +
+
Ah-oh, 404!
+ + ); +}; + +const LazyAdmin = React.lazy(() => + import(/* webpackChunkName: "admin" */ './admin/Admin') +); + +const App: React.FC = () => { + const user = useOptionalUser(); + + React.useEffect(() => { + void checkUserLoginState(); + }, []); + + let body; + if (user === undefined) { + body = ; + } else { + body = ( + }> + + + + + + + + + + + + + + + + + + + + {user && user.administrator && ( + + + + )} + + + + + + ); + } + + return ( + <> + {body} + + + ); +}; + +export default hot(App); diff --git a/Timeline/ClientApp/src/app/about/About.tsx b/Timeline/ClientApp/src/app/about/About.tsx new file mode 100644 index 00000000..bce4c06e --- /dev/null +++ b/Timeline/ClientApp/src/app/about/About.tsx @@ -0,0 +1,180 @@ +import React from 'react'; +import { useTranslation, Trans } from 'react-i18next'; + +import authorAvatarUrl from './author-avatar.png'; + +import AppBar from '../common/AppBar'; + +const frontendCredits: { + name: string; + url: string; + icon?: string; +}[] = [ + { + name: 'reactjs', + url: 'https://reactjs.org', + icon: 'react', + }, + { + name: 'typescript', + url: 'https://www.typescriptlang.org', + }, + { + name: 'bootstrap', + url: 'https://getbootstrap.com', + icon: 'bootstrap', + }, + { + name: 'reactstrap', + url: 'https://reactstrap.github.io', + }, + { + name: 'babeljs', + url: 'https://babeljs.io', + }, + { + name: 'webpack', + url: 'https://webpack.js.org', + }, + { + name: 'sass', + url: 'https://sass-lang.com', + icon: 'sass', + }, + { + name: 'fontawesome', + url: 'https://fontawesome.com', + icon: 'font-awesome-flag', + }, + { + name: 'eslint', + url: 'https://eslint.org', + }, + { + name: 'prettier', + url: 'https://prettier.io', + }, + { + name: 'pepjs', + url: 'https://github.com/jquery/PEP', + }, +]; + +const backendCredits: { + name: string; + url: string; + icon?: string; +}[] = [ + { + name: 'ASP.NET Core', + url: 'https://dotnet.microsoft.com/learn/aspnet/what-is-aspnet-core', + }, + { name: 'sqlite', url: 'https://sqlite.org' }, + { + name: 'ImageSharp', + url: 'https://github.com/SixLabors/ImageSharp', + }, +]; + +const About: React.FC = () => { + const { t } = useTranslation(); + + return ( + <> + +
+
+

{t('about.author.title')}

+
+
+ +
+

+ {t('about.author.fullname')} + 杨宇千 +

+

+ {t('about.author.nickname')} + crupest +

+

+ {t('about.author.introduction')} + {t('about.author.introductionContent')} +

+
+
+

+ {t('about.author.links')} + + + +

+
+
+
+

{t('about.site.title')}

+

+ + 01234 + 56 + +

+

+ + {t('about.site.repo')} + +

+
+
+

{t('about.credits.title')}

+

{t('about.credits.content')}

+

{t('about.credits.frontend')}

+ +

{t('about.credits.backend')}

+ +
+
+ + ); +}; + +export default About; diff --git a/Timeline/ClientApp/src/app/about/about.sass b/Timeline/ClientApp/src/app/about/about.sass new file mode 100644 index 00000000..0b0f89f5 --- /dev/null +++ b/Timeline/ClientApp/src/app/about/about.sass @@ -0,0 +1,3 @@ +.about-link-icon + @extend .mx-2 + font-size: 1.2em diff --git a/Timeline/ClientApp/src/app/about/author-avatar.png b/Timeline/ClientApp/src/app/about/author-avatar.png new file mode 100644 index 00000000..d890d8d0 Binary files /dev/null and b/Timeline/ClientApp/src/app/about/author-avatar.png differ diff --git a/Timeline/ClientApp/src/app/admin/Admin.tsx b/Timeline/ClientApp/src/app/admin/Admin.tsx new file mode 100644 index 00000000..9e7d592f --- /dev/null +++ b/Timeline/ClientApp/src/app/admin/Admin.tsx @@ -0,0 +1,78 @@ +import React, { Fragment } from 'react'; +import { Nav, NavItem, NavLink } from 'reactstrap'; +import { + Redirect, + Route, + Switch, + useRouteMatch, + useHistory +} from 'react-router'; +import classnames from 'classnames'; + +import AppBar from '../common/AppBar'; +import UserAdmin from './UserAdmin'; + +import { UserWithToken } from '../data/user'; + +interface AdminProps { + user: UserWithToken; +} + +const Admin: React.FC = props => { + const match = useRouteMatch(); + const history = useHistory(); + type TabNames = 'users' | 'more'; + + const tabName = history.location.pathname.replace(match.path + '/', ''); + + function toggle(newTab: TabNames): void { + history.push(`${match.url}/${newTab}`); + } + + const createRoute = ( + name: string, + body: React.ReactNode + ): React.ReactNode => { + return ( + + +
+ + {body} + + ); + }; + + return ( + + + + {createRoute('users', )} + {createRoute('more',
More Page Works
)} +
+
+ ); +}; + +export default Admin; diff --git a/Timeline/ClientApp/src/app/admin/UserAdmin.tsx b/Timeline/ClientApp/src/app/admin/UserAdmin.tsx new file mode 100644 index 00000000..ba14fc84 --- /dev/null +++ b/Timeline/ClientApp/src/app/admin/UserAdmin.tsx @@ -0,0 +1,463 @@ +import React, { useState, useEffect } from 'react'; +import { + ListGroupItem, + Row, + Col, + UncontrolledDropdown, + DropdownToggle, + DropdownMenu, + DropdownItem, + Spinner, + Button, +} from 'reactstrap'; +import axios from 'axios'; + +import OperationDialog from '../common/OperationDialog'; + +import { User, UserWithToken } from '../data/user'; +import { apiBaseUrl } from '../config'; + +async function fetchUserList(_token: string): Promise { + const res = await axios.get(`${apiBaseUrl}/users`); + return res.data; +} + +interface CreateUserInfo { + username: string; + password: string; + administrator: boolean; +} + +async function createUser(user: CreateUserInfo, token: string): Promise { + const res = await axios.post( + `${apiBaseUrl}/userop/createuser?token=${token}`, + user + ); + return res.data; +} + +function deleteUser(username: string, token: string): Promise { + return axios.delete(`${apiBaseUrl}/users/${username}?token=${token}`); +} + +function changeUsername( + oldUsername: string, + newUsername: string, + token: string +): Promise { + return axios.patch(`${apiBaseUrl}/users/${oldUsername}?token=${token}`, { + username: newUsername, + }); +} + +function changePassword( + username: string, + newPassword: string, + token: string +): Promise { + return axios.patch(`${apiBaseUrl}/users/${username}?token=${token}`, { + password: newPassword, + }); +} + +function changePermission( + username: string, + newPermission: boolean, + token: string +): Promise { + return axios.patch(`${apiBaseUrl}/users/${username}?token=${token}`, { + administrator: newPermission, + }); +} + +const kChangeUsername = 'changeusername'; +const kChangePassword = 'changepassword'; +const kChangePermission = 'changepermission'; +const kDelete = 'delete'; + +type TChangeUsername = typeof kChangeUsername; +type TChangePassword = typeof kChangePassword; +type TChangePermission = typeof kChangePermission; +type TDelete = typeof kDelete; + +type ContextMenuItem = + | TChangeUsername + | TChangePassword + | TChangePermission + | TDelete; + +interface UserCardProps { + onContextMenu: (item: ContextMenuItem) => void; + user: User; +} + +const UserItem: React.FC = (props) => { + const user = props.user; + + const createClickCallback = (item: ContextMenuItem): (() => void) => { + return () => { + props.onContextMenu(item); + }; + }; + + return ( + + + +

{user.username}

+ + {user.administrator ? 'administrator' : 'user'} + + + + + + Manage + + + + Change Username + + + Change Password + + + Change Permission + + + Delete + + + + +
+
+ ); +}; + +interface DialogProps { + open: boolean; + close: () => void; +} + +interface CreateUserDialogProps extends DialogProps { + process: (user: CreateUserInfo) => Promise; +} + +const CreateUserDialog: React.FC = (props) => { + return ( + + props.process({ + username: username as string, + password: password as string, + administrator: administrator as boolean, + }) + } + close={props.close} + open={props.open} + /> + ); +}; + +const UsernameLabel: React.FC = (props) => { + return {props.children}; +}; + +interface UserDeleteDialogProps extends DialogProps { + username: string; + process: () => Promise; +} + +const UserDeleteDialog: React.FC = (props) => { + return ( + ( + <> + {'You are deleting user '} + {props.username} + {' !'} + + )} + onProcess={props.process} + /> + ); +}; + +interface UserModifyDialogProps extends DialogProps { + username: string; + process: (value: T) => Promise; +} + +const UserChangeUsernameDialog: React.FC> = ( + props +) => { + return ( + ( + <> + {'You are change the username of user '} + {props.username} + {' !'} + + )} + inputScheme={[{ type: 'text', label: 'New Username' }]} + onProcess={([newUsername]) => { + return props.process(newUsername as string); + }} + /> + ); +}; + +const UserChangePasswordDialog: React.FC> = ( + props +) => { + return ( + ( + <> + {'You are change the password of user '} + {props.username} + {' !'} + + )} + inputScheme={[{ type: 'text', label: 'New Password' }]} + onProcess={([newPassword]) => { + return props.process(newPassword as string); + }} + /> + ); +}; + +interface UserChangePermissionDialogProps extends DialogProps { + username: string; + newPermission: boolean; + process: () => Promise; +} + +const UserChangePermissionDialog: React.FC = ( + props +) => { + return ( + ( + <> + {'You are change user '} + {props.username} + {' to '} + + {props.newPermission ? 'administrator' : 'normal user'} + + {' !'} + + )} + onProcess={props.process} + /> + ); +}; + +interface UserAdminProps { + user: UserWithToken; +} + +const UserAdmin: React.FC = (props) => { + type DialogInfo = + | null + | { + type: 'create'; + } + | { type: TDelete; username: string } + | { + type: TChangeUsername; + username: string; + } + | { + type: TChangePassword; + username: string; + } + | { + type: TChangePermission; + username: string; + newPermission: boolean; + }; + + const [users, setUsers] = useState(null); + const [dialog, setDialog] = useState(null); + + const token = props.user.token; + + useEffect(() => { + let subscribe = true; + void fetchUserList(props.user.token).then((us) => { + if (subscribe) { + setUsers(us); + } + }); + return () => { + subscribe = false; + }; + }, [props.user]); + + let dialogNode: React.ReactNode; + if (dialog) + switch (dialog.type) { + case 'create': + dialogNode = ( + setDialog(null)} + process={async (user) => { + const u = await createUser(user, token); + setUsers((oldUsers) => [...(oldUsers ?? []), u]); + }} + /> + ); + break; + case 'delete': + dialogNode = ( + setDialog(null)} + username={dialog.username} + process={async () => { + await deleteUser(dialog.username, token); + setUsers((oldUsers) => + (oldUsers ?? []).filter((u) => u.username !== dialog.username) + ); + }} + /> + ); + break; + case kChangeUsername: + dialogNode = ( + setDialog(null)} + username={dialog.username} + process={async (newUsername) => { + await changeUsername(dialog.username, newUsername, token); + setUsers((oldUsers) => { + const users = (oldUsers ?? []).slice(); + const findedUser = users.find( + (u) => u.username === dialog.username + ); + if (findedUser) findedUser.username = newUsername; + return users; + }); + }} + /> + ); + break; + case kChangePassword: + dialogNode = ( + setDialog(null)} + username={dialog.username} + process={async (newPassword) => { + await changePassword(dialog.username, newPassword, token); + }} + /> + ); + break; + case kChangePermission: { + const newPermission = dialog.newPermission; + dialogNode = ( + setDialog(null)} + username={dialog.username} + newPermission={newPermission} + process={async () => { + await changePermission(dialog.username, newPermission, token); + setUsers((oldUsers) => { + const users = (oldUsers ?? []).slice(); + const findedUser = users.find( + (u) => u.username === dialog.username + ); + if (findedUser) findedUser.administrator = newPermission; + return users; + }); + }} + /> + ); + break; + } + } + + if (users) { + const userComponents = users.map((user) => { + return ( + { + setDialog( + item === kChangePermission + ? { + type: kChangePermission, + username: user.username, + newPermission: !user.administrator, + } + : { + type: item, + username: user.username, + } + ); + }} + /> + ); + }); + + return ( + <> + + {userComponents} + {dialogNode} + + ); + } else { + return ; + } +}; + +export default UserAdmin; diff --git a/Timeline/ClientApp/src/app/common.ts b/Timeline/ClientApp/src/app/common.ts new file mode 100644 index 00000000..0b11791a --- /dev/null +++ b/Timeline/ClientApp/src/app/common.ts @@ -0,0 +1,4 @@ +// This error is thrown when ui goes wrong with bad logic. +// Such as am variable should not be null, but it does. +// This error should never occur. If it does, it indicates there is some logic bug in codes. +export class UiLogicError extends Error {} diff --git a/Timeline/ClientApp/src/app/common/AlertHost.tsx b/Timeline/ClientApp/src/app/common/AlertHost.tsx new file mode 100644 index 00000000..c815db2b --- /dev/null +++ b/Timeline/ClientApp/src/app/common/AlertHost.tsx @@ -0,0 +1,75 @@ +import React, { useCallback } from 'react'; +import { Alert } from 'reactstrap'; +import without from 'lodash/without'; +import concat from 'lodash/concat'; + +import { + alertService, + AlertInfoEx, + kAlertHostId, + AlertInfo, +} from './alert-service'; + +interface AutoCloseAlertProps { + alert: AlertInfo; + close: () => void; +} + +export const AutoCloseAlert: React.FC = (props) => { + const { alert } = props; + + React.useEffect(() => { + const tag = window.setTimeout(props.close, 5000); + return () => window.clearTimeout(tag); + }, [props.close]); + + return ( + + {alert.message} + + ); +}; + +// oh what a bad name! +interface AlertInfoExEx extends AlertInfoEx { + close: () => void; +} + +export const AlertHost: React.FC = () => { + const [alerts, setAlerts] = React.useState([]); + + // react guarantee that state setters are stable, so we don't need to add it to dependency list + + const consume = useCallback((alert: AlertInfoEx): void => { + const alertEx: AlertInfoExEx = { + ...alert, + close: () => { + setAlerts((oldAlerts) => { + return without(oldAlerts, alertEx); + }); + }, + }; + setAlerts((oldAlerts) => { + return concat(oldAlerts, alertEx); + }); + }, []); + + React.useEffect(() => { + alertService.registerConsumer(consume); + return () => { + alertService.unregisterConsumer(consume); + }; + }, [consume]); + + return ( +
+ {alerts.map((alert) => { + return ( + + ); + })} +
+ ); +}; + +export default AlertHost; diff --git a/Timeline/ClientApp/src/app/common/AppBar.tsx b/Timeline/ClientApp/src/app/common/AppBar.tsx new file mode 100644 index 00000000..f75fe08f --- /dev/null +++ b/Timeline/ClientApp/src/app/common/AppBar.tsx @@ -0,0 +1,107 @@ +import React from 'react'; +import { useHistory, matchPath } from 'react-router'; +import { Link, NavLink } from 'react-router-dom'; +import { Navbar, NavbarToggler, Collapse, Nav, NavItem } from 'reactstrap'; +import { useMediaQuery } from 'react-responsive'; +import { useTranslation } from 'react-i18next'; + +import { useUser } from '../data/user'; +import { useOptionalVersionedAvatarUrl } from '../user/api'; + +import TimelineLogo from './TimelineLogo'; + +const AppBar: React.FC = (_) => { + const history = useHistory(); + const user = useUser(); + const avatarUrl = useOptionalVersionedAvatarUrl(user?._links?.avatar); + + const { t } = useTranslation(); + + const isUpMd = useMediaQuery({ + minWidth: getComputedStyle(document.documentElement).getPropertyValue( + '--breakpoint-md' + ), + }); + + const [isMenuOpen, setIsMenuOpen] = React.useState(false); + + const toggleMenu = React.useCallback((): void => { + setIsMenuOpen((oldIsMenuOpen) => !oldIsMenuOpen); + }, []); + + const isAdministrator = user && user.administrator; + + const rightArea = ( +
+ {user != null ? ( + + + + ) : ( + + {t('nav.login')} + + )} +
+ ); + + return ( + + + + Timeline + + + {isUpMd ? null : rightArea} + + + + + {isUpMd ? rightArea : null} + + + ); +}; + +export default AppBar; diff --git a/Timeline/ClientApp/src/app/common/CollapseButton.tsx b/Timeline/ClientApp/src/app/common/CollapseButton.tsx new file mode 100644 index 00000000..5307c4ac --- /dev/null +++ b/Timeline/ClientApp/src/app/common/CollapseButton.tsx @@ -0,0 +1,101 @@ +import React from 'react'; + +export interface CollapseButtonProps { + collapse: boolean; + onClick: () => void; + className?: string; +} + +const CollapseButton: React.FC = (props) => { + const { onClick, collapse, className } = props; + + return ( + + {(() => { + if (collapse) { + return ( + <> + + + + + + ); + } else { + return ( + <> + + + + + + ); + } + })()} + + ); +}; + +export default CollapseButton; diff --git a/Timeline/ClientApp/src/app/common/FileInput.tsx b/Timeline/ClientApp/src/app/common/FileInput.tsx new file mode 100644 index 00000000..20da7b71 --- /dev/null +++ b/Timeline/ClientApp/src/app/common/FileInput.tsx @@ -0,0 +1,41 @@ +import React from 'react'; +import clsx from 'clsx'; + +import { ExcludeKey } from '../type-utilities'; + +export interface FileInputProps + extends ExcludeKey< + React.InputHTMLAttributes, + 'type' | 'id' + > { + inputId?: string; + labelText: string; + color?: string; + className?: string; +} + +const FileInput: React.FC = props => { + const { inputId, labelText, color, className, ...otherProps } = props; + + const realInputId = React.useMemo(() => { + if (inputId != null) return inputId; + return ( + 'file-input-' + + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) + ); + }, [inputId]); + + return ( + <> + + + + ); +}; + +export default FileInput; diff --git a/Timeline/ClientApp/src/app/common/ImageCropper.tsx b/Timeline/ClientApp/src/app/common/ImageCropper.tsx new file mode 100644 index 00000000..7cb8d3cf --- /dev/null +++ b/Timeline/ClientApp/src/app/common/ImageCropper.tsx @@ -0,0 +1,306 @@ +import * as React from 'react'; +import clsx from 'clsx'; + +import { UiLogicError } from '../common'; + +export interface Clip { + left: number; + top: number; + width: number; +} + +interface NormailizedClip extends Clip { + height: number; +} + +interface ImageInfo { + width: number; + height: number; + landscape: boolean; + ratio: number; + maxClipWidth: number; + maxClipHeight: number; +} + +interface ImageCropperSavedState { + clip: NormailizedClip; + x: number; + y: number; + pointerId: number; +} + +export interface ImageCropperProps { + clip: Clip | null; + imageUrl: string; + onChange: (clip: Clip) => void; + imageElementCallback?: (element: HTMLImageElement | null) => void; + className?: string; +} + +const ImageCropper = (props: ImageCropperProps): React.ReactElement => { + const { clip, imageUrl, onChange, imageElementCallback, className } = props; + + const [oldState, setOldState] = React.useState( + null + ); + const [imageInfo, setImageInfo] = React.useState(null); + + const normalizeClip = (c: Clip | null | undefined): NormailizedClip => { + if (c == null) { + return { left: 0, top: 0, width: 0, height: 0 }; + } + + return { + left: c.left || 0, + top: c.top || 0, + width: c.width || 0, + height: imageInfo != null ? (c.width || 0) / imageInfo.ratio : 0, + }; + }; + + const c = normalizeClip(clip); + + const imgElementRef = React.useRef(null); + + const onImageRef = React.useCallback( + (e: HTMLImageElement | null) => { + imgElementRef.current = e; + if (imageElementCallback != null && e == null) { + imageElementCallback(null); + } + }, + [imageElementCallback] + ); + + const onImageLoad = React.useCallback( + (e: React.SyntheticEvent) => { + const img = e.currentTarget; + const landscape = img.naturalWidth >= img.naturalHeight; + + const info = { + width: img.naturalWidth, + height: img.naturalHeight, + landscape, + ratio: img.naturalHeight / img.naturalWidth, + maxClipWidth: landscape ? img.naturalHeight / img.naturalWidth : 1, + maxClipHeight: landscape ? 1 : img.naturalWidth / img.naturalHeight, + }; + setImageInfo(info); + onChange({ left: 0, top: 0, width: info.maxClipWidth }); + if (imageElementCallback != null) { + imageElementCallback(img); + } + }, + [onChange, imageElementCallback] + ); + + const onPointerDown = React.useCallback( + (e: React.PointerEvent) => { + if (oldState != null) return; + e.currentTarget.setPointerCapture(e.pointerId); + setOldState({ + x: e.clientX, + y: e.clientY, + clip: c, + pointerId: e.pointerId, + }); + }, + [oldState, c] + ); + + const onPointerUp = React.useCallback( + (e: React.PointerEvent) => { + if (oldState == null || oldState.pointerId !== e.pointerId) return; + e.currentTarget.releasePointerCapture(e.pointerId); + setOldState(null); + }, + [oldState] + ); + + const onPointerMove = React.useCallback( + (e: React.PointerEvent) => { + if (oldState == null) return; + + const oldClip = oldState.clip; + + const movement = { x: e.clientX - oldState.x, y: e.clientY - oldState.y }; + + const { current: imgElement } = imgElementRef; + + if (imgElement == null) throw new UiLogicError('Image element is null.'); + + const moveRatio = { + x: movement.x / imgElement.width, + y: movement.y / imgElement.height, + }; + + const newRatio = { + x: oldClip.left + moveRatio.x, + y: oldClip.top + moveRatio.y, + }; + if (newRatio.x < 0) { + newRatio.x = 0; + } else if (newRatio.x > 1 - oldClip.width) { + newRatio.x = 1 - oldClip.width; + } + if (newRatio.y < 0) { + newRatio.y = 0; + } else if (newRatio.y > 1 - oldClip.height) { + newRatio.y = 1 - oldClip.height; + } + + onChange({ left: newRatio.x, top: newRatio.y, width: oldClip.width }); + }, + [oldState, onChange] + ); + + const onHandlerPointerMove = React.useCallback( + (e: React.PointerEvent) => { + if (oldState == null) return; + + const oldClip = oldState.clip; + + const movement = { x: e.clientX - oldState.x, y: e.clientY - oldState.y }; + + const ratio = imageInfo == null ? 1 : imageInfo.ratio; + + const { current: imgElement } = imgElementRef; + + if (imgElement == null) throw new UiLogicError('Image element is null.'); + + const moveRatio = { + x: movement.x / imgElement.width, + y: movement.x / imgElement.width / ratio, + }; + + const newRatio = { + x: oldClip.width + moveRatio.x, + y: oldClip.height + moveRatio.y, + }; + + const maxRatio = { + x: Math.min(1 - oldClip.left, newRatio.x), + y: Math.min(1 - oldClip.top, newRatio.y), + }; + + const maxWidthRatio = Math.min(maxRatio.x, maxRatio.y * ratio); + + let newWidth; + if (newRatio.x < 0) { + newWidth = 0; + } else if (newRatio.x > maxWidthRatio) { + newWidth = maxWidthRatio; + } else { + newWidth = newRatio.x; + } + + onChange({ left: oldClip.left, top: oldClip.top, width: newWidth }); + }, + [imageInfo, oldState, onChange] + ); + + const toPercentage = (n: number): string => `${n}%`; + + // fuck!!! I just can't find a better way to implement this in pure css + const containerStyle: React.CSSProperties = (() => { + if (imageInfo == null) { + return { width: '100%', paddingTop: '100%', height: 0 }; + } else { + if (imageInfo.ratio > 1) { + return { + width: toPercentage(100 / imageInfo.ratio), + paddingTop: '100%', + height: 0, + }; + } else { + return { + width: '100%', + paddingTop: toPercentage(100 * imageInfo.ratio), + height: 0, + }; + } + } + })(); + + return ( +
+ to crop +
+
+
+
+
+ ); +}; + +export default ImageCropper; + +export function applyClipToImage( + image: HTMLImageElement, + clip: Clip, + mimeType: string +): Promise { + return new Promise((resolve, reject) => { + const naturalSize = { + width: image.naturalWidth, + height: image.naturalHeight, + }; + const clipArea = { + x: naturalSize.width * clip.left, + y: naturalSize.height * clip.top, + length: naturalSize.width * clip.width, + }; + + const canvas = document.createElement('canvas'); + canvas.width = clipArea.length; + canvas.height = clipArea.length; + const context = canvas.getContext('2d'); + + if (context == null) throw new Error('Failed to create context.'); + + context.drawImage( + image, + clipArea.x, + clipArea.y, + clipArea.length, + clipArea.length, + 0, + 0, + clipArea.length, + clipArea.length + ); + + canvas.toBlob((blob) => { + if (blob == null) { + reject(new Error('canvas.toBlob returns null')); + } else { + resolve(blob); + } + }, mimeType); + }); +} diff --git a/Timeline/ClientApp/src/app/common/LoadingPage.tsx b/Timeline/ClientApp/src/app/common/LoadingPage.tsx new file mode 100644 index 00000000..81bc74cf --- /dev/null +++ b/Timeline/ClientApp/src/app/common/LoadingPage.tsx @@ -0,0 +1,12 @@ +import React from 'react'; +import { Spinner } from 'reactstrap'; + +const LoadingPage: React.FC = () => { + return ( +
+ +
+ ); +}; + +export default LoadingPage; diff --git a/Timeline/ClientApp/src/app/common/OperationDialog.tsx b/Timeline/ClientApp/src/app/common/OperationDialog.tsx new file mode 100644 index 00000000..30db4053 --- /dev/null +++ b/Timeline/ClientApp/src/app/common/OperationDialog.tsx @@ -0,0 +1,381 @@ +import React, { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { + Spinner, + Container, + ModalBody, + Label, + Input, + FormGroup, + FormFeedback, + ModalFooter, + Button, + Modal, + ModalHeader, + FormText, +} from 'reactstrap'; + +import { UiLogicError } from '../common'; + +const DefaultProcessPrompt: React.FC = (_) => { + return ( + + + + ); +}; + +interface DefaultErrorPromptProps { + error?: string; +} + +const DefaultErrorPrompt: React.FC = (props) => { + const { t } = useTranslation(); + + let result =

{t('operationDialog.error')}

; + + if (props.error != null) { + result = ( + <> + {result} +

{props.error}

+ + ); + } + + return result; +}; + +export type OperationInputOptionalError = undefined | null | string; + +export interface OperationInputErrorInfo { + [index: number]: OperationInputOptionalError; +} + +export type OperationInputValidator = ( + value: TValue, + values: (string | boolean)[] +) => OperationInputOptionalError | OperationInputErrorInfo; + +export interface OperationTextInputInfo { + type: 'text'; + password?: boolean; + label?: string; + initValue?: string; + textFieldProps?: Omit< + React.InputHTMLAttributes, + 'type' | 'value' | 'onChange' + >; + helperText?: string; + validator?: OperationInputValidator; +} + +export interface OperationBoolInputInfo { + type: 'bool'; + label: string; + initValue?: boolean; +} + +export interface OperationSelectInputInfoOption { + value: string; + label: string; + icon?: React.ReactElement; +} + +export interface OperationSelectInputInfo { + type: 'select'; + label: string; + options: OperationSelectInputInfoOption[]; + initValue?: string; +} + +export type OperationInputInfo = + | OperationTextInputInfo + | OperationBoolInputInfo + | OperationSelectInputInfo; + +interface OperationResult { + type: 'success' | 'failure'; + data: unknown; +} + +interface OperationDialogProps { + open: boolean; + close: () => void; + title: React.ReactNode; + titleColor?: 'default' | 'dangerous' | 'create' | string; + onProcess: (inputs: (string | boolean)[]) => Promise; + inputScheme?: OperationInputInfo[]; + inputPrompt?: string | (() => React.ReactNode); + processPrompt?: () => React.ReactNode; + successPrompt?: (data: unknown) => React.ReactNode; + failurePrompt?: (error: unknown) => React.ReactNode; + onSuccessAndClose?: () => void; +} + +const OperationDialog: React.FC = (props) => { + const inputScheme = props.inputScheme ?? []; + + const { t } = useTranslation(); + + type Step = 'input' | 'process' | OperationResult; + const [step, setStep] = useState('input'); + const [values, setValues] = useState<(boolean | string)[]>( + inputScheme.map((i) => { + if (i.type === 'bool') { + return i.initValue ?? false; + } else if (i.type === 'text' || i.type === 'select') { + return i.initValue ?? ''; + } else { + throw new UiLogicError('Unknown input scheme.'); + } + }) + ); + const [inputError, setInputError] = useState({}); + + const close = (): void => { + if (step !== 'process') { + props.close(); + if ( + typeof step === 'object' && + step.type === 'success' && + props.onSuccessAndClose + ) { + props.onSuccessAndClose(); + } + } else { + console.log('Attempt to close modal when processing.'); + } + }; + + const onConfirm = (): void => { + setStep('process'); + props.onProcess(values).then( + (d: unknown) => { + setStep({ + type: 'success', + data: d, + }); + }, + (e: unknown) => { + setStep({ + type: 'failure', + data: e, + }); + } + ); + }; + + let body: React.ReactNode; + if (step === 'input') { + let inputPrompt = + typeof props.inputPrompt === 'function' + ? props.inputPrompt() + : props.inputPrompt; + inputPrompt =
{inputPrompt}
; + + const updateValue = ( + index: number, + newValue: string | boolean + ): (string | boolean)[] => { + const oldValues = values; + const newValues = oldValues.slice(); + newValues[index] = newValue; + setValues(newValues); + return newValues; + }; + + const testErrorInfo = (errorInfo: OperationInputErrorInfo): boolean => { + for (let i = 0; i < inputScheme.length; i++) { + if (inputScheme[i].type === 'text' && errorInfo[i] != null) { + return true; + } + } + return false; + }; + + const calculateError = ( + oldError: OperationInputErrorInfo, + index: number, + newError: OperationInputOptionalError | OperationInputErrorInfo + ): OperationInputErrorInfo => { + if (newError === undefined) { + return oldError; + } else if (newError === null || typeof newError === 'string') { + return { ...oldError, [index]: newError }; + } else { + const newInputError: OperationInputErrorInfo = { ...oldError }; + for (const [index, error] of Object.entries(newError)) { + if (error !== undefined) { + newInputError[+index] = error as OperationInputOptionalError; + } + } + return newInputError; + } + }; + + const validateAll = (): boolean => { + let newInputError = inputError; + for (let i = 0; i < inputScheme.length; i++) { + const item = inputScheme[i]; + if (item.type === 'text') { + newInputError = calculateError( + newInputError, + i, + item.validator?.(values[i] as string, values) + ); + } + } + const result = !testErrorInfo(newInputError); + setInputError(newInputError); + return result; + }; + + body = ( + <> + + {inputPrompt} + {inputScheme.map((item, index) => { + const value = values[index]; + const error: string | undefined = ((e) => + typeof e === 'string' ? t(e) : undefined)(inputError?.[index]); + + if (item.type === 'text') { + return ( + + {item.label && } + { + const v = e.target.value; + const newValues = updateValue(index, v); + setInputError( + calculateError( + inputError, + index, + item.validator?.(v, newValues) + ) + ); + }} + invalid={error != null} + {...item.textFieldProps} + /> + {error != null && {error}} + {item.helperText && {t(item.helperText)}} + + ); + } else if (item.type === 'bool') { + return ( + + { + updateValue( + index, + (e.target as HTMLInputElement).checked + ); + }} + /> + + + ); + } else if (item.type === 'select') { + return ( + + + { + updateValue(index, event.target.value); + }} + > + {item.options.map((option, i) => { + return ( + + ); + })} + + + ); + } + })} + + + + + + + ); + } else if (step === 'process') { + body = ( + + {props.processPrompt?.() ?? } + + ); + } else { + let content: React.ReactNode; + const result = step; + if (result.type === 'success') { + content = + props.successPrompt?.(result.data) ?? t('operationDialog.success'); + if (typeof content === 'string') + content =

{content}

; + } else { + content = props.failurePrompt?.(result.data) ?? ; + if (typeof content === 'string') + content = ; + } + body = ( + <> + {content} + + + + + ); + } + + const title = typeof props.title === 'string' ? t(props.title) : props.title; + + return ( + + + {title} + + {body} + + ); +}; + +export default OperationDialog; diff --git a/Timeline/ClientApp/src/app/common/SearchInput.tsx b/Timeline/ClientApp/src/app/common/SearchInput.tsx new file mode 100644 index 00000000..50c252fa --- /dev/null +++ b/Timeline/ClientApp/src/app/common/SearchInput.tsx @@ -0,0 +1,63 @@ +import React, { useCallback } from 'react'; +import clsx from 'clsx'; +import { Spinner, Input, Button } from 'reactstrap'; +import { useTranslation } from 'react-i18next'; + +export interface SearchInputProps { + value: string; + onChange: (value: string) => void; + onButtonClick: () => void; + className?: string; + loading?: boolean; + buttonText?: string; + placeholder?: string; + additionalButton?: React.ReactNode; +} + +const SearchInput: React.FC = (props) => { + const { onChange, onButtonClick } = props; + + const { t } = useTranslation(); + + const onInputChange = useCallback( + (event: React.ChangeEvent): void => { + onChange(event.currentTarget.value); + }, + [onChange] + ); + + const onInputKeyPress = useCallback( + (event: React.KeyboardEvent): void => { + if (event.key === 'Enter') { + onButtonClick(); + } + }, + [onButtonClick] + ); + + return ( +
+ +
+ {props.additionalButton} +
+
+ {props.loading ? ( + + ) : ( + + )} +
+
+ ); +}; + +export default SearchInput; diff --git a/Timeline/ClientApp/src/app/common/TimelineLogo.tsx b/Timeline/ClientApp/src/app/common/TimelineLogo.tsx new file mode 100644 index 00000000..8dd9e97b --- /dev/null +++ b/Timeline/ClientApp/src/app/common/TimelineLogo.tsx @@ -0,0 +1,26 @@ +import React, { SVGAttributes } from 'react'; + +export interface TimelineLogoProps extends SVGAttributes { + color?: string; +} + +const TimelineLogo: React.FC = props => { + const { color, ...forwardProps } = props; + const coercedColor = color ?? 'currentcolor'; + return ( + + + + + + ); +}; + +export default TimelineLogo; diff --git a/Timeline/ClientApp/src/app/common/UserTimelineLogo.tsx b/Timeline/ClientApp/src/app/common/UserTimelineLogo.tsx new file mode 100644 index 00000000..58a429d8 --- /dev/null +++ b/Timeline/ClientApp/src/app/common/UserTimelineLogo.tsx @@ -0,0 +1,26 @@ +import React, { SVGAttributes } from 'react'; + +export interface UserTimelineLogoProps extends SVGAttributes { + color?: string; +} + +const UserTimelineLogo: React.FC = props => { + const { color, ...forwardProps } = props; + const coercedColor = color ?? 'currentcolor'; + + return ( + + + + + + + + + + + + ); +}; + +export default UserTimelineLogo; diff --git a/Timeline/ClientApp/src/app/common/alert-service.ts b/Timeline/ClientApp/src/app/common/alert-service.ts new file mode 100644 index 00000000..6d3f8af8 --- /dev/null +++ b/Timeline/ClientApp/src/app/common/alert-service.ts @@ -0,0 +1,59 @@ +import pull from 'lodash/pull'; + +export interface AlertInfo { + type?: 'primary' | 'secondary' | 'success' | 'danger' | 'warning' | 'info'; + message: string; +} + +export interface AlertInfoEx extends AlertInfo { + id: number; +} + +export type AlertConsumer = (alerts: AlertInfoEx) => void; + +export class AlertService { + private consumers: AlertConsumer[] = []; + private savedAlerts: AlertInfoEx[] = []; + private currentId = 1; + + private produce(alert: AlertInfoEx): void { + for (const consumer of this.consumers) { + consumer(alert); + } + } + + registerConsumer(consumer: AlertConsumer): void { + this.consumers.push(consumer); + if (this.savedAlerts.length !== 0) { + for (const alert of this.savedAlerts) { + this.produce(alert); + } + this.savedAlerts = []; + } + } + + unregisterConsumer(consumer: AlertConsumer): void { + pull(this.consumers, consumer); + } + + push(alert: AlertInfo): void { + const newAlert: AlertInfoEx = { ...alert, id: this.currentId++ }; + if (this.consumers.length === 0) { + this.savedAlerts.push(newAlert); + } else { + this.produce(newAlert); + } + } +} + +export const alertService = new AlertService(); + +export function pushAlert(alert: AlertInfo): void { + alertService.push(alert); +} + +export const kAlertHostId = 'alert-host'; + +export function getAlertHost(): HTMLElement | null { + return document.getElementById(kAlertHostId); +} diff --git a/Timeline/ClientApp/src/app/common/alert.sass b/Timeline/ClientApp/src/app/common/alert.sass new file mode 100644 index 00000000..5b6e65c2 --- /dev/null +++ b/Timeline/ClientApp/src/app/common/alert.sass @@ -0,0 +1,15 @@ +.alert-container + position: fixed + z-index: $zindex-popover + +@include media-breakpoint-up(sm) + .alert-container + bottom: 0 + right: 0 + +@include media-breakpoint-down(sm) + .alert-container + bottom: 0 + right: 0 + left: 0 + text-align: center diff --git a/Timeline/ClientApp/src/app/common/common.sass b/Timeline/ClientApp/src/app/common/common.sass new file mode 100644 index 00000000..15d34d7c --- /dev/null +++ b/Timeline/ClientApp/src/app/common/common.sass @@ -0,0 +1,33 @@ +.image-cropper-container + position: relative + box-sizing: border-box + user-select: none + +.image-cropper-container img + position: absolute + left: 0 + top: 0 + width: 100% + height: 100% + +.image-cropper-mask-container + position: absolute + left: 0 + top: 0 + right: 0 + bottom: 0 + overflow: hidden + +.image-cropper-mask + position: absolute + box-shadow: 0 0 0 10000px rgba(255, 255, 255, 80%) + touch-action: none + +.image-cropper-handler + position: absolute + width: 26px + height: 26px + border: black solid 2px + border-radius: 50% + background: white + touch-action: none diff --git a/Timeline/ClientApp/src/app/config.ts b/Timeline/ClientApp/src/app/config.ts new file mode 100644 index 00000000..081a2cf6 --- /dev/null +++ b/Timeline/ClientApp/src/app/config.ts @@ -0,0 +1 @@ +export const apiBaseUrl = '/api'; diff --git a/Timeline/ClientApp/src/app/data/base64.ts b/Timeline/ClientApp/src/app/data/base64.ts new file mode 100644 index 00000000..7f7c6fcc --- /dev/null +++ b/Timeline/ClientApp/src/app/data/base64.ts @@ -0,0 +1,9 @@ +export function base64(blob: Blob): Promise { + return new Promise(resolve => { + const reader = new FileReader(); + reader.onload = function() { + resolve((reader.result as string).replace(/^data:.+;base64,/, '')); + }; + reader.readAsDataURL(blob); + }); +} diff --git a/Timeline/ClientApp/src/app/data/common.ts b/Timeline/ClientApp/src/app/data/common.ts new file mode 100644 index 00000000..1cdf93f1 --- /dev/null +++ b/Timeline/ClientApp/src/app/data/common.ts @@ -0,0 +1,25 @@ +import { AxiosError } from 'axios'; + +export function extractStatusCode(error: AxiosError): number | null { + const code = error.response && error.response.status; + if (typeof code === 'number') { + return code; + } else { + return null; + } +} + +export interface CommonErrorResponse { + code: number; + message: string; +} + +export function extractErrorCode(error: AxiosError): number | null { + const { response } = error as AxiosError; + const code = response && response.data && response.data.code; + if (typeof code === 'number') { + return code; + } else { + return null; + } +} diff --git a/Timeline/ClientApp/src/app/data/timeline.ts b/Timeline/ClientApp/src/app/data/timeline.ts new file mode 100644 index 00000000..19bb3d45 --- /dev/null +++ b/Timeline/ClientApp/src/app/data/timeline.ts @@ -0,0 +1,345 @@ +import axios from 'axios'; +import XRegExp from 'xregexp'; + +import { base64 } from './base64'; +import { apiBaseUrl } from '../config'; +import { User, UserAuthInfo, getCurrentUser, UserWithToken } from './user'; +import { UiLogicError } from '../common'; + +export const kTimelineVisibilities = ['Public', 'Register', 'Private'] as const; + +export type TimelineVisibility = typeof kTimelineVisibilities[number]; + +export const timelineVisibilityTooltipTranslationMap: Record< + TimelineVisibility, + string +> = { + Public: 'timeline.visibilityTooltip.public', + Register: 'timeline.visibilityTooltip.register', + Private: 'timeline.visibilityTooltip.private', +}; + +export interface TimelineInfo { + name: string; + description: string; + owner: User; + visibility: TimelineVisibility; + members: User[]; + _links: { + posts: string; + }; +} + +export interface TimelinePostTextContent { + type: 'text'; + text: string; +} + +export interface TimelinePostImageContent { + type: 'image'; + url: string; +} + +export type TimelinePostContent = + | TimelinePostTextContent + | TimelinePostImageContent; + +export interface TimelinePostInfo { + id: number; + content: TimelinePostContent; + time: Date; + author: User; +} + +export interface CreatePostRequestTextContent { + type: 'text'; + text: string; +} + +export interface CreatePostRequestImageContent { + type: 'image'; + data: Blob; +} + +export type CreatePostRequestContent = + | CreatePostRequestTextContent + | CreatePostRequestImageContent; + +export interface CreatePostRequest { + content: CreatePostRequestContent; + time?: Date; +} + +// TODO: Remove in the future +export interface TimelineChangePropertyRequest { + visibility?: TimelineVisibility; + description?: string; +} + +export interface PersonalTimelineChangePropertyRequest { + visibility?: TimelineVisibility; + description?: string; +} + +export interface OrdinaryTimelineChangePropertyRequest { + // not supported by server now + // name?: string; + visibility?: TimelineVisibility; + description?: string; +} + +//-------------------- begin: internal model -------------------- + +interface RawTimelinePostTextContent { + type: 'text'; + text: string; +} + +interface RawTimelinePostImageContent { + type: 'image'; + url: string; +} + +type RawTimelinePostContent = + | RawTimelinePostTextContent + | RawTimelinePostImageContent; + +interface RawTimelinePostInfo { + id: number; + content: RawTimelinePostContent; + time: string; + author: User; +} + +interface RawCreatePostRequestTextContent { + type: 'text'; + text: string; +} + +interface RawCreatePostRequestImageContent { + type: 'text'; + data: string; +} + +type RawCreatePostRequestContent = + | RawCreatePostRequestTextContent + | RawCreatePostRequestImageContent; + +interface RawCreatePostRequest { + content: RawCreatePostRequestContent; + time?: string; +} + +//-------------------- end: internal model -------------------- + +function processRawTimelinePostInfo( + raw: RawTimelinePostInfo, + token?: string +): TimelinePostInfo { + return { + ...raw, + content: (() => { + if (raw.content.type === 'image' && token != null) { + return { + ...raw.content, + url: raw.content.url + '?token=' + token, + }; + } + return raw.content; + })(), + time: new Date(raw.time), + }; +} + +type TimelineUrlResolver = (name: string) => string; + +export class TimelineServiceTemplate< + TTimeline extends TimelineInfo, + TChangePropertyRequest +> { + private checkUser(): UserWithToken { + const user = getCurrentUser(); + if (user == null) { + throw new UiLogicError('You must login to perform the operation.'); + } + return user; + } + + constructor(private urlResolver: TimelineUrlResolver) {} + + changeProperty( + name: string, + req: TChangePropertyRequest + ): Promise { + const user = this.checkUser(); + + return axios + .patch(`${this.urlResolver(name)}?token=${user.token}`, req) + .then((res) => res.data); + } + + fetch(name: string): Promise { + return axios + .get(`${this.urlResolver(name)}`) + .then((res) => res.data); + } + + fetchPosts(name: string): Promise { + const token = getCurrentUser()?.token; + return axios + .get( + token == null + ? `${this.urlResolver(name)}/posts` + : `${this.urlResolver(name)}/posts?token=${token}` + ) + .then((res) => res.data.map((p) => processRawTimelinePostInfo(p, token))); + } + + createPost( + name: string, + request: CreatePostRequest + ): Promise { + const user = this.checkUser(); + + const rawReq: Promise = new Promise< + RawCreatePostRequestContent + >((resolve) => { + if (request.content.type === 'image') { + void base64(request.content.data).then((d) => + resolve({ + ...request.content, + data: d, + } as RawCreatePostRequestImageContent) + ); + } else { + resolve(request.content); + } + }).then((content) => { + const rawReq: RawCreatePostRequest = { + content, + }; + if (request.time != null) { + rawReq.time = request.time.toISOString(); + } + return rawReq; + }); + + return rawReq + .then((req) => + axios.post( + `${this.urlResolver(name)}/posts?token=${user.token}`, + req + ) + ) + .then((res) => processRawTimelinePostInfo(res.data, user.token)); + } + + deletePost(name: string, id: number): Promise { + const user = this.checkUser(); + + return axios.delete( + `${this.urlResolver(name)}/posts/${id}?token=${user.token}` + ); + } + + addMember(name: string, username: string): Promise { + const user = this.checkUser(); + + return axios.put( + `${this.urlResolver(name)}/members/${username}?token=${user.token}` + ); + } + + removeMember(name: string, username: string): Promise { + const user = this.checkUser(); + + return axios.delete( + `${this.urlResolver(name)}/members/${username}?token=${user.token}` + ); + } + + isMemberOf(username: string, timeline: TTimeline): boolean { + return timeline.members.findIndex((m) => m.username == username) >= 0; + } + + hasReadPermission( + user: UserAuthInfo | null | undefined, + timeline: TTimeline + ): boolean { + if (user != null && user.administrator) return true; + + const { visibility } = timeline; + if (visibility === 'Public') { + return true; + } else if (visibility === 'Register') { + if (user != null) return true; + } else if (visibility === 'Private') { + if (user != null && this.isMemberOf(user.username, timeline)) { + return true; + } + } + return false; + } + + hasPostPermission( + user: UserAuthInfo | null | undefined, + timeline: TTimeline + ): boolean { + if (user != null && user.administrator) return true; + + return ( + user != null && + (timeline.owner.username === user.username || + this.isMemberOf(user.username, timeline)) + ); + } + + hasManagePermission( + user: UserAuthInfo | null | undefined, + timeline: TTimeline + ): boolean { + if (user != null && user.administrator) return true; + + return user != null && user.username == timeline.owner.username; + } + + hasModifyPostPermission( + user: UserAuthInfo | null | undefined, + timeline: TTimeline, + post: TimelinePostInfo + ): boolean { + if (user != null && user.administrator) return true; + + return ( + user != null && + (user.username === timeline.owner.username || + user.username === post.author.username) + ); + } +} + +export type PersonalTimelineService = TimelineServiceTemplate< + TimelineInfo, + PersonalTimelineChangePropertyRequest +>; + +export const personalTimelineService: PersonalTimelineService = new TimelineServiceTemplate< + TimelineInfo, + PersonalTimelineChangePropertyRequest +>((name) => `${apiBaseUrl}/timelines/@${name}`); + +export type OrdinaryTimelineService = TimelineServiceTemplate< + TimelineInfo, + OrdinaryTimelineChangePropertyRequest +>; + +export const ordinaryTimelineService: OrdinaryTimelineService = new TimelineServiceTemplate< + TimelineInfo, + TimelineChangePropertyRequest +>((name) => `${apiBaseUrl}/timelines/${name}`); + +const timelineNameReg = XRegExp('^[-_\\p{L}]*$', 'u'); + +export function validateTimelineName(name: string): boolean { + return timelineNameReg.test(name); +} diff --git a/Timeline/ClientApp/src/app/data/user.ts b/Timeline/ClientApp/src/app/data/user.ts new file mode 100644 index 00000000..8f787478 --- /dev/null +++ b/Timeline/ClientApp/src/app/data/user.ts @@ -0,0 +1,224 @@ +import axios, { AxiosError } from 'axios'; +import { useState, useEffect } from 'react'; +import { BehaviorSubject, Observable } from 'rxjs'; + +import { apiBaseUrl } from '../config'; +import { extractErrorCode } from './common'; +import { pushAlert } from '../common/alert-service'; +import { i18nPromise } from '../i18n'; +import { UiLogicError } from '../common'; + +export interface UserAuthInfo { + username: string; + administrator: boolean; +} + +export interface User { + username: string; + administrator: boolean; + nickname: string; + _links: { + avatar: string; + timeline: string; + }; +} + +export interface UserWithToken extends User { + token: string; +} + +interface CreateTokenRequest { + username: string; + password: string; +} + +interface CreateTokenResponse { + token: string; + user: User; +} + +interface VerifyTokenRequest { + token: string; +} + +interface VerifyTokenResponse { + user: User; +} + +export type LoginCredentials = CreateTokenRequest; + +const userSubject = new BehaviorSubject( + undefined +); + +export const user$: Observable = userSubject; + +export function getCurrentUser(): UserWithToken | null | undefined { + return userSubject.value; +} + +const kCreateTokenUrl = '/token/create'; +const kVerifyTokenUrl = '/token/verify'; +const createTokenUrl = apiBaseUrl + kCreateTokenUrl; +const verifyTokenUrl = apiBaseUrl + kVerifyTokenUrl; + +function verifyToken(token: string): Promise { + return axios + .post(verifyTokenUrl, { + token: token, + } as VerifyTokenRequest) + .then((res) => res.data.user); +} + +const TOKEN_STORAGE_KEY = 'token'; + +export function checkUserLoginState(): Promise { + if (getCurrentUser() !== undefined) + throw new UiLogicError("Already checked user. Can't check twice."); + + const savedToken = window.localStorage.getItem(TOKEN_STORAGE_KEY); + if (savedToken) { + return verifyToken(savedToken) + .then( + (u) => { + const user: UserWithToken = { + ...u, + token: savedToken, + }; + void i18nPromise.then((t) => { + pushAlert({ + type: 'success', + message: t('user.welcomeBack'), + }); + }); + return user; + }, + (e: AxiosError) => { + if (e.response != null) { + window.localStorage.removeItem(TOKEN_STORAGE_KEY); + void i18nPromise.then((t) => { + pushAlert({ + type: 'danger', + message: t('user.verifyTokenFailed'), + }); + }); + } else { + void i18nPromise.then((t) => { + pushAlert({ + type: 'danger', + message: t('user.verifyTokenFailedNetwork'), + }); + }); + } + + return null; + } + ) + .then((u) => { + userSubject.next(u); + return u; + }); + } + userSubject.next(null); + return Promise.resolve(null); +} + +export class BadCredentialError { + constructor(public innerError: Error) {} + + message = 'login.badCredential'; +} + +export function userLogin( + credentials: LoginCredentials, + rememberMe: boolean +): Promise { + if (getCurrentUser()) { + throw new UiLogicError('Already login.'); + } + return axios + .post(createTokenUrl, { ...credentials, expire: 30 }) + .catch((e: AxiosError) => { + if (extractErrorCode(e) === 11010101) { + throw new BadCredentialError(e); + } + throw e; + }) + .then((res) => { + const body = res.data; + const token = body.token; + if (rememberMe) { + window.localStorage.setItem(TOKEN_STORAGE_KEY, token); + } + const user = { + ...body.user, + token, + }; + userSubject.next(user); + return user; + }); +} + +export function userLogout(): void { + if (getCurrentUser() === undefined) { + throw new UiLogicError('Please check user first.'); + } + if (getCurrentUser() === null) { + throw new UiLogicError('No login.'); + } + window.localStorage.removeItem(TOKEN_STORAGE_KEY); + userSubject.next(null); +} + +export function useOptionalUser(): UserWithToken | null | undefined { + const [user, setUser] = useState( + userSubject.value + ); + useEffect(() => { + const sub = user$.subscribe((u) => setUser(u)); + return () => { + sub.unsubscribe(); + }; + }); + return user; +} + +export function useUser(): UserWithToken | null { + const [user, setUser] = useState(() => { + const initUser = userSubject.value; + if (initUser === undefined) { + throw new UiLogicError( + "This is a logic error in user module. Current user can't be undefined in useUser." + ); + } + return initUser; + }); + useEffect(() => { + const sub = user$.subscribe((u) => { + if (u === undefined) { + throw new UiLogicError( + "This is a logic error in user module. User emitted can't be undefined later." + ); + } + setUser(u); + }); + return () => { + sub.unsubscribe(); + }; + }); + return user; +} + +export function useUserLoggedIn(): UserWithToken { + const user = useUser(); + if (user == null) { + throw new UiLogicError('You assert user has logged in but actually not.'); + } + return user; +} + +export function fetchUser(username: string): Promise { + return axios + .get(`${apiBaseUrl}/users/${username}`) + .then((res) => res.data); +} diff --git a/Timeline/ClientApp/src/app/helper.ts b/Timeline/ClientApp/src/app/helper.ts new file mode 100644 index 00000000..b48829b5 --- /dev/null +++ b/Timeline/ClientApp/src/app/helper.ts @@ -0,0 +1,35 @@ +//copied from https://stackoverflow.com/questions/5999118/how-can-i-add-or-update-a-query-string-parameter +export function updateQueryString( + key: string, + value?: string | null, + url?: string +): string { + if (!url) url = window.location.href; + const re = new RegExp('([?&])' + key + '=.*?(&|#|$)(.*)', 'gi'); + let hash; + + if (re.test(url)) { + if (typeof value !== 'undefined' && value !== null) { + return url.replace(re, '$1' + key + '=' + value + '$2$3'); + } else { + hash = url.split('#'); + url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, ''); + if (typeof hash[1] !== 'undefined' && hash[1] !== null) { + url += '#' + hash[1]; + } + return url; + } + } else { + if (typeof value !== 'undefined' && value !== null) { + const separator = url.includes('?') ? '&' : '?'; + hash = url.split('#'); + url = hash[0] + separator + key + '=' + value; + if (typeof hash[1] !== 'undefined' && hash[1] !== null) { + url += '#' + hash[1]; + } + return url; + } else { + return url; + } + } +} diff --git a/Timeline/ClientApp/src/app/home/Home.tsx b/Timeline/ClientApp/src/app/home/Home.tsx new file mode 100644 index 00000000..775a1a87 --- /dev/null +++ b/Timeline/ClientApp/src/app/home/Home.tsx @@ -0,0 +1,155 @@ +import React from 'react'; +import { useHistory } from 'react-router'; +import { Row, Container, Button, Col } from 'reactstrap'; +import { useTranslation } from 'react-i18next'; +import axios from 'axios'; + +import { apiBaseUrl } from '../config'; +import { useUser } from '../data/user'; +import { TimelineInfo } from '../data/timeline'; + +import AppBar from '../common/AppBar'; +import SearchInput from '../common/SearchInput'; +import TimelineBoardAreaWithoutUser from './TimelineBoardAreaWithoutUser'; +import TimelineBoardAreaWithUser from './TimelineBoardAreaWithUser'; +import TimelineCreateDialog from './TimelineCreateDialog'; + +const Home: React.FC = (_) => { + const history = useHistory(); + + const { t } = useTranslation(); + + const user = useUser(); + + const [navText, setNavText] = React.useState(''); + + const [publicTimelines, setPublicTimelines] = React.useState< + TimelineInfo[] | undefined + >(undefined); + const [ownTimelines, setOwnTimelines] = React.useState< + TimelineInfo[] | undefined + >(undefined); + const [joinTimelines, setJoinTimelines] = React.useState< + TimelineInfo[] | undefined + >(undefined); + + React.useEffect(() => { + let subscribe = true; + if (user == null) { + setOwnTimelines(undefined); + setJoinTimelines(undefined); + void axios + .get(`${apiBaseUrl}/timelines?visibility=public`) + .then((res) => { + if (subscribe) { + setPublicTimelines(res.data); + } + }); + } else { + setPublicTimelines(undefined); + void axios + .get( + `${apiBaseUrl}/timelines?relate=${user.username}&relateType=own` + ) + .then((res) => { + if (subscribe) { + setOwnTimelines(res.data); + } + }); + void axios + .get( + `${apiBaseUrl}/timelines?relate=${user.username}&relateType=join` + ) + .then((res) => { + if (subscribe) { + setJoinTimelines(res.data); + } + }); + } + return () => { + subscribe = false; + }; + }, [user]); + + const [dialog, setDialog] = React.useState<'create' | null>(null); + + const goto = React.useCallback((): void => { + if (navText === '') { + history.push('users/crupest'); + } else if (navText.startsWith('@')) { + history.push(`users/${navText.slice(1)}`); + } else { + history.push(`timelines/${navText}`); + } + }, [navText, history]); + + const openCreateDialog = React.useCallback(() => { + setDialog('create'); + }, []); + + const closeDialog = React.useCallback(() => { + setDialog(null); + }, []); + + return ( + <> + + + + + + {t('home.createButton')} + + ) + } + /> + + + {(() => { + if (user == null) { + return ( + + ); + } else { + return ( + + ); + } + })()} + + + {dialog === 'create' && } + + ); +}; + +export default Home; diff --git a/Timeline/ClientApp/src/app/home/TimelineBoard.tsx b/Timeline/ClientApp/src/app/home/TimelineBoard.tsx new file mode 100644 index 00000000..ca77ab43 --- /dev/null +++ b/Timeline/ClientApp/src/app/home/TimelineBoard.tsx @@ -0,0 +1,54 @@ +import React from 'react'; +import clsx from 'clsx'; +import { Link } from 'react-router-dom'; +import { Spinner } from 'reactstrap'; + +import { TimelineInfo } from '../data/timeline'; + +import TimelineLogo from '../common/TimelineLogo'; +import UserTimelineLogo from '../common/UserTimelineLogo'; + +export interface TimelineBoardProps { + title?: string; + timelines?: TimelineInfo[]; + className?: string; +} + +const TimelineBoard: React.FC = props => { + const { title, timelines, className } = props; + + return ( +
+ {title != null &&

{title}

} + {(() => { + if (timelines == null) { + return ( +
+ +
+ ); + } else { + return timelines.map(timeline => { + const { name } = timeline; + const isPersonal = name.startsWith('@'); + const url = isPersonal + ? `/users/${timeline.owner.username}` + : `/timelines/${name}`; + return ( +
+ {isPersonal ? ( + + ) : ( + + )} + {name} +
+ ); + }); + } + })()} +
+ ); +}; + +export default TimelineBoard; diff --git a/Timeline/ClientApp/src/app/home/TimelineBoardAreaWithUser.tsx b/Timeline/ClientApp/src/app/home/TimelineBoardAreaWithUser.tsx new file mode 100644 index 00000000..ea1c6beb --- /dev/null +++ b/Timeline/ClientApp/src/app/home/TimelineBoardAreaWithUser.tsx @@ -0,0 +1,36 @@ +import React from 'react'; +import { Row, Col } from 'reactstrap'; +import { useTranslation } from 'react-i18next'; + +import TimelineBoard from './TimelineBoard'; +import { TimelineInfo } from '../data/timeline'; + +interface TimelineBoardAreaWithUserProps { + ownTimelines?: TimelineInfo[]; + joinTimelines?: TimelineInfo[]; +} + +const TimelineBoardAreaWithUser: React.FC = ( + props +) => { + const { t } = useTranslation(); + + return ( + + + + + + + + + ); +}; + +export default TimelineBoardAreaWithUser; diff --git a/Timeline/ClientApp/src/app/home/TimelineBoardAreaWithoutUser.tsx b/Timeline/ClientApp/src/app/home/TimelineBoardAreaWithoutUser.tsx new file mode 100644 index 00000000..c79558b6 --- /dev/null +++ b/Timeline/ClientApp/src/app/home/TimelineBoardAreaWithoutUser.tsx @@ -0,0 +1,26 @@ +import React from 'react'; +import { Row, Col } from 'reactstrap'; + +import { TimelineInfo } from '../data/timeline'; + +import TimelineBoard from './TimelineBoard'; + +interface TimelineBoardAreaWithoutUserProps { + publicTimelines?: TimelineInfo[]; +} + +const TimelineBoardAreaWithoutUser: React.FC = ( + props +) => { + const { publicTimelines } = props; + + return ( + + + + + + ); +}; + +export default TimelineBoardAreaWithoutUser; diff --git a/Timeline/ClientApp/src/app/home/TimelineCreateDialog.tsx b/Timeline/ClientApp/src/app/home/TimelineCreateDialog.tsx new file mode 100644 index 00000000..925c6c76 --- /dev/null +++ b/Timeline/ClientApp/src/app/home/TimelineCreateDialog.tsx @@ -0,0 +1,60 @@ +import React from 'react'; +import { useHistory } from 'react-router'; +import axios from 'axios'; + +import { apiBaseUrl } from '../config'; +import { useUserLoggedIn } from '../data/user'; +import { validateTimelineName } from '../data/timeline'; + +import OperationDialog from '../common/OperationDialog'; + +interface TimelineCreateDialogProps { + open: boolean; + close: () => void; +} + +const TimelineCreateDialog: React.FC = (props) => { + const history = useHistory(); + const user = useUserLoggedIn(); + + let nameSaved: string; + + return ( + { + if (name.length === 0) { + return 'home.createDialog.noEmpty'; + } else if (name.length > 26) { + return 'home.createDialog.tooLong'; + } else if (!validateTimelineName(name)) { + return 'home.createDialog.badFormat'; + } else { + return null; + } + }, + }, + ]} + onProcess={([name]) => { + nameSaved = name as string; + return axios.post(`${apiBaseUrl}/timelines?token=${user.token}`, { + name, + }); + }} + onSuccessAndClose={() => { + history.push(`timelines/${nameSaved}`); + }} + failurePrompt={(e) => `${e as string}`} + /> + ); +}; + +export default TimelineCreateDialog; diff --git a/Timeline/ClientApp/src/app/home/home.sass b/Timeline/ClientApp/src/app/home/home.sass new file mode 100644 index 00000000..f5d6ffc3 --- /dev/null +++ b/Timeline/ClientApp/src/app/home/home.sass @@ -0,0 +1,13 @@ +.timeline-board-item + font-size: 1.1em + @extend .my-2 + .icon + height: 1.3em + @extend .mr-2 + +.timeline-board + @extend .cru-card + @extend .d-flex + @extend .flex-column + @extend .p-3 + min-height: 200px diff --git a/Timeline/ClientApp/src/app/i18n.ts b/Timeline/ClientApp/src/app/i18n.ts new file mode 100644 index 00000000..bda33fe8 --- /dev/null +++ b/Timeline/ClientApp/src/app/i18n.ts @@ -0,0 +1,79 @@ +import i18n, { BackendModule, ResourceKey } from 'i18next'; +import LanguageDetector from 'i18next-browser-languagedetector'; +import { initReactI18next } from 'react-i18next'; + +const backend: BackendModule = { + type: 'backend', + async read(language, namespace, callback) { + function error(message: string): void { + callback(new Error(message), false); + } + + function success(result: ResourceKey): void { + callback(null, result); + } + + if (namespace !== 'translation') { + error("Namespace must be 'translation'."); + } + + if (language === 'en') { + const res = ( + await import( + /* webpackChunkName: "locales-en" */ './locales/en/translation' + ) + ).default; + success(res); + } else if (language === 'zh-cn' || language === 'zh') { + const res = ( + await import( + /* webpackChunkName: "locales-zh" */ './locales/zh/translation' + ) + ).default; + success(res); + } else { + error(`Language ${language} is not supported.`); + } + }, + init() {}, // eslint-disable-line @typescript-eslint/no-empty-function + create() {}, // eslint-disable-line @typescript-eslint/no-empty-function +}; + +export const i18nPromise = i18n + .use(LanguageDetector) + .use(backend) + .use(initReactI18next) // bind react-i18next to the instance + .init({ + fallbackLng: false, + lowerCaseLng: true, + + debug: process.env.NODE_ENV === 'development', + + interpolation: { + escapeValue: false, // not needed for react!! + }, + + // react i18next special options (optional) + // override if needed - omit if ok with defaults + /* + react: { + bindI18n: 'languageChanged', + bindI18nStore: '', + transEmptyNodeValue: '', + transSupportBasicHtmlNodes: true, + transKeepBasicHtmlNodesFor: ['br', 'strong', 'i'], + useSuspense: true, + } + */ + }); + +if (module.hot) { + module.hot.accept( + ['./locales/en/translation', './locales/zh/translation'], + () => { + void i18n.reloadResources(); + } + ); +} + +export default i18n; diff --git a/Timeline/ClientApp/src/app/index.sass b/Timeline/ClientApp/src/app/index.sass new file mode 100644 index 00000000..86276701 --- /dev/null +++ b/Timeline/ClientApp/src/app/index.sass @@ -0,0 +1,86 @@ +@import '~bootstrap/scss/bootstrap' +$fa-font-path: '~@fortawesome/fontawesome-free/webfonts' +@import '~@fortawesome/fontawesome-free/scss/fontawesome' +@import '~@fortawesome/fontawesome-free/scss/solid' +@import '~@fortawesome/fontawesome-free/scss/brands' + +@import './common/common' +@import './common/alert' +@import './home/home' +@import './about/about' +@import './timeline/timeline' +@import './timeline/timeline-ui' +@import './user/user-page' + +body + margin: 0 + +#app + display: flex + flex-direction: column + +small + line-height: 1.2 + +.width-1px + width: 1px + +.flex-fix-length + flex-grow: 0 + flex-shrink: 0 + +.position-lt + left: 0 + top: 0 + +.position-rb + right: 0 + bottom: 0 + +.app-bar + z-index: 1035 + +.avatar + width: 60px + +.avatar.large + width: 100px + +.avatar.small + width: 40px + +.mt-appbar + margin-top: 56px + +.icon-button + font-size: 20px + +.large-icon + font-size: 26px + +.cursor-pointer + cursor: pointer + +textarea + resize: none + +.white-space-no-wrap + white-space: nowrap + +.cru-card + @extend .shadow + @extend .border + @extend .border-primary + @extend .rounded + @extend .bg-light + +.full-viewport-center-child + position: fixed + width: 100vw + height: 100vh + display: flex + justify-content: center + align-items: center + +.text-orange + color: $orange diff --git a/Timeline/ClientApp/src/app/index.tsx b/Timeline/ClientApp/src/app/index.tsx new file mode 100644 index 00000000..73788c3a --- /dev/null +++ b/Timeline/ClientApp/src/app/index.tsx @@ -0,0 +1,22 @@ +import 'regenerator-runtime'; +import 'core-js/modules/es.promise'; +import 'core-js/modules/es.array.iterator'; +import 'pepjs'; + +import React from 'react'; +import ReactDOM from 'react-dom'; + +import './index.sass'; + +import './i18n'; + +import App from './App'; + +ReactDOM.render(, document.getElementById('app')); + +if ('serviceWorker' in navigator) { + // Use the window load event to keep the page load performant + window.addEventListener('load', () => { + void navigator.serviceWorker.register('/sw.js'); + }); +} diff --git a/Timeline/ClientApp/src/app/locales/en/translation.ts b/Timeline/ClientApp/src/app/locales/en/translation.ts new file mode 100644 index 00000000..00672f67 --- /dev/null +++ b/Timeline/ClientApp/src/app/locales/en/translation.ts @@ -0,0 +1,183 @@ +import TranslationResource from '../scheme'; + +const translation: TranslationResource = { + welcome: 'Welcome!', + search: 'Search', + nav: { + settings: 'Settings', + login: 'Login', + about: 'About', + }, + chooseImage: 'Choose a image', + loadImageError: 'Failed to load image.', + home: { + go: 'Go!', + allTimeline: 'All Timelines', + joinTimeline: 'Joined Timelines', + ownTimeline: 'Owned Timelines', + createButton: 'Create Timeline', + createDialog: { + title: 'Create Timeline!', + name: 'Name', + nameFormat: + 'Name must consist of only letter including non-English letter, digit, hyphen(-) and underline(_) and be no longer than 26.', + badFormat: 'Bad format.', + noEmpty: 'Empty is not allowed.', + tooLong: 'Too long.', + }, + }, + operationDialog: { + retry: 'Retry', + nextStep: 'Next', + previousStep: 'Previous', + confirm: 'Confirm', + cancel: 'Cancel', + ok: 'OK!', + processing: 'Processing...', + success: 'Success!', + error: 'An error occured.', + }, + timeline: { + messageCantSee: 'Sorry, you are not allowed to see this timeline.😅', + userNotExist: 'The user does not exist!', + timelineNotExist: 'The timeline does not exist!', + manage: 'Manage', + memberButton: 'Member', + send: 'Send', + deletePostFailed: 'Failed to delete post.', + sendPostFailed: 'Failed to send post.', + visibility: { + public: 'public to everyone', + register: 'only registed people can see', + private: 'only members can see', + }, + visibilityTooltip: { + public: + 'Everyone including those without accounts can see content of the timeline.', + register: + 'Only those who have an account and logined can see content of the timeline.', + private: 'Only members of this timeline can see content of the timeline.', + }, + dialogChangeProperty: { + title: 'Change Timeline Properties', + visibility: 'Visibility', + description: 'Description', + }, + member: { + alreadyMember: 'The user is already a member.', + add: 'Add', + remove: 'Remove', + }, + manageItem: { + nickname: 'Nickname', + avatar: 'Avatar', + property: 'Timeline Property', + member: 'Timeline Member', + delete: 'Delete Timeline', + }, + deleteDialog: { + title: 'Delete Timeline', + inputPrompt: + 'This is a dangerous action. If you are sure to delete timeline<1>{{name}}, please input its name below and click confirm button.', + notMatch: 'Name does not match.', + }, + post: { + deleteDialog: { + title: 'Confirm Delete', + prompt: + 'Are you sure to delete the post? This operation is not recoverable.', + }, + }, + }, + user: { + username: 'username', + password: 'password', + login: 'login', + rememberMe: 'Remember Me', + welcomeBack: 'Welcome back!', + verifyTokenFailed: 'User login info is expired. Please login again!', + verifyTokenFailedNetwork: + 'Verifying user login info failed. Please check your network and refresh page!', + }, + login: { + emptyUsername: "Username can't be empty.", + emptyPassword: "Password can't be empty.", + badCredential: 'Username or password is invalid.', + alreadyLogin: 'Already login! Redirect to home page in 3s!', + }, + userPage: { + dialogChangeNickname: { + title: 'Change Nickname', + inputLabel: 'New nickname', + }, + dialogChangeAvatar: { + title: 'Change Avatar', + previewImgAlt: 'preview', + prompt: { + select: 'Please select a picture.', + crop: 'Please crop the picture.', + processingCrop: 'Cropping picture...', + uploading: 'Uploading...', + preview: 'Please preview avatar', + }, + upload: 'upload', + }, + }, + settings: { + subheaders: { + account: 'Account', + customization: 'Customization', + }, + languagePrimary: 'Choose display language.', + languageSecondary: + 'You language preference will be saved locally. Next time you visit this page, last language option will be used.', + changePassword: "Change account's password.", + logout: 'Log out this account.', + gotoSelf: + 'Click here to go to timeline of myself to change nickname and avatar.', + dialogChangePassword: { + title: 'Change Password', + prompt: + 'You are changing your password. You need to input the correct old password. After change, you need to login again and all old login will be invalid.', + inputOldPassword: 'Old password', + inputNewPassword: 'New password', + inputRetypeNewPassword: 'Retype new password', + errorEmptyOldPassword: "Old password can't be empty.", + errorEmptyNewPassword: "New password can't be empty.", + errorRetypeNotMatch: 'Password retyped does not match.', + }, + dialogConfirmLogout: { + title: 'Confirm Logout', + prompt: + 'Are you sure to log out? All cached data in the browser will be deleted.', + }, + }, + about: { + author: { + title: 'Site Developer', + fullname: 'Fullname: ', + nickname: 'Nickname: ', + introduction: 'Introduction: ', + introductionContent: 'A programmer coding based on coincidence', + links: 'Links: ', + }, + site: { + title: 'Site Information', + content: + 'The name of this site is <1>Timeline, which is a Web App with <3>timeline as its core concept. Its frontend and backend are both developed by <5>me, and open source on GitHub. It is relatively easy to deploy it on your own server, which is also one of my goals. Welcome to comment anything in GitHub repository.', + repo: 'GitHub Repo', + }, + credits: { + title: 'Credits', + content: + 'Timeline is works standing on shoulders of gaints. Special appreciation for many open source projects listed below or not. Related licenses could be found in GitHub repository.', + frontend: 'Frontend: ', + backend: 'Backend: ', + }, + }, + admin: { + title: 'admin', + }, +}; + +export default translation; diff --git a/Timeline/ClientApp/src/app/locales/scheme.ts b/Timeline/ClientApp/src/app/locales/scheme.ts new file mode 100644 index 00000000..bb3f14df --- /dev/null +++ b/Timeline/ClientApp/src/app/locales/scheme.ts @@ -0,0 +1,167 @@ +export default interface TranslationResource { + welcome: string; + search: string; + chooseImage: string; + loadImageError: string; + nav: { + settings: string; + login: string; + about: string; + }; + home: { + go: string; + allTimeline: string; + joinTimeline: string; + ownTimeline: string; + createButton: string; + createDialog: { + title: string; + name: string; + nameFormat: string; + badFormat: string; + noEmpty: string; + tooLong: string; + }; + }; + operationDialog: { + retry: string; + nextStep: string; + previousStep: string; + confirm: string; + cancel: string; + ok: string; + processing: string; + success: string; + error: string; + }; + timeline: { + messageCantSee: string; + userNotExist: string; + timelineNotExist: string; + manage: string; + memberButton: string; + send: string; + deletePostFailed: string; + sendPostFailed: string; + visibility: { + public: string; + register: string; + private: string; + }; + visibilityTooltip: { + public: string; + register: string; + private: string; + }; + dialogChangeProperty: { + title: string; + visibility: string; + description: string; + }; + member: { + alreadyMember: string; + add: string; + remove: string; + }; + manageItem: { + nickname: string; + avatar: string; + property: string; + member: string; + delete: string; + }; + deleteDialog: { + title: string; + inputPrompt: string; + notMatch: string; + }; + post: { + deleteDialog: { + title: string; + prompt: string; + }; + }; + }; + user: { + username: string; + password: string; + login: string; + rememberMe: string; + welcomeBack: string; + verifyTokenFailed: string; + verifyTokenFailedNetwork: string; + }; + login: { + emptyUsername: string; + emptyPassword: string; + badCredential: string; + alreadyLogin: string; + }; + userPage: { + dialogChangeNickname: { + title: string; + inputLabel: string; + }; + dialogChangeAvatar: { + title: string; + previewImgAlt: string; + prompt: { + select: string; + crop: string; + processingCrop: string; + preview: string; + uploading: string; + }; + upload: string; + }; + }; + settings: { + subheaders: { + account: string; + customization: string; + }; + languagePrimary: string; + languageSecondary: string; + changePassword: string; + logout: string; + gotoSelf: string; + dialogChangePassword: { + title: string; + prompt: string; + inputOldPassword: string; + inputNewPassword: string; + inputRetypeNewPassword: string; + errorEmptyOldPassword: string; + errorEmptyNewPassword: string; + errorRetypeNotMatch: string; + }; + dialogConfirmLogout: { + title: string; + prompt: string; + }; + }; + about: { + author: { + title: string; + fullname: string; + nickname: string; + introduction: string; + introductionContent: string; + links: string; + }; + site: { + title: string; + content: string; + repo: string; + }; + credits: { + title: string; + content: string; + frontend: string; + backend: string; + }; + }; + admin: { + title: string; + }; +} diff --git a/Timeline/ClientApp/src/app/locales/zh/translation.ts b/Timeline/ClientApp/src/app/locales/zh/translation.ts new file mode 100644 index 00000000..66421375 --- /dev/null +++ b/Timeline/ClientApp/src/app/locales/zh/translation.ts @@ -0,0 +1,178 @@ +import TranslationResource from '../scheme'; + +const translation: TranslationResource = { + welcome: '欢迎!', + search: '搜索', + nav: { + settings: '设置', + login: '登陆', + about: '关于', + }, + chooseImage: '选择一个图片', + loadImageError: '加载图片失败', + home: { + go: '冲!', + allTimeline: '所有的时间线', + joinTimeline: '加入的时间线', + ownTimeline: '拥有的时间线', + createButton: '创建时间线', + createDialog: { + title: '创建时间线!', + name: '名字', + nameFormat: + '名字只能由字母、汉字、数字、下划线(_)和连字符(-)构成,且长度不能超过26.', + badFormat: '格式错误', + noEmpty: '不能为空', + tooLong: '太长了', + }, + }, + operationDialog: { + retry: '重试', + nextStep: '下一步', + previousStep: '上一步', + confirm: '确定', + cancel: '取消', + ok: '好的!', + processing: '处理中...', + success: '成功!', + error: '出错啦!', + }, + timeline: { + messageCantSee: '不好意思,你没有权限查看这个时间线。😅', + userNotExist: '该用户不存在!', + timelineNotExist: '该时间线不存在!', + manage: '管理', + memberButton: '成员', + send: '发送', + deletePostFailed: '删除消息失败。', + sendPostFailed: '发送消息失败。', + visibility: { + public: '对所有人公开', + register: '仅注册可见', + private: '仅成员可见', + }, + visibilityTooltip: { + public: '所有人都可以看到这个时间线的内容,包括没有注册的人。', + register: '只有拥有本网站的账号且登陆了的人才能看到这个时间线的内容。', + private: '只有这个时间线的成员可以看到这个时间线的内容。', + }, + dialogChangeProperty: { + title: '修改时间线属性', + visibility: '可见性', + description: '描述', + }, + member: { + alreadyMember: '该用户已经是一个成员。', + add: '添加', + remove: '移除', + }, + manageItem: { + nickname: '昵称', + avatar: '头像', + property: '时间线属性', + member: '时间线成员', + delete: '删除时间线', + }, + deleteDialog: { + title: '删除时间线', + inputPrompt: + '这是一个危险的操作。如果您确认要删除时间线<1>{{name}},请在下面输入它的名字并点击确认。', + notMatch: '名字不匹配', + }, + post: { + deleteDialog: { + title: '确认删除', + prompt: '确定删除这个消息?这个操作不可撤销。', + }, + }, + }, + user: { + username: '用户名', + password: '密码', + login: '登录', + rememberMe: '记住我', + welcomeBack: '欢迎回来!', + verifyTokenFailed: '用户登录信息已过期,请重新登陆!', + verifyTokenFailedNetwork: + '验证用户登录信息失败,请检查网络连接并刷新页面!', + }, + login: { + emptyUsername: '用户名不能为空。', + emptyPassword: '密码不能为空。', + badCredential: '用户名或密码错误。', + alreadyLogin: '已经登陆,三秒后导航到首页!', + }, + userPage: { + dialogChangeNickname: { + title: '更改昵称', + inputLabel: '新昵称', + }, + dialogChangeAvatar: { + title: '修改头像', + previewImgAlt: '预览', + prompt: { + select: '请选择一个图片', + crop: '请裁剪图片', + processingCrop: '正在裁剪图片', + uploading: '正在上传', + preview: '请预览图片', + }, + upload: '上传', + }, + }, + settings: { + subheaders: { + account: '账户', + customization: '个性化', + }, + languagePrimary: '选择显示的语言。', + languageSecondary: + '您的语言偏好将会存储在本地,下次浏览时将自动使用上次保存的语言选项。', + changePassword: '更改账号的密码。', + logout: '注销此账号。', + gotoSelf: '点击前往个人时间线修改昵称和头像!', + dialogChangePassword: { + title: '修改密码', + prompt: + '您正在修改密码,您需要输入正确的旧密码。成功修改后您需要重新登陆,而且以前所有的登录都会失效。', + inputOldPassword: '旧密码', + inputNewPassword: '新密码', + inputRetypeNewPassword: '再次输入新密码', + errorEmptyOldPassword: '旧密码不能为空。', + errorEmptyNewPassword: '新密码不能为空', + errorRetypeNotMatch: '两次输入的密码不一致', + }, + dialogConfirmLogout: { + title: '确定注销', + prompt: '您确定注销此账号?这将删除所有已经缓存在浏览器的数据。', + }, + }, + about: { + author: { + title: '网站作者', + fullname: '姓名:', + nickname: '昵称:', + introduction: '简介:', + introductionContent: '一个基于巧合编程的代码爱好者。', + links: '链接:', + }, + site: { + title: '网站信息', + content: + '这个网站的名字叫 <1>Timeline,是一个以<3>时间线为核心概念的 Web App . 它的前端和后端都是由<5>我开发,并且在 GitHub 上开源。大家可以相对轻松的把它们部署在自己的服务器上,这也是我的目标之一。欢迎大家前往 GitHub 仓库提出任何意见。', + repo: 'GitHub 仓库', + }, + credits: { + title: '鸣谢', + content: + 'Timeline 是站在巨人肩膀上的作品,感谢以下列出的和其他未列出的许多开源项目,相关 License 请在 GitHub 仓库中查看。', + frontend: '前端:', + backend: '后端:', + }, + }, + admin: { + title: '管理', + }, +}; + +export default translation; diff --git a/Timeline/ClientApp/src/app/settings/Settings.tsx b/Timeline/ClientApp/src/app/settings/Settings.tsx new file mode 100644 index 00000000..96a3fab4 --- /dev/null +++ b/Timeline/ClientApp/src/app/settings/Settings.tsx @@ -0,0 +1,253 @@ +import React, { useState } from 'react'; +import { useHistory } from 'react-router'; +import { useTranslation } from 'react-i18next'; +import axios, { AxiosError } from 'axios'; +import { + Container, + Row, + Col, + Input, + Modal, + ModalHeader, + ModalBody, + ModalFooter, + Button, +} from 'reactstrap'; + +import { apiBaseUrl } from '../config'; + +import { useUser, userLogout, useUserLoggedIn } from '../data/user'; + +import AppBar from '../common/AppBar'; +import OperationDialog, { + OperationInputErrorInfo, +} from '../common/OperationDialog'; +import { CommonErrorResponse } from '../data/common'; + +interface ChangePasswordDialogProps { + open: boolean; + close: () => void; +} + +async function changePassword( + oldPassword: string, + newPassword: string, + token: string +): Promise { + const url = `${apiBaseUrl}/userop/changepassword?token=${token}`; + try { + await axios.post(url, { + oldPassword, + newPassword, + }); + } catch (e) { + const error = e as AxiosError; + if ( + error.response && + error.response.status === 400 && + error.response.data && + error.response.data.message + ) { + throw error.response.data.message; + } + throw e; + } +} + +const ChangePasswordDialog: React.FC = (props) => { + const user = useUserLoggedIn(); + const history = useHistory(); + const { t } = useTranslation(); + + const [redirect, setRedirect] = useState(false); + + return ( + + v === '' + ? 'settings.dialogChangePassword.errorEmptyOldPassword' + : null, + }, + { + type: 'text', + label: t('settings.dialogChangePassword.inputNewPassword'), + password: true, + validator: (v, values) => { + const error: OperationInputErrorInfo = {}; + error[1] = + v === '' + ? 'settings.dialogChangePassword.errorEmptyNewPassword' + : null; + if (v === values[2]) { + error[2] = null; + } else { + if (values[2] !== '') { + error[2] = 'settings.dialogChangePassword.errorRetypeNotMatch'; + } + } + return error; + }, + }, + { + type: 'text', + label: t('settings.dialogChangePassword.inputRetypeNewPassword'), + password: true, + validator: (v, values) => + v !== values[1] + ? 'settings.dialogChangePassword.errorRetypeNotMatch' + : null, + }, + ]} + onProcess={async ([oldPassword, newPassword]) => { + await changePassword( + oldPassword as string, + newPassword as string, + user.token + ); + userLogout(); + setRedirect(true); + }} + close={() => { + props.close(); + if (redirect) { + history.push('/login'); + } + }} + /> + ); +}; + +const ConfirmLogoutDialog: React.FC<{ + toggle: () => void; + onConfirm: () => void; +}> = ({ toggle, onConfirm }) => { + const { t } = useTranslation(); + + return ( + + + {t('settings.dialogConfirmLogout.title')} + + {t('settings.dialogConfirmLogout.prompt')} + + + + + + ); +}; + +const Settings: React.FC = (_) => { + const { i18n, t } = useTranslation(); + const user = useUser(); + const history = useHistory(); + + const [dialog, setDialog] = useState( + null + ); + + const language = i18n.language.slice(0, 2); + + return ( + <> + + + {user ? ( + <> + + +
{ + history.push(`/users/${user.username}`); + }} + > + {t('settings.gotoSelf')} +
+ +
+ + +
setDialog('changepassword')} + > + {t('settings.changePassword')} +
+ +
+ + +
{ + setDialog('logout'); + }} + > + {t('settings.logout')} +
+ +
+ + ) : null} + + +
{t('settings.languagePrimary')}
+

{t('settings.languageSecondary')}

+ + + { + void i18n.changeLanguage(e.target.value); + }} + > + + + + +
+ {(() => { + switch (dialog) { + case 'changepassword': + return ( + { + setDialog(null); + }} + /> + ); + case 'logout': + return ( + setDialog(null)} + onConfirm={() => { + userLogout(); + history.push('/'); + }} + /> + ); + default: + return null; + } + })()} +
+ + ); +}; + +export default Settings; diff --git a/Timeline/ClientApp/src/app/timeline/Timeline.tsx b/Timeline/ClientApp/src/app/timeline/Timeline.tsx new file mode 100644 index 00000000..35d6490b --- /dev/null +++ b/Timeline/ClientApp/src/app/timeline/Timeline.tsx @@ -0,0 +1,99 @@ +import React from 'react'; +import clsx from 'clsx'; +import { Container } from 'reactstrap'; + +import { TimelinePostInfo } from '../data/timeline'; +import { useUser } from '../data/user'; +import { useAvatarVersion } from '../user/api'; + +import TimelineItem from './TimelineItem'; + +export interface TimelinePostInfoEx extends TimelinePostInfo { + deletable: boolean; +} + +export type TimelineDeleteCallback = (index: number, id: number) => void; + +export interface TimelineProps { + className?: string; + posts: TimelinePostInfoEx[]; + onDelete: TimelineDeleteCallback; + onResize?: () => void; +} + +const Timeline: React.FC = (props) => { + const user = useUser(); + const avatarVersion = useAvatarVersion(); + + const { posts, onDelete, onResize } = props; + + const [indexShowDeleteButton, setIndexShowDeleteButton] = React.useState< + number + >(-1); + + const onItemClick = React.useCallback(() => { + setIndexShowDeleteButton(-1); + }, []); + + const onToggleDelete = React.useMemo(() => { + return posts.map((post, i) => { + return post.deletable + ? () => { + setIndexShowDeleteButton((oldIndexShowDeleteButton) => { + return oldIndexShowDeleteButton !== i ? i : -1; + }); + } + : undefined; + }); + }, [posts]); + + const onItemDelete = React.useMemo(() => { + return posts.map((post, i) => { + return () => { + onDelete(i, post.id); + }; + }); + }, [posts, onDelete]); + + return ( + +
+ {(() => { + const length = posts.length; + return posts.map((post, i) => { + const av: number | undefined = + user != null && user.username === post.author.username + ? avatarVersion + : undefined; + + const toggleMore = onToggleDelete[i]; + + return ( + + ); + }); + })()} + + ); +}; + +export default Timeline; diff --git a/Timeline/ClientApp/src/app/timeline/TimelineDeleteDialog.tsx b/Timeline/ClientApp/src/app/timeline/TimelineDeleteDialog.tsx new file mode 100644 index 00000000..5e7c6dd4 --- /dev/null +++ b/Timeline/ClientApp/src/app/timeline/TimelineDeleteDialog.tsx @@ -0,0 +1,59 @@ +import React from 'react'; +import axios from 'axios'; +import { useHistory } from 'react-router'; +import { Trans } from 'react-i18next'; + +import { apiBaseUrl } from '../config'; +import { useUserLoggedIn } from '../data/user'; +import OperationDialog from '../common/OperationDialog'; + +interface TimelineDeleteDialog { + open: boolean; + name: string; + close: () => void; +} + +const TimelineDeleteDialog: React.FC = (props) => { + const user = useUserLoggedIn(); + const history = useHistory(); + + const { name } = props; + + return ( + { + return ( + + 0{{ name }}2 + + ); + }} + inputScheme={[ + { + type: 'text', + validator: (value) => { + if (value !== name) { + return 'timeline.deleteDialog.notMatch'; + } else { + return null; + } + }, + }, + ]} + onProcess={() => { + return axios.delete( + `${apiBaseUrl}/timelines/${name}?token=${user.token}` + ); + }} + onSuccessAndClose={() => { + history.replace('/'); + }} + /> + ); +}; + +export default TimelineDeleteDialog; diff --git a/Timeline/ClientApp/src/app/timeline/TimelineInfoCard.tsx b/Timeline/ClientApp/src/app/timeline/TimelineInfoCard.tsx new file mode 100644 index 00000000..e4bc07d1 --- /dev/null +++ b/Timeline/ClientApp/src/app/timeline/TimelineInfoCard.tsx @@ -0,0 +1,109 @@ +import React from 'react'; +import clsx from 'clsx'; +import { + Dropdown, + DropdownToggle, + DropdownMenu, + DropdownItem, + Button, +} from 'reactstrap'; +import { useTranslation } from 'react-i18next'; +import { fromEvent } from 'rxjs'; + +import { + timelineVisibilityTooltipTranslationMap, + TimelineInfo, +} from '../data/timeline'; +import { TimelineCardComponentProps } from './TimelinePageTemplateUI'; + +export type OrdinaryTimelineManageItem = 'delete'; + +export type TimelineInfoCardProps = TimelineCardComponentProps< + TimelineInfo, + OrdinaryTimelineManageItem +>; + +const TimelineInfoCard: React.FC = (props) => { + const { onHeight, onManage } = props; + + const { t } = useTranslation(); + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const containerRef = React.useRef(null!); + + const notifyHeight = React.useCallback((): void => { + if (onHeight) { + onHeight(containerRef.current.getBoundingClientRect().height); + } + }, [onHeight]); + + React.useEffect(() => { + const subscription = fromEvent(window, 'resize').subscribe(notifyHeight); + return () => subscription.unsubscribe(); + }); + + const [manageDropdownOpen, setManageDropdownOpen] = React.useState( + false + ); + const toggleManageDropdown = React.useCallback( + (): void => setManageDropdownOpen((old) => !old), + [] + ); + + return ( +
+

+ {props.timeline.name} +

+
+ + {props.timeline.owner.nickname} + + @{props.timeline.owner.username} + +
+

{props.timeline.description}

+ + {t(timelineVisibilityTooltipTranslationMap[props.timeline.visibility])} + +
+ {onManage != null ? ( + + + {t('timeline.manage')} + + + onManage('property')}> + {t('timeline.manageItem.property')} + + + {t('timeline.manageItem.member')} + + + onManage('delete')} + > + {t('timeline.manageItem.delete')} + + + + ) : ( + + )} +
+
+ ); +}; + +export default TimelineInfoCard; diff --git a/Timeline/ClientApp/src/app/timeline/TimelineItem.tsx b/Timeline/ClientApp/src/app/timeline/TimelineItem.tsx new file mode 100644 index 00000000..4737fd7d --- /dev/null +++ b/Timeline/ClientApp/src/app/timeline/TimelineItem.tsx @@ -0,0 +1,175 @@ +import React from 'react'; +import clsx from 'clsx'; +import { + Row, + Col, + Modal, + ModalHeader, + ModalBody, + ModalFooter, + Button, +} from 'reactstrap'; +import { Link } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; + +import { TimelinePostInfo } from '../data/timeline'; +import { useAvatarUrlWithGivenVersion } from '../user/api'; + +const TimelinePostDeleteConfirmDialog: React.FC<{ + toggle: () => void; + onConfirm: () => void; +}> = ({ toggle, onConfirm }) => { + const { t } = useTranslation(); + + return ( + + + {t('timeline.post.deleteDialog.title')} + + {t('timeline.post.deleteDialog.prompt')} + + + + + + ); +}; + +export interface TimelineItemProps { + post: TimelinePostInfo; + current?: boolean; + more?: { + isOpen: boolean; + toggle: () => void; + onDelete: () => void; + }; + onClick?: () => void; + avatarVersion?: number; + onResize?: () => void; + className?: string; + style?: React.CSSProperties; +} + +const TimelineItem: React.FC = (props) => { + const { i18n } = useTranslation(); + + const current = props.current === true; + + const { more, onResize } = props; + + const avatarUrl = useAvatarUrlWithGivenVersion( + props.avatarVersion, + props.post.author._links.avatar + ); + + const [deleteDialog, setDeleteDialog] = React.useState(false); + const toggleDeleteDialog = React.useCallback( + () => setDeleteDialog((old) => !old), + [] + ); + + return ( + + +
+
+
+
+
+ {current &&
} + + + +
+ + + {props.post.time.toLocaleString(i18n.languages)} + + + {props.post.author.nickname} + + +
+ {more != null ? ( +
+ { + more.toggle(); + e.stopPropagation(); + }} + /> +
+ ) : null} +
+

+ + + + {(() => { + const { content } = props.post; + if (content.type === 'text') { + return content.text; + } else { + return ( + + ); + } + })()} +

+ + {more != null && more.isOpen ? ( + <> +
+ { + toggleDeleteDialog(); + e.stopPropagation(); + }} + /> +
+ {deleteDialog ? ( + { + toggleDeleteDialog(); + more.toggle(); + }} + onConfirm={more.onDelete} + /> + ) : null} + + ) : null} + + ); +}; + +export default TimelineItem; diff --git a/Timeline/ClientApp/src/app/timeline/TimelineMember.tsx b/Timeline/ClientApp/src/app/timeline/TimelineMember.tsx new file mode 100644 index 00000000..f9747b4d --- /dev/null +++ b/Timeline/ClientApp/src/app/timeline/TimelineMember.tsx @@ -0,0 +1,196 @@ +import React, { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { User } from '../data/user'; + +import SearchInput from '../common/SearchInput'; +import { + Container, + ListGroup, + ListGroupItem, + Modal, + Row, + Col, + Button, +} from 'reactstrap'; + +export interface TimelineMemberCallbacks { + onCheckUser: (username: string) => Promise; + onAddUser: (user: User) => Promise; + onRemoveUser: (username: string) => void; +} + +export interface TimelineMemberProps { + members: User[]; + edit: TimelineMemberCallbacks | null | undefined; +} + +const TimelineMember: React.FC = (props) => { + const { t } = useTranslation(); + + const [userSearchText, setUserSearchText] = useState(''); + const [userSearchState, setUserSearchState] = useState< + | { + type: 'user'; + data: User; + } + | { type: 'error'; data: string } + | { type: 'loading' } + | { type: 'init' } + >({ type: 'init' }); + + const members = props.members; + + return ( + + + {members.map((member, index) => ( + + + + + + + {member.nickname} + + {'@' + member.username} + + + {(() => { + if (index === 0) { + return null; + } + const onRemove = props.edit?.onRemoveUser; + if (onRemove == null) { + return null; + } + return ( + + ); + })()} + + + ))} + + {(() => { + const edit = props.edit; + if (edit != null) { + return ( + <> + { + setUserSearchText(v); + }} + loading={userSearchState.type === 'loading'} + onButtonClick={() => { + if (userSearchText === '') { + setUserSearchState({ + type: 'error', + data: 'login.emptyUsername', + }); + return; + } + + setUserSearchState({ type: 'loading' }); + edit.onCheckUser(userSearchText).then( + (u) => { + if (u == null) { + setUserSearchState({ + type: 'error', + data: 'timeline.userNotExist', + }); + } else { + setUserSearchState({ type: 'user', data: u }); + } + }, + (e) => { + setUserSearchState({ + type: 'error', + data: `${e as string}`, + }); + } + ); + }} + /> + {(() => { + if (userSearchState.type === 'user') { + const u = userSearchState.data; + const addable = + members.findIndex((m) => m.username === u.username) === -1; + return ( + <> + {!addable ? ( +

{t('timeline.member.alreadyMember')}

+ ) : null} + + + + + + + {u.nickname} + + {'@' + u.username} + + + + + + + ); + } else if (userSearchState.type === 'error') { + return ( +

{t(userSearchState.data)}

+ ); + } + })()} + + ); + } else { + return null; + } + })()} +
+ ); +}; + +export default TimelineMember; + +export interface TimelineMemberDialogProps extends TimelineMemberProps { + open: boolean; + onClose: () => void; +} + +export const TimelineMemberDialog: React.FC = ( + props +) => { + return ( + + + + ); +}; diff --git a/Timeline/ClientApp/src/app/timeline/TimelinePage.tsx b/Timeline/ClientApp/src/app/timeline/TimelinePage.tsx new file mode 100644 index 00000000..900d6e6a --- /dev/null +++ b/Timeline/ClientApp/src/app/timeline/TimelinePage.tsx @@ -0,0 +1,39 @@ +import React from 'react'; +import { useParams } from 'react-router'; + +import { ordinaryTimelineService } from '../data/timeline'; + +import TimelinePageUI from './TimelinePageUI'; +import TimelinePageTemplate from '../timeline/TimelinePageTemplate'; +import { OrdinaryTimelineManageItem } from './TimelineInfoCard'; +import TimelineDeleteDialog from './TimelineDeleteDialog'; + +const TimelinePage: React.FC = _ => { + const { name } = useParams<{ name: string }>(); + + const [dialog, setDialog] = React.useState( + null + ); + + let dialogElement: React.ReactElement | undefined; + if (dialog === 'delete') { + dialogElement = ( + setDialog(null)} name={name} /> + ); + } + + return ( + <> + setDialog(item)} + service={ordinaryTimelineService} + notFoundI18nKey="timeline.timelineNotExist" + /> + {dialogElement} + + ); +}; + +export default TimelinePage; diff --git a/Timeline/ClientApp/src/app/timeline/TimelinePageTemplate.tsx b/Timeline/ClientApp/src/app/timeline/TimelinePageTemplate.tsx new file mode 100644 index 00000000..38ecd8f9 --- /dev/null +++ b/Timeline/ClientApp/src/app/timeline/TimelinePageTemplate.tsx @@ -0,0 +1,275 @@ +import React from 'react'; +import { useTranslation } from 'react-i18next'; +import { AxiosError } from 'axios'; +import concat from 'lodash/concat'; +import without from 'lodash/without'; + +import { ExcludeKey } from '../type-utilities'; +import { useUser, fetchUser } from '../data/user'; +import { pushAlert } from '../common/alert-service'; +import { extractStatusCode, extractErrorCode } from '../data/common'; +import { + TimelineServiceTemplate, + TimelineInfo, + TimelineChangePropertyRequest, +} from '../data/timeline'; + +import { TimelinePostInfoEx, TimelineDeleteCallback } from './Timeline'; +import { TimelineMemberDialog } from './TimelineMember'; +import TimelinePropertyChangeDialog from './TimelinePropertyChangeDialog'; +import { TimelinePageTemplateUIProps } from './TimelinePageTemplateUI'; +import { TimelinePostSendCallback } from './TimelinePostEdit'; +import { UiLogicError } from '../common'; + +export interface TimelinePageTemplateProps< + TManageItem, + TTimeline extends TimelineInfo +> { + name: string; + onManage: (item: TManageItem) => void; + service: TimelineServiceTemplate; + UiComponent: React.ComponentType< + ExcludeKey< + TimelinePageTemplateUIProps, + 'CardComponent' + > + >; + dataVersion?: number; + notFoundI18nKey: string; +} + +export default function TimelinePageTemplate< + TManageItem, + TTimeline extends TimelineInfo +>( + props: TimelinePageTemplateProps +): React.ReactElement | null { + const { t } = useTranslation(); + + const { name } = props; + + const user = useUser(); + + const [dialog, setDialog] = React.useState( + null + ); + const [timeline, setTimeline] = React.useState( + undefined + ); + const [posts, setPosts] = React.useState< + TimelinePostInfoEx[] | 'forbid' | undefined + >(undefined); + const [error, setError] = React.useState(undefined); + + const service = props.service; + + React.useEffect(() => { + let subscribe = true; + service.fetch(name).then( + (ti) => { + if (subscribe) { + setTimeline(ti); + if (!service.hasReadPermission(user, ti)) { + setPosts('forbid'); + } else { + service.fetchPosts(name).then( + (data) => { + if (subscribe) { + setPosts( + data.map((post) => ({ + ...post, + deletable: service.hasModifyPostPermission( + user, + ti, + post + ), + })) + ); + } + }, + (error) => { + if (subscribe) { + setError(`${error as string}`); + } + } + ); + } + } + }, + (error: AxiosError) => { + if (subscribe) { + if ( + extractStatusCode(error) === 404 || + extractErrorCode(error) === 11020101 + ) { + setError(t(props.notFoundI18nKey)); + } else { + setError(error.toString()); + } + } + } + ); + return () => { + subscribe = false; + }; + }, [name, service, user, t, props.dataVersion, props.notFoundI18nKey]); + + const closeDialog = React.useCallback((): void => { + setDialog(null); + }, []); + + let dialogElement: React.ReactElement | undefined; + + if (dialog === 'property') { + if (timeline == null) { + throw new UiLogicError( + 'Timeline is null but attempt to open change property dialog.' + ); + } + + dialogElement = ( + { + return service.changeProperty(name, req).then((newTimeline) => { + setTimeline(newTimeline); + }); + }} + /> + ); + } else if (dialog === 'member') { + if (timeline == null) { + throw new UiLogicError( + 'Timeline is null but attempt to open change property dialog.' + ); + } + + dialogElement = ( + { + return fetchUser(u).catch((e) => { + if ( + extractStatusCode(e) === 404 || + extractErrorCode(e) === 11020101 + ) { + return Promise.resolve(null); + } else { + return Promise.reject(e); + } + }); + }, + onAddUser: (u) => { + return service.addMember(name, u.username).then((_) => { + setTimeline({ + ...timeline, + members: concat(timeline.members, u), + }); + }); + }, + onRemoveUser: (u) => { + void service.removeMember(name, u).then((_) => { + setTimeline({ + ...timeline, + members: without( + timeline.members, + timeline.members.find((m) => m.username === u) + ), + }); + }); + }, + } + : null + } + /> + ); + } + + const { UiComponent } = props; + + const onDelete: TimelineDeleteCallback = React.useCallback( + (index, id) => { + service.deletePost(name, id).then( + (_) => { + setPosts((oldPosts) => + without( + oldPosts as TimelinePostInfoEx[], + (oldPosts as TimelinePostInfoEx[])[index] + ) + ); + }, + () => { + pushAlert({ + type: 'danger', + message: t('timeline.deletePostFailed'), + }); + } + ); + }, + [service, name, t] + ); + + const onPost: TimelinePostSendCallback = React.useCallback( + (req) => { + return service.createPost(name, req).then((newPost) => { + setPosts((oldPosts) => + concat(oldPosts as TimelinePostInfoEx[], { + ...newPost, + deletable: true, + }) + ); + }); + }, + [service, name] + ); + + const onManageProp = props.onManage; + + const onManage = React.useCallback( + (item: 'property' | TManageItem) => { + if (item === 'property') { + setDialog(item); + } else { + onManageProp(item); + } + }, + [onManageProp] + ); + + const onMember = React.useCallback(() => { + setDialog('member'); + }, []); + + return ( + <> + + {dialogElement} + + ); +} diff --git a/Timeline/ClientApp/src/app/timeline/TimelinePageTemplateUI.tsx b/Timeline/ClientApp/src/app/timeline/TimelinePageTemplateUI.tsx new file mode 100644 index 00000000..d74fffc4 --- /dev/null +++ b/Timeline/ClientApp/src/app/timeline/TimelinePageTemplateUI.tsx @@ -0,0 +1,212 @@ +import React from 'react'; +import { Spinner } from 'reactstrap'; +import { useTranslation } from 'react-i18next'; +import { Subject, fromEvent } from 'rxjs'; + +import { getAlertHost } from '../common/alert-service'; + +import Timeline, { + TimelinePostInfoEx, + TimelineDeleteCallback, +} from './Timeline'; +import AppBar from '../common/AppBar'; +import TimelinePostEdit, { TimelinePostSendCallback } from './TimelinePostEdit'; +import CollapseButton from '../common/CollapseButton'; + +export interface TimelineCardComponentProps { + timeline: TTimeline; + onManage?: (item: TManageItems | 'property') => void; + onMember: () => void; + className?: string; + onHeight?: (height: number) => void; +} + +export interface TimelinePageTemplateUIProps< + TTimeline extends { name: string }, + TManageItems +> { + avatarKey?: string | number; + timeline?: TTimeline; + posts?: TimelinePostInfoEx[] | 'forbid'; + CardComponent: React.ComponentType< + TimelineCardComponentProps + >; + onMember: () => void; + onManage?: (item: TManageItems | 'property') => void; + onPost?: TimelinePostSendCallback; + onDelete: TimelineDeleteCallback; + error?: string; +} + +export default function TimelinePageTemplateUI< + TTimeline extends { name: string }, + TEditItems +>( + props: TimelinePageTemplateUIProps +): React.ReactElement | null { + const { timeline } = props; + + const { t } = useTranslation(); + + const bottomSpaceRef = React.useRef(null); + + const onPostEditHeightChange = React.useCallback((height: number): void => { + const { current: bottomSpaceDiv } = bottomSpaceRef; + if (bottomSpaceDiv != null) { + bottomSpaceDiv.style.height = `${height}px`; + } + if (height === 0) { + const alertHost = getAlertHost(); + if (alertHost != null) { + alertHost.style.removeProperty('margin-bottom'); + } + } else { + const alertHost = getAlertHost(); + if (alertHost != null) { + alertHost.style.marginBottom = `${height}px`; + } + } + }, []); + + const resizeSubject = React.useMemo(() => new Subject(), []); + const triggerResizeEvent = React.useCallback(() => { + resizeSubject.next(null); + }, [resizeSubject]); + + React.useEffect(() => { + let scrollToBottom = true; + const disableScrollToBottom = (): void => { + scrollToBottom = false; + }; + + const subscriptions = [ + fromEvent(window, 'wheel').subscribe(disableScrollToBottom), + fromEvent(window, 'pointerdown').subscribe(disableScrollToBottom), + fromEvent(window, 'keydown').subscribe(disableScrollToBottom), + resizeSubject.subscribe(() => { + if (scrollToBottom) { + window.scrollTo(0, document.body.scrollHeight); + } + }), + ]; + + return () => { + subscriptions.forEach((s) => s.unsubscribe()); + }; + }, [resizeSubject, timeline, props.posts]); + + const [cardHeight, setCardHeight] = React.useState(0); + + const onCardHeightChange = React.useCallback((height: number) => { + setCardHeight(height); + }, []); + + const genCardCollapseLocalStorageKey = (timelineName: string): string => + `timeline.${timelineName}.cardCollapse`; + + const cardCollapseLocalStorageKey = + timeline != null ? genCardCollapseLocalStorageKey(timeline.name) : null; + + const [infoCardCollapse, setInfoCardCollapse] = React.useState(true); + React.useEffect(() => { + if (cardCollapseLocalStorageKey != null) { + const savedCollapse = + window.localStorage.getItem(cardCollapseLocalStorageKey) === 'true'; + setInfoCardCollapse(savedCollapse); + } + }, [cardCollapseLocalStorageKey]); + + let body: React.ReactElement; + + if (props.error != null) { + body =

{t(props.error)}

; + } else { + if (timeline != null) { + let timelineBody: React.ReactElement; + if (props.posts != null) { + if (props.posts === 'forbid') { + timelineBody = ( +

{t('timeline.messageCantSee')}

+ ); + } else { + timelineBody = ( + + ); + if (props.onPost != null) { + timelineBody = ( + <> + {timelineBody} +
+ + + ); + } + } + } else { + timelineBody = ( +
+ +
+ ); + } + const { CardComponent } = props; + + body = ( + <> +
+ { + const newState = !infoCardCollapse; + setInfoCardCollapse(newState); + window.localStorage.setItem( + genCardCollapseLocalStorageKey(timeline.name), + newState.toString() + ); + }} + className="float-right m-1 info-card-collapse-button text-orange" + /> + +
+ {timelineBody} + + ); + } else { + body = ( +
+ +
+ ); + } + } + + return ( + <> + +
+
+ {body} +
+ + ); +} diff --git a/Timeline/ClientApp/src/app/timeline/TimelinePageUI.tsx b/Timeline/ClientApp/src/app/timeline/TimelinePageUI.tsx new file mode 100644 index 00000000..d7e9d81b --- /dev/null +++ b/Timeline/ClientApp/src/app/timeline/TimelinePageUI.tsx @@ -0,0 +1,22 @@ +import React from 'react'; + +import { ExcludeKey } from '../type-utilities'; +import { TimelineInfo } from '../data/timeline'; + +import TimelinePageTemplateUI, { + TimelinePageTemplateUIProps +} from './TimelinePageTemplateUI'; +import TimelineInfoCard, { + OrdinaryTimelineManageItem +} from './TimelineInfoCard'; + +export type TimelinePageUIProps = ExcludeKey< + TimelinePageTemplateUIProps, + 'CardComponent' +>; + +const TimelinePageUI: React.FC = props => { + return ; +}; + +export default TimelinePageUI; diff --git a/Timeline/ClientApp/src/app/timeline/TimelinePostEdit.tsx b/Timeline/ClientApp/src/app/timeline/TimelinePostEdit.tsx new file mode 100644 index 00000000..f12b6892 --- /dev/null +++ b/Timeline/ClientApp/src/app/timeline/TimelinePostEdit.tsx @@ -0,0 +1,224 @@ +import React from 'react'; +import clsx from 'clsx'; +import { Button, Spinner, Row, Col } from 'reactstrap'; +import { useTranslation } from 'react-i18next'; + +import { pushAlert } from '../common/alert-service'; +import { CreatePostRequest } from '../data/timeline'; + +import FileInput from '../common/FileInput'; +import { UiLogicError } from '../common'; + +interface TimelinePostEditImageProps { + onSelect: (blob: Blob | null) => void; +} + +const TimelinePostEditImage: React.FC = (props) => { + const { onSelect } = props; + const { t } = useTranslation(); + + const [file, setFile] = React.useState(null); + const [fileUrl, setFileUrl] = React.useState(null); + const [error, setError] = React.useState(null); + + React.useEffect(() => { + if (file != null) { + const url = URL.createObjectURL(file); + setFileUrl(url); + return () => { + URL.revokeObjectURL(url); + }; + } + }, [file]); + + const onInputChange: React.ChangeEventHandler = React.useCallback( + (e) => { + const files = e.target.files; + if (files == null || files.length === 0) { + setFile(null); + setFileUrl(null); + } else { + setFile(files[0]); + } + onSelect(null); + setError(null); + }, + [onSelect] + ); + + const onImgLoad = React.useCallback(() => { + onSelect(file); + }, [onSelect, file]); + + const onImgError = React.useCallback(() => { + setError('loadImageError'); + }, []); + + return ( + <> + + {fileUrl && error == null && ( + + )} + {error != null &&
{t(error)}
} + + ); +}; + +export type TimelinePostSendCallback = ( + content: CreatePostRequest +) => Promise; + +export interface TimelinePostEditProps { + className?: string; + onPost: TimelinePostSendCallback; + onHeightChange?: (height: number) => void; + timelineName: string; +} + +const TimelinePostEdit: React.FC = (props) => { + const { onPost } = props; + + const { t } = useTranslation(); + + const [state, setState] = React.useState<'input' | 'process'>('input'); + const [kind, setKind] = React.useState<'text' | 'image'>('text'); + const [text, setText] = React.useState(''); + const [imageBlob, setImageBlob] = React.useState(null); + + const draftLocalStorageKey = `timeline.${props.timelineName}.postDraft`; + + React.useEffect(() => { + setText(window.localStorage.getItem(draftLocalStorageKey) ?? ''); + }, [draftLocalStorageKey]); + + const canSend = kind === 'text' || (kind === 'image' && imageBlob != null); + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const containerRef = React.useRef(null!); + + React.useEffect(() => { + if (props.onHeightChange) { + props.onHeightChange(containerRef.current.clientHeight); + } + return () => { + if (props.onHeightChange) { + props.onHeightChange(0); + } + }; + }); + + const toggleKind = React.useCallback(() => { + setKind((oldKind) => (oldKind === 'text' ? 'image' : 'text')); + setImageBlob(null); + }, []); + + const onSend = React.useCallback(() => { + setState('process'); + + const req: CreatePostRequest = (() => { + switch (kind) { + case 'text': + return { + content: { + type: 'text', + text: text, + }, + } as CreatePostRequest; + case 'image': + if (imageBlob == null) { + throw new UiLogicError( + 'Content type is image but image blob is null.' + ); + } + return { + content: { + type: 'image', + data: imageBlob, + }, + } as CreatePostRequest; + default: + throw new UiLogicError('Unknown content type.'); + } + })(); + + onPost(req).then( + (_) => { + if (kind === 'text') { + setText(''); + window.localStorage.removeItem(draftLocalStorageKey); + } + setState('input'); + setKind('text'); + }, + (_) => { + pushAlert({ + type: 'danger', + message: t('timeline.sendPostFailed'), + }); + setState('input'); + } + ); + }, [onPost, kind, text, imageBlob, t, draftLocalStorageKey]); + + const onImageSelect = React.useCallback((blob: Blob | null) => { + setImageBlob(blob); + }, []); + + return ( +
+ + + {kind === 'text' ? ( +