Skip to content

Commit

Permalink
Add listener in capture phase and locate nearest source if needed
Browse files Browse the repository at this point in the history
1. Capture Phase listener allows the plugin to work for the cases where stopPropagation is done in bubble phase.
2. Looking for nearest parent element with dataset source handles the case when the element directly doesn't have dataset source. This hhappens if the element is not created through JSX e.g. Chakra UI ModalCloseButton. Basically any component coming through an npm dependency should have this problem. See https://codesandbox.io/s/suspicious-breeze-smdrq?file=/src/index.js
  • Loading branch information
hariombalhara committed Sep 22, 2021
1 parent 652a9db commit 0f97de0
Showing 1 changed file with 24 additions and 9 deletions.
33 changes: 24 additions & 9 deletions packages/babel-plugin-open-source/script.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,25 @@
if (typeof document !== 'undefined') {
document.addEventListener('click', (event) => {
if (!event.target.dataset.source) return;
if (!event.altKey) return;
(function () {

// Element being clicked might not have the dataset source on it directly.
// Get the nearest available in the tree
// e.g. this happens for Chakra UI Components.
function getSource(element) {
while (element && !element.dataset.source) {
element = element.parentElement;
}

event.preventDefault();
const { filename, start } = JSON.parse(event.target.dataset.source)
window.open('vscode://file/' + filename + ':' + start)
})
}
return element.dataset.source;
}

if (typeof document !== 'undefined') {
document.addEventListener('click', (event) => {
let source = getSource(event.target)
if (!source) return;
if (!event.altKey) return;

event.preventDefault();
const { filename, start } = JSON.parse(source)
window.open('vscode://file/' + filename + ':' + start)
}, true)
}
})();

0 comments on commit 0f97de0

Please sign in to comment.