Vue/Vuex/GSAP-Animation: Add DOM elements to store - dom

In a Vue project, I am looking for a way to save DOM elements to the store. Those elements shall then be animated with GSAP.
Unfortunately, there is a bit of a problem with when the DOM is ready (so I can use document.querySelector) and when Vue's transition system is firing.
the store has about this structure:
const store = new Vuex.Store({
state: {
settings: {
ui: {
btns: {
cBtnNavMain: {
el: document.querySelector('.c-btn__nav--main') // does not work, because DOM is not yet ready
[...]
}
}
}
}
},
mutations: {
// Add DOM element later via a mutation?
addDomElementToStore: (state, obj) => {
console.log("MUTATION addDomElementToStore, obj =", obj) // shows `null`
obj.el = obj.domEl
}
}
}
Then, in App.vue (loaded by main.js) there is basically this script:
created() {
console.log("App.vue created")
}
mounted() {
console.log("App.vue created")
}
methods: {
beforeEnter(el) {
console.log("BeforeEnter called, obj")
// This could be the place to add DOM to the store, but how?
// I tried a mutations like this (see above in store.mutations):
this.$store.commit('addDomElementToSettings', {
el: this.$store.state.settings.ui.btns.cNavMainBtn.el,
domEl: document.querySelector('.c-btn__nav--main')
})
// ...but won't work though, the console shows, obj params are empty
}
[...]
}
The console result shows something like this:
App.vue created
BeforeEnter called // <-- beginEnter before mounted called!
MUTATION addDomElementToStore, obj = {el: null, domElem: null}
App.vue mounted
Since "beforeEnter" is called after created, but BEFORE mounted (which is, where the DOM would be easily accessible), the DOM is not really accessible yet, it seems. So I thought, I use "beforeEnter" to assign new DOM elements to store.settings using a mutation. But that doesn't work at all - and GSAP eventually has do DOM elements to animate on.
What do I have to do to get my DOM elements saves to the settings, so that I do not have to use document.querySelector all the time, when I want to address a DOM element with GSAP?

Why don't try you using the mounted() lifecycle method to fire the mutation that stores DOM element selections in vuex state? That way you know something exists to select.

Related

cy.trigger() throws "cy.trigger() can only be called on a single element.in Cypress

For my application, I have to select multiple items and perform drag and drop operation, but I got the following error.
cy.trigger() can only be called on a single element. Your subject contained 2 elements.
cy.get('item1').click();
cy.get('item2')
.click({ctrlkey:true})
.trigger('dragstart',{dataTransfer}))
.trigger('drag',{});
cy.get('targetelement')
.trigger('dragover', { dataTransfer })
.trigger('drop', { dataTransfer })
.trigger('dragend', { dataTransfer });
Every drag and drop has some variation, so this might not work for you. See Issue: Move the cursor (Drag and Drop) #845
There isn't a generic answer for this - it depends on what your app is bound to, and what events and properties it's listening for.
If the dragstart event listener is attached to document you can use
cy.document()
.its('documentElement')
.trigger('dragstart', { dataTransfer: {} });
I used this CodePen Mouse Droppings as a basic multi-select drag-and-drop example app.
It has different events, which I've substituted below your events in the test,
dragover changed to dragenter
drop changed to dragleave
but you will use the events applicable to your app.
Hopefully the key principle cy.document().trigger('dragstart', { dataTransfer: {} }) also works with your app.
My test
it('drags and drops multiple items', () => {
cy.visit('http://127.0.0.1:5500/dist/index.html') // CodePen exported and run locally
cy.contains('Item 0').click(); // select 1st item
cy.contains('Item 2').click({ctrlKey:true}); // also select 3rd item
cy.document()
.its('documentElement')
.trigger('dragstart', { dataTransfer: {} })
cy.get('ol').eq(2) // get the target
// .trigger('dragover', { dataTransfer: {} })
.trigger('dragenter', { dataTransfer: {} })
// .trigger('drop', { dataTransfer: {} })
.trigger('dragleave', { dataTransfer: {} })
.trigger('dragend', { dataTransfer: {} });
cy.get('ol').eq(2).contains('Item 0'); // verify 1st item moved
cy.get('ol').eq(2).contains('Item 2'); // verify 3rd item moved
})
The result is items 0 & 2 from the first list end up on the third list.

LitElement with data from Firestore

I've been trying to dynamically insert data from Firestore into my component.
Currently, I'm using the firstUpdated() lifecycle. My code works but it fell like there's a better way of doing this.
This is my current component.
static get properties() {
return {
firebaseData: {type:Object},
}
}
constructor() {
super()
this.firebaseData = {}
}
firstUpdated() {
firestore.doc(`...`).get()
.then(doc => {this.firebaseData = doc.data()})
})
.catch(err => console.error(err))
}
render() {
return html `${firebaseData.title}`
}
I was hope someone with more experience would be open to sharing their knowledge. Thanks in advance!
firstUpdated should be used when you need to interact with shadow DOM elements inside your web component, as they aren't created until then. It's the earliest moment when you can be sure your component DOM exists.
I would prefer to do the firebase call earlier, even in the constructor.
The idea is, your firebase call isn't dependent of the rendering, so you could directly do it at the earliest moment, and as in the callback of the function you update the firebaseData property, a new rendering cycle will be done then.

Polymer 2 - Perform action every time element is shown via iron-pages/iron-selector

I'm attempting to create a logout page that will work even after that element has been attached once to the DOM. This occurs when you get a login, then logout, then login again, and attempt to log back out.
For instance, the shell has
<iron-selector selected="[[page]]" attr-for-selected="name">
<a name="logout" href="[[rootPath]]logout">
<paper-icon-button icon="my-icons:sign-out" title="Logout" hidden$="[[!loggedIn]]"></paper-icon-button>
</a>
<a name="login" href="[[rootPath]]login">
<paper-icon-button icon="my-icons:sign-in" title="Login" hidden$="[[loggedIn]]"></paper-icon-button>
</a>
</iron-selector>
<<SNIP>>
<iron-pages selected="[[page]]" attr-for-selected="name" fallback-selection="view404" role="main">
<my-search name="search"></my-search>
<my-login name="login"></my-login>
<my-logout name="logout"></my-logout>
<my-view404 name="view404"></my-view404>
</iron-pages>
I also have an observer for page changes in the shell:
static get observers() {
return [
'_routePageChanged(routeData.page)',
];
}
_routePageChanged(page) {
this.loggedIn = MyApp._computeLogin();
if (this.loggedIn) {
this.page = page || 'search';
} else {
window.history.pushState({}, 'Login', '/login');
window.dispatchEvent(new CustomEvent('location-changed'));
sessionStorage.clear();
this.page = 'login';
}
}
This works well as when I click on the icon to logout, it attaches the my-logout element just fine and performs what in ready() or connectedCallback() just fine.
my-logout has
ready() {
super.ready();
this._performLogout();
}
The issue comes when, without refreshing the browser and causing a DOM refresh, you log back in and attempt to log out a second time. Since the DOM never cleared, my-logout is still attached, so neither ready() nor connectedCallback() fire.
I've figured out a way of working around this, but it feels very kludgy. Basically, I can add an event listener to the element that will perform this._performLogout(); when the icon is selected:
ready() {
super.ready();
this._performLogout();
document.addEventListener('iron-select', (event) => {
if (event.detail.item === this) {
this._performLogout();
}
});
}
Like I said, it works, but I dislike having a global event listener, plus I have to call the logout function the first time the element attaches and I have to listen as the listener isn't active till after the first time the element is attached.
There does not appear to be a "one size fits all" solution to this. The central question is, "Do you want the parent to tell the child, or for the child to listen on the parent?". The "answer" I came up with in the question works if you want to listen to the parent, but because I don't like the idea of a global event listener, the below is how to use <iron-pages> to tell a child element that it has been selected for viewing.
We add the selected-attribute property to <iron-pages>:
<iron-pages selected="[[page]]" attr-for-selected="name" selected-attribute="selected" fallback-selection="view404" role="main">
<my-search name="search"></my-search>
<my-login name="login"></my-login>
<my-logout name="logout"></my-logout>
<my-view404 name="view404"></my-view404>
</iron-pages>
Yes, this looks a little confusing considering the attr-for-selected property. attr-for-selected says, "What attribute should I match on these child elements with the value of my selected property?" So when I click on
<iron-selector selected="[[page]]" attr-for-selected="name">
<a name="logout" href="[[rootPath]]logout"><paper-icon-button icon="my-icons:sign-out" title="Logout" hidden$="[[!loggedIn]]"></paper-icon-button></a>
</iron-selector>
it will set the <my-logout> internally as the selected element and display it. What selected-attribute="selected" does is to set an attribute on the child element. If you look in the browser JS console, you will see that the element now looks like
<my-login name="login"></my-logout>
<my-logout name="login" class="iron-selected" selected></my-logout>
We can define an observer in that in the <my-logout> element that checks for changes
static get properties() {
return {
// Other properties
selected: {
type: Boolean,
value: false,
observer: '_selectedChanged',
},
};
}
_selectedChanged(selected) {
if (selected) {
this._performLogout();
}
}
The if statement is so that we only fire the logic when we are displayed, not when we leave. One advantage of this is that we don't care if the element has already been attached to the DOM or not. When <iron-selector>/<iron-pages> selects the <my-logout> the first time, the attribute is set, the element attaches, the observer fires, the observer sees that selected is now true (as opposed to the defined false) and runs the logic.

How to seperate Vue logic in a laravel app based on layout and page templates

I have a laravel app and a Vue instance attached to the body (or a div, just inside the body).
const app = new Vue({
el: '#app'
});
I think it makes sense to use the Vue instance for stuff relating to the layout (eg header, nav, footer logic).
Now I have a form that is visible on a specific route (e.g. example.com/thing/create). I want to add some logic to it, e.g. hiding a field based on selected option in the form. It is logic meant for just this form (not to be reused). I prefer not to put all the logic inline with the form but put it in the app.js. I could put it in the Vue instance bound to the body but that sounds odd as it only applies to the form that is much deeper into the dom.
I want to leave the markup of the form in the blade template (that inherits the layout).
I tried creating a component but am not sure how to bind this inside the main Vue instance. What is the best way to handle things for this form, put it in the app.js and have it somewhat structured, putting the variables somewhat into scope. Or is it really necessary to remove the main Vue instance bound to the full layout code?
What I tried was something like this, but it does not work (attaching it to the <form id="object-form"> seems to fail:
var ObjectForm = {
template: function() { return '#object-form'},
data: function() {
return {
selectedOption: 1
}
},
computed: {
displayField: function() {
// return true or false depending on form state
return true;
}
}
};
Things do work if I remove the #app Vue instance or when I put everything directly in the app Vue instance. But that seems messy, if I have similar variables for another form they should be seperated somewhat.
I would appreciate some advice regarding the structure (differentiate page layout and page specific forms) and if possible some example to put the form logic inside the main app.js.
I hope this helps kind of break things down for you and helps you understand Vue templating.
It is best to take advantage of Vue's components. For you it would look something like this. Some of this code depends on your file structure, but you should be able to understand it.
In your app.js file (or your main js file)
Vue.component('myform',require('./components/MyForm.vue'));
const app = new Vue({
el: "#app"
});
Then create the MyForm.vue file
<template>
<form>
Put Your Form Markup Here
</form>
</template>
<script>
// Here is where you would handle the form scripts.
// Use methods, props, data to help set up your component
module.exports = {
data: function() {
return {
selectedOption: 1
}
},
computed: {
displayField: function() {
// return true or false depending on form state
return true;
}
},
methods: {
// add methods for dynamically changing form values
}
}
</script>
Then you will be able to just call in your blade file.
<myform></myform>
I found out how to do it. The trick was to use an inline template. Surround the form in the view with:
<object-form inline-template>
<form>...</form>
</object-form>
Where object-form is the name of the component. In the ObjectForm code above I remove the template, like this:
var ObjectForm = {
data: function() {
return {
selectedOption: 1
}
},
computed: {
displayField: function() {
// return true or false depending on form state
return true;
}
}
};
I attach the component within the root vue app like this:
const app = new Vue({
el: 'body',
components: {
'object-form': ObjectForm
}
});
This way I can use the form as it was generated from the controller and view and I can separate it from the root (attached to body) methods and properties.
To organize it even better I can probably store the ObjectForm in a seperate .vue file the way #Tayler Foster suggested.

Join two observables in RX.js

I'm trying to create new observable based on two others. I have:
var mouseClickObservable = Rx.Observable.fromEvent(this.canvas, "click");
var mouseMoveObservable = Rx.Observable.fromEvent(this.canvas, "mousemove");
function findObject(x, y) {/* logic for finding object under cursor here. */}
var objectUnderCursor = this.mouseMoveObservable.select(function (ev) {
return findObject(ev.clientX, clientY);
});
I want to create objectClicked observable, that should produce values when user clicks on an object. I could just call findObject again, like this:
var objectClicked = this.mouseClickObservable.select(function (ev) {
return findObject(ev.clientX, clientY);
});
but it's very time-consuming function.
Another way, which I currently use, is to store last hovered object in a variable, but I assume, there should be pure functional way of doing this. I tryed to use Observable.join like this:
var objectClicked = this.objectUnderCursor.join(
mouseClickObservable,
function (obj) { return this.objectUnderCursor },
function (ev) { return Rx.Observable.empty() },
function (obj, ev) { return obj })
but it produces multiple values for one click
I don't see any code where you actually subscribe to any of these observables you have defined, so it is hard to provide a good answer. Do you actually need to call findObject on every mouse move? Are you needing to provide some sort of hover effect as the mouse moves? Or do you just need to know the object that was clicked, in which case you only need to call findObject once when clicked?
Assuming you only need to know what object was clicked, you don't even worry about mouse moves and just do something like:
var objectClicked = mouseClickObservable
.select(function (ev) { return findObject(ev.clientX, ev.clientY); });
objectClicked.subscribe(function(o) { ... });
If you indeed need to know what object the mouse is hovering over, but want to avoid calling your expensive hit test also on a click, then indeed you need to store the intermediate value (which you are needing to store anyway to do your hovering effects). You can use a BehaviorSubject for this purpose:
this.objectUnderCursor = new Rx.BehaviorSubject();
mouseMoveObservable
.select(function (ev) { return findObject(ev.clientX, ev.clientY); })
.subscribe(this.objectUnderCursor);
this.objectUnderCursor.subscribe(function (o) { do your hover effects here });
mouseClickObservable
.selectMany(function () { return this.objectUnderCursor; })
.subscribe(function (o) { do your click effect });