mirror of
https://github.com/zhigang1992/react-native.git
synced 2026-04-23 20:01:01 +08:00
Updates from Thu 19 Mar
- [ReactNative] Add root package.json name back | Tadeu Zagallo
- [react-packager] Make sure projectRoots is converted to an array | Amjad Masad
- [ReactNative] Init script that bootstraps new Xcode project | Alex Kotliarskyi
- [ReactNative] New SampleApp | Alex Kotliarskyi
- [ReactNative] Touchable invoke press on longPress when longPress handler missing | Eric Vicenti
- [ReactNative] Commit missing RCTWebSocketDebugger.xcodeproj | Alex Kotliarskyi
- [ReactNative] Add Custom Components folder | Christopher Chedeau
- [react-packager] Hash cache file name information to avoid long names | Amjad Masad
- [ReactNative] Put all iOS-related files in a subfolder | Alex Kotliarskyi
- [react-packager] Fix OOM | Amjad Masad
- [ReactNative] Bring Chrome debugger to OSS. Part 2 | Alex Kotliarskyi
- [ReactNative] Add search to UIExplorer | Tadeu Zagallo
- [ReactNative][RFC] Bring Chrome debugger to OSS. Part 1 | Alex Kotliarskyi
- [ReactNative] Return the appropriate status code from XHR | Tadeu Zagallo
- [ReactNative] Make JS stack traces in Xcode prettier | Alex Kotliarskyi
- [ReactNative] Remove duplicate package.json with the same name | Christopher Chedeau
- [ReactNative] Remove invariant from require('react-native') | Christopher Chedeau
- [ReactNative] Remove ListViewDataSource from require('react-native') | Christopher Chedeau
- [react-packager] Add assetRoots option | Amjad Masad
- Convert UIExplorer to ListView | Christopher Chedeau
- purge rni | Basil Hosmer
- [ReactNative] s/render*View/render/ in <WebView> | Christopher Chedeau
This commit is contained in:
9
Libraries/CustomComponents/LICENSE
Normal file
9
Libraries/CustomComponents/LICENSE
Normal file
@@ -0,0 +1,9 @@
|
||||
LICENSE AGREEMENT
|
||||
|
||||
For React Native Custom Components software
|
||||
|
||||
Copyright (c) 2015, Facebook, Inc. All rights reserved.
|
||||
|
||||
Facebook, Inc. (“Facebook”) owns all right, title and interest, including all intellectual property and other proprietary rights, in and to the React Native Custom Components software (the “Software”). Subject to your compliance with these terms, you are hereby granted a non-exclusive, worldwide, royalty-free copyright license to (1) use and copy the Software; and (2) reproduce and distribute the Software as part of your own software (“Your Software”). Facebook reserves all rights not expressly granted to you in this license agreement.
|
||||
|
||||
THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
475
Libraries/CustomComponents/ListView/ListView.js
Normal file
475
Libraries/CustomComponents/ListView/ListView.js
Normal file
@@ -0,0 +1,475 @@
|
||||
/**
|
||||
* Copyright 2004-present Facebook. All Rights Reserved.
|
||||
*
|
||||
* @providesModule ListView
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var ListViewDataSource = require('ListViewDataSource');
|
||||
var React = require('React');
|
||||
var RCTUIManager = require('NativeModules').UIManager;
|
||||
var ScrollView = require('ScrollView');
|
||||
var ScrollResponder = require('ScrollResponder');
|
||||
var StaticRenderer = require('StaticRenderer');
|
||||
var TimerMixin = require('TimerMixin');
|
||||
|
||||
var logError = require('logError');
|
||||
var merge = require('merge');
|
||||
var isEmpty = require('isEmpty');
|
||||
|
||||
var PropTypes = React.PropTypes;
|
||||
|
||||
var DEFAULT_PAGE_SIZE = 1;
|
||||
var DEFAULT_INITIAL_ROWS = 10;
|
||||
var DEFAULT_SCROLL_RENDER_AHEAD = 1000;
|
||||
var DEFAULT_END_REACHED_THRESHOLD = 1000;
|
||||
var DEFAULT_SCROLL_CALLBACK_THROTTLE = 50;
|
||||
var RENDER_INTERVAL = 20;
|
||||
var SCROLLVIEW_REF = 'listviewscroll';
|
||||
|
||||
|
||||
/**
|
||||
* ListView - A core component designed for efficient display of vertically
|
||||
* scrolling lists of changing data. The minimal API is to create a
|
||||
* `ListView.DataSource`, populate it with a simple array of data blobs, and
|
||||
* instantiate a `ListView` component with that data source and a `renderRow`
|
||||
* callback which takes a blob from the data array and returns a renderable
|
||||
* component.
|
||||
*
|
||||
* Minimal example:
|
||||
*
|
||||
* ```
|
||||
* getInitialState: function() {
|
||||
* var ds = new ListViewDataSource({rowHasChanged: (r1, r2) => r1 !== r2});
|
||||
* return {
|
||||
* dataSource: ds.cloneWithRows(['row 1', 'row 2']),
|
||||
* };
|
||||
* },
|
||||
*
|
||||
* render: function() {
|
||||
* return (
|
||||
* <ListView
|
||||
* dataSource={this.state.dataSource}
|
||||
* renderRow={(rowData) => <Text>{rowData}</Text>}
|
||||
* />
|
||||
* );
|
||||
* },
|
||||
* ```
|
||||
*
|
||||
* ListView also supports more advanced features, including sections with sticky
|
||||
* section headers, header and footer support, callbacks on reaching the end of
|
||||
* the available data (`onEndReached`) and on the set of rows that are visible
|
||||
* in the device viewport change (`onChangeVisibleRows`), and several
|
||||
* performance optimizations.
|
||||
*
|
||||
* There are a few performance operations designed to make ListView scroll
|
||||
* smoothly while dynamically loading potentially very large (or conceptually
|
||||
* infinite) data sets:
|
||||
*
|
||||
* * Only re-render changed rows - the hasRowChanged function provided to the
|
||||
* data source tells the ListView if it needs to re-render a row because the
|
||||
* source data has changed - see ListViewDataSource for more details.
|
||||
*
|
||||
* * Rate-limited row rendering - By default, only one row is rendered per
|
||||
* event-loop (customizable with the `pageSize` prop). This breaks up the
|
||||
* work into smaller chunks to reduce the chance of dropping frames while
|
||||
* rendering rows.
|
||||
*/
|
||||
|
||||
var ListView = React.createClass({
|
||||
mixins: [ScrollResponder.Mixin, TimerMixin],
|
||||
|
||||
statics: {
|
||||
DataSource: ListViewDataSource,
|
||||
},
|
||||
|
||||
/**
|
||||
* You must provide a renderRow function. If you omit any of the other render
|
||||
* functions, ListView will simply skip rendering them.
|
||||
*
|
||||
* - renderRow(rowData, sectionID, rowID);
|
||||
* - renderSectionHeader(sectionData, sectionID);
|
||||
*/
|
||||
propTypes: {
|
||||
...ScrollView.propTypes,
|
||||
|
||||
dataSource: PropTypes.instanceOf(ListViewDataSource).isRequired,
|
||||
/**
|
||||
* (rowData, sectionID, rowID) => renderable
|
||||
* Takes a data entry from the data source and its ids and should return
|
||||
* a renderable component to be rendered as the row. By default the data
|
||||
* is exactly what was put into the data source, but it's also possible to
|
||||
* provide custom extractors.
|
||||
*/
|
||||
renderRow: PropTypes.func.isRequired,
|
||||
/**
|
||||
* How many rows to render on initial component mount. Use this to make
|
||||
* it so that the first screen worth of data apears at one time instead of
|
||||
* over the course of multiple frames.
|
||||
*/
|
||||
initialListSize: PropTypes.number,
|
||||
/**
|
||||
* Called when all rows have been rendered and the list has been scrolled
|
||||
* to within onEndReachedThreshold of the bottom. The native scroll
|
||||
* event is provided.
|
||||
*/
|
||||
onEndReached: PropTypes.func,
|
||||
/**
|
||||
* Threshold in pixels for onEndReached.
|
||||
*/
|
||||
onEndReachedThreshold: PropTypes.number,
|
||||
/**
|
||||
* Number of rows to render per event loop.
|
||||
*/
|
||||
pageSize: PropTypes.number,
|
||||
/**
|
||||
* () => renderable
|
||||
*
|
||||
* The header and footer are always rendered (if these props are provided)
|
||||
* on every render pass. If they are expensive to re-render, wrap them
|
||||
* in StaticContainer or other mechanism as appropriate. Footer is always
|
||||
* at the bottom of the list, and header at the top, on every render pass.
|
||||
*/
|
||||
renderFooter: PropTypes.func,
|
||||
renderHeader: PropTypes.func,
|
||||
/**
|
||||
* (sectionData, sectionID) => renderable
|
||||
*
|
||||
* If provided, a sticky header is rendered for this section. The sticky
|
||||
* behavior means that it will scroll with the content at the top of the
|
||||
* section until it reaches the top of the screen, at which point it will
|
||||
* stick to the top until it is pushed off the screen by the next section
|
||||
* header.
|
||||
*/
|
||||
renderSectionHeader: PropTypes.func,
|
||||
/**
|
||||
* How early to start rendering rows before they come on screen, in
|
||||
* pixels.
|
||||
*/
|
||||
scrollRenderAheadDistance: React.PropTypes.number,
|
||||
/**
|
||||
* (visibleRows, changedRows) => void
|
||||
*
|
||||
* Called when the set of visible rows changes. `visibleRows` maps
|
||||
* { sectionID: { rowID: true }} for all the visible rows, and
|
||||
* `changedRows` maps { sectionID: { rowID: true | false }} for the rows
|
||||
* that have changed their visibility, with true indicating visible, and
|
||||
* false indicating the view has moved out of view.
|
||||
*/
|
||||
onChangeVisibleRows: React.PropTypes.func,
|
||||
/**
|
||||
* An experimental performance optimization for improving scroll perf of
|
||||
* large lists, used in conjunction with overflow: 'hidden' on the row
|
||||
* containers. Use at your own risk.
|
||||
*/
|
||||
removeClippedSubviews: React.PropTypes.bool,
|
||||
},
|
||||
|
||||
/**
|
||||
* Exports some data, e.g. for perf investigations or analytics.
|
||||
*/
|
||||
getMetrics: function() {
|
||||
return {
|
||||
contentHeight: this.scrollProperties.contentHeight,
|
||||
totalRows: this.props.dataSource.getRowCount(),
|
||||
renderedRows: this.state.curRenderedRowsCount,
|
||||
visibleRows: Object.keys(this._visibleRows).length,
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Provides a handle to the underlying scroll responder to support operations
|
||||
* such as scrollTo.
|
||||
*/
|
||||
getScrollResponder: function() {
|
||||
return this.refs[SCROLLVIEW_REF];
|
||||
},
|
||||
|
||||
setNativeProps: function(props) {
|
||||
this.refs[SCROLLVIEW_REF].setNativeProps(props);
|
||||
},
|
||||
|
||||
/**
|
||||
* React life cycle hooks.
|
||||
*/
|
||||
|
||||
getDefaultProps: function() {
|
||||
return {
|
||||
initialListSize: DEFAULT_INITIAL_ROWS,
|
||||
pageSize: DEFAULT_PAGE_SIZE,
|
||||
scrollRenderAheadDistance: DEFAULT_SCROLL_RENDER_AHEAD,
|
||||
onEndReachedThreshold: DEFAULT_END_REACHED_THRESHOLD,
|
||||
};
|
||||
},
|
||||
|
||||
getInitialState: function() {
|
||||
return {
|
||||
curRenderedRowsCount: this.props.initialListSize,
|
||||
prevRenderedRowsCount: 0,
|
||||
};
|
||||
},
|
||||
|
||||
componentWillMount: function() {
|
||||
// this data should never trigger a render pass, so don't put in state
|
||||
this.scrollProperties = {
|
||||
visibleHeight: null,
|
||||
contentHeight: null,
|
||||
offsetY: 0
|
||||
};
|
||||
this._childFrames = [];
|
||||
this._visibleRows = {};
|
||||
},
|
||||
|
||||
componentDidMount: function() {
|
||||
// do this in animation frame until componentDidMount actually runs after
|
||||
// the component is laid out
|
||||
this.requestAnimationFrame(() => {
|
||||
this._measureAndUpdateScrollProps();
|
||||
this.setInterval(this._renderMoreRowsIfNeeded, RENDER_INTERVAL);
|
||||
});
|
||||
},
|
||||
|
||||
componentWillReceiveProps: function(nextProps) {
|
||||
if (this.props.dataSource !== nextProps.dataSource) {
|
||||
this.setState({prevRenderedRowsCount: 0});
|
||||
}
|
||||
},
|
||||
|
||||
render: function() {
|
||||
var bodyComponents = [];
|
||||
|
||||
var dataSource = this.props.dataSource;
|
||||
var allRowIDs = dataSource.rowIdentities;
|
||||
var rowCount = 0;
|
||||
var sectionHeaderIndices = [];
|
||||
|
||||
var header = this.props.renderHeader && this.props.renderHeader();
|
||||
var footer = this.props.renderFooter && this.props.renderFooter();
|
||||
var totalIndex = header ? 1 : 0;
|
||||
|
||||
for (var sectionIdx = 0; sectionIdx < allRowIDs.length; sectionIdx++) {
|
||||
var sectionID = dataSource.sectionIdentities[sectionIdx];
|
||||
var rowIDs = allRowIDs[sectionIdx];
|
||||
if (rowIDs.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.props.renderSectionHeader) {
|
||||
var shouldUpdateHeader = rowCount >= this.state.prevRenderedRowsCount &&
|
||||
dataSource.sectionHeaderShouldUpdate(sectionIdx);
|
||||
bodyComponents.push(
|
||||
<StaticRenderer
|
||||
key={'s_' + sectionID}
|
||||
shouldUpdate={!!shouldUpdateHeader}
|
||||
render={this.props.renderSectionHeader.bind(
|
||||
null,
|
||||
dataSource.getSectionHeaderData(sectionIdx),
|
||||
sectionID
|
||||
)}
|
||||
/>
|
||||
);
|
||||
sectionHeaderIndices.push(totalIndex++);
|
||||
}
|
||||
|
||||
for (var rowIdx = 0; rowIdx < rowIDs.length; rowIdx++) {
|
||||
var rowID = rowIDs[rowIdx];
|
||||
var comboID = sectionID + rowID;
|
||||
var shouldUpdateRow = rowCount >= this.state.prevRenderedRowsCount &&
|
||||
dataSource.rowShouldUpdate(sectionIdx, rowIdx);
|
||||
var row =
|
||||
<StaticRenderer
|
||||
key={'r_' + comboID}
|
||||
shouldUpdate={!!shouldUpdateRow}
|
||||
render={this.props.renderRow.bind(
|
||||
null,
|
||||
dataSource.getRowData(sectionIdx, rowIdx),
|
||||
sectionID,
|
||||
rowID
|
||||
)}
|
||||
/>;
|
||||
bodyComponents.push(row);
|
||||
totalIndex++;
|
||||
if (++rowCount === this.state.curRenderedRowsCount) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (rowCount >= this.state.curRenderedRowsCount) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var props = merge(
|
||||
this.props, {
|
||||
onScroll: this._onScroll,
|
||||
stickyHeaderIndices: sectionHeaderIndices,
|
||||
}
|
||||
);
|
||||
if (!props.throttleScrollCallbackMS) {
|
||||
props.throttleScrollCallbackMS = DEFAULT_SCROLL_CALLBACK_THROTTLE;
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollView {...props}
|
||||
ref={SCROLLVIEW_REF}>
|
||||
{header}
|
||||
{bodyComponents}
|
||||
{footer}
|
||||
</ScrollView>
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Private methods
|
||||
*/
|
||||
|
||||
_measureAndUpdateScrollProps: function() {
|
||||
RCTUIManager.measureLayout(
|
||||
this.refs[SCROLLVIEW_REF].getInnerViewNode(),
|
||||
this.refs[SCROLLVIEW_REF].getNodeHandle(),
|
||||
logError,
|
||||
this._setScrollContentHeight
|
||||
);
|
||||
RCTUIManager.measureLayoutRelativeToParent(
|
||||
this.refs[SCROLLVIEW_REF].getNodeHandle(),
|
||||
logError,
|
||||
this._setScrollVisibleHeight
|
||||
);
|
||||
},
|
||||
|
||||
_setScrollContentHeight: function(left, top, width, height) {
|
||||
this.scrollProperties.contentHeight = height;
|
||||
},
|
||||
|
||||
_setScrollVisibleHeight: function(left, top, width, height) {
|
||||
this.scrollProperties.visibleHeight = height;
|
||||
this._updateVisibleRows();
|
||||
},
|
||||
|
||||
_renderMoreRowsIfNeeded: function() {
|
||||
if (this.scrollProperties.contentHeight === null ||
|
||||
this.scrollProperties.visibleHeight === null ||
|
||||
this.state.curRenderedRowsCount === this.props.dataSource.getRowCount()) {
|
||||
return;
|
||||
}
|
||||
|
||||
var distanceFromEnd = this._getDistanceFromEnd(this.scrollProperties);
|
||||
if (distanceFromEnd < this.props.scrollRenderAheadDistance) {
|
||||
this._pageInNewRows();
|
||||
}
|
||||
},
|
||||
|
||||
_pageInNewRows: function() {
|
||||
var rowsToRender = Math.min(
|
||||
this.state.curRenderedRowsCount + this.props.pageSize,
|
||||
this.props.dataSource.getRowCount()
|
||||
);
|
||||
this.setState(
|
||||
{
|
||||
prevRenderedRowsCount: this.state.curRenderedRowsCount,
|
||||
curRenderedRowsCount: rowsToRender
|
||||
},
|
||||
() => {
|
||||
this._measureAndUpdateScrollProps();
|
||||
this.setState({
|
||||
prevRenderedRowsCount: this.state.curRenderedRowsCount,
|
||||
});
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
_getDistanceFromEnd: function(scrollProperties) {
|
||||
return scrollProperties.contentHeight -
|
||||
scrollProperties.visibleHeight -
|
||||
scrollProperties.offsetY;
|
||||
},
|
||||
|
||||
_updateVisibleRows: function(e) {
|
||||
if (!this.props.onChangeVisibleRows) {
|
||||
return; // No need to compute visible rows if there is no callback
|
||||
}
|
||||
var updatedFrames = e && e.nativeEvent.updatedChildFrames;
|
||||
if (updatedFrames) {
|
||||
updatedFrames.forEach((frame) => {
|
||||
this._childFrames[frame.index] = merge(frame);
|
||||
});
|
||||
}
|
||||
var dataSource = this.props.dataSource;
|
||||
var visibleTop = this.scrollProperties.offsetY;
|
||||
var visibleBottom = visibleTop + this.scrollProperties.visibleHeight;
|
||||
var allRowIDs = dataSource.rowIdentities;
|
||||
|
||||
var header = this.props.renderHeader && this.props.renderHeader();
|
||||
var totalIndex = header ? 1 : 0;
|
||||
var visibilityChanged = false;
|
||||
var changedRows = {};
|
||||
for (var sectionIdx = 0; sectionIdx < allRowIDs.length; sectionIdx++) {
|
||||
var rowIDs = allRowIDs[sectionIdx];
|
||||
if (rowIDs.length === 0) {
|
||||
continue;
|
||||
}
|
||||
var sectionID = dataSource.sectionIdentities[sectionIdx];
|
||||
if (this.props.renderSectionHeader) {
|
||||
totalIndex++;
|
||||
}
|
||||
var visibleSection = this._visibleRows[sectionID];
|
||||
if (!visibleSection) {
|
||||
visibleSection = {};
|
||||
}
|
||||
for (var rowIdx = 0; rowIdx < rowIDs.length; rowIdx++) {
|
||||
var rowID = rowIDs[rowIdx];
|
||||
var frame = this._childFrames[totalIndex];
|
||||
totalIndex++;
|
||||
if (!frame) {
|
||||
break;
|
||||
}
|
||||
var rowVisible = visibleSection[rowID];
|
||||
var top = frame.y;
|
||||
var bottom = top + frame.height;
|
||||
if (top > visibleBottom || bottom < visibleTop) {
|
||||
if (rowVisible) {
|
||||
visibilityChanged = true;
|
||||
delete visibleSection[rowID];
|
||||
if (!changedRows[sectionID]) {
|
||||
changedRows[sectionID] = {};
|
||||
}
|
||||
changedRows[sectionID][rowID] = false;
|
||||
}
|
||||
} else if (!rowVisible) {
|
||||
visibilityChanged = true;
|
||||
visibleSection[rowID] = true;
|
||||
if (!changedRows[sectionID]) {
|
||||
changedRows[sectionID] = {};
|
||||
}
|
||||
changedRows[sectionID][rowID] = true;
|
||||
}
|
||||
}
|
||||
if (!isEmpty(visibleSection)) {
|
||||
this._visibleRows[sectionID] = visibleSection;
|
||||
} else if (this._visibleRows[sectionID]) {
|
||||
delete this._visibleRows[sectionID];
|
||||
}
|
||||
}
|
||||
visibilityChanged && this.props.onChangeVisibleRows(this._visibleRows, changedRows);
|
||||
},
|
||||
|
||||
_onScroll: function(e) {
|
||||
this.scrollProperties.visibleHeight = e.nativeEvent.layoutMeasurement.height;
|
||||
this.scrollProperties.contentHeight = e.nativeEvent.contentSize.height;
|
||||
this.scrollProperties.offsetY = e.nativeEvent.contentOffset.y;
|
||||
this._updateVisibleRows(e);
|
||||
var nearEnd = this._getDistanceFromEnd(this.scrollProperties) < this.props.onEndReachedThreshold;
|
||||
if (nearEnd &&
|
||||
this.props.onEndReached &&
|
||||
this.scrollProperties.contentHeight !== this._sentEndForContentHeight &&
|
||||
this.state.curRenderedRowsCount === this.props.dataSource.getRowCount()) {
|
||||
this._sentEndForContentHeight = this.scrollProperties.contentHeight;
|
||||
this.props.onEndReached(e);
|
||||
} else {
|
||||
this._renderMoreRowsIfNeeded();
|
||||
}
|
||||
|
||||
this.props.onScroll && this.props.onScroll(e);
|
||||
},
|
||||
});
|
||||
|
||||
module.exports = ListView;
|
||||
383
Libraries/CustomComponents/ListView/ListViewDataSource.js
Normal file
383
Libraries/CustomComponents/ListView/ListViewDataSource.js
Normal file
@@ -0,0 +1,383 @@
|
||||
/**
|
||||
* Copyright 2004-present Facebook. All Rights Reserved.
|
||||
*
|
||||
* @providesModule ListViewDataSource
|
||||
* @typechecks
|
||||
* @flow
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
var invariant = require('invariant');
|
||||
var isEmpty = require('isEmpty');
|
||||
var warning = require('warning');
|
||||
|
||||
/**
|
||||
* ListViewDataSource - Provides efficient data processing and access to the
|
||||
* ListView component. A ListViewDataSource is created with functions for
|
||||
* extracting data from the input blob, and comparing elements (with default
|
||||
* implementations for convenience). The input blob can be as simple as an
|
||||
* array of strings, or an object with rows nested inside section objects.
|
||||
*
|
||||
* To update the data in the datasource, use `cloneWithRows` (or
|
||||
* `cloneWithRowsAndSections` if you care about sections). The data in the
|
||||
* data source is immutable, so you can't modify it directly. The clone methods
|
||||
* suck in the new data and compute a diff for each row so ListView knows
|
||||
* whether to re-render it or not.
|
||||
*
|
||||
* In this example, a component receives data in chunks, handled by
|
||||
* `_onDataArrived`, which concats the new data onto the old data and updates the
|
||||
* data source. We use `concat` to create a new array - mutating `this._data`,
|
||||
* e.g. with `this._data.push(newRowData)`, would be an error. `_rowHasChanged`
|
||||
* understands the shape of the row data and knows how to efficiently compare
|
||||
* it.
|
||||
*
|
||||
* getInitialState: function() {
|
||||
* var ds = new ListViewDataSource({rowHasChanged: this._rowHasChanged});
|
||||
* return {ds};
|
||||
* },
|
||||
* _onDataArrived(newData) {
|
||||
* this._data = this._data.concat(newData);
|
||||
* this.setState({
|
||||
* ds: this.state.ds.cloneWithRows(this._data)
|
||||
* });
|
||||
* }
|
||||
*/
|
||||
|
||||
function defaultGetRowData(
|
||||
dataBlob: any,
|
||||
sectionID: number | string,
|
||||
rowID: number | string
|
||||
): any {
|
||||
return dataBlob[sectionID][rowID];
|
||||
}
|
||||
|
||||
function defaultGetSectionHeaderData(
|
||||
dataBlob: any,
|
||||
sectionID: number | string
|
||||
): any {
|
||||
return dataBlob[sectionID];
|
||||
}
|
||||
|
||||
type differType = (data1: any, data2: any) => bool;
|
||||
|
||||
type ParamType = {
|
||||
rowHasChanged: differType;
|
||||
getRowData: ?typeof defaultGetRowData;
|
||||
sectionHeaderHasChanged: ?differType;
|
||||
getSectionHeaderData: ?typeof defaultGetSectionHeaderData;
|
||||
}
|
||||
|
||||
class ListViewDataSource {
|
||||
|
||||
/**
|
||||
* @param {ParamType} params
|
||||
*
|
||||
* You can provide custom extraction and 'hasChanged' functions for section
|
||||
* headers and rows. If absent, data will be extracted with the
|
||||
* `defaultGetRowData` and `defaultGetSectionHeaderData` functions.
|
||||
*
|
||||
* - getRowData(dataBlob, sectionID, rowID);
|
||||
* - getSectionHeaderData(dataBlob, sectionID);
|
||||
* - rowHasChanged(prevRowData, nextRowData);
|
||||
* - sectionHeaderHasChanged(prevSectionData, nextSectionData);
|
||||
*/
|
||||
constructor(params: ParamType) {
|
||||
invariant(
|
||||
params && typeof params.rowHasChanged === 'function',
|
||||
'Must provide a rowHasChanged function.'
|
||||
);
|
||||
this._rowHasChanged = params.rowHasChanged;
|
||||
this._getRowData = params.getRowData || defaultGetRowData;
|
||||
this._sectionHeaderHasChanged = params.sectionHeaderHasChanged;
|
||||
this._getSectionHeaderData =
|
||||
params.getSectionHeaderData || defaultGetSectionHeaderData;
|
||||
|
||||
this._dataBlob = null;
|
||||
this._dirtyRows = [];
|
||||
this._dirtySections = [];
|
||||
this._cachedRowCount = 0;
|
||||
|
||||
// These two private variables are accessed by outsiders because ListView
|
||||
// uses them to iterate over the data in this class.
|
||||
this.rowIdentities = [];
|
||||
this.sectionIdentities = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} dataBlob -- This is an arbitrary blob of data. An extractor
|
||||
* function was defined at construction time. The default extractor assumes
|
||||
* the data is a plain array or keyed object.
|
||||
*/
|
||||
cloneWithRows(
|
||||
dataBlob: Array<any> | {[key: string]: any},
|
||||
rowIdentities: ?Array<string>
|
||||
): ListViewDataSource {
|
||||
var rowIds = rowIdentities ? [rowIdentities] : null;
|
||||
if (!this._sectionHeaderHasChanged) {
|
||||
this._sectionHeaderHasChanged = () => false;
|
||||
}
|
||||
return this.cloneWithRowsAndSections({s1: dataBlob}, ['s1'], rowIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} dataBlob -- This is an arbitrary blob of data. An extractor
|
||||
* function was defined at construction time. The default extractor assumes
|
||||
* the data is a nested array or keyed object of the form:
|
||||
*
|
||||
* { sectionID_1: { rowID_1: <rowData1>, ... }, ... }
|
||||
*
|
||||
* or
|
||||
*
|
||||
* [ [ <rowData1>, <rowData2>, ... ], ... ]
|
||||
*
|
||||
* @param {array} sectionIdentities -- This is an array of identifiers for
|
||||
* sections. ie. ['s1', 's2', ...]. If not provided, it's assumed that the
|
||||
* keys of dataBlob are the section identities.
|
||||
* @param {array} rowIdentities -- This is a 2D array of identifiers for rows.
|
||||
* ie. [['a1', 'a2'], ['b1', 'b2', 'b3'], ...]. If not provided, it's
|
||||
* assumed that the keys of the section data are the row identities.
|
||||
*
|
||||
* Note: this returns a new object!
|
||||
*/
|
||||
cloneWithRowsAndSections(
|
||||
dataBlob: any,
|
||||
sectionIdentities: ?Array<string>,
|
||||
rowIdentities: ?Array<Array<string>>
|
||||
): ListViewDataSource {
|
||||
invariant(
|
||||
typeof this._sectionHeaderHasChanged === 'function',
|
||||
'Must provide a sectionHeaderHasChanged function with section data.'
|
||||
);
|
||||
var newSource = new ListViewDataSource({
|
||||
getRowData: this._getRowData,
|
||||
getSectionHeaderData: this._getSectionHeaderData,
|
||||
rowHasChanged: this._rowHasChanged,
|
||||
sectionHeaderHasChanged: this._sectionHeaderHasChanged,
|
||||
});
|
||||
newSource._dataBlob = dataBlob;
|
||||
if (sectionIdentities) {
|
||||
newSource.sectionIdentities = sectionIdentities;
|
||||
} else {
|
||||
newSource.sectionIdentities = Object.keys(dataBlob);
|
||||
}
|
||||
if (rowIdentities) {
|
||||
newSource.rowIdentities = rowIdentities;
|
||||
} else {
|
||||
newSource.rowIdentities = [];
|
||||
newSource.sectionIdentities.forEach((sectionID) => {
|
||||
newSource.rowIdentities.push(Object.keys(dataBlob[sectionID]));
|
||||
});
|
||||
}
|
||||
newSource._cachedRowCount = countRows(newSource.rowIdentities);
|
||||
|
||||
newSource._calculateDirtyArrays(
|
||||
this._dataBlob,
|
||||
this.sectionIdentities,
|
||||
this.rowIdentities
|
||||
);
|
||||
|
||||
return newSource;
|
||||
}
|
||||
|
||||
getRowCount(): number {
|
||||
return this._cachedRowCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} sectionIndex
|
||||
* @param {number} rowIndex
|
||||
*
|
||||
* Returns if the row is dirtied and needs to be rerendered
|
||||
*/
|
||||
rowShouldUpdate(sectionIndex: number, rowIndex: number): bool {
|
||||
var needsUpdate = this._dirtyRows[sectionIndex][rowIndex];
|
||||
warning(needsUpdate !== undefined,
|
||||
'missing dirtyBit for section, row: ' + sectionIndex + ', ' + rowIndex);
|
||||
return needsUpdate;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} sectionIndex
|
||||
* @param {number} rowIndex
|
||||
*
|
||||
* Gets the data required to render the row.
|
||||
*/
|
||||
getRowData(sectionIndex: number, rowIndex: number): any {
|
||||
var sectionID = this.sectionIdentities[sectionIndex];
|
||||
var rowID = this.rowIdentities[sectionIndex][rowIndex];
|
||||
warning(
|
||||
sectionID !== undefined && rowID !== undefined,
|
||||
'rendering invalid section, row: ' + sectionIndex + ', ' + rowIndex
|
||||
);
|
||||
return this._getRowData(this._dataBlob, sectionID, rowID);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} index
|
||||
*
|
||||
* Gets the rowID at index provided if the dataSource arrays were flattened,
|
||||
* or null of out of range indexes.
|
||||
*/
|
||||
getRowIDForFlatIndex(index: number): ?string {
|
||||
var accessIndex = index;
|
||||
for (var ii = 0; ii < this.sectionIdentities.length; ii++) {
|
||||
if (accessIndex >= this.rowIdentities[ii].length) {
|
||||
accessIndex -= this.rowIdentities[ii].length;
|
||||
} else {
|
||||
return this.rowIdentities[ii][accessIndex];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} index
|
||||
*
|
||||
* Gets the sectionID at index provided if the dataSource arrays were flattened,
|
||||
* or null for out of range indexes.
|
||||
*/
|
||||
getSectionIDForFlatIndex(index: number): ?string {
|
||||
var accessIndex = index;
|
||||
for (var ii = 0; ii < this.sectionIdentities.length; ii++) {
|
||||
if (accessIndex >= this.rowIdentities[ii].length) {
|
||||
accessIndex -= this.rowIdentities[ii].length;
|
||||
} else {
|
||||
return this.sectionIdentities[ii];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array containing the number of rows in each section
|
||||
*/
|
||||
getSectionLengths(): Array<number> {
|
||||
var results = [];
|
||||
for (var ii = 0; ii < this.sectionIdentities.length; ii++) {
|
||||
results.push(this.rowIdentities[ii].length);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} sectionIndex
|
||||
*
|
||||
* Returns if the section header is dirtied and needs to be rerendered
|
||||
*/
|
||||
sectionHeaderShouldUpdate(sectionIndex: number): bool {
|
||||
var needsUpdate = this._dirtySections[sectionIndex];
|
||||
warning(needsUpdate !== undefined,
|
||||
'missing dirtyBit for section: ' + sectionIndex);
|
||||
return needsUpdate;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} sectionIndex
|
||||
*
|
||||
* Gets the data required to render the section header
|
||||
*/
|
||||
getSectionHeaderData(sectionIndex: number): any {
|
||||
if (!this._getSectionHeaderData) {
|
||||
return null;
|
||||
}
|
||||
var sectionID = this.sectionIdentities[sectionIndex];
|
||||
warning(sectionID !== undefined,
|
||||
'renderSection called on invalid section: ' + sectionIndex);
|
||||
return this._getSectionHeaderData(this._dataBlob, sectionID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Private members and methods.
|
||||
*/
|
||||
|
||||
_getRowData: typeof defaultGetRowData;
|
||||
_getSectionHeaderData: typeof defaultGetSectionHeaderData;
|
||||
_rowHasChanged: differType;
|
||||
_sectionHeaderHasChanged: ?differType;
|
||||
|
||||
_dataBlob: any;
|
||||
_dirtyRows: Array<Array<bool>>;
|
||||
_dirtySections: Array<bool>;
|
||||
_cachedRowCount: number;
|
||||
|
||||
// These two 'protected' variables are accessed by ListView to iterate over
|
||||
// the data in this class.
|
||||
rowIdentities: Array<Array<string>>;
|
||||
sectionIdentities: Array<string>;
|
||||
|
||||
_calculateDirtyArrays(
|
||||
prevDataBlob: any,
|
||||
prevSectionIDs: Array<string>,
|
||||
prevRowIDs: Array<Array<string>>
|
||||
): void {
|
||||
// construct a hashmap of the existing (old) id arrays
|
||||
var prevSectionsHash = keyedDictionaryFromArray(prevSectionIDs);
|
||||
var prevRowsHash = {};
|
||||
for (var ii = 0; ii < prevRowIDs.length; ii++) {
|
||||
var sectionID = prevSectionIDs[ii];
|
||||
warning(
|
||||
!prevRowsHash[sectionID],
|
||||
'SectionID appears more than once: ' + sectionID
|
||||
);
|
||||
prevRowsHash[sectionID] = keyedDictionaryFromArray(prevRowIDs[ii]);
|
||||
}
|
||||
|
||||
// compare the 2 identity array and get the dirtied rows
|
||||
this._dirtySections = [];
|
||||
this._dirtyRows = [];
|
||||
|
||||
var dirty;
|
||||
for (var sIndex = 0; sIndex < this.sectionIdentities.length; sIndex++) {
|
||||
var sectionID = this.sectionIdentities[sIndex];
|
||||
// dirty if the sectionHeader is new or _sectionHasChanged is true
|
||||
dirty = !prevSectionsHash[sectionID];
|
||||
var sectionHeaderHasChanged = this._sectionHeaderHasChanged;
|
||||
if (!dirty && sectionHeaderHasChanged) {
|
||||
dirty = sectionHeaderHasChanged(
|
||||
this._getSectionHeaderData(prevDataBlob, sectionID),
|
||||
this._getSectionHeaderData(this._dataBlob, sectionID)
|
||||
);
|
||||
}
|
||||
this._dirtySections.push(!!dirty);
|
||||
|
||||
this._dirtyRows[sIndex] = [];
|
||||
for (var rIndex = 0; rIndex < this.rowIdentities[sIndex].length; rIndex++) {
|
||||
var rowID = this.rowIdentities[sIndex][rIndex];
|
||||
// dirty if the section is new, row is new or _rowHasChanged is true
|
||||
dirty =
|
||||
!prevSectionsHash[sectionID] ||
|
||||
!prevRowsHash[sectionID][rowID] ||
|
||||
this._rowHasChanged(
|
||||
this._getRowData(prevDataBlob, sectionID, rowID),
|
||||
this._getRowData(this._dataBlob, sectionID, rowID)
|
||||
);
|
||||
this._dirtyRows[sIndex].push(!!dirty);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function countRows(allRowIDs) {
|
||||
var totalRows = 0;
|
||||
for (var sectionIdx = 0; sectionIdx < allRowIDs.length; sectionIdx++) {
|
||||
var rowIDs = allRowIDs[sectionIdx];
|
||||
totalRows += rowIDs.length;
|
||||
}
|
||||
return totalRows;
|
||||
}
|
||||
|
||||
function keyedDictionaryFromArray(arr) {
|
||||
if (isEmpty(arr)) {
|
||||
return {};
|
||||
}
|
||||
var result = {};
|
||||
for (var ii = 0; ii < arr.length; ii++) {
|
||||
var key = arr[ii];
|
||||
warning(!result[key], 'Value appears more than once in array: ' + key);
|
||||
result[key] = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
module.exports = ListViewDataSource;
|
||||
Reference in New Issue
Block a user