All files nodeClipboard.js

94.37% Statements 302/320
59.67% Branches 74/124
100% Functions 17/17
94.37% Lines 302/320

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 3212x 2x 2x 2x 2x 26x 26x 26x 26x 26x 26x     26x   26x 2x 39x 39x 39x 39x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 9x 9x 9x 2x 9x 2x 2x 2x 2x 2x 2x 9x 2x 6x 6x 6x 2x 5x 5x 5x 5x 2x 9x 9x 9x 2x 9x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 8x 8x 8x 1x 1x 8x     8x 8x 2x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 2x 4x 4x 4x 4x 4x 4x 4x 4x 8x 8x 8x       8x 4x 4x 4x 2x 5x 5x 5x 5x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 5x 5x 5x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 4x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 2x 2x 2x 2x 2x 2x 2x 4x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x     1x 2x 2x 5x 5x 5x 5x 5x 5x 5x     5x 5x 5x 5x 5x 8x 5x 5x 5x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 5x 5x 5x 5x 3x 3x 5x 5x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 5x 5x 5x 5x 5x 5x 5x 5x  
import { sortNodesForParentOrder } from './nodeHierarchy.js';
 
export const NODE_CLIPBOARD_KIND = 'tono/node-selection';
export const NODE_CLIPBOARD_MIME = 'application/x-tono-node-selection';
 
function cloneValue(value) {
  if (value == null) return value;
  if (typeof structuredClone === 'function') {
    try {
      return structuredClone(value);
    } catch {
      // Fall through to JSON clone for simple plain data.
    }
  }
  return JSON.parse(JSON.stringify(value));
}
 
function clonePlainObject(value) {
  if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
  return cloneValue(value) || {};
}
 
function encodeProxyHandleRef(handleId) {
  return encodeURIComponent(String(handleId || ''));
}
 
function decodeProxyHandleRef(encoded) {
  try {
    return decodeURIComponent(String(encoded || ''));
  } catch {
    return String(encoded || '');
  }
}
 
function parseGroupProxyHandle(handleId) {
  const text = String(handleId || '');
  if (!text.startsWith('group-proxy::')) return null;
  const parts = text.split('::');
  if (parts.length < 5) return null;
  return {
    direction: parts[1],
    nodeId: parts[2],
    type: parts[3],
    realHandle: decodeProxyHandleRef(parts.slice(4).join('::')),
  };
}
 
function hasOwn(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}
 
function remapNodeId(value, idMap) {
  if (value == null) return value;
  return idMap.get(String(value)) || String(value);
}
 
function remapGroupProxyHandle(handleId, idMap) {
  const proxy = parseGroupProxyHandle(handleId);
  if (!proxy) return handleId;
  return `group-proxy::${proxy.direction}::${remapNodeId(proxy.nodeId, idMap)}::${proxy.type}::${encodeProxyHandleRef(proxy.realHandle)}`;
}
 
function remapGroupProxyDescriptors(items, idMap) {
  if (!Array.isArray(items)) return items;
  return items.map((item) => {
    if (!item || typeof item !== 'object') return item;
    const nextItem = { ...item };
    if (typeof nextItem.key === 'string') {
      const separator = nextItem.key.indexOf('::');
      if (separator !== -1) {
        const handleId = nextItem.key.slice(separator + 2);
        nextItem.key = `${remapNodeId(nextItem.key.slice(0, separator), idMap)}::${remapGroupProxyHandle(handleId, idMap)}`;
      }
    }
    if (typeof nextItem.handleId === 'string') {
      nextItem.handleId = remapGroupProxyHandle(nextItem.handleId, idMap);
    }
    return nextItem;
  });
}
 
function remapClipboardExtraData(extraData, idMap) {
  const nextExtraData = clonePlainObject(extraData);
  if (Array.isArray(nextExtraData.proxyInputs)) {
    nextExtraData.proxyInputs = remapGroupProxyDescriptors(nextExtraData.proxyInputs, idMap);
  }
  if (Array.isArray(nextExtraData.proxyOutputs)) {
    nextExtraData.proxyOutputs = remapGroupProxyDescriptors(nextExtraData.proxyOutputs, idMap);
  }
  return nextExtraData;
}
 
function remapClipboardEdgeData(data, idMap) {
  if (!data || typeof data !== 'object' || Array.isArray(data)) return cloneValue(data);
 
  const nextData = cloneValue(data);
  if (hasOwn(nextData, 'groupInternalHiddenBy')) {
    nextData.groupInternalHiddenBy = remapNodeId(nextData.groupInternalHiddenBy, idMap);
  }
  if (hasOwn(nextData, 'groupProxyOwner')) {
    nextData.groupProxyOwner = remapNodeId(nextData.groupProxyOwner, idMap);
  }
 
  const original = nextData.groupProxyOriginal;
  if (original && typeof original === 'object' && !Array.isArray(original)) {
    if (hasOwn(original, 'source')) original.source = remapNodeId(original.source, idMap);
    if (hasOwn(original, 'target')) original.target = remapNodeId(original.target, idMap);
    if (hasOwn(original, 'sourceHandle')) {
      original.sourceHandle = remapGroupProxyHandle(original.sourceHandle, idMap);
    }
    if (hasOwn(original, 'targetHandle')) {
      original.targetHandle = remapGroupProxyHandle(original.targetHandle, idMap);
    }
  }
 
  return nextData;
}
 
function collectSelectedNodeIds(nodes, nodeIds) {
  const selectedIdSet = new Set((Array.isArray(nodeIds) ? nodeIds : []).map((id) => String(id)));
  if (selectedIdSet.size === 0) return selectedIdSet;
 
  let changed = true;
  while (changed) {
    changed = false;
    for (const node of Array.isArray(nodes) ? nodes : []) {
      const parentId = node?.parentId ? String(node.parentId) : null;
      const nodeId = String(node?.id);
      if (parentId && selectedIdSet.has(parentId) && !selectedIdSet.has(nodeId)) {
        selectedIdSet.add(nodeId);
        changed = true;
      }
    }
  }
  return selectedIdSet;
}
 
function extractExtraData(data) {
  const source = data || {};
  return Object.fromEntries(
    Object.entries(source).filter(([key]) => ![
      'label',
      'className',
      'widgetValues',
      'runtimeValues',
      'definition',
      'previewImage',
      'tableRows',
      'meshData',
      'overlay',
      'scalarValue',
      'processingTimeMs',
      'warning',
    ].includes(key)),
  );
}
 
export function buildNodeClipboardPayloadForIds(
  nodes,
  edges,
  nodeIds,
  { includeIncomingExternalEdges = false } = {},
) {
  const selectedIdSet = collectSelectedNodeIds(nodes, nodeIds);
  const selectedNodes = Array.isArray(nodes)
    ? nodes.filter((node) => selectedIdSet.has(String(node.id)))
    : [];
  if (selectedNodes.length === 0) return null;
 
  const capturedEdges = Array.isArray(edges)
    ? edges.filter((edge) => (
      selectedIdSet.has(String(edge.target))
      && (
        selectedIdSet.has(String(edge.source))
        || (includeIncomingExternalEdges && !selectedIdSet.has(String(edge.source)))
      )
    ))
    : [];
 
  return {
    kind: NODE_CLIPBOARD_KIND,
    version: 1,
    nodes: selectedNodes.map((node) => ({
      id: String(node.id),
      type: node.type || 'custom',
      position: {
        x: Number(node.position?.x) || 0,
        y: Number(node.position?.y) || 0,
      },
      ...(node.className ? { className: node.className } : {}),
      ...(node.parentId ? { parentId: String(node.parentId) } : {}),
      ...(node.extent ? { extent: node.extent } : {}),
      ...(node.hidden ? { hidden: true } : {}),
      ...(node.style ? { style: cloneValue(node.style) } : {}),
      dragHandle: node.dragHandle || '.drag-handle',
      data: {
        label: node.data?.label || node.data?.className || 'Node',
        className: node.data?.className || '',
        widgetValues: clonePlainObject(node.data?.widgetValues),
        runtimeValues: clonePlainObject(node.data?.runtimeValues),
        extraData: clonePlainObject(extractExtraData(node.data)),
      },
    })),
    edges: capturedEdges.map((edge) => ({
      source: String(edge.source),
      sourceHandle: edge.sourceHandle,
      target: String(edge.target),
      targetHandle: edge.targetHandle,
      ...(edge.style ? { style: { ...edge.style } } : {}),
      ...(edge.hidden ? { hidden: true } : {}),
      ...(edge.data ? { data: cloneValue(edge.data) } : {}),
    })),
  };
}
 
export function buildNodeClipboardPayload(nodes, edges) {
  const selectedNodes = Array.isArray(nodes)
    ? nodes.filter((node) => node?.selected)
    : [];
  const selectedIds = selectedNodes.map((node) => String(node.id));
  const includeIncomingExternalEdges = selectedNodes.some((node) => node?.data?.className === 'Group');
  return buildNodeClipboardPayloadForIds(nodes, edges, selectedIds, { includeIncomingExternalEdges });
}
 
export function parseNodeClipboardPayload(text) {
  if (typeof text !== 'string' || !text.trim()) return null;
 
  try {
    const parsed = JSON.parse(text);
    if (parsed?.kind !== NODE_CLIPBOARD_KIND) return null;
    if (!Array.isArray(parsed.nodes) || !Array.isArray(parsed.edges)) return null;
    return parsed;
  } catch {
    return null;
  }
}
 
export function instantiateNodeClipboardPayload(
  payload,
  defs = {},
  nextNodeId = 1,
  offset = { x: 40, y: 40 },
  { keepExternalSources = false } = {},
) {
  if (!payload || !Array.isArray(payload.nodes) || payload.nodes.length === 0) {
    return { nodes: [], edges: [], nextNodeId };
  }
 
  const idMap = new Map();
  let currentId = Number(nextNodeId) || 1;
 
  payload.nodes.forEach((node) => {
    idMap.set(String(node.id), String(currentId++));
  });
 
  const nodes = sortNodesForParentOrder(payload.nodes.map((node) => {
    const newId = idMap.get(String(node.id));
    const className = node.data?.className || '';
    const definition = className ? defs[className] || null : null;
    const extraData = remapClipboardExtraData(node.data?.extraData, idMap);
 
    return {
      id: newId,
      type: node.type || 'custom',
      className: node.className,
      position: {
        x: (Number(node.position?.x) || 0) + (Number(offset?.x) || 0),
        y: (Number(node.position?.y) || 0) + (Number(offset?.y) || 0),
      },
      ...(node.parentId ? { parentId: idMap.get(String(node.parentId)) || String(node.parentId) } : {}),
      ...(node.extent ? { extent: node.extent } : {}),
      ...(node.hidden ? { hidden: true } : {}),
      ...(node.style ? { style: cloneValue(node.style) } : {}),
      dragHandle: node.dragHandle || '.drag-handle',
      selected: true,
      data: {
        label: node.data?.label || className || 'Node',
        className,
        widgetValues: clonePlainObject(node.data?.widgetValues),
        runtimeValues: clonePlainObject(node.data?.runtimeValues),
        ...extraData,
        definition,
        previewImage: null,
        tableRows: null,
        meshData: null,
        overlay: null,
        scalarValue: null,
        processingTimeMs: null,
        warning: null,
      },
    };
  }));
 
  const edges = payload.edges
    .filter((edge) => (
      idMap.has(String(edge.target))
      && (idMap.has(String(edge.source)) || keepExternalSources)
    ))
    .map((edge, index) => {
      const source = idMap.get(String(edge.source)) || String(edge.source);
      const target = idMap.get(String(edge.target));
      return {
        id: `e${source}-${target}-${index}`,
        source,
        sourceHandle: remapGroupProxyHandle(edge.sourceHandle, idMap),
        target,
        targetHandle: remapGroupProxyHandle(edge.targetHandle, idMap),
        selected: false,
        ...(edge.style ? { style: { ...edge.style } } : {}),
        ...(edge.hidden ? { hidden: true } : {}),
        ...(edge.data ? { data: remapClipboardEdgeData(edge.data, idMap) } : {}),
      };
    });
 
  return {
    nodes,
    edges,
    nextNodeId: currentId,
  };
}