<commit_before>var vows = require('vows'),
    assert = require('assert'),
    AssetGraph = require('../lib'),
    _ = require('underscore'),
    cssText = '';

vows.describe('transforms.splitCssIfIeLimitIsReached').addBatch({
    'After loading a simple Css test case': {
        topic: function () {
            new AssetGraph({root: __dirname + '/splitCssIfIeLimitIsReached/'})
/*
                // debug
                .on('addAsset', function (asset) {
                    console.warn('Added: ' + asset.url);
                })
                .on('addRelation', function (relation) {
                    console.warn('Added: ' + relation.from.url + ' --> ' + relation.to.url);
                })
                .on('removeAsset', function (asset) {
                    console.warn('Removed: ' + asset.url);
                })
                .on('removeRelation', function (relation) {
                    console.warn('Removed: ' + relation.from.url + ' --> ' + relation.to.url);
                })
*/
                .loadAssets('index.html')
                .populate()
                .minifyAssets({ type: 'Css', isLoaded: true})
                .run(this.callback);
        },
        'the graph should contain 1 Css asset': function (assetGraph) {
            var cssAssets = assetGraph.findAssets({type: 'Css'});

            assert.equal(cssAssets.length, 1);

            cssText = cssAssets.map(function (cssAsset) {
                return cssAsset.text;
            }).join('');
        },
        'the Css asset should contain 4096 rules': function (assetGraph) {
            assert.equal(assetGraph.findAssets({ type: 'Css' })[0].parseTree.cssRules.length, 4096);
        },
        'then running the splitCssIfIeLimitIsReached transform': {
            topic: function (assetGraph) {
                assetGraph.__infos = [];

                assetGraph
                    .on('info', function (err) {
                        assetGraph.__infos.push(err);
                    })
                    .splitCssIfIeLimitIsReached()
                    .minifyAssets({ type: 'Css', isLoaded: true})
                    .run(this.callback);
            },
            'the graph should have 1 emitted info': function (assetGraph) {
                assert.equal(assetGraph.__infos.length, 1);
            },
            'the graph should contain 2 Css asset': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css'}).length, 2);
            },
            'the Css assets should contain 4096 rules': function (assetGraph) {
                assert.equal(assetGraph.findAssets({ type: 'Css' }).map(function (cssAsset) {
                    return cssAsset.parseTree.cssRules.length;
                }).reduce(function (prev, current) {
                    return prev + current;
                }, 0), 4096);
            },
            'each Css asset should be smaller than the original': function (assetGraph) {
                assetGraph.findAssets({type: 'Css'}).forEach(function (cssAsset) {
                    assert(cssAsset.text.length < cssText.length, cssAsset.url);
                });
            },
            'the concatenated css text content should be unchanged from before': function (assetGraph) {
                var text = '';
                assetGraph.findAssets({type: 'Css'}).forEach(function (cssAsset) {
                    text += cssAsset.text;
                });

                assert(text === cssText, 'Concatenation of text of split up css assets differ from original');
            },
            'the background image should have an incoming relation from the second new css asset': function (assetGraph) {
                var cssAssets = assetGraph.findAssets({
                        type: 'Css'
                    }),
                    pngRelations = assetGraph.findRelations({
                        to: {
                            type: 'Png'
                        }
                    });

                assert.equal(pngRelations.length, 1);
                assert.equal(pngRelations[0].from, cssAssets[1]);
            }
        }
    },

    'After loading a real life huge Css test case': {
        topic: function () {
            new AssetGraph({root: __dirname + '/splitCssIfIeLimitIsReached/'})
                .loadAssets('falcon.html')
                .populate()
                .minifyAssets({ type: 'Css', isLoaded: true})
                .mergeIdenticalAssets({
                    isLoaded: true
                })
                .run(this.callback);
        },
        'the graph should contain 1 Css asset': function (assetGraph) {
            var cssAssets = assetGraph.findAssets({type: 'Css'});

            assert.equal(cssAssets.length, 1);

            cssText = cssAssets.map(function (cssAsset) {
                return cssAsset.text;
            }).join('');
        },
        'the Css asset should contain 6290 rules': function (assetGraph) {
            var rules = assetGraph.findAssets({ type: 'Css' })[0].parseTree.cssRules.length;
            assetGraph.__rules = rules;
            assert.equal(rules, 6290);
        },
        'the graph should have 1 of each of asset types "png", "gif", "svg", "ttf", "eot", "woff"': function (assetGraph) {
            ['png', 'gif', 'svg', 'ttf', 'eot', 'woff'].forEach(function (extension) {
                assert.equal(assetGraph.findAssets({
                    url: new RegExp('\\.' + extension + '(?:$|#)')
                }).length, 1);
            });
        },
        'the graph should contain 6 files named fake.*': function (assetGraph) {
            assert.equal(assetGraph.findAssets({
                url: /fake\./
            }).length, 6);
        },
        'then running the splitCssIfIeLimitIsReached transform': {
            topic: function (assetGraph) {
                assetGraph.__infos = [];

                assetGraph
                    .on('info', function (err) {
                        assetGraph.__infos.push(err);
                    })
                    .splitCssIfIeLimitIsReached()
                    .minifyAssets({ type: 'Css', isLoaded: true})
                    .run(this.callback);
            },
            'the graph should have 1 emitted info': function (assetGraph) {
                assert.equal(assetGraph.__infos.length, 1);
            },
            'the graph should contain 3 Css asset': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css'}).length, 3);
            },
            'the Css assets should contain 6290 rules': function (assetGraph) {
                assert.equal(assetGraph.findAssets({ type: 'Css' }).map(function (cssAsset) {
                    return cssAsset.parseTree.cssRules.length;
                }).reduce(function (prev, current) {
                    return prev + current;
                }, 0), 6290);
            },
            'each Css asset should be smaller than the original': function (assetGraph) {
                var cssAssets = assetGraph.findAssets({type: 'Css'}),
                    rules = [2806, 2399, 1085],
                    sum = 0;

                cssAssets.forEach(function (cssAsset, idx) {
                    var assetRules = cssAsset.parseTree.cssRules.length;
                    assert(cssAsset.text.length < cssText.length);
                    assert.equal(assetRules, rules[idx]);
                    sum += assetRules;
                });

                assert.equal(sum, assetGraph.__rules);
            },
            'the concatenated css text content should be unchanged from before': function (assetGraph) {
                var text = '';
                assetGraph.findAssets({type: 'Css'}).forEach(function (cssAsset) {
                    text += cssAsset.text;
                });

                assert(text === cssText, 'Concatenation of text of split up css assets differ from original');
            },
            'the graph should have 1 of each of asset types "png", "gif", "svg", "ttf", "eot", "woff"': function (assetGraph) {
                ['png', 'gif', 'svg', 'ttf', 'eot', 'woff'].forEach(function (extension) {
                    assert.equal(assetGraph.findAssets({
                        url: new RegExp('\\.' + extension + '(?:$|#)')
                    }).length, 1);
                });
            }
        }
    },
    'After loading a test case with an inline stylesheet': {
        topic: function () {
            new AssetGraph({root: __dirname + '/splitCssIfIeLimitIsReached/'})
                .loadAssets('inline.html')
                .populate()
                .run(this.callback);
        },
        'the graph should contain 2 assets': function (assetGraph) {
            assert.equal(assetGraph.findAssets().length, 2);
        },
        'the graph should contain one Html asset': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'Html'}).length, 1);
        },
        'the graph should contain one Css asset': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'Css'}).length, 1);
        },
        'then running the splitCssIfIeLimitIsReached transform': {
            topic: function (assetGraph) {
                assetGraph
                    .splitCssIfIeLimitIsReached({}, {rulesPerStylesheetLimit: 2})
                    .run(this.callback);
            },
            'the graph should contain 3 inline Css assets': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css', isInline: true}).length, 3);
            },
            'the graph should contain 3 HtmlStyle relations': function (assetGraph) {
                assert.equal(assetGraph.findRelations({type: 'HtmlStyle'}).length, 3);
            },
            'the Css assets should have the expected contents': function (assetGraph) {
                assert.deepEqual(_.pluck(assetGraph.findAssets({type: 'Css'}), 'text'),
                    [
                        '.a {color: #aaa;}.b {color: #bbb;}',
                        '.c {color: #ccc;}.d {color: #ddd;}',
                        '.e {color: #eee;}'
                    ]
                );
            },
            'the Html asset should contain 3 inline stylesheets': function (assetGraph) {
                var htmlAsset = assetGraph.findAssets({type: 'Html'})[0],
                    matchInlineStylesheets = htmlAsset.text.match(/<style type="text\/css">/g);
                assert.ok(matchInlineStylesheets);
                assert.equal(matchInlineStylesheets.length, 3);
            }
        }
    },
    'After loading a test case with an inline that has rules in media queries': {
        topic: function () {
            new AssetGraph({root: __dirname + '/splitCssIfIeLimitIsReached/'})
                .loadAssets('inlineWithMedia.html')
                .populate()
                .run(this.callback);
        },
        'the graph should contain 2 assets': function (assetGraph) {
            assert.equal(assetGraph.findAssets().length, 2);
        },
        'the graph should contain one Html asset': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'Html'}).length, 1);
        },
        'the graph should contain one Css asset': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'Css'}).length, 1);
        },
        'then running the splitCssIfIeLimitIsReached transform': {
            topic: function (assetGraph) {
                assetGraph
                    .splitCssIfIeLimitIsReached({}, {rulesPerStylesheetLimit: 3})
                    .run(this.callback);
            },
            'the graph should contain 4 inline Css assets': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css', isInline: true}).length, 4);
            },
            'the graph should contain 4 HtmlStyle relations': function (assetGraph) {
                assert.equal(assetGraph.findRelations({type: 'HtmlStyle'}).length, 4);
            },
            'the Css assets should have the expected contents': function (assetGraph) {
                assert.deepEqual(_.pluck(assetGraph.findAssets({type: 'Css'}), 'text'),
                    [
                        '@media screen {.a, .quux, .baz {color: #aaa;}}',
                        '.b {color: #bbb;}.c {color: #ccc;}',
                        '@media print {.d {color: #ddd;}.e {color: #eee;}.f {color: #fff;}}',
                        '.hey {color: #000;}.there {color: #fff;}'
                    ]
                );
            },
            'the Html asset should contain 4 inline stylesheets': function (assetGraph) {
                var htmlAsset = assetGraph.findAssets({type: 'Html'})[0],
                    matchInlineStylesheets = htmlAsset.text.match(/<style type="text\/css">/g);
                assert.ok(matchInlineStylesheets);
                assert.equal(matchInlineStylesheets.length, 4);
            }
        }
    }
})['export'](module);
<commit_msg>Speed up splitCss transform tests<commit_after>var vows = require('vows'),
    assert = require('assert'),
    AssetGraph = require('../lib'),
    _ = require('underscore');

vows.describe('transforms.splitCssIfIeLimitIsReached').addBatch({
    'After loading a simple Css test case': {
        topic: function () {
            new AssetGraph({root: __dirname + '/splitCssIfIeLimitIsReached/'})
/*
                // debug
                .on('addAsset', function (asset) {
                    console.warn('Added: ' + asset.url);
                })
                .on('addRelation', function (relation) {
                    console.warn('Added: ' + relation.from.url + ' --> ' + relation.to.url);
                })
                .on('removeAsset', function (asset) {
                    console.warn('Removed: ' + asset.url);
                })
                .on('removeRelation', function (relation) {
                    console.warn('Removed: ' + relation.from.url + ' --> ' + relation.to.url);
                })
*/
                .loadAssets('index.html')
                .populate()
                .run(this.callback);
        },
        'the graph should contain 1 Css asset': function (assetGraph) {
            var cssAssets = assetGraph.findAssets({type: 'Css'});

            assert.equal(cssAssets.length, 1);

            assetGraph._parseTreeBefore = cssAssets[0].parseTree;
        },
        'the Css asset should contain 4096 rules': function (assetGraph) {
            assert.equal(assetGraph.findAssets({ type: 'Css' })[0].parseTree.cssRules.length, 4096);
        },
        'then running the splitCssIfIeLimitIsReached transform': {
            topic: function (assetGraph) {
                assetGraph.__infos = [];

                assetGraph
                    .on('info', function (err) {
                        assetGraph.__infos.push(err);
                    })
                    .splitCssIfIeLimitIsReached()
                    .run(this.callback);
            },
            'the graph should have 1 emitted info': function (assetGraph) {
                assert.equal(assetGraph.__infos.length, 1);
            },
            'the graph should contain 2 Css asset': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css'}).length, 2);
            },
            'the Css assets should contain 4096 rules': function (assetGraph) {
                assert.equal(assetGraph.findAssets({ type: 'Css' }).map(function (cssAsset) {
                    return cssAsset.parseTree.cssRules.length;
                }).reduce(function (prev, current) {
                    return prev + current;
                }, 0), 4096);
            },
            'each Css asset should be smaller than the original': function (assetGraph) {
                assetGraph.findAssets({type: 'Css'}).forEach(function (cssAsset) {
                    assert(cssAsset.parseTree.cssRules.length < assetGraph._parseTreeBefore.cssRules.length, cssAsset.url);
                });
            },
            'the concatenated css text content should be unchanged from before': function (assetGraph) {
                var cssAfter = new AssetGraph.Css({
                    text: assetGraph.findAssets({type: 'Css'}).map(function (cssAsset) {
                        return cssAsset.text;
                    }).join('')
                }).parseTree.toString();

                assert(assetGraph._parseTreeBefore.toString() === cssAfter, 'Concatenation of text of split up css assets differ from original');
            },
            'the background image should have an incoming relation from the second new css asset': function (assetGraph) {
                var cssAssets = assetGraph.findAssets({
                        type: 'Css'
                    }),
                    pngRelations = assetGraph.findRelations({
                        to: {
                            type: 'Png'
                        }
                    });

                assert.equal(pngRelations.length, 1);
                assert.equal(pngRelations[0].from, cssAssets[1]);
            }
        }
    },
    'After loading a real life huge Css test case': {
        topic: function () {
            new AssetGraph({root: __dirname + '/splitCssIfIeLimitIsReached/'})
                .loadAssets('falcon.html')
                .populate()
                .run(this.callback);
        },
        'the graph should contain 1 Css asset': function (assetGraph) {
            var cssAssets = assetGraph.findAssets({type: 'Css'});

            assert.equal(cssAssets.length, 1);

            assetGraph._parseTreeBefore = cssAssets[0].parseTree;
        },
        'the Css asset should contain 6290 rules': function (assetGraph) {
            var rules = assetGraph.findAssets({ type: 'Css' })[0].parseTree.cssRules.length;
            assetGraph.__rules = rules;
            assert.equal(rules, 6290);
        },
        'the graph should have 1 of each of asset types "png", "gif", "svg", "ttf", "eot", "woff"': function (assetGraph) {
            ['png', 'gif', 'svg', 'ttf', 'eot', 'woff'].forEach(function (extension) {
                assert.equal(assetGraph.findAssets({
                    url: new RegExp('\\.' + extension + '(?:$|#)')
                }).length, 1);
            });
        },
        'the graph should contain 7 files named fake.*': function (assetGraph) {
            assert.equal(assetGraph.findAssets({
                url: /fake\./
            }).length, 7);
        },
        'then running the splitCssIfIeLimitIsReached transform': {
            topic: function (assetGraph) {
                assetGraph.__infos = [];

                assetGraph
                    .on('info', function (err) {
                        assetGraph.__infos.push(err);
                    })
                    .splitCssIfIeLimitIsReached()
                    .run(this.callback);
            },
            'the graph should have 1 emitted info': function (assetGraph) {
                assert.equal(assetGraph.__infos.length, 1);
            },
            'the graph should contain 3 Css asset': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css'}).length, 3);
            },
            'the Css assets should contain 6290 rules': function (assetGraph) {
                assert.equal(assetGraph.findAssets({ type: 'Css' }).map(function (cssAsset) {
                    return cssAsset.parseTree.cssRules.length;
                }).reduce(function (prev, current) {
                    return prev + current;
                }, 0), 6290);
            },
            'each Css asset should be smaller than the original': function (assetGraph) {
                var cssAssets = assetGraph.findAssets({type: 'Css'}),
                    parseTreeBefore = assetGraph._parseTreeBefore,
                    rules = [2806, 2399, 1085],
                    sum = 0;

                cssAssets.forEach(function (cssAsset, idx) {
                    var assetRules = cssAsset.parseTree.cssRules.length;
                    assert(assetRules < parseTreeBefore.cssRules.length);
                    assert.equal(assetRules, rules[idx]);
                    sum += assetRules;
                });

                assert.equal(sum, assetGraph.__rules);
            },
            'the concatenated css text content should be unchanged from before': function (assetGraph) {
                var text = assetGraph.findAssets({type: 'Css'}).map(function (cssAsset) {
                            return cssAsset.text;
                        }).join('\n'),
                    parseTreeAfter = new AssetGraph.Css({
                        text: text
                    }).parseTree;

                assert(assetGraph._parseTreeBefore.toString() === parseTreeAfter.toString(), 'Concatenation of text of split up css assets differ from original');
            },
            'the graph should have 1 of each of asset types "png", "gif", "svg", "ttf", "eot", "woff"': function (assetGraph) {
                ['png', 'gif', 'svg', 'ttf', 'eot', 'woff'].forEach(function (extension) {
                    assert.equal(assetGraph.findAssets({
                        url: new RegExp('\\.' + extension + '(?:$|#)')
                    }).length, 1);
                });
            }
        }
    },
    'After loading a test case with an inline stylesheet': {
        topic: function () {
            new AssetGraph({root: __dirname + '/splitCssIfIeLimitIsReached/'})
                .loadAssets('inline.html')
                .populate()
                .run(this.callback);
        },
        'the graph should contain 2 assets': function (assetGraph) {
            assert.equal(assetGraph.findAssets().length, 2);
        },
        'the graph should contain one Html asset': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'Html'}).length, 1);
        },
        'the graph should contain one Css asset': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'Css'}).length, 1);
        },
        'then running the splitCssIfIeLimitIsReached transform': {
            topic: function (assetGraph) {
                assetGraph
                    .splitCssIfIeLimitIsReached({}, {rulesPerStylesheetLimit: 2})
                    .run(this.callback);
            },
            'the graph should contain 3 inline Css assets': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css', isInline: true}).length, 3);
            },
            'the graph should contain 3 HtmlStyle relations': function (assetGraph) {
                assert.equal(assetGraph.findRelations({type: 'HtmlStyle'}).length, 3);
            },
            'the Css assets should have the expected contents': function (assetGraph) {
                assert.deepEqual(_.pluck(assetGraph.findAssets({type: 'Css'}), 'text'),
                    [
                        '.a {color: #aaa;}.b {color: #bbb;}',
                        '.c {color: #ccc;}.d {color: #ddd;}',
                        '.e {color: #eee;}'
                    ]
                );
            },
            'the Html asset should contain 3 inline stylesheets': function (assetGraph) {
                var htmlAsset = assetGraph.findAssets({type: 'Html'})[0],
                    matchInlineStylesheets = htmlAsset.text.match(/<style type="text\/css">/g);
                assert.ok(matchInlineStylesheets);
                assert.equal(matchInlineStylesheets.length, 3);
            }
        }
    },
    'After loading a test case with an inline that has rules in media queries': {
        topic: function () {
            new AssetGraph({root: __dirname + '/splitCssIfIeLimitIsReached/'})
                .loadAssets('inlineWithMedia.html')
                .populate()
                .run(this.callback);
        },
        'the graph should contain 2 assets': function (assetGraph) {
            assert.equal(assetGraph.findAssets().length, 2);
        },
        'the graph should contain one Html asset': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'Html'}).length, 1);
        },
        'the graph should contain one Css asset': function (assetGraph) {
            assert.equal(assetGraph.findAssets({type: 'Css'}).length, 1);
        },
        'then running the splitCssIfIeLimitIsReached transform': {
            topic: function (assetGraph) {
                assetGraph
                    .splitCssIfIeLimitIsReached({}, {rulesPerStylesheetLimit: 3})
                    .run(this.callback);
            },
            'the graph should contain 4 inline Css assets': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css', isInline: true}).length, 4);
            },
            'the graph should contain 4 HtmlStyle relations': function (assetGraph) {
                assert.equal(assetGraph.findRelations({type: 'HtmlStyle'}).length, 4);
            },
            'the Css assets should have the expected contents': function (assetGraph) {
                assert.deepEqual(_.pluck(assetGraph.findAssets({type: 'Css'}), 'text'),
                    [
                        '@media screen {.a, .quux, .baz {color: #aaa;}}',
                        '.b {color: #bbb;}.c {color: #ccc;}',
                        '@media print {.d {color: #ddd;}.e {color: #eee;}.f {color: #fff;}}',
                        '.hey {color: #000;}.there {color: #fff;}'
                    ]
                );
            },
            'the Html asset should contain 4 inline stylesheets': function (assetGraph) {
                var htmlAsset = assetGraph.findAssets({type: 'Html'})[0],
                    matchInlineStylesheets = htmlAsset.text.match(/<style type="text\/css">/g);
                assert.ok(matchInlineStylesheets);
                assert.equal(matchInlineStylesheets.length, 4);
            }
        }
    }
})['export'](module);
<|endoftext|>


<commit_before>window.FolioConsole = window.FolioConsole || {}

window.FolioConsole.NotesCatalogueTooltip = {}

window.FolioConsole.NotesCatalogueTooltip.onChange = (e) => {
  const $input = $(e.target)
  const $tooltip = $input.closest('.f-c-console-notes-catalogue-tooltip')

  if ($tooltip.hasClass('f-c-console-notes-catalogue-tooltip--submitting')) return

  $tooltip.addClass('f-c-console-notes-catalogue-tooltip--submitting')

  $.ajax({
    url: $input.data('url'),
    method: "POST",
    data: {
      closed: $input.prop('checked'),
    },
    success: (res) => {
      if (res && res.data) {
        if (res.data.catalogue_tooltip) {
          $tooltip
            .find('.f-c-console-notes-catalogue-tooltip__tooltip-inner')
            .replaceWith($(res.data.catalogue_tooltip).find('.f-c-console-notes-catalogue-tooltip__tooltip-inner'))
        } else {
          $tooltip.remove()
        }
      }

      $tooltip.removeClass('f-c-console-notes-catalogue-tooltip--submitting')

      window.FolioConsole.flashMessageFromMeta(res)
    },
    error: (jxHr) => {
      if (jxHr.responseText) {
        try {
          window.FolioConsole.flashMessageFromApiErrors(JSON.parse(jxHr.responseText))
        } catch (_e) {}
      }

      $tooltip.removeClass('f-c-console-notes-catalogue-tooltip--submitting')
      $input.prop('checked', !$input.prop('checked'))
    }
  })
}

$(document).on('change',
               '.f-c-console-notes-catalogue-tooltip__note-input',
               window.FolioConsole.NotesCatalogueTooltip.onChange)
<commit_msg>add onSuccess to console notes catalogue_tooltip js<commit_after>window.FolioConsole = window.FolioConsole || {}

window.FolioConsole.NotesCatalogueTooltip = {}

window.FolioConsole.NotesCatalogueTooltip.onSuccess = ($tooltip, res) => {
  // to be overriden in app
}

window.FolioConsole.NotesCatalogueTooltip.onChange = (e) => {
  const $input = $(e.target)
  const $tooltip = $input.closest('.f-c-console-notes-catalogue-tooltip')

  if ($tooltip.hasClass('f-c-console-notes-catalogue-tooltip--submitting')) return

  $tooltip.addClass('f-c-console-notes-catalogue-tooltip--submitting')

  $.ajax({
    url: $input.data('url'),
    method: "POST",
    data: {
      closed: $input.prop('checked'),
    },
    success: (res) => {
      if (res && res.data) {
        window.FolioConsole.NotesCatalogueTooltip.onSuccess($tooltip, res)

        if (res.data.catalogue_tooltip) {
          $tooltip
            .find('.f-c-console-notes-catalogue-tooltip__tooltip-inner')
            .replaceWith($(res.data.catalogue_tooltip).find('.f-c-console-notes-catalogue-tooltip__tooltip-inner'))
        } else {
          $tooltip.remove()
        }
      }

      $tooltip.removeClass('f-c-console-notes-catalogue-tooltip--submitting')

      window.FolioConsole.flashMessageFromMeta(res)
    },
    error: (jxHr) => {
      if (jxHr.responseText) {
        try {
          window.FolioConsole.flashMessageFromApiErrors(JSON.parse(jxHr.responseText))
        } catch (_e) {}
      }

      $tooltip.removeClass('f-c-console-notes-catalogue-tooltip--submitting')
      $input.prop('checked', !$input.prop('checked'))
    }
  })
}

$(document).on('change',
               '.f-c-console-notes-catalogue-tooltip__note-input',
               window.FolioConsole.NotesCatalogueTooltip.onChange)
<|endoftext|>


<commit_before>'use strict'

var util = require('util')
var WebSocketSignaling = require('../../lib/signaling/out-of-band/websocket')

function FilteringWebSocketSignaling (args) {
  if (!(this instanceof FilteringWebSocketSignaling)) {
    return new FilteringWebSocketSignaling(args)
  }
  // init
  this._filter = (args.filter === undefined) ? function () { return false } : args.filter
  WebSocketSignaling.call(this, args)
}

// Inherit EventEmitter
util.inherits(FilteringWebSocketSignaling, WebSocketSignaling)

// do not fire an error when a message was not properly delivered
FilteringWebSocketSignaling.prototype.send = function (message, destinationInfo, onSuccess, onFailure) {
  // if message passes the filter test
  if (this._args.filter(message)) {
    console.log('IGNORING message ' + JSON.stringify(message))
    // then return -- dropping request on the floor
    return
  }
  FilteringWebSocketSignaling.super_.prototype.send.call(this, message, destinationInfo, onSuccess, onFailure)
}

module.exports = FilteringWebSocketSignaling
<commit_msg>bug fix<commit_after>'use strict'

var util = require('util')
var WebSocketSignaling = require('../../../lib/signaling/out-of-band/websocket')

function FilteringWebSocketSignaling (args) {
  if (!(this instanceof FilteringWebSocketSignaling)) {
    return new FilteringWebSocketSignaling(args)
  }
  // init
  this._filter = (args.filter === undefined) ? function () { return false } : args.filter
  WebSocketSignaling.call(this, args)
}

// Inherit EventEmitter
util.inherits(FilteringWebSocketSignaling, WebSocketSignaling)

// do not fire an error when a message was not properly delivered
FilteringWebSocketSignaling.prototype.send = function (message, destinationInfo, onSuccess, onFailure) {
  // if message passes the filter test
  if (this._args.filter(message)) {
    console.log('IGNORING message ' + JSON.stringify(message))
    // then return -- dropping request on the floor
    return
  }
  FilteringWebSocketSignaling.super_.prototype.send.call(this, message, destinationInfo, onSuccess, onFailure)
}

module.exports = FilteringWebSocketSignaling
<|endoftext|>


<commit_before>import React from 'react';
import { IntlProvider } from 'react-intl';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { expect } from 'chai';
import { render } from 'enzyme';

import SourceAnnotation from '../../src/app/components/annotations/SourceAnnotation';

describe('<SourceAnnotation />', () => {
  const timestamp = new Date('2017-02-08 17:19:40 UTC').valueOf() / 1000;

  const annotation = {
    annotation_type: 'comment',
    content: JSON.stringify({ text: 'testing' }),
    updated_at: timestamp.toString(),
    created_at: timestamp.toString(),
    medias: { edges: [] },
    permissions: JSON.stringify({ 'read Comment': false, 'update Comment': true, 'destroy Comment': true }),
    annotator: { name: '', profile_image: null },
  };
  const annotated = {};

  it('should render annotation updated_at time', () => {
    const wrapper = render(<IntlProvider locale="en"><MuiThemeProvider><SourceAnnotation annotation={annotation} annotated={annotated} annotatedType={'ProjectSource'} /></MuiThemeProvider></IntlProvider>);
    const container = wrapper.find('.annotation__timestamp > time');
    expect(container.length).to.equal(1);
    expect(container.prop('title')).to.contain('2017-02-08');
  });
});
<commit_msg>Remove unused SourceAnnotation test #6325<commit_after><|endoftext|>


<commit_before>'use strict';

const generateRuleTests = require('../../helpers/rule-test-harness');
const rule = require('../../../lib/rules/no-invalid-role');

const { createErrorMessage } = rule;

generateRuleTests({
  name: 'no-invalid-role',

  config: true,

  good: [
    '

',
    '

',
    '

',
    '',
    '',
    '',
    '',
    '',
    '',
    '<svg role="none"></svg>',
    '<svg role="presentation"></svg>',
    '<custom-component role="none"></custom-component>',
  ],

  bad: [
    {
      template: '

',
      result: {
        message: createErrorMessage('ul'),
        moduleId: 'layout.hbs',
        source: '

',
        line: 1,
        column: 0,
      },
    },
    {
      template: '

',
      result: {
        message: createErrorMessage('table'),
        moduleId: 'layout.hbs',
        source: '

',
        line: 1,
        column: 0,
      },
    },
    {
      template: '

',
      result: {
        message: createErrorMessage('table'),
        moduleId: 'layout.hbs',
        source: '

',
        line: 1,
        column: 0,
      },
    },
  ],
});
<commit_msg>Add angle bracket invocation test<commit_after>'use strict';

const generateRuleTests = require('../../helpers/rule-test-harness');
const rule = require('../../../lib/rules/no-invalid-role');

const { createErrorMessage } = rule;

generateRuleTests({
  name: 'no-invalid-role',

  config: true,

  good: [
    '

',
    '

',
    '

',
    '',
    '',
    '',
    '',
    '',
    '',
    '<svg role="none"></svg>',
    '<svg role="presentation"></svg>',
    '<custom-component role="none"></custom-component>',
    '<AwesomeThing role="none"></AwesomeThing>',
    '<AwesomeThing role="presentation"></AwesomeThing>',
  ],

  bad: [
    {
      template: '

',
      result: {
        message: createErrorMessage('ul'),
        moduleId: 'layout.hbs',
        source: '

',
        line: 1,
        column: 0,
      },
    },
    {
      template: '

',
      result: {
        message: createErrorMessage('table'),
        moduleId: 'layout.hbs',
        source: '

',
        line: 1,
        column: 0,
      },
    },
    {
      template: '

',
      result: {
        message: createErrorMessage('table'),
        moduleId: 'layout.hbs',
        source: '

',
        line: 1,
        column: 0,
      },
    },
  ],
});
<|endoftext|>


<commit_before>'use strict';

var fnTrue = () => true;
var fnSelf = x => x;

let parentSymbol = Symbol();
let indexSymbol = Symbol();
let colSymbol = Symbol();
let selectorSymbol = Symbol();
let countSymbol = Symbol();
let startSymbol = Symbol();

class Enumerable {
    constructor(arr = []) {
        this[parentSymbol] = arr;
        this[indexSymbol] = 0;
    }

    [Symbol.iterator]() {
        return this;
    }

    next() {
        if (this[indexSymbol] < this[parentSymbol].length) {
            return {
                value: this[parentSymbol][this[indexSymbol]++],
                done: false
            };
        }

        return {
            done: true
        };
    }

    aggregate(seed, fn, selector) {
        var it = this;

        switch (arguments.length) {
            case 1:
                fn = seed;
                seed = it.next().value;
                break;

            case 2:
                if (typeof seed === 'function') {
                    selector = fn;
                    fn = seed;
                    seed = it.next().value;
                }
                break;
        }
        for (let item of it) {
            seed = fn(seed, item);
        }

        if (selector) {
            return selector(seed);
        }
        return seed;
    }

    all(fn = fnTrue) {
        for (let x of this) {
            if (!fn(x)) {
                return false;
            }
        }
        return true;
    }

    any(fn = fnTrue) {
        for (let x of this) {
            if (fn(x)) {
                return true;
            }
        }
        return false;
    }

    average(fn = fnSelf) {
        var total = 0;
        var count = 0;

        for (let item of this) {
            total += fn(item);
            count++;
        }

        if (count) {
            return total / count;
        }

        throw Error('Sequence contains no elements');
    }

    concat(col) {
        return new ConcatEnumerable(this, col);
    }

    contains(value, tester = x => x === value) {
        var it = this;

        for (let item of it) {
            if (tester(item, value)) {
                return true;
            }
        }
        return false;
    }

    count(fn = fnTrue) {
        var count = 0;
        for (let i of this) {
            if (fn(i)) {
                count++;
            }
        }
        return count;
    }

    filter(selector) {
        return this.where(selector);
    }

    first(selector = fnTrue) {
        for (let item of this) {
            if (selector(item)) {
                return item;
            }
        }

        throw new Error('Sequence contains no matching elements');
    }

    firstOrDefault(selector = fnTrue) {
        try {
            return this.first(selector);
        } catch (e) {
            return undefined;
        }
    }

    last(selector = fnTrue) {
        for (let item of this.reverse()) {
            if (selector(item)) {
                return item;
            }
        }

        throw new Error('Sequence contains no matching elements');
    }

    lastOrDefault(selector = fnTrue) {
        try {
            return this.last(selector);
        } catch (e) {
            return undefined;
        }
    }

    map(fn) {
        return this.select(fn);
    }

    select(fn = fnSelf) {
        return new SelectEnumerable(this, fn);
    }

    selectMany(colSelector = fnSelf, resSelector) {
        return new SelectManyEnumerable(this, colSelector, resSelector);
    }

    single(selector = fnTrue) {
        var matched;
        for (let item of this) {
            if (selector(item)) {
                if (matched) {
                    throw Error('Sequence contains more than one matching element');
                } else {
                    matched = item;
                }
            }
        }
        if (matched) {
            return matched;
        }

        throw Error('Sequence contains no matching element');
    }

    singleOrDefault(selector = fnTrue) {
        try {
            return this.single(selector);
        } catch (e) {
            if (e.message === 'Sequence contains no matching element') {
                return undefined;
            }
            throw e;
        }
    }

    skip(count = 0) {
        return new SkipEnumerable(this, count);
    }

    skipWhile(fn = 0) {
        if (fn === 0) {
            return this.skip();
        }
        return new SkipEnumerable(this, fn);
    }

    take(count = 0) {
        return new TakeEnumerable(this, count);
    }

    takeWhile(fn = 0) {
        if (fn === 0) {
            return this.take();
        }
        return new TakeEnumerable(this, fn);
    }

    toArray() {
        var arr = [];
        for (let i of this) {
            arr.push(i);
        }
        return arr;
    }

    where(selector) {
        return new WhereEnumerable(this, selector);
    }

    static range(start = 0, end = 0) {
        return new RangeEnumerable(start, end);
    }

    static repeat(item, count = 0) {
        return new RepeatEnumerable(item, count);
    }
}

class ConcatEnumerable extends Enumerable {
    constructor(arr, col) {
        super();
        this[parentSymbol] = arr;
        this[colSymbol] = Array.isArray(col) ? col.asEnumerable() : col;
    }

    next() {
        var value = this[parentSymbol].next();
        if (!value.done) {
            return value;
        }

        value = this[colSymbol].next();
        return value;
    }
}

class WhereEnumerable extends Enumerable {
    constructor(arr, selector) {
        super();
        this[parentSymbol] = arr;
        this[selectorSymbol] = selector;
        this[indexSymbol] = 0;
    }

    next() {
        var val = this[parentSymbol].next();
        if (val.done) {
            return val;
        }

        if (this[selectorSymbol](val.value, this[indexSymbol]++)) {
            return val;
        }

        return this.next();
    }
}

class SelectEnumerable extends Enumerable {
    constructor(arr, fn) {
        super();
        this[parentSymbol] = arr;
        this[selectorSymbol] = fn;
        this[indexSymbol] = 0;
    }

    next() {
        var value = this[parentSymbol].next();
        if (value.done) {
            return value;
        }
        return {
            value: this[selectorSymbol](value.value, this[indexSymbol]++),
            done: false
        };
    }
}

class SelectManyEnumerable extends Enumerable {
    constructor(arr, colSelector, resultSelector) {
        super();
        this[parentSymbol] = arr;
        this[colSymbol] = colSelector;
        this[selectorSymbol] = resultSelector || ((_, x) => x);
        this[indexSymbol] = 0;
    }

    next() {
        var value = this[parentSymbol].next();
        if (value.done) {
            return value;
        }
        let arr = this[colSymbol](value.value, this[indexSymbol]++);
        return {
            value: this[selectorSymbol](arr, arr[0]),
            done: false
        };
    }
}

class RangeEnumerable extends Enumerable {
    constructor(start, count) {
        super();
        this[countSymbol] = count;
        this[indexSymbol] = 0;
        this[startSymbol] = start;
    }

    next() {
        if (this[indexSymbol] === this[countSymbol]) {
            return {
                done: true
            };
        }

        var value = this[startSymbol];
        this[startSymbol]++;
        this[indexSymbol]++;
        return {
            value: value,
            done: false
        };
    }
}

class TakeEnumerable extends Enumerable {
    constructor(arr, selector) {
        super();
        this[parentSymbol] = arr;
        this[selectorSymbol] = selector;
        this[indexSymbol] = 0;
    }

    next() {
        var item = this[parentSymbol].next();
        if (item.done) {
            return item;
        }

        if (typeof this[selectorSymbol] === 'number') {
            if (this[indexSymbol] < this[selectorSymbol]) {
                this[indexSymbol]++;
                return item;
            } else {
                return {
                    done: true
                };
            }
        } else {
            if (this[selectorSymbol](item.value, this[indexSymbol])) {
                this[indexSymbol]++;
                return item;
            } else {
                return {
                    done: true
                };
            }
        }
    }
}

class SkipEnumerable extends Enumerable {
    constructor(arr, selector) {
        super();
        this[parentSymbol] = arr;
        this[selectorSymbol] = selector;
        this[indexSymbol] = 0;
        this[startSymbol] = false;
    }

    next() {
        var item = this[parentSymbol].next();
        if (item.done) {
            return item;
        }

        var i = this[indexSymbol];
        this[indexSymbol]++;
        if (typeof this[selectorSymbol] === 'number') {
            if (i >= this[selectorSymbol]) {
                return item;
            } else {
                return this.next();
            }
        } else {
            if (!this[startSymbol] && !this[selectorSymbol](item.value, i)) {
                this[startSymbol] = true;
            }
            if (this[startSymbol]) {
                return item;
            }
            return this.next();
        }
    }
}

class RepeatEnumerable extends Enumerable {
    constructor(item, count) {
        super();
        this[selectorSymbol] = item;
        this[countSymbol] = count;
        this[indexSymbol] = 0;
    }

    next() {
        if (this[indexSymbol] === this[countSymbol]) {
            return {
                done: true
            };
        }

        var stripped = JSON.stringify(this[selectorSymbol]);
        this[indexSymbol]++;
        return {
            value: JSON.parse(stripped),
            done: false
        };
    }
}

// extension methods
Array.prototype.asEnumerable = function() {
    return new Enumerable(this);
};

export default Enumerable;
<commit_msg>Avoid Exception Handling for firstOrDefault and lastOrDefault<commit_after>'use strict';

var fnTrue = () => true;
var fnSelf = x => x;

let parentSymbol = Symbol();
let indexSymbol = Symbol();
let colSymbol = Symbol();
let selectorSymbol = Symbol();
let countSymbol = Symbol();
let startSymbol = Symbol();

class Enumerable {
    constructor(arr = []) {
        this[parentSymbol] = arr;
        this[indexSymbol] = 0;
    }

    [Symbol.iterator]() {
        return this;
    }

    next() {
        if (this[indexSymbol] < this[parentSymbol].length) {
            return {
                value: this[parentSymbol][this[indexSymbol]++],
                done: false
            };
        }

        return {
            done: true
        };
    }

    aggregate(seed, fn, selector) {
        var it = this;

        switch (arguments.length) {
            case 1:
                fn = seed;
                seed = it.next().value;
                break;

            case 2:
                if (typeof seed === 'function') {
                    selector = fn;
                    fn = seed;
                    seed = it.next().value;
                }
                break;
        }
        for (let item of it) {
            seed = fn(seed, item);
        }

        if (selector) {
            return selector(seed);
        }
        return seed;
    }

    all(fn = fnTrue) {
        for (let x of this) {
            if (!fn(x)) {
                return false;
            }
        }
        return true;
    }

    any(fn = fnTrue) {
        for (let x of this) {
            if (fn(x)) {
                return true;
            }
        }
        return false;
    }

    average(fn = fnSelf) {
        var total = 0;
        var count = 0;

        for (let item of this) {
            total += fn(item);
            count++;
        }

        if (count) {
            return total / count;
        }

        throw Error('Sequence contains no elements');
    }

    concat(col) {
        return new ConcatEnumerable(this, col);
    }

    contains(value, tester = x => x === value) {
        var it = this;

        for (let item of it) {
            if (tester(item, value)) {
                return true;
            }
        }
        return false;
    }

    count(fn = fnTrue) {
        var count = 0;
        for (let i of this) {
            if (fn(i)) {
                count++;
            }
        }
        return count;
    }

    filter(selector) {
        return this.where(selector);
    }

    first(selector = fnTrue) {
        var item = this.firstOrDefault(selector);
        if(item)
            return item;

        throw new Error('Sequence contains no matching elements');
    }

    firstOrDefault(selector = fnTrue) {
        for (let item of this) {
            if (selector(item)) {
                return item;
            }
        }
    }

    last(selector = fnTrue) {
        var item = this.lastOrDefault(selector);
        if(item)
            return item;

        throw new Error('Sequence contains no matching elements');
    }

    lastOrDefault(selector = fnTrue) {
        for (let item of this.reverse()) {
            if (selector(item)) {
                return item;
            }
        }
    }

    map(fn) {
        return this.select(fn);
    }

    select(fn = fnSelf) {
        return new SelectEnumerable(this, fn);
    }

    selectMany(colSelector = fnSelf, resSelector) {
        return new SelectManyEnumerable(this, colSelector, resSelector);
    }

    single(selector = fnTrue) {
        var matched;
        for (let item of this) {
            if (selector(item)) {
                if (matched) {
                    throw Error('Sequence contains more than one matching element');
                } else {
                    matched = item;
                }
            }
        }
        if (matched) {
            return matched;
        }

        throw Error('Sequence contains no matching element');
    }

    singleOrDefault(selector = fnTrue) {
        try {
            return this.single(selector);
        } catch (e) {
            if (e.message === 'Sequence contains no matching element') {
                return undefined;
            }
            throw e;
        }
    }

    skip(count = 0) {
        return new SkipEnumerable(this, count);
    }

    skipWhile(fn = 0) {
        if (fn === 0) {
            return this.skip();
        }
        return new SkipEnumerable(this, fn);
    }

    take(count = 0) {
        return new TakeEnumerable(this, count);
    }

    takeWhile(fn = 0) {
        if (fn === 0) {
            return this.take();
        }
        return new TakeEnumerable(this, fn);
    }

    toArray() {
        var arr = [];
        for (let i of this) {
            arr.push(i);
        }
        return arr;
    }

    where(selector) {
        return new WhereEnumerable(this, selector);
    }

    static range(start = 0, end = 0) {
        return new RangeEnumerable(start, end);
    }

    static repeat(item, count = 0) {
        return new RepeatEnumerable(item, count);
    }
}

class ConcatEnumerable extends Enumerable {
    constructor(arr, col) {
        super();
        this[parentSymbol] = arr;
        this[colSymbol] = Array.isArray(col) ? col.asEnumerable() : col;
    }

    next() {
        var value = this[parentSymbol].next();
        if (!value.done) {
            return value;
        }

        value = this[colSymbol].next();
        return value;
    }
}

class WhereEnumerable extends Enumerable {
    constructor(arr, selector) {
        super();
        this[parentSymbol] = arr;
        this[selectorSymbol] = selector;
        this[indexSymbol] = 0;
    }

    next() {
        var val = this[parentSymbol].next();
        if (val.done) {
            return val;
        }

        if (this[selectorSymbol](val.value, this[indexSymbol]++)) {
            return val;
        }

        return this.next();
    }
}

class SelectEnumerable extends Enumerable {
    constructor(arr, fn) {
        super();
        this[parentSymbol] = arr;
        this[selectorSymbol] = fn;
        this[indexSymbol] = 0;
    }

    next() {
        var value = this[parentSymbol].next();
        if (value.done) {
            return value;
        }
        return {
            value: this[selectorSymbol](value.value, this[indexSymbol]++),
            done: false
        };
    }
}

class SelectManyEnumerable extends Enumerable {
    constructor(arr, colSelector, resultSelector) {
        super();
        this[parentSymbol] = arr;
        this[colSymbol] = colSelector;
        this[selectorSymbol] = resultSelector || ((_, x) => x);
        this[indexSymbol] = 0;
    }

    next() {
        var value = this[parentSymbol].next();
        if (value.done) {
            return value;
        }
        let arr = this[colSymbol](value.value, this[indexSymbol]++);
        return {
            value: this[selectorSymbol](arr, arr[0]),
            done: false
        };
    }
}

class RangeEnumerable extends Enumerable {
    constructor(start, count) {
        super();
        this[countSymbol] = count;
        this[indexSymbol] = 0;
        this[startSymbol] = start;
    }

    next() {
        if (this[indexSymbol] === this[countSymbol]) {
            return {
                done: true
            };
        }

        var value = this[startSymbol];
        this[startSymbol]++;
        this[indexSymbol]++;
        return {
            value: value,
            done: false
        };
    }
}

class TakeEnumerable extends Enumerable {
    constructor(arr, selector) {
        super();
        this[parentSymbol] = arr;
        this[selectorSymbol] = selector;
        this[indexSymbol] = 0;
    }

    next() {
        var item = this[parentSymbol].next();
        if (item.done) {
            return item;
        }

        if (typeof this[selectorSymbol] === 'number') {
            if (this[indexSymbol] < this[selectorSymbol]) {
                this[indexSymbol]++;
                return item;
            } else {
                return {
                    done: true
                };
            }
        } else {
            if (this[selectorSymbol](item.value, this[indexSymbol])) {
                this[indexSymbol]++;
                return item;
            } else {
                return {
                    done: true
                };
            }
        }
    }
}

class SkipEnumerable extends Enumerable {
    constructor(arr, selector) {
        super();
        this[parentSymbol] = arr;
        this[selectorSymbol] = selector;
        this[indexSymbol] = 0;
        this[startSymbol] = false;
    }

    next() {
        var item = this[parentSymbol].next();
        if (item.done) {
            return item;
        }

        var i = this[indexSymbol];
        this[indexSymbol]++;
        if (typeof this[selectorSymbol] === 'number') {
            if (i >= this[selectorSymbol]) {
                return item;
            } else {
                return this.next();
            }
        } else {
            if (!this[startSymbol] && !this[selectorSymbol](item.value, i)) {
                this[startSymbol] = true;
            }
            if (this[startSymbol]) {
                return item;
            }
            return this.next();
        }
    }
}

class RepeatEnumerable extends Enumerable {
    constructor(item, count) {
        super();
        this[selectorSymbol] = item;
        this[countSymbol] = count;
        this[indexSymbol] = 0;
    }

    next() {
        if (this[indexSymbol] === this[countSymbol]) {
            return {
                done: true
            };
        }

        var stripped = JSON.stringify(this[selectorSymbol]);
        this[indexSymbol]++;
        return {
            value: JSON.parse(stripped),
            done: false
        };
    }
}

// extension methods
Array.prototype.asEnumerable = function() {
    return new Enumerable(this);
};

export default Enumerable;
<|endoftext|>


<commit_before>(function (global) {
    'use strict';

    var __extends = function (d, b) {
        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    };

    var fnTrue = function () { return true; };
    var fnSelf = function (x) { return x; };

    var generator = function* (array) {
        for (let i = 0; i < array.length; i++) {
            yield array[i];
        }
    };

    var Enumerable = function (array) {
        if (this && this.constructor == Enumerable) {
            throw 'This is not a constructable type, don\'t use the `new` operator';
        }
        var instance = generator.bind(this, array);

        __extends(instance, generator);
        return instance
    };

    var first = function (nullable, selector) {
        return function (fn) {
            fn = fn || selector;
            for (let item of this()) {
                if (fn(item)) {
                    return item;
                }
            }

            if (nullable) {
                return undefined;
            }
            throw 'Sequence contains no matching elements';
        };
    };

    var single = function (nullable, selector) {
        return function (fn) {
            fn = fn || selector;
            var matched;
            for (let item of this()) {
                if (fn(item)) {
                    if (matched) {
                        throw 'Sequence contains more than one matching element';
                    }
                    else {
                        matched = item;
                    }
                }
            }

            if (matched) {
                return matched;
            }

            if (!matched && nullable) {
                return undefined;
            }

            throw 'Sequence contains no matching elements';
        };
    };

    var all = function (fn) {
        for (let x of this()) {
            if (!fn(x)) {
                return false;
            }
        }

        return true;
    };

    var any = function (fn) {
        fn = fn || fnTrue;

        for (let x of this()) {
            if (fn(x)) {
                return true;
            }
        }
        return false;
    }

    var count = function (fn) {
        fn = fn || fnTrue;

        var count = 0;
        for (var i of this()) {
            if (fn(i)) {
                count++;
            }
        }
        return count;
    };

    var aggregate = function (seed, fn, selector) {
        var it = this();

        switch (arguments.length) {
            case 1:
                fn = seed;
                seed = it.next().value;
                break;

            case 2:
                if (typeof seed === 'function') {
                    selector = fn;
                    fn = seed;
                    seed = it.next().value;
                }
                break;
        }
        for (let item of it) {
            seed = fn(seed, item);
        }

        if (selector) {
            return selector(seed);
        }
        return seed;
    };

    var average = function (fn) {
        var total = 0;
        var count = 0;

        fn = fn || fnSelf;

        for (let item of this()) {
            total += fn(item);
            count++;
        }

        if (count) {
            return total / count;
        }
        throw Error('No items in the collection');
    };

    var concat = function (col) {
        return ConcatEnumerable(this, col);;
    };

    var contains = function (value, tester) {
        var it = this();

        if (!tester) {
            for (let item of it) {
                if (item === value) {
                    return true;
                }
            }
        } else {
            for (let item of it) {
                if (tester(item, value)) {
                    return true;
                }
            }
        }
        return false;
    };

    var where = function (fn) {
        return WhereEnumerable(this, fn);
    };

    var select = function (fn) {
        return SelectEnumerable(this, fn);
    };

    var selectMany = function (fn) {
        return SelectManyEnumerable(this, fn);
    };

    var take = function (count) {
        return TakeEnumerable(this, count || 0);
    };

    var takeWhile = function (fn) {
        return TakeEnumerable(this, fn || 0);
    };

    var skip = function (count) {
        return SkipEnumerable(this, count || 0);
    };

    var skipWhile = function (fn) {
        return SkipEnumerable(this, fn || 0);
    };

    var toArray = function() {
        var arr = [];
        for (let i of this()) {
            arr.push(i);
        }
        return arr;
    };

    generator.where = where;
    generator.filter = where;

    generator.select = select;
    generator.map = select;
    generator.selectMany = selectMany;

    generator.first = first(false, fnTrue);
    generator.firstOrDefault = first(true, fnTrue);

    generator.single = single(false, fnTrue);
    generator.singleOrDefault = single(true, fnTrue);

    generator.all = all;
    generator.any = any;
    generator.count = count;
    generator.aggregate = aggregate;
    generator.average = average;
    generator.concat = concat;
    generator.contains = contains;

    generator.take = take;
    generator.takeWhile = takeWhile;

    generator.skip = skip;
    generator.skipWhile = skipWhile;

    generator.toArray = toArray;

    var ConcatEnumerable = (function (__super) {
        return function (parent, col) {
            if (col.constructor === Array) {
                col = col.asEnumerable();
            }

            function* concat(col) {
                for (let item of parent()) {
                    yield item;
                }

                for (let item of col()) {
                    yield item;
                }
            }

            var x = concat.bind(this, col);
            __extends(x, __super);
            return x;
        };
    })(generator);

    var WhereEnumerable = (function (__super) {
        return function WhereEnumerable(parent, fn) {
            function* where(fn) {
                var index = 0;
                for (let x of parent()) {
                    if (fn(x, index)) {
                        yield x;
                    }
                    index++;
                }
            }

            var x = where.bind(this, fn);
            __extends(x, __super);
            return x;
        };
    })(generator);

    var SelectEnumerable = (function (__super) {
        return function (parent, fn) {
            var selector = function* (parent, fn) {
                var index = 0;
                for (let item of parent()) {
                    yield fn(item, index++);
                }
            };

            var instance = selector.bind(this, parent, fn);
            __extends(instance, __super);
            return instance;
        };
    })(generator);

    var SelectManyEnumerable = (function (__super) {
        return function (parent, colSelector, resultSelector) {
            var selectMany = function* (parent, colSelector, resultSelector) {
                resultSelector = resultSelector || function (col, x) { return x; };
                var index = 0;

                for (let item of parent()) {
                    let arr = colSelector(item, index++);
                    for (let i = 0; i < arr.length; i++) {
                        let foo = resultSelector(arr, arr[i]);
                        yield foo;
                    }
                }
            };

            var instance = selectMany.bind(this, parent, colSelector, resultSelector);
            __extends(instance, __super);
            return instance;
        };
    })(generator);

    var RangeEnumerable = (function (__super) {
        return function (start, end) {
            var ranger = function* (start, end) {
                for (let i = 0; i < end; start++, i++) {
                    yield start;
                }
            };

            var instance = ranger.bind(this, start, end);
            __extends(instance, __super);
            return instance;
        };
    })(generator);

    var TakeEnumerable = (function (__super) {
        return function (parent, selector) {
            var taker = function* (parent, selector) {
                var index = 0;
                if (typeof selector === 'number') {
                    for (let item of parent()) {
                        if (index < selector) {
                            yield item;
                            index++;
                        } else {
                            break;
                        }
                    }
                } else if (typeof selector === 'function') {
                    for (let item of parent()) {
                        if (selector(item, index)) {
                            yield item;
                        } else {
                            break;
                        }
                        index++;
                    }
                }
            };

            var instance = taker.bind(this, parent, selector);
            __extends(instance, __super);
            return instance;
        };
    })(generator);

    var SkipEnumerable = (function (__super) {
        return function (parent, selector) {
            var skippy = function* (parent, selector) {
                var index = 0;
                if (typeof selector === 'number') {
                    for (let item of parent()) {
                        if (index >= selector) {
                            yield item;
                        }
                        index++;
                    }
                } else if (typeof selector === 'function') {
                    let flag = false;
                    index = -1;
                    for (let item of parent()) {
                        index++;
                        if (!flag && !selector(item, index)) {
                            flag = true;
                        }

                        if (flag) {
                            yield item;
                        }
                    }
                }
            };

            var instance = skippy.bind(this, parent, selector);
            __extends(instance, __super);
            return instance;
        };
    })(generator);

    var RepeatEnumerable = (function (__super) {
        return function (item, count) {
            var repeater = function* (item, count) {
                var stripped = JSON.stringify(item);
                for (var i = 0; i < count; i++) {
                    yield JSON.parse(stripped);
                }
            };

            var instance = repeater.bind(this, item, count);
            __extends(instance, __super);
            return instance;
        };
    })(generator);

    Enumerable.range = function (start, end) {
        start = start || 0;
        end = end || 0;

        return RangeEnumerable(start, end);
    };

    Enumerable.repeat = function (item, count) {
        return RepeatEnumerable(item, count || 0);
    };

    // extension methods
    Array.prototype.asEnumerable = function() {
        return Enumerable(this);
    };

    if (typeof module === 'object' && typeof module.exports === 'object') {
        module.exports = Enumerable;
    } else if (typeof define === 'function' && define.amd) {
        define('linq', function () {
            return Enumerable;
        });
    } else {
        global.Enumerable = Enumerable;
    }
})(this);
<commit_msg>using ES6 arrow functions<commit_after>(function (global) {
    'use strict';

    var __extends = function (d, b) {
        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    };

    var fnTrue = () => true;
    var fnSelf = x => x;

    var generator = function* (array) {
        for (let i = 0; i < array.length; i++) {
            yield array[i];
        }
    };

    var Enumerable = function (array) {
        if (this && this.constructor == Enumerable) {
            throw 'This is not a constructable type, don\'t use the `new` operator';
        }
        var instance = generator.bind(this, array);

        __extends(instance, generator);
        return instance
    };

    var first = function (nullable, selector) {
        return function (fn) {
            fn = fn || selector;
            for (let item of this()) {
                if (fn(item)) {
                    return item;
                }
            }

            if (nullable) {
                return undefined;
            }
            throw 'Sequence contains no matching elements';
        };
    };

    var single = function (nullable, selector) {
        return function (fn) {
            fn = fn || selector;
            var matched;
            for (let item of this()) {
                if (fn(item)) {
                    if (matched) {
                        throw 'Sequence contains more than one matching element';
                    }
                    else {
                        matched = item;
                    }
                }
            }

            if (matched) {
                return matched;
            }

            if (!matched && nullable) {
                return undefined;
            }

            throw 'Sequence contains no matching elements';
        };
    };

    var all = function (fn) {
        for (let x of this()) {
            if (!fn(x)) {
                return false;
            }
        }

        return true;
    };

    var any = function (fn) {
        fn = fn || fnTrue;

        for (let x of this()) {
            if (fn(x)) {
                return true;
            }
        }
        return false;
    }

    var count = function (fn) {
        fn = fn || fnTrue;

        var count = 0;
        for (var i of this()) {
            if (fn(i)) {
                count++;
            }
        }
        return count;
    };

    var aggregate = function (seed, fn, selector) {
        var it = this();

        switch (arguments.length) {
            case 1:
                fn = seed;
                seed = it.next().value;
                break;

            case 2:
                if (typeof seed === 'function') {
                    selector = fn;
                    fn = seed;
                    seed = it.next().value;
                }
                break;
        }
        for (let item of it) {
            seed = fn(seed, item);
        }

        if (selector) {
            return selector(seed);
        }
        return seed;
    };

    var average = function (fn) {
        var total = 0;
        var count = 0;

        fn = fn || fnSelf;

        for (let item of this()) {
            total += fn(item);
            count++;
        }

        if (count) {
            return total / count;
        }
        throw Error('No items in the collection');
    };

    var concat = function (col) {
        return ConcatEnumerable(this, col);;
    };

    var contains = function (value, tester) {
        var it = this();

        if (!tester) {
            for (let item of it) {
                if (item === value) {
                    return true;
                }
            }
        } else {
            for (let item of it) {
                if (tester(item, value)) {
                    return true;
                }
            }
        }
        return false;
    };

    var where = function (fn) {
        return WhereEnumerable(this, fn);
    };

    var select = function (fn) {
        return SelectEnumerable(this, fn);
    };

    var selectMany = function (fn) {
        return SelectManyEnumerable(this, fn);
    };

    var take = function (count) {
        return TakeEnumerable(this, count || 0);
    };

    var takeWhile = function (fn) {
        return TakeEnumerable(this, fn || 0);
    };

    var skip = function (count) {
        return SkipEnumerable(this, count || 0);
    };

    var skipWhile = function (fn) {
        return SkipEnumerable(this, fn || 0);
    };

    var toArray = function() {
        var arr = [];
        for (let i of this()) {
            arr.push(i);
        }
        return arr;
    };

    generator.where = where;
    generator.filter = where;

    generator.select = select;
    generator.map = select;
    generator.selectMany = selectMany;

    generator.first = first(false, fnTrue);
    generator.firstOrDefault = first(true, fnTrue);

    generator.single = single(false, fnTrue);
    generator.singleOrDefault = single(true, fnTrue);

    generator.all = all;
    generator.any = any;
    generator.count = count;
    generator.aggregate = aggregate;
    generator.average = average;
    generator.concat = concat;
    generator.contains = contains;

    generator.take = take;
    generator.takeWhile = takeWhile;

    generator.skip = skip;
    generator.skipWhile = skipWhile;

    generator.toArray = toArray;

    var ConcatEnumerable = (function (__super) {
        return function (parent, col) {
            if (col.constructor === Array) {
                col = col.asEnumerable();
            }

            function* concat(col) {
                for (let item of parent()) {
                    yield item;
                }

                for (let item of col()) {
                    yield item;
                }
            }

            var x = concat.bind(this, col);
            __extends(x, __super);
            return x;
        };
    })(generator);

    var WhereEnumerable = (function (__super) {
        return function WhereEnumerable(parent, fn) {
            function* where(fn) {
                var index = 0;
                for (let x of parent()) {
                    if (fn(x, index)) {
                        yield x;
                    }
                    index++;
                }
            }

            var x = where.bind(this, fn);
            __extends(x, __super);
            return x;
        };
    })(generator);

    var SelectEnumerable = (function (__super) {
        return function (parent, fn) {
            var selector = function* (parent, fn) {
                var index = 0;
                for (let item of parent()) {
                    yield fn(item, index++);
                }
            };

            var instance = selector.bind(this, parent, fn);
            __extends(instance, __super);
            return instance;
        };
    })(generator);

    var SelectManyEnumerable = (function (__super) {
        return function (parent, colSelector, resultSelector) {
            var selectMany = function* (parent, colSelector, resultSelector) {
                resultSelector = resultSelector || function (col, x) { return x; };
                var index = 0;

                for (let item of parent()) {
                    let arr = colSelector(item, index++);
                    for (let i = 0; i < arr.length; i++) {
                        let foo = resultSelector(arr, arr[i]);
                        yield foo;
                    }
                }
            };

            var instance = selectMany.bind(this, parent, colSelector, resultSelector);
            __extends(instance, __super);
            return instance;
        };
    })(generator);

    var RangeEnumerable = (function (__super) {
        return function (start, end) {
            var ranger = function* (start, end) {
                for (let i = 0; i < end; start++, i++) {
                    yield start;
                }
            };

            var instance = ranger.bind(this, start, end);
            __extends(instance, __super);
            return instance;
        };
    })(generator);

    var TakeEnumerable = (function (__super) {
        return function (parent, selector) {
            var taker = function* (parent, selector) {
                var index = 0;
                if (typeof selector === 'number') {
                    for (let item of parent()) {
                        if (index < selector) {
                            yield item;
                            index++;
                        } else {
                            break;
                        }
                    }
                } else if (typeof selector === 'function') {
                    for (let item of parent()) {
                        if (selector(item, index)) {
                            yield item;
                        } else {
                            break;
                        }
                        index++;
                    }
                }
            };

            var instance = taker.bind(this, parent, selector);
            __extends(instance, __super);
            return instance;
        };
    })(generator);

    var SkipEnumerable = (function (__super) {
        return function (parent, selector) {
            var skippy = function* (parent, selector) {
                var index = 0;
                if (typeof selector === 'number') {
                    for (let item of parent()) {
                        if (index >= selector) {
                            yield item;
                        }
                        index++;
                    }
                } else if (typeof selector === 'function') {
                    let flag = false;
                    index = -1;
                    for (let item of parent()) {
                        index++;
                        if (!flag && !selector(item, index)) {
                            flag = true;
                        }

                        if (flag) {
                            yield item;
                        }
                    }
                }
            };

            var instance = skippy.bind(this, parent, selector);
            __extends(instance, __super);
            return instance;
        };
    })(generator);

    var RepeatEnumerable = (function (__super) {
        return function (item, count) {
            var repeater = function* (item, count) {
                var stripped = JSON.stringify(item);
                for (var i = 0; i < count; i++) {
                    yield JSON.parse(stripped);
                }
            };

            var instance = repeater.bind(this, item, count);
            __extends(instance, __super);
            return instance;
        };
    })(generator);

    Enumerable.range = (start = 0, end = 0) => RangeEnumerable(start, end);

    Enumerable.repeat = (item, count = 0) => RepeatEnumerable(item, count || 0);

    // extension methods
    Array.prototype.asEnumerable = function() {
        return Enumerable(this);
    };

    if (typeof module === 'object' && typeof module.exports === 'object') {
        module.exports = Enumerable;
    } else if (typeof define === 'function' && define.amd) {
        define('linq', function () {
            return Enumerable;
        });
    } else {
        global.Enumerable = Enumerable;
    }
})(this);
<|endoftext|>


<commit_before>class Lint {
    constructor(tree, filename = null, namespace = []) {
        Object.assign(
            this,
            {
                filename: filename,
                namespace: namespace,
                tree: tree,
            }
        );
    }
    check() {
        return Lint.ShadowTree.Node.typed(this.tree).check();
    }
    static check(tree, filename = null) {
        var l = new Lint(tree, filename);
        return l.check();
    }
};

Lint.PHPStrictError = class extends Error {
};
Lint.ShadowTree = {
    Node: class {
        /** @property {Location|null} loc
          * @property {string} kind
          */
        constructor(node) {
            Object.assign(
                this,
                node
            );
        }
        check(ns) {
            return true;
        }
        static typed(node) {
            var c = Lint.ShadowTree[node.constructor.name];
            if(!c) {
                throw new Error(`No handler for ${node.constructor.name}`);
            }
            return new c(node);
        }
    },
};
Object.assign(
    Lint.ShadowTree,
    {
        Statement: class extends Lint.ShadowTree.Node {
        },
        Expression: class extends Lint.ShadowTree.Node {
        },
    }
);
Object.assign(
    Lint.ShadowTree,
    {
        Assign: class extends Lint.ShadowTree.Statement {
            /** @property {Expression} left
              * @property {Expression} right
              * @property {string} operator
              */
            constructor(node) {
                super(node);
                this.left = Lint.ShadowTree.Node.typed(node.left);
                this.right = Lint.ShadowTree.Node.typed(node.right);
            }
            check(ns) {
                ns.push(this.left.name);
                this.right.check(ns);
                return super.check(ns);
            }
        },
        Block: class extends Lint.ShadowTree.Statement {
            /** @property {Node[]} children */
            constructor(node) {
                super(node);
                this.children = node.children.map(child => Lint.ShadowTree.Node.typed(child));
            }
        },
        Literal: class extends Lint.ShadowTree.Expression {
            /** @property {Node|string|number|boolean|null} value */
        },
        Sys: class extends Lint.ShadowTree.Statement {
            /** @property {Node[]} arguments */
            constructor(node) {
                super(node);
                this.arguments = node.arguments.map(child => Lint.ShadowTree.Node.typed(child));
            }
        },
        Variable: class extends Lint.ShadowTree.Expression {
            /** @property {string|Node} name
              * @property {bool} byref
              */
            constructor(node) {
                super(node);
                if(typeof this.name == "object") {
                    this.name = Lint.ShadowTree.Node.typed(child);
                }
            }
            check(ns) {
                if(!ns.find(name => name == this.name)) {
                    throw new Lint.PHPStrictError(`Name \$${this.name} is not defined in this namespace`);
                }
                return super.check(ns);
            }
        },
    }
);
Object.assign(
    Lint.ShadowTree,
    {
        Echo: class extends Lint.ShadowTree.Sys {
            check(ns) {
                this.arguments.forEach(child => child.check(ns));
                return super.check(ns);
            }
        },
        Program: class extends Lint.ShadowTree.Block {
            /** @property {Error[]} errors */
            check(ns) {
                var ns_inner = [];
                this.children.forEach(child => child.check(ns_inner));
                return super.check(ns);
            }
        },
        String: class extends Lint.ShadowTree.Literal {
            /** @property {string} label */
        },
    }
);
module.exports = Lint;
<commit_msg>Switch to property getters in general<commit_after>class Lint {
    constructor(tree, filename = null, namespace = []) {
        Object.assign(
            this,
            {
                filename: filename,
                namespace: namespace,
                tree: tree,
            }
        );
    }
    check() {
        return Lint.ShadowTree.Node.typed(this.tree).check();
    }
    static check(tree, filename = null) {
        var l = new Lint(tree, filename);
        return l.check();
    }
};

Lint.PHPStrictError = class extends Error {
};
Lint.ShadowTree = {
    Node: class {
        constructor(node) {
            Object.assign(
                this,
                {
                    _cache: {},
                    node: node
                }
            );
        }
        /** @property {string} kind */
        get kind() {
            return this.node.kind;
        }
        /** @property {Location|null} loc */
        get loc() {
            return this.node.loc;
        }
        cacheProperty(name, f) {
            if(!this._cache.hasOwnProperty(name)) {
                this._cache[name] = f(this.node[name]);
            }
            return this._cache[name];
        }
        check(ns) {
            return true;
        }
        static typed(node) {
            var c = Lint.ShadowTree[node.constructor.name];
            if(!c) {
                throw new Error(`No handler for ${node.constructor.name}`);
            }
            return new c(node);
        }
    },
};
Object.assign(
    Lint.ShadowTree,
    {
        Statement: class extends Lint.ShadowTree.Node {
        },
        Expression: class extends Lint.ShadowTree.Node {
        },
    }
);
Object.assign(
    Lint.ShadowTree,
    {
        Assign: class extends Lint.ShadowTree.Statement {
            /** @property {string} operator */
            get operator() {
                return this.node.operator;
            }
            /** @property {Expression} left */
            get left() {
                return this.cacheProperty("left", subnode => Lint.ShadowTree.Node.typed(subnode))
            }
            /** @property {Expression} right */
            get right() {
                return this.cacheProperty("right", subnode => Lint.ShadowTree.Node.typed(subnode))
            }
            check(ns) {
                ns.push(this.left.name);
                this.right.check(ns);
                return super.check(ns);
            }
        },
        Block: class extends Lint.ShadowTree.Statement {
            /** @property {Node[]} children */
            get children() {
                return this.cacheProperty(
                    "children",
                    nodes => nodes.map(child => Lint.ShadowTree.Node.typed(child))
                );
            }
        },
        Literal: class extends Lint.ShadowTree.Expression {
            /** @property {Node|string|number|boolean|null} value */
        },
        Sys: class extends Lint.ShadowTree.Statement {
            /** @property {Node[]} arguments */
            get arguments() {
                return this.cacheProperty(
                    "arguments",
                    nodes => nodes.map(child => Lint.ShadowTree.Node.typed(child))
                );
            }
        },
        Variable: class extends Lint.ShadowTree.Expression {
            /** @property {bool} byref */
            get byref() {
                return this.node.byref;
            }
            /** @property {string|Node} name */
            get name() {
                return this.cacheProperty(
                    "name",
                    node => {
                        if(typeof node == "object") {
                            return Lint.ShadowTree.Node.typed(child);
                        } else {
                            return node;
                        }
                    }
                );
            }
            check(ns) {
                if(!ns.find(name => name == this.name)) {
                    throw new Lint.PHPStrictError(`Name \$${this.name} is not defined in this namespace`);
                }
                return super.check(ns);
            }
        },
    }
);
Object.assign(
    Lint.ShadowTree,
    {
        Echo: class extends Lint.ShadowTree.Sys {
            check(ns) {
                this.arguments.forEach(child => child.check(ns));
                return super.check(ns);
            }
        },
        Program: class extends Lint.ShadowTree.Block {
            /** @property {Error[]} errors */
            check(ns) {
                var ns_inner = [];
                this.children.forEach(child => child.check(ns_inner));
                return super.check(ns);
            }
        },
        String: class extends Lint.ShadowTree.Literal {
            /** @property {string} label */
        },
    }
);
module.exports = Lint;
<|endoftext|>