fn2.dart 27.7 KB
Newer Older
1 2 3 4 5 6
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

library fn;

7
import 'app.dart';
8 9 10 11
import 'dart:async';
import 'dart:collection';
import 'dart:mirrors';
import 'dart:sky' as sky;
12
import 'package:vector_math/vector_math.dart';
13
import 'reflect.dart' as reflect;
14 15 16
import 'rendering/block.dart';
import 'rendering/box.dart';
import 'rendering/flex.dart';
H
Hixie 已提交
17
import 'rendering/object.dart';
18
import 'rendering/paragraph.dart';
A
Adam Barth 已提交
19
import 'rendering/stack.dart';
20

21
// final sky.Tracing _tracing = sky.window.tracing;
22 23 24 25

final bool _shouldLogRenderDuration = false;
final bool _shouldTrace = false;

26
enum _SyncOperation { identical, insertion, stateful, stateless, removal }
27 28 29 30 31 32 33 34 35

/*
 * All Effen nodes derive from UINode. All nodes have a _parent, a _key and
 * can be sync'd.
 */
abstract class UINode {
  String _key;
  UINode _parent;
  UINode get parent => _parent;
H
Hixie 已提交
36
  RenderObject root;
37 38 39 40 41 42 43 44 45 46 47 48 49 50
  bool _defunct = false;

  UINode({ Object key }) {
    _key = key == null ? "$runtimeType" : "$runtimeType-$key";
    assert(this is App || _inRenderDirtyComponents); // you should not build the UI tree ahead of time, build it only during build()
  }

  // Subclasses which implements Nodes that become stateful may return true
  // if the |old| node has become stateful and should be retained.
  bool _willSync(UINode old) => false;

  bool get interchangeable => false; // if true, then keys can be duplicated

  void _sync(UINode old, dynamic slot);
H
Hixie 已提交
51
  // 'slot' is the identifier that the parent RenderObjectWrapper uses to know
52 53
  // where to put this descendant

A
Adam Barth 已提交
54
  void remove() {
55
    _defunct = true;
56
    root = null;
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
    handleRemoved();
  }
  void handleRemoved() { }

  UINode findAncestor(Type targetType) {
    var ancestor = _parent;
    while (ancestor != null && !reflectClass(ancestor.runtimeType).isSubtypeOf(reflectClass(targetType)))
      ancestor = ancestor._parent;
    return ancestor;
  }

  int _nodeDepth;
  void _ensureDepth() {
    if (_nodeDepth == null) {
      if (_parent != null) {
        _parent._ensureDepth();
        _nodeDepth = _parent._nodeDepth + 1;
      } else {
        _nodeDepth = 0;
      }
    }
  }

  void _trace(String message) {
    if (!_shouldTrace)
      return;

    _ensureDepth();
    print((' ' * _nodeDepth) + message);
  }

  void _traceSync(_SyncOperation op, String key) {
    if (!_shouldTrace)
      return;

    String opString = op.toString().toLowerCase();
    String outString = opString.substring(opString.indexOf('.') + 1);
    _trace('_sync($outString) $key');
  }

97
  void removeChild(UINode node) {
98
    _traceSync(_SyncOperation.removal, node._key);
A
Adam Barth 已提交
99
    node.remove();
100 101 102
  }

  // Returns the child which should be retained as the child of this node.
103
  UINode syncChild(UINode node, UINode oldNode, dynamic slot) {
104
    if (node == oldNode) {
105
      _traceSync(_SyncOperation.identical, node == null ? '*null*' : node._key);
106 107 108
      return node; // Nothing to do. Subtrees must be identical.
    }

109 110 111 112 113 114 115
    if (node == null) {
      // the child in this slot has gone away
      removeChild(oldNode);
      return null;
    }
    assert(oldNode == null || node._key == oldNode._key);

116 117 118 119
    // TODO(rafaelw): This eagerly removes the old DOM. It may be that a
    // new component was built that could re-use some of it. Consider
    // syncing the new VDOM against the old one.
    if (oldNode != null && node._key != oldNode._key) {
120
      removeChild(oldNode);
121 122 123
    }

    if (node._willSync(oldNode)) {
124
      _traceSync(_SyncOperation.stateful, node._key);
125 126
      oldNode._sync(node, slot);
      node._defunct = true;
H
Hixie 已提交
127
      assert(oldNode.root is RenderObject);
128 129 130 131 132 133 134
      return oldNode;
    }

    assert(!node._defunct);
    node._parent = this;

    if (oldNode == null) {
135
      _traceSync(_SyncOperation.insertion, node._key);
136
    } else {
137
      _traceSync(_SyncOperation.stateless, node._key);
138 139 140 141 142
    }
    node._sync(oldNode, slot);
    if (oldNode != null)
      oldNode._defunct = true;

H
Hixie 已提交
143
    assert(node.root is RenderObject);
144 145 146 147 148 149 150 151 152 153 154
    return node;
  }
}

abstract class ContentNode extends UINode {
  UINode content;

  ContentNode(UINode content) : this.content = content, super(key: content._key);

  void _sync(UINode old, dynamic slot) {
    UINode oldContent = old == null ? null : (old as ContentNode).content;
155
    content = syncChild(content, oldContent, slot);
156 157
    assert(content.root != null);
    root = content.root;
158 159
  }

A
Adam Barth 已提交
160
  void remove() {
161
    if (content != null)
162
      removeChild(content);
A
Adam Barth 已提交
163
    super.remove();
164 165 166 167 168 169 170 171 172
  }
}

class ParentDataNode extends ContentNode {
  final ParentData parentData;

  ParentDataNode(UINode content, this.parentData): super(content);
}

173 174 175
typedef void GestureEventListener(sky.GestureEvent e);
typedef void PointerEventListener(sky.PointerEvent e);
typedef void EventListener(sky.Event e);
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

class EventListenerNode extends ContentNode  {
  final Map<String, sky.EventListener> listeners;

  static Map<String, sky.EventListener> _createListeners({
    EventListener onWheel,
    GestureEventListener onGestureFlingCancel,
    GestureEventListener onGestureFlingStart,
    GestureEventListener onGestureScrollStart,
    GestureEventListener onGestureScrollUpdate,
    GestureEventListener onGestureTap,
    GestureEventListener onGestureTapDown,
    PointerEventListener onPointerCancel,
    PointerEventListener onPointerDown,
    PointerEventListener onPointerMove,
    PointerEventListener onPointerUp,
    Map<String, sky.EventListener> custom
  }) {
    var listeners = custom != null ?
        new HashMap<String, sky.EventListener>.from(custom) :
        new HashMap<String, sky.EventListener>();

    if (onWheel != null)
      listeners['wheel'] = onWheel;
    if (onGestureFlingCancel != null)
      listeners['gestureflingcancel'] = onGestureFlingCancel;
    if (onGestureFlingStart != null)
      listeners['gestureflingstart'] = onGestureFlingStart;
    if (onGestureScrollStart != null)
      listeners['gesturescrollstart'] = onGestureScrollStart;
    if (onGestureScrollUpdate != null)
      listeners['gesturescrollupdate'] = onGestureScrollUpdate;
    if (onGestureTap != null)
      listeners['gesturetap'] = onGestureTap;
    if (onGestureTapDown != null)
      listeners['gesturetapdown'] = onGestureTapDown;
    if (onPointerCancel != null)
      listeners['pointercancel'] = onPointerCancel;
    if (onPointerDown != null)
      listeners['pointerdown'] = onPointerDown;
    if (onPointerMove != null)
      listeners['pointermove'] = onPointerMove;
    if (onPointerUp != null)
      listeners['pointerup'] = onPointerUp;

    return listeners;
  }

  EventListenerNode(UINode content, {
    EventListener onWheel,
    GestureEventListener onGestureFlingCancel,
    GestureEventListener onGestureFlingStart,
    GestureEventListener onGestureScrollStart,
    GestureEventListener onGestureScrollUpdate,
    GestureEventListener onGestureTap,
    GestureEventListener onGestureTapDown,
    PointerEventListener onPointerCancel,
    PointerEventListener onPointerDown,
    PointerEventListener onPointerMove,
    PointerEventListener onPointerUp,
    Map<String, sky.EventListener> custom
  }) : listeners = _createListeners(
         onWheel: onWheel,
         onGestureFlingCancel: onGestureFlingCancel,
         onGestureFlingStart: onGestureFlingStart,
         onGestureScrollUpdate: onGestureScrollUpdate,
         onGestureScrollStart: onGestureScrollStart,
         onGestureTap: onGestureTap,
         onGestureTapDown: onGestureTapDown,
         onPointerCancel: onPointerCancel,
         onPointerDown: onPointerDown,
         onPointerMove: onPointerMove,
         onPointerUp: onPointerUp,
         custom: custom
       ),
       super(content);

  void _handleEvent(sky.Event e) {
    sky.EventListener listener = listeners[e.type];
    if (listener != null) {
      listener(e);
    }
  }
}

/*
H
Hixie 已提交
262
 * RenderObjectWrappers correspond to a desired state of a RenderObject.
263
 * They are fully immutable, with one exception: A UINode which is a
264
 * Component which lives within an MultiChildRenderObjectWrapper's
265 266 267
 * children list, may be replaced with the "old" instance if it has
 * become stateful.
 */
H
Hixie 已提交
268
abstract class RenderObjectWrapper extends UINode {
269

H
Hixie 已提交
270 271
  static final Map<RenderObject, RenderObjectWrapper> _nodeMap =
      new HashMap<RenderObject, RenderObjectWrapper>();
272

H
Hixie 已提交
273
  static RenderObjectWrapper _getMounted(RenderObject node) => _nodeMap[node];
274

H
Hixie 已提交
275
  RenderObjectWrapper({
276
    Object key
277 278
  }) : super(key: key);

H
Hixie 已提交
279
  RenderObject createNode();
280

H
Hixie 已提交
281
  void insert(RenderObjectWrapper child, dynamic slot);
282 283 284

  void _sync(UINode old, dynamic slot) {
    if (old == null) {
285 286
      root = createNode();
      assert(root != null);
H
Hixie 已提交
287 288
      var ancestor = findAncestor(RenderObjectWrapper);
      if (ancestor is RenderObjectWrapper)
289 290
        ancestor.insert(this, slot);
    } else {
291 292
      root = old.root;
      assert(root != null);
293 294
    }

295
    _nodeMap[root] = this;
H
Hixie 已提交
296
    syncRenderObject(old);
297 298
  }

H
Hixie 已提交
299
  void syncRenderObject(RenderObjectWrapper old) {
300 301
    ParentData parentData = null;
    UINode parent = _parent;
H
Hixie 已提交
302
    while (parent != null && parent is! RenderObjectWrapper) {
303 304 305 306 307 308 309 310 311
      if (parent is ParentDataNode && parent.parentData != null) {
        if (parentData != null)
          parentData.merge(parent.parentData); // this will throw if the types aren't the same
        else
          parentData = parent.parentData;
      }
      parent = parent._parent;
    }
    if (parentData != null) {
312 313
      assert(root.parentData != null);
      root.parentData.merge(parentData); // this will throw if the types aren't approriate
314
      assert(parent != null);
315 316
      assert(parent.root != null);
      parent.root.markNeedsLayout();
317 318 319
    }
  }

A
Adam Barth 已提交
320
  void remove() {
321 322
    assert(root != null);
    _nodeMap.remove(root);
A
Adam Barth 已提交
323
    super.remove();
324 325 326
  }
}

H
Hixie 已提交
327
abstract class OneChildRenderObjectWrapper extends RenderObjectWrapper {
A
Adam Barth 已提交
328 329
  final UINode child;

H
Hixie 已提交
330
  OneChildRenderObjectWrapper({ this.child, Object key }) : super(key: key);
A
Adam Barth 已提交
331

A
Adam Barth 已提交
332 333 334
  void syncRenderObject(RenderObjectWrapper old) {
    super.syncRenderObject(old);
    UINode oldChild = old == null ? null : (old as OneChildRenderObjectWrapper).child;
H
Hixie 已提交
335 336 337
    syncChild(child, oldChild, null);
  }

H
Hixie 已提交
338
  void insert(RenderObjectWrapper child, dynamic slot) {
339
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
A
Adam Barth 已提交
340
    assert(slot == null);
341
    assert(root is RenderObjectWithChildMixin);
A
Adam Barth 已提交
342
    root.child = child.root;
343
    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
A
Adam Barth 已提交
344 345
  }

H
Hixie 已提交
346
  void removeChild(UINode node) {
347 348
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
    assert(root is RenderObjectWithChildMixin);
H
Hixie 已提交
349 350
    root.child = null;
    super.removeChild(node);
351
    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
A
Adam Barth 已提交
352 353
  }

A
Adam Barth 已提交
354
  void remove() {
H
Hixie 已提交
355 356
    if (child != null)
      removeChild(child);
A
Adam Barth 已提交
357
    super.remove();
A
Adam Barth 已提交
358 359 360
  }
}

361 362 363 364 365 366 367 368 369
class Clip extends OneChildRenderObjectWrapper {
  RenderClip root;

  Clip({ UINode child, Object key })
    : super(child: child, key: key);

  RenderClip createNode() => new RenderClip();
}

H
Hixie 已提交
370
class Padding extends OneChildRenderObjectWrapper {
A
Adam Barth 已提交
371 372 373 374 375 376 377 378
  RenderPadding root;
  final EdgeDims padding;

  Padding({ this.padding, UINode child, Object key })
    : super(child: child, key: key);

  RenderPadding createNode() => new RenderPadding(padding: padding);

H
Hixie 已提交
379 380
  void syncRenderObject(Padding old) {
    super.syncRenderObject(old);
A
Adam Barth 已提交
381 382 383 384
    root.padding = padding;
  }
}

H
Hixie 已提交
385
class DecoratedBox extends OneChildRenderObjectWrapper {
A
Adam Barth 已提交
386 387 388 389 390 391 392 393
  RenderDecoratedBox root;
  final BoxDecoration decoration;

  DecoratedBox({ this.decoration, UINode child, Object key })
    : super(child: child, key: key);

  RenderDecoratedBox createNode() => new RenderDecoratedBox(decoration: decoration);

H
Hixie 已提交
394 395
  void syncRenderObject(DecoratedBox old) {
    super.syncRenderObject(old);
A
Adam Barth 已提交
396 397 398 399
    root.decoration = decoration;
  }
}

H
Hixie 已提交
400
class SizedBox extends OneChildRenderObjectWrapper {
A
Adam Barth 已提交
401 402 403 404 405 406 407 408
  RenderSizedBox root;
  final sky.Size desiredSize;

  SizedBox({ this.desiredSize, UINode child, Object key })
    : super(child: child, key: key);

  RenderSizedBox createNode() => new RenderSizedBox(desiredSize: desiredSize);

H
Hixie 已提交
409 410
  void syncRenderObject(SizedBox old) {
    super.syncRenderObject(old);
A
Adam Barth 已提交
411 412 413 414
    root.desiredSize = desiredSize;
  }
}

H
Hixie 已提交
415
class Transform extends OneChildRenderObjectWrapper {
416 417 418 419 420 421 422 423
  RenderTransform root;
  final Matrix4 transform;

  Transform({ this.transform, UINode child, Object key })
    : super(child: child, key: key);

  RenderTransform createNode() => new RenderTransform(transform: transform);

H
Hixie 已提交
424 425
  void syncRenderObject(Transform old) {
    super.syncRenderObject(old);
426 427 428 429
    root.transform = transform;
  }
}

430 431 432 433 434 435 436 437 438 439 440 441 442 443
class SizeObserver extends OneChildRenderObjectWrapper {
  RenderSizeObserver root;
  final SizeChangedCallback callback;

  SizeObserver({ this.callback, UINode child, Object key })
    : super(child: child, key: key);

  RenderSizeObserver createNode() => new RenderSizeObserver(callback: callback);

  void syncRenderObject(SizeObserver old) {
    super.syncRenderObject(old);
    root.callback = callback;
  }

A
Adam Barth 已提交
444
  void remove() {
445
    root.callback = null;
A
Adam Barth 已提交
446
    super.remove();
447 448 449
  }
}

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
// TODO(jackson) need a mechanism for marking the RenderCustomPaint as needing paint
class CustomPaint extends OneChildRenderObjectWrapper {
  RenderCustomPaint root;
  final CustomPaintCallback callback;

  CustomPaint({ this.callback, UINode child, Object key })
    : super(child: child, key: key);

  RenderCustomPaint createNode() => new RenderCustomPaint(callback: callback);

  void syncRenderObject(CustomPaint old) {
    super.syncRenderObject(old);
    root.callback = callback;
  }

A
Adam Barth 已提交
465
  void remove() {
466
    root.callback = null;
A
Adam Barth 已提交
467
    super.remove();
468 469
  }
}
470

471 472
final List<UINode> _emptyList = new List<UINode>();

473
abstract class MultiChildRenderObjectWrapper extends RenderObjectWrapper {
474

475
  // In MultiChildRenderObjectWrapper subclasses, slots are RenderObject nodes
H
Hixie 已提交
476
  // to use as the "insert before" sibling in ContainerRenderObjectMixin.add() calls
477 478 479

  final List<UINode> children;

480
  MultiChildRenderObjectWrapper({
481
    Object key,
482
    List<UINode> children
483 484
  }) : this.children = children == null ? _emptyList : children,
  super(
485
    key: key
486 487 488 489
  ) {
    assert(!_debugHasDuplicateIds());
  }

H
Hixie 已提交
490
  void insert(RenderObjectWrapper child, dynamic slot) {
491
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
H
Hixie 已提交
492
    assert(slot == null || slot is RenderObject);
493
    assert(root is ContainerRenderObjectMixin);
494
    root.add(child.root, before: slot);
495
    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
496 497
  }

H
Hixie 已提交
498
  void removeChild(UINode node) {
499
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
A
Adam Barth 已提交
500
    assert(root is ContainerRenderObjectMixin);
H
Hixie 已提交
501 502
    root.remove(node.root);
    super.removeChild(node);
503
    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
H
Hixie 已提交
504 505
  }

A
Adam Barth 已提交
506
  void remove() {
507 508 509
    assert(children != null);
    for (var child in children) {
      assert(child != null);
510
      removeChild(child);
511
    }
A
Adam Barth 已提交
512
    super.remove();
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
  }

  bool _debugHasDuplicateIds() {
    var idSet = new HashSet<String>();
    for (var child in children) {
      assert(child != null);
      if (child.interchangeable)
        continue; // when these nodes are reordered, we just reassign the data

      if (!idSet.add(child._key)) {
        throw '''If multiple non-interchangeable nodes of the same type exist as children
                of another node, they must have unique keys.
                Duplicate: "${child._key}"''';
      }
    }
    return false;
  }

531
  void syncRenderObject(MultiChildRenderObjectWrapper old) {
H
Hixie 已提交
532
    super.syncRenderObject(old);
533

534
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
H
Hixie 已提交
535
    if (root is! ContainerRenderObjectMixin)
536 537 538 539 540
      return;

    var startIndex = 0;
    var endIndex = children.length;

541
    var oldChildren = old == null ? [] : old.children;
542 543 544
    var oldStartIndex = 0;
    var oldEndIndex = oldChildren.length;

H
Hixie 已提交
545
    RenderObject nextSibling = null;
546 547 548 549
    UINode currentNode = null;
    UINode oldNode = null;

    void sync(int atIndex) {
550
      children[atIndex] = syncChild(currentNode, oldNode, nextSibling);
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
      assert(children[atIndex] != null);
    }

    // Scan backwards from end of list while nodes can be directly synced
    // without reordering.
    while (endIndex > startIndex && oldEndIndex > oldStartIndex) {
      currentNode = children[endIndex - 1];
      oldNode = oldChildren[oldEndIndex - 1];

      if (currentNode._key != oldNode._key) {
        break;
      }

      endIndex--;
      oldEndIndex--;
      sync(endIndex);
    }

    HashMap<String, UINode> oldNodeIdMap = null;

    bool oldNodeReordered(String key) {
      return oldNodeIdMap != null &&
             oldNodeIdMap.containsKey(key) &&
             oldNodeIdMap[key] == null;
    }

    void advanceOldStartIndex() {
      oldStartIndex++;
      while (oldStartIndex < oldEndIndex &&
             oldNodeReordered(oldChildren[oldStartIndex]._key)) {
        oldStartIndex++;
      }
    }

    void ensureOldIdMap() {
      if (oldNodeIdMap != null)
        return;

      oldNodeIdMap = new HashMap<String, UINode>();
      for (int i = oldStartIndex; i < oldEndIndex; i++) {
        var node = oldChildren[i];
        if (!node.interchangeable)
          oldNodeIdMap.putIfAbsent(node._key, () => node);
      }
    }

    bool searchForOldNode() {
      if (currentNode.interchangeable)
        return false; // never re-order these nodes

      ensureOldIdMap();
      oldNode = oldNodeIdMap[currentNode._key];
      if (oldNode == null)
        return false;

      oldNodeIdMap[currentNode._key] = null; // mark it reordered
H
Hixie 已提交
607
      assert(root is ContainerRenderObjectMixin);
608 609
      assert(old.root is ContainerRenderObjectMixin);
      assert(oldNode.root != null);
610

611
      (old.root as ContainerRenderObjectMixin).remove(oldNode.root); // TODO(ianh): Remove cast once the analyzer is cleverer
612
      root.add(oldNode.root, before: nextSibling);
613 614 615 616 617

      return true;
    }

    // Scan forwards, this time we may re-order;
618
    nextSibling = root.firstChild;
619 620 621 622 623 624
    while (startIndex < endIndex && oldStartIndex < oldEndIndex) {
      currentNode = children[startIndex];
      oldNode = oldChildren[oldStartIndex];

      if (currentNode._key == oldNode._key) {
        assert(currentNode.runtimeType == oldNode.runtimeType);
625
        nextSibling = root.childAfter(nextSibling);
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
        sync(startIndex);
        startIndex++;
        advanceOldStartIndex();
        continue;
      }

      oldNode = null;
      searchForOldNode();
      sync(startIndex);
      startIndex++;
    }

    // New insertions
    oldNode = null;
    while (startIndex < endIndex) {
      currentNode = children[startIndex];
      sync(startIndex);
      startIndex++;
    }

    // Removals
    currentNode = null;
    while (oldStartIndex < oldEndIndex) {
      oldNode = oldChildren[oldStartIndex];
650
      removeChild(oldNode);
651 652
      advanceOldStartIndex();
    }
653 654

    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
655 656 657
  }
}

658
class BlockContainer extends MultiChildRenderObjectWrapper {
A
Adam Barth 已提交
659 660
  RenderBlock root;
  RenderBlock createNode() => new RenderBlock();
661

662 663
  BlockContainer({ Object key, List<UINode> children })
    : super(key: key, children: children);
664 665
}

666
class StackContainer extends MultiChildRenderObjectWrapper {
A
Adam Barth 已提交
667 668 669 670 671 672 673
  RenderStack root;
  RenderStack createNode() => new RenderStack();

  StackContainer({ Object key, List<UINode> children })
    : super(key: key, children: children);
}

H
Hixie 已提交
674
class Paragraph extends RenderObjectWrapper {
675
  RenderParagraph root;
676
  RenderParagraph createNode() => new RenderParagraph(text: text);
677

678
  final String text;
679

680
  Paragraph({ Object key, this.text }) : super(key: key);
681

H
Hixie 已提交
682 683
  void syncRenderObject(UINode old) {
    super.syncRenderObject(old);
684 685
    root.text = text;
  }
686 687 688 689 690

  void insert(RenderObjectWrapper child, dynamic slot) {
    assert(false);
    // Paragraph does not support having children currently
  }
691 692
}

693
class FlexContainer extends MultiChildRenderObjectWrapper {
694
  RenderFlex root;
695
  RenderFlex createNode() => new RenderFlex(direction: this.direction);
696 697 698 699 700 701

  final FlexDirection direction;

  FlexContainer({
    Object key,
    List<UINode> children,
702
    this.direction: FlexDirection.horizontal
703
  }) : super(key: key, children: children);
704

H
Hixie 已提交
705 706
  void syncRenderObject(UINode old) {
    super.syncRenderObject(old);
707
    root.direction = direction;
708 709 710
  }
}

711
class FlexExpandingChild extends ParentDataNode {
712 713
  FlexExpandingChild(UINode content, [int flex = 1])
    : super(content, new FlexBoxParentData()..flex = flex);
A
Adam Barth 已提交
714 715
}

H
Hixie 已提交
716
class Image extends RenderObjectWrapper {
717 718
  RenderImage root;
  RenderImage createNode() => new RenderImage(this.src, this.size);
719 720

  final String src;
721
  final sky.Size size;
722 723 724

  Image({
    Object key,
725 726
    this.src,
    this.size
727
  }) : super(key: key);
728

H
Hixie 已提交
729 730
  void syncRenderObject(UINode old) {
    super.syncRenderObject(old);
731 732
    root.src = src;
    root.requestedSize = size;
733
  }
734 735 736 737 738

  void insert(RenderObjectWrapper child, dynamic slot) {
    assert(false);
    // Image does not support having children currently
  }
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
}


Set<Component> _mountedComponents = new HashSet<Component>();
Set<Component> _unmountedComponents = new HashSet<Component>();

void _enqueueDidMount(Component c) {
  assert(!_notifingMountStatus);
  _mountedComponents.add(c);
}

void _enqueueDidUnmount(Component c) {
  assert(!_notifingMountStatus);
  _unmountedComponents.add(c);
}

bool _notifingMountStatus = false;

void _notifyMountStatusChanged() {
  try {
    _notifingMountStatus = true;
    _unmountedComponents.forEach((c) => c._didUnmount());
    _mountedComponents.forEach((c) => c._didMount());
    _mountedComponents.clear();
    _unmountedComponents.clear();
  } finally {
    _notifingMountStatus = false;
  }
}

List<Component> _dirtyComponents = new List<Component>();
bool _buildScheduled = false;
bool _inRenderDirtyComponents = false;

void _buildDirtyComponents() {
774
  //_tracing.begin('fn::_buildDirtyComponents');
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800

  Stopwatch sw;
  if (_shouldLogRenderDuration)
    sw = new Stopwatch()..start();

  try {
    _inRenderDirtyComponents = true;

    _dirtyComponents.sort((a, b) => a._order - b._order);
    for (var comp in _dirtyComponents) {
      comp._buildIfDirty();
    }

    _dirtyComponents.clear();
    _buildScheduled = false;
  } finally {
    _inRenderDirtyComponents = false;
  }

  _notifyMountStatusChanged();

  if (_shouldLogRenderDuration) {
    sw.stop();
    print('Render took ${sw.elapsedMicroseconds} microseconds');
  }

801
  //_tracing.end('fn::_buildDirtyComponents');
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
}

void _scheduleComponentForRender(Component c) {
  assert(!_inRenderDirtyComponents);
  _dirtyComponents.add(c);

  if (!_buildScheduled) {
    _buildScheduled = true;
    new Future.microtask(_buildDirtyComponents);
  }
}

abstract class Component extends UINode {
  bool get _isBuilding => _currentlyBuilding == this;
  bool _dirty = true;

  UINode _built;
  final int _order;
  static int _currentOrder = 0;
  bool _stateful;
  static Component _currentlyBuilding;
  List<Function> _mountCallbacks;
  List<Function> _unmountCallbacks;
  dynamic _slot; // cached slot from the last time we were synced

  void onDidMount(Function fn) {
    if (_mountCallbacks == null)
      _mountCallbacks = new List<Function>();

    _mountCallbacks.add(fn);
  }

  void onDidUnmount(Function fn) {
    if (_unmountCallbacks == null)
      _unmountCallbacks = new List<Function>();

    _unmountCallbacks.add(fn);
  }


  Component({ Object key, bool stateful })
      : _stateful = stateful != null ? stateful : false,
        _order = _currentOrder + 1,
        super(key: key);

  Component.fromArgs(Object key, bool stateful)
      : this(key: key, stateful: stateful);

  void _didMount() {
    if (_mountCallbacks != null)
      _mountCallbacks.forEach((fn) => fn());
  }

  void _didUnmount() {
    if (_unmountCallbacks != null)
      _unmountCallbacks.forEach((fn) => fn());
  }

  // TODO(rafaelw): It seems wrong to expose DOM at all. This is presently
  // needed to get sizing info.
H
Hixie 已提交
862
  RenderObject getRoot() => root;
863

A
Adam Barth 已提交
864
  void remove() {
865
    assert(_built != null);
866 867
    assert(root != null);
    removeChild(_built);
868 869
    _built = null;
    _enqueueDidUnmount(this);
A
Adam Barth 已提交
870
    super.remove();
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
  }

  bool _willSync(UINode old) {
    Component oldComponent = old as Component;
    if (oldComponent == null || !oldComponent._stateful)
      return false;

    // Make |this| the "old" Component
    _stateful = false;
    _built = oldComponent._built;
    assert(_built != null);

    // Make |oldComponent| the "new" component
    reflect.copyPublicFields(this, oldComponent);
    oldComponent._built = null;
    oldComponent._dirty = true;
    return true;
  }

  /* There are three cases here:
   * 1) Building for the first time:
   *      assert(_built == null && old == null)
   * 2) Re-building (because a dirty flag got set):
   *      assert(_built != null && old == null)
   * 3) Syncing against an old version
   *      assert(_built == null && old != null)
   */
  void _sync(UINode old, dynamic slot) {
    assert(!_defunct);
    assert(_built == null || old == null);

    Component oldComponent = old as Component;

    _slot = slot;

    var oldBuilt;
    if (oldComponent == null) {
      oldBuilt = _built;
    } else {
      assert(_built == null);
      oldBuilt = oldComponent._built;
    }

    if (oldBuilt == null)
      _enqueueDidMount(this);

    int lastOrder = _currentOrder;
    _currentOrder = _order;
    _currentlyBuilding = this;
    _built = build();
    _currentlyBuilding = null;
    _currentOrder = lastOrder;

924
    _built = syncChild(_built, oldBuilt, slot);
925
    _dirty = false;
926 927
    root = _built.root;
    assert(root != null);
928 929 930 931 932 933 934
  }

  void _buildIfDirty() {
    if (!_dirty || _defunct)
      return;

    _trace('$_key rebuilding...');
935
    assert(root != null);
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
    _sync(null, _slot);
  }

  void scheduleBuild() {
    setState(() {});
  }

  void setState(Function fn()) {
    _stateful = true;
    fn();
    if (_isBuilding || _dirty || _defunct)
      return;

    _dirty = true;
    _scheduleComponentForRender(this);
  }

  UINode build();
}

A
Adam Barth 已提交
956 957
class Container extends Component {
  final UINode child;
958
  final Matrix4 transform;
A
Adam Barth 已提交
959 960 961 962 963 964 965 966
  final EdgeDims margin;
  final BoxDecoration decoration;
  final sky.Size desiredSize;
  final EdgeDims padding;

  Container({
    Object key,
    this.child,
967
    this.transform,
A
Adam Barth 已提交
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
    this.margin,
    this.decoration,
    this.desiredSize,
    this.padding
  }) : super(key: key);

  UINode build() {
    UINode current = child;

    if (padding != null)
      current = new Padding(padding: padding, child: current);

    if (decoration != null)
      current = new DecoratedBox(decoration: decoration, child: current);

    if (desiredSize != null)
      current = new SizedBox(desiredSize: desiredSize, child: current);

    if (margin != null)
      current = new Padding(padding: margin, child: current);

A
Adam Barth 已提交
989 990 991
    if (transform != null)
      current = new Transform(transform: transform, child: current);

A
Adam Barth 已提交
992 993 994 995
    return current;
  }
}

996 997 998
class _AppView extends AppView {
  _AppView() : super(null);

A
Adam Barth 已提交
999 1000
  void dispatchEvent(sky.Event event, HitTestResult result) {
    super.dispatchEvent(event, result);
1001

H
Hixie 已提交
1002
    UINode target = RenderObjectWrapper._getMounted(result.path.first);
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012

    // TODO(rafaelw): StopPropagation?
    while (target != null) {
      if (target is EventListenerNode)
        target._handleEvent(event);
      target = target._parent;
    }
  }
}

1013 1014 1015
abstract class App extends Component {

  App() : super(stateful: true) {
1016
    _appView = new _AppView();
1017 1018 1019
    _scheduleComponentForRender(this);
  }

1020
  AppView _appView;
1021
  AppView get appView => _appView;
1022

1023 1024 1025 1026
  void _buildIfDirty() {
    assert(_dirty);
    assert(!_defunct);
    _trace('$_key rebuilding app...');
1027
    _sync(null, null);
1028
    if (root.parent == null)
1029 1030
      _appView.root = root;
    assert(root.parent is RenderView);
1031 1032 1033 1034 1035 1036 1037
  }
}

class Text extends Component {
  Text(this.data) : super(key: '*text*');
  final String data;
  bool get interchangeable => true;
1038
  UINode build() => new Paragraph(text: data);
1039
}