Skip to main content

Web API recipes

Use these recipes to connect your own browser JavaScript to a Mimeeq configurator. The complete examples can run independently on a page with an inline or modal configurator embed. Load the code as a deferred script or a module so the host page's DOM exists.

The examples assume one configurator per page. For a host that replaces or remounts the embed, initialize again for the new mount and clean up the previous mount's subscriptions, listeners, and controls. For cleanup when an embed is removed, attach its unmount listener to the embed element.

Connect to the Web API​

Check for window.mimeeqApp so the code works even when it loads after the embed script. If the API is still loading, listen once for mimeeq-api-installed on document.

function start() {
console.log('Mimeeq Web API is available');
}

if (window.mimeeqApp) start();
else document.addEventListener('mimeeq-api-installed', start, { once: true });
SignalTypeMeaning
window.mimeeqAppMimeeqApp once availableThe API object is available for attaching observers.
mimeeq-api-installedEvent with no application payloadThe bundle has assigned the API object.
status.firstRender, status.sceneSettledboolean eachWait for the first frame before using 3D geometry or camera controls. Check sceneSettled when you need a still scene.

The mimeeq-app-loaded event signals that the first embed has loaded. A modal or product picker can reach that milestone before opening a product. See Observers for product and scene readiness.

Choose the readiness signal for your task​

Use status.settled to read product configuration data once the product has loaded, the canvas is unblocked, no item is being moved or rotated, and no 3D tasks are pending. Camera motion can continue during that read. For a still 3D picture, use status.sceneSettled together with status.firstRender. An empty modular scene can render its first frame without any placed items. Check scene.bounds or scene.instanceBounds separately when you need measured geometry.

This example reads the latest SKU whenever the configurator becomes settled or the SKU changes while settled.

function showSettledSku() {
const { status, product } = window.mimeeqApp.observers;
const output = document.createElement('output');
document.body.append(output);
const render = () => {
output.textContent = status.settled.getValue()
? product.sku.getValue() || 'SKU unavailable'
: 'Preparing configuration…';
};
const subscriptions = [status.settled.subscribe(render), product.sku.subscribe(render)];
window.addEventListener('pagehide', () => subscriptions.forEach((sub) => sub.unsubscribe()), {
once: true,
});
}
if (window.mimeeqApp) showSettledSku();
else document.addEventListener('mimeeq-api-installed', showSettledSku, { once: true });

For a capture button, keep it disabled until all three scene checks pass. The plan view for a PDF shows the subscriptions and capture together. When displaying a final price, watch status.priceLoading separately.

Show AR progress​

Subscribe to status.ar before calling actions.showAR(). It emits generating while the built-in AR view prepares its link or file, ready when available, failed if preparation fails, and closed when the view is dismissed. Listen for mimeeq-ar-ready to receive the QR landing page URL when one is presented.

Show an embed load error​

Attach the mimeeq-app-config-error listener before the embed starts loading. Once the API is available, subscribe to status.loadError to replay the current failure and clear your message when a new load starts. Choose the message from reason and use the optional HTTP status for diagnostics or retry decisions.

const embed = document.querySelector('mmq-embed');
const message = document.querySelector('#embed-message');
const copy = {
short_code_missing: 'This configuration link is incomplete.',
short_code_not_found: 'This configuration link is unavailable.',
customer_not_found: 'This configurator is unavailable.',
customer_inactive: 'This configurator is unavailable.',
product_not_found: 'This product is unavailable.',
offline: 'Reconnect to the internet and try again.',
network: 'Check your connection and try again.',
timeout: 'The request timed out. Please try again.',
http_5xx: 'The service is temporarily unavailable. Please try again.',
};
const showError = (reason) => {
message.textContent = reason ? (copy[reason] ?? 'The configurator could not load.') : '';
};

embed.addEventListener('mimeeq-app-config-error', ({ detail }) => {
showError(detail.reason ?? 'unknown');
});

function watchFailure() {
const subscription = window.mimeeqApp.observers.status.loadError.subscribe(({ newValue }) => {
showError(newValue?.reason);
});
window.addEventListener('pagehide', () => subscription.unsubscribe(), { once: true });
}
if (window.mimeeqApp) watchFailure();
else document.addEventListener('mimeeq-api-installed', watchFailure, { once: true });

Read and watch the selected options for a block​

Use window.mimeeqApp.observers.optionSets.selectedOptionsByBlockCode to keep host UI in sync with a known block. Replace Finish with the exact block code configured for your product.

function start() {
const blockCode = 'Finish';
const selections = window.mimeeqApp.observers.optionSets.selectedOptionsByBlockCode;
const output = document.createElement('output');
document.body.append(output);

console.log('Current selection:', selections.getValue()?.[blockCode] ?? []);

const subscription = selections.subscribe(({ newValue }) => {
const options = newValue?.[blockCode] ?? [];
output.textContent = options.length
? `Finish: ${options.map(({ code }) => code).join(', ')}`
: 'Choose a finish';
});

document.querySelector('mmq-embed')?.addEventListener(
'mimeeq-embed-unmounted',
() => {
subscription.unsubscribe();
output.remove();
},
{ once: true },
);
}

if (window.mimeeqApp) start();
else document.addEventListener('mimeeq-api-installed', start, { once: true });
ValueTypeMeaning
Observer valuePartial<Record<string, readonly OptionSetOption[]>>Keys are configured block codes (blockName). An empty map means there are no selections indexed.
value[blockCode]readonly OptionSetOption[] | undefinedAll selected options for the block. An absent key means there is no indexed selection for that code.
option.codestringThe option's configuration code. Use it for integration logic.

getValue() reads synchronously. subscribe() emits the current value immediately as { newValue }, then emits { newValue, oldValue } on changes. A block can have multiple selections. In a modular configurator the map follows the current selection context. For a specific placed item, use the per-item options example. Treat observer values as read-only.

Read visible choices, the price break, and cropped artwork​

Run these reads after the API is installed.

const { optionSets, pricing } = window.mimeeqApp.observers;
const block = optionSets.blocks.getValue()?.find(({ blockName }) => blockName === 'Finish');
const choices = block ? optionSets.visibleOptionsByBlock.getValue()?.[block.id] ?? [] : [];
const enabledChoices = choices.filter(({ isDisabled }) => !isDisabled);
const tier = pricing.activePriceTier.getValue();
const crops = optionSets.printOnDemandCrops.getValue() ?? {};
const artworkBlock = optionSets.blocks.getValue()?.find(({ blockName }) => blockName === 'Artwork');
const cropUrl = artworkBlock ? crops.SINGLE_PRODUCT_ID?.[artworkBlock.id] ?? null : null;

Replace Finish and Artwork with your authored block codes. The choices already exclude authored and rule-hidden options. For a modular product, look up the crop by the placed item's instance ID in place of SINGLE_PRODUCT_ID.

Use subscribe(({ newValue }) => ...) on any of these observers to update your controls as the values change.

Save and restore a local modular design​

Call the local autosave from a Save button after the API is installed. The action resolves to true once the browser stores the current modular design, or false for an empty or standard configuration or when storage fails.

const didSave = await window.mimeeqApp.actions.saveLastSavedDesign();
if (didSave) console.log('Saved on this device');

Wait for the modular product to load before reading its local autosave. If a saved design is available, you can offer a restore control and pass its configuration to the scene loader.

const { actions } = window.mimeeqApp;
const saved = await actions.getLastSavedDesign();
if (saved) await actions.loadModularScene(null, true, false, false, saved.config);

Build an asset URL from the embed CDN​

Use window.mimeeqApp.observers.config.cdnPath to build URLs for assets stored on the embed's CDN. Replace assetPath with the relative path of your uploaded asset.

function showAsset(image, assetPath) {
const { cdnPath } = window.mimeeqApp.observers.config;
const subscription = cdnPath.subscribe(({ newValue }) => {
if (newValue) image.src = new URL(assetPath, newValue.replace(/\/?$/, '/')).href;
else image.removeAttribute('src');
});
return () => subscription.unsubscribe();
}

Call showAsset after the Web API is available. The observer replays the current base URL, or undefined if the path is unavailable. Run the returned cleanup function when removing the image.

Greet the signed-in user and gate a control​

Use window.mimeeqApp.observers.auth.user to render a host control that follows the embed's sign-in state.

function start() {
const user = window.mimeeqApp.observers.auth.user;
const greeting = document.createElement('p');
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'Show account options';
button.onclick = () => {
greeting.textContent = 'Account options are available while you are signed in.';
};
document.body.append(greeting, button);

const subscription = user.subscribe(({ newValue }) => {
greeting.textContent = newValue
? `Hello, ${newValue.name || 'there'}!`
: 'Sign in for account options.';
button.hidden = !newValue;
});
document.querySelector('mmq-embed')?.addEventListener(
'mimeeq-embed-unmounted',
() => {
subscription.unsubscribe();
greeting.remove();
button.remove();
},
{ once: true },
);
}

if (window.mimeeqApp) start();
else document.addEventListener('mimeeq-api-installed', start, { once: true });
FieldTypeMeaning
idstringSigned-in user ID.
name, emailstring | undefinedProfile name and email, when supplied.
customerId, companyId, typestring | undefinedAccount context, when supplied.

null means there is no signed-in embed user. This controls what the browser displays. Authorize protected operations on your server.

Use window.mimeeqApp.actions.getShareUrl() to copy a URL that restores the current options on the host page.

function start() {
const button = document.createElement('button');
const status = document.createElement('output');
button.type = 'button';
button.textContent = 'Copy configuration link';
document.body.append(button, status);

button.onclick = async () => {
button.disabled = true;
try {
const url = await window.mimeeqApp.actions.getShareUrl();
if (!url) {
status.textContent = 'Open a standard product first.';
return;
}
try {
await navigator.clipboard.writeText(url);
status.textContent = 'Configuration link copied.';
} catch {
status.textContent = url;
}
} catch {
status.textContent = 'Could not create the configuration link.';
} finally {
button.disabled = false;
}
};
}

if (window.mimeeqApp) start();
else document.addEventListener('mimeeq-api-installed', start, { once: true });
ResultTypeMeaning
Share URLstringAbsolute URL containing the configuration. On host pages it includes mmqShare=1 and an mmqEmbed scope when the active embed can be identified.
UnavailablenullThe standard product is loading or absent, or its prefix is unavailable.

Copy the entire returned URL and leave its query parameters intact. Keep the host page and its embed available to recipients. If the clipboard is unavailable or blocked, the example displays the URL for manual copying.

Use window.mimeeqApp.actions.getModularShareUrl() to save the layout of a modular scene and copy its URL.

function start() {
const button = document.createElement('button');
const status = document.createElement('output');
button.type = 'button';
button.textContent = 'Copy scene link';
document.body.append(button, status);

button.onclick = async () => {
button.disabled = true;
try {
const url = await window.mimeeqApp.actions.getModularShareUrl();
if (!url) {
status.textContent = 'Could not save the scene for sharing.';
return;
}
try {
await navigator.clipboard.writeText(url);
status.textContent = 'Scene link copied.';
} catch {
status.textContent = url;
}
} catch {
status.textContent = 'Could not create the scene link.';
} finally {
button.disabled = false;
}
};
}

if (window.mimeeqApp) start();
else document.addEventListener('mimeeq-api-installed', start, { once: true });
ResultTypeMeaning
Scene URLstringAbsolute URL for the saved scene. A host embed URL carries its scene shortCode.
UnavailablenullNo product ID or prefix is available, or the scene short code could not be saved.

Call this for a modular product after the desired scene edits are complete. It saves the current scene when called, so call it on demand. Pass true only when you want the saved short code by itself. The example displays the URL if the clipboard write fails.

Set a custom price without reacting to your own update​

Enable Use Custom Pricing on the standard embed template. Use option and quantity changes to calculate a price, then use pricing.priceSource to separate Mimeeq price updates from calls to utils.setPrice(). This example uses a fixed unit price and applies it to the current quantity.

function start() {
const { observers, utils } = window.mimeeqApp;
const updatePrice = () => {
if (observers.status.loading.getValue() !== false) return;
const quantity = observers.pricing.quantity.getValue() ?? 1;
const unitPrice = 49;
utils.setPrice({ price: unitPrice * quantity, unitPrice, currency: 'EUR', levels: [] });
};

const subscriptions = [
observers.status.loading.subscribe(updatePrice),
observers.optionSets.selectedOptionsByBlockCode.subscribe(updatePrice),
observers.pricing.quantity.subscribe(updatePrice),
observers.pricing.priceSource.subscribe(({ newValue }) => {
if (newValue?.source !== 'engine') return;
console.log('Mimeeq engine price:', newValue.prices.price);
}),
];

document.querySelector('mmq-embed')?.addEventListener(
'mimeeq-embed-unmounted',
() => {
subscriptions.forEach((subscription) => subscription.unsubscribe());
},
{ once: true },
);
}

if (window.mimeeqApp) start();
else document.addEventListener('mimeeq-api-installed', start, { once: true });
FieldTypeMeaning
source'engine' | 'custom'Origin of the current prices. 'custom' means a custom price was applied, including your own call to setPrice().
pricesPriceDataCurrent price object. price is the total, unitPrice the per-unit amount, and currency the ISO currency code. levels: [] supplies no quantity breaks.

priceSource is null before a sourced price is available. With custom pricing enabled, the built-in price fetch is bypassed, so an engine update is not required to start your calculation. For async quotes, discard results for options or quantities the shopper has since changed. Custom pricing integration

Show delivery time​

Use window.mimeeqApp.observers.product.availability for a host delivery label based on the current configuration's Item Master data.

function start() {
const output = document.createElement('output');
document.body.append(output);
const subscription = window.mimeeqApp.observers.product.availability.subscribe(({ newValue }) => {
const days = newValue?.deliveryTime;
output.textContent =
days == null
? 'Delivery estimate unavailable'
: `Estimated lead time: ${days} ${days === 1 ? 'day' : 'days'}`;
});
document.querySelector('mmq-embed')?.addEventListener(
'mimeeq-embed-unmounted',
() => {
subscription.unsubscribe();
output.remove();
},
{ once: true },
);
}

if (window.mimeeqApp) start();
else document.addEventListener('mimeeq-api-installed', start, { once: true });
FieldTypeMeaning
deliveryTimenumber | nullLongest known Item Master lead time in days. Zero is a known lead time. Guard a null value as unavailable.

The whole value is null while the product or price is loading or when there is no applicable lead time. Use a separate inventory source for stock data.

Add a configuration to a Shopify cart​

Set Basket Support on the embed template and choose HTML integration. This example is for a Shopify product page with one Mimeeq configurator and a single mapped Shopify variant. Set data-mimeeq-cart-variant on your page to that variant's numeric ID, for example on an element rendered by your theme. For a multi-variant product, update the attribute when the shopper changes Shopify variants.

const status = document.createElement('output');
status.setAttribute('aria-live', 'polite');
const preview = document.createElement('img');
preview.alt = 'Configuration added to cart';
preview.hidden = true;
document.body.append(status, preview);

let adding = false;

document.addEventListener('mimeeq-add-to-cart', async ({ detail }) => {
if (detail.basketImplementationType !== 'html' || adding) return;

const variantId = Number(
document.querySelector('[data-mimeeq-cart-variant]')?.getAttribute('data-mimeeq-cart-variant'),
);
if (!Number.isSafeInteger(variantId) || variantId <= 0) {
status.textContent = 'Select a Shopify variant first.';
return;
}

adding = true;
status.textContent = 'Adding to cart…';
preview.hidden = true;

try {
const root = window.Shopify?.routes?.root ?? '/';
const response = await fetch(`${root}cart/add.js`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
items: [
{
id: variantId,
quantity: detail.qty,
properties: {
'Mimeeq configuration': detail.variantCode,
...(detail.shortCode ? { 'Mimeeq short code': detail.shortCode } : {}),
},
},
],
}),
});
if (!response.ok) throw new Error('Shopify did not accept the line item.');

status.textContent = `${detail.productName} added to cart.`;
if (detail.image) {
preview.src = detail.image;
preview.hidden = false;
}
} catch {
status.textContent = 'Could not add the configuration to the cart.';
} finally {
adding = false;
}
});
FieldTypeMeaning
productId, productNamestringMimeeq product ID and display name. Map to your own cart's merchandise ID.
qtynumberConfigured order quantity.
variantCode, shortCodestringStandard variant identifier and configuration short code. For modular products, variantCode is the product prefix and shortCode identifies the saved scene.
imagestring | undefinedA data URL when a snapshot or thumbnail is available. Hide the preview for missing or empty images.
price, unitPrice, currencynumber | undefined, number | undefined, string | undefinedMimeeq total, per-unit price and currency when available. Shopify prices the mapped variant.
basketImplementationType'html' | 'mimeeq' | undefinedWhich system owns the cart. The example handles HTML integration only.

Register the listener on document before a shopper can add an item. The event hands off the configuration. Your cart response determines success. The example uses the image for a local preview. If the image needs to survive navigation, store it through your own backend and keep a reference with the line item. With multiple embeds, use detail.embedInstanceId to route events to the correct cart mapping. Ecommerce integration · Shopify Cart API

Open a widget or group from your own button​

Call window.mimeeqApp.actions.openWidget(blockId) or window.mimeeqApp.actions.openGroup(groupId) when a host control opens its own panel and needs to run the product's configured open rules. This example opens a host details panel for the first enabled block or the first group in the current options panel.

function start() {
const {
actions,
observers: { optionSets },
} = window.mimeeqApp;
const widget = document.createElement('button');
const group = document.createElement('button');
widget.type = group.type = 'button';
widget.textContent = 'Open first option widget';
group.textContent = 'Open first option group';
const panel = document.createElement('p');
panel.hidden = true;
widget.onclick = () => {
const block = optionSets.blocks.getValue()?.find((item) => !item.isDisabled);
panel.hidden = false;
panel.textContent = block?.name ?? 'No available option widget';
if (block) void actions.openWidget(block.id);
};
group.onclick = () => {
const first = optionSets.blockGroups.getValue()?.[0];
panel.hidden = false;
panel.textContent = first?.name ?? 'No available option group';
if (first) void actions.openGroup(first.id);
};
document.body.append(widget, group, panel);
}

if (window.mimeeqApp) start();
else document.addEventListener('mimeeq-api-installed', start, { once: true });
ValueTypeMeaning
block.idstringWidget block ID from optionSets.blocks.
group.idstringOption group ID from optionSets.blockGroups.
Action resultPromise<void>Resolves after the corresponding UI trigger is queued.

Supply IDs from the active product. These actions run the configured widget and group triggers. In a custom UI, open your own panel and call the action to notify Mimeeq. Related actions include closeWidget, clickButtonWidget, closeGroup, and hoverGroup(groupId, 'hover-off').

Close the active hotspot​

Use window.mimeeqApp.actions.closeHotspot(hotspotId) for a host control that dismisses open hotspot information and runs the close trigger.

function start() {
const { actions, observers } = window.mimeeqApp;
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'Close hotspot';
button.onclick = () => {
const hotspotId = observers.product.hotSpot.getValue()?.meshId;
if (hotspotId) void actions.closeHotspot(hotspotId);
};
document.body.append(button);
}

if (window.mimeeqApp) start();
else document.addEventListener('mimeeq-api-installed', start, { once: true });
ValueTypeMeaning
hotSpot.meshIdstringHotspot identifier used by the close trigger.
hotSpot.instanceIdstringID of the product instance carrying the hotspot.
hotSpot.dimensionsCoordinatesProjected screen position of the hotspot.

A missing hotspot means there is nothing to close. An omitted or empty ID is ignored by the action.

React to a breakpoint​

Use window.mimeeqApp.utils.cssMedia.matchMedia() to switch your host controls between layouts when a media query changes.

function start() {
const media = window.mimeeqApp.utils.cssMedia.matchMedia('(min-width: 960px)');
const output = document.createElement('output');
document.body.append(output);

const render = () => {
output.textContent = media.matches ? 'Wide controls' : 'Compact controls';
};
render();
media.addListener(render);

document.querySelector('mmq-embed')?.addEventListener(
'mimeeq-embed-unmounted',
() => {
media.dispose();
output.remove();
},
{ once: true },
);
}

if (window.mimeeqApp) start();
else document.addEventListener('mimeeq-api-installed', start, { once: true });
ValueTypeMeaning
media.matchesbooleanWhether the query currently matches. The example uses a breakpoint in CSS pixels.
media.mediastringThe media query associated with the watcher.
Listener argumentMediaQueryListEventBrowser notification when the match changes.

Read matches for the initial layout. You can remove one listener with removeListener(). Dispose the watcher when its host control is removed to release browser updates and listeners.

Fire your own event​

Use window.mimeeqApp.utils.dispatchEvent() when a custom control needs to notify another script on the page.

function start() {
const app = window.mimeeqApp;
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'Announce that options are ready';
document.body.append(button);

const lifetime = new AbortController();
document.addEventListener(
'storefront:options-ready',
(event) => {
if (event instanceof CustomEvent) console.log('Panel is ready:', event.detail.panel);
},
{ signal: lifetime.signal },
);
document.querySelector('mmq-embed')?.addEventListener(
'mimeeq-embed-unmounted',
() => {
lifetime.abort();
button.remove();
},
{ once: true },
);
button.onclick = () => {
app.utils.dispatchEvent('storefront:options-ready', { panel: 'options' });
};
}

if (window.mimeeqApp) start();
else document.addEventListener('mimeeq-api-installed', start, { once: true });
ArgumentTypeMeaning
namestringYour event name. Give it a prefix owned by your integration.
detailOptional JSON-serializable valueData available to listeners in event.detail.
targetHTMLElement | DocumentOptional dispatch target. Defaults to document.
bubblesbooleanOptional flag to bubble from the target. Defaults to false.

The helper can relay the event and its detail with postMessage, so keep the payload small and free of private data. A custom event is a notification. Use a public action for a change to Mimeeq state.

Pin hotspot labels to visible meshes​

For a standard 3D product, place an overlay element such as <div id="hotspot-labels"></div> over the active canvas. Give the overlay position: absolute; inset: 0; pointer-events: none inside a positioned host whose edges match the canvas. The projected rectangle is measured in CSS pixels from the canvas's top-left corner.

meshes.hotspots describes hotspot presentation for the selected options. This recipe labels active hotspots with a projected rectangle in view. Enabled hotspot anchor meshes can be projected even when their geometry is invisible. A rectangle with screen.visible intersects the camera view and may still be occluded by another part. The camera subscriptions below refresh labels when the main camera changes on a drawn frame.

function mountHotspotLabels() {
const layer = document.getElementById('hotspot-labels');
if (!layer) return;
const { actions, observers } = window.mimeeqApp;
const { camera, meshes, status } = observers;
let frame = 0;
let generation = 0;

const schedule = () => {
generation += 1;
if (frame) return;
frame = requestAnimationFrame(async () => {
frame = 0;
const current = generation;
const hotspots = (meshes.hotspots.getValue() ?? []).filter(({ active }) => active);
const labels = [];
if (status.firstRender.getValue()) {
for (const { instanceId, meshId, meshName, config } of hotspots) {
// Enabled hotspot anchors can be projected even when their geometry is invisible.
const position = await actions.getMeshPosition({ instanceId, meshId });
if (!position?.screen.visible) continue;
const { x, y, width } = position.screen;
const label = document.createElement('span');
label.textContent = config?.label || meshName;
Object.assign(label.style, {
position: 'absolute',
left: `${x + width / 2}px`,
top: `${y}px`,
transform: 'translate(-50%, -100%)',
background: 'white',
});
labels.push(label);
}
}
if (current === generation) layer.replaceChildren(...labels);
});
};
const subscriptions = [
status.firstRender,
meshes.hotspots,
meshes.active,
camera.position,
camera.target,
camera.zoomLevel,
camera.projectionMode,
].map((observer) => observer.subscribe(schedule));
const resize = new ResizeObserver(schedule);
resize.observe(layer);
window.addEventListener(
'pagehide',
() => {
generation += 1;
cancelAnimationFrame(frame);
resize.disconnect();
subscriptions.forEach((subscription) => subscription.unsubscribe());
},
{ once: true },
);
}
if (window.mimeeqApp) mountHotspotLabels();
else document.addEventListener('mimeeq-api-installed', mountHotspotLabels, { once: true });

getMeshPosition({ instanceId, meshId, meshName }) returns combined world: { center, min, max } and screen: { x, y, width, height, visible } for matching visible meshes and enabled hotspot anchors, or null when none can be projected. Supply a mesh ID, an exact case-sensitive mesh name, or a name regular expression. With both filters, a mesh must match both. The instance ID is optional for a standard product.

To project your own world-space points, call actions.getScreenPosition(points). Pass an array of { x, y, z } objects or [x, y, z] tuples. The result is an equally ordered array of { x, y, inView } in canvas-relative CSS pixels, or null if projection or any point is invalid. Use inView to hide points outside the viewport or depth range.

List active materials with thumbnails​

Each material entry includes the references of the active meshes that use it. Use the resolved thumbnail URL directly and show a text label when the thumbnail is null. This works for standard products and for placed modular items.

function mountMaterialList() {
const { materials } = window.mimeeqApp.observers.meshes;
const list = document.createElement('ul');
list.setAttribute('aria-label', 'Materials in use');
document.body.append(list);

const render = () => {
const rows = (materials.getValue() ?? []).map(({ materialId, name, thumbnail, meshes }) => {
const row = document.createElement('li');
if (thumbnail) {
const image = document.createElement('img');
image.src = thumbnail;
image.alt = '';
image.width = 48;
row.append(image);
}
row.append(`${name || materialId} (${meshes.length} parts)`);
return row;
});
list.replaceChildren(...rows);
};
const subscription = materials.subscribe(render);
window.addEventListener('pagehide', () => subscription.unsubscribe(), {
once: true,
});
}
if (window.mimeeqApp) mountMaterialList();
else document.addEventListener('mimeeq-api-installed', mountMaterialList, { once: true });

Explain required snaps and offer placement​

Read observers.modular.modularSceneElements for requiredSnaps on each placed instance. number is the minimum connected count, and list holds each applicable mesh as { id, code, status, connectedTo }. One required code can match several meshes. Status is connected, missing (no connection found), or broken (the stored connection cannot be resolved).

Use sceneValidity.isValid as the scene verdict. sceneValidity.missingRequiredSnaps lists the missing or broken entries on items below their minimum, with instanceId, productId, and productName. Filling the minimum for an item can clear its warning even when some of its connectors remain open.

After the user chooses a component to add, read snapPlacementControls for current candidates. Use an available add control for a direct connection and an available insert control to insert at an occupied joint. An empty scene has no placed snap targets. See the snap-aware add flow for adding a first item.

function mountSnapControls() {
const { actions, observers } = window.mimeeqApp;
const { modular, status } = observers;
const warnings = document.createElement('ul');
const button = document.createElement('button');
const output = document.createElement('output');
document.body.append(warnings, button, output);

const getCandidate = () => {
const placement = modular.snapPlacementControls.getValue();
if (!placement || !status.firstRender.getValue() || !status.settled.getValue()) return;
const control = placement.controls.find(({ availability }) => availability === 'available');
if (control) return { ...control, productId: placement.productId };
};

let placing = false;
const render = () => {
const items = modular.modularSceneElements.getValue() ?? {};
const validity = modular.sceneValidity.getValue();
const rows = (validity?.missingRequiredSnaps ?? []).map(
({ instanceId, id, code, productName, status }) => {
const row = document.createElement('li');
const required = items[instanceId]?.requiredSnaps;
const connected = required?.list.filter(({ status }) => status === 'connected').length;
row.textContent = `${productName}: ${code} (${id}) is ${status}`;
if (required) row.append(` · ${connected} of ${required.number} required connections made`);
return row;
},
);
if (validity?.isValid === false && !rows.length) {
const row = document.createElement('li');
row.textContent = 'The scene could not be validated';
rows.push(row);
}
warnings.replaceChildren(...rows);
const candidate = getCandidate();
button.disabled = placing || !candidate;
button.textContent = candidate
? `${candidate.type === 'insert' ? 'Insert' : 'Add'} at ${candidate.target.snapId}`
: 'No placement available';
};

button.onclick = async () => {
const candidate = getCandidate();
if (placing || !candidate) return;
const { type, target, productId } = candidate;
placing = true;
render();
try {
const placed = await (type === 'insert'
? actions.insertProductAtSnap(target, productId)
: actions.addProductToSnappingPoint(target.instanceId, target.snapId, productId));
output.textContent = placed ? 'Component placed' : 'Placement is no longer available';
} catch (error) {
output.textContent = 'Could not place the component';
console.error(error);
} finally {
placing = false;
render();
}
};

const subscriptions = [
modular.modularSceneElements,
modular.sceneValidity,
modular.snapPlacementControls,
status.firstRender,
status.settled,
].map((observer) => observer.subscribe(render));
window.addEventListener('pagehide', () => subscriptions.forEach((sub) => sub.unsubscribe()), {
once: true,
});
}
if (window.mimeeqApp) mountSnapControls();
else document.addEventListener('mimeeq-api-installed', mountSnapControls, { once: true });

Place a free item and undo​

actions.placeFreeItem(instanceId, { position, rotation? }) moves an already placed, free-moving modular item with no snap connections. Position is absolute in Y-up scene units. Rotation is an optional absolute heading in degrees about Y. Leave it out to keep the current orientation. A successful placement records one undo step and resolves when the move's own 3D work finishes. The action returns false if the input is invalid, the scene or item geometry is unavailable, the item cannot move freely, the shopper is dragging, or a canvas loader or image capture blocks the move. Reloading or clearing the scene also invalidates a pending placement.

This example moves the first eligible item one scene unit along X. Use the standard undo action and its availability observer, so Undo always follows scene history.

function mountFreePlacement() {
const { actions, observers } = window.mimeeqApp;
const { status, modular, history } = observers;
const move = document.createElement('button');
move.textContent = 'Move free item along X';
const undo = document.createElement('button');
undo.textContent = 'Undo';
const output = document.createElement('output');
document.body.append(move, undo, output);

const getItem = () =>
Object.values(modular.modularSceneElements.getValue() ?? {}).find(
({ freeMove, connections, position }) => freeMove && !connections.length && position,
);
let moving = false;
const render = () => {
const ready = status.firstRender.getValue() && status.settled.getValue();
move.disabled = moving || !ready || !getItem();
undo.disabled = moving || !ready || !history.canUndo.getValue();
};
move.onclick = async () => {
const item = getItem();
if (move.disabled || !item) return;
const { x, y, z } = item.position;
moving = true;
render();
try {
const placed = await actions.placeFreeItem(item.instanceId, { position: { x: x + 1, y, z } });
output.textContent = placed ? 'Item moved' : 'Could not move the item';
} catch (error) {
output.textContent = 'Could not move the item';
console.error(error);
} finally {
moving = false;
render();
}
};
undo.onclick = () => actions.goBack();
const subscriptions = [
status.firstRender,
status.settled,
modular.modularSceneElements,
history.canUndo,
].map((observer) => observer.subscribe(render));
window.addEventListener('pagehide', () => subscriptions.forEach((sub) => sub.unsubscribe()), {
once: true,
});
}
if (window.mimeeqApp) mountFreePlacement();
else document.addEventListener('mimeeq-api-installed', mountFreePlacement, { once: true });

See Undo and redo for waiting through an undo or redo transition.

Build a custom PDF button​

Call actions.getPdfTabs() after a product loads. It returns { id, name, type } entries in export order, starting with the translated Configuration Specification. Eligible product tabs follow in product order. They must be visible through the product tabs observer, have a name, and be enabled for PDF. Downloads, dynamic popular configurations, related products, and the configurator tab are excluded. The action returns an empty list without a loaded product.

Use getPdfTabs() for the choice labels and IDs. To export, pass full ProductTab records from observers.product.tabs to actions.generateProductPDF(). For the configuration specification, build the record from the returned descriptor. This example exports one selected section.

function mountPdfButton() {
const { actions, observers } = window.mimeeqApp;
const select = document.createElement('select');
select.setAttribute('aria-label', 'PDF section');
const button = document.createElement('button');
button.textContent = 'Export PDF';
const output = document.createElement('output');
document.body.append(select, button, output);

let exporting = false;
let request = 0;
const refresh = async () => {
const current = ++request;
button.disabled = true;
const previous = select.value;
try {
const tabs = await actions.getPdfTabs();
if (current !== request) return;
select.replaceChildren(...tabs.map(({ name, id }) => new Option(name, id)));
if (tabs.some(({ id }) => id === previous)) select.value = previous;
button.disabled = exporting || !tabs.length;
} catch (error) {
if (current === request) output.textContent = 'Could not load PDF sections';
console.error(error);
}
};

button.onclick = async () => {
if (exporting || button.disabled) return;
const id = select.value;
exporting = true;
button.disabled = true;
output.textContent = '';
try {
const tab = (await actions.getPdfTabs()).find((entry) => entry.id === id);
if (!tab) return;
const section =
tab.type === 'CONFIGURATION'
? { id: tab.id, tabName: tab.name, tabType: tab.type }
: observers.product.tabs.getValue()?.find((entry) => entry.id === tab.id);
if (section) await actions.generateProductPDF([section]);
} catch (error) {
output.textContent = 'Could not export the PDF';
console.error(error);
} finally {
exporting = false;
void refresh();
}
};

const subscription = observers.product.tabs.subscribe(refresh);
window.addEventListener('pagehide', () => subscription.unsubscribe(), { once: true });
}
if (window.mimeeqApp) mountPdfButton();
else document.addEventListener('mimeeq-api-installed', mountPdfButton, { once: true });

See PDF customization for layout and delivery hooks. Use mimeeq-pdf-generate-done when your UI needs the export outcome.

Save shopper uploads to the Media Library from a PDF script​

Use actions.savePodFilesToMediaLibrary to save the shopper's Print on Demand (POD) artwork as a ZIP and include its link in the PDF. Pass the configuration short code for the standard product being exported. Your script can generate a code for the selected options with utils.getShortcode.

Set up the getPdfContent callback before loading the embed. This example reads the product and selected options together, then generates a matching short code.

window.mimeeqAppConfig ??= {};
window.mimeeqAppConfig.pdf = {
...window.mimeeqAppConfig.pdf,
async getPdfContent() {
const { actions, observers, utils } = window.mimeeqApp;
const documentForPdf = document.implementation.createHTMLDocument('Artwork');
const heading = documentForPdf.createElement('h1');
heading.textContent = 'Artwork';
documentForPdf.body.append(heading);

const product = observers.product.mainProductData.getValue();
const configurationCode = observers.product.configurationCode.getValue();
if (!product || !actions.savePodFilesToMediaLibrary) {
documentForPdf.body.append('The artwork archive is unavailable.');
return documentForPdf.documentElement.outerHTML;
}

try {
const shortCode = await utils.getShortcode(product.productId, configurationCode);
const { fileName, url } = await actions.savePodFilesToMediaLibrary(shortCode);

const link = documentForPdf.createElement('a');
link.textContent = fileName;
link.href = url;
documentForPdf.body.append(link);
} catch (error) {
console.warn('Could not add the artwork archive to the PDF', error);
documentForPdf.body.append('The artwork archive is unavailable.');
}

return documentForPdf.documentElement.outerHTML;
},
};

The ZIP is named <shortCode>.zip and saved in _products/pod-files/ in the customer's Media Library. It counts toward the customer's storage limit. The action rejects when there is no POD artwork for the configuration or the archive cannot be saved. The example still creates the PDF in either case.