<commit_before>/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
 * Copyright 2013 Mozilla Foundation
 *
 * 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.
 */
/* global importScripts, FileReader, FileReaderSync, SWF,
 defineBitmap, defineImage, defineFont, defineShape, defineSound,
 defineLabel, defineButton, defineText, createSoundStream,
 SWF_TAG_CODE_DEFINE_BITS, SWF_TAG_CODE_DEFINE_BITS_JPEG2,
 SWF_TAG_CODE_DEFINE_BITS_JPEG3, SWF_TAG_CODE_DEFINE_BITS_JPEG4,
 SWF_TAG_CODE_DEFINE_BITS_LOSSLESS, SWF_TAG_CODE_DEFINE_BITS_LOSSLESS2,
 SWF_TAG_CODE_DEFINE_BUTTON, SWF_TAG_CODE_DEFINE_BUTTON2,
 SWF_TAG_CODE_DEFINE_EDIT_TEXT, SWF_TAG_CODE_DEFINE_FONT,
 SWF_TAG_CODE_DEFINE_FONT2, SWF_TAG_CODE_DEFINE_FONT3,
 SWF_TAG_CODE_DEFINE_FONT4, SWF_TAG_CODE_DEFINE_MORPH_SHAPE,
 SWF_TAG_CODE_DEFINE_MORPH_SHAPE2, SWF_TAG_CODE_DEFINE_SCALING_GRID,
 SWF_TAG_CODE_DEFINE_SCENE_AND_FRAME_LABEL_DATA, SWF_TAG_CODE_DEFINE_SHAPE,
 SWF_TAG_CODE_DEFINE_SHAPE2, SWF_TAG_CODE_DEFINE_SHAPE3,
 SWF_TAG_CODE_DEFINE_SHAPE4, SWF_TAG_CODE_DEFINE_SOUND,
 SWF_TAG_CODE_DEFINE_SPRITE, SWF_TAG_CODE_DEFINE_TEXT,
 SWF_TAG_CODE_DEFINE_TEXT2, SWF_TAG_CODE_DO_ABC,
 SWF_TAG_CODE_DO_ABC_, SWF_TAG_CODE_DO_ACTION,
 SWF_TAG_CODE_DO_INIT_ACTION, SWF_TAG_CODE_FRAME_LABEL,
 SWF_TAG_CODE_JPEG_TABLES, SWF_TAG_CODE_PLACE_OBJECT,
 SWF_TAG_CODE_PLACE_OBJECT2, SWF_TAG_CODE_PLACE_OBJECT3,
 SWF_TAG_CODE_REMOVE_OBJECT, SWF_TAG_CODE_REMOVE_OBJECT2,
 SWF_TAG_CODE_SET_BACKGROUND_COLOR, SWF_TAG_CODE_SHOW_FRAME,
 SWF_TAG_CODE_SOUND_STREAM_BLOCK, SWF_TAG_CODE_SOUND_STREAM_HEAD,
 SWF_TAG_CODE_START_SOUND, SWF_TAG_CODE_SYMBOL_CLASS,
 SWF_TAG_CODE_DEFINE_BINARY_DATA, SWF_TAG_CODE_EXPORT_ASSETS */

var $RELEASE = false;
var isWorker = typeof window === 'undefined';

if (isWorker && !$RELEASE) {
  importScripts.apply(null, [
    // TODO: drop DataView, probably
    '../../lib/DataView.js/DataView.js',
    '../flash/util.js',
    'config.js',
    'swf.js',
    'types.js',
    'structs.js',
    'tags.js',
    'inflate.js',
    'stream.js',
    'templates.js',
    'generator.js',
    'handlers.js',
    'parser.js',
    'bitmap.js',
    'button.js',
    'font.js',
    'image.js',
    'label.js',
    'shape.js',
    'sound.js',
    'text.js'
  ]);
}

function loadFromWorker(loader, request, context) {
  var symbols = { };

  var commitData = function (data, transferables) {
    try {
      loader.postMessage(data, transferables);
    } catch (ex) {
      // Attempting to fix IE10/IE11 transferables
      if (ex != 'DataCloneError') {
        throw ex;
      }
      commitData = function (data) {
        loader.postMessage(data);
      };
      commitData(data);
    }
  };

  function defineSymbol(swfTag) {
    var symbol;

    switch (swfTag.code) {
      case SWF_TAG_CODE_DEFINE_BITS:
      case SWF_TAG_CODE_DEFINE_BITS_JPEG2:
      case SWF_TAG_CODE_DEFINE_BITS_JPEG3:
      case SWF_TAG_CODE_DEFINE_BITS_JPEG4:
      case SWF_TAG_CODE_JPEG_TABLES:
        symbol = defineImage(swfTag, symbols);
        break;
      case SWF_TAG_CODE_DEFINE_BITS_LOSSLESS:
      case SWF_TAG_CODE_DEFINE_BITS_LOSSLESS2:
        symbol = defineBitmap(swfTag);
        break;
      case SWF_TAG_CODE_DEFINE_BUTTON:
      case SWF_TAG_CODE_DEFINE_BUTTON2:
        symbol = defineButton(swfTag, symbols);
        break;
      case SWF_TAG_CODE_DEFINE_EDIT_TEXT:
        symbol = defineText(swfTag, symbols);
        break;
      case SWF_TAG_CODE_DEFINE_FONT:
      case SWF_TAG_CODE_DEFINE_FONT2:
      case SWF_TAG_CODE_DEFINE_FONT3:
      case SWF_TAG_CODE_DEFINE_FONT4:
        symbol = defineFont(swfTag, symbols);
        break;
      case SWF_TAG_CODE_DEFINE_MORPH_SHAPE:
      case SWF_TAG_CODE_DEFINE_MORPH_SHAPE2:
      case SWF_TAG_CODE_DEFINE_SHAPE:
      case SWF_TAG_CODE_DEFINE_SHAPE2:
      case SWF_TAG_CODE_DEFINE_SHAPE3:
      case SWF_TAG_CODE_DEFINE_SHAPE4:
        symbol = defineShape(swfTag, symbols);
        break;
      case SWF_TAG_CODE_DEFINE_SOUND:
        symbol = defineSound(swfTag, symbols);
        break;
      case SWF_TAG_CODE_DEFINE_BINARY_DATA:
        symbol = {
          type: 'binary',
          id: swfTag.id,
          // TODO: make transferable
          data: swfTag.data
        };
        break;
      case SWF_TAG_CODE_DEFINE_SPRITE:
        var depths = { };
        var frame = { type: 'frame' };
        var frames = [];
        var tags = swfTag.tags;
        var frameScripts = null;
        var frameIndex = 0;
        var soundStream = null;
        for (var i = 0, n = tags.length; i < n; i++) {
          var tag = tags[i];
          switch (tag.code) {
            case SWF_TAG_CODE_DO_ACTION:
              if (!frameScripts)
                frameScripts = [];
              frameScripts.push(frameIndex);
              frameScripts.push(tag.actionsData);
              break;
            // case SWF_TAG_CODE_DO_INIT_ACTION: ??
            case SWF_TAG_CODE_START_SOUND:
              var startSounds = frame.startSounds || (frame.startSounds = []);
              startSounds.push(tag);
              break;
            case SWF_TAG_CODE_SOUND_STREAM_HEAD:
              try {
                // TODO: make transferable
                soundStream = createSoundStream(tag);
                frame.soundStream = soundStream.info;
              } catch (e) {
                // ignoring if sound stream codec is not supported
                // console.error('ERROR: ' + e.message);
              }
              break;
            case SWF_TAG_CODE_SOUND_STREAM_BLOCK:
              if (soundStream) {
                frame.soundStreamBlock = soundStream.decode(tag.data);
              }
              break;
            case SWF_TAG_CODE_FRAME_LABEL:
              frame.labelName = tag.name;
              break;
            case SWF_TAG_CODE_PLACE_OBJECT:
            case SWF_TAG_CODE_PLACE_OBJECT2:
            case SWF_TAG_CODE_PLACE_OBJECT3:
              depths[tag.depth] = tag;
              break;
            case SWF_TAG_CODE_REMOVE_OBJECT:
            case SWF_TAG_CODE_REMOVE_OBJECT2:
              depths[tag.depth] = null;
              break;
            case SWF_TAG_CODE_SHOW_FRAME:
              var repeat = 1;
              while (i < n - 1) {
                var nextTag = tags[i + 1];
                if (nextTag.code !== SWF_TAG_CODE_SHOW_FRAME)
                  break;
                i++;
                repeat++;
              }
              frameIndex += repeat;
              frame.repeat = repeat;
              frame.depths = depths;
              frames.push(frame);
              depths = { };
              frame = { type: 'frame' };
              break;
          }
        }
        symbol = {
          type: 'sprite',
          id: swfTag.id,
          frameCount: swfTag.frameCount,
          frames: frames,
          frameScripts: frameScripts
        };
        break;
      case SWF_TAG_CODE_DEFINE_TEXT:
      case SWF_TAG_CODE_DEFINE_TEXT2:
        symbol = defineLabel(swfTag, symbols);
        break;
    }

    if (!symbol) {
      commitData({
                   command: 'error',
                   message: 'unknown symbol type: ' + swfTag.code
                 });
      return;
    }

    symbol.isSymbol = true;
    symbols[swfTag.id] = symbol;
    commitData(symbol, symbol.transferables);
  }
  function createParsingContext() {
    var depths = { };
    var frame = { type: 'frame' };
    var tagsProcessed = 0;
    var soundStream = null;
    var lastProgressSent = 0;

    return {
      onstart: function(result) {
        commitData({command: 'init', result: result});
      },
      onprogress: function(result) {
        if (Date.now() - lastProgressSent > 1000 / 24 ||
            result.bytesLoaded === result.bytesTotal) {
          commitData({command: 'progress', result: {
            bytesLoaded: result.bytesLoaded,
            bytesTotal: result.bytesTotal
          }});
          lastProgressSent = Date.now();
        }

        var tags = result.tags;
        for (var n = tags.length; tagsProcessed < n; tagsProcessed++) {
          var tag = tags[tagsProcessed];
          if ('id' in tag) {
            defineSymbol(tag);
            continue;
          }

          switch (tag.code) {
            case SWF_TAG_CODE_DEFINE_SCENE_AND_FRAME_LABEL_DATA:
              frame.sceneData = tag;
              break;
            case SWF_TAG_CODE_DEFINE_SCALING_GRID:
              var symbolUpdate = {
                isSymbol: true,
                id: tag.symbolId,
                updates: {
                  scale9Grid: tag.splitter
                }
              };
              commitData(symbolUpdate);
              break;
            case SWF_TAG_CODE_DO_ABC:
            case SWF_TAG_CODE_DO_ABC_:
              var abcBlocks = frame.abcBlocks;
              if (abcBlocks)
                abcBlocks.push({data: tag.data, flags: tag.flags});
              else
                frame.abcBlocks = [{data: tag.data, flags: tag.flags}];
              break;
            case SWF_TAG_CODE_DO_ACTION:
              var actionBlocks = frame.actionBlocks;
              if (actionBlocks)
                actionBlocks.push(tag.actionsData);
              else
                frame.actionBlocks = [tag.actionsData];
              break;
            case SWF_TAG_CODE_DO_INIT_ACTION:
              var initActionBlocks = frame.initActionBlocks ||
                                     (frame.initActionBlocks = []);
              initActionBlocks.push({spriteId: tag.spriteId, actionsData: tag.actionsData});
              break;
            case SWF_TAG_CODE_START_SOUND:
              var startSounds = frame.startSounds;
              if (!startSounds)
                frame.startSounds = startSounds = [];
              startSounds.push(tag);
              break;
            case SWF_TAG_CODE_SOUND_STREAM_HEAD:
              try {
                // TODO: make transferable
                soundStream = createSoundStream(tag);
                frame.soundStream = soundStream.info;
              } catch (e) {
                // ignoring if sound stream codec is not supported
                // console.error('ERROR: ' + e.message);
              }
              break;
            case SWF_TAG_CODE_SOUND_STREAM_BLOCK:
              if (soundStream) {
                frame.soundStreamBlock = soundStream.decode(tag.data);
              }
              break;
            case SWF_TAG_CODE_EXPORT_ASSETS:
              var exports = frame.exports;
              if (exports)
                frame.exports = exports.concat(tag.exports);
              else
                frame.exports = tag.exports.slice(0);
              break;
            case SWF_TAG_CODE_SYMBOL_CLASS:
              var symbolClasses = frame.symbolClasses;
              if (symbolClasses)
                frame.symbolClasses = symbolClasses.concat(tag.exports);
              else
                frame.symbolClasses = tag.exports.slice(0);
              break;
            case SWF_TAG_CODE_FRAME_LABEL:
              frame.labelName = tag.name;
              break;
            case SWF_TAG_CODE_PLACE_OBJECT:
            case SWF_TAG_CODE_PLACE_OBJECT2:
            case SWF_TAG_CODE_PLACE_OBJECT3:
              depths[tag.depth] = tag;
              break;
            case SWF_TAG_CODE_REMOVE_OBJECT:
            case SWF_TAG_CODE_REMOVE_OBJECT2:
              depths[tag.depth] = null;
              break;
            case SWF_TAG_CODE_SET_BACKGROUND_COLOR:
              frame.bgcolor = tag.color;
              break;
            case SWF_TAG_CODE_SHOW_FRAME:
              var repeat = 1;
              while (tagsProcessed < n) {
                var nextTag = tags[tagsProcessed + 1];
                if (!nextTag || nextTag.code !== SWF_TAG_CODE_SHOW_FRAME)
                  break;
                tagsProcessed++;
                repeat++;
              }
              frame.repeat = repeat;
              frame.depths = depths;
              commitData(frame);
              depths = { };
              frame = { type: 'frame' };
              break;
          }
        }
      },
      oncomplete: function(result) {
        commitData(result);

        var stats;
        if (typeof result.swfVersion === 'number') {
          // Extracting stats from the context object
          var bbox = result.bbox;
          stats = {
            topic: 'parseInfo', // HACK additional field for telemetry
            parseTime: result.parseTime,
            bytesTotal: result.bytesTotal,
            swfVersion: result.swfVersion,
            frameRate: result.frameRate,
            width: (bbox.xMax - bbox.xMin) / 20,
            height: (bbox.yMax - bbox.yMin) / 20,
            isAvm2: !!result.fileAttributes.doAbc
          };
        }

        commitData({command: 'complete', stats: stats});
      }
    };
  }
  function parseBytes(bytes) {
    SWF.parse(bytes, createParsingContext());
  }

  if (request instanceof ArrayBuffer) {
    parseBytes(request);
  } else if ('subscribe' in request) {
    var pipe = SWF.parseAsync(createParsingContext());
    request.subscribe(function (data, progress) {
      if (data) {
        pipe.push(data, progress);
      } else {
        pipe.close();
      }
    });
  } else if (typeof FileReaderSync !== 'undefined') {
    var reader = new FileReaderSync();
    var buffer = reader.readAsArrayBuffer(request);
    parseBytes(buffer);
  } else {
    var reader = new FileReader();
    reader.onload = function () {
      parseBytes(this.result);
    };
    reader.readAsArrayBuffer(request);
  }
}

function createResourceDataListener(loader) {
  var subscription = null;
  return function (data) {
    if (subscription) {
      subscription.callback(data.data, data.progress);
    } else if (data === 'pipe:') {
      // progressive data loading is requested, replacing onmessage handler
      // for the following messages
      subscription = {
        subscribe: function(callback) {
          this.callback = callback;
        }
      };
      loadFromWorker(loader, subscription);
    } else {
      loadFromWorker(loader, data);
    }
  };
}
function ResourceLoader(scope) {
  var loader;

  if (!isWorker) {
    var self = this;
    loader = {
      postMessage : function(data) {
        self.onmessage({data:data});
      }
    };
    this.postMessage = function(data) {
      listener && listener(data);
    };
    this.terminate = function() {
      listener = null;
      loader = null;
      scope = null;
    };
  } else {
    loader = scope;
    scope.onmessage = function(event) {
      listener(event.data);
    };
  }
  var listener = createResourceDataListener(loader);
}

if (isWorker) {
  var loader = new ResourceLoader(this);
}
<commit_msg>Moves large child functions out of resourceloader's loadFromWorker<commit_after>/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
 * Copyright 2013 Mozilla Foundation
 *
 * 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.
 */
/* global importScripts, FileReader, FileReaderSync, SWF,
 defineBitmap, defineImage, defineFont, defineShape, defineSound,
 defineLabel, defineButton, defineText, createSoundStream,
 SWF_TAG_CODE_DEFINE_BITS, SWF_TAG_CODE_DEFINE_BITS_JPEG2,
 SWF_TAG_CODE_DEFINE_BITS_JPEG3, SWF_TAG_CODE_DEFINE_BITS_JPEG4,
 SWF_TAG_CODE_DEFINE_BITS_LOSSLESS, SWF_TAG_CODE_DEFINE_BITS_LOSSLESS2,
 SWF_TAG_CODE_DEFINE_BUTTON, SWF_TAG_CODE_DEFINE_BUTTON2,
 SWF_TAG_CODE_DEFINE_EDIT_TEXT, SWF_TAG_CODE_DEFINE_FONT,
 SWF_TAG_CODE_DEFINE_FONT2, SWF_TAG_CODE_DEFINE_FONT3,
 SWF_TAG_CODE_DEFINE_FONT4, SWF_TAG_CODE_DEFINE_MORPH_SHAPE,
 SWF_TAG_CODE_DEFINE_MORPH_SHAPE2, SWF_TAG_CODE_DEFINE_SCALING_GRID,
 SWF_TAG_CODE_DEFINE_SCENE_AND_FRAME_LABEL_DATA, SWF_TAG_CODE_DEFINE_SHAPE,
 SWF_TAG_CODE_DEFINE_SHAPE2, SWF_TAG_CODE_DEFINE_SHAPE3,
 SWF_TAG_CODE_DEFINE_SHAPE4, SWF_TAG_CODE_DEFINE_SOUND,
 SWF_TAG_CODE_DEFINE_SPRITE, SWF_TAG_CODE_DEFINE_TEXT,
 SWF_TAG_CODE_DEFINE_TEXT2, SWF_TAG_CODE_DO_ABC,
 SWF_TAG_CODE_DO_ABC_, SWF_TAG_CODE_DO_ACTION,
 SWF_TAG_CODE_DO_INIT_ACTION, SWF_TAG_CODE_FRAME_LABEL,
 SWF_TAG_CODE_JPEG_TABLES, SWF_TAG_CODE_PLACE_OBJECT,
 SWF_TAG_CODE_PLACE_OBJECT2, SWF_TAG_CODE_PLACE_OBJECT3,
 SWF_TAG_CODE_REMOVE_OBJECT, SWF_TAG_CODE_REMOVE_OBJECT2,
 SWF_TAG_CODE_SET_BACKGROUND_COLOR, SWF_TAG_CODE_SHOW_FRAME,
 SWF_TAG_CODE_SOUND_STREAM_BLOCK, SWF_TAG_CODE_SOUND_STREAM_HEAD,
 SWF_TAG_CODE_START_SOUND, SWF_TAG_CODE_SYMBOL_CLASS,
 SWF_TAG_CODE_DEFINE_BINARY_DATA, SWF_TAG_CODE_EXPORT_ASSETS */

var $RELEASE = false;
var isWorker = typeof window === 'undefined';

if (isWorker && !$RELEASE) {
  importScripts.apply(null, [
    // TODO: drop DataView, probably
    '../../lib/DataView.js/DataView.js',
    '../flash/util.js',
    'config.js',
    'swf.js',
    'types.js',
    'structs.js',
    'tags.js',
    'inflate.js',
    'stream.js',
    'templates.js',
    'generator.js',
    'handlers.js',
    'parser.js',
    'bitmap.js',
    'button.js',
    'font.js',
    'image.js',
    'label.js',
    'shape.js',
    'sound.js',
    'text.js'
  ]);
}

function loadFromWorker(loader, request, context) {

  function commitData(data, transferables) {
    try {
      loader.postMessage(data, transferables);
    } catch (ex) {
      // Attempting to fix IE10/IE11 transferables by retrying without
      // Transerables.
      if (ex != 'DataCloneError') {
        throw ex;
      }
      loader.postMessage(data);
    }
  };

  if (request instanceof ArrayBuffer) {
    parseBytes(request, commitData);
  } else if ('subscribe' in request) {
    var pipe = SWF.parseAsync(createParsingContext(commitData));
    request.subscribe(function (data, progress) {
      if (data) {
        pipe.push(data, progress);
      } else {
        pipe.close();
      }
    });
  } else if (typeof FileReaderSync !== 'undefined') {
    var reader = new FileReaderSync();
    var buffer = reader.readAsArrayBuffer(request);
    parseBytes(buffer, commitData);
  } else {
    var reader = new FileReader();
    reader.onload = function () {
      parseBytes(this.result, commitData);
    };
    reader.readAsArrayBuffer(request);
  }
}

function defineSymbol(swfTag, symbols) {
  var symbol;

  switch (swfTag.code) {
    case SWF_TAG_CODE_DEFINE_BITS:
    case SWF_TAG_CODE_DEFINE_BITS_JPEG2:
    case SWF_TAG_CODE_DEFINE_BITS_JPEG3:
    case SWF_TAG_CODE_DEFINE_BITS_JPEG4:
    case SWF_TAG_CODE_JPEG_TABLES:
      symbol = defineImage(swfTag, symbols);
      break;
    case SWF_TAG_CODE_DEFINE_BITS_LOSSLESS:
    case SWF_TAG_CODE_DEFINE_BITS_LOSSLESS2:
      symbol = defineBitmap(swfTag);
      break;
    case SWF_TAG_CODE_DEFINE_BUTTON:
    case SWF_TAG_CODE_DEFINE_BUTTON2:
      symbol = defineButton(swfTag, symbols);
      break;
    case SWF_TAG_CODE_DEFINE_EDIT_TEXT:
      symbol = defineText(swfTag, symbols);
      break;
    case SWF_TAG_CODE_DEFINE_FONT:
    case SWF_TAG_CODE_DEFINE_FONT2:
    case SWF_TAG_CODE_DEFINE_FONT3:
    case SWF_TAG_CODE_DEFINE_FONT4:
      symbol = defineFont(swfTag, symbols);
      break;
    case SWF_TAG_CODE_DEFINE_MORPH_SHAPE:
    case SWF_TAG_CODE_DEFINE_MORPH_SHAPE2:
    case SWF_TAG_CODE_DEFINE_SHAPE:
    case SWF_TAG_CODE_DEFINE_SHAPE2:
    case SWF_TAG_CODE_DEFINE_SHAPE3:
    case SWF_TAG_CODE_DEFINE_SHAPE4:
      symbol = defineShape(swfTag, symbols);
      break;
    case SWF_TAG_CODE_DEFINE_SOUND:
      symbol = defineSound(swfTag, symbols);
      break;
    case SWF_TAG_CODE_DEFINE_BINARY_DATA:
      symbol = {
        type: 'binary',
        id: swfTag.id,
        // TODO: make transferable
        data: swfTag.data
      };
      break;
    case SWF_TAG_CODE_DEFINE_SPRITE:
      var depths = { };
      var frame = { type: 'frame' };
      var frames = [];
      var tags = swfTag.tags;
      var frameScripts = null;
      var frameIndex = 0;
      var soundStream = null;
      for (var i = 0, n = tags.length; i < n; i++) {
        var tag = tags[i];
        switch (tag.code) {
          case SWF_TAG_CODE_DO_ACTION:
            if (!frameScripts)
              frameScripts = [];
            frameScripts.push(frameIndex);
            frameScripts.push(tag.actionsData);
            break;
          // case SWF_TAG_CODE_DO_INIT_ACTION: ??
          case SWF_TAG_CODE_START_SOUND:
            var startSounds = frame.startSounds || (frame.startSounds = []);
            startSounds.push(tag);
            break;
          case SWF_TAG_CODE_SOUND_STREAM_HEAD:
            try {
              // TODO: make transferable
              soundStream = createSoundStream(tag);
              frame.soundStream = soundStream.info;
            } catch (e) {
              // ignoring if sound stream codec is not supported
              // console.error('ERROR: ' + e.message);
            }
            break;
          case SWF_TAG_CODE_SOUND_STREAM_BLOCK:
            if (soundStream) {
              frame.soundStreamBlock = soundStream.decode(tag.data);
            }
            break;
          case SWF_TAG_CODE_FRAME_LABEL:
            frame.labelName = tag.name;
            break;
          case SWF_TAG_CODE_PLACE_OBJECT:
          case SWF_TAG_CODE_PLACE_OBJECT2:
          case SWF_TAG_CODE_PLACE_OBJECT3:
            depths[tag.depth] = tag;
            break;
          case SWF_TAG_CODE_REMOVE_OBJECT:
          case SWF_TAG_CODE_REMOVE_OBJECT2:
            depths[tag.depth] = null;
            break;
          case SWF_TAG_CODE_SHOW_FRAME:
            var repeat = 1;
            while (i < n - 1) {
              var nextTag = tags[i + 1];
              if (nextTag.code !== SWF_TAG_CODE_SHOW_FRAME)
                break;
              i++;
              repeat++;
            }
            frameIndex += repeat;
            frame.repeat = repeat;
            frame.depths = depths;
            frames.push(frame);
            depths = { };
            frame = { type: 'frame' };
            break;
        }
      }
      symbol = {
        type: 'sprite',
        id: swfTag.id,
        frameCount: swfTag.frameCount,
        frames: frames,
        frameScripts: frameScripts
      };
      break;
    case SWF_TAG_CODE_DEFINE_TEXT:
    case SWF_TAG_CODE_DEFINE_TEXT2:
      symbol = defineLabel(swfTag, symbols);
      break;
  }

  if (!symbol) {
    return {command: 'error', message: 'unknown symbol type: ' + swfTag.code};
  }

  symbol.isSymbol = true;
  symbols[swfTag.id] = symbol;
  return symbol;
}
function createParsingContext(commitData) {
  var depths = {};
  var symbols = {};
  var frame = { type: 'frame' };
  var tagsProcessed = 0;
  var soundStream = null;
  var lastProgressSent = 0;

  return {
    onstart: function(result) {
      commitData({command: 'init', result: result});
    },
    onprogress: function(result) {
      if (Date.now() - lastProgressSent > 1000 / 24 ||
          result.bytesLoaded === result.bytesTotal) {
        commitData({command: 'progress', result: {
          bytesLoaded: result.bytesLoaded,
          bytesTotal: result.bytesTotal
        }});
        lastProgressSent = Date.now();
      }

      var tags = result.tags;
      for (var n = tags.length; tagsProcessed < n; tagsProcessed++) {
        var tag = tags[tagsProcessed];
        if ('id' in tag) {
          var symbol = defineSymbol(tag, symbols);
          commitData(symbol, symbol.transferables);
          continue;
        }

        switch (tag.code) {
          case SWF_TAG_CODE_DEFINE_SCENE_AND_FRAME_LABEL_DATA:
            frame.sceneData = tag;
            break;
          case SWF_TAG_CODE_DEFINE_SCALING_GRID:
            var symbolUpdate = {
              isSymbol: true,
              id: tag.symbolId,
              updates: {
                scale9Grid: tag.splitter
              }
            };
            commitData(symbolUpdate);
            break;
          case SWF_TAG_CODE_DO_ABC:
          case SWF_TAG_CODE_DO_ABC_:
            var abcBlocks = frame.abcBlocks;
            if (abcBlocks)
              abcBlocks.push({data: tag.data, flags: tag.flags});
            else
              frame.abcBlocks = [{data: tag.data, flags: tag.flags}];
            break;
          case SWF_TAG_CODE_DO_ACTION:
            var actionBlocks = frame.actionBlocks;
            if (actionBlocks)
              actionBlocks.push(tag.actionsData);
            else
              frame.actionBlocks = [tag.actionsData];
            break;
          case SWF_TAG_CODE_DO_INIT_ACTION:
            var initActionBlocks = frame.initActionBlocks ||
                                   (frame.initActionBlocks = []);
            initActionBlocks.push({spriteId: tag.spriteId, actionsData: tag.actionsData});
            break;
          case SWF_TAG_CODE_START_SOUND:
            var startSounds = frame.startSounds;
            if (!startSounds)
              frame.startSounds = startSounds = [];
            startSounds.push(tag);
            break;
          case SWF_TAG_CODE_SOUND_STREAM_HEAD:
            try {
              // TODO: make transferable
              soundStream = createSoundStream(tag);
              frame.soundStream = soundStream.info;
            } catch (e) {
              // ignoring if sound stream codec is not supported
              // console.error('ERROR: ' + e.message);
            }
            break;
          case SWF_TAG_CODE_SOUND_STREAM_BLOCK:
            if (soundStream) {
              frame.soundStreamBlock = soundStream.decode(tag.data);
            }
            break;
          case SWF_TAG_CODE_EXPORT_ASSETS:
            var exports = frame.exports;
            if (exports)
              frame.exports = exports.concat(tag.exports);
            else
              frame.exports = tag.exports.slice(0);
            break;
          case SWF_TAG_CODE_SYMBOL_CLASS:
            var symbolClasses = frame.symbolClasses;
            if (symbolClasses)
              frame.symbolClasses = symbolClasses.concat(tag.exports);
            else
              frame.symbolClasses = tag.exports.slice(0);
            break;
          case SWF_TAG_CODE_FRAME_LABEL:
            frame.labelName = tag.name;
            break;
          case SWF_TAG_CODE_PLACE_OBJECT:
          case SWF_TAG_CODE_PLACE_OBJECT2:
          case SWF_TAG_CODE_PLACE_OBJECT3:
            depths[tag.depth] = tag;
            break;
          case SWF_TAG_CODE_REMOVE_OBJECT:
          case SWF_TAG_CODE_REMOVE_OBJECT2:
            depths[tag.depth] = null;
            break;
          case SWF_TAG_CODE_SET_BACKGROUND_COLOR:
            frame.bgcolor = tag.color;
            break;
          case SWF_TAG_CODE_SHOW_FRAME:
            var repeat = 1;
            while (tagsProcessed < n) {
              var nextTag = tags[tagsProcessed + 1];
              if (!nextTag || nextTag.code !== SWF_TAG_CODE_SHOW_FRAME)
                break;
              tagsProcessed++;
              repeat++;
            }
            frame.repeat = repeat;
            frame.depths = depths;
            commitData(frame);
            depths = { };
            frame = { type: 'frame' };
            break;
        }
      }
    },
    oncomplete: function(result) {
      commitData(result);

      var stats;
      if (typeof result.swfVersion === 'number') {
        // Extracting stats from the context object
        var bbox = result.bbox;
        stats = {
          topic: 'parseInfo', // HACK additional field for telemetry
          parseTime: result.parseTime,
          bytesTotal: result.bytesTotal,
          swfVersion: result.swfVersion,
          frameRate: result.frameRate,
          width: (bbox.xMax - bbox.xMin) / 20,
          height: (bbox.yMax - bbox.yMin) / 20,
          isAvm2: !!result.fileAttributes.doAbc
        };
      }

      commitData({command: 'complete', stats: stats});
    }
  };
}
function parseBytes(bytes, commitData) {
  SWF.parse(bytes, createParsingContext(commitData));
}

function createResourceDataListener(loader) {
  var subscription = null;
  return function (data) {
    if (subscription) {
      subscription.callback(data.data, data.progress);
    } else if (data === 'pipe:') {
      // progressive data loading is requested, replacing onmessage handler
      // for the following messages
      subscription = {
        subscribe: function(callback) {
          this.callback = callback;
        }
      };
      loadFromWorker(loader, subscription);
    } else {
      loadFromWorker(loader, data);
    }
  };
}
function ResourceLoader(scope) {
  var loader;

  if (!isWorker) {
    var self = this;
    loader = {
      postMessage : function(data) {
        self.onmessage({data:data});
      }
    };
    this.postMessage = function(data) {
      listener && listener(data);
    };
    this.terminate = function() {
      listener = null;
      loader = null;
      scope = null;
    };
  } else {
    loader = scope;
    scope.onmessage = function(event) {
      listener(event.data);
    };
  }
  var listener = createResourceDataListener(loader);
}

if (isWorker) {
  var loader = new ResourceLoader(this);
}
<|endoftext|>


<commit_before>import path from "path"
import { execSync } from "child_process"
import _ from "lodash"

function maybeTypeToPropType(maybeType) {
  switch (maybeType) {
    case "boolean":
      return "bool"
    case "number":
      return maybeType
    case "string":
      return maybeType
    default:
      return "any"
  }
}

export default function transformer(file, api) {
  const j = api.jscodeshift
  const wrap = j(file.source)

  const exportConfig = wrap.find(j.ExportNamedDeclaration).at(0)
  const configString = exportConfig.find(j.TemplateElement).get().node.value.raw
  const {
    prohibitedPropNames = [],
    eventMapOverrides,
    getInstanceFromComponent,
  } = JSON.parse(configString)
  exportConfig.remove()
  const eventNamesOverrides = _.values(eventMapOverrides)

  const KlassName = wrap
    .find(j.ClassDeclaration)
    .at(0)
    .get().node.id.name

  const result = execSync(
    `./node_modules/.bin/babel-node ${path.resolve(
      __dirname,
      `./ClassDefinition.js`
    )} "${KlassName}"`,
    {
      encoding: "utf-8",
    }
  )
  const { constructor, methods, events } = JSON.parse(result)
  const methodAsProps = methods.filter(({ name }) => {
    const matchResult = name.match(/^set(\S+)/)
    return (
      name !== "setMap" &&
      matchResult &&
      !_.includes(prohibitedPropNames, _.lowerFirst(matchResult[1]))
    )
  })

  const publicMethods = methods.filter(({ name }) => {
    const matchResult = name.match(/^get(\S+)/)
    return (
      !name.match(/Map$/) &&
      matchResult &&
      !_.includes(prohibitedPropNames, _.lowerFirst(matchResult[1]))
    )
  })

  wrap.find(j.ClassBody).forEach(path => {
    j(path).replaceWith(
      Object.assign(path.node.__clone(), {
        body: [...path.node.body, ...txClassMethods()],
      })
    )
  })

  wrap.find(j.ObjectExpression).forEach(path => {
    if (_.get(path, "parentPath.node.key.name") === "propTypes") {
      j(path).replaceWith(
        Object.assign(path.node.__clone(), {
          properties: [
            ...path.node.properties.filter(
              ({ key: { name } }) => name !== "__jscodeshiftPlaceholder__"
            ),
            ...txPropTypes(),
          ],
        })
      )
    } else if (_.get(path, "parentPath.node.id.name") === "eventMap") {
      j(path).replaceWith(
        Object.assign(path.node.__clone(), {
          properties: [...path.node.properties, ...eventMap()],
        })
      )
    } else if (_.get(path, "parentPath.node.id.name") === "updaterMap") {
      j(path).replaceWith(
        Object.assign(path.node.__clone(), {
          properties: [...path.node.properties, ...updaterMap()],
        })
      )
    }
  })

  return wrap.toSource()

  function txPropTypes() {
    return [
      ...methodAsProps.map(({ name, args, desc }) => {
        const [, prop] = name.match(/^set(\S+)/)
        const [, maybeType] = args.match(/\S+:(\S+)/)

        return Object.assign(
          j.objectProperty(
            j.identifier(`default${prop}`),
            j.identifier(`PropTypes.${maybeTypeToPropType(maybeType)}`)
          ),
          {
            comments: [j.commentBlock(`*\n * @type ${maybeType}\n `, true)],
          }
        )
      }),
      ...methodAsProps.map(({ name, args, desc }) => {
        const [, prop] = name.match(/^set(\S+)/)
        const [, maybeType] = args.match(/\S+:(\S+)/)

        return Object.assign(
          j.objectProperty(
            j.identifier(_.lowerFirst(prop)),
            j.identifier(`PropTypes.${maybeTypeToPropType(maybeType)}`)
          ),
          {
            comments: [j.commentBlock(`*\n * @type ${maybeType}\n `, true)],
          }
        )
      }),

      ..._.map(eventMapOverrides, (eventName, callbackName) =>
        Object.assign(
          j.objectProperty(
            j.identifier(callbackName),
            j.identifier(`PropTypes.func`)
          ),
          {
            comments: [j.commentBlock(`*\n * function\n `, true)],
          }
        )
      ),
      ...events
        .filter(({ name }) => !_.includes(eventNamesOverrides, name))
        .map(({ name }) =>
          Object.assign(
            j.objectProperty(
              j.identifier(_.camelCase(`on${_.capitalize(name)}`)),
              j.identifier(`PropTypes.func`)
            ),
            {
              comments: [j.commentBlock(`*\n * function\n `, true)],
            }
          )
        ),
    ]
  }

  function txClassMethods() {
    return [
      ...publicMethods.map(({ name, returns, returnsDesc }) => {
        return Object.assign(
          j.classMethod(
            "method",
            j.identifier(name),
            [],
            j.blockStatement([
              j.returnStatement(
                j.callExpression(
                  j.identifier(`${getInstanceFromComponent}.${name}`),
                  []
                )
              ),
            ])
          ),
          {
            comments: [
              j.commentBlock(
                `*\n * ${returnsDesc}\n * @type ${returns}\n `,
                true
              ),
            ],
          }
        )
      }),
    ]
  }

  function eventMap() {
    return [
      ..._.map(eventMapOverrides, (eventName, callbackName) =>
        j.objectProperty(j.identifier(callbackName), j.stringLiteral(eventName))
      ),
      ...events
        .filter(({ name }) => !_.includes(eventNamesOverrides, name))
        .map(({ name }) =>
          j.objectProperty(
            j.identifier(_.camelCase(`on${_.capitalize(name)}`)),
            j.stringLiteral(name)
          )
        ),
    ]
  }

  function updaterMap() {
    return [
      ...methodAsProps.map(({ name, args, desc }) => {
        const [, prop] = name.match(/^set(\S+)/)

        return j.objectMethod(
          "method",
          j.identifier(_.lowerFirst(prop)),
          [j.identifier("instance"), j.identifier(_.lowerFirst(prop))],
          j.blockStatement([
            j.expressionStatement(
              j.callExpression(j.identifier(`instance.${name}`), [
                j.identifier(_.lowerFirst(prop)),
              ])
            ),
          ])
        )
      }),
    ]
  }
}
<commit_msg>chore(tx): add @public to instance methods<commit_after>import path from "path"
import { execSync } from "child_process"
import _ from "lodash"

function maybeTypeToPropType(maybeType) {
  switch (maybeType) {
    case "boolean":
      return "bool"
    case "number":
      return maybeType
    case "string":
      return maybeType
    default:
      return "any"
  }
}

export default function transformer(file, api) {
  const j = api.jscodeshift
  const wrap = j(file.source)

  const exportConfig = wrap.find(j.ExportNamedDeclaration).at(0)
  const configString = exportConfig.find(j.TemplateElement).get().node.value.raw
  const {
    prohibitedPropNames = [],
    eventMapOverrides,
    getInstanceFromComponent,
  } = JSON.parse(configString)
  exportConfig.remove()
  const eventNamesOverrides = _.values(eventMapOverrides)

  const KlassName = wrap
    .find(j.ClassDeclaration)
    .at(0)
    .get().node.id.name

  const result = execSync(
    `./node_modules/.bin/babel-node ${path.resolve(
      __dirname,
      `./ClassDefinition.js`
    )} "${KlassName}"`,
    {
      encoding: "utf-8",
    }
  )
  const { constructor, methods, events } = JSON.parse(result)
  const methodAsProps = methods.filter(({ name }) => {
    const matchResult = name.match(/^set(\S+)/)
    return (
      name !== "setMap" &&
      matchResult &&
      !_.includes(prohibitedPropNames, _.lowerFirst(matchResult[1]))
    )
  })

  const publicMethods = methods.filter(({ name }) => {
    const matchResult = name.match(/^get(\S+)/)
    return (
      !name.match(/Map$/) &&
      matchResult &&
      !_.includes(prohibitedPropNames, _.lowerFirst(matchResult[1]))
    )
  })

  wrap.find(j.ClassBody).forEach(path => {
    j(path).replaceWith(
      Object.assign(path.node.__clone(), {
        body: [...path.node.body, ...txClassMethods()],
      })
    )
  })

  wrap.find(j.ObjectExpression).forEach(path => {
    if (_.get(path, "parentPath.node.key.name") === "propTypes") {
      j(path).replaceWith(
        Object.assign(path.node.__clone(), {
          properties: [
            ...path.node.properties.filter(
              ({ key: { name } }) => name !== "__jscodeshiftPlaceholder__"
            ),
            ...txPropTypes(),
          ],
        })
      )
    } else if (_.get(path, "parentPath.node.id.name") === "eventMap") {
      j(path).replaceWith(
        Object.assign(path.node.__clone(), {
          properties: [...path.node.properties, ...eventMap()],
        })
      )
    } else if (_.get(path, "parentPath.node.id.name") === "updaterMap") {
      j(path).replaceWith(
        Object.assign(path.node.__clone(), {
          properties: [...path.node.properties, ...updaterMap()],
        })
      )
    }
  })

  return wrap.toSource()

  function txPropTypes() {
    return [
      ...methodAsProps.map(({ name, args, desc }) => {
        const [, prop] = name.match(/^set(\S+)/)
        const [, maybeType] = args.match(/\S+:(\S+)/)

        return Object.assign(
          j.objectProperty(
            j.identifier(`default${prop}`),
            j.identifier(`PropTypes.${maybeTypeToPropType(maybeType)}`)
          ),
          {
            comments: [j.commentBlock(`*\n * @type ${maybeType}\n `, true)],
          }
        )
      }),
      ...methodAsProps.map(({ name, args, desc }) => {
        const [, prop] = name.match(/^set(\S+)/)
        const [, maybeType] = args.match(/\S+:(\S+)/)

        return Object.assign(
          j.objectProperty(
            j.identifier(_.lowerFirst(prop)),
            j.identifier(`PropTypes.${maybeTypeToPropType(maybeType)}`)
          ),
          {
            comments: [j.commentBlock(`*\n * @type ${maybeType}\n `, true)],
          }
        )
      }),

      ..._.map(eventMapOverrides, (eventName, callbackName) =>
        Object.assign(
          j.objectProperty(
            j.identifier(callbackName),
            j.identifier(`PropTypes.func`)
          ),
          {
            comments: [j.commentBlock(`*\n * function\n `, true)],
          }
        )
      ),
      ...events
        .filter(({ name }) => !_.includes(eventNamesOverrides, name))
        .map(({ name }) =>
          Object.assign(
            j.objectProperty(
              j.identifier(_.camelCase(`on${_.capitalize(name)}`)),
              j.identifier(`PropTypes.func`)
            ),
            {
              comments: [j.commentBlock(`*\n * function\n `, true)],
            }
          )
        ),
    ]
  }

  function txClassMethods() {
    return [
      ...publicMethods.map(({ name, returns, returnsDesc }) => {
        return Object.assign(
          j.classMethod(
            "method",
            j.identifier(name),
            [],
            j.blockStatement([
              j.returnStatement(
                j.callExpression(
                  j.identifier(`${getInstanceFromComponent}.${name}`),
                  []
                )
              ),
            ])
          ),
          {
            comments: [
              j.commentBlock(
                `*\n * ${returnsDesc}\n * @type ${returns}\n * @public \n `,
                true
              ),
            ],
          }
        )
      }),
    ]
  }

  function eventMap() {
    return [
      ..._.map(eventMapOverrides, (eventName, callbackName) =>
        j.objectProperty(j.identifier(callbackName), j.stringLiteral(eventName))
      ),
      ...events
        .filter(({ name }) => !_.includes(eventNamesOverrides, name))
        .map(({ name }) =>
          j.objectProperty(
            j.identifier(_.camelCase(`on${_.capitalize(name)}`)),
            j.stringLiteral(name)
          )
        ),
    ]
  }

  function updaterMap() {
    return [
      ...methodAsProps.map(({ name, args, desc }) => {
        const [, prop] = name.match(/^set(\S+)/)

        return j.objectMethod(
          "method",
          j.identifier(_.lowerFirst(prop)),
          [j.identifier("instance"), j.identifier(_.lowerFirst(prop))],
          j.blockStatement([
            j.expressionStatement(
              j.callExpression(j.identifier(`instance.${name}`), [
                j.identifier(_.lowerFirst(prop)),
              ])
            ),
          ])
        )
      }),
    ]
  }
}
<|endoftext|>


<commit_before>var $ = require('../../node_modules/jquery/dist/jquery.min');

var viewEvent = require('./viewEvent');

// publiic function
var initEvents = function( parent, eventsUser ){
    openCloseDropdownEvent( parent );
    closeTagsMenuListEvent( parent, eventsUser );
    closeTagsListEvent( parent, eventsUser );
    addTagsListActiveEvent( parent, eventsUser );
    editTagsDropdownEvent( parent );
    closeEditDropdownEvent( parent );
    updateValueTagEvent( parent, eventsUser );
    changeColorTagEvent( parent, eventsUser );
    addInputTagKeyEvent( parent, eventsUser );
}

// private function
function openCloseDropdownEvent( parent ){

    // open event dropdown tag
    var liButtonAddTag = $( parent ).find('.tagProjectButtonAdd');
    $( liButtonAddTag ).click(function(e) {
        var dropdown = $(liButtonAddTag).find( $('.tagProjectDropdown') )[0];
        $(dropdown).addClass("active");
        e.stopPropagation();
    });

    // close event dropdown tag
    $(document).click(function (e) {
        e.stopPropagation();
        var dropdown = $(liButtonAddTag).find( $('.tagProjectDropdown') )[0];

        //check if the clicked area is dropdown or not
        if ( $(dropdown).has(e.target).length === 0 ) {
            $(dropdown).removeClass('active');
        }
    })

}

function closeEditDropdownEvent( parent ){

    // close event dropdown tag
    $(document).click(function (e) {
        e.stopPropagation();
        var editDropdown = $( parent ).find('.tagProjectEditTagDropdown');

        //check if the clicked area is dropdown or not
        if ( $(editDropdown).has(e.target).length === 0 ) {
            $(editDropdown).removeClass('active');
        }
    })

}

function closeTagsMenuListEvent( parent, eventsUser ){
    $( parent ).find('.tagProjectDropdown li').map(
        function (pos, el){
            viewEvent.closeSingleTagMenuEvent(el, eventsUser);
        }
    );
}

function closeTagsListEvent( parent, eventsUser ){
    $( parent ).children().first().children().map(
        function (pos, el){
            if ( pos + 1 < $( parent ).children().first().children().length - 1){
                viewEvent.closeSingleTagListEvent(parent, el, eventsUser);
            }
        }
    );
}

function addTagsListActiveEvent( parent, eventsUser ){
    $( parent ).find('.tagProjectDropdown li').map(
         function (pos, el){
            viewEvent.addSingleTagListActiveEvent(parent, el, eventsUser);
        }
    );
}

function editTagsDropdownEvent( parent ){
    $(parent).children().first().children().map(
        function(pos, el){
            if ( pos + 1 < $( parent ).children().first().children().length - 1){
                viewEvent.editSingleTagEditDropdownEvent( el );
            }
        }
    );
}

function updateValueTagEvent( parent, eventsUser ){
    $( parent ).find('.tagProjectEditInput').keyup(function(e){
        if(e.keyCode == 13)
        {
            //$(parent).find('.selected').first().text( e.target.value );
            $(parent).find('.selected')[0].childNodes[0].nodeValue =  e.target.value;
            $(document).trigger( "click" );
            setTimeout( x => {
            if ( eventsUser && eventsUser.events && eventsUser.events.editTagActiveListEvent )
                eventsUser.events.editTagActiveListEvent({value: 'editTagActiveListEvent'});
            }, 200);
        }
    });
}

function changeColorTagEvent( parent, eventsUser ){
    $(parent).find('.tagProjectContent li').map(
        function(pos, el){
            $(el).click(
                function (e){
                    $(parent).find('.selected').removeAttr( 'style' ).attr('class', $(e.currentTarget).attr("class") + ' selected' );
                    $(document).trigger("click");
                    setTimeout( x => {
                    if ( eventsUser && eventsUser.events && eventsUser.events.editTagActiveListEvent )
                        eventsUser.events.editTagActiveListEvent({value: 'editTagActiveListEvent'});
                    }, 200);
                }
            );
        }
    );
}

function addInputTagKeyEvent ( parent, eventsUser ){
    $(parent).find(".tagProjectDropdown" ).children().first().keyup(function (e){
                                                                                if (e.keyCode === 13) {
                                                                                viewEvent.addTagMenuList(parent, {value: e.target.value }, eventsUser);
                                                                                e.target.value = '';
                                                                                }
                                                                                });;
}

module.exports = {
            initEvents: initEvents,
}<commit_msg>0.4.0<commit_after>var $ = require('../../node_modules/jquery/dist/jquery.min');

var viewEvent = require('./viewEvent');

// publiic function
var initEvents = function( parent, eventsUser ){
    openCloseDropdownEvent( parent );
    closeTagsMenuListEvent( parent, eventsUser );
    closeTagsListEvent( parent, eventsUser );
    addTagsListActiveEvent( parent, eventsUser );
    editTagsDropdownEvent( parent );
    closeEditDropdownEvent( parent );
    updateValueTagEvent( parent, eventsUser );
    changeColorTagEvent( parent, eventsUser );
    addInputTagKeyEvent( parent, eventsUser );
}

// private function
function openCloseDropdownEvent( parent ){

    // open event dropdown tag
    var liButtonAddTag = $( parent ).find('.tagProjectButtonAdd');
    $( liButtonAddTag ).click(function(e) {
        var dropdown = $(liButtonAddTag).find( $('.tagProjectDropdown') )[0];
        $(dropdown).addClass("active");
        e.stopPropagation();
    });

    // close event dropdown tag
    $(document).click(function (e) {
        e.stopPropagation();
        var dropdown = $(liButtonAddTag).find( $('.tagProjectDropdown') )[0];

        //check if the clicked area is dropdown or not
        if ( $(dropdown).has(e.target).length === 0 ) {
            $(dropdown).removeClass('active');
        }
    })

}

function closeEditDropdownEvent( parent ){

    // close event dropdown tag
    $(document).click(function (e) {
        e.stopPropagation();
        var editDropdown = $( parent ).find('.tagProjectEditTagDropdown');

        //check if the clicked area is dropdown or not
        if ( $(editDropdown).has(e.target).length === 0 ) {
            $(editDropdown).removeClass('active');
        }
    })

}

function closeTagsMenuListEvent( parent, eventsUser ){
    $( parent ).find('.tagProjectDropdown li').map(
        function (pos, el){
            viewEvent.closeSingleTagMenuEvent(el, eventsUser);
        }
    );
}

function closeTagsListEvent( parent, eventsUser ){
    $( parent ).children().first().children().map(
        function (pos, el){
            if ( pos + 1 < $( parent ).children().first().children().length - 1){
                viewEvent.closeSingleTagListEvent(parent, el, eventsUser);
            }
        }
    );
}

function addTagsListActiveEvent( parent, eventsUser ){
    $( parent ).find('.tagProjectDropdown li').map(
         function (pos, el){
            viewEvent.addSingleTagListActiveEvent(parent, el, eventsUser);
        }
    );
}

function editTagsDropdownEvent( parent ){
    $(parent).children().first().children().map(
        function(pos, el){
            if ( pos + 1 < $( parent ).children().first().children().length - 1){
                viewEvent.editSingleTagEditDropdownEvent( el );
            }
        }
    );
}

function updateValueTagEvent( parent, eventsUser ){
    $( parent ).find('.tagProjectEditInput').keyup(function(e){
        if(e.keyCode == 13)
        {
            //$(parent).find('.selected').first().text( e.target.value );
            $(parent).find('.selected')[0].childNodes[0].nodeValue =  e.target.value;
            $(document).trigger( "click" );
            setTimeout( x => {
            if ( eventsUser && eventsUser.events && eventsUser.events.editTagActiveListEvent )
                eventsUser.events.editTagActiveListEvent({value: 'editTagActiveListEvent'});
            }, 200);
        }
    });
}

function changeColorTagEvent( parent, eventsUser ){
    $(parent).find('.tagProjectContent li').map(
        function(pos, el){
            $(el).click(
                function (e){
                    $(parent).find('.selected').removeAttr( 'style' ).attr('class', $(e.currentTarget).attr("class") + ' selected' );
                    $(document).trigger("click");
                    setTimeout( x => {
                    if ( eventsUser && eventsUser.events && eventsUser.events.editTagActiveListEvent )
                        eventsUser.events.editTagActiveListEvent({value: 'editTagActiveListEvent'});
                    }, 200);
                }
            );
        }
    );
}

function addInputTagKeyEvent ( parent, eventsUser ){
    $(parent).find(".tagProjectDropdown" ).children().first().keyup(function (e){
                                                                                if (e.keyCode === 13) {
                                                                                viewEvent.addTagMenuList(parent, {value: e.target.value }, eventsUser);
                                                                                e.target.value = '';
                                                                                }
                                                                                });;
}

module.exports = {
            initEvents: initEvents,
}<|endoftext|>


<commit_before>import glob from "glob";
import path from "path";
import yaml from "yaml";
import * as status from "../utils/status";

/**
 * Finds where the manifest file actually exists and loads it into
 * our context.
 *
 * @param  {Object} ctx
 * @param  {Callback<Error>} next
 */
export default function (ctx, next) {
  status.report("Searching for the manifest file");
  var tempDir = ctx.paths.temp;
  var manifestName = ctx.manifestName;
  var pattern = path.join(tempDir, `**/${manifestName}.{js,json,yml,yaml}`);
  glob(pattern, {}, function (err, files) {
    try {
      if (err) throw err;
      if (files.length === 0) {
        throw new Error("A valid manifest file could be not found.  Are you sure this is a Helpful CLI compliant template?");
      }

      var manifestPath = files[0];
      ctx.paths.template = path.resolve(path.dirname(manifestPath));
      if (path.extname(manifestPath).indexOf(".y") === 0) {
        ctx.manifest = yaml.load(manifestPath);
      } else {
        ctx.manifest = require(manifestPath);
      }
    } catch (e) {
      status.fail();
      return next(e);
    }

    status.complete();
    next();
  });
}<commit_msg>Fixed bug with wrong module being loaded for yaml<commit_after>import glob from "glob";
import path from "path";
import yaml from "yamljs";
import * as status from "../utils/status";

/**
 * Finds where the manifest file actually exists and loads it into
 * our context.
 *
 * @param  {Object} ctx
 * @param  {Callback<Error>} next
 */
export default function (ctx, next) {
  status.report("Searching for the manifest file");
  var tempDir = ctx.paths.temp;
  var manifestName = ctx.manifestName;
  var pattern = path.join(tempDir, `**/${manifestName}.{js,json,yml,yaml}`);
  glob(pattern, {}, function (err, files) {
    try {
      if (err) throw err;
      if (files.length === 0) {
        throw new Error("A valid manifest file could be not found.  Are you sure this is a Helpful CLI compliant template?");
      }

      var manifestPath = files[0];
      ctx.paths.template = path.resolve(path.dirname(manifestPath));
      if (path.extname(manifestPath).indexOf(".y") === 0) {
        ctx.manifest = yaml.load(manifestPath);
      } else {
        ctx.manifest = require(manifestPath);
      }
    } catch (e) {
      status.fail();
      return next(e);
    }

    status.complete();
    next();
  });
}<|endoftext|>


<commit_before>var httpRequest

function changeStatus(id_num) {
  httpRequest = new XMLHttpRequest();
  var st = document.getElementById(id_num).value;
  httpRequest.onreadystatechange = function() {
    if (alertContents() == true) {
      moveNode(st, id_num)
    }
  };
  httpRequest.open('POST', '/update-status', true);
  httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  httpRequest.send("id_num="+id_num+"&status="+st);
};

function alertContents() {
  if (httpRequest.readyState == 4) {
    if (httpRequest.status === 200) {
      return true
    } else {
      alert('There was a problem with the request.');
      return false
    }
  }
};

function moveNode(new_st, id_num) {
  // get
 to move
  var old_node = document.getElementById(id_num).parentNode
  if (new_st == "NEVER" || new_st == "REJECTED") {
    old_node.parentNode.removeChild(old_node)
  }
  else {
    // get new parent and existing <select> node
    var new_par = document.getElementById(new_st)
    var sel = old_node.getElementsByTagName("select")[0];
    // remove each existing <option> in the <select>
    var num_opts = sel.children.length;
    var i;
    for (i = 0; i<num_opts; i++) {
        sel.removeChild(sel.firstChild);
    }
    // get new <options>
    getOptions(id_num, new_st)
    // insert
 into new

    if (httpRequest.responseText != false) {
      new_par.insertBefore(old_node, document.getElementById(httpRequest.responseText));
    } else {
      new_par.appendChild(old_node);
    };
  };
};

function getOptions(sel_id, status) {
  var sel = document.getElementById(sel_id);
  switch(status) {
    case "NEW":
      new_opts = ["NEVER", "LATER", "INTERESTED"];
      break;
    case "INTERESTED":
      new_opts = ["NEVER", "LATER", "APPLIED"];
      break;
    case "APPLIED":
      new_opts = ["INTERVIEW", "REJECTED"];
      break;
    case "INTERVIEW":
      new_opts = ["OFFER", "REJECTED"];
      break;
    case "OFFER":
      new_opts = ["ACCEPT?"];
      break;
    case "LATER":
      new_opts = ["NEVER", "INTERESTED"];
      break;
  }

  for (x in new_opts) {
    var new_opt = document.createElement("option");
    new_opt.value = new_opts[x];
    new_opt.selected = "selected";
    new_opt.appendChild(document.createTextNode(new_opts[x]))
    sel.insertBefore(new_opt, sel.firstChild)
  };
}
<commit_msg>switched the order for APPLIED and INTERVIEW<commit_after>var httpRequest

function changeStatus(id_num) {
  httpRequest = new XMLHttpRequest();
  var st = document.getElementById(id_num).value;
  httpRequest.onreadystatechange = function() {
    if (alertContents() == true) {
      moveNode(st, id_num)
    }
  };
  httpRequest.open('POST', '/update-status', true);
  httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  httpRequest.send("id_num="+id_num+"&status="+st);
};

function alertContents() {
  if (httpRequest.readyState == 4) {
    if (httpRequest.status === 200) {
      return true
    } else {
      alert('There was a problem with the request.');
      return false
    }
  }
};

function moveNode(new_st, id_num) {
  // get
 to move
  var old_node = document.getElementById(id_num).parentNode
  if (new_st == "NEVER" || new_st == "REJECTED") {
    old_node.parentNode.removeChild(old_node)
  }
  else {
    // get new parent and existing <select> node
    var new_par = document.getElementById(new_st)
    var sel = old_node.getElementsByTagName("select")[0];
    // remove each existing <option> in the <select>
    var num_opts = sel.children.length;
    var i;
    for (i = 0; i<num_opts; i++) {
        sel.removeChild(sel.firstChild);
    }
    // get new <options>
    getOptions(id_num, new_st)
    // insert
 into new

    if (httpRequest.responseText != false) {
      new_par.insertBefore(old_node, document.getElementById(httpRequest.responseText));
    } else {
      new_par.appendChild(old_node);
    };
  };
};

function getOptions(sel_id, status) {
  var sel = document.getElementById(sel_id);
  switch(status) {
    case "NEW":
      new_opts = ["NEVER", "LATER", "INTERESTED"];
      break;
    case "INTERESTED":
      new_opts = ["NEVER", "LATER", "APPLIED"];
      break;
    case "APPLIED":
      new_opts = ["REJECTED", "INTERVIEW"];
      break;
    case "INTERVIEW":
      new_opts = ["REJECTED", "OFFER"];
      break;
    case "OFFER":
      new_opts = ["ACCEPT?"];
      break;
    case "LATER":
      new_opts = ["NEVER", "INTERESTED"];
      break;
  }

  for (x in new_opts) {
    var new_opt = document.createElement("option");
    new_opt.value = new_opts[x];
    new_opt.selected = "selected";
    new_opt.appendChild(document.createTextNode(new_opts[x]))
    sel.insertBefore(new_opt, sel.firstChild)
  };
}
<|endoftext|>


<commit_before>Meteor.startup(function() {
    let lightState = new LightState("rescue-time",3000);
    Meteor.setInterval(function(){
        try {
            const settings = PluginSettings.findOne("rescueTime");
            if(!settings || !settings.key) return;
            if(!settings.enabled){
                lightState.clearState(settings.light);
                return;
            }
            const reqString = "https://www.rescuetime.com/anapi/data?key="+settings.key+"&perspective=interval&rs=day&restrict_kind=efficiency&format=json";
            const data = HTTP.get(reqString);
            const prodPercent = data.data.rows[0][4];
            const color = tinycolor.mix("#F00", "#00F", prodPercent);
            const {r,g,b} = color.toRgb();
            lightState.setLight(settings.light, {rgb: {r, g, b}});
        }
        catch(e){
            console.log(e);
            // nada
        }
    }, 15000);
});<commit_msg>rescue time logging<commit_after>let log = new BolideLog({category: "plugin", module:"rescuetime"});
Meteor.startup(function() {
    log.info("Started");
    let lightState = new LightState("rescue-time",3000);
    Meteor.setInterval(function(){
        try {
            const settings = PluginSettings.findOne("rescueTime");
            if(!settings || !settings.key) return;
            if(!settings.enabled){
                lightState.clearState(settings.light);
                return;
            }
            const reqString = "https://www.rescuetime.com/anapi/data?key="+settings.key+"&perspective=interval&rs=day&restrict_kind=efficiency&format=json";
            const data = HTTP.get(reqString);
            const prodPercent = data.data.rows[0][4];
            const color = tinycolor.mix("#F00", "#00F", prodPercent);
            log.info(`Productivity ${prodPercent*100} resulting in ${color.toRgbString()}`);
            const {r,g,b} = color.toRgb();
            lightState.setLight(settings.light, {rgb: {r, g, b}});
        }
        catch(e){
            log.info(`Error ${e.ToString()}`);

        }
    }, 15000);
});<|endoftext|>


<commit_before>
import React from 'react';
import PropTypes from 'prop-types';
import { messageActions } from '../../actions';
import {Pagination} from 'react-bootstrap';
import {
    Card,
    CardText,
    RaisedButton,
    CardTitle,
    CardActions,
    Table,
    TableBody,
    TableHeader
} from 'material-ui';
import CrudSearch from './CrudSearch';

class Crud extends React.Component
{
    constructor(props)
    {
        super(props);

        this.handleConsultar = this.handleConsultar.bind(this);
        this.handleAdicionar = this.handleAdicionar.bind(this);

        this.resource = `${window.App.basePath}/app/${this.props.resource}`;
        this.state = {
            itens: [],
            form: false,
            obj: null
        };

        this.consulta = {
            page: 1,
            rows: 10,
            total: 1,
            info: '',
            filtros: (this.props.filtros || {}),
            sidx: this.props.sidx,
            sord: this.props.sord
        };
    }

    componentWillReceiveProps(nextProps)
    {
        if (this.consulta.sidx != nextProps.sidx || this.consulta.sord != nextProps.sord) {
            this.consulta.sidx = nextProps.sidx;
            this.consulta.sord = nextProps.sord;
            this.consultar(this.consulta.page);
        }
    }

    consultar(page)
    {
//        this.consulta.page = page;
//
//        this.consulta.info = 'pagina 1 de 1';
//        this.consulta.page = 1;
//        this.consulta.total = 10;
//        this.setState({itens: this.state.itens});

        App.fetch.getJson(this.resource + '/consultar', {
            body: JSON.stringify(this.consulta),
            method: "POST"
        }).then((resp) => {

            var inicio = 0,
                info = '',
                fim = 0;

            if (resp.rows.length) {
                inicio = ((resp.page - 1) * 10) + 1;
                fim = inicio + resp.rows.length - 1;
            }

            var info = 'Mostrando ' + inicio + ' até ' + fim + ' de ' + resp.records + ' registros';

            this.consulta.info = info;
            this.consulta.page = resp.page;
            this.consulta.total = resp.total;
            this.setState({itens: resp.rows});
        });
    }

    remover(id)
    {
        this.props.onClear && this.props.onClear();
        var itens = this.state.itens;
        delete itens[id];
        this.setState({itens: itens});

        return;

        App.fetch.getJson(this.resource + '/excluir/' + id).then((data) => {
            if (data.type === "success") {
                this.consultar();
                this.props.onClear && this.props.onClear();
                this.context.store.dispatch(messageActions.showNotify(data.msg));
                return;
            }
            this.consulta.setState({bloqueado: false});
            if (!data.exception) {
                this.context.store.dispatch(messageActions.showNotify(data.msg));
                return;
            }

            this.context.store.dispatch(messageActions.showError(data.msg, data.exception));
        });
    }

    handleConsultar()
    {
        this.consultar(this.consulta.page);
    }

    onPageChange(page)
    {
        this.consultar(page);
    }

    handleAdicionar()
    {
        this.setState({form: true, obj: {}});
    }

    handleCancelar()
    {
        this.props.onClear && this.props.onClear();
        this.setState({form: false, obj: null});
    }

    onSearch(filtros)
    {
        this.consulta.filtros = filtros;
        this.consultar(this.consulta.page);
    }

    render()
    {
        if (this.state.form) {
            const formulario = this.props.renderFormulario && this.props.renderFormulario(this.state.obj);

            if (this.props.onlyClose) {
                return (
                    <Card style={{ margin: '2em'}}>
                        {this.props.title && <CardTitle title={this.props.title}/>}
                        <CardText>{formulario}</CardText>
                        <CardActions style={{  textAlign: 'right' }}>
                            <RaisedButton
                                label="Fechar"
                                secondary={true}
                                onTouchTap={this.handleCancelar.bind(this)}
                                disabled={this.state.bloqueado}
                            />
                        </CardActions>
                    </Card>
                );
            }

            return (
                <Card style={{ margin: '2em'}}>
                    {this.props.title && <CardTitle title={this.props.title}/>}
                    <form ref="form" onSubmit={this.props.onSubmit}>
                        <CardText>{formulario}</CardText>
                        <CardActions style={{  textAlign: 'right' }}>
                            <RaisedButton
                                label="Cancelar"
                                secondary={true}
                                onTouchTap={this.handleCancelar.bind(this)}
                                disabled={this.state.bloqueado}
                            />
                            <RaisedButton label="Salvar" primary={true} type="submit" disabled={this.state.bloqueado}/>
                        </CardActions>
                    </form>
                </Card>
            );
        }

        var itens = this.props.renderItens(this.state.itens);
        return (
            <Card style={{ margin: '2em'}}>
                <CrudSearch
                    title={this.props.title}
                    campos={this.props.campos}
                    filtros={this.consulta.filtros}
                    filters={this.props.filters}
                    onSearch={this.onSearch.bind(this)}
                    handleConsultar={this.handleConsultar}
                    handleAdicionar={this.handleAdicionar}
                />

 { this.table = elm; }} wrapperStyle={{'width': '100%'}}>
                    {this.props.tableHeader}
                    <TableBody displayRowCheckbox={false}>{itens}</TableBody>

                    <Pagination
                        prev next first last ellipsis boundaryLinks
                        maxButtons={5}
                        items={this.consulta.total}
                        activePage={this.consulta.page}
                        onSelect={this.onPageChange.bind(this)} />

                    {this.consulta.info}

            </Card>
        );
    }
};

Crud.propTypes = {
    resource: PropTypes.string.isRequired,
    renderItens: PropTypes.func.isRequired,
    formulario: PropTypes.func,
    onSubmit: PropTypes.func.isRequired,
    campos: PropTypes.array,
    tableHeader: PropTypes.object
};

Crud.defaultProps = {

};

Crud.contextTypes = {
    router: React.PropTypes.object.isRequired,
    store: React.PropTypes.object.isRequired
};

export default Crud;
<commit_msg>Posição paginação<commit_after>
import React from 'react';
import PropTypes from 'prop-types';
import { messageActions } from '../../actions';
import {Pagination} from 'react-bootstrap';
import {
    Card,
    CardText,
    RaisedButton,
    CardTitle,
    CardActions,
    Table,
    TableBody,
    TableHeader
} from 'material-ui';
import CrudSearch from './CrudSearch';

class Crud extends React.Component
{
    constructor(props)
    {
        super(props);

        this.handleConsultar = this.handleConsultar.bind(this);
        this.handleAdicionar = this.handleAdicionar.bind(this);

        this.resource = `${window.App.basePath}/app/${this.props.resource}`;
        this.state = {
            itens: [],
            form: false,
            obj: null
        };

        this.consulta = {
            page: 1,
            rows: 10,
            total: 1,
            info: '',
            filtros: (this.props.filtros || {}),
            sidx: this.props.sidx,
            sord: this.props.sord
        };
    }

    componentWillReceiveProps(nextProps)
    {
        if (this.consulta.sidx != nextProps.sidx || this.consulta.sord != nextProps.sord) {
            this.consulta.sidx = nextProps.sidx;
            this.consulta.sord = nextProps.sord;
            this.consultar(this.consulta.page);
        }
    }

    consultar(page)
    {
//        this.consulta.page = page;
//
//        this.consulta.info = 'pagina 1 de 1';
//        this.consulta.page = 1;
//        this.consulta.total = 10;
//        this.setState({itens: this.state.itens});

        App.fetch.getJson(this.resource + '/consultar', {
            body: JSON.stringify(this.consulta),
            method: "POST"
        }).then((resp) => {

            var inicio = 0,
                info = '',
                fim = 0;

            if (resp.rows.length) {
                inicio = ((resp.page - 1) * 10) + 1;
                fim = inicio + resp.rows.length - 1;
            }

            var info = 'Mostrando ' + inicio + ' até ' + fim + ' de ' + resp.records + ' registros';

            this.consulta.info = info;
            this.consulta.page = resp.page;
            this.consulta.total = resp.total;
            this.setState({itens: resp.rows});
        });
    }

    remover(id)
    {
        this.props.onClear && this.props.onClear();
        var itens = this.state.itens;
        delete itens[id];
        this.setState({itens: itens});

        return;

        App.fetch.getJson(this.resource + '/excluir/' + id).then((data) => {
            if (data.type === "success") {
                this.consultar();
                this.props.onClear && this.props.onClear();
                this.context.store.dispatch(messageActions.showNotify(data.msg));
                return;
            }
            this.consulta.setState({bloqueado: false});
            if (!data.exception) {
                this.context.store.dispatch(messageActions.showNotify(data.msg));
                return;
            }

            this.context.store.dispatch(messageActions.showError(data.msg, data.exception));
        });
    }

    handleConsultar()
    {
        this.consultar(this.consulta.page);
    }

    onPageChange(page)
    {
        this.consultar(page);
    }

    handleAdicionar()
    {
        this.setState({form: true, obj: {}});
    }

    handleCancelar()
    {
        this.props.onClear && this.props.onClear();
        this.setState({form: false, obj: null});
    }

    onSearch(filtros)
    {
        this.consulta.filtros = filtros;
        this.consultar(this.consulta.page);
    }

    render()
    {
        if (this.state.form) {
            const formulario = this.props.renderFormulario && this.props.renderFormulario(this.state.obj);

            if (this.props.onlyClose) {
                return (
                    <Card style={{ margin: '2em'}}>
                        {this.props.title && <CardTitle title={this.props.title}/>}
                        <CardText>{formulario}</CardText>
                        <CardActions style={{  textAlign: 'right' }}>
                            <RaisedButton
                                label="Fechar"
                                secondary={true}
                                onTouchTap={this.handleCancelar.bind(this)}
                                disabled={this.state.bloqueado}
                            />
                        </CardActions>
                    </Card>
                );
            }

            return (
                <Card style={{ margin: '2em'}}>
                    {this.props.title && <CardTitle title={this.props.title}/>}
                    <form ref="form" onSubmit={this.props.onSubmit}>
                        <CardText>{formulario}</CardText>
                        <CardActions style={{  textAlign: 'right' }}>
                            <RaisedButton
                                label="Cancelar"
                                secondary={true}
                                onTouchTap={this.handleCancelar.bind(this)}
                                disabled={this.state.bloqueado}
                            />
                            <RaisedButton label="Salvar" primary={true} type="submit" disabled={this.state.bloqueado}/>
                        </CardActions>
                    </form>
                </Card>
            );
        }

        var itens = this.props.renderItens(this.state.itens);
        return (
            <Card style={{ margin: '2em'}}>
                <CrudSearch
                    title={this.props.title}
                    campos={this.props.campos}
                    filtros={this.consulta.filtros}
                    filters={this.props.filters}
                    onSearch={this.onSearch.bind(this)}
                    handleConsultar={this.handleConsultar}
                    handleAdicionar={this.handleAdicionar}
                />

 { this.table = elm; }} wrapperStyle={{'width': '100%'}}>
                    {this.props.tableHeader}
                    <TableBody displayRowCheckbox={false}>{itens}</TableBody>

                    <Pagination
                        prev next first last ellipsis boundaryLinks
                        maxButtons={5}
                        items={this.consulta.total}
                        activePage={this.consulta.page}
                        onSelect={this.onPageChange.bind(this)} />

                    {this.consulta.info}

            </Card>
        );
    }
};

Crud.propTypes = {
    resource: PropTypes.string.isRequired,
    renderItens: PropTypes.func.isRequired,
    formulario: PropTypes.func,
    onSubmit: PropTypes.func.isRequired,
    campos: PropTypes.array,
    tableHeader: PropTypes.object
};

Crud.defaultProps = {

};

Crud.contextTypes = {
    router: React.PropTypes.object.isRequired,
    store: React.PropTypes.object.isRequired
};

export default Crud;
<|endoftext|>


<commit_before>export default class System {
  constructor() {
    this.layers = [];
  }

  update(game) {
    this.layers.forEach(layer => {
      if (!!layer) {
        for (var k in layer) {
          if (layer.hasOwnProperty(k)) {
            layer[k].update(game);
          }
        }
        // Object.values(layer).forEach(entity => {
        //   entity.update(game);
        // })
      }
    })
  }

  register(layer, id, entity) {
    if (!!!this.layers[layer]) {
      this.layers[layer] = {}
    }
    if (entity.create) {
      entity.crate();
    }
    this.layers[layer][id] = entity;
  }

  remove(layer, id) {
    delete(this.layers[layer][id]);
  }

  get(layer, id) {
    return this.layers[layer][id];
  }
}
<commit_msg>pass reference to System to Entitiy.update<commit_after>export default class System {
  constructor() {
    this.layers = [];
  }

  update(game) {
    let that = this;
    this.layers.forEach(layer => {
      if (!!layer) {
        for (var k in layer) {
          if (layer.hasOwnProperty(k)) {
            layer[k].update(game, that);
          }
        }
        // Object.values(layer).forEach(entity => {
        //   entity.update(game);
        // })
      }
    })
  }

  register(layer, id, entity) {
    if (!!!this.layers[layer]) {
      this.layers[layer] = {}
    }
    if (entity.create) {
      entity.crate();
    }
    this.layers[layer][id] = entity;
  }

  remove(layer, id) {
    delete(this.layers[layer][id]);
  }

  get(layer, id) {
    return this.layers[layer][id];
  }
}
<|endoftext|>


<commit_before>var alg_size;
var alg_data = new Array();     // Raw alg_data from JSON
var alg_request = new XMLHttpRequest();
var alg_matrix = new Array();   // Main money alg_matrix
var alg_mapping = new Array();  // Key for "alg_matrix" array
var alg_numpayto;   // Number of people to be paid
var alg_numpayer;   // Number of payers
var starttotal=0;   // Number of dollars in transfer before algorithm
var endtotal=0; // Number of dollars in transfer after algorithm
var alg_changed = true;

function init(trans)
{

    alg_data = trans;
    checkSize();
    createMatrix();
    checkMatrix();
    algorithm();
    checkMatrix();
    return sendResults();
}

function checkSize()    // Calculates required alg_size for "alg_matrix" array
{
    for(var i = 0; i<alg_data.length; i++)
    {

        var duplicate = false;
        for (var j = 0; j<alg_mapping.length; j++)
        {
            var strpayer = alg_data[i]["payer"];
            var strtest = alg_mapping[j];

            if(strpayer == strtest)
            {
                duplicate = true;
            }
        }
        if(duplicate == false)
        {
            var name = alg_data[i]["payer"];
            alg_mapping[alg_mapping.length] = name;
        }

    }

    for(var i = 0; i<alg_data.length; i++)
    {

        var duplicate = false;
        for (var j = 0; j<alg_mapping.length; j++)
        {
            var strpayto = alg_data[i]["payee"];
            var strtest = alg_mapping[j];

            if(strpayto == strtest)
            {
                duplicate = true;
            }
        }
        if(duplicate == false)
        {
            var name = alg_data[i]["payee"];
            alg_mapping[alg_mapping.length] = name;
        }
    }
    alg_size = alg_mapping.length;
}

function createMatrix() // Creates and fills the "alg_matrix" array
{
    alg_matrix = new Array(alg_size);
    for(var i = 0; i<alg_size; i++)
    {
        alg_matrix[i] = new Array(alg_size);
    }
    for(var i = 0; i<alg_size;i++)
    {
        for(var j = 0; j<alg_size; j++)
        {
            alg_matrix[i][j] = 0.00;
        }
    }

    for(var i = 0; i<alg_data.length; i++)
    {
        var payer = alg_data[i]["payee"];
        var amount = alg_data[i]["amount"];
        var payto = alg_data[i]["payer"];
        var payermap;
        var paytomap;

        for(var j=0; j<alg_mapping.length;j++)
        {
            if(payer == alg_mapping[j])
            {
                payermap = j;
            }
            if(payto == alg_mapping[j])
            {
                paytomap = j;
            }
        }

        alg_matrix[payermap][paytomap] += amount;
        alg_matrix[payermap][paytomap] = Math.round(alg_matrix[payermap][paytomap]*100)/100;
    }

    for(var i = 0; i<alg_size; i++)
    {
        for(var j = 0; j<alg_size; j++)
        {
            starttotal += alg_matrix[i][j];
        }
    }

}

function algorithm()    // The Algorithm. Simplifies the debts.
{
    alg_changed = true;
    while (alg_changed == true)
    {
        alg_changed = false;
        var x;
        var y;
        var z;
        var xamount;
        var yamount;
        for(var i = 0; i<alg_size; i++)
        {
            for(var j = 0; j<alg_size; j++)
            {

                x = i;
                y = j;
                for(var k =  0; k<alg_size; k++)
                {
                    var action = false;
                    xamount = alg_matrix[i][j];
                    // Bidirectional - Debt between 2 people
                    if(alg_matrix[i][j] != 0 && alg_matrix[j][i] !=0)
                    {
                        if(alg_matrix[i][j] > alg_matrix[j][i])
                        {
                            var a = alg_matrix[i][j]
                                var b = alg_matrix[j][i]
                                alg_matrix[i][j] = a-b;
                            alg_matrix[j][i] = 0
                                alg_changed = true;
                            action = true;
                        }
                        else if(alg_matrix[i][j] > alg_matrix[j][i])
                        {
                            var a = alg_matrix[i][j]
                                var b = alg_matrix[j][i]
                                alg_matrix[i][j] = 0;
                            alg_matrix[j][i] = b-a;
                            alg_changed = true;
                            action = true;
                        }
                        else if(alg_matrix[i][j] == alg_matrix[j][i])
                        {
                            alg_matrix[i][j] = 0;
                            alg_matrix[j][i] = 0;
                            alg_changed = true;
                            action = true;
                        }
                    }
                    yamount = alg_matrix[j][k];
                    // Person A can exactly pay Person B's debt
                    if(xamount == yamount && xamount != 0 && yamount != 0 && x !=k)
                    {
                        alg_matrix[j][k] = 0
                        alg_matrix[i][k] += xamount;
                        alg_matrix[i][j] = 0;
                        alg_changed = true;
                        action = true;
                    }
                    // Person A pays part of Person B's debt to Person C
                    else if(xamount < yamount && xamount != 0 && yamount!= 0 && x!=k)
                    {
                        alg_matrix[i][k] += xamount;
                        alg_matrix[j][k] = yamount-xamount;
                        alg_matrix[i][j] = 0;
                        alg_changed = true;
                        action = true;
                    }
                    // Person A pays all of Person B's debt to Person C and pays Person B
                    else if(xamount > yamount && xamount != 0 & yamount != 0 && x!=k)
                    {
                        alg_matrix[i][k] += yamount;
                        alg_matrix[j][k] = 0;
                        alg_matrix[i][j] = xamount - yamount;
                        alg_changed = true;
                        action = true;
                    }

                    if(action == true)
                    {
                        checkMatrix();
                    }

                    alg_matrix[i][j] = Math.round(alg_matrix[i][j]*100)/100;
                    alg_matrix[i][k] = Math.round(alg_matrix[i][k]*100)/100;
                    alg_matrix[j][i] = Math.round(alg_matrix[j][i]*100)/100;
                    alg_matrix[j][k] = Math.round(alg_matrix[j][k]*100)/100;
                    alg_matrix[k][j] = Math.round(alg_matrix[k][j]*100)/100;
                    alg_matrix[k][i] = Math.round(alg_matrix[k][i]*100)/100;
                }
            }
        }
    }
}

function checkMatrix()  // Prints out visual representation of "alg_matrix" and key in console
{
    //console.log(alg_mapping);
    for(var i = 0; i<alg_size; i++)
    {
        var printout="";
        for(var j=0; j<alg_size; j++)
        {
            printout += alg_matrix[i][j] + " | ";
        }
        //console.log(printout);

    }
    //console.log("next");

}

function sendResults() // Sends final outcome to alg_database
{
    finastr = "";
    for(var i = 0; i<alg_size; i++)
    {
        for(var j = 0; j<alg_size; j++)
        {
            endtotal += alg_matrix[i][j];
        }
    }
    var finalarray = new Array();
    var diff = (starttotal - endtotal);

    diff = diff.toFixed(2);

    var numtrans = 0;
    for(var i = 0; i<alg_size; i++)
    {
        for(var j = 0; j<alg_size; j++)
        {
            if(alg_matrix[i][j] != 0)
            {
                numtrans++;
                var finalpayer = alg_mapping[i];
                var finalpayee = alg_mapping[j];
                var finalamount = alg_matrix[i][j].toFixed(2);

                finalarray[finalarray.length] = {"payer":finalpayer, "payee": finalpayee, "amount": finalamount};
            }
        }
    }
    finalstr = JSON.stringify(finalarray);
    endtotal = 0;
    numtrans = 0;
    return finalstr;
}
<commit_msg>string issue fix<commit_after>var alg_size;
var alg_data = new Array();     // Raw alg_data from JSON
var alg_request = new XMLHttpRequest();
var alg_matrix = new Array();   // Main money alg_matrix
var alg_mapping = new Array();  // Key for "alg_matrix" array
var alg_numpayto;   // Number of people to be paid
var alg_numpayer;   // Number of payers
var starttotal=0;   // Number of dollars in transfer before algorithm
var endtotal=0; // Number of dollars in transfer after algorithm
var alg_changed = true;

function init(trans)
{

    alg_data = trans;
    checkSize();
    createMatrix();
    checkMatrix();
    algorithm();
    checkMatrix();
    return sendResults();
}

function checkSize()    // Calculates required alg_size for "alg_matrix" array
{
    for(var i = 0; i<alg_data.length; i++)
    {

        var duplicate = false;
        for (var j = 0; j<alg_mapping.length; j++)
        {
            var strpayer = alg_data[i]["payer"];
            var strtest = alg_mapping[j];

            if(strpayer == strtest)
            {
                duplicate = true;
            }
        }
        if(duplicate == false)
        {
            var name = alg_data[i]["payer"];
            alg_mapping[alg_mapping.length] = name;
        }

    }

    for(var i = 0; i<alg_data.length; i++)
    {

        var duplicate = false;
        for (var j = 0; j<alg_mapping.length; j++)
        {
            var strpayto = alg_data[i]["payee"];
            var strtest = alg_mapping[j];

            if(strpayto == strtest)
            {
                duplicate = true;
            }
        }
        if(duplicate == false)
        {
            var name = alg_data[i]["payee"];
            alg_mapping[alg_mapping.length] = name;
        }
    }
    alg_size = alg_mapping.length;
}

function createMatrix() // Creates and fills the "alg_matrix" array
{
    alg_matrix = new Array(alg_size);
    for(var i = 0; i<alg_size; i++)
    {
        alg_matrix[i] = new Array(alg_size);
    }
    for(var i = 0; i<alg_size;i++)
    {
        for(var j = 0; j<alg_size; j++)
        {
            alg_matrix[i][j] = 0.00;
        }
    }

    for(var i = 0; i<alg_data.length; i++)
    {
        var payer = alg_data[i]["payee"];
        var amount = Number(alg_data[i]["amount"]);
        var payto = alg_data[i]["payer"];
        var payermap;
        var paytomap;

        for(var j=0; j<alg_mapping.length;j++)
        {
            if(payer == alg_mapping[j])
            {
                payermap = j;
            }
            if(payto == alg_mapping[j])
            {
                paytomap = j;
            }
        }

        alg_matrix[payermap][paytomap] += amount;
        alg_matrix[payermap][paytomap] = Math.round(alg_matrix[payermap][paytomap]*100)/100;
    }

    for(var i = 0; i<alg_size; i++)
    {
        for(var j = 0; j<alg_size; j++)
        {
            starttotal += alg_matrix[i][j];
        }
    }

}

function algorithm()    // The Algorithm. Simplifies the debts.
{
    alg_changed = true;
    while (alg_changed == true)
    {
        alg_changed = false;
        var x;
        var y;
        var z;
        var xamount;
        var yamount;
        for(var i = 0; i<alg_size; i++)
        {
            for(var j = 0; j<alg_size; j++)
            {

                x = i;
                y = j;
                for(var k =  0; k<alg_size; k++)
                {
                    var action = false;
                    xamount = alg_matrix[i][j];
                    // Bidirectional - Debt between 2 people
                    if(alg_matrix[i][j] != 0 && alg_matrix[j][i] !=0)
                    {
                        if(alg_matrix[i][j] > alg_matrix[j][i])
                        {
                            var a = alg_matrix[i][j]
                                var b = alg_matrix[j][i]
                                alg_matrix[i][j] = a-b;
                            alg_matrix[j][i] = 0
                                alg_changed = true;
                            action = true;
                        }
                        else if(alg_matrix[i][j] > alg_matrix[j][i])
                        {
                            var a = alg_matrix[i][j]
                                var b = alg_matrix[j][i]
                                alg_matrix[i][j] = 0;
                            alg_matrix[j][i] = b-a;
                            alg_changed = true;
                            action = true;
                        }
                        else if(alg_matrix[i][j] == alg_matrix[j][i])
                        {
                            alg_matrix[i][j] = 0;
                            alg_matrix[j][i] = 0;
                            alg_changed = true;
                            action = true;
                        }
                    }
                    yamount = alg_matrix[j][k];
                    // Person A can exactly pay Person B's debt
                    if(xamount == yamount && xamount != 0 && yamount != 0 && x !=k)
                    {
                        alg_matrix[j][k] = 0
                        alg_matrix[i][k] += xamount;
                        alg_matrix[i][j] = 0;
                        alg_changed = true;
                        action = true;
                    }
                    // Person A pays part of Person B's debt to Person C
                    else if(xamount < yamount && xamount != 0 && yamount!= 0 && x!=k)
                    {
                        alg_matrix[i][k] += xamount;
                        alg_matrix[j][k] = yamount-xamount;
                        alg_matrix[i][j] = 0;
                        alg_changed = true;
                        action = true;
                    }
                    // Person A pays all of Person B's debt to Person C and pays Person B
                    else if(xamount > yamount && xamount != 0 & yamount != 0 && x!=k)
                    {
                        alg_matrix[i][k] += yamount;
                        alg_matrix[j][k] = 0;
                        alg_matrix[i][j] = xamount - yamount;
                        alg_changed = true;
                        action = true;
                    }

                    if(action == true)
                    {
                        checkMatrix();
                    }

                    alg_matrix[i][j] = Math.round(alg_matrix[i][j]*100)/100;
                    alg_matrix[i][k] = Math.round(alg_matrix[i][k]*100)/100;
                    alg_matrix[j][i] = Math.round(alg_matrix[j][i]*100)/100;
                    alg_matrix[j][k] = Math.round(alg_matrix[j][k]*100)/100;
                    alg_matrix[k][j] = Math.round(alg_matrix[k][j]*100)/100;
                    alg_matrix[k][i] = Math.round(alg_matrix[k][i]*100)/100;
                }
            }
        }
    }
}

function checkMatrix()  // Prints out visual representation of "alg_matrix" and key in console
{
    //console.log(alg_mapping);
    for(var i = 0; i<alg_size; i++)
    {
        var printout="";
        for(var j=0; j<alg_size; j++)
        {
            printout += alg_matrix[i][j] + " | ";
        }
        //console.log(printout);

    }
    //console.log("next");

}

function sendResults() // Sends final outcome to alg_database
{
    finastr = "";
    for(var i = 0; i<alg_size; i++)
    {
        for(var j = 0; j<alg_size; j++)
        {
            endtotal += alg_matrix[i][j];
        }
    }
    var finalarray = new Array();
    var diff = (starttotal - endtotal);

    diff = diff.toFixed(2);

    var numtrans = 0;
    for(var i = 0; i<alg_size; i++)
    {
        for(var j = 0; j<alg_size; j++)
        {
            if(alg_matrix[i][j] != 0)
            {
                numtrans++;
                var finalpayer = alg_mapping[i];
                var finalpayee = alg_mapping[j];
                var finalamount = alg_matrix[i][j].toFixed(2);

                finalarray[finalarray.length] = {"payer":finalpayer, "payee": finalpayee, "amount": finalamount};
            }
        }
    }
    finalstr = JSON.stringify(finalarray);
    endtotal = 0;
    numtrans = 0;
    return finalstr;
}
<|endoftext|>


<commit_before>var styles  = require('../string/ansiStyles')
var forEach = require('../array/forEach')
var keys    = require('../object/keys')

var colorz = {}

forEach(keys(styles), function (style) {
  var open = '\u001b[' + styles[style][0] + 'm'
  var clos = '\u001b[' + styles[style][1] + 'm'

  colorz[style] = function (msg) {
    return open + msg + clos
  }
})

function strip (str) {
  return str.replace(/(?:\u001b\[)\d+m/g, '')
}

function expose (style, str, noColor) {
  if (typeof str === 'boolean') {
    noColor = str
    str = 'Hello World'
  }

  str = str || 'Hello World'

  return noColor
    ? style + ': ' + JSON.stringify(colorz[style](str))
    : style + ': '
      + JSON.stringify(colorz[style](str))
      .replace(/(\\u001b\[\d+m)/g, colorz[style](['$1']))
}

function colorize (str, style) {
  if (!style) return str

  if (Array.isArray(style) && style.length > 1) {
    return colorize(colorz[style[0]](str), style.slice(1))
  } else {
    return colorz[Array.isArray(style) ? style[0] : style](str)
  }
}

module.exports = colorz
module.exports.strip = strip
module.exports.expose = expose
module.exports.colorize = colorize
module.exports.format = colorize
<commit_msg>update utils/colorz -- move ansiStyles back into colorz<commit_after><|endoftext|>


<commit_before>/*
Let's import all our files here.
*/

import "./callbacks.js"
import "./emails.js"
import "./custom_fields.js"
import "./i18n.js"
import "./groups.js"
import "./routes.jsx"

import "./components/CustomLogo.jsx";
import "./components/CustomNewsletter.jsx";
import "./components/CustomPostsItem.jsx";
import "./components/MyCustomPage.jsx";
<commit_msg>customization-demo: import order + comments<commit_after>/*
Let's import all our files here.
*/

// general business logic of this customization
import "./callbacks.js"
import "./emails.js"
import "./custom_fields.js"
import "./i18n.js"
import "./groups.js"

// custom components
import "./components/CustomLogo.jsx";
import "./components/CustomNewsletter.jsx";
import "./components/CustomPostsItem.jsx";
import "./components/MyCustomPage.jsx";

// custom routes
import "./routes.jsx";
<|endoftext|>


<commit_before>/* eslint-disable no-use-before-define */
import _ from 'lodash';

const operatorMap = {
  ne: '$ne',
  gt: '$gt',
  ge: '$gte',
  gte: '$gte',
  lt: '$lt',
  le: '$lte',
  lte: '$lte',
  and: '$and',
  or: '$or',
  like: '$like',
  startsWith: '$like',
  endsWith: '$like',
};

const literalMap = {
  like: node => `%${node}%`,
  startsWith: node => `${node}%`,
  endsWith: node => `%${node}`,
  and: node => mapNode(_.values(node)),
  or: node => mapNode(_.values(node)),
};

const mapKey = key => {
  const operator = operatorMap[key];
  if (operator) {
    return operator;
  }

  if (key.includes('.')) {
    return `$${key}$`;
  }

  return key;
};

const mapNode = node => {
  if (_.isArray(node)) {
    return node.map(inner => mapNode(inner));
  }

  if (_.isObject(node)) {
    return _.reduce(node, (result, value, key) => {
      const mappedKey = mapKey(key);
      let mappedValue = mapNode(value);

      const translate = literalMap[key];
      if (translate) {
        mappedValue = translate(mappedValue);
      }

      return {...result, [mappedKey]: mappedValue};
    }, {});
  }

  return node;
};

export const buildWhere = args => {
  if (!args.where || _.keys(args.where).length === 0) {
    return undefined; // eslint-disable-line
  }

  return mapNode(args.where);
};
<commit_msg>Fixed issue where navigation property clauses are double escaped.<commit_after>/* eslint-disable no-use-before-define */
import _ from 'lodash';

const operatorMap = {
  ne: '$ne',
  gt: '$gt',
  ge: '$gte',
  gte: '$gte',
  lt: '$lt',
  le: '$lte',
  lte: '$lte',
  and: '$and',
  or: '$or',
  like: '$like',
  startsWith: '$like',
  endsWith: '$like',
};

const literalMap = {
  like: node => `%${node}%`,
  startsWith: node => `${node}%`,
  endsWith: node => `%${node}`,
};

const mapKey = key => {
  const operator = operatorMap[key];
  if (operator) {
    return operator;
  }

  if (key.includes('.')) {
    return `$${key}$`;
  }

  return key;
};

const mapNode = node => {
  if (_.isArray(node)) {
    return node.map(inner => mapNode(inner));
  }

  if (_.isObject(node)) {
    return _.reduce(node, (result, value, key) => {
      const mappedKey = mapKey(key);
      let mappedValue = mapNode(value);

      const translate = literalMap[key];
      if (translate) {
        mappedValue = translate(mappedValue);
      }

      return {...result, [mappedKey]: mappedValue};
    }, {});
  }

  return node;
};

export const buildWhere = args => {
  if (!args.where || _.keys(args.where).length === 0) {
    return undefined; // eslint-disable-line
  }

  return mapNode(args.where);
};
<|endoftext|>