refactoring+

This commit is contained in:
Gregory Bednov 2025-01-29 00:04:11 +03:00
commit 1e9a6d3052
11 changed files with 561 additions and 376 deletions

10
.prettierrc Normal file
View file

@ -0,0 +1,10 @@
{
"semi": false,
"singleQuote": true,
"trailingComma": "es5",
"tabWidth": 2,
"useTabs": false,
"bracketSpacing": true,
"arrowParens": "always",
"printWidth": 80
}

View file

@ -1,141 +1,212 @@
const stateInstrument = {
фиксация: 'НаМесте',
типПрибора: 'Величина',
величина: 'Напряжение',
уточнение: null,
функции: []
};
export const stateInstrument = {
фиксация: 'НаМесте',
типПрибора: 'Величина',
величина: 'Напряжение',
являетсяПАЗ: false,
уточнение: null,
функции: [] as string[],
}
const stateMechanism = {
ручной: false,
направление: null as string | null
};
export const stateMechanism = {
ручной: false,
направление: null as string | null,
}
// Настройки для выбора значений
const функцииПоТипу = {
ВыполняемаяФункция: [
'Сигнализация'
, 'АвтоматическоеРегулирование'
, 'ВеличинаОтклоненияОтЗаданной'
, 'Регистрация'
],
ФункциональныйПризнак: [
'ЧувствительныйЭлемент'
, 'Преобразование'
, 'ПервичныйПоказывающийПрибор'
, 'СтанцияУправления'
, 'ВключениеОтключениеПереключение'
]
};
// Создание элементов формы
export function createInstrumentForm(container: HTMLElement | null) {
const form = document.createElement('form');
// Фиксация
const fixationLabel = document.createElement('label');
fixationLabel.innerText = 'Фиксация:';
const fixationSelect = document.createElement('select');
fixationSelect.innerHTML = '<option value="НаМесте">На месте</option><option value="НаЩите">На щите</option>';
fixationSelect.value = stateInstrument.фиксация;
fixationSelect.addEventListener('change', (e) => {
const target = e.target as HTMLInputElement;
stateInstrument.фиксация = target.value;
});
fixationLabel.appendChild(fixationSelect);
form.appendChild(fixationLabel);
// Тип прибора
const typeLabel = document.createElement('label');
typeLabel.innerText = 'Тип прибора:';
const typeSelect = document.createElement('select');
typeSelect.innerHTML = '<option value="Величина">Величина</option><option value="Мультивеличина">Мультивеличина</option>';
typeSelect.value = stateInstrument.типПрибора;
typeSelect.addEventListener('change', (e) => {
const target = e.target as HTMLInputElement;
stateInstrument.типПрибора = target.value;
});
typeLabel.appendChild(typeSelect);
form.appendChild(typeLabel);
// Величина
const magnitudeLabel = document.createElement('label');
magnitudeLabel.innerText = 'Величина:';
const magnitudeSelect = document.createElement('select');
const choices = [
{ value: 'A', label: 'Анализ, качество' },
{ value: 'B', label: 'Пламя, горение' },
{ value: 'C', label: 'Дополнительная величина (C)' },
{ value: 'D', label: 'Дополнительная величина (D)' },
{ value: 'E', label: 'Напряжение' },
{ value: 'F', label: 'Расход' },
{ value: 'G', label: 'Дополнительная величина (G)' },
{ value: 'H', label: 'Ручное воздействие' },
{ value: 'I', label: 'Ток' },
{ value: 'J', label: 'Мощность' },
{ value: 'K', label: 'Время' },
{ value: 'L', label: 'Уровень' },
{ value: 'M', label: 'Дополнительная величина (N)' },
{ value: 'N', label: 'Дополнительная величина (N))' },
{ value: 'O', label: 'Дополнительная величина (O)' },
{ value: 'P', label: 'Давление' },
{ value: 'Q', label: 'Количество' },
{ value: 'E', label: 'Радиоактивность' },
{ value: 'S', label: 'Скорость, частота' },
{ value: 'T', label: 'Температура' },
{ value: 'U', label: 'Разнородные величины' }, // несколько величин ТОЛЬКО здесь
{ value: 'V', label: 'Вибрация' },
{ value: 'W', label: 'Вес' },
{ value: 'X', label: 'Дополнительная величина (нерекомендованная буква X)' },
{ value: 'Y', label: 'Событие' },
{ value: 'Z', label: 'Размер' }
];
choices.forEach(element => {
const opt = document.createElement<'option'>('option')
opt.setAttribute('value', element.value)
opt.appendChild(document.createTextNode(element.label))
magnitudeSelect.appendChild(opt)
});
magnitudeSelect.addEventListener('change', (e) => {
const target = e.target as HTMLInputElement;
stateInstrument.величина = target.value;
});
magnitudeLabel.appendChild(magnitudeSelect);
form.appendChild(magnitudeLabel);
// Добавить форму на страницу
container?.appendChild(form);
ВыполняемаяФункция: [
'Сигнализация',
'АвтоматическоеРегулирование',
'ВеличинаОтклоненияОтЗаданной',
'Регистрация',
],
ФункциональныйПризнак: [
'ЧувствительныйЭлемент',
'Преобразование',
'ПервичныйПоказывающийПрибор',
'СтанцияУправления',
'ВключениеОтключениеПереключение',
],
}
export function createMechanismForm(container: HTMLElement | null) {
const form = document.createElement('form');
export function createInstrumentForm(): HTMLElement {
const form = document.createElement('form')
// Ручное управление
const manualControlLabel = document.createElement('label');
manualControlLabel.innerText = 'Имеет ручное управление:';
const manualControlCheckbox = document.createElement('input');
manualControlCheckbox.type = 'checkbox';
manualControlCheckbox.checked = stateMechanism.ручной;
manualControlCheckbox.addEventListener('change', (e) => {
const target = e.target as HTMLInputElement;
stateMechanism.ручной = target.checked;
});
manualControlLabel.appendChild(manualControlCheckbox);
form.appendChild(manualControlLabel);
// Фиксация
const fixationLabel = document.createElement('label')
fixationLabel.innerText = 'Фиксация:'
const fixationSelect = document.createElement('select')
fixationSelect.innerHTML =
'<option value="НаМесте">На месте</option><option value="НаЩите">На щите</option>'
fixationSelect.value = stateInstrument.фиксация
fixationSelect.addEventListener('change', (e) => {
const target = e.target as HTMLInputElement
stateInstrument.фиксация = target.value
})
fixationLabel.appendChild(fixationSelect)
form.appendChild(fixationLabel)
// Направление
const directionLabel = document.createElement('label');
directionLabel.innerText = 'Направление:';
const directionSelect = document.createElement('select');
directionSelect.innerHTML = '<option value="Открывается">Открывается</option><option value="Закрывается">Закрывается</option><option value="ОстаётсяНаМесте">Остаётся на месте</option>';
directionSelect.value = stateMechanism.направление || '';
directionSelect.addEventListener('change', (e) => {
const target = e.target as HTMLInputElement;
stateMechanism.направление = target.value;
});
directionLabel.appendChild(directionSelect);
form.appendChild(directionLabel);
const manualControlLabel = document.createElement('label')
manualControlLabel.innerText = 'Является ПАЗ:'
const manualControlCheckbox = document.createElement('input')
manualControlCheckbox.type = 'checkbox'
manualControlCheckbox.checked = stateInstrument.являетсяПАЗ
manualControlCheckbox.addEventListener('change', (e) => {
const target = e.target as HTMLInputElement
stateInstrument.являетсяПАЗ = target.checked
})
manualControlLabel.appendChild(manualControlCheckbox)
form.appendChild(manualControlLabel)
// Добавить форму на страницу
container?.appendChild(form);
}
// Тип прибора
const typeLabel = document.createElement('label')
typeLabel.innerText = 'Тип прибора:'
const typeSelect = document.createElement('select')
typeSelect.innerHTML =
'<option value="Величина">Величина</option><option value="Мультивеличина">Мультивеличина</option>'
typeSelect.value = stateInstrument.типПрибора
typeSelect.addEventListener('change', (e) => {
const target = e.target as HTMLInputElement
stateInstrument.типПрибора = target.value
})
typeLabel.appendChild(typeSelect)
form.appendChild(typeLabel)
// Величина
const magnitudeLabel = document.createElement('label')
magnitudeLabel.innerText = 'Величина:'
const magnitudeSelect = document.createElement('select')
const choices = [
{ value: 'A', label: 'Анализ, качество' },
{ value: 'B', label: 'Пламя, горение' },
{ value: 'C', label: 'Дополнительная величина (C)' },
{ value: 'D', label: 'Дополнительная величина (D)' },
{ value: 'E', label: 'Напряжение' },
{ value: 'F', label: 'Расход' },
{ value: 'G', label: 'Дополнительная величина (G)' },
{ value: 'H', label: 'Ручное воздействие' },
{ value: 'I', label: 'Ток' },
{ value: 'J', label: 'Мощность' },
{ value: 'K', label: 'Время' },
{ value: 'L', label: 'Уровень' },
{ value: 'M', label: 'Дополнительная величина (N)' },
{ value: 'N', label: 'Дополнительная величина (N))' },
{ value: 'O', label: 'Дополнительная величина (O)' },
{ value: 'P', label: 'Давление' },
{ value: 'Q', label: 'Количество' },
{ value: 'E', label: 'Радиоактивность' },
{ value: 'S', label: 'Скорость, частота' },
{ value: 'T', label: 'Температура' },
{ value: 'U', label: 'Разнородные величины' },
{ value: 'V', label: 'Вибрация' },
{ value: 'W', label: 'Вес' },
{
value: 'X',
label: 'Дополнительная величина (нерекомендованная буква X)',
},
{ value: 'Y', label: 'Событие' },
{ value: 'Z', label: 'Размер' },
]
choices.forEach((element) => {
const opt = document.createElement('option')
opt.setAttribute('value', element.value)
opt.appendChild(document.createTextNode(element.label))
magnitudeSelect.appendChild(opt)
})
magnitudeSelect.value = stateInstrument.величина
magnitudeSelect.addEventListener('change', (e) => {
const target = e.target as HTMLInputElement
stateInstrument.величина = target.value
})
magnitudeLabel.appendChild(magnitudeSelect)
form.appendChild(magnitudeLabel)
// Функции
const functionsLabel = document.createElement('label')
functionsLabel.innerText = 'Функции:'
const functionsContainer = document.createElement('div')
const updateFunctionsUI = () => {
functionsContainer.innerHTML = ''
stateInstrument.функции.forEach((func, index) => {
const funcWrapper = document.createElement('div')
funcWrapper.style.display = 'flex'
funcWrapper.style.alignItems = 'center'
const funcSelect = document.createElement('select')
функцииПоТипу.ВыполняемаяФункция
.concat(функцииПоТипу.ФункциональныйПризнак)
.forEach((f) => {
const option = document.createElement('option')
option.value = f
option.textContent = f
funcSelect.appendChild(option)
})
funcSelect.value = func
funcSelect.addEventListener('change', (e) => {
const target = e.target as HTMLSelectElement
stateInstrument.функции[index] = target.value
})
const removeButton = document.createElement('button')
removeButton.type = 'button'
removeButton.innerText = 'x'
removeButton.addEventListener('click', () => {
stateInstrument.функции.splice(index, 1)
updateFunctionsUI()
})
funcWrapper.appendChild(funcSelect)
funcWrapper.appendChild(removeButton)
functionsContainer.appendChild(funcWrapper)
})
}
const addButton = document.createElement('button')
addButton.type = 'button'
addButton.innerText = '+'
addButton.addEventListener('click', () => {
stateInstrument.функции.push('')
updateFunctionsUI()
})
updateFunctionsUI()
functionsLabel.appendChild(functionsContainer)
form.appendChild(functionsLabel)
form.appendChild(addButton)
return form
}
export function createMechanismForm(): HTMLElement {
const form = document.createElement('form')
// Ручное управление
const manualControlLabel = document.createElement('label')
manualControlLabel.innerText = 'Имеет ручное управление:'
const manualControlCheckbox = document.createElement('input')
manualControlCheckbox.type = 'checkbox'
manualControlCheckbox.checked = stateMechanism.ручной
manualControlCheckbox.addEventListener('change', (e) => {
const target = e.target as HTMLInputElement
stateMechanism.ручной = target.checked
})
manualControlLabel.appendChild(manualControlCheckbox)
form.appendChild(manualControlLabel)
// Направление
const directionLabel = document.createElement('label')
directionLabel.innerText = 'Направление:'
const directionSelect = document.createElement('select')
directionSelect.innerHTML =
'<option value="Открывается">Открывается</option><option value="Закрывается">Закрывается</option><option value="ОстаётсяНаМесте">Остаётся на месте</option>'
directionSelect.value = stateMechanism.направление || ''
directionSelect.addEventListener('change', (e) => {
const target = e.target as HTMLInputElement
stateMechanism.направление = target.value
})
directionLabel.appendChild(directionSelect)
form.appendChild(directionLabel)
return form
}

View file

@ -20,31 +20,29 @@ import ShapeRendererModule from './modules/ShapeRendererModule'
import OutlineModule from './modules/OutlineModule'
export default function Editor(container: HTMLElement): Diagram {
return new Diagram(
{
canvas: {container},
modules: [
BendpointMoveModule
, ConnectModule
, ContextPadModule
, CreateModule
, GlobalConnectModule
, LassoToolModule
, ModelingModule
, MoveCanvasModule
, MoveModule
, PaletteModule
return new Diagram({
canvas: { container },
modules: [
BendpointMoveModule,
ConnectModule,
ContextPadModule,
CreateModule,
GlobalConnectModule,
LassoToolModule,
ModelingModule,
MoveCanvasModule,
MoveModule,
PaletteModule,
//, ResizeModule
, RulesModule
, SelectionModule
, ZoomScrollModule
, StyleModule
, ManhattanConnectionModule
, PaletteModule
, GlobalConnectRulesModule
, ShapeRendererModule
, OutlineModule
]
}
)
RulesModule,
SelectionModule,
ZoomScrollModule,
StyleModule,
ManhattanConnectionModule,
PaletteModule,
GlobalConnectRulesModule,
ShapeRendererModule,
OutlineModule,
],
})
}

View file

@ -1,21 +1,33 @@
import {createInstrumentForm, createMechanismForm} from './addObjectForm'
import {
stateInstrument,
stateMechanism,
createInstrumentForm,
createMechanismForm,
} from './addObjectForm'
import Editor from './editor'
import 'diagram-js/assets/diagram-js.css'
const instrumentContainer = document.getElementById('instrument-form')
const mechanismContainer = document.getElementById('mechanism-form')
const instrMechContainer = document.getElementById('instrument-form')
const instrument = createInstrumentForm()
const mechanism = createMechanismForm()
createInstrumentForm(instrumentContainer)
createMechanismForm(mechanismContainer)
instrument.onchange = function () {
console.log(stateInstrument)
}
mechanism.onchange = function () {
console.log(stateMechanism)
}
instrMechContainer?.appendChild(instrument)
instrMechContainer?.appendChild(mechanism)
const diagramElement = document.getElementById('diagram')
if (!diagramElement) {
throw new Error('Element with ID "diagram" not found in DOM.')
}
diagramElement.style.width='297mm'
diagramElement.style.height='210mm'
diagramElement.style.border='solid'
diagramElement.style.borderColor='canvastext'
diagramElement.style.borderWidth='1px'
diagramElement.style.width = '297mm'
diagramElement.style.height = '210mm'
diagramElement.style.border = 'solid'
diagramElement.style.borderColor = 'canvastext'
diagramElement.style.borderWidth = '1px'
const diagram = Editor(diagramElement)
export default diagram
export default diagram

View file

@ -1,35 +1,34 @@
import RuleProvider from 'diagram-js/lib/features/rules/RuleProvider';
import RuleProvider from 'diagram-js/lib/features/rules/RuleProvider'
class CustomGlobalConnectRules extends RuleProvider {
static $inject = ['eventBus'];
static $inject = ['eventBus']
constructor(eventBus: any) {
super(eventBus);
super(eventBus)
}
init(): void {
this.addRule('connection.start', (context) => {
return true;
const { source } = context;
return true
const { source } = context
if (source?.businessObject?.type === 'custom:connectable') {
return true; // Разрешить соединение
return true // Разрешить соединение
}
return false; // Запретить соединение
});
return false // Запретить соединение
})
// Правило для создания соединения
this.addRule('connection.create', (context) => {
// const { source, target } = context;
return { type: 'Connection' };
return false; // Запретить соединение
});
// const { source, target } = context;
return { type: 'Connection' }
return false // Запретить соединение
})
}
}
export default {
__init__: ['customGlobalConnectRules'],
customGlobalConnectRules: ['type', CustomGlobalConnectRules]
};
customGlobalConnectRules: ['type', CustomGlobalConnectRules],
}

View file

@ -1,53 +1,54 @@
import { connectPoints } from 'diagram-js/lib/layout/ManhattanLayout';
import Modeling from 'diagram-js/lib/features/modeling/Modeling';
import EventBus from 'diagram-js/lib/core/EventBus';
import type { Connection } from 'diagram-js/lib/model/Types';
import { connectPoints } from 'diagram-js/lib/layout/ManhattanLayout'
import Modeling from 'diagram-js/lib/features/modeling/Modeling'
import EventBus from 'diagram-js/lib/core/EventBus'
import type { Connection } from 'diagram-js/lib/model/Types'
export function updateWaypointsByManhattan (connection: Connection, modeling: Modeling ): void {
export function updateWaypointsByManhattan(
connection: Connection,
modeling: Modeling
): void {
if (connection.source && connection.target) {
const x0 = connection.source.x + connection.source.width / 2;
const x1 = connection.target.x + connection.target.width / 2;
const y0 = connection.source.y + connection.source.height / 2;
const y1 = connection.target.y + connection.target.height / 2;
const x2 = (Math.abs(x0-x1) < 5) ? x0 : x1;
const y2 = (Math.abs(y0-y1) < 5) ? y0 : y1;
const waypoints = connectPoints(
{ x: x0, y: y0 },
{ x: x2, y: y2 });
const x0 = connection.source.x + connection.source.width / 2
const x1 = connection.target.x + connection.target.width / 2
const y0 = connection.source.y + connection.source.height / 2
const y1 = connection.target.y + connection.target.height / 2
const x2 = Math.abs(x0 - x1) < 5 ? x0 : x1
const y2 = Math.abs(y0 - y1) < 5 ? y0 : y1
const waypoints = connectPoints({ x: x0, y: y0 }, { x: x2, y: y2 })
const hasChanged = JSON.stringify(connection.waypoints) != JSON.stringify(waypoints);
if (hasChanged) {
modeling.updateWaypoints(connection, waypoints)
}
const hasChanged =
JSON.stringify(connection.waypoints) != JSON.stringify(waypoints)
if (hasChanged) {
modeling.updateWaypoints(connection, waypoints)
}
}
}
function ManhattanLayoutPlugin(eventBus: EventBus, modeling: Modeling) {
eventBus.on('commandStack.connection.create.executed', (event) => {
var connection = (event as any).element;
var connection = (event as any).element
if (connection) {
updateWaypointsByManhattan(connection, modeling);
updateWaypointsByManhattan(connection, modeling)
}
});
})
eventBus.on('shape.move.end', (event) => {
const shape = (event as any).shape;
if (shape.incoming) {
shape.incoming.forEach((element: Connection) => {
updateWaypointsByManhattan(element, modeling);
});
}
if (shape.outgoing) {
shape.outgoing.forEach((element: Connection) => {
updateWaypointsByManhattan(element, modeling);
});
}
});
const shape = (event as any).shape
if (shape.incoming) {
shape.incoming.forEach((element: Connection) => {
updateWaypointsByManhattan(element, modeling)
})
}
if (shape.outgoing) {
shape.outgoing.forEach((element: Connection) => {
updateWaypointsByManhattan(element, modeling)
})
}
})
}
export default {
__init__: [ 'manhattanLayoutPlugin' ],
manhattanLayoutPlugin: [ 'type', ManhattanLayoutPlugin ]
};
__init__: ['manhattanLayoutPlugin'],
manhattanLayoutPlugin: ['type', ManhattanLayoutPlugin],
}

View file

@ -1,60 +1,57 @@
import { Element } from 'diagram-js/lib/model/Types';
import { Outline } from 'diagram-js/lib/features/outline/OutlineProvider';
import { Element } from 'diagram-js/lib/model/Types'
import { Outline } from 'diagram-js/lib/features/outline/OutlineProvider'
import {
attr as svgAttr,
create as svgCreate} from 'tiny-svg';
import { attr as svgAttr, create as svgCreate } from 'tiny-svg'
import Styles from 'diagram-js/lib/draw/Styles';
import Styles from 'diagram-js/lib/draw/Styles'
function CustomOutlineProvider(this: any, outline:Outline, styles:Styles) {
this._styles = styles;
outline.registerProvider(this);
function CustomOutlineProvider(this: any, outline: Outline, styles: Styles) {
this._styles = styles
outline.registerProvider(this)
}
CustomOutlineProvider.$inject = [
'outline',
'styles'
];
CustomOutlineProvider.$inject = ['outline', 'styles']
CustomOutlineProvider.prototype.getOutline = function(element:Element) {
if (element.type === 'custom:circle') {
const outline = svgCreate('circle');
//CustomOutlineProvider.prototype.getOutline = function(element:Element) {
// if (element.type === 'mechanism') {
// const outline = svgCreate('circle');
//
// svgAttr(outline , {
// x: `${element.x}`,
// y: `${element.y}`,
// cx: element.width / 2,
// cy: element.height / 2,
// r: 60,
// fill: "none",
// });
// return outline;
// }
//}
svgAttr(outline , {
CustomOutlineProvider.prototype.updateOutline = function (
element: Element,
outline: Outline
) {
if (element.type === 'mechanism') {
outline = svgCreate('rect')
svgAttr(outline, {
x: `${element.x}`,
y: `${element.y}`,
cx: element.width / 2,
cy: element.height / 2,
r: 60,
fill: "none",
});
return outline;
}
}
CustomOutlineProvider.prototype.updateOutline = function(element: Element, outline: Outline) {
if (element.type === 'custom:circle') {
outline = svgCreate('rect');
svgAttr(outline , {
x: `${element.x}`,
y: `${element.y}`,
cx: element.width / 2,
cy: element.height / 2,
r: 60,
fill: "none",
});
r: 60,
fill: 'none',
})
}
return false;
return false
}
import Ouline from 'diagram-js/lib/features/outline'; // idk why it's called such way
import Ouline from 'diagram-js/lib/features/outline' // idk why it's called such way
export default {
__init__: ['outlineProvider'],
__depends__: [ Ouline ],
outlineProvider: ['type', CustomOutlineProvider]
}
__depends__: [Ouline],
outlineProvider: ['type', CustomOutlineProvider],
}

View file

@ -14,8 +14,8 @@ export default {
LassoToolModule,
HandToolModule,
GlobalConnectModule,
translate
translate,
],
__init__: [ 'paletteProvider' ],
paletteProvider: [ 'type', PaletteProvider ]
};
__init__: ['paletteProvider'],
paletteProvider: ['type', PaletteProvider],
}

View file

@ -1,29 +1,31 @@
import ElementFactory from "diagram-js/lib/core/ElementFactory";
import Palette from "diagram-js/lib/features/palette/Palette"
import LassoTool from "diagram-js/lib/features/lasso-tool/LassoTool";
import Create from "diagram-js/lib/features/create/Create";
import GlobalConnect from "diagram-js/lib/features/global-connect/GlobalConnect";
import Translate from "diagram-js/lib/i18n/translate/Translate";
import HandTool from "diagram-js/lib/features/hand-tool/HandTool";
import { assign } from "min-dash";
import ElementFactory from 'diagram-js/lib/core/ElementFactory'
import Palette from 'diagram-js/lib/features/palette/Palette'
import LassoTool from 'diagram-js/lib/features/lasso-tool/LassoTool'
import Create from 'diagram-js/lib/features/create/Create'
import GlobalConnect from 'diagram-js/lib/features/global-connect/GlobalConnect'
import Translate from 'diagram-js/lib/i18n/translate/Translate'
import HandTool from 'diagram-js/lib/features/hand-tool/HandTool'
import { assign } from 'min-dash'
import { stateInstrument, stateMechanism } from '../addObjectForm'
export default function PaletteProvider(
this: any,
palette: Palette,
create: Create,
this: any,
palette: Palette,
create: Create,
elementFactory: ElementFactory,
lassoTool: LassoTool,
handTool:HandTool,
globalConnect:GlobalConnect,
translate:typeof Translate) {
this._palette = palette;
this._create = create;
this._elementFactory = elementFactory;
this._lassoTool = lassoTool;
this._handTool = handTool;
this._globalConnect = globalConnect;
this._translate = translate;
palette.registerProvider(this);
lassoTool: LassoTool,
handTool: HandTool,
globalConnect: GlobalConnect,
translate: typeof Translate
) {
this._palette = palette
this._create = create
this._elementFactory = elementFactory
this._lassoTool = lassoTool
this._handTool = handTool
this._globalConnect = globalConnect
this._translate = translate
palette.registerProvider(this)
}
PaletteProvider.$inject = [
@ -33,18 +35,17 @@ PaletteProvider.$inject = [
'lassoTool',
'handTool',
'globalConnect',
'translate'
'translate',
]
PaletteProvider.prototype.getPaletteEntries = function() {
PaletteProvider.prototype.getPaletteEntries = function () {
var actions = {},
create = this._create,
elementFactory = this._elementFactory,
lassoTool = this._lassoTool,
handTool = this._handTool,
globalConnect = this._globalConnect,
translate = this._translate;
create = this._create,
elementFactory = this._elementFactory,
lassoTool = this._lassoTool,
handTool = this._handTool,
globalConnect = this._globalConnect,
translate = this._translate
assign(actions, {
'hand-tool': {
@ -52,69 +53,85 @@ PaletteProvider.prototype.getPaletteEntries = function() {
className: 'icon-hand-tool',
title: translate('Activate hand tool'),
action: {
click: function(event: Event) {
handTool.activateHand(event);
}
}
click: function (event: Event) {
handTool.activateHand(event)
},
},
},
'lasso-tool': {
group: 'tools',
className: 'icon-lasso-tool',
title: translate('Activate lasso tool'),
action: {
click: function(event: Event) {
lassoTool.activateSelection(event);
}
}
click: function (event: Event) {
lassoTool.activateSelection(event)
},
},
},
'global-connect-tool': {
group: 'tools',
className: 'icon-connect',
title: translate('Activate global connect tool'),
action: {
click: function(event: Event) {
globalConnect.start(event);
}
}
click: function (event: Event) {
globalConnect.start(event)
},
},
},
'tool-separator': {
group: 'tools',
separator: true
separator: true,
},
'create-shape': {
group: 'create',
className: 'icon-create-shape',
title: 'Create Shape',
action: {
click: function() {
click: function () {
var shape = elementFactory.createShape({
width: 100,
height: 80,
canStartConnection:true
});
console.log(shape.canStartConnection);
create.start(event, shape);
}
}
canStartConnection: true,
})
create.start(event, shape)
},
},
},
'create-device': {
group: 'create',
className: 'icon-create-shape',
title: 'Create Device',
title: 'Добавить Прибор',
action: {
click: function() {
click: function () {
var shape = elementFactory.createShape({
width: 100,
height: 80,
canStartConnection:true,
type: 'custom:circle'
});
console.log(shape.canStartConnection);
create.start(event, shape);
}
}
width: 50,
height: 120,
canStartConnection: true,
type: 'instrument',
obj: structuredClone(stateInstrument),
})
create.start(event, shape)
},
},
},
});
'create-mechanism': {
group: 'create',
className: 'icon-create-shape',
title: 'Добавить Исполнительный Механизм',
action: {
click: function () {
var shape = elementFactory.createShape({
width: 50,
height: 120,
canStartConnection: true,
type: 'mechanism',
obj: structuredClone(stateMechanism),
})
create.start(event, shape)
},
},
},
})
return actions;
};
return actions
}

View file

@ -3,59 +3,126 @@ import { assign } from 'min-dash'
import {
append as svgAppend,
attr as svgAttr,
create as svgCreate
create as svgCreate,
} from 'tiny-svg'
import { Shape } from 'diagram-js/lib/model/Types'
const HIGH_PRIORITY = 1500;
const HIGH_PRIORITY = 1500
class CustomShapeRenderer extends BaseRenderer {
styles: any
SHAPE_STYLE: any
styles: any
SHAPE_STYLE: any
static $inject = ['eventBus', 'styles']
constructor(eventBus: any, styles: any) {
super(eventBus, HIGH_PRIORITY)
this.styles = styles
this.SHAPE_STYLE = styles.style({ fill: 'Canvas', stroke: 'CanvasText', strokeWidth: 2 })
this.SHAPE_STYLE = styles.style({
fill: 'Canvas',
stroke: 'CanvasText',
strokeWidth: 2,
})
}
canRender(element: any): boolean {
return element.type === 'custom:circle';
return element.type === 'mechanism' || element.type == 'instrument'
}
drawShape(visuals: Element, element: { width: number; height: number; }) : SVGElement {
var circle = svgCreate('circle');
drawShape(visuals: Element, shape: Shape): SVGElement {
var g = svgCreate('g')
if (shape.type == 'mechanism') {
g = drawMechanism(shape)
}
if (shape.type == 'instrument') {
g = drawInstrument(shape)
}
svgAttr(circle, {
cx: `${element.width / 2}`,
cy: `${element.height / 2 - 52}`,
r: '2.5mm',
fill: "none",
stroke: "CanvasText",
});
svgAttr(g, assign({}, this.SHAPE_STYLE))
svgAppend(visuals, g)
var line = svgCreate('line');
svgAttr(line, {
x1: element.width / 2,
x2: element.width / 2,
y1: element.height/2,
y2: element.height/2 - 40 - 2,
stroke: "CanvasText",
return g
}
}
function drawMechanism(shape: Shape): SVGGElement {
var circle = svgCreate('circle')
svgAttr(circle, {
cx: `${shape.width / 2}`,
cy: `${shape.height / 2 - 52}`,
r: '2.5mm',
fill: 'none',
stroke: 'CanvasText',
})
var line = svgCreate('line')
svgAttr(line, {
x1: shape.width / 2,
x2: shape.width / 2,
y1: shape.height / 2,
y2: shape.height / 2 - 40 - 2,
stroke: 'CanvasText',
})
var text = svgCreate('text')
svgAttr(text, {
x: shape.width / 2 - 4,
y: shape.height / 2 - 40 - 10,
'font-size': 10,
'font-family': 'Arial',
})
text.innerHTML = 'M'
var g = svgCreate('g')
svgAppend(g, circle)
svgAppend(g, line)
if (shape.obj.ручной) {
svgAppend(g, text)
}
return g
}
function drawInstrument(shape: Shape): SVGGElement {
var g = svgCreate('g')
if (!shape.obj.является_паз) {
const circle = svgCreate('circle', {
cx: shape.width / 2,
cy: shape.height / 2,
r: '5mm',
stroke: 'CanvasText',
fill: 'Canvas',
})
var g = svgCreate('g');
svgAppend(g, circle);
svgAppend(g, line);
svgAttr(g, assign({}, this.SHAPE_STYLE));
svgAppend(visuals, g);
return g;
svgAppend(g, circle)
} else {
function diamond(w: number, h: number, x: number, y: number) {
return svgCreate('polygon', {
points: `${x + w / 2}, ${y - h / 2}, ${x + w + w / 2}, ${y + h / 2}, ${x + w / 2}, ${y + h + h / 2}, ${x - w / 2}, ${y + h / 2}`,
stroke: 'CanvasText',
fill: 'Canvas',
})
}
svgAppend(g, diamond(shape.width, shape.height, 0, 0))
}
if (shape.obj.фиксация == 'НаЩите') {
svgAppend(
g,
svgCreate('line', {
x1: shape.width / 2 - 20,
y1: shape.height / 2,
x2: shape.width / 2 + 20,
y2: shape.height / 2,
stroke: 'CanvasText',
fill: 'Canvas',
})
)
}
return g
}
export default {
__init__: ['customShapeRenderer'],
customShapeRenderer: ['type', CustomShapeRenderer]
};
customShapeRenderer: ['type', CustomShapeRenderer],
}

View file

@ -1,11 +1,24 @@
export default {
__init__: [ 'customRenderer' ],
__init__: ['customRenderer'],
customRenderer: [
'type',
function (defaultRenderer: any) {
defaultRenderer.CONNECTION_STYLE = { fill: 'none', strokeWidth: 5, stroke: 'CanvasText' };
defaultRenderer.SHAPE_STYLE = { fill: 'Canvas', stroke: 'CanvasText', strokeWidth: 2 };
defaultRenderer.FRAME_STYLE = { fill: 'none', stroke: 'CanvasText', strokeDasharray: 4, strokeWidth: 2 };
}
]
};
defaultRenderer.CONNECTION_STYLE = {
fill: 'none',
strokeWidth: 5,
stroke: 'CanvasText',
}
defaultRenderer.SHAPE_STYLE = {
fill: 'Canvas',
stroke: 'CanvasText',
strokeWidth: 2,
}
defaultRenderer.FRAME_STYLE = {
fill: 'none',
stroke: 'CanvasText',
strokeDasharray: 4,
strokeWidth: 2,
}
},
],
}