编译组件节点

@param {ANode} aNode 节点对象
@param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
@param {Component} owner 所属组件实例环境
@param {Object} extra 编译所需的一些额外信息
@param {Function} extra.ComponentClass 对应组件类
8891
function (aNode, sourceBuffer, owner, extra) {
        var dataLiteral = '{}';

        sourceBuffer.addRaw('var $sourceSlots = [];');
        if (aNode.children) {
            var defaultSourceSlots = [];
            var sourceSlotCodes = {};

            each(aNode.children, function (child) {
                var slotBind = !child.textExpr && getANodeProp(child, 'slot');
                if (slotBind) {
                    if (!sourceSlotCodes[slotBind.raw]) {
                        sourceSlotCodes[slotBind.raw] = {
                            children: [],
                            prop: slotBind
                        };
                    }

                    sourceSlotCodes[slotBind.raw].children.push(child);
                }
                else {
                    defaultSourceSlots.push(child);
                }
            });

            if (defaultSourceSlots.length) {
                sourceBuffer.addRaw('$sourceSlots.push([function (componentCtx) {');
                sourceBuffer.addRaw('  var html = "";');
                defaultSourceSlots.forEach(function (child) {
                    aNodeCompiler.compile(child, sourceBuffer, owner);
                });
                sourceBuffer.addRaw('  return html;');
                sourceBuffer.addRaw('}]);');
            }

            for (var key in sourceSlotCodes) {
                var sourceSlotCode = sourceSlotCodes[key];
                sourceBuffer.addRaw('$sourceSlots.push([function (componentCtx) {');
                sourceBuffer.addRaw('  var html = "";');
                sourceBuffer.addRaw(sourceSlotCode.children.forEach(function (child) {
                    aNodeCompiler.compile(child, sourceBuffer, owner);
                }));
                sourceBuffer.addRaw('  return html;');
                sourceBuffer.addRaw('}, ' + compileExprSource.expr(sourceSlotCode.prop.expr) + ']);');
            }
        }


        var givenData = [];
        each(camelComponentBinds(aNode.props), function (prop) {
            postProp(prop);
            givenData.push(
                compileExprSource.stringLiteralize(prop.name)
                + ':'
                + compileExprSource.expr(prop.expr)
            );
        });

        dataLiteral = '{' + givenData.join(',\n') + '}';
        if (aNode.directives.bind) {
            dataLiteral = 'extend('
                + compileExprSource.expr(aNode.directives.bind.value)
                + ', '
                + dataLiteral
                + ')';
        }

        var renderId = compileComponentSource(sourceBuffer, extra.ComponentClass, owner.ssrContextId);
        sourceBuffer.addRaw('html += componentRenderers.' + renderId + '(');
        sourceBuffer.addRaw(dataLiteral + ', true, componentCtx, '
            + stringifier.str(aNode.tagName) + ', $sourceSlots);');
        sourceBuffer.addRaw('$sourceSlots = null;');
    }
498993
function (aNode, sourceBuffer) {
        if (aNode.textExpr.original) {
            sourceBuffer.joinString(serializeStump('text'));
        }

        if (aNode.textExpr.value != null) {
            sourceBuffer.joinString(aNode.textExpr.segs[0].literal);
        }
        else {
            sourceBuffer.joinExpr(aNode.textExpr);
        }

        if (aNode.textExpr.original) {
            sourceBuffer.joinString(serializeStumpEnd('text'));
        }
    }
590580
function (internalInstance, nextElement, transaction, context) {
    var prevElement = internalInstance._currentElement;

    if (nextElement === prevElement && context === internalInstance._context) {
      // Since elements are immutable after the owner is rendered,
      // we can do a cheap identity compare here to determine if this is a
      // superfluous reconcile. It's possible for state to be mutable but such
      // change should trigger an update of the owner which would recreate
      // the element. We explicitly check for the existence of an owner since
      // it's possible for an element created outside a composite to be
      // deeply mutated and reused.

      // TODO: Bailing out early is just a perf optimization right?
      // TODO: Removing the return statement should affect correctness?
      return;
    }

    if (process.env.NODE_ENV !== 'production') {
      if (internalInstance._debugID !== 0) {
        ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement);
      }
    }

    var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement);

    if (refsChanged) {
      ReactRef.detachRefs(internalInstance, prevElement);
    }

    internalInstance.receiveComponent(nextElement, transaction, context);

    if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) {
      transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
    }

    if (process.env.NODE_ENV !== 'production') {
      if (internalInstance._debugID !== 0) {
        ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);
      }
    }
  }
347214
function (sourceBuffer, aNode, owner) {
        // inner content
        if (aNode.tagName === 'textarea') {
            var valueProp = getANodeProp(aNode, 'value');
            if (valueProp) {
                sourceBuffer.joinRaw('escapeHTML('
                    + compileExprSource.expr(valueProp.expr)
                    + ')'
                );
            }

            return;
        }

        var htmlDirective = aNode.directives.html;
        if (htmlDirective) {
            sourceBuffer.joinExpr(htmlDirective.value);
        }
        else {
            /* eslint-disable no-use-before-define */
            each(aNode.children, function (aNodeChild) {
                aNodeCompiler.compile(aNodeChild, sourceBuffer, owner);
            });
            /* eslint-enable no-use-before-define */
        }
    }
149951
function compile(inFile, outFile, sourceMap, cb) {
    console.log('Compiling ' + inFile + ' to ' + outFile);
    var outStream = fs.createWriteStream(outFile, 'utf8');
    outStream.on('close', cb);
    browserify({debug: true})
      .require(inFile, { entry: true })
      .bundle()
      .pipe(exorcist(sourceMap))
      .pipe(outStream);
}
1133876
function initSource(inputModule) {

  const eventIn = new lfo.source.EventIn({
    frameType: 'vector',
    frameSize: 3,
    frameRate: 1,
  });

  const socketSend = new lfo.sink.SocketSend({
    port: 3000
  });

  const template = (frame) => {
    return `
      <p>time: ${frame.time}</p>
      <ul>
        <li>alpha: ${frame.data[0]}</li>
        <li>beta: ${frame.data[1]}</li>
        <li>gamma: ${frame.data[2]}</li>
      </ul>
    `;
  }

  const bridge = new lfo.sink.Bridge({
    processFrame: (frame) => {
      const html = template(frame);
      $container.innerHTML = html;
    }
  });

  eventIn.connect(socketSend);
  eventIn.connect(bridge);

  eventIn.init().then(() => {
    eventIn.start();

    inputModule.addListener((data) => {
      const now = window.performance.now() / 1000;
      eventIn.process(now, data);
    });
  });
}
1201516
function(component, ref, owner) {
    ("production" !== "development" ? invariant(
      ReactOwner.isValidOwner(owner),
      'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. This ' +
      'usually means that you\'re trying to remove a ref to a component that ' +
      'doesn\'t have an owner (that is, was not created inside of another ' +
      'component\'s `render` method). Try rendering this component inside of ' +
      'a new top-level component which will hold the ref.'
    ) : invariant(ReactOwner.isValidOwner(owner)));
    // Check that `component` is still the current ref because we do not want to
    // detach the ref if another component stole it.
    if (owner.getPublicInstance().refs[ref] === component.getPublicInstance()) {
      owner.detachRef(ref);
    }
  }
824791
function genComponentContextCode(component, componentIdInContext) {
    var code = ['var componentCtx = {'];

    // proto
    code.push('proto: ' + componentIdInContext + 'Proto,');

    // sourceSlots
    code.push('sourceSlots: sourceSlots,');

    // data
    var defaultData = component.data.get();
    code.push('data: data || ' + stringifier.any(defaultData) + ',');

    // parentCtx
    code.push('owner: parentCtx,');

    // slotRenderers
    code.push('slotRenderers: {}');

    code.push('};');

    return code.join('\n');
}
1195883
function initText(elem, parsed, extra){
  var param = extra.param;
  var throttle, lazy = param.lazy

  if('throttle' in param){
    // <input throttle r-model>
    if(param.throttle === true){
      throttle = 400;
    }else{
      throttle = parseInt(param.throttle, 10)
    }
  }

  var self = this;
  var wc = this.$watch(parsed, function(newValue){
    if(elem.value !== newValue) elem.value = newValue == null? "": "" + newValue;
  }, STABLE);

  // @TODO to fixed event
  var isCompositing = false;
  var handler = function (ev){

    if(isCompositing) return;

    isCompositing = false;

    var that = this;
    if(ev.type==='cut' || ev.type==='paste'){
      _.nextTick(function(){
        var value = that.value
        parsed.set(self, value);
        wc.last = value;
        self.$update();
      })
    }else{
        var value = that.value
        parsed.set(self, value);
        wc.last = value;
        self.$update();
    }
  };

  function onCompositionStart(){
    isCompositing = true;
  }

  function onCompositionEnd(ev){
    isCompositing = false;
    handler.call(this,ev)
  }

  if(throttle && !lazy){
    var preHandle = handler, tid;
    handler = _.throttle(handler, throttle);
  }

  if(hasInput === undefined){
    hasInput = dom.msie !== 9 && "oninput" in document.createElement('input')
  }

  if(lazy){
    dom.on(elem, 'change', handler)
  }else{

    if(typeof CompositionEvent === 'function' ){ //lazy的情况不需要compositionend
      elem.addEventListener("compositionstart", onCompositionStart );
      elem.addEventListener("compositionend", onCompositionEnd );
    }

    if( hasInput){
      elem.addEventListener("input", handler );
    }else{
      dom.on(elem, "paste keyup cut change", handler)
    }
  }
  if(parsed.get(self) === undefined && elem.value){
     parsed.set(self, elem.value);
  }
  return function (){
    if(lazy) return dom.off(elem, "change", handler);
    if( hasInput ){
      elem.removeEventListener("input", handler );
    }else{
      dom.off(elem, "paste keyup cut change", handler)
    }
  }
}
391836
function compileExpression(expression, extraFunctions /* optional */) {
    var functions = {
        abs: Math.abs,
        ceil: Math.ceil,
        floor: Math.floor,
        log: Math.log,
        max: Math.max,
        min: Math.min,
        random: Math.random,
        round: Math.round,
        sqrt: Math.sqrt,
    };
    if (extraFunctions) {
        for (var name in extraFunctions) {
            if (extraFunctions.hasOwnProperty(name)) {
                functions[name] = extraFunctions[name];
            }
        }
    }
    if (!compileExpression.parser) {
        // Building the original parser is the heaviest part. Do it
        // once and cache the result in our own function.
        compileExpression.parser = filtrexParser();
    }
    var tree = compileExpression.parser.parse(expression);

    var js = [];
    js.push('return ');
    function toJs(node) {
        if (Array.isArray(node)) {
            node.forEach(toJs);
        } else {
            js.push(node);
        }
    }
    tree.forEach(toJs);
    js.push(';');

    function unknown(funcName) {
        throw 'Unknown function: ' + funcName + '()';
    }

    function prop(obj, name) {
        return Object.prototype.hasOwnProperty.call(obj||{}, name) ? obj[name] : undefined;
    }

    var func = new Function('functions', 'data', 'unknown', 'prop', js.join(''));

    return function(data) {
        return func(functions, data, unknown, prop);
    };
}
952705
protected void addSource (
        DragSource source, JComponent comp, boolean autoremove)
    {
        _draggers.put(comp, source);
        comp.addMouseListener(_sourceListener);
        comp.addMouseMotionListener(_sourceListener);
        if (autoremove) {
            comp.addAncestorListener(_remover);
        }
    }
1109897
function parents(instance, context) {
            var results = []
            var parent
            if (context === undefined) return results

            // parents(instance, array)
            if (!Util.isString(context) && !context.nodeType && context.length) {
                Util.each(context, function(item /*, index*/ ) {
                    results = results.concat(parents(instance, item))
                })
                return results
            }

            // 从当前组件 instance 开始，逐层向上遍历

            // parents(instance, component)
            if (context.options && context.render) {
                parent = instance

                // 在 instance 的祖先元素中，查找与 context.clientId 匹配的元素
                while ((parent = CACHE[parent.parentClientId])) {
                    if (parent.clientId === context.clientId) {
                        results.push(parent)
                        break
                    }
                }

            } else if (context.nodeType) {
                // parents(instance, element)
                parent = instance.element

                // 在 instance 的祖先元素中，查找与 context 相等的元素
                while ((parent = parent.parentNode)) {
                    if (parent === context) {
                        results.push(parent)
                        break
                    }
                }

            } else {
                // parents(instance, moduleId)    
                parent = instance

                // 在 instance 的祖先元素中，查找与 context 匹配的元素
                while ((parent = CACHE[parent.parentClientId])) {
                    if (parent.moduleId === context) {
                        results.push(parent)
                    }
                }
            }

            return results
        }
394903
function CustomBuffer(existingBuffer) {
    var buffer = existingBuffer || new Buffer(48);
    var offset = 0;

    this.writeVarInt = function(val) {
        while (true) {
            if ((val & 0xFFFFFF80) == 0) {
                this.writeUByte(val);

                return;
            }

            this.writeUByte(val & 0x7F | 0x80);

            val = val >>> 7;
        }
    };

    this.writeString = function(string) {
        this.writeVarInt(string.length);

        if (offset + string.length >= buffer.length) {
            Buffer.concat([buffer, new Buffer(string.length)]);
        }

        buffer.write(string, offset, string.length, "UTF-8");

        offset += string.length;
    };

    this.writeUShort = function(val) {
        this.writeUByte(val >> 8);
        this.writeUByte(val & 0xFF);
    };

    this.writeUByte = function(val) {
        if (offset + 1 >= buffer.length) {
            Buffer.concat([buffer, new Buffer(50)]);
        }

        buffer.writeUInt8(val, offset++);
    };

    this.readVarInt = function() {
        var val = 0;
        var count = 0;

        while (true) {
            var i = buffer.readUInt8(offset++);

            val |= (i & 0x7F) << count++ * 7;

            if ((i & 0x80) != 128) {
                break
            }
        }

        return val;
    };

    this.readString = function() {
        var length = this.readVarInt();
        var str = buffer.toString("UTF-8", offset, offset + length);

        offset += length;
        
        return str;
    };

    this.buffer = function() {
        return buffer.slice(0, offset);
    };

    this.offset = function() {
        return offset;
    };
}
517332
function instantiateReactComponent(node, shouldHaveDebugID) {
  var instance;

  if (node === null || node === false) {
    instance = ReactEmptyComponent.create(instantiateReactComponent);
  } else if (typeof node === 'object') {
    var element = node;
    !(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? "development" !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : _prodInvariant('130', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : void 0;

    // Special case string values
    if (typeof element.type === 'string') {
      instance = ReactHostComponent.createInternalComponent(element);
    } else if (isInternalComponentType(element.type)) {
      // This is temporarily available for custom components that are not string
      // representations. I.e. ART. Once those are updated to use the string
      // representation, we can drop this code path.
      instance = new element.type(element);

      // We renamed this. Allow the old name for compat. :(
      if (!instance.getHostNode) {
        instance.getHostNode = instance.getNativeNode;
      }
    } else {
      instance = new ReactCompositeComponentWrapper(element);
    }
  } else if (typeof node === 'string' || typeof node === 'number') {
    instance = ReactHostComponent.createInstanceForText(node);
  } else {
    !false ? "development" !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : _prodInvariant('131', typeof node) : void 0;
  }

  if ("development" !== 'production') {
    "development" !== 'production' ? warning(typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.getHostNode === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : void 0;
  }

  // These two fields are used by the DOM and ART diffing algorithms
  // respectively. Instead of using expandos on components, we should be
  // storing the state needed by the diffing algorithms elsewhere.
  instance._mountIndex = 0;
  instance._mountImage = null;

  if ("development" !== 'production') {
    instance._debugID = shouldHaveDebugID ? nextDebugID++ : 0;
  }

  // Internal instances should fully constructed at this point, so they should
  // not get any new fields added to them at this point.
  if ("development" !== 'production') {
    if (Object.preventExtensions) {
      Object.preventExtensions(instance);
    }
  }

  return instance;
}
424018
function (component, ref, owner) {
    !ReactOwner.isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('119') : void 0;
    owner.attachRef(ref, component);
  }
1039518
function compileComponentSource(sourceBuffer, ComponentClass, contextId) {
    ComponentClass.ssrContext = ComponentClass.ssrContext || {};
    var componentIdInContext = ComponentClass.ssrContext[contextId];

    if (!componentIdInContext) {
        componentIdInContext = genSSRId();
        ComponentClass.ssrContext[contextId] = componentIdInContext;

        // 先初始化个实例，让模板编译成 ANode，并且能获得初始化数据
        var component = new ComponentClass();
        component.ssrContextId = contextId;

        if (component.components) {
            Object.keys(component.components).forEach(
                function (key) {
                    var CmptClass = component.components[key];
                    if (CmptClass instanceof ComponentLoader) {
                        CmptClass = CmptClass.placeholder;
                    }

                    if (CmptClass) {
                        compileComponentSource(sourceBuffer, CmptClass, contextId);
                    }
                }
            );
        }

        sourceBuffer.addRaw('componentRenderers.' + componentIdInContext + ' = componentRenderers.'
            + componentIdInContext + '|| ' + componentIdInContext + ';');

        sourceBuffer.addRaw('var ' + componentIdInContext + 'Proto = ' + genComponentProtoCode(component));
        sourceBuffer.addRaw('function ' + componentIdInContext
            + '(data, noDataOutput, parentCtx, tagName, sourceSlots) {');
        sourceBuffer.addRaw('var html = "";');

        sourceBuffer.addRaw(genComponentContextCode(component, componentIdInContext));


        // init data
        var defaultData = component.data.get();
        sourceBuffer.addRaw('if (data) {');
        Object.keys(defaultData).forEach(function (key) {
            sourceBuffer.addRaw('componentCtx.data["' + key + '"] = componentCtx.data["' + key + '"] || '
                + stringifier.any(defaultData[key]) + ';');
        });
        sourceBuffer.addRaw('}');

        // calc computed
        sourceBuffer.addRaw('var computedNames = componentCtx.proto.computedNames;');
        sourceBuffer.addRaw('for (var $i = 0; $i < computedNames.length; $i++) {');
        sourceBuffer.addRaw('  var $computedName = computedNames[$i];');
        sourceBuffer.addRaw('  data[$computedName] = componentCtx.proto.computed[$computedName](componentCtx);');
        sourceBuffer.addRaw('}');


        var ifDirective = component.aNode.directives['if']; // eslint-disable-line dot-notation
        if (ifDirective) {
            sourceBuffer.addRaw('if (' + compileExprSource.expr(ifDirective.value) + ') {');
        }

        elementSourceCompiler.tagStart(sourceBuffer, component.aNode, 'tagName');


        sourceBuffer.addRaw('if (!noDataOutput) {');
        sourceBuffer.joinDataStringify();
        sourceBuffer.addRaw('}');


        elementSourceCompiler.inner(sourceBuffer, component.aNode, component);
        elementSourceCompiler.tagEnd(sourceBuffer, component.aNode, 'tagName');

        if (ifDirective) {
            sourceBuffer.addRaw('}');
        }

        sourceBuffer.addRaw('return html;');
        sourceBuffer.addRaw('};');
    }

    return componentIdInContext;
}
349579
function enhance(Component, ...args) {
	let oComp = new Component(...args);

	// 添加字段
	enhanceFields(oComp);	// 组件对象ID等

	// 添加方法
	enhanceRender(oComp);	// 组件渲染
	enhanceState(oComp);	// 组件状态存取
	enhanceRef(oComp);		// 按引用名取DOM节点或组件对象
	enhanceRoot(oComp);		// 取组件根节点DOM元素

	return oComp;
}