<commit_before>(function() {
  var gui = require('nw.gui');
  var iframe = document.querySelector('iframe');

  var handleClick = function(e) {
    var checkForLink = function(el) {
      var openLink = function(url) {
        gui.Shell.openExternal(url);
        e.preventDefault();
      };

      if (el.nodeName.toLowerCase() === 'a') {
        var href = el.getAttribute('href');
        if (href !== null) {
          var middleButton = e.which === 2;
          if (middleButton ||
              (el.target === '_blank' &&
               el.rel !== 'user' &&
               el.rel !== 'mediaPreview')) {
            openLink(href);
          }

          console.log(href, middleButton, el.target, el.rel);
        }
      } else if ((p = el.parentElement) !== null) {
        checkForLink(p);
      }
    };

    checkForLink(e.target);
  };

  var init = function() {
    if (iframe &&
        iframe.contentWindow &&
        iframe.contentWindow.document &&
        iframe.contentWindow.document.body &&
        iframe.contentWindow.document.body.innerHTML) {
     iframe.contentWindow.document.body.addEventListener('click', handleClick, false);
    } else {
      setTimeout(init, 100);
    }
  };

  init();
}).apply(this);
<commit_msg>Support zooming and unzooming<commit_after>(function() {
  var gui = require('nw.gui');
  var iframe = document.querySelector('iframe');
  var win = gui.Window.get();

  var handleClick = function(e) {
    var checkForLink = function(el) {
      var openLink = function(url) {
        gui.Shell.openExternal(url);
        e.preventDefault();
      };

      if (el.nodeName.toLowerCase() === 'a') {
        var href = el.getAttribute('href');
        if (href !== null) {
          var middleButton = e.which === 2;
          if (middleButton ||
              (el.target === '_blank' &&
               el.rel !== 'user' &&
               el.rel !== 'mediaPreview')) {
            openLink(href);
          }

          console.log(href, middleButton, el.target, el.rel);
        }
      } else if ((p = el.parentElement) !== null) {
        checkForLink(p);
      }
    };

    checkForLink(e.target);
  };

  var zoom = function () { win.zoomLevel += 1; }
  var unzoom = function () { win.zoomLevel -= 1; }
  var resetZoom = function () { win.zoomLevel = 0; }

  var handleKeydown = function (e) {
    if (e.ctrlKey) {
      if (e.keyCode == 187) zoom();
      else if (e.keyCode == 189) unzoom();
      else if (e.keyCode == 48) resetZoom();
    }
  };

  var init = function() {
    if (iframe &&
        iframe.contentWindow &&
        iframe.contentWindow.document &&
        iframe.contentWindow.document.body &&
        iframe.contentWindow.document.body.innerHTML) {
     iframe.contentWindow.document.body.addEventListener('click', handleClick, false);
     iframe.contentWindow.document.body.addEventListener('keydown', handleKeydown, false);
    } else {
      setTimeout(init, 100);
    }
  };

  init();
}).apply(this);
<|endoftext|>


<commit_before>// -----------------------------------------------------------------------------
// CONSTANTS
// -----------------------------------------------------------------------------

// Default modifier keys for binds
const MODIFIERS = ['ctrl', 'shift'];

// Default modifier keys for resizing windows binds
const RESIZE_MODIFIERS = ['shift', 'alt'];

// Default modifier keys for positioning windows binds.
const POSITION_MODIFIERS = ['ctrl', 'shift'];

// Grid width and height for centering windows with different sizes
const GRID_WIDTH = 12;
const GRID_HEIGHT = 10;

// Margin to have around each window edge
const MARGIN = 10;

// Size for resizing/positioning increments/decrements.
const RESIZE_POSITION_AMOUNT = 40;

// -----------------------------------------------------------------------------
// FUNCTIONS
// -----------------------------------------------------------------------------

Bind.on("s", MODIFIERS, () => {
  Stark.run("/usr/bin/open", ["/System/Library/CoreServices/ScreenSaverEngine.app"]);
});

// -----------------------------------------------------------------------------
// WINDOW MOVEMENT
// -----------------------------------------------------------------------------

Bind.on("up", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x;
  const y = win.topLeft.y - RESIZE_POSITION_AMOUNT;

  win.setTopLeft({ x, y });
});

Bind.on("down", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x;
  const y = win.topLeft.y + RESIZE_POSITION_AMOUNT;

  win.setTopLeft({ x, y });
});

Bind.on("left", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x - RESIZE_POSITION_AMOUNT;
  const y = win.topLeft.y;

  win.setTopLeft({ x, y });
});

Bind.on("right", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x + RESIZE_POSITION_AMOUNT;
  const y = win.topLeft.y;

  win.setTopLeft({ x, y });
});

// -----------------------------------------------------------------------------
// WINDOW RESIZING
// -----------------------------------------------------------------------------

Bind.on("up", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width;
  const height = win.size.height - RESIZE_POSITION_AMOUNT;

  win.setSize({ width, height });
});

Bind.on("down", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width;
  const height = win.size.height + RESIZE_POSITION_AMOUNT;

  win.setSize({ width, height });
});

Bind.on("left", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width - RESIZE_POSITION_AMOUNT;
  const height = win.size.height;

  win.setSize({ width, height });
});

Bind.on("right", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width + RESIZE_POSITION_AMOUNT;
  const height = win.size.height;

  win.setSize({ width, height });
});

// -----------------------------------------------------------------------------
// WINDOW CENTERING
// -----------------------------------------------------------------------------

Bind.on("z", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.width / GRID_WIDTH) * 2;
  const y = r.y + (r.height / GRID_HEIGHT) * 2;

  const width = (r.width / GRID_WIDTH) * 8;
  const height = (r.height / GRID_HEIGHT) * 6;

  win.setFrame({ x, y, width, height });
});

Bind.on("x", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.width / GRID_WIDTH;
  const y = r.y + (r.height / GRID_HEIGHT);

  const width = (r.width / GRID_WIDTH) * 10;
  const height = (r.height / GRID_HEIGHT) * 8;

  win.setFrame({ x, y, width, height });
});

Bind.on("c", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width - (MARGIN * 2);
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

// -----------------------------------------------------------------------------
// WINDOW POSITIONING
// -----------------------------------------------------------------------------

Bind.on("h", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

Bind.on("l", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

Bind.on("j", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

Bind.on("k", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

// -----------------------------------------------------------------------------
// APP EVENTS
// -----------------------------------------------------------------------------

Event.on("applicationDidLaunch", (app) => {
  if (app.name === 'iTerm2') {
    _.each(app.windows({ visible: true }), (win) => {
      const r = win.screen.frameWithoutDockOrMenu;

      const x = r.x + MARGIN;
      const y = r.y + MARGIN;

      const width = r.width / 2 - (MARGIN + (MARGIN / 2));
      const height = r.height - (MARGIN * 2);

      win.setFrame({ x, y, width, height });
    });
  }
});

// -----------------------------------------------------------------------------
// APP POSITIONING
// -----------------------------------------------------------------------------

Bind.on("t", MODIFIERS, () => {
  const app = App.find("Tweetbot");

  if (!app) {
    return;
  }

  _.each(app.windows(), (win) => {
    const r = win.screen.frameWithoutDockOrMenu;

    const x = r.x + MARGIN;
    const y = r.y + MARGIN;

    const width = r.width / 4 - (MARGIN + (MARGIN / 2));
    const height = r.height - (MARGIN * 2);

    win.setFrame({ x, y, width, height });
  });
});
<commit_msg>Add event for repositioning MacVim windows<commit_after>// -----------------------------------------------------------------------------
// CONSTANTS
// -----------------------------------------------------------------------------

// Default modifier keys for binds
const MODIFIERS = ['ctrl', 'shift'];

// Default modifier keys for resizing windows binds
const RESIZE_MODIFIERS = ['shift', 'alt'];

// Default modifier keys for positioning windows binds.
const POSITION_MODIFIERS = ['ctrl', 'shift'];

// Grid width and height for centering windows with different sizes
const GRID_WIDTH = 12;
const GRID_HEIGHT = 10;

// Margin to have around each window edge
const MARGIN = 10;

// Size for resizing/positioning increments/decrements.
const RESIZE_POSITION_AMOUNT = 40;

// -----------------------------------------------------------------------------
// FUNCTIONS
// -----------------------------------------------------------------------------

Bind.on("s", MODIFIERS, () => {
  Stark.run("/usr/bin/open", ["/System/Library/CoreServices/ScreenSaverEngine.app"]);
});

// -----------------------------------------------------------------------------
// WINDOW MOVEMENT
// -----------------------------------------------------------------------------

Bind.on("up", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x;
  const y = win.topLeft.y - RESIZE_POSITION_AMOUNT;

  win.setTopLeft({ x, y });
});

Bind.on("down", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x;
  const y = win.topLeft.y + RESIZE_POSITION_AMOUNT;

  win.setTopLeft({ x, y });
});

Bind.on("left", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x - RESIZE_POSITION_AMOUNT;
  const y = win.topLeft.y;

  win.setTopLeft({ x, y });
});

Bind.on("right", POSITION_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const x = win.topLeft.x + RESIZE_POSITION_AMOUNT;
  const y = win.topLeft.y;

  win.setTopLeft({ x, y });
});

// -----------------------------------------------------------------------------
// WINDOW RESIZING
// -----------------------------------------------------------------------------

Bind.on("up", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width;
  const height = win.size.height - RESIZE_POSITION_AMOUNT;

  win.setSize({ width, height });
});

Bind.on("down", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width;
  const height = win.size.height + RESIZE_POSITION_AMOUNT;

  win.setSize({ width, height });
});

Bind.on("left", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width - RESIZE_POSITION_AMOUNT;
  const height = win.size.height;

  win.setSize({ width, height });
});

Bind.on("right", RESIZE_MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const width = win.size.width + RESIZE_POSITION_AMOUNT;
  const height = win.size.height;

  win.setSize({ width, height });
});

// -----------------------------------------------------------------------------
// WINDOW CENTERING
// -----------------------------------------------------------------------------

Bind.on("z", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.width / GRID_WIDTH) * 2;
  const y = r.y + (r.height / GRID_HEIGHT) * 2;

  const width = (r.width / GRID_WIDTH) * 8;
  const height = (r.height / GRID_HEIGHT) * 6;

  win.setFrame({ x, y, width, height });
});

Bind.on("x", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.width / GRID_WIDTH;
  const y = r.y + (r.height / GRID_HEIGHT);

  const width = (r.width / GRID_WIDTH) * 10;
  const height = (r.height / GRID_HEIGHT) * 8;

  win.setFrame({ x, y, width, height });
});

Bind.on("c", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width - (MARGIN * 2);
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

// -----------------------------------------------------------------------------
// WINDOW POSITIONING
// -----------------------------------------------------------------------------

Bind.on("h", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

Bind.on("l", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

Bind.on("j", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

Bind.on("k", MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

// -----------------------------------------------------------------------------
// APP POSITIONING
// -----------------------------------------------------------------------------

Bind.on("t", MODIFIERS, () => {
  const app = App.find("Tweetbot");

  if (!app) {
    return;
  }

  _.each(app.windows(), (win) => {
    const r = win.screen.frameWithoutDockOrMenu;

    const x = r.x + MARGIN;
    const y = r.y + MARGIN;

    const width = r.width / 4 - (MARGIN + (MARGIN / 2));
    const height = r.height - (MARGIN * 2);

    win.setFrame({ x, y, width, height });
  });
});

// -----------------------------------------------------------------------------
// EVENTS
// -----------------------------------------------------------------------------

Event.on("applicationDidLaunch", (app) => {
  if (app.name === 'iTerm2') {
    _.each(app.windows({ visible: true }), (win) => {
      const r = win.screen.frameWithoutDockOrMenu;

      const x = r.x + MARGIN;
      const y = r.y + MARGIN;

      const width = r.width / 2 - (MARGIN + (MARGIN / 2));
      const height = r.height - (MARGIN * 2);

      win.setFrame({ x, y, width, height });
    });

    return;
  }
});

Event.on("windowDidOpen", (win) => {
  if (win.app.name === 'MacVim') {
    const r = win.screen.frameWithoutDockOrMenu;

    const x = (r.x + (r.width / 2)) + (MARGIN / 2);
    const y = r.y + MARGIN;

    const width = r.width / 2 - (MARGIN + (MARGIN / 2));
    const height = r.height - (MARGIN * 2);

    win.setFrame({ x, y, width, height });

    return;
  }
});
<|endoftext|>


<commit_before>// -----------------------------------------------------------------------------
// CONSTANTS
// -----------------------------------------------------------------------------

// Default modifier keys for binds
const MODIFIERS = ['ctrl', 'shift'];

// Grid width and height for centering windows with different sizes
const GRID_WIDTH = 12;
const GRID_HEIGHT = 10;

// Margin to have around each window edge
const MARGIN = 10;

// App names
const apps = {
  iterm: 'iTerm2',
  tweetbot: 'Tweetbot',
};

// -----------------------------------------------------------------------------
// FUNCTIONS
// -----------------------------------------------------------------------------

Bind.on('s', MODIFIERS, () => {
  Stark.run('/usr/local/bin/lock', []);
});

// -----------------------------------------------------------------------------
// DEBUG & PLAYGROUND
// -----------------------------------------------------------------------------

Bind.on('d', MODIFIERS, () => {});

// -----------------------------------------------------------------------------
// SPOTIFY CONTROLLING
// -----------------------------------------------------------------------------

Bind.on('q', MODIFIERS, () => {
  Stark.run('/usr/bin/osascript', [
    '-e', `tell application "Spotify"`,
    '-e', `  set player position to 0`,
    '-e', `  previous track`,
    '-e', `end tell`,
  ]);
});

Bind.on('w', MODIFIERS, () => {
  Stark.run('/usr/bin/osascript', ['-e', `tell application "Spotify" to playpause`]);
});

Bind.on('e', MODIFIERS, () => {
  Stark.run('/usr/bin/osascript', ['-e', `tell application "Spotify" to next track`]);
});

// -----------------------------------------------------------------------------
// WINDOW CENTERING
// -----------------------------------------------------------------------------

Bind.on('z', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.width / GRID_WIDTH) * 2;
  const y = r.y + (r.height / GRID_HEIGHT) * 2;

  const width = (r.width / GRID_WIDTH) * 8;
  const height = (r.height / GRID_HEIGHT) * 6;

  win.setFrame({ x, y, width, height });
});

Bind.on('x', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.width / GRID_WIDTH;
  const y = r.y + (r.height / GRID_HEIGHT);

  const width = (r.width / GRID_WIDTH) * 10;
  const height = (r.height / GRID_HEIGHT) * 8;

  win.setFrame({ x, y, width, height });
});

Bind.on('c', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width - (MARGIN * 2);
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

Bind.on('g', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const { y, width, height } = win.frame;

  const x = (r.width / 2) - (width / 2);

  win.setTopLeft({ x, y });
});

// -----------------------------------------------------------------------------
// WINDOW POSITIONING
// -----------------------------------------------------------------------------

Bind.on('h', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

Bind.on('l', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

Bind.on('j', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = r.x + MARGIN;
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

Bind.on('k', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;

  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;

  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

// -----------------------------------------------------------------------------
// SPACES MANAGEMENT
// -----------------------------------------------------------------------------

[1, 2, 3, 4].forEach((space) => {
  Bind.on(`${space}`, MODIFIERS, () => {
    const win = Window.focused();

    if (!win) {
      return;
    }

    Space.active().removeWindows([win]);
    Space.all()[space - 1].addWindows([win]);
  });
});

// -----------------------------------------------------------------------------
// APP POSITIONING
// -----------------------------------------------------------------------------

Bind.on('t', MODIFIERS, () => {
  const app = App.find(apps.tweetbot);

  if (!app) {
    return;
  }

  _.each(app.windows(), (win) => {
    const r = win.screen.frameWithoutDockOrMenu;

    const x = r.x + MARGIN;
    const y = r.y + MARGIN;

    const width = r.width / 4 - (MARGIN + (MARGIN / 2));
    const height = r.height - (MARGIN * 2);

    win.setFrame({ x, y, width, height });
  });
});

// -----------------------------------------------------------------------------
// EVENTS
// -----------------------------------------------------------------------------

Event.on('applicationDidLaunch', (app) => {
  if (app.name === apps.iterm && !app.isTerminated) {
    _.each(app.windows({ visible: true }), (win) => {
      const r = win.screen.frameWithoutDockOrMenu;

      const x = r.x + MARGIN;
      const y = r.y + MARGIN;

      const width = r.width / 2 - (MARGIN + (MARGIN / 2));
      const height = r.height - (MARGIN * 2);

      win.setFrame({ x, y, width, height });
    });

    return;
  }
});
<commit_msg>Reduce new lines in stark.js<commit_after>// -----------------------------------------------------------------------------
// CONSTANTS
// -----------------------------------------------------------------------------

// Default modifier keys for binds
const MODIFIERS = ['ctrl', 'shift'];

// Grid width and height for centering windows with different sizes
const GRID_WIDTH = 12;
const GRID_HEIGHT = 10;

// Margin to have around each window edge
const MARGIN = 10;

// App names
const apps = {
  iterm: 'iTerm2',
  tweetbot: 'Tweetbot',
};

// -----------------------------------------------------------------------------
// FUNCTIONS
// -----------------------------------------------------------------------------

Bind.on('s', MODIFIERS, () => {
  Stark.run('/usr/local/bin/lock', []);
});

// -----------------------------------------------------------------------------
// DEBUG & PLAYGROUND
// -----------------------------------------------------------------------------

Bind.on('d', MODIFIERS, () => {});

// -----------------------------------------------------------------------------
// SPOTIFY CONTROLLING
// -----------------------------------------------------------------------------

Bind.on('q', MODIFIERS, () => {
  Stark.run('/usr/bin/osascript', [
    '-e', `tell application "Spotify"`,
    '-e', `  set player position to 0`,
    '-e', `  previous track`,
    '-e', `end tell`,
  ]);
});

Bind.on('w', MODIFIERS, () => {
  Stark.run('/usr/bin/osascript', ['-e', `tell application "Spotify" to playpause`]);
});

Bind.on('e', MODIFIERS, () => {
  Stark.run('/usr/bin/osascript', ['-e', `tell application "Spotify" to next track`]);
});

// -----------------------------------------------------------------------------
// WINDOW CENTERING
// -----------------------------------------------------------------------------

Bind.on('z', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;
  const x = (r.width / GRID_WIDTH) * 2;
  const y = r.y + (r.height / GRID_HEIGHT) * 2;
  const width = (r.width / GRID_WIDTH) * 8;
  const height = (r.height / GRID_HEIGHT) * 6;

  win.setFrame({ x, y, width, height });
});

Bind.on('x', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;
  const x = r.width / GRID_WIDTH;
  const y = r.y + (r.height / GRID_HEIGHT);
  const width = (r.width / GRID_WIDTH) * 10;
  const height = (r.height / GRID_HEIGHT) * 8;

  win.setFrame({ x, y, width, height });
});

Bind.on('c', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;
  const x = r.x + MARGIN;
  const y = r.y + MARGIN;
  const width = r.width - (MARGIN * 2);
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

Bind.on('g', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;
  const { y, width } = win.frame;
  const x = (r.width / 2) - (width / 2);

  win.setTopLeft({ x, y });
});

// -----------------------------------------------------------------------------
// WINDOW POSITIONING
// -----------------------------------------------------------------------------

Bind.on('h', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;
  const x = r.x + MARGIN;
  const y = r.y + MARGIN;
  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

Bind.on('l', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;
  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;
  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height - (MARGIN * 2);

  win.setFrame({ x, y, width, height });
});

Bind.on('j', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;
  const x = r.x + MARGIN;
  const y = r.y + MARGIN;
  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

Bind.on('k', MODIFIERS, () => {
  const win = Window.focused();

  if (!win) {
    return;
  }

  const r = win.screen.frameWithoutDockOrMenu;
  const x = (r.x + (r.width / 2)) + (MARGIN / 2);
  const y = r.y + MARGIN;
  const width = r.width / 2 - (MARGIN + (MARGIN / 2));
  const height = r.height / 2 - (MARGIN + (MARGIN / 2));

  win.setFrame({ x, y, width, height });
});

// -----------------------------------------------------------------------------
// SPACES MANAGEMENT
// -----------------------------------------------------------------------------

[1, 2, 3, 4].forEach((space) => {
  Bind.on(`${space}`, MODIFIERS, () => {
    const win = Window.focused();

    if (!win) {
      return;
    }

    Space.active().removeWindows([win]);
    Space.all()[space - 1].addWindows([win]);
  });
});

// -----------------------------------------------------------------------------
// APP POSITIONING
// -----------------------------------------------------------------------------

Bind.on('t', MODIFIERS, () => {
  const app = App.find(apps.tweetbot);

  if (!app) {
    return;
  }

  _.each(app.windows(), (win) => {
    const r = win.screen.frameWithoutDockOrMenu;
    const x = r.x + MARGIN;
    const y = r.y + MARGIN;
    const width = r.width / 4 - (MARGIN + (MARGIN / 2));
    const height = r.height - (MARGIN * 2);

    win.setFrame({ x, y, width, height });
  });
});

// -----------------------------------------------------------------------------
// EVENTS
// -----------------------------------------------------------------------------

Event.on('applicationDidLaunch', (app) => {
  if (app.name === apps.iterm && !app.isTerminated) {
    app.windows({ visible: true }).forEach((win) => {
      const r = win.screen.frameWithoutDockOrMenu;
      const x = r.x + MARGIN;
      const y = r.y + MARGIN;
      const width = r.width / 2 - (MARGIN + (MARGIN / 2));
      const height = r.height - (MARGIN * 2);

      win.setFrame({ x, y, width, height });
    });
  }
});
<|endoftext|>


<commit_before>var config = require('./serverconfig');
var fs = require('fs');
var SocketServer = require("./socketserver/socketserver");
var log = new(require('basic-logger'))({
    showTimestamp: true,
    prefix: "SocketServer"
});
////var SocketServer = require("./socketserver_mysql/socketserver");

if(!config.setup){
	log.error("Please, setup your server by editing the 'serverconfig.js' file");
	return;
}

var server = null;

var webConfig = '// THIS IS AN AUTOMATICALLY GENERATED FILE\n\nvar config=JSON.parse(\'' + JSON.stringify(
	{
		useSSL: config.useSSL,
		serverPort: config.socketServer.port,
		selfHosted: true
	}
	) + '\')';

if (config.hostWebserver){
	fs.writeFile('./webserver/public/lib/js/webconfig.js', webConfig);
	// but works to me with fs.writeFile('./webserver/public/lib/js/'+config.room.slug+'-config.js', webConfig); --> caipira
	var webserver = require('./webserver/app');
	server = (config.socketServer.port == config.webServer.port || config.socketServer.port == '') ? webserver.server : null;
}

if (config.apis.musiqpad.sendLobbyStats && (!config.apis.musiqpad.key || config.apis.musiqpad.key == '')) {
	throw 'In order to send stats to the lobby you must generate an key here: https://musiqpad.com/lounge';
}

fs.writeFile('./webconfig.js', webConfig);
var socketServer = new SocketServer(server);

process.on('uncaughtException', function(err) {
  console.log(err);
  console.log(err.stack);
  socketServer.gracefulExit();
});

process.on('exit', socketServer.gracefulExit);

//catches ctrl+c event
process.on('SIGINT', socketServer.gracefulExit);<commit_msg>Socket Server host wasn't set in the config<commit_after>var config = require('./serverconfig');
var fs = require('fs');
var SocketServer = require("./socketserver/socketserver");
var log = new(require('basic-logger'))({
    showTimestamp: true,
    prefix: "SocketServer"
});
////var SocketServer = require("./socketserver_mysql/socketserver");

if(!config.setup){
	log.error("Please, setup your server by editing the 'serverconfig.js' file");
	return;
}

var server = null;

var webConfig = '// THIS IS AN AUTOMATICALLY GENERATED FILE\n\nvar config=JSON.parse(\'' + JSON.stringify(
	{
		useSSL: config.useSSL,
		serverPort: config.socketServer.port,
		selfHosted: true,
		serverHost: config.socketServer.host
	}
	) + '\')';

if (config.hostWebserver){
	fs.writeFile('./webserver/public/lib/js/webconfig.js', webConfig);
	// but works to me with fs.writeFile('./webserver/public/lib/js/'+config.room.slug+'-config.js', webConfig); --> caipira
	var webserver = require('./webserver/app');
	server = (config.socketServer.port == config.webServer.port || config.socketServer.port == '') ? webserver.server : null;
}

if (config.apis.musiqpad.sendLobbyStats && (!config.apis.musiqpad.key || config.apis.musiqpad.key == '')) {
	throw 'In order to send stats to the lobby you must generate an key here: https://musiqpad.com/lounge';
}

fs.writeFile('./webconfig.js', webConfig);
var socketServer = new SocketServer(server);

process.on('uncaughtException', function(err) {
  console.log(err);
  console.log(err.stack);
  socketServer.gracefulExit();
});

process.on('exit', socketServer.gracefulExit);

//catches ctrl+c event
process.on('SIGINT', socketServer.gracefulExit);
<|endoftext|>


<commit_before>'use strict'
import rAF from "./dom/requestAnimationFrame";

let dom = {
      bindEvent(el,event,listener){
        if(el.addEventListener){
            el.addEventListener(event,listener,false);
        }else if(el.attachEvent){
            el.attachEvent("on${event}",(e)=>{
                listener.call(el,e||window.event);
            });
        }
      },
      unbindEvent(el,event,listener){
        if(el.removeEventListener){
            el.removeEventListener(event,listener);
        }else if(el.detachEvent){
            el.detachEvent("on${event}",listener);
        }
      },
      offset(element,dynamic = false) {
        if (!element) {
          return null;
        }
        var top = 0, left = 0;
        if ("getBoundingClientRect" in document.documentElement && !dynamic) {
          var rect = element.getBoundingClientRect();
          var doc = element.ownerDocument;
          var body = doc.body;
          var docEl = doc.documentElement;
          var clientTop = docEl.clientTop || body.clientTop || 0;
          var clientLeft = docEl.clientLeft || body.clientLeft || 0;
          var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
          var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;

          return {
            top: rect.top + scrollTop - clientTop,
            left: rect.left + scrollLeft - clientLeft
          };
        }else{
          do{
            top += element.offsetTop || 0;
            left += element.offsetLeft || 0;
            element = element.offsetParent;
          }while(element);
          return {top,left};
        }
      },
      ownerWindow(element){
        const doc = (element && element.ownerDocument) || document;
        return doc.defaultView || doc.parentWindow || window;
      },
      inViewport(element,container = window,diffInViewport = 0){
        if(container === window){
          let top = element.offsetTop;
          let left = element.offsetLeft;
          let width = element.offsetWidth;
          let height = element.offsetHeight;
          while(element.offsetParent){
            element = element.offsetParent;
            top += element.offsetTop;
            left += element.offsetLeft;
          }
          return (
            top < (window.pageYOffset + window.innerHeight) &&
            left < (window.pageXOffset + window.innerWidth) &&
            (top + height) > window.pageYOffset &&
            (left + width) > window.pageXOffset
          )
        }else{
          let top = dom.offset(element).top;
          let containerTop = dom.scrollTop(container);
          let containerPaddingTop = dom.offset(container.firstChild).top;

        return (containerTop + containerPaddingTop) < (top + element.offsetHeight) &&
                (top - diffInViewport) < (containerTop + container.offsetHeight)
        }
      },
      scrollNode(element){
        let scrollNode = element;
        while(scrollNode !== window){
          scrollNode = scrollNode.parentNode;
          if(scrollNode.scrollTop > 0){
            break;
          }
        }
        return scrollNode;
      },
      scrollInView(element,container = window,callback = ()=>{},axis = "y"){
        let top = dom.offset(element).top - dom.offset(container.firstChild).top;
        let left = dom.offset(element).left - dom.offset(container.firstChild).left;
        let step = 15;
        const cancelScroll = ()=>{
            abort()
        };
        function abort(){
            dom.unbindEvent(element,"touchstart",cancelScroll);
        }
        dom.bindEvent(element,"touchstart",cancelScroll);

        rAF(function smoothScroll(){
          let scrollTop = dom.scrollTop(container);
          let scrollLeft = dom.scrollLeft(container);
          if(axis === "y"){
            if(top > scrollTop && (scrollTop + container.offsetHeight) !== container.scrollHeight){
                scrollTop = (scrollTop + step) >= top ? top: scrollTop + step;
                dom.scrollTop(container,scrollTop)
                rAF(smoothScroll)
            }else if(top < scrollTop && scrollTop >= 0){
                scrollTop  = (scrollTop - step) <= top ? top: scrollTop - step;
                dom.scrollTop(container,scrollTop)
                rAF(smoothScroll)
            }else{
                abort()
                callback()
            }
          }else if(axis === "x"){
            if(left > scrollLeft && (scrollLeft + container.offsetWidth) !== container.scrollWidth){
            //console.log("scroll right")
              scrollLeft = (scrollLeft + step) >= left ? left: scrollLeft + step;
              dom.scrollLeft(container,scrollLeft)
              rAF(smoothScroll())
            }else if(left < scrollLeft && scrollLeft >= 0){
            //console.log("scroll left")
              scrollLeft = (scrollLeft - step) <= left ? left: scrollLeft - step;
              dom.scrollLeft(container,scrollLeft)
              rAF(smoothScroll())
            }else{
              abort()
              callback()
            }
          }
        })
      },
      scrollPosition(element){
        let isCSS1Compat = (document.compatMode === 'CSS1Compat');
        let supportPageOffset = window.pageYOffset !== undefined;
        let scrollTop,scrollLeft;
        if(element === window){
          scrollTop = supportPageOffset ? window.pageYOffset :
                          isCSS1Compat? document.documentElement.scrollTop:
                          document.body.scrollTop;
          scrollLeft = supportPageOffset ? window.pageXOffset :
                        isCSS1Compat? document.documentElement.scrollLeft:
                        document.body.scrollLeft;
        }else{
          scrollTop = element.scrollTop;
          scrollLeft = element.scrollLeft;
        }
        return {
          scrollLeft,scrollTop
        }
      },
      scrollTop(element,value){
        const {scrollTop,scrollLeft} = dom.scrollPosition(element)
        if(value !== undefined){
            if(element === window){
              window.scrollTo(scrollLeft,value);
            }else{
              element.scrollTop = value;
            }
        }
        return scrollTop;
      },
      scrollLeft(element,value){
        const {scrollTop,scrollLeft} = dom.scrollPosition(element)
        if(value !== undefined){
          if(element === window){
            window.scrollTo(value,scrollTop)
          }else{
            element.scrollLeft = value
          }
        }
        return scrollLeft;
      },
      smoothScroll(element = window,position = {},axis = "y"){
        const targetY = position.top && parseInt(position.top,10) || 0;
        const targetX = position.left && parseInt(position.left,10) || 0;
        const initialY = dom.scrollTop(element);
        const initialX = dom.scrollLeft(element)
        var lastY = initialY;
        var lastX = initialX;
        var delta = asxis === "y" ? targetY - initialY : targetX - initialX;
        const speed = Math.min(750,Math.min(1500,Math.abs(delta)));
        // var scrollInProgress = true;
        if(delta === 0 ){
            return;
        }
        function smooth(pos){
            if ((pos /= 0.5) < 1) {
                return 0.5 * Math.pow(pos, 5);
            }
            return 0.5 * (Math.pow((pos - 2), 5) + 2);
        }
        const cancelScroll = ()=>{
            abort()
        };
        function abort(){
            dom.unbindEvent(element,"touchstart",cancelScroll);
            // scrollInProgress = false;
        }
        dom.bindEvent(element,"touchstart",cancelScroll);

        var start,t,y,x;
        rAF(function render(){
            // if(!scrollInProgress){
            //     return;
            // }
            // scrollInProgress = true;
            const now = Date.now();
            if(!start){
                start = now;
            }
            // calculate t, position of animation in [0..1]
            t = Math.min(1, Math.max((now - start) / speed, 0));
            if(axis === "y"){
              y = Math.round(initialY + delta * smooth(t));
              if(delta < 0 && y < targetY){
                  y = targetY;
              }
              if(delta >0 && y > targetY){
                  y = targetY;
              }
              if(lastY !== y){
                  dom.scrollTop(element,y);
              }
              // refresh current position Y
              lastY = y;
              if(y !== targetY){
                  rAF(render);
              }else{
                  abort();
              }
            }else if(axis === "x"){
              x = Math.round(initialX + delta * smooth(t));
              if(delta < 0 && x < targetX){
                  x = targetX;
              }
              if(delta >0 && x > targetX){
                  x = targetX;
              }
              if(lastX !== x){
                  dom.scrollLeft(element,x);
              }
              // refresh current position Y
              lastX = x;
              if(x !== targetX){
                  rAF(render);
              }else{
                  abort();
              }
            }
        });
      },
      hasClass(element,className){
        if (element.classList) {
          return !!className && element.classList.contains(className);
        }
        return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1;
      },
      addClass(element,className){
        if (element) {
          if (element.classList) {
            element.classList.add(className);
          } else if (!dom.hasClass(element, className)) {
            element.className = element.className + ' ' + className;
          }
        }
        return element;
      },
      removeClass(element,className){
        if (element && element.classList) {
            element.classList.remove(className);
        } else if (dom.hasClass(element, className)) {
            element.className = element.className
              .replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1')
              .replace(/\s+/g, ' ') // multiple spaces to one
              .replace(/^\s*|\s*$/g, ''); // trim the ends
          }
      },
      hasNode(node,parent){
        while(node){
          if(node === parent){
            return true;
          }
          node = node.parentNode;
        }
        return false;
      },
      inTouchableRegion(x,y,element){
        const offset = dom.offset(element);
        const minY = offset.top;
        const maxY = offset.top + element.offsetHeight;
        const minX = offset.left;
        const maxX = offset.left + element.offsetWidth;
        const isXValid = (x >= minX && x <= maxX);
        const isYValid = (y >= minY && y <= maxY);
        if(isXValid && isYValid){
            return true;
        }
        return false;
    }
}

export default dom;<commit_msg>fix dom<commit_after>'use strict'
import rAF from "./dom/requestAnimationFrame";

let dom = {
      bindEvent(el,event,listener){
        if(el.addEventListener){
            el.addEventListener(event,listener,false);
        }else if(el.attachEvent){
            el.attachEvent("on${event}",(e)=>{
                listener.call(el,e||window.event);
            });
        }
      },
      unbindEvent(el,event,listener){
        if(el.removeEventListener){
            el.removeEventListener(event,listener);
        }else if(el.detachEvent){
            el.detachEvent("on${event}",listener);
        }
      },
      offset(element,dynamic = false) {
        if (!element) {
          return null;
        }
        var top = 0, left = 0;
        if ("getBoundingClientRect" in document.documentElement && !dynamic) {
          var rect = element.getBoundingClientRect();
          var doc = element.ownerDocument;
          var body = doc.body;
          var docEl = doc.documentElement;
          var clientTop = docEl.clientTop || body.clientTop || 0;
          var clientLeft = docEl.clientLeft || body.clientLeft || 0;
          var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
          var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;

          return {
            top: rect.top + scrollTop - clientTop,
            left: rect.left + scrollLeft - clientLeft
          };
        }else{
          do{
            top += element.offsetTop || 0;
            left += element.offsetLeft || 0;
            element = element.offsetParent;
          }while(element);
          return {top,left};
        }
      },
      ownerWindow(element){
        const doc = (element && element.ownerDocument) || document;
        return doc.defaultView || doc.parentWindow || window;
      },
      inViewport(element,container = window,diffInViewport = 0){
        if(container === window){
          let top = element.offsetTop;
          let left = element.offsetLeft;
          let width = element.offsetWidth;
          let height = element.offsetHeight;
          while(element.offsetParent){
            element = element.offsetParent;
            top += element.offsetTop;
            left += element.offsetLeft;
          }
          return (
            top < (window.pageYOffset + window.innerHeight) &&
            left < (window.pageXOffset + window.innerWidth) &&
            (top + height) > window.pageYOffset &&
            (left + width) > window.pageXOffset
          )
        }else{
          let top = dom.offset(element).top;
          let containerTop = dom.scrollTop(container);
          let containerPaddingTop = dom.offset(container.firstChild).top;

        return (containerTop + containerPaddingTop) < (top + element.offsetHeight) &&
                (top - diffInViewport) < (containerTop + container.offsetHeight)
        }
      },
      scrollNode(element){
        let scrollNode = element;
        while(scrollNode !== window){
          scrollNode = scrollNode.parentNode;
          if(scrollNode.scrollTop > 0){
            break;
          }
        }
        return scrollNode;
      },
      scrollInView(element,container = window,callback = ()=>{},axis = "y"){
        let top = dom.offset(element).top - dom.offset(container.firstChild).top;
        let left = dom.offset(element).left - dom.offset(container.firstChild).left;
        let step = 15;
        const cancelScroll = ()=>{
            abort()
        };
        function abort(){
            dom.unbindEvent(element,"touchstart",cancelScroll);
        }
        dom.bindEvent(element,"touchstart",cancelScroll);

        rAF(function smoothScroll(){
          let scrollTop = dom.scrollTop(container);
          let scrollLeft = dom.scrollLeft(container);
          if(axis === "y"){
            if(top > scrollTop && (scrollTop + container.offsetHeight) !== container.scrollHeight){
                scrollTop = (scrollTop + step) >= top ? top: scrollTop + step;
                dom.scrollTop(container,scrollTop)
                rAF(smoothScroll)
            }else if(top < scrollTop && scrollTop >= 0){
                scrollTop  = (scrollTop - step) <= top ? top: scrollTop - step;
                dom.scrollTop(container,scrollTop)
                rAF(smoothScroll)
            }else{
                abort()
                callback()
            }
          }else if(axis === "x"){
            if(left > scrollLeft && (scrollLeft + container.offsetWidth) !== container.scrollWidth){
            //console.log("scroll right")
              scrollLeft = (scrollLeft + step) >= left ? left: scrollLeft + step;
              dom.scrollLeft(container,scrollLeft)
              rAF(smoothScroll())
            }else if(left < scrollLeft && scrollLeft >= 0){
            //console.log("scroll left")
              scrollLeft = (scrollLeft - step) <= left ? left: scrollLeft - step;
              dom.scrollLeft(container,scrollLeft)
              rAF(smoothScroll())
            }else{
              abort()
              callback()
            }
          }
        })
      },
      scrollPosition(element){
        let isCSS1Compat = (document.compatMode === 'CSS1Compat');
        let supportPageOffset = window.pageYOffset !== undefined;
        let scrollTop,scrollLeft;
        if(element === window){
          scrollTop = supportPageOffset ? window.pageYOffset :
                          isCSS1Compat? document.documentElement.scrollTop:
                          document.body.scrollTop;
          scrollLeft = supportPageOffset ? window.pageXOffset :
                        isCSS1Compat? document.documentElement.scrollLeft:
                        document.body.scrollLeft;
        }else{
          scrollTop = element.scrollTop;
          scrollLeft = element.scrollLeft;
        }
        return {
          scrollLeft,scrollTop
        }
      },
      scrollTop(element,value){
        const {scrollTop,scrollLeft} = dom.scrollPosition(element)
        if(value !== undefined){
            if(element === window){
              window.scrollTo(scrollLeft,value);
            }else{
              element.scrollTop = value;
            }
        }
        return scrollTop;
      },
      scrollLeft(element,value){
        const {scrollTop,scrollLeft} = dom.scrollPosition(element)
        if(value !== undefined){
          if(element === window){
            window.scrollTo(value,scrollTop)
          }else{
            element.scrollLeft = value
          }
        }
        return scrollLeft;
      },
      smoothScroll(element = window,position = {},axis = "y"){
        const targetY = position.top && parseInt(position.top,10) || 0;
        const targetX = position.left && parseInt(position.left,10) || 0;
        const initialY = dom.scrollTop(element);
        const initialX = dom.scrollLeft(element)
        var lastY = initialY;
        var lastX = initialX;
        var delta = axis === "y" ? targetY - initialY : targetX - initialX;
        const speed = Math.min(750,Math.min(1500,Math.abs(delta)));
        // var scrollInProgress = true;
        if(delta === 0 ){
            return;
        }
        function smooth(pos){
            if ((pos /= 0.5) < 1) {
                return 0.5 * Math.pow(pos, 5);
            }
            return 0.5 * (Math.pow((pos - 2), 5) + 2);
        }
        const cancelScroll = ()=>{
            abort()
        };
        function abort(){
            dom.unbindEvent(element,"touchstart",cancelScroll);
            // scrollInProgress = false;
        }
        dom.bindEvent(element,"touchstart",cancelScroll);

        var start,t,y,x;
        rAF(function render(){
            // if(!scrollInProgress){
            //     return;
            // }
            // scrollInProgress = true;
            const now = Date.now();
            if(!start){
                start = now;
            }
            // calculate t, position of animation in [0..1]
            t = Math.min(1, Math.max((now - start) / speed, 0));
            if(axis === "y"){
              y = Math.round(initialY + delta * smooth(t));
              if(delta < 0 && y < targetY){
                  y = targetY;
              }
              if(delta >0 && y > targetY){
                  y = targetY;
              }
              if(lastY !== y){
                  dom.scrollTop(element,y);
              }
              // refresh current position Y
              lastY = y;
              if(y !== targetY){
                  rAF(render);
              }else{
                  abort();
              }
            }else if(axis === "x"){
              x = Math.round(initialX + delta * smooth(t));
              if(delta < 0 && x < targetX){
                  x = targetX;
              }
              if(delta >0 && x > targetX){
                  x = targetX;
              }
              if(lastX !== x){
                  dom.scrollLeft(element,x);
              }
              // refresh current position Y
              lastX = x;
              if(x !== targetX){
                  rAF(render);
              }else{
                  abort();
              }
            }
        });
      },
      hasClass(element,className){
        if (element.classList) {
          return !!className && element.classList.contains(className);
        }
        return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1;
      },
      addClass(element,className){
        if (element) {
          if (element.classList) {
            element.classList.add(className);
          } else if (!dom.hasClass(element, className)) {
            element.className = element.className + ' ' + className;
          }
        }
        return element;
      },
      removeClass(element,className){
        if (element && element.classList) {
            element.classList.remove(className);
        } else if (dom.hasClass(element, className)) {
            element.className = element.className
              .replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1')
              .replace(/\s+/g, ' ') // multiple spaces to one
              .replace(/^\s*|\s*$/g, ''); // trim the ends
          }
      },
      hasNode(node,parent){
        while(node){
          if(node === parent){
            return true;
          }
          node = node.parentNode;
        }
        return false;
      },
      inTouchableRegion(x,y,element){
        const offset = dom.offset(element);
        const minY = offset.top;
        const maxY = offset.top + element.offsetHeight;
        const minX = offset.left;
        const maxX = offset.left + element.offsetWidth;
        const isXValid = (x >= minX && x <= maxX);
        const isYValid = (y >= minY && y <= maxY);
        if(isXValid && isYValid){
            return true;
        }
        return false;
    }
}

export default dom;<|endoftext|>


<commit_before>var fs = require('fs')
  , path = require('path')
;

var rRequireSingleQuote = /require\s*\(\s*'(\.[^']+?)'\s*\)/g
  , rRequireDoubleQuote = /require\s*\(\s*"(\.[^"]+?)"\s*\)/g
;

var rBlockComment = new RegExp('/\\*[\\s\\S]*?\\*/', 'g')
  , rLineComment = new RegExp('//.*', 'g')
;

var rJSExt = /\.js$/;

/**
 * @param {String} srcRoot Absolute path to the source root directory.
 * @param {String} pathRel Path to the JS file relative to the source root.
 * @class
 * @constructor
 */
var File = function(srcRoot, pathRel) {
    this.srcRoot = srcRoot;
    this.pathRel = pathRel;
    this.pathAbs = path.resolve(this.srcRoot, this.pathRel);
    this.parentRel = path.dirname(this.pathRel);
    this.parentAbs = path.dirname(this.pathAbs);

    this._fileContents = null;
    this._strippedFileContents = null;
    this._fileContentsPathNormalized = null;
    this._directDependencies = null;

    this._pathNormMap = {};
};

var _match = function(stripped, regex) {
    return (stripped.match(regex) || [])
        .map(function(str) {
            return new RegExp(regex).exec(str);
        });
};

File.prototype = {

    _getFileContents: function() {
        return fs.readFileSync(this.pathAbs, { encoding: 'utf-8' });
    },

    _getStrippedFileContents: function() {
        var fileContents = this.fileContents;
        return fileContents
            .replace(rBlockComment, '')
            .replace(rLineComment, '')
        ;
    },

    _getFileContentsPathNormalized: function() {
        var self = this;
        var fileContents = this.fileContents;
        fileContents = fileContents.replace(rRequireSingleQuote, function(matchSubstring, badPath, offset, totalString) {
            return matchSubstring.replace(badPath, self._pathNormMap[badPath]);
        });
        fileContents = fileContents.replace(rRequireDoubleQuote, function(matchSubstring, badPath, offset, totalString) {
            return matchSubstring.replace(badPath, self._pathNormMap[badPath]);
        });
        console.log(fileContents);
        return fileContents;
    },

    _getDirectDependencies: function() {
        var self = this
          , stripped = this.strippedFileContents
          , single   = _match(stripped, rRequireSingleQuote)
          , double   = _match(stripped, rRequireDoubleQuote)
          , matches  = [].concat(single).concat(double)
        ;
        return matches.map(function(match) {
            var depPathRelToSelf = rJSExt.test(match[1]) ? match[1] : match[1] + '.js'
              , depPathAbs = path.resolve(self.parentAbs, depPathRelToSelf)
              , depPathRelToRoot = path.relative(self.srcRoot, depPathAbs)
            ;
            self._pathNormMap[match[1]] = depPathRelToRoot;
            return depPathRelToRoot;
        });
    },

    toString: function() {
        return this.pathRel;
    }

};

Object.defineProperties(File.prototype, {

    fileContents: {
        get: function() {
            return this._fileContents || (this._fileContents = this._getFileContents());
        }
    },

    strippedFileContents: {
        get: function() {
            return this._strippedFileContents || (this._strippedFileContents = this._getStrippedFileContents());
        }
    },

    fileContentsPathNormalized: {
        get: function() {
            return this._fileContentsPathNormalized || (this._fileContentsPathNormalized = this._getFileContentsPathNormalized());
        }
    },

    directDependencies: {
        get: function() {
            return this._directDependencies || (this._directDependencies = this._getDirectDependencies());
        }
    }

});

module.exports = File;
<commit_msg>Cleanup<commit_after>var fs = require('fs')
  , path = require('path')
;

var rRequireSingleQuote = /require\s*\(\s*'(\.[^']+?)'\s*\)/g
  , rRequireDoubleQuote = /require\s*\(\s*"(\.[^"]+?)"\s*\)/g
;

var rBlockComment = new RegExp('/\\*[\\s\\S]*?\\*/', 'g')
  , rLineComment = new RegExp('//.*', 'g')
;

var rJSExt = /\.js$/;

/**
 * @param {String} srcRoot Absolute path to the source root directory.
 * @param {String} pathRel Path to the JS file relative to the source root.
 * @class
 * @constructor
 */
var File = function(srcRoot, pathRel) {
    this.srcRoot = srcRoot;
    this.pathRel = pathRel;
    this.pathAbs = path.resolve(this.srcRoot, this.pathRel);
    this.parentRel = path.dirname(this.pathRel);
    this.parentAbs = path.dirname(this.pathAbs);

    this._fileContents = null;
    this._strippedFileContents = null;
    this._fileContentsPathNormalized = null;
    this._directDependencies = null;

    this._pathNormMap = {};
};

var _match = function(stripped, regex) {
    return (stripped.match(regex) || [])
        .map(function(str) {
            return new RegExp(regex).exec(str);
        });
};

File.prototype = {

    _getFileContents: function() {
        return fs.readFileSync(this.pathAbs, { encoding: 'utf-8' });
    },

    _getStrippedFileContents: function() {
        var fileContents = this.fileContents;
        return fileContents
            .replace(rBlockComment, '')
            .replace(rLineComment, '')
        ;
    },

    _getFileContentsPathNormalized: function() {
        var fileContents = this.fileContents;
        fileContents = this._normalize(fileContents, rRequireSingleQuote);
        fileContents = this._normalize(fileContents, rRequireDoubleQuote);
        return fileContents;
    },

    _normalize: function(contents, regex) {
        var self = this;
        return contents.replace(regex, function(matchSubstring, badPath, offset, totalString) {
            return matchSubstring.replace(badPath, self._pathNormMap[badPath]);
        });
    },

    _getDirectDependencies: function() {
        var self = this
          , stripped = this.strippedFileContents
          , single   = _match(stripped, rRequireSingleQuote)
          , double   = _match(stripped, rRequireDoubleQuote)
          , matches  = [].concat(single).concat(double)
        ;
        return matches.map(function(match) {
            var depPathRelToSelf = rJSExt.test(match[1]) ? match[1] : match[1] + '.js'
              , depPathAbs = path.resolve(self.parentAbs, depPathRelToSelf)
              , depPathRelToRoot = path.relative(self.srcRoot, depPathAbs)
            ;
            self._pathNormMap[match[1]] = depPathRelToRoot;
            return depPathRelToRoot;
        });
    },

    toString: function() {
        return this.pathRel;
    }

};

Object.defineProperties(File.prototype, {

    fileContents: {
        get: function() {
            return this._fileContents || (this._fileContents = this._getFileContents());
        }
    },

    strippedFileContents: {
        get: function() {
            return this._strippedFileContents || (this._strippedFileContents = this._getStrippedFileContents());
        }
    },

    fileContentsPathNormalized: {
        get: function() {
            return this._fileContentsPathNormalized || (this._fileContentsPathNormalized = this._getFileContentsPathNormalized());
        }
    },

    directDependencies: {
        get: function() {
            return this._directDependencies || (this._directDependencies = this._getDirectDependencies());
        }
    }

});

module.exports = File;
<|endoftext|>


<commit_before>/* Copyright © 2016 Dmitri Kourennyi
   See the file COPYING for copying permission.
*/
/* jshint moz: true, strict: global, browser: true, devel:true */
/* globals require */
'use strict';

// Import the page-mod API
var pageMod = require("sdk/page-mod");
var prefs = require("sdk/preferences/service");
var { PrefsTarget } = require("sdk/preferences/event-target");

var darkColor, lightColor, allColors;

// Load the desired system colors once to pass to pageMod
cacheColors();

// Add listener for changes to preferences so colors can be re-loaded
var target = PrefsTarget({branchName: "browser.display."});

target.on("use_system_colors", cacheColors);
target.on("foreground_color", cacheColors);
target.on("background_color", cacheColors);
require('sdk/simple-prefs').on('allColors', cacheColors);

// Create page mod to fix colors
pageMod.PageMod({
  include: /.*/,
  contentScriptFile : './checkContrast.js',
  onAttach: function(worker) {
    worker.port.emit("colors", [darkColor, lightColor, allColors]);
  }
});

function cacheColors()
{
    darkColor = prefs.get("browser.display.foreground_color");
    lightColor = prefs.get("browser.display.background_color");
    if (require('sdk/simple-prefs').prefs.allColors === true) {
        allColors = true;
    } else {
        allColors = false;
    }
}
<commit_msg>Remove unused main file from port<commit_after><|endoftext|>


<commit_before>var maskAreEqual;
var maskIncludes;
var maskIntersection;
var maskIsEmpty;
var maskNew;
var maskNewInverted;
var maskUnion;
var maskWithBit;

(function ()
{
    maskAreEqual =
    function (mask1, mask2)
    {
        var equal = mask1[0] === mask2[0] && mask1[1] === mask2[1];
        return equal;
    };

    maskIncludes =
    function (includingMask, includedMask)
    {
        var part0;
        var part1;
        var included =
        ((part0 = includedMask[0]) & includingMask[0]) === part0 &&
        ((part1 = includedMask[1]) & includingMask[1]) === part1;
        return included;
    };

    maskIntersection =
    function (mask1, mask2)
    {
        var mask = [mask1[0] & mask2[0], mask1[1] & mask2[1]];
        return mask;
    };

    maskIsEmpty =
    function (mask)
    {
        var empty = !(mask[0] | mask[1]);
        return empty;
    };

    maskNew =
    function ()
    {
        var mask = [0, 0];
        return mask;
    };

    maskUnion =
    function (mask1, mask2)
    {
        var mask = [mask1[0] | mask2[0], mask1[1] | mask2[1]];
        return mask;
    };

    maskWithBit =
    function (bitIndex)
    {
        var mask = [0, 0];
        mask[bitIndex >> 5] |= 1 << bitIndex;
        return mask;
    };
}
)();
<commit_msg>Removed unused code<commit_after>var maskAreEqual;
var maskIncludes;
var maskIntersection;
var maskIsEmpty;
var maskNew;
var maskUnion;
var maskWithBit;

(function ()
{
    maskAreEqual =
    function (mask1, mask2)
    {
        var equal = mask1[0] === mask2[0] && mask1[1] === mask2[1];
        return equal;
    };

    maskIncludes =
    function (includingMask, includedMask)
    {
        var part0;
        var part1;
        var included =
        ((part0 = includedMask[0]) & includingMask[0]) === part0 &&
        ((part1 = includedMask[1]) & includingMask[1]) === part1;
        return included;
    };

    maskIntersection =
    function (mask1, mask2)
    {
        var mask = [mask1[0] & mask2[0], mask1[1] & mask2[1]];
        return mask;
    };

    maskIsEmpty =
    function (mask)
    {
        var empty = !(mask[0] | mask[1]);
        return empty;
    };

    maskNew =
    function ()
    {
        var mask = [0, 0];
        return mask;
    };

    maskUnion =
    function (mask1, mask2)
    {
        var mask = [mask1[0] | mask2[0], mask1[1] | mask2[1]];
        return mask;
    };

    maskWithBit =
    function (bitIndex)
    {
        var mask = [0, 0];
        mask[bitIndex >> 5] |= 1 << bitIndex;
        return mask;
    };
}
)();
<|endoftext|>


<commit_before>IRIS.ZONE_TYPE_LINE_2D = 'line2D';
IRIS.ZONE_TYPE_CIRCLE = 'circle';
IRIS.ZONE_TYPE_DISC = 'disc';
IRIS.ZONE_TYPE_SIN = 'sin';
IRIS.ZONE_TYPE_COS = 'cos';
IRIS.ZONE_TYPE_TAN = 'tan';
IRIS.ZONE_TYPE_SQUARE = 'square';
IRIS.ZONE_TYPE_RECTANGLE = 'rectangle';
IRIS.ZONE_TYPE_VERTEX = 'vertex';

IRIS.ZONE_TYPE_LINE_3D = 'line3D';
IRIS.ZONE_TYPE_SPHERE = 'sphere';
IRIS.ZONE_TYPE_BALL = 'ball';
IRIS.ZONE_TYPE_BOX = 'box';
IRIS.ZONE_TYPE_CUBE = 'cube';
IRIS.ZONE_TYPE_SPRING = 'spring';

IRIS.ZONE_PATTERN_RANDOM = 0;
IRIS.ZONE_PATTERN_LINEAL = 1;

IRIS.ZONE_PLANE_XY = 'xy';
IRIS.ZONE_PLANE_YX = 'yx';
IRIS.ZONE_PLANE_YZ = 'yz';
IRIS.ZONE_PLANE_ZY = 'zy';
IRIS.ZONE_PLANE_XZ = 'xz';
IRIS.ZONE_PLANE_ZX = 'zx';

IRIS.BaseVectorZone = Class.extend({
    init: function(opts) {
        this.x = IRIS._setterUndef(opts.x,0);
        this.y = IRIS._setterUndef(opts.y,0);
        this.pattern = IRIS._setterUndef(opts.pattern,IRIS.ZONE_PATTERN_RANDOM);
        this.step = IRIS._setterUndef(opts.step, 0.1);
        this.scale = IRIS._setterUndef(opts.scale, 1);
    }
});

IRIS.Vector2Zone = IRIS.BaseVectorZone.extend({
    init: function(opts) {
        this._super(opts);
        this.plane = IRIS._setterUndef(opts.plane, false);
        if (this.plane) {
            this.rotation = IRIS._setterVector3(opts.rotation, new IRIS.Vector3(0,0,0));
            this.position = IRIS._setterVector3(opts.position, new IRIS.Vector3(0,0,0));
        } else {
            this.rotation = IRIS._setterVector2(opts.rotation, new IRIS.Vector2(0,0));
            this.position = IRIS._setterVector2(opts.position, new IRIS.Vector2(0,0));
        }
    },
    _vector2ToPlane: function(x, y, plane) {
        if (x instanceof IRIS.Vector2) {
            plane = y;
            y = x.y;
            x = x.x;
        }
        switch (plane) {
            case IRIS.ZONE_PLANE_YX:
                return new IRIS.Vector3(y, x, 0);
            case IRIS.ZONE_PLANE_YZ:
                return new IRIS.Vector3(0, x, y);
            case IRIS.ZONE_PLANE_ZY:
                return new IRIS.Vector3(0, y, x);
            case IRIS.ZONE_PLANE_XZ:
                return new IRIS.Vector3(x, 0, y);
            case IRIS.ZONE_PLANE_ZX:
                return new IRIS.Vector3(y, 0, x);
            default:
                return new IRIS.Vector3(x, y, 0);
        }
    }
});

IRIS.Vector3Zone = IRIS.BaseVectorZone.extend({
    init: function(opts) {
        this._super(opts);
        this.z = IRIS._setterUndef(opts.z,0);
        this.rotation = IRIS._setterVector3(opts.rotation, new IRIS.Vector3(0,0,0));
        this.position = IRIS._setterVector3(opts.position, new IRIS.Vector3(0,0,0));
    }
});

IRIS.ctrl.zone = {};
IRIS.registerZone = function(zoneClass, id) {
    IRIS.ctrl.zone[id] = zoneClass;
};
IRIS.getZone = function(id, opts) {
    if (IRIS._isUndef(IRIS.ctrl.zone[id]))
        return false;
    return new IRIS.ctrl.zone[id](opts);
};
IRIS.isZone = function(id) {
    if (IRIS._isUndef(IRIS.ctrl.zone[id]))
        return false;
    return true;
};

IRIS.VertexZone = IRIS.Vector2Zone.extend({
    init: function(opts) {
        opts = IRIS._setterUndef(opts, {});
        this._super(opts);
        if (!IRIS._isUndef(opts.vertices))
            this.setVertices(opts.vertices);
        this._stepVector = 0;
    },
    setVertices: function(vertices) {
        var defVec = new IRIS.Vector2(0, 0);
        if (IRIS._isArray(vertices)) {
            for(var key in vertices) {
                vertices[key] = IRIS._setterVector2(vertices[key], defVec);
                if (this.plane)
                    vertices[key] = this._vector2ToPlane(vertices[key], this.plane);
            }
            this.vertices = vertices;
            this._lengths = [];
            this._sumLengths = [];
            this._length = 0;
            var nextVertex;
            for(var i = 0; i < this.vertices.length; i++) {
                if (i == this.vertices.length-1)
                    nextVertex = this.vertices[0];
                else
                    nextVertex = this.vertices[i+1];
                var length = this.vertices[i].dist(nextVertex);
                this._lengths.push(length);
                this._sumLengths.push(this._length);
                this._length += length;
            }
        } else {
            this.vertices = false;
        }
    },
    getStep: function() {
        if (this.pattern == IRIS.ZONE_PATTERN_RANDOM) {
            this._stepVector = IRIS._random(0, this._length);
        } else {
            this._stepVector += this.step;
            if (this._stepVector > this._length)
                this._stepVector -= this._length;
        }
        return this._getPointAtLength(this._stepVector);;
    },
    _getPointAtLength: function(length) {
        var index = 0;
        for(var i = 0;i <= this._sumLengths.length; i++)
            if (length > this._sumLengths[i])
                index=i;
            else
                break;
        var startVertex = this.vertices[index];
        if (index == this.vertices.length-1)
            var endVertex = this.vertices[0];
        else
            var endVertex = this.vertices[index+1];
        var blend = (length - this._sumLengths[index])/this._lengths[index];
        return startVertex.pointTo(endVertex, blend).mul(this.scale);
    }
});

IRIS.registerZone(IRIS.VertexZone, IRIS.ZONE_TYPE_VERTEX);
<commit_msg>Includes a z value in case the Zone2D is used on a 3D context.<commit_after>IRIS.ZONE_TYPE_LINE_2D = 'line2D';
IRIS.ZONE_TYPE_CIRCLE = 'circle';
IRIS.ZONE_TYPE_DISC = 'disc';
IRIS.ZONE_TYPE_SIN = 'sin';
IRIS.ZONE_TYPE_COS = 'cos';
IRIS.ZONE_TYPE_TAN = 'tan';
IRIS.ZONE_TYPE_SQUARE = 'square';
IRIS.ZONE_TYPE_RECTANGLE = 'rectangle';
IRIS.ZONE_TYPE_VERTEX = 'vertex';

IRIS.ZONE_TYPE_LINE_3D = 'line3D';
IRIS.ZONE_TYPE_SPHERE = 'sphere';
IRIS.ZONE_TYPE_BALL = 'ball';
IRIS.ZONE_TYPE_BOX = 'box';
IRIS.ZONE_TYPE_CUBE = 'cube';
IRIS.ZONE_TYPE_SPRING = 'spring';

IRIS.ZONE_PATTERN_RANDOM = 0;
IRIS.ZONE_PATTERN_LINEAL = 1;

IRIS.ZONE_PLANE_XY = 'xy';
IRIS.ZONE_PLANE_YX = 'yx';
IRIS.ZONE_PLANE_YZ = 'yz';
IRIS.ZONE_PLANE_ZY = 'zy';
IRIS.ZONE_PLANE_XZ = 'xz';
IRIS.ZONE_PLANE_ZX = 'zx';

IRIS.BaseVectorZone = Class.extend({
    init: function(opts) {
        this.x = IRIS._setterUndef(opts.x,0);
        this.y = IRIS._setterUndef(opts.y,0);
        this.z = IRIS._setterUndef(opts.z,0);
        this.pattern = IRIS._setterUndef(opts.pattern,IRIS.ZONE_PATTERN_RANDOM);
        this.step = IRIS._setterUndef(opts.step, 0.1); //TODO: if not specified try to calculate step value according to numb. of elements.
        this.scale = IRIS._setterUndef(opts.scale, 1);
        this.onStep = (IRIS._isFn(opts.onStep)?opts.onStep:false);
    }
});

IRIS.Vector2Zone = IRIS.BaseVectorZone.extend({
    init: function(opts) {
        this._super(opts);
        this.plane = IRIS._setterUndef(opts.plane, false);
        if (this.plane) {
            this.rotation = IRIS._setterVector3(opts.rotation, new IRIS.Vector3(0,0,0));
            this.position = IRIS._setterVector3(opts.position, new IRIS.Vector3(0,0,0));
        } else {
            this.rotation = IRIS._setterVector2(opts.rotation, new IRIS.Vector2(0,0));
            this.position = IRIS._setterVector2(opts.position, new IRIS.Vector2(0,0));
        }
    },
    _vector2ToPlane: function(x, y, plane) {
        if (x instanceof IRIS.Vector2) {
            plane = y;
            y = x.y;
            x = x.x;
        }
        switch (plane) {
            case IRIS.ZONE_PLANE_YX:
                return new IRIS.Vector3(y, x, 0);
            case IRIS.ZONE_PLANE_YZ:
                return new IRIS.Vector3(0, x, y);
            case IRIS.ZONE_PLANE_ZY:
                return new IRIS.Vector3(0, y, x);
            case IRIS.ZONE_PLANE_XZ:
                return new IRIS.Vector3(x, 0, y);
            case IRIS.ZONE_PLANE_ZX:
                return new IRIS.Vector3(y, 0, x);
            default:
                return new IRIS.Vector3(x, y, 0);
        }
    }
});

IRIS.Vector3Zone = IRIS.BaseVectorZone.extend({
    init: function(opts) {
        this._super(opts);
        this.z = IRIS._setterUndef(opts.z,0);
        this.rotation = IRIS._setterVector3(opts.rotation, new IRIS.Vector3(0,0,0));
        this.position = IRIS._setterVector3(opts.position, new IRIS.Vector3(0,0,0));
    }
});

IRIS.ctrl.zone = {};
IRIS.registerZone = function(zoneClass, id) {
    IRIS.ctrl.zone[id] = zoneClass;
};
IRIS.getZone = function(id, opts) {
    if (IRIS._isUndef(IRIS.ctrl.zone[id]))
        return false;
    return new IRIS.ctrl.zone[id](opts);
};
IRIS.isZone = function(id) {
    if (IRIS._isUndef(IRIS.ctrl.zone[id]))
        return false;
    return true;
};

IRIS.VertexZone = IRIS.Vector2Zone.extend({
    init: function(opts) {
        opts = IRIS._setterUndef(opts, {});
        this._super(opts);
        if (!IRIS._isUndef(opts.vertices))
            this.setVertices(opts.vertices);
        this._stepVector = 0;
    },
    setVertices: function(vertices) {
        var defVec = new IRIS.Vector2(0, 0);
        if (IRIS._isArray(vertices)) {
            for(var key in vertices) {
                vertices[key] = IRIS._setterVector2(vertices[key], defVec);
                if (this.plane)
                    vertices[key] = this._vector2ToPlane(vertices[key], this.plane);
            }
            this.vertices = vertices;
            this._lengths = [];
            this._sumLengths = [];
            this._length = 0;
            var nextVertex;
            for(var i = 0; i < this.vertices.length; i++) {
                if (i == this.vertices.length-1)
                    nextVertex = this.vertices[0];
                else
                    nextVertex = this.vertices[i+1];
                var length = this.vertices[i].dist(nextVertex);
                this._lengths.push(length);
                this._sumLengths.push(this._length);
                this._length += length;
            }
        } else {
            this.vertices = false;
        }
    },
    getStep: function() {
        if (this.pattern == IRIS.ZONE_PATTERN_RANDOM) {
            this._stepVector = IRIS._random(0, this._length);
        } else {
            this._stepVector += this.step;
            if (this._stepVector > this._length)
                this._stepVector -= this._length;
        }
        return this._getPointAtLength(this._stepVector);;
    },
    _getPointAtLength: function(length) {
        var index = 0;
        for(var i = 0;i <= this._sumLengths.length; i++)
            if (length > this._sumLengths[i])
                index=i;
            else
                break;
        var startVertex = this.vertices[index];
        if (index == this.vertices.length-1)
            var endVertex = this.vertices[0];
        else
            var endVertex = this.vertices[index+1];
        var blend = (length - this._sumLengths[index])/this._lengths[index];
        return startVertex.pointTo(endVertex, blend).mul(this.scale);
    }
});

IRIS.registerZone(IRIS.VertexZone, IRIS.ZONE_TYPE_VERTEX);
<|endoftext|>


<commit_before>define([
  'jquery',
  'underscore',
  'backbone',
  'models/testsuite/TestSuiteModel',
  'text!templates/testsuites/testSuiteTemplate.html'
], function($, _, Backbone, TestSuiteModel, testSuiteTemplate){

  var TestSuiteView = Backbone.View.extend({

    initialize: function (options) {
      this.id = options.testSuiteId;
      this.projectId = options.projectId;
      this.model = new TestSuiteModel({id: this.id, projectId: this.projectId});
      _.bindAll(this, 'render', 'save');
    },

    render: function() {
      $('.menu a').removeClass('active');
      $('.menu a[href="#/projects"]').addClass('active');
      var self = this;
      this.model.fetch({
        success: function () {
          var data = {
            testsuite: self.model,
            projectId: self.projectId,
            _: _
          }
          var compiledTemplate = _.template( testSuiteTemplate, data );
          $("#content-area").html(compiledTemplate);
        },
        error: function() {
          throw new Error("Failed to fetch test suite");
        }
      });
    },

    save: function(e) {
      e.preventDefault();
      var arr = this.$('form').serializeArray();
      var data = _(arr).reduce(function(acc, field) {
        acc[field.name] = field.value;
        return acc;
      }, {});
      Backbone.history.navigate('#projects', true);
      // this.model.save();
      return false;
    }

  });

  return TestSuiteView;

});<commit_msg>Format nit<commit_after>define([
    'jquery',
    'underscore',
    'backbone',
    'models/testsuite/TestSuiteModel',
    'text!templates/testsuites/testSuiteTemplate.html'
], function($, _, Backbone, TestSuiteModel, testSuiteTemplate) {

    var TestSuiteView = Backbone.View.extend({

        initialize: function(options) {
            this.id = options.testSuiteId;
            this.projectId = options.projectId;
            this.model = new TestSuiteModel({
                id: this.id,
                projectId: this.projectId
            });
            _.bindAll(this, 'render', 'save');
        },

        render: function() {
            $('.menu a').removeClass('active');
            $('.menu a[href="#/projects"]').addClass('active');
            var self = this;
            this.model.fetch({
                success: function() {
                    var data = {
                        testsuite: self.model,
                        projectId: self.projectId,
                        _: _
                    }
                    var compiledTemplate = _.template(testSuiteTemplate, data);
                    $("#content-area").html(compiledTemplate);
                },
                error: function() {
                    throw new Error("Failed to fetch test suite");
                }
            });
        },

        save: function(e) {
            e.preventDefault();
            var arr = this.$('form').serializeArray();
            var data = _(arr).reduce(function(acc, field) {
                acc[field.name] = field.value;
                return acc;
            }, {});
            Backbone.history.navigate('#projects', true);
            // this.model.save();
            return false;
        }

    });

    return TestSuiteView;

});<|endoftext|>


<commit_before>angular.module('bitvagas.jobs.services', [])
.service('JobService', JobService);

JobService.$inject = ['$http'];
function JobService($http){
    var baseUrl = '/api/jobs/';

    this.create = function(job){
        return $http.post(baseUrl + 'create', job);
    };
    this.findAll = function(){
        return $http.get(baseUrl);
    }
    this.findById = function(id){
        return $http.get(baseUrl+id);
    }
}
<commit_msg>added post job service<commit_after>angular.module('bitvagas.jobs.services', [])
.service('JobService', JobService);

JobService.$inject = ['$http'];
function JobService($http){
    var baseUrl = '/api/jobs/';

    this.create = function(job){
        return $http.post(baseUrl, job);
    }
    this.post = function(job){
        return $http.post(baseUrl + 'post', job);
    }
    this.findAll = function(){
        return $http.get(baseUrl);
    }
    this.findById = function(id){
        return $http.get(baseUrl+id);
    }
}
<|endoftext|>


<commit_before>/*
 * Multiple Choice Quiz Module
 */
VISH.Editor.Quiz.MC = (function(V,$,undefined){
	var choicesLetters = ['a)','b)','c)','d)','e)','f)','g)','h)','i)','j)','k)','l)','m)','n)','o)','p)','q)','r)','s)'];
	var addQuizOptionButtonClass = "add_quiz_option_mc";
	var deleteQuizOptionButtonClass = "delete_quiz_option_mc";
	var mcCheckbox = "mcCheckbox";
	var initialized = false;

	var init = function(){
		if(!initialized){
			$(document).on('click', '.' + 'mcContainer', _clickOnQuizArea);
			$(document).on('click','.'+ addQuizOptionButtonClass, _clickToAddOptionInQuiz);
			$(document).on('click','.'+ deleteQuizOptionButtonClass, _removeOptionInQuiz);
			$(document).on('click','.'+ mcCheckbox, _onCheckboxClick);
			initialized = true;
		}
	};

	/*
	 * Manage click events
	 */
	var _clickOnQuizArea = function (event) {
		switch (event.target.classList[0]) {
			case "mcContainer":
				V.Editor.setCurrentArea($("#" + event.target.parentElement.id));
				break;
			case "mc_option_text":
				V.Editor.setCurrentArea($("#" + event.target.parentElement.parentElement.parentElement.parentElement.id));
				break;
			case "mc_option":
				V.Editor.setCurrentArea($("#" + event.target.parentElement.parentElement.parentElement.id));
				break;
			default:
				break;
		}
	};

	/*
	 * Change checkbox status
	 */
	var _onCheckboxClick = function(event){
		var check = $(event.target).attr("check");
		switch(check){
			case "true":
				V.Quiz.updateCheckbox(event.target,"none");
				break;
			case "false":
				//Not false in MC, just switch between true and none
				break;
			case "none":
			default:
				V.Quiz.updateCheckbox(event.target,"true");
				break;
		}
	}

	/*
	 * Create an empty MC Quiz
	 */
	var add = function(area) {
		area.append(_getDummy());
		area.find(".menuselect_hide").remove();
		area.attr('type','quiz');
		area.attr('quiztype', V.Constant.QZ_TYPE.MCHOICE);
		_launchTextEditorForQuestion(area);
		_addOptionInQuiz(area);
		V.Editor.addDeleteButton(area);
	};

	var _getDummy = function(){
		return "

<input type='hidden' name='quiz_id'/>

";
	}

	var _getOptionDummy = function(){
		return "

";
	}

	/*
	 * AddOptionInQuiz called from click event
	 */
	var _clickToAddOptionInQuiz = function (event) {
		var area = $("#" + event.target.parentElement.parentElement.id);
		V.Editor.setCurrentArea(area);
		_addOptionInQuiz(area);
	}

	var _addOptionInQuiz = function (area,value,check) {
		var nChoices = $(area).find("li.mc_option").size();
		var quiz_option = _getOptionDummy();
		var quiz_option = $(quiz_option).attr("nChoice",(nChoices+1));
		$(area).find(".mc_options").append(quiz_option);
		_refreshChoicesIndexs(area);
		if(check){
			V.Quiz.updateCheckbox($(quiz_option).find("td > img")[1],check);
		}
		_launchTextEditorForOptions(area, nChoices,value);
		if(nChoices>0) {
			$(area).find("li[nChoice='"+(nChoices+1)+"']").find("."+deleteQuizOptionButtonClass).css("visibility","visible");
		}
	};

	var _removeOptionInQuiz = function (event) {
		var area = $("div[type='quiz']").has(event.target);
		V.Editor.setCurrentArea(area);
		var liToRemove = $("li.mc_option").has(event.target);
		$(liToRemove).remove();
		_refreshChoicesIndexs(area);
	};

	var _refreshChoicesIndexs = function(area){
		var nChoices = $(area).find("li.mc_option").size();
		$(area).find("li.mc_option").each(function(index, option_element) {
			$(option_element).find(".mc_option_index").text(_getChoiceLetter(nChoices,index+1));
		});
	}

	var _getChoiceLetter = function(nChoices,nChoice){
		if(nChoices<=choicesLetters.length){
			return choicesLetters[nChoice-1];
		} else {
			return ((nChoice)+")");
		}
	}

	var _launchTextEditorForQuestion = function(area,question){
		var textArea = $(area).find(".mc_question_wrapper");
		if(!question){
			V.Editor.Text.launchTextEditor({}, textArea, "", {quiz: true, forceNew: true, fontSize: 38, focus: true, autogrow: true});
		} else {
			V.Editor.Text.launchTextEditor({}, textArea, question, {quiz: true, autogrow: true});
		}
	}

	var _launchTextEditorForOptions = function(area,nChoice,value){
		var first = (nChoice===0);
		var textArea = $(area).find(".mc_option_text")[nChoice];
		if(!value){
			if(first){
				V.Editor.Text.launchTextEditor({}, textArea, "Write options here", {forceNew: true, fontSize: 24, autogrow: true, placeholder: true});
			} else {
				V.Editor.Text.launchTextEditor({}, textArea, "", {forceNew: true, fontSize: 24, autogrow: true, focus: true});
			}
		}else{
			V.Editor.Text.launchTextEditor({}, textArea, value, {autogrow: true});
		}
	}

	/*
	 * Generate JSON
	 */
	 var save = function(area){
	 	var textArea = $(area).find(".mc_question_wrapper");
	 	var quiz = {};
	 	quiz.quizType = VISH.Constant.QZ_TYPE.MCHOICE;
	 	// Self-assessment (Autoevaluación)
	 	quiz.selfA = false; //false by default

	 	var questionInstance = V.Editor.Text.getCKEditorFromTextArea($(area).find(".mc_question_wrapper"));
	 	quiz.question = {};
	 	quiz.question.value = questionInstance.getPlainText();
	 	quiz.question.wysiwygValue = questionInstance.getData();

	 	quiz.choices = [];

	 	var nChoices = $(area).find("li.mc_option").size();
	 	var optionTextAreas = $(area).find(".mc_option_text");

	 	for(var i=0; i<nChoices; i++){
	 		var textArea = optionTextAreas[i];
	 		var optionInstance = V.Editor.Text.getCKEditorFromTextArea(textArea);
	 		var choice = {};
	 		choice.value = optionInstance.getPlainText();
	 		choice.wysiwygValue = optionInstance.getData();
	 		if($(textArea).parent().find(".mcCheckbox").attr("check")==="true"){
	 			choice.answer = true;
	 			quiz.selfA = true;
	 		} else {
	 			choice.answer = "?";
	 		}
	 		quiz.choices.push(choice);
	 	}

	 	if(quiz.selfA){
		 	$(quiz.choices).each(function(index,choice){
		 		if(choice.answer !== true){
		 			choice.answer = false;
		 		}
		 	});
	 	}

	 	return quiz;
	 }

	/*
	 * Render the quiz in the editor
	 * slide is the area and contains all the required parameters
	 */
	var draw = function(area,quiz){
		//Draw question
		$(area).append(_getDummy());
		$(area).attr('type','quiz');
		$(area).attr('quiztype', VISH.Constant.QZ_TYPE.MCHOICE);
		_launchTextEditorForQuestion(area,quiz.question.wysiwygValue);
		V.Editor.addDeleteButton(area);

		//Draw choices (checking selfA)
		$(quiz.choices).each(function(index,choice){
			var check = undefined;
			if(quiz.selfA){
				if(choice.answer===true){
					check = "true";
				}
			}
			_addOptionInQuiz(area,choice.wysiwygValue,check);
		});
	};

	return {
		init			: init,
		add				: add,
		save			: save,
		draw			: draw
	};

}) (VISH, jQuery);<commit_msg>Add multipleAnswer option in MC Quiz<commit_after>/*
 * Multiple Choice Quiz Module
 */
VISH.Editor.Quiz.MC = (function(V,$,undefined){
	var choicesLetters = ['a)','b)','c)','d)','e)','f)','g)','h)','i)','j)','k)','l)','m)','n)','o)','p)','q)','r)','s)'];
	var addQuizOptionButtonClass = "add_quiz_option_mc";
	var deleteQuizOptionButtonClass = "delete_quiz_option_mc";
	var mcCheckbox = "mcCheckbox";
	var initialized = false;

	var init = function(){
		if(!initialized){
			$(document).on('click', '.' + 'mcContainer', _clickOnQuizArea);
			$(document).on('click','.'+ addQuizOptionButtonClass, _clickToAddOptionInQuiz);
			$(document).on('click','.'+ deleteQuizOptionButtonClass, _removeOptionInQuiz);
			$(document).on('click','.'+ mcCheckbox, _onCheckboxClick);
			initialized = true;
		}
	};

	/*
	 * Manage click events
	 */
	var _clickOnQuizArea = function (event) {
		switch (event.target.classList[0]) {
			case "mcContainer":
				V.Editor.setCurrentArea($("#" + event.target.parentElement.id));
				break;
			case "mc_option_text":
				V.Editor.setCurrentArea($("#" + event.target.parentElement.parentElement.parentElement.parentElement.id));
				break;
			case "mc_option":
				V.Editor.setCurrentArea($("#" + event.target.parentElement.parentElement.parentElement.id));
				break;
			default:
				break;
		}
	};

	/*
	 * Change checkbox status
	 */
	var _onCheckboxClick = function(event){
		var check = $(event.target).attr("check");
		switch(check){
			case "true":
				V.Quiz.updateCheckbox(event.target,"none");
				break;
			case "false":
				//Not false in MC, just switch between true and none
				break;
			case "none":
			default:
				V.Quiz.updateCheckbox(event.target,"true");
				break;
		}
	}

	/*
	 * Create an empty MC Quiz
	 */
	var add = function(area) {
		area.append(_getDummy());
		area.find(".menuselect_hide").remove();
		area.attr('type','quiz');
		area.attr('quiztype', V.Constant.QZ_TYPE.MCHOICE);
		_launchTextEditorForQuestion(area);
		_addOptionInQuiz(area);
		V.Editor.addDeleteButton(area);
	};

	var _getDummy = function(){
		return "

<input type='hidden' name='quiz_id'/>

";
	}

	var _getOptionDummy = function(){
		return "

";
	}

	/*
	 * AddOptionInQuiz called from click event
	 */
	var _clickToAddOptionInQuiz = function (event) {
		var area = $("#" + event.target.parentElement.parentElement.id);
		V.Editor.setCurrentArea(area);
		_addOptionInQuiz(area);
	}

	var _addOptionInQuiz = function (area,value,check) {
		var nChoices = $(area).find("li.mc_option").size();
		var quiz_option = _getOptionDummy();
		var quiz_option = $(quiz_option).attr("nChoice",(nChoices+1));
		$(area).find(".mc_options").append(quiz_option);
		_refreshChoicesIndexs(area);
		if(check){
			V.Quiz.updateCheckbox($(quiz_option).find("td > img")[1],check);
		}
		_launchTextEditorForOptions(area, nChoices,value);
		if(nChoices>0) {
			$(area).find("li[nChoice='"+(nChoices+1)+"']").find("."+deleteQuizOptionButtonClass).css("visibility","visible");
		}
	};

	var _removeOptionInQuiz = function (event) {
		var area = $("div[type='quiz']").has(event.target);
		V.Editor.setCurrentArea(area);
		var liToRemove = $("li.mc_option").has(event.target);
		$(liToRemove).remove();
		_refreshChoicesIndexs(area);
	};

	var _refreshChoicesIndexs = function(area){
		var nChoices = $(area).find("li.mc_option").size();
		$(area).find("li.mc_option").each(function(index, option_element) {
			$(option_element).find(".mc_option_index").text(_getChoiceLetter(nChoices,index+1));
		});
	}

	var _getChoiceLetter = function(nChoices,nChoice){
		if(nChoices<=choicesLetters.length){
			return choicesLetters[nChoice-1];
		} else {
			return ((nChoice)+")");
		}
	}

	var _launchTextEditorForQuestion = function(area,question){
		var textArea = $(area).find(".mc_question_wrapper");
		if(!question){
			V.Editor.Text.launchTextEditor({}, textArea, "", {quiz: true, forceNew: true, fontSize: 38, focus: true, autogrow: true});
		} else {
			V.Editor.Text.launchTextEditor({}, textArea, question, {quiz: true, autogrow: true});
		}
	}

	var _launchTextEditorForOptions = function(area,nChoice,value){
		var first = (nChoice===0);
		var textArea = $(area).find(".mc_option_text")[nChoice];
		if(!value){
			if(first){
				V.Editor.Text.launchTextEditor({}, textArea, "Write options here", {forceNew: true, fontSize: 24, autogrow: true, placeholder: true});
			} else {
				V.Editor.Text.launchTextEditor({}, textArea, "", {forceNew: true, fontSize: 24, autogrow: true, focus: true});
			}
		}else{
			V.Editor.Text.launchTextEditor({}, textArea, value, {autogrow: true});
		}
	}

	/*
	 * Generate JSON
	 */
	 var save = function(area){
	 	var textArea = $(area).find(".mc_question_wrapper");
	 	var quiz = {};
	 	quiz.quizType = VISH.Constant.QZ_TYPE.MCHOICE;
	 	// Self-assessment (Autoevaluación)
	 	quiz.selfA = false; //false by default
	 	quiz.extras = {};
	 	quiz.extras.multipleAnswer = false; //false by default
	 	var nAnswers = 0;

	 	var questionInstance = V.Editor.Text.getCKEditorFromTextArea($(area).find(".mc_question_wrapper"));
	 	quiz.question = {};
	 	quiz.question.value = questionInstance.getPlainText();
	 	quiz.question.wysiwygValue = questionInstance.getData();

	 	quiz.choices = [];

	 	var nChoices = $(area).find("li.mc_option").size();
	 	var optionTextAreas = $(area).find(".mc_option_text");

	 	for(var i=0; i<nChoices; i++){
	 		var textArea = optionTextAreas[i];
	 		var optionInstance = V.Editor.Text.getCKEditorFromTextArea(textArea);
	 		var choice = {};
	 		choice.value = optionInstance.getPlainText();
	 		choice.wysiwygValue = optionInstance.getData();
	 		if($(textArea).parent().find(".mcCheckbox").attr("check")==="true"){
	 			choice.answer = true;
	 			quiz.selfA = true;
	 			nAnswers++;
	 		} else {
	 			choice.answer = "?";
	 		}
	 		quiz.choices.push(choice);
	 	}

	 	if(quiz.selfA){
		 	$(quiz.choices).each(function(index,choice){
		 		if(choice.answer !== true){
		 			choice.answer = false;
		 		}
		 	});
	 	}

	 	if(nAnswers>1){
	 		quiz.extras.multipleAnswer = true;
	 	}

	 	return quiz;
	 }

	/*
	 * Render the quiz in the editor
	 * slide is the area and contains all the required parameters
	 */
	var draw = function(area,quiz){
		//Draw question
		$(area).append(_getDummy());
		$(area).attr('type','quiz');
		$(area).attr('quiztype', VISH.Constant.QZ_TYPE.MCHOICE);
		_launchTextEditorForQuestion(area,quiz.question.wysiwygValue);
		V.Editor.addDeleteButton(area);

		//Draw choices (checking selfA)
		$(quiz.choices).each(function(index,choice){
			var check = undefined;
			if(quiz.selfA){
				if(choice.answer===true){
					check = "true";
				}
			}
			_addOptionInQuiz(area,choice.wysiwygValue,check);
		});
	};

	return {
		init			: init,
		add				: add,
		save			: save,
		draw			: draw
	};

}) (VISH, jQuery);<|endoftext|>


<commit_before>#! /usr/bin/env node

const shell = require('shelljs');

const docsDir = './docs/gaiden-css';
const sourceDocsDir = './docs/demo/gaiden-css/scss';
const sourceDir = './src/scss';
const minifiedDocsFile = `${docsDir}/ninja-demo.css`;

const timestamp = new Date().getTime();

const options = {
  sass: ` --include-path ${sourceDocsDir} \
    --include-path ${sourceDir} \
    --output-style expanded \
    --sourceComments true \
    -o ${docsDir} \
    --recursive `
}

shell.exec(`node-sass ${sourceDocsDir} ${options.sass} ${minifiedDocsFile}`);
shell.exec(`documentjs -f`);

shell.exec('git checkout -B gh-pages');
shell.exec('git pull origin gh-pages --no-commit');

shell.cp('-f', './dist/gaiden.min.css', './gaiden.css');

const filesToFixPath = shell.ls('-R', './docs/demo/').filter(function(file) {
  return file.match(/(\.html$|\.js$)/);
});

filesToFixPath.forEach(function(file) {
  shell.sed('-i', '.\/docs\/demo\/', '\/demo', `./docs/demo/${file}`);
  shell.sed('-i', '\/gaiden-css\/gaiden.css', '\/gaiden.css', `./docs/demo/${file}`);
});

shell.cp('-fr', `${docsDir}/`, './');

shell.cp('-Rf', './docs/demo/', './demo/');

const gaidenLastTag = shell.exec('git describe').stdout.replace(/\n/g, '');

shell.exec('git add . -A');
shell.exec(`git commit -m "${timestamp}: Updating docs ${gaidenLastTag}"`);
shell.exec('git push origin gh-pages --force');
shell.exec('git checkout -');
<commit_msg>Adding more options to sed files<commit_after>#! /usr/bin/env node

const shell = require('shelljs');

const docsDir = './docs/gaiden-css';
const sourceDocsDir = './docs/demo/gaiden-css/scss';
const sourceDir = './src/scss';
const minifiedDocsFile = `${docsDir}/ninja-demo.css`;

const timestamp = new Date().getTime();

const options = {
  sass: ` --include-path ${sourceDocsDir} \
    --include-path ${sourceDir} \
    --output-style expanded \
    --sourceComments true \
    -o ${docsDir} \
    --recursive `
}

shell.exec(`node-sass ${sourceDocsDir} ${options.sass} ${minifiedDocsFile}`);
shell.exec(`documentjs -f`);

shell.exec('git checkout -B gh-pages');
shell.exec('git pull origin gh-pages --no-commit');

shell.cp('-f', './dist/gaiden.min.css', './gaiden.css');

const filesToFixPath = shell.ls('-R', './docs/demo/').filter(function(file) {
  return file.match(/(\.html$|\.js$)/);
});

filesToFixPath.forEach(function(file) {
  shell.sed('-i', '\/docs\/demo\/', '\/demo', `./docs/demo/${file}`);
  shell.sed('-i', '..\/..\/docs\/demo\/', '\/demo', `./docs/demo/${file}`);
  shell.sed('-i', '\/gaiden-css\/gaiden.css', '\/gaiden.css', `./docs/demo/${file}`);
});

shell.cp('-fr', `${docsDir}/`, './');

shell.cp('-Rf', './docs/demo/', './demo/');

const gaidenLastTag = shell.exec('git describe').stdout.replace(/\n/g, '');

shell.exec('git add . -A');
shell.exec(`git commit -m "${timestamp}: Updating docs ${gaidenLastTag}"`);
shell.exec('git push origin gh-pages --force');
shell.exec('git checkout -');
<|endoftext|>


<commit_before><commit_msg>Adding functions<commit_after><|endoftext|>