Can't swap images in a ngx-gallery - javascript

I'm having a little issue using ngx-gallery Here is the github page and my stackblitz example.
Scenario - I want my user click a button to swap the images around to the first image in the gallery.
Ex. User clicks button and moves the image from position 3 to image position 1. Including the small thumbnail, the medium image (main viewer) and the big preview image.
Problem - Everything I've tried doesn't seem to work. I can't really find any methods that swap the indexes and when I swap them manually nothing happens.
FYI - I can add and delete images to the viewer with push and pop, I just can't set (swap) the first image programmatically with another.
stackblitz example
Here is some of the examples I've tried.
export class AppComponent implements OnInit {
#ViewChild('gallery') gallery: NgxGalleryComponent;
galleryOptions: NgxGalleryOptions[];
galleryImages: NgxGalleryImage[];
constructor() {}
ngOnInit() {
this.galleryOptions = [{
width: '600px',
height: '400px',
thumbnailsColumns: 4,
arrowPrevIcon: 'fa fa-chevron-left',
arrowNextIcon: 'fa fa-chevron-right',
imageAnimation: NgxGalleryAnimation.Slide
}
];
this.galleryImages = [{
small: 'https://preview.ibb.co/jrsA6R/img12.jpg',
medium: 'https://preview.ibb.co/jrsA6R/img12.jpg',
big: 'https://preview.ibb.co/jrsA6R/img12.jpg'
},
{
small: 'https://preview.ibb.co/kPE1D6/clouds.jpg',
medium: 'https://preview.ibb.co/kPE1D6/clouds.jpg',
big: 'https://preview.ibb.co/kPE1D6/clouds.jpg'
},
{
small: 'https://preview.ibb.co/mwsA6R/img7.jpg',
medium: 'https://preview.ibb.co/mwsA6R/img7.jpg',
big: 'https://preview.ibb.co/mwsA6R/img7.jpg'
}, {
small: 'https://preview.ibb.co/kZGsLm/img8.jpg',
medium: 'https://preview.ibb.co/kZGsLm/img8.jpg',
big: 'https://preview.ibb.co/kZGsLm/img8.jpg'
},
];
}
swap() {
console.log("button clicked!");
// doesn't do anything
[this.galleryImages[2], this.galleryImages[0]] = [this.galleryImages[0], this.galleryImages[2]];
// doesn't do anything
[this.gallery.thumbnails.images[2], this.gallery.thumbnails.images[0]] = [this.gallery.thumbnails.images[0], this.gallery.thumbnails.images[2]];
// doesn't do anything
[this.gallery.images[2], this.gallery.images[0]] = [this.gallery.images[0], this.gallery.images[2]];
}
}
<div class="gallery-wrapper">
<ngx-gallery #gallery [options]="galleryOptions" [images]="galleryImages" class="ngx-gallery"></ngx-gallery>
</div>
<button (click)="swap()">swap image 1 and 3</button>

This may be because you are mutating the array. Sometimes Angular change detection only kicks in when you do not mutate.
Mutating happens when you change the array (the items in the array or the order of items in the array) but do not change the array reference.
To avoid mutating try:
this.galleryImages = [this.galleryImages[2], this.galleryImages[1], this.galleryImages[0]]
Alternatively, even when you do mutate an Array you can solve the problem by running lodash cloneDeep afterwards, which will get you a new reference after mutating:
import { cloneDeep } from 'lodash-es'
// your existing code
this.galleryImages = cloneDeep(this.galleryImages)
Note that there are some decent npm packages for changing the position of items in an array such as array-move - this avoids mutation - note there are other good packages for this too, look for competitors on npm trends

Related

randomizing multiple objects stored in a list.js

Been bashing my head over this for a while. The project I'm working on requires that I display two randomly selected videos from a list of four possible, unique animations, and on the next page, display the correct corresponding textual description for the video selected. Right now, the approach I'm taking is creating a separate list.js file apart from my code, with each video grouped with its corresponding sentence, but as my code is right now, I cannot use the randomization function to randomize all objects at once.
the list.js file.
//two randomly selected animations are shown here as samples
var stims = jsPsych.randomization.factorial(list.js)
for (const i of stims) {
var video = "video/" + i[video] + ".mp4"
var description = {
type: "html-keyboard-response",
stimulus: [
i["sentence"] +
"<p> Press spacebar to proceed to the next sample animation </p>"
],
choices: [' ']
}
var experience = {
timeline:
[
{
type: 'video',
width: 600,
data: {
subject: code,
},
sources: [video]
}
]
}
timeline.push(fixation);
timeline.push(experience);
timeline.push(description);
}
above is the pertinent code in my experiment.

Not able to make sprite interaction to work

I'm trying to build a simple game menu, containing some clickable sprites, which will be used as buttons to navigate around the menu.
( I'm using the latest pixi.js (v4.3.5) )
Structure of my app:
loader.module ( makes use of the pixi.loaders.Loader )
events.module (basic event sub/pub module)
base.view
menu.view ( extends base.view )
game.main
How it all works now ?
Both all resources and ui elements have to be explicitly defined, before initializing the view.
so in the menu.view, the follwoing attributes have to be defined.
this.resources = [
{ name: 'start', src: 'img/start.png'},
{ name: 'start2', src: 'img/start2.png'}
];
this.ui = [{
name: 'start', /// resource name
type: 'img',
pos: { x: 0, y: 0 }
}];
Now I only need to call view.init() to get it all loaded and drawn. On the visual side, evrything works perfectly, however the 'start' sprite (which has it's interactive and buttonMode set to true) is not reacting to any mouse events.
The below method is responsible for getting the required resource and returning a new sprite. It also enables the actual interaction functionality as part of this process. But the test function is never triggered for some reason.
__getSpriteObject( element ){
let sprite = new PIXI.Sprite( this.loader.loader.resources[ element.name ].texture );
sprite.x = element.pos.x;
sprite.y = element.pos.y;
sprite.interactive = true;
sprite.buttonMode = true;
console.log( sprite )
sprite.on('pointerdown', function(){
console.log("what")
})
return sprite;
}
If the above info isn't sufficient , here is also a working example.
I answered this here: http://www.html5gamedevs.com/topic/28474-not-able-to-make-sprite-interaction-to-work/?do=findComment&comment=163647 in any case anyone else is curious

How to auto-slide the window out from behind keyboard when TextInput has focus?

I've seen this hack for native apps to auto scroll the window, but wondering best way to do it in React Native... When a <TextInput> field gets focus and is positioned low in the view, the keyboard will cover up the text field.
You can see this issue in example UIExplorer's TextInputExample.js view.
Does anyone have a good solution?
2017 Answer
The KeyboardAvoidingView is probably the best way to go now. Check out the docs here. It is really simple compared to Keyboard module which gives Developer more control to perform animations. Spencer Carli demonstrated all the possible ways on his medium blog.
2015 Answer
The correct way to do this in react-native does not require external libraries, takes advantage of native code, and includes animations.
First define a function that will handle the onFocus event for each TextInput (or any other component you would like to scroll to):
// Scroll a component into view. Just pass the component ref string.
inputFocused (refName) {
setTimeout(() => {
let scrollResponder = this.refs.scrollView.getScrollResponder();
scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
React.findNodeHandle(this.refs[refName]),
110, //additionalOffset
true
);
}, 50);
}
Then, in your render function:
render () {
return (
<ScrollView ref='scrollView'>
<TextInput ref='username'
onFocus={this.inputFocused.bind(this, 'username')}
</ScrollView>
)
}
This uses the RCTDeviceEventEmitter for keyboard events and sizing, measures the position of the component using RCTUIManager.measureLayout, and calculates the exact scroll movement required in scrollResponderInputMeasureAndScrollToKeyboard.
You may want to play around with the additionalOffset parameter, to fit the needs of your specific UI design.
Facebook open sourced KeyboardAvoidingView in react native 0.29 to solve this problem. Documentation and usage example can be found here.
We combined some of the code form react-native-keyboard-spacer and the code from #Sherlock to create a KeyboardHandler component that can be wrapped around any View with TextInput elements. Works like a charm! :-)
/**
* Handle resizing enclosed View and scrolling to input
* Usage:
* <KeyboardHandler ref='kh' offset={50}>
* <View>
* ...
* <TextInput ref='username'
* onFocus={()=>this.refs.kh.inputFocused(this,'username')}/>
* ...
* </View>
* </KeyboardHandler>
*
* offset is optional and defaults to 34
* Any other specified props will be passed on to ScrollView
*/
'use strict';
var React=require('react-native');
var {
ScrollView,
View,
DeviceEventEmitter,
}=React;
var myprops={
offset:34,
}
var KeyboardHandler=React.createClass({
propTypes:{
offset: React.PropTypes.number,
},
getDefaultProps(){
return myprops;
},
getInitialState(){
DeviceEventEmitter.addListener('keyboardDidShow',(frames)=>{
if (!frames.endCoordinates) return;
this.setState({keyboardSpace: frames.endCoordinates.height});
});
DeviceEventEmitter.addListener('keyboardWillHide',(frames)=>{
this.setState({keyboardSpace:0});
});
this.scrollviewProps={
automaticallyAdjustContentInsets:true,
scrollEventThrottle:200,
};
// pass on any props we don't own to ScrollView
Object.keys(this.props).filter((n)=>{return n!='children'})
.forEach((e)=>{if(!myprops[e])this.scrollviewProps[e]=this.props[e]});
return {
keyboardSpace:0,
};
},
render(){
return (
<ScrollView ref='scrollView' {...this.scrollviewProps}>
{this.props.children}
<View style={{height:this.state.keyboardSpace}}></View>
</ScrollView>
);
},
inputFocused(_this,refName){
setTimeout(()=>{
let scrollResponder=this.refs.scrollView.getScrollResponder();
scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
React.findNodeHandle(_this.refs[refName]),
this.props.offset, //additionalOffset
true
);
}, 50);
}
}) // KeyboardHandler
module.exports=KeyboardHandler;
First you need to install react-native-keyboardevents.
In XCode, in the project navigator, right click Libraries ➜ Add
Files to [your project's name] Go to node_modules ➜
react-native-keyboardevents and add the .xcodeproj file
In XCode, in the
project navigator, select your project. Add the lib*.a from the keyboardevents
project to your project's Build Phases ➜ Link Binary With Libraries Click
.xcodeproj file you added before in the project navigator and go the Build
Settings tab. Make sure 'All' is toggled on (instead of 'Basic').
Look for Header Search Paths and make sure it contains both
$(SRCROOT)/../react-native/React and $(SRCROOT)/../../React - mark
both as recursive.
Run your project (Cmd+R)
Then back in javascript land:
You need to import the react-native-keyboardevents.
var KeyboardEvents = require('react-native-keyboardevents');
var KeyboardEventEmitter = KeyboardEvents.Emitter;
Then in your view, add some state for the keyboard space and update from listening to the keyboard events.
getInitialState: function() {
KeyboardEventEmitter.on(KeyboardEvents.KeyboardDidShowEvent, (frames) => {
this.setState({keyboardSpace: frames.end.height});
});
KeyboardEventEmitter.on(KeyboardEvents.KeyboardWillHideEvent, (frames) => {
this.setState({keyboardSpace: 0});
});
return {
keyboardSpace: 0,
};
},
Finally, add a spacer to your render function beneath everything so when it increases size it bumps your stuff up.
<View style={{height: this.state.keyboardSpace}}></View>
It is also possible to use the animation api, but for simplicity's sake we just adjust after the animation.
react-native-keyboard-aware-scroll-view solved the problem for me.
react-native-keyboard-aware-scroll-view on GitHub
Try this:
import React, {
DeviceEventEmitter,
Dimensions
} from 'react-native';
...
getInitialState: function() {
return {
visibleHeight: Dimensions.get('window').height
}
},
...
componentDidMount: function() {
let self = this;
DeviceEventEmitter.addListener('keyboardWillShow', function(e: Event) {
self.keyboardWillShow(e);
});
DeviceEventEmitter.addListener('keyboardWillHide', function(e: Event) {
self.keyboardWillHide(e);
});
}
...
keyboardWillShow (e) {
let newSize = Dimensions.get('window').height - e.endCoordinates.height;
this.setState({visibleHeight: newSize});
},
keyboardWillHide (e) {
this.setState({visibleHeight: Dimensions.get('window').height});
},
...
render: function() {
return (<View style={{height: this.state.visibleHeight}}>your view code here...</View>);
}
...
It worked for me. The view basically shrinks when the keyboard is displayed, and grows back again when its hidden.
Just wanted to mention, now there is a KeyboardAvoidingView in RN. Just import it and use it as any other module in RN.
Here is the link to the commit on RN:
https://github.com/facebook/react-native/commit/8b78846a9501ef9c5ce9d1e18ee104bfae76af2e
It is available from 0.29.0
They have also included an example on UIExplorer.
Maybe is to late, but the best solution is to use a native library, IQKeyboardManager
Just drag and drop IQKeyboardManager directory from demo project to your iOS project. That's it. Also you can setup some valus, as isToolbar enabled, or the space between text input and keyboard in the AppDelegate.m file. More details about customisation are in the GitHub page link that I've added.
I used TextInput.onFocus and ScrollView.scrollTo.
...
<ScrollView ref="scrollView">
...
<TextInput onFocus={this.scrolldown}>
...
scrolldown: function(){
this.refs.scrollView.scrollTo(width*2/3);
},
#Stephen
If you don't mind not having the height animate at exactly the same rate that the keyboard appears, you can just use LayoutAnimation, so that at least the height doesn't jump into place. e.g.
import LayoutAnimation from react-native and add the following methods to your component.
getInitialState: function() {
return {keyboardSpace: 0};
},
updateKeyboardSpace: function(frames) {
LayoutAnimation.configureNext(animations.layout.spring);
this.setState({keyboardSpace: frames.end.height});
},
resetKeyboardSpace: function() {
LayoutAnimation.configureNext(animations.layout.spring);
this.setState({keyboardSpace: 0});
},
componentDidMount: function() {
KeyboardEventEmitter.on(KeyboardEvents.KeyboardDidShowEvent, this.updateKeyboardSpace);
KeyboardEventEmitter.on(KeyboardEvents.KeyboardWillHideEvent, this.resetKeyboardSpace);
},
componentWillUnmount: function() {
KeyboardEventEmitter.off(KeyboardEvents.KeyboardDidShowEvent, this.updateKeyboardSpace);
KeyboardEventEmitter.off(KeyboardEvents.KeyboardWillHideEvent, this.resetKeyboardSpace);
},
Some example animations are (I'm using the spring one above):
var animations = {
layout: {
spring: {
duration: 400,
create: {
duration: 300,
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.opacity,
},
update: {
type: LayoutAnimation.Types.spring,
springDamping: 400,
},
},
easeInEaseOut: {
duration: 400,
create: {
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.scaleXY,
},
update: {
type: LayoutAnimation.Types.easeInEaseOut,
},
},
},
};
UPDATE:
See #sherlock's answer below, as of react-native 0.11 the keyboard resizing can be solved using built in functionality.
You can combine a few of the methods into something a little simpler.
Attach a onFocus listener on your inputs
<TextInput ref="password" secureTextEntry={true}
onFocus={this.scrolldown.bind(this,'password')}
/>
Our scroll down method looks something like :
scrolldown(ref) {
const self = this;
this.refs[ref].measure((ox, oy, width, height, px, py) => {
self.refs.scrollView.scrollTo({y: oy - 200});
});
}
This tells our scroll view (remember to add a ref) to scroll to down to the position of our focused input - 200 (it's roughly the size of the keyboard)
componentWillMount() {
this.keyboardDidHideListener = Keyboard.addListener(
'keyboardWillHide',
this.keyboardDidHide.bind(this)
)
}
componentWillUnmount() {
this.keyboardDidHideListener.remove()
}
keyboardDidHide(e) {
this.refs.scrollView.scrollTo({y: 0});
}
Here we reset our scroll view back to the top,
I'm using a simpler method, but it's not animated yet. I have a component state called "bumpedUp" which I default to 0, but set to 1 when the textInput gets focus, like this:
On my textInput:
onFocus={() => this.setState({bumpedUp: 1})}
onEndEditing={() => this.setState({bumpedUp: 0})}
I also have style that gives the wrapping container of everything on that screen a bottom margin and negative top margin, like this:
mythingscontainer: {
flex: 1,
justifyContent: "center",
alignItems: "center",
flexDirection: "column",
},
bumpedcontainer: {
marginBottom: 210,
marginTop: -210,
},
And then on the wrapping container, I set the styles like this:
<View style={[styles.mythingscontainer, this.state.bumpedUp && styles.bumpedcontainer]}>
So, when the "bumpedUp" state gets set to 1, the bumpedcontainer style kicks in and moves the content up.
Kinda hacky and the margins are hardcoded, but it works :)
I use brysgo answer to raise the bottom of my scrollview. Then I use the onScroll to update the current position of the scrollview. I then found this React Native: Getting the position of an element to get the position of the textinput. I then do some simple math to figure out if the input is in the current view. Then I use scrollTo to move the minimum amount plus a margin. It's pretty smooth. Heres the code for the scrolling portion:
focusOn: function(target) {
return () => {
var handle = React.findNodeHandle(this.refs[target]);
UIManager.measureLayoutRelativeToParent( handle,
(e) => {console.error(e)},
(x,y,w,h) => {
var offs = this.scrollPosition + 250;
var subHeaderHeight = (Sizes.width > 320) ? Sizes.height * 0.067 : Sizes.height * 0.077;
var headerHeight = Sizes.height / 9;
var largeSpace = (Sizes.height - (subHeaderHeight + headerHeight));
var shortSpace = largeSpace - this.keyboardOffset;
if(y+h >= this.scrollPosition + shortSpace) {
this.refs.sv.scrollTo(y+h - shortSpace + 20);
}
if(y < this.scrollPosition) this.refs.sv.scrollTo(this.scrollPosition - (this.scrollPosition-y) - 20 );
}
);
};
},
I also meet this question. Finally, I resolve it by defining the height of each scene, such as:
<Navigator
...
sceneStyle={{height: **}}
/>
And, I also use a third-party module https://github.com/jaysoo/react-native-extra-dimensions-android to get the real height.

clicking items inside a famo.us scrollview

I have a scrollview with a number of images.
events are working such that the scrollview can be dragged around.
i want to be able to click on a single image to get a detail view so used a:
surface.on 'click', => #parent.navTo('detail')
however, this has the effect that if i click an image when scrolling the above event will also fire.
i guess this is the whole reason mobile browsers have that 300ms delay - to tell if you're clicking or dragging. does Famous have other events to listen for?
In inputs/FastClick.js i only see 'touchstart' 'touchmove' and 'touchend'
do we have to track if a drag motion happened, in our own code, or does the famous engine assist with this?
FWIW i'm using a GenericSync to pipe the events around, and to make the view also work on the desktop.
constructor: (#parentView, #data) ->
SCROLLDIR = 1 # 0 horiz, 1 vertical
super({
direction: SCROLLDIR
paginated: true
pageStopSpeed: 5
})
#addContent()
#mouseSync = new famous.inputs.MouseSync({direction: SCROLLDIR})
#mouseSync.pipe(this)
addContent: () ->
comics = Comics.find()
surfaces = []
#sequenceFrom(surfaces)
for item in comics.fetch()
div = document.createElement('div')
comp = UI.renderWithData(Template.comicCover, item)
UI.insert(comp, div)
surface = new famous.core.Surface({
content: div
size: [undefined, 400]
properties:
backgroundColor: "#eff"
})
surfaces.push(surface)
surface.pipe(this)
surface.on 'click', => #parentView.navTo('comicPages')
# surface.pipe(#mouseSync)
return #surface
I have encountered a similar issue. To get around it, I simply track when the scrollview is scrolling and then ensure not scrolling on click.
Here is the code that I would add.. Hope it helps!
# In constructor
this.sync.on 'update', () => #scrolling = true
this.sync.on 'end', () => #scrolling = false
# In addContent
surface.on 'click', () =>
if !#scrolling
#parentView.navTo('comicPages')

How do I morph a class with Scripty 2?

In Scriptaculous 1, you could animate styles:
new Effect.Morph('id', {
style: { background: tomato },
duration: '4' });
But a better way was to keep the CSS and JS separate and merely reference a class:
new Effect.Morph('id', {
style: 'important',
duration: '4' });
Marvellous. But this doesn't seem to work with the new Scripty 2. Works:
$('id').morph('background: tomato', { duration: 4 });
Breaks:
$('id').morph('important', { duration: 4 });
What is the right way to animate using a class in Scripty 2? (I suspected Style, but the docs were vague.)
I checked out the source code and s2 only takes 'styleProp:value' for the style option. The string needs to have a colon.
The only method that will additionally take the class name as well 'styleProp:value' for the style option is a method called S2.FX.Operators.WebkitCssTransition. However, the S2.Extensions.webkitCSSTransitions are turned off by default. Although, the code in that method to be used to make your own patch to the .Morph method.

Categories

Resources