Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
tree: e28754f341
Fetching contributors…

Cannot retrieve contributors at this time

560 lines (471 sloc) 21.074 kB
<!--
Copyright Facebook Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- This container holds the nile as well as the scrollbar next to it
It also manages fetching data from the various active filters -->
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:nile="fbair.nile.*"
creationComplete="creationComplete(event)"
addedToStage="addedToStage(event)" >
<mx:Canvas id="nileCanvas"
width="100%"
height="100%"
added="nileAdded(event)"
removed="nileRemoved(event)" />
<mx:Box height="100%"
styleName="scrollBarContainer" >
<mx:VScrollBar id="scrollBar"
height="100%"
pageScrollSize="{PageScrollSize}"
pageSize="{nileCanvas.height}"
scrollPosition="{-nile.y}"
maxScrollPosition="{nile.height - nileCanvas.height}"
scroll="scrollNile(event)" />
</mx:Box>
<mx:Script><![CDATA[
import fb.FBConnect;
import fb.FBEvent;
import fb.util.Output;
import fbair.gc.Depot;
import fbair.nile.Nile;
import fbair.nile.renderers.NileRenderer;
import fbair.server.Fetcher;
import fbair.util.display.AnimatedCanvas;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
import flash.utils.getTimer;
import mx.collections.ArrayCollection;
import mx.collections.Sort;
import mx.collections.SortField;
import mx.core.Application;
import mx.events.FlexEvent
import mx.events.FlexNativeWindowBoundsEvent;
import mx.events.ScrollEvent;
import mx.utils.ObjectUtil;
private static const MinAnimationDelay:int = 500;
private static const PageScrollSize:int = 512;
private static const MouseWheelSize:int = 16;
private static const MaxEntries:int = 50;
private static const MaxAnimations:int = 3;
private static const SlideDuration:int = 300; // Milliseconds per renderer
private static var SlideSpeed:Number; // Pixels per millisecond
// Our current filter, and whether we're on a page
[Bindable] public static var CurrentFilter:String;
[Bindable] public static var FilterIsPage:Boolean = false;
// All our niles, keyed by filter_key
private var niles:Object = new Object();
// Our current nile
[Bindable] private var nile:Nile;
// List of story-ids we have absolutely deleted
// We hold on to make sure a quick refresh doesn't revive them.
private var zombies:Object = new Object();
// List of story-ids we just created
// We hold on once to make sure a quick refresh doesn't delete.
private var immunes:Object = new Object();
// Renderer we're sliding to during keyboard motion
// and time when last slide started
private var destRenderer:NileRenderer;
private var slideTime:int = 0;
// Cache of all nile renderer data
public var dataCache:Object = new Object();
// Our active filters, by filter_key
private static var streamFilters:Object = new Object();
// Our active pages, by page_id (but stored as filter_key)
private static var pages:Object = new Object();
// Sorter for anything based on created_time
private var sort:Sort = new Sort();
// One per filter. Key => FilterName, Value => latestUpdate
private var latestUpdates:Object = new Object();
private function getLatestUpdate(filter_key:String):int {
if (latestUpdates[filter_key]) return latestUpdates[filter_key];
else return 0;
}
// Initializing..
private function creationComplete(event:FlexEvent):void {
// Pay attention to window resizing for the scrollbar
Application.application.addEventListener(
FlexNativeWindowBoundsEvent.WINDOW_RESIZE, boundNile);
// Listen to bubbling story_deleted messages
addEventListener(NileRenderer.STORY_REMOVED, storyRemoved);
// Listen for when fetcher is going to the server
// so we can feed it our request in fql
Fetcher.steve.addEventListener(FBEvent.FETCHING_DATA, fetchingData);
// Called by fetcher when it has our data
Fetcher.steve.addEventListener(FBEvent.DATA_RECEIVED, dataReceived);
// Initialize created_time sorter
sort.fields = [new SortField("created_time", false, true)];
}
private function addedToStage(event:Event):void {
// Listen for keypresses to scroll
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
}
// We call this on launch to set up our initial set of filters, if cached
// dataCache should already be set now as well
public function loadInitialFilters(stream_filters:Object,
new_pages:Object):void {
// Populate our filters and their niles
streamFilters = stream_filters;
pages = new_pages;
for (var streamFilter:String in streamFilters)
createInitialNile(streamFilter);
for (var page:String in pages)
createInitialNile(page);
}
private function createInitialNile(key:String):void {
niles[key] = Depot.get(Nile);
niles[key].visible = false;
if (dataCache[key])
niles[key].data = dataCache[key];
nileCanvas.addChild(niles[key]);
}
// When we remove old items from the nile,
// we have to be sure to remove any event listeners from any persistent
// objects or it won't get garbage collected
private function nileRemoved(event:Event):void {
if (event.target is Nile) {
event.target.removeEventListener(Event.RESIZE, boundNile);
Depot.put(event.target);
}
removeMouseWheel(event.target);
}
private function removeMouseWheel(displayObject:*):void {
displayObject.removeEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelNile);
if (displayObject is DisplayObjectContainer)
for (var i:int = 0; i < displayObject.numChildren; i++)
removeMouseWheel(displayObject.getChildAt(i));
}
// Called when something is added to the nile.
// We need to catch mousewheels inside textareas
// So we'll just subscribe to every child and then only listen to the
// original dispatcher to avoid duplicate work with bubbling events
private function nileAdded(event:Event):void {
if (event.target is Nile)
event.target.addEventListener(Event.RESIZE, boundNile);
addMouseWheel(event.target);
}
private function addMouseWheel(displayObject:*):void {
displayObject.addEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelNile);
if (displayObject is DisplayObjectContainer)
for (var i:int = 0; i < displayObject.numChildren; i++)
addMouseWheel(displayObject.getChildAt(i));
}
// Called by master when we're beginning things...
public function beginning():void {
nile.visible = true;
}
// Called by Fetcher when it's about to get data
private function fetchingData(event:FBEvent):void {
// Build our filter-key or statement
var requested_filters:Array = new Array();
for (var streamFilter:String in streamFilters)
requested_filters.push("(filter_key = '" + streamFilter + "' and " +
"created_time >= " + getLatestUpdate(streamFilter) + ")");
// Build our page-id or statement
var requested_pages:Array = new Array();
for (var page:String in pages)
requested_pages.push("(source_id = '" + page + "' and " +
"created_time >= " + getLatestUpdate(streamFilter) + ")");
// Base string for selecting out of stream...
var stream_select:String = "select post_id, source_id, created_time, " +
"actor_id, target_id, app_id, message, attachment, comments, likes, " +
"permalink, attribution, type, filter_key from stream where ";
var stream_order:String = "order by created_time desc";
// Build our queries for filter or pages or both
if (requested_filters.length > 0)
Fetcher.queries.stream = stream_select +
requested_filters.join(" or ") + " " + stream_order
if (requested_pages.length > 0)
Fetcher.queries.pages = stream_select +
requested_pages.join(" or ") + " " + stream_order
}
// Called when data fetcher has new shit for us
private function dataReceived(event:FBEvent):void {
// Ok we're going to take our 'pages' results and rebrand them
// as filters but with an "is_page" flag. That way we can reuse
// and treat them as filters wherever possible...
if (!event.data.stream)
event.data.stream = new Array();
if (event.data.pages)
for each (var page:Object in event.data.pages) {
page.is_page = true;
page.filter_key = page.source_id;
event.data.stream.push(page);
}
// Now set data to our new mega-list in .stream
data = event.data.stream;
// We don't want to allow animating till the next frame...
if (dataCache[CurrentFilter])
addEventListener(Event.ENTER_FRAME, afterUpdatesReturned);
}
private function afterUpdatesReturned(event:Event):void {
removeEventListener(Event.ENTER_FRAME, afterUpdatesReturned);
AnimatedCanvas.Animate = true;
}
// Setting our massive container data (massive, baby, that's what she said)
override public function set data(new_data:Object):void {
// Set LongDelay
var longDelay:Boolean = (new Date()).time - Fetcher.updateTime >
MinAnimationDelay;
// All our updates, wrapped in an array collection
var updates:ArrayCollection = new ArrayCollection(new_data as Array);
var filterSet:ArrayCollection;
var filterKey:String;
var update:Object;
// If we have any zombies, they need to be counted out right away
for (var z:int = 0; z < updates.length; z++)
if (zombies[updates[z].post_id])
updates.removeItemAt(z--);
// Remove everything from dataCache, except immunes, then done w/ immunes
for each (filterSet in dataCache)
for (var f:int = 0; f < filterSet.length; f++)
if (!immunes[filterSet[f].post_id]) filterSet.removeItemAt(f--);
immunes = new Object();
// Push into dataCache, and build global list of ids
for each (update in updates) {
if (!dataCache[update.filter_key]) {
dataCache[update.filter_key] = new ArrayCollection();
dataCache[update.filter_key].sort = sort;
}
dataCache[update.filter_key].addItem(update);
}
// Delete any over the max in each filter list
for each (filterSet in dataCache)
while (filterSet.length > MaxEntries)
filterSet.removeItemAt(filterSet.length-1);
// Update our metadata
updateMetadata();
// Determine BigUpdate
var totalAdditions:int = 0;
for each (update in dataCache[CurrentFilter])
if (nile && !nile.items.hasKey(update.post_id))
totalAdditions++;
var bigUpdate:Boolean = (totalAdditions > MaxAnimations);
Output.log("Total additions in this update: " + totalAdditions);
// Determine whether to animate
AnimatedCanvas.Animate = !bigUpdate && longDelay;
// Set nile data everywhere
for (filterKey in dataCache)
if (niles[filterKey])
niles[filterKey].data = dataCache[filterKey];
// If there's nothing in our current filter, then we need to clear it
if (nile && !dataCache[CurrentFilter])
nile.data = new Array();
}
// Called to update data built off dataCache
public function updateMetadata():void {
// Get latestUpdates on these jonx filters
for (var filterKey:String in dataCache) {
var filterList:ArrayCollection = dataCache[filterKey];
latestUpdates[filterKey] = filterList.length == MaxEntries ?
filterList[filterList.length-1].created_time : 0;
}
}
// Called when user has created their own status update
public function addStatusMessage(storyData:Object):void {
Output.assert(nile != null, "Adding status message with no nile?");
// Into the newsfeed dataCache and currentfilter...
dataCache["nf"].addItem(storyData);
if (CurrentFilter != "nf")
dataCache[CurrentFilter].addItem(storyData);
// Mark immune, then give to NewsFeed and CurrentFilter
// NileRenderers own their data with logic so each
// has to get it's own deep copy via ObjectUtil.copy
immunes[storyData.post_id] = true;
nile.addStory(ObjectUtil.copy(storyData));
if (niles["nf"] && niles["nf"] != nile)
niles["nf"].addStory(ObjectUtil.copy(storyData));
}
// Bubbling event listener informs us that a story wants to be deleted
private function storyRemoved(event:Event):void {
var deadRenderer:NileRenderer = event.target as NileRenderer;
// Sweep out of filters
for each (var filterSet:ArrayCollection in dataCache)
for (var i:int = 0; i < filterSet.length; i++)
if (filterSet[i].post_id == deadRenderer.data.post_id)
filterSet.removeItemAt(i--);
// Zombie
zombies[deadRenderer.data.post_id] = true;
// Remove from all niles
for each (var cur_nile:Nile in niles)
cur_nile.removeStoryByID(deadRenderer.data.post_id);
}
// Called when new filter has added to tab bar
public function filterAdded(filter_key:String,
is_page:Boolean = false):void {
Output.assert(streamFilters[filter_key] == null &&
pages[filter_key] == null,
"Adding filter_key that we already had?: " + filter_key);
Output.assert(niles[filter_key] == null,
"Adding filter_key with nile we had?:" + filter_key);
// Store key in pages or streamFilters
if (is_page)
pages[filter_key] = true;
else
streamFilters[filter_key] = true;
// Create a new nile, and add it
niles[filter_key] = Depot.get(Nile);
niles[filter_key].visible = false;
nileCanvas.addChild(niles[filter_key]);
// poll baby
if (FBConnect.status == FBConnect.Connected) {
FBConnect.dispatcher.dispatchEvent(
new FBEvent(FBEvent.ALERT, "Loading Stream"));
Fetcher.steve.poll();
}
}
// Called when a filter has been removed
public function filterRemoved(filter_key:String):void {
Output.assert(streamFilters[filter_key] != null ||
pages[filter_key] != null,
"Removing filter not in streamFilters or pages?: " + filter_key);
Output.assert(niles[filter_key] != null,
"Removing filter that had no nile?: " + filter_key);
// Remove nile itself
if (nile == niles[filter_key]) {
stopSliding();
nile = null;
}
nileCanvas.removeChild(niles[filter_key]);
delete niles[filter_key];
// Remove from filters and pages
delete streamFilters[filter_key];
delete pages[filter_key];
}
// Called when a new filter is selected!
public function filterSelected(filter_key:String):void {
Output.assert(streamFilters[filter_key] != null ||
pages[filter_key] != null,
"Selecting filter we don't have?: " + filter_key);
Output.assert(niles[filter_key] != null,
"Selecting filter with no nile?: " + filter_key);
Output.assert(CurrentFilter != filter_key,
"Selecting filter that's already current?!");
// Select this filter only if not active, and show what we have
CurrentFilter = filter_key;
FilterIsPage = (pages[filter_key] != null);
// Remove old nile, and stop any sliding
stopSliding();
if (nile) nile.visible = false;
// Select new main nile
nile = niles[filter_key];
boundNile();
Output.log("Now showing key: " + filter_key + " with nile: " + nile);
// We may not have authed yet, so don't show unless we have
if (FBConnect.status == FBConnect.Connected) nile.visible = true;
}
// Called when the nile scrollbar has moved, and we need to move
// the nile itself to keep pace.
private function scrollNile(event:ScrollEvent = null):void {
// No fucking sliding now
stopSliding();
// Move the nile position
nile.y = -scrollBar.scrollPosition;
// Find the renderer on top, and cache it
nile.markTopRenderer();
}
// Called when we move the mouse wheel over the nile, so
// we want to scroll
private function mouseWheelNile(event:MouseEvent):void {
// If not the original dispatcher, then nevermind.
// because we don't want to duplicate scrolling efforts
if (event.target != event.currentTarget) return;
// Move scrollPosition
scrollBar.scrollPosition -= event.delta * MouseWheelSize;
scrollBar.scrollPosition = Math.min(scrollBar.scrollPosition,
scrollBar.maxScrollPosition);
scrollBar.scrollPosition = Math.max(scrollBar.scrollPosition,
scrollBar.minScrollPosition);
// Update the position of the nile based on scrollposition
scrollNile();
}
// Ensures that our nile is not being displayed beyond the scrollable edges
// If we move, we also recache what the topRenderer is
// We do this to ALL niles to make sure none get over limits
private function boundNile(event:Event = null):void {
var cur_nile:Nile = (event && (event.target is Nile) ?
Nile(event.target) : nile);
if (!cur_nile) return;
cur_nile.y = Math.min(0, cur_nile.y);
if (cur_nile.height < nileCanvas.height) {
cur_nile.y = 0;
if (cur_nile == nile)
scrollBar.scrollPosition = 0;
cur_nile.markTopRenderer();
}
else if (cur_nile.y < nileCanvas.height - cur_nile.height) {
cur_nile.y = nileCanvas.height - cur_nile.height;
if (cur_nile == nile)
scrollBar.scrollPosition = scrollBar.maxScrollPosition;
cur_nile.markTopRenderer();
}
}
// For keyboard shortcuts
private function keyDown(event:KeyboardEvent):void {
// If a textfield has focus, then nevermind!
if (focusManager.getFocus()) return;
// Determine where we're going
var oldDest:NileRenderer = destRenderer;
var newDest:NileRenderer;
if (event.keyCode == Keyboard.UP)
newDest = oldDest ? nile.getPrevious(oldDest) : nile.topRenderer;
else if (event.keyCode == Keyboard.DOWN)
newDest = oldDest ? nile.getNext(oldDest) : nile.nextToTopRenderer;
// Nothing changed...
if (newDest == oldDest) return;
// If we have a new destination...
if (newDest) {
destRenderer = newDest;
// Update our speed
SlideSpeed = Math.abs(destRenderer.y + nile.y) / SlideDuration;
// Slide if not already sliding
if (!oldDest) startSliding();
}
}
// Start sliding!
private function startSliding():void {
if (!destRenderer) return;
slideTime = getTimer();
addEventListener(Event.ENTER_FRAME, slide);
}
// Stop Sliding!
private function stopSliding():void {
removeEventListener(Event.ENTER_FRAME, slide);
destRenderer = null;
}
// Called once a frame during slide!
private function slide(event:Event = null):void {
Output.assert(destRenderer != null,
"Sliding with no destRenderer?!");
Output.assert(nile != null,
"Sliding with no nile?!");
// Determine time since last slide call
var slide_duration:int = getTimer() - slideTime;
slideTime = getTimer();
// Determine distance to travel
var orig_y:Number = nile.y;
var travel_y:Number = slide_duration * SlideSpeed;
// Travel
if (destRenderer.y + nile.y < 0)
nile.y += Math.min(travel_y, Math.abs(destRenderer.y + nile.y));
else if (destRenderer.y + nile.y > 0)
nile.y -= Math.min(travel_y, Math.abs(destRenderer.y + nile.y));
// Make sure we didn't overjump things, and re-mark topRenderer
boundNile();
nile.markTopRenderer();
// If we've made no progress or we're at our destination, then stop
if (orig_y == nile.y || destRenderer.y + nile.y == 0) stopSliding();
}
]]></mx:Script>
</mx:HBox>
Jump to Line
Something went wrong with that request. Please try again.