Skip to content
This repository was archived by the owner on Oct 19, 2021. It is now read-only.
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,42 @@ const states = [
'textChanged',
];

// Stores the transition callback handlers in a flat object, looks like:
// { "attached": fn, "detached": fn, ... }
const transitionsMap = new WeakMap();

/**
* Used to clean up all transition states around an element whenever it is
* detached or replaced.
*/
function cleanup(element) {
if (transitionMap.has(element)) {
const internalMap = transitionsMap.get(element) || {};

Object.keys(internalMap).forEach(key => {
removeTransitionState(key, internalMap[key])
});

transitionsMap.delete(element);
}
}

/**
* Binds inline transitions to the parent element and triggers for any matching
* nested children.
*/
export default function({ addTransitionState, removeTransitionState }) {
// When the element is attached, trigger the state handler if it exists.
addTransitionState('attached', (element) => {
if (element.attributes.attached) {
return element.attached.call(this, element, element);
}
});

// Remove all transitions whenever the element is detached or replaced.
addTransitionState('detached', removeTransitions);
addTransitionstate('replaced', removeTransitions);

// Set a "global" `attributeChanged` to monitor all elements for transition
// states being attached.
addTransitionState('attributeChanged', (element, name, oldVal, newVal) => {
Expand All @@ -28,6 +51,7 @@ export default function({ addTransitionState, removeTransitionState }) {
return;
}

// A new value means to set the internal map.
if (newVal) {
transitionsMap.set(element, Object.assign(internalMap, {
[name]: (...args) => {
Expand All @@ -39,6 +63,7 @@ export default function({ addTransitionState, removeTransitionState }) {

addTransitionState(name, internalMap[name])
}
// No new value indicates a removal.
else if (internalMap[name]) {
removeTransitionState(name, internalMap[name])
delete internalMap[name];
Expand Down