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
- Listen for
mimeeq-app-loadedondocument, then subscribe. Each observer emits{ newValue, oldValue }and sends its current value on subscribe. The callback re-renders from synchronousgetValue()snapshots. The panel enables actions oncestatus.firstRenderandstatus.settledare true. - Use
snapStatusesto 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. - Pass the full
ProductListItemfrommodular.componentstoactions.chooseProductToAdd(product). Some products can be placed immediately, including a first component or a free-moving item. Otherwise, watchchosenProductIdand wait untilsnapPlacementControls.productIdmatches it.chooseProductToAddresolves toundefinedon completion orfalsefor an invalid input or interrupted scene work. The observers show whether a placement choice is still active. - Render both
addandinsertcontrols and disable candidates markedunavailable. For an available add, calladdProductToSnappingPoint(instanceId, snapId). Omitting the third argument uses the current picker selection. For an available insert, callinsertProductAtSnap(target, productId)with the candidate's target and the chosen product ID. - Check the boolean returned by either placement action.
truemeans the add or insert committed. Onfalse, 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 withcancelOperations().
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
| Field | Type | Meaning |
|---|---|---|
| Top-level value | string | null | undefined | Chosen component's product ID. A missing value means there is no current selection for placement. |
window.mimeeqApp.observers.modular.snapStatuses
| Field | Type | Meaning |
|---|---|---|
| Top-level value | PlacedItemSnapStatus[] | null | null before modular data is loaded or for a standard product. [] for an empty modular scene. |
instanceId, productId | string | Which placed item owns the snaps and which component product it represents. |
snaps | SnapStatus[] | Authored snaps on the item. Empty when no snap definitions are available for it. |
snaps[].snapId, code | string | Mesh 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, hiddenByRule | boolean | null | Evaluated 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[].unavailableReasons | String array | Possible values are occupied, disabled, hiddenByRule, collision, conditionalRuleFailed, notEvaluated and targetSnapUnavailable. Empty when the snap evaluation reports no blocking reason. |
window.mimeeqApp.observers.modular.snapPlacementControls
| Field | Type | Meaning |
|---|---|---|
| Top-level value | SnapPlacementControls | null | null 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. |
productId | string | Chosen component for which the controls were evaluated. |
controls | Array | The 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[].sourceSnapIds | string[] | Matching snap IDs on the chosen product. An unavailable control can list authored matches that are currently hidden. |
controls[].unavailableReasons | String array | Possible values are sourceSnapHidden, targetSnapHidden, targetSnapUnavailable, conditionalRuleFailed, occupied and insertRestricted. Empty for an available candidate. |
Edge cases
- A saved joint can show
takenbefore snap evaluation. Wait for evaluation before treating anunknownsnap 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: falsefor 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.