ui-router icon indicating copy to clipboard operation
ui-router copied to clipboard

RFC: Leaving specified views intact during state transitions

Open MrOrz opened this issue 13 years ago • 46 comments

I would like to send a pull request proposing a solution to #63 and #317, with two lines of code modification.

https://github.com/MrOrz/ui-router/compare/angular-ui:master...patch-1

Summary of Changes

The template string of a state can be set to =. When entering such state, the named views with its template set to = will remain intact. Neither the scope nor the DOM will be destructed.

When = is introduced, implementing modal dialogs with ui-router can be straight-forward. I humbly provide a few motivating examples in the following sections. For each example, click "Edit in JSBin" button on the upper right corner to view its source.


Usage Example

// A page that lists all the items.
// Clicking the items will show the details in a modal dialog.
//
$stateProvider.state('index', {
  url: '/',
  templateUrl: 'index.html'
});

// The detail pages. 
// Populates "modal" view and keeps the main view.
//
$stateProvider.state('detail', {
  url: '/detail/:id',
  views: {
    '': {
      template: '='
    },
    modal: {
      templateUrl: 'modal.html',
      controller: modalCtrl
    }
  }
});

HTML Setup: Two ui-views, side-by-side.

<div ui-view></div>
<div ui-view="modal"></div>

Proof of Concept

http://jsbin.com/AYoKuHe/latest#/ Each "detail page" can be accessed individually via URLs. All the states are correctly managed by ui-router.

Notice that when the modal opens, the underlying index is still visible.

This is achieved by setting the template of main ui-view to = while in the "detail" state.

When the detail page is accessed directly via URL, the underlying page is blank. http://jsbin.com/AYoKuHe/latest#/detail/4

Adding some simple trick and CSS magic, the detail pages can be shown outside of a modal when their URLs are directly accessed. http://jsbin.com/itOjaj/latest#/detail/2

Notice the detail pages can still be viewed in modal after navigating to the index page. The behaviour is exactly the same as Facebook albums and Instagram colorboxes.

Integration with ui-modal

See it in action: http://jsbin.com/aFemAfe/latest Individual detail pages are shown outside the modal: http://jsbin.com/aFemAfe/latest

The trick here is to move ui-view="modal" around. Kind of stupid, but it is somewhat better than fighting bugs caused by preventing state changes.

MrOrz avatar Nov 06 '13 16:11 MrOrz

Wow this is pretty bad ass... I'm trying to find holes in it though. I'll let you know.

timkindberg avatar Nov 06 '13 18:11 timkindberg

  1. So if a much deeper nest state wanted to set a top level view in the same manner would you need to set every other possible ancestor view to '='?
  2. Also not digging using '=' so much, we already have ^ and @, I think we should be more explicit. I would prefer a special string like '$retain' or a config property retain: true. Not saying 'retain' has to be the word but you get what I mean.

timkindberg avatar Nov 06 '13 18:11 timkindberg

Certainly looks interesting. After a cursory review, the code looks okay, but one thing I noticed is that if you refresh, you lose the modal overlay. Did I miss a part in the description where this was intentional?

nateabele avatar Nov 06 '13 19:11 nateabele

Could we not make changing a named view opt-in? So you don't need '=' or retain, just don't specify a change?

Continuing with the above example

$stateProvider.state('detail', {
  url: '/detail/:id',
  views: {
    modal: {
      templateUrl: 'modal.html',
      controller: modalCtrl
    }
  }
});

I may be missing something obvious as I'm pretty new to ui-router...

deedubs avatar Nov 06 '13 21:11 deedubs

@deedubs that makes too much sense. But I haven't thought deeply about the implications. Seems like it would make for good usability from an API perspective too! I like it.

timkindberg avatar Nov 06 '13 21:11 timkindberg

This is a very welcome addition! +1

Cinamonas avatar Nov 07 '13 08:11 Cinamonas

I don't see how this would solve #63, as the tabs use-case requires that you keep the view/controller around when the ui-view it's attached to changes, not when an unrelated named view does. The best option for #63 remains some kind of caching capability on ui-view, IMO.

This is a pretty neat idea though, and would very useful for modals, other overlays, and things like sign-in dropdowns. Although for those, I would still prefer the ability to create additional state machines that could be independently serialized to and from the URL.

jonrimmer avatar Nov 07 '13 10:11 jonrimmer

Really like this and tried in our current app, works nicely, but I had to change your locals-comparison because it broke most state transitioning in our app (angular.equals ignores all properties starting with $ so it ignored many state changes) (using 1.2rc3)

if (locals === viewLocals || /* fast-check the obj references */
                  (locals && viewLocals && /* deep-comparing essential elements */
                      angular.equals(locals, viewLocals) &&
                      angular.equals(locals.$stateParams, viewLocals.$stateParams)) ) return;

I made it working like this:

if (locals === viewLocals || /* fast-check the obj references */
                  (locals && viewLocals && /* deep-comparing essential elements */
                      angular.equals(locals.$$state, viewLocals.$$state) &&
                      angular.equals(locals.$stateParams, viewLocals.$stateParams)) ) return;

RBLU avatar Nov 07 '13 10:11 RBLU

@RBLU That's exactly what I was about to report :) Relevant line in angular.equals source.

Cinamonas avatar Nov 07 '13 10:11 Cinamonas

made it working like this:

if (locals === viewLocals || /* fast-check the obj references / (locals && viewLocals && / deep-comparing essential elements */ angular.equals(locals.$$state, viewLocals.$$state) && angular.equals(locals.$stateParams, viewLocals.$stateParams)) ) return;

well, this quick fix is obviously not good enough. It needs both lines, the one I added and the one I replaced, otherwise the state is not updated when the locals ('resolves') change. So, better is:

if (locals === viewLocals || /* fast-check the obj references */
                  (locals && viewLocals && /* deep-comparing essential elements */
                      angular.equals(locals, viewLocals) &&
                      angular.equals(locals.$$state, viewLocals.$$state) &&
                      angular.equals(locals.$stateParams, viewLocals.$stateParams)) ) return;

RBLU avatar Nov 07 '13 12:11 RBLU

@JonRimmer the templates are already cached, not as a detached DOM though, but keeping controllers around may have side effects, so it's more sane if that doesn't happen as part of a router solution IMO... (Basically my advice is to not make components with a router)

A tab view should instead be a component (directive + needed services) in it self... then just switch to the right tab based on a routing parameter... It's actually not that difficult to achieve... Doing this in an explicit way rather than weaving it into the router means people can be more aware of the side effects it may have...

A Very basic solution for a single tab view can be done in 21 lines of javascript + some html... As I demonstrated in #63 ... that just shows how simple it is... making it the right way (directive+services) would require a bit more work... but really...

From here on out it makes more sense to look towards: http://angular-ui.github.io/bootstrap/#/tabs for how to combine ui-router + ui-bootstraps tabs to achieve this (in your own solution)

That is just my point of view though...

jeme avatar Nov 07 '13 13:11 jeme

I collected some modal related issues, which are listed below. These issues comes from different use cases and has different requirements. And I also found that my proposal did not resolve #63 :P

I hope the list give us insights on where we will be heading for, as well as to understand how far we can get with the simple modification proposed in my original post.


#475 : Parallel state handing

We have view A and view B, and we wish to change one view without touching the other. retain or = would work for this case. However, if there are too many states in A and B, we will have to add retain in each and every state.

By making named-view refresh opt-in, which is proposed by @deedub, the state setup would be much cleaner and more intuitive. @deedub 's idea fits perfectly into this scenario.


However, the retain trick would not be sufficient in solving the following issues.

#490 : is there a way to handle multiple states?

As the previous issue, we have two views that want to work separately. However, this time we need to encode all the currently active states in the views into the URL, so that the views can be rendered correctly when the user visits the page directly via URL. #123, which is similar, requires remembering the page behind the modal dialog.

#63 : Optional support for keeping a view around

This issue differs from my issue because they want to preserve the compiled DOM, scopes and the controller even after the ui-view is populated with another content.

#160 discusses a much more general case, which can achieve complex structures like widgets and portlets.


As for my modification to $anchorScroll, I found that its existence was already challenged in #97 XD

In fact I removed $anchorScroll merely because it will scroll my page to the top when I quit the modal dialog.

MrOrz avatar Nov 07 '13 13:11 MrOrz

@nateabele The modal overlay is deliberately removed when the detail page URL is accessed directly. This is to mimic the behavior of Facebook albums and Pinterest overlays.

For instance, the page http://www.pinterest.com/merblood/if-i-do/ is a list of images. When an image is clicked, a modal dialog with much detail shows up, and the URL is changed to something like http://www.pinterest.com/pin/5348093281506292/.

When we directly access http://www.pinterest.com/pin/5348093281506292/ , the detail page is shown directly, without the modal overlay.

MrOrz avatar Nov 07 '13 13:11 MrOrz

@RBLU @Cinamonas Wow I didn't know that before :P. It seems like I have overestimated what angular.equals can do. Thanks for pointing that out and the neat patch!

MrOrz avatar Nov 07 '13 13:11 MrOrz

@jeme We're probably getting a little off-topic here. I understand your point of view, and the code you provided is great, but as I think about it, my view is that caching goes beyond the use-case of tabs, to a broader use-case of managing the life-cycle of views and controllers.

In a rich desktop-like application, there can be a non-trivial cost to instantiating a controller, resolving its dependencies, and rendering a complex view into the DOM. Imagine an interactive dashboard, with lots data retrieved via ajax and displayed with D3 SVG charts that can be manipulated and filtered by the user. I will likely want to let the user switch to another part of the application, do some work, then come back to the dashboard and have it the same as they left it, but at present, everything will have been destroyed and need to be reinstantiated when they navigate back.

The usual advice is, "store everything in services", but this seems to me like a hack, because much of what you're storing in the services is not reusable data, but the state of the UI (such as filters, selected dropbox values, etc.). In rich UIs, the controller acts as a view model: It holds state related to the UI that is ancillary to the actual business data you want to display. When you store UI state in a service, what you're really doing is recreating your controller as a non-reusable, single-purpose service, just to take advantage of the service life-cycle, and that is an anti-pattern IMO.

The tabs use-case is just the simplest manifestation of a need to have parts of your UI whose state persists even when they are not being rendered. Yes, it's possible to do this by moving things outside of the view hierarchy and using ng-show, but I think the router should be the place where I configure the navigation hierarchy, templates, controllers, and resolves, and to that end, it should support more complex life-cycles for views and controllers.

jonrimmer avatar Nov 07 '13 14:11 jonrimmer

Implemented @deedubs 's idea in a separate branch.

https://github.com/MrOrz/ui-router/compare/angular-ui:master...patch-2

Example (ui-bootstrap integration): http://jsbin.com/OkuZiTA/2/edit

MrOrz avatar Nov 07 '13 14:11 MrOrz

@JonRimmer I have already debated against exactly what you mention in #63, the exact same example came up.

My whole point is that wrapping "Components" into views and control their state that way is an anti-pattern in angular to me... Angular has directives for a reason, they are extremely powerful, and i know they are a bit difficult to learn, so many people seem to dive into UI-Router to replace what they are actually their for... And that is not something I would like to help them do, because then I am really not helping them learning Angular, instead I feel like I am helping them to avoid Angular...

If you have a dashboard that needs to be "active" at all time, I would simply place it above or outside the scope of views... You can still control it's state through the UI-Router and it's controllers if that's needed... And it becomes more apparent that it's actually always their... Views are a special type of Directives, which have a template you wish to replace... the rest isn't views... it's components...

I have tried to lift an idea for a refresh opt-in for views for when source and target state is the same but parameters has changed, the controller and the view DOM would not be rebuild, but instead a refresh would somehow be communicated to the controller, as I think it could help in many of the scenarios people try to solve with independent states, or multiple active states.

If ill get the type ill try to leverage that with an example as well at some point... As for getting off-topic... yes indeed... but we can just continue in #63.

jeme avatar Nov 07 '13 15:11 jeme

@mrorz great summary several posts up. Very helpful.

timkindberg avatar Nov 08 '13 03:11 timkindberg

I found that the demo page for patch-2 branch contains a bug.

Steps to reproduce:

  1. Visit http://jsbin.com/OkuZiTA/2#/detail/2 directly.
  2. Click "Return to index"
  3. Scroll down to the very end, you will find the content of the detail/2 at the end of the page.

This is because in patch-2 the views are not cleared by default. Now we to tell ui-router to clean up the view.

The demo page can be fixed by modifying the state definitions to:

$stateProvider.state('index', {
  url: '/',
  views: {
    "":{
      templateUrl: 'index.html'          
    },
    modal:{
      template: "" 
    }
  }
});
$stateProvider.state('detail', {
  url: '/detail/:id',
  views: {
    modal: {
      templateUrl: 'modal.html',
      controller: modalCtrl
    }
  }
});

See the fix in action: http://jsbin.com/OkuZiTA/3/edit

The question is, when I am using the patch in my own project, in the detail page I have links to multiple states. This means that I have to duplicate the "modal view cleanup" settings to these states. Is there any way to balance between the retain solution and the opt-in solution?

MrOrz avatar Nov 10 '13 04:11 MrOrz

This is great work and I believe this should be further integrated into the mainstream.

Here is one big note from me - the variant with explicit view behavior should be implemented e.g. template: '=' as this way developers get full control over the states.

The variant to not destroy views by default leads to big issues as there is no way to destroy them.

Thanks and great work again!

smoke avatar Nov 25 '13 20:11 smoke