-
-
Notifications
You must be signed in to change notification settings - Fork 241
FIX: ListView infinite change detection #288
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
c5a93fa
Updated async examples
2530918
list-test updated
2b36449
Fix: Cyclic change detection when list view is present
f34cf23
Manually trigger change detection onItemLoading for current item only
eb27a01
Refactor and simplify
9d03c28
Clean up unused variables
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,21 @@ | ||
import { | ||
Component, | ||
DoCheck, | ||
ElementRef, | ||
Component, | ||
DoCheck, | ||
OnDestroy, | ||
ElementRef, | ||
ViewContainerRef, | ||
TemplateRef, | ||
ContentChild, | ||
TemplateRef, | ||
ContentChild, | ||
EmbeddedViewRef, | ||
HostListener, | ||
IterableDiffers, | ||
HostListener, | ||
IterableDiffers, | ||
IterableDiffer, | ||
ChangeDetectorRef, | ||
EventEmitter, | ||
ViewChild, | ||
Output, | ||
ChangeDetectionStrategy} from '@angular/core'; | ||
NgZone, | ||
ChangeDetectionStrategy } from '@angular/core'; | ||
import {isBlank} from '@angular/core/src/facade/lang'; | ||
import {isListLikeIterable} from '@angular/core/src/facade/collection'; | ||
import {Observable as RxObservable} from 'rxjs' | ||
|
@@ -22,7 +24,8 @@ import {View} from 'ui/core/view'; | |
import {NgView} from '../view-util'; | ||
import {ObservableArray} from 'data/observable-array'; | ||
import {LayoutBase} from 'ui/layouts/layout-base'; | ||
import {rendererLog, rendererError} from "../trace"; | ||
import {listViewLog} from "../trace"; | ||
|
||
const NG_VIEW = "_ngViewRef"; | ||
|
||
export class ListItemContext { | ||
|
@@ -51,15 +54,15 @@ export interface SetupItemViewArgs { | |
inputs: ['items'], | ||
changeDetection: ChangeDetectionStrategy.OnPush | ||
}) | ||
export class ListViewComponent { | ||
export class ListViewComponent implements DoCheck, OnDestroy { | ||
public get nativeElement(): ListView { | ||
return this.listView; | ||
} | ||
|
||
private listView: ListView; | ||
private _items: any; | ||
private _differ: IterableDiffer; | ||
|
||
@ViewChild('loader', { read: ViewContainerRef }) loader: ViewContainerRef; | ||
|
||
@Output() public setupItemView: EventEmitter<SetupItemViewArgs> = new EventEmitter<SetupItemViewArgs>(); | ||
|
@@ -73,21 +76,26 @@ export class ListViewComponent { | |
needDiffer = false; | ||
} | ||
if (needDiffer && !this._differ && isListLikeIterable(value)) { | ||
this._differ = this._iterableDiffers.find(this._items).create(this._cdr, (index, item) => { return item;}); | ||
this._differ = this._iterableDiffers.find(this._items).create(this._cdr, (index, item) => { return item; }); | ||
} | ||
|
||
// this._cdr.detach(); | ||
this.listView.items = this._items; | ||
} | ||
|
||
private timerId: number; | ||
private doCheckDelay = 5; | ||
|
||
constructor(private _elementRef: ElementRef, | ||
private _iterableDiffers: IterableDiffers, | ||
private _cdr: ChangeDetectorRef) { | ||
private _iterableDiffers: IterableDiffers, | ||
private _cdr: ChangeDetectorRef, | ||
private _zone: NgZone) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
this.listView = _elementRef.nativeElement; | ||
|
||
this.listView.on("itemLoading", this.onItemLoading, this); | ||
} | ||
|
||
ngOnDestroy() { | ||
this.listView.off("itemLoading", this.onItemLoading, this); | ||
} | ||
|
||
@HostListener("itemLoading", ['$event']) | ||
public onItemLoading(args) { | ||
if (!this.itemTemplate) { | ||
return; | ||
|
@@ -99,20 +107,22 @@ export class ListViewComponent { | |
let viewRef: EmbeddedViewRef<ListItemContext>; | ||
|
||
if (args.view) { | ||
rendererLog("ListView.onItemLoading: " + index + " - Reusing existing view"); | ||
listViewLog("onItemLoading: " + index + " - Reusing existing view"); | ||
viewRef = args.view[NG_VIEW]; | ||
// getting angular view from original element (in cases when ProxyViewContainer is used NativeScript internally wraps it in a StackLayout) | ||
if (!viewRef) { | ||
viewRef = (args.view._subViews && args.view._subViews.length > 0) ? args.view._subViews[0][NG_VIEW] : undefined; | ||
} | ||
} | ||
else { | ||
rendererLog("ListView.onItemLoading: " + index + " - Creating view from template"); | ||
listViewLog("onItemLoading: " + index + " - Creating view from template"); | ||
viewRef = this.loader.createEmbeddedView(this.itemTemplate, new ListItemContext(), 0); | ||
args.view = getSingleViewFromViewRef(viewRef); | ||
args.view[NG_VIEW] = viewRef; | ||
} | ||
this.setupViewRef(viewRef, currentItem, index); | ||
|
||
this.detectChangesOnChild(viewRef, index); | ||
} | ||
|
||
public setupViewRef(viewRef: EmbeddedViewRef<ListItemContext>, data: any, index: number): void { | ||
|
@@ -126,49 +136,63 @@ export class ListViewComponent { | |
context.even = (index % 2 == 0); | ||
context.odd = !context.even; | ||
|
||
this.setupItemView.next({view: viewRef, data: data, index: index, context: context}); | ||
this.setupItemView.next({ view: viewRef, data: data, index: index, context: context }); | ||
} | ||
|
||
ngDoCheck() { | ||
if (this.timerId) { | ||
clearTimeout(this.timerId); | ||
} | ||
private detectChangesOnChild(viewRef: EmbeddedViewRef<ListItemContext>, index: number) { | ||
// Manually detect changes in view ref | ||
// | ||
const childChangeDetector = <ChangeDetectorRef>(<any>viewRef); | ||
|
||
this.timerId = setTimeout(() => { | ||
clearTimeout(this.timerId); | ||
if (this._differ) { | ||
var changes = this._differ.diff(this._items); | ||
if (changes) { | ||
this.listView.refresh(); | ||
} | ||
listViewLog("Manually detect changes in child: " + index) | ||
// listViewLog("CangeDetectionState child before mark " + getChangeDetectorState((<any>viewRef)._view)); | ||
childChangeDetector.markForCheck(); | ||
childChangeDetector.detectChanges(); | ||
// listViewLog("CangeDetectionState child after detect " + getChangeDetectorState((<any>viewRef)._view)); | ||
} | ||
|
||
ngDoCheck() { | ||
if (this._differ) { | ||
listViewLog("ngDoCheck() - execute differ") | ||
const changes = this._differ.diff(this._items); | ||
if (changes) { | ||
listViewLog("ngDoCheck() - refresh") | ||
this.listView.refresh(); | ||
} | ||
}, this.doCheckDelay); | ||
} | ||
} | ||
} | ||
|
||
function getSingleViewFromViewRef(viewRef: EmbeddedViewRef<any>): View { | ||
var getSingleViewRecursive = (nodes: Array<any>, nestLevel: number) => { | ||
var actualNodes = nodes.filter((n) => !!n && n.nodeName !== "#text"); | ||
|
||
if (actualNodes.length === 0) { | ||
throw new Error("No suitable views found in list template! Nesting level: " + nestLevel); | ||
} | ||
else if (actualNodes.length > 1) { | ||
throw new Error("More than one view found in list template! Nesting level: " + nestLevel); | ||
function getSingleViewRecursive(nodes: Array<any>, nestLevel: number) { | ||
const actualNodes = nodes.filter((n) => !!n && n.nodeName !== "#text"); | ||
|
||
if (actualNodes.length === 0) { | ||
throw new Error("No suitable views found in list template! Nesting level: " + nestLevel); | ||
} | ||
else if (actualNodes.length > 1) { | ||
throw new Error("More than one view found in list template! Nesting level: " + nestLevel); | ||
} | ||
else { | ||
if (actualNodes[0]) { | ||
let parentLayout = actualNodes[0].parent; | ||
if (parentLayout instanceof LayoutBase) { | ||
parentLayout.removeChild(actualNodes[0]); | ||
} | ||
return actualNodes[0]; | ||
} | ||
else { | ||
if (actualNodes[0]) { | ||
let parentLayout = actualNodes[0].parent; | ||
if (parentLayout instanceof LayoutBase) { | ||
parentLayout.removeChild(actualNodes[0]); | ||
} | ||
return actualNodes[0]; | ||
} | ||
else { | ||
return getSingleViewRecursive(actualNodes[0].children, nestLevel + 1) | ||
} | ||
return getSingleViewRecursive(actualNodes[0].children, nestLevel + 1) | ||
} | ||
} | ||
} | ||
|
||
function getSingleViewFromViewRef(viewRef: EmbeddedViewRef<any>): View { | ||
return getSingleViewRecursive(viewRef.rootNodes, 0); | ||
} | ||
|
||
const changeDetectorMode = ["CheckOnce", "Checked", "CheckAlways", "Detached", "OnPush", "Default"]; | ||
const changeDetectorStates = ["Never", "CheckedBefore", "Error"]; | ||
function getChangeDetectorState(cdr: any) { | ||
return "Mode: " + changeDetectorMode[parseInt(cdr.cdMode)] + " State: " + changeDetectorStates[parseInt(cdr.cdState)]; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import { Injectable } from '@angular/core'; | ||
import { BehaviorSubject } from "rxjs/BehaviorSubject"; | ||
|
||
export class DataItem { | ||
constructor(public id: number, public name: string) { } | ||
} | ||
|
||
@Injectable() | ||
export class DataService { | ||
private _intervalId; | ||
private _counter = 0; | ||
private _currentItems: Array<DataItem>; | ||
|
||
public items$: BehaviorSubject<Array<DataItem>>; | ||
|
||
constructor() { | ||
this._currentItems = []; | ||
for (var i = 0; i < 3; i++) { | ||
this.appendItem() | ||
} | ||
|
||
this.items$ = new BehaviorSubject(this._currentItems); | ||
} | ||
|
||
public startAsyncUpdates() { | ||
if (this._intervalId) { | ||
throw new Error("Updates are already started"); | ||
} | ||
|
||
this._intervalId = setInterval(() => { | ||
this.appendItem(); | ||
this.publishUpdates(); | ||
}, 200); | ||
|
||
} | ||
|
||
public stopAsyncUpdates() { | ||
if (!this._intervalId) { | ||
throw new Error("Updates are not started"); | ||
} | ||
|
||
clearInterval(this._intervalId); | ||
this._intervalId = undefined; | ||
} | ||
|
||
private publishUpdates() { | ||
this.items$.next([...this._currentItems]); | ||
} | ||
|
||
private appendItem() { | ||
this._currentItems.push(new DataItem(this._counter, "data item " + this._counter)); | ||
this._counter++; | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Probably forgotten to delete the commented out line.