<commit_before>Ember.FacebookMixin = Ember.Mixin.create({
    FBUser: void 0,
    appId: void 0,
    facebookParams: Ember.Object.create(),
    fetchPicture: true,
    connectError: false,

    init: function() {
        this._super();
        return window.FBApp = this;
    },

    facebookConfigChanged: (function() {
        var _this = this;
        this.removeObserver('appId');

        window.fbAsyncInit = function() {
            return _this.fbAsyncInit();
        };

        return $(function() {
            var js;
            $('body').append($("<div>").attr('id', 'fb-root'));
            js = document.createElement('script');

            $(js).attr({
                id: 'facebook-jssdk',
                async: true,
                src: "//connect.facebook.net/en_US/all.js"
            });
            return $('head').append(js);
        });
    }).observes('facebookParams', 'appId'),

    fbAsyncInit: function() {
        var facebookParams,
            _this = this;

        facebookParams = this.get('facebookParams');
        facebookParams = facebookParams.setProperties({
            appId: this.get('appId' || facebookParams.get('appId') || void 0),
            status: facebookParams.get('status') || true,
            cookie: facebookParams.get('cookie') || true,
            xfbml: facebookParams.get('xfbml') || true,
            channelUrl: facebookParams.get('channelUrl') || void 0
        });

        FB.init(facebookParams);

        this.set('FBloading', true);
    },

    updateFBUser: function(response) {
        var _this = this;
        if (response.status === 'connected') {
            FBApp.set("connectError", false);
            return FB.api('/me', function(user) {
                var FBUser;
                FBUser = Ember.Object.create(user);
                FBUser.set('accessToken', response.authResponse.accessToken);
                FBUser.set('expiresIn', response.authResponse.expiresIn);

                if (_this.get('fetchPicture')) {
                    return FB.api('/me/picture', function(resp) {
                        FBUser.picture = resp.data.url;
                        _this.set('FBUser', FBUser);
                        return FB.api('/me/picture?type=large', function(resp) {
                            FBUser.largePicture = resp.data.url;
                            _this.set('FBUser', FBUser);
                            return _this.set('FBloading', false);
                        });
                    });
                } else {
                    _this.set('FBUser', FBUser);
                    return _this.set('FBloading', false);
                }
            });
        } else {
            this.set('FBUser', false);
            return this.set('FBloading', false);
        }
    }
});

Ember.FBView = Ember.View.extend({
   classNameBindings: [':btn', ':btn-facebook', ':btn-iconed', ':fb-login-button', 'isBusy:is-loading'],
   attributeBindings: ['data-scope','data-size'],

    click: function(e){
        var _this = this;
        _this.set('isBusy', true);
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                App.fbLogin(response.authResponse);
            } else {
               FB.login(function(response){
                    if (response.status === 'connected') {
                        App.fbLogin(response.authResponse);
                    }

                    if (response.authResponse == null && (response.status == 'unknown') ){
                        FBApp.set('connectError', gettext("There was an error connecting Facebook"));
                    }

                    if (response.authResponse == null && (response.status == 'not_authorized') ){
                        FBApp.set('connectError', gettext("Unauthorized to connect to Facebook "));
                    }
                    _this.set('isBusy', false);
               }, {scope: 'email,public_profile,user_friends,user_birthday'});
            } // The above call to Login defines the sets the permissions that go with the access token, even before python-social-auth.
        });
    }
});
<commit_msg>update fb login code to api version 2.1 CLUB-933<commit_after>Ember.FacebookMixin = Ember.Mixin.create({
    FBUser: void 0,
    appId: void 0,
    apiVersion: 'v2.1',
    facebookParams: Ember.Object.create(),
    fetchPicture: true,
    connectError: false,

    init: function() {
        this._super();
        return window.FBApp = this;
    },

    facebookConfigChanged: (function() {
        var _this = this;
        this.removeObserver('appId');

        window.fbAsyncInit = function() {
            return _this.fbAsyncInit();
        };

        return $(function() {
            var js;
            $('body').append($("<div>").attr('id', 'fb-root'));
            js = document.createElement('script');

            $(js).attr({
                id: 'facebook-jssdk',
                async: true,
                src: "//connect.facebook.com/en_US/sdk.js"
            });
            return $('head').append(js);
        });
    }).observes('facebookParams', 'appId'),

    fbAsyncInit: function() {
        var facebookParams,
            _this = this;

        facebookParams = this.get('facebookParams');
        facebookParams = facebookParams.setProperties({
            appId:      this.get('appId' || facebookParams.get('appId') || void 0),
            status:     facebookParams.get('status') || true,
            cookie:     facebookParams.get('cookie') || true,
            xfbml:      facebookParams.get('xfbml') || true,
            channelUrl: facebookParams.get('channelUrl') || void 0,
            version:    this.get('apiVersion')
        });

        FB.init(facebookParams);

        this.set('FBloading', true);
    },

    updateFBUser: function(response) {
        var _this = this;
        if (response.status === 'connected') {
            FBApp.set("connectError", false);
            return FB.api('/me', function(user) {
                var FBUser;
                FBUser = Ember.Object.create(user);
                FBUser.set('accessToken', response.authResponse.accessToken);
                FBUser.set('expiresIn', response.authResponse.expiresIn);

                if (_this.get('fetchPicture')) {
                    return FB.api('/me/picture', function(resp) {
                        FBUser.picture = resp.data.url;
                        _this.set('FBUser', FBUser);
                        return FB.api('/me/picture?type=large', function(resp) {
                            FBUser.largePicture = resp.data.url;
                            _this.set('FBUser', FBUser);
                            return _this.set('FBloading', false);
                        });
                    });
                } else {
                    _this.set('FBUser', FBUser);
                    return _this.set('FBloading', false);
                }
            });
        } else {
            this.set('FBUser', false);
            return this.set('FBloading', false);
        }
    }
});

Ember.FBView = Ember.View.extend({
   classNameBindings: [':btn', ':btn-facebook', ':btn-iconed', ':fb-login-button', 'isBusy:is-loading'],
   attributeBindings: ['data-scope','data-size'],

    click: function(e){
        var _this = this;
        _this.set('isBusy', true);
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                App.fbLogin(response.authResponse);
            } else {
               FB.login(function(response){
                    if (response.status === 'connected') {
                        App.fbLogin(response.authResponse);
                    }

                    if (response.authResponse == null && (response.status == 'unknown') ){
                        FBApp.set('connectError', gettext("There was an error connecting Facebook"));
                    }

                    if (response.authResponse == null && (response.status == 'not_authorized') ){
                        FBApp.set('connectError', gettext("Unauthorized to connect to Facebook "));
                    }
                    _this.set('isBusy', false);
               }, {scope: 'email,public_profile,user_friends,user_birthday'});
            } // The above call to Login defines the sets the permissions that go with the access token, even before python-social-auth.
        });
    }
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

// WARNING: this code is untranspiled and is used in browser too.
// Please make sure any changes are in ES5 or contribute a Babel compile step.

// Some custom utilities to prettify Webpack output.
// This is quite hacky and hopefully won't be needed when Webpack fixes this.
// https://github.com/webpack/webpack/issues/2878

var friendlySyntaxErrorLabel = 'Syntax error:';

function isLikelyASyntaxError(message) {
  return message.indexOf(friendlySyntaxErrorLabel) !== -1;
}

// Cleans up webpack error messages.
function formatMessage(message, isError) {
  var lines = message.split('\n');

  if (lines.length > 2 && lines[1] === '') {
    // Remove extra newline.
    lines.splice(1, 1);
  }

  // Remove webpack-specific loader notation from filename.
  // Before:
  // ./~/css-loader!./~/postcss-loader!./src/App.css
  // After:
  // ./src/App.css
  if (lines[0].lastIndexOf('!') !== -1) {
    lines[0] = lines[0].substr(lines[0].lastIndexOf('!') + 1);
  }

  lines = lines.filter(function(line) {
    // Webpack adds a list of entry points to warning messages:
    //  @ ./src/index.js
    //  @ multi react-scripts/~/react-dev-utils/webpackHotDevClient.js ...
    // It is misleading (and unrelated to the warnings) so we clean it up.
    // It is only useful for syntax errors but we have beautiful frames for them.
    return line.indexOf(' @ ') !== 0;
  });

  // line #0 is filename
  // line #1 is the main error message
  if (!lines[0] || !lines[1]) {
    return lines.join('\n');
  }

  // Cleans up verbose "module not found" messages for files and packages.
  if (lines[1].indexOf('Module not found: ') === 0) {
    lines = [
      lines[0],
      // Clean up message because "Module not found: " is descriptive enough.
      lines[1]
        .replace("Cannot resolve 'file' or 'directory' ", '')
        .replace('Cannot resolve module ', '')
        .replace('Error: ', ''),
    ];
  }

  // Cleans up syntax error messages.
  if (lines[1].indexOf('Module build failed: ') === 0) {
    lines[1] = lines[1].replace(
      'Module build failed: SyntaxError:',
      friendlySyntaxErrorLabel
    );
  }

  // Clean up export errors.
  // TODO: we should really send a PR to Webpack for this.
  var exportError = /\s*(.+?)\s*(")?export '(.+?)' was not found in '(.+?)'/;
  if (lines[1].match(exportError)) {
    lines[1] = lines[1].replace(
      exportError,
      "$1 '$4' does not contain an export named '$3'."
    );
  }

  // TODO: Ideally we should write a custom ESLint formatter instead.

  // If the second line already includes a filename, and it's a warning,
  // this is likely coming from ESLint. Skip it because Webpack also prints it.
  // Let's omit that in this case.
  var BEGIN_ESLINT_FILENAME = String.fromCharCode(27) + '[4m';
  // Also filter out ESLint summaries for each file
  var BEGIN_ESLINT_WARNING_SUMMARY = String.fromCharCode(27) +
    '[33m' +
    String.fromCharCode(27) +
    '[1m' +
    String.fromCharCode(10006);
  var BEGIN_ESLINT_ERROR_SUMMARY = String.fromCharCode(27) +
    '[31m' +
    String.fromCharCode(27) +
    '[1m' +
    String.fromCharCode(10006);
  // ESLint puts separators like this between groups. We don't need them:
  var ESLINT_EMPTY_SEPARATOR = String.fromCharCode(27) +
    '[22m' +
    String.fromCharCode(27) +
    '[39m';
  // Go!
  lines = lines.filter(function(line) {
    if (line === ESLINT_EMPTY_SEPARATOR) {
      return false;
    }
    if (
      line.indexOf(BEGIN_ESLINT_FILENAME) === 0 ||
      line.indexOf(BEGIN_ESLINT_WARNING_SUMMARY) === 0 ||
      line.indexOf(BEGIN_ESLINT_ERROR_SUMMARY) === 0
    ) {
      return false;
    }
    return true;
  });

  // Prepend filename with an explanation.
  lines[0] =
    // Underline
    String.fromCharCode(27) +
    '[4m' +
    // Filename
    lines[0] +
    // End underline
    String.fromCharCode(27) +
    '[24m' +
    (isError ? ' contains errors.' : ' contains warnings.');

  // Reassemble the message.
  message = lines.join('\n');
  // Internal stacks are generally useless so we strip them... with the
  // exception of stacks containing `webpack:` because they're normally
  // from user code generated by WebPack. For more information see
  // https://github.com/facebookincubator/create-react-app/pull/1050
  message = message.replace(
    /^\s*at\s((?!webpack:).)*:\d+:\d+[\s\)]*(\n|$)/gm,
    ''
  ); // at ... ...:x:y

  return message.trim();
}

function formatWebpackMessages(json) {
  var formattedErrors = json.errors.map(function(message) {
    return formatMessage(message, true);
  });
  var formattedWarnings = json.warnings.map(function(message) {
    return formatMessage(message, false);
  });
  var result = {
    errors: formattedErrors,
    warnings: formattedWarnings,
  };
  if (result.errors.some(isLikelyASyntaxError)) {
    // If there are any syntax errors, show just them.
    // This prevents a confusing ESLint parsing error
    // preceding a much more useful Babel syntax error.
    result.errors = result.errors.filter(isLikelyASyntaxError);
  }
  return result;
}

module.exports = formatWebpackMessages;
<commit_msg>Omit ESLint warnings when there are ESLint errors (#2120)<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

// WARNING: this code is untranspiled and is used in browser too.
// Please make sure any changes are in ES5 or contribute a Babel compile step.

// Some custom utilities to prettify Webpack output.
// This is quite hacky and hopefully won't be needed when Webpack fixes this.
// https://github.com/webpack/webpack/issues/2878

var friendlySyntaxErrorLabel = 'Syntax error:';

function isLikelyASyntaxError(message) {
  return message.indexOf(friendlySyntaxErrorLabel) !== -1;
}

// Cleans up webpack error messages.
function formatMessage(message, isError) {
  var lines = message.split('\n');

  if (lines.length > 2 && lines[1] === '') {
    // Remove extra newline.
    lines.splice(1, 1);
  }

  // Remove webpack-specific loader notation from filename.
  // Before:
  // ./~/css-loader!./~/postcss-loader!./src/App.css
  // After:
  // ./src/App.css
  if (lines[0].lastIndexOf('!') !== -1) {
    lines[0] = lines[0].substr(lines[0].lastIndexOf('!') + 1);
  }

  lines = lines.filter(function(line) {
    // Webpack adds a list of entry points to warning messages:
    //  @ ./src/index.js
    //  @ multi react-scripts/~/react-dev-utils/webpackHotDevClient.js ...
    // It is misleading (and unrelated to the warnings) so we clean it up.
    // It is only useful for syntax errors but we have beautiful frames for them.
    return line.indexOf(' @ ') !== 0;
  });

  // line #0 is filename
  // line #1 is the main error message
  if (!lines[0] || !lines[1]) {
    return lines.join('\n');
  }

  // Cleans up verbose "module not found" messages for files and packages.
  if (lines[1].indexOf('Module not found: ') === 0) {
    lines = [
      lines[0],
      // Clean up message because "Module not found: " is descriptive enough.
      lines[1]
        .replace("Cannot resolve 'file' or 'directory' ", '')
        .replace('Cannot resolve module ', '')
        .replace('Error: ', ''),
    ];
  }

  // Cleans up syntax error messages.
  if (lines[1].indexOf('Module build failed: ') === 0) {
    lines[1] = lines[1].replace(
      'Module build failed: SyntaxError:',
      friendlySyntaxErrorLabel
    );
  }

  // Clean up export errors.
  // TODO: we should really send a PR to Webpack for this.
  var exportError = /\s*(.+?)\s*(")?export '(.+?)' was not found in '(.+?)'/;
  if (lines[1].match(exportError)) {
    lines[1] = lines[1].replace(
      exportError,
      "$1 '$4' does not contain an export named '$3'."
    );
  }

  // TODO: Ideally we should write a custom ESLint formatter instead.

  // If the second line already includes a filename, and it's a warning,
  // this is likely coming from ESLint. Skip it because Webpack also prints it.
  // Let's omit that in this case.
  var BEGIN_ESLINT_FILENAME = String.fromCharCode(27) + '[4m';
  // Also filter out ESLint summaries for each file
  var BEGIN_ESLINT_WARNING_SUMMARY = String.fromCharCode(27) +
    '[33m' +
    String.fromCharCode(27) +
    '[1m' +
    String.fromCharCode(10006);
  var BEGIN_ESLINT_ERROR_SUMMARY = String.fromCharCode(27) +
    '[31m' +
    String.fromCharCode(27) +
    '[1m' +
    String.fromCharCode(10006);
  // ESLint puts separators like this between groups. We don't need them:
  var ESLINT_EMPTY_SEPARATOR = String.fromCharCode(27) +
    '[22m' +
    String.fromCharCode(27) +
    '[39m';
  // Go!
  lines = lines.filter(function(line) {
    if (line === ESLINT_EMPTY_SEPARATOR) {
      return false;
    }
    if (
      line.indexOf(BEGIN_ESLINT_FILENAME) === 0 ||
      line.indexOf(BEGIN_ESLINT_WARNING_SUMMARY) === 0 ||
      line.indexOf(BEGIN_ESLINT_ERROR_SUMMARY) === 0
    ) {
      return false;
    }
    return true;
  });

  var ESLINT_WARNING_LABEL = String.fromCharCode(27) +
    '[33m' +
    'warning' +
    String.fromCharCode(27) +
    '[39m';
  // If there were errors, omit any warnings.
  if (isError) {
    lines = lines.filter(function(line) {
      return line.indexOf(ESLINT_WARNING_LABEL) === -1;
    });
  }

  // Prepend filename with an explanation.
  lines[0] =
    // Underline
    String.fromCharCode(27) +
    '[4m' +
    // Filename
    lines[0] +
    // End underline
    String.fromCharCode(27) +
    '[24m' +
    (isError ? ' contains errors.' : ' contains warnings.');

  // Reassemble the message.
  message = lines.join('\n');
  // Internal stacks are generally useless so we strip them... with the
  // exception of stacks containing `webpack:` because they're normally
  // from user code generated by WebPack. For more information see
  // https://github.com/facebookincubator/create-react-app/pull/1050
  message = message.replace(
    /^\s*at\s((?!webpack:).)*:\d+:\d+[\s\)]*(\n|$)/gm,
    ''
  ); // at ... ...:x:y

  return message.trim();
}

function formatWebpackMessages(json) {
  var formattedErrors = json.errors.map(function(message) {
    return formatMessage(message, true);
  });
  var formattedWarnings = json.warnings.map(function(message) {
    return formatMessage(message, false);
  });
  var result = {
    errors: formattedErrors,
    warnings: formattedWarnings,
  };
  if (result.errors.some(isLikelyASyntaxError)) {
    // If there are any syntax errors, show just them.
    // This prevents a confusing ESLint parsing error
    // preceding a much more useful Babel syntax error.
    result.errors = result.errors.filter(isLikelyASyntaxError);
  }
  return result;
}

module.exports = formatWebpackMessages;
<|endoftext|>


<commit_before>'use strict'

var request = require('../index')
  , server = require('./server')
  , tape = require('tape')

var s = server.createServer()

tape('setup', function(t) {
  s.listen(s.port, function() {
    t.end()
  })
})

tape('re-emit formData errors', function(t) {
  s.on('/', function(req, res) {
    res.writeHead(400)
    res.end()
    t.fail('The form-data error did not abort the request.')
  })

  request.post(s.url, function (err, res, body) {
    t.equal(err.message, 'form-data: Arrays are not supported.')
    setTimeout(function() {
      t.end()
    }, 10)
  }).form().append('field', ['value1', 'value2'])
})

tape('cleanup', function(t) {
  s.close(function() {
    t.end()
  })
})
<commit_msg>added a test case for setting content-length header value to NaN when using chunked HTTP response in form data.<commit_after>'use strict'

var request = require('../index')
  , server = require('./server')
  , tape = require('tape')

var s = server.createServer()

tape('setup', function(t) {
  s.listen(s.port, function() {
    t.end()
  })
})

tape('re-emit formData errors', function(t) {
  s.on('/', function(req, res) {
    res.writeHead(400)
    res.end()
    t.fail('The form-data error did not abort the request.')
  })

  request.post(s.url, function (err, res, body) {
    t.equal(err.message, 'form-data: Arrays are not supported.')
    setTimeout(function() {
      t.end()
    }, 10)
  }).form().append('field', ['value1', 'value2'])
})

tape('omit content-length header if the value is set to NaN', function(t) {

  // returns chunked HTTP response which is streamed to the 2nd HTTP request in the form data
  s.on('/chunky', server.createChunkResponse(
    ['some string',
      'some other string'
    ]))

  // accepts form data request
  s.on('/stream', function(req, resp) {
    req.on('data', function(chunk) {
      // consume the request body
    })
    req.on('end', function() {
      resp.writeHead(200)
      resp.end()
    })
  })

  var sendStreamRequest = function(stream) {
    request.post({
      uri: s.url + '/stream',
      formData: {
        param: stream
      }
    }, function(err, res) {
      t.error(err, 'request failed')
      t.end()
    })
  }

  request.get({
    uri: s.url + '/chunky',
  }).on('response', function(res) {
    sendStreamRequest(res)
  })
})

tape('cleanup', function(t) {
  s.close(function() {
    t.end()
  })
})<|endoftext|>


<commit_before>var mod;

mod = angular.module('on-scroll', []);

mod.value('THROTTLE_MILLISECONDS', null);

mod.directive('onScroll', ['$rootScope', '$window', '$timeout', 'THROTTLE_MILLISECONDS',
    function ($window, $timeout) {
        return {
            restrict: "A",
            link: function (scope, element, attr) {
                var window = angular.element($window);
                var scrollEnabled = true;
                //var origHeight = window[0].screen.height;
                //var height = (origHeight * 0.55);
                var lastPosition = 0;
                var repeat = false;
                var reset = true;
                var startingThreshold = attr.onScrollThreshold;
                var threshold = attr.onScrollThreshold;
                repeat = attr.onScrollRepeat;
                reset = attr.onScrollReset;
                // bind the digest cycle to be triggered by the scroll event
                // when it exceeds a threshold
                window.bind('scroll', function () {
                    if (scrollEnabled == true) {
                        scope.onScrollPosition = window[0].scrollY;
                        scope.$digest();
                        // console.log( scope.onScrollPosition );
                    }
                });
                //emit a message called scrollEnabled
                scope.$on('scrollEnabled', function () {
                    //console.log('message recieved' );
                    scrollEnabled = false;
                    scope.$eval(attr.onScrollTop);
                });

                scope.$watch(
                    function () {
                        //determine that we are scrolling down
                        if (scope.onScrollPosition > lastPosition) {
                            lastPosition = scope.onScrollPosition
                            //see if we have passed the threshold
                            if (scope.onScrollPosition >= threshold) {
                                // increment the threshold if we are repeating
                                if (repeat == true) {
                                    threshold += (threshold * 1.5);
                                }
                                // invoke the function passed into the 'whenScrolled' attribute
                                return attr.onScroll;
                            }
                            else return false;
                        }
                        if (scope.onScrollPosition < lastPosition) {
                            lastPosition = scope.onScrollPosition
                            if (scope.onScrollPosition <= startingThreshold) {
                                // reset the threshold if reset is true
                                if (reset == true) {
                                    threshold = startingThreshold;
                                }
                                // invoke the function passed into the 'whenScrolled' attribute
                                return attr.onScrollUnset;
                            }
                            else return false;
                        }
                        else return false;
                    },
                    function (newValue) {
                        // invoke the function passed into the 'whenScrolled' attribute
                        scope.$eval(newValue);
                    }
                );
            }
        }
    }]);
<commit_msg>Switch out incorrect scoping<commit_after>var mod;

mod = angular.module('on-scroll', []);

mod.value('THROTTLE_MILLISECONDS', null);

mod.directive('onScroll', ['$scope', '$window', '$timeout', 'THROTTLE_MILLISECONDS',
    function ($window, $timeout) {
        return {
            restrict: "A",
            link: function (scope, element, attr) {
                var window = angular.element($window);
                var scrollEnabled = true;
                //var origHeight = window[0].screen.height;
                //var height = (origHeight * 0.55);
                var lastPosition = 0;
                var repeat = false;
                var reset = true;
                var startingThreshold = attr.onScrollThreshold;
                var threshold = attr.onScrollThreshold;
                repeat = attr.onScrollRepeat;
                reset = attr.onScrollReset;
                // bind the digest cycle to be triggered by the scroll event
                // when it exceeds a threshold
                window.bind('scroll', function () {
                    if (scrollEnabled == true) {
                        scope.onScrollPosition = window[0].scrollY;
                        scope.$digest();
                        // console.log( scope.onScrollPosition );
                    }
                });
                //emit a message called scrollEnabled
                scope.$on('scrollEnabled', function () {
                    //console.log('message recieved' );
                    scrollEnabled = false;
                    scope.$eval(attr.onScrollTop);
                });

                scope.$watch(
                    function () {
                        //determine that we are scrolling down
                        if (scope.onScrollPosition > lastPosition) {
                            lastPosition = scope.onScrollPosition
                            //see if we have passed the threshold
                            if (scope.onScrollPosition >= threshold) {
                                // increment the threshold if we are repeating
                                if (repeat == true) {
                                    threshold += (threshold * 1.5);
                                }
                                // invoke the function passed into the 'whenScrolled' attribute
                                return attr.onScroll;
                            }
                            else return false;
                        }
                        if (scope.onScrollPosition < lastPosition) {
                            lastPosition = scope.onScrollPosition
                            if (scope.onScrollPosition <= startingThreshold) {
                                // reset the threshold if reset is true
                                if (reset == true) {
                                    threshold = startingThreshold;
                                }
                                // invoke the function passed into the 'whenScrolled' attribute
                                return attr.onScrollUnset;
                            }
                            else return false;
                        }
                        else return false;
                    },
                    function (newValue) {
                        // invoke the function passed into the 'whenScrolled' attribute
                        scope.$eval(newValue);
                    }
                );
            }
        }
    }]);
<|endoftext|>


<commit_before>/* global describe it */
var assert = require('assert')
var note = require('../note')

describe('music-notation/note', function () {
  it('get notes in scientific notation', function () {
    assert.equal(note('fx'), 'F##')
    assert.equal(note('fx/4'), 'F##')
    assert.equal(note('blah'), null)
    assert.equal(note(), null)
  })
})
<commit_msg>Remove note/index test<commit_after>/* global describe it */
var assert = require('assert')
var note = require('../note')

describe('music-notation/note', function () {
  it.skip('get notes in scientific notation', function () {
    assert.equal(note('fx'), 'F##')
    assert.equal(note('fx/4'), 'F##')
    assert.equal(note('blah'), null)
    assert.equal(note(), null)
  })
})
<|endoftext|>


<commit_before>const path = require('path')
const alias = require('rollup-plugin-alias')
const replace = require('rollup-plugin-replace')
const nodeResolve = require('rollup-plugin-node-resolve')
const commonjs = require('rollup-plugin-commonjs')
const requireContext = require('../lib/rollup-plugin-require-context')

const resolve = dir => path.resolve(__dirname, '../', dir)

module.exports = {
  input: 'packages/uni-stat/src/index.js',
  output: {
    file: 'packages/uni-stat/dist/index.js',
    format: 'es'
  },
  external: ['vue', '@dcloudio/uni-stat/package.json'],
  plugins: []
}
<commit_msg>chore(stat): lint<commit_after>module.exports = {
  input: 'packages/uni-stat/src/index.js',
  output: {
    file: 'packages/uni-stat/dist/index.js',
    format: 'es'
  },
  external: ['vue', '@dcloudio/uni-stat/package.json'],
  plugins: []
}
<|endoftext|>


<commit_before>import { GraphQLSchema } from 'meteor/nova:core';

// add these specific resolvers separately
const specificResolvers = {
  Post: {
    categories(post, args, context) {
      return post.categories ? context.Categories.find({_id: {$in: post.categories}}, { fields: context.getViewableFields(context.currentUser, context.Categories) }).fetch() : [];
    },
  },
  // TODO: fix this
  // Category: {
  //   parent(category, args, context) {
  //     return category.parent ? context.Categories.findOne({_id: category.parent }, { fields: context.getViewableFields(context.currentUser, context.Categories) }) : null;
  //   }
  // },
};
GraphQLSchema.addResolvers(specificResolvers);

// root resolvers: basic list, single, and total query resolvers
const resolvers = {

  list: {

    name: 'categoriesList',

    resolver(root, {terms}, context, info) {
      let {selector, options} = context.Categories.getParameters(terms);

      options.limit = terms.limit;
      options.skip = terms.offset;
      options.fields = context.getViewableFields(context.currentUser, context.Categories);

      return context.Categories.find(selector, options).fetch();
    },

  },

  single: {

    name: 'categoriesSingle',

    resolver(root, {documentId}, context) {
      return context.Categories.findOne({_id: documentId}, { fields: context.getViewableFields(context.currentUser, context.Categories) });
    },

  },

  total: {

    name: 'categoriesTotal',

    resolver(root, args, context) {
      return context.Categories.find().count();
    },

  }
};

export default resolvers;
<commit_msg>allow to query single category with its slug<commit_after>import { GraphQLSchema } from 'meteor/nova:core';

// add these specific resolvers separately
const specificResolvers = {
  Post: {
    categories(post, args, context) {
      return post.categories ? context.Categories.find({_id: {$in: post.categories}}, { fields: context.getViewableFields(context.currentUser, context.Categories) }).fetch() : [];
    },
  },
  // TODO: fix this
  // Category: {
  //   parent(category, args, context) {
  //     return category.parent ? context.Categories.findOne({_id: category.parent }, { fields: context.getViewableFields(context.currentUser, context.Categories) }) : null;
  //   }
  // },
};
GraphQLSchema.addResolvers(specificResolvers);

// root resolvers: basic list, single, and total query resolvers
const resolvers = {

  list: {

    name: 'categoriesList',

    resolver(root, {terms}, context, info) {
      let {selector, options} = context.Categories.getParameters(terms);

      options.limit = terms.limit;
      options.skip = terms.offset;
      options.fields = context.getViewableFields(context.currentUser, context.Categories);

      return context.Categories.find(selector, options).fetch();
    },

  },

  single: {

    name: 'categoriesSingle',

    resolver(root, {documentId, slug}, context) {
      const selector = documentId ? {_id: documentId} : {slug: slug};
      return context.Categories.findOne(selector, { fields: context.getViewableFields(context.currentUser, context.Categories) });
    },

  },

  total: {

    name: 'categoriesTotal',

    resolver(root, args, context) {
      return context.Categories.find().count();
    },

  }
};

export default resolvers;
<|endoftext|>


<commit_before>/* global config, fs, path, project */
/* jshint maxdepth: 6 */

module.exports = function(grunt) {
	grunt.registerTask('buildModules', function() {
		fs.readdirSync(config.paths.moduleSource).forEach(function(name) {
			var modulePath = config.paths.moduleSource + name,
				configFile = modulePath + '/module.json';

			// Ensure the child is a directory
			if (! fs.statSync(modulePath).isDirectory()) {
				return;
			}

			var module = fs.readJsonSync(configFile, {
				throws: false
			});

			// Validate the module.json file
			if (! module) {
				Wee.notify({
					title: 'Module Error',
					message: 'Missing or invalid module.json for "' + name + '" module.'
				}, 'fail', true);
			}

			var scriptRoot = modulePath + '/core/js/',
				moduleScript = [
					config.paths.temp + 'moduleView-' + name + '.js',
					scriptRoot + 'vendor/**/*.js',
					scriptRoot + 'init.js',
					scriptRoot + '**/*.js',
					'!' + scriptRoot + 'script.js'
				],
				vars = JSON.parse(JSON.stringify(config.style.vars)),
				less = fs.readFileSync(config.paths.wee + 'css/wee.module.less', 'utf8'),
				namespace = 'Wee',
				coreScript = [],
				globalScript = [],
				imports = [],
				namespaceOpen = '',
				namespaceClose = '';

			// Push default values into module array
			config.modules[name] = {
				autoload: module.autoload === true,
				namespace: false,
				tasks: false
			};

			// Reference core Less and inherit namespace if extension
			if (module.extension) {
				imports.push("@import (reference) 'wee.less';");

				namespaceOpen = config.style.namespaceOpen || '';
				namespaceClose = config.style.namespaceClose || '';
			}

			// Add core styling
			imports.push('@import (optional) "' + modulePath + '/core/css/screen.less";');

			if (module.style) {
				// Namespace mixins and reset
				if (module.style.core && typeof module.style.core.namespace === 'string') {
					namespaceOpen = module.style.core.namespace + ' {';
					namespaceClose = '}';
				}

				// Build additional style
				if (module.style.build) {
					Wee.$toArray(module.style.build).forEach(function(target) {
						imports.push('@import (less) "' + modulePath + '/' + target + '";');
					});
				}

				// Compile additional style
				if (module.style.compile) {
					for (var styleTarget in module.style.compile) {
						var styleTask = styleTarget.replace(/\./g, '-') + '-' + name + '-style',
							styleSources = Wee.$toArray(module.style.compile[styleTarget]),
							styleFiles = styleSources.map(function(source) {
								return Wee.buildPath(modulePath, source);
							});

						grunt.config.set('watch.' + styleTask, {
							files: styleFiles,
							tasks: [
								'less:' + styleTask
							]
						});

						grunt.config.set('less.' + styleTask, {
							files: [{
								dest: Wee.buildPath(config.paths.module + name, styleTarget),
								src: styleFiles
							}],
							options: {
								globalVars: {
									weePath: '"' + config.paths.weeTemp + '"'
								}
							}
						});

						config.style.tasks.push('less:' + styleTask);
						grunt.task.run('less:' + styleTask);
					}
				}
			}

			module.style = module.style || {};
			module.script = module.script || {};

			if (module.script) {
				// Set module namespace
				if (module.script.core && module.script.core.namespace) {
					namespace = module.script.core.namespace;
				}

				config.modules[name].namespace = namespace;

				// Set global data variables
				if (
					(module.data && Object.keys(module.data).length) ||
					(module.script.data && Object.keys(module.script.data).length)
				) {
					var configScriptVars = Wee.$extend(
						module.data || {},
						module.script.data || {}
					);

					globalScript.push(
						namespace + '.$set("' + name + '.global", ' +
						JSON.stringify(configScriptVars) + ');'
					);
				}

				// Inject global script
				if (globalScript.length) {
					var tempPath = config.paths.temp + name + '.global.js';

					fs.writeFileSync(tempPath, globalScript.join(''));
					moduleScript.unshift(tempPath);
				}

				// Build additional script
				if (module.script.build) {
					Wee.$toArray(module.script.build).forEach(function(source) {
						moduleScript.push(path.join(modulePath, source));
					});
				}

				// Include Core if referenced
				if (! module.autoload && module.script.core && module.script.core.enable) {
					var features = module.script.core.features,
						root = config.paths.wee + 'js/',
						chained = [];

					coreScript.push(root + 'wee.js');

					if (features.chain === true) {
						chained.push(root + 'wee.chain.js');
					}

					if (features.animate === true) {
						coreScript.push(root + 'wee.animate.js');

						if (features.chain === true) {
							chained.push(root + 'chain/wee.chain.animate.js');
						}
					}

					if (features.assets === true) {
						coreScript.push(root + 'wee.assets.js');
					}

					if (features.data === true) {
						coreScript.push(root + 'wee.data.js');
					}

					if (features.dom === true) {
						coreScript.push(root + 'wee.dom.js');

						if (features.chain === true) {
							chained.push(root + 'chain/wee.chain.dom.js');
						}
					}

					if (features.events === true) {
						coreScript.push(root + 'wee.events.js');

						if (features.chain === true) {
							chained.push(root + 'chain/wee.chain.events.js');
						}
					}

					if (features.history === true) {
						coreScript.push(root + 'wee.history.js');
					}

					if (features.routes === true) {
						coreScript.push(root + 'wee.routes.js');
					}

					if (features.screen === true) {
						coreScript.push(root + 'wee.screen.js');
					}

					if (features.touch === true) {
						coreScript.push(root + 'wee.touch.js');
					}

					if (features.view === true) {
						coreScript.push(root + 'wee.view.js');
						coreScript.push(root + 'wee.view.diff.js');

						if (features.chain === true) {
							chained.push(root + 'chain/wee.chain.view.js');
						}
					}

					coreScript = coreScript.concat(chained);
				}

				// Compile additional script
				if (module.script.compile) {
					for (var scriptTarget in module.script.compile) {
						var scriptTask = scriptTarget.replace(/\./g, '-') + '-' + name + '-script',
							scriptSources = Wee.$toArray(module.script.compile[scriptTarget]),
							scriptFiles = scriptSources.map(function(source) {
								return Wee.buildPath(modulePath, source);
							});

						grunt.config.set('watch.' + scriptTask, {
							files: scriptFiles,
							tasks: [
								'uglify:' + scriptTask
							]
						});

						grunt.config.set('uglify.' + scriptTask, {
							files: [{
								dest: Wee.buildPath(config.paths.module + name, scriptTarget),
								src: scriptFiles
							}]
						});

						grunt.task.run('uglify:' + scriptTask);
					}
				}
			}

			// Append primary script
			moduleScript.push(scriptRoot + 'script.js');

			// Write temporary file
			fs.writeFileSync(config.paths.temp + name + '.less',
				less.replace(/{{moduleName}}/g, name)
					.replace(/{{modulePath}}/g, modulePath)
					.replace('{{namespaceOpen}}', namespaceOpen)
					.replace('{{namespaceClose}}', namespaceClose)
					.replace('{{fontPath}}', '/' + project.paths.assets + '/modules/' + name + '/fonts/')
					.replace('{{imgPath}}', '/' + project.paths.assets + '/modules/' + name + '/img/')
					.replace('{{imports}}', imports.join('\n'))
			);

			// Set global data variables
			if (
				(module.data && Object.keys(module.data).length) ||
				(module.style && module.style.data && Object.keys(module.style.data).length)
			) {
				var configStyleVars = Wee.$extend(
					module.data || {},
					module.style.data || {}
				);

				for (var key in configStyleVars) {
					var value = configStyleVars[key];

					if (typeof value === 'string') {
						vars[key] = value;
					}
				}
			}

			// Create module style compile task
			var dest = module.autoload === true ?
				config.paths.temp + name + '.css' :
				config.paths.module + name + '/style.min.css';

			grunt.config.set('less.' + name, {
				files: [{
					dest: dest,
					src: config.paths.temp + name + '.less'
				}],
				options: {
					globalVars: {
						weePath: '"' + config.paths.weeTemp + '"'
					},
					modifyVars: vars
				}
			});

			config.style.tasks.push('less:' + name);

			grunt.config.set('watch.' + name + '-style', {
				files: modulePath + '/**/*.less',
				tasks: [
					'less:' + name,
					'concat:style'
				]
			});

			grunt.task.run('less:' + name);
			grunt.task.run('concat:style');

			if (module.autoload === true) {
				// Push temporary style to concat array
				config.style.concat.push(dest);

				// Add script paths to uglify
				config.script.build = config.script.build.concat(moduleScript);
			} else {
				var maps = [],
					tasks = [];

				// Process core script compilation
				if (coreScript.length) {
					grunt.config.set('uglify.' + name + '-core', {
						options: {
							wrap: namespace
						},
						files: [{
							dest: config.paths.temp + name + '-core.min.js',
							src: coreScript
						}]
					});

					grunt.task.run('uglify:' + name + '-core');

					grunt.config.set('uglify.' + name + '-build', {
						files: [{
							dest: config.paths.temp + name + '-build.min.js',
							src: moduleScript
						}]
					});

					tasks.push('uglify:' + name + '-build');

					// Concatenate module core and build
					grunt.config.set('concat.' + name + '-concat', {
						files: [{
							dest: config.paths.module + name + '/script.min.js',
							src: [
								config.paths.temp + name + '-core.min.js',
								config.paths.temp + name + '-build.min.js'
							]
						}]
					});

					tasks.push('concat:' + name + '-concat');

					config.modules[name].tasks = [
						'uglify:' + name + '-build',
						'concat:' + name + '-concat'
					];

					if (project.script.sourceMaps === true) {
						maps['uglify.' + name + '-core'] =
							path.join(config.paths.temp, name + '-core.js.map');
						maps['uglify.' + name + '-build'] =
							path.join(config.paths.temp, name + '-build.js.map');
						maps['concat.' + name + '-concat'] =
							path.join(config.paths.jsMaps, name + '.script.js.map');
					}
				} else {
					grunt.config.set('uglify.' + name, {
						files: [{
							dest: config.paths.module + name + '/script.min.js',
							src: moduleScript
						}]
					});

					tasks.push('uglify:' + name);

					config.modules[name].tasks = [
						'uglify:' + name
					];

					if (project.script.sourceMaps === true) {
						maps['uglify.' + name] =
							path.join(config.paths.jsMaps, name + '.script.js.map');
					}
				}

				if (maps.length) {
					Wee.addMaps(grunt, maps);
				}

				grunt.config.set('watch.' + name + '-script', {
					files: moduleScript,
					tasks: tasks
				});

				grunt.task.run(tasks);
			}
		});
	});
};<commit_msg>Ensure modules inherit chainable History build functionality<commit_after>/* global config, fs, path, project */
/* jshint maxdepth: 6 */

module.exports = function(grunt) {
	grunt.registerTask('buildModules', function() {
		fs.readdirSync(config.paths.moduleSource).forEach(function(name) {
			var modulePath = config.paths.moduleSource + name,
				configFile = modulePath + '/module.json';

			// Ensure the child is a directory
			if (! fs.statSync(modulePath).isDirectory()) {
				return;
			}

			var module = fs.readJsonSync(configFile, {
				throws: false
			});

			// Validate the module.json file
			if (! module) {
				Wee.notify({
					title: 'Module Error',
					message: 'Missing or invalid module.json for "' + name + '" module.'
				}, 'fail', true);
			}

			var scriptRoot = modulePath + '/core/js/',
				moduleScript = [
					config.paths.temp + 'moduleView-' + name + '.js',
					scriptRoot + 'vendor/**/*.js',
					scriptRoot + 'init.js',
					scriptRoot + '**/*.js',
					'!' + scriptRoot + 'script.js'
				],
				vars = JSON.parse(JSON.stringify(config.style.vars)),
				less = fs.readFileSync(config.paths.wee + 'css/wee.module.less', 'utf8'),
				namespace = 'Wee',
				coreScript = [],
				globalScript = [],
				imports = [],
				namespaceOpen = '',
				namespaceClose = '';

			// Push default values into module array
			config.modules[name] = {
				autoload: module.autoload === true,
				namespace: false,
				tasks: false
			};

			// Reference core Less and inherit namespace if extension
			if (module.extension) {
				imports.push("@import (reference) 'wee.less';");

				namespaceOpen = config.style.namespaceOpen || '';
				namespaceClose = config.style.namespaceClose || '';
			}

			// Add core styling
			imports.push('@import (optional) "' + modulePath + '/core/css/screen.less";');

			if (module.style) {
				// Namespace mixins and reset
				if (module.style.core && typeof module.style.core.namespace === 'string') {
					namespaceOpen = module.style.core.namespace + ' {';
					namespaceClose = '}';
				}

				// Build additional style
				if (module.style.build) {
					Wee.$toArray(module.style.build).forEach(function(target) {
						imports.push('@import (less) "' + modulePath + '/' + target + '";');
					});
				}

				// Compile additional style
				if (module.style.compile) {
					for (var styleTarget in module.style.compile) {
						var styleTask = styleTarget.replace(/\./g, '-') + '-' + name + '-style',
							styleSources = Wee.$toArray(module.style.compile[styleTarget]),
							styleFiles = styleSources.map(function(source) {
								return Wee.buildPath(modulePath, source);
							});

						grunt.config.set('watch.' + styleTask, {
							files: styleFiles,
							tasks: [
								'less:' + styleTask
							]
						});

						grunt.config.set('less.' + styleTask, {
							files: [{
								dest: Wee.buildPath(config.paths.module + name, styleTarget),
								src: styleFiles
							}],
							options: {
								globalVars: {
									weePath: '"' + config.paths.weeTemp + '"'
								}
							}
						});

						config.style.tasks.push('less:' + styleTask);
						grunt.task.run('less:' + styleTask);
					}
				}
			}

			module.style = module.style || {};
			module.script = module.script || {};

			if (module.script) {
				// Set module namespace
				if (module.script.core && module.script.core.namespace) {
					namespace = module.script.core.namespace;
				}

				config.modules[name].namespace = namespace;

				// Set global data variables
				if (
					(module.data && Object.keys(module.data).length) ||
					(module.script.data && Object.keys(module.script.data).length)
				) {
					var configScriptVars = Wee.$extend(
						module.data || {},
						module.script.data || {}
					);

					globalScript.push(
						namespace + '.$set("' + name + '.global", ' +
						JSON.stringify(configScriptVars) + ');'
					);
				}

				// Inject global script
				if (globalScript.length) {
					var tempPath = config.paths.temp + name + '.global.js';

					fs.writeFileSync(tempPath, globalScript.join(''));
					moduleScript.unshift(tempPath);
				}

				// Build additional script
				if (module.script.build) {
					Wee.$toArray(module.script.build).forEach(function(source) {
						moduleScript.push(path.join(modulePath, source));
					});
				}

				// Include Core if referenced
				if (! module.autoload && module.script.core && module.script.core.enable) {
					var features = module.script.core.features,
						root = config.paths.wee + 'js/',
						chained = [];

					coreScript.push(root + 'wee.js');

					if (features.chain === true) {
						chained.push(root + 'wee.chain.js');
					}

					if (features.animate === true) {
						coreScript.push(root + 'wee.animate.js');

						if (features.chain === true) {
							chained.push(root + 'chain/wee.chain.animate.js');
						}
					}

					if (features.assets === true) {
						coreScript.push(root + 'wee.assets.js');
					}

					if (features.data === true) {
						coreScript.push(root + 'wee.data.js');
					}

					if (features.dom === true) {
						coreScript.push(root + 'wee.dom.js');

						if (features.chain === true) {
							chained.push(root + 'chain/wee.chain.dom.js');
						}
					}

					if (features.events === true) {
						coreScript.push(root + 'wee.events.js');

						if (features.chain === true) {
							chained.push(root + 'chain/wee.chain.events.js');
						}
					}

					if (features.history === true) {
						coreScript.push(root + 'wee.history.js');

						if (features.chain === true) {
							chained.push(root + 'chain/wee.chain.history.js');
						}
					}

					if (features.routes === true) {
						coreScript.push(root + 'wee.routes.js');
					}

					if (features.screen === true) {
						coreScript.push(root + 'wee.screen.js');
					}

					if (features.touch === true) {
						coreScript.push(root + 'wee.touch.js');
					}

					if (features.view === true) {
						coreScript.push(root + 'wee.view.js');
						coreScript.push(root + 'wee.view.diff.js');

						if (features.chain === true) {
							chained.push(root + 'chain/wee.chain.view.js');
						}
					}

					coreScript = coreScript.concat(chained);
				}

				// Compile additional script
				if (module.script.compile) {
					for (var scriptTarget in module.script.compile) {
						var scriptTask = scriptTarget.replace(/\./g, '-') + '-' + name + '-script',
							scriptSources = Wee.$toArray(module.script.compile[scriptTarget]),
							scriptFiles = scriptSources.map(function(source) {
								return Wee.buildPath(modulePath, source);
							});

						grunt.config.set('watch.' + scriptTask, {
							files: scriptFiles,
							tasks: [
								'uglify:' + scriptTask
							]
						});

						grunt.config.set('uglify.' + scriptTask, {
							files: [{
								dest: Wee.buildPath(config.paths.module + name, scriptTarget),
								src: scriptFiles
							}]
						});

						grunt.task.run('uglify:' + scriptTask);
					}
				}
			}

			// Append primary script
			moduleScript.push(scriptRoot + 'script.js');

			// Write temporary file
			fs.writeFileSync(config.paths.temp + name + '.less',
				less.replace(/{{moduleName}}/g, name)
					.replace(/{{modulePath}}/g, modulePath)
					.replace(/{{standalone}}/g, module.standalone === true)
					.replace('{{namespaceOpen}}', namespaceOpen)
					.replace('{{namespaceClose}}', namespaceClose)
					.replace('{{fontPath}}', '/' + project.paths.assets + '/modules/' + name + '/fonts/')
					.replace('{{imgPath}}', '/' + project.paths.assets + '/modules/' + name + '/img/')
					.replace('{{imports}}', imports.join('\n'))
			);

			// Set global data variables
			if (
				(module.data && Object.keys(module.data).length) ||
				(module.style && module.style.data && Object.keys(module.style.data).length)
			) {
				var configStyleVars = Wee.$extend(
					module.data || {},
					module.style.data || {}
				);

				for (var key in configStyleVars) {
					var value = configStyleVars[key];

					if (typeof value === 'string') {
						vars[key] = value;
					}
				}
			}

			// Create module style compile task
			var dest = module.autoload === true ?
				config.paths.temp + name + '.css' :
				config.paths.module + name + '/style.min.css';

			grunt.config.set('less.' + name, {
				files: [{
					dest: dest,
					src: config.paths.temp + name + '.less'
				}],
				options: {
					globalVars: {
						weePath: '"' + config.paths.weeTemp + '"'
					},
					modifyVars: vars
				}
			});

			config.style.tasks.push('less:' + name);

			grunt.config.set('watch.' + name + '-style', {
				files: modulePath + '/**/*.less',
				tasks: [
					'less:' + name,
					'concat:style'
				]
			});

			grunt.task.run('less:' + name);
			grunt.task.run('concat:style');

			if (module.autoload === true) {
				// Push temporary style to concat array
				config.style.concat.push(dest);

				// Add script paths to uglify
				config.script.build = config.script.build.concat(moduleScript);
			} else {
				var maps = [],
					tasks = [];

				// Process core script compilation
				if (coreScript.length) {
					grunt.config.set('uglify.' + name + '-core', {
						options: {
							wrap: namespace
						},
						files: [{
							dest: config.paths.temp + name + '-core.min.js',
							src: coreScript
						}]
					});

					grunt.task.run('uglify:' + name + '-core');

					grunt.config.set('uglify.' + name + '-build', {
						files: [{
							dest: config.paths.temp + name + '-build.min.js',
							src: moduleScript
						}]
					});

					tasks.push('uglify:' + name + '-build');

					// Concatenate module core and build
					grunt.config.set('concat.' + name + '-concat', {
						files: [{
							dest: config.paths.module + name + '/script.min.js',
							src: [
								config.paths.temp + name + '-core.min.js',
								config.paths.temp + name + '-build.min.js'
							]
						}]
					});

					tasks.push('concat:' + name + '-concat');

					config.modules[name].tasks = [
						'uglify:' + name + '-build',
						'concat:' + name + '-concat'
					];

					if (project.script.sourceMaps === true) {
						maps['uglify.' + name + '-core'] =
							path.join(config.paths.temp, name + '-core.js.map');
						maps['uglify.' + name + '-build'] =
							path.join(config.paths.temp, name + '-build.js.map');
						maps['concat.' + name + '-concat'] =
							path.join(config.paths.jsMaps, name + '.script.js.map');
					}
				} else {
					grunt.config.set('uglify.' + name, {
						files: [{
							dest: config.paths.module + name + '/script.min.js',
							src: moduleScript
						}]
					});

					tasks.push('uglify:' + name);

					config.modules[name].tasks = [
						'uglify:' + name
					];

					if (project.script.sourceMaps === true) {
						maps['uglify.' + name] =
							path.join(config.paths.jsMaps, name + '.script.js.map');
					}
				}

				if (maps.length) {
					Wee.addMaps(grunt, maps);
				}

				grunt.config.set('watch.' + name + '-script', {
					files: moduleScript,
					tasks: tasks
				});

				grunt.task.run(tasks);
			}
		});
	});
};<|endoftext|>


<commit_before>function createCollection() {

  var publishTime, collectionId, collectionDate, releaseUri;
  collectionId = $('#collectionname').val();
  var publishType = $('input[name="publishType"]:checked').val();
  var scheduleType = $('input[name="scheduleType"]:checked').val();

  if (publishType === 'scheduled') {
    publishTime  = parseInt($('#hour').val()) + parseInt($('#min').val());
    var toIsoDate = $('#date').datepicker("getDate");
    collectionDate = new Date(parseInt(new Date(toIsoDate).getTime()) + publishTime).toISOString();
  } else {
    collectionDate  = null;
  };

  if (scheduleType === 'release' && publishType === 'scheduled') {
    releaseUri  = $('#collection-release').val();
  } else {
    releaseUri  = null;
  };

  // inline tests
  if (collectionId === '') {
    alert('This is not a valid collection name');
    return true;
  } if (collectionId.match(/\./)) {
    alert('This is not a valid collection name. You can not use dots');
    return true;
  } if ((publishType === 'scheduled') && (scheduleType === 'custom')  && (isValidDate(new Date(collectionDate)))) {
    alert('This is not a valid date');
    return true;
  } if ((publishType === 'scheduled') && (scheduleType === 'custom') && (Date.parse(collectionDate) < new Date())) {
    alert('This is not a valid date');
    return true;
  } else {
    // Create the collection
    $.ajax({
      url: "/zebedee/collection",
      dataType: 'json',
      contentType: 'application/json',
      type: 'POST',
      data: JSON.stringify({name: collectionId, type: publishType, publishDate: collectionDate, releaseUri: releaseUri}),
      success: function (collection) {
        Florence.setActiveCollection(collection);
        createWorkspace('', collection.id, 'browse');
      },
      error: function (response) {
        if(response.status === 409) {
          alert(response.responseJSON.message);
        }
        else {
          handleApiError(response);
        }
      }
    });
  }
}

function isValidDate(d) {
  if (!isNaN(d.getTime()))
    {return false;}
  else
    {return true;}
}

<commit_msg>Remove console logging.<commit_after>function createCollection() {

  var publishTime, collectionId, collectionDate, releaseUri;
  collectionId = $('#collectionname').val();
  var publishType = $('input[name="publishType"]:checked').val();
  var scheduleType = $('input[name="scheduleType"]:checked').val();

  console.log('publish type: ' + publishType);
  console.log('schedule type: ' + scheduleType);

  if (publishType === 'scheduled') {
    publishTime  = parseInt($('#hour').val()) + parseInt($('#min').val());
    var toIsoDate = $('#date').datepicker("getDate");
    collectionDate = new Date(parseInt(new Date(toIsoDate).getTime()) + publishTime).toISOString();
  } else {
    collectionDate  = null;
  };

  if (scheduleType === 'release' && publishType === 'scheduled') {
    releaseUri  = $('#collection-release').val();
  } else {
    releaseUri  = null;
  };

  // inline tests
  if (collectionId === '') {
    alert('This is not a valid collection name');
    return true;
  } if (collectionId.match(/\./)) {
    alert('This is not a valid collection name. You can not use dots');
    return true;
  } if ((publishType === 'scheduled') && (scheduleType === 'custom')  && (isValidDate(new Date(collectionDate)))) {
    alert('This is not a valid date');
    return true;
  } if ((publishType === 'scheduled') && (scheduleType === 'custom') && (Date.parse(collectionDate) < new Date())) {
    alert('This is not a valid date');
    return true;
  } else {
    // Create the collection
    $.ajax({
      url: "/zebedee/collection",
      dataType: 'json',
      contentType: 'application/json',
      type: 'POST',
      data: JSON.stringify({name: collectionId, type: publishType, publishDate: collectionDate, releaseUri: releaseUri}),
      success: function (collection) {
        Florence.setActiveCollection(collection);
        createWorkspace('', collection.id, 'browse');
      },
      error: function (response) {
        if(response.status === 409) {
          alert(response.responseJSON.message);
        }
        else {
          handleApiError(response);
        }
      }
    });
  }
}

function isValidDate(d) {
  if (!isNaN(d.getTime()))
    {return false;}
  else
    {return true;}
}

<|endoftext|>


<commit_before>/* global Prism */

(() => {
  const reactVersion = '17.0.2';
  let flavor = getFlavor();
  let count = 1;

  // Sync flavor UI on page load
  setFlavor(getFlavor());

  if (!window.$docsify) {
    throw new Error('Docsify must be loaded before installing this plugin.');
  }

  function convertModuleLinks(html) {
    const version = sessionStorage.getItem('sl-version');

    html = html
      .replace(/@shoelace-style\/shoelace/g, `https://cdn.skypack.dev/@shoelace-style/shoelace@${version}`)
      .replace(/from 'react'/g, `from 'https://cdn.skypack.dev/react@${reactVersion}'`)
      .replace(/from "react"/g, `from "https://cdn.skypack.dev/react@${reactVersion}"`);

    return html;
  }

  function getAdjacentExample(name, pre) {
    let currentPre = pre.nextElementSibling;

    while (currentPre?.tagName.toLowerCase() === 'pre') {
      if (currentPre?.getAttribute('data-lang').split(' ').includes(name)) {
        return currentPre;
      }

      currentPre = currentPre.nextElementSibling;
    }

    return null;
  }

  function runScript(script) {
    const newScript = document.createElement('script');

    if (script.type === 'module') {
      newScript.type = 'module';
      newScript.textContent = script.innerHTML;
    } else {
      newScript.appendChild(document.createTextNode(`(() => { ${script.innerHTML} })();`));
    }

    script.parentNode.replaceChild(newScript, script);
  }

  function getFlavor() {
    return localStorage.getItem('flavor') || 'html';
  }

  function setFlavor(newFlavor) {
    flavor = ['html', 'react'].includes(newFlavor) ? newFlavor : 'html';
    localStorage.setItem('flavor', flavor);

    // Set the flavor class on the body
    document.body.classList.toggle('flavor-html', flavor === 'html');
    document.body.classList.toggle('flavor-react', flavor === 'react');
  }

  window.$docsify.plugins.push(hook => {
    // Convert code blocks to previews
    hook.afterEach((html, next) => {
      const domParser = new DOMParser();
      const doc = domParser.parseFromString(html, 'text/html');

      const htmlButton = `
        <button
          type="button"
          title="Show HTML code"
          class="code-block__button code-block__button--html ${flavor === 'html' ? 'code-block__button--selected' : ''}"
        >
          HTML
        </button>
      `;

      const reactButton = `
        <button
          type="button"
          title="Show React code"
          class="code-block__button code-block__button--react ${
            flavor === 'react' ? 'code-block__button--selected' : ''
          }"
        >
          React
        </button>
      `;

      const codePenButton = `
        <button type="button" class="code-block__button code-block__button--codepen" title="Edit on CodePen">
          <svg
            width="138"
            height="26"
            viewBox="0 0 138 26"
            fill="none"
            stroke="currentColor"
            stroke-width="2.3"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <path d="M80 6h-9v14h9 M114 6h-9 v14h9 M111 13h-6 M77 13h-6 M122 20V6l11 14V6 M22 16.7L33 24l11-7.3V9.3L33 2L22 9.3V16.7z M44 16.7L33 9.3l-11 7.4 M22 9.3l11 7.3 l11-7.3 M33 2v7.3 M33 16.7V24 M88 14h6c2.2 0 4-1.8 4-4s-1.8-4-4-4h-6v14 M15 8c-1.3-1.3-3-2-5-2c-4 0-7 3-7 7s3 7 7 7 c2 0 3.7-0.8 5-2 M64 13c0 4-3 7-7 7h-5V6h5C61 6 64 9 64 13z" />
          </svg>
        </button>
      `;

      [...doc.querySelectorAll('code[class^="lang-"]')].forEach(code => {
        if (code.classList.contains('preview')) {
          const isExpanded = code.classList.contains('expanded');
          const pre = code.closest('pre');
          const sourceGroupId = `code-block-source-group-${count}`;
          const toggleId = `code-block-toggle-${count}`;
          const reactPre = getAdjacentExample('react', pre);
          const hasReact = reactPre !== null;

          pre.setAttribute('data-lang', pre.getAttribute('data-lang').replace(/ preview$/, ''));
          pre.setAttribute('aria-labelledby', toggleId);

          const codeBlock = `

                ${code.textContent}

                  <sl-icon name="grip-vertical"></sl-icon>

                  ${pre.outerHTML}

                ${
                  hasReact
                    ? `

                    ${reactPre.outerHTML}

                `
                    : ''
                }

                ${hasReact ? ` ${htmlButton} ${reactButton} ` : ''}

                <button
                  type="button"
                  class="code-block__button code-block__toggle"
                  aria-expanded="${isExpanded ? 'true' : 'false'}"
                  aria-controls="${sourceGroupId}"
                >
                  Source
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  >
                    <polyline points="6 9 12 15 18 9"></polyline>
                  </svg>
                </button>

                ${!code.classList.contains('no-codepen') ? codePenButton : ''}

          `;

          pre.replaceWith(domParser.parseFromString(codeBlock, 'text/html').body);
          reactPre?.remove();

          count++;
        }
      });

      // Force the highlighter to run again so JSX fields get highlighted properly
      requestAnimationFrame(() => Prism.highlightAll());

      next(doc.body.innerHTML);
    });

    // After the page is done loading, force scripts in previews to execute
    hook.doneEach(() => {
      [...document.querySelectorAll('.code-block__preview script')].map(script => runScript(script));
    });

    // Horizontal resizing
    hook.doneEach(() => {
      [...document.querySelectorAll('.code-block__preview')].forEach(preview => {
        const resizer = preview.querySelector('.code-block__resizer');
        let startX;
        let startWidth;

        function dragStart(event) {
          startX = event.changedTouches ? event.changedTouches[0].pageX : event.clientX;
          startWidth = parseInt(document.defaultView.getComputedStyle(preview).width, 10);
          preview.classList.add('code-block__preview--dragging');
          event.preventDefault();
          document.documentElement.addEventListener('mousemove', dragMove);
          document.documentElement.addEventListener('touchmove', dragMove);
          document.documentElement.addEventListener('mouseup', dragStop);
          document.documentElement.addEventListener('touchend', dragStop);
        }

        function dragMove(event) {
          setWidth(startWidth + (event.changedTouches ? event.changedTouches[0].pageX : event.pageX) - startX);
        }

        function dragStop() {
          preview.classList.remove('code-block__preview--dragging');
          document.documentElement.removeEventListener('mousemove', dragMove);
          document.documentElement.removeEventListener('touchmove', dragMove);
          document.documentElement.removeEventListener('mouseup', dragStop);
          document.documentElement.removeEventListener('touchend', dragStop);
        }

        function setWidth(width) {
          preview.style.width = `${width}px`;
        }

        resizer.addEventListener('mousedown', dragStart);
        resizer.addEventListener('touchstart', dragStart, { passive: true });
      }, false);
    });
  });

  // Toggle source mode
  document.addEventListener('click', event => {
    const button = event.target.closest('button');

    if (button?.classList.contains('code-block__button--html')) {
      setFlavor('html');
    } else if (button?.classList.contains('code-block__button--react')) {
      setFlavor('react');
    } else {
      return;
    }

    // Update flavor buttons
    [...document.querySelectorAll('.code-block')].forEach(codeBlock => {
      codeBlock
        .querySelector('.code-block__button--html')
        ?.classList.toggle('code-block__button--selected', flavor === 'html');
      codeBlock
        .querySelector('.code-block__button--react')
        ?.classList.toggle('code-block__button--selected', flavor === 'react');
    });
  });

  // Expand and collapse code blocks
  document.addEventListener('click', event => {
    const toggle = event.target.closest('.code-block__toggle');
    if (toggle) {
      const codeBlock = event.target.closest('.code-block');
      codeBlock.classList.toggle('code-block--expanded');
      event.target.setAttribute('aria-expanded', codeBlock.classList.contains('code-block--expanded'));
    }
  });

  // Show pulse when copying
  document.addEventListener('click', event => {
    const button = event.target.closest('.docsify-copy-code-button');
    if (button) {
      button.classList.remove('copied');
      requestAnimationFrame(() => {
        button.addEventListener('animationend', () => button.classList.remove('copied'), { once: true });
        button.classList.add('copied');
      });
    }
  });

  // Open in CodePen
  document.addEventListener('click', event => {
    const button = event.target.closest('button');
    const version = sessionStorage.getItem('sl-version');

    if (button?.classList.contains('code-block__button--codepen')) {
      const codeBlock = button.closest('.code-block');
      const htmlExample = codeBlock.querySelector('.code-block__source--html > pre > code')?.textContent;
      const reactExample = codeBlock.querySelector('.code-block__source--react > pre > code')?.textContent;
      const isReact = flavor === 'react' && typeof reactExample === 'string';
      const theme = localStorage.getItem('theme');
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      const isDark = theme === 'dark' || (theme === 'auto' && prefersDark);
      const editors = isReact ? '0010' : '1000';
      let htmlTemplate = '';
      let jsTemplate = '';
      let cssTemplate = '';

      const form = document.createElement('form');
      form.action = 'https://codepen.io/pen/define';
      form.method = 'POST';
      form.target = '_blank';

      // HTML templates
      if (!isReact) {
        htmlTemplate =
          `<script type="module" src="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@${version}/dist/shoelace.js"></script>\n` +
          `\n${htmlExample}`;
        jsTemplate = '';
      }

      // React templates
      if (isReact) {
        htmlTemplate = '

';
        jsTemplate =
          `import React from 'https://cdn.skypack.dev/react@${reactVersion}';\n` +
          `import ReactDOM from 'https://cdn.skypack.dev/react-dom@${reactVersion}';\n` +
          `import { setBasePath } from 'https://cdn.skypack.dev/@shoelace-style/shoelace@${version}/dist/utilities/base-path';\n` +
          `\n` +
          `// Set the base path for Shoelace assets\n` +
          `setBasePath('https://cdn.skypack.dev/@shoelace-style/shoelace@${version}/dist/')\n` +
          `\n${convertModuleLinks(reactExample)}\n` +
          `\n` +
          `ReactDOM.render(<App />, document.getElementById('root'));`;
      }

      // CSS templates
      cssTemplate =
        `@import 'https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@${version}/dist/themes/${
          isDark ? 'dark' : 'light'
        }.css';\n` +
        '\n' +
        'body {\n' +
        '  font: 16px sans-serif;\n' +
        '  background-color: var(--sl-color-neutral-0);\n' +
        '  color: var(--sl-color-neutral-900);\n' +
        '  padding: 1rem;\n' +
        '}';

      // Docs: https://blog.codepen.io/documentation/prefill/
      const data = {
        title: '',
        description: '',
        tags: ['shoelace', 'web components'],
        editors,
        head: `<meta name="viewport" content="width=device-width">`,
        html_classes: `sl-theme-${isDark ? 'dark' : 'light'}`,
        css_external: ``,
        js_external: ``,
        js_module: true,
        js_pre_processor: isReact ? 'babel' : 'none',
        html: htmlTemplate,
        css: cssTemplate,
        js: jsTemplate
      };

      const input = document.createElement('input');
      input.type = 'hidden';
      input.name = 'data';
      input.value = JSON.stringify(data);
      form.append(input);

      document.body.append(form);
      form.submit();
      form.remove();
    }
  });
})();
<commit_msg>move controls and show code when clicking<commit_after>/* global Prism */

(() => {
  const reactVersion = '17.0.2';
  let flavor = getFlavor();
  let count = 1;

  // Sync flavor UI on page load
  setFlavor(getFlavor());

  if (!window.$docsify) {
    throw new Error('Docsify must be loaded before installing this plugin.');
  }

  function convertModuleLinks(html) {
    const version = sessionStorage.getItem('sl-version');

    html = html
      .replace(/@shoelace-style\/shoelace/g, `https://cdn.skypack.dev/@shoelace-style/shoelace@${version}`)
      .replace(/from 'react'/g, `from 'https://cdn.skypack.dev/react@${reactVersion}'`)
      .replace(/from "react"/g, `from "https://cdn.skypack.dev/react@${reactVersion}"`);

    return html;
  }

  function getAdjacentExample(name, pre) {
    let currentPre = pre.nextElementSibling;

    while (currentPre?.tagName.toLowerCase() === 'pre') {
      if (currentPre?.getAttribute('data-lang').split(' ').includes(name)) {
        return currentPre;
      }

      currentPre = currentPre.nextElementSibling;
    }

    return null;
  }

  function runScript(script) {
    const newScript = document.createElement('script');

    if (script.type === 'module') {
      newScript.type = 'module';
      newScript.textContent = script.innerHTML;
    } else {
      newScript.appendChild(document.createTextNode(`(() => { ${script.innerHTML} })();`));
    }

    script.parentNode.replaceChild(newScript, script);
  }

  function getFlavor() {
    return localStorage.getItem('flavor') || 'html';
  }

  function setFlavor(newFlavor) {
    flavor = ['html', 'react'].includes(newFlavor) ? newFlavor : 'html';
    localStorage.setItem('flavor', flavor);

    // Set the flavor class on the body
    document.body.classList.toggle('flavor-html', flavor === 'html');
    document.body.classList.toggle('flavor-react', flavor === 'react');
  }

  window.$docsify.plugins.push(hook => {
    // Convert code blocks to previews
    hook.afterEach((html, next) => {
      const domParser = new DOMParser();
      const doc = domParser.parseFromString(html, 'text/html');

      const htmlButton = `
        <button
          type="button"
          title="Show HTML code"
          class="code-block__button code-block__button--html ${flavor === 'html' ? 'code-block__button--selected' : ''}"
        >
          HTML
        </button>
      `;

      const reactButton = `
        <button
          type="button"
          title="Show React code"
          class="code-block__button code-block__button--react ${
            flavor === 'react' ? 'code-block__button--selected' : ''
          }"
        >
          React
        </button>
      `;

      const codePenButton = `
        <button type="button" class="code-block__button code-block__button--codepen" title="Edit on CodePen">
          <svg
            width="138"
            height="26"
            viewBox="0 0 138 26"
            fill="none"
            stroke="currentColor"
            stroke-width="2.3"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <path d="M80 6h-9v14h9 M114 6h-9 v14h9 M111 13h-6 M77 13h-6 M122 20V6l11 14V6 M22 16.7L33 24l11-7.3V9.3L33 2L22 9.3V16.7z M44 16.7L33 9.3l-11 7.4 M22 9.3l11 7.3 l11-7.3 M33 2v7.3 M33 16.7V24 M88 14h6c2.2 0 4-1.8 4-4s-1.8-4-4-4h-6v14 M15 8c-1.3-1.3-3-2-5-2c-4 0-7 3-7 7s3 7 7 7 c2 0 3.7-0.8 5-2 M64 13c0 4-3 7-7 7h-5V6h5C61 6 64 9 64 13z" />
          </svg>
        </button>
      `;

      [...doc.querySelectorAll('code[class^="lang-"]')].forEach(code => {
        if (code.classList.contains('preview')) {
          const isExpanded = code.classList.contains('expanded');
          const pre = code.closest('pre');
          const sourceGroupId = `code-block-source-group-${count}`;
          const toggleId = `code-block-toggle-${count}`;
          const reactPre = getAdjacentExample('react', pre);
          const hasReact = reactPre !== null;

          pre.setAttribute('data-lang', pre.getAttribute('data-lang').replace(/ preview$/, ''));
          pre.setAttribute('aria-labelledby', toggleId);

          const codeBlock = `

                ${code.textContent}

                  <sl-icon name="grip-vertical"></sl-icon>

                  ${pre.outerHTML}

                ${
                  hasReact
                    ? `

                    ${reactPre.outerHTML}

                `
                    : ''
                }

                <button
                  type="button"
                  class="code-block__button code-block__toggle"
                  aria-expanded="${isExpanded ? 'true' : 'false'}"
                  aria-controls="${sourceGroupId}"
                >
                  Source
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  >
                    <polyline points="6 9 12 15 18 9"></polyline>
                  </svg>
                </button>

                ${hasReact ? ` ${htmlButton} ${reactButton} ` : ''}

                ${!code.classList.contains('no-codepen') ? codePenButton : ''}

          `;

          pre.replaceWith(domParser.parseFromString(codeBlock, 'text/html').body);
          reactPre?.remove();

          count++;
        }
      });

      // Force the highlighter to run again so JSX fields get highlighted properly
      requestAnimationFrame(() => Prism.highlightAll());

      next(doc.body.innerHTML);
    });

    // After the page is done loading, force scripts in previews to execute
    hook.doneEach(() => {
      [...document.querySelectorAll('.code-block__preview script')].map(script => runScript(script));
    });

    // Horizontal resizing
    hook.doneEach(() => {
      [...document.querySelectorAll('.code-block__preview')].forEach(preview => {
        const resizer = preview.querySelector('.code-block__resizer');
        let startX;
        let startWidth;

        function dragStart(event) {
          startX = event.changedTouches ? event.changedTouches[0].pageX : event.clientX;
          startWidth = parseInt(document.defaultView.getComputedStyle(preview).width, 10);
          preview.classList.add('code-block__preview--dragging');
          event.preventDefault();
          document.documentElement.addEventListener('mousemove', dragMove);
          document.documentElement.addEventListener('touchmove', dragMove);
          document.documentElement.addEventListener('mouseup', dragStop);
          document.documentElement.addEventListener('touchend', dragStop);
        }

        function dragMove(event) {
          setWidth(startWidth + (event.changedTouches ? event.changedTouches[0].pageX : event.pageX) - startX);
        }

        function dragStop() {
          preview.classList.remove('code-block__preview--dragging');
          document.documentElement.removeEventListener('mousemove', dragMove);
          document.documentElement.removeEventListener('touchmove', dragMove);
          document.documentElement.removeEventListener('mouseup', dragStop);
          document.documentElement.removeEventListener('touchend', dragStop);
        }

        function setWidth(width) {
          preview.style.width = `${width}px`;
        }

        resizer.addEventListener('mousedown', dragStart);
        resizer.addEventListener('touchstart', dragStart, { passive: true });
      }, false);
    });
  });

  // Toggle source mode
  document.addEventListener('click', event => {
    const button = event.target.closest('.code-block__button');
    const codeBlock = button?.closest('.code-block');

    if (button?.classList.contains('code-block__button--html')) {
      // Show HTML
      setFlavor('html');
      toggleSource(codeBlock, true);
    } else if (button?.classList.contains('code-block__button--react')) {
      // Show React
      setFlavor('react');
      toggleSource(codeBlock, true);
    } else if (button?.classList.contains('code-block__toggle')) {
      // Toggle source
      toggleSource(codeBlock);
    } else {
      return;
    }

    // Update flavor buttons
    [...document.querySelectorAll('.code-block')].forEach(cb => {
      cb.querySelector('.code-block__button--html')?.classList.toggle(
        'code-block__button--selected',
        flavor === 'html'
      );
      cb.querySelector('.code-block__button--react')?.classList.toggle(
        'code-block__button--selected',
        flavor === 'react'
      );
    });
  });

  function toggleSource(codeBlock, force) {
    const toggle = codeBlock.querySelector('.code-block__toggle');

    if (toggle) {
      codeBlock.classList.toggle('code-block--expanded', force === undefined ? undefined : force);
      event.target.setAttribute('aria-expanded', codeBlock.classList.contains('code-block--expanded'));
    }
  }

  // Show pulse when copying
  document.addEventListener('click', event => {
    const button = event.target.closest('.docsify-copy-code-button');
    if (button) {
      button.classList.remove('copied');
      requestAnimationFrame(() => {
        button.addEventListener('animationend', () => button.classList.remove('copied'), { once: true });
        button.classList.add('copied');
      });
    }
  });

  // Open in CodePen
  document.addEventListener('click', event => {
    const button = event.target.closest('button');
    const version = sessionStorage.getItem('sl-version');

    if (button?.classList.contains('code-block__button--codepen')) {
      const codeBlock = button.closest('.code-block');
      const htmlExample = codeBlock.querySelector('.code-block__source--html > pre > code')?.textContent;
      const reactExample = codeBlock.querySelector('.code-block__source--react > pre > code')?.textContent;
      const isReact = flavor === 'react' && typeof reactExample === 'string';
      const theme = localStorage.getItem('theme');
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      const isDark = theme === 'dark' || (theme === 'auto' && prefersDark);
      const editors = isReact ? '0010' : '1000';
      let htmlTemplate = '';
      let jsTemplate = '';
      let cssTemplate = '';

      const form = document.createElement('form');
      form.action = 'https://codepen.io/pen/define';
      form.method = 'POST';
      form.target = '_blank';

      // HTML templates
      if (!isReact) {
        htmlTemplate =
          `<script type="module" src="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@${version}/dist/shoelace.js"></script>\n` +
          `\n${htmlExample}`;
        jsTemplate = '';
      }

      // React templates
      if (isReact) {
        htmlTemplate = '

';
        jsTemplate =
          `import React from 'https://cdn.skypack.dev/react@${reactVersion}';\n` +
          `import ReactDOM from 'https://cdn.skypack.dev/react-dom@${reactVersion}';\n` +
          `import { setBasePath } from 'https://cdn.skypack.dev/@shoelace-style/shoelace@${version}/dist/utilities/base-path';\n` +
          `\n` +
          `// Set the base path for Shoelace assets\n` +
          `setBasePath('https://cdn.skypack.dev/@shoelace-style/shoelace@${version}/dist/')\n` +
          `\n${convertModuleLinks(reactExample)}\n` +
          `\n` +
          `ReactDOM.render(<App />, document.getElementById('root'));`;
      }

      // CSS templates
      cssTemplate =
        `@import 'https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@${version}/dist/themes/${
          isDark ? 'dark' : 'light'
        }.css';\n` +
        '\n' +
        'body {\n' +
        '  font: 16px sans-serif;\n' +
        '  background-color: var(--sl-color-neutral-0);\n' +
        '  color: var(--sl-color-neutral-900);\n' +
        '  padding: 1rem;\n' +
        '}';

      // Docs: https://blog.codepen.io/documentation/prefill/
      const data = {
        title: '',
        description: '',
        tags: ['shoelace', 'web components'],
        editors,
        head: `<meta name="viewport" content="width=device-width">`,
        html_classes: `sl-theme-${isDark ? 'dark' : 'light'}`,
        css_external: ``,
        js_external: ``,
        js_module: true,
        js_pre_processor: isReact ? 'babel' : 'none',
        html: htmlTemplate,
        css: cssTemplate,
        js: jsTemplate
      };

      const input = document.createElement('input');
      input.type = 'hidden';
      input.name = 'data';
      input.value = JSON.stringify(data);
      form.append(input);

      document.body.append(form);
      form.submit();
      form.remove();
    }
  });
})();
<|endoftext|>


<commit_before>//=require underscore/underscore
//=require jquery/dist/jquery
//=require papa-parse/jquery.parse
//=require templates/table

var viewHelpers = {
  table: function(klass, options){
    if (klass){
      return '
';
    } else {
      return '
';
    }
  },
  theads: function(cells, options){
    var output = '',
        self = this;

    _.each(cells, function(cell, idx){
      output += self.tag('th', options[idx]);
      output += cell.trim() + '	';
    });

    return output;
  },
  tableElements: function(name, row, options){
    var self = this,
        output = '',
        titles = _.keys(row),
        values = _.values(row);

    _.each(values, function(cell, idx){
      options[idx]['data-title'] = titles[idx].trim();
      output += self.tag(name, options[idx]);
      output += cell.trim() + '</' + name + '>';
    });

    return output;
  },
  tag: function(name, options){
    var output = '<' + name,
        attributes = this.buildAttributes(options);

    if(attributes.length === 0){
      output += '>';
    } else {
      output += ' '+ attributes + '>';
    }
    return output;
  },
  buildAttributes: function(options){
    var output = [];
    for (var key in options) {
      if (options.hasOwnProperty(key)){
        output.push(key + '="' + options[key] + '"');
      }
    }
    return output.join(' ');
  }
}

var converter = {
  convert: function(){
    var template = JST['templates/table'];
    var input = $('textarea').val();
    var parsed = $.parse(input, {
      header: true
    });

    var data = {
      rows: parsed.results.rows,
      fields: parsed.results.fields,
      tableOptions: {
        klass: 'table-klass',
        id: 'table-id'
      },
      thOptions: {
        0: {'class': 'first-klass'},
        1: {'class': 'second-klass'}
      },
      tdOptions: {
        0: {'class': 'center'},
        1: {'class': 'right'}
      }
    }

    _.extend(data, viewHelpers);

    $(".output textarea").html(template(data));
  }
}

$(document).ready(function(){
  $('.input textarea').on('change', function(event){
    event.preventDefault();
    converter.convert();
  });

  $('input.convert').on('click', function(event){
    event.preventDefault();
    converter.convert();
  });
});
<commit_msg>Fix empty cells issues<commit_after>//=require underscore/underscore
//=require jquery/dist/jquery
//=require papa-parse/jquery.parse
//=require templates/table

var viewHelpers = {
  table: function(klass, options){
    if (klass){
      return '
';
    } else {
      return '
';
    }
  },
  theads: function(cells, options){
    var output = '',
        self = this;

    _.each(cells, function(cell, idx){
      output += self.tag('th', options[idx]);
      output += cell.trim() + '	';
    });

    return output;
  },
  tableElements: function(name, row, options){
    var self = this,
        output = '',
        titles = _.keys(row),
        values = _.values(row);

    _.each(values, function(cell, idx){
      if(typeof options[idx] === 'undefined'){
        options[idx] = {};
      }
      options[idx]['data-title'] = titles[idx].trim();
      output += self.tag(name, options[idx]);
      output += (cell ? cell.toString().trim() : '') + '</' + name + '>';
    });

    return output;
  },
  tag: function(name, options){
    var output = '<' + name,
        attributes = this.buildAttributes(options);

    if(attributes.length === 0){
      output += '>';
    } else {
      output += ' '+ attributes + '>';
    }
    return output;
  },
  buildAttributes: function(options){
    var output = [];
    for (var key in options) {
      if (options.hasOwnProperty(key)){
        output.push(key + '="' + options[key] + '"');
      }
    }
    return output.join(' ');
  }
}

var converter = {
  convert: function(){
    var template = JST['templates/table'];
    var input = $('textarea').val();
    var parsed = $.parse(input, {
      header: true
    });

    var data = {
      rows: parsed.results.rows,
      fields: parsed.results.fields,
      tableOptions: {
        klass: 'table-klass',
        id: 'table-id'
      },
      thOptions: {
        0: {'class': 'first-klass'},
        1: {'class': 'second-klass'},
        2: {'class': 'number'}
      },
      tdOptions: {
        0: {'class': 'center'},
        2: {'class': 'number'}
      }
    }

    _.extend(data, viewHelpers);

    $(".output textarea").html(template(data));
  }
}

function inputsPopulate(){
  var template = JST['templates/input'];
  var input = $('textarea').val();
  var parsed = $.parse(input, {
    header: true
  });
  var headers = parsed.results.fields;
  var output = '';

  _.each(headers, function(header, idx){
    output += template({header: header, idx: idx});
  });
  $('.tds').html(output);
}

$(document).ready(function(){
  $('.input textarea').on('change', function(event){
    event.preventDefault();
    converter.convert();
    inputsPopulate();
  });

  $('input.convert').on('click', function(event){
    event.preventDefault();
    converter.convert();
    inputsPopulate();
  });
});
<|endoftext|>


<commit_before>/************************************************
 * jQuery iOS App Switcher
 *	- by Ryan Scherf
 *
 * Convert your site's links to URL
 * schemes to deeplink to iOS apps.
 ************************************************/

(function($) {
	$.fn.switcher = function(options) {

		var settings = $.extend({
			additionalSchemas : [],
			debug							: false,
			iOS								: /(iPad|iPhone|iPod)/g.test(navigator.userAgent)
    }, options);

		if(settings.iOS || settings.debug)
		{
			// Define the native apps to deeplink
			var services = [
				{
					pattern	: /(facebook)/g,
					scheme	: function(username) {

						var facebookId = "";

						if(isNaN(parseInt(username)))
						{
							$.ajax({
								url			 : "http://graph.facebook.com/" + username,
								type 		 : "get",
								dataType : "json",
								async		 : false,
							}).done(function(response) {
								facebookId = response.id;
							});
						}
						else
						{
							facebookId = username;
						}

						return "fb://profile/" + facebookId;
					}
				},
				{
					pattern : /(linkedin)/g,
					scheme  : function(username) {
						return "linkedin://#profile/" + username
					}
				},
				{
					pattern	: /(instagram)/g,
					scheme	: function(username) {
						return "instagram://user?username=" + username
					}
				},
				{
					pattern	: /(quirky)/g,
					scheme	: function(username) {
						return "quirky:///" + username
					}
				},
				{
					pattern	: /(twitter)/g,
					scheme	: function(username) {
						return "twitter://user?screen_name=" + username
					}
				},
				{
					pattern : /(ryan.sc)/g,
					scheme : function(u) {
						return "ryansc://no-app-here"
					}
				}
			];

			// Add on any user defined schemas
			services = services.concat(settings.additionalSchemas);

			// Iterate through the set
	    this.each(function() {

	  		var $this    = $(this),
					href  	 	 = $(this).attr("href"),
					identifier = href.split(".com/");

				if($this.data("username"))
					username = $this.data("username");
				else if(identifier.length > 1)
					username = identifier[1];
				else
					username = "notfound";

				$(services).each(function(i) {
					if(services[i].pattern.test(href))
					{
						$this.attr("href", services[i].scheme(username));
						return false;
					}
				});

				// If visitor doesn't have the app, open the link
				$(this).on("click", function() {
					setTimeout(function() {
						window.location = href;
					}, 300);
				});

	    });

	  }

    return this;

	};
}(jQuery));
<commit_msg>Corrects incorrect tabs/spaces<commit_after>/************************************************
 * jQuery iOS App Switcher
 *	- by Ryan Scherf
 *
 * Convert your site's links to URL
 * schemes to deeplink to iOS apps.
 ************************************************/

(function($) {
	$.fn.switcher = function(options) {

	var settings = $.extend({
		additionalSchemas : [],
		debug							: false,
		iOS								: /(iPad|iPhone|iPod)/g.test(navigator.userAgent)
	}, options);

	if(settings.iOS || settings.debug)
	{
		// Define the native apps to deeplink
		var services = [
			{
				pattern	: /(facebook)/g,
				scheme	: function(username) {

					var facebookId = "";

					if(isNaN(parseInt(username)))
					{
						$.ajax({
							url			 : "http://graph.facebook.com/" + username,
							type 		 : "get",
							dataType : "json",
							async		 : false,
						}).done(function(response) {
							facebookId = response.id;
						});
					}
					else
					{
						facebookId = username;
					}

					return "fb://profile/" + facebookId;
				}
			},
			{
				pattern : /(linkedin)/g,
				scheme  : function(username) {
					return "linkedin://#profile/" + username
				}
			},
			{
				pattern	: /(instagram)/g,
				scheme	: function(username) {
					return "instagram://user?username=" + username
				}
			},
			{
				pattern	: /(quirky)/g,
				scheme	: function(username) {
					return "quirky:///" + username
				}
			},
			{
				pattern	: /(twitter)/g,
				scheme	: function(username) {
					return "twitter://user?screen_name=" + username
				}
			},
			{
				pattern : /(ryan.sc)/g,
				scheme : function(u) {
					return "ryansc://no-app-here"
				}
			}
		];

		// Add on any user defined schemas
		services = services.concat(settings.additionalSchemas);

		// Iterate through the set
		this.each(function() {

			var $this	 = $(this),
			href  	 	 = $(this).attr("href"),
			identifier = href.split(".com/");

			if($this.data("username"))
				username = $this.data("username");
			else if(identifier.length > 1)
				username = identifier[1];
			else
				username = "notfound";

			$(services).each(function(i) {
				if(services[i].pattern.test(href))
				{
					$this.attr("href", services[i].scheme(username));
					return false;
				}
			});

			// If visitor doesn't have the app, open the link
			$(this).on("click", function() {
				setTimeout(function() {
					window.location = href;
				}, 300);
			});

		});

	}

	return this;

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