<commit_before>var hookx = function (matcher, move, event, targetChild) {
    var recover = function (element) {
        moveMargin(element, 0);
    };
    var moveMargin = function (element, movePixels) {
        if (element.moved === movePixels) return;
        element.moved = movePixels;
        element.moving = new Date;
        css(element, {
            transition: movePixels !== false ? "margin .1s" : '',
            userSelect: "none",
            marginLeft: movePixels ? fromOffset(movePixels) : "",
            marginRight: movePixels ? fromOffset(-movePixels) : ""
        });
        if (isArray(element.with)) {
            element.with.map(function (element) {
                moveMargin(element, movePixels);
            });
        }
    };
    var cloneCell = function (element) {
        var targets = getTargetIn(matcher, element, false);
        if (isArray(targets)) {
            var extra = targets.slice(1);
            targets = cloneVisible(targets[0]);
            targets.extraStyles = extra.map(function (extra) {
                var style = extra.style;
                return [style.opacity, style.filter];
            });
            targets.extra = extra;
            once("remove")(targets, function () {
                var { extra, extraStyles } = this;
                extra.map(function (elem, cx) {
                    var [opacity, filter] = extraStyles[cx];
                    extend(elem.style, {
                        opacity,
                        filter
                    });
                });
                delete this.extra;
            });
            targets.with = extra.map(cloneVisible);
            extra.map(function (elem) {
                setOpacity(elem, 0);
            });
        } else {
            targets = cloneVisible(targets);
        }
        return targets;
    };
    if (event.target === this) return;
    // var targetChild = getTargetIn(matcher, event.target);
    if (!targetChild) return;
    drag(targetChild, event, false);
    if (isArray(targetChild)) {
        targetChild = targetChild[0];
    }
    var targetBox = targetChild.parentNode;
    var saved_opacity = targetBox.style.opacity;
    var saved_filter = targetBox.style.filter;
    var previousElements = getPreviousElementSiblings(targetChild), followedElements = getFollowedElementSiblings(targetChild);
    var offall = function () {
        offmousup();
        offtouchend();
        offdragstart();
        offtouchconcel();
    };
    var offtouchconcel = on("touchconcel")(targetChild, offall);
    var offtouchend = on("touchend")(targetChild, offall);
    var offmousup = on("mouseup")(window, offall);
    var autoScroll = function () {
        if (autoScroll.ing) return;

        autoScroll.ing = setInterval(function () {
            var dragTarget = drag.target;
            if (!dragTarget) return;
            var areaPosition = getScreenPosition(targetBox);
            var dragPosition = getScreenPosition(dragTarget);
            var scrollDelta = 0;
            if (dragPosition.left - 40 < areaPosition.left && dragPosition.right + 20 > areaPosition.left) {
                scrollDelta = dragPosition.left - 20 - areaPosition.left;
            } else if (dragPosition.right + 40 > areaPosition.right && dragPosition.left - 20 < areaPosition.right) {
                scrollDelta = dragPosition.right + 20 - areaPosition.right;
            }
            if (scrollDelta) {
                vscroll.X.call(targetBox, scrollDelta / 16, false);
                moveChildren();
            }
        }, 16);
    };
    var cancelScroll = function () {
        clearInterval(autoScroll.ing);
        autoScroll.ing = 0;
    };
    var moveChildren = function () {
        var dragTarget = drag.target;
        if (dragTarget) {
            var area = overlap(dragTarget, targetBox);
            if (area > 0) {
                var dragPosition = getScreenPosition(dragTarget);
                var dragPositionLeft = dragPosition.left;
                var currentTime = new Date;
                previousElements.map(function (element) {
                    if (currentTime - element.moving < 100) return;
                    var elementPosition = getScreenPosition(element);
                    var elementCenter = elementPosition.left + elementPosition.width / 2;
                    if (elementCenter - (element.moved || 0) <= dragPositionLeft) {
                        recover(element);
                    } else {
                        moveMargin(element, dragPosition.width);
                    }
                });
                var dragPositionRight = dragPosition.left + dragPosition.width;
                followedElements.map(function (element) {
                    if (currentTime - element.moving < 100) return;
                    var elementPosition = getScreenPosition(element);
                    var elementCenter = elementPosition.left + elementPosition.width / 2;
                    if (elementCenter - (element.moved || 0) <= dragPositionRight) {
                        moveMargin(element, -dragPosition.width);
                    } else {
                        recover(element);
                    }
                });
            } else {
                previousElements.map(recover);
                followedElements.map(recover);
            }
        } else {
            previousElements.map(recover);
            followedElements.map(recover);
        }
    };
    // 修改margin无效的情况
    function dragclone() {
        addClass(targetBox, 'dropping');
        previousElements = previousElements.map(cloneCell);
        followedElements = followedElements.map(cloneCell);
        setOpacity(targetBox, 0);
        appendChild(document.body, previousElements);
        appendChild(document.body, followedElements);
        var offall = function () {
            offdragmove();
            offdragend();
            removeClass(targetBox, "dropping");
        };
        var offdragend = on("dragend")(targetChild, function () {
            offall();
            css(targetBox, { opacity: saved_opacity, filter: saved_filter });
            remove(previousElements);
            remove(followedElements);
            var dst, appendSibling, delta;
            var src = previousElements.length;
            if (previousElements.length && previousElements[0].moved) for (var cx = 1, dx = previousElements.length + 1; cx < dx; cx++) {
                if (!previousElements[cx]) {
                    dst = 0;
                    delta = 0;
                    appendSibling = appendChild.before;
                } else if (!previousElements[cx].moved) {
                    dst = previousElements.length - cx;
                    delta = -1;
                    appendSibling = appendChild.after;
                    break;
                }
            }

            if (followedElements.length && followedElements[0].moved) for (var cx = 1, dx = followedElements.length + 1; cx < dx; cx++) {
                if (!followedElements[cx]) {
                    dst = followedElements.length + previousElements.length;
                    delta = 0;
                    appendSibling = appendChild.after;
                } else if (!followedElements[cx].moved) {
                    dst = previousElements.length + cx;
                    delta = 1;
                    appendSibling = appendChild.before;
                    break;
                }
            }
            previousElements.map(recover);
            followedElements.map(recover);
            if (appendSibling) {
                var children = this.parentNode.children;
                var srcElement = children[src];
                var dstElement = children[dst + delta];
                appendSibling(dstElement, srcElement);
                isFunction(move) && move(src, dst, dst + delta, appendSibling, this.parentNode);
            }
        });
        var offdragmove = on("dragmove")(targetChild, moveChildren);
    }
    // 仅修改Margin就可以实现拖拽效果
    function draglist() {
        addClass(targetBox, 'dropping');
        autoScroll();
        var style = targetBox.style;
        var savedStyle = { overflow: style.overflow, display: style.display };
        css(targetBox, "overflow:hidden;display:block");
        var offall = function () {
            cancelScroll();
            offdragmove();
            offdragend();
            removeClass(targetBox, "dropping");
            css(targetBox, savedStyle);
        };
        var offdragend = on("dragend")(targetChild, function () {
            offall();
            css(targetBox, { opacity: saved_opacity, filter: saved_filter });
            var dst, appendSibling, delta;
            var src = previousElements.length;
            if (previousElements.length && previousElements[0].moved) for (var cx = 1, dx = previousElements.length + 1; cx < dx; cx++) {
                if (!previousElements[cx]) {
                    dst = 0;
                    delta = 0;
                    appendSibling = appendChild.before;
                } else if (!previousElements[cx].moved) {
                    dst = previousElements.length - cx;
                    delta = -1;
                    appendSibling = appendChild.after;
                    break;
                }
            }

            if (followedElements.length && followedElements[0].moved) for (var cx = 1, dx = followedElements.length + 1; cx < dx; cx++) {
                if (!followedElements[cx]) {
                    dst = followedElements.length + previousElements.length;
                    delta = 0;
                    appendSibling = appendChild.after;
                } else if (!followedElements[cx].moved) {
                    dst = previousElements.length + cx;
                    delta = 1;
                    appendSibling = appendChild.before;
                    break;
                }
            }
            previousElements.map(e => moveMargin(e, false));
            followedElements.map(e => moveMargin(e, false));
            if (appendSibling) {
                var children = this.parentNode.children;
                var srcElement = children[src];
                var dstElement = children[dst + delta];
                appendSibling(dstElement, srcElement);
                isFunction(move) && move(src, dst, dst + delta, appendSibling, this.parentNode);
            }
        });
        var offdragmove = on("dragmove")(targetChild, moveChildren);
    }
    if (/^table/i.test(getComputedStyle(targetChild).display)) {
        var offdragstart = on("dragstart")(targetChild, dragclone);
    } else {
        var offdragstart = on("dragstart")(targetChild, draglist);
    }
};
var hooky = arriswise(hookx, arguments);
var hook = function (matcher, move, event) {
    if (event.target === this) return;
    var targetChild = getTargetIn(matcher, event.target, false);
    if (!targetChild) return;
    var run;
    if (/cell|inline/i.test(getComputedStyle(targetChild instanceof Array ? targetChild[0] : targetChild).display)) {
        run = hookx;
    } else {
        run = hooky;
    }
    run.call(this, matcher, move, event, targetChild);
};

function autodragchildren(target, matcher, move) {
    onmousedown(target, hook.bind(target, matcher, move));
    ontouchstart(target, hook.bind(target, matcher, move));
    return target;
}
<commit_msg>支持拖拽添加<commit_after>var moveMarginX = function moveMarginX(element, movePixels) {
    if (element.moved === movePixels) return;
    element.moved = movePixels;
    element.moving = new Date;
    css(element, {
        transition: movePixels !== false ? "margin .1s" : '',
        userSelect: "none",
        marginLeft: movePixels ? fromOffset(movePixels) : "",
        marginRight: movePixels ? fromOffset(-movePixels) : ""
    });
    if (isArray(element.with)) {
        element.with.map(function (element) {
            moveMarginX(element, movePixels);
        });
    }
};
var moveChildrenX = function (targetBox, previousElements, followedElements, moveMargin, recover) {
    var dragTarget = drag.target;
    if (dragTarget) {
        var area = overlap(dragTarget, targetBox);
        if (area > 0) {
            var dragPosition = getScreenPosition(dragTarget);
            var dragPositionLeft = dragPosition.left;
            var currentTime = new Date;
            previousElements.map(function (element) {
                if (currentTime - element.moving < 100) return;
                var elementPosition = getScreenPosition(element);
                var elementCenter = elementPosition.left + elementPosition.width / 2;
                if (elementCenter - (element.moved || 0) <= dragPositionLeft) {
                    recover(element);
                } else {
                    moveMargin(element, dragPosition.width);
                }
            });
            var dragPositionRight = dragPosition.left + dragPosition.width;
            followedElements.map(function (element) {
                if (currentTime - element.moving < 100) return;
                var elementPosition = getScreenPosition(element);
                var elementCenter = elementPosition.left + elementPosition.width / 2;
                if (elementCenter - (element.moved || 0) <= dragPositionRight) {
                    moveMargin(element, -dragPosition.width);
                } else {
                    recover(element);
                }
            });
        } else {
            previousElements.map(recover);
            followedElements.map(recover);
        }
    } else {
        previousElements.map(recover);
        followedElements.map(recover);
    }
};
var scrollX = function (targetBox, moveChildren) {
    var dragTarget = drag.target;
    if (!dragTarget) return;
    var areaPosition = getScreenPosition(targetBox);
    var dragPosition = getScreenPosition(dragTarget);
    var scrollDelta = 0;
    if (dragPosition.left - 40 < areaPosition.left && dragPosition.right + 20 > areaPosition.left) {
        scrollDelta = dragPosition.left - 20 - areaPosition.left;
    } else if (dragPosition.right + 40 > areaPosition.right && dragPosition.left - 20 < areaPosition.right) {
        scrollDelta = dragPosition.right + 20 - areaPosition.right;
    }
    if (scrollDelta) {
        vscroll.X.call(targetBox, scrollDelta / 16, false);
        moveChildren();
    }
};
var scrollY = arriswise(scrollX, arguments);
var moveMarginY = arriswise(moveMarginX, arguments);
var moveChildrenY = arriswise(moveChildrenX, arguments);
var getMoveFuncs = function (child) {
    child = child instanceof Array ? child[0] : child;
    if (child && /cell|inline/i.test(getComputedStyle(child).display)) {
        return [moveMarginX, moveChildrenX, scrollX];
    } else {
        return [moveMarginY, moveChildrenY, scrollY];
    }
};
var hooka = function (matcher, move, event, targetChild, hideDraggingSource) {
    var draggingSourceOpacity = hideDraggingSource !== false ? 0 : 1;

    var recover = function (element) {
        moveMargin(element, 0);
    };
    var cloneCell = function (element) {
        var targets = getTargetIn(matcher, element, false);
        if (isArray(targets)) {
            var extra = targets.slice(1);
            targets = cloneVisible(targets[0]);
            targets.extraStyles = extra.map(function (extra) {
                var style = extra.style;
                return [style.opacity, style.filter];
            });
            targets.extra = extra;
            once("remove")(targets, function () {
                var { extra, extraStyles } = this;
                extra.map(function (elem, cx) {
                    var [opacity, filter] = extraStyles[cx];
                    extend(elem.style, {
                        opacity,
                        filter
                    });
                });
                delete this.extra;
            });
            targets.with = extra.map(cloneVisible);
            extra.map(function (elem) {
                setOpacity(elem, draggingSourceOpacity);
            });
        } else {
            targets = cloneVisible(targets);
        }
        return targets;
    };
    if (event.target === this) return;
    // var targetChild = getTargetIn(matcher, event.target);
    if (!targetChild) return;
    drag(targetChild, event, false);
    if (isArray(targetChild)) {
        targetChild = targetChild[0];
    }
    var targetBox, saved_opacity, saved_filter, moveMargin, moveChildren;
    var previousElements, followedElements, rebuildTargets, scroll;
    if (getTargetIn(this, targetChild)) {
        targetBox = targetChild.parentNode;
        previousElements = getPreviousElementSiblings(targetChild);
        followedElements = getFollowedElementSiblings(targetChild);
        saved_filter = targetBox.style.filter;
        saved_opacity = targetBox.style.opacity;
        rebuildTargets = function () { };
        [moveMargin, moveChildren, scroll] = getMoveFuncs(targetChild);
        moveChildren = moveChildren.bind(null, targetBox, previousElements, followedElements, moveMargin, recover);
    } else {
        rebuildTargets = function () {
            var temp = matcher(targetChild);
            if (temp === targetBox) return;
            if (previousElements) previousElements.map(recover);
            if (followedElements) followedElements.map(recover);
            if (targetBox) {
                removeClass(targetBox, "dropping");
            }
            targetBox = temp;
            if (!targetBox) {
                previousElements = [];
                followedElements = [];
                return;
            }
            addClass(targetBox, "dropping");
            previousElements = [].slice.call(targetBox.children, 0).reverse();
            followedElements = [];
            [moveMargin, moveChildren, scroll] = getMoveFuncs(previousElements[0]);
            moveChildren = moveChildren.bind(null, targetBox, previousElements, followedElements, moveMargin, recover);
        };
    }
    var offall = function () {
        offmousup();
        offtouchend();
        offdragstart();
        offtouchconcel();
    };
    var offtouchconcel = on("touchconcel")(targetChild, offall);
    var offtouchend = on("touchend")(targetChild, offall);
    var offmousup = on("mouseup")(window, offall);
    var autoScroll = function () {
        if (autoScroll.ing) return;
        if (scroll);
        autoScroll.ing = setInterval(scroll, 16);
    };
    var cancelScroll = function () {
        clearInterval(autoScroll.ing);
        autoScroll.ing = 0;
    };

    // 修改margin无效的情况
    function dragclone() {
        rebuildTargets();
        addClass(targetBox, 'dropping');
        previousElements = previousElements.map(cloneCell);
        followedElements = followedElements.map(cloneCell);
        setOpacity(targetBox, draggingSourceOpacity);
        appendChild(document.body, previousElements);
        appendChild(document.body, followedElements);
        var offall = function () {
            offdragmove();
            offdragend();
            removeClass(targetBox, "dropping");
        };
        var offdragend = on("dragend")(targetChild, function () {
            offall();
            css(targetBox, { opacity: saved_opacity, filter: saved_filter });
            remove(previousElements);
            remove(followedElements);
            var dst, appendSibling, delta;
            var src = previousElements.length;
            if (previousElements.length && previousElements[0].moved) for (var cx = 1, dx = previousElements.length + 1; cx < dx; cx++) {
                if (!previousElements[cx]) {
                    dst = 0;
                    delta = 0;
                    appendSibling = appendChild.before;
                } else if (!previousElements[cx].moved) {
                    dst = previousElements.length - cx;
                    delta = -1;
                    appendSibling = appendChild.after;
                    break;
                }
            }

            if (followedElements.length && followedElements[0].moved) for (var cx = 1, dx = followedElements.length + 1; cx < dx; cx++) {
                if (!followedElements[cx]) {
                    dst = followedElements.length + previousElements.length;
                    delta = 0;
                    appendSibling = appendChild.after;
                } else if (!followedElements[cx].moved) {
                    dst = previousElements.length + cx;
                    delta = 1;
                    appendSibling = appendChild.before;
                    break;
                }
            }
            previousElements.map(recover);
            followedElements.map(recover);
            if (appendSibling) {
                var children = this.parentNode.children;
                var srcElement = children[src];
                var dstElement = children[dst + delta];
                appendSibling(dstElement, srcElement);
                isFunction(move) && move(src, dst, dst + delta, appendSibling, this.parentNode);
            }
        });
        var offdragmove = on("dragmove")(targetChild, moveChildren);
    }
    // 仅修改Margin就可以实现拖拽效果
    function draglist() {
        rebuildTargets();
        addClass(targetBox, 'dropping');
        autoScroll();
        var offall = function () {
            cancelScroll();
            offdragmove();
            offdragend();
            removeClass(targetBox, "dropping");
        };
        var offdragend = on("dragend")(targetChild, function () {
            offall();
            var dst, appendSibling, delta;
            var src = previousElements.length;
            if (previousElements.length && previousElements[0].moved) for (var cx = 1, dx = previousElements.length + 1; cx < dx; cx++) {
                if (!previousElements[cx]) {
                    dst = 0;
                    delta = 0;
                    appendSibling = appendChild.before;
                } else if (!previousElements[cx].moved) {
                    dst = previousElements.length - cx;
                    delta = -1;
                    appendSibling = appendChild.after;
                    break;
                }
            }

            if (followedElements.length && followedElements[0].moved) for (var cx = 1, dx = followedElements.length + 1; cx < dx; cx++) {
                if (!followedElements[cx]) {
                    dst = followedElements.length + previousElements.length;
                    delta = 0;
                    appendSibling = appendChild.after;
                } else if (!followedElements[cx].moved) {
                    dst = previousElements.length + cx;
                    delta = 1;
                    appendSibling = appendChild.before;
                    break;
                }
            }
            previousElements.map(e => moveMargin(e, false));
            followedElements.map(e => moveMargin(e, false));
            if (appendSibling) {
                var children = this.parentNode.children;
                var srcElement = children[src];
                var dstElement = children[dst + delta];
                appendSibling(dstElement, srcElement);
                isFunction(move) && move(src, dst, dst + delta, appendSibling, this.parentNode);
            } else if (hideDraggingSource !== false) {
                move(previousElements.length, previousElements.length, previousElements.length);
            }
        });
        var offdragmove = on("dragmove")(targetChild, moveChildren);
    }
    if (/^table/i.test(getComputedStyle(targetChild).display)) {
        var offdragstart = on("dragstart")(targetChild, dragclone);
    } else {
        var offdragstart = on("dragstart")(targetChild, draglist);
    }
};
var hookEvent = function (matcher, move, event) {
    if (event.target === this) return;
    var targetChild = getTargetIn(matcher, event.target, false);
    if (!targetChild) return;
    hooka.call(this, matcher, move, event, targetChild);
};
function addhook(mousedownEvent, callback, matcher) {
    var target = mousedownEvent.currentTarget;
    hooka(function (target) {
        var res = matcher ? matcher(target) : [].filter.call(document.querySelectorAll("[allowdrop]"), function (child) {
            return overlap(child, target);
        });
        if (res instanceof Array) {
            return res[res.length - 1];
        }
        return res;
    }, function (_, dst) {
        if (isFunction(callback)) callback(dst);
    }, mousedownEvent, target);
}
function autodragchildren(target, matcher, move) {
    onmousedown(target, hookEvent.bind(target, matcher, move));
    ontouchstart(target, hookEvent.bind(target, matcher, move));
    return target;
}
autodragchildren.hook = addhook;
<|endoftext|>


<commit_before>/*
 *
 * Copyright 2015 gRPC authors.
 *
 * 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.
 *
 */

'use strict';

var grpc = require('grpc');

var _get = require('lodash.get');
var _clone = require('lodash.clone')

var health_messages = require('./v1/health_pb');
var health_service = require('./v1/health_grpc_pb');

function HealthImplementation(statusMap) {
  this.statusMap = _clone(statusMap);
}

HealthImplementation.prototype.setStatus = function(service, status) {
  this.statusMap[service] = status;
};

HealthImplementation.prototype.check = function(call, callback){
  var service = call.request.getService();
  var status = _get(this.statusMap, service, null);
  if (status === null) {
    // TODO(murgatroid99): Do this without an explicit reference to grpc.
    callback({code:grpc.status.NOT_FOUND});
  } else {
    var response = new health_messages.HealthCheckResponse();
    response.setStatus(status);
    callback(null, response);
  }
};

module.exports = {
  Client: health_service.HealthClient,
  service: health_service.HealthService,
  Implementation: HealthImplementation
};
<commit_msg>Export health-check messages<commit_after>/*
 *
 * Copyright 2015 gRPC authors.
 *
 * 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.
 *
 */

'use strict';

var grpc = require('grpc');

var _get = require('lodash.get');
var _clone = require('lodash.clone')

var health_messages = require('./v1/health_pb');
var health_service = require('./v1/health_grpc_pb');

function HealthImplementation(statusMap) {
  this.statusMap = _clone(statusMap);
}

HealthImplementation.prototype.setStatus = function(service, status) {
  this.statusMap[service] = status;
};

HealthImplementation.prototype.check = function(call, callback){
  var service = call.request.getService();
  var status = _get(this.statusMap, service, null);
  if (status === null) {
    // TODO(murgatroid99): Do this without an explicit reference to grpc.
    callback({code:grpc.status.NOT_FOUND});
  } else {
    var response = new health_messages.HealthCheckResponse();
    response.setStatus(status);
    callback(null, response);
  }
};

module.exports = {
  Client: health_service.HealthClient,
  messages: health_messages,
  service: health_service.HealthService,
  Implementation: HealthImplementation
};
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import scrollparent from 'scrollparent';
import scrollMonitor from 'scrollmonitor';
import ReactJsonSchema from './utils/schema2element';
import entries from 'object.entries';
import values from 'object.values';
import {
  getData,
  getVars,
  filterASTForDocument,
  splitAST,
  translate,
  findWrapTargets,
  mapTree,
  evalExpression,
  hooks,
  scrollMonitorEvents
} from './utils';

const updatePropsCallbacks = [];
const updateRefsCallbacks = [];
const scrollWatchers = [];
const scrollOffsets = {};
const refCache = {};
const evalContext = {};
let scrollContainer;

const getRefs = () => {
  const refs = {};
  if (!scrollContainer) {
    return;
  }

  scrollWatchers.forEach(watcher => {
    // left and right props assume no horizontal scrolling
    const { watchItem, callbacks, container, recalculateLocation, offsets, ...watcherProps} = watcher;
    refs[watchItem.dataset.ref] = {
      ...watcherProps,
      domNode: watchItem
    };
  });

  return refs;
};

let wrapperKey = 0;
class Wrapper extends React.PureComponent {
  constructor(props) {
    super(props);

    this.key = wrapperKey++;
    this.ref = {};
    this.onUpdateRefs = this.onUpdateRefs.bind(this);
    this.onUpdateProps = this.onUpdateProps.bind(this);

    const vars = values(props.__vars__);
    const exps = values(props.__expr__);

    this.usesRefs = exps.some(v => v.includes('refs.'));

    // listen for props updates IF we care about them
    if (vars.length || exps.length) {
      // called with new doc state
      // when any component calls updateProps()
      updatePropsCallbacks.push(this.onUpdateProps);
    }

    // listen for ref updates IF we care about them
    if (props.hasHook || this.usesRefs) {
      updateRefsCallbacks.push(this.onUpdateRefs);
    }

    this.state = { hasError: false, error: null };
  }

  componentDidCatch(error, info) {
    this.setState({ hasError: true, error: error });
  }

  onUpdateProps(newState, changedKeys) {
    const { __vars__, __expr__ } = this.props;

    // were there changes to any vars we track?
    // or vars our expressions reference?
    const shouldUpdate = changedKeys.some(k => {
      return (
        values(__vars__).includes(k) ||
        values(__expr__).some(expr => expr.includes(k))
      );
    });
    // if nothing we care about changed bail out and don't re-render
    if (!shouldUpdate) return;

    // update this component's state
    const nextState = {};
    // pull in the latest value for any tracked vars
    Object.keys(__vars__).forEach(key => {
      nextState[key] = newState[__vars__[key]];
    });
    // re-run this component's expressions using the latest doc state
    Object.keys(__expr__).forEach(key => {
      nextState[key] = evalExpression(newState, __expr__[key], key, evalContext);
    });
    // trigger a re-render of this component
    // and more importantly, its wrapped component
    this.setState(nextState);
  }

  onUpdateRefs(newState) {
    const { __expr__ } = this.props;

    if (this.usesRefs) {
      const nextState = {refs: newState.refs};
      entries(__expr__)
        .forEach(([key, val]) => {
          if (!key.includes('refs.')) {
            return;
          }
          nextState[key] = evalExpression(newState, val, key, evalContext);
        });

      // trigger a render with latest state
      this.setState(nextState);
    }
  }

  componentWillUnmount() {
    const propsIndex = updatePropsCallbacks.indexOf(this.onUpdateProps);
    if (propsIndex > -1) updatePropsCallbacks.splice(propsIndex, 1);

    const refsIndex = updateRefsCallbacks.indexOf(this.onUpdateRefs);
    if (refsIndex > -1) updateRefsCallbacks.splice(refsIndex, 1);
  }

  render() {
    if (this.state.hasError) {
      return (

          {this.state.error.message}

      );
    }

    const { __expr__, __vars__, hasError, ...state } = this.state;
    return React.Children.map(this.props.children, (c, i) => {
      return React.cloneElement(c, {key: `${this.key}-${i}`, ...state});
    });
  }
}

const getDerivedValues = dVars => {
  const o = {};
  Object.keys(dVars).forEach(key => o[key] = dVars[key].value);
  return o;
};

class IdyllDocument extends React.PureComponent {
  constructor(props) {
    super(props);

    this.scrollListener = this.scrollListener.bind(this);
    this.initScrollListener = this.initScrollListener.bind(this);

    const ast = filterASTForDocument(props.ast);

    const {
      vars,
      derived,
      data,
      elements,
    } = splitAST(ast);

    const initialState = {
      ...getVars(vars),
      ...getData(data, props.datasets),
    };
    const derivedVars = this.derivedVars = getVars(derived, initialState);

    let state = this.state = {
      ...initialState,
      ...getDerivedValues(derivedVars),
    };

    this.updateState = (newState) => {
      // merge new doc state with old
      const newMergedState = {...this.state, ...newState};
      // update derived values
      const newDerivedValues = getDerivedValues(
        getVars(derived, newMergedState),
      );
      const nextState = {...newMergedState, ...newDerivedValues};
      const changedKeys = Object.keys(state).reduce(
        (acc, k) => {
          if (state[k] !== nextState[k]) acc.push(k);
          return acc;
        },
        []
      )
      // Update doc state reference.
      // We re-use the same object here so that
      // IdyllDocument.state can be accurately checked in tests
      state = Object.assign(state, nextState);
      // pass the new doc state to all listeners aka component wrappers
      updatePropsCallbacks.forEach(f => f(state, changedKeys));
    };

    evalContext.update = this.updateState;

    const rjs = new ReactJsonSchema({...props.components, Wrapper});
    const schema = translate(ast);

    const wrapTargets = findWrapTargets(schema, this.state);

    let refCounter = 0;

    const transformedSchema = mapTree(
      schema,
      node => {
        if (typeof node === 'string') return node;

        // transform refs from strings to functions and store them
        if (node.ref || node.hasHook) {
          node.refName = node.ref || node.component + (refCounter++).toString();
          node.ref = el => {
            if (!el) return;
            const domNode = ReactDOM.findDOMNode(el);
            domNode.dataset.ref = node.refName;
            scrollOffsets[node.refName] = node.scrollOffset || 0;
            refCache[node.refName] = {
              props: node,
              domNode: domNode
            };
          };
        }

        if (!wrapTargets.includes(node)) return node;

        const {
          component,
          children,
          key,
          __vars__ = {},
          __expr__ = {},
          ...props // actual component props
        } = node;

        // assign the initial values for tracked vars and expressions
        Object.keys(props).forEach(k => {
          if (__vars__[k]) {
            node[k] = state[__vars__[k]];
          }
          if (__expr__[k] && !__expr__[k].includes('refs.')) {
            if (hooks.indexOf(k) > -1) {
              return;
            }
            node[k] = evalExpression(state, __expr__[k], k, evalContext);
          }
        });

        // define the function wrapped components will call via this.props.updateProps
        node.updateProps = (newProps) => {
          // init new doc state object
          const newState = {};
          // iterate over passed in updates
          Object.keys(newProps).forEach(k => {
            // if a tracked var was updated get its new value
            if (__vars__[k]) {
              newState[__vars__[k]] = newProps[k];
            }
          });
          this.updateState(newState);
        };

        return {
          component: Wrapper,
          __vars__,
          __expr__,
          hasHook: node.hasHook,
          refName: node.refName,
          children: [
            node
          ],
        };
      }
    );

    this.kids = (

        {rjs.parseSchema(transformedSchema)}

    );
  }

  scrollListener() {
    const refs = getRefs();
    updateRefsCallbacks.forEach(f => f({ ...this.state, refs }));
  }

  initScrollListener(el) {
    if (!el) return;

    let scroller = scrollparent(el);
    if (scroller === document.documentElement) {
      scroller = document.body;
    }
    scrollContainer = scrollMonitor.createContainer(scroller);
    Object.keys(refCache).forEach((key) => {
      const { props, domNode } = refCache[key];
      const watcher = scrollContainer.create(domNode, scrollOffsets[key]);
      hooks.forEach((hook) => {
        if (props[hook]) {
          watcher[scrollMonitorEvents[hook]](() => {
            evalExpression(this.state, props[hook], hook, evalContext)();
          });
        }
      })
      scrollWatchers.push(watcher);
    });
    if (scroller === document.body) {
      scroller = window;
    }
    scroller.addEventListener('scroll', this.scrollListener);
  }

  updateDerivedVars(newState) {
    Object.keys(this.derivedVars).forEach(dv => {
      this.derivedVars[dv].value = this.derivedVars[dv].update(
        newState,
        this.state,
      );
    });
  }

  getDerivedVars() {
    let dvs = {};
    Object.keys(this.derivedVars).forEach(dv => {
      dvs[dv] = this.derivedVars[dv].value;
    });
    return dvs;
  }

  componentDidMount() {
    const refs = getRefs();
    updateRefsCallbacks.forEach(f => f({ ...this.state, refs }));
  }

  render() {
    return this.kids;
  }
}

export default IdyllDocument;
<commit_msg>Pass props through to wrapped components<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import scrollparent from 'scrollparent';
import scrollMonitor from 'scrollmonitor';
import ReactJsonSchema from './utils/schema2element';
import entries from 'object.entries';
import values from 'object.values';
import {
  getData,
  getVars,
  filterASTForDocument,
  splitAST,
  translate,
  findWrapTargets,
  mapTree,
  evalExpression,
  hooks,
  scrollMonitorEvents
} from './utils';

const updatePropsCallbacks = [];
const updateRefsCallbacks = [];
const scrollWatchers = [];
const scrollOffsets = {};
const refCache = {};
const evalContext = {};
let scrollContainer;

const getRefs = () => {
  const refs = {};
  if (!scrollContainer) {
    return;
  }

  scrollWatchers.forEach(watcher => {
    // left and right props assume no horizontal scrolling
    const { watchItem, callbacks, container, recalculateLocation, offsets, ...watcherProps} = watcher;
    refs[watchItem.dataset.ref] = {
      ...watcherProps,
      domNode: watchItem
    };
  });

  return refs;
};

let wrapperKey = 0;
class Wrapper extends React.PureComponent {
  constructor(props) {
    super(props);

    this.key = wrapperKey++;
    this.ref = {};
    this.onUpdateRefs = this.onUpdateRefs.bind(this);
    this.onUpdateProps = this.onUpdateProps.bind(this);

    const vars = values(props.__vars__);
    const exps = values(props.__expr__);

    this.usesRefs = exps.some(v => v.includes('refs.'));

    // listen for props updates IF we care about them
    if (vars.length || exps.length) {
      // called with new doc state
      // when any component calls updateProps()
      updatePropsCallbacks.push(this.onUpdateProps);
    }

    // listen for ref updates IF we care about them
    if (props.hasHook || this.usesRefs) {
      updateRefsCallbacks.push(this.onUpdateRefs);
    }

    this.state = { hasError: false, error: null };
  }

  componentDidCatch(error, info) {
    this.setState({ hasError: true, error: error });
  }

  onUpdateProps(newState, changedKeys) {
    const { __vars__, __expr__ } = this.props;

    // were there changes to any vars we track?
    // or vars our expressions reference?
    const shouldUpdate = changedKeys.some(k => {
      return (
        values(__vars__).includes(k) ||
        values(__expr__).some(expr => expr.includes(k))
      );
    });
    // if nothing we care about changed bail out and don't re-render
    if (!shouldUpdate) return;

    // update this component's state
    const nextState = {};
    // pull in the latest value for any tracked vars
    Object.keys(__vars__).forEach(key => {
      nextState[key] = newState[__vars__[key]];
    });
    // re-run this component's expressions using the latest doc state
    Object.keys(__expr__).forEach(key => {
      nextState[key] = evalExpression(newState, __expr__[key], key, evalContext);
    });
    // trigger a re-render of this component
    // and more importantly, its wrapped component
    this.setState(nextState);
  }

  onUpdateRefs(newState) {
    const { __expr__ } = this.props;

    if (this.usesRefs) {
      const nextState = {refs: newState.refs};
      entries(__expr__)
        .forEach(([key, val]) => {
          if (!key.includes('refs.')) {
            return;
          }
          nextState[key] = evalExpression(newState, val, key, evalContext);
        });

      // trigger a render with latest state
      this.setState(nextState);
    }
  }

  componentWillUnmount() {
    const propsIndex = updatePropsCallbacks.indexOf(this.onUpdateProps);
    if (propsIndex > -1) updatePropsCallbacks.splice(propsIndex, 1);

    const refsIndex = updateRefsCallbacks.indexOf(this.onUpdateRefs);
    if (refsIndex > -1) updateRefsCallbacks.splice(refsIndex, 1);
  }

  render() {
    if (this.state.hasError) {
      return (

          {this.state.error.message}

      );
    }

    const { __expr__, __vars__, hasError, ...state } = this.state
    const { children, ...passThruProps } = this.props
    return React.Children.map(children, (c, i) => {
      return React.cloneElement(c, {
        key: `${this.key}-${i}`,
        ...state,
        ...passThruProps,
      })
    })
  }
}

const getDerivedValues = dVars => {
  const o = {};
  Object.keys(dVars).forEach(key => o[key] = dVars[key].value);
  return o;
};

class IdyllDocument extends React.PureComponent {
  constructor(props) {
    super(props);

    this.scrollListener = this.scrollListener.bind(this);
    this.initScrollListener = this.initScrollListener.bind(this);

    const ast = filterASTForDocument(props.ast);

    const {
      vars,
      derived,
      data,
      elements,
    } = splitAST(ast);

    const initialState = {
      ...getVars(vars),
      ...getData(data, props.datasets),
    };
    const derivedVars = this.derivedVars = getVars(derived, initialState);

    let state = this.state = {
      ...initialState,
      ...getDerivedValues(derivedVars),
    };

    this.updateState = (newState) => {
      // merge new doc state with old
      const newMergedState = {...this.state, ...newState};
      // update derived values
      const newDerivedValues = getDerivedValues(
        getVars(derived, newMergedState),
      );
      const nextState = {...newMergedState, ...newDerivedValues};
      const changedKeys = Object.keys(state).reduce(
        (acc, k) => {
          if (state[k] !== nextState[k]) acc.push(k);
          return acc;
        },
        []
      )
      // Update doc state reference.
      // We re-use the same object here so that
      // IdyllDocument.state can be accurately checked in tests
      state = Object.assign(state, nextState);
      // pass the new doc state to all listeners aka component wrappers
      updatePropsCallbacks.forEach(f => f(state, changedKeys));
    };

    evalContext.update = this.updateState;

    const rjs = new ReactJsonSchema({...props.components, Wrapper});
    const schema = translate(ast);

    const wrapTargets = findWrapTargets(schema, this.state);

    let refCounter = 0;

    const transformedSchema = mapTree(
      schema,
      node => {
        if (typeof node === 'string') return node;

        // transform refs from strings to functions and store them
        if (node.ref || node.hasHook) {
          node.refName = node.ref || node.component + (refCounter++).toString();
          node.ref = el => {
            if (!el) return;
            const domNode = ReactDOM.findDOMNode(el);
            domNode.dataset.ref = node.refName;
            scrollOffsets[node.refName] = node.scrollOffset || 0;
            refCache[node.refName] = {
              props: node,
              domNode: domNode
            };
          };
        }

        if (!wrapTargets.includes(node)) return node;

        const {
          component,
          children,
          key,
          __vars__ = {},
          __expr__ = {},
          ...props // actual component props
        } = node;

        // assign the initial values for tracked vars and expressions
        Object.keys(props).forEach(k => {
          if (__vars__[k]) {
            node[k] = state[__vars__[k]];
          }
          if (__expr__[k] && !__expr__[k].includes('refs.')) {
            if (hooks.indexOf(k) > -1) {
              return;
            }
            node[k] = evalExpression(state, __expr__[k], k, evalContext);
          }
        });

        // define the function wrapped components will call via this.props.updateProps
        node.updateProps = (newProps) => {
          // init new doc state object
          const newState = {};
          // iterate over passed in updates
          Object.keys(newProps).forEach(k => {
            // if a tracked var was updated get its new value
            if (__vars__[k]) {
              newState[__vars__[k]] = newProps[k];
            }
          });
          this.updateState(newState);
        };

        return {
          component: Wrapper,
          __vars__,
          __expr__,
          hasHook: node.hasHook,
          refName: node.refName,
          children: [
            node
          ],
        };
      }
    );

    this.kids = (

        {rjs.parseSchema(transformedSchema)}

    );
  }

  scrollListener() {
    const refs = getRefs();
    updateRefsCallbacks.forEach(f => f({ ...this.state, refs }));
  }

  initScrollListener(el) {
    if (!el) return;

    let scroller = scrollparent(el);
    if (scroller === document.documentElement) {
      scroller = document.body;
    }
    scrollContainer = scrollMonitor.createContainer(scroller);
    Object.keys(refCache).forEach((key) => {
      const { props, domNode } = refCache[key];
      const watcher = scrollContainer.create(domNode, scrollOffsets[key]);
      hooks.forEach((hook) => {
        if (props[hook]) {
          watcher[scrollMonitorEvents[hook]](() => {
            evalExpression(this.state, props[hook], hook, evalContext)();
          });
        }
      })
      scrollWatchers.push(watcher);
    });
    if (scroller === document.body) {
      scroller = window;
    }
    scroller.addEventListener('scroll', this.scrollListener);
  }

  updateDerivedVars(newState) {
    Object.keys(this.derivedVars).forEach(dv => {
      this.derivedVars[dv].value = this.derivedVars[dv].update(
        newState,
        this.state,
      );
    });
  }

  getDerivedVars() {
    let dvs = {};
    Object.keys(this.derivedVars).forEach(dv => {
      dvs[dv] = this.derivedVars[dv].value;
    });
    return dvs;
  }

  componentDidMount() {
    const refs = getRefs();
    updateRefsCallbacks.forEach(f => f({ ...this.state, refs }));
  }

  render() {
    return this.kids;
  }
}

export default IdyllDocument;
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import scrollparent from 'scrollparent';
import scrollMonitor from 'scrollmonitor';
import ReactJsonSchema from './utils/schema2element';
import entries from 'object.entries';
import values from 'object.values';
import {
  getData,
  getVars,
  filterASTForDocument,
  splitAST,
  translate,
  findWrapTargets,
  mapTree,
  evalExpression,
  hooks,
  scrollMonitorEvents
} from './utils';

const updatePropsCallbacks = [];
const updateRefsCallbacks = [];
const scrollWatchers = [];
const scrollOffsets = {};
const refCache = {};
const evalContext = {};
let scrollContainer;

const getRefs = () => {
  const refs = {};
  if (!scrollContainer) {
    return;
  }

  scrollWatchers.forEach(watcher => {
    // left and right props assume no horizontal scrolling
    const { watchItem, callbacks, container, recalculateLocation, offsets, ...watcherProps} = watcher;
    refs[watchItem.dataset.ref] = {
      ...watcherProps,
      domNode: watchItem
    };
  });

  return refs;
};

let wrapperKey = 0;
class Wrapper extends React.PureComponent {
  constructor(props) {
    super(props);

    this.key = wrapperKey++;
    this.ref = {};
    this.onUpdateRefs = this.onUpdateRefs.bind(this);
    this.onUpdateProps = this.onUpdateProps.bind(this);

    const vars = values(props.__vars__);
    const exps = values(props.__expr__);

    this.usesRefs = exps.some(v => v.includes('refs.'));

    // listen for props updates IF we care about them
    if (vars.length || exps.length) {
      // called with new doc state
      // when any component calls updateProps()
      updatePropsCallbacks.push(this.onUpdateProps);
    }

    // listen for ref updates IF we care about them
    if (props.hasHook || this.usesRefs) {
      updateRefsCallbacks.push(this.onUpdateRefs);
    }

    this.state = { hasError: false, error: null };
  }

  componentDidCatch(error, info) {
    this.setState({ hasError: true, error: error });
  }

  onUpdateProps(newState, changedKeys) {
    const { __vars__, __expr__ } = this.props;

    // were there changes to any vars we track?
    // or vars our expressions reference?
    const shouldUpdate = changedKeys.some(k => {
      return (
        values(__vars__).includes(k) ||
        values(__expr__).some(expr => expr.includes(k))
      );
    });
    // if nothing we care about changed bail out and don't re-render
    if (!shouldUpdate) return;

    // update this component's state
    const nextState = {};
    // pull in the latest value for any tracked vars
    Object.keys(__vars__).forEach(key => {
      nextState[key] = newState[__vars__[key]];
    });
    // re-run this component's expressions using the latest doc state
    Object.keys(__expr__).forEach(key => {
      nextState[key] = evalExpression(newState, __expr__[key], key, evalContext);
    });
    // trigger a re-render of this component
    // and more importantly, its wrapped component
    this.setState(nextState);
  }

  onUpdateRefs(newState) {
    const { __expr__ } = this.props;

    if (this.usesRefs) {
      const nextState = {refs: newState.refs};
      entries(__expr__)
        .forEach(([key, val]) => {
          if (!key.includes('refs.')) {
            return;
          }
          nextState[key] = evalExpression(newState, val, key, evalContext);
        });

      // trigger a render with latest state
      this.setState(nextState);
    }
  }

  componentWillUnmount() {
    const propsIndex = updatePropsCallbacks.indexOf(this.onUpdateProps);
    if (propsIndex > -1) updatePropsCallbacks.splice(propsIndex, 1);

    const refsIndex = updateRefsCallbacks.indexOf(this.onUpdateRefs);
    if (refsIndex > -1) updateRefsCallbacks.splice(refsIndex, 1);
  }

  render() {
    if (this.state.hasError) {
      return (

          {this.state.error.message}

      );
    }

    const { __expr__, __vars__, hasError, ...state } = this.state
    const { children, __expr__: _e, __vars__: _v, ...passThruProps } = this.props
    return React.Children.map(children, (c, i) => {
      return React.cloneElement(c, {
        key: `${this.key}-${i}`,
        ...state,
        ...passThruProps,
      })
    })
  }
}

const getDerivedValues = dVars => {
  const o = {};
  Object.keys(dVars).forEach(key => o[key] = dVars[key].value);
  return o;
};

class IdyllDocument extends React.PureComponent {
  constructor(props) {
    super(props);

    this.scrollListener = this.scrollListener.bind(this);
    this.initScrollListener = this.initScrollListener.bind(this);

    const ast = filterASTForDocument(props.ast);

    const {
      vars,
      derived,
      data,
      elements,
    } = splitAST(ast);

    const initialState = {
      ...getVars(vars),
      ...getData(data, props.datasets),
    };
    const derivedVars = this.derivedVars = getVars(derived, initialState);

    let state = this.state = {
      ...initialState,
      ...getDerivedValues(derivedVars),
    };

    this.updateState = (newState) => {
      // merge new doc state with old
      const newMergedState = {...this.state, ...newState};
      // update derived values
      const newDerivedValues = getDerivedValues(
        getVars(derived, newMergedState),
      );
      const nextState = {...newMergedState, ...newDerivedValues};
      const changedKeys = Object.keys(state).reduce(
        (acc, k) => {
          if (state[k] !== nextState[k]) acc.push(k);
          return acc;
        },
        []
      )
      // Update doc state reference.
      // We re-use the same object here so that
      // IdyllDocument.state can be accurately checked in tests
      state = Object.assign(state, nextState);
      // pass the new doc state to all listeners aka component wrappers
      updatePropsCallbacks.forEach(f => f(state, changedKeys));
    };

    evalContext.update = this.updateState;

    const rjs = new ReactJsonSchema({...props.components, Wrapper});
    const schema = translate(ast);

    const wrapTargets = findWrapTargets(schema, this.state);

    let refCounter = 0;

    const transformedSchema = mapTree(
      schema,
      node => {
        if (typeof node === 'string') return node;

        // transform refs from strings to functions and store them
        if (node.ref || node.hasHook) {
          node.refName = node.ref || node.component + (refCounter++).toString();
          node.ref = el => {
            if (!el) return;
            const domNode = ReactDOM.findDOMNode(el);
            domNode.dataset.ref = node.refName;
            scrollOffsets[node.refName] = node.scrollOffset || 0;
            refCache[node.refName] = {
              props: node,
              domNode: domNode
            };
          };
        }

        if (!wrapTargets.includes(node)) return node;

        const {
          component,
          children,
          key,
          __vars__ = {},
          __expr__ = {},
          ...props // actual component props
        } = node;

        // assign the initial values for tracked vars and expressions
        Object.keys(props).forEach(k => {
          if (__vars__[k]) {
            node[k] = state[__vars__[k]];
          }
          if (__expr__[k] && !__expr__[k].includes('refs.')) {
            if (hooks.indexOf(k) > -1) {
              return;
            }
            node[k] = evalExpression(state, __expr__[k], k, evalContext);
          }
        });

        // define the function wrapped components will call via this.props.updateProps
        node.updateProps = (newProps) => {
          // init new doc state object
          const newState = {};
          // iterate over passed in updates
          Object.keys(newProps).forEach(k => {
            // if a tracked var was updated get its new value
            if (__vars__[k]) {
              newState[__vars__[k]] = newProps[k];
            }
          });
          this.updateState(newState);
        };

        return {
          component: Wrapper,
          __vars__,
          __expr__,
          hasHook: node.hasHook,
          refName: node.refName,
          children: [
            node
          ],
        };
      }
    );

    this.kids = (

        {rjs.parseSchema(transformedSchema)}

    );
  }

  scrollListener() {
    const refs = getRefs();
    updateRefsCallbacks.forEach(f => f({ ...this.state, refs }));
  }

  initScrollListener(el) {
    if (!el) return;

    let scroller = scrollparent(el);
    if (scroller === document.documentElement) {
      scroller = document.body;
    }
    scrollContainer = scrollMonitor.createContainer(scroller);
    Object.keys(refCache).forEach((key) => {
      const { props, domNode } = refCache[key];
      const watcher = scrollContainer.create(domNode, scrollOffsets[key]);
      hooks.forEach((hook) => {
        if (props[hook]) {
          watcher[scrollMonitorEvents[hook]](() => {
            evalExpression(this.state, props[hook], hook, evalContext)();
          });
        }
      })
      scrollWatchers.push(watcher);
    });
    if (scroller === document.body) {
      scroller = window;
    }
    scroller.addEventListener('scroll', this.scrollListener);
  }

  updateDerivedVars(newState) {
    Object.keys(this.derivedVars).forEach(dv => {
      this.derivedVars[dv].value = this.derivedVars[dv].update(
        newState,
        this.state,
      );
    });
  }

  getDerivedVars() {
    let dvs = {};
    Object.keys(this.derivedVars).forEach(dv => {
      dvs[dv] = this.derivedVars[dv].value;
    });
    return dvs;
  }

  componentDidMount() {
    const refs = getRefs();
    updateRefsCallbacks.forEach(f => f({ ...this.state, refs }));
  }

  render() {
    return this.kids;
  }
}

export default IdyllDocument;
<commit_msg>filter refName<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import scrollparent from 'scrollparent';
import scrollMonitor from 'scrollmonitor';
import ReactJsonSchema from './utils/schema2element';
import entries from 'object.entries';
import values from 'object.values';
import {
  getData,
  getVars,
  filterASTForDocument,
  splitAST,
  translate,
  findWrapTargets,
  mapTree,
  evalExpression,
  hooks,
  scrollMonitorEvents
} from './utils';

const updatePropsCallbacks = [];
const updateRefsCallbacks = [];
const scrollWatchers = [];
const scrollOffsets = {};
const refCache = {};
const evalContext = {};
let scrollContainer;

const getRefs = () => {
  const refs = {};
  if (!scrollContainer) {
    return;
  }

  scrollWatchers.forEach(watcher => {
    // left and right props assume no horizontal scrolling
    const { watchItem, callbacks, container, recalculateLocation, offsets, ...watcherProps} = watcher;
    refs[watchItem.dataset.ref] = {
      ...watcherProps,
      domNode: watchItem
    };
  });

  return refs;
};

let wrapperKey = 0;
class Wrapper extends React.PureComponent {
  constructor(props) {
    super(props);

    this.key = wrapperKey++;
    this.ref = {};
    this.onUpdateRefs = this.onUpdateRefs.bind(this);
    this.onUpdateProps = this.onUpdateProps.bind(this);

    const vars = values(props.__vars__);
    const exps = values(props.__expr__);

    this.usesRefs = exps.some(v => v.includes('refs.'));

    // listen for props updates IF we care about them
    if (vars.length || exps.length) {
      // called with new doc state
      // when any component calls updateProps()
      updatePropsCallbacks.push(this.onUpdateProps);
    }

    // listen for ref updates IF we care about them
    if (props.hasHook || this.usesRefs) {
      updateRefsCallbacks.push(this.onUpdateRefs);
    }

    this.state = { hasError: false, error: null };
  }

  componentDidCatch(error, info) {
    this.setState({ hasError: true, error: error });
  }

  onUpdateProps(newState, changedKeys) {
    const { __vars__, __expr__ } = this.props;

    // were there changes to any vars we track?
    // or vars our expressions reference?
    const shouldUpdate = changedKeys.some(k => {
      return (
        values(__vars__).includes(k) ||
        values(__expr__).some(expr => expr.includes(k))
      );
    });
    // if nothing we care about changed bail out and don't re-render
    if (!shouldUpdate) return;

    // update this component's state
    const nextState = {};
    // pull in the latest value for any tracked vars
    Object.keys(__vars__).forEach(key => {
      nextState[key] = newState[__vars__[key]];
    });
    // re-run this component's expressions using the latest doc state
    Object.keys(__expr__).forEach(key => {
      nextState[key] = evalExpression(newState, __expr__[key], key, evalContext);
    });
    // trigger a re-render of this component
    // and more importantly, its wrapped component
    this.setState(nextState);
  }

  onUpdateRefs(newState) {
    const { __expr__ } = this.props;

    if (this.usesRefs) {
      const nextState = {refs: newState.refs};
      entries(__expr__)
        .forEach(([key, val]) => {
          if (!key.includes('refs.')) {
            return;
          }
          nextState[key] = evalExpression(newState, val, key, evalContext);
        });

      // trigger a render with latest state
      this.setState(nextState);
    }
  }

  componentWillUnmount() {
    const propsIndex = updatePropsCallbacks.indexOf(this.onUpdateProps);
    if (propsIndex > -1) updatePropsCallbacks.splice(propsIndex, 1);

    const refsIndex = updateRefsCallbacks.indexOf(this.onUpdateRefs);
    if (refsIndex > -1) updateRefsCallbacks.splice(refsIndex, 1);
  }

  render() {
    if (this.state.hasError) {
      return (

          {this.state.error.message}

      );
    }

    const { __expr__, __vars__, hasError, refName, ...state } = this.state
    const { children, refName: _r, __expr__: _e, __vars__: _v, ...passThruProps } = this.props
    return React.Children.map(children, (c, i) => {
      return React.cloneElement(c, {
        key: `${this.key}-${i}`,
        ...state,
        ...passThruProps,
      })
    })
  }
}

const getDerivedValues = dVars => {
  const o = {};
  Object.keys(dVars).forEach(key => o[key] = dVars[key].value);
  return o;
};

class IdyllDocument extends React.PureComponent {
  constructor(props) {
    super(props);

    this.scrollListener = this.scrollListener.bind(this);
    this.initScrollListener = this.initScrollListener.bind(this);

    const ast = filterASTForDocument(props.ast);

    const {
      vars,
      derived,
      data,
      elements,
    } = splitAST(ast);

    const initialState = {
      ...getVars(vars),
      ...getData(data, props.datasets),
    };
    const derivedVars = this.derivedVars = getVars(derived, initialState);

    let state = this.state = {
      ...initialState,
      ...getDerivedValues(derivedVars),
    };

    this.updateState = (newState) => {
      // merge new doc state with old
      const newMergedState = {...this.state, ...newState};
      // update derived values
      const newDerivedValues = getDerivedValues(
        getVars(derived, newMergedState),
      );
      const nextState = {...newMergedState, ...newDerivedValues};
      const changedKeys = Object.keys(state).reduce(
        (acc, k) => {
          if (state[k] !== nextState[k]) acc.push(k);
          return acc;
        },
        []
      )
      // Update doc state reference.
      // We re-use the same object here so that
      // IdyllDocument.state can be accurately checked in tests
      state = Object.assign(state, nextState);
      // pass the new doc state to all listeners aka component wrappers
      updatePropsCallbacks.forEach(f => f(state, changedKeys));
    };

    evalContext.update = this.updateState;

    const rjs = new ReactJsonSchema({...props.components, Wrapper});
    const schema = translate(ast);

    const wrapTargets = findWrapTargets(schema, this.state);

    let refCounter = 0;

    const transformedSchema = mapTree(
      schema,
      node => {
        if (typeof node === 'string') return node;

        // transform refs from strings to functions and store them
        if (node.ref || node.hasHook) {
          node.refName = node.ref || node.component + (refCounter++).toString();
          node.ref = el => {
            if (!el) return;
            const domNode = ReactDOM.findDOMNode(el);
            domNode.dataset.ref = node.refName;
            scrollOffsets[node.refName] = node.scrollOffset || 0;
            refCache[node.refName] = {
              props: node,
              domNode: domNode
            };
          };
        }

        if (!wrapTargets.includes(node)) return node;

        const {
          component,
          children,
          key,
          __vars__ = {},
          __expr__ = {},
          ...props // actual component props
        } = node;

        // assign the initial values for tracked vars and expressions
        Object.keys(props).forEach(k => {
          if (__vars__[k]) {
            node[k] = state[__vars__[k]];
          }
          if (__expr__[k] && !__expr__[k].includes('refs.')) {
            if (hooks.indexOf(k) > -1) {
              return;
            }
            node[k] = evalExpression(state, __expr__[k], k, evalContext);
          }
        });

        // define the function wrapped components will call via this.props.updateProps
        node.updateProps = (newProps) => {
          // init new doc state object
          const newState = {};
          // iterate over passed in updates
          Object.keys(newProps).forEach(k => {
            // if a tracked var was updated get its new value
            if (__vars__[k]) {
              newState[__vars__[k]] = newProps[k];
            }
          });
          this.updateState(newState);
        };

        return {
          component: Wrapper,
          __vars__,
          __expr__,
          hasHook: node.hasHook,
          refName: node.refName,
          children: [
            node
          ],
        };
      }
    );

    this.kids = (

        {rjs.parseSchema(transformedSchema)}

    );
  }

  scrollListener() {
    const refs = getRefs();
    updateRefsCallbacks.forEach(f => f({ ...this.state, refs }));
  }

  initScrollListener(el) {
    if (!el) return;

    let scroller = scrollparent(el);
    if (scroller === document.documentElement) {
      scroller = document.body;
    }
    scrollContainer = scrollMonitor.createContainer(scroller);
    Object.keys(refCache).forEach((key) => {
      const { props, domNode } = refCache[key];
      const watcher = scrollContainer.create(domNode, scrollOffsets[key]);
      hooks.forEach((hook) => {
        if (props[hook]) {
          watcher[scrollMonitorEvents[hook]](() => {
            evalExpression(this.state, props[hook], hook, evalContext)();
          });
        }
      })
      scrollWatchers.push(watcher);
    });
    if (scroller === document.body) {
      scroller = window;
    }
    scroller.addEventListener('scroll', this.scrollListener);
  }

  updateDerivedVars(newState) {
    Object.keys(this.derivedVars).forEach(dv => {
      this.derivedVars[dv].value = this.derivedVars[dv].update(
        newState,
        this.state,
      );
    });
  }

  getDerivedVars() {
    let dvs = {};
    Object.keys(this.derivedVars).forEach(dv => {
      dvs[dv] = this.derivedVars[dv].value;
    });
    return dvs;
  }

  componentDidMount() {
    const refs = getRefs();
    updateRefsCallbacks.forEach(f => f({ ...this.state, refs }));
  }

  render() {
    return this.kids;
  }
}

export default IdyllDocument;
<|endoftext|>


<commit_before>import React from "react";
import { TouchableHighlight } from "react-native";
import PropTypes from "prop-types";

import { __RouterContext as RouterContext } from "react-router";

class Link extends React.Component {
  static defaultProps = {
    component: TouchableHighlight,
    replace: false
  };

  handlePress = (event, history) => {
    console.log(history);
    if (this.props.onPress) this.props.onPress(event);

    if (!event.defaultPrevented) {
      const { to, replace } = this.props;

      if (replace) {
        history.replace(to);
      } else {
        history.push(to);
      }
    }
  };

  render() {
    const { component: Component, to, replace, ...rest } = this.props;

    return (
      <RouterContext.Consumer>
        {context => (
          <Component
            {...rest}
            onPress={event => this.handlePress(event, context.history)}
          />
        )}
      </RouterContext.Consumer>
    );
  }
}

const __DEV__ = true; // TODO

if (__DEV__) {
  Link.propTypes = {
    onPress: PropTypes.func,
    component: PropTypes.func,
    replace: PropTypes.bool,
    to: PropTypes.oneOfType([PropTypes.string, PropTypes.object])
  };
}

export default Link;
<commit_msg>Remove errant console.log<commit_after>import React from "react";
import { TouchableHighlight } from "react-native";
import PropTypes from "prop-types";

import { __RouterContext as RouterContext } from "react-router";

class Link extends React.Component {
  static defaultProps = {
    component: TouchableHighlight,
    replace: false
  };

  handlePress = (event, history) => {
    if (this.props.onPress) this.props.onPress(event);

    if (!event.defaultPrevented) {
      const { to, replace } = this.props;

      if (replace) {
        history.replace(to);
      } else {
        history.push(to);
      }
    }
  };

  render() {
    const { component: Component, to, replace, ...rest } = this.props;

    return (
      <RouterContext.Consumer>
        {context => (
          <Component
            {...rest}
            onPress={event => this.handlePress(event, context.history)}
          />
        )}
      </RouterContext.Consumer>
    );
  }
}

const __DEV__ = true; // TODO

if (__DEV__) {
  Link.propTypes = {
    onPress: PropTypes.func,
    component: PropTypes.func,
    replace: PropTypes.bool,
    to: PropTypes.oneOfType([PropTypes.string, PropTypes.object])
  };
}

export default Link;
<|endoftext|>


<commit_before>import './Swagger'
import './expandParameters'

import { route as inferRoute } from './inference/route'
import { parameter as inferParameter } from './inference/parameter'

export function compileRoute(route, app) {
	let docs = !route.context.isNil ? route.context.swagger : null
	let routePath = route.path
	let method = route.methods

	if(typeof method === 'object') {
		method = Object.keys(method)[0]
	} else {
		method = null
	}

	if(docs.isNil || routePath.isNil || method.isNil) {
		return null
	}

	method = method.toLowerCase()

	if(typeof docs === 'string') {
		docs = { description: docs }
	}

	// Expand base parameters
	docs.parameters = expandParameters(docs.parameters)

	// Add in shared parameters
	Swagger.applyParameters(docs.use, docs.parameters)

	// Infer route, which will modify parameters
	routePath = inferRoute(routePath, app, docs.parameters)

	// Infer all parameters
	for(const parameter of docs.parameters) {
		inferParameter(parameter, method)
	}

	if(docs.parameters.length === 0) {
		delete docs.parameters
	}

	if(!docs.use.isNil) {
		delete docs.use
	}

	if(docs.responses.isNil) {
		docs.responses = {
			default: {
				description: docs.description || ''
			}
		}
	}

	return { routePath, method, swagger: docs }
}
<commit_msg>Fixed a bug in compileRoute where it was using incorrect casing for an import path<commit_after>import './Swagger'
import './expandParameters'

import { route as inferRoute } from './Inference/route'
import { parameter as inferParameter } from './Inference/parameter'

export function compileRoute(route, app) {
	let docs = !route.context.isNil ? route.context.swagger : null
	let routePath = route.path
	let method = route.methods

	if(typeof method === 'object') {
		method = Object.keys(method)[0]
	} else {
		method = null
	}

	if(docs.isNil || routePath.isNil || method.isNil) {
		return null
	}

	method = method.toLowerCase()

	if(typeof docs === 'string') {
		docs = { description: docs }
	}

	// Expand base parameters
	docs.parameters = expandParameters(docs.parameters)

	// Add in shared parameters
	Swagger.applyParameters(docs.use, docs.parameters)

	// Infer route, which will modify parameters
	routePath = inferRoute(routePath, app, docs.parameters)

	// Infer all parameters
	for(const parameter of docs.parameters) {
		inferParameter(parameter, method)
	}

	if(docs.parameters.length === 0) {
		delete docs.parameters
	}

	if(!docs.use.isNil) {
		delete docs.use
	}

	if(docs.responses.isNil) {
		docs.responses = {
			default: {
				description: docs.description || ''
			}
		}
	}

	return { routePath, method, swagger: docs }
}
<|endoftext|>


<commit_before>var ReplManager = require("./repl");
var Command = require("./command");
var provision = require("truffle-provisioner");
var contract = require("truffle-contract");
var Web3 = require("web3");
var vm = require("vm");
var expect = require("truffle-expect");
var _ = require("lodash");
var TruffleError = require("truffle-error");
var fs = require("fs");
var os = require("os");
var path = require("path");
var EventEmitter = require("events");
var inherits = require("util").inherits;

inherits(Console, EventEmitter);

function Console(tasks, options) {
  EventEmitter.call(this);

  var self = this;

  expect.options(options, [
    "working_directory",
    "contracts_directory",
    "contracts_build_directory",
    "migrations_directory",
    "network",
    "network_id",
    "provider",
    "resolver",
    "build_directory"
  ]);

  this.options = options;

  this.repl = options.repl || new ReplManager(options);
  this.command = new Command(tasks);

  this.web3 = new Web3();
  this.web3.setProvider(options.provider);

  // Bubble the ReplManager's exit event
  this.repl.on("exit", function() {
    self.emit("exit");
  });
};

Console.prototype.start = function(callback) {
  var self = this;

  if (!this.repl) {
    this.repl = new Repl(this.options);
  }

  // TODO: This should probalby be elsewhere.
  // It's here to ensure the repl manager instance gets
  // passed down to commands.
  this.options.repl = this.repl;

  this.provision(function(err, abstractions) {
    if (err) {
      self.options.logger.log("Unexpected error: Cannot provision contracts while instantiating the console.");
      self.options.logger.log(err.stack || err.message || err);
    }

    self.repl.start({
      prompt: "truffle(" + self.options.network + ")> ",
      context: {
        web3: self.web3,
      },
      interpreter: self.interpret.bind(self),
      done: callback
    });

    self.resetContractsInConsoleContext(abstractions);
  });
};

Console.prototype.provision = function(callback) {
  var self = this;

  fs.readdir(this.options.contracts_build_directory, function(err, files) {
    if (err) {
      // Error reading the build directory? Must mean it doesn't exist or we don't have access to it.
      // Couldn't provision the contracts if we wanted. It's possible we're hiding very rare FS
      // errors, but that's better than showing the user error messages that will be "build folder
      // doesn't exist" 99.9% of the time.
    }

    var promises = [];
    files = files || [];

    files.forEach(function(file) {
      promises.push(new Promise(function(accept, reject) {
        fs.readFile(path.join(self.options.contracts_build_directory, file), "utf8", function(err, body) {
          if (err) return reject(err);
          try {
            body = JSON.parse(body);
          } catch (e) {
            return reject(new Error("Cannot parse " + file + ": " + e.message));
          }

          accept(body);
        })
      }))
    });

    Promise.all(promises).then(function(json_blobs) {
      var abstractions = json_blobs.map(function(json) {
        var abstraction = contract(json);
        provision(abstraction, self.options);
        return abstraction;
      });

      self.resetContractsInConsoleContext(abstractions);

      callback(null, abstractions);
    }).catch(callback);
  });
};

Console.prototype.resetContractsInConsoleContext = function(abstractions) {
  var self = this;

  abstractions = abstractions || []

  var contextVars = {};

  abstractions.forEach(function(abstraction) {
    contextVars[abstraction.contract_name] = abstraction;
  });

  self.repl.setContextVars(contextVars);
}

Console.prototype.interpret = function(cmd, context, filename, callback) {
  var self = this;

  if (this.command.getCommand(cmd.trim(), this.options.noAliases) != null) {
    return self.command.run(cmd.trim(), this.options, function(err) {
      if (err) {
        // Perform error handling ourselves.
        if (err instanceof TruffleError) {
          console.log(err.message);
        } else {
          // Bubble up all other unexpected errors.
          console.log(err.stack || err.toString());
        }
        return callback();
      }

      // Reprovision after each command as it may change contracts.
      self.provision(function(err, abstractions) {
        // Don't pass abstractions to the callback if they're there or else
        // they'll get printed in the repl.
        callback(err);
      });
    });
  }

  var result;

  // Much of the following code is from here, though spruced up:
  // https://github.com/nfcampos/await-outside

  /*
  - allow whitespace before everything else
  - optionally capture `var|let|const <varname> = `
    - varname only matches if it starts with a-Z or _ or $
      and if contains only those chars or numbers
    - this is overly restrictive but is easier to maintain
  - capture `await <anything that follows it>`
  */
  let includesAwait = /^\s*((?:(?:var|const|let)\s+)?[a-zA-Z_$][0-9a-zA-Z_$]*\s*=\s*)?(\(?\s*await[\s\S]*)/;

  var match = cmd.match(includesAwait);
  var newSource = cmd;
  var assignment = null;

  // If our code includes an await, add special processing to ensure it's evaluated properly.
  if (match) {
    var assign = match[1];
    var expression = match[2];

    var RESULT = "__await_outside_result";

    // Wrap the await inside an async function.
    // Strange indentation keeps column offset correct in stack traces
    newSource = `(async function() { try { ${assign ? `global.${RESULT} =` : "return"} (
${expression.trim()}
); } catch(e) { global.ERROR = e; throw e; } }())`;

    assignment = assign
      ? `${assign.trim()} global.${RESULT}; void delete global.${RESULT};`
      : null;
  } else {
    // No await? Just process the source as normal.
    newSource = cmd;
  }

  var runScript = function(s) {
    const options = { displayErrors: true, breakOnSigint: true, filename: filename };
    return s.runInContext(context, options);
  };

  try {
    const options = { displayErrors: true, lineOffset: -1 };
    var script = vm.createScript(newSource, options);
  } catch (e) {
    // If syntax error, or similar, bail.
    return callback(e);
  }

  // Ensure our script returns a promise whether we're using an
  // async function or not. If our script is an async function,
  // this will ensure the console waits until that await is finished.
  Promise.resolve(runScript(script)).then(function(value) {
    // If there's an assignment to run, run that.
    if (assignment) {
      return runScript(vm.createScript(assignment));
    } else {
      return value;
    }
  }).then(function(value) {
    // All good? Return the value (e.g., eval'd script or assignment)
    callback(null, value);
  }).catch(callback);
}

module.exports = Console;
<commit_msg>Remove unnecessary block; rename newSource to source.<commit_after>var ReplManager = require("./repl");
var Command = require("./command");
var provision = require("truffle-provisioner");
var contract = require("truffle-contract");
var Web3 = require("web3");
var vm = require("vm");
var expect = require("truffle-expect");
var _ = require("lodash");
var TruffleError = require("truffle-error");
var fs = require("fs");
var os = require("os");
var path = require("path");
var EventEmitter = require("events");
var inherits = require("util").inherits;

inherits(Console, EventEmitter);

function Console(tasks, options) {
  EventEmitter.call(this);

  var self = this;

  expect.options(options, [
    "working_directory",
    "contracts_directory",
    "contracts_build_directory",
    "migrations_directory",
    "network",
    "network_id",
    "provider",
    "resolver",
    "build_directory"
  ]);

  this.options = options;

  this.repl = options.repl || new ReplManager(options);
  this.command = new Command(tasks);

  this.web3 = new Web3();
  this.web3.setProvider(options.provider);

  // Bubble the ReplManager's exit event
  this.repl.on("exit", function() {
    self.emit("exit");
  });
};

Console.prototype.start = function(callback) {
  var self = this;

  if (!this.repl) {
    this.repl = new Repl(this.options);
  }

  // TODO: This should probalby be elsewhere.
  // It's here to ensure the repl manager instance gets
  // passed down to commands.
  this.options.repl = this.repl;

  this.provision(function(err, abstractions) {
    if (err) {
      self.options.logger.log("Unexpected error: Cannot provision contracts while instantiating the console.");
      self.options.logger.log(err.stack || err.message || err);
    }

    self.repl.start({
      prompt: "truffle(" + self.options.network + ")> ",
      context: {
        web3: self.web3,
      },
      interpreter: self.interpret.bind(self),
      done: callback
    });

    self.resetContractsInConsoleContext(abstractions);
  });
};

Console.prototype.provision = function(callback) {
  var self = this;

  fs.readdir(this.options.contracts_build_directory, function(err, files) {
    if (err) {
      // Error reading the build directory? Must mean it doesn't exist or we don't have access to it.
      // Couldn't provision the contracts if we wanted. It's possible we're hiding very rare FS
      // errors, but that's better than showing the user error messages that will be "build folder
      // doesn't exist" 99.9% of the time.
    }

    var promises = [];
    files = files || [];

    files.forEach(function(file) {
      promises.push(new Promise(function(accept, reject) {
        fs.readFile(path.join(self.options.contracts_build_directory, file), "utf8", function(err, body) {
          if (err) return reject(err);
          try {
            body = JSON.parse(body);
          } catch (e) {
            return reject(new Error("Cannot parse " + file + ": " + e.message));
          }

          accept(body);
        })
      }))
    });

    Promise.all(promises).then(function(json_blobs) {
      var abstractions = json_blobs.map(function(json) {
        var abstraction = contract(json);
        provision(abstraction, self.options);
        return abstraction;
      });

      self.resetContractsInConsoleContext(abstractions);

      callback(null, abstractions);
    }).catch(callback);
  });
};

Console.prototype.resetContractsInConsoleContext = function(abstractions) {
  var self = this;

  abstractions = abstractions || []

  var contextVars = {};

  abstractions.forEach(function(abstraction) {
    contextVars[abstraction.contract_name] = abstraction;
  });

  self.repl.setContextVars(contextVars);
}

Console.prototype.interpret = function(cmd, context, filename, callback) {
  var self = this;

  if (this.command.getCommand(cmd.trim(), this.options.noAliases) != null) {
    return self.command.run(cmd.trim(), this.options, function(err) {
      if (err) {
        // Perform error handling ourselves.
        if (err instanceof TruffleError) {
          console.log(err.message);
        } else {
          // Bubble up all other unexpected errors.
          console.log(err.stack || err.toString());
        }
        return callback();
      }

      // Reprovision after each command as it may change contracts.
      self.provision(function(err, abstractions) {
        // Don't pass abstractions to the callback if they're there or else
        // they'll get printed in the repl.
        callback(err);
      });
    });
  }

  var result;

  // Much of the following code is from here, though spruced up:
  // https://github.com/nfcampos/await-outside

  /*
  - allow whitespace before everything else
  - optionally capture `var|let|const <varname> = `
    - varname only matches if it starts with a-Z or _ or $
      and if contains only those chars or numbers
    - this is overly restrictive but is easier to maintain
  - capture `await <anything that follows it>`
  */
  let includesAwait = /^\s*((?:(?:var|const|let)\s+)?[a-zA-Z_$][0-9a-zA-Z_$]*\s*=\s*)?(\(?\s*await[\s\S]*)/;

  var match = cmd.match(includesAwait);
  var source = cmd;
  var assignment = null;

  // If our code includes an await, add special processing to ensure it's evaluated properly.
  if (match) {
    var assign = match[1];
    var expression = match[2];

    var RESULT = "__await_outside_result";

    // Wrap the await inside an async function.
    // Strange indentation keeps column offset correct in stack traces
    source = `(async function() { try { ${assign ? `global.${RESULT} =` : "return"} (
${expression.trim()}
); } catch(e) { global.ERROR = e; throw e; } }())`;

    assignment = assign
      ? `${assign.trim()} global.${RESULT}; void delete global.${RESULT};`
      : null;
  }

  var runScript = function(s) {
    const options = { displayErrors: true, breakOnSigint: true, filename: filename };
    return s.runInContext(context, options);
  };

  try {
    const options = { displayErrors: true, lineOffset: -1 };
    var script = vm.createScript(source, options);
  } catch (e) {
    // If syntax error, or similar, bail.
    return callback(e);
  }

  // Ensure our script returns a promise whether we're using an
  // async function or not. If our script is an async function,
  // this will ensure the console waits until that await is finished.
  Promise.resolve(runScript(script)).then(function(value) {
    // If there's an assignment to run, run that.
    if (assignment) {
      return runScript(vm.createScript(assignment));
    } else {
      return value;
    }
  }).then(function(value) {
    // All good? Return the value (e.g., eval'd script or assignment)
    callback(null, value);
  }).catch(callback);
}

module.exports = Console;
<|endoftext|>


<commit_before>app.controller("RegisterTreatmentCtrl", function ($scope, $http) {
    $scope.$on('$viewContentLoaded', function () {
        $('#fromTime').datetimepicker();
        $('#toTime').datetimepicker();
    });

    function getData() {
        $http.get('/api/hospital/GetHospitals').then(function (data) {
            $scope.data = data.data;
            $scope.data.forEach(function (data) {
                data.hospitals.forEach(function (hospital) {
                    hospital.departments.push({ name: ''});
                });
            });
            $scope.provide = $scope.data[1];
            $scope.$watch('provide', function () {
                if ($scope.provide && $scope.provide.hospitals) {
                    $scope.hospital = $scope.provide.hospitals[0];
                }
            });
            $scope.$watch('hospital', function () {
                if ($scope.hospital && $scope.hospital.departments) {
                    $scope.department = $scope.hospital.departments[0];
                }
            });
        });
    };
    getData();

    $scope.model = {};
    $scope.submit = function () {
        $scope.model.hospitalId = $scope.hospital.id;
        $scope.model.departmentId = $scope.department.id;
        if ($scope.doctor) {
            $scope.model.DoctorId = $scope.doctor.id;
        }
        $scope.model.startTime = $('#fromTime').val();
        $scope.model.endTime = $('#toTime').val();
        $http.post('/api/appointment/requestappointment', $scope.model).then(function (data) {
            $scope.isSuccess = true;
        }, function () {
            $scope.isError = true;
        });
    };
});<commit_msg>update provide<commit_after>app.controller("RegisterTreatmentCtrl", function ($scope, $http) {
    $scope.$on('$viewContentLoaded', function () {
        $('#fromTime').datetimepicker();
        $('#toTime').datetimepicker();
    });

    function getData() {
        $http.get('/api/hospital/GetHospitals').then(function (data) {
            $scope.data = data.data;
            $scope.data.forEach(function (data) {
                data.hospitals.forEach(function (hospital) {
                    hospital.departments.push({ name: ''});
                });
            });
            $scope.data.forEach(function (item) {
                if (item.province == 'Bình Dương') {
                    $scope.provide = item;
                }
            });
            $scope.$watch('provide', function () {
                if ($scope.provide && $scope.provide.hospitals) {
                    $scope.hospital = $scope.provide.hospitals[0];
                }
            });
            $scope.$watch('hospital', function () {
                if ($scope.hospital && $scope.hospital.departments) {
                    $scope.department = $scope.hospital.departments[0];
                }
            });
        });
    };
    getData();

    $scope.model = {};
    $scope.submit = function () {
        $scope.model.hospitalId = $scope.hospital.id;
        $scope.model.departmentId = $scope.department.id;
        if ($scope.doctor) {
            $scope.model.DoctorId = $scope.doctor.id;
        }
        $scope.model.startTime = $('#fromTime').val();
        $scope.model.endTime = $('#toTime').val();
        $http.post('/api/appointment/requestappointment', $scope.model).then(function (data) {
            $scope.isSuccess = true;
        }, function () {
            $scope.isError = true;
        });
    };
});<|endoftext|>


<commit_before>'use strict'

const assert = require('assert')
const pathresolve = require('path').resolve
const fs = require('fs')
const Koa = require('koa')
const mixins = require('./mixin')
const LocalUtil = require('./util.js')

const Tiz = module.exports = class Tiz extends Koa {
  constructor(projectHome) {
    super()

    this.projectHome = projectHome || process.cwd()
    this.appHome = this.projectHome + '/app'
    this.configHome = this.projectHome + '/config'

    // others
    this._util = LocalUtil
  }

  /**
   * path.resolve bind for projectHome
   */

  resolve(path) {
    return pathresolve(this.projectHome, path)
  }

  /**
   * init for Tiz
   */

  async start(startConfig) {
    // global var
    global.tiz = this
    const app = this
    this.startConfig = startConfig

    // read configs
    this.config = this.readConfig(startConfig)

    // service
    this.setupServices()

    // middlewares
    this.setupMiddlewares()

    // plugins
    this.setupPlugins()

    // await bootstrap
    const bsp = this.appHome + '/bootstrap.js'
    if (fs.existsAync(bsp)) {
      await require(bsp).call(this, this)
    }

    // listen
    if (this.config.listen !== false) {
      await new Promise((resolve, reject) => {
        app.listen(this.config.port, function() {
          console.log('tiz listening at http://localhost:%s', this.address().port)
          app.server = this
          app.emit('ready')
          resolve()
        })
      })
    }
  }
}

/**
 * add mixin
 */

Object.assign(Tiz.prototype, mixins)<commit_msg>core: fix<commit_after>'use strict'

const assert = require('assert')
const pathresolve = require('path').resolve
const fs = require('fs')
const Koa = require('koa')
const mixins = require('./mixin')
const LocalUtil = require('./util.js')

const Tiz = module.exports = class Tiz extends Koa {
  constructor(projectHome) {
    super()

    this.projectHome = projectHome || process.cwd()
    this.appHome = this.projectHome + '/app'
    this.configHome = this.projectHome + '/config'

    // others
    this._util = LocalUtil
  }

  /**
   * path.resolve bind for projectHome
   */

  resolve(path) {
    return pathresolve(this.projectHome, path)
  }

  /**
   * init for Tiz
   */

  async start(startConfig) {
    // global var
    global.tiz = this
    const app = this

    // read configs
    this.config = this.readConfig(startConfig)

    // service
    this.setupServices()

    // middlewares
    this.setupMiddlewares()

    // plugins
    this.setupPlugins()

    // await bootstrap
    const bsp = this.appHome + '/bootstrap.js'
    if (fs.existsSync(bsp)) {
      await require(bsp).call(this, this)
    }

    // listen
    if (this.config.listen !== false) {
      await new Promise((resolve, reject) => {
        app.listen(this.config.port, function() {
          console.log('tiz listening at http://localhost:%s', this.address().port)
          app.server = this
          app.emit('ready')
          resolve()
        })
      })
    }
  }
}

/**
 * add mixin
 */

Object.assign(Tiz.prototype, mixins)<|endoftext|>