Javascript блок схем редактор

mxGraph JavaScript

The examples can be edited with any texteditor. To run the examples point your browser directly to the local files (use links below) or use a webserver to deliver the files. Note that the files should always be delivered via a webserver in production. Local usage of files is only recommended for development and testing. (Please read this for running examples from the local filesystem in Internet Explorer.)

Examples

javascript/examples/editors contains the following examples:

  • Graph Editor — Fully functional diagram editor and drawing application.
  • mxDraw — Web 2.0-style diagram editor and drawing application.
  • mxProcess — Process editor with a fancy stylesheet and user interface.
  • mxWorkflow — BPMN workflow editor with various example diagrams.
  • mxWorkflow/Layout — BPMN workflow editor with automatic layout.(Experimental)

javascript/examples contains the following examples:

  • Anchors — Define fixed connection points for all shapes.
  • Animation — Using SVG animation to visualize the flow in a pipe.
  • Autolayout — Running and animating a layout algorithm after every change to a graph.
  • Boundary — Implementing boundary events in BPMN diagrams.
  • Clipboard — Using the clipboard for providing cross-tab and cross-browser copy and paste.
  • Codec — Dynamically creating a graph from XML and encoding the model into XML, as well as changing the default style for edges in-place.
  • Collapse — Changing the style of a cell based on its collapsed state.
  • Constituent — Using cells as parts of other cells.
  • ContextIcons — Adding icons to selected vertices to carry out special operations.
  • Control — Adding controls to specific cells in a graph.
  • Dragsource — Using one drag source for multiple graphs and changing the drag icon.
  • Drop — Handling native drag and drop of images (requires modern browser).
  • Dynamicloading — Loading graph model data dynamically to limit the number of cells in the model.
  • Dynamic Style — Changing the style of a cell by overriding mxGraphModel.
  • Dynamic Toolbar — Changing the state of the toolbar at runtime.
  • EdgeTolerance — Increasing the tolerance for hit detection on edges.
  • Editing — Using the in-place editor trigger to specify the editing value and write the new value into a specific field of the user object. Wrapping and DOM nodes as labels are also demonstrated here.
  • Events — Creating a graph container and using the mxDivResizer to update the size, interaction on the graph, including marquee selection, custom tooltips, context menu handling and changing the default menu opacity. It also demonstrates how to use an edgestyle in the default stylesheet, and handle the doubleclick on the adjustment point. See also: overlays.html for click event handling.
  • Extend canvas — Implementing an infinite canvas with scrollbars.
  • File I/O — Reading an XML file, writing a custom parser, applying an automatic layout and defining a 2-way edge.
  • FixedIcon — Customizing the icon position in the mxLabel shape.
  • FixedPoints — Using fixed connection points for connecting edges to vertices.
  • Folding — Using a layout to implement a nested group structure.
  • Graphlayout — Using automatic graph layouts and listening to changes of the graph size to keep the container size in sync.
  • Grid — Drawing a grid dynamically using HTML 5 canvas.
  • Groups — Using cells as parts of other cells.
  • Guides — Using the guidesEnabled and snapToTerminals switches, creating a grid using a canvas and handling cursor keys.
  • Handles — Using mxHandle to change custom styles interactively.
  • HelloPort — Using the isPort hook for visually connecting to another cell.
  • Hello, World! — Using a DOM node to create a graph and adding vertices and edges.
  • Hierarchical Layout — Using the hierarchical and organic layout algorithms.
  • HoverIcons — Showing icons on vertices as mouse hovers over them.
  • Hoverstyle — Change the style of a vertex on mouseover.
  • HTML label — Using HTML labels that are connected to the state of the user object.
  • IE9SVG — Using SVG for rendering a diagram in IE9 (and the HTML5 doctype).
  • Images — Using background images and images for for the label- and image-shape.
  • Indicators — Using small subshapes (indicators) inside a parent shape, typically an mxLabel.
  • JQuery — Using a JQuery plugin to generate labels for vertices on the fly.
  • JSON data — Using JSON to encode/decode parts of the graph model in mxCodec.
  • Label Position — Using the label position styles to set the position of vertex labels.
  • Labels — Wrapping and clipping for HTML labels of vertices, truncating labels to fit the size of a vertex, and manually placing vertex labels and relative children that act as «sublabels».
  • Layers — Using multiple layers to contain cells.
  • LOD — Implementing a level of detail per cell.
  • Map — Implementing an overlay for Google Maps.
  • Markers — Creating custom marker.
  • Menustyle — Styling the built-in popupmenu using CSS.
  • Merge — Using the mergeChildren function to merge two graphs.
  • Monitor — Using mxGraph to display the current state of a workflow.
  • Morph — Using mxMorphing for simple cell animations.
  • Offpage Connectors — Creating offpage connectors in a graph and loading a new diagram on a single click.
  • Orgchart — Using automatic layouts, fit to page zoom and poster print (across multiple pages).
  • Orthogonal — Demonstrates the use of port constraints and orthogonal edge styles and handlers.
  • Overlays — Cell highlighting, overlays and handling click and double click events. See also: events.html for more event handling.
  • Pagebreaks — Using the pageBreaksVisible and preferPageSize switches and adding headers and footers to print output.
  • Perimeter — How to avoid edge and label intersections.
  • Permissions — Creating permissions to define the available operations on a graph.
  • Portrefs — Referencing connection points by ID.
  • Ports — Implementing ports as child vertices with relative positions, drag and drop and using images and HTML in cells.
  • Radial Tree Layout — Demonstrates the use of Radial Tree Layout with a graph.
  • Resources — Disabling the Synchronous XMLHttpRequest on main thread warning.
  • Schema — Implementing a database schema editor.
  • Scrollbars — Using a scrollable table with different sections in a cell label.
  • Secondlabel — Adding another string label to vertices.
  • ServerView — Using a server-side image of the graph as the diagram in the client.
  • Shape — How to implement and use a custom shape.
  • Showregion — Using a custom rubberband handler to show the selected region in a new window.
  • Standardsmode — How to use mxGraphs VML rendering with a Doctype in IE.
  • Stencils — Using an XML file to define new stencils to be used as shapes.
  • Stylesheet — Using a custom stylesheet and control points in edges, as well as overriding the getLabel and getTooltip function to return dynamic information, and making a supercall in JavaScript.
  • Swimlanes — Using swimlanes for pools and lanes and using the stack layout as an automatic layout.
  • Thread — Setting overlays in mxGraph from within a timed function.
  • Toolbar — Using existing cells as templates for creating new cells.
  • Touch — Handling touch, mouse and pointer events.
  • Tree — Folding for subtrees in acyclic graphs (trees).
  • UIConfig — Using a config file to configure the toolbar and popup menu in mxEditor.
  • Userobject — Using XML objects as values for cells.
  • Validation — Using multiplicities for automatically validating a graph.
  • Visibility — Various solutions for hiding and showing cells.
  • Windows — Using the mxWindow class for displaying windows.
  • Wires — Drawing electrical and digital circuits with devices and wires.
  • Wrapping — Using HTML markup and word-wrapping in vertex and edge labels.
Читайте также:  Java gaming and graphics

Источник

Редактор блок схем — о дружбе Vue.js и MxGraph

Я фронтенд разработчик, но стремлюсь к развитию, решил написать fullstack приложение и стать миллионером получить бесценный опыт.

Так вот, начал планировать бэкенд, выбрал MongoDB для хранения данных, и был готов планировать структуру и связи полей.

Но столкнулся с отсутствием простого и достаточно функционального редактора схем без излишеств для NoSQL баз данных.

— Нет? Значит сделаю делов то, найти библиотеку и накидать интерфейс!
Fullstack идея была отодвинута на задний план и я начал проработку простейшего редактора схем БД.
— Наивный… – но это я понял немного позднее.

Поиски

Во первых библиотеки такого рода в основном платные и требуют за них очень немало!
Во вторых те что бесплатные не блещут функционалом или полны багов!

В третьих не будет ибо нашел MxGraph. Он практически не упоминается на просторах интернета, хотя на нем написан прекрасный сервис draw.io да и сам по себе это весьма удобный инструмент для визуализации и редактирования данных.

Представление

О Vue.js думаю слышали все, но на всякий случай — это JavaScript — фреймворк для создания пользовательских интерфейсов в реактивном стиле.

MxGraph – это библиотека для визуализации и редактирования различных процессов, workflow и BPM, визуализации базы данных, отображение сетей и телекоммуникаций, картографических приложений и GIS, диаграмм UML, электронных схем, СБИС, САПР, финансовых и социальных сетей, организационных схем и многого другого.

Совместимость

MxGraph достаточно старый(но не устаревшый) инструмент поэтому простой npm install в Vue проект тут не даст нам полной совместимости. Поэтому тут пришлось перекапывать сеть и открывать производство велосипедов.

Выстраданные Найденные решения

Импорт и встраивание в компонент Vue выглядит таким образом:

  

Зачем создал переменные, а потом еще и в window их прописал?!

Дело в том что webpack при сборке переименовывает переменные и mxgraph в последствии не может их найти. Поэтому специально для mxgraph я вынес их в глобальный объект.

Читайте также:  Fireevent java что это

Также не забудьте про конфигурацию – особенно при использовании встроенных интерфейсов mxEditor, иначе возникнут проблемы с контентом библиотеки.

А переменную editor зачем вынес из vue?!

Во время работы у нас не всегда будет возможность обратиться к переменной vue из-за контекста методов mxgraph. А вынос в глобальные переменные серьезно сэкономит время и пару горстей нервов.

Кастомные объекты данных зачем опять в window?!

Для создания новых объектов данных в mxgraph используются прототипы. Их тоже нужно записывать в window – иначе возникнут проблемы со встроенным импортом\экспортом схем.

Дальше разработка пошла легче и проблем с доступом к объектам я больше не встретил.
Я не считаю такой подход идеальным, и буду рад если кто то предложит альтернативу такому решению совместимости.

И что получилось?

Небольшое приложение для моделинга схем баз данных: nosqldbm.ru
Которое помогает мне, визуализировать примерную схему БД будущих проектов.

Спасибо что прочитали мою первую публикацию, надеюсь вам было интересно.

Подборка материалов по MxGraph

Источник

Оцените статью