massive refactoring, Svelte removing

This commit is contained in:
Gregory Bednov 2025-01-18 05:56:20 +03:00
commit ecf4feb870
22 changed files with 1121 additions and 561 deletions

View file

@ -1,267 +0,0 @@
<script lang="ts">
import {
create as svgCreate,
append as svgAppend
} from 'tiny-svg';
import { writable } from 'svelte/store';
let типОбъекта: 'Прибор' | 'ИсполнительныйМеханизм' = 'Прибор';
let фиксация: 'НаМесте' | 'НаЩите' = 'НаМесте';
let типПрибора: 'Величина' | 'Мультивеличина' = 'Величина';
let величина: 'Напряжение' | 'Температура' = 'Напряжение';
let уточнение: 'ИнтегрированиеСуммированиеПоВремени' | 'РазностьПерепад' | null = null;
interface Функция {
тип: string;
значение: string;
}
let функции: Функция[] = [];
const функцииПоТипу = {
ВыполняемаяФункция: [
'Сигнализация',
'АвтоматическоеРегулирование',
'ВеличинаОтклоненияОтЗаданной',
'Регистрация'],
ФункциональныйПризнак: [
'ЧувствительныйЭлемент',
'Преобразование',
'ПервичныйПоказывающийПрибор',
'СтанцияУправления',
'ВключениеОтключениеПереключение',
'Преобразование',
'VДополнительный',
'ВспомогательныеКомпьютерныеУстройства',
'ВспомогательныеВычислительноеУстройство',
'ZДополнительный']};
function addFunction() {
функции = [...функции, { тип: 'ВыполняемаяФункция', значение: 'Регистрация' }]
}
function removeFunction(index: number) {
функции = функции.filter((_, i) => i !== index);
}
let являетсяПаз = false;
let ручной = false;
let направление: 'Открывается' | 'Закрывается' | 'ОстаётсяНаМесте' | null = null
export const data = writable({ value: svgCreate('g') });
function handleSubmit() {
data.update((_) => ({value: to_svg(0,0)}));
}
export function to_svg(x, y):SVGElement {
const r = svgCreate('g');
if (типОбъекта === 'ИсполнительныйМеханизм') {
var circle = svgCreate('circle',
{
cx: x,
cy: y - 52,
r: '2.5mm',
fill: "none",
stroke: "CanvasText",
});
var lineAttrs: {
x1: any;
x2: any;
y1: any;
y2: number;
stroke: string;
"marker-start"?: string;
"marker-end"?: string;
} = {
x1: x,
x2: x,
y1: y,
y2: y - 42,
stroke: "CanvasText",
}
if (направление == "Открывается" || направление == "ОстаётсяНаМесте") {
lineAttrs["marker-start"] = "url(#arrow)"
}
if (направление == "Закрывается" || направление == "ОстаётсяНаМесте") {
lineAttrs["marker-end"] = "url(#arrow)"
}
const line = svgCreate("line", lineAttrs);
svgAppend(r, circle)
svgAppend(r, line)
return r
}
if (являетсяПаз) {
const w = 10;
const h = 10;
const outer = svgCreate('polygon', {points: `${x},${y+h} ${x+w},${y} ${x},${y-h} ${x-w},${y}`, stroke:"CanvasText", fill:"Canvas"});
svgAppend(r, outer);
const rect = svgCreate('rect', {x: x-w/2, y: y-h/2, width:w, height: h, stroke:"CanvasText", fill:"Canvas"})
svgAppend(r, rect);
} else {
const circle = svgCreate('circle', {x: x, y: y, r: "5mm", stroke:"CanvasText", fill:"Canvas"});
svgAppend(r, circle);
}
if (фиксация == "НаЩите") {
const h = svgCreate('line', {x0: x - 5, y0: y, x1: x + 5, y1: y, stroke:"CanvasText"})
svgAppend(r, h);
}
return r;
}
</script>
<div>
<label>
<span>Тип объекта:</span>
<select bind:value={типОбъекта}>
<option value="Прибор">Прибор</option>
<option value="ИсполнительныйМеханизм">Исполнительный механизм</option>
</select>
</label>
<br/>
{#if типОбъекта === 'Прибор'}
<label>
<span>Фиксация:</span>
<select bind:value={фиксация}>
<option value="НаМесте">На месте</option>
<option value="НаЩите">На щите</option>
</select>
</label>
<br/>
<label>
<span>Тип прибора:</span>
<select bind:value={типПрибора}>
<option value="Величина">Величина</option>
<option value="Мультивеличина">Мультивеличина</option>
</select>
</label>
<br/>
<label>
<span>Величина:</span>
<select id="choices-select" bind:value={величина}>
<option value="A">Анализ, качество</option>
<option value="B">Пламя, горение</option>
<option value="C">Дополнительная величина</option>
<option value="D">Дополнительная величина</option>
<option value="E">Напряжение</option>
<option value="F">Расход</option>
<option value="G">Дополнительная величина</option>
<option value="H">Ручное воздействие</option>
<option value="I">Ток</option>
<option value="J">Мощность</option>
<option value="K">Время</option>
<option value="L">Уровень</option>
<option value="M">Дополнительная величина</option>
<option value="N">Дополнительная величина</option>
<option value="O">Дополнительная величина</option>
<option value="P">Давление</option>
<option value="Q">Количество</option>
<option value="E">Радиоактивность</option>
<option value="S">Скорость, частота</option>
<option value="T">Температура</option>
<option value="U">Разнородные величины</option> // несколько величин ТОЛЬКО здесь
<option value="V">Вибрация</option>
<option value="W">Вес</option>
<option value="X">Дополнительная величина (нерекомендованная буква)</option>
<option value="Y">Событие</option>
<option value="Z">Размер</option>
</select>
</label>
<br/>
<label>
<span>Уточнение:</span>
<select bind:value={уточнение}>
<option value="ИнтегрированиеСуммированиеПоВремени">Интегрирование</option>
<option value="РазностьПерепад">Разность</option>
<option value={null}>Без уточнения</option>
</select>
</label>
<br/>
<label>
<input type="checkbox" bind:checked={являетсяПаз} />
<span>Является паз</span>
</label>
<br/>
<strong>Функции<button type="button" on:click={addFunction} class="simplebutton">+</button></strong>
{#each функции as функция, i}
<div class="функция-элемент" style="margin-bottom: 10px;">
<label>
Тип функции:
<select bind:value={функция.тип}>
<option value="ВыполняемаяФункция">Выполняемая функция</option>
<option value="ФункциональныйПризнак">Функциональный признак</option>
</select>
</label>
<label>
Значение:
<select bind:value={функция.значение}>
{#if функция.тип === 'ВыполняемаяФункция'}
{#each функцииПоТипу.ВыполняемаяФункция as val}
<option value={val}>{val}</option>
{/each}
{/if}
{#if функция.тип === 'ФункциональныйПризнак'}
{#each функцииПоТипу.ФункциональныйПризнак as val}
<option value={val}>{val}</option>
{/each}
{/if}
</select>
</label>
<button type="button" on:click={() => removeFunction(i)} class="simplebutton">-</button>
</div>
{/each}
{:else}
<label>
<span>Имеет ручное управление:</span>
<input type="checkbox" bind:checked={ручной} />
</label>
<br/>
<label>
<span>Направление:</span>
<select bind:value={направление}>
<option value="Открывается">Открывается</option>
<option value="Закрывается">Закрывается</option>
<option value="ОстаётсяНаМесте">Остаётся на месте</option>
<option value={null}>Не указано</option>
</select>
</label>
<br/>
{/if}
<br/>
<button on:click={handleSubmit}>OK</button>
<br/>
</div>
<style>
.simplebutton {
width: 40px; /* Ширина кнопки */
height: 40px; /* Высота кнопки должна совпадать с шириной */
border: 1px solid lightgray;
margin-left: 5px;
border-radius: 50%; /* Делает кнопку круглой */
display: inline-flex; /* Для центрирования содержимого */
justify-content: center; /* Горизонтальное центрирование */
align-items: center; /* Вертикальное центрирование */
cursor: pointer; /* Изменение курсора */
}
</style>

View file

@ -1,17 +0,0 @@
<script>
import AddObjectForm from './AddObjectForm.svelte';
import Diagram from './Diagram.svelte';
</script>
<main>
<h1>FSA Editor</h1>
<AddObjectForm/>
<Diagram />
</main>
<style>
main {
font-family: Arial, sans-serif;
padding: 1rem;
}
</style>

View file

@ -1,8 +0,0 @@
import CustomGlobalConnectRules from './CustomGlobalConnectRules';
const CustomGlobalConnectRulesModule = {
__init__: ['customGlobalConnectRules'],
customGlobalConnectRules: ['type', CustomGlobalConnectRules]
};
export default CustomGlobalConnectRulesModule;

View file

@ -1,89 +0,0 @@
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";
function PalettePlugin (create: Create,
elementFactory:ElementFactory,
globalConnect: GlobalConnect,
lassoTool: LassoTool,
palette: Palette) {
palette.registerProvider({
getPaletteEntries: () => ({
'hand-tool': {
group: 'tools',
className: 'icon-hand-tool',
title: 'Hand Tool',
action: {
click: function() {
//console.log("Hello");
}
}
},
'lasso-tool': {
group: 'tools',
className: 'icon-lasso-tool',
title: 'Lasso Tool',
action: {
click: function(event) {
lassoTool.activateSelection(event as MouseEvent);
}
}
},
'tool-separator': {
group: 'tools',
separator: true,
action: {}
},
'create-shape': {
group: 'create',
className: 'icon-create-shape',
title: 'Create Shape',
action: {
click: function() {
var shape = elementFactory.createShape({
width: 100,
height: 80,
canStartConnection:true
});
console.log(shape.canStartConnection);
create.start(event, shape);
}
}
},
'create-device': {
group: 'create',
className: 'icon-create-shape',
title: 'Create Device',
action: {
click: function() {
var shape = elementFactory.createShape({
width: 100,
height: 80,
canStartConnection:true,
type: 'custom:circle'
});
console.log(shape.canStartConnection);
create.start(event, shape);
}
}
},
'create-connection': {
group: 'create',
className: 'icon-connect',
title: 'Create Connection',
action: {
click: (event) => {
globalConnect.start(event, false);
}
}
}
})
});
}
export default {
__init__: [ 'palettePlugin' ],
palettePlugin: [ 'type', PalettePlugin ]
};

View file

@ -1,44 +0,0 @@
<script lang="ts">
import { onMount } from "svelte";
import Canvas from "diagram-js/lib/core/Canvas";
import ElementFactory from 'diagram-js/lib/core/ElementFactory';
import Editor from './editor.ts'
import 'diagram-js/assets/diagram-js.css';
let container: HTMLDivElement | null = null;
onMount(() => {
if (container === null) return;
const diagram = Editor({ container });
const canvas = diagram.get<Canvas>("canvas");
const elementFactory = diagram.get<ElementFactory>('elementFactory');
var root = elementFactory.createRoot();
canvas.setRootElement(root);
});
</script>
<svg>
<defs>
<marker
id="arrow"
refX="9"
refY="5"
fill="CanvasText"
markerHeight="6"
markerWidth="6"
orient="auto-start-reverse"
viewBox="0 0 297 210">
<path d="M 0 0 L 10 5 L 0 10 z"></path>
</marker>
</defs>
</svg>
<style>
.container {
width: 297mm;
height: 210mm;
border: 1px solid #aaa;
}
</style>
<div bind:this={container} class="container"></div>

145
src/addObjectForm.ts Normal file
View file

@ -0,0 +1,145 @@
import 'choices.js/public/assets/styles/choices.min.css'
// Инициализация состояний для формы "Прибор"
const stateInstrument = {
фиксация: 'НаМесте',
типПрибора: 'Величина',
величина: 'Напряжение',
уточнение: null,
функции: []
};
// Инициализация состояний для формы "Исполнительный механизм"
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');
// Ручное управление
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);
// Добавить форму на страницу
container?.appendChild(form);
}

View file

@ -1,64 +1,50 @@
import Diagram from 'diagram-js';
import ConnectModule from 'diagram-js/lib/features/connect';
import ContextPadModule from 'diagram-js/lib/features/context-pad';
import CreateModule from 'diagram-js/lib/features/create';
import LassoToolModule from 'diagram-js/lib/features/lasso-tool';
import ModelingModule from 'diagram-js/lib/features/modeling';
import MoveCanvasModule from 'diagram-js/lib/navigation/movecanvas';
import MoveModule from 'diagram-js/lib/features/move';
import OutlineModule from 'diagram-js/lib/features/outline';
import PaletteModule from 'diagram-js/lib/features/palette';
import ResizeModule from 'diagram-js/lib/features/resize';
import RulesModule from 'diagram-js/lib/features/rules';
import SelectionModule from 'diagram-js/lib/features/selection';
import GlobalConnectModule from 'diagram-js/lib/features/global-connect';
import ZoomScrollModule from 'diagram-js/lib/navigation/zoomscroll';
import BendpointMoveModule from 'diagram-js/lib/features/bendpoints';
import StyleModule from './StyleModule.ts';
import ManhattanConnectionModule from './ManhattanConnectionModule.ts';
import CustomPaletteModule from './CustomPaletteModule.ts';
import CustomGlobalConnectRulesModule from './CustomGlobalConnectRulesModule.ts';
import CustomShapeRendererModule from './CustomShapeRendererModule.ts';
import CustomOutlineModule from './CustomOutlineModule.ts';
import Diagram from 'diagram-js'
import ConnectModule from 'diagram-js/lib/features/connect'
import ContextPadModule from 'diagram-js/lib/features/context-pad'
import CreateModule from 'diagram-js/lib/features/create'
import LassoToolModule from 'diagram-js/lib/features/lasso-tool'
import ModelingModule from 'diagram-js/lib/features/modeling'
import MoveCanvasModule from 'diagram-js/lib/navigation/movecanvas'
import MoveModule from 'diagram-js/lib/features/move'
import RulesModule from 'diagram-js/lib/features/rules'
import SelectionModule from 'diagram-js/lib/features/selection'
import GlobalConnectModule from 'diagram-js/lib/features/global-connect'
import ZoomScrollModule from 'diagram-js/lib/navigation/zoomscroll'
import BendpointMoveModule from 'diagram-js/lib/features/bendpoints'
interface EditorOptions {
container: HTMLElement;
additionalModules?: Array<any>;
}
export default function Editor(options: EditorOptions): Diagram {
const { container } = options;
const modules = [
BendpointMoveModule
, ConnectModule
, ContextPadModule
, CreateModule
, GlobalConnectModule
, LassoToolModule
, ModelingModule
, MoveCanvasModule
, MoveModule
//, OutlineModule
, PaletteModule
//, ResizeModule
, RulesModule
, SelectionModule
, ZoomScrollModule
, StyleModule
, ManhattanConnectionModule
, CustomPaletteModule
, CustomGlobalConnectRulesModule
, CustomShapeRendererModule
, CustomOutlineModule
];
console.log(container);
return new Diagram({
canvas: {
container
},
modules: modules
});
import StyleModule from './modules/StyleModule'
import ManhattanConnectionModule from './modules/ManhattanConnectionModule'
import PaletteModule from './modules/PaletteModule'
import GlobalConnectRulesModule from './modules/GlobalConnectRulesModule'
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
//, ResizeModule
, RulesModule
, SelectionModule
, ZoomScrollModule
, StyleModule
, ManhattanConnectionModule
, PaletteModule
, GlobalConnectRulesModule
, ShapeRendererModule
, OutlineModule
]
}
)
}

View file

@ -1,13 +1,21 @@
import { mount } from 'svelte'
import App from './App.svelte';
import {createInstrumentForm, createMechanismForm} from './addObjectForm'
import Editor from './editor'
import 'diagram-js/assets/diagram-js.css'
const target = document.getElementById('app');
const instrumentContainer = document.getElementById('instrument-form')
const mechanismContainer = document.getElementById('mechanism-form')
if (!target) {
throw new Error("Target element with ID 'app' not found in DOM.");
createInstrumentForm(instrumentContainer)
createMechanismForm(mechanismContainer)
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'
const diagram = Editor(diagramElement)
const app = mount(App, {
target: document.getElementById('app')!,
})
export default app;
export default diagram

View file

@ -1,5 +1,6 @@
import RuleProvider from 'diagram-js/lib/features/rules/RuleProvider';
export default class CustomGlobalConnectRules extends RuleProvider {
class CustomGlobalConnectRules extends RuleProvider {
static $inject = ['eventBus'];
constructor(eventBus: any) {
@ -7,7 +8,6 @@ export default class CustomGlobalConnectRules extends RuleProvider {
}
init(): void {
// Правило для начала соединения
this.addRule('connection.start', (context) => {
return true;
const { source } = context;
@ -21,23 +21,15 @@ export default class CustomGlobalConnectRules extends RuleProvider {
// Правило для создания соединения
this.addRule('connection.create', (context) => {
//return true;
const { source, target } = context;
// console.log(typeof source);
// console.log(source.constructor.name)
// instanceof Shape);
//if (source?.type === Shape)
//if (
// source?.businessObject?.type === 'custom:connectable' &&
// target?.businessObject?.type === 'custom:connectable'
//) {
// const { source, target } = context;
return { type: 'Connection' };
// { type: 'Connection' }; // Тип соединения
// }
return false; // Запретить соединение
});
}
}
export default {
__init__: ['customGlobalConnectRules'],
customGlobalConnectRules: ['type', CustomGlobalConnectRules]
};

View file

@ -2,7 +2,7 @@
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 { Connection } from 'diagram-js/lib/model/Types';
import type { Connection } from 'diagram-js/lib/model/Types';
export function updateWaypointsByManhattan (connection: Connection, modeling: Modeling ): void {
if (connection.source && connection.target) {
@ -32,8 +32,8 @@ function ManhattanLayoutPlugin(eventBus: EventBus, modeling: Modeling) {
});
eventBus.on("shape.move.end", (event) => {
var shape = (event as any).shape;
eventBus.on('shape.move.end', (event) => {
const shape = (event as any).shape;
if (shape.incoming) {
shape.incoming.forEach((element: Connection) => {
updateWaypointsByManhattan(element, modeling);

View file

@ -1,13 +1,13 @@
import { Element } from 'diagram-js/lib/model/Types';
import { Outline } from 'diagram-js/lib/features/outline/OutlineProvider';
import OutlineProvider from 'diagram-js/lib/features/outline/OutlineProvider';
import {
attr as svgAttr,
create as svgCreate} from 'tiny-svg';
import Styles from 'diagram-js/lib/draw/Styles';
function CustomOutlineProvider(outline:OutlineProvider, styles:Styles) {
function CustomOutlineProvider(this: any, outline:Outline, styles:Styles) {
this._styles = styles;
outline.registerProvider(this);
}
@ -50,10 +50,11 @@ CustomOutlineProvider.prototype.updateOutline = function(element: Element, outli
return false;
}
const CustomOutlineModule = {
__init__: ['outlineProvider'],
__depends__: [ 'Outline' ],
outlineProvider: ['type', CustomOutlineProvider]
};
import Ouline from 'diagram-js/lib/features/outline'; // idk why it's called such way
export default CustomOutlineModule;
export default {
__init__: ['outlineProvider'],
__depends__: [ Ouline ],
outlineProvider: ['type', CustomOutlineProvider]
}

View file

@ -0,0 +1,21 @@
import PaletteModule from 'diagram-js/lib/features/palette'
import CreateModule from 'diagram-js/lib/features/create'
import LassoToolModule from 'diagram-js/lib/features/lasso-tool'
import HandToolModule from 'diagram-js/lib/features/hand-tool'
import GlobalConnectModule from 'diagram-js/lib/features/global-connect'
import translate from 'diagram-js/lib/i18n/translate'
import PaletteProvider from './PaletteProvider'
export default {
__depends__: [
PaletteModule,
CreateModule,
LassoToolModule,
HandToolModule,
GlobalConnectModule,
translate
],
__init__: [ 'paletteProvider' ],
paletteProvider: [ 'type', PaletteProvider ]
};

View file

@ -0,0 +1,120 @@
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";
export default function PaletteProvider(
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);
}
PaletteProvider.$inject = [
'palette',
'create',
'elementFactory',
'lassoTool',
'handTool',
'globalConnect',
'translate'
]
PaletteProvider.prototype.getPaletteEntries = function() {
var actions = {},
create = this._create,
elementFactory = this._elementFactory,
lassoTool = this._lassoTool,
handTool = this._handTool,
globalConnect = this._globalConnect,
translate = this._translate;
assign(actions, {
'hand-tool': {
group: 'tools',
className: 'icon-hand-tool',
title: translate('Activate hand tool'),
action: {
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);
}
}
},
'global-connect-tool': {
group: 'tools',
className: 'icon-connect',
title: translate('Activate global connect tool'),
action: {
click: function(event: Event) {
globalConnect.start(event);
}
}
},
'tool-separator': {
group: 'tools',
separator: true
},
'create-shape': {
group: 'create',
className: 'icon-create-shape',
title: 'Create Shape',
action: {
click: function() {
var shape = elementFactory.createShape({
width: 100,
height: 80,
canStartConnection:true
});
console.log(shape.canStartConnection);
create.start(event, shape);
}
}
},
'create-device': {
group: 'create',
className: 'icon-create-shape',
title: 'Create Device',
action: {
click: function() {
var shape = elementFactory.createShape({
width: 100,
height: 80,
canStartConnection:true,
type: 'custom:circle'
});
console.log(shape.canStartConnection);
create.start(event, shape);
}
}
},
});
return actions;
};

View file

@ -1,34 +1,30 @@
import BaseRenderer from 'diagram-js/lib/draw/BaseRenderer';
import { assign } from 'min-dash';
import BaseRenderer from 'diagram-js/lib/draw/BaseRenderer'
import { assign } from 'min-dash'
import {
append as svgAppend,
attr as svgAttr,
create as svgCreate
} from 'tiny-svg';
import data from './AddObjectForm.svelte';
} from 'tiny-svg'
const HIGH_PRIORITY = 1500;
class CustomShapeRenderer extends BaseRenderer {
styles: any
SHAPE_STYLE: any
static $inject = ['eventBus', 'styles'];
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 });
super(eventBus, HIGH_PRIORITY)
this.styles = styles
this.SHAPE_STYLE = styles.style({ fill: 'Canvas', stroke: 'CanvasText', strokeWidth: 2 })
}
canRender(element: any): boolean {
return element.type === 'custom:circle';
}
drawShape(visuals, element, attrs): SVGElement {
console.log(data.value);
drawShape(visuals: Element, element: { width: number; height: number; }) : SVGElement {
var circle = svgCreate('circle');
svgAttr(circle, {
@ -52,19 +48,14 @@ class CustomShapeRenderer extends BaseRenderer {
var g = svgCreate('g');
svgAppend(g, circle);
svgAppend(g, line);
svgAttr(g, assign({}, this.SHAPE_STYLE, attrs || {}));
svgAttr(g, assign({}, this.SHAPE_STYLE));
svgAppend(visuals, g);
return g;
}
}
const CustomShapeRendererModule = {
export default {
__init__: ['customShapeRenderer'],
customShapeRenderer: ['type', CustomShapeRenderer]
};
export default CustomShapeRendererModule;
};

View file

@ -1,5 +1,5 @@
export default {
__init__: ['customRenderer'],
__init__: [ 'customRenderer' ],
customRenderer: [
'type',
function (defaultRenderer: any) {