Skip to content

Network Mapper Shapes and Layers Developer Guide 2

Ed Mozley edited this page Nov 24, 2026 · 3 revisions

Network Mapper - Shapes and Layers - Developer Guide (Part 2)

Part 1: tables, node styling, shapes, pages and layers Β· Part 2 of 2 Β· the basics: Network Mapper - Developer Guide Β· what the analyst sees: Network Mapper

In plain words

This part is about doing things to several items at once, joining anything to anything, the right-click menus, and how a save carries all of it through a server that replaces every row each time. The files table and the schema are in Part 1. The one idea to hold on to: row ids are thrown away on every save, so everything that must survive a save is a key the browser chose - a node's id/tempId mapped by the server within one save, a shape's uid, a page_key, a layer_key, a group_key.

4. Multi-select and grouping

The selection model

There are now four kinds of selection, and only one is active at a time:

State Holds Panel
selectedNodeKey one nodeKey() node detail panel
selectedShapeKey one shapeKey() Format panel
selectedConnectorKey one connectorKey() Format panel (connector)
multi a Set of 'n:<nodeKey>' / 's:<shapeKey>' Selection panel, in the Format panel's frame
    let multi = new Set();
    let multiDrag = null;        // { start, items: [{it, kind, x0, y0}], moved }
    let band = null;             // rubber band { x0, y0, el, add }
    let clipboard = null;        // { nodes, shapes, connectors } copied with Ctrl+C

    const mkN = n => 'n:' + nodeKey(n);
    const mkS = s => 's:' + shapeKey(s);

The prefix is needed because a node key 'r12' and a shape key 's12' live in one set. Connectors are never in multi; a multi-selection carries its connectors implicitly (copy takes the ones between selected items, delete takes the ones touching them).

Every change of selection goes through setSelection(list), which enforces "one item is an ordinary selection, two or more is a multi-selection":

    function setSelection(list) {
        const keys = new Set(list.map(x => x.kind === 'n' ? mkN(x.it) : mkS(x.it)));
        if (keys.size < 2) {
            multi = new Set();
            applyMultiClasses();
            const only = list[0];
            if (!only) { selectNode(null); selectShape(null); selectConnector(null); closeShapePanel(); return; }
            if (only.kind === 'n') selectNode(nodeKey(only.it)); else selectShape(shapeKey(only.it));
            return;
        }
        selectNode(null);
        selectConnector(null);
        if (selectedShapeKey != null) { const p = findShapeByKey(selectedShapeKey); selectedShapeKey = null; if (p) rerenderShape(p); }
        multi = keys;
        applyMultiClasses();
        renderMultiPanel();
    }

The single-selection functions clear multi in turn (selectNode(), selectShape() and selectConnector() each start with if (key != null && multi.size) { multi = new Set(); applyMultiClasses(); }), so the four states cannot overlap. applyMultiClasses() only toggles the in-multi class on the existing elements, it never rebuilds them, so selecting 200 items does not re-render 200 items.

Clicking: Shift, Ctrl, Alt and groups

Both onNodeMouseDown() and onShapeMouseDown() hand the event to multiMouseDown() first and stop if it returns true:

        if (multiMouseDown(e, 'n', n)) return;   // GH #433: Shift-click, the selection, a group
    function multiMouseDown(e, kind, it) {
        if (e.button !== 0) return false;
        const key = kind === 'n' ? mkN(it) : mkS(it);
        if (e.shiftKey || e.ctrlKey || e.metaKey) {
            e.stopPropagation();
            e.preventDefault();
            let cur = multi.size ? multiItems() : [];
            if (!cur.length) {
                if (selectedNodeKey != null) { const n = findNodeByKey(selectedNodeKey); if (n) cur.push({ kind: 'n', it: n }); }
                if (selectedShapeKey != null) { const s = findShapeByKey(selectedShapeKey); if (s) cur.push({ kind: 's', it: s }); }
            }
            const members = e.altKey ? [{ kind, it }] : groupOf(kind, it);

So Shift-click (or Ctrl / Cmd) toggles the item and its group in or out of the selection, starting from whatever single item was selected. Holding Alt as well toggles just the one item. Without a modifier:

        // Alt+click picks one item out of its group - even while the whole group is selected.
        if (e.altKey) { if (multi.size) clearMulti(); return false; }
        let sel = null;
        if (multi.has(key)) sel = multiItems();
        else if (it.group_key && !e.altKey) {
            const g = groupOf(kind, it);
            if (g.length > 1) { setSelection(g); sel = g; }
        }
        if (!sel) { if (multi.size) clearMulti(); return false; }
        e.stopPropagation();
        e.preventDefault();
        if (!canEdit()) return true;
        multiDrag = { start: canvasModelCoords(e), items: sel.map(x => ({ kind: x.kind, it: x.it, x0: x.it.x, y0: x.it.y })), moved: false };

A plain click on an item that is already in the selection starts moving the whole selection; a plain click on a grouped item selects and moves its group; Alt+click picks one item out of its group, and the normal single-item handler takes over - checked before multi.has(key), because right after Ctrl+G the whole group is the selection and an Alt+click inside it would otherwise grab the group again (fixed in 5.11.0). On a read-only version the selection still happens but no drag starts.

onMultiDragMove() moves every item by the same delta from where it started (x0, y0), not by the mouse movement since the last event, so rounding never accumulates:

        const dx = snapS(c.x - multiDrag.start.x), dy = snapS(c.y - multiDrag.start.y);
        if (!multiDrag.moved && !dx && !dy) return;
        multiDrag.moved = true;
        multiDrag.items.forEach(m => {
            m.it.x = Math.max(0, m.x0 + dx);
            m.it.y = Math.max(0, m.y0 + dy);

The delta snaps to the 10px shape grid, so nodes that were on the 20px grid can end up on a 10px position after a multi-drag.

Groups

A group is nothing more than a shared group_key string on network_diagram_nodes and network_diagram_shapes. There is no groups table. groupSelection() makes a fresh key and stamps it on every selected item:

    function groupSelection() {
        const items = multiItems();
        if (items.length < 2 || !canEdit()) return;
        const g = 'g' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
        items.forEach(x => { x.it.group_key = g; });

Grouping a selection that already contains a group therefore replaces the inner key: there are no nested groups. Ungroup sets every selected item's key to null.

Who is in a group is always worked out live, and only among the current page's visible, unlocked items:

    /** The members of an item's group on this page (visible, unlocked) - or just the item. */
    function groupOf(kind, it) {
        if (!it.group_key) return [{ kind, it }];
        return visibleNodes().filter(n => n.group_key === it.group_key && !itemLocked(n)).map(n => ({ kind: 'n', it: n }))
            .concat(visibleShapes().filter(s => s.group_key === it.group_key && !itemLocked(s)).map(s => ({ kind: 's', it: s })));
    }

That keeps groups from ever reaching across pages or grabbing something on a locked layer, even if the same key ends up on both (a duplicated page copies group_key as it is). The server only checks the key's format:

    /** GH #433: a group key - letters, digits, _ and -, up to 40; anything else is no group. */
    private static function groupOf($v): ?string
    {
        $v = is_string($v) ? trim($v) : '';
        return preg_match('/^[A-Za-z0-9_-]{1,40}$/', $v) ? $v : null;
    }

drawGroupOutlines() draws a dashed .nm-group-outline round each group that is part of the selection (or the selected shape's group). Export and Present hide it by CSS.

Rubber band and Ctrl+A

A mousedown on empty canvas (the canvas, the SVG layer itself, or #canvasInner) clears the selection and, outside Present, starts a band:

            if (isCanvasBg || isSvgBg || t === elCanvasInner) {
                selectNode(null);
                selectConnector(null);
                selectShape(null);   // GH #433
                if (!e.shiftKey) clearMulti();
                if (!isPresenting()) startBand(e);   // drag on empty space selects an area
            }

On mouseup, onBandUp() picks items whose whole box is inside the band (not merely touching it), then widens the pick to whole groups, and with Shift adds to what was selected:

        const inside = x => { const bx = boxOf(x); return bx.x >= r.x && bx.y >= r.y && bx.x + bx.w <= r.x + r.w && bx.y + bx.h <= r.y + r.h; };
        let picked = visibleNodes().filter(n => !itemLocked(n)).map(n => ({ kind: 'n', it: n }))
            .concat(visibleShapes().filter(s => !itemLocked(s)).map(s => ({ kind: 's', it: s }))).filter(inside);
        // A grouped item brings its whole group.

A drag of three pixels or less is treated as a click (band.moved), so clicking empty canvas still just clears the selection. Ctrl+A (selectAllOnPage()) uses the same filters: current page, visible, unlocked.

Align and distribute

Both work on boxes from boxOf(), which is nodeExtent() for a node (Part 1) and x, y, w, h for a shape:

    function alignSelection(how) {
        const items = multiItems();
        if (items.length < 2 || !canEdit()) return;
        const B = boundsOf(items);
        items.forEach(x => {
            const b = boxOf(x);
            if (how === 'left') x.it.x = B.x;
            if (how === 'centre') x.it.x = Math.round(B.x + B.w / 2 - b.w / 2);
            if (how === 'right') x.it.x = B.x + B.w - b.w;
            if (how === 'top') x.it.y = B.y;
            if (how === 'middle') x.it.y = Math.round(B.y + B.h / 2 - b.h / 2);
            if (how === 'bottom') x.it.y = B.y + B.h - b.h;
        });
        rerenderAfterMulti();
    }

Align lines items up against the selection's own bounding box B, not against the first-clicked item. Right moves each item so its right edge meets B's right edge; centre puts each item's centre on B's centre line.

    function distributeSelection(axis) {
        const items = multiItems();
        if (items.length < 3 || !canEdit()) return;
        const c = x => { const b = boxOf(x); return axis === 'h' ? b.x + b.w / 2 : b.y + b.h / 2; };
        items.sort((a, b) => c(a) - c(b));
        const first = c(items[0]), last = c(items[items.length - 1]), step = (last - first) / (items.length - 1);
        items.forEach((x, i) => {
            const b = boxOf(x);
            if (axis === 'h') x.it.x = Math.round(first + step * i - b.w / 2);
            else x.it.y = Math.round(first + step * i - b.h / 2);
        });
        rerenderAfterMulti();
    }

Distribute spaces centres evenly: the two outermost items stay where they are and the rest get equal centre-to-centre steps between them. It needs three items (with two there is nothing between). This is "equal centre spacing", not draw.io's "equal gaps"; with items of very different widths the gaps will differ. Neither function snaps to the grid.

The Selection panel (renderMultiPanel()) offers these plus Group / Ungroup, Copy, Delete, Move to layer and one shared style editor. The style editor starts from the first shape's look (or the first node's) and applies a change to every item, each the way its kind stores style: a shape gets its full resolved look plus the patch, a node gets only the changed keys.

Keyboard

All in the document keydown in bindCanvasEvents(), after the guards for form fields, contenteditable and open modals:

Keys Does
Ctrl+A selectAllOnPage()
Ctrl+C copySelection() - skipped when text is selected on the page, so copying text still works
Ctrl+X copy, then delete the selection, the shape or the node
Ctrl+V nothing in keydown - see "Paste" below
Ctrl+G / Ctrl+Shift+G Group / Ungroup
Arrows nudge the multi-selection or the selected shape by 1px (with Shift, 10px)
Delete / Backspace delete the multi-selection, else the shape, connector or node
Escape close a right-click menu, else clear a multi-selection or a selected shape

Arrow nudges are 1px on purpose, finer than both grids; nudge is how an analyst gets off-grid.

Copy and paste

copySelection() deep-copies the items and the connectors whose both ends are among them:

        const ns = items.filter(x => x.kind === 'n').map(x => x.it);
        const ss = items.filter(x => x.kind === 's').map(x => x.it);
        const refs = new Set(ns.map(nodeRef));
        const uids = new Set(ss.map(sh => sh.uid).filter(Boolean));
        const inside = (c, side) => c[side + '_shape_uid'] ? uids.has(c[side + '_shape_uid']) : refs.has(c[side + '_node_id']);
        clipboard = {
            nodes: JSON.parse(JSON.stringify(ns)),
            shapes: JSON.parse(JSON.stringify(ss)),
            connectors: JSON.parse(JSON.stringify(connectors.filter(c => inside(c, 'from') && inside(c, 'to'))))
        };

The clipboard is a module variable, not the system clipboard. It lives as long as the page: it survives page switches and saves inside one diagram, and is gone when the editor is reloaded or another diagram is opened. It is self-consistent even across a save: the copied connectors refer to the copied nodes by the refs they had when copied, and the copied nodes still carry those same refs, so remapConnectors() can still pair them after the live ids have changed.

pasteClipboard(at) places the copies on the current page and active layer:

        const lk = activeLayerKey();
        const here = new Set(pageNodes().map(n => n.cmdb_object_id));
        const groupMap = {};
        const newGroup = g => g ? (groupMap[g] = groupMap[g] || ('g' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6))) : null;
        const fromThisPage = clipboard.nodes.concat(clipboard.shapes).some(x => itemPage(x) === currentPage);
        let off = fromThisPage ? 20 : 0, offY = off;

and then copies each node, skipping one whose CMDB object is already on this page:

        clipboard.nodes.forEach(src => {
            if (here.has(src.cmdb_object_id)) { skipped++; return; }
            const n = Object.assign(JSON.parse(JSON.stringify(src)), { id: null, tempId: nextTempId--, page_key: currentPage, layer_key: lk,
                x: Math.max(0, src.x + off), y: Math.max(0, src.y + offY), group_key: newGroup(src.group_key) });
            refMap.set(nodeRef(src), n.tempId);
            nodes.push(n);
            here.add(n.cmdb_object_id);
            pasted.push({ kind: 'n', it: n });
        });

The decisions in those lines:

  • The CMDB rule: a CMDB object is on a page once (Part 1, "Per-page CMDB objects"). Pasting onto the page the nodes came from skips every node and says so in a toast (network-mapper.select.skipped); shapes always paste. Pasting onto another page brings the nodes across.
  • Offset: 20px along when pasting onto the page it came from, so the copy does not sit exactly on the original; 0 on another page, so a "same layout on page 2" paste lines up. A right-click "Paste here" passes at, and the top-left of the copied items lands on the clicked point instead.
  • Groups: every group in the paste gets a new key (groupMap maps old to new within one paste). The copies form their own group, not a bigger group with the originals.
  • Shapes get a new uid and go on top (z: maxZ + 1 + i).

Then the connectors:

    /** Copies the connectors whose both ends were copied, pointing them at the copies. */
    function remapConnectors(list, refMap, uidMap) {
        const mapEnd = (c, side, out) => {
            const uid = c[side + '_shape_uid'];
            if (uid) { if (!uidMap.has(uid)) return false; out[side + '_shape_uid'] = uidMap.get(uid); out[side + '_node_id'] = null; return true; }
            if (!refMap.has(c[side + '_node_id'])) return false;
            out[side + '_node_id'] = refMap.get(c[side + '_node_id']); out[side + '_shape_uid'] = null; return true;
        };
        list.forEach(c => {
            const out = Object.assign(JSON.parse(JSON.stringify(c)), { id: null, _tempKey: nextTempId-- });
            if (mapEnd(c, 'from', out) && mapEnd(c, 'to', out)) connectors.push(out);
        });
    }

A connector to a skipped node is dropped, because the skipped node never entered refMap. The same function serves duplicatePage() (Part 1).

Finally the clipboard itself moves along, so pasting again steps another 20px instead of landing on the last paste:

        // Paste again and it moves along again.
        clipboard.nodes.forEach(n => { n.x += off; n.y += offY; n.page_key = currentPage; });
        clipboard.shapes.forEach(s => { s.x += off; s.y += offY; s.page_key = currentPage; });

Ctrl+V is not a keydown. The keydown handler returns early on Ctrl+V and lets the browser fire a paste event, because the clipboard might hold a picture from outside the browser and only the paste event can read it:

    function onPaste(e) {
        const a = document.activeElement;
        if (a && (a.tagName === 'INPUT' || a.tagName === 'TEXTAREA' || a.tagName === 'SELECT' || a.isContentEditable)) return;
        if (document.querySelector('.nm-modal-overlay.active')) return;
        const files = Array.from((e.clipboardData && e.clipboardData.files) || []).filter(f => /^image\//.test(f.type));
        if (files.length && canEdit()) {
            e.preventDefault();
            uploadImages(files, lastCanvasPoint);
            return;
        }
        if (pasteClipboard()) e.preventDefault();
    }

A picture wins over the editor's own clipboard. The picture path (My images) is in Network Mapper - Icon Libraries - Developer Guide.

5. Connectors between anything

An end is a node or a shape

A connector end is either *_node_id (a node's real id or negative temp id, as before) or *_shape_uid (a shape's uid). Never both: the save payload nulls the node id whenever a shape uid is set. endOf() is the one function that resolves an end, for drawing and for every check:

    /** One end of a connector: {kind 'n' | 's', it, box} or null when it is gone. */
    function endOf(c, side) {
        const uid = c[side + '_shape_uid'];
        if (uid) { const s = shapeByUid(uid); return s ? { kind: 's', it: s, box: shapeBox(s) } : null; }
        const n = findNodeByRef(c[side + '_node_id']);
        if (!n) return null;
        // The icon for top / left / right, but the bottom of the whole node - a line arriving from
        // below would otherwise end behind the name, arrowhead and all.
        const ib = nodeIconBBox(n);
        const bottom = Math.max(ib.y + ib.h, n.y + nodeExtent(n).h - 6);
        return { kind: 'n', it: n, box: Object.assign({}, ib, { h: bottom - ib.y }) };
    }

The node's box is its icon box stretched down to the bottom of the whole node. Before #433 lines anchored to the icon only, and a line arriving from below ran through the label and hid its arrowhead behind it.

Why shapes have a uid

A node end can use the node's id because the server maps ids within the save (section 7). A shape cannot: shapes are replaced in a separate step (replaceShapes()) after connectors are written, and nothing maps shape row ids to connectors. So each shape carries a uid the browser makes, which the server stores as it is and which never changes:

    function newUid() { return 'u' + Date.now().toString(36).slice(-5) + Math.random().toString(36).slice(2, 8); }
    function ensureShapeUid(s) { if (!s.uid) s.uid = newUid(); return s.uid; }

That is at most 12 characters, inside the VARCHAR(20) and the server's ^[A-Za-z0-9_-]{1,20}$. addShapeAt() gives every new shape a uid; ensurePagesLayers() gives one to any shape loaded without (made before connectors, or through an API caller), and onConnectDragUp() calls ensureShapeUid() again as a belt-and-braces. A uid is unique within a diagram, which is all that matters: the connector's diagram_id already narrows it. Copies (duplicate, paste, duplicate page) always get a new uid; a new version keeps the same uids (section 7).

Connection dots

Nodes keep their four .nm-edge-handle dots on the icon. Shapes got four .nm-shape-port dots, built in buildShapeEl() on an editable, unlocked shape that is not being typed into:

        if (canEdit() && !editing && !itemLocked(s)) {
            // GH #433: drag from a dot to another shape or a node to connect them
            ['top', 'right', 'bottom', 'left'].forEach(side => { html += '<div class="nm-shape-port" data-side="' + side + '"></div>'; });
        }

They sit 14px outside each edge, so they do not collide with the eight resize squares that sit on the edges:

        .nm-shape-port[data-side="top"]    { left: 50%;  top: -14px; }
        .nm-shape-port[data-side="right"]  { left: calc(100% + 14px); top: 50%; }
        .nm-shape-port[data-side="bottom"] { left: 50%;  top: calc(100% + 14px); }
        .nm-shape-port[data-side="left"]   { left: -14px; top: 50%; }
        .nm-shape:hover .nm-shape-port, .nm-shape.selected .nm-shape-port { opacity: 1; }

Both kinds of dot start the same drag. The old startConnectDrag() became a one-line wrapper:

    function startConnectDrag(e, fromNode, side) { startConnectFrom(e, { kind: 'n', it: fromNode }, side); }

Making the connector

onConnectDragUp() hit-tests the drop point - nodes first (icon box, findNodeAt()), then shapes (findShapeAt(), topmost first, the shape it started from excluded) - and builds a connector with every end field present:

        const node = findNodeAt(cursor.x, cursor.y);
        const to = node ? { kind: 'n', it: node } : (findShapeAt(cursor.x, cursor.y, from.kind === 's' ? from.it : null));
        if (!to || to.it === from.it) return;   // nowhere, or itself
        const c = { id: null, _tempKey: nextTempId--, cmdb_relationship_id: null, label: null, line_style: 'solid', style: null,
                    from_node_id: null, to_node_id: null, from_shape_uid: null, to_shape_uid: null };
        if (from.kind === 'n') c.from_node_id = nodeRef(from.it); else c.from_shape_uid = ensureShapeUid(from.it);
        if (to.kind === 'n') c.to_node_id = nodeRef(to.it); else c.to_shape_uid = ensureShapeUid(to.it);
        // The same two ends the same way round already joined: nothing to add.
        if (connectors.some(x => x.from_node_id === c.from_node_id && x.to_node_id === c.to_node_id
                              && (x.from_shape_uid || null) === c.from_shape_uid && (x.to_shape_uid || null) === c.to_shape_uid)) return;

The duplicate rule is unchanged from before #433 - same ends, same direction - just extended to compare all four fields. A connector A to B and one B to A may both exist.

findShapeAt() orders the candidates the way they are drawn, so the drop lands on what the analyst sees on top:

        hits.sort((a, b) => ((b.layer === 'front') - (a.layer === 'front')) || (layerRank(b) - layerRank(a)) || ((b.z || 0) - (a.z || 0)));

A dragged connector is a plain line with no CMDB relationship. Only connectors created through Add related objects carry a cmdb_relationship_id (see the basics page).

Geometry and routing

calcConnectorPoints() is the pre-#433 function with one addition - it now reports which axis won, because elbow and curved lines need it:

        return { x1: x1, y1: y1, x2: x2, y2: y2, axis: Math.abs(dx) > Math.abs(dy) ? 'h' : 'v' };   // GH #433: for elbow / curved
    function connPath(p, routing) {
        if (routing === 'elbow') {
            if (p.axis === 'h') { const mx = (p.x1 + p.x2) / 2; return 'M' + p.x1 + ',' + p.y1 + ' H' + mx + ' V' + p.y2 + ' H' + p.x2; }
            const my = (p.y1 + p.y2) / 2; return 'M' + p.x1 + ',' + p.y1 + ' V' + my + ' H' + p.x2 + ' V' + p.y2;
        }
        if (routing === 'curved') {
            if (p.axis === 'h') { const k = (p.x2 - p.x1) / 2; return 'M' + p.x1 + ',' + p.y1 + ' C' + (p.x1 + k) + ',' + p.y1 + ' ' + (p.x2 - k) + ',' + p.y2 + ' ' + p.x2 + ',' + p.y2; }
            const k = (p.y2 - p.y1) / 2; return 'M' + p.x1 + ',' + p.y1 + ' C' + p.x1 + ',' + (p.y1 + k) + ' ' + p.x2 + ',' + (p.y2 - k) + ' ' + p.x2 + ',' + p.y2;
        }
        return 'M' + p.x1 + ',' + p.y1 + ' L' + p.x2 + ',' + p.y2;
    }

The elbow is always three segments with the bend half way, leaving and arriving along the winning axis - which is the side the end sits on, so the line leaves a box at right angles. The curve is a cubic Bezier whose control points are pulled half the distance along the same axis, so it also leaves and arrives at right angles. There is no obstacle avoidance and no draggable waypoint; a line can cross a shape.

The label sits at the midpoint of the two end points for every routing:

    /** Where the label sits: the middle of the line, whichever way it runs. */
    function connMid(p) { return { x: (p.x1 + p.x2) / 2, y: (p.y1 + p.y2) / 2 }; }

That point is on the line in all three cases: on the elbow's middle segment, and on the curve because a cubic with these symmetric control points passes through the midpoint at t = 0.5. (renderConnectors() calls connMid(pts, st.routing) with a second argument the function ignores.)

Look: colour, width, dash, arrowheads

The look is style JSON plus the old line_style column for the dash, merged over a default:

    const CONN_DEFAULT = { colour: '#64748b', width: 2, arrowStart: 'none', arrowEnd: 'arrow', routing: 'straight' };
    function connStyle(c) { return Object.assign({}, CONN_DEFAULT, c.style || {}); }

The dash stayed in line_style (now solid / dashed / dotted) rather than moving into style, so the REST API and existing data keep working. The dash pattern scales with the width:

    function connDash(lineStyle, w) {
        if (lineStyle === 'dashed') return (w * 3 + 2) + ' ' + (w * 2 + 2);
        if (lineStyle === 'dotted') return '0.1 ' + (w * 2 + 2);
        return '';
    }

'0.1 gap' with stroke-linecap: round (set for dotted) draws round dots of the line's width.

In renderConnectors() colour and width go on as inline style, not attributes, and only when the line is not selected:

            if (isSel) path.classList.add('selected');
            else {
                // Inline style, not attributes: the stylesheet's own stroke would beat an attribute,
                // while the selected rule above still wins over nothing.
                path.style.stroke = st.colour;
                path.style.strokeWidth = String(st.width);
            }

Arrowheads are SVG <marker>s, and a marker cannot inherit the line's colour in every browser, so ensureMarker() makes one marker per (type, colour, width) and keeps it in the layer's <defs>:

    function ensureMarker(type, colour, width) {
        const id = 'nm-mk-' + type + '-' + String(colour).replace('#', '') + '-' + String(width).replace('.', '_');
        if (document.getElementById(id)) return id;
        const defs = elSvgLayer.querySelector('defs');
        const s = 4 + width * 3;                     // a heavier line gets a bigger head
        const m = document.createElementNS(SVG_NS, 'marker');
        m.setAttribute('id', id);
        m.setAttribute('viewBox', '0 0 10 10');
        m.setAttribute('markerUnits', 'userSpaceOnUse');
        m.setAttribute('markerWidth', String(s));
        m.setAttribute('markerHeight', String(s));
        m.setAttribute('refY', '5');
        m.setAttribute('orient', 'auto-start-reverse');

orient="auto-start-reverse" is what lets one marker serve both ends: as marker-start it is flipped to point backwards. markerUnits="userSpaceOnUse" sizes it in canvas pixels instead of multiples of the stroke width, so 4 + width * 3 is the real size. Markers are never removed; a long editing session leaves a few unused ones in <defs>, which is harmless. The id is built from the colour, which is safe only because the colour has passed the hex check on the server and comes from <input type="color"> in the browser.

The connector Format panel

Selecting a connector opens renderConnectorPanel() in the shape Format panel's frame: label, dash (segmented), colour and width, start and end arrowheads, routing, then Swap, Reset and Delete. On a read-only version it shows the same controls disabled and binds nothing.

Swap reverses the direction by exchanging both kinds of end field at once:

        document.getElementById('cpSwap').addEventListener('click', () => {
            ['node_id', 'shape_uid'].forEach(k => { const t2 = c['from_' + k]; c['from_' + k] = c['to_' + k]; c['to_' + k] = t2; });
            renderConnectors(); markDirty();
        });

Swapping only node_id would turn a shape-to-node line into nonsense. A swapped connector keeps its cmdb_relationship_id; that is valid because the server accepts a relationship between the two objects either way round (below). The arrowheads stay as they were, so Swap is how an analyst flips which end has the arrow.

Reset sets style = null and line_style = 'solid', back to the grey arrow.

Deleting a shape or a node removes the connectors on it. For a shape that is touchesShape():

    /** True when a connector has an end on this shape. */
    function touchesShape(c, s) { return !!(s.uid && (c.from_shape_uid === s.uid || c.to_shape_uid === s.uid)); }

What the server keeps

replaceContents() resolves each end. A uid is format-checked; a node end goes through the existing ref map:

            // GH #433: an end may be a shape, named by its uid.
            $uidOf = function (string $prefix) use ($k): ?string {
                $u = isset($k["{$prefix}_shape_uid"]) ? trim((string)$k["{$prefix}_shape_uid"]) : '';
                return preg_match('/^[A-Za-z0-9_-]{1,20}$/', $u) ? $u : null;
            };
            $fromUid = $uidOf('from');
            $toUid   = $uidOf('to');
            $fromId = $fromUid === null ? $resolve('from') : null;
            $toId   = $toUid === null ? $resolve('to') : null;
            if (($fromId !== null && $fromId === $toId) || ($fromUid !== null && $fromUid === $toUid)) {
                throw new ServiceError('validation', 'invalid_field', "connectors[{$i}]: cannot connect something to itself.");
            }
            // A CMDB relationship only ever stands between two nodes.
            $relId = ($fromId !== null && $toId !== null) ? self::resolveRelationshipId($conn, $k['cmdb_relationship_id'] ?? null, $fromId, $toId) : null;

A malformed uid is not silently dropped: it falls through to $resolve(), which finds no ref and throws "needs 'from_ref' or 'from_object_id'". A connector with a shape end never keeps a CMDB relationship, whatever the caller sent. The pre-existing TRAP: in resolveRelationshipId() still applies to node-to-node lines: the relationship must link this connector's two objects, either way round.

The look is cleaned, never refused, like the shape style:

    public static function sanitiseConnectorStyle($in): ?string
    {
        if (is_string($in)) $in = json_decode($in, true);
        if (!is_array($in)) return null;
        $out = [];
        if (isset($in['colour']) && is_string($in['colour']) && preg_match('/^#[0-9a-fA-F]{6}$/', $in['colour'])) $out['colour'] = strtolower($in['colour']);
        if (isset($in['width']) && is_numeric($in['width']) && (float)$in['width'] >= 0.5 && (float)$in['width'] <= 12) $out['width'] = round((float)$in['width'], 1);
        foreach (['arrowStart', 'arrowEnd'] as $k) {
            if (isset($in[$k]) && in_array($in[$k], ['none', 'arrow', 'open', 'diamond', 'circle'], true)) $out[$k] = $in[$k];
        }
        if (isset($in['routing']) && in_array($in['routing'], ['straight', 'elbow', 'curved'], true)) $out['routing'] = $in['routing'];
        return $out ? json_encode($out) : null;
    }

line_style stays strict (LINE_STYLES = ['solid', 'dashed', 'dotted']), because it is an old column the REST API also writes.

The server does not check that a *_shape_uid names a shape in the same save. A connector to a uid with no shape is stored; the editor's ensurePagesLayers() drops it on the next load and the next save deletes it. See Traps.

6. Right-click menus

One builder, one handler

showCtxMenu(x, y, items, parentEl) draws any menu from a list of {label, act, disabled, hint, sub} objects and 'sep' strings. A sub list opens a sub-menu to the side, on hover or on click (for touch), by calling showCtxMenu() again with the parent element:

            if (it.sub) {
                const open = () => {
                    document.querySelectorAll('.nm-ctx-menu.sub').forEach(s => s.remove());
                    m.querySelectorAll('.nm-ctx-item.open').forEach(o => o.classList.remove('open'));
                    b.classList.add('open');
                    const r = b.getBoundingClientRect();
                    const sm = showCtxMenu(r.right - 2, r.top - 4, it.sub, m);
                    sm.classList.add('sub');

The menu is position: fixed on document.body, outside the zoomed canvas, so it is never scaled with the diagram. It is kept on screen: a menu that would run off the right edge moves left, and a sub-menu that would run off flips to the left of its parent.

It closes on a mousedown anywhere outside it (a capture listener, so it closes even when the click lands on something that stops propagation), on window blur, and on Escape:

        document.addEventListener('mousedown', e => { if (!(e.target.closest && e.target.closest('.nm-ctx-menu'))) closeCtxMenu(); }, true);
        window.addEventListener('blur', closeCtxMenu);

There is one contextmenu listener, on #canvas, and it does nothing in Present (the browser's own menu shows there):

        elCanvas.addEventListener('contextmenu', onCanvasContextMenu);   // GH #433: right-click menus

ctxTarget() finds what was right-clicked by walking up from the event target - shape, then node, then connector group:

    function ctxTarget(e) {
        const t = e.target;
        const sEl = t.closest && t.closest('.nm-shape');
        if (sEl) { const s = findShapeByKey(sEl.dataset.key); if (s) return { kind: 's', it: s }; }
        const nEl = t.closest && t.closest('.nm-node');
        if (nEl) { const n = findNodeByKey(nEl.dataset.key); if (n) return { kind: 'n', it: n }; }
        const g = t.closest && t.closest('.nm-connector-group');
        if (g) { const c = findConnectorByKey(g.dataset.connKey); if (c) return { kind: 'c', it: c }; }
        return null;
    }

A locked item has pointer-events: none, so right-clicking it reaches the canvas behind and shows the empty-canvas menu - consistent with "locked means you cannot pick it up".

Right-click selects first

Before building a menu, onCanvasContextMenu() makes the selection match what was clicked, as a left click would - the whole group for a grouped item, and nothing changes when the item is already in a multi-selection:

        if (tg && tg.kind !== 'c') {
            const key = tg.kind === 'n' ? mkN(tg.it) : mkS(tg.it);
            if (!multi.has(key)) {
                // Right-click selects what is under it - its whole group, as a left click would.
                const g = groupOf(tg.kind, tg.it);
                if (g.length > 1) setSelection(g); else setSelection([tg]);
            }
        } else if (tg && tg.kind === 'c') {
            selectConnector(connectorKey(tg.it));
        }

That is why the menu's actions can be the same functions as the toolbar and keyboard (deleteSelection, copySelection, deleteSelectedShape...) - they all act on the selection, and the selection is now the right-clicked thing.

The five menus

Right-clicked Menu
Two or more selected Cut, Copy, Delete, Group, Ungroup, Align (sub), Distribute (sub, 3+ items), Move to layer (sub), Paste style
A shape Edit text, Open article, Link article, Cut, Copy, Paste, Duplicate, Delete, Bring to front, Send to back, In front / Behind, Move to layer (sub), Copy style, Paste style, Reset style
A node Open in CMDB, Add related objects, Change icon, Open article, Link article, Cut, Copy, Delete, Move to layer (sub), Copy style, Paste style, Reset style
A connector Edit label, Swap direction, Routing (sub), Delete
Empty canvas Paste here, Select all, Fit, Centre on page

The "Move to layer" sub-menu is built from the current page's layers, top first, with locked layers disabled:

        const layerSub = apply => pageLayers(currentPage).slice().reverse().map(l => ({ label: l.name, disabled: !ed || l.locked, act: () => apply(l.layer_key) }));

Copy style / Paste style use their own styleClipboard, separate from the item clipboard. A shape copies its full resolved look, a node only its own keys; pasteStyleTo() merges the copied keys over each target the way its kind stores style, so a node pasted with a shape's style gets the shape's fill and border but keeps nothing it cannot use.

Read-only versions

On a historical version ed is false and every item that changes something is shown disabled, not hidden:

            items = [
                { label: M('edit_text'), disabled: !ed, act: () => startShapeTextEdit(s) },
                { label: M('open_article'), disabled: !s.article_id || kbTitle(s.article_id) === null, act: () => openArticle(s.article_id) },
                { label: M('link_article'), disabled: !ed || !canReadKb, act: () => openArticlePicker(a => setItemArticle(s, a)) },

What stays enabled is what changes nothing stored: Copy, Copy style, Open article, Open in CMDB, Select all, Fit. Showing the full menu greyed out tells the analyst the action exists and that this version is frozen. Centre on page is disabled on a read-only version because it moves items. The functions themselves also check canEdit() (or diagram.is_current), and markDirty() is a no-op on a historical version, so a menu item enabled by mistake still cannot change anything - and the server refuses a write to a non-leaf anyway.

The page tab's own right-click menu (openPageMenu()) is separate, older and simpler; it is only bound on the current version.

7. How a save carries all of this

The payload

save() sends everything, every time. The new parts of the body:

                    pages: pages.map(p => ({ page_key: p.page_key, name: p.name, sort: p.sort })),
                    layers: layers.map(l => ({ page_key: l.page_key, layer_key: l.layer_key, name: l.name, sort: l.sort, visible: l.visible !== false, locked: !!l.locked })),
                    // GH #433: the freestanding shapes, in z order
                    shapes: shapes.map(sh => ({
                        shape_type: sh.shape_type, x: sh.x, y: sh.y, w: sh.w, h: sh.h,
                        rotation: sh.rotation || 0, text: sh.text || '', style: sh.style || null,
                        layer: sh.layer || 'back', z: sh.z || 0, icon_id: sh.icon_id || null, uid: sh.uid || null,
                        page_key: itemPage(sh), layer_key: itemLayer(sh), group_key: sh.group_key || null,
                        article_id: sh.article_id || null
                    })),
                    connectors: connectors.map(c => ({
                        from_node_id: c.from_shape_uid ? null : c.from_node_id,
                        to_node_id: c.to_shape_uid ? null : c.to_node_id,
                        from_shape_uid: c.from_shape_uid || null,   // GH #433: an end on a shape
                        to_shape_uid: c.to_shape_uid || null,
                        cmdb_relationship_id: c.cmdb_relationship_id || null,
                        label: c.label || null,
                        line_style: c.line_style || 'solid',
                        style: c.style || null
                    }))

Each node additionally sends colour_override, w, h, style, page_key, layer_key, group_key and article_id. Shapes send no id and no tempId at all - nothing on the server needs them. Every field is listed by hand, which is why editor-only caches such as n._iconY never leak into the database.

api/network-mapper/save_diagram.php maps nodes and connectors onto the service's canonical names (ref, from_ref, to_ref, Part 1 shows the shapes / pages lines) and calls NetworkMapperService::saveDiagram().

The order inside the transaction

            if ((isset($in['nodes']) && is_array($in['nodes'])) || (isset($in['connectors']) && is_array($in['connectors']))) {
                self::replaceContents($conn, $ctx, $diagramId, $in['nodes'] ?? [], $in['connectors'] ?? [], $articles);
            }
            // GH #433: shapes are replaced only when the caller sends them, so an API
            // caller that only knows about nodes and connectors never wipes them.
            if (isset($in['shapes']) && is_array($in['shapes'])) {
                self::replaceShapes($conn, $diagramId, $in['shapes'], $articles);
            }
            // GH #433: pages and their layers, when the caller sends them.
            if (isset($in['pages']) && is_array($in['pages'])) {
                self::replacePages($conn, $diagramId, $in['pages'], is_array($in['layers'] ?? null) ? $in['layers'] : []);
            }
            $conn->commit();

All three run in the one transaction saveDiagram() opened, so a refusal anywhere - a bad colour on node 40, a malformed shape type, no pages - rolls back everything including the metadata update. Connectors are written before shapes. That only works because a shape end is a uid string with no foreign key; had connectors pointed at shape row ids, they would have to be written after the shapes and re-mapped.

What survives, and how

Every row id is new after a save. This is how each kind of link survives:

Link Carried by Mapped where
Connector to node the node's id or negative tempId, sent as ref replaceContents(): $refMap[$ref] = $newId while inserting nodes, then each connector's from_ref / to_ref looked up in it
Connector to shape the shape's uid not mapped - stored as it is, the same string before and after
Item to page page_key not mapped - small integer the browser chose
Item to layer page_key + layer_key not mapped
Group membership group_key not mapped - shared string
Layer to page page_key on the layer row not mapped

Only the node link needs mapping, and only because node ids pre-date #433. Everything added since uses a key the browser owns, so the server never has to translate it.

After the POST, save() reloads with api/network-mapper/get_diagram.php and rebuilds its arrays. The selection has to be re-found without ids:

            // GH #433: shapes have no natural id across the reload - keep the selection by position
            // (the array is kept in z order and the server returns ORDER BY z, id).
            const selShapeIdx = selectedShapeKey != null ? shapes.indexOf(findShapeByKey(selectedShapeKey)) : -1;
                ensurePagesLayers();
                if (multi.size) { multi = new Set(); closeShapePanel(); }   // temp keys are gone
                selectedShapeKey = selShapeIdx >= 0 && shapes[selShapeIdx] ? shapeKey(shapes[selShapeIdx]) : null;
                if (selectedCmdbId) {
                    const reselect = pageNodes().find(n => n.cmdb_object_id === selectedCmdbId);
                    if (reselect) selectNode(nodeKey(reselect));
                }

A selected node is re-found by CMDB object on the current page; a selected shape by its index in the z-ordered array; a multi-selection and a connector selection are dropped. currentPage is a plain number and survives untouched, so the analyst stays on the same tab. (The shape could have been re-found by uid instead of index; the index works because renderShapes() keeps the array sorted, see Part 1.)

New versions copy everything

createVersion() copies nodes with a node map, then connectors through that map, and copies shapes, pages and layers with INSERT ... SELECT because their keys need no translation:

            foreach ($conns->fetchAll(PDO::FETCH_ASSOC) as $k) {
                // GH #433: either end may be a shape (uid, unchanged in the copy) instead of a node.
                $insertConn->execute([
                    $newId,
                    $k['from_node_id'] !== null ? ($nodeMap[(int)$k['from_node_id']] ?? null) : null,
                    $k['to_node_id'] !== null ? ($nodeMap[(int)$k['to_node_id']] ?? null) : null,
                    $k['from_shape_uid'] ?? null, $k['to_shape_uid'] ?? null,
                    $k['cmdb_relationship_id'] !== null ? (int)$k['cmdb_relationship_id'] : null,
                    $k['label'], $k['line_style'], $k['style'] ?? null,
                ]);
            }
            // GH #433: and the freestanding shapes.
            $conn->prepare(
                "INSERT INTO network_diagram_shapes (diagram_id, shape_type, x, y, w, h, rotation, text, style, layer, z, icon_id, page_key, layer_key, group_key, uid, article_id)
                 SELECT ?, shape_type, x, y, w, h, rotation, text, style, layer, z, icon_id, page_key, layer_key, group_key, uid, article_id FROM network_diagram_shapes WHERE diagram_id = ? ORDER BY id"
            )->execute([$newId, $parentId]);
            // ...and the pages and layers they sit on.
            $conn->prepare("INSERT INTO network_diagram_pages (diagram_id, page_key, name, sort) SELECT ?, page_key, name, sort FROM network_diagram_pages WHERE diagram_id = ?")
                 ->execute([$newId, $parentId]);
            $conn->prepare("INSERT INTO network_diagram_layers (diagram_id, page_key, layer_key, name, sort, visible, locked)
                            SELECT ?, page_key, layer_key, name, sort, visible, locked FROM network_diagram_layers WHERE diagram_id = ?")
                 ->execute([$newId, $parentId]);

The new version's shapes keep the same uids as the old version's. That is correct (uids only need to be unique within one diagram row) and it is what keeps the copied shape connectors pointing at the copied shapes without any map. The node insert copies colour_override, w, h, style, page_key, layer_key, group_key and article_id too. As before, the copy is of what is stored, which is why openNewVersionModal() saves first when the diagram is dirty.

deleteDiagram() deletes connectors, nodes, shapes, layers and pages explicitly before the diagram rows, rather than relying on ON DELETE CASCADE: a grown install may not have the foreign keys yet (see the long comment above the Network Mapper foreign keys in api/system/db_verify.php).

The REST API

Before 5.11.0 the REST resource returned none of this, so an agent that read a diagram and wrote it back put every node on page 0 with the plain look and lost every connector that ended on a shape. api/v1/resources/network_mapper.php now returns each piece under the same field name a full-replace PATCH accepts, so "GET, change one thing, PATCH it back" keeps everything. The node serializer:

        'icon_override' => $n['icon_override'],
        // GH #433: the node's own look and place. Sent back unchanged in a full-replace PATCH,
        // these keep it - leave them out and the node goes back to the plain look on page 0.
        'colour_override' => $n['colour_override'] ?? null,
        'w'             => isset($n['w']) ? (int)$n['w'] : null,
        'h'             => isset($n['h']) ? (int)$n['h'] : null,
        'style'         => apiNmJson($n['style'] ?? null),
        'page_key'      => (int)($n['page_key'] ?? 0),
        'layer_key'     => (int)($n['layer_key'] ?? 0),
        'group_key'     => $n['group_key'] ?? null,
        'article_id'    => isset($n['article_id']) ? (int)$n['article_id'] : null,

Connectors were read with an inner join on both nodes, which hid every connector with a shape end. The joins are LEFT now and each end says which kind it is:

         LEFT JOIN network_diagram_nodes fn ON fn.id = k.from_node_id      -- LEFT: an end can be a shape (GH #433)
         LEFT JOIN network_diagram_nodes tn ON tn.id = k.to_node_id
         LEFT JOIN cmdb_objects fo  ON fo.id  = fn.cmdb_object_id
         LEFT JOIN cmdb_objects to2 ON to2.id = tn.cmdb_object_id
        // GH #433: an end is a node (node_id, object_*) or a shape (shape_uid) - the others are null.
        'from'         => [
            'node_id'     => $k['from_node_id'] === null ? null : (int)$k['from_node_id'],
            'object_id'   => $k['from_object_id'] === null ? null : (int)$k['from_object_id'],
            'object_name' => $k['from_object_name'],
            'shape_uid'   => $k['from_shape_uid'] ?? null,
        ],

Everything else on the diagram comes from one helper, apiNmExtrasForDiagram(), added to both GET and every full response (create, PATCH, new version) with $out += apiNmExtrasForDiagram($conn, $diagramId);. It returns shapes, pages, layers and related_article_ids. Article ids only: a title is governed by Knowledge's own visibility, which an API key is not judged against here. Each query is wrapped so an install that has not run DB Verify since #433 answers with empty lists rather than a 500.

To write a diagram back, a client maps the read into the PATCH shape - nodes carry a ref, and each connector end becomes {from,to}_ref or {from,to}_shape_uid. This is exactly what tests/api-network-mapper-drawing.php does:

    $nodes = array_map(fn($n) => ['cmdb_object_id' => $n['object']['id'], 'ref' => 'n' . $n['id']]
        + array_intersect_key($n, array_flip(['x', 'y', 'size', 'icon_override', 'colour_override', 'w', 'h', 'style', 'page_key', 'layer_key', 'group_key', 'article_id'])), $g['nodes']);
    $end = fn(array $e, string $p) => $e['shape_uid'] !== null ? ["{$p}_shape_uid" => $e['shape_uid']] : ["{$p}_ref" => 'n' . $e['node_id']];
    $connectors = array_map(fn($k) => $end($k['from'], 'from') + $end($k['to'], 'to') + ['label' => $k['label'], 'line_style' => $k['line_style'], 'style' => $k['style']], $g['connectors']);

The incremental endpoints learned the new fields too:

Endpoint What changed
PATCH .../nodes/{node_id} Takes colour_override, w, h, style, page_key, layer_key, group_key. A field not sent is left alone; null clears colour, size and style. Validated with the service's own sanitiseStyle(), keyOf() and groupOf() (now public)
POST .../connectors An end may be from_shape_uid / to_shape_uid (apiNmResolveShapeEnd() checks the shape is on the diagram, else 422); takes style; a CMDB relationship is only ever bound between two nodes
PATCH .../connectors/{id} Takes style; cmdb_relationship_id on a connector with a shape end is a 422
Both connector endpoints API_NM_LINE_STYLES is ['solid', 'dashed', 'dotted']

The OpenAPI schemas (api/v1/lib/openapi_schemas.php: NetworkNode, NetworkConnector, NetworkConnectorEndpoint, the new NetworkShape, NetworkPage, NetworkLayer) and the endpoint text in api/v1/spec.json were edited by hand - never through api/v1/dev/openapi_fix.php, which rewrites the file and strips its comments - then checked with api/v1/dev/openapi_verify.php against live responses holding every new field.

Traps

There is one TRAP: comment in this code (in resolveRelationshipId(), about the relationship linking the connector's two objects - it pre-dates #433 and still applies). These are the other things that will bite:

  • πŸ”΄ A NULL node id is not an orphan. Before attaching the foreign keys, api/system/db_verify.php sweeps connectors whose node is gone. Since #433 a shape end has from_node_id IS NULL, so the original sweep (LEFT JOIN network_diagram_nodes n ON n.id = c.from_node_id WHERE n.id IS NULL) deleted every connector that ended on a shape, on every DB Verify run. Found while writing this page (2026-11-24) and fixed before 5.11.0 shipped, so no released version had it. Any sweep over a column that can legitimately be NULL needs the IS NOT NULL guard:
                $conn->exec("DELETE c FROM network_diagram_connectors c LEFT JOIN network_diagram_nodes n ON n.id = c.from_node_id WHERE c.from_node_id IS NOT NULL AND n.id IS NULL");   // TRAP: a shape end has a NULL node id - not an orphan
                $conn->exec("DELETE c FROM network_diagram_connectors c LEFT JOIN network_diagram_nodes n ON n.id = c.to_node_id WHERE c.to_node_id IS NOT NULL AND n.id IS NULL");

tests/network-mapper-connectors.php reads those two statements out of api/system/db_verify.php, runs each as a SELECT COUNT(*) against a diagram holding shape-end connectors, and fails if any would be deleted - so the test follows the real SQL rather than a copy of it.

  • πŸ”΄ A REST client must send the new fields back. A full-replace PATCH with nodes rebuilds every node from what is sent, so a client that drops colour_override, style, page_key and the rest resets those nodes. GET returns them under the names PATCH accepts (see The REST API); a client written before 5.11.0 that builds nodes from scratch should switch to the single-node PATCH, which leaves unsent fields alone.
  • ⚠️ Rotation is visual only. x, y, w, h are the unrotated box. Connector end points (shapeBox()), connection dots, findShapeAt(), the rubber band, align, distribute and the export bounds all use the unrotated box, and the resize handles turn with the shape while the resize maths does not. A shape at 0, 90, 180 or 270 degrees behaves; anything else is approximate.
  • ⚠️ Never keep a row id across a save - this was true for nodes before #433 and is now true for shapes, pages and layers. Use uid, page_key, layer_key, group_key; for nodes, the browser re-finds by cmdb_object_id on the current page.
  • ⚠️ shapes.sort() in renderShapes() sorts the model in place, and save() re-finds the selected shape by array index. Sorting a copy instead breaks shape re-selection after a save without any error.
  • ⚠️ A node's style holds only changed keys; a shape's holds its full look. Code that reads a style must resolve it the right way: Object.assign({}, NODE_STYLE_SHOWN, n.style || {}) for a node, nmShapeStyle(type, s.style) for a shape. Reading n.style.fill directly gives undefined for most nodes.
  • ⚠️ Sending pages without layers deletes every layer row. api/network-mapper/save_diagram.php turns a missing layers into [] when pages is present.
  • ⚠️ The server does not check that a connector's shape uid exists, or that an item's page or layer exists. Both are repaired in the browser by ensurePagesLayers() on load, not refused on save. Code that reads diagrams server-side (a report, an export) must tolerate a connector to a uid with no shape and an item on a page with no row.
  • ⚠️ Autosave must wait for every gesture. The reload after a save replaces nodes, shapes and connectors under whatever is in progress, so scheduleAutosave() reschedules while any of nodeDrag, nodeResize, shapeDrag, shapeResize, shapeEditKey, multiDrag, band or connectDrag is set, or focus is in a connector label, page or layer rename box. Until 5.11.0 the last four were missing and a rubber band could be cut short by a save. Add any new drag or inline editor to that list.
  • πŸ”΄ An edit made while a save is in flight must survive the reload. The request carries the diagram as it was when Save started; the reload afterwards replaces nodes, shapes, connectors, pages and layers with what the server has. Until 5.11.0 anything changed in between was silently lost, with the status reading Saved. markDirty() now bumps editSeq, and save() compares it twice - after the POST and after the reload fetch:
        const seqAtStart = editSeq;
        // TRAP: anything changed after this point is NOT in the request. The reload below would
        // replace nodes / shapes / connectors with what the server has and quietly lose it, so
        // if editSeq moves on we keep the editor's own state and save again (GH #433). Ids in a
        // save are only keys that wire connectors to nodes, so re-sending them is safe.
        const editedSince = () => editSeq !== seqAtStart;
            if (editedSince()) { saveAgainAfterEdits(); return; }
    function saveAgainAfterEdits() {
        dirty = true;
        setStatus('unsaved');
        if (autosaveOn) scheduleAutosave();
        else setTimeout(() => { if (dirty && !saveInFlight) save(true); }, 0);   // a manual save: finish the job it started
    }

Skipping the reload is safe because the ids in a save are only keys that wire connectors to nodes (api/network-mapper/save_diagram.php uses id ?? tempId as the ref), so the next save can send the editor's stale ids. Proven in the browser with a save slowed to 1.5 s: the old code kept 1px of a 31px move, the new one saves all 31 in two saves.

  • ⚠️ A copy of one member is not in the group. duplicateSelectedShape() sets group_key: null on the copy; paste gives copied groups a fresh key of their own. Until 5.11.0 Duplicate kept the key, so the copy silently joined the original's group.
  • πŸ”΄ No marker-end in the export CSS. captureCanvas() clears the selection and redraws the connectors before html2canvas runs, so each line already carries its own markers. An old rule, .nm-canvas-inner.is-exporting .nm-connector-line { marker-end: url(#nm-arrow) !important; }, beat them (a CSS property wins over the marker-end attribute) and put the default arrow on every line in PNG / PDF - diamonds, open arrows and lines set to no arrow alike. Removed in 5.11.0; a TRAP: comment marks the spot in network-mapper/diagram.php.
  • ⚠️ A locked item is out of reach twice over. CSS gives .is-locked pointer-events: none, which covers clicks and right-clicks, but every hit test done in JavaScript (findNodeAt(), findShapeAt(), the band, Select all, groupOf()) filters with itemLocked() by hand. A new hit test that forgets it lets a connector or a selection reach a locked item.
  • ⚠️ Ctrl+V is handled by the paste event, not keydown. Adding a paste shortcut in the keydown handler would stop pictures being pasted.

Tests

All four are CLI-only service tests (see tests/README.md): they refuse to run unless FREEITSM_TEST_DATABASE names the database config.php uses, they need two CMDB objects on the install, every diagram they make is a ZZ diagram deleted in finally, and every refusal they check has a positive control next to it.

Test Proves
tests/network-mapper-node-style.php colour_override, w and h save (colour lower-cased) and a node without them stays NULL; red and rgba() are refused while #0d9488 saves; a width under 20 and a height over 2000 are refused while 20 and 2000 save; an empty colour means none; a new version carries colour and box size
tests/network-mapper-shapes.php sanitiseStyle() keeps known keys with good values, drops unknown keys, bad colours, out-of-range numbers and non-booleans, returns NULL when nothing is left, and reads a JSON string; shapes save in z order with CRLF made LF, rotation and layer kept, an unknown well-formed type kept and sizes clamped to 10..5000; a node style saves sanitised; a bad, missing or non-object shape_type is refused and the refusal changes nothing; a metadata-only save and a nodes-and-connectors save leave shapes alone while an empty list clears them; a new version copies shapes and node style; deleting a version removes its shapes
tests/network-mapper-pages.php two pages save, a repeated key is dropped, a long name is cut to 100; layers save with hidden / locked and a layer of a missing page is dropped; nodes and shapes keep their page and layer; a group key is kept and a malformed one saves as no group; no pages at all is refused (with a single page as the positive control) and the refusal changes nothing; a metadata-only save keeps pages and layers; a new version copies pages, layers, groups and every item's page and layer; deleting a version removes them
tests/network-mapper-connectors.php node-node, shape-shape and shape-node connectors save; a shape end has no node id; dotted is a line style; the style JSON is kept with the colour lower-cased and unknown keys dropped; a CMDB relationship is never kept on a shape end; DB Verify's orphan sweep would not delete a shape-end connector; shapes keep their uid; a shape connected to itself, an end with no usable node or shape, and an unknown line style are refused while a good list saves; a new version copies both connectors (the shape one by uid with its style), the shapes keep their uids, and the node connector points at the new version's nodes

The REST round trip is covered by tests/api-network-mapper-drawing.php (16 checks: GET returns everything, a read-then-write keeps it, the single-node and single-connector endpoints and their refusals). What no test covers yet: anything in the browser - multi-select, align, paste, the menus and layer locking are verified by hand only.


Back to Part 1 Β· Network Mapper - Developer Guide Β· Network Mapper - Icon Libraries - Developer Guide Β· Network Mapper - Knowledge and Export - Developer Guide Β· REST API: Network Mapper Β· Code Traps

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally