Skip to main content

Build your own add and insert flow

Build a placement panel for a modular sofa. Use window.mimeeqApp.observers.modular.snapStatuses to show which ends are open, then use window.mimeeqApp.observers.modular.snapPlacementControls to show exactly where the chosen component can be added or inserted. The same joint can reject a normal add and allow an insert.

Complete example​

Paste this into an HTML page with one embed. Use a shortcode and template for a full modular product that renders inline. To try both actions, use a product range with compatible snaps and a joint that allows insertion between items. Start with a layout or choose a component that can start one. Keep the configurator out of replace mode while using this panel.

<mmq-embed short-code="YOUR_SHORT_CODE" template="YOUR_TEMPLATE" render-at-mount></mmq-embed>

<section aria-label="Modular placement">
<h2>Choose a component</h2>
<ul id="product-picker"></ul>
<button id="cancel-placement" type="button" disabled>Cancel placement</button>
<p id="placement-status" role="status">Opening the configurator…</p>
<h2>Snaps on placed items</h2>
<ul id="snap-statuses"></ul>
<h2>Placement spots</h2>
<ul id="placement-spots"></ul>
</section>

<script>
document.addEventListener(
'mimeeq-app-loaded',
() => {
const { observers, actions } = window.mimeeqApp;
const { firstRender, settled } = observers.status;
const { components, chosenProductId, sceneItems, snapStatuses, snapPlacementControls } =
observers.modular;
const picker = document.getElementById('product-picker');
const cancel = document.getElementById('cancel-placement');
const message = document.getElementById('placement-status');
const snaps = document.getElementById('snap-statuses');
const spots = document.getElementById('placement-spots');
if (!picker || !(cancel instanceof HTMLButtonElement) || !message || !snaps || !spots) return;
let pending = false;
let feedback = '';

const reasonLabels = {
occupied: 'Already connected or attached',
disabled: 'Snap disabled',
hiddenByRule: 'Hidden by a rule',
collision: 'Blocked by a collision',
conditionalRuleFailed: 'A placement rule is not satisfied',
notEvaluated: 'Waiting for snap evaluation',
targetSnapUnavailable: 'Target snap unavailable',
sourceSnapHidden: 'The matching snap on the chosen product is hidden',
targetSnapHidden: 'The snap on the placed item is hidden',
insertRestricted: 'This joint does not allow insertion',
};

function listItem(content) {
const result = document.createElement('li');
result.append(content);
return result;
}

function button(label, disabled, onClick) {
const result = document.createElement('button');
result.type = 'button';
result.textContent = label;
result.disabled = disabled;
result.addEventListener('click', onClick);
return result;
}

function canAct() {
return firstRender.getValue() && settled.getValue();
}

async function run(operation, failureMessage) {
if (pending || !canAct()) return;
pending = true;
feedback = '';
render();
try {
if ((await operation()) === false) feedback = failureMessage;
} catch (error) {
feedback = failureMessage;
console.error(error);
} finally {
pending = false;
render();
}
}

const render = () => {
const chosen = chosenProductId.getValue();
const placement = snapPlacementControls.getValue();
const items = sceneItems.getValue() ?? {};
const disabled = pending || !canAct();
const currentPlacement = chosen && placement?.productId === chosen ? placement : null;

function itemLabel(instanceId) {
const item = items[instanceId];
return item ? `Item ${item.positionOrder} (${item.productName})` : instanceId;
}

picker.replaceChildren(
...(components.getValue() ?? []).map((product) => {
const atLimit = product.isQuantityLimitReached;
const label = atLimit
? `${product.label} — ${product.disabledTooltipMessage || 'Quantity limit reached'}`
: product.label;
return listItem(
button(label, disabled || !!product.isDisabled || !!atLimit, () => {
void run(
() => actions.chooseProductToAdd(product),
'Could not choose this component.',
);
}),
);
}),
);
cancel.disabled = disabled || !chosen;
const placedSnaps = snapStatuses.getValue();
snaps.replaceChildren(
...(placedSnaps ?? []).flatMap(({ instanceId, snaps: itemSnaps }) =>
itemSnaps.map(({ code, snapId, occupancy, unavailableReasons }) => {
const reasons = unavailableReasons.map((reason) => reasonLabels[reason]).join(', ');
return listItem(
`${itemLabel(instanceId)}, ${code || snapId}: ${occupancy}${reasons ? ` — ${reasons}` : ''}`,
);
}),
),
);

if (!firstRender.getValue()) {
message.textContent = 'Waiting for the scene…';
} else if (pending) {
message.textContent = 'Updating placement…';
} else if (feedback) {
message.textContent = feedback;
} else if (chosen && !currentPlacement) {
message.textContent = 'Waiting for placement spots…';
} else if (!chosen) {
message.textContent = 'Choose a component to see its placement spots.';
} else {
message.textContent = currentPlacement?.controls.some(
({ availability }) => availability === 'available',
)
? 'Choose a placement spot.'
: 'No placement spots are available for this component.';
}

spots.replaceChildren(
...(currentPlacement?.controls ?? []).map((control) => {
const { target, type, availability, unavailableReasons } = control;
const snap = placedSnaps
?.find(({ instanceId }) => instanceId === target.instanceId)
?.snaps.find(({ snapId }) => snapId === target.snapId);
const label = `${type === 'insert' ? 'Insert at' : 'Add at'} ${itemLabel(target.instanceId)}, ${snap?.code || target.snapId}`;
const reasons = unavailableReasons.map((reason) => reasonLabels[reason]).join(', ');
return listItem(
button(
reasons ? `${label} — ${reasons}` : label,
disabled || availability !== 'available',
() => {
void run(async () => {
const latest = snapPlacementControls.getValue();
if (
!chosen ||
chosenProductId.getValue() !== chosen ||
latest?.productId !== chosen ||
!latest.controls.some(
(candidate) =>
candidate.type === type &&
candidate.target.instanceId === target.instanceId &&
candidate.target.snapId === target.snapId &&
candidate.availability === 'available',
)
) {
return false;
}
if (type === 'insert') {
return actions.insertProductAtSnap(target, latest.productId);
}
return actions.addProductToSnappingPoint(target.instanceId, target.snapId);
}, 'This spot is no longer available. Choose another spot or component.');
},
),
);
}),
);
};

cancel.addEventListener('click', () => {
void run(() => actions.cancelOperations(), 'Could not cancel placement.');
});

const subscriptions = [
...[firstRender, settled].map((observer) => observer.subscribe(render)),
components.subscribe(render),
chosenProductId.subscribe(render),
sceneItems.subscribe(render),
snapStatuses.subscribe(render),
snapPlacementControls.subscribe(render),
];
window.addEventListener('pagehide', (event) => {
if (!event.persisted) subscriptions.forEach((subscription) => subscription.unsubscribe());
});
},
{ once: true },
);
</script>
<script src="https://cdn.mimeeq.com/read_models/embed/app-embed.js" async></script>

How it works​

  1. Listen for mimeeq-app-loaded on document, then subscribe. Each observer emits { newValue, oldValue } and sends its current value on subscribe. The callback re-renders from synchronous getValue() snapshots. The panel enables actions once status.firstRender and status.settled are true.
  2. Use snapStatuses to describe each placed snap. A free snap with no unavailable reasons is an open end in the layout. The chosen product still needs a compatible candidate there. Use the authored snap code as a label and the mesh ID for actions.
  3. Pass the full ProductListItem from modular.components to actions.chooseProductToAdd(product). Some products can be placed immediately, including a first component or a free-moving item. Otherwise, watch chosenProductId and wait until snapPlacementControls.productId matches it. chooseProductToAdd resolves to undefined on completion or false for an invalid input or interrupted scene work. The observers show whether a placement choice is still active.
  4. Render both add and insert controls and disable candidates marked unavailable. For an available add, call addProductToSnappingPoint(instanceId, snapId). Omitting the third argument uses the current picker selection. For an available insert, call insertProductAtSnap(target, productId) with the candidate's target and the chosen product ID.
  5. Check the boolean returned by either placement action. true means the add or insert committed. On false, let the user choose from the latest candidates. A candidate can become stale between render and click, or while the action is running. Cancel the active placement with cancelOperations().

See Read the scene and the catalog for the status, modular.components and modular.sceneItems payloads used here.

Observer payloads​

window.mimeeqApp.observers.modular.chosenProductId​

FieldTypeMeaning
Top-level valuestring | null | undefinedChosen component's product ID. A missing value means there is no current selection for placement.

window.mimeeqApp.observers.modular.snapStatuses​

FieldTypeMeaning
Top-level valuePlacedItemSnapStatus[] | nullnull before modular data is loaded or for a standard product. [] for an empty modular scene.
instanceId, productIdstringWhich placed item owns the snaps and which component product it represents.
snapsSnapStatus[]Authored snaps on the item. Empty when no snap definitions are available for it.
snaps[].snapId, codestringMesh ID and authored snap code.
snaps[].occupancy'free' | 'taken' | 'unknown'taken means a connection or active attachment exists. free means an evaluated snap has neither. unknown means evaluation is missing and there is no known connection or attachment.
snaps[].connections{ instanceId: string; snapId: string }[]Other placed snaps this snap is connected to. Empty when there are no such connections.
snaps[].enabled, hiddenByRuleboolean | nullEvaluated enabled and visibility flags. null means the snap has no current evaluation.
snaps[].welding, magnetic{ active: false } | { active: true; instanceId: string | null }Attachment status. An active attachment can lack an instance ID.
snaps[].unavailableReasonsString arrayPossible values are occupied, disabled, hiddenByRule, collision, conditionalRuleFailed, notEvaluated and targetSnapUnavailable. Empty when the snap evaluation reports no blocking reason.

window.mimeeqApp.observers.modular.snapPlacementControls​

FieldTypeMeaning
Top-level valueSnapPlacementControls | nullnull with no chosen product, while candidates are being calculated, or while the canvas is unmounted. Use chosenProductId and scene readiness to tell these states apart.
productIdstringChosen component for which the controls were evaluated.
controlsArrayThe evaluated candidates. An empty array means the calculation produced no controls.
controls[].target{ instanceId: string; snapId: string }Target on the existing scene item.
controls[].type'add' | 'insert'Add at a snap or insert between previously connected items.
controls[].availability'available' | 'unavailable'Whether the calculation found a valid placement for this control.
controls[].sourceSnapIdsstring[]Matching snap IDs on the chosen product. An unavailable control can list authored matches that are currently hidden.
controls[].unavailableReasonsString arrayPossible values are sourceSnapHidden, targetSnapHidden, targetSnapUnavailable, conditionalRuleFailed, occupied and insertRestricted. Empty for an available candidate.

Edge cases​

  • A saved joint can show taken before snap evaluation. Wait for evaluation before treating an unknown snap as open.
  • A visually open end can reject a specific product. Display the reasons that came with its evaluated control. Some incompatible snaps produce no candidate at all.
  • Keep the default force: false for normal adds. An occupied joint uses the separate insert action when an insert candidate is available. The chooser can replace a selected item if replace mode is already active, so keep add and replace controls in separate modes.

What this replaces​

Custom sofa builders have used patterns in snap codes and scanned connection lists to guess open ends and valid spots. The status observer reports occupancy, connections and evaluated blockers directly. Use placement controls to decide whether the chosen product can attach at an end or go between two items. If your design needs a label such as “left,” use an authored label or the layout's orientation.

For the component list and ordering used here, see Read the scene and the catalog.