Skip to content

Network Mapper Background Developer Guide

Ed Mozley edited this page Nov 29, 2026 · 1 revision

🖼️ A background picture on a diagram page - Developer Guide

Discussion #434 (asked by @Shadowtech87) · Network Mapper · built after 5.13.0 (#3256-#3257)

How a page gets a floor plan behind it: the layer that holds it, how a PDF or a huge picture becomes something small enough to upload, the Adjust mode, and the server's rules. For what an analyst sees, start at Network Mapper → Background Picture; for the decisions, the design page. It builds on Shapes, pages and layers and Icon libraries and images; read those first if layers or My images are new to you.

1. Files

Key: 🗄️ schema · 📖 read · ✏️ write · 🔌 REST · 🖥️ UI · 🧪 test

🎨 File What it does
🗄️ database/freeitsm.sql, includes/db_verify_schema.php network_diagram_layers.is_background TINYINT(1) NOT NULL DEFAULT 0
✏️ includes/services/network_mapper.php replacePages() saves it (one per page, always locked); createVersion() copies it; backgroundReady() says whether the column exists yet
📖 api/network-mapper/get_diagram.php Returns is_background on each layer (SELECT *, so it works before Database Verification)
🔌 api/v1/resources/network_mapper.php, api/v1/lib/openapi_schemas.php is_background on a layer in the REST API, read and write
🖥️ assets/js/network-mapper-background.js The browser-side picture work: is it a PDF, draw a PDF page, make a picture small enough (window.NMBackground)
🖥️ assets/js/network-mapper.js The background layer helpers, the dialog, placing and fitting, Adjust mode, the Layers dropdown and right-click entries, corner resize keeping proportions
🖥️ network-mapper/diagram.php The #bgModal dialog, its styles, and the script tag
🖥️ network-mapper/help.php, lang/en/network-mapper.php (background.*, help.bg_*) Help and every string
🖥️ includes/feature_bingo/cards/network-mapper.php Card network-mapper.background
🧪 tests/network-mapper-background.php 12 server-side checks (section 7)

What is NOT new: the picture itself. A background is an ordinary icon shape (network_diagram_shapes.shape_type = 'icon', icon_id → network_icon_library_icons) uploaded to My images through the existing icon_libraries.php?action=upload, with its existing byte checks. No new table, no new endpoint, no new storage.

2. The model: one flagged layer

A page's background is the layer with is_background = 1, and its picture is the icon shape on that layer.

// assets/js/network-mapper.js
function bgLayer(pk) { return layers.find(l => l.page_key === pk && l.is_background) || null; }
function bgShape(pk) {
    const l = bgLayer(pk);
    return l ? (shapes.find(s => itemPage(s) === pk && itemLayer(s) === l.layer_key && s.shape_type === 'icon') || null) : null;
}
/** Puts the page's background layer first in its order (the bottom) and renumbers the sorts. */
function keepBgAtBottom(pk) { ... }

Why a flag and not the layer's name: a renamed layer ("Floor 2 plan") is still the background, and a layer someone happens to call "Background" isn't. Typed names are never used as config.

The rules, and where each is enforced:

Rule Browser Server
At most one per page ensurePagesLayers() keeps the first replacePages() keeps the first ($bgPage)
Always at the bottom keepBgAtBottom(); its arrows are disabled; layerAction() refuses to move another layer below it - (order is the editor's)
Always locked when saved The save payload sends locked: l.is_background ? true : !!l.locked replacePages() sets locked = 1 whatever was sent
Nothing else lands on it It's locked, so activeLayerKey() skips it; clicking its row doesn't make it active; the Layer pickers (side panel, right-click Move to layer) disable it -
Deleting another layer never moves things onto it deleteLayer() picks its target from the layers that aren't the background -
Copied with a page duplicatePage() copies layers with Object.assign, flag included createVersion() copies the column

backgroundReady() (a SELECT is_background ... LIMIT 0 probe) lets an install that hasn't run Database Verification keep saving diagrams: the column is simply left out of the INSERT.

3. Getting a picture small enough (in the browser)

// assets/js/network-mapper-background.js
const MAX_SIDE = 4000;                               // sharp enough to zoom into a floor plan
const TARGET_BYTES = Math.round(1.8 * 1024 * 1024);  // under PHP's stock 2 MB upload limit

async function prepare(blob, name) {
    // unchanged when it already fits: a supported type (not GIF), under TARGET_BYTES and MAX_SIDE
    ...
    let side = Math.min(MAX_SIDE, Math.max(w, h));
    for (let round = 0; round < 6; round++) {
        const cv = await draw(blob, side);
        for (const q of [0.88, 0.78, 0.66]) {
            let out = await toBlob(cv, 'image/webp', q);
            if (!out || out.type !== 'image/webp') out = await toBlob(cv, 'image/jpeg', q);   // no WebP writer
            if (out && out.size <= TARGET_BYTES) return { blob: out, name: base + '.' + ext };
        }
        side = Math.round(side * 0.75);
    }
    throw new Error('too_big');
}

Why in the browser: a floor plan is usually a PDF or a 20 MB scan, and the server takes 4 MB (2 MB on a stock PHP install). Doing it here needs no Ghostscript or Imagick on the server, and the server still checks the result by its bytes like any upload (NetworkIconService::addUpload() → safeImage()).

A GIF is always redrawn, so an animated one becomes a still picture. Something that isn't a picture fails at createImageBitmap() and comes back as not_image.

A PDF page:

async function openPdf(file) {
    const lib = await pdfjs();   // assets/js/vendor/pdfjs - the files the Files viewer uses
    const task = lib.getDocument({ data: new Uint8Array(await file.arrayBuffer()), isEvalSupported: false });
    const pdf = await task.promise;
    return { pages: pdf.numPages, async render(n) { /* page n at MAX_SIDE, white behind it, as PNG */ }, close() { task.destroy(); } };
}

⚠️ TRAP: isEvalSupported: false. A PDF can carry font programs; pdf.js must never eval them. Same setting as assets/js/files-thumbs.js. Keep it on any new pdf.js call.

The rendered PNG then goes through prepare() like any picture. A one-page PDF is used straight away; a longer one shows the Page of the PDF row in the dialog.

4. Placing it

// assets/js/network-mapper.js
function setBackground(ic) {
    let l = bgLayer(pk);
    if (!l) {   // the page's first background: a new layer, flagged, locked, at the bottom
        l = { page_key: pk, layer_key: lk, name: t('network-mapper.background.layer_name'), sort: -1, visible: true, locked: true, is_background: true };
        layers.push(l);
        keepBgAtBottom(pk);
    }
    const box = bgFitBox(ic.w, ic.h);
    const old = bgShape(pk);
    if (old) { old.icon_id = ic.id; Object.assign(old, box); }          // a new picture replaces the old one
    else shapes.push({ shape_type: 'icon', icon_id: ic.id, ...box, layer: 'back', z: minZ - 1, layer_key: l.layer_key, ... });
    ...
}

bgFitBox() fits the picture, keeping its proportions and centred, into the first of:

  1. the paper, when a paper size is set (pageDimensionsPx());
  2. what is on the page, not counting the background (nodes by nodeExtent(), shapes by their box), padded 40 px and at least 800 × 600;
  3. what the canvas shows at the current zoom and scroll.

The dialog's three ways in all end at setBackground():

  • a picture from My images (the grid);
  • an upload: onBackgroundFile(), then useBackgroundBlob() → prepare() → uploadPicture();
  • a PDF page: useBackgroundPdfPage() → render(n) → useBackgroundBlob().

uploadPicture() was split out of the existing uploadImages() (paste and the palette's Upload) so both register the new picture in the palette the same way.

5. Adjust mode

let bgAdjust = null;   // the page whose background is being adjusted, or null

function startBgAdjust() { ... bgAdjust = currentPage; l.locked = false; l.visible = true; renderShapes(); selectShape(shapeKey(sh)); renderBgBar(); }
function endBgAdjust()   { if (bgAdjust === null) return; bgLayer(bgAdjust).locked = true; bgAdjust = null; /* bar removed */ ... }
  • Unlocking is the whole trick. A locked layer's items get .is-locked (pointer-events: none), which is why clicks fall through to the canvas and its right-click menu (Background..., Adjust background). Unlocked, the picture is an ordinary selectable shape: drag to move, handles to resize, and the usual Format panel.
  • endBgAdjust() is called from everywhere that leaves: Done, Esc (the document keydown handler), switching page, entering Present, opening the dialog, removing the background. It is safe to call when not adjusting.
  • The bar (#bgBar, .nm-bg-bar) is added to the canvas's parent. Opacity writes style.opacity on the shape, the same key the Format panel uses, and re-renders that panel when the slider is released so the two agree. Fit reuses bgFitBox(); Original sets the shape to the picture's own w × h.
  • The background's padlock in Layers is Adjust, and its × is Remove. removeBackground() deletes the layer's shapes (and connectors touching them) and the layer; the picture stays in My images.

Corners keep proportions (every picture, #3257):

// onShapeResizeMove(e)
if (s.shape_type === 'icon' && r.dir.length === 2 && !e.shiftKey && r.w > 0 && r.h > 0) {
    const k = Math.max(w / r.w, h / r.h, MIN / Math.min(r.w, r.h));
    w = Math.round(r.w * k); h = Math.round(r.h * k);
    x = r.dir.indexOf('w') >= 0 ? r.x + r.w - w : r.x;   // the opposite corner stays put
    y = r.dir.indexOf('n') >= 0 ? r.y + r.h - h : r.y;
}

It applies to every icon shape, so logos and photos don't get stretched by accident either. Side handles (n, e, s, w) still stretch one way, and Shift on a corner stretches freely. Snapping is skipped while keeping proportions, because snapping both sides would break the ratio.

6. Export, Present and read-only versions

Nothing special: the background is a shape on a visible layer, so PNG and PDF export and Present show it, and hiding its layer with the eye leaves it out of all three, like any layer. A read-only version can't set, adjust or remove one: every entry point checks canEdit().

7. Testing

FREEITSM_TEST_DATABASE=freeitsm_prtest FREEITSM_TEST_URL=http://localhost/freeitsm-prtest \
FREEITSM_SESS_DIR=C:/wamp64/tmp php tests/network-mapper-background.php      (from the prtest folder)

The test (12 checks) covers the server:

  • one background per page, and it's saved locked even when sent unlocked;
  • an ordinary layer isn't locked by it (positive control);
  • a save without the flag makes none;
  • createVersion() copies the layer and its picture;
  • the REST API's layer list says true or false;
  • api/network-mapper/get_diagram.php, over HTTP, tells the editor.

The browser side was checked in Chrome when it was built:

  • a picture and a PDF page through the dialog, read back from the database;
  • a 6000 × 3600 picture became a 4000 × 2400 WebP of 374 KB, and a text file is refused;
  • click-through when locked, a corner drag keeping the ratio (0.707 → 0.707), Shift stretching, Esc relocking;
  • dark mode.

⚠️ TRAP for anyone re-testing in a headless browser: pdf.js runs in a worker, and big canvas.toBlob() / createImageBitmap() calls run off the main thread. Under --virtual-time-budget (the usual --screenshot / --dump-dom runs) they never finish, and everything after them silently doesn't run. Drive Chrome in real time over its DevTools socket instead, as tests/virtual-estate-storage-browser.php does with cdpEvaluate().

8. Extending it

  • Another source (a picture already in Files, say): end at useBackgroundBlob(blob, name), and it goes through the same shrinking and upload.
  • A bigger or smaller target: MAX_SIDE and TARGET_BYTES in assets/js/network-mapper-background.js. Keep TARGET_BYTES under the smallest upload limit you want to support, not the server's 4 MB.
  • A scale on the plan, or seats and rooms as records: out of scope here (design section 6). Seats would be their own records linked to Locations and assets, not shapes with special names.

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally