Major UI improvements pass

This commit is contained in:
IRBorisov 2023-08-27 15:39:49 +03:00
parent 2feebec64d
commit e87a6278e1
41 changed files with 591 additions and 351 deletions

View File

@ -24,7 +24,7 @@ class LibraryActiveView(generics.ListAPIView):
def get_queryset(self):
user = self.request.user
if not user.is_anonymous:
# pyling: disable=unsupported-binary-operation
# pylint: disable=unsupported-binary-operation
return m.LibraryItem.objects.filter(Q(is_common=True) | Q(owner=user) | Q(subscription__user=user))
else:
return m.LibraryItem.objects.filter(is_common=True)

View File

@ -16,7 +16,7 @@ import RSFormPage from './pages/RSFormPage';
import UserProfilePage from './pages/UserProfilePage';
function App () {
const { noNavigation, viewportHeight, mainHeight } = useConceptTheme();
const { noNavigation, noFooter, viewportHeight, mainHeight } = useConceptTheme();
return (
<div className='antialiased clr-app'>
<Navigation />
@ -45,7 +45,7 @@ function App () {
<Route path='*' element={ <NotFoundPage/>} />
</Routes>
</main>
{!noNavigation && <Footer />}
{!noNavigation && !noFooter && <Footer />}
</div>
</div>
);

View File

@ -1,6 +1,7 @@
import DataTable, { createTheme, type TableProps } from 'react-data-table-component';
import { useConceptTheme } from '../../context/ThemeContext';
import { dataTableDarkT, dataTableLightT } from '../../utils/color';
export interface SelectionInfo<T> {
allSelected: boolean
@ -8,47 +9,21 @@ export interface SelectionInfo<T> {
selectedRows: T[]
}
createTheme('customDark', {
text: {
primary: 'rgba(228, 228, 231, 1)',
secondary: 'rgba(228, 228, 231, 0.87)',
disabled: 'rgba(228, 228, 231, 0.54)'
},
background: {
default: '#111827'
},
highlightOnHover: {
default: '#4d6080',
text: 'rgba(228, 228, 231, 1)'
},
divider: {
default: '#6b6b6b'
},
striped: {
default: '#374151',
text: 'rgba(228, 228, 231, 1)'
},
selected: {
default: '#4d6080',
text: 'rgba(228, 228, 231, 1)'
}
}, 'dark');
createTheme('customDark', dataTableDarkT, 'dark');
createTheme('customLight', dataTableLightT, 'light');
createTheme('customLight', {
divider: {
default: '#d1d5db'
},
striped: {
default: '#f0f2f7'
},
}, 'light');
interface ConceptDataTableProps<T>
extends Omit<TableProps<T>, 'paginationComponentOptions'> {}
function ConceptDataTable<T>({ theme, ...props }: TableProps<T>) {
function ConceptDataTable<T>({ theme, ...props }: ConceptDataTableProps<T>) {
const { darkMode } = useConceptTheme();
return (
<DataTable<T>
theme={ theme ?? (darkMode ? 'customDark' : 'customLight')}
paginationComponentOptions={{
rowsPerPageText: 'строк на страницу'
}}
{...props}
/>
);

View File

@ -1,11 +1,15 @@
import type { TabProps } from 'react-tabs';
import { Tab } from 'react-tabs';
function ConceptTab({ children, className, ...otherProps }: TabProps) {
interface ConceptTabProps
extends Omit<TabProps, 'className'> {
className?: string
}
function ConceptTab({ children, className, ...otherProps }: ConceptTabProps) {
return (
<Tab
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
className={`px-2 py-1 border-r-2 text-sm hover:cursor-pointer clr-tab whitespace-nowrap ${className}`}
className={`px-2 py-1 text-sm hover:cursor-pointer clr-tab whitespace-nowrap ${className}`}
{...otherProps}
>
{children}

View File

@ -46,7 +46,7 @@ function Modal({
<div className='max-h-[calc(95vh-15rem)]'>
{children}
</div>
<div className='flex justify-center w-full gap-4 pt-4 mt-2 border-t-4'>
<div className='flex justify-center w-full gap-4 pt-4 mt-2 border-t-4 clr-border'>
{!readonly &&
<Button
text={submitText}

View File

@ -27,7 +27,7 @@ function TextInput({
/>
<input id={id}
title={tooltip}
className={`px-3 py-2 mt-2 leading-tight border shadow truncate hover:text-clip ${colorClass} ${singleRow ? '' : widthClass}`}
className={`px-3 py-2 leading-tight border shadow truncate hover:text-clip ${colorClass} ${singleRow ? '' : 'mt-2 ' + widthClass}`}
required={required}
{...props}
/>

View File

@ -1,98 +0,0 @@
export const lightTheme = {
canvas: {
background: '#f9fafb',
},
node: {
fill: '#7CA0AB',
activeFill: '#1DE9AC',
opacity: 1,
selectedOpacity: 1,
inactiveOpacity: 0.2,
label: {
color: '#2A6475',
stroke: '#fff',
activeColor: '#1DE9AC'
}
},
lasso: {
border: '1px solid #55aaff',
background: 'rgba(75, 160, 255, 0.1)'
},
ring: {
fill: '#D8E6EA',
activeFill: '#1DE9AC'
},
edge: {
fill: '#D8E6EA',
activeFill: '#1DE9AC',
opacity: 1,
selectedOpacity: 1,
inactiveOpacity: 0.1,
label: {
stroke: '#fff',
color: '#2A6475',
activeColor: '#1DE9AC'
}
},
arrow: {
fill: '#D8E6EA',
activeFill: '#1DE9AC'
},
cluster: {
stroke: '#D8E6EA',
label: {
stroke: '#fff',
color: '#2A6475'
}
}
}
export const darkTheme = {
canvas: {
background: '#1f2937'
},
node: {
fill: '#7A8C9E',
activeFill: '#1DE9AC',
opacity: 1,
selectedOpacity: 1,
inactiveOpacity: 0.2,
label: {
stroke: '#1E2026',
color: '#ACBAC7',
activeColor: '#1DE9AC'
}
},
lasso: {
border: '1px solid #55aaff',
background: 'rgba(75, 160, 255, 0.1)'
},
ring: {
fill: '#54616D',
activeFill: '#1DE9AC'
},
edge: {
fill: '#474B56',
activeFill: '#1DE9AC',
opacity: 1,
selectedOpacity: 1,
inactiveOpacity: 0.1,
label: {
stroke: '#1E2026',
color: '#ACBAC7',
activeColor: '#1DE9AC'
}
},
arrow: {
fill: '#474B56',
activeFill: '#1DE9AC'
},
cluster: {
stroke: '#474B56',
label: {
stroke: '#1E2026',
color: '#ACBAC7'
}
}
}

View File

@ -1,4 +1,5 @@
import { urls } from '../../utils/constants';
import { LibraryFilterStrategy } from '../../utils/models';
import TextURL from '../Common/TextURL';
function HelpMain() {
@ -9,8 +10,9 @@ function HelpMain() {
<p>Навигация по порталу осуществляется верхнюю панель или ссылки в "подвале" страницы. Их можно скрыть с помощью кнопки в правом верхнем углу</p>
<p>В меню пользователя (правый верхний угол) редактирование данных пользователя и изменение цветовой темы.</p>
<p className='mt-2'><b>Основные разделы Портала</b></p>
<li><TextURL text='Библиотека' href='/library?filter=common' /> - общедоступные схемы и инструменты поиска и навигации по ним</li>
<li><TextURL text='Мои схемы' href='/library?filter=personal' /> - отслеживаемые и редактируемые схемы. Основной рабочий раздел</li>
<li><TextURL text='Библиотека' href='/library' /> - все схемы доступные пользователю</li>
<li><TextURL text='Общие схемы' href={`/library?filter=${LibraryFilterStrategy.COMMON}`} /> - общедоступные схемы и инструменты поиска и навигации по ним</li>
<li><TextURL text='Мои схемы' href={`/library?filter=${LibraryFilterStrategy.PERSONAL}`} /> - отслеживаемые и редактируемые схемы. Основной рабочий раздел</li>
<li><TextURL text='Профиль' href='/profile' /> - данные пользователя и смена пароля</li>
<p className='mt-2'><b>Поддержка Портала</b></p>
<p>Портал разрабатывается <TextURL text='Центром Концепт' href={urls.concept}/> и является проектом с открытым исходным кодом, доступным на <TextURL text='Github' href={urls.gitrepo}/>.</p>

View File

@ -6,6 +6,7 @@ function HelpRSFormMeta() {
<p>Для <b>общедоступных</b> схем владельцем может стать любой пользователь</p>
<p>Для <b>библиотечных</b> схем правом редактирования обладают только администраторы</p>
<p><b>Клонировать</b> - создать копию схемы для дальнейшего редактирования</p>
<p><b>Отслеживание</b> - возможность видеть схему в Библиотеке и использовать фильтры</p>
<p><b>Загрузить/Выгрузить схему</b> - взаимодействие с Экстеор через файлы формата TRS</p>
</div>
);

View File

@ -8,7 +8,7 @@ function Logo({ title }: LogoProps) {
return (
<Link to='/' className='flex items-center mr-4' tabIndex={-1}>
<img src='/favicon.svg' className='min-h-[2rem] mr-2 min-w-[2rem]' alt=''/>
<span className='self-center hidden text-xl font-semibold lg:block whitespace-nowrap dark:text-white'>{title}</span>
<span className='self-center hidden text-xl font-semibold md:block whitespace-nowrap dark:text-white'>{title}</span>
</Link>
);
}

View File

@ -10,7 +10,7 @@ function Navigation () {
const navigate = useNavigate();
const { noNavigation, toggleNoNavigation } = useConceptTheme();
const navigateCommon = () => { navigate('/library?filter=common') };
const navigateLibrary = () => { navigate('/library') };
const navigateHelp = () => { navigate('/manuals') };
return (
@ -42,7 +42,7 @@ function Navigation () {
text='Библиотека'
description='Библиотека концептуальных схем'
icon={<LibraryIcon />}
onClick={navigateCommon}
onClick={navigateLibrary}
/>
<NavigationButton
text='Справка'

View File

@ -2,6 +2,7 @@ import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';
import { useConceptTheme } from '../../context/ThemeContext';
import { LibraryFilterStrategy } from '../../utils/models';
import Dropdown from '../Common/Dropdown';
import DropdownButton from '../Common/DropdownButton';
@ -27,7 +28,7 @@ function UserDropdown({ hideDropdown }: UserDropdownProps) {
const navigateMyWork = () => {
hideDropdown();
navigate('/library?filter=personal');
navigate(`/library?filter=${LibraryFilterStrategy.PERSONAL}`);
};
return (

View File

@ -1,6 +1,8 @@
import { bracketMatching, MatchResult } from '@codemirror/language';
import { Decoration, EditorView } from '@codemirror/view';
import { bracketsDarkT, bracketsLightT } from '../../utils/color';
const matchingMark = Decoration.mark({class: "cc-matchingBracket"});
const nonmatchingMark = Decoration.mark({class: "cc-nonmatchingBracket"});
@ -14,31 +16,9 @@ function bracketRender(match: MatchResult) {
return decorations;
}
const darkTheme = EditorView.baseTheme({
'.cc-matchingBracket': {
fontWeight: 600,
},
'.cc-nonmatchingBracket': {
color: '#ef4444',
fontWeight: 700,
},
'&.cm-focused .cc-matchingBracket': {
backgroundColor: '#734f00',
},
});
const darkTheme = EditorView.baseTheme(bracketsDarkT);
const lightTheme = EditorView.baseTheme({
'.cc-matchingBracket': {
fontWeight: 600,
},
'.cc-nonmatchingBracket': {
color: '#ef4444',
fontWeight: 700,
},
'&.cm-focused .cc-matchingBracket': {
backgroundColor: '#dae6f2',
},
});
const lightTheme = EditorView.baseTheme(bracketsLightT);
export function ccBracketMatching(darkMode: boolean) {
return [bracketMatching({ renderMatch: bracketRender }), darkMode ? darkTheme : lightTheme];

View File

@ -54,7 +54,7 @@ function RSInput({
id, label, innerref, onChange, editable,
...props
}: RSInputProps) {
const { darkMode } = useConceptTheme();
const { darkMode, colors } = useConceptTheme();
const { schema } = useRSForm();
const internalRef = useRef<ReactCodeMirrorRef>(null);
@ -69,9 +69,9 @@ function RSInput({
theme: 'light',
settings: {
fontFamily: 'inherit',
background: editable ? '#ffffff' : '#f0f2f7',
foreground: '#000000',
selection: '#aacef2',
background: editable ? colors.input : colors.inputDisabled,
foreground: colors.text,
selection: colors.selection,
caret: '#5d00ff',
},
styles: [
@ -83,16 +83,16 @@ function RSInput({
{ tag: t.controlKeyword, class: 'font-semibold'}, // R | I | D
{ tag: t.unit, class: 'text-[0.75rem]' }, // indicies
]
}), [editable]);
}), [editable, colors]);
const darkTheme: Extension = useMemo(
() => createTheme({
theme: 'dark',
settings: {
fontFamily: 'inherit',
background: editable ? '#070b12' : '#374151',
foreground: '#e4e4e7',
selection: '#8c6000',
background: editable ? colors.input : colors.inputDisabled,
foreground: colors.text,
selection: colors.selection,
caret: '#ffaa00'
},
styles: [
@ -104,7 +104,7 @@ function RSInput({
{ tag: t.controlKeyword, class: 'font-semibold'}, // R | I | D
{ tag: t.unit, class: 'text-[0.75rem]' }, // indicies
]
}), [editable]);
}), [editable, colors]);
const editorExtensions = useMemo(
() => [

View File

@ -3,7 +3,8 @@ import { createContext, useCallback, useContext, useLayoutEffect, useState } fro
import { type ErrorInfo } from '../components/BackendError';
import useLocalStorage from '../hooks/useLocalStorage';
import { type DataCallback, getAuth, patchPassword,postLogin, postLogout, postSignup } from '../utils/backendAPI';
import { ICurrentUser, IUserLoginData, IUserProfile, IUserSignupData, IUserUpdatePassword } from '../utils/models';
import { ICurrentUser, IUserInfo, IUserLoginData, IUserProfile, IUserSignupData, IUserUpdatePassword } from '../utils/models';
import { useUsers } from './UsersContext';
interface IAuthContext {
user: ICurrentUser | undefined
@ -32,6 +33,7 @@ interface AuthStateProps {
}
export const AuthState = ({ children }: AuthStateProps) => {
const { users } = useUsers();
const [user, setUser] = useLocalStorage<ICurrentUser | undefined>('user', undefined);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<ErrorInfo>(undefined);
@ -82,6 +84,7 @@ export const AuthState = ({ children }: AuthStateProps) => {
setLoading: setLoading,
onError: error => setError(error),
onSuccess: newData => reload(() => {
users.push(newData as IUserInfo);
if (callback) callback(newData);
})
});

View File

@ -91,12 +91,14 @@ export const LibraryState = ({ children }: LibraryStateProps) => {
showError: true,
setLoading: setProcessing,
onError: error => setError(error),
onSuccess: newSchema => {
reload();
if (callback) callback(newSchema);
onSuccess: newSchema => reload(() => {
if (user && !user.subscriptions.includes(newSchema.id)) {
user.subscriptions.push(newSchema.id);
}
if (callback) callback(newSchema);
})
});
}, [reload]);
}, [reload, user]);
const destroySchema = useCallback(
(target: number, callback?: () => void) => {
@ -106,10 +108,13 @@ export const LibraryState = ({ children }: LibraryStateProps) => {
setLoading: setProcessing,
onError: error => setError(error),
onSuccess: () => reload(() => {
if (user && user.subscriptions.includes(target)) {
user.subscriptions.splice(user.subscriptions.findIndex(item => item === target), 1);
}
if (callback) callback();
})
});
}, [setError, reload]);
}, [setError, reload, user]);
const cloneSchema = useCallback(
(target: number, data: IRSFormCreateData, callback: DataCallback<IRSFormData>) => {
@ -123,6 +128,9 @@ export const LibraryState = ({ children }: LibraryStateProps) => {
setLoading: setProcessing,
onError: error => setError(error),
onSuccess: newSchema => reload(() => {
if (user && !user.subscriptions.includes(newSchema.id)) {
user.subscriptions.push(newSchema.id);
}
if (callback) callback(newSchema);
})
});

View File

@ -15,6 +15,7 @@ import {
ILibraryUpdateData, IRSForm, IRSFormUploadData
} from '../utils/models'
import { useAuth } from './AuthContext'
import { useLibrary } from './LibraryContext'
interface IRSFormContext {
schema?: IRSForm
@ -66,6 +67,7 @@ interface RSFormStateProps {
}
export const RSFormState = ({ schemaID, children }: RSFormStateProps) => {
const library = useLibrary();
const { user } = useAuth();
const { schema, reload, error, setError, setSchema, loading } = useRSFormDetails({ target: schemaID });
const [ processing, setProcessing ] = useState(false);
@ -114,10 +116,14 @@ export const RSFormState = ({ schemaID, children }: RSFormStateProps) => {
onError: error => setError(error),
onSuccess: newData => {
setSchema(Object.assign(schema, newData));
const libraryItem = library.items.find(item => item.id === newData.id);
if (libraryItem) {
Object.assign(libraryItem, newData);
}
if (callback) callback(newData);
}
});
}, [schemaID, setError, setSchema, schema]);
}, [schemaID, setError, setSchema, schema, library]);
const upload = useCallback(
(data: IRSFormUploadData, callback?: () => void) => {
@ -132,10 +138,14 @@ export const RSFormState = ({ schemaID, children }: RSFormStateProps) => {
onError: error => setError(error),
onSuccess: newData => {
setSchema(newData);
const libraryItem = library.items.find(item => item.id === newData.id);
if (libraryItem) {
Object.assign(libraryItem, newData);
}
if (callback) callback();
}
});
}, [schemaID, setError, setSchema, schema]);
}, [schemaID, setError, setSchema, schema, library]);
const claim = useCallback(
(callback?: DataCallback<ILibraryItem>) => {
@ -149,10 +159,17 @@ export const RSFormState = ({ schemaID, children }: RSFormStateProps) => {
onError: error => setError(error),
onSuccess: newData => {
setSchema(Object.assign(schema, newData));
const libraryItem = library.items.find(item => item.id === newData.id);
if (libraryItem) {
libraryItem.owner = user.id
}
if (!user.subscriptions.includes(schema.id)) {
user.subscriptions.push(schema.id);
}
if (callback) callback(newData);
}
});
}, [schemaID, setError, schema, user, setSchema]);
}, [schemaID, setError, schema, user, setSchema, library]);
const subscribe = useCallback(
(callback?: () => void) => {

View File

@ -4,12 +4,17 @@ import useLocalStorage from '../hooks/useLocalStorage';
import { darkT, IColorTheme, lightT } from '../utils/color';
interface IThemeContext {
darkMode: boolean
noNavigation: boolean
viewportHeight: string
mainHeight: string
colors: IColorTheme
darkMode: boolean
toggleDarkMode: () => void
noNavigation: boolean
noFooter: boolean
setNoFooter: (value: boolean) => void
toggleNoNavigation: () => void
}
@ -17,9 +22,7 @@ const ThemeContext = createContext<IThemeContext | null>(null);
export const useConceptTheme = () => {
const context = useContext(ThemeContext);
if (!context) {
throw new Error(
'useConceptTheme has to be used within <ThemeState.Provider>'
);
throw new Error('useConceptTheme has to be used within <ThemeState.Provider>');
}
return context;
}
@ -32,8 +35,9 @@ export const ThemeState = ({ children }: ThemeStateProps) => {
const [darkMode, setDarkMode] = useLocalStorage('darkMode', false);
const [colors, setColors] = useState<IColorTheme>(lightT);
const [noNavigation, setNoNavigation] = useState(false);
const [noFooter, setNoFooter] = useState(false);
const setDarkClass = (isDark: boolean) => {
function setDarkClass(isDark: boolean) {
const root = window.document.documentElement;
if (isDark) {
root.classList.add('dark');
@ -41,7 +45,7 @@ export const ThemeState = ({ children }: ThemeStateProps) => {
root.classList.remove('dark');
}
root.setAttribute('data-color-scheme', !isDark ? 'light' : 'dark');
};
}
useLayoutEffect(() => {
setDarkClass(darkMode)
@ -68,9 +72,10 @@ export const ThemeState = ({ children }: ThemeStateProps) => {
return (
<ThemeContext.Provider value={{
darkMode, colors,
noNavigation,
noNavigation, noFooter,
toggleDarkMode: () => setDarkMode(prev => !prev),
toggleNoNavigation: () => setNoNavigation(prev => !prev),
setNoFooter,
viewportHeight, mainHeight
}}>
{children}

View File

@ -3,6 +3,7 @@ import { createContext, useCallback, useContext, useEffect, useState } from 'rea
import { ErrorInfo } from '../components/BackendError';
import { DataCallback, getProfile, patchProfile } from '../utils/backendAPI';
import { IUserProfile, IUserUpdateData } from '../utils/models';
import { useUsers } from './UsersContext';
interface IUserProfileContext {
user: IUserProfile | undefined
@ -30,6 +31,7 @@ interface UserProfileStateProps {
}
export const UserProfileState = ({ children }: UserProfileStateProps) => {
const { users } = useUsers();
const [user, setUser] = useState<IUserProfile | undefined>(undefined);
const [loading, setLoading] = useState(false);
const [processing, setProcessing] = useState(false);
@ -42,11 +44,10 @@ export const UserProfileState = ({ children }: UserProfileStateProps) => {
getProfile({
showError: true,
setLoading: setLoading,
onError: error => { setError(error); },
onSuccess: newData => { setUser(newData); }
onError: error => setError(error),
onSuccess: newData => setUser(newData)
});
}, [setUser]
);
}, [setUser]);
const updateUser = useCallback(
(data: IUserUpdateData, callback?: DataCallback<IUserProfile>) => {
@ -55,14 +56,18 @@ export const UserProfileState = ({ children }: UserProfileStateProps) => {
data: data,
showError: true,
setLoading: setProcessing,
onError: error => { setError(error); },
onError: error => setError(error),
onSuccess: newData => {
setUser(newData);
const libraryUser = users.find(item => item.id === user?.id);
if (libraryUser) {
libraryUser.first_name = newData.first_name;
libraryUser.last_name = newData.last_name;
}
if (callback) callback(newData);
}
});
}, [setUser]
);
}, [setUser, users]);
useEffect(() => {
reload();

View File

@ -13,9 +13,7 @@ const UsersContext = createContext<IUsersContext | null>(null)
export const useUsers = (): IUsersContext => {
const context = useContext(UsersContext);
if (context === null) {
throw new Error(
'useUsers has to be used within <UsersState.Provider>'
);
throw new Error('useUsers has to be used within <UsersState.Provider>');
}
return context;
}

View File

@ -29,6 +29,32 @@ function checkTypeConsistency(type: CstType, typification: string, args: IFuncti
}
}
function adjustResults(parse: IExpressionParse, emptyExpression: boolean, cstType: CstType) {
if (!parse.parseResult && parse.errors.length > 0 && parse.errors[0].errorType !== RSErrorType.syntax) {
return;
}
if (cstType === CstType.BASE || cstType === CstType.CONSTANT) {
if (!emptyExpression) {
parse.parseResult = false;
parse.errors.push({
errorType: RSErrorType.globalNonemptyBase,
isCritical: true,
params: [],
position: 0
});
}
}
if (!checkTypeConsistency(cstType, parse.typification, parse.args)) {
parse.parseResult = false;
parse.errors.push({
errorType: RSErrorType.globalUnexpectedType,
isCritical: true,
params: [],
position: 0
});
}
}
function useCheckExpression({ schema }: { schema?: IRSForm }) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<ErrorInfo>(undefined);
@ -42,29 +68,10 @@ function useCheckExpression({ schema }: { schema?: IRSForm }) {
data: { expression: expression },
showError: true,
setLoading,
onError: error => { setError(error); },
onError: error => setError(error),
onSuccess: parse => {
if (activeCst && parse.parseResult) {
if (activeCst.cstType === CstType.BASE || activeCst.cstType === CstType.CONSTANT) {
if (expression !== getCstExpressionPrefix(activeCst)) {
parse.parseResult = false;
parse.errors.push({
errorType: RSErrorType.globalNonemptyBase,
isCritical: true,
params: [],
position: 0
});
}
}
if (!checkTypeConsistency(activeCst.cstType, parse.typification, parse.args)) {
parse.parseResult = false;
parse.errors.push({
errorType: RSErrorType.globalUnexpectedType,
isCritical: true,
params: [],
position: 0
});
}
if (activeCst) {
adjustResults(parse, expression === getCstExpressionPrefix(activeCst), activeCst.cstType);
}
setParseData(parse);
if (onSuccess) onSuccess(parse);

View File

@ -42,6 +42,10 @@
@apply clr-border rounded
}
.text-btn {
@apply text-gray-600 dark:text-zinc-200 dark:disabled:text-zinc-400 disabled:text-gray-400
}
.clr-border {
@apply border-gray-300 dark:border-gray-400
}
@ -102,7 +106,7 @@
@apply text-white bg-blue-400 hover:bg-blue-600 dark:bg-blue-600 dark:hover:bg-blue-400 dark:text-black disabled:bg-gray-400 dark:disabled:bg-gray-600
}
.clr-btn-default {
@apply text-gray-600 dark:text-zinc-200 dark:disabled:text-zinc-400 disabled:text-gray-400 bg-[#f0f2f7] hover:bg-gray-300 dark:bg-gray-600 dark:hover:bg-gray-400
@apply bg-[#f0f2f7] hover:bg-gray-300 dark:bg-gray-600 dark:hover:bg-gray-400 text-btn
}
/* Transparent button */

View File

@ -35,15 +35,15 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
>
<IntlProvider locale='ru' defaultLocale='ru'>
<ThemeState>
<AuthState>
<UsersState>
<AuthState>
<LibraryState>
<App />
</LibraryState>
</UsersState>
</AuthState>
</UsersState>
</ThemeState>
</IntlProvider>
</ErrorBoundary>

View File

@ -15,7 +15,7 @@ function HomePage() {
}, TIMEOUT_UI_REFRESH);
} else if(!user.is_staff) {
setTimeout(() => {
navigate('/library?filter=personal');
navigate('/library');
}, TIMEOUT_UI_REFRESH);
}
}, [navigate, user])

View File

@ -0,0 +1,83 @@
import { useCallback } from 'react';
import Button from '../../components/Common/Button';
import Checkbox from '../../components/Common/Checkbox';
import Dropdown from '../../components/Common/Dropdown';
import DropdownButton from '../../components/Common/DropdownButton';
import { FilterCogIcon } from '../../components/Icons';
import useDropdown from '../../hooks/useDropdown';
import { LibraryFilterStrategy } from '../../utils/models';
interface PickerStrategyProps {
value: LibraryFilterStrategy
onChange: (value: LibraryFilterStrategy) => void
}
function PickerStrategy({ value, onChange }: PickerStrategyProps) {
const pickerMenu = useDropdown();
const handleChange = useCallback(
(newValue: LibraryFilterStrategy) => {
pickerMenu.hide();
onChange(newValue);
}, [pickerMenu, onChange]);
return (
<div ref={pickerMenu.ref} className='h-full text-right'>
<Button
icon={<FilterCogIcon size={6} />}
dense
tooltip='Фильтры'
colorClass='clr-input clr-hover text-btn'
widthClass='h-full py-1 px-2 border-none'
onClick={pickerMenu.toggle}
/>
{ pickerMenu.isActive &&
<Dropdown>
<DropdownButton onClick={() => handleChange(LibraryFilterStrategy.MANUAL)}>
<Checkbox
value={value === LibraryFilterStrategy.MANUAL}
label='Отображать все'
/>
</DropdownButton>
<DropdownButton onClick={() => handleChange(LibraryFilterStrategy.COMMON)}>
<Checkbox
value={value === LibraryFilterStrategy.COMMON}
label='Общедоступные'
tooltip='Отображать только общедоступные схемы'
/>
</DropdownButton>
<DropdownButton onClick={() => handleChange(LibraryFilterStrategy.CANONICAL)}>
<Checkbox
value={value === LibraryFilterStrategy.CANONICAL}
label='Библиотечные'
tooltip='Отображать только библиотечные схемы'
/>
</DropdownButton>
<DropdownButton onClick={() => handleChange(LibraryFilterStrategy.PERSONAL)}>
<Checkbox
value={value === LibraryFilterStrategy.PERSONAL}
label='Личные'
tooltip='Отображать только подписки и владеемые схемы'
/>
</DropdownButton>
<DropdownButton onClick={() => handleChange(LibraryFilterStrategy.SUBSCRIBE)}>
<Checkbox
value={value === LibraryFilterStrategy.SUBSCRIBE}
label='Подписки'
tooltip='Отображать только подписки'
/>
</DropdownButton>
<DropdownButton onClick={() => handleChange(LibraryFilterStrategy.OWNED)}>
<Checkbox
value={value === LibraryFilterStrategy.OWNED}
label='Я - Владелец!'
tooltip='Отображать только владеемые схемы'
/>
</DropdownButton>
</Dropdown>}
</div>
);
}
export default PickerStrategy;

View File

@ -1,19 +1,36 @@
import { useLayoutEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { useCallback, useLayoutEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { MagnifyingGlassIcon } from '../../components/Icons';
import { useAuth } from '../../context/AuthContext';
import { ILibraryFilter } from '../../utils/models';
import { ILibraryFilter, LibraryFilterStrategy } from '../../utils/models';
import PickerStrategy from './PickerStrategy';
function ApplyStrategy(strategy: LibraryFilterStrategy): ILibraryFilter {
switch (strategy) {
case LibraryFilterStrategy.MANUAL: return {};
case LibraryFilterStrategy.COMMON: return { is_common: true };
case LibraryFilterStrategy.CANONICAL: return { is_canonical: true };
case LibraryFilterStrategy.PERSONAL: return { is_personal: true };
case LibraryFilterStrategy.SUBSCRIBE: return { is_subscribed: true };
case LibraryFilterStrategy.OWNED: return { is_owned: true };
}
}
interface SearchPanelProps {
total: number
filtered: number
setFilter: React.Dispatch<React.SetStateAction<ILibraryFilter>>
}
function SearchPanel({ setFilter }: SearchPanelProps) {
function SearchPanel({ total, filtered, setFilter }: SearchPanelProps) {
const navigate = useNavigate();
const search = useLocation().search;
const { user } = useAuth();
const [query, setQuery] = useState('');
const [strategy, setStrategy] = useState(LibraryFilterStrategy.MANUAL);
function handleChangeQuery(event: React.ChangeEvent<HTMLInputElement>) {
const newQuery = event.target.value;
@ -31,22 +48,34 @@ function SearchPanel({ setFilter }: SearchPanelProps) {
}
useLayoutEffect(() => {
const filterType = new URLSearchParams(search).get('filter');
if (filterType === 'common') {
setQuery('');
setFilter({
is_common: true
});
} else if (filterType === 'personal' && user) {
setQuery('');
setFilter({
is_personal: true
});
}
const searchFilter = new URLSearchParams(search).get('filter') as LibraryFilterStrategy | null;
const inputStrategy = searchFilter && Object.values(LibraryFilterStrategy).includes(searchFilter) ? searchFilter : LibraryFilterStrategy.MANUAL;
setQuery('')
setStrategy(inputStrategy)
setFilter(ApplyStrategy(inputStrategy));
}, [user, search, setQuery, setFilter]);
const handleChangeStrategy = useCallback(
(value: LibraryFilterStrategy) => {
if (value === strategy) {
return;
}
navigate(`/library?filter=${value}`)
}, [strategy, navigate]);
return (
<div className='sticky top-0 left-0 right-0 z-10 flex justify-center w-full border-b clr-input'>
<div className='sticky top-0 left-0 right-0 z-10 flex items-center justify-start w-full border-b clr-input'>
<div className='px-2 py-1 select-none whitespace-nowrap min-w-[10rem]'>
Фильтр
<span className='ml-2'>
<b>{filtered}</b> из {total}
</span>
</div>
<div className='flex items-center justify-center w-full pr-[10rem]'>
<PickerStrategy
value={strategy}
onChange={handleChangeStrategy}
/>
<div className='relative w-96 min-w-[10rem]'>
<div className='absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none'>
<MagnifyingGlassIcon />
@ -54,31 +83,14 @@ function SearchPanel({ setFilter }: SearchPanelProps) {
<input
type='text'
value={query}
className='w-full p-2 pl-10 text-sm outline-none clr-input border-x clr-border'
className='w-full p-2 pl-10 text-sm outline-none clr-input'
placeholder='Поиск схемы...'
onChange={handleChangeQuery}
/>
</div>
</div>
</div>
);
}
export default SearchPanel;
{/* <div className='sticky top-0 left-0 right-0 z-10 flex items-start justify-between w-full gap-1 px-2 py-1 bg-white border-b rounded clr-bg-pop clr-border'>
<MatchModePicker
value={filterMatch}
onChange={setFilterMatch}
/>
<input type='text'
className='w-full px-2 bg-white outline-none select-none hover:text-clip clr-bg-pop'
placeholder='наберите текст фильтра'
value={filterText}
onChange={event => setFilterText(event.target.value)}
/>
<DependencyModePicker
value={filterSource}
onChange={setFilterSource}
/>
</div> */}

View File

@ -124,7 +124,7 @@ function ViewLibrary({ items, cleanQuery }: ViewLibraryProps) {
<p>
<TextURL text='Создать схему' href='/rsform-create'/>
<span> | </span>
<TextURL text='Все схемы' href='/library?filter=common'/>
<TextURL text='Все схемы' href='/library'/>
<span> | </span>
<span className='cursor-pointer hover:underline text-url' onClick={cleanQuery}>
<b>Очистить фильтр</b>

View File

@ -25,6 +25,8 @@ function LibraryPage() {
{ !library.loading && library.items &&
<div className='flex flex-col w-full'>
<SearchPanel
total={library.items.length ?? 0}
filtered={items.length}
setFilter={setFilter}
/>
<ViewLibrary

View File

@ -39,9 +39,15 @@ function LoginPage() {
}
return (
<div className='w-full py-4'> { user
<div className='flex justify-center w-full'>
<div className='py-2'> { user
? <b>{`Вы вошли в систему как ${user.username}`}</b>
: <Form title='Ввод данных пользователя' onSubmit={handleSubmit} widthClass='w-[21rem]'>
:
<Form
title='Ввод данных пользователя'
onSubmit={handleSubmit}
widthClass='w-[24rem]'
>
<TextInput id='username'
label='Имя пользователя'
required
@ -72,6 +78,7 @@ function LoginPage() {
{ error && <BackendError error={error} />}
</Form>
}</div>
</div>
);
}

View File

@ -66,9 +66,9 @@ function DlgRenameCst({ hideWindow, initial, onRename }: DlgRenameCstProps) {
submitInvalidTooltip={'Введите имя, соответствующее типу и отсутствующее в схеме'}
submitText='Переименовать'
>
<div className='flex items-center gap-4 px-2 mb-2 h-fit min-w-[25rem]'>
<div className='flex items-center gap-4 px-2 my-2 h-fit min-w-[25rem]'>
<ConceptSelect
className='mt-2 min-w-[14rem] self-center'
className='min-w-[14rem] self-center'
options={CstTypeSelector}
placeholder='Выберите тип'
values={cstType ? [{ value: cstType, label: getCstTypeLabel(cstType) }] : []}

View File

@ -126,7 +126,7 @@ function EditorConstituenta({ activeID, onShowAST, onCreateCst, onRenameCst, onO
return (
<div className='flex items-stretch w-full gap-2 mb-2 justify-stretch'>
<form onSubmit={handleSubmit} className='min-w-[50rem] max-w-min px-4 py-2 border'>
<form onSubmit={handleSubmit} className='min-w-[50rem] max-w-min px-4 py-2 border-y border-r clr-border'>
<div className='relative'>
<div className='absolute top-0 left-0'>
<MiniButton
@ -220,7 +220,7 @@ function EditorConstituenta({ activeID, onShowAST, onCreateCst, onRenameCst, onO
onChange={event => { setConvention(event.target.value); }}
onFocus={() => { setEditMode(EditMode.TEXT); }}
/>
<div className='flex justify-center w-full mt-2'>
<div className='flex justify-center w-full mt-4 mb-2'>
<SubmitButton
text='Сохранить изменения'
disabled={!isModified || !isEnabled}

View File

@ -27,7 +27,7 @@ function EditorRSForm({ onDestroy, onClaim, onShare, onDownload }: EditorRSFormP
const { getUserLabel } = useUsers();
const {
schema, update, isForceAdmin,
isEditable, isOwned, isClaimable, processing
isEditable, isClaimable, processing
} = useRSForm();
const { user } = useAuth();
@ -79,7 +79,7 @@ function EditorRSForm({ onDestroy, onClaim, onShare, onDownload }: EditorRSFormP
};
return (
<form onSubmit={handleSubmit} className='flex-grow max-w-[34.7rem] px-4 py-2 border min-w-fit'>
<form onSubmit={handleSubmit} className='flex-grow max-w-[35.3rem] px-4 py-2 border-y border-r clr-border min-w-fit'>
<div className='relative w-full'>
<div className='absolute top-0 right-0 flex'>
<MiniButton
@ -93,8 +93,8 @@ function EditorRSForm({ onDestroy, onClaim, onShare, onDownload }: EditorRSFormP
onClick={onDownload}
/>
<MiniButton
tooltip={isClaimable ? 'Стать владельцем' : 'Вы уже являетесь владельцем' }
icon={<CrownIcon size={5} color={isOwned ? '' : 'text-green'}/>}
tooltip={isClaimable ? 'Стать владельцем' : 'Невозможно стать владельцем' }
icon={<CrownIcon size={5} color={!isClaimable ? '' : 'text-green'}/>}
disabled={!isClaimable || !user}
onClick={onClaim}
/>

View File

@ -9,14 +9,13 @@ import ConceptSelect from '../../components/Common/ConceptSelect';
import ConceptTooltip from '../../components/Common/ConceptTooltip';
import Divider from '../../components/Common/Divider';
import MiniButton from '../../components/Common/MiniButton';
import { darkTheme, lightTheme } from '../../components/GraphThemes';
import HelpTermGraph from '../../components/Help/HelpTermGraph';
import InfoConstituenta from '../../components/Help/InfoConstituenta';
import { ArrowsRotateIcon, DumpBinIcon, FilterCogIcon, HelpIcon, SmallPlusIcon } from '../../components/Icons';
import { useRSForm } from '../../context/RSFormContext';
import { useConceptTheme } from '../../context/ThemeContext';
import useLocalStorage from '../../hooks/useLocalStorage';
import { IColorTheme } from '../../utils/color';
import { graphDarkT, graphLightT, IColorTheme } from '../../utils/color';
import { prefixes, resources } from '../../utils/constants';
import { Graph } from '../../utils/Graph';
import { CstType, IConstituenta, ICstCreateData } from '../../utils/models';
@ -30,14 +29,14 @@ import ConstituentaTooltip from './elements/ConstituentaTooltip';
export type ColoringScheme = 'none' | 'status' | 'type';
const TREE_SIZE_MILESTONE = 50;
function getCstNodeColor(cst: IConstituenta, coloringScheme: ColoringScheme, darkMode: boolean, colors: IColorTheme): string {
function getCstNodeColor(cst: IConstituenta, coloringScheme: ColoringScheme, colors: IColorTheme): string {
if (coloringScheme === 'type') {
return getCstClassColor(cst.cstClass, colors);
}
if (coloringScheme === 'status') {
return getCstStatusColor(cst.status, colors);
}
return (darkMode ? '#7a8c9e' :'#7ca0ab');
return '';
}
export interface GraphEditorParams {
@ -173,13 +172,13 @@ function EditorTermGraph({ onOpenEdit, onCreateCst, onDeleteCst }: EditorTermGra
if (cst) {
result.push({
id: String(node.id),
fill: getCstNodeColor(cst, coloringScheme, darkMode, colors),
fill: getCstNodeColor(cst, coloringScheme, colors),
label: cst.term.resolved && !noTerms ? `${cst.alias}: ${cst.term.resolved}` : cst.alias
});
}
});
return result;
}, [schema, coloringScheme, filtered.nodes, darkMode, noTerms, colors]);
}, [schema, coloringScheme, filtered.nodes, noTerms, colors]);
const edges: GraphEdge[] = useMemo(
() => {
@ -356,7 +355,7 @@ function EditorTermGraph({ onOpenEdit, onCreateCst, onDeleteCst }: EditorTermGra
initial={getOptions()}
onConfirm={handleChangeOptions}
/>}
<div className='flex flex-col border-r border-b min-w-[13rem] pr-2 pb-2 text-sm select-none clr-border' style={{height: canvasHeight}}>
<div className='flex flex-col border-r border-b min-w-[13.5rem] px-2 pb-2 text-sm select-none clr-border' style={{height: canvasHeight}}>
{hoverCst &&
<div className='relative'>
<InfoConstituenta
@ -444,7 +443,7 @@ function EditorTermGraph({ onOpenEdit, onCreateCst, onDeleteCst }: EditorTermGra
id={`${prefixes.cst_list}${cst.alias}`}
className='w-fit min-w-[3rem] rounded-md text-center cursor-pointer'
style={{
backgroundColor: getCstNodeColor(cst, adjustedColoring, darkMode, colors),
backgroundColor: getCstNodeColor(cst, adjustedColoring, colors),
...dismissedStyle(cstID)
}}
onClick={() => toggleDismissed(cstID)}
@ -497,7 +496,7 @@ function EditorTermGraph({ onOpenEdit, onCreateCst, onDeleteCst }: EditorTermGra
: undefined
}
labelFontUrl={resources.graph_font}
theme={darkMode ? darkTheme : lightTheme}
theme={darkMode ? graphDarkT : graphLightT}
renderNode={({ node, ...rest }) => (
<Sphere {...rest} node={node} />
)}

View File

@ -9,8 +9,9 @@ import ConceptTab from '../../components/Common/ConceptTab';
import { Loader } from '../../components/Common/Loader';
import { useLibrary } from '../../context/LibraryContext';
import { useRSForm } from '../../context/RSFormContext';
import { useConceptTheme } from '../../context/ThemeContext';
import { prefixes, TIMEOUT_UI_REFRESH } from '../../utils/constants';
import { ICstCreateData, ICstRenameData, SyntaxTree } from '../../utils/models';
import { ICstCreateData, ICstRenameData, LibraryFilterStrategy, SyntaxTree } from '../../utils/models';
import { createAliasFor } from '../../utils/staticUI';
import DlgCloneRSForm from './DlgCloneRSForm';
import DlgCreateCst from './DlgCreateCst';
@ -25,7 +26,7 @@ import EditorTermGraph from './EditorTermGraph';
import RSFormStats from './elements/RSFormStats';
import RSTabsMenu from './RSTabsMenu';
export enum RSTabsList {
export enum RSTabID {
CARD = 0,
CST_LIST = 1,
CST_EDIT = 2,
@ -40,8 +41,9 @@ function RSTabs() {
cstCreate, cstDelete, cstRename, subscribe, unsubscribe
} = useRSForm();
const { destroySchema } = useLibrary();
const { setNoFooter } = useConceptTheme();
const [activeTab, setActiveTab] = useState(RSTabsList.CARD);
const [activeTab, setActiveTab] = useState<RSTabID>(RSTabID.CARD);
const [activeID, setActiveID] = useState<number | undefined>(undefined);
const [showUpload, setShowUpload] = useState(false);
@ -72,21 +74,23 @@ function RSTabs() {
}, [schema]);
useLayoutEffect(() => {
const activeTab = Number(new URLSearchParams(search).get('tab')) ?? RSTabsList.CARD;
const activeTab = (Number(new URLSearchParams(search).get('tab')) ?? RSTabID.CARD) as RSTabID;
const cstQuery = new URLSearchParams(search).get('active');
setActiveTab(activeTab);
setNoFooter(activeTab === RSTabID.CST_EDIT || activeTab === RSTabID.CST_LIST);
setActiveID(Number(cstQuery) ?? ((schema && schema?.items.length > 0) ? schema.items[0].id : undefined));
}, [search, setActiveTab, setActiveID, schema]);
return () => setNoFooter(false);
}, [search, setActiveTab, setActiveID, schema, setNoFooter]);
function onSelectTab(index: number) {
navigateTo(index, activeID);
}
const navigateTo = useCallback(
(tab: RSTabsList, activeID?: number) => {
(tab: RSTabID, activeID?: number) => {
if (activeID) {
navigate(`/rsforms/${schema!.id}?tab=${tab}&active=${activeID}`, {
replace: tab === activeTab && tab !== RSTabsList.CST_EDIT
replace: tab === activeTab && tab !== RSTabID.CST_EDIT
});
} else {
navigate(`/rsforms/${schema!.id}?tab=${tab}`);
@ -102,7 +106,7 @@ function RSTabs() {
cstCreate(data, newCst => {
toast.success(`Конституента добавлена: ${newCst.alias}`);
navigateTo(activeTab, newCst.id);
if (activeTab === RSTabsList.CST_EDIT || activeTab === RSTabsList.CST_LIST) {
if (activeTab === RSTabID.CST_EDIT || activeTab === RSTabID.CST_LIST) {
setTimeout(() => {
const element = document.getElementById(`${prefixes.cst_list}${newCst.alias}`);
if (element) {
@ -151,7 +155,7 @@ function RSTabs() {
const deletedNames = deleted.map(id => schema.items.find(cst => cst.id === id)?.alias).join(', ');
toast.success(`Конституенты удалены: ${deletedNames}`);
if (deleted.length === schema.items.length) {
navigateTo(RSTabsList.CST_LIST);
navigateTo(RSTabID.CST_LIST);
}
if (activeIndex) {
while (activeIndex < schema.items.length && deleted.find(id => id === schema.items[activeIndex].id)) {
@ -182,7 +186,7 @@ function RSTabs() {
const onOpenCst = useCallback(
(cstID: number) => {
navigateTo(RSTabsList.CST_EDIT, cstID)
navigateTo(RSTabID.CST_EDIT, cstID)
}, [navigateTo]);
const onDestroySchema = useCallback(
@ -192,7 +196,7 @@ function RSTabs() {
}
destroySchema(schema.id, () => {
toast.success('Схема удалена');
navigate('/library?filter=personal');
navigate(`/library?filter=${LibraryFilterStrategy.PERSONAL}`);
});
}, [schema, destroySchema, navigate]);
@ -283,7 +287,7 @@ function RSTabs() {
defaultFocus={true}
selectedTabClassName='font-bold'
>
<TabList className='flex items-start pl-2 border-b select-none w-fit clr-bg-pop clr-border'>
<TabList className='flex items-start pl-2 border-b border-r-2 select-none w-fit clr-bg-pop clr-border'>
<RSTabsMenu
onDownload={onDownloadSchema}
onDestroy={onDestroySchema}
@ -302,7 +306,7 @@ function RSTabs() {
<ConceptTab className='min-w-[6.5rem]'>Граф термов</ConceptTab>
</TabList>
<TabPanel className='flex items-start w-full gap-2 px-2'>
<TabPanel className='flex w-full gap-4'>
<EditorRSForm
onDownload={onDownloadSchema}
onDestroy={onDestroySchema}
@ -320,7 +324,7 @@ function RSTabs() {
/>
</TabPanel>
<TabPanel className='pl-2'>
<TabPanel>
<EditorConstituenta
activeID={activeID}
onOpenEdit={onOpenCst}
@ -331,7 +335,7 @@ function RSTabs() {
/>
</TabPanel>
<TabPanel className='pl-2'>
<TabPanel>
<EditorTermGraph
onOpenEdit={onOpenCst}
onCreateCst={promptCreateCst}

View File

@ -52,14 +52,6 @@ function DependencyModePicker({ value, onChange }: DependencyModePickerProps) {
</Dropdown>
}
</div>
// case DependencyMode.OUTPUTS: return 'потребители';
// case DependencyMode.INPUTS: return 'поставщики';
// case DependencyMode.EXPAND_INPUTS: return 'влияющие';
// case DependencyMode.EXPAND_OUTPUTS: return 'зависимые';
// }
// }
);
}

View File

@ -8,7 +8,7 @@ interface RSFormStatsProps {
function RSFormStats({ stats }: RSFormStatsProps) {
return (
<div className='px-4 py-2 border'>
<div className='flex flex-col gap-1 px-4 py-2 border min-w-[16rem]'>
<LabeledText id='count_all'
label='Всего конституент '
text={stats.count_all}
@ -27,12 +27,20 @@ function RSFormStats({ stats }: RSFormStatsProps) {
label='Невычислимы '
text={stats.count_incalc}
/>}
<Divider margins='my-1' />
<Divider margins='my-2' />
<LabeledText id='count_termin'
label='Термины '
text={stats.count_termin}
/>
<Divider margins='my-1' />
<LabeledText id='count_definition'
label='Определения '
text={stats.count_definition}
/>
<LabeledText id='count_convention'
label='Конвенции '
text={stats.count_convention}
/>
<Divider margins='my-2' />
{ stats.count_base > 0 &&
<LabeledText id='count_base'
label='Базисные множества '

View File

@ -12,7 +12,7 @@ import DependencyModePicker from './DependencyModePicker';
import MatchModePicker from './MatchModePicker';
// Height that should be left to accomodate navigation panel + bottom margin
const LOCAL_NAVIGATION_H = '2.6rem';
const LOCAL_NAVIGATION_H = '2.1rem';
interface ViewSideConstituentsProps {
expression: string
@ -26,7 +26,7 @@ function isMockCst(cst: IConstituenta) {
}
function ViewSideConstituents({ expression, baseHeight, activeID, onOpenEdit }: ViewSideConstituentsProps) {
const { darkMode, noNavigation, colors } = useConceptTheme();
const { noNavigation, colors } = useConceptTheme();
const { schema } = useRSForm();
const [filterMatch, setFilterMatch] = useLocalStorage('side-filter-match', CstMatchMode.ALL);
@ -81,10 +81,10 @@ function ViewSideConstituents({ expression, baseHeight, activeID, onOpenEdit }:
{
when: (cst: IConstituenta) => cst.id === activeID,
style: {
backgroundColor: darkMode ? '#0068b3' : '#def1ff',
backgroundColor: colors.selection,
},
}
], [activeID, darkMode]);
], [activeID, colors]);
const columns = useMemo(
() => [
@ -113,7 +113,7 @@ function ViewSideConstituents({ expression, baseHeight, activeID, onOpenEdit }:
conditionalCellStyles: [
{
when: (cst: IConstituenta) => isMockCst(cst),
classNames: ['bg-[#ffc9c9]', 'dark:bg-[#592b2b]']
style: {backgroundColor: colors.selectionError}
}
]
},
@ -126,7 +126,7 @@ function ViewSideConstituents({ expression, baseHeight, activeID, onOpenEdit }:
conditionalCellStyles: [
{
when: (cst: IConstituenta) => isMockCst(cst),
classNames: ['bg-[#ffc9c9]', 'dark:bg-[#592b2b]']
style: {backgroundColor: colors.selectionError}
}
]
},
@ -141,7 +141,7 @@ function ViewSideConstituents({ expression, baseHeight, activeID, onOpenEdit }:
conditionalCellStyles: [
{
when: (cst: IConstituenta) => isMockCst(cst),
classNames: ['bg-[#ffc9c9]', 'dark:bg-[#592b2b]']
style: {backgroundColor: colors.selectionError}
}
]
}

View File

@ -47,7 +47,11 @@ function RegisterPage() {
{ user &&
<b>{`Вы вошли в систему как ${user.username}. Если хотите зарегистрировать нового пользователя, выйдите из системы (меню в правом верхнем углу экрана)`}</b>}
{ !user &&
<Form title='Регистрация пользователя' onSubmit={handleSubmit}>
<Form
title='Регистрация пользователя'
onSubmit={handleSubmit}
widthClass='w-[24rem]'
>
<TextInput id='username' label='Имя пользователя' type='text'
required
value={username}
@ -66,7 +70,7 @@ function RegisterPage() {
<div className='text-sm'>
<p>- используйте уникальный пароль</p>
<p>- портал функционирует в тестовом режиме</p>
<p>- безопасность информации пользователей не гарантируется</p>
<p className='font-semibold text-red'>- безопасность информации не гарантируется</p>
{/* <p>- минимум 8 символов</p>
<p>- большие, маленькие буквы, цифры</p>
<p>- минимум 1 спец. символ</p> */}
@ -85,7 +89,7 @@ function RegisterPage() {
onChange={event => { setLastName(event.target.value); }}
/>
<div className='flex items-center justify-between my-4'>
<div className='flex items-center justify-center w-full my-4'>
<SubmitButton text='Регистрировать' loading={loading}/>
</div>
{ error && <BackendError error={error} />}

View File

@ -14,6 +14,20 @@ function EditorProfile() {
const [first_name, setFirstName] = useState('');
const [last_name, setLastName] = useState('');
const [isModified, setIsModified] = useState(true);
useLayoutEffect(() => {
if (!user) {
setIsModified(false);
return;
}
setIsModified(
user.email !== email ||
user.first_name !== first_name ||
user.last_name !== last_name
);
}, [user, user?.email, user?.first_name, user?.last_name, email, first_name, last_name]);
useLayoutEffect(() => {
if (user) {
setUsername(user.username);
@ -57,6 +71,7 @@ function EditorProfile() {
<SubmitButton
text='Сохранить данные'
loading={processing}
disabled={!isModified}
/>
</div>
</form>

View File

@ -5,6 +5,13 @@ export interface IColorTheme {
teal: string
orange: string
text: string
input: string
inputDisabled: string
selection: string
selectionError: string
// bg100: string
// bg70: string
// bg50: string
@ -17,12 +24,20 @@ export interface IColorTheme {
// secondary: string
}
// =========== GENERAL THEMES =========
export const lightT: IColorTheme = {
red: '#ffc9c9',
green: '#aaff80',
blue: '#b3bdff',
teal: '#a5e9fa',
orange: '#ffbb80',
text: '#000000',
input: '#ffffff',
inputDisabled: '#f0f2f7',
selection: '#def1ff',
selectionError: '#ffc9c9'
};
export const darkT: IColorTheme = {
@ -31,4 +46,174 @@ export const darkT: IColorTheme = {
blue: '#394bbf',
teal: '#0099bf',
orange: '#964600',
text: '#e4e4e7',
input: '#070b12',
inputDisabled: '#374151', // bg-gray-700
selection: '#8c6000',
selectionError: '#592b2b'
};
// ========= DATA TABLE THEMES ========
export const dataTableLightT = {
divider: {
default: '#d1d5db'
},
striped: {
default: '#f0f2f7'
},
}
export const dataTableDarkT = {
text: {
primary: 'rgba(228, 228, 231, 1)',
secondary: 'rgba(228, 228, 231, 0.87)',
disabled: 'rgba(228, 228, 231, 0.54)'
},
background: {
default: '#111827'
},
highlightOnHover: {
default: '#4d6080',
text: 'rgba(228, 228, 231, 1)'
},
divider: {
default: '#6b6b6b'
},
striped: {
default: '#374151',
text: 'rgba(228, 228, 231, 1)'
},
selected: {
default: '#4d6080',
text: 'rgba(228, 228, 231, 1)'
}
};
// ============ GRAPH THEMES ==========
export const graphLightT = {
canvas: {
background: '#f9fafb',
},
node: {
fill: '#7ca0ab',
activeFill: '#1DE9AC',
opacity: 1,
selectedOpacity: 1,
inactiveOpacity: 0.2,
label: {
color: '#2A6475',
stroke: '#fff',
activeColor: '#1DE9AC'
}
},
lasso: {
border: '1px solid #55aaff',
background: 'rgba(75, 160, 255, 0.1)'
},
ring: {
fill: '#D8E6EA',
activeFill: '#1DE9AC'
},
edge: {
fill: '#D8E6EA',
activeFill: '#1DE9AC',
opacity: 1,
selectedOpacity: 1,
inactiveOpacity: 0.1,
label: {
stroke: '#fff',
color: '#2A6475',
activeColor: '#1DE9AC'
}
},
arrow: {
fill: '#D8E6EA',
activeFill: '#1DE9AC'
},
cluster: {
stroke: '#D8E6EA',
label: {
stroke: '#fff',
color: '#2A6475'
}
}
}
export const graphDarkT = {
canvas: {
background: '#1f2937'
},
node: {
fill: '#7a8c9e',
activeFill: '#1DE9AC',
opacity: 1,
selectedOpacity: 1,
inactiveOpacity: 0.2,
label: {
stroke: '#1E2026',
color: '#ACBAC7',
activeColor: '#1DE9AC'
}
},
lasso: {
border: '1px solid #55aaff',
background: 'rgba(75, 160, 255, 0.1)'
},
ring: {
fill: '#54616D',
activeFill: '#1DE9AC'
},
edge: {
fill: '#474B56',
activeFill: '#1DE9AC',
opacity: 1,
selectedOpacity: 1,
inactiveOpacity: 0.1,
label: {
stroke: '#1E2026',
color: '#ACBAC7',
activeColor: '#1DE9AC'
}
},
arrow: {
fill: '#474B56',
activeFill: '#1DE9AC'
},
cluster: {
stroke: '#474B56',
label: {
stroke: '#1E2026',
color: '#ACBAC7'
}
}
}
// ======== Bracket Matching Themes ===========
export const bracketsLightT = {
'.cc-matchingBracket': {
fontWeight: 600,
},
'.cc-nonmatchingBracket': {
color: '#ef4444',
fontWeight: 700,
},
'&.cm-focused .cc-matchingBracket': {
backgroundColor: '#dae6f2',
},
};
export const bracketsDarkT = {
'.cc-matchingBracket': {
fontWeight: 600,
},
'.cc-nonmatchingBracket': {
color: '#ef4444',
fontWeight: 700,
},
'&.cm-focused .cc-matchingBracket': {
backgroundColor: '#734f00',
},
};

View File

@ -247,6 +247,8 @@ export interface IRSFormStats {
count_incalc: number
count_termin: number
count_definition: number
count_convention: number
count_base: number
count_constant: number
@ -281,6 +283,15 @@ export interface IRSFormUploadData {
}
// ========== Library =====
export enum LibraryFilterStrategy {
MANUAL = 'manual',
PERSONAL = 'personal',
COMMON = 'common',
SUBSCRIBE = 'subscribe',
CANONICAL = 'canonical',
OWNED = 'owned'
}
export interface ILibraryFilter {
query?: string
is_personal?: boolean
@ -395,6 +406,8 @@ export function LoadRSFormData(schema: IRSFormData): IRSForm {
count_incalc: 0,
count_termin: 0,
count_definition: 0,
count_convention: 0,
count_base: 0,
count_constant: 0,
@ -419,6 +432,10 @@ export function LoadRSFormData(schema: IRSFormData): IRSForm {
count_termin: result.items.reduce(
(sum, cst) => (sum + (cst.term?.raw ? 1 : 0) || 0), 0),
count_definition: result.items.reduce(
(sum, cst) => (sum + (cst.definition?.text.raw ? 1 : 0) || 0), 0),
count_convention: result.items.reduce(
(sum, cst) => (sum + (cst.convention ? 1 : 0) || 0), 0),
count_base: result.items.reduce(
(sum, cst) => sum + (cst.cstType === CstType.BASE ? 1 : 0), 0),