Ionic 3 - How to prevent the user from clicking slide pager from slide 0 to slide 2 if slide 1 is not answered - ionic-framework

I am working on a Ionic 3 questionnaire application where the user cannot go from one slide to another until the question is answered on a slide. I got everything working except pager (this dots) is allowing the user to go from one slide to another even though question# 2 is not answered.
I added the following logic but its not working as expected. Its still allowing me to jump from slide 0 to slide 2. Adding this.slideTo(this.currentIndex) changed the dot to be highlighted for slide 0 however its showing the contents of Slide# 2.
onSlideWillChange(event) {
let answerNotSelected: boolean = false;
for (let i: number = 0; i < this.slides.getActiveIndex(); i++) {
answerNotSelected = this.questionnaire.questions[i].selectedAnswer === undefined;
if (answerNotSelected) {
console.log('Returning from newQuestionIndex ' + this.slides.getActiveIndex() + ' to current slide:' + this.currentQuestionIndex);
this.slideTo(this.currentQuestionIndex);
}
} }

You could just lock the slides, and only enable back when the question has an answer. That way, the pager won't change the current slide (It would just be there to give the user some feedback about how many other questions are there in the questionnaire):
import { Component, ViewChild } from '#angular/core';
import { NavController, Content, Slides } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'app/home.page.html'
})
export class HomePage {
#ViewChild(Slides) slides: Slides;
ngOnInit() {
this.slides.lockSwipes(true); // Lock the slides
}
public showPrevious(): void {
this.slides.lockSwipes(false); // Unlock the slides
this.slides.slidePrev(500); // Move the the previous
this.slides.lockSwipes(true); // Lock the slides again
}
public showNext(): void {
this.slides.lockSwipes(false); // Unlock the slides
this.slides.slideNext(500); // Move the the next
this.slides.lockSwipes(true); // Lock the slides again
}
}
Please take a look at this working plunker for a demo.

I had the same problem - for anyone in the future I solved it in a albeit slightly hacky way (since _paginationContainer is an internal variable). You could probably also as easily just find elements in the DOM.
I called this on
ionSlideWillChange
, but it could probably be called on any of the swipe events.
ion-slide is very poorly documented, but it is based off of http://idangero.us/swiper/api/ and has all the same methods so you can look here for better documentation.
lockAll() {
var current = this.slider.getActiveIndex();
let array = this.slider._paginationContainer.childNodes
for (let index = 0; index < array.length; index++) {
var button : any = array[index];
if (this.inRange(index, current -1, current +1)) {
button.disabled = false;
}
else {
button.disabled = true
}
}
}
inRange(x, min, max) {
return ((x-min)*(x-max) <= 0);
}

Related

Is it possible to handle swipe gestures in PWA application?

I'm creating a PWA, ASP server side and JS client side.
Users interact nicely with it using buttons.
The boss ask me if we can implement something like "scroll between app screen" or "perform some operation (edit, delete..) on elements" using the swipe gesture, as many native apps do.
Is there an easy way? or any way anyhow?
Thanks!
There are a couple of libraries that can help implement touch gestures for PWAs - have a look at Hammerjs:
https://hammerjs.github.io/
Your question is fairly generic though, there might be better solutions but that's just one off the top of my head
Have a drawer component in a PWA that can swipe to close using similar JS as below. Made an example that logs out the direction of a swipe / gesture here: https://jsfiddle.net/jamiesmith/e9gndqpc/3/
Below checks a function called ignoreSwipe so we can add a class of ignoreSwipe to some element(s) we specifically want to ignore gestures from.
Some standards below makes use of:
TouchEvent.touches - https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches
TouchEvent.touchstart & touchmove - https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
let _xDown, _yDown;
document.querySelector('div.app')
.addEventListener(
'touchstart',
handleTouchStart,
false
);
document.querySelector('div.app')
.addEventListener(
'touchmove',
handleTouchMove,
false
);
function ignoreSwipe(event) {
// if some touches come from elements with ignoreswipe class > ignore
return Array.from(event.touches).some((t) =>
t.target.classList.contains('noswipe')
);
}
function handleTouchStart(event) {
if (ignoreSwipe(event)) {
_xDown = undefined;
_yDown = undefined;
return;
}
const firstTouch = event.touches[0];
_xDown = firstTouch.clientX;
_yDown = firstTouch.clientY;
}
function handleTouchMove(event) {
if (!_xDown || !_yDown) {
return;
}
const xUp = event.touches[0].clientX;
const yUp = event.touches[0].clientY;
const xDiff = _xDown - xUp;
const yDiff = _yDown - yUp;
if (Math.abs(xDiff) > Math.abs(yDiff)) {
/*most significant*/
if (xDiff > 0) {
/* left swipe */
console.log('app: left swipe ', true);
} else {
/* right swipe */
console.log('app: right swipe ', true);
}
} else {
if (yDiff > 0) {
/* up swipe */
console.log('app: up swipe ', true);
} else {
/* down swipe */
console.log('app: down swipe ', true);
}
}
/* reset values */
_xDown = null;
_yDown = null;
}

Flutter - PageView animatedToPage will load middle page. How to avoid it?

I have a PageView, I want scroll pageView programmatically, so I have two choices:
use animateToPage
use jumpToPage
now, I need smooth transition effect, so I have to use first api. But, I have a problem: animateToPage will load middle pages which don't need to be shown at this time when I scroll from the first page to the last page.(jumpToPage don't have this problem, but I need animation).
How to avoid it?
We can achieve that by
Swap lastPage Widget to next position of current page
Animate to next page
Jump to real lastPage index
Refresh swapped Index to its previous value
In this example, I used fixed PageView children count, which is 8.
Demo
Comparison
Combine to 8th page Button
as CopsOnRoad suggested, this button will trigger Scroll animation to last page (in this case 8th page). Firstly, we
jumpToPage(6), and then animateToPage(7, ..).
This method works, but adversely, user will notice sudden change of current page to 7th page.
Flash Jump to 8th page Button
Unlike like first method, this button will avoid displaying 7th page unnecessarily
Syntax Explanation
this is the main function
void flashToEight() async {
int pageCurrent = pageController.page.round();
int pageTarget = 7;
if (pageCurrent == pageTarget){
return;
}
swapChildren(pageCurrent, pageTarget); // Step # 1
await quickJump(pageCurrent, pageTarget); // Step # 2 and # 3
WidgetsBinding.instance.addPostFrameCallback(refreshChildren); // Step # 4
}
detailed look
// Step # 1
void swapChildren(int pageCurrent, int pageTarget) {
List<Widget> newVisiblePageViews = [];
newVisiblePageViews.addAll(pageViews);
if (pageTarget > pageCurrent) {
newVisiblePageViews[pageCurrent + 1] = visiblePageViews[pageTarget];
} else if (pageTarget < pageCurrent) {
newVisiblePageViews[pageCurrent - 1] = visiblePageViews[pageTarget];
}
setState(() {
visiblePageViews = newVisiblePageViews;
});
}
// Step # 2 and # 3
Future quickJump(int pageCurrent, int pageTarget) async {
int quickJumpTarget;
if (pageTarget > pageCurrent) {
quickJumpTarget = pageCurrent + 1;
} else if (pageTarget < pageCurrent) {
quickJumpTarget = pageCurrent - 1;
}
await pageController.animateToPage(
quickJumpTarget,
curve: Curves.easeIn,
duration: Duration(seconds: 1),
);
pageController.jumpToPage(pageTarget);
}
// Step # 4
List<Widget> createPageContents() {
return <Widget>[
PageContent(1),
PageContent(2),
PageContent(3),
PageContent(4),
PageContent(5),
PageContent(6),
PageContent(7),
PageContent(8),
];
}
void refreshChildren(Duration duration) {
setState(() {
visiblePageViews = createPageContents();
});
}
Full Working-Example Repository
You may look into full source code and build locally. Github

prevent multiple posts in react/mongoose

I'm working on an app in reactjs/redux with mongoose. I have form which allows to auth ppl add a comment to the article but if user clicks like 10 times in 1 second form gonna send 10 requests.. which is bad. How can I prevent this?
Let's say user clicks once on a button and then he needs to wait 5 seconds to send another comment.
As for the frontend part, you can add a timestamp to the component state or redux, something like lastPostTime for that user and then compare it to the current time and if it's less than 5 seconds or other timeframe that you want to prevent the post, make the button disabled.
Here is some imaginary component example:
class App extends Component {
constructor() {
super();
this.state = {
lastPostTime: null
};
this.handleCommentSubmit = this.handleCommentSubmit.bind(this);
this.checkIfTimeoutPassed = this.checkIfTimeoutPassed.bind(this);
}
handleCommentSubmit(e) {
if (this.checkIfTimeoutPassed()) {
console.log('sent');
this.setState({ lastPostTime: Date.now() });
}
}
checkIfTimeoutPassed() {
const postTimeOut = 5000;
const { lastPostTime } = this.state;
const timeSinceLastPost = Date.now() - lastPostTime;
return !lastPostTime || timeSinceLastPost > postTimeOut;
}
render() {
return (<button onClick={this.handleCommentSubmit}>Click me</button>);
}
}
It would make sense to make a similar checks on the backend in case the user will hack through the frontend limitations.

How to keep focus within modal dialog?

I'm developing an app with Angular and Semantic-UI. The app should be accessible, this means it should be compliant with WCAG 2.0.
To reach this purpose the modals should keep focus within the dialog and prevents users from going outside or move with "tabs" between elements of the page that lays under the modal.
I have found some working examples, like the following:
JQuery dialog: https://jqueryui.com/dialog/#modal-confirmation
dialog HTML 5.1 element: https://demo.agektmr.com/dialog
ARIA modal dialog example:
http://w3c.github.io/aria-practices/examples/dialog-modal/dialog.html
(that I have reproduced on Plunker)
Here is my try to create an accessible modal with Semantic-UI: https://plnkr.co/edit/HjhkZg
As you can see I used the following attributes:
role="dialog"
aria-labelledby="modal-title"
aria-modal="true"
But they don't solve my issue. Do you know any way to make my modal keeping focus and lose it only when user click on cancel/confirm buttons?
There is currently no easy way to achieve this. The inert attribute was proposed to try to solve this problem by making any element with the attribute and all of it's children inaccessible. However, adoption has been slow and only recently did it land in Chrome Canary behind a flag.
Another proposed solution is making a native API that would keep track of the modal stack, essentially making everything not currently the top of the stack inert. I'm not sure the status of the proposal, but it doesn't look like it will be implemented any time soon.
So where does that leave us?
Unfortunately without a good solution. One solution that is popular is to create a query selector of all known focusable elements and then trap focus to the modal by adding a keydown event to the last and first elements in the modal. However, with the rise of web components and shadow DOM, this solution can no longer find all focusable elements.
If you always control all the elements within the dialog (and you're not creating a generic dialog library), then probably the easiest way to go is to add an event listener for keydown on the first and last focusable elements, check if tab or shift tab was used, and then focus the first or last element to trap focus.
If you're creating a generic dialog library, the only thing I have found that works reasonably well is to either use the inert polyfill or make everything outside of the modal have a tabindex=-1.
var nonModalNodes;
function openDialog() {
var modalNodes = Array.from( document.querySelectorAll('dialog *') );
// by only finding elements that do not have tabindex="-1" we ensure we don't
// corrupt the previous state of the element if a modal was already open
nonModalNodes = document.querySelectorAll('body *:not(dialog):not([tabindex="-1"])');
for (var i = 0; i < nonModalNodes.length; i++) {
var node = nonModalNodes[i];
if (!modalNodes.includes(node)) {
// save the previous tabindex state so we can restore it on close
node._prevTabindex = node.getAttribute('tabindex');
node.setAttribute('tabindex', -1);
// tabindex=-1 does not prevent the mouse from focusing the node (which
// would show a focus outline around the element). prevent this by disabling
// outline styles while the modal is open
// #see https://www.sitepoint.com/when-do-elements-take-the-focus/
node.style.outline = 'none';
}
}
}
function closeDialog() {
// close the modal and restore tabindex
if (this.type === 'modal') {
document.body.style.overflow = null;
// restore or remove tabindex from nodes
for (var i = 0; i < nonModalNodes.length; i++) {
var node = nonModalNodes[i];
if (node._prevTabindex) {
node.setAttribute('tabindex', node._prevTabindex);
node._prevTabindex = null;
}
else {
node.removeAttribute('tabindex');
}
node.style.outline = null;
}
}
}
The different "working examples" do not work as expected with a screenreader.
They do not trap the screenreader visual focus inside the modal.
For this to work, you have to :
Set the aria-hidden attribute on any other nodes
disable keyboard focusable elements inside those trees (links using tabindex=-1, controls using disabled, ...)
The jQuery :focusable pseudo selector can be useful to find focusable elements.
add a transparent layer over the page to disable mouse selection.
or you can use the css pointer-events: none property when the browser handles it with non SVG elements, not in IE
This focus-trap plugin is excellent at making sure that focus stays trapped inside of dialogue elements.
It sounds like your problem can be broken down into 2 categories:
focus on dialog box
Add a tabindex of -1 to the main container which is the DOM element that has role="dialog". Set the focus to the container.
wrapping the tab key
I found no other way of doing this except by getting the tabbable elements within the dialog box and listening it on keydown. When I know the element in focus (document.activeElement) is the last one on the list, I make it wrap
"focus" events can be intercepted in the capture phase, so you can listen for them at the document.body level, squelch them before they reach the target element, and redirect focus back to a control in your modal dialog. This example assumes a modal dialog with an input element gets displayed and assigned to the variable currDialog:
document.body.addEventListener("focus", (event) => {
if (currDialog && !currDialog.contains(event.target)) {
event.preventDefault();
event.stopPropagation();
currDialog.querySelector("input").focus();
}
}, {capture: true});
You may also want to contain such a dialog in a fixed-position, clear (or low-opacity) backdrop element that takes up the full screen in order to capture and suppress mouse/pointer events, so that no browser feedback (hover, etc.) occurs that could give the user the impression that the background is active.
Don't use any solution requiring you to look up "tabbable" elements. Instead, use keydown and either click events or a backdrop in an effective manor.
(Angular1)
See Asheesh Kumar's answer at https://stackoverflow.com/a/31292097/1754995 for something similar to what I am going for below.
(Angular2-x, I haven't done Angular1 in a while)
Say you have 3 components: BackdropComponent, ModalComponent (has an input), and AppComponent (has an input, the BackdropComponent, and the ModalComponent). You display BackdropComponent and ModalComponent with the correct z-index, both are currently displayed/visible.
What you need to do is have a general window.keydown event with preventDefault() to stop all tabbing when the backdrop/modal component is displayed. I recommend you put that on a BackdropComponent. Then you need a keydown.tab event with stopPropagation() to handle tabbing for the ModalComponent. Both the window.keydown and keydown.tab could probably be in the ModalComponent but there is purpose in a BackdropComponent further than just modals.
This should prevent clicking and tabbing to the AppComponent input and only click or tab to the ModalComponent input [and browser stuffs] when the modal is shown.
If you don't want to use a backdrop to prevent clicking, you can use use click events similarly to the keydown events described above.
Backdrop Component:
#Component({
selector: 'my-backdrop',
host: {
'tabindex': '-1',
'(window:keydown)': 'preventTabbing($event)'
},
...
})
export class BackdropComponent {
...
private preventTabbing(event: KeyboardEvent) {
if (event.keyCode === 9) { // && backdrop shown?
event.preventDefault();
}
}
...
}
Modal Component:
#Component({
selector: 'my-modal',
host: {
'tabindex': '-1',
'(keydown.tab)': 'onTab($event)'
},
...
})
export class ModalComponent {
...
private onTab(event: KeyboardEvent) {
event.stopPropagation();
}
...
}
Here's my solution. It traps Tab or Shift+Tab as necessary on first/last element of modal dialog (in my case found with role="dialog"). Eligible elements being checked are all visible input controls whose HTML may be input,select,textarea,button.
$(document).on('keydown', function(e) {
var target = e.target;
var shiftPressed = e.shiftKey;
// If TAB key pressed
if (e.keyCode == 9) {
// If inside a Modal dialog (determined by attribute role="dialog")
if ($(target).parents('[role=dialog]').length) {
// Find first or last input element in the dialog parent (depending on whether Shift was pressed).
// Input elements must be visible, and can be Input/Select/Button/Textarea.
var borderElem = shiftPressed ?
$(target).closest('[role=dialog]').find('input:visible,select:visible,button:visible,textarea:visible').first()
:
$(target).closest('[role=dialog]').find('input:visible,select:visible,button:visible,textarea:visible').last();
if ($(borderElem).length) {
if ($(target).is($(borderElem))) {
return false;
} else {
return true;
}
}
}
}
return true;
});
we can use the focus trap npm package.
npm i focus-trap
This might help someone who is looking for solution in Angular.
Step 1: Add keydown event on dialog component
#HostListener('document:keydown', ['$event'])
handleTabKeyWInModel(event: any) {
this.sharedService.handleTabKeyWInModel(event, '#modal_id', this.elementRef.nativeElement, 'input,button,select,textarea,a,[tabindex]:not([tabindex="-1"])');
}
This will filters the elements which are preseneted in the Modal dialog.
Step 2: Add common method to handle focus in shared service (or you can add it in your component as well)
handleTabKeyWInModel(e, modelId: string, nativeElement, tagsList: string) {
if (e.keyCode === 9) {
const focusable = nativeElement.querySelector(modelId).querySelectorAll(tagsList);
if (focusable.length) {
const first = focusable[0];
const last = focusable[focusable.length - 1];
const shift = e.shiftKey;
if (shift) {
if (e.target === first) { // shift-tab pressed on first input in dialog
last.focus();
e.preventDefault();
}
} else {
if (e.target === last) { // tab pressed on last input in dialog
first.focus();
e.preventDefault();
}
}
}
}
}
Now this method will take the modal dialog native element and start evaluate on every tab key. Finally we will filter the event on first and last so that we can focus on appropriate elements (on first after last element tab click and on last shift+tab event on first element).
Happy Coding.. :)
I used one of the methods suggested by Steven Lambert, namely, listening to keydown events and intercepting "tab" and "shift+tab" keys. Here's my sample code (Angular 5):
import { Directive, ElementRef, Attribute, HostListener, OnInit } from '#angular/core';
/**
* This directive allows to override default tab order for page controls.
* Particularly useful for working around the modal dialog TAB issue
* (when tab key allows to move focus outside of dialog).
*
* Usage: add "custom-taborder" and "tab-next='next_control'"/"tab-prev='prev_control'" attributes
* to the first and last controls of the dialog.
*
* For example, the first control is <input type="text" name="ctlName">
* and the last one is <button type="submit" name="btnOk">
*
* You should modify the above declarations as follows:
* <input type="text" name="ctlName" custom-taborder tab-prev="btnOk">
* <button type="submit" name="btnOk" custom-taborder tab-next="ctlName">
*/
#Directive({
selector: '[custom-taborder]'
})
export class CustomTabOrderDirective {
private elem: HTMLInputElement;
private nextElemName: string;
private prevElemName: string;
private nextElem: HTMLElement;
private prevElem: HTMLElement;
constructor(
private elemRef: ElementRef
, #Attribute('tab-next') public tabNext: string
, #Attribute('tab-prev') public tabPrev: string
) {
this.elem = this.elemRef.nativeElement;
this.nextElemName = tabNext;
this.prevElemName = tabPrev;
}
ngOnInit() {
if (this.nextElemName) {
var elems = document.getElementsByName(this.nextElemName);
if (elems && elems.length && elems.length > 0)
this.nextElem = elems[0];
}
if (this.prevElemName) {
var elems = document.getElementsByName(this.prevElemName);
if (elems && elems.length && elems.length > 0)
this.prevElem = elems[0];
}
}
#HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
if (event.key !== "Tab")
return;
if (!event.shiftKey && this.nextElem) {
this.nextElem.focus();
event.preventDefault();
}
if (event.shiftKey && this.prevElem) {
this.prevElem.focus();
event.preventDefault();
}
}
}
To use this directive, just import it to your module and add to Declarations section.
I've been successful using Angular Material's A11yModule.
Using your favorite package manager install these to packages into your Angular app.
**"#angular/material": "^10.1.2"**
**"#angular/cdk": "^10.1.2"**
In your Angular module where you import the Angular Material modules add this:
**import {A11yModule} from '#angular/cdk/a11y';**
In your component HTML apply the cdkTrapFocus directive to any parent element, example: div, form, etc.
Run the app, tabbing will now be contained within the decorated parent element.
For jquery users:
Assign role="dialog" to your modal
Find first and last interactive element inside the dialog modal.
Check if current target is one of them(depending on shift key is
pressed or not).
If target element is one of first or last interactive element of the
dialog, return false
Working code sample:
//on keydown inside dialog
$('.modal[role=dialog]').on('keydown', e => {
let target = e.target;
let shiftPressed = e.shiftKey;
// If TAB is pressed
if (e.keyCode === 9) {
// Find first and last element in the ,modal-dialog parent.
// Elements must be interactive i.e. visible, and can be Input/Select/Button/Textarea.
let first = $(target).closest('[role=dialog]').find('input:visible,select:visible,button:visible,textarea:visible').first();
let last = $(target).closest('[role=dialog]').find('input:visible,select:visible,button:visible,textarea:visible').last();
let borderElem = shiftPressed ? first : last //border element on the basis of shift key pressed
if ($(borderElem).length) {
return !$(target).is($(borderElem)); //if target is border element , return false
}
}
return true;
});
I read through most of the answers, while the package focus-trap seems like a good option. #BenVida shared a very simple VanillaJS solution here in another Stack Overflow post.
Here is the code:
const container=document.querySelector("_selector_for_the_container_")
//optional: needed only if the container element is not focusable already
container.setAttribute("tabindex","0")
container.addEventListener("focusout", (ev)=>{
if (!container.contains(ev.relatedTarget)) container.focus()
})

Model update not reflected in UI only on second NavController page

I have a bizarre problem that when I change a value in the model, it does not update the view. My demo is a simple page which displays a timer whose value is updated in the model which I want reflected in the UI:
import { Component } from '#angular/core';
import { Observable } from 'rxjs/Rx';
#Component({
template: '<ion-content>Ticks (every second) : {{ticks}}</ion-content>',
})
export class ProgramOverviewPage {
ticks = 0;
ngOnInit() {
let timer = Observable.timer(0, 1000);
timer.subscribe(t => { this.ticks = t; console.log(t);});
}
}
If I set this page as my root page, it works fine. However, if I set a different page as my root page, and then immediately navigate to the timer page:
ngOnInit() {
this.nav.push(ProgramOverviewPage, {
});
}
then the page renders, but the tick value does not update the UI. I can't think of anything other than that the NavController is messing with the ChangeDetector, but I don't know why that would be. Anything I can add to debug this is much appreciated.
"ionic-angular": "2.0.0-beta.10"
Ionic 2 seems to be automatically setting Change Detection to OnPush for each of the Content objects (generated from <ion-content> I believe). This can be verified by using Augury and clicking on the Content object.
Because of this, it's necessary to explicitly tell the change detection system whenever you make any change which should be pushed to the UI using the ChangeDetectorRef.detectChanges() method. See the thoughtram blog for details.
import { Component, ChangeDetectorRef } from '#angular/core';
import { Observable } from 'rxjs/Rx';
#Component({
template: '<ion-content>Ticks (every second) : {{ticks}}</ion-content>',
})
export class ProgramOverviewPage {
ticks = 0;
ngOnInit() {
let timer = Observable.timer(0, 1000);
timer.subscribe(t => {
this.ticks = t;
console.log(t);
this.cd.detectChanges(); // Invoke the change detector
});
}
}