// -----------------------------------------------------------------------
//
// Copyright 2015 MIT Licence. See licence.md for more information.
//
// -----------------------------------------------------------------------
namespace Perspex.Animation
{
using System;
using System.Collections.Generic;
using System.Reactive.Threading.Tasks;
using System.Threading.Tasks;
using Perspex.Media;
///
/// Transitions between two pages by sliding them horizontally.
///
public class PageSlide : IPageTransition
{
///
/// Initializes a new instance of the class.
///
/// The duration of the animation.
public PageSlide(TimeSpan duration)
{
this.Duration = duration;
}
///
/// Gets the duration of the animation.
///
public TimeSpan Duration { get; }
///
/// Starts the animation.
///
///
/// The control that is being transitioned away from. May be null.
///
///
/// The control that is being transitioned to. May be null.
///
///
/// If true, the new page is slid in from the right, or if false from the left.
///
///
/// A that tracks the progress of the animation.
///
public async Task Start(IVisual from, IVisual to, bool forward)
{
var tasks = new List();
var parent = GetVisualParent(from, to);
var distance = parent.Bounds.Width;
if (from != null)
{
var transform = new TranslateTransform();
from.RenderTransform = transform;
tasks.Add(Animate.Property(
transform,
TranslateTransform.XProperty,
0.0,
forward ? -distance : distance,
LinearEasing.For(),
this.Duration).ToTask());
}
if (to != null)
{
var transform = new TranslateTransform();
to.RenderTransform = transform;
to.IsVisible = true;
tasks.Add(Animate.Property(
transform,
TranslateTransform.XProperty,
forward ? distance : -distance,
0.0,
LinearEasing.For(),
this.Duration).ToTask());
}
await Task.WhenAll(tasks.ToArray());
if (from != null)
{
from.IsVisible = false;
}
}
///
/// Gets the common visual parent of the two control.
///
/// The from control.
/// The to control.
/// The common parent.
///
/// The two controls do not share a common parent.
///
///
/// Any one of the parameters may be null, but not both.
///
private static IVisual GetVisualParent(IVisual from, IVisual to)
{
var p1 = (from ?? to).VisualParent;
var p2 = (to ?? from).VisualParent;
if (p1 != null && p2 != null && p1 != p2)
{
throw new ArgumentException("Controls for PageSlide must have same parent.");
}
return p1;
}
}
}