svg.js icon indicating copy to clipboard operation
svg.js copied to clipboard

position(), prev(), etc. returning incorrect values

Open samhocevar opened this issue 3 years ago • 2 comments

Bug report

Fiddle

https://jsfiddle.net/azqoxptd/

data = `<svg id="doc">
  <path id="a" fill="#DA251d" d="M-20,-15"/>
  <path id="b" fill="#FF0" d="M0,-6"/>
  <path id="c" fill="#FF0" d="M0,-6"/>
  <path id="d" fill="#FF0" d="M5.7063,-1.8541"/>
</svg>`
var canvas = SVG().addTo('#canvas').size('100%', '100%')
canvas.svg(data);

let do_something = function(e) {
    for (let child of e.children())
        do_something(child);
    if (e.position() > 0)
        console.info(`${e.position()}: ${e.id()} (after ${e.prev().id()})`);
}
do_something(canvas);

Explanation

I expect to see the following output:

1: b (after a)
2: c (after b)
3: d (after c)

Instead I see the following:

1: a (after a)
3: b (after c)
Uncaught TypeError: Cannot read property 'id' of undefined

Everything is wrong with these lines:

  • a.position() returns 1 (should be 0)
  • a.prev() returns a (should be null)
  • b.position() returns 3 (should be 1)
  • b.prev() returns c (should be a)
  • c.prev() returns null (should be b)

Maybe this happens because the calls to prev() are inside an enumeration of the parent’s children? Anyway, if there are limitations and shortcomings with the use of these function, I could not find them in the documentation.

samhocevar avatar Feb 26 '21 16:02 samhocevar

I realise that everything works properly if the SVG is built like this:

var canvas = SVG().addTo('#canvas').size('100%', '100%')
canvas.id('doc');
canvas.path('M0,0').id('a');
canvas.path('M0,0').id('b');
canvas.path('M0,0').id('c');
canvas.path('M0,0').id('d');

So maybe the problem lies within SVG.svg().

samhocevar avatar Feb 28 '21 20:02 samhocevar

It's because of whitespaces

Fuzzyma avatar Feb 28 '21 21:02 Fuzzyma

Changing this would be a major breaking change and therefore this is a wontfix until we decide to develop a v4

Fuzzyma avatar Sep 03 '23 10:09 Fuzzyma