You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jsTreeR库禁止将分支节点拖放至叶子节点

需求:禁止分支节点拖放至叶子节点(jsTreeR)

这是我此前问题的跟进。感谢@StéphaneLaurent和@ismirsehregal提供的自定义jsTreeR右键菜单方案,代码如下:

library(jsTreeR)
library(shiny)

nodes <- list(
  list(
    text = "Branch 1",
    state = list(opened = TRUE, disabled = FALSE),
    type = "parent",
    children = list(
      list(text = "Leaf A", type = "undeletable", state = list(disabled = FALSE), data = list(customdata = 1)),
      list(text = "Leaf B", type = "undeletable", state = list(disabled = FALSE), data = list(customdata = 2)),
      list(text = "Leaf C", type = "undeletable", state = list(disabled = FALSE), data = list(customdata = 3)),
      list(text = "Leaf D", type = "undeletable", state = list(disabled = FALSE), data = list(customdata = 4))
    )
  ),
  list(text = "Branch 2", type = "parent", state = list(opened = TRUE))
)

ui <- fluidPage(
  jstreeOutput("mytree")
)

customMenu <- JS(
  "function customMenu(node) {
  var tree = $('#mytree').jstree(true);
  var items = {
    'rename' : {
      'label' : 'Rename',
      'action' : function (obj) { tree.edit(node); },
      'icon': 'glyphicon glyphicon-edit'
    },
    'delete' : {
      'label' : 'Delete',
      'action' : function (obj) { tree.delete_node(node); },
      'icon' : 'glyphicon glyphicon-trash'
    },
    'create' : {
      'label' : 'Create',
      'action' : function (obj) { tree.create_node(node); },
      'icon': 'glyphicon glyphicon-plus'
    }
  }
  
  if (node.children.length > 0) { items.delete._disabled = true; }
  if (node.type === 'undeletable') { items.rename._disabled = true;
                                     items.delete._disabled = true;
                                     items.create._disabled = true;
                                    }

  return items;
}")

server <- function(input, output, session){
  output[["mytree"]] <- renderJstree({
    suppressMessages(jstree(
      nodes,
      search = list(
        show_only_matches = TRUE,
        case_sensitive = FALSE,
        search_leaves_only = FALSE
      ),
      dragAndDrop = TRUE,
      multiple = TRUE,
      contextMenu = list(items = customMenu),
      types = list(default = list(icon = "fa fa-caret-right"), undeletable = list(icon = "fa-solid fa-leaf"), parent = list(icon = "fa-brands fa-pagelines")),
      theme = "proton"
    ))
  })
}  

shinyApp(ui, server)

基于上述代码,我需要实现禁止将分支节点拖放至叶子节点的功能。不再为整棵树统一设置dragAndDrop = TRUE,而是根据节点类型区分操作权限:

允许的操作

允许的拖放操作示例


禁止的操作

禁止的拖放操作示例


内容的提问来源于stack exchange,提问作者ahnungslos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:35:16