Skip to content
This repository
tree: e28754f341
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 560 lines (471 sloc) 21.074 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
<!--
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>
Something went wrong with that request. Please try again.