R: Refactor const global objects

This commit is contained in:
Ivan 2025-04-30 01:10:01 +03:00
parent 7f0c0fd70e
commit 687aa55dcb
26 changed files with 65 additions and 77 deletions

View File

@ -4,9 +4,7 @@
import { buildConstants } from '@/utils/build-constants'; import { buildConstants } from '@/utils/build-constants';
/** /** Routes. */
* Routes.
*/
export const routes = { export const routes = {
not_found: 'not-found', not_found: 'not-found',
login: 'login', login: 'login',
@ -22,11 +20,9 @@ export const routes = {
oss: 'oss', oss: 'oss',
icons: 'icons', icons: 'icons',
database_schema: 'database-schema' database_schema: 'database-schema'
}; } as const;
/** /** Internal navigation URLs. */
* Internal navigation URLs.
*/
export const urls = { export const urls = {
page404: '/not-found', page404: '/not-found',
admin: `${buildConstants.backend}/admin`, admin: `${buildConstants.backend}/admin`,
@ -66,4 +62,4 @@ export const urls = {
oss_props: ({ id, tab }: { id: number | string; tab: number }) => { oss_props: ({ id, tab }: { id: number | string; tab: number }) => {
return `/oss/${id}?tab=${tab}`; return `/oss/${id}?tab=${tab}`;
} }
}; } as const;

View File

@ -6,7 +6,7 @@ export const DELAYS = {
staleShort: 5 * 60 * 1000, staleShort: 5 * 60 * 1000,
staleMedium: 1 * 60 * 60 * 1000, staleMedium: 1 * 60 * 60 * 1000,
staleLong: 24 * 60 * 60 * 1000 staleLong: 24 * 60 * 60 * 1000
}; } as const;
/** API keys for local cache. */ /** API keys for local cache. */
export const KEYS = { export const KEYS = {
@ -19,8 +19,8 @@ export const KEYS = {
global_mutation: 'global_mutation', global_mutation: 'global_mutation',
composite: { composite: {
libraryList: ['library', 'list'], libraryList: ['library', 'list'] as const,
ossItem: ({ itemID }: { itemID?: number }) => [KEYS.oss, 'item', itemID], ossItem: ({ itemID }: { itemID?: number }) => [KEYS.oss, 'item', itemID],
rsItem: ({ itemID, version }: { itemID?: number; version?: number }) => [KEYS.rsform, 'item', itemID, version ?? ''] rsItem: ({ itemID, version }: { itemID?: number; version?: number }) => [KEYS.rsform, 'item', itemID, version ?? '']
} }
}; } as const;

View File

@ -78,7 +78,7 @@ export interface DataTableProps<TData extends RowData>
paginationPerPage?: number; paginationPerPage?: number;
/** List of options to choose from for pagination. */ /** List of options to choose from for pagination. */
paginationOptions?: number[]; paginationOptions?: readonly number[];
/** Callback to be called when the pagination option is changed. */ /** Callback to be called when the pagination option is changed. */
onChangePaginationOption?: (newValue: number) => void; onChangePaginationOption?: (newValue: number) => void;

View File

@ -10,7 +10,7 @@ import { SelectPagination } from './select-pagination';
interface PaginationToolsProps<TData> { interface PaginationToolsProps<TData> {
id?: string; id?: string;
table: Table<TData>; table: Table<TData>;
paginationOptions: number[]; paginationOptions: readonly number[];
onChangePaginationOption?: (newValue: number) => void; onChangePaginationOption?: (newValue: number) => void;
} }

View File

@ -11,7 +11,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '.
interface SelectPaginationProps<TData> { interface SelectPaginationProps<TData> {
id?: string; id?: string;
table: Table<TData>; table: Table<TData>;
paginationOptions: number[]; paginationOptions: readonly number[];
onChange?: (newValue: number) => void; onChange?: (newValue: number) => void;
} }

View File

@ -61,4 +61,4 @@ export const authApi = {
endpoint: '/users/api/password-reset/confirm', endpoint: '/users/api/password-reset/confirm',
request: { data: data } request: { data: data }
}) })
}; } as const;

View File

@ -169,4 +169,4 @@ export const libraryApi = {
successMessage: infoMsg.versionDestroyed successMessage: infoMsg.versionDestroyed
} }
}) })
}; } as const;

View File

@ -164,4 +164,4 @@ export const ossApi = {
endpoint: '/api/oss/get-predecessor', endpoint: '/api/oss/get-predecessor',
request: { data: { target: cstID } } request: { data: { target: cstID } }
}) })
}; } as const;

View File

@ -8,4 +8,4 @@ export const OssNodeTypes: NodeTypes = {
synthesis: OperationNode, synthesis: OperationNode,
input: InputNode, input: InputNode,
block: BlockNode block: BlockNode
}; } as const;

View File

@ -153,4 +153,4 @@ export const rsformsApi = {
endpoint: `/api/rsforms/${itemID}/check-constituenta`, endpoint: `/api/rsforms/${itemID}/check-constituenta`,
request: { data: data } request: { data: data }
}) })
}; } as const;

View File

@ -30,4 +30,4 @@ export const cctextApi = {
endpoint: '/api/cctext/generate-lexeme', endpoint: '/api/cctext/generate-lexeme',
request: { data: data } request: { data: data }
}) })
}; } as const;

View File

@ -17,7 +17,7 @@ export const BRACKETS_THEME = {
backgroundColor: APP_COLORS.bgSelected, backgroundColor: APP_COLORS.bgSelected,
color: APP_COLORS.fgSelected color: APP_COLORS.fgSelected
} }
}; } as const;
/** Determines background color for {@link ISyntaxTreeNode} based on its type. */ /** Determines background color for {@link ISyntaxTreeNode} based on its type. */
export function colorBgSyntaxTree(node: ISyntaxTreeNode): string { export function colorBgSyntaxTree(node: ISyntaxTreeNode): string {

View File

@ -3,7 +3,7 @@ import { LRLanguage } from '@codemirror/language';
import { parser } from './parser'; import { parser } from './parser';
import { RefEntity, RefSyntactic } from './parser.terms'; import { RefEntity, RefSyntactic } from './parser.terms';
export const ReferenceTokens: number[] = [RefSyntactic, RefEntity]; export const ReferenceTokens = [RefSyntactic, RefEntity] as const;
export const NaturalLanguage = LRLanguage.define({ export const NaturalLanguage = LRLanguage.define({
parser: parser, parser: parser,

View File

@ -3,7 +3,7 @@ import { LRLanguage } from '@codemirror/language';
import { parser } from './parser'; import { parser } from './parser';
import { Function, Global, Predicate } from './parser.terms'; import { Function, Global, Predicate } from './parser.terms';
export const GlobalTokens: number[] = [Global, Function, Predicate]; export const GlobalTokens = [Global, Function, Predicate] as const;
export const RSLanguage = LRLanguage.define({ export const RSLanguage = LRLanguage.define({
parser: parser, parser: parser,

View File

@ -4,4 +4,4 @@ import { DynamicEdge } from '@/components/flow/dynamic-edge';
export const ASTEdgeTypes: EdgeTypes = { export const ASTEdgeTypes: EdgeTypes = {
dynamic: DynamicEdge dynamic: DynamicEdge
}; } as const;

View File

@ -4,4 +4,4 @@ import { ASTNode } from './ast-node';
export const ASTNodeTypes: NodeTypes = { export const ASTNodeTypes: NodeTypes = {
token: ASTNode token: ASTNode
}; } as const;

View File

@ -6,4 +6,4 @@ import { CartesianEdge } from './cartesian-edge';
export const TMGraphEdgeTypes: EdgeTypes = { export const TMGraphEdgeTypes: EdgeTypes = {
boolean: BooleanEdge, boolean: BooleanEdge,
cartesian: CartesianEdge cartesian: CartesianEdge
}; } as const;

View File

@ -4,4 +4,4 @@ import { MGraphNode } from './mgraph-node';
export const TMGraphNodeTypes: NodeTypes = { export const TMGraphNodeTypes: NodeTypes = {
step: MGraphNode step: MGraphNode
}; } as const;

View File

@ -4,4 +4,4 @@ import { DynamicEdge } from '@/components/flow/dynamic-edge';
export const TGEdgeTypes: EdgeTypes = { export const TGEdgeTypes: EdgeTypes = {
termEdge: DynamicEdge termEdge: DynamicEdge
}; } as const;

View File

@ -4,4 +4,4 @@ import { TGNode } from './tg-node';
export const TGNodeTypes: NodeTypes = { export const TGNodeTypes: NodeTypes = {
concept: TGNode concept: TGNode
}; } as const;

View File

@ -59,4 +59,4 @@ export const usersApi = {
successMessage: infoMsg.changesSaved successMessage: infoMsg.changesSaved
} }
}) })
}; } as const;

View File

@ -36,4 +36,4 @@ export const APP_COLORS = {
fgPurple: 'var(--acc-fg-purple)', fgPurple: 'var(--acc-fg-purple)',
fgTeal: 'var(--acc-fg-teal)', fgTeal: 'var(--acc-fg-teal)',
fgOrange: 'var(--acc-fg-orange)' fgOrange: 'var(--acc-fg-orange)'
} } as const

View File

@ -4,4 +4,4 @@
*/ */
export const buildConstants = { export const buildConstants = {
backend: import.meta.env.VITE_PORTAL_BACKEND as string backend: import.meta.env.VITE_PORTAL_BACKEND as string
}; } as const;

View File

@ -72,7 +72,12 @@ export function printTree(tree: Tree): string {
} }
/** Retrieves a list of all nodes, containing given range and corresponding to a filter. */ /** Retrieves a list of all nodes, containing given range and corresponding to a filter. */
export function findEnvelopingNodes(start: number, finish: number, tree: Tree, filter?: number[]): SyntaxNode[] { export function findEnvelopingNodes(
start: number,
finish: number,
tree: Tree,
filter?: readonly number[]
): SyntaxNode[] {
const result: SyntaxNode[] = []; const result: SyntaxNode[] = [];
tree.cursor().iterate(node => { tree.cursor().iterate(node => {
if ((!filter || filter.includes(node.type.id)) && node.to >= start && node.from <= finish) { if ((!filter || filter.includes(node.type.id)) && node.to >= start && node.from <= finish) {
@ -87,7 +92,12 @@ export function findEnvelopingNodes(start: number, finish: number, tree: Tree, f
} }
/** Retrieves a list of all nodes, contained in given range and corresponding to a filter. */ /** Retrieves a list of all nodes, contained in given range and corresponding to a filter. */
export function findContainedNodes(start: number, finish: number, tree: Tree, filter?: number[]): SyntaxNode[] { export function findContainedNodes(
start: number,
finish: number,
tree: Tree,
filter?: readonly number[]
): SyntaxNode[] {
const result: SyntaxNode[] = []; const result: SyntaxNode[] = [];
tree.cursor().iterate(node => { tree.cursor().iterate(node => {
if ((!filter || filter.includes(node.type.id)) && node.to <= finish && node.from >= start) { if ((!filter || filter.includes(node.type.id)) && node.to <= finish && node.from >= start) {
@ -169,7 +179,7 @@ export class CodeMirrorWrapper {
/** /**
* Access list of SyntaxNodes contained in current selection. * Access list of SyntaxNodes contained in current selection.
*/ */
getContainedNodes(tokenFilter?: number[]): SyntaxNode[] { getContainedNodes(tokenFilter?: readonly number[]): SyntaxNode[] {
const selection = this.getSelection(); const selection = this.getSelection();
return findContainedNodes(selection.from, selection.to, syntaxTree(this.ref.view.state), tokenFilter); return findContainedNodes(selection.from, selection.to, syntaxTree(this.ref.view.state), tokenFilter);
} }
@ -177,7 +187,7 @@ export class CodeMirrorWrapper {
/** /**
* Access list of SyntaxNodes enveloping current selection. * Access list of SyntaxNodes enveloping current selection.
*/ */
getEnvelopingNodes(tokenFilter?: number[]): SyntaxNode[] { getEnvelopingNodes(tokenFilter?: readonly number[]): SyntaxNode[] {
const selection = this.getSelection(); const selection = this.getSelection();
return findEnvelopingNodes(selection.from, selection.to, syntaxTree(this.ref.view.state), tokenFilter); return findEnvelopingNodes(selection.from, selection.to, syntaxTree(this.ref.view.state), tokenFilter);
} }
@ -185,7 +195,7 @@ export class CodeMirrorWrapper {
/** /**
* Access list of SyntaxNodes contained in documents. * Access list of SyntaxNodes contained in documents.
*/ */
getAllNodes(tokenFilter?: number[]): SyntaxNode[] { getAllNodes(tokenFilter?: readonly number[]): SyntaxNode[] {
return findContainedNodes(0, this.ref.view.state.doc.length, syntaxTree(this.ref.view.state), tokenFilter); return findContainedNodes(0, this.ref.view.state.doc.length, syntaxTree(this.ref.view.state), tokenFilter);
} }
@ -194,7 +204,7 @@ export class CodeMirrorWrapper {
* *
* If tokenFilter is provided then minimal valid token is selected. * If tokenFilter is provided then minimal valid token is selected.
*/ */
fixSelection(tokenFilter?: number[]) { fixSelection(tokenFilter?: readonly number[]) {
const selection = this.getSelection(); const selection = this.getSelection();
if (tokenFilter) { if (tokenFilter) {
const nodes = findEnvelopingNodes(selection.from, selection.to, syntaxTree(this.ref.view.state), tokenFilter); const nodes = findEnvelopingNodes(selection.from, selection.to, syntaxTree(this.ref.view.state), tokenFilter);

View File

@ -2,9 +2,7 @@
* Module: Global constants. * Module: Global constants.
*/ */
/** /** Global application Parameters. The place where magic numbers are put to rest. */
* Global application Parameters. The place where magic numbers are put to rest.
*/
export const PARAMETER = { export const PARAMETER = {
smallScreen: 640, // == tailwind:sm smallScreen: 640, // == tailwind:sm
@ -26,46 +24,34 @@ export const PARAMETER = {
logicLabel: 'LOGIC', logicLabel: 'LOGIC',
errorNodeLabel: '[ERROR]', errorNodeLabel: '[ERROR]',
exteorVersion: '4.9.7' exteorVersion: '4.9.7'
}; } as const;
/** /** Numeric limitations. */
* Numeric limitations.
*/
export const limits = { export const limits = {
location_len: 500 location_len: 500
}; } as const;
/** /** Exteor file extension for RSForm. */
* Exteor file extension for RSForm.
*/
export const EXTEOR_TRS_FILE = '.trs'; export const EXTEOR_TRS_FILE = '.trs';
/** /** Regex patterns for data validation. */
* Regex patterns for data validation.
*/
export const patterns = { export const patterns = {
login: '^[a-zA-Z][a-zA-Z0-9_\\-]{1,}[a-zA-Z0-9]$' login: '^[a-zA-Z][a-zA-Z0-9_\\-]{1,}[a-zA-Z0-9]$'
}; } as const;
/** /** Local URIs. */
* Local URIs.
*/
export const resources = { export const resources = {
privacy_policy: '/privacy.pdf', privacy_policy: '/privacy.pdf',
logo: '/logo_full.svg', logo: '/logo_full.svg',
db_schema: '/db_schema.svg' db_schema: '/db_schema.svg'
}; } as const;
/** /** Youtube IDs for embedding. */
* Youtube IDs for embedding.
*/
export const youtube = { export const youtube = {
intro: '0Ty9mu9sOJo' intro: '0Ty9mu9sOJo'
}; } as const;
/** /** External URLs. */
* External URLs.
*/
export const external_urls = { export const external_urls = {
concept: 'https://www.acconcept.ru/', concept: 'https://www.acconcept.ru/',
exteor32: 'https://drive.google.com/open?id=1IHlMMwaYlAUBRSxU1RU_hXM5mFU9-oyK&usp=drive_fs', exteor32: 'https://drive.google.com/open?id=1IHlMMwaYlAUBRSxU1RU_hXM5mFU9-oyK&usp=drive_fs',
@ -81,11 +67,9 @@ export const external_urls = {
git_cctext: 'https://github.com/IRBorisov/cctext', git_cctext: 'https://github.com/IRBorisov/cctext',
mail_portal: 'mailto:portal@acconcept.ru', mail_portal: 'mailto:portal@acconcept.ru',
restAPI: 'https://api.portal.acconcept.ru' restAPI: 'https://api.portal.acconcept.ru'
}; } as const;
/** /** Global element ID. */
* Global element ID.
*/
export const globalIDs = { export const globalIDs = {
tooltip: 'global_tooltip', tooltip: 'global_tooltip',
value_tooltip: 'value_tooltip', value_tooltip: 'value_tooltip',
@ -96,11 +80,9 @@ export const globalIDs = {
constituenta_editor: 'constituenta_editor', constituenta_editor: 'constituenta_editor',
graph_schemas: 'graph_schemas_tooltip', graph_schemas: 'graph_schemas_tooltip',
user_dropdown: 'user_dropdown' user_dropdown: 'user_dropdown'
}; } as const;
/** /** Prefixes for generating unique keys for lists. */
* Prefixes for generating unique keys for lists.
*/
export const prefixes = { export const prefixes = {
page_size: 'page_size_', page_size: 'page_size_',
oss_list: 'oss_list_', oss_list: 'oss_list_',
@ -123,4 +105,4 @@ export const prefixes = {
user_editors: 'user_editors_', user_editors: 'user_editors_',
wordform_list: 'wordform_list_', wordform_list: 'wordform_list_',
rsedit_btn: 'rsedit_btn_' rsedit_btn: 'rsedit_btn_'
}; } as const;

View File

@ -41,7 +41,7 @@ export const infoMsg = {
operationExecuted: 'Операция выполнена', operationExecuted: 'Операция выполнена',
allOperationExecuted: 'Все операции выполнены', allOperationExecuted: 'Все операции выполнены',
constituentsDestroyed: (count: number) => `Конституенты удалены: ${count}` constituentsDestroyed: (count: number) => `Конституенты удалены: ${count}`
}; } as const;
/** /**
* UI error descriptors. * UI error descriptors.
@ -65,7 +65,7 @@ export const errorMsg = {
emptySubstitutions: 'Выберите хотя бы одно отождествление', emptySubstitutions: 'Выберите хотя бы одно отождествление',
aliasInvalid: 'Введите незанятое имя, соответствующее типу', aliasInvalid: 'Введите незанятое имя, соответствующее типу',
invalidResponse: 'Некорректный ответ сервера' invalidResponse: 'Некорректный ответ сервера'
}; } as const;
/** /**
* UI tooltip descriptors. * UI tooltip descriptors.
@ -73,7 +73,7 @@ export const errorMsg = {
export const tooltipText = { export const tooltipText = {
unsaved: 'Сохраните или отмените изменения', unsaved: 'Сохраните или отмените изменения',
shareItem: (isPublic: boolean) => (isPublic ? 'Поделиться схемой' : 'Поделиться можно только <br/>открытой схемой') shareItem: (isPublic: boolean) => (isPublic ? 'Поделиться схемой' : 'Поделиться можно только <br/>открытой схемой')
}; } as const;
/** /**
* UI prompt messages. * UI prompt messages.
@ -88,4 +88,4 @@ export const promptText = {
restoreArchive: 'При восстановлении архивной версии актуальная схему будет заменена. Продолжить?', restoreArchive: 'При восстановлении архивной версии актуальная схему будет заменена. Продолжить?',
ownerChange: ownerChange:
'Вы уверены, что хотите изменить владельца? Вы потеряете право управления данной схемой. Данное действие отменить нельзя' 'Вы уверены, что хотите изменить владельца? Вы потеряете право управления данной схемой. Данное действие отменить нельзя'
}; } as const;