How can I copy a subtree with a link to the original parent?

Hi

I’m using a GoJS diagram together with an instance of go.GraphLinksModel. I’m trying to copy and paste a subtree and preserve the link to the original parent. I’ve set commandHandler.copiesTree = true and this allows me to successfully copy my selected node as well as its children. However, the copied subtree is not linked to the original parent.

In my screenshot, I selected the “Experience 1” node and copy/pasted it. A copy of the subtree was created (Experience 1 (Copy)) but I need it to be linked to the original parent (Journey Satisfaction).

How can I implement this behaviour?

I think i need to override the command handler’s copyToClipboard function (https://gojs.net/latest/api/symbols/CommandHandler.html#copyToClipboard) but I’m not sure how to proceed.

Thanks so much.

If your model is a TreeModel, just set CommandHandler.copiesParentKey to true.

Hi Walter

Unfortunately I can’t use a TreeModel because children can have multiple parents. How can I do it with a GraphLinksModel?

Ah, the reason that CommandHandler.copiesParentKey property doesn’t work for GraphLinksModels is exactly this situation – establishing the desired links to the copied nodes can be complicated and subject to a lot of varying requirements.

CommandHandler.copyToClipboard is called when copying the selection to the clipboard. Call the base method first and then record the “predecessor” links of the selected node(s).

You also want to override CommandHandler.pasteFromClipboard, because that is when you want to do the extra work to add new links to the newly copied nodes given the original link information saved in your override of copyToClipboard. Call the base method first and then add the links (by calling GraphLinksModel.addLinkData).

It would be wise not to save references to the actual Links that connect the rest of the graph with the selection that is being copied, but some more fundamental identifying information about the links or their source nodes/ports.

There are two reasons for this (at least!). First, keeping those references might be hanging onto a lot of stuff in the diagram that might want to be garbage collected, unless you can clear that saved information at the appropriate times.

Second, what happens if after the “Copy” command the user deletes or reconnects some of those links? If you were to depend on the original Links, a “Paste” command might be working on the wrong information.