Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

javascript - How to make an svg interactive to gather comments/annotations on depicted elements

I create directed graphs like the following from wikidata with the help of networkx and nxv. The result is an svg file which might be embedded in some html page.

wikidata digraph

Now I want that every node and every edge is "clickable", such that a user can add their comments to specific elements of the graph. I think this could be done with a modal dialog popping up. This dialog should know from which element it was triggered and it should send the content of the textarea to some url via a post request.

What would be the best way to achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Wrapped in a W3C standard Web Component (supported in all Modern Browsers) you can make it generic for any src="filename.svg"

<graphviz-svg-annotator src="fsm.svg"></graphviz-svg-annotator>
<graphviz-svg-annotator src="Linux_kernel_diagram.svg"></graphviz-svg-annotator>
<style>
  svg .annotate { cursor:pointer }
</style>
<script>
  customElements.define('graphviz-svg-annotator', class extends HTMLElement {
    constructor() {
      let loadSVG = async ( src , container = this.shadowRoot ) => {
        container.innerHTML = `<style>:host { display:inline-block }
                               ::slotted(svg)  { width:100%;height:200px }
                               </style>
                               <slot name="svgonly">Loading ${src}</slot>`;
        this.innerHTML = await(await fetch(src)).text(); // load full XML in lightDOM
        let svg = this.querySelector("svg");
        svg.slot = "svgonly"; // show only SVG part in shadowDOM slot
        svg.querySelectorAll('g[id*="node"],g[id*="edge"]').forEach(g => {
          let label  = g.querySelector("text")?.innerHTML || "No label";
          let shapes = g.querySelectorAll("*:not(title):not(text)");
          let fill   = (color = "none") => shapes.forEach(x => x.style.fill = color);
          let prompt = "Please annotate: ID: " + g.id + " label: " + label; 
          g.classList.add("annotate");
          g.onmouseenter = evt => fill("lightgreen");
          g.onmouseleave = evt => fill();
          g.onclick = evt => g.setAttribute("annotation", window.prompt(prompt));
        })
      }
      super().attachShadow({ mode: 'open' });
      loadSVG("//graphviz.org/Gallery/directed/"+this.getAttribute("src"));
    }});
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...