Aframe component with dependencies on component with multiple true - aframe

I am writing a custom component that I would like to define other component dependencies.
The dependencies are different animations types.
Let's say they have the names "animation__x" and "animation__y"
x and y can be any name, so I am looking for something like animation__*
or /animation__\s*/
The only way I have made this work at the moment is either ensuring my component is placed after the animation components on the HTML or alternatively to force update components using this.el.updateComponents()
Neither of these solutions feels right to me.
AFRAME.registerComponent('cool-component', {
dependencies: ['animation'],
update: functions(data){
//detect available animations and do some stuff with them
let animations = Object.keys(components).filter((key) => {
return /(^animation__\w*)/.test(key);
});
//animations results in an empty array
}
});
html that is not working
<a-scene cool-component animation__x="" animation__y="" animation__z=""></a-scene>
html that is working (but its not good as I cant ensure my component is always last in the list
<a-scene animation__x="" animation__y="" animation__z="" cool-component></a-scene>
js that works, but doesnt feel write as I am using the entities internal functions
AFRAME.registerComponent('cool-component', {
dependencies: ['animation'],
update: functions(data){
this.el.updateComponents(); //<-- I DONT LIKE THIS BUT IT WORKS
//detect available animations and do some stuff with them
//now all animations are available as this.el.components
let animations = Object.keys(components).filter((key) => {
return /(^animation__\w*)/.test(key);
});
}
});

Three options:
Depend on the specific component names: dependencies: ['animation__xxx']
Make cool-component set those animations:
AFRAME.registerComponent('cool-component', {
init: functions(data){
this.el.setAttribute('animation__xxx', {...});
}
});
You can also defer cool-component logic until the entity has loaded and all the components have initialized:
init: function () {
this.el.addEvenListener(‘loaded’, this.doStuffAferComponentsLoad.bind(this));
}
More details in what cool-component is trying to accomplish will help to get a more precise answer.

Related

How to use react-jss within react class Components?

In react-jss documentation, the authors have written:
'HOC based API is deprecated as of v10 and will be removed in v11.'
This means, as far as I understand, that such HOC functionality as injectSheet and withStyles will no longer be available in V11.
The new react-based stylesheet generating functions seem to be all based on react hooks. The function createUseStyles seemed very promising to myself and my team, until upon looking further into the source code we realised that it was only available within functional components, as it makes use of hooks.
The Problem
As a team we still make heavy use of React Class components and have no plans to move completely to hooks, not because hooks aren't useful, but because sometimes functional components aren't the best or most organised solution to writing a component.
Perhaps I'm missing something-- but it seems like there is now no solution left for React Class based components, other than writing our own manual implementation from core jss.
What solutions are there for a developer to make use of react-jss in a way similar to that achieved by createUseStyles, keeping up with the latest version of react-jss, being able to pass dynamic props, and etc. without writing a manual implementation?
While not specific to JSS, keep in mind that you can always use a tiny wrapper to convert any Hook to render prop or a HOC.
Converting Hook to a render prop is described here: https://reacttraining.com/blog/using-hooks-in-classes/
You can use a similar approach to convert any Hook to a HOC.
import { Classes } from 'jss';
import { createUseStyles } from 'react-jss';
First, lets create a more type safe function for creating styles.
export function createStyles(classes: { [name: string]: Partial<CSSStyleDeclaration> }) {
return createUseStyles(classes as any);
}
Secondly, we'll create a simple wrapper to allow hooks for our components.
function Styles<T extends string | number | symbol>(props: { styles: () => Classes<T>, children: (classes: Classes<T>) => ReactElement }) {
const classes = props.styles();
return props.children(classes);
}
Example
const styles = createStyles({
title: {
fontSize: '25px',
textTransform: 'uppercase'
},
message: {
color: 'red'
}
});
export const App = () => (
<Styles styles={styles}>
{classes => (
<Fragment>
<h1 className={classes.title}>Title</h1>
<p className={classes.message}>message</p>
</Fragment>
)}
</Styles>
);
Output

Custom background for Chrome new tab replacement extension

I'm developing a new tab replacement extension for Google Chrome and I'd like to allow the user to customize the background, to do so I'm using the storage.sync API as suggested by this page.
The problem is that the style changes are applied asynchronously, so the default background (white) is briefly used during the page load resulting in unpleasing flashes.
Possible (unsatisfying) solutions are:
do not allow to change the background;
hard code a black background in the CSS (and move the problem to custom light backgrounds);
use a CSS transition (still super-ugly).
What could be an alternative approach?
Follows a minimal example.
manifest.json
{
"manifest_version": 2,
"name": "Dummy",
"version": "0.1.0",
"chrome_url_overrides": {
"newtab": "newtab.html"
},
"permissions": [
"storage"
]
}
newtab.html
<script src="/newtab.js"></script>
newtab.js
chrome.storage.sync.get({background: 'black'}, ({background}) => {
document.body.style.background = background;
});
I come up with a reasonable solution. Basically since the localStorage API is synchronous we can use it as a cache for storage.sync.
Something like this:
newtab.js
// use the value from cache
document.body.style.background = localStorage.getItem('background') || 'black';
// update the cache if the value changes from the outside (will be used the next time)
chrome.storage.sync.get({background: 'black'}, ({background}) => {
localStorage.setItem('background', background);
});
// this represents the user changing the option
function setBackground(background) {
// save to storage.sync
chrome.storage.sync.set({background}, () => {
// TODO handle error
// update the cache
localStorage.setItem('background', background);
});
}
This doesn't work 100% of the times but neither do the simple:
document.body.style.background = 'black';
So it's good enough.¹
¹ In the real extension I change the CSS variables directly and I obtain much better results than setting the element style.

Adding class to React Component after a certain amount of time

I have a react component:
React.createComponent({
render: function () {
return (<div className="some-component"></div>);
}
});
Some seconds after it renders, I want it to add a class from within the component. The class is for the purposes of revealing the component with an animation. I don't regard it as a real change of state, as it has no affect on the application other than to give the component an animated introduction, so I'm loathed to initiate it from outside of the component via a change of store/state.
How would I do this in simple terms? Something like:
{setTimeout(function () {
this.addClass('show'); //pseudo code
}, 1000)}
Obviously I could use jQuery, but that feels anti-React, and prone to side-effects.
I don't regard it as a real change of state, as it has no affect on the application other than to give the component an animated introduction
A change of state in the component seems the natural and proper solution for this scenario. A change in a component state triggers a re-render, which is exactly what you need here. Consider that we're talking about the state of your component, not of your application here.
In React, you don't deal with the DOM directly (e.g. by using jQuery), instead your component state should "drive" what's rendered, so you let React "react" to changes in state/props and update the DOM for you to reflect the current state:
React.createComponent({
componentDidMount () {
this.timeoutId = setTimeout(function () {
this.setState({show: true});
}.bind(this), 1000);
}
componentWillUnmount () {
if (this.timeoutId) {
clearTimeout(this.timeoutId);
}
}
render: function () {
return (<div className={this.state.show ? 'show' : null}></div>);
}
});
When using setTimeout in React you need to be careful and make sure to cancel the timeout when the component gets unmounted, otherwise your timeout callback function will run anyway if the timeout is still pending and your component gets removed.
If you need to perform an initial mount animation or more complicated animations, consider using ReactCssTransitionGroup, which handles timeouts and other things for you out of the box: https://facebook.github.io/react/docs/animation.html

react css animation when component mounts

Here's a fiddle of what I want to do: https://jsfiddle.net/s7s07chm/7/
But I want to do this with react instead of jquery. Basically, I put the className of the element in the state, and on componentDidMount I update the className to initiate the transition.
But this isn't working. The component is just rendering with the transitioned state. In other words, instead of sliding down, it appears at the bottom from the beginning
Am I doing this wrong?
If so, is there another way to accomplish this?
here's the actual code
getInitialState: function() {
return {
childClass: 'child'
};
},
componentDidMount: function() {
this.setState({
childClass: 'child low'
});
},
the reason that won't work is because your DOM won't be updated until the component is mounted. So the class you're assigning with getInitialState will never appear in the DOM, but the one you set with componentDidMount will. As Ray mentioned, you should take a look at ReactCSSTransitionGroup.
componentDidMount is called after React hands them off to the browser, but the browser might not have finished drawing.
You can however use requestAnimationFrame to ensure setState is called after the browser has finished drawing the component.
componentDidMount() {
requestAnimationFrame(() => this.setState({
childClass: 'child low'
}))
}

Ember.js Router: How to animate state transitions

Has somebody found a good way to animate state transitions?
The router immediately removes the view from the DOM. The problem with that is that I can't defer that until the end of the animation. Note: I'm using v1.0.0-pre.4.
Billy's Billing just released an Ember module that supports animated transitions.
I'll expand on Lesyk's answer. If you need to apply it to multiple views in a DRY way, you can create a customization class like this:
App.CrossfadeView = {
didInsertElement: function(){
//called on creation
this.$().hide().fadeIn(400);
},
willDestroyElement: function(){
//called on destruction
this.$().slideDown(250);
}
};
And then in your code you apply it on your various view classes. As Ember depends on jQuery you can use pretty much any jQuery animation.
App.IndexView = Ember.View.extend(App.CrossfadeView);
App.PostView = Ember.View.extend(App.CrossfadeView);
I know this is pretty old, but the best solution for this context-specific animation today is probably ember liquid fire.
It allows you to do things like this in a transition file:
export default function(){
this.transition(
this.fromRoute('people.index'),
this.toRoute('people.detail'),
this.use('toLeft'),
this.reverse('toRight')
);
};
Ran into this same requirement on my app. Tried Ember Animated Outlet, but didn't give the granularity I needed (element specific animations).
The solution that worked for me was as follows --
Change linkTo to be an action
{{#linkTo "todos"}}<button>Todos</button>{{/linkTo}}
Becomes...
<a href="#/todos" {{action "goToTodos"}}><button>Todos</button></a>
Create Method for goToTodos in current controller
App.IndexController = Ember.Controller.extend({
goToTodos: function(){
// Get Current 'this' (for lack of a better solution, as it's late)
var holdThis = this;
// Do Element Specific Animation Here
$('#something').hide(500, function(){
// Transition to New Template
holdThis.transitionToRoute('todos');
});
}
});
Finally -- To animate in elements on the Todos Template, use didInsertElement on the view
App.TodosView = Ember.View.extend({
didInsertElement: function(){
// Hide Everything
this.$().hide();
// Do Element Specific Animations Here
$('#something_else').fadeIn(500);
}
});
So far, this is the most elegant solution I've found for element specific animations on transition. If there is anything better, would love to hear!
I've found another drop-in solution that implements animations in Views: ember-animate
Example:
App.ExampleView = Ember.View.extend({
willAnimateIn : function () {
this.$().css("opacity", 0);
},
animateIn : function (done) {
this.$().fadeTo(500, 1, done);
},
animateOut : function (done) {
this.$().fadeTo(500, 0, done);
}
}
Demo: author's personal website
App.SomeView = Ember.View.extend({
didInsertElement: function(){
//called on creation
this.$().hide().fadeIn(400);
},
willDestroyElement: function(){
//called on destruction
this.$().slideDown(250)
}
});

Resources