From ea000b648fa544757dfb5bfa5d1487cfafe12e94 Mon Sep 17 00:00:00 2001 From: Osvaldas Valutis Date: Mon, 22 Nov 2021 17:46:58 +0200 Subject: [PATCH] feat: traversal next prev (#17) --- index.js | 35 +++++++++++++++++++++++++---------- package.json | 2 +- 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/index.js b/index.js index 0bf7860..1e85fb2 100644 --- a/index.js +++ b/index.js @@ -24,16 +24,31 @@ const getInsertionNodeElem = function(insertionNode, insertionTraversal, btn) { return insertionNode(btn); } - if(insertionTraversal) { - // TODO: - // https://github.com/nathanvda/cocoon/blob/master/app/assets/javascripts/cocoon.js#L32 - // data-association-insertion-traversal: the jquery traversal method to - // allow node selection relative to the link. closest, next, children, etc. - // return $this[insertionTraversal](insertionNode); - return null; - } - else { - return document.querySelector(insertionNode); + if(typeof insertionNode == 'string') { + if (insertionTraversal) { + // @TODO + // - prevUntil + // - nextUntil + + const prevNext = { + prev: 'previousElementSibling', + next: 'nextElementSibling', + }[insertionTraversal] + + if (prevNext) { + const el = btn[prevNext].closest(insertionNode) + if (el === btn[prevNext]) return el + } + else if (insertionTraversal == 'closest') { + return btn.closest(insertionNode) + } + else { + console.warn('The provided association-insertion-traversal is not supported'); + } + } + else { + return insertionNode == 'this' ? btn : document.querySelector(insertionNode); + } } }; diff --git a/package.json b/package.json index 781c0c1..e3c3b77 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@oddcamp/cocoon-vanilla-js", - "version": "1.1.2", + "version": "1.1.3", "description": "A vanilla JS replacement for (Rails) Cocoon's jQuery script", "main": "index.js", "repository": "git+https://github.com/oddcamp/cocoon-vanilla-js.git",