From e0be375fc57930306999f15c7a7266edb0ba3432 Mon Sep 17 00:00:00 2001 From: Morgan Harris Date: Tue, 23 Nov 2021 13:12:44 +1100 Subject: [PATCH] Return null if `until` not in parent chain --- spec/spec/elements/Element.js | 14 ++++++++++++++ src/elements/Element.js | 15 ++++++++------- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/spec/spec/elements/Element.js b/spec/spec/elements/Element.js index 5076373..38b862f 100644 --- a/spec/spec/elements/Element.js +++ b/spec/spec/elements/Element.js @@ -188,6 +188,20 @@ describe('Element.js', function () { expect(rect.parents('.foo')).toEqual([ group3 ]) expect(rect.parents('.test:not(.foo)')).toEqual([ group3, group2, group1 ]) }) + + it('returns null if the passed element is not an ancestor', () => { + const canvas = SVG().addTo(container) + const groupA = canvas.group().addClass('test') + const group1 = canvas.group() + const group2 = group1.group() + const group3 = group2.group() + const rect = group3.rect(100, 100) + + + expect(rect.parents('.does-not-exist')).toEqual(null) + expect(rect.parents('.test')).toEqual(null) + expect(rect.parents(groupA)).toEqual(null) + }) }) describe('reference()', () => { diff --git a/src/elements/Element.js b/src/elements/Element.js index a1e7236..2aaeab5 100644 --- a/src/elements/Element.js +++ b/src/elements/Element.js @@ -87,11 +87,8 @@ export default class Element extends Dom { // return array of all ancestors of given type up to the root svg parents (until = this.root()) { - let selector = null - if (typeof until === 'string') { - selector = until - until = this.root() - } else { + const isSelector = typeof until === 'string' + if (!isSelector) { until = makeInstance(until) } const parents = new List() @@ -104,12 +101,16 @@ export default class Element extends Dom { parents.push(parent) - if (parent.node === until.node) { + if (!isSelector && (parent.node === until.node)) { break } - if (selector && parent.matches(selector)) { + if (isSelector && parent.matches(until)) { break } + if (parent.node === this.root().node) { + // We worked our way to the root and didn't match `until` + return null + } } return parents -- 2.39.5