Как имитировать перетаскивание прямоугольника с текстом

Я хотел перетащить каждую строку таблицы как rectangle, она должна выполнять те же функции, что и rectangle.

Как только вы запустите код, вы увидите, что таблица ниже прямоугольника table будет там слева вверху, я хотел воспроизвести ту же функциональность для >строка таблицы drag

Вопрос: когда я перетаскиваю drag строку таблицы ниже graph области, это следует рассматривать как перетаскивание прямоугольника. аналогично рядом graph области верхнего левого прямоугольника drag.

я использую (документация): https://jgraph.github.io/mxgraph/docs/manual.html

Для полного представления см. codepen: https://codepen.io/eabangalore/pen/vMvdmZ

Видео покажет вам мою проблему:https://drive.google.com/file/d/1DR3qMxX8JViSwMbA5vWYhMeMgRlQ0Krs/view

// Program starts here. Creates a sample graph in the
// DOM node with the specified ID. This function is invoked
// from the onLoad event handler of the document (see below).
function main() {
  // Checks if browser is supported
  if (!mxClient.isBrowserSupported()) {
    // Displays an error message if the browser is
    // not supported.
    mxUtils.error('Browser is not supported!', 200, false);
  } else {
    // Defines an icon for creating new connections in the connection handler.
    // This will automatically disable the highlighting of the source vertex.
    mxConnectionHandler.prototype.connectImage = new mxImage('images/connector.gif', 16, 16);

    // Creates the div for the toolbar
    var tbContainer = document.createElement('div');
    tbContainer.style.position = 'absolute';
    tbContainer.style.overflow = 'hidden';
    tbContainer.style.padding = '2px';
    tbContainer.style.left = '0px';
    tbContainer.style.top = '0px';
    tbContainer.style.width = '24px';
    tbContainer.style.bottom = '0px';

    document.body.appendChild(tbContainer);

    // Creates new toolbar without event processing
    var toolbar = new mxToolbar(tbContainer);
    toolbar.enabled = false

    // Creates the div for the graph
    var container = document.createElement('div');
    container.style.position = 'absolute';
    container.style.overflow = 'hidden';
    container.style.left = '24px';
    container.style.top = '0px';
    container.style.right = '0px';
    container.style.bottom = '0px';
    container.style.background = 'url("https://jgraph.github.io/mxgraph/javascript/examples/editors/images/grid.gif")';
    //document.getElementById('graph-wrapper').style.background = 'url("editors/images/grid.gif")';

    document.getElementById('graph-wrapper').appendChild(container);

    // Workaround for Internet Explorer ignoring certain styles
    if (mxClient.IS_QUIRKS) {
      document.body.style.overflow = 'hidden';
      new mxDivResizer(tbContainer);
      new mxDivResizer(container);
    }

    // Creates the model and the graph inside the container
    // using the fastest rendering available on the browser
    var model = new mxGraphModel();
    var graph = new mxGraph(container, model);

    // Enables new connections in the graph
    graph.setConnectable(true);
    graph.setMultigraph(false);

    // Stops editing on enter or escape keypress
    var keyHandler = new mxKeyHandler(graph);
    var rubberband = new mxRubberband(graph);

    var addVertex = function(icon, w, h, style) {
      var vertex = new mxCell(null, new mxGeometry(0, 0, w, h), style);
      vertex.setVertex(true);

      console.log('vertex vertex', vertex);

      var img = addToolbarItem(graph, toolbar, vertex, icon);
      //img.enabled = true;

      graph.getSelectionModel().addListener(mxEvent.CHANGE, function() {
        var tmp = graph.isSelectionEmpty();
        mxUtils.setOpacity(img, (tmp) ? 100 : 20);
        img.enabled = tmp;
      });
    };

    addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/rounded.gif', 100, 40, 'shape=rounded');
  }
}

function addToolbarItem(graph, toolbar, prototype, image) {
  // Function that is executed when the image is dropped on
  // the graph. The cell argument points to the cell under
  // the mousepointer if there is one.
  var funct = function(graph, evt, cell, x, y) {
    graph.stopEditing(false);

    var vertex = graph.getModel().cloneCell(prototype);
    vertex.geometry.x = x;
    vertex.geometry.y = y;

    graph.addCell(vertex);
    graph.setSelectionCell(vertex);
  }

  // Creates the image which is used as the drag icon (preview)
  var img = toolbar.addMode(null, image, function(evt, cell) {
    var pt = this.graph.getPointForEvent(evt);
    funct(graph, evt, cell, pt.x, pt.y);
  });

  // Disables dragging if element is disabled. This is a workaround
  // for wrong event order in IE. Following is a dummy listener that
  // is invoked as the last listener in IE.
  mxEvent.addListener(img, 'mousedown', function(evt) {
    // do nothing
  });

  // This listener is always called first before any other listener
  // in all browsers.
  mxEvent.addListener(img, 'mousedown', function(evt) {
    if (img.enabled == false) {
      mxEvent.consume(evt);
    }
  });

  mxUtils.makeDraggable(img, graph, funct);

  return img;
}

<
/script> <
/head>

<!-- Calls the main function after the page has loaded. Container is dynamically created. -->
<
body onload = "main();" >
  <
  div class = "table-wrapper" >
  <
  table >
  <
  tr draggable = "true"
ondragstart = "importDragHandler(event)" >
  <
  th > Company < /th> <
  th > Contact < /th> <
  th > Country < /th> <
  /tr> <
  tr draggable = "true"
ondragstart = "importDragHandler(event)" >
  <
  td > Alfreds Futterkiste < /td> <
  td > Maria Anders < /td> <
  td > Germany < /td> <
  /tr> <
  tr draggable = "true"
ondragstart = "importDragHandler(event)" >
  <
  td > Centro comercial Moctezuma < /td> <
  td > Francisco Chang < /td> <
  td > Mexico < /td> <
  /tr>

  <
  /table> <
  /div> <
  div id = "graph-wrapper" >

  <
  /div> <
  script >

  function importDragHandler(event) {
    console.log('event..........', event);
    var elem = document.createElement("div");
    elem.innerHTML = "";
    elem.id = "import_handler_drag_ghost";
    elem.textNode = "Dragging";
    // elem.style.position = "absolute";
    elem.style.top = "-1000px";
    document.body.appendChild(elem);
    event.dataTransfer.setDragImage(elem, 0, 0);
  }

document.addEventListener("dragend", function(e) {
  var ghost = document.getElementById("import_handler_drag_ghost");
  if (ghost.parentNode) {
    //ghost.parentNode.removeChild(ghost);
    $('#import_handler_drag_ghost').fadeOut(3000, function() {
      $('#import_handler_drag_ghost').remove();
    });
  }

}, false);
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}

body {
  height: 900px;
}

div:last-child {
  position: absolute;
  overflow: hidden;
  left: 10px !important;
  top: 264px !important;
  border: 1px solid #dedede;
  background: #e5e5e5;
  //padding: 32px;
  height: 100%;
}

#import_handler_drag_ghost {
  width: 90px !important;
  height: 25px !important;
  border: 2px solid;
  background: #fff;
  padding: 0px !important;
}

#graph-wrapper {
  height: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
  mxBasePath = 'https://jgraph.github.io/mxgraph/javascript/src';
</script>
<script src="https://jgraph.github.io/mxgraph/javascript/src/js/mxClient.js"></script>

Помогите пожалуйста заранее спасибо!!!


person Community    schedule 19.04.2019    source источник
comment
Не ясно, пожалуйста, объясните подробнее, что вы подразумеваете под симуляцией? какой вывод вы хотите?   -  person Shoyeb Sheikh    schedule 19.04.2019
comment
Перетаскивание прямоугольника должно происходить для текста, вот и все   -  person    schedule 19.04.2019
comment
Если текст, имитирующий прямоугольник, перетаскивается, он должен вести себя как прямоугольник.   -  person    schedule 19.04.2019
comment
Вы хотите изменить размер или переместить текст с помощью щелчка/перетаскивания?   -  person apocalysque    schedule 21.04.2019
comment
Если я перетащу текст rectangle, должен появиться и должен имитировать rectangle drag   -  person    schedule 21.04.2019
comment
Я все еще не могу решить. пожалуйста, помогите мне. мой вопрос прост. если текст dragged из sidebar, он должен рассматриваться как rectangle фиксированного размера.   -  person    schedule 23.04.2019
comment
Пожалуйста, обратите внимание, что я упростил свой question. осталось всего 2 дня до истечения срока действия Bounty. пожалуйста, помогите мне с вашим ценным решением.   -  person    schedule 26.04.2019


Ответы (2)


Вы были на правильном пути. В обработчике событий перетаскивания создайте вершинный объект и заполните его данными таблицы.

Итак, для перетаскиваемых строк таблиц: <tr draggable="true" ondragstart="drag(event)">...</tr>

Дайте контейнеру (сетке) идентификатор, чтобы вы могли найти его позже, и добавьте обработчики событий dragover и drop:

// Creates the div for the graph
var container = document.createElement("div");   
container.id = "grid" // an ID so we can find it later
container.style.position = "absolute";
// etc...

container.addEventListener("dragover", function(event) {
  event.preventDefault();
});

container.addEventListener("drop", function(event) {
  drop(event);
});

...

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.innerText); // save whatever text you want here
}

function drop(ev) {
  ev.preventDefault();

  var data = ev.dataTransfer.getData("text");

  // Gets the default parent for inserting new cells. This
  // is normally the first child of the root (ie. layer 0).
  var parent = graph.getDefaultParent();
  graph.getModel().beginUpdate();

  var gridRect = $('#grid')[0].getBoundingClientRect();
  var targetX = ev.x - gridRect.x;
  var targetY = ev.y - gridRect.y;

  try {
    var v1 = graph.insertVertex(parent, null, data, targetX, targetY, 300, 30);
  } finally {
    // Updates the display
    graph.getModel().endUpdate();
  }
}

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

Codepen: перетаскивание строк таблицы

person K Scandrett    schedule 26.04.2019
comment
Другое изменение, которое я сделал, заключалось в том, чтобы сделать graph глобальным объектом, чтобы я мог ссылаться на него позже. - person K Scandrett; 26.04.2019
comment
Проверено в Фаерфоксе - person K Scandrett; 26.04.2019
comment
большое спасибо за вашу большую помощь, пожалуйста, посмотрите на этот мой вопрос stackoverflow.com/questions/55835272/ - person ; 27.04.2019

Добрый день.

1. Во-первых, вы не можете просто добавить элемент

setTimeout(function(){
     var html = '<div class="simulate"><p>Simulate Above Rect Drag</p></div><div 
     class="simulate"><p>Simulate Above Rect Drag</p></div>';
    $('.geSidebarContainer').append(html);
},3500);

Механика перетаскивания реализована собственными обработчиками событий js!

Draw.io использует собственную механику для боковой панели и перетаскивания элементов с боковой панели!

Если вы не хотите жесткого кода (и застряли в кодовой базе draw.io), лучше используйте реализованный механизм Draw.io

2.in Sidebar.js Вы можете добавить собственную палитру

Sidebar.prototype.init = function()
{
    var dir = STENCIL_PATH;

    this.addSearchPalette(true);
    this.addFalconPalette(true);   //Thats my pallete
    .......
}

3.Добавьте свой код поддона В этот код вы можете добавить пользовательские элементы, что бы вы ни захотели!

Sidebar.prototype.addFalconPalette = function(expand)
{

    // Avoids having to bind all functions to "this"
    var sb = this;

    // Reusable cells
    var field = new mxCell('+ field: type', new mxGeometry(0, 0, 100, 26), 'text;strokeColor=none;fillColor=none;align=left;verticalAlign=top;spacingLeft=4;spacingRight=4;overflow=hidden;rotatable=0;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;');
    field.vertex = true;

    var divider = new mxCell('', new mxGeometry(0, 0, 40, 8), 'line;strokeWidth=1;fillColor=none;align=left;verticalAlign=middle;spacingTop=-1;spacingLeft=3;spacingRight=3;rotatable=0;labelPosition=right;points=[];portConstraint=eastwest;');
    divider.vertex = true;

    var w = 50;     var h = 50;

    var s = 'shape=mxgraph.bpmn.shape;html=1;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;verticalAlign=top;align=center;perimeter=ellipsePerimeter;outlineConnect=0;';
    var dt = 'Falcon';

    var s2 = 'shape=mxgraph.bpmn.shape;html=1;verticalLabelPosition=bottom;labelBackgroundColor=#ffffff;verticalAlign=top;align=center;perimeter=rhombusPerimeter;background=gateway;outlineConnect=0;';
    //default tags
    var dt2 = 'bpmn business process model gateway '; 


    var fns = [
        this.createVertexTemplateEntry(s + 'outline=standard;symbol=general;', w, h, getxml("StartEvent",1), 'StartEvent', null, null, dt + 'general start'),
        this.createVertexTemplateEntry(s + 'outline=end;symbol=general;', w, h, getxml("EndEvent",1), 'EndEvent', null, null, dt + 'general end'),

        this.addEntry(this.getTagsForStencil('mxgraph.bpmn', 'user_task').join(' '), function()
        {
            var cell = new mxCell(getxml("UserTask"), new mxGeometry(0, 0, 120, 80), 'html=1;whiteSpace=wrap;rounded=1;');
            cell.vertex = true;

            // var cell1 = new mxCell('', new mxGeometry(0, 0, 14, 14), 'html=1;shape=mxgraph.bpmn.user_task;outlineConnect=0;');
            // cell1.vertex = true;
            // cell1.geometry.relative = true;
            // cell1.geometry.offset = new mxPoint(7, 7);
            // cell.insert(cell1);

            return sb.createVertexTemplateFromCells([cell], cell.geometry.width, cell.geometry.height, 'User Task');
        }),

        this.createVertexTemplateEntry(s2 + 'outline=none;symbol=exclusiveGw;', w, h, getxml("ExclusiveGateway",1), 'Exclusive Gateway', null, null, dt2 + 'exclusive'),
        this.createVertexTemplateEntry(s2 + 'outline=none;symbol=parallelGw;', w, h, getxml("ParallelGateway",1), 'Parallel Gateway', null, null, dt2 + 'parallel'),
    ];

    this.addPaletteFunctions('bpmnEvents', mxResources.get('falcon'), expand || false, fns);
};

4. Нет необходимости переделывать механику перетаскивания с боковой панели. Вам просто нужно понять, как работает боковая панель!

5. Лучше клонировать репозиторий Draw.io! https://github.com/jgraph/drawio Посмотрите на addGeneralPalette, там уже есть пользовательский текстовый элемент!

Sidebar.prototype.addGeneralPalette = function(expand)
{
    //return false;
    var lineTags = 'line lines connector connectors connection connections arrow arrows ';

    var fns = [
        this.createVertexTemplateEntry('rounded=0;whiteSpace=wrap;html=1;', 120, 60, '', 'Rectangle', null, null, 'rect rectangle box'),
        this.createVertexTemplateEntry('rounded=1;whiteSpace=wrap;html=1;', 120, 60, '', 'Rounded Rectangle', null, null, 'rounded rect rectangle box'),
        // Explicit strokecolor/fillcolor=none is a workaround to maintain transparent background regardless of current style
        this.createVertexTemplateEntry('text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;',
            40, 20, 'Text', 'Text', null, null, 'text textbox textarea label'),
        this.createVertexTemplateEntry('text;html=1;strokeColor=none;fillColor=none;spacing=5;spacingTop=-20;whiteSpace=wrap;overflow=hidden;rounded=0;', 190, 120,
            '<h1>Heading</h1><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>',
            'Textbox', null, null, 'text textbox textarea'),

введите здесь описание изображения

person Diaskhan    schedule 21.04.2019
comment
В настоящее время реализует собственный конструктор Bpmn! на основе Draw.io - person Diaskhan; 21.04.2019
comment
отлично, но я хочу, чтобы текст был обрамлен рамкой, то есть rectangle с text внутри. вы показали Заголовок с текстом lorem ipsum, который не заключен в границу. Мое ожидание очень простое: ** мне не нужна никакая фигура в sidebar, мне нужен текст, если он dragged в **контейнере, он должен стать rectangle. - person ; 22.04.2019
comment
Это не имеет значения, потому что в mxgrap есть два возможных объекта. Край и вершина. Все остальные вещи сделаны с помощью стилизации объекта! Стиль тега! ‹mxCell id=MXCwDfMTKnOZLDN-ocCG-1 значение=стиль текста=текст;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0; vertex=1 parent=1› ‹mxGeometry x=40 y=60 width=40 height=20 as=geometry/› ‹/mxCell› - person Diaskhan; 22.04.2019
comment
Проанализируйте github.com/jgraph/mxgraph/blob/master/javascript /examples/ Нужно изучить основы mxgraph! - person Diaskhan; 22.04.2019
comment
Я все еще не могу решить. пожалуйста, помогите мне. мой вопрос прост. если текст dragged из sidebar, его следует рассматривать как rectangle фиксированного размера. - person ; 23.04.2019
comment
Вам нужно использовать его jqueryui.com/draggable после запуска события перетаскивания, вы должны вызвать этот код var v1 = graph .insertVertex(родительский, ноль, «Здравствуйте», 20, 20, 80, 30);. Я надеюсь, что это помогает!!! - person Diaskhan; 23.04.2019
comment
Вы можете показать это один раз. Я действительно смущен и ничего не понимаю. пожалуйста, помогите мне - person ; 24.04.2019
comment
Здесь stackoverflow.com /вопросы/34608701/ - person Diaskhan; 24.04.2019
comment
Я упростил свой Вопрос, пожалуйста, посмотрите. пожалуйста, помогите мне - person ; 26.04.2019