<commit_before>import {PhoneNumberFormat, PhoneNumberUtil} from 'google-libphonenumber';

import DataType, {validationErrors} from './';
import ValidationError from './validationError';

const phoneUtil = PhoneNumberUtil.getInstance();

/**
 * The DataType for text values.
 *
 * |Name|Type|Attribute|Description|
 * |----|----|---------|-----------|
 * |type|{@link string}|

optional

default: 'raw'

 | The type of text to handle. This affects both validation and display. 'raw' | 'email' | 'url' | 'ssn' | 'zipCode' | 'tel' | 'password' |
 * |multi|{@link boolean}|

optional

default: false

 | Whether or not to allow newline characters in the text. |
 * |mask|{@link string}|

optional

default: '###-##-####' (for `type='ssn'` only)
 | A mask to use while editing the value. |
 *
 * @extends {DataType}
 */
export default class TextType extends DataType {
  static typeName = 'text';

  static regexps = {
    email: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
    url: /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/,
    ssn: /^(\d{3}-?\d{2}-?\d{4}|XXX-XX-XXXX)$/,
    zipCode: /^\d{5}([ \-]\d{4})?$/,
  };

  getType() {
    return this.options.get('textType', 'raw');
  }

  isMultiLined() {
    return this.options.get('multi', false);
  }

  getMask() {
    const defaultMask = this.getType() == 'ssn' ? '###-##-####' : '';
    return this.options.get('mask', defaultMask);
  }

  hasValue(value, checkDefault) {
    if (!super.hasValue(value, checkDefault)) {
      return false;
    }
    return typeof value == 'string' && value.length > 0;
  }

  getDefaultValue() {
    return super.getDefaultValue('');
  }

  format(value) {
    switch (this.getType()) {
      case 'tel':
        return this.getDisplay(value);

      default:
        return value || '';
    }
  }

  getDisplay(value) {
    switch (this.getType()) {
      case 'password':
        return '********';

      case 'tel':
        try {
          const telno = phoneUtil.parse(value, 'US');
          return phoneUtil.format(telno, PhoneNumberFormat.NATIONAL);
        } catch (e) {}
        return value || '';

      default:
        if (this.isMultiLined()) {
          if (value && value.includes('\n')) {
            return `${value.split('\n')[0]}...`;
          }
        }
        return value || '';
    }
  }

  validate(value) {
    return super.validate(value, () => {
      const type = this.getType();
      switch (type) {
        case 'email':
        case 'url':
        case 'ssn':
        case 'zipCode':
          if (!TextType.regexps[type].test(value)) {
            return new ValidationError(validationErrors[type], this);
          }
          return;

        case 'tel':
          try {
            const telno = phoneUtil.parse(value, 'US');
            if (!phoneUtil.isValidNumber(telno)) {
              return new ValidationError(validationErrors.tel, this);
            }
          } catch (e) {
            return new ValidationError(e.message, this);
          }
          return;

        case 'password':
        default:
          if (!this.isMultiLined() && value.includes('\n')) {
            return new ValidationError(validationErrors.singleline, this);
          }
          return;
      }
    });
  }

  filter(filterValue, rowValue) {
    const filterString = `${filterValue}`.toLowerCase();
    const rowString = `${rowValue}`.toLowerCase();
    return rowString.indexOf(filterString) >= 0;
  }
}
<commit_msg>added SSN check into getDisplay function which adds dashes to SSN<commit_after>import {PhoneNumberFormat, PhoneNumberUtil} from 'google-libphonenumber';

import DataType, {validationErrors} from './';
import ValidationError from './validationError';

const phoneUtil = PhoneNumberUtil.getInstance();

/**
 * The DataType for text values.
 *
 * |Name|Type|Attribute|Description|
 * |----|----|---------|-----------|
 * |type|{@link string}|

optional

default: 'raw'

 | The type of text to handle. This affects both validation and display. 'raw' | 'email' | 'url' | 'ssn' | 'zipCode' | 'tel' | 'password' |
 * |multi|{@link boolean}|

optional

default: false

 | Whether or not to allow newline characters in the text. |
 * |mask|{@link string}|

optional

default: '###-##-####' (for `type='ssn'` only)
 | A mask to use while editing the value. |
 *
 * @extends {DataType}
 */
export default class TextType extends DataType {
  static typeName = 'text';

  static regexps = {
    email: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
    url: /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/,
    ssn: /^(\d{3}-?\d{2}-?\d{4}|XXX-XX-XXXX)$/,
    ssnDisplay: /^(\d{3}-\d{2}-\d{4})$/,
    zipCode: /^\d{5}([ \-]\d{4})?$/,
  };

  getType() {
    return this.options.get('textType', 'raw');
  }

  isMultiLined() {
    return this.options.get('multi', false);
  }

  getMask() {
    const defaultMask = this.getType() == 'ssn' ? '###-##-####' : '';
    return this.options.get('mask', defaultMask);
  }

  hasValue(value, checkDefault) {
    if (!super.hasValue(value, checkDefault)) {
      return false;
    }
    return typeof value == 'string' && value.length > 0;
  }

  getDefaultValue() {
    return super.getDefaultValue('');
  }

  format(value) {
    switch (this.getType()) {
      case 'tel':
        return this.getDisplay(value);

      default:
        return value || '';
    }
  }

  getDisplay(value) {
    switch (this.getType()) {
      case 'password':
        return '********';

      case 'tel':
        try {
          const telno = phoneUtil.parse(value, 'US');
          return phoneUtil.format(telno, PhoneNumberFormat.NATIONAL);
        } catch (e) {}
        return value || '';

      case 'ssn':
        if(!TextType.regexps.ssnDisplay.test(value)) {
          return value.replace(TextType.regexps.ssnDisplay, "$1-$2-$3");
        }
        return value || '';

      default:
        if (this.isMultiLined()) {
          if (value && value.includes('\n')) {
            return `${value.split('\n')[0]}...`;
          }
        }
        return value || '';
    }
  }

  validate(value) {
    return super.validate(value, () => {
      const type = this.getType();
      switch (type) {
        case 'email':
        case 'url':
        case 'ssn':
        case 'zipCode':
          if (!TextType.regexps[type].test(value)) {
            return new ValidationError(validationErrors[type], this);
          }
          return;

        case 'tel':
          try {
            const telno = phoneUtil.parse(value, 'US');
            if (!phoneUtil.isValidNumber(telno)) {
              return new ValidationError(validationErrors.tel, this);
            }
          } catch (e) {
            return new ValidationError(e.message, this);
          }
          return;

        case 'password':
        default:
          if (!this.isMultiLined() && value.includes('\n')) {
            return new ValidationError(validationErrors.singleline, this);
          }
          return;
      }
    });
  }

  filter(filterValue, rowValue) {
    const filterString = `${filterValue}`.toLowerCase();
    const rowString = `${rowValue}`.toLowerCase();
    return rowString.indexOf(filterString) >= 0;
  }
}
<|endoftext|>


<commit_before>// Use this to customize the visual editor boot process
// Just mirror the options specified in your visual editor's config with the new
// options here.  This will completely override anything specified in your visual
// editor's boot process for that key, e.g. skin: 'something_else'
if (typeof(custom_visual_editor_options) == "undefined") {
  custom_visual_editor_options = {};
}
<commit_msg>Fixed variable name for editor options<commit_after>// Use this to customize the visual editor boot process
// Just mirror the options specified in your visual editor's config with the new
// options here.  This will completely override anything specified in your visual
// editor's boot process for that key, e.g. skin: 'something_else'
if (typeof(custom_visual_editor_boot_options) == "undefined") {
  var custom_visual_editor_boot_options = {};
}
<|endoftext|>


<commit_before>/**
Copyright © 2015 Luis Sieira Garcia

This file is part of Planète.

    Planète is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Planète is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>
**/
'use strict';

var Logger = (function _Logger() {
  var CoreModule = require('_/core-module'),
      config = require('_').config;

  var logger = new CoreModule(__dirname);

  var Color = {
    GREEN_FG: '\x1b[32m',
    MAGENTA_FG: '\x1b[35m',
    RED_FG: '\x1b[31m',
    RESET:  '\x1b[0m',
    YELLOW_FG: '\x1b[33m'
  };

  function colorLogger(tag, color) {
    return function() {
      if(config.NODE_ENV != 'test') {
        var args = [].slice.call(arguments);
        console.log.apply(null, ['%s [%s] %s [%s] ' + args.shift(), color, tag, Color.RESET, Date(Date.now())].concat(args));
      }
    }
  }

  logger.close = function() {};
  logger.new = function() {
    return new _Logger();
  };

  logger.log = console.log;
  logger.info = colorLogger('i', Color.YELLOW_FG);
  logger.OK = colorLogger('✔', Color.GREEN_FG);
  logger.error = colorLogger('x', Color.RED_FG);
  logger.stack = logger.error;

  logger.middleware = function(req, res, next) {
    var ip = req.ip || req._remoteAddress || (req.connection && req.connection.remoteAddress) || undefined;
    var url = req.originalUrl || req.url;

    logger.info('%s %s request from %s ', req.method, url, ip);
    next();
  }

  logger.OK('Logger is configured');

  return logger;
})();

module.exports = Logger;
<commit_msg>change middleware to log response<commit_after>/**
Copyright © 2015 Luis Sieira Garcia

This file is part of Planète.

    Planète is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Planète is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>
**/
'use strict';

var Logger = (function _Logger() {
  var CoreModule = require('_/core-module'),
      config = require('_').config;

  var logger = new CoreModule(__dirname);

  var Color = {
    BLUE_FG: '\x1b[34m',
    GREEN_FG: '\x1b[32m',
    MAGENTA_FG: '\x1b[35m',
    RED_FG: '\x1b[31m',
    RESET:  '\x1b[0m',
    YELLOW_FG: '\x1b[33m'
  };

  function colorLogger(tag, color) {
    return function() {
      if(config.NODE_ENV != 'test') {
        var args = [].slice.call(arguments);
        console.log.apply(null, ['%s [%s] %s [%s] ' + args.shift(), color, tag, Color.RESET, Date(Date.now())].concat(args));
      }
    }
  }

  logger.close = function() {};
  logger.new = function() {
    return new _Logger();
  };

  logger.log = console.log;
  logger.info = colorLogger('i', Color.YELLOW_FG);
  logger.OK = colorLogger('✔', Color.GREEN_FG);
  logger.error = colorLogger('x', Color.RED_FG);
  logger.http = colorLogger('ǁ', Color.BLUE_FG);
  logger.stack = logger.error;

  logger.middleware = function(req, res, next) {
    var ip = req.ip || req._remoteAddress || (req.connection && req.connection.remoteAddress) || undefined;
    var url = req.originalUrl || req.url;

    req.on('end', function() {
      logger.http('%s - "%s %s" %d', ip, req.method, url, res.statusCode);
    });
    next();
  }

  logger.OK('Logger is configured');

  return logger;
})();

module.exports = Logger;
<|endoftext|>


<commit_before>'use strict';

import _ from 'lodash';
import nodefn from 'when/node';
import { reach } from 'origami';

import rest from '../lib/rest-client';

function availability (options, callback) {
  const settings = {
    method: 'POST',
    path: 'https://api.cronofy.com/v1/availability',
    headers: {
      Authorization: 'Bearer ' + options.access_token
    },
    params: _.omit(options, 'access_token')
  };
  const result = rest(settings).fold(reach, 'entity');

  return nodefn.bindCallback(result, callback);
}

export default availability;
<commit_msg>Set content type to json for availability API<commit_after>'use strict';

import _ from 'lodash';
import nodefn from 'when/node';
import { reach } from 'origami';

import rest from '../lib/rest-client';

function availability (options, callback) {
  const settings = {
    method: 'POST',
    path: 'https://api.cronofy.com/v1/availability',
    headers: {
      Authorization: 'Bearer ' + options.access_token,
      'Content-Type': 'application/json',
    },
    params: _.omit(options, 'access_token')
  };
  const result = rest(settings).fold(reach, 'entity');

  return nodefn.bindCallback(result, callback);
}

export default availability;
<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * Packages needed for certain APIs
 */
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

/**
 * Code editor to put on page.
 */
function codeEditor() {
  var codeText =
    "int number = 0;" +
    "\nfor(int i=0; i<3; i++){" +
    "\n  number++;" +
    "\n  console.writeln(\"Current Number: \" + number);" +
    "\n}" +
    "\nconsole.writeln(\"Final Number: \" + number)";

  var myCodeEditor = CodeMirror.fromTextArea(document.querySelector('#js'), {
    autocorrect: true,
    lineNumbers: true,
    mode: "javascript",
    spellcheck: true,
    theme: "base16-dark",
    value: codeText
  });
}

/**
 * "Runs" the code in the looping code editor.
 */
function compile() {
  // Display the output of the code on the page
  document.querySelector('#code').style.visibility = 'visible';
  document.querySelector('#code').style.display = 'block';
}

/**
 * Deletes all the comments from the 'Comments' servlet.
 */
async function deleteDataUsingAsyncAwait() {
  // Retrieve the data from '/comments' and delete the comments from the admin page
  /* TODO: handle errors */
  const response = await fetch('/comments', {
    method: 'DELETE',
  });

  // Delete the data from the page
  const dataContainer = document.querySelector('#data-container');
  dataContainer.style.visibility = 'hidden';
  dataContainer.style.display = 'block';
  dataContainer.innerHTML = data;
}

/**
  * Fetches sport votes and uses it to create a chart.
  */
function drawChart() {
  fetch('/sports').then(response => response.json())
  .then((sportVotes) => {
    const data = new google.visualization.DataTable();
    data.addColumn('string', 'Sport');
    data.addColumn('number', 'Votes');
    Object.keys(sportVotes).forEach((sport) => {
      data.addRow([sport, sportVotes[sport]]);
    });

    const options = {
      'title': 'Favorite Sports',
      'width': 550,
      'height': 500,
      'backgroundColor': '#b0b7bc',
    };

    const chart = new google.visualization.ColumnChart(
        document.querySelector('#chart-container'));
    chart.draw(data, options);
  });

  // Display the chart on to the page
  document.querySelector('#chart-container').style.visibility = 'visible';
  document.querySelector('#chart-container').style.display = 'block';
}

/**
 * Adds the data from the Comments servlet using async/await (the return values are used directly), and converts it to a JSON.
 */
async function getDataUsingAsyncAwait() {
  // Retrieve the data from '/comments'
  /* TODO: handle errors */
  const response = await fetch('/comments?numComments=' + document.querySelector('#numComments').value);
  const data = await response.json();
  var text = "";
  for(i = 0; i < data.length; i++){
    text += "" + data[i].name + " " + data[i].email + "" + " " + "" + data[i].comment + "
";
  }

  // Add the data to the page
  const dataContainer = document.querySelector('#data-container');
  dataContainer.style.visibility = 'visible';
  dataContainer.style.display = 'block';
  dataContainer.innerHTML = text;
}

/** Displays login button when user is not signed in. */
function displayLoginOption() {

 fetch('/login')
     .then(response=> response.json())
     .then(studentInfo=> {
     if (studentInfo.userId == null) {
        document.querySelector("#loginLink").innerHTML = "Login";
        console.log(studentInfo.userId);
     } else {
        document.querySelector("#loginLink").innerHTML = "Logout";
     }
     })
     .catch((error) => {
         console.error(error);
         sessionStorage.setItem('logged-in','');
         displayLoginOption();
     });
}

function login(){

  fetch('/login')
    .then(response=> response.json())
    .then(studentInfo=> {
      //If user has nickname then display it if not use their user id.
      const studentNickname = studentInfo.nickname || studentInfo.userId;
      sessionStorage.setItem('logged-in', studentNickname);
      window.location.href = studentInfo.logOutUrl;
    })
    .catch((error) => {
        console.error(error);
        sessionStorage.setItem('logged-in','');
        displayLoginOption();
    });
}

/**
 * Manages the visibility of certain content based on the login status of the user.
 */
function manageVisibility() {
  let dataContainer = document.querySelectorAll('.requiresauth');
  let unauth = document.querySelector('#unauth');
  fetch('/authstatus', {
    method: 'GET',
  }).then(function (response) {
    if (response.ok) {
      for (let item of dataContainer) {
       item.style.visibility = 'visible';
       item.style.display = 'block';
      }
      unauth.style.visibility = 'hidden';
      unauth.style.display = 'none';
      getDataUsingAsyncAwait();
    }
    else {
      for (let item of dataContainer) {
        item.style.visibility = 'hidden';
        item.style.display = 'none';
      }
      unauth.style.visibility = 'visible';
      unauth.style.display = 'block';
    }
  })
  .catch(function() {
    for (let item of dataContainer) {
      item.style.visibility = 'hidden';
      item.style.display = 'none';
    }
    unauth.style.visibility = 'hidden';
    unauth.style.display = 'none';
    });
    codeEditor();
  }

/**
 * Submits the comment to the '/comment' servlet.
 */
async function submitComment() {
  // Retrieve the data from '/comments'
  const data = {
    'name': document.querySelector('#username').value,
    'comment': document.querySelector('#comment').value,
  };
  const response = await fetch('/comments', {
    method: 'POST',
    body: JSON.stringify(data)
  });

  // Set the values to empty strings so the next data can be itself
  document.querySelector('#username').value = "";
  document.querySelector('#comment').value = "";

  // Put the text on the page
  getDataUsingAsyncAwait();
}

/**
 * Submits the vote to the '/sports' servlet.
 */
async function submitVote() {
  // Retrieve the data from '/comments'
  const data = {
    'sport': document.querySelector('#selectsport').value,
  };
  const response = await fetch('/sports', {
    method: 'POST',
  });

  // Set the values to empty strings so the next data can be itself
  document.querySelector('#selectsport').value = "";

  // Put the vote on the graph
  drawChart();
}
<commit_msg>Remove leftover codes from old project.<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * Packages needed for certain APIs
 */
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

/**
 * Code editor to put on page.
 */
function codeEditor() {
  var codeText =
    "int number = 0;" +
    "\nfor(int i=0; i<3; i++){" +
    "\n  number++;" +
    "\n  console.writeln(\"Current Number: \" + number);" +
    "\n}" +
    "\nconsole.writeln(\"Final Number: \" + number)";

  var myCodeEditor = CodeMirror.fromTextArea(document.querySelector('#js'), {
    autocorrect: true,
    lineNumbers: true,
    mode: "javascript",
    spellcheck: true,
    theme: "base16-dark",
    value: codeText
  });
}

/**
 * "Runs" the code in the looping code editor.
 */
function compile() {
  // Display the output of the code on the page
  document.querySelector('#code').style.visibility = 'visible';
  document.querySelector('#code').style.display = 'block';
}

/**
 * Deletes all the comments from the 'Comments' servlet.
 */
async function deleteDataUsingAsyncAwait() {
  // Retrieve the data from '/comments' and delete the comments from the admin page
  /* TODO: handle errors */
  const response = await fetch('/comments', {
    method: 'DELETE',
  });

  // Delete the data from the page
  const dataContainer = document.querySelector('#data-container');
  dataContainer.style.visibility = 'hidden';
  dataContainer.style.display = 'block';
  dataContainer.innerHTML = data;
}

/**
  * Fetches sport votes and uses it to create a chart.
  */
function drawChart() {
  fetch('/sports').then(response => response.json())
  .then((sportVotes) => {
    const data = new google.visualization.DataTable();
    data.addColumn('string', 'Sport');
    data.addColumn('number', 'Votes');
    Object.keys(sportVotes).forEach((sport) => {
      data.addRow([sport, sportVotes[sport]]);
    });

    const options = {
      'title': 'Favorite Sports',
      'width': 550,
      'height': 500,
      'backgroundColor': '#b0b7bc',
    };

    const chart = new google.visualization.ColumnChart(
        document.querySelector('#chart-container'));
    chart.draw(data, options);
  });

  // Display the chart on to the page
  document.querySelector('#chart-container').style.visibility = 'visible';
  document.querySelector('#chart-container').style.display = 'block';
}

/** Displays login button when user is not signed in. */
function displayLoginOption() {

 fetch('/login')
     .then(response=> response.json())
     .then(studentInfo=> {
     if (studentInfo.userId == null) {
        document.querySelector("#loginLink").innerHTML = "Login";
        console.log(studentInfo.userId);
     } else {
        document.querySelector("#loginLink").innerHTML = "Logout";
     }
     })
     .catch((error) => {
         console.error(error);
         sessionStorage.setItem('logged-in','');
         displayLoginOption();
     });
}

function login(){

  fetch('/login')
    .then(response=> response.json())
    .then(studentInfo=> {
      //If user has nickname then display it if not use their user id.
      const studentNickname = studentInfo.nickname || studentInfo.userId;
      sessionStorage.setItem('logged-in', studentNickname);
      window.location.href = studentInfo.logOutUrl;
    })
    .catch((error) => {
        console.error(error);
        sessionStorage.setItem('logged-in','');
        displayLoginOption();
    });
}

/**
 * Manages the visibility of certain content based on the login status of the user.
 */
function manageVisibility() {
  let dataContainer = document.querySelectorAll('.requiresauth');
  let unauth = document.querySelector('#unauth');
  fetch('/authstatus', {
    method: 'GET',
  }).then(function (response) {
    if (response.ok) {
      for (let item of dataContainer) {
       item.style.visibility = 'visible';
       item.style.display = 'block';
      }
      unauth.style.visibility = 'hidden';
      unauth.style.display = 'none';
      getDataUsingAsyncAwait();
    }
    else {
      for (let item of dataContainer) {
        item.style.visibility = 'hidden';
        item.style.display = 'none';
      }
      unauth.style.visibility = 'visible';
      unauth.style.display = 'block';
    }
  })
  .catch(function() {
    for (let item of dataContainer) {
      item.style.visibility = 'hidden';
      item.style.display = 'none';
    }
    unauth.style.visibility = 'hidden';
    unauth.style.display = 'none';
    });
    codeEditor();
  }

/**
 * Submits the comment to the '/comment' servlet.
 */
async function submitComment() {
  // Retrieve the data from '/comments'
  const data = {
    'name': document.querySelector('#username').value,
    'comment': document.querySelector('#comment').value,
  };
  const response = await fetch('/comments', {
    method: 'POST',
    body: JSON.stringify(data)
  });

  // Set the values to empty strings so the next data can be itself
  document.querySelector('#username').value = "";
  document.querySelector('#comment').value = "";

  // Put the text on the page
  getDataUsingAsyncAwait();
}

/**
 * Submits the vote to the '/sports' servlet.
 */
async function submitVote() {
  // Retrieve the data from '/comments'
  const data = {
    'sport': document.querySelector('#selectsport').value,
  };
  const response = await fetch('/sports', {
    method: 'POST',
  });

  // Set the values to empty strings so the next data can be itself
  document.querySelector('#selectsport').value = "";

  // Put the vote on the graph
  drawChart();
}
<|endoftext|>


<commit_before>/* global OC, Handlebars */

/*
 * Copyright (c) 2015
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */

/* globals Handlebars */

(function() {
	if (!OC.Share) {
		OC.Share = {};
	}

	var TEMPLATE =
			'
' +
			'{{#each sharees}}' +
				'
' +
					'{{#if avatarEnabled}}' +
					'

' +
					'{{/if}}' +
					'{{shareWithDisplayName}}' +
					'' +
						'{{#if editPermissionPossible}}' +
						'{{#unless isFileSharedByMail}}' +
						'' +
							'<input id="canEdit-{{cid}}-{{shareWith}}" type="checkbox" name="edit" class="permissions checkbox" {{#if hasEditPermission}}checked="checked"{{/if}} />' +
							'{{canEditLabel}}' +
						'' +
						'{{/unless}}' +
						'{{/if}}' +
						'{{#unless isMailShare}}' +
						'' +
						'
' +
							'
' +
								'{{#if isResharingAllowed}} {{#if sharePermissionPossible}} {{#unless isMailShare}}' +
								'
' +
									'' +
										'<input id="canShare-{{cid}}-{{shareWith}}" type="checkbox" name="share" class="permissions checkbox" {{#if hasSharePermission}}checked="checked"{{/if}} data-permissions="{{sharePermission}}" />' +
										'{{canShareLabel}}' +
									'' +
								'
' +
								'{{/unless}} {{/if}} {{/if}}' +
								'{{#if isFolder}}' +
									'{{#if createPermissionPossible}}' +
									'
' +
										'' +
											'<input id="canCreate-{{cid}}-{{shareWith}}" type="checkbox" name="create" class="permissions checkbox" {{#if hasCreatePermission}}checked="checked"{{/if}} data-permissions="{{createPermission}}"/>' +
											'{{createPermissionLabel}}' +
										'' +
									'
' +
									'{{/if}}' +
									'{{#if updatePermissionPossible}}' +
									'
' +
										'' +
											'<input id="canUpdate-{{cid}}-{{shareWith}}" type="checkbox" name="update" class="permissions checkbox" {{#if hasUpdatePermission}}checked="checked"{{/if}} data-permissions="{{updatePermission}}"/>' +
											'{{updatePermissionLabel}}' +
										'' +
									'
' +
									'{{/if}}' +
									'{{#if deletePermissionPossible}}' +
									'
' +
										'' +
											'<input id="canDelete-{{cid}}-{{shareWith}}" type="checkbox" name="delete" class="permissions checkbox" {{#if hasDeletePermission}}checked="checked"{{/if}} data-permissions="{{deletePermission}}"/>' +
											'{{deletePermissionLabel}}' +
										'' +
									'
' +
									'{{/if}}' +
								'{{/if}}' +
								'
' +
									'{{unshareLabel}}' +
								'
' +
							'
' +
						'
' +
						'{{/unless}}' +
						'{{unshareLabel}}' +
					'' +
				'
' +
			'{{/each}}' +
			'{{#each linkReshares}}' +
				'
' +
					'{{#if avatarEnabled}}' +
					'

' +
					'{{/if}}' +
					'' + t('core', '{{shareInitiatorDisplayName}} shared via link') + '' +

					'' +
						'{{unshareLabel}}' +
					'' +
				'
' +
			'{{/each}}' +
			'
'
		;

	/**
	 * @class OCA.Share.ShareDialogShareeListView
	 * @member {OC.Share.ShareItemModel} model
	 * @member {jQuery} $el
	 * @memberof OCA.Sharing
	 * @classdesc
	 *
	 * Represents the sharee list part in the GUI of the share dialogue
	 *
	 */
	var ShareDialogShareeListView = OC.Backbone.View.extend({
		/** @type {string} **/
		id: 'shareDialogLinkShare',

		/** @type {OC.Share.ShareConfigModel} **/
		configModel: undefined,

		/** @type {Function} **/
		_template: undefined,

		_menuOpen: false,

		events: {
			'click .unshare': 'onUnshare',
			'click .icon-more': 'onToggleMenu',
			'click .permissions': 'onPermissionChange',
		},

		initialize: function(options) {
			if(!_.isUndefined(options.configModel)) {
				this.configModel = options.configModel;
			} else {
				throw 'missing OC.Share.ShareConfigModel';
			}

			var view = this;
			this.model.on('change:shares', function() {
				view.render();
			});
		},

		/**
		 *
		 * @param {OC.Share.Types.ShareInfo} shareInfo
		 * @returns {object}
		 */
		getShareeObject: function(shareIndex) {
			var shareWith = this.model.getShareWith(shareIndex);
			var shareWithDisplayName = this.model.getShareWithDisplayName(shareIndex);
			var shareWithTitle = '';
			var shareType = this.model.getShareType(shareIndex);

			var hasPermissionOverride = {};
			if (shareType === OC.Share.SHARE_TYPE_GROUP) {
				shareWithDisplayName = shareWithDisplayName + " (" + t('core', 'group') + ')';
			} else if (shareType === OC.Share.SHARE_TYPE_REMOTE) {
				shareWithDisplayName = shareWithDisplayName + " (" + t('core', 'remote') + ')';
			} else if (shareType === OC.Share.SHARE_TYPE_EMAIL) {
				shareWithDisplayName = shareWithDisplayName + " (" + t('core', 'email') + ')';
			}

			if (shareType === OC.Share.SHARE_TYPE_GROUP) {
				shareWithTitle = shareWith + " (" + t('core', 'group') + ')';
			} else if (shareType === OC.Share.SHARE_TYPE_REMOTE) {
				shareWithTitle = shareWith + " (" + t('core', 'remote') + ')';
			} else if (shareType === OC.Share.SHARE_TYPE_EMAIL) {
				shareWithTitle = shareWith + " (" + t('core', 'email') + ')';
			}

			return _.extend(hasPermissionOverride, {
				cid: this.cid,
				hasSharePermission: this.model.hasSharePermission(shareIndex),
				hasEditPermission: this.model.hasEditPermission(shareIndex),
				hasCreatePermission: this.model.hasCreatePermission(shareIndex),
				hasUpdatePermission: this.model.hasUpdatePermission(shareIndex),
				hasDeletePermission: this.model.hasDeletePermission(shareIndex),
				shareWith: shareWith,
				shareWithDisplayName: shareWithDisplayName,
				shareWithTitle: shareWithTitle,
				shareType: shareType,
				shareId: this.model.get('shares')[shareIndex].id,
				modSeed: shareType !== OC.Share.SHARE_TYPE_USER,
				isRemoteShare: shareType === OC.Share.SHARE_TYPE_REMOTE,
				isMailShare: shareType === OC.Share.SHARE_TYPE_EMAIL,
				isFileSharedByMail: shareType === OC.Share.SHARE_TYPE_EMAIL && !this.model.isFolder()
			});
		},

		getShareeList: function() {
			var universal = {
				avatarEnabled: this.configModel.areAvatarsEnabled(),
				unshareLabel: t('core', 'Unshare'),
				canShareLabel: t('core', 'can reshare'),
				canEditLabel: t('core', 'can edit'),
				createPermissionLabel: t('core', 'can create'),
				updatePermissionLabel: t('core', 'can change'),
				deletePermissionLabel: t('core', 'can delete'),
				crudsLabel: t('core', 'access control'),
				triangleSImage: OC.imagePath('core', 'actions/triangle-s'),
				isResharingAllowed: this.configModel.get('isResharingAllowed'),
				sharePermissionPossible: this.model.sharePermissionPossible(),
				editPermissionPossible: this.model.editPermissionPossible(),
				createPermissionPossible: this.model.createPermissionPossible(),
				updatePermissionPossible: this.model.updatePermissionPossible(),
				deletePermissionPossible: this.model.deletePermissionPossible(),
				sharePermission: OC.PERMISSION_SHARE,
				createPermission: OC.PERMISSION_CREATE,
				updatePermission: OC.PERMISSION_UPDATE,
				deletePermission: OC.PERMISSION_DELETE,
				isFolder: this.model.isFolder()
			};

			if(!this.model.hasUserShares()) {
				return [];
			}

			var shares = this.model.get('shares');
			var list = [];
			for(var index = 0; index < shares.length; index++) {
				var share = this.getShareeObject(index);

				if (share.shareType === OC.Share.SHARE_TYPE_LINK) {
					continue;
				}
				// first empty {} is necessary, otherwise we get in trouble
				// with references
				list.push(_.extend({}, universal, share));
			}

			return list;
		},

		getLinkReshares: function() {
			var universal = {
				unshareLabel: t('core', 'Unshare'),
				avatarEnabled: this.configModel.areAvatarsEnabled(),
			};

			if(!this.model.hasUserShares()) {
				return [];
			}

			var shares = this.model.get('shares');
			var list = [];
			for(var index = 0; index < shares.length; index++) {
				var share = this.getShareeObject(index);

				if (share.shareType !== OC.Share.SHARE_TYPE_LINK) {
					continue;
				}
				// first empty {} is necessary, otherwise we get in trouble
				// with references
				list.push(_.extend({}, universal, share, {
					shareInitiator: shares[index].uid_owner,
					shareInitiatorDisplayName: shares[index].displayname_owner
				}));
			}

			return list;
		},

		render: function() {
			this.$el.html(this.template({
				cid: this.cid,
				sharees: this.getShareeList(),
				linkReshares: this.getLinkReshares()
			}));

			if(this.configModel.areAvatarsEnabled()) {
				this.$('.avatar').each(function() {
					var $this = $(this);
					if ($this.hasClass('imageplaceholderseed')) {
						$this.css({width: 32, height: 32});
						$this.imageplaceholder($this.data('seed'));
					} else {
						$this.avatar($this.data('username'), 32);
					}
				});
			}

			this.$('.has-tooltip').tooltip({
				placement: 'bottom'
			});

			var _this = this;
			this.$('.popovermenu').on('afterHide', function() {
				_this._menuOpen = false;
			});
			if (this._menuOpen) {
				// Open menu again if it was opened before
				OC.showMenu(null, this.$('.popovermenu'));
			}

			this.delegateEvents();

			return this;
		},

		/**
		 * @returns {Function} from Handlebars
		 * @private
		 */
		template: function (data) {
			if (!this._template) {
				this._template = Handlebars.compile(TEMPLATE);
			}
			return this._template(data);
		},

		onUnshare: function(event) {
			event.preventDefault();
			event.stopPropagation();
			var self = this;
			var $element = $(event.target);
			if (!$element.is('a')) {
				$element = $element.closest('a');
			}

			var $loading = $element.find('.icon-loading-small').eq(0);
			if(!$loading.hasClass('hidden')) {
				// in process
				return false;
			}
			$loading.removeClass('hidden');

			var $li = $element.closest('li[data-share-id]');

			var shareId = $li.data('share-id');

			self.model.removeShare(shareId)
				.done(function() {
					$li.remove();
				})
				.fail(function() {
					$loading.addClass('hidden');
					OC.Notification.showTemporary(t('core', 'Could not unshare'));
				});
			return false;
		},

		onToggleMenu: function(event) {
			event.preventDefault();
			event.stopPropagation();
			var $element = $(event.target);
			var $li = $element.closest('li[data-share-id]');
			var $menu = $li.find('.popovermenu');

			OC.showMenu(null, $menu);
			this._menuOpen = true;
		},

		onPermissionChange: function(event) {
			event.preventDefault();
			event.stopPropagation();
			var $element = $(event.target);
			var $li = $element.closest('li[data-share-id]');
			var shareId = $li.data('share-id');

			var permissions = OC.PERMISSION_READ;

			if (this.model.isFolder()) {
				// adjust checkbox states
				var $checkboxes = $('.permissions', $li).not('input[name="edit"]').not('input[name="share"]');
				var checked;
				if ($element.attr('name') === 'edit') {
					checked = $element.is(':checked');
					// Check/uncheck Create, Update, and Delete checkboxes if Edit is checked/unck
					$($checkboxes).prop('checked', checked);
				} else {
					var numberChecked = $checkboxes.filter(':checked').length;
					checked = numberChecked > 0;
					$('input[name="edit"]', $li).prop('checked', checked);
				}
			} else {
				if ($element.attr('name') === 'edit' && $element.is(':checked')) {
					permissions |= OC.PERMISSION_UPDATE;
				}
			}

			$('.permissions', $li).not('input[name="edit"]').filter(':checked').each(function(index, checkbox) {
				permissions |= $(checkbox).data('permissions');
			});

			this.model.updateShare(shareId, {permissions: permissions});
		},
	});

	OC.Share.ShareDialogShareeListView = ShareDialogShareeListView;

})();
<commit_msg>remove Unshare icon in list<commit_after>/* global OC, Handlebars */

/*
 * Copyright (c) 2015
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */

/* globals Handlebars */

(function() {
	if (!OC.Share) {
		OC.Share = {};
	}

	var TEMPLATE =
			'
' +
			'{{#each sharees}}' +
				'
' +
					'{{#if avatarEnabled}}' +
					'

' +
					'{{/if}}' +
					'{{shareWithDisplayName}}' +
					'' +
						'{{#if editPermissionPossible}}' +
						'{{#unless isFileSharedByMail}}' +
						'' +
							'<input id="canEdit-{{cid}}-{{shareWith}}" type="checkbox" name="edit" class="permissions checkbox" {{#if hasEditPermission}}checked="checked"{{/if}} />' +
							'{{canEditLabel}}' +
						'' +
						'{{/unless}}' +
						'{{/if}}' +
						'{{#unless isMailShare}}' +
						'' +
						'
' +
							'
' +
								'{{#if isResharingAllowed}} {{#if sharePermissionPossible}} {{#unless isMailShare}}' +
								'
' +
									'' +
										'<input id="canShare-{{cid}}-{{shareWith}}" type="checkbox" name="share" class="permissions checkbox" {{#if hasSharePermission}}checked="checked"{{/if}} data-permissions="{{sharePermission}}" />' +
										'{{canShareLabel}}' +
									'' +
								'
' +
								'{{/unless}} {{/if}} {{/if}}' +
								'{{#if isFolder}}' +
									'{{#if createPermissionPossible}}' +
									'
' +
										'' +
											'<input id="canCreate-{{cid}}-{{shareWith}}" type="checkbox" name="create" class="permissions checkbox" {{#if hasCreatePermission}}checked="checked"{{/if}} data-permissions="{{createPermission}}"/>' +
											'{{createPermissionLabel}}' +
										'' +
									'
' +
									'{{/if}}' +
									'{{#if updatePermissionPossible}}' +
									'
' +
										'' +
											'<input id="canUpdate-{{cid}}-{{shareWith}}" type="checkbox" name="update" class="permissions checkbox" {{#if hasUpdatePermission}}checked="checked"{{/if}} data-permissions="{{updatePermission}}"/>' +
											'{{updatePermissionLabel}}' +
										'' +
									'
' +
									'{{/if}}' +
									'{{#if deletePermissionPossible}}' +
									'
' +
										'' +
											'<input id="canDelete-{{cid}}-{{shareWith}}" type="checkbox" name="delete" class="permissions checkbox" {{#if hasDeletePermission}}checked="checked"{{/if}} data-permissions="{{deletePermission}}"/>' +
											'{{deletePermissionLabel}}' +
										'' +
									'
' +
									'{{/if}}' +
								'{{/if}}' +
								'
' +
									'{{unshareLabel}}' +
								'
' +
							'
' +
						'
' +
						'{{/unless}}' +
					'' +
				'
' +
			'{{/each}}' +
			'{{#each linkReshares}}' +
				'
' +
					'{{#if avatarEnabled}}' +
					'

' +
					'{{/if}}' +
					'' + t('core', '{{shareInitiatorDisplayName}} shared via link') + '' +

					'' +
						'{{unshareLabel}}' +
					'' +
				'
' +
			'{{/each}}' +
			'
'
		;

	/**
	 * @class OCA.Share.ShareDialogShareeListView
	 * @member {OC.Share.ShareItemModel} model
	 * @member {jQuery} $el
	 * @memberof OCA.Sharing
	 * @classdesc
	 *
	 * Represents the sharee list part in the GUI of the share dialogue
	 *
	 */
	var ShareDialogShareeListView = OC.Backbone.View.extend({
		/** @type {string} **/
		id: 'shareDialogLinkShare',

		/** @type {OC.Share.ShareConfigModel} **/
		configModel: undefined,

		/** @type {Function} **/
		_template: undefined,

		_menuOpen: false,

		events: {
			'click .unshare': 'onUnshare',
			'click .icon-more': 'onToggleMenu',
			'click .permissions': 'onPermissionChange',
		},

		initialize: function(options) {
			if(!_.isUndefined(options.configModel)) {
				this.configModel = options.configModel;
			} else {
				throw 'missing OC.Share.ShareConfigModel';
			}

			var view = this;
			this.model.on('change:shares', function() {
				view.render();
			});
		},

		/**
		 *
		 * @param {OC.Share.Types.ShareInfo} shareInfo
		 * @returns {object}
		 */
		getShareeObject: function(shareIndex) {
			var shareWith = this.model.getShareWith(shareIndex);
			var shareWithDisplayName = this.model.getShareWithDisplayName(shareIndex);
			var shareWithTitle = '';
			var shareType = this.model.getShareType(shareIndex);

			var hasPermissionOverride = {};
			if (shareType === OC.Share.SHARE_TYPE_GROUP) {
				shareWithDisplayName = shareWithDisplayName + " (" + t('core', 'group') + ')';
			} else if (shareType === OC.Share.SHARE_TYPE_REMOTE) {
				shareWithDisplayName = shareWithDisplayName + " (" + t('core', 'remote') + ')';
			} else if (shareType === OC.Share.SHARE_TYPE_EMAIL) {
				shareWithDisplayName = shareWithDisplayName + " (" + t('core', 'email') + ')';
			}

			if (shareType === OC.Share.SHARE_TYPE_GROUP) {
				shareWithTitle = shareWith + " (" + t('core', 'group') + ')';
			} else if (shareType === OC.Share.SHARE_TYPE_REMOTE) {
				shareWithTitle = shareWith + " (" + t('core', 'remote') + ')';
			} else if (shareType === OC.Share.SHARE_TYPE_EMAIL) {
				shareWithTitle = shareWith + " (" + t('core', 'email') + ')';
			}

			return _.extend(hasPermissionOverride, {
				cid: this.cid,
				hasSharePermission: this.model.hasSharePermission(shareIndex),
				hasEditPermission: this.model.hasEditPermission(shareIndex),
				hasCreatePermission: this.model.hasCreatePermission(shareIndex),
				hasUpdatePermission: this.model.hasUpdatePermission(shareIndex),
				hasDeletePermission: this.model.hasDeletePermission(shareIndex),
				shareWith: shareWith,
				shareWithDisplayName: shareWithDisplayName,
				shareWithTitle: shareWithTitle,
				shareType: shareType,
				shareId: this.model.get('shares')[shareIndex].id,
				modSeed: shareType !== OC.Share.SHARE_TYPE_USER,
				isRemoteShare: shareType === OC.Share.SHARE_TYPE_REMOTE,
				isMailShare: shareType === OC.Share.SHARE_TYPE_EMAIL,
				isFileSharedByMail: shareType === OC.Share.SHARE_TYPE_EMAIL && !this.model.isFolder()
			});
		},

		getShareeList: function() {
			var universal = {
				avatarEnabled: this.configModel.areAvatarsEnabled(),
				unshareLabel: t('core', 'Unshare'),
				canShareLabel: t('core', 'can reshare'),
				canEditLabel: t('core', 'can edit'),
				createPermissionLabel: t('core', 'can create'),
				updatePermissionLabel: t('core', 'can change'),
				deletePermissionLabel: t('core', 'can delete'),
				crudsLabel: t('core', 'access control'),
				triangleSImage: OC.imagePath('core', 'actions/triangle-s'),
				isResharingAllowed: this.configModel.get('isResharingAllowed'),
				sharePermissionPossible: this.model.sharePermissionPossible(),
				editPermissionPossible: this.model.editPermissionPossible(),
				createPermissionPossible: this.model.createPermissionPossible(),
				updatePermissionPossible: this.model.updatePermissionPossible(),
				deletePermissionPossible: this.model.deletePermissionPossible(),
				sharePermission: OC.PERMISSION_SHARE,
				createPermission: OC.PERMISSION_CREATE,
				updatePermission: OC.PERMISSION_UPDATE,
				deletePermission: OC.PERMISSION_DELETE,
				isFolder: this.model.isFolder()
			};

			if(!this.model.hasUserShares()) {
				return [];
			}

			var shares = this.model.get('shares');
			var list = [];
			for(var index = 0; index < shares.length; index++) {
				var share = this.getShareeObject(index);

				if (share.shareType === OC.Share.SHARE_TYPE_LINK) {
					continue;
				}
				// first empty {} is necessary, otherwise we get in trouble
				// with references
				list.push(_.extend({}, universal, share));
			}

			return list;
		},

		getLinkReshares: function() {
			var universal = {
				unshareLabel: t('core', 'Unshare'),
				avatarEnabled: this.configModel.areAvatarsEnabled(),
			};

			if(!this.model.hasUserShares()) {
				return [];
			}

			var shares = this.model.get('shares');
			var list = [];
			for(var index = 0; index < shares.length; index++) {
				var share = this.getShareeObject(index);

				if (share.shareType !== OC.Share.SHARE_TYPE_LINK) {
					continue;
				}
				// first empty {} is necessary, otherwise we get in trouble
				// with references
				list.push(_.extend({}, universal, share, {
					shareInitiator: shares[index].uid_owner,
					shareInitiatorDisplayName: shares[index].displayname_owner
				}));
			}

			return list;
		},

		render: function() {
			this.$el.html(this.template({
				cid: this.cid,
				sharees: this.getShareeList(),
				linkReshares: this.getLinkReshares()
			}));

			if(this.configModel.areAvatarsEnabled()) {
				this.$('.avatar').each(function() {
					var $this = $(this);
					if ($this.hasClass('imageplaceholderseed')) {
						$this.css({width: 32, height: 32});
						$this.imageplaceholder($this.data('seed'));
					} else {
						$this.avatar($this.data('username'), 32);
					}
				});
			}

			this.$('.has-tooltip').tooltip({
				placement: 'bottom'
			});

			var _this = this;
			this.$('.popovermenu').on('afterHide', function() {
				_this._menuOpen = false;
			});
			if (this._menuOpen) {
				// Open menu again if it was opened before
				OC.showMenu(null, this.$('.popovermenu'));
			}

			this.delegateEvents();

			return this;
		},

		/**
		 * @returns {Function} from Handlebars
		 * @private
		 */
		template: function (data) {
			if (!this._template) {
				this._template = Handlebars.compile(TEMPLATE);
			}
			return this._template(data);
		},

		onUnshare: function(event) {
			event.preventDefault();
			event.stopPropagation();
			var self = this;
			var $element = $(event.target);
			if (!$element.is('a')) {
				$element = $element.closest('a');
			}

			var $loading = $element.find('.icon-loading-small').eq(0);
			if(!$loading.hasClass('hidden')) {
				// in process
				return false;
			}
			$loading.removeClass('hidden');

			var $li = $element.closest('li[data-share-id]');

			var shareId = $li.data('share-id');

			self.model.removeShare(shareId)
				.done(function() {
					$li.remove();
				})
				.fail(function() {
					$loading.addClass('hidden');
					OC.Notification.showTemporary(t('core', 'Could not unshare'));
				});
			return false;
		},

		onToggleMenu: function(event) {
			event.preventDefault();
			event.stopPropagation();
			var $element = $(event.target);
			var $li = $element.closest('li[data-share-id]');
			var $menu = $li.find('.popovermenu');

			OC.showMenu(null, $menu);
			this._menuOpen = true;
		},

		onPermissionChange: function(event) {
			event.preventDefault();
			event.stopPropagation();
			var $element = $(event.target);
			var $li = $element.closest('li[data-share-id]');
			var shareId = $li.data('share-id');

			var permissions = OC.PERMISSION_READ;

			if (this.model.isFolder()) {
				// adjust checkbox states
				var $checkboxes = $('.permissions', $li).not('input[name="edit"]').not('input[name="share"]');
				var checked;
				if ($element.attr('name') === 'edit') {
					checked = $element.is(':checked');
					// Check/uncheck Create, Update, and Delete checkboxes if Edit is checked/unck
					$($checkboxes).prop('checked', checked);
				} else {
					var numberChecked = $checkboxes.filter(':checked').length;
					checked = numberChecked > 0;
					$('input[name="edit"]', $li).prop('checked', checked);
				}
			} else {
				if ($element.attr('name') === 'edit' && $element.is(':checked')) {
					permissions |= OC.PERMISSION_UPDATE;
				}
			}

			$('.permissions', $li).not('input[name="edit"]').filter(':checked').each(function(index, checkbox) {
				permissions |= $(checkbox).data('permissions');
			});

			this.model.updateShare(shareId, {permissions: permissions});
		},
	});

	OC.Share.ShareDialogShareeListView = ShareDialogShareeListView;

})();
<|endoftext|>


<commit_before>// Copyright 2012 Navigation North Learning Solutions LLC
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations under
// the License.

var BROWSER = (function () {

    // private fields

    var resourceServiceUrl = 'http://localhost/extract/standards-alignment-related/resource-by-discriminator'; // default value

    var $screen;

    var state = {
	category: undefined,
	standard: undefined,
	grade: $.cookie('grade-filter') || 'K',
	nodes: []
    };

    // private event handlers

    var categoryClick = function (event) {
	var category = $(event.target).data('category');
	updateState(category);
	updateHashLocation();
	return false;
    };

    var standardClick = function (event) {
	var standard = $(event.target).data('standard');
	var category = $(event.target).data('category')
	    || $(event.target).closest('.category').data('category');
	updateState(category, standard);
	updateHashLocation();
	return false;
    };

    var gradeChange = function (event) {
	var $target = $(event.target);
	var standard = $target.data('standard');
	var category = $target.data('category')
	    || $(event.target).closest('.category').data('category');
	var grade = $target.val();

	updateState(category, standard, grade);
	updateHashLocation();
	return false;
    };

    var childClick = function (event) {
	var $target    = $(event.target);
	var $ancestors = $target.parents('.node');
	var $container = $target.closest('.node');
	var parentId   = $container.data('id');
	var nodes      = [];

	// handle toggle and button
	var closed = $target.text() === '[ + ]' ? true : false;

	$container.children('.children').toggle();

	if(closed) {
	    $target.text('[ - ]');

	    // walk up the DOM and find IDs of all nodes in hierarchy
	    $ancestors.each( function (i, e) {
		nodes.unshift($(e).data('id'));
	    });

	    updateNodes(nodes);
	    updateHashLocation();
	}
	else {
	    $target.text('[ + ]');
	}
	return false;
    };

    // private methods

    var updateState = function (category, standard, grade) {
	state.category = category;
	state.standard = standard;
        if (grade) {
	    state.grade = grade;
	    $.cookie('grade-filter', grade);
	}
    };

    var updateNodes = function (nodes) {
	state.nodes = nodes;
    };

    var updateHashLocation = function () {
	var hashParts = [];

	if (state.category) {
	    hashParts.push(state.category);
	    if (state.standard) {
		hashParts.push(state.standard);
		if (state.grade) {
		    hashParts.push(state.grade);
		    if (state.nodes) {
			hashParts = hashParts.concat(state.nodes);
		    }
		}
	    }
	}

	location.hash = hashParts.join('/');
    };

    var createCategoryLink = function (category) {
	var link = $('<a/>').addClass('category-link')
	    .data('category', category)
	    .text(category)
	    .attr('href', '#');

	return link;
    };

    var createStandardLink = function (category, standard) {
	var link = $('<a/>').addClass('standard-link')
	    .data('category', category)
	    .data('standard', standard)
	    .text(standard)
	    .attr('href', '#');

	return link;
    };

    var createGradeLink = function (category, standard) {
	var gradeFilterClone = $('#grade-filter-master').clone();
	var grade = $.cookie('grade-filter') || 'K';

	var link = gradeFilterClone.removeAttr('id');

	link.find('.grade-link').data('category', category);
	link.find('.grade-link').data('standard', standard);
	link.find('.grade-link').val(grade);
	link.show();

	return link;
    };

    // returns function to descend into the node path provided
    // moves to next node after each is finished loading
    var recursiveDescent = function recursiveDescent (nodes) {
	return function () {
	    var node      = nodes.shift();
	    var $target   = $(document).find("[data-id='" + node + "']");
	    if($target.length) {
		$target.children('.expand-node').text('[ - ]');
		loadNodes($target, { parent: node }, recursiveDescent(nodes));
	    }
	};
    };

    var loadResources = function ($div, callback) {
	$div.find('.resources').each( function (i, e) {
	    var $resourceDiv  = $(e);
	    var $resourceLink = $resourceDiv.find('.resource-count');

	    var id = $resourceLink.data('id');

	    $resourceLink.text( 'loading...' );

	    $.ajax(resourceServiceUrl, {
		data: {discriminator: id},
                dataType: 'json',
		success: function (resources) {
		    var count = resources.documents.length;

		    // remove element if no resources
		    if (count === 0) {
			$resourceLink.text( 'no resources found' );
			return;
		    }

		    // get resource/s depending on how many
		    var pluralText = count === 1 ? 'resource' : 'resources';

		    var div = $('<div/>');
		    $('<h2 />').text('Resources').appendTo(div);

		    $.each( resources.documents, function(i, doc) {
			var link = doc.result_data.resource;
			var a = $('<a/>').attr('href', link).text(link)
			    .attr('target', '_blank');
			var p = $('<p/>');
			p.append(a);
			div.append(p);
		    });

		    var $newResourceLink = $('<a/>')
			.attr('href', '#').text( count + ' ' + pluralText );

		    $newResourceLink.click( function (event) {
			$.modal(div);
			return false;
		    });

		    $resourceLink.replaceWith($newResourceLink);
		}
	    });
	});
    };

    var loadNodes = function ($query, data, callback) {
	var nodesUrl = '/nodes/';
	var $div = $('<div/>').addClass('children');
	$div.load(nodesUrl, data, function () {
	    loadResources($div);
	    $query.append($div);
	    if (callback) callback();
	});
    };

    // singleton
    var browser = {
	setResourceServiceUrl: function (url) {
	    resourceServiceUrl = url;
	},
	start: function ($screenIn) { // $screen is where stuff will be loaded
	    $screen = $screenIn;

	    // set up category, standard, and grade events
	    $(document).on( 'click',  '.category-link', categoryClick );
	    $(document).on( 'click',  '.standard-link', standardClick );
	    $(document).on( 'change', '.grade-link',    gradeChange );
	    $(document).on( 'click',  '.expand-node',   childClick );

	    // load the list of all categories and standards
	    $screen.load('/standards/', function () {
		$(window).hashchange( function () {
		    var hashParts = unescape(location.hash).split('/');

		    var category = hashParts.shift();
		    var standard = hashParts.shift();
		    var grade    = hashParts.shift();
		    var nodes    = hashParts; // only nodes are left over, if any

		    var categoryUrl = '/standards/';

		    var childrenToLoad = [];
		    var first;

		    // remove leading # and set Url
		    if (category) {
			category     = category.substring(1);
			categoryUrl += escape(category);
		    }

		    updateState(category, standard, grade);
		    updateNodes(nodes);

		    // load the display
		    if (!state.category) {
			$screen.load(categoryUrl, function () {
			    CRUMBS.clear($('#crumbs'));
			});
			return;
		    }

		    if (!state.standard) {
			$screen.load(categoryUrl, function () {
			    CRUMBS.clear($('#crumbs'));
			    CRUMBS.push($('#crumbs'), createCategoryLink(state.category));
			});
			return;
		    }

		    var screenLoaded = $screen.find('.node').length > 0 ? true : false;
		    var callback;
		    var $loadLocation;
		    var discriminator;

		    // clear, then add the crumbs to the trail
		    CRUMBS.clear($('#crumbs'));
		    CRUMBS.push($('#crumbs'), createCategoryLink(state.category));
		    CRUMBS.push($('#crumbs'), createStandardLink(state.category, state.standard));
		    CRUMBS.push($('#crumbs'), createGradeLink(state.category, state.standard, state.grade));

		    // either load screen, no nodes open
		    // or screen loaded, open nodes
		    // or load screen, then open nodes
		    if (!screenLoaded || !state.nodes || state.nodes.length === 0) {
			$loadLocation = $screen;
			$screen.html('');
			discriminator = { category: category, standard: standard };
	            }

		    // find out what part of the node tree needs to be loaded
		    nodes.forEach( function (node) {
			var $target = $("[data-id='" + node + "']").find('.children');
			if (!$target.length) childrenToLoad.push(node);
		    });

		    if (state.nodes && state.nodes.length > 0) {
			callback = recursiveDescent(childrenToLoad);
		    }

		    if (screenLoaded && state.nodes && state.nodes.length > 0) {
			first = childrenToLoad.shift();
			$loadLocation = $("[data-id='" + first + "']");
			discriminator = { parent: first };
			callback = recursiveDescent(childrenToLoad);
		    }

		    loadNodes($loadLocation, discriminator, callback);
		});

		// fire the hashchange event in case bookmarked hash supplied
		$(window).hashchange();
	    });
	}
    };

    return browser;

})();
<commit_msg>Fix bug where changing the grade would not update the display after nodes had been clicked.  Resets open nodes on grade change.<commit_after>// Copyright 2012 Navigation North Learning Solutions LLC
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations under
// the License.

var BROWSER = (function () {

    // private fields

    var resourceServiceUrl = 'http://localhost/extract/standards-alignment-related/resource-by-discriminator'; // default value

    var $screen;

    var state = {
	category: undefined,
	standard: undefined,
	grade: $.cookie('grade-filter') || 'K',
	nodes: []
    };

    // private event handlers

    var categoryClick = function (event) {
	var category = $(event.target).data('category');
	updateState(category);
	updateHashLocation();
	return false;
    };

    var standardClick = function (event) {
	var standard = $(event.target).data('standard');
	var category = $(event.target).data('category')
	    || $(event.target).closest('.category').data('category');
	updateState(category, standard);
	updateHashLocation();
	return false;
    };

    var gradeChange = function (event) {
	var $target = $(event.target);
	var standard = $target.data('standard');
	var category = $target.data('category')
	    || $(event.target).closest('.category').data('category');
	var grade = $target.val();

	updateState(category, standard, grade);
        updateNodes([]);
	updateHashLocation();
	return false;
    };

    var childClick = function (event) {
	var $target    = $(event.target);
	var $ancestors = $target.parents('.node');
	var $container = $target.closest('.node');
	var parentId   = $container.data('id');
	var nodes      = [];

	// handle toggle and button
	var closed = $target.text() === '[ + ]' ? true : false;

	$container.children('.children').toggle();

	if(closed) {
	    $target.text('[ - ]');

	    // walk up the DOM and find IDs of all nodes in hierarchy
	    $ancestors.each( function (i, e) {
		nodes.unshift($(e).data('id'));
	    });

	    updateNodes(nodes);
	    updateHashLocation();
	}
	else {
	    $target.text('[ + ]');
	}
	return false;
    };

    // private methods

    var updateState = function (category, standard, grade) {
	state.category = category;
	state.standard = standard;
        if (grade) {
	    state.grade = grade;
	    $.cookie('grade-filter', grade);
	}
    };

    var updateNodes = function (nodes) {
	state.nodes = nodes;
    };

    var updateHashLocation = function () {
	var hashParts = [];

	if (state.category) {
	    hashParts.push(state.category);
	    if (state.standard) {
		hashParts.push(state.standard);
		if (state.grade) {
		    hashParts.push(state.grade);
		    if (state.nodes) {
			hashParts = hashParts.concat(state.nodes);
		    }
		}
	    }
	}

	location.hash = hashParts.join('/');
    };

    var createCategoryLink = function (category) {
	var link = $('<a/>').addClass('category-link')
	    .data('category', category)
	    .text(category)
	    .attr('href', '#');

	return link;
    };

    var createStandardLink = function (category, standard) {
	var link = $('<a/>').addClass('standard-link')
	    .data('category', category)
	    .data('standard', standard)
	    .text(standard)
	    .attr('href', '#');

	return link;
    };

    var createGradeLink = function (category, standard) {
	var gradeFilterClone = $('#grade-filter-master').clone();
	var grade = $.cookie('grade-filter') || 'K';

	var link = gradeFilterClone.removeAttr('id');

	link.find('.grade-link').data('category', category);
	link.find('.grade-link').data('standard', standard);
	link.find('.grade-link').val(grade);
	link.show();

	return link;
    };

    // returns function to descend into the node path provided
    // moves to next node after each is finished loading
    var recursiveDescent = function recursiveDescent (nodes) {
	return function () {
	    var node      = nodes.shift();
	    var $target   = $(document).find("[data-id='" + node + "']");
	    if($target.length) {
		$target.children('.expand-node').text('[ - ]');
		loadNodes($target, { parent: node }, recursiveDescent(nodes));
	    }
	};
    };

    var loadResources = function ($div, callback) {
	$div.find('.resources').each( function (i, e) {
	    var $resourceDiv  = $(e);
	    var $resourceLink = $resourceDiv.find('.resource-count');

	    var id = $resourceLink.data('id');

	    $resourceLink.text( 'loading...' );

	    $.ajax(resourceServiceUrl, {
		data: {discriminator: id},
                dataType: 'json',
		success: function (resources) {
		    var count = resources.documents.length;

		    // remove element if no resources
		    if (count === 0) {
			$resourceLink.text( 'no resources found' );
			return;
		    }

		    // get resource/s depending on how many
		    var pluralText = count === 1 ? 'resource' : 'resources';

		    var div = $('<div/>');
		    $('<h2 />').text('Resources').appendTo(div);

		    $.each( resources.documents, function(i, doc) {
			var link = doc.result_data.resource;
			var a = $('<a/>').attr('href', link).text(link)
			    .attr('target', '_blank');
			var p = $('<p/>');
			p.append(a);
			div.append(p);
		    });

		    var $newResourceLink = $('<a/>')
			.attr('href', '#').text( count + ' ' + pluralText );

		    $newResourceLink.click( function (event) {
			$.modal(div);
			return false;
		    });

		    $resourceLink.replaceWith($newResourceLink);
		}
	    });
	});
    };

    var loadNodes = function ($query, data, callback) {
	var nodesUrl = '/nodes/';
	var $div = $('<div/>').addClass('children');
	$div.load(nodesUrl, data, function () {
	    loadResources($div);
	    $query.append($div);
	    if (callback) callback();
	});
    };

    // singleton
    var browser = {
	setResourceServiceUrl: function (url) {
	    resourceServiceUrl = url;
	},
	start: function ($screenIn) { // $screen is where stuff will be loaded
	    $screen = $screenIn;

	    // set up category, standard, and grade events
	    $(document).on( 'click',  '.category-link', categoryClick );
	    $(document).on( 'click',  '.standard-link', standardClick );
	    $(document).on( 'change', '.grade-link',    gradeChange );
	    $(document).on( 'click',  '.expand-node',   childClick );

	    // load the list of all categories and standards
	    $screen.load('/standards/', function () {
		$(window).hashchange( function () {
		    var hashParts = unescape(location.hash).split('/');

		    var category = hashParts.shift();
		    var standard = hashParts.shift();
		    var grade    = hashParts.shift();
		    var nodes    = hashParts; // only nodes are left over, if any

		    var categoryUrl = '/standards/';

		    var childrenToLoad = [];
		    var first;

		    // remove leading # and set Url
		    if (category) {
			category     = category.substring(1);
			categoryUrl += escape(category);
		    }

		    updateState(category, standard, grade);
		    updateNodes(nodes);

		    // load the display
		    if (!state.category) {
			$screen.load(categoryUrl, function () {
			    CRUMBS.clear($('#crumbs'));
			});
			return;
		    }

		    if (!state.standard) {
			$screen.load(categoryUrl, function () {
			    CRUMBS.clear($('#crumbs'));
			    CRUMBS.push($('#crumbs'), createCategoryLink(state.category));
			});
			return;
		    }

		    var screenLoaded = $screen.find('.node').length > 0 ? true : false;
		    var callback;
		    var $loadLocation;
		    var discriminator;

		    // clear, then add the crumbs to the trail
		    CRUMBS.clear($('#crumbs'));
		    CRUMBS.push($('#crumbs'), createCategoryLink(state.category));
		    CRUMBS.push($('#crumbs'), createStandardLink(state.category, state.standard));
		    CRUMBS.push($('#crumbs'), createGradeLink(state.category, state.standard, state.grade));

		    // either load screen, no nodes open
		    // or screen loaded, open nodes
		    // or load screen, then open nodes
		    if (!screenLoaded || !state.nodes || state.nodes.length === 0) {
			$loadLocation = $screen;
			$screen.html('');
			discriminator = { category: category, standard: standard };
	            }

		    // find out what part of the node tree needs to be loaded
		    nodes.forEach( function (node) {
			var $target = $("[data-id='" + node + "']").find('.children');
			if (!$target.length) childrenToLoad.push(node);
		    });

		    if (state.nodes && state.nodes.length > 0) {
			callback = recursiveDescent(childrenToLoad);
		    }

		    if (screenLoaded && state.nodes && state.nodes.length > 0) {
			first = childrenToLoad.shift();
			$loadLocation = $("[data-id='" + first + "']");
			discriminator = { parent: first };
			callback = recursiveDescent(childrenToLoad);
		    }

		    loadNodes($loadLocation, discriminator, callback);
		});

		// fire the hashchange event in case bookmarked hash supplied
		$(window).hashchange();
	    });
	}
    };

    return browser;

})();
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */

(function() {
	if (!OC.Share) {
		OC.Share = {};
	}

	var TEMPLATE =
			'
' +
			'{{#each sharees}}' +
				'
' +
					'{{unshareLabel}}' +
					'{{#if avatarEnabled}}' +
					'

' +
					'{{/if}}' +
					'{{shareWithDisplayName}}' +
					'{{#if mailNotificationEnabled}}  {{#unless isRemoteShare}}' +
					'' +
						'<input id="mail-{{cid}}-{{shareWith}}" type="checkbox" name="mailNotification" class="mailNotification checkbox" {{#if wasMailSent}}checked="checked"{{/if}} />' +
						'{{notifyByMailLabel}}' +
					'' +
					'{{/unless}} {{/if}}' +
					/*
					'{{#if isResharingAllowed}} {{#if sharePermissionPossible}}' +
					'' +
						'<input id="canShare-{{cid}}-{{shareWith}}" type="checkbox" name="share" class="permissions checkbox" {{#if hasSharePermission}}checked="checked"{{/if}} data-permissions="{{sharePermission}}" />' +
						'{{canShareLabel}}' +
					'' +
					'{{/if}} {{/if}}' +
					*/
					'{{#if editPermissionPossible}}' +
					'{{/if}}' +
					'
' +
						'' +
							'<input type="checkbox" name="read" class="permissions checkbox" checked="checked" disabled />' +
							'read' +
						'' +
						'{{#if createPermissionPossible}}' +
						'' +
							'<input id="canCreate-{{cid}}-{{shareWith}}" type="checkbox" name="create" class="permissions checkbox" {{#if hasCreatePermission}}checked="checked"{{/if}} data-permissions="{{createPermission}}"/>' +
							'write + delete' +
						'' +
						'{{/if}}' +
						'{{#if mailerAppEnabled}}' +
						'' +
							'<button class="cbox-mail-notification">Send notification</button>' +
						'' +
						'{{/if}}' +
						/*
						'{{#if createPermissionPossible}}' +
						'' +
							'<input id="canCreate-{{cid}}-{{shareWith}}" type="checkbox" name="create" class="permissions checkbox" {{#if hasCreatePermission}}checked="checked"{{/if}} data-permissions="{{createPermission}}"/>' +
							'{{createPermissionLabel}}' +
						'' +
						'{{/if}}' +
						'{{#if updatePermissionPossible}}' +
						'' +
							'<input id="canUpdate-{{cid}}-{{shareWith}}" type="checkbox" name="update" class="permissions checkbox" {{#if hasUpdatePermission}}checked="checked"{{/if}} data-permissions="{{updatePermission}}"/>' +
							'{{updatePermissionLabel}}' +
						'' +
						'{{/if}}' +
						'{{#if deletePermissionPossible}}' +
						'' +
							'<input id="canDelete-{{cid}}-{{shareWith}}" type="checkbox" name="delete" class="permissions checkbox" {{#if hasDeletePermission}}checked="checked"{{/if}} data-permissions="{{deletePermission}}"/>' +
							'{{deletePermissionLabel}}' +
						'' +
						'{{/if}}' +
						*/
					'
' +
				'
' +
			'{{/each}}' +
			'
'
		;

	/**
	 * @class OCA.Share.ShareDialogShareeListView
	 * @member {OC.Share.ShareItemModel} model
	 * @member {jQuery} $el
	 * @memberof OCA.Sharing
	 * @classdesc
	 *
	 * Represents the sharee list part in the GUI of the share dialogue
	 *
	 */
	var ShareDialogShareeListView = OC.Backbone.View.extend({
		/** @type {string} **/
		id: 'shareDialogLinkShare',

		/** @type {OC.Share.ShareConfigModel} **/
		configModel: undefined,

		/** @type {Function} **/
		_template: undefined,

		events: {
			'click .unshare': 'onUnshare',
			'click .permissions': 'onPermissionChange',
			'click .showCruds': 'onCrudsToggle',
			'click .mailNotification': 'onSendMailNotification',
			'click .cbox-mail-notification': 'onSendCboxMailNotification'
		},

		initialize: function(options) {
			if(!_.isUndefined(options.configModel)) {
				this.configModel = options.configModel;
			} else {
				throw 'missing OC.Share.ShareConfigModel';
			}

			var view = this;
			this.model.on('change:shares', function() {
				view.render();
			});
		},

		/**
		 *
		 * @param {OC.Share.Types.ShareInfo} shareInfo
		 * @returns {object}
		 */
		getShareeObject: function(shareIndex) {
			var shareWith = this.model.getShareWith(shareIndex);
			var shareWithDisplayName = this.model.getShareWithDisplayName(shareIndex);
			var shareType = this.model.getShareType(shareIndex);

			var hasPermissionOverride = {};
			if (shareType === OC.Share.SHARE_TYPE_GROUP) {
				shareWithDisplayName = shareWithDisplayName + " (" + t('core', 'group') + ')';
			} else if (shareType === OC.Share.SHARE_TYPE_REMOTE) {
				shareWithDisplayName = shareWithDisplayName + " (" + t('core', 'remote') + ')';
			}

			return _.extend(hasPermissionOverride, {
				cid: this.cid,
				hasSharePermission: this.model.hasSharePermission(shareIndex),
				hasEditPermission: this.model.hasEditPermission(shareIndex),
				hasCreatePermission: this.model.hasCreatePermission(shareIndex),
				hasUpdatePermission: this.model.hasUpdatePermission(shareIndex),
				hasDeletePermission: this.model.hasDeletePermission(shareIndex),
				wasMailSent: this.model.notificationMailWasSent(shareIndex),
				shareWith: shareWith,
				shareWithDisplayName: shareWithDisplayName,
				shareType: shareType,
				shareId: this.model.get('shares')[shareIndex].id,
				modSeed: shareType !== OC.Share.SHARE_TYPE_USER,
				isRemoteShare: shareType === OC.Share.SHARE_TYPE_REMOTE
			});
		},

		getShareeList: function() {
			var universal = {
				avatarEnabled: this.configModel.areAvatarsEnabled(),
				mailNotificationEnabled: this.configModel.isMailNotificationEnabled(),
				notifyByMailLabel: t('core', 'notify by email'),
				unshareLabel: t('core', 'Unshare'),
				canShareLabel: t('core', 'can share'),
				canEditLabel: t('core', 'can edit'),
				createPermissionLabel: t('core', 'create'),
				updatePermissionLabel: t('core', 'change'),
				deletePermissionLabel: t('core', 'delete'),
				crudsLabel: t('core', 'access control'),
				triangleSImage: OC.imagePath('core', 'actions/triangle-s'),
				isResharingAllowed: this.configModel.get('isResharingAllowed'),
				sharePermissionPossible: this.model.sharePermissionPossible(),
				editPermissionPossible: this.model.editPermissionPossible(),
				createPermissionPossible: this.model.createPermissionPossible(),
				updatePermissionPossible: this.model.updatePermissionPossible(),
				deletePermissionPossible: this.model.deletePermissionPossible(),
				sharePermission: OC.PERMISSION_SHARE,
				createPermission: OC.PERMISSION_CREATE,
				updatePermission: OC.PERMISSION_UPDATE,
				deletePermission: OC.PERMISSION_DELETE,
				mailerAppEnabled: OCA.Mailer ? true : false,
			};

			if(!this.model.hasUserShares()) {
				return [];
			}

			var shares = this.model.get('shares');
			var list = [];
			for(var index = 0; index < shares.length; index++) {
				// first empty {} is necessary, otherwise we get in trouble
				// with references
				list.push(_.extend({}, universal, this.getShareeObject(index)));
			}

			return list;
		},

		render: function() {
			this.$el.html(this.template({
				cid: this.cid,
				sharees: this.getShareeList()
			}));

			if(this.configModel.areAvatarsEnabled()) {
				this.$el.find('.avatar').each(function() {
					var $this = $(this);
					if ($this.hasClass('imageplaceholderseed')) {
						$this.css({width: 32, height: 32});
						$this.imageplaceholder($this.data('seed'));
					} else {
						$this.avatar($this.data('username'), 32);
					}
				});
			}

			this.$el.find('.has-tooltip').tooltip({
				placement: 'bottom'
			});

			this.delegateEvents();

			return this;
		},

		/**
		 * @returns {Function} from Handlebars
		 * @private
		 */
		template: function (data) {
			if (!this._template) {
				this._template = Handlebars.compile(TEMPLATE);
			}
			return this._template(data);
		},

		onUnshare: function(event) {
			var self = this;
			var $element = $(event.target);
			if (!$element.is('a')) {
				$element = $element.closest('a');
			}

			var $loading = $element.find('.icon-loading-small').eq(0);
			if(!$loading.hasClass('hidden')) {
				// in process
				return false;
			}
			$loading.removeClass('hidden');

			var $li = $element.closest('li');

			var shareId = $li.data('share-id');

			self.model.removeShare(shareId)
				.done(function() {
					$li.remove();
				})
				.fail(function() {
					$loading.addClass('hidden');
					OC.Notification.showTemporary(t('core', 'Could not unshare'));
				});
			return false;
		},

		onPermissionChange: function(event) {
			var $element = $(event.target);
			var $li = $element.closest('li');
			var shareId = $li.data('share-id');
			var shareType = $li.data('share-type');
			var shareWith = $li.attr('data-share-with');

			// adjust checkbox states
			var $checkboxes = $('.permissions', $li).not('input[name="edit"]').not('input[name="share"]');
			var checked;
			if ($element.attr('name') === 'edit') {
				checked = $element.is(':checked');
				// Check/uncheck Create, Update, and Delete checkboxes if Edit is checked/unck
				$($checkboxes).prop('checked', checked);
			} else {
				var numberChecked = $checkboxes.filter(':checked').length;
				checked = numberChecked > 0;
				$('input[name="edit"]', $li).prop('checked', checked);
			}

			var permissions = OC.PERMISSION_READ;
			$('.permissions', $li).not('input[name="edit"]').filter(':checked').each(function(index, checkbox) {
				permissions |= $(checkbox).data('permissions');
			});

			this.model.updateShare(shareId, {permissions: permissions});
		},

		onCrudsToggle: function(event) {
			var $target = $(event.target);
			$target.closest('li').find('.cruds').toggleClass('hidden');
			return false;
		},

		onSendMailNotification: function(event) {
			var $target = $(event.target);
			var $li = $(event.target).closest('li');
			var shareType = $li.data('share-type');
			var shareWith = $li.attr('data-share-with');

			this.model.sendNotificationForShare(shareType, shareWith, $target.is(':checked'));
		},

		onSendCboxMailNotification: function(event) {
			var $target = $(event.target);
			var $li = $(event.target).closest('li');
			var shareType = $li.data('share-type');
			var shareWith = $li.attr('data-share-with');
			var shareID = $li.attr('data-share-id');
			this.model.sendCboxNotificationForShare(shareID, shareType, shareWith);
		}
	});

	OC.Share.ShareDialogShareeListView = ShareDialogShareeListView;

})();
<commit_msg>Add mail notification only for users<commit_after>/*
 * Copyright (c) 2015
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */

(function() {
	if (!OC.Share) {
		OC.Share = {};
	}

	var TEMPLATE =
			'
' +
			'{{#each sharees}}' +
				'
' +
					'{{unshareLabel}}' +
					'{{#if avatarEnabled}}' +
					'

' +
					'{{/if}}' +
					'{{shareWithDisplayName}}' +
					'{{#if mailNotificationEnabled}}  {{#unless isRemoteShare}}' +
					'' +
						'<input id="mail-{{cid}}-{{shareWith}}" type="checkbox" name="mailNotification" class="mailNotification checkbox" {{#if wasMailSent}}checked="checked"{{/if}} />' +
						'{{notifyByMailLabel}}' +
					'' +
					'{{/unless}} {{/if}}' +
					/*
					'{{#if isResharingAllowed}} {{#if sharePermissionPossible}}' +
					'' +
						'<input id="canShare-{{cid}}-{{shareWith}}" type="checkbox" name="share" class="permissions checkbox" {{#if hasSharePermission}}checked="checked"{{/if}} data-permissions="{{sharePermission}}" />' +
						'{{canShareLabel}}' +
					'' +
					'{{/if}} {{/if}}' +
					*/
					'{{#if editPermissionPossible}}' +
					'{{/if}}' +
					'
' +
						'' +
							'<input type="checkbox" name="read" class="permissions checkbox" checked="checked" disabled />' +
							'read' +
						'' +
						'{{#if createPermissionPossible}}' +
						'' +
							'<input id="canCreate-{{cid}}-{{shareWith}}" type="checkbox" name="create" class="permissions checkbox" {{#if hasCreatePermission}}checked="checked"{{/if}} data-permissions="{{createPermission}}"/>' +
							'write + delete' +
						'' +
						'{{/if}}' +
						'{{#if mailerAppEnabled}}' +
						'{{#if isNotificationEnabled }}' +
						'' +
							'<button class="cbox-mail-notification">Send notification</button>' +
						'' +
						'{{/if}}' +
						'{{/if}}' +
						/*
						'{{#if createPermissionPossible}}' +
						'' +
							'<input id="canCreate-{{cid}}-{{shareWith}}" type="checkbox" name="create" class="permissions checkbox" {{#if hasCreatePermission}}checked="checked"{{/if}} data-permissions="{{createPermission}}"/>' +
							'{{createPermissionLabel}}' +
						'' +
						'{{/if}}' +
						'{{#if updatePermissionPossible}}' +
						'' +
							'<input id="canUpdate-{{cid}}-{{shareWith}}" type="checkbox" name="update" class="permissions checkbox" {{#if hasUpdatePermission}}checked="checked"{{/if}} data-permissions="{{updatePermission}}"/>' +
							'{{updatePermissionLabel}}' +
						'' +
						'{{/if}}' +
						'{{#if deletePermissionPossible}}' +
						'' +
							'<input id="canDelete-{{cid}}-{{shareWith}}" type="checkbox" name="delete" class="permissions checkbox" {{#if hasDeletePermission}}checked="checked"{{/if}} data-permissions="{{deletePermission}}"/>' +
							'{{deletePermissionLabel}}' +
						'' +
						'{{/if}}' +
						*/
					'
' +
				'
' +
			'{{/each}}' +
			'
'
		;

	/**
	 * @class OCA.Share.ShareDialogShareeListView
	 * @member {OC.Share.ShareItemModel} model
	 * @member {jQuery} $el
	 * @memberof OCA.Sharing
	 * @classdesc
	 *
	 * Represents the sharee list part in the GUI of the share dialogue
	 *
	 */
	var ShareDialogShareeListView = OC.Backbone.View.extend({
		/** @type {string} **/
		id: 'shareDialogLinkShare',

		/** @type {OC.Share.ShareConfigModel} **/
		configModel: undefined,

		/** @type {Function} **/
		_template: undefined,

		events: {
			'click .unshare': 'onUnshare',
			'click .permissions': 'onPermissionChange',
			'click .showCruds': 'onCrudsToggle',
			'click .mailNotification': 'onSendMailNotification',
			'click .cbox-mail-notification': 'onSendCboxMailNotification'
		},

		initialize: function(options) {
			if(!_.isUndefined(options.configModel)) {
				this.configModel = options.configModel;
			} else {
				throw 'missing OC.Share.ShareConfigModel';
			}

			var view = this;
			this.model.on('change:shares', function() {
				view.render();
			});
		},

		/**
		 *
		 * @param {OC.Share.Types.ShareInfo} shareInfo
		 * @returns {object}
		 */
		getShareeObject: function(shareIndex) {
			var shareWith = this.model.getShareWith(shareIndex);
			var shareWithDisplayName = this.model.getShareWithDisplayName(shareIndex);
			var shareType = this.model.getShareType(shareIndex);

			var hasPermissionOverride = {};
			if (shareType === OC.Share.SHARE_TYPE_GROUP) {
				shareWithDisplayName = shareWithDisplayName + " (" + t('core', 'group') + ')';
			} else if (shareType === OC.Share.SHARE_TYPE_REMOTE) {
				shareWithDisplayName = shareWithDisplayName + " (" + t('core', 'remote') + ')';
			}

			return _.extend(hasPermissionOverride, {
				cid: this.cid,
				hasSharePermission: this.model.hasSharePermission(shareIndex),
				hasEditPermission: this.model.hasEditPermission(shareIndex),
				hasCreatePermission: this.model.hasCreatePermission(shareIndex),
				hasUpdatePermission: this.model.hasUpdatePermission(shareIndex),
				hasDeletePermission: this.model.hasDeletePermission(shareIndex),
				wasMailSent: this.model.notificationMailWasSent(shareIndex),
				shareWith: shareWith,
				shareWithDisplayName: shareWithDisplayName,
				shareType: shareType,
				shareId: this.model.get('shares')[shareIndex].id,
				modSeed: shareType !== OC.Share.SHARE_TYPE_USER,
				isRemoteShare: shareType === OC.Share.SHARE_TYPE_REMOTE,
				isNotificationEnabled: shareType === OC.Share.SHARE_TYPE_USER,
			});
		},

		getShareeList: function() {
			var universal = {
				avatarEnabled: this.configModel.areAvatarsEnabled(),
				mailNotificationEnabled: this.configModel.isMailNotificationEnabled(),
				notifyByMailLabel: t('core', 'notify by email'),
				unshareLabel: t('core', 'Unshare'),
				canShareLabel: t('core', 'can share'),
				canEditLabel: t('core', 'can edit'),
				createPermissionLabel: t('core', 'create'),
				updatePermissionLabel: t('core', 'change'),
				deletePermissionLabel: t('core', 'delete'),
				crudsLabel: t('core', 'access control'),
				triangleSImage: OC.imagePath('core', 'actions/triangle-s'),
				isResharingAllowed: this.configModel.get('isResharingAllowed'),
				sharePermissionPossible: this.model.sharePermissionPossible(),
				editPermissionPossible: this.model.editPermissionPossible(),
				createPermissionPossible: this.model.createPermissionPossible(),
				updatePermissionPossible: this.model.updatePermissionPossible(),
				deletePermissionPossible: this.model.deletePermissionPossible(),
				sharePermission: OC.PERMISSION_SHARE,
				createPermission: OC.PERMISSION_CREATE,
				updatePermission: OC.PERMISSION_UPDATE,
				deletePermission: OC.PERMISSION_DELETE,
				mailerAppEnabled: OCA.Mailer ? true : false,
			};

			if(!this.model.hasUserShares()) {
				return [];
			}

			var shares = this.model.get('shares');
			var list = [];
			for(var index = 0; index < shares.length; index++) {
				// first empty {} is necessary, otherwise we get in trouble
				// with references
				list.push(_.extend({}, universal, this.getShareeObject(index)));
			}

			return list;
		},

		render: function() {
			this.$el.html(this.template({
				cid: this.cid,
				sharees: this.getShareeList()
			}));

			if(this.configModel.areAvatarsEnabled()) {
				this.$el.find('.avatar').each(function() {
					var $this = $(this);
					if ($this.hasClass('imageplaceholderseed')) {
						$this.css({width: 32, height: 32});
						$this.imageplaceholder($this.data('seed'));
					} else {
						$this.avatar($this.data('username'), 32);
					}
				});
			}

			this.$el.find('.has-tooltip').tooltip({
				placement: 'bottom'
			});

			this.delegateEvents();

			return this;
		},

		/**
		 * @returns {Function} from Handlebars
		 * @private
		 */
		template: function (data) {
			if (!this._template) {
				this._template = Handlebars.compile(TEMPLATE);
			}
			return this._template(data);
		},

		onUnshare: function(event) {
			var self = this;
			var $element = $(event.target);
			if (!$element.is('a')) {
				$element = $element.closest('a');
			}

			var $loading = $element.find('.icon-loading-small').eq(0);
			if(!$loading.hasClass('hidden')) {
				// in process
				return false;
			}
			$loading.removeClass('hidden');

			var $li = $element.closest('li');

			var shareId = $li.data('share-id');

			self.model.removeShare(shareId)
				.done(function() {
					$li.remove();
				})
				.fail(function() {
					$loading.addClass('hidden');
					OC.Notification.showTemporary(t('core', 'Could not unshare'));
				});
			return false;
		},

		onPermissionChange: function(event) {
			var $element = $(event.target);
			var $li = $element.closest('li');
			var shareId = $li.data('share-id');
			var shareType = $li.data('share-type');
			var shareWith = $li.attr('data-share-with');

			// adjust checkbox states
			var $checkboxes = $('.permissions', $li).not('input[name="edit"]').not('input[name="share"]');
			var checked;
			if ($element.attr('name') === 'edit') {
				checked = $element.is(':checked');
				// Check/uncheck Create, Update, and Delete checkboxes if Edit is checked/unck
				$($checkboxes).prop('checked', checked);
			} else {
				var numberChecked = $checkboxes.filter(':checked').length;
				checked = numberChecked > 0;
				$('input[name="edit"]', $li).prop('checked', checked);
			}

			var permissions = OC.PERMISSION_READ;
			$('.permissions', $li).not('input[name="edit"]').filter(':checked').each(function(index, checkbox) {
				permissions |= $(checkbox).data('permissions');
			});

			this.model.updateShare(shareId, {permissions: permissions});
		},

		onCrudsToggle: function(event) {
			var $target = $(event.target);
			$target.closest('li').find('.cruds').toggleClass('hidden');
			return false;
		},

		onSendMailNotification: function(event) {
			var $target = $(event.target);
			var $li = $(event.target).closest('li');
			var shareType = $li.data('share-type');
			var shareWith = $li.attr('data-share-with');

			this.model.sendNotificationForShare(shareType, shareWith, $target.is(':checked'));
		},

		onSendCboxMailNotification: function(event) {
			var $target = $(event.target);
			var $li = $(event.target).closest('li');
			var shareType = $li.data('share-type');
			var shareWith = $li.attr('data-share-with');
			var shareID = $li.attr('data-share-id');
			this.model.sendCboxNotificationForShare(shareID, shareType, shareWith);
		}
	});

	OC.Share.ShareDialogShareeListView = ShareDialogShareeListView;

})();
<|endoftext|>


<commit_before>'use strict'
var DropdownPanel = require('./DropdownPanel')
var yo = require('yo-yo')

function StoragePanel (_parent, _traceManager, _address) {
  this.parent = _parent
  this.traceManager = _traceManager
  this.basicPanel = new DropdownPanel('Storage Changes', {json: true})
  this.address = _address
  this.init()
  this.disabled = false
}

StoragePanel.prototype.render = function () {
  return yo`<div id='storagepanel' >${this.basicPanel.render()}</div>`
}

StoragePanel.prototype.init = function () {
  var self = this
  this.parent.event.register('indexChanged', this, function (index) {
    if (self.disabled) return
    if (index < 0) return
    if (self.parent.currentStepIndex !== index) return

    self.traceManager.getStorageAt(index, self.parent.tx, function (error, storage) {
      if (error) {
        console.log(error)
        self.basicPanel.update({})
      } else if (self.parent.currentStepIndex === index) {
        self.basicPanel.update(storage)
      }
    }, self.address)
  })
}

module.exports = StoragePanel
<commit_msg>use storageResolver in StoragePanel<commit_after>'use strict'
var DropdownPanel = require('./DropdownPanel')
var yo = require('yo-yo')

function StoragePanel (_parent, _traceManager, _storageResolver) {
  this.parent = _parent
  this.storageResolver = _storageResolver
  this.traceManager = _traceManager
  this.basicPanel = new DropdownPanel('Storage', {json: true})
  this.init()
  this.disabled = false
}

StoragePanel.prototype.render = function () {
  return yo`<div id='storagepanel' >${this.basicPanel.render()}</div>`
}

StoragePanel.prototype.init = function () {
  var self = this
  this.parent.event.register('indexChanged', this, function (index) {
    if (self.disabled) return
    if (index < 0) return
    if (self.parent.currentStepIndex !== index) return

    self.storageResolver.storageRange((error, storage) => {
      if (error) {
        console.log(error)
        self.basicPanel.update({})
      } else if (self.parent.currentStepIndex === index) {
        self.basicPanel.update(storage)
      }
    })
  })
}

module.exports = StoragePanel
<|endoftext|>


<commit_before>/**
 * @param A point a, example: {x : 0,y : 0}
 * @param A point b, example: {x : 0,y : 0}
 * @return A vector ab, example: {x : 0,y : 0}
 */
const newVector = (a, b) => {
  return {x: b.x-a.x, y: b.y-a.y};
};

/**
 * Performs the cross product between two vectors.
 * @param A vector object, example: {x : 0,y : 0}
 * @param A vector object, example: {x : 0,y : 0}
 * @return The result of the cross product between u and v.
 */
const crossProduct = (u, v) => {
  return u.x*v.y - u.y*v.x;
};

/**
 * Calculates the area of the parallelogram that can be
 * generated by the vectors ab and ac.
 *
 * @param A point a, example: {x : 0,y : 0}
 * @param A point b, example: {x : 0,y : 0}
 * @param A point c, example: {x : 0,y : 0}
 * @return A vector ab, example: {x : 0,y : 0}
 * Note: Given that the area of the parallelogram is equal
 * to the length of the vector w = (ab)x(ac) times -1, if the
 * z coordinate of w is negative. With the right-hand rule
 * we can deduce that if the area is negative, then
 * the vector ab followed by the vector ac do not performs a
 * left-turn.
 */
const parallelogramArea = (a, b, c) => {
  return crossProduct(newVector(a, b), newVector(a, c));
};

/**
 * @param A point object, example: {x : 0,y : 0}
 * @param A point object, example: {x : 0,y : 0}
 * @param A point object, example: {x : 0,y : 0}
 * @return Returns true if the point c is clockwise with respect
 * to the straight-line which contains the vector ab, otherwise returns false.
 * Note: This rule is given by the Right-hand rule.
 */
const isClockwise = (a, b, c) => {
  return parallelogramArea(a, b, c) < 0;
};

/**
 * @param A point object, example: {x : 0,y : 0}
 * @param A point object, example: {x : 0,y : 0}
 * @param A point object, example: {x : 0,y : 0}
 * @return Returns true if the point c is counter-clockwise with respect
 * to the straight-line which contains the vector ab, otherwise returns false.
 * Note: This rule is given by the Right-hand rule.
 */
const isCounterClockwise = (a, b, c) => {
  return parallelogramArea(a, b, c) > 0;
};

module.exports = {
  newVector: newVector,
  crossProduct: crossProduct,
  parallelogramArea: parallelogramArea,
  isClockwise: isClockwise,
  isCounterClockwise: isCounterClockwise
};
<commit_msg>Add length function<commit_after>/**
 * @param A point a, example: {x : 0,y : 0}
 * @param A point b, example: {x : 0,y : 0}
 * @return A vector ab, example: {x : 0,y : 0}
 */
const newVector = (a, b) => {
  return {x: b.x-a.x, y: b.y-a.y};
};

/**
 * @param A vector v, example: {x : 0,y : 0}
 * @return The length of v.
 */
const length = v => {
  return v.x*v.x + v.y*v.y;
};

/**
 * Performs the cross product between two vectors.
 * @param A vector object, example: {x : 0,y : 0}
 * @param A vector object, example: {x : 0,y : 0}
 * @return The result of the cross product between u and v.
 */
const crossProduct = (u, v) => {
  return u.x*v.y - u.y*v.x;
};

/**
 * Calculates the area of the parallelogram that can be
 * generated by the vectors ab and ac.
 *
 * @param A point a, example: {x : 0,y : 0}
 * @param A point b, example: {x : 0,y : 0}
 * @param A point c, example: {x : 0,y : 0}
 * @return A vector ab, example: {x : 0,y : 0}
 * Note: Given that the area of the parallelogram is equal
 * to the length of the vector w = (ab)x(ac) times -1, if the
 * z coordinate of w is negative. With the right-hand rule
 * we can deduce that if the area is negative, then
 * the vector ab followed by the vector ac do not performs a
 * left-turn.
 */
const parallelogramArea = (a, b, c) => {
  return crossProduct(newVector(a, b), newVector(a, c));
};

/**
 * @param A point object, example: {x : 0,y : 0}
 * @param A point object, example: {x : 0,y : 0}
 * @param A point object, example: {x : 0,y : 0}
 * @return Returns true if the point c is clockwise with respect
 * to the straight-line which contains the vector ab, otherwise returns false.
 * Note: This rule is given by the Right-hand rule.
 */
const isClockwise = (a, b, c) => {
  return parallelogramArea(a, b, c) < 0;
};

/**
 * @param A point object, example: {x : 0,y : 0}
 * @param A point object, example: {x : 0,y : 0}
 * @param A point object, example: {x : 0,y : 0}
 * @return Returns true if the point c is counter-clockwise with respect
 * to the straight-line which contains the vector ab, otherwise returns false.
 * Note: This rule is given by the Right-hand rule.
 */
const isCounterClockwise = (a, b, c) => {
  return parallelogramArea(a, b, c) > 0;
};

module.exports = {
  newVector: newVector,
  length: length,
  crossProduct: crossProduct,
  parallelogramArea: parallelogramArea,
  isClockwise: isClockwise,
  isCounterClockwise: isCounterClockwise
};
<|endoftext|>


<commit_before>import isRootNode from './is-root-node';
import isSlotNode from './is-slot-node';

export default function(root) {
  // IE requies the last argument, so we must provide both the 3rd and last.
  const walker = document.createTreeWalker(root, Node.SHOW_ELEMENT, null, false);
  const slots = [];

  let inDescendantRoot = false;

  while (walker.nextNode()) {
    const { currentNode } = walker;
    const isCurrentSlot = isSlotNode(currentNode);

    if (inDescendantRoot && isCurrentSlot) {
      inDescendantRoot = false;
      continue;
    }

    if (isRootNode(currentNode)) {
      inDescendantRoot = true;
      continue;
    }

    if (!inDescendantRoot && isCurrentSlot) {
      slots.push(currentNode);
    }
  }

  return slots;
}
<commit_msg>fix(ie): Fix createTreeWalker() quirsk in IE.<commit_after>import isRootNode from './is-root-node';
import isSlotNode from './is-slot-node';

export default function(root) {
  const slots = [];

  // IE complains if you call nextNode() on a tree walker that isn't an element.
  if (root.nodeType !== Node.ELEMENT_NODE) {
    return [];
  }

  // IE requies the last argument, so we must provide both the 3rd and last.
  const walker = document.createTreeWalker(root, Node.SHOW_ELEMENT, null, false);
  let inDescendantRoot = false;

  while (walker.nextNode()) {
    const { currentNode } = walker;
    const isCurrentSlot = isSlotNode(currentNode);

    if (inDescendantRoot && isCurrentSlot) {
      inDescendantRoot = false;
      continue;
    }

    if (isRootNode(currentNode)) {
      inDescendantRoot = true;
      continue;
    }

    if (!inDescendantRoot && isCurrentSlot) {
      slots.push(currentNode);
    }
  }

  return slots;
}
<|endoftext|>