R: Refactor term-graph preparing to extract shared components

This commit is contained in:
Ivan 2025-07-09 12:15:53 +03:00
parent acdd74001e
commit 3fb28e4867
16 changed files with 192 additions and 97 deletions

View File

@ -0,0 +1,52 @@
// Dialog for read-only display of the TermGraph for OSS. Currently ignores activeCst and only shows the schema graph.
import { ReactFlowProvider } from 'reactflow';
import { urls, useConceptNavigation } from '@/app';
// import { useDialogsStore } from '@/stores/dialogs';
import { type IRSForm } from '@/features/rsform';
import { TGFlow } from '@/features/rsform/pages/rsform-page/editor-term-graph/tg-flow';
import { RSTabID } from '@/features/rsform/pages/rsform-page/rsedit-context';
import { MiniButton } from '@/components/control';
import { IconRSForm } from '@/components/icons';
import { ModalView } from '@/components/modal';
import { useDialogsStore } from '@/stores/dialogs';
export interface DlgShowTermGraphProps {
schema: IRSForm;
}
export function DlgShowTermGraph() {
const { schema } = useDialogsStore(state => state.props as DlgShowTermGraphProps);
const hideDialog = useDialogsStore(state => state.hideDialog);
const router = useConceptNavigation();
function navigateToSchema() {
hideDialog();
router.push({
path: urls.schema_props({
id: schema.id,
tab: RSTabID.GRAPH
})
});
}
return (
<ModalView
className='relative w-[calc(100dvw-3rem)] h-[calc(100dvh-3rem)] cc-mask-sides'
fullScreen
header='Граф термов'
>
<MiniButton
title='Открыть концептуальную схему'
noPadding
icon={<IconRSForm size='1.25rem' className='text-primary' />}
onClick={navigateToSchema}
/>
<ReactFlowProvider>
{/* TGFlow expects schema from context, so you may need to refactor TGFlow to accept schema as prop if needed */}
<TGFlow />
</ReactFlowProvider>
</ModalView>
);
}

View File

@ -0,0 +1 @@
export * from './dlg-show-term-graph';

View File

@ -17,7 +17,6 @@ import { OssFlowContext } from './oss-flow-context';
const Z_BLOCK = 1;
const Z_SCHEMA = 10;
// TODO: decouple nodes and edges from controller callbacks
export const OssFlowState = ({ children }: React.PropsWithChildren) => {
const { schema, setSelected } = useOssEdit();
const { fitView } = useReactFlow();
@ -77,6 +76,7 @@ export const OssFlowState = ({ children }: React.PropsWithChildren) => {
target: target.nodeID,
type: edgeStraight ? 'straight' : 'simplebezier',
animated: edgeAnimate,
focusable: false,
targetHandle: source.x > target.x ? 'right' : 'left'
};
});

View File

@ -23,7 +23,6 @@ import { cn } from '@/components/utils';
import { useDialogsStore } from '@/stores/dialogs';
import { PARAMETER, prefixes } from '@/utils/constants';
import { type RO } from '@/utils/meta';
import { notImplemented } from '@/utils/utils';
interface ToolbarConstituentsProps {
schema: IRSForm;
@ -52,6 +51,7 @@ export function ToolbarConstituents({
const showCreateCst = useDialogsStore(state => state.showCreateCst);
const showDeleteCst = useDialogsStore(state => state.showDeleteCst);
const showTypeGraph = useDialogsStore(state => state.showShowTypeGraph);
const showTermGraph = useDialogsStore(state => state.showShowTermGraph);
const { moveConstituents } = useMoveConstituents();
const { createConstituenta } = useCreateConstituenta();
@ -225,7 +225,7 @@ export function ToolbarConstituents({
<MiniButton
icon={<IconTree size='1rem' className='hover:text-primary' />}
title='Граф термов'
onClick={notImplemented}
onClick={() => showTermGraph({ schema })}
/>
<MiniButton
icon={<IconTypeGraph size='1rem' className='hover:text-primary' />}

View File

@ -92,7 +92,6 @@ export function DlgEditCst() {
title='Редактировать в КС'
noPadding
icon={<IconRSForm size='1.25rem' className='text-primary' />}
className=''
onClick={navigateToTarget}
/>
<MiniButton

View File

@ -1,11 +1,35 @@
/**
* Module: Graph of Terms graphical representation.
*/
import { type Edge, type Node } from 'reactflow';
import dagre from '@dagrejs/dagre';
import { PARAMETER } from '@/utils/constants';
import { type IConstituenta } from '../../../../models/rsform';
import { type IConstituenta } from './rsform';
export function applyLayout(nodes: Node<IConstituenta>[], edges: Edge[], subLabels: boolean) {
export interface TGNodeState {
cst: IConstituenta;
focused: boolean;
}
/** Represents graph node. */
export interface TGNodeData extends Node {
id: string;
data: TGNodeState;
}
/** Represents graph node internal data. */
export interface TGNodeInternal {
id: string;
data: TGNodeState;
selected: boolean;
dragging: boolean;
xPos: number;
yPos: number;
}
export function applyLayout(nodes: Node<TGNodeState>[], edges: Edge[], subLabels: boolean) {
const dagreGraph = new dagre.graphlib.Graph().setDefaultEdgeLabel(() => ({}));
dagreGraph.setGraph({
rankdir: 'TB',

View File

@ -277,7 +277,7 @@ export function FormConstituenta({ disabled, id, toggleReset, schema, activeCst,
id='cst_convention'
{...register('item_data.convention')}
fitContent
className='max-h-32'
className='disabled:min-h-9 max-h-32'
spellCheck
label={isBasic ? 'Конвенция' : 'Комментарий'}
placeholder={disabled ? '' : isBasic ? 'Договоренность об интерпретации' : 'Пояснение разработчика'}

View File

@ -8,45 +8,19 @@ import { globalIDs } from '@/utils/constants';
import { colorBgGraphNode } from '../../../../colors';
import { labelCstTypification } from '../../../../labels';
import { type TGNodeInternal } from '../../../../models/graph-layout';
import { type IConstituenta } from '../../../../models/rsform';
import { useTermGraphStore } from '../../../../stores/term-graph';
import { useRSEdit } from '../../rsedit-context';
const DESCRIPTION_THRESHOLD = 15;
const LABEL_THRESHOLD = 3;
/**
* Represents graph AST node internal data.
*/
interface TGNodeInternal {
id: string;
data: IConstituenta;
selected: boolean;
dragging: boolean;
xPos: number;
yPos: number;
}
export function TGNode(node: TGNodeInternal) {
const { focusCst, setFocus, navigateCst } = useRSEdit();
const filter = useTermGraphStore(state => state.filter);
const coloring = useTermGraphStore(state => state.coloring);
const isFocused = focusCst?.id === node.data.id;
const label = node.data.alias;
const description = !filter.noText ? node.data.term_resolved : '';
function handleContextMenu(event: React.MouseEvent<HTMLElement>) {
event.stopPropagation();
event.preventDefault();
setFocus(isFocused ? null : node.data);
}
function handleDoubleClick(event: React.MouseEvent) {
event.preventDefault();
event.stopPropagation();
navigateCst(node.data.id);
}
const label = node.data.cst.alias;
const description = !filter.noText ? node.data.cst.term_resolved : '';
return (
<>
@ -54,21 +28,19 @@ export function TGNode(node: TGNodeInternal) {
<div
className={clsx(
'w-full h-full cursor-default flex items-center justify-center rounded-full',
isFocused && 'border-[2px] border-selected',
node.data.focused && 'border-[2px] border-selected',
label.length > LABEL_THRESHOLD ? 'text-[12px]/[16px]' : 'text-[14px]/[20px]'
)}
style={{
backgroundColor: node.selected
? APP_COLORS.bgActiveSelection
: isFocused
: node.data.focused
? APP_COLORS.bgPurple
: colorBgGraphNode(node.data, coloring)
: colorBgGraphNode(node.data.cst, coloring)
}}
data-tooltip-id={globalIDs.tooltip}
data-tooltip-html={describeCstNode(node.data)}
data-tooltip-html={describeCstNode(node.data.cst)}
data-tooltip-hidden={node.dragging}
onContextMenu={handleContextMenu}
onDoubleClick={handleDoubleClick}
>
<div className='cc-node-label'>{label}</div>
</div>
@ -80,8 +52,6 @@ export function TGNode(node: TGNodeInternal) {
'pointer-events-none',
description.length > DESCRIPTION_THRESHOLD ? 'text-[10px]/[12px]' : 'text-[12px]/[16px]'
)}
onContextMenu={handleContextMenu}
onDoubleClick={handleDoubleClick}
>
<div className='absolute top-0 px-[4px] left-0 text-center w-full line-clamp-3 hover:line-clamp-none'>
{description}

View File

@ -1,15 +1,18 @@
import { useLibrary } from '@/features/library/backend/use-library';
import { type IRSForm } from '@/features/rsform/models/rsform';
import { Tooltip } from '@/components/container';
import { IconHelp } from '@/components/icons';
import { globalIDs, prefixes } from '@/utils/constants';
import { colorBgSchemas } from '../../../colors';
import { useRSEdit } from '../rsedit-context';
export function SchemasGuide() {
interface SchemasGuideProps {
schema: IRSForm;
}
export function SchemasGuide({ schema }: SchemasGuideProps) {
const libraryItems = useLibrary().items;
const schema = useRSEdit().schema;
const schemas = (() => {
const processed = new Set<number>();

View File

@ -1,23 +1,32 @@
import { HelpTopic } from '@/features/help';
import { BadgeHelp } from '@/features/help/components/badge-help';
import { type IRSForm } from '@/features/rsform/models/rsform';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/input/select';
import { cn } from '@/components/utils';
import { mapLabelColoring } from '../../../labels';
import { useTermGraphStore } from '../../../stores/term-graph';
import { SchemasGuide } from './schemas-guide';
export function SelectColoring() {
interface SelectColoringProps {
className?: string;
schema: IRSForm;
}
export function SelectColoring({ className, schema }: SelectColoringProps) {
const coloring = useTermGraphStore(state => state.coloring);
const setColoring = useTermGraphStore(state => state.setColoring);
return (
<div className='relative border rounded-b-none select-none bg-input rounded-t-md pointer-events-auto'>
<div
className={cn('relative border rounded-b-none select-none bg-input rounded-t-md pointer-events-auto', className)}
>
<div className='absolute z-pop right-10 h-9 flex items-center'>
{coloring === 'status' ? <BadgeHelp topic={HelpTopic.UI_CST_STATUS} contentClass='min-w-100' /> : null}
{coloring === 'type' ? <BadgeHelp topic={HelpTopic.UI_CST_CLASS} contentClass='min-w-100' /> : null}
{coloring === 'schemas' ? <SchemasGuide /> : null}
{coloring === 'schemas' ? <SchemasGuide schema={schema} /> : null}
</div>
<Select onValueChange={setColoring} defaultValue={coloring}>

View File

@ -3,6 +3,8 @@
import { useEffect, useRef } from 'react';
import { type Edge, MarkerType, type Node, useEdgesState, useNodesState, useOnSelectionChange } from 'reactflow';
import { applyLayout, type TGNodeData } from '@/features/rsform/models/graph-layout';
import { DiagramFlow, useReactFlow, useStoreApi } from '@/components/flow/diagram-flow';
import { useMainHeight } from '@/stores/app-layout';
import { PARAMETER } from '@/utils/constants';
@ -10,13 +12,11 @@ import { withPreventDefault } from '@/utils/utils';
import { useMutatingRSForm } from '../../../backend/use-mutating-rsform';
import { ToolbarGraphSelection } from '../../../components/toolbar-graph-selection';
import { type IConstituenta } from '../../../models/rsform';
import { isBasicConcept } from '../../../models/rsform-api';
import { useTermGraphStore } from '../../../stores/term-graph';
import { useRSEdit } from '../rsedit-context';
import { TGEdgeTypes } from './graph/tg-edge-types';
import { applyLayout } from './graph/tg-layout';
import { TGNodeTypes } from './graph/tg-node-types';
import { SelectColoring } from './select-coloring';
import { ToolbarFocusedCst } from './toolbar-focused-cst';
@ -40,13 +40,24 @@ export function TGFlow() {
const store = useStoreApi();
const { addSelectedNodes } = store.getState();
const isProcessing = useMutatingRSForm();
const { isContentEditable, schema, selected, setSelected, promptDeleteCst, focusCst, setFocus, deselectAll } =
useRSEdit();
const {
isContentEditable,
schema,
selected,
setSelected,
promptDeleteCst,
focusCst,
setFocus,
deselectAll,
navigateCst
} = useRSEdit();
const [nodes, setNodes, onNodesChange] = useNodesState([]);
const [edges, setEdges] = useEdgesState([]);
const [nodes, setNodes, onNodesChange] = useNodesState<Node>([]);
const [edges, setEdges] = useEdgesState<Edge>([]);
const filter = useTermGraphStore(state => state.filter);
const toggleFocusInputs = useTermGraphStore(state => state.toggleFocusInputs);
const toggleFocusOutputs = useTermGraphStore(state => state.toggleFocusOutputs);
const { filteredGraph, hidden } = useFilteredGraph();
function onSelectionChange({ nodes }: { nodes: Node[] }) {
@ -65,7 +76,7 @@ export function TGFlow() {
if (!viewportInitialized) {
return;
}
const newNodes: Node<IConstituenta>[] = [];
const newNodes: Node[] = [];
filteredGraph.nodes.forEach(node => {
const cst = schema.cstByID.get(node.id);
if (cst) {
@ -73,7 +84,7 @@ export function TGFlow() {
id: String(node.id),
type: 'concept',
position: { x: 0, y: 0 },
data: cst
data: { cst: cst, focused: focusCst?.id === cst.id }
});
}
});
@ -144,11 +155,30 @@ export function TGFlow() {
}
}
function handleNodeContextMenu(event: React.MouseEvent<Element>, node: TGNodeData) {
event.preventDefault();
event.stopPropagation();
setFocus(focusCst?.id === node.data.cst.id ? null : node.data.cst);
}
function handleNodeDoubleClick(event: React.MouseEvent<Element>, node: TGNodeData) {
event.preventDefault();
event.stopPropagation();
navigateCst(node.data.cst.id);
}
return (
<div className='relative' tabIndex={-1} onKeyDown={handleKeyDown}>
<div className='cc-tab-tools flex flex-col items-center rounded-b-2xl backdrop-blur-xs'>
<ToolbarTermGraph />
<ToolbarFocusedCst />
<ToolbarFocusedCst
focus={focusCst}
resetFocus={() => setFocus(null)}
showInputs={filter.focusShowInputs}
toggleShowInputs={toggleFocusInputs}
showOutputs={filter.focusShowOutputs}
toggleShowOutputs={toggleFocusOutputs}
/>
{!focusCst ? (
<ToolbarGraphSelection
graph={schema.graph}
@ -167,7 +197,7 @@ export function TGFlow() {
<span className='px-2 pb-1 select-none whitespace-nowrap backdrop-blur-xs rounded-xl w-fit'>
Выбор {selected.length} из {schema.stats?.count_all ?? 0}
</span>
<SelectColoring />
<SelectColoring schema={schema} />
<ViewHidden items={hidden} />
</div>
@ -180,6 +210,8 @@ export function TGFlow() {
nodeTypes={TGNodeTypes}
edgeTypes={TGEdgeTypes}
onContextMenu={event => event.preventDefault()}
onNodeContextMenu={handleNodeContextMenu}
onNodeDoubleClick={handleNodeDoubleClick}
/>
</div>
);

View File

@ -1,45 +1,40 @@
'use client';
import { type IConstituenta } from '@/features/rsform/models/rsform';
import { MiniButton } from '@/components/control';
import { IconGraphInputs, IconGraphOutputs, IconReset } from '@/components/icons';
import { cn } from '@/components/utils';
import { useTermGraphStore } from '../../../stores/term-graph';
import { useRSEdit } from '../rsedit-context';
interface ToolbarFocusedCstProps {
className?: string;
focus: IConstituenta | null;
resetFocus: () => void;
export function ToolbarFocusedCst() {
const { setFocus, focusCst } = useRSEdit();
showInputs: boolean;
toggleShowInputs: () => void;
const filter = useTermGraphStore(state => state.filter);
const setFilter = useTermGraphStore(state => state.setFilter);
showOutputs: boolean;
toggleShowOutputs: () => void;
}
function resetFocus() {
setFocus(null);
}
function handleShowInputs() {
setFilter({
...filter,
focusShowInputs: !filter.focusShowInputs
});
}
function handleShowOutputs() {
setFilter({
...filter,
focusShowOutputs: !filter.focusShowOutputs
});
}
if (!focusCst) {
export function ToolbarFocusedCst({
focus,
resetFocus,
className,
showInputs,
toggleShowInputs,
showOutputs,
toggleShowOutputs
}: ToolbarFocusedCstProps) {
if (!focus) {
return null;
}
return (
<div className='flex items-center cc-icons'>
<div className={cn('flex items-center cc-icons', className)}>
<div className='w-31 mt-0.5 text-right select-none text-(--acc-fg-purple)'>
<span>
Фокус
<b> {focusCst.alias} </b>
<b> {focus.alias} </b>
</span>
</div>
@ -49,14 +44,14 @@ export function ToolbarFocusedCst() {
onClick={resetFocus}
/>
<MiniButton
title={filter.focusShowInputs ? 'Скрыть поставщиков' : 'Отобразить поставщиков'}
icon={<IconGraphInputs size='1.25rem' className={filter.focusShowInputs ? 'icon-green' : 'icon-primary'} />}
onClick={handleShowInputs}
title={showInputs ? 'Скрыть поставщиков' : 'Отобразить поставщиков'}
icon={<IconGraphInputs size='1.25rem' className={showInputs ? 'icon-green' : 'icon-primary'} />}
onClick={toggleShowInputs}
/>
<MiniButton
title={filter.focusShowOutputs ? 'Скрыть потребителей' : 'Отобразить потребителей'}
icon={<IconGraphOutputs size='1.25rem' className={filter.focusShowOutputs ? 'icon-green' : 'icon-primary'} />}
onClick={handleShowOutputs}
title={showOutputs ? 'Скрыть потребителей' : 'Отобразить потребителей'}
icon={<IconGraphOutputs size='1.25rem' className={showOutputs ? 'icon-green' : 'icon-primary'} />}
onClick={toggleShowOutputs}
/>
</div>
);

View File

@ -14,7 +14,7 @@ export function useFilteredGraph() {
}
// ====== Internals =========
function produceFilteredGraph(schema: IRSForm, params: GraphFilterParams, focusCst: IConstituenta | null) {
export function produceFilteredGraph(schema: IRSForm, params: GraphFilterParams, focusCst: IConstituenta | null) {
const filtered = schema.graph.clone();
const allowedTypes: CstType[] = (() => {
const result: CstType[] = [];

View File

@ -9,7 +9,7 @@ export const RSTabID = {
CARD: 0,
CST_LIST: 1,
CST_EDIT: 2,
TERM_GRAPH: 3
GRAPH: 3
} as const;
export type RSTabID = (typeof RSTabID)[keyof typeof RSTabID];

View File

@ -32,6 +32,8 @@ export interface GraphFilterParams {
interface TermGraphStore {
filter: GraphFilterParams;
setFilter: (value: GraphFilterParams) => void;
toggleFocusInputs: () => void;
toggleFocusOutputs: () => void;
foldHidden: boolean;
toggleFoldHidden: () => void;
@ -63,6 +65,10 @@ export const useTermGraphStore = create<TermGraphStore>()(
allowTheorem: true
},
setFilter: value => set({ filter: value }),
toggleFocusInputs: () =>
set(state => ({ filter: { ...state.filter, focusShowInputs: !state.filter.focusShowInputs } })),
toggleFocusOutputs: () =>
set(state => ({ filter: { ...state.filter, focusShowOutputs: !state.filter.focusShowOutputs } })),
foldHidden: false,
toggleFoldHidden: () => set(state => ({ foldHidden: !state.foldHidden })),

View File

@ -12,6 +12,7 @@ import { type DlgDeleteOperationProps } from '@/features/oss/dialogs/dlg-delete-
import { type DlgEditBlockProps } from '@/features/oss/dialogs/dlg-edit-block';
import { type DlgEditOperationProps } from '@/features/oss/dialogs/dlg-edit-operation/dlg-edit-operation';
import { type DlgRelocateConstituentsProps } from '@/features/oss/dialogs/dlg-relocate-constituents';
import { type DlgShowTermGraphProps } from '@/features/oss/dialogs/dlg-show-term-graph/dlg-show-term-graph';
import { type DlgCreateCstProps } from '@/features/rsform/dialogs/dlg-create-cst/dlg-create-cst';
import { type DlgCstTemplateProps } from '@/features/rsform/dialogs/dlg-cst-template/dlg-cst-template';
import { type DlgDeleteCstProps } from '@/features/rsform/dialogs/dlg-delete-cst/dlg-delete-cst';
@ -61,7 +62,8 @@ export const DialogType = {
SHOW_QR_CODE: 21,
SHOW_AST: 22,
SHOW_TYPE_GRAPH: 23,
GRAPH_PARAMETERS: 24
GRAPH_PARAMETERS: 24,
SHOW_TERM_GRAPH: 25
} as const;
export type DialogType = (typeof DialogType)[keyof typeof DialogType];
@ -88,6 +90,7 @@ interface DialogsStore {
showInlineSynthesis: (props: DlgInlineSynthesisProps) => void;
showShowAST: (props: DlgShowASTProps) => void;
showShowTypeGraph: (props: DlgShowTypeGraphProps) => void;
showShowTermGraph: (props: DlgShowTermGraphProps) => void;
showChangeInputSchema: (props: DlgChangeInputSchemaProps) => void;
showChangeLocation: (props: DlgChangeLocationProps) => void;
showCloneLibraryItem: (props: DlgCloneLibraryItemProps) => void;
@ -127,6 +130,7 @@ export const useDialogsStore = create<DialogsStore>()(set => ({
showInlineSynthesis: props => set({ active: DialogType.INLINE_SYNTHESIS, props: props }),
showShowAST: props => set({ active: DialogType.SHOW_AST, props: props }),
showShowTypeGraph: props => set({ active: DialogType.SHOW_TYPE_GRAPH, props: props }),
showShowTermGraph: props => set({ active: DialogType.SHOW_TERM_GRAPH, props: props }),
showChangeInputSchema: props => set({ active: DialogType.CHANGE_INPUT_SCHEMA, props: props }),
showChangeLocation: props => set({ active: DialogType.CHANGE_LOCATION, props: props }),
showCloneLibraryItem: props => set({ active: DialogType.CLONE_LIBRARY_ITEM, props: props }),