Skip to content

Network Mapper Shapes and Layers Developer Guide

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

Network Mapper - Shapes and Layers - Developer Guide

Part 1 of 2 Β· Part 2: multi-select, connectors, menus and saving Β· the basics this builds on: Network Mapper - Developer Guide Β· what the analyst sees: Network Mapper

In plain words

Before GH #433 a diagram was CMDB nodes and the lines between them, nothing else. In November 2026 the editor grew everything a draw.io user expects: a node can have its own colour, box size and look; freestanding shapes (rectangles, flowchart symbols, arrows, zones, text, notes) sit beside the nodes; a diagram has pages (tabs) and each page has layers that can be hidden or locked; several things can be selected, aligned and grouped; a connector can join anything (node or shape) and has its own colour, arrowheads and routing; and every item has a right-click menu.

None of it changed the save model described in the basics page: the browser still sends the whole diagram and the server still deletes and re-inserts every row. What is new is that the things which must survive that (which page an item is on, which layer, which group, which shape a connector ends on) are carried as small stable keys chosen by the browser, never as row ids. That idea runs through both parts of this guide.

This part covers the tables, node styling, shapes, and pages and layers. Part 2 covers multi-select and grouping, connectors, the right-click menus, how saving and versions carry all of it, the traps and the tests.

Not covered here: icon libraries and My images (shape_type = 'icon') are in Network Mapper - Icon Libraries - Developer Guide; the article_id columns, the Articles panel and PNG / PDF export are in Network Mapper - Knowledge and Export - Developer Guide.

Files

Key: πŸ—„οΈ schema Β· πŸ“– read Β· ✏️ write Β· πŸ”Œ REST Β· πŸ–₯️ UI Β· πŸ§ͺ test

🎨 File What it does
πŸ—„οΈ database/freeitsm.sql Fresh-install DDL: the new columns on network_diagram_nodes and network_diagram_connectors, and the tables network_diagram_shapes, network_diagram_pages, network_diagram_layers, with a comment block on each
πŸ—„οΈ includes/db_verify_schema.php The $schema entries DB Verify builds columns from on a grown install
πŸ—„οΈ api/system/db_verify.php Network Mapper foreign keys, the orphan sweep that runs before them, and the one-off relaxing of from_node_id / to_node_id to NULL
πŸ—„οΈ includes/db_verify_indexes.php GENERATED by scripts/gen_db_verify_indexes.php - the uq_net_page and uq_net_layer unique keys and the shape indexes. Never edit by hand
πŸ“– api/network-mapper/get_diagram.php Returns nodes (with colour_override, w, h, style, page_key, layer_key, group_key), connectors (with the shape ends and style), shapes, pages and layers
✏️ api/network-mapper/save_diagram.php Thin adapter: maps the editor's payload onto NetworkMapperService::saveDiagram() and passes shapes, pages and layers straight through
✏️ includes/services/network_mapper.php NetworkMapperService - replaceContents(), replaceShapes(), replacePages(), sanitiseStyle(), sanitiseConnectorStyle(), keyOf(), groupOf(), and createVersion() copying all of it
✏️ api/network-mapper/create_version.php Calls NetworkMapperService::createVersion() - unchanged, but the service now copies shapes, pages and layers too
πŸ”Œ api/v1/resources/network_mapper.php The REST resource: GET returns all of it (node look and place, shape ends, shapes, pages, layers), so a read-then-write keeps it - see Part 2
πŸ–₯️ assets/js/network-mapper.js The editor (one IIFE, window.NM). Every section below lives here
πŸ–₯️ assets/js/network-mapper-shapes.js The shape library (window.NM_SHAPES) and the style renderers nmShapeStyle, nmShapeSvg, nmShapeTextBox, nmShapePreview, nmTextCss, nmNodeBoxCss
πŸ–₯️ network-mapper/diagram.php Markup and inline CSS: the palette tabs, the page tab bar, the Layers dropdown, the node panel's Colour / Icon size / Box size / Layer / Style rows, the Format panel (#shapeFormatPanel), and the .nm-shape*, .has-colour, .has-style, .nm-ctx-menu, .nm-band rules
πŸ–₯️ lang/en/network-mapper.php The strings, under detail, connector, shapes, menu, select, pages, layers and style (and the same keys in every other locale)
πŸ–₯️ includes/feature_bingo/cards/network-mapper.php The Feature Bingo cards for these features
πŸ§ͺ tests/network-mapper-node-style.php Node colour and box size
πŸ§ͺ tests/network-mapper-shapes.php Shapes and the style JSON
πŸ§ͺ tests/network-mapper-pages.php Pages, layers and group keys
πŸ§ͺ tests/network-mapper-connectors.php Connectors with shape ends and their style

The tables

What changed on the two old tables

network_diagram_nodes gained eight columns. From database/freeitsm.sql:

    -- GH #433: a node's own colour (#rrggbb; NULL = the normal look) and its box size in
    -- canvas pixels (NULL = automatic: as wide as the icon, label clamped to two lines).
    `colour_override` VARCHAR(20) NULL,
    `w`              INT NULL,
    `h`              INT NULL,
    -- Shapes: the node's own look as JSON (fill, gradient, border, shadow, opacity,
    -- rounded corners, font) - only the keys that differ from the normal look.
    -- NetworkMapperService::sanitiseStyle() whitelists every key. NULL = normal.
    `style`          TEXT NULL,
    -- Pages and layers: which page (network_diagram_pages.page_key) and which layer on it
    -- (network_diagram_layers.layer_key) the node is on. 0 / 0 = the first page and its
    -- first layer, which every diagram has even before it has any page rows.
    `page_key`       INT NOT NULL DEFAULT 0,
    `layer_key`      INT NOT NULL DEFAULT 0,
    -- A group: nodes and shapes on the same page with the same group_key move and select
    -- together (Group / Ungroup in the editor). NULL = not grouped.
    `group_key`      VARCHAR(40) NULL,

Every one of them is NULL or defaults to 0, so a row written before #433 means exactly what it meant before: the normal look, page 0, layer 0, no group. That is why nothing had to be migrated. (article_id arrived in the same series; see the Knowledge page.)

network_diagram_connectors changed shape more than it grew:

    -- GH #433: an end is a node (from_node_id / to_node_id) OR a shape (from_shape_uid /
    -- to_shape_uid - network_diagram_shapes.uid, stable across saves where row ids are not).
    `from_node_id`             INT NULL,
    `to_node_id`               INT NULL,
    `from_shape_uid`           VARCHAR(20) NULL,
    `to_shape_uid`             VARCHAR(20) NULL,
    `cmdb_relationship_id`     INT NULL,
    `label`                    VARCHAR(255) NULL,
    `line_style`               VARCHAR(20) NULL DEFAULT 'solid',
    -- The line's own look as JSON: colour, width, arrowStart, arrowEnd (none / arrow / open /
    -- diamond / circle), routing (straight / elbow / curved). NULL = the normal grey arrow.
    `style`                    TEXT NULL,

from_node_id and to_node_id used to be NOT NULL. A grown install has the old definition, and the $schema array in includes/db_verify_schema.php only adds missing columns, it never alters one. So api/system/db_verify.php carries a dedicated step:

    // GH #433: a connector end can now be a shape, so its node columns may be NULL. Relaxing a
    // NOT NULL cannot invalidate an existing row (every one has both nodes), and the foreign keys
    // still hold - a NULL has nothing to check.
    if ($tableExists('network_diagram_connectors')) {
        try {
            $cc = $conn->prepare("SELECT column_name, is_nullable FROM information_schema.columns
                                   WHERE table_schema = ? AND table_name = 'network_diagram_connectors' AND column_name IN ('from_node_id', 'to_node_id')");
            $cc->execute([$dbName]);
            foreach ($cc->fetchAll(PDO::FETCH_NUM) as [$col, $nullable]) {
                if (strtoupper($nullable) === 'NO') {
                    $conn->exec("ALTER TABLE `network_diagram_connectors` MODIFY `$col` INT NULL");

Until DB Verify has run, a save with a connector ending on a shape fails on the NOT NULL, and the whole save rolls back. That is the right failure: nothing is half-written.

network_diagram_shapes

CREATE TABLE IF NOT EXISTS `network_diagram_shapes` (
    `id`             INT NOT NULL AUTO_INCREMENT,
    `diagram_id`     INT NOT NULL,
    `shape_type`     VARCHAR(40) NOT NULL,
    `x`              INT NOT NULL DEFAULT 0,
    `y`              INT NOT NULL DEFAULT 0,
    `w`              INT NOT NULL DEFAULT 120,
    `h`              INT NOT NULL DEFAULT 80,
    `rotation`       INT NOT NULL DEFAULT 0,
    `text`           TEXT NULL,
    `style`          TEXT NULL,
    `layer`          VARCHAR(10) NOT NULL DEFAULT 'back',
    `z`              INT NOT NULL DEFAULT 0,
    -- An icon from an imported icon library (shape_type 'icon'); NULL for drawn shapes, and
    -- for an icon whose library was removed (the shape keeps its place, loses the picture).
    `icon_id`        INT NULL,
    `page_key`       INT NOT NULL DEFAULT 0,   -- as network_diagram_nodes.page_key
    `layer_key`      INT NOT NULL DEFAULT 0,
    `group_key`      VARCHAR(40) NULL,         -- as network_diagram_nodes.group_key
    -- A stable id for connectors to point at (letters, digits, _ and -). Row ids change on
    -- every save because shapes are replaced; this does not.
    `uid`            VARCHAR(20) NULL,

Three columns sound alike and are not:

Column Means Values
layer Behind or in front of the CMDB nodes and the connector lines back / front
layer_key Which user layer of the page (the Layers panel) a small number, network_diagram_layers.layer_key
z Order among shapes any integer, larger is on top

shape_type is a free VARCHAR(40), not an ENUM and not a foreign key. The comment above the table says why: an unknown key draws as a rectangle, so the library can grow without a schema change, and a diagram saved by a newer version still opens in an older one.

network_diagram_pages and network_diagram_layers

-- Pages and layers: a diagram has tabs (pages); each page has layers that can be hidden or
-- locked. Items carry page_key / layer_key - small numbers stable across saves and versions
-- (rows are replaced on every save, ids are not stable). A diagram with no rows here is one
-- page with one layer, key 0 / 0. sort orders tabs left to right and layers bottom to top.
CREATE TABLE IF NOT EXISTS `network_diagram_pages` (
    `id`          INT NOT NULL AUTO_INCREMENT,
    `diagram_id`  INT NOT NULL,
    `page_key`    INT NOT NULL DEFAULT 0,
    `name`        VARCHAR(100) NOT NULL,
    `sort`        INT NOT NULL DEFAULT 0,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uq_net_page` (`diagram_id`, `page_key`),
    CONSTRAINT `fk_net_page_diag` FOREIGN KEY (`diagram_id`) REFERENCES `network_diagrams` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `network_diagram_layers` (
    `id`          INT NOT NULL AUTO_INCREMENT,
    `diagram_id`  INT NOT NULL,
    `page_key`    INT NOT NULL DEFAULT 0,
    `layer_key`   INT NOT NULL DEFAULT 0,
    `name`        VARCHAR(100) NOT NULL,
    `sort`        INT NOT NULL DEFAULT 0,
    `visible`     TINYINT(1) NOT NULL DEFAULT 1,
    `locked`      TINYINT(1) NOT NULL DEFAULT 0,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uq_net_layer` (`diagram_id`, `page_key`, `layer_key`),

Layers are their own table, keyed by (diagram_id, page_key, layer_key), not a JSON column on the page. A layer belongs to a page through page_key, never through network_diagram_pages.id - that id is replaced on every save, so a foreign key to it would break each time. Nothing joins items to these tables in SQL: an item's page_key / layer_key are matched in the browser.

Why the keys and not the ids: every save deletes and re-inserts pages, layers, nodes and shapes, so every id is new after a save. A key is a small number the browser picks (nextPageKey(), addLayer()) and sends back unchanged, so a node saved with page_key = 1, layer_key = 3 still points at the same tab and the same layer after any number of saves and version copies.

visible and locked are saved per layer. Hiding a layer is therefore part of the diagram, not a viewer preference - see "Read-only versions" below for the one exception.

1. Node styling

Colour, box size and icon size

size (small / medium / large) is the old column and now only sets the icon size. The box around the icon is new: w / h NULL means the old automatic box. The editor's model of a node's outer box is nodeExtent():

    /** True when the node has its own box size (w/h set), rather than the automatic one. */
    function hasBoxSize(n) { return !!(n && (n.w || n.h)); }

    /**
     * A node's outer box in canvas px: its own size, or the automatic one (icon plus padding, with the
     * label hanging about 40px below). Used to frame fit, centre and export.
     */
    function nodeExtent(n) {
        const sz = NODE_SIZES[n.size] || NODE_SIZES.medium;
        return { w: n.w || (sz + NODE_PADDING * 2), h: n.h || (sz + NODE_PADDING * 2 + 40) };
    }

Fit, Centre, export, rubber-band hit tests, align and distribute all use nodeExtent(). If you add something that needs a node's size, use it too; the icon size alone is wrong for any node with its own box.

buildNodeEl() applies the three looks as classes plus inline values:

        if (hasBoxSize(n)) {
            // GH #433: its own box - the label gets the full width and is no longer cut to two lines.
            el.classList.add('has-size');
            el.style.boxSizing = 'border-box';
            el.style.width = nodeExtent(n).w + 'px';
            if (n.h) el.style.minHeight = n.h + 'px';
        }
        if (n.colour_override) {
            // GH #433: custom properties, not inline border/background, so the selected ring still wins.
            el.classList.add('has-colour');
            el.style.setProperty('--nmc', n.colour_override);
            el.style.setProperty('--nmc-bg', hexToRgba(n.colour_override, 0.12));
        }
        if (n.style && window.nmNodeBoxCss) {
            // GH #433: the node's own fill, border, shadow, corners and opacity (font goes on the label below)
            el.classList.add('has-style');
            el.style.cssText += window.nmNodeBoxCss(n.style);
        }

The colour goes through custom properties, and that is deliberate. An inline border-color would beat the stylesheet's .nm-node.selected cyan ring, so a selected coloured node would show no selection. With custom properties the stylesheet in network-mapper/diagram.php decides:

        .nm-node.has-colour { border-color: var(--nmc); background: var(--nmc-bg); }
        .nm-node.has-colour:hover { border-color: var(--nmc); }
        .nm-node.has-colour .nm-node-icon { color: var(--nmc); }
        .nm-node.has-colour.selected { border-color: #06b6d4; }
        .nm-node.has-size { justify-content: center; }   /* icon + name centred as one group in a taller box */

.nm-node-icon { color: var(--nmc) } works because the CMDB icons are drawn with currentColor, so one property recolours the picture.

The side panel's eight swatches are NODE_COLOURS, plus an <input type="color"> for anything else; setNodeColour() lower-cases the value. The server is strict about the format and refuses rather than cleans:

        // GH #433: a node's own colour and box size - all optional, NULL = the normal look.
        $colour = null;
        if (isset($n['colour_override']) && trim((string)$n['colour_override']) !== '') {
            $colour = strtolower(trim((string)$n['colour_override']));
            if (!preg_match('/^#[0-9a-f]{6}$/', $colour)) {
                throw new ServiceError('validation', 'invalid_field', "nodes[{$index}]: 'colour_override' must be a colour like #2563eb.");
            }
        }
        $dim = function (string $k) use ($n, $index): ?int {
            if (!isset($n[$k]) || $n[$k] === '') return null;
            $v = (int)$n[$k];
            if ($v < 20 || $v > 2000) {
                throw new ServiceError('validation', 'invalid_field', "nodes[{$index}]: '{$k}' must be between 20 and 2000.");
            }
            return $v;
        };

Compare that with the style JSON below, which is cleaned, never refused. The colour and box size are typed columns with one right shape, so a wrong value is a bug worth surfacing. The style is a bag of optional keys that will grow, so an unknown key from a newer editor must not block a save.

Resizing a node

The bottom-right .nm-resize-handle only exists on the current version (it is part of the same handleHtml as the four edge handles) and only shows on a selected node. startNodeResize() records the starting size and a minimum that still fits the icon:

        nodeResize = {
            key: nodeKey(n),
            start: canvasModelCoords(e),
            w: el.offsetWidth,
            h: el.offsetHeight,
            minW: sz + NODE_PADDING * 2,
            minH: sz + NODE_PADDING * 2 + 20,
            moved: false
        };

and onNodeResizeMove() snaps to the 20px node grid and clamps at the server's 2000:

        const w = Math.min(2000, Math.max(nodeResize.minW, snap(nodeResize.w + c.x - nodeResize.start.x)));
        const h = Math.min(2000, Math.max(nodeResize.minH, snap(nodeResize.h + c.y - nodeResize.start.y)));

Changing the icon size can make an own box too small for the new icon, so setNodeIconSize() grows it:

        // An own box must still fit the bigger icon.
        const ext = NODE_SIZES[size] + NODE_PADDING * 2;
        if (n.w && n.w < ext) n.w = snap(ext + GRID / 2);
        if (n.h && n.h < ext + 20) n.h = snap(ext + 20 + GRID / 2);

Where the icon is inside a resized node (commit d9ea6e20a)

In an automatic box the icon sits at NODE_PADDING from the top-left. In an own box it is centred: horizontally by arithmetic (iconOffsetX()), vertically by CSS (.has-size { justify-content: center }), which centres icon and wrapped label together. That vertical position depends on how many lines the label wraps to, which only the browser knows. So syncIconY() reads it back from the drawn element:

    function syncIconY(el, n) {
        const icon = el ? el.querySelector('.nm-node-icon') : null;
        const sz = NODE_SIZES[n.size] || NODE_SIZES.medium;
        const iy = (n.h && icon) ? icon.offsetTop : NODE_PADDING;
        n._iconY = iy;
        if (!el || iy === NODE_PADDING) return;
        el.querySelectorAll('.nm-edge-handle').forEach(h => {
            const side = h.dataset.side;
            h.style.top = (side === 'top' ? iy : side === 'bottom' ? iy + sz : iy + sz / 2) + 'px';
        });
    }

n._iconY is a cache on the node object, never saved (the save payload lists its fields explicitly). nodeIconBBox() uses it, so connector ends and connection dots land on the icon:

        const ix = iconOffsetX(n);   // GH #433: centred when the box has its own width
        const iy = (n._iconY != null) ? n._iconY : pad;   // ...and its own height (syncIconY)

syncIconY() must run after the element is in the page (offsetTop is 0 on a detached element). renderNodes() and rerenderNode() both append first and call it second; keep that order in any new render path.

The node Style section

The same style editor that formats shapes also formats a node's box and label. NODE_STYLE_SHOWN is what an unstyled node looks like, so the controls start from the truth instead of the shape defaults:

    const NODE_STYLE_SHOWN = { fill: 'solid', fillColour: '#ffffff', stroke: 'none', strokeColour: '#64748b', strokeWidth: 1.5,
        opacity: 100, shadow: false, rounded: 8, font: 'sans', fontSize: 12, fontColour: '#1f2937', bold: false, italic: false, underline: false, align: 'center' };

    function renderNodeStyleEditor(n) {
        const box = document.getElementById('ndStyle');
        if (!box) return;
        renderStyleEditor(box, Object.assign({}, NODE_STYLE_SHOWN, n.style || {}), {
            rounded: true, valign: false, editable: canEdit(),
            onChange: patch => {
                if (!canEdit()) return;
                n.style = Object.assign({}, n.style || {}, patch);

Note the difference from shapes: a node stores only the keys that were changed (Object.assign({}, n.style || {}, patch)), while a shape stores its full look (see "Adding a shape"). An unstyled node keeps style = NULL and the normal stylesheet look, including dark mode. nmNodeBoxCss() in assets/js/network-mapper-shapes.js turns the keys into CSS, again through custom properties for the border so the selected ring wins:

        if (st.stroke === 'none') css += '--nms-bw:0px;';
        else if (st.stroke) {
            css += '--nms-bs:' + st.stroke + ';';
            if (st.strokeWidth != null) css += '--nms-bw:' + (+st.strokeWidth) + 'px;';
            if (hex(st.strokeColour)) css += '--nms-bc:' + st.strokeColour + ';';
        }
        if (st.rounded != null) css += 'border-radius:' + (+st.rounded) + 'px;';
        if (st.shadow) css += '--nms-shadow:0 3px 9px rgba(0,0,0,0.28);';
        .nm-node.has-style {
            border-width: var(--nms-bw, 1.5px);
            border-style: var(--nms-bs, solid);
            border-color: var(--nms-bc, var(--nmc, transparent));
            box-shadow: var(--nms-shadow, none);
        }

var(--nms-bc, var(--nmc, transparent)) is how the two features combine: a styled border colour wins, otherwise the node's own colour, otherwise none. The font keys go on the label through nmTextCss(), not on the box.

2. Shapes

The library

assets/js/network-mapper-shapes.js holds every shape as a definition, registered with add(key, def):

    // w/h: the size a shape is dropped at. text(w,h): where its text sits (default: the whole
    // shape, inset). rounded: the Rounded corners control applies. style: defaults that differ
    // from SHAPE_STYLE below.
    const S = {};
    const add = (key, def) => { S[key] = def; };

    // Basic
    add('rectangle',         { cat: 'basic', w: 120, h: 70, rounded: true, draw: (w, h, r) => ({ d: rrect(0, 0, w, h, r) }) });
    add('rounded_rectangle', { cat: 'basic', w: 120, h: 70, rounded: true, style: { rounded: 12 }, draw: (w, h, r) => ({ d: rrect(0, 0, w, h, r) }) });
    add('ellipse',           { cat: 'basic', w: 120, h: 80, draw: (w, h) => ({ d: ellipse(0, 0, w, h) }), text: (w, h) => box(w * 0.15, h * 0.15, w * 0.7, h * 0.7) });

There are 62 add() calls: 61 drawn shapes in the palette's five groups (basic 18, flow 24, arrows 8, containers 4, text 7) and the special icon in the library group, which is not in NM_SHAPE_CATS and so never shows as a drawn tile:

    window.NM_SHAPES = S;
    window.NM_SHAPE_CATS = ['basic', 'flow', 'arrows', 'containers', 'text'];

Each definition's draw(w, h, r) returns SVG path data for the shape at its real size, not a 100 x 100 picture stretched with a viewBox. The file header gives the reason: stretched, a circle's border would get thicker on the long side and a rounded corner would turn oval. draw() may return three paths:

Key Drawn as Used for
d the filled outline, with the shadow filter every shape
tail a second filled path supported by nmShapeSvg(), but no shape in the library returns one today
lines unfilled strokes inner detail: the cylinder's top rim, the swimlane header line, the note's folded corner

text(w, h) returns the box the text sits in, in the shape's own pixels. A diamond's text sits in its middle 60%; or, summing_junction, collate, sort, line_h and line_v return a zero box, which means "no text". The organic shapes (cloud, heart, document waves) are written once in a 100-wide box and scaled with scaled():

    function scaled(tpl, w, h, bh) {
        const sx = w / 100, sy = h / (bh || 100);
        let i = 0;
        return tpl.replace(/-?\d+(\.\d+)?/g, m => f(parseFloat(m) * (i++ % 2 === 0 ? sx : sy)));
    }

That only works because the templates use absolute commands with numbers in x,y pairs. An arc (A) has seven numbers and would be scaled wrongly, which is why the arcs in the library (rrect, ellipse, cylinder, delay, display, stored_data) are built from w and h directly.

To add a shape: one add() line in a category, plus a name_<key> string under shapes in lang/en/network-mapper.php (without it shapeName() falls back to the key with spaces). No schema change, no server change - the server only checks the key's format.

Style: three layers of defaults

    const SHAPE_STYLE = {
        fill: 'solid', fillColour: '#ffffff', fillColour2: '#dbeafe', gradientDir: 'down',
        stroke: 'solid', strokeColour: '#64748b', strokeWidth: 1.5,
        opacity: 100, shadow: false, rounded: 0,
        font: 'sans', fontSize: 13, fontColour: '#1f2937', bold: false, italic: false, underline: false,
        align: 'center', valign: 'middle'
    };
    /** The full style for a shape: library defaults, then the shape type's, then its own. */
    window.nmShapeStyle = function (type, style) {
        const def = S[type] || S.rectangle;
        return Object.assign({}, SHAPE_STYLE, def.style || {}, style || {});
    };

So a zone is light blue with a dashed blue border because its definition says so, and any key the shape has of its own wins over both.

Drawing one shape

nmShapeSvg() builds one <svg> per shape. Every value that reaches the markup is either the library's own string or a colour that passed the hex test, which is why it can be built as a string:

    window.nmShapeSvg = function (shape, idPrefix) {
        const def = S[shape.shape_type] || S.rectangle;
        const st = window.nmShapeStyle(shape.shape_type, shape.style);
        const w = Math.max(1, shape.w), h = Math.max(1, shape.h);
        const g = def.draw(w, h, def.rounded ? (+st.rounded || 0) : 0);
        let defs = '';
        let fill = 'none';
        if (st.fill === 'solid') fill = hex(st.fillColour) || '#ffffff';
        if (st.fill === 'gradient') {
            const c1 = hex(st.fillColour) || '#ffffff', c2 = hex(st.fillColour2) || '#dbeafe';
            const gid = idPrefix + '-g';

S[shape.shape_type] || S.rectangle is the "unknown key draws as a rectangle" rule. idPrefix matters: gradients and the shadow filter are referenced by id, and ids are page-global, so two shapes with gradients need different ids. The editor passes 'nms-' + shapeKey(s), the palette passes 'nmpv-' + type.

In the editor, buildShapeEl() wraps the SVG in an absolutely positioned <div class="nm-shape"> with the text, the resize handles and the connection dots:

        el.style.left = s.x + 'px';
        el.style.top = s.y + 'px';
        el.style.width = s.w + 'px';
        el.style.height = s.h + 'px';
        if (s.rotation) el.style.transform = 'rotate(' + s.rotation + 'deg)';
        if (st.opacity != null && +st.opacity < 100) el.style.opacity = String(+st.opacity / 100);
        const tb = window.nmShapeTextBox ? window.nmShapeTextBox(s) : { x: 0, y: 0, w: s.w, h: s.h };
        const editing = key === shapeEditKey;
        if ((s.text || editing) && tb.w > 0 && tb.h > 0) {
            const jc = st.valign === 'top' ? 'flex-start' : st.valign === 'bottom' ? 'flex-end' : 'center';
            html += '<div class="nm-shape-text" style="left:' + tb.x + 'px;top:' + tb.y + 'px;width:' + tb.w + 'px;height:' + tb.h + 'px;justify-content:' + jc + ';">'
                + '<div class="nm-shape-text-inner" style="' + escapeAttr(window.nmTextCss ? window.nmTextCss(st) : '') + '"'
                + (editing ? ' contenteditable="true" spellcheck="true"' : '') + '>' + escapeHtml(s.text || '') + '</div></div>';
        }
        if (key === selectedShapeKey && canEdit() && !editing) {
            ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'].forEach(d => { html += '<div class="nm-shape-handle" data-dir="' + d + '"></div>'; });
        }

The text is an HTML <div> over the SVG, not an SVG <text>. HTML wraps, SVG text does not; white-space: pre-wrap keeps the analyst's own line breaks. The text is escaped with escapeHtml(); it is the only free text in a shape.

Rotation

Rotation is a number in the Format panel (spR, step 5, -360 to 360) and nothing else - there is no rotate handle. It is a CSS transform on the shape's <div> with transform-origin: 50% 50%, so the SVG, text and handles all turn together. The model never rotates: x, y, w, h stay the unrotated box. See Traps in Part 2 for what that means for connectors and hit tests.

Resizing a shape

Eight handles, nw to w. onShapeResizeMove() reads the direction letters, so one function serves all eight:

        const r = shapeResize, c = canvasModelCoords(e);
        const dx = c.x - r.start.x, dy = c.y - r.start.y, MIN = 10;
        let x = r.x, y = r.y, w = r.w, h = r.h;
        if (r.dir.indexOf('e') >= 0) w = Math.max(MIN, snapS(r.w + dx));
        if (r.dir.indexOf('s') >= 0) h = Math.max(MIN, snapS(r.h + dy));
        if (r.dir.indexOf('w') >= 0) { const nx = Math.min(snapS(r.x + dx), r.x + r.w - MIN); w = r.w + (r.x - nx); x = nx; }
        if (r.dir.indexOf('n') >= 0) { const ny = Math.min(snapS(r.y + dy), r.y + r.h - MIN); h = r.h + (r.y - ny); y = ny; }

A west or north drag moves the left / top edge, so x / y change and the opposite edge stays put; the Math.min(..., r.x + r.w - MIN) stops the edge crossing over. Shapes snap to a 10px grid (SHAPE_GRID), finer than the nodes' 20px GRID, because shapes are used for fine layout (labels, lines) where 20px is too coarse.

Typing into a shape

Double-click calls startShapeTextEdit(), which sets shapeEditKey and re-renders the shape with contenteditable="true". Three guards keep typing from turning into editor commands:

  • the editable <div> stops mousedown propagation, so clicking inside it does not start a drag;
  • its own keydown handler stops propagation, so Delete deletes a character and not the shape;
  • the document keydown in bindCanvasEvents() also bails out first:
            // GH #433: typing in a shape - its own keys, never a delete of the shape
            if (document.activeElement && document.activeElement.isContentEditable) return;

Blur commits through commitShapeTextEdit(), which reads innerText (so the browser's own line breaks become \n) and only marks the diagram dirty when the text changed. Escape re-renders without committing. Autosave waits while shapeEditKey is set, because the reload after a save would rebuild the element under the cursor.

Adding a shape

From the palette, a click adds it in the middle of the view (addShapeInView()), a drag drops it where it lands (onCanvasDrop() sees kind: 'nm-shape'). Both end in addShapeAt():

        const maxZ = shapes.reduce((m, s) => Math.max(m, s.z || 0), 0);
        const s = {
            id: null, tempId: nextTempShapeId--, shape_type: type, icon_id: iconId,
            x: Math.max(0, snapS(cx - w / 2)), y: Math.max(0, snapS(cy - h / 2)),
            w: w, h: h, rotation: 0, text: defaultShapeText(type),
            style: window.nmShapeStyle(type, {}),   // the full look, so later library changes never move it
            layer: 'back', z: maxZ + 1, uid: newUid()
        };
        placeOnPage(s);   // GH #433

Three things here matter later:

  • style: window.nmShapeStyle(type, {}) stores the full resolved look, not just the differences. If a later release changes the zone default colour, existing zones keep the colour they were drawn with.
  • uid: newUid() gives the shape its connector key at birth (Part 2).
  • placeOnPage(s) stamps the current page and the active layer (below).

shapeKey() is 's' + id for a saved shape and 't' + tempId for a new one, the same pattern as nodeKey(). Temp ids count down from -1 in their own counter, nextTempShapeId.

The Format panel

A selected shape opens #shapeFormatPanel (same frame as the node detail panel) through renderShapePanel(): X / Y / W / H / rotation, the Layer select, the Knowledge field, Behind / In front, To front / To back, Duplicate, Delete, then the shared style editor:

        renderStyleEditor(document.getElementById('spStyle'), window.nmShapeStyle(s.shape_type, s.style), {
            rounded: !!def.rounded, valign: true, editable: ed,
            onChange: patch => { patchShapeStyle(patch); },
            onRebuild: () => renderShapePanel(),
            onReset: () => { s.style = window.nmShapeStyle(s.shape_type, {}); rerenderShape(s); markDirty(); renderShapePanel(); }
        });

renderStyleEditor(box, st, opts) is one function used by three callers - the shape panel, the node Style section and the multi-selection panel (Part 2). It knows nothing about shapes or nodes; it shows st and reports changes through opts.onChange(patch). opts.onRebuild() exists because some choices show or hide controls (choosing Gradient adds the second colour and the direction), so the editor redraws itself, but a colour picker or a number field must keep focus while it is being used, so those call onChange without a rebuild. The ten quick-style buttons are STYLE_PRESETS; a preset is applied with shadow: false first so a preset without a shadow clears one.

The panel's X / Y / W / H inputs are kept in step during a drag by syncShapePanelGeometry(), which skips the field that has focus so typing is never overwritten.

Z-order: behind, in front, to front, to back

Two independent controls:

    /** To front / to back within the shape's layer, or move it to the other layer. */
    function arrangeShape(how) {
        const s = findShapeByKey(selectedShapeKey);
        if (!s || !canEdit()) return;
        if (how === 'front') s.z = shapes.reduce((m, x) => Math.max(m, x.z || 0), 0) + 1;
        else if (how === 'back') s.z = shapes.reduce((m, x) => Math.min(m, x.z || 0), 0) - 1;
        else if (how === 'layer_front') s.layer = 'front';
        else if (how === 'layer_back') s.layer = 'back';

layer decides the side of the CMDB nodes, by CSS z-index in network-mapper/diagram.php. The connector SVG is z-index: 1 ("under nodes (z:2) and selected nodes (z:3)"), and:

        .nm-shape { position: absolute; z-index: 0; cursor: move; transform-origin: 50% 50%; user-select: none; }
        .nm-shape.is-front { z-index: 6; }

So a Behind shape is under the lines and the nodes (a zone you draw nodes inside), and an In front shape is over both (a callout over a node). z orders shapes among themselves; renderShapes() sorts by user layer first, then z, and inserts every shape before the first node so DOM order agrees:

    function renderShapes() {
        if (!elCanvasInner) return;
        elCanvasInner.querySelectorAll('.nm-shape').forEach(el => el.remove());
        shapes.sort((a, b) => (a.z || 0) - (b.z || 0));
        const first = elCanvasInner.querySelector('.nm-node');
        // GH #433: this page's visible layers, a higher layer's shapes over a lower one's
        visibleShapes().sort((a, b) => (layerRank(a) - layerRank(b)) || ((a.z || 0) - (b.z || 0)))
            .forEach(s => elCanvasInner.insertBefore(buildShapeEl(s), first || null));

shapes.sort() sorts the model array in place, not a copy. That is load-bearing: the save sends shapes in array order, the server returns ORDER BY z, id, and save() re-finds the selected shape after the reload by its index in that array (Part 2). Do not replace that line with a sorted copy.

z can go negative (To back takes min - 1); the server clamps it to -100000 .. 100000.

What the server keeps

replaceShapes() deletes the diagram's shapes and inserts the list it was sent. Bad values are clamped, bad keys refused:

        $int = function ($v, int $min, int $max, int $default) {
            if ($v === null || $v === '' || !is_numeric($v)) return $default;
            return max($min, min($max, (int)round((float)$v)));
        };
        if (count($shapesIn) > 2000) {
            throw new ServiceError('validation', 'invalid_field', 'A diagram can have at most 2000 shapes.');
        }
        foreach (array_values($shapesIn) as $i => $s) {
            if (!is_array($s)) {
                throw new ServiceError('validation', 'invalid_field', "shapes[{$i}] must be an object.");
            }
            $type = strtolower(trim((string)($s['shape_type'] ?? '')));
            if (!preg_match('/^[a-z0-9_]{1,40}$/', $type)) {
                throw new ServiceError('validation', 'invalid_field', "shapes[{$i}]: 'shape_type' is missing or not a shape key.");
            }
            $text = isset($s['text']) ? (string)$s['text'] : '';
            $text = mb_substr(str_replace("\r\n", "\n", $text), 0, 4000);
            $layer = (($s['layer'] ?? 'back') === 'front') ? 'front' : 'back';

The shape_type check is a format check only. The server does not know the library (it lives in JavaScript), and does not need to: an unknown key draws as a rectangle.

sanitiseStyle() is the one gate for every style JSON on a node or a shape. It keeps known keys with sane values and drops the rest silently:

        $enums = [
            'fill'        => ['none', 'solid', 'gradient'],
            'gradientDir' => ['down', 'right', 'diag', 'radial'],
            'stroke'      => ['none', 'solid', 'dashed', 'dotted'],
            'font'        => ['sans', 'serif', 'mono', 'arial', 'verdana', 'tahoma', 'trebuchet', 'georgia', 'times', 'courier', 'comic'],
            'align'       => ['left', 'center', 'right'],
            'valign'      => ['top', 'middle', 'bottom'],
        ];
        $colours = ['fillColour', 'fillColour2', 'strokeColour', 'fontColour'];
        $numbers = ['strokeWidth' => [0, 20], 'opacity' => [0, 100], 'rounded' => [0, 500], 'fontSize' => [6, 96]];
        $bools = ['shadow', 'bold', 'italic', 'underline'];

The whitelist is also the security boundary. nmShapeSvg() and nmNodeBoxCss() write style values into markup and CSS; because the server only ever stores enum values, #rrggbb colours, numbers and real booleans, a hand-crafted save cannot inject markup through a style. If you add a style key, add it here and in the JavaScript renderers, and keep its value type this narrow. The font names are keys into FONTS in assets/js/network-mapper-shapes.js, never font-family strings.

replaceShapes() only runs when the caller sends shapes:

            // 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);
            }

An absent key keeps the shapes; an empty array clears them. tests/network-mapper-shapes.php proves both.

Reading shapes on an older install

api/network-mapper/get_diagram.php reads shapes inside two nested try blocks:

    // GH #433: freestanding shapes. An install that has not run DB Verify since the
    // table arrived simply has none - the diagram still opens.
    $shapes = [];
    try {
        try {
            $sstmt = $conn->prepare(
                "SELECT id, 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 z, id"
            );
            $sstmt->execute([$id]);
        } catch (PDOException $e) {
            // icon_id arrived after the shapes table - an install between the two still opens.
            $sstmt = $conn->prepare(
                "SELECT id, shape_type, x, y, w, h, rotation, text, style, layer, z, NULL AS icon_id, 0 AS page_key, 0 AS layer_key, NULL AS group_key, NULL AS uid, NULL AS article_id

The outer try covers "no table at all", the inner one "table but missing later columns". The pages and layers read has the same outer guard. The point is that upgrading the code before running DB Verify must never stop a diagram from opening.

3. Pages and layers

The model in the browser

    let pages = [];              // [{page_key, name, sort}]
    let layers = [];             // [{page_key, layer_key, name, sort, visible, locked}]
    let currentPage = 0;
    const activeLayers = {};     // page_key -> the layer new items go on

nodes and shapes stay flat arrays for the whole diagram; each item carries its own page_key / layer_key. A page is never a container in memory. Everything that asks "which items do I draw" goes through a handful of helpers:

    function itemPage(it) { return (it && it.page_key) || 0; }
    function itemLayer(it) { return (it && it.layer_key) || 0; }
    function pageLayers(pk) {
        return layers.filter(l => l.page_key === pk).sort((a, b) => (a.sort - b.sort) || (a.layer_key - b.layer_key));
    }
    function findLayer(pk, lk) { return layers.find(l => l.page_key === pk && l.layer_key === lk) || null; }
    function layerOfItem(it) { return findLayer(itemPage(it), itemLayer(it)); }
    /** On the current page and on a visible layer. */
    function itemVisible(it) {
        if (itemPage(it) !== currentPage) return false;
        const l = layerOfItem(it);
        return !l || l.visible !== false;
    }
    function itemLocked(it) { const l = layerOfItem(it); return !!(l && l.locked); }
    function visibleNodes() { return nodes.filter(itemVisible); }
    function visibleShapes() { return shapes.filter(itemVisible); }
    function pageNodes() { return nodes.filter(n => itemPage(n) === currentPage); }

visibleNodes() (this page, visible layers) and pageNodes() (this page, any layer) are different questions. Rendering, Fit, export, rubber band and Select all use visibleNodes(). The "is this CMDB object already here?" checks use pageNodes(), because a node on a hidden layer is still on the page.

renderNodes() and renderShapes() only build elements for visible items, and renderConnectors() skips a line whose either end is not visible:

            if (!from || !to) return; // an end was deleted but the connector lingered - skip silently
            if (!itemVisible(from.it) || !itemVisible(to.it)) return;   // another page, or a hidden layer

So switching page is just changing currentPage and re-rendering:

    function switchPage(pk) {
        if (pk === currentPage || !pages.some(p => p.page_key === pk)) return;
        clearSelection();
        currentPage = pk;
        renderNodes();
        renderShapes();
        renderPageTabs();
        renderLayersPanel();
    }

Present and export show the current page only

Because the DOM only holds the current page's visible items, Present and PNG / PDF export get "this page minus hidden layers" for free; html2canvas photographs what is there. The size of the export area is computed from the same helpers in computeExportRect():

        if (!visibleNodes().length && !visibleShapes().length) return null;

zoomFit() and centreOnPage() use them too. The page tab bar is hidden in Present by CSS (.nm-editor.is-presenting .nm-page-tabs { display: none; }), and Page Up / Page Down still switch pages there, which is how a multi-page diagram is presented. (Export itself is covered in Network Mapper - Knowledge and Export - Developer Guide.)

The first page and repairing what arrives

A diagram saved before #433, or one written through the REST API, has no page or layer rows. ensurePagesLayers() runs after every load and every save reload and makes the model whole:

    function ensurePagesLayers() {
        if (!pages.length) pages = [{ page_key: 0, name: t('network-mapper.pages.default_name', { n: 1 }), sort: 0 }];
        // Items on a page that has no row (an API caller, an older save) still get a tab.
        nodes.concat(shapes).forEach(it => {
            if (!pages.some(p => p.page_key === itemPage(it))) {
                pages.push({ page_key: itemPage(it), name: t('network-mapper.pages.default_name', { n: pages.length + 1 }), sort: pages.length });
            }
        });
        pages.sort((a, b) => (a.sort - b.sort) || (a.page_key - b.page_key));
        pages.forEach(p => {
            if (!pageLayers(p.page_key).length) {
                layers.push({ page_key: p.page_key, layer_key: 0, name: t('network-mapper.layers.default_name', { n: 1 }), sort: 0, visible: true, locked: false });
            }
        });
        // GH #433: every shape has a uid for connectors; a connector whose end is gone is dropped.
        shapes.forEach(ensureShapeUid);
        connectors = connectors.filter(c => endOf(c, 'from') && endOf(c, 'to'));
        // An item on a layer that is gone goes on the page's bottom layer.
        nodes.concat(shapes).forEach(it => {
            if (!layerOfItem(it)) it.layer_key = pageLayers(itemPage(it))[0].layer_key;
        });
        if (!pages.some(p => p.page_key === currentPage)) currentPage = pages[0].page_key;
    }

The rule throughout: never lose an item because its page or layer row is missing. An orphan page key gets a tab; an orphan layer key moves the item to the bottom layer. The default names are made in the analyst's language and only become rows on the next save. Note also the two lines in the middle: this is where connectors with a vanished end are dropped and old shapes get a uid (Part 2).

The tab bar and the page menu

renderPageTabs() draws one button per page plus + on the current version. Click switches, double-click renames inline (renamePageInline()), right-click opens openPageMenu() with Rename, Duplicate, Move left, Move right and Delete. Page Up / Page Down are in the document keydown, checked before the "typing in a shape" guard so they work everywhere except form fields:

            if ((e.key === 'PageDown' || e.key === 'PageUp') && pages.length > 1) {   // GH #433: next / previous page
                const i = pages.findIndex(p => p.page_key === currentPage) + (e.key === 'PageDown' ? 1 : -1);
                if (i >= 0 && i < pages.length) { e.preventDefault(); switchPage(pages[i].page_key); }
                return;
            }

A new page key is always one more than the largest in use, never the count, so deleting page 1 of 0, 1, 2 and adding a page gives 3, not a second 2:

    function nextPageKey() { return pages.reduce((m, p) => Math.max(m, p.page_key), -1) + 1; }

movePage() swaps two entries and renumbers sort 0..n; page_key never changes, so items do not move with it. deletePage() removes the page's nodes, shapes and layers, and every connector touching any of them:

        const gone = new Set(nodes.filter(n => itemPage(n) === pk).map(n => nodeRef(n)));
        connectors = connectors.filter(c => !gone.has(c.from_node_id) && !gone.has(c.to_node_id)
            && !shapes.some(sh => itemPage(sh) === pk && touchesShape(c, sh)));

It asks for confirmation only when the page has something on it.

Per-page CMDB objects

Before #433 a CMDB object could be on a diagram once. Now the rule is once per page: the same switch can be on an Overview page and on a Rack page. Every place that hides or skips "already there" was narrowed from nodes to pageNodes():

        const onCanvas = new Set(pageNodes().map(n => n.cmdb_object_id));   // GH #433: on this page

That line is in renderPickerResults(), onPickerKeyDown() and renderRelatedRows(); commitRelatedSelections() builds its existingByCmdb map from pageNodes() the same way, and paste applies the rule too (Part 2). The server does not enforce it at all - replaceContents() accepts the same CI twice anywhere. The rule is an editor convenience, not an invariant, so code reading diagrams must not assume one node per CI per diagram. One consequence: save() re-selects a node after the reload by cmdb_object_id within the current page, because the same object may now be on several pages.

duplicatePage() copies every node on the page, which is fine because the copies land on a new page:

        const refMap = new Map();
        nodes.filter(n => itemPage(n) === pk).forEach(n => {
            const copy = Object.assign({}, n, { id: null, tempId: nextTempId--, page_key: nk,
                style: n.style ? JSON.parse(JSON.stringify(n.style)) : null });
            refMap.set(nodeRef(n), copy.tempId);
            nodes.push(copy);
        });
        const uidMap = new Map();
        shapes.filter(s => itemPage(s) === pk).forEach(s => {
            const copy = Object.assign({}, s, { id: null, tempId: nextTempShapeId--, page_key: nk, uid: newUid(),
                style: s.style ? JSON.parse(JSON.stringify(s.style)) : null });
            if (s.uid) uidMap.set(s.uid, copy.uid);
            shapes.push(copy);
        });
        remapConnectors(connectors.slice(), refMap, uidMap);

Object.assign is a shallow copy, so style is deep-copied by hand; without that, restyling a copy would restyle the original. refMap and uidMap translate "old end" to "new end" so remapConnectors() (Part 2) can copy only the connectors whose both ends were copied. connectors.slice() matters: remapConnectors() pushes onto connectors while it iterates the list it was given.

Layers

The Layers toolbar button opens #layersDropdown, drawn by renderLayersPanel(). The list is shown top layer first (pageLayers(currentPage).slice().reverse()), as draw.io lists them, while sort counts bottom to top. Each row has show / hide, lock / unlock, the name (double-click to rename), the number of items on it, up, down and delete. A click on the row itself makes it the active layer - where new items go - unless it is locked.

layerAction() handles the buttons:

        if (act === 'eye') {
            l.visible = l.visible === false;
            if (l.visible === false) clearSelection();
            if (ed) markDirty();   // a read-only version can still hide a layer to look - it just isn't saved
        } else if (!ed) {
            return;
        } else if (act === 'lock') {
            l.locked = !l.locked;
            if (l.locked) clearSelection();
            markDirty();
        } else if (act === 'up' || act === 'down') {
            const list = pageLayers(currentPage);
            const i = list.indexOf(l), j = i + (act === 'up' ? 1 : -1);
            if (j < 0 || j >= list.length) return;
            const tmp = list[i]; list[i] = list[j]; list[j] = tmp;
            list.forEach((x, k) => { x.sort = k; });
            markDirty();

Show / hide is the only action allowed on a read-only version: looking at an old version with a layer hidden changes nothing stored, and markDirty() is a no-op there anyway. Hiding or locking clears the selection, so a selected item can never be on a layer that is hidden or locked.

Locked means "can be seen, not picked up". It is enforced twice: CSS removes the items from the mouse entirely,

        .nm-node.is-locked, .nm-shape.is-locked { pointer-events: none; }

and every JavaScript hit test that does not go through the DOM filters them out by hand - findNodeAt(), findShapeAt(), the rubber band, Select all and groupOf(). A locked shape also gets no connection dots in buildShapeEl(). If you write a new hit test, filter with itemLocked() too.

Where a new item goes is activeLayerKey(), which refuses to put anything on a layer where it would vanish or be stuck:

    function activeLayerKey() {
        const k = activeLayers[currentPage];
        const l = k != null ? findLayer(currentPage, k) : null;
        // A new item never lands on a locked or hidden layer - it would vanish or be stuck.
        if (l && !l.locked && l.visible !== false) return l.layer_key;
        const list = pageLayers(currentPage).filter(x => !x.locked && x.visible !== false);
        return list.length ? list[list.length - 1].layer_key : 0;
    }
    /** Stamps a new item with the current page and the active layer. */
    function placeOnPage(it) { it.page_key = currentPage; it.layer_key = activeLayerKey(); return it; }

placeOnPage() is called by every path that creates an item: commitPickerSelection(), commitRelatedSelections() and addShapeAt(). Paste sets the same two fields itself. activeLayers is per page and is not saved; on load every page's active layer is the top usable one.

deleteLayer() never deletes items. They move to the layer below, or the one above for the bottom layer:

        const i = list.indexOf(l);
        const to = list[i > 0 ? i - 1 : 1];

Layer order also orders shapes. A shape on a higher user layer draws over one on a lower layer (layerRank() in renderShapes() above), and wins the hit test in findShapeAt(). Each shape's Behind / In front still decides which side of the nodes it is on; layers order shapes within that.

An item moves to another layer through the Layer select in its panel (layerSelectHtml() / bindLayerSelect(), locked layers disabled), the multi-selection panel, or the right-click "Move to layer" sub-menu.

What the server keeps

replacePages() cleans rather than refuses, except for one rule: a diagram must have a page.

        $pages = [];
        foreach (array_values($pagesIn) as $i => $p) {
            if (!is_array($p)) continue;
            $key = self::keyOf($p['page_key'] ?? $i);
            if (isset($pages[$key])) continue;
            $name = mb_substr(trim((string)($p['name'] ?? '')), 0, 100);
            $pages[$key] = [$name !== '' ? $name : 'Page ' . ($i + 1), (int)($p['sort'] ?? $i)];
        }
        if (!$pages) {
            throw new ServiceError('validation', 'invalid_field', 'A diagram needs at least one page.');
        }
        foreach (array_values($layersIn) as $i => $l) {
            if (!is_array($l)) continue;
            $pk = self::keyOf($l['page_key'] ?? 0);
            $lk = self::keyOf($l['layer_key'] ?? 0);
            if (!isset($pages[$pk]) || isset($seen["$pk:$lk"])) continue;
            $seen["$pk:$lk"] = true;
            $name = mb_substr(trim((string)($l['name'] ?? '')), 0, 100);
            $insL->execute([$diagramId, $pk, $lk, $name !== '' ? $name : 'Layer ' . ($lk + 1), (int)($l['sort'] ?? $i),
                            !isset($l['visible']) || $l['visible'] ? 1 : 0, !empty($l['locked']) ? 1 : 0]);
        }

A repeated key or a layer of a page that is not in the list is dropped rather than refused, because the unique keys uq_net_page / uq_net_layer would otherwise fail the whole save on an insert. visible defaults to on when missing (!isset(...) ||), locked to off - the safe direction for both. The English fallback names ('Page 1', 'Layer 1') are only reached by an API caller sending empty names; the editor always sends its own translated defaults.

Every item's keys go through keyOf():

    /** GH #433: a page or layer key - a small whole number, 0 when missing or odd. */
    private static function keyOf($v): int
    {
        return (is_numeric($v) && (int)$v >= 0 && (int)$v <= 100000) ? (int)$v : 0;
    }

The server does not check that an item's page_key / layer_key exists in the pages and layers it was sent. A node can be saved on page 7 with no page 7 row. That is allowed on purpose, and ensurePagesLayers() in the browser is what turns it into a tab again on the next load.

Like shapes, pages and layers are only replaced when pages is sent (saveDiagram() checks isset($in['pages'])), and api/network-mapper/save_diagram.php only forwards layers together with pages:

    // GH #433: pages (tabs) and their layers.
    if (array_key_exists('pages', $data) && is_array($data['pages'])) {
        $in['pages'] = $data['pages'];
        $in['layers'] = is_array($data['layers'] ?? null) ? $data['layers'] : [];
    }

Sending pages without layers therefore deletes every layer row; the editor always sends both.


Continue in Part 2: multi-select, connectors, menus and saving - including the Traps and Tests sections for both parts. Back to Network Mapper - Developer Guide.

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally