574 KiB
/* LayerManager X — generated bundle SPDX-License-Identifier: MIT Source project: obsidian-excalidraw-layer-manager Source repo: https://github.com/tryingET/obsidian-plugins/tree/main/packages/obsidian-excalidraw-layer-manager Do not edit this file directly. Edit src/* and run npm run build. */ "use strict"; (() => { // src/model/settings.ts var DEFAULT_SETTINGS = { groupFreedraw: true, debug: false };
// src/adapter/nativeStagingIsolation.ts var withIsolatedNativeStaging = (ea2, prepareCommit) => { const previousElements = ea2.elementsDict; if (!previousElements) return prepareCommit(() => true); const previousImages = ea2.imagesDict; const elements = {}; const images = {}; ea2.elementsDict = elements; if (previousImages) ea2.imagesDict = images; try { return prepareCommit( () => ea2.elementsDict === elements && (!previousImages || ea2.imagesDict === images) ); } finally { if (ea2.elementsDict === elements) ea2.elementsDict = previousElements; if (previousImages && ea2.imagesDict === images) ea2.imagesDict = previousImages; } };
// src/adapter/excalidrawAdapter.ts
var normalizeElementType = (rawType) => {
switch (rawType) {
case "rectangle":
case "ellipse":
case "diamond":
case "line":
case "arrow":
case "freedraw":
case "text":
case "image":
case "frame":
return rawType;
default:
return "unknown";
}
};
var normalizeElement = (element, zIndex) => {
const normalized = {
id: element.id,
type: normalizeElementType(element.type),
zIndex,
groupIds: Array.isArray(element.groupIds) ? element.groupIds : [],
frameId: element.frameId ?? null,
containerId: element.containerId ?? null,
opacity: typeof element.opacity === "number" ? element.opacity : 100,
locked: element.locked === true,
isDeleted: element.isDeleted === true,
customData: element.customData ?? {}
};
if (typeof element.name === "string") {
normalized.name = element.name;
}
if (typeof element.text === "string") {
normalized.text = element.text;
}
return normalized;
};
var readSettings = (ea2) => {
const raw = ea2.getScriptSettings?.();
const groupFreedrawValue = raw?.["group_freedraw"]?.value;
const debugValue = raw?.["debug"]?.value;
return {
groupFreedraw: typeof groupFreedrawValue === "boolean" ? groupFreedrawValue : DEFAULT_SETTINGS.groupFreedraw,
debug: typeof debugValue === "boolean" ? debugValue : DEFAULT_SETTINGS.debug
};
};
var hasExplicitTargetViewProperty = (ea2) => {
return Object.hasOwn(ea2, "targetView");
};
var getCurrentTargetView = (ea2) => {
return ea2.targetView ?? null;
};
var isUsableTargetView = (value) => {
if (!value || typeof value !== "object") {
return false;
}
const record = value;
if ("_loaded" in record) {
return record["_loaded"] === true;
}
return true;
};
var invokeSetView = (ea2, viewArg, reveal) => {
const setView = ea2.setView;
if (!setView) {
return null;
}
return setView.call(ea2, viewArg, reveal);
};
var ensureTargetView = (ea2) => {
if (isUsableTargetView(getCurrentTargetView(ea2))) {
return true;
}
if (!ea2.setView) {
return !hasExplicitTargetViewProperty(ea2);
}
const strategies = [
{ viewArg: "active", reveal: false },
{ viewArg: void 0, reveal: false },
{ viewArg: "active", reveal: true },
{ viewArg: void 0, reveal: true }
];
for (const strategy of strategies) {
try {
const resolved = invokeSetView(ea2, strategy.viewArg, strategy.reveal);
if (isUsableTargetView(resolved) || isUsableTargetView(getCurrentTargetView(ea2))) {
return true;
}
} catch {
}
}
return !hasExplicitTargetViewProperty(ea2) || isUsableTargetView(getCurrentTargetView(ea2));
};
var readViewElements = (ea2) => {
if (!ensureTargetView(ea2)) {
return [];
}
try {
return ea2.getViewElements?.() ?? [];
} catch {
return [];
}
};
var readViewSelectedElements = (ea2) => {
if (!ensureTargetView(ea2)) {
return [];
}
try {
return ea2.getViewSelectedElements?.() ?? [];
} catch {
return [];
}
};
var snapshotVersionCounter = 0;
var readSnapshot = (ea2) => {
const rawElements = readViewElements(ea2);
const selected = readViewSelectedElements(ea2);
snapshotVersionCounter += 1;
return {
version: snapshotVersionCounter,
elements: rawElements.map((element, index) => normalizeElement(element, index)),
selectedIds: new Set(selected.map((element) => element.id)),
settings: readSettings(ea2)
};
};
var hasDuplicateIds = (ids) => {
return new Set(ids).size !== ids.length;
};
var isFullPermutation = (orderedIds, currentIds) => {
if (orderedIds.length !== currentIds.size) {
return false;
}
const seen = /* @PURE / new Set();
for (const id of orderedIds) {
if (seen.has(id)) {
return false;
}
if (!currentIds.has(id)) {
return false;
}
seen.add(id);
}
return seen.size === currentIds.size;
};
var capabilityCache = / @PURE / new WeakMap();
var probeCapabilities = (ea2) => {
const cached = capabilityCache.get(ea2);
if (cached) {
return cached;
}
const result = {
legacy: !!ea2.copyViewElementsToEAforEditing && !!ea2.getElement && !!ea2.addElementsToView,
updateScene: !!ea2.getExcalidrawAPI?.()?.updateScene
};
capabilityCache.set(ea2, result);
return result;
};
var hasLegacyElementMutationCapabilities = (ea2) => {
return probeCapabilities(ea2).legacy;
};
var hasUpdateSceneCapability = (ea2) => {
return probeCapabilities(ea2).updateScene;
};
var hasElementMutationCapability = (ea2) => {
const caps = probeCapabilities(ea2);
return caps.legacy || caps.updateScene;
};
var preflightPatch = (ea2, patch) => {
ensureTargetView(ea2);
const hasElementMutations = patch.elementPatches.length > 0;
const hasReorderMutation = !!patch.reorder;
const requiresMutationCapabilities = hasElementMutations || hasReorderMutation;
if (requiresMutationCapabilities && !ea2.getViewElements) {
return {
ok: false,
outcome: {
status: "capabilityMissing",
reason: "Missing getViewElements capability for mutation preflight."
}
};
}
const currentElements = readViewElements(ea2);
const currentIds = new Set(currentElements.map((element) => element.id));
if (hasElementMutations) {
if (!hasElementMutationCapability(ea2)) {
return {
ok: false,
outcome: {
status: "capabilityMissing",
reason: "Missing element-mutation capabilities."
}
};
}
const patchIds = patch.elementPatches.map((entry) => entry.id);
if (hasDuplicateIds(patchIds)) {
return {
ok: false,
outcome: {
status: "preflightFailed",
reason: "Duplicate elementPatch IDs are invalid."
}
};
}
for (const id of patchIds) {
if (!currentIds.has(id)) {
return {
ok: false,
outcome: {
status: "preflightFailed",
reason: Element patch target missing in current scene: ${id}
}
};
}
}
}
if (hasReorderMutation) {
if (!hasUpdateSceneCapability(ea2)) {
return {
ok: false,
outcome: {
status: "capabilityMissing",
reason: "Missing reorder capability (updateScene)."
}
};
}
if (!patch.reorder || !isFullPermutation(patch.reorder.orderedElementIds, currentIds)) {
return {
ok: false,
outcome: {
status: "preflightFailed",
reason: "Reorder payload must be a full permutation of current scene IDs."
}
};
}
}
return { ok: true };
};
var patchElementProperties = (target, elementPatch) => {
const { set } = elementPatch;
if (set.groupIds !== void 0) target.groupIds = [...set.groupIds];
if (set.frameId !== void 0) target.frameId = set.frameId;
if (set.opacity !== void 0) target.opacity = set.opacity;
if (set.locked !== void 0) target.locked = set.locked;
if (set.isDeleted !== void 0) target.isDeleted = set.isDeleted;
if (set.customData !== void 0) {
target.customData = { ...set.customData };
}
if (set.name !== void 0 && target.type === "frame") target.name = set.name;
};
var applyElementPatchesViaLegacyEditing = async (ea2, patch, canExecute) => {
const { copyViewElementsToEAforEditing, getElement, addElementsToView } = ea2;
if (!copyViewElementsToEAforEditing || !getElement || !addElementsToView) {
return false;
}
ensureTargetView(ea2);
const currentElements = readViewElements(ea2);
const currentById = new Map(currentElements.map((element) => [element.id, element]));
const targets = [];
for (const elementPatch of patch.elementPatches) {
const target = currentById.get(elementPatch.id);
if (!target) {
return false;
}
targets.push(target);
}
if (!canExecute()) return false;
try {
const commit = withIsolatedNativeStaging(ea2, (ownsStaging) => {
copyViewElementsToEAforEditing.call(ea2, targets);
if (!canExecute() || !ownsStaging()) return false;
const editableById = / @PURE */ new Map();
for (const elementPatch of patch.elementPatches) {
const editable = getElement.call(ea2, elementPatch.id);
if (!editable) return false;
editableById.set(elementPatch.id, editable);
}
for (const elementPatch of patch.elementPatches) {
const editable = editableById.get(elementPatch.id);
if (!editable || !canExecute() || !ownsStaging()) return false;
patchElementProperties(editable, elementPatch);
}
if (!canExecute() || !ownsStaging()) return false;
return addElementsToView.call(ea2, false, false);
});
if (commit === false) return false;
await commit;
} catch {
return false;
}
return true;
};
var cloneElementForSceneMutation = (element) => {
const nextElement = {
...element
};
if (Array.isArray(element.groupIds)) {
nextElement.groupIds = [...element.groupIds];
}
if (element.customData) {
nextElement.customData = { ...element.customData };
}
return nextElement;
};
var buildNextElementsForUpdateScene = (current, patch) => {
const patchById = new Map(patch.elementPatches.map((entry) => [entry.id, entry]));
let appliedPatchCount = 0;
const patchedElements = current.map((element) => {
const nextElement = cloneElementForSceneMutation(element);
const elementPatch = patchById.get(element.id);
if (!elementPatch) {
return nextElement;
}
appliedPatchCount += 1;
patchElementProperties(nextElement, elementPatch);
return nextElement;
});
if (appliedPatchCount !== patch.elementPatches.length) {
return null;
}
if (!patch.reorder) {
return patchedElements;
}
const byId = new Map(patchedElements.map((element) => [element.id, element]));
const orderedElements = patch.reorder.orderedElementIds.map((id) => byId.get(id)).filter((element) => Boolean(element));
if (orderedElements.length !== patchedElements.length) {
return null;
}
return orderedElements;
};
var applyPatchViaUpdateScene = (ea2, patch, canExecute) => {
ensureTargetView(ea2);
const api = ea2.getExcalidrawAPI?.();
const current = readViewElements(ea2);
if (!api?.updateScene) {
return false;
}
const nextElements = buildNextElementsForUpdateScene(current, patch);
if (!nextElements) {
return false;
}
if (!canExecute()) return false;
try {
api.updateScene({ elements: [...nextElements] });
return true;
} catch {
return false;
}
};
var applyElementPatchesViaUpdateScene = (ea2, patch, canExecute) => {
return applyPatchViaUpdateScene(ea2, patch, canExecute);
};
var applyElementPatches = async (ea2, patch, canExecute) => {
if (patch.elementPatches.length === 0) {
return {
ok: true
};
}
if (hasLegacyElementMutationCapabilities(ea2)) {
const legacyApplied = await applyElementPatchesViaLegacyEditing(ea2, patch, canExecute);
if (!canExecute()) return { ok: false };
if (legacyApplied) {
return {
ok: true
};
}
}
if (hasUpdateSceneCapability(ea2)) {
return {
ok: applyElementPatchesViaUpdateScene(ea2, patch, canExecute)
};
}
return {
ok: false
};
};
var applyPatch = async (ea2, patch, canExecute = () => true) => {
const expired = {
status: "capabilityMissing",
reason: "Scene ownership changed during execution."
};
if (!canExecute()) return expired;
const preflight = preflightPatch(ea2, patch);
if (!canExecute()) return expired;
if (!preflight.ok) {
return preflight.outcome ?? {
status: "preflightFailed",
reason: "Patch preflight failed."
};
}
if (patch.reorder) {
const patchApplied = applyPatchViaUpdateScene(ea2, patch, canExecute);
if (!canExecute()) return expired;
if (!patchApplied) {
return {
status: "preflightFailed",
reason: "Patch apply failed before commit due to scene mismatch."
};
}
} else {
const elementApply = await applyElementPatches(ea2, patch, canExecute);
if (!canExecute()) return expired;
if (!elementApply.ok) {
return {
status: "preflightFailed",
reason: "Element patch apply failed due to scene mismatch."
};
}
}
if (!canExecute()) return expired;
if (patch.selectIds && ea2.selectElementsInView) {
ea2.selectElementsInView([...patch.selectIds]);
}
return {
status: "applied"
};
};
// src/model/lmxMetadata.ts var asRecord = (value) => { if (!value || typeof value !== "object" || Array.isArray(value)) { return null; } return value; }; var normalizeStoredLabel = (value) => { if (typeof value !== "string") { return null; } const trimmed = value.trim(); return trimmed.length > 0 ? trimmed : null; }; var getLmxRecord = (customData) => { return asRecord(customData["lmx"]); }; var buildNextLmxRecord = (customData) => { return { ...getLmxRecord(customData) ?? {} }; }; var readLmxElementLabel = (customData) => { return normalizeStoredLabel(getLmxRecord(customData)?.["label"]); }; var readLmxGroupLabel = (customData, groupId) => { const lmxRecord = getLmxRecord(customData); if (!lmxRecord) { return null; } const groupLabels = asRecord(lmxRecord["groupLabels"]); return normalizeStoredLabel(groupLabels?.[groupId]); }; var withLmxElementLabel = (customData, label) => { const nextCustomData = { ...customData }; const nextLmxRecord = buildNextLmxRecord(customData); nextLmxRecord["label"] = label; nextCustomData.lmx = nextLmxRecord; return nextCustomData; }; var withLmxGroupLabel = (customData, groupId, label) => { const nextCustomData = { ...customData }; const nextLmxRecord = buildNextLmxRecord(customData); const nextGroupLabels = { ...asRecord(nextLmxRecord["groupLabels"]) ?? {}, [groupId]: label }; nextLmxRecord["groupLabels"] = nextGroupLabels; nextCustomData.lmx = nextLmxRecord; return nextCustomData; };
// src/model/tree.ts var resolveRepresentativeElementId = (node) => { return node.primaryElementId; }; var resolveFrameRowElementId = (node) => { return node.type === "frame" ? resolveRepresentativeElementId(node) : null; };
// src/domain/treeBuilder.ts
var makeNodeId = (prefix, id) => ${prefix}:${id};
var normalizeSearchSourceText = (value) => {
return value.replaceAll("\n", " ").trim();
};
var normalizeLabelText = (value, maxLength = 24) => {
const normalized = normalizeSearchSourceText(value);
if (normalized.length <= maxLength) {
return normalized;
}
return ${normalized.slice(0, maxLength)}…;
};
var normalizeExplicitLabel = (value) => {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
};
var collectBoundTextContainerSearchFragments = (element, indexes) => {
if (element.type === "text") {
return [];
}
const fragments = [];
const boundTextEntries = indexes.boundTextByContainer.get(element.id) ?? [];
for (const entry of boundTextEntries) {
if (entry.type !== "text" || !entry.text) {
continue;
}
const fragment = normalizeSearchSourceText(entry.text);
if (fragment.length > 0) {
fragments.push(fragment);
}
}
return fragments;
};
var getBoundTextContainerLabel = (element, indexes) => {
const [firstFragment] = collectBoundTextContainerSearchFragments(element, indexes);
return firstFragment ? normalizeLabelText(firstFragment) : null;
};
var joinUniqueSearchFragments = (fragments) => {
const normalizedFragments = [];
const seen = /* @PURE / new Set();
for (const fragment of fragments) {
if (typeof fragment !== "string") {
continue;
}
const normalized = normalizeSearchSourceText(fragment);
if (normalized.length === 0) {
continue;
}
const fingerprint = normalized.toLowerCase();
if (seen.has(fingerprint)) {
continue;
}
seen.add(fingerprint);
normalizedFragments.push(normalized);
}
return normalizedFragments.length > 0 ? normalizedFragments.join(" ") : void 0;
};
var getElementSearchText = (element, indexes) => {
return joinUniqueSearchFragments([
readLmxElementLabel(element.customData),
normalizeExplicitLabel(element.name),
...collectBoundTextContainerSearchFragments(element, indexes),
element.type === "text" ? element.text : void 0
]);
};
var getElementLabel = (element, indexes) => {
const metadataLabel = readLmxElementLabel(element.customData);
const explicitName = normalizeExplicitLabel(element.name);
if (element.type === "frame") {
if (explicitName) {
return explicitName;
}
if (metadataLabel) {
return metadataLabel;
}
} else {
if (metadataLabel) {
return metadataLabel;
}
if (explicitName) {
return explicitName;
}
}
const boundTextLabel = getBoundTextContainerLabel(element, indexes);
if (boundTextLabel) {
return boundTextLabel;
}
if (element.type === "text" && element.text) {
return normalizeLabelText(element.text);
}
return element.type;
};
var isBoundTextWithExistingContainer = (element, indexes) => {
return element.type === "text" && !!element.containerId && indexes.byId.has(element.containerId);
};
var getOuterGroupId = (element) => {
if (element.groupIds.length === 0) {
return null;
}
return element.groupIds[element.groupIds.length - 1] ?? null;
};
var getPathInsideOuter = (element, outerGroupId) => {
const index = element.groupIds.lastIndexOf(outerGroupId);
if (index <= 0) {
return [];
}
return [...element.groupIds.slice(0, index)].reverse();
};
var appendUniqueElementIds = (target, seen, values) => {
for (const value of values) {
if (seen.has(value)) {
continue;
}
seen.add(value);
target.push(value);
}
};
var makeElementNode = (element, indexes, expandedNodeIds) => {
const extras = indexes.boundTextByContainer.get(element.id) ?? [];
const elementIds = [];
const seenElementIds = / @PURE / new Set();
appendUniqueElementIds(elementIds, seenElementIds, [element.id]);
for (const entry of extras) {
appendUniqueElementIds(elementIds, seenElementIds, [entry.id]);
}
const nodeId = makeNodeId("el", element.id);
const searchText = getElementSearchText(element, indexes);
return {
id: nodeId,
type: "element",
elementIds,
primaryElementId: element.id,
children: [],
canExpand: false,
isExpanded: expandedNodeIds.has(nodeId),
groupId: null,
frameId: element.frameId,
label: getElementLabel(element, indexes),
...searchText ? { searchText } : {}
};
};
var isUngroupedFreedraw = (element) => {
return element.type === "freedraw" && element.groupIds.length === 0;
};
var makeFreedrawBucketNode = (elements) => {
const elementIds = elements.map((element) => element.id);
const primaryElementId = elements[0]?.id ?? "freedraw";
const frameId = elements[0]?.frameId ?? null;
const stableBucketKey = [...elementIds].sort().join("|");
const bucketId = makeNodeId("freedraw", stableBucketKey);
return {
id: bucketId,
type: "freedrawBucket",
elementIds,
primaryElementId,
children: [],
canExpand: false,
isExpanded: false,
groupId: null,
frameId,
label: freedraw (${elementIds.length})
};
};
var createMutableGroupNode = (input) => ({
kind: "mutableGroup",
id: input.id,
groupId: input.groupId,
frameId: input.frameId,
label: input.groupId,
isExpanded: input.expandedNodeIds.has(input.id),
children: []
});
var isMutableGroupNode = (node) => {
return "kind" in node && node.kind === "mutableGroup";
};
var readGroupLabelFromMembers = (groupId, primaryElementId, elementIds, indexes) => {
const candidateIds = [primaryElementId, ...elementIds.filter((id) => id !== primaryElementId)];
for (const elementId of candidateIds) {
const candidate = indexes.byId.get(elementId);
if (!candidate) {
continue;
}
const metadataLabel = readLmxGroupLabel(candidate.customData, groupId);
if (metadataLabel) {
return metadataLabel;
}
}
return null;
};
var resolveGroupLabel = (defaultLabel, groupId, primaryElementId, elementIds, indexes) => {
const metadataLabel = readGroupLabelFromMembers(groupId, primaryElementId, elementIds, indexes);
if (metadataLabel) {
return metadataLabel;
}
const representative = indexes.byId.get(primaryElementId);
const fallbackName = normalizeExplicitLabel(representative?.name);
if (fallbackName) {
return fallbackName;
}
return defaultLabel;
};
var finalizeMutableGroupNode = (node, indexes) => {
const finalizedChildren = [];
const elementIds = [];
const seenElementIds = / @PURE / new Set();
let primaryElementId = node.groupId;
for (const child of node.children) {
const finalized = isMutableGroupNode(child) ? finalizeMutableGroupNode(child, indexes) : child;
finalizedChildren.push(finalized);
if (primaryElementId === node.groupId) {
primaryElementId = finalized.primaryElementId;
}
appendUniqueElementIds(elementIds, seenElementIds, finalized.elementIds);
}
return {
id: node.id,
type: "group",
elementIds,
primaryElementId,
children: finalizedChildren,
canExpand: finalizedChildren.length > 0,
isExpanded: node.isExpanded,
groupId: node.groupId,
frameId: node.frameId,
label: resolveGroupLabel(node.label, node.groupId, primaryElementId, elementIds, indexes)
};
};
var getContainerFrameId = (members) => {
let frameId;
for (const member of members) {
if (frameId === void 0) {
frameId = member.frameId;
continue;
}
if (frameId !== member.frameId) {
return null;
}
}
return frameId ?? null;
};
var buildMaxGroupNode = (outerGroupId, members, context, indexes, zIndexById) => {
const containerFrameId = getContainerFrameId(members);
const rootId = makeNodeId("group", outerGroupId);
const root = createMutableGroupNode({
id: rootId,
groupId: outerGroupId,
frameId: containerFrameId,
expandedNodeIds: context.expandedNodeIds
});
const groupsById = / @PURE / new Map();
groupsById.set(rootId, root);
const sortedMembers = [...members].sort((left, right) => {
const leftZ = zIndexById.get(left.id) ?? left.zIndex;
const rightZ = zIndexById.get(right.id) ?? right.zIndex;
return rightZ - leftZ;
});
for (const member of sortedMembers) {
if (isBoundTextWithExistingContainer(member, indexes)) {
continue;
}
const pathInsideOuter = getPathInsideOuter(member, outerGroupId);
let parent = root;
let pathPrefix = outerGroupId;
for (const groupId of pathInsideOuter) {
pathPrefix = ${pathPrefix}/${groupId};
const childId = makeNodeId("group", pathPrefix);
let child = groupsById.get(childId);
if (!child) {
child = createMutableGroupNode({
id: childId,
groupId,
frameId: containerFrameId,
expandedNodeIds: context.expandedNodeIds
});
groupsById.set(childId, child);
parent.children.push(child);
}
parent = child;
}
parent.children.push(makeElementNode(member, indexes, context.expandedNodeIds));
}
const finalized = finalizeMutableGroupNode(root, indexes);
if (finalized.elementIds.length === 0) {
return null;
}
return finalized;
};
var makeFrameNode = (frame, childNodes, expandedNodeIds, indexes) => {
const nodeId = makeNodeId("frame", frame.id);
const isExpanded = expandedNodeIds.has(nodeId);
const elementIds = [frame.id];
const seenElementIds = new Set(elementIds);
for (const child of childNodes) {
appendUniqueElementIds(elementIds, seenElementIds, child.elementIds);
}
const searchText = getElementSearchText(frame, indexes);
return {
id: nodeId,
type: "frame",
elementIds,
primaryElementId: frame.id,
children: [...childNodes],
canExpand: childNodes.length > 0,
isExpanded,
groupId: null,
frameId: null,
label: getElementLabel(frame, indexes),
...searchText ? { searchText } : {}
};
};
var buildLayerTree = (context, indexes) => {
const ordered = context.elements.map((element, inputIndex) => ({ element, inputIndex })).sort((left, right) => {
if (left.element.zIndex === right.element.zIndex) {
return left.inputIndex - right.inputIndex;
}
return left.element.zIndex - right.element.zIndex;
}).map((entry) => entry.element);
const zIndexById = / @PURE / new Map();
for (let index = 0; index < ordered.length; index += 1) {
const element = ordered[index];
if (!element) {
continue;
}
zIndexById.set(element.id, index);
}
const maxGroupByElementId = / @PURE / new Map();
const maxGroupMembers = / @PURE / new Map();
for (const element of ordered) {
if (element.type === "frame") {
continue;
}
const outerGroupId = getOuterGroupId(element);
if (!outerGroupId) {
continue;
}
maxGroupByElementId.set(element.id, outerGroupId);
const existingMembers = maxGroupMembers.get(outerGroupId);
if (existingMembers) {
existingMembers.push(element);
continue;
}
maxGroupMembers.set(outerGroupId, [element]);
}
const frameBuckets = / @PURE / new Map();
for (const element of ordered) {
if (element.type !== "frame") {
continue;
}
frameBuckets.set(element.id, {
frame: element,
children: []
});
}
const processedIds = / @PURE */ new Set();
const topLevelEntries = [];
const placeNode = (node) => {
if (node.type === "group") {
if (node.frameId && frameBuckets.has(node.frameId)) {
frameBuckets.get(node.frameId)?.children.push(node);
return;
}
topLevelEntries.push({ kind: "node", node });
return;
}
const representative = indexes.byId.get(resolveRepresentativeElementId(node));
const representativeFrameId = representative?.frameId ?? node.frameId;
if (representativeFrameId && frameBuckets.has(representativeFrameId)) {
frameBuckets.get(representativeFrameId)?.children.push(node);
return;
}
topLevelEntries.push({ kind: "node", node });
};
for (let index = ordered.length - 1; index >= 0; index -= 1) {
const element = ordered[index];
if (!element || processedIds.has(element.id)) {
continue;
}
if (isBoundTextWithExistingContainer(element, indexes)) {
processedIds.add(element.id);
continue;
}
if (element.type === "frame") {
processedIds.add(element.id);
if (frameBuckets.has(element.id)) {
topLevelEntries.push({
kind: "frame",
frameId: element.id
});
}
continue;
}
const outerGroupId = maxGroupByElementId.get(element.id);
if (outerGroupId) {
const members = maxGroupMembers.get(outerGroupId) ?? [];
for (const member of members) {
processedIds.add(member.id);
}
const groupNode = buildMaxGroupNode(outerGroupId, members, context, indexes, zIndexById);
if (groupNode) {
placeNode(groupNode);
}
continue;
}
if (context.groupFreedraw && isUngroupedFreedraw(element)) {
const bucketMembers = [];
for (let cursor = index; cursor >= 0; cursor -= 1) {
const candidate = ordered[cursor];
if (!candidate || processedIds.has(candidate.id)) {
break;
}
if (!isUngroupedFreedraw(candidate)) {
break;
}
if (candidate.frameId !== element.frameId) {
break;
}
bucketMembers.push(candidate);
}
for (const member of bucketMembers) {
processedIds.add(member.id);
}
if (bucketMembers.length > 0) {
placeNode(makeFreedrawBucketNode(bucketMembers));
}
continue;
}
processedIds.add(element.id);
placeNode(makeElementNode(element, indexes, context.expandedNodeIds));
}
const topLevelNodes = [];
for (const entry of topLevelEntries) {
if (entry.kind === "frame") {
const bucket = frameBuckets.get(entry.frameId);
if (!bucket) {
continue;
}
topLevelNodes.push(
makeFrameNode(bucket.frame, bucket.children, context.expandedNodeIds, indexes)
);
continue;
}
topLevelNodes.push(entry.node);
}
return topLevelNodes;
};
// src/model/indexes.ts var pushMapArray = (map, key, value) => { const current = map.get(key); if (current) { current.push(value); return; } map.set(key, [value]); }; var isBoundText = (element) => { return element.type === "text" && typeof element.containerId === "string"; }; var buildSceneIndexes = (snapshot) => { const byId = /* @PURE / new Map(); const boundTextByContainer = / @PURE / new Map(); const elementsByFrameId = / @PURE / new Map(); const elementsByGroupId = / @PURE */ new Map(); for (const element of snapshot.elements) { byId.set(element.id, element); if (isBoundText(element) && element.containerId) { pushMapArray(boundTextByContainer, element.containerId, element); } pushMapArray(elementsByFrameId, element.frameId, element); for (const groupId of element.groupIds) { pushMapArray(elementsByGroupId, groupId, element); } } return { byId, boundTextByContainer, elementsByFrameId, elementsByGroupId }; };
// src/model/result.ts var ok = (value) => ({ ok: true, value }); var err = (error) => ({ ok: false, error });
// src/commands/helpers.ts var isBoundTextWithExistingContainer2 = (element, context) => { return element.type === "text" && !!element.containerId && context.indexes.byId.has(element.containerId); }; var appendIfExisting = (context, id, seen, output) => { if (seen.has(id) || !context.indexes.byId.has(id)) { return; } seen.add(id); output.push(id); }; var appendContainerClosure = (context, containerId, seen, output) => { appendIfExisting(context, containerId, seen, output); const boundTexts = context.indexes.boundTextByContainer.get(containerId) ?? []; for (const boundText of boundTexts) { appendIfExisting(context, boundText.id, seen, output); } }; var stableUniqueExistingInput = (context, ids) => { const seen = /* @PURE / new Set(); const output = []; for (const id of ids) { if (seen.has(id)) { continue; } seen.add(id); if (context.indexes.byId.has(id)) { output.push(id); } } return output; }; var normalizeTargetIds = (context, elementIds) => { const requested = stableUniqueExistingInput(context, elementIds); const normalized = []; const seenNormalized = / @PURE */ new Set(); for (const id of requested) { const element = context.indexes.byId.get(id); if (!element) { continue; } if (isBoundTextWithExistingContainer2(element, context)) { appendContainerClosure(context, element.containerId, seenNormalized, normalized); continue; } appendIfExisting(context, id, seenNormalized, normalized); appendContainerClosure(context, id, seenNormalized, normalized); } return normalized; }; var resolveExistingIds = (context, elementIds) => { const resolved = normalizeTargetIds(context, elementIds); if (resolved.length === 0) { return err("No existing elements found for command."); } return ok(resolved); };
// src/commands/createGroup.ts
var normalizeGroupLabel = (seed) => {
const compact = seed.trim().replaceAll(/\s+/g, " ");
return compact.length > 0 ? compact : "Group";
};
var normalizeGroupSeed = (seed) => {
const compact = normalizeGroupLabel(seed).replaceAll(/[\/]+/g, " ").trim().replaceAll(/\s+/g, "-");
return compact.length > 0 ? compact : "Group";
};
var makeUniqueGroupId = (context, base) => {
const existing = new Set(context.indexes.elementsByGroupId.keys());
if (!existing.has(base)) {
return base;
}
let index = 2;
while (existing.has(${base}-${index})) {
index += 1;
}
return ${base}-${index};
};
var planCreateGroup = (context, input) => {
const resolved = resolveExistingIds(context, input.elementIds);
if (!resolved.ok) {
return resolved;
}
if (resolved.value.length < 2) {
return err("Need at least two elements to create a group.");
}
const targets = resolved.value.map((id) => context.indexes.byId.get(id)).filter((entry) => Boolean(entry));
const sourceFrameId = targets[0]?.frameId ?? null;
const spansMultipleFrames = targets.some((target) => target.frameId !== sourceFrameId);
if (spansMultipleFrames) {
return err("Cannot create a group across multiple frames.");
}
const groupLabel = normalizeGroupLabel(input.nameSeed ?? "Group");
const base = normalizeGroupSeed(groupLabel);
const groupId = makeUniqueGroupId(context, base);
const patch = {
elementPatches: resolved.value.map((id) => {
const current = context.indexes.byId.get(id);
const nextGroupIds = [...current?.groupIds ?? []];
if (!nextGroupIds.includes(groupId)) {
nextGroupIds.push(groupId);
}
return {
id,
set: {
groupIds: nextGroupIds,
customData: withLmxGroupLabel(current?.customData ?? {}, groupId, groupLabel)
}
};
}),
selectIds: resolved.value
};
return ok({ groupId, patch });
};
// src/commands/deleteNode.ts var planDeleteNode = (context, input) => { const resolved = resolveExistingIds(context, input.elementIds); if (!resolved.ok) { return resolved; } return ok({ elementPatches: resolved.value.map((id) => ({ id, set: { isDeleted: true } })) }); };
// src/commands/renameNode.ts var normalizeRenameValue = (value) => { const normalized = value.trim(); if (!normalized) { return err("Name cannot be empty."); } return ok(normalized); }; var planElementRename = (context, elementId, normalizedName) => { const element = context.indexes.byId.get(elementId); if (!element) { return err("Element to rename does not exist."); } return ok({ elementPatches: [ { id: element.id, set: element.type === "frame" ? { name: normalizedName } : { customData: withLmxElementLabel(element.customData, normalizedName) } } ] }); }; var planGroupRename = (context, groupId, normalizedName) => { const groupMembers = context.indexes.elementsByGroupId.get(groupId) ?? []; if (groupMembers.length === 0) { return err("Group to rename does not exist."); } return ok({ elementPatches: groupMembers.map((member) => ({ id: member.id, set: { customData: withLmxGroupLabel(member.customData, groupId, normalizedName) } })) }); }; var planRenameNode = (context, input) => { const normalized = normalizeRenameValue(input.nextName); if (!normalized.ok) { return normalized; } if ("groupId" in input) { return planGroupRename(context, input.groupId, normalized.value); } return planElementRename(context, input.elementId, normalized.value); };
// src/model/patch.ts var emptyPatch = () => ({ elementPatches: [] });
// src/commands/reorderNode.ts
var ROOT_SCOPE_KEY = "root";
var REORDER_MODES = ["forward", "backward", "front", "back"];
var REORDER_PLACEMENTS = ["before", "after"];
var isReorderMode = (value) => {
return REORDER_MODES.includes(value);
};
var isReorderPlacement = (value) => {
return REORDER_PLACEMENTS.includes(value);
};
var haveSameIdsInSameOrder = (left, right) => {
if (left.length !== right.length) {
return false;
}
for (let index = 0; index < left.length; index += 1) {
if (left[index] !== right[index]) {
return false;
}
}
return true;
};
var haveSameNodeOrder = (left, right) => {
if (left.length !== right.length) {
return false;
}
for (let index = 0; index < left.length; index += 1) {
if (left[index]?.id !== right[index]?.id) {
return false;
}
}
return true;
};
var buildSceneIndexById = (context) => {
const indexById = /* @PURE / new Map();
context.snapshot.elements.forEach((element, index) => {
indexById.set(element.id, index);
});
return indexById;
};
var orderElementIdsByScene = (ids, sceneIndexById) => {
return [...ids].sort((left, right) => {
const leftIndex = sceneIndexById.get(left) ?? Number.MAX_SAFE_INTEGER;
const rightIndex = sceneIndexById.get(right) ?? Number.MAX_SAFE_INTEGER;
return leftIndex - rightIndex;
});
};
var buildScopeChildrenMap = (nodes, scopeKey, scopeChildrenByKey) => {
scopeChildrenByKey.set(scopeKey, nodes);
for (const node of nodes) {
if (node.children.length === 0) {
continue;
}
buildScopeChildrenMap(node.children, node.id, scopeChildrenByKey);
}
};
var buildNodeScopeIndex = (nodes, scopeKey, nodeScopeById) => {
for (const node of nodes) {
nodeScopeById.set(node.id, scopeKey);
if (node.children.length === 0) {
continue;
}
buildNodeScopeIndex(node.children, node.id, nodeScopeById);
}
};
var isNodeFullySelected = (node, selectedIds) => {
if (node.elementIds.length === 0) {
return false;
}
return node.elementIds.every((elementId) => selectedIds.has(elementId));
};
var hasSelectedLeafContent = (node, selectedIds) => {
return node.elementIds.some((elementId) => selectedIds.has(elementId));
};
var collectSelectedBlocks = (nodes, selectedIds, scopeKey) => {
const blocks = [];
for (const node of nodes) {
if (isNodeFullySelected(node, selectedIds)) {
blocks.push({
nodeId: node.id,
scopeKey
});
continue;
}
if (node.children.length > 0) {
blocks.push(...collectSelectedBlocks(node.children, selectedIds, node.id));
continue;
}
if (hasSelectedLeafContent(node, selectedIds)) {
blocks.push({
nodeId: node.id,
scopeKey
});
}
}
return blocks;
};
var moveSelectedTowardFront = (children, selectedNodeIds) => {
const reordered = [...children];
for (let index = 1; index < reordered.length; index += 1) {
const current = reordered[index];
const previous = reordered[index - 1];
if (!current || !previous) {
continue;
}
if (!selectedNodeIds.has(current.id) || selectedNodeIds.has(previous.id)) {
continue;
}
reordered[index - 1] = current;
reordered[index] = previous;
}
return reordered;
};
var moveSelectedTowardBack = (children, selectedNodeIds) => {
const reordered = [...children];
for (let index = reordered.length - 2; index >= 0; index -= 1) {
const current = reordered[index];
const next = reordered[index + 1];
if (!current || !next) {
continue;
}
if (!selectedNodeIds.has(current.id) || selectedNodeIds.has(next.id)) {
continue;
}
reordered[index] = next;
reordered[index + 1] = current;
}
return reordered;
};
var reorderScopeChildren = (children, selectedNodeIds, mode) => {
const selectedChildren = children.filter((child) => selectedNodeIds.has(child.id));
if (selectedChildren.length === 0) {
return children;
}
if (mode === "front") {
const remaining = children.filter((child) => !selectedNodeIds.has(child.id));
return [...selectedChildren, ...remaining];
}
if (mode === "back") {
const remaining = children.filter((child) => !selectedNodeIds.has(child.id));
return [...remaining, ...selectedChildren];
}
if (mode === "forward") {
return moveSelectedTowardFront(children, selectedNodeIds);
}
return moveSelectedTowardBack(children, selectedNodeIds);
};
var reorderScopeChildrenRelativeToAnchor = (children, selectedNodeIds, anchorNodeId, placement) => {
if (selectedNodeIds.has(anchorNodeId)) {
return err("Relative reorder target must not be one of the dragged rows.");
}
const selectedChildren = children.filter((child) => selectedNodeIds.has(child.id));
if (selectedChildren.length === 0) {
return err("Relative reorder could not resolve the dragged rows inside the target scope.");
}
const remainingChildren = children.filter((child) => !selectedNodeIds.has(child.id));
const anchorIndex = remainingChildren.findIndex((child) => child.id === anchorNodeId);
if (anchorIndex < 0) {
return err("Relative reorder target is no longer a sibling in the dragged row scope.");
}
const insertIndex = placement === "before" ? anchorIndex : anchorIndex + 1;
return ok([
...remainingChildren.slice(0, insertIndex),
...selectedChildren,
...remainingChildren.slice(insertIndex)
]);
};
var flattenScopeToSceneOrder = (scopeKey, scopeChildrenByKey, reorderedChildrenByScope, sceneIndexById) => {
const children = reorderedChildrenByScope.get(scopeKey) ?? scopeChildrenByKey.get(scopeKey) ?? [];
const orderedIds = [];
for (let index = children.length - 1; index >= 0; index -= 1) {
const child = children[index];
if (!child) {
continue;
}
orderedIds.push(
...flattenNodeToSceneOrder(
child,
scopeChildrenByKey,
reorderedChildrenByScope,
sceneIndexById
)
);
}
return orderedIds;
};
var flattenNodeToSceneOrder = (node, scopeChildrenByKey, reorderedChildrenByScope, sceneIndexById) => {
if (node.type === "frame") {
return [
node.primaryElementId,
...flattenScopeToSceneOrder(
node.id,
scopeChildrenByKey,
reorderedChildrenByScope,
sceneIndexById
)
];
}
if (node.children.length > 0) {
return flattenScopeToSceneOrder(
node.id,
scopeChildrenByKey,
reorderedChildrenByScope,
sceneIndexById
);
}
return orderElementIdsByScene(node.elementIds, sceneIndexById);
};
var isFullPermutation2 = (currentIds, nextIds) => {
if (currentIds.length !== nextIds.length) {
return false;
}
const seen = new Set(nextIds);
if (seen.size !== currentIds.length) {
return false;
}
return currentIds.every((id) => seen.has(id));
};
var planReorder = (context, input) => {
const targetIds = normalizeTargetIds(context, input.orderedElementIds);
if (targetIds.length === 0) {
return err("No valid element IDs for reorder.");
}
const hasAnchorTarget = typeof input.anchorNodeId === "string" && input.anchorNodeId.length > 0;
const requestedMode = input.mode ?? "front";
if (!hasAnchorTarget && !isReorderMode(requestedMode)) {
return err(Unknown reorder mode: ${requestedMode}.);
}
const requestedPlacement = input.placement ?? "before";
if (hasAnchorTarget && !isReorderPlacement(requestedPlacement)) {
return err(Unknown reorder placement: ${requestedPlacement}.);
}
const selectedIds = new Set(targetIds);
const sceneIndexById = buildSceneIndexById(context);
const currentSceneOrder = context.snapshot.elements.map((element) => element.id);
const tree = buildLayerTree(
{
elements: context.snapshot.elements,
expandedNodeIds: / @PURE / new Set(),
groupFreedraw: context.snapshot.settings.groupFreedraw
},
context.indexes
);
const scopeChildrenByKey = / @PURE / new Map();
buildScopeChildrenMap(tree, ROOT_SCOPE_KEY, scopeChildrenByKey);
const nodeScopeById = / @PURE / new Map();
buildNodeScopeIndex(tree, ROOT_SCOPE_KEY, nodeScopeById);
const selectedBlocks = collectSelectedBlocks(tree, selectedIds, ROOT_SCOPE_KEY);
if (selectedBlocks.length === 0) {
return err("No selected rows could be resolved for reorder.");
}
const selectedNodeIdsByScope = / @PURE / new Map();
for (const block of selectedBlocks) {
const selectedNodeIds = selectedNodeIdsByScope.get(block.scopeKey);
if (selectedNodeIds) {
selectedNodeIds.add(block.nodeId);
continue;
}
selectedNodeIdsByScope.set(block.scopeKey, / @PURE / new Set([block.nodeId]));
}
const reorderedChildrenByScope = / @PURE */ new Map();
if (hasAnchorTarget) {
const anchorNodeId = input.anchorNodeId ?? "";
const anchorScopeKey = nodeScopeById.get(anchorNodeId);
if (!anchorScopeKey) {
return err(Relative reorder anchor not found: ${anchorNodeId}.);
}
const selectedNodeIds = selectedNodeIdsByScope.get(anchorScopeKey);
if (!selectedNodeIds || selectedNodeIdsByScope.size !== 1) {
return err(
"Relative reorder requires the dragged rows and target row to share one canonical parent scope."
);
}
const children = scopeChildrenByKey.get(anchorScopeKey);
if (!children || children.length === 0) {
return err("Relative reorder scope is empty or no longer available.");
}
const reordered = reorderScopeChildrenRelativeToAnchor(
children,
selectedNodeIds,
anchorNodeId,
requestedPlacement
);
if (!reordered.ok) {
return reordered;
}
if (!haveSameNodeOrder(children, reordered.value)) {
reorderedChildrenByScope.set(anchorScopeKey, reordered.value);
}
} else {
const mode = requestedMode;
for (const [scopeKey, selectedNodeIds] of selectedNodeIdsByScope) {
const children = scopeChildrenByKey.get(scopeKey);
if (!children || children.length === 0) {
continue;
}
const reordered = reorderScopeChildren(children, selectedNodeIds, mode);
if (!haveSameNodeOrder(children, reordered)) {
reorderedChildrenByScope.set(scopeKey, reordered);
}
}
}
if (reorderedChildrenByScope.size === 0) {
return ok(emptyPatch());
}
const nextSceneOrder = flattenScopeToSceneOrder(
ROOT_SCOPE_KEY,
scopeChildrenByKey,
reorderedChildrenByScope,
sceneIndexById
);
if (!isFullPermutation2(currentSceneOrder, nextSceneOrder)) {
return err("Reorder planner failed to emit a full-scene permutation.");
}
if (haveSameIdsInSameOrder(currentSceneOrder, nextSceneOrder)) {
return ok(emptyPatch());
}
return ok({
elementPatches: [],
reorder: {
orderedElementIds: nextSceneOrder
}
});
};
// src/domain/invariants.ts var makeCanonicalTargetParentPathKey = (targetFrameId, targetParentPath) => { return JSON.stringify({ targetFrameId, targetParentPath: [...targetParentPath] }); }; var collectCanonicalTargetParentPathKeys = (tree) => { const keys = /* @PURE / new Set([makeCanonicalTargetParentPathKey(null, [])]); const walk = (nodes, branchContext) => { for (const node of nodes) { const nodeFrameId = resolveFrameRowElementId(node) ?? node.frameId ?? branchContext.frameId; keys.add(makeCanonicalTargetParentPathKey(nodeFrameId, branchContext.groupPath)); const childGroupPath = node.type === "group" && node.groupId ? [...branchContext.groupPath, node.groupId] : branchContext.groupPath; if (node.type === "group" && node.groupId) { keys.add(makeCanonicalTargetParentPathKey(nodeFrameId, childGroupPath)); } if (node.children.length > 0) { walk(node.children, { frameId: nodeFrameId, groupPath: childGroupPath }); } } }; walk(tree, { frameId: null, groupPath: [] }); return keys; }; var validateTargetParentPathSegments = (targetParentPath) => { const seen = / @PURE / new Set(); for (const groupId of targetParentPath) { if (groupId.trim().length === 0) { return err("targetParentPath cannot contain blank group ids."); } if (seen.has(groupId)) { return err("targetParentPath cannot contain duplicate group ids."); } seen.add(groupId); } return ok(void 0); }; var validateCanonicalTargetParentPath = (targetFrameId, targetParentPath, canonicalTargetParentPathKeys) => { if (!canonicalTargetParentPathKeys) { return ok(void 0); } if (!canonicalTargetParentPathKeys.has( makeCanonicalTargetParentPathKey(targetFrameId, targetParentPath) )) { return err("Target parent path is stale or no longer exists in the structural tree."); } return ok(void 0); }; var validateNoCrossFrameMove = (sourceFrameId, targetFrameId) => { if (sourceFrameId !== targetFrameId) { return err("Cross-frame moves are not supported."); } return ok(void 0); }; var validateNoSelfNesting = (sourceGroupId, targetParentPath) => { if (sourceGroupId && targetParentPath.includes(sourceGroupId)) { return err("Cannot move a group into itself."); } return ok(void 0); }; var collectDescendantGroupIds = (nodes, targetGroupId) => { const descendants = / @PURE */ new Set(); const walk = (children) => { for (const child of children) { if (child.type === "group" && child.groupId === targetGroupId) { collectAllGroupIds(child.children, descendants); return true; } if (child.children.length > 0 && walk(child.children)) { return true; } } return false; }; walk(nodes); return descendants; }; var collectAllGroupIds = (nodes, out) => { for (const node of nodes) { if (node.type === "group" && node.groupId) { out.add(node.groupId); } if (node.children.length > 0) { collectAllGroupIds(node.children, out); } } }; var validateNoDescendantCycle = (sourceGroupId, targetParentPath, structuralTree) => { if (!sourceGroupId || targetParentPath.length === 0 || !structuralTree) { return ok(void 0); } const descendantGroupIds = collectDescendantGroupIds(structuralTree, sourceGroupId); for (const pathGroupId of targetParentPath) { if (descendantGroupIds.has(pathGroupId)) { return err("Cannot move a group into one of its own descendants (would create a cycle)."); } } return ok(void 0); }; var validateReparentInvariants = (input) => { const pathCheck = validateTargetParentPathSegments(input.targetParentPath); if (!pathCheck.ok) { return pathCheck; } const frameCheck = validateNoCrossFrameMove(input.sourceFrameId, input.targetFrameId); if (!frameCheck.ok) { return frameCheck; } const cycleCheck = validateNoSelfNesting(input.sourceGroupId, input.targetParentPath); if (!cycleCheck.ok) { return cycleCheck; } const descendantCycleCheck = validateNoDescendantCycle( input.sourceGroupId, input.targetParentPath, input.structuralTree ); if (!descendantCycleCheck.ok) { return descendantCycleCheck; } const canonicalPathCheck = validateCanonicalTargetParentPath( input.targetFrameId, input.targetParentPath, input.canonicalTargetParentPathKeys ); if (!canonicalPathCheck.ok) { return canonicalPathCheck; } return ok(void 0); };
// src/commands/reparentNode.ts var buildReparentedGroupIds = (targetGroupIds, sourceGroupId, targetSuffix) => { if (!sourceGroupId) { return [...targetSuffix]; } const sourceIndex = targetGroupIds.lastIndexOf(sourceGroupId); if (sourceIndex < 0) { return [sourceGroupId, ...targetSuffix]; } const innerPrefix = targetGroupIds.slice(0, sourceIndex); return [...innerPrefix, sourceGroupId, ...targetSuffix]; }; var planReparentNode = (context, input) => { const resolved = resolveExistingIds(context, input.elementIds); if (!resolved.ok) { return resolved; } const targets = resolved.value.map((id) => context.indexes.byId.get(id)).filter((entry) => Boolean(entry)); if (targets.length === 0) { return err("No targets to reparent."); } if (targets.some((target) => target.type === "frame")) { return err("Frame elements cannot be structurally reparented."); } if (input.sourceGroupId) { const sourceGroupId = input.sourceGroupId; const everyTargetContainsSourceGroup = targets.every( (target) => target.groupIds.includes(sourceGroupId) ); if (!everyTargetContainsSourceGroup) { return err("sourceGroupId must exist in every normalized target for reparent."); } } const sourceFrameId = targets[0]?.frameId ?? null; const mixedFrames = targets.some((target) => target.frameId !== sourceFrameId); if (mixedFrames) { return err("Cannot reparent nodes spanning multiple source frames."); } const structuralTree = buildLayerTree( { elements: context.snapshot.elements, expandedNodeIds: /* @PURE */ new Set(), groupFreedraw: context.snapshot.settings.groupFreedraw }, context.indexes ); const validation = validateReparentInvariants({ sourceFrameId, targetFrameId: input.targetFrameId, sourceGroupId: input.sourceGroupId, targetParentPath: input.targetParentPath, canonicalTargetParentPathKeys: collectCanonicalTargetParentPathKeys(structuralTree), structuralTree }); if (!validation.ok) { return validation; } const targetSuffix = [...input.targetParentPath].reverse(); const elementPatches = targets.flatMap((target) => { const nextGroupIds = buildReparentedGroupIds(target.groupIds, input.sourceGroupId, targetSuffix); const frameChanged = target.frameId !== input.targetFrameId; const groupIdsChanged = target.groupIds.length !== nextGroupIds.length || target.groupIds.some((groupId, index) => groupId !== nextGroupIds[index]); if (!frameChanged && !groupIdsChanged) { return []; } return [ { id: target.id, set: { frameId: input.targetFrameId, groupIds: nextGroupIds } } ]; }); if (elementPatches.length === 0) { return ok(emptyPatch()); } return ok({ elementPatches }); };
// src/commands/toggleLock.ts var planToggleLock = (context, input) => { const resolved = resolveExistingIds(context, input.elementIds); if (!resolved.ok) { return resolved; } const targets = resolved.value.map((id) => context.indexes.byId.get(id)).filter((entry) => Boolean(entry)); if (targets.length === 0) { return err("No toggle lock targets resolved."); } const allLocked = targets.every((target) => target.locked); return ok({ elementPatches: targets.map((target) => ({ id: target.id, set: { locked: !allLocked } })) }); };
// src/commands/toggleVisibility.ts var planToggleVisibility = (context, input) => { const resolved = resolveExistingIds(context, input.elementIds); if (!resolved.ok) { return resolved; } const targets = resolved.value.map((id) => context.indexes.byId.get(id)).filter((entry) => Boolean(entry)); if (targets.length === 0) { return err("No toggle visibility targets resolved."); } const anyHidden = targets.some((target) => target.opacity <= 0); return ok({ elementPatches: targets.flatMap((target) => { if (anyHidden) { if (target.opacity > 0) { return []; } const originalOpacity = target.customData.originalOpacity; const restoreOpacity = typeof originalOpacity === "number" && originalOpacity > 0 ? originalOpacity : 100; const { originalOpacity: _, ...cleanedCustomData } = target.customData; return [ { id: target.id, set: { opacity: restoreOpacity, customData: cleanedCustomData } } ]; } return [ { id: target.id, set: { opacity: 0, customData: { ...target.customData, originalOpacity: target.opacity } } } ]; }) }); };
// src/runtime/commandFacade.ts
var formatFailureMessage = (commandName, outcome) => {
if (outcome.status === "plannerError") {
return ${commandName} failed: ${outcome.error};
}
return ${commandName} not applied (${outcome.status}): ${outcome.reason};
};
var runFacadeCommand = async (commandName, executeIntent, planner, notify, options) => {
const outcome = await executeIntent(planner);
if (outcome.status !== "applied" && options?.notifyOnFailure !== false) {
notify?.(formatFailureMessage(commandName, outcome));
}
return outcome;
};
var createLayerManagerCommandFacade = (input) => {
const run = (commandName, planner, options) => {
return runFacadeCommand(commandName, input.executeIntent, planner, input.notify, options);
};
return {
toggleVisibility: (commandInput, options) => run("toggleVisibility", (context) => planToggleVisibility(context, commandInput), options),
toggleLock: (commandInput, options) => run("toggleLock", (context) => planToggleLock(context, commandInput), options),
renameNode: (commandInput, options) => run("renameNode", (context) => planRenameNode(context, commandInput), options),
deleteNode: (commandInput, options) => run("deleteNode", (context) => planDeleteNode(context, commandInput), options),
createGroup: (commandInput, options) => run(
"createGroup",
(context) => {
const plan = planCreateGroup(context, commandInput);
if (!plan.ok) {
return plan;
}
return ok(plan.value.patch);
},
options
),
reorder: (commandInput, options) => run("reorder", (context) => planReorder(context, commandInput), options),
reparent: (commandInput, options) => run("reparent", (context) => planReparentNode(context, commandInput), options)
};
};
// ../../node_modules/xstate/dist/xstate-dev.esm.js function getGlobal() { if (typeof globalThis !== "undefined") { return globalThis; } if (typeof self !== "undefined") { return self; } if (typeof window !== "undefined") { return window; } if (typeof global !== "undefined") { return global; } } function getDevTools() { const w = getGlobal(); if (w.xstate) { return w.xstate; } return void 0; } var devToolsAdapter = (service) => { if (typeof window === "undefined") { return; } const devTools = getDevTools(); if (devTools) { devTools.register(service); } };
// ../../node_modules/xstate/dist/raise-8dd8aaec.esm.js
var Mailbox = class {
constructor(_process) {
this._process = _process;
this._active = false;
this._current = null;
this._last = null;
}
start() {
this._active = true;
this.flush();
}
clear() {
if (this._current) {
this._current.next = null;
this._last = this._current;
}
}
enqueue(event) {
const enqueued = {
value: event,
next: null
};
if (this._current) {
this._last.next = enqueued;
this._last = enqueued;
return;
}
this._current = enqueued;
this._last = enqueued;
if (this._active) {
this.flush();
}
}
flush() {
while (this._current) {
const consumed = this._current;
this._process(consumed.value);
this._current = consumed.next;
}
this._last = null;
}
};
var STATE_DELIMITER = ".";
var TARGETLESS_KEY = "";
var NULL_EVENT = "";
var STATE_IDENTIFIER = "#";
var WILDCARD = "";
var XSTATE_INIT = "xstate.init";
var XSTATE_ERROR = "xstate.error";
var XSTATE_STOP = "xstate.stop";
function createAfterEvent(delayRef, id) {
return {
type: xstate.after.${delayRef}.${id}
};
}
function createDoneStateEvent(id, output) {
return {
type: xstate.done.state.${id},
output
};
}
function createDoneActorEvent(invokeId, output) {
return {
type: xstate.done.actor.${invokeId},
output,
actorId: invokeId
};
}
function createErrorActorEvent(id, error) {
return {
type: xstate.error.actor.${id},
error,
actorId: id
};
}
function createInitEvent(input) {
return {
type: XSTATE_INIT,
input
};
}
function reportUnhandledError(err2) {
setTimeout(() => {
throw err2;
});
}
var symbolObservable = (() => typeof Symbol === "function" && Symbol.observable || "@@observable")();
function matchesState(parentStateId, childStateId) {
const parentStateValue = toStateValue(parentStateId);
const childStateValue = toStateValue(childStateId);
if (typeof childStateValue === "string") {
if (typeof parentStateValue === "string") {
return childStateValue === parentStateValue;
}
return false;
}
if (typeof parentStateValue === "string") {
return parentStateValue in childStateValue;
}
return Object.keys(parentStateValue).every((key) => {
if (!(key in childStateValue)) {
return false;
}
return matchesState(parentStateValue[key], childStateValue[key]);
});
}
function toStatePath(stateId) {
if (isArray(stateId)) {
return stateId;
}
const result = [];
let segment = "";
for (let i = 0; i < stateId.length; i++) {
const char = stateId.charCodeAt(i);
switch (char) {
//
case 92:
segment += stateId[i + 1];
i++;
continue;
// .
case 46:
result.push(segment);
segment = "";
continue;
}
segment += stateId[i];
}
result.push(segment);
return result;
}
function toStateValue(stateValue) {
if (isMachineSnapshot(stateValue)) {
return stateValue.value;
}
if (typeof stateValue !== "string") {
return stateValue;
}
const statePath = toStatePath(stateValue);
return pathToStateValue(statePath);
}
function pathToStateValue(statePath) {
if (statePath.length === 1) {
return statePath[0];
}
const value = {};
let marker = value;
for (let i = 0; i < statePath.length - 1; i++) {
if (i === statePath.length - 2) {
marker[statePath[i]] = statePath[i + 1];
} else {
const previous = marker;
marker = {};
previous[statePath[i]] = marker;
}
}
return value;
}
function mapValues(collection, iteratee) {
const result = {};
const collectionKeys = Object.keys(collection);
for (let i = 0; i < collectionKeys.length; i++) {
const key = collectionKeys[i];
result[key] = iteratee(collection[key], key, collection, i);
}
return result;
}
function toArrayStrict(value) {
if (isArray(value)) {
return value;
}
return [value];
}
function toArray(value) {
if (value === void 0) {
return [];
}
return toArrayStrict(value);
}
function resolveOutput(mapper, context, event, self2) {
if (typeof mapper === "function") {
return mapper({
context,
event,
self: self2
});
}
return mapper;
}
function isArray(value) {
return Array.isArray(value);
}
function isErrorActorEvent(event) {
return event.type.startsWith("xstate.error.actor");
}
function toTransitionConfigArray(configLike) {
return toArrayStrict(configLike).map((transitionLike) => {
if (typeof transitionLike === "undefined" || typeof transitionLike === "string") {
return {
target: transitionLike
};
}
return transitionLike;
});
}
function normalizeTarget(target) {
if (target === void 0 || target === TARGETLESS_KEY) {
return void 0;
}
return toArray(target);
}
function toObserver(nextHandler, errorHandler, completionHandler) {
const isObserver = typeof nextHandler === "object";
const self2 = isObserver ? nextHandler : void 0;
return {
next: (isObserver ? nextHandler.next : nextHandler)?.bind(self2),
error: (isObserver ? nextHandler.error : errorHandler)?.bind(self2),
complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self2)
};
}
function createInvokeId(stateNodeId, index) {
return ${index}.${stateNodeId};
}
function resolveReferencedActor(machine, src) {
const match = src.match(/^xstate.invoke.(\d+).(.)/);
if (!match) {
return machine.implementations.actors[src];
}
const [, indexStr, nodeId] = match;
const node = machine.getStateNodeById(nodeId);
const invokeConfig = node.config.invoke;
return (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;
}
function matchesEventDescriptor(eventType, descriptor) {
if (descriptor === eventType) {
return true;
}
if (descriptor === WILDCARD) {
return true;
}
if (!descriptor.endsWith(".")) {
return false;
}
const partialEventTokens = descriptor.split(".");
const eventTokens = eventType.split(".");
for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
const partialEventToken = partialEventTokens[tokenIndex];
const eventToken = eventTokens[tokenIndex];
if (partialEventToken === "") {
const isLastToken = tokenIndex === partialEventTokens.length - 1;
return isLastToken;
}
if (partialEventToken !== eventToken) {
return false;
}
}
return true;
}
function createScheduledEventId(actorRef, id) {
return ${actorRef.sessionId}.${id};
}
var idCounter = 0;
function createSystem(rootActor, options) {
const children = /* @PURE / new Map();
const keyedActors = / @PURE / new Map();
const reverseKeyedActors = / @PURE / new WeakMap();
const inspectionObservers = / @PURE / new Set();
const timerMap = {};
const {
clock,
logger
} = options;
const scheduler = {
schedule: (source, target, event, delay, id = Math.random().toString(36).slice(2)) => {
const scheduledEvent = {
source,
target,
event,
delay,
id,
startedAt: Date.now()
};
const scheduledEventId = createScheduledEventId(source, id);
system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;
const timeout = clock.setTimeout(() => {
delete timerMap[scheduledEventId];
delete system._snapshot._scheduledEvents[scheduledEventId];
system._relay(source, target, event);
}, delay);
timerMap[scheduledEventId] = timeout;
},
cancel: (source, id) => {
const scheduledEventId = createScheduledEventId(source, id);
const timeout = timerMap[scheduledEventId];
delete timerMap[scheduledEventId];
delete system._snapshot._scheduledEvents[scheduledEventId];
if (timeout !== void 0) {
clock.clearTimeout(timeout);
}
},
cancelAll: (actorRef) => {
for (const scheduledEventId in system._snapshot._scheduledEvents) {
const scheduledEvent = system._snapshot._scheduledEvents[scheduledEventId];
if (scheduledEvent.source === actorRef) {
scheduler.cancel(actorRef, scheduledEvent.id);
}
}
}
};
const sendInspectionEvent = (event) => {
if (!inspectionObservers.size) {
return;
}
const resolvedInspectionEvent = {
...event,
rootId: rootActor.sessionId
};
inspectionObservers.forEach((observer) => observer.next?.(resolvedInspectionEvent));
};
const system = {
_snapshot: {
_scheduledEvents: (options?.snapshot && options.snapshot.scheduler) ?? {}
},
_bookId: () => x:${idCounter++},
_register: (sessionId, actorRef) => {
children.set(sessionId, actorRef);
return sessionId;
},
_unregister: (actorRef) => {
children.delete(actorRef.sessionId);
const systemId = reverseKeyedActors.get(actorRef);
if (systemId !== void 0) {
keyedActors.delete(systemId);
reverseKeyedActors.delete(actorRef);
}
},
get: (systemId) => {
return keyedActors.get(systemId);
},
getAll: () => {
return Object.fromEntries(keyedActors.entries());
},
_set: (systemId, actorRef) => {
const existing = keyedActors.get(systemId);
if (existing && existing !== actorRef) {
throw new Error(Actor with system ID '${systemId}' already exists.);
}
keyedActors.set(systemId, actorRef);
reverseKeyedActors.set(actorRef, systemId);
},
inspect: (observerOrFn) => {
const observer = toObserver(observerOrFn);
inspectionObservers.add(observer);
return {
unsubscribe() {
inspectionObservers.delete(observer);
}
};
},
_sendInspectionEvent: sendInspectionEvent,
_relay: (source, target, event) => {
system._sendInspectionEvent({
type: "@xstate.event",
sourceRef: source,
actorRef: target,
event
});
target._send(event);
},
scheduler,
getSnapshot: () => {
return {
_scheduledEvents: {
...system._snapshot._scheduledEvents
}
};
},
start: () => {
const scheduledEvents = system._snapshot._scheduledEvents;
system._snapshot._scheduledEvents = {};
for (const scheduledId in scheduledEvents) {
const {
source,
target,
event,
delay,
id
} = scheduledEvents[scheduledId];
scheduler.schedule(source, target, event, delay, id);
}
},
_clock: clock,
_logger: logger
};
return system;
}
var executingCustomAction = false;
var $$ACTOR_TYPE = 1;
var ProcessingStatus = / @PURE / (function(ProcessingStatus2) {
ProcessingStatus2[ProcessingStatus2["NotStarted"] = 0] = "NotStarted";
ProcessingStatus2[ProcessingStatus2["Running"] = 1] = "Running";
ProcessingStatus2[ProcessingStatus2["Stopped"] = 2] = "Stopped";
return ProcessingStatus2;
})({});
var defaultOptions = {
clock: {
setTimeout: (fn, ms) => {
return setTimeout(fn, ms);
},
clearTimeout: (id) => {
return clearTimeout(id);
}
},
logger: console.log.bind(console),
devTools: false
};
var Actor = class {
/*
* Creates a new actor instance for the given logic with the provided options,
* if any.
*
* @param logic The logic to create an actor from
* @param options Actor options
/
constructor(logic, options) {
this.logic = logic;
this._snapshot = void 0;
this.clock = void 0;
this.options = void 0;
this.id = void 0;
this.mailbox = new Mailbox(this._process.bind(this));
this.observers = / @PURE / new Set();
this.eventListeners = / @PURE / new Map();
this.logger = void 0;
this._processingStatus = ProcessingStatus.NotStarted;
this._parent = void 0;
this._syncSnapshot = void 0;
this.ref = void 0;
this._actorScope = void 0;
this.systemId = void 0;
this.sessionId = void 0;
this.system = void 0;
this._doneEvent = void 0;
this.src = void 0;
this._deferred = [];
const resolvedOptions = {
...defaultOptions,
...options
};
const {
clock,
logger,
parent,
syncSnapshot,
id,
systemId,
inspect
} = resolvedOptions;
this.system = parent ? parent.system : createSystem(this, {
clock,
logger
});
if (inspect && !parent) {
this.system.inspect(toObserver(inspect));
}
this.sessionId = this.system._bookId();
this.id = id ?? this.sessionId;
this.logger = options?.logger ?? this.system._logger;
this.clock = options?.clock ?? this.system._clock;
this._parent = parent;
this._syncSnapshot = syncSnapshot;
this.options = resolvedOptions;
this.src = resolvedOptions.src ?? logic;
this.ref = this;
this._actorScope = {
self: this,
id: this.id,
sessionId: this.sessionId,
logger: this.logger,
defer: (fn) => {
this._deferred.push(fn);
},
system: this.system,
stopChild: (child) => {
if (child._parent !== this) {
throw new Error(Cannot stop child actor ${child.id} of ${this.id} because it is not a child);
}
child._stop();
},
emit: (emittedEvent) => {
const listeners = this.eventListeners.get(emittedEvent.type);
const wildcardListener = this.eventListeners.get("");
if (!listeners && !wildcardListener) {
return;
}
const allListeners = [...listeners ? listeners.values() : [], ...wildcardListener ? wildcardListener.values() : []];
for (const handler of allListeners) {
try {
handler(emittedEvent);
} catch (err2) {
reportUnhandledError(err2);
}
}
},
actionExecutor: (action) => {
const exec = () => {
this._actorScope.system._sendInspectionEvent({
type: "@xstate.action",
actorRef: this,
action: {
type: action.type,
params: action.params
}
});
if (!action.exec) {
return;
}
const saveExecutingCustomAction = executingCustomAction;
try {
executingCustomAction = true;
action.exec(action.info, action.params);
} finally {
executingCustomAction = saveExecutingCustomAction;
}
};
if (this._processingStatus === ProcessingStatus.Running) {
exec();
} else {
this._deferred.push(exec);
}
}
};
this.send = this.send.bind(this);
this.system._sendInspectionEvent({
type: "@xstate.actor",
actorRef: this
});
if (systemId) {
this.systemId = systemId;
this.system._set(systemId, this);
}
this._initState(options?.snapshot ?? options?.state);
if (systemId && this._snapshot.status !== "active") {
this.system._unregister(this);
}
}
_initState(persistedState) {
try {
this._snapshot = persistedState ? this.logic.restoreSnapshot ? this.logic.restoreSnapshot(persistedState, this._actorScope) : persistedState : this.logic.getInitialSnapshot(this._actorScope, this.options?.input);
} catch (err2) {
this._snapshot = {
status: "error",
output: void 0,
error: err2
};
}
}
update(snapshot, event) {
this._snapshot = snapshot;
let deferredFn;
while (deferredFn = this._deferred.shift()) {
try {
deferredFn();
} catch (err2) {
this._deferred.length = 0;
this._snapshot = {
...snapshot,
status: "error",
error: err2
};
}
}
switch (this._snapshot.status) {
case "active":
for (const observer of this.observers) {
try {
observer.next?.(snapshot);
} catch (err2) {
reportUnhandledError(err2);
}
}
break;
case "done":
for (const observer of this.observers) {
try {
observer.next?.(snapshot);
} catch (err2) {
reportUnhandledError(err2);
}
}
this._stopProcedure();
this._complete();
this._doneEvent = createDoneActorEvent(this.id, this._snapshot.output);
if (this._parent) {
this.system._relay(this, this._parent, this._doneEvent);
}
break;
case "error":
this._error(this._snapshot.error);
break;
}
this.system._sendInspectionEvent({
type: "@xstate.snapshot",
actorRef: this,
event,
snapshot
});
}
/**
* Subscribe an observer to an actor’s snapshot values.
*
* @remarks
* The observer will receive the actor’s snapshot value when it is emitted.
* The observer can be:
*
* - A plain function that receives the latest snapshot, or
* - An observer object whose .next(snapshot) method receives the latest
* snapshot
*
* @example
*
* ts * // Observer as a plain function * const subscription = actor.subscribe((snapshot) => { * console.log(snapshot); * }); *
*
* @example
*
* ts * // Observer as an object * const subscription = actor.subscribe({ * next(snapshot) { * console.log(snapshot); * }, * error(err) { * // ... * }, * complete() { * // ... * } * }); *
*
* The return value of actor.subscribe(observer) is a subscription object
* that has an .unsubscribe() method. You can call
* subscription.unsubscribe() to unsubscribe the observer:
*
* @example
*
* ts * const subscription = actor.subscribe((snapshot) => { * // ... * }); * * // Unsubscribe the observer * subscription.unsubscribe(); *
*
* When the actor is stopped, all of its observers will automatically be
* unsubscribed.
*
* @param observer - Either a plain function that receives the latest
* snapshot, or an observer object whose .next(snapshot) method receives
* the latest snapshot
/
subscribe(nextListenerOrObserver, errorListener, completeListener) {
const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
if (this._processingStatus !== ProcessingStatus.Stopped) {
this.observers.add(observer);
} else {
switch (this._snapshot.status) {
case "done":
try {
observer.complete?.();
} catch (err2) {
reportUnhandledError(err2);
}
break;
case "error": {
const err2 = this._snapshot.error;
if (!observer.error) {
reportUnhandledError(err2);
} else {
try {
observer.error(err2);
} catch (err3) {
reportUnhandledError(err3);
}
}
break;
}
}
}
return {
unsubscribe: () => {
this.observers.delete(observer);
}
};
}
on(type, handler) {
let listeners = this.eventListeners.get(type);
if (!listeners) {
listeners = / @PURE / new Set();
this.eventListeners.set(type, listeners);
}
const wrappedHandler = handler.bind(void 0);
listeners.add(wrappedHandler);
return {
unsubscribe: () => {
listeners.delete(wrappedHandler);
}
};
}
select(selector, equalityFn = Object.is) {
return {
subscribe: (observerOrFn) => {
const observer = toObserver(observerOrFn);
const snapshot = this.getSnapshot();
let previousSelected = selector(snapshot);
return this.subscribe((snapshot2) => {
const nextSelected = selector(snapshot2);
if (!equalityFn(previousSelected, nextSelected)) {
previousSelected = nextSelected;
observer.next?.(nextSelected);
}
});
},
get: () => selector(this.getSnapshot())
};
}
/* Starts the Actor from the initial state /
start() {
if (this._processingStatus === ProcessingStatus.Running) {
return this;
}
if (this._syncSnapshot) {
this.subscribe({
next: (snapshot) => {
if (snapshot.status === "active") {
this.system._relay(this, this._parent, {
type: xstate.snapshot.${this.id},
snapshot
});
}
},
error: () => {
}
});
}
this.system._register(this.sessionId, this);
if (this.systemId) {
this.system._set(this.systemId, this);
}
this._processingStatus = ProcessingStatus.Running;
const initEvent = createInitEvent(this.options.input);
this.system._sendInspectionEvent({
type: "@xstate.event",
sourceRef: this._parent,
actorRef: this,
event: initEvent
});
const status = this._snapshot.status;
switch (status) {
case "done":
this.update(this._snapshot, initEvent);
return this;
case "error":
this._error(this._snapshot.error);
return this;
}
if (!this._parent) {
this.system.start();
}
if (this.logic.start) {
try {
this.logic.start(this._snapshot, this._actorScope);
} catch (err2) {
this._snapshot = {
...this._snapshot,
status: "error",
error: err2
};
this._error(err2);
return this;
}
}
this.update(this._snapshot, initEvent);
if (this.options.devTools) {
this.attachDevTools();
}
this.mailbox.start();
return this;
}
_process(event) {
let nextState;
let caughtError;
try {
nextState = this.logic.transition(this._snapshot, event, this._actorScope);
} catch (err2) {
caughtError = {
err: err2
};
}
if (caughtError) {
const {
err: err2
} = caughtError;
this._snapshot = {
...this._snapshot,
status: "error",
error: err2
};
this._error(err2);
return;
}
this.update(nextState, event);
if (event.type === XSTATE_STOP) {
this._stopProcedure();
this._complete();
}
}
_stop() {
if (this._processingStatus === ProcessingStatus.Stopped) {
return this;
}
this.mailbox.clear();
if (this._processingStatus === ProcessingStatus.NotStarted) {
this._processingStatus = ProcessingStatus.Stopped;
return this;
}
this.mailbox.enqueue({
type: XSTATE_STOP
});
return this;
}
/* Stops the Actor and unsubscribe all listeners. /
stop() {
if (this._parent) {
throw new Error("A non-root actor cannot be stopped directly.");
}
return this._stop();
}
_complete() {
for (const observer of this.observers) {
try {
observer.complete?.();
} catch (err2) {
reportUnhandledError(err2);
}
}
this.observers.clear();
this.eventListeners.clear();
}
_reportError(err2) {
if (!this.observers.size) {
if (!this._parent) {
reportUnhandledError(err2);
}
this.eventListeners.clear();
return;
}
let reportError = false;
for (const observer of this.observers) {
const errorListener = observer.error;
reportError ||= !errorListener;
try {
errorListener?.(err2);
} catch (err22) {
reportUnhandledError(err22);
}
}
this.observers.clear();
this.eventListeners.clear();
if (reportError) {
reportUnhandledError(err2);
}
}
_error(err2) {
this._stopProcedure();
this._reportError(err2);
if (this._parent) {
this.system._relay(this, this._parent, createErrorActorEvent(this.id, err2));
}
}
// TODO: atm children don't belong entirely to the actor so
// in a way - it's not even super aware of them
// so we can't stop them from here but we really should!
// right now, they are being stopped within the machine's transition
// but that could throw and leave us with "orphaned" active actors
_stopProcedure() {
if (this._processingStatus !== ProcessingStatus.Running) {
return this;
}
this.system.scheduler.cancelAll(this);
this.mailbox.clear();
this.mailbox = new Mailbox(this._process.bind(this));
this._processingStatus = ProcessingStatus.Stopped;
this.system._unregister(this);
return this;
}
/* @internal /
_send(event) {
if (this._processingStatus === ProcessingStatus.Stopped) {
return;
}
this.mailbox.enqueue(event);
}
/*
* Sends an event to the running Actor to trigger a transition.
*
* @param event The event to send
/
send(event) {
this.system._relay(void 0, this, event);
}
attachDevTools() {
const {
devTools
} = this.options;
if (devTools) {
const resolvedDevToolsAdapter = typeof devTools === "function" ? devTools : devToolsAdapter;
resolvedDevToolsAdapter(this);
}
}
toJSON() {
return {
xstate$type: $ACTOR_TYPE,
id: this.id
};
}
/*
* Obtain the internal state of the actor, which can be persisted.
*
* @remarks
* The internal state can be persisted from any actor, not only machines.
*
* Note that the persisted state is not the same as the snapshot from
* {@link Actor.getSnapshot}. Persisted state represents the internal state of
* the actor, while snapshots represent the actor's last emitted value.
*
* Can be restored with {@link ActorOptions.state}
* @see https://stately.ai/docs/persistence
/
getPersistedSnapshot(options) {
return this.logic.getPersistedSnapshot(this._snapshot, options);
}
symbolObservable {
return this;
}
/*
* Read an actor’s snapshot synchronously.
*
* @remarks
* The snapshot represent an actor's last emitted value.
*
* When an actor receives an event, its internal state may change. An actor
* may emit a snapshot when a state transition occurs.
*
* Note that some actors, such as callback actors generated with
* fromCallback, will not emit snapshots.
* @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.
* @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).
/
getSnapshot() {
return this.snapshot;
}
};
function createActor(logic, ...[options]) {
return new Actor(logic, options);
}
function resolveCancel(, snapshot, actionArgs, actionParams, {
sendId
}) {
const resolvedSendId = typeof sendId === "function" ? sendId(actionArgs, actionParams) : sendId;
return [snapshot, {
sendId: resolvedSendId
}, void 0];
}
function executeCancel(actorScope, params) {
actorScope.defer(() => {
actorScope.system.scheduler.cancel(actorScope.self, params.sendId);
});
}
function cancel(sendId) {
function cancel2(_args, _params) {
}
cancel2.type = "xstate.cancel";
cancel2.sendId = sendId;
cancel2.resolve = resolveCancel;
cancel2.execute = executeCancel;
return cancel2;
}
function resolveSpawn(actorScope, snapshot, actionArgs, _actionParams, {
id,
systemId,
src,
input,
syncSnapshot
}) {
const logic = typeof src === "string" ? resolveReferencedActor(snapshot.machine, src) : src;
const resolvedId = typeof id === "function" ? id(actionArgs) : id;
let actorRef;
let resolvedInput = void 0;
if (logic) {
resolvedInput = typeof input === "function" ? input({
context: snapshot.context,
event: actionArgs.event,
self: actorScope.self
}) : input;
actorRef = createActor(logic, {
id: resolvedId,
src,
parent: actorScope.self,
syncSnapshot,
systemId,
input: resolvedInput
});
}
return [cloneMachineSnapshot(snapshot, {
children: {
...snapshot.children,
[resolvedId]: actorRef
}
}), {
id,
systemId,
actorRef,
src,
input: resolvedInput
}, void 0];
}
function executeSpawn(actorScope, {
actorRef
}) {
if (!actorRef) {
return;
}
actorScope.defer(() => {
if (actorRef._processingStatus === ProcessingStatus.Stopped) {
return;
}
actorRef.start();
});
}
function spawnChild(...[src, {
id,
systemId,
input,
syncSnapshot = false
} = {}]) {
function spawnChild2(_args, params) {
}
spawnChild2.type = "xstate.spawnChild";
spawnChild2.id = id;
spawnChild2.systemId = systemId;
spawnChild2.src = src;
spawnChild2.input = input;
spawnChild2.syncSnapshot = syncSnapshot;
spawnChild2.resolve = resolveSpawn;
spawnChild2.execute = executeSpawn;
return spawnChild2;
}
function resolveStop(, snapshot, args, actionParams, {
actorRef
}) {
const actorRefOrString = typeof actorRef === "function" ? actorRef(args, actionParams) : actorRef;
const resolvedActorRef = typeof actorRefOrString === "string" ? snapshot.children[actorRefOrString] : actorRefOrString;
let children = snapshot.children;
if (resolvedActorRef) {
children = {
...children
};
delete children[resolvedActorRef.id];
}
return [cloneMachineSnapshot(snapshot, {
children
}), resolvedActorRef, void 0];
}
function unregisterRecursively(actorScope, actorRef) {
const snapshot = actorRef.getSnapshot();
if (snapshot && "children" in snapshot) {
for (const child of Object.values(snapshot.children)) {
unregisterRecursively(actorScope, child);
}
}
actorScope.system._unregister(actorRef);
}
function executeStop(actorScope, actorRef) {
if (!actorRef) {
return;
}
unregisterRecursively(actorScope, actorRef);
if (actorRef._processingStatus !== ProcessingStatus.Running) {
actorScope.stopChild(actorRef);
return;
}
actorScope.defer(() => {
actorScope.stopChild(actorRef);
});
}
function stopChild(actorRef) {
function stop2(_args, _params) {
}
stop2.type = "xstate.stopChild";
stop2.actorRef = actorRef;
stop2.resolve = resolveStop;
stop2.execute = executeStop;
return stop2;
}
function checkAnd(snapshot, {
context,
event
}, {
guards
}) {
return guards.every((guard) => evaluateGuard(guard, context, event, snapshot));
}
function and(guards) {
function and2(_args, _params) {
return false;
}
and2.check = checkAnd;
and2.guards = guards;
return and2;
}
function evaluateGuard(guard, context, event, snapshot) {
const {
machine
} = snapshot;
const isInline = typeof guard === "function";
const resolved = isInline ? guard : machine.implementations.guards[typeof guard === "string" ? guard : guard.type];
if (!isInline && !resolved) {
throw new Error(Guard '${typeof guard === "string" ? guard : guard.type}' is not implemented.'.);
}
if (typeof resolved !== "function") {
return evaluateGuard(resolved, context, event, snapshot);
}
const guardArgs = {
context,
event
};
const guardParams = isInline || typeof guard === "string" ? void 0 : "params" in guard ? typeof guard.params === "function" ? guard.params({
context,
event
}) : guard.params : void 0;
if (!("check" in resolved)) {
return resolved(guardArgs, guardParams);
}
const builtinGuard = resolved;
return builtinGuard.check(
snapshot,
guardArgs,
resolved
// this holds all params
);
}
function isAtomicStateNode(stateNode) {
return stateNode.type === "atomic" || stateNode.type === "final";
}
function getChildren(stateNode) {
return Object.values(stateNode.states).filter((sn) => sn.type !== "history");
}
function getProperAncestors(stateNode, toStateNode) {
const ancestors = [];
if (toStateNode === stateNode) {
return ancestors;
}
let m = stateNode.parent;
while (m && m !== toStateNode) {
ancestors.push(m);
m = m.parent;
}
return ancestors;
}
function getAllStateNodes(stateNodes) {
const nodeSet = new Set(stateNodes);
const adjList = getAdjList(nodeSet);
for (const s of nodeSet) {
if (s.type === "compound" && (!adjList.get(s) || !adjList.get(s).length)) {
getInitialStateNodesWithTheirAncestors(s).forEach((sn) => nodeSet.add(sn));
} else {
if (s.type === "parallel") {
for (const child of getChildren(s)) {
if (child.type === "history") {
continue;
}
if (!nodeSet.has(child)) {
const initialStates = getInitialStateNodesWithTheirAncestors(child);
for (const initialStateNode of initialStates) {
nodeSet.add(initialStateNode);
}
}
}
}
}
}
for (const s of nodeSet) {
let m = s.parent;
while (m) {
nodeSet.add(m);
m = m.parent;
}
}
return nodeSet;
}
function getValueFromAdj(baseNode, adjList) {
const childStateNodes = adjList.get(baseNode);
if (!childStateNodes) {
return {};
}
if (baseNode.type === "compound") {
const childStateNode = childStateNodes[0];
if (childStateNode) {
if (isAtomicStateNode(childStateNode)) {
return childStateNode.key;
}
} else {
return {};
}
}
const stateValue = {};
for (const childStateNode of childStateNodes) {
stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);
}
return stateValue;
}
function getAdjList(stateNodes) {
const adjList = / @PURE / new Map();
for (const s of stateNodes) {
if (!adjList.has(s)) {
adjList.set(s, []);
}
if (s.parent) {
if (!adjList.has(s.parent)) {
adjList.set(s.parent, []);
}
adjList.get(s.parent).push(s);
}
}
return adjList;
}
function getStateValue(rootNode, stateNodes) {
const config = getAllStateNodes(stateNodes);
return getValueFromAdj(rootNode, getAdjList(config));
}
function isInFinalState(stateNodeSet, stateNode) {
if (stateNode.type === "compound") {
return getChildren(stateNode).some((s) => s.type === "final" && stateNodeSet.has(s));
}
if (stateNode.type === "parallel") {
return getChildren(stateNode).every((sn) => isInFinalState(stateNodeSet, sn));
}
return stateNode.type === "final";
}
var isStateId = (str) => str[0] === STATE_IDENTIFIER;
function getCandidates(stateNode, receivedEventType) {
const exactMatch = stateNode.transitions.get(receivedEventType);
const wildcardCandidates = [...stateNode.transitions.keys()].filter((eventDescriptor) => eventDescriptor !== receivedEventType && matchesEventDescriptor(receivedEventType, eventDescriptor)).sort((a, b) => b.length - a.length).flatMap((key) => stateNode.transitions.get(key));
return exactMatch ? [...exactMatch, ...wildcardCandidates] : wildcardCandidates;
}
function getDelayedTransitions(stateNode) {
const afterConfig = stateNode.config.after;
if (!afterConfig) {
return [];
}
const mutateEntryExit = (delay) => {
const afterEvent = createAfterEvent(delay, stateNode.id);
const eventType = afterEvent.type;
stateNode.entry.push(raise(afterEvent, {
id: eventType,
delay
}));
stateNode.exit.push(cancel(eventType));
return eventType;
};
const delayedTransitions = Object.keys(afterConfig).flatMap((delay) => {
const configTransition = afterConfig[delay];
const resolvedTransition = typeof configTransition === "string" ? {
target: configTransition
} : configTransition;
const resolvedDelay = Number.isNaN(+delay) ? delay : +delay;
const eventType = mutateEntryExit(resolvedDelay);
return toArray(resolvedTransition).map((transition) => ({
...transition,
event: eventType,
delay: resolvedDelay
}));
});
return delayedTransitions.map((delayedTransition) => {
const {
delay
} = delayedTransition;
return {
...formatTransition(stateNode, delayedTransition.event, delayedTransition),
delay
};
});
}
function formatTransition(stateNode, descriptor, transitionConfig) {
const normalizedTarget = normalizeTarget(transitionConfig.target);
const reenter = transitionConfig.reenter ?? false;
const target = resolveTarget(stateNode, normalizedTarget);
const transition = {
...transitionConfig,
actions: toArray(transitionConfig.actions),
guard: transitionConfig.guard,
target,
source: stateNode,
reenter,
eventType: descriptor,
toJSON: () => ({
...transition,
source: #${stateNode.id},
target: target ? target.map((t) => #${t.id}) : void 0
})
};
return transition;
}
function formatTransitions(stateNode) {
const transitions = / @PURE / new Map();
if (stateNode.config.on) {
for (const descriptor of Object.keys(stateNode.config.on)) {
if (descriptor === NULL_EVENT) {
throw new Error('Null events ("") cannot be specified as a transition key. Use always: { ... } instead.');
}
const transitionsConfig = stateNode.config.on[descriptor];
transitions.set(descriptor, toTransitionConfigArray(transitionsConfig).map((t) => formatTransition(stateNode, descriptor, t)));
}
}
if (stateNode.config.onDone) {
const descriptor = xstate.done.state.${stateNode.id};
transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map((t) => formatTransition(stateNode, descriptor, t)));
}
for (const invokeDef of stateNode.invoke) {
if (invokeDef.onDone) {
const descriptor = xstate.done.actor.${invokeDef.id};
transitions.set(descriptor, toTransitionConfigArray(invokeDef.onDone).map((t) => formatTransition(stateNode, descriptor, t)));
}
if (invokeDef.onError) {
const descriptor = xstate.error.actor.${invokeDef.id};
transitions.set(descriptor, toTransitionConfigArray(invokeDef.onError).map((t) => formatTransition(stateNode, descriptor, t)));
}
if (invokeDef.onSnapshot) {
const descriptor = xstate.snapshot.${invokeDef.id};
transitions.set(descriptor, toTransitionConfigArray(invokeDef.onSnapshot).map((t) => formatTransition(stateNode, descriptor, t)));
}
}
for (const delayedTransition of stateNode.after) {
let existing = transitions.get(delayedTransition.eventType);
if (!existing) {
existing = [];
transitions.set(delayedTransition.eventType, existing);
}
existing.push(delayedTransition);
}
return transitions;
}
function formatRouteTransitions(rootStateNode) {
const routeTransitions = [];
const collectRoutes = (states) => {
Object.values(states).forEach((sn) => {
if (sn.config.route && sn.config.id) {
const routeId = sn.config.id;
const userGuard = sn.config.route.guard;
const routeMatches = ({
event
}) => event.to === #${routeId};
const transition = {
...sn.config.route,
guard: userGuard ? and([routeMatches, userGuard]) : routeMatches,
target: #${routeId}
};
routeTransitions.push(formatTransition(rootStateNode, "xstate.route", transition));
}
if (sn.states) {
collectRoutes(sn.states);
}
});
};
collectRoutes(rootStateNode.states);
if (routeTransitions.length > 0) {
rootStateNode.transitions.set("xstate.route", routeTransitions);
}
}
function formatInitialTransition(stateNode, _target) {
const resolvedTarget = typeof _target === "string" ? stateNode.states[_target] : _target ? stateNode.states[_target.target] : void 0;
if (!resolvedTarget && _target) {
throw new Error(
// oxlint-disable-next-line typescript/restrict-template-expressions, typescript/no-base-to-string
Initial state node "${_target}" not found on parent state node #${stateNode.id}
);
}
const transition = {
source: stateNode,
actions: !_target || typeof _target === "string" ? [] : toArray(_target.actions),
eventType: null,
reenter: false,
target: resolvedTarget ? [resolvedTarget] : [],
toJSON: () => ({
...transition,
source: #${stateNode.id},
target: resolvedTarget ? [#${resolvedTarget.id}] : []
})
};
return transition;
}
function resolveTarget(stateNode, targets) {
if (targets === void 0) {
return void 0;
}
return targets.map((target) => {
if (typeof target !== "string") {
return target;
}
if (isStateId(target)) {
return stateNode.machine.getStateNodeById(target);
}
const isInternalTarget = target[0] === STATE_DELIMITER;
if (isInternalTarget && !stateNode.parent) {
return getStateNodeByPath(stateNode, target.slice(1));
}
const resolvedTarget = isInternalTarget ? stateNode.key + target : target;
if (stateNode.parent) {
try {
const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
return targetStateNode;
} catch (err2) {
throw new Error(Invalid transition definition for state node '${stateNode.id}': ${err2.message});
}
} else {
throw new Error(Invalid target: "${target}" is not a valid target from the root node. Did you mean ".${target}"?);
}
});
}
function resolveHistoryDefaultTransition(stateNode) {
const normalizedTarget = normalizeTarget(stateNode.config.target);
if (!normalizedTarget) {
if (stateNode.parent.type === "parallel") {
return {
target: [stateNode.parent]
};
}
return stateNode.parent.initial;
}
return {
target: normalizedTarget.map((t) => typeof t === "string" ? getStateNodeByPath(stateNode.parent, t) : t)
};
}
function isHistoryNode(stateNode) {
return stateNode.type === "history";
}
function getInitialStateNodesWithTheirAncestors(stateNode) {
const states = getInitialStateNodes(stateNode);
for (const initialState of states) {
for (const ancestor of getProperAncestors(initialState, stateNode)) {
states.add(ancestor);
}
}
return states;
}
function getInitialStateNodes(stateNode) {
const set = / @PURE / new Set();
function iter(descStateNode) {
if (set.has(descStateNode)) {
return;
}
set.add(descStateNode);
if (descStateNode.type === "compound") {
iter(descStateNode.initial.target[0]);
} else if (descStateNode.type === "parallel") {
for (const child of getChildren(descStateNode)) {
iter(child);
}
}
}
iter(stateNode);
return set;
}
function getStateNode(stateNode, stateKey) {
if (isStateId(stateKey)) {
return stateNode.machine.getStateNodeById(stateKey);
}
if (!stateNode.states) {
throw new Error(Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.);
}
const result = stateNode.states[stateKey];
if (!result) {
throw new Error(Child state '${stateKey}' does not exist on '${stateNode.id}');
}
return result;
}
function getStateNodeByPath(stateNode, statePath) {
if (typeof statePath === "string" && isStateId(statePath)) {
try {
return stateNode.machine.getStateNodeById(statePath);
} catch {
}
}
const arrayStatePath = toStatePath(statePath).slice();
let currentStateNode = stateNode;
while (arrayStatePath.length) {
const key = arrayStatePath.shift();
if (!key.length) {
break;
}
currentStateNode = getStateNode(currentStateNode, key);
}
return currentStateNode;
}
function getStateNodes(stateNode, stateValue) {
if (typeof stateValue === "string") {
const childStateNode = stateNode.states[stateValue];
if (!childStateNode) {
throw new Error(State '${stateValue}' does not exist on '${stateNode.id}');
}
return [stateNode, childStateNode];
}
const childStateKeys = Object.keys(stateValue);
const childStateNodes = childStateKeys.map((subStateKey) => getStateNode(stateNode, subStateKey)).filter(Boolean);
return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {
const subStateNode = getStateNode(stateNode, subStateKey);
if (!subStateNode) {
return allSubStateNodes;
}
const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);
return allSubStateNodes.concat(subStateNodes);
}, []));
}
function transitionAtomicNode(stateNode, stateValue, snapshot, event) {
const childStateNode = getStateNode(stateNode, stateValue);
const next = childStateNode.next(snapshot, event);
if (!next || !next.length) {
return stateNode.next(snapshot, event);
}
return next;
}
function transitionCompoundNode(stateNode, stateValue, snapshot, event) {
const subStateKeys = Object.keys(stateValue);
const childStateNode = getStateNode(stateNode, subStateKeys[0]);
const next = transitionNode(childStateNode, stateValue[subStateKeys[0]], snapshot, event);
if (!next || !next.length) {
return stateNode.next(snapshot, event);
}
return next;
}
function transitionParallelNode(stateNode, stateValue, snapshot, event) {
const allInnerTransitions = [];
for (const subStateKey of Object.keys(stateValue)) {
const subStateValue = stateValue[subStateKey];
if (!subStateValue) {
continue;
}
const subStateNode = getStateNode(stateNode, subStateKey);
const innerTransitions = transitionNode(subStateNode, subStateValue, snapshot, event);
if (innerTransitions) {
allInnerTransitions.push(...innerTransitions);
}
}
if (!allInnerTransitions.length) {
return stateNode.next(snapshot, event);
}
return allInnerTransitions;
}
function transitionNode(stateNode, stateValue, snapshot, event) {
if (typeof stateValue === "string") {
return transitionAtomicNode(stateNode, stateValue, snapshot, event);
}
if (Object.keys(stateValue).length === 1) {
return transitionCompoundNode(stateNode, stateValue, snapshot, event);
}
return transitionParallelNode(stateNode, stateValue, snapshot, event);
}
function getHistoryNodes(stateNode) {
return Object.keys(stateNode.states).map((key) => stateNode.states[key]).filter((sn) => sn.type === "history");
}
function isDescendant(childStateNode, parentStateNode) {
let marker = childStateNode;
while (marker.parent && marker.parent !== parentStateNode) {
marker = marker.parent;
}
return marker.parent === parentStateNode;
}
function hasIntersection(s1, s2) {
const set1 = new Set(s1);
const set2 = new Set(s2);
for (const item of set1) {
if (set2.has(item)) {
return true;
}
}
for (const item of set2) {
if (set1.has(item)) {
return true;
}
}
return false;
}
function removeConflictingTransitions(enabledTransitions, stateNodeSet, historyValue) {
const filteredTransitions = / @PURE / new Set();
for (const t1 of enabledTransitions) {
let t1Preempted = false;
const transitionsToRemove = / @PURE / new Set();
for (const t2 of filteredTransitions) {
if (hasIntersection(computeExitSet([t1], stateNodeSet, historyValue), computeExitSet([t2], stateNodeSet, historyValue))) {
if (isDescendant(t1.source, t2.source)) {
transitionsToRemove.add(t2);
} else {
t1Preempted = true;
break;
}
}
}
if (!t1Preempted) {
for (const t3 of transitionsToRemove) {
filteredTransitions.delete(t3);
}
filteredTransitions.add(t1);
}
}
return Array.from(filteredTransitions);
}
function findLeastCommonAncestor(stateNodes) {
const [head, ...tail] = stateNodes;
for (const ancestor of getProperAncestors(head, void 0)) {
if (tail.every((sn) => isDescendant(sn, ancestor))) {
return ancestor;
}
}
}
function getEffectiveTargetStates(transition, historyValue) {
if (!transition.target) {
return [];
}
const targets = / @PURE / new Set();
for (const targetNode of transition.target) {
if (isHistoryNode(targetNode)) {
if (historyValue[targetNode.id]) {
for (const node of historyValue[targetNode.id]) {
targets.add(node);
}
} else {
for (const node of getEffectiveTargetStates(resolveHistoryDefaultTransition(targetNode), historyValue)) {
targets.add(node);
}
}
} else {
targets.add(targetNode);
}
}
return [...targets];
}
function getTransitionDomain(transition, historyValue) {
const targetStates = getEffectiveTargetStates(transition, historyValue);
if (!targetStates) {
return;
}
if (!transition.reenter && targetStates.every((target) => target === transition.source || isDescendant(target, transition.source))) {
return transition.source;
}
const lca = findLeastCommonAncestor(targetStates.concat(transition.source));
if (lca) {
return lca;
}
if (transition.reenter) {
return;
}
return transition.source.machine.root;
}
function computeExitSet(transitions, stateNodeSet, historyValue) {
const statesToExit = / @PURE / new Set();
for (const t of transitions) {
if (t.target?.length) {
const domain = getTransitionDomain(t, historyValue);
if (t.reenter && t.source === domain) {
statesToExit.add(domain);
}
for (const stateNode of stateNodeSet) {
if (isDescendant(stateNode, domain)) {
statesToExit.add(stateNode);
}
}
}
}
return [...statesToExit];
}
function areStateNodeCollectionsEqual(prevStateNodes, nextStateNodeSet) {
if (prevStateNodes.length !== nextStateNodeSet.size) {
return false;
}
for (const node of prevStateNodes) {
if (!nextStateNodeSet.has(node)) {
return false;
}
}
return true;
}
function initialMicrostep(root, preInitialState, actorScope, initEvent, internalQueue) {
return microstep([{
target: [...getInitialStateNodes(root)],
source: root,
reenter: true,
actions: [],
eventType: null,
toJSON: null
}], preInitialState, actorScope, initEvent, true, internalQueue);
}
function microstep(transitions, currentSnapshot, actorScope, event, isInitial, internalQueue) {
const actions = [];
if (!transitions.length) {
return [currentSnapshot, actions];
}
const originalExecutor = actorScope.actionExecutor;
actorScope.actionExecutor = (action) => {
actions.push(action);
originalExecutor(action);
};
try {
const mutStateNodeSet = new Set(currentSnapshot._nodes);
let historyValue = currentSnapshot.historyValue;
const filteredTransitions = removeConflictingTransitions(transitions, mutStateNodeSet, historyValue);
let nextState = currentSnapshot;
if (!isInitial) {
[nextState, historyValue] = exitStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, historyValue, internalQueue, actorScope.actionExecutor);
}
nextState = resolveActionsAndContext(nextState, event, actorScope, filteredTransitions.flatMap((t) => t.actions), internalQueue, void 0);
nextState = enterStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial);
const nextStateNodes = [...mutStateNodeSet];
if (nextState.status === "done") {
nextState = resolveActionsAndContext(nextState, event, actorScope, nextStateNodes.sort((a, b) => b.order - a.order).flatMap((state) => state.exit), internalQueue, void 0);
}
try {
if (historyValue === currentSnapshot.historyValue && areStateNodeCollectionsEqual(currentSnapshot._nodes, mutStateNodeSet)) {
return [nextState, actions];
}
return [cloneMachineSnapshot(nextState, {
_nodes: nextStateNodes,
historyValue
}), actions];
} catch (e) {
throw e;
}
} finally {
actorScope.actionExecutor = originalExecutor;
}
}
function getMachineOutput(snapshot, event, actorScope, rootNode, rootCompletionNode) {
if (rootNode.output === void 0) {
return;
}
const doneStateEvent = createDoneStateEvent(rootCompletionNode.id, rootCompletionNode.output !== void 0 && rootCompletionNode.parent ? resolveOutput(rootCompletionNode.output, snapshot.context, event, actorScope.self) : void 0);
return resolveOutput(rootNode.output, snapshot.context, doneStateEvent, actorScope.self);
}
function enterStates(currentSnapshot, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial) {
let nextSnapshot = currentSnapshot;
const statesToEnter = / @PURE / new Set();
const statesForDefaultEntry = / @PURE / new Set();
computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);
if (isInitial) {
statesForDefaultEntry.add(currentSnapshot.machine.root);
}
const completedNodes = / @PURE / new Set();
for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
mutStateNodeSet.add(stateNodeToEnter);
const actions = [];
actions.push(...stateNodeToEnter.entry);
for (const invokeDef of stateNodeToEnter.invoke) {
actions.push(spawnChild(invokeDef.src, {
...invokeDef,
syncSnapshot: !!invokeDef.onSnapshot
}));
}
if (statesForDefaultEntry.has(stateNodeToEnter)) {
const initialActions = stateNodeToEnter.initial.actions;
actions.push(...initialActions);
}
nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, actions, internalQueue, stateNodeToEnter.invoke.map((invokeDef) => invokeDef.id));
if (stateNodeToEnter.type === "final") {
const parent = stateNodeToEnter.parent;
let ancestorMarker = parent?.type === "parallel" ? parent : parent?.parent;
let rootCompletionNode = ancestorMarker || stateNodeToEnter;
if (parent?.type === "compound") {
internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output !== void 0 ? resolveOutput(stateNodeToEnter.output, nextSnapshot.context, event, actorScope.self) : void 0));
}
while (ancestorMarker?.type === "parallel" && !completedNodes.has(ancestorMarker) && isInFinalState(mutStateNodeSet, ancestorMarker)) {
completedNodes.add(ancestorMarker);
internalQueue.push(createDoneStateEvent(ancestorMarker.id));
rootCompletionNode = ancestorMarker;
ancestorMarker = ancestorMarker.parent;
}
if (ancestorMarker) {
continue;
}
nextSnapshot = cloneMachineSnapshot(nextSnapshot, {
status: "done",
output: getMachineOutput(nextSnapshot, event, actorScope, nextSnapshot.machine.root, rootCompletionNode)
});
}
}
return nextSnapshot;
}
function computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {
for (const t of transitions) {
const domain = getTransitionDomain(t, historyValue);
for (const s of t.target || []) {
if (!isHistoryNode(s) && // if the target is different than the source then it will definitely be entered
(t.source !== s || // we know that the domain can't lie within the source
// if it's different than the source then it's outside of it and it means that the target has to be entered as well
t.source !== domain || // reentering transitions always enter the target, even if it's the source itself
t.reenter)) {
statesToEnter.add(s);
statesForDefaultEntry.add(s);
}
addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
}
const targetStates = getEffectiveTargetStates(t, historyValue);
for (const s of targetStates) {
const ancestors = getProperAncestors(s, domain);
if (domain?.type === "parallel") {
ancestors.push(domain);
}
addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, !t.source.parent && t.reenter ? void 0 : domain);
}
}
}
function addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {
if (isHistoryNode(stateNode)) {
if (historyValue[stateNode.id]) {
const historyStateNodes = historyValue[stateNode.id];
for (const s of historyStateNodes) {
statesToEnter.add(s);
addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
}
for (const s of historyStateNodes) {
addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
}
} else {
const historyDefaultTransition = resolveHistoryDefaultTransition(stateNode);
for (const s of historyDefaultTransition.target) {
statesToEnter.add(s);
if (historyDefaultTransition === stateNode.parent?.initial) {
statesForDefaultEntry.add(stateNode.parent);
}
addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
}
for (const s of historyDefaultTransition.target) {
addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
}
}
} else {
if (stateNode.type === "compound") {
const [initialState] = stateNode.initial.target;
if (!isHistoryNode(initialState)) {
statesToEnter.add(initialState);
statesForDefaultEntry.add(initialState);
}
addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);
addProperAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
} else {
if (stateNode.type === "parallel") {
for (const child of getChildren(stateNode).filter((sn) => !isHistoryNode(sn))) {
if (![...statesToEnter].some((s) => isDescendant(s, child))) {
if (!isHistoryNode(child)) {
statesToEnter.add(child);
statesForDefaultEntry.add(child);
}
addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
}
}
}
}
}
}
function addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, reentrancyDomain) {
for (const anc of ancestors) {
if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {
statesToEnter.add(anc);
}
if (anc.type === "parallel") {
for (const child of getChildren(anc).filter((sn) => !isHistoryNode(sn))) {
if (![...statesToEnter].some((s) => isDescendant(s, child))) {
statesToEnter.add(child);
addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
}
}
}
}
}
function addProperAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {
addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, getProperAncestors(stateNode, toStateNode));
}
function exitStates(currentSnapshot, event, actorScope, transitions, mutStateNodeSet, historyValue, internalQueue, _actionExecutor) {
let nextSnapshot = currentSnapshot;
const statesToExit = computeExitSet(transitions, mutStateNodeSet, historyValue);
statesToExit.sort((a, b) => b.order - a.order);
let changedHistory;
for (const exitStateNode of statesToExit) {
for (const historyNode of getHistoryNodes(exitStateNode)) {
let predicate;
if (historyNode.history === "deep") {
predicate = (sn) => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);
} else {
predicate = (sn) => {
return sn.parent === exitStateNode;
};
}
changedHistory ??= {
...historyValue
};
changedHistory[historyNode.id] = Array.from(mutStateNodeSet).filter(predicate);
}
}
for (const s of statesToExit) {
nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, [...s.exit, ...s.invoke.map((def) => stopChild(def.id))], internalQueue, void 0);
mutStateNodeSet.delete(s);
}
return [nextSnapshot, changedHistory || historyValue];
}
function getAction(machine, actionType) {
return machine.implementations.actions[actionType];
}
function resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, extra, retries) {
const {
machine
} = currentSnapshot;
let intermediateSnapshot = currentSnapshot;
for (const action of actions) {
const isInline = typeof action === "function";
const resolvedAction = isInline ? action : (
// the existing type of .actions assumes non-nullable TExpressionAction
// it's fine to cast this here to get a common type and lack of errors in the rest of the code
// our logic below makes sure that we call those 2 "variants" correctly
getAction(machine, typeof action === "string" ? action : action.type)
);
const actionArgs = {
context: intermediateSnapshot.context,
event,
self: actorScope.self,
system: actorScope.system
};
const actionParams = isInline || typeof action === "string" ? void 0 : "params" in action ? typeof action.params === "function" ? action.params({
context: intermediateSnapshot.context,
event
}) : action.params : void 0;
if (!resolvedAction || !("resolve" in resolvedAction)) {
actorScope.actionExecutor({
type: typeof action === "string" ? action : typeof action === "object" ? action.type : action.name || "(anonymous)",
info: actionArgs,
params: actionParams,
exec: resolvedAction
});
continue;
}
const builtinAction = resolvedAction;
const [nextState, params, actions2] = builtinAction.resolve(
actorScope,
intermediateSnapshot,
actionArgs,
actionParams,
resolvedAction,
// this holds all params
extra
);
intermediateSnapshot = nextState;
if ("retryResolve" in builtinAction) {
retries?.push([builtinAction, params]);
}
if ("execute" in builtinAction) {
actorScope.actionExecutor({
type: builtinAction.type,
info: actionArgs,
params,
exec: builtinAction.execute.bind(null, actorScope, params)
});
}
if (actions2) {
intermediateSnapshot = resolveAndExecuteActionsWithContext(intermediateSnapshot, event, actorScope, actions2, extra, retries);
}
}
return intermediateSnapshot;
}
function resolveActionsAndContext(currentSnapshot, event, actorScope, actions, internalQueue, deferredActorIds) {
const retries = deferredActorIds ? [] : void 0;
const nextState = resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, {
internalQueue,
deferredActorIds
}, retries);
retries?.forEach(([builtinAction, params]) => {
builtinAction.retryResolve(actorScope, nextState, params);
});
return nextState;
}
function macrostep(snapshot, event, actorScope, internalQueue) {
let nextSnapshot = snapshot;
const microsteps = [];
function addMicrostep(step, event2, transitions) {
actorScope.system._sendInspectionEvent({
type: "@xstate.microstep",
actorRef: actorScope.self,
event: event2,
snapshot: step[0],
_transitions: transitions
});
microsteps.push(step);
}
if (event.type === XSTATE_STOP) {
nextSnapshot = cloneMachineSnapshot(stopChildren(nextSnapshot, event, actorScope), {
status: "stopped"
});
addMicrostep([nextSnapshot, []], event, []);
return {
snapshot: nextSnapshot,
microsteps
};
}
let nextEvent = event;
if (nextEvent.type !== XSTATE_INIT) {
const currentEvent = nextEvent;
const isErr = isErrorActorEvent(currentEvent);
const transitions = selectTransitions(currentEvent, nextSnapshot);
if (isErr && !transitions.length) {
nextSnapshot = cloneMachineSnapshot(snapshot, {
status: "error",
error: currentEvent.error
});
addMicrostep([nextSnapshot, []], currentEvent, []);
return {
snapshot: nextSnapshot,
microsteps
};
}
const step = microstep(
transitions,
snapshot,
actorScope,
nextEvent,
false,
// isInitial
internalQueue
);
nextSnapshot = step[0];
addMicrostep(step, currentEvent, transitions);
}
let shouldSelectEventlessTransitions = true;
const maxIterations = snapshot.machine.options?.maxIterations ?? Infinity;
let iterationCount = 0;
while (nextSnapshot.status === "active") {
iterationCount++;
if (iterationCount > maxIterations) {
throw new Error(Infinite loop detected: the machine has processed more than ${maxIterations} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).);
}
let enabledTransitions = shouldSelectEventlessTransitions ? selectEventlessTransitions(nextSnapshot, nextEvent) : [];
const previousState = enabledTransitions.length ? nextSnapshot : void 0;
if (!enabledTransitions.length) {
if (!internalQueue.length) {
break;
}
nextEvent = internalQueue.shift();
enabledTransitions = selectTransitions(nextEvent, nextSnapshot);
}
const step = microstep(enabledTransitions, nextSnapshot, actorScope, nextEvent, false, internalQueue);
nextSnapshot = step[0];
shouldSelectEventlessTransitions = nextSnapshot !== previousState;
addMicrostep(step, nextEvent, enabledTransitions);
}
if (nextSnapshot.status !== "active") {
stopChildren(nextSnapshot, nextEvent, actorScope);
}
return {
snapshot: nextSnapshot,
microsteps
};
}
function stopChildren(nextState, event, actorScope) {
return resolveActionsAndContext(nextState, event, actorScope, Object.values(nextState.children).map((child) => stopChild(child)), [], void 0);
}
function selectTransitions(event, nextState) {
return nextState.machine.getTransitionData(nextState, event);
}
function selectEventlessTransitions(nextState, event) {
const enabledTransitionSet = / @PURE */ new Set();
const atomicStates = nextState._nodes.filter(isAtomicStateNode);
for (const stateNode of atomicStates) {
loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, void 0))) {
if (!s.always) {
continue;
}
for (const transition of s.always) {
if (transition.guard === void 0 || evaluateGuard(transition.guard, nextState.context, event, nextState)) {
enabledTransitionSet.add(transition);
break loop;
}
}
}
}
return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState._nodes), nextState.historyValue);
}
function resolveStateValue(rootNode, stateValue) {
const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));
return getStateValue(rootNode, [...allStateNodes]);
}
function isMachineSnapshot(value) {
return !!value && typeof value === "object" && "machine" in value && "value" in value;
}
var machineSnapshotMatches = function matches(testValue) {
return matchesState(testValue, this.value);
};
var machineSnapshotHasTag = function hasTag(tag) {
return this.tags.has(tag);
};
var machineSnapshotCan = function can(event) {
const transitionData = this.machine.getTransitionData(this, event);
return !!transitionData?.length && // Check that at least one transition is not forbidden
transitionData.some((t) => t.target !== void 0 || t.actions.length);
};
var machineSnapshotToJSON = function toJSON() {
const {
_nodes: nodes,
tags,
machine,
getMeta: getMeta2,
toJSON: toJSON2,
can: can2,
hasTag: hasTag2,
matches: matches2,
...jsonValues
} = this;
return {
...jsonValues,
tags: Array.from(tags)
};
};
var machineSnapshotGetMeta = function getMeta() {
return this._nodes.reduce((acc, stateNode) => {
if (stateNode.meta !== void 0) {
acc[stateNode.id] = stateNode.meta;
}
return acc;
}, {});
};
function createMachineSnapshot(config, machine) {
return {
status: config.status,
output: config.output,
error: config.error,
machine,
context: config.context,
_nodes: config._nodes,
value: getStateValue(machine.root, config._nodes),
tags: new Set(config._nodes.flatMap((sn) => sn.tags)),
children: config.children,
historyValue: config.historyValue || {},
matches: machineSnapshotMatches,
hasTag: machineSnapshotHasTag,
can: machineSnapshotCan,
getMeta: machineSnapshotGetMeta,
toJSON: machineSnapshotToJSON
};
}
function cloneMachineSnapshot(snapshot, config = {}) {
return createMachineSnapshot({
...snapshot,
...config
}, snapshot.machine);
}
function serializeHistoryValue(historyValue) {
if (typeof historyValue !== "object" || historyValue === null) {
return {};
}
const result = {};
for (const key in historyValue) {
const value = historyValue[key];
if (Array.isArray(value)) {
result[key] = value.map((item) => ({
id: item.id
}));
}
}
return result;
}
function getPersistedSnapshot(snapshot, options) {
const {
_nodes: nodes,
tags,
machine,
children,
context,
can: can2,
hasTag: hasTag2,
matches: matches2,
getMeta: getMeta2,
toJSON: toJSON2,
...jsonValues
} = snapshot;
const childrenJson = {};
for (const id in children) {
const child = children[id];
childrenJson[id] = {
snapshot: child.getPersistedSnapshot(options),
src: child.src,
systemId: child.systemId,
syncSnapshot: child.syncSnapshot
};
}
const persisted = {
...jsonValues,
context: persistContext(context),
children: childrenJson,
historyValue: serializeHistoryValue(jsonValues.historyValue)
};
return persisted;
}
function persistContext(contextPart) {
let copy;
for (const key in contextPart) {
const value = contextPart[key];
if (value && typeof value === "object") {
if ("sessionId" in value && "send" in value && "ref" in value) {
copy ??= Array.isArray(contextPart) ? contextPart.slice() : {
...contextPart
};
copy[key] = {
xstate$type: $ACTOR_TYPE,
id: value.id
};
} else {
const result = persistContext(value);
if (result !== value) {
copy ??= Array.isArray(contextPart) ? contextPart.slice() : {
...contextPart
};
copy[key] = result;
}
}
}
}
return copy ?? contextPart;
}
function resolveRaise(, snapshot, args, actionParams, {
event: eventOrExpr,
id,
delay
}, {
internalQueue
}) {
const delaysMap = snapshot.machine.implementations.delays;
if (typeof eventOrExpr === "string") {
throw new Error(
// oxlint-disable-next-line typescript/restrict-template-expressions
Only event objects may be used with raise; use raise({ type: "${eventOrExpr}" }) instead
);
}
const resolvedEvent = typeof eventOrExpr === "function" ? eventOrExpr(args, actionParams) : eventOrExpr;
let resolvedDelay;
if (typeof delay === "string") {
const configDelay = delaysMap && delaysMap[delay];
resolvedDelay = typeof configDelay === "function" ? configDelay(args, actionParams) : configDelay;
} else {
resolvedDelay = typeof delay === "function" ? delay(args, actionParams) : delay;
}
if (typeof resolvedDelay !== "number") {
internalQueue.push(resolvedEvent);
}
return [snapshot, {
event: resolvedEvent,
id,
delay: resolvedDelay
}, void 0];
}
function executeRaise(actorScope, params) {
const {
event,
delay,
id
} = params;
if (typeof delay === "number") {
actorScope.defer(() => {
const self2 = actorScope.self;
actorScope.system.scheduler.schedule(self2, self2, event, delay, id);
});
return;
}
}
function raise(eventOrExpr, options) {
function raise2(_args, _params) {
}
raise2.type = "xstate.raise";
raise2.event = eventOrExpr;
raise2.id = options?.id;
raise2.delay = options?.delay;
raise2.resolve = resolveRaise;
raise2.execute = executeRaise;
return raise2;
}
// ../../node_modules/xstate/dist/xstate-actors.esm.js function fromTransition(transition, initialContext) { return { config: transition, transition: (snapshot, event, actorScope) => { return { ...snapshot, context: transition(snapshot.context, event, actorScope) }; }, getInitialSnapshot: (_, input) => { return { status: "active", output: void 0, error: void 0, context: typeof initialContext === "function" ? initialContext({ input }) : initialContext }; }, getPersistedSnapshot: (snapshot) => snapshot, restoreSnapshot: (snapshot) => snapshot }; } var XSTATE_PROMISE_RESOLVE = "xstate.promise.resolve"; var XSTATE_PROMISE_REJECT = "xstate.promise.reject"; var controllerMap = /* @PURE */ new WeakMap(); function fromPromise(promiseCreator) { const logic = { config: promiseCreator, transition: (state, event, scope) => { if (state.status !== "active") { return state; } switch (event.type) { case XSTATE_PROMISE_RESOLVE: { const resolvedValue = event.data; return { ...state, status: "done", output: resolvedValue, input: void 0 }; } case XSTATE_PROMISE_REJECT: return { ...state, status: "error", error: event.data, input: void 0 }; case XSTATE_STOP: { controllerMap.get(scope.self)?.abort(); controllerMap.delete(scope.self); return { ...state, status: "stopped", input: void 0 }; } default: return state; } }, start: (state, { self: self2, system, emit: emit2 }) => { if (state.status !== "active") { return; } const controller = new AbortController(); controllerMap.set(self2, controller); const resolvedPromise = Promise.resolve(promiseCreator({ input: state.input, system, self: self2, signal: controller.signal, emit: emit2 })); resolvedPromise.then((response) => { if (self2.getSnapshot().status !== "active") { return; } controllerMap.delete(self2); system.relay(self2, self2, { type: XSTATE_PROMISE_RESOLVE, data: response }); }, (errorData) => { if (self2.getSnapshot().status !== "active") { return; } controllerMap.delete(self2); system.relay(self2, self2, { type: XSTATE_PROMISE_REJECT, data: errorData }); }); }, getInitialSnapshot: (, input) => { return { status: "active", output: void 0, error: void 0, input }; }, getPersistedSnapshot: (snapshot) => snapshot, restoreSnapshot: (snapshot) => snapshot }; return logic; } var emptyLogic = fromTransition(() => void 0, void 0);
// ../../node_modules/xstate/dist/assign-54f9e2d3.esm.js
function createSpawner(actorScope, {
machine,
context
}, event, spawnedChildren) {
const spawn = (src, options) => {
if (typeof src === "string") {
const logic = resolveReferencedActor(machine, src);
if (!logic) {
throw new Error(Actor logic '${src}' not implemented in machine '${machine.id}');
}
const actorRef = createActor(logic, {
id: options?.id,
parent: actorScope.self,
syncSnapshot: options?.syncSnapshot,
input: typeof options?.input === "function" ? options.input({
context,
event,
self: actorScope.self
}) : options?.input,
src,
systemId: options?.systemId
});
spawnedChildren[actorRef.id] = actorRef;
return actorRef;
} else {
const actorRef = createActor(src, {
id: options?.id,
parent: actorScope.self,
syncSnapshot: options?.syncSnapshot,
input: options?.input,
src,
systemId: options?.systemId
});
return actorRef;
}
};
return (src, options) => {
const actorRef = spawn(src, options);
spawnedChildren[actorRef.id] = actorRef;
actorScope.defer(() => {
if (actorRef._processingStatus === ProcessingStatus.Stopped) {
return;
}
actorRef.start();
});
return actorRef;
};
}
function resolveAssign(actorScope, snapshot, actionArgs, actionParams, {
assignment
}) {
if (!snapshot.context) {
throw new Error("Cannot assign to undefined context. Ensure that context is defined in the machine config.");
}
const spawnedChildren = {};
const assignArgs = {
context: snapshot.context,
event: actionArgs.event,
spawn: createSpawner(actorScope, snapshot, actionArgs.event, spawnedChildren),
self: actorScope.self,
system: actorScope.system
};
let partialUpdate = {};
if (typeof assignment === "function") {
partialUpdate = assignment(assignArgs, actionParams);
} else {
for (const key of Object.keys(assignment)) {
const propAssignment = assignment[key];
partialUpdate[key] = typeof propAssignment === "function" ? propAssignment(assignArgs, actionParams) : propAssignment;
}
}
const updatedContext = Object.assign({}, snapshot.context, partialUpdate);
return [cloneMachineSnapshot(snapshot, {
context: updatedContext,
children: Object.keys(spawnedChildren).length ? {
...snapshot.children,
...spawnedChildren
} : snapshot.children
}), void 0, void 0];
}
function assign(assignment) {
function assign2(_args, _params) {
}
assign2.type = "xstate.assign";
assign2.assignment = assignment;
assign2.resolve = resolveAssign;
return assign2;
}
// ../../node_modules/xstate/dist/StateMachine-28a9f50e.esm.js
var cache = /* @PURE / new WeakMap();
function memo(object, key, fn) {
let memoizedData = cache.get(object);
if (!memoizedData) {
memoizedData = {
[key]: fn()
};
cache.set(object, memoizedData);
} else if (!(key in memoizedData)) {
memoizedData[key] = fn();
}
return memoizedData[key];
}
var EMPTY_OBJECT = {};
var toSerializableAction = (action) => {
if (typeof action === "string") {
return {
type: action
};
}
if (typeof action === "function") {
if ("resolve" in action) {
return {
type: action.type
};
}
return {
type: action.name
};
}
return action;
};
var StateNode = class _StateNode {
constructor(config, options) {
this.config = config;
this.key = void 0;
this.id = void 0;
this.type = void 0;
this.path = void 0;
this.states = void 0;
this.history = void 0;
this.entry = void 0;
this.exit = void 0;
this.parent = void 0;
this.machine = void 0;
this.meta = void 0;
this.output = void 0;
this.order = -1;
this.description = void 0;
this.tags = [];
this.transitions = void 0;
this.always = void 0;
this.parent = options._parent;
this.key = options._key;
this.machine = options._machine;
this.path = this.parent ? this.parent.path.concat(this.key) : [];
this.id = this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);
this.type = this.config.type || (this.config.states && Object.keys(this.config.states).length ? "compound" : this.config.history ? "history" : "atomic");
this.description = this.config.description;
this.order = this.machine.idMap.size;
this.machine.idMap.set(this.id, this);
this.states = this.config.states ? mapValues(this.config.states, (stateConfig, key) => {
const stateNode = new _StateNode(stateConfig, {
_parent: this,
_key: key,
_machine: this.machine
});
return stateNode;
}) : EMPTY_OBJECT;
if (this.type === "compound" && !this.config.initial) {
throw new Error(No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.);
}
this.history = this.config.history === true ? "shallow" : this.config.history || false;
this.entry = toArray(this.config.entry).slice();
this.exit = toArray(this.config.exit).slice();
this.meta = this.config.meta;
this.output = this.type === "final" || !this.parent ? this.config.output : void 0;
this.tags = toArray(config.tags).slice();
}
/* @internal /
_initialize() {
this.transitions = formatTransitions(this);
if (this.config.always) {
this.always = toTransitionConfigArray(this.config.always).map((t) => formatTransition(this, NULL_EVENT, t));
}
Object.keys(this.states).forEach((key) => {
this.states[key]._initialize();
});
}
/* The well-structured state node definition. /
get definition() {
return {
id: this.id,
key: this.key,
version: this.machine.version,
type: this.type,
initial: this.initial ? {
target: this.initial.target,
source: this,
actions: this.initial.actions.map(toSerializableAction),
eventType: null,
reenter: false,
toJSON: () => ({
target: this.initial.target.map((t) => #${t.id}),
source: #${this.id},
actions: this.initial.actions.map(toSerializableAction),
eventType: null
})
} : void 0,
history: this.history,
states: mapValues(this.states, (state) => {
return state.definition;
}),
on: this.on,
transitions: [...this.transitions.values()].flat().map((t) => ({
...t,
actions: t.actions.map(toSerializableAction)
})),
entry: this.entry.map(toSerializableAction),
exit: this.exit.map(toSerializableAction),
meta: this.meta,
order: this.order || -1,
output: this.output,
invoke: this.invoke,
description: this.description,
tags: this.tags
};
}
/* @internal /
toJSON() {
return this.definition;
}
/* The logic invoked as actors by this state node. /
get invoke() {
return memo(this, "invoke", () => toArray(this.config.invoke).map((invokeConfig, i) => {
const {
src,
systemId
} = invokeConfig;
const resolvedId = invokeConfig.id ?? createInvokeId(this.id, i);
const sourceName = typeof src === "string" ? src : xstate.invoke.${createInvokeId(this.id, i)};
return {
...invokeConfig,
src: sourceName,
id: resolvedId,
systemId,
toJSON() {
const {
onDone,
onError,
...invokeDefValues
} = invokeConfig;
return {
...invokeDefValues,
type: "xstate.invoke",
src: sourceName,
id: resolvedId
};
}
};
}));
}
/* The mapping of events to transitions. /
get on() {
return memo(this, "on", () => {
const transitions = this.transitions;
return [...transitions].flatMap(([descriptor, t]) => t.map((t2) => [descriptor, t2])).reduce((map, [descriptor, transition]) => {
map[descriptor] = map[descriptor] || [];
map[descriptor].push(transition);
return map;
}, {});
});
}
get after() {
return memo(this, "delayedTransitions", () => getDelayedTransitions(this));
}
get initial() {
return memo(this, "initial", () => formatInitialTransition(this, this.config.initial));
}
/* @internal /
next(snapshot, event) {
const eventType = event.type;
const actions = [];
let selectedTransition;
const candidates = memo(this, candidates-${eventType}, () => getCandidates(this, eventType));
for (const candidate of candidates) {
const {
guard
} = candidate;
const resolvedContext = snapshot.context;
let guardPassed = false;
try {
guardPassed = !guard || evaluateGuard(guard, resolvedContext, event, snapshot);
} catch (err2) {
const guardType = typeof guard === "string" ? guard : typeof guard === "object" ? guard.type : void 0;
throw new Error(Unable to evaluate guard ${guardType ? '${guardType}' : ""}in transition for event '${eventType}' in state node '${this.id}': ${err2.message});
}
if (guardPassed) {
actions.push(...candidate.actions);
selectedTransition = candidate;
break;
}
}
return selectedTransition ? [selectedTransition] : void 0;
}
/* All the event types accepted by this state node and its descendants. /
get events() {
return memo(this, "events", () => {
const {
states
} = this;
const events = new Set(this.ownEvents);
if (states) {
for (const stateId of Object.keys(states)) {
const state = states[stateId];
if (state.states) {
for (const event of state.events) {
events.add(${event});
}
}
}
}
return Array.from(events);
});
}
/*
* All the events that have transitions directly from this state node.
*
* Excludes any inert events.
/
get ownEvents() {
const keys = Object.keys(Object.fromEntries(this.transitions));
const events = new Set(keys.filter((descriptor) => {
return this.transitions.get(descriptor).some((transition) => !(!transition.target && !transition.actions.length && !transition.reenter));
}));
return Array.from(events);
}
};
var STATE_IDENTIFIER2 = "#";
var StateMachine = class _StateMachine {
constructor(config, implementations) {
this.config = config;
this.version = void 0;
this.schemas = void 0;
this.implementations = void 0;
this.options = void 0;
this.__xstatenode = true;
this.idMap = / @PURE / new Map();
this.root = void 0;
this.id = void 0;
this.states = void 0;
this.events = void 0;
this.id = config.id || "(machine)";
this.implementations = {
actors: implementations?.actors ?? {},
actions: implementations?.actions ?? {},
delays: implementations?.delays ?? {},
guards: implementations?.guards ?? {}
};
this.version = this.config.version;
this.schemas = this.config.schemas;
this.options = {
maxIterations: Infinity,
...this.config.options
};
this.transition = this.transition.bind(this);
this.getInitialSnapshot = this.getInitialSnapshot.bind(this);
this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);
this.restoreSnapshot = this.restoreSnapshot.bind(this);
this.start = this.start.bind(this);
this.root = new StateNode(config, {
_key: this.id,
_machine: this
});
this.root._initialize();
formatRouteTransitions(this.root);
this.states = this.root.states;
this.events = this.root.events;
}
/*
* Clones this state machine with the provided implementations.
*
* @param implementations Options (actions, guards, actors, delays) to
* recursively merge with the existing options.
* @returns A new StateMachine instance with the provided implementations.
/
provide(implementations) {
const {
actions,
guards,
actors,
delays
} = this.implementations;
return new _StateMachine(this.config, {
actions: {
...actions,
...implementations.actions
},
guards: {
...guards,
...implementations.guards
},
actors: {
...actors,
...implementations.actors
},
delays: {
...delays,
...implementations.delays
}
});
}
resolveState(config) {
const resolvedStateValue = resolveStateValue(this.root, config.value);
const nodeSet = getAllStateNodes(getStateNodes(this.root, resolvedStateValue));
return createMachineSnapshot({
_nodes: [...nodeSet],
context: config.context || {},
children: {},
status: isInFinalState(nodeSet, this.root) ? "done" : config.status || "active",
output: config.output,
error: config.error,
historyValue: config.historyValue
}, this);
}
/*
* Determines the next snapshot given the current snapshot and received
* event. Calculates a full macrostep from all microsteps.
*
* @param snapshot The current snapshot
* @param event The received event
/
transition(snapshot, event, actorScope) {
return macrostep(snapshot, event, actorScope, []).snapshot;
}
/*
* Determines the next state given the current state and event. Calculates
* a microstep.
*
* @param state The current state
* @param event The received event
/
microstep(snapshot, event, actorScope) {
return macrostep(snapshot, event, actorScope, []).microsteps.map(([s]) => s);
}
getTransitionData(snapshot, event) {
return transitionNode(this.root, snapshot.value, snapshot, event) || [];
}
/*
* The initial state before evaluating any microsteps. This "pre-initial"
* state is provided to initial actions executed in the initial state.
*
* @internal
/
_getPreInitialState(actorScope, initEvent, internalQueue) {
const {
context
} = this.config;
const preInitial = createMachineSnapshot({
context: typeof context !== "function" && context ? context : {},
_nodes: [this.root],
children: {},
status: "active"
}, this);
if (typeof context === "function") {
const assignment = ({
spawn,
event,
self: self2
}) => context({
spawn,
input: event.input,
self: self2
});
return resolveActionsAndContext(preInitial, initEvent, actorScope, [assign(assignment)], internalQueue, void 0);
}
return preInitial;
}
/*
* Returns the initial State instance, with reference to self as an
* ActorRef.
/
getInitialSnapshot(actorScope, input) {
const initEvent = createInitEvent(input);
const internalQueue = [];
let snapshot = createMachineSnapshot({
context: typeof this.config.context !== "function" && this.config.context ? this.config.context : {},
_nodes: [this.root],
children: {},
status: "active"
}, this);
try {
snapshot = this._getPreInitialState(actorScope, initEvent, internalQueue);
const [nextState] = initialMicrostep(this.root, snapshot, actorScope, initEvent, internalQueue);
const {
snapshot: macroState
} = macrostep(nextState, initEvent, actorScope, internalQueue);
return macroState;
} catch (error) {
return cloneMachineSnapshot(snapshot, {
status: "error",
error
});
}
}
start(snapshot) {
Object.values(snapshot.children).forEach((child) => {
if (child.getSnapshot().status === "active") {
child.start();
}
});
}
getStateNodeById(stateId) {
const fullPath = toStatePath(stateId);
const relativePath = fullPath.slice(1);
const resolvedStateId = isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER2.length) : fullPath[0];
const stateNode = this.idMap.get(resolvedStateId);
if (!stateNode) {
throw new Error(Child state node '#${resolvedStateId}' does not exist on machine '${this.id}');
}
return getStateNodeByPath(stateNode, relativePath);
}
get definition() {
return this.root.definition;
}
toJSON() {
return this.definition;
}
getPersistedSnapshot(snapshot, options) {
return getPersistedSnapshot(snapshot, options);
}
restoreSnapshot(snapshot, _actorScope) {
const children = {};
const snapshotChildren = snapshot.children;
Object.keys(snapshotChildren).forEach((actorId) => {
const actorData = snapshotChildren[actorId];
const childState = actorData.snapshot;
const src = actorData.src;
const logic = typeof src === "string" ? resolveReferencedActor(this, src) : src;
if (!logic) {
return;
}
const actorRef = createActor(logic, {
id: actorId,
parent: _actorScope.self,
syncSnapshot: actorData.syncSnapshot,
snapshot: childState,
src,
systemId: actorData.systemId
});
children[actorId] = actorRef;
});
function resolveHistoryReferencedState(root, referenced) {
if (referenced instanceof StateNode) {
return referenced;
}
try {
return root.machine.getStateNodeById(referenced.id);
} catch {
}
}
function reviveHistoryValue(root, historyValue) {
if (!historyValue || typeof historyValue !== "object") {
return {};
}
const revived = {};
for (const key in historyValue) {
const arr = historyValue[key];
for (const item of arr) {
const resolved = resolveHistoryReferencedState(root, item);
if (!resolved) {
continue;
}
revived[key] ??= [];
revived[key].push(resolved);
}
}
return revived;
}
const revivedHistoryValue = reviveHistoryValue(this.root, snapshot.historyValue);
const restoredSnapshot = createMachineSnapshot({
...snapshot,
children,
_nodes: Array.from(getAllStateNodes(getStateNodes(this.root, snapshot.value))),
historyValue: revivedHistoryValue
}, this);
const seen = / @PURE */ new Set();
function reviveContext(contextPart, children2) {
if (seen.has(contextPart)) {
return;
}
seen.add(contextPart);
for (const key in contextPart) {
const value = contextPart[key];
if (value && typeof value === "object") {
if ("xstate$type" in value && value.xstatetype === $ACTOR_TYPE) {
contextPart[key] = children2[value.id];
continue;
}
reviveContext(value, children2);
}
}
}
reviveContext(restoredSnapshot.context, children);
return restoredSnapshot;
}
};
// ../../node_modules/xstate/dist/log-66075555.esm.js
function resolveEmit(_, snapshot, args, actionParams, {
event: eventOrExpr
}) {
const resolvedEvent = typeof eventOrExpr === "function" ? eventOrExpr(args, actionParams) : eventOrExpr;
return [snapshot, {
event: resolvedEvent
}, void 0];
}
function executeEmit(actorScope, {
event
}) {
actorScope.defer(() => actorScope.emit(event));
}
function emit(eventOrExpr) {
function emit2(_args, _params) {
}
emit2.type = "xstate.emit";
emit2.event = eventOrExpr;
emit2.resolve = resolveEmit;
emit2.execute = executeEmit;
return emit2;
}
var SpecialTargets = /* @PURE */ (function(SpecialTargets2) {
SpecialTargets2["Parent"] = "#_parent";
SpecialTargets2["Internal"] = "#internal";
return SpecialTargets2;
})({});
function resolveSendTo(actorScope, snapshot, args, actionParams, {
to,
event: eventOrExpr,
id,
delay
}, extra) {
const delaysMap = snapshot.machine.implementations.delays;
if (typeof eventOrExpr === "string") {
throw new Error(
// oxlint-disable-next-line typescript/restrict-template-expressions
Only event objects may be used with sendTo; use sendTo({ type: "${eventOrExpr}" }) instead
);
}
const resolvedEvent = typeof eventOrExpr === "function" ? eventOrExpr(args, actionParams) : eventOrExpr;
let resolvedDelay;
if (typeof delay === "string") {
const configDelay = delaysMap && delaysMap[delay];
resolvedDelay = typeof configDelay === "function" ? configDelay(args, actionParams) : configDelay;
} else {
resolvedDelay = typeof delay === "function" ? delay(args, actionParams) : delay;
}
const resolvedTarget = typeof to === "function" ? to(args, actionParams) : to;
let targetActorRef;
if (typeof resolvedTarget === "string") {
if (resolvedTarget === SpecialTargets.Parent) {
targetActorRef = actorScope.self.parent;
} else if (resolvedTarget === SpecialTargets.Internal) {
targetActorRef = actorScope.self;
} else if (resolvedTarget.startsWith("#")) {
targetActorRef = snapshot.children[resolvedTarget.slice(2)];
} else {
targetActorRef = extra.deferredActorIds?.includes(resolvedTarget) ? resolvedTarget : snapshot.children[resolvedTarget];
}
if (!targetActorRef) {
throw new Error(Unable to send event to actor '${resolvedTarget}' from machine '${snapshot.machine.id}'.);
}
} else {
targetActorRef = resolvedTarget || actorScope.self;
}
return [snapshot, {
to: targetActorRef,
targetId: typeof resolvedTarget === "string" ? resolvedTarget : void 0,
event: resolvedEvent,
id,
delay: resolvedDelay
}, void 0];
}
function retryResolveSendTo(, snapshot, params) {
if (typeof params.to === "string") {
params.to = snapshot.children[params.to];
}
}
function executeSendTo(actorScope, params) {
actorScope.defer(() => {
const {
to,
event,
delay,
id
} = params;
if (typeof delay === "number") {
actorScope.system.scheduler.schedule(actorScope.self, to, event, delay, id);
return;
}
actorScope.system._relay(
actorScope.self,
// at this point, in a deferred task, it should already be mutated by retryResolveSendTo
// if it initially started as a string
to,
event.type === XSTATE_ERROR ? createErrorActorEvent(actorScope.self.id, event.data) : event
);
});
}
function sendTo(to, eventOrExpr, options) {
function sendTo2(_args, _params) {
}
sendTo2.type = "xstate.sendTo";
sendTo2.to = to;
sendTo2.event = eventOrExpr;
sendTo2.id = options?.id;
sendTo2.delay = options?.delay;
sendTo2.resolve = resolveSendTo;
sendTo2.retryResolve = retryResolveSendTo;
sendTo2.execute = executeSendTo;
return sendTo2;
}
function sendParent(event, options) {
return sendTo(SpecialTargets.Parent, event, options);
}
function resolveEnqueueActions(actorScope, snapshot, args, actionParams, {
collect
}) {
const actions = [];
const enqueue = function enqueue2(action) {
actions.push(action);
};
enqueue.assign = (...args2) => {
actions.push(assign(...args2));
};
enqueue.cancel = (...args2) => {
actions.push(cancel(...args2));
};
enqueue.raise = (...args2) => {
actions.push(raise(...args2));
};
enqueue.sendTo = (...args2) => {
actions.push(sendTo(...args2));
};
enqueue.sendParent = (...args2) => {
actions.push(sendParent(...args2));
};
enqueue.spawnChild = (...args2) => {
actions.push(spawnChild(...args2));
};
enqueue.stopChild = (...args2) => {
actions.push(stopChild(...args2));
};
enqueue.emit = (...args2) => {
actions.push(emit(...args2));
};
collect({
context: args.context,
event: args.event,
enqueue,
check: (guard) => evaluateGuard(guard, snapshot.context, args.event, snapshot),
self: actorScope.self,
system: actorScope.system
}, actionParams);
return [snapshot, void 0, actions];
}
function enqueueActions(collect) {
function enqueueActions2(_args, params) {
}
enqueueActions2.type = "xstate.enqueueActions";
enqueueActions2.collect = collect;
enqueueActions2.resolve = resolveEnqueueActions;
return enqueueActions2;
}
function resolveLog(, snapshot, actionArgs, actionParams, {
value,
label
}) {
return [snapshot, {
value: typeof value === "function" ? value(actionArgs, actionParams) : value,
label
}, void 0];
}
function executeLog({
logger
}, {
value,
label
}) {
if (label) {
logger(label, value);
} else {
logger(value);
}
}
function log(value = ({
context,
event
}) => ({
context,
event
}), label) {
function log2(_args, _params) {
}
log2.type = "xstate.log";
log2.value = value;
log2.label = label;
log2.resolve = resolveLog;
log2.execute = executeLog;
return log2;
}
// ../../node_modules/xstate/dist/xstate.esm.js function createMachine(config, implementations) { return new StateMachine(config, implementations); } function setup({ schemas, actors, actions, guards, delays }) { return { assign, sendTo, raise, log, cancel, stopChild, enqueueActions, emit, spawnChild, createStateConfig: (config) => config, createAction: (fn) => fn, createMachine: (config) => createMachine({ ...config, schemas }, { actors, actions, guards, delays }), extend: (extended) => setup({ schemas, actors, actions: { ...actions, ...extended.actions }, guards: { ...guards, ...extended.guards }, delays: { ...delays, ...extended.delays } }) }; }
// src/runtime/runtimeLifecycleMachine.ts var createDisposedError = () => new Error("Layer Manager runtime disposed."); var executeIntentRequest = async (ea2, planner, canExecute) => { let attempts = 0; while (attempts < 2) { attempts += 1; const attempt = attempts; if (!canExecute()) { return { status: "capabilityMissing", reason: "Scene ownership changed before execution.", attempts: attempt }; } const planningSnapshot = readSnapshot(ea2); const planningContext = { snapshot: planningSnapshot, indexes: buildSceneIndexes(planningSnapshot) }; const planned = planner(planningContext); if (!planned.ok) { return { status: "plannerError", error: planned.error, attempts: attempt }; } const applyOutcome = await applyPatch(ea2, planned.value, canExecute); if (applyOutcome.status === "applied") { return { status: "applied", attempts: attempt }; } if (applyOutcome.status === "preflightFailed" && attempts < 2) { continue; } return { status: applyOutcome.status, reason: applyOutcome.reason, attempts: attempt }; } return { status: "preflightFailed", reason: "Patch preflight failed after bounded retry.", attempts: 2 }; }; var runtimeLifecycleMachine = setup({ types: { context: {}, input: {}, events: {} }, actors: { flushExternalRefresh: fromPromise(async () => { await Promise.resolve(); }), runMutation: fromPromise( async ({ input }) => { if (input.request.type === "APPLY_REQUEST") { const outcome2 = input.request.canExecute() ? await applyPatch(input.ea, input.request.patch, input.request.canExecute) : { status: "capabilityMissing", reason: "Scene ownership changed before execution." }; return { kind: "apply", request: input.request, outcome: outcome2 }; } const outcome = await executeIntentRequest( input.ea, input.request.planner, input.request.canExecute ); return { kind: "executeIntent", request: input.request, outcome }; } ) }, guards: { hasRefreshRequest: ({ context }) => context.refreshRequested, hasQueuedMutation: ({ context }) => context.activeMutation === null && context.mutationQueue.length > 0, isInteractionActive: ({ context }) => context.interactionDepth > 0, willRemainInteractiveAfterEnd: ({ context }) => context.interactionDepth > 1, shouldRefreshAfterInteractionEnd: ({ context }) => context.interactionDepth === 1 && context.pendingRefreshWhileInteractive, isFinalInteractionEnd: ({ context }) => context.interactionDepth === 1 && !context.pendingRefreshWhileInteractive }, actions: { beginInteraction: assign({ interactionDepth: ({ context }) => context.interactionDepth + 1, pendingRefreshWhileInteractive: true }), decrementInteractionDepth: assign({ interactionDepth: ({ context }) => Math.max(0, context.interactionDepth - 1) }), finishInteractionAndPromotePendingRefresh: assign({ interactionDepth: 0, pendingRefreshWhileInteractive: false, refreshRequested: true }), finishInteractionDuringMutation: assign(({ context }) => { const nextDepth = Math.max(0, context.interactionDepth - 1); const shouldPromoteRefresh = context.interactionDepth === 1 && context.pendingRefreshWhileInteractive; return { interactionDepth: nextDepth, pendingRefreshWhileInteractive: shouldPromoteRefresh ? false : context.pendingRefreshWhileInteractive, refreshRequested: shouldPromoteRefresh ? true : context.refreshRequested }; }), requestRefresh: assign(({ context }) => { if (context.interactionDepth > 0) { return { pendingRefreshWhileInteractive: true }; } return { refreshRequested: true }; }), enqueueMutationFromEvent: assign({ mutationQueue: ({ context, event }) => { if (event.type !== "APPLY_REQUEST" && event.type !== "EXECUTE_INTENT_REQUEST") { return context.mutationQueue; } return [...context.mutationQueue, event]; } }), promoteNextMutation: assign(({ context }) => { const [activeMutation, ...remaining] = context.mutationQueue; return { activeMutation: activeMutation ?? null, mutationQueue: remaining }; }), clearActiveMutation: assign({ activeMutation: null }), resolveMutationRequest: ({ event }) => { const { output } = event; if (output.kind === "apply") { output.request.resolve(output.outcome); return; } output.request.resolve(output.outcome); }, rejectActiveMutation: ({ context, event }) => { const activeMutation = context.activeMutation; if (!activeMutation) { return; } const { error } = event; activeMutation.reject(error); }, clearRefreshRequest: assign({ refreshRequested: false, pendingRefreshWhileInteractive: false }), performRefresh: ({ context }) => { context.renderLatestSnapshot(); }, rejectPendingMutations: assign(({ context }) => { const disposedError = createDisposedError(); context.activeMutation?.reject(disposedError); for (const request of context.mutationQueue) { request.reject(disposedError); } return { activeMutation: null, mutationQueue: [] }; }) } }).createMachine({ id: "layerManagerRuntimeLifecycle", initial: "active", context: ({ input }) => ({ ea: input.ea, renderLatestSnapshot: input.renderLatestSnapshot, interactionDepth: 0, pendingRefreshWhileInteractive: false, refreshRequested: false, mutationQueue: [], activeMutation: null }), states: { active: { type: "parallel", on: { APPLY_REQUEST: { actions: "enqueueMutationFromEvent" }, EXECUTE_INTENT_REQUEST: { actions: "enqueueMutationFromEvent" }, REFRESH_REQUEST: { actions: "requestRefresh" }, DISPOSE: { target: "disposed", actions: ["rejectPendingMutations"] } }, states: { lifecycle: { initial: "idle", states: { idle: { on: { BEGIN_INTERACTION: { target: "interacting", actions: "beginInteraction" } }, always: [ { guard: "hasRefreshRequest", target: "refreshing" }, { guard: "hasQueuedMutation", target: "runningMutation", actions: "promoteNextMutation" } ] }, interacting: { on: { BEGIN_INTERACTION: { actions: "beginInteraction" }, END_INTERACTION: [ { guard: "willRemainInteractiveAfterEnd", actions: "decrementInteractionDepth" }, { guard: "shouldRefreshAfterInteractionEnd", target: "refreshing", actions: "finishInteractionAndPromotePendingRefresh" }, { guard: "isFinalInteractionEnd", target: "idle", actions: ["decrementInteractionDepth"] } ] } }, refreshing: { entry: ["performRefresh", "clearRefreshRequest"], always: [ { guard: "isInteractionActive", target: "interacting" }, { guard: "hasQueuedMutation", target: "runningMutation", actions: "promoteNextMutation" }, { target: "idle" } ] }, runningMutation: { invoke: { src: "runMutation", input: ({ context }) => { if (!context.activeMutation) { throw new Error("Missing active runtime mutation."); } return { ea: context.ea, request: context.activeMutation }; }, onDone: [ { guard: "isInteractionActive", target: "interacting", actions: ["resolveMutationRequest", "clearActiveMutation", "requestRefresh"] }, { target: "idle", actions: [ "clearActiveMutation", "clearRefreshRequest", "performRefresh", "resolveMutationRequest" ] } ], onError: [ { guard: "isInteractionActive", target: "interacting", actions: ["rejectActiveMutation", "clearActiveMutation"] }, { target: "idle", actions: ["rejectActiveMutation", "clearActiveMutation"] } ] }, on: { BEGIN_INTERACTION: { actions: "beginInteraction" }, END_INTERACTION: [ { guard: "willRemainInteractiveAfterEnd", actions: "decrementInteractionDepth" }, { guard: "shouldRefreshAfterInteractionEnd", actions: "finishInteractionDuringMutation" }, { guard: "isFinalInteractionEnd", actions: ["decrementInteractionDepth"] } ] } } } }, externalRefresh: { initial: "unscheduled", states: { unscheduled: { on: { SCENE_CHANGE_NOTICED: { target: "scheduled" } } }, scheduled: { invoke: { src: "flushExternalRefresh", onDone: { target: "unscheduled", actions: "requestRefresh" } }, on: { SCENE_CHANGE_NOTICED: { actions: [] } } } } } } }, disposed: { type: "final" } } }); var createRuntimeLifecycleActor = (input) => { return createActor(runtimeLifecycleMachine, { input }); };
// src/state/store.ts var cloneSet = (set) => new Set(set); var LayerManagerStore = class { #state; #listeners = /* @PURE / new Set(); constructor(initial) { this.#state = { expandedNodeIds: cloneSet(initial?.expandedNodeIds ?? / @PURE */ new Set()), selectedNodeId: initial?.selectedNodeId ?? null, filterQuery: initial?.filterQuery ?? "", draggingNodeId: initial?.draggingNodeId ?? null }; } getState() { return { ...this.#state, expandedNodeIds: cloneSet(this.#state.expandedNodeIds) }; } subscribe(listener) { this.#listeners.add(listener); listener(this.getState()); return () => { this.#listeners.delete(listener); }; } update(patch) { this.#state = { ...this.#state, ...patch, expandedNodeIds: patch.expandedNodeIds ? cloneSet(patch.expandedNodeIds) : cloneSet(this.#state.expandedNodeIds) }; for (const listener of this.#listeners) { listener(this.getState()); } } toggleExpanded(nodeId) { const next = new Set(this.#state.expandedNodeIds); if (next.has(nodeId)) { next.delete(nodeId); } else { next.add(nodeId); } this.update({ expandedNodeIds: next }); } };
// src/ui/controller.ts
var plannerErrorOutcome = (error) => ({
status: "plannerError",
error,
attempts: 1
});
var noopInteractionLifecycle = {
waitForIdle: async () => {
},
beginInteraction: () => {
},
endInteraction: () => {
}
};
var LayerManagerController = class {
#store;
#renderer;
#interactionLifecycle;
#unsubscribeFromStore;
#onExpandedStateChanged;
#latestTree = [];
#latestNodeById = /* @PURE / new Map();
#latestVersion = 0;
#latestSelectedIds = / @PURE / new Set();
#latestElementStateById = / @PURE / new Map();
#commandFacade = null;
#suppressNextStoreRender = false;
#beginInteractionAction = () => {
this.#interactionLifecycle.beginInteraction();
};
#endInteractionAction = () => {
this.#interactionLifecycle.endInteraction();
};
#toggleExpandedAction = (nodeId) => {
this.toggleExpanded(nodeId);
};
#toggleVisibilityNodeAction = async (nodeId) => {
await this.#interactionLifecycle.waitForIdle();
const resolved = this.resolveElementIdsFromNodeIds("toggleVisibility", [nodeId]);
if (!resolved.ok) {
return resolved.outcome;
}
return resolved.commandFacade.toggleVisibility({
elementIds: resolved.elementIds
});
};
#toggleLockNodeAction = async (nodeId) => {
await this.#interactionLifecycle.waitForIdle();
const resolved = this.resolveElementIdsFromNodeIds("toggleLock", [nodeId]);
if (!resolved.ok) {
return resolved.outcome;
}
return resolved.commandFacade.toggleLock({
elementIds: resolved.elementIds
});
};
#renameNodeAction = async (nodeId, nextName) => {
await this.#interactionLifecycle.waitForIdle();
const resolved = this.resolveNodeAction("renameNode", nodeId);
if (!resolved.ok) {
return resolved.outcome;
}
if (resolved.node.type === "group" && resolved.node.groupId) {
return resolved.commandFacade.renameNode({
groupId: resolved.node.groupId,
nextName
});
}
return resolved.commandFacade.renameNode({
elementId: resolveRepresentativeElementId(resolved.node),
nextName
});
};
#deleteNodeAction = async (nodeId) => {
await this.#interactionLifecycle.waitForIdle();
const resolved = this.resolveElementIdsFromNodeIds("deleteNode", [nodeId]);
if (!resolved.ok) {
return resolved.outcome;
}
return resolved.commandFacade.deleteNode({
elementIds: resolved.elementIds
});
};
#createGroupFromNodeIdsAction = async (input) => {
await this.#interactionLifecycle.waitForIdle();
const resolved = this.resolveElementIdsFromNodeIds("createGroup", input.nodeIds);
if (!resolved.ok) {
return resolved.outcome;
}
if (input.nameSeed === void 0) {
return resolved.commandFacade.createGroup({
elementIds: resolved.elementIds
});
}
return resolved.commandFacade.createGroup({
elementIds: resolved.elementIds,
nameSeed: input.nameSeed
});
};
#reorderFromNodeIdsAction = async (nodeIds, mode = "front") => {
await this.#interactionLifecycle.waitForIdle();
const resolved = this.resolveElementIdsFromNodeIds("reorder", nodeIds);
if (!resolved.ok) {
return resolved.outcome;
}
return resolved.commandFacade.reorder({
orderedElementIds: resolved.elementIds,
mode
});
};
#reparentFromNodeIdsAction = async (input) => {
await this.#interactionLifecycle.waitForIdle();
const notifyOnFailure = input.notifyOnFailure !== false;
const resolved = this.resolveElementIdsFromNodeIds("reparent", input.nodeIds, notifyOnFailure);
if (!resolved.ok) {
return resolved.outcome;
}
return resolved.commandFacade.reparent(
{
elementIds: resolved.elementIds,
sourceGroupId: input.sourceGroupId,
targetParentPath: input.targetParentPath,
targetFrameId: input.targetFrameId
},
{
notifyOnFailure
}
);
};
#reorderRelativeToNodeIdsAction = async (input) => {
await this.#interactionLifecycle.waitForIdle();
const notifyOnFailure = input.notifyOnFailure !== false;
const resolved = this.resolveElementIdsFromNodeIds("reorder", input.nodeIds, notifyOnFailure);
if (!resolved.ok) {
return resolved.outcome;
}
if (!this.#latestNodeById.has(input.anchorNodeId)) {
const message = reorder failed: node not found (${input.anchorNodeId}).;
if (notifyOnFailure) {
this.notify(message);
}
return plannerErrorOutcome(message);
}
return resolved.commandFacade.reorder(
{
orderedElementIds: resolved.elementIds,
anchorNodeId: input.anchorNodeId,
placement: input.placement
},
{
notifyOnFailure
}
);
};
constructor(renderer, store, interactionLifecycle = noopInteractionLifecycle, onExpandedStateChanged = () => {
}) {
this.#renderer = renderer;
this.#store = store ?? new LayerManagerStore();
this.#interactionLifecycle = interactionLifecycle;
this.#onExpandedStateChanged = onExpandedStateChanged;
this.#unsubscribeFromStore = this.#store.subscribe(() => {
if (this.#suppressNextStoreRender) {
this.#suppressNextStoreRender = false;
return;
}
this.render();
});
}
dispose() {
this.#unsubscribeFromStore();
}
setTree(tree, sceneVersion, selectedIds, elementStateById) {
this.#latestTree = tree;
this.#latestNodeById = this.buildNodeIndex(tree);
this.#latestVersion = sceneVersion;
this.#latestSelectedIds = selectedIds;
this.#latestElementStateById = elementStateById ?? / @PURE / new Map();
this.render();
}
setCommandFacade(commandFacade) {
this.#commandFacade = commandFacade;
this.render();
}
toggleExpanded(nodeId) {
this.#suppressNextStoreRender = true;
this.#store.toggleExpanded(nodeId);
this.#onExpandedStateChanged();
}
getExpandedNodeIds() {
return this.#store.getState().expandedNodeIds;
}
notify(message) {
this.#renderer.notify?.(message);
}
buildNodeIndex(nodes) {
const nodeById = / @PURE / new Map();
const stack = [...nodes];
while (stack.length > 0) {
const node = stack.pop();
if (!node) {
continue;
}
nodeById.set(node.id, node);
for (let index = node.children.length - 1; index >= 0; index -= 1) {
const child = node.children[index];
if (child) {
stack.push(child);
}
}
}
return nodeById;
}
resolveCommandFacade(commandName, notifyOnFailure = true) {
if (this.#commandFacade) {
return {
ok: true,
commandFacade: this.#commandFacade
};
}
const message = ${commandName} failed: command facade is not initialized.;
if (notifyOnFailure) {
this.notify(message);
}
return {
ok: false,
outcome: plannerErrorOutcome(message)
};
}
resolveNodeAction(commandName, nodeId, notifyOnFailure = true) {
const commandFacade = this.resolveCommandFacade(commandName, notifyOnFailure);
if (!commandFacade.ok) {
return commandFacade;
}
const node = this.#latestNodeById.get(nodeId);
if (!node) {
const message = ${commandName} failed: node not found (${nodeId}).;
if (notifyOnFailure) {
this.notify(message);
}
return {
ok: false,
outcome: plannerErrorOutcome(message)
};
}
return {
ok: true,
commandFacade: commandFacade.commandFacade,
node
};
}
resolveElementIdsFromNodeIds(commandName, nodeIds, notifyOnFailure = true) {
const commandFacade = this.resolveCommandFacade(commandName, notifyOnFailure);
if (!commandFacade.ok) {
return commandFacade;
}
if (nodeIds.length === 0) {
const message = ${commandName} failed: no node IDs provided.;
if (notifyOnFailure) {
this.notify(message);
}
return {
ok: false,
outcome: plannerErrorOutcome(message)
};
}
const elementIds = [];
const seenElementIds = / @PURE */ new Set();
for (const nodeId of nodeIds) {
const node = this.#latestNodeById.get(nodeId);
if (!node) {
const message = ${commandName} failed: node not found (${nodeId}).;
if (notifyOnFailure) {
this.notify(message);
}
return {
ok: false,
outcome: plannerErrorOutcome(message)
};
}
for (const elementId of node.elementIds) {
if (seenElementIds.has(elementId)) {
continue;
}
seenElementIds.add(elementId);
elementIds.push(elementId);
}
}
if (elementIds.length === 0) {
const message = ${commandName} failed: no target elements resolved from node IDs.;
if (notifyOnFailure) {
this.notify(message);
}
return {
ok: false,
outcome: plannerErrorOutcome(message)
};
}
return {
ok: true,
commandFacade: commandFacade.commandFacade,
elementIds
};
}
render() {
const model = {
tree: this.#latestTree,
selectedIds: this.#latestSelectedIds,
sceneVersion: this.#latestVersion,
elementStateById: this.#latestElementStateById
};
if (this.#commandFacade) {
this.#renderer.render({
...model,
// Architecture seam note:
// renderer actions are intent-only entry points; command execution stays behind
// facade -> executeIntent -> adapter preflight/apply.
actions: {
beginInteraction: this.#beginInteractionAction,
endInteraction: this.#endInteractionAction,
toggleExpanded: this.#toggleExpandedAction,
toggleVisibilityNode: this.#toggleVisibilityNodeAction,
toggleLockNode: this.#toggleLockNodeAction,
renameNode: this.#renameNodeAction,
deleteNode: this.#deleteNodeAction,
createGroupFromNodeIds: this.#createGroupFromNodeIdsAction,
reorderFromNodeIds: this.#reorderFromNodeIdsAction,
reorderRelativeToNodeIds: this.#reorderRelativeToNodeIdsAction,
reparentFromNodeIds: this.#reparentFromNodeIdsAction,
commands: this.#commandFacade
}
});
return;
}
this.#renderer.render(model);
}
};
// src/ui/interactionOutcome.ts var didInteractionApply = (outcome) => { return outcome.status === "applied"; };
// src/ui/renderer.ts
var ConsoleRenderer = class {
render(model) {
const lines = [];
const walk = (nodes, level) => {
for (const node of nodes) {
const indent = " ".repeat(level);
lines.push(${indent}- [${node.type}] ${node.label} (${node.elementIds.length}));
if (node.isExpanded && node.children.length > 0) {
walk(node.children, level + 1);
}
}
};
walk(model.tree, 0);
console.log([LMX] render@${model.sceneVersion} ${lines.join("\n")});
}
notify(message) {
console.log([LMX] ${message});
}
};
// src/ui/sidepanel/selection/structuralMoveSelection.ts var selectionIncludesFrameRows = (selection) => { return selection.nodes.some((node) => node.type === "frame"); }; var selectionIncludesGroupRows = (selection) => { return selection.nodes.some((node) => node.type === "group"); }; var resolveStructuralMoveSelection = (nodes) => { if (nodes.length === 0) { return null; } if (nodes.some((node) => node.type === "frame")) { return null; } if (nodes.length === 1) { const node = nodes[0]; if (node?.type === "group" && node.groupId) { return { nodeIds: [node.id], sourceGroupId: node.groupId }; } } if (nodes.some((node) => node.type === "group")) { return null; } return { nodeIds: nodes.map((node) => node.id), sourceGroupId: null }; }; var resolveExplicitSelectionNodeIds = (selection) => { return (selection.explicitSelectedNodes ?? []).map((node) => node.id); }; var resolveSelectionStructuralMove = (selection) => { return selection.structuralMove ?? resolveStructuralMoveSelection(selection.nodes); }; var resolveStructuralSelectionIssue = (selection, emptySelectionMessage = "Select rows or elements first.") => { const structuralMove = resolveSelectionStructuralMove(selection); const hasSelection = selection.elementIds.length > 0 || selection.nodes.length > 0 || !!structuralMove; if (!hasSelection) { return emptySelectionMessage; } if (selectionIncludesFrameRows(selection)) { return "Selection includes frame rows."; } if (!selection.frameResolution.ok) { return "Selection spans multiple frames."; } if (selectionIncludesGroupRows(selection) && !structuralMove) { return "Selection includes mixed or multiple group rows."; } return null; }; var resolveFocusedNodeStructuralMove = (node) => { if (node.type === "frame") { return null; } if (node.type === "group" && node.groupId) { return { nodeIds: [node.id], sourceGroupId: node.groupId }; } return { nodeIds: [node.id], sourceGroupId: null }; };
// src/ui/sidepanel/actions/selectionActionController.ts
var runSelectionReparent = async (actions, selection, input) => {
if (selection.structuralMove) {
return actions.reparentFromNodeIds({
nodeIds: selection.structuralMove.nodeIds,
sourceGroupId: selection.structuralMove.sourceGroupId,
targetParentPath: input.targetParentPath,
targetFrameId: input.targetFrameId
});
}
return actions.commands.reparent({
elementIds: selection.elementIds,
sourceGroupId: null,
targetParentPath: input.targetParentPath,
targetFrameId: input.targetFrameId
});
};
var resolveStructuralReparentIssue = (selection, actionLabel) => {
if (selection.elementIds.length === 0) {
return ${actionLabel} requires at least one selected element.;
}
if (selectionIncludesFrameRows(selection)) {
return ${actionLabel} failed: frame rows cannot be structurally moved.;
}
if (!selection.frameResolution.ok) {
return ${actionLabel} failed: selected items span multiple frames.;
}
if (selectionIncludesGroupRows(selection) && !selection.structuralMove) {
return ${actionLabel} failed: mixed or multiple group rows are not supported.;
}
return null;
};
var SidepanelSelectionActionController = class {
#host;
constructor(host) {
this.#host = host;
}
async groupSelected(actions, selection) {
if (selection.elementIds.length < 2) {
this.#host.notify("Create group requires at least two selected elements.");
return;
}
await this.#host.promptService.withPromptlessInteraction(actions, async () => {
const explicitSelectedNodeIds = resolveExplicitSelectionNodeIds(selection);
if (explicitSelectedNodeIds.length > 0) {
await actions.createGroupFromNodeIds({
nodeIds: explicitSelectedNodeIds
});
return;
}
await actions.commands.createGroup({
elementIds: selection.elementIds
});
});
}
async reorderSelected(actions, selection, mode) {
const explicitSelectedNodeIds = resolveExplicitSelectionNodeIds(selection);
if (explicitSelectedNodeIds.length > 0) {
await actions.reorderFromNodeIds(explicitSelectedNodeIds, mode);
return;
}
if (selection.elementIds.length === 0) {
this.#host.notify("Reorder requires at least one selected element.");
return;
}
await actions.commands.reorder({
orderedElementIds: selection.elementIds,
mode
});
}
async applyGroupPreset(actions, selection, preset) {
const selectionIssue = resolveStructuralReparentIssue(selection, "Preset move");
if (selectionIssue) {
this.#host.notify(selectionIssue);
return;
}
const frameResolution = selection.frameResolution;
if (frameResolution.frameId !== preset.targetFrameId) {
this.#host.notify("Preset move failed: selected items are in a different frame.");
return;
}
const outcome = await runSelectionReparent(actions, selection, {
targetParentPath: preset.targetParentPath,
targetFrameId: preset.targetFrameId
});
if (didInteractionApply(outcome)) {
this.#host.setLastQuickMoveDestination({
kind: "preset",
preset
});
}
}
async moveSelectionToRoot(actions, selection, targetFrameId = selection.frameResolution.frameId) {
const selectionIssue = resolveStructuralReparentIssue(selection, "Move to root");
if (selectionIssue) {
this.#host.notify(selectionIssue);
return;
}
const frameResolution = selection.frameResolution;
if (frameResolution.frameId !== targetFrameId) {
this.#host.notify("Move to root failed: selected items are in a different frame.");
return;
}
const outcome = await runSelectionReparent(actions, selection, {
targetParentPath: [],
targetFrameId
});
if (didInteractionApply(outcome)) {
this.#host.setLastQuickMoveDestination({
kind: "root",
targetFrameId
});
}
}
async ungroupLikeSelection(actions, selection) {
const selectionIssue = resolveStructuralReparentIssue(selection, "Move out of group");
if (selectionIssue) {
this.#host.notify(selectionIssue);
return;
}
await this.#host.promptService.withPromptlessInteraction(actions, async () => {
await this.moveSelectionToRoot(actions, selection);
});
}
};
// src/ui/sidepanel/dragdrop/dragDropController.ts
var haveSamePath = (left, right) => {
if (left.length !== right.length) {
return false;
}
return left.every((segment, index) => segment === right[index]);
};
var haveSameScope = (left, right) => {
return left.frameId === right.frameId && haveSamePath(left.groupPath, right.groupPath);
};
var resolveStructuralNodePosition = (nodes, targetNodeId, branchContext, resolveNodeFrameId2) => {
for (const [siblingIndex, node] of nodes.entries()) {
const nodeFrameId = resolveNodeFrameId2(node, branchContext);
if (node.id === targetNodeId) {
return {
node,
branchContext,
siblingIndex,
nodeFrameId
};
}
if (node.children.length === 0) {
continue;
}
const childBranchContext = {
frameId: nodeFrameId,
groupPath: node.type === "group" && node.groupId ? [...branchContext.groupPath, node.groupId] : branchContext.groupPath
};
const nestedMatch = resolveStructuralNodePosition(
node.children,
targetNodeId,
childBranchContext,
resolveNodeFrameId2
);
if (nestedMatch) {
return nestedMatch;
}
}
return null;
};
var SidepanelDragDropController = class {
#host;
#draggedNodeState = null;
#dropHint = null;
#hoverDepthByNodeId = /* @PURE */ new Map();
#pendingDropHintClear = null;
constructor(host) {
this.#host = host;
}
get dropHint() {
return this.#dropHint;
}
get dropHintNodeId() {
return this.#dropHint?.nodeId ?? null;
}
clear() {
this.#draggedNodeState = null;
this.resetHoverTracking();
this.#dropHint = null;
}
resolveNodeFrameId(node, branchContext) {
return resolveFrameRowElementId(node) ?? node.frameId ?? branchContext.frameId;
}
resolveDropTargetForNode(node, branchContext, siblingIndex) {
const nodeFrameId = this.resolveNodeFrameId(node, branchContext);
if (node.type === "group" && node.groupId) {
return {
targetParentPath: [...branchContext.groupPath, node.groupId],
targetFrameId: nodeFrameId,
rowScope: {
frameId: branchContext.frameId,
groupPath: [...branchContext.groupPath]
},
siblingIndex,
rowReorderEligible: true
};
}
if (node.type === "frame") {
return {
targetParentPath: [],
targetFrameId: resolveFrameRowElementId(node),
rowScope: {
frameId: branchContext.frameId,
groupPath: [...branchContext.groupPath]
},
siblingIndex,
rowReorderEligible: false
};
}
return {
targetParentPath: [...branchContext.groupPath],
targetFrameId: nodeFrameId,
rowScope: {
frameId: branchContext.frameId,
groupPath: [...branchContext.groupPath]
},
siblingIndex,
rowReorderEligible: true
};
}
canDropDraggedNode(targetNodeId, dropTarget, options) {
return this.qualifyDropIntent(targetNodeId, dropTarget, options).status === "qualified";
}
previewDropIntent(targetNodeId, dropTarget, options) {
const resolution = this.qualifyDropIntent(targetNodeId, dropTarget, options);
if (resolution.status !== "qualified") {
return null;
}
return resolution.intent;
}
startRowDrag(input) {
this.resetHoverTracking();
const structuralMove = this.#host.getActiveStructuralMoveSelection?.(input.node.id) ?? null;
const draggedNodeIds = structuralMove?.nodeIds.includes(input.node.id) ? structuralMove.nodeIds : [input.node.id];
this.#draggedNodeState = {
nodeId: input.node.id,
nodeIds: [...draggedNodeIds],
sourceGroupId: structuralMove?.sourceGroupId ?? (input.node.type === "group" ? input.node.groupId : null),
sourceFrameId: input.nodeFrameId,
sourceParentPath: [...input.branchGroupPath],
sourceRowScope: {
frameId: input.rowScope.frameId,
groupPath: [...input.rowScope.groupPath]
},
sourceSiblingRange: {
min: input.siblingIndex,
max: input.siblingIndex
},
sharesSingleScope: true
};
if (input.dragEvent.dataTransfer) {
input.dragEvent.dataTransfer.effectAllowed = "move";
input.dragEvent.dataTransfer.setData("text/plain", input.node.id);
}
this.updateDropHint(null);
}
endRowDrag() {
this.#draggedNodeState = null;
this.resetHoverTracking();
this.updateDropHint(null);
}
handleDragEnter(targetNodeId, dropTarget, event, options) {
this.incrementHoverDepth(targetNodeId);
const nextDropHint = this.resolveDropHint(targetNodeId, dropTarget, options);
if (!nextDropHint) {
if (this.#dropHint?.nodeId === targetNodeId) {
this.updateDropHint(null);
}
return;
}
event.preventDefault();
this.updateDropHint(nextDropHint);
}
handleDragOver(targetNodeId, dropTarget, event, options) {
this.ensureHoverDepth(targetNodeId);
const nextDropHint = this.resolveDropHint(targetNodeId, dropTarget, options);
if (!nextDropHint) {
if (this.#dropHint?.nodeId === targetNodeId) {
this.updateDropHint(null);
}
return;
}
event.preventDefault();
if (event.dataTransfer) {
event.dataTransfer.dropEffect = "move";
}
this.updateDropHint(nextDropHint);
}
handleDragLeave(targetNodeId, relatedTargetInsideRow) {
if (relatedTargetInsideRow) {
return;
}
this.decrementHoverDepth(targetNodeId);
if (this.#dropHint?.nodeId === targetNodeId) {
this.scheduleDropHintClear(targetNodeId);
}
}
resetDragState() {
this.#draggedNodeState = null;
this.resetHoverTracking();
this.updateDropHint(null);
}
async runDragDropMove(actions, targetNodeId, dropTarget, options) {
const resolution = this.qualifyDropIntent(targetNodeId, dropTarget, options);
if (resolution.status !== "qualified") {
this.#host.notify(
resolution.status === "notReady" ? "Drag and drop move is no longer active." : "Drop target is not compatible for this move."
);
return {
status: resolution.status === "notReady" ? "notReady" : "incompatible"
};
}
const { dragged, intent, dropTarget: resolvedDropTarget } = resolution;
if (intent.kind === "reorder") {
const outcome2 = await actions.reorderRelativeToNodeIds({
nodeIds: dragged.nodeIds,
anchorNodeId: targetNodeId,
placement: intent.placement,
notifyOnFailure: false
});
if (outcome2.status === "plannerError") {
this.#host.notify(Drag and drop reorder failed: ${outcome2.error});
return {
status: "notApplied"
};
}
if (!didInteractionApply(outcome2)) {
this.#host.notify(Drag and drop reorder failed: ${outcome2.reason});
return {
status: "notApplied"
};
}
return {
status: "applied",
effect: {
kind: "reorder"
}
};
}
const outcome = await actions.reparentFromNodeIds({
nodeIds: dragged.nodeIds,
sourceGroupId: dragged.sourceGroupId,
targetParentPath: resolvedDropTarget.targetParentPath,
targetFrameId: resolvedDropTarget.targetFrameId,
notifyOnFailure: false
});
if (outcome.status === "plannerError") {
this.#host.notify(Drag and drop reparent failed: ${outcome.error});
return {
status: "notApplied"
};
}
if (!didInteractionApply(outcome)) {
this.#host.notify(Drag and drop reparent failed: ${outcome.reason});
return {
status: "notApplied"
};
}
if (resolvedDropTarget.targetParentPath.length === 0) {
return {
status: "applied",
effect: {
kind: "reparent",
destination: {
kind: "root",
targetFrameId: resolvedDropTarget.targetFrameId
}
}
};
}
return {
status: "applied",
effect: {
kind: "reparent",
destination: {
kind: "preset",
targetParentPath: [...resolvedDropTarget.targetParentPath],
targetFrameId: resolvedDropTarget.targetFrameId
}
}
};
}
qualifyDropIntent(targetNodeId, dropTarget, options) {
const dragged = this.resolveCurrentDraggedNodeState();
if (!dragged) {
return {
status: "notReady"
};
}
const resolvedDropTarget = this.resolveCurrentDropTarget(targetNodeId, dropTarget);
if (!resolvedDropTarget) {
return {
status: "incompatible"
};
}
if (dragged.nodeIds.includes(targetNodeId)) {
return {
status: "incompatible"
};
}
const explicitReorderPlacement = this.resolveExplicitReorderPlacement(
dragged,
resolvedDropTarget,
options
);
if (explicitReorderPlacement) {
return {
status: "qualified",
dragged,
dropTarget: resolvedDropTarget,
intent: {
kind: "reorder",
placement: explicitReorderPlacement
}
};
}
if (options?.zone !== "inside" && resolvedDropTarget.rowReorderEligible && dragged.sharesSingleScope && haveSameScope(dragged.sourceRowScope, resolvedDropTarget.rowScope)) {
return {
status: "qualified",
dragged,
dropTarget: resolvedDropTarget,
intent: {
kind: "reorder",
placement: resolvedDropTarget.siblingIndex < dragged.sourceSiblingRange.min ? "before" : "after"
}
};
}
if (dragged.sourceFrameId !== resolvedDropTarget.targetFrameId) {
return {
status: "incompatible"
};
}
if (dragged.sourceGroupId && resolvedDropTarget.targetParentPath.includes(dragged.sourceGroupId)) {
return {
status: "incompatible"
};
}
if (haveSamePath(dragged.sourceParentPath, resolvedDropTarget.targetParentPath)) {
return {
status: "incompatible"
};
}
return {
status: "qualified",
dragged,
dropTarget: resolvedDropTarget,
intent: {
kind: "reparent"
}
};
}
resolveExplicitReorderPlacement(dragged, dropTarget, options) {
if (options?.zone !== "before" && options?.zone !== "after") {
return null;
}
if (!dropTarget.rowReorderEligible || !dragged.sharesSingleScope) {
return null;
}
if (!haveSameScope(dragged.sourceRowScope, dropTarget.rowScope)) {
return null;
}
return options.zone === "before" ? "before" : "after";
}
resolveCurrentDraggedNodeState() {
const dragged = this.#draggedNodeState;
if (!dragged) {
return null;
}
const structuralTree = this.#host.getLatestStructuralTree?.() ?? null;
if (!structuralTree) {
return dragged;
}
const positions = [];
for (const nodeId of dragged.nodeIds) {
const position = resolveStructuralNodePosition(
structuralTree,
nodeId,
{
frameId: null,
groupPath: []
},
(node, branchContext) => this.resolveNodeFrameId(node, branchContext)
);
if (!position) {
return null;
}
positions.push(position);
}
const primaryPosition = positions.find((position) => position.node.id === dragged.nodeId) ?? positions[0] ?? null;
if (!primaryPosition) {
return null;
}
const sourceRowScope = {
frameId: primaryPosition.branchContext.frameId,
groupPath: [...primaryPosition.branchContext.groupPath]
};
const sharesSingleScope = positions.every(
(position) => position.nodeFrameId === primaryPosition.nodeFrameId && haveSameScope(
{
frameId: position.branchContext.frameId,
groupPath: position.branchContext.groupPath
},
sourceRowScope
)
);
const sourceSiblingRange = sharesSingleScope ? {
min: Math.min(...positions.map((position) => position.siblingIndex)),
max: Math.max(...positions.map((position) => position.siblingIndex))
} : {
min: primaryPosition.siblingIndex,
max: primaryPosition.siblingIndex
};
return {
nodeId: primaryPosition.node.id,
nodeIds: [...dragged.nodeIds],
sourceGroupId: dragged.sourceGroupId,
sourceFrameId: primaryPosition.nodeFrameId,
sourceParentPath: [...primaryPosition.branchContext.groupPath],
sourceRowScope,
sourceSiblingRange,
sharesSingleScope
};
}
resolveCurrentDropTarget(targetNodeId, fallbackDropTarget) {
const structuralTree = this.#host.getLatestStructuralTree?.() ?? null;
if (!structuralTree) {
return fallbackDropTarget;
}
const position = resolveStructuralNodePosition(
structuralTree,
targetNodeId,
{
frameId: null,
groupPath: []
},
(node, branchContext) => this.resolveNodeFrameId(node, branchContext)
);
if (!position) {
return null;
}
return this.resolveDropTargetForNode(
position.node,
position.branchContext,
position.siblingIndex
);
}
resolveDropHint(targetNodeId, dropTarget, options) {
const preview = this.previewDropIntent(targetNodeId, dropTarget, options);
if (!preview) {
return null;
}
if (preview.kind === "reorder") {
return {
nodeId: targetNodeId,
kind: "reorder",
placement: preview.placement
};
}
return {
nodeId: targetNodeId,
kind: "reparent"
};
}
incrementHoverDepth(targetNodeId) {
this.cancelPendingDropHintClear(targetNodeId);
this.#hoverDepthByNodeId.set(targetNodeId, 1);
}
ensureHoverDepth(targetNodeId) {
this.cancelPendingDropHintClear(targetNodeId);
if ((this.#hoverDepthByNodeId.get(targetNodeId) ?? 0) === 0) {
this.#hoverDepthByNodeId.set(targetNodeId, 1);
}
}
decrementHoverDepth(targetNodeId) {
this.#hoverDepthByNodeId.delete(targetNodeId);
}
scheduleDropHintClear(targetNodeId) {
this.cancelPendingDropHintClear(targetNodeId);
this.#pendingDropHintClear = {
targetNodeId,
timeoutId: setTimeout(() => {
if (this.#pendingDropHintClear?.targetNodeId !== targetNodeId) {
return;
}
this.#pendingDropHintClear = null;
if ((this.#hoverDepthByNodeId.get(targetNodeId) ?? 0) > 0) {
return;
}
if (this.#dropHint?.nodeId !== targetNodeId) {
return;
}
this.updateDropHint(null);
}, 0)
};
}
cancelPendingDropHintClear(targetNodeId) {
if (!this.#pendingDropHintClear) {
return;
}
if (targetNodeId && this.#pendingDropHintClear.targetNodeId !== targetNodeId) {
return;
}
clearTimeout(this.#pendingDropHintClear.timeoutId);
this.#pendingDropHintClear = null;
}
resetHoverTracking() {
this.cancelPendingDropHintClear();
this.#hoverDepthByNodeId.clear();
}
updateDropHint(nextDropHint) {
if (this.#dropHint?.nodeId === nextDropHint?.nodeId && this.#dropHint?.kind === nextDropHint?.kind && (this.#dropHint?.kind !== "reorder" || nextDropHint?.kind !== "reorder" || this.#dropHint.placement === nextDropHint.placement)) {
return;
}
this.#dropHint = nextDropHint;
this.#host.requestRenderFromLatestModel();
}
};
// src/ui/sidepanel/focus/focusOutGuard.ts var isNodeTarget = (target) => { if (!target || typeof target !== "object") { return false; } const nodeType = target.nodeType; return typeof nodeType === "number"; }; var containsTarget = (contentRoot, target) => { if (!isNodeTarget(target)) { return false; } try { return contentRoot.contains(target); } catch { return false; } }; var SidepanelFocusOutGuard = class { #nowMs; #suppressUntilMs = 0; #pendingResolutionToken = 0; constructor(options = {}) { this.#nowMs = options.nowMs ?? Date.now; } reset() { this.#suppressUntilMs = 0; this.cancelPending(); } suppressFor(durationMs) { if (durationMs <= 0) { return; } this.#suppressUntilMs = this.#nowMs() + durationMs; } isSuppressed() { return this.#nowMs() < this.#suppressUntilMs; } cancelPending() { this.#pendingResolutionToken += 1; } handleFocusOut(input) { const contentRoot = input.contentRoot; if (!contentRoot) { return; } if (this.isSuppressed()) { return; } if (containsTarget(contentRoot, input.relatedTarget)) { return; } const resolutionToken = ++this.#pendingResolutionToken; Promise.resolve().then(() => { if (this.#pendingResolutionToken !== resolutionToken) { return; } if (this.isSuppressed()) { return; } if (input.isContentRootCurrent && !input.isContentRootCurrent(contentRoot)) { return; } const activeElement = contentRoot.ownerDocument.activeElement; if (containsTarget(contentRoot, activeElement)) { return; } input.onConfirmedFocusOut(); }); } };
// src/ui/sidepanel/focus/focusOwnershipCoordinator.ts var captureFocusScrollPositions = (element) => { const positions = []; let current = element; while (current) { positions.push({ element: current, top: current.scrollTop, left: current.scrollLeft }); current = current.parentElement; } return positions; }; var restoreFocusScrollPositions = (positions) => { for (const position of positions) { position.element.scrollTop = position.top; position.element.scrollLeft = position.left; } }; var focusElementWithoutScroll = (element) => { const scrollPositions = captureFocusScrollPositions(element); try { element.focus({ preventScroll: true }); } catch { try { element.focus(); } catch { } } restoreFocusScrollPositions(scrollPositions); }; var focusOwnershipMachine = setup({ types: { context: {}, input: {}, events: {} }, actions: { setShouldAutofocusContentRootFromEvent: assign({ shouldAutofocusContentRoot: ({ context, event }) => { if (event.type !== "SET_SHOULD_AUTOFOCUS_CONTENT_ROOT") { return context.shouldAutofocusContentRoot; } return event.value; } }), setHostDocumentAuthorityFromEvent: assign(({ context, event }) => { if (event.type !== "SET_HOST_DOCUMENT_AUTHORITY") { return { hostDocumentAuthority: context.hostDocumentAuthority }; } if (event.value) { return { hostDocumentAuthority: true }; } context.focusOutGuard.reset(); return { hostDocumentAuthority: false, shouldAutofocusContentRoot: false, keyboardCaptureActive: false, keyboardCaptureStickyUntilMs: 0, deferredFocusEpoch: context.deferredFocusEpoch + 1 }; }), activateKeyboardCapture: assign({ keyboardCaptureActive: ({ context }) => context.hostDocumentAuthority, keyboardCaptureStickyUntilMs: ({ context }) => context.hostDocumentAuthority ? context.nowMs() + context.keyboardStickyCaptureMs : 0 }), releaseKeyboardCapture: assign({ keyboardCaptureActive: false }), confirmOutsideFocusOut: assign({ shouldAutofocusContentRoot: false, keyboardCaptureActive: false, keyboardCaptureStickyUntilMs: 0, deferredFocusEpoch: ({ context }) => context.deferredFocusEpoch + 1 }), suppressTransientFocusOut: ({ context }) => { context.focusOutGuard.suppressFor(context.focusOutSuppressionWindowMs); }, cancelPendingFocusOut: ({ context }) => { context.focusOutGuard.cancelPending(); }, cancelDeferredFocusRestore: assign({ deferredFocusEpoch: ({ context }) => context.deferredFocusEpoch + 1 }), scheduleDeferredFocusRestore: assign({ deferredFocusEpoch: ({ context }) => context.deferredFocusEpoch + 1 }), claimAutofocusContentRoot: assign({ shouldAutofocusContentRoot: false, keyboardCaptureActive: true, keyboardCaptureStickyUntilMs: ({ context }) => context.nowMs() + context.keyboardStickyCaptureMs }), resetFocusOutGuard: ({ context }) => { context.focusOutGuard.reset(); }, resetFocusOwnership: assign(({ context }) => ({ shouldAutofocusContentRoot: context.hostDocumentAuthority, keyboardCaptureActive: false, keyboardCaptureStickyUntilMs: 0, deferredFocusEpoch: 0 })) } }).createMachine({ id: "sidepanelFocusOwnership", initial: "active", context: ({ input }) => ({ nowMs: input.nowMs, focusOutSuppressionWindowMs: input.focusOutSuppressionWindowMs, keyboardStickyCaptureMs: input.keyboardStickyCaptureMs, focusOutGuard: new SidepanelFocusOutGuard({ nowMs: input.nowMs }), hostDocumentAuthority: true, shouldAutofocusContentRoot: true, keyboardCaptureActive: false, keyboardCaptureStickyUntilMs: 0, deferredFocusEpoch: 0 }), states: { active: { on: { SET_SHOULD_AUTOFOCUS_CONTENT_ROOT: { actions: "setShouldAutofocusContentRootFromEvent" }, SET_HOST_DOCUMENT_AUTHORITY: { actions: "setHostDocumentAuthorityFromEvent" }, ACTIVATE_KEYBOARD_CAPTURE: { actions: "activateKeyboardCapture" }, RELEASE_KEYBOARD_CAPTURE: { actions: "releaseKeyboardCapture" }, CONFIRM_OUTSIDE_FOCUS_OUT: { actions: "confirmOutsideFocusOut" }, SUPPRESS_TRANSIENT_FOCUS_OUT: { actions: "suppressTransientFocusOut" }, CANCEL_PENDING_FOCUS_OUT: { actions: "cancelPendingFocusOut" }, CANCEL_DEFERRED_FOCUS_RESTORE: { actions: "cancelDeferredFocusRestore" }, SCHEDULE_DEFERRED_FOCUS_RESTORE: { actions: "scheduleDeferredFocusRestore" }, CLAIM_AUTOFOCUS_CONTENT_ROOT: { actions: "claimAutofocusContentRoot" }, RESET: { actions: ["resetFocusOutGuard", "resetFocusOwnership"] } } } } }); var createFocusOwnershipActor = (input) => { return createActor(focusOwnershipMachine, { input }); }; var SidepanelFocusOwnershipCoordinator = class { #actor; constructor(options) { this.#actor = createFocusOwnershipActor({ nowMs: options.nowMs ?? Date.now, focusOutSuppressionWindowMs: options.focusOutSuppressionWindowMs, keyboardStickyCaptureMs: options.keyboardStickyCaptureMs }); this.#actor.start(); } get #context() { return this.#actor.getSnapshot().context; } get shouldAutofocusContentRoot() { return this.#context.shouldAutofocusContentRoot; } hasHostDocumentAuthority() { return this.#context.hostDocumentAuthority; } setShouldAutofocusContentRoot(value) { this.#actor.send({ type: "SET_SHOULD_AUTOFOCUS_CONTENT_ROOT", value }); } setHostDocumentAuthority(value) { this.#actor.send({ type: "SET_HOST_DOCUMENT_AUTHORITY", value }); } isKeyboardCaptureActive() { return this.#context.keyboardCaptureActive; } activateKeyboardCapture() { if (!this.hasHostDocumentAuthority()) { return; } this.#actor.send({ type: "ACTIVATE_KEYBOARD_CAPTURE" }); } releaseKeyboardCapture() { this.#actor.send({ type: "RELEASE_KEYBOARD_CAPTURE" }); } confirmOutsideFocusOut() { this.#actor.send({ type: "CONFIRM_OUTSIDE_FOCUS_OUT" }); } isKeyboardRoutingActive() { const context = this.#context; if (!context.hostDocumentAuthority) { return false; } return context.keyboardCaptureActive || context.nowMs() < context.keyboardCaptureStickyUntilMs; } suppressTransientFocusOut() { this.#actor.send({ type: "SUPPRESS_TRANSIENT_FOCUS_OUT" }); } isFocusOutSuppressed() { return this.#context.focusOutGuard.isSuppressed(); } cancelPendingFocusOut() { this.#actor.send({ type: "CANCEL_PENDING_FOCUS_OUT" }); } handleContentFocusOut(input) { if (this.isFocusOutSuppressed()) { return; } this.#context.focusOutGuard.handleFocusOut(input); } focusContentRootImmediate(contentRoot) { if (!contentRoot) { return; } focusElementWithoutScroll(contentRoot); } cancelDeferredFocusRestore() { this.#actor.send({ type: "CANCEL_DEFERRED_FOCUS_RESTORE" }); } focusContentRootBestEffort(input) { if (!this.hasHostDocumentAuthority()) { return; } const contentRoot = input.contentRoot; if (!contentRoot) { return; } this.focusContentRootImmediate(contentRoot); this.#actor.send({ type: "SCHEDULE_DEFERRED_FOCUS_RESTORE" }); const focusEpoch = this.#context.deferredFocusEpoch; Promise.resolve().then(() => { if (this.#context.deferredFocusEpoch !== focusEpoch) { return; } if (input.isContentRootCurrent && !input.isContentRootCurrent(contentRoot)) { return; } this.focusContentRootImmediate(contentRoot); }); } autofocusContentRootIfNeeded(contentRoot, isTextInputTarget2) { if (!this.hasHostDocumentAuthority() || !this.shouldAutofocusContentRoot) { return; } const ownerDocument = contentRoot.ownerDocument; const activeElement = ownerDocument.activeElement; if (activeElement && contentRoot.contains(activeElement)) { this.#actor.send({ type: "CLAIM_AUTOFOCUS_CONTENT_ROOT" }); return; } if (isTextInputTarget2(activeElement)) { return; } this.focusContentRootImmediate(contentRoot); const focusedElement = ownerDocument.activeElement; if (focusedElement && contentRoot.contains(focusedElement)) { this.#actor.send({ type: "CLAIM_AUTOFOCUS_CONTENT_ROOT" }); } } reset() { this.#actor.send({ type: "RESET" }); } dispose() { this.reset(); this.#actor.stop(); } };
// src/ui/sidepanel/selection/selectionIds.ts var collectUniqueSelectionIds = (selectedElements) => { const selectedIds = []; const seenIds = /* @PURE */ new Set(); for (const element of selectedElements) { if (seenIds.has(element.id)) { continue; } seenIds.add(element.id); selectedIds.push(element.id); } return selectedIds; }; var haveSameIdsInSameOrder2 = (left, right) => { if (left.length !== right.length) { return false; } for (let index = 0; index < left.length; index += 1) { if (left[index] !== right[index]) { return false; } } return true; }; var haveSameIds = (left, right) => { if (left.length !== right.length) { return false; } const leftIds = new Set(left); if (leftIds.size !== left.length) { return false; } return right.every((id) => leftIds.has(id)); }; var appendUniqueIds = (target, seen, ids) => { for (const id of ids) { if (seen.has(id)) { continue; } seen.add(id); target.push(id); } };
// src/ui/sidepanel/selection/rowClickSelection.ts var appendUniqueNodes = (target, seenNodeIds, nodes) => { for (const node of nodes) { if (seenNodeIds.has(node.id)) { continue; } seenNodeIds.add(node.id); target.push(node); } }; var collectSelectedElementIds = (selectedNodes) => { const selectedElementIds = []; const seenElementIds = /* @PURE / new Set(); for (const node of selectedNodes) { appendUniqueIds(selectedElementIds, seenElementIds, node.elementIds); } return selectedElementIds; }; var resolveToggleAnchorNodeId = (selectedNodes, clickedNode, currentAnchorNodeId, removedExistingSelection) => { if (selectedNodes.length === 0) { return null; } if (!removedExistingSelection) { return clickedNode.id; } if (currentAnchorNodeId && selectedNodes.some((node) => node.id === currentAnchorNodeId)) { return currentAnchorNodeId; } return selectedNodes[0]?.id ?? null; }; var resolveVisibleRangeNodes = (visibleNodes, anchorNodeId, targetNodeId) => { const anchorIndex = visibleNodes.findIndex((node) => node.id === anchorNodeId); const targetIndex = visibleNodes.findIndex((node) => node.id === targetNodeId); if (anchorIndex < 0 || targetIndex < 0) { return null; } const start = Math.min(anchorIndex, targetIndex); const end = Math.max(anchorIndex, targetIndex); return visibleNodes.slice(start, end + 1); }; var resolveRowClickSelection = (input) => { const { clickedNode, currentSelectedNodes, modifiers } = input; const currentAnchorNodeId = input.currentAnchorNodeId ?? input.fallbackAnchorNodeId ?? null; if (modifiers.shiftKey) { const effectiveAnchorNodeId = currentAnchorNodeId ?? clickedNode.id; const resolvedRangeNodes = resolveVisibleRangeNodes( input.visibleNodes, effectiveAnchorNodeId, clickedNode.id ); const rangeNodes = resolvedRangeNodes ?? [clickedNode]; const nextAnchorNodeId = resolvedRangeNodes ? effectiveAnchorNodeId : clickedNode.id; if (modifiers.toggleKey) { const selectedNodes = []; const seenNodeIds = / @PURE */ new Set(); appendUniqueNodes(selectedNodes, seenNodeIds, currentSelectedNodes); appendUniqueNodes(selectedNodes, seenNodeIds, rangeNodes); return { selectedNodes, selectedElementIds: collectSelectedElementIds(selectedNodes), anchorNodeId: nextAnchorNodeId }; } return { selectedNodes: rangeNodes, selectedElementIds: collectSelectedElementIds(rangeNodes), anchorNodeId: nextAnchorNodeId }; } if (modifiers.toggleKey) { const nextSelectedNodes = currentSelectedNodes.filter((node) => node.id !== clickedNode.id); const removedExistingSelection = nextSelectedNodes.length !== currentSelectedNodes.length; const selectedNodes = removedExistingSelection ? nextSelectedNodes : [...currentSelectedNodes, clickedNode]; return { selectedNodes, selectedElementIds: collectSelectedElementIds(selectedNodes), anchorNodeId: resolveToggleAnchorNodeId( selectedNodes, clickedNode, currentAnchorNodeId, removedExistingSelection ) }; } return { selectedNodes: [clickedNode], selectedElementIds: collectSelectedElementIds([clickedNode]), anchorNodeId: clickedNode.id }; };
// ../obsidian-plugin-kit/src/debug/keyboardEventFlightRecorder.ts
var DEFAULT_MAX_EVENTS = 160;
var DEFAULT_CONSOLE_PREFIX = "[debug:key]";
var getRuntime = () => {
return globalThis;
};
var normalizeKeyboardKey = (key) => {
return key.length === 1 ? key.toLowerCase() : key;
};
var resolveTargetTagName = (target) => {
if (!target || typeof target !== "object" || !("tagName" in target)) {
return null;
}
const tagName = target.tagName;
return typeof tagName === "string" && tagName.length > 0 ? tagName : null;
};
var clonePayload = (payload) => {
return Object.fromEntries(Object.entries(payload));
};
var stringifyPayload = (payload) => {
try {
return JSON.stringify(payload, null, 2);
} catch {
return JSON.stringify({ error: "payload-unserializable" }, null, 2);
}
};
var createDefaultShouldTrace = (event) => {
return event.code === "Space" || normalizeKeyboardKey(event.key) === "t" || event.code === "KeyT" || event.altKey || event.ctrlKey || event.metaKey;
};
var createGlobalKeyboardEventFlightRecorder = (options) => {
const consolePrefix = options.consolePrefix ?? DEFAULT_CONSOLE_PREFIX;
const dumpTitle = options.dumpTitle ?? "# Key Event Trace";
const maxEvents = options.maxEvents ?? DEFAULT_MAX_EVENTS;
const shouldTrace = options.shouldTrace ?? createDefaultShouldTrace;
const getRecorderState2 = () => {
const runtime = getRuntime();
const existing = runtime[options.stateKey];
if (existing && typeof existing === "object" && "nextSequence" in existing && "events" in existing && Array.isArray(existing.events)) {
return existing;
}
const nextState = {
nextSequence: 1,
events: []
};
runtime[options.stateKey] = nextState;
return nextState;
};
const describeKeyboardEventForTrace = (event, payload) => {
return {
type: event.type,
key: event.key,
code: event.code ?? "",
altKey: event.altKey,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
shiftKey: event.shiftKey,
repeat: event.repeat,
defaultPrevented: event.defaultPrevented,
targetTagName: resolveTargetTagName(event.target),
...payload ?? {}
};
};
const isDebugEnabled = () => {
return getRuntime()[options.debugFlagKey] === true;
};
const recordKeyEventTrace = (source, payload) => {
const state = getRecorderState2();
const event = {
sequence: state.nextSequence,
atMs: Date.now(),
atIso: (/* @PURE */ new Date()).toISOString(),
source,
payload: clonePayload(payload)
};
state.nextSequence += 1;
state.events.push(event);
if (state.events.length > maxEvents) {
state.events.splice(0, state.events.length - maxEvents);
}
if (isDebugEnabled()) {
console.log(${consolePrefix} ${source}, event.payload);
}
return event;
};
const traceKeyboardEventIfRelevant2 = (source, event, payload) => {
if (!shouldTrace(event)) {
return;
}
recordKeyEventTrace(source, describeKeyboardEventForTrace(event, payload));
};
const readKeyEventTrace = () => {
return getRecorderState2().events.map((event) => ({
...event,
payload: clonePayload(event.payload)
}));
};
const clearKeyEventTrace2 = () => {
const state = getRecorderState2();
state.events.splice(0, state.events.length);
state.nextSequence = 1;
};
const formatKeyEventTraceDump = () => {
const events = readKeyEventTrace();
const lines = [dumpTitle, events=${events.length}, ""];
for (const event of events) {
lines.push([${${event.sequence}.padStart(3, "0")}] ${event.atIso} source=${event.source});
lines.push(stringifyPayload(event.payload));
lines.push("");
}
return lines.join("\n");
};
const installKeyEventFlightRecorderGlobals2 = () => {
const runtime = getRuntime();
runtime[options.globalReadKey] = () => readKeyEventTrace();
runtime[options.globalClearKey] = () => {
clearKeyEventTrace2();
};
runtime[options.globalDumpKey] = () => {
const dump = formatKeyEventTraceDump();
console.log(dump);
return dump;
};
};
return {
debugFlagKey: options.debugFlagKey,
shouldTraceKeyboardEvent: shouldTrace,
describeKeyboardEventForTrace,
isDebugEnabled,
recordKeyEventTrace,
traceKeyboardEventIfRelevant: traceKeyboardEventIfRelevant2,
readKeyEventTrace,
clearKeyEventTrace: clearKeyEventTrace2,
formatKeyEventTraceDump,
installKeyEventFlightRecorderGlobals: installKeyEventFlightRecorderGlobals2
};
};
// src/ui/sidepanel/keyboard/layerManagerKeyboardEventFlightRecorder.ts var KEY_EVENT_DEBUG_FLAG = "LMX_DEBUG_KEY_CAPTURE"; var recorder = createGlobalKeyboardEventFlightRecorder({ stateKey: "LMX_KEY_EVENT_FLIGHT_RECORDER", debugFlagKey: KEY_EVENT_DEBUG_FLAG, globalReadKey: "LMX_KEY_TRACE_READ", globalClearKey: "LMX_KEY_TRACE_CLEAR", globalDumpKey: "LMX_KEY_TRACE_DUMP", consolePrefix: "[LMX:key]", dumpTitle: "# LMX Key Event Trace", shouldTrace: (event) => event.code === "Space" || event.altKey || event.ctrlKey || event.metaKey }); var traceKeyboardEventIfRelevant = recorder.traceKeyboardEventIfRelevant; var clearKeyEventTrace = recorder.clearKeyEventTrace; var installKeyEventFlightRecorderGlobals = recorder.installKeyEventFlightRecorderGlobals;
// src/ui/sidepanel/keyboard/keyboardShortcutController.ts
var renderKeyboardSelectionRequirementMessage = (actionLabel) => {
return Keyboard ${actionLabel} requires an active selection or a focused row.;
};
var claimHandledKeyboardEvent = (event) => {
event.preventDefault();
event.stopPropagation?.();
event.stopImmediatePropagation?.();
};
var normalizeKeyboardKey2 = (key) => {
return key.length === 1 ? key.toLowerCase() : key;
};
var isSpaceShortcutEvent = (event) => {
return event.code === "Space" || event.key === " " || event.key === "Space" || event.key === "Spacebar";
};
var SidepanelKeyboardShortcutController = class {
#host;
constructor(host) {
this.#host = host;
}
handleContentKeydown(event) {
const targetTagName = this.resolveTargetTagName(event.target);
this.#host.debugInteraction?.("keydown received", {
key: event.key,
code: event.code ?? "",
shiftKey: event.shiftKey,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
altKey: event.altKey,
focusedNodeId: this.#host.getFocusedNodeId(),
targetTagName
});
traceKeyboardEventIfRelevant("controller:keydown-received", event, {
focusedNodeId: this.#host.getFocusedNodeId(),
targetTagName
});
if (this.isAltModifierStateKey(event)) {
return;
}
const baseContext = this.#host.getKeyboardContext();
if (!baseContext) {
this.traceIgnoredKeydown(
event,
"keyboardContextUnavailable",
"keydown ignored: keyboard context unavailable"
);
return;
}
const normalizedKey = normalizeKeyboardKey2(event.key);
const hasToggleModifier = event.ctrlKey || event.metaKey;
if (this.shouldIgnoreKeydown(event, normalizedKey, hasToggleModifier)) {
return;
}
const context = this.#host.resolveKeyboardContext(baseContext);
if (this.handleAltQuickMoveShortcut(event, context)) {
return;
}
if (this.handleAltStructuralMoveShortcut(event, context)) {
return;
}
if (this.handleAltReorderShortcut(event, context)) {
return;
}
if (this.handleNavigationShortcut(event, context)) {
return;
}
if (this.handleSelectionAliasShortcut(event, context, normalizedKey, hasToggleModifier)) {
return;
}
this.handleMutationShortcut(event, context, normalizedKey);
}
resolveTargetTagName(target) {
return target && typeof target === "object" && "tagName" in target ? ${target.tagName ?? ""} : null;
}
traceIgnoredKeydown(event, reason, debugMessage) {
if (debugMessage) {
this.#host.debugInteraction?.(debugMessage);
}
traceKeyboardEventIfRelevant("controller:keydown-ignored", event, {
reason
});
}
shouldIgnoreKeydown(event, normalizedKey, hasToggleModifier) {
if (this.#host.isTextInputTarget(event.target)) {
this.traceIgnoredKeydown(event, "textInputTarget");
return true;
}
if (this.#host.isKeyboardSuppressed()) {
this.traceIgnoredKeydown(event, "keyboardSuppressed");
return true;
}
if (event.altKey && !this.isAltReorderShortcut(event) && !this.isAltQuickMoveShortcut(event) && !this.isAltStructuralMoveShortcut(event)) {
this.traceIgnoredKeydown(event, "altShortcutNotAuthorized");
return true;
}
if (hasToggleModifier && !this.isSelectionAliasShortcut(event, normalizedKey)) {
this.traceIgnoredKeydown(event, "modifierShortcutNotAuthorized");
return true;
}
return false;
}
isSelectionAliasShortcut(event, normalizedKey) {
return isSpaceShortcutEvent(event) || normalizedKey === "n" || normalizedKey === "m";
}
isAltModifierStateKey(event) {
if (event.ctrlKey || event.metaKey || event.shiftKey) {
return false;
}
return event.key === "Alt" || event.code === "AltLeft" || event.code === "AltRight";
}
resolveAltQuickMoveDigit(event) {
if (!event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
return null;
}
if (typeof event.code === "string") {
const match = /^Digit([0-9])$/.exec(event.code);
if (match) {
return Number(match[1]);
}
}
return /^[0-9]$/.test(event.key) ? Number(event.key) : null;
}
isAltQuickMoveShortcut(event) {
return this.resolveAltQuickMoveDigit(event) !== null;
}
resolveAltStructuralMoveDirection(event) {
if (!event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
return null;
}
if (event.code === "BracketLeft" || event.key === "[") {
return "out";
}
if (event.code === "BracketRight" || event.key === "]") {
return "in";
}
return null;
}
isAltStructuralMoveShortcut(event) {
return this.resolveAltStructuralMoveDirection(event) !== null;
}
isAltReorderShortcut(event) {
if (!event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
return false;
}
return event.key === "ArrowUp" || event.key === "ArrowDown";
}
claimKeyboardShortcut(event) {
this.#host.suppressTransientFocusOut();
claimHandledKeyboardEvent(event);
}
handleAltQuickMoveShortcut(event, context) {
const digit = this.resolveAltQuickMoveDigit(event);
if (digit === null || !this.#host.runNumberedQuickMoveDestination) {
return false;
}
return this.runClaimedKeyboardUiAction(
event,
"Keyboard move failed",
() => this.#host.runNumberedQuickMoveDestination?.(digit, context) ?? Promise.resolve()
);
}
handleAltStructuralMoveShortcut(event, context) {
const direction = this.resolveAltStructuralMoveDirection(event);
if (!direction || !this.#host.runAltStructuralMove) {
return false;
}
traceKeyboardEventIfRelevant("controller:alt-structural-move", event, {
direction,
focusedNodeId: this.#host.getFocusedNodeId()
});
return this.runClaimedKeyboardUiAction(
event,
direction === "in" ? "Keyboard move into group failed" : "Keyboard move out of group failed",
() => this.#host.runAltStructuralMove?.(direction, context) ?? Promise.resolve()
);
}
handleAltReorderShortcut(event, context) {
if (!this.isAltReorderShortcut(event)) {
return false;
}
const mode = event.key === "ArrowUp" ? "forward" : "backward";
return this.runClaimedKeyboardUiAction(
event,
"Keyboard reorder failed",
() => this.runKeyboardReorder(context, mode)
);
}
handleNavigationShortcut(event, context) {
switch (event.key) {
case "ArrowDown":
this.claimKeyboardShortcut(event);
if (event.shiftKey) {
this.extendSelectionWithKeyboard(context, 1);
} else {
this.moveFocusedNode(context, 1);
}
return true;
case "ArrowUp":
this.claimKeyboardShortcut(event);
if (event.shiftKey) {
this.extendSelectionWithKeyboard(context, -1);
} else {
this.moveFocusedNode(context, -1);
}
return true;
case "Home":
this.claimKeyboardShortcut(event);
this.moveFocusedNodeToBoundary(context, "start");
return true;
case "End":
this.claimKeyboardShortcut(event);
this.moveFocusedNodeToBoundary(context, "end");
return true;
case "PageDown":
this.claimKeyboardShortcut(event);
if (event.shiftKey) {
this.extendSelectionByPage(context, 1);
} else {
this.moveFocusedNodeByPage(context, 1);
}
return true;
case "PageUp":
this.claimKeyboardShortcut(event);
if (event.shiftKey) {
this.extendSelectionByPage(context, -1);
} else {
this.moveFocusedNodeByPage(context, -1);
}
return true;
case "ArrowRight":
this.claimKeyboardShortcut(event);
this.handleArrowRight(context);
return true;
case "ArrowLeft":
this.claimKeyboardShortcut(event);
this.handleArrowLeft(context);
return true;
default:
return false;
}
}
handleSelectionAliasShortcut(event, context, normalizedKey, hasToggleModifier) {
if (!this.isSelectionAliasShortcut(event, normalizedKey)) {
return false;
}
this.claimKeyboardShortcut(event);
if (event.shiftKey) {
traceKeyboardEventIfRelevant("controller:selection-alias", event, {
action: "rangeAdd"
});
this.selectVisibleRangeToFocusedNode(context, hasToggleModifier);
return true;
}
if (hasToggleModifier) {
traceKeyboardEventIfRelevant("controller:selection-alias", event, {
action: "toggleFocusedNodeSelection"
});
this.toggleFocusedNodeSelection(context);
return true;
}
this.selectFocusedNodeLikePlainClick(context);
return true;
}
runClaimedKeyboardUiAction(event, fallbackMessage, action) {
this.claimKeyboardShortcut(event);
this.#host.runUiAction(action, fallbackMessage);
return true;
}
handleMutationShortcut(event, context, normalizedKey) {
if (event.key === "Enter") {
return this.runClaimedKeyboardUiAction(
event,
"Keyboard rename failed",
() => this.runKeyboardRenameFocused(context)
);
}
if (event.key === "Delete" || event.key === "Backspace") {
return this.runClaimedKeyboardUiAction(
event,
"Keyboard delete failed",
() => this.runKeyboardDeleteSelectionOrFocused(context)
);
}
switch (normalizedKey) {
case "f":
return this.runClaimedKeyboardUiAction(
event,
"Keyboard reorder failed",
() => this.runKeyboardReorder(context, event.shiftKey ? "front" : "forward")
);
case "b":
return this.runClaimedKeyboardUiAction(
event,
"Keyboard reorder failed",
() => this.runKeyboardReorder(context, event.shiftKey ? "back" : "backward")
);
case "g":
return this.runClaimedKeyboardUiAction(
event,
"Keyboard grouping failed",
() => this.runKeyboardGroupSelection(context)
);
case "u":
return this.runClaimedKeyboardUiAction(
event,
"Keyboard move out of group failed",
() => this.runKeyboardUngroupLike(context)
);
default:
return false;
}
}
handleContentFocusOut(event, contentRoot) {
if (!contentRoot) {
return;
}
const nextTarget = event.relatedTarget;
if (nextTarget && contentRoot.contains(nextTarget)) {
return;
}
this.#host.releaseKeyboardCapture();
this.#host.confirmOutsideFocusOut?.();
this.#host.debugInteraction?.("content focusout", {
focusedNodeId: this.#host.getFocusedNodeId(),
nextTargetTagName: nextTarget && typeof nextTarget === "object" && "tagName" in nextTarget ? ${nextTarget.tagName ?? ""} : null
});
}
moveFocusedNode(context, delta) {
if (context.visibleNodes.length === 0) {
this.#host.setFocusedNodeIdSilently(null);
return;
}
const visibleNodeIds = context.visibleNodes.map((node) => node.id);
const currentFocusedNodeId = this.#host.getFocusedNodeId();
const currentIndex = currentFocusedNodeId ? visibleNodeIds.indexOf(currentFocusedNodeId) : -1;
if (currentIndex === -1) {
const fallbackIndex = delta > 0 ? 0 : visibleNodeIds.length - 1;
const fallbackNodeId = visibleNodeIds[fallbackIndex] ?? null;
this.#host.setFocusedNode(fallbackNodeId);
return;
}
const boundedNextIndex = Math.min(visibleNodeIds.length - 1, Math.max(0, currentIndex + delta));
const nextFocusedNodeId = visibleNodeIds[boundedNextIndex] ?? null;
this.#host.setFocusedNode(nextFocusedNodeId);
}
moveFocusedNodeToBoundary(context, boundary) {
if (context.visibleNodes.length === 0) {
this.#host.setFocusedNodeIdSilently(null);
return;
}
const targetIndex = boundary === "start" ? 0 : context.visibleNodes.length - 1;
const targetNodeId = context.visibleNodes[targetIndex]?.id ?? null;
this.#host.setFocusedNode(targetNodeId);
}
moveFocusedNodeByPage(context, direction) {
if (context.visibleNodes.length === 0) {
this.#host.setFocusedNodeIdSilently(null);
return;
}
const visibleNodeIds = context.visibleNodes.map((node) => node.id);
const currentFocusedNodeId = this.#host.getFocusedNodeId();
const currentIndex = currentFocusedNodeId ? visibleNodeIds.indexOf(currentFocusedNodeId) : -1;
if (currentIndex === -1) {
const fallbackIndex = direction > 0 ? 0 : visibleNodeIds.length - 1;
const fallbackNodeId = visibleNodeIds[fallbackIndex] ?? null;
this.#host.setFocusedNode(fallbackNodeId);
return;
}
const step = this.resolvePageNavigationStep(context);
const boundedNextIndex = Math.min(
visibleNodeIds.length - 1,
Math.max(0, currentIndex + step * direction)
);
const nextFocusedNodeId = visibleNodeIds[boundedNextIndex] ?? null;
this.#host.setFocusedNode(nextFocusedNodeId);
}
extendSelectionWithKeyboard(context, delta) {
this.extendSelectionToRelativeTarget(context, delta);
}
extendSelectionByPage(context, direction) {
this.extendSelectionToRelativeTarget(
context,
this.resolvePageNavigationStep(context) * direction
);
}
extendSelectionToRelativeTarget(context, delta) {
const navigationTarget = this.resolveRelativeSelectionTarget(context, delta);
if (!navigationTarget) {
return;
}
const nextSelection = resolveRowClickSelection({
clickedNode: navigationTarget.nextNode,
visibleNodes: context.visibleNodes,
currentSelectedNodes: this.resolveCurrentSelectionNodes(context),
currentAnchorNodeId: context.anchorNodeId ?? null,
fallbackAnchorNodeId: navigationTarget.currentNode.id,
modifiers: {
shiftKey: true,
toggleKey: false
}
});
this.applyResolvedRowSelection("keyboardExtend", nextSelection);
this.#host.setFocusedNode(navigationTarget.nextNode.id);
}
resolveRelativeSelectionTarget(context, delta) {
if (context.visibleNodes.length === 0) {
this.#host.setFocusedNodeIdSilently(null);
return null;
}
const visibleNodeIds = context.visibleNodes.map((node) => node.id);
const currentFocusedNodeId = this.#host.getFocusedNodeId();
const currentIndex = currentFocusedNodeId ? visibleNodeIds.indexOf(currentFocusedNodeId) : -1;
const fallbackIndex = delta >= 0 ? 0 : visibleNodeIds.length - 1;
const resolvedCurrentIndex = currentIndex === -1 ? fallbackIndex : currentIndex;
const boundedNextIndex = Math.min(
visibleNodeIds.length - 1,
Math.max(0, resolvedCurrentIndex + delta)
);
const currentNode = context.visibleNodes[resolvedCurrentIndex];
const nextNode = context.visibleNodes[boundedNextIndex];
if (!currentNode || !nextNode) {
return null;
}
return {
currentNode,
nextNode
};
}
resolvePageNavigationStep(context) {
const hostStep = this.#host.getPageNavigationStep?.() ?? 0;
if (hostStep > 0) {
return Math.max(1, Math.min(context.visibleNodes.length, Math.floor(hostStep)));
}
return Math.max(1, Math.floor(Math.max(1, context.visibleNodes.length) / 2));
}
resolveFocusedNodeForSelectionGesture(context) {
if (context.visibleNodes.length === 0) {
this.#host.setFocusedNodeIdSilently(null);
this.#host.notify("Keyboard selection requires at least one visible row.");
return null;
}
return this.resolveFocusedNodeForHorizontalNavigation(context);
}
resolveCurrentSelectionNodes(context) {
const currentSelectionNodes = context.explicitSelectedNodes ?? context.selection.nodes;
if (currentSelectionNodes.length > 0) {
return currentSelectionNodes;
}
if (!context.anchorNodeId) {
return currentSelectionNodes;
}
const anchorNode = context.nodeById.get(context.anchorNodeId);
return anchorNode ? [anchorNode] : currentSelectionNodes;
}
applyResolvedRowSelection(source, input) {
if (this.#host.applyResolvedRowSelection) {
this.#host.applyResolvedRowSelection({
source,
...input
});
} else {
this.#host.setSelectionAnchorNodeId?.(input.anchorNodeId);
if (input.selectedNodes.length > 0 && this.#host.setSelectionOverrideWithNodes) {
this.#host.setSelectionOverrideWithNodes(input.selectedElementIds, input.selectedNodes);
} else if (input.selectedElementIds.length > 0) {
this.#host.setSelectionOverride(input.selectedElementIds);
} else {
this.#host.setSelectionOverride([]);
}
if (this.#host.mirrorSelectionToHost) {
this.#host.mirrorSelectionToHost(input.selectedElementIds);
} else if (this.#host.selectElementsInView) {
this.#host.ensureHostViewContext();
try {
this.#host.selectElementsInView([...input.selectedElementIds]);
} catch {
}
}
}
this.#host.requestRowTreeAutofocus?.();
this.#host.requestRenderFromLatestModel();
}
selectFocusedNodeLikePlainClick(context) {
const focusedNode = this.resolveFocusedNodeForSelectionGesture(context);
if (!focusedNode) {
return;
}
const currentSelectedNodes = this.resolveCurrentSelectionNodes(context);
const focusedNodeIsSelected = currentSelectedNodes.some((node) => node.id === focusedNode.id);
this.applyResolvedRowSelection(
focusedNodeIsSelected ? "keyboardModifierToggle" : "keyboardToggle",
resolveRowClickSelection({
clickedNode: focusedNode,
visibleNodes: context.visibleNodes,
currentSelectedNodes,
currentAnchorNodeId: context.anchorNodeId ?? null,
fallbackAnchorNodeId: focusedNode.id,
modifiers: {
shiftKey: false,
toggleKey: focusedNodeIsSelected
}
})
);
}
toggleFocusedNodeSelection(context) {
const focusedNode = this.resolveFocusedNodeForSelectionGesture(context);
if (!focusedNode) {
return;
}
this.applyResolvedRowSelection(
"keyboardModifierToggle",
resolveRowClickSelection({
clickedNode: focusedNode,
visibleNodes: context.visibleNodes,
currentSelectedNodes: this.resolveCurrentSelectionNodes(context),
currentAnchorNodeId: context.anchorNodeId ?? null,
fallbackAnchorNodeId: focusedNode.id,
modifiers: {
shiftKey: false,
toggleKey: true
}
})
);
}
selectVisibleRangeToFocusedNode(context, toggleKey = false) {
const focusedNode = this.resolveFocusedNodeForSelectionGesture(context);
if (!focusedNode) {
return;
}
this.applyResolvedRowSelection(
"keyboardRange",
resolveRowClickSelection({
clickedNode: focusedNode,
visibleNodes: context.visibleNodes,
currentSelectedNodes: this.resolveCurrentSelectionNodes(context),
currentAnchorNodeId: context.anchorNodeId ?? null,
fallbackAnchorNodeId: focusedNode.id,
modifiers: {
shiftKey: true,
toggleKey
}
})
);
}
resolveFocusedNodeForHorizontalNavigation(context) {
const focusedNodeId = this.#host.getFocusedNodeId();
if (focusedNodeId) {
const focusedNode = context.nodeById.get(focusedNodeId);
if (focusedNode) {
return focusedNode;
}
this.#host.notify("Keyboard focus is stale. Refreshing row focus.");
}
const fallbackNode = context.visibleNodes[0] ?? null;
if (!fallbackNode) {
this.#host.setFocusedNodeIdSilently(null);
return null;
}
this.#host.setFocusedNode(fallbackNode.id);
return fallbackNode;
}
handleArrowRight(context) {
const focusedNode = this.resolveFocusedNodeForHorizontalNavigation(context);
if (!focusedNode) {
return;
}
if (focusedNode.canExpand && !focusedNode.isExpanded) {
context.actions.toggleExpanded(focusedNode.id);
return;
}
this.focusFirstVisibleChild(context, focusedNode.id);
}
handleArrowLeft(context) {
const focusedNode = this.resolveFocusedNodeForHorizontalNavigation(context);
if (!focusedNode) {
return;
}
if (focusedNode.canExpand && focusedNode.isExpanded) {
context.actions.toggleExpanded(focusedNode.id);
return;
}
this.focusParentNode(context, focusedNode.id);
}
focusParentNode(context, nodeId) {
const parentNodeId = context.parentById.get(nodeId);
if (!parentNodeId) {
return;
}
this.#host.setFocusedNode(parentNodeId);
}
focusFirstVisibleChild(context, nodeId) {
const nodeIndex = context.visibleNodes.findIndex((node) => node.id === nodeId);
if (nodeIndex === -1) {
return;
}
for (let index = nodeIndex + 1; index < context.visibleNodes.length; index += 1) {
const candidate = context.visibleNodes[index];
if (!candidate) {
continue;
}
if (context.parentById.get(candidate.id) === nodeId) {
this.#host.setFocusedNode(candidate.id);
return;
}
}
}
/**
* Keyboard-first tree selection command precedence:
* explicit row selection -> canonical element selection -> focused-row fallback.
*/
resolveFocusedNodeIdOrNotify(context, emptyMessage) {
let focusedNodeId = this.#host.getFocusedNodeId();
if (!focusedNodeId) {
focusedNodeId = context.visibleNodes[0]?.id ?? null;
this.#host.setFocusedNodeIdSilently(focusedNodeId);
}
if (!focusedNodeId) {
this.#host.notify(emptyMessage);
return null;
}
return focusedNodeId;
}
async runKeyboardRenameFocused(context) {
const focusedNodeId = this.resolveFocusedNodeIdOrNotify(
context,
"Keyboard rename requires at least one visible row."
);
if (!focusedNodeId) {
return;
}
const focusedNode = context.nodeById.get(focusedNodeId);
if (!focusedNode) {
this.#host.notify("Keyboard rename failed: focused row is stale.");
return;
}
if (this.#host.getInlineRenameNodeId() === focusedNode.id) {
await this.#host.commitInlineRename(context.actions, focusedNode.id);
return;
}
this.#host.beginInlineRename(focusedNode.id, focusedNode.label);
}
async runKeyboardDeleteSelectionOrFocused(context) {
const explicitSelectedNodeIds = resolveExplicitSelectionNodeIds({
explicitSelectedNodes: context.explicitSelectedNodes
});
const explicitSelectedNodeId = explicitSelectedNodeIds.length === 1 ? explicitSelectedNodeIds[0] ?? null : null;
if (explicitSelectedNodeId) {
await context.actions.deleteNode(explicitSelectedNodeId);
return;
}
if (context.selection.elementIds.length > 0) {
await context.actions.commands.deleteNode({
elementIds: context.selection.elementIds
});
return;
}
const focusedNodeId = this.#host.getFocusedNodeId();
if (!focusedNodeId) {
this.#host.notify(renderKeyboardSelectionRequirementMessage("delete"));
return;
}
await context.actions.deleteNode(focusedNodeId);
}
async runKeyboardGroupSelection(context) {
const explicitSelectedNodeIds = resolveExplicitSelectionNodeIds({
explicitSelectedNodes: context.explicitSelectedNodes
});
if (explicitSelectedNodeIds.length > 0) {
await context.actions.createGroupFromNodeIds({
nodeIds: explicitSelectedNodeIds
});
return;
}
if (context.selection.elementIds.length > 0) {
await context.actions.commands.createGroup({
elementIds: context.selection.elementIds
});
return;
}
const focusedNodeId = this.resolveFocusedNodeIdOrNotify(
context,
renderKeyboardSelectionRequirementMessage("group")
);
if (!focusedNodeId) {
return;
}
await context.actions.createGroupFromNodeIds({
nodeIds: [focusedNodeId]
});
}
async runKeyboardReorder(context, mode) {
const explicitSelectedNodeIds = resolveExplicitSelectionNodeIds({
explicitSelectedNodes: context.explicitSelectedNodes
});
if (explicitSelectedNodeIds.length > 0) {
await context.actions.reorderFromNodeIds(explicitSelectedNodeIds, mode);
return;
}
if (context.selection.elementIds.length > 0) {
await context.actions.commands.reorder({
orderedElementIds: context.selection.elementIds,
mode
});
return;
}
const focusedNodeId = this.resolveFocusedNodeIdOrNotify(
context,
renderKeyboardSelectionRequirementMessage("reorder")
);
if (!focusedNodeId) {
return;
}
await context.actions.reorderFromNodeIds([focusedNodeId], mode);
}
async runKeyboardUngroupLike(context) {
if (context.selection.elementIds.length > 0) {
await this.#host.moveSelectionToRoot(context.actions, context.selection);
return;
}
const focusedNodeId = this.resolveFocusedNodeIdOrNotify(
context,
renderKeyboardSelectionRequirementMessage("move out of group")
);
if (!focusedNodeId) {
return;
}
const focusedNode = context.nodeById.get(focusedNodeId);
if (!focusedNode) {
this.#host.notify("Keyboard move out of group failed: focused row is stale.");
return;
}
const structuralMove = resolveFocusedNodeStructuralMove(focusedNode);
if (!structuralMove) {
this.#host.notify(
"Keyboard move out of group failed: frame rows cannot be structurally moved."
);
return;
}
const targetFrameId = focusedNode.frameId ?? null;
const outcome = await context.actions.reparentFromNodeIds({
nodeIds: structuralMove.nodeIds,
sourceGroupId: structuralMove.sourceGroupId,
targetParentPath: [],
targetFrameId
});
if (didInteractionApply(outcome)) {
this.#host.setLastQuickMoveDestinationToRoot(targetFrameId);
}
}
};
// src/runtime/sidepanelLifecycleBinding.ts var ownerKey = /* @PURE */ Symbol.for("excalidraw-layer-manager.sidepanel-lifecycle-owner"); var getOwner = (tab) => Reflect.get(tab, ownerKey); var hasSidepanelLifecycleOwner = (tab) => { return getOwner(tab) !== void 0; }; var bindTargetView = (ea2, view) => { try { ea2.setView?.call(ea2, view, false); } catch { } if (ea2.targetView !== view) { try { ea2.targetView = view; } catch { } } }; var createRuntimeSidepanelLifecycleBinding = (input) => { let disposed = false; let boundTab = null; let restore = []; const release = () => { if (boundTab && getOwner(boundTab) === binding) Reflect.deleteProperty(boundTab, ownerKey); boundTab = null; for (const restoreHook of restore) restoreHook(); restore = []; }; const sync = () => { if (disposed) return; const tab = input.ea.sidepanelTab ?? null; if (tab === boundTab) return; release(); if (!tab) return; getOwner(tab)?.release(); boundTab = tab; Object.defineProperty(tab, ownerKey, { value: binding, configurable: true }); let closed = false; const owns = () => !disposed && !closed && boundTab === tab && getOwner(tab) === binding; const install = (key, handler) => { const descriptor = Object.getOwnPropertyDescriptor(tab, key); tab[key] = handler; restore.push(() => { if (tab[key] !== handler) return; if (descriptor) Object.defineProperty(tab, key, descriptor); else Reflect.deleteProperty(tab, key); }); }; const previousOpen = tab.onOpen; install("onOpen", () => { if (!owns()) return; try { return previousOpen?.call(tab); } finally { if (owns()) input.requestRefresh(); } }); const previousFocus = tab.onFocus; install("onFocus", (view) => { if (!owns()) return; try { return previousFocus?.call(tab, view); } finally { if (owns()) { bindTargetView(input.ea, view); input.onFocus?.(view); input.requestRefresh(); } } }); const previousClose = tab.onClose; install("onClose", () => { if (!owns()) return; closed = true; try { return previousClose?.call(tab); } finally { input.requestDispose(); } }); const previousViewClosed = tab.onExcalidrawViewClosed; install("onExcalidrawViewClosed", () => { if (!owns()) return; try { return previousViewClosed?.call(tab); } finally { if (owns()) { bindTargetView(input.ea, null); input.onFocus?.(null); input.requestRefresh(); } } }); const previousMigration = tab.onWindowMigrated; install("onWindowMigrated", (win) => { if (!owns()) return; try { return previousMigration?.call(tab, win); } finally { if (owns()) { input.onWindowMigrated?.(win); input.requestRefresh(); } } }); }; const binding = { sync, release, dispose: () => { if (disposed) return; disposed = true; release(); } }; sync(); return binding; };
// src/runtime/sidepanelPendingCreationOwnership.ts var registryKey = /* @PURE / Symbol.for("excalidraw-layer-manager.pending-sidepanel-creations.v1"); var createSidepanelPendingCreationLease = (host) => { const scope = host.plugin ?? host.app ?? globalThis; const key = host.activeScript || host; const token = / @PURE / Symbol("pending-sidepanel-invocation"); let disposed = false; const readRegistry = () => Reflect.get(scope, registryKey); const group = () => { let registry = readRegistry(); if (!registry) { registry = / @PURE / new Map(); Object.defineProperty(scope, registryKey, { value: registry, configurable: true }); } let entry = registry.get(key); if (!entry) { entry = { pending: / @PURE / new Set(), orphans: / @PURE */ new Map() }; registry.set(key, entry); } return entry; }; const flush = () => { const registry = readRegistry(); const entry = registry?.get(key); if (!registry || !entry) return; const ownsEntry = () => readRegistry() === registry && registry.get(key) === entry; while (ownsEntry() && entry.pending.size === 0 && entry.orphans.size > 0) { const first = entry.orphans.entries().next().value; if (!first) break; const [tab, cleanup] = first; entry.orphans.delete(tab); cleanup(); } if (ownsEntry() && entry.pending.size === 0 && entry.orphans.size === 0) { registry.delete(key); if (registry.size === 0 && readRegistry() === registry) { Reflect.deleteProperty(scope, registryKey); } } }; const settle = () => { readRegistry()?.get(key)?.pending.delete(token); flush(); }; return { begin: () => { if (!disposed) group().pending.add(token); }, settle, deferOrphan: (tab, cleanup) => { const entry = group(); if (!entry.orphans.has(tab)) entry.orphans.set(tab, cleanup); flush(); }, dispose: () => { disposed = true; settle(); } }; };
// src/ui/sidepanel/mount/sidepanelMountManager.ts
var isPromiseLike = (value) => {
return !!value && typeof value === "object" && "then" in value;
};
var isTabRenderable = (tab) => {
return !!tab && (!!tab.contentEl || typeof tab.setContent === "function");
};
var toMountCapabilities = (host, tab) => {
return {
canUseContentEl: !!tab.contentEl,
canUseSetContent: typeof tab.setContent === "function",
canClose: typeof tab.close === "function" || !!host.closeSidepanelTab
};
};
var isLikelyPersistedTab = (host, tab) => {
const getHostEA = tab.getHostEA;
if (!getHostEA) {
return false;
}
try {
const hostEA = getHostEA.call(tab);
return !!hostEA && hostEA !== host;
} catch {
return false;
}
};
var SIDEPANEL_ROOT_ID = "lmx-sidepanel-content-root";
var isLikelyLayerManagerContentRoot = (element) => {
const candidate = element;
if (candidate.id === SIDEPANEL_ROOT_ID) {
return true;
}
return candidate.tabIndex === 0 && candidate.style?.display === "flex" && candidate.style?.flexDirection === "column" && candidate.style?.gap === "6px" && candidate.style?.padding === "8px";
};
var createSidepanelMountStrategy = (input) => {
if (input.tab.contentEl) {
const contentEl = input.tab.contentEl;
return {
kind: "contentEl",
resolveOwnerDocument: () => contentEl.ownerDocument,
attach: (contentRoot) => {
for (const child of Array.from(contentEl.children)) {
if (child === contentRoot || !isLikelyLayerManagerContentRoot(child)) {
continue;
}
child.remove();
}
if (!contentEl.contains(contentRoot)) {
contentEl.appendChild(contentRoot);
}
return {
ok: true
};
}
};
}
if (input.tab.setContent) {
const setContent = input.tab.setContent;
return {
kind: "setContent",
resolveOwnerDocument: () => {
if (input.existingContentRoot) {
return input.existingContentRoot.ownerDocument;
}
if (typeof document !== "undefined") {
return document;
}
return null;
},
attach: (contentRoot) => {
try {
setContent.call(input.tab, contentRoot);
return {
ok: true
};
} catch {
input.onSetContentFailure();
return {
ok: false,
reason: "setContentFailed"
};
}
}
};
}
return null;
};
var toMountFailureMessage = (reason) => {
switch (reason) {
case "tabCreationFailed":
return "Failed to create Layer Manager sidepanel tab.";
case "tabUnavailable":
return "Layer Manager sidepanel unavailable in this host. Falling back to console renderer.";
case "tabUnrenderable":
return "Layer Manager sidepanel tab is not renderable in this host. Falling back to console renderer.";
case "ownerDocumentUnavailable":
return "Layer Manager sidepanel owner document is unavailable. Falling back to console renderer.";
case "attachTargetMissing":
return "Layer Manager sidepanel has no valid attach target. Falling back to console renderer.";
case "setContentFailed":
return null;
}
};
var sidepanelMountMachine = setup({
types: {
context: {},
input: {},
events: {}
},
actions: {
markAttachRetry: assign({
mountTelemetry: ({ context }) => ({
...context.mountTelemetry,
attachRetryCount: context.mountTelemetry.attachRetryCount + 1
})
}),
registerPendingTabCreationFromEvent: assign({
pendingTabCreation: ({ context, event }) => {
if (event.type !== "REGISTER_PENDING_TAB_CREATION") {
return context.pendingTabCreation;
}
return event.pendingTabCreation;
}
}),
clearPendingTabCreationFromEvent: assign({
pendingTabCreation: ({ context, event }) => {
if (event.type !== "CLEAR_PENDING_TAB_CREATION") {
return context.pendingTabCreation;
}
return context.pendingTabCreation === event.pendingTabCreation ? null : context.pendingTabCreation;
}
}),
registerAsyncResolvedTabFromEvent: ({ context, event }) => {
if (event.type !== "REGISTER_ASYNC_RESOLVED_TAB") {
return;
}
context.host.sidepanelTab = event.tab;
if (event.persisted) {
context.onPersistedTabDetected();
}
context.onAsyncTabResolved();
},
registerActiveTabFromEvent: assign(({ context, event }) => {
if (event.type !== "REGISTER_ACTIVE_TAB") {
return {};
}
context.host.sidepanelTab = event.tab;
const didSwitch = event.tab !== context.activeTab;
if (didSwitch) {
context.onTabSwitched();
}
return {
activeTab: event.tab,
didOpenTab: didSwitch ? false : context.didOpenTab,
mountCapabilities: toMountCapabilities(context.host, event.tab)
};
}),
markActiveTabOpened: assign(({ context }) => {
context.activeTab?.open?.();
return {
didOpenTab: true
};
}),
markAttachAttempt: assign({
mountTelemetry: ({ context }) => ({
...context.mountTelemetry,
attachCount: context.mountTelemetry.attachCount + 1
})
}),
recordAttachFailureFromEvent: assign(({ context, event }) => {
if (event.type !== "ATTACH_FAILED") {
return {};
}
context.debugLifecycle(mount failed with reason=${event.reason});
if (context.lastNotifiedMountFailureReason !== event.reason) {
const failureMessage = toMountFailureMessage(event.reason);
if (failureMessage) {
context.notify(failureMessage);
}
}
return {
lastMountFailureReason: event.reason,
lastNotifiedMountFailureReason: event.reason,
mountTelemetry: {
...context.mountTelemetry,
attachFailureCount: context.mountTelemetry.attachFailureCount + 1
}
};
}),
clearAttachFailure: assign({
lastMountFailureReason: null,
lastNotifiedMountFailureReason: null
}),
adoptPersistedTabFromEvent: assign(({ context, event }) => {
if (event.type !== "ADOPT_PERSISTED_TAB") {
return {};
}
context.host.sidepanelTab = event.tab;
const didSwitch = event.tab !== context.activeTab;
if (didSwitch) {
context.onTabSwitched();
}
return {
activeTab: event.tab,
didOpenTab: didSwitch ? false : context.didOpenTab,
mountCapabilities: toMountCapabilities(context.host, event.tab)
};
}),
resetAfterClose: assign(({ context }) => {
context.host.sidepanelTab = null;
return {
activeTab: null,
didOpenTab: false,
pendingTabCreation: null,
mountCapabilities: null
};
})
}
}).createMachine({
id: "sidepanelMount",
initial: "idle",
context: ({ input }) => ({
host: input.host,
notify: input.notify,
debugLifecycle: input.debugLifecycle,
onTabSwitched: input.onTabSwitched,
onAsyncTabResolved: input.onAsyncTabResolved,
onPersistedTabDetected: input.onPersistedTabDetected,
activeTab: null,
didOpenTab: false,
pendingTabCreation: null,
lastMountFailureReason: null,
lastNotifiedMountFailureReason: null,
mountCapabilities: null,
mountTelemetry: {
attachCount: 0,
attachFailureCount: 0,
attachRetryCount: 0
}
}),
on: {
MARK_ATTACH_RETRY: {
actions: "markAttachRetry"
},
REGISTER_PENDING_TAB_CREATION: {
actions: "registerPendingTabCreationFromEvent"
},
CLEAR_PENDING_TAB_CREATION: {
actions: "clearPendingTabCreationFromEvent"
},
REGISTER_ASYNC_RESOLVED_TAB: {
actions: "registerAsyncResolvedTabFromEvent"
},
REGISTER_ACTIVE_TAB: {
actions: "registerActiveTabFromEvent"
},
MARK_ACTIVE_TAB_OPENED: {
actions: "markActiveTabOpened"
}
},
states: {
idle: {
on: {
START_PREPARE_MOUNT: {
target: "resolvingTab"
},
ADOPT_PERSISTED_TAB: {
target: "mounted",
actions: "adoptPersistedTabFromEvent"
},
RESET_AFTER_CLOSE: {
target: "closed",
actions: "resetAfterClose"
}
}
},
resolvingTab: {
on: {
START_PREPARE_MOUNT: {
target: "resolvingTab"
},
MARK_ATTACH_ATTEMPT: {
target: "mounting",
actions: "markAttachAttempt"
},
ATTACH_FAILED: {
target: "failed",
actions: "recordAttachFailureFromEvent"
},
ADOPT_PERSISTED_TAB: {
target: "mounted",
actions: "adoptPersistedTabFromEvent"
},
RESET_AFTER_CLOSE: {
target: "closed",
actions: "resetAfterClose"
}
}
},
mounting: {
on: {
ATTACH_SUCCEEDED: {
target: "mounted",
actions: "clearAttachFailure"
},
ATTACH_FAILED: {
target: "failed",
actions: "recordAttachFailureFromEvent"
},
ADOPT_PERSISTED_TAB: {
target: "mounted",
actions: "adoptPersistedTabFromEvent"
},
RESET_AFTER_CLOSE: {
target: "closed",
actions: "resetAfterClose"
}
}
},
mounted: {
on: {
START_PREPARE_MOUNT: {
target: "resolvingTab"
},
MARK_ATTACH_ATTEMPT: {
target: "mounting",
actions: "markAttachAttempt"
},
ATTACH_FAILED: {
target: "failed",
actions: "recordAttachFailureFromEvent"
},
ATTACH_SUCCEEDED: {
actions: "clearAttachFailure"
},
ADOPT_PERSISTED_TAB: {
target: "mounted",
actions: "adoptPersistedTabFromEvent"
},
RESET_AFTER_CLOSE: {
target: "closed",
actions: "resetAfterClose"
}
}
},
failed: {
on: {
START_PREPARE_MOUNT: {
target: "resolvingTab"
},
ADOPT_PERSISTED_TAB: {
target: "mounted",
actions: "adoptPersistedTabFromEvent"
},
RESET_AFTER_CLOSE: {
target: "closed",
actions: "resetAfterClose"
}
}
},
closed: {
on: {
START_PREPARE_MOUNT: {
target: "resolvingTab"
},
ADOPT_PERSISTED_TAB: {
target: "mounted",
actions: "adoptPersistedTabFromEvent"
},
RESET_AFTER_CLOSE: {
actions: "resetAfterClose"
}
}
}
}
});
var createSidepanelMountActor = (input) => {
return createActor(sidepanelMountMachine, {
input
});
};
var SidepanelMountManager = class {
#host;
#title;
#actor;
#lifecycle;
#pendingCreation;
#disposed = false;
#creationFailed = false;
#failure = null;
constructor(input) {
this.#host = input.host;
this.#title = input.title;
this.#pendingCreation = createSidepanelPendingCreationLease(this.#host);
this.#actor = createSidepanelMountActor(input);
this.#actor.subscribe({
error: (error) => {
this.#failure = { error };
try {
this.dispose();
} finally {
input.lifecycle?.requestDispose();
}
}
});
this.#actor.start();
this.#lifecycle = createRuntimeSidepanelLifecycleBinding({
ea: this.#host,
requestRefresh: input.lifecycle?.requestRefresh ?? input.onAsyncTabResolved,
requestDispose: () => {
this.dispose();
input.lifecycle?.requestDispose();
},
...input.lifecycle?.onFocus ? { onFocus: input.lifecycle.onFocus } : {},
...input.lifecycle?.onWindowMigrated ? { onWindowMigrated: input.lifecycle.onWindowMigrated } : {}
});
}
get #snapshot() {
return this.#actor.getSnapshot();
}
get mountCapabilities() {
return this.#snapshot.context.mountCapabilities;
}
get mountTelemetry() {
return this.#snapshot.context.mountTelemetry;
}
adoptPersistedTab(tab) {
if (this.#disposed) {
return;
}
this.bindLifecycleToTab(tab);
this.#actor.send({
type: "ADOPT_PERSISTED_TAB",
tab
});
}
releaseLifecycleBinding() {
this.#lifecycle.release();
}
resetAfterClose() {
if (this.#disposed) {
return;
}
this.releaseLifecycleBinding();
this.#actor.send({
type: "RESET_AFTER_CLOSE"
});
}
dispose() {
if (this.#disposed) {
return;
}
this.#lifecycle.dispose();
this.#disposed = true;
this.#actor.stop();
this.#pendingCreation.dispose();
}
prepareMount(input) {
if (this.#disposed) {
return {
status: "unavailable"
};
}
if (this.#snapshot.matches("failed")) {
this.#actor.send({
type: "MARK_ATTACH_RETRY"
});
}
this.#actor.send({
type: "START_PREPARE_MOUNT"
});
const tabResolution = this.ensureSidepanelTab();
if (this.#failure) throw this.#failure.error;
if (this.#disposed) return { status: "unavailable" };
const tab = tabResolution.tab;
if (!tab) {
if (this.#snapshot.context.pendingTabCreation) {
return {
status: "pending"
};
}
this.#actor.send({
type: "ATTACH_FAILED",
reason: tabResolution.failureReason ?? "tabUnavailable"
});
return {
status: "unavailable"
};
}
const mountStrategy = createSidepanelMountStrategy({
tab,
existingContentRoot: input.resolveExistingContentRoot(),
onSetContentFailure: input.onSetContentFailure
});
if (!mountStrategy) {
this.#actor.send({
type: "ATTACH_FAILED",
reason: "attachTargetMissing"
});
return {
status: "unavailable"
};
}
const ownerDocument = mountStrategy.resolveOwnerDocument();
if (!ownerDocument) {
this.#actor.send({
type: "ATTACH_FAILED",
reason: "ownerDocumentUnavailable"
});
return {
status: "unavailable"
};
}
this.#actor.send({
type: "MARK_ATTACH_ATTEMPT"
});
return {
status: "ready",
mountStrategy,
ownerDocument
};
}
finalizeMountAttach(outcome) {
if (this.#disposed) {
return false;
}
if (!outcome.ok) {
this.#actor.send({
type: "ATTACH_FAILED",
reason: outcome.reason
});
return false;
}
this.#actor.send({
type: "ATTACH_SUCCEEDED"
});
return true;
}
bindLifecycleToTab(tab) {
if (this.#disposed) return;
this.#host.sidepanelTab = tab;
this.#lifecycle.sync();
}
closeOrphanTab(tab) {
if (!tab) return;
this.#pendingCreation.deferOrphan(tab, () => {
if (hasSidepanelLifecycleOwner(tab)) return;
try {
tab.close?.();
} catch {
} finally {
if (this.#host.sidepanelTab === tab) this.#host.sidepanelTab = null;
}
});
}
ensureSidepanelTab() {
let failureReason = this.#creationFailed ? "tabCreationFailed" : null;
let tab = isTabRenderable(this.#host.sidepanelTab) ? this.#host.sidepanelTab : null;
if (!tab && this.#host.sidepanelTab && !isTabRenderable(this.#host.sidepanelTab)) {
failureReason = "tabUnrenderable";
this.#host.sidepanelTab = null;
}
if (!tab && this.#host.checkForActiveSidepanelTabForScript) {
const lookedUp = this.#host.checkForActiveSidepanelTabForScript(this.#host.activeScript);
if (isTabRenderable(lookedUp)) {
if (!this.#host.createSidepanelTab || !isLikelyPersistedTab(this.#host, lookedUp)) {
tab = lookedUp;
}
} else if (lookedUp) {
failureReason = "tabUnrenderable";
}
}
if (!tab && !this.#creationFailed && this.#host.createSidepanelTab && !this.#snapshot.context.pendingTabCreation) {
let created;
try {
created = this.#host.createSidepanelTab(this.#title, false, true);
} catch {
this.#creationFailed = true;
failureReason = "tabCreationFailed";
}
if (isPromiseLike(created)) {
this.#pendingCreation.begin();
const pendingTabCreation = Promise.resolve(created);
this.#actor.send({
type: "REGISTER_PENDING_TAB_CREATION",
pendingTabCreation
});
void pendingTabCreation.then((resolved) => {
if (this.#disposed || this.#snapshot.context.pendingTabCreation !== pendingTabCreation) {
queueMicrotask(() => this.closeOrphanTab(resolved));
return;
}
if (!isTabRenderable(resolved)) {
this.#actor.send({ type: "ATTACH_FAILED", reason: "tabUnrenderable" });
return;
}
this.bindLifecycleToTab(resolved);
this.#actor.send({
type: "REGISTER_ASYNC_RESOLVED_TAB",
tab: resolved,
persisted: isLikelyPersistedTab(this.#host, resolved)
});
}).catch(() => {
if (this.#disposed) {
return;
}
this.#actor.send({ type: "ATTACH_FAILED", reason: "tabCreationFailed" });
}).finally(() => {
this.#pendingCreation.settle();
if (this.#disposed) {
return;
}
this.#actor.send({
type: "CLEAR_PENDING_TAB_CREATION",
pendingTabCreation
});
});
}
if (!isPromiseLike(created) && isTabRenderable(created)) {
tab = created;
} else if (!isPromiseLike(created) && created) {
failureReason = "tabUnrenderable";
} else if (isTabRenderable(this.#host.sidepanelTab)) {
tab = this.#host.sidepanelTab;
}
}
if (!tab) {
return {
tab: null,
failureReason
};
}
this.bindLifecycleToTab(tab);
this.#actor.send({
type: "REGISTER_ACTIVE_TAB",
tab
});
if (isLikelyPersistedTab(this.#host, tab)) {
this.#snapshot.context.onPersistedTabDetected();
}
tab.setTitle?.(this.#title);
if (!this.#snapshot.context.didOpenTab) {
this.#actor.send({
type: "MARK_ACTIVE_TAB_OPENED"
});
}
return {
tab,
failureReason: null
};
}
};
// src/ui/sidepanel/prompt/promptInteractionService.ts
var collectPromptSources = (ownerDocument) => {
const sources = [];
const pushPromptSource = (owner) => {
if (!owner || typeof owner !== "object" && typeof owner !== "function") {
return;
}
const promptCandidate = owner["prompt"];
if (typeof promptCandidate !== "function") {
return;
}
sources.push({
owner,
prompt: promptCandidate
});
};
pushPromptSource(globalThis);
pushPromptSource(globalThis.window);
pushPromptSource(ownerDocument?.defaultView ?? null);
return sources;
};
var resolvePromptRaw = (ownerDocument, message, initialValue) => {
const promptSources = collectPromptSources(ownerDocument);
for (const source of promptSources) {
try {
const response = source.prompt.call(source.owner, message, initialValue);
if (response === null || typeof response === "string") {
return {
available: true,
value: response
};
}
return {
available: true,
value: ${response}
};
} catch {
}
}
return {
available: false
};
};
var finalizeInteractionWindow = (host, actions) => {
actions.endInteraction();
host.suppressKeyboardAfterPrompt();
host.setShouldAutofocusContentRoot(true);
host.focusContentRoot();
};
var runInteractionWindow = (host, actions, operation) => {
actions.beginInteraction();
try {
return operation();
} finally {
finalizeInteractionWindow(host, actions);
}
};
var promptInteractionMachine = setup({
types: {
context: {},
input: {},
events: {}
},
actions: {
runInteractionWindowEvent: ({ context, event }) => {
if (event.type !== "RUN_INTERACTION_WINDOW") {
return;
}
try {
const result = runInteractionWindow(context.host, event.actions, event.operation);
event.respond(result);
} catch (error) {
event.fail(error);
}
},
runPromptWithInteractionEvent: ({ context, event }) => {
if (event.type !== "PROMPT_WITH_INTERACTION") {
return;
}
try {
const result = runInteractionWindow(context.host, event.actions, () => {
const promptResult = resolvePromptRaw(
context.host.getOwnerDocument(),
event.message,
event.initialValue
);
if (!promptResult.available) {
context.host.notify(event.unsupportedPromptMessage);
return {
cancelled: true
};
}
if (promptResult.value === null) {
return {
cancelled: true
};
}
return {
cancelled: false,
value: promptResult.value
};
});
event.respond(result);
} catch (error) {
event.fail(error);
}
}
}
}).createMachine({
id: "sidepanelPromptInteraction",
initial: "ready",
context: ({ input }) => ({
host: input.host
}),
states: {
ready: {
on: {
RUN_INTERACTION_WINDOW: {
actions: "runInteractionWindowEvent"
},
PROMPT_WITH_INTERACTION: {
actions: "runPromptWithInteractionEvent"
}
}
}
}
});
var createPromptInteractionActor = (input) => {
return createActor(promptInteractionMachine, {
input
});
};
var SidepanelPromptInteractionService = class {
#host;
#actor;
constructor(host) {
this.#host = host;
this.#actor = createPromptInteractionActor({
host
});
this.#actor.start();
}
dispose() {
this.#actor.stop();
}
promptRaw(message, initialValue) {
return resolvePromptRaw(this.#host.getOwnerDocument(), message, initialValue);
}
withInteractionWindow(actions, operation) {
let settled = false;
let result;
let failure;
this.#actor.send({
type: "RUN_INTERACTION_WINDOW",
actions,
operation,
respond: (nextResult) => {
settled = true;
result = nextResult;
},
fail: (error) => {
settled = true;
failure = error;
}
});
if (!settled) {
throw new Error("Prompt interaction actor did not settle synchronously.");
}
if (failure !== void 0) {
throw failure;
}
return result;
}
withPromptlessInteraction(actions, operation) {
return this.withInteractionWindow(actions, operation);
}
promptWithInteraction(actions, message, initialValue, unsupportedPromptMessage) {
let result = null;
let failure;
this.#actor.send({
type: "PROMPT_WITH_INTERACTION",
actions,
message,
initialValue,
unsupportedPromptMessage,
respond: (nextResult) => {
result = nextResult;
},
fail: (error) => {
failure = error;
}
});
if (failure !== void 0) {
throw failure;
}
if (!result) {
throw new Error("Prompt interaction actor did not produce a prompt result.");
}
return result;
}
};
// src/ui/sidepanel/quickmove/presetHelpers.ts
var resolveNodeFrameId = (node) => {
return resolveFrameRowElementId(node) ?? node.frameId ?? null;
};
var resolveSharedFrame = (nodes) => {
let frameId;
for (const node of nodes) {
const nodeFrameId = resolveNodeFrameId(node);
if (frameId === void 0) {
frameId = nodeFrameId;
continue;
}
if (frameId !== nodeFrameId) {
return {
ok: false,
frameId: null
};
}
}
return {
ok: true,
frameId: frameId ?? null
};
};
var truncateLabel = (label, maxLength) => {
if (label.length <= maxLength) {
return label;
}
return ${label.slice(0, maxLength - 1)}…;
};
var makePresetOptionLabel = (path) => {
if (path.length === 0) {
return "Root";
}
return Inside ${path.join(" › ")};
};
var makePresetKey = (path, targetFrameId) => {
return ${targetFrameId ?? "null"}:${path.join("/")};
};
var collectGroupReparentPresets = (tree, maxCount, includeNestedGroups) => {
const presets = [];
const seenKeys = /* @PURE */ new Set();
const appendPreset = (path, labelPath, targetFrameId) => {
const key = makePresetKey(path, targetFrameId);
if (seenKeys.has(key)) {
return false;
}
seenKeys.add(key);
presets.push({
key,
label: makePresetOptionLabel(labelPath),
targetParentPath: path,
targetFrameId
});
return true;
};
const walk = (nodes, parentPath, parentLabelPath, groupAncestorDepth) => {
for (const node of nodes) {
if (presets.length >= maxCount) {
return true;
}
let nextPath = parentPath;
let nextLabelPath = parentLabelPath;
let nextGroupAncestorDepth = groupAncestorDepth;
if (node.type === "group" && node.groupId) {
nextPath = [...parentPath, node.groupId];
nextLabelPath = [...parentLabelPath, node.label];
if (includeNestedGroups || groupAncestorDepth === 0) {
appendPreset(nextPath, nextLabelPath, resolveNodeFrameId(node));
if (presets.length >= maxCount) {
return true;
}
}
nextGroupAncestorDepth = groupAncestorDepth + 1;
}
if (node.children.length > 0) {
const finished = walk(node.children, nextPath, nextLabelPath, nextGroupAncestorDepth);
if (finished) {
return true;
}
}
}
return false;
};
walk(tree, [], [], 0);
return presets;
};
var collectTopLevelGroupReparentPresets = (tree, maxCount = Number.MAX_SAFE_INTEGER) => {
return collectGroupReparentPresets(tree, maxCount, false);
};
var collectAllGroupReparentPresets = (tree, maxCount = Number.MAX_SAFE_INTEGER) => {
return collectGroupReparentPresets(tree, maxCount, true);
};
// src/ui/sidepanel/quickmove/destinationProjection.ts
var getDestinationIdentity = (destination) => {
return destination.kind === "root" ? root:${destination.targetFrameId ?? "null"} : destination.preset.key;
};
var collectLiveFrameProjection = (tree) => {
const liveFrameIds = /* @PURE / new Set();
const frameLabelById = / @PURE / new Map();
const stack = [...tree];
while (stack.length > 0) {
const node = stack.pop();
if (!node) {
continue;
}
const frameId = resolveNodeFrameId(node);
if (node.type === "frame" && frameId) {
liveFrameIds.add(frameId);
frameLabelById.set(frameId, node.label);
}
for (let index = node.children.length - 1; index >= 0; index -= 1) {
const child = node.children[index];
if (child) {
stack.push(child);
}
}
}
return {
liveFrameIds,
frameLabelById
};
};
var isLiveRootDestination = (destination, liveFrameIds) => {
return !destination.targetFrameId || liveFrameIds.has(destination.targetFrameId);
};
var describeDestinationFrame = (targetFrameId, frameLabelById) => {
if (!targetFrameId) {
return "canvas";
}
return frame ${frameLabelById.get(targetFrameId) ?? targetFrameId};
};
var describeCanonicalPath = (preset) => {
return preset.targetParentPath.join("/");
};
var disambiguatePresetLabels = (presets, frameLabelById) => {
const labelsByKey = new Map(presets.map((preset) => [preset.key, preset.label]));
const qualifierResolvers = [
(preset) => describeDestinationFrame(preset.targetFrameId, frameLabelById),
(preset) => describeCanonicalPath(preset),
(preset) => preset.key
];
for (const resolveQualifier of qualifierResolvers) {
const presetsByLabel = / @PURE / new Map();
for (const preset of presets) {
const currentLabel = labelsByKey.get(preset.key) ?? preset.label;
const existing = presetsByLabel.get(currentLabel);
if (existing) {
existing.push(preset);
continue;
}
presetsByLabel.set(currentLabel, [preset]);
}
const duplicateEntries = [...presetsByLabel.entries()].filter(
([, entries]) => entries.length > 1
);
if (duplicateEntries.length === 0) {
break;
}
for (const [, duplicatePresets] of duplicateEntries) {
for (const preset of duplicatePresets) {
const currentLabel = labelsByKey.get(preset.key) ?? preset.label;
labelsByKey.set(preset.key, ${currentLabel} — ${resolveQualifier(preset)});
}
}
}
return presets.map((preset) => ({
...preset,
label: labelsByKey.get(preset.key) ?? preset.label
}));
};
var stableRankByCompatibility = (values, isCompatible) => {
return values.map((value, index) => ({
value,
index,
compatibilityRank: isCompatible(value) ? 0 : 1
})).sort((left, right) => {
if (left.compatibilityRank !== right.compatibilityRank) {
return left.compatibilityRank - right.compatibilityRank;
}
return left.index - right.index;
}).map((entry) => entry.value);
};
var isPresetFrameCompatible = (frameResolution, preset) => {
return frameResolution.ok && frameResolution.frameId === preset.targetFrameId;
};
var isRootFrameCompatible = (frameResolution, destination) => {
return frameResolution.ok && frameResolution.frameId === destination.targetFrameId;
};
var isDestinationFrameCompatible = (frameResolution, destination) => {
if (destination.kind === "root") {
return isRootFrameCompatible(frameResolution, destination);
}
return isPresetFrameCompatible(frameResolution, destination.preset);
};
var rankGroupReparentPresetsByCompatibility = (presets, frameResolution) => {
if (!frameResolution.ok) {
return [...presets];
}
return stableRankByCompatibility(
presets,
(preset) => isPresetFrameCompatible(frameResolution, preset)
);
};
var rankQuickMoveDestinationsByCompatibility = (destinations, frameResolution) => {
if (!frameResolution.ok) {
return [...destinations];
}
return stableRankByCompatibility(
destinations,
(destination) => isDestinationFrameCompatible(frameResolution, destination)
);
};
var buildSidepanelQuickMoveDestinationProjection = (tree, quickPresetTotalMax, allDestinationTotalMax) => {
const frameProjection = collectLiveFrameProjection(tree);
const allKnownDestinations = disambiguatePresetLabels(
collectAllGroupReparentPresets(tree),
frameProjection.frameLabelById
);
const destinationByKey = new Map(allKnownDestinations.map((preset) => [preset.key, preset]));
const topLevelPresets = collectTopLevelGroupReparentPresets(tree, quickPresetTotalMax).map(
(preset) => destinationByKey.get(preset.key) ?? preset
);
return {
topLevelPresets,
allDestinations: allKnownDestinations.slice(0, allDestinationTotalMax),
destinationByKey,
destinationPickerWasCapped: allKnownDestinations.length > allDestinationTotalMax,
liveFrameIds: frameProjection.liveFrameIds,
frameLabelById: frameProjection.frameLabelById
};
};
var projectQuickMoveDestination = (destination, destinationByKey, liveFrameIds) => {
if (!destination) {
return null;
}
if (destination.kind === "root") {
return isLiveRootDestination(destination, liveFrameIds) ? destination : null;
}
const livePreset = destinationByKey.get(destination.preset.key);
if (!livePreset) {
return null;
}
return {
kind: "preset",
preset: livePreset
};
};
var projectQuickMoveDestinations = (destinations, destinationByKey, liveFrameIds) => {
const projected = [];
const seenDestinationIds = / @PURE */ new Set();
for (const destination of destinations) {
const nextDestination = projectQuickMoveDestination(destination, destinationByKey, liveFrameIds);
if (!nextDestination) {
continue;
}
const destinationIdentity = getDestinationIdentity(nextDestination);
if (seenDestinationIds.has(destinationIdentity)) {
continue;
}
seenDestinationIds.add(destinationIdentity);
projected.push(nextDestination);
}
return projected;
};
var resolveProjectedQuickMovePreset = (targetParentPath, targetFrameId, destinationByKey) => {
return destinationByKey.get(makePresetKey(targetParentPath, targetFrameId)) ?? null;
};
// src/ui/sidepanel/quickmove/quickMovePersistenceService.ts var SETTING_KEY_PERSIST_LAST_MOVE = "lmx_persist_last_move_destination"; var SETTING_KEY_LAST_MOVE_DESTINATION = "lmx_last_move_destination"; var SETTING_DESC_PERSIST_LAST_MOVE = "Persist LayerManager quick-move destination across Obsidian restarts"; var SETTING_DESC_LAST_MOVE_DESTINATION = "LayerManager quick-move destination payload"; var RECENT_DESTINATION_LIMIT = 4; var toPersistedLastMovePayload = (destination) => { if (destination.kind === "root") { return { kind: "root", targetFrameId: destination.targetFrameId }; } return { kind: "preset", targetParentPath: [...destination.preset.targetParentPath], targetFrameId: destination.preset.targetFrameId, label: destination.preset.label }; }; var fromPersistedLastMovePayload = (value) => { if (!value || typeof value !== "object") { return null; } const payload = value; const kind = payload["kind"]; if (kind === "root") { const rawTargetFrameId2 = payload["targetFrameId"]; return { kind: "root", targetFrameId: typeof rawTargetFrameId2 === "string" ? rawTargetFrameId2 : null }; } if (kind !== "preset") { return null; } const rawPath = payload["targetParentPath"]; if (!Array.isArray(rawPath) || rawPath.length === 0) { return null; } const targetParentPath = []; for (const segment of rawPath) { if (typeof segment !== "string") { return null; } const normalizedSegment = segment.trim(); if (normalizedSegment.length === 0 || normalizedSegment !== segment) { return null; } targetParentPath.push(segment); } const rawTargetFrameId = payload["targetFrameId"]; const targetFrameId = typeof rawTargetFrameId === "string" ? rawTargetFrameId : null; const rawLabel = payload["label"]; const label = typeof rawLabel === "string" && rawLabel.trim().length > 0 ? rawLabel.trim() : makePresetOptionLabel(targetParentPath); const preset = { key: makePresetKey(targetParentPath, targetFrameId), label, targetParentPath, targetFrameId }; return { kind: "preset", preset }; }; var isSameDestination = (left, right) => { if (left.kind === "root" || right.kind === "root") { return left.kind === "root" && right.kind === "root" && left.targetFrameId === right.targetFrameId; } return left.preset.key === right.preset.key; }; var areSamePresetPaths = (left, right) => { if (left.length !== right.length) { return false; } return left.every((segment, index) => segment === right[index]); }; var areEquivalentDestinations = (left, right) => { if (left === right) { return true; } if (!left || !right) { return left === right; } if (left.kind === "root" || right.kind === "root") { return left.kind === "root" && right.kind === "root" && left.targetFrameId === right.targetFrameId; } return left.preset.key === right.preset.key && left.preset.label === right.preset.label && left.preset.targetFrameId === right.preset.targetFrameId && areSamePresetPaths(left.preset.targetParentPath, right.preset.targetParentPath); }; var areEquivalentDestinationLists = (left, right) => { if (left.length !== right.length) { return false; } return left.every( (destination, index) => areEquivalentDestinations(destination, right[index] ?? null) ); }; var buildReboundRecentDestinations = (lastQuickMoveDestination, recentQuickMoveDestinations) => { const reboundDestinations = []; const appendDestination = (destination) => { if (!destination) { return; } if (reboundDestinations.some((existing) => isSameDestination(existing, destination))) { return; } reboundDestinations.push(destination); }; appendDestination(lastQuickMoveDestination); for (const destination of recentQuickMoveDestinations) { appendDestination(destination); if (reboundDestinations.length >= RECENT_DESTINATION_LIMIT) { break; } } return reboundDestinations; }; var SidepanelQuickMovePersistenceService = class { #getScriptSettings; #settingsWriteQueue; #lastQuickMoveDestination = null; #recentQuickMoveDestinations = []; #persistLastMoveAcrossRestarts = false; #didLoadLastMovePersistenceSettings = false; #failedRememberedDestinationRebindTarget = null; constructor(input) { this.#getScriptSettings = input.getScriptSettings; this.#settingsWriteQueue = input.settingsWriteQueue; } get canPersistSettings() { return !!this.#getScriptSettings && this.#settingsWriteQueue.canWrite; } get lastQuickMoveDestination() { return this.#lastQuickMoveDestination; } get recentQuickMoveDestinations() { return this.#recentQuickMoveDestinations; } get persistLastMoveAcrossRestarts() { return this.#persistLastMoveAcrossRestarts; } loadFromSettingsOnce() { if (this.#didLoadLastMovePersistenceSettings) { return; } this.#didLoadLastMovePersistenceSettings = true; const settings = this.#getScriptSettings?.(); if (!settings) { return; } this.#persistLastMoveAcrossRestarts = settings[SETTING_KEY_PERSIST_LAST_MOVE]?.value === true; if (!this.#persistLastMoveAcrossRestarts) { return; } const persistedPayload = settings[SETTING_KEY_LAST_MOVE_DESTINATION]?.value; const persistedDestination = fromPersistedLastMovePayload(persistedPayload); if (!persistedDestination) { return; } this.#lastQuickMoveDestination = persistedDestination; this.rememberRecentDestination(persistedDestination); } async setPersistLastMoveAcrossRestarts(nextValue) { const previousValue = this.#persistLastMoveAcrossRestarts; this.#persistLastMoveAcrossRestarts = nextValue; const persisted = await this.persistLastMovePersistencePreference(); if (!persisted) { this.#persistLastMoveAcrossRestarts = previousValue; return false; } this.clearFailedRememberedDestinationRebindTarget(); return true; } async setLastQuickMoveDestination(destination) { const previousDestination = this.#lastQuickMoveDestination; const previousRecentDestinations = [...this.#recentQuickMoveDestinations]; this.#lastQuickMoveDestination = destination; if (destination) { this.rememberRecentDestination(destination); } const persisted = await this.persistLastMoveDestinationIfEnabled(); if (!persisted) { this.#lastQuickMoveDestination = previousDestination; this.#recentQuickMoveDestinations = previousRecentDestinations; return false; } this.clearFailedRememberedDestinationRebindTarget(); return true; } previewReboundRememberedDestinations(input) { const nextRecentQuickMoveDestinations = buildReboundRecentDestinations( input.lastQuickMoveDestination, input.recentQuickMoveDestinations ); const changed = !areEquivalentDestinations(this.#lastQuickMoveDestination, input.lastQuickMoveDestination) || !areEquivalentDestinationLists( this.#recentQuickMoveDestinations, nextRecentQuickMoveDestinations ); return { lastQuickMoveDestination: input.lastQuickMoveDestination, recentQuickMoveDestinations: nextRecentQuickMoveDestinations, changed }; } shouldSuppressRememberedDestinationRebind(preview) { if (!preview.changed || !this.#persistLastMoveAcrossRestarts) { return false; } const failedTarget = this.#failedRememberedDestinationRebindTarget; if (!failedTarget) { return false; } return areEquivalentDestinations( failedTarget.lastQuickMoveDestination, preview.lastQuickMoveDestination ) && areEquivalentDestinationLists( failedTarget.recentQuickMoveDestinations, preview.recentQuickMoveDestinations ); } async rebindRememberedDestinations(input) { const preview = this.previewReboundRememberedDestinations(input); if (!preview.changed) { return { status: "unchanged" }; } if (this.shouldSuppressRememberedDestinationRebind(preview)) { return { status: "suppressed" }; } const previousLastQuickMoveDestination = this.#lastQuickMoveDestination; const previousRecentQuickMoveDestinations = [...this.#recentQuickMoveDestinations]; this.#lastQuickMoveDestination = preview.lastQuickMoveDestination; this.#recentQuickMoveDestinations = [...preview.recentQuickMoveDestinations]; const persisted = await this.persistLastMoveDestinationIfEnabled(); if (persisted) { this.clearFailedRememberedDestinationRebindTarget(); return { status: "reconciled", persisted: true }; } this.#failedRememberedDestinationRebindTarget = { lastQuickMoveDestination: preview.lastQuickMoveDestination, recentQuickMoveDestinations: [...preview.recentQuickMoveDestinations] }; this.#lastQuickMoveDestination = previousLastQuickMoveDestination; this.#recentQuickMoveDestinations = previousRecentQuickMoveDestinations; return { status: "reconciled", persisted: false, revertedTo: { lastQuickMoveDestination: previousLastQuickMoveDestination, recentQuickMoveDestinations: previousRecentQuickMoveDestinations } }; } clearFailedRememberedDestinationRebindTarget() { this.#failedRememberedDestinationRebindTarget = null; } rememberRecentDestination(destination) { const withoutDuplicate = this.#recentQuickMoveDestinations.filter( (existing) => !isSameDestination(existing, destination) ); this.#recentQuickMoveDestinations = [destination, ...withoutDuplicate].slice( 0, RECENT_DESTINATION_LIMIT ); } persistLastMovePersistencePreference() { const persistLastMoveAcrossRestarts = this.#persistLastMoveAcrossRestarts; const persistedLastMoveDestination = persistLastMoveAcrossRestarts && this.#lastQuickMoveDestination ? toPersistedLastMovePayload(this.#lastQuickMoveDestination) : null; return this.#settingsWriteQueue.enqueue((settings) => { settings[SETTING_KEY_PERSIST_LAST_MOVE] = { value: persistLastMoveAcrossRestarts, description: SETTING_DESC_PERSIST_LAST_MOVE }; settings[SETTING_KEY_LAST_MOVE_DESTINATION] = { value: persistedLastMoveDestination, description: SETTING_DESC_LAST_MOVE_DESTINATION }; }, "Failed to persist last-move preference."); } persistLastMoveDestinationIfEnabled() { if (!this.#persistLastMoveAcrossRestarts) { return Promise.resolve(true); } const persistedLastMoveDestination = this.#lastQuickMoveDestination ? toPersistedLastMovePayload(this.#lastQuickMoveDestination) : null; return this.#settingsWriteQueue.enqueue((settings) => { settings[SETTING_KEY_PERSIST_LAST_MOVE] = { value: true, description: SETTING_DESC_PERSIST_LAST_MOVE }; settings[SETTING_KEY_LAST_MOVE_DESTINATION] = { value: persistedLastMoveDestination, description: SETTING_DESC_LAST_MOVE_DESTINATION }; }, "Failed to persist last move destination."); } };
// src/ui/sidepanel/quickmove/rememberedDestinationReconcileMachine.ts
var shouldProcessCandidate = (service, candidate) => {
const preview = service.previewReboundRememberedDestinations(candidate);
return preview.changed && !service.shouldSuppressRememberedDestinationRebind(preview);
};
var rememberedDestinationReconcileMachine = setup({
types: {
context: {},
input: {},
events: {}
},
actors: {
reconcileRememberedDestinations: fromPromise(
async ({
input
}) => {
return input.service.rebindRememberedDestinations(input.candidate);
}
)
},
guards: {
shouldStartReconcile: ({ context, event }) => {
if (event.type !== "PROJECTION_UPDATED") {
return false;
}
return shouldProcessCandidate(context.service, event.candidate);
},
hasReplayCandidate: ({ context }) => {
const pendingCandidate = context.pendingCandidate;
if (!pendingCandidate) {
return false;
}
return shouldProcessCandidate(context.service, pendingCandidate);
}
},
actions: {
setActiveCandidateFromEvent: assign({
activeCandidate: ({ event }) => event.type === "PROJECTION_UPDATED" ? event.candidate : null,
pendingCandidate: null
}),
updatePendingCandidateFromEvent: assign({
pendingCandidate: ({ context, event }) => {
if (event.type !== "PROJECTION_UPDATED") {
return context.pendingCandidate;
}
return shouldProcessCandidate(context.service, event.candidate) ? event.candidate : null;
}
}),
promotePendingCandidateToActive: assign({
activeCandidate: ({ context }) => context.pendingCandidate,
pendingCandidate: null
}),
clearCandidates: assign({
activeCandidate: null,
pendingCandidate: null
})
}
}).createMachine({
id: "rememberedDestinationReconcile",
initial: "idle",
context: ({ input }) => ({
service: input.service,
notify: input.notify,
activeCandidate: null,
pendingCandidate: null
}),
states: {
idle: {
on: {
PROJECTION_UPDATED: [
{
guard: "shouldStartReconcile",
target: "reconciling",
actions: "setActiveCandidateFromEvent"
},
{
actions: "clearCandidates"
}
]
}
},
reconciling: {
invoke: {
src: "reconcileRememberedDestinations",
input: ({ context }) => {
if (!context.activeCandidate) {
throw new Error("Missing active remembered-destination candidate.");
}
return {
service: context.service,
candidate: context.activeCandidate
};
},
onDone: [
{
guard: "hasReplayCandidate",
target: "reconciling",
actions: [
({ context, event }) => {
if (event.output.status === "reconciled" && !event.output.persisted) {
context.notify(
"Remembered last-move destination reverted because reconciliation could not persist."
);
}
},
"promotePendingCandidateToActive"
]
},
{
target: "idle",
actions: [
({ context, event }) => {
if (event.output.status === "reconciled" && !event.output.persisted) {
context.notify(
"Remembered last-move destination reverted because reconciliation could not persist."
);
}
},
"clearCandidates"
]
}
],
onError: {
target: "idle",
actions: [
({ context, event }) => {
const message = event.error instanceof Error ? event.error.message : String(event.error);
context.notify(Quick-move reconciliation failed: ${message});
},
"clearCandidates"
]
}
},
on: {
PROJECTION_UPDATED: {
actions: "updatePendingCandidateFromEvent"
}
}
}
}
});
var createRememberedDestinationReconcileActor = (input) => {
return createActor(rememberedDestinationReconcileMachine, {
input
});
};
// src/ui/sidepanel/rename/inlineRenameController.ts var haveSameInlineRenameState = (left, right) => { if (!left || !right) { return left === right; } return left.nodeId === right.nodeId && left.draft === right.draft && left.shouldAutofocusInput === right.shouldAutofocusInput; }; var inlineRenameMachine = setup({ types: { context: {}, input: {}, events: {} }, actors: { commitInlineRename: fromPromise(async ({ input }) => { return { nodeId: input.nodeId, draft: input.draft, outcome: await input.actions.renameNode(input.nodeId, input.nextName) }; }) }, guards: { isDuplicateBegin: ({ context, event }) => { if (event.type !== "BEGIN_INLINE_RENAME") { return false; } const current = context.inlineRenameState; return current?.nodeId === event.nodeId && current.draft === event.initialValue; }, hasNonEmptyCommitDraft: ({ context, event }) => { if (event.type !== "COMMIT_INLINE_RENAME") { return false; } const current = context.inlineRenameState; return current?.nodeId === event.nodeId && current.draft.trim().length > 0; }, isCommitForActiveNode: ({ context, event }) => { if (event.type !== "COMMIT_INLINE_RENAME") { return false; } return context.inlineRenameState?.nodeId === event.nodeId; }, didCommitApply: ({ event }) => { const { output } = event; return didInteractionApply(output.outcome); }, hasInlineRenameState: ({ context }) => context.inlineRenameState !== null }, actions: { setInlineRenameStateFromEvent: assign({ inlineRenameState: ({ context, event }) => { if (event.type !== "BEGIN_INLINE_RENAME") { return context.inlineRenameState; } return { nodeId: event.nodeId, draft: event.initialValue, shouldAutofocusInput: true }; } }), updateInlineRenameDraftFromEvent: assign({ inlineRenameState: ({ context, event }) => { if (event.type !== "UPDATE_INLINE_RENAME_DRAFT") { return context.inlineRenameState; } const current = context.inlineRenameState; if (!current) { return current; } return { ...current, draft: event.nextDraft, shouldAutofocusInput: false }; } }), clearInlineRenameState: assign({ inlineRenameState: null }), clearActiveCommit: assign({ activeCommit: null }), clearAll: assign({ inlineRenameState: null, activeCommit: null }), markAutofocusHandledFromEvent: assign({ inlineRenameState: ({ context, event }) => { if (event.type !== "MARK_INLINE_RENAME_AUTOFOCUS_HANDLED") { return context.inlineRenameState; } const current = context.inlineRenameState; if (!current || current.nodeId !== event.nodeId || !current.shouldAutofocusInput) { return current; } return { ...current, shouldAutofocusInput: false }; } }), storeActiveCommitFromEvent: assign({ activeCommit: ({ context, event }) => { if (event.type !== "COMMIT_INLINE_RENAME") { return context.activeCommit; } const current = context.inlineRenameState; if (!current || current.nodeId !== event.nodeId) { return context.activeCommit; } return { nodeId: event.nodeId, nextName: current.draft.trim(), draft: current.draft, actions: event.actions, resolve: event.resolve, reject: event.reject }; } }), resolveCommitAsEmptyName: ({ event }) => { if (event.type !== "COMMIT_INLINE_RENAME") { return; } event.resolve({ kind: "emptyName" }); }, resolveCommitAsIgnored: ({ event }) => { if (event.type !== "COMMIT_INLINE_RENAME") { return; } event.resolve({ kind: "ignored" }); }, resolveAppliedCommit: ({ context, event }) => { const { output } = event; context.activeCommit?.resolve({ kind: "applied", nodeId: output.nodeId, outcome: output.outcome }); }, resolveNotAppliedCommit: ({ context, event }) => { const { output } = event; context.activeCommit?.resolve({ kind: "notApplied", nodeId: output.nodeId, outcome: output.outcome, preservedDraft: output.draft }); }, rejectActiveCommit: ({ context, event }) => { const { error } = event; context.activeCommit?.reject(error); }, notifyEmptyName: ({ context }) => { context.host.notify("Rename failed: name cannot be empty."); } } }).createMachine({ id: "sidepanelInlineRename", initial: "idle", context: ({ input }) => ({ host: input.host, inlineRenameState: null, activeCommit: null }), states: { idle: { on: { BEGIN_INLINE_RENAME: { target: "editing", actions: "setInlineRenameStateFromEvent" }, CLEAR_INLINE_RENAME: { actions: "clearAll" } } }, editing: { on: { BEGIN_INLINE_RENAME: [ { guard: "isDuplicateBegin" }, { actions: "setInlineRenameStateFromEvent" } ], UPDATE_INLINE_RENAME_DRAFT: { actions: "updateInlineRenameDraftFromEvent" }, CANCEL_INLINE_RENAME: { target: "idle", actions: "clearInlineRenameState" }, MARK_INLINE_RENAME_AUTOFOCUS_HANDLED: { actions: "markAutofocusHandledFromEvent" }, CLEAR_INLINE_RENAME: { target: "idle", actions: "clearAll" }, COMMIT_INLINE_RENAME: [ { guard: "hasNonEmptyCommitDraft", target: "committing", actions: "storeActiveCommitFromEvent" }, { guard: "isCommitForActiveNode", actions: ["notifyEmptyName", "resolveCommitAsEmptyName"] }, { actions: "resolveCommitAsIgnored" } ] } }, committing: { invoke: { src: "commitInlineRename", input: ({ context }) => { if (!context.activeCommit) { throw new Error("Missing active inline-rename commit."); } return { actions: context.activeCommit.actions, nodeId: context.activeCommit.nodeId, nextName: context.activeCommit.nextName, draft: context.activeCommit.draft }; }, onDone: [ { guard: "didCommitApply", target: "idle", actions: ["clearInlineRenameState", "resolveAppliedCommit", "clearActiveCommit"] }, { guard: "hasInlineRenameState", target: "editing", actions: ["resolveNotAppliedCommit", "clearActiveCommit"] }, { target: "idle", actions: ["resolveNotAppliedCommit", "clearActiveCommit"] } ], onError: [ { guard: "hasInlineRenameState", target: "editing", actions: ["rejectActiveCommit", "clearActiveCommit"] }, { target: "idle", actions: ["rejectActiveCommit", "clearActiveCommit"] } ] }, on: { CLEAR_INLINE_RENAME: { actions: "clearInlineRenameState" } } } } }); var createInlineRenameActor = (input) => { return createActor(inlineRenameMachine, { input }); }; var SidepanelInlineRenameController = class { #host; #actor; constructor(host) { this.#host = host; this.#actor = createInlineRenameActor({ host }); this.#actor.start(); } get state() { return this.#actor.getSnapshot().context.inlineRenameState; } get nodeId() { return this.state?.nodeId ?? null; } dispose() { this.#actor.stop(); } clear() { this.#actor.send({ type: "CLEAR_INLINE_RENAME" }); } beginInlineRename(nodeId, initialValue) { const previousState = this.state; this.#actor.send({ type: "BEGIN_INLINE_RENAME", nodeId, initialValue }); const nextState = this.state; if (haveSameInlineRenameState(previousState, nextState)) { return; } this.#host.debugInteraction?.("inline rename begin", { nodeId, initialValue, focusedNodeId: this.#host.getFocusedNodeId() }); this.#host.requestRenderFromLatestModel(); } updateInlineRenameDraft(nextDraft) { this.#actor.send({ type: "UPDATE_INLINE_RENAME_DRAFT", nextDraft }); } cancelInlineRename() { if (!this.state || this.#actor.getSnapshot().matches("committing")) { return; } this.#actor.send({ type: "CANCEL_INLINE_RENAME" }); this.#host.setShouldAutofocusContentRoot(true); this.#host.focusContentRoot(); this.#host.requestRenderFromLatestModel(); } async commitInlineRename(actions, nodeId) { const current = this.state; if (!current || current.nodeId !== nodeId || this.#actor.getSnapshot().matches("committing")) { return; } const nextName = current.draft.trim(); if (nextName.length > 0) { this.#host.debugInteraction?.("inline rename commit requested", { nodeId, nextName, focusedNodeId: this.#host.getFocusedNodeId(), keyboardCaptureActive: this.#host.getKeyboardCaptureActive() }); } const resolution = await new Promise((resolve, reject) => { this.#actor.send({ type: "COMMIT_INLINE_RENAME", actions, nodeId, resolve, reject }); }); if (resolution.kind === "emptyName" || resolution.kind === "ignored") { return; } if (resolution.kind === "notApplied") { this.#host.debugInteraction?.("inline rename commit finished", { nodeId: resolution.nodeId, outcomeStatus: resolution.outcome.status, preservedDraft: resolution.preservedDraft, focusedNodeId: this.#host.getFocusedNodeId(), keyboardCaptureActive: this.#host.getKeyboardCaptureActive() }); return; } this.#host.requestRenderFromLatestModel(); this.#host.suppressNextContentFocusOut(); this.#host.setShouldAutofocusContentRoot(true); this.#host.focusContentRoot(); Promise.resolve().then(() => { if (!this.state) { this.#host.requestRenderFromLatestModel(); } }); this.#host.debugInteraction?.("inline rename commit finished", { nodeId: resolution.nodeId, outcomeStatus: resolution.outcome.status, focusedNodeId: this.#host.getFocusedNodeId(), keyboardCaptureActive: this.#host.getKeyboardCaptureActive() }); } markAutofocusHandled(nodeId) { this.#actor.send({ type: "MARK_INLINE_RENAME_AUTOFOCUS_HANDLED", nodeId }); } };
// src/ui/sidepanel/rename/inlineRenameDomSession.ts var containsNode = (nodes, nodeId) => nodes.some((node) => node.id === nodeId || containsNode(node.children, nodeId)); var InlineRenameDomSession = class { #generation = 0; #authority = null; #input = null; #selection = null; get generation() { return this.#generation; } get restoringFocus() { return this.#selection !== null; } begin(host) { this.clear(); this.#authority = { view: host.targetView, api: host.getExcalidrawAPI?.() }; } clear() { this.#generation += 1; this.#authority = null; this.#input = null; this.#selection = null; } owns(generation, host) { return generation === this.#generation && this.hasAuthority(host); } hasAuthority(host) { return !!this.#authority && this.#authority.view === host.targetView && this.#authority.api === host.getExcalidrawAPI?.(); } beforeRender(host, nodeId, tree, contentRoot) { this.#generation += 1; const input = this.#input; this.#input = null; this.#selection = null; if (!nodeId || !this.hasAuthority(host) || !containsNode(tree, nodeId)) { this.clear(); return { discard: true, focusedDraft: null }; } if (input && contentRoot?.contains(input) && input.ownerDocument.activeElement === input) { this.#selection = { start: input.selectionStart, end: input.selectionEnd, direction: input.selectionDirection }; return { discard: false, focusedDraft: input.value }; } return { discard: false, focusedDraft: null }; } setInput(input) { this.#input = input; } restoreFocus() { const selection = this.#selection; this.#selection = null; if (!selection || !this.#input) return; try { this.#input.focus({ preventScroll: true }); if (selection.start !== null && selection.end !== null) { this.#input.setSelectionRange(selection.start, selection.end, selection.direction ?? "none"); } } catch { } } };
// src/ui/sidepanel/render/excalidrawIconNode.ts
var SVG_NS = "http://www.w3.org/2000/svg";
var TABLER_ICON_VIEWBOX = "0 0 24 24";
var DEFAULT_STROKE_WIDTH = "1.5";
var EXCALIDRAW_LIKE_ICON_DEFINITIONS = {
eye: {
strokeWidth: "1.5",
paths: [
{
d: "M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0"
},
{
d: "M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6"
}
]
},
"eye-off": {
paths: [
{
d: "M10.585 10.587a2 2 0 0 0 2.829 2.828"
},
{
d: "M16.681 16.673a8.717 8.717 0 0 1 -4.681 1.327c-3.6 0 -6.6 -2 -9 -6c1.272 -2.12 2.712 -3.678 4.32 -4.674m2.86 -1.146a9.055 9.055 0 0 1 1.82 -.18c3.6 0 6.6 2 9 6c-.666 1.11 -1.379 2.067 -2.138 2.87"
},
{
d: "M3 3l18 18"
}
]
},
lock: {
strokeWidth: "1.25",
paths: [
{
d: "M13.542 8.542H6.458a2.5 2.5 0 0 0-2.5 2.5v3.75a2.5 2.5 0 0 0 2.5 2.5h7.084a2.5 2.5 0 0 0 2.5-2.5v-3.75a2.5 2.5 0 0 0-2.5-2.5Z"
},
{
d: "M10 13.958a1.042 1.042 0 1 0 0-2.083 1.042 1.042 0 0 0 0 2.083Z"
},
{
d: "M6.667 8.333V5.417C6.667 3.806 8.159 2.5 10 2.5c1.841 0 3.333 1.306 3.333 2.917v2.916"
}
]
},
unlock: {
strokeWidth: "1.25",
paths: [
{
d: "M13.542 8.542H6.458a2.5 2.5 0 0 0-2.5 2.5v3.75a2.5 2.5 0 0 0 2.5 2.5h7.084a2.5 2.5 0 0 0 2.5-2.5v-3.75a2.5 2.5 0 0 0-2.5-2.5Z"
},
{
d: "M10 13.958a1.042 1.042 0 1 0 0-2.083 1.042 1.042 0 0 0 0 2.083Z"
},
{
d: "M6.4 9.56V5.18c0-.93.4-1.82 1.12-2.48a3.981 3.981 0 0 1 2.69-1.03c1.01 0 1.98.37 2.69 1.03c.72.66 1.12 1.55 1.12 2.48"
}
]
},
"edit-3": {
strokeWidth: "1.25",
paths: [
{
d: "M4 20h4l10.5 -10.5a2.828 2.828 0 1 0 -4 -4l-10.5 10.5v4"
},
{
d: "M13.5 6.5l4 4"
}
]
},
"trash-2": {
paths: [
{
d: "M4 7l16 0"
},
{
d: "M10 11l0 6"
},
{
d: "M14 11l0 6"
},
{
d: "M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12"
},
{
d: "M9 7l1 -3h4l1 3"
}
]
},
"help-circle": {
paths: [
{
d: "M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"
},
{
d: "M12 17l0 .01"
},
{
d: "M12 13.5a1.5 1.5 0 0 1 1 -1.5a2.6 2.6 0 1 0 -3 -4"
}
]
},
"zindex-send-backward": {
paths: [
{
d: "M12 5l0 14",
transform: "rotate(180 12 12)"
},
{
d: "M16 9l-4 -4",
transform: "rotate(180 12 12)"
},
{
d: "M8 9l4 -4",
transform: "rotate(180 12 12)"
}
]
},
"zindex-bring-forward": {
paths: [
{
d: "M12 5l0 14"
},
{
d: "M16 9l-4 -4"
},
{
d: "M8 9l4 -4"
}
]
},
"zindex-send-to-back": {
paths: [
{
d: "M12 10l0 10",
transform: "rotate(180 12 12)"
},
{
d: "M12 10l4 4",
transform: "rotate(180 12 12)"
},
{
d: "M12 10l-4 4",
transform: "rotate(180 12 12)"
},
{
d: "M4 4l16 0",
transform: "rotate(180 12 12)"
}
]
},
"zindex-bring-to-front": {
paths: [
{
d: "M12 10l0 10"
},
{
d: "M12 10l4 4"
},
{
d: "M12 10l-4 4"
},
{
d: "M4 4l16 0"
}
]
}
};
var createFallbackIconSpan = (ownerDocument, fallbackLabel, sizePx) => {
const fallback = ownerDocument.createElement("span");
fallback.textContent = fallbackLabel;
fallback.style.display = "inline-flex";
fallback.style.alignItems = "center";
fallback.style.justifyContent = "center";
fallback.style.width = ${sizePx}px;
fallback.style.height = ${sizePx}px;
fallback.style.fontSize = ${sizePx}px;
fallback.style.lineHeight = "1";
return fallback;
};
var createExcalidrawLikeIconNode = (ownerDocument, iconName, fallbackLabel, sizePx) => {
const definition = EXCALIDRAW_LIKE_ICON_DEFINITIONS[iconName];
if (!definition) {
return null;
}
if (!("createElementNS" in ownerDocument) || typeof ownerDocument.createElementNS !== "function") {
return createFallbackIconSpan(ownerDocument, fallbackLabel, sizePx);
}
const svg = ownerDocument.createElementNS(SVG_NS, "svg");
svg.setAttribute("viewBox", definition.viewBox ?? TABLER_ICON_VIEWBOX);
svg.setAttribute("fill", "none");
svg.setAttribute("stroke", "currentColor");
svg.setAttribute("stroke-width", definition.strokeWidth ?? DEFAULT_STROKE_WIDTH);
svg.setAttribute("stroke-linecap", "round");
svg.setAttribute("stroke-linejoin", "round");
svg.setAttribute("width", ${sizePx});
svg.setAttribute("height", ${sizePx});
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("focusable", "false");
for (const pathDefinition of definition.paths) {
const path = ownerDocument.createElementNS(SVG_NS, "path");
path.setAttribute("d", pathDefinition.d);
path.setAttribute("fill", pathDefinition.fill ?? "none");
path.setAttribute("stroke", pathDefinition.stroke ?? "currentColor");
if (pathDefinition.strokeWidth) {
path.setAttribute("stroke-width", pathDefinition.strokeWidth);
}
if (pathDefinition.transform) {
path.setAttribute("transform", pathDefinition.transform);
}
svg.appendChild(path);
}
return svg;
};
// src/ui/sidepanel/render/quickMoveRenderer.ts
var RECENT_TARGET_BUTTON_MAX = 2;
var QUICK_MOVE_SHORTCUT_LIMIT = 10;
var styleQuickMoveButton = (button, tone = "neutral") => {
button.style.position = "relative";
button.style.fontSize = "11px";
button.style.lineHeight = "1.2";
button.style.minHeight = "20px";
button.style.padding = "2px 7px";
button.style.borderRadius = "5px";
button.style.border = "1px solid var(--background-modifier-border, rgba(120,120,120,0.18))";
button.style.boxShadow = "none";
button.style.background = tone === "primary" ? "var(--background-secondary-alt, rgba(120,120,120,0.1))" : "var(--background-primary-alt, rgba(120,120,120,0.04))";
};
var styleQuickMoveSelect = (select, maxWidthPx) => {
select.style.fontSize = "11px";
select.style.minHeight = "20px";
select.style.padding = "1px 4px";
select.style.maxWidth = ${maxWidthPx}px;
select.style.borderRadius = "5px";
select.style.border = "1px solid var(--background-modifier-border, rgba(120,120,120,0.18))";
select.style.boxShadow = "none";
select.style.background = "var(--background-primary, transparent)";
};
var createQuickMoveButton = (input, label, action, tone = "neutral") => {
const button = input.createToolbarButton(input.ownerDocument, label, action);
styleQuickMoveButton(button, tone);
return button;
};
var toQuickMoveDestinationKey = (destination) => {
return destination.kind === "root" ? root:${destination.targetFrameId ?? "canvas"} : preset:${destination.preset.key};
};
var appendUniqueQuickMoveDestination = (target, seenKeys, destination) => {
const destinationKey = toQuickMoveDestinationKey(destination);
if (seenKeys.has(destinationKey)) {
return;
}
seenKeys.add(destinationKey);
target.push(destination);
};
var resolveQuickMoveShortcutTargets = (input) => {
const rankedTopLevelPresets = rankGroupReparentPresetsByCompatibility(
input.topLevelPresets,
input.frameResolution
);
const inlinePresets = rankedTopLevelPresets.length <= input.quickPresetInlineMax ? rankedTopLevelPresets : [];
const recentPresetDestinations = rankQuickMoveDestinationsByCompatibility(
input.recentQuickMoveDestinations.filter(
(destination) => {
return destination.kind === "preset";
}
).filter((destination) => {
const lastDestination = input.lastQuickMoveDestination;
if (!lastDestination || lastDestination.kind !== "preset") {
return true;
}
return !isSameDestination2(destination, lastDestination);
}),
input.frameResolution
).slice(0, RECENT_TARGET_BUTTON_MAX);
const destinations = [];
const seenKeys = /* @PURE */ new Set();
appendUniqueQuickMoveDestination(destinations, seenKeys, {
kind: "root",
targetFrameId: input.frameResolution.frameId
});
if (input.lastQuickMoveDestination?.kind === "preset") {
appendUniqueQuickMoveDestination(destinations, seenKeys, input.lastQuickMoveDestination);
}
for (const destination of recentPresetDestinations) {
appendUniqueQuickMoveDestination(destinations, seenKeys, destination);
}
for (const preset of inlinePresets) {
appendUniqueQuickMoveDestination(destinations, seenKeys, {
kind: "preset",
preset
});
}
return destinations.slice(0, QUICK_MOVE_SHORTCUT_LIMIT).map((destination, index) => ({
digit: index,
destination
}));
};
var resolveQuickMoveShortcutDigit = (targets, destination) => {
return targets.find((target) => isSameDestination2(target.destination, destination))?.digit ?? null;
};
var appendShortcutBadge = (button, digit) => {
const badge = button.ownerDocument.createElement("span");
badge.textContent = ${digit};
badge.ariaHidden = "true";
badge.style.position = "absolute";
badge.style.top = "-5px";
badge.style.right = "-5px";
badge.style.display = "inline-flex";
badge.style.alignItems = "center";
badge.style.justifyContent = "center";
badge.style.minWidth = "12px";
badge.style.height = "12px";
badge.style.padding = "0 2px";
badge.style.borderRadius = "999px";
badge.style.border = "1px solid var(--background-modifier-border, rgba(120,120,120,0.28))";
badge.style.background = "var(--background-primary, rgba(24,24,24,0.95))";
badge.style.color = "var(--text-muted, inherit)";
badge.style.fontSize = "8px";
badge.style.fontWeight = "700";
badge.style.lineHeight = "1";
badge.style.pointerEvents = "none";
button.appendChild(badge);
};
var decorateQuickMoveButtonWithShortcut = (input, button, targets, destination) => {
const digit = resolveQuickMoveShortcutDigit(targets, destination);
if (digit === null) {
return;
}
;
button.__lmxQuickMoveShortcutDigit = digit;
if (!input.showShortcutHints) {
return;
}
appendShortcutBadge(button, digit);
};
var resolveSelectionIssue = (selection, _frameResolution) => {
return resolveStructuralSelectionIssue(selection);
};
var describeRootDestination = (destination, frameLabelById) => {
if (!destination.targetFrameId) {
return "Canvas root";
}
const frameLabel = frameLabelById.get(destination.targetFrameId) ?? destination.targetFrameId;
return Frame root: ${frameLabel};
};
var describeFrameSurface = (targetFrameId, frameLabelById) => {
if (!targetFrameId) {
return "canvas";
}
return frame ${frameLabelById.get(targetFrameId) ?? targetFrameId};
};
var describePresetDestinationOptionLabel = (preset, frameLabelById) => {
return ${preset.label} · ${describeFrameSurface(preset.targetFrameId, frameLabelById)};
};
var isSameDestination2 = (left, right) => {
if (left.kind === "root" || right.kind === "root") {
return left.kind === "root" && right.kind === "root" && left.targetFrameId === right.targetFrameId;
}
return left.preset.key === right.preset.key;
};
var renderSidepanelQuickMove = (input) => {
if (!input.hasActions) {
return null;
}
const renderState = {
hasSelection: input.selection.elementIds.length > 0,
frameResolution: input.selection.frameResolution,
selectionIssue: resolveSelectionIssue(input.selection, input.selection.frameResolution)
};
const projectedInput = {
...input,
lastQuickMoveDestination: projectQuickMoveDestination(
input.lastQuickMoveDestination,
input.destinationProjection.destinationByKey,
input.destinationProjection.liveFrameIds
),
recentQuickMoveDestinations: projectQuickMoveDestinations(
input.recentQuickMoveDestinations,
input.destinationProjection.destinationByKey,
input.destinationProjection.liveFrameIds
)
};
const presetRow = createControlRow(projectedInput);
appendRowTitle(
presetRow,
projectedInput,
projectedInput.reviewScope.active ? "Move selection from review scope:" : "Move selection:"
);
const rankedTopLevelPresets = rankGroupReparentPresetsByCompatibility(
projectedInput.destinationProjection.topLevelPresets,
renderState.frameResolution
);
const shortcutTargets = resolveQuickMoveShortcutTargets({
frameResolution: renderState.frameResolution,
topLevelPresets: projectedInput.destinationProjection.topLevelPresets,
lastQuickMoveDestination: projectedInput.lastQuickMoveDestination,
recentQuickMoveDestinations: projectedInput.recentQuickMoveDestinations,
quickPresetInlineMax: projectedInput.quickPresetInlineMax
});
appendLastQuickMoveControl(projectedInput, presetRow, renderState, shortcutTargets);
appendRecentDestinationControls(projectedInput, presetRow, renderState, shortcutTargets);
appendRootMoveControl(projectedInput, presetRow, renderState, shortcutTargets);
if (rankedTopLevelPresets.length <= projectedInput.quickPresetInlineMax) {
appendInlinePresetButtons(
projectedInput,
presetRow,
rankedTopLevelPresets,
renderState,
shortcutTargets
);
} else {
appendPresetDropdown(projectedInput, presetRow, rankedTopLevelPresets, renderState);
}
return presetRow;
};
var createControlRow = (input) => {
const row = input.ownerDocument.createElement("div");
row.style.display = "flex";
row.style.flexWrap = "wrap";
row.style.alignItems = "center";
row.style.gap = "4px";
row.style.marginBottom = "6px";
row.style.padding = "4px 6px";
row.style.borderRadius = "6px";
row.style.border = "1px solid var(--background-modifier-border, rgba(120,120,120,0.16))";
row.style.background = "var(--background-primary-alt, rgba(120,120,120,0.04))";
input.container.appendChild(row);
return row;
};
var appendRowTitle = (row, input, label) => {
const title = input.ownerDocument.createElement("span");
title.textContent = label;
title.style.fontSize = "11px";
title.style.fontWeight = "600";
title.style.opacity = "0.75";
title.style.paddingRight = "2px";
row.appendChild(title);
};
var appendRootMoveControl = (input, presetRow, renderState, shortcutTargets) => {
const rootLabel = renderState.hasSelection && input.lastQuickMoveDestination?.kind === "root" && isRootFrameCompatible(renderState.frameResolution, input.lastQuickMoveDestination) ? "Root ★" : "Root";
const rootButton = createQuickMoveButton(input, rootLabel, async () => {
await input.onMoveSelectionToRoot(renderState.frameResolution.frameId);
});
rootButton.disabled = !!renderState.selectionIssue;
const rootDestination = {
kind: "root",
targetFrameId: renderState.frameResolution.frameId
};
decorateQuickMoveButtonWithShortcut(input, rootButton, shortcutTargets, rootDestination);
presetRow.appendChild(rootButton);
};
var appendLastQuickMoveControl = (input, presetRow, renderState, shortcutTargets) => {
const lastDestination = input.lastQuickMoveDestination;
if (!lastDestination) {
return;
}
const label = lastDestination.kind === "root" ? ↺ Last: ${describeRootDestination(lastDestination, input.destinationProjection.frameLabelById)} : ↺ Last: ${lastDestination.preset.label};
const repeatButton = createQuickMoveButton(
input,
truncateLabel(label, input.lastMoveLabelMax),
async () => {
if (lastDestination.kind === "root") {
await input.onMoveSelectionToRoot(lastDestination.targetFrameId);
return;
}
await input.onApplyGroupPreset(lastDestination.preset);
}
);
if (renderState.selectionIssue) {
repeatButton.disabled = true;
presetRow.appendChild(repeatButton);
return;
}
if (lastDestination.kind === "root" && !isRootFrameCompatible(renderState.frameResolution, lastDestination)) {
repeatButton.disabled = true;
presetRow.appendChild(repeatButton);
return;
}
if (lastDestination.kind === "preset" && !isPresetFrameCompatible(renderState.frameResolution, lastDestination.preset)) {
repeatButton.disabled = true;
presetRow.appendChild(repeatButton);
return;
}
decorateQuickMoveButtonWithShortcut(input, repeatButton, shortcutTargets, lastDestination);
presetRow.appendChild(repeatButton);
};
var appendRecentDestinationControls = (input, presetRow, renderState, shortcutTargets) => {
const recentDestinations = rankQuickMoveDestinationsByCompatibility(
input.recentQuickMoveDestinations.filter((destination) => {
const lastDestination = input.lastQuickMoveDestination;
if (!lastDestination) {
return true;
}
return !isSameDestination2(destination, lastDestination);
}),
renderState.frameResolution
).slice(0, RECENT_TARGET_BUTTON_MAX);
if (recentDestinations.length === 0) {
return;
}
const recentLabel = input.ownerDocument.createElement("span");
recentLabel.textContent = "Recent:";
recentLabel.style.fontSize = "11px";
recentLabel.style.opacity = "0.75";
presetRow.appendChild(recentLabel);
for (const destination of recentDestinations) {
const buttonLabel = destination.kind === "root" ? describeRootDestination(destination, input.destinationProjection.frameLabelById) : truncateLabel(destination.preset.label, input.lastMoveLabelMax);
const button = createQuickMoveButton(input, buttonLabel, async () => {
if (destination.kind === "root") {
await input.onMoveSelectionToRoot(destination.targetFrameId);
return;
}
await input.onApplyGroupPreset(destination.preset);
});
if (renderState.selectionIssue) {
button.disabled = true;
presetRow.appendChild(button);
continue;
}
if (!isDestinationFrameCompatible(renderState.frameResolution, destination)) {
button.disabled = true;
presetRow.appendChild(button);
continue;
}
decorateQuickMoveButtonWithShortcut(input, button, shortcutTargets, destination);
presetRow.appendChild(button);
}
};
var appendInlinePresetButtons = (input, presetRow, presets, renderState, shortcutTargets) => {
for (const preset of presets) {
const lastDestination = input.lastQuickMoveDestination;
const isLastPreset = lastDestination?.kind === "preset" && lastDestination.preset.key === preset.key;
const presetLabel = isLastPreset ? ${preset.label} ★ : preset.label;
const presetButton = createQuickMoveButton(input, presetLabel, async () => {
await input.onApplyGroupPreset(preset);
});
const isFrameCompatible = isPresetFrameCompatible(renderState.frameResolution, preset);
presetButton.disabled = !!renderState.selectionIssue || !isFrameCompatible;
decorateQuickMoveButtonWithShortcut(input, presetButton, shortcutTargets, {
kind: "preset",
preset
});
presetRow.appendChild(presetButton);
}
};
var appendPresetDropdown = (input, presetRow, presets, renderState) => {
const presetByKey = new Map(presets.map((preset) => [preset.key, preset]));
const lastPresetKey = input.lastQuickMoveDestination?.kind === "preset" ? input.lastQuickMoveDestination.preset.key : null;
const select = input.ownerDocument.createElement("select");
styleQuickMoveSelect(select, 180);
const placeholder = input.ownerDocument.createElement("option");
placeholder.value = "";
placeholder.textContent = input.reviewScope.active ? More review destinations (${presets.length}) : More groups (${presets.length});
select.appendChild(placeholder);
let compatibleCount = 0;
for (const preset of presets) {
const option = input.ownerDocument.createElement("option");
option.value = preset.key;
option.textContent = preset.key === lastPresetKey ? ${describePresetDestinationOptionLabel(preset, input.destinationProjection.frameLabelById)} ★ : describePresetDestinationOptionLabel(preset, input.destinationProjection.frameLabelById);
const isFrameCompatible = isPresetFrameCompatible(renderState.frameResolution, preset);
if (renderState.hasSelection && renderState.frameResolution.ok && !isFrameCompatible) {
option.disabled = true;
}
if (isFrameCompatible) {
compatibleCount += 1;
}
select.appendChild(option);
}
if (lastPresetKey && presetByKey.has(lastPresetKey)) {
select.value = lastPresetKey;
}
if (renderState.selectionIssue || compatibleCount === 0) {
select.disabled = true;
}
const applyButton = createQuickMoveButton(
input,
"Move",
async () => {
const selectedKey = select.value;
const preset = presetByKey.get(selectedKey);
if (!preset) {
input.onNotify("Choose a top-level group preset first.");
return;
}
await input.onApplyGroupPreset(preset);
},
"primary"
);
const updateApplyState = () => {
const selectedKey = select.value;
const preset = presetByKey.get(selectedKey);
const canApply = !!preset && !renderState.selectionIssue && isPresetFrameCompatible(renderState.frameResolution, preset);
applyButton.disabled = !canApply;
if (renderState.selectionIssue) {
return;
}
if (!preset) {
return;
}
if (!isPresetFrameCompatible(renderState.frameResolution, preset)) {
return;
}
};
select.addEventListener("change", updateApplyState);
updateApplyState();
presetRow.appendChild(select);
presetRow.appendChild(applyButton);
};
// src/ui/sidepanel/render/rowInteractionBinder.ts var bindSidepanelRowInteractions = (input) => { input.row.addEventListener("click", (event) => { event.stopPropagation(); input.onRowClick(event); }); input.row.addEventListener("dblclick", (event) => { event.preventDefault(); event.stopPropagation(); input.onRowDoubleClick(); }); if (input.draggable) { input.row.draggable = true; input.row.addEventListener("dragstart", (event) => { input.onDragStart(event); }); input.row.addEventListener("dragend", () => { input.onDragEnd(); }); } input.row.addEventListener("dragenter", (event) => { input.onDragEnter(event); }); input.row.addEventListener("dragover", (event) => { input.onDragOver(event); }); input.row.addEventListener("dragleave", (event) => { const relatedTarget = event.relatedTarget; input.onDragLeave(relatedTarget); }); input.row.addEventListener("drop", (event) => { event.preventDefault(); event.stopPropagation(); input.onDrop(event); }); };
// src/ui/sidepanel/render/rowPresentation.ts
var DEFAULT_VISUAL_STATE = {
visibility: "visible",
lock: "unlocked"
};
var normalizeSearchFragment = (value) => {
if (typeof value !== "string") {
return "";
}
return value.replace(/[[]·]/g, " ").trim().toLowerCase();
};
var resolveSidepanelTypeBadgeLabel = (node) => {
if (node.type === "freedrawBucket") {
return "[strokes]";
}
return [${node.type}];
};
var resolveStructureBadgeDescriptor = (node) => {
if (node.type !== "group" && node.type !== "frame") {
return null;
}
if (node.canExpand && !node.isExpanded) {
return {
text: "collapsed",
emphasis: "structure"
};
}
if (node.children.length > 0) {
return {
text: node.children.length === 1 ? "1 child row" : ${node.children.length} child rows,
emphasis: "structure"
};
}
return null;
};
var resolveCountBadgeDescriptor = (node) => {
if (node.type === "freedrawBucket") {
return {
text: ${node.elementIds.length} strokes,
emphasis: "default"
};
}
if (node.type === "group" || node.type === "frame") {
return {
text: ${node.elementIds.length} items,
emphasis: "default"
};
}
if (node.elementIds.length > 1) {
return {
text: ${node.elementIds.length} linked,
emphasis: "default"
};
}
return null;
};
var resolveFilterMatchBadgeDescriptor = (filterMatchKind) => {
if (filterMatchKind === "self") {
return {
text: "match",
emphasis: "match"
};
}
if (filterMatchKind === "descendant") {
return {
text: "nested match",
emphasis: "match"
};
}
return null;
};
var resolveVisibilityBadgeDescriptor = (state) => {
if (state.visibility === "hidden") {
return {
text: "hidden",
emphasis: "visibility"
};
}
if (state.visibility === "mixed") {
return {
text: "some hidden",
emphasis: "visibility"
};
}
return null;
};
var resolveLockBadgeDescriptor = (state) => {
if (state.lock === "locked") {
return {
text: "locked",
emphasis: "lock"
};
}
if (state.lock === "mixed") {
return {
text: "some locked",
emphasis: "lock"
};
}
return null;
};
var resolveExpandButtonLabel = (node) => {
if (!node.canExpand) {
return null;
}
return ${node.isExpanded ? "Collapse" : "Expand"} row ${node.label};
};
var collectMetaBadges = (node, state, filterMatchKind) => {
return [
resolveStructureBadgeDescriptor(node),
resolveCountBadgeDescriptor(node),
resolveFilterMatchBadgeDescriptor(filterMatchKind),
resolveVisibilityBadgeDescriptor(state),
resolveLockBadgeDescriptor(state)
].filter((badge) => badge !== null);
};
var buildSidepanelRowSearchText = (node) => {
return buildSidepanelRowDescriptors({ node }).searchText;
};
var buildSidepanelRowDescriptors = (input) => {
const state = input.nodeVisualState ?? DEFAULT_VISUAL_STATE;
const filterMatchKind = input.filterMatchKind ?? "none";
const typeBadge = {
text: resolveSidepanelTypeBadgeLabel(input.node),
emphasis: "type"
};
const metaBadges = collectMetaBadges(input.node, state, filterMatchKind);
const ariaParts = [
${typeBadge.text} ${input.node.label},
...metaBadges.map((badge) => badge.text)
];
const searchFragments = [
input.node.label,
input.node.searchText,
input.node.type,
typeBadge.text,
...metaBadges.map((badge) => badge.text)
].map(normalizeSearchFragment);
return {
typeBadge,
metaBadges,
ariaLabel: ariaParts.join(" · "),
searchText: searchFragments.filter((fragment) => fragment.length > 0).join(" "),
expandButtonLabel: resolveExpandButtonLabel(input.node)
};
};
// src/ui/sidepanel/render/rowModel.ts var normalizeQuery = (value) => value.trim().toLowerCase(); var countRenderedRows = (nodes) => { let total = 0; const walk = (nextNodes) => { for (const node of nextNodes) { total += 1; if (node.children.length > 0) { walk(node.children); } } }; walk(nodes); return total; }; var countSearchableRows = (nodes) => { let total = 0; const walk = (nextNodes) => { for (const node of nextNodes) { total += 1; if (node.children.length > 0) { walk(node.children); } } }; walk(nodes); return total; }; var projectExpandedVisibleRows = (nodes) => { return nodes.map((node) => ({ ...node, children: node.isExpanded ? projectExpandedVisibleRows(node.children) : [], canExpand: node.canExpand || node.children.length > 0 })); }; var countFilterMatchKinds = (matchKindByNodeId) => { let matchingRowCount = 0; let contextRowCount = 0; for (const matchKind of matchKindByNodeId.values()) { if (matchKind === "self") { matchingRowCount += 1; continue; } if (matchKind === "descendant") { contextRowCount += 1; } } return { matchingRowCount, contextRowCount }; }; var filterNodesForQuery = (nodes, query, matchKindByNodeId) => { const filtered = []; for (const node of nodes) { const filteredChildren = filterNodesForQuery(node.children, query, matchKindByNodeId); const selfMatches = buildSidepanelRowSearchText(node).includes(query); if (!selfMatches && filteredChildren.length === 0) { continue; } matchKindByNodeId.set(node.id, selfMatches ? "self" : "descendant"); filtered.push({ ...node, children: filteredChildren, // Filter mode projects the currently relevant descendants directly and suppresses // expand/collapse affordances so visible-row controls stay honest about what the // filter can actually reveal. canExpand: false, isExpanded: filteredChildren.length > 0 }); } return filtered; }; var buildSidepanelVisibleRowTreeResult = (structuralTree, query) => { const normalizedQuery = normalizeQuery(query); const searchableRowCount = countSearchableRows(structuralTree); if (normalizedQuery.length === 0) { const visibleTree2 = projectExpandedVisibleRows(structuralTree); return { visibleTree: visibleTree2, active: false, query: "", renderedRowCount: countRenderedRows(visibleTree2), searchableRowCount, matchingRowCount: 0, contextRowCount: 0, matchKindByNodeId: /* @PURE / new Map() }; } const matchKindByNodeId = / @PURE */ new Map(); const visibleTree = filterNodesForQuery(structuralTree, normalizedQuery, matchKindByNodeId); const { matchingRowCount, contextRowCount } = countFilterMatchKinds(matchKindByNodeId); return { visibleTree, active: true, query: normalizedQuery, renderedRowCount: countRenderedRows(visibleTree), searchableRowCount, matchingRowCount, contextRowCount, matchKindByNodeId }; }; var resolveSidepanelRowVisualState = (node, elementStateById) => { if (!elementStateById || node.elementIds.length === 0) { return { visibility: "visible", lock: "unlocked" }; } let knownElements = 0; let hiddenCount = 0; let lockedCount = 0; for (const elementId of node.elementIds) { const state = elementStateById.get(elementId); if (!state) { continue; } knownElements += 1; if (state.opacity <= 0) { hiddenCount += 1; } if (state.locked) { lockedCount += 1; } } if (knownElements === 0) { return { visibility: "visible", lock: "unlocked" }; } const visibility = hiddenCount === 0 ? "visible" : hiddenCount === knownElements ? "hidden" : "mixed"; const lock = lockedCount === 0 ? "unlocked" : lockedCount === knownElements ? "locked" : "mixed"; return { visibility, lock }; };
// src/ui/sidepanel/render/rowRenderer.ts
var createMetaBadge = (ownerDocument, text, emphasis = "default") => {
const badge = ownerDocument.createElement("span");
badge.textContent = text;
badge.style.display = "inline-flex";
badge.style.alignItems = "center";
badge.style.flexShrink = "0";
badge.style.padding = "0 4px";
badge.style.borderRadius = "999px";
badge.style.fontSize = "9px";
badge.style.lineHeight = "14px";
badge.style.letterSpacing = "0.01em";
if (emphasis === "match") {
badge.style.background = "var(--interactive-accent-hover, rgba(120,120,120,0.2))";
badge.style.color = "var(--text-normal, inherit)";
return badge;
}
if (emphasis === "type") {
badge.style.border = "1px solid var(--background-modifier-border, rgba(120,120,120,0.12))";
badge.style.background = "transparent";
badge.style.color = "var(--text-muted, inherit)";
return badge;
}
if (emphasis === "structure") {
badge.style.border = "1px solid var(--background-modifier-border, rgba(120,120,120,0.12))";
badge.style.background = "var(--background-secondary-alt, rgba(120,120,120,0.08))";
badge.style.color = "var(--text-muted, inherit)";
return badge;
}
if (emphasis === "visibility") {
badge.style.background = "var(--background-modifier-hover, rgba(120,120,120,0.12))";
badge.style.color = "var(--text-muted, inherit)";
return badge;
}
if (emphasis === "lock") {
badge.style.background = "var(--background-secondary-alt, rgba(120,120,120,0.12))";
badge.style.color = "var(--text-muted, inherit)";
return badge;
}
badge.style.background = "var(--background-modifier-border, rgba(120,120,120,0.12))";
badge.style.color = "var(--text-muted, inherit)";
return badge;
};
var resolveRowShellBoxShadow = (state, dropHintKind) => {
const shadows = [];
if (state.visibility === "hidden") {
shadows.push("inset 3px 0 0 0 var(--text-faint, rgba(120,120,120,0.55))");
} else if (state.visibility === "mixed") {
shadows.push("inset 3px 0 0 0 var(--background-modifier-border-hover, rgba(120,120,120,0.45))");
}
if (state.lock === "locked") {
shadows.push("inset -3px 0 0 0 var(--text-muted, rgba(120,120,120,0.6))");
} else if (state.lock === "mixed") {
shadows.push("inset -3px 0 0 0 var(--background-secondary-alt, rgba(120,120,120,0.45))");
}
if (dropHintKind === "reparent") {
shadows.push("inset 0 0 0 2px var(--interactive-accent, rgba(120,120,120,0.68))");
}
if (dropHintKind === "reorderBefore") {
shadows.push("inset 0 3px 0 0 var(--interactive-accent, rgba(120,120,120,0.92))");
}
if (dropHintKind === "reorderAfter") {
shadows.push("inset 0 -3px 0 0 var(--interactive-accent, rgba(120,120,120,0.92))");
}
return shadows.join(", ");
};
var resolveVisibilityActionIcon = (state) => {
if (state.visibility === "hidden") {
return {
iconName: "eye-off",
fallbackLabel: "🙈",
title: "Show all items"
};
}
if (state.visibility === "mixed") {
return {
iconName: "eye",
fallbackLabel: "◐",
title: "Show hidden items"
};
}
return {
iconName: "eye",
fallbackLabel: "👁",
title: "Hide all items"
};
};
var resolveLockActionIcon = (state) => {
if (state.lock === "locked") {
return {
iconName: "lock",
fallbackLabel: "🔒",
title: "Unlock all items"
};
}
if (state.lock === "mixed") {
return {
iconName: "lock",
fallbackLabel: "◪",
title: "Lock unlocked items"
};
}
return {
iconName: "unlock",
fallbackLabel: "🔓",
title: "Lock all items"
};
};
var styleRowActionButton = (button) => {
button.style.flexShrink = "0";
button.style.border = "1px solid var(--background-modifier-border, rgba(120,120,120,0.16))";
button.style.background = "var(--background-primary-alt, rgba(120,120,120,0.04))";
button.style.opacity = "0.85";
};
var resolveFocusedRowOutline = () => {
return "2px solid var(--text-normal, rgba(255,255,255,0.92))";
};
var renderSidepanelRow = (input) => {
const rowDescriptors = buildSidepanelRowDescriptors({
node: input.node,
nodeVisualState: input.nodeVisualState,
filterMatchKind: input.filterMatchKind
});
const row = input.ownerDocument.createElement("div");
row.id = input.rowDomId;
row.role = "treeitem";
row.style.display = "flex";
row.style.position = "relative";
row.style.alignItems = "center";
row.style.gap = "3px";
row.style.minHeight = ${input.styleConfig.rowMinHeightPx}px;
row.style.paddingTop = "1px";
row.style.paddingBottom = "1px";
row.style.paddingLeft = ${input.depth * input.styleConfig.indentStepPx}px;
row.style.paddingRight = "2px";
row.style.borderRadius = "4px";
row.style.fontSize = ${input.styleConfig.rowFontSizePx}px;
row.style.border = "1px solid transparent";
row.ariaLabel = rowDescriptors.ariaLabel;
row.ariaSelected = input.selected ? "true" : "false";
row.ariaLevel = ${input.depth + 1};
if (input.node.canExpand || input.node.children.length > 0) {
row.ariaExpanded = input.node.isExpanded ? "true" : "false";
}
row.tabIndex = -1;
const rowBoxShadow = resolveRowShellBoxShadow(input.nodeVisualState, input.dropHintKind);
if (rowBoxShadow.length > 0) {
row.style.boxShadow = rowBoxShadow;
}
if (input.filterMatchKind === "self") {
row.style.background = "var(--background-modifier-hover, rgba(120,120,120,0.12))";
row.style.borderColor = "var(--background-modifier-border, rgba(120,120,120,0.16))";
}
if (input.selected) {
row.style.background = "var(--interactive-accent-hover, rgba(120,120,120,0.2))";
row.style.borderColor = "var(--interactive-accent, rgba(120,120,120,0.32))";
}
if (input.dropHintKind === "reparent" && !input.selected) {
row.style.background = "var(--interactive-accent-hover, rgba(120,120,120,0.16))";
row.style.borderColor = "var(--interactive-accent, rgba(120,120,120,0.68))";
}
if (input.focused) {
row.style.outline = resolveFocusedRowOutline();
row.style.outlineOffset = "-2px";
}
if (input.actions) {
row.style.cursor = "pointer";
}
appendExpandControl(input, row, rowDescriptors.expandButtonLabel);
const renameInputForAutofocus = appendLabelOrRenameInput(
input,
row,
rowDescriptors.typeBadge.text
);
appendMetaBadges(input, row, rowDescriptors.metaBadges);
appendRowActionButtons(input, row);
appendDropHintAssistiveLabel(input, row);
return {
row,
renameInputForAutofocus
};
};
var appendExpandControl = (input, row, expandButtonLabel) => {
const { node, actions, ownerDocument } = input;
if (node.canExpand && actions) {
const expandButton = ownerDocument.createElement("button");
expandButton.type = "button";
expandButton.textContent = node.isExpanded ? "▾" : "▸";
expandButton.style.minWidth = ${input.styleConfig.iconButtonSizePx}px;
expandButton.style.minHeight = ${input.styleConfig.iconButtonSizePx}px;
expandButton.style.fontSize = ${input.styleConfig.iconSizePx}px;
expandButton.style.padding = "0";
expandButton.style.border = "none";
expandButton.style.background = "transparent";
expandButton.style.boxShadow = "none";
if (expandButtonLabel) {
expandButton.ariaLabel = expandButtonLabel;
}
expandButton.addEventListener("click", (event) => {
event.stopPropagation();
input.onToggleExpanded(node.id);
});
row.appendChild(expandButton);
return;
}
const spacer = ownerDocument.createElement("span");
spacer.style.display = "inline-block";
spacer.style.minWidth = ${input.styleConfig.iconButtonSizePx}px;
row.appendChild(spacer);
};
var appendLabelOrRenameInput = (input, row, typeBadgeLabel) => {
const inlineRenameState = input.inlineRenameState?.nodeId === input.node.id ? input.inlineRenameState : null;
row.appendChild(createMetaBadge(input.ownerDocument, typeBadgeLabel, "type"));
if (inlineRenameState && input.actions) {
const renameInput = input.ownerDocument.createElement("input");
renameInput.type = "text";
renameInput.value = inlineRenameState.draft;
renameInput.style.flex = "1";
renameInput.style.fontSize = ${input.styleConfig.rowFontSizePx}px;
renameInput.style.padding = "1px 3px";
renameInput.style.minWidth = "0";
renameInput.addEventListener("click", (event) => {
event.stopPropagation();
});
renameInput.addEventListener("input", () => {
input.onInlineRenameDraftChange(renameInput.value);
});
renameInput.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
input.onInlineRenameCommit(input.node.id);
return;
}
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
input.onInlineRenameCancel();
return;
}
event.stopPropagation();
});
renameInput.addEventListener("blur", () => {
if (!input.isInlineRenameActiveForNode(input.node.id)) {
return;
}
input.onInlineRenameCommit(input.node.id);
});
row.appendChild(renameInput);
return renameInput;
}
const label = input.ownerDocument.createElement("span");
label.textContent = input.node.label;
label.style.flex = "1";
label.style.minWidth = "0";
label.style.fontSize = ${input.styleConfig.rowFontSizePx}px;
label.style.color = "var(--text-normal, inherit)";
label.style.fontWeight = input.filterMatchKind === "self" ? "600" : "500";
label.style.paddingRight = "2px";
label.style.overflow = "hidden";
label.style.textOverflow = "ellipsis";
label.style.whiteSpace = "nowrap";
label.style.opacity = input.nodeVisualState.visibility === "hidden" ? "0.6" : input.nodeVisualState.visibility === "mixed" ? "0.85" : "1";
label.style.textDecoration = input.nodeVisualState.visibility === "hidden" ? "line-through" : "none";
row.appendChild(label);
return null;
};
var appendMetaBadges = (input, row, metaBadges) => {
if (metaBadges.length === 0) {
return;
}
const metaHost = input.ownerDocument.createElement("div");
metaHost.style.display = "inline-flex";
metaHost.style.alignItems = "center";
metaHost.style.justifyContent = "flex-end";
metaHost.style.flexWrap = "wrap";
metaHost.style.gap = "3px";
metaHost.style.rowGap = "2px";
for (const badge of metaBadges) {
metaHost.appendChild(createMetaBadge(input.ownerDocument, badge.text, badge.emphasis));
}
row.appendChild(metaHost);
};
var appendDropHintAssistiveLabel = (input, row) => {
if (!input.dropHintKind) {
return;
}
const assistiveLabel = input.ownerDocument.createElement("span");
assistiveLabel.textContent = input.dropHintLabel ?? "drop target";
assistiveLabel.style.position = "absolute";
assistiveLabel.style.width = "1px";
assistiveLabel.style.height = "1px";
assistiveLabel.style.padding = "0";
assistiveLabel.style.margin = "-1px";
assistiveLabel.style.overflow = "hidden";
assistiveLabel.style.clip = "rect(0 0 0 0)";
assistiveLabel.style.clipPath = "inset(50%)";
assistiveLabel.style.whiteSpace = "nowrap";
assistiveLabel.style.border = "0";
row.appendChild(assistiveLabel);
};
var appendRowActionButtons = (input, row) => {
const actions = input.actions;
if (!actions) {
return;
}
const visibilityButton = input.createIconActionButton(
input.ownerDocument,
resolveVisibilityActionIcon(input.nodeVisualState),
() => actions.toggleVisibilityNode(input.node.id)
);
styleRowActionButton(visibilityButton);
row.appendChild(visibilityButton);
const lockButton = input.createIconActionButton(
input.ownerDocument,
resolveLockActionIcon(input.nodeVisualState),
() => actions.toggleLockNode(input.node.id)
);
styleRowActionButton(lockButton);
row.appendChild(lockButton);
const renameButton = input.createIconActionButton(
input.ownerDocument,
{
iconName: "edit-3",
fallbackLabel: "✎",
title: "Rename layer"
},
async () => {
input.onRenameNodeFromAction(input.node.id, input.node.label);
}
);
styleRowActionButton(renameButton);
row.appendChild(renameButton);
const deleteButton = input.createIconActionButton(
input.ownerDocument,
{
iconName: "trash-2",
fallbackLabel: "🗑",
title: "Delete layer"
},
() => actions.deleteNode(input.node.id)
);
styleRowActionButton(deleteButton);
row.appendChild(deleteButton);
};
// src/ui/sidepanel/render/rowTreeRenderer.ts var hasVisibleChildren = (node) => { return node.isExpanded && node.children.length > 0; }; var renderSidepanelRowTree = (input) => { for (const [siblingIndex, node] of input.nodes.entries()) { const nodeFrameId = input.resolveNodeFrameId(node, input.branchContext); const childBranchContext = { frameId: nodeFrameId, groupPath: node.type === "group" && node.groupId ? [...input.branchContext.groupPath, node.groupId] : input.branchContext.groupPath }; input.visitNode({ node, depth: input.depth, branchContext: input.branchContext, siblingIndex, nodeFrameId, childBranchContext }); if (!hasVisibleChildren(node)) { continue; } renderSidepanelRowTree({ ...input, nodes: node.children, depth: input.depth + 1, branchContext: childBranchContext }); } };
// src/ui/sidepanel/render/toolbarRenderer.ts var styleToolbarButton = (button, tone = "neutral") => { button.style.fontSize = "11px"; button.style.lineHeight = "1.2"; button.style.minHeight = "20px"; button.style.padding = "2px 7px"; button.style.borderRadius = "5px"; button.style.border = "1px solid var(--background-modifier-border, rgba(120,120,120,0.18))"; button.style.boxShadow = "none"; button.style.background = tone === "primary" ? "var(--background-secondary-alt, rgba(120,120,120,0.1))" : "var(--background-primary-alt, rgba(120,120,120,0.04))"; }; var createStyledToolbarButton = (input, label, action, tone = "neutral") => { const button = input.createToolbarButton(input.ownerDocument, label, action); styleToolbarButton(button, tone); return button; }; var createStyledToolbarIconButton = (input, icon, action, tone = "neutral") => { const button = input.createToolbarIconButton(input.ownerDocument, icon, action); styleToolbarButton(button, tone); button.style.display = "inline-flex"; button.style.alignItems = "center"; button.style.justifyContent = "center"; button.style.minWidth = "24px"; button.style.padding = "2px 6px"; return button; }; var renderSidepanelToolbar = (input) => { const toolbar = input.ownerDocument.createElement("div"); toolbar.style.display = "flex"; toolbar.style.flexWrap = "wrap"; toolbar.style.gap = "4px"; toolbar.style.marginBottom = "6px"; toolbar.style.padding = "4px 6px"; toolbar.style.borderRadius = "6px"; toolbar.style.border = "1px solid var(--background-modifier-border, rgba(120,120,120,0.16))"; toolbar.style.background = "var(--background-primary-alt, rgba(120,120,120,0.04))"; input.container.appendChild(toolbar); if (!input.hasActions) { return toolbar; } const groupButton = createStyledToolbarButton( input, "Group selected", async () => { await input.onGroupSelected(); }, "primary" ); groupButton.disabled = input.selectedElementCount < 2; toolbar.appendChild(groupButton); appendReorderControls(input, toolbar); const moveOutOfGroupButton = createStyledToolbarButton(input, "Move out of group", async () => { await input.onUngroupLikeSelection(); }); moveOutOfGroupButton.disabled = input.selectedElementCount === 0 || !!input.ungroupLikeIssue; toolbar.appendChild(moveOutOfGroupButton); return toolbar; }; var appendReorderControls = (input, toolbar) => { const controls = [ { label: "Send to back", mode: "back", iconName: "zindex-send-to-back", fallbackLabel: "⇊" }, { label: "Send backward", mode: "backward", iconName: "zindex-send-backward", fallbackLabel: "↓" }, { label: "Bring forward", mode: "forward", iconName: "zindex-bring-forward", fallbackLabel: "↑" }, { label: "Bring to front", mode: "front", iconName: "zindex-bring-to-front", fallbackLabel: "⇈" } ]; for (const control of controls) { const button = createStyledToolbarIconButton( input, { iconName: control.iconName, fallbackLabel: control.fallbackLabel, title: control.label }, async () => { await input.onReorderSelected(control.mode); } ); button.disabled = input.selectedElementCount === 0; toolbar.appendChild(button); } };
// src/ui/sidepanel/selection/hostContextFlightRecorder.ts
var SIDEPANEL_LIFECYCLE_DEBUG_FLAG = "LMX_DEBUG_SIDEPANEL_LIFECYCLE";
var HOST_CONTEXT_FLIGHT_RECORDER_MAX_EVENTS = 240;
var getRuntime2 = () => {
return globalThis;
};
var getRecorderState = () => {
const runtime = getRuntime2();
if (!runtime.LMX_HOST_CONTEXT_FLIGHT_RECORDER) {
runtime.LMX_HOST_CONTEXT_FLIGHT_RECORDER = {
nextSequence: 1,
events: []
};
}
return runtime.LMX_HOST_CONTEXT_FLIGHT_RECORDER;
};
var sanitizeForRecorder = (value, depth = 0, seen = /* @PURE / new WeakSet()) => {
if (value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return value ?? null;
}
if (typeof value === "bigint") {
return ${value}n;
}
if (typeof value === "symbol") {
return String(value);
}
if (typeof value === "function") {
return "[function]";
}
if (depth >= 5) {
return "[depth-limit]";
}
if (Array.isArray(value)) {
return value.map((entry) => sanitizeForRecorder(entry, depth + 1, seen));
}
if (value instanceof Set) {
return [...value].map((entry) => sanitizeForRecorder(entry, depth + 1, seen));
}
if (value instanceof Map) {
return [...value.entries()].map(([key, entry]) => [
sanitizeForRecorder(key, depth + 1, seen),
sanitizeForRecorder(entry, depth + 1, seen)
]);
}
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
stack: value.stack ?? null
};
}
if (typeof value !== "object") {
return ${value};
}
if (seen.has(value)) {
return "[circular]";
}
seen.add(value);
const record = value;
const output = {};
for (const [key, entry] of Object.entries(record)) {
output[key] = sanitizeForRecorder(entry, depth + 1, seen);
}
seen.delete(value);
return output;
};
var sanitizePayload = (payload) => {
if (!payload) {
return null;
}
return sanitizeForRecorder(payload);
};
var cloneRecordedPayload = (payload) => {
if (!payload) {
return null;
}
return sanitizeForRecorder(payload);
};
var stringifyEventPayload = (payload) => {
if (!payload) {
return "{}";
}
try {
return JSON.stringify(payload, null, 2);
} catch {
return JSON.stringify({ error: "payload-unserializable" }, null, 2);
}
};
var isLifecycleDebugEnabled = () => {
return getRuntime2()[SIDEPANEL_LIFECYCLE_DEBUG_FLAG] === true;
};
var logLifecycleDebug = (message, payload) => {
if (!isLifecycleDebugEnabled()) {
return;
}
if (payload) {
console.log([LMX:lifecycle] ${message}, payload);
return;
}
console.log([LMX:lifecycle] ${message});
};
var recordHostContextFlightRecorderEvent = (category, message, payload) => {
const state = getRecorderState();
const event = {
sequence: state.nextSequence,
atMs: Date.now(),
atIso: (/ @PURE */ new Date()).toISOString(),
category,
message,
payload: sanitizePayload(payload)
};
state.nextSequence += 1;
state.events.push(event);
if (state.events.length > HOST_CONTEXT_FLIGHT_RECORDER_MAX_EVENTS) {
state.events.splice(0, state.events.length - HOST_CONTEXT_FLIGHT_RECORDER_MAX_EVENTS);
}
return event;
};
var traceHostContextLifecycleEvent = (category, message, payload) => {
const event = recordHostContextFlightRecorderEvent(category, message, payload);
logLifecycleDebug(message, event.payload ?? void 0);
return event;
};
var readHostContextFlightRecorderEvents = () => {
const state = getRecorderState();
return state.events.map((event) => ({
...event,
payload: cloneRecordedPayload(event.payload)
}));
};
var clearHostContextFlightRecorder = () => {
const state = getRecorderState();
state.events.splice(0, state.events.length);
state.nextSequence = 1;
};
var formatHostContextFlightRecorderDump = () => {
const events = readHostContextFlightRecorderEvents();
const lines = ["# LMX Host Context Flight Recorder", events=${events.length}, ""];
for (const event of events) {
lines.push(
[${${event.sequence}.padStart(3, "0")}] ${event.atIso} category=${event.category} message=${event.message}
);
lines.push(stringifyEventPayload(event.payload));
lines.push("");
}
return lines.join("\n");
};
var resolveClipboard = () => {
const navigatorCandidate = globalThis.navigator;
const clipboardCandidate = navigatorCandidate?.clipboard;
return clipboardCandidate && typeof clipboardCandidate === "object" ? clipboardCandidate : null;
};
var copyHostContextFlightRecorderDump = async (options) => {
const dump = formatHostContextFlightRecorderDump();
const clipboard = resolveClipboard();
if (typeof clipboard?.writeText === "function") {
await clipboard.writeText(dump);
options?.Notice && new options.Notice("[LMX] Host-context trace copied.", 2200);
return dump;
}
options?.Notice && new options.Notice("[LMX] Clipboard unavailable; trace returned in console result.", 2600);
return dump;
};
var installHostContextFlightRecorderGlobals = (options) => {
const runtime = getRuntime2();
runtime.LMX_HOST_CONTEXT_TRACE_READ = () => readHostContextFlightRecorderEvents();
runtime.LMX_HOST_CONTEXT_TRACE_CLEAR = () => {
clearHostContextFlightRecorder();
};
runtime.LMX_HOST_CONTEXT_TRACE_DUMP = () => {
const dump = formatHostContextFlightRecorderDump();
console.log(dump);
return dump;
};
runtime.LMX_HOST_CONTEXT_TRACE_COPY = async () => {
return copyHostContextFlightRecorderDump(options);
};
};
// src/ui/sidepanel/selection/hostViewContext.ts
var EXCALIDRAW_FRONTMATTER_KEY = "excalidraw-plugin";
var EXCALIDRAW_FRONTMATTER_VALUE = "parsed";
var VIEW_BIND_STRATEGIES = [
{ viewArg: "active", reveal: false },
{ viewArg: void 0, reveal: false },
{ viewArg: "active", reveal: true },
{ viewArg: void 0, reveal: true }
];
var invokeHostSetView = (host, viewArg, reveal) => {
const setView = host.setView;
if (!setView) {
return null;
}
return setView.call(host, viewArg, reveal);
};
var hasExplicitTargetViewProperty2 = (host) => {
return Object.hasOwn(host, "targetView");
};
var getCurrentHostTargetView = (host) => {
return host.targetView ?? null;
};
var isUsableTargetView2 = (value) => {
if (!value || typeof value !== "object") {
return false;
}
const record = value;
if ("_loaded" in record) {
return record["_loaded"] === true;
}
return true;
};
var resolveTargetViewFile = (targetView) => {
if (!targetView || typeof targetView !== "object") {
return null;
}
const fileCandidate = targetView["file"];
return fileCandidate && typeof fileCandidate === "object" ? fileCandidate : null;
};
var resolveTargetViewFilePath = (targetView) => {
const file = resolveTargetViewFile(targetView);
return typeof file?.["path"] === "string" ? file["path"] : null;
};
var normalizeIdentityToken = (value) => {
if (typeof value === "string") {
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
return typeof value === "number" && Number.isFinite(value) ? ${value} : null;
};
var resolveTargetViewIdentity = (targetView) => {
if (!targetView || typeof targetView !== "object") {
return null;
}
const record = targetView;
const leafRecord = record["leaf"] && typeof record["leaf"] === "object" ? record["leaf"] : null;
const identityCandidates = [
record["id"],
record["viewId"],
record["leafId"],
record["workspaceLeafId"],
leafRecord?.["id"]
];
for (const candidate of identityCandidates) {
const identityToken = normalizeIdentityToken(candidate);
if (identityToken) {
return identityToken;
}
}
return null;
};
var toAppCandidate = (candidate) => {
return candidate && typeof candidate === "object" ? candidate : null;
};
var hasMetadataCacheSurface = (candidate) => {
return !!candidate?.metadataCache && typeof candidate.metadataCache === "object";
};
var hasWorkspaceSurface = (candidate) => {
return !!candidate?.workspace && typeof candidate.workspace === "object";
};
var resolveTargetViewApp = (targetView) => {
const targetViewRecord = targetView && typeof targetView === "object" ? targetView : null;
return toAppCandidate(targetViewRecord?.["app"]);
};
var resolveCanonicalHostAppCandidates = (host) => {
return [
host.app,
host.obsidian?.app,
globalThis["app"],
globalThis.window?.app,
globalThis.obsidian?.app
].flatMap((candidate) => {
const resolvedCandidate = toAppCandidate(candidate);
return resolvedCandidate ? [resolvedCandidate] : [];
});
};
var resolveTargetViewMetadataApp = (host, targetView) => {
const targetViewApp = resolveTargetViewApp(targetView);
const canonicalHostApps = resolveCanonicalHostAppCandidates(host);
if (hasMetadataCacheSurface(targetViewApp)) {
return targetViewApp;
}
for (const candidate of canonicalHostApps) {
if (hasMetadataCacheSurface(candidate)) {
return candidate;
}
}
return targetViewApp ?? canonicalHostApps[0] ?? null;
};
var resolveActiveWorkspaceApp = (host, targetView = getCurrentHostTargetView(host)) => {
const canonicalHostApps = resolveCanonicalHostAppCandidates(host);
const targetViewApp = resolveTargetViewApp(targetView);
for (const candidate of canonicalHostApps) {
if (hasWorkspaceSurface(candidate)) {
return candidate;
}
}
if (hasWorkspaceSurface(targetViewApp)) {
return targetViewApp;
}
return canonicalHostApps[0] ?? targetViewApp ?? null;
};
var resolveFileExcalidrawMetadata = (app, file) => {
if (!file) {
return {
available: false,
value: null
};
}
const getFileCache = app?.metadataCache?.getFileCache;
if (!getFileCache) {
return {
available: false,
value: null
};
}
try {
const fileCache = getFileCache(file);
const frontmatter = fileCache?.frontmatter;
const excalidrawPluginValue = frontmatter?.[EXCALIDRAW_FRONTMATTER_KEY];
return {
available: true,
value: typeof excalidrawPluginValue === "string" ? excalidrawPluginValue : null
};
} catch {
return {
available: false,
value: null
};
}
};
var resolveTargetViewExcalidrawMetadata = (host, targetView) => {
return resolveFileExcalidrawMetadata(
resolveTargetViewMetadataApp(host, targetView),
resolveTargetViewFile(targetView)
);
};
var resolveWorkspace = (app) => {
return app?.workspace ?? null;
};
var normalizeFilePath = (file) => {
if (typeof file === "string") {
const trimmed = file.trim();
return trimmed.length > 0 ? trimmed : null;
}
if (!file || typeof file !== "object") {
return null;
}
return typeof file["path"] === "string" ? file["path"] : null;
};
var normalizeFileLike = (file) => {
if (file && typeof file === "object") {
return file;
}
const path = normalizeFilePath(file);
return path ? { path } : null;
};
var resolveActiveWorkspaceLeaf = (workspace) => {
const workspaceRecord = workspace;
if (!workspaceRecord) {
return null;
}
const leafCandidates = [workspaceRecord.activeLeaf];
if (typeof workspaceRecord.getMostRecentLeaf === "function") {
try {
leafCandidates.push(workspaceRecord.getMostRecentLeaf());
} catch {
}
}
for (const candidate of leafCandidates) {
if (candidate && typeof candidate === "object") {
return candidate;
}
}
return null;
};
var resolveActiveWorkspaceLeafFile = (activeLeaf) => {
if (!activeLeaf) {
return null;
}
const viewRecord = activeLeaf["view"] && typeof activeLeaf["view"] === "object" ? activeLeaf["view"] : null;
const directCandidates = [viewRecord?.["file"], activeLeaf["file"]];
for (const candidate of directCandidates) {
const normalizedCandidate = normalizeFileLike(candidate);
if (normalizedCandidate) {
return normalizedCandidate;
}
}
const methodCandidates = [
{ owner: activeLeaf, getFile: activeLeaf["getFile"] },
...viewRecord ? [{ owner: viewRecord, getFile: viewRecord["getFile"] }] : []
];
for (const candidate of methodCandidates) {
if (typeof candidate.getFile !== "function") {
continue;
}
try {
const resolvedFile = normalizeFileLike(candidate.getFile.call(candidate.owner));
if (resolvedFile) {
return resolvedFile;
}
} catch {
}
}
return null;
};
var resolveActiveWorkspaceFile = (workspace, activeLeaf) => {
const getActiveFile = workspace?.getActiveFile;
if (getActiveFile) {
try {
const activeFile = normalizeFileLike(getActiveFile());
if (activeFile) {
return activeFile;
}
} catch {
}
}
return resolveActiveWorkspaceLeafFile(activeLeaf);
};
var resolveActiveWorkspaceLeafIdentity = (activeLeaf) => {
if (!activeLeaf) {
return null;
}
const viewRecord = activeLeaf["view"] && typeof activeLeaf["view"] === "object" ? activeLeaf["view"] : null;
const identityCandidates = [
activeLeaf["id"],
activeLeaf["leafId"],
activeLeaf["workspaceLeafId"],
viewRecord?.["leafId"]
];
for (const candidate of identityCandidates) {
const identityToken = normalizeIdentityToken(candidate);
if (identityToken) {
return identityToken;
}
}
return null;
};
var resolveActiveWorkspaceViewType = (activeLeaf) => {
if (!activeLeaf) {
return null;
}
const viewRecord = activeLeaf["view"] && typeof activeLeaf["view"] === "object" ? activeLeaf["view"] : null;
const directViewType = normalizeIdentityToken(viewRecord?.["viewType"]);
if (directViewType) {
return directViewType;
}
const getViewType = viewRecord?.["getViewType"];
if (typeof getViewType === "function") {
try {
return normalizeIdentityToken(getViewType.call(viewRecord));
} catch {
}
}
return null;
};
var isExcalidrawCapableMetadataValue = (value) => {
return value?.trim().toLowerCase() === EXCALIDRAW_FRONTMATTER_VALUE;
};
var resolveHostViewContextDescription = (host, targetView = getCurrentHostTargetView(host)) => {
const targetViewLoaded = targetView && typeof targetView === "object" && "_loaded" in targetView ? targetView["_loaded"] === true : null;
const targetViewUsable = isUsableTargetView2(targetView);
const targetViewIdentity = resolveTargetViewIdentity(targetView);
const targetViewMetadata = resolveTargetViewExcalidrawMetadata(host, targetView);
const targetViewExcalidrawCapable = targetViewMetadata.available ? isExcalidrawCapableMetadataValue(targetViewMetadata.value) : null;
const activeWorkspaceApp = resolveActiveWorkspaceApp(host, targetView);
const activeWorkspace = resolveWorkspace(activeWorkspaceApp);
const activeWorkspaceLeaf = resolveActiveWorkspaceLeaf(activeWorkspace);
const activeFile = resolveActiveWorkspaceFile(activeWorkspace, activeWorkspaceLeaf);
const activeFilePath = normalizeFilePath(activeFile);
const activeWorkspaceLeafIdentity = resolveActiveWorkspaceLeafIdentity(activeWorkspaceLeaf);
const activeWorkspaceViewType = resolveActiveWorkspaceViewType(activeWorkspaceLeaf);
const activeFileMetadata = resolveFileExcalidrawMetadata(activeWorkspaceApp, activeFile);
const activeFileExcalidrawCapable = activeFileMetadata.available ? isExcalidrawCapableMetadataValue(activeFileMetadata.value) : null;
const legacyHostWithoutTargetViewProperty = !hasExplicitTargetViewProperty2(host);
const effectiveExcalidrawCapable = activeFileMetadata.available ? activeFileExcalidrawCapable : targetViewExcalidrawCapable;
const activeWorkspaceDefinitelyInactive = isDefinitelyInactiveActiveWorkspaceContext({
activeFilePath,
activeWorkspaceViewType,
activeFileMetadataAvailable: activeFileMetadata.available,
activeFileExcalidrawCapable,
targetViewFilePath: resolveTargetViewFilePath(targetView)
});
return {
hasTargetView: targetView !== null,
targetViewLoaded,
targetViewUsable,
targetViewIdentity,
targetViewFilePath: resolveTargetViewFilePath(targetView),
targetViewMetadataAvailable: targetViewMetadata.available,
targetViewExcalidrawPlugin: targetViewMetadata.value,
targetViewExcalidrawCapable,
activeFilePath,
activeWorkspaceLeafIdentity,
activeWorkspaceViewType,
activeWorkspaceDefinitelyInactive,
activeFileMetadataAvailable: activeFileMetadata.available,
activeFileExcalidrawPlugin: activeFileMetadata.value,
activeFileExcalidrawCapable,
hostEligible: legacyHostWithoutTargetViewProperty ? true : activeWorkspaceDefinitelyInactive ? false : targetViewUsable && (effectiveExcalidrawCapable ?? true),
hasSetView: typeof host.setView === "function"
};
};
var observeHostViewContext = (host) => {
const targetView = getCurrentHostTargetView(host);
return {
hasExplicitTargetViewProperty: hasExplicitTargetViewProperty2(host),
targetView,
description: resolveHostViewContextDescription(host, targetView)
};
};
var describeHostViewContext = (host) => {
return observeHostViewContext(host).description;
};
var resolveHostViewContextShellStateFromObservation = (observation) => {
const { description } = observation;
if (!observation.hasExplicitTargetViewProperty) {
return "live";
}
if (isDefinitelyInactiveActiveWorkspaceContext({
activeFilePath: description.activeFilePath,
activeWorkspaceViewType: description.activeWorkspaceViewType,
activeFileMetadataAvailable: description.activeFileMetadataAvailable,
activeFileExcalidrawCapable: description.activeFileExcalidrawCapable,
targetViewFilePath: description.targetViewFilePath
})) {
return "inactive";
}
if (description.hostEligible) {
return "live";
}
if (description.activeFileMetadataAvailable && description.activeFileExcalidrawCapable === false) {
return "inactive";
}
if (description.targetViewMetadataAvailable && description.targetViewExcalidrawCapable === false) {
return "inactive";
}
return "unbound";
};
var resolveHostViewContextEligibilityKey = (description) => {
return description.activeFileMetadataAvailable ? description.activeFileExcalidrawCapable ? "eligible" : "ineligible" : description.targetViewMetadataAvailable ? description.targetViewExcalidrawCapable ? "eligible" : "ineligible" : "legacy";
};
var resolveTargetViewSceneKey = (description) => {
const targetFileKey = description.targetViewFilePath ? file:${description.targetViewFilePath} : "file:none";
const targetViewIdentityKey = description.targetViewIdentity ? view:${description.targetViewIdentity} : "view:none";
return scene:target-view::${targetFileKey}::${targetViewIdentityKey};
};
var resolveActiveLeafFallbackSceneKey = (description) => {
if (!description.activeFilePath && !description.activeWorkspaceLeafIdentity && !description.activeWorkspaceViewType) {
return null;
}
const activeFileKey = description.activeFilePath ? file:${description.activeFilePath} : "file:none";
const activeLeafKey = description.activeWorkspaceLeafIdentity ? leaf:${description.activeWorkspaceLeafIdentity} : "leaf:none";
const activeViewTypeKey = description.activeWorkspaceViewType ? view-type:${description.activeWorkspaceViewType} : "view-type:none";
return scene:active-leaf::${activeFileKey}::${activeLeafKey}::${activeViewTypeKey};
};
var resolveHostViewContextKeyFromObservation = (observation) => {
if (!observation.hasExplicitTargetViewProperty) {
return "target:legacy-host";
}
const { description } = observation;
const state = resolveHostViewContextShellStateFromObservation(observation);
if (state === "live" && description.targetViewUsable) {
return resolveTargetViewSceneKey(description);
}
return resolveActiveLeafFallbackSceneKey(description) ?? scene:none::eligibility:${resolveHostViewContextEligibilityKey(description)};
};
var summarizeHostViewContextForDebug = (description) => {
return {
activeFilePath: description.activeFilePath,
activeLeafIdentity: description.activeWorkspaceLeafIdentity,
activeViewType: description.activeWorkspaceViewType,
targetViewIdentity: description.targetViewIdentity,
targetViewFilePath: description.targetViewFilePath,
targetViewLoaded: description.targetViewLoaded,
targetViewUsable: description.targetViewUsable,
hostEligible: description.hostEligible,
hasSetView: description.hasSetView
};
};
var renderViewBindStrategyLabel = (strategy) => {
const viewArgLabel = strategy.viewArg === void 0 ? "undefined" : ${strategy.viewArg};
return ${viewArgLabel}|reveal:${strategy.reveal};
};
var normalizeWorkspaceViewType = (value) => {
const normalized = value?.trim().toLowerCase() ?? null;
return normalized && normalized.length > 0 ? normalized : null;
};
var isNeutralNonHostActiveWorkspaceViewType = (value) => {
return normalizeWorkspaceViewType(value) === "sidepanel";
};
var isDefinitelyInactiveActiveWorkspaceContext = (input) => {
const normalizedViewType = normalizeWorkspaceViewType(input.activeWorkspaceViewType);
if (!input.activeFilePath || normalizedViewType === null) {
return false;
}
if (normalizedViewType === "excalidraw") {
return false;
}
if (isNeutralNonHostActiveWorkspaceViewType(normalizedViewType)) {
return false;
}
if (input.activeFileMetadataAvailable) {
return input.activeFileExcalidrawCapable === false;
}
return input.targetViewFilePath !== null && input.targetViewFilePath !== input.activeFilePath;
};
var isDefinitelyNonRebindableActiveWorkspaceViewType = (value) => {
const normalizedViewType = normalizeWorkspaceViewType(value);
return normalizedViewType !== null && normalizedViewType !== "excalidraw";
};
var shouldRebindHostViewToActiveWorkspaceView = (host) => {
const { description } = observeHostViewContext(host);
if (!description.hasSetView) {
return false;
}
if (isDefinitelyNonRebindableActiveWorkspaceViewType(description.activeWorkspaceViewType)) {
return false;
}
if (!description.targetViewUsable) {
if (description.activeFileMetadataAvailable && description.activeFileExcalidrawCapable === false) {
return false;
}
return normalizeWorkspaceViewType(description.activeWorkspaceViewType) === "excalidraw" || description.activeFilePath !== null;
}
if (!description.activeFilePath) {
return false;
}
if (description.activeFileMetadataAvailable && description.activeFileExcalidrawCapable === false) {
return false;
}
return description.targetViewFilePath !== description.activeFilePath;
};
var bindHostViewToActiveWorkspaceView = (host) => {
const initialDescription = resolveHostViewContextDescription(host);
if (!shouldRebindHostViewToActiveWorkspaceView(host)) {
return {
ok: true,
rebound: false
};
}
traceHostContextLifecycleEvent("rebind", "host view rebind requested", {
...summarizeHostViewContextForDebug(initialDescription)
});
if (!host.setView) {
traceHostContextLifecycleEvent("rebind", "host view rebind unavailable: host has no setView", {
...summarizeHostViewContextForDebug(initialDescription)
});
return {
ok: !shouldRebindHostViewToActiveWorkspaceView(host),
rebound: false
};
}
for (const strategy of VIEW_BIND_STRATEGIES) {
const beforeDescription = resolveHostViewContextDescription(host);
let threw = false;
let errorMessage = null;
try {
invokeHostSetView(host, strategy.viewArg, strategy.reveal);
} catch (error) {
threw = true;
errorMessage = error instanceof Error ? error.message : ${error};
}
const afterDescription = resolveHostViewContextDescription(host);
const shouldAttemptRebindAfter = shouldRebindHostViewToActiveWorkspaceView(host);
traceHostContextLifecycleEvent("rebind", "host view rebind strategy attempted", {
strategy: renderViewBindStrategyLabel(strategy),
threw,
...errorMessage ? { errorMessage } : {},
before: summarizeHostViewContextForDebug(beforeDescription),
after: summarizeHostViewContextForDebug(afterDescription),
shouldAttemptRebindAfter
});
if (!shouldAttemptRebindAfter) {
traceHostContextLifecycleEvent("rebind", "host view rebind confirmed", {
strategy: renderViewBindStrategyLabel(strategy),
...summarizeHostViewContextForDebug(afterDescription)
});
return {
ok: true,
rebound: true
};
}
}
const finalDescription = resolveHostViewContextDescription(host);
traceHostContextLifecycleEvent("rebind", "host view rebind exhausted without usable targetView", {
initial: summarizeHostViewContextForDebug(initialDescription),
final: summarizeHostViewContextForDebug(finalDescription)
});
return {
ok: !shouldRebindHostViewToActiveWorkspaceView(host),
rebound: false
};
};
var resolveLiveExcalidrawApiFromTargetView = (targetView) => {
if (!targetView || typeof targetView !== "object") {
return null;
}
const record = targetView;
if ("_loaded" in record && record["_loaded"] !== true) {
return null;
}
return record["excalidrawAPI"] ?? null;
};
var recoverHostViewFromReplacedLeaf = (host, context) => {
try {
const leaf = context.leaf;
const replacement = leaf?.view;
if (!leaf || !replacement || replacement === context.view) return "unavailable";
const view = replacement;
if (context.filePath && view.file?.path && view.file.path !== context.filePath)
return "unavailable";
const workspace = context.workspace;
if (view.getViewType?.() !== "excalidraw") return "unavailable";
if (workspace?.activeLeaf !== leaf && workspace?.getMostRecentLeaf?.() !== leaf)
return "unavailable";
if (!resolveLiveExcalidrawApiFromTargetView(replacement)) return "pending";
invokeHostSetView(host, replacement, false);
return host.targetView === replacement ? "recovered" : "unavailable";
} catch {
return "unavailable";
}
};
var ensureHostViewContextState = (host) => {
if (resolveHostViewContextDescription(host).hostEligible) {
return {
ok: true,
rebound: false
};
}
if (!host.setView) {
return {
ok: resolveHostViewContextDescription(host).hostEligible,
rebound: false
};
}
for (const strategy of VIEW_BIND_STRATEGIES) {
try {
invokeHostSetView(host, strategy.viewArg, strategy.reveal);
if (resolveHostViewContextDescription(host).hostEligible) {
return {
ok: true,
rebound: true
};
}
} catch {
}
}
return {
ok: resolveHostViewContextDescription(host).hostEligible,
rebound: false
};
};
// src/ui/sidepanel/selection/sceneBinding.ts
var createSceneRef = (input) => {
return input;
};
var resolveSceneRefFromObservation = (observation) => {
const { description } = observation;
const key = resolveHostViewContextKeyFromObservation(observation);
const state = resolveHostViewContextShellStateFromObservation(observation);
if (!observation.hasExplicitTargetViewProperty) {
return createSceneRef({
source: "legacy-host",
key,
filePath: description.activeFilePath,
viewIdentity: description.targetViewIdentity ?? description.activeFilePath,
leafIdentity: description.activeWorkspaceLeafIdentity,
viewType: description.activeWorkspaceViewType
});
}
if (state === "live" && description.targetViewUsable) {
return createSceneRef({
source: "target-view",
key,
filePath: description.targetViewFilePath,
viewIdentity: description.targetViewIdentity,
leafIdentity: description.activeWorkspaceLeafIdentity,
viewType: description.activeWorkspaceViewType
});
}
if (description.activeFilePath || description.activeWorkspaceLeafIdentity || description.activeWorkspaceViewType) {
return createSceneRef({
source: "active-leaf",
key,
filePath: description.activeFilePath,
viewIdentity: description.activeWorkspaceLeafIdentity ?? description.activeWorkspaceViewType ?? description.activeFilePath,
leafIdentity: description.activeWorkspaceLeafIdentity,
viewType: description.activeWorkspaceViewType
});
}
return null;
};
var resolveSceneBindingFromObservation = (input) => {
const sceneRef = resolveSceneRefFromObservation(input.observation);
const sceneKey = sceneRef?.key ?? resolveHostViewContextKeyFromObservation(input.observation);
return {
source: sceneRef?.source ?? "none",
sceneRef,
sceneKey,
refreshKey: ${sceneKey}::state:${input.state}::rebind:${input.shouldAttemptRebind ? "yes" : "no"},
state: input.state,
shouldAttemptRebind: input.shouldAttemptRebind
};
};
var resolveSceneBindingFromHost = (host) => {
const observation = observeHostViewContext(host);
return resolveSceneBindingFromObservation({
observation,
state: resolveHostViewContextShellStateFromObservation(observation),
shouldAttemptRebind: shouldRebindHostViewToActiveWorkspaceView(host)
});
};
var haveSameSceneBindingRefreshKey = (left, right) => {
if (!left || !right) {
return left === right;
}
return left.refreshKey === right.refreshKey;
};
var canMirrorSelectionToSceneBinding = (binding) => {
if (binding.state !== "live" || binding.shouldAttemptRebind) {
return false;
}
return binding.source === "legacy-host" || binding.source === "target-view";
};
// src/ui/sidepanel/selection/hostSelectionBridge.ts var SidepanelHostSelectionBridge = class { #host; #suppressContentFocusOut; #resolveCurrentSceneBinding; #latestMirrorRequestId = 0; #pendingMirrorRequestId = null; constructor(input) { this.#host = input.host; this.#suppressContentFocusOut = input.suppressContentFocusOut; this.#resolveCurrentSceneBinding = input.resolveCurrentSceneBinding; } invalidatePendingSelectionMirror() { this.#latestMirrorRequestId += 1; this.#pendingMirrorRequestId = null; } hasPendingSelectionMirror() { return this.#pendingMirrorRequestId !== null; } resolveCurrentSceneBinding() { return this.#resolveCurrentSceneBinding?.() ?? resolveSceneBindingFromHost(this.#host); } matchesExpectedSceneBinding(expectedSceneBinding) { if (!expectedSceneBinding) { return true; } const currentSceneBinding = this.resolveCurrentSceneBinding(); return haveSameSceneBindingRefreshKey(expectedSceneBinding, currentSceneBinding) && canMirrorSelectionToSceneBinding(currentSceneBinding); } resolveFallbackApi(expectedSceneBinding) { if (expectedSceneBinding && !this.matchesExpectedSceneBinding(expectedSceneBinding)) { return null; } try { return this.#host.getExcalidrawAPI?.() ?? null; } catch { return null; } } mirrorSelectionToHost(elementIds, expectedSceneBinding) { if (expectedSceneBinding && !this.matchesExpectedSceneBinding(expectedSceneBinding)) { this.invalidatePendingSelectionMirror(); return; } if (!expectedSceneBinding && !ensureHostViewContextState(this.#host).ok) { this.invalidatePendingSelectionMirror(); return; } const targetView = this.#host.targetView; const view = targetView; const leafView = view?.leaf?.view; const api = this.resolveFallbackApi(expectedSceneBinding); const hasAuthority = () => mirrorRequestId === this.#latestMirrorRequestId && targetView === this.#host.targetView && leafView === view?.leaf?.view && api === this.resolveFallbackApi(expectedSceneBinding); const nextElementIds = [...elementIds]; const mirrorRequestId = this.#latestMirrorRequestId + 1; this.#latestMirrorRequestId = mirrorRequestId; this.#pendingMirrorRequestId = mirrorRequestId; const runSelectAttempt = () => { if (expectedSceneBinding) { if (!this.matchesExpectedSceneBinding(expectedSceneBinding)) { return "hostUnavailable"; } } else { const hostViewContext = ensureHostViewContextState(this.#host); if (!hostViewContext.ok) { return "hostUnavailable"; } } if (!this.#host.selectElementsInView) { return "failed"; } if (!hasAuthority()) return "hostUnavailable"; this.#suppressContentFocusOut(); if (!hasAuthority()) return "hostUnavailable"; try { this.#host.selectElementsInView([...nextElementIds]); return "applied"; } catch { return "failed"; } }; const runAppStateFallback = () => { if (expectedSceneBinding) { if (!this.matchesExpectedSceneBinding(expectedSceneBinding)) { return false; } } else { const hostViewContext = ensureHostViewContextState(this.#host); if (!hostViewContext.ok) { return false; } } const apiCandidate = this.resolveFallbackApi(expectedSceneBinding); if (!apiCandidate || typeof apiCandidate !== "object") { return false; } const updateScene = apiCandidate.updateScene; if (!updateScene) { return false; } const selectedElementIds = Object.fromEntries(nextElementIds.map((id) => [id, true])); if (!hasAuthority() || apiCandidate !== api) return false; try { updateScene({ appState: { selectedElementIds } }); return true; } catch { return false; } }; const resolveVerificationState = () => { try { if (expectedSceneBinding) { if (!this.matchesExpectedSceneBinding(expectedSceneBinding)) { return "hostUnavailable"; } } else { const hostViewContext = ensureHostViewContextState(this.#host); if (!hostViewContext.ok) { return "hostUnavailable"; } } if (!hasAuthority()) return "hostUnavailable"; const liveSelectedIds = collectUniqueSelectionIds( this.#host.getViewSelectedElements?.() ?? [] ); return haveSameIds(liveSelectedIds, nextElementIds) ? "match" : "mismatch"; } catch { return "mismatch"; } }; const firstAttemptResult = runSelectAttempt(); if (firstAttemptResult === "hostUnavailable") { if (this.#pendingMirrorRequestId === mirrorRequestId) { this.#pendingMirrorRequestId = null; } return; } if (firstAttemptResult === "failed") { runAppStateFallback(); } if (!this.#host.getViewSelectedElements) { if (this.#pendingMirrorRequestId === mirrorRequestId) { this.#pendingMirrorRequestId = null; } return; } Promise.resolve().then(() => { if (!hasAuthority()) { if (this.#pendingMirrorRequestId === mirrorRequestId) this.#pendingMirrorRequestId = null; return; } const firstVerification = resolveVerificationState(); if (firstVerification === "match") { if (this.#pendingMirrorRequestId === mirrorRequestId) { this.#pendingMirrorRequestId = null; } return; } if (firstVerification === "hostUnavailable") { if (this.#pendingMirrorRequestId === mirrorRequestId) { this.#pendingMirrorRequestId = null; } return; } if (mirrorRequestId !== this.#latestMirrorRequestId) { return; } const retryResult = runSelectAttempt(); if (retryResult === "hostUnavailable") { if (this.#pendingMirrorRequestId === mirrorRequestId) { this.#pendingMirrorRequestId = null; } return; } if (retryResult === "applied" && resolveVerificationState() === "match") { if (this.#pendingMirrorRequestId === mirrorRequestId) { this.#pendingMirrorRequestId = null; } return; } if (mirrorRequestId !== this.#latestMirrorRequestId) { return; } const fallbackApplied = runAppStateFallback(); if (!fallbackApplied) { if (this.#pendingMirrorRequestId === mirrorRequestId) { this.#pendingMirrorRequestId = null; } return; } const fallbackVerification = resolveVerificationState(); if ((fallbackVerification === "match" || fallbackVerification === "hostUnavailable") && this.#pendingMirrorRequestId === mirrorRequestId) { this.#pendingMirrorRequestId = null; } }); } };
// src/ui/sidepanel/selection/nodeContext.ts var isMoreSpecificCandidate = (candidate, candidateDepth, current) => { if (candidate.elementIds.length !== current.node.elementIds.length) { return candidate.elementIds.length < current.node.elementIds.length; } if (candidateDepth !== current.depth) { return candidateDepth > current.depth; } return candidate.children.length < current.node.children.length; }; var resolveSelectedNodes = (tree, selectedElementIds) => { const bestByElementId = /* @PURE / new Map(); const stack = tree.map((node) => ({ node, depth: 0 })); while (stack.length > 0) { const next = stack.pop(); if (!next) { continue; } const { node, depth } = next; for (const elementId of node.elementIds) { const currentBest = bestByElementId.get(elementId); if (!currentBest || isMoreSpecificCandidate(node, depth, currentBest)) { bestByElementId.set(elementId, { node, depth }); } } if (node.children.length === 0) { continue; } for (let index = node.children.length - 1; index >= 0; index -= 1) { const child = node.children[index]; if (child) { stack.push({ node: child, depth: depth + 1 }); } } } const seenNodeIds = / @PURE / new Set(); const resolved = []; for (const selectedElementId of selectedElementIds) { const node = bestByElementId.get(selectedElementId)?.node; if (!node || seenNodeIds.has(node.id)) { continue; } seenNodeIds.add(node.id); resolved.push(node); } return resolved; }; var collectVisibleNodeContext = (nodes) => { const visibleNodes = []; const parentById = / @PURE */ new Map(); const walk = (nextNodes, parentId) => { for (const node of nextNodes) { visibleNodes.push(node); parentById.set(node.id, parentId); if (node.isExpanded && node.children.length > 0) { walk(node.children, node.id); } } }; walk(nodes, null); return { visibleNodes, parentById }; };
// src/ui/sidepanel/selection/selectionReconciler.ts var reconcileSelectedElementIds = (input) => { if (!input.getViewSelectedElements) { return { source: "noLiveSelectionApi", resolvedSelection: input.selectionOverride ?? input.snapshotSelection, clearSelectionOverride: false }; } const hostViewReady = input.ensureHostViewContext(); if (!hostViewReady) { const failStoppedPendingMirror = input.hasPendingSelectionMirror === true; return { source: "hostViewUnavailable", resolvedSelection: failStoppedPendingMirror ? input.snapshotSelection : input.selectionOverride ?? input.snapshotSelection, clearSelectionOverride: failStoppedPendingMirror }; } try { const liveSelection = collectUniqueSelectionIds(input.getViewSelectedElements() ?? []); if (input.selectionOverride && haveSameIds(liveSelection, input.selectionOverride)) { return { source: "liveMatchesOverride", resolvedSelection: liveSelection, clearSelectionOverride: false }; } if (input.selectionOverride && !input.hasSelectionBridge && liveSelection.length === 0) { return { source: "overrideWithoutBridgeFallback", resolvedSelection: input.selectionOverride, clearSelectionOverride: false }; } if (input.selectionOverride && input.hasPendingSelectionMirror === true && !haveSameIds(liveSelection, input.selectionOverride)) { return { source: "pendingMirrorKeepsOverride", resolvedSelection: input.selectionOverride, clearSelectionOverride: false }; } if (liveSelection.length === 0 && input.snapshotSelection.length > 0) { if (input.hasSelectionBridge && input.hostViewRebound !== true && input.selectionOverride === null) { return { source: "liveDiffersFromSnapshot", resolvedSelection: liveSelection, clearSelectionOverride: true }; } const hasStaleOverrideAgainstSnapshot = !!input.selectionOverride && !haveSameIds(input.selectionOverride, input.snapshotSelection); return { source: "snapshotPreferredOverEmptyLive", resolvedSelection: hasStaleOverrideAgainstSnapshot ? input.snapshotSelection : input.selectionOverride ?? input.snapshotSelection, clearSelectionOverride: hasStaleOverrideAgainstSnapshot }; } if (!haveSameIds(liveSelection, input.snapshotSelection)) { return { source: "liveDiffersFromSnapshot", resolvedSelection: liveSelection, clearSelectionOverride: true }; } const hasStaleOverrideAgainstLive = !!input.selectionOverride && !haveSameIds(liveSelection, input.selectionOverride); if (hasStaleOverrideAgainstLive) { return { source: "snapshotOrOverrideFallback", resolvedSelection: liveSelection, clearSelectionOverride: true }; } } catch (error) { return { source: "snapshotOrOverrideFallback", resolvedSelection: input.selectionOverride ?? input.snapshotSelection, clearSelectionOverride: false, readErrorMessage: error instanceof Error ? error.message : "unknown" }; } return { source: "snapshotOrOverrideFallback", resolvedSelection: input.selectionOverride ?? input.snapshotSelection, clearSelectionOverride: false }; };
// src/ui/sidepanel/selection/selectionResolution.ts var resolveCurrentSidepanelSelectionNodes = (resolution) => { return resolution.explicitSelectedNodes ?? resolution.selection.nodes; }; var buildLayerNodeLookup = (tree) => { const nodeById = /* @PURE / new Map(); const groupNodeByGroupId = / @PURE */ new Map(); const stack = [...tree]; while (stack.length > 0) { const node = stack.pop(); if (!node) { continue; } nodeById.set(node.id, node); if (node.type === "group" && node.groupId && !groupNodeByGroupId.has(node.groupId)) { groupNodeByGroupId.set(node.groupId, node); } for (let index = node.children.length - 1; index >= 0; index -= 1) { const child = node.children[index]; if (child) { stack.push(child); } } } return { nodeById, groupNodeByGroupId }; }; var makeSidepanelSelectionNodeRef = (node) => { if (node.type === "group" && node.groupId) { return { kind: "groupId", groupId: node.groupId }; } return { kind: "nodeId", nodeId: node.id }; }; var resolveExplicitSelectedNodes = (tree, selectionOverride, selectedElementIds) => { if (!selectionOverride?.nodeRefs || !haveSameIds(selectionOverride.elementIds, selectedElementIds)) { return null; } const lookup = buildLayerNodeLookup(tree); const resolvedNodes = selectionOverride.nodeRefs.map((nodeRef) => { if (nodeRef.kind === "groupId") { return lookup.groupNodeByGroupId.get(nodeRef.groupId) ?? null; } return lookup.nodeById.get(nodeRef.nodeId) ?? null; }).filter((node) => Boolean(node)); if (resolvedNodes.length !== selectionOverride.nodeRefs.length) { return null; } return resolvedNodes; }; var resolveSidepanelSelection = (input) => { const explicitSelectedNodes = resolveExplicitSelectedNodes( input.tree, input.selectionOverride, input.selectedElementIds ); const resolvedSelectionNodes = explicitSelectedNodes ?? resolveSelectedNodes(input.tree, input.selectedElementIds); return { explicitSelectedNodes, selection: { elementIds: input.selectedElementIds, nodes: resolvedSelectionNodes, explicitSelectedNodes, frameResolution: resolveSharedFrame(resolvedSelectionNodes), structuralMove: explicitSelectedNodes ? resolveStructuralMoveSelection(explicitSelectedNodes) : null } }; };
// src/ui/sidepanel/settings/settingsWriteQueue.ts var SETTINGS_WRITE_VERIFICATION_MAX_ATTEMPTS = 2; var isPromiseLike2 = (value) => { return !!value && typeof value === "object" && "then" in value; }; var readScriptSettingsSnapshot = (getScriptSettings) => { const settings = getScriptSettings?.() ?? {}; const snapshot = {}; for (const [key, entry] of Object.entries(settings)) { if (!entry || typeof entry !== "object" || !("value" in entry)) { continue; } const cast = entry; if (typeof cast.description === "string") { snapshot[key] = { value: cast.value, description: cast.description }; continue; } snapshot[key] = { value: cast.value }; } return snapshot; }; var buildNextSettingsSnapshot = (input) => { const nextSettings = readScriptSettingsSnapshot(input.getScriptSettings); for (const entry of input.batch) { entry.mutator(nextSettings); } return nextSettings; }; var areEquivalentSettingValues = (left, right) => { if (Object.is(left, right)) { return true; } if (Array.isArray(left) || Array.isArray(right)) { if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) { return false; } return left.every((entry, index) => areEquivalentSettingValues(entry, right[index])); } if (!left || !right || typeof left !== "object" || typeof right !== "object") { return false; } const leftEntries = Object.entries(left); const rightEntries = Object.entries(right); if (leftEntries.length !== rightEntries.length) { return false; } return leftEntries.every( ([key, value]) => areEquivalentSettingValues(value, right[key]) ); }; var areEquivalentSettingEntries = (left, right) => { if (!left || !right) { return left === right; } return areEquivalentSettingValues(left.value, right.value) && left.description === right.description; }; var doesSettingsSnapshotContain = (currentSettings, expectedSettings) => { return Object.entries(expectedSettings).every( ([key, entry]) => areEquivalentSettingEntries(currentSettings[key], entry) ); }; var persistSettingsBatch = async (input) => { for (let attempt = 0; attempt < SETTINGS_WRITE_VERIFICATION_MAX_ATTEMPTS; attempt += 1) { const nextSettings = buildNextSettingsSnapshot(input); const result = input.setScriptSettings(nextSettings); if (isPromiseLike2(result)) { await result; } await Promise.resolve(); const persistedSettings = readScriptSettingsSnapshot(input.getScriptSettings); if (doesSettingsSnapshotContain(persistedSettings, nextSettings)) { return; } } throw new Error("Script settings verification failed after bounded retries."); }; var resolveBatch = (batch, result) => { for (const entry of batch) { entry.resolve(result); } }; var settingsPersistenceMachine = setup({ types: { context: {}, input: {}, events: {} }, actors: { writeSettingsBatch: fromPromise( async ({ input }) => { await persistSettingsBatch(input); } ) }, guards: { hasPendingWrites: ({ context }) => context.pendingWrites.length > 0 }, actions: { startBatchFromEvent: assign({ activeBatch: ({ event }) => event.type === "ENQUEUE" ? [event.entry] : [], pendingWrites: [] }), appendPendingWriteFromEvent: assign({ pendingWrites: ({ context, event }) => { if (event.type !== "ENQUEUE") { return context.pendingWrites; } return [...context.pendingWrites, event.entry]; } }), promotePendingWritesToActiveBatch: assign({ activeBatch: ({ context }) => context.pendingWrites, pendingWrites: [] }), clearBatches: assign({ activeBatch: [], pendingWrites: [] }), resolveActiveBatchSuccess: ({ context }) => { resolveBatch(context.activeBatch, true); }, resolveActiveBatchFailure: ({ context }) => { resolveBatch(context.activeBatch, false); }, notifyActiveBatchFailure: ({ context }) => { const message = context.activeBatch.at(-1)?.onErrorMessage ?? "Failed to persist LayerManager script settings."; context.notify(message); }, resolveAllWritesAsFailed: ({ context }) => { resolveBatch(context.activeBatch, false); resolveBatch(context.pendingWrites, false); } } }).createMachine({ id: "sidepanelSettingsPersistence", initial: "idle", context: ({ input }) => ({ getScriptSettings: input.getScriptSettings, setScriptSettings: input.setScriptSettings, notify: input.notify, activeBatch: [], pendingWrites: [] }), states: { idle: { on: { ENQUEUE: { target: "writing", actions: "startBatchFromEvent" }, DISPOSE: { target: "closed", actions: ["resolveAllWritesAsFailed", "clearBatches"] } } }, writing: { invoke: { src: "writeSettingsBatch", input: ({ context }) => { if (!context.getScriptSettings || !context.setScriptSettings) { throw new Error("Missing script settings persistence host APIs."); } return { getScriptSettings: context.getScriptSettings, setScriptSettings: context.setScriptSettings, batch: context.activeBatch }; }, onDone: [ { guard: "hasPendingWrites", target: "writing", reenter: true, actions: ["resolveActiveBatchSuccess", "promotePendingWritesToActiveBatch"] }, { target: "idle", actions: ["resolveActiveBatchSuccess", "clearBatches"] } ], onError: [ { guard: "hasPendingWrites", target: "writing", reenter: true, actions: [ "notifyActiveBatchFailure", "resolveActiveBatchFailure", "promotePendingWritesToActiveBatch" ] }, { target: "idle", actions: ["notifyActiveBatchFailure", "resolveActiveBatchFailure", "clearBatches"] } ] }, on: { ENQUEUE: { actions: "appendPendingWriteFromEvent" }, DISPOSE: { target: "closed", actions: ["resolveAllWritesAsFailed", "clearBatches"] } } }, closed: { type: "final" } } }); var createSidepanelSettingsPersistenceActor = (input) => { return createActor(settingsPersistenceMachine, { input }); }; var SidepanelSettingsWriteQueue = class { #getScriptSettings; #setScriptSettings; #actor; #disposed = false; constructor(input) { this.#getScriptSettings = input.getScriptSettings; this.#setScriptSettings = input.setScriptSettings; this.#actor = createSidepanelSettingsPersistenceActor(input); this.#actor.start(); } get canWrite() { return !this.#disposed && !!this.#getScriptSettings && !!this.#setScriptSettings; } enqueue(mutator, onErrorMessage) { if (!this.canWrite) { return Promise.resolve(false); } return new Promise((resolve) => { this.#actor.send({ type: "ENQUEUE", entry: { mutator, onErrorMessage, resolve } }); }); } dispose() { if (this.#disposed) { return; } this.#disposed = true; this.#actor.send({ type: "DISPOSE" }); this.#actor.stop(); } };
// src/ui/excalidrawSidepanelRenderer.ts
var SIDEPANEL_TITLE = "Layer Manager";
var INDENT_STEP_PX = 12;
var QUICK_PRESET_INLINE_MAX = 4;
var QUICK_PRESET_TOTAL_MAX = 24;
var ALL_DESTINATION_TOTAL_MAX = 64;
var LAST_MOVE_LABEL_MAX = 26;
var KEYBOARD_PROMPT_SUPPRESSION_MS = 160;
var FOCUSOUT_SUPPRESSION_WINDOW_MS = 420;
var KEYBOARD_STICKY_CAPTURE_MS = 1400;
var ROW_MIN_HEIGHT_PX = 20;
var REVIEW_CURSOR_COMFORT_MIN_MARGIN_ROWS = 2;
var REVIEW_CURSOR_COMFORT_VIEWPORT_RATIO = 0.18;
var REVIEW_CURSOR_COMFORT_MAX_VIEWPORT_RATIO = 0.3;
var ROW_FONT_SIZE_PX = 11;
var ICON_SIZE_PX = 13;
var ICON_BUTTON_SIZE_PX = 16;
var TOOLBAR_FONT_SIZE_PX = 11;
var GROUP_ROW_DROP_EDGE_RATIO = 0.24;
var GROUP_ROW_DROP_EDGE_MIN_PX = 4;
var SIDEPANEL_INTERACTION_DEBUG_FLAG = "LMX_DEBUG_SIDEPANEL_INTERACTION";
var SIDEPANEL_KEYBOARD_HINT_LINES = [
"↑/↓ focus rows",
"Shift+↑/↓ extend row selection",
"Home/End bounds",
"PgUp/PgDn page",
"Shift+PgUp/PgDn extend page",
"Space select/deselect row",
"Ctrl+Space toggle row",
"Shift+Space add range to selection",
"←/→ collapse/expand",
"Enter rename",
"Del delete",
"Alt+↑/↓ nudge order",
"Alt+[ / ] out/in group",
"Alt+0 root",
"Alt+1..9 pick group",
"F/B reorder",
"Shift+F/B front/back",
"G/U structural"
];
var SIDEPANEL_KEYBOARD_HINT_TOOLTIP = [
"Keyboard shortcuts",
...SIDEPANEL_KEYBOARD_HINT_LINES
].join("\n");
var resolveRowSelectionDebugSemantics = (source) => {
switch (source) {
case "keyboardToggle":
return {
selectionOrigin: "keyboard",
selectionSemantics: "replace"
};
case "keyboardModifierToggle":
return {
selectionOrigin: "keyboard",
selectionSemantics: "toggle"
};
case "keyboardRange":
return {
selectionOrigin: "keyboard",
selectionSemantics: "range"
};
case "keyboardExtend":
return {
selectionOrigin: "keyboard",
selectionSemantics: "extend"
};
case "mouseClick":
return {
selectionOrigin: "mouse",
selectionSemantics: "replace"
};
case "mouseToggle":
return {
selectionOrigin: "mouse",
selectionSemantics: "toggle"
};
case "mouseRange":
return {
selectionOrigin: "mouse",
selectionSemantics: "range"
};
}
};
var nextSidepanelRendererInstanceId = 0;
var ROW_STYLE_CONFIG = {
indentStepPx: INDENT_STEP_PX,
rowMinHeightPx: ROW_MIN_HEIGHT_PX,
rowFontSizePx: ROW_FONT_SIZE_PX,
iconButtonSizePx: ICON_BUTTON_SIZE_PX,
iconSizePx: ICON_SIZE_PX
};
var cloneDragDropHint = (hint) => {
if (!hint) {
return null;
}
return hint.kind === "reorder" ? {
kind: "reorder",
nodeId: hint.nodeId,
placement: hint.placement
} : {
kind: "reparent",
nodeId: hint.nodeId
};
};
var haveSameDragDropHint = (left, right) => {
if (!left || !right) {
return left === right;
}
if (left.nodeId !== right.nodeId || left.kind !== right.kind) {
return false;
}
if (left.kind === "reorder" && right.kind === "reorder") {
return left.placement === right.placement;
}
return true;
};
var resolveSidepanelRowDropHintKind = (hint) => {
if (!hint) {
return null;
}
if (hint.kind === "reorder") {
return hint.placement === "before" ? "reorderBefore" : "reorderAfter";
}
return "reparent";
};
var resolveRowPreviewBoxShadow = (node, state, dropHintKind) => {
const shadows = [];
if (state.visibility === "hidden") {
shadows.push("inset 3px 0 0 0 var(--text-faint, rgba(120,120,120,0.55))");
} else if (state.visibility === "mixed") {
shadows.push("inset 3px 0 0 0 var(--background-modifier-border-hover, rgba(120,120,120,0.45))");
}
if (state.lock === "locked") {
shadows.push("inset -3px 0 0 0 var(--text-muted, rgba(120,120,120,0.6))");
} else if (state.lock === "mixed") {
shadows.push("inset -3px 0 0 0 var(--background-secondary-alt, rgba(120,120,120,0.45))");
}
if (dropHintKind === "reparent") {
shadows.push("inset 0 0 0 2px var(--interactive-accent, rgba(120,120,120,0.68))");
if (node.type === "group") {
shadows.push("inset 0 0 0 999px var(--interactive-accent-hover, rgba(120,120,120,0.1))");
}
}
if (dropHintKind === "reorderBefore") {
shadows.push("inset 0 3px 0 0 var(--interactive-accent, rgba(120,120,120,0.92))");
}
if (dropHintKind === "reorderAfter") {
shadows.push("inset 0 -3px 0 0 var(--interactive-accent, rgba(120,120,120,0.92))");
}
return shadows.join(", ");
};
var applyRenderedRowPreviewShellState = (row, input) => {
row.style.boxShadow = resolveRowPreviewBoxShadow(
input.node,
input.nodeVisualState,
input.dropHintKind
);
row.style.background = "";
row.style.borderColor = "";
row.style.borderStyle = "solid";
if (input.filterMatchKind === "self") {
row.style.background = "var(--background-modifier-hover, rgba(120,120,120,0.12))";
row.style.borderColor = "var(--background-modifier-border, rgba(120,120,120,0.16))";
}
if (input.selected) {
row.style.background = "var(--interactive-accent-hover, rgba(120,120,120,0.2))";
row.style.borderColor = "var(--interactive-accent, rgba(120,120,120,0.32))";
}
if (input.dropHintKind === "reparent" && !input.selected) {
row.style.background = input.node.type === "group" ? "var(--interactive-accent-hover, rgba(120,120,120,0.22))" : "var(--interactive-accent-hover, rgba(120,120,120,0.16))";
row.style.borderColor = "var(--interactive-accent, rgba(120,120,120,0.68))";
}
if (input.dropHintKind === "reparent" && input.node.type === "group") {
row.style.borderColor = "var(--interactive-accent, rgba(120,120,120,0.78))";
row.style.borderStyle = "dashed";
}
};
var styleDropHintAssistiveLabel = (label) => {
label.style.position = "absolute";
label.style.width = "1px";
label.style.height = "1px";
label.style.padding = "0";
label.style.margin = "-1px";
label.style.overflow = "hidden";
label.style.clip = "rect(0 0 0 0)";
label.style.clipPath = "inset(50%)";
label.style.whiteSpace = "nowrap";
label.style.border = "0";
};
var styleVisibleDropHintIndicator = (label) => {
label.style.position = "absolute";
label.style.top = "50%";
label.style.left = "50%";
label.style.transform = "translate(-50%, -50%)";
label.style.display = "inline-flex";
label.style.alignItems = "center";
label.style.justifyContent = "center";
label.style.padding = "1px 6px";
label.style.borderRadius = "999px";
label.style.border = "1px solid var(--interactive-accent, rgba(120,120,120,0.72))";
label.style.background = "var(--background-primary, rgba(24,24,24,0.92))";
label.style.color = "var(--text-normal, inherit)";
label.style.fontSize = "9px";
label.style.lineHeight = "1.3";
label.style.letterSpacing = "0.02em";
label.style.whiteSpace = "nowrap";
label.style.pointerEvents = "none";
label.style.boxShadow = "0 0 0 1px rgba(0,0,0,0.12)";
};
var isDropHintAssistiveLabel = (element) => {
return element.tagName === "SPAN" && element.style.position === "absolute" && element.style.clipPath === "inset(50%)";
};
var resolveVisibleDropHintIndicatorText = (hint, node) => {
if (!hint || node.type !== "group") {
return null;
}
if (hint.kind === "reparent") {
return "Into group";
}
return hint.placement === "before" ? "Before group" : "After group";
};
var findRenderedRowDropHintAssistiveLabel = (row) => {
return Array.from(row.children).find(isDropHintAssistiveLabel) ?? null;
};
var hasDom = () => {
return typeof document !== "undefined";
};
var readNumericDimension = (value) => {
return typeof value === "number" && Number.isFinite(value) ? value : 0;
};
var resolveElementViewportHeight = (element) => {
const clientHeight = readNumericDimension(
element.clientHeight
);
if (clientHeight > 0) {
return clientHeight;
}
const rect = element.getBoundingClientRect?.();
return rect && Number.isFinite(rect.height) ? rect.height : 0;
};
var resolveElementScrollHeight = (element) => {
const scrollHeight = readNumericDimension(
element.scrollHeight
);
if (scrollHeight > 0) {
return scrollHeight;
}
return resolveElementViewportHeight(element);
};
var resolveElementScrollTop = (element) => {
return readNumericDimension(element.scrollTop);
};
var runUiAction = (action, onError, fallbackMessage) => {
void action().catch((error) => {
if (error instanceof Error) {
onError(${fallbackMessage}: ${error.message});
return;
}
onError(fallbackMessage);
});
};
var isTextInputTarget = (target) => {
if (!target || typeof target !== "object") {
return false;
}
if (target.isContentEditable === true) {
return true;
}
if (!("tagName" in target)) {
return false;
}
const rawTagName = target.tagName;
if (typeof rawTagName !== "string") {
return false;
}
const tagName = rawTagName.toLowerCase();
return tagName === "input" || tagName === "textarea" || tagName === "select";
};
var isSpaceLikeKey = (key) => {
return key === " " || key === "Space" || key === "Spacebar";
};
var isSpaceShortcutEvent2 = (event) => {
return event.code === "Space" || isSpaceLikeKey(event.key);
};
var isDocumentReroutableModifierSpaceShortcut = (event) => {
return (event.ctrlKey || event.metaKey) && !event.altKey && isSpaceShortcutEvent2(event);
};
var shouldClaimDocumentSpaceLikeEvent = (event) => {
if (event.altKey || !isSpaceShortcutEvent2(event)) {
return false;
}
return !event.ctrlKey && !event.metaKey || isDocumentReroutableModifierSpaceShortcut(event);
};
var resolveDocumentAltMoveDigit = (event) => {
if (!event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
return null;
}
if (typeof event.code === "string") {
const match = /^Digit([0-9])$/.exec(event.code);
if (match) {
return Number(match[1]);
}
}
return /^[0-9]$/.test(event.key) ? Number(event.key) : null;
};
var resolveDocumentAltStructuralMoveDirection = (event) => {
if (!event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
return null;
}
if (event.code === "BracketLeft" || event.key === "[") {
return "out";
}
if (event.code === "BracketRight" || event.key === "]") {
return "in";
}
return null;
};
var isDocumentReroutableAltMovementShortcut = (event) => {
if (!event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
return false;
}
return event.key === "ArrowDown" || event.key === "ArrowUp" || resolveDocumentAltStructuralMoveDirection(event) !== null || resolveDocumentAltMoveDigit(event) !== null;
};
var isDocumentRoutingContinuationKey = (event) => {
if (isDocumentReroutableModifierSpaceShortcut(event) || isDocumentReroutableAltMovementShortcut(event)) {
return true;
}
if (event.ctrlKey || event.metaKey || event.altKey) {
return false;
}
switch (event.key) {
case "ArrowDown":
case "ArrowUp":
case "ArrowLeft":
case "ArrowRight":
case "Home":
case "End":
case "PageDown":
case "PageUp":
case "Enter":
case "Delete":
case "Backspace":
return true;
default:
return false;
}
};
var claimHandledKeyboardEvent2 = (event) => {
event.preventDefault();
event.stopPropagation?.();
event.stopImmediatePropagation?.();
};
var ExcalidrawSidepanelRenderer = class {
constructor(host, lifecycle) {
this.lifecycle = lifecycle;
this.#host = host;
this.#settingsWriteQueue = new SidepanelSettingsWriteQueue({
...host.getScriptSettings ? { getScriptSettings: host.getScriptSettings.bind(host) } : {},
...host.setScriptSettings ? { setScriptSettings: host.setScriptSettings.bind(host) } : {},
notify: (message) => {
this.notify(message);
}
});
this.#quickMovePersistenceService = new SidepanelQuickMovePersistenceService({
...host.getScriptSettings ? { getScriptSettings: host.getScriptSettings.bind(host) } : {},
settingsWriteQueue: this.#settingsWriteQueue
});
this.#rememberedDestinationReconcileActor = createRememberedDestinationReconcileActor({
service: this.#quickMovePersistenceService,
notify: (message) => {
this.notify(message);
}
});
this.#rememberedDestinationReconcileActor.start();
this.#promptInteractionService = new SidepanelPromptInteractionService({
getOwnerDocument: () => this.#contentRoot?.ownerDocument ?? null,
notify: (message) => {
this.notify(message);
},
suppressKeyboardAfterPrompt: () => {
this.suppressKeyboardAfterPrompt();
},
setShouldAutofocusContentRoot: (value) => {
this.#focusOwnership.setShouldAutofocusContentRoot(value);
},
focusContentRoot: () => {
this.focusContentRootBestEffort();
}
});
this.#selectionActionController = new SidepanelSelectionActionController({
notify: (message) => {
this.notify(message);
},
promptService: this.#promptInteractionService,
setLastQuickMoveDestination: (destination) => {
void this.setLastQuickMoveDestination(destination);
}
});
this.#hostSelectionBridge = new SidepanelHostSelectionBridge({
host,
suppressContentFocusOut: () => {
this.suppressContentFocusOut();
},
resolveCurrentSceneBinding: () => resolveSceneBindingFromHost(this.#host)
});
this.#mountManager = new SidepanelMountManager({
host,
title: SIDEPANEL_TITLE,
notify: (message) => {
this.notify(message);
},
debugLifecycle: (message) => {
this.debugLifecycle(message);
},
onTabSwitched: () => {
this.clearInteractiveBindings();
},
onAsyncTabResolved: () => {
if (this.#latestModel) {
this.render(this.#latestModel);
}
},
onPersistedTabDetected: () => {
this.#didPersistTab = true;
},
lifecycle: {
requestRefresh: () => {
if (this.#disposed) return;
if (this.lifecycle) this.lifecycle.requestRefresh();
else this.requestRenderFromLatestModel();
},
requestDispose: () => {
this.dispose();
this.lifecycle?.requestDispose();
},
onFocus: (view) => {
this.lifecycle?.onFocus?.(view);
this.handleSidepanelFocus();
},
onWindowMigrated: (win) => {
this.attachOwnerDocumentKeyCapture(win.document);
}
}
});
this.#inlineRenameController = new SidepanelInlineRenameController({
notify: (message) => {
this.notify(message);
},
requestRenderFromLatestModel: () => {
this.requestRenderFromLatestModel();
},
setShouldAutofocusContentRoot: (value) => {
this.#focusOwnership.setShouldAutofocusContentRoot(value);
},
focusContentRoot: () => {
this.focusContentRootImmediate();
},
suppressNextContentFocusOut: () => {
this.suppressContentFocusOut();
},
getFocusedNodeId: () => this.#focusedNodeId,
getKeyboardCaptureActive: () => this.#focusOwnership.isKeyboardCaptureActive(),
debugInteraction: (message, payload) => {
this.debugInteraction(message, payload);
}
});
this.#dragDropController = new SidepanelDragDropController({
notify: (message) => {
this.notify(message);
},
requestRenderFromLatestModel: () => {
this.requestDragDropPreviewRender();
},
getLatestStructuralTree: () => {
return this.#latestModel?.tree ?? null;
},
getActiveStructuralMoveSelection: (draggedNodeId) => {
const selection = this.#latestSelectionResolution?.selection;
if (!selection?.structuralMove || resolveStructuralSelectionIssue(selection)) {
return null;
}
return selection.structuralMove.nodeIds.includes(draggedNodeId) ? selection.structuralMove : null;
}
});
this.#keyboardController = new SidepanelKeyboardShortcutController({
getKeyboardContext: () => this.#keyboardContext,
resolveKeyboardContext: (context) => this.resolveKeyboardContext(context),
getFocusedNodeId: () => this.#focusedNodeId,
setFocusedNodeIdSilently: (nodeId) => {
this.#focusedNodeId = nodeId;
},
setFocusedNode: (nodeId) => {
this.setFocusedNode(nodeId);
},
getInlineRenameNodeId: () => this.#inlineRenameController.nodeId,
beginInlineRename: (nodeId, initialValue) => {
this.beginInlineRenameFromInteraction(nodeId, initialValue);
},
commitInlineRename: (actions, nodeId) => this.#inlineRenameController.commitInlineRename(actions, nodeId),
setSelectionOverride: (elementIds) => {
this.setSelectionOverride(elementIds);
},
setSelectionOverrideWithNodes: (elementIds, nodes) => {
this.setSelectionOverrideFromNodes(elementIds, nodes);
},
setSelectionAnchorNodeId: (nodeId) => {
this.#selectionAnchorNodeId = nodeId;
},
applyResolvedRowSelection: (input) => {
this.applyResolvedRowSelectionGesture(input);
},
mirrorSelectionToHost: (elementIds) => {
this.#hostSelectionBridge.mirrorSelectionToHost(
elementIds,
this.#lastRenderedSceneBinding ?? void 0
);
},
getPageNavigationStep: () => this.resolveKeyboardPageNavigationStep(),
ensureHostViewContext: () => ensureHostViewContextState(this.#host).ok,
...this.#host.selectElementsInView ? { selectElementsInView: this.#host.selectElementsInView } : {},
moveSelectionToRoot: (actions, selection, targetFrameId) => this.#selectionActionController.moveSelectionToRoot(actions, selection, targetFrameId),
setLastQuickMoveDestinationToRoot: (targetFrameId) => {
void this.setLastQuickMoveDestination({
kind: "root",
targetFrameId
});
},
runNumberedQuickMoveDestination: (index, context) => this.runNumberedQuickMoveDestination(index, context),
runAltStructuralMove: (direction, context) => this.runAltStructuralMove(direction, context),
isTextInputTarget,
isKeyboardSuppressed: () => this.isKeyboardSuppressed(),
releaseKeyboardCapture: () => {
this.#focusOwnership.releaseKeyboardCapture();
},
confirmOutsideFocusOut: () => {
this.#focusOwnership.confirmOutsideFocusOut();
},
suppressTransientFocusOut: () => {
this.suppressContentFocusOut();
},
notify: (message) => {
this.notify(message);
},
runUiAction: (action, fallbackMessage) => {
runUiAction(action, (message) => this.notify(message), fallbackMessage);
},
requestRenderFromLatestModel: () => {
this.requestRenderFromLatestModel();
},
requestRowTreeAutofocus: () => {
this.requestRowTreeAutofocus();
},
debugInteraction: (message, payload) => {
this.debugInteraction(message, payload);
}
});
this.#lastRenderedSceneBinding = resolveSceneBindingFromHost(this.#host);
this.syncFocusOwnershipHostAuthority(this.#lastRenderedSceneBinding);
}
lifecycle;
#host;
#fallbackRenderer = new ConsoleRenderer();
#mountManager;
#keyboardController;
#inlineRenameController;
#inlineRenameDomSession = new InlineRenameDomSession();
#dragDropController;
#settingsWriteQueue;
#quickMovePersistenceService;
#rememberedDestinationReconcileActor;
#promptInteractionService;
#selectionActionController;
#hostSelectionBridge;
#focusOwnership = new SidepanelFocusOwnershipCoordinator({
focusOutSuppressionWindowMs: FOCUSOUT_SUPPRESSION_WINDOW_MS,
keyboardStickyCaptureMs: KEYBOARD_STICKY_CAPTURE_MS
});
#contentRoot = null;
#rowTreeRoot = null;
#renderedRowPreviewStateByNodeId = /* @PURE / new Map();
#lastRenderedDragDropHint = null;
#latestModel = null;
#focusedNodeId = null;
#keyboardContext = null;
#lastHandledContentKeydownEvent = null;
#didPersistTab = false;
#keyboardSuppressedUntilMs = 0;
#ownerDocumentWithKeyCapture = null;
#selectionOverrideState = null;
#selectionAnchorNodeId = null;
#latestSelectionResolution = null;
#lastSnapshotSelectionIds = [];
#pendingFocusedRowRevealNodeId = null;
#lastRenderedSceneBinding = null;
#preserveSidepanelFocusForCurrentHostViewChange = false;
#disposed = false;
#rowFilterQuery = "";
#showQuickMoveShortcutHints = false;
#shouldAutofocusRowFilterInput = false;
#cachedRowFilterResult = null;
#cachedQuickMoveDestinationProjection = null;
#rowDomIdPrefix = lmx-row-${++nextSidepanelRendererInstanceId};
#contentKeydownHandler = (event) => {
traceKeyboardEventIfRelevant("renderer:content-keydown", event, {
keyboardRoutingActive: this.#focusOwnership.isKeyboardRoutingActive(),
keyboardCaptureActive: this.#focusOwnership.isKeyboardCaptureActive(),
focusedNodeId: this.#focusedNodeId
});
this.updateQuickMoveShortcutHintVisibilityFromKeydown(event);
this.#lastHandledContentKeydownEvent = event;
this.#focusOwnership.activateKeyboardCapture();
this.#keyboardController.handleContentKeydown(event);
};
#documentKeydownHandler = (event) => {
traceKeyboardEventIfRelevant("renderer:document-keydown", event, {
keyboardRoutingActive: this.#focusOwnership.isKeyboardRoutingActive(),
keyboardCaptureActive: this.#focusOwnership.isKeyboardCaptureActive(),
focusedNodeId: this.#focusedNodeId,
sameAsLastContentEvent: event === this.#lastHandledContentKeydownEvent,
documentReroutableAltMovement: isDocumentReroutableAltMovementShortcut(event)
});
if (event === this.#lastHandledContentKeydownEvent) {
this.#lastHandledContentKeydownEvent = null;
return;
}
if (!this.#focusOwnership.isKeyboardRoutingActive()) {
return;
}
const contentRoot = this.#contentRoot;
if (!contentRoot) {
return;
}
const eventTarget = event.target;
const hasNodeType = !!eventTarget && typeof eventTarget === "object" && eventTarget.nodeType !== void 0;
if (hasNodeType && contentRoot.contains(eventTarget)) {
return;
}
if (isTextInputTarget(eventTarget) || !isDocumentRoutingContinuationKey(event)) {
this.#focusOwnership.confirmOutsideFocusOut();
return;
}
if (event.altKey) {
traceKeyboardEventIfRelevant("renderer:document-keydown-reroute", event, {
focusedNodeId: this.#focusedNodeId
});
}
this.focusContentRootImmediate();
this.#focusOwnership.activateKeyboardCapture();
this.#keyboardController.handleContentKeydown(event);
};
#documentKeypressHandler = (event) => {
traceKeyboardEventIfRelevant("renderer:document-keypress", event, {
keyboardRoutingActive: this.#focusOwnership.isKeyboardRoutingActive(),
keyboardCaptureActive: this.#focusOwnership.isKeyboardCaptureActive(),
focusedNodeId: this.#focusedNodeId
});
if (!this.#focusOwnership.isKeyboardRoutingActive()) {
return;
}
if (isTextInputTarget(event.target) || !shouldClaimDocumentSpaceLikeEvent(event)) {
return;
}
claimHandledKeyboardEvent2(event);
};
#documentKeyupHandler = (event) => {
traceKeyboardEventIfRelevant("renderer:document-keyup", event, {
keyboardRoutingActive: this.#focusOwnership.isKeyboardRoutingActive(),
keyboardCaptureActive: this.#focusOwnership.isKeyboardCaptureActive(),
focusedNodeId: this.#focusedNodeId
});
this.updateQuickMoveShortcutHintVisibilityFromKeyup(event);
if (!this.#focusOwnership.isKeyboardRoutingActive()) {
return;
}
if (isTextInputTarget(event.target) || !shouldClaimDocumentSpaceLikeEvent(event)) {
return;
}
claimHandledKeyboardEvent2(event);
};
#contentFocusOutHandler = (event) => {
this.setQuickMoveShortcutHintsVisible(false);
if (this.#focusOwnership.isFocusOutSuppressed()) {
this.debugInteraction("content focusout suppressed");
return;
}
this.#focusOwnership.handleContentFocusOut({
contentRoot: this.#contentRoot,
relatedTarget: event.relatedTarget,
isContentRootCurrent: (contentRoot) => this.#contentRoot === contentRoot,
onConfirmedFocusOut: () => {
this.#keyboardController.handleContentFocusOut(event, this.#contentRoot);
}
});
};
#contentFocusInHandler = () => {
this.#focusOwnership.cancelPendingFocusOut();
this.#focusOwnership.activateKeyboardCapture();
this.debugInteraction("content focusin", {
keyboardCaptureActive: this.#focusOwnership.isKeyboardCaptureActive(),
focusedNodeId: this.#focusedNodeId
});
};
#contentPointerDownHandler = () => {
this.#focusOwnership.cancelPendingFocusOut();
this.#focusOwnership.activateKeyboardCapture();
this.debugInteraction("content pointerdown", {
keyboardCaptureActive: this.#focusOwnership.isKeyboardCaptureActive(),
focusedNodeId: this.#focusedNodeId
});
};
render(model) {
if (this.#disposed) return;
this.#latestModel = model;
const renameRender = this.#inlineRenameDomSession.beforeRender(
this.#host,
this.#inlineRenameController.nodeId,
model.tree,
this.#contentRoot
);
if (renameRender.discard) this.#inlineRenameController.clear();
else if (renameRender.focusedDraft !== null) {
this.#inlineRenameController.updateInlineRenameDraft(renameRender.focusedDraft);
this.cancelDeferredFocusRestore();
this.#focusOwnership.setShouldAutofocusContentRoot(false);
}
const sceneBinding = resolveSceneBindingFromHost(this.#host);
const hostViewContext = describeHostViewContext(this.#host);
this.syncFocusOwnershipHostAuthority(sceneBinding);
this.reconcileHostViewContextBeforeRender(sceneBinding);
this.#lastRenderedSceneBinding = sceneBinding;
if (sceneBinding.state !== "live") {
this.renderInactiveHostState(hostViewContext, model);
return;
}
const liveRenderRoot = this.beginLiveRender();
if (!liveRenderRoot) {
this.#fallbackRenderer.render(model);
return;
}
const liveRenderState = this.prepareLiveRenderState(model, liveRenderRoot);
this.updateKeyboardContextFromRender(model, liveRenderState);
this.renderLivePanelChrome(liveRenderRoot, model.actions, liveRenderState);
this.renderLiveRows(liveRenderRoot, model.actions, liveRenderState);
this.finalizeLiveRender(liveRenderRoot.contentRoot);
this.#inlineRenameDomSession.restoreFocus();
}
beginLiveRender() {
const contentRoot = this.ensureContentRoot();
if (!contentRoot) {
return null;
}
const ownerDocument = contentRoot.ownerDocument;
const activeElementBeforeRender = ownerDocument.activeElement;
const previousRowTreeRoot = this.#rowTreeRoot;
const shouldRestoreRowTreeFocus = !!(activeElementBeforeRender && previousRowTreeRoot && (activeElementBeforeRender === previousRowTreeRoot || previousRowTreeRoot.contains(activeElementBeforeRender)));
this.#quickMovePersistenceService.loadFromSettingsOnce();
if (shouldRestoreRowTreeFocus && !this.#inlineRenameDomSession.restoringFocus) {
this.requestRowTreeAutofocus();
}
contentRoot.innerHTML = "";
this.#rowTreeRoot = null;
this.clearRenderedRowPreviewState();
return {
contentRoot,
ownerDocument
};
}
prepareLiveRenderState(model, liveRenderRoot) {
const { contentRoot, ownerDocument } = liveRenderRoot;
const structuralTree = model.tree;
const selectedElementIds = this.resolveSelectedElementIds(model.selectedIds);
const selectionResolution = this.resolveSelection(structuralTree, selectedElementIds);
this.#latestSelectionResolution = selectionResolution;
const resolvedSelection = selectionResolution.selection;
const currentSelectedNodes = resolveCurrentSidepanelSelectionNodes(selectionResolution);
const selectedNodeIds = new Set(currentSelectedNodes.map((node) => node.id));
this.reconcileSelectionAnchor(currentSelectedNodes);
const rowFilter = this.getRowFilterResult(structuralTree);
const destinationProjection = this.getQuickMoveDestinationProjection(structuralTree);
this.scheduleRememberedDestinationReconciliation(destinationProjection);
const visibleRowTree = rowFilter.visibleTree;
const { visibleNodes, parentById } = collectVisibleNodeContext(visibleRowTree);
const visibleNodeIds = new Set(visibleNodes.map((node) => node.id));
const activeElement = ownerDocument.activeElement;
const hasKeyboardOwnership = this.resolveHasKeyboardOwnership(contentRoot, activeElement);
if (hasKeyboardOwnership) {
this.activateKeyboardCapture();
}
this.reconcileFocusedNodeForVisibleRows(visibleNodes, hasKeyboardOwnership);
this.logRenderOwnership({
activeElement,
hasKeyboardOwnership,
model,
rowFilter,
selectedElementCount: selectedElementIds.length,
visibleNodeCount: visibleNodes.length
});
return {
destinationProjection,
currentSelectedNodes,
hasKeyboardOwnership,
parentById,
resolvedSelection,
rowFilter,
selectedElementIds,
selectedNodeIds,
selectionResolution,
visibleNodeIds,
visibleNodes,
visibleRowTree
};
}
resolveHasKeyboardOwnership(contentRoot, activeElement) {
return this.#focusOwnership.shouldAutofocusContentRoot || !!(activeElement && contentRoot.contains(activeElement));
}
reconcileFocusedNodeForVisibleRows(visibleNodes, hasKeyboardOwnership) {
const focusedNodeIdBeforeVisibleReconcile = this.#focusedNodeId;
if (visibleNodes.length === 0) {
this.#focusedNodeId = null;
} else if (this.#focusedNodeId && !visibleNodes.some((node) => node.id === this.#focusedNodeId)) {
this.#focusedNodeId = hasKeyboardOwnership ? visibleNodes[0]?.id ?? null : null;
} else if (!this.#focusedNodeId && hasKeyboardOwnership) {
this.#focusedNodeId = visibleNodes[0]?.id ?? null;
}
if (hasKeyboardOwnership && this.#focusedNodeId && this.#focusedNodeId !== focusedNodeIdBeforeVisibleReconcile) {
this.requestFocusedRowReveal(this.#focusedNodeId);
}
}
logRenderOwnership(input) {
const activeTagName = input.activeElement && typeof input.activeElement === "object" && "tagName" in input.activeElement ? ${input.activeElement.tagName ?? ""} : null;
this.debugInteraction("render ownership", {
sceneVersion: input.model.sceneVersion,
hasKeyboardOwnership: input.hasKeyboardOwnership,
keyboardCaptureActive: this.#focusOwnership.isKeyboardCaptureActive(),
shouldAutofocusContentRoot: this.#focusOwnership.shouldAutofocusContentRoot,
focusedNodeId: this.#focusedNodeId,
activeTagName,
visibleNodeCount: input.visibleNodeCount,
selectedElementCount: input.selectedElementCount,
filterActive: input.rowFilter.active,
filterQuery: input.rowFilter.query
});
}
updateKeyboardContextFromRender(model, liveRenderState) {
if (!model.actions) {
this.#keyboardContext = null;
return;
}
const nodeById = / @PURE / new Map();
for (const node of liveRenderState.visibleNodes) {
nodeById.set(node.id, node);
}
this.#keyboardContext = {
actions: model.actions,
selection: liveRenderState.resolvedSelection,
explicitSelectedNodes: liveRenderState.selectionResolution.explicitSelectedNodes,
anchorNodeId: this.#selectionAnchorNodeId,
visibleNodes: liveRenderState.visibleNodes,
nodeById,
parentById: liveRenderState.parentById
};
}
renderLivePanelChrome(liveRenderRoot, actions, liveRenderState) {
const { contentRoot, ownerDocument } = liveRenderRoot;
this.renderLiveStatusHeader(contentRoot, ownerDocument, this.#latestModel?.sceneVersion ?? 0);
this.renderRowFilterControls(contentRoot, ownerDocument, liveRenderState.rowFilter);
const toolbar = this.renderLiveToolbar(contentRoot, ownerDocument, actions, liveRenderState);
if (!actions) {
toolbar.style.background = "";
}
this.renderLiveQuickMove(contentRoot, ownerDocument, actions, liveRenderState);
}
renderLiveStatusHeader(container, ownerDocument, sceneVersion) {
const header = ownerDocument.createElement("div");
header.style.display = "flex";
header.style.alignItems = "center";
header.style.justifyContent = "space-between";
header.style.gap = "8px";
header.style.marginBottom = "6px";
const title = ownerDocument.createElement("div");
title.style.fontWeight = "600";
title.textContent = Layer Manager · v${sceneVersion};
header.appendChild(title);
header.appendChild(this.createKeyboardHelpButton(ownerDocument));
container.appendChild(header);
}
renderLiveToolbar(container, ownerDocument, actions, liveRenderState) {
return renderSidepanelToolbar({
container,
ownerDocument,
hasActions: !!actions,
selectedElementCount: liveRenderState.resolvedSelection.elementIds.length,
reviewScopeActive: liveRenderState.rowFilter.active,
ungroupLikeIssue: resolveStructuralSelectionIssue(liveRenderState.resolvedSelection),
canPersistTab: !!this.#host.persistSidepanelTab,
didPersistTab: this.#didPersistTab,
canCloseTab: this.#mountManager.mountCapabilities?.canClose ?? (!!this.#host.closeSidepanelTab || !!this.#host.sidepanelTab?.close),
canPersistLastMovePreference: this.#quickMovePersistenceService.canPersistSettings,
persistLastMoveAcrossRestarts: this.#quickMovePersistenceService.persistLastMoveAcrossRestarts,
createToolbarButton: (nextOwnerDocument, label, action) => this.createToolbarButton(nextOwnerDocument, label, action),
createToolbarIconButton: (nextOwnerDocument, icon, action) => this.createIconActionButton(nextOwnerDocument, icon, action),
onGroupSelected: async () => {
if (!actions) {
return;
}
await this.#selectionActionController.groupSelected(
actions,
liveRenderState.resolvedSelection
);
},
onReorderSelected: async (mode) => {
if (!actions) {
return;
}
await this.#selectionActionController.reorderSelected(
actions,
liveRenderState.resolvedSelection,
mode
);
},
onUngroupLikeSelection: async () => {
if (!actions) {
return;
}
await this.#selectionActionController.ungroupLikeSelection(
actions,
liveRenderState.resolvedSelection
);
},
onTogglePersistLastMoveAcrossRestarts: async (nextPreference) => {
return await this.#quickMovePersistenceService.setPersistLastMoveAcrossRestarts(
nextPreference
);
},
onNotify: (message) => {
this.notify(message);
},
onPersistTab: () => {
const persistedTab = this.#host.persistSidepanelTab?.();
if (!persistedTab) {
return false;
}
this.#didPersistTab = true;
this.#mountManager.adoptPersistedTab(persistedTab);
return true;
},
onCloseTab: () => {
if (this.#host.closeSidepanelTab) {
this.#host.closeSidepanelTab();
} else {
this.#host.sidepanelTab?.close?.();
}
this.clearMountedOutput();
this.dispose();
this.lifecycle?.requestDispose();
}
});
}
renderLiveQuickMove(container, ownerDocument, actions, liveRenderState) {
renderSidepanelQuickMove({
container,
ownerDocument,
hasActions: !!actions,
selection: liveRenderState.resolvedSelection,
reviewScope: {
active: liveRenderState.rowFilter.active,
matchingRowCount: liveRenderState.rowFilter.matchingRowCount,
contextRowCount: liveRenderState.rowFilter.contextRowCount
},
destinationProjection: liveRenderState.destinationProjection,
lastQuickMoveDestination: this.#quickMovePersistenceService.lastQuickMoveDestination,
recentQuickMoveDestinations: this.#quickMovePersistenceService.recentQuickMoveDestinations,
quickPresetInlineMax: QUICK_PRESET_INLINE_MAX,
lastMoveLabelMax: LAST_MOVE_LABEL_MAX,
showShortcutHints: false,
createToolbarButton: (nextOwnerDocument, label, action) => this.createToolbarButton(nextOwnerDocument, label, action),
onMoveSelectionToRoot: async (targetFrameId) => {
if (!actions) {
return;
}
await this.#selectionActionController.moveSelectionToRoot(
actions,
liveRenderState.resolvedSelection,
targetFrameId
);
},
onApplyGroupPreset: async (preset) => {
if (!actions) {
return;
}
await this.#selectionActionController.applyGroupPreset(
actions,
liveRenderState.resolvedSelection,
preset
);
},
onNotify: (message) => {
this.notify(message);
}
});
}
resolveStructuralNodeLocation(targetNodeId, nodes = this.#latestModel?.tree ?? [], parentPath = [], frameId = null) {
for (const node of nodes) {
const nodeFrameId = resolveFrameRowElementId(node) ?? node.frameId ?? frameId;
if (node.id === targetNodeId) {
return {
node,
parentPath: [...parentPath],
frameId: nodeFrameId
};
}
if (node.children.length === 0) {
continue;
}
const childParentPath = node.type === "group" && node.groupId ? [...parentPath, node.groupId] : parentPath;
const nestedMatch = this.resolveStructuralNodeLocation(
targetNodeId,
node.children,
childParentPath,
nodeFrameId
);
if (nestedMatch) {
return nestedMatch;
}
}
return null;
}
resolveQuickMoveShortcutTargets(selection) {
const latestStructuralTree = this.#latestModel?.tree ?? [];
const destinationProjection = this.getQuickMoveDestinationProjection(latestStructuralTree);
return resolveQuickMoveShortcutTargets({
frameResolution: selection.frameResolution,
topLevelPresets: destinationProjection.topLevelPresets,
lastQuickMoveDestination: projectQuickMoveDestination(
this.#quickMovePersistenceService.lastQuickMoveDestination,
destinationProjection.destinationByKey,
destinationProjection.liveFrameIds
),
recentQuickMoveDestinations: projectQuickMoveDestinations(
this.#quickMovePersistenceService.recentQuickMoveDestinations,
destinationProjection.destinationByKey,
destinationProjection.liveFrameIds
),
quickPresetInlineMax: QUICK_PRESET_INLINE_MAX
});
}
async rememberStructuralMoveDestination(targetParentPath, targetFrameId) {
if (targetParentPath.length === 0) {
await this.setLastQuickMoveDestination({
kind: "root",
targetFrameId
});
return;
}
await this.setLastQuickMoveDestination({
kind: "preset",
preset: {
key: makePresetKey(targetParentPath, targetFrameId),
label: makePresetOptionLabel(targetParentPath),
targetParentPath: [...targetParentPath],
targetFrameId
}
});
}
async runSelectionReparentToPath(actions, selection, targetParentPath, targetFrameId) {
if (selection.structuralMove) {
return actions.reparentFromNodeIds({
nodeIds: selection.structuralMove.nodeIds,
sourceGroupId: selection.structuralMove.sourceGroupId,
targetParentPath,
targetFrameId
});
}
return actions.commands.reparent({
elementIds: selection.elementIds,
sourceGroupId: null,
targetParentPath,
targetFrameId
});
}
async runAltStructuralMove(direction, context) {
if (direction === "in") {
if (context.selection.elementIds.length === 0) {
this.notify(
"Keyboard move into group failed: select rows first, then focus a target group."
);
return;
}
const targetGroupNodeId = this.#focusedNodeId;
if (!targetGroupNodeId) {
this.notify("Keyboard move into group failed: focus a target group row first.");
return;
}
const targetGroup = context.nodeById.get(targetGroupNodeId);
if (!targetGroup || targetGroup.type !== "group" || !targetGroup.groupId) {
this.notify("Keyboard move into group failed: focused row is not a group target.");
return;
}
if (context.selection.nodes.some((node) => node.id === targetGroupNodeId)) {
this.notify(
"Keyboard move into group failed: target group must differ from the current selection."
);
return;
}
const targetLocation = this.resolveStructuralNodeLocation(targetGroupNodeId);
if (!targetLocation) {
this.notify("Keyboard move into group failed: target group is stale.");
return;
}
const targetParentPath2 = [...targetLocation.parentPath, targetGroup.groupId];
const targetFrameId2 = targetLocation.frameId;
const outcome2 = await this.runSelectionReparentToPath(
context.actions,
context.selection,
targetParentPath2,
targetFrameId2
);
if (didInteractionApply(outcome2)) {
await this.rememberStructuralMoveDestination(targetParentPath2, targetFrameId2);
}
return;
}
if (context.selection.elementIds.length > 0) {
const selectionIssue = resolveStructuralSelectionIssue(context.selection);
if (selectionIssue) {
this.notify(Move out of group failed: ${selectionIssue});
return;
}
const sourceNode = context.selection.nodes[0] ?? null;
if (!sourceNode) {
this.notify("Move out of group failed: selected rows are unavailable.");
return;
}
const sourceLocation2 = this.resolveStructuralNodeLocation(sourceNode.id);
if (!sourceLocation2) {
this.notify("Move out of group failed: selected rows are stale.");
return;
}
if (sourceLocation2.parentPath.length === 0) {
this.notify("Move out of group failed: selection is already at the outermost level.");
return;
}
const targetParentPath2 = sourceLocation2.parentPath.slice(0, -1);
const targetFrameId2 = context.selection.frameResolution.frameId ?? sourceLocation2.frameId;
const outcome2 = await this.runSelectionReparentToPath(
context.actions,
context.selection,
targetParentPath2,
targetFrameId2
);
if (didInteractionApply(outcome2)) {
await this.rememberStructuralMoveDestination(targetParentPath2, targetFrameId2);
}
return;
}
const focusedNodeId = this.#focusedNodeId ?? context.visibleNodes[0]?.id ?? null;
if (!focusedNodeId) {
this.notify("Keyboard move out of group failed: focused row is unavailable.");
return;
}
if (!this.#focusedNodeId) {
this.#focusedNodeId = focusedNodeId;
}
const focusedNode = context.nodeById.get(focusedNodeId);
if (!focusedNode) {
this.notify("Keyboard move out of group failed: focused row is stale.");
return;
}
const structuralMove = resolveFocusedNodeStructuralMove(focusedNode);
if (!structuralMove) {
this.notify("Keyboard move out of group failed: frame rows cannot be structurally moved.");
return;
}
const sourceLocation = this.resolveStructuralNodeLocation(focusedNode.id);
if (!sourceLocation) {
this.notify("Keyboard move out of group failed: focused row is stale.");
return;
}
if (sourceLocation.parentPath.length === 0) {
this.notify(
"Keyboard move out of group failed: focused row is already at the outermost level."
);
return;
}
const targetParentPath = sourceLocation.parentPath.slice(0, -1);
const targetFrameId = focusedNode.frameId ?? sourceLocation.frameId ?? null;
const outcome = await context.actions.reparentFromNodeIds({
nodeIds: structuralMove.nodeIds,
sourceGroupId: structuralMove.sourceGroupId,
targetParentPath,
targetFrameId
});
if (didInteractionApply(outcome)) {
await this.rememberStructuralMoveDestination(targetParentPath, targetFrameId);
}
}
async runNumberedQuickMoveDestination(index, context) {
const destination = this.resolveQuickMoveShortcutTargets(context.selection).find(
(target) => target.digit === index
)?.destination;
if (!destination) {
this.notify(No move target is mapped to Alt+${index}.);
return;
}
if (context.selection.elementIds.length > 0) {
if (destination.kind === "root") {
await this.#selectionActionController.moveSelectionToRoot(
context.actions,
context.selection,
destination.targetFrameId
);
return;
}
await this.#selectionActionController.applyGroupPreset(
context.actions,
context.selection,
destination.preset
);
return;
}
const focusedNodeId = this.#focusedNodeId ?? context.visibleNodes[0]?.id ?? null;
if (!focusedNodeId) {
this.notify("Keyboard move failed: focused row is unavailable.");
return;
}
if (!this.#focusedNodeId) {
this.#focusedNodeId = focusedNodeId;
}
const focusedNode = context.nodeById.get(focusedNodeId);
if (!focusedNode) {
this.notify("Keyboard move failed: focused row is stale.");
return;
}
const structuralMove = resolveFocusedNodeStructuralMove(focusedNode);
if (!structuralMove) {
this.notify("Keyboard move failed: frame rows cannot be structurally moved.");
return;
}
if (destination.kind === "root") {
const targetFrameId = destination.targetFrameId ?? focusedNode.frameId ?? null;
const outcome2 = await context.actions.reparentFromNodeIds({
nodeIds: structuralMove.nodeIds,
sourceGroupId: structuralMove.sourceGroupId,
targetParentPath: [],
targetFrameId
});
if (didInteractionApply(outcome2)) {
await this.setLastQuickMoveDestination({
kind: "root",
targetFrameId
});
}
return;
}
if (focusedNode.frameId !== destination.preset.targetFrameId) {
this.notify("Keyboard move failed: focused row is in a different frame.");
return;
}
const outcome = await context.actions.reparentFromNodeIds({
nodeIds: structuralMove.nodeIds,
sourceGroupId: structuralMove.sourceGroupId,
targetParentPath: destination.preset.targetParentPath,
targetFrameId: destination.preset.targetFrameId
});
if (didInteractionApply(outcome)) {
await this.setLastQuickMoveDestination({
kind: "preset",
preset: destination.preset
});
}
}
renderLiveRows(liveRenderRoot, actions, liveRenderState) {
const rows = this.createRowTreeRoot(liveRenderRoot.ownerDocument);
this.#rowTreeRoot = rows;
liveRenderRoot.contentRoot.appendChild(rows);
if (liveRenderState.visibleRowTree.length === 0) {
this.renderEmptyRowTreeState(rows, liveRenderState.rowFilter);
} else {
this.renderNodes(
rows,
liveRenderState.visibleRowTree,
liveRenderState.visibleNodes,
liveRenderState.currentSelectedNodes,
0,
liveRenderState.selectedNodeIds,
actions,
{
frameId: null,
groupPath: []
},
liveRenderState.rowFilter.matchKindByNodeId
);
}
if (this.#focusedNodeId && liveRenderState.visibleNodeIds.has(this.#focusedNodeId)) {
;
rows.ariaActivedescendant = this.resolveRowDomId(this.#focusedNodeId);
}
}
createRowTreeRoot(ownerDocument) {
const rows = ownerDocument.createElement("div");
rows.style.display = "flex";
rows.style.flexDirection = "column";
rows.style.gap = "2px";
rows.tabIndex = 0;
rows.role = "tree";
rows.ariaLabel = "Layer rows";
rows.ariaMultiSelectable = "true";
return rows;
}
renderEmptyRowTreeState(rows, rowFilter) {
const emptyState = rows.ownerDocument.createElement("div");
emptyState.style.opacity = "0.75";
emptyState.style.fontSize = "11px";
emptyState.style.padding = "6px 0";
emptyState.textContent = rowFilter.active ? No rows match “${this.#rowFilterQuery.trim()}”. : "No layer rows available.";
rows.appendChild(emptyState);
}
finalizeLiveRender(contentRoot) {
const focusTargetRoot = this.getFocusTargetRoot(contentRoot);
if (focusTargetRoot) {
this.autofocusContentRootIfNeeded(focusTargetRoot);
}
this.applyQuickMoveShortcutHintVisibility(this.#showQuickMoveShortcutHints);
this.#lastRenderedDragDropHint = cloneDragDropHint(this.#dragDropController.dropHint);
this.revealFocusedRowWithinComfortBandIfNeeded();
this.scheduleDeferredFocusedRowReveal(contentRoot);
}
renderRowFilterControls(container, ownerDocument, rowFilter) {
const controls = ownerDocument.createElement("div");
controls.style.display = "flex";
controls.style.alignItems = "center";
controls.style.gap = "6px";
controls.style.marginBottom = "6px";
const searchInput = ownerDocument.createElement("input");
searchInput.type = "text";
searchInput.value = this.#rowFilterQuery;
searchInput.placeholder = "Search layer rows";
searchInput.ariaLabel = "Search layer rows";
searchInput.spellcheck = false;
searchInput.style.flex = "1";
searchInput.style.minWidth = "0";
searchInput.style.fontSize = "12px";
searchInput.style.padding = "3px 6px";
searchInput.addEventListener("click", (event) => {
event.stopPropagation();
});
searchInput.addEventListener("input", () => {
this.updateRowFilterQuery(searchInput.value, true);
});
searchInput.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
this.clearRowFilterAndFocusRows();
return;
}
event.stopPropagation();
});
controls.appendChild(searchInput);
if (rowFilter.active) {
const clearButton = this.createToolbarButton(ownerDocument, "Clear filter", async () => {
this.updateRowFilterQuery("", true);
});
controls.appendChild(clearButton);
}
container.appendChild(controls);
if (rowFilter.active) {
const reviewScopeHint = ownerDocument.createElement("div");
reviewScopeHint.style.opacity = "0.65";
reviewScopeHint.style.fontSize = "11px";
reviewScopeHint.style.marginBottom = "6px";
reviewScopeHint.textContent = "Review scope only — move and toolbar commands still act on canonical selected rows.";
container.appendChild(reviewScopeHint);
}
if (this.#shouldAutofocusRowFilterInput) {
try {
searchInput.focus();
} catch {
}
this.#shouldAutofocusRowFilterInput = false;
}
}
updateRowFilterQuery(nextQuery, shouldAutofocusInput = false) {
this.#rowFilterQuery = nextQuery;
this.#shouldAutofocusRowFilterInput = shouldAutofocusInput;
this.requestRenderFromLatestModel();
}
requestRowTreeAutofocus() {
this.#shouldAutofocusRowFilterInput = false;
this.#focusOwnership.setShouldAutofocusContentRoot(true);
}
clearRowFilterAndFocusRows() {
this.#rowFilterQuery = "";
this.requestRowTreeAutofocus();
this.requestRenderFromLatestModel();
this.focusContentRootBestEffort();
}
notify(message) {
const Notice = this.#host.obsidian?.Notice;
if (Notice) {
new Notice(message);
return;
}
console.log([LMX] ${message});
}
dispose() {
if (this.#disposed) return;
this.#disposed = true;
this.#hostSelectionBridge.invalidatePendingSelectionMirror();
if (this.#contentRoot) {
this.clearMountedOutput();
}
this.clearInteractiveBindings();
this.#settingsWriteQueue.dispose();
this.#rememberedDestinationReconcileActor.stop();
this.#promptInteractionService.dispose();
this.#inlineRenameController.dispose();
this.#mountManager.dispose();
this.#focusOwnership.dispose();
this.#latestModel = null;
}
resolveSelectedElementIds(snapshotSelectedIds, options = {}) {
const snapshotSelection = [...snapshotSelectedIds];
const selectionOverride = this.#selectionOverrideState?.elementIds ?? null;
const snapshotSelectionChanged = !haveSameIdsInSameOrder2(
snapshotSelection,
this.#lastSnapshotSelectionIds
);
if (options.trustProvidedSelection === true && snapshotSelection.length > 0 && !this.#hostSelectionBridge.hasPendingSelectionMirror()) {
this.#lastSnapshotSelectionIds = snapshotSelection;
return snapshotSelection;
}
if (snapshotSelectionChanged && snapshotSelection.length > 0 && !this.#hostSelectionBridge.hasPendingSelectionMirror()) {
const clearSelectionOverride = !!selectionOverride && !haveSameIds(selectionOverride, snapshotSelection);
if (clearSelectionOverride) {
this.#hostSelectionBridge.invalidatePendingSelectionMirror();
this.#selectionOverrideState = null;
}
this.#lastSnapshotSelectionIds = snapshotSelection;
this.debugInteraction("selection resolution", {
source: clearSelectionOverride ? "snapshotSupersedesStaleOverride" : "snapshotChangePreferred",
snapshotSize: snapshotSelection.length,
overrideSize: selectionOverride?.length ?? 0,
resolvedSize: snapshotSelection.length,
clearSelectionOverride,
...this.buildHostViewDebugPayload()
});
return snapshotSelection;
}
const hostViewEnsureResult = ensureHostViewContextState(this.#host);
const result = reconcileSelectedElementIds({
snapshotSelection,
selectionOverride,
...this.#host.getViewSelectedElements ? {
getViewSelectedElements: () => {
return this.#host.getViewSelectedElements?.() ?? [];
}
} : {},
hasSelectionBridge: !!this.#host.selectElementsInView,
hasPendingSelectionMirror: this.#hostSelectionBridge.hasPendingSelectionMirror(),
hostViewRebound: hostViewEnsureResult.rebound,
ensureHostViewContext: () => hostViewEnsureResult.ok
});
if (result.clearSelectionOverride) {
this.#hostSelectionBridge.invalidatePendingSelectionMirror();
this.#selectionOverrideState = null;
}
if (result.readErrorMessage) {
this.debugInteraction("selection read failed", {
errorMessage: result.readErrorMessage,
...this.buildHostViewDebugPayload()
});
}
this.debugInteraction("selection resolution", {
source: result.source,
snapshotSize: snapshotSelection.length,
overrideSize: selectionOverride?.length ?? 0,
resolvedSize: result.resolvedSelection.length,
clearSelectionOverride: result.clearSelectionOverride,
...this.buildHostViewDebugPayload()
});
this.#lastSnapshotSelectionIds = snapshotSelection;
return result.resolvedSelection;
}
autofocusContentRootIfNeeded(contentRoot) {
this.#focusOwnership.autofocusContentRootIfNeeded(contentRoot, isTextInputTarget);
}
async setLastQuickMoveDestination(destination) {
const persisted = await this.#quickMovePersistenceService.setLastQuickMoveDestination(destination);
if (!persisted) {
this.notify("Last move destination reverted because persistence failed.");
}
return persisted;
}
buildRememberedDestinationCandidate(destinationProjection) {
return {
lastQuickMoveDestination: projectQuickMoveDestination(
this.#quickMovePersistenceService.lastQuickMoveDestination,
destinationProjection.destinationByKey,
destinationProjection.liveFrameIds
),
recentQuickMoveDestinations: projectQuickMoveDestinations(
this.#quickMovePersistenceService.recentQuickMoveDestinations,
destinationProjection.destinationByKey,
destinationProjection.liveFrameIds
)
};
}
scheduleRememberedDestinationReconciliation(destinationProjection) {
this.#rememberedDestinationReconcileActor.send({
type: "PROJECTION_UPDATED",
candidate: this.buildRememberedDestinationCandidate(destinationProjection)
});
}
debugLifecycle(message, payload) {
traceHostContextLifecycleEvent("renderer", message, payload);
}
isInteractionDebugEnabled() {
const runtime = globalThis;
return runtime[SIDEPANEL_INTERACTION_DEBUG_FLAG] === true;
}
debugInteraction(message, payload) {
if (!this.isInteractionDebugEnabled()) {
return;
}
if (payload) {
console.log([LMX:interaction] ${message}, payload);
return;
}
console.log([LMX:interaction] ${message});
}
attachOwnerDocumentKeyCapture(ownerDocument) {
if (this.#ownerDocumentWithKeyCapture === ownerDocument) {
return;
}
this.detachOwnerDocumentKeyCapture();
const addEventListener = ownerDocument.addEventListener;
if (!addEventListener) {
return;
}
addEventListener.call(ownerDocument, "keydown", this.#documentKeydownHandler, {
capture: true
});
addEventListener.call(
ownerDocument,
"keypress",
this.#documentKeypressHandler,
{
capture: true
}
);
addEventListener.call(ownerDocument, "keyup", this.#documentKeyupHandler, {
capture: true
});
this.#ownerDocumentWithKeyCapture = ownerDocument;
}
detachOwnerDocumentKeyCapture() {
const ownerDocument = this.#ownerDocumentWithKeyCapture;
if (!ownerDocument) {
return;
}
const removeEventListener = ownerDocument.removeEventListener;
if (removeEventListener) {
removeEventListener.call(
ownerDocument,
"keydown",
this.#documentKeydownHandler,
{
capture: true
}
);
removeEventListener.call(
ownerDocument,
"keypress",
this.#documentKeypressHandler,
{
capture: true
}
);
removeEventListener.call(
ownerDocument,
"keyup",
this.#documentKeyupHandler,
{
capture: true
}
);
}
this.#ownerDocumentWithKeyCapture = null;
}
clearRenderedRowPreviewState() {
this.#renderedRowPreviewStateByNodeId.clear();
this.#lastRenderedDragDropHint = null;
}
handleSidepanelFocus() {
const sceneBinding = resolveSceneBindingFromHost(this.#host);
const hostViewContext = describeHostViewContext(this.#host);
const preserveSidepanelFocus = sceneBinding.state === "live" && !sceneBinding.shouldAttemptRebind;
this.debugLifecycle("sidepanel onFocus received", {
sceneBindingSource: sceneBinding.source,
sceneBindingState: sceneBinding.state,
sceneBindingRefreshKey: sceneBinding.refreshKey,
sceneBindingShouldAttemptRebind: sceneBinding.shouldAttemptRebind,
preserveSidepanelFocus,
activeFilePath: hostViewContext.activeFilePath,
activeLeafIdentity: hostViewContext.activeWorkspaceLeafIdentity,
activeViewType: hostViewContext.activeWorkspaceViewType,
targetViewIdentity: hostViewContext.targetViewIdentity,
targetViewFilePath: hostViewContext.targetViewFilePath,
hostEligible: hostViewContext.hostEligible
});
this.syncFocusOwnershipHostAuthority(sceneBinding);
this.runWithCurrentHostViewChangeFocusPreservation(preserveSidepanelFocus, () => {
this.requestRenderFromLatestModel();
});
}
clearInteractiveBindings() {
this.#inlineRenameDomSession.clear();
this.#contentRoot?.removeEventListener("keydown", this.#contentKeydownHandler);
this.#contentRoot?.removeEventListener("focusout", this.#contentFocusOutHandler);
this.#contentRoot?.removeEventListener("focusin", this.#contentFocusInHandler);
this.#contentRoot?.removeEventListener("pointerdown", this.#contentPointerDownHandler);
this.detachOwnerDocumentKeyCapture();
this.#contentRoot = null;
this.#rowTreeRoot = null;
this.clearRenderedRowPreviewState();
this.#keyboardContext = null;
this.#focusedNodeId = null;
this.#selectionOverrideState = null;
this.#selectionAnchorNodeId = null;
this.#latestSelectionResolution = null;
this.#lastSnapshotSelectionIds = [];
this.#lastHandledContentKeydownEvent = null;
this.#pendingFocusedRowRevealNodeId = null;
this.#showQuickMoveShortcutHints = false;
this.#cachedRowFilterResult = null;
this.#cachedQuickMoveDestinationProjection = null;
this.#focusOwnership.reset();
this.#inlineRenameController.clear();
this.#dragDropController.clear();
}
clearMountedOutput() {
this.#showQuickMoveShortcutHints = false;
const sidepanelTab = this.#host.sidepanelTab;
const contentRoot = this.#contentRoot;
const attachedRootParent = contentRoot?.parentElement;
if (contentRoot?.remove) {
contentRoot.remove();
return;
}
if (attachedRootParent) {
attachedRootParent.innerHTML = "";
return;
}
if (sidepanelTab?.contentEl) {
sidepanelTab.contentEl.innerHTML = "";
return;
}
sidepanelTab?.setContent?.("");
}
syncFocusOwnershipHostAuthority(sceneBinding = resolveSceneBindingFromHost(this.#host)) {
this.#focusOwnership.setHostDocumentAuthority(
sceneBinding.state === "live" && !sceneBinding.shouldAttemptRebind
);
}
resolveInactiveHostPresentation(hostViewContext) {
if (hostViewContext.activeWorkspaceDefinitelyInactive) {
return {
title: "Layer Manager inactive",
detail: "Active leaf is not Excalidraw.",
hint: "Focus an Excalidraw view to resume live Layer Manager interaction."
};
}
if (hostViewContext.activeFileMetadataAvailable && hostViewContext.activeFileExcalidrawCapable === false) {
return {
title: "Layer Manager inactive",
detail: "Active leaf is not Excalidraw.",
hint: "Focus an Excalidraw view to resume live Layer Manager interaction."
};
}
if (hostViewContext.targetViewMetadataAvailable && hostViewContext.targetViewExcalidrawCapable === false) {
return {
title: "Layer Manager inactive",
detail: "Bound host view is not Excalidraw.",
hint: "Focus an Excalidraw view to resume live Layer Manager interaction."
};
}
return {
title: "Layer Manager unbound",
detail: "No active Excalidraw view is currently bound.",
hint: "Focus an Excalidraw view to resume live Layer Manager interaction."
};
}
renderInactiveHostState(hostViewContext, model) {
const presentation = this.resolveInactiveHostPresentation(hostViewContext);
this.debugLifecycle("rendering inactive sidepanel state", {
title: presentation.title,
detail: presentation.detail,
activeFilePath: hostViewContext.activeFilePath,
activeLeafIdentity: hostViewContext.activeWorkspaceLeafIdentity,
activeViewType: hostViewContext.activeWorkspaceViewType,
targetViewIdentity: hostViewContext.targetViewIdentity,
targetViewFilePath: hostViewContext.targetViewFilePath,
hostEligible: hostViewContext.hostEligible
});
this.resetForInactiveHostState();
const contentRoot = this.ensureContentRoot();
if (!contentRoot) {
this.#fallbackRenderer.render({
...model,
tree: [],
selectedIds: / @PURE / new Set()
});
return;
}
const ownerDocument = contentRoot.ownerDocument;
contentRoot.innerHTML = "";
this.#rowTreeRoot = null;
const statusCard = ownerDocument.createElement("div");
statusCard.style.display = "flex";
statusCard.style.flexDirection = "column";
statusCard.style.gap = "6px";
statusCard.style.padding = "10px";
statusCard.style.border = "1px solid rgba(127, 127, 127, 0.35)";
statusCard.style.borderRadius = "8px";
statusCard.style.background = "rgba(127, 127, 127, 0.08)";
const title = ownerDocument.createElement("div");
title.textContent = presentation.title;
title.style.fontSize = "12px";
title.style.fontWeight = "600";
const detail = ownerDocument.createElement("div");
detail.textContent = presentation.detail;
detail.style.fontSize = "11px";
detail.style.lineHeight = "1.4";
const hint = ownerDocument.createElement("div");
hint.textContent = presentation.hint;
hint.style.fontSize = "11px";
hint.style.lineHeight = "1.4";
hint.style.opacity = "0.85";
statusCard.appendChild(title);
statusCard.appendChild(detail);
statusCard.appendChild(hint);
contentRoot.appendChild(statusCard);
}
ensureContentRoot() {
const mountPreparation = this.#mountManager.prepareMount({
resolveExistingContentRoot: () => this.#contentRoot,
onSetContentFailure: () => {
this.notify("Failed to attach Layer Manager content to sidepanel tab.");
}
});
if (this.#disposed || mountPreparation.status !== "ready") {
return null;
}
const { mountStrategy, ownerDocument } = mountPreparation;
if (!this.#contentRoot || this.#contentRoot.ownerDocument !== ownerDocument) {
this.#contentRoot?.removeEventListener("keydown", this.#contentKeydownHandler);
this.#contentRoot?.removeEventListener("focusout", this.#contentFocusOutHandler);
this.#contentRoot?.removeEventListener("focusin", this.#contentFocusInHandler);
this.#contentRoot?.removeEventListener("pointerdown", this.#contentPointerDownHandler);
this.#focusOwnership.cancelPendingFocusOut();
const nextContentRoot = ownerDocument.createElement("div");
nextContentRoot.id = SIDEPANEL_ROOT_ID;
nextContentRoot.style.display = "flex";
nextContentRoot.style.flexDirection = "column";
nextContentRoot.style.gap = "6px";
nextContentRoot.style.padding = "8px";
nextContentRoot.tabIndex = 0;
nextContentRoot.addEventListener("keydown", this.#contentKeydownHandler);
nextContentRoot.addEventListener("focusout", this.#contentFocusOutHandler);
nextContentRoot.addEventListener("focusin", this.#contentFocusInHandler);
nextContentRoot.addEventListener("pointerdown", this.#contentPointerDownHandler);
this.attachOwnerDocumentKeyCapture(ownerDocument);
this.#contentRoot = nextContentRoot;
this.#focusOwnership.setShouldAutofocusContentRoot(true);
}
this.attachOwnerDocumentKeyCapture(ownerDocument);
const attached = mountStrategy.attach(this.#contentRoot);
if (this.#disposed || !this.#mountManager.finalizeMountAttach(attached)) {
return null;
}
return this.#contentRoot;
}
requestRenderFromLatestModel() {
if (this.#latestModel) {
this.render(this.#latestModel);
}
}
requestDragDropPreviewRender() {
if (this.refreshRenderedDragDropPreview()) {
return;
}
this.requestRenderFromLatestModel();
}
refreshRenderedDragDropPreview() {
const rowTreeRoot = this.#rowTreeRoot;
if (!rowTreeRoot) {
return false;
}
const nextHint = cloneDragDropHint(this.#dragDropController.dropHint);
if (haveSameDragDropHint(this.#lastRenderedDragDropHint, nextHint)) {
return true;
}
if (nextHint && !this.#renderedRowPreviewStateByNodeId.has(nextHint.nodeId)) {
return false;
}
const affectedNodeIds = / @PURE */ new Set();
if (this.#lastRenderedDragDropHint) {
affectedNodeIds.add(this.#lastRenderedDragDropHint.nodeId);
}
if (nextHint) {
affectedNodeIds.add(nextHint.nodeId);
}
for (const nodeId of affectedNodeIds) {
const renderedRow = this.#renderedRowPreviewStateByNodeId.get(nodeId);
if (!renderedRow) {
continue;
}
if (!rowTreeRoot.contains(renderedRow.row)) {
return false;
}
this.updateRenderedRowPreview(renderedRow, nextHint?.nodeId === nodeId ? nextHint : null);
}
this.#lastRenderedDragDropHint = nextHint;
return true;
}
updateRenderedRowPreview(renderedRow, activeDropHint) {
const dropHintKind = resolveSidepanelRowDropHintKind(activeDropHint);
applyRenderedRowPreviewShellState(renderedRow.row, {
node: renderedRow.node,
nodeVisualState: renderedRow.nodeVisualState,
filterMatchKind: renderedRow.filterMatchKind,
selected: renderedRow.selected,
dropHintKind
});
if (!activeDropHint || !dropHintKind) {
if (renderedRow.dropHintAssistiveLabel) {
renderedRow.dropHintAssistiveLabel.textContent = "";
renderedRow.dropHintAssistiveLabel.style.display = "none";
}
if (renderedRow.dropHintIndicator) {
renderedRow.dropHintIndicator.textContent = "";
renderedRow.dropHintIndicator.style.display = "none";
}
return;
}
const assistiveLabel = renderedRow.dropHintAssistiveLabel ?? findRenderedRowDropHintAssistiveLabel(renderedRow.row) ?? this.createDropHintAssistiveLabel(renderedRow.row);
assistiveLabel.textContent = this.describeDropHint(
activeDropHint,
renderedRow.node,
this.resolveDropTargetForNode(
renderedRow.node,
renderedRow.branchContext,
renderedRow.siblingIndex
)
);
assistiveLabel.style.display = "";
renderedRow.dropHintAssistiveLabel = assistiveLabel;
const visibleIndicatorText = resolveVisibleDropHintIndicatorText(
activeDropHint,
renderedRow.node
);
if (!visibleIndicatorText) {
if (renderedRow.dropHintIndicator) {
renderedRow.dropHintIndicator.textContent = "";
renderedRow.dropHintIndicator.style.display = "none";
}
return;
}
const indicator = renderedRow.dropHintIndicator ?? this.createDropHintIndicator(renderedRow.row);
indicator.textContent = visibleIndicatorText;
indicator.style.display = "inline-flex";
renderedRow.dropHintIndicator = indicator;
}
createDropHintAssistiveLabel(row) {
const assistiveLabel = row.ownerDocument.createElement("span");
styleDropHintAssistiveLabel(assistiveLabel);
row.appendChild(assistiveLabel);
return assistiveLabel;
}
createDropHintIndicator(row) {
const indicator = row.ownerDocument.createElement("span");
styleVisibleDropHintIndicator(indicator);
row.appendChild(indicator);
return indicator;
}
resetForViewContextBoundary() {
this.#inlineRenameDomSession.clear();
this.#hostSelectionBridge.invalidatePendingSelectionMirror();
this.cancelDeferredFocusRestore();
this.#keyboardContext = null;
this.#focusedNodeId = null;
this.#selectionOverrideState = null;
this.#selectionAnchorNodeId = null;
this.#latestSelectionResolution = null;
this.#lastSnapshotSelectionIds = [];
this.#pendingFocusedRowRevealNodeId = null;
this.#showQuickMoveShortcutHints = false;
this.#rowFilterQuery = "";
this.#shouldAutofocusRowFilterInput = false;
this.#cachedRowFilterResult = null;
this.#cachedQuickMoveDestinationProjection = null;
this.#lastHandledContentKeydownEvent = null;
this.#keyboardSuppressedUntilMs = 0;
this.clearRenderedRowPreviewState();
this.#inlineRenameController.clear();
this.#dragDropController.clear();
this.#focusOwnership.reset();
}
shouldPreserveSidepanelFocusAcrossHostViewContextChange() {
if (this.#preserveSidepanelFocusForCurrentHostViewChange) {
return true;
}
const contentRoot = this.#contentRoot;
if (!contentRoot) {
return false;
}
const activeElement = contentRoot.ownerDocument.activeElement;
return !!(activeElement && contentRoot.contains(activeElement));
}
runWithCurrentHostViewChangeFocusPreservation(preserveSidepanelFocus, action) {
const previous = this.#preserveSidepanelFocusForCurrentHostViewChange;
this.#preserveSidepanelFocusForCurrentHostViewChange = preserveSidepanelFocus;
try {
return action();
} finally {
this.#preserveSidepanelFocusForCurrentHostViewChange = previous;
}
}
resetForHostViewContextChange(preserveSidepanelFocus) {
this.resetForViewContextBoundary();
if (preserveSidepanelFocus) {
this.requestRowTreeAutofocus();
return;
}
this.#focusOwnership.setShouldAutofocusContentRoot(false);
}
resetForInactiveHostState() {
this.resetForViewContextBoundary();
}
reconcileHostViewContextBeforeRender(sceneBinding) {
if (this.#lastRenderedSceneBinding === null) {
return;
}
if (this.#lastRenderedSceneBinding.refreshKey === sceneBinding.refreshKey) {
return;
}
const preserveSidepanelFocus = this.shouldPreserveSidepanelFocusAcrossHostViewContextChange();
this.resetForHostViewContextChange(preserveSidepanelFocus);
this.debugInteraction("host view context changed", {
previousSceneBindingRefreshKey: this.#lastRenderedSceneBinding.refreshKey,
nextSceneBindingRefreshKey: sceneBinding.refreshKey,
previousSceneBindingSource: this.#lastRenderedSceneBinding.source,
nextSceneBindingSource: sceneBinding.source,
previousSceneBindingState: this.#lastRenderedSceneBinding.state,
nextSceneBindingState: sceneBinding.state,
preserveSidepanelFocus,
...this.buildHostViewDebugPayload()
});
}
getRowFilterResult(structuralTree) {
const cached = this.#cachedRowFilterResult;
if (cached && cached.structuralTree === structuralTree && cached.query === this.#rowFilterQuery) {
return cached.result;
}
const result = buildSidepanelVisibleRowTreeResult(structuralTree, this.#rowFilterQuery);
this.#cachedRowFilterResult = {
structuralTree,
query: this.#rowFilterQuery,
result
};
return result;
}
getQuickMoveDestinationProjection(tree) {
const cached = this.#cachedQuickMoveDestinationProjection;
if (cached && cached.tree === tree) {
return cached.projection;
}
const projection = buildSidepanelQuickMoveDestinationProjection(
tree,
QUICK_PRESET_TOTAL_MAX,
ALL_DESTINATION_TOTAL_MAX
);
this.#cachedQuickMoveDestinationProjection = {
tree,
projection
};
return projection;
}
resolveSelection(tree, selectedElementIds) {
return resolveSidepanelSelection({
tree,
selectedElementIds,
selectionOverride: this.#selectionOverrideState
});
}
setSelectionOverrideState(selectionOverride) {
if (!selectionOverride) {
this.#hostSelectionBridge.invalidatePendingSelectionMirror();
}
this.#selectionOverrideState = selectionOverride;
if (!selectionOverride) {
this.debugInteraction("selection override cleared");
return;
}
this.debugInteraction("selection override updated", {
size: selectionOverride.elementIds.length,
nodeRefCount: selectionOverride.nodeRefs?.length ?? 0
});
}
setSelectionOverride(elementIds) {
if (!elementIds) {
this.setSelectionOverrideState(null);
return;
}
this.setSelectionOverrideState({
elementIds: [...elementIds],
nodeRefs: elementIds.length === 0 ? [] : null
});
}
setSelectionOverrideFromNodes(elementIds, nodes) {
if (elementIds.length === 0 || nodes.length === 0) {
this.setSelectionOverride(elementIds);
return;
}
const nodeRefs = nodes.map((node) => makeSidepanelSelectionNodeRef(node));
this.setSelectionOverrideState({
elementIds: [...elementIds],
nodeRefs
});
}
buildHostViewDebugPayload() {
return {
...describeHostViewContext(this.#host)
};
}
applyResolvedRowSelectionGesture(input) {
this.#selectionAnchorNodeId = input.anchorNodeId;
if (input.selectedNodes.length > 0) {
this.setSelectionOverrideFromNodes(input.selectedElementIds, input.selectedNodes);
} else {
this.setSelectionOverride([]);
}
this.debugInteraction("row selection gesture", {
source: input.source,
...resolveRowSelectionDebugSemantics(input.source),
selectedNodeIds: input.selectedNodes.map((node) => node.id),
selectedElementIds: [...input.selectedElementIds],
anchorNodeId: input.anchorNodeId,
focusedNodeId: this.#focusedNodeId,
...this.buildHostViewDebugPayload()
});
const expectedSceneBinding = input.source.startsWith("keyboard") && this.#lastRenderedSceneBinding && !canMirrorSelectionToSceneBinding(this.#lastRenderedSceneBinding) ? void 0 : this.#lastRenderedSceneBinding ?? void 0;
this.#hostSelectionBridge.mirrorSelectionToHost(input.selectedElementIds, expectedSceneBinding);
}
reconcileSelectionAnchor(selectedNodes) {
if (selectedNodes.length === 0) {
this.#selectionAnchorNodeId = null;
return;
}
if (this.#selectionOverrideState && this.#selectionAnchorNodeId) {
return;
}
if (this.#selectionAnchorNodeId && selectedNodes.some((node) => node.id === this.#selectionAnchorNodeId)) {
return;
}
if (this.#focusedNodeId && selectedNodes.some((node) => node.id === this.#focusedNodeId)) {
this.#selectionAnchorNodeId = this.#focusedNodeId;
return;
}
this.#selectionAnchorNodeId = selectedNodes.length === 1 ? selectedNodes[0]?.id ?? null : null;
}
beginInlineRename(nodeId, initialValue) {
const current = this.#inlineRenameController.state;
if (current?.nodeId !== nodeId || current.draft !== initialValue) {
this.#inlineRenameDomSession.begin(this.#host);
}
this.cancelDeferredFocusRestore();
this.#inlineRenameController.beginInlineRename(nodeId, initialValue);
}
beginInlineRenameFromInteraction(nodeId, initialValue) {
this.activateKeyboardCapture();
this.#focusedNodeId = nodeId;
this.suppressContentFocusOut();
this.focusContentRootImmediate();
this.beginInlineRename(nodeId, initialValue);
}
updateInlineRenameDraft(nextDraft) {
this.#inlineRenameController.updateInlineRenameDraft(nextDraft);
}
cancelInlineRename() {
this.#inlineRenameController.cancelInlineRename();
}
async commitInlineRename(actions, nodeId) {
await this.#inlineRenameController.commitInlineRename(actions, nodeId);
}
resolveKeyboardContext(context) {
const latestModel = this.#latestModel;
if (!latestModel) {
return context;
}
const resolvedElementIds = this.resolveSelectedElementIds(
new Set(context.selection.elementIds),
{
trustProvidedSelection: true
}
);
const selectionResolution = this.resolveSelection(latestModel.tree, resolvedElementIds);
const explicitSelectedNodeIds = (selectionResolution.explicitSelectedNodes ?? []).map(
(node) => node.id
);
const contextExplicitNodeIds = (context.explicitSelectedNodes ?? []).map((node) => node.id);
if (haveSameIdsInSameOrder2(resolvedElementIds, context.selection.elementIds) && haveSameIds(explicitSelectedNodeIds, contextExplicitNodeIds) && context.anchorNodeId === this.#selectionAnchorNodeId) {
return context;
}
return {
...context,
selection: selectionResolution.selection,
explicitSelectedNodes: selectionResolution.explicitSelectedNodes,
anchorNodeId: this.#selectionAnchorNodeId
};
}
suppressKeyboardAfterPrompt() {
this.#keyboardSuppressedUntilMs = Date.now() + KEYBOARD_PROMPT_SUPPRESSION_MS;
}
styleLiveQuickMoveShortcutBadge(label) {
label.style.position = "absolute";
label.style.top = "-5px";
label.style.right = "-5px";
label.style.display = "inline-flex";
label.style.alignItems = "center";
label.style.justifyContent = "center";
label.style.minWidth = "12px";
label.style.height = "12px";
label.style.padding = "0 2px";
label.style.borderRadius = "999px";
label.style.border = "1px solid var(--background-modifier-border, rgba(120,120,120,0.28))";
label.style.background = "var(--background-primary, rgba(24,24,24,0.95))";
label.style.color = "var(--text-muted, inherit)";
label.style.fontSize = "8px";
label.style.fontWeight = "700";
label.style.lineHeight = "1";
label.style.pointerEvents = "none";
}
collectQuickMoveShortcutButtons(root) {
if (!root) {
return [];
}
const collected = [];
const walk = (element) => {
const buttonCandidate = element;
if (element.tagName === "BUTTON" && typeof buttonCandidate.__lmxQuickMoveShortcutDigit === "number") {
collected.push(buttonCandidate);
}
for (const child of Array.from(element.children)) {
walk(child);
}
};
walk(root);
return collected;
}
findLiveQuickMoveShortcutBadge(button) {
return Array.from(button.children).find((child) => {
return child.__lmxQuickMoveShortcutBadge === true;
}) ?? null;
}
applyQuickMoveShortcutHintVisibility(visible) {
const buttons = this.collectQuickMoveShortcutButtons(this.#contentRoot);
for (const button of buttons) {
const digit = button.__lmxQuickMoveShortcutDigit;
if (typeof digit !== "number") {
continue;
}
const existingBadge = this.findLiveQuickMoveShortcutBadge(button);
if (!visible) {
existingBadge?.remove();
continue;
}
if (existingBadge) {
continue;
}
const badge = button.ownerDocument.createElement("span");
badge.__lmxQuickMoveShortcutBadge = true;
badge.textContent = ${digit};
badge.ariaHidden = "true";
this.styleLiveQuickMoveShortcutBadge(badge);
button.appendChild(badge);
}
}
setQuickMoveShortcutHintsVisible(visible) {
if (this.#showQuickMoveShortcutHints === visible) {
return;
}
this.#showQuickMoveShortcutHints = visible;
this.applyQuickMoveShortcutHintVisibility(visible);
}
updateQuickMoveShortcutHintVisibilityFromKeydown(event) {
if (event.key === "Alt" || event.altKey) {
this.setQuickMoveShortcutHintsVisible(true);
return;
}
if (this.#showQuickMoveShortcutHints) {
this.setQuickMoveShortcutHintsVisible(false);
}
}
updateQuickMoveShortcutHintVisibilityFromKeyup(event) {
if ((event.key === "Alt" || !event.altKey) && this.#showQuickMoveShortcutHints) {
this.setQuickMoveShortcutHintsVisible(false);
}
}
isKeyboardSuppressed() {
return Date.now() < this.#keyboardSuppressedUntilMs;
}
activateKeyboardCapture() {
this.#focusOwnership.activateKeyboardCapture();
}
suppressContentFocusOut() {
this.#focusOwnership.suppressTransientFocusOut();
}
getFocusTargetRoot(contentRoot = this.#contentRoot) {
if (this.#rowTreeRoot && contentRoot && contentRoot.contains(this.#rowTreeRoot)) {
return this.#rowTreeRoot;
}
return contentRoot;
}
resolveRowDomId(nodeId) {
const safeNodeId = encodeURIComponent(nodeId).replace(/%/g, "_");
return ${this.#rowDomIdPrefix}-${safeNodeId};
}
focusContentRootImmediate() {
this.#focusOwnership.focusContentRootImmediate(this.getFocusTargetRoot());
}
cancelDeferredFocusRestore() {
this.#focusOwnership.cancelDeferredFocusRestore();
}
focusContentRootBestEffort() {
this.#focusOwnership.focusContentRootBestEffort({
contentRoot: this.getFocusTargetRoot(),
isContentRootCurrent: (contentRoot) => this.getFocusTargetRoot() === contentRoot
});
}
requestFocusedRowReveal(nodeId) {
this.#pendingFocusedRowRevealNodeId = nodeId;
}
scheduleDeferredFocusedRowReveal(contentRoot) {
const focusedNodeId = this.#focusedNodeId;
if (!focusedNodeId) {
return;
}
this.requestFocusedRowReveal(focusedNodeId);
Promise.resolve().then(() => {
if (this.#contentRoot !== contentRoot || this.#focusedNodeId !== focusedNodeId) {
return;
}
this.revealFocusedRowWithinComfortBandIfNeeded();
});
}
resolveKeyboardPageNavigationStep() {
const focusTargetRoot = this.getFocusTargetRoot();
if (!focusTargetRoot) {
return 1;
}
const scrollContainer = this.resolveReviewCursorScrollContainer(focusTargetRoot) ?? focusTargetRoot;
const viewportHeight = resolveElementViewportHeight(scrollContainer);
if (viewportHeight <= 0) {
return 1;
}
return Math.max(1, Math.floor(viewportHeight / ROW_MIN_HEIGHT_PX) - 1);
}
revealFocusedRowWithinComfortBandIfNeeded() {
const pendingNodeId = this.#pendingFocusedRowRevealNodeId;
if (!pendingNodeId || !this.#focusedNodeId || pendingNodeId !== this.#focusedNodeId) {
return;
}
this.#pendingFocusedRowRevealNodeId = null;
const rowElement = this.findElementById(
this.#contentRoot,
this.resolveRowDomId(this.#focusedNodeId)
);
if (!rowElement) {
return;
}
const scrollContainer = this.resolveReviewCursorScrollContainer(rowElement);
if (!scrollContainer) {
rowElement.scrollIntoView?.({
block: "nearest"
});
return;
}
const viewportHeight = resolveElementViewportHeight(scrollContainer);
if (viewportHeight <= 0) {
rowElement.scrollIntoView?.({
block: "nearest"
});
return;
}
const rowRect = rowElement.getBoundingClientRect?.();
const containerRect = scrollContainer.getBoundingClientRect?.();
if (!rowRect || !containerRect) {
return;
}
const comfortInset = this.resolveReviewCursorComfortInset(viewportHeight);
const comfortTop = containerRect.top + comfortInset;
const comfortBottom = containerRect.bottom - comfortInset;
const currentScrollTop = resolveElementScrollTop(scrollContainer);
let nextScrollTop = currentScrollTop;
if (rowRect.top < comfortTop) {
nextScrollTop -= comfortTop - rowRect.top;
} else if (rowRect.bottom > comfortBottom) {
nextScrollTop += rowRect.bottom - comfortBottom;
}
const maxScrollTop = Math.max(0, resolveElementScrollHeight(scrollContainer) - viewportHeight);
const clampedScrollTop = Math.max(0, Math.min(maxScrollTop, nextScrollTop));
if (Math.abs(clampedScrollTop - currentScrollTop) < 1) {
return;
}
;
scrollContainer.scrollTop = clampedScrollTop;
}
resolveReviewCursorComfortInset(viewportHeight) {
const desiredInset = Math.max(
ROW_MIN_HEIGHT_PX * REVIEW_CURSOR_COMFORT_MIN_MARGIN_ROWS,
Math.floor(viewportHeight * REVIEW_CURSOR_COMFORT_VIEWPORT_RATIO)
);
const maxInset = Math.floor(viewportHeight * REVIEW_CURSOR_COMFORT_MAX_VIEWPORT_RATIO);
return Math.max(0, Math.min(desiredInset, maxInset));
}
resolveReviewCursorScrollContainer(start) {
let current = start;
while (current) {
const viewportHeight = resolveElementViewportHeight(current);
const scrollHeight = resolveElementScrollHeight(current);
if (viewportHeight > 0 && scrollHeight > viewportHeight + 1) {
return current;
}
current = current.parentElement;
}
return null;
}
findElementById(root, targetId) {
if (!root) {
return null;
}
if (root.id === targetId) {
return root;
}
const childElements = Array.from(root.children ?? []);
for (const child of childElements) {
const match = this.findElementById(child, targetId);
if (match) {
return match;
}
}
return null;
}
setFocusedNode(nodeId) {
if (nodeId === this.#focusedNodeId) {
return;
}
this.#focusedNodeId = nodeId;
this.requestFocusedRowReveal(nodeId);
this.requestRowTreeAutofocus();
this.requestRenderFromLatestModel();
}
resolveRowDragDropIntentOptions(row, node, event) {
if (node.type !== "group") {
return void 0;
}
const clientY = event.clientY;
if (typeof clientY !== "number" || !Number.isFinite(clientY)) {
return void 0;
}
const rowRect = row.getBoundingClientRect?.();
if (!rowRect || !Number.isFinite(rowRect.top) || !Number.isFinite(rowRect.height)) {
return void 0;
}
const rowHeight = rowRect.height;
if (rowHeight <= 0) {
return void 0;
}
const offsetY = clientY - rowRect.top;
if (!Number.isFinite(offsetY)) {
return void 0;
}
const edgeZoneHeight = Math.min(
Math.max(rowHeight * GROUP_ROW_DROP_EDGE_RATIO, GROUP_ROW_DROP_EDGE_MIN_PX),
rowHeight / 2
);
if (offsetY <= edgeZoneHeight) {
return {
zone: "before"
};
}
if (offsetY >= rowHeight - edgeZoneHeight) {
return {
zone: "after"
};
}
return {
zone: "inside"
};
}
resolveNodeFrameId(node, branchContext) {
return this.#dragDropController.resolveNodeFrameId(node, branchContext);
}
resolveDropTargetForNode(node, branchContext, siblingIndex) {
return this.#dragDropController.resolveDropTargetForNode(node, branchContext, siblingIndex);
}
describeDropHint(preview, node, dropTarget) {
if (preview.kind === "reorder") {
return preview.placement === "before" ? "reorder before row" : "reorder after row";
}
if (node.type === "group") {
return "drop into group";
}
if (node.type === "frame") {
return "drop into frame";
}
if (dropTarget.targetParentPath.length > 0) {
return "drop into parent group";
}
if (dropTarget.targetFrameId) {
return "drop to frame root";
}
return "drop to root";
}
applyDragDropDestination(destination) {
if (destination.kind === "root") {
void this.setLastQuickMoveDestination({
kind: "root",
targetFrameId: destination.targetFrameId
});
return;
}
const latestStructuralTree = this.#latestModel?.tree ?? [];
const destinationProjection = this.getQuickMoveDestinationProjection(latestStructuralTree);
const projectedPreset = resolveProjectedQuickMovePreset(
destination.targetParentPath,
destination.targetFrameId,
destinationProjection.destinationByKey
);
void this.setLastQuickMoveDestination({
kind: "preset",
preset: projectedPreset ?? {
key: makePresetKey(destination.targetParentPath, destination.targetFrameId),
label: makePresetOptionLabel(destination.targetParentPath),
targetParentPath: [...destination.targetParentPath],
targetFrameId: destination.targetFrameId
}
});
}
async runDragDropMove(actions, targetNodeId, dropTarget, options) {
const outcome = await this.#dragDropController.runDragDropMove(
actions,
targetNodeId,
dropTarget,
options
);
if (outcome.status !== "applied") {
return;
}
if (outcome.effect.kind === "reparent") {
this.applyDragDropDestination(outcome.effect.destination);
}
}
async handleRowDrop(actions, targetNodeId, dropTarget, options) {
try {
await this.runDragDropMove(actions, targetNodeId, dropTarget, options);
} catch (error) {
if (error instanceof Error) {
this.notify(Drag and drop move failed: ${error.message});
} else {
this.notify("Drag and drop move failed");
}
} finally {
this.#dragDropController.resetDragState();
this.requestRowTreeAutofocus();
this.focusContentRootBestEffort();
}
}
renderNodes(container, nodes, visibleNodes, currentSelectedNodes, depth, selectedNodeIds, actions, branchContext, matchKindByNodeId) {
const ownerDocument = container.ownerDocument;
renderSidepanelRowTree({
nodes,
depth,
branchContext,
resolveNodeFrameId: (node, nodeBranchContext) => this.resolveNodeFrameId(node, nodeBranchContext),
visitNode: ({
node,
depth: nodeDepth,
branchContext: nodeBranchContext,
siblingIndex,
nodeFrameId
}) => {
const nodeDropTarget = this.resolveDropTargetForNode(node, nodeBranchContext, siblingIndex);
const activeDropHint = this.#dragDropController.dropHint?.nodeId === node.id ? this.#dragDropController.dropHint : null;
const currentInlineRenameState = this.#inlineRenameController.state;
const renameGeneration = this.#inlineRenameDomSession.generation;
const canHandleRename = () => !this.#disposed && this.#inlineRenameDomSession.owns(renameGeneration, this.#host) && !!this.#contentRoot?.contains(row);
const inlineRenameState = currentInlineRenameState?.nodeId === node.id ? currentInlineRenameState : null;
const selected = selectedNodeIds.has(node.id);
const focused = this.#focusedNodeId === node.id;
const filterMatchKind = matchKindByNodeId.get(node.id) ?? "none";
const nodeVisualState = resolveSidepanelRowVisualState(
node,
this.#latestModel?.elementStateById
);
const dropHintKind = resolveSidepanelRowDropHintKind(activeDropHint);
const { row, renameInputForAutofocus } = renderSidepanelRow({
ownerDocument,
rowDomId: this.resolveRowDomId(node.id),
node,
depth: nodeDepth,
selected,
focused,
dropHintKind,
dropHintLabel: activeDropHint ? this.describeDropHint(activeDropHint, node, nodeDropTarget) : null,
actions,
styleConfig: ROW_STYLE_CONFIG,
nodeVisualState,
filterMatchKind,
inlineRenameState,
onToggleExpanded: (targetNodeId) => {
actions?.toggleExpanded(targetNodeId);
},
onInlineRenameDraftChange: (nextDraft) => {
if (canHandleRename()) this.updateInlineRenameDraft(nextDraft);
},
onInlineRenameCommit: (targetNodeId) => {
if (!actions || !canHandleRename()) {
return;
}
runUiAction(
() => this.commitInlineRename(actions, targetNodeId),
(message) => this.notify(message),
"Rename failed"
);
},
onInlineRenameCancel: () => {
if (canHandleRename()) this.cancelInlineRename();
},
isInlineRenameActiveForNode: (targetNodeId) => canHandleRename() && this.#inlineRenameController.nodeId === targetNodeId,
onRenameNodeFromAction: (targetNodeId, initialValue) => {
this.beginInlineRenameFromInteraction(targetNodeId, initialValue);
},
createIconActionButton: (nextOwnerDocument, icon, action) => this.createIconActionButton(nextOwnerDocument, icon, action)
});
const renderedRowPreviewState = {
row,
node,
branchContext: nodeBranchContext,
siblingIndex,
selected,
filterMatchKind,
nodeVisualState,
dropHintAssistiveLabel: findRenderedRowDropHintAssistiveLabel(row),
dropHintIndicator: null
};
this.#renderedRowPreviewStateByNodeId.set(node.id, renderedRowPreviewState);
if (activeDropHint) {
this.updateRenderedRowPreview(renderedRowPreviewState, activeDropHint);
}
if (actions) {
bindSidepanelRowInteractions({
row,
draggable: node.type !== "frame",
onRowClick: (event) => {
const previousFocusedNodeId = this.#focusedNodeId;
this.activateKeyboardCapture();
this.#focusedNodeId = node.id;
const nextSelection = resolveRowClickSelection({
clickedNode: node,
visibleNodes,
currentSelectedNodes,
currentAnchorNodeId: this.#selectionAnchorNodeId,
fallbackAnchorNodeId: previousFocusedNodeId,
modifiers: {
shiftKey: event.shiftKey,
toggleKey: event.ctrlKey || event.metaKey
}
});
this.applyResolvedRowSelectionGesture({
source: event.shiftKey ? "mouseRange" : event.ctrlKey || event.metaKey ? "mouseToggle" : "mouseClick",
...nextSelection
});
this.focusContentRootBestEffort();
this.requestRenderFromLatestModel();
},
onRowDoubleClick: () => {
this.beginInlineRenameFromInteraction(node.id, node.label);
},
onDragStart: (event) => {
this.#dragDropController.startRowDrag({
node,
nodeFrameId,
branchGroupPath: nodeBranchContext.groupPath,
rowScope: nodeBranchContext,
siblingIndex,
dragEvent: event
});
},
onDragEnd: () => {
this.#dragDropController.endRowDrag();
},
onDragEnter: (event) => {
this.#dragDropController.handleDragEnter(
node.id,
nodeDropTarget,
event,
this.resolveRowDragDropIntentOptions(row, node, event)
);
},
onDragOver: (event) => {
this.#dragDropController.handleDragOver(
node.id,
nodeDropTarget,
event,
this.resolveRowDragDropIntentOptions(row, node, event)
);
},
onDragLeave: (relatedTarget) => {
this.#dragDropController.handleDragLeave(
node.id,
!!(relatedTarget && row.contains(relatedTarget))
);
},
onDrop: (event) => {
void this.handleRowDrop(
actions,
node.id,
nodeDropTarget,
this.resolveRowDragDropIntentOptions(row, node, event)
);
}
});
}
container.appendChild(row);
if (renameInputForAutofocus) {
this.#inlineRenameDomSession.setInput(renameInputForAutofocus);
}
if (inlineRenameState?.shouldAutofocusInput && renameInputForAutofocus) {
try {
renameInputForAutofocus.focus();
} catch {
}
this.#inlineRenameController.markAutofocusHandled(node.id);
}
}
});
}
createIconNode(ownerDocument, iconName, fallbackLabel) {
const excalidrawLikeIcon = createExcalidrawLikeIconNode(
ownerDocument,
iconName,
fallbackLabel,
ICON_SIZE_PX
);
if (excalidrawLikeIcon) {
return excalidrawLikeIcon;
}
const iconFactory = this.#host.obsidian?.getIcon;
if (iconFactory) {
try {
const icon = iconFactory(iconName);
if (icon) {
const clone = icon.cloneNode(true);
const viewHtmlElement = ownerDocument.defaultView?.HTMLElement;
if (viewHtmlElement && clone instanceof viewHtmlElement) {
clone.style.width = ${ICON_SIZE_PX}px;
clone.style.height = ${ICON_SIZE_PX}px;
clone.style.display = "inline-block";
}
return clone;
}
} catch {
}
}
const fallback = ownerDocument.createElement("span");
fallback.textContent = fallbackLabel;
fallback.style.fontSize = ${ICON_SIZE_PX}px;
fallback.style.lineHeight = "1";
return fallback;
}
createIconActionButton(ownerDocument, icon, action) {
const button = ownerDocument.createElement("button");
button.type = "button";
button.style.minWidth = ${ICON_BUTTON_SIZE_PX}px;
button.style.minHeight = ${ICON_BUTTON_SIZE_PX}px;
button.style.display = "inline-flex";
button.style.alignItems = "center";
button.style.justifyContent = "center";
button.style.lineHeight = "1";
button.style.padding = "0";
button.style.border = "none";
button.style.borderRadius = "4px";
button.style.background = "transparent";
button.style.boxShadow = "none";
button.style.fontSize = ${TOOLBAR_FONT_SIZE_PX}px;
if (icon.title) {
button.ariaLabel = icon.title;
}
const iconNode = this.createIconNode(ownerDocument, icon.iconName, icon.fallbackLabel);
button.appendChild(iconNode);
button.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
runUiAction(action, (message) => this.notify(message), "LayerManager action failed");
});
return button;
}
createKeyboardHelpButton(ownerDocument) {
const helpGlyph = ownerDocument.createElement("span");
helpGlyph.title = SIDEPANEL_KEYBOARD_HINT_TOOLTIP;
helpGlyph.style.minWidth = ${ICON_BUTTON_SIZE_PX}px;
helpGlyph.style.minHeight = ${ICON_BUTTON_SIZE_PX}px;
helpGlyph.style.display = "inline-flex";
helpGlyph.style.alignItems = "center";
helpGlyph.style.justifyContent = "center";
helpGlyph.style.color = "var(--text-muted, inherit)";
helpGlyph.style.cursor = "help";
helpGlyph.style.userSelect = "none";
const iconNode = this.createIconNode(ownerDocument, "help-circle", "?");
helpGlyph.appendChild(iconNode);
return helpGlyph;
}
createToolbarButton(ownerDocument, label, action) {
const button = ownerDocument.createElement("button");
button.type = "button";
button.textContent = label;
button.style.fontSize = ${TOOLBAR_FONT_SIZE_PX}px;
button.style.lineHeight = "1.2";
button.style.minHeight = "20px";
button.style.padding = "2px 7px";
button.style.borderRadius = "5px";
button.style.border = "1px solid var(--background-modifier-border, rgba(120,120,120,0.18))";
button.style.background = "var(--background-primary-alt, rgba(120,120,120,0.04))";
button.style.boxShadow = "none";
button.addEventListener("click", () => {
runUiAction(action, (message) => this.notify(message), "LayerManager toolbar action failed");
});
return button;
}
};
var createExcalidrawSidepanelRenderer = (host, lifecycle) => {
if (!hasDom()) {
return null;
}
const canCreateOrReuseTab = !!host.createSidepanelTab || !!host.sidepanelTab || !!host.checkForActiveSidepanelTabForScript;
if (!canCreateOrReuseTab) {
return null;
}
const hostViewContext = describeHostViewContext(host);
if (hostViewContext.activeFileMetadataAvailable && hostViewContext.activeFileExcalidrawCapable === false || hostViewContext.targetViewMetadataAvailable && hostViewContext.targetViewExcalidrawCapable === false) {
return null;
}
return new ExcalidrawSidepanelRenderer(host, lifecycle);
};
// src/ui/sidepanel/selection/hostContextCoordinator.ts var DEFAULT_AUTO_REBIND_SIGNALS = /* @PURE */ new Set([ "manual", "leaf-change", "sidepanel-view-change", "poll" ]); var resolveSceneApi = (host, observation, state) => { if (state !== "live") { return null; } if (observation.hasExplicitTargetViewProperty) { return resolveLiveExcalidrawApiFromTargetView(observation.targetView) ?? null; } try { return host.getExcalidrawAPI?.() ?? null; } catch { return null; } }; var createSnapshot = (input) => { const { description } = input.observation; const state = resolveHostViewContextShellStateFromObservation(input.observation); const sceneBinding = resolveSceneBindingFromObservation({ observation: input.observation, state, shouldAttemptRebind: input.shouldAttemptRebind }); return { bindingKey: sceneBinding.sceneKey, sceneRef: sceneBinding.sceneRef, sceneBinding, state, activeFilePath: description.activeFilePath, activeLeafIdentity: description.activeWorkspaceLeafIdentity, activeViewType: description.activeWorkspaceViewType, targetViewIdentity: description.targetViewIdentity, targetViewFilePath: description.targetViewFilePath, targetViewUsable: description.targetViewUsable, hasExplicitTargetViewProperty: input.observation.hasExplicitTargetViewProperty, hostEligible: description.hostEligible, shouldAttemptRebind: input.shouldAttemptRebind, canOwnKeyboardRouting: description.hostEligible, sceneApi: resolveSceneApi(input.host, input.observation, state), currentTargetView: input.observation.targetView, hasCachedTargetView: input.cachedTargetView !== null, cachedTargetViewIdentity: resolveTargetViewIdentity(input.cachedTargetView), signal: input.signal }; }; var haveEquivalentSnapshots = (left, right) => { if (!left) { return false; } return left.sceneBinding.refreshKey === right.sceneBinding.refreshKey && left.currentTargetView === right.currentTargetView && (!right.hasExplicitTargetViewProperty || left.sceneApi === right.sceneApi) && left.targetViewIdentity === right.targetViewIdentity && left.targetViewUsable === right.targetViewUsable && left.hostEligible === right.hostEligible && left.hasCachedTargetView === right.hasCachedTargetView && left.cachedTargetViewIdentity === right.cachedTargetViewIdentity; }; var buildRepeatedFailedRebindSuppressionKey = (input) => { const { description } = input.observation; return [ description.activeFilePath ?? "none", description.activeWorkspaceLeafIdentity ?? "none", description.activeWorkspaceViewType ?? "none", description.targetViewIdentity ?? "none", description.targetViewFilePath ?? "none", description.targetViewUsable ? "usable:yes" : "usable:no", input.cachedTargetViewIdentity ?? "cached:none" ].join("::"); }; var SidepanelHostContextCoordinator = class { #host; #autoRebindSignals; #cachedTargetView = null; #snapshot = null; #lastFailedRebindDebugKey = null; #lastRepeatedFailedRebindSuppressionKey = null; constructor(host, options = {}) { this.#host = host; this.#autoRebindSignals = new Set(options.autoRebindSignals ?? DEFAULT_AUTO_REBIND_SIGNALS); this.#snapshot = this.#reconcile("initial", false).snapshot; } getSnapshot() { return this.#snapshot ?? this.#reconcile("initial", false).snapshot; } getCachedTargetView() { return this.#cachedTargetView; } primeCachedTargetView(targetView) { this.rememberUsableTargetView(targetView); } reconcile(signal = "manual") { return this.#reconcile(signal, this.#autoRebindSignals.has(signal)); } handleWorkspaceLeafChange() { return this.reconcile("leaf-change"); } handleSidepanelViewChange(targetView = getCurrentHostTargetView(this.#host)) { this.rememberUsableTargetView(targetView); return this.reconcile("sidepanel-view-change"); } handlePollingFallback() { return this.reconcile("poll"); } rememberUsableTargetView(targetView) { if (!isUsableTargetView2(targetView)) { return; } this.#cachedTargetView = targetView; } #reconcile(signal, attemptRebind) { let observation = observeHostViewContext(this.#host); this.rememberUsableTargetView(observation.targetView); let rebound = false; let shouldAttemptRebind = shouldRebindHostViewToActiveWorkspaceView(this.#host); const cachedTargetViewIdentityBeforeAttempt = resolveTargetViewIdentity(this.#cachedTargetView); const repeatedFailedRebindSuppressionKey = buildRepeatedFailedRebindSuppressionKey({ observation, cachedTargetViewIdentity: cachedTargetViewIdentityBeforeAttempt }); const shouldSuppressRepeatedFailedAutoRebind = attemptRebind && (signal === "manual" || signal === "poll") && this.#lastRepeatedFailedRebindSuppressionKey === repeatedFailedRebindSuppressionKey; if (attemptRebind && shouldAttemptRebind && !shouldSuppressRepeatedFailedAutoRebind) { const rebindResult = bindHostViewToActiveWorkspaceView(this.#host); rebound = rebindResult.rebound; observation = observeHostViewContext(this.#host); this.rememberUsableTargetView(observation.targetView); shouldAttemptRebind = shouldRebindHostViewToActiveWorkspaceView(this.#host); } const snapshot = createSnapshot({ host: this.#host, observation, cachedTargetView: this.#cachedTargetView, signal, shouldAttemptRebind }); if (attemptRebind && shouldAttemptRebind && !rebound) { this.#lastRepeatedFailedRebindSuppressionKey = repeatedFailedRebindSuppressionKey; } else if (!shouldAttemptRebind || rebound || this.#lastRepeatedFailedRebindSuppressionKey !== repeatedFailedRebindSuppressionKey) { this.#lastRepeatedFailedRebindSuppressionKey = null; } const changed = !haveEquivalentSnapshots(this.#snapshot, snapshot); if (attemptRebind && !rebound && shouldAttemptRebind) { const failedRebindDebugKey = [ signal, snapshot.state, snapshot.activeFilePath ?? "none", snapshot.activeLeafIdentity ?? "none", snapshot.activeViewType ?? "none", snapshot.targetViewIdentity ?? "none", snapshot.targetViewFilePath ?? "none", snapshot.cachedTargetViewIdentity ?? "none" ].join("::"); if (this.#lastFailedRebindDebugKey !== failedRebindDebugKey) { traceHostContextLifecycleEvent( "decision", "host context rebind attempt did not confirm a usable targetView", { signal, state: snapshot.state, activeFilePath: snapshot.activeFilePath, activeLeafIdentity: snapshot.activeLeafIdentity, activeViewType: snapshot.activeViewType, targetViewIdentity: snapshot.targetViewIdentity, targetViewFilePath: snapshot.targetViewFilePath, targetViewUsable: snapshot.targetViewUsable, hasSetView: observation.description.hasSetView, shouldAttemptRebind: snapshot.shouldAttemptRebind, cachedTargetViewIdentity: snapshot.cachedTargetViewIdentity } ); this.#lastFailedRebindDebugKey = failedRebindDebugKey; } } else { this.#lastFailedRebindDebugKey = null; } this.#snapshot = snapshot; return { snapshot, changed, rebound }; } }; var createSidepanelHostContextCoordinator = (host, options) => { return new SidepanelHostContextCoordinator(host, options); };
// src/main.ts
var readSelectedIdsFromAppState = (appState) => {
if (!appState || typeof appState !== "object") {
return null;
}
const selectedElementIdsCandidate = appState["selectedElementIds"];
if (!selectedElementIdsCandidate) {
return null;
}
if (Array.isArray(selectedElementIdsCandidate)) {
return new Set(
selectedElementIdsCandidate.filter((entry) => typeof entry === "string")
);
}
if (selectedElementIdsCandidate instanceof Set) {
return new Set(
[...selectedElementIdsCandidate].filter(
(entry) => typeof entry === "string"
)
);
}
if (typeof selectedElementIdsCandidate !== "object") {
return null;
}
const selectedById = selectedElementIdsCandidate;
const ids = Object.keys(selectedById).filter((id) => selectedById[id] === true);
return new Set(ids);
};
var toSceneChangeUnsubscribe = (value) => {
return typeof value === "function" ? value : null;
};
var WORKSPACE_ACTIVE_FILE_POLL_MS = 350;
var READINESS_BACKOFF_MS = 2e3;
var toAppCandidate2 = (candidate) => {
return candidate && typeof candidate === "object" ? candidate : null;
};
var hasWorkspaceSurface2 = (candidate) => {
return !!candidate?.workspace && typeof candidate.workspace === "object";
};
var resolveRuntimeApp = (ea2) => {
const targetViewApp = toAppCandidate2(
ea2.targetView && typeof ea2.targetView === "object" ? ea2.targetView["app"] : null
);
const canonicalCandidates = [
ea2.app,
ea2.obsidian?.app,
globalThis["app"],
globalThis.window?.app,
globalThis.obsidian?.app
].map(toAppCandidate2);
for (const candidate of canonicalCandidates) {
if (hasWorkspaceSurface2(candidate)) {
return candidate;
}
}
if (hasWorkspaceSurface2(targetViewApp)) {
return targetViewApp;
}
for (const candidate of canonicalCandidates) {
if (candidate) {
return candidate;
}
}
return targetViewApp;
};
var createLayerManagerRuntime = (ea2, providedRenderer) => {
const runtimeApp = resolveRuntimeApp(ea2);
const hostContextCoordinator = createSidepanelHostContextCoordinator(ea2);
let hostContextSnapshot = hostContextCoordinator.getSnapshot();
let snapshot = readSnapshot(ea2);
let renderLatestSnapshot = () => {
};
let disposed = false;
let initialized = false;
let lifecycleFailure = null;
let readinessTimer = null;
let readinessAttempts = 0;
let hostFocusReleased = false;
let releasedContext = null;
let recoveryTimer = null;
let recoveryAttempts = 0;
let hostAuthorityEpoch = 0;
let sceneSubscriptionGeneration = 0;
let runtime = null;
const renderer = providedRenderer ?? createExcalidrawSidepanelRenderer(ea2, {
requestRefresh: () => refresh(),
requestDispose: () => dispose(),
onFocus: (view) => {
if (disposed) return;
const bindingChanged = hostContextSnapshot.currentTargetView !== view;
clearPendingReadiness();
clearPendingRecovery();
if (view === null && !hostFocusReleased) {
const previousView = hostContextSnapshot.currentTargetView;
releasedContext = {
view: previousView,
leaf: previousView?.leaf,
workspace: runtimeApp?.workspace,
filePath: hostContextSnapshot.targetViewFilePath
};
}
if (view !== null) releasedContext = null;
hostFocusReleased = view === null;
if (bindingChanged || hostFocusReleased) {
hostAuthorityEpoch += 1;
selectedIdsHintFromOnChange = null;
clearSceneChangeSubscription();
}
reconcileHostContext("manual");
if (hostFocusReleased) recoverReleasedView();
}
}) ?? new ConsoleRenderer();
let sceneChangeUnsubscribe = null;
let subscribedSceneChangeApi = null;
let activeSceneBindingKey = hostContextSnapshot.sceneBinding.sceneKey;
let subscribedSceneBindingKey = null;
let lifecycleActor = null;
let workspaceRefreshRefs = [];
let workspaceRefreshScheduled = false;
let workspaceActiveFilePoll = null;
const sendLifecycleEvent = (event) => {
if (disposed || !lifecycleActor) {
return;
}
lifecycleActor.send(event);
};
const isInteractionActive = () => {
if (disposed || !lifecycleActor) {
return false;
}
return lifecycleActor.getSnapshot().context.interactionDepth > 0;
};
const isInteractionLifecycleSettled = () => {
if (!lifecycleActor) {
return true;
}
const lifecycleSnapshot = lifecycleActor.getSnapshot();
if (lifecycleSnapshot.matches({ active: { lifecycle: "interacting" } })) {
return false;
}
if (lifecycleSnapshot.matches({ active: { lifecycle: "refreshing" } })) {
return false;
}
return lifecycleSnapshot.context.interactionDepth === 0 && !lifecycleSnapshot.context.pendingRefreshWhileInteractive && !lifecycleSnapshot.context.refreshRequested;
};
const waitForInteractionIdle = async () => {
if (disposed || !lifecycleActor || isInteractionLifecycleSettled()) {
return;
}
await new Promise((resolve) => {
const actor = lifecycleActor;
if (!actor) {
resolve();
return;
}
let resolved = false;
const subscription = actor.subscribe(() => {
if (resolved || !isInteractionLifecycleSettled()) {
return;
}
resolved = true;
subscription.unsubscribe();
resolve();
});
if (!resolved && isInteractionLifecycleSettled()) {
resolved = true;
subscription.unsubscribe();
resolve();
}
});
};
const beginInteraction = () => {
sendLifecycleEvent({ type: "BEGIN_INTERACTION" });
};
const endInteraction = () => {
sendLifecycleEvent({ type: "END_INTERACTION" });
};
const withInteraction = async (operation) => {
beginInteraction();
try {
return await operation();
} finally {
endInteraction();
}
};
const controller = new LayerManagerController(
{
// Store subscription renders synchronously. Do not mount host UI until
// every callback dependency and the runtime disposal handle exists.
render: (model) => {
if (!initialized || disposed) return;
try {
renderer.render(model);
} catch (error) {
lifecycleFailure = { error };
throw error;
}
},
notify: (message) => renderer.notify?.(message)
},
void 0,
{
waitForIdle: waitForInteractionIdle,
beginInteraction,
endInteraction
},
() => {
refresh();
}
);
let selectedIdsHintFromOnChange = null;
const reconcileHostContext = (signal) => {
const previousBindingKey = activeSceneBindingKey;
const result = hostFocusReleased ? hostContextCoordinator.reconcile("initial") : signal === "leaf-change" ? hostContextCoordinator.handleWorkspaceLeafChange() : signal === "poll" ? hostContextCoordinator.handlePollingFallback() : hostContextCoordinator.reconcile(signal);
if (previousBindingKey !== result.snapshot.sceneBinding.sceneKey || hostContextSnapshot.currentTargetView !== result.snapshot.currentTargetView || hostContextSnapshot.hasExplicitTargetViewProperty && hostContextSnapshot.sceneApi !== result.snapshot.sceneApi) {
hostAuthorityEpoch += 1;
clearPendingReadiness();
clearSceneChangeSubscription();
}
hostContextSnapshot = result.snapshot;
activeSceneBindingKey = result.snapshot.sceneBinding.sceneKey;
if (result.changed || previousBindingKey !== result.snapshot.bindingKey) {
selectedIdsHintFromOnChange = null;
}
return result;
};
const renderSnapshot = (nextSnapshot) => {
const elementIds = new Set(nextSnapshot.elements.map((element) => element.id));
const resolvedSelectedIds = hostContextSnapshot.state !== "live" ? /* @PURE / new Set() : selectedIdsHintFromOnChange ? new Set([...selectedIdsHintFromOnChange].filter((id) => elementIds.has(id))) : nextSnapshot.selectedIds;
snapshot = {
...nextSnapshot,
selectedIds: resolvedSelectedIds
};
const indexes = buildSceneIndexes(nextSnapshot);
const tree = buildLayerTree(
{
elements: nextSnapshot.elements,
expandedNodeIds: controller.getExpandedNodeIds(),
groupFreedraw: nextSnapshot.settings.groupFreedraw
},
indexes
);
const elementStateById = new Map(
nextSnapshot.elements.map(
(element) => [
element.id,
{
opacity: element.opacity,
locked: element.locked
}
]
)
);
controller.setTree(tree, nextSnapshot.version, resolvedSelectedIds, elementStateById);
};
const clearSceneChangeSubscription = () => {
sceneSubscriptionGeneration += 1;
try {
sceneChangeUnsubscribe?.();
} catch {
}
sceneChangeUnsubscribe = null;
subscribedSceneChangeApi = null;
subscribedSceneBindingKey = null;
};
const clearPendingReadiness = () => {
if (readinessTimer !== null) clearTimeout(readinessTimer);
readinessTimer = null;
readinessAttempts = 0;
};
const clearPendingRecovery = () => {
if (recoveryTimer !== null) clearTimeout(recoveryTimer);
recoveryTimer = null;
recoveryAttempts = 0;
};
const recoverReleasedView = () => {
if (disposed || !hostFocusReleased || !releasedContext) return;
let relevant = false;
try {
const leaf = releasedContext.leaf;
const workspace = releasedContext.workspace;
const replacementPath = leaf?.view?.file?.path;
relevant = !!leaf && (workspace?.activeLeaf === leaf || workspace?.getMostRecentLeaf?.() === leaf) && (!releasedContext.filePath || !replacementPath || replacementPath === releasedContext.filePath);
} catch {
}
if (!relevant) {
clearPendingRecovery();
releasedContext = null;
return;
}
const result = recoverHostViewFromReplacedLeaf(ea2, releasedContext);
if (result !== "recovered") {
if (recoveryTimer === null) {
const delay = recoveryAttempts < 20 ? WORKSPACE_ACTIVE_FILE_POLL_MS : READINESS_BACKOFF_MS;
recoveryAttempts = Math.min(recoveryAttempts + 1, 20);
recoveryTimer = setTimeout(() => {
recoveryTimer = null;
recoverReleasedView();
}, delay);
}
return;
}
clearPendingRecovery();
if (result === "recovered") {
hostFocusReleased = false;
releasedContext = null;
traceHostContextLifecycleEvent("rebind", "same-leaf replacement ready", {});
reconcileHostContext("manual");
scheduleHostContextRefresh();
}
};
const clearWorkspaceRefreshSubscriptions = () => {
clearPendingReadiness();
clearPendingRecovery();
releasedContext = null;
const workspace = runtimeApp?.workspace;
for (const ref of workspaceRefreshRefs) {
if (typeof ref === "function") {
try {
ref();
} catch {
}
continue;
}
try {
workspace?.offref?.(ref);
} catch {
}
}
if (workspaceActiveFilePoll !== null) {
clearInterval(workspaceActiveFilePoll);
workspaceActiveFilePoll = null;
}
workspaceRefreshRefs = [];
workspaceRefreshScheduled = false;
};
const scheduleHostContextRefresh = () => {
if (disposed || workspaceRefreshScheduled) {
return;
}
workspaceRefreshScheduled = true;
Promise.resolve().then(() => {
workspaceRefreshScheduled = false;
if (disposed) {
return;
}
sendLifecycleEvent({ type: "REFRESH_REQUEST" });
});
};
const shouldScheduleHostContextRefresh = (input) => {
return input.result.changed || input.result.rebound || input.previousRefreshKey !== input.result.snapshot.sceneBinding.refreshKey;
};
const logHostContextRefreshDecision = (input) => {
if (!input.result.changed && !input.result.rebound && !input.scheduledRefresh && input.previousBindingKey === input.result.snapshot.bindingKey && input.previousRefreshKey === input.result.snapshot.sceneBinding.refreshKey) {
return;
}
traceHostContextLifecycleEvent("signal", "host-context signal reconciled", {
source: input.source,
changed: input.result.changed,
rebound: input.result.rebound,
scheduledRefresh: input.scheduledRefresh,
previousBindingKey: input.previousBindingKey,
nextBindingKey: input.result.snapshot.bindingKey,
previousRefreshKey: input.previousRefreshKey,
nextRefreshKey: input.result.snapshot.sceneBinding.refreshKey,
sceneRefSource: input.result.snapshot.sceneBinding.source,
previousState: input.previousState,
nextState: input.result.snapshot.state,
previousShouldAttemptRebind: input.previousShouldAttemptRebind,
nextShouldAttemptRebind: input.result.snapshot.shouldAttemptRebind,
activeFilePath: input.result.snapshot.activeFilePath,
activeLeafIdentity: input.result.snapshot.activeLeafIdentity,
activeViewType: input.result.snapshot.activeViewType,
targetViewIdentity: input.result.snapshot.targetViewIdentity,
targetViewFilePath: input.result.snapshot.targetViewFilePath,
targetViewUsable: input.result.snapshot.targetViewUsable,
cachedTargetViewIdentity: input.result.snapshot.cachedTargetViewIdentity
});
};
const subscribeToWorkspaceRefresh = () => {
const workspace = runtimeApp?.workspace;
if (!workspace) {
traceHostContextLifecycleEvent("startup", "workspace refresh infrastructure unavailable", {
runtimeAppResolved: runtimeApp !== null,
hasWorkspace: false,
hasWorkspaceOn: false,
hasWorkspaceOffref: false,
pollArmed: false,
initialState: hostContextSnapshot.state,
initialBindingKey: hostContextSnapshot.bindingKey
});
return;
}
if (workspaceRefreshRefs.length === 0) {
const on = workspace.on;
if (on) {
for (const eventName of ["file-open", "active-leaf-change", "layout-change"]) {
try {
const ref = on.call(workspace, eventName, () => {
if (disposed) return;
if (hostFocusReleased) {
if (recoveryTimer === null) recoveryAttempts = 0;
recoverReleasedView();
}
const previousBindingKey = activeSceneBindingKey;
const previousRefreshKey = hostContextSnapshot.sceneBinding.refreshKey;
const previousState = hostContextSnapshot.state;
const previousShouldAttemptRebind = hostContextSnapshot.shouldAttemptRebind;
const reconcileResult = reconcileHostContext("leaf-change");
const scheduledRefresh = shouldScheduleHostContextRefresh({
previousRefreshKey,
result: reconcileResult
});
logHostContextRefreshDecision({
source: workspace:${eventName},
previousBindingKey,
previousRefreshKey,
previousState,
previousShouldAttemptRebind,
result: reconcileResult,
scheduledRefresh
});
if (!scheduledRefresh) {
return;
}
scheduleHostContextRefresh();
});
if (ref !== void 0) {
workspaceRefreshRefs.push(ref);
}
} catch {
}
}
}
}
const shouldArmPollingFallback = workspaceRefreshRefs.length === 0;
if (shouldArmPollingFallback && workspaceActiveFilePoll === null) {
workspaceActiveFilePoll = setInterval(() => {
const previousBindingKey = activeSceneBindingKey;
const previousRefreshKey = hostContextSnapshot.sceneBinding.refreshKey;
const previousState = hostContextSnapshot.state;
const previousShouldAttemptRebind = hostContextSnapshot.shouldAttemptRebind;
const reconcileResult = reconcileHostContext("poll");
const scheduledRefresh = shouldScheduleHostContextRefresh({
previousRefreshKey,
result: reconcileResult
});
logHostContextRefreshDecision({
source: "workspace:poll",
previousBindingKey,
previousRefreshKey,
previousState,
previousShouldAttemptRebind,
result: reconcileResult,
scheduledRefresh
});
if (!scheduledRefresh) {
return;
}
scheduleHostContextRefresh();
}, WORKSPACE_ACTIVE_FILE_POLL_MS);
}
traceHostContextLifecycleEvent("startup", "workspace refresh infrastructure ready", {
runtimeAppResolved: true,
hasWorkspace: true,
hasWorkspaceOn: typeof workspace.on === "function",
hasWorkspaceOffref: typeof workspace.offref === "function",
subscribedEvents: workspaceRefreshRefs.length,
pollArmed: workspaceActiveFilePoll !== null,
pollIntervalMs: WORKSPACE_ACTIVE_FILE_POLL_MS,
initialState: hostContextSnapshot.state,
initialBindingKey: hostContextSnapshot.bindingKey,
activeFilePath: hostContextSnapshot.activeFilePath,
activeLeafIdentity: hostContextSnapshot.activeLeafIdentity,
activeViewType: hostContextSnapshot.activeViewType,
targetViewIdentity: hostContextSnapshot.targetViewIdentity,
targetViewFilePath: hostContextSnapshot.targetViewFilePath
});
};
const scheduleApiReadinessCheck = () => {
if (disposed || readinessTimer !== null) return;
const expectedView = ea2.targetView;
if (!expectedView || typeof expectedView !== "object" || hostFocusReleased) return;
const view = expectedView;
if (view.getViewType && view.getViewType() !== "excalidraw") return;
if (!ea2.getExcalidrawAPI && !("excalidrawAPI" in view)) return;
const delay = readinessAttempts < 20 ? WORKSPACE_ACTIVE_FILE_POLL_MS : READINESS_BACKOFF_MS;
readinessAttempts = Math.min(readinessAttempts + 1, 20);
readinessTimer = setTimeout(() => {
readinessTimer = null;
if (disposed || hostFocusReleased) return;
if (ea2.targetView !== expectedView) {
clearPendingReadiness();
reconcileHostContext("manual");
scheduleHostContextRefresh();
return;
}
reconcileHostContext("manual");
if (hostContextSnapshot.sceneApi) {
readinessAttempts = 0;
scheduleHostContextRefresh();
} else {
scheduleApiReadinessCheck();
}
}, delay);
};
const subscribeToSceneChanges = () => {
if (disposed) return;
const api = hostContextSnapshot.sceneApi;
const currentSceneBindingKey = activeSceneBindingKey;
const sceneBindingChanged = currentSceneBindingKey !== subscribedSceneBindingKey;
if (sceneBindingChanged) {
selectedIdsHintFromOnChange = null;
}
if (!api) {
clearSceneChangeSubscription();
scheduleApiReadinessCheck();
return;
}
if (readinessTimer !== null) clearTimeout(readinessTimer);
readinessTimer = null;
readinessAttempts = 0;
if (api === subscribedSceneChangeApi && !sceneBindingChanged) {
return;
}
clearSceneChangeSubscription();
subscribedSceneChangeApi = api;
subscribedSceneBindingKey = currentSceneBindingKey;
const onChange = api.onChange;
if (!onChange) {
return;
}
const subscriptionGeneration = sceneSubscriptionGeneration;
try {
const unsubscribeCandidate = onChange.call(api, (_elements, appState) => {
if (disposed || subscriptionGeneration !== sceneSubscriptionGeneration || api !== subscribedSceneChangeApi || currentSceneBindingKey !== subscribedSceneBindingKey)
return;
selectedIdsHintFromOnChange = readSelectedIdsFromAppState(appState);
sendLifecycleEvent({ type: "SCENE_CHANGE_NOTICED" });
});
sceneChangeUnsubscribe = toSceneChangeUnsubscribe(unsubscribeCandidate);
} catch {
}
};
renderLatestSnapshot = () => {
if (disposed) {
return;
}
reconcileHostContext("manual");
const nextSnapshot = hostFocusReleased ? { ...snapshot, version: snapshot.version + 1, elements: [], selectedIds: / @PURE */ new Set() } : readSnapshot(ea2);
reconcileHostContext("manual");
renderSnapshot({
...nextSnapshot,
version: Math.max(nextSnapshot.version, snapshot.version + 1)
});
subscribeToSceneChanges();
};
lifecycleActor = createRuntimeLifecycleActor({
ea: ea2,
renderLatestSnapshot
});
const refresh = () => {
sendLifecycleEvent({ type: "REFRESH_REQUEST" });
if (lifecycleFailure) throw lifecycleFailure.error;
};
const captureMutationAuthority = () => {
const epoch = hostAuthorityEpoch;
const targetView = ea2.targetView;
const view = targetView;
const api = view?.excalidrawAPI;
const leafView = view?.leaf?.view;
return () => !disposed && !hostFocusReleased && epoch === hostAuthorityEpoch && targetView === ea2.targetView && api === view?.excalidrawAPI && leafView === view?.leaf?.view;
};
const apply = async (patch) => {
if (disposed) {
throw new Error("Layer Manager runtime disposed.");
}
if (hostFocusReleased)
return { status: "capabilityMissing", reason: "No active Excalidraw view." };
return new Promise((resolve, reject) => {
sendLifecycleEvent({
type: "APPLY_REQUEST",
patch,
canExecute: captureMutationAuthority(),
resolve,
reject
});
});
};
const executeIntent = async (planner) => {
if (disposed) {
throw new Error("Layer Manager runtime disposed.");
}
if (hostFocusReleased)
return { status: "capabilityMissing", reason: "No active Excalidraw view.", attempts: 1 };
return new Promise((resolve, reject) => {
sendLifecycleEvent({
type: "EXECUTE_INTENT_REQUEST",
planner,
canExecute: captureMutationAuthority(),
resolve,
reject
});
});
};
const commands = createLayerManagerCommandFacade({
executeIntent,
notify: (message) => {
controller.notify(message);
}
});
const dispose = () => {
if (disposed) {
return;
}
disposed = true;
const failedSnapshot = lifecycleActor?.getSnapshot();
if (failedSnapshot?.status === "error") {
const error = lifecycleFailure?.error ?? new Error("Layer Manager runtime failed.");
failedSnapshot.context.activeMutation?.reject(error);
for (const request of failedSnapshot.context.mutationQueue) request.reject(error);
}
lifecycleActor?.send({ type: "DISPOSE" });
lifecycleActor?.stop();
lifecycleActor = null;
clearSceneChangeSubscription();
clearWorkspaceRefreshSubscriptions();
if (runtimeGlobal.excalidrawLayerManagerRuntime === runtime) {
Reflect.deleteProperty(runtimeGlobal, "excalidrawLayerManagerRuntime");
}
try {
renderer.dispose?.();
} finally {
controller.dispose();
}
};
controller.setCommandFacade(commands);
const toggleExpanded = (nodeId) => {
controller.toggleExpanded(nodeId);
};
runtime = {
refresh,
apply,
executeIntent,
getSnapshot: () => snapshot,
toggleExpanded,
beginInteraction,
endInteraction,
withInteraction,
isInteractionActive,
dispose,
isDisposed: () => disposed,
commands
};
lifecycleActor.subscribe({
error: (error) => {
lifecycleFailure = { error };
try {
dispose();
} catch {
}
}
});
initialized = true;
try {
lifecycleActor.start();
subscribeToWorkspaceRefresh();
refresh();
} catch (error) {
try {
dispose();
} catch {
}
throw error;
}
return runtime;
};
var runtimeGlobal = globalThis;
var resolveScriptEa = () => {
if (typeof ea !== "undefined" && ea) {
return ea;
}
const globalEa = globalThis.ea;
if (globalEa) {
return globalEa;
}
return void 0;
};
var scriptEa = resolveScriptEa();
if (scriptEa) {
const Notice = scriptEa.obsidian?.Notice;
installHostContextFlightRecorderGlobals({ Notice });
installKeyEventFlightRecorderGlobals();
clearHostContextFlightRecorder();
clearKeyEventTrace();
traceHostContextLifecycleEvent("startup", "LayerManager script executed", {
runtimeAppResolved: resolveRuntimeApp(scriptEa) !== null,
...describeHostViewContext(scriptEa)
});
if (isLifecycleDebugEnabled()) {
if (Notice) {
new Notice("[LMX] LayerManager script executed.", 2200);
}
console.log("[LMX] LayerManager script executed.");
console.log("[LMX] EA pre-runtime context", {
...describeHostViewContext(scriptEa)
});
}
runtimeGlobal.excalidrawLayerManagerRuntime?.dispose?.();
const candidate = createLayerManagerRuntime(scriptEa);
if (!candidate.isDisposed()) runtimeGlobal.excalidrawLayerManagerRuntime = candidate;
} else {
installHostContextFlightRecorderGlobals();
installKeyEventFlightRecorderGlobals();
clearHostContextFlightRecorder();
clearKeyEventTrace();
traceHostContextLifecycleEvent(
"startup",
"No active Excalidraw context (ea missing). Open an Excalidraw drawing and rerun LayerManager.",
{
hasScriptEa: false,
runtimeAppResolved: false
}
);
if (isLifecycleDebugEnabled()) {
console.log(
"[LMX] No active Excalidraw context (ea missing). Open an Excalidraw drawing and rerun LayerManager."
);
}
}
})();